@mastra/ai-sdk 0.0.0-new-button-export-20251219133013 → 0.0.0-om-20260129012647

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 (35) hide show
  1. package/CHANGELOG.md +378 -6
  2. package/dist/chat-route.d.ts +7 -6
  3. package/dist/chat-route.d.ts.map +1 -1
  4. package/dist/{chunk-KYQEM4AK.js → chunk-AAQDCHJY.js} +10 -11
  5. package/dist/chunk-AAQDCHJY.js.map +1 -0
  6. package/dist/{chunk-TD7TJ4N5.cjs → chunk-CCJXHQQO.cjs} +10 -11
  7. package/dist/chunk-CCJXHQQO.cjs.map +1 -0
  8. package/dist/convert-streams.d.ts +4 -3
  9. package/dist/convert-streams.d.ts.map +1 -1
  10. package/dist/helpers.d.ts +3 -3
  11. package/dist/helpers.d.ts.map +1 -1
  12. package/dist/index.cjs +148 -217
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.js +149 -218
  15. package/dist/index.js.map +1 -1
  16. package/dist/middleware.d.ts.map +1 -1
  17. package/dist/network-route.d.ts +5 -6
  18. package/dist/network-route.d.ts.map +1 -1
  19. package/dist/{token-5ZTQBFQ6.cjs → token-36YTPVWD.cjs} +9 -9
  20. package/dist/token-36YTPVWD.cjs.map +1 -0
  21. package/dist/{token-UOO4N54I.js → token-ZFKXETJY.js} +7 -7
  22. package/dist/token-ZFKXETJY.js.map +1 -0
  23. package/dist/token-util-737PGIQA.cjs +9 -0
  24. package/dist/{token-util-DUN56AZR.cjs.map → token-util-737PGIQA.cjs.map} +1 -1
  25. package/dist/token-util-SD2EI4DD.js +7 -0
  26. package/dist/{token-util-JCUK3SCT.js.map → token-util-SD2EI4DD.js.map} +1 -1
  27. package/dist/transformers.d.ts +17 -15
  28. package/dist/transformers.d.ts.map +1 -1
  29. package/package.json +9 -9
  30. package/dist/chunk-KYQEM4AK.js.map +0 -1
  31. package/dist/chunk-TD7TJ4N5.cjs.map +0 -1
  32. package/dist/token-5ZTQBFQ6.cjs.map +0 -1
  33. package/dist/token-UOO4N54I.js.map +0 -1
  34. package/dist/token-util-DUN56AZR.cjs +0 -9
  35. package/dist/token-util-JCUK3SCT.js +0 -7
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@ import { registerApiRoute } from '@mastra/core/server';
2
2
  import * as z4 from 'zod/v4';
3
3
  import { z } from 'zod/v4';
4
4
  import { ZodFirstPartyTypeKind } from 'zod/v3';
5
+ import { TransformStream as TransformStream$1, ReadableStream as ReadableStream$1 } from 'stream/web';
5
6
  import { convertFullStreamChunkToMastra, DefaultGeneratedFile, DefaultGeneratedFileWithType } from '@mastra/core/stream';
6
- import { TripWire, MessageList } from '@mastra/core/agent';
7
+ import { TripWire, MessageList, aiV5ModelMessageToV2PromptMessage } from '@mastra/core/agent';
7
8
  import { RequestContext } from '@mastra/core/di';
8
9
  import { WorkingMemory, MessageHistory, SemanticRecall } from '@mastra/core/processors';
9
10
 
@@ -207,14 +208,18 @@ function filter(obj) {
207
208
  }
208
209
  function secureJsonParse(text2) {
209
210
  const { stackTraceLimit } = Error;
210
- Error.stackTraceLimit = 0;
211
+ try {
212
+ Error.stackTraceLimit = 0;
213
+ } catch (e) {
214
+ return _parse(text2);
215
+ }
211
216
  try {
212
217
  return _parse(text2);
213
218
  } finally {
214
219
  Error.stackTraceLimit = stackTraceLimit;
215
220
  }
216
221
  }
217
- var validatorSymbol = Symbol.for("vercel.ai.validator");
222
+ var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator");
218
223
  function validator(validate) {
219
224
  return { [validatorSymbol]: true, validate };
220
225
  }
@@ -297,7 +302,7 @@ var getRelativePath = (pathA, pathB) => {
297
302
  }
298
303
  return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
299
304
  };
