@mastra/core 0.9.2 → 0.9.3-alpha.0

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 (73) hide show
  1. package/dist/agent/index.cjs +2 -2
  2. package/dist/agent/index.d.cts +1 -1
  3. package/dist/agent/index.d.ts +1 -1
  4. package/dist/agent/index.js +1 -1
  5. package/dist/{base-B3g_Q3KV.d.cts → base-Cs0ddGCf.d.cts} +5 -5
  6. package/dist/{base-Dq_YZkEc.d.ts → base-CzHSMvOb.d.ts} +5 -5
  7. package/dist/{chunk-ZVBLRU4W.cjs → chunk-22CFFDPA.cjs} +5 -5
  8. package/dist/{chunk-QV4ZJLWA.js → chunk-2UAN6SRJ.js} +1 -1
  9. package/dist/{chunk-6FW4DXZO.cjs → chunk-4DEDPTLO.cjs} +2 -2
  10. package/dist/{chunk-SIQPAONL.js → chunk-6HHSM7FP.js} +1 -1
  11. package/dist/{chunk-URYHOYKQ.js → chunk-KSH5B376.js} +3 -3
  12. package/dist/{chunk-B7N24G5E.cjs → chunk-O6EYGXZO.cjs} +2 -2
  13. package/dist/chunk-OHIRECYU.cjs +930 -0
  14. package/dist/{chunk-2JNVEJCM.js → chunk-PPNVAI5G.js} +1 -1
  15. package/dist/{chunk-JTKSOVYL.cjs → chunk-QJJD56YR.cjs} +2 -2
  16. package/dist/{chunk-IBKW4TJU.js → chunk-TZIOJX3N.js} +1 -1
  17. package/dist/chunk-WD3HYQV3.js +911 -0
  18. package/dist/{chunk-HAFLSGW5.cjs → chunk-WYL4MKWH.cjs} +14 -14
  19. package/dist/eval/index.d.cts +1 -1
  20. package/dist/eval/index.d.ts +1 -1
  21. package/dist/index.cjs +57 -57
  22. package/dist/index.d.cts +3 -3
  23. package/dist/index.d.ts +3 -3
  24. package/dist/index.js +8 -8
  25. package/dist/integration/index.cjs +3 -3
  26. package/dist/integration/index.d.cts +1 -1
  27. package/dist/integration/index.d.ts +1 -1
  28. package/dist/integration/index.js +1 -1
  29. package/dist/llm/index.d.cts +1 -1
  30. package/dist/llm/index.d.ts +1 -1
  31. package/dist/mastra/index.d.cts +1 -1
  32. package/dist/mastra/index.d.ts +1 -1
  33. package/dist/memory/index.cjs +4 -4
  34. package/dist/memory/index.d.cts +1 -1
  35. package/dist/memory/index.d.ts +1 -1
  36. package/dist/memory/index.js +1 -1
  37. package/dist/network/index.cjs +4 -4
  38. package/dist/network/index.d.cts +1 -1
  39. package/dist/network/index.d.ts +1 -1
  40. package/dist/network/index.js +2 -2
  41. package/dist/relevance/index.cjs +4 -4
  42. package/dist/relevance/index.d.cts +1 -1
  43. package/dist/relevance/index.d.ts +1 -1
  44. package/dist/relevance/index.js +1 -1
  45. package/dist/server/index.d.cts +1 -1
  46. package/dist/server/index.d.ts +1 -1
  47. package/dist/storage/index.d.cts +1 -1
  48. package/dist/storage/index.d.ts +1 -1
  49. package/dist/storage/libsql/index.d.cts +1 -1
  50. package/dist/storage/libsql/index.d.ts +1 -1
  51. package/dist/telemetry/index.d.cts +1 -1
  52. package/dist/telemetry/index.d.ts +1 -1
  53. package/dist/tools/index.cjs +4 -4
  54. package/dist/tools/index.d.cts +1 -1
  55. package/dist/tools/index.d.ts +1 -1
  56. package/dist/tools/index.js +1 -1
  57. package/dist/utils.cjs +12 -12
  58. package/dist/utils.d.cts +7 -6
  59. package/dist/utils.d.ts +7 -6
  60. package/dist/utils.js +1 -1
  61. package/dist/voice/index.d.cts +1 -1
  62. package/dist/voice/index.d.ts +1 -1
  63. package/dist/workflows/index.cjs +22 -22
  64. package/dist/workflows/index.d.cts +2 -2
  65. package/dist/workflows/index.d.ts +2 -2
  66. package/dist/workflows/index.js +1 -1
  67. package/dist/workflows/vNext/index.cjs +13 -13
  68. package/dist/workflows/vNext/index.d.cts +2 -2
  69. package/dist/workflows/vNext/index.d.ts +2 -2
  70. package/dist/workflows/vNext/index.js +11 -11
  71. package/package.json +7 -5
  72. package/dist/chunk-D2Y3ET63.cjs +0 -362
  73. package/dist/chunk-ZCJJ6XOH.js +0 -344
