@ai-sdk/moonshotai 3.0.38 → 3.0.41

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.
package/dist/index.js CHANGED
@@ -15,10 +15,11 @@ import {
15
15
  createJsonErrorResponseHandler,
16
16
  createJsonResponseHandler,
17
17
  createLanguageModelResponseMetadata as getResponseMetadata,
18
+ createProviderStreamError,
18
19
  generateId,
19
20
  isCustomReasoning,
20
21
  mapReasoningToProviderEffort,
21
- parseProviderOptions,
22
+ parseProviderOptions as parseProviderOptions2,
22
23
  postJsonToApi,
23
24
  serializeModelOptions,
24
25
  StreamingToolCallTracker,
@@ -28,28 +29,391 @@ import {
28
29
 
29
30
  // src/convert-to-moonshotai-chat-messages.ts
30
31
  import {
31
- UnsupportedFunctionalityError
32
+ InvalidPromptError,
33
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError3
32
34
  } from "@ai-sdk/provider";
33
35
  import {
34
36
  convertBase64ToUint8Array,
35
37
  convertToBase64,
36
38
  getTopLevelMediaType,
39
+ parseProviderOptions,
40
+ resolveProviderReference,
37
41
  resolveFullMediaType
38
42
  } from "@ai-sdk/provider-utils";
39
- function convertToMoonshotAIChatMessages(prompt) {
40
- var _a;
43
+
44
+ // src/moonshotai-chat-options.ts
45
+ import { z } from "zod/v4";
46
+ function isMoonshotAIKimiModel(modelId) {
47
+ return getMoonshotAIModelFamily(modelId).startsWith("kimi-");
48
+ }
49
+ function getMoonshotAIModelFamily(modelId) {
50
+ if (modelId === "kimi-k2.5") return "kimi-k2.5";
51
+ if (modelId === "kimi-k2.6") return "kimi-k2.6";
52
+ if (modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
53
+ return "kimi-k2.7";
54
+ }
55
+ if (modelId === "kimi-k3") return "kimi-k3";
56
+ if (modelId.startsWith("moonshot-v1-")) return "moonshot-v1";
57
+ return "unknown";
58
+ }
59
+ var moonshotaiLanguageModelOptions = z.object({
60
+ /**
61
+ * Whether to use strict JSON schema validation for structured outputs.
62
+ *
63
+ * @default true
64
+ */
65
+ strictJsonSchema: z.boolean().optional(),
66
+ /**
67
+ * Whether to return log probabilities for generated tokens.
68
+ */
69
+ logprobs: z.boolean().optional(),
70
+ /**
71
+ * Number of most likely tokens to return at each token position.
72
+ *
73
+ * Setting this option automatically enables `logprobs`.
74
+ */
75
+ topLogprobs: z.number().int().min(0).max(20).optional(),
76
+ /**
77
+ * Reasoning effort for Kimi K3. Supports `low`, `high`, and `max`;
78
+ * defaults to `max`.
79
+ */
80
+ reasoningEffort: z.enum(["low", "high", "max"]).optional(),
81
+ /**
82
+ * Static predicted content that can accelerate responses when much of the
83
+ * output is known ahead of time.
84
+ */
85
+ prediction: z.object({
86
+ type: z.literal("content"),
87
+ content: z.union([
88
+ z.string(),
89
+ z.array(z.object({ type: z.literal("text"), text: z.string() }))
90
+ ])
91
+ }).optional(),
92
+ /**
93
+ * Thinking configuration for Kimi K2.x models. Kimi K2.5 and K2.6 support
94
+ * enabling or disabling thinking. Kimi K2.7 Code always has thinking
95
+ * enabled.
96
+ */
97
+ thinking: z.object({
98
+ type: z.enum(["enabled", "disabled"]).optional(),
99
+ /**
100
+ * @deprecated Moonshot Chat Completions does not support thinking
101
+ * budgets. Accepted for backwards compatibility, then omitted with a
102
+ * warning.
103
+ */
104
+ budgetTokens: z.number().int().min(1024).optional()
105
+ }).optional(),
106
+ /**
107
+ * Controls preserved reasoning behavior in multi-turn conversations.
108
+ * `disabled` and `interleaved` are compatibility values that leave the
109
+ * request unchanged. `preserved` maps to `thinking.keep: 'all'` for Kimi
110
+ * K2.6. Kimi K2.7 and K3 preserve reasoning by default.
111
+ */
112
+ reasoningHistory: z.enum(["disabled", "interleaved", "preserved"]).optional(),
113
+ /**
114
+ * Used to cache responses for similar requests to optimize cache hit rates.
115
+ * Typically a session or task id.
116
+ */
117
+ promptCacheKey: z.string().optional(),
118
+ /**
119
+ * A stable identifier used to help Moonshot detect users violating usage
120
+ * policies. Recommended to hash the username or email address.
121
+ */
122
+ safetyIdentifier: z.string().optional()
123
+ });
124
+ var moonshotaiMessageProviderOptions = z.object({
125
+ /**
126
+ * The name of the participant represented by the message.
127
+ *
128
+ * Supported on system, user, and assistant messages.
129
+ */
130
+ name: z.string().optional()
131
+ });
132
+ var moonshotaiAssistantMessageProviderOptions = moonshotaiMessageProviderOptions.extend({
133
+ /**
134
+ * Whether the assistant message content is a partial response that Moonshot
135
+ * should continue. Only supported on the final assistant message and cannot
136
+ * be combined with JSON object response format.
137
+ */
138
+ partial: z.literal(true).optional()
139
+ });
140
+ var moonshotaiDynamicToolSchema = z.object({
141
+ type: z.literal("function"),
142
+ name: z.string(),
143
+ description: z.string().optional(),
144
+ inputSchema: z.record(z.string(), z.unknown()),
145
+ strict: z.boolean().optional()
146
+ });
147
+ var moonshotaiAllMessageProviderOptions = moonshotaiAssistantMessageProviderOptions.extend({
148
+ /** Function tools to load at this point in a Kimi K3 conversation. */
149
+ tools: z.array(moonshotaiDynamicToolSchema).optional()
150
+ });
151
+
152
+ // src/moonshotai-prepare-tools.ts
153
+ import {
154
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
155
+ } from "@ai-sdk/provider";
156
+
157
+ // src/normalize-json-schema-for-mfjs.ts
158
+ import { UnsupportedFunctionalityError } from "@ai-sdk/provider";
159
+ import { isRecord } from "@ai-sdk/provider-utils";
160
+ var SCHEMA_ARRAY_KEYS = ["allOf", "anyOf", "oneOf", "prefixItems"];
161
+ var SCHEMA_MAP_KEYS = [
162
+ "properties",
163
+ "patternProperties",
164
+ "$defs",
165
+ "dependentSchemas"
166
+ ];
167
+ var SCHEMA_SINGLE_KEYS = [
168
+ "additionalProperties",
169
+ "propertyNames",
170
+ "items",
171
+ "contains",
172
+ "not",
173
+ "if",
174
+ "then",
175
+ "else"
176
+ ];
177
+ function normalizeJsonSchemaForMFJS(schema) {
178
+ return normalizeDefinition(schema, true);
179
+ }
180
+ function normalizeDefinition(definition, isRoot) {
181
+ if (typeof definition === "boolean" || !isRecord(definition)) {
182
+ if (isRoot) {
183
+ throw new UnsupportedFunctionalityError({
184
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
185
+ });
186
+ }
187
+ return definition;
188
+ }
189
+ if (isRoot && definition.type !== "object") {
190
+ throw new UnsupportedFunctionalityError({
191
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
192
+ });
193
+ }
194
+ const result = { ...definition };
195
+ if (Array.isArray(result.items)) {
196
+ const tuple = result.items;
197
+ result.prefixItems = [
198
+ ...Array.isArray(result.prefixItems) ? result.prefixItems : [],
199
+ ...tuple.map((item) => normalizeDefinition(item, false))
200
+ ];
201
+ delete result.items;
202
+ } else if (isRecord(result.items)) {
203
+ result.items = normalizeDefinition(result.items, false);
204
+ }
205
+ if (typeof result.type === "string" && Array.isArray(result.anyOf)) {
206
+ const parentType = result.type;
207
+ delete result.type;
208
+ result.anyOf = result.anyOf.map(
209
+ (branch) => isRecord(branch) && branch.type == null ? { type: parentType, ...branch } : branch
210
+ );
211
+ }
212
+ for (const key of SCHEMA_ARRAY_KEYS) {
213
+ const value = result[key];
214
+ if (Array.isArray(value)) {
215
+ result[key] = value.map((item) => normalizeDefinition(item, false));
216
+ }
217
+ }
218
+ for (const key of SCHEMA_MAP_KEYS) {
219
+ const value = result[key];
220
+ if (isRecord(value)) {
221
+ result[key] = Object.fromEntries(
222
+ Object.entries(value).map(([k, v]) => [
223
+ k,
224
+ normalizeDefinition(v, false)
225
+ ])
226
+ );
227
+ }
228
+ }
229
+ for (const key of SCHEMA_SINGLE_KEYS) {
230
+ const value = result[key];
231
+ if (isRecord(value) || typeof value === "boolean") {
232
+ result[key] = normalizeDefinition(value, false);
233
+ }
234
+ }
235
+ return result;
236
+ }
237
+
238
+ // src/moonshotai-prepare-tools.ts
239
+ function prepareTools({
240
+ tools,
241
+ toolChoice,
242
+ modelId
243
+ }) {
244
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
245
+ const toolWarnings = [];
246
+ if (tools == null) {
247
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
248
+ }
249
+ const moonshotTools = [];
250
+ for (const tool of tools) {
251
+ if (tool.type === "provider") {
252
+ toolWarnings.push({
253
+ type: "unsupported",
254
+ feature: `provider-defined tool ${tool.id}`
255
+ });
256
+ } else {
257
+ moonshotTools.push({
258
+ type: "function",
259
+ function: {
260
+ name: tool.name,
261
+ description: tool.description,
262
+ parameters: normalizeJsonSchemaForMFJS(tool.inputSchema),
263
+ ...tool.strict != null ? { strict: tool.strict } : {}
264
+ }
265
+ });
266
+ }
267
+ }
268
+ if (toolChoice == null) {
269
+ return { tools: moonshotTools, toolChoice: void 0, toolWarnings };
270
+ }
271
+ const type = toolChoice.type;
272
+ switch (type) {
273
+ case "auto":
274
+ case "none":
275
+ return { tools: moonshotTools, toolChoice: type, toolWarnings };
276
+ case "required":
277
+ if (modelId === "kimi-k2.6" || modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
278
+ toolWarnings.push({
279
+ type: "unsupported",
280
+ feature: `tool choice "required" for model "${modelId}"`,
281
+ details: 'Moonshot AI rejects required tool choice for this model. The setting has been omitted; use "auto" or select a specific tool instead.'
282
+ });
283
+ return {
284
+ tools: moonshotTools,
285
+ toolChoice: void 0,
286
+ toolWarnings
287
+ };
288
+ }
289
+ return { tools: moonshotTools, toolChoice: type, toolWarnings };
290
+ case "tool":
291
+ return {
292
+ tools: moonshotTools,
293
+ toolChoice: {
294
+ type: "function",
295
+ function: { name: toolChoice.toolName }
296
+ },
297
+ toolWarnings
298
+ };
299
+ default: {
300
+ const _exhaustiveCheck = type;
301
+ throw new UnsupportedFunctionalityError2({
302
+ functionality: `tool choice type: ${_exhaustiveCheck}`
303
+ });
304
+ }
305
+ }
306
+ }
307
+
308
+ // src/convert-to-moonshotai-chat-messages.ts
309
+ var supportedImageMediaTypes = [
310
+ "image/jpeg",
311
+ "image/png",
312
+ "image/gif",
313
+ "image/webp",
314
+ "image/bmp",
315
+ "image/heic",
316
+ "image/heif"
317
+ ];
318
+ var supportedVideoMediaTypes = [
319
+ "video/mp4",
320
+ "video/mpeg",
321
+ "video/mov",
322
+ "video/avi",
323
+ "video/x-flv",
324
+ "video/mpg",
325
+ "video/webm",
326
+ "video/wmv",
327
+ "video/3gpp"
328
+ ];
329
+ function formatMediaUrl({
330
+ part,
331
+ supportedMediaTypes,
332
+ topLevelMediaType
333
+ }) {
334
+ if (part.data.type !== "url" && part.data.type !== "data") {
335
+ throw new UnsupportedFunctionalityError3({
336
+ functionality: `file part data type ${part.data.type}`
337
+ });
338
+ }
339
+ const mediaType = part.data.type === "url" ? part.mediaType : resolveFullMediaType({ part });
340
+ if (!supportedMediaTypes.includes(mediaType) && !(part.data.type === "url" && (mediaType === topLevelMediaType || mediaType === `${topLevelMediaType}/*`))) {
341
+ throw new UnsupportedFunctionalityError3({
342
+ functionality: `file part media type ${mediaType}`
343
+ });
344
+ }
345
+ return part.data.type === "url" ? part.data.url.toString() : `data:${mediaType};base64,${convertToBase64(part.data.data)}`;
346
+ }
347
+ async function convertToMoonshotAIChatMessages({
348
+ modelId,
349
+ prompt,
350
+ providerOptionsName = "moonshotai",
351
+ responseFormat
352
+ }) {
353
+ var _a, _b;
41
354
  const messages = [];
42
- for (const { role, content } of prompt) {
355
+ const warnings = [];
356
+ const modelFamily = modelId == null ? "unknown" : getMoonshotAIModelFamily(modelId);
357
+ for (const [index, { role, content, providerOptions }] of prompt.entries()) {
358
+ const moonshotMessageOptions = await parseProviderOptions({
359
+ provider: providerOptionsName,
360
+ providerOptions,
361
+ schema: moonshotaiAllMessageProviderOptions
362
+ });
363
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true && role !== "assistant") {
364
+ throw new InvalidPromptError({
365
+ prompt,
366
+ message: "Moonshot AI Partial Mode requires `partial: true` on an assistant message."
367
+ });
368
+ }
369
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.tools) != null && role !== "system") {
370
+ throw new InvalidPromptError({
371
+ prompt,
372
+ message: "Moonshot dynamic tools must be configured on a system message."
373
+ });
374
+ }
43
375
  switch (role) {
44
376
  case "system": {
45
- messages.push({ role: "system", content });
377
+ if ((_a = moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.tools) == null ? void 0 : _a.length) {
378
+ if (content.length > 0) {
379
+ throw new InvalidPromptError({
380
+ prompt,
381
+ message: "A Moonshot dynamic-tool system message must use empty content because the API forbids content alongside tools."
382
+ });
383
+ }
384
+ if (modelFamily !== "kimi-k3" && modelFamily !== "unknown") {
385
+ warnings.push({
386
+ type: "unsupported",
387
+ feature: `dynamic tool loading for model "${modelId}"`,
388
+ details: "Moonshot documents dynamic tool loading only for Kimi K3. The dynamic system message has been omitted."
389
+ });
390
+ break;
391
+ }
392
+ const { tools, toolWarnings } = prepareTools({
393
+ modelId: modelId != null ? modelId : "custom-model",
394
+ tools: moonshotMessageOptions.tools
395
+ });
396
+ warnings.push(...toolWarnings);
397
+ messages.push({ role: "system", tools: tools != null ? tools : [] });
398
+ break;
399
+ }
400
+ messages.push({
401
+ role: "system",
402
+ content,
403
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
404
+ name: moonshotMessageOptions.name
405
+ }
406
+ });
46
407
  break;
47
408
  }
48
409
  case "user": {
49
410
  if (content.length === 1 && content[0].type === "text") {
50
411
  messages.push({
51
412
  role: "user",
52
- content: content[0].text
413
+ content: content[0].text,
414
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
415
+ name: moonshotMessageOptions.name
416
+ }
53
417
  });
54
418
  break;
55
419
  }
@@ -61,25 +425,53 @@ function convertToMoonshotAIChatMessages(prompt) {
61
425
  return { type: "text", text: part.text };
62
426
  }
63
427
  case "file": {
428
+ const topLevel = getTopLevelMediaType(part.mediaType);
64
429
  switch (part.data.type) {
65
430
  case "reference": {
66
- throw new UnsupportedFunctionalityError({
67
- functionality: "file parts with provider references"
431
+ if (topLevel !== "image" && topLevel !== "video") {
432
+ throw new UnsupportedFunctionalityError3({
433
+ functionality: `file part media type ${part.mediaType}`
434
+ });
435
+ }
436
+ const reference = resolveProviderReference({
437
+ reference: part.data.reference,
438
+ provider: "moonshotai"
68
439
  });
440
+ if (!reference.startsWith("ms://")) {
441
+ throw new UnsupportedFunctionalityError3({
442
+ functionality: "Moonshot file provider references without an ms:// URL"
443
+ });
444
+ }
445
+ return topLevel === "image" ? {
446
+ type: "image_url",
447
+ image_url: { url: reference }
448
+ } : {
449
+ type: "video_url",
450
+ video_url: { url: reference }
451
+ };
69
452
  }
70
453
  case "text": {
71
- throw new UnsupportedFunctionalityError({
72
- functionality: "text file parts"
454
+ if (topLevel === "text") {
455
+ return {
456
+ type: "text",
457
+ text: part.data.text
458
+ };
459
+ }
460
+ throw new UnsupportedFunctionalityError3({
461
+ functionality: `file part media type ${part.mediaType}`
73
462
  });
74
463
  }
75
464
  case "url":
76
465
  case "data": {
77
- const topLevel = getTopLevelMediaType(part.mediaType);
78
466
  if (topLevel === "image") {
79
467
  return {
80
468
  type: "image_url",
81
469
  image_url: {
82
- url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`
470
+ url: formatMediaUrl({
471
+ part,
472
+ supportedMediaTypes: supportedImageMediaTypes,
473
+ topLevelMediaType: "image"
474
+ })
83
475
  }
84
476
  };
85
477
  }
@@ -87,7 +479,11 @@ function convertToMoonshotAIChatMessages(prompt) {
87
479
  return {
88
480
  type: "video_url",
89
481
  video_url: {
90
- url: part.data.type === "url" ? part.data.url.toString() : `data:${resolveFullMediaType({ part })};base64,${convertToBase64(part.data.data)}`
482
+ url: formatMediaUrl({
483
+ part,
484
+ supportedMediaTypes: supportedVideoMediaTypes,
485
+ topLevelMediaType: "video"
486
+ })
91
487
  }
92
488
  };
93
489
  }
@@ -100,18 +496,35 @@ function convertToMoonshotAIChatMessages(prompt) {
100
496
  text: textContent
101
497
  };
102
498
  }
103
- throw new UnsupportedFunctionalityError({
499
+ throw new UnsupportedFunctionalityError3({
104
500
  functionality: `file part media type ${part.mediaType}`
105
501
  });
106
502
  }
107
503
  }
108
504
  }
109
505
  }
110
- })
506
+ }),
507
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
508
+ name: moonshotMessageOptions.name
509
+ }
111
510
  });
112
511
  break;
113
512
  }
114
513
  case "assistant": {
514
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true) {
515
+ if (index !== prompt.length - 1) {
516
+ throw new InvalidPromptError({
517
+ prompt,
518
+ message: "Moonshot AI Partial Mode requires the partial assistant message to be the final message."
519
+ });
520
+ }
521
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json_object") {
522
+ throw new InvalidPromptError({
523
+ prompt,
524
+ message: "Moonshot AI Partial Mode cannot be combined with JSON object response format."
525
+ });
526
+ }
527
+ }
115
528
  let text = "";
116
529
  let reasoning = "";
117
530
  const toolCalls = [];
@@ -141,12 +554,24 @@ function convertToMoonshotAIChatMessages(prompt) {
141
554
  messages.push({
142
555
  role: "assistant",
143
556
  content: toolCalls.length > 0 ? text || null : text,
557
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
558
+ name: moonshotMessageOptions.name
559
+ },
560
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true && {
561
+ partial: true
562
+ },
144
563
  ...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
145
564
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0
146
565
  });
147
566
  break;
148
567
  }
149
568
  case "tool": {
569
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null) {
570
+ warnings.push({
571
+ type: "unsupported",
572
+ feature: "message name on tool messages"
573
+ });
574
+ }
150
575
  for (const toolResponse of content) {
151
576
  if (toolResponse.type === "tool-approval-response") {
152
577
  continue;
@@ -159,7 +584,7 @@ function convertToMoonshotAIChatMessages(prompt) {
159
584
  contentValue = output.value;
160
585
  break;
161
586
  case "execution-denied":
162
- contentValue = (_a = output.reason) != null ? _a : "Tool call execution denied.";
587
+ contentValue = (_b = output.reason) != null ? _b : "Tool call execution denied.";
163
588
  break;
164
589
  case "content":
165
590
  case "json":
@@ -181,7 +606,7 @@ function convertToMoonshotAIChatMessages(prompt) {
181
606
  }
182
607
  }
183
608
  }
184
- return messages;
609
+ return { messages, warnings };
185
610
  }
186
611
 
187
612
  // src/convert-moonshotai-chat-usage.ts
@@ -230,75 +655,100 @@ function mapMoonshotAIFinishReason(finishReason) {
230
655
 
231
656
  // src/moonshotai-chat-api-types.ts
232
657
  import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
233
- import { z } from "zod/v4";
234
- var tokenUsageSchema = z.object({
235
- prompt_tokens: z.number().nullish(),
236
- completion_tokens: z.number().nullish(),
237
- cached_tokens: z.number().nullish(),
238
- total_tokens: z.number().nullish(),
239
- prompt_tokens_details: z.object({
240
- cached_tokens: z.number().nullish()
658
+ import { z as z2 } from "zod/v4";
659
+ var tokenUsageSchema = z2.looseObject({
660
+ prompt_tokens: z2.number().nullish(),
661
+ completion_tokens: z2.number().nullish(),
662
+ cached_tokens: z2.number().nullish(),
663
+ total_tokens: z2.number().nullish(),
664
+ prompt_tokens_details: z2.looseObject({
665
+ cached_tokens: z2.number().nullish()
241
666
  }).nullish(),
242
- completion_tokens_details: z.object({
243
- reasoning_tokens: z.number().nullish()
667
+ completion_tokens_details: z2.looseObject({
668
+ reasoning_tokens: z2.number().nullish()
244
669
  }).nullish()
245
670
  }).nullish();
246
- var moonshotAIErrorSchema = z.object({
247
- error: z.object({
248
- message: z.string(),
249
- type: z.string().nullish()
671
+ var moonshotAIErrorSchema = z2.object({
672
+ error: z2.object({
673
+ message: z2.string(),
674
+ type: z2.string().nullish(),
675
+ code: z2.string().nullish()
250
676
  })
251
677
  });
252
- var moonshotAIChatResponseSchema = z.object({
253
- id: z.string().nullish(),
254
- created: z.number().nullish(),
255
- model: z.string().nullish(),
256
- choices: z.array(
257
- z.object({
258
- message: z.object({
259
- role: z.literal("assistant").nullish(),
260
- content: z.string().nullish(),
261
- reasoning_content: z.string().nullish(),
262
- tool_calls: z.array(
263
- z.object({
264
- id: z.string().nullish(),
265
- function: z.object({
266
- name: z.string(),
267
- arguments: z.string()
678
+ var moonshotAIChatLogprobSchema = z2.object({
679
+ token: z2.string(),
680
+ logprob: z2.number(),
681
+ bytes: z2.array(z2.number()).nullable(),
682
+ top_logprobs: z2.array(
683
+ z2.object({
684
+ token: z2.string(),
685
+ logprob: z2.number(),
686
+ bytes: z2.array(z2.number()).nullable()
687
+ })
688
+ )
689
+ });
690
+ var moonshotAIChatLogprobsSchema = z2.object({
691
+ content: z2.array(moonshotAIChatLogprobSchema).nullish()
692
+ }).nullish();
693
+ var moonshotAIChatResponseSchema = z2.object({
694
+ id: z2.string().nullish(),
695
+ created: z2.number().nullish(),
696
+ model: z2.string().nullish(),
697
+ object: z2.literal("chat.completion").nullish(),
698
+ choices: z2.array(
699
+ z2.object({
700
+ index: z2.number().nullish(),
701
+ message: z2.object({
702
+ role: z2.literal("assistant").nullish(),
703
+ content: z2.string().nullish(),
704
+ reasoning_content: z2.string().nullish(),
705
+ tool_calls: z2.array(
706
+ z2.object({
707
+ id: z2.string().nullish(),
708
+ type: z2.literal("function").nullish(),
709
+ function: z2.object({
710
+ name: z2.string(),
711
+ arguments: z2.string()
268
712
  })
269
713
  })
270
714
  ).nullish()
271
715
  }),
272
- finish_reason: z.string().nullish()
716
+ logprobs: moonshotAIChatLogprobsSchema,
717
+ finish_reason: z2.string().nullish()
273
718
  })
274
719
  ),
275
720
  usage: tokenUsageSchema
276
721
  });
277
722
  var moonshotAIChatChunkSchema = lazySchema(
278
723
  () => zodSchema(
279
- z.union([
280
- z.object({
281
- id: z.string().nullish(),
282
- created: z.number().nullish(),
283
- model: z.string().nullish(),
284
- choices: z.array(
285
- z.object({
286
- delta: z.object({
287
- role: z.literal("assistant").nullish(),
288
- content: z.string().nullish(),
289
- reasoning_content: z.string().nullish(),
290
- tool_calls: z.array(
291
- z.object({
292
- index: z.number(),
293
- id: z.string().nullish(),
294
- function: z.object({
295
- name: z.string().nullish(),
296
- arguments: z.string().nullish()
724
+ z2.union([
725
+ z2.object({
726
+ id: z2.string().nullish(),
727
+ created: z2.number().nullish(),
728
+ model: z2.string().nullish(),
729
+ object: z2.literal("chat.completion.chunk").nullish(),
730
+ choices: z2.array(
731
+ z2.object({
732
+ index: z2.number().nullish(),
733
+ delta: z2.object({
734
+ role: z2.literal("assistant").nullish(),
735
+ content: z2.string().nullish(),
736
+ reasoning_content: z2.string().nullish(),
737
+ tool_calls: z2.array(
738
+ z2.object({
739
+ index: z2.number().nullish(),
740
+ id: z2.string().nullish(),
741
+ type: z2.literal("function").nullish(),
742
+ function: z2.object({
743
+ name: z2.string().nullish(),
744
+ arguments: z2.string().nullish()
297
745
  })
298
746
  })
299
747
  ).nullish()
300
748
  }).nullish(),
301
- finish_reason: z.string().nullish()
749
+ logprobs: moonshotAIChatLogprobsSchema,
750
+ finish_reason: z2.string().nullish(),
751
+ usage: tokenUsageSchema
302
752
  })
303
753
  ),
304
754
  usage: tokenUsageSchema
@@ -308,176 +758,48 @@ var moonshotAIChatChunkSchema = lazySchema(
308
758
  )
309
759
  );
310
760
 
311
- // src/moonshotai-chat-options.ts
312
- import { z as z2 } from "zod/v4";
313
- var moonshotaiLanguageModelOptions = z2.object({
314
- /**
315
- * Reasoning effort for Kimi K3.
316
- */
317
- reasoningEffort: z2.enum(["low", "high", "max"]).optional(),
318
- thinking: z2.object({
319
- type: z2.enum(["enabled", "disabled"]).optional(),
320
- budgetTokens: z2.number().int().min(1024).optional()
321
- }).optional(),
322
- reasoningHistory: z2.enum(["disabled", "interleaved", "preserved"]).optional(),
323
- /**
324
- * Used to cache responses for similar requests to optimize cache hit rates.
325
- * Typically a session or task id.
326
- */
327
- promptCacheKey: z2.string().optional(),
328
- /**
329
- * A stable identifier used to help Moonshot detect users violating usage
330
- * policies. Recommended to hash the username or email address.
331
- */
332
- safetyIdentifier: z2.string().optional()
333
- });
334
- function getModelThinkingKeepSupport(modelId) {
335
- return modelId === "kimi-k2.6" || modelId === "kimi-k3" || modelId.startsWith("kimi-k2.7-code");
336
- }
337
-
338
- // src/moonshotai-prepare-tools.ts
339
- import {
340
- UnsupportedFunctionalityError as UnsupportedFunctionalityError3
341
- } from "@ai-sdk/provider";
342
-
343
- // src/normalize-json-schema-for-mfjs.ts
344
- import { UnsupportedFunctionalityError as UnsupportedFunctionalityError2 } from "@ai-sdk/provider";
345
- import { isRecord } from "@ai-sdk/provider-utils";
346
- var SCHEMA_ARRAY_KEYS = ["allOf", "anyOf", "oneOf", "prefixItems"];
347
- var SCHEMA_MAP_KEYS = [
348
- "properties",
349
- "patternProperties",
350
- "$defs",
351
- "dependentSchemas"
352
- ];
353
- var SCHEMA_SINGLE_KEYS = [
354
- "additionalProperties",
355
- "propertyNames",
356
- "items",
357
- "contains",
358
- "not",
359
- "if",
360
- "then",
361
- "else"
362
- ];
363
- function normalizeJsonSchemaForMFJS(schema) {
364
- return normalizeDefinition(schema, true);
365
- }
366
- function normalizeDefinition(definition, isRoot) {
367
- if (typeof definition === "boolean" || !isRecord(definition)) {
368
- if (isRoot) {
369
- throw new UnsupportedFunctionalityError2({
370
- functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
371
- });
372
- }
373
- return definition;
374
- }
375
- if (isRoot && definition.type !== "object") {
376
- throw new UnsupportedFunctionalityError2({
377
- functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
378
- });
379
- }
380
- const result = { ...definition };
381
- if (Array.isArray(result.items)) {
382
- const tuple = result.items;
383
- result.prefixItems = [
384
- ...Array.isArray(result.prefixItems) ? result.prefixItems : [],
385
- ...tuple.map((item) => normalizeDefinition(item, false))
386
- ];
387
- delete result.items;
388
- } else if (isRecord(result.items)) {
389
- result.items = normalizeDefinition(result.items, false);
390
- }
391
- if (typeof result.type === "string" && Array.isArray(result.anyOf)) {
392
- const parentType = result.type;
393
- delete result.type;
394
- result.anyOf = result.anyOf.map(
395
- (branch) => isRecord(branch) && branch.type == null ? { type: parentType, ...branch } : branch
396
- );
397
- }
398
- for (const key of SCHEMA_ARRAY_KEYS) {
399
- const value = result[key];
400
- if (Array.isArray(value)) {
401
- result[key] = value.map((item) => normalizeDefinition(item, false));
402
- }
403
- }
404
- for (const key of SCHEMA_MAP_KEYS) {
405
- const value = result[key];
406
- if (isRecord(value)) {
407
- result[key] = Object.fromEntries(
408
- Object.entries(value).map(([k, v]) => [
409
- k,
410
- normalizeDefinition(v, false)
411
- ])
412
- );
413
- }
414
- }
415
- for (const key of SCHEMA_SINGLE_KEYS) {
416
- const value = result[key];
417
- if (isRecord(value) || typeof value === "boolean") {
418
- result[key] = normalizeDefinition(value, false);
419
- }
420
- }
421
- return result;
761
+ // src/moonshotai-chat-language-model.ts
762
+ function createMoonshotAIStreamError(error, data) {
763
+ var _a, _b;
764
+ return createProviderStreamError({
765
+ message: error.message,
766
+ type: (_a = error.type) != null ? _a : void 0,
767
+ code: (_b = error.code) != null ? _b : void 0,
768
+ ...getMoonshotAIStreamErrorMetadata(error.type),
769
+ data
770
+ });
422
771
  }
423
-
424
- // src/moonshotai-prepare-tools.ts
425
- function prepareTools({
426
- tools,
427
- toolChoice
428
- }) {
429
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
430
- const toolWarnings = [];
431
- if (tools == null) {
432
- return { tools: void 0, toolChoice: void 0, toolWarnings };
433
- }
434
- const moonshotTools = [];
435
- for (const tool of tools) {
436
- if (tool.type === "provider") {
437
- toolWarnings.push({
438
- type: "unsupported",
439
- feature: `provider-defined tool ${tool.id}`
440
- });
441
- } else {
442
- moonshotTools.push({
443
- type: "function",
444
- function: {
445
- name: tool.name,
446
- description: tool.description,
447
- parameters: normalizeJsonSchemaForMFJS(tool.inputSchema),
448
- ...tool.strict != null ? { strict: tool.strict } : {}
449
- }
450
- });
451
- }
452
- }
453
- if (toolChoice == null) {
454
- return { tools: moonshotTools, toolChoice: void 0, toolWarnings };
455
- }
456
- const type = toolChoice.type;
772
+ function getMoonshotAIStreamErrorMetadata(type) {
457
773
  switch (type) {
458
- case "auto":
459
- case "none":
460
- case "required":
461
- return { tools: moonshotTools, toolChoice: type, toolWarnings };
462
- case "tool":
463
- return {
464
- tools: moonshotTools,
465
- toolChoice: {
466
- type: "function",
467
- function: { name: toolChoice.toolName }
468
- },
469
- toolWarnings
470
- };
471
- default: {
472
- const _exhaustiveCheck = type;
473
- throw new UnsupportedFunctionalityError3({
474
- functionality: `tool choice type: ${_exhaustiveCheck}`
475
- });
476
- }
774
+ case "rate_limit_exceeded":
775
+ case "rate_limit_error":
776
+ return { statusCode: 429, isRetryable: true };
777
+ case "server_error":
778
+ case "api_error":
779
+ case "internal_server_error":
780
+ return { statusCode: 500, isRetryable: true };
781
+ case "overloaded_error":
782
+ case "service_unavailable":
783
+ return { statusCode: 503, isRetryable: true };
784
+ case "timeout":
785
+ case "timeout_error":
786
+ return { statusCode: 504, isRetryable: true };
787
+ case "authentication_error":
788
+ case "invalid_api_key":
789
+ return { statusCode: 401, isRetryable: false };
790
+ case "permission_error":
791
+ return { statusCode: 403, isRetryable: false };
792
+ case "not_found_error":
793
+ case "model_not_found":
794
+ return { statusCode: 404, isRetryable: false };
795
+ case "bad_request":
796
+ case "context_length_exceeded":
797
+ case "invalid_request_error":
798
+ return { statusCode: 400, isRetryable: false };
799
+ default:
800
+ return {};
477
801
  }
478
802
  }
479
-
480
- // src/moonshotai-chat-language-model.ts
481
803
  var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
482
804
  constructor(modelId, config) {
483
805
  this.specificationVersion = "v4";
@@ -526,13 +848,12 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
526
848
  toolChoice,
527
849
  tools
528
850
  }) {
529
- var _a, _b, _c;
530
- const moonshotOptions = (_a = await parseProviderOptions({
851
+ var _a, _b, _c, _d, _e;
852
+ const moonshotOptions = (_a = await parseProviderOptions2({
531
853
  provider: this.providerOptionsName,
532
854
  providerOptions,
533
855
  schema: moonshotaiLanguageModelOptions
534
856
  })) != null ? _a : {};
535
- const messages = convertToMoonshotAIChatMessages(prompt);
536
857
  const allWarnings = [];
537
858
  if (topK != null) {
538
859
  allWarnings.push({ type: "unsupported", feature: "topK" });
@@ -540,40 +861,184 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
540
861
  if (seed != null) {
541
862
  allWarnings.push({ type: "unsupported", feature: "seed" });
542
863
  }
864
+ const supportsSamplingOptions = !isMoonshotAIKimiModel(this.modelId);
865
+ if (!supportsSamplingOptions && temperature != null) {
866
+ allWarnings.push({
867
+ type: "unsupported",
868
+ feature: "temperature",
869
+ details: `temperature is fixed by model "${this.modelId}" and has been omitted.`
870
+ });
871
+ }
872
+ if (!supportsSamplingOptions && topP != null) {
873
+ allWarnings.push({
874
+ type: "unsupported",
875
+ feature: "topP",
876
+ details: `topP is fixed by model "${this.modelId}" and has been omitted.`
877
+ });
878
+ }
879
+ if (!supportsSamplingOptions && frequencyPenalty != null) {
880
+ allWarnings.push({
881
+ type: "unsupported",
882
+ feature: "frequencyPenalty",
883
+ details: `frequencyPenalty is fixed by model "${this.modelId}" and has been omitted.`
884
+ });
885
+ }
886
+ if (!supportsSamplingOptions && presencePenalty != null) {
887
+ allWarnings.push({
888
+ type: "unsupported",
889
+ feature: "presencePenalty",
890
+ details: `presencePenalty is fixed by model "${this.modelId}" and has been omitted.`
891
+ });
892
+ }
543
893
  const {
544
894
  tools: moonshotTools,
545
895
  toolChoice: moonshotToolChoice,
546
896
  toolWarnings
547
- } = prepareTools({ tools, toolChoice });
548
- const thinking = moonshotOptions.thinking;
549
- let keep;
550
- if (moonshotOptions.reasoningHistory === "preserved") {
551
- if (getModelThinkingKeepSupport(this.modelId)) {
552
- keep = "all";
553
- } else {
897
+ } = prepareTools({ tools, toolChoice, modelId: this.modelId });
898
+ const modelFamily = getMoonshotAIModelFamily(this.modelId);
899
+ const requestedThinking = moonshotOptions.thinking;
900
+ const requestedReasoningEffort = moonshotOptions.reasoningEffort;
901
+ const preserveReasoning = moonshotOptions.reasoningHistory === "preserved";
902
+ if ((requestedThinking == null ? void 0 : requestedThinking.budgetTokens) != null) {
903
+ allWarnings.push({
904
+ type: "deprecated",
905
+ setting: "providerOptions.moonshotai.thinking.budgetTokens",
906
+ message: "Moonshot Chat Completions does not support budget_tokens. Remove budgetTokens; the option has been omitted."
907
+ });
908
+ }
909
+ let thinking;
910
+ let reasoningEffort;
911
+ const warnUnsupportedReasoningEffort = () => {
912
+ if (requestedReasoningEffort != null) {
554
913
  allWarnings.push({
555
914
  type: "unsupported",
556
- feature: `reasoningHistory 'preserved' is not supported by model "${this.modelId}"`
915
+ feature: "reasoningEffort",
916
+ details: `reasoningEffort is only supported by Kimi K3 and has been omitted for model "${this.modelId}".`
557
917
  });
558
918
  }
919
+ };
920
+ switch (modelFamily) {
921
+ case "kimi-k3": {
922
+ if (requestedThinking != null) {
923
+ allWarnings.push({
924
+ type: "unsupported",
925
+ feature: "thinking",
926
+ details: "Kimi K3 always reasons and does not accept the thinking field. The option has been omitted."
927
+ });
928
+ }
929
+ if (reasoning === "none") {
930
+ allWarnings.push({
931
+ type: "unsupported",
932
+ feature: 'reasoning "none"',
933
+ details: "Kimi K3 reasoning cannot be disabled."
934
+ });
935
+ }
936
+ reasoningEffort = requestedReasoningEffort != null ? requestedReasoningEffort : isCustomReasoning(reasoning) && reasoning !== "none" ? mapReasoningToProviderEffort({
937
+ reasoning,
938
+ effortMap: {
939
+ minimal: "low",
940
+ low: "low",
941
+ medium: "high",
942
+ high: "high",
943
+ xhigh: "max"
944
+ },
945
+ warnings: allWarnings
946
+ }) : void 0;
947
+ break;
948
+ }
949
+ case "kimi-k2.7": {
950
+ warnUnsupportedReasoningEffort();
951
+ if ((requestedThinking == null ? void 0 : requestedThinking.type) === "disabled" || reasoning === "none") {
952
+ allWarnings.push({
953
+ type: "unsupported",
954
+ feature: (requestedThinking == null ? void 0 : requestedThinking.type) === "disabled" ? 'thinking.type "disabled"' : 'reasoning "none"',
955
+ details: "Kimi K2.7 thinking cannot be disabled."
956
+ });
957
+ } else if ((requestedThinking == null ? void 0 : requestedThinking.type) === "enabled") {
958
+ thinking = { type: "enabled" };
959
+ }
960
+ break;
961
+ }
962
+ case "kimi-k2.6": {
963
+ warnUnsupportedReasoningEffort();
964
+ const thinkingType = (_b = requestedThinking == null ? void 0 : requestedThinking.type) != null ? _b : isCustomReasoning(reasoning) ? reasoning === "none" ? "disabled" : "enabled" : void 0;
965
+ if (thinkingType != null || preserveReasoning) {
966
+ thinking = {
967
+ type: thinkingType != null ? thinkingType : "enabled",
968
+ ...preserveReasoning ? { keep: "all" } : {}
969
+ };
970
+ }
971
+ break;
972
+ }
973
+ case "kimi-k2.5": {
974
+ warnUnsupportedReasoningEffort();
975
+ const thinkingType = (_c = requestedThinking == null ? void 0 : requestedThinking.type) != null ? _c : isCustomReasoning(reasoning) ? reasoning === "none" ? "disabled" : "enabled" : void 0;
976
+ if (thinkingType != null) {
977
+ thinking = { type: thinkingType };
978
+ }
979
+ if (preserveReasoning) {
980
+ allWarnings.push({
981
+ type: "unsupported",
982
+ feature: `reasoningHistory 'preserved' is not supported by model "${this.modelId}"`
983
+ });
984
+ }
985
+ break;
986
+ }
987
+ case "moonshot-v1": {
988
+ warnUnsupportedReasoningEffort();
989
+ if (requestedThinking != null) {
990
+ allWarnings.push({
991
+ type: "unsupported",
992
+ feature: "thinking",
993
+ details: `thinking is not supported by model "${this.modelId}" and has been omitted.`
994
+ });
995
+ }
996
+ if (isCustomReasoning(reasoning) && reasoning !== "none") {
997
+ allWarnings.push({
998
+ type: "unsupported",
999
+ feature: "reasoning",
1000
+ details: `reasoning is not supported by model "${this.modelId}".`
1001
+ });
1002
+ }
1003
+ if (preserveReasoning) {
1004
+ allWarnings.push({
1005
+ type: "unsupported",
1006
+ feature: `reasoningHistory 'preserved' is not supported by model "${this.modelId}"`
1007
+ });
1008
+ }
1009
+ break;
1010
+ }
1011
+ case "unknown": {
1012
+ if (reasoning === "none") {
1013
+ allWarnings.push({
1014
+ type: "unsupported",
1015
+ feature: 'reasoning "none"',
1016
+ details: "Use providerOptions.moonshotai.thinking to control thinking on custom models."
1017
+ });
1018
+ }
1019
+ reasoningEffort = requestedReasoningEffort != null ? requestedReasoningEffort : isCustomReasoning(reasoning) && reasoning !== "none" ? mapReasoningToProviderEffort({
1020
+ reasoning,
1021
+ effortMap: {
1022
+ minimal: "low",
1023
+ low: "low",
1024
+ medium: "high",
1025
+ high: "high",
1026
+ xhigh: "max"
1027
+ },
1028
+ warnings: allWarnings
1029
+ }) : void 0;
1030
+ if ((requestedThinking == null ? void 0 : requestedThinking.type) != null) {
1031
+ thinking = { type: requestedThinking.type };
1032
+ }
1033
+ if (preserveReasoning) {
1034
+ allWarnings.push({
1035
+ type: "unsupported",
1036
+ feature: `reasoningHistory 'preserved' is not supported by model "${this.modelId}"`
1037
+ });
1038
+ }
1039
+ break;
1040
+ }
559
1041
  }
560
- if (reasoning === "none") {
561
- allWarnings.push({
562
- type: "unsupported",
563
- feature: 'reasoning "none" (use providerOptions.moonshotai.thinking to control thinking)'
564
- });
565
- }
566
- const reasoningEffort = (_b = moonshotOptions.reasoningEffort) != null ? _b : isCustomReasoning(reasoning) && reasoning !== "none" ? mapReasoningToProviderEffort({
567
- reasoning,
568
- effortMap: {
569
- minimal: "low",
570
- low: "low",
571
- medium: "high",
572
- high: "high",
573
- xhigh: "max"
574
- },
575
- warnings: allWarnings
576
- }) : void 0;
577
1042
  let response_format;
578
1043
  if ((responseFormat == null ? void 0 : responseFormat.type) === "json") {
579
1044
  if (this.config.supportsStructuredOutputs === true && responseFormat.schema != null) {
@@ -581,39 +1046,43 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
581
1046
  response_format = {
582
1047
  type: "json_schema",
583
1048
  json_schema: {
584
- name: (_c = responseFormat.name) != null ? _c : "response",
585
- schema: schemaWithoutDollarSchema,
586
- ...responseFormat.description != null && {
587
- description: responseFormat.description
588
- }
1049
+ name: (_d = responseFormat.name) != null ? _d : "response",
1050
+ strict: (_e = moonshotOptions.strictJsonSchema) != null ? _e : true,
1051
+ schema: normalizeJsonSchemaForMFJS(schemaWithoutDollarSchema)
589
1052
  }
590
1053
  };
591
1054
  } else {
592
1055
  response_format = { type: "json_object" };
593
1056
  }
594
1057
  }
1058
+ const { messages, warnings: messageWarnings } = await convertToMoonshotAIChatMessages({
1059
+ modelId: this.modelId,
1060
+ prompt,
1061
+ providerOptionsName: this.providerOptionsName,
1062
+ responseFormat: response_format
1063
+ });
1064
+ allWarnings.push(...messageWarnings);
595
1065
  return {
596
1066
  args: {
597
1067
  model: this.modelId,
598
- max_tokens: maxOutputTokens,
599
- temperature,
600
- top_p: topP,
601
- frequency_penalty: frequencyPenalty,
602
- presence_penalty: presencePenalty,
1068
+ ...(moonshotOptions.logprobs === true || moonshotOptions.topLogprobs != null) && { logprobs: true },
1069
+ ...moonshotOptions.topLogprobs != null && {
1070
+ top_logprobs: moonshotOptions.topLogprobs
1071
+ },
1072
+ max_completion_tokens: maxOutputTokens,
1073
+ temperature: supportsSamplingOptions ? temperature : void 0,
1074
+ top_p: supportsSamplingOptions ? topP : void 0,
1075
+ frequency_penalty: supportsSamplingOptions ? frequencyPenalty : void 0,
1076
+ presence_penalty: supportsSamplingOptions ? presencePenalty : void 0,
603
1077
  response_format,
604
1078
  stop: stopSequences,
605
1079
  messages,
606
1080
  tools: moonshotTools,
607
1081
  tool_choice: moonshotToolChoice,
608
- ...thinking != null || keep != null ? {
609
- thinking: {
610
- ...(thinking == null ? void 0 : thinking.type) != null && { type: thinking.type },
611
- ...(thinking == null ? void 0 : thinking.budgetTokens) !== void 0 && {
612
- budget_tokens: thinking.budgetTokens
613
- },
614
- ...keep != null && { keep }
615
- }
616
- } : {},
1082
+ ...moonshotOptions.prediction != null && {
1083
+ prediction: moonshotOptions.prediction
1084
+ },
1085
+ ...thinking != null ? { thinking } : {},
617
1086
  ...reasoningEffort != null && {
618
1087
  reasoning_effort: reasoningEffort
619
1088
  },
@@ -675,6 +1144,21 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
675
1144
  raw: (_d = choice.finish_reason) != null ? _d : void 0
676
1145
  },
677
1146
  usage: convertMoonshotAIChatUsage(responseBody.usage),
1147
+ providerMetadata: {
1148
+ [this.providerOptionsName]: {
1149
+ ...choice.logprobs != null && { logprobs: choice.logprobs },
1150
+ ...responseBody.object != null && {
1151
+ responseObject: responseBody.object
1152
+ },
1153
+ ...choice.index != null && { choiceIndex: choice.index },
1154
+ ...choice.message.role != null && {
1155
+ messageRole: choice.message.role
1156
+ },
1157
+ ...choice.message.tool_calls != null && {
1158
+ toolCallTypes: choice.message.tool_calls.map((toolCall) => toolCall.type).filter((type) => type != null)
1159
+ }
1160
+ }
1161
+ },
678
1162
  request: { body: args },
679
1163
  response: {
680
1164
  ...getResponseMetadata(responseBody),
@@ -713,10 +1197,17 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
713
1197
  unified: "other",
714
1198
  raw: void 0
715
1199
  };
716
- let usage = void 0;
1200
+ let topLevelUsage = void 0;
1201
+ let choiceUsage = void 0;
1202
+ const contentLogprobs = [];
1203
+ const providerOptionsName = this.providerOptionsName;
717
1204
  let isFirstChunk = true;
718
1205
  let isActiveReasoning = false;
719
1206
  let isActiveText = false;
1207
+ let responseObject;
1208
+ let choiceIndex;
1209
+ let messageRole;
1210
+ const toolCallTypes = /* @__PURE__ */ new Map();
720
1211
  return {
721
1212
  stream: response.pipeThrough(
722
1213
  new TransformStream({
@@ -727,6 +1218,7 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
727
1218
  controller.enqueue({ type: "stream-start", warnings });
728
1219
  },
729
1220
  transform(chunk, controller) {
1221
+ var _a2, _b2;
730
1222
  if (options.includeRawChunks) {
731
1223
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
732
1224
  }
@@ -738,7 +1230,10 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
738
1230
  const value = chunk.value;
739
1231
  if ("error" in value) {
740
1232
  finishReason = { unified: "error", raw: void 0 };
741
- controller.enqueue({ type: "error", error: value.error.message });
1233
+ controller.enqueue({
1234
+ type: "error",
1235
+ error: createMoonshotAIStreamError(value.error, value)
1236
+ });
742
1237
  return;
743
1238
  }
744
1239
  if (isFirstChunk) {
@@ -749,19 +1244,34 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
749
1244
  });
750
1245
  }
751
1246
  if (value.usage != null) {
752
- usage = value.usage;
1247
+ topLevelUsage = value.usage;
1248
+ }
1249
+ if (value.object != null) {
1250
+ responseObject = value.object;
753
1251
  }
754
1252
  const choice = value.choices[0];
1253
+ if ((choice == null ? void 0 : choice.usage) != null) {
1254
+ choiceUsage = choice.usage;
1255
+ }
1256
+ if ((choice == null ? void 0 : choice.index) != null) {
1257
+ choiceIndex = choice.index;
1258
+ }
755
1259
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
756
1260
  finishReason = {
757
1261
  unified: mapMoonshotAIFinishReason(choice.finish_reason),
758
1262
  raw: choice.finish_reason
759
1263
  };
760
1264
  }
1265
+ if (((_a2 = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _a2.content) != null) {
1266
+ contentLogprobs.push(...choice.logprobs.content);
1267
+ }
761
1268
  if ((choice == null ? void 0 : choice.delta) == null) {
762
1269
  return;
763
1270
  }
764
1271
  const delta = choice.delta;
1272
+ if (delta.role != null) {
1273
+ messageRole = delta.role;
1274
+ }
765
1275
  const reasoningContent = delta.reasoning_content;
766
1276
  if (reasoningContent) {
767
1277
  if (!isActiveReasoning) {
@@ -803,8 +1313,15 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
803
1313
  });
804
1314
  isActiveReasoning = false;
805
1315
  }
806
- for (const toolCallDelta of delta.tool_calls) {
807
- toolCallTracker.processDelta(toolCallDelta);
1316
+ for (const [index, toolCallDelta] of delta.tool_calls.entries()) {
1317
+ const toolCallIndex = (_b2 = toolCallDelta.index) != null ? _b2 : index;
1318
+ if (toolCallDelta.type != null) {
1319
+ toolCallTypes.set(toolCallIndex, toolCallDelta.type);
1320
+ }
1321
+ toolCallTracker.processDelta({
1322
+ ...toolCallDelta,
1323
+ index: toolCallIndex
1324
+ });
808
1325
  }
809
1326
  }
810
1327
  },
@@ -819,7 +1336,20 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
819
1336
  controller.enqueue({
820
1337
  type: "finish",
821
1338
  finishReason,
822
- usage: convertMoonshotAIChatUsage(usage)
1339
+ usage: convertMoonshotAIChatUsage(topLevelUsage != null ? topLevelUsage : choiceUsage),
1340
+ providerMetadata: {
1341
+ [providerOptionsName]: {
1342
+ ...contentLogprobs.length > 0 && {
1343
+ logprobs: { content: contentLogprobs }
1344
+ },
1345
+ ...responseObject != null && { responseObject },
1346
+ ...choiceIndex != null && { choiceIndex },
1347
+ ...messageRole != null && { messageRole },
1348
+ ...toolCallTypes.size > 0 && {
1349
+ toolCallTypes: [...toolCallTypes.entries()].sort(([left], [right]) => left - right).map(([, type]) => type)
1350
+ }
1351
+ }
1352
+ }
823
1353
  });
824
1354
  }
825
1355
  })
@@ -831,13 +1361,12 @@ var MoonshotAIChatLanguageModel = class _MoonshotAIChatLanguageModel {
831
1361
  };
832
1362
 
833
1363
  // src/version.ts
834
- var VERSION = true ? "3.0.38" : "0.0.0-test";
1364
+ var VERSION = true ? "3.0.41" : "0.0.0-test";
835
1365
 
836
1366
  // src/moonshotai-provider.ts
837
1367
  var defaultBaseURL = "https://api.moonshot.ai/v1";
838
1368
  function getModelStructuredOutputSupport(modelId) {
839
- if (modelId.startsWith("kimi-k")) return true;
840
- return false;
1369
+ return modelId.startsWith("kimi-k") || modelId === "moonshot-v1-8k" || modelId === "moonshot-v1-32k" || modelId === "moonshot-v1-128k" || modelId === "moonshot-v1-auto" || modelId === "moonshot-v1-8k-vision-preview" || modelId === "moonshot-v1-32k-vision-preview" || modelId === "moonshot-v1-128k-vision-preview";
841
1370
  }
842
1371
  function createMoonshotAI(options = {}) {
843
1372
  var _a;