@mastra/core 1.0.0-beta.0 → 1.0.0-beta.2

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 (100) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/agent/index.cjs +6 -6
  3. package/dist/agent/index.js +1 -1
  4. package/dist/{chunk-QCQLOMJM.cjs → chunk-22443P6A.cjs} +22 -21
  5. package/dist/chunk-22443P6A.cjs.map +1 -0
  6. package/dist/{chunk-YIK3ASEG.cjs → chunk-2ZVKF4HP.cjs} +117 -42
  7. package/dist/chunk-2ZVKF4HP.cjs.map +1 -0
  8. package/dist/{chunk-26SQQNMU.js → chunk-7CBEP2ZQ.js} +36 -12
  9. package/dist/chunk-7CBEP2ZQ.js.map +1 -0
  10. package/dist/{chunk-7SKXKUYT.js → chunk-7PO6SEJF.js} +6 -3
  11. package/dist/chunk-7PO6SEJF.js.map +1 -0
  12. package/dist/{chunk-S5MJLXMG.cjs → chunk-CB575O6L.cjs} +10 -2
  13. package/dist/chunk-CB575O6L.cjs.map +1 -0
  14. package/dist/chunk-HDJFSJCK.js +2237 -0
  15. package/dist/chunk-HDJFSJCK.js.map +1 -0
  16. package/dist/{chunk-BU4IAJWF.js → chunk-I4CXL4SR.js} +3 -3
  17. package/dist/{chunk-BU4IAJWF.js.map → chunk-I4CXL4SR.js.map} +1 -1
  18. package/dist/{chunk-VV753WCB.cjs → chunk-IQO7ANVS.cjs} +8 -8
  19. package/dist/{chunk-VV753WCB.cjs.map → chunk-IQO7ANVS.cjs.map} +1 -1
  20. package/dist/{chunk-L7XKOKOW.js → chunk-JPGVRWWL.js} +3 -3
  21. package/dist/chunk-JPGVRWWL.js.map +1 -0
  22. package/dist/{chunk-BXOL277H.cjs → chunk-JYYQQEBH.cjs} +7 -4
  23. package/dist/chunk-JYYQQEBH.cjs.map +1 -0
  24. package/dist/chunk-LWBQ4P4N.cjs +2240 -0
  25. package/dist/chunk-LWBQ4P4N.cjs.map +1 -0
  26. package/dist/{chunk-VJUZZB2I.js → chunk-SNPVZPLB.js} +4 -4
  27. package/dist/{chunk-VJUZZB2I.js.map → chunk-SNPVZPLB.js.map} +1 -1
  28. package/dist/{chunk-32CTMD2C.js → chunk-W7UH2PWL.js} +108 -33
  29. package/dist/chunk-W7UH2PWL.js.map +1 -0
  30. package/dist/{chunk-FD734TPS.cjs → chunk-YCVEJ3UN.cjs} +37 -13
  31. package/dist/chunk-YCVEJ3UN.cjs.map +1 -0
  32. package/dist/{chunk-P6APHXPZ.js → chunk-ZGHTOYHW.js} +5 -4
  33. package/dist/chunk-ZGHTOYHW.js.map +1 -0
  34. package/dist/{chunk-QUZGDSWE.cjs → chunk-ZWNI5IWX.cjs} +11 -11
  35. package/dist/{chunk-QUZGDSWE.cjs.map → chunk-ZWNI5IWX.cjs.map} +1 -1
  36. package/dist/evals/index.cjs +4 -4
  37. package/dist/evals/index.js +1 -1
  38. package/dist/evals/scoreTraces/index.cjs +3 -3
  39. package/dist/evals/scoreTraces/index.js +1 -1
  40. package/dist/index.cjs +2 -2
  41. package/dist/index.js +1 -1
  42. package/dist/llm/index.cjs +7 -7
  43. package/dist/llm/index.js +1 -1
  44. package/dist/llm/model/gateways/constants.d.ts.map +1 -1
  45. package/dist/llm/model/gateways/models-dev.d.ts.map +1 -1
  46. package/dist/llm/model/provider-types.generated.d.ts +48 -10
  47. package/dist/loop/index.cjs +2 -2
  48. package/dist/loop/index.js +1 -1
  49. package/dist/mastra/index.cjs +2 -2
  50. package/dist/mastra/index.d.ts.map +1 -1
  51. package/dist/mastra/index.js +1 -1
  52. package/dist/memory/index.cjs +2 -2
  53. package/dist/memory/index.js +1 -1
  54. package/dist/models-dev-DNBKXHT4.js +3 -0
  55. package/dist/{models-dev-7U4NRMM3.js.map → models-dev-DNBKXHT4.js.map} +1 -1
  56. package/dist/models-dev-YBEEQIX6.cjs +12 -0
  57. package/dist/{models-dev-VKSAQPRK.cjs.map → models-dev-YBEEQIX6.cjs.map} +1 -1
  58. package/dist/netlify-7G2L5VSH.js +3 -0
  59. package/dist/{netlify-42ZNWIDQ.js.map → netlify-7G2L5VSH.js.map} +1 -1
  60. package/dist/netlify-GWNGSIRZ.cjs +12 -0
  61. package/dist/{netlify-2IDXTNFW.cjs.map → netlify-GWNGSIRZ.cjs.map} +1 -1
  62. package/dist/processors/index.cjs +11 -11
  63. package/dist/processors/index.js +1 -1
  64. package/dist/provider-registry.json +101 -26
  65. package/dist/relevance/index.cjs +2 -2
  66. package/dist/relevance/index.js +1 -1
  67. package/dist/stream/index.cjs +8 -8
  68. package/dist/stream/index.js +1 -1
  69. package/dist/workflows/default.d.ts.map +1 -1
  70. package/dist/workflows/evented/index.cjs +10 -10
  71. package/dist/workflows/evented/index.js +1 -1
  72. package/dist/workflows/evented/step-executor.d.ts.map +1 -1
  73. package/dist/workflows/index.cjs +16 -16
  74. package/dist/workflows/index.js +1 -1
  75. package/dist/workflows/step.d.ts +1 -1
  76. package/dist/workflows/step.d.ts.map +1 -1
  77. package/dist/workflows/types.d.ts +11 -5
  78. package/dist/workflows/types.d.ts.map +1 -1
  79. package/dist/workflows/workflow.d.ts +1 -0
  80. package/dist/workflows/workflow.d.ts.map +1 -1
  81. package/package.json +5 -4
  82. package/src/llm/model/provider-types.generated.d.ts +48 -10
  83. package/dist/chunk-26SQQNMU.js.map +0 -1
  84. package/dist/chunk-32CTMD2C.js.map +0 -1
  85. package/dist/chunk-7SKXKUYT.js.map +0 -1
  86. package/dist/chunk-BNBRQS7N.js +0 -910
  87. package/dist/chunk-BNBRQS7N.js.map +0 -1
  88. package/dist/chunk-BXOL277H.cjs.map +0 -1
  89. package/dist/chunk-FD734TPS.cjs.map +0 -1
  90. package/dist/chunk-IU2SZXJQ.cjs +0 -913
  91. package/dist/chunk-IU2SZXJQ.cjs.map +0 -1
  92. package/dist/chunk-L7XKOKOW.js.map +0 -1
  93. package/dist/chunk-P6APHXPZ.js.map +0 -1
  94. package/dist/chunk-QCQLOMJM.cjs.map +0 -1
  95. package/dist/chunk-S5MJLXMG.cjs.map +0 -1
  96. package/dist/chunk-YIK3ASEG.cjs.map +0 -1
  97. package/dist/models-dev-7U4NRMM3.js +0 -3
  98. package/dist/models-dev-VKSAQPRK.cjs +0 -12
  99. package/dist/netlify-2IDXTNFW.cjs +0 -12
  100. package/dist/netlify-42ZNWIDQ.js +0 -3
