@eminent337/aery-ai 0.1.119

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 (210) hide show
  1. package/README.md +1383 -0
  2. package/dist/api-registry.d.ts +20 -0
  3. package/dist/api-registry.d.ts.map +1 -0
  4. package/dist/api-registry.js +44 -0
  5. package/dist/api-registry.js.map +1 -0
  6. package/dist/bedrock-provider.d.ts +5 -0
  7. package/dist/bedrock-provider.d.ts.map +1 -0
  8. package/dist/bedrock-provider.js +6 -0
  9. package/dist/bedrock-provider.js.map +1 -0
  10. package/dist/cli.d.ts +3 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +116 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/env-api-keys.d.ts +18 -0
  15. package/dist/env-api-keys.d.ts.map +1 -0
  16. package/dist/env-api-keys.js +170 -0
  17. package/dist/env-api-keys.js.map +1 -0
  18. package/dist/image-models.d.ts +10 -0
  19. package/dist/image-models.d.ts.map +1 -0
  20. package/dist/image-models.generated.d.ts +260 -0
  21. package/dist/image-models.generated.d.ts.map +1 -0
  22. package/dist/image-models.generated.js +262 -0
  23. package/dist/image-models.generated.js.map +1 -0
  24. package/dist/image-models.js +23 -0
  25. package/dist/image-models.js.map +1 -0
  26. package/dist/images-api-registry.d.ts +14 -0
  27. package/dist/images-api-registry.d.ts.map +1 -0
  28. package/dist/images-api-registry.js +22 -0
  29. package/dist/images-api-registry.js.map +1 -0
  30. package/dist/images.d.ts +4 -0
  31. package/dist/images.d.ts.map +1 -0
  32. package/dist/images.js +14 -0
  33. package/dist/images.js.map +1 -0
  34. package/dist/index.d.ts +32 -0
  35. package/dist/index.d.ts.map +1 -0
  36. package/dist/index.js +20 -0
  37. package/dist/index.js.map +1 -0
  38. package/dist/models.d.ts +18 -0
  39. package/dist/models.d.ts.map +1 -0
  40. package/dist/models.generated.d.ts +18237 -0
  41. package/dist/models.generated.d.ts.map +1 -0
  42. package/dist/models.generated.js +17251 -0
  43. package/dist/models.generated.js.map +1 -0
  44. package/dist/models.js +71 -0
  45. package/dist/models.js.map +1 -0
  46. package/dist/oauth.d.ts +2 -0
  47. package/dist/oauth.d.ts.map +1 -0
  48. package/dist/oauth.js +2 -0
  49. package/dist/oauth.js.map +1 -0
  50. package/dist/providers/aery-error-formatting.d.ts +13 -0
  51. package/dist/providers/aery-error-formatting.d.ts.map +1 -0
  52. package/dist/providers/aery-error-formatting.js +112 -0
  53. package/dist/providers/aery-error-formatting.js.map +1 -0
  54. package/dist/providers/amazon-bedrock.d.ts +38 -0
  55. package/dist/providers/amazon-bedrock.d.ts.map +1 -0
  56. package/dist/providers/amazon-bedrock.js +750 -0
  57. package/dist/providers/amazon-bedrock.js.map +1 -0
  58. package/dist/providers/anthropic.d.ts +54 -0
  59. package/dist/providers/anthropic.d.ts.map +1 -0
  60. package/dist/providers/anthropic.js +960 -0
  61. package/dist/providers/anthropic.js.map +1 -0
  62. package/dist/providers/azure-openai-responses.d.ts +15 -0
  63. package/dist/providers/azure-openai-responses.d.ts.map +1 -0
  64. package/dist/providers/azure-openai-responses.js +208 -0
  65. package/dist/providers/azure-openai-responses.js.map +1 -0
  66. package/dist/providers/cloudflare.d.ts +13 -0
  67. package/dist/providers/cloudflare.d.ts.map +1 -0
  68. package/dist/providers/cloudflare.js +26 -0
  69. package/dist/providers/cloudflare.js.map +1 -0
  70. package/dist/providers/faux.d.ts +56 -0
  71. package/dist/providers/faux.d.ts.map +1 -0
  72. package/dist/providers/faux.js +368 -0
  73. package/dist/providers/faux.js.map +1 -0
  74. package/dist/providers/github-copilot-headers.d.ts +8 -0
  75. package/dist/providers/github-copilot-headers.d.ts.map +1 -0
  76. package/dist/providers/github-copilot-headers.js +29 -0
  77. package/dist/providers/github-copilot-headers.js.map +1 -0
  78. package/dist/providers/google-shared.d.ts +70 -0
  79. package/dist/providers/google-shared.d.ts.map +1 -0
  80. package/dist/providers/google-shared.js +329 -0
  81. package/dist/providers/google-shared.js.map +1 -0
  82. package/dist/providers/google-vertex.d.ts +15 -0
  83. package/dist/providers/google-vertex.d.ts.map +1 -0
  84. package/dist/providers/google-vertex.js +442 -0
  85. package/dist/providers/google-vertex.js.map +1 -0
  86. package/dist/providers/google.d.ts +13 -0
  87. package/dist/providers/google.d.ts.map +1 -0
  88. package/dist/providers/google.js +400 -0
  89. package/dist/providers/google.js.map +1 -0
  90. package/dist/providers/images/openrouter.d.ts +3 -0
  91. package/dist/providers/images/openrouter.d.ts.map +1 -0
  92. package/dist/providers/images/openrouter.js +129 -0
  93. package/dist/providers/images/openrouter.js.map +1 -0
  94. package/dist/providers/images/register-builtins.d.ts +4 -0
  95. package/dist/providers/images/register-builtins.d.ts.map +1 -0
  96. package/dist/providers/images/register-builtins.js +34 -0
  97. package/dist/providers/images/register-builtins.js.map +1 -0
  98. package/dist/providers/mistral.d.ts +25 -0
  99. package/dist/providers/mistral.d.ts.map +1 -0
  100. package/dist/providers/mistral.js +535 -0
  101. package/dist/providers/mistral.js.map +1 -0
  102. package/dist/providers/openai-codex-responses.d.ts +30 -0
  103. package/dist/providers/openai-codex-responses.d.ts.map +1 -0
  104. package/dist/providers/openai-codex-responses.js +1080 -0
  105. package/dist/providers/openai-codex-responses.js.map +1 -0
  106. package/dist/providers/openai-completions.d.ts +19 -0
  107. package/dist/providers/openai-completions.d.ts.map +1 -0
  108. package/dist/providers/openai-completions.js +936 -0
  109. package/dist/providers/openai-completions.js.map +1 -0
  110. package/dist/providers/openai-responses-shared.d.ts +18 -0
  111. package/dist/providers/openai-responses-shared.d.ts.map +1 -0
  112. package/dist/providers/openai-responses-shared.js +492 -0
  113. package/dist/providers/openai-responses-shared.js.map +1 -0
  114. package/dist/providers/openai-responses.d.ts +13 -0
  115. package/dist/providers/openai-responses.d.ts.map +1 -0
  116. package/dist/providers/openai-responses.js +220 -0
  117. package/dist/providers/openai-responses.js.map +1 -0
  118. package/dist/providers/register-builtins.d.ts +35 -0
  119. package/dist/providers/register-builtins.d.ts.map +1 -0
  120. package/dist/providers/register-builtins.js +243 -0
  121. package/dist/providers/register-builtins.js.map +1 -0
  122. package/dist/providers/simple-options.d.ts +8 -0
  123. package/dist/providers/simple-options.d.ts.map +1 -0
  124. package/dist/providers/simple-options.js +39 -0
  125. package/dist/providers/simple-options.js.map +1 -0
  126. package/dist/providers/transform-messages.d.ts +8 -0
  127. package/dist/providers/transform-messages.d.ts.map +1 -0
  128. package/dist/providers/transform-messages.js +184 -0
  129. package/dist/providers/transform-messages.js.map +1 -0
  130. package/dist/session-resources.d.ts +4 -0
  131. package/dist/session-resources.d.ts.map +1 -0
  132. package/dist/session-resources.js +22 -0
  133. package/dist/session-resources.js.map +1 -0
  134. package/dist/stream.d.ts +8 -0
  135. package/dist/stream.d.ts.map +1 -0
  136. package/dist/stream.js +27 -0
  137. package/dist/stream.js.map +1 -0
  138. package/dist/types.d.ts +488 -0
  139. package/dist/types.d.ts.map +1 -0
  140. package/dist/types.js +2 -0
  141. package/dist/types.js.map +1 -0
  142. package/dist/utils/diagnostics.d.ts +19 -0
  143. package/dist/utils/diagnostics.d.ts.map +1 -0
  144. package/dist/utils/diagnostics.js +25 -0
  145. package/dist/utils/diagnostics.js.map +1 -0
  146. package/dist/utils/event-stream.d.ts +21 -0
  147. package/dist/utils/event-stream.d.ts.map +1 -0
  148. package/dist/utils/event-stream.js +81 -0
  149. package/dist/utils/event-stream.js.map +1 -0
  150. package/dist/utils/hash.d.ts +3 -0
  151. package/dist/utils/hash.d.ts.map +1 -0
  152. package/dist/utils/hash.js +14 -0
  153. package/dist/utils/hash.js.map +1 -0
  154. package/dist/utils/headers.d.ts +2 -0
  155. package/dist/utils/headers.d.ts.map +1 -0
  156. package/dist/utils/headers.js +8 -0
  157. package/dist/utils/headers.js.map +1 -0
  158. package/dist/utils/json-parse.d.ts +16 -0
  159. package/dist/utils/json-parse.d.ts.map +1 -0
  160. package/dist/utils/json-parse.js +113 -0
  161. package/dist/utils/json-parse.js.map +1 -0
  162. package/dist/utils/node-http-proxy.d.ts +10 -0
  163. package/dist/utils/node-http-proxy.d.ts.map +1 -0
  164. package/dist/utils/node-http-proxy.js +34 -0
  165. package/dist/utils/node-http-proxy.js.map +1 -0
  166. package/dist/utils/oauth/anthropic.d.ts +25 -0
  167. package/dist/utils/oauth/anthropic.d.ts.map +1 -0
  168. package/dist/utils/oauth/anthropic.js +335 -0
  169. package/dist/utils/oauth/anthropic.js.map +1 -0
  170. package/dist/utils/oauth/github-copilot.d.ts +30 -0
  171. package/dist/utils/oauth/github-copilot.d.ts.map +1 -0
  172. package/dist/utils/oauth/github-copilot.js +292 -0
  173. package/dist/utils/oauth/github-copilot.js.map +1 -0
  174. package/dist/utils/oauth/index.d.ts +57 -0
  175. package/dist/utils/oauth/index.d.ts.map +1 -0
  176. package/dist/utils/oauth/index.js +121 -0
  177. package/dist/utils/oauth/index.js.map +1 -0
  178. package/dist/utils/oauth/oauth-page.d.ts +3 -0
  179. package/dist/utils/oauth/oauth-page.d.ts.map +1 -0
  180. package/dist/utils/oauth/oauth-page.js +105 -0
  181. package/dist/utils/oauth/oauth-page.js.map +1 -0
  182. package/dist/utils/oauth/openai-codex.d.ts +34 -0
  183. package/dist/utils/oauth/openai-codex.d.ts.map +1 -0
  184. package/dist/utils/oauth/openai-codex.js +385 -0
  185. package/dist/utils/oauth/openai-codex.js.map +1 -0
  186. package/dist/utils/oauth/pkce.d.ts +13 -0
  187. package/dist/utils/oauth/pkce.d.ts.map +1 -0
  188. package/dist/utils/oauth/pkce.js +31 -0
  189. package/dist/utils/oauth/pkce.js.map +1 -0
  190. package/dist/utils/oauth/types.d.ts +57 -0
  191. package/dist/utils/oauth/types.d.ts.map +1 -0
  192. package/dist/utils/oauth/types.js +2 -0
  193. package/dist/utils/oauth/types.js.map +1 -0
  194. package/dist/utils/overflow.d.ts +56 -0
  195. package/dist/utils/overflow.d.ts.map +1 -0
  196. package/dist/utils/overflow.js +149 -0
  197. package/dist/utils/overflow.js.map +1 -0
  198. package/dist/utils/sanitize-unicode.d.ts +22 -0
  199. package/dist/utils/sanitize-unicode.d.ts.map +1 -0
  200. package/dist/utils/sanitize-unicode.js +26 -0
  201. package/dist/utils/sanitize-unicode.js.map +1 -0
  202. package/dist/utils/typebox-helpers.d.ts +17 -0
  203. package/dist/utils/typebox-helpers.d.ts.map +1 -0
  204. package/dist/utils/typebox-helpers.js +21 -0
  205. package/dist/utils/typebox-helpers.js.map +1 -0
  206. package/dist/utils/validation.d.ts +18 -0
  207. package/dist/utils/validation.d.ts.map +1 -0
  208. package/dist/utils/validation.js +281 -0
  209. package/dist/utils/validation.js.map +1 -0
  210. package/package.json +108 -0
