@openclaw/ai 2026.7.2-beta.5 → 2026.7.2-beta.7

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 (47) hide show
  1. package/dist/{anthropic-CQVj3le6.mjs → anthropic-CH4UUnZr.mjs} +14 -463
  2. package/dist/anthropic-usage-DWU-x8MI.mjs +459 -0
  3. package/dist/{azure-openai-responses-DIYgsqFM.mjs → azure-openai-responses-CImcwB83.mjs} +4 -3
  4. package/dist/azure-openai-responses-client-compat-C7K7QfUE.mjs +62 -0
  5. package/dist/cache-retention-0x979a5V.mjs +12 -0
  6. package/dist/deferred-event-buffer-DAvyP7qA.mjs +19 -0
  7. package/dist/github-copilot-headers-NCJtz9i0.mjs +37 -0
  8. package/dist/{google-f-A8xrae.mjs → google-CtSg0iTS.mjs} +3 -3
  9. package/dist/{google-shared-J6qvYINH.mjs → google-shared-DNBz5rcD.mjs} +5 -3
  10. package/dist/{google-vertex-D3yMVXIY.mjs → google-vertex-31f1uS9L.mjs} +3 -3
  11. package/dist/host-Dog2WQiR.mjs +369 -0
  12. package/dist/index.mjs +1 -1
  13. package/dist/internal/anthropic.d.mts +3 -53
  14. package/dist/internal/anthropic.mjs +3 -2
  15. package/dist/internal/openai.d.mts +259 -2
  16. package/dist/internal/openai.mjs +8 -4
  17. package/dist/internal/runtime.mjs +6 -4
  18. package/dist/internal/shared.d.mts +1 -1
  19. package/dist/internal/shared.mjs +5 -1
  20. package/dist/{llm-request-activity-CehVkZP-.mjs → llm-request-activity-BjtkplhG.mjs} +1 -19
  21. package/dist/{mistral-CKV-TOQj.mjs → mistral-CWmpvWYh.mjs} +5 -3
  22. package/dist/{openai-chatgpt-responses-CedIj0hk.mjs → openai-chatgpt-responses-B84Ibtrd.mjs} +18 -13
  23. package/dist/openai-completions-DsOxhOD1.mjs +630 -0
  24. package/dist/openai-completions-compat-DBWjXoMZ.d.mts +43 -0
  25. package/dist/openai-reasoning-compat-YgeLncHw.mjs +396 -0
  26. package/dist/openai-responses-BT7A3sLu.mjs +138 -0
  27. package/dist/openai-responses-shared-pXl6Wd8S.mjs +392 -0
  28. package/dist/{openai-D3PD6PE-.mjs → openai-responses-stream-internal-Cw5txaGW.mjs} +1409 -1863
  29. package/dist/openai-tool-projection-OhX64DoP.mjs +215 -0
  30. package/dist/{provider-error-apVOZI6G.mjs → provider-error-CAEvRjry.mjs} +1 -1
  31. package/dist/provider-options-D8bB3z9b.d.mts +144 -0
  32. package/dist/providers.mjs +8 -8
  33. package/dist/{stream-first-event-timeout-C3OgBjIk.mjs → reasoning-tag-text-partitioner-CGDyLWUR.mjs} +1 -86
  34. package/dist/simple-options-9lhRrN73.mjs +50 -0
  35. package/dist/stream-first-event-timeout-BBys9hSb.mjs +86 -0
  36. package/dist/tls-certificate-errors-DXSpluKI.mjs +93 -0
  37. package/dist/tool-result-text-CTpIRbYd.mjs +225 -0
  38. package/dist/{github-copilot-headers-BCoBNmL7.mjs → tool-schema-json-projection-BwNu3nDi.mjs} +1 -48
  39. package/dist/transform-messages-C8mBqZxF.mjs +2 -0
  40. package/dist/{transport-stream-shared-BbMELSI4.mjs → transport-stream-shared-D81p90xq.mjs} +4 -4
  41. package/dist/transports.d.mts +13 -33
  42. package/dist/transports.mjs +75 -34
  43. package/package.json +4 -4
  44. package/dist/host-XYGZcgO8.mjs +0 -98
  45. package/dist/openai-BPor_3WI.d.mts +0 -358
  46. package/dist/openai-completions-CiSutyu0.mjs +0 -1223
  47. package/dist/shared-CdjNZd35.mjs +0 -634
