ai 7.0.79 → 7.0.83

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 (59) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/index.d.ts +139 -53
  3. package/dist/index.js +872 -496
  4. package/dist/index.js.map +1 -1
  5. package/dist/internal/index.d.ts +9 -1
  6. package/dist/internal/index.js +4 -2
  7. package/dist/internal/index.js.map +1 -1
  8. package/dist/test/index.d.ts +4 -1
  9. package/dist/test/index.js +4 -0
  10. package/dist/test/index.js.map +1 -1
  11. package/docs/03-agents/06-policy-tool-approvals.mdx +1 -1
  12. package/docs/03-agents/06-tool-approvals.mdx +6 -0
  13. package/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx +6 -4
  14. package/docs/03-ai-sdk-core/50-error-handling.mdx +17 -2
  15. package/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx +6 -0
  16. package/docs/04-ai-sdk-ui/50-stream-protocol.mdx +2 -2
  17. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +1 -1
  18. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +8 -7
  19. package/docs/07-reference/01-ai-sdk-core/06-embed-many.mdx +6 -2
  20. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +1 -1
  21. package/docs/07-reference/02-ai-sdk-ui/31-convert-to-model-messages.mdx +2 -2
  22. package/docs/07-reference/02-ai-sdk-ui/40-create-ui-message-stream.mdx +35 -6
  23. package/docs/07-reference/04-ai-sdk-workflow/03-generate-video.mdx +157 -0
  24. package/docs/07-reference/04-ai-sdk-workflow/index.mdx +6 -0
  25. package/docs/07-reference/05-ai-sdk-errors/ai-stream-provider-error.mdx +52 -0
  26. package/docs/07-reference/05-ai-sdk-errors/index.mdx +1 -0
  27. package/package.json +14 -3
  28. package/src/agent/create-agent-ui-stream.ts +2 -2
  29. package/src/embed/embed-many.ts +78 -8
  30. package/src/error/index.ts +1 -0
  31. package/src/error/stream-provider-error.ts +78 -0
  32. package/src/generate-text/execute-tools-from-stream.ts +3 -0
  33. package/src/generate-text/generate-text-result.ts +2 -1
  34. package/src/generate-text/generate-text.ts +6 -3
  35. package/src/generate-text/stream-language-model-call.ts +8 -0
  36. package/src/generate-text/to-response-messages.ts +1 -0
  37. package/src/generate-text/tool-approval-configuration.ts +5 -1
  38. package/src/generate-text/tool-approval-request-output.ts +5 -0
  39. package/src/middleware/wrap-embedding-model.ts +11 -2
  40. package/src/model/get-embedding-model-max-input-bytes-per-call.ts +15 -0
  41. package/src/prompt/content-part.ts +1 -0
  42. package/src/prompt/normalize-stream-provider-error.ts +131 -0
  43. package/src/test/mock-embedding-model-v4.ts +9 -0
  44. package/src/ui/convert-to-model-messages.ts +3 -0
  45. package/src/ui/direct-chat-transport.ts +2 -2
  46. package/src/ui/last-assistant-message-is-complete-with-approval-responses.ts +1 -0
  47. package/src/ui/process-ui-message-stream.ts +6 -0
  48. package/src/ui/ui-messages.ts +10 -0
  49. package/src/ui/validate-ui-messages.ts +146 -55
  50. package/src/ui-message-stream/create-ui-message-stream.ts +47 -17
  51. package/src/ui-message-stream/handle-ui-message-stream-finish.ts +51 -14
  52. package/src/ui-message-stream/index.ts +5 -1
  53. package/src/ui-message-stream/to-ui-message-chunk.ts +1 -0
  54. package/src/ui-message-stream/to-ui-message-stream.ts +108 -26
  55. package/src/ui-message-stream/ui-message-chunks.ts +2 -0
  56. package/src/ui-message-stream/ui-message-stream-on-end-callback.ts +7 -0
  57. package/src/ui-message-stream/ui-message-stream-outcome.ts +12 -0
  58. package/src/ui-message-stream/ui-message-stream-writer.ts +15 -0
  59. package/src/util/create-stitchable-stream.ts +31 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __export = (target, all) => {
3
- for (var name23 in all)
4
- __defProp(target, name23, { get: all[name23], enumerable: true });
3
+ for (var name24 in all)
4
+ __defProp(target, name24, { get: all[name24], enumerable: true });
5
5
  };
6
6
 
7
7
  // src/index.ts
