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

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 +305 -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 +27 -0
  9. package/dist/adapters/anthropic/failure.js +53 -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 +38 -0
  18. package/dist/adapters/anthropic/response.js +237 -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 +32 -0
  30. package/dist/adapters/openai-chat/failure.js +40 -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 +22 -0
  42. package/dist/adapters/openai-chat/usage.js +25 -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 +98 -0
  48. package/dist/adapters/wire.js +187 -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 +44 -0
  61. package/dist/cost.js +132 -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 +33 -0
  88. package/dist/retry.js +219 -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 +143 -0
  121. package/dist/types.js +6 -0
  122. package/dist/types.js.map +1 -0
  123. package/dist/usage.d.ts +16 -0
  124. package/dist/usage.js +31 -0
  125. package/dist/usage.js.map +1 -0
  126. package/package.json +50 -3
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at
3
+ * https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and
4
+ * `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of
5
+ * November 2026.
6
+ *
7
+ * - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold
8
+ * only text, so a result's images follow in one user message after the turn's results, and a failed result's text
9
+ * starts with `Error: `. The transcript's reasoning
10
+ * is never sent, because a Chat Completions message has no field for it.
11
+ * - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,
12
+ * and the plan keeps the original schema of each, so the reply's added nulls can be stripped.
13
+ * - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or
14
+ * tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: "24h"`; or neither,
15
+ * which leaves the server's automatic prefix cache.
16
+ */
17
+ import { createToolNameMap, TOOL_NAME_RULES } from "../../names.js";
18
+ import { transformMessages } from "../../transform-messages.js";
19
+ import { lowerToStrict } from "../strict-schema.js";
20
+ import { isObject } from "../wire.js";
21
+ // Strict function calling makes every property required, so an optional one becomes nullable. The formats, the kept
22
+ // and rejected keywords and the limits are those of Structured model outputs, "Supported schemas"
23
+ // (https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026), which
24
+ // does not list `prefixItems`, so a schema that uses it is sent without strict.
25
+ const STRICT_DIALECT = {
26
+ optional: "nullable",
27
+ formats: new Set(["date-time", "time", "date", "duration", "email", "hostname", "ipv4", "ipv6", "uuid"]),
28
+ objectRoot: true,
29
+ keeps: new Set(["minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum", "multipleOf", "minItems", "maxItems"]),
30
+ rejects: new Set(["allOf", "dependentRequired", "dependentSchemas", "if", "then", "else", "prefixItems"]),
31
+ limits: {
32
+ properties: 5000,
33
+ depth: 10,
34
+ enumValues: 1000,
35
+ stringLength: 120_000,
36
+ largeEnum: { values: 250, length: 15_000 },
37
+ },
38
+ };
39
+ const TOOL_IMAGES_NOTE = "The images below are part of the tool results above.";
40
+ /** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */
41
+ export function openaiChatOptions(options) {
42
+ const raw = options.providerOptions?.openaiChat;
43
+ if (!isObject(raw))
44
+ return {};
45
+ return isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {};
46
+ }
47
+ // Content -------------------------------------------------------------------------------------------------------------
48
+ function imagePart(block) {
49
+ return { type: "image_url", image_url: { url: `data:${block.mediaType};base64,${block.data}` } };
50
+ }
51
+ function contentPart(block) {
52
+ if (block.type === "text")
53
+ return block.text === "" ? [] : [{ type: "text", text: block.text }];
54
+ return block.type === "image" ? [imagePart(block)] : [];
55
+ }
56
+ /** A user message's content: a plain string for a single text block, which every compatible server reads. */
57
+ function userContent(blocks) {
58
+ const [only] = blocks;
59
+ if (blocks.length === 1 && only?.type === "text")
60
+ return only.text;
61
+ return blocks.flatMap(contentPart);
62
+ }
63
+ function assistantMessage(message, names) {
64
+ // Text blocks a reasoning block or a merged turn kept apart stay apart, as paragraphs.
65
+ const text = message.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n\n");
66
+ const toolCalls = message.content.flatMap((block) => {
67
+ if (block.type !== "tool_call")
68
+ return [];
69
+ // A call cut off by the output limit holds its partial JSON as a string; the wire needs a JSON object.
70
+ const input = isObject(block.input) ? block.input : {};
71
+ return [
72
+ {
73
+ id: block.callId,
74
+ type: "function",
75
+ function: { name: names.sanitize(block.name), arguments: JSON.stringify(input) },
76
+ },
77
+ ];
78
+ });
79
+ if (text === "" && toolCalls.length === 0)
80
+ return undefined;
81
+ return {
82
+ role: "assistant",
83
+ content: text === "" ? null : text,
84
+ ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
85
+ };
86
+ }
87
+ // A tool message has no error field, so a failed result says so in its text.
88
+ const TOOL_ERROR_PREFIX = "Error: ";
89
+ function toolMessage(message) {
90
+ const text = message.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
91
+ return { role: "tool", tool_call_id: message.callId, content: message.isError ? TOOL_ERROR_PREFIX + text : text };
92
+ }
93
+ /** Encodes the transcript; a run of tool results is followed by one user message with their images, if any. */
94
+ function encodeMessages(messages, names) {
95
+ const out = [];
96
+ let images = [];
97
+ const flushImages = () => {
98
+ if (images.length > 0)
99
+ out.push({ role: "user", content: [{ type: "text", text: TOOL_IMAGES_NOTE }, ...images] });
100
+ images = [];
101
+ };
102
+ for (const message of messages) {
103
+ if (message.role === "tool") {
104
+ out.push(toolMessage(message));
105
+ images.push(...message.content.flatMap((block) => (block.type === "image" ? [imagePart(block)] : [])));
106
+ continue;
107
+ }
108
+ flushImages();
109
+ const encoded = message.role === "user"
110
+ ? { role: "user", content: userContent(message.content) }
111
+ : assistantMessage(message, names);
112
+ if (encoded)
113
+ out.push(encoded);
114
+ }
115
+ flushImages();
116
+ return out;
117
+ }
118
+ // Caching ------------------------------------------------------------------------------------------------------------
119
+ /** Puts the breakpoint on the last content part of a message, turning string content into one text part. */
120
+ function markMessage(message, breakpoint) {
121
+ if (typeof message.content === "string") {
122
+ message.content = [{ type: "text", text: message.content, prompt_cache_breakpoint: breakpoint }];
123
+ return;
124
+ }
125
+ const last = Array.isArray(message.content) ? message.content.at(-1) : undefined;
126
+ if (isObject(last))
127
+ last.prompt_cache_breakpoint = breakpoint;
128
+ }
129
+ // Chat Completions caches for 30 minutes: its `prompt_cache_options.ttl` takes only "30m", and the 12-hour lifetime
130
+ // is offered in the Responses API (Prompt caching, "Cache lifetime",
131
+ // https://developers.openai.com/api/docs/guides/prompt-caching, as of November 2026).
132
+ const LONG_BREAKPOINTS_NOTE = 'cacheRetention "long" asks for a 12-hour cache, which Chat Completions does not offer, ' +
133
+ "so the request was sent with 30-minute breakpoints.";
134
+ /** The caching fields for the body, after marking the messages that take a breakpoint. */
135
+ function applyCaching(messages, retention, compat) {
136
+ if (compat.cacheBreakpoints) {
137
+ // Explicit mode with no breakpoint turns caching off; implicit mode adds the server's own breakpoint to ours.
138
+ if (retention === "none")
139
+ return { fields: { prompt_cache_options: { mode: "explicit" } }, warnings: [] };
140
+ const system = messages[0]?.role === compat.systemRole ? messages[0] : undefined;
141
+ const newest = messages.findLast((message) => message.role === "user" || message.role === "tool");
142
+ for (const message of new Set([system, newest]))
143
+ if (message)
144
+ markMessage(message, { mode: "explicit" });
145
+ return { fields: {}, warnings: retention === "long" ? [warning(LONG_BREAKPOINTS_NOTE)] : [] };
146
+ }
147
+ const fields = retention === "long" && compat.promptCacheRetention ? { prompt_cache_retention: "24h" } : {};
148
+ return { fields, warnings: [] };
149
+ }
150
+ // Tools --------------------------------------------------------------------------------------------------------------
151
+ function encodeTools(tools, names, compat) {
152
+ const strictSchemas = new Map();
153
+ const encoded = tools.map((tool) => {
154
+ const strict = compat.strictTools ? lowerToStrict(tool.inputSchema, STRICT_DIALECT) : undefined;
155
+ if (strict)
156
+ strictSchemas.set(tool.name, tool.inputSchema);
157
+ const definition = {
158
+ name: names.sanitize(tool.name),
159
+ ...(tool.description ? { description: tool.description } : {}),
160
+ parameters: strict ? strict.schema : tool.inputSchema,
161
+ ...(strict ? { strict: true } : {}),
162
+ };
163
+ return { type: "function", function: definition };
164
+ });
165
+ return { encoded, strictSchemas };
166
+ }
167
+ // The body -----------------------------------------------------------------------------------------------------------
168
+ function toolNames(context, messages) {
169
+ const called = messages.flatMap((message) => message.role === "assistant" ? message.content.flatMap((b) => (b.type === "tool_call" ? [b.name] : [])) : []);
170
+ return [...context.tools.map((tool) => tool.name), ...called];
171
+ }
172
+ function warning(message) {
173
+ return { type: "warning", code: "unsupported_option", message };
174
+ }
175
+ /** The adapter's own fields over the caller's extras, with a warning naming any extra they overrode. */
176
+ function mergeExtras(own, extras, owned) {
177
+ const overridden = owned.filter((key) => key in extras);
178
+ const body = { ...extras, ...own };
179
+ for (const key of owned)
180
+ if (!(key in own))
181
+ delete body[key];
182
+ const warnings = overridden.length === 0
183
+ ? []
184
+ : [
185
+ warning(`providerOptions.openaiChat.extraBody cannot set ${overridden.join(", ")}, ` +
186
+ "which the adapter sets itself, so those extraBody values were not sent."),
187
+ ];
188
+ return { body, warnings };
189
+ }
190
+ function samplingFields(options, model, compat) {
191
+ if (options.temperature === undefined)
192
+ return { fields: {}, warnings: [] };
193
+ if (compat.temperature)
194
+ return { fields: { temperature: options.temperature }, warnings: [] };
195
+ const text = `${model.id} does not accept temperature, so the request was sent without it.`;
196
+ return { fields: {}, warnings: [warning(text)] };
197
+ }
198
+ /** Builds one call's request body. */
199
+ export function buildRequest(model, context, options, caps, compat) {
200
+ const messages = transformMessages(context.messages, model, caps);
201
+ const names = createToolNameMap(TOOL_NAME_RULES.openaiChat, toolNames(context, messages));
202
+ const system = context.system === "" ? [] : [{ role: compat.systemRole, content: context.system }];
203
+ const wireMessages = [...system, ...encodeMessages(messages, names)];
204
+ const caching = applyCaching(wireMessages, options.cacheRetention, compat);
205
+ const tools = encodeTools(context.tools, names, compat);
206
+ const sampling = samplingFields(options, model, compat);
207
+ const own = {
208
+ model: model.id,
209
+ stream: true,
210
+ ...(compat.streamUsage ? { stream_options: { include_usage: true } } : {}),
211
+ messages: wireMessages,
212
+ ...(tools.encoded.length > 0 ? { tools: tools.encoded } : {}),
213
+ [compat.maxTokensField]: options.maxOutputTokens ?? caps.maxOutputTokens,
214
+ ...sampling.fields,
215
+ ...caching.fields,
216
+ };
217
+ // Both output-limit fields, so an extra cannot send a second limit beside the adapter's.
218
+ const owned = ["model", "stream", "stream_options", "messages", "tools", "max_completion_tokens", "max_tokens"];
219
+ const { body, warnings } = mergeExtras(own, openaiChatOptions(options).extraBody ?? {}, owned);
220
+ return {
221
+ body,
222
+ warnings: [...sampling.warnings, ...caching.warnings, ...warnings],
223
+ names,
224
+ strictSchemas: tools.strictSchemas,
225
+ };
226
+ }
227
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sourceR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AC;QAC1E,QAAQ,EAAE,YAAY;QACtB,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE,OAAO,CAAC,eAAe,IAAI,IAAI,CAAC,eAAe;QACxE,GAAG,QAAQ,CAAC,MAAM;QAClB,GAAG,OAAO,CAAC,MAAM;KAClB,CAAC;IACF,yFAAyF;IACzF,MAAM,KAAK,GAAG,CAAC,OAAO,EAAE,QAAQ,EAAE,gBAAgB,EAAE,UAAU,EAAE,OAAO,EAAE,uBAAuB,EAAE,YAAY,CAAC,CAAC;IAChH,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,WAAW,CAAC,GAAG,EAAE,iBAAiB,CAAC,OAAO,CAAC,CAAC,SAAS,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;IAC/F,OAAO;QACL,IAAI;QACJ,QAAQ,EAAE,CAAC,GAAG,QAAQ,CAAC,QAAQ,EAAE,GAAG,OAAO,CAAC,QAAQ,EAAE,GAAG,QAAQ,CAAC;QAClE,KAAK;QACL,aAAa,EAAE,KAAK,CAAC,aAAa;KACnC,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Builds the Chat Completions request body from a `ModelContext`. Every field below follows the API reference at\n * https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create and\n * `ChatCompletionCreateParams` in openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`), both as of\n * November 2026.\n *\n * - Messages pass through `transformMessages()` first. A tool result becomes a `tool` message, whose content can hold\n * only text, so a result's images follow in one user message after the turn's results, and a failed result's text\n * starts with `Error: `. The transcript's reasoning\n * is never sent, because a Chat Completions message has no field for it.\n * - Tool names go through the run's `ToolNameMap`. A tool is sent with `strict: true` when its schema can be lowered,\n * and the plan keeps the original schema of each, so the reply's added nulls can be stripped.\n * - Caching follows the model's `ChatCompat` flags: explicit breakpoints on the system prompt and the newest user or\n * tool message, with the 30-minute lifetime Chat Completions offers; `prompt_cache_retention: \"24h\"`; or neither,\n * which leaves the server's automatic prefix cache.\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, ModelContext, ModelRef, WireTool } from \"../../types.js\";\nimport { lowerToStrict, type StrictDialect } from \"../strict-schema.js\";\nimport { isObject, type Json } from \"../wire.js\";\nimport type { ResolvedCompat } from \"./compat.js\";\n\ntype Warning = Extract<ModelEvent, { type: \"warning\" }>;\n\n/** What the adapter reads from `providerOptions.openaiChat`. */\nexport interface OpenAIChatProviderOptions {\n /**\n * Extra fields for the request body, such as `reasoning_effort`, `prompt_cache_key` or `parallel_tool_calls`. The\n * fields the adapter sets itself (`model`, `stream`, `stream_options`, `messages`, `tools`, `max_completion_tokens`\n * and `max_tokens`) win over these: an `extraBody` value for one is not sent, and the call streams an\n * `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 original input schema of each tool sent strict, by tool name. */\n readonly strictSchemas: ReadonlyMap<string, Json>;\n}\n\n// Strict function calling makes every property required, so an optional one becomes nullable. The formats, the kept\n// and rejected keywords and the limits are those of Structured model outputs, \"Supported schemas\"\n// (https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas, as of November 2026), which\n// does not list `prefixItems`, so a schema that uses it is sent without strict.\nconst STRICT_DIALECT: StrictDialect = {\n optional: \"nullable\",\n formats: new Set([\"date-time\", \"time\", \"date\", \"duration\", \"email\", \"hostname\", \"ipv4\", \"ipv6\", \"uuid\"]),\n objectRoot: true,\n keeps: new Set([\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\", \"multipleOf\", \"minItems\", \"maxItems\"]),\n rejects: new Set([\"allOf\", \"dependentRequired\", \"dependentSchemas\", \"if\", \"then\", \"else\", \"prefixItems\"]),\n limits: {\n properties: 5000,\n depth: 10,\n enumValues: 1000,\n stringLength: 120_000,\n largeEnum: { values: 250, length: 15_000 },\n },\n};\n\nconst TOOL_IMAGES_NOTE = \"The images below are part of the tool results above.\";\n\n/** Reads `providerOptions.openaiChat`, ignoring fields of the wrong type. */\nexport function openaiChatOptions(options: StreamOptions): OpenAIChatProviderOptions {\n const raw = options.providerOptions?.openaiChat;\n if (!isObject(raw)) return {};\n return isObject(raw.extraBody) ? { extraBody: raw.extraBody } : {};\n}\n\n// Content -------------------------------------------------------------------------------------------------------------\n\nfunction imagePart(block: Extract<ContentBlock, { type: \"image\" }>): Json {\n return { type: \"image_url\", image_url: { url: `data:${block.mediaType};base64,${block.data}` } };\n}\n\nfunction contentPart(block: ContentBlock): Json[] {\n if (block.type === \"text\") return block.text === \"\" ? [] : [{ type: \"text\", text: block.text }];\n return block.type === \"image\" ? [imagePart(block)] : [];\n}\n\n/** A user message's content: a plain string for a single text block, which every compatible server reads. */\nfunction userContent(blocks: readonly ContentBlock[]): string | Json[] {\n const [only] = blocks;\n if (blocks.length === 1 && only?.type === \"text\") return only.text;\n return blocks.flatMap(contentPart);\n}\n\nfunction assistantMessage(message: Extract<Message, { role: \"assistant\" }>, names: ToolNameMap): Json | undefined {\n // Text blocks a reasoning block or a merged turn kept apart stay apart, as paragraphs.\n const text = message.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\\n\");\n const toolCalls = message.content.flatMap((block): Json[] => {\n if (block.type !== \"tool_call\") return [];\n // A call cut off by the output limit holds its partial JSON as a string; the wire needs a JSON object.\n const input = isObject(block.input) ? block.input : {};\n return [\n {\n id: block.callId,\n type: \"function\",\n function: { name: names.sanitize(block.name), arguments: JSON.stringify(input) },\n },\n ];\n });\n if (text === \"\" && toolCalls.length === 0) return undefined;\n return {\n role: \"assistant\",\n content: text === \"\" ? null : text,\n ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n };\n}\n\n// A tool message has no error field, so a failed result says so in its text.\nconst TOOL_ERROR_PREFIX = \"Error: \";\n\nfunction toolMessage(message: Extract<Message, { role: \"tool\" }>): Json {\n const text = message.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n return { role: \"tool\", tool_call_id: message.callId, content: message.isError ? TOOL_ERROR_PREFIX + text : text };\n}\n\n/** Encodes the transcript; a run of tool results is followed by one user message with their images, if any. */\nfunction encodeMessages(messages: readonly Message[], names: ToolNameMap): Json[] {\n const out: Json[] = [];\n let images: Json[] = [];\n const flushImages = () => {\n if (images.length > 0) out.push({ role: \"user\", content: [{ type: \"text\", text: TOOL_IMAGES_NOTE }, ...images] });\n images = [];\n };\n for (const message of messages) {\n if (message.role === \"tool\") {\n out.push(toolMessage(message));\n images.push(...message.content.flatMap((block) => (block.type === \"image\" ? [imagePart(block)] : [])));\n continue;\n }\n flushImages();\n const encoded =\n message.role === \"user\"\n ? { role: \"user\", content: userContent(message.content) }\n : assistantMessage(message, names);\n if (encoded) out.push(encoded);\n }\n flushImages();\n return out;\n}\n\n// Caching ------------------------------------------------------------------------------------------------------------\n\n/** Puts the breakpoint on the last content part of a message, turning string content into one text part. */\nfunction markMessage(message: Json, breakpoint: Json): void {\n if (typeof message.content === \"string\") {\n message.content = [{ type: \"text\", text: message.content, prompt_cache_breakpoint: breakpoint }];\n return;\n }\n const last = Array.isArray(message.content) ? message.content.at(-1) : undefined;\n if (isObject(last)) last.prompt_cache_breakpoint = breakpoint;\n}\n\n// Chat Completions caches for 30 minutes: its `prompt_cache_options.ttl` takes only \"30m\", and the 12-hour lifetime\n// is offered in the Responses API (Prompt caching, \"Cache lifetime\",\n// https://developers.openai.com/api/docs/guides/prompt-caching, as of November 2026).\nconst LONG_BREAKPOINTS_NOTE =\n 'cacheRetention \"long\" asks for a 12-hour cache, which Chat Completions does not offer, ' +\n \"so the request was sent with 30-minute breakpoints.\";\n\n/** The caching fields for the body, after marking the messages that take a breakpoint. */\nfunction applyCaching(\n messages: Json[],\n retention: StreamOptions[\"cacheRetention\"],\n compat: ResolvedCompat,\n): { fields: Json; warnings: Warning[] } {\n if (compat.cacheBreakpoints) {\n // Explicit mode with no breakpoint turns caching off; implicit mode adds the server's own breakpoint to ours.\n if (retention === \"none\") return { fields: { prompt_cache_options: { mode: \"explicit\" } }, warnings: [] };\n const system = messages[0]?.role === compat.systemRole ? messages[0] : undefined;\n const newest = messages.findLast((message) => message.role === \"user\" || message.role === \"tool\");\n for (const message of new Set([system, newest])) if (message) markMessage(message, { mode: \"explicit\" });\n return { fields: {}, warnings: retention === \"long\" ? [warning(LONG_BREAKPOINTS_NOTE)] : [] };\n }\n const fields = retention === \"long\" && compat.promptCacheRetention ? { prompt_cache_retention: \"24h\" } : {};\n return { fields, warnings: [] };\n}\n\n// Tools --------------------------------------------------------------------------------------------------------------\n\nfunction encodeTools(tools: readonly WireTool[], names: ToolNameMap, compat: ResolvedCompat) {\n const strictSchemas = new Map<string, Json>();\n const encoded = tools.map((tool): Json => {\n const strict = compat.strictTools ? lowerToStrict(tool.inputSchema, STRICT_DIALECT) : undefined;\n if (strict) strictSchemas.set(tool.name, tool.inputSchema);\n const definition: Json = {\n name: names.sanitize(tool.name),\n ...(tool.description ? { description: tool.description } : {}),\n parameters: strict ? strict.schema : tool.inputSchema,\n ...(strict ? { strict: true } : {}),\n };\n return { type: \"function\", function: definition };\n });\n return { encoded, strictSchemas };\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\nfunction warning(message: string): Warning {\n return { type: \"warning\", code: \"unsupported_option\", message };\n}\n\n/** The adapter's own fields over the caller's extras, with a warning naming any extra they overrode. */\nfunction mergeExtras(own: Json, extras: Readonly<Json>, owned: readonly string[]): { body: Json; warnings: Warning[] } {\n const overridden = owned.filter((key) => key in extras);\n const body: Json = { ...extras, ...own };\n for (const key of owned) if (!(key in own)) delete body[key];\n const warnings =\n overridden.length === 0\n ? []\n : [\n warning(\n `providerOptions.openaiChat.extraBody cannot set ${overridden.join(\", \")}, ` +\n \"which the adapter sets itself, so those extraBody values were not sent.\",\n ),\n ];\n return { body, warnings };\n}\n\nfunction samplingFields(options: StreamOptions, model: ModelRef, compat: ResolvedCompat) {\n if (options.temperature === undefined) return { fields: {}, warnings: [] };\n if (compat.temperature) return { fields: { temperature: options.temperature }, warnings: [] };\n const text = `${model.id} does not accept temperature, so the request was sent without it.`;\n return { fields: {}, warnings: [warning(text)] };\n}\n\n/** Builds one call's request body. */\nexport function buildRequest(\n model: ModelRef,\n context: ModelContext,\n options: StreamOptions,\n caps: ModelCaps,\n compat: ResolvedCompat,\n): RequestPlan {\n const messages = transformMessages(context.messages, model, caps);\n const names = createToolNameMap(TOOL_NAME_RULES.openaiChat, toolNames(context, messages));\n const system = context.system === \"\" ? [] : [{ role: compat.systemRole, content: context.system }];\n const wireMessages = [...system, ...encodeMessages(messages, names)];\n const caching = applyCaching(wireMessages, options.cacheRetention, compat);\n const tools = encodeTools(context.tools, names, compat);\n const sampling = samplingFields(options, model, compat);\n const own: Json = {\n model: model.id,\n stream: true,\n ...(compat.streamUsage ? { stream_options: { include_usage: true } } : {}),\n messages: wireMessages,\n ...(tools.encoded.length > 0 ? { tools: tools.encoded } : {}),\n [compat.maxTokensField]: options.maxOutputTokens ?? caps.maxOutputTokens,\n ...sampling.fields,\n ...caching.fields,\n };\n // Both output-limit fields, so an extra cannot send a second limit beside the adapter's.\n const owned = [\"model\", \"stream\", \"stream_options\", \"messages\", \"tools\", \"max_completion_tokens\", \"max_tokens\"];\n const { body, warnings } = mergeExtras(own, openaiChatOptions(options).extraBody ?? {}, owned);\n return {\n body,\n warnings: [...sampling.warnings, ...caching.warnings, ...warnings],\n names,\n strictSchemas: tools.strictSchemas,\n };\n}\n"]}
@@ -0,0 +1,22 @@
1
+ import type { ModelEvent } from "../../spec.js";
2
+ import type { ServerSentEvent } from "../../sse.js";
3
+ import type { ContentBlock, ModelRef, Usage } from "../../types.js";
4
+ import { type StreamReader } from "../wire.js";
5
+ import type { RequestPlan } from "./request.js";
6
+ /** One stream's state: the blocks so far, the usage and the finish reason. */
7
+ export declare class ChunkAssembler implements StreamReader {
8
+ #private;
9
+ constructor(model: ModelRef, plan: Pick<RequestPlan, "names" | "strictSchemas">);
10
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
11
+ handle(sse: ServerSentEvent): ModelEvent[];
12
+ /**
13
+ * A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because
14
+ * some compatible servers never send `[DONE]`; any other is a retryable failure.
15
+ */
16
+ ended(): ModelEvent[];
17
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
18
+ partial(): {
19
+ content: ContentBlock[];
20
+ usage: Usage;
21
+ };
22
+ }
@@ -0,0 +1,203 @@
1
+ import { stripAddedNulls } from "../strict-schema.js";
2
+ import { isObject, parseToolInput, str, terminalMessage } from "../wire.js";
3
+ import { failureEvent, failureFrom } from "./failure.js";
4
+ import { openaiUsage } from "./usage.js";
5
+ // Each wire finish reason as the gateway's. `content_filter` is handled apart, as a failure.
6
+ const STOP_REASONS = {
7
+ stop: "stop",
8
+ length: "length",
9
+ tool_calls: "tool_calls",
10
+ function_call: "tool_calls",
11
+ };
12
+ /**
13
+ * An error chunk as the `{ error: { message, ... } }` body `failureFrom()` reads. A compatible server may send the
14
+ * error object bare, or only its message as a string.
15
+ */
16
+ function errorBody(chunk) {
17
+ if (isObject(chunk) && isObject(chunk.error))
18
+ return chunk;
19
+ if (isObject(chunk) && typeof chunk.error === "string")
20
+ return { error: { message: chunk.error } };
21
+ if (typeof chunk === "string")
22
+ return { error: { message: chunk } };
23
+ return isObject(chunk) ? { error: chunk } : {};
24
+ }
25
+ /** An error event's data: JSON when it parses, else its text, which some compatible servers send bare. */
26
+ function parseErrorData(data) {
27
+ try {
28
+ return JSON.parse(data);
29
+ }
30
+ catch {
31
+ return data;
32
+ }
33
+ }
34
+ /** One stream's state: the blocks so far, the usage and the finish reason. */
35
+ export class ChunkAssembler {
36
+ #model;
37
+ #names;
38
+ #strictSchemas;
39
+ #open = new Map();
40
+ #closed = new Map();
41
+ // The block index of each wire tool-call index, and of the open text and reasoning blocks.
42
+ #tools = new Map();
43
+ #text;
44
+ #reasoning;
45
+ #nextIndex = 0;
46
+ #usage = null;
47
+ #finish = "";
48
+ #refusal = "";
49
+ constructor(model, plan) {
50
+ this.#model = model;
51
+ this.#names = plan.names;
52
+ this.#strictSchemas = plan.strictSchemas;
53
+ }
54
+ /** The events one server-sent event produces. The last one is the terminal when the stream has ended. */
55
+ handle(sse) {
56
+ if (sse.data.trim() === "[DONE]")
57
+ return this.#terminal();
58
+ const chunk = sse.event === "error" ? parseErrorData(sse.data) : JSON.parse(sse.data);
59
+ if (sse.event === "error" || (isObject(chunk) && (isObject(chunk.error) || typeof chunk.error === "string"))) {
60
+ return [failureEvent(this.#model, failureFrom(errorBody(chunk), undefined, "stream error"), this.partial())];
61
+ }
62
+ if (!isObject(chunk))
63
+ return [];
64
+ if (isObject(chunk.usage))
65
+ this.#usage = chunk.usage;
66
+ const choices = Array.isArray(chunk.choices) ? chunk.choices.filter(isObject) : [];
67
+ // The adapter never asks for more than one choice, so it reads the first.
68
+ const choice = choices.find((entry) => entry.index === 0) ?? choices[0];
69
+ if (choice === undefined)
70
+ return [];
71
+ if (typeof choice.finish_reason === "string")
72
+ this.#finish = choice.finish_reason;
73
+ return isObject(choice.delta) ? this.#delta(choice.delta) : [];
74
+ }
75
+ /**
76
+ * A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because
77
+ * some compatible servers never send `[DONE]`; any other is a retryable failure.
78
+ */
79
+ ended() {
80
+ if (this.#finish !== "")
81
+ return this.#terminal();
82
+ return [failureEvent(this.#model, { message: "the stream ended before [DONE]" }, this.partial())];
83
+ }
84
+ /** The content and usage so far, open blocks included, for an `error` terminal. */
85
+ partial() {
86
+ const open = [...this.#open].map(([index, block]) => [index, this.#finishBlock(block)]);
87
+ const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);
88
+ return { content, usage: openaiUsage(this.#usage) };
89
+ }
90
+ #delta(delta) {
91
+ const events = [];
92
+ const reasoning = str(delta.reasoning_content) || str(delta.reasoning);
93
+ if (reasoning !== "")
94
+ events.push(...this.#appendProse("reasoning", reasoning));
95
+ const content = str(delta.content);
96
+ if (content !== "")
97
+ events.push(...this.#appendProse("text", content));
98
+ this.#refusal += str(delta.refusal);
99
+ const calls = Array.isArray(delta.tool_calls) ? delta.tool_calls.filter(isObject) : [];
100
+ for (const call of calls)
101
+ events.push(...this.#appendToolCall(call));
102
+ return events;
103
+ }
104
+ /** Adds text or reasoning to its open block, opening one first and closing the other kind. */
105
+ #appendProse(kind, text) {
106
+ const events = this.#closeIndex(kind === "text" ? this.#reasoning : this.#text);
107
+ let index = kind === "text" ? this.#text : this.#reasoning;
108
+ if (index === undefined) {
109
+ index = this.#openBlock({ kind, text: "" });
110
+ if (kind === "text")
111
+ this.#text = index;
112
+ else
113
+ this.#reasoning = index;
114
+ events.push({ type: `${kind}_start`, index });
115
+ }
116
+ const open = this.#open.get(index);
117
+ if (open)
118
+ open.text += text;
119
+ events.push({ type: `${kind}_delta`, index, delta: text });
120
+ return events;
121
+ }
122
+ #appendToolCall(call) {
123
+ const wireIndex = typeof call.index === "number" ? call.index : 0;
124
+ const fn = isObject(call.function) ? call.function : {};
125
+ const id = str(call.id);
126
+ const events = [];
127
+ let index = this.#tools.get(wireIndex);
128
+ // A server that leaves out `index` sends each call whole under its own id, so a new id starts a new call.
129
+ const current = index === undefined ? undefined : this.#open.get(index);
130
+ if (id !== "" && current?.callId && current.callId !== id)
131
+ index = undefined;
132
+ if (index === undefined) {
133
+ events.push(...this.#closeIndex(this.#text), ...this.#closeIndex(this.#reasoning));
134
+ index = this.#openBlock({ kind: "tool_input", text: "", callId: id, name: str(fn.name) });
135
+ this.#tools.set(wireIndex, index);
136
+ events.push({ type: "tool_input_start", index });
137
+ }
138
+ const open = this.#open.get(index);
139
+ if (open === undefined)
140
+ return events;
141
+ // The first entry carries the id and name; a server that repeats them in later entries adds nothing.
142
+ if (!open.callId)
143
+ open.callId = id;
144
+ if (!open.name)
145
+ open.name = str(fn.name);
146
+ const args = str(fn.arguments);
147
+ if (args === "")
148
+ return events;
149
+ open.text += args;
150
+ events.push({ type: "tool_input_delta", index, delta: args });
151
+ return events;
152
+ }
153
+ #openBlock(block) {
154
+ const index = this.#nextIndex;
155
+ this.#nextIndex += 1;
156
+ this.#open.set(index, block);
157
+ return index;
158
+ }
159
+ #closeIndex(index) {
160
+ if (index === undefined)
161
+ return [];
162
+ const open = this.#open.get(index);
163
+ if (index === this.#text)
164
+ this.#text = undefined;
165
+ if (index === this.#reasoning)
166
+ this.#reasoning = undefined;
167
+ if (open === undefined)
168
+ return [];
169
+ this.#open.delete(index);
170
+ const block = this.#finishBlock(open);
171
+ this.#closed.set(index, block);
172
+ return [{ type: `${open.kind}_end`, index, block }];
173
+ }
174
+ #finishBlock(open) {
175
+ if (open.kind === "text")
176
+ return { type: "text", text: open.text };
177
+ if (open.kind === "reasoning")
178
+ return { type: "reasoning", text: open.text };
179
+ const wire = open.name ?? "";
180
+ const name = this.#names.restore(wire) ?? wire;
181
+ const input = parseToolInput(open.text);
182
+ const schema = this.#strictSchemas.get(name);
183
+ // A call cut off by the output limit keeps its partial JSON text as it arrived.
184
+ const stripped = schema === undefined || typeof input === "string" ? input : stripAddedNulls(input, schema);
185
+ return { type: "tool_call", callId: open.callId ?? "", name, input: stripped };
186
+ }
187
+ #terminal() {
188
+ const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#closeIndex(index));
189
+ const { content, usage } = this.partial();
190
+ if (this.#finish === "content_filter" || this.#refusal !== "") {
191
+ const message = this.#refusal !== ""
192
+ ? `refusal: ${this.#refusal}`
193
+ : "content_filter: the provider's content filter omitted all or part of the reply";
194
+ return [...closing, failureEvent(this.#model, { message, kind: "fatal" }, { content, usage })];
195
+ }
196
+ const hasCalls = content.some((block) => block.type === "tool_call");
197
+ const mapped = STOP_REASONS[this.#finish] ?? "stop";
198
+ // Some compatible servers end a reply that calls tools with "stop"; the calls still need their results.
199
+ const stopReason = mapped === "stop" && hasCalls ? "tool_calls" : mapped;
200
+ return [...closing, { type: "done", message: terminalMessage(this.#model, { content, usage }, stopReason) }];
201
+ }
202
+ }
203
+ //# sourceMappingURL=response.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"response.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/response.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAa,cAAc,EAAqB,GAAG,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEzD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAWzC,6FAA6F;AAC7F,MAAM,YAAY,GAA6D;IAC7E,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;IAChB,UAAU,EAAE,YAAY;IACxB,aAAa,EAAE,YAAY;CAC5B,CAAC;AAEF;;;GAGG;AACH,SAAS,SAAS,CAAC,KAAc;IAC/B,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3D,IAAI,QAAQ,CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ;QAAE,OAAO,E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AC,CAAC;QACjG,CAAC;QACD,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC;QACpD,wGAAwG;QACxG,MAAM,UAAU,GAAG,MAAM,KAAK,MAAM,IAAI,QAAQ,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC;QACzE,OAAO,CAAC,GAAG,OAAO,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;IAC/G,CAAC;CACF","sourcesContent":["/**\n * Turns a Chat Completions stream into `ModelEvent`s, from `ChatCompletionChunk` and the stream reader in\n * openai-node v7.49.0 (`src/resources/chat/completions/completions.ts`, `src/core/streaming.ts`, as of November 2026).\n * Each server-sent event's data is one chunk; `data: [DONE]` ends the stream. A chunk's `choices[0].delta` carries\n * text in `content`, a refusal in `refusal`, and tool calls in `tool_calls`, each entry keyed by its `index`, with\n * the `id` and `function.name` in its first entry and `function.arguments` streamed in pieces. `finish_reason` arrives\n * on the last chunk with a choice. With `stream_options.include_usage`, one more chunk, with empty `choices`, carries\n * the `usage` of the whole request before `[DONE]`.\n *\n * OpenAI's models stream no reasoning text, only a count of reasoning tokens. Several compatible servers stream it as\n * `delta.reasoning_content` or `delta.reasoning`, which becomes an unsigned reasoning block.\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 { stripAddedNulls } from \"../strict-schema.js\";\nimport { isObject, type Json, parseToolInput, type StreamReader, str, terminalMessage } from \"../wire.js\";\nimport { failureEvent, failureFrom } from \"./failure.js\";\nimport type { RequestPlan } from \"./request.js\";\nimport { openaiUsage } from \"./usage.js\";\n\ntype BlockKind = \"text\" | \"reasoning\" | \"tool_input\";\n\ninterface OpenBlock {\n readonly kind: BlockKind;\n text: string;\n callId?: string;\n name?: string;\n}\n\n// Each wire finish reason as the gateway's. `content_filter` is handled apart, as a failure.\nconst STOP_REASONS: Readonly<Record<string, AssistantMessage[\"stopReason\"]>> = {\n stop: \"stop\",\n length: \"length\",\n tool_calls: \"tool_calls\",\n function_call: \"tool_calls\",\n};\n\n/**\n * An error chunk as the `{ error: { message, ... } }` body `failureFrom()` reads. A compatible server may send the\n * error object bare, or only its message as a string.\n */\nfunction errorBody(chunk: unknown): Json {\n if (isObject(chunk) && isObject(chunk.error)) return chunk;\n if (isObject(chunk) && typeof chunk.error === \"string\") return { error: { message: chunk.error } };\n if (typeof chunk === \"string\") return { error: { message: chunk } };\n return isObject(chunk) ? { error: chunk } : {};\n}\n\n/** An error event's data: JSON when it parses, else its text, which some compatible servers send bare. */\nfunction parseErrorData(data: string): unknown {\n try {\n return JSON.parse(data);\n } catch {\n return data;\n }\n}\n\n/** One stream's state: the blocks so far, the usage and the finish reason. */\nexport class ChunkAssembler implements StreamReader {\n readonly #model: ModelRef;\n readonly #names: ToolNameMap;\n readonly #strictSchemas: ReadonlyMap<string, Json>;\n readonly #open = new Map<number, OpenBlock>();\n readonly #closed = new Map<number, ContentBlock>();\n // The block index of each wire tool-call index, and of the open text and reasoning blocks.\n readonly #tools = new Map<number, number>();\n #text: number | undefined;\n #reasoning: number | undefined;\n #nextIndex = 0;\n #usage: unknown = null;\n #finish = \"\";\n #refusal = \"\";\n\n constructor(model: ModelRef, plan: Pick<RequestPlan, \"names\" | \"strictSchemas\">) {\n this.#model = model;\n this.#names = plan.names;\n this.#strictSchemas = plan.strictSchemas;\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 if (sse.data.trim() === \"[DONE]\") return this.#terminal();\n const chunk: unknown = sse.event === \"error\" ? parseErrorData(sse.data) : JSON.parse(sse.data);\n if (sse.event === \"error\" || (isObject(chunk) && (isObject(chunk.error) || typeof chunk.error === \"string\"))) {\n return [failureEvent(this.#model, failureFrom(errorBody(chunk), undefined, \"stream error\"), this.partial())];\n }\n if (!isObject(chunk)) return [];\n if (isObject(chunk.usage)) this.#usage = chunk.usage;\n const choices = Array.isArray(chunk.choices) ? chunk.choices.filter(isObject) : [];\n // The adapter never asks for more than one choice, so it reads the first.\n const choice = choices.find((entry) => entry.index === 0) ?? choices[0];\n if (choice === undefined) return [];\n if (typeof choice.finish_reason === \"string\") this.#finish = choice.finish_reason;\n return isObject(choice.delta) ? this.#delta(choice.delta) : [];\n }\n\n /**\n * A stream that closed without `[DONE]`. One that already sent its finish reason ends as it would have, because\n * some compatible servers never send `[DONE]`; any other is a retryable failure.\n */\n ended(): ModelEvent[] {\n if (this.#finish !== \"\") return this.#terminal();\n return [failureEvent(this.#model, { message: \"the stream ended before [DONE]\" }, this.partial())];\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.#finishBlock(block)] as const);\n const content = [...this.#closed, ...open].sort(([a], [b]) => a - b).map(([, block]) => block);\n return { content, usage: openaiUsage(this.#usage) };\n }\n\n #delta(delta: Json): ModelEvent[] {\n const events: ModelEvent[] = [];\n const reasoning = str(delta.reasoning_content) || str(delta.reasoning);\n if (reasoning !== \"\") events.push(...this.#appendProse(\"reasoning\", reasoning));\n const content = str(delta.content);\n if (content !== \"\") events.push(...this.#appendProse(\"text\", content));\n this.#refusal += str(delta.refusal);\n const calls = Array.isArray(delta.tool_calls) ? delta.tool_calls.filter(isObject) : [];\n for (const call of calls) events.push(...this.#appendToolCall(call));\n return events;\n }\n\n /** Adds text or reasoning to its open block, opening one first and closing the other kind. */\n #appendProse(kind: \"text\" | \"reasoning\", text: string): ModelEvent[] {\n const events = this.#closeIndex(kind === \"text\" ? this.#reasoning : this.#text);\n let index = kind === \"text\" ? this.#text : this.#reasoning;\n if (index === undefined) {\n index = this.#openBlock({ kind, text: \"\" });\n if (kind === \"text\") this.#text = index;\n else this.#reasoning = index;\n events.push({ type: `${kind}_start`, index });\n }\n const open = this.#open.get(index);\n if (open) open.text += text;\n events.push({ type: `${kind}_delta`, index, delta: text });\n return events;\n }\n\n #appendToolCall(call: Json): ModelEvent[] {\n const wireIndex = typeof call.index === \"number\" ? call.index : 0;\n const fn = isObject(call.function) ? call.function : {};\n const id = str(call.id);\n const events: ModelEvent[] = [];\n let index = this.#tools.get(wireIndex);\n // A server that leaves out `index` sends each call whole under its own id, so a new id starts a new call.\n const current = index === undefined ? undefined : this.#open.get(index);\n if (id !== \"\" && current?.callId && current.callId !== id) index = undefined;\n if (index === undefined) {\n events.push(...this.#closeIndex(this.#text), ...this.#closeIndex(this.#reasoning));\n index = this.#openBlock({ kind: \"tool_input\", text: \"\", callId: id, name: str(fn.name) });\n this.#tools.set(wireIndex, index);\n events.push({ type: \"tool_input_start\", index });\n }\n const open = this.#open.get(index);\n if (open === undefined) return events;\n // The first entry carries the id and name; a server that repeats them in later entries adds nothing.\n if (!open.callId) open.callId = id;\n if (!open.name) open.name = str(fn.name);\n const args = str(fn.arguments);\n if (args === \"\") return events;\n open.text += args;\n events.push({ type: \"tool_input_delta\", index, delta: args });\n return events;\n }\n\n #openBlock(block: OpenBlock): number {\n const index = this.#nextIndex;\n this.#nextIndex += 1;\n this.#open.set(index, block);\n return index;\n }\n\n #closeIndex(index: number | undefined): ModelEvent[] {\n if (index === undefined) return [];\n const open = this.#open.get(index);\n if (index === this.#text) this.#text = undefined;\n if (index === this.#reasoning) this.#reasoning = undefined;\n if (open === undefined) return [];\n this.#open.delete(index);\n const block = this.#finishBlock(open);\n this.#closed.set(index, block);\n return [{ type: `${open.kind}_end`, index, block }];\n }\n\n #finishBlock(open: OpenBlock): ContentBlock {\n if (open.kind === \"text\") return { type: \"text\", text: open.text };\n if (open.kind === \"reasoning\") return { type: \"reasoning\", text: open.text };\n const wire = open.name ?? \"\";\n const name = this.#names.restore(wire) ?? wire;\n const input = parseToolInput(open.text);\n const schema = this.#strictSchemas.get(name);\n // A call cut off by the output limit keeps its partial JSON text as it arrived.\n const stripped = schema === undefined || typeof input === \"string\" ? input : stripAddedNulls(input, schema);\n return { type: \"tool_call\", callId: open.callId ?? \"\", name, input: stripped };\n }\n\n #terminal(): ModelEvent[] {\n const closing = [...this.#open.keys()].sort((a, b) => a - b).flatMap((index) => this.#closeIndex(index));\n const { content, usage } = this.partial();\n if (this.#finish === \"content_filter\" || this.#refusal !== \"\") {\n const message =\n this.#refusal !== \"\"\n ? `refusal: ${this.#refusal}`\n : \"content_filter: the provider's content filter omitted all or part of the reply\";\n return [...closing, failureEvent(this.#model, { message, kind: \"fatal\" }, { content, usage })];\n }\n const hasCalls = content.some((block) => block.type === \"tool_call\");\n const mapped = STOP_REASONS[this.#finish] ?? \"stop\";\n // Some compatible servers end a reply that calls tools with \"stop\"; the calls still need their results.\n const stopReason = mapped === \"stop\" && hasCalls ? \"tool_calls\" : mapped;\n return [...closing, { type: \"done\", message: terminalMessage(this.#model, { content, usage }, stopReason) }];\n }\n}\n"]}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Maps a Chat Completions `usage` object into the gateway's four token classes (D3), from the `usage` of a chat
3
+ * completion (https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) and
4
+ * the Prompt caching guide (https://developers.openai.com/api/docs/guides/prompt-caching), both as of November 2026:
5
+ *
6
+ * - `prompt_tokens` counts the whole prompt. `prompt_tokens_details.cached_tokens` counts billed cache reads, which
7
+ * exclude the tokens charged as writes, and `cache_write_tokens` the prompt tokens written to cache. The guide
8
+ * computes ordinary input as the input tokens less both, and so does the adapter.
9
+ * - Chat Completions writes only 30-minute cache entries, so every write counts under `Usage.cacheWrite["5m"]`, the
10
+ * key for the short cache-write rate; an OpenAI catalog entry stores its 30-minute rate there.
11
+ * - `completion_tokens` is the output, and `completion_tokens_details.reasoning_tokens` the part of it spent on
12
+ * reasoning: `max_completion_tokens` bounds "visible output tokens and reasoning tokens" together, and the
13
+ * reference says rejected prediction tokens are, "like reasoning tokens", counted in the completion tokens for billing.
14
+ *
15
+ * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.
16
+ */
17
+ import type { Usage } from "../../types.js";
18
+ /**
19
+ * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores
20
+ * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.
21
+ */
22
+ export declare function openaiUsage(raw: unknown): Usage;
@@ -0,0 +1,25 @@
1
+ import { unreportedUsage } from "../../usage.js";
2
+ import { count, isObject } from "../wire.js";
3
+ /**
4
+ * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores
5
+ * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.
6
+ */
7
+ export function openaiUsage(raw) {
8
+ if (!isObject(raw))
9
+ return unreportedUsage(raw ?? null);
10
+ const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};
11
+ const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};
12
+ const cacheRead = count(prompt.cached_tokens);
13
+ const written = count(prompt.cache_write_tokens);
14
+ const output = count(raw.completion_tokens);
15
+ return {
16
+ uncachedInput: Math.max(0, count(raw.prompt_tokens) - cacheRead - written),
17
+ cacheRead,
18
+ cacheWrite: { "5m": written, "1h": 0 },
19
+ output,
20
+ // Reasoning is a part of output; the cap keeps that true for a server that reports more.
21
+ reasoning: Math.min(count(completion.reasoning_tokens), output),
22
+ raw,
23
+ };
24
+ }
25
+ //# sourceMappingURL=usage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.js","sourceRoot":"","sources":["../../../src/adapters/openai-chat/usage.ts"],"names":[],"mappings":"AAiBA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE7C;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,GAAY;IACtC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,eAAe,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC,CAAC,EAAE,CAAC;IACpF,MAAM,UAAU,GAAG,QAAQ,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC,EAAE,CAAC;IAChG,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;IAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;IAC5C,OAAO;QACL,aAAa,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,aAAa,CAAC,GAAG,SAAS,GAAG,OAAO,CAAC;QAC1E,SAAS;QACT,UAAU,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,EAAE;QACtC,MAAM;QACN,yFAAyF;QACzF,SAAS,EAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;QAC/D,GAAG;KACJ,CAAC;AACJ,CAAC","sourcesContent":["/**\n * Maps a Chat Completions `usage` object into the gateway's four token classes (D3), from the `usage` of a chat\n * completion (https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create) and\n * the Prompt caching guide (https://developers.openai.com/api/docs/guides/prompt-caching), both as of November 2026:\n *\n * - `prompt_tokens` counts the whole prompt. `prompt_tokens_details.cached_tokens` counts billed cache reads, which\n * exclude the tokens charged as writes, and `cache_write_tokens` the prompt tokens written to cache. The guide\n * computes ordinary input as the input tokens less both, and so does the adapter.\n * - Chat Completions writes only 30-minute cache entries, so every write counts under `Usage.cacheWrite[\"5m\"]`, the\n * key for the short cache-write rate; an OpenAI catalog entry stores its 30-minute rate there.\n * - `completion_tokens` is the output, and `completion_tokens_details.reasoning_tokens` the part of it spent on\n * reasoning: `max_completion_tokens` bounds \"visible output tokens and reasoning tokens\" together, and the\n * reference says rejected prediction tokens are, \"like reasoning tokens\", counted in the completion tokens for billing.\n *\n * The usage object holds token counts only, so a reply carries no billed price and the cost comes from the catalog.\n */\nimport type { Usage } from \"../../types.js\";\nimport { unreportedUsage } from \"../../usage.js\";\nimport { count, isObject } from \"../wire.js\";\n\n/**\n * The gateway's `Usage` for a Chat Completions usage object. A reply without one, from a server that ignores\n * `stream_options.include_usage` or a stream that ended before its usage chunk, has `unreported` usage.\n */\nexport function openaiUsage(raw: unknown): Usage {\n if (!isObject(raw)) return unreportedUsage(raw ?? null);\n const prompt = isObject(raw.prompt_tokens_details) ? raw.prompt_tokens_details : {};\n const completion = isObject(raw.completion_tokens_details) ? raw.completion_tokens_details : {};\n const cacheRead = count(prompt.cached_tokens);\n const written = count(prompt.cache_write_tokens);\n const output = count(raw.completion_tokens);\n return {\n uncachedInput: Math.max(0, count(raw.prompt_tokens) - cacheRead - written),\n cacheRead,\n cacheWrite: { \"5m\": written, \"1h\": 0 },\n output,\n // Reasoning is a part of output; the cap keeps that true for a server that reports more.\n reasoning: Math.min(count(completion.reasoning_tokens), output),\n raw,\n };\n}\n"]}