@nexface/agent 0.1.15-alpha.0 → 0.1.15-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/agent.d.ts +1 -2
  2. package/dist/agent.js +936 -334
  3. package/dist/browser-policy/gpt.js +36 -12
  4. package/dist/browser-policy/jev.js +21 -9
  5. package/dist/browser-policy/response-error.js +4 -2
  6. package/dist/browser-policy/shared.js +49 -21
  7. package/dist/browser-prompt.d.ts +1 -1
  8. package/dist/browser-prompt.generated.d.ts +1 -1
  9. package/dist/browser-prompt.generated.js +6 -3
  10. package/dist/browser-prompt.js +0 -1
  11. package/dist/errors.d.ts +2 -2
  12. package/dist/errors.js +3 -4
  13. package/dist/history-compaction.js +47 -26
  14. package/dist/history-version.js +11 -4
  15. package/dist/index.js +0 -1
  16. package/dist/model/binding.js +0 -1
  17. package/dist/model/error.js +0 -1
  18. package/dist/model/internal-adapter.js +1 -2
  19. package/dist/model/types.js +0 -1
  20. package/dist/models/3.js +5553 -0
  21. package/dist/models/3e.js +4 -0
  22. package/dist/models/6.js +506 -0
  23. package/dist/models/anthropic-messages.js +5 -20
  24. package/dist/models/anthropic-messages~1.js +5629 -0
  25. package/dist/models/deferred-tools.js +28 -0
  26. package/dist/models/error-body.js +64 -0
  27. package/dist/models/google-generative-ai.js +4 -19
  28. package/dist/models/google-generative-ai~1.js +18305 -0
  29. package/dist/models/google-generative-ai~1.js.LICENSE.txt +5 -0
  30. package/dist/models/{39.js → k.js} +168 -336
  31. package/dist/models/openai-completions.js +3 -10
  32. package/dist/models/openai-completions~1.js +987 -0
  33. package/dist/models/openai-responses.js +3 -10
  34. package/dist/models/openai-responses~1.js +848 -0
  35. package/dist/models/rslib-runtime.js +32 -56
  36. package/dist/models/v.js +346 -0
  37. package/dist/page-decision.js +197 -59
  38. package/dist/page-decisions/gpt.js +0 -1
  39. package/dist/page-decisions/jev.js +0 -1
  40. package/dist/page-decisions/shared.js +26 -9
  41. package/dist/page-diagnostics.js +8 -3
  42. package/dist/page-observation.js +11 -6
  43. package/dist/request.js +169 -41
  44. package/dist/shared/definition.js +2 -3
  45. package/dist/shared/errors.d.ts +1 -1
  46. package/dist/shared/errors.js +0 -1
  47. package/dist/shared/page-protocol.js +0 -1
  48. package/dist/shared/page-tools.js +2 -3
  49. package/dist/shared/runtime-controller.d.ts +1 -0
  50. package/dist/shared/runtime-controller.js +0 -1
  51. package/dist/shared/runtime-execution.js +0 -1
  52. package/dist/shared/schema.js +45 -19
  53. package/dist/tool-catalog.js +23 -25
  54. package/dist/tool-result.js +7 -3
  55. package/dist/types.js +0 -1
  56. package/package.json +6 -2
  57. package/dist/agent.js.map +0 -1
  58. package/dist/browser-policy/gpt.js.map +0 -1
  59. package/dist/browser-policy/jev.js.map +0 -1
  60. package/dist/browser-policy/response-error.js.map +0 -1
  61. package/dist/browser-policy/shared.js.map +0 -1
  62. package/dist/browser-prompt.generated.js.map +0 -1
  63. package/dist/browser-prompt.js.map +0 -1
  64. package/dist/errors.js.map +0 -1
  65. package/dist/history-compaction.js.map +0 -1
  66. package/dist/history-version.js.map +0 -1
  67. package/dist/index.js.map +0 -1
  68. package/dist/model/binding.js.map +0 -1
  69. package/dist/model/error.js.map +0 -1
  70. package/dist/model/internal-adapter.js.map +0 -1
  71. package/dist/model/types.js.map +0 -1
  72. package/dist/models/851.js +0 -10
  73. package/dist/models/_chunks/360-7e580bb2.js +0 -1189
  74. package/dist/models/_chunks/474-e1813138.js +0 -8304
  75. package/dist/models/_chunks/86-c0c5ac98.js +0 -453
  76. package/dist/models/_chunks/anthropic-messages~1-d35e3e7d.js +0 -8057
  77. package/dist/models/_chunks/deferred-tools-90f3c977.js +0 -37
  78. package/dist/models/_chunks/error-body-8bee35c2.js +0 -134
  79. package/dist/models/_chunks/google-generative-ai~1-2ba71457.js +0 -22104
  80. package/dist/models/_chunks/openai-completions~1-b340f0e0.js +0 -1285
  81. package/dist/models/_chunks/openai-responses~1-b53c65c2.js +0 -958
  82. package/dist/page-decision.js.map +0 -1
  83. package/dist/page-decisions/gpt.js.map +0 -1
  84. package/dist/page-decisions/jev.js.map +0 -1
  85. package/dist/page-decisions/shared.js.map +0 -1
  86. package/dist/page-diagnostics.js.map +0 -1
  87. package/dist/page-observation.js.map +0 -1
  88. package/dist/request.js.map +0 -1
  89. package/dist/shared/definition.js.map +0 -1
  90. package/dist/shared/errors.js.map +0 -1
  91. package/dist/shared/page-protocol.js.map +0 -1
  92. package/dist/shared/page-tools.js.map +0 -1
  93. package/dist/shared/runtime-controller.js.map +0 -1
  94. package/dist/shared/runtime-execution.js.map +0 -1
  95. package/dist/shared/schema.js.map +0 -1
  96. package/dist/shared/tool-registry.d.ts +0 -6
  97. package/dist/shared/tool-registry.js +0 -10
  98. package/dist/shared/tool-registry.js.map +0 -1
  99. package/dist/tool-catalog.js.map +0 -1
  100. package/dist/tool-result.js.map +0 -1
  101. package/dist/types.js.map +0 -1
