@ponythewhite/base-context 1.0.8 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/base-context-runtime/pyproject.toml +1 -1
  3. package/dist/base-context-runtime/uv.lock +1 -1
  4. package/dist/build-info.json +1 -1
  5. package/dist/bundle/{bundled-modules-IGMJH2MU.js → bundled-modules-MX6YNAM2.js} +2 -2
  6. package/dist/bundle/{chunk-EXEFSSF4.js → chunk-CDXQNS5P.js} +176 -37
  7. package/dist/bundle/{chunk-RVJVXZCS.js → chunk-UHLGPYMI.js} +20 -40
  8. package/dist/bundle/{cli-main-BUK7QTHO.js → cli-main-D7W3WWCV.js} +2 -2
  9. package/dist/bundle/cli.js +1 -1
  10. package/dist/bundle/{main-2FWHT2WZ.js → main-5J3QBZ5Y.js} +2 -2
  11. package/dist/core/agent-session.d.ts +3 -0
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +48 -5
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/canonical-context.d.ts.map +1 -1
  16. package/dist/core/canonical-context.js +115 -30
  17. package/dist/core/canonical-context.js.map +1 -1
  18. package/dist/core/context-epoch.d.ts +14 -3
  19. package/dist/core/context-epoch.d.ts.map +1 -1
  20. package/dist/core/context-epoch.js +5 -1
  21. package/dist/core/context-epoch.js.map +1 -1
  22. package/dist/core/inference-coordinator.d.ts +1 -1
  23. package/dist/core/inference-coordinator.d.ts.map +1 -1
  24. package/dist/core/inference-coordinator.js +2 -2
  25. package/dist/core/inference-coordinator.js.map +1 -1
  26. package/dist/core/public-context.d.ts.map +1 -1
  27. package/dist/core/public-context.js +20 -8
  28. package/dist/core/public-context.js.map +1 -1
  29. package/dist/core/request-view-selection.d.ts +4 -2
  30. package/dist/core/request-view-selection.d.ts.map +1 -1
  31. package/dist/core/request-view-selection.js +7 -4
  32. package/dist/core/request-view-selection.js.map +1 -1
  33. package/dist/core/session-manager.d.ts +2 -0
  34. package/dist/core/session-manager.d.ts.map +1 -1
  35. package/dist/core/session-manager.js +38 -13
  36. package/dist/core/session-manager.js.map +1 -1
  37. package/dist/modes/daemon/daemon-mode.d.ts.map +1 -1
  38. package/dist/modes/daemon/daemon-mode.js +15 -30
  39. package/dist/modes/daemon/daemon-mode.js.map +1 -1
  40. package/dist/modes/daemon/daemon-socket.d.ts +5 -0
  41. package/dist/modes/daemon/daemon-socket.d.ts.map +1 -1
  42. package/dist/modes/daemon/daemon-socket.js +19 -0
  43. package/dist/modes/daemon/daemon-socket.js.map +1 -1
  44. package/dist/modes/daemon/daemon-supervisor.d.ts.map +1 -1
  45. package/dist/modes/daemon/daemon-supervisor.js +6 -7
  46. package/dist/modes/daemon/daemon-supervisor.js.map +1 -1
  47. package/dist/modes/daemon/daemon-worker-client.d.ts.map +1 -1
  48. package/dist/modes/daemon/daemon-worker-client.js +5 -5
  49. package/dist/modes/daemon/daemon-worker-client.js.map +1 -1
  50. package/package.json +4 -4
@@ -13,15 +13,26 @@ export declare const CONTEXT_TOOL_EPOCH_RENDERER = "native-canonical-epoch/6";
13
13
  export declare const CONTEXT_SKILL_EPOCH_RENDERER = "native-canonical-epoch/7";
14
14
  /** Source-backed summary with retained public tool groups, not a measured MAIN request. */
15
15
  export declare const CONTEXT_TOOL_SUMMARY_RENDERER = "native-canonical-epoch/8";
16
+ /** Public recipes may record absent admission, never a fabricated execution outcome. */
17
+ export declare const CONTEXT_INTERRUPTED_TOOL_RENDERER = "native-canonical-epoch/9";
16
18
  /** Descriptive, source-backed outcomes in the existing accepted epoch, not an execution store. */
17
19
  export interface ToolContinuationGroup {
18
20
  readonly assistantEntryId: string;
19
- readonly calls: readonly {
21
+ readonly calls: readonly ({
22
+ readonly admission?: never;
20
23
  readonly executionId: string;
21
24
  readonly intent: Pick<IndexedSourceEvent, "id" | "sequence" | "revision">;
22
25
  readonly outcome: "outcome_unknown" | "not_started" | "completed" | "failed";
23
26
  readonly result?: Pick<IndexedSourceEvent, "id" | "sequence" | "revision">;
24
- }[];
27
+ } | {
28
+ readonly admission: "absent";
29
+ /** Absence is scoped to this exact captured branch prefix, not external effects. */
30
+ readonly source: SourceSnapshotRef;
31
+ readonly executionId?: never;
32
+ readonly intent?: never;
33
+ readonly outcome?: never;
34
+ readonly result?: never;
35
+ })[];
25
36
  }
26
37
  export type ContextMode = "on" | "off";
27
38
  /** Compatibility retained from an accepted native request, not measurement or replay credit. */
@@ -51,7 +62,7 @@ export interface EpochViewReference {
51
62
  readonly rendering?: "public-history/1" | "public-tool-continuation/1";
52
63
  }