300
- var ignoreOverride = Symbol(
305
+ var ignoreOverride = /* @__PURE__ */ Symbol(
301
306
  "Let zodToJsonSchema decide on which parser to use"
302
307
  );
303
308
  var defaultOptions = {
@@ -332,11 +337,11 @@ function parseAnyDef() {
332
337
  return {};
333
338
  }
334
339
  function parseArrayDef(def, refs) {
335
- var _a17, _b, _c;
340
+ var _a16, _b, _c;
336
341
  const res = {
337
342
  type: "array"
338
343
  };
339
- if (((_a17 = def.type) == null ? void 0 : _a17._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
344
+ if (((_a16 = def.type) == null ? void 0 : _a16._def) && ((_c = (_b = def.type) == null ? void 0 : _b._def) == null ? void 0 : _c.typeName) !== ZodFirstPartyTypeKind.ZodAny) {
340
345
  res.items = parseDef(def.type._def, {
341
346
  ...refs,
342
347
  currentPath: [...refs.currentPath, "items"]
@@ -695,8 +700,8 @@ function escapeNonAlphaNumeric(source) {
695
700
  return result;
696
701
  }
697
702
  function addFormat(schema, value, message, refs) {
698
- var _a17;
699
- if (schema.format || ((_a17 = schema.anyOf) == null ? void 0 : _a17.some((x) => x.format))) {
703
+ var _a16;
704
+ if (schema.format || ((_a16 = schema.anyOf) == null ? void 0 : _a16.some((x) => x.format))) {
700
705
  if (!schema.anyOf) {
701
706
  schema.anyOf = [];
702
707
  }
@@ -715,8 +720,8 @@ function addFormat(schema, value, message, refs) {
715
720
  }
716
721
  }
717
722
  function addPattern(schema, regex, message, refs) {
718
- var _a17;
719
- if (schema.pattern || ((_a17 = schema.allOf) == null ? void 0 : _a17.some((x) => x.pattern))) {
723
+ var _a16;
724
+ if (schema.pattern || ((_a16 = schema.allOf) == null ? void 0 : _a16.some((x) => x.pattern))) {
720
725
  if (!schema.allOf) {
721
726
  schema.allOf = [];
722
727
  }
@@ -735,7 +740,7 @@ function addPattern(schema, regex, message, refs) {
735
740
  }
736
741
  }
737
742
  function stringifyRegExpWithFlags(regex, refs) {
738
- var _a17;
743
+ var _a16;
739
744
  if (!refs.applyRegexFlags || !regex.flags) {
740
745
  return regex.source;
741
746
  }
@@ -765,7 +770,7 @@ function stringifyRegExpWithFlags(regex, refs) {
765
770
  pattern += source[i];
766
771
  pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
767
772
  inCharRange = false;
768
- } else if (source[i + 1] === "-" && ((_a17 = source[i + 2]) == null ? void 0 : _a17.match(/[a-z]/))) {
773
+ } else if (source[i + 1] === "-" && ((_a16 = source[i + 2]) == null ? void 0 : _a16.match(/[a-z]/))) {
769
774
  pattern += source[i];
770
775
  inCharRange = true;
771
776
  } else {
@@ -807,13 +812,13 @@ function stringifyRegExpWithFlags(regex, refs) {
807
812
  return pattern;
808
813
  }
809
814
  function parseRecordDef(def, refs) {
810
- var _a17, _b, _c, _d, _e, _f;
815
+ var _a16, _b, _c, _d, _e, _f;
811
816
  const schema = {
812
817
  type: "object",
813
- additionalProperties: (_a17 = parseDef(def.valueType._def, {
818
+ additionalProperties: (_a16 = parseDef(def.valueType._def, {
814
819
  ...refs,
815
820
  currentPath: [...refs.currentPath, "additionalProperties"]
816
- })) != null ? _a17 : refs.allowedAdditionalProperties
821
+ })) != null ? _a16 : refs.allowedAdditionalProperties
817
822
  };
818
823
  if (((_b = def.keyType) == null ? void 0 : _b._def.typeName) === ZodFirstPartyTypeKind.ZodString && ((_c = def.keyType._def.checks) == null ? void 0 : _c.length)) {
819
824
  const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
@@ -1070,8 +1075,8 @@ function safeIsOptional(schema) {
1070
1075
  }
1071
1076
  }
1072
1077
  var parseOptionalDef = (def, refs) => {
1073
- var _a17;
1074
- if (refs.currentPath.toString() === ((_a17 = refs.propertyPath) == null ? void 0 : _a17.toString())) {
1078
+ var _a16;
1079
+ if (refs.currentPath.toString() === ((_a16 = refs.propertyPath) == null ? void 0 : _a16.toString())) {
1075
1080
  return parseDef(def.innerType._def, refs);
1076
1081
  }
1077
1082
  const innerSchema = parseDef(def.innerType._def, {
@@ -1241,10 +1246,10 @@ var selectParser = (def, typeName, refs) => {
1241
1246
  }
1242
1247
  };
1243
1248
  function parseDef(def, refs, forceResolution = false) {
1244
- var _a17;
1249
+ var _a16;
1245
1250
  const seenItem = refs.seen.get(def);
1246
1251
  if (refs.override) {
1247
- const overrideResult = (_a17 = refs.override) == null ? void 0 : _a17.call(
1252
+ const overrideResult = (_a16 = refs.override) == null ? void 0 : _a16.call(
1248
1253
  refs,
1249
1254
  def,
1250
1255
  refs,
@@ -1310,11 +1315,11 @@ var getRefs = (options) => {
1310
1315
  currentPath,
1311
1316
  propertyPath: void 0,
1312
1317
  seen: new Map(
1313
- Object.entries(_options.definitions).map(([name17, def]) => [
1318
+ Object.entries(_options.definitions).map(([name16, def]) => [
1314
1319
  def._def,
1315
1320
  {
1316
1321
  def: def._def,
1317
- path: [..._options.basePath, _options.definitionPath, name17],
1322
+ path: [..._options.basePath, _options.definitionPath, name16],
1318
1323
  // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1319
1324
  jsonSchema: void 0
1320
1325
  }
@@ -1323,7 +1328,7 @@ var getRefs = (options) => {
1323
1328
  };
1324
1329
  };
1325
1330
  var zodToJsonSchema = (schema, options) => {
1326
- var _a17;
1331
+ var _a16;
1327
1332
  const refs = getRefs(options);
1328
1333
  let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce(
1329
1334
  (acc, [name23, schema2]) => {
@@ -1342,31 +1347,31 @@ var zodToJsonSchema = (schema, options) => {
1342
1347
  },
1343
1348
  {}
1344
1349
  ) : void 0;
1345
- const name17 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1346
- const main = (_a17 = parseDef(
1350
+ const name16 = typeof options === "string" ? options : (options == null ? void 0 : options.nameStrategy) === "title" ? void 0 : options == null ? void 0 : options.name;
1351
+ const main = (_a16 = parseDef(
1347
1352
  schema._def,
1348
- name17 === void 0 ? refs : {
1353
+ name16 === void 0 ? refs : {
1349
1354
  ...refs,
1350
- currentPath: [...refs.basePath, refs.definitionPath, name17]
1355
+ currentPath: [...refs.basePath, refs.definitionPath, name16]
1351
1356
  },
1352
1357
  false
1353
- )) != null ? _a17 : parseAnyDef();
1358
+ )) != null ? _a16 : parseAnyDef();
1354
1359
  const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1355
1360
  if (title !== void 0) {
1356
1361
  main.title = title;
1357
1362
  }
1358
- const combined = name17 === void 0 ? definitions ? {
1363
+ const combined = name16 === void 0 ? definitions ? {
1359
1364
  ...main,
1360
1365
  [refs.definitionPath]: definitions
1361
1366
  } : main : {
1362
1367
  $ref: [
1363
1368
  ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1364
1369
  refs.definitionPath,
1365
- name17
1370
+ name16
1366
1371
  ].join("/"),
1367
1372
  [refs.definitionPath]: {
1368
1373
  ...definitions,
1369
- [name17]: main
1374
+ [name16]: main
1370
1375
  }
1371
1376
  };
1372
1377
  combined.$schema = "http://json-schema.org/draft-07/schema#";
@@ -1374,8 +1379,8 @@ var zodToJsonSchema = (schema, options) => {
1374
1379
  };
1375
1380
  var zod_to_json_schema_default = zodToJsonSchema;
1376
1381
  function zod3Schema(zodSchema2, options) {
1377
- var _a17;
1378
- const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
1382
+ var _a16;
1383
+ const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
1379
1384
  return jsonSchema(
1380
1385
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1381
1386
  () => zod_to_json_schema_default(zodSchema2, {
@@ -1390,8 +1395,8 @@ function zod3Schema(zodSchema2, options) {
1390
1395
  );
1391
1396
  }
1392
1397
  function zod4Schema(zodSchema2, options) {
1393
- var _a17;
1394
- const useReferences = (_a17 = void 0 ) != null ? _a17 : false;
1398
+ var _a16;
1399
+ const useReferences = (_a16 = void 0 ) != null ? _a16 : false;
1395
1400
  return jsonSchema(
1396
1401
  // defer json schema creation to avoid unnecessary computation when only validation is needed
1397
1402
  () => z4.toJSONSchema(zodSchema2, {
@@ -1417,7 +1422,7 @@ function zodSchema(zodSchema2, options) {
1417
1422
  return zod3Schema(zodSchema2);
1418
1423
  }
1419
1424
  }
1420
- var schemaSymbol = Symbol.for("vercel.ai.schema");
1425
+ var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1421
1426
  function jsonSchema(jsonSchema2, {
1422
1427
  validate
1423
1428
  } = {}) {
@@ -1446,13 +1451,13 @@ function asSchema(schema) {
1446
1451
  }
1447
1452
  var __defProp = Object.defineProperty;
1448
1453
  var __export = (target, all) => {
1449
- for (var name17 in all)
1450
- __defProp(target, name17, { get: all[name17], enumerable: true });
1454
+ for (var name16 in all)
1455
+ __defProp(target, name16, { get: all[name16], enumerable: true });
1451
1456
  };
1452
- var name72 = "AI_NoObjectGeneratedError";
1453
- var marker72 = `vercel.ai.error.${name72}`;
1454
- var symbol72 = Symbol.for(marker72);
1455
- var _a72;
1457
+ var name62 = "AI_NoObjectGeneratedError";
1458
+ var marker62 = `vercel.ai.error.${name62}`;
1459
+ var symbol62 = Symbol.for(marker62);
1460
+ var _a62;
1456
1461
  var NoObjectGeneratedError = class extends AISDKError {
1457
1462
  constructor({
1458
1463
  message = "No object generated.",
@@ -1462,18 +1467,18 @@ var NoObjectGeneratedError = class extends AISDKError {
1462
1467
  usage,
1463
1468
  finishReason
1464
1469
  }) {
1465
- super({ name: name72, message, cause });
1466
- this[_a72] = true;
1470
+ super({ name: name62, message, cause });
1471
+ this[_a62] = true;
1467
1472
  this.text = text2;
1468
1473
  this.response = response;
1469
1474
  this.usage = usage;
1470
1475
  this.finishReason = finishReason;
1471
1476
  }
1472
1477
  static isInstance(error) {
1473
- return AISDKError.hasMarker(error, marker72);
1478
+ return AISDKError.hasMarker(error, marker62);
1474
1479
  }
1475
1480
  };
1476
- _a72 = symbol72;
1481
+ _a62 = symbol62;
1477
1482
  var dataContentSchema = z.union([
1478
1483
  z.string(),
1479
1484
  z.instanceof(Uint8Array),
@@ -1481,8 +1486,8 @@ var dataContentSchema = z.union([
1481
1486
  z.custom(
1482
1487
  // Buffer might not be available in some environments such as CloudFlare:
1483
1488
  (value) => {
1484
- var _a17, _b;
1485
- return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
1489
+ var _a16, _b;
1490
+ return (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;
1486
1491
  },
1487
1492
  { message: "Must be a Buffer" }
1488
1493
  )
@@ -2071,7 +2076,7 @@ function processUIMessageStream({
2071
2076
  new TransformStream({
2072
2077
  async transform(chunk, controller) {
2073
2078
  await runUpdateMessageJob(async ({ state, write }) => {
2074
- var _a17, _b, _c, _d;
2079
+ var _a16, _b, _c, _d;
2075
2080
  function getToolInvocation(toolCallId) {
2076
2081
  const toolInvocations = state.message.parts.filter(isToolUIPart);
2077
2082
  const toolInvocation = toolInvocations.find(
@@ -2099,7 +2104,7 @@ function processUIMessageStream({
2099
2104
  return toolInvocation;
2100
2105
  }
2101
2106
  function updateToolPart(options) {
2102
- var _a18;
2107
+ var _a17;
2103
2108
  const part = state.message.parts.find(
2104
2109
  (part2) => isToolUIPart(part2) && part2.toolCallId === options.toolCallId
2105
2110
  );
@@ -2112,7 +2117,7 @@ function processUIMessageStream({
2112
2117
  anyPart.errorText = anyOptions.errorText;
2113
2118
  anyPart.rawInput = anyOptions.rawInput;
2114
2119
  anyPart.preliminary = anyOptions.preliminary;
2115
- anyPart.providerExecuted = (_a18 = anyOptions.providerExecuted) != null ? _a18 : part.providerExecuted;
2120
+ anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
2116
2121
  if (anyOptions.providerMetadata != null && part.state === "input-available") {
2117
2122
  part.callProviderMetadata = anyOptions.providerMetadata;
2118
2123
  }
@@ -2132,7 +2137,7 @@ function processUIMessageStream({
2132
2137
  }
2133
2138
  }
2134
2139
  function updateDynamicToolPart(options) {
2135
- var _a18;
2140
+ var _a17, _b2;
2136
2141
  const part = state.message.parts.find(
2137
2142
  (part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
2138
2143
  );
@@ -2144,8 +2149,9 @@ function processUIMessageStream({
2144
2149
  anyPart.input = anyOptions.input;
2145
2150
  anyPart.output = anyOptions.output;
2146
2151
  anyPart.errorText = anyOptions.errorText;
2147
- anyPart.rawInput = (_a18 = anyOptions.rawInput) != null ? _a18 : anyPart.rawInput;
2152
+ anyPart.rawInput = (_a17 = anyOptions.rawInput) != null ? _a17 : anyPart.rawInput;
2148
2153
  anyPart.preliminary = anyOptions.preliminary;
2154
+ anyPart.providerExecuted = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;
2149
2155
  if (anyOptions.providerMetadata != null && part.state === "input-available") {
2150
2156
  part.callProviderMetadata = anyOptions.providerMetadata;
2151
2157
  }
@@ -2159,6 +2165,7 @@ function processUIMessageStream({
2159
2165
  output: anyOptions.output,
2160
2166
  errorText: anyOptions.errorText,
2161
2167
  preliminary: anyOptions.preliminary,
2168
+ providerExecuted: anyOptions.providerExecuted,
2162
2169
  ...anyOptions.providerMetadata != null ? { callProviderMetadata: anyOptions.providerMetadata } : {}
2163
2170
  });
2164
2171
  }
@@ -2191,7 +2198,7 @@ function processUIMessageStream({
2191
2198
  case "text-delta": {
2192
2199
  const textPart = state.activeTextParts[chunk.id];
2193
2200
  textPart.text += chunk.delta;
2194
- textPart.providerMetadata = (_a17 = chunk.providerMetadata) != null ? _a17 : textPart.providerMetadata;
2201
+ textPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;
2195
2202
  write();
2196
2203
  break;
2197
2204
  }
@@ -2275,7 +2282,8 @@ function processUIMessageStream({
2275
2282
  toolCallId: chunk.toolCallId,
2276
2283
  toolName: chunk.toolName,
2277
2284
  state: "input-streaming",
2278
- input: void 0
2285
+ input: void 0,
2286
+ providerExecuted: chunk.providerExecuted
2279
2287
  });
2280
2288
  } else {
2281
2289
  updateToolPart({
@@ -2320,6 +2328,7 @@ function processUIMessageStream({
2320
2328
  toolName: chunk.toolName,
2321
2329
  state: "input-available",
2322
2330
  input: chunk.input,
2331
+ providerExecuted: chunk.providerExecuted,
2323
2332
  providerMetadata: chunk.providerMetadata
2324
2333
  });
2325
2334
  } else {
@@ -2348,6 +2357,7 @@ function processUIMessageStream({
2348
2357
  state: "output-error",
2349
2358
  input: chunk.input,
2350
2359
  errorText: chunk.errorText,
2360
+ providerExecuted: chunk.providerExecuted,
2351
2361
  providerMetadata: chunk.providerMetadata
2352
2362
  });
2353
2363
  } else {
@@ -2403,7 +2413,8 @@ function processUIMessageStream({
2403
2413
  toolName: toolInvocation.toolName,
2404
2414
  state: "output-error",
2405
2415
  input: toolInvocation.input,
2406
- errorText: chunk.errorText
2416
+ errorText: chunk.errorText,
2417
+ providerExecuted: chunk.providerExecuted
2407
2418
  });
2408
2419
  } else {
2409
2420
  const toolInvocation = getToolInvocation(chunk.toolCallId);
@@ -2413,7 +2424,8 @@ function processUIMessageStream({
2413
2424
  state: "output-error",
2414
2425
  input: toolInvocation.input,
2415
2426
  rawInput: toolInvocation.rawInput,
2416
- errorText: chunk.errorText
2427
+ errorText: chunk.errorText,
2428
+ providerExecuted: chunk.providerExecuted
2417
2429
  });
2418
2430
  }
2419
2431
  write();
@@ -2439,6 +2451,9 @@ function processUIMessageStream({
2439
2451
  break;
2440
2452
  }
2441
2453
  case "finish": {
2454
+ if (chunk.finishReason != null) {
2455
+ state.finishReason = chunk.finishReason;
2456
+ }
2442
2457
  await updateMessageMetadata(chunk.messageMetadata);
2443
2458
  if (chunk.messageMetadata != null) {
2444
2459
  write();
@@ -2544,7 +2559,8 @@ function handleUIMessageStreamFinish({
2544
2559
  messages: [
2545
2560
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
2546
2561
  state.message
2547
- ]
2562
+ ],
2563
+ finishReason: state.finishReason
2548
2564
  });
2549
2565
  };
2550
2566
  return processUIMessageStream({
@@ -2651,7 +2667,7 @@ var wrapLanguageModel = ({
2651
2667
  modelId,
2652
2668
  providerId
2653
2669
  }) => {
2654
- return asArray(middlewareArg).reverse().reduce((wrappedModel, middleware) => {
2670
+ return [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {
2655
2671
  return doWrap({ model: wrappedModel, middleware, modelId, providerId });
2656
2672
  }, model);
2657
2673
  };
@@ -2668,7 +2684,7 @@ var doWrap = ({
2668
2684
  modelId,
2669
2685
  providerId
2670
2686
  }) => {
2671
- var _a17, _b, _c;
2687
+ var _a16, _b, _c;
2672
2688
  async function doTransform({
2673
2689
  params,
2674
2690
  type
@@ -2677,7 +2693,7 @@ var doWrap = ({
2677
2693
  }
2678
2694
  return {
2679
2695
  specificationVersion: "v2",
2680
- provider: (_a17 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a17 : model.provider,
2696
+ provider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,
2681
2697
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
2682
2698
  supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
2683
2699
  async doGenerate(params) {
@@ -2699,130 +2715,6 @@ var doWrap = ({
2699
2715
  }
2700
2716
  };
2701
2717
  };
2702
- var ClientOrServerImplementationSchema = z.looseObject({
2703
- name: z.string(),
2704
- version: z.string()
2705
- });
2706
- var BaseParamsSchema = z.looseObject({
2707
- _meta: z.optional(z.object({}).loose())
2708
- });
2709
- var ResultSchema = BaseParamsSchema;
2710
- var RequestSchema = z.object({
2711
- method: z.string(),
2712
- params: z.optional(BaseParamsSchema)
2713
- });
2714
- var ServerCapabilitiesSchema = z.looseObject({
2715
- experimental: z.optional(z.object({}).loose()),
2716
- logging: z.optional(z.object({}).loose()),
2717
- prompts: z.optional(
2718
- z.looseObject({
2719
- listChanged: z.optional(z.boolean())
2720
- })
2721
- ),
2722
- resources: z.optional(
2723
- z.looseObject({
2724
- subscribe: z.optional(z.boolean()),
2725
- listChanged: z.optional(z.boolean())
2726
- })
2727
- ),
2728
- tools: z.optional(
2729
- z.looseObject({
2730
- listChanged: z.optional(z.boolean())
2731
- })
2732
- )
2733
- });
2734
- ResultSchema.extend({
2735
- protocolVersion: z.string(),
2736
- capabilities: ServerCapabilitiesSchema,
2737
- serverInfo: ClientOrServerImplementationSchema,
2738
- instructions: z.optional(z.string())
2739
- });
2740
- var PaginatedResultSchema = ResultSchema.extend({
2741
- nextCursor: z.optional(z.string())
2742
- });
2743
- var ToolSchema = z.object({
2744
- name: z.string(),
2745
- description: z.optional(z.string()),
2746
- inputSchema: z.object({
2747
- type: z.literal("object"),
2748
- properties: z.optional(z.object({}).loose())
2749
- }).loose()
2750
- }).loose();
2751
- PaginatedResultSchema.extend({
2752
- tools: z.array(ToolSchema)
2753
- });
2754
- var TextContentSchema = z.object({
2755
- type: z.literal("text"),
2756
- text: z.string()
2757
- }).loose();
2758
- var ImageContentSchema = z.object({
2759
- type: z.literal("image"),
2760
- data: z.base64(),
2761
- mimeType: z.string()
2762
- }).loose();
2763
- var ResourceContentsSchema = z.object({
2764
- /**
2765
- * The URI of this resource.
2766
- */
2767
- uri: z.string(),
2768
- /**
2769
- * The MIME type of this resource, if known.
2770
- */
2771
- mimeType: z.optional(z.string())
2772
- }).loose();
2773
- var TextResourceContentsSchema = ResourceContentsSchema.extend({
2774
- text: z.string()
2775
- });
2776
- var BlobResourceContentsSchema = ResourceContentsSchema.extend({
2777
- blob: z.base64()
2778
- });
2779
- var EmbeddedResourceSchema = z.object({
2780
- type: z.literal("resource"),
2781
- resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema])
2782
- }).loose();
2783
- ResultSchema.extend({
2784
- content: z.array(
2785
- z.union([TextContentSchema, ImageContentSchema, EmbeddedResourceSchema])
2786
- ),
2787
- isError: z.boolean().default(false).optional()
2788
- }).or(
2789
- ResultSchema.extend({
2790
- toolResult: z.unknown()
2791
- })
2792
- );
2793
- var JSONRPC_VERSION = "2.0";
2794
- var JSONRPCRequestSchema = z.object({
2795
- jsonrpc: z.literal(JSONRPC_VERSION),
2796
- id: z.union([z.string(), z.number().int()])
2797
- }).merge(RequestSchema).strict();
2798
- var JSONRPCResponseSchema = z.object({
2799
- jsonrpc: z.literal(JSONRPC_VERSION),
2800
- id: z.union([z.string(), z.number().int()]),
2801
- result: ResultSchema
2802
- }).strict();
2803
- var JSONRPCErrorSchema = z.object({
2804
- jsonrpc: z.literal(JSONRPC_VERSION),
2805
- id: z.union([z.string(), z.number().int()]),
2806
- error: z.object({
2807
- code: z.number().int(),
2808
- message: z.string(),
2809
- data: z.optional(z.unknown())
2810
- })
2811
- }).strict();
2812
- var JSONRPCNotificationSchema = z.object({
2813
- jsonrpc: z.literal(JSONRPC_VERSION)
2814
- }).merge(
2815
- z.object({
2816
- method: z.string(),
2817
- params: z.optional(BaseParamsSchema)
2818
- })
2819
- ).strict();
2820
- z.union([
2821
- JSONRPCRequestSchema,
2822
- JSONRPCNotificationSchema,
2823
- JSONRPCResponseSchema,
2824
- JSONRPCErrorSchema
2825
- ]);
2826
2718
  function createUIMessageStream({
2827
2719
  execute,
2828
2720
  onError = getErrorMessage2,
@@ -3087,7 +2979,8 @@ function convertMastraChunkToAISDKv5({
3087
2979
  runId: chunk.runId,
3088
2980
  toolCallId: chunk.payload.toolCallId,
3089
2981
  toolName: chunk.payload.toolName,
3090
- args: chunk.payload.args
2982
+ args: chunk.payload.args,
2983
+ resumeSchema: chunk.payload.resumeSchema
3091
2984
  }
3092
2985
  };
3093
2986
  case "tool-call-suspended":
@@ -3098,7 +2991,8 @@ function convertMastraChunkToAISDKv5({
3098
2991
  runId: chunk.runId,
3099
2992
  toolCallId: chunk.payload.toolCallId,
3100
2993
  toolName: chunk.payload.toolName,
3101
- suspendPayload: chunk.payload.suspendPayload
2994
+ suspendPayload: chunk.payload.suspendPayload,
2995
+ resumeSchema: chunk.payload.resumeSchema
3102
2996
  }
3103
2997
  };
3104
2998
  case "tool-call-input-streaming-start":
@@ -3364,7 +3258,8 @@ function convertFullStreamChunkToUIMessageStream({
3364
3258
  ${JSON.stringify(part)}`
3365
3259
  );
3366
3260
  }
3367
- return part.output;
3261
+ const { type, data, id } = part.output;
3262
+ return { type, data, ...id !== void 0 && { id } };
3368
3263
  }
3369
3264
  return;
3370
3265
  }
@@ -3426,7 +3321,8 @@ function convertFullStreamChunkToUIMessageStream({
3426
3321
  ${JSON.stringify(part)}`
3427
3322
  );
3428
3323
  }
3429
- return part;
3324
+ const { type, data, id } = part;
3325
+ return { type, data, ...id !== void 0 && { id } };
3430
3326
  }
3431
3327
  return;
3432
3328
  }
@@ -3434,12 +3330,12 @@ function convertFullStreamChunkToUIMessageStream({
3434
3330
  }
3435
3331
 
3436
3332
  // src/transformers.ts
3437
- var PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
3333
+ var PRIMITIVE_CACHE_SYMBOL = /* @__PURE__ */ Symbol("primitive-cache");
3438
3334
  function WorkflowStreamToAISDKTransformer({
3439
3335
  includeTextStreamParts
3440
3336
  } = {}) {
3441
3337
  const bufferedWorkflows = /* @__PURE__ */ new Map();
3442
- return new TransformStream({
3338
+ return new TransformStream$1({
3443
3339
  start(controller) {
3444
3340
  controller.enqueue({
3445
3341
  type: "start"
@@ -3458,7 +3354,7 @@ function WorkflowStreamToAISDKTransformer({
3458
3354
  }
3459
3355
  function AgentNetworkToAISDKTransformer() {
3460
3356
  const bufferedNetworks = /* @__PURE__ */ new Map();
3461
- return new TransformStream({
3357
+ return new TransformStream$1({
3462
3358
  start(controller) {
3463
3359
  controller.enqueue({
3464
3360
  type: "start"
@@ -3471,14 +3367,22 @@ function AgentNetworkToAISDKTransformer() {
3471
3367
  },
3472
3368
  transform(chunk, controller) {
3473
3369
  const transformed = transformNetwork(chunk, bufferedNetworks);
3474
- if (transformed) controller.enqueue(transformed);
3370
+ if (transformed) {
3371
+ if (Array.isArray(transformed)) {
3372
+ for (const item of transformed) {
3373
+ controller.enqueue(item);
3374
+ }
3375
+ } else {
3376
+ controller.enqueue(transformed);
3377
+ }
3378
+ }
3475
3379
  }
3476
3380
  });
3477
3381
  }
3478
3382
  function AgentStreamToAISDKTransformer({
3479
3383
  lastMessageId,
3480
- sendStart,
3481
- sendFinish,
3384
+ sendStart = true,
3385
+ sendFinish = true,
3482
3386
  sendReasoning,
3483
3387
  sendSources,
3484
3388
  messageMetadata,
@@ -3487,7 +3391,7 @@ function AgentStreamToAISDKTransformer({
3487
3391
  let bufferedSteps = /* @__PURE__ */ new Map();
3488
3392
  let tripwireOccurred = false;
3489
3393
  let finishEventSent = false;
3490
- return new TransformStream({
3394
+ return new TransformStream$1({
3491
3395
  transform(chunk, controller) {
3492
3396
  if (chunk.type === "tripwire") {
3493
3397
  tripwireOccurred = true;
@@ -3784,7 +3688,8 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
3784
3688
  ${JSON.stringify(output)}`
3785
3689
  );
3786
3690
  }
3787
- return output;
3691
+ const { type, data, id } = output;
3692
+ return { type, data, ...id !== void 0 && { id } };
3788
3693
  }
3789
3694
  return null;
3790
3695
  }
@@ -3796,7 +3701,12 @@ function transformWorkflow(payload, bufferedWorkflows, isNested, includeTextStre
3796
3701
  ${JSON.stringify(payload)}`
3797
3702
  );
3798
3703
  }
3799
- return payload;
3704
+ const { type, data, id } = payload;
3705
+ return {
3706
+ type,
3707
+ data,
3708
+ ...id !== void 0 && { id }
3709
+ };
3800
3710
  }
3801
3711
  return null;
3802
3712
  }
@@ -3810,7 +3720,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
3810
3720
  name: payload.payload.networkId,
3811
3721
  steps: [],
3812
3722
  usage: null,
3813
- output: null
3723
+ output: null,
3724
+ hasEmittedText: false
3814
3725
  });
3815
3726
  }
3816
3727
  const current = bufferedNetworks.get(payload.runId);
@@ -3845,6 +3756,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
3845
3756
  case "routing-agent-text-start": {
3846
3757
  const current = bufferedNetworks.get(payload.runId);
3847
3758
  if (!current) return null;
3759
+ current.hasEmittedText = true;
3848
3760
  return {
3849
3761
  type: "text-start",
3850
3762
  id: payload.runId
@@ -3853,6 +3765,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
3853
3765
  case "routing-agent-text-delta": {
3854
3766
  const current = bufferedNetworks.get(payload.runId);
3855
3767
  if (!current) return null;
3768
+ current.hasEmittedText = true;
3856
3769
  return {
3857
3770
  type: "text-delta",
3858
3771
  id: payload.runId,
@@ -4027,15 +3940,25 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
4027
3940
  case "network-execution-event-step-finish": {
4028
3941
  const current = bufferedNetworks.get(payload.runId);
4029
3942
  if (!current) return null;
4030
- return {
3943
+ const resultText = payload.payload?.result;
3944
+ const dataNetworkChunk = {
4031
3945
  type: isNested ? "data-tool-network" : "data-network",
4032
3946
  id: payload.runId,
4033
3947
  data: {
4034
3948
  ...current,
4035
3949
  status: "finished",
4036
- output: payload.payload?.result ?? current.output
3950
+ output: resultText ?? current.output
4037
3951
  }
4038
3952
  };
3953
+ if (!current.hasEmittedText && resultText && typeof resultText === "string" && resultText.length > 0) {
3954
+ current.hasEmittedText = true;
3955
+ return [
3956
+ { type: "text-start", id: payload.runId },
3957
+ { type: "text-delta", id: payload.runId, delta: resultText },
3958
+ dataNetworkChunk
3959
+ ];
3960
+ }
3961
+ return dataNetworkChunk;
4039
3962
  }
4040
3963
  case "network-execution-event-finish": {
4041
3964
  const current = bufferedNetworks.get(payload.runId);
@@ -4051,6 +3974,10 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
4051
3974
  }
4052
3975
  };
4053
3976
  }
3977
+ case "network-object":
3978
+ case "network-object-result": {
3979
+ return null;
3980
+ }
4054
3981
  default: {
4055
3982
  if (isAgentExecutionDataChunkType(payload)) {
4056
3983
  if (!("data" in payload.payload)) {
@@ -4059,8 +3986,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
4059
3986
  ${JSON.stringify(payload)}`
4060
3987
  );
4061
3988
  }
4062
- const { type, data } = payload.payload;
4063
- return { type, data };
3989
+ const { type, data, id } = payload.payload;
3990
+ return { type, data, ...id !== void 0 && { id } };
4064
3991
  }
4065
3992
  if (isWorkflowExecutionDataChunkType(payload)) {
4066
3993
  if (!("data" in payload.payload)) {
@@ -4069,8 +3996,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
4069
3996
  ${JSON.stringify(payload)}`
4070
3997
  );
4071
3998
  }
4072
- const { type, data } = payload.payload;
4073
- return { type, data };
3999
+ const { type, data, id } = payload.payload;
4000
+ return { type, data, ...id !== void 0 && { id } };
4074
4001
  }
4075
4002
  if (payload.type.startsWith("agent-execution-event-")) {
4076
4003
  const stepId = payload.payload.runId;
@@ -4130,8 +4057,8 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
4130
4057
  ${JSON.stringify(payload)}`
4131
4058
  );
4132
4059
  }
4133
- const { type, data } = payload;
4134
- return { type, data };
4060
+ const { type, data, id } = payload;
4061
+ return { type, data, ...id !== void 0 && { id } };
4135
4062
  }
4136
4063
  return null;
4137
4064
  }
@@ -4179,7 +4106,7 @@ async function handleChatStream({
4179
4106
  sendReasoning = false,
4180
4107
  sendSources = false
4181
4108
  }) {
4182
- const { messages, resumeData, runId, requestContext, ...rest } = params;
4109
+ const { messages, resumeData, runId, requestContext, trigger, ...rest } = params;
4183
4110
  if (resumeData && !runId) {
4184
4111
  throw new Error("runId is required when resumeData is provided");
4185
4112
  }
@@ -4190,20 +4117,24 @@ async function handleChatStream({
4190
4117
  if (!Array.isArray(messages)) {
4191
4118
  throw new Error("Messages must be an array of UIMessage objects");
4192
4119
  }
4193
- const mergedOptions = {
4194
- ...defaultOptions2,
4195
- ...rest,
4196
- ...runId && { runId },
4197
- requestContext: requestContext || defaultOptions2?.requestContext
4198
- };
4199
- const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messages, mergedOptions);
4200
4120
  let lastMessageId;
4201
- if (messages.length) {
4121
+ let messagesToSend = messages;
4122
+ if (messages.length > 0) {
4202
4123
  const lastMessage = messages[messages.length - 1];
4203
4124
  if (lastMessage?.role === "assistant") {
4204
4125
  lastMessageId = lastMessage.id;
4126
+ if (trigger === "regenerate-message") {
4127
+ messagesToSend = messages.slice(0, -1);
4128
+ }
4205
4129
  }
4206
4130
  }
4131
+ const mergedOptions = {
4132
+ ...defaultOptions2,
4133
+ ...rest,
4134
+ ...runId && { runId },
4135
+ requestContext: requestContext || defaultOptions2?.requestContext
4136
+ };
4137
+ const result = resumeData ? await agentObj.resumeStream(resumeData, mergedOptions) : await agentObj.stream(messagesToSend, mergedOptions);
4207
4138
  return createUIMessageStream({
4208
4139
  originalMessages: messages,
4209
4140
  execute: async ({ writer }) => {
@@ -4710,7 +4641,7 @@ function createProcessorMiddleware(options) {
4710
4641
  }
4711
4642
  }
4712
4643
  }
4713
- const newPrompt = messageList.get.all.aiV5.prompt().map(MessageList.aiV5ModelMessageToV2PromptMessage);
4644
+ const newPrompt = messageList.get.all.aiV5.prompt().map(aiV5ModelMessageToV2PromptMessage);
4714
4645
  return {
4715
4646
  ...params,
4716
4647
  prompt: newPrompt
@@ -4802,7 +4733,7 @@ function createProcessorMiddleware(options) {
4802
4733
  const processorStates = /* @__PURE__ */ new Map();
4803
4734
  const runId = crypto.randomUUID();
4804
4735
  const transformedStream = stream.pipeThrough(
4805
- new TransformStream({
4736
+ new TransformStream$1({
4806
4737
  async transform(chunk, controller) {
4807
4738
  let mastraChunk = convertFullStreamChunkToMastra(
4808
4739
  chunk,
@@ -4862,7 +4793,7 @@ function createProcessorMiddleware(options) {
4862
4793
  };
4863
4794
  }
4864
4795
  function createBlockedStream(reason) {
4865
- return new ReadableStream({
4796
+ return new ReadableStream$1({
4866
4797
  start(controller) {
4867
4798
  const id = crypto.randomUUID();
4868
4799
  controller.enqueue({