@@ -1,913 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkS5MJLXMG_cjs = require('./chunk-S5MJLXMG.cjs');
4
- var v4 = require('zod/v4');
5
- var aiSdkProviderV5 = require('@openrouter/ai-sdk-provider-v5');
6
-
7
- function convertToXaiChatMessages(prompt) {
8
- const messages = [];
9
- const warnings = [];
10
- for (const { role, content } of prompt) {
11
- switch (role) {
12
- case "system": {
13
- messages.push({ role: "system", content });
14
- break;
15
- }
16
- case "user": {
17
- if (content.length === 1 && content[0].type === "text") {
18
- messages.push({ role: "user", content: content[0].text });
19
- break;
20
- }
21
- messages.push({
22
- role: "user",
23
- content: content.map((part) => {
24
- switch (part.type) {
25
- case "text": {
26
- return { type: "text", text: part.text };
27
- }
28
- case "file": {
29
- if (part.mediaType.startsWith("image/")) {
30
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
31
- return {
32
- type: "image_url",
33
- image_url: {
34
- url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${chunkS5MJLXMG_cjs.convertToBase64(part.data)}`
35
- }
36
- };
37
- } else {
38
- throw new chunkS5MJLXMG_cjs.UnsupportedFunctionalityError({
39
- functionality: `file part media type ${part.mediaType}`
40
- });
41
- }
42
- }
43
- }
44
- })
45
- });
46
- break;
47
- }
48
- case "assistant": {
49
- let text = "";
50
- const toolCalls = [];
51
- for (const part of content) {
52
- switch (part.type) {
53
- case "text": {
54
- text += part.text;
55
- break;
56
- }
57
- case "tool-call": {
58
- toolCalls.push({
59
- id: part.toolCallId,
60
- type: "function",
61
- function: {
62
- name: part.toolName,
63
- arguments: JSON.stringify(part.input)
64
- }
65
- });
66
- break;
67
- }
68
- }
69
- }
70
- messages.push({
71
- role: "assistant",
72
- content: text,
73
- tool_calls: toolCalls.length > 0 ? toolCalls : void 0
74
- });
75
- break;
76
- }
77
- case "tool": {
78
- for (const toolResponse of content) {
79
- const output = toolResponse.output;
80
- let contentValue;
81
- switch (output.type) {
82
- case "text":
83
- case "error-text":
84
- contentValue = output.value;
85
- break;
86
- case "content":
87
- case "json":
88
- case "error-json":
89
- contentValue = JSON.stringify(output.value);
90
- break;
91
- }
92
- messages.push({
93
- role: "tool",
94
- tool_call_id: toolResponse.toolCallId,
95
- content: contentValue
96
- });
97
- }
98
- break;
99
- }
100
- default: {
101
- const _exhaustiveCheck = role;
102
- throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
103
- }
104
- }
105
- }
106
- return { messages, warnings };
107
- }
108
- function getResponseMetadata({
109
- id,
110
- model,
111
- created
112
- }) {
113
- return {
114
- id: id != null ? id : void 0,
115
- modelId: model != null ? model : void 0,
116
- timestamp: created != null ? new Date(created * 1e3) : void 0
117
- };
118
- }
119
- function mapXaiFinishReason(finishReason) {
120
- switch (finishReason) {
121
- case "stop":
122
- return "stop";
123
- case "length":
124
- return "length";
125
- case "tool_calls":
126
- case "function_call":
127
- return "tool-calls";
128
- case "content_filter":
129
- return "content-filter";
130
- default:
131
- return "unknown";
132
- }
133
- }
134
- var webSourceSchema = v4.z.object({
135
- type: v4.z.literal("web"),
136
- country: v4.z.string().length(2).optional(),
137
- excludedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
138
- allowedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
139
- safeSearch: v4.z.boolean().optional()
140
- });
141
- var xSourceSchema = v4.z.object({
142
- type: v4.z.literal("x"),
143
- excludedXHandles: v4.z.array(v4.z.string()).optional(),
144
- includedXHandles: v4.z.array(v4.z.string()).optional(),
145
- postFavoriteCount: v4.z.number().int().optional(),
146
- postViewCount: v4.z.number().int().optional(),
147
- /**
148
- * @deprecated use `includedXHandles` instead
149
- */
150
- xHandles: v4.z.array(v4.z.string()).optional()
151
- });
152
- var newsSourceSchema = v4.z.object({
153
- type: v4.z.literal("news"),
154
- country: v4.z.string().length(2).optional(),
155
- excludedWebsites: v4.z.array(v4.z.string()).max(5).optional(),
156
- safeSearch: v4.z.boolean().optional()
157
- });
158
- var rssSourceSchema = v4.z.object({
159
- type: v4.z.literal("rss"),
160
- links: v4.z.array(v4.z.string().url()).max(1)
161
- // currently only supports one RSS link
162
- });
163
- var searchSourceSchema = v4.z.discriminatedUnion("type", [
164
- webSourceSchema,
165
- xSourceSchema,
166
- newsSourceSchema,
167
- rssSourceSchema
168
- ]);
169
- var xaiProviderOptions = v4.z.object({
170
- reasoningEffort: v4.z.enum(["low", "high"]).optional(),
171
- searchParameters: v4.z.object({
172
- /**
173
- * search mode preference
174
- * - "off": disables search completely
175
- * - "auto": model decides whether to search (default)
176
- * - "on": always enables search
177
- */
178
- mode: v4.z.enum(["off", "auto", "on"]),
179
- /**
180
- * whether to return citations in the response
181
- * defaults to true
182
- */
183
- returnCitations: v4.z.boolean().optional(),
184
- /**
185
- * start date for search data (ISO8601 format: YYYY-MM-DD)
186
- */
187
- fromDate: v4.z.string().optional(),
188
- /**
189
- * end date for search data (ISO8601 format: YYYY-MM-DD)
190
- */
191
- toDate: v4.z.string().optional(),
192
- /**
193
- * maximum number of search results to consider
194
- * defaults to 20
195
- */
196
- maxSearchResults: v4.z.number().min(1).max(50).optional(),
197
- /**
198
- * data sources to search from
199
- * defaults to ["web", "x"] if not specified
200
- */
201
- sources: v4.z.array(searchSourceSchema).optional()
202
- }).optional()
203
- });
204
- var xaiErrorDataSchema = v4.z.object({
205
- error: v4.z.object({
206
- message: v4.z.string(),
207
- type: v4.z.string().nullish(),
208
- param: v4.z.any().nullish(),
209
- code: v4.z.union([v4.z.string(), v4.z.number()]).nullish()
210
- })
211
- });
212
- var xaiFailedResponseHandler = chunkS5MJLXMG_cjs.createJsonErrorResponseHandler({
213
- errorSchema: xaiErrorDataSchema,
214
- errorToMessage: (data) => data.error.message
215
- });
216
- function prepareTools({
217
- tools,
218
- toolChoice
219
- }) {
220
- tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
221
- const toolWarnings = [];
222
- if (tools == null) {
223
- return { tools: void 0, toolChoice: void 0, toolWarnings };
224
- }
225
- const xaiTools = [];
226
- for (const tool of tools) {
227
- if (tool.type === "provider-defined") {
228
- toolWarnings.push({ type: "unsupported-tool", tool });
229
- } else {
230
- xaiTools.push({
231
- type: "function",
232
- function: {
233
- name: tool.name,
234
- description: tool.description,
235
- parameters: tool.inputSchema
236
- }
237
- });
238
- }
239
- }
240
- if (toolChoice == null) {
241
- return { tools: xaiTools, toolChoice: void 0, toolWarnings };
242
- }
243
- const type = toolChoice.type;
244
- switch (type) {
245
- case "auto":
246
- case "none":
247
- return { tools: xaiTools, toolChoice: type, toolWarnings };
248
- case "required":
249
- return { tools: xaiTools, toolChoice: "required", toolWarnings };
250
- case "tool":
251
- return {
252
- tools: xaiTools,
253
- toolChoice: {
254
- type: "function",
255
- function: { name: toolChoice.toolName }
256
- },
257
- toolWarnings
258
- };
259
- default: {
260
- const _exhaustiveCheck = type;
261
- throw new chunkS5MJLXMG_cjs.UnsupportedFunctionalityError({
262
- functionality: `tool choice type: ${_exhaustiveCheck}`
263
- });
264
- }
265
- }
266
- }
267
- var XaiChatLanguageModel = class {
268
- constructor(modelId, config) {
269
- this.specificationVersion = "v2";
270
- this.supportedUrls = {
271
- "image/*": [/^https?:\/\/.*$/]
272
- };
273
- this.modelId = modelId;
274
- this.config = config;
275
- }
276
- get provider() {
277
- return this.config.provider;
278
- }
279
- async getArgs({
280
- prompt,
281
- maxOutputTokens,
282
- temperature,
283
- topP,
284
- topK,
285
- frequencyPenalty,
286
- presencePenalty,
287
- stopSequences,
288
- seed,
289
- responseFormat,
290
- providerOptions,
291
- tools,
292
- toolChoice
293
- }) {
294
- var _a, _b, _c;
295
- const warnings = [];
296
- const options = (_a = await chunkS5MJLXMG_cjs.parseProviderOptions({
297
- provider: "xai",
298
- providerOptions,
299
- schema: xaiProviderOptions
300
- })) != null ? _a : {};
301
- if (topK != null) {
302
- warnings.push({
303
- type: "unsupported-setting",
304
- setting: "topK"
305
- });
306
- }
307
- if (frequencyPenalty != null) {
308
- warnings.push({
309
- type: "unsupported-setting",
310
- setting: "frequencyPenalty"
311
- });
312
- }
313
- if (presencePenalty != null) {
314
- warnings.push({
315
- type: "unsupported-setting",
316
- setting: "presencePenalty"
317
- });
318
- }
319
- if (stopSequences != null) {
320
- warnings.push({
321
- type: "unsupported-setting",
322
- setting: "stopSequences"
323
- });
324
- }
325
- if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) {
326
- warnings.push({
327
- type: "unsupported-setting",
328
- setting: "responseFormat",
329
- details: "JSON response format schema is not supported"
330
- });
331
- }
332
- const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
333
- warnings.push(...messageWarnings);
334
- const {
335
- tools: xaiTools,
336
- toolChoice: xaiToolChoice,
337
- toolWarnings
338
- } = prepareTools({
339
- tools,
340
- toolChoice
341
- });
342
- warnings.push(...toolWarnings);
343
- const baseArgs = {
344
- // model id
345
- model: this.modelId,
346
- // standard generation settings
347
- max_tokens: maxOutputTokens,
348
- temperature,
349
- top_p: topP,
350
- seed,
351
- reasoning_effort: options.reasoningEffort,
352
- // response format
353
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
354
- type: "json_schema",
355
- json_schema: {
356
- name: (_b = responseFormat.name) != null ? _b : "response",
357
- schema: responseFormat.schema,
358
- strict: true
359
- }
360
- } : { type: "json_object" } : void 0,
361
- // search parameters
362
- search_parameters: options.searchParameters ? {
363
- mode: options.searchParameters.mode,
364
- return_citations: options.searchParameters.returnCitations,
365
- from_date: options.searchParameters.fromDate,
366
- to_date: options.searchParameters.toDate,
367
- max_search_results: options.searchParameters.maxSearchResults,
368
- sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
369
- var _a2;
370
- return {
371
- type: source.type,
372
- ...source.type === "web" && {
373
- country: source.country,
374
- excluded_websites: source.excludedWebsites,
375
- allowed_websites: source.allowedWebsites,
376
- safe_search: source.safeSearch
377
- },
378
- ...source.type === "x" && {
379
- excluded_x_handles: source.excludedXHandles,
380
- included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
381
- post_favorite_count: source.postFavoriteCount,
382
- post_view_count: source.postViewCount
383
- },
384
- ...source.type === "news" && {
385
- country: source.country,
386
- excluded_websites: source.excludedWebsites,
387
- safe_search: source.safeSearch
388
- },
389
- ...source.type === "rss" && {
390
- links: source.links
391
- }
392
- };
393
- })
394
- } : void 0,
395
- // messages in xai format
396
- messages,
397
- // tools in xai format
398
- tools: xaiTools,
399
- tool_choice: xaiToolChoice
400
- };
401
- return {
402
- args: baseArgs,
403
- warnings
404
- };
405
- }
406
- async doGenerate(options) {
407
- var _a, _b, _c;
408
- const { args: body, warnings } = await this.getArgs(options);
409
- const {
410
- responseHeaders,
411
- value: response,
412
- rawValue: rawResponse
413
- } = await chunkS5MJLXMG_cjs.postJsonToApi({
414
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
415
- headers: chunkS5MJLXMG_cjs.combineHeaders(this.config.headers(), options.headers),
416
- body,
417
- failedResponseHandler: xaiFailedResponseHandler,
418
- successfulResponseHandler: chunkS5MJLXMG_cjs.createJsonResponseHandler(
419
- xaiChatResponseSchema
420
- ),
421
- abortSignal: options.abortSignal,
422
- fetch: this.config.fetch
423
- });
424
- const choice = response.choices[0];
425
- const content = [];
426
- if (choice.message.content != null && choice.message.content.length > 0) {
427
- let text = choice.message.content;
428
- const lastMessage = body.messages[body.messages.length - 1];
429
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
430
- text = "";
431
- }
432
- if (text.length > 0) {
433
- content.push({ type: "text", text });
434
- }
435
- }
436
- if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
437
- content.push({
438
- type: "reasoning",
439
- text: choice.message.reasoning_content
440
- });
441
- }
442
- if (choice.message.tool_calls != null) {
443
- for (const toolCall of choice.message.tool_calls) {
444
- content.push({
445
- type: "tool-call",
446
- toolCallId: toolCall.id,
447
- toolName: toolCall.function.name,
448
- input: toolCall.function.arguments
449
- });
450
- }
451
- }
452
- if (response.citations != null) {
453
- for (const url of response.citations) {
454
- content.push({
455
- type: "source",
456
- sourceType: "url",
457
- id: this.config.generateId(),
458
- url
459
- });
460
- }
461
- }
462
- return {
463
- content,
464
- finishReason: mapXaiFinishReason(choice.finish_reason),
465
- usage: {
466
- inputTokens: response.usage.prompt_tokens,
467
- outputTokens: response.usage.completion_tokens,
468
- totalTokens: response.usage.total_tokens,
469
- reasoningTokens: (_c = (_b = response.usage.completion_tokens_details) == null ? void 0 : _b.reasoning_tokens) != null ? _c : void 0
470
- },
471
- request: { body },
472
- response: {
473
- ...getResponseMetadata(response),
474
- headers: responseHeaders,
475
- body: rawResponse
476
- },
477
- warnings
478
- };
479
- }
480
- async doStream(options) {
481
- var _a;
482
- const { args, warnings } = await this.getArgs(options);
483
- const body = {
484
- ...args,
485
- stream: true,
486
- stream_options: {
487
- include_usage: true
488
- }
489
- };
490
- const { responseHeaders, value: response } = await chunkS5MJLXMG_cjs.postJsonToApi({
491
- url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`,
492
- headers: chunkS5MJLXMG_cjs.combineHeaders(this.config.headers(), options.headers),
493
- body,
494
- failedResponseHandler: xaiFailedResponseHandler,
495
- successfulResponseHandler: chunkS5MJLXMG_cjs.createEventSourceResponseHandler(xaiChatChunkSchema),
496
- abortSignal: options.abortSignal,
497
- fetch: this.config.fetch
498
- });
499
- let finishReason = "unknown";
500
- const usage = {
501
- inputTokens: void 0,
502
- outputTokens: void 0,
503
- totalTokens: void 0
504
- };
505
- let isFirstChunk = true;
506
- const contentBlocks = {};
507
- const lastReasoningDeltas = {};
508
- const self = this;
509
- return {
510
- stream: response.pipeThrough(
511
- new TransformStream({
512
- start(controller) {
513
- controller.enqueue({ type: "stream-start", warnings });
514
- },
515
- transform(chunk, controller) {
516
- var _a2, _b;
517
- if (options.includeRawChunks) {
518
- controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
519
- }
520
- if (!chunk.success) {
521
- controller.enqueue({ type: "error", error: chunk.error });
522
- return;
523
- }
524
- const value = chunk.value;
525
- if (isFirstChunk) {
526
- controller.enqueue({
527
- type: "response-metadata",
528
- ...getResponseMetadata(value)
529
- });
530
- isFirstChunk = false;
531
- }
532
- if (value.citations != null) {
533
- for (const url of value.citations) {
534
- controller.enqueue({
535
- type: "source",
536
- sourceType: "url",
537
- id: self.config.generateId(),
538
- url
539
- });
540
- }
541
- }
542
- if (value.usage != null) {
543
- usage.inputTokens = value.usage.prompt_tokens;
544
- usage.outputTokens = value.usage.completion_tokens;
545
- usage.totalTokens = value.usage.total_tokens;
546
- usage.reasoningTokens = (_b = (_a2 = value.usage.completion_tokens_details) == null ? void 0 : _a2.reasoning_tokens) != null ? _b : void 0;
547
- }
548
- const choice = value.choices[0];
549
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
550
- finishReason = mapXaiFinishReason(choice.finish_reason);
551
- }
552
- if ((choice == null ? void 0 : choice.delta) == null) {
553
- return;
554
- }
555
- const delta = choice.delta;
556
- const choiceIndex = choice.index;
557
- if (delta.content != null && delta.content.length > 0) {
558
- const textContent = delta.content;
559
- const lastMessage = body.messages[body.messages.length - 1];
560
- if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
561
- return;
562
- }
563
- const blockId = `text-${value.id || choiceIndex}`;
564
- if (contentBlocks[blockId] == null) {
565
- contentBlocks[blockId] = { type: "text" };
566
- controller.enqueue({
567
- type: "text-start",
568
- id: blockId
569
- });
570
- }
571
- controller.enqueue({
572
- type: "text-delta",
573
- id: blockId,
574
- delta: textContent
575
- });
576
- }
577
- if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
578
- const blockId = `reasoning-${value.id || choiceIndex}`;
579
- if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
580
- return;
581
- }
582
- lastReasoningDeltas[blockId] = delta.reasoning_content;
583
- if (contentBlocks[blockId] == null) {
584
- contentBlocks[blockId] = { type: "reasoning" };
585
- controller.enqueue({
586
- type: "reasoning-start",
587
- id: blockId
588
- });
589
- }
590
- controller.enqueue({
591
- type: "reasoning-delta",
592
- id: blockId,
593
- delta: delta.reasoning_content
594
- });
595
- }
596
- if (delta.tool_calls != null) {
597
- for (const toolCall of delta.tool_calls) {
598
- const toolCallId = toolCall.id;
599
- controller.enqueue({
600
- type: "tool-input-start",
601
- id: toolCallId,
602
- toolName: toolCall.function.name
603
- });
604
- controller.enqueue({
605
- type: "tool-input-delta",
606
- id: toolCallId,
607
- delta: toolCall.function.arguments
608
- });
609
- controller.enqueue({
610
- type: "tool-input-end",
611
- id: toolCallId
612
- });
613
- controller.enqueue({
614
- type: "tool-call",
615
- toolCallId,
616
- toolName: toolCall.function.name,
617
- input: toolCall.function.arguments
618
- });
619
- }
620
- }
621
- },
622
- flush(controller) {
623
- for (const [blockId, block] of Object.entries(contentBlocks)) {
624
- controller.enqueue({
625
- type: block.type === "text" ? "text-end" : "reasoning-end",
626
- id: blockId
627
- });
628
- }
629
- controller.enqueue({ type: "finish", finishReason, usage });
630
- }
631
- })
632
- ),
633
- request: { body },
634
- response: { headers: responseHeaders }
635
- };
636
- }
637
- };
638
- var xaiUsageSchema = v4.z.object({
639
- prompt_tokens: v4.z.number(),
640
- completion_tokens: v4.z.number(),
641
- total_tokens: v4.z.number(),
642
- completion_tokens_details: v4.z.object({
643
- reasoning_tokens: v4.z.number().nullish()
644
- }).nullish()
645
- });
646
- var xaiChatResponseSchema = v4.z.object({
647
- id: v4.z.string().nullish(),
648
- created: v4.z.number().nullish(),
649
- model: v4.z.string().nullish(),
650
- choices: v4.z.array(
651
- v4.z.object({
652
- message: v4.z.object({
653
- role: v4.z.literal("assistant"),
654
- content: v4.z.string().nullish(),
655
- reasoning_content: v4.z.string().nullish(),
656
- tool_calls: v4.z.array(
657
- v4.z.object({
658
- id: v4.z.string(),
659
- type: v4.z.literal("function"),
660
- function: v4.z.object({
661
- name: v4.z.string(),
662
- arguments: v4.z.string()
663
- })
664
- })
665
- ).nullish()
666
- }),
667
- index: v4.z.number(),
668
- finish_reason: v4.z.string().nullish()
669
- })
670
- ),
671
- object: v4.z.literal("chat.completion"),
672
- usage: xaiUsageSchema,
673
- citations: v4.z.array(v4.z.string().url()).nullish()
674
- });
675
- var xaiChatChunkSchema = v4.z.object({
676
- id: v4.z.string().nullish(),
677
- created: v4.z.number().nullish(),
678
- model: v4.z.string().nullish(),
679
- choices: v4.z.array(
680
- v4.z.object({
681
- delta: v4.z.object({
682
- role: v4.z.enum(["assistant"]).optional(),
683
- content: v4.z.string().nullish(),
684
- reasoning_content: v4.z.string().nullish(),
685
- tool_calls: v4.z.array(
686
- v4.z.object({
687
- id: v4.z.string(),
688
- type: v4.z.literal("function"),
689
- function: v4.z.object({
690
- name: v4.z.string(),
691
- arguments: v4.z.string()
692
- })
693
- })
694
- ).nullish()
695
- }),
696
- finish_reason: v4.z.string().nullish(),
697
- index: v4.z.number()
698
- })
699
- ),
700
- usage: xaiUsageSchema.nullish(),
701
- citations: v4.z.array(v4.z.string().url()).nullish()
702
- });
703
- var VERSION = "2.0.26" ;
704
- var xaiErrorStructure = {
705
- errorSchema: xaiErrorDataSchema,
706
- errorToMessage: (data) => data.error.message
707
- };
708
- function createXai(options = {}) {
709
- var _a;
710
- const baseURL = chunkS5MJLXMG_cjs.withoutTrailingSlash(
711
- (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
712
- );
713
- const getHeaders = () => chunkS5MJLXMG_cjs.withUserAgentSuffix(
714
- {
715
- Authorization: `Bearer ${chunkS5MJLXMG_cjs.loadApiKey({
716
- apiKey: options.apiKey,
717
- environmentVariableName: "XAI_API_KEY",
718
- description: "xAI API key"
719
- })}`,
720
- ...options.headers
721
- },
722
- `ai-sdk/xai/${VERSION}`
723
- );
724
- const createLanguageModel = (modelId) => {
725
- return new XaiChatLanguageModel(modelId, {
726
- provider: "xai.chat",
727
- baseURL,
728
- headers: getHeaders,
729
- generateId: chunkS5MJLXMG_cjs.generateId,
730
- fetch: options.fetch
731
- });
732
- };
733
- const createImageModel = (modelId) => {
734
- return new chunkS5MJLXMG_cjs.OpenAICompatibleImageModel(modelId, {
735
- provider: "xai.image",
736
- url: ({ path }) => `${baseURL}${path}`,
737
- headers: getHeaders,
738
- fetch: options.fetch,
739
- errorStructure: xaiErrorStructure
740
- });
741
- };
742
- const provider = (modelId) => createLanguageModel(modelId);
743
- provider.languageModel = createLanguageModel;
744
- provider.chat = createLanguageModel;
745
- provider.textEmbeddingModel = (modelId) => {
746
- throw new chunkS5MJLXMG_cjs.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
747
- };
748
- provider.imageModel = createImageModel;
749
- provider.image = createImageModel;
750
- return provider;
751
- }
752
- createXai();
753
-
754
- // src/llm/model/gateway-resolver.ts
755
- function parseModelRouterId(routerId, gatewayPrefix) {
756
- if (gatewayPrefix && !routerId.startsWith(`${gatewayPrefix}/`)) {
757
- throw new Error(`Expected ${gatewayPrefix}/ in model router ID ${routerId}`);
758
- }
759
- const idParts = routerId.split("/");
760
- if (gatewayPrefix && idParts.length < 3) {
761
- throw new Error(
762
- `Expected atleast 3 id parts ${gatewayPrefix}/provider/model, but only saw ${idParts.length} in ${routerId}`
763
- );
764
- }
765
- const providerId = idParts.at(gatewayPrefix ? 1 : 0);
766
- const modelId = idParts.slice(gatewayPrefix ? 2 : 1).join(`/`);
767
- if (!routerId.includes(`/`) || !providerId || !modelId) {
768
- throw new Error(
769
- `Attempted to parse provider/model from ${routerId} but this ID doesn't appear to contain a provider`
770
- );
771
- }
772
- return {
773
- providerId,
774
- modelId
775
- };
776
- }
777
-
778
- // src/llm/model/gateways/constants.ts
779
- var PROVIDERS_WITH_INSTALLED_PACKAGES = ["anthropic", "google", "openai", "openrouter", "xai"];
780
- var EXCLUDED_PROVIDERS = ["github-copilot"];
781
-
782
- // src/llm/model/gateways/models-dev.ts
783
- var OPENAI_COMPATIBLE_OVERRIDES = {
784
- cerebras: {
785
- url: "https://api.cerebras.ai/v1"
786
- },
787
- mistral: {
788
- url: "https://api.mistral.ai/v1"
789
- },
790
- groq: {
791
- url: "https://api.groq.com/openai/v1"
792
- },
793
- togetherai: {
794
- url: "https://api.together.xyz/v1"
795
- },
796
- deepinfra: {
797
- url: "https://api.deepinfra.com/v1/openai"
798
- },
799
- perplexity: {
800
- url: "https://api.perplexity.ai"
801
- },
802
- vercel: {
803
- url: "https://ai-gateway.vercel.sh/v1",
804
- apiKeyEnvVar: "AI_GATEWAY_API_KEY"
805
- }
806
- };
807
- var ModelsDevGateway = class extends chunkS5MJLXMG_cjs.MastraModelGateway {
808
- name = "models.dev";
809
- prefix = void 0;
810
- // No prefix for registry gateway
811
- providerConfigs = {};
812
- constructor(providerConfigs) {
813
- super();
814
- if (providerConfigs) this.providerConfigs = providerConfigs;
815
- }
816
- async fetchProviders() {
817
- const response = await fetch("https://models.dev/api.json");
818
- if (!response.ok) {
819
- throw new Error(`Failed to fetch from models.dev: ${response.statusText}`);
820
- }
821
- const data = await response.json();
822
- const providerConfigs = {};
823
- for (const [providerId, providerInfo] of Object.entries(data)) {
824
- if (EXCLUDED_PROVIDERS.includes(providerId)) continue;
825
- if (!providerInfo || typeof providerInfo !== "object" || !providerInfo.models) continue;
826
- const normalizedId = providerId;
827
- const isOpenAICompatible = providerInfo.npm === "@ai-sdk/openai-compatible" || providerInfo.npm === "@ai-sdk/gateway" || // Vercel AI Gateway is OpenAI-compatible
828
- normalizedId in OPENAI_COMPATIBLE_OVERRIDES;
829
- const hasInstalledPackage = PROVIDERS_WITH_INSTALLED_PACKAGES.includes(providerId);
830
- const hasApiAndEnv = providerInfo.api && providerInfo.env && providerInfo.env.length > 0;
831
- if (isOpenAICompatible || hasInstalledPackage || hasApiAndEnv) {
832
- const modelIds = Object.keys(providerInfo.models).sort();
833
- const url = providerInfo.api || OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.url;
834
- if (!hasInstalledPackage && !url) {
835
- continue;
836
- }
837
- const apiKeyEnvVar = providerInfo.env?.[0] || `${normalizedId.toUpperCase().replace(/-/g, "_")}_API_KEY`;
838
- const apiKeyHeader = !hasInstalledPackage ? OPENAI_COMPATIBLE_OVERRIDES[normalizedId]?.apiKeyHeader || "Authorization" : void 0;
839
- providerConfigs[normalizedId] = {
840
- url,
841
- apiKeyEnvVar,
842
- apiKeyHeader,
843
- name: providerInfo.name || providerId.charAt(0).toUpperCase() + providerId.slice(1),
844
- models: modelIds,
845
- docUrl: providerInfo.doc,
846
- // Include documentation URL if available
847
- gateway: `models.dev`
848
- };
849
- }
850
- }
851
- this.providerConfigs = providerConfigs;
852
- return providerConfigs;
853
- }
854
- buildUrl(routerId, envVars) {
855
- const { providerId } = parseModelRouterId(routerId);
856
- const config = this.providerConfigs[providerId];
857
- if (!config?.url) {
858
- return;
859
- }
860
- const baseUrlEnvVar = `${providerId.toUpperCase().replace(/-/g, "_")}_BASE_URL`;
861
- const customBaseUrl = envVars?.[baseUrlEnvVar] || process.env[baseUrlEnvVar];
862
- return customBaseUrl || config.url;
863
- }
864
- getApiKey(modelId) {
865
- const [provider, model] = modelId.split("/");
866
- if (!provider || !model) {
867
- throw new Error(`Could not identify provider from model id ${modelId}`);
868
- }
869
- const config = this.providerConfigs[provider];
870
- if (!config) {
871
- throw new Error(`Could not find config for provider ${provider} with model id ${modelId}`);
872
- }
873
- const apiKey = typeof config.apiKeyEnvVar === `string` ? process.env[config.apiKeyEnvVar] : void 0;
874
- if (!apiKey) {
875
- throw new Error(`Could not find API key process.env.${config.apiKeyEnvVar} for model id ${modelId}`);
876
- }
877
- return Promise.resolve(apiKey);
878
- }
879
- async resolveLanguageModel({
880
- modelId,
881
- providerId,
882
- apiKey
883
- }) {
884
- const baseURL = this.buildUrl(`${providerId}/${modelId}`);
885
- switch (providerId) {
886
- case "openai":
887
- return chunkS5MJLXMG_cjs.createOpenAI({ apiKey }).responses(modelId);
888
- case "gemini":
889
- case "google":
890
- return chunkS5MJLXMG_cjs.createGoogleGenerativeAI({
891
- apiKey
892
- }).chat(modelId);
893
- case "anthropic":
894
- return chunkS5MJLXMG_cjs.createAnthropic({ apiKey })(modelId);
895
- case "openrouter":
896
- return aiSdkProviderV5.createOpenRouter({ apiKey })(modelId);
897
- case "xai":
898
- return createXai({
899
- apiKey
900
- })(modelId);
901
- default:
902
- if (!baseURL) throw new Error(`No API URL found for ${providerId}/${modelId}`);
903
- return chunkS5MJLXMG_cjs.createOpenAICompatible({ name: providerId, apiKey, baseURL, supportsStructuredOutputs: true }).chatModel(
904
- modelId
905
- );
906
- }
907
- }
908
- };
909
-
910
- exports.ModelsDevGateway = ModelsDevGateway;
911
- exports.parseModelRouterId = parseModelRouterId;
912
- //# sourceMappingURL=chunk-IU2SZXJQ.cjs.map
913
- //# sourceMappingURL=chunk-IU2SZXJQ.cjs.map