@buildanagent/gateway 0.0.0-stage → 0.1.0-alpha.0

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 (126) hide show
  1. package/LICENSE +52 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +299 -2
  5. package/dist/adapters/anthropic/adapter.d.ts +25 -0
  6. package/dist/adapters/anthropic/adapter.js +183 -0
  7. package/dist/adapters/anthropic/adapter.js.map +1 -0
  8. package/dist/adapters/anthropic/failure.d.ts +20 -0
  9. package/dist/adapters/anthropic/failure.js +46 -0
  10. package/dist/adapters/anthropic/failure.js.map +1 -0
  11. package/dist/adapters/anthropic/index.d.ts +3 -0
  12. package/dist/adapters/anthropic/index.js +3 -0
  13. package/dist/adapters/anthropic/index.js.map +1 -0
  14. package/dist/adapters/anthropic/request.d.ts +53 -0
  15. package/dist/adapters/anthropic/request.js +250 -0
  16. package/dist/adapters/anthropic/request.js.map +1 -0
  17. package/dist/adapters/anthropic/response.d.ts +31 -0
  18. package/dist/adapters/anthropic/response.js +212 -0
  19. package/dist/adapters/anthropic/response.js.map +1 -0
  20. package/dist/adapters/anthropic/usage.d.ts +26 -0
  21. package/dist/adapters/anthropic/usage.js +39 -0
  22. package/dist/adapters/anthropic/usage.js.map +1 -0
  23. package/dist/adapters/openai-chat/adapter.d.ts +18 -0
  24. package/dist/adapters/openai-chat/adapter.js +86 -0
  25. package/dist/adapters/openai-chat/adapter.js.map +1 -0
  26. package/dist/adapters/openai-chat/compat.d.ts +58 -0
  27. package/dist/adapters/openai-chat/compat.js +19 -0
  28. package/dist/adapters/openai-chat/compat.js.map +1 -0
  29. package/dist/adapters/openai-chat/failure.d.ts +25 -0
  30. package/dist/adapters/openai-chat/failure.js +33 -0
  31. package/dist/adapters/openai-chat/failure.js.map +1 -0
  32. package/dist/adapters/openai-chat/index.d.ts +4 -0
  33. package/dist/adapters/openai-chat/index.js +3 -0
  34. package/dist/adapters/openai-chat/index.js.map +1 -0
  35. package/dist/adapters/openai-chat/request.d.ts +47 -0
  36. package/dist/adapters/openai-chat/request.js +227 -0
  37. package/dist/adapters/openai-chat/request.js.map +1 -0
  38. package/dist/adapters/openai-chat/response.d.ts +22 -0
  39. package/dist/adapters/openai-chat/response.js +203 -0
  40. package/dist/adapters/openai-chat/response.js.map +1 -0
  41. package/dist/adapters/openai-chat/usage.d.ts +19 -0
  42. package/dist/adapters/openai-chat/usage.js +22 -0
  43. package/dist/adapters/openai-chat/usage.js.map +1 -0
  44. package/dist/adapters/strict-schema.d.ts +67 -0
  45. package/dist/adapters/strict-schema.js +269 -0
  46. package/dist/adapters/strict-schema.js.map +1 -0
  47. package/dist/adapters/wire.d.ts +77 -0
  48. package/dist/adapters/wire.js +137 -0
  49. package/dist/adapters/wire.js.map +1 -0
  50. package/dist/catalog.d.ts +65 -0
  51. package/dist/catalog.js +145 -0
  52. package/dist/catalog.js.map +1 -0
  53. package/dist/catalog.json +120 -0
  54. package/dist/classify.d.ts +25 -0
  55. package/dist/classify.js +37 -0
  56. package/dist/classify.js.map +1 -0
  57. package/dist/complete.d.ts +9 -0
  58. package/dist/complete.js +13 -0
  59. package/dist/complete.js.map +1 -0
  60. package/dist/cost.d.ts +42 -0
  61. package/dist/cost.js +122 -0
  62. package/dist/cost.js.map +1 -0
  63. package/dist/create-model.d.ts +7 -0
  64. package/dist/create-model.js +81 -0
  65. package/dist/create-model.js.map +1 -0
  66. package/dist/errors.d.ts +17 -0
  67. package/dist/errors.js +24 -0
  68. package/dist/errors.js.map +1 -0
  69. package/dist/index.d.ts +19 -0
  70. package/dist/index.js +17 -0
  71. package/dist/index.js.map +1 -0
  72. package/dist/middleware.d.ts +11 -0
  73. package/dist/middleware.js +22 -0
  74. package/dist/middleware.js.map +1 -0
  75. package/dist/names.d.ts +72 -0
  76. package/dist/names.js +175 -0
  77. package/dist/names.js.map +1 -0
  78. package/dist/provider-config.d.ts +15 -0
  79. package/dist/provider-config.js +23 -0
  80. package/dist/provider-config.js.map +1 -0
  81. package/dist/request-dump.d.ts +28 -0
  82. package/dist/request-dump.js +52 -0
  83. package/dist/request-dump.js.map +1 -0
  84. package/dist/request-policy.d.ts +18 -0
  85. package/dist/request-policy.js +27 -0
  86. package/dist/request-policy.js.map +1 -0
  87. package/dist/retry.d.ts +30 -0
  88. package/dist/retry.js +191 -0
  89. package/dist/retry.js.map +1 -0
  90. package/dist/runtime-types.d.ts +112 -0
  91. package/dist/runtime-types.js +2 -0
  92. package/dist/runtime-types.js.map +1 -0
  93. package/dist/spec.d.ts +67 -0
  94. package/dist/spec.js +2 -0
  95. package/dist/spec.js.map +1 -0
  96. package/dist/sse.d.ts +15 -0
  97. package/dist/sse.js +73 -0
  98. package/dist/sse.js.map +1 -0
  99. package/dist/stream-contract.d.ts +23 -0
  100. package/dist/stream-contract.js +101 -0
  101. package/dist/stream-contract.js.map +1 -0
  102. package/dist/testing/guards.d.ts +16 -0
  103. package/dist/testing/guards.js +48 -0
  104. package/dist/testing/guards.js.map +1 -0
  105. package/dist/testing/index.d.ts +12 -0
  106. package/dist/testing/index.js +13 -0
  107. package/dist/testing/index.js.map +1 -0
  108. package/dist/testing/mock-transport.d.ts +49 -0
  109. package/dist/testing/mock-transport.js +101 -0
  110. package/dist/testing/mock-transport.js.map +1 -0
  111. package/dist/testing/random.d.ts +3 -0
  112. package/dist/testing/random.js +13 -0
  113. package/dist/testing/random.js.map +1 -0
  114. package/dist/testing/setup.d.ts +1 -0
  115. package/dist/testing/setup.js +12 -0
  116. package/dist/testing/setup.js.map +1 -0
  117. package/dist/transform-messages.d.ts +32 -0
  118. package/dist/transform-messages.js +291 -0
  119. package/dist/transform-messages.js.map +1 -0
  120. package/dist/types.d.ts +130 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +8 -0
  124. package/dist/usage.js +20 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +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AM,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC;IACpE,MAAM,UAAU,GACd,OAAO,CAAC,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,aAAa,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,aAAa,CAAC,CAAC,CAAC;IAC/G,OAAO;QACL,IAAI;QACJ,QAAQ,EAAE,CAAC,GAAG,eAAe,CAAC,UAAU,CAAC,EAAE,GAAG,eAAe,CAAC,UAAU,CAAC,CAAC;QAC1E,KAAK;QACL,QAAQ,EAAE,OAAO,CAAC,cAAc,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KAC1D,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Builds the Messages API request body from a `ModelContext` (Messages API reference,\n * https://platform.claude.com/docs/en/api/messages/create, as of November 2026).\n *\n * - Messages pass through `transformMessages()` first; tool results become `tool_result` blocks in a user message,\n * all results of one turn in one message, as the tool-use docs ask. `caps.reasoning` decides only whether the body\n * asks for thinking: signed Anthropic thinking is replayed either way, because the API checks it against its\n * signature rather than the model's caps, and dropping it would lose a turn's reasoning for a model the catalog\n * merely doesn't mark as reasoning.\n * - Tool names go through the run's `ToolNameMap`; tools are sent strict when their schema can be\n * (`../strict-schema.ts`).\n * - Caching puts at most three `cache_control` breakpoints, on the system prompt, the last tool and the last block\n * of the last user message, below the API's limit of 4 (Prompt caching,\n * https://platform.claude.com/docs/en/build-with-claude/prompt-caching, as of November 2026).\n * - `temperature`, `top_p` and `top_k` are never sent: on API version 2026-10-21 any of them is a 400 \"even at the\n * parameter's default value\" (https://platform.claude.com/docs/en/api/migration-2026-10-21, as of November 2026).\n */\nimport { createToolNameMap, TOOL_NAME_RULES, type ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent, StreamOptions } from \"../../spec.js\";\nimport { transformMessages } from \"../../transform-messages.js\";\nimport type { ContentBlock, Message, ModelCaps, ModelContent, ModelContext, ModelRef, WireTool } from \"../../types.js\";\nimport { lowerToStrict, type StrictDialect } from \"../strict-schema.js\";\nimport { isObject, type Json } from \"../wire.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\n/** A prefix on an `OpaqueToken` value that marks a `redacted_thinking` block's `data`, not a thinking signature. */\nexport const REDACTED_THINKING_PREFIX = \"redacted_thinking:\";\n\nconst SAMPLING_PARAMETERS = [\"temperature\", \"top_p\", \"top_k\"] as const;\n\n// Strict tool use keeps optional properties optional and takes these string formats (Structured outputs, \"JSON Schema\n// limitations\"); the request-wide limits are from its \"Schema complexity limits\" section.\nconst STRICT_DIALECT: StrictDialect = {\n optional: \"keep\",\n formats: new Set([\"date-time\", \"time\", \"date\", \"duration\", \"email\", \"hostname\", \"uri\", \"ipv4\", \"ipv6\", \"uuid\"]),\n objectRoot: false,\n};\n/** The request-wide limits on strict schemas: strict tools, optional properties and union-typed parameters. */\nconst STRICT_LIMITS = { tools: 20, optional: 24, unions: 16 } as const;\n\n/** What the adapter reads from `providerOptions.anthropic`. */\nexport interface AnthropicProviderOptions {\n /**\n * Names the conversation, so the adapter can remember a choice that must hold for its later requests. Without it,\n * the adapter recognises a conversation by its system prompt and first message.\n */\n readonly conversationId?: string;\n /**\n * Extra fields for the request body, such as `output_config` or `thinking: { display: \"summarized\" }`. The fields\n * the adapter sets itself (`model`, `max_tokens`, `stream`, `system`, `messages`, `tools`, and `thinking.type` for a\n * reasoning model) win over these, and sampling fields are dropped; either streams an `unsupported_option` warning.\n */\n readonly extraBody?: Readonly<Record<string, unknown>>;\n}\n\n/** One request's body and what reading its response needs. */\nexport interface RequestPlan {\n readonly body: Json;\n readonly warnings: readonly Warning[];\n readonly names: ToolNameMap;\n /** The TTL the breakpoints asked for, used when a response reports cache writes without their split. */\n readonly cacheTtl: \"5m\" | \"1h\";\n}\n\n/** Reads `providerOptions.anthropic`, ignoring fields of the wrong type. */\nexport function anthropicOptions(options: StreamOptions): AnthropicProviderOptions {\n const raw = options.providerOptions?.anthropic;\n if (!isObject(raw)) return {};\n return {\n ...(typeof raw.conversationId === \"string\" ? { conversationId: raw.conversationId } : {}),\n ...(isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {}),\n };\n}\n\nfunction cacheControlFor(retention: StreamOptions[\"cacheRetention\"]): Json | undefined {\n if (retention === \"none\") return undefined;\n return retention === \"long\" ? { type: \"ephemeral\", ttl: \"1h\" } : { type: \"ephemeral\" };\n}\n\n// Content blocks ------------------------------------------------------------------------------------------------------\n\nfunction imageBlock(block: Extract<ContentBlock, { type: \"image\" }>): Json {\n return { type: \"image\", source: { type: \"base64\", media_type: block.mediaType, data: block.data } };\n}\n\nfunction userBlock(block: ContentBlock): Json[] {\n if (block.type === \"text\") return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n if (block.type === \"image\") return [imageBlock(block)];\n return [];\n}\n\nfunction reasoningBlock(block: Extract<ContentBlock, { type: \"reasoning\" }>): Json[] {\n // An unsigned block cannot pass Anthropic's signature check; transformMessages already drops them for this target.\n const value = block.signature?.value;\n if (value === undefined) return [];\n if (value.startsWith(REDACTED_THINKING_PREFIX)) {\n return [{ type: \"redacted_thinking\", data: value.slice(REDACTED_THINKING_PREFIX.length) }];\n }\n return [{ type: \"thinking\", thinking: block.text, signature: value }];\n}\n\nfunction assistantBlock(block: ContentBlock, names: ToolNameMap): Json[] {\n switch (block.type) {\n case \"text\":\n return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n case \"reasoning\":\n return reasoningBlock(block);\n case \"tool_call\":\n // A call cut off by the output limit holds its partial JSON as a string; the wire needs an object.\n return [\n {\n type: \"tool_use\",\n id: block.callId,\n name: names.sanitize(block.name),\n input: isObject(block.input) ? block.input : {},\n },\n ];\n case \"image\":\n return [];\n }\n}\n\nfunction toolResultBlock(message: Extract<Message, { role: \"tool\" }>): Json {\n const content = message.content.flatMap((block: ModelContent) => userBlock(block));\n return {\n type: \"tool_result\",\n tool_use_id: message.callId,\n ...(content.length > 0 ? { content } : {}),\n ...(message.isError ? { is_error: true } : {}),\n };\n}\n\n// Messages -----------------------------------------------------------------------------------------------------------\n\nfunction appendUserBlocks(out: Json[], blocks: Json[]): void {\n if (blocks.length === 0) return;\n const last = out.at(-1);\n if (last?.role === \"user\" && Array.isArray(last.content)) last.content.push(...blocks);\n else out.push({ role: \"user\", content: blocks });\n}\n\nfunction encodeMessages(messages: readonly Message[], names: ToolNameMap): Json[] {\n const out: Json[] = [];\n for (const message of messages) {\n if (message.role === \"assistant\") {\n const content = message.content.flatMap((block) => assistantBlock(block, names));\n if (content.length > 0) out.push({ role: \"assistant\", content });\n } else {\n appendUserBlocks(out, message.role === \"tool\" ? [toolResultBlock(message)] : message.content.flatMap(userBlock));\n }\n }\n return out;\n}\n\nfunction markLastUserBlock(messages: Json[], cacheControl: Json): void {\n const lastUser = messages.findLast((message) => message.role === \"user\");\n const content = lastUser?.content;\n const block = Array.isArray(content) ? content.at(-1) : undefined;\n if (isObject(block)) block.cache_control = cacheControl;\n}\n\n// Tools --------------------------------------------------------------------------------------------------------------\n\nfunction encodeTools(tools: readonly WireTool[], names: ToolNameMap, cacheControl: Json | undefined): Json[] {\n const used = { tools: 0, optional: 0, unions: 0 };\n const encoded = tools.map((tool): Json => {\n const base: Json = {\n name: names.sanitize(tool.name),\n ...(tool.description ? { description: tool.description } : {}),\n };\n const strict = lowerToStrict(tool.inputSchema, STRICT_DIALECT);\n const fits =\n strict !== undefined &&\n used.tools < STRICT_LIMITS.tools &&\n used.optional + strict.optional <= STRICT_LIMITS.optional &&\n used.unions + strict.unions <= STRICT_LIMITS.unions;\n // A tool past the request-wide limits goes without `strict`, so one large schema cannot fail the whole request.\n if (!fits || strict === undefined) return { ...base, input_schema: tool.inputSchema };\n used.tools += 1;\n used.optional += strict.optional;\n used.unions += strict.unions;\n return { ...base, input_schema: strict.schema, strict: true };\n });\n const last = encoded.at(-1);\n if (last && cacheControl) last.cache_control = cacheControl;\n return encoded;\n}\n\n// The body -----------------------------------------------------------------------------------------------------------\n\nfunction toolNames(context: ModelContext, messages: readonly Message[]): string[] {\n const called = messages.flatMap((message) =>\n message.role === \"assistant\" ? message.content.flatMap((b) => (b.type === \"tool_call\" ? [b.name] : [])) : [],\n );\n return [...context.tools.map((tool) => tool.name), ...called];\n}\n\n/** Splits the sampling fields off `extra`, and returns the rest with the names of the fields it dropped. */\nfunction withoutSampling(extra: Readonly<Json>): { rest: Json; dropped: string[] } {\n const rest: Json = {};\n const dropped: string[] = [];\n for (const [key, value] of Object.entries(extra)) {\n if ((SAMPLING_PARAMETERS as readonly string[]).includes(key)) dropped.push(key);\n else rest[key] = value;\n }\n return { rest, dropped };\n}\n\nfunction samplingWarning(dropped: readonly string[]): Warning[] {\n if (dropped.length === 0) return [];\n return [\n {\n type: \"warning\",\n code: \"unsupported_option\",\n message:\n \"Anthropic API version 2026-10-21 rejects temperature, top_p and top_k at any value, \" +\n `so the request was sent without ${dropped.join(\", \")}.`,\n },\n ];\n}\n\n// Body fields the adapter always sets from the context and options, so an `extraBody` field of the same name is\n// ignored. `thinking` is owned only when the caps ask for it, and then only its `type`.\nconst ADAPTER_FIELDS = [\"model\", \"max_tokens\", \"stream\", \"system\", \"messages\", \"tools\"] as const;\n\n/**\n * The adapter's own fields over the caller's extras, and the names of the extras they overrode. A caller's `thinking`\n * keeps its other fields, such as `display`, under the adapter's `type: \"adaptive\"`.\n */\nfunction mergeExtras(own: Json, extras: Json, ownsThinking: boolean): { body: Json; overridden: string[] } {\n const overridden: string[] = ADAPTER_FIELDS.filter((key) => key in extras);\n const body: Json = { ...extras, ...own };\n for (const key of ADAPTER_FIELDS) if (!(key in own)) delete body[key];\n if (ownsThinking) {\n const extra = extras.thinking;\n if (extra !== undefined && !(isObject(extra) && (extra.type === undefined || extra.type === \"adaptive\"))) {\n overridden.push(\"thinking.type\");\n }\n body.thinking = { ...(isObject(extra) ? extra : {}), type: \"adaptive\" };\n }\n return { body, overridden };\n}\n\nfunction overrideWarning(overridden: readonly string[]): Warning[] {\n if (overridden.length === 0) return [];\n return [\n {\n type: \"warning\",\n code: \"unsupported_option\",\n message:\n `providerOptions.anthropic.extraBody cannot set ${overridden.join(\", \")}, ` +\n \"which the adapter sets itself, so the request was sent with the adapter's value.\",\n },\n ];\n}\n\n/** Builds one call's request body. The adapter adds the thinking-binding setting to it before each HTTP request. */\nexport function buildRequest(\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n caps: ModelCaps,\n): RequestPlan {\n // Replay keeps signed thinking whatever caps.reasoning says; the caps decide only the `thinking` field below.\n const messages = transformMessages(context.messages, model, { ...caps, reasoning: true });\n const names = createToolNameMap(TOOL_NAME_RULES.anthropicMessages, toolNames(context, messages));\n const cacheControl = cacheControlFor(options.cacheRetention);\n const wireMessages = encodeMessages(messages, names);\n if (cacheControl) markLastUserBlock(wireMessages, cacheControl);\n const tools = encodeTools(context.tools, names, cacheControl);\n const system =\n context.system === \"\"\n ? undefined\n : [{ type: \"text\", text: context.system, ...(cacheControl ? { cache_control: cacheControl } : {}) }];\n const { rest, dropped } = withoutSampling(anthropicOptions(options).extraBody ?? {});\n const own: Json = {\n model: model.id,\n max_tokens: options.maxOutputTokens ?? caps.maxOutputTokens,\n stream: true,\n ...(system ? { system } : {}),\n messages: wireMessages,\n ...(tools.length > 0 ? { tools } : {}),\n };\n const { body, overridden } = mergeExtras(own, rest, caps.reasoning);\n const droppedAll =\n options.temperature === undefined ? dropped : [\"temperature\", ...dropped.filter((d) => d !== \"temperature\")];\n return {\n body,\n warnings: [...samplingWarning(droppedAll), ...overrideWarning(overridden)],\n names,\n cacheTtl: options.cacheRetention === \"long\" ? \"1h\" : \"5m\",\n };\n}\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,
3
+ * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs
4
+ * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and
5
+ * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events
6
+ * and event types the adapter does not know are skipped, as the versioning policy asks.
7
+ *
8
+ * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,
9
+ * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are
10
+ * skipped.
11
+ */
12
+ import type { ToolNameMap } from "../../names.js";
13
+ import type { ModelEvent } from "../../spec.js";
14
+ import type { ServerSentEvent } from "../../sse.js";
15
+ import type { ContentBlock, ModelRef, Usage } from "../../types.js";
16
+ import { type StreamReader } from "../wire.js";
17
+ /** One stream's state: the blocks so far, the usage and the stop reason. */
18
+ export declare class MessageAssembler implements StreamReader {
19
+ #private;
20
+ constructor(model: ModelRef, names: ToolNameMap, cacheTtl: "5m" | "1h");
21
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
22
+ handle(sse: ServerSentEvent): ModelEvent[];
23
+ /** No status and no terminal: the connection closed early, which a retry may fix. */
24
+ ended(): ModelEvent[];
25
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
26
+ partial(): {
27
+ content: ContentBlock[];
28
+ usage: Usage;
29
+ };
30
+ usage(): Usage;
31
+ }
@@ -0,0 +1,212 @@
1
+ import { isObject, parseToolInput, str, terminalMessage } from "../wire.js";
2
+ import { failureEvent, failureFrom } from "./failure.js";
3
+ import { REDACTED_THINKING_PREFIX } from "./request.js";
4
+ import { anthropicUsage, mergeUsage } from "./usage.js";
5
+ // Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.
6
+ const STOP_REASONS = {
7
+ end_turn: "stop",
8
+ stop_sequence: "stop",
9
+ pause_turn: "stop",
10
+ tool_use: "tool_calls",
11
+ max_tokens: "length",
12
+ model_context_window_exceeded: "length",
13
+ };
14
+ /** One stream's state: the blocks so far, the usage and the stop reason. */
15
+ export class MessageAssembler {
16
+ #model;
17
+ #names;
18
+ #cacheTtl;
19
+ #open = new Map();
20
+ #closed = new Map();
21
+ #transformations = new Set();
22
+ #usage = {};
23
+ #stopReason = "";
24
+ #stopDetails;
25
+ constructor(model, names, cacheTtl) {
26
+ this.#model = model;
27
+ this.#names = names;
28
+ this.#cacheTtl = cacheTtl;
29
+ }
30
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
31
+ handle(sse) {
32
+ const data = JSON.parse(sse.data);
33
+ if (!isObject(data))
34
+ return [];
35
+ return this.#dispatch(typeof data.type === "string" ? data.type : sse.event, data);
36
+ }
37
+ /** No status and no terminal: the connection closed early, which a retry may fix. */
38
+ ended() {
39
+ return [failureEvent(this.#model, { message: "the stream ended before message_stop" }, this.partial())];
40
+ }
41
+ #dispatch(type, data) {
42
+ switch (type) {
43
+ case "message_start":
44
+ return this.#messageStart(data);
45
+ case "content_block_start":
46
+ return this.#blockStart(data);
47
+ case "content_block_delta":
48
+ return this.#blockDelta(data);
49
+ case "content_block_stop":
50
+ return this.#blockStop(data);
51
+ case "message_delta":
52
+ return this.#messageDelta(data);
53
+ case "message_stop":
54
+ return this.#messageStop();
55
+ case "error":
56
+ return [failureEvent(this.#model, failureFrom(data, undefined, "stream error"), this.partial())];
57
+ default:
58
+ return [];
59
+ }
60
+ }
61
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
62
+ partial() {
63
+ const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)]);
64
+ const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);
65
+ return { content, usage: this.usage() };
66
+ }
67
+ usage() {
68
+ return anthropicUsage(this.#usage, this.#cacheTtl);
69
+ }
70
+ #messageStart(data) {
71
+ const message = isObject(data.message) ? data.message : {};
72
+ this.#usage = mergeUsage({}, message.usage);
73
+ return this.#transformationWarnings(message.input_transformations);
74
+ }
75
+ // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`
76
+ // carries it again after a mid-stream fallback (Streaming, "Event types"). Each entry is warned about once.
77
+ #transformationWarnings(entries) {
78
+ if (!Array.isArray(entries))
79
+ return [];
80
+ return entries.flatMap((entry) => {
81
+ if (!isObject(entry) || entry.type !== "thinking_mismatch_allowed")
82
+ return [];
83
+ const key = `${str(entry.path)}|${str(entry.reason)}`;
84
+ if (this.#transformations.has(key))
85
+ return [];
86
+ this.#transformations.add(key);
87
+ return [
88
+ {
89
+ type: "warning",
90
+ code: "thinking_mismatch_allowed",
91
+ message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,
92
+ },
93
+ ];
94
+ });
95
+ }
96
+ #blockStart(data) {
97
+ const index = typeof data.index === "number" ? data.index : -1;
98
+ const block = isObject(data.content_block) ? data.content_block : {};
99
+ const open = this.#openBlock(block);
100
+ if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index))
101
+ return [];
102
+ this.#open.set(index, open);
103
+ const startEvent = { type: `${open.kind}_start`, index };
104
+ // A redacted block arrives whole, with no deltas, so it ends where it starts.
105
+ return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];
106
+ }
107
+ #openBlock(block) {
108
+ switch (block.type) {
109
+ case "text":
110
+ return { kind: "text", text: str(block.text) };
111
+ case "thinking":
112
+ return { kind: "reasoning", text: str(block.thinking), signature: str(block.signature) };
113
+ case "redacted_thinking":
114
+ return { kind: "reasoning", text: "", redacted: str(block.data) };
115
+ case "tool_use":
116
+ return { kind: "tool_input", text: "", callId: str(block.id), name: str(block.name), startInput: block.input };
117
+ default:
118
+ return undefined;
119
+ }
120
+ }
121
+ #blockDelta(data) {
122
+ const index = typeof data.index === "number" ? data.index : -1;
123
+ const open = this.#open.get(index);
124
+ const delta = isObject(data.delta) ? data.delta : {};
125
+ if (open === undefined)
126
+ return [];
127
+ if (delta.type === "signature_delta") {
128
+ open.signature = (open.signature ?? "") + str(delta.signature);
129
+ return [];
130
+ }
131
+ const text = str(delta.type === "thinking_delta"
132
+ ? delta.thinking
133
+ : delta.type === "input_json_delta"
134
+ ? delta.partial_json
135
+ : delta.text);
136
+ const fits = (open.kind === "text" && delta.type === "text_delta") ||
137
+ (open.kind === "reasoning" && delta.type === "thinking_delta") ||
138
+ (open.kind === "tool_input" && delta.type === "input_json_delta");
139
+ // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.
140
+ if (!fits || text === "")
141
+ return [];
142
+ open.text += text;
143
+ return [{ type: `${open.kind}_delta`, index, delta: text }];
144
+ }
145
+ #blockStop(data) {
146
+ return typeof data.index === "number" ? this.#close(data.index) : [];
147
+ }
148
+ #close(index) {
149
+ const open = this.#open.get(index);
150
+ if (open === undefined)
151
+ return [];
152
+ this.#open.delete(index);
153
+ const block = this.#finish(open);
154
+ this.#closed.set(index, block);
155
+ return [{ type: `${open.kind}_end`, index, block }];
156
+ }
157
+ #finish(open) {
158
+ if (open.kind === "text")
159
+ return { type: "text", text: open.text };
160
+ if (open.kind === "tool_input") {
161
+ const wire = open.name ?? "";
162
+ return {
163
+ type: "tool_call",
164
+ callId: open.callId ?? "",
165
+ name: this.#names.restore(wire) ?? wire,
166
+ input: parseToolInput(open.text, open.startInput ?? {}),
167
+ };
168
+ }
169
+ const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;
170
+ const { api, provider, id } = this.#model;
171
+ return value
172
+ ? { type: "reasoning", text: open.text, signature: { api, provider, model: id, value } }
173
+ : { type: "reasoning", text: open.text };
174
+ }
175
+ #messageDelta(data) {
176
+ const delta = isObject(data.delta) ? data.delta : {};
177
+ if (typeof delta.stop_reason === "string")
178
+ this.#stopReason = delta.stop_reason;
179
+ if (delta.stop_details !== undefined)
180
+ this.#stopDetails = delta.stop_details;
181
+ this.#usage = mergeUsage(this.#usage, data.usage);
182
+ return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);
183
+ }
184
+ #messageStop() {
185
+ // The output limit can end a stream with a block still open; the block ends here with what arrived.
186
+ const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));
187
+ return [...closing, ...this.#terminal()];
188
+ }
189
+ #terminal() {
190
+ const { content, usage } = this.partial();
191
+ if (this.#stopReason === "refusal") {
192
+ const details = isObject(this.#stopDetails) ? this.#stopDetails : {};
193
+ const category = str(details.category) || "no category";
194
+ const message = `refusal (${category}): ${str(details.explanation) || "the model declined the request"}`;
195
+ // No `type`: failureEvent prefixes the type to the message, which already starts with "refusal".
196
+ return [failureEvent(this.#model, { message, kind: "fatal" }, { content, usage })];
197
+ }
198
+ const stopReason = STOP_REASONS[this.#stopReason] ?? "stop";
199
+ const warnings = this.#stopReason === "pause_turn"
200
+ ? [
201
+ {
202
+ type: "warning",
203
+ code: "pause_turn",
204
+ message: "The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool " +
205
+ "blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.",
206
+ },
207
+ ]
208
+ : [];
209
+ return [...warnings, { type: "done", message: terminalMessage(this.#model, { content, usage }, stopReason) }];
210
+ }
211
+ }
212
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/response.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAcxD,oFAAoF;AACpF,MAAM,YAAY,GAA6D;IAC7E,QAAQ,EAAE,MAAM;IAChB,aAAa,EAAE,MAAM;IACrB,UAAU,EAAE,MAAM;IAClB,QAAQ,EAAE,YAAY;IACtB,UAAU,EAAE,QAAQ;IACpB,6BAA6B,EAAE,QAAQ;CACxC,CAAC;AAEF,4EAA4E;AAC5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,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;QACrF,CAAC;QACD,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,MAAM,CAAC;QAC5D,MAAM,QAAQ,GACZ,IAAI,CAAC,WAAW,KAAK,YAAY;YAC/B,CAAC,CAAC;gBACE;oBACE,IAAI,EAAE,SAAS;oBACf,IAAI,EAAE,YAAY;oBAClB,OAAO,EACL,mGAAmG;wBACnG,iGAAiG;iBACpG;aACF;YACH,CAAC,CAAC,EAAE,CAAC;QACT,OAAO,CAAC,GAAG,QAAQ,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,eAAe,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,UAAU,CAAC,EAAE,CAAC,CAAC;IAChH,CAAC;CACF","sourcesContent":["/**\n * Turns the Messages API's stream events into `ModelEvent`s (Streaming messages,\n * https://platform.claude.com/docs/en/build-with-claude/streaming, as of November 2026). A stream runs\n * `message_start`, then each content block as `content_block_start`, its `content_block_delta`s and\n * `content_block_stop`, then one or more `message_delta`s with cumulative usage, then `message_stop`. `ping` events\n * and event types the adapter does not know are skipped, as the versioning policy asks.\n *\n * Text blocks become text, `thinking` and `redacted_thinking` blocks become reasoning with an Anthropic signature,\n * and `tool_use` blocks become tool calls. Server-tool blocks carry nothing this transcript can replay, so they are\n * skipped.\n */\nimport type { ToolNameMap } from \"../../names.js\";\nimport type { ModelEvent } from \"../../spec.js\";\nimport type { ServerSentEvent } from \"../../sse.js\";\nimport type { AssistantMessage, ContentBlock, ModelRef, Usage } from \"../../types.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport { REDACTED_THINKING_PREFIX } from \"./request.js\";\nimport { anthropicUsage, mergeUsage } from \"./usage.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\ninterface OpenBlock {\n readonly kind: \"text\" | \"reasoning\" | \"tool_input\";\n text: string;\n signature?: string;\n redacted?: string;\n callId?: string;\n name?: string;\n startInput?: unknown;\n}\n\n// Each wire stop reason as the gateway's. `refusal` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n end_turn: \"stop\",\n stop_sequence: \"stop\",\n pause_turn: \"stop\",\n tool_use: \"tool_calls\",\n max_tokens: \"length\",\n model_context_window_exceeded: \"length\",\n};\n\n/** One stream's state: the blocks so far, the usage and the stop reason. */\nexport class MessageAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #cacheTtl: \"5m\" | \"1h\";\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n readonly #transformations = new Set<string>();\n #usage: Json = {};\n #stopReason = \"\";\n #stopDetails: unknown;\n\n constructor(model: ModelRef, names: ToolNameMap, cacheTtl: \"5m\" | \"1h\") {\n this.#model = model;\n this.#names = names;\n this.#cacheTtl = cacheTtl;\n }\n\n /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */\n handle(sse: ServerSentEvent): ModelEvent[] {\n const data: unknown = JSON.parse(sse.data);\n if (!isObject(data)) return [];\n return this.#dispatch(typeof data.type === \"string\" ? data.type : sse.event, data);\n }\n\n /** No status and no terminal: the connection closed early, which a retry may fix. */\n ended(): ModelEvent[] {\n return [failureEvent(this.#model, { message: \"the stream ended before message_stop\" }, this.partial())];\n }\n\n #dispatch(type: string, data: Json): ModelEvent[] {\n switch (type) {\n case \"message_start\":\n return this.#messageStart(data);\n case \"content_block_start\":\n return this.#blockStart(data);\n case \"content_block_delta\":\n return this.#blockDelta(data);\n case \"content_block_stop\":\n return this.#blockStop(data);\n case \"message_delta\":\n return this.#messageDelta(data);\n case \"message_stop\":\n return this.#messageStop();\n case \"error\":\n return [failureEvent(this.#model, failureFrom(data, undefined, \"stream error\"), this.partial())];\n default:\n return [];\n }\n }\n\n /** The content and usage so far, open blocks included, for an `error` terminal. */\n partial(): { content: ContentBlock[]; usage: Usage } {\n const open = [...this.#open].map(([index, block]) => [index, this.#finish(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: this.usage() };\n }\n\n usage(): Usage {\n return anthropicUsage(this.#usage, this.#cacheTtl);\n }\n\n #messageStart(data: Json): ModelEvent[] {\n const message = isObject(data.message) ? data.message : {};\n this.#usage = mergeUsage({}, message.usage);\n return this.#transformationWarnings(message.input_transformations);\n }\n\n // Under the thinking-binding beta, `message_start` carries `input_transformations`, and the final `message_delta`\n // carries it again after a mid-stream fallback (Streaming, \"Event types\"). Each entry is warned about once.\n #transformationWarnings(entries: unknown): Warning[] {\n if (!Array.isArray(entries)) return [];\n return entries.flatMap((entry): Warning[] => {\n if (!isObject(entry) || entry.type !== \"thinking_mismatch_allowed\") return [];\n const key = `${str(entry.path)}|${str(entry.reason)}`;\n if (this.#transformations.has(key)) return [];\n this.#transformations.add(key);\n return [\n {\n type: \"warning\",\n code: \"thinking_mismatch_allowed\",\n message: `${str(entry.path)}: a thinking block failed the prefix check (${str(entry.reason)}) and reached the model`,\n },\n ];\n });\n }\n\n #blockStart(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const block = isObject(data.content_block) ? data.content_block : {};\n const open = this.#openBlock(block);\n if (open === undefined || index < 0 || this.#open.has(index) || this.#closed.has(index)) return [];\n this.#open.set(index, open);\n const startEvent: ModelEvent = { type: `${open.kind}_start`, index };\n // A redacted block arrives whole, with no deltas, so it ends where it starts.\n return open.redacted === undefined ? [startEvent] : [startEvent, ...this.#close(index)];\n }\n\n #openBlock(block: Json): OpenBlock | undefined {\n switch (block.type) {\n case \"text\":\n return { kind: \"text\", text: str(block.text) };\n case \"thinking\":\n return { kind: \"reasoning\", text: str(block.thinking), signature: str(block.signature) };\n case \"redacted_thinking\":\n return { kind: \"reasoning\", text: \"\", redacted: str(block.data) };\n case \"tool_use\":\n return { kind: \"tool_input\", text: \"\", callId: str(block.id), name: str(block.name), startInput: block.input };\n default:\n return undefined;\n }\n }\n\n #blockDelta(data: Json): ModelEvent[] {\n const index = typeof data.index === \"number\" ? data.index : -1;\n const open = this.#open.get(index);\n const delta = isObject(data.delta) ? data.delta : {};\n if (open === undefined) return [];\n if (delta.type === \"signature_delta\") {\n open.signature = (open.signature ?? \"\") + str(delta.signature);\n return [];\n }\n const text = str(\n delta.type === \"thinking_delta\"\n ? delta.thinking\n : delta.type === \"input_json_delta\"\n ? delta.partial_json\n : delta.text,\n );\n const fits =\n (open.kind === \"text\" && delta.type === \"text_delta\") ||\n (open.kind === \"reasoning\" && delta.type === \"thinking_delta\") ||\n (open.kind === \"tool_input\" && delta.type === \"input_json_delta\");\n // An empty delta adds nothing; a citations delta or another kind of delta has no place in this transcript.\n if (!fits || text === \"\") return [];\n open.text += text;\n return [{ type: `${open.kind}_delta`, index, delta: text }];\n }\n\n #blockStop(data: Json): ModelEvent[] {\n return typeof data.index === \"number\" ? this.#close(data.index) : [];\n }\n\n #close(index: number): ModelEvent[] {\n const open = this.#open.get(index);\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finish(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finish(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"tool_input\") {\n const wire = open.name ?? \"\";\n return {\n type: \"tool_call\",\n callId: open.callId ?? \"\",\n name: this.#names.restore(wire) ?? wire,\n input: parseToolInput(open.text, open.startInput ?? {}),\n };\n }\n const value = open.redacted === undefined ? open.signature : `${REDACTED_THINKING_PREFIX}${open.redacted}`;\n const { api, provider, id } = this.#model;\n return value\n ? { type: \"reasoning\", text: open.text, signature: { api, provider, model: id, value } }\n : { type: \"reasoning\", text: open.text };\n }\n\n #messageDelta(data: Json): ModelEvent[] {\n const delta = isObject(data.delta) ? data.delta : {};\n if (typeof delta.stop_reason === \"string\") this.#stopReason = delta.stop_reason;\n if (delta.stop_details !== undefined) this.#stopDetails = delta.stop_details;\n this.#usage = mergeUsage(this.#usage, data.usage);\n return this.#transformationWarnings(data.input_transformations ?? delta.input_transformations);\n }\n\n #messageStop(): ModelEvent[] {\n // The output limit can end a stream with a block still open; the block ends here with what arrived.\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#close(index));\n return [...closing, ...this.#terminal()];\n }\n\n #terminal(): ModelEvent[] {\n const { content, usage } = this.partial();\n if (this.#stopReason === \"refusal\") {\n const details = isObject(this.#stopDetails) ? this.#stopDetails : {};\n const category = str(details.category) || \"no category\";\n const message = `refusal (${category}): ${str(details.explanation) || \"the model declined the request\"}`;\n // No `type`: failureEvent prefixes the type to the message, which already starts with \"refusal\".\n return [failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const stopReason = STOP_REASONS[this.#stopReason] ?? \"stop\";\n const warnings: Warning[] =\n this.#stopReason === \"pause_turn\"\n ? [\n {\n type: \"warning\",\n code: \"pause_turn\",\n message:\n \"The provider paused a long-running server-tool turn. This adapter dropped the turn's server-tool \" +\n \"blocks, so it cannot resume the paused turn; the reply holds only the content before the pause.\",\n },\n ]\n : [];\n return [...warnings, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Maps Anthropic's `usage` object into the gateway's four token classes (D3), from the Messages API reference's
3
+ * `Usage` and `MessageDeltaUsage` (https://platform.claude.com/docs/en/api/messages/create, as of November 2026):
4
+ *
5
+ * - `input_tokens` is the uncached input: the reference says total input is the sum of `input_tokens`,
6
+ * `cache_creation_input_tokens` and `cache_read_input_tokens`.
7
+ * - `cache_creation.ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` split the cache writes by TTL.
8
+ * - `output_tokens` is "the inclusive, authoritative total used for billing", and
9
+ * `output_tokens_details.thinking_tokens` is the part spent on reasoning, "always ≤ `output_tokens`". When
10
+ * streaming, the breakdown arrives only on the final `message_delta` (Extended thinking,
11
+ * https://platform.claude.com/docs/en/build-with-claude/extended-thinking, as of November 2026).
12
+ *
13
+ * The response carries no billed price, so the cost always comes from the catalog.
14
+ */
15
+ import type { Usage } from "../../types.js";
16
+ import { type Json } from "../wire.js";
17
+ /**
18
+ * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends
19
+ * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.
20
+ */
21
+ export declare function mergeUsage(earlier: Json, later: unknown): Json;
22
+ /**
23
+ * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as
24
+ * `fallbackTtl`, the TTL the request asked for.
25
+ */
26
+ export declare function anthropicUsage(raw: Json, fallbackTtl: "5m" | "1h"): Usage;
@@ -0,0 +1,39 @@
1
+ import { count, isObject } from "../wire.js";
2
+ /**
3
+ * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends
4
+ * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.
5
+ */
6
+ export function mergeUsage(earlier, later) {
7
+ if (!isObject(later))
8
+ return earlier;
9
+ const merged = { ...earlier };
10
+ for (const [key, value] of Object.entries(later)) {
11
+ if (value === null || value === undefined)
12
+ continue;
13
+ merged[key] = isObject(value) && isObject(earlier[key]) ? { ...earlier[key], ...value } : value;
14
+ }
15
+ return merged;
16
+ }
17
+ /**
18
+ * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as
19
+ * `fallbackTtl`, the TTL the request asked for.
20
+ */
21
+ export function anthropicUsage(raw, fallbackTtl) {
22
+ const split = isObject(raw.cache_creation) ? raw.cache_creation : undefined;
23
+ const written = count(raw.cache_creation_input_tokens);
24
+ const cacheWrite = split
25
+ ? { "5m": count(split.ephemeral_5m_input_tokens), "1h": count(split.ephemeral_1h_input_tokens) }
26
+ : { "5m": fallbackTtl === "5m" ? written : 0, "1h": fallbackTtl === "1h" ? written : 0 };
27
+ const output = count(raw.output_tokens);
28
+ const details = isObject(raw.output_tokens_details) ? raw.output_tokens_details : {};
29
+ return {
30
+ uncachedInput: count(raw.input_tokens),
31
+ cacheRead: count(raw.cache_read_input_tokens),
32
+ cacheWrite,
33
+ output,
34
+ // Reasoning is a part of output; the reference guarantees it never exceeds it, and the cap keeps that true.
35
+ reasoning: Math.min(count(details.thinking_tokens), output),
36
+ raw,
37
+ };
38
+ }
39
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/adapters/anthropic/usage.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAa,MAAM,YAAY,CAAC;AAExD;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAC,OAAa,EAAE,KAAc;IACtD,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,OAAO,CAAC;IACrC,MAAM,MAAM,GAAS,EAAE,GAAG,OAAO,EAAE,CAAC;IACpC,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QACjD,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;YAAE,SAAS;QACpD,MAAM,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAI,OAAO,CAAC,GAAG,CAAU,EAAE,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IAC5G,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,GAAS,EAAE,WAAwB;IAChE,MAAM,KAAK,GAAG,QAAQ,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC;IAC5E,MAAM,OAAO,GAAG,KAAK,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;IACvD,MAAM,UAAU,GAAG,KAAK;QACtB,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,yBAAyB,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,yBAAyB,CAAC,EAAE;QAChG,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC3F,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAAC;IACrF,OAAO;QACL,aAAa,EAAE,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC;QACtC,SAAS,EAAE,KAAK,CAAC,GAAG,CAAC,uBAAuB,CAAC;QAC7C,UAAU;QACV,MAAM;QACN,4GAA4G;QAC5G,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;QAC3D,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Maps Anthropic's `usage` object into the gateway's four token classes (D3), from the Messages API reference's\n * `Usage` and `MessageDeltaUsage` (https://platform.claude.com/docs/en/api/messages/create, as of November 2026):\n *\n * - `input_tokens` is the uncached input: the reference says total input is the sum of `input_tokens`,\n * `cache_creation_input_tokens` and `cache_read_input_tokens`.\n * - `cache_creation.ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens` split the cache writes by TTL.\n * - `output_tokens` is \"the inclusive, authoritative total used for billing\", and\n * `output_tokens_details.thinking_tokens` is the part spent on reasoning, \"always ≤ `output_tokens`\". When\n * streaming, the breakdown arrives only on the final `message_delta` (Extended thinking,\n * https://platform.claude.com/docs/en/build-with-claude/extended-thinking, as of November 2026).\n *\n * The response carries no billed price, so the cost always comes from the catalog.\n */\nimport type { Usage } from \"../../types.js\";\nimport { count, isObject, type Json } from \"../wire.js\";\n\n/**\n * Overlays a later usage report on an earlier one. A `message_delta`'s counts are cumulative, and a field it sends\n * as `null` or leaves out keeps the earlier value, so the `message_start` split of cache writes survives.\n */\nexport function mergeUsage(earlier: Json, later: unknown): Json {\n if (!isObject(later)) return earlier;\n const merged: Json = { ...earlier };\n for (const [key, value] of Object.entries(later)) {\n if (value === null || value === undefined) continue;\n merged[key] = isObject(value) && isObject(earlier[key]) ? { ...(earlier[key] as Json), ...value } : value;\n }\n return merged;\n}\n\n/**\n * The gateway's `Usage` for an Anthropic usage object. Cache writes reported without their TTL split count as\n * `fallbackTtl`, the TTL the request asked for.\n */\nexport function anthropicUsage(raw: Json, fallbackTtl: \"5m\" | \"1h\"): Usage {\n const split = isObject(raw.cache_creation) ? raw.cache_creation : undefined;\n const written = count(raw.cache_creation_input_tokens);\n const cacheWrite = split\n ? { \"5m\": count(split.ephemeral_5m_input_tokens), \"1h\": count(split.ephemeral_1h_input_tokens) }\n : { \"5m\": fallbackTtl === \"5m\" ? written : 0, \"1h\": fallbackTtl === \"1h\" ? written : 0 };\n const output = count(raw.output_tokens);\n const details = isObject(raw.output_tokens_details) ? raw.output_tokens_details : {};\n return {\n uncachedInput: count(raw.input_tokens),\n cacheRead: count(raw.cache_read_input_tokens),\n cacheWrite,\n output,\n // Reasoning is a part of output; the reference guarantees it never exceeds it, and the cap keeps that true.\n reasoning: Math.min(count(details.thinking_tokens), output),\n raw,\n };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { ModelAdapter } from "../../spec.js";
2
+ import { type OpenAIChatConfig } from "./compat.js";
3
+ /**
4
+ * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to
5
+ * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from
6
+ * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to
7
+ * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.
8
+ *
9
+ * The adapter reports the provider `config.provider`, `"openai"` by default, which is the name `createModel()` looks
10
+ * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and
11
+ * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`
12
+ * sets; a direct call without them uses `defaultCaps`, which send no images.
13
+ *
14
+ * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or
15
+ * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as
16
+ * `reasoning_effort`.
17
+ */
18
+ export declare function openaiChat(config: OpenAIChatConfig): ModelAdapter;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `openaiChat()`: the OpenAI-compatible Chat Completions adapter over the gateway's `Transport` (D2). It streams every
3
+ * call and posts to `{baseURL}/chat/completions` with `Authorization: Bearer <apiKey>`, as openai-node v7.49.0 does
4
+ * (`src/client.ts`, `src/resources/chat/completions/completions.ts`, as of November 2026). The quirks of other
5
+ * compatible servers come in through `ChatCompat` flags, per adapter or per model.
6
+ */
7
+ import { resolveProviderConfig } from "../../provider-config.js";
8
+ import { payloadOf, readEventStream, sendRequest } from "../wire.js";
9
+ import { compatFor } from "./compat.js";
10
+ import { failureEvent, failureFromResponse } from "./failure.js";
11
+ import { buildRequest } from "./request.js";
12
+ import { ChunkAssembler } from "./response.js";
13
+ const DEFAULT_BASE_URL = "https://api.openai.com/v1";
14
+ // The adapter's `defaultCaps`, for a model with no catalog entry. An unknown model behind a compatible server may
15
+ // read text only and may reject reasoning settings, so it is sent no images and asked for no reasoning.
16
+ const DEFAULT_CAPS = { contextWindow: 128_000, maxOutputTokens: 16_384, images: false, reasoning: false };
17
+ // Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key
18
+ // the adapter sends.
19
+ const CALLER_HEADERS_DROPPED = new Set(["authorization", "api-key", "x-api-key"]);
20
+ function callerHeaders(headers) {
21
+ const rest = {};
22
+ for (const [name, value] of Object.entries(headers)) {
23
+ const lower = name.toLowerCase();
24
+ if (!CALLER_HEADERS_DROPPED.has(lower))
25
+ rest[lower] = value;
26
+ }
27
+ return rest;
28
+ }
29
+ function requestFor(config, body, signal) {
30
+ const headers = {
31
+ ...callerHeaders(config.headers),
32
+ "content-type": "application/json",
33
+ accept: "text/event-stream",
34
+ authorization: `Bearer ${config.apiKey}`,
35
+ };
36
+ const url = `${config.baseURL.replace(/\/+$/, "")}/chat/completions`;
37
+ return new Request(url, { method: "POST", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });
38
+ }
39
+ async function* streamCompletion(settings, resolved, model, context, options) {
40
+ yield { type: "start" };
41
+ const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS, compatFor(settings, model.id));
42
+ // Each attempt warns again; the gateway's retries stream a repeated warning only once per call.
43
+ yield* plan.warnings;
44
+ const request = requestFor(resolved, payloadOf(plan.body, options), options.signal);
45
+ const response = yield* sendRequest(resolved.transport, request, model, options.signal);
46
+ if (response === undefined)
47
+ return;
48
+ if (!response.ok) {
49
+ yield failureEvent(model, await failureFromResponse(response));
50
+ return;
51
+ }
52
+ yield* readEventStream(response, model, new ChunkAssembler(model, plan), options.signal);
53
+ }
54
+ /**
55
+ * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to
56
+ * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from
57
+ * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to
58
+ * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.
59
+ *
60
+ * The adapter reports the provider `config.provider`, `"openai"` by default, which is the name `createModel()` looks
61
+ * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and
62
+ * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`
63
+ * sets; a direct call without them uses `defaultCaps`, which send no images.
64
+ *
65
+ * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or
66
+ * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as
67
+ * `reasoning_effort`.
68
+ */
69
+ export function openaiChat(config) {
70
+ const resolved = resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL });
71
+ // Copied, so a caller who changes the objects later does not change the adapter's requests.
72
+ const settings = {
73
+ ...(config.compat ? { compat: { ...config.compat } } : {}),
74
+ ...(config.modelCompat
75
+ ? { modelCompat: Object.fromEntries(Object.entries(config.modelCompat).map(([id, own]) => [id, { ...own }])) }
76
+ : {}),
77
+ };
78
+ return {
79
+ specificationVersion: "v1",
80
+ api: "openai-chat",
81
+ provider: config.provider ?? "openai",
82
+ defaultCaps: DEFAULT_CAPS,
83
+ stream: (model, context, options) => streamCompletion(settings, resolved, model, context, options),
84
+ };
85
+ }
86
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/adapter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAA+B,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AAG9F,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAuB,SAAS,EAAyB,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,E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OAAO,EAAE,gBAAgB,EAAE,CAAC,CAAC;IAC9E,4FAA4F;IAC5F,MAAM,QAAQ,GAAmB;QAC/B,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC1D,GAAG,CAAC,MAAM,CAAC,WAAW;YACpB,CAAC,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,EAAE,EAAE,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE;YAC9G,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;IACF,OAAO;QACL,oBAAoB,EAAE,IAAI;QAC1B,GAAG,EAAE,aAAa;QAClB,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,QAAQ;QACrC,WAAW,EAAE,YAAY;QACzB,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC;KACnG,CAAC;AACJ,CAAC","sourcesContent":["/**\n * `openaiChat()`: the OpenAI-compatible Chat Completions adapter over the gateway's `Transport` (D2). It streams every\n * call and posts to `{baseURL}/chat/completions` with `Authorization: Bearer <apiKey>`, as openai-node v7.49.0 does\n * (`src/client.ts`, `src/resources/chat/completions/completions.ts`, as of November 2026). The quirks of other\n * compatible servers come in through `ChatCompat` flags, per adapter or per model.\n */\nimport { type ResolvedProviderConfig, resolveProviderConfig } from \"../../provider-config.js\";\nimport type { ModelAdapter, ModelEvent, StreamOptions } from \"../../spec.js\";\nimport type { ModelCaps, ModelContext, ModelRef } from \"../../types.js\";\nimport { payloadOf, readEventStream, sendRequest } from \"../wire.js\";\nimport { type CompatSettings, compatFor, type OpenAIChatConfig } from \"./compat.js\";\nimport { failureEvent, failureFromResponse } from \"./failure.js\";\nimport { buildRequest } from \"./request.js\";\nimport { ChunkAssembler } from \"./response.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.openai.com/v1\";\n\n// The adapter's `defaultCaps`, for a model with no catalog entry. An unknown model behind a compatible server may\n// read text only and may reject reasoning settings, so it is sent no images and asked for no reasoning.\nconst DEFAULT_CAPS: ModelCaps = { contextWindow: 128_000, maxOutputTokens: 16_384, images: false, reasoning: false };\n\n// Header names the adapter sets itself. A caller's key header is dropped, because `config.apiKey` is the only key\n// the adapter sends.\nconst CALLER_HEADERS_DROPPED = new Set([\"authorization\", \"api-key\", \"x-api-key\"]);\n\nfunction callerHeaders(headers: Readonly<Record<string, string>>): Record<string, string> {\n const rest: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n const lower = name.toLowerCase();\n if (!CALLER_HEADERS_DROPPED.has(lower)) rest[lower] = value;\n }\n return rest;\n}\n\nfunction requestFor(config: ResolvedProviderConfig, body: unknown, signal: AbortSignal | undefined): Request {\n const headers = {\n ...callerHeaders(config.headers),\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${config.apiKey}`,\n };\n const url = `${config.baseURL.replace(/\\/+$/, \"\")}/chat/completions`;\n return new Request(url, { method: \"POST\", headers, body: JSON.stringify(body), ...(signal ? { signal } : {}) });\n}\n\nasync function* streamCompletion(\n settings: CompatSettings,\n resolved: ResolvedProviderConfig,\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n): AsyncGenerator<ModelEvent> {\n yield { type: \"start\" };\n const plan = buildRequest(model, context, options, options.caps ?? DEFAULT_CAPS, compatFor(settings, model.id));\n // Each attempt warns again; the gateway's retries stream a repeated warning only once per call.\n yield* plan.warnings;\n const request = requestFor(resolved, payloadOf(plan.body, options), options.signal);\n const response = yield* sendRequest(resolved.transport, request, model, options.signal);\n if (response === undefined) return;\n if (!response.ok) {\n yield failureEvent(model, await failureFromResponse(response));\n return;\n }\n yield* readEventStream(response, model, new ChunkAssembler(model, plan), options.signal);\n}\n\n/**\n * Creates an adapter for OpenAI's Chat Completions API or a server compatible with it. Every request goes to\n * `{baseURL}/chat/completions` through `config.transport`, streams its response, and sends the key from\n * `config.apiKey` as a bearer token; it is the only key the adapter sends. `baseURL` defaults to\n * `https://api.openai.com/v1`. Throws a `GatewayError` with code `missing_api_key` when the key is missing or empty.\n *\n * The adapter reports the provider `config.provider`, `\"openai\"` by default, which is the name `createModel()` looks\n * the model up under in the price catalog. `config.compat` sets the server's quirks for every model, and\n * `config.modelCompat` for single models by id. The model's caps come from `options.caps`, which `createModel()`\n * sets; a direct call without them uses `defaultCaps`, which send no images.\n *\n * Caller headers from `config.headers` are sent with lower-case names; a caller `authorization`, `api-key` or\n * `x-api-key` is dropped. `providerOptions.openaiChat.extraBody` adds fields to the request body, such as\n * `reasoning_effort`.\n */\nexport function openaiChat(config: OpenAIChatConfig): ModelAdapter {\n const resolved = resolveProviderConfig(config, { baseURL: DEFAULT_BASE_URL });\n // Copied, so a caller who changes the objects later does not change the adapter's requests.\n const settings: CompatSettings = {\n ...(config.compat ? { compat: { ...config.compat } } : {}),\n ...(config.modelCompat\n ? { modelCompat: Object.fromEntries(Object.entries(config.modelCompat).map(([id, own]) => [id, { ...own }])) }\n : {}),\n };\n return {\n specificationVersion: \"v1\",\n api: \"openai-chat\",\n provider: config.provider ?? \"openai\",\n defaultCaps: DEFAULT_CAPS,\n stream: (model, context, options) => streamCompletion(settings, resolved, model, context, options),\n };\n}\n"]}
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The quirks of one OpenAI-compatible server or model, as flags (D2: one wire adapter serves many vendors, and their
3
+ * differences live in per-model data, as Pi's `compat` objects do). Every default is what OpenAI's own Chat
4
+ * Completions API accepts, as its parameters read in openai-node v7.49.0
5
+ * (`src/resources/chat/completions/completions.ts`, as of November 2026).
6
+ */
7
+ import type { ProviderConfig } from "../../runtime-types.js";
8
+ /** How one OpenAI-compatible server or model differs from OpenAI's own Chat Completions API. */
9
+ export interface ChatCompat {
10
+ /**
11
+ * The body field that carries the output limit. Defaults to `"max_completion_tokens"`; OpenAI deprecates
12
+ * `max_tokens` and says reasoning models do not accept it, but many compatible servers read only `max_tokens`.
13
+ */
14
+ readonly maxTokensField?: "max_completion_tokens" | "max_tokens";
15
+ /** The role the system prompt is sent as. Defaults to `"system"`, which every compatible server reads. */
16
+ readonly systemRole?: "system" | "developer";
17
+ /**
18
+ * Whether to ask for a final usage chunk with `stream_options: { include_usage: true }`. Defaults to `true`. A
19
+ * server that rejects the field needs `false`, and its replies then report no usage.
20
+ */
21
+ readonly streamUsage?: boolean;
22
+ /** Whether tools are sent with `strict: true` when their schema allows it. Defaults to `true`. */
23
+ readonly strictTools?: boolean;
24
+ /**
25
+ * Whether the model accepts `temperature`. Defaults to `true`; with `false`, a `temperature` you set is not sent and
26
+ * the call streams a warning.
27
+ */
28
+ readonly temperature?: boolean;
29
+ /**
30
+ * Whether the model takes explicit cache breakpoints (`prompt_cache_breakpoint` on content parts and
31
+ * `prompt_cache_options`), which OpenAI supports from `gpt-5.6`. Defaults to `false`, which leaves caching to the
32
+ * server's automatic prefix cache.
33
+ */
34
+ readonly cacheBreakpoints?: boolean;
35
+ /**
36
+ * Whether `cacheRetention: "long"` sends `prompt_cache_retention: "24h"`, for models before `gpt-5.6` that offer
37
+ * extended caching. Defaults to `false`.
38
+ */
39
+ readonly promptCacheRetention?: boolean;
40
+ }
41
+ /** The configuration `openaiChat()` takes: a `ProviderConfig` plus the server's name and quirks. */
42
+ export interface OpenAIChatConfig extends ProviderConfig {
43
+ /**
44
+ * The vendor name the adapter reports, which `createModel()` looks the model up under in the price catalog.
45
+ * Defaults to `"openai"`; set it for another OpenAI-compatible server.
46
+ */
47
+ readonly provider?: string;
48
+ /** Quirks that hold for every model behind this adapter. */
49
+ readonly compat?: ChatCompat;
50
+ /** Quirks for single models, by model id, which override `compat` flag by flag. */
51
+ readonly modelCompat?: Readonly<Record<string, ChatCompat>>;
52
+ }
53
+ /** The part of the configuration `compatFor()` reads. */
54
+ export type CompatSettings = Pick<OpenAIChatConfig, "compat" | "modelCompat">;
55
+ /** A `ChatCompat` with every flag set. */
56
+ export type ResolvedCompat = Required<ChatCompat>;
57
+ /** The flags for one model: its own entry over the adapter's, over the defaults. */
58
+ export declare function compatFor(config: CompatSettings, modelId: string): ResolvedCompat;