@@ -0,0 +1,630 @@
1
+ import { n as getEnvApiKey, r as __exportAll } from "./env-api-keys-DrgeBuva.mjs";
2
+ import { t as AssistantMessageEventStream } from "./event-stream-D8n2uFee.mjs";
3
+ import { n as getAiTransportHost } from "./host-Dog2WQiR.mjs";
4
+ import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-mZTCdRPo.mjs";
5
+ import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
6
+ import { u as splitSystemPromptCacheBoundary } from "./tool-result-text-CTpIRbYd.mjs";
7
+ import { n as reconcileOpenAICompletionsToolChoice, t as projectOpenAITools } from "./openai-tool-projection-OhX64DoP.mjs";
8
+ import { c as calculateCost, l as clampThinkingLevel, s as applyProviderReportedUsageCost } from "./number-coercion-DvG7SNMg.mjs";
9
+ import { a as resolveOpenAICompletionsCompat, c as clearPendingCommentaryText, l as rememberPendingCommentaryTags, n as mapOpenAIStopReason, o as resolveOpenAICompletionsResponseFormat, r as convertMessages, s as shouldOmitOllamaCompatResponseFormat, t as resolveOpenAIReasoningEffortMap, u as tagPendingCommentaryText } from "./openai-reasoning-compat-YgeLncHw.mjs";
10
+ import { n as parseStreamingJson } from "./json-parse-BvXNt1-7.mjs";
11
+ import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
12
+ import { d as transportAbortError } from "./transport-stream-shared-D81p90xq.mjs";
13
+ import { t as createReasoningTagTextPartitioner } from "./reasoning-tag-text-partitioner-CGDyLWUR.mjs";
14
+ import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-BBys9hSb.mjs";
15
+ import { t as headersToRecord } from "./headers-B_e4-1J0.mjs";
16
+ import { t as formatProviderError } from "./provider-error-CAEvRjry.mjs";
17
+ import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, r as isCloudflareProvider, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-NCJtz9i0.mjs";
18
+ import { n as buildBaseOptions } from "./simple-options-9lhRrN73.mjs";
19
+ import OpenAI from "openai";
20
+ //#region packages/ai/src/providers/openai-completions.ts
21
+ var openai_completions_exports = /* @__PURE__ */ __exportAll({
22
+ convertMessages: () => convertMessages,
23
+ streamOpenAICompletions: () => streamOpenAICompletions,
24
+ streamSimpleOpenAICompletions: () => streamSimpleOpenAICompletions
25
+ });
26
+ /**
27
+ * Check if conversation messages contain tool calls or tool results.
28
+ * This is needed because Anthropic (via proxy) requires the tools param
29
+ * to be present when messages include tool_calls or tool role messages.
30
+ */
31
+ function hasToolHistory(messages) {
32
+ for (const msg of messages) {
33
+ if (msg.role === "toolResult") return true;
34
+ if (msg.role === "assistant") {
35
+ if (Array.isArray(msg.content) && msg.content.some((block) => block.type === "toolCall")) return true;
36
+ }
37
+ }
38
+ return false;
39
+ }
40
+ function isEncryptedReasoningDetail(detail) {
41
+ if (typeof detail !== "object" || detail === null) return false;
42
+ const candidate = detail;
43
+ return candidate.type === "reasoning.encrypted" && typeof candidate.id === "string" && candidate.id.length > 0 && typeof candidate.data === "string" && candidate.data.length > 0;
44
+ }
45
+ const streamOpenAICompletions = (model, context, options) => {
46
+ const stream = new AssistantMessageEventStream();
47
+ (async () => {
48
+ const output = {
49
+ role: "assistant",
50
+ content: [],
51
+ api: model.api,
52
+ provider: model.provider,
53
+ model: model.id,
54
+ usage: {
55
+ input: 0,
56
+ output: 0,
57
+ cacheRead: 0,
58
+ cacheWrite: 0,
59
+ totalTokens: 0,
60
+ cost: {
61
+ input: 0,
62
+ output: 0,
63
+ cacheRead: 0,
64
+ cacheWrite: 0,
65
+ total: 0
66
+ }
67
+ },
68
+ stopReason: "stop",
69
+ timestamp: Date.now()
70
+ };
71
+ const provisionalCommentaryTags = /* @__PURE__ */ new Map();
72
+ let firstEventAbort;
73
+ try {
74
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
75
+ const compat = resolveOpenAICompletionsCompat(model);
76
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention);
77
+ const cacheSessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
78
+ const client = createClient(model, context, apiKey, options?.headers, cacheSessionId, compat);
79
+ let params = buildParams(model, context, options, compat, cacheRetention);
80
+ const nextParams = await options?.onPayload?.(params, model);
81
+ if (nextParams !== void 0) params = nextParams;
82
+ firstEventAbort = createFirstStreamEventAbortController(options?.signal);
83
+ const requestOptions = {
84
+ signal: firstEventAbort.signal,
85
+ ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
86
+ maxRetries: options?.maxRetries ?? 0
87
+ };
88
+ const { data: openaiStream, response } = await client.chat.completions.create(params, requestOptions).withResponse();
89
+ await options?.onResponse?.({
90
+ status: response.status,
91
+ headers: headersToRecord(response.headers)
92
+ }, model);
93
+ stream.push({
94
+ type: "start",
95
+ partial: output
96
+ });
97
+ let textBlock = null;
98
+ let thinkingBlock = null;
99
+ let hasFinishReason = false;
100
+ const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
101
+ const toolCallBlocksById = /* @__PURE__ */ new Map();
102
+ const toolCallBlocksByFirstId = /* @__PURE__ */ new Map();
103
+ const pendingReasoningDetailsByToolCallId = /* @__PURE__ */ new Map();
104
+ const blocks = output.content;
105
+ const finishedBlocks = /* @__PURE__ */ new Set();
106
+ const contentIndices = /* @__PURE__ */ new WeakMap();
107
+ const appendBlock = (block) => {
108
+ contentIndices.set(block, blocks.length);
109
+ blocks.push(block);
110
+ };
111
+ const getContentIndex = (block) => contentIndices.get(block) ?? -1;
112
+ const rememberFirstToolCallById = (id, block) => {
113
+ if (toolCallBlocksByFirstId.has(id)) return;
114
+ toolCallBlocksByFirstId.set(id, block);
115
+ const pendingDetail = pendingReasoningDetailsByToolCallId.get(id);
116
+ if (pendingDetail) {
117
+ block.thoughtSignature = pendingDetail;
118
+ pendingReasoningDetailsByToolCallId.delete(id);
119
+ }
120
+ };
121
+ const finishBlock = (block) => {
122
+ const contentIndex = getContentIndex(block);
123
+ if (contentIndex === -1 || finishedBlocks.has(block)) return;
124
+ finishedBlocks.add(block);
125
+ if (block.type === "text") stream.push({
126
+ type: "text_end",
127
+ contentIndex,
128
+ content: block.text,
129
+ partial: output
130
+ });
131
+ else if (block.type === "thinking") stream.push({
132
+ type: "thinking_end",
133
+ contentIndex,
134
+ content: block.thinking,
135
+ partial: output
136
+ });
137
+ else if (block.type === "toolCall") {
138
+ delete block.partialArgs;
139
+ delete block.streamIndex;
140
+ stream.push({
141
+ type: "toolcall_end",
142
+ contentIndex,
143
+ toolCall: block,
144
+ partial: output
145
+ });
146
+ }
147
+ };
148
+ const ensureTextBlock = () => {
149
+ if (!textBlock) {
150
+ textBlock = {
151
+ type: "text",
152
+ text: ""
153
+ };
154
+ appendBlock(textBlock);
155
+ stream.push({
156
+ type: "text_start",
157
+ contentIndex: getContentIndex(textBlock),
158
+ partial: output
159
+ });
160
+ }
161
+ return textBlock;
162
+ };
163
+ const ensureThinkingBlock = (thinkingSignature) => {
164
+ if (!thinkingBlock) {
165
+ thinkingBlock = {
166
+ type: "thinking",
167
+ thinking: "",
168
+ thinkingSignature
169
+ };
170
+ appendBlock(thinkingBlock);
171
+ stream.push({
172
+ type: "thinking_start",
173
+ contentIndex: getContentIndex(thinkingBlock),
174
+ partial: output
175
+ });
176
+ }
177
+ return thinkingBlock;
178
+ };
179
+ const sealNativeReasoningBeforeText = () => {
180
+ if (thinkingBlock && !reasoningTagTextPartitioner.isInsideReasoning()) {
181
+ finishBlock(thinkingBlock);
182
+ thinkingBlock = null;
183
+ }
184
+ };
185
+ const appendTextDelta = (delta) => {
186
+ sealNativeReasoningBeforeText();
187
+ const block = ensureTextBlock();
188
+ block.text += delta;
189
+ stream.push({
190
+ type: "text_delta",
191
+ contentIndex: getContentIndex(block),
192
+ delta,
193
+ partial: output
194
+ });
195
+ };
196
+ const appendThinkingDelta = (thinkingSignature, delta) => {
197
+ const block = ensureThinkingBlock(thinkingSignature);
198
+ block.thinking += delta;
199
+ stream.push({
200
+ type: "thinking_delta",
201
+ contentIndex: getContentIndex(block),
202
+ delta,
203
+ partial: output
204
+ });
205
+ };
206
+ const ensureToolCallBlock = (toolCall) => {
207
+ const streamIndex = typeof toolCall.index === "number" ? toolCall.index : void 0;
208
+ let block = streamIndex !== void 0 ? toolCallBlocksByIndex.get(streamIndex) : void 0;
209
+ if (!block && toolCall.id) block = toolCallBlocksById.get(toolCall.id);
210
+ if (!block) {
211
+ block = {
212
+ type: "toolCall",
213
+ id: toolCall.id || "",
214
+ name: toolCall.function?.name || "",
215
+ arguments: {},
216
+ partialArgs: "",
217
+ streamIndex
218
+ };
219
+ if (streamIndex !== void 0) toolCallBlocksByIndex.set(streamIndex, block);
220
+ if (toolCall.id) {
221
+ toolCallBlocksById.set(toolCall.id, block);
222
+ rememberFirstToolCallById(toolCall.id, block);
223
+ }
224
+ appendBlock(block);
225
+ stream.push({
226
+ type: "toolcall_start",
227
+ contentIndex: getContentIndex(block),
228
+ partial: output
229
+ });
230
+ }
231
+ if (streamIndex !== void 0 && block.streamIndex === void 0) {
232
+ block.streamIndex = streamIndex;
233
+ toolCallBlocksByIndex.set(streamIndex, block);
234
+ }
235
+ if (toolCall.id) toolCallBlocksById.set(toolCall.id, block);
236
+ return block;
237
+ };
238
+ const reasoningTagTextPartitioner = createReasoningTagTextPartitioner();
239
+ const appendPartitionedContent = (text, hasMirroredReasoning) => {
240
+ const routedDeltas = hasMirroredReasoning ? reasoningTagTextPartitioner.push(text) : reasoningTagTextPartitioner.pushVisible(text);
241
+ for (const delta of routedDeltas) if (delta.kind === "text") appendTextDelta(delta.text);
242
+ };
243
+ const flushPartitionedContent = () => {
244
+ for (const delta of reasoningTagTextPartitioner.flush()) if (delta.kind === "text") appendTextDelta(delta.text);
245
+ };
246
+ const guardedOpenaiStream = withFirstStreamEventTimeout(openaiStream, {
247
+ provider: model.provider,
248
+ api: model.api,
249
+ model: model.id,
250
+ timeoutMs: getFirstStreamEventTimeoutMs(options) ?? 0,
251
+ stage: "completions",
252
+ abort: firstEventAbort.abort,
253
+ onTimeout: getFirstStreamEventTimeoutHandler(options),
254
+ hint: "The provider may be stalled while parsing the tool payload; retry with a smaller tool surface or enable OPENCLAW_DEBUG_MODEL_PAYLOAD=tools to inspect exposed tools."
255
+ });
256
+ for await (const chunk of guardedOpenaiStream) {
257
+ if (!chunk || typeof chunk !== "object") continue;
258
+ notifyLlmRequestActivity(options?.signal);
259
+ output.responseId ||= chunk.id;
260
+ if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
261
+ if (chunk.usage) output.usage = parseChunkUsage(chunk.usage, model);
262
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
263
+ if (!choice) continue;
264
+ const choiceUsage = choice.usage;
265
+ if (!chunk.usage && choiceUsage) output.usage = parseChunkUsage(choiceUsage, model);
266
+ if (choice.finish_reason) {
267
+ const finishReasonResult = mapOpenAIStopReason(choice.finish_reason);
268
+ output.stopReason = finishReasonResult.stopReason;
269
+ if (finishReasonResult.errorMessage) output.errorMessage = finishReasonResult.errorMessage;
270
+ hasFinishReason = true;
271
+ }
272
+ const choiceDelta = choice.delta ?? choice.message;
273
+ if (choiceDelta) {
274
+ const reasoningFields = [
275
+ "reasoning_content",
276
+ "reasoning",
277
+ "reasoning_text"
278
+ ];
279
+ const deltaFields = choiceDelta;
280
+ const shouldEmitReasoning = Boolean(model.reasoning && options?.reasoningEffort);
281
+ let foundReasoningField = null;
282
+ for (const field of reasoningFields) {
283
+ const value = deltaFields[field];
284
+ if (typeof value === "string" && value.length > 0) {
285
+ foundReasoningField = field;
286
+ break;
287
+ }
288
+ }
289
+ if (foundReasoningField) reasoningTagTextPartitioner.markStrict();
290
+ if (shouldEmitReasoning && foundReasoningField) {
291
+ const delta = deltaFields[foundReasoningField];
292
+ if (typeof delta === "string" && delta.length > 0) appendThinkingDelta(model.provider === "opencode-go" && foundReasoningField === "reasoning" ? "reasoning_content" : foundReasoningField, delta);
293
+ }
294
+ if (choiceDelta.content !== null && choiceDelta.content !== void 0 && choiceDelta.content.length > 0) appendPartitionedContent(choiceDelta.content, Boolean(foundReasoningField));
295
+ const refusalText = typeof choiceDelta.refusal === "string" ? choiceDelta.refusal : "";
296
+ if (refusalText.length > 0) appendPartitionedContent(refusalText, Boolean(foundReasoningField));
297
+ if (choiceDelta.tool_calls && choiceDelta.tool_calls.length > 0) {
298
+ flushPartitionedContent();
299
+ sealNativeReasoningBeforeText();
300
+ rememberPendingCommentaryTags(provisionalCommentaryTags, tagPendingCommentaryText(output.content));
301
+ for (const toolCall of choiceDelta.tool_calls) {
302
+ const block = ensureToolCallBlock(toolCall);
303
+ if (!block.id && toolCall.id) {
304
+ block.id = toolCall.id;
305
+ toolCallBlocksById.set(toolCall.id, block);
306
+ rememberFirstToolCallById(toolCall.id, block);
307
+ }
308
+ if (!block.name && toolCall.function?.name) block.name = toolCall.function.name;
309
+ let delta = "";
310
+ if (toolCall.function?.arguments) {
311
+ delta = toolCall.function.arguments;
312
+ block.partialArgs = (block.partialArgs ?? "") + toolCall.function.arguments;
313
+ block.arguments = parseStreamingJson(block.partialArgs);
314
+ }
315
+ stream.push({
316
+ type: "toolcall_delta",
317
+ contentIndex: getContentIndex(block),
318
+ delta,
319
+ partial: output
320
+ });
321
+ }
322
+ }
323
+ const reasoningDetails = choiceDelta.reasoning_details;
324
+ if (Array.isArray(reasoningDetails)) {
325
+ for (const detail of reasoningDetails) if (isEncryptedReasoningDetail(detail)) {
326
+ const serializedDetail = JSON.stringify(detail);
327
+ const matchingToolCall = toolCallBlocksByFirstId.get(detail.id);
328
+ if (matchingToolCall) matchingToolCall.thoughtSignature = serializedDetail;
329
+ else pendingReasoningDetailsByToolCallId.set(detail.id, serializedDetail);
330
+ }
331
+ }
332
+ }
333
+ }
334
+ flushPartitionedContent();
335
+ for (const block of blocks) finishBlock(block);
336
+ if (options?.signal?.aborted) throw transportAbortError(options.signal);
337
+ if (output.stopReason === "aborted") throw new Error("Request was aborted");
338
+ if (output.stopReason === "error") throw new Error(output.errorMessage || "Provider returned an error stop reason");
339
+ if (!hasFinishReason) throw new Error("Stream ended without finish_reason");
340
+ const hasToolCalls = output.content.some((block) => block.type === "toolCall");
341
+ const hasVisibleText = output.content.some((block) => block.type === "text" && block.text.trim().length > 0);
342
+ if (output.stopReason === "toolUse" && !hasToolCalls) output.stopReason = "stop";
343
+ if (output.stopReason === "stop" && hasToolCalls && !hasVisibleText) output.stopReason = "toolUse";
344
+ if (hasToolCalls && output.stopReason !== "toolUse") output.content = output.content.filter((block) => block.type !== "toolCall");
345
+ if (output.stopReason !== "toolUse") clearPendingCommentaryText(provisionalCommentaryTags);
346
+ if (output.stopReason === "toolUse") tagPendingCommentaryText(output.content);
347
+ stream.push({
348
+ type: "done",
349
+ reason: output.stopReason,
350
+ message: output
351
+ });
352
+ stream.end();
353
+ } catch (error) {
354
+ for (const block of output.content) {
355
+ delete block.index;
356
+ delete block.partialArgs;
357
+ delete block.streamIndex;
358
+ }
359
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
360
+ output.errorMessage = formatProviderError(error);
361
+ const rawMetadata = error?.error?.metadata?.raw;
362
+ if (rawMetadata && !output.errorMessage.includes(rawMetadata)) output.errorMessage += `\n${rawMetadata}`;
363
+ stream.push({
364
+ type: "error",
365
+ reason: output.stopReason,
366
+ error: output
367
+ });
368
+ stream.end();
369
+ } finally {
370
+ firstEventAbort?.dispose();
371
+ }
372
+ })();
373
+ return stream;
374
+ };
375
+ const streamSimpleOpenAICompletions = (model, context, options) => {
376
+ const apiKey = options?.apiKey || getEnvApiKey(model.provider);
377
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
378
+ const base = buildBaseOptions(model, options, apiKey);
379
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
380
+ const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning === "max" ? "xhigh" : clampedReasoning;
381
+ const toolChoice = options?.toolChoice;
382
+ return streamOpenAICompletions(model, context, {
383
+ ...base,
384
+ reasoningEffort,
385
+ toolChoice
386
+ });
387
+ };
388
+ function createClient(model, context, apiKey, optionsHeaders, sessionId, compat = resolveOpenAICompletionsCompat(model)) {
389
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
390
+ const headers = { ...model.headers };
391
+ if (model.provider === "github-copilot") {
392
+ const hasImages = hasCopilotVisionInput(context.messages);
393
+ const copilotHeaders = buildCopilotDynamicHeaders({
394
+ messages: context.messages,
395
+ hasImages
396
+ });
397
+ Object.assign(headers, copilotHeaders);
398
+ }
399
+ if (sessionId && compat.sessionAffinity !== "none") if (compat.sessionAffinity === "openrouter") headers["x-session-id"] = sessionId;
400
+ else {
401
+ headers.session_id = sessionId;
402
+ headers["x-client-request-id"] = sessionId;
403
+ headers["x-session-affinity"] = sessionId;
404
+ }
405
+ if (optionsHeaders) Object.assign(headers, optionsHeaders);
406
+ const defaultHeaders = model.provider === "cloudflare-ai-gateway" ? {
407
+ ...headers,
408
+ Authorization: headers.Authorization ?? null,
409
+ "cf-aig-authorization": `Bearer ${apiKey}`
410
+ } : headers;
411
+ return new OpenAI({
412
+ apiKey,
413
+ baseURL: isCloudflareProvider(model.provider) ? resolveCloudflareBaseUrl(model) : model.baseUrl,
414
+ dangerouslyAllowBrowser: true,
415
+ defaultHeaders,
416
+ fetch: getAiTransportHost().buildModelFetch(model)
417
+ });
418
+ }
419
+ function buildParams(model, context, options, compat = resolveOpenAICompletionsCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention)) {
420
+ const cacheControl = getCompatCacheControl(compat, cacheRetention);
421
+ const cacheOptOutIndexes = /* @__PURE__ */ new Set();
422
+ const messages = convertMessages(model, context, compat, {
423
+ cacheOptOutIndexes,
424
+ preserveSystemPromptCacheBoundary: cacheControl !== void 0
425
+ });
426
+ const supportsPromptCacheKey = model.baseUrl.includes("api.openai.com") || compat.supportsPromptCacheKey;
427
+ const promptCacheKey = supportsPromptCacheKey && cacheRetention !== "none" ? clampOpenAIPromptCacheKey(options?.promptCacheKey ?? options?.sessionId) : void 0;
428
+ const params = {
429
+ model: model.id,
430
+ messages,
431
+ stream: true,
432
+ prompt_cache_key: promptCacheKey,
433
+ prompt_cache_retention: supportsPromptCacheKey && cacheRetention === "long" && compat.supportsLongCacheRetention ? "24h" : void 0
434
+ };
435
+ if (compat.supportsUsageInStreaming) params.stream_options = { include_usage: true };
436
+ if (compat.supportsStore) params.store = false;
437
+ if (options?.maxTokens) {
438
+ const maxTokens = clampOpenAICompletionsMaxTokens(model, options.maxTokens);
439
+ if (compat.maxTokensField === "max_tokens") params.max_tokens = maxTokens;
440
+ else params.max_completion_tokens = maxTokens;
441
+ }
442
+ if (options?.temperature !== void 0) params.temperature = options.temperature;
443
+ if (options?.stop !== void 0 && options.stop.length > 0) params.stop = options.stop;
444
+ const requestedResponseFormat = options?.responseFormat;
445
+ const responseFormat = requestedResponseFormat === void 0 ? void 0 : resolveOpenAICompletionsResponseFormat(shouldOmitOllamaCompatResponseFormat({
446
+ provider: model.provider,
447
+ baseUrl: model.baseUrl,
448
+ hasTools: () => Boolean(context.tools?.length)
449
+ }) ? void 0 : requestedResponseFormat, compat.supportsJsonSchemaResponseFormat);
450
+ if (responseFormat !== void 0) params.response_format = responseFormat;
451
+ let toolProjection;
452
+ if (context.tools) {
453
+ const converted = convertTools(context.tools, compat);
454
+ toolProjection = converted.projection;
455
+ if (converted.tools.length > 0) params.tools = converted.tools;
456
+ else if (hasToolHistory(context.messages)) params.tools = [];
457
+ if (compat.zaiToolStream && converted.tools.length > 0) params.tool_stream = true;
458
+ } else if (hasToolHistory(context.messages)) params.tools = [];
459
+ if (cacheControl) applyAnthropicCacheControl(messages, params.tools, cacheControl, cacheOptOutIndexes);
460
+ if (options?.toolChoice) {
461
+ const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, toolProjection ?? projectOpenAITools([]));
462
+ if (toolChoice !== void 0) params.tool_choice = toolChoice;
463
+ }
464
+ const reasoningEffortMap = resolveOpenAIReasoningEffortMap(model);
465
+ const thinkingLevelMap = model.thinkingLevelMap;
466
+ const reasoningEffort = options?.reasoningEffort === void 0 ? void 0 : reasoningEffortMap[options.reasoningEffort] ?? thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
467
+ const reasoningEnabled = reasoningEffort !== void 0 && reasoningEffort !== "none";
468
+ const offReasoningEffort = reasoningEffortMap.off ?? model.thinkingLevelMap?.off;
469
+ if (compat.thinkingFormat === "zai" && model.reasoning) params.thinking = reasoningEnabled ? {
470
+ type: "enabled",
471
+ clear_thinking: false
472
+ } : { type: "disabled" };
473
+ else if (compat.thinkingFormat === "qwen" && model.reasoning) params.enable_thinking = reasoningEnabled;
474
+ else if (compat.thinkingFormat === "qwen-chat-template" && model.reasoning) params.chat_template_kwargs = {
475
+ enable_thinking: reasoningEnabled,
476
+ preserve_thinking: true
477
+ };
478
+ else if (compat.thinkingFormat === "deepseek" && model.reasoning) {
479
+ params.thinking = { type: reasoningEnabled ? "enabled" : "disabled" };
480
+ if (reasoningEnabled && compat.supportsReasoningEffort) params.reasoning_effort = reasoningEffort;
481
+ } else if (compat.thinkingFormat === "openrouter" && model.reasoning) {
482
+ const openRouterParams = params;
483
+ if (reasoningEnabled) openRouterParams.reasoning = { effort: reasoningEffort };
484
+ else if (offReasoningEffort !== null) openRouterParams.reasoning = { effort: offReasoningEffort ?? "none" };
485
+ } else if (compat.thinkingFormat === "together" && model.reasoning) {
486
+ const togetherParams = params;
487
+ togetherParams.reasoning = { enabled: reasoningEnabled };
488
+ if (reasoningEnabled && compat.supportsReasoningEffort) togetherParams.reasoning_effort = reasoningEffort;
489
+ } else if (reasoningEnabled && model.reasoning && compat.supportsReasoningEffort) params.reasoning_effort = reasoningEffort;
490
+ else if (model.reasoning && compat.supportsReasoningEffort) {
491
+ if (typeof offReasoningEffort === "string") params.reasoning_effort = offReasoningEffort;
492
+ }
493
+ if (compat.openRouterRouting) params.provider = compat.openRouterRouting;
494
+ if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
495
+ const routing = model.compat.vercelGatewayRouting;
496
+ if (routing.only || routing.order) {
497
+ const gatewayOptions = {};
498
+ if (routing.only) gatewayOptions.only = routing.only;
499
+ if (routing.order) gatewayOptions.order = routing.order;
500
+ params.providerOptions = { gateway: gatewayOptions };
501
+ }
502
+ }
503
+ return params;
504
+ }
505
+ function clampOpenAICompletionsMaxTokens(model, requestedMaxTokens) {
506
+ const modelMaxTokens = typeof model.maxTokens === "number" && Number.isFinite(model.maxTokens) && model.maxTokens > 0 ? Math.floor(model.maxTokens) : void 0;
507
+ return modelMaxTokens === void 0 || requestedMaxTokens <= modelMaxTokens ? requestedMaxTokens : modelMaxTokens;
508
+ }
509
+ function getCompatCacheControl(compat, cacheRetention) {
510
+ if (compat.cacheControlFormat !== "anthropic" || cacheRetention === "none") return;
511
+ const ttl = cacheRetention === "long" && compat.supportsLongCacheRetention ? "1h" : void 0;
512
+ return {
513
+ type: "ephemeral",
514
+ ...ttl ? { ttl } : {}
515
+ };
516
+ }
517
+ function applyAnthropicCacheControl(messages, tools, cacheControl, cacheOptOutIndexes) {
518
+ addCacheControlToSystemPrompt(messages, cacheControl);
519
+ addCacheControlToLastTool(tools, cacheControl);
520
+ addCacheControlToLastConversationMessage(messages, cacheControl, cacheOptOutIndexes);
521
+ }
522
+ function addCacheControlToSystemPrompt(messages, cacheControl) {
523
+ for (const message of messages) if (message.role === "system" || message.role === "developer") {
524
+ addCacheControlToInstructionMessage(message, cacheControl);
525
+ return;
526
+ }
527
+ }
528
+ function addCacheControlToLastConversationMessage(messages, cacheControl, cacheOptOutIndexes) {
529
+ for (let i = messages.length - 1; i >= 0; i--) {
530
+ const message = messages[i];
531
+ if (!message || cacheOptOutIndexes.has(i)) continue;
532
+ if (message.role === "user" || message.role === "assistant") {
533
+ if (addCacheControlToMessage(message, cacheControl)) return;
534
+ }
535
+ }
536
+ }
537
+ function addCacheControlToLastTool(tools, cacheControl) {
538
+ if (!tools || tools.length === 0) return;
539
+ const lastTool = tools.at(-1);
540
+ if (!lastTool) return;
541
+ lastTool.cache_control = cacheControl;
542
+ }
543
+ function addCacheControlToInstructionMessage(message, cacheControl) {
544
+ return addCacheControlToTextContent(message, cacheControl);
545
+ }
546
+ function addCacheControlToMessage(message, cacheControl) {
547
+ if (message.role === "user" || message.role === "assistant") return addCacheControlToTextContent(message, cacheControl);
548
+ return false;
549
+ }
550
+ function addCacheControlToTextContent(message, cacheControl) {
551
+ const content = message.content;
552
+ if (typeof content === "string") {
553
+ if (content.length === 0) return false;
554
+ message.content = buildCacheControlledTextParts(content, cacheControl);
555
+ return true;
556
+ }
557
+ if (!Array.isArray(content)) return false;
558
+ for (let i = content.length - 1; i >= 0; i--) {
559
+ const part = content[i];
560
+ if (part?.type === "text") {
561
+ const text = part.text;
562
+ content.splice(i, 1, ...buildCacheControlledTextParts(text, cacheControl));
563
+ return true;
564
+ }
565
+ }
566
+ return false;
567
+ }
568
+ function buildCacheControlledTextParts(text, cacheControl) {
569
+ const split = splitSystemPromptCacheBoundary(text);
570
+ if (!split) return [{
571
+ type: "text",
572
+ text,
573
+ cache_control: cacheControl
574
+ }];
575
+ const parts = [];
576
+ if (split.stablePrefix) parts.push({
577
+ type: "text",
578
+ text: split.stablePrefix,
579
+ cache_control: cacheControl
580
+ });
581
+ if (split.dynamicSuffix) parts.push({
582
+ type: "text",
583
+ text: split.dynamicSuffix
584
+ });
585
+ return parts.length > 0 ? parts : [{
586
+ type: "text",
587
+ text: ""
588
+ }];
589
+ }
590
+ function convertTools(tools, compat) {
591
+ const projection = projectOpenAITools(tools);
592
+ return {
593
+ projection,
594
+ tools: projection.tools.map((tool) => ({
595
+ type: "function",
596
+ function: {
597
+ name: tool.name,
598
+ description: tool.description,
599
+ parameters: tool.parameters,
600
+ ...compat.supportsStrictMode && { strict: false }
601
+ }
602
+ }))
603
+ };
604
+ }
605
+ function parseChunkUsage(rawUsage, model) {
606
+ const promptTokens = rawUsage.prompt_tokens || 0;
607
+ const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;
608
+ const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;
609
+ const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
610
+ const outputTokens = rawUsage.completion_tokens || 0;
611
+ const usage = {
612
+ input,
613
+ output: outputTokens,
614
+ cacheRead: cacheReadTokens,
615
+ cacheWrite: cacheWriteTokens,
616
+ totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,
617
+ cost: {
618
+ input: 0,
619
+ output: 0,
620
+ cacheRead: 0,
621
+ cacheWrite: 0,
622
+ total: 0
623
+ }
624
+ };
625
+ calculateCost(model, usage);
626
+ applyProviderReportedUsageCost(usage, rawUsage.cost);
627
+ return usage;
628
+ }
629
+ //#endregion
630
+ export { streamOpenAICompletions as n, streamSimpleOpenAICompletions as r, openai_completions_exports as t };
@@ -0,0 +1,43 @@
1
+ import { E as Model, O as OpenAICompletionsCompat } from "./types-bzp5k29J.mjs";
2
+ import { a as AiProviderRequestPolicyInput, i as AiProviderRequestCapabilities } from "./host-B9GUmcra.mjs";
3
+
4
+ //#region packages/ai/src/transports/openai-completions-compat.d.ts
5
+ type ProviderRequestCapabilities = AiProviderRequestCapabilities;
6
+ type OpenAICompletionsSessionAffinity = "none" | "openai" | "openrouter";
7
+ type OpenAICompletionsCompatDefaults = {
8
+ supportsStore: boolean;
9
+ supportsDeveloperRole: boolean;
10
+ supportsReasoningEffort: boolean;
11
+ supportsUsageInStreaming: boolean;
12
+ maxTokensField: "max_completion_tokens" | "max_tokens";
13
+ thinkingFormat: "openai" | "openrouter" | "deepseek" | "together" | "zai";
14
+ visibleReasoningDetailTypes: string[];
15
+ supportsStrictMode: boolean;
16
+ supportsJsonSchemaResponseFormat: boolean;
17
+ requiresReasoningContentOnAssistantMessages: boolean;
18
+ requiresNonEmptyUserOrAssistantMessage: boolean;
19
+ cacheControlFormat?: OpenAICompletionsCompat["cacheControlFormat"];
20
+ sessionAffinityFormat: Exclude<OpenAICompletionsSessionAffinity, "none">;
21
+ supportsLongCacheRetention: boolean;
22
+ };
23
+ type DetectedOpenAICompletionsCompat = {
24
+ capabilities: ProviderRequestCapabilities;
25
+ defaults: OpenAICompletionsCompatDefaults;
26
+ };
27
+ type ResolvedOpenAICompletionsCompat = Omit<Required<OpenAICompletionsCompat>, "cacheControlFormat" | "openRouterRouting" | "sendSessionAffinityHeaders"> & {
28
+ cacheControlFormat?: OpenAICompletionsCompat["cacheControlFormat"];
29
+ openRouterRouting?: OpenAICompletionsCompat["openRouterRouting"];
30
+ sessionAffinity: OpenAICompletionsSessionAffinity;
31
+ visibleReasoningDetailTypes: string[];
32
+ requiresNonEmptyUserOrAssistantMessage: boolean;
33
+ };
34
+ /** Detects endpoint capabilities and defaults for an OpenAI-completions model. */
35
+ declare function detectOpenAICompletionsCompat(model: Pick<Model<"openai-completions">, "provider" | "baseUrl" | "id"> & {
36
+ compat?: {
37
+ supportsStore?: boolean;
38
+ } | null;
39
+ }, resolveCapabilities?: (input: AiProviderRequestPolicyInput) => ProviderRequestCapabilities): DetectedOpenAICompletionsCompat;
40
+ /** Applies explicit model overrides once on top of the canonical transport defaults. */
41
+ declare function resolveOpenAICompletionsCompat(model: Model<"openai-completions">, resolveCapabilities?: (input: AiProviderRequestPolicyInput) => ProviderRequestCapabilities): ResolvedOpenAICompletionsCompat;
42
+ //#endregion
43
+ export { detectOpenAICompletionsCompat as n, resolveOpenAICompletionsCompat as r, ResolvedOpenAICompletionsCompat as t };