@ai-sdk/moonshotai 2.0.51 → 2.0.54

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.mjs CHANGED
@@ -24,12 +24,300 @@ import {
24
24
 
25
25
  // src/convert-to-moonshotai-chat-messages.ts
26
26
  import {
27
- UnsupportedFunctionalityError
27
+ InvalidArgumentError,
28
+ InvalidPromptError,
29
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError3
28
30
  } from "@ai-sdk/provider";
29
31
  import {
30
32
  convertBase64ToUint8Array,
31
33
  convertToBase64
32
34
  } from "@ai-sdk/provider-utils";
35
+
36
+ // src/moonshotai-chat-options.ts
37
+ import { z } from "zod/v4";
38
+ function isMoonshotAIKimiModel(modelId) {
39
+ return getMoonshotAIModelFamily(modelId).startsWith("kimi-");
40
+ }
41
+ function getMoonshotAIModelFamily(modelId) {
42
+ if (modelId === "kimi-k2.5") return "kimi-k2.5";
43
+ if (modelId === "kimi-k2.6") return "kimi-k2.6";
44
+ if (modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
45
+ return "kimi-k2.7";
46
+ }
47
+ if (modelId === "kimi-k3") return "kimi-k3";
48
+ if (modelId.startsWith("moonshot-v1-")) return "moonshot-v1";
49
+ return "unknown";
50
+ }
51
+ var moonshotaiLanguageModelOptions = z.object({
52
+ /**
53
+ * Whether to use strict JSON schema validation for structured outputs.
54
+ *
55
+ * @default true
56
+ */
57
+ strictJsonSchema: z.boolean().optional(),
58
+ /**
59
+ * Whether to return log probabilities for generated tokens.
60
+ */
61
+ logprobs: z.boolean().optional(),
62
+ /**
63
+ * Number of most likely tokens to return at each token position.
64
+ *
65
+ * Setting this option automatically enables `logprobs`.
66
+ */
67
+ topLogprobs: z.number().int().min(0).max(20).optional(),
68
+ /**
69
+ * Reasoning effort for Kimi K3. Supports `low`, `high`, and `max`;
70
+ * defaults to `max`.
71
+ */
72
+ reasoningEffort: z.enum(["low", "high", "max"]).optional(),
73
+ /**
74
+ * Static predicted content that can accelerate responses when much of the
75
+ * output is known ahead of time.
76
+ */
77
+ prediction: z.object({
78
+ type: z.literal("content"),
79
+ content: z.union([
80
+ z.string(),
81
+ z.array(z.object({ type: z.literal("text"), text: z.string() }))
82
+ ])
83
+ }).optional(),
84
+ /**
85
+ * Thinking configuration for Kimi K2.x models. Kimi K2.5 and K2.6 support
86
+ * enabling or disabling thinking. Kimi K2.7 Code always has thinking
87
+ * enabled.
88
+ */
89
+ thinking: z.object({
90
+ type: z.enum(["enabled", "disabled"]).optional(),
91
+ /**
92
+ * @deprecated Moonshot Chat Completions does not support thinking
93
+ * budgets. Accepted for backwards compatibility, then omitted with a
94
+ * warning.
95
+ */
96
+ budgetTokens: z.number().int().min(1024).optional()
97
+ }).optional(),
98
+ /**
99
+ * Controls preserved reasoning behavior in multi-turn conversations.
100
+ * `disabled` and `interleaved` are compatibility values that leave the
101
+ * request unchanged. `preserved` maps to `thinking.keep: 'all'` for Kimi
102
+ * K2.6. Kimi K2.7 and K3 preserve reasoning by default.
103
+ */
104
+ reasoningHistory: z.enum(["disabled", "interleaved", "preserved"]).optional(),
105
+ /**
106
+ * Used to cache responses for similar requests to optimize cache hit rates.
107
+ * Typically a session or task id.
108
+ */
109
+ promptCacheKey: z.string().optional(),
110
+ /**
111
+ * A stable identifier used to help Moonshot detect users violating usage
112
+ * policies. Recommended to hash the username or email address.
113
+ */
114
+ safetyIdentifier: z.string().optional()
115
+ });
116
+ var moonshotaiMessageProviderOptions = z.object({
117
+ /**
118
+ * The name of the participant represented by the message.
119
+ *
120
+ * Supported on system, user, and assistant messages.
121
+ */
122
+ name: z.string().optional()
123
+ });
124
+ var moonshotaiAssistantMessageProviderOptions = moonshotaiMessageProviderOptions.extend({
125
+ /**
126
+ * Whether the assistant message content is a partial response that Moonshot
127
+ * should continue. Only supported on the final assistant message and cannot
128
+ * be combined with JSON object response format.
129
+ */
130
+ partial: z.literal(true).optional()
131
+ });
132
+ var moonshotaiDynamicToolSchema = z.object({
133
+ type: z.literal("function"),
134
+ name: z.string(),
135
+ description: z.string().optional(),
136
+ inputSchema: z.record(z.string(), z.unknown()),
137
+ strict: z.boolean().optional()
138
+ });
139
+ var moonshotaiAllMessageProviderOptions = moonshotaiAssistantMessageProviderOptions.extend({
140
+ /** Function tools to load at this point in a Kimi K3 conversation. */
141
+ tools: z.array(moonshotaiDynamicToolSchema).optional()
142
+ });
143
+
144
+ // src/moonshotai-prepare-tools.ts
145
+ import {
146
+ UnsupportedFunctionalityError as UnsupportedFunctionalityError2
147
+ } from "@ai-sdk/provider";
148
+
149
+ // src/normalize-json-schema-for-mfjs.ts
150
+ import { UnsupportedFunctionalityError } from "@ai-sdk/provider";
151
+ function isRecord(value) {
152
+ return typeof value === "object" && value !== null && !Array.isArray(value);
153
+ }
154
+ var SCHEMA_ARRAY_KEYS = ["allOf", "anyOf", "oneOf", "prefixItems"];
155
+ var SCHEMA_MAP_KEYS = [
156
+ "properties",
157
+ "patternProperties",
158
+ "$defs",
159
+ "dependentSchemas"
160
+ ];
161
+ var SCHEMA_SINGLE_KEYS = [
162
+ "additionalProperties",
163
+ "propertyNames",
164
+ "items",
165
+ "contains",
166
+ "not",
167
+ "if",
168
+ "then",
169
+ "else"
170
+ ];
171
+ function normalizeJsonSchemaForMFJS(schema) {
172
+ return normalizeDefinition(schema, true);
173
+ }
174
+ function normalizeDefinition(definition, isRoot) {
175
+ if (typeof definition === "boolean" || !isRecord(definition)) {
176
+ if (isRoot) {
177
+ throw new UnsupportedFunctionalityError({
178
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
179
+ });
180
+ }
181
+ return definition;
182
+ }
183
+ if (isRoot && definition.type !== "object") {
184
+ throw new UnsupportedFunctionalityError({
185
+ functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
186
+ });
187
+ }
188
+ const result = { ...definition };
189
+ if (Array.isArray(result.items)) {
190
+ const tuple = result.items;
191
+ result.prefixItems = [
192
+ ...Array.isArray(result.prefixItems) ? result.prefixItems : [],
193
+ ...tuple.map((item) => normalizeDefinition(item, false))
194
+ ];
195
+ delete result.items;
196
+ } else if (isRecord(result.items)) {
197
+ result.items = normalizeDefinition(result.items, false);
198
+ }
199
+ if (typeof result.type === "string" && Array.isArray(result.anyOf)) {
200
+ const parentType = result.type;
201
+ delete result.type;
202
+ result.anyOf = result.anyOf.map(
203
+ (branch) => isRecord(branch) && branch.type == null ? { type: parentType, ...branch } : branch
204
+ );
205
+ }
206
+ for (const key of SCHEMA_ARRAY_KEYS) {
207
+ const value = result[key];
208
+ if (Array.isArray(value)) {
209
+ result[key] = value.map((item) => normalizeDefinition(item, false));
210
+ }
211
+ }
212
+ for (const key of SCHEMA_MAP_KEYS) {
213
+ const value = result[key];
214
+ if (isRecord(value)) {
215
+ result[key] = Object.fromEntries(
216
+ Object.entries(value).map(([k, v]) => [
217
+ k,
218
+ normalizeDefinition(v, false)
219
+ ])
220
+ );
221
+ }
222
+ }
223
+ for (const key of SCHEMA_SINGLE_KEYS) {
224
+ const value = result[key];
225
+ if (isRecord(value) || typeof value === "boolean") {
226
+ result[key] = normalizeDefinition(value, false);
227
+ }
228
+ }
229
+ return result;
230
+ }
231
+
232
+ // src/moonshotai-prepare-tools.ts
233
+ function prepareTools({
234
+ tools,
235
+ toolChoice,
236
+ modelId
237
+ }) {
238
+ tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
239
+ const toolWarnings = [];
240
+ if (tools == null) {
241
+ return { tools: void 0, toolChoice: void 0, toolWarnings };
242
+ }
243
+ const moonshotTools = [];
244
+ for (const tool of tools) {
245
+ if (tool.type === "provider") {
246
+ toolWarnings.push({
247
+ type: "unsupported",
248
+ feature: `provider-defined tool ${tool.id}`
249
+ });
250
+ } else {
251
+ moonshotTools.push({
252
+ type: "function",
253
+ function: {
254
+ name: tool.name,
255
+ description: tool.description,
256
+ parameters: normalizeJsonSchemaForMFJS(tool.inputSchema),
257
+ ...tool.strict != null ? { strict: tool.strict } : {}
258
+ }
259
+ });
260
+ }
261
+ }
262
+ if (toolChoice == null) {
263
+ return { tools: moonshotTools, toolChoice: void 0, toolWarnings };
264
+ }
265
+ const type = toolChoice.type;
266
+ switch (type) {
267
+ case "auto":
268
+ case "none":
269
+ return { tools: moonshotTools, toolChoice: type, toolWarnings };
270
+ case "required":
271
+ if (modelId === "kimi-k2.6" || modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
272
+ toolWarnings.push({
273
+ type: "unsupported",
274
+ feature: `tool choice "required" for model "${modelId}"`,
275
+ details: 'Moonshot AI rejects required tool choice for this model. The setting has been omitted; use "auto" or select a specific tool instead.'
276
+ });
277
+ return {
278
+ tools: moonshotTools,
279
+ toolChoice: void 0,
280
+ toolWarnings
281
+ };
282
+ }
283
+ return { tools: moonshotTools, toolChoice: type, toolWarnings };
284
+ case "tool":
285
+ return {
286
+ tools: moonshotTools,
287
+ toolChoice: {
288
+ type: "function",
289
+ function: { name: toolChoice.toolName }
290
+ },
291
+ toolWarnings
292
+ };
293
+ default: {
294
+ const _exhaustiveCheck = type;
295
+ throw new UnsupportedFunctionalityError2({
296
+ functionality: `tool choice type: ${_exhaustiveCheck}`
297
+ });
298
+ }
299
+ }
300
+ }
301
+
302
+ // src/convert-to-moonshotai-chat-messages.ts
303
+ function parseMoonshotAIMessageProviderOptions({
304
+ providerOptions,
305
+ providerOptionsName
306
+ }) {
307
+ const value = providerOptions == null ? void 0 : providerOptions[providerOptionsName];
308
+ if (value == null) {
309
+ return void 0;
310
+ }
311
+ const result = moonshotaiAllMessageProviderOptions.safeParse(value);
312
+ if (!result.success) {
313
+ throw new InvalidArgumentError({
314
+ argument: "providerOptions",
315
+ message: `invalid ${providerOptionsName} provider options`,
316
+ cause: result.error
317
+ });
318
+ }
319
+ return result.data;
320
+ }
33
321
  var supportedImageMediaTypes = [
34
322
  "image/jpeg",
35
323
  "image/png",
@@ -57,26 +345,81 @@ function validateMediaType({
57
345
  }) {
58
346
  const normalizedMediaType = mediaType === `${topLevelMediaType}/*` ? topLevelMediaType === "image" ? "image/jpeg" : "video/mp4" : mediaType;
59
347
  if (!supportedMediaTypes.includes(normalizedMediaType)) {
60
- throw new UnsupportedFunctionalityError({
348
+ throw new UnsupportedFunctionalityError3({
61
349
  functionality: `file part media type ${normalizedMediaType}`
62
350
  });
63
351
  }
64
352
  return normalizedMediaType;
65
353
  }
66
- function convertToMoonshotAIChatMessages(prompt) {
67
- var _a;
354
+ function convertToMoonshotAIChatMessages({
355
+ modelId,
356
+ prompt,
357
+ providerOptionsName = "moonshotai",
358
+ responseFormat
359
+ }) {
360
+ var _a, _b;
68
361
  const messages = [];
69
- for (const { role, content } of prompt) {
362
+ const warnings = [];
363
+ const modelFamily = modelId == null ? "unknown" : getMoonshotAIModelFamily(modelId);
364
+ for (const [index, { role, content, providerOptions }] of prompt.entries()) {
365
+ const moonshotMessageOptions = parseMoonshotAIMessageProviderOptions({
366
+ providerOptions,
367
+ providerOptionsName
368
+ });
369
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true && role !== "assistant") {
370
+ throw new InvalidPromptError({
371
+ prompt,
372
+ message: "Moonshot AI Partial Mode requires `partial: true` on an assistant message."
373
+ });
374
+ }
375
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.tools) != null && role !== "system") {
376
+ throw new InvalidPromptError({
377
+ prompt,
378
+ message: "Moonshot dynamic tools must be configured on a system message."
379
+ });
380
+ }
70
381
  switch (role) {
71
382
  case "system": {
72
- messages.push({ role: "system", content });
383
+ if ((_a = moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.tools) == null ? void 0 : _a.length) {
384
+ if (content.length > 0) {
385
+ throw new InvalidPromptError({
386
+ prompt,
387
+ message: "A Moonshot dynamic-tool system message must use empty content because the API forbids content alongside tools."
388
+ });
389
+ }
390
+ if (modelFamily !== "kimi-k3" && modelFamily !== "unknown") {
391
+ warnings.push({
392
+ type: "unsupported",
393
+ feature: `dynamic tool loading for model "${modelId}"`,
394
+ details: "Moonshot documents dynamic tool loading only for Kimi K3. The dynamic system message has been omitted."
395
+ });
396
+ break;
397
+ }
398
+ const { tools, toolWarnings } = prepareTools({
399
+ modelId: modelId != null ? modelId : "custom-model",
400
+ tools: moonshotMessageOptions.tools
401
+ });
402
+ warnings.push(...toolWarnings);
403
+ messages.push({ role: "system", tools: tools != null ? tools : [] });
404
+ break;
405
+ }
406
+ messages.push({
407
+ role: "system",
408
+ content,
409
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
410
+ name: moonshotMessageOptions.name
411
+ }
412
+ });
73
413
  break;
74
414
  }
75
415
  case "user": {
76
416
  if (content.length === 1 && content[0].type === "text") {
77
417
  messages.push({
78
418
  role: "user",
79
- content: content[0].text
419
+ content: content[0].text,
420
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
421
+ name: moonshotMessageOptions.name
422
+ }
80
423
  });
81
424
  break;
82
425
  }
@@ -123,16 +466,33 @@ function convertToMoonshotAIChatMessages(prompt) {
123
466
  text: textContent
124
467
  };
125
468
  }
126
- throw new UnsupportedFunctionalityError({
469
+ throw new UnsupportedFunctionalityError3({
127
470
  functionality: `file part media type ${part.mediaType}`
128
471
  });
129
472
  }
130
473
  }
131
- })
474
+ }),
475
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
476
+ name: moonshotMessageOptions.name
477
+ }
132
478
  });