@@ -0,0 +1,987 @@
1
+ import { OpenAI, shortHash, clampOpenAIPromptCacheKey } from "./3.js";
2
+ import { getProviderEnvValue, buildCopilotDynamicHeaders, parseStreamingJson, hasCopilotVisionInput } from "./v.js";
3
+ import { AssistantMessageEventStream } from "./k.js";
4
+ import { sanitizeSurrogates, appendGrammarToolInputJsonDelta, resolveGrammarConstrainedSampling, getGrammarToolInput, headersToRecord, clampThinkingLevel, clampReasoning, resolveJsonSchemaStrictSampling, transformMessages, calculateCost, buildBaseOptions, retryProviderRequest, createGrammarToolInputProperties } from "./6.js";
5
+ import { formatProviderError, normalizeProviderError } from "./error-body.js";
6
+ function hasHeader(headers, name) {
7
+ if (!headers) return false;
8
+ const expected = name.toLowerCase();
9
+ for (const [key, value] of Object.entries(headers))if (key.toLowerCase() === expected && null !== value && value.trim().length > 0) return true;
10
+ return false;
11
+ }
12
+ function getClientApiKey(provider, apiKey, headers) {
13
+ if (apiKey) return apiKey;
14
+ if (hasHeader(headers, "authorization") || hasHeader(headers, "cf-aig-authorization")) return "unused";
15
+ throw new Error(`No API key for provider: ${provider}`);
16
+ }
17
+ function hasToolHistory(messages) {
18
+ for (const msg of messages){
19
+ if ("toolResult" === msg.role) return true;
20
+ if ("assistant" === msg.role) {
21
+ if (msg.content.some((block)=>"toolCall" === block.type)) return true;
22
+ }
23
+ }
24
+ return false;
25
+ }
26
+ function getDeferredToolNames(messages) {
27
+ const names = new Set();
28
+ for (const message of messages)if ("toolResult" === message.role) for (const name of message.addedToolNames ?? [])names.add(name);
29
+ return names;
30
+ }
31
+ function getToolsByName(tools, names) {
32
+ if (!tools) return [];
33
+ const toolsByName = new Map(tools.map((tool)=>[
34
+ tool.name,
35
+ tool
36
+ ]));
37
+ return Array.from(names).map((name)=>toolsByName.get(name)).filter((tool)=>void 0 !== tool);
38
+ }
39
+ function isTextContentBlock(block) {
40
+ return "text" === block.type;
41
+ }
42
+ function isThinkingContentBlock(block) {
43
+ return "thinking" === block.type;
44
+ }
45
+ function isToolCallBlock(block) {
46
+ return "toolCall" === block.type;
47
+ }
48
+ function isImageContentBlock(block) {
49
+ return "image" === block.type;
50
+ }
51
+ function isEncryptedReasoningDetail(detail) {
52
+ if ("object" != typeof detail || null === detail) return false;
53
+ const candidate = detail;
54
+ return "reasoning.encrypted" === candidate.type && "string" == typeof candidate.id && candidate.id.length > 0 && "string" == typeof candidate.data && candidate.data.length > 0;
55
+ }
56
+ function resolveCacheRetention(cacheRetention, env) {
57
+ if (cacheRetention) return cacheRetention;
58
+ if ("long" === getProviderEnvValue("PI_CACHE_RETENTION", env)) return "long";
59
+ return "short";
60
+ }
61
+ const openai_completions_stream = (model, context, options)=>{
62
+ const stream = new AssistantMessageEventStream();
63
+ (async ()=>{
64
+ const output = {
65
+ role: "assistant",
66
+ content: [],
67
+ api: model.api,
68
+ provider: model.provider,
69
+ model: model.id,
70
+ usage: {
71
+ input: 0,
72
+ output: 0,
73
+ cacheRead: 0,
74
+ cacheWrite: 0,
75
+ totalTokens: 0,
76
+ cost: {
77
+ input: 0,
78
+ output: 0,
79
+ cacheRead: 0,
80
+ cacheWrite: 0,
81
+ total: 0
82
+ }
83
+ },
84
+ stopReason: "pending",
85
+ timestamp: Date.now()
86
+ };
87
+ try {
88
+ const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);
89
+ const compat = getCompat(model);
90
+ const grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools);
91
+ const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
92
+ const cacheSessionId = "none" === cacheRetention ? void 0 : options?.sessionId;
93
+ const client = createClient(model, context, apiKey, options?.headers, options?.fetch, cacheSessionId, compat);
94
+ let params = buildParams(model, context, options, compat, cacheRetention, grammarToolInputProperties);
95
+ const nextParams = await options?.onPayload?.(params, model);
96
+ if (void 0 !== nextParams) params = nextParams;
97
+ const requestOptions = {
98
+ ...options?.signal ? {
99
+ signal: options.signal
100
+ } : {},
101
+ ...options?.timeoutMs !== void 0 ? {
102
+ timeout: options.timeoutMs
103
+ } : {},
104
+ maxRetries: 0
105
+ };
106
+ const { data: openaiStream, response } = await retryProviderRequest(()=>client.chat.completions.create(params, requestOptions).withResponse(), {
107
+ maxRetries: options?.maxRetries,
108
+ maxRetryDelayMs: options?.maxRetryDelayMs,
109
+ signal: options?.signal
110
+ });
111
+ await options?.onResponse?.({
112
+ status: response.status,
113
+ headers: headersToRecord(response.headers)
114
+ }, model);
115
+ stream.push({
116
+ type: "start",
117
+ partial: output
118
+ });
119
+ let textBlock = null;
120
+ let thinkingBlock = null;
121
+ let hasFinishReason = false;
122
+ const toolCallBlocksByIndex = new Map();
123
+ const toolCallBlocksById = new Map();
124
+ const pendingReasoningDetailsByToolCallId = new Map();
125
+ const blocks = output.content;
126
+ const getContentIndex = (block)=>blocks.indexOf(block);
127
+ const getCustomToolCallInput = (block)=>{
128
+ const property = block.customInput?.property;
129
+ if (void 0 === property) return "";
130
+ const value = block.arguments[property];
131
+ return "string" == typeof value ? value : "";
132
+ };
133
+ const appendCustomToolCallInput = (block, nextInput, close)=>{
134
+ const customInput = block.customInput;
135
+ if (!customInput) return;
136
+ const delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);
137
+ block.arguments = {
138
+ [customInput.property]: nextInput
139
+ };
140
+ return delta;
141
+ };
142
+ const finishBlock = (block)=>{
143
+ const contentIndex = getContentIndex(block);
144
+ if (-1 === contentIndex) return;
145
+ if ("text" === block.type) stream.push({
146
+ type: "text_end",
147
+ contentIndex,
148
+ content: block.text,
149
+ partial: output
150
+ });
151
+ else if ("thinking" === block.type) stream.push({
152
+ type: "thinking_end",
153
+ contentIndex,
154
+ content: block.thinking,
155
+ partial: output
156
+ });
157
+ else if ("toolCall" === block.type) {
158
+ if (block.customInput) {
159
+ const delta = appendCustomToolCallInput(block, getCustomToolCallInput(block), true);
160
+ if (void 0 !== delta) stream.push({
161
+ type: "toolcall_delta",
162
+ contentIndex,
163
+ delta,
164
+ partial: output
165
+ });
166
+ } else block.arguments = parseStreamingJson(block.partialArgs);
167
+ delete block.partialArgs;
168
+ delete block.customInput;
169
+ delete block.streamIndex;
170
+ stream.push({
171
+ type: "toolcall_end",
172
+ contentIndex,
173
+ toolCall: block,
174
+ partial: output
175
+ });
176
+ }
177
+ };
178
+ const ensureTextBlock = ()=>{
179
+ if (!textBlock) {
180
+ textBlock = {
181
+ type: "text",
182
+ text: ""
183
+ };
184
+ blocks.push(textBlock);
185
+ stream.push({
186
+ type: "text_start",
187
+ contentIndex: getContentIndex(textBlock),
188
+ partial: output
189
+ });
190
+ }
191
+ return textBlock;
192
+ };
193
+ const ensureThinkingBlock = (thinkingSignature)=>{
194
+ if (!thinkingBlock) {
195
+ thinkingBlock = {
196
+ type: "thinking",
197
+ thinking: "",
198
+ thinkingSignature
199
+ };
200
+ blocks.push(thinkingBlock);
201
+ stream.push({
202
+ type: "thinking_start",
203
+ contentIndex: getContentIndex(thinkingBlock),
204
+ partial: output
205
+ });
206
+ }
207
+ return thinkingBlock;
208
+ };
209
+ const applyPendingReasoningDetail = (block)=>{
210
+ if (!block.id) return;
211
+ const pendingReasoningDetail = pendingReasoningDetailsByToolCallId.get(block.id);
212
+ if (pendingReasoningDetail) {
213
+ block.thoughtSignature = pendingReasoningDetail;
214
+ pendingReasoningDetailsByToolCallId.delete(block.id);
215
+ }
216
+ };
217
+ const ensureToolCallBlock = (toolCall)=>{
218
+ const streamIndex = "number" == typeof toolCall.index ? toolCall.index : void 0;
219
+ const name = toolCall.function?.name ?? toolCall.custom?.name ?? "";
220
+ let block = void 0 !== streamIndex ? toolCallBlocksByIndex.get(streamIndex) : void 0;
221
+ if (!block && toolCall.id) block = toolCallBlocksById.get(toolCall.id);
222
+ if (!block) {
223
+ const customInputProperty = toolCall.custom && !toolCall.function ? grammarToolInputProperties.get(name) ?? "input" : void 0;
224
+ const hasCustomInput = void 0 !== customInputProperty;
225
+ block = {
226
+ type: "toolCall",
227
+ id: toolCall.id || "",
228
+ name,
229
+ arguments: hasCustomInput ? {
230
+ [customInputProperty]: ""
231
+ } : {},
232
+ partialArgs: hasCustomInput ? void 0 : "",
233
+ customInput: hasCustomInput ? {
234
+ property: customInputProperty,
235
+ jsonBuffer: {
236
+ input: "",
237
+ started: false,
238
+ closed: false
239
+ }
240
+ } : void 0,
241
+ streamIndex
242
+ };
243
+ if (void 0 !== streamIndex) toolCallBlocksByIndex.set(streamIndex, block);
244
+ if (toolCall.id) toolCallBlocksById.set(toolCall.id, block);
245
+ blocks.push(block);
246
+ stream.push({
247
+ type: "toolcall_start",
248
+ contentIndex: getContentIndex(block),
249
+ partial: output
250
+ });
251
+ }
252
+ if (void 0 !== streamIndex && void 0 === block.streamIndex) {
253
+ block.streamIndex = streamIndex;
254
+ toolCallBlocksByIndex.set(streamIndex, block);
255
+ }
256
+ if (toolCall.id) toolCallBlocksById.set(toolCall.id, block);
257
+ if (!block.name && name) block.name = name;
258
+ if (toolCall.custom && !toolCall.function && !block.customInput) {
259
+ const customInputProperty = grammarToolInputProperties.get(block.name) ?? "input";
260
+ block.arguments = {
261
+ [customInputProperty]: ""
262
+ };
263
+ block.customInput = {
264
+ property: customInputProperty,
265
+ jsonBuffer: {
266
+ input: "",
267
+ started: false,
268
+ closed: false
269
+ }
270
+ };
271
+ delete block.partialArgs;
272
+ }
273
+ applyPendingReasoningDetail(block);
274
+ return block;
275
+ };
276
+ for await (const chunk of openaiStream){
277
+ if (!chunk || "object" != typeof chunk) continue;
278
+ output.responseId ||= chunk.id;
279
+ if ("string" == typeof chunk.model && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
280
+ if (chunk.usage) output.usage = parseChunkUsage(chunk.usage, model);
281
+ const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
282
+ if (choice) {
283
+ if (!chunk.usage && choice.usage) output.usage = parseChunkUsage(choice.usage, model);
284
+ if (choice.finish_reason) {
285
+ output.rawStopReason = choice.finish_reason;
286
+ const finishReasonResult = mapStopReason(choice.finish_reason);
287
+ output.stopReason = finishReasonResult.stopReason;
288
+ if (finishReasonResult.errorMessage) output.errorMessage = finishReasonResult.errorMessage;
289
+ hasFinishReason = true;
290
+ }
291
+ if (choice.delta) {
292
+ if (null !== choice.delta.content && void 0 !== choice.delta.content && choice.delta.content.length > 0) {
293
+ const block = ensureTextBlock();
294
+ block.text += choice.delta.content;
295
+ stream.push({
296
+ type: "text_delta",
297
+ contentIndex: getContentIndex(block),
298
+ delta: choice.delta.content,
299
+ partial: output
300
+ });
301
+ }
302
+ const reasoningFields = [
303
+ "reasoning_content",
304
+ "reasoning",
305
+ "reasoning_text"
306
+ ];
307
+ const deltaFields = choice.delta;
308
+ let foundReasoningField = null;
309
+ for (const field of reasoningFields){
310
+ const value = deltaFields[field];
311
+ if ("string" == typeof value && value.length > 0) {
312
+ foundReasoningField = field;
313
+ break;
314
+ }
315
+ }
316
+ if (foundReasoningField) {
317
+ const delta = deltaFields[foundReasoningField];
318
+ if ("string" == typeof delta && delta.length > 0) {
319
+ const thinkingSignature = "opencode-go" === model.provider && "reasoning" === foundReasoningField ? "reasoning_content" : foundReasoningField;
320
+ const block = ensureThinkingBlock(thinkingSignature);
321
+ block.thinking += delta;
322
+ stream.push({
323
+ type: "thinking_delta",
324
+ contentIndex: getContentIndex(block),
325
+ delta,
326
+ partial: output
327
+ });
328
+ }
329
+ }
330
+ if (choice?.delta?.tool_calls) for (const toolCall of choice.delta.tool_calls){
331
+ const block = ensureToolCallBlock(toolCall);
332
+ if (!block.id && toolCall.id) {
333
+ block.id = toolCall.id;
334
+ toolCallBlocksById.set(toolCall.id, block);
335
+ }
336
+ const name = toolCall.function?.name ?? toolCall.custom?.name;
337
+ if (!block.name && name) block.name = name;
338
+ let delta = "";
339
+ if (toolCall.function?.arguments) {
340
+ delta = toolCall.function.arguments;
341
+ block.partialArgs = (block.partialArgs ?? "") + toolCall.function.arguments;
342
+ block.arguments = parseStreamingJson(block.partialArgs);
343
+ } else if (toolCall.custom?.input) {
344
+ const nextInput = getCustomToolCallInput(block) + toolCall.custom.input;
345
+ delta = appendCustomToolCallInput(block, nextInput, false) ?? "";
346
+ }
347
+ stream.push({
348
+ type: "toolcall_delta",
349
+ contentIndex: getContentIndex(block),
350
+ delta,
351
+ partial: output
352
+ });
353
+ }
354
+ const reasoningDetails = choice.delta.reasoning_details;
355
+ if (Array.isArray(reasoningDetails)) {
356
+ for (const detail of reasoningDetails)if (isEncryptedReasoningDetail(detail)) {
357
+ const serializedDetail = JSON.stringify(detail);
358
+ const matchingToolCall = toolCallBlocksById.get(detail.id);
359
+ if (matchingToolCall) matchingToolCall.thoughtSignature = serializedDetail;
360
+ else pendingReasoningDetailsByToolCallId.set(detail.id, serializedDetail);
361
+ }
362
+ }
363
+ }
364
+ }
365
+ }
366
+ for (const block of blocks)finishBlock(block);
367
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
368
+ if ("aborted" === output.stopReason) throw new Error("Request was aborted");
369
+ if (!hasFinishReason && !compat.supportsFinishReason) output.stopReason = output.content.some((block)=>"toolCall" === block.type) ? "toolUse" : "stop";
370
+ if ("error" === output.stopReason) throw new Error(output.errorMessage || "Provider returned an error stop reason");
371
+ if (compat.supportsFinishReason && !hasFinishReason || "pending" === output.stopReason) throw new Error("Stream ended without finish_reason");
372
+ stream.push({
373
+ type: "done",
374
+ reason: output.stopReason,
375
+ message: output
376
+ });
377
+ stream.end();
378
+ } catch (error) {
379
+ for (const block of output.content){
380
+ delete block.index;
381
+ delete block.partialArgs;
382
+ delete block.customInput;
383
+ delete block.streamIndex;
384
+ }
385
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
386
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
387
+ const rawMetadata = error?.error?.metadata?.raw;
388
+ if (rawMetadata && !output.errorMessage.includes(String(rawMetadata))) output.errorMessage += `\n${rawMetadata}`;
389
+ stream.push({
390
+ type: "error",
391
+ reason: output.stopReason,
392
+ error: output
393
+ });
394
+ stream.end();
395
+ }
396
+ })();
397
+ return stream;
398
+ };
399
+ const streamSimple = (model, context, options)=>{
400
+ getClientApiKey(model.provider, options?.apiKey, options?.headers);
401
+ const base = buildBaseOptions(model, context, options, options?.apiKey);
402
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
403
+ const reasoningEffort = "off" === clampedReasoning ? void 0 : clampedReasoning;
404
+ const toolChoice = options?.toolChoice;
405
+ return openai_completions_stream(model, context, {
406
+ ...base,
407
+ reasoningEffort,
408
+ toolChoice,
409
+ thinkingBudgets: options?.thinkingBudgets
410
+ });
411
+ };
412
+ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId, compat = getCompat(model)) {
413
+ const headers = {
414
+ ...model.headers
415
+ };
416
+ if ("github-copilot" === model.provider) {
417
+ const hasImages = hasCopilotVisionInput(context.messages);
418
+ const copilotHeaders = buildCopilotDynamicHeaders({
419
+ messages: context.messages,
420
+ hasImages
421
+ });
422
+ Object.assign(headers, copilotHeaders);
423
+ }
424
+ if (sessionId && compat.sendSessionAffinityHeaders) if ("openrouter" === compat.sessionAffinityFormat) headers["x-session-id"] = sessionId;
425
+ else {
426
+ if ("openai" === compat.sessionAffinityFormat) headers.session_id = sessionId;
427
+ headers["x-client-request-id"] = sessionId;
428
+ headers["x-session-affinity"] = sessionId;
429
+ }
430
+ if (optionsHeaders) Object.assign(headers, optionsHeaders);
431
+ return new OpenAI({
432
+ apiKey,
433
+ baseURL: model.baseUrl,
434
+ dangerouslyAllowBrowser: true,
435
+ fetch,
436
+ defaultHeaders: headers
437
+ });
438
+ }
439
+ function buildParams(model, context, options, compat = getCompat(model), cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env), grammarToolInputProperties = createGrammarToolInputProperties(context.tools, compat.supportsOpenAIGrammarTools)) {
440
+ const messages = convertMessages(model, context, compat, {
441
+ grammarToolInputProperties
442
+ });
443
+ const cacheControl = getCompatCacheControl(compat, cacheRetention);
444
+ const params = {
445
+ model: model.id,
446
+ messages,
447
+ stream: true,
448
+ prompt_cache_key: model.baseUrl.includes("api.openai.com") && "none" !== cacheRetention || "long" === cacheRetention && compat.supportsLongCacheRetention ? clampOpenAIPromptCacheKey(options?.sessionId) : void 0,
449
+ prompt_cache_retention: "long" === cacheRetention && compat.supportsLongCacheRetention ? "24h" : void 0
450
+ };
451
+ if (false !== compat.supportsUsageInStreaming) params.stream_options = {
452
+ include_usage: true
453
+ };
454
+ if (compat.supportsStore) params.store = false;
455
+ if (options?.maxTokens) if ("max_tokens" === compat.maxTokensField) params.max_tokens = options.maxTokens;
456
+ else params.max_completion_tokens = options.maxTokens;
457
+ if (options?.temperature !== void 0) params.temperature = options.temperature;
458
+ const deferredToolNames = "kimi" === compat.deferredToolsMode ? getDeferredToolNames(context.messages) : new Set();
459
+ const activeTools = context.tools?.filter((tool)=>!deferredToolNames.has(tool.name));
460
+ if (activeTools && activeTools.length > 0) {
461
+ params.tools = convertTools(activeTools, compat);
462
+ if (compat.zaiToolStream) params.tool_stream = true;
463
+ } else if (hasToolHistory(context.messages)) params.tools = [];
464
+ if (cacheControl) applyAnthropicCacheControl(messages, params.tools, cacheControl);
465
+ if (options?.toolChoice) params.tool_choice = options.toolChoice;
466
+ if ("zai" === compat.thinkingFormat && model.reasoning) {
467
+ const zaiParams = params;
468
+ zaiParams.thinking = options?.reasoningEffort ? {
469
+ type: "enabled",
470
+ clear_thinking: false
471
+ } : {
472
+ type: "disabled"
473
+ };
474
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
475
+ const mappedEffort = model.thinkingLevelMap?.[options.reasoningEffort];
476
+ const effort = void 0 === mappedEffort ? options.reasoningEffort : mappedEffort;
477
+ if ("string" == typeof effort) zaiParams.reasoning_effort = effort;
478
+ }
479
+ } else if ("qwen" === compat.thinkingFormat && model.reasoning) {
480
+ params.enable_thinking = !!options?.reasoningEffort;
481
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) {
482
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
483
+ if ("string" == typeof effort) params.reasoning_effort = effort;
484
+ }
485
+ } else if ("qwen-chat-template" === compat.thinkingFormat && model.reasoning) params.chat_template_kwargs = {
486
+ enable_thinking: !!options?.reasoningEffort,
487
+ preserve_thinking: true
488
+ };
489
+ else if ("chat-template" === compat.thinkingFormat && model.reasoning) {
490
+ const chatTemplateKwargs = buildChatTemplateValues(model, options, compat.chatTemplateKwargs);
491
+ if (chatTemplateKwargs) params.chat_template_kwargs = chatTemplateKwargs;
492
+ } else if ("baseten" === compat.thinkingFormat && model.reasoning) {
493
+ const basetenParams = params;
494
+ const chatTemplateArgs = buildChatTemplateValues(model, options, compat.chatTemplateArgs);
495
+ if (chatTemplateArgs) basetenParams.chat_template_args = chatTemplateArgs;
496
+ if (compat.supportsReasoningEffort) {
497
+ const requestedEffort = options?.reasoningEffort;
498
+ const mappedEffort = requestedEffort ? model.thinkingLevelMap?.[requestedEffort] : model.thinkingLevelMap?.off;
499
+ const effort = void 0 === mappedEffort ? requestedEffort : mappedEffort;
500
+ if ("string" == typeof effort) basetenParams.reasoning_effort = effort;
501
+ }
502
+ } else if ("deepseek" === compat.thinkingFormat && model.reasoning) {
503
+ if (options?.reasoningEffort) params.thinking = {
504
+ type: "enabled"
505
+ };
506
+ else if (model.thinkingLevelMap?.off !== null) params.thinking = {
507
+ type: "disabled"
508
+ };
509
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
510
+ } else if ("openrouter" === compat.thinkingFormat && model.reasoning) {
511
+ const openRouterParams = params;
512
+ if (options?.reasoningEffort) openRouterParams.reasoning = {
513
+ effort: model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort
514
+ };
515
+ else if (model.thinkingLevelMap?.off !== null) openRouterParams.reasoning = {
516
+ effort: model.thinkingLevelMap?.off ?? "none"
517
+ };
518
+ } else if ("ant-ling" === compat.thinkingFormat && model.reasoning && options?.reasoningEffort) {
519
+ const effort = model.thinkingLevelMap?.[options.reasoningEffort];
520
+ if ("string" == typeof effort) params.reasoning = {
521
+ effort
522
+ };
523
+ } else if ("together" === compat.thinkingFormat && model.reasoning) {
524
+ const togetherParams = params;
525
+ togetherParams.reasoning = {
526
+ enabled: !!options?.reasoningEffort
527
+ };
528
+ if (options?.reasoningEffort && compat.supportsReasoningEffort) togetherParams.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
529
+ } else if ("string-thinking" === compat.thinkingFormat && model.reasoning) {
530
+ const stringThinkingParams = params;
531
+ if (options?.reasoningEffort) stringThinkingParams.thinking = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
532
+ else if (model.thinkingLevelMap?.off !== null) stringThinkingParams.thinking = model.thinkingLevelMap?.off ?? "none";
533
+ } else if (options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) params.reasoning_effort = model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
534
+ else if (!options?.reasoningEffort && model.reasoning && compat.supportsReasoningEffort) {
535
+ const offValue = model.thinkingLevelMap?.off;
536
+ if ("string" == typeof offValue) params.reasoning_effort = offValue;
537
+ }
538
+ if (compat.supportsThinkingTokenBudget && options?.reasoningEffort && model.reasoning) {
539
+ const level = clampReasoning(options.reasoningEffort);
540
+ const budgets = {
541
+ minimal: 1024,
542
+ low: 2048,
543
+ medium: 8192,
544
+ high: 16384,
545
+ ...options.thinkingBudgets
546
+ };
547
+ const ceiling = params.max_tokens ?? params.max_completion_tokens ?? model.maxTokens;
548
+ const budget = Math.min(budgets[level], Math.max(0, ceiling - 1024));
549
+ if (budget > 0) params.thinking_token_budget = budget;
550
+ }
551
+ if (model.compat?.openRouterRouting) params.provider = model.compat.openRouterRouting;
552
+ if (model.compat?.vercelGatewayRouting) {
553
+ const routing = model.compat.vercelGatewayRouting;
554
+ if (routing.only || routing.order) {
555
+ const gatewayOptions = {};
556
+ if (routing.only) gatewayOptions.only = routing.only;
557
+ if (routing.order) gatewayOptions.order = routing.order;
558
+ params.providerOptions = {
559
+ gateway: gatewayOptions
560
+ };
561
+ }
562
+ }
563
+ if (options?.samplingParams) Object.assign(params, options.samplingParams);
564
+ return params;
565
+ }
566
+ function buildChatTemplateValues(model, options, values) {
567
+ const resolvedValues = {};
568
+ for (const [key, value] of Object.entries(values)){
569
+ const resolved = resolveChatTemplateKwargValue(model, options, value);
570
+ if (void 0 !== resolved) resolvedValues[key] = resolved;
571
+ }
572
+ return Object.keys(resolvedValues).length > 0 ? resolvedValues : void 0;
573
+ }
574
+ function resolveChatTemplateKwargValue(model, options, value) {
575
+ if ("object" != typeof value || null === value) return value;
576
+ const reasoningEffort = options?.reasoningEffort;
577
+ if (!reasoningEffort && value.omitWhenOff) return;
578
+ if ("thinking.enabled" === value.$var) return !!reasoningEffort;
579
+ const mappedValue = reasoningEffort ? model.thinkingLevelMap?.[reasoningEffort] : model.thinkingLevelMap?.off;
580
+ return void 0 === mappedValue ? reasoningEffort : "string" == typeof mappedValue ? mappedValue : void 0;
581
+ }
582
+ function getCompatCacheControl(compat, cacheRetention) {
583
+ if ("anthropic" !== compat.cacheControlFormat || "none" === cacheRetention) return;
584
+ const ttl = "long" === cacheRetention && compat.supportsLongCacheRetention ? "1h" : void 0;
585
+ return {
586
+ type: "ephemeral",
587
+ ...ttl ? {
588
+ ttl
589
+ } : {}
590
+ };
591
+ }
592
+ function applyAnthropicCacheControl(messages, tools, cacheControl) {
593
+ addCacheControlToSystemPrompt(messages, cacheControl);
594
+ addCacheControlToLastTool(tools, cacheControl);
595
+ addCacheControlToLastConversationMessage(messages, cacheControl);
596
+ }
597
+ function addCacheControlToSystemPrompt(messages, cacheControl) {
598
+ for (const message of messages)if ("system" === message.role || "developer" === message.role) return void addCacheControlToInstructionMessage(message, cacheControl);
599
+ }
600
+ function addCacheControlToLastConversationMessage(messages, cacheControl) {
601
+ for(let i = messages.length - 1; i >= 0; i--){
602
+ const message = messages[i];
603
+ if ("user" === message.role || "assistant" === message.role || "tool" === message.role) {
604
+ if (addCacheControlToMessage(message, cacheControl)) return;
605
+ }
606
+ }
607
+ }
608
+ function addCacheControlToLastTool(tools, cacheControl) {
609
+ if (!tools || 0 === tools.length) return;
610
+ const lastTool = tools[tools.length - 1];
611
+ lastTool.cache_control = cacheControl;
612
+ }
613
+ function addCacheControlToInstructionMessage(message, cacheControl) {
614
+ return addCacheControlToTextContent(message, cacheControl);
615
+ }
616
+ function addCacheControlToMessage(message, cacheControl) {
617
+ if ("user" === message.role || "assistant" === message.role || "tool" === message.role) return addCacheControlToTextContent(message, cacheControl);
618
+ return false;
619
+ }
620
+ function addCacheControlToTextContent(message, cacheControl) {
621
+ const content = message.content;
622
+ if ("string" == typeof content) {
623
+ if (0 === content.length) return false;
624
+ message.content = [
625
+ {
626
+ type: "text",
627
+ text: content,
628
+ cache_control: cacheControl
629
+ }
630
+ ];
631
+ return true;
632
+ }
633
+ if (!Array.isArray(content)) return false;
634
+ for(let i = content.length - 1; i >= 0; i--){
635
+ const part = content[i];
636
+ if (part?.type === "text") {
637
+ const textPart = part;
638
+ textPart.cache_control = cacheControl;
639
+ return true;
640
+ }
641
+ }
642
+ return false;
643
+ }
644
+ function convertMessages(model, context, compat, options) {
645
+ const params = [];
646
+ const normalizeToolCallId = (id)=>{
647
+ if (id.includes("|")) {
648
+ const separatorIndex = id.indexOf("|");
649
+ const callId = id.slice(0, separatorIndex).replace(/[^a-zA-Z0-9_-]/g, "_");
650
+ const itemId = id.slice(separatorIndex + 1).replace(/[^a-zA-Z0-9_-]/g, "_");
651
+ const combinedId = itemId.length > 0 ? `${callId}_${itemId}` : callId;
652
+ if (combinedId.length <= 40) return combinedId;
653
+ const hash = shortHash(id).slice(0, 8);
654
+ const prefix = callId.slice(0, Math.max(1, 40 - hash.length - 1));
655
+ return `${prefix}_${hash}`;
656
+ }
657
+ if ("openai" === model.provider) return id.length > 40 ? id.slice(0, 40) : id;
658
+ return id;
659
+ };
660
+ const transformedMessages = transformMessages(context.messages, model, (id)=>normalizeToolCallId(id));
661
+ if (context.systemPrompt) {
662
+ const useDeveloperRole = model.reasoning && compat.supportsDeveloperRole;
663
+ const role = useDeveloperRole ? "developer" : "system";
664
+ params.push({
665
+ role: role,
666
+ content: sanitizeSurrogates(context.systemPrompt)
667
+ });
668
+ }
669
+ let lastRole = null;
670
+ for(let i = 0; i < transformedMessages.length; i++){
671
+ const msg = transformedMessages[i];
672
+ if (compat.requiresAssistantAfterToolResult && "toolResult" === lastRole && "user" === msg.role) params.push({
673
+ role: "assistant",
674
+ content: "I have processed the tool results."
675
+ });
676
+ if ("user" === msg.role) if ("string" == typeof msg.content) params.push({
677
+ role: "user",
678
+ content: sanitizeSurrogates(msg.content)
679
+ });
680
+ else {
681
+ const content = msg.content.map((item)=>{
682
+ if ("text" === item.type) return {
683
+ type: "text",
684
+ text: sanitizeSurrogates(item.text)
685
+ };
686
+ else return {
687
+ type: "image_url",
688
+ image_url: {
689
+ url: `data:${item.mimeType};base64,${item.data}`
690
+ }
691
+ };
692
+ });
693
+ if (0 === content.length) continue;
694
+ params.push({
695
+ role: "user",
696
+ content
697
+ });
698
+ }
699
+ else if ("assistant" === msg.role) {
700
+ const assistantMsg = {
701
+ role: "assistant",
702
+ content: compat.requiresAssistantAfterToolResult ? "" : null
703
+ };
704
+ const assistantTextParts = msg.content.filter(isTextContentBlock).filter((block)=>block.text.trim().length > 0).map((block)=>({
705
+ type: "text",
706
+ text: sanitizeSurrogates(block.text)
707
+ }));
708
+ const assistantText = assistantTextParts.map((part)=>part.text).join("");
709
+ const nonEmptyThinkingBlocks = msg.content.filter(isThinkingContentBlock).filter((block)=>block.thinking.trim().length > 0);
710
+ if (nonEmptyThinkingBlocks.length > 0) if (compat.requiresThinkingAsText) {
711
+ const thinkingText = nonEmptyThinkingBlocks.map((block)=>sanitizeSurrogates(block.thinking)).join("\n\n");
712
+ assistantMsg.content = [
713
+ {
714
+ type: "text",
715
+ text: thinkingText
716
+ },
717
+ ...assistantTextParts
718
+ ];
719
+ } else {
720
+ if (assistantText.length > 0) assistantMsg.content = assistantText;
721
+ let signature = nonEmptyThinkingBlocks[0].thinkingSignature;
722
+ if ("opencode-go" === model.provider && "reasoning" === signature) signature = "reasoning_content";
723
+ if (signature && signature.length > 0) assistantMsg[signature] = nonEmptyThinkingBlocks.map((block)=>block.thinking).join("\n");
724
+ }
725
+ else if (assistantText.length > 0) assistantMsg.content = assistantText;
726
+ const toolCalls = msg.content.filter(isToolCallBlock);
727
+ if (toolCalls.length > 0) {
728
+ assistantMsg.tool_calls = toolCalls.map((tc)=>{
729
+ const customInputProperty = options?.grammarToolInputProperties?.get(tc.name);
730
+ if (void 0 !== customInputProperty) return {
731
+ id: tc.id,
732
+ type: "custom",
733
+ custom: {
734
+ name: tc.name,
735
+ input: sanitizeSurrogates(getGrammarToolInput(tc.name, tc.arguments, customInputProperty))
736
+ }
737
+ };
738
+ return {
739
+ id: tc.id,
740
+ type: "function",
741
+ function: {
742
+ name: tc.name,
743
+ arguments: JSON.stringify(tc.arguments)
744
+ }
745
+ };
746
+ });
747
+ const reasoningDetails = toolCalls.filter((tc)=>tc.thoughtSignature).map((tc)=>{
748
+ try {
749
+ return JSON.parse(tc.thoughtSignature);
750
+ } catch {
751
+ return null;
752
+ }
753
+ }).filter(Boolean);
754
+ if (reasoningDetails.length > 0) assistantMsg.reasoning_details = reasoningDetails;
755
+ }
756
+ if (compat.requiresReasoningContentOnAssistantMessages && model.reasoning && void 0 === assistantMsg.reasoning_content) assistantMsg.reasoning_content = "";
757
+ const content = assistantMsg.content;
758
+ const hasContent = null != content && ("string" == typeof content ? content.length > 0 : content.length > 0);
759
+ if (!hasContent && !assistantMsg.tool_calls) continue;
760
+ params.push(assistantMsg);
761
+ } else if ("toolResult" === msg.role) {
762
+ const imageBlocks = [];
763
+ const deferredToolNames = new Set();
764
+ let j = i;
765
+ for(; j < transformedMessages.length && "toolResult" === transformedMessages[j].role; j++){
766
+ const toolMsg = transformedMessages[j];
767
+ const textResult = toolMsg.content.filter(isTextContentBlock).map((block)=>block.text).join("\n");
768
+ const hasImages = toolMsg.content.some((c)=>"image" === c.type);
769
+ const hasText = textResult.length > 0;
770
+ const toolResultText = hasText ? textResult : hasImages ? "(see attached image)" : "(no tool output)";
771
+ const toolResultMsg = {
772
+ role: "tool",
773
+ content: sanitizeSurrogates(toolResultText),
774
+ tool_call_id: toolMsg.toolCallId
775
+ };
776
+ if (compat.requiresToolResultName && toolMsg.toolName) toolResultMsg.name = toolMsg.toolName;
777
+ params.push(toolResultMsg);
778
+ if ("kimi" === compat.deferredToolsMode) for (const name of toolMsg.addedToolNames ?? [])deferredToolNames.add(name);
779
+ if (hasImages && model.input.includes("image")) {
780
+ for (const block of toolMsg.content)if (isImageContentBlock(block)) imageBlocks.push({
781
+ type: "image_url",
782
+ image_url: {
783
+ url: `data:${block.mimeType};base64,${block.data}`
784
+ }
785
+ });
786
+ }
787
+ }
788
+ i = j - 1;
789
+ if (imageBlocks.length > 0) {
790
+ if (compat.requiresAssistantAfterToolResult) params.push({
791
+ role: "assistant",
792
+ content: "I have processed the tool results."
793
+ });
794
+ params.push({
795
+ role: "user",
796
+ content: [
797
+ {
798
+ type: "text",
799
+ text: "Attached image(s) from tool result:"
800
+ },
801
+ ...imageBlocks
802
+ ]
803
+ });
804
+ lastRole = "user";
805
+ } else lastRole = "toolResult";
806
+ if (deferredToolNames.size > 0) {
807
+ const deferredTools = getToolsByName(context.tools, deferredToolNames);
808
+ if (deferredTools.length > 0) {
809
+ const kimiToolMessage = {
810
+ role: "system",
811
+ tools: convertTools(deferredTools, compat)
812
+ };
813
+ params.push(kimiToolMessage);
814
+ }
815
+ }
816
+ continue;
817
+ }
818
+ lastRole = msg.role;
819
+ }
820
+ return params;
821
+ }
822
+ function convertTools(tools, compat) {
823
+ return tools.map((tool)=>{
824
+ const grammar = resolveGrammarConstrainedSampling(tool, compat.supportsOpenAIGrammarTools);
825
+ if (grammar) return {
826
+ type: "custom",
827
+ custom: {
828
+ name: tool.name,
829
+ description: tool.description,
830
+ format: {
831
+ type: "grammar",
832
+ grammar: {
833
+ syntax: grammar.format,
834
+ definition: grammar.definition
835
+ }
836
+ }
837
+ }
838
+ };
839
+ const strict = resolveJsonSchemaStrictSampling(tool, false !== compat.supportsStrictMode);
840
+ return {
841
+ type: "function",
842
+ function: {
843
+ name: tool.name,
844
+ description: tool.description,
845
+ parameters: tool.parameters,
846
+ ...false !== compat.supportsStrictMode && {
847
+ strict: strict ?? false
848
+ }
849
+ }
850
+ };
851
+ });
852
+ }
853
+ function parseChunkUsage(rawUsage, model) {
854
+ const promptTokens = rawUsage.prompt_tokens || 0;
855
+ const cacheReadTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? 0;
856
+ const cacheWriteTokens = rawUsage.prompt_tokens_details?.cache_write_tokens || 0;
857
+ const input = Math.max(0, promptTokens - cacheReadTokens - cacheWriteTokens);
858
+ const outputTokens = rawUsage.completion_tokens || 0;
859
+ const usage = {
860
+ input,
861
+ output: outputTokens,
862
+ cacheRead: cacheReadTokens,
863
+ cacheWrite: cacheWriteTokens,
864
+ reasoning: rawUsage.completion_tokens_details?.reasoning_tokens || 0,
865
+ totalTokens: input + outputTokens + cacheReadTokens + cacheWriteTokens,
866
+ cost: {
867
+ input: 0,
868
+ output: 0,
869
+ cacheRead: 0,
870
+ cacheWrite: 0,
871
+ total: 0
872
+ }
873
+ };
874
+ calculateCost(model, usage);
875
+ return usage;
876
+ }
877
+ function mapStopReason(reason) {
878
+ if (null === reason) return {
879
+ stopReason: "stop"
880
+ };
881
+ switch(reason){
882
+ case "stop":
883
+ case "end":
884
+ return {
885
+ stopReason: "stop"
886
+ };
887
+ case "length":
888
+ return {
889
+ stopReason: "length"
890
+ };
891
+ case "function_call":
892
+ case "tool_calls":
893
+ return {
894
+ stopReason: "toolUse"
895
+ };
896
+ case "content_filter":
897
+ return {
898
+ stopReason: "error",
899
+ errorMessage: "Provider finish_reason: content_filter"
900
+ };
901
+ case "network_error":
902
+ return {
903
+ stopReason: "error",
904
+ errorMessage: "Provider finish_reason: network_error"
905
+ };
906
+ default:
907
+ return {
908
+ stopReason: "error",
909
+ errorMessage: `Provider finish_reason: ${reason}`
910
+ };
911
+ }
912
+ }
913
+ function detectCompat(model) {
914
+ const provider = model.provider;
915
+ const baseUrl = model.baseUrl;
916
+ const isZai = "zai" === provider || "zai-coding-cn" === provider || baseUrl.includes("api.z.ai") || baseUrl.includes("open.bigmodel.cn");
917
+ const isTogether = "together" === provider || baseUrl.includes("api.together.ai") || baseUrl.includes("api.together.xyz");
918
+ const isMoonshot = "moonshotai" === provider || "moonshotai-cn" === provider || baseUrl.includes("api.moonshot.");
919
+ const isOpenRouter = "openrouter" === provider || baseUrl.includes("openrouter.ai");
920
+ const isCloudflareWorkersAI = "cloudflare-workers-ai" === provider || baseUrl.includes("api.cloudflare.com");
921
+ const isCloudflareAiGateway = "cloudflare-ai-gateway" === provider || baseUrl.includes("gateway.ai.cloudflare.com");
922
+ const isNvidia = "nvidia" === provider || baseUrl.includes("integrate.api.nvidia.com");
923
+ const isAntLing = "ant-ling" === provider || baseUrl.includes("api.ant-ling.com");
924
+ const isNonStandard = isNvidia || "cerebras" === provider || baseUrl.includes("cerebras.ai") || "xai" === provider || baseUrl.includes("api.x.ai") || isTogether || baseUrl.includes("chutes.ai") || baseUrl.includes("deepseek.com") || isZai || isMoonshot || "opencode" === provider || baseUrl.includes("opencode.ai") || isCloudflareWorkersAI || isCloudflareAiGateway || isAntLing;
925
+ const useMaxTokens = baseUrl.includes("chutes.ai") || isMoonshot || isCloudflareAiGateway || isTogether || isNvidia || isAntLing || isZai;
926
+ const isGrok = "xai" === provider || baseUrl.includes("api.x.ai");
927
+ const isDeepSeek = "deepseek" === provider || baseUrl.includes("deepseek.com");
928
+ const isOpenRouterDeveloperRoleModel = isOpenRouter && (model.id.startsWith("anthropic/") || model.id.startsWith("openai/"));
929
+ const cacheControlFormat = "openrouter" === provider && model.id.startsWith("anthropic/") ? "anthropic" : void 0;
930
+ return {
931
+ supportsStore: !isNonStandard,
932
+ supportsDeveloperRole: isOpenRouterDeveloperRoleModel || !isNonStandard && !isOpenRouter,
933
+ supportsReasoningEffort: !isGrok && !isZai && !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia && !isAntLing,
934
+ supportsUsageInStreaming: true,
935
+ supportsFinishReason: true,
936
+ maxTokensField: useMaxTokens ? "max_tokens" : "max_completion_tokens",
937
+ requiresToolResultName: false,
938
+ requiresAssistantAfterToolResult: false,
939
+ requiresThinkingAsText: false,
940
+ requiresReasoningContentOnAssistantMessages: isDeepSeek,
941
+ thinkingFormat: isDeepSeek ? "deepseek" : isZai ? "zai" : isTogether ? "together" : isAntLing ? "ant-ling" : isOpenRouter ? "openrouter" : "openai",
942
+ openRouterRouting: {},
943
+ vercelGatewayRouting: {},
944
+ chatTemplateKwargs: {},
945
+ chatTemplateArgs: {},
946
+ zaiToolStream: false,
947
+ supportsThinkingTokenBudget: false,
948
+ supportsStrictMode: !isMoonshot && !isTogether && !isCloudflareAiGateway && !isNvidia,
949
+ supportsOpenAIGrammarTools: false,
950
+ cacheControlFormat,
951
+ sendSessionAffinityHeaders: false,
952
+ deferredToolsMode: void 0,
953
+ sessionAffinityFormat: isOpenRouter ? "openrouter" : "openai",
954
+ supportsLongCacheRetention: !(isTogether || isCloudflareWorkersAI || isCloudflareAiGateway || isNvidia || isAntLing)
955
+ };
956
+ }
957
+ function getCompat(model) {
958
+ const detected = detectCompat(model);
959
+ if (!model.compat) return detected;
960
+ return {
961
+ supportsStore: model.compat.supportsStore ?? detected.supportsStore,
962
+ supportsDeveloperRole: model.compat.supportsDeveloperRole ?? detected.supportsDeveloperRole,
963
+ supportsReasoningEffort: model.compat.supportsReasoningEffort ?? detected.supportsReasoningEffort,
964
+ supportsUsageInStreaming: model.compat.supportsUsageInStreaming ?? detected.supportsUsageInStreaming,
965
+ supportsFinishReason: model.compat.supportsFinishReason ?? detected.supportsFinishReason,
966
+ maxTokensField: model.compat.maxTokensField ?? detected.maxTokensField,
967
+ requiresToolResultName: model.compat.requiresToolResultName ?? detected.requiresToolResultName,
968
+ requiresAssistantAfterToolResult: model.compat.requiresAssistantAfterToolResult ?? detected.requiresAssistantAfterToolResult,
969
+ requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,
970
+ requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ?? detected.requiresReasoningContentOnAssistantMessages,
971
+ thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,
972
+ openRouterRouting: model.compat.openRouterRouting ?? {},
973
+ vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,
974
+ chatTemplateKwargs: model.compat.chatTemplateKwargs ?? detected.chatTemplateKwargs,
975
+ chatTemplateArgs: model.compat.chatTemplateArgs ?? detected.chatTemplateArgs,
976
+ zaiToolStream: model.compat.zaiToolStream ?? detected.zaiToolStream,
977
+ supportsThinkingTokenBudget: model.compat.supportsThinkingTokenBudget ?? detected.supportsThinkingTokenBudget,
978
+ supportsStrictMode: model.compat.supportsStrictMode ?? detected.supportsStrictMode,
979
+ supportsOpenAIGrammarTools: model.compat.supportsOpenAIGrammarTools ?? detected.supportsOpenAIGrammarTools,
980
+ cacheControlFormat: model.compat.cacheControlFormat ?? detected.cacheControlFormat,
981
+ sendSessionAffinityHeaders: model.compat.sendSessionAffinityHeaders ?? detected.sendSessionAffinityHeaders,
982
+ deferredToolsMode: model.compat.deferredToolsMode ?? detected.deferredToolsMode,
983
+ sessionAffinityFormat: model.compat.sessionAffinityFormat ?? detected.sessionAffinityFormat,
984
+ supportsLongCacheRetention: model.compat.supportsLongCacheRetention ?? detected.supportsLongCacheRetention
985
+ };
986
+ }
987
+ export { convertMessages, openai_completions_stream as stream, streamSimple };