@@ -37,7 +37,7 @@ import {
37
37
 
38
38
  // src/error/index.ts
39
39
  import {
40
- AISDKError as AISDKError23,
40
+ AISDKError as AISDKError24,
41
41
  APICallError,
42
42
  EmptyResponseBodyError,
43
43
  InvalidPromptError,
@@ -416,31 +416,64 @@ var NoSuchToolError = class extends AISDKError15 {
416
416
  };
417
417
  _a15 = symbol15;
418
418
 
419
- // src/error/tool-call-repair-error.ts
420
- import { AISDKError as AISDKError16, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
421
- var name16 = "AI_ToolCallRepairError";
419
+ // src/error/stream-provider-error.ts
420
+ import { AISDKError as AISDKError16 } from "@ai-sdk/provider";
421
+ var name16 = "AI_StreamProviderError";
422
422
  var marker16 = `vercel.ai.error.${name16}`;
423
423
  var symbol16 = Symbol.for(marker16);
424
424
  var _a16;
425
- var ToolCallRepairError = class extends AISDKError16 {
425
+ var StreamProviderError = class extends AISDKError16 {
426
426
  constructor({
427
- cause,
428
- originalError,
429
- message = `Error repairing tool call: ${getErrorMessage2(cause)}`
427
+ message,
428
+ type,
429
+ code,
430
+ statusCode,
431
+ isRetryable = isRetryableStatusCode(statusCode),
432
+ data,
433
+ cause
430
434
  }) {
431
435
  super({ name: name16, message, cause });
432
436
  this[_a16] = true;
433
- this.originalError = originalError;
437
+ this.type = type;
438
+ this.code = code;
439
+ this.statusCode = statusCode;
440
+ this.isRetryable = isRetryable;
441
+ this.data = data;
434
442
  }
435
443
  static isInstance(error) {
436
444
  return AISDKError16.hasMarker(error, marker16);
437
445
  }
438
446
  };
439
447
  _a16 = symbol16;
448
+ function isRetryableStatusCode(statusCode) {
449
+ return statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500);
450
+ }
451
+
452
+ // src/error/tool-call-repair-error.ts
453
+ import { AISDKError as AISDKError17, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
454
+ var name17 = "AI_ToolCallRepairError";
455
+ var marker17 = `vercel.ai.error.${name17}`;
456
+ var symbol17 = Symbol.for(marker17);
457
+ var _a17;
458
+ var ToolCallRepairError = class extends AISDKError17 {
459
+ constructor({
460
+ cause,
461
+ originalError,
462
+ message = `Error repairing tool call: ${getErrorMessage2(cause)}`
463
+ }) {
464
+ super({ name: name17, message, cause });
465
+ this[_a17] = true;
466
+ this.originalError = originalError;
467
+ }
468
+ static isInstance(error) {
469
+ return AISDKError17.hasMarker(error, marker17);
470
+ }
471
+ };
472
+ _a17 = symbol17;
440
473
 
441
474
  // src/error/unsupported-model-version-error.ts
442
- import { AISDKError as AISDKError17 } from "@ai-sdk/provider";
443
- var UnsupportedModelVersionError = class extends AISDKError17 {
475
+ import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
476
+ var UnsupportedModelVersionError = class extends AISDKError18 {
444
477
  constructor(options) {
445
478
  super({
446
479
  name: "AI_UnsupportedModelVersionError",
@@ -453,118 +486,118 @@ var UnsupportedModelVersionError = class extends AISDKError17 {
453
486
  };
454
487
 
455
488
  // src/error/ui-message-stream-error.ts
456
- import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
457
- var name17 = "AI_UIMessageStreamError";
458
- var marker17 = `vercel.ai.error.${name17}`;
459
- var symbol17 = Symbol.for(marker17);
460
- var _a17;
461
- var UIMessageStreamError = class extends AISDKError18 {
489
+ import { AISDKError as AISDKError19 } from "@ai-sdk/provider";
490
+ var name18 = "AI_UIMessageStreamError";
491
+ var marker18 = `vercel.ai.error.${name18}`;
492
+ var symbol18 = Symbol.for(marker18);
493
+ var _a18;
494
+ var UIMessageStreamError = class extends AISDKError19 {
462
495
  constructor({
463
496
  chunkType,
464
497
  chunkId,
465
498
  message
466
499
  }) {
467
- super({ name: name17, message });
468
- this[_a17] = true;
500
+ super({ name: name18, message });
501
+ this[_a18] = true;
469
502
  this.chunkType = chunkType;
470
503
  this.chunkId = chunkId;
471
504
  }
472
505
  static isInstance(error) {
473
- return AISDKError18.hasMarker(error, marker17);
506
+ return AISDKError19.hasMarker(error, marker18);
474
507
  }
475
508
  };
476
- _a17 = symbol17;
509
+ _a18 = symbol18;
477
510
 
478
511
  // src/prompt/invalid-data-content-error.ts
479
- import { AISDKError as AISDKError19 } from "@ai-sdk/provider";
480
- var name18 = "AI_InvalidDataContentError";
481
- var marker18 = `vercel.ai.error.${name18}`;
482
- var symbol18 = Symbol.for(marker18);
483
- var _a18;
484
- var InvalidDataContentError = class extends AISDKError19 {
512
+ import { AISDKError as AISDKError20 } from "@ai-sdk/provider";
513
+ var name19 = "AI_InvalidDataContentError";
514
+ var marker19 = `vercel.ai.error.${name19}`;
515
+ var symbol19 = Symbol.for(marker19);
516
+ var _a19;
517
+ var InvalidDataContentError = class extends AISDKError20 {
485
518
  constructor({
486
519
  content,
487
520
  cause,
488
521
  message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
489
522
  }) {
490
- super({ name: name18, message, cause });
491
- this[_a18] = true;
523
+ super({ name: name19, message, cause });
524
+ this[_a19] = true;
492
525
  this.content = content;
493
526
  }
494
527
  static isInstance(error) {
495
- return AISDKError19.hasMarker(error, marker18);
528
+ return AISDKError20.hasMarker(error, marker19);
496
529
  }
497
530
  };
498
- _a18 = symbol18;
531
+ _a19 = symbol19;
499
532
 
500
533
  // src/prompt/invalid-message-role-error.ts
501
- import { AISDKError as AISDKError20 } from "@ai-sdk/provider";
502
- var name19 = "AI_InvalidMessageRoleError";
503
- var marker19 = `vercel.ai.error.${name19}`;
504
- var symbol19 = Symbol.for(marker19);
505
- var _a19;
506
- var InvalidMessageRoleError = class extends AISDKError20 {
534
+ import { AISDKError as AISDKError21 } from "@ai-sdk/provider";
535
+ var name20 = "AI_InvalidMessageRoleError";
536
+ var marker20 = `vercel.ai.error.${name20}`;
537
+ var symbol20 = Symbol.for(marker20);
538
+ var _a20;
539
+ var InvalidMessageRoleError = class extends AISDKError21 {
507
540
  constructor({
508
541
  role,
509
542
  message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
510
543
  }) {
511
- super({ name: name19, message });
512
- this[_a19] = true;
544
+ super({ name: name20, message });
545
+ this[_a20] = true;
513
546
  this.role = role;
514
547
  }
515
548
  static isInstance(error) {
516
- return AISDKError20.hasMarker(error, marker19);
549
+ return AISDKError21.hasMarker(error, marker20);
517
550
  }
518
551
  };
519
- _a19 = symbol19;
552
+ _a20 = symbol20;
520
553
 
521
554
  // src/prompt/message-conversion-error.ts
522
- import { AISDKError as AISDKError21 } from "@ai-sdk/provider";
523
- var name20 = "AI_MessageConversionError";
524
- var marker20 = `vercel.ai.error.${name20}`;
525
- var symbol20 = Symbol.for(marker20);
526
- var _a20;
527
- var MessageConversionError = class extends AISDKError21 {
555
+ import { AISDKError as AISDKError22 } from "@ai-sdk/provider";
556
+ var name21 = "AI_MessageConversionError";
557
+ var marker21 = `vercel.ai.error.${name21}`;
558
+ var symbol21 = Symbol.for(marker21);
559
+ var _a21;
560
+ var MessageConversionError = class extends AISDKError22 {
528
561
  constructor({
529
562
  originalMessage,
530
563
  message
531
564
  }) {
532
- super({ name: name20, message });
533
- this[_a20] = true;
565
+ super({ name: name21, message });
566
+ this[_a21] = true;
534
567
  this.originalMessage = originalMessage;
535
568
  }
536
569
  static isInstance(error) {
537
- return AISDKError21.hasMarker(error, marker20);
570
+ return AISDKError22.hasMarker(error, marker21);
538
571
  }
539
572
  };
540
- _a20 = symbol20;
573
+ _a21 = symbol21;
541
574
 
542
575
  // src/error/index.ts
543
576
  import { DownloadError } from "@ai-sdk/provider-utils";
544
577
 
545
578
  // src/util/retry-error.ts
546
- import { AISDKError as AISDKError22 } from "@ai-sdk/provider";
547
- var name21 = "AI_RetryError";
548
- var marker21 = `vercel.ai.error.${name21}`;
549
- var symbol21 = Symbol.for(marker21);
550
- var _a21;
551
- var RetryError = class extends AISDKError22 {
579
+ import { AISDKError as AISDKError23 } from "@ai-sdk/provider";
580
+ var name22 = "AI_RetryError";
581
+ var marker22 = `vercel.ai.error.${name22}`;
582
+ var symbol22 = Symbol.for(marker22);
583
+ var _a22;
584
+ var RetryError = class extends AISDKError23 {
552
585
  constructor({
553
586
  message,
554
587
  reason,
555
588
  errors
556
589
  }) {
557
- super({ name: name21, message });
558
- this[_a21] = true;
590
+ super({ name: name22, message });
591
+ this[_a22] = true;
559
592
  this.reason = reason;
560
593
  this.errors = errors;
561
594
  this.lastError = errors[errors.length - 1];
562
595
  }
563
596
  static isInstance(error) {
564
- return AISDKError22.hasMarker(error, marker21);
597
+ return AISDKError23.hasMarker(error, marker22);
565
598
  }
566
599
  };
567
- _a21 = symbol21;
600
+ _a22 = symbol22;
568
601
 
569
602
  // src/logger/log-warnings.ts
570
603
  function formatWarning({
@@ -984,9 +1017,9 @@ function resolveEmbeddingModel(model) {
984
1017
  return asEmbeddingModelV4(model);
985
1018
  }
986
1019
  function resolveTranscriptionModel(model) {
987
- var _a23, _b;
1020
+ var _a24, _b;
988
1021
  if (typeof model === "string") {
989
- return (_b = (_a23 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a23, model);
1022
+ return (_b = (_a24 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a24, model);
990
1023
  }
991
1024
  if (!["v4", "v3", "v2"].includes(model.specificationVersion)) {
992
1025
  const unsupportedModel = model;
@@ -999,9 +1032,9 @@ function resolveTranscriptionModel(model) {
999
1032
  return asTranscriptionModelV4(model);
1000
1033
  }
1001
1034
  function resolveSpeechTranslationModel(model) {
1002
- var _a23;
1035
+ var _a24;
1003
1036
  if (typeof model === "string") {
1004
- const provider = (_a23 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a23 : gateway;
1037
+ const provider = (_a24 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a24 : gateway;
1005
1038
  const speechTranslationModel = provider.speechTranslationModel;
1006
1039
  if (!speechTranslationModel) {
1007
1040
  throw new Error(
@@ -1021,9 +1054,9 @@ function resolveSpeechTranslationModel(model) {
1021
1054
  return model;
1022
1055
  }
1023
1056
  function resolveSpeechModel(model) {
1024
- var _a23, _b;
1057
+ var _a24, _b;
1025
1058
  if (typeof model === "string") {
1026
- return (_b = (_a23 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a23, model);
1059
+ return (_b = (_a24 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a24, model);
1027
1060
  }
1028
1061
  if (!["v4", "v3", "v2"].includes(model.specificationVersion)) {
1029
1062
  const unsupportedModel = model;
@@ -1050,9 +1083,9 @@ function resolveImageModel(model) {
1050
1083
  return asImageModelV4(model);
1051
1084
  }
1052
1085
  function resolveVideoModel(model) {
1053
- var _a23;
1086
+ var _a24;
1054
1087
  if (typeof model === "string") {
1055
- const provider = (_a23 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a23 : gateway;
1088
+ const provider = (_a24 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a24 : gateway;
1056
1089
  const videoModel = provider.videoModel;
1057
1090
  if (!videoModel) {
1058
1091
  throw new Error(
@@ -1093,8 +1126,8 @@ function resolveRerankingModel(model) {
1093
1126
  return asRerankingModelV4(model);
1094
1127
  }
1095
1128
  function getGlobalProvider() {
1096
- var _a23;
1097
- const provider = (_a23 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a23 : gateway;
1129
+ var _a24;
1130
+ const provider = (_a24 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a24 : gateway;
1098
1131
  return asProviderV4(provider);
1099
1132
  }
1100
1133
 
@@ -1146,7 +1179,7 @@ import {
1146
1179
  } from "@ai-sdk/provider-utils";
1147
1180
 
1148
1181
  // src/version.ts
1149
- var VERSION = true ? "7.0.79" : "0.0.0-test";
1182
+ var VERSION = true ? "7.0.83" : "0.0.0-test";
1150
1183
 
1151
1184
  // src/util/download/download.ts
1152
1185
  var download = async ({
@@ -1154,7 +1187,7 @@ var download = async ({
1154
1187
  maxBytes,
1155
1188
  abortSignal
1156
1189
  }) => {
1157
- var _a23;
1190
+ var _a24;
1158
1191
  const urlText = url.toString();
1159
1192
  try {
1160
1193
  const headers = withUserAgentSuffix(
@@ -1182,7 +1215,7 @@ var download = async ({
1182
1215
  });
1183
1216
  return {
1184
1217
  data,
1185
- mediaType: (_a23 = response.headers.get("content-type")) != null ? _a23 : void 0
1218
+ mediaType: (_a24 = response.headers.get("content-type")) != null ? _a24 : void 0
1186
1219
  };
1187
1220
  } catch (error) {
1188
1221
  if (DownloadError2.isInstance(error)) {
@@ -1649,14 +1682,14 @@ function convertToLanguageModelMessage({
1649
1682
  }
1650
1683
  }
1651
1684
  function convertImagePartToFilePart(part) {
1652
- var _a23;
1685
+ var _a24;
1653
1686
  if (part.type !== "image") {
1654
1687
  return part;
1655
1688
  }
1656
1689
  return {
1657
1690
  type: "file",
1658
1691
  data: part.image,
1659
- mediaType: (_a23 = part.mediaType) != null ? _a23 : "image",
1692
+ mediaType: (_a24 = part.mediaType) != null ? _a24 : "image",
1660
1693
  providerOptions: part.providerOptions
1661
1694
  };
1662
1695
  }
@@ -1778,7 +1811,7 @@ function mapToolResultOutput({
1778
1811
  return {
1779
1812
  type: "content",
1780
1813
  value: output.value.map((item) => {
1781
- var _a23;
1814
+ var _a24;
1782
1815
  switch (item.type) {
1783
1816
  case "file": {
1784
1817
  const convertedPart = convertPartToLanguageModelPart(
@@ -1807,7 +1840,7 @@ function mapToolResultOutput({
1807
1840
  };
1808
1841
  }
1809
1842
  case "file-url": {
1810
- const mediaType = (_a23 = item.mediaType) != null ? _a23 : getMediaTypeFromUrl(item.url);
1843
+ const mediaType = (_a24 = item.mediaType) != null ? _a24 : getMediaTypeFromUrl(item.url);
1811
1844
  let message = `The "file-url" type for tool result content is deprecated. Use the "file" type with mediaType and { type: 'url', url } instead.`;
1812
1845
  if (!item.mediaType) {
1813
1846
  const inferenceSuffix = mediaType === "application/octet-stream" ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.` : `Inferred media type '${mediaType}' from URL.`;
@@ -1961,10 +1994,10 @@ var URL_EXTENSION_TO_MEDIA_TYPE = {
1961
1994
  ogg: "audio/ogg"
1962
1995
  };
1963
1996
  function getMediaTypeFromUrl(url, fallbackMediaType = "application/octet-stream") {
1964
- var _a23;
1997
+ var _a24;
1965
1998
  try {
1966
1999
  const pathname = new URL(url).pathname;
1967
- const fileExtension = (_a23 = pathname.split(".").pop()) == null ? void 0 : _a23.toLowerCase();
2000
+ const fileExtension = (_a24 = pathname.split(".").pop()) == null ? void 0 : _a24.toLowerCase();
1968
2001
  if (fileExtension && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)) {
1969
2002
  return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];
1970
2003
  }
@@ -2119,7 +2152,7 @@ async function prepareTools({
2119
2152
  return void 0;
2120
2153
  }
2121
2154
  const languageModelTools = [];
2122
- for (const [name23, tool2] of orderToolEntries({ tools, toolOrder })) {
2155
+ for (const [name24, tool2] of orderToolEntries({ tools, toolOrder })) {
2123
2156
  const toolType = tool2.type;
2124
2157
  switch (toolType) {
2125
2158
  case void 0:
@@ -2127,7 +2160,7 @@ async function prepareTools({
2127
2160
  case "function": {
2128
2161
  const description = resolveToolDescription({
2129
2162
  tool: tool2,
2130
- toolName: name23,
2163
+ toolName: name24,
2131
2164
  toolsContext,
2132
2165
  experimental_sandbox: sandbox
2133
2166
  });
@@ -2136,7 +2169,7 @@ async function prepareTools({
2136
2169
  const strict = tool2.strict;
2137
2170
  languageModelTools.push({
2138
2171
  type: "function",
2139
- name: name23,
2172
+ name: name24,
2140
2173
  inputSchema: await asSchema(tool2.inputSchema).jsonSchema,
2141
2174
  ...description != null ? { description } : {},
2142
2175
  ...inputExamples != null ? { inputExamples } : {},
@@ -2148,7 +2181,7 @@ async function prepareTools({
2148
2181
  case "provider": {
2149
2182
  languageModelTools.push({
2150
2183
  type: "provider",
2151
- name: name23,
2184
+ name: name24,
2152
2185
  id: tool2.id,
2153
2186
  args: tool2.args
2154
2187
  });
@@ -2170,10 +2203,10 @@ function orderToolEntries({
2170
2203
  return Object.entries(tools);
2171
2204
  }
2172
2205
  const toolEntries = Object.entries(tools);
2173
- const orderedTools = toolEntries.filter(([name23]) => toolOrder.includes(name23)).sort(
2206
+ const orderedTools = toolEntries.filter(([name24]) => toolOrder.includes(name24)).sort(
2174
2207
  ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB)
2175
2208
  );
2176
- const unorderedTools = toolEntries.filter(([name23]) => !toolOrder.includes(name23)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0);
2209
+ const unorderedTools = toolEntries.filter(([name24]) => !toolOrder.includes(name24)).sort(([nameA], [nameB]) => nameA < nameB ? -1 : nameA > nameB ? 1 : 0);
2177
2210
  return [...orderedTools, ...unorderedTools];
2178
2211
  }
2179
2212
  function resolveToolDescription({
@@ -2217,11 +2250,11 @@ function getChunkTimeoutMs(timeout) {
2217
2250
  return timeout.chunkMs;
2218
2251
  }
2219
2252
  function getToolTimeoutMs(timeout, toolName) {
2220
- var _a23, _b;
2253
+ var _a24, _b;
2221
2254
  if (timeout == null || typeof timeout === "number") {
2222
2255
  return void 0;
2223
2256
  }
2224
- return (_b = (_a23 = timeout.tools) == null ? void 0 : _a23[`${toolName}Ms`]) != null ? _b : timeout.toolMs;
2257
+ return (_b = (_a24 = timeout.tools) == null ? void 0 : _a24[`${toolName}Ms`]) != null ? _b : timeout.toolMs;
2225
2258
  }
2226
2259
 
2227
2260
  // src/prompt/standardize-prompt.ts
@@ -2484,7 +2517,8 @@ var toolApprovalRequestSchema = z.object(
2484
2517
  {
2485
2518
  type: z.literal("tool-approval-request"),
2486
2519
  approvalId: z.string(),
2487
- toolCallId: z.string()
2520
+ toolCallId: z.string(),
2521
+ reason: z.string().optional()
2488
2522
  }
2489
2523
  );
2490
2524
  var toolApprovalResponseSchema = z.object({
@@ -2603,14 +2637,14 @@ async function standardizePrompt({
2603
2637
 
2604
2638
  // src/prompt/wrap-gateway-error.ts
2605
2639
  import { GatewayAuthenticationError } from "@ai-sdk/gateway";
2606
- import { AISDKError as AISDKError24 } from "@ai-sdk/provider";
2640
+ import { AISDKError as AISDKError25 } from "@ai-sdk/provider";
2607
2641
  function wrapGatewayError(error) {
2608
2642
  if (!GatewayAuthenticationError.isInstance(error))
2609
2643
  return error;
2610
2644
  const isProductionEnv = (process == null ? void 0 : process.env.NODE_ENV) === "production";
2611
2645
  const moreInfoURL = "https://ai-sdk.dev/unauthenticated-ai-gateway";
2612
2646
  if (isProductionEnv) {
2613
- return new AISDKError24({
2647
+ return new AISDKError25({
2614
2648
  name: "GatewayError",
2615
2649
  message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`
2616
2650
  });
@@ -2668,12 +2702,12 @@ function createNullLanguageModelUsage() {
2668
2702
  };
2669
2703
  }
2670
2704
  function addLanguageModelUsage(usage1, usage2) {
2671
- var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2705
+ var _a24, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2672
2706
  return {
2673
2707
  inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2674
2708
  inputTokenDetails: {
2675
2709
  noCacheTokens: addTokenCounts(
2676
- (_a23 = usage1.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens,
2710
+ (_a24 = usage1.inputTokenDetails) == null ? void 0 : _a24.noCacheTokens,
2677
2711
  (_b = usage2.inputTokenDetails) == null ? void 0 : _b.noCacheTokens
2678
2712
  ),
2679
2713
  cacheReadTokens: addTokenCounts(
@@ -2726,8 +2760,8 @@ function mergeAbortSignals(...signals) {
2726
2760
 
2727
2761
  // src/util/now.ts
2728
2762
  function now() {
2729
- var _a23, _b;
2730
- return (_b = (_a23 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a23.now()) != null ? _b : Date.now();
2763
+ var _a24, _b;
2764
+ return (_b = (_a24 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a24.now()) != null ? _b : Date.now();
2731
2765
  }
2732
2766
 
2733
2767
  // src/util/notify.ts
@@ -3101,7 +3135,7 @@ function filterActiveTools({
3101
3135
  return tools;
3102
3136
  }
3103
3137
  return Object.fromEntries(
3104
- Object.entries(tools).filter(([name23]) => activeTools.includes(name23))
3138
+ Object.entries(tools).filter(([name24]) => activeTools.includes(name24))
3105
3139
  );
3106
3140
  }
3107
3141
 
@@ -3538,7 +3572,7 @@ var text = () => ({
3538
3572
  });
3539
3573
  var object2 = ({
3540
3574
  schema: inputSchema,
3541
- name: name23,
3575
+ name: name24,
3542
3576
  description
3543
3577
  }) => {
3544
3578
  const schema = asSchema2(inputSchema);
@@ -3547,7 +3581,7 @@ var object2 = ({
3547
3581
  responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({
3548
3582
  type: "json",
3549
3583
  schema: jsonSchema2,
3550
- ...name23 != null && { name: name23 },
3584
+ ...name24 != null && { name: name24 },
3551
3585
  ...description != null && { description }
3552
3586
  })),
3553
3587
  async parseCompleteOutput({ text: text2 }, context) {
@@ -3601,7 +3635,7 @@ var object2 = ({
3601
3635
  };
3602
3636
  var array2 = ({
3603
3637
  element: inputElementSchema,
3604
- name: name23,
3638
+ name: name24,
3605
3639
  description
3606
3640
  }) => {
3607
3641
  const elementSchema = asSchema2(inputElementSchema);
@@ -3628,7 +3662,7 @@ var array2 = ({
3628
3662
  required: ["elements"],
3629
3663
  additionalProperties: false
3630
3664
  },
3631
- ...name23 != null && { name: name23 },
3665
+ ...name24 != null && { name: name24 },
3632
3666
  ...description != null && { description }
3633
3667
  };
3634
3668
  }),
@@ -3722,7 +3756,7 @@ var array2 = ({
3722
3756
  };
3723
3757
  var choice = ({
3724
3758
  options: choiceOptions,
3725
- name: name23,
3759
+ name: name24,
3726
3760
  description
3727
3761
  }) => {
3728
3762
  return {
@@ -3739,7 +3773,7 @@ var choice = ({
3739
3773
  required: ["result"],
3740
3774
  additionalProperties: false
3741
3775
  },
3742
- ...name23 != null && { name: name23 },
3776
+ ...name24 != null && { name: name24 },
3743
3777
  ...description != null && { description }
3744
3778
  }),
3745
3779
  async parseCompleteOutput({ text: text2 }, context) {
@@ -3800,14 +3834,14 @@ var choice = ({
3800
3834
  };
3801
3835
  };
3802
3836
  var json = ({
3803
- name: name23,
3837
+ name: name24,
3804
3838
  description
3805
3839
  } = {}) => {
3806
3840
  return {
3807
3841
  name: "json",
3808
3842
  responseFormat: Promise.resolve({
3809
3843
  type: "json",
3810
- ...name23 != null && { name: name23 },
3844
+ ...name24 != null && { name: name24 },
3811
3845
  ...description != null && { description }
3812
3846
  }),
3813
3847
  async parseCompleteOutput({ text: text2 }, context) {
@@ -3882,8 +3916,8 @@ async function parseToolCall({
3882
3916
  toolCall,
3883
3917
  tools,
3884
3918
  inputSchema: async ({ toolName }) => {
3885
- var _a23;
3886
- const inputSchema = (_a23 = getOwn(tools, toolName)) == null ? void 0 : _a23.inputSchema;
3919
+ var _a24;
3920
+ const inputSchema = (_a24 = getOwn(tools, toolName)) == null ? void 0 : _a24.inputSchema;
3887
3921
  return await asSchema3(inputSchema).jsonSchema;
3888
3922
  },
3889
3923
  instructions,
@@ -4007,9 +4041,9 @@ function prepareStepCallSettings({
4007
4041
  callSettings,
4008
4042
  stepSettings
4009
4043
  }) {
4010
- var _a23, _b, _c, _d, _e, _f, _g, _h, _i;
4044
+ var _a24, _b, _c, _d, _e, _f, _g, _h, _i;
4011
4045
  return prepareLanguageModelCallOptions({
4012
- maxOutputTokens: (_a23 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a23 : callSettings.maxOutputTokens,
4046
+ maxOutputTokens: (_a24 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a24 : callSettings.maxOutputTokens,
4013
4047
  temperature: (_b = stepSettings == null ? void 0 : stepSettings.temperature) != null ? _b : callSettings.temperature,
4014
4048
  topP: (_c = stepSettings == null ? void 0 : stepSettings.topP) != null ? _c : callSettings.topP,
4015
4049
  topK: (_d = stepSettings == null ? void 0 : stepSettings.topK) != null ? _d : callSettings.topK,
@@ -4141,8 +4175,8 @@ var AI_SDK_TELEMETRY_TRACING_CHANNEL = "ai:telemetry";
4141
4175
 
4142
4176
  // src/util/is-node-runtime.ts
4143
4177
  function isNodeRuntime() {
4144
- var _a23;
4145
- return typeof process !== "undefined" && ((_a23 = process.release) == null ? void 0 : _a23.name) === "node";
4178
+ var _a24;
4179
+ return typeof process !== "undefined" && ((_a24 = process.release) == null ? void 0 : _a24.name) === "node";
4146
4180
  }
4147
4181
 
4148
4182
  // src/telemetry/tracing-channel-publisher.ts
@@ -4159,18 +4193,18 @@ async function loadDiagnosticsChannel() {
4159
4193
  return diagnosticsChannelPromise;
4160
4194
  }
4161
4195
  function loadBuiltinModule(id) {
4162
- var _a23;
4196
+ var _a24;
4163
4197
  const processWithBuiltins = globalThis.process;
4164
4198
  try {
4165
- return (_a23 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a23.call(processWithBuiltins, id);
4199
+ return (_a24 = processWithBuiltins == null ? void 0 : processWithBuiltins.getBuiltinModule) == null ? void 0 : _a24.call(processWithBuiltins, id);
4166
4200
  } catch (e) {
4167
4201
  return void 0;
4168
4202
  }
4169
4203
  }
4170
4204
  async function runWithTracingChannelSpan(message, execute) {
4171
- var _a23;
4205
+ var _a24;
4172
4206
  const diagnosticsChannel = await loadDiagnosticsChannel();
4173
- const tracingChannel = (_a23 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a23.call(
4207
+ const tracingChannel = (_a24 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a24.call(
4174
4208
  diagnosticsChannel,
4175
4209
  AI_SDK_TELEMETRY_TRACING_CHANNEL
4176
4210
  );
@@ -4221,7 +4255,7 @@ function openTelemetryChannelSpanContext({
4221
4255
  message,
4222
4256
  completion
4223
4257
  }) {
4224
- var _a23;
4258
+ var _a24;
4225
4259
  if (!isNodeRuntime()) {
4226
4260
  return void 0;
4227
4261
  }
@@ -4229,7 +4263,7 @@ function openTelemetryChannelSpanContext({
4229
4263
  "node:diagnostics_channel"
4230
4264
  );
4231
4265
  const asyncHooks = loadBuiltinModule("node:async_hooks");
4232
- const tracingChannel = (_a23 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a23.call(
4266
+ const tracingChannel = (_a24 = diagnosticsChannel == null ? void 0 : diagnosticsChannel.tracingChannel) == null ? void 0 : _a24.call(
4233
4267
  diagnosticsChannel,
4234
4268
  AI_SDK_TELEMETRY_TRACING_CHANNEL
4235
4269
  );
@@ -4287,8 +4321,8 @@ function registerTelemetry(...integrations) {
4287
4321
  globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);
4288
4322
  }
4289
4323
  function getGlobalTelemetryIntegrations() {
4290
- var _a23;
4291
- return (_a23 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a23 : [];
4324
+ var _a24;
4325
+ return (_a24 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a24 : [];
4292
4326
  }
4293
4327
 
4294
4328
  // src/telemetry/create-telemetry-dispatcher.ts
@@ -4314,8 +4348,8 @@ function createTelemetryDispatcher({
4314
4348
  };
4315
4349
  const mergeTelemetryCallback = (key) => {
4316
4350
  const integrationCallbacks = integrations.map((integration) => {
4317
- var _a23;
4318
- return (_a23 = integration[key]) == null ? void 0 : _a23.bind(integration);
4351
+ var _a24;
4352
+ return (_a24 = integration[key]) == null ? void 0 : _a24.bind(integration);
4319
4353
  }).filter(Boolean).map(
4320
4354
  (callback) => (event) => callback(augmentEvent(event, telemetryMetadata))
4321
4355
  );
@@ -4325,12 +4359,12 @@ function createTelemetryDispatcher({
4325
4359
  };
4326
4360
  };
4327
4361
  const executeLanguageModelCallWrappers = integrations.map((integration) => {
4328
- var _a23;
4329
- return (_a23 = integration.executeLanguageModelCall) == null ? void 0 : _a23.bind(integration);
4362
+ var _a24;
4363
+ return (_a24 = integration.executeLanguageModelCall) == null ? void 0 : _a24.bind(integration);
4330
4364
  }).filter(Boolean);
4331
4365
  const executeToolWrappers = integrations.map((integration) => {
4332
- var _a23;
4333
- return (_a23 = integration.executeTool) == null ? void 0 : _a23.bind(integration);
4366
+ var _a24;
4367
+ return (_a24 = integration.executeTool) == null ? void 0 : _a24.bind(integration);
4334
4368
  }).filter(Boolean);
4335
4369
  return {
4336
4370
  runInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan(
@@ -4574,8 +4608,8 @@ function createRestrictedTelemetryDispatcher({
4574
4608
  return {
4575
4609
  ...telemetryDispatcher,
4576
4610
  onStart: (event) => {
4577
- var _a23;
4578
- return (_a23 = telemetryDispatcher.onStart) == null ? void 0 : _a23.call(telemetryDispatcher, {
4611
+ var _a24;
4612
+ return (_a24 = telemetryDispatcher.onStart) == null ? void 0 : _a24.call(telemetryDispatcher, {
4579
4613
  ...event,
4580
4614
  runtimeContext: filterIncludedContext({
4581
4615
  context: event.runtimeContext,
@@ -4588,8 +4622,8 @@ function createRestrictedTelemetryDispatcher({
4588
4622
  });
4589
4623
  },
4590
4624
  onStepStart: (event) => {
4591
- var _a23;
4592
- return (_a23 = telemetryDispatcher.onStepStart) == null ? void 0 : _a23.call(telemetryDispatcher, {
4625
+ var _a24;
4626
+ return (_a24 = telemetryDispatcher.onStepStart) == null ? void 0 : _a24.call(telemetryDispatcher, {
4593
4627
  ...event,
4594
4628
  runtimeContext: filterIncludedContext({
4595
4629
  context: event.runtimeContext,
@@ -4609,8 +4643,8 @@ function createRestrictedTelemetryDispatcher({
4609
4643
  });
4610
4644
  },
4611
4645
  onStepEnd: (event) => {
4612
- var _a23;
4613
- return (_a23 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a23.call(
4646
+ var _a24;
4647
+ return (_a24 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a24.call(
4614
4648
  telemetryDispatcher,
4615
4649
  restrictStepResult({
4616
4650
  step: event,
@@ -4620,8 +4654,8 @@ function createRestrictedTelemetryDispatcher({
4620
4654
  );
4621
4655
  },
4622
4656
  onStepFinish: (event) => {
4623
- var _a23;
4624
- return (_a23 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a23.call(
4657
+ var _a24;
4658
+ return (_a24 = telemetryDispatcher.onStepEnd) == null ? void 0 : _a24.call(
4625
4659
  telemetryDispatcher,
4626
4660
  restrictStepResult({
4627
4661
  step: event,
@@ -4631,8 +4665,8 @@ function createRestrictedTelemetryDispatcher({
4631
4665
  );
4632
4666
  },
4633
4667
  onEnd: (event) => {
4634
- var _a23;
4635
- return (_a23 = telemetryDispatcher.onEnd) == null ? void 0 : _a23.call(
4668
+ var _a24;
4669
+ return (_a24 = telemetryDispatcher.onEnd) == null ? void 0 : _a24.call(
4636
4670
  telemetryDispatcher,
4637
4671
  ((restrictedSteps) => {
4638
4672
  return {
@@ -4660,8 +4694,8 @@ function createRestrictedTelemetryDispatcher({
4660
4694
  );
4661
4695
  },
4662
4696
  onAbort: (event) => {
4663
- var _a23;
4664
- return (_a23 = telemetryDispatcher.onAbort) == null ? void 0 : _a23.call(telemetryDispatcher, {
4697
+ var _a24;
4698
+ return (_a24 = telemetryDispatcher.onAbort) == null ? void 0 : _a24.call(telemetryDispatcher, {
4665
4699
  ...event,
4666
4700
  steps: event.steps.map(
4667
4701
  (step) => restrictStepResult({
@@ -4673,8 +4707,8 @@ function createRestrictedTelemetryDispatcher({
4673
4707
  });
4674
4708
  },
4675
4709
  onToolExecutionStart: (event) => {
4676
- var _a23;
4677
- return (_a23 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a23.call(telemetryDispatcher, {
4710
+ var _a24;
4711
+ return (_a24 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a24.call(telemetryDispatcher, {
4678
4712
  ...event,
4679
4713
  toolContext: filterToolContext({
4680
4714
  toolName: event.toolCall.toolName,
@@ -4684,8 +4718,8 @@ function createRestrictedTelemetryDispatcher({
4684
4718
  });
4685
4719
  },
4686
4720
  onToolExecutionEnd: (event) => {
4687
- var _a23;
4688
- return (_a23 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _a23.call(telemetryDispatcher, {
4721
+ var _a24;
4722
+ return (_a24 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _a24.call(telemetryDispatcher, {
4689
4723
  ...event,
4690
4724
  toolContext: filterToolContext({
4691
4725
  toolName: event.toolCall.toolName,
@@ -4706,8 +4740,8 @@ function isLoopFinished() {
4706
4740
  }
4707
4741
  function hasToolCall(...toolName) {
4708
4742
  return ({ steps }) => {
4709
- var _a23, _b, _c;
4710
- return (_c = (_b = (_a23 = steps[steps.length - 1]) == null ? void 0 : _a23.toolCalls) == null ? void 0 : _b.some(
4743
+ var _a24, _b, _c;
4744
+ return (_c = (_b = (_a24 = steps[steps.length - 1]) == null ? void 0 : _a24.toolCalls) == null ? void 0 : _b.some(
4711
4745
  (toolCall) => toolName.includes(toolCall.toolName)
4712
4746
  )) != null ? _c : false;
4713
4747
  };
@@ -4832,6 +4866,7 @@ async function toResponseMessages({
4832
4866
  type: "tool-approval-request",
4833
4867
  approvalId: part.approvalId,
4834
4868
  toolCallId: part.toolCall.toolCallId,
4869
+ ...part.reason != null ? { reason: part.reason } : {},
4835
4870
  isAutomatic: part.isAutomatic,
4836
4871
  ...part.signature != null ? { signature: part.signature } : {}
4837
4872
  });
@@ -4971,7 +5006,7 @@ function prepareToolsForToolCallers({
4971
5006
  tools,
4972
5007
  toolCallers
4973
5008
  }) {
4974
- var _a23, _b;
5009
+ var _a24, _b;
4975
5010
  if (tools == null || toolCallers == null) {
4976
5011
  return { executionTools: tools, modelTools: tools };
4977
5012
  }
@@ -5004,7 +5039,7 @@ function prepareToolsForToolCallers({
5004
5039
  )
5005
5040
  };
5006
5041
  } else {
5007
- const localTools = (_a23 = localToolsByCaller.get(callerName)) != null ? _a23 : {};
5042
+ const localTools = (_a24 = localToolsByCaller.get(callerName)) != null ? _a24 : {};
5008
5043
  localTools[toolName] = preparedTool;
5009
5044
  localToolsByCaller.set(callerName, localTools);
5010
5045
  }
@@ -5163,7 +5198,7 @@ async function validateApprovedToolApprovals({
5163
5198
  runtimeContext,
5164
5199
  toolApprovalSecret
5165
5200
  }) {
5166
- var _a23;
5201
+ var _a24;
5167
5202
  const approved = [];
5168
5203
  const denied = [];
5169
5204
  const invalid = [];
@@ -5225,7 +5260,7 @@ async function validateApprovedToolApprovals({
5225
5260
  approvalResponse: {
5226
5261
  ...approval.approvalResponse,
5227
5262
  approved: false,
5228
- reason: (_a23 = approvalStatus.reason) != null ? _a23 : approval.approvalResponse.reason
5263
+ reason: (_a24 = approvalStatus.reason) != null ? _a24 : approval.approvalResponse.reason
5229
5264
  }
5230
5265
  });
5231
5266
  } else {
@@ -5304,9 +5339,9 @@ async function generateText({
5304
5339
  onEnd = onFinish,
5305
5340
  ...settings
5306
5341
  }) {
5307
- var _a23, _b, _c, _d;
5342
+ var _a24, _b, _c, _d;
5308
5343
  include = {
5309
- requestBody: (_a23 = include == null ? void 0 : include.requestBody) != null ? _a23 : false,
5344
+ requestBody: (_a24 = include == null ? void 0 : include.requestBody) != null ? _a24 : false,
5310
5345
  requestMessages: (_b = include == null ? void 0 : include.requestMessages) != null ? _b : false,
5311
5346
  responseBody: (_c = include == null ? void 0 : include.responseBody) != null ? _c : false
5312
5347
  };
@@ -5405,7 +5440,7 @@ async function generateText({
5405
5440
  toolsContext
5406
5441
  };
5407
5442
  const executeGenerateText = async () => {
5408
- var _a24;
5443
+ var _a25;
5409
5444
  await notify({
5410
5445
  event: generateTextStartEvent,
5411
5446
  callbacks: [resolvedOnStart, telemetryDispatcher.onStart]
@@ -5551,7 +5586,7 @@ async function generateText({
5551
5586
  type: "step",
5552
5587
  event: { callId, stepNumber },
5553
5588
  execute: async () => {
5554
- var _a25, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
5589
+ var _a26, _b2, _c2, _d2, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
5555
5590
  const accumulatedResponseMessages = [
5556
5591
  ...initialResponseMessages,
5557
5592
  ...steps.flatMap((step) => step.response.messages)
@@ -5570,7 +5605,7 @@ async function generateText({
5570
5605
  toolsContext,
5571
5606
  experimental_sandbox: sandbox
5572
5607
  }));
5573
- const stepSandbox = (_a25 = prepareStepResult == null ? void 0 : prepareStepResult.experimental_sandbox) != null ? _a25 : sandbox;
5608
+ const stepSandbox = (_a26 = prepareStepResult == null ? void 0 : prepareStepResult.experimental_sandbox) != null ? _a26 : sandbox;
5574
5609
  const stepModel = resolveLanguageModel(
5575
5610
  (_b2 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _b2 : model
5576
5611
  );
@@ -5665,7 +5700,7 @@ async function generateText({
5665
5700
  });
5666
5701
  const executeLanguageModelCallInTelemetryContext = (_n = telemetryDispatcher.executeLanguageModelCall) != null ? _n : async ({ execute }) => await execute();
5667
5702
  currentModelResponse = await retry(async () => {
5668
- var _a26, _b3, _c3, _d3, _e2, _f2, _g2, _h2;
5703
+ var _a27, _b3, _c3, _d3, _e2, _f2, _g2, _h2;
5669
5704
  const result = await executeLanguageModelCallInTelemetryContext(
5670
5705
  {
5671
5706
  ...languageModelCallStartEvent,
@@ -5682,7 +5717,7 @@ async function generateText({
5682
5717
  }
5683
5718
  );
5684
5719
  const responseData = {
5685
- id: (_b3 = (_a26 = result.response) == null ? void 0 : _a26.id) != null ? _b3 : generateId4(),
5720
+ id: (_b3 = (_a27 = result.response) == null ? void 0 : _a27.id) != null ? _b3 : generateId4(),
5686
5721
  timestamp: (_d3 = (_c3 = result.response) == null ? void 0 : _c3.timestamp) != null ? _d3 : /* @__PURE__ */ new Date(),
5687
5722
  modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,
5688
5723
  headers: (_g2 = result.response) == null ? void 0 : _g2.headers,
@@ -5804,6 +5839,7 @@ async function generateText({
5804
5839
  type: "tool-approval-request",
5805
5840
  approvalId,
5806
5841
  toolCall,
5842
+ ...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},
5807
5843
  ...signature != null ? { signature } : {}
5808
5844
  };
5809
5845
  blockedToolCallIds.add(toolCall.toolCallId);
@@ -6042,8 +6078,8 @@ async function generateText({
6042
6078
  const staticToolResults = steps.flatMap((step) => step.staticToolResults);
6043
6079
  const dynamicToolResults = steps.flatMap((step) => step.dynamicToolResults);
6044
6080
  const warnings = steps.flatMap((step) => {
6045
- var _a25;
6046
- return (_a25 = step.warnings) != null ? _a25 : [];
6081
+ var _a26;
6082
+ return (_a26 = step.warnings) != null ? _a26 : [];
6047
6083
  });
6048
6084
  const onEndEvent = {
6049
6085
  callId,
@@ -6083,7 +6119,7 @@ async function generateText({
6083
6119
  callbacks: [onEnd, telemetryDispatcher.onEnd]
6084
6120
  });
6085
6121
  let resolvedOutput;
6086
- if (lastStep.finishReason === "stop" || lastStep.finishReason == null && lastStep.text.length > 0) {
6122
+ if (lastStep.finishReason === "stop" || lastStep.finishReason !== "tool-calls" && lastStep.text.length > 0) {
6087
6123
  const outputSpecification = output != null ? output : text();
6088
6124
  resolvedOutput = await outputSpecification.parseCompleteOutput(
6089
6125
  { text: lastStep.text },
@@ -6101,7 +6137,7 @@ async function generateText({
6101
6137
  output: resolvedOutput
6102
6138
  });
6103
6139
  } catch (error) {
6104
- await ((_a24 = telemetryDispatcher.onError) == null ? void 0 : _a24.call(telemetryDispatcher, { callId, error }));
6140
+ await ((_a25 = telemetryDispatcher.onError) == null ? void 0 : _a25.call(telemetryDispatcher, { callId, error }));
6105
6141
  throw wrapGatewayError(error);
6106
6142
  }
6107
6143
  };
@@ -6201,8 +6237,8 @@ var DefaultGenerateTextResult = class {
6201
6237
  }
6202
6238
  get warnings() {
6203
6239
  return this.steps.flatMap((step) => {
6204
- var _a23;
6205
- return (_a23 = step.warnings) != null ? _a23 : [];
6240
+ var _a24;
6241
+ return (_a24 = step.warnings) != null ? _a24 : [];
6206
6242
  });
6207
6243
  }
6208
6244
  get providerMetadata() {
@@ -6647,6 +6683,7 @@ var uiMessageChunkSchema = lazySchema(
6647
6683
  type: z.literal("tool-approval-request"),
6648
6684
  approvalId: z.string(),
6649
6685
  toolCallId: z.string(),
6686
+ reason: z.string().optional(),
6650
6687
  isAutomatic: z.boolean().optional(),
6651
6688
  signature: z.string().optional()
6652
6689
  }),
@@ -6850,7 +6887,7 @@ function processUIMessageStream({
6850
6887
  new TransformStream({
6851
6888
  async transform(chunk, controller) {
6852
6889
  await runUpdateMessageJob(async ({ state, write }) => {
6853
- var _a23, _b, _c, _d;
6890
+ var _a24, _b, _c, _d;
6854
6891
  function getCurrentStepParts() {
6855
6892
  const parts = state.message.parts;
6856
6893
  let currentStepStartIndex = parts.length - 1;
@@ -6890,8 +6927,8 @@ function processUIMessageStream({
6890
6927
  const toolInvocations = state.message.parts.filter(isToolUIPart);
6891
6928
  const toolInvocation = toolInvocations.find(
6892
6929
  (invocation) => {
6893
- var _a24;
6894
- return ((_a24 = invocation.approval) == null ? void 0 : _a24.id) === approvalId;
6930
+ var _a25;
6931
+ return ((_a25 = invocation.approval) == null ? void 0 : _a25.id) === approvalId;
6895
6932
  }
6896
6933
  );
6897
6934
  if (toolInvocation == null) {
@@ -6904,7 +6941,7 @@ function processUIMessageStream({
6904
6941
  return toolInvocation;
6905
6942
  }
6906
6943
  function updateToolPart(options, existingPart) {
6907
- var _a24;
6944
+ var _a25;
6908
6945
  const part = existingPart != null ? existingPart : getCurrentStepParts().find(
6909
6946
  (part2) => isStaticToolUIPart(part2) && part2.toolCallId === options.toolCallId
6910
6947
  );
@@ -6923,7 +6960,7 @@ function processUIMessageStream({
6923
6960
  if (options.toolMetadata !== void 0) {
6924
6961
  anyPart.toolMetadata = options.toolMetadata;
6925
6962
  }
6926
- anyPart.providerExecuted = (_a24 = anyOptions.providerExecuted) != null ? _a24 : part.providerExecuted;
6963
+ anyPart.providerExecuted = (_a25 = anyOptions.providerExecuted) != null ? _a25 : part.providerExecuted;
6927
6964
  const providerMetadata = anyOptions.providerMetadata;
6928
6965
  if (providerMetadata != null) {
6929
6966
  if (options.state === "output-available" || options.state === "output-error") {
@@ -6952,7 +6989,7 @@ function processUIMessageStream({
6952
6989
  }
6953
6990
  }
6954
6991
  function updateDynamicToolPart(options, existingPart) {
6955
- var _a24, _b2;
6992
+ var _a25, _b2;
6956
6993
  const part = existingPart != null ? existingPart : getCurrentStepParts().find(
6957
6994
  (part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
6958
6995
  );
@@ -6964,7 +7001,7 @@ function processUIMessageStream({
6964
7001
  anyPart.input = anyOptions.input;
6965
7002
  anyPart.output = anyOptions.output;
6966
7003
  anyPart.errorText = anyOptions.errorText;
6967
- anyPart.rawInput = (_a24 = anyOptions.rawInput) != null ? _a24 : anyPart.rawInput;
7004
+ anyPart.rawInput = (_a25 = anyOptions.rawInput) != null ? _a25 : anyPart.rawInput;
6968
7005
  anyPart.preliminary = anyOptions.preliminary;
6969
7006
  if (options.title !== void 0) {
6970
7007
  anyPart.title = options.title;
@@ -7039,7 +7076,7 @@ function processUIMessageStream({
7039
7076
  });
7040
7077
  }
7041
7078
  textPart.text += chunk.delta;
7042
- textPart.providerMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textPart.providerMetadata;
7079
+ textPart.providerMetadata = (_a24 = chunk.providerMetadata) != null ? _a24 : textPart.providerMetadata;
7043
7080
  write();
7044
7081
  break;
7045
7082
  }
@@ -7282,6 +7319,7 @@ function processUIMessageStream({
7282
7319
  toolInvocation.state = "approval-requested";
7283
7320
  toolInvocation.approval = {
7284
7321
  id: chunk.approvalId,
7322
+ ...chunk.reason != null ? { requestReason: chunk.reason } : {},
7285
7323
  ...chunk.isAutomatic === true ? { isAutomatic: true } : {},
7286
7324
  ...chunk.signature != null ? { signature: chunk.signature } : {}
7287
7325
  };
@@ -7297,6 +7335,7 @@ function processUIMessageStream({
7297
7335
  toolInvocation.approval = {
7298
7336
  id: chunk.approvalId,
7299
7337
  approved: chunk.approved,
7338
+ ...approval.requestReason != null ? { requestReason: approval.requestReason } : {},
7300
7339
  ...chunk.reason != null ? { reason: chunk.reason } : {},
7301
7340
  ...approval.isAutomatic === true ? { isAutomatic: true } : {},
7302
7341
  ...approval.signature != null ? { signature: approval.signature } : {}
@@ -7494,7 +7533,8 @@ function handleUIMessageStreamFinish({
7494
7533
  onEnd,
7495
7534
  onFinish,
7496
7535
  onError,
7497
- stream
7536
+ stream,
7537
+ getOutcome
7498
7538
  }) {
7499
7539
  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
7500
7540
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
@@ -7503,19 +7543,34 @@ function handleUIMessageStreamFinish({
7503
7543
  messageId = lastMessage.id;
7504
7544
  }
7505
7545
  let isAborted = false;
7546
+ let hasProcessingFailure = false;
7547
+ let processingError;
7548
+ const recordProcessingFailure = (error) => {
7549
+ hasProcessingFailure = true;
7550
+ processingError = error;
7551
+ };
7506
7552
  const idInjectedStream = stream.pipeThrough(
7507
7553
  new TransformStream({
7508
7554
  transform(chunk, controller) {
7509
- if (chunk.type === "start") {
7510
- const startChunk = chunk;
7511
- if (startChunk.messageId == null && messageId != null) {
7512
- startChunk.messageId = messageId;
7555
+ try {
7556
+ let outputChunk = chunk;
7557
+ if (chunk.type === "start") {
7558
+ const startChunk = chunk;
7559
+ if (startChunk.messageId == null && messageId != null) {
7560
+ outputChunk = {
7561
+ ...startChunk,
7562
+ messageId
7563
+ };
7564
+ }
7513
7565
  }
7566
+ if (chunk.type === "abort") {
7567
+ isAborted = true;
7568
+ }
7569
+ controller.enqueue(outputChunk);
7570
+ } catch (error) {
7571
+ recordProcessingFailure(error);
7572
+ throw error;
7514
7573
  }
7515
- if (chunk.type === "abort") {
7516
- isAborted = true;
7517
- }
7518
- controller.enqueue(chunk);
7519
7574
  }
7520
7575
  })
7521
7576
  );
@@ -7530,19 +7585,28 @@ function handleUIMessageStreamFinish({
7530
7585
  // will be overridden by the stream
7531
7586
  });
7532
7587
  const runUpdateMessageJob = async (job) => {
7533
- await job({ state, write: () => {
7534
- } });
7588
+ try {
7589
+ await job({ state, write: () => {
7590
+ } });
7591
+ } catch (error) {
7592
+ recordProcessingFailure(error);
7593
+ throw error;
7594
+ }
7535
7595
  };
7536
7596
  let finishCalled = false;
7537
7597
  const callOnEnd = async () => {
7598
+ var _a24;
7538
7599
  if (finishCalled || !resolvedOnEnd) {
7539
7600
  return;
7540
7601
  }
7541
7602
  finishCalled = true;
7542
7603
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
7604
+ const declaredOutcome = (_a24 = getOutcome == null ? void 0 : getOutcome()) != null ? _a24 : { status: "unknown" };
7605
+ const outcome = hasProcessingFailure ? { status: "failed", error: processingError } : declaredOutcome.status === "unknown" && isAborted ? { status: "aborted" } : declaredOutcome;
7543
7606
  await resolvedOnEnd({
7544
- isAborted,
7607
+ isAborted: isAborted || outcome.status === "aborted",
7545
7608
  isContinuation,
7609
+ outcome,
7546
7610
  responseMessage: state.message,
7547
7611
  messages: [
7548
7612
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
@@ -7754,6 +7818,7 @@ function toUIMessageChunk(part, {
7754
7818
  type: "tool-approval-request",
7755
7819
  approvalId: part.approvalId,
7756
7820
  toolCallId: part.toolCall.toolCallId,
7821
+ ...part.reason != null ? { reason: part.reason } : {},
7757
7822
  ...part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {},
7758
7823
  ...part.signature != null ? { signature: part.signature } : {}
7759
7824
  };
@@ -7862,32 +7927,96 @@ function toUIMessageStream({
7862
7927
  onEnd,
7863
7928
  onFinish
7864
7929
  }) {
7930
+ let outcome = { status: "unknown" };
7931
+ let hasFatalFailure = false;
7932
+ const setSourceOutcome = (newOutcome) => {
7933
+ if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) {
7934
+ outcome = newOutcome;
7935
+ }
7936
+ };
7937
+ const failOutcome = (error) => {
7938
+ hasFatalFailure = true;
7939
+ outcome = { status: "failed", error };
7940
+ };
7865
7941
  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({
7866
7942
  originalMessages,
7867
7943
  responseMessageId: generateMessageId
7868
7944
  }) : void 0;
7869
- const uiMessageChunkStream = stream.pipeThrough(
7945
+ const sourceReader = stream.getReader();
7946
+ let sourceReaderReleased = false;
7947
+ let sourceStreamCancelled = false;
7948
+ const releaseSourceReader = () => {
7949
+ if (!sourceReaderReleased) {
7950
+ sourceReader.releaseLock();
7951
+ sourceReaderReleased = true;
7952
+ }
7953
+ };
7954
+ const sourceStream = new ReadableStream({
7955
+ async pull(controller) {
7956
+ try {
7957
+ const { done, value } = await sourceReader.read();
7958
+ if (done) {
7959
+ releaseSourceReader();
7960
+ if (!sourceStreamCancelled) {
7961
+ controller.close();
7962
+ }
7963
+ } else {
7964
+ controller.enqueue(value);
7965
+ }
7966
+ } catch (error) {
7967
+ releaseSourceReader();
7968
+ if (!sourceStreamCancelled) {
7969
+ failOutcome(error);
7970
+ controller.error(error);
7971
+ }
7972
+ }
7973
+ },
7974
+ async cancel(reason) {
7975
+ sourceStreamCancelled = true;
7976
+ if (sourceReaderReleased) {
7977
+ return;
7978
+ }
7979
+ try {
7980
+ await sourceReader.cancel(reason);
7981
+ } finally {
7982
+ releaseSourceReader();
7983
+ }
7984
+ }
7985
+ });
7986
+ const uiMessageChunkStream = sourceStream.pipeThrough(
7870
7987
  new TransformStream({
7871
7988
  transform: async (part, controller) => {
7872
- const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
7873
- const uiMessageChunk = toUIMessageChunk(part, {
7874
- tools,
7875
- sendReasoning,
7876
- sendSources,
7877
- sendStart,
7878
- sendFinish,
7879
- onError,
7880
- messageMetadata: messageMetadataValue,
7881
- responseMessageId
7882
- });
7883
- if (uiMessageChunk != null) {
7884
- controller.enqueue(uiMessageChunk);
7885
- }
7886
- if (messageMetadataValue != null && part.type !== "start" && part.type !== "finish") {
7887
- controller.enqueue({
7888
- type: "message-metadata",
7889
- messageMetadata: messageMetadataValue
7989
+ try {
7990
+ const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
7991
+ const uiMessageChunk = toUIMessageChunk(part, {
7992
+ tools,
7993
+ sendReasoning,
7994
+ sendSources,
7995
+ sendStart,
7996
+ sendFinish,
7997
+ onError,
7998
+ messageMetadata: messageMetadataValue,
7999
+ responseMessageId
7890
8000
  });
8001
+ if (uiMessageChunk != null) {
8002
+ controller.enqueue(uiMessageChunk);
8003
+ }
8004
+ if (messageMetadataValue != null && part.type !== "start" && part.type !== "finish") {
8005
+ controller.enqueue({
8006
+ type: "message-metadata",
8007
+ messageMetadata: messageMetadataValue
8008
+ });
8009
+ }
8010
+ if (part.type === "finish") {
8011
+ setSourceOutcome({ status: "completed" });
8012
+ } else if (part.type === "abort") {
8013
+ setSourceOutcome({ status: "aborted" });
8014
+ } else if (part.type === "error") {
8015
+ setSourceOutcome({ status: "failed", error: part.error });
8016
+ }
8017
+ } catch (error) {
8018
+ failOutcome(error);
8019
+ throw error;
7891
8020
  }
7892
8021
  }
7893
8022
  })
@@ -7897,7 +8026,8 @@ function toUIMessageStream({
7897
8026
  messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),
7898
8027
  originalMessages,
7899
8028
  onEnd: onEnd != null ? onEnd : onFinish,
7900
- onError
8029
+ onError,
8030
+ getOutcome: () => outcome
7901
8031
  });
7902
8032
  }
7903
8033
 
@@ -7910,13 +8040,13 @@ function asAsyncIterableStream(stream) {
7910
8040
  const reader = this.getReader();
7911
8041
  let finished = false;
7912
8042
  async function cleanup(cancelStream) {
7913
- var _a23;
8043
+ var _a24;
7914
8044
  if (finished)
7915
8045
  return;
7916
8046
  finished = true;
7917
8047
  try {
7918
8048
  if (cancelStream) {
7919
- await ((_a23 = reader.cancel) == null ? void 0 : _a23.call(reader));
8049
+ await ((_a24 = reader.cancel) == null ? void 0 : _a24.call(reader));
7920
8050
  }
7921
8051
  } finally {
7922
8052
  try {
@@ -8022,8 +8152,12 @@ function createStitchableStream() {
8022
8152
  let innerStreams = [];
8023
8153
  let controller = null;
8024
8154
  let isClosed = false;
8155
+ let isCancelled = false;
8025
8156
  let waitForNewStream = createResolvablePromise();
8026
8157
  const terminate = () => {
8158
+ if (isCancelled) {
8159
+ return;
8160
+ }
8027
8161
  isClosed = true;
8028
8162
  waitForNewStream.resolve();
8029
8163
  innerStreams.forEach(({ reader, onCancel }) => {
@@ -8034,7 +8168,10 @@ function createStitchableStream() {
8034
8168
  controller == null ? void 0 : controller.close();
8035
8169
  };
8036
8170
  const processPull = async () => {
8037
- var _a23;
8171
+ var _a24;
8172
+ if (isCancelled) {
8173
+ return;
8174
+ }
8038
8175
  if (isClosed && innerStreams.length === 0) {
8039
8176
  controller == null ? void 0 : controller.close();
8040
8177
  return;
@@ -8047,6 +8184,9 @@ function createStitchableStream() {
8047
8184
  const currentStream = innerStreams[0];
8048
8185
  try {
8049
8186
  const { value, done } = await currentStream.reader.read();
8187
+ if (isCancelled) {
8188
+ return;
8189
+ }
8050
8190
  if (done) {
8051
8191
  innerStreams.shift();
8052
8192
  if (innerStreams.length === 0 && isClosed) {
@@ -8058,7 +8198,10 @@ function createStitchableStream() {
8058
8198
  controller == null ? void 0 : controller.enqueue(value);
8059
8199
  }
8060
8200
  } catch (error) {
8061
- (_a23 = currentStream.onError) == null ? void 0 : _a23.call(currentStream, error);
8201
+ if (isCancelled) {
8202
+ return;
8203
+ }
8204
+ (_a24 = currentStream.onError) == null ? void 0 : _a24.call(currentStream, error);
8062
8205
  controller == null ? void 0 : controller.error(error);
8063
8206
  innerStreams.shift();
8064
8207
  terminate();
@@ -8071,15 +8214,24 @@ function createStitchableStream() {
8071
8214
  },
8072
8215
  pull: processPull,
8073
8216
  async cancel() {
8217
+ isCancelled = true;
8218
+ isClosed = true;
8219
+ waitForNewStream.resolve();
8074
8220
  for (const { reader, onCancel } of innerStreams) {
8075
8221
  onCancel == null ? void 0 : onCancel();
8076
8222
  await reader.cancel();
8077
8223
  }
8078
8224
  innerStreams = [];
8079
- isClosed = true;
8080
8225
  }
8081
8226
  }),
8082
8227
  addStream: (innerStream, callbacks) => {
8228
+ var _a24;
8229
+ if (isCancelled) {
8230
+ (_a24 = callbacks == null ? void 0 : callbacks.onCancel) == null ? void 0 : _a24.call(callbacks);
8231
+ void innerStream.cancel().catch(() => {
8232
+ });
8233
+ return;
8234
+ }
8083
8235
  if (isClosed) {
8084
8236
  throw new Error("Cannot add inner stream: outer stream is closed");
8085
8237
  }
@@ -8094,6 +8246,9 @@ function createStitchableStream() {
8094
8246
  * finish processing and then close the outer stream.
8095
8247
  */
8096
8248
  close: () => {
8249
+ if (isCancelled) {
8250
+ return;
8251
+ }
8097
8252
  isClosed = true;
8098
8253
  waitForNewStream.resolve();
8099
8254
  if (innerStreams.length === 0) {
@@ -8170,6 +8325,7 @@ function executeToolsFromStream({
8170
8325
  type: "tool-approval-request",
8171
8326
  approvalId,
8172
8327
  toolCall: chunk,
8328
+ ...toolApprovalStatus.reason != null ? { reason: toolApprovalStatus.reason } : {},
8173
8329
  ...signature != null ? { signature } : {}
8174
8330
  });
8175
8331
  return;
@@ -8334,6 +8490,77 @@ import {
8334
8490
  import {
8335
8491
  createIdGenerator as createIdGenerator2
8336
8492
  } from "@ai-sdk/provider-utils";
8493
+
8494
+ // src/prompt/normalize-stream-provider-error.ts
8495
+ import { AISDKError as AISDKError26 } from "@ai-sdk/provider";
8496
+ import { isProviderStreamError } from "@ai-sdk/provider-utils";
8497
+ function normalizeStreamProviderError(error) {
8498
+ var _a24, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
8499
+ if (isError(error) || AISDKError26.isInstance(error) || StreamProviderError.isInstance(error)) {
8500
+ return error;
8501
+ }
8502
+ const outer = asRecord(error);
8503
+ if (outer == null) {
8504
+ return error;
8505
+ }
8506
+ const providerStreamError = isProviderStreamError(error);
8507
+ const details = providerStreamError ? outer : (_c = (_b = asRecord((_a24 = asRecord(outer.response)) == null ? void 0 : _a24.error)) != null ? _b : asRecord(outer.error)) != null ? _c : outer;
8508
+ if (typeof details.message !== "string") {
8509
+ return error;
8510
+ }
8511
+ const type = (_d = getString(details.type)) != null ? _d : getString(outer.type);
8512
+ const code = (_e = getStringOrNumber(details.code)) != null ? _e : getStringOrNumber(outer.code);
8513
+ const explicitStatusCode = (_l = (_k = (_j = (_i = (_h = (_g = (_f = getHttpStatusCode(details.statusCode)) != null ? _f : getHttpStatusCode(outer.statusCode)) != null ? _g : getHttpStatusCode(details.status_code)) != null ? _h : getHttpStatusCode(outer.status_code)) != null ? _i : getHttpStatusCode(details.status)) != null ? _j : getHttpStatusCode(outer.status)) != null ? _k : getHttpStatusCode(details.code)) != null ? _l : getHttpStatusCode(outer.code);
8514
+ const messageMetadata = inferExactMessageMetadata(details.message);
8515
+ const statusCode = explicitStatusCode != null ? explicitStatusCode : messageMetadata == null ? void 0 : messageMetadata.statusCode;
8516
+ const explicitRetryability = (_o = (_n = (_m = getBoolean(details.isRetryable)) != null ? _m : getBoolean(outer.isRetryable)) != null ? _n : getBoolean(details.is_retryable)) != null ? _o : getBoolean(outer.is_retryable);
8517
+ return new StreamProviderError({
8518
+ message: details.message,
8519
+ type,
8520
+ code,
8521
+ statusCode,
8522
+ isRetryable: (_p = explicitRetryability != null ? explicitRetryability : messageMetadata == null ? void 0 : messageMetadata.isRetryable) != null ? _p : isRetryableStatusCode2(statusCode),
8523
+ data: providerStreamError ? error.data : error
8524
+ });
8525
+ }
8526
+ function inferExactMessageMetadata(message) {
8527
+ switch (message.trim().toLowerCase()) {
8528
+ case "overloaded":
8529
+ case "overloaded error":
8530
+ case "model overloaded":
8531
+ return { statusCode: 503, isRetryable: true };
8532
+ case "internal server error":
8533
+ return { statusCode: 500, isRetryable: true };
8534
+ case "service unavailable":
8535
+ return { statusCode: 503, isRetryable: true };
8536
+ default:
8537
+ return void 0;
8538
+ }
8539
+ }
8540
+ function isRetryableStatusCode2(statusCode) {
8541
+ return statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500);
8542
+ }
8543
+ function asRecord(value) {
8544
+ return typeof value === "object" && value != null ? value : void 0;
8545
+ }
8546
+ function isError(value) {
8547
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
8548
+ }
8549
+ function getString(value) {
8550
+ return typeof value === "string" ? value : void 0;
8551
+ }
8552
+ function getStringOrNumber(value) {
8553
+ return typeof value === "string" || typeof value === "number" ? value : void 0;
8554
+ }
8555
+ function getBoolean(value) {
8556
+ return typeof value === "boolean" ? value : void 0;
8557
+ }
8558
+ function getHttpStatusCode(value) {
8559
+ const statusCode = typeof value === "string" && /^\d{3}$/.test(value) ? Number(value) : value;
8560
+ return typeof statusCode === "number" && Number.isInteger(statusCode) && statusCode >= 400 && statusCode <= 599 ? statusCode : void 0;
8561
+ }
8562
+
8563
+ // src/generate-text/stream-language-model-call.ts
8337
8564
  var originalGenerateId2 = createIdGenerator2({
8338
8565
  prefix: "aitxt",
8339
8566
  size: 24
@@ -8487,7 +8714,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8487
8714
  const timeBetweenOutputChunksMs = [];
8488
8715
  return new TransformStream({
8489
8716
  async transform(chunk, controller) {
8490
- var _a23, _b, _c;
8717
+ var _a24, _b, _c;
8491
8718
  if (isOutputChunk(chunk)) {
8492
8719
  const outputChunkTimestampMs = now2();
8493
8720
  if (timeToFirstOutputMs == null) {
@@ -8500,6 +8727,12 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8500
8727
  previousOutputChunkTimestampMs = outputChunkTimestampMs;
8501
8728
  }
8502
8729
  switch (chunk.type) {
8730
+ case "error":
8731
+ controller.enqueue({
8732
+ type: "error",
8733
+ error: normalizeStreamProviderError(chunk.error)
8734
+ });
8735
+ break;
8503
8736
  case "text-start":
8504
8737
  upsertTextContentPart({
8505
8738
  content: modelCallContent,
@@ -8726,7 +8959,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
8726
8959
  const tool2 = getOwn(tools, chunk.toolName);
8727
8960
  controller.enqueue({
8728
8961
  ...chunk,
8729
- dynamic: (_a23 = chunk.dynamic) != null ? _a23 : (tool2 == null ? void 0 : tool2.type) === "dynamic",
8962
+ dynamic: (_a24 = chunk.dynamic) != null ? _a24 : (tool2 == null ? void 0 : tool2.type) === "dynamic",
8730
8963
  title: tool2 == null ? void 0 : tool2.title,
8731
8964
  ...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}
8732
8965
  });
@@ -8920,7 +9153,7 @@ function streamText({
8920
9153
  } = {},
8921
9154
  ...settings
8922
9155
  }) {
8923
- var _a23, _b, _c, _d;
9156
+ var _a24, _b, _c, _d;
8924
9157
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
8925
9158
  const stepTimeoutMs = getStepTimeoutMs(timeout);
8926
9159
  const firstChunkTimeoutMs = getFirstChunkTimeoutMs(timeout);
@@ -8994,7 +9227,7 @@ function streamText({
8994
9227
  download: download2,
8995
9228
  // assign default values to include:
8996
9229
  include: {
8997
- requestBody: (_a23 = include == null ? void 0 : include.requestBody) != null ? _a23 : false,
9230
+ requestBody: (_a24 = include == null ? void 0 : include.requestBody) != null ? _a24 : false,
8998
9231
  requestMessages: (_b = include == null ? void 0 : include.requestMessages) != null ? _b : false,
8999
9232
  rawChunks: (_d = (_c = include == null ? void 0 : include.rawChunks) != null ? _c : includeRawChunks) != null ? _d : false
9000
9233
  }
@@ -9029,7 +9262,7 @@ function createOutputTransformStream(output) {
9029
9262
  }
9030
9263
  return new TransformStream({
9031
9264
  async transform(chunk, controller) {
9032
- var _a23;
9265
+ var _a24;
9033
9266
  if (chunk.type === "finish-step" && textChunk.length > 0) {
9034
9267
  publishTextChunk({ controller });
9035
9268
  }
@@ -9056,7 +9289,7 @@ function createOutputTransformStream(output) {
9056
9289
  }
9057
9290
  text2 += chunk.text;
9058
9291
  textChunk += chunk.text;
9059
- textProviderMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textProviderMetadata;
9292
+ textProviderMetadata = (_a24 = chunk.providerMetadata) != null ? _a24 : textProviderMetadata;
9060
9293
  if (chunk.text.length === 0 && chunk.providerMetadata != null) {
9061
9294
  controller.enqueue({ part: chunk, partialOutput: void 0 });
9062
9295
  return;
@@ -9179,7 +9412,7 @@ var DefaultStreamTextResult = class {
9179
9412
  let recordedNoOutputError;
9180
9413
  const eventProcessor = new TransformStream({
9181
9414
  async transform(chunk, controller) {
9182
- var _a23, _b, _c, _d;
9415
+ var _a24, _b, _c, _d;
9183
9416
  controller.enqueue(chunk);
9184
9417
  const { part } = chunk;
9185
9418
  await notify({
@@ -9220,7 +9453,7 @@ var DefaultStreamTextResult = class {
9220
9453
  return;
9221
9454
  }
9222
9455
  activeText.text += part.text;
9223
- activeText.providerMetadata = (_a23 = part.providerMetadata) != null ? _a23 : activeText.providerMetadata;
9456
+ activeText.providerMetadata = (_a24 = part.providerMetadata) != null ? _a24 : activeText.providerMetadata;
9224
9457
  }
9225
9458
  if (part.type === "text-end") {
9226
9459
  const activeText = activeTextContent[part.id];
@@ -9376,8 +9609,8 @@ var DefaultStreamTextResult = class {
9376
9609
  (step) => step.dynamicToolResults
9377
9610
  );
9378
9611
  const warnings = recordedSteps.flatMap((step) => {
9379
- var _a23;
9380
- return (_a23 = step.warnings) != null ? _a23 : [];
9612
+ var _a24;
9613
+ return (_a24 = step.warnings) != null ? _a24 : [];
9381
9614
  });
9382
9615
  await notify({
9383
9616
  event: {
@@ -9500,7 +9733,7 @@ var DefaultStreamTextResult = class {
9500
9733
  const self = this;
9501
9734
  const callId = generateCallId();
9502
9735
  (async () => {
9503
- var _a23;
9736
+ var _a24;
9504
9737
  const initialPrompt = await standardizePrompt({
9505
9738
  instructions,
9506
9739
  system,
@@ -9536,14 +9769,14 @@ var DefaultStreamTextResult = class {
9536
9769
  runtimeContext,
9537
9770
  toolsContext
9538
9771
  };
9539
- const streamTextTracingChannelContext = (_a23 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a23.call(telemetryDispatcher, {
9772
+ const streamTextTracingChannelContext = (_a24 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a24.call(telemetryDispatcher, {
9540
9773
  type: "streamText",
9541
9774
  event: startEvent,
9542
9775
  completion: self._totalUsage.promise.then(() => void 0)
9543
9776
  });
9544
9777
  const runInStreamTextTracingChannelContext = (execute) => {
9545
- var _a24;
9546
- return (_a24 = streamTextTracingChannelContext == null ? void 0 : streamTextTracingChannelContext.run(execute)) != null ? _a24 : execute();
9778
+ var _a25;
9779
+ return (_a25 = streamTextTracingChannelContext == null ? void 0 : streamTextTracingChannelContext.run(execute)) != null ? _a25 : execute();
9547
9780
  };
9548
9781
  const runInTracingChannelSpanInStreamText = telemetryDispatcher.runInTracingChannelSpan == null ? void 0 : (options) => runInStreamTextTracingChannelContext(
9549
9782
  () => telemetryDispatcher.runInTracingChannelSpan(options)
@@ -9700,7 +9933,7 @@ var DefaultStreamTextResult = class {
9700
9933
  currentStep,
9701
9934
  usage
9702
9935
  }) {
9703
- var _a24, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
9936
+ var _a25, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
9704
9937
  const stepTimeoutId = setAbortTimeout({
9705
9938
  abortController: stepAbortController,
9706
9939
  label: "Step",
@@ -9759,14 +9992,14 @@ var DefaultStreamTextResult = class {
9759
9992
  });
9760
9993
  try {
9761
9994
  stepFinish = new DelayedPromise();
9762
- const stepTracingChannelContext = (_a24 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a24.call(telemetryDispatcher, {
9995
+ const stepTracingChannelContext = (_a25 = telemetryDispatcher.startTracingChannelContext) == null ? void 0 : _a25.call(telemetryDispatcher, {
9763
9996
  type: "step",
9764
9997
  event: { callId, stepNumber: currentStep },
9765
9998
  completion: stepFinish.promise
9766
9999
  });
9767
10000
  const runInStepTracingChannelContext = (execute) => {
9768
- var _a25;
9769
- return (_a25 = stepTracingChannelContext == null ? void 0 : stepTracingChannelContext.run(execute)) != null ? _a25 : execute();
10001
+ var _a26;
10002
+ return (_a26 = stepTracingChannelContext == null ? void 0 : stepTracingChannelContext.run(execute)) != null ? _a26 : execute();
9770
10003
  };
9771
10004
  const responseMessagesFromPreviousSteps = recordedSteps.flatMap(
9772
10005
  (step) => step.response.messages
@@ -9841,9 +10074,9 @@ var DefaultStreamTextResult = class {
9841
10074
  } = await runInStepTracingChannelContext(
9842
10075
  () => retry(
9843
10076
  async () => {
9844
- var _a25, _b2;
10077
+ var _a26, _b2;
9845
10078
  return streamLanguageModelCall({
9846
- model: (_a25 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a25 : model,
10079
+ model: (_a26 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a26 : model,
9847
10080
  tools: stepModelTools,
9848
10081
  toolOrder: stepToolOrder,
9849
10082
  toolChoice: (_b2 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _b2 : toolChoice,
@@ -9871,7 +10104,7 @@ var DefaultStreamTextResult = class {
9871
10104
  telemetryDispatcher.onLanguageModelCallEnd
9872
10105
  ),
9873
10106
  onStart: async ({ promptMessages }) => {
9874
- var _a26, _b3;
10107
+ var _a27, _b3;
9875
10108
  await notify({
9876
10109
  event: {
9877
10110
  callId,
@@ -9881,7 +10114,7 @@ var DefaultStreamTextResult = class {
9881
10114
  instructions: stepInstructions,
9882
10115
  messages: stepMessages,
9883
10116
  tools,
9884
- toolChoice: (_a26 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _a26 : toolChoice,
10117
+ toolChoice: (_a27 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _a27 : toolChoice,
9885
10118
  activeTools: (_b3 = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _b3 : activeTools,
9886
10119
  toolOrder: stepToolOrder,
9887
10120
  steps: [...recordedSteps],
@@ -9979,7 +10212,7 @@ var DefaultStreamTextResult = class {
9979
10212
  streamWithToolResults.pipeThrough(
9980
10213
  new TransformStream({
9981
10214
  async transform(chunk, controller) {
9982
- var _a25, _b2, _c2, _d2, _e2, _f2, _g2;
10215
+ var _a26, _b2, _c2, _d2, _e2, _f2, _g2;
9983
10216
  if (chunk.type === "model-call-start") {
9984
10217
  warnings = chunk.warnings;
9985
10218
  return;
@@ -10022,7 +10255,7 @@ var DefaultStreamTextResult = class {
10022
10255
  if (chunk.text.length > 0 || chunk.providerMetadata != null) {
10023
10256
  controller.enqueue({
10024
10257
  ...chunk,
10025
- id: (_a25 = textPartIds.get(chunk.id)) != null ? _a25 : chunk.id
10258
+ id: (_a26 = textPartIds.get(chunk.id)) != null ? _a26 : chunk.id
10026
10259
  });
10027
10260
  }
10028
10261
  break;
@@ -10235,8 +10468,8 @@ var DefaultStreamTextResult = class {
10235
10468
  )
10236
10469
  );
10237
10470
  })().catch(async (error) => {
10238
- var _a23;
10239
- await ((_a23 = telemetryDispatcher.onError) == null ? void 0 : _a23.call(telemetryDispatcher, { callId, error }));
10471
+ var _a24;
10472
+ await ((_a24 = telemetryDispatcher.onError) == null ? void 0 : _a24.call(telemetryDispatcher, { callId, error }));
10240
10473
  self._initialResponseMessages.reject(error);
10241
10474
  markPromiseAsHandled(self._initialResponseMessages.promise);
10242
10475
  self.addStream(
@@ -10262,8 +10495,8 @@ var DefaultStreamTextResult = class {
10262
10495
  }
10263
10496
  get warnings() {
10264
10497
  return this.steps.then((steps) => steps.flatMap((step) => {
10265
- var _a23;
10266
- return (_a23 = step.warnings) != null ? _a23 : [];
10498
+ var _a24;
10499
+ return (_a24 = step.warnings) != null ? _a24 : [];
10267
10500
  }));
10268
10501
  }
10269
10502
  get providerMetadata() {
@@ -10392,19 +10625,19 @@ var DefaultStreamTextResult = class {
10392
10625
  }
10393
10626
  }
10394
10627
  async consumeStream(options) {
10395
- var _a23;
10628
+ var _a24;
10396
10629
  try {
10397
10630
  await consumeStream({
10398
10631
  stream: this.stream,
10399
10632
  onError: (error) => {
10400
- var _a24;
10633
+ var _a25;
10401
10634
  this.rejectResultPromises(error);
10402
- (_a24 = options == null ? void 0 : options.onError) == null ? void 0 : _a24.call(options, error);
10635
+ (_a25 = options == null ? void 0 : options.onError) == null ? void 0 : _a25.call(options, error);
10403
10636
  }
10404
10637
  });
10405
10638
  } catch (error) {
10406
10639
  this.rejectResultPromises(error);
10407
- (_a23 = options == null ? void 0 : options.onError) == null ? void 0 : _a23.call(options, error);
10640
+ (_a24 = options == null ? void 0 : options.onError) == null ? void 0 : _a24.call(options, error);
10408
10641
  }
10409
10642
  }
10410
10643
  get experimental_partialOutputStream() {
@@ -10424,8 +10657,8 @@ var DefaultStreamTextResult = class {
10424
10657
  );
10425
10658
  }
10426
10659
  get elementStream() {
10427
- var _a23, _b, _c;
10428
- const transform = (_a23 = this.outputSpecification) == null ? void 0 : _a23.createElementStreamTransform();
10660
+ var _a24, _b, _c;
10661
+ const transform = (_a24 = this.outputSpecification) == null ? void 0 : _a24.createElementStreamTransform();
10429
10662
  if (transform == null) {
10430
10663
  throw new UnsupportedFunctionalityError2({
10431
10664
  functionality: `element streams in ${(_c = (_b = this.outputSpecification) == null ? void 0 : _b.name) != null ? _c : "text"} mode`
@@ -10435,8 +10668,8 @@ var DefaultStreamTextResult = class {
10435
10668
  }
10436
10669
  get output() {
10437
10670
  return this.finalStep.then((step) => {
10438
- var _a23;
10439
- const output = (_a23 = this.outputSpecification) != null ? _a23 : text();
10671
+ var _a24;
10672
+ const output = (_a24 = this.outputSpecification) != null ? _a24 : text();
10440
10673
  return output.parseCompleteOutput(
10441
10674
  { text: step.text },
10442
10675
  {
@@ -10567,7 +10800,7 @@ var ToolLoopAgent = class {
10567
10800
  return this.settings.tools;
10568
10801
  }
10569
10802
  async prepareCall(options) {
10570
- var _a23, _b, _c, _d;
10803
+ var _a24, _b, _c, _d;
10571
10804
  if (this.settings.callOptionsSchema != null && options.options !== void 0) {
10572
10805
  const validatedOptions = await validateTypes3({
10573
10806
  value: options.options,
@@ -10591,7 +10824,7 @@ var ToolLoopAgent = class {
10591
10824
  } = this.settings;
10592
10825
  const baseCallArgs = {
10593
10826
  ...settingsWithoutCallbacks,
10594
- stopWhen: (_a23 = this.settings.stopWhen) != null ? _a23 : isStepCount(20),
10827
+ stopWhen: (_a24 = this.settings.stopWhen) != null ? _a24 : isStepCount(20),
10595
10828
  ...options
10596
10829
  };
10597
10830
  const preparedCallArgs = (_d = await ((_c = (_b = this.settings).prepareCall) == null ? void 0 : _c.call(
@@ -10630,9 +10863,9 @@ var ToolLoopAgent = class {
10630
10863
  * downstream by generateText/streamText and the provider.
10631
10864
  */
10632
10865
  agentHeaders(preparedCall) {
10633
- var _a23;
10866
+ var _a24;
10634
10867
  return withUserAgentSuffix3(
10635
- (_a23 = preparedCall.headers) != null ? _a23 : {},
10868
+ (_a24 = preparedCall.headers) != null ? _a24 : {},
10636
10869
  "ai-sdk-agent/tool-loop"
10637
10870
  );
10638
10871
  }
@@ -10655,7 +10888,7 @@ var ToolLoopAgent = class {
10655
10888
  onEnd = onFinish,
10656
10889
  ...options
10657
10890
  }) {
10658
- var _a23, _b, _c;
10891
+ var _a24, _b, _c;
10659
10892
  const generate = generateText;
10660
10893
  const preparedCall = await this.prepareCall({
10661
10894
  ...options,
@@ -10666,7 +10899,7 @@ var ToolLoopAgent = class {
10666
10899
  timeout: timeout != null ? timeout : preparedCall.timeout,
10667
10900
  experimental_sandbox: sandbox,
10668
10901
  onStart: mergeCallbacks(
10669
- (_a23 = this.settings.onStart) != null ? _a23 : this.settings.experimental_onStart,
10902
+ (_a24 = this.settings.onStart) != null ? _a24 : this.settings.experimental_onStart,
10670
10903
  onStart != null ? onStart : experimental_onStart
10671
10904
  ),
10672
10905
  onStepStart: mergeCallbacks(
@@ -10713,7 +10946,7 @@ var ToolLoopAgent = class {
10713
10946
  onEnd = onFinish,
10714
10947
  ...options
10715
10948
  }) {
10716
- var _a23, _b, _c;
10949
+ var _a24, _b, _c;
10717
10950
  const stream = streamText;
10718
10951
  const preparedCall = await this.prepareCall({
10719
10952
  ...options,
@@ -10725,7 +10958,7 @@ var ToolLoopAgent = class {
10725
10958
  experimental_sandbox: sandbox,
10726
10959
  experimental_transform,
10727
10960
  onStart: mergeCallbacks(
10728
- (_a23 = this.settings.onStart) != null ? _a23 : this.settings.experimental_onStart,
10961
+ (_a24 = this.settings.onStart) != null ? _a24 : this.settings.experimental_onStart,
10729
10962
  onStart != null ? onStart : experimental_onStart
10730
10963
  ),
10731
10964
  onStepStart: mergeCallbacks(
@@ -10771,6 +11004,7 @@ function createUIMessageStream({
10771
11004
  }) {
10772
11005
  let controller;
10773
11006
  const ongoingStreamPromises = [];
11007
+ let outcome = { status: "unknown" };
10774
11008
  const stream = new ReadableStream({
10775
11009
  start(controllerArg) {
10776
11010
  controller = controllerArg;
@@ -10782,6 +11016,35 @@ function createUIMessageStream({
10782
11016
  } catch (e) {
10783
11017
  }
10784
11018
  }
11019
+ function setOutcome(newOutcome) {
11020
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") {
11021
+ outcome = newOutcome;
11022
+ }
11023
+ }
11024
+ function failOutcome(error) {
11025
+ outcome = { status: "failed", error };
11026
+ }
11027
+ function safeError(error) {
11028
+ try {
11029
+ controller.error(error);
11030
+ } catch (e) {
11031
+ }
11032
+ }
11033
+ function handleError(error) {
11034
+ failOutcome(error);
11035
+ let errorText;
11036
+ try {
11037
+ errorText = onError(error);
11038
+ } catch (onErrorError) {
11039
+ failOutcome(onErrorError);
11040
+ safeError(onErrorError);
11041
+ return;
11042
+ }
11043
+ safeEnqueue({
11044
+ type: "error",
11045
+ errorText
11046
+ });
11047
+ }
10785
11048
  try {
10786
11049
  const result = execute({
10787
11050
  writer: {
@@ -10799,38 +11062,29 @@ function createUIMessageStream({
10799
11062
  safeEnqueue(value);
10800
11063
  }
10801
11064
  })().catch((error) => {
10802
- safeEnqueue({
10803
- type: "error",
10804
- errorText: onError(error)
10805
- });
11065
+ handleError(error);
10806
11066
  })
10807
11067
  );
10808
11068
  },
11069
+ setOutcome,
10809
11070
  onError
10810
11071
  }
10811
11072
  });
10812
11073
  if (result) {
10813
11074
  ongoingStreamPromises.push(
10814
11075
  result.catch((error) => {
10815
- safeEnqueue({
10816
- type: "error",
10817
- errorText: onError(error)
10818
- });
11076
+ handleError(error);
10819
11077
  })
10820
11078
  );
10821
11079
  }
10822
11080
  } catch (error) {
10823
- safeEnqueue({
10824
- type: "error",
10825
- errorText: onError(error)
10826
- });
11081
+ handleError(error);
10827
11082
  }
10828
- const waitForStreams = new Promise(async (resolve3) => {
11083
+ const waitForStreams = (async () => {
10829
11084
  while (ongoingStreamPromises.length > 0) {
10830
11085
  await ongoingStreamPromises.shift();
10831
11086
  }
10832
- resolve3();
10833
- });
11087
+ })();
10834
11088
  waitForStreams.finally(() => {
10835
11089
  try {
10836
11090
  controller.close();
@@ -10843,7 +11097,8 @@ function createUIMessageStream({
10843
11097
  originalMessages,
10844
11098
  onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish,
10845
11099
  onEnd: onEnd != null ? onEnd : onFinish,
10846
- onError
11100
+ onError,
11101
+ getOutcome: () => outcome
10847
11102
  });
10848
11103
  }
10849
11104
 
@@ -10875,7 +11130,7 @@ function readUIMessageStream({
10875
11130
  onError,
10876
11131
  terminateOnError = false
10877
11132
  }) {
10878
- var _a23;
11133
+ var _a24;
10879
11134
  let controller;
10880
11135
  let hasErrored = false;
10881
11136
  const outputStream = new ReadableStream({
@@ -10884,7 +11139,7 @@ function readUIMessageStream({
10884
11139
  }
10885
11140
  });
10886
11141
  const state = createStreamingUIMessageState({
10887
- messageId: (_a23 = message == null ? void 0 : message.id) != null ? _a23 : "",
11142
+ messageId: (_a24 = message == null ? void 0 : message.id) != null ? _a24 : "",
10888
11143
  lastMessage: message
10889
11144
  });
10890
11145
  const handleError = (error) => {
@@ -10953,7 +11208,7 @@ async function convertToModelMessages(messages, options) {
10953
11208
  modelMessages.push({
10954
11209
  role: "user",
10955
11210
  content: message.parts.map((part) => {
10956
- var _a23;
11211
+ var _a24;
10957
11212
  if (isTextUIPart(part)) {
10958
11213
  return {
10959
11214
  type: "text",
@@ -10974,7 +11229,7 @@ async function convertToModelMessages(messages, options) {
10974
11229
  };
10975
11230
  }
10976
11231
  if (isDataUIPart(part)) {
10977
- return (_a23 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a23.call(
11232
+ return (_a24 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a24.call(
10978
11233
  options,
10979
11234
  part
10980
11235
  );
@@ -10987,7 +11242,7 @@ async function convertToModelMessages(messages, options) {
10987
11242
  if (message.parts != null) {
10988
11243
  let block = [];
10989
11244
  async function processBlock() {
10990
- var _a23, _b, _c, _d, _e, _f, _g;
11245
+ var _a24, _b, _c, _d, _e, _f, _g;
10991
11246
  if (block.length === 0) {
10992
11247
  return;
10993
11248
  }
@@ -11036,7 +11291,7 @@ async function convertToModelMessages(messages, options) {
11036
11291
  type: "tool-call",
11037
11292
  toolCallId: part.toolCallId,
11038
11293
  toolName,
11039
- input: part.state === "output-error" ? (_a23 = part.input) != null ? _a23 : "rawInput" in part ? part.rawInput : void 0 : part.input,
11294
+ input: part.state === "output-error" ? (_a24 = part.input) != null ? _a24 : "rawInput" in part ? part.rawInput : void 0 : part.input,
11040
11295
  providerExecuted: part.providerExecuted,
11041
11296
  ...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}
11042
11297
  });
@@ -11046,6 +11301,7 @@ async function convertToModelMessages(messages, options) {
11046
11301
  approvalId: part.approval.id,
11047
11302
  toolCallId: part.toolCallId,
11048
11303
  isAutomatic: part.approval.isAutomatic,
11304
+ ...part.approval.requestReason != null ? { reason: part.approval.requestReason } : {},
11049
11305
  ...part.approval.signature != null ? { signature: part.approval.signature } : {}
11050
11306
  });
11051
11307
  }
@@ -11087,8 +11343,8 @@ async function convertToModelMessages(messages, options) {
11087
11343
  }
11088
11344
  const toolParts = block.filter(
11089
11345
  (part) => {
11090
- var _a24;
11091
- return isToolUIPart(part) && (part.providerExecuted !== true || ((_a24 = part.approval) == null ? void 0 : _a24.approved) != null);
11346
+ var _a25;
11347
+ return isToolUIPart(part) && (part.providerExecuted !== true || ((_a25 = part.approval) == null ? void 0 : _a25.approved) != null);
11092
11348
  }
11093
11349
  );
11094
11350
  if (toolParts.length > 0) {
@@ -11191,6 +11447,7 @@ async function convertToModelMessages(messages, options) {
11191
11447
  import { TypeValidationError as TypeValidationError3 } from "@ai-sdk/provider";
11192
11448
  import {
11193
11449
  lazySchema as lazySchema2,
11450
+ safeValidateTypes as safeValidateTypes5,
11194
11451
  validateTypes as validateTypes4,
11195
11452
  zodSchema as zodSchema2
11196
11453
  } from "@ai-sdk/provider-utils";
@@ -11199,6 +11456,17 @@ var toolMetadataSchema2 = z.record(
11199
11456
  jsonValueSchema.optional()
11200
11457
  );
11201
11458
  var providerReferenceSchema2 = z.record(z.string(), z.string());
11459
+ function isEmptyObject(value) {
11460
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11461
+ }
11462
+ function asDynamicToolPart(toolPart) {
11463
+ const { type, ...part } = toolPart;
11464
+ return {
11465
+ ...part,
11466
+ type: "dynamic-tool",
11467
+ toolName: type.slice(5)
11468
+ };
11469
+ }
11202
11470
  var uiMessagesSchema = lazySchema2(
11203
11471
  () => zodSchema2(
11204
11472
  z.array(
@@ -11303,6 +11571,7 @@ var uiMessagesSchema = lazySchema2(
11303
11571
  approval: z.object({
11304
11572
  id: z.string(),
11305
11573
  approved: z.never().optional(),
11574
+ requestReason: z.string().optional(),
11306
11575
  reason: z.never().optional(),
11307
11576
  isAutomatic: z.boolean().optional(),
11308
11577
  signature: z.string().optional()
@@ -11322,6 +11591,7 @@ var uiMessagesSchema = lazySchema2(
11322
11591
  approval: z.object({
11323
11592
  id: z.string(),
11324
11593
  approved: z.boolean(),
11594
+ requestReason: z.string().optional(),
11325
11595
  reason: z.string().optional(),
11326
11596
  isAutomatic: z.boolean().optional(),
11327
11597
  signature: z.string().optional()
@@ -11343,6 +11613,7 @@ var uiMessagesSchema = lazySchema2(
11343
11613
  approval: z.object({
11344
11614
  id: z.string(),
11345
11615
  approved: z.literal(true),
11616
+ requestReason: z.string().optional(),
11346
11617
  reason: z.string().optional(),
11347
11618
  isAutomatic: z.boolean().optional(),
11348
11619
  signature: z.string().optional()
@@ -11364,6 +11635,7 @@ var uiMessagesSchema = lazySchema2(
11364
11635
  approval: z.object({
11365
11636
  id: z.string(),
11366
11637
  approved: z.literal(true),
11638
+ requestReason: z.string().optional(),
11367
11639
  reason: z.string().optional(),
11368
11640
  isAutomatic: z.boolean().optional(),
11369
11641
  signature: z.string().optional()
@@ -11383,6 +11655,7 @@ var uiMessagesSchema = lazySchema2(
11383
11655
  approval: z.object({
11384
11656
  id: z.string(),
11385
11657
  approved: z.literal(false),
11658
+ requestReason: z.string().optional(),
11386
11659
  reason: z.string().optional(),
11387
11660
  isAutomatic: z.boolean().optional(),
11388
11661
  signature: z.string().optional()
@@ -11425,6 +11698,7 @@ var uiMessagesSchema = lazySchema2(
11425
11698
  approval: z.object({
11426
11699
  id: z.string(),
11427
11700
  approved: z.never().optional(),
11701
+ requestReason: z.string().optional(),
11428
11702
  reason: z.never().optional(),
11429
11703
  isAutomatic: z.boolean().optional(),
11430
11704
  signature: z.string().optional()
@@ -11443,6 +11717,7 @@ var uiMessagesSchema = lazySchema2(
11443
11717
  approval: z.object({
11444
11718
  id: z.string(),
11445
11719
  approved: z.boolean(),
11720
+ requestReason: z.string().optional(),
11446
11721
  reason: z.string().optional(),
11447
11722
  isAutomatic: z.boolean().optional(),
11448
11723
  signature: z.string().optional()
@@ -11463,6 +11738,7 @@ var uiMessagesSchema = lazySchema2(
11463
11738
  approval: z.object({
11464
11739
  id: z.string(),
11465
11740
  approved: z.literal(true),
11741
+ requestReason: z.string().optional(),
11466
11742
  reason: z.string().optional(),
11467
11743
  isAutomatic: z.boolean().optional(),
11468
11744
  signature: z.string().optional()
@@ -11483,6 +11759,7 @@ var uiMessagesSchema = lazySchema2(
11483
11759
  approval: z.object({
11484
11760
  id: z.string(),
11485
11761
  approved: z.literal(true),
11762
+ requestReason: z.string().optional(),
11486
11763
  reason: z.string().optional(),
11487
11764
  isAutomatic: z.boolean().optional(),
11488
11765
  signature: z.string().optional()
@@ -11501,6 +11778,7 @@ var uiMessagesSchema = lazySchema2(
11501
11778
  approval: z.object({
11502
11779
  id: z.string(),
11503
11780
  approved: z.literal(false),
11781
+ requestReason: z.string().optional(),
11504
11782
  reason: z.string().optional(),
11505
11783
  isAutomatic: z.boolean().optional(),
11506
11784
  signature: z.string().optional()
@@ -11524,11 +11802,13 @@ var uiMessagesSchema = lazySchema2(
11524
11802
  ).nonempty("Messages array must not be empty")
11525
11803
  )
11526
11804
  );
11527
- async function safeValidateUIMessages({
11805
+ async function safeValidateUIMessagesInternal({
11528
11806
  messages,
11529
11807
  metadataSchema,
11530
11808
  dataSchemas,
11531
11809
  tools
11810
+ }, {
11811
+ convertMissingTerminalToolsToDynamic
11532
11812
  }) {
11533
11813
  try {
11534
11814
  if (messages == null) {
@@ -11557,7 +11837,8 @@ async function safeValidateUIMessages({
11557
11837
  });
11558
11838
  }
11559
11839
  }
11560
- if (dataSchemas || tools) {
11840
+ const shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;
11841
+ if (dataSchemas || shouldValidateToolParts) {
11561
11842
  for (const [msgIdx, message] of validatedMessages.entries()) {
11562
11843
  for (const [partIdx, part] of message.parts.entries()) {
11563
11844
  if (dataSchemas && part.type.startsWith("data-")) {
@@ -11588,11 +11869,17 @@ async function safeValidateUIMessages({
11588
11869
  }
11589
11870
  });
11590
11871
  }
11591
- if (tools && part.type.startsWith("tool-")) {
11872
+ if (shouldValidateToolParts && part.type.startsWith("tool-")) {
11592
11873
  const toolPart = part;
11593
11874
  const toolName = toolPart.type.slice(5);
11594
- const tool2 = getOwn(tools, toolName);
11595
- if (!tool2 && (toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied")) {
11875
+ const tool2 = tools == null ? void 0 : getOwn(tools, toolName);
11876
+ const isTerminal = toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied";
11877
+ if (!tool2 && isTerminal) {
11878
+ if (tools != null || convertMissingTerminalToolsToDynamic) {
11879
+ message.parts[partIdx] = asDynamicToolPart(
11880
+ toolPart
11881
+ );
11882
+ }
11596
11883
  continue;
11597
11884
  }
11598
11885
  if (!tool2) {
@@ -11609,15 +11896,39 @@ async function safeValidateUIMessages({
11609
11896
  })
11610
11897
  };
11611
11898
  }
11612
- if (toolPart.state === "input-available") {
11613
- await validateTypes4({
11899
+ const inputValidationContext = {
11900
+ field: `messages[${msgIdx}].parts[${partIdx}].input`,
11901
+ entityName: toolName,
11902
+ entityId: toolPart.toolCallId
11903
+ };
11904
+ let convertToDynamic = false;
11905
+ if (toolPart.state === "output-error") {
11906
+ if (toolPart.input !== void 0) {
11907
+ const result = await safeValidateTypes5({
11908
+ value: toolPart.input,
11909
+ schema: tool2.inputSchema,
11910
+ context: inputValidationContext
11911
+ });
11912
+ convertToDynamic = !result.success;
11913
+ }
11914
+ } else if (toolPart.state === "output-available") {
11915
+ const result = await safeValidateTypes5({
11614
11916
  value: toolPart.input,
11615
11917
  schema: tool2.inputSchema,
11616
- context: {
11617
- field: `messages[${msgIdx}].parts[${partIdx}].input`,
11618
- entityName: toolName,
11619
- entityId: toolPart.toolCallId
11918
+ context: inputValidationContext
11919
+ });
11920
+ if (!result.success) {
11921
+ if (isEmptyObject(toolPart.input)) {
11922
+ convertToDynamic = true;
11923
+ } else {
11924
+ throw result.error;
11620
11925
  }
11926
+ }
11927
+ } else if (toolPart.state === "input-available" || toolPart.state === "approval-requested" || toolPart.state === "approval-responded" || toolPart.state === "output-denied") {
11928
+ await validateTypes4({
11929
+ value: toolPart.input,
11930
+ schema: tool2.inputSchema,
11931
+ context: inputValidationContext
11621
11932
  });
11622
11933
  }
11623
11934
  if (toolPart.state === "output-available" && tool2.outputSchema) {
@@ -11631,6 +11942,11 @@ async function safeValidateUIMessages({
11631
11942
  }
11632
11943
  });
11633
11944
  }
11945
+ if (convertToDynamic) {
11946
+ message.parts[partIdx] = asDynamicToolPart(
11947
+ toolPart
11948
+ );
11949
+ }
11634
11950
  }
11635
11951
  }
11636
11952
  }
@@ -11647,17 +11963,23 @@ async function safeValidateUIMessages({
11647
11963
  };
11648
11964
  }
11649
11965
  }
11650
- async function validateUIMessages({
11651
- messages,
11652
- metadataSchema,
11653
- dataSchemas,
11654
- tools
11655
- }) {
11656
- const response = await safeValidateUIMessages({
11657
- messages,
11658
- metadataSchema,
11659
- dataSchemas,
11660
- tools
11966
+ async function safeValidateUIMessages(options) {
11967
+ return safeValidateUIMessagesInternal(options, {
11968
+ convertMissingTerminalToolsToDynamic: false
11969
+ });
11970
+ }
11971
+ async function validateUIMessages(options) {
11972
+ const response = await safeValidateUIMessages(options);
11973
+ if (!response.success)
11974
+ throw response.error;
11975
+ return response.data;
11976
+ }
11977
+ async function validateUIMessagesForAgent(options) {
11978
+ const response = await safeValidateUIMessagesInternal(options, {
11979
+ // Agent tool sets can include ephemeral tools (for example, tools from a
11980
+ // disconnected MCP server), so terminal history is converted to dynamic
11981
+ // tool parts when those tools are no longer registered.
11982
+ convertMissingTerminalToolsToDynamic: true
11661
11983
  });
11662
11984
  if (!response.success)
11663
11985
  throw response.error;
@@ -11677,8 +11999,8 @@ async function createAgentUIStream({
11677
11999
  onStepFinish,
11678
12000
  ...uiMessageStreamOptions
11679
12001
  }) {
11680
- var _a23;
11681
- const validatedMessages = await validateUIMessages({
12002
+ var _a24;
12003
+ const validatedMessages = await validateUIMessagesForAgent({
11682
12004
  messages: uiMessages,
11683
12005
  // tools are compatible; the casting is required because the context param is
11684
12006
  // not available in ui messages
@@ -11696,7 +12018,7 @@ async function createAgentUIStream({
11696
12018
  experimental_transform,
11697
12019
  onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish
11698
12020
  });
11699
- const originalMessages = (_a23 = uiMessageStreamOptions.originalMessages) != null ? _a23 : validatedMessages;
12021
+ const originalMessages = (_a24 = uiMessageStreamOptions.originalMessages) != null ? _a24 : validatedMessages;
11700
12022
  return createAsyncIterableStream(
11701
12023
  toUIMessageStream({
11702
12024
  ...uiMessageStreamOptions,
@@ -11970,7 +12292,7 @@ function convertBatchItemResult(item) {
11970
12292
  };
11971
12293
  }
11972
12294
  function convertGenerateResult(result) {
11973
- var _a23;
12295
+ var _a24;
11974
12296
  return {
11975
12297
  text: result.content.filter(
11976
12298
  (part) => part.type === "text"
@@ -11981,7 +12303,7 @@ function convertGenerateResult(result) {
11981
12303
  ...result.response != null ? {
11982
12304
  response: {
11983
12305
  id: result.response.id,
11984
- timestamp: (_a23 = result.response.timestamp) == null ? void 0 : _a23.toISOString(),
12306
+ timestamp: (_a24 = result.response.timestamp) == null ? void 0 : _a24.toISOString(),
11985
12307
  modelId: result.response.modelId
11986
12308
  }
11987
12309
  } : {},
@@ -12013,7 +12335,7 @@ async function embed({
12013
12335
  experimental_onEnd,
12014
12336
  _internal: { generateCallId = originalGenerateCallId4 } = {}
12015
12337
  }) {
12016
- var _a23;
12338
+ var _a24;
12017
12339
  const model = resolveEmbeddingModel(modelArg);
12018
12340
  const { maxRetries, retry } = prepareRetries({
12019
12341
  maxRetries: maxRetriesArg,
@@ -12029,7 +12351,7 @@ async function embed({
12029
12351
  const telemetryDispatcher = createTelemetryDispatcher({
12030
12352
  telemetry
12031
12353
  });
12032
- const runInTracingChannelSpan = (_a23 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a23 : async ({ execute }) => await execute();
12354
+ const runInTracingChannelSpan = (_a24 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a24 : async ({ execute }) => await execute();
12033
12355
  const startEvent = {
12034
12356
  callId,
12035
12357
  operationId: "ai.embed",
@@ -12044,14 +12366,14 @@ async function embed({
12044
12366
  type: "embed",
12045
12367
  event: startEvent,
12046
12368
  execute: async () => {
12047
- var _a24;
12369
+ var _a25;
12048
12370
  await notify({
12049
12371
  event: startEvent,
12050
12372
  callbacks: [resolvedOnStart, telemetryDispatcher.onStart]
12051
12373
  });
12052
12374
  try {
12053
12375
  const { embedding, usage, warnings, response, providerMetadata } = await retry(async () => {
12054
- var _a25, _b;
12376
+ var _a26, _b;
12055
12377
  const embedCallId = generateCallId();
12056
12378
  await notify({
12057
12379
  event: {
@@ -12071,7 +12393,7 @@ async function embed({
12071
12393
  providerOptions
12072
12394
  });
12073
12395
  const embedding2 = modelResponse.embeddings[0];
12074
- const usage2 = (_a25 = modelResponse.usage) != null ? _a25 : { tokens: NaN };
12396
+ const usage2 = (_a26 = modelResponse.usage) != null ? _a26 : { tokens: NaN };
12075
12397
  await notify({
12076
12398
  event: {
12077
12399
  callId,
@@ -12122,7 +12444,7 @@ async function embed({
12122
12444
  response
12123
12445
  });
12124
12446
  } catch (error) {
12125
- await ((_a24 = telemetryDispatcher.onError) == null ? void 0 : _a24.call(telemetryDispatcher, { callId, error }));
12447
+ await ((_a25 = telemetryDispatcher.onError) == null ? void 0 : _a25.call(telemetryDispatcher, { callId, error }));
12126
12448
  throw error;
12127
12449
  }
12128
12450
  }
@@ -12145,6 +12467,12 @@ import {
12145
12467
  withUserAgentSuffix as withUserAgentSuffix6
12146
12468
  } from "@ai-sdk/provider-utils";
12147
12469
 
12470
+ // src/model/get-embedding-model-max-input-bytes-per-call.ts
12471
+ import { EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL } from "@ai-sdk/provider-utils";
12472
+ function getEmbeddingModelMaxInputBytesPerCall(model) {
12473
+ return model[EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL];
12474
+ }
12475
+
12148
12476
  // src/util/split-array.ts
12149
12477
  function splitArray(array3, chunkSize) {
12150
12478
  if (chunkSize <= 0) {
@@ -12178,7 +12506,7 @@ async function embedMany({
12178
12506
  experimental_onEnd,
12179
12507
  _internal: { generateCallId = originalGenerateCallId5 } = {}
12180
12508
  }) {
12181
- var _a23;
12509
+ var _a24;
12182
12510
  const model = resolveEmbeddingModel(modelArg);
12183
12511
  const { maxRetries, retry } = prepareRetries({
12184
12512
  maxRetries: maxRetriesArg,
@@ -12194,7 +12522,7 @@ async function embedMany({
12194
12522
  const telemetryDispatcher = createTelemetryDispatcher({
12195
12523
  telemetry
12196
12524
  });
12197
- const runInTracingChannelSpan = (_a23 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a23 : async ({ execute }) => await execute();
12525
+ const runInTracingChannelSpan = (_a24 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a24 : async ({ execute }) => await execute();
12198
12526
  const startEvent = {
12199
12527
  callId,
12200
12528
  operationId: "ai.embedMany",
@@ -12209,18 +12537,26 @@ async function embedMany({
12209
12537
  type: "embedMany",
12210
12538
  event: startEvent,
12211
12539
  execute: async () => {
12212
- var _a24, _b;
12540
+ var _a25, _b;
12213
12541
  await notify({
12214
12542
  event: startEvent,
12215
12543
  callbacks: [resolvedOnStart, telemetryDispatcher.onStart]
12216
12544
  });
12217
12545
  try {
12218
- const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all(
12219
- [model.maxEmbeddingsPerCall, model.supportsParallelCalls]
12220
- );
12221
- if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {
12546
+ const [
12547
+ maxEmbeddingsPerCall,
12548
+ maxInputBytesPerCall,
12549
+ supportsParallelCalls
12550
+ ] = await Promise.all([
12551
+ model.maxEmbeddingsPerCall,
12552
+ getEmbeddingModelMaxInputBytesPerCall(model),
12553
+ model.supportsParallelCalls
12554
+ ]);
12555
+ const hasEmbeddingLimit = maxEmbeddingsPerCall != null && maxEmbeddingsPerCall !== Infinity;
12556
+ const hasInputByteLimit = maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;
12557
+ if (!hasEmbeddingLimit && !hasInputByteLimit) {
12222
12558
  const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(async () => {
12223
- var _a25, _b2;
12559
+ var _a26, _b2;
12224
12560
  const embedCallId = generateCallId();
12225
12561
  await notify({
12226
12562
  event: {
@@ -12240,7 +12576,7 @@ async function embedMany({
12240
12576
  providerOptions
12241
12577
  });
12242
12578
  const embeddings3 = modelResponse.embeddings;
12243
- const usage2 = (_a25 = modelResponse.usage) != null ? _a25 : { tokens: NaN };
12579
+ const usage2 = (_a26 = modelResponse.usage) != null ? _a26 : { tokens: NaN };
12244
12580
  await notify({
12245
12581
  event: {
12246
12582
  callId,
@@ -12291,7 +12627,11 @@ async function embedMany({
12291
12627
  responses: [response]
12292
12628
  });
12293
12629
  }
12294
- const valueChunks = splitArray(values, maxEmbeddingsPerCall);
12630
+ const valueChunks = splitByEmbeddingLimits({
12631
+ values,
12632
+ maxEmbeddingsPerCall: hasEmbeddingLimit ? maxEmbeddingsPerCall : Infinity,
12633
+ maxInputBytesPerCall: hasInputByteLimit ? maxInputBytesPerCall : Infinity
12634
+ });
12295
12635
  const embeddings = [];
12296
12636
  const warnings = [];
12297
12637
  const responses = [];
@@ -12305,7 +12645,7 @@ async function embedMany({
12305
12645
  const results = await Promise.all(
12306
12646
  parallelChunk.map((chunk) => {
12307
12647
  return retry(async () => {
12308
- var _a25, _b2;
12648
+ var _a26, _b2;
12309
12649
  const embedCallId = generateCallId();
12310
12650
  await notify({
12311
12651
  event: {
@@ -12325,7 +12665,7 @@ async function embedMany({
12325
12665
  providerOptions
12326
12666
  });
12327
12667
  const chunkEmbeddings = modelResponse.embeddings;
12328
- const usage = (_a25 = modelResponse.usage) != null ? _a25 : { tokens: NaN };
12668
+ const usage = (_a26 = modelResponse.usage) != null ? _a26 : { tokens: NaN };
12329
12669
  await notify({
12330
12670
  event: {
12331
12671
  callId,
@@ -12362,7 +12702,7 @@ async function embedMany({
12362
12702
  result.providerMetadata
12363
12703
  )) {
12364
12704
  providerMetadata[providerName] = {
12365
- ...(_a24 = providerMetadata[providerName]) != null ? _a24 : {},
12705
+ ...(_a25 = providerMetadata[providerName]) != null ? _a25 : {},
12366
12706
  ...metadata
12367
12707
  };
12368
12708
  }
@@ -12405,6 +12745,37 @@ async function embedMany({
12405
12745
  }
12406
12746
  });
12407
12747
  }
12748
+ var textEncoder = new TextEncoder();
12749
+ function splitByEmbeddingLimits({
12750
+ values,
12751
+ maxEmbeddingsPerCall,
12752
+ maxInputBytesPerCall
12753
+ }) {
12754
+ if (maxEmbeddingsPerCall <= 0) {
12755
+ throw new Error("maxEmbeddingsPerCall must be greater than 0");
12756
+ }
12757
+ if (maxInputBytesPerCall <= 0) {
12758
+ throw new Error("maxInputBytesPerCall must be greater than 0");
12759
+ }
12760
+ if (values.length === 0) {
12761
+ return [];
12762
+ }
12763
+ const chunks = [];
12764
+ let currentChunk = [];
12765
+ let currentInputBytes = 0;
12766
+ for (const value of values) {
12767
+ const inputBytes = textEncoder.encode(value).length;
12768
+ if (currentChunk.length > 0 && (currentChunk.length >= maxEmbeddingsPerCall || currentInputBytes + inputBytes > maxInputBytesPerCall)) {
12769
+ chunks.push(currentChunk);
12770
+ currentChunk = [];
12771
+ currentInputBytes = 0;
12772
+ }
12773
+ currentChunk.push(value);
12774
+ currentInputBytes += inputBytes;
12775
+ }
12776
+ chunks.push(currentChunk);
12777
+ return chunks;
12778
+ }
12408
12779
  var DefaultEmbedManyResult = class {
12409
12780
  constructor(options) {
12410
12781
  this.values = options.values;
@@ -12472,7 +12843,7 @@ async function generateImage({
12472
12843
  abortSignal,
12473
12844
  headers
12474
12845
  }) {
12475
- var _a23, _b;
12846
+ var _a24, _b;
12476
12847
  const model = resolveImageModel(modelArg);
12477
12848
  const headersWithUserAgent = withUserAgentSuffix7(
12478
12849
  headers != null ? headers : {},
@@ -12482,7 +12853,7 @@ async function generateImage({
12482
12853
  maxRetries: maxRetriesArg,
12483
12854
  abortSignal
12484
12855
  });
12485
- const maxImagesPerCallWithDefault = (_a23 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a23 : 1;
12856
+ const maxImagesPerCallWithDefault = (_a24 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a24 : 1;
12486
12857
  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);
12487
12858
  const callImageCounts = Array.from({ length: callCount }, (_, i) => {
12488
12859
  if (i < callCount - 1) {
@@ -12523,13 +12894,13 @@ async function generateImage({
12523
12894
  images.push(
12524
12895
  ...result.images.map(
12525
12896
  (image) => {
12526
- var _a24;
12897
+ var _a25;
12527
12898
  return new DefaultGeneratedFile({
12528
12899
  data: image,
12529
- mediaType: (_a24 = detectMediaType2({
12900
+ mediaType: (_a25 = detectMediaType2({
12530
12901
  data: image,
12531
12902
  topLevelType: "image"
12532
- })) != null ? _a24 : "image/png"
12903
+ })) != null ? _a25 : "image/png"
12533
12904
  });
12534
12905
  }
12535
12906
  )
@@ -12673,7 +13044,7 @@ import {
12673
13044
  } from "@ai-sdk/provider";
12674
13045
  import {
12675
13046
  asSchema as asSchema5,
12676
- safeValidateTypes as safeValidateTypes5
13047
+ safeValidateTypes as safeValidateTypes6
12677
13048
  } from "@ai-sdk/provider-utils";
12678
13049
  var noSchemaOutputStrategy = {
12679
13050
  type: "no-schema",
@@ -12713,7 +13084,7 @@ var objectOutputStrategy = (schema) => ({
12713
13084
  };
12714
13085
  },
12715
13086
  async validateFinalResult(value) {
12716
- return safeValidateTypes5({ value, schema });
13087
+ return safeValidateTypes6({ value, schema });
12717
13088
  },
12718
13089
  createElementStream() {
12719
13090
  throw new UnsupportedFunctionalityError4({
@@ -12752,7 +13123,7 @@ var arrayOutputStrategy = (schema) => {
12752
13123
  isFirstDelta,
12753
13124
  isFinalDelta
12754
13125
  }) {
12755
- var _a23;
13126
+ var _a24;
12756
13127
  if (!isJSONObject(value) || !isJSONArray(value.elements)) {
12757
13128
  return {
12758
13129
  success: false,
@@ -12766,7 +13137,7 @@ var arrayOutputStrategy = (schema) => {
12766
13137
  const resultArray = [];
12767
13138
  for (let i = 0; i < inputArray.length; i++) {
12768
13139
  const element = inputArray[i];
12769
- const result = await safeValidateTypes5({ value: element, schema });
13140
+ const result = await safeValidateTypes6({ value: element, schema });
12770
13141
  if (i === inputArray.length - 1 && !isFinalDelta) {
12771
13142
  continue;
12772
13143
  }
@@ -12775,7 +13146,7 @@ var arrayOutputStrategy = (schema) => {
12775
13146
  }
12776
13147
  resultArray.push(result.value);
12777
13148
  }
12778
- const publishedElementCount = (_a23 = latestObject == null ? void 0 : latestObject.length) != null ? _a23 : 0;
13149
+ const publishedElementCount = (_a24 = latestObject == null ? void 0 : latestObject.length) != null ? _a24 : 0;
12779
13150
  let textDelta = "";
12780
13151
  if (isFirstDelta) {
12781
13152
  textDelta += "[";
@@ -12808,7 +13179,7 @@ var arrayOutputStrategy = (schema) => {
12808
13179
  const inputArray = value.elements;
12809
13180
  const resultArray = [];
12810
13181
  for (const element of inputArray) {
12811
- const result = await safeValidateTypes5({ value: element, schema });
13182
+ const result = await safeValidateTypes6({ value: element, schema });
12812
13183
  if (!result.success) {
12813
13184
  return result;
12814
13185
  }
@@ -13119,7 +13490,7 @@ function validateObjectGenerationInput({
13119
13490
  // src/generate-object/generate-object.ts
13120
13491
  var originalGenerateId4 = createIdGenerator6({ prefix: "aiobj", size: 24 });
13121
13492
  async function generateObject(options) {
13122
- var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j;
13493
+ var _a24, _b, _c, _d, _e, _f, _g, _h, _i, _j;
13123
13494
  const {
13124
13495
  model: modelArg,
13125
13496
  output = "object",
@@ -13254,7 +13625,7 @@ async function generateObject(options) {
13254
13625
  })
13255
13626
  );
13256
13627
  const responseData = {
13257
- id: (_b = (_a23 = generateResult.response) == null ? void 0 : _a23.id) != null ? _b : generateId4(),
13628
+ id: (_b = (_a24 = generateResult.response) == null ? void 0 : _a24.id) != null ? _b : generateId4(),
13258
13629
  timestamp: (_d = (_c = generateResult.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),
13259
13630
  modelId: (_f = (_e = generateResult.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,
13260
13631
  headers: (_g = generateResult.response) == null ? void 0 : _g.headers,
@@ -13352,9 +13723,9 @@ var DefaultGenerateObjectResult = class {
13352
13723
  this.reasoning = options.reasoning;
13353
13724
  }
13354
13725
  toJsonResponse(init) {
13355
- var _a23;
13726
+ var _a24;
13356
13727
  return new Response(JSON.stringify(this.object), {
13357
- status: (_a23 = init == null ? void 0 : init.status) != null ? _a23 : 200,
13728
+ status: (_a24 = init == null ? void 0 : init.status) != null ? _a24 : 200,
13358
13729
  headers: prepareHeaders(init == null ? void 0 : init.headers, {
13359
13730
  "content-type": "application/json; charset=utf-8"
13360
13731
  })
@@ -13488,8 +13859,8 @@ function simulateReadableStream({
13488
13859
  chunkDelayInMs = 0,
13489
13860
  _internal
13490
13861
  }) {
13491
- var _a23;
13492
- const delay = (_a23 = _internal == null ? void 0 : _internal.delay) != null ? _a23 : delayFunction;
13862
+ var _a24;
13863
+ const delay = (_a24 = _internal == null ? void 0 : _internal.delay) != null ? _a24 : delayFunction;
13493
13864
  let index = 0;
13494
13865
  return new ReadableStream({
13495
13866
  async pull(controller) {
@@ -13759,7 +14130,7 @@ var DefaultStreamObjectResult = class {
13759
14130
  const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(
13760
14131
  new TransformStream({
13761
14132
  async transform(chunk, controller) {
13762
- var _a23, _b, _c;
14133
+ var _a24, _b, _c;
13763
14134
  if (typeof chunk === "object" && chunk.type === "stream-start") {
13764
14135
  warnings = chunk.warnings;
13765
14136
  return;
@@ -13803,7 +14174,7 @@ var DefaultStreamObjectResult = class {
13803
14174
  switch (chunk.type) {
13804
14175
  case "response-metadata": {
13805
14176
  fullResponse = {
13806
- id: (_a23 = chunk.id) != null ? _a23 : fullResponse.id,
14177
+ id: (_a24 = chunk.id) != null ? _a24 : fullResponse.id,
13807
14178
  timestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,
13808
14179
  modelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId
13809
14180
  };
@@ -13939,9 +14310,9 @@ var DefaultStreamObjectResult = class {
13939
14310
  }
13940
14311
  });
13941
14312
  })().catch(async (error) => {
13942
- var _a23;
14313
+ var _a24;
13943
14314
  self.rejectResultPromises(error);
13944
- await ((_a23 = telemetryDispatcher.onError) == null ? void 0 : _a23.call(telemetryDispatcher, { callId, error }));
14315
+ await ((_a24 = telemetryDispatcher.onError) == null ? void 0 : _a24.call(telemetryDispatcher, { callId, error }));
13945
14316
  stitchableStream.addStream(
13946
14317
  new ReadableStream({
13947
14318
  start(controller) {
@@ -14106,7 +14477,7 @@ async function generateSpeech({
14106
14477
  abortSignal,
14107
14478
  headers
14108
14479
  }) {
14109
- var _a23;
14480
+ var _a24;
14110
14481
  const resolvedModel = resolveSpeechModel(model);
14111
14482
  if (!resolvedModel) {
14112
14483
  throw new Error("Model could not be resolved");
@@ -14143,10 +14514,10 @@ async function generateSpeech({
14143
14514
  return new DefaultSpeechResult({
14144
14515
  audio: new DefaultGeneratedAudioFile({
14145
14516
  data: result.audio,
14146
- mediaType: (_a23 = detectMediaType3({
14517
+ mediaType: (_a24 = detectMediaType3({
14147
14518
  data: result.audio,
14148
14519
  topLevelType: "audio"
14149
- })) != null ? _a23 : "audio/mp3"
14520
+ })) != null ? _a24 : "audio/mp3"
14150
14521
  }),
14151
14522
  warnings: result.warnings,
14152
14523
  responses: [result.response],
@@ -14155,11 +14526,11 @@ async function generateSpeech({
14155
14526
  }
14156
14527
  var DefaultSpeechResult = class {
14157
14528
  constructor(options) {
14158
- var _a23;
14529
+ var _a24;
14159
14530
  this.audio = options.audio;
14160
14531
  this.warnings = options.warnings;
14161
14532
  this.responses = options.responses;
14162
- this.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};
14533
+ this.providerMetadata = (_a24 = options.providerMetadata) != null ? _a24 : {};
14163
14534
  }
14164
14535
  };
14165
14536
 
@@ -14373,14 +14744,14 @@ function tagDescription(description) {
14373
14744
  }
14374
14745
  async function fingerprintTools(tools) {
14375
14746
  const entries = await Promise.all(
14376
- Object.keys(tools).map(async (name23) => {
14377
- const tool2 = tools[name23];
14747
+ Object.keys(tools).map(async (name24) => {
14748
+ const tool2 = tools[name24];
14378
14749
  const digest = await hashCanonical({
14379
14750
  description: tagDescription(tool2.description),
14380
14751
  inputSchema: await asSchema6(tool2.inputSchema).jsonSchema,
14381
14752
  title: tool2.title
14382
14753
  });
14383
- return [name23, digest];
14754
+ return [name24, digest];
14384
14755
  })
14385
14756
  );
14386
14757
  return Object.fromEntries(entries);
@@ -14389,16 +14760,16 @@ function detectToolDrift(current, baseline) {
14389
14760
  const added = [];
14390
14761
  const removed = [];
14391
14762
  const changed = [];
14392
- for (const name23 of Object.keys(current)) {
14393
- if (!Object.hasOwn(baseline, name23)) {
14394
- added.push(name23);
14395
- } else if (current[name23] !== baseline[name23]) {
14396
- changed.push(name23);
14763
+ for (const name24 of Object.keys(current)) {
14764
+ if (!Object.hasOwn(baseline, name24)) {
14765
+ added.push(name24);
14766
+ } else if (current[name24] !== baseline[name24]) {
14767
+ changed.push(name24);
14397
14768
  }
14398
14769
  }
14399
- for (const name23 of Object.keys(baseline)) {
14400
- if (!Object.hasOwn(current, name23)) {
14401
- removed.push(name23);
14770
+ for (const name24 of Object.keys(baseline)) {
14771
+ if (!Object.hasOwn(current, name24)) {
14772
+ removed.push(name24);
14402
14773
  }
14403
14774
  }
14404
14775
  return { added, removed, changed };
@@ -14434,7 +14805,7 @@ async function experimental_generateVideo({
14434
14805
  poll,
14435
14806
  webhook
14436
14807
  }) {
14437
- var _a23;
14808
+ var _a24;
14438
14809
  const model = resolveVideoModel(modelArg);
14439
14810
  const headersWithUserAgent = withUserAgentSuffix10(
14440
14811
  headers != null ? headers : {},
@@ -14451,7 +14822,7 @@ async function experimental_generateVideo({
14451
14822
  effectiveInputReferences,
14452
14823
  warnings
14453
14824
  } = normalizeVideoCallInputs({ promptArg, frameImages, inputReferences });
14454
- const maxVideosPerCallWithDefault = (_a23 = maxVideosPerCall != null ? maxVideosPerCall : await invokeModelMaxVideosPerCall(model)) != null ? _a23 : 1;
14825
+ const maxVideosPerCallWithDefault = (_a24 = maxVideosPerCall != null ? maxVideosPerCall : await invokeModelMaxVideosPerCall(model)) != null ? _a24 : 1;
14455
14826
  const hasStartStatus = model.doStart != null && model.doStatus != null;
14456
14827
  const useStartStatus = hasStartStatus && (poll != null || webhook != null || model.doGenerate == null);
14457
14828
  if (model.doGenerate == null && !hasStartStatus) {
@@ -14590,7 +14961,7 @@ async function executeStartStatusFlow({
14590
14961
  webhook: webhookFactory,
14591
14962
  retry
14592
14963
  }) {
14593
- var _a23, _b, _c, _d;
14964
+ var _a24, _b, _c, _d;
14594
14965
  const earlyWarnings = [];
14595
14966
  let webhookUrl;
14596
14967
  let webhookReceived;
@@ -14609,7 +14980,7 @@ async function executeStartStatusFlow({
14609
14980
  });
14610
14981
  }
14611
14982
  }
14612
- const callerIdempotencyKey = Object.entries((_a23 = callOptions.headers) != null ? _a23 : {}).find(
14983
+ const callerIdempotencyKey = Object.entries((_a24 = callOptions.headers) != null ? _a24 : {}).find(
14613
14984
  ([key, value]) => key.toLowerCase() === "idempotency-key" && value !== void 0
14614
14985
  );
14615
14986
  const startCallOptions = {
@@ -14739,7 +15110,7 @@ function normalizeVideoCallInputs({
14739
15110
  frameImages,
14740
15111
  inputReferences
14741
15112
  }) {
14742
- var _a23;
15113
+ var _a24;
14743
15114
  const { prompt, image } = normalizePrompt2(promptArg);
14744
15115
  const normalizedFrameImages = frameImages == null ? void 0 : frameImages.flatMap((frame) => {
14745
15116
  const normalizedImage = normalizeImageData(frame.image);
@@ -14757,9 +15128,9 @@ function normalizeVideoCallInputs({
14757
15128
  message: "inputReferences were ignored because frameImages were provided; frameImages and inputReferences cannot be combined."
14758
15129
  });
14759
15130
  }
14760
- const firstFrameImage = (_a23 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find(
15131
+ const firstFrameImage = (_a24 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find(
14761
15132
  (frame) => frame.frameType === "first_frame"
14762
- )) == null ? void 0 : _a23.image;
15133
+ )) == null ? void 0 : _a24.image;
14763
15134
  if (image != null && firstFrameImage != null) {
14764
15135
  warnings.push({
14765
15136
  type: "other",
@@ -15005,8 +15376,8 @@ function stripMarkdownCodeFenceSuffix(text2) {
15005
15376
  return text2.replace(/\n?```\s*$/, "").trimEnd();
15006
15377
  }
15007
15378
  function extractJsonMiddleware(options) {
15008
- var _a23;
15009
- const transform = (_a23 = options == null ? void 0 : options.transform) != null ? _a23 : defaultTransform;
15379
+ var _a24;
15380
+ const transform = (_a24 = options == null ? void 0 : options.transform) != null ? _a24 : defaultTransform;
15010
15381
  const hasCustomTransform = (options == null ? void 0 : options.transform) !== void 0;
15011
15382
  return {
15012
15383
  specificationVersion: "v4",
@@ -15382,13 +15753,13 @@ function addToolInputExamplesMiddleware({
15382
15753
  return {
15383
15754
  specificationVersion: "v4",
15384
15755
  transformParams: async ({ params }) => {
15385
- var _a23;
15386
- if (!((_a23 = params.tools) == null ? void 0 : _a23.length)) {
15756
+ var _a24;
15757
+ if (!((_a24 = params.tools) == null ? void 0 : _a24.length)) {
15387
15758
  return params;
15388
15759
  }
15389
15760
  const transformedTools = params.tools.map((tool2) => {
15390
- var _a24;
15391
- if (tool2.type !== "function" || !((_a24 = tool2.inputExamples) == null ? void 0 : _a24.length)) {
15761
+ var _a25;
15762
+ if (tool2.type !== "function" || !((_a25 = tool2.inputExamples) == null ? void 0 : _a25.length)) {
15392
15763
  return tool2;
15393
15764
  }
15394
15765
  const formattedExamples = tool2.inputExamples.map((example, index) => format(example, index)).join("\n");
@@ -15437,7 +15808,7 @@ var doWrap = ({
15437
15808
  modelId,
15438
15809
  providerId
15439
15810
  }) => {
15440
- var _a23, _b, _c;
15811
+ var _a24, _b, _c;
15441
15812
  async function doTransform({
15442
15813
  params,
15443
15814
  type
@@ -15446,7 +15817,7 @@ var doWrap = ({
15446
15817
  }
15447
15818
  return {
15448
15819
  specificationVersion: "v4",
15449
- provider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,
15820
+ provider: (_a24 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a24 : model.provider,
15450
15821
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
15451
15822
  supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
15452
15823
  async doGenerate(params) {
@@ -15475,7 +15846,10 @@ var doWrap = ({
15475
15846
  };
15476
15847
 
15477
15848
  // src/middleware/wrap-embedding-model.ts
15478
- import { asArray as asArray9 } from "@ai-sdk/provider-utils";
15849
+ import {
15850
+ asArray as asArray9,
15851
+ EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2
15852
+ } from "@ai-sdk/provider-utils";
15479
15853
  var wrapEmbeddingModel = ({
15480
15854
  model: inputModel,
15481
15855
  middleware: middlewareArg,
@@ -15500,7 +15874,7 @@ var doWrap2 = ({
15500
15874
  modelId,
15501
15875
  providerId
15502
15876
  }) => {
15503
- var _a23, _b, _c, _d;
15877
+ var _a24, _b, _c, _d;
15504
15878
  async function doTransform({
15505
15879
  params
15506
15880
  }) {
@@ -15508,9 +15882,10 @@ var doWrap2 = ({
15508
15882
  }
15509
15883
  return {
15510
15884
  specificationVersion: "v4",
15511
- provider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,
15885
+ provider: (_a24 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a24 : model.provider,
15512
15886
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
15513
15887
  maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,
15888
+ [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2]: getEmbeddingModelMaxInputBytesPerCall(model),
15514
15889
  supportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,
15515
15890
  async doEmbed(params) {
15516
15891
  const transformedParams = await doTransform({ params });
@@ -15549,11 +15924,11 @@ var doWrap3 = ({
15549
15924
  modelId,
15550
15925
  providerId
15551
15926
  }) => {
15552
- var _a23, _b, _c;
15927
+ var _a24, _b, _c;
15553
15928
  async function doTransform({ params }) {
15554
15929
  return transformParams ? await transformParams({ params, model }) : params;
15555
15930
  }
15556
- const maxImagesPerCallRaw = (_a23 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a23 : model.maxImagesPerCall;
15931
+ const maxImagesPerCallRaw = (_a24 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a24 : model.maxImagesPerCall;
15557
15932
  const maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;
15558
15933
  return {
15559
15934
  specificationVersion: "v4",
@@ -15655,7 +16030,7 @@ async function getRealtimeToolDefinitions({
15655
16030
  toolsContext = {}
15656
16031
  }) {
15657
16032
  const definitions = [];
15658
- for (const [name23, tool2] of Object.entries(tools)) {
16033
+ for (const [name24, tool2] of Object.entries(tools)) {
15659
16034
  const toolType = tool2.type;
15660
16035
  switch (toolType) {
15661
16036
  case void 0:
@@ -15663,12 +16038,12 @@ async function getRealtimeToolDefinitions({
15663
16038
  case "dynamic": {
15664
16039
  const description = resolveRealtimeToolDescription({
15665
16040
  tool: tool2,
15666
- toolName: name23,
16041
+ toolName: name24,
15667
16042
  toolsContext
15668
16043
  });
15669
16044
  definitions.push({
15670
16045
  type: "function",
15671
- name: name23,
16046
+ name: name24,
15672
16047
  description,
15673
16048
  parameters: await asSchema7(tool2.inputSchema).jsonSchema
15674
16049
  });
@@ -15742,8 +16117,8 @@ var BrowserRealtimeAudio = class {
15742
16117
  this.onCapturingChange(true);
15743
16118
  }
15744
16119
  stopCapture() {
15745
- var _a23, _b, _c, _d;
15746
- (_a23 = this.captureProcessor) == null ? void 0 : _a23.disconnect();
16120
+ var _a24, _b, _c, _d;
16121
+ (_a24 = this.captureProcessor) == null ? void 0 : _a24.disconnect();
15747
16122
  (_b = this.captureSource) == null ? void 0 : _b.disconnect();
15748
16123
  void ((_c = this.captureContext) == null ? void 0 : _c.close());
15749
16124
  (_d = this.captureStream) == null ? void 0 : _d.getTracks().forEach((track) => track.stop());
@@ -15779,16 +16154,16 @@ var BrowserRealtimeAudio = class {
15779
16154
  return (ctx.currentTime - this.playbackStartTime) * 1e3;
15780
16155
  }
15781
16156
  dispose() {
15782
- var _a23;
16157
+ var _a24;
15783
16158
  this.stopCapture();
15784
16159
  this.stopPlayback();
15785
- void ((_a23 = this.playbackContext) == null ? void 0 : _a23.close());
16160
+ void ((_a24 = this.playbackContext) == null ? void 0 : _a24.close());
15786
16161
  this.playbackContext = null;
15787
16162
  }
15788
16163
  setPlaying(isPlaying) {
15789
- var _a23, _b;
16164
+ var _a24, _b;
15790
16165
  if (isPlaying && !this.isPlaying) {
15791
- this.playbackStartTime = (_b = (_a23 = this.playbackContext) == null ? void 0 : _a23.currentTime) != null ? _b : 0;
16166
+ this.playbackStartTime = (_b = (_a24 = this.playbackContext) == null ? void 0 : _a24.currentTime) != null ? _b : 0;
15792
16167
  }
15793
16168
  if (this.isPlaying !== isPlaying) {
15794
16169
  this.isPlaying = isPlaying;
@@ -15841,8 +16216,8 @@ var BrowserRealtimeTransport = class {
15841
16216
  url,
15842
16217
  onOpen
15843
16218
  }) {
15844
- var _a23;
15845
- (_a23 = this.ws) == null ? void 0 : _a23.close();
16219
+ var _a24;
16220
+ (_a24 = this.ws) == null ? void 0 : _a24.close();
15846
16221
  this.ws = null;
15847
16222
  const wsConfig = this.model.getWebSocketConfig({ token, url });
15848
16223
  const ws = new WebSocket(wsConfig.url, wsConfig.protocols);
@@ -15866,8 +16241,8 @@ var BrowserRealtimeTransport = class {
15866
16241
  };
15867
16242
  }
15868
16243
  disconnect() {
15869
- var _a23;
15870
- (_a23 = this.ws) == null ? void 0 : _a23.close();
16244
+ var _a24;
16245
+ (_a24 = this.ws) == null ? void 0 : _a24.close();
15871
16246
  this.ws = null;
15872
16247
  }
15873
16248
  sendEvent(event) {
@@ -15883,8 +16258,8 @@ var BrowserRealtimeTransport = class {
15883
16258
  });
15884
16259
  }
15885
16260
  sendRaw(data) {
15886
- var _a23;
15887
- if (((_a23 = this.ws) == null ? void 0 : _a23.readyState) === WebSocket.OPEN) {
16261
+ var _a24;
16262
+ if (((_a24 = this.ws) == null ? void 0 : _a24.readyState) === WebSocket.OPEN) {
15888
16263
  if (typeof data === "string" || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || data instanceof Blob) {
15889
16264
  this.ws.send(data);
15890
16265
  } else {
@@ -15977,7 +16352,7 @@ var RealtimeEventReducer = class {
15977
16352
  };
15978
16353
  }
15979
16354
  async reduceServerEvent(state, event) {
15980
- var _a23;
16355
+ var _a24;
15981
16356
  let nextState = this.pushEvent(state, event);
15982
16357
  const effects = [];
15983
16358
  switch (event.type) {
@@ -16044,7 +16419,7 @@ var RealtimeEventReducer = class {
16044
16419
  const { state: updatedState, messageId } = this.getOrCreateAssistantMessage(nextState);
16045
16420
  nextState = updatedState;
16046
16421
  this.toolCallIdToMessageId.set(event.callId, messageId);
16047
- const acc = (_a23 = this.toolArgAccumulators.get(event.callId)) != null ? _a23 : "";
16422
+ const acc = (_a24 = this.toolArgAccumulators.get(event.callId)) != null ? _a24 : "";
16048
16423
  this.toolArgAccumulators.set(event.callId, acc + event.delta);
16049
16424
  nextState = this.ensureToolPart(nextState, messageId, event.callId);
16050
16425
  break;
@@ -16118,7 +16493,7 @@ var RealtimeEventReducer = class {
16118
16493
  };
16119
16494
  }
16120
16495
  addInputTranscriptionMessage(state, itemId, transcript) {
16121
- var _a23;
16496
+ var _a24;
16122
16497
  const messageId = `user-${itemId}`;
16123
16498
  const existingMessage = state.messages.find(
16124
16499
  (message) => message.id === messageId
@@ -16141,7 +16516,7 @@ var RealtimeEventReducer = class {
16141
16516
  };
16142
16517
  }
16143
16518
  const insertIndex = Math.min(
16144
- (_a23 = this.inputAudioMessageInsertIndex.get(itemId)) != null ? _a23 : state.messages.length,
16519
+ (_a24 = this.inputAudioMessageInsertIndex.get(itemId)) != null ? _a24 : state.messages.length,
16145
16520
  state.messages.length
16146
16521
  );
16147
16522
  const messages = [...state.messages];
@@ -16162,9 +16537,9 @@ var RealtimeEventReducer = class {
16162
16537
  };
16163
16538
  }
16164
16539
  appendTextDelta(state, itemId, delta) {
16165
- var _a23;
16540
+ var _a24;
16166
16541
  const { state: stateWithMessage, messageId } = this.getOrCreateAssistantMessage(state);
16167
- const acc = (_a23 = this.textAccumulators.get(itemId)) != null ? _a23 : "";
16542
+ const acc = (_a24 = this.textAccumulators.get(itemId)) != null ? _a24 : "";
16168
16543
  const text2 = acc + delta;
16169
16544
  this.textAccumulators.set(itemId, text2);
16170
16545
  const location = this.itemIdToPartLocation.get(itemId);
@@ -16194,8 +16569,8 @@ var RealtimeEventReducer = class {
16194
16569
  };
16195
16570
  }
16196
16571
  finalizeText(state, itemId, finalText) {
16197
- var _a23;
16198
- const text2 = (_a23 = finalText != null ? finalText : this.textAccumulators.get(itemId)) != null ? _a23 : "";
16572
+ var _a24;
16573
+ const text2 = (_a24 = finalText != null ? finalText : this.textAccumulators.get(itemId)) != null ? _a24 : "";
16199
16574
  this.textAccumulators.delete(itemId);
16200
16575
  const location = this.itemIdToPartLocation.get(itemId);
16201
16576
  if (location == null)
@@ -16235,7 +16610,7 @@ var RealtimeEventReducer = class {
16235
16610
  })
16236
16611
  };
16237
16612
  }
16238
- markToolInputAvailable(state, messageId, callId, name23, input) {
16613
+ markToolInputAvailable(state, messageId, callId, name24, input) {
16239
16614
  return {
16240
16615
  ...state,
16241
16616
  messages: state.messages.map((message) => {
@@ -16251,7 +16626,7 @@ var RealtimeEventReducer = class {
16251
16626
  return part;
16252
16627
  return {
16253
16628
  ...toolPart,
16254
- toolName: name23,
16629
+ toolName: name24,
16255
16630
  state: "input-available",
16256
16631
  input
16257
16632
  };
@@ -16313,11 +16688,11 @@ var AbstractRealtimeSession = class {
16313
16688
  this.toolCallsInResponse = /* @__PURE__ */ new Set();
16314
16689
  this.submittedToolOutputs = /* @__PURE__ */ new Set();
16315
16690
  this.responseToolCallsClosed = false;
16316
- var _a23, _b, _c, _d, _e, _f, _g, _h;
16691
+ var _a24, _b, _c, _d, _e, _f, _g, _h;
16317
16692
  this.model = options.model;
16318
16693
  this.api = options.api;
16319
16694
  this.sessionConfig = options.sessionConfig;
16320
- this.maxEvents = (_a23 = options.maxEvents) != null ? _a23 : 500;
16695
+ this.maxEvents = (_a24 = options.maxEvents) != null ? _a24 : 500;
16321
16696
  this.reducer = new RealtimeEventReducer(this.maxEvents);
16322
16697
  this.onToolCall = options.onToolCall;
16323
16698
  this.onEvent = options.onEvent;
@@ -16329,9 +16704,9 @@ var AbstractRealtimeSession = class {
16329
16704
  model: this.model,
16330
16705
  onServerEvent: (event) => this.handleServerEvent(event),
16331
16706
  onError: (error) => {
16332
- var _a24;
16707
+ var _a25;
16333
16708
  this.applyState(this.reducer.setStatus(this.state, "error"));
16334
- (_a24 = this.onError) == null ? void 0 : _a24.call(this, error);
16709
+ (_a25 = this.onError) == null ? void 0 : _a25.call(this, error);
16335
16710
  },
16336
16711
  onClose: () => {
16337
16712
  this.applyState(this.reducer.setStatus(this.state, "disconnected"));
@@ -16351,7 +16726,7 @@ var AbstractRealtimeSession = class {
16351
16726
  }
16352
16727
  // ── Connection ─────────────────────────────────────────────────────
16353
16728
  async connect() {
16354
- var _a23;
16729
+ var _a24;
16355
16730
  this.applyState(this.reducer.setStatus(this.state, "connecting"));
16356
16731
  try {
16357
16732
  const response = await fetch(this.api.token, {
@@ -16381,7 +16756,7 @@ var AbstractRealtimeSession = class {
16381
16756
  });
16382
16757
  } catch (error) {
16383
16758
  this.applyState(this.reducer.setStatus(this.state, "error"));
16384
- (_a23 = this.onError) == null ? void 0 : _a23.call(
16759
+ (_a24 = this.onError) == null ? void 0 : _a24.call(
16385
16760
  this,
16386
16761
  error instanceof Error ? error : new Error(`Connection failed: ${String(error)}`)
16387
16762
  );
@@ -16507,18 +16882,18 @@ var AbstractRealtimeSession = class {
16507
16882
  }
16508
16883
  }
16509
16884
  async executeToolCall({
16510
- name: name23,
16885
+ name: name24,
16511
16886
  args,
16512
16887
  callId
16513
16888
  }) {
16514
- var _a23, _b;
16889
+ var _a24, _b;
16515
16890
  if (this.onToolCall == null) {
16516
- (_a23 = this.onError) == null ? void 0 : _a23.call(this, new Error(`No handler provided for tool "${name23}"`));
16891
+ (_a24 = this.onError) == null ? void 0 : _a24.call(this, new Error(`No handler provided for tool "${name24}"`));
16517
16892
  return;
16518
16893
  }
16519
16894
  try {
16520
16895
  const result = await this.onToolCall({
16521
- toolCall: { toolCallId: callId, toolName: name23, args }
16896
+ toolCall: { toolCallId: callId, toolName: name24, args }
16522
16897
  });
16523
16898
  if (result !== void 0) {
16524
16899
  this.addToolOutput(callId, result);
@@ -16531,10 +16906,10 @@ var AbstractRealtimeSession = class {
16531
16906
  }
16532
16907
  }
16533
16908
  async handleServerEvent(event) {
16534
- var _a23;
16909
+ var _a24;
16535
16910
  const result = await this.reducer.reduceServerEvent(this.state, event);
16536
16911
  this.applyState(result.state);
16537
- (_a23 = this.onEvent) == null ? void 0 : _a23.call(this, event);
16912
+ (_a24 = this.onEvent) == null ? void 0 : _a24.call(this, event);
16538
16913
  for (const effect of result.effects) {
16539
16914
  this.handleReducerEffect(effect);
16540
16915
  }
@@ -16544,7 +16919,7 @@ var AbstractRealtimeSession = class {
16544
16919
  }
16545
16920
  }
16546
16921
  handleReducerEffect(effect) {
16547
- var _a23;
16922
+ var _a24;
16548
16923
  switch (effect.type) {
16549
16924
  case "play-audio": {
16550
16925
  this.currentResponseItemId = effect.itemId;
@@ -16576,7 +16951,7 @@ var AbstractRealtimeSession = class {
16576
16951
  break;
16577
16952
  }
16578
16953
  case "error": {
16579
- (_a23 = this.onError) == null ? void 0 : _a23.call(this, effect.error);
16954
+ (_a24 = this.onError) == null ? void 0 : _a24.call(this, effect.error);
16580
16955
  break;
16581
16956
  }
16582
16957
  }
@@ -16689,11 +17064,11 @@ function customProvider({
16689
17064
  }
16690
17065
 
16691
17066
  // src/registry/no-such-provider-error.ts
16692
- import { AISDKError as AISDKError25, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
16693
- var name22 = "AI_NoSuchProviderError";
16694
- var marker22 = `vercel.ai.error.${name22}`;
16695
- var symbol22 = Symbol.for(marker22);
16696
- var _a22;
17067
+ import { AISDKError as AISDKError27, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
17068
+ var name23 = "AI_NoSuchProviderError";
17069
+ var marker23 = `vercel.ai.error.${name23}`;
17070
+ var symbol23 = Symbol.for(marker23);
17071
+ var _a23;
16697
17072
  var NoSuchProviderError = class extends NoSuchModelError3 {
16698
17073
  constructor({
16699
17074
  modelId,
@@ -16702,16 +17077,16 @@ var NoSuchProviderError = class extends NoSuchModelError3 {
16702
17077
  availableProviders,
16703
17078
  message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`
16704
17079
  }) {
16705
- super({ errorName: name22, modelId, modelType, message });
16706
- this[_a22] = true;
17080
+ super({ errorName: name23, modelId, modelType, message });
17081
+ this[_a23] = true;
16707
17082
  this.providerId = providerId;
16708
17083
  this.availableProviders = availableProviders;
16709
17084
  }
16710
17085
  static isInstance(error) {
16711
- return AISDKError25.hasMarker(error, marker22);
17086
+ return AISDKError27.hasMarker(error, marker23);
16712
17087
  }
16713
17088
  };
16714
- _a22 = symbol22;
17089
+ _a23 = symbol23;
16715
17090
 
16716
17091
  // src/registry/provider-registry.ts
16717
17092
  import {
@@ -16748,9 +17123,9 @@ var DefaultProviderRegistry = class {
16748
17123
  id,
16749
17124
  provider
16750
17125
  }) {
16751
- var _a23;
17126
+ var _a24;
16752
17127
  const providerV4 = asProviderV4(provider);
16753
- const videoModel = (_a23 = provider.videoModel) == null ? void 0 : _a23.bind(provider);
17128
+ const videoModel = (_a24 = provider.videoModel) == null ? void 0 : _a24.bind(provider);
16754
17129
  this.providers[id] = videoModel == null ? providerV4 : Object.assign(Object.create(Object.getPrototypeOf(providerV4)), {
16755
17130
  ...providerV4,
16756
17131
  videoModel: (modelId) => asVideoModelV4(videoModel(modelId))
@@ -16780,10 +17155,10 @@ var DefaultProviderRegistry = class {
16780
17155
  return [id.slice(0, index), id.slice(index + this.separator.length)];
16781
17156
  }
16782
17157
  languageModel(id) {
16783
- var _a23, _b;
17158
+ var _a24, _b;
16784
17159
  const [providerId, modelId] = this.splitId(id, "languageModel");
16785
- let model = (_b = (_a23 = this.getProvider(providerId, "languageModel")).languageModel) == null ? void 0 : _b.call(
16786
- _a23,
17160
+ let model = (_b = (_a24 = this.getProvider(providerId, "languageModel")).languageModel) == null ? void 0 : _b.call(
17161
+ _a24,
16787
17162
  modelId
16788
17163
  );
16789
17164
  if (model == null) {
@@ -16798,10 +17173,10 @@ var DefaultProviderRegistry = class {
16798
17173
  return model;
16799
17174
  }
16800
17175
  embeddingModel(id) {
16801
- var _a23;
17176
+ var _a24;
16802
17177
  const [providerId, modelId] = this.splitId(id, "embeddingModel");
16803
17178
  const provider = this.getProvider(providerId, "embeddingModel");
16804
- const model = (_a23 = provider.embeddingModel) == null ? void 0 : _a23.call(provider, modelId);
17179
+ const model = (_a24 = provider.embeddingModel) == null ? void 0 : _a24.call(provider, modelId);
16805
17180
  if (model == null) {
16806
17181
  throw new NoSuchModelError4({
16807
17182
  modelId: id,
@@ -16811,10 +17186,10 @@ var DefaultProviderRegistry = class {
16811
17186
  return model;
16812
17187
  }
16813
17188
  imageModel(id) {
16814
- var _a23;
17189
+ var _a24;
16815
17190
  const [providerId, modelId] = this.splitId(id, "imageModel");
16816
17191
  const provider = this.getProvider(providerId, "imageModel");
16817
- let model = (_a23 = provider.imageModel) == null ? void 0 : _a23.call(provider, modelId);
17192
+ let model = (_a24 = provider.imageModel) == null ? void 0 : _a24.call(provider, modelId);
16818
17193
  if (model == null) {
16819
17194
  throw new NoSuchModelError4({ modelId: id, modelType: "imageModel" });
16820
17195
  }
@@ -16827,10 +17202,10 @@ var DefaultProviderRegistry = class {
16827
17202
  return model;
16828
17203
  }
16829
17204
  transcriptionModel(id) {
16830
- var _a23;
17205
+ var _a24;
16831
17206
  const [providerId, modelId] = this.splitId(id, "transcriptionModel");
16832
17207
  const provider = this.getProvider(providerId, "transcriptionModel");
16833
- const model = (_a23 = provider.transcriptionModel) == null ? void 0 : _a23.call(provider, modelId);
17208
+ const model = (_a24 = provider.transcriptionModel) == null ? void 0 : _a24.call(provider, modelId);
16834
17209
  if (model == null) {
16835
17210
  throw new NoSuchModelError4({
16836
17211
  modelId: id,
@@ -16840,39 +17215,39 @@ var DefaultProviderRegistry = class {
16840
17215
  return model;
16841
17216
  }
16842
17217
  speechModel(id) {
16843
- var _a23;
17218
+ var _a24;
16844
17219
  const [providerId, modelId] = this.splitId(id, "speechModel");
16845
17220
  const provider = this.getProvider(providerId, "speechModel");
16846
- const model = (_a23 = provider.speechModel) == null ? void 0 : _a23.call(provider, modelId);
17221
+ const model = (_a24 = provider.speechModel) == null ? void 0 : _a24.call(provider, modelId);
16847
17222
  if (model == null) {
16848
17223
  throw new NoSuchModelError4({ modelId: id, modelType: "speechModel" });
16849
17224
  }
16850
17225
  return model;
16851
17226
  }
16852
17227
  rerankingModel(id) {
16853
- var _a23;
17228
+ var _a24;
16854
17229
  const [providerId, modelId] = this.splitId(id, "rerankingModel");
16855
17230
  const provider = this.getProvider(providerId, "rerankingModel");
16856
- const model = (_a23 = provider.rerankingModel) == null ? void 0 : _a23.call(provider, modelId);
17231
+ const model = (_a24 = provider.rerankingModel) == null ? void 0 : _a24.call(provider, modelId);
16857
17232
  if (model == null) {
16858
17233
  throw new NoSuchModelError4({ modelId: id, modelType: "rerankingModel" });
16859
17234
  }
16860
17235
  return model;
16861
17236
  }
16862
17237
  videoModel(id) {
16863
- var _a23;
17238
+ var _a24;
16864
17239
  const [providerId, modelId] = this.splitId(id, "videoModel");
16865
17240
  const provider = this.getProvider(providerId, "videoModel");
16866
- const model = (_a23 = provider.videoModel) == null ? void 0 : _a23.call(provider, modelId);
17241
+ const model = (_a24 = provider.videoModel) == null ? void 0 : _a24.call(provider, modelId);
16867
17242
  if (model == null) {
16868
17243
  throw new NoSuchModelError4({ modelId: id, modelType: "videoModel" });
16869
17244
  }
16870
17245
  return asVideoModelV4(model);
16871
17246
  }
16872
17247
  files(id) {
16873
- var _a23;
17248
+ var _a24;
16874
17249
  const provider = this.getProvider(id, "languageModel");
16875
- const files = (_a23 = provider.files) == null ? void 0 : _a23.call(provider);
17250
+ const files = (_a24 = provider.files) == null ? void 0 : _a24.call(provider);
16876
17251
  if (files == null) {
16877
17252
  throw new Error(
16878
17253
  `The provider "${id}" does not support file uploads. Make sure it exposes a files() method.`
@@ -16881,9 +17256,9 @@ var DefaultProviderRegistry = class {
16881
17256
  return files;
16882
17257
  }
16883
17258
  skills(id) {
16884
- var _a23;
17259
+ var _a24;
16885
17260
  const provider = this.getProvider(id, "languageModel");
16886
- const skills = (_a23 = provider.skills) == null ? void 0 : _a23.call(provider);
17261
+ const skills = (_a24 = provider.skills) == null ? void 0 : _a24.call(provider);
16887
17262
  if (skills == null) {
16888
17263
  throw new Error(
16889
17264
  `The provider "${id}" does not support skills. Make sure it exposes a skills() method.`
@@ -16918,7 +17293,7 @@ async function rerank({
16918
17293
  experimental_onEnd,
16919
17294
  _internal: { generateCallId = originalGenerateCallId6 } = {}
16920
17295
  }) {
16921
- var _a23;
17296
+ var _a24;
16922
17297
  const model = resolveRerankingModel(modelArg);
16923
17298
  const callId = generateCallId();
16924
17299
  const resolvedOnStart = onStart != null ? onStart : experimental_onStart;
@@ -16926,7 +17301,7 @@ async function rerank({
16926
17301
  const telemetryDispatcher = createTelemetryDispatcher({
16927
17302
  telemetry
16928
17303
  });
16929
- const runInTracingChannelSpan = (_a23 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a23 : async ({ execute }) => await execute();
17304
+ const runInTracingChannelSpan = (_a24 = telemetryDispatcher.runInTracingChannelSpan) != null ? _a24 : async ({ execute }) => await execute();
16930
17305
  if (documents.length === 0) {
16931
17306
  await notify({
16932
17307
  event: {
@@ -16992,7 +17367,7 @@ async function rerank({
16992
17367
  type: "rerank",
16993
17368
  event: startEvent,
16994
17369
  execute: async () => {
16995
- var _a24, _b, _c, _d, _e;
17370
+ var _a25, _b, _c, _d, _e;
16996
17371
  await notify({
16997
17372
  event: startEvent,
16998
17373
  callbacks: [resolvedOnStart, telemetryDispatcher.onStart]
@@ -17063,7 +17438,7 @@ async function rerank({
17063
17438
  providerMetadata,
17064
17439
  response: {
17065
17440
  id: response == null ? void 0 : response.id,
17066
- timestamp: (_a24 = response == null ? void 0 : response.timestamp) != null ? _a24 : /* @__PURE__ */ new Date(),
17441
+ timestamp: (_a25 = response == null ? void 0 : response.timestamp) != null ? _a25 : /* @__PURE__ */ new Date(),
17067
17442
  modelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,
17068
17443
  headers: response == null ? void 0 : response.headers,
17069
17444
  body: response == null ? void 0 : response.body
@@ -17136,16 +17511,16 @@ async function transcribe({
17136
17511
  const audioData = audio instanceof URL ? (await downloadFn({ url: audio, abortSignal })).data : convertDataContentToUint8Array(audio);
17137
17512
  const result = await retry(
17138
17513
  () => {
17139
- var _a23;
17514
+ var _a24;
17140
17515
  return resolvedModel.doGenerate({
17141
17516
  audio: audioData,
17142
17517
  abortSignal,
17143
17518
  headers: headersWithUserAgent,
17144
17519
  providerOptions,
17145
- mediaType: (_a23 = detectMediaType5({
17520
+ mediaType: (_a24 = detectMediaType5({
17146
17521
  data: audioData,
17147
17522
  topLevelType: "audio"
17148
- })) != null ? _a23 : "audio/wav"
17523
+ })) != null ? _a24 : "audio/wav"
17149
17524
  });
17150
17525
  }
17151
17526
  );
@@ -17169,14 +17544,14 @@ async function transcribe({
17169
17544
  }
17170
17545
  var DefaultTranscriptionResult = class {
17171
17546
  constructor(options) {
17172
- var _a23;
17547
+ var _a24;
17173
17548
  this.text = options.text;
17174
17549
  this.segments = options.segments;
17175
17550
  this.language = options.language;
17176
17551
  this.durationInSeconds = options.durationInSeconds;
17177
17552
  this.warnings = options.warnings;
17178
17553
  this.responses = options.responses;
17179
- this.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};
17554
+ this.providerMetadata = (_a24 = options.providerMetadata) != null ? _a24 : {};
17180
17555
  }
17181
17556
  };
17182
17557
 
@@ -17198,12 +17573,12 @@ function streamTranscribe({
17198
17573
  includeRawChunks,
17199
17574
  _internal: { currentDate = () => /* @__PURE__ */ new Date() } = {}
17200
17575
  }) {
17201
- var _a23;
17576
+ var _a24;
17202
17577
  const resolvedModel = resolveTranscriptionModel(model);
17203
17578
  if (!resolvedModel) {
17204
17579
  throw new Error("Model could not be resolved");
17205
17580
  }
17206
- const doStream = (_a23 = resolvedModel.doStream) == null ? void 0 : _a23.bind(resolvedModel);
17581
+ const doStream = (_a24 = resolvedModel.doStream) == null ? void 0 : _a24.bind(resolvedModel);
17207
17582
  if (doStream == null) {
17208
17583
  throw new UnsupportedFunctionalityError5({
17209
17584
  functionality: "streaming transcription",
@@ -17250,7 +17625,7 @@ function streamTranscribe({
17250
17625
  const pipeAbortController = new AbortController();
17251
17626
  const transformer = {
17252
17627
  transform(value, controller) {
17253
- var _a24, _b, _c, _d;
17628
+ var _a25, _b, _c, _d;
17254
17629
  switch (value.type) {
17255
17630
  case "stream-start": {
17256
17631
  resolveWarnings(value.warnings);
@@ -17258,7 +17633,7 @@ function streamTranscribe({
17258
17633
  }
17259
17634
  case "response-metadata": {
17260
17635
  response = {
17261
- timestamp: (_a24 = value.timestamp) != null ? _a24 : currentResponseMetadata().timestamp,
17636
+ timestamp: (_a25 = value.timestamp) != null ? _a25 : currentResponseMetadata().timestamp,
17262
17637
  modelId: (_b = value.modelId) != null ? _b : currentResponseMetadata().modelId,
17263
17638
  headers: (_c = value.headers) != null ? _c : response == null ? void 0 : response.headers
17264
17639
  };
@@ -17306,7 +17681,7 @@ function streamTranscribe({
17306
17681
  };
17307
17682
  const transform = new TransformStream(transformer);
17308
17683
  void (async () => {
17309
- var _a24, _b, _c, _d, _e;
17684
+ var _a25, _b, _c, _d, _e;
17310
17685
  const result = await doStream({
17311
17686
  audio,
17312
17687
  inputAudioFormat,
@@ -17317,7 +17692,7 @@ function streamTranscribe({
17317
17692
  includeRawChunks
17318
17693
  });
17319
17694
  response = {
17320
- timestamp: (_b = (_a24 = result.response) == null ? void 0 : _a24.timestamp) != null ? _b : startedAt,
17695
+ timestamp: (_b = (_a25 = result.response) == null ? void 0 : _a25.timestamp) != null ? _b : startedAt,
17321
17696
  modelId: (_d = (_c = result.response) == null ? void 0 : _c.modelId) != null ? _d : resolvedModel.modelId,
17322
17697
  headers: (_e = result.response) == null ? void 0 : _e.headers
17323
17698
  };
@@ -17453,7 +17828,7 @@ function streamTranslate({
17453
17828
  let hasAudioOutput = false;
17454
17829
  const transformer = {
17455
17830
  transform(value, controller) {
17456
- var _a23, _b, _c, _d;
17831
+ var _a24, _b, _c, _d;
17457
17832
  switch (value.type) {
17458
17833
  case "stream-start": {
17459
17834
  resolveWarnings(value.warnings);
@@ -17461,7 +17836,7 @@ function streamTranslate({
17461
17836
  }
17462
17837
  case "response-metadata": {
17463
17838
  response = {
17464
- timestamp: (_a23 = value.timestamp) != null ? _a23 : currentResponseMetadata().timestamp,
17839
+ timestamp: (_a24 = value.timestamp) != null ? _a24 : currentResponseMetadata().timestamp,
17465
17840
  modelId: (_b = value.modelId) != null ? _b : currentResponseMetadata().modelId,
17466
17841
  headers: (_c = value.headers) != null ? _c : response == null ? void 0 : response.headers
17467
17842
  };
@@ -17520,7 +17895,7 @@ function streamTranslate({
17520
17895
  };
17521
17896
  const transform = new TransformStream(transformer);
17522
17897
  void (async () => {
17523
- var _a23, _b, _c, _d, _e;
17898
+ var _a24, _b, _c, _d, _e;
17524
17899
  const result = await doStream({
17525
17900
  audio,
17526
17901
  inputAudioFormat,
@@ -17534,7 +17909,7 @@ function streamTranslate({
17534
17909
  includeRawChunks
17535
17910
  });
17536
17911
  response = {
17537
- timestamp: (_b = (_a23 = result.response) == null ? void 0 : _a23.timestamp) != null ? _b : startedAt,
17912
+ timestamp: (_b = (_a24 = result.response) == null ? void 0 : _a24.timestamp) != null ? _b : startedAt,
17538
17913
  modelId: (_d = (_c = result.response) == null ? void 0 : _c.modelId) != null ? _d : resolvedModel.modelId,
17539
17914
  headers: (_e = result.response) == null ? void 0 : _e.headers
17540
17915
  };
@@ -17645,7 +18020,7 @@ async function callCompletionApi({
17645
18020
  onError,
17646
18021
  fetch: fetch2 = getOriginalFetch()
17647
18022
  }) {
17648
- var _a23;
18023
+ var _a24;
17649
18024
  try {
17650
18025
  setLoading(true);
17651
18026
  setError(void 0);
@@ -17673,7 +18048,7 @@ async function callCompletionApi({
17673
18048
  });
17674
18049
  if (!response.ok) {
17675
18050
  throw new Error(
17676
- (_a23 = await response.text()) != null ? _a23 : "Failed to fetch the chat response."
18051
+ (_a24 = await response.text()) != null ? _a24 : "Failed to fetch the chat response."
17677
18052
  );
17678
18053
  }
17679
18054
  if (!response.body) {
@@ -17759,12 +18134,12 @@ async function convertFileListToFileUIParts(files) {
17759
18134
  }
17760
18135
  return Promise.all(
17761
18136
  Array.from(files).map(async (file) => {
17762
- const { name: name23, type } = file;
18137
+ const { name: name24, type } = file;
17763
18138
  const dataUrl = await new Promise((resolve3, reject) => {
17764
18139
  const reader = new FileReader();
17765
18140
  reader.onload = (readerEvent) => {
17766
- var _a23;
17767
- resolve3((_a23 = readerEvent.target) == null ? void 0 : _a23.result);
18141
+ var _a24;
18142
+ resolve3((_a24 = readerEvent.target) == null ? void 0 : _a24.result);
17768
18143
  };
17769
18144
  reader.onerror = (error) => reject(error);
17770
18145
  reader.readAsDataURL(file);
@@ -17772,7 +18147,7 @@ async function convertFileListToFileUIParts(files) {
17772
18147
  return {
17773
18148
  type: "file",
17774
18149
  mediaType: type,
17775
- filename: name23,
18150
+ filename: name24,
17776
18151
  url: dataUrl
17777
18152
  };
17778
18153
  })
@@ -17809,7 +18184,7 @@ var HttpChatTransport = class {
17809
18184
  abortSignal,
17810
18185
  ...options
17811
18186
  }) {
17812
- var _a23, _b, _c, _d, _e;
18187
+ var _a24, _b, _c, _d, _e;
17813
18188
  const resolvedBody = await resolve2(this.body);
17814
18189
  const resolvedHeaders = await resolve2(this.headers);
17815
18190
  const resolvedCredentials = await resolve2(this.credentials);
@@ -17817,7 +18192,7 @@ var HttpChatTransport = class {
17817
18192
  ...normalizeHeaders(resolvedHeaders),
17818
18193
  ...normalizeHeaders(options.headers)
17819
18194
  };
17820
- const preparedRequest = await ((_a23 = this.prepareSendMessagesRequest) == null ? void 0 : _a23.call(this, {
18195
+ const preparedRequest = await ((_a24 = this.prepareSendMessagesRequest) == null ? void 0 : _a24.call(this, {
17821
18196
  api: this.api,
17822
18197
  id: options.chatId,
17823
18198
  messages: options.messages,
@@ -17861,7 +18236,7 @@ var HttpChatTransport = class {
17861
18236
  return this.processResponseStream(response.body);
17862
18237
  }
17863
18238
  async reconnectToStream(options) {
17864
- var _a23, _b, _c, _d, _e;
18239
+ var _a24, _b, _c, _d, _e;
17865
18240
  const resolvedBody = await resolve2(this.body);
17866
18241
  const resolvedHeaders = await resolve2(this.headers);
17867
18242
  const resolvedCredentials = await resolve2(this.credentials);
@@ -17869,7 +18244,7 @@ var HttpChatTransport = class {
17869
18244
  ...normalizeHeaders(resolvedHeaders),
17870
18245
  ...normalizeHeaders(options.headers)
17871
18246
  };
17872
- const preparedRequest = await ((_a23 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a23.call(this, {
18247
+ const preparedRequest = await ((_a24 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a24.call(this, {
17873
18248
  api: this.api,
17874
18249
  id: options.chatId,
17875
18250
  body: { ...resolvedBody, ...options.body },
@@ -17950,11 +18325,11 @@ var AbstractChat = class {
17950
18325
  * If a messageId is provided, the message will be replaced.
17951
18326
  */
17952
18327
  this.sendMessage = async (message, options) => {
17953
- var _a23, _b, _c, _d;
18328
+ var _a24, _b, _c, _d;
17954
18329
  if (message == null) {
17955
18330
  await this.makeRequest({
17956
18331
  trigger: "submit-message",
17957
- messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
18332
+ messageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,
17958
18333
  ...options
17959
18334
  });
17960
18335
  return;
@@ -18074,11 +18449,11 @@ var AbstractChat = class {
18074
18449
  }
18075
18450
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
18076
18451
  this.shouldSendAutomatically().then((shouldSend) => {
18077
- var _a23;
18452
+ var _a24;
18078
18453
  if (shouldSend) {
18079
18454
  this.makeRequest({
18080
18455
  trigger: "submit-message",
18081
- messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
18456
+ messageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,
18082
18457
  ...options
18083
18458
  });
18084
18459
  }
@@ -18104,11 +18479,11 @@ var AbstractChat = class {
18104
18479
  }
18105
18480
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
18106
18481
  this.shouldSendAutomatically().then((shouldSend) => {
18107
- var _a23;
18482
+ var _a24;
18108
18483
  if (shouldSend) {
18109
18484
  this.makeRequest({
18110
18485
  trigger: "submit-message",
18111
- messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
18486
+ messageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,
18112
18487
  ...options
18113
18488
  });
18114
18489
  }
@@ -18121,11 +18496,11 @@ var AbstractChat = class {
18121
18496
  * Abort the current request immediately, keep the generated tokens if any.
18122
18497
  */
18123
18498
  this.stop = async () => {
18124
- var _a23, _b;
18499
+ var _a24, _b;
18125
18500
  for (const controller of this.pendingMessagePreparations) {
18126
18501
  controller.abort();
18127
18502
  }
18128
- (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
18503
+ (_a24 = this.activeResumeRequest) == null ? void 0 : _a24.abortController.abort();
18129
18504
  (_b = this.activeResponse) == null ? void 0 : _b.abortController.abort();
18130
18505
  };
18131
18506
  this.id = id;
@@ -18190,11 +18565,11 @@ var AbstractChat = class {
18190
18565
  body,
18191
18566
  messageId
18192
18567
  }) {
18193
- var _a23, _b, _c;
18568
+ var _a24, _b, _c;
18194
18569
  const abortController = new AbortController();
18195
18570
  const activeResumeRequest = trigger === "resume-stream" ? { abortController } : void 0;
18196
18571
  if (activeResumeRequest) {
18197
- (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
18572
+ (_a24 = this.activeResumeRequest) == null ? void 0 : _a24.abortController.abort();
18198
18573
  this.activeResumeRequest = activeResumeRequest;
18199
18574
  }
18200
18575
  const isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;
@@ -18251,7 +18626,7 @@ var AbstractChat = class {
18251
18626
  const lastMessage = this.lastMessage;
18252
18627
  let isAbort = false;
18253
18628
  let isDisconnect = false;
18254
- let isError = false;
18629
+ let isError2 = false;
18255
18630
  let activeResponse;
18256
18631
  try {
18257
18632
  const response = {
@@ -18290,14 +18665,14 @@ var AbstractChat = class {
18290
18665
  return job({
18291
18666
  state: response.state,
18292
18667
  write: ({ updateStatus = true } = {}) => {
18293
- var _a24;
18668
+ var _a25;
18294
18669
  if (response.abortController.signal.aborted) {
18295
18670
  return;
18296
18671
  }
18297
18672
  if (updateStatus) {
18298
18673
  this.setStatus({ status: "streaming" });
18299
18674
  }
18300
- const replaceLastMessage = response.state.message.id === ((_a24 = this.lastMessage) == null ? void 0 : _a24.id);
18675
+ const replaceLastMessage = response.state.message.id === ((_a25 = this.lastMessage) == null ? void 0 : _a25.id);
18301
18676
  if (replaceLastMessage) {
18302
18677
  this.state.replaceMessage(
18303
18678
  this.state.messages.length - 1,
@@ -18347,7 +18722,7 @@ var AbstractChat = class {
18347
18722
  if (!isCurrentRequest()) {
18348
18723
  return null;
18349
18724
  }
18350
- isError = true;
18725
+ isError2 = true;
18351
18726
  if (err instanceof TypeError && (err.message.toLowerCase().includes("fetch") || err.message.toLowerCase().includes("network"))) {
18352
18727
  isDisconnect = true;
18353
18728
  }
@@ -18363,7 +18738,7 @@ var AbstractChat = class {
18363
18738
  messages: this.state.messages,
18364
18739
  isAbort,
18365
18740
  isDisconnect,
18366
- isError,
18741
+ isError: isError2,
18367
18742
  finishReason: activeResponse.state.finishReason
18368
18743
  });
18369
18744
  }
@@ -18374,7 +18749,7 @@ var AbstractChat = class {
18374
18749
  clearActiveResumeRequest();
18375
18750
  }
18376
18751
  }
18377
- if (!isError && await this.shouldSendAutomatically()) {
18752
+ if (!isError2 && await this.shouldSendAutomatically()) {
18378
18753
  await this.makeRequest({
18379
18754
  trigger: "submit-message",
18380
18755
  messageId: (_c = this.lastMessage) == null ? void 0 : _c.id,
@@ -18401,7 +18776,7 @@ var DirectChatTransport = class {
18401
18776
  messages,
18402
18777
  abortSignal
18403
18778
  }) {
18404
- const validatedMessages = await validateUIMessages({
18779
+ const validatedMessages = await validateUIMessagesForAgent({
18405
18780
  messages,
18406
18781
  // tools are compatible; the casting is required because the context param is
18407
18782
  // not available in ui messages
@@ -18451,7 +18826,7 @@ function lastAssistantMessageIsCompleteWithApprovalResponses({
18451
18826
  // has at least one tool approval response
18452
18827
  lastStepToolInvocations.filter((part) => part.state === "approval-responded").length > 0 && // all tool approvals must have a response
18453
18828
  lastStepToolInvocations.every(
18454
- (part) => part.state === "output-available" || part.state === "output-error" || part.state === "approval-responded"
18829
+ (part) => part.state === "output-available" || part.state === "output-error" || part.state === "output-denied" || part.state === "approval-responded"
18455
18830
  )
18456
18831
  );
18457
18832
  }
@@ -18523,9 +18898,9 @@ async function uploadFile({
18523
18898
  filename,
18524
18899
  providerOptions
18525
18900
  }) {
18526
- var _a23;
18901
+ var _a24;
18527
18902
  const data = dataArg instanceof Uint8Array || typeof dataArg === "string" ? { type: "data", data: dataArg } : dataArg;
18528
- const mediaType = mediaTypeArg != null ? mediaTypeArg : data.type === "text" ? "text/plain" : (_a23 = detectMediaType6({ data: data.data })) != null ? _a23 : isLikelyText(data.data) ? "text/plain" : "application/octet-stream";
18903
+ const mediaType = mediaTypeArg != null ? mediaTypeArg : data.type === "text" ? "text/plain" : (_a24 = detectMediaType6({ data: data.data })) != null ? _a24 : isLikelyText(data.data) ? "text/plain" : "application/octet-stream";
18529
18904
  const filesApi = "uploadFile" in api ? api : typeof api.files === "function" ? api.files() : (() => {
18530
18905
  throw new Error(
18531
18906
  "The provider does not support file uploads. Make sure it exposes a files() method."
@@ -18596,7 +18971,7 @@ async function uploadSkill({
18596
18971
  return result;
18597
18972
  }
18598
18973
  export {
18599
- AISDKError23 as AISDKError,
18974
+ AISDKError24 as AISDKError,
18600
18975
  AI_SDK_TELEMETRY_TRACING_CHANNEL,
18601
18976
  APICallError,
18602
18977
  AbstractChat,
@@ -18638,6 +19013,7 @@ export {
18638
19013
  output_exports as Output,
18639
19014
  RetryError,
18640
19015
  SerialJobExecutor,
19016
+ StreamProviderError,
18641
19017
  TextStreamChatTransport,
18642
19018
  TooManyEmbeddingValuesForCallError,
18643
19019
  ToolCallNotFoundForApprovalError,