53
64
  interface ContextEpochFields {
54
- readonly renderer: "native-canonical-epoch/1" | "native-canonical-epoch/2" | "native-canonical-epoch/3" | typeof CONTEXT_EPOCH_RENDERER | typeof CONTEXT_POLICY_EPOCH_RENDERER | typeof CONTEXT_TOOL_EPOCH_RENDERER | typeof CONTEXT_SKILL_EPOCH_RENDERER | typeof CONTEXT_TOOL_SUMMARY_RENDERER;
65
+ readonly renderer: "native-canonical-epoch/1" | "native-canonical-epoch/2" | "native-canonical-epoch/3" | typeof CONTEXT_EPOCH_RENDERER | typeof CONTEXT_POLICY_EPOCH_RENDERER | typeof CONTEXT_TOOL_EPOCH_RENDERER | typeof CONTEXT_SKILL_EPOCH_RENDERER | typeof CONTEXT_TOOL_SUMMARY_RENDERER | typeof CONTEXT_INTERRUPTED_TOOL_RENDERER;
55
66
  readonly source: SourceSnapshotRef;
56
67
  readonly includeSummary?: true;
57
68
  /** Granted by an actual accepted adapter projection, never a caller profile name. */
@@ -1 +1 @@
1
- {"version":3,"file":"context-epoch.d.ts","sourceRoot":"","sources":["../../src/core/context-epoch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,sBAAsB,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AAGlH,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC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9C,QAAQ,EAAE,MAAM,EAChB,gBAAgB,UAAQ,EACxB,oBAAoB,CAAC,EAAE,MAAM,GAC3B,MAAM,CAiFR","sourcesContent":["import type { ProviderRequestRepresentation, RequestTokenAssessment, Usage } from \"@ponythewhite/base-context-ai\";\nimport { requestTokenRouteIdentity } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { ContextRef, IndexedSourceEvent } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport { MAX_RESOURCE_REVISION_BYTES } from \"./resource-view.js\";\nimport type { SelectedSkillReference } from \"./selected-skills.js\";\nimport type { CompiledTaskFrame } from \"./task-frame.js\";\n\nexport const CONTEXT_EPOCH_DETAIL = \"baseContextEpoch\";\n/** Internal admission, not a field accepted by ordinary appendCompaction callers. */\nexport const appendContextEpoch = Symbol(\"appendContextEpoch\");\nexport const CONTEXT_EPOCH_RENDERER = \"native-canonical-epoch/4\";\nexport const CONTEXT_POLICY_EPOCH_RENDERER = \"native-canonical-epoch/5\";\nexport const CONTEXT_TOOL_EPOCH_RENDERER = \"native-canonical-epoch/6\";\n/** Selection-bearing v4/v5/v6 variants; older readers must refuse rather than drop these refs. */\nexport const CONTEXT_SKILL_EPOCH_RENDERER = \"native-canonical-epoch/7\";\n/** Source-backed summary with retained public tool groups, not a measured MAIN request. */\nexport const CONTEXT_TOOL_SUMMARY_RENDERER = \"native-canonical-epoch/8\";\n\n/** Descriptive, source-backed outcomes in the existing accepted epoch, not an execution store. */\nexport interface ToolContinuationGroup {\n\treadonly assistantEntryId: string;\n\treadonly calls: readonly {\n\t\treadonly executionId: string;\n\t\treadonly intent: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\treadonly outcome: \"outcome_unknown\" | \"not_started\" | \"completed\" | \"failed\";\n\t\treadonly result?: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t}[];\n}\nexport type ContextMode = \"on\" | \"off\";\n\n/** Compatibility retained from an accepted native request, not measurement or replay credit. */\nexport interface ContextEpochRequestContract {\n\treadonly api: string;\n\treadonly provider: string;\n\treadonly route: string;\n\treadonly model: string;\n\treadonly replayContract: ContextReplayContract;\n}\nexport type ContextReplayContract = \"complete-context\" | \"message-groups\";\n\n/** An ordinary summary and its retained source recipes share the existing compaction ACK. */\nexport interface ContextEpochSummary {\n\treadonly summary: string;\n\treadonly details?: Record<string, unknown>;\n\treadonly fromHook?: boolean;\n\treadonly customInstructions?: string;\n\treadonly usage?: Usage;\n}\n\n/** A frozen read recipe, not a second copy of an archived message body. */\nexport interface EpochViewReference {\n\treadonly source: SourceSnapshotRef;\n\treadonly ref: ContextRef;\n\treadonly sourceRevision: string;\n\t/** Present only for an existing rendered compaction summary. */\n\treadonly retainedMessageCount?: number;\n\treadonly rendering?: \"public-history/1\" | \"public-tool-continuation/1\";\n}\n\ninterface ContextEpochFields {\n\treadonly renderer:\n\t\t| \"native-canonical-epoch/1\"\n\t\t| \"native-canonical-epoch/2\"\n\t\t| \"native-canonical-epoch/3\"\n\t\t| typeof CONTEXT_EPOCH_RENDERER\n\t\t| typeof CONTEXT_POLICY_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_SKILL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_SUMMARY_RENDERER;\n\treadonly source: SourceSnapshotRef;\n\treadonly includeSummary?: true;\n\t/** Granted by an actual accepted adapter projection, never a caller profile name. */\n\treadonly replayContract?: ContextReplayContract;\n\t/** Actual adapter permission to leave completed native groups for a fresh public window. */\n\treadonly publicWindow?: true;\n\t/** Frozen public transition. Later native messages are not silently converted. */\n\treadonly continuation?: {\n\t\treadonly kind: \"harness-summary\" | \"portable-checkpoint\";\n\t\treadonly publicTailThrough: SourceSnapshotRef;\n\t};\n\treadonly views: readonly EpochViewReference[];\n\t/** Captured versions, not a body cache or authority inferred from transcript markup. */\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\t/** v6 requests and v8 summaries retain whole public groups and their exact outcome refs. */\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n\t/** Derived display only. The task reducer remains the authority for later changes. */\n\treadonly taskFrame?: CompiledTaskFrame;\n\t/** Accepted-state comparison only; saved metadata never establishes current resource liveness. */\n\treadonly resourceRevision?: string;\n\treadonly literalTailId: string;\n}\n\n/** v5 policy-only null is a mode ACK, not an ordinary summary or a measured request. */\nexport type ContextEpochCheckpoint = ContextEpochFields &\n\t(\n\t\t| {\n\t\t\t\treadonly version: 1 | 2 | 3 | 4 | 6;\n\t\t\t\treadonly representation: string | null;\n\t\t\t\treadonly mode?: never;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 8;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly includeSummary: true;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 5;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly policyOnly: true;\n\t\t\t\treadonly includeSummary?: never;\n\t\t\t\treadonly requestContract?: ContextEpochRequestContract;\n\t\t\t\treadonly pendingRequestContract?: true;\n\t\t }\n\t);\n\nexport function contextEpochMode(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n\tinitial: ContextMode = \"on\",\n): ContextMode {\n\treturn checkpoint ? (checkpoint.version === 5 || checkpoint.version === 8 ? checkpoint.mode : \"on\") : initial;\n}\n\nfunction isRequestContract(value: unknown): value is ContextEpochRequestContract {\n\tif (!value || typeof value !== \"object\") return false;\n\treturn (\n\t\t[\"api\", \"provider\", \"route\", \"model\"].every(\n\t\t\t(key) =>\n\t\t\t\tkey in value &&\n\t\t\t\ttypeof (value as Record<string, unknown>)[key] === \"string\" &&\n\t\t\t\t(value as Record<string, unknown>)[key] !== \"\",\n\t\t) &&\n\t\t\"replayContract\" in value &&\n\t\t(value.replayContract === \"complete-context\" || value.replayContract === \"message-groups\")\n\t);\n}\n\n/** Only call with a qualified checkpoint, never raw compaction marker data. */\nexport function retainedContextRequestContract(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n): ContextEpochRequestContract | undefined {\n\tif (!checkpoint) return;\n\tif (checkpoint.requestContract) return structuredClone(checkpoint.requestContract);\n\tif (!checkpoint.representation) return;\n\tconst accepted: unknown = JSON.parse(checkpoint.representation);\n\tif (!accepted || typeof accepted !== \"object\") throw new Error(\"Accepted context request contract is unavailable\");\n\tconst value = { ...accepted, replayContract: checkpoint.replayContract ?? \"complete-context\" };\n\tif (!isRequestContract(value)) throw new Error(\"Accepted context request contract is unavailable\");\n\treturn {\n\t\tapi: value.api,\n\t\tprovider: value.provider,\n\t\troute: value.route,\n\t\tmodel: value.model,\n\t\treplayContract: value.replayContract,\n\t};\n}\n\n/** Identity comes from the actual final native serialization, not a model/profile label. */\nexport function contextRequestContract(\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): ContextEpochRequestContract {\n\tconst route = requestTokenRouteIdentity(request.url);\n\tconst body: unknown = request.body === undefined ? undefined : JSON.parse(request.body);\n\tif (\n\t\t!route ||\n\t\t!body ||\n\t\ttypeof body !== \"object\" ||\n\t\t!(\"model\" in body) ||\n\t\ttypeof body.model !== \"string\" ||\n\t\t!body.model\n\t)\n\t\tthrow new Error(\"Native context request identity is unavailable\");\n\treturn { api: request.api, provider: request.provider, route, model: body.model, replayContract };\n}\n\nexport function assertContextRequestContract(\n\tcontract: ContextEpochRequestContract,\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): void {\n\tconst actual = contextRequestContract(request, replayContract);\n\tif (\n\t\tactual.api !== contract.api ||\n\t\tactual.provider !== contract.provider ||\n\t\tactual.route !== contract.route ||\n\t\tactual.model !== contract.model ||\n\t\tactual.replayContract !== contract.replayContract\n\t)\n\t\tthrow new Error(\"Retained context requires its accepted native request contract\");\n}\n\nexport function snapshotContextEpoch<T extends ContextEpochCheckpoint>(value: T, maxBytes: number): T {\n\treturn JSON.parse(stringifyBoundedJson(value, maxBytes)) as T;\n}\n\n/** Called only after checking the source frame's genuine epoch qualification. */\nexport function readContextEpoch(details: unknown, maxBytes: number): ContextEpochCheckpoint | undefined {\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return;\n\tconst value: unknown = details[CONTEXT_EPOCH_DETAIL];\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"version\" in value) ||\n\t\t!(\"renderer\" in value) ||\n\t\t!(\n\t\t\t(value.version === 1 && value.renderer === \"native-canonical-epoch/1\") ||\n\t\t\t(value.version === 2 && value.renderer === \"native-canonical-epoch/2\") ||\n\t\t\t(value.version === 3 && value.renderer === \"native-canonical-epoch/3\") ||\n\t\t\t(value.version === 4 && value.renderer === \"native-canonical-epoch/4\") ||\n\t\t\t(value.version === 5 && value.renderer === CONTEXT_POLICY_EPOCH_RENDERER) ||\n\t\t\t(value.version === 6 && value.renderer === CONTEXT_TOOL_EPOCH_RENDERER) ||\n\t\t\t(value.version === 8 && value.renderer === CONTEXT_TOOL_SUMMARY_RENDERER) ||\n\t\t\t([4, 5, 6].includes(value.version as number) && value.renderer === CONTEXT_SKILL_EPOCH_RENDERER)\n\t\t) ||\n\t\t(value.renderer === CONTEXT_SKILL_EPOCH_RENDERER || (value.version === 8 && \"selectedSkills\" in value)\n\t\t\t? !(\"selectedSkills\" in value) ||\n\t\t\t\t!Array.isArray(value.selectedSkills) ||\n\t\t\t\tvalue.selectedSkills.length === 0 ||\n\t\t\t\tvalue.selectedSkills.some(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\t!item ||\n\t\t\t\t\t\ttypeof item.name !== \"string\" ||\n\t\t\t\t\t\t!item.view ||\n\t\t\t\t\t\t![\"custom_message\", \"custom\"].includes(item.view.ref?.kind) ||\n\t\t\t\t\t\ttypeof item.view.sourceRevision !== \"string\",\n\t\t\t\t) ||\n\t\t\t\tnew Set(value.selectedSkills.map((item) => item.name)).size !== value.selectedSkills.length\n\t\t\t: \"selectedSkills\" in value) ||\n\t\t!(\"source\" in value) ||\n\t\t!value.source ||\n\t\t!(\"views\" in value) ||\n\t\t!Array.isArray(value.views) ||\n\t\t!(\"literalTailId\" in value) ||\n\t\ttypeof value.literalTailId !== \"string\" ||\n\t\t!(\"representation\" in value) ||\n\t\t(value.version === 5 || value.version === 8\n\t\t\t? !(\"mode\" in value) || (value.mode !== \"on\" && value.mode !== \"off\")\n\t\t\t: \"mode\" in value) ||\n\t\t(value.version === 8 &&\n\t\t\t(value.representation !== null || !(\"includeSummary\" in value) || value.includeSummary !== true)) ||\n\t\t(value.version === 5 &&\n\t\t\t(value.representation !== null || !(\"policyOnly\" in value) || value.policyOnly !== true)) ||\n\t\t(\"policyOnly\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\tvalue.policyOnly !== true ||\n\t\t\t\tvalue.representation !== null ||\n\t\t\t\t\"includeSummary\" in value)) ||\n\t\t(\"pendingRequestContract\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\t!(\"mode\" in value) ||\n\t\t\t\tvalue.mode !== \"off\" ||\n\t\t\t\tvalue.pendingRequestContract !== true ||\n\t\t\t\t\"requestContract\" in value)) ||\n\t\t(\"requestContract\" in value && (value.version !== 5 || !isRequestContract(value.requestContract))) ||\n\t\t!(\n\t\t\ttypeof value.representation === \"string\" ||\n\t\t\t(value.version === 5 && value.representation === null && \"policyOnly\" in value && value.policyOnly === true) ||\n\t\t\t((value.version === 2 || value.version === 3 || value.version === 4 || value.version === 8) &&\n\t\t\t\tvalue.representation === null &&\n\t\t\t\t\"includeSummary\" in value &&\n\t\t\t\tvalue.includeSummary === true)\n\t\t) ||\n\t\t(\"includeSummary\" in value &&\n\t\t\t((value.version !== 2 && value.version !== 3 && value.version !== 4 && value.version !== 8) ||\n\t\t\t\tvalue.includeSummary !== true ||\n\t\t\t\tvalue.representation !== null)) ||\n\t\t(\"replayContract\" in value &&\n\t\t\tvalue.replayContract !== \"complete-context\" &&\n\t\t\tvalue.replayContract !== \"message-groups\") ||\n\t\t(\"resourceRevision\" in value &&\n\t\t\t(typeof value.resourceRevision !== \"string\" ||\n\t\t\t\tBuffer.byteLength(value.resourceRevision, \"utf8\") > MAX_RESOURCE_REVISION_BYTES)) ||\n\t\t(\"publicWindow\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\tvalue.publicWindow !== true)) ||\n\t\t(\"toolContinuations\" in value && value.version !== 6 && value.version !== 8) ||\n\t\t((value.version === 6 || value.version === 8) &&\n\t\t\t(!(\"toolContinuations\" in value) ||\n\t\t\t\t!Array.isArray(value.toolContinuations) ||\n\t\t\t\t!value.toolContinuations.length ||\n\t\t\t\t!(\"replayContract\" in value) ||\n\t\t\t\t(value.version === 6 &&\n\t\t\t\t\t(!(\"publicWindow\" in value) ||\n\t\t\t\t\t\tvalue.publicWindow !== true ||\n\t\t\t\t\t\tvalue.replayContract !== \"message-groups\")))) ||\n\t\t(\"continuation\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\t!value.continuation ||\n\t\t\t\ttypeof value.continuation !== \"object\" ||\n\t\t\t\t!(\"kind\" in value.continuation) ||\n\t\t\t\t(value.continuation.kind !== \"harness-summary\" &&\n\t\t\t\t\t((value.version !== 4 && value.version !== 5 && value.version !== 6) ||\n\t\t\t\t\t\tvalue.continuation.kind !== \"portable-checkpoint\")) ||\n\t\t\t\t!(\"publicTailThrough\" in value.continuation) ||\n\t\t\t\t!value.continuation.publicTailThrough))\n\t)\n\t\tthrow new Error(\"Invalid committed context epoch\");\n\treturn snapshotContextEpoch(value as ContextEpochCheckpoint, maxBytes);\n}\n\n/** Stable representation, not the changing input, an auth envelope, or a cache-hit claim. */\nexport function contextEpochRepresentation(\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n\tmaxBytes: number,\n\tunbudgetedPublic = false,\n\tresponseItemIdentity?: string,\n): string {\n\tif (\n\t\t(!assessment && !unbudgetedPublic) ||\n\t\t(assessment &&\n\t\t\t(!assessment.profile ||\n\t\t\t\tassessment.limitSource !== \"explicit-profile\" ||\n\t\t\t\t!assessment.route ||\n\t\t\t\t!assessment.model)) ||\n\t\trequest.body === undefined\n\t)\n\t\tthrow new Error(\"Committed context epoch requires its explicit request profile\");\n\tconst identity = assessment ?? contextRequestContract(request, \"message-groups\");\n\tconst body: unknown = JSON.parse(request.body);\n\tif (!body || typeof body !== \"object\" || Array.isArray(body))\n\t\tthrow new Error(\"Context epoch request representation is unavailable\");\n\tconst configuration: Record<string, unknown> = {};\n\tconst fields = new Set([\n\t\t\"model\",\n\t\t\"instructions\",\n\t\t\"stream\",\n\t\t\"max_output_tokens\",\n\t\t\"max_tokens\",\n\t\t\"max_completion_tokens\",\n\t\t\"temperature\",\n\t\t\"top_p\",\n\t\t\"text\",\n\t\t\"tools\",\n\t\t\"tool_choice\",\n\t\t\"parallel_tool_calls\",\n\t\t\"store\",\n\t\t\"reasoning\",\n\t\t\"service_tier\",\n\t\t\"truncation\",\n\t\t\"include\",\n\t\t\"prompt_cache_retention\",\n\t\t\"stream_options\",\n\t]);\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\tidentity.route === request.url &&\n\t\t\"model\" in body &&\n\t\tbody.model === \"deepseek-flash\" &&\n\t\tidentity.model === body.model\n\t) {\n\t\tfields.add(\"thinking\");\n\t\tfields.add(\"reasoning_effort\");\n\t}\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif ([\"input\", \"messages\", \"previous_response_id\", \"prompt_cache_key\"].includes(key)) continue;\n\t\t// Unknown payload extensions may contain private data or change the representation.\n\t\tif (!fields.has(key)) throw new Error(\"Unsupported context epoch request configuration\");\n\t\tconfiguration[key] = value;\n\t}\n\tconst input: unknown = \"input\" in body ? body.input : \"messages\" in body ? body.messages : undefined;\n\tif (!Array.isArray(input)) throw new Error(\"Context epoch request messages are unavailable\");\n\tconst policy = input.filter(\n\t\t(item: unknown) =>\n\t\t\titem && typeof item === \"object\" && \"role\" in item && (item.role === \"system\" || item.role === \"developer\"),\n\t);\n\treturn stringifyBoundedJson(\n\t\t{\n\t\t\trenderer: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(responseItemIdentity ? { responseItemIdentity } : {}),\n\t\t\tapi: request.api,\n\t\t\tprovider: request.provider,\n\t\t\troute: identity.route,\n\t\t\tmodel: identity.model,\n\t\t\t...(assessment\n\t\t\t\t? {\n\t\t\t\t\t\tprofile: assessment.profile,\n\t\t\t\t\t\tcontextTokens: assessment.contextTokens,\n\t\t\t\t\t\toutputReserveTokens: assessment.outputReserveTokens,\n\t\t\t\t\t}\n\t\t\t\t: { budget: \"unbudgeted\" }),\n\t\t\tconfiguration,\n\t\t\tpolicy,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n"]}
1
+ {"version":3,"file":"context-epoch.d.ts","sourceRoot":"","sources":["../../src/core/context-epoch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,sBAAsB,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AAGlH,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AACzE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AA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B,EACtC,cAAc,EAAE,qBAAqB,GACnC,IAAI,CAUN;AAED,wBAAgB,oBAAoB,CAAC,CAAC,SAAS,sBAAsB,EAAE,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,CAEpG;AAED,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,sBAAsB,GAAG,SAAS,CAgHvG;AAED,6FAA6F;AAC7F,wBAAgB,0BAA0B,CACzC,OAAO,EAAE,6BAA6B,EACtC,UAAU,EAAE,sBAAsB,GAAG,SAAS,EAC9C,QAAQ,EAAE,MAAM,EAChB,gBAAgB,UAAQ,EACxB,oBAAoB,CAAC,EAAE,MAAM,GAC3B,MAAM,CAiFR","sourcesContent":["import type { ProviderRequestRepresentation, RequestTokenAssessment, Usage } from \"@ponythewhite/base-context-ai\";\nimport { requestTokenRouteIdentity } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { ContextRef, IndexedSourceEvent } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport { MAX_RESOURCE_REVISION_BYTES } from \"./resource-view.js\";\nimport type { SelectedSkillReference } from \"./selected-skills.js\";\nimport type { CompiledTaskFrame } from \"./task-frame.js\";\n\nexport const CONTEXT_EPOCH_DETAIL = \"baseContextEpoch\";\n/** Internal admission, not a field accepted by ordinary appendCompaction callers. */\nexport const appendContextEpoch = Symbol(\"appendContextEpoch\");\nexport const CONTEXT_EPOCH_RENDERER = \"native-canonical-epoch/4\";\nexport const CONTEXT_POLICY_EPOCH_RENDERER = \"native-canonical-epoch/5\";\nexport const CONTEXT_TOOL_EPOCH_RENDERER = \"native-canonical-epoch/6\";\n/** Selection-bearing v4/v5/v6 variants; older readers must refuse rather than drop these refs. */\nexport const CONTEXT_SKILL_EPOCH_RENDERER = \"native-canonical-epoch/7\";\n/** Source-backed summary with retained public tool groups, not a measured MAIN request. */\nexport const CONTEXT_TOOL_SUMMARY_RENDERER = \"native-canonical-epoch/8\";\n/** Public recipes may record absent admission, never a fabricated execution outcome. */\nexport const CONTEXT_INTERRUPTED_TOOL_RENDERER = \"native-canonical-epoch/9\";\n\n/** Descriptive, source-backed outcomes in the existing accepted epoch, not an execution store. */\nexport interface ToolContinuationGroup {\n\treadonly assistantEntryId: string;\n\treadonly calls: readonly (\n\t\t| {\n\t\t\t\treadonly admission?: never;\n\t\t\t\treadonly executionId: string;\n\t\t\t\treadonly intent: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\t\t\treadonly outcome: \"outcome_unknown\" | \"not_started\" | \"completed\" | \"failed\";\n\t\t\t\treadonly result?: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\t }\n\t\t| {\n\t\t\t\treadonly admission: \"absent\";\n\t\t\t\t/** Absence is scoped to this exact captured branch prefix, not external effects. */\n\t\t\t\treadonly source: SourceSnapshotRef;\n\t\t\t\treadonly executionId?: never;\n\t\t\t\treadonly intent?: never;\n\t\t\t\treadonly outcome?: never;\n\t\t\t\treadonly result?: never;\n\t\t }\n\t)[];\n}\nexport type ContextMode = \"on\" | \"off\";\n\n/** Compatibility retained from an accepted native request, not measurement or replay credit. */\nexport interface ContextEpochRequestContract {\n\treadonly api: string;\n\treadonly provider: string;\n\treadonly route: string;\n\treadonly model: string;\n\treadonly replayContract: ContextReplayContract;\n}\nexport type ContextReplayContract = \"complete-context\" | \"message-groups\";\n\n/** An ordinary summary and its retained source recipes share the existing compaction ACK. */\nexport interface ContextEpochSummary {\n\treadonly summary: string;\n\treadonly details?: Record<string, unknown>;\n\treadonly fromHook?: boolean;\n\treadonly customInstructions?: string;\n\treadonly usage?: Usage;\n}\n\n/** A frozen read recipe, not a second copy of an archived message body. */\nexport interface EpochViewReference {\n\treadonly source: SourceSnapshotRef;\n\treadonly ref: ContextRef;\n\treadonly sourceRevision: string;\n\t/** Present only for an existing rendered compaction summary. */\n\treadonly retainedMessageCount?: number;\n\treadonly rendering?: \"public-history/1\" | \"public-tool-continuation/1\";\n}\n\ninterface ContextEpochFields {\n\treadonly renderer:\n\t\t| \"native-canonical-epoch/1\"\n\t\t| \"native-canonical-epoch/2\"\n\t\t| \"native-canonical-epoch/3\"\n\t\t| typeof CONTEXT_EPOCH_RENDERER\n\t\t| typeof CONTEXT_POLICY_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_SKILL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_SUMMARY_RENDERER\n\t\t| typeof CONTEXT_INTERRUPTED_TOOL_RENDERER;\n\treadonly source: SourceSnapshotRef;\n\treadonly includeSummary?: true;\n\t/** Granted by an actual accepted adapter projection, never a caller profile name. */\n\treadonly replayContract?: ContextReplayContract;\n\t/** Actual adapter permission to leave completed native groups for a fresh public window. */\n\treadonly publicWindow?: true;\n\t/** Frozen public transition. Later native messages are not silently converted. */\n\treadonly continuation?: {\n\t\treadonly kind: \"harness-summary\" | \"portable-checkpoint\";\n\t\treadonly publicTailThrough: SourceSnapshotRef;\n\t};\n\treadonly views: readonly EpochViewReference[];\n\t/** Captured versions, not a body cache or authority inferred from transcript markup. */\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\t/** v6 requests and v8 summaries retain whole public groups and their exact outcome refs. */\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n\t/** Derived display only. The task reducer remains the authority for later changes. */\n\treadonly taskFrame?: CompiledTaskFrame;\n\t/** Accepted-state comparison only; saved metadata never establishes current resource liveness. */\n\treadonly resourceRevision?: string;\n\treadonly literalTailId: string;\n}\n\n/** v5 policy-only null is a mode ACK, not an ordinary summary or a measured request. */\nexport type ContextEpochCheckpoint = ContextEpochFields &\n\t(\n\t\t| {\n\t\t\t\treadonly version: 1 | 2 | 3 | 4 | 6;\n\t\t\t\treadonly representation: string | null;\n\t\t\t\treadonly mode?: never;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 8;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly includeSummary: true;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 5;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly policyOnly: true;\n\t\t\t\treadonly includeSummary?: never;\n\t\t\t\treadonly requestContract?: ContextEpochRequestContract;\n\t\t\t\treadonly pendingRequestContract?: true;\n\t\t }\n\t);\n\nexport function contextEpochMode(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n\tinitial: ContextMode = \"on\",\n): ContextMode {\n\treturn checkpoint ? (checkpoint.version === 5 || checkpoint.version === 8 ? checkpoint.mode : \"on\") : initial;\n}\n\nfunction isRequestContract(value: unknown): value is ContextEpochRequestContract {\n\tif (!value || typeof value !== \"object\") return false;\n\treturn (\n\t\t[\"api\", \"provider\", \"route\", \"model\"].every(\n\t\t\t(key) =>\n\t\t\t\tkey in value &&\n\t\t\t\ttypeof (value as Record<string, unknown>)[key] === \"string\" &&\n\t\t\t\t(value as Record<string, unknown>)[key] !== \"\",\n\t\t) &&\n\t\t\"replayContract\" in value &&\n\t\t(value.replayContract === \"complete-context\" || value.replayContract === \"message-groups\")\n\t);\n}\n\n/** Only call with a qualified checkpoint, never raw compaction marker data. */\nexport function retainedContextRequestContract(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n): ContextEpochRequestContract | undefined {\n\tif (!checkpoint) return;\n\tif (checkpoint.requestContract) return structuredClone(checkpoint.requestContract);\n\tif (!checkpoint.representation) return;\n\tconst accepted: unknown = JSON.parse(checkpoint.representation);\n\tif (!accepted || typeof accepted !== \"object\") throw new Error(\"Accepted context request contract is unavailable\");\n\tconst value = { ...accepted, replayContract: checkpoint.replayContract ?? \"complete-context\" };\n\tif (!isRequestContract(value)) throw new Error(\"Accepted context request contract is unavailable\");\n\treturn {\n\t\tapi: value.api,\n\t\tprovider: value.provider,\n\t\troute: value.route,\n\t\tmodel: value.model,\n\t\treplayContract: value.replayContract,\n\t};\n}\n\n/** Identity comes from the actual final native serialization, not a model/profile label. */\nexport function contextRequestContract(\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): ContextEpochRequestContract {\n\tconst route = requestTokenRouteIdentity(request.url);\n\tconst body: unknown = request.body === undefined ? undefined : JSON.parse(request.body);\n\tif (\n\t\t!route ||\n\t\t!body ||\n\t\ttypeof body !== \"object\" ||\n\t\t!(\"model\" in body) ||\n\t\ttypeof body.model !== \"string\" ||\n\t\t!body.model\n\t)\n\t\tthrow new Error(\"Native context request identity is unavailable\");\n\treturn { api: request.api, provider: request.provider, route, model: body.model, replayContract };\n}\n\nexport function assertContextRequestContract(\n\tcontract: ContextEpochRequestContract,\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): void {\n\tconst actual = contextRequestContract(request, replayContract);\n\tif (\n\t\tactual.api !== contract.api ||\n\t\tactual.provider !== contract.provider ||\n\t\tactual.route !== contract.route ||\n\t\tactual.model !== contract.model ||\n\t\tactual.replayContract !== contract.replayContract\n\t)\n\t\tthrow new Error(\"Retained context requires its accepted native request contract\");\n}\n\nexport function snapshotContextEpoch<T extends ContextEpochCheckpoint>(value: T, maxBytes: number): T {\n\treturn JSON.parse(stringifyBoundedJson(value, maxBytes)) as T;\n}\n\n/** Called only after checking the source frame's genuine epoch qualification. */\nexport function readContextEpoch(details: unknown, maxBytes: number): ContextEpochCheckpoint | undefined {\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return;\n\tconst value: unknown = details[CONTEXT_EPOCH_DETAIL];\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"version\" in value) ||\n\t\t!(\"renderer\" in value) ||\n\t\t!(\n\t\t\t(value.version === 1 && value.renderer === \"native-canonical-epoch/1\") ||\n\t\t\t(value.version === 2 && value.renderer === \"native-canonical-epoch/2\") ||\n\t\t\t(value.version === 3 && value.renderer === \"native-canonical-epoch/3\") ||\n\t\t\t(value.version === 4 && value.renderer === \"native-canonical-epoch/4\") ||\n\t\t\t(value.version === 5 && value.renderer === CONTEXT_POLICY_EPOCH_RENDERER) ||\n\t\t\t(value.version === 6 && value.renderer === CONTEXT_TOOL_EPOCH_RENDERER) ||\n\t\t\t(value.version === 8 && value.renderer === CONTEXT_TOOL_SUMMARY_RENDERER) ||\n\t\t\t([6, 8].includes(value.version as number) && value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) ||\n\t\t\t([4, 5, 6].includes(value.version as number) && value.renderer === CONTEXT_SKILL_EPOCH_RENDERER)\n\t\t) ||\n\t\t(value.renderer === CONTEXT_SKILL_EPOCH_RENDERER ||\n\t\t((value.version === 8 || value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) && \"selectedSkills\" in value)\n\t\t\t? !(\"selectedSkills\" in value) ||\n\t\t\t\t!Array.isArray(value.selectedSkills) ||\n\t\t\t\tvalue.selectedSkills.length === 0 ||\n\t\t\t\tvalue.selectedSkills.some(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\t!item ||\n\t\t\t\t\t\ttypeof item.name !== \"string\" ||\n\t\t\t\t\t\t!item.view ||\n\t\t\t\t\t\t![\"custom_message\", \"custom\"].includes(item.view.ref?.kind) ||\n\t\t\t\t\t\ttypeof item.view.sourceRevision !== \"string\",\n\t\t\t\t) ||\n\t\t\t\tnew Set(value.selectedSkills.map((item) => item.name)).size !== value.selectedSkills.length\n\t\t\t: \"selectedSkills\" in value) ||\n\t\t!(\"source\" in value) ||\n\t\t!value.source ||\n\t\t!(\"views\" in value) ||\n\t\t!Array.isArray(value.views) ||\n\t\t!(\"literalTailId\" in value) ||\n\t\ttypeof value.literalTailId !== \"string\" ||\n\t\t!(\"representation\" in value) ||\n\t\t(value.version === 5 || value.version === 8\n\t\t\t? !(\"mode\" in value) || (value.mode !== \"on\" && value.mode !== \"off\")\n\t\t\t: \"mode\" in value) ||\n\t\t(value.version === 8 &&\n\t\t\t(value.representation !== null || !(\"includeSummary\" in value) || value.includeSummary !== true)) ||\n\t\t(value.version === 5 &&\n\t\t\t(value.representation !== null || !(\"policyOnly\" in value) || value.policyOnly !== true)) ||\n\t\t(\"policyOnly\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\tvalue.policyOnly !== true ||\n\t\t\t\tvalue.representation !== null ||\n\t\t\t\t\"includeSummary\" in value)) ||\n\t\t(\"pendingRequestContract\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\t!(\"mode\" in value) ||\n\t\t\t\tvalue.mode !== \"off\" ||\n\t\t\t\tvalue.pendingRequestContract !== true ||\n\t\t\t\t\"requestContract\" in value)) ||\n\t\t(\"requestContract\" in value && (value.version !== 5 || !isRequestContract(value.requestContract))) ||\n\t\t!(\n\t\t\ttypeof value.representation === \"string\" ||\n\t\t\t(value.version === 5 && value.representation === null && \"policyOnly\" in value && value.policyOnly === true) ||\n\t\t\t((value.version === 2 || value.version === 3 || value.version === 4 || value.version === 8) &&\n\t\t\t\tvalue.representation === null &&\n\t\t\t\t\"includeSummary\" in value &&\n\t\t\t\tvalue.includeSummary === true)\n\t\t) ||\n\t\t(\"includeSummary\" in value &&\n\t\t\t((value.version !== 2 && value.version !== 3 && value.version !== 4 && value.version !== 8) ||\n\t\t\t\tvalue.includeSummary !== true ||\n\t\t\t\tvalue.representation !== null)) ||\n\t\t(\"replayContract\" in value &&\n\t\t\tvalue.replayContract !== \"complete-context\" &&\n\t\t\tvalue.replayContract !== \"message-groups\") ||\n\t\t(\"resourceRevision\" in value &&\n\t\t\t(typeof value.resourceRevision !== \"string\" ||\n\t\t\t\tBuffer.byteLength(value.resourceRevision, \"utf8\") > MAX_RESOURCE_REVISION_BYTES)) ||\n\t\t(\"publicWindow\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\tvalue.publicWindow !== true)) ||\n\t\t(\"toolContinuations\" in value && value.version !== 6 && value.version !== 8) ||\n\t\t((value.version === 6 || value.version === 8) &&\n\t\t\t(!(\"toolContinuations\" in value) ||\n\t\t\t\t!Array.isArray(value.toolContinuations) ||\n\t\t\t\t!value.toolContinuations.length ||\n\t\t\t\t!(\"replayContract\" in value) ||\n\t\t\t\t(value.version === 6 &&\n\t\t\t\t\t(!(\"publicWindow\" in value) ||\n\t\t\t\t\t\tvalue.publicWindow !== true ||\n\t\t\t\t\t\tvalue.replayContract !== \"message-groups\")))) ||\n\t\t(\"continuation\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\t!value.continuation ||\n\t\t\t\ttypeof value.continuation !== \"object\" ||\n\t\t\t\t!(\"kind\" in value.continuation) ||\n\t\t\t\t(value.continuation.kind !== \"harness-summary\" &&\n\t\t\t\t\t((value.version !== 4 && value.version !== 5 && value.version !== 6) ||\n\t\t\t\t\t\tvalue.continuation.kind !== \"portable-checkpoint\")) ||\n\t\t\t\t!(\"publicTailThrough\" in value.continuation) ||\n\t\t\t\t!value.continuation.publicTailThrough))\n\t)\n\t\tthrow new Error(\"Invalid committed context epoch\");\n\treturn snapshotContextEpoch(value as ContextEpochCheckpoint, maxBytes);\n}\n\n/** Stable representation, not the changing input, an auth envelope, or a cache-hit claim. */\nexport function contextEpochRepresentation(\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n\tmaxBytes: number,\n\tunbudgetedPublic = false,\n\tresponseItemIdentity?: string,\n): string {\n\tif (\n\t\t(!assessment && !unbudgetedPublic) ||\n\t\t(assessment &&\n\t\t\t(!assessment.profile ||\n\t\t\t\tassessment.limitSource !== \"explicit-profile\" ||\n\t\t\t\t!assessment.route ||\n\t\t\t\t!assessment.model)) ||\n\t\trequest.body === undefined\n\t)\n\t\tthrow new Error(\"Committed context epoch requires its explicit request profile\");\n\tconst identity = assessment ?? contextRequestContract(request, \"message-groups\");\n\tconst body: unknown = JSON.parse(request.body);\n\tif (!body || typeof body !== \"object\" || Array.isArray(body))\n\t\tthrow new Error(\"Context epoch request representation is unavailable\");\n\tconst configuration: Record<string, unknown> = {};\n\tconst fields = new Set([\n\t\t\"model\",\n\t\t\"instructions\",\n\t\t\"stream\",\n\t\t\"max_output_tokens\",\n\t\t\"max_tokens\",\n\t\t\"max_completion_tokens\",\n\t\t\"temperature\",\n\t\t\"top_p\",\n\t\t\"text\",\n\t\t\"tools\",\n\t\t\"tool_choice\",\n\t\t\"parallel_tool_calls\",\n\t\t\"store\",\n\t\t\"reasoning\",\n\t\t\"service_tier\",\n\t\t\"truncation\",\n\t\t\"include\",\n\t\t\"prompt_cache_retention\",\n\t\t\"stream_options\",\n\t]);\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\tidentity.route === request.url &&\n\t\t\"model\" in body &&\n\t\tbody.model === \"deepseek-flash\" &&\n\t\tidentity.model === body.model\n\t) {\n\t\tfields.add(\"thinking\");\n\t\tfields.add(\"reasoning_effort\");\n\t}\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif ([\"input\", \"messages\", \"previous_response_id\", \"prompt_cache_key\"].includes(key)) continue;\n\t\t// Unknown payload extensions may contain private data or change the representation.\n\t\tif (!fields.has(key)) throw new Error(\"Unsupported context epoch request configuration\");\n\t\tconfiguration[key] = value;\n\t}\n\tconst input: unknown = \"input\" in body ? body.input : \"messages\" in body ? body.messages : undefined;\n\tif (!Array.isArray(input)) throw new Error(\"Context epoch request messages are unavailable\");\n\tconst policy = input.filter(\n\t\t(item: unknown) =>\n\t\t\titem && typeof item === \"object\" && \"role\" in item && (item.role === \"system\" || item.role === \"developer\"),\n\t);\n\treturn stringifyBoundedJson(\n\t\t{\n\t\t\trenderer: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(responseItemIdentity ? { responseItemIdentity } : {}),\n\t\t\tapi: request.api,\n\t\t\tprovider: request.provider,\n\t\t\troute: identity.route,\n\t\t\tmodel: identity.model,\n\t\t\t...(assessment\n\t\t\t\t? {\n\t\t\t\t\t\tprofile: assessment.profile,\n\t\t\t\t\t\tcontextTokens: assessment.contextTokens,\n\t\t\t\t\t\toutputReserveTokens: assessment.outputReserveTokens,\n\t\t\t\t\t}\n\t\t\t\t: { budget: \"unbudgeted\" }),\n\t\t\tconfiguration,\n\t\t\tpolicy,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n"]}
@@ -11,6 +11,8 @@ export const CONTEXT_TOOL_EPOCH_RENDERER = "native-canonical-epoch/6";
11
11
  export const CONTEXT_SKILL_EPOCH_RENDERER = "native-canonical-epoch/7";
12
12
  /** Source-backed summary with retained public tool groups, not a measured MAIN request. */
13
13
  export const CONTEXT_TOOL_SUMMARY_RENDERER = "native-canonical-epoch/8";
14
+ /** Public recipes may record absent admission, never a fabricated execution outcome. */
15
+ export const CONTEXT_INTERRUPTED_TOOL_RENDERER = "native-canonical-epoch/9";
14
16
  export function contextEpochMode(checkpoint, initial = "on") {
15
17
  return checkpoint ? (checkpoint.version === 5 || checkpoint.version === 8 ? checkpoint.mode : "on") : initial;
16
18
  }
@@ -86,8 +88,10 @@ export function readContextEpoch(details, maxBytes) {
86
88
  (value.version === 5 && value.renderer === CONTEXT_POLICY_EPOCH_RENDERER) ||
87
89
  (value.version === 6 && value.renderer === CONTEXT_TOOL_EPOCH_RENDERER) ||
88
90
  (value.version === 8 && value.renderer === CONTEXT_TOOL_SUMMARY_RENDERER) ||
91
+ ([6, 8].includes(value.version) && value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) ||
89
92
  ([4, 5, 6].includes(value.version) && value.renderer === CONTEXT_SKILL_EPOCH_RENDERER)) ||
90
- (value.renderer === CONTEXT_SKILL_EPOCH_RENDERER || (value.version === 8 && "selectedSkills" in value)
93
+ (value.renderer === CONTEXT_SKILL_EPOCH_RENDERER ||
94
+ ((value.version === 8 || value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) && "selectedSkills" in value)
91
95
  ? !("selectedSkills" in value) ||
92
96
  !Array.isArray(value.selectedSkills) ||
93
97
  value.selectedSkills.length === 0 ||
@@ -1 +1 @@
1
- {"version":3,"file":"context-epoch.js","sourceRoot":"","sources":["../../src/core/context-epoch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAGzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAIjE,MAAM,CAAC,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AACvD,qFAAqF;AACrF,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAC/D,MAAM,CAAC,MAAM,sBAAsB,GAAG,0BAA0B,CAAC;AACjE,MAAM,CAAC,MAAM,6BAA6B,GAAG,0BAA0B,CAAC;AACxE,MAAM,CAAC,MAAM,2BAA2B,GAAG,0BAA0B,CAAC;AACtE,kGAAkG;AAClG,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AACvE,2FAA2F;AAC3F,MAAM,CAAC,MAAM,6BAA6B,GAAG,0BAA0B,CAAC;AA2GxE,MAAM,UAAU,gBAAgB,CAC/B,UAA8C,EAC9C,OAAO,GAAgB,IAAI,EACb;IACd,OAAO,UAAU,CAAC,CAAC,CAAC,CAAC,UAAU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AAC,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC;IACrG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IAC7F,MAAM,MAAM,GAAG,KAAK,CAAC,MAAM,CAC1B,CAAC,IAAa,EAAE,EAAE,CACjB,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,KAAK,WAAW,CAAC,CAC5G,CAAC;IACF,OAAO,oBAAoB,CAC1B;QACC,QAAQ,EAAE,sBAAsB;QAChC,GAAG,CAAC,oBAAoB,CAAC,CAAC,CAAC,EAAE,oBAAoB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACzD,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,KAAK,EAAE,QAAQ,CAAC,KAAK;QACrB,GAAG,CAAC,UAAU;YACb,CAAC,CAAC;gBACA,OAAO,EAAE,UAAU,CAAC,OAAO;gBAC3B,aAAa,EAAE,UAAU,CAAC,aAAa;gBACvC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;aACnD;YACF,CAAC,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;QAC5B,aAAa;QACb,MAAM;KACN,EACD,QAAQ,CACR,CAAC;AAAA,CACF","sourcesContent":["import type { ProviderRequestRepresentation, RequestTokenAssessment, Usage } from \"@ponythewhite/base-context-ai\";\nimport { requestTokenRouteIdentity } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { ContextRef, IndexedSourceEvent } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport { MAX_RESOURCE_REVISION_BYTES } from \"./resource-view.js\";\nimport type { SelectedSkillReference } from \"./selected-skills.js\";\nimport type { CompiledTaskFrame } from \"./task-frame.js\";\n\nexport const CONTEXT_EPOCH_DETAIL = \"baseContextEpoch\";\n/** Internal admission, not a field accepted by ordinary appendCompaction callers. */\nexport const appendContextEpoch = Symbol(\"appendContextEpoch\");\nexport const CONTEXT_EPOCH_RENDERER = \"native-canonical-epoch/4\";\nexport const CONTEXT_POLICY_EPOCH_RENDERER = \"native-canonical-epoch/5\";\nexport const CONTEXT_TOOL_EPOCH_RENDERER = \"native-canonical-epoch/6\";\n/** Selection-bearing v4/v5/v6 variants; older readers must refuse rather than drop these refs. */\nexport const CONTEXT_SKILL_EPOCH_RENDERER = \"native-canonical-epoch/7\";\n/** Source-backed summary with retained public tool groups, not a measured MAIN request. */\nexport const CONTEXT_TOOL_SUMMARY_RENDERER = \"native-canonical-epoch/8\";\n\n/** Descriptive, source-backed outcomes in the existing accepted epoch, not an execution store. */\nexport interface ToolContinuationGroup {\n\treadonly assistantEntryId: string;\n\treadonly calls: readonly {\n\t\treadonly executionId: string;\n\t\treadonly intent: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\treadonly outcome: \"outcome_unknown\" | \"not_started\" | \"completed\" | \"failed\";\n\t\treadonly result?: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t}[];\n}\nexport type ContextMode = \"on\" | \"off\";\n\n/** Compatibility retained from an accepted native request, not measurement or replay credit. */\nexport interface ContextEpochRequestContract {\n\treadonly api: string;\n\treadonly provider: string;\n\treadonly route: string;\n\treadonly model: string;\n\treadonly replayContract: ContextReplayContract;\n}\nexport type ContextReplayContract = \"complete-context\" | \"message-groups\";\n\n/** An ordinary summary and its retained source recipes share the existing compaction ACK. */\nexport interface ContextEpochSummary {\n\treadonly summary: string;\n\treadonly details?: Record<string, unknown>;\n\treadonly fromHook?: boolean;\n\treadonly customInstructions?: string;\n\treadonly usage?: Usage;\n}\n\n/** A frozen read recipe, not a second copy of an archived message body. */\nexport interface EpochViewReference {\n\treadonly source: SourceSnapshotRef;\n\treadonly ref: ContextRef;\n\treadonly sourceRevision: string;\n\t/** Present only for an existing rendered compaction summary. */\n\treadonly retainedMessageCount?: number;\n\treadonly rendering?: \"public-history/1\" | \"public-tool-continuation/1\";\n}\n\ninterface ContextEpochFields {\n\treadonly renderer:\n\t\t| \"native-canonical-epoch/1\"\n\t\t| \"native-canonical-epoch/2\"\n\t\t| \"native-canonical-epoch/3\"\n\t\t| typeof CONTEXT_EPOCH_RENDERER\n\t\t| typeof CONTEXT_POLICY_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_SKILL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_SUMMARY_RENDERER;\n\treadonly source: SourceSnapshotRef;\n\treadonly includeSummary?: true;\n\t/** Granted by an actual accepted adapter projection, never a caller profile name. */\n\treadonly replayContract?: ContextReplayContract;\n\t/** Actual adapter permission to leave completed native groups for a fresh public window. */\n\treadonly publicWindow?: true;\n\t/** Frozen public transition. Later native messages are not silently converted. */\n\treadonly continuation?: {\n\t\treadonly kind: \"harness-summary\" | \"portable-checkpoint\";\n\t\treadonly publicTailThrough: SourceSnapshotRef;\n\t};\n\treadonly views: readonly EpochViewReference[];\n\t/** Captured versions, not a body cache or authority inferred from transcript markup. */\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\t/** v6 requests and v8 summaries retain whole public groups and their exact outcome refs. */\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n\t/** Derived display only. The task reducer remains the authority for later changes. */\n\treadonly taskFrame?: CompiledTaskFrame;\n\t/** Accepted-state comparison only; saved metadata never establishes current resource liveness. */\n\treadonly resourceRevision?: string;\n\treadonly literalTailId: string;\n}\n\n/** v5 policy-only null is a mode ACK, not an ordinary summary or a measured request. */\nexport type ContextEpochCheckpoint = ContextEpochFields &\n\t(\n\t\t| {\n\t\t\t\treadonly version: 1 | 2 | 3 | 4 | 6;\n\t\t\t\treadonly representation: string | null;\n\t\t\t\treadonly mode?: never;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 8;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly includeSummary: true;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 5;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly policyOnly: true;\n\t\t\t\treadonly includeSummary?: never;\n\t\t\t\treadonly requestContract?: ContextEpochRequestContract;\n\t\t\t\treadonly pendingRequestContract?: true;\n\t\t }\n\t);\n\nexport function contextEpochMode(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n\tinitial: ContextMode = \"on\",\n): ContextMode {\n\treturn checkpoint ? (checkpoint.version === 5 || checkpoint.version === 8 ? checkpoint.mode : \"on\") : initial;\n}\n\nfunction isRequestContract(value: unknown): value is ContextEpochRequestContract {\n\tif (!value || typeof value !== \"object\") return false;\n\treturn (\n\t\t[\"api\", \"provider\", \"route\", \"model\"].every(\n\t\t\t(key) =>\n\t\t\t\tkey in value &&\n\t\t\t\ttypeof (value as Record<string, unknown>)[key] === \"string\" &&\n\t\t\t\t(value as Record<string, unknown>)[key] !== \"\",\n\t\t) &&\n\t\t\"replayContract\" in value &&\n\t\t(value.replayContract === \"complete-context\" || value.replayContract === \"message-groups\")\n\t);\n}\n\n/** Only call with a qualified checkpoint, never raw compaction marker data. */\nexport function retainedContextRequestContract(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n): ContextEpochRequestContract | undefined {\n\tif (!checkpoint) return;\n\tif (checkpoint.requestContract) return structuredClone(checkpoint.requestContract);\n\tif (!checkpoint.representation) return;\n\tconst accepted: unknown = JSON.parse(checkpoint.representation);\n\tif (!accepted || typeof accepted !== \"object\") throw new Error(\"Accepted context request contract is unavailable\");\n\tconst value = { ...accepted, replayContract: checkpoint.replayContract ?? \"complete-context\" };\n\tif (!isRequestContract(value)) throw new Error(\"Accepted context request contract is unavailable\");\n\treturn {\n\t\tapi: value.api,\n\t\tprovider: value.provider,\n\t\troute: value.route,\n\t\tmodel: value.model,\n\t\treplayContract: value.replayContract,\n\t};\n}\n\n/** Identity comes from the actual final native serialization, not a model/profile label. */\nexport function contextRequestContract(\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): ContextEpochRequestContract {\n\tconst route = requestTokenRouteIdentity(request.url);\n\tconst body: unknown = request.body === undefined ? undefined : JSON.parse(request.body);\n\tif (\n\t\t!route ||\n\t\t!body ||\n\t\ttypeof body !== \"object\" ||\n\t\t!(\"model\" in body) ||\n\t\ttypeof body.model !== \"string\" ||\n\t\t!body.model\n\t)\n\t\tthrow new Error(\"Native context request identity is unavailable\");\n\treturn { api: request.api, provider: request.provider, route, model: body.model, replayContract };\n}\n\nexport function assertContextRequestContract(\n\tcontract: ContextEpochRequestContract,\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): void {\n\tconst actual = contextRequestContract(request, replayContract);\n\tif (\n\t\tactual.api !== contract.api ||\n\t\tactual.provider !== contract.provider ||\n\t\tactual.route !== contract.route ||\n\t\tactual.model !== contract.model ||\n\t\tactual.replayContract !== contract.replayContract\n\t)\n\t\tthrow new Error(\"Retained context requires its accepted native request contract\");\n}\n\nexport function snapshotContextEpoch<T extends ContextEpochCheckpoint>(value: T, maxBytes: number): T {\n\treturn JSON.parse(stringifyBoundedJson(value, maxBytes)) as T;\n}\n\n/** Called only after checking the source frame's genuine epoch qualification. */\nexport function readContextEpoch(details: unknown, maxBytes: number): ContextEpochCheckpoint | undefined {\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return;\n\tconst value: unknown = details[CONTEXT_EPOCH_DETAIL];\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"version\" in value) ||\n\t\t!(\"renderer\" in value) ||\n\t\t!(\n\t\t\t(value.version === 1 && value.renderer === \"native-canonical-epoch/1\") ||\n\t\t\t(value.version === 2 && value.renderer === \"native-canonical-epoch/2\") ||\n\t\t\t(value.version === 3 && value.renderer === \"native-canonical-epoch/3\") ||\n\t\t\t(value.version === 4 && value.renderer === \"native-canonical-epoch/4\") ||\n\t\t\t(value.version === 5 && value.renderer === CONTEXT_POLICY_EPOCH_RENDERER) ||\n\t\t\t(value.version === 6 && value.renderer === CONTEXT_TOOL_EPOCH_RENDERER) ||\n\t\t\t(value.version === 8 && value.renderer === CONTEXT_TOOL_SUMMARY_RENDERER) ||\n\t\t\t([4, 5, 6].includes(value.version as number) && value.renderer === CONTEXT_SKILL_EPOCH_RENDERER)\n\t\t) ||\n\t\t(value.renderer === CONTEXT_SKILL_EPOCH_RENDERER || (value.version === 8 && \"selectedSkills\" in value)\n\t\t\t? !(\"selectedSkills\" in value) ||\n\t\t\t\t!Array.isArray(value.selectedSkills) ||\n\t\t\t\tvalue.selectedSkills.length === 0 ||\n\t\t\t\tvalue.selectedSkills.some(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\t!item ||\n\t\t\t\t\t\ttypeof item.name !== \"string\" ||\n\t\t\t\t\t\t!item.view ||\n\t\t\t\t\t\t![\"custom_message\", \"custom\"].includes(item.view.ref?.kind) ||\n\t\t\t\t\t\ttypeof item.view.sourceRevision !== \"string\",\n\t\t\t\t) ||\n\t\t\t\tnew Set(value.selectedSkills.map((item) => item.name)).size !== value.selectedSkills.length\n\t\t\t: \"selectedSkills\" in value) ||\n\t\t!(\"source\" in value) ||\n\t\t!value.source ||\n\t\t!(\"views\" in value) ||\n\t\t!Array.isArray(value.views) ||\n\t\t!(\"literalTailId\" in value) ||\n\t\ttypeof value.literalTailId !== \"string\" ||\n\t\t!(\"representation\" in value) ||\n\t\t(value.version === 5 || value.version === 8\n\t\t\t? !(\"mode\" in value) || (value.mode !== \"on\" && value.mode !== \"off\")\n\t\t\t: \"mode\" in value) ||\n\t\t(value.version === 8 &&\n\t\t\t(value.representation !== null || !(\"includeSummary\" in value) || value.includeSummary !== true)) ||\n\t\t(value.version === 5 &&\n\t\t\t(value.representation !== null || !(\"policyOnly\" in value) || value.policyOnly !== true)) ||\n\t\t(\"policyOnly\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\tvalue.policyOnly !== true ||\n\t\t\t\tvalue.representation !== null ||\n\t\t\t\t\"includeSummary\" in value)) ||\n\t\t(\"pendingRequestContract\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\t!(\"mode\" in value) ||\n\t\t\t\tvalue.mode !== \"off\" ||\n\t\t\t\tvalue.pendingRequestContract !== true ||\n\t\t\t\t\"requestContract\" in value)) ||\n\t\t(\"requestContract\" in value && (value.version !== 5 || !isRequestContract(value.requestContract))) ||\n\t\t!(\n\t\t\ttypeof value.representation === \"string\" ||\n\t\t\t(value.version === 5 && value.representation === null && \"policyOnly\" in value && value.policyOnly === true) ||\n\t\t\t((value.version === 2 || value.version === 3 || value.version === 4 || value.version === 8) &&\n\t\t\t\tvalue.representation === null &&\n\t\t\t\t\"includeSummary\" in value &&\n\t\t\t\tvalue.includeSummary === true)\n\t\t) ||\n\t\t(\"includeSummary\" in value &&\n\t\t\t((value.version !== 2 && value.version !== 3 && value.version !== 4 && value.version !== 8) ||\n\t\t\t\tvalue.includeSummary !== true ||\n\t\t\t\tvalue.representation !== null)) ||\n\t\t(\"replayContract\" in value &&\n\t\t\tvalue.replayContract !== \"complete-context\" &&\n\t\t\tvalue.replayContract !== \"message-groups\") ||\n\t\t(\"resourceRevision\" in value &&\n\t\t\t(typeof value.resourceRevision !== \"string\" ||\n\t\t\t\tBuffer.byteLength(value.resourceRevision, \"utf8\") > MAX_RESOURCE_REVISION_BYTES)) ||\n\t\t(\"publicWindow\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\tvalue.publicWindow !== true)) ||\n\t\t(\"toolContinuations\" in value && value.version !== 6 && value.version !== 8) ||\n\t\t((value.version === 6 || value.version === 8) &&\n\t\t\t(!(\"toolContinuations\" in value) ||\n\t\t\t\t!Array.isArray(value.toolContinuations) ||\n\t\t\t\t!value.toolContinuations.length ||\n\t\t\t\t!(\"replayContract\" in value) ||\n\t\t\t\t(value.version === 6 &&\n\t\t\t\t\t(!(\"publicWindow\" in value) ||\n\t\t\t\t\t\tvalue.publicWindow !== true ||\n\t\t\t\t\t\tvalue.replayContract !== \"message-groups\")))) ||\n\t\t(\"continuation\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\t!value.continuation ||\n\t\t\t\ttypeof value.continuation !== \"object\" ||\n\t\t\t\t!(\"kind\" in value.continuation) ||\n\t\t\t\t(value.continuation.kind !== \"harness-summary\" &&\n\t\t\t\t\t((value.version !== 4 && value.version !== 5 && value.version !== 6) ||\n\t\t\t\t\t\tvalue.continuation.kind !== \"portable-checkpoint\")) ||\n\t\t\t\t!(\"publicTailThrough\" in value.continuation) ||\n\t\t\t\t!value.continuation.publicTailThrough))\n\t)\n\t\tthrow new Error(\"Invalid committed context epoch\");\n\treturn snapshotContextEpoch(value as ContextEpochCheckpoint, maxBytes);\n}\n\n/** Stable representation, not the changing input, an auth envelope, or a cache-hit claim. */\nexport function contextEpochRepresentation(\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n\tmaxBytes: number,\n\tunbudgetedPublic = false,\n\tresponseItemIdentity?: string,\n): string {\n\tif (\n\t\t(!assessment && !unbudgetedPublic) ||\n\t\t(assessment &&\n\t\t\t(!assessment.profile ||\n\t\t\t\tassessment.limitSource !== \"explicit-profile\" ||\n\t\t\t\t!assessment.route ||\n\t\t\t\t!assessment.model)) ||\n\t\trequest.body === undefined\n\t)\n\t\tthrow new Error(\"Committed context epoch requires its explicit request profile\");\n\tconst identity = assessment ?? contextRequestContract(request, \"message-groups\");\n\tconst body: unknown = JSON.parse(request.body);\n\tif (!body || typeof body !== \"object\" || Array.isArray(body))\n\t\tthrow new Error(\"Context epoch request representation is unavailable\");\n\tconst configuration: Record<string, unknown> = {};\n\tconst fields = new Set([\n\t\t\"model\",\n\t\t\"instructions\",\n\t\t\"stream\",\n\t\t\"max_output_tokens\",\n\t\t\"max_tokens\",\n\t\t\"max_completion_tokens\",\n\t\t\"temperature\",\n\t\t\"top_p\",\n\t\t\"text\",\n\t\t\"tools\",\n\t\t\"tool_choice\",\n\t\t\"parallel_tool_calls\",\n\t\t\"store\",\n\t\t\"reasoning\",\n\t\t\"service_tier\",\n\t\t\"truncation\",\n\t\t\"include\",\n\t\t\"prompt_cache_retention\",\n\t\t\"stream_options\",\n\t]);\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\tidentity.route === request.url &&\n\t\t\"model\" in body &&\n\t\tbody.model === \"deepseek-flash\" &&\n\t\tidentity.model === body.model\n\t) {\n\t\tfields.add(\"thinking\");\n\t\tfields.add(\"reasoning_effort\");\n\t}\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif ([\"input\", \"messages\", \"previous_response_id\", \"prompt_cache_key\"].includes(key)) continue;\n\t\t// Unknown payload extensions may contain private data or change the representation.\n\t\tif (!fields.has(key)) throw new Error(\"Unsupported context epoch request configuration\");\n\t\tconfiguration[key] = value;\n\t}\n\tconst input: unknown = \"input\" in body ? body.input : \"messages\" in body ? body.messages : undefined;\n\tif (!Array.isArray(input)) throw new Error(\"Context epoch request messages are unavailable\");\n\tconst policy = input.filter(\n\t\t(item: unknown) =>\n\t\t\titem && typeof item === \"object\" && \"role\" in item && (item.role === \"system\" || item.role === \"developer\"),\n\t);\n\treturn stringifyBoundedJson(\n\t\t{\n\t\t\trenderer: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(responseItemIdentity ? { responseItemIdentity } : {}),\n\t\t\tapi: request.api,\n\t\t\tprovider: request.provider,\n\t\t\troute: identity.route,\n\t\t\tmodel: identity.model,\n\t\t\t...(assessment\n\t\t\t\t? {\n\t\t\t\t\t\tprofile: assessment.profile,\n\t\t\t\t\t\tcontextTokens: assessment.contextTokens,\n\t\t\t\t\t\toutputReserveTokens: assessment.outputReserveTokens,\n\t\t\t\t\t}\n\t\t\t\t: { budget: \"unbudgeted\" }),\n\t\t\tconfiguration,\n\t\t\tpolicy,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n"]}
1
+ {"version":3,"file":"context-epoch.js","sourceRoot":"","sources":["../../src/core/context-epoch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AAGzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,oBAAoB,CAAC;AAIjE,MAAM,CAAC,MAAM,oBAAoB,GAAG,kBAAkB,CAAC;AACvD,qFAAqF;AACrF,MAAM,CAAC,MAAM,kBAAkB,GAAG,MAAM,CAAC,oBAAoB,CAAC,CAAC;AAC/D,MAAM,CAAC,MAAM,sBAAsB,GAAG,0BAA0B,CAAC;AACjE,MAAM,CAAC,MAAM,6BAA6B,GAAG,0BAA0B,CAAC;AACxE,MAAM,CAAC,MAAM,2BAA2B,GAAG,0BAA0B,CAAC;AACtE,kGAAkG;AAClG,MAAM,CAAC,MAAM,4BAA4B,GAAG,0BAA0B,CAAC;AACvE,2FAA2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C,OAAO;gBAC3B,aAAa,EAAE,UAAU,CAAC,aAAa;gBACvC,mBAAmB,EAAE,UAAU,CAAC,mBAAmB;aACnD;YACF,CAAC,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC;QAC5B,aAAa;QACb,MAAM;KACN,EACD,QAAQ,CACR,CAAC;AAAA,CACF","sourcesContent":["import type { ProviderRequestRepresentation, RequestTokenAssessment, Usage } from \"@ponythewhite/base-context-ai\";\nimport { requestTokenRouteIdentity } from \"@ponythewhite/base-context-ai\";\nimport { stringifyBoundedJson } from \"./bounded-json.js\";\nimport type { ContextRef, IndexedSourceEvent } from \"./history-index.js\";\nimport type { SourceSnapshotRef } from \"./request-events.js\";\nimport { MAX_RESOURCE_REVISION_BYTES } from \"./resource-view.js\";\nimport type { SelectedSkillReference } from \"./selected-skills.js\";\nimport type { CompiledTaskFrame } from \"./task-frame.js\";\n\nexport const CONTEXT_EPOCH_DETAIL = \"baseContextEpoch\";\n/** Internal admission, not a field accepted by ordinary appendCompaction callers. */\nexport const appendContextEpoch = Symbol(\"appendContextEpoch\");\nexport const CONTEXT_EPOCH_RENDERER = \"native-canonical-epoch/4\";\nexport const CONTEXT_POLICY_EPOCH_RENDERER = \"native-canonical-epoch/5\";\nexport const CONTEXT_TOOL_EPOCH_RENDERER = \"native-canonical-epoch/6\";\n/** Selection-bearing v4/v5/v6 variants; older readers must refuse rather than drop these refs. */\nexport const CONTEXT_SKILL_EPOCH_RENDERER = \"native-canonical-epoch/7\";\n/** Source-backed summary with retained public tool groups, not a measured MAIN request. */\nexport const CONTEXT_TOOL_SUMMARY_RENDERER = \"native-canonical-epoch/8\";\n/** Public recipes may record absent admission, never a fabricated execution outcome. */\nexport const CONTEXT_INTERRUPTED_TOOL_RENDERER = \"native-canonical-epoch/9\";\n\n/** Descriptive, source-backed outcomes in the existing accepted epoch, not an execution store. */\nexport interface ToolContinuationGroup {\n\treadonly assistantEntryId: string;\n\treadonly calls: readonly (\n\t\t| {\n\t\t\t\treadonly admission?: never;\n\t\t\t\treadonly executionId: string;\n\t\t\t\treadonly intent: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\t\t\treadonly outcome: \"outcome_unknown\" | \"not_started\" | \"completed\" | \"failed\";\n\t\t\t\treadonly result?: Pick<IndexedSourceEvent, \"id\" | \"sequence\" | \"revision\">;\n\t\t }\n\t\t| {\n\t\t\t\treadonly admission: \"absent\";\n\t\t\t\t/** Absence is scoped to this exact captured branch prefix, not external effects. */\n\t\t\t\treadonly source: SourceSnapshotRef;\n\t\t\t\treadonly executionId?: never;\n\t\t\t\treadonly intent?: never;\n\t\t\t\treadonly outcome?: never;\n\t\t\t\treadonly result?: never;\n\t\t }\n\t)[];\n}\nexport type ContextMode = \"on\" | \"off\";\n\n/** Compatibility retained from an accepted native request, not measurement or replay credit. */\nexport interface ContextEpochRequestContract {\n\treadonly api: string;\n\treadonly provider: string;\n\treadonly route: string;\n\treadonly model: string;\n\treadonly replayContract: ContextReplayContract;\n}\nexport type ContextReplayContract = \"complete-context\" | \"message-groups\";\n\n/** An ordinary summary and its retained source recipes share the existing compaction ACK. */\nexport interface ContextEpochSummary {\n\treadonly summary: string;\n\treadonly details?: Record<string, unknown>;\n\treadonly fromHook?: boolean;\n\treadonly customInstructions?: string;\n\treadonly usage?: Usage;\n}\n\n/** A frozen read recipe, not a second copy of an archived message body. */\nexport interface EpochViewReference {\n\treadonly source: SourceSnapshotRef;\n\treadonly ref: ContextRef;\n\treadonly sourceRevision: string;\n\t/** Present only for an existing rendered compaction summary. */\n\treadonly retainedMessageCount?: number;\n\treadonly rendering?: \"public-history/1\" | \"public-tool-continuation/1\";\n}\n\ninterface ContextEpochFields {\n\treadonly renderer:\n\t\t| \"native-canonical-epoch/1\"\n\t\t| \"native-canonical-epoch/2\"\n\t\t| \"native-canonical-epoch/3\"\n\t\t| typeof CONTEXT_EPOCH_RENDERER\n\t\t| typeof CONTEXT_POLICY_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_SKILL_EPOCH_RENDERER\n\t\t| typeof CONTEXT_TOOL_SUMMARY_RENDERER\n\t\t| typeof CONTEXT_INTERRUPTED_TOOL_RENDERER;\n\treadonly source: SourceSnapshotRef;\n\treadonly includeSummary?: true;\n\t/** Granted by an actual accepted adapter projection, never a caller profile name. */\n\treadonly replayContract?: ContextReplayContract;\n\t/** Actual adapter permission to leave completed native groups for a fresh public window. */\n\treadonly publicWindow?: true;\n\t/** Frozen public transition. Later native messages are not silently converted. */\n\treadonly continuation?: {\n\t\treadonly kind: \"harness-summary\" | \"portable-checkpoint\";\n\t\treadonly publicTailThrough: SourceSnapshotRef;\n\t};\n\treadonly views: readonly EpochViewReference[];\n\t/** Captured versions, not a body cache or authority inferred from transcript markup. */\n\treadonly selectedSkills?: readonly SelectedSkillReference[];\n\t/** v6 requests and v8 summaries retain whole public groups and their exact outcome refs. */\n\treadonly toolContinuations?: readonly ToolContinuationGroup[];\n\t/** Derived display only. The task reducer remains the authority for later changes. */\n\treadonly taskFrame?: CompiledTaskFrame;\n\t/** Accepted-state comparison only; saved metadata never establishes current resource liveness. */\n\treadonly resourceRevision?: string;\n\treadonly literalTailId: string;\n}\n\n/** v5 policy-only null is a mode ACK, not an ordinary summary or a measured request. */\nexport type ContextEpochCheckpoint = ContextEpochFields &\n\t(\n\t\t| {\n\t\t\t\treadonly version: 1 | 2 | 3 | 4 | 6;\n\t\t\t\treadonly representation: string | null;\n\t\t\t\treadonly mode?: never;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 8;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly includeSummary: true;\n\t\t\t\treadonly policyOnly?: never;\n\t\t\t\treadonly requestContract?: never;\n\t\t\t\treadonly pendingRequestContract?: never;\n\t\t }\n\t\t| {\n\t\t\t\treadonly version: 5;\n\t\t\t\treadonly mode: ContextMode;\n\t\t\t\treadonly representation: null;\n\t\t\t\treadonly policyOnly: true;\n\t\t\t\treadonly includeSummary?: never;\n\t\t\t\treadonly requestContract?: ContextEpochRequestContract;\n\t\t\t\treadonly pendingRequestContract?: true;\n\t\t }\n\t);\n\nexport function contextEpochMode(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n\tinitial: ContextMode = \"on\",\n): ContextMode {\n\treturn checkpoint ? (checkpoint.version === 5 || checkpoint.version === 8 ? checkpoint.mode : \"on\") : initial;\n}\n\nfunction isRequestContract(value: unknown): value is ContextEpochRequestContract {\n\tif (!value || typeof value !== \"object\") return false;\n\treturn (\n\t\t[\"api\", \"provider\", \"route\", \"model\"].every(\n\t\t\t(key) =>\n\t\t\t\tkey in value &&\n\t\t\t\ttypeof (value as Record<string, unknown>)[key] === \"string\" &&\n\t\t\t\t(value as Record<string, unknown>)[key] !== \"\",\n\t\t) &&\n\t\t\"replayContract\" in value &&\n\t\t(value.replayContract === \"complete-context\" || value.replayContract === \"message-groups\")\n\t);\n}\n\n/** Only call with a qualified checkpoint, never raw compaction marker data. */\nexport function retainedContextRequestContract(\n\tcheckpoint: ContextEpochCheckpoint | undefined,\n): ContextEpochRequestContract | undefined {\n\tif (!checkpoint) return;\n\tif (checkpoint.requestContract) return structuredClone(checkpoint.requestContract);\n\tif (!checkpoint.representation) return;\n\tconst accepted: unknown = JSON.parse(checkpoint.representation);\n\tif (!accepted || typeof accepted !== \"object\") throw new Error(\"Accepted context request contract is unavailable\");\n\tconst value = { ...accepted, replayContract: checkpoint.replayContract ?? \"complete-context\" };\n\tif (!isRequestContract(value)) throw new Error(\"Accepted context request contract is unavailable\");\n\treturn {\n\t\tapi: value.api,\n\t\tprovider: value.provider,\n\t\troute: value.route,\n\t\tmodel: value.model,\n\t\treplayContract: value.replayContract,\n\t};\n}\n\n/** Identity comes from the actual final native serialization, not a model/profile label. */\nexport function contextRequestContract(\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): ContextEpochRequestContract {\n\tconst route = requestTokenRouteIdentity(request.url);\n\tconst body: unknown = request.body === undefined ? undefined : JSON.parse(request.body);\n\tif (\n\t\t!route ||\n\t\t!body ||\n\t\ttypeof body !== \"object\" ||\n\t\t!(\"model\" in body) ||\n\t\ttypeof body.model !== \"string\" ||\n\t\t!body.model\n\t)\n\t\tthrow new Error(\"Native context request identity is unavailable\");\n\treturn { api: request.api, provider: request.provider, route, model: body.model, replayContract };\n}\n\nexport function assertContextRequestContract(\n\tcontract: ContextEpochRequestContract,\n\trequest: ProviderRequestRepresentation,\n\treplayContract: ContextReplayContract,\n): void {\n\tconst actual = contextRequestContract(request, replayContract);\n\tif (\n\t\tactual.api !== contract.api ||\n\t\tactual.provider !== contract.provider ||\n\t\tactual.route !== contract.route ||\n\t\tactual.model !== contract.model ||\n\t\tactual.replayContract !== contract.replayContract\n\t)\n\t\tthrow new Error(\"Retained context requires its accepted native request contract\");\n}\n\nexport function snapshotContextEpoch<T extends ContextEpochCheckpoint>(value: T, maxBytes: number): T {\n\treturn JSON.parse(stringifyBoundedJson(value, maxBytes)) as T;\n}\n\n/** Called only after checking the source frame's genuine epoch qualification. */\nexport function readContextEpoch(details: unknown, maxBytes: number): ContextEpochCheckpoint | undefined {\n\tif (!details || typeof details !== \"object\" || !(CONTEXT_EPOCH_DETAIL in details)) return;\n\tconst value: unknown = details[CONTEXT_EPOCH_DETAIL];\n\tif (\n\t\t!value ||\n\t\ttypeof value !== \"object\" ||\n\t\t!(\"version\" in value) ||\n\t\t!(\"renderer\" in value) ||\n\t\t!(\n\t\t\t(value.version === 1 && value.renderer === \"native-canonical-epoch/1\") ||\n\t\t\t(value.version === 2 && value.renderer === \"native-canonical-epoch/2\") ||\n\t\t\t(value.version === 3 && value.renderer === \"native-canonical-epoch/3\") ||\n\t\t\t(value.version === 4 && value.renderer === \"native-canonical-epoch/4\") ||\n\t\t\t(value.version === 5 && value.renderer === CONTEXT_POLICY_EPOCH_RENDERER) ||\n\t\t\t(value.version === 6 && value.renderer === CONTEXT_TOOL_EPOCH_RENDERER) ||\n\t\t\t(value.version === 8 && value.renderer === CONTEXT_TOOL_SUMMARY_RENDERER) ||\n\t\t\t([6, 8].includes(value.version as number) && value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) ||\n\t\t\t([4, 5, 6].includes(value.version as number) && value.renderer === CONTEXT_SKILL_EPOCH_RENDERER)\n\t\t) ||\n\t\t(value.renderer === CONTEXT_SKILL_EPOCH_RENDERER ||\n\t\t((value.version === 8 || value.renderer === CONTEXT_INTERRUPTED_TOOL_RENDERER) && \"selectedSkills\" in value)\n\t\t\t? !(\"selectedSkills\" in value) ||\n\t\t\t\t!Array.isArray(value.selectedSkills) ||\n\t\t\t\tvalue.selectedSkills.length === 0 ||\n\t\t\t\tvalue.selectedSkills.some(\n\t\t\t\t\t(item) =>\n\t\t\t\t\t\t!item ||\n\t\t\t\t\t\ttypeof item.name !== \"string\" ||\n\t\t\t\t\t\t!item.view ||\n\t\t\t\t\t\t![\"custom_message\", \"custom\"].includes(item.view.ref?.kind) ||\n\t\t\t\t\t\ttypeof item.view.sourceRevision !== \"string\",\n\t\t\t\t) ||\n\t\t\t\tnew Set(value.selectedSkills.map((item) => item.name)).size !== value.selectedSkills.length\n\t\t\t: \"selectedSkills\" in value) ||\n\t\t!(\"source\" in value) ||\n\t\t!value.source ||\n\t\t!(\"views\" in value) ||\n\t\t!Array.isArray(value.views) ||\n\t\t!(\"literalTailId\" in value) ||\n\t\ttypeof value.literalTailId !== \"string\" ||\n\t\t!(\"representation\" in value) ||\n\t\t(value.version === 5 || value.version === 8\n\t\t\t? !(\"mode\" in value) || (value.mode !== \"on\" && value.mode !== \"off\")\n\t\t\t: \"mode\" in value) ||\n\t\t(value.version === 8 &&\n\t\t\t(value.representation !== null || !(\"includeSummary\" in value) || value.includeSummary !== true)) ||\n\t\t(value.version === 5 &&\n\t\t\t(value.representation !== null || !(\"policyOnly\" in value) || value.policyOnly !== true)) ||\n\t\t(\"policyOnly\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\tvalue.policyOnly !== true ||\n\t\t\t\tvalue.representation !== null ||\n\t\t\t\t\"includeSummary\" in value)) ||\n\t\t(\"pendingRequestContract\" in value &&\n\t\t\t(value.version !== 5 ||\n\t\t\t\t!(\"mode\" in value) ||\n\t\t\t\tvalue.mode !== \"off\" ||\n\t\t\t\tvalue.pendingRequestContract !== true ||\n\t\t\t\t\"requestContract\" in value)) ||\n\t\t(\"requestContract\" in value && (value.version !== 5 || !isRequestContract(value.requestContract))) ||\n\t\t!(\n\t\t\ttypeof value.representation === \"string\" ||\n\t\t\t(value.version === 5 && value.representation === null && \"policyOnly\" in value && value.policyOnly === true) ||\n\t\t\t((value.version === 2 || value.version === 3 || value.version === 4 || value.version === 8) &&\n\t\t\t\tvalue.representation === null &&\n\t\t\t\t\"includeSummary\" in value &&\n\t\t\t\tvalue.includeSummary === true)\n\t\t) ||\n\t\t(\"includeSummary\" in value &&\n\t\t\t((value.version !== 2 && value.version !== 3 && value.version !== 4 && value.version !== 8) ||\n\t\t\t\tvalue.includeSummary !== true ||\n\t\t\t\tvalue.representation !== null)) ||\n\t\t(\"replayContract\" in value &&\n\t\t\tvalue.replayContract !== \"complete-context\" &&\n\t\t\tvalue.replayContract !== \"message-groups\") ||\n\t\t(\"resourceRevision\" in value &&\n\t\t\t(typeof value.resourceRevision !== \"string\" ||\n\t\t\t\tBuffer.byteLength(value.resourceRevision, \"utf8\") > MAX_RESOURCE_REVISION_BYTES)) ||\n\t\t(\"publicWindow\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\tvalue.publicWindow !== true)) ||\n\t\t(\"toolContinuations\" in value && value.version !== 6 && value.version !== 8) ||\n\t\t((value.version === 6 || value.version === 8) &&\n\t\t\t(!(\"toolContinuations\" in value) ||\n\t\t\t\t!Array.isArray(value.toolContinuations) ||\n\t\t\t\t!value.toolContinuations.length ||\n\t\t\t\t!(\"replayContract\" in value) ||\n\t\t\t\t(value.version === 6 &&\n\t\t\t\t\t(!(\"publicWindow\" in value) ||\n\t\t\t\t\t\tvalue.publicWindow !== true ||\n\t\t\t\t\t\tvalue.replayContract !== \"message-groups\")))) ||\n\t\t(\"continuation\" in value &&\n\t\t\t((value.version !== 3 &&\n\t\t\t\tvalue.version !== 4 &&\n\t\t\t\tvalue.version !== 5 &&\n\t\t\t\tvalue.version !== 6 &&\n\t\t\t\tvalue.version !== 8) ||\n\t\t\t\t!value.continuation ||\n\t\t\t\ttypeof value.continuation !== \"object\" ||\n\t\t\t\t!(\"kind\" in value.continuation) ||\n\t\t\t\t(value.continuation.kind !== \"harness-summary\" &&\n\t\t\t\t\t((value.version !== 4 && value.version !== 5 && value.version !== 6) ||\n\t\t\t\t\t\tvalue.continuation.kind !== \"portable-checkpoint\")) ||\n\t\t\t\t!(\"publicTailThrough\" in value.continuation) ||\n\t\t\t\t!value.continuation.publicTailThrough))\n\t)\n\t\tthrow new Error(\"Invalid committed context epoch\");\n\treturn snapshotContextEpoch(value as ContextEpochCheckpoint, maxBytes);\n}\n\n/** Stable representation, not the changing input, an auth envelope, or a cache-hit claim. */\nexport function contextEpochRepresentation(\n\trequest: ProviderRequestRepresentation,\n\tassessment: RequestTokenAssessment | undefined,\n\tmaxBytes: number,\n\tunbudgetedPublic = false,\n\tresponseItemIdentity?: string,\n): string {\n\tif (\n\t\t(!assessment && !unbudgetedPublic) ||\n\t\t(assessment &&\n\t\t\t(!assessment.profile ||\n\t\t\t\tassessment.limitSource !== \"explicit-profile\" ||\n\t\t\t\t!assessment.route ||\n\t\t\t\t!assessment.model)) ||\n\t\trequest.body === undefined\n\t)\n\t\tthrow new Error(\"Committed context epoch requires its explicit request profile\");\n\tconst identity = assessment ?? contextRequestContract(request, \"message-groups\");\n\tconst body: unknown = JSON.parse(request.body);\n\tif (!body || typeof body !== \"object\" || Array.isArray(body))\n\t\tthrow new Error(\"Context epoch request representation is unavailable\");\n\tconst configuration: Record<string, unknown> = {};\n\tconst fields = new Set([\n\t\t\"model\",\n\t\t\"instructions\",\n\t\t\"stream\",\n\t\t\"max_output_tokens\",\n\t\t\"max_tokens\",\n\t\t\"max_completion_tokens\",\n\t\t\"temperature\",\n\t\t\"top_p\",\n\t\t\"text\",\n\t\t\"tools\",\n\t\t\"tool_choice\",\n\t\t\"parallel_tool_calls\",\n\t\t\"store\",\n\t\t\"reasoning\",\n\t\t\"service_tier\",\n\t\t\"truncation\",\n\t\t\"include\",\n\t\t\"prompt_cache_retention\",\n\t\t\"stream_options\",\n\t]);\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\tidentity.route === request.url &&\n\t\t\"model\" in body &&\n\t\tbody.model === \"deepseek-flash\" &&\n\t\tidentity.model === body.model\n\t) {\n\t\tfields.add(\"thinking\");\n\t\tfields.add(\"reasoning_effort\");\n\t}\n\tfor (const [key, value] of Object.entries(body)) {\n\t\tif ([\"input\", \"messages\", \"previous_response_id\", \"prompt_cache_key\"].includes(key)) continue;\n\t\t// Unknown payload extensions may contain private data or change the representation.\n\t\tif (!fields.has(key)) throw new Error(\"Unsupported context epoch request configuration\");\n\t\tconfiguration[key] = value;\n\t}\n\tconst input: unknown = \"input\" in body ? body.input : \"messages\" in body ? body.messages : undefined;\n\tif (!Array.isArray(input)) throw new Error(\"Context epoch request messages are unavailable\");\n\tconst policy = input.filter(\n\t\t(item: unknown) =>\n\t\t\titem && typeof item === \"object\" && \"role\" in item && (item.role === \"system\" || item.role === \"developer\"),\n\t);\n\treturn stringifyBoundedJson(\n\t\t{\n\t\t\trenderer: CONTEXT_EPOCH_RENDERER,\n\t\t\t...(responseItemIdentity ? { responseItemIdentity } : {}),\n\t\t\tapi: request.api,\n\t\t\tprovider: request.provider,\n\t\t\troute: identity.route,\n\t\t\tmodel: identity.model,\n\t\t\t...(assessment\n\t\t\t\t? {\n\t\t\t\t\t\tprofile: assessment.profile,\n\t\t\t\t\t\tcontextTokens: assessment.contextTokens,\n\t\t\t\t\t\toutputReserveTokens: assessment.outputReserveTokens,\n\t\t\t\t\t}\n\t\t\t\t: { budget: \"unbudgeted\" }),\n\t\t\tconfiguration,\n\t\t\tpolicy,\n\t\t},\n\t\tmaxBytes,\n\t);\n}\n"]}
@@ -93,7 +93,7 @@ export declare class InferenceCoordinator {
93
93
  /** Capture an auxiliary operation's subject before asynchronous auth or UI work. */
94
94
  capture(sink?: BoundRequestSink): InferenceCoordinator;
95
95
  /** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */
96
- bindRequestViewBoundary(messages: readonly AgentMessage[], commit: RequestViewCommit, validate?: RequestViewValidate, fixedPrepare?: RequestViewFixedPrepare): void;
96
+ bindRequestViewBoundary(messages: readonly AgentMessage[], commit: RequestViewCommit, validate?: RequestViewValidate, fixedPrepare?: RequestViewFixedPrepare, isSourceCurrent?: () => boolean): void;
97
97
  /** Read through an explicit capture, never by recapturing the mutable current session. */
98
98
  readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T>;
99
99
  /** Release an unused capture, or join this capture's admitted requests. */
@@ -1 +1 @@
1
- {"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK,OAAO,EAKZ,KAAK,KAAK,EAMV,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EAExB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,C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AG,SAAS,EAC1C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,OAAO,EAChB,OAAO,EAAE,mBAAmB,GAAG,SAAS,EACxC,OAAO,EAAE,uBAAuB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAE3B;AAED,MAAM,MAAM,yBAAyB,GAAG,QAAQ,GAAG;IAClD,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,sBAAsB,CAAC,CAAC,OAAO,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3F,CAAC;AAEF,yFAAyF;AACzF,wBAAgB,4BAA4B,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\ttype ProviderInputTokenCounter,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tresponsesMessageIds: new Map<string, number>(),\n\t\tresponsesIdentity: randomUUID(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst inputCountAttempts = new Map<string, NativeRequestMetadata>();\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tlet countingInput = false;\n\t\t\tlet countedInput: { request: ProviderRequestRepresentation; tokens: number } | undefined;\n\t\t\tconst measure = (request: ProviderRequestRepresentation) => {\n\t\t\t\tconst same =\n\t\t\t\t\tcountedInput &&\n\t\t\t\t\t!request.retainedPrefix &&\n\t\t\t\t\tcountedInput.request.api === request.api &&\n\t\t\t\t\tcountedInput.request.provider === request.provider &&\n\t\t\t\t\tcountedInput.request.url === request.url &&\n\t\t\t\t\tcountedInput.request.body === request.body;\n\t\t\t\treturn budget?.measure(\n\t\t\t\t\trequest,\n\t\t\t\t\tsame\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tinputTokens: countedInput!.tokens,\n\t\t\t\t\t\t\t\tmethod: \"openai-responses-input-count\",\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst finalizeMeasurement = async (\n\t\t\t\trequest: ProviderRequestRepresentation,\n\t\t\t\tcountInput?: ProviderInputTokenCounter,\n\t\t\t\tpreparedAssessment?: RequestTokenAssessment,\n\t\t\t) => {\n\t\t\t\tlet assessment = countedInput ? measure(request) : (preparedAssessment ?? measure(request));\n\t\t\t\tconst estimated = assessment?.estimatedInputTokens;\n\t\t\t\tconst available = assessment?.availableInputTokens;\n\t\t\t\tif (\n\t\t\t\t\tcountInput &&\n\t\t\t\t\tassessment?.counter === \"openai-o200k-base-estimate\" &&\n\t\t\t\t\tassessment.status !== \"unknown\" &&\n\t\t\t\t\testimated !== null &&\n\t\t\t\t\testimated !== undefined &&\n\t\t\t\t\tavailable !== null &&\n\t\t\t\t\tavailable !== undefined &&\n\t\t\t\t\tavailable > 0 &&\n\t\t\t\t\testimated >= available * 0.9 &&\n\t\t\t\t\testimated <= available * 1.1\n\t\t\t\t) {\n\t\t\t\t\tthis.assertAdmission();\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tcountingInput = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst tokens = await countInput(request);\n\t\t\t\t\t\tcountedInput = { request: Object.freeze({ ...request }), tokens };\n\t\t\t\t\t\tassessment = measure(request);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcountingInput = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn assessment;\n\t\t\t};\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tconst requiredEpoch = boundary?.requiresEpoch === true;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare || requiredPublic || requiredEpoch) &&\n\t\t\t\tboundary &&\n\t\t\t\tmatchesRequestView(boundary, source, context);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tconst responsesMessageIds =\n\t\t\t\tcanSelect &&\n\t\t\t\t!boundary.fixedPrepare &&\n\t\t\t\t(model.api === \"openai-responses\" || model.api === \"openai-codex-responses\")\n\t\t\t\t\t? boundary.providerMessageIndices.map((index) => {\n\t\t\t\t\t\t\tconst unit = boundary.units[index];\n\t\t\t\t\t\t\tconst key = JSON.stringify([\n\t\t\t\t\t\t\t\tboundary.source.sessionId,\n\t\t\t\t\t\t\t\tboundary.source.sessionFile,\n\t\t\t\t\t\t\t\tunit.id,\n\t\t\t\t\t\t\t\tunit.sourceRevision,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tlet id = this.work.responsesMessageIds.get(key);\n\t\t\t\t\t\t\tif (id === undefined) {\n\t\t\t\t\t\t\t\tid = this.work.responsesMessageIds.size;\n\t\t\t\t\t\t\t\tthis.work.responsesMessageIds.set(key, id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn id;\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(responsesMessageIds ? { responsesMessageIds } : {}),\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\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...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(budget || canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection, countInput) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (!canSelect) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// An unmapped native body must pass the existing final boundary\n\t\t\t\t\t\t\t\t\t// validator before any provider call, including an input count.\n\t\t\t\t\t\t\t\t\tif (!projection) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\t...(responsesMessageIds ? { responseItemIdentity: this.work.responsesIdentity } : {}),\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t\t(request, assessment) => finalizeMeasurement(request, countInput, assessment),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tconst inputCount = descriptor.kind === \"input-count\";\n\t\t\t\t\tif (inputCount && !countingInput) throw new Error(\"Input count requires its owned prepared request\");\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tif (!inputCount && requiredEpoch && !selectedContextEpoch)\n\t\t\t\t\t\tthrow new Error(\"Context transition requires an acknowledged native epoch\");\n\t\t\t\t\tif (!inputCount && requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (!inputCount && measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch =\n\t\t\t\t\t\t!inputCount && selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst attemptMetadata: NativeRequestMetadata = inputCount\n\t\t\t\t\t\t? { ...metadata, purpose: \"native-control\", purposeDetail: \"input-token-count\" }\n\t\t\t\t\t\t: metadata;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...attemptMetadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (inputCount) inputCountAttempts.set(attemptId, attemptMetadata);\n\t\t\t\t\telse admittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst inputCountMetadata = inputCountAttempts.get(receipt.attemptId);\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...(inputCountMetadata ?? metadata),\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (!inputCountMetadata) parentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}
1
+ {"version":3,"file":"inference-coordinator.d.ts","sourceRoot":"","sources":["../../src/core/inference-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AACnG,OAAO,EACN,KAAK,GAAG,EACR,KAAK,gBAAgB,EAErB,KAAK,OAAO,EAKZ,KAAK,KAAK,EAMV,KAAK,yBAAyB,EAC9B,KAAK,mBAAmB,EAExB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EACX,gBAAgB,EAEhB,+BAA+B,EAC/B,wCAAwC,EACxC,gCAAgC,EAGhC,eAAe,EACf,cAAc,EAGd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAKN,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,EAC5B,KAAK,mBAAmB,EAExB,MAAM,6BAA6B,CAAC;AAErC,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAQzE,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,OAAO,EAAE,cAAc,CAAC;IACjC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;IAC9B,QAAQ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,CAC3C,QAAQ,EAAE,QAAQ,EAClB,OAAO,EAAE,uBAAuB,GAC9B,yBAAyB,CAM3B","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { AgentMessage, AgentOwnedStreamFn, StreamFn } from \"@ponythewhite/base-context-agent\";\nimport {\n\ttype Api,\n\ttype AssistantMessage,\n\tassertBuiltInAttemptSupport,\n\ttype Context,\n\tcompleteSimple,\n\tinvokeRequestMeasurement,\n\tisLocalFauxStream,\n\tisTransientProviderFailure,\n\ttype Model,\n\ttype ProviderAttemptObserver,\n\ttype ProviderInputTokenCounter,\n\ttype ProviderRequestRepresentation,\n\ttype RequestTokenAssessment,\n\tRequestTokenBudget,\n\ttype RequestTokenBudgetOptions,\n\ttype SimpleStreamOptions,\n\tstreamSimple,\n} from \"@ponythewhite/base-context-ai\";\nimport type { AuthSourceToken } from \"./auth-storage.js\";\nimport type {\n\tBoundRequestSink,\n\tContextEpochEntryRef,\n\tNativeBranchRequestOutputWriter,\n\tNativeCompactionRequestOutputAssociation,\n\tNativePlannerRequestOutputWriter,\n\tNativeRequestMetadata,\n\tNativeRequestOutputWriter,\n\tRequestOwnerRef,\n\tRequestPurpose,\n\tResolvedModelContract,\n\tSourceSnapshotRef,\n} from \"./request-events.js\";\nimport {\n\ttype CapturedRequestViewBoundary,\n\tcaptureRequestViewBoundary,\n\tmatchesRequestView,\n\tprepareFixedRequestView,\n\ttype RequestViewCommit,\n\ttype RequestViewFixedPrepare,\n\ttype RequestViewValidate,\n\tselectRequestView,\n} from \"./request-view-selection.js\";\nimport { hashTurnBody, MODEL_REQUEST_ID_HEADER, unwrapSemanticEdgeStreamFn } from \"./semantic-edges.js\";\nimport type { SessionHistoryReadView } from \"./session-history-index.js\";\nimport {\n\tcaptureNativeBranchOutputSource,\n\tcaptureNativeCompactionOutputSource,\n\tcaptureNativePlannerOutputSource,\n\tcaptureNativeRequestOutputSource,\n} from \"./session-manager.js\";\n\nexport interface InferenceRequestOptions {\n\treadonly purpose: RequestPurpose;\n\treadonly purposeDetail?: string;\n\treadonly operationId?: string;\n\treadonly parentOperationId?: string;\n\treadonly semanticEdgeId?: string;\n}\n\nexport interface InferenceSettlement {\n\treadonly message: AssistantMessage;\n\treadonly operationId: string;\n\treadonly attemptIds: readonly string[];\n\t/** Reporting is not a guarantee about an opaque adapter's hidden retries. */\n\treadonly physicalCoverage: \"reported\" | \"unestablished\" | \"local-simulation\";\n}\n\n/** Private completion identity carries this actual source, never descriptive sink labels. */\nexport interface NativeCompactionOutputBinding {\n\treadonly sink: BoundRequestSink;\n\treadonly output: NativeCompactionRequestOutputAssociation;\n}\n\ninterface NativeBranchOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativeBranchRequestOutputWriter;\n}\n\ninterface NativePlannerOutputBinding {\n\treadonly owner: InferenceCoordinator;\n\treadonly write: NativePlannerRequestOutputWriter;\n}\n\nexport interface InferenceRun {\n\treadonly events: Awaited<ReturnType<StreamFn>>;\n\treadonly settled: Promise<InferenceSettlement>;\n}\n\nexport interface SessionRuntimeServices {\n\treadonly requests: InferenceCoordinator;\n}\n\ninterface ProviderRecoveryPolicy {\n\tenabled: boolean;\n\tbaseDelayMs: number;\n\tmaxRetryDelayMs: number;\n}\n\ninterface SinkUse {\n\treadonly sink: BoundRequestSink;\n\tactiveUsers: number;\n\tcaptures: number;\n\trelease?: Promise<void>;\n}\n\ninterface BoundOperation {\n\treadonly binding: SinkUse;\n\treadonly owner: Omit<RequestOwnerRef, \"sessionId\">;\n\treadonly metadata: Omit<NativeRequestMetadata, \"source\" | \"owner\" | \"contextEpoch\">;\n}\n\nconst REQUEST_STREAM_BINDING = Symbol(\"base-context.request-stream-binding\");\n/** Internal AgentSession built-in compaction entry, not a public inference option. */\nexport const captureNativeCompactionRequests = Symbol(\"base-context.native-compaction-requests\");\n/** Internal AgentSession built-in branch-summary invocation, never inherited by generic capture. */\nexport const captureNativeBranchRequests = Symbol(\"base-context.native-branch-requests\");\n/** Internal native AgentSession planner capture, never inherited by generic capture. */\nexport const captureNativePlannerRequests = Symbol(\"base-context.native-planner-requests\");\n/** Internal native AgentSession reviewer invocation. */\nexport const captureNativeReviewerRequests = Symbol(\"base-context.native-reviewer-requests\");\ninterface StreamBinding {\n\treadonly coordinator: InferenceCoordinator;\n\treadonly inner: StreamFn;\n}\ntype BoundStreamFn = AgentOwnedStreamFn & { [REQUEST_STREAM_BINDING]?: StreamBinding };\n\nfunction modelContract(model: Model<Api>): ResolvedModelContract {\n\treturn {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tprofile: { id: \"native-default\", status: \"unvalidated\" },\n\t\tpricing: {\n\t\t\tstatus: \"unvalidated\",\n\t\t\tcurrency: \"USD\",\n\t\t\tunit: \"million-tokens\",\n\t\t\tcatalogRates: {\n\t\t\t\tinput: model.cost.input,\n\t\t\t\toutput: model.cost.output,\n\t\t\t\tcacheRead: model.cost.cacheRead,\n\t\t\t\tcacheWrite: model.cost.cacheWrite,\n\t\t\t},\n\t\t},\n\t};\n}\n\nconst nativeStreamFunctions = new WeakSet<StreamFn>();\nconst nativeAuthSources = new WeakMap<AssistantMessage, AuthSourceToken>();\n\n/** Consume the credential source resolved for this exact native request. Never persisted or sent to providers. */\nexport function takeNativeInferenceAuthSource(message: AssistantMessage): AuthSourceToken | undefined {\n\tconst source = nativeAuthSources.get(message);\n\tnativeAuthSources.delete(message);\n\treturn source;\n}\n\n/** Internal SDK auth/options resolver; transport stays the known instrumented AI dispatcher. */\nexport function createNativeInferenceStream(\n\tresolveOptions: (\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t) => Promise<SimpleStreamOptions & { authSourceToken?: AuthSourceToken }>,\n): StreamFn {\n\tconst dispatch: StreamFn = async (model, context, options) => {\n\t\tconst { authSourceToken, ...resolved } = await resolveOptions(model, context, options);\n\t\tconst events = streamSimple(model, context, {\n\t\t\t...resolved,\n\t\t\tsignal: options?.signal,\n\t\t\tattempts: options?.attempts,\n\t\t\trequireProviderAttempts: true,\n\t\t});\n\t\tif (authSourceToken) {\n\t\t\tconst source = { ...authSourceToken };\n\t\t\tconst result = events.result().then((message) => {\n\t\t\t\tnativeAuthSources.set(message, source);\n\t\t\t\treturn message;\n\t\t\t});\n\t\t\tevents.result = () => result;\n\t\t}\n\t\treturn events;\n\t};\n\tnativeStreamFunctions.add(dispatch);\n\treturn dispatch;\n}\n\n/** Routes physical observations to the source writer. It owns no receipt store. */\nexport class InferenceCoordinator {\n\t#nativeCompactionOutput = false;\n\t#nativeBranchOutput = false;\n\t#nativePlannerOutput = false;\n\t#auxiliaryAttempts?: { remaining: number };\n\tprivate retryTurn = false;\n\tprivate requestViewBoundary?: CapturedRequestViewBoundary;\n\tprivate active = new Set<Promise<void>>();\n\tprivate capturedSink?: SinkUse;\n\tprivate captureReserved = false;\n\tprivate finishCapturePending?: () => void;\n\tprivate disposed = false;\n\tprivate disposal?: Promise<void>;\n\tprivate work = {\n\t\tpending: new Set<Promise<void>>(),\n\t\tresponsesMessageIds: new Map<string, number>(),\n\t\tresponsesIdentity: randomUUID(),\n\t\tsinks: new WeakMap<BoundRequestSink, SinkUse>(),\n\t\tmainOutputs: new WeakMap<AssistantMessage, NativeRequestOutputWriter>(),\n\t\tcompactionSettlements: new WeakMap<InferenceSettlement, NativeCompactionOutputBinding>(),\n\t\tcompactionCompletions: new WeakMap<Promise<AssistantMessage>, NativeCompactionOutputBinding>(),\n\t\tbranchSettlements: new WeakMap<InferenceSettlement, NativeBranchOutputBinding>(),\n\t\tbranchCompletions: new WeakMap<Promise<AssistantMessage>, NativeBranchOutputBinding>(),\n\t\tplannerSettlements: new WeakMap<InferenceSettlement, NativePlannerOutputBinding>(),\n\t\tplannerCompletions: new WeakMap<Promise<AssistantMessage>, NativePlannerOutputBinding>(),\n\t\tlisteners: new Set<() => void>(),\n\t\tadmissionOpen: true,\n\t\tcancellation: new AbortController(),\n\t\tbudget: undefined as RequestTokenBudget | undefined,\n\t\tbudgetMode: undefined as RequestTokenBudgetOptions[\"mode\"] | undefined,\n\t\tproviderRecoveryPolicy: undefined as (() => ProviderRecoveryPolicy) | undefined,\n\t};\n\n\tsetProviderRecoveryPolicy(policy: () => ProviderRecoveryPolicy): void {\n\t\tthis.work.providerRecoveryPolicy = policy;\n\t}\n\n\tget hasPending(): boolean {\n\t\treturn this.work.pending.size > 0;\n\t}\n\tget pendingCount(): number {\n\t\treturn this.work.pending.size;\n\t}\n\n\tonActivityChange(listener: () => void): () => void {\n\t\tthis.work.listeners.add(listener);\n\t\treturn () => this.work.listeners.delete(listener);\n\t}\n\n\tprivate notifyActivity(): void {\n\t\t// Observers can wake an existing owner, but cannot own request settlement.\n\t\tfor (const listener of this.work.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener();\n\t\t\t} catch {\n\t\t\t\t/* Notification is not execution. */\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Consume only this owner's real returned object. Labels and replacement messages remain unassociated. */\n\tappendMainOutput(message: AssistantMessage, owner: object): Promise<string | undefined> | undefined {\n\t\tconst write = this.work.mainOutputs.get(message);\n\t\tthis.work.mainOutputs.delete(message);\n\t\treturn write?.(owner, message);\n\t}\n\n\t/** Opt this native invocation into output association; ordinary captures do not inherit that authority. */\n\t[captureNativeCompactionRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#nativeCompactionOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 4 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeBranchRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativeBranchOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakeBranchOutput(completion: Promise<AssistantMessage>): NativeBranchRequestOutputWriter | undefined {\n\t\tconst binding = this.work.branchCompletions.get(completion);\n\t\tthis.work.branchCompletions.delete(completion);\n\t\tif (!binding || !this.#nativeBranchOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t[captureNativePlannerRequests](sink: BoundRequestSink): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this, sink);\n\t\tcaptured.#nativePlannerOutput = true;\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\t[captureNativeReviewerRequests](): InferenceCoordinator {\n\t\tconst captured = InferenceCoordinator.prototype.capture.call(this);\n\t\tcaptured.#auxiliaryAttempts ??= { remaining: 2 };\n\t\treturn captured;\n\t}\n\n\ttakePlannerOutput(completion: Promise<AssistantMessage>): NativePlannerRequestOutputWriter | undefined {\n\t\tconst binding = this.work.plannerCompletions.get(completion);\n\t\tthis.work.plannerCompletions.delete(completion);\n\t\tif (!binding || !this.#nativePlannerOutput || binding.owner !== this) return undefined;\n\t\treturn binding.write;\n\t}\n\n\t/** Only the original completion promise and captured source can supply a projected-output link. */\n\ttakeCompactionOutput(completion: Promise<AssistantMessage>): NativeCompactionOutputBinding | undefined {\n\t\tconst binding = this.work.compactionCompletions.get(completion);\n\t\tthis.work.compactionCompletions.delete(completion);\n\t\treturn binding?.sink === this.capturedSink?.sink ? binding : undefined;\n\t}\n\n\t/** Owner teardown stops new sends, but never suppresses an admitted request's settlement. */\n\tstopAdmission(): void {\n\t\tthis.work.admissionOpen = false;\n\t\tthis.work.cancellation.abort();\n\t\tthis.notifyActivity();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (this.work.pending.size > 0) await Promise.all([...this.work.pending]);\n\t}\n\n\tprepareTurnRetry(): void {\n\t\tthis.retryTurn = true;\n\t}\n\tclearTurnRetry(): void {\n\t\tthis.retryTurn = false;\n\t}\n\n\tconstructor(\n\t\tprivate readonly bindSink: () => BoundRequestSink,\n\t\tprivate readonly owner: () => Omit<RequestOwnerRef, \"sessionId\"> = () => ({}),\n\t\trequestTokenBudget?: RequestTokenBudgetOptions,\n\t) {\n\t\tif (requestTokenBudget) {\n\t\t\tthis.work.budget = new RequestTokenBudget(requestTokenBudget);\n\t\t\tthis.work.budgetMode = requestTokenBudget.mode;\n\t\t}\n\t}\n\n\t/** Copy the configured policy, not this owner's learned request observations. */\n\tgetRequestTokenBudgetOptions(): RequestTokenBudgetOptions | undefined {\n\t\treturn this.work.budget?.getOptions();\n\t}\n\n\tprivate assertAdmission(): void {\n\t\tif (this.disposed || !this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t}\n\n\tprivate sinkUse(sink: BoundRequestSink): SinkUse {\n\t\tlet binding = this.work.sinks.get(sink);\n\t\tif (!binding) {\n\t\t\tbinding = { sink, activeUsers: 0, captures: 0 };\n\t\t\tthis.work.sinks.set(sink, binding);\n\t\t}\n\t\treturn binding;\n\t}\n\n\tprivate releaseCapture(): void {\n\t\tif (this.captureReserved && this.capturedSink) {\n\t\t\tthis.captureReserved = false;\n\t\t\tthis.capturedSink.captures--;\n\t\t}\n\t}\n\n\t/** Capture an auxiliary operation's subject before asynchronous auth or UI work. */\n\tcapture(sink?: BoundRequestSink): InferenceCoordinator {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst binding = this.sinkUse(sink ?? this.bindSink());\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tconst captured = new InferenceCoordinator(\n\t\t\t() => binding.sink,\n\t\t\t() => owner,\n\t\t);\n\t\tcaptured.work = this.work;\n\t\t// Nested captures share the invocation's allowance, not its native output authority.\n\t\tcaptured.#auxiliaryAttempts = this.#auxiliaryAttempts;\n\t\tcaptured.capturedSink = binding;\n\t\tcaptured.captureReserved = true;\n\t\tlet release!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tcaptured.finishCapturePending = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tcaptured.finishCapturePending = undefined;\n\t\t\trelease();\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tthis.notifyActivity();\n\t\treturn captured;\n\t}\n\n\t/** Explicit Root-owned epoch boundary, on this same captured MAIN source only. */\n\tbindRequestViewBoundary(\n\t\tmessages: readonly AgentMessage[],\n\t\tcommit: RequestViewCommit,\n\t\tvalidate?: RequestViewValidate,\n\t\tfixedPrepare?: RequestViewFixedPrepare,\n\t\tisSourceCurrent?: () => boolean,\n\t): void {\n\t\tthis.assertAdmission();\n\t\tif (!this.capturedSink) throw new Error(\"Request view boundary requires a captured inference owner\");\n\t\tif (this.requestViewBoundary) throw new Error(\"Request view boundary is already bound\");\n\t\tthis.requestViewBoundary = captureRequestViewBoundary(messages, commit, validate, fixedPrepare, isSourceCurrent);\n\t}\n\n\t/** Read through an explicit capture, never by recapturing the mutable current session. */\n\tasync readHistory<T>(read: (view: SessionHistoryReadView) => Promise<T>): Promise<T> {\n\t\tthis.assertAdmission();\n\t\tconst sink = this.capturedSink?.sink;\n\t\tif (!sink?.readHistory) throw new Error(\"Captured canonical history is unavailable\");\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\ttry {\n\t\t\treturn await sink.readHistory(read);\n\t\t} finally {\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tfinish();\n\t\t\tthis.notifyActivity();\n\t\t}\n\t}\n\n\t/** Release an unused capture, or join this capture's admitted requests. */\n\tdispose(): Promise<void> {\n\t\tthis.disposed = true;\n\t\tthis.disposal ??= (async () => {\n\t\t\tthis.releaseCapture();\n\t\t\ttry {\n\t\t\t\tawait Promise.all([...this.active]);\n\t\t\t\tif (this.capturedSink) await this.finishSink(this.capturedSink, [], false, []);\n\t\t\t} finally {\n\t\t\t\tthis.finishCapturePending?.();\n\t\t\t}\n\t\t})();\n\t\treturn this.disposal;\n\t}\n\n\tprivate bindOperation(model: Model<Api>, request: InferenceRequestOptions, operationId: string): BoundOperation {\n\t\tthis.assertAdmission();\n\t\tconst owner = Object.freeze({ ...this.owner() });\n\t\tconst metadata = Object.freeze({\n\t\t\toperationId,\n\t\t\tparentOperationId: request.parentOperationId,\n\t\t\tsemanticEdgeId: request.semanticEdgeId,\n\t\t\tpurpose: request.purpose,\n\t\t\tpurposeDetail: request.purposeDetail,\n\t\t\tmodelContract: modelContract(model),\n\t\t});\n\t\treturn { binding: this.sinkUse(this.bindSink()), owner, metadata };\n\t}\n\n\tprivate async finishSink(\n\t\tbinding: SinkUse,\n\t\twrites: readonly Promise<void>[],\n\t\tactiveUser: boolean,\n\t\tfailures: unknown[],\n\t): Promise<void> {\n\t\tconst results = await Promise.allSettled([binding.sink.source, ...writes]);\n\t\tfor (const result of results) {\n\t\t\tif (result.status === \"rejected\") failures.push(result.reason);\n\t\t}\n\t\tif (activeUser) binding.activeUsers--;\n\t\ttry {\n\t\t\tif (binding.activeUsers === 0 && binding.captures === 0) {\n\t\t\t\tbinding.release ??= binding.sink.release();\n\t\t\t\tawait binding.release;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailures.push(error);\n\t\t}\n\t\tconst distinct = [...new Set(failures)];\n\t\tif (distinct.length === 1) throw distinct[0];\n\t\tif (distinct.length > 1) throw new AggregateError(distinct, \"Inference request or source cleanup failed\");\n\t}\n\n\t/** Hold one logical operation through settled sends and recovery delays. */\n\tprivate retainWork(binding: SinkUse): (failures?: unknown[]) => Promise<void> {\n\t\tthis.assertAdmission();\n\t\tbinding.sink.retain();\n\t\tbinding.release = undefined;\n\t\tbinding.captures++;\n\t\tlet finish!: () => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\tfinish = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tlet release: Promise<void> | undefined;\n\t\treturn (failures = []) => {\n\t\t\trelease ??= (async () => {\n\t\t\t\tbinding.captures--;\n\t\t\t\ttry {\n\t\t\t\t\tawait this.finishSink(binding, [], false, failures);\n\t\t\t\t} finally {\n\t\t\t\t\tthis.active.delete(pending);\n\t\t\t\t\tthis.work.pending.delete(pending);\n\t\t\t\t\tfinish();\n\t\t\t\t\tthis.notifyActivity();\n\t\t\t\t}\n\t\t\t})();\n\t\t\treturn release;\n\t\t};\n\t}\n\n\tprivate providerRecoveryWait(): (message: AssistantMessage, signal?: AbortSignal) => Promise<boolean> {\n\t\tlet nextDelayMs: number | undefined;\n\t\treturn async (message, callerSignal) => {\n\t\t\tconst policy = this.work.providerRecoveryPolicy?.();\n\t\t\tif (!policy?.enabled || !isTransientProviderFailure(message)) return false;\n\t\t\tthis.assertAdmission();\n\t\t\tconst signal = callerSignal\n\t\t\t\t? AbortSignal.any([callerSignal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tsignal.throwIfAborted();\n\t\t\tconst delayMs = Math.min(nextDelayMs ?? policy.baseDelayMs, policy.maxRetryDelayMs);\n\t\t\tawait delay(delayMs, undefined, { signal });\n\t\t\tsignal.throwIfAborted();\n\t\t\tthis.assertAdmission();\n\t\t\tnextDelayMs = Math.min(delayMs * 2, policy.maxRetryDelayMs);\n\t\t\treturn this.work.providerRecoveryPolicy?.().enabled === true;\n\t\t};\n\t}\n\n\tprivate async execute(\n\t\toperation: BoundOperation,\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\tsend: StreamFn,\n\t\tbindMainOutput = false,\n\t): Promise<InferenceRun> {\n\t\tconst outputSource = bindMainOutput ? captureNativeRequestOutputSource(operation.binding.sink) : undefined;\n\t\tconst part =\n\t\t\toperation.metadata.purpose === \"summary\"\n\t\t\t\t? operation.metadata.purposeDetail === \"compaction\"\n\t\t\t\t\t? \"history\"\n\t\t\t\t\t: operation.metadata.purposeDetail === \"compaction-turn-prefix\"\n\t\t\t\t\t\t? \"turn-prefix\"\n\t\t\t\t\t\t: undefined\n\t\t\t\t: undefined;\n\t\tconst compactionSource =\n\t\t\tthis.#nativeCompactionOutput && part && this.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeCompactionOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst branchSource =\n\t\t\tthis.#nativeBranchOutput &&\n\t\t\toperation.metadata.purpose === \"summary\" &&\n\t\t\toperation.metadata.purposeDetail === \"branch\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativeBranchOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tconst plannerSource =\n\t\t\tthis.#nativePlannerOutput &&\n\t\t\toperation.metadata.purpose === \"refine\" &&\n\t\t\toperation.metadata.purposeDetail === \"plan\" &&\n\t\t\tthis.capturedSink?.sink === operation.binding.sink\n\t\t\t\t? captureNativePlannerOutputSource(operation.binding.sink)\n\t\t\t\t: undefined;\n\t\tlet outputSourceRef: SourceSnapshotRef | undefined;\n\t\tlet release!: (completion?: PromiseLike<void>) => void;\n\t\tconst pending = new Promise<void>((resolve) => {\n\t\t\trelease = resolve;\n\t\t});\n\t\tthis.work.pending.add(pending);\n\t\tthis.active.add(pending);\n\t\tthis.notifyActivity();\n\t\tconst finish = () => {\n\t\t\tthis.work.pending.delete(pending);\n\t\t\tthis.active.delete(pending);\n\t\t\tthis.notifyActivity();\n\t\t};\n\t\tconst admittedAttempts: Array<{ attemptId: string; contextEpoch?: ContextEpochEntryRef }> = [];\n\t\tconst inputCountAttempts = new Map<string, NativeRequestMetadata>();\n\t\tconst receiptWrites: Promise<void>[] = [];\n\t\tlet activeUser = false;\n\t\tlet localSimulation = false;\n\t\tlet budgetFailure: unknown;\n\t\tconst settle = async (result: Promise<AssistantMessage>): Promise<InferenceSettlement> => {\n\t\t\tconst failures: unknown[] = [];\n\t\t\tlet message: AssistantMessage | undefined;\n\t\t\ttry {\n\t\t\t\tmessage = await result;\n\t\t\t} catch (error) {\n\t\t\t\tfailures.push(error);\n\t\t\t}\n\t\t\tif (budgetFailure !== undefined && !failures.includes(budgetFailure)) failures.push(budgetFailure);\n\t\t\tawait this.finishSink(operation.binding, receiptWrites, activeUser, failures);\n\t\t\tif (message && outputSource && outputSourceRef) {\n\t\t\t\tconst write = outputSource({\n\t\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.mainOutputs.set(message, write);\n\t\t\t}\n\t\t\tconst settlement: InferenceSettlement = {\n\t\t\t\tmessage: message!,\n\t\t\t\toperationId: operation.metadata.operationId,\n\t\t\t\tattemptIds: admittedAttempts.map(({ attemptId }) => attemptId),\n\t\t\t\tphysicalCoverage: admittedAttempts.length\n\t\t\t\t\t? \"reported\"\n\t\t\t\t\t: localSimulation\n\t\t\t\t\t\t? \"local-simulation\"\n\t\t\t\t\t\t: \"unestablished\",\n\t\t\t};\n\t\t\tif (part && compactionSource && outputSourceRef) {\n\t\t\t\tconst output = compactionSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (output)\n\t\t\t\t\tthis.work.compactionSettlements.set(settlement, {\n\t\t\t\t\t\tsink: operation.binding.sink,\n\t\t\t\t\t\toutput: { ...output, part },\n\t\t\t\t\t});\n\t\t\t}\n\t\t\tif (branchSource && outputSourceRef) {\n\t\t\t\tconst write = branchSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.branchSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\tif (plannerSource && outputSourceRef) {\n\t\t\t\tconst write = plannerSource({\n\t\t\t\t\toperationId: settlement.operationId,\n\t\t\t\t\tattemptIds: settlement.attemptIds,\n\t\t\t\t\tsource: outputSourceRef,\n\t\t\t\t});\n\t\t\t\tif (write) this.work.plannerSettlements.set(settlement, { owner: this, write });\n\t\t\t}\n\t\t\treturn settlement;\n\t\t};\n\t\ttry {\n\t\t\tthis.assertAdmission();\n\t\t\toperation.binding.sink.retain();\n\t\t\toperation.binding.release = undefined;\n\t\t\toperation.binding.activeUsers++;\n\t\t\tactiveUser = true;\n\t\t\tthis.releaseCapture();\n\t\t\tthis.finishCapturePending?.();\n\t\t\t// Capture the opted-in budgeted invocation before source/auth waits. Callbacks and signals stay live handles.\n\t\t\tif (this.work.budget || (this.requestViewBoundary && operation.metadata.purpose === \"main\")) {\n\t\t\t\tmodel = structuredClone(model);\n\t\t\t\t// Agent tool objects also carry live executors. Snapshot only the native Tool definition.\n\t\t\t\tcontext = structuredClone({\n\t\t\t\t\t...context,\n\t\t\t\t\t...(context.tools\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\ttools: context.tools.map(({ name, description, parameters }) => ({\n\t\t\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t\t\t\tdescription,\n\t\t\t\t\t\t\t\t\tparameters,\n\t\t\t\t\t\t\t\t})),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t});\n\t\t\t\toptions = options\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...options,\n\t\t\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tconst source = Object.freeze({ ...(await operation.binding.sink.source) });\n\t\t\toutputSourceRef = source;\n\t\t\tconst metadata: NativeRequestMetadata = {\n\t\t\t\t...operation.metadata,\n\t\t\t\tsource,\n\t\t\t\towner: Object.freeze({ ...operation.owner, sessionId: source.sessionId }),\n\t\t\t};\n\t\t\tif (send !== streamSimple && !nativeStreamFunctions.has(send)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Native inference cannot admit a custom or proxy StreamFn with unestablished physical-attempt coverage. Use the SDK's instrumented built-in API route instead.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tassertBuiltInAttemptSupport(model.api);\n\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\tconst parentBudget = this.work.budget;\n\t\t\tconst boundary = operation.metadata.purpose === \"main\" ? this.requestViewBoundary : undefined;\n\t\t\tconst budget = boundary ? parentBudget?.capture() : parentBudget;\n\t\t\tlet measuredForAdmission = false;\n\t\t\tlet countingInput = false;\n\t\t\tlet countedInput: { request: ProviderRequestRepresentation; tokens: number } | undefined;\n\t\t\tconst measure = (request: ProviderRequestRepresentation) => {\n\t\t\t\tconst same =\n\t\t\t\t\tcountedInput &&\n\t\t\t\t\t!request.retainedPrefix &&\n\t\t\t\t\tcountedInput.request.api === request.api &&\n\t\t\t\t\tcountedInput.request.provider === request.provider &&\n\t\t\t\t\tcountedInput.request.url === request.url &&\n\t\t\t\t\tcountedInput.request.body === request.body;\n\t\t\t\treturn budget?.measure(\n\t\t\t\t\trequest,\n\t\t\t\t\tsame\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tinputTokens: countedInput!.tokens,\n\t\t\t\t\t\t\t\tmethod: \"openai-responses-input-count\",\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: undefined,\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst finalizeMeasurement = async (\n\t\t\t\trequest: ProviderRequestRepresentation,\n\t\t\t\tcountInput?: ProviderInputTokenCounter,\n\t\t\t\tpreparedAssessment?: RequestTokenAssessment,\n\t\t\t) => {\n\t\t\t\tlet assessment = countedInput ? measure(request) : (preparedAssessment ?? measure(request));\n\t\t\t\tconst estimated = assessment?.estimatedInputTokens;\n\t\t\t\tconst available = assessment?.availableInputTokens;\n\t\t\t\tif (\n\t\t\t\t\tcountInput &&\n\t\t\t\t\tassessment?.counter === \"openai-o200k-base-estimate\" &&\n\t\t\t\t\tassessment.status !== \"unknown\" &&\n\t\t\t\t\testimated !== null &&\n\t\t\t\t\testimated !== undefined &&\n\t\t\t\t\tavailable !== null &&\n\t\t\t\t\tavailable !== undefined &&\n\t\t\t\t\tavailable > 0 &&\n\t\t\t\t\testimated >= available * 0.9 &&\n\t\t\t\t\testimated <= available * 1.1\n\t\t\t\t) {\n\t\t\t\t\tthis.assertAdmission();\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tcountingInput = true;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst tokens = await countInput(request);\n\t\t\t\t\t\tcountedInput = { request: Object.freeze({ ...request }), tokens };\n\t\t\t\t\t\tassessment = measure(request);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcountingInput = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn assessment;\n\t\t\t};\n\t\t\tconst measureRequest: ProviderAttemptObserver[\"measureRequest\"] =\n\t\t\t\tbudget || boundary?.validate\n\t\t\t\t\t? (representation) => {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tconst assessment = measure(representation);\n\t\t\t\t\t\t\t\tboundary?.validate?.(representation, assessment);\n\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\tmeasuredForAdmission = true;\n\t\t\t\t\t\t\t\treturn assessment;\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined;\n\t\t\tconst requiredPublic = Boolean(boundary?.pendingPublicMessageGroups?.length);\n\t\t\tconst requiredEpoch = boundary?.requiresEpoch === true;\n\t\t\tconst canSelect =\n\t\t\t\t(budget || boundary?.fixedPrepare || requiredPublic || requiredEpoch) &&\n\t\t\t\tboundary &&\n\t\t\t\tmatchesRequestView(boundary, source, context);\n\t\t\tif (requiredPublic && (!canSelect || boundary?.fixedPrepare))\n\t\t\t\tthrow new Error(\"Tool continuation requires a selectable native public request boundary\");\n\t\t\tconst responsesMessageIds =\n\t\t\t\tcanSelect &&\n\t\t\t\t!boundary.fixedPrepare &&\n\t\t\t\t(model.api === \"openai-responses\" || model.api === \"openai-codex-responses\")\n\t\t\t\t\t? boundary.providerMessageIndices.map((index) => {\n\t\t\t\t\t\t\tconst unit = boundary.units[index];\n\t\t\t\t\t\t\tconst key = JSON.stringify([\n\t\t\t\t\t\t\t\tboundary.source.sessionId,\n\t\t\t\t\t\t\t\tboundary.source.sessionFile,\n\t\t\t\t\t\t\t\tunit.id,\n\t\t\t\t\t\t\t\tunit.sourceRevision,\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t\tlet id = this.work.responsesMessageIds.get(key);\n\t\t\t\t\t\t\tif (id === undefined) {\n\t\t\t\t\t\t\t\tid = this.work.responsesMessageIds.size;\n\t\t\t\t\t\t\t\tthis.work.responsesMessageIds.set(key, id);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn id;\n\t\t\t\t\t\t})\n\t\t\t\t\t: undefined;\n\t\t\tlet publicAccepted = false;\n\t\t\tlet selectedContextEpoch: ContextEpochEntryRef | undefined;\n\t\t\tconst attempts: ProviderAttemptObserver = {\n\t\t\t\t...(responsesMessageIds ? { responsesMessageIds } : {}),\n\t\t\t\t...(requiredPublic\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tpendingPublicMessageGroups: boundary!.providerPendingPublicMessageGroups!.map((group) => [\n\t\t\t\t\t\t\t\t...group,\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...(measureRequest ? { measureRequest } : {}),\n\t\t\t\t...(budget || canSelect\n\t\t\t\t\t? ({\n\t\t\t\t\t\t\tprepareRequest: async (representation, projection, countInput) => {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tselectedContextEpoch = undefined;\n\t\t\t\t\t\t\t\t\tpublicAccepted = false;\n\t\t\t\t\t\t\t\t\tif (JSON.parse(representation.body!).model !== model.id) return;\n\t\t\t\t\t\t\t\t\tif (!canSelect) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t// An unmapped native body must pass the existing final boundary\n\t\t\t\t\t\t\t\t\t// validator before any provider call, including an input count.\n\t\t\t\t\t\t\t\t\tif (!projection) return;\n\t\t\t\t\t\t\t\t\tif (boundary!.fixedPrepare) {\n\t\t\t\t\t\t\t\t\t\tconst assessment = await finalizeMeasurement(representation, countInput);\n\t\t\t\t\t\t\t\t\t\tif (budget && assessment) budget.assert(assessment);\n\t\t\t\t\t\t\t\t\t\tconst accepted = await prepareFixedRequestView(\n\t\t\t\t\t\t\t\t\t\t\tboundary!,\n\t\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\t\tassessment,\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\treturn await selectRequestView(\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t...boundary!,\n\t\t\t\t\t\t\t\t\t\t\t...(responsesMessageIds ? { responseItemIdentity: this.work.responsesIdentity } : {}),\n\t\t\t\t\t\t\t\t\t\t\tcommit: async (candidate) => {\n\t\t\t\t\t\t\t\t\t\t\t\tconst accepted = await boundary!.commit(candidate);\n\t\t\t\t\t\t\t\t\t\t\t\tif (accepted) selectedContextEpoch = Object.freeze({ ...accepted });\n\t\t\t\t\t\t\t\t\t\t\t\tpublicAccepted = Boolean(\n\t\t\t\t\t\t\t\t\t\t\t\t\taccepted &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.publicMessages &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcandidate.projection.publicWindow &&\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t!candidate.projection.pendingPublicMessageGroups?.length,\n\t\t\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t\t\t\treturn accepted || undefined;\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\trepresentation,\n\t\t\t\t\t\t\t\t\t\tprojection,\n\t\t\t\t\t\t\t\t\t\tbudget,\n\t\t\t\t\t\t\t\t\t\tthis.work.budgetMode === \"enforce\",\n\t\t\t\t\t\t\t\t\t\t(request, assessment) => finalizeMeasurement(request, countInput, assessment),\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\tbudgetFailure = error;\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t} satisfies Pick<ProviderAttemptObserver, \"prepareRequest\">)\n\t\t\t\t\t: {}),\n\t\t\t\tadmit: async (descriptor) => {\n\t\t\t\t\tconst inputCount = descriptor.kind === \"input-count\";\n\t\t\t\t\tif (inputCount && !countingInput) throw new Error(\"Input count requires its owned prepared request\");\n\t\t\t\t\toptions?.signal?.throwIfAborted();\n\t\t\t\t\tthis.work.cancellation.signal.throwIfAborted();\n\t\t\t\t\tif (!inputCount && requiredEpoch && !selectedContextEpoch)\n\t\t\t\t\t\tthrow new Error(\"Context transition requires an acknowledged native epoch\");\n\t\t\t\t\tif (!inputCount && requiredPublic && !publicAccepted)\n\t\t\t\t\t\tthrow new Error(\"Unaccepted tool continuation cannot enter native transport\");\n\t\t\t\t\tif (!this.work.admissionOpen) throw new Error(\"Inference owner is closing\");\n\t\t\t\t\t// An adapter without a serializer meter must not bypass an enforced budget.\n\t\t\t\t\tif (!inputCount && measureRequest && !descriptor.requestBudget && (budget || !measuredForAdmission)) {\n\t\t\t\t\t\tconst assessment = invokeRequestMeasurement(attempts, {\n\t\t\t\t\t\t\tapi: descriptor.api,\n\t\t\t\t\t\t\tprovider: descriptor.provider,\n\t\t\t\t\t\t\turl: \"\",\n\t\t\t\t\t\t\tbody: undefined,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (assessment) descriptor = { ...descriptor, requestBudget: assessment };\n\t\t\t\t\t}\n\t\t\t\t\tmeasuredForAdmission = false;\n\t\t\t\t\tif (this.#auxiliaryAttempts) {\n\t\t\t\t\t\tif (this.#auxiliaryAttempts.remaining === 0) {\n\t\t\t\t\t\t\tbudgetFailure ??= new Error(\"Native auxiliary operation attempt limit exhausted\");\n\t\t\t\t\t\t\tthrow budgetFailure;\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Reserve synchronously before persistence; failures and cancellation do not refund it.\n\t\t\t\t\t\tthis.#auxiliaryAttempts.remaining--;\n\t\t\t\t\t}\n\t\t\t\t\tconst attemptId = randomUUID();\n\t\t\t\t\tconst contextEpoch =\n\t\t\t\t\t\t!inputCount && selectedContextEpoch ? Object.freeze({ ...selectedContextEpoch }) : undefined;\n\t\t\t\t\tconst attemptMetadata: NativeRequestMetadata = inputCount\n\t\t\t\t\t\t? { ...metadata, purpose: \"native-control\", purposeDetail: \"input-token-count\" }\n\t\t\t\t\t\t: metadata;\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...attemptMetadata,\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_admitted\",\n\t\t\t\t\t\tattemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\tdescriptor,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (inputCount) inputCountAttempts.set(attemptId, attemptMetadata);\n\t\t\t\t\telse admittedAttempts.push({ attemptId, contextEpoch });\n\t\t\t\t\treturn attemptId;\n\t\t\t\t},\n\t\t\t\tsettle: async (receipt) => {\n\t\t\t\t\tconst contextEpoch = admittedAttempts.find(\n\t\t\t\t\t\t(attempt) => attempt.attemptId === receipt.attemptId,\n\t\t\t\t\t)?.contextEpoch;\n\t\t\t\t\tconst inputCountMetadata = inputCountAttempts.get(receipt.attemptId);\n\t\t\t\t\tconst write = operation.binding.sink.persist({\n\t\t\t\t\t\t...(inputCountMetadata ?? metadata),\n\t\t\t\t\t\t...(contextEpoch ? { contextEpoch } : {}),\n\t\t\t\t\t\ttype: \"attempt_settled\",\n\t\t\t\t\t\tattemptId: receipt.attemptId,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t\treceipt,\n\t\t\t\t\t});\n\t\t\t\t\treceiptWrites.push(write);\n\t\t\t\t\tawait write;\n\t\t\t\t\tif (!inputCountMetadata) parentBudget?.observe(receipt);\n\t\t\t\t},\n\t\t\t};\n\t\t\tconst signal = options?.signal\n\t\t\t\t? AbortSignal.any([options.signal, this.work.cancellation.signal])\n\t\t\t\t: this.work.cancellation.signal;\n\t\t\tconst events = await send(model, context, { ...options, signal, attempts, requireProviderAttempts: true });\n\t\t\tlocalSimulation = isLocalFauxStream(events);\n\t\t\tconst settled = settle(events.result());\n\t\t\tevents.result = async () => (await settled).message;\n\t\t\t// Idle tracking observes rejection; callers still receive it through settled/result().\n\t\t\trelease(settled.then(finish, finish));\n\t\t\treturn { events, settled };\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tawait settle(Promise.reject(error));\n\t\t\t} finally {\n\t\t\t\tfinish();\n\t\t\t\trelease();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tasync start(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceRun> {\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\treturn this.execute(\n\t\t\tthis.bindOperation(model, { ...request, semanticEdgeId }, operationId),\n\t\t\tmodel,\n\t\t\tcontext,\n\t\t\toptions,\n\t\t\tstreamSimple,\n\t\t);\n\t}\n\n\tprivate async completeWithProviderRecovery(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<InferenceSettlement> {\n\t\t// Retry the same request, not a caller's later mutable inputs. Keep callbacks/signals live.\n\t\tmodel = structuredClone(model);\n\t\tcontext = structuredClone({\n\t\t\t...context,\n\t\t\t...(context.tools\n\t\t\t\t? { tools: context.tools.map(({ name, description, parameters }) => ({ name, description, parameters })) }\n\t\t\t\t: {}),\n\t\t});\n\t\toptions = options\n\t\t\t? {\n\t\t\t\t\t...options,\n\t\t\t\t\theaders: options.headers ? { ...options.headers } : undefined,\n\t\t\t\t\tthinkingBudgets: options.thinkingBudgets ? { ...options.thinkingBudgets } : undefined,\n\t\t\t\t\tmetadata: options.metadata ? structuredClone(options.metadata) : undefined,\n\t\t\t\t}\n\t\t\t: undefined;\n\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\tconst operationId = request.operationId ?? semanticEdgeId ?? randomUUID();\n\t\tconst operation = this.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\tconst release = this.retainWork(operation.binding);\n\t\tconst recover = this.providerRecoveryWait();\n\t\tlet failure: unknown;\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst settlement = await (await this.execute(operation, model, context, options, streamSimple)).settled;\n\t\t\t\t// Rejected execution/settlement, including local allowance exhaustion, never reaches recovery.\n\t\t\t\tif (!(await recover(settlement.message, options?.signal))) return settlement;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = error;\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tawait release(failure === undefined ? [] : [failure]);\n\t\t}\n\t}\n\n\tcomplete(\n\t\tmodel: Model<Api>,\n\t\tcontext: Context,\n\t\toptions: SimpleStreamOptions | undefined,\n\t\trequest: InferenceRequestOptions,\n\t): Promise<AssistantMessage> {\n\t\tlet completion!: Promise<AssistantMessage>;\n\t\tcompletion = (async () => {\n\t\t\tconst settlement = this.work.providerRecoveryPolicy?.().enabled\n\t\t\t\t? await this.completeWithProviderRecovery(model, context, options, request)\n\t\t\t\t: await (await this.start(model, context, options, request)).settled;\n\t\t\tconst binding = this.work.compactionSettlements.get(settlement);\n\t\t\tthis.work.compactionSettlements.delete(settlement);\n\t\t\tif (binding) this.work.compactionCompletions.set(completion, binding);\n\t\t\tconst branchBinding = this.work.branchSettlements.get(settlement);\n\t\t\tthis.work.branchSettlements.delete(settlement);\n\t\t\tif (branchBinding) this.work.branchCompletions.set(completion, branchBinding);\n\t\t\tconst plannerBinding = this.work.plannerSettlements.get(settlement);\n\t\t\tthis.work.plannerSettlements.delete(settlement);\n\t\t\tif (plannerBinding) this.work.plannerCompletions.set(completion, plannerBinding);\n\t\t\treturn settlement.message;\n\t\t})();\n\t\treturn completion;\n\t}\n\n\tbindAuxiliaryStream(streamFn: StreamFn, request: InferenceRequestOptions): DisposableInferenceStream {\n\t\tconst captured = this.capture();\n\t\tconst release = captured.retainWork(captured.capturedSink!);\n\t\tconst recover = captured.providerRecoveryWait();\n\t\tconst stream = captured.bindStream(streamFn, request);\n\t\tlet disposal: Promise<void> | undefined;\n\t\treturn Object.assign(stream, {\n\t\t\trecoverProviderFailure: async (message: AssistantMessage, signal?: AbortSignal) => {\n\t\t\t\tif (!(await recover(message, signal))) return false;\n\t\t\t\tcaptured.prepareTurnRetry();\n\t\t\t\treturn true;\n\t\t\t},\n\t\t\tdispose: () => {\n\t\t\t\tdisposal ??= (async () => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait release();\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tawait captured.dispose();\n\t\t\t\t\t}\n\t\t\t\t})();\n\t\t\t\treturn disposal;\n\t\t\t},\n\t\t});\n\t}\n\n\tbindStream(streamFn: StreamFn, request: InferenceRequestOptions): AgentOwnedStreamFn {\n\t\tconst unwrapped = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\t\tconst inner = unwrapped[REQUEST_STREAM_BINDING]?.inner ?? unwrapped;\n\t\t// One Agent stream is serial. Keep only its latest binding for semantic retries.\n\t\t// A side question or child gets its own closure, not the parent's source binding.\n\t\tlet previous: BoundOperation | undefined;\n\t\tlet previousBody: string | undefined;\n\t\tconst wrapped: BoundStreamFn = async (model, context, options, streamContext) => {\n\t\t\tlet captured: InferenceCoordinator | undefined;\n\t\t\tif (streamContext !== undefined) {\n\t\t\t\tif (\n\t\t\t\t\t!(streamContext instanceof InferenceCoordinator) ||\n\t\t\t\t\tstreamContext.work !== this.work ||\n\t\t\t\t\t!streamContext.capturedSink\n\t\t\t\t)\n\t\t\t\t\tthrow new Error(\"Native stream context is not a capture of this inference owner\");\n\t\t\t\tcaptured = streamContext;\n\t\t\t}\n\t\t\tconst executor = captured ?? this;\n\t\t\tconst semanticEdgeId = request.semanticEdgeId ?? options?.headers?.[MODEL_REQUEST_ID_HEADER];\n\t\t\t// Reuse the existing semantic body identity if its best-effort recorder is unavailable.\n\t\t\tconst body = semanticEdgeId ? undefined : hashTurnBody(model, context, options);\n\t\t\tconst retryId =\n\t\t\t\tthis.retryTurn && body !== undefined && body === previousBody ? previous?.metadata.operationId : undefined;\n\t\t\tthis.retryTurn = false;\n\t\t\tconst operationId = request.operationId ?? semanticEdgeId ?? retryId ?? randomUUID();\n\t\t\tpreviousBody = body;\n\t\t\tif (captured || previous?.metadata.operationId !== operationId) {\n\t\t\t\t// A semantic retry can reuse its operation ID, but compilation owns this exact source frontier.\n\t\t\t\tprevious = executor.bindOperation(model, { ...request, semanticEdgeId }, operationId);\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tawait executor.execute(\n\t\t\t\t\tprevious,\n\t\t\t\t\tmodel,\n\t\t\t\t\tcontext,\n\t\t\t\t\toptions,\n\t\t\t\t\tinner,\n\t\t\t\t\tcaptured !== undefined && request.purpose === \"main\",\n\t\t\t\t)\n\t\t\t).events;\n\t\t};\n\t\twrapped[REQUEST_STREAM_BINDING] = { coordinator: this, inner };\n\t\treturn wrapped;\n\t}\n}\n\n/** Standalone helper embedding stays optional; native session callers always supply requests. */\nexport function completeInference(\n\trequests: InferenceCoordinator | undefined,\n\tmodel: Model<Api>,\n\tcontext: Context,\n\toptions: SimpleStreamOptions | undefined,\n\trequest: InferenceRequestOptions,\n): Promise<AssistantMessage> {\n\treturn requests ? requests.complete(model, context, options, request) : completeSimple(model, context, options);\n}\n\nexport type DisposableInferenceStream = StreamFn & {\n\tdispose(): Promise<void>;\n\trecoverProviderFailure?(message: AssistantMessage, signal?: AbortSignal): Promise<boolean>;\n};\n\n/** Side questions keep the subject's writer, but get their own operation and purpose. */\nexport function bindAuxiliaryInferenceStream(\n\tstreamFn: StreamFn,\n\trequest: InferenceRequestOptions,\n): DisposableInferenceStream {\n\tconst inner = unwrapSemanticEdgeStreamFn(streamFn) as BoundStreamFn;\n\tconst binding = inner[REQUEST_STREAM_BINDING];\n\tif (binding) return binding.coordinator.bindAuxiliaryStream(binding.inner, request);\n\tconst stream: StreamFn = (model, context, options) => inner(model, context, options);\n\treturn Object.assign(stream, { dispose: async () => {} });\n}\n"]}