@@ -0,0 +1,911 @@
1
+ import { MastraBase } from './chunk-CLJQYXNM.js';
2
+ import { RuntimeContext } from './chunk-SGGPJWRQ.js';
3
+ import { createHash } from 'crypto';
4
+ import { convertToCoreMessages, jsonSchema, zodSchema } from 'ai';
5
+ import jsonSchemaToZod from 'json-schema-to-zod';
6
+ import { z } from 'zod';
7
+ import zodToJsonSchema from 'zod-to-json-schema';
8
+
9
+ // src/tools/tool.ts
10
+ var Tool = class {
11
+ id;
12
+ description;
13
+ inputSchema;
14
+ outputSchema;
15
+ execute;
16
+ mastra;
17
+ constructor(opts) {
18
+ this.id = opts.id;
19
+ this.description = opts.description;
20
+ this.inputSchema = opts.inputSchema;
21
+ this.outputSchema = opts.outputSchema;
22
+ this.execute = opts.execute;
23
+ this.mastra = opts.mastra;
24
+ }
25
+ };
26
+ function createTool(opts) {
27
+ return new Tool(opts);
28
+ }
29
+ var ALL_STRING_CHECKS = ["regex", "emoji", "email", "url", "uuid", "cuid", "min", "max"];
30
+ var ALL_NUMBER_CHECKS = [
31
+ "min",
32
+ // gte internally
33
+ "max",
34
+ // lte internally
35
+ "multipleOf"
36
+ ];
37
+ var ALL_ARRAY_CHECKS = ["min", "max", "length"];
38
+ var UNSUPPORTED_ZOD_TYPES = ["ZodIntersection", "ZodNever", "ZodNull", "ZodTuple", "ZodUndefined"];
39
+ var ToolCompatibility = class extends MastraBase {
40
+ model;
41
+ constructor(model) {
42
+ super({ name: "SchemaCompatibility" });
43
+ this.model = model;
44
+ }
45
+ getModel() {
46
+ return this.model;
47
+ }
48
+ zodToAISDKSchema(zodSchema2) {
49
+ const newSchema = z.object(
50
+ Object.entries(zodSchema2.shape).reduce(
51
+ (acc, [key, value]) => ({
52
+ ...acc,
53
+ [key]: this.processZodType(value)
54
+ }),
55
+ {}
56
+ )
57
+ );
58
+ const schema = jsonSchema(
59
+ zodToJsonSchema(newSchema, {
60
+ $refStrategy: "none",
61
+ target: this.getSchemaTarget()
62
+ }),
63
+ {
64
+ validate: (value) => {
65
+ const result = newSchema.safeParse(value);
66
+ return result.success ? { success: true, value: result.data } : { success: false, error: result.error };
67
+ }
68
+ }
69
+ );
70
+ return { schema };
71
+ }
72
+ defaultZodObjectHandler(value) {
73
+ const zodObject = value;
74
+ const processedShape = Object.entries(zodObject.shape || {}).reduce(
75
+ (acc, [key, propValue]) => {
76
+ const typedPropValue = propValue;
77
+ const processedValue = this.processZodType(typedPropValue);
78
+ acc[key] = processedValue;
79
+ return acc;
80
+ },
81
+ {}
82
+ );
83
+ let result = z.object(processedShape);
84
+ if (value.description) {
85
+ result = result.describe(value.description);
86
+ }
87
+ return result;
88
+ }
89
+ mergeParameterDescription(description, constraints) {
90
+ if (Object.keys(constraints).length > 0) {
91
+ return (description ? description + "\n" : "") + JSON.stringify(constraints);
92
+ } else {
93
+ return description;
94
+ }
95
+ }
96
+ defaultUnsupportedZodTypeHandler(value, throwOnTypes = UNSUPPORTED_ZOD_TYPES) {
97
+ if (throwOnTypes.includes(value._def.typeName)) {
98
+ throw new Error(`${this.model.modelId} does not support zod type: ${value._def.typeName}`);
99
+ }
100
+ return value;
101
+ }
102
+ defaultZodArrayHandler(value, handleChecks = ALL_ARRAY_CHECKS) {
103
+ const zodArray = value._def;
104
+ const arrayType = zodArray.type;
105
+ const constraints = {};
106
+ if (zodArray.minLength?.value !== void 0 && handleChecks.includes("min")) {
107
+ constraints.minLength = zodArray.minLength.value;
108
+ }
109
+ if (zodArray.maxLength?.value !== void 0 && handleChecks.includes("max")) {
110
+ constraints.maxLength = zodArray.maxLength.value;
111
+ }
112
+ if (zodArray.exactLength?.value !== void 0 && handleChecks.includes("length")) {
113
+ constraints.exactLength = zodArray.exactLength.value;
114
+ }
115
+ const processedType = arrayType._def.typeName === "ZodObject" ? this.processZodType(arrayType) : arrayType;
116
+ let result = z.array(processedType);
117
+ if (zodArray.minLength?.value !== void 0 && !handleChecks.includes("min")) {
118
+ result = result.min(zodArray.minLength.value);
119
+ }
120
+ if (zodArray.maxLength?.value !== void 0 && !handleChecks.includes("max")) {
121
+ result = result.max(zodArray.maxLength.value);
122
+ }
123
+ if (zodArray.exactLength?.value !== void 0 && !handleChecks.includes("length")) {
124
+ result = result.length(zodArray.exactLength.value);
125
+ }
126
+ const description = this.mergeParameterDescription(value.description, constraints);
127
+ if (description) {
128
+ result = result.describe(description);
129
+ }
130
+ return result;
131
+ }
132
+ defaultZodUnionHandler(value) {
133
+ const zodUnion = value;
134
+ const processedOptions = zodUnion._def.options.map((option) => this.processZodType(option));
135
+ if (processedOptions.length < 2) throw new Error("Union must have at least 2 options");
136
+ let result = z.union(processedOptions);
137
+ if (value.description) {
138
+ result = result.describe(value.description);
139
+ }
140
+ return result;
141
+ }
142
+ defaultZodStringHandler(value, handleChecks = ALL_STRING_CHECKS) {
143
+ const zodString = value;
144
+ const constraints = {};
145
+ const checks = zodString._def.checks || [];
146
+ const newChecks = [];
147
+ for (const check of checks) {
148
+ if ("kind" in check) {
149
+ if (handleChecks.includes(check.kind)) {
150
+ switch (check.kind) {
151
+ case "regex": {
152
+ constraints.regex = {
153
+ pattern: check.regex.source,
154
+ flags: check.regex.flags
155
+ };
156
+ break;
157
+ }
158
+ case "emoji": {
159
+ constraints.emoji = true;
160
+ break;
161
+ }
162
+ case "email": {
163
+ constraints.email = true;
164
+ break;
165
+ }
166
+ case "url": {
167
+ constraints.url = true;
168
+ break;
169
+ }
170
+ case "uuid": {
171
+ constraints.uuid = true;
172
+ break;
173
+ }
174
+ case "cuid": {
175
+ constraints.cuid = true;
176
+ break;
177
+ }
178
+ case "min": {
179
+ constraints.minLength = check.value;
180
+ break;
181
+ }
182
+ case "max": {
183
+ constraints.maxLength = check.value;
184
+ break;
185
+ }
186
+ }
187
+ } else {
188
+ newChecks.push(check);
189
+ }
190
+ }
191
+ }
192
+ let result = z.string();
193
+ for (const check of newChecks) {
194
+ result = result._addCheck(check);
195
+ }
196
+ const description = this.mergeParameterDescription(value.description, constraints);
197
+ if (description) {
198
+ result = result.describe(description);
199
+ }
200
+ return result;
201
+ }
202
+ defaultZodNumberHandler(value, handleChecks = ALL_NUMBER_CHECKS) {
203
+ const zodNumber = value;
204
+ const constraints = {};
205
+ const checks = zodNumber._def.checks || [];
206
+ const newChecks = [];
207
+ for (const check of checks) {
208
+ if ("kind" in check) {
209
+ if (handleChecks.includes(check.kind)) {
210
+ switch (check.kind) {
211
+ case "min":
212
+ if (check.inclusive) {
213
+ constraints.gte = check.value;
214
+ } else {
215
+ constraints.gt = check.value;
216
+ }
217
+ break;
218
+ case "max":
219
+ if (check.inclusive) {
220
+ constraints.lte = check.value;
221
+ } else {
222
+ constraints.lt = check.value;
223
+ }
224
+ break;
225
+ case "multipleOf": {
226
+ constraints.multipleOf = check.value;
227
+ break;
228
+ }
229
+ }
230
+ } else {
231
+ newChecks.push(check);
232
+ }
233
+ }
234
+ }
235
+ let result = z.number();
236
+ for (const check of newChecks) {
237
+ switch (check.kind) {
238
+ case "int":
239
+ result = result.int();
240
+ break;
241
+ case "finite":
242
+ result = result.finite();
243
+ break;
244
+ default:
245
+ result = result._addCheck(check);
246
+ }
247
+ }
248
+ const description = this.mergeParameterDescription(value.description, constraints);
249
+ if (description) {
250
+ result = result.describe(description);
251
+ }
252
+ return result;
253
+ }
254
+ defaultZodDateHandler(value) {
255
+ const zodDate = value;
256
+ const constraints = {};
257
+ const checks = zodDate._def.checks || [];
258
+ for (const check of checks) {
259
+ if ("kind" in check) {
260
+ switch (check.kind) {
261
+ case "min":
262
+ const minDate = new Date(check.value);
263
+ if (!isNaN(minDate.getTime())) {
264
+ constraints.minDate = minDate.toISOString();
265
+ }
266
+ break;
267
+ case "max":
268
+ const maxDate = new Date(check.value);
269
+ if (!isNaN(maxDate.getTime())) {
270
+ constraints.maxDate = maxDate.toISOString();
271
+ }
272
+ break;
273
+ }
274
+ }
275
+ }
276
+ constraints.dateFormat = "date-time";
277
+ let result = z.string().describe("date-time");
278
+ const description = this.mergeParameterDescription(value.description, constraints);
279
+ if (description) {
280
+ result = result.describe(description);
281
+ }
282
+ return result;
283
+ }
284
+ process(tool) {
285
+ if (isVercelTool(tool)) {
286
+ return {
287
+ description: tool.description,
288
+ // TODO: should we also process vercel tool params?
289
+ parameters: zodSchema(convertVercelToolParameters(tool))
290
+ };
291
+ }
292
+ const { schema } = this.zodToAISDKSchema(tool.inputSchema);
293
+ return {
294
+ description: tool.description,
295
+ parameters: schema
296
+ };
297
+ }
298
+ };
299
+
300
+ // src/tools/tool-compatibility/provider-compats/anthropic.ts
301
+ var AnthropicToolCompat = class extends ToolCompatibility {
302
+ constructor(model) {
303
+ super(model);
304
+ }
305
+ getSchemaTarget() {
306
+ return "jsonSchema7";
307
+ }
308
+ shouldApply() {
309
+ return this.getModel().modelId.includes("claude");
310
+ }
311
+ processZodType(value) {
312
+ switch (value._def.typeName) {
313
+ case "ZodObject": {
314
+ return this.defaultZodObjectHandler(value);
315
+ }
316
+ case "ZodArray": {
317
+ return this.defaultZodArrayHandler(value, []);
318
+ }
319
+ case "ZodUnion": {
320
+ return this.defaultZodUnionHandler(value);
321
+ }
322
+ // the claude-3.5-haiku model support these properties but the model doesn't respect them, but it respects them when they're
323
+ // added to the tool description
324
+ case "ZodString": {
325
+ if (this.getModel().modelId.includes("claude-3.5-haiku")) {
326
+ return this.defaultZodStringHandler(value, ["max", "min"]);
327
+ } else {
328
+ return value;
329
+ }
330
+ }
331
+ default:
332
+ if (this.getModel().modelId.includes("claude-3.7")) {
333
+ return this.defaultUnsupportedZodTypeHandler(value, ["ZodNever", "ZodTuple", "ZodUndefined"]);
334
+ } else {
335
+ return this.defaultUnsupportedZodTypeHandler(value, ["ZodNever", "ZodUndefined"]);
336
+ }
337
+ }
338
+ }
339
+ };
340
+
341
+ // src/tools/tool-compatibility/provider-compats/deepseek.ts
342
+ var DeepSeekToolCompat = class extends ToolCompatibility {
343
+ constructor(model) {
344
+ super(model);
345
+ }
346
+ getSchemaTarget() {
347
+ return "jsonSchema7";
348
+ }
349
+ shouldApply() {
350
+ return this.getModel().modelId.includes("deepseek");
351
+ }
352
+ processZodType(value) {
353
+ switch (value._def.typeName) {
354
+ case "ZodObject": {
355
+ return this.defaultZodObjectHandler(value);
356
+ }
357
+ case "ZodArray": {
358
+ return this.defaultZodArrayHandler(value, ["min", "max"]);
359
+ }
360
+ case "ZodUnion": {
361
+ return this.defaultZodUnionHandler(value);
362
+ }
363
+ case "ZodString": {
364
+ return this.defaultZodStringHandler(value);
365
+ }
366
+ default:
367
+ return value;
368
+ }
369
+ }
370
+ };
371
+
372
+ // src/tools/tool-compatibility/provider-compats/google.ts
373
+ var GoogleToolCompat = class extends ToolCompatibility {
374
+ constructor(model) {
375
+ super(model);
376
+ }
377
+ getSchemaTarget() {
378
+ return "jsonSchema7";
379
+ }
380
+ shouldApply() {
381
+ return this.getModel().provider.includes("google") || this.getModel().modelId.includes("google");
382
+ }
383
+ processZodType(value) {
384
+ switch (value._def.typeName) {
385
+ case "ZodObject": {
386
+ return this.defaultZodObjectHandler(value);
387
+ }
388
+ case "ZodArray": {
389
+ return this.defaultZodArrayHandler(value, []);
390
+ }
391
+ case "ZodUnion": {
392
+ return this.defaultZodUnionHandler(value);
393
+ }
394
+ // Google models support these properties but the model doesn't respect them, but it respects them when they're
395
+ // added to the tool description
396
+ case "ZodString": {
397
+ return this.defaultZodStringHandler(value);
398
+ }
399
+ case "ZodNumber": {
400
+ return this.defaultZodNumberHandler(value);
401
+ }
402
+ default:
403
+ return this.defaultUnsupportedZodTypeHandler(value);
404
+ }
405
+ }
406
+ };
407
+
408
+ // src/tools/tool-compatibility/provider-compats/meta.ts
409
+ var MetaToolCompat = class extends ToolCompatibility {
410
+ constructor(model) {
411
+ super(model);
412
+ }
413
+ getSchemaTarget() {
414
+ return "jsonSchema7";
415
+ }
416
+ shouldApply() {
417
+ return this.getModel().modelId.includes("meta");
418
+ }
419
+ processZodType(value) {
420
+ switch (value._def.typeName) {
421
+ case "ZodObject": {
422
+ return this.defaultZodObjectHandler(value);
423
+ }
424
+ case "ZodArray": {
425
+ return this.defaultZodArrayHandler(value, ["min", "max"]);
426
+ }
427
+ case "ZodUnion": {
428
+ return this.defaultZodUnionHandler(value);
429
+ }
430
+ case "ZodNumber": {
431
+ return this.defaultZodNumberHandler(value);
432
+ }
433
+ case "ZodString": {
434
+ return this.defaultZodStringHandler(value);
435
+ }
436
+ default:
437
+ return value;
438
+ }
439
+ }
440
+ };
441
+
442
+ // src/tools/tool-compatibility/provider-compats/openai.ts
443
+ var OpenAIToolCompat = class extends ToolCompatibility {
444
+ constructor(model) {
445
+ super(model);
446
+ }
447
+ getSchemaTarget() {
448
+ return `jsonSchema7`;
449
+ }
450
+ shouldApply() {
451
+ if (!this.getModel().supportsStructuredOutputs && (this.getModel().provider.includes(`openai`) || this.getModel().modelId.includes(`openai`))) {
452
+ return true;
453
+ }
454
+ return false;
455
+ }
456
+ processZodType(value) {
457
+ switch (value._def.typeName) {
458
+ case "ZodObject": {
459
+ return this.defaultZodObjectHandler(value);
460
+ }
461
+ case "ZodUnion": {
462
+ return this.defaultZodUnionHandler(value);
463
+ }
464
+ case "ZodArray": {
465
+ return this.defaultZodArrayHandler(value);
466
+ }
467
+ case "ZodString": {
468
+ const model = this.getModel();
469
+ const checks = ["emoji"];
470
+ if (model.modelId.includes("gpt-4o-mini")) {
471
+ checks.push("regex");
472
+ }
473
+ return this.defaultZodStringHandler(value, checks);
474
+ }
475
+ default:
476
+ return this.defaultUnsupportedZodTypeHandler(value, ["ZodNever", "ZodUndefined", "ZodTuple"]);
477
+ }
478
+ }
479
+ };
480
+
481
+ // src/tools/tool-compatibility/provider-compats/openai-reasoning.ts
482
+ var OpenAIReasoningToolCompat = class extends ToolCompatibility {
483
+ constructor(model) {
484
+ super(model);
485
+ }
486
+ getSchemaTarget() {
487
+ return `openApi3`;
488
+ }
489
+ isReasoningModel() {
490
+ return this.getModel().modelId.includes(`o3`) || this.getModel().modelId.includes(`o4`);
491
+ }
492
+ shouldApply() {
493
+ if ((this.getModel().supportsStructuredOutputs || this.isReasoningModel()) && (this.getModel().provider.includes(`openai`) || this.getModel().modelId.includes(`openai`))) {
494
+ return true;
495
+ }
496
+ return false;
497
+ }
498
+ processZodType(value) {
499
+ switch (value._def.typeName) {
500
+ case "ZodOptional":
501
+ return value.unwrap().nullable();
502
+ case "ZodObject": {
503
+ return this.defaultZodObjectHandler(value);
504
+ }
505
+ case "ZodArray": {
506
+ return this.defaultZodArrayHandler(value);
507
+ }
508
+ case "ZodUnion": {
509
+ return this.defaultZodUnionHandler(value);
510
+ }
511
+ case "ZodDefault": {
512
+ const defaultDef = value._def;
513
+ const innerType = defaultDef.innerType;
514
+ const defaultValue = defaultDef.defaultValue();
515
+ const constraints = {};
516
+ if (defaultValue !== void 0) {
517
+ constraints.defaultValue = defaultValue;
518
+ }
519
+ const description = this.mergeParameterDescription(value.description, constraints);
520
+ let result = this.processZodType(innerType);
521
+ if (description) {
522
+ result = result.describe(description);
523
+ }
524
+ return result;
525
+ }
526
+ case "ZodNumber": {
527
+ return this.defaultZodNumberHandler(value);
528
+ }
529
+ case "ZodString": {
530
+ return this.defaultZodStringHandler(value);
531
+ }
532
+ case "ZodDate": {
533
+ return this.defaultZodDateHandler(value);
534
+ }
535
+ default:
536
+ return this.defaultUnsupportedZodTypeHandler(value);
537
+ }
538
+ }
539
+ };
540
+
541
+ // src/tools/tool-compatibility/builder.ts
542
+ function convertVercelToolParameters(tool) {
543
+ const schema = tool.parameters ?? z.object({});
544
+ return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));
545
+ }
546
+ function convertInputSchema(tool) {
547
+ const schema = tool.inputSchema ?? z.object({});
548
+ return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));
549
+ }
550
+ var CoreToolBuilder = class extends MastraBase {
551
+ originalTool;
552
+ options;
553
+ logType;
554
+ constructor(input) {
555
+ super({ name: "CoreToolBuilder" });
556
+ this.originalTool = input.originalTool;
557
+ this.options = input.options;
558
+ this.logType = input.logType;
559
+ }
560
+ // Helper to get parameters based on tool type
561
+ getParameters = () => {
562
+ if (isVercelTool(this.originalTool)) {
563
+ return convertVercelToolParameters(this.originalTool);
564
+ }
565
+ return convertInputSchema(this.originalTool);
566
+ };
567
+ // For provider-defined tools, we need to include all required properties
568
+ buildProviderTool(tool) {
569
+ if ("type" in tool && tool.type === "provider-defined" && "id" in tool && typeof tool.id === "string" && tool.id.includes(".")) {
570
+ return {
571
+ type: "provider-defined",
572
+ id: tool.id,
573
+ args: "args" in this.originalTool ? this.originalTool.args : {},
574
+ description: tool.description,
575
+ parameters: this.getParameters(),
576
+ execute: this.originalTool.execute ? this.createExecute(
577
+ this.originalTool,
578
+ { ...this.options, description: this.originalTool.description },
579
+ this.logType
580
+ ) : void 0
581
+ };
582
+ }
583
+ return void 0;
584
+ }
585
+ createLogMessageOptions({ agentName, toolName, type }) {
586
+ if (!agentName) {
587
+ return {
588
+ start: `Executing tool ${toolName}`,
589
+ error: `Failed tool execution`
590
+ };
591
+ }
592
+ const prefix = `[Agent:${agentName}]`;
593
+ const toolType = type === "toolset" ? "toolset" : "tool";
594
+ return {
595
+ start: `${prefix} - Executing ${toolType} ${toolName}`,
596
+ error: `${prefix} - Failed ${toolType} execution`
597
+ };
598
+ }
599
+ createExecute(tool, options, logType) {
600
+ const { logger, mastra: _mastra, memory: _memory, runtimeContext, ...rest } = options;
601
+ const { start, error } = this.createLogMessageOptions({
602
+ agentName: options.agentName,
603
+ toolName: options.name,
604
+ type: logType
605
+ });
606
+ const execFunction = async (args, execOptions) => {
607
+ if (isVercelTool(tool)) {
608
+ return tool?.execute?.(args, execOptions) ?? void 0;
609
+ }
610
+ return tool?.execute?.(
611
+ {
612
+ context: args,
613
+ threadId: options.threadId,
614
+ resourceId: options.resourceId,
615
+ mastra: options.mastra,
616
+ memory: options.memory,
617
+ runId: options.runId,
618
+ runtimeContext: options.runtimeContext ?? new RuntimeContext()
619
+ },
620
+ execOptions
621
+ ) ?? void 0;
622
+ };
623
+ return async (args, execOptions) => {
624
+ try {
625
+ (options.logger || this.logger).debug(start, { ...rest, args });
626
+ return await execFunction(args, execOptions);
627
+ } catch (err) {
628
+ (options.logger || this.logger).error(error, { ...rest, error: err, args });
629
+ throw err;
630
+ }
631
+ };
632
+ }
633
+ build() {
634
+ const providerTool = this.buildProviderTool(this.originalTool);
635
+ if (providerTool) {
636
+ return providerTool;
637
+ }
638
+ const definition = {
639
+ type: "function",
640
+ description: this.originalTool.description,
641
+ parameters: this.getParameters(),
642
+ execute: this.originalTool.execute ? this.createExecute(
643
+ this.originalTool,
644
+ { ...this.options, description: this.originalTool.description },
645
+ this.logType
646
+ ) : void 0
647
+ };
648
+ const model = this.options.model;
649
+ if (model) {
650
+ for (const compat of [
651
+ new OpenAIReasoningToolCompat(model),
652
+ new OpenAIToolCompat(model),
653
+ new GoogleToolCompat(model),
654
+ new AnthropicToolCompat(model),
655
+ new DeepSeekToolCompat(model),
656
+ new MetaToolCompat(model)
657
+ ]) {
658
+ if (compat.shouldApply()) {
659
+ return { ...definition, ...compat.process(this.originalTool) };
660
+ }
661
+ }
662
+ }
663
+ return definition;
664
+ }
665
+ };
666
+
667
+ // src/utils.ts
668
+ var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
669
+ function deepMerge(target, source) {
670
+ const output = { ...target };
671
+ if (!source) return output;
672
+ Object.keys(source).forEach((key) => {
673
+ const targetValue = output[key];
674
+ const sourceValue = source[key];
675
+ if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
676
+ output[key] = sourceValue;
677
+ } else if (sourceValue instanceof Object && targetValue instanceof Object && !Array.isArray(sourceValue) && !Array.isArray(targetValue)) {
678
+ output[key] = deepMerge(targetValue, sourceValue);
679
+ } else if (sourceValue !== void 0) {
680
+ output[key] = sourceValue;
681
+ }
682
+ });
683
+ return output;
684
+ }
685
+ async function* maskStreamTags(stream, tag, options = {}) {
686
+ const { onStart, onEnd, onMask } = options;
687
+ const openTag = `<${tag}>`;
688
+ const closeTag = `</${tag}>`;
689
+ let buffer = "";
690
+ let fullContent = "";
691
+ let isMasking = false;
692
+ let isBuffering = false;
693
+ const trimOutsideDelimiter = (text, delimiter, trim) => {
694
+ if (!text.includes(delimiter)) {
695
+ return text;
696
+ }
697
+ const parts = text.split(delimiter);
698
+ if (trim === `before-start`) {
699
+ return `${delimiter}${parts[1]}`;
700
+ }
701
+ return `${parts[0]}${delimiter}`;
702
+ };
703
+ const startsWith = (text, pattern) => {
704
+ if (pattern.includes(openTag.substring(0, 3))) {
705
+ pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);
706
+ }
707
+ return text.trim().startsWith(pattern.trim());
708
+ };
709
+ for await (const chunk of stream) {
710
+ fullContent += chunk;
711
+ if (isBuffering) buffer += chunk;
712
+ const chunkHasTag = startsWith(chunk, openTag);
713
+ const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);
714
+ let toYieldBeforeMaskedStartTag = ``;
715
+ if (!isMasking && (chunkHasTag || bufferHasTag)) {
716
+ isMasking = true;
717
+ isBuffering = false;
718
+ const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);
719
+ if (taggedTextToMask !== buffer.trim()) {
720
+ toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);
721
+ }
722
+ buffer = "";
723
+ onStart?.();
724
+ }
725
+ if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== "") {
726
+ isBuffering = true;
727
+ buffer += chunk;
728
+ continue;
729
+ }
730
+ if (isBuffering && buffer && !startsWith(openTag, buffer)) {
731
+ yield buffer;
732
+ buffer = "";
733
+ isBuffering = false;
734
+ continue;
735
+ }
736
+ if (isMasking && fullContent.includes(closeTag)) {
737
+ onMask?.(chunk);
738
+ onEnd?.();
739
+ isMasking = false;
740
+ const lastFullContent = fullContent;
741
+ fullContent = ``;
742
+ const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, "after-end");
743
+ if (textUntilEndTag !== lastFullContent) {
744
+ yield lastFullContent.replace(textUntilEndTag, ``);
745
+ }
746
+ continue;
747
+ }
748
+ if (isMasking) {
749
+ onMask?.(chunk);
750
+ if (toYieldBeforeMaskedStartTag) {
751
+ yield toYieldBeforeMaskedStartTag;
752
+ }
753
+ continue;
754
+ }
755
+ yield chunk;
756
+ }
757
+ }
758
+ function resolveSerializedZodOutput(schema) {
759
+ return Function("z", `"use strict";return (${schema});`)(z);
760
+ }
761
+ function isVercelTool(tool) {
762
+ return !!(tool && !(tool instanceof Tool) && "parameters" in tool);
763
+ }
764
+ function isZodType(value) {
765
+ return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
766
+ }
767
+ function createDeterministicId(input) {
768
+ return createHash("sha256").update(input).digest("hex").slice(0, 8);
769
+ }
770
+ function setVercelToolProperties(tool) {
771
+ const inputSchema = convertVercelToolParameters2(tool);
772
+ const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
773
+ return {
774
+ ...tool,
775
+ id: toolId,
776
+ inputSchema
777
+ };
778
+ }
779
+ function ensureToolProperties(tools) {
780
+ const toolsWithProperties = Object.keys(tools).reduce((acc, key) => {
781
+ const tool = tools?.[key];
782
+ if (tool) {
783
+ if (isVercelTool(tool)) {
784
+ acc[key] = setVercelToolProperties(tool);
785
+ } else {
786
+ acc[key] = tool;
787
+ }
788
+ }
789
+ return acc;
790
+ }, {});
791
+ return toolsWithProperties;
792
+ }
793
+ function convertVercelToolParameters2(tool) {
794
+ const schema = tool.parameters ?? z.object({});
795
+ return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));
796
+ }
797
+ function makeCoreTool(originalTool, options, logType) {
798
+ return new CoreToolBuilder({ originalTool, options, logType }).build();
799
+ }
800
+ function createMastraProxy({ mastra, logger }) {
801
+ return new Proxy(mastra, {
802
+ get(target, prop) {
803
+ const hasProp = Reflect.has(target, prop);
804
+ if (hasProp) {
805
+ const value = Reflect.get(target, prop);
806
+ const isFunction = typeof value === "function";
807
+ if (isFunction) {
808
+ return value.bind(target);
809
+ }
810
+ return value;
811
+ }
812
+ if (prop === "logger") {
813
+ logger.warn(`Please use 'getLogger' instead, logger is deprecated`);
814
+ return Reflect.apply(target.getLogger, target, []);
815
+ }
816
+ if (prop === "telemetry") {
817
+ logger.warn(`Please use 'getTelemetry' instead, telemetry is deprecated`);
818
+ return Reflect.apply(target.getTelemetry, target, []);
819
+ }
820
+ if (prop === "storage") {
821
+ logger.warn(`Please use 'getStorage' instead, storage is deprecated`);
822
+ return Reflect.get(target, "storage");
823
+ }
824
+ if (prop === "agents") {
825
+ logger.warn(`Please use 'getAgents' instead, agents is deprecated`);
826
+ return Reflect.apply(target.getAgents, target, []);
827
+ }
828
+ if (prop === "tts") {
829
+ logger.warn(`Please use 'getTTS' instead, tts is deprecated`);
830
+ return Reflect.apply(target.getTTS, target, []);
831
+ }
832
+ if (prop === "vectors") {
833
+ logger.warn(`Please use 'getVectors' instead, vectors is deprecated`);
834
+ return Reflect.apply(target.getVectors, target, []);
835
+ }
836
+ if (prop === "memory") {
837
+ logger.warn(`Please use 'getMemory' instead, memory is deprecated`);
838
+ return Reflect.get(target, "memory");
839
+ }
840
+ return Reflect.get(target, prop);
841
+ }
842
+ });
843
+ }
844
+ function checkEvalStorageFields(traceObject, logger) {
845
+ const missingFields = [];
846
+ if (!traceObject.input) missingFields.push("input");
847
+ if (!traceObject.output) missingFields.push("output");
848
+ if (!traceObject.agentName) missingFields.push("agent_name");
849
+ if (!traceObject.metricName) missingFields.push("metric_name");
850
+ if (!traceObject.instructions) missingFields.push("instructions");
851
+ if (!traceObject.globalRunId) missingFields.push("global_run_id");
852
+ if (!traceObject.runId) missingFields.push("run_id");
853
+ if (missingFields.length > 0) {
854
+ if (logger) {
855
+ logger.warn("Skipping evaluation storage due to missing required fields", {
856
+ missingFields,
857
+ runId: traceObject.runId,
858
+ agentName: traceObject.agentName
859
+ });
860
+ } else {
861
+ console.warn("Skipping evaluation storage due to missing required fields", {
862
+ missingFields,
863
+ runId: traceObject.runId,
864
+ agentName: traceObject.agentName
865
+ });
866
+ }
867
+ return false;
868
+ }
869
+ return true;
870
+ }
871
+ function detectSingleMessageCharacteristics(message) {
872
+ if (typeof message === "object" && message !== null && (message.role === "function" || // UI-only role
873
+ message.role === "data" || // UI-only role
874
+ "toolInvocations" in message || // UI-specific field
875
+ "parts" in message || // UI-specific field
876
+ "experimental_attachments" in message)) {
877
+ return "has-ui-specific-parts";
878
+ } else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || // Core messages can have array content
879
+ "experimental_providerMetadata" in message || "providerOptions" in message)) {
880
+ return "has-core-specific-parts";
881
+ } else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && ["system", "user", "assistant", "tool"].includes(message.role)) {
882
+ return "message";
883
+ } else {
884
+ return "other";
885
+ }
886
+ }
887
+ function isUiMessage(message) {
888
+ return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;
889
+ }
890
+ function isCoreMessage(message) {
891
+ return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));
892
+ }
893
+ function ensureAllMessagesAreCoreMessages(messages) {
894
+ return messages.map((message) => {
895
+ if (isUiMessage(message)) {
896
+ return convertToCoreMessages([message]);
897
+ }
898
+ if (isCoreMessage(message)) {
899
+ return message;
900
+ }
901
+ const characteristics = detectSingleMessageCharacteristics(message);
902
+ throw new Error(
903
+ `Message does not appear to be a core message or a UI message but must be one of the two, found "${characteristics}" type for message:
904
+
905
+ ${JSON.stringify(message, null, 2)}
906
+ `
907
+ );
908
+ }).flat();
909
+ }
910
+
911
+ export { Tool, checkEvalStorageFields, createMastraProxy, createTool, deepMerge, delay, ensureAllMessagesAreCoreMessages, ensureToolProperties, isVercelTool, isZodType, makeCoreTool, maskStreamTags, resolveSerializedZodOutput };