@@ -0,0 +1,492 @@
1
+ import { calculateCost } from "../models.js";
2
+ import { shortHash } from "../utils/hash.js";
3
+ import { parseStreamingJson } from "../utils/json-parse.js";
4
+ import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
5
+ import { transformMessages } from "./transform-messages.js";
6
+ // =============================================================================
7
+ // Utilities
8
+ // =============================================================================
9
+ function encodeTextSignatureV1(id, phase) {
10
+ const payload = { v: 1, id };
11
+ if (phase)
12
+ payload.phase = phase;
13
+ return JSON.stringify(payload);
14
+ }
15
+ function parseTextSignature(signature) {
16
+ if (!signature)
17
+ return undefined;
18
+ if (signature.startsWith("{")) {
19
+ try {
20
+ const parsed = JSON.parse(signature);
21
+ if (parsed.v === 1 && typeof parsed.id === "string") {
22
+ if (parsed.phase === "commentary" || parsed.phase === "final_answer") {
23
+ return { id: parsed.id, phase: parsed.phase };
24
+ }
25
+ return { id: parsed.id };
26
+ }
27
+ }
28
+ catch {
29
+ // Fall through to legacy plain-string handling.
30
+ }
31
+ }
32
+ return { id: signature };
33
+ }
34
+ // =============================================================================
35
+ // Message conversion
36
+ // =============================================================================
37
+ export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
38
+ const messages = [];
39
+ const normalizeIdPart = (part) => {
40
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
41
+ const normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;
42
+ return normalized.replace(/_+$/, "");
43
+ };
44
+ const buildForeignResponsesItemId = (itemId) => {
45
+ const normalized = `fc_${shortHash(itemId)}`;
46
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
47
+ };
48
+ const normalizeToolCallId = (id, _targetModel, source) => {
49
+ if (!allowedToolCallProviders.has(model.provider))
50
+ return normalizeIdPart(id);
51
+ if (!id.includes("|"))
52
+ return normalizeIdPart(id);
53
+ const [callId, itemId] = id.split("|");
54
+ const normalizedCallId = normalizeIdPart(callId);
55
+ const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;
56
+ let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
57
+ // OpenAI Responses API requires item id to start with "fc"
58
+ if (!normalizedItemId.startsWith("fc_")) {
59
+ normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
60
+ }
61
+ return `${normalizedCallId}|${normalizedItemId}`;
62
+ };
63
+ const transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);
64
+ const includeSystemPrompt = options?.includeSystemPrompt ?? true;
65
+ if (includeSystemPrompt && context.systemPrompt) {
66
+ const role = model.reasoning ? "developer" : "system";
67
+ messages.push({
68
+ role,
69
+ content: sanitizeSurrogates(context.systemPrompt),
70
+ });
71
+ }
72
+ let msgIndex = 0;
73
+ for (const msg of transformedMessages) {
74
+ if (msg.role === "user") {
75
+ if (typeof msg.content === "string") {
76
+ messages.push({
77
+ role: "user",
78
+ content: [{ type: "input_text", text: sanitizeSurrogates(msg.content) }],
79
+ });
80
+ }
81
+ else {
82
+ const content = msg.content.map((item) => {
83
+ if (item.type === "text") {
84
+ return {
85
+ type: "input_text",
86
+ text: sanitizeSurrogates(item.text),
87
+ };
88
+ }
89
+ return {
90
+ type: "input_image",
91
+ detail: "auto",
92
+ image_url: `data:${item.mimeType};base64,${item.data}`,
93
+ };
94
+ });
95
+ if (content.length === 0)
96
+ continue;
97
+ messages.push({
98
+ role: "user",
99
+ content,
100
+ });
101
+ }
102
+ }
103
+ else if (msg.role === "assistant") {
104
+ const output = [];
105
+ const assistantMsg = msg;
106
+ const isDifferentModel = assistantMsg.model !== model.id &&
107
+ assistantMsg.provider === model.provider &&
108
+ assistantMsg.api === model.api;
109
+ for (const block of msg.content) {
110
+ if (block.type === "thinking") {
111
+ if (block.thinkingSignature) {
112
+ const reasoningItem = JSON.parse(block.thinkingSignature);
113
+ output.push(reasoningItem);
114
+ }
115
+ }
116
+ else if (block.type === "text") {
117
+ const textBlock = block;
118
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
119
+ // OpenAI requires id to be max 64 characters
120
+ let msgId = parsedSignature?.id;
121
+ if (!msgId) {
122
+ msgId = `msg_${msgIndex}`;
123
+ }
124
+ else if (msgId.length > 64) {
125
+ msgId = `msg_${shortHash(msgId)}`;
126
+ }
127
+ output.push({
128
+ type: "message",
129
+ role: "assistant",
130
+ content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
131
+ status: "completed",
132
+ id: msgId,
133
+ phase: parsedSignature?.phase,
134
+ });
135
+ }
136
+ else if (block.type === "toolCall") {
137
+ const toolCall = block;
138
+ const [callId, itemIdRaw] = toolCall.id.split("|");
139
+ let itemId = itemIdRaw;
140
+ // For different-model messages, set id to undefined to avoid pairing validation.
141
+ // OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.
142
+ // By omitting the id, we avoid triggering that validation (like cross-provider does).
143
+ if (isDifferentModel && itemId?.startsWith("fc_")) {
144
+ itemId = undefined;
145
+ }
146
+ output.push({
147
+ type: "function_call",
148
+ id: itemId,
149
+ call_id: callId,
150
+ name: toolCall.name,
151
+ arguments: JSON.stringify(toolCall.arguments),
152
+ });
153
+ }
154
+ }
155
+ if (output.length === 0)
156
+ continue;
157
+ messages.push(...output);
158
+ }
159
+ else if (msg.role === "toolResult") {
160
+ const textResult = msg.content
161
+ .filter((c) => c.type === "text")
162
+ .map((c) => c.text)
163
+ .join("\n");
164
+ const hasImages = msg.content.some((c) => c.type === "image");
165
+ const hasText = textResult.length > 0;
166
+ const [callId] = msg.toolCallId.split("|");
167
+ let output;
168
+ if (hasImages && model.input.includes("image")) {
169
+ const contentParts = [];
170
+ if (hasText) {
171
+ contentParts.push({
172
+ type: "input_text",
173
+ text: sanitizeSurrogates(textResult),
174
+ });
175
+ }
176
+ for (const block of msg.content) {
177
+ if (block.type === "image") {
178
+ contentParts.push({
179
+ type: "input_image",
180
+ detail: "auto",
181
+ image_url: `data:${block.mimeType};base64,${block.data}`,
182
+ });
183
+ }
184
+ }
185
+ output = contentParts;
186
+ }
187
+ else {
188
+ output = sanitizeSurrogates(hasText ? textResult : "(see attached image)");
189
+ }
190
+ messages.push({
191
+ type: "function_call_output",
192
+ call_id: callId,
193
+ output,
194
+ });
195
+ }
196
+ msgIndex++;
197
+ }
198
+ return messages;
199
+ }
200
+ // =============================================================================
201
+ // Tool conversion
202
+ // =============================================================================
203
+ export function convertResponsesTools(tools, options) {
204
+ const strict = options?.strict === undefined ? false : options.strict;
205
+ return tools.map((tool) => ({
206
+ type: "function",
207
+ name: tool.name,
208
+ description: tool.description,
209
+ parameters: tool.parameters, // TypeBox already generates JSON Schema
210
+ strict,
211
+ }));
212
+ }
213
+ // =============================================================================
214
+ // Stream processing
215
+ // =============================================================================
216
+ export async function processResponsesStream(openaiStream, output, stream, model, options) {
217
+ let currentItem = null;
218
+ let currentBlock = null;
219
+ const blocks = output.content;
220
+ const blockIndex = () => blocks.length - 1;
221
+ for await (const event of openaiStream) {
222
+ if (event.type === "response.created") {
223
+ output.responseId = event.response.id;
224
+ }
225
+ else if (event.type === "response.output_item.added") {
226
+ const item = event.item;
227
+ if (item.type === "reasoning") {
228
+ currentItem = item;
229
+ currentBlock = { type: "thinking", thinking: "" };
230
+ output.content.push(currentBlock);
231
+ stream.push({ type: "thinking_start", contentIndex: blockIndex(), partial: output });
232
+ }
233
+ else if (item.type === "message") {
234
+ currentItem = item;
235
+ currentBlock = { type: "text", text: "" };
236
+ output.content.push(currentBlock);
237
+ stream.push({ type: "text_start", contentIndex: blockIndex(), partial: output });
238
+ }
239
+ else if (item.type === "function_call") {
240
+ currentItem = item;
241
+ currentBlock = {
242
+ type: "toolCall",
243
+ id: `${item.call_id}|${item.id}`,
244
+ name: item.name,
245
+ arguments: {},
246
+ partialJson: item.arguments || "",
247
+ };
248
+ output.content.push(currentBlock);
249
+ stream.push({ type: "toolcall_start", contentIndex: blockIndex(), partial: output });
250
+ }
251
+ }
252
+ else if (event.type === "response.reasoning_summary_part.added") {
253
+ if (currentItem && currentItem.type === "reasoning") {
254
+ currentItem.summary = currentItem.summary || [];
255
+ currentItem.summary.push(event.part);
256
+ }
257
+ }
258
+ else if (event.type === "response.reasoning_summary_text.delta") {
259
+ if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
260
+ currentItem.summary = currentItem.summary || [];
261
+ const lastPart = currentItem.summary[currentItem.summary.length - 1];
262
+ if (lastPart) {
263
+ currentBlock.thinking += event.delta;
264
+ lastPart.text += event.delta;
265
+ stream.push({
266
+ type: "thinking_delta",
267
+ contentIndex: blockIndex(),
268
+ delta: event.delta,
269
+ partial: output,
270
+ });
271
+ }
272
+ }
273
+ }
274
+ else if (event.type === "response.reasoning_summary_part.done") {
275
+ if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
276
+ currentItem.summary = currentItem.summary || [];
277
+ const lastPart = currentItem.summary[currentItem.summary.length - 1];
278
+ if (lastPart) {
279
+ currentBlock.thinking += "\n\n";
280
+ lastPart.text += "\n\n";
281
+ stream.push({
282
+ type: "thinking_delta",
283
+ contentIndex: blockIndex(),
284
+ delta: "\n\n",
285
+ partial: output,
286
+ });
287
+ }
288
+ }
289
+ }
290
+ else if (event.type === "response.reasoning_text.delta") {
291
+ if (currentItem?.type === "reasoning" && currentBlock?.type === "thinking") {
292
+ currentBlock.thinking += event.delta;
293
+ stream.push({
294
+ type: "thinking_delta",
295
+ contentIndex: blockIndex(),
296
+ delta: event.delta,
297
+ partial: output,
298
+ });
299
+ }
300
+ }
301
+ else if (event.type === "response.content_part.added") {
302
+ if (currentItem?.type === "message") {
303
+ currentItem.content = currentItem.content || [];
304
+ // Filter out ReasoningText, only accept output_text and refusal
305
+ if (event.part.type === "output_text" || event.part.type === "refusal") {
306
+ currentItem.content.push(event.part);
307
+ }
308
+ }
309
+ }
310
+ else if (event.type === "response.output_text.delta") {
311
+ if (currentItem?.type === "message" && currentBlock?.type === "text") {
312
+ if (!currentItem.content || currentItem.content.length === 0) {
313
+ continue;
314
+ }
315
+ const lastPart = currentItem.content[currentItem.content.length - 1];
316
+ if (lastPart?.type === "output_text") {
317
+ currentBlock.text += event.delta;
318
+ lastPart.text += event.delta;
319
+ stream.push({
320
+ type: "text_delta",
321
+ contentIndex: blockIndex(),
322
+ delta: event.delta,
323
+ partial: output,
324
+ });
325
+ }
326
+ }
327
+ }
328
+ else if (event.type === "response.refusal.delta") {
329
+ if (currentItem?.type === "message" && currentBlock?.type === "text") {
330
+ if (!currentItem.content || currentItem.content.length === 0) {
331
+ continue;
332
+ }
333
+ const lastPart = currentItem.content[currentItem.content.length - 1];
334
+ if (lastPart?.type === "refusal") {
335
+ currentBlock.text += event.delta;
336
+ lastPart.refusal += event.delta;
337
+ stream.push({
338
+ type: "text_delta",
339
+ contentIndex: blockIndex(),
340
+ delta: event.delta,
341
+ partial: output,
342
+ });
343
+ }
344
+ }
345
+ }
346
+ else if (event.type === "response.function_call_arguments.delta") {
347
+ if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
348
+ currentBlock.partialJson += event.delta;
349
+ currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
350
+ stream.push({
351
+ type: "toolcall_delta",
352
+ contentIndex: blockIndex(),
353
+ delta: event.delta,
354
+ partial: output,
355
+ });
356
+ }
357
+ }
358
+ else if (event.type === "response.function_call_arguments.done") {
359
+ if (currentItem?.type === "function_call" && currentBlock?.type === "toolCall") {
360
+ const previousPartialJson = currentBlock.partialJson;
361
+ currentBlock.partialJson = event.arguments;
362
+ currentBlock.arguments = parseStreamingJson(currentBlock.partialJson);
363
+ if (event.arguments.startsWith(previousPartialJson)) {
364
+ const delta = event.arguments.slice(previousPartialJson.length);
365
+ if (delta.length > 0) {
366
+ stream.push({
367
+ type: "toolcall_delta",
368
+ contentIndex: blockIndex(),
369
+ delta,
370
+ partial: output,
371
+ });
372
+ }
373
+ }
374
+ }
375
+ }
376
+ else if (event.type === "response.output_item.done") {
377
+ const item = event.item;
378
+ if (item.type === "reasoning" && currentBlock?.type === "thinking") {
379
+ const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
380
+ const contentText = item.content?.map((c) => c.text).join("\n\n") || "";
381
+ currentBlock.thinking = summaryText || contentText || currentBlock.thinking;
382
+ currentBlock.thinkingSignature = JSON.stringify(item);
383
+ stream.push({
384
+ type: "thinking_end",
385
+ contentIndex: blockIndex(),
386
+ content: currentBlock.thinking,
387
+ partial: output,
388
+ });
389
+ currentBlock = null;
390
+ }
391
+ else if (item.type === "message" && currentBlock?.type === "text") {
392
+ currentBlock.text = item.content.map((c) => (c.type === "output_text" ? c.text : c.refusal)).join("");
393
+ currentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);
394
+ stream.push({
395
+ type: "text_end",
396
+ contentIndex: blockIndex(),
397
+ content: currentBlock.text,
398
+ partial: output,
399
+ });
400
+ currentBlock = null;
401
+ }
402
+ else if (item.type === "function_call") {
403
+ const args = currentBlock?.type === "toolCall" && currentBlock.partialJson
404
+ ? parseStreamingJson(currentBlock.partialJson)
405
+ : parseStreamingJson(item.arguments || "{}");
406
+ let toolCall;
407
+ if (currentBlock?.type === "toolCall") {
408
+ // Finalize in-place and strip the scratch buffer so replay only
409
+ // carries parsed arguments.
410
+ currentBlock.arguments = args;
411
+ delete currentBlock.partialJson;
412
+ toolCall = currentBlock;
413
+ }
414
+ else {
415
+ toolCall = {
416
+ type: "toolCall",
417
+ id: `${item.call_id}|${item.id}`,
418
+ name: item.name,
419
+ arguments: args,
420
+ };
421
+ }
422
+ currentBlock = null;
423
+ stream.push({ type: "toolcall_end", contentIndex: blockIndex(), toolCall, partial: output });
424
+ }
425
+ }
426
+ else if (event.type === "response.completed") {
427
+ const response = event.response;
428
+ if (response?.id) {
429
+ output.responseId = response.id;
430
+ }
431
+ if (response?.usage) {
432
+ const cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;
433
+ output.usage = {
434
+ // OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input
435
+ input: (response.usage.input_tokens || 0) - cachedTokens,
436
+ output: response.usage.output_tokens || 0,
437
+ cacheRead: cachedTokens,
438
+ cacheWrite: 0,
439
+ totalTokens: response.usage.total_tokens || 0,
440
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
441
+ };
442
+ }
443
+ calculateCost(model, output.usage);
444
+ if (options?.applyServiceTierPricing) {
445
+ const serviceTier = options.resolveServiceTier
446
+ ? options.resolveServiceTier(response?.service_tier, options.serviceTier)
447
+ : (response?.service_tier ?? options.serviceTier);
448
+ options.applyServiceTierPricing(output.usage, serviceTier);
449
+ }
450
+ // Map status to stop reason
451
+ output.stopReason = mapStopReason(response?.status);
452
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") {
453
+ output.stopReason = "toolUse";
454
+ }
455
+ }
456
+ else if (event.type === "error") {
457
+ throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
458
+ }
459
+ else if (event.type === "response.failed") {
460
+ const error = event.response?.error;
461
+ const details = event.response?.incomplete_details;
462
+ const msg = error
463
+ ? `${error.code || "unknown"}: ${error.message || "no message"}`
464
+ : details?.reason
465
+ ? `incomplete: ${details.reason}`
466
+ : "Unknown error (no error details in response)";
467
+ throw new Error(msg);
468
+ }
469
+ }
470
+ }
471
+ function mapStopReason(status) {
472
+ if (!status)
473
+ return "stop";
474
+ switch (status) {
475
+ case "completed":
476
+ return "stop";
477
+ case "incomplete":
478
+ return "length";
479
+ case "failed":
480
+ case "cancelled":
481
+ return "error";
482
+ // These two are wonky ...
483
+ case "in_progress":
484
+ case "queued":
485
+ return "stop";
486
+ default: {
487
+ const _exhaustive = status;
488
+ throw new Error(`Unhandled stop reason: ${_exhaustive}`);
489
+ }
490
+ }
491
+ }
492
+ //# sourceMappingURL=openai-responses-shared.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/providers/openai-responses-shared.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAgB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,SAAS,qBAAqB,CAAC,EAAU,EAAE,KAAgC,EAAU;IACpF,MAAM,OAAO,GAAoB,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IAC9C,IAAI,KAAK;QAAE,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;IACjC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AAAA,CAC/B;AAED,SAAS,kBAAkB,CAC1B,SAA6B,EACkC;IAC/D,IAAI,CAAC,SAAS;QAAE,OAAO,SAAS,CAAC;IACjC,IAAI,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QAC/B,IAAI,CAAC;YACJ,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAA6B,CAAC;YACjE,IAAI,MAAM,CAAC,CAAC,KAAK,CAAC,IAAI,OAAO,MAAM,CAAC,EAAE,KAAK,QAAQ,EAAE,CAAC;gBACrD,IAAI,MAAM,CAAC,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AAmD,EAAc;IACvF,IAAI,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC;IAC3B,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,OAAO,CAAC;QAChB,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AAAA,CACD","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionCallOutputItemList,\n\tResponseFunctionToolCall,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tStopReason,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.js\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { shortHash } from \"../utils/hash.js\";\nimport { parseStreamingJson } from \"../utils/json-parse.js\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.js\";\nimport { transformMessages } from \"./transform-messages.js\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignatureV1[\"phase\"]): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: TextSignatureV1[\"phase\"] } | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => ResponseCreateParamsStreaming[\"service_tier\"] | undefined;\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInput = [];\n\n\tconst normalizeIdPart = (part: string): string => {\n\t\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\t\treturn normalized.replace(/_+$/, \"\");\n\t};\n\n\tconst buildForeignResponsesItemId = (itemId: string): string => {\n\t\tconst normalized = `fc_${shortHash(itemId)}`;\n\t\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n\t};\n\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);\n\t\tif (!id.includes(\"|\")) return normalizeIdPart(id);\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst normalizedCallId = normalizeIdPart(callId);\n\t\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId);\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && context.systemPrompt) {\n\t\tconst role = model.reasoning ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\tconst parsedSignature = parseTextSignature(textBlock.textSignature);\n\t\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\t\tlet msgId = parsedSignature?.id;\n\t\t\t\t\tif (!msgId) {\n\t\t\t\t\t\tmsgId = `msg_${msgIndex}`;\n\t\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\t\tmsgId = `msg_${shortHash(msgId)}`;\n\t\t\t\t\t}\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: msgId,\n\t\t\t\t\t\tphase: parsedSignature?.phase,\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\tif (isDifferentModel && itemId?.startsWith(\"fc_\")) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst textResult = msg.content\n\t\t\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t\t\t.map((c) => c.text)\n\t\t\t\t.join(\"\\n\");\n\t\t\tconst hasImages = msg.content.some((c): c is ImageContent => c.type === \"image\");\n\t\t\tconst hasText = textResult.length > 0;\n\t\t\tconst [callId] = msg.toolCallId.split(\"|\");\n\n\t\t\tlet output: string | ResponseFunctionCallOutputItemList;\n\t\t\tif (hasImages && model.input.includes(\"image\")) {\n\t\t\t\tconst contentParts: ResponseFunctionCallOutputItemList = [];\n\n\t\t\t\tif (hasText) {\n\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\ttext: sanitizeSurrogates(textResult),\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tfor (const block of msg.content) {\n\t\t\t\t\tif (block.type === \"image\") {\n\t\t\t\t\t\tcontentParts.push({\n\t\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\t\timage_url: `data:${block.mimeType};base64,${block.data}`,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\toutput = contentParts;\n\t\t\t} else {\n\t\t\t\toutput = sanitizeSurrogates(hasText ? textResult : \"(see attached image)\");\n\t\t\t}\n\n\t\t\tmessages.push({\n\t\t\t\ttype: \"function_call_output\",\n\t\t\t\tcall_id: callId,\n\t\t\t\toutput,\n\t\t\t});\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst strict = options?.strict === undefined ? false : options.strict;\n\treturn tools.map((tool) => ({\n\t\ttype: \"function\",\n\t\tname: tool.name,\n\t\tdescription: tool.description,\n\t\tparameters: tool.parameters as any, // TypeBox already generates JSON Schema\n\t\tstrict,\n\t}));\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet currentItem: ResponseReasoningItem | ResponseOutputMessage | ResponseFunctionToolCall | null = null;\n\tlet currentBlock: ThinkingContent | TextContent | (ToolCall & { partialJson: string }) | null = null;\n\tconst blocks = output.content;\n\tconst blockIndex = () => blocks.length - 1;\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.created\") {\n\t\t\toutput.responseId = event.response.id;\n\t\t} else if (event.type === \"response.output_item.added\") {\n\t\t\tconst item = event.item;\n\t\t\tif (item.type === \"reasoning\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"thinking\", thinking: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"thinking_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"message\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = { type: \"text\", text: \"\" };\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"text_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tcurrentItem = item;\n\t\t\t\tcurrentBlock = {\n\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\tname: item.name,\n\t\t\t\t\targuments: {},\n\t\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t\t};\n\t\t\t\toutput.content.push(currentBlock);\n\t\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: blockIndex(), partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.added\") {\n\t\t\tif (currentItem && currentItem.type === \"reasoning\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tcurrentItem.summary.push(event.part);\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentItem.summary = currentItem.summary || [];\n\t\t\t\tconst lastPart = currentItem.summary[currentItem.summary.length - 1];\n\t\t\t\tif (lastPart) {\n\t\t\t\t\tcurrentBlock.thinking += \"\\n\\n\";\n\t\t\t\t\tlastPart.text += \"\\n\\n\";\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.reasoning_text.delta\") {\n\t\t\tif (currentItem?.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tcurrentBlock.thinking += event.delta;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (event.type === \"response.content_part.added\") {\n\t\t\tif (currentItem?.type === \"message\") {\n\t\t\t\tcurrentItem.content = currentItem.content || [];\n\t\t\t\t// Filter out ReasoningText, only accept output_text and refusal\n\t\t\t\tif (event.part.type === \"output_text\" || event.part.type === \"refusal\") {\n\t\t\t\t\tcurrentItem.content.push(event.part);\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"output_text\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.text += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tif (currentItem?.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tif (!currentItem.content || currentItem.content.length === 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst lastPart = currentItem.content[currentItem.content.length - 1];\n\t\t\t\tif (lastPart?.type === \"refusal\") {\n\t\t\t\t\tcurrentBlock.text += event.delta;\n\t\t\t\t\tlastPart.refusal += event.delta;\n\t\t\t\t\tstream.push({\n\t\t\t\t\t\ttype: \"text_delta\",\n\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tcurrentBlock.partialJson += event.delta;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tdelta: event.delta,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tif (currentItem?.type === \"function_call\" && currentBlock?.type === \"toolCall\") {\n\t\t\t\tconst previousPartialJson = currentBlock.partialJson;\n\t\t\t\tcurrentBlock.partialJson = event.arguments;\n\t\t\t\tcurrentBlock.arguments = parseStreamingJson(currentBlock.partialJson);\n\n\t\t\t\tif (event.arguments.startsWith(previousPartialJson)) {\n\t\t\t\t\tconst delta = event.arguments.slice(previousPartialJson.length);\n\t\t\t\t\tif (delta.length > 0) {\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"toolcall_delta\",\n\t\t\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\t\t\tdelta,\n\t\t\t\t\t\t\tpartial: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\n\t\t\tif (item.type === \"reasoning\" && currentBlock?.type === \"thinking\") {\n\t\t\t\tconst summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tconst contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tcurrentBlock.thinking = summaryText || contentText || currentBlock.thinking;\n\t\t\t\tcurrentBlock.thinkingSignature = JSON.stringify(item);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"message\" && currentBlock?.type === \"text\") {\n\t\t\t\tcurrentBlock.text = item.content.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\");\n\t\t\t\tcurrentBlock.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: blockIndex(),\n\t\t\t\t\tcontent: currentBlock.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\tcurrentBlock = null;\n\t\t\t} else if (item.type === \"function_call\") {\n\t\t\t\tconst args =\n\t\t\t\t\tcurrentBlock?.type === \"toolCall\" && currentBlock.partialJson\n\t\t\t\t\t\t? parseStreamingJson(currentBlock.partialJson)\n\t\t\t\t\t\t: parseStreamingJson(item.arguments || \"{}\");\n\n\t\t\t\tlet toolCall: ToolCall;\n\t\t\t\tif (currentBlock?.type === \"toolCall\") {\n\t\t\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t\t\t// carries parsed arguments.\n\t\t\t\t\tcurrentBlock.arguments = args;\n\t\t\t\t\tdelete (currentBlock as { partialJson?: string }).partialJson;\n\t\t\t\t\ttoolCall = currentBlock;\n\t\t\t\t} else {\n\t\t\t\t\ttoolCall = {\n\t\t\t\t\t\ttype: \"toolCall\",\n\t\t\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\t\t\tname: item.name,\n\t\t\t\t\t\targuments: args,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tcurrentBlock = null;\n\t\t\t\tstream.push({ type: \"toolcall_end\", contentIndex: blockIndex(), toolCall, partial: output });\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\") {\n\t\t\tconst response = event.response;\n\t\t\tif (response?.id) {\n\t\t\t\toutput.responseId = response.id;\n\t\t\t}\n\t\t\tif (response?.usage) {\n\t\t\t\tconst cachedTokens = response.usage.input_tokens_details?.cached_tokens || 0;\n\t\t\t\toutput.usage = {\n\t\t\t\t\t// OpenAI includes cached tokens in input_tokens, so subtract to get non-cached input\n\t\t\t\t\tinput: (response.usage.input_tokens || 0) - cachedTokens,\n\t\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\t\tcacheWrite: 0,\n\t\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tcalculateCost(model, output.usage);\n\t\t\tif (options?.applyServiceTierPricing) {\n\t\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t\t? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n\t\t\t\t\t: (response?.service_tier ?? options.serviceTier);\n\t\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\t}\n\t\t\t// Map status to stop reason\n\t\t\toutput.stopReason = mapStopReason(response?.status);\n\t\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\t\toutput.stopReason = \"toolUse\";\n\t\t\t}\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tconst error = event.response?.error;\n\t\t\tconst details = event.response?.incomplete_details;\n\t\t\tconst msg = error\n\t\t\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t\t\t: details?.reason\n\t\t\t\t\t? `incomplete: ${details.reason}`\n\t\t\t\t\t: \"Unknown error (no error details in response)\";\n\t\t\tthrow new Error(msg);\n\t\t}\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
2
+ import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.js";
3
+ export interface OpenAIResponsesOptions extends StreamOptions {
4
+ reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh";
5
+ reasoningSummary?: "auto" | "detailed" | "concise" | null;
6
+ serviceTier?: ResponseCreateParamsStreaming["service_tier"];
7
+ }
8
+ /**
9
+ * Generate function for OpenAI Responses API
10
+ */
11
+ export declare const streamOpenAIResponses: StreamFunction<"openai-responses", OpenAIResponsesOptions>;
12
+ export declare const streamSimpleOpenAIResponses: StreamFunction<"openai-responses", SimpleStreamOptions>;
13
+ //# sourceMappingURL=openai-responses.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/providers/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAG7F,OAAO,KAAK,EAOX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AAuCrB,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,CAAC;IAClE,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;CAC5D;AAED;;GAEG;AACH,eAAO,MAAM,qBAAqB,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CA4E5F,CAAC;AAEF,eAAO,MAAM,2BAA2B,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkB/F,CAAC","sourcesContent":["import OpenAI from \"openai\";\nimport type { ResponseCreateParamsStreaming } from \"openai/resources/responses/responses.js\";\nimport { getEnvApiKey } from \"../env-api-keys.js\";\nimport { clampThinkingLevel } from \"../models.js\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tCacheRetention,\n\tContext,\n\tModel,\n\tOpenAIResponsesCompat,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.js\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.js\";\nimport { headersToRecord } from \"../utils/headers.js\";\nimport { isCloudflareProvider, resolveCloudflareBaseUrl } from \"./cloudflare.js\";\nimport { buildCopilotDynamicHeaders, hasCopilotVisionInput } from \"./github-copilot-headers.js\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.js\";\nimport { buildBaseOptions } from \"./simple-options.js\";\n\nconst OPENAI_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\n\n/**\n * Resolve cache retention preference.\n * Defaults to \"short\" and uses AERY_CACHE_RETENTION for backward compatibility.\n */\nfunction resolveCacheRetention(cacheRetention?: CacheRetention): CacheRetention {\n\tif (cacheRetention) {\n\t\treturn cacheRetention;\n\t}\n\tif (typeof process !== \"undefined\" && process.env.AERY_CACHE_RETENTION === \"long\") {\n\t\treturn \"long\";\n\t}\n\treturn \"short\";\n}\n\nfunction getCompat(model: Model<\"openai-responses\">): Required<OpenAIResponsesCompat> {\n\treturn {\n\t\tsendSessionIdHeader: model.compat?.sendSessionIdHeader ?? true,\n\t\tsupportsLongCacheRetention: model.compat?.supportsLongCacheRetention ?? true,\n\t};\n}\n\nfunction getPromptCacheRetention(\n\tcompat: Required<OpenAIResponsesCompat>,\n\tcacheRetention: CacheRetention,\n): \"24h\" | undefined {\n\treturn cacheRetention === \"long\" && compat.supportsLongCacheRetention ? \"24h\" : undefined;\n}\n\n// OpenAI Responses-specific options\nexport interface OpenAIResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n\treasoningSummary?: \"auto\" | \"detailed\" | \"concise\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n}\n\n/**\n * Generate function for OpenAI Responses API\n */\nexport const streamOpenAIResponses: StreamFunction<\"openai-responses\", OpenAIResponsesOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: OpenAIResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t// Start async processing\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: model.api as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\t// Create OpenAI client\n\t\t\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider) || \"\";\n\t\t\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\t\t\tconst cacheSessionId = cacheRetention === \"none\" ? undefined : options?.sessionId;\n\t\t\tconst client = createClient(model, context, apiKey, options?.headers, cacheSessionId);\n\t\t\tlet params = buildParams(model, context, options);\n\t\t\tconst nextParams = await options?.onPayload?.(params, model);\n\t\t\tif (nextParams !== undefined) {\n\t\t\t\tparams = nextParams as ResponseCreateParamsStreaming;\n\t\t\t}\n\t\t\tconst requestOptions = {\n\t\t\t\t...(options?.signal ? { signal: options.signal } : {}),\n\t\t\t\t...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),\n\t\t\t\t...(options?.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}),\n\t\t\t};\n\t\t\tconst { data: openaiStream, response } = await client.responses.create(params, requestOptions).withResponse();\n\t\t\tawait options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\t\tstream.push({ type: \"start\", partial: output });\n\n\t\t\tawait processResponsesStream(openaiStream, output, stream, model, {\n\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t});\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tif (output.stopReason === \"aborted\" || output.stopReason === \"error\") {\n\t\t\t\tthrow new Error(\"An unknown error occurred\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason, message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\tdelete (block as { index?: number }).index;\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimpleOpenAIResponses: StreamFunction<\"openai-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey || getEnvApiKey(model.provider);\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\n\treturn streamOpenAIResponses(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAIResponsesOptions);\n};\n\nfunction createClient(\n\tmodel: Model<\"openai-responses\">,\n\tcontext: Context,\n\tapiKey?: string,\n\toptionsHeaders?: Record<string, string>,\n\tsessionId?: string,\n) {\n\tif (!apiKey) {\n\t\tif (!process.env.OPENAI_API_KEY) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OpenAI API key is required. Set OPENAI_API_KEY environment variable or pass it as an argument.\",\n\t\t\t);\n\t\t}\n\t\tapiKey = process.env.OPENAI_API_KEY;\n\t}\n\n\tconst compat = getCompat(model);\n\tconst headers = { ...model.headers };\n\tif (model.provider === \"github-copilot\") {\n\t\tconst hasImages = hasCopilotVisionInput(context.messages);\n\t\tconst copilotHeaders = buildCopilotDynamicHeaders({\n\t\t\tmessages: context.messages,\n\t\t\thasImages,\n\t\t});\n\t\tObject.assign(headers, copilotHeaders);\n\t}\n\n\tif (sessionId) {\n\t\tif (compat.sendSessionIdHeader) {\n\t\t\theaders.session_id = sessionId;\n\t\t}\n\t\theaders[\"x-client-request-id\"] = sessionId;\n\t}\n\n\t// Merge options headers last so they can override defaults\n\tif (optionsHeaders) {\n\t\tObject.assign(headers, optionsHeaders);\n\t}\n\n\tconst defaultHeaders =\n\t\tmodel.provider === \"cloudflare-ai-gateway\"\n\t\t\t? {\n\t\t\t\t\t...headers,\n\t\t\t\t\tAuthorization: headers.Authorization ?? null,\n\t\t\t\t\t\"cf-aig-authorization\": `Bearer ${apiKey}`,\n\t\t\t\t}\n\t\t\t: headers;\n\n\treturn new OpenAI({\n\t\tapiKey,\n\t\tbaseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,\n\t\tdangerouslyAllowBrowser: true,\n\t\tdefaultHeaders,\n\t});\n}\n\nfunction buildParams(model: Model<\"openai-responses\">, context: Context, options?: OpenAIResponsesOptions) {\n\tconst messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS);\n\n\tconst cacheRetention = resolveCacheRetention(options?.cacheRetention);\n\tconst compat = getCompat(model);\n\tconst params: ResponseCreateParamsStreaming = {\n\t\tmodel: model.id,\n\t\tinput: messages,\n\t\tstream: true,\n\t\tprompt_cache_key: cacheRetention === \"none\" ? undefined : options?.sessionId,\n\t\tprompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),\n\t\tstore: false,\n\t};\n\n\tif (options?.maxTokens) {\n\t\tparams.max_output_tokens = options?.maxTokens;\n\t}\n\n\tif (options?.temperature !== undefined) {\n\t\tparams.temperature = options?.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tparams.service_tier = options.serviceTier;\n\t}\n\n\tif (context.tools && context.tools.length > 0) {\n\t\tparams.tools = convertResponsesTools(context.tools);\n\t}\n\n\tif (model.reasoning) {\n\t\tif (options?.reasoningEffort || options?.reasoningSummary) {\n\t\t\tconst effort = options?.reasoningEffort\n\t\t\t\t? (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort)\n\t\t\t\t: \"medium\";\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: effort as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t\tsummary: options?.reasoningSummary || \"auto\",\n\t\t\t};\n\t\t\tparams.include = [\"reasoning.encrypted_content\"];\n\t\t} else if (model.provider !== \"github-copilot\" && model.thinkingLevelMap?.off !== null) {\n\t\t\tparams.reasoning = {\n\t\t\t\teffort: (model.thinkingLevelMap?.off ?? \"none\") as NonNullable<typeof params.reasoning>[\"effort\"],\n\t\t\t};\n\t\t}\n\t}\n\n\treturn params;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\tmodel: Pick<Model<\"openai-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n"]}