133
479
  break;
134
480
  }
135
481
  case "assistant": {
482
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true) {
483
+ if (index !== prompt.length - 1) {
484
+ throw new InvalidPromptError({
485
+ prompt,
486
+ message: "Moonshot AI Partial Mode requires the partial assistant message to be the final message."
487
+ });
488
+ }
489
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json_object") {
490
+ throw new InvalidPromptError({
491
+ prompt,
492
+ message: "Moonshot AI Partial Mode cannot be combined with JSON object response format."
493
+ });
494
+ }
495
+ }
136
496
  let text = "";
137
497
  let reasoning = "";
138
498
  const toolCalls = [];
@@ -162,12 +522,24 @@ function convertToMoonshotAIChatMessages(prompt) {
162
522
  messages.push({
163
523
  role: "assistant",
164
524
  content: toolCalls.length > 0 ? text || null : text,
525
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null && {
526
+ name: moonshotMessageOptions.name
527
+ },
528
+ ...(moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.partial) === true && {
529
+ partial: true
530
+ },
165
531
  ...reasoning.length > 0 ? { reasoning_content: reasoning } : {},
166
532
  tool_calls: toolCalls.length > 0 ? toolCalls : void 0
167
533
  });
168
534
  break;
169
535
  }
170
536
  case "tool": {
537
+ if ((moonshotMessageOptions == null ? void 0 : moonshotMessageOptions.name) != null) {
538
+ warnings.push({
539
+ type: "unsupported",
540
+ feature: "message name on tool messages"
541
+ });
542
+ }
171
543
  for (const toolResponse of content) {
172
544
  if (toolResponse.type === "tool-approval-response") {
173
545
  continue;
@@ -180,7 +552,7 @@ function convertToMoonshotAIChatMessages(prompt) {
180
552
  contentValue = output.value;
181
553
  break;
182
554
  case "execution-denied":
183
- contentValue = (_a = output.reason) != null ? _a : "Tool call execution denied.";
555
+ contentValue = (_b = output.reason) != null ? _b : "Tool call execution denied.";
184
556
  break;
185
557
  case "content":
186
558
  case "json":
@@ -202,7 +574,7 @@ function convertToMoonshotAIChatMessages(prompt) {
202
574
  }
203
575
  }
204
576
  }
205
- return messages;
577
+ return { messages, warnings };
206
578
  }
207
579
 
208
580
  // src/convert-moonshotai-chat-usage.ts
@@ -276,75 +648,99 @@ function mapMoonshotAIFinishReason(finishReason) {
276
648
 
277
649
  // src/moonshotai-chat-api-types.ts
278
650
  import { lazySchema, zodSchema } from "@ai-sdk/provider-utils";
279
- import { z } from "zod/v4";
280
- var tokenUsageSchema = z.object({
281
- prompt_tokens: z.number().nullish(),
282
- completion_tokens: z.number().nullish(),
283
- cached_tokens: z.number().nullish(),
284
- total_tokens: z.number().nullish(),
285
- prompt_tokens_details: z.object({
286
- cached_tokens: z.number().nullish()
651
+ import { z as z2 } from "zod/v4";
652
+ var tokenUsageSchema = z2.looseObject({
653
+ prompt_tokens: z2.number().nullish(),
654
+ completion_tokens: z2.number().nullish(),
655
+ cached_tokens: z2.number().nullish(),
656
+ total_tokens: z2.number().nullish(),
657
+ prompt_tokens_details: z2.looseObject({
658
+ cached_tokens: z2.number().nullish()
287
659
  }).nullish(),
288
- completion_tokens_details: z.object({
289
- reasoning_tokens: z.number().nullish()
660
+ completion_tokens_details: z2.looseObject({
661
+ reasoning_tokens: z2.number().nullish()
290
662
  }).nullish()
291
663
  }).nullish();
292
- var moonshotAIErrorSchema = z.object({
293
- error: z.object({
294
- message: z.string(),
295
- type: z.string().nullish()
664
+ var moonshotAIErrorSchema = z2.object({
665
+ error: z2.object({
666
+ message: z2.string(),
667
+ type: z2.string().nullish(),
668
+ code: z2.string().nullish()
296
669
  })
297
670
  });
298
- var moonshotAIChatResponseSchema = z.object({
299
- id: z.string().nullish(),
300
- created: z.number().nullish(),
301
- model: z.string().nullish(),
302
- choices: z.array(
303
- z.object({
304
- message: z.object({
305
- role: z.literal("assistant").nullish(),
306
- content: z.string().nullish(),
307
- reasoning_content: z.string().nullish(),
308
- tool_calls: z.array(
309
- z.object({
310
- id: z.string().nullish(),
311
- function: z.object({
312
- name: z.string(),
313
- arguments: z.string()
671
+ var moonshotAIChatLogprobSchema = z2.object({
672
+ token: z2.string(),
673
+ logprob: z2.number(),
674
+ bytes: z2.array(z2.number()).nullable(),
675
+ top_logprobs: z2.array(
676
+ z2.object({
677
+ token: z2.string(),
678
+ logprob: z2.number(),
679
+ bytes: z2.array(z2.number()).nullable()
680
+ })
681
+ )
682
+ });
683
+ var moonshotAIChatLogprobsSchema = z2.object({
684
+ content: z2.array(moonshotAIChatLogprobSchema).nullish()
685
+ }).nullish();
686
+ var moonshotAIChatResponseSchema = z2.object({
687
+ id: z2.string().nullish(),
688
+ created: z2.number().nullish(),
689
+ model: z2.string().nullish(),
690
+ object: z2.literal("chat.completion").nullish(),
691
+ choices: z2.array(
692
+ z2.object({
693
+ index: z2.number().nullish(),
694
+ message: z2.object({
695
+ role: z2.literal("assistant").nullish(),
696
+ content: z2.string().nullish(),
697
+ reasoning_content: z2.string().nullish(),
698
+ tool_calls: z2.array(
699
+ z2.object({
700
+ id: z2.string().nullish(),
701
+ type: z2.literal("function").nullish(),
702
+ function: z2.object({
703
+ name: z2.string(),
704
+ arguments: z2.string()
314
705
  })
315
706
  })
316
707
  ).nullish()
317
708
  }),
318
- finish_reason: z.string().nullish()
709
+ logprobs: moonshotAIChatLogprobsSchema,
710
+ finish_reason: z2.string().nullish()
319
711
  })
320
712
  ),
321
713
  usage: tokenUsageSchema
322
714
  });
323
715
  var moonshotAIChatChunkSchema = lazySchema(
324
716
  () => zodSchema(
325
- z.union([
326
- z.object({
327
- id: z.string().nullish(),
328
- created: z.number().nullish(),
329
- model: z.string().nullish(),
330
- choices: z.array(
331
- z.object({
332
- delta: z.object({
333
- role: z.literal("assistant").nullish(),
334
- content: z.string().nullish(),
335
- reasoning_content: z.string().nullish(),
336
- tool_calls: z.array(
337
- z.object({
338
- index: z.number().nullish(),
339
- id: z.string().nullish(),
340
- function: z.object({
341
- name: z.string().nullish(),
342
- arguments: z.string().nullish()
717
+ z2.union([
718
+ z2.object({
719
+ id: z2.string().nullish(),
720
+ created: z2.number().nullish(),
721
+ model: z2.string().nullish(),
722
+ object: z2.literal("chat.completion.chunk").nullish(),
723
+ choices: z2.array(
724
+ z2.object({
725
+ index: z2.number().nullish(),
726
+ delta: z2.object({
727
+ role: z2.literal("assistant").nullish(),
728
+ content: z2.string().nullish(),
729
+ reasoning_content: z2.string().nullish(),
730
+ tool_calls: z2.array(
731
+ z2.object({
732
+ index: z2.number().nullish(),
733
+ id: z2.string().nullish(),
734
+ type: z2.literal("function").nullish(),
735
+ function: z2.object({
736
+ name: z2.string().nullish(),
737
+ arguments: z2.string().nullish()
343
738
  })
344
739
  })
345
740
  ).nullish()
346
741
  }).nullish(),
347
- finish_reason: z.string().nullish(),
742
+ logprobs: moonshotAIChatLogprobsSchema,
743
+ finish_reason: z2.string().nullish(),
348
744
  usage: tokenUsageSchema
349
745
  })
350
746
  ),
@@ -355,207 +751,6 @@ var moonshotAIChatChunkSchema = lazySchema(
355
751
  )
356
752
  );
357
753
 
358
- // src/moonshotai-chat-options.ts
359
- import { z as z2 } from "zod/v4";
360
- function isMoonshotAIKimiModel(modelId) {
361
- return getMoonshotAIModelFamily(modelId).startsWith("kimi-");
362
- }
363
- function getMoonshotAIModelFamily(modelId) {
364
- if (modelId === "kimi-k2.5") return "kimi-k2.5";
365
- if (modelId === "kimi-k2.6") return "kimi-k2.6";
366
- if (modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
367
- return "kimi-k2.7";
368
- }
369
- if (modelId === "kimi-k3") return "kimi-k3";
370
- if (modelId.startsWith("moonshot-v1-")) return "moonshot-v1";
371
- return "unknown";
372
- }
373
- var moonshotaiLanguageModelOptions = z2.object({
374
- /**
375
- * Whether to use strict JSON schema validation for structured outputs.
376
- *
377
- * @default true
378
- */
379
- strictJsonSchema: z2.boolean().optional(),
380
- /**
381
- * Reasoning effort for Kimi K3.
382
- */
383
- reasoningEffort: z2.enum(["low", "high", "max"]).optional(),
384
- thinking: z2.object({
385
- type: z2.enum(["enabled", "disabled"]).optional(),
386
- // Accepted so existing callers receive a migration warning. It remains
387
- // in the public compatibility type below as a deprecated property.
388
- budgetTokens: z2.number().int().min(1024).optional()
389
- }).optional(),
390
- reasoningHistory: z2.enum(["disabled", "interleaved", "preserved"]).optional(),
391
- /**
392
- * Used to cache responses for similar requests to optimize cache hit rates.
393
- * Typically a session or task id.
394
- */
395
- promptCacheKey: z2.string().optional(),
396
- /**
397
- * A stable identifier used to help Moonshot detect users violating usage
398
- * policies. Recommended to hash the username or email address.
399
- */
400
- safetyIdentifier: z2.string().optional()
401
- });
402
-
403
- // src/normalize-json-schema-for-mfjs.ts
404
- import { UnsupportedFunctionalityError as UnsupportedFunctionalityError2 } from "@ai-sdk/provider";
405
- function isRecord(value) {
406
- return typeof value === "object" && value !== null && !Array.isArray(value);
407
- }
408
- var SCHEMA_ARRAY_KEYS = ["allOf", "anyOf", "oneOf", "prefixItems"];
409
- var SCHEMA_MAP_KEYS = [
410
- "properties",
411
- "patternProperties",
412
- "$defs",
413
- "dependentSchemas"
414
- ];
415
- var SCHEMA_SINGLE_KEYS = [
416
- "additionalProperties",
417
- "propertyNames",
418
- "items",
419
- "contains",
420
- "not",
421
- "if",
422
- "then",
423
- "else"
424
- ];
425
- function normalizeJsonSchemaForMFJS(schema) {
426
- return normalizeDefinition(schema, true);
427
- }
428
- function normalizeDefinition(definition, isRoot) {
429
- if (typeof definition === "boolean" || !isRecord(definition)) {
430
- if (isRoot) {
431
- throw new UnsupportedFunctionalityError2({
432
- functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
433
- });
434
- }
435
- return definition;
436
- }
437
- if (isRoot && definition.type !== "object") {
438
- throw new UnsupportedFunctionalityError2({
439
- functionality: 'tool parameters must be a JSON Schema object with type "object" for moonshotai (MFJS)'
440
- });
441
- }
442
- const result = { ...definition };
443
- if (Array.isArray(result.items)) {
444
- const tuple = result.items;
445
- result.prefixItems = [
446
- ...Array.isArray(result.prefixItems) ? result.prefixItems : [],
447
- ...tuple.map((item) => normalizeDefinition(item, false))
448
- ];
449
- delete result.items;
450
- } else if (isRecord(result.items)) {
451
- result.items = normalizeDefinition(result.items, false);
452
- }
453
- if (typeof result.type === "string" && Array.isArray(result.anyOf)) {
454
- const parentType = result.type;
455
- delete result.type;
456
- result.anyOf = result.anyOf.map(
457
- (branch) => isRecord(branch) && branch.type == null ? { type: parentType, ...branch } : branch
458
- );
459
- }
460
- for (const key of SCHEMA_ARRAY_KEYS) {
461
- const value = result[key];
462
- if (Array.isArray(value)) {
463
- result[key] = value.map((item) => normalizeDefinition(item, false));
464
- }
465
- }
466
- for (const key of SCHEMA_MAP_KEYS) {
467
- const value = result[key];
468
- if (isRecord(value)) {
469
- result[key] = Object.fromEntries(
470
- Object.entries(value).map(([k, v]) => [
471
- k,
472
- normalizeDefinition(v, false)
473
- ])
474
- );
475
- }
476
- }
477
- for (const key of SCHEMA_SINGLE_KEYS) {
478
- const value = result[key];
479
- if (isRecord(value) || typeof value === "boolean") {
480
- result[key] = normalizeDefinition(value, false);
481
- }
482
- }
483
- return result;
484
- }
485
-
486
- // src/moonshotai-prepare-tools.ts
487
- import {
488
- UnsupportedFunctionalityError as UnsupportedFunctionalityError3
489
- } from "@ai-sdk/provider";
490
- function prepareTools({
491
- tools,
492
- toolChoice,
493
- modelId
494
- }) {
495
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
496
- const toolWarnings = [];
497
- if (tools == null) {
498
- return { tools: void 0, toolChoice: void 0, toolWarnings };
499
- }
500
- const moonshotTools = [];
501
- for (const tool of tools) {
502
- if (tool.type === "provider") {
503
- toolWarnings.push({
504
- type: "unsupported",
505
- feature: `provider-defined tool ${tool.id}`
506
- });
507
- } else {
508
- moonshotTools.push({
509
- type: "function",
510
- function: {
511
- name: tool.name,
512
- description: tool.description,
513
- parameters: normalizeJsonSchemaForMFJS(tool.inputSchema),
514
- ...tool.strict != null ? { strict: tool.strict } : {}
515
- }
516
- });
517
- }
518
- }
519
- if (toolChoice == null) {
520
- return { tools: moonshotTools, toolChoice: void 0, toolWarnings };
521
- }
522
- const type = toolChoice.type;
523
- switch (type) {
524
- case "auto":
525
- case "none":
526
- return { tools: moonshotTools, toolChoice: type, toolWarnings };
527
- case "required":
528
- if (modelId === "kimi-k2.6" || modelId === "kimi-k2.7-code" || modelId === "kimi-k2.7-code-highspeed") {
529
- toolWarnings.push({
530
- type: "unsupported",
531
- feature: `tool choice "required" for model "${modelId}"`,
532
- details: 'Moonshot AI rejects required tool choice for this model. The setting has been omitted; use "auto" or select a specific tool instead.'
533
- });
534
- return {
535
- tools: moonshotTools,
536
- toolChoice: void 0,
537
- toolWarnings
538
- };
539
- }
540
- return { tools: moonshotTools, toolChoice: type, toolWarnings };
541
- case "tool":
542
- return {
543
- tools: moonshotTools,
544
- toolChoice: {
545
- type: "function",
546
- function: { name: toolChoice.toolName }
547
- },
548
- toolWarnings
549
- };
550
- default: {
551
- const _exhaustiveCheck = type;
552
- throw new UnsupportedFunctionalityError3({
553
- functionality: `tool choice type: ${_exhaustiveCheck}`
554
- });
555
- }
556
- }
557
- }
558
-
559
754
  // src/moonshotai-chat-language-model.ts
560
755
  var MoonshotAIChatLanguageModel = class {
561
756
  constructor(modelId, config) {
@@ -601,7 +796,6 @@ var MoonshotAIChatLanguageModel = class {
601
796
  providerOptions,
602
797
  schema: moonshotaiLanguageModelOptions
603
798
  })) != null ? _a : {};
604
- const messages = convertToMoonshotAIChatMessages(prompt);
605
799
  const allWarnings = [];
606
800
  if (topK != null) {
607
801
  allWarnings.push({ type: "unsupported", feature: "topK" });
@@ -761,9 +955,20 @@ var MoonshotAIChatLanguageModel = class {
761
955
  response_format = { type: "json_object" };
762
956
  }
763
957
  }
958
+ const { messages, warnings: messageWarnings } = convertToMoonshotAIChatMessages({
959
+ modelId: this.modelId,
960
+ prompt,
961
+ providerOptionsName: this.providerOptionsName,
962
+ responseFormat: response_format
963
+ });
964
+ allWarnings.push(...messageWarnings);
764
965
  return {
765
966
  args: {
766
967
  model: this.modelId,
968
+ ...(moonshotOptions.logprobs === true || moonshotOptions.topLogprobs != null) && { logprobs: true },
969
+ ...moonshotOptions.topLogprobs != null && {
970
+ top_logprobs: moonshotOptions.topLogprobs
971
+ },
767
972
  max_completion_tokens: maxOutputTokens,
768
973
  temperature: supportsSamplingOptions ? temperature : void 0,
769
974
  top_p: supportsSamplingOptions ? topP : void 0,
@@ -774,6 +979,9 @@ var MoonshotAIChatLanguageModel = class {
774
979
  messages,
775
980
  tools: moonshotTools,
776
981
  tool_choice: moonshotToolChoice,
982
+ ...moonshotOptions.prediction != null && {
983
+ prediction: moonshotOptions.prediction
984
+ },
777
985
  ...thinking != null ? { thinking } : {},
778
986
  ...reasoningEffort != null && {
779
987
  reasoning_effort: reasoningEffort
@@ -836,6 +1044,21 @@ var MoonshotAIChatLanguageModel = class {
836
1044
  raw: (_e = choice.finish_reason) != null ? _e : void 0
837
1045
  },
838
1046
  usage: convertMoonshotAIChatUsage(responseBody.usage),
1047
+ providerMetadata: {
1048
+ [this.providerOptionsName]: {
1049
+ ...responseBody.object != null && {
1050
+ responseObject: responseBody.object
1051
+ },
1052
+ ...choice.index != null && { choiceIndex: choice.index },
1053
+ ...choice.message.role != null && {
1054
+ messageRole: choice.message.role
1055
+ },
1056
+ ...choice.message.tool_calls != null && {
1057
+ toolCallTypes: choice.message.tool_calls.map((toolCall) => toolCall.type).filter((type) => type != null)
1058
+ },
1059
+ ...choice.logprobs != null && { logprobs: choice.logprobs }
1060
+ }
1061
+ },
839
1062
  request: { body: args },
840
1063
  response: {
841
1064
  ...getResponseMetadata(responseBody),
@@ -876,9 +1099,15 @@ var MoonshotAIChatLanguageModel = class {
876
1099
  };
877
1100
  let topLevelUsage = void 0;
878
1101
  let choiceUsage = void 0;
1102
+ const contentLogprobs = [];
1103
+ const providerOptionsName = this.providerOptionsName;
879
1104
  let isFirstChunk = true;
880
1105
  let isActiveReasoning = false;
881
1106
  let isActiveText = false;
1107
+ let responseObject;
1108
+ let choiceIndex;
1109
+ let messageRole;
1110
+ const toolCallTypes = /* @__PURE__ */ new Map();
882
1111
  return {
883
1112
  stream: response.pipeThrough(
884
1113
  new TransformStream({
@@ -886,7 +1115,7 @@ var MoonshotAIChatLanguageModel = class {
886
1115
  controller.enqueue({ type: "stream-start", warnings });
887
1116
  },
888
1117
  transform(chunk, controller) {
889
- var _a2, _b2, _c, _d, _e, _f, _g;
1118
+ var _a2, _b2, _c, _d, _e, _f, _g, _h;
890
1119
  if (options.includeRawChunks) {
891
1120
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
892
1121
  }
@@ -898,7 +1127,7 @@ var MoonshotAIChatLanguageModel = class {
898
1127
  const value = chunk.value;
899
1128
  if ("error" in value) {
900
1129
  finishReason = { unified: "error", raw: void 0 };
901
- controller.enqueue({ type: "error", error: value.error.message });
1130
+ controller.enqueue({ type: "error", error: value.error });
902
1131
  return;
903
1132
  }
904
1133
  if (isFirstChunk) {
@@ -911,20 +1140,32 @@ var MoonshotAIChatLanguageModel = class {
911
1140
  if (value.usage != null) {
912
1141
  topLevelUsage = value.usage;
913
1142
  }
1143
+ if (value.object != null) {
1144
+ responseObject = value.object;
1145
+ }
914
1146
  const choice = value.choices[0];
915
1147
  if ((choice == null ? void 0 : choice.usage) != null) {
916
1148
  choiceUsage = choice.usage;
917
1149
  }
1150
+ if ((choice == null ? void 0 : choice.index) != null) {
1151
+ choiceIndex = choice.index;
1152
+ }
918
1153
  if ((choice == null ? void 0 : choice.finish_reason) != null) {
919
1154
  finishReason = {
920
1155
  unified: mapMoonshotAIFinishReason(choice.finish_reason),
921
1156
  raw: choice.finish_reason
922
1157
  };
923
1158
  }
1159
+ if (((_a2 = choice == null ? void 0 : choice.logprobs) == null ? void 0 : _a2.content) != null) {
1160
+ contentLogprobs.push(...choice.logprobs.content);
1161
+ }
924
1162
  if ((choice == null ? void 0 : choice.delta) == null) {
925
1163
  return;
926
1164
  }
927
1165
  const delta = choice.delta;
1166
+ if (delta.role != null) {
1167
+ messageRole = delta.role;
1168
+ }
928
1169
  const reasoningContent = delta.reasoning_content;
929
1170
  if (reasoningContent) {
930
1171
  if (!isActiveReasoning) {
@@ -970,7 +1211,10 @@ var MoonshotAIChatLanguageModel = class {
970
1211
  fallbackIndex,
971
1212
  toolCallDelta
972
1213
  ] of delta.tool_calls.entries()) {
973
- const index = (_a2 = toolCallDelta.index) != null ? _a2 : fallbackIndex;
1214
+ const index = (_b2 = toolCallDelta.index) != null ? _b2 : fallbackIndex;
1215
+ if (toolCallDelta.type != null) {
1216
+ toolCallTypes.set(index, toolCallDelta.type);
1217
+ }
974
1218
  if (toolCalls[index] == null) {
975
1219
  if (toolCallDelta.id == null) {
976
1220
  throw new InvalidResponseDataError({
@@ -978,7 +1222,7 @@ var MoonshotAIChatLanguageModel = class {
978
1222
  message: `Expected 'id' to be a string.`
979
1223
  });
980
1224
  }
981
- if (((_b2 = toolCallDelta.function) == null ? void 0 : _b2.name) == null) {
1225
+ if (((_c = toolCallDelta.function) == null ? void 0 : _c.name) == null) {
982
1226
  throw new InvalidResponseDataError({
983
1227
  data: toolCallDelta,
984
1228
  message: `Expected 'function.name' to be a string.`
@@ -994,12 +1238,12 @@ var MoonshotAIChatLanguageModel = class {
994
1238
  type: "function",
995
1239
  function: {
996
1240
  name: toolCallDelta.function.name,
997
- arguments: (_c = toolCallDelta.function.arguments) != null ? _c : ""
1241
+ arguments: (_d = toolCallDelta.function.arguments) != null ? _d : ""
998
1242
  },
999
1243
  hasFinished: false
1000
1244
  };
1001
1245
  const toolCall2 = toolCalls[index];
1002
- if (((_d = toolCall2.function) == null ? void 0 : _d.name) != null && ((_e = toolCall2.function) == null ? void 0 : _e.arguments) != null && toolCall2.function.arguments.length > 0) {
1246
+ if (((_e = toolCall2.function) == null ? void 0 : _e.name) != null && ((_f = toolCall2.function) == null ? void 0 : _f.arguments) != null && toolCall2.function.arguments.length > 0) {
1003
1247
  controller.enqueue({
1004
1248
  type: "tool-input-delta",
1005
1249
  id: toolCall2.id,
@@ -1012,13 +1256,13 @@ var MoonshotAIChatLanguageModel = class {
1012
1256
  if (toolCall.hasFinished) {
1013
1257
  continue;
1014
1258
  }
1015
- if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) {
1259
+ if (((_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null) {
1016
1260
  toolCall.function.arguments += toolCallDelta.function.arguments;
1017
1261
  }
1018
1262
  controller.enqueue({
1019
1263
  type: "tool-input-delta",
1020
1264
  id: toolCall.id,
1021
- delta: (_g = toolCallDelta.function.arguments) != null ? _g : ""
1265
+ delta: (_h = toolCallDelta.function.arguments) != null ? _h : ""
1022
1266
  });
1023
1267
  }
1024
1268
  }
@@ -1047,7 +1291,22 @@ var MoonshotAIChatLanguageModel = class {
1047
1291
  controller.enqueue({
1048
1292
  type: "finish",
1049
1293
  finishReason,
1050
- usage: convertMoonshotAIChatUsage(topLevelUsage != null ? topLevelUsage : choiceUsage)
1294
+ usage: convertMoonshotAIChatUsage(topLevelUsage != null ? topLevelUsage : choiceUsage),
1295
+ providerMetadata: {
1296
+ [providerOptionsName]: {
1297
+ ...responseObject != null && { responseObject },
1298
+ ...choiceIndex != null && { choiceIndex },
1299
+ ...messageRole != null && { messageRole },
1300
+ ...toolCallTypes.size > 0 && {
1301
+ toolCallTypes: [...toolCallTypes.entries()].sort(([left], [right]) => left - right).map(([, type]) => type)
1302
+ },
1303
+ ...contentLogprobs.length > 0 && {
1304
+ logprobs: {
1305
+ content: contentLogprobs
1306
+ }
1307
+ }
1308
+ }
1309
+ }
1051
1310
  });
1052
1311
  }
1053
1312
  })
@@ -1059,7 +1318,7 @@ var MoonshotAIChatLanguageModel = class {
1059
1318
  };
1060
1319
 
1061
1320
  // src/version.ts
1062
- var VERSION = true ? "2.0.51" : "0.0.0-test";
1321
+ var VERSION = true ? "2.0.54" : "0.0.0-test";
1063
1322
 
1064
1323
  // src/moonshotai-provider.ts
1065
1324
  var defaultBaseURL = "https://api.moonshot.ai/v1";