ai 6.0.270 → 6.0.272

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __export = (target, all) => {
3
- for (var name22 in all)
4
- __defProp(target, name22, { get: all[name22], enumerable: true });
3
+ for (var name23 in all)
4
+ __defProp(target, name23, { get: all[name23], enumerable: true });
5
5
  };
6
6
 
7
7
  // src/index.ts
@@ -29,7 +29,7 @@ import {
29
29
 
30
30
  // src/error/index.ts
31
31
  import {
32
- AISDKError as AISDKError22,
32
+ AISDKError as AISDKError23,
33
33
  APICallError,
34
34
  EmptyResponseBodyError,
35
35
  InvalidPromptError,
@@ -386,31 +386,62 @@ var NoSuchToolError = class extends AISDKError14 {
386
386
  };
387
387
  _a14 = symbol14;
388
388
 
389
- // src/error/tool-call-repair-error.ts
390
- import { AISDKError as AISDKError15, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
391
- var name15 = "AI_ToolCallRepairError";
389
+ // src/error/tool-choice-violation-error.ts
390
+ import {
391
+ AISDKError as AISDKError15
392
+ } from "@ai-sdk/provider";
393
+ var name15 = "AI_ToolChoiceViolationError";
392
394
  var marker15 = `vercel.ai.error.${name15}`;
393
395
  var symbol15 = Symbol.for(marker15);
394
396
  var _a15;
395
- var ToolCallRepairError = class extends AISDKError15 {
397
+ var ToolChoiceViolationError = class extends AISDKError15 {
398
+ constructor({
399
+ toolChoice,
400
+ finishReason,
401
+ provider,
402
+ modelId,
403
+ content,
404
+ message = toolChoice.type === "required" ? "Model response did not contain a tool call even though tool choice was required." : `Model response did not contain a call to the required tool '${toolChoice.toolName}'.`
405
+ }) {
406
+ super({ name: name15, message });
407
+ this[_a15] = true;
408
+ this.toolChoice = toolChoice;
409
+ this.finishReason = finishReason;
410
+ this.provider = provider;
411
+ this.modelId = modelId;
412
+ this.content = content;
413
+ }
414
+ static isInstance(error) {
415
+ return AISDKError15.hasMarker(error, marker15);
416
+ }
417
+ };
418
+ _a15 = symbol15;
419
+
420
+ // src/error/tool-call-repair-error.ts
421
+ import { AISDKError as AISDKError16, getErrorMessage as getErrorMessage2 } from "@ai-sdk/provider";
422
+ var name16 = "AI_ToolCallRepairError";
423
+ var marker16 = `vercel.ai.error.${name16}`;
424
+ var symbol16 = Symbol.for(marker16);
425
+ var _a16;
426
+ var ToolCallRepairError = class extends AISDKError16 {
396
427
  constructor({
397
428
  cause,
398
429
  originalError,
399
430
  message = `Error repairing tool call: ${getErrorMessage2(cause)}`
400
431
  }) {
401
- super({ name: name15, message, cause });
402
- this[_a15] = true;
432
+ super({ name: name16, message, cause });
433
+ this[_a16] = true;
403
434
  this.originalError = originalError;
404
435
  }
405
436
  static isInstance(error) {
406
- return AISDKError15.hasMarker(error, marker15);
437
+ return AISDKError16.hasMarker(error, marker16);
407
438
  }
408
439
  };
409
- _a15 = symbol15;
440
+ _a16 = symbol16;
410
441
 
411
442
  // src/error/unsupported-model-version-error.ts
412
- import { AISDKError as AISDKError16 } from "@ai-sdk/provider";
413
- var UnsupportedModelVersionError = class extends AISDKError16 {
443
+ import { AISDKError as AISDKError17 } from "@ai-sdk/provider";
444
+ var UnsupportedModelVersionError = class extends AISDKError17 {
414
445
  constructor(options) {
415
446
  super({
416
447
  name: "AI_UnsupportedModelVersionError",
@@ -423,118 +454,118 @@ var UnsupportedModelVersionError = class extends AISDKError16 {
423
454
  };
424
455
 
425
456
  // src/error/ui-message-stream-error.ts
426
- import { AISDKError as AISDKError17 } from "@ai-sdk/provider";
427
- var name16 = "AI_UIMessageStreamError";
428
- var marker16 = `vercel.ai.error.${name16}`;
429
- var symbol16 = Symbol.for(marker16);
430
- var _a16;
431
- var UIMessageStreamError = class extends AISDKError17 {
457
+ import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
458
+ var name17 = "AI_UIMessageStreamError";
459
+ var marker17 = `vercel.ai.error.${name17}`;
460
+ var symbol17 = Symbol.for(marker17);
461
+ var _a17;
462
+ var UIMessageStreamError = class extends AISDKError18 {
432
463
  constructor({
433
464
  chunkType,
434
465
  chunkId,
435
466
  message
436
467
  }) {
437
- super({ name: name16, message });
438
- this[_a16] = true;
468
+ super({ name: name17, message });
469
+ this[_a17] = true;
439
470
  this.chunkType = chunkType;
440
471
  this.chunkId = chunkId;
441
472
  }
442
473
  static isInstance(error) {
443
- return AISDKError17.hasMarker(error, marker16);
474
+ return AISDKError18.hasMarker(error, marker17);
444
475
  }
445
476
  };
446
- _a16 = symbol16;
477
+ _a17 = symbol17;
447
478
 
448
479
  // src/prompt/invalid-data-content-error.ts
449
- import { AISDKError as AISDKError18 } from "@ai-sdk/provider";
450
- var name17 = "AI_InvalidDataContentError";
451
- var marker17 = `vercel.ai.error.${name17}`;
452
- var symbol17 = Symbol.for(marker17);
453
- var _a17;
454
- var InvalidDataContentError = class extends AISDKError18 {
480
+ import { AISDKError as AISDKError19 } from "@ai-sdk/provider";
481
+ var name18 = "AI_InvalidDataContentError";
482
+ var marker18 = `vercel.ai.error.${name18}`;
483
+ var symbol18 = Symbol.for(marker18);
484
+ var _a18;
485
+ var InvalidDataContentError = class extends AISDKError19 {
455
486
  constructor({
456
487
  content,
457
488
  cause,
458
489
  message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`
459
490
  }) {
460
- super({ name: name17, message, cause });
461
- this[_a17] = true;
491
+ super({ name: name18, message, cause });
492
+ this[_a18] = true;
462
493
  this.content = content;
463
494
  }
464
495
  static isInstance(error) {
465
- return AISDKError18.hasMarker(error, marker17);
496
+ return AISDKError19.hasMarker(error, marker18);
466
497
  }
467
498
  };
468
- _a17 = symbol17;
499
+ _a18 = symbol18;
469
500
 
470
501
  // src/prompt/invalid-message-role-error.ts
471
- import { AISDKError as AISDKError19 } from "@ai-sdk/provider";
472
- var name18 = "AI_InvalidMessageRoleError";
473
- var marker18 = `vercel.ai.error.${name18}`;
474
- var symbol18 = Symbol.for(marker18);
475
- var _a18;
476
- var InvalidMessageRoleError = class extends AISDKError19 {
502
+ import { AISDKError as AISDKError20 } from "@ai-sdk/provider";
503
+ var name19 = "AI_InvalidMessageRoleError";
504
+ var marker19 = `vercel.ai.error.${name19}`;
505
+ var symbol19 = Symbol.for(marker19);
506
+ var _a19;
507
+ var InvalidMessageRoleError = class extends AISDKError20 {
477
508
  constructor({
478
509
  role,
479
510
  message = `Invalid message role: '${role}'. Must be one of: "system", "user", "assistant", "tool".`
480
511
  }) {
481
- super({ name: name18, message });
482
- this[_a18] = true;
512
+ super({ name: name19, message });
513
+ this[_a19] = true;
483
514
  this.role = role;
484
515
  }
485
516
  static isInstance(error) {
486
- return AISDKError19.hasMarker(error, marker18);
517
+ return AISDKError20.hasMarker(error, marker19);
487
518
  }
488
519
  };
489
- _a18 = symbol18;
520
+ _a19 = symbol19;
490
521
 
491
522
  // src/prompt/message-conversion-error.ts
492
- import { AISDKError as AISDKError20 } from "@ai-sdk/provider";
493
- var name19 = "AI_MessageConversionError";
494
- var marker19 = `vercel.ai.error.${name19}`;
495
- var symbol19 = Symbol.for(marker19);
496
- var _a19;
497
- var MessageConversionError = class extends AISDKError20 {
523
+ import { AISDKError as AISDKError21 } from "@ai-sdk/provider";
524
+ var name20 = "AI_MessageConversionError";
525
+ var marker20 = `vercel.ai.error.${name20}`;
526
+ var symbol20 = Symbol.for(marker20);
527
+ var _a20;
528
+ var MessageConversionError = class extends AISDKError21 {
498
529
  constructor({
499
530
  originalMessage,
500
531
  message
501
532
  }) {
502
- super({ name: name19, message });
503
- this[_a19] = true;
533
+ super({ name: name20, message });
534
+ this[_a20] = true;
504
535
  this.originalMessage = originalMessage;
505
536
  }
506
537
  static isInstance(error) {
507
- return AISDKError20.hasMarker(error, marker19);
538
+ return AISDKError21.hasMarker(error, marker20);
508
539
  }
509
540
  };
510
- _a19 = symbol19;
541
+ _a20 = symbol20;
511
542
 
512
543
  // src/error/index.ts
513
544
  import { DownloadError } from "@ai-sdk/provider-utils";
514
545
 
515
546
  // src/util/retry-error.ts
516
- import { AISDKError as AISDKError21 } from "@ai-sdk/provider";
517
- var name20 = "AI_RetryError";
518
- var marker20 = `vercel.ai.error.${name20}`;
519
- var symbol20 = Symbol.for(marker20);
520
- var _a20;
521
- var RetryError = class extends AISDKError21 {
547
+ import { AISDKError as AISDKError22 } from "@ai-sdk/provider";
548
+ var name21 = "AI_RetryError";
549
+ var marker21 = `vercel.ai.error.${name21}`;
550
+ var symbol21 = Symbol.for(marker21);
551
+ var _a21;
552
+ var RetryError = class extends AISDKError22 {
522
553
  constructor({
523
554
  message,
524
555
  reason,
525
556
  errors
526
557
  }) {
527
- super({ name: name20, message });
528
- this[_a20] = true;
558
+ super({ name: name21, message });
559
+ this[_a21] = true;
529
560
  this.reason = reason;
530
561
  this.errors = errors;
531
562
  this.lastError = errors[errors.length - 1];
532
563
  }
533
564
  static isInstance(error) {
534
- return AISDKError21.hasMarker(error, marker20);
565
+ return AISDKError22.hasMarker(error, marker21);
535
566
  }
536
567
  };
537
- _a20 = symbol20;
568
+ _a21 = symbol21;
538
569
 
539
570
  // src/util/as-array.ts
540
571
  function asArray(value) {
@@ -814,7 +845,7 @@ function resolveEmbeddingModel(model) {
814
845
  return getGlobalProvider().embeddingModel(model);
815
846
  }
816
847
  function resolveTranscriptionModel(model) {
817
- var _a22, _b;
848
+ var _a23, _b;
818
849
  if (typeof model !== "string") {
819
850
  if (model.specificationVersion !== "v3" && model.specificationVersion !== "v2") {
820
851
  const unsupportedModel = model;
@@ -826,10 +857,10 @@ function resolveTranscriptionModel(model) {
826
857
  }
827
858
  return asTranscriptionModelV3(model);
828
859
  }
829
- return (_b = (_a22 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a22, model);
860
+ return (_b = (_a23 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a23, model);
830
861
  }
831
862
  function resolveSpeechModel(model) {
832
- var _a22, _b;
863
+ var _a23, _b;
833
864
  if (typeof model !== "string") {
834
865
  if (model.specificationVersion !== "v3" && model.specificationVersion !== "v2") {
835
866
  const unsupportedModel = model;
@@ -841,7 +872,7 @@ function resolveSpeechModel(model) {
841
872
  }
842
873
  return asSpeechModelV3(model);
843
874
  }
844
- return (_b = (_a22 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a22, model);
875
+ return (_b = (_a23 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a23, model);
845
876
  }
846
877
  function resolveImageModel(model) {
847
878
  if (typeof model !== "string") {
@@ -900,8 +931,8 @@ function resolveRerankingModel(model) {
900
931
  return model;
901
932
  }
902
933
  function getGlobalProvider() {
903
- var _a22;
904
- return (_a22 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a22 : gateway;
934
+ var _a23;
935
+ return (_a23 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a23 : gateway;
905
936
  }
906
937
 
907
938
  // src/prompt/call-settings.ts
@@ -1193,7 +1224,7 @@ import {
1193
1224
  } from "@ai-sdk/provider-utils";
1194
1225
 
1195
1226
  // src/version.ts
1196
- var VERSION = true ? "6.0.270" : "0.0.0-test";
1227
+ var VERSION = true ? "6.0.272" : "0.0.0-test";
1197
1228
 
1198
1229
  // src/util/download/download.ts
1199
1230
  var download = async ({
@@ -1201,7 +1232,7 @@ var download = async ({
1201
1232
  maxBytes,
1202
1233
  abortSignal
1203
1234
  }) => {
1204
- var _a22;
1235
+ var _a23;
1205
1236
  const urlText = url.toString();
1206
1237
  try {
1207
1238
  const headers = withUserAgentSuffix(
@@ -1229,7 +1260,7 @@ var download = async ({
1229
1260
  });
1230
1261
  return {
1231
1262
  data,
1232
- mediaType: (_a22 = response.headers.get("content-type")) != null ? _a22 : void 0
1263
+ mediaType: (_a23 = response.headers.get("content-type")) != null ? _a23 : void 0
1233
1264
  };
1234
1265
  } catch (error) {
1235
1266
  if (DownloadError2.isInstance(error)) {
@@ -1283,7 +1314,7 @@ function mergeObjects(base, overrides) {
1283
1314
  }
1284
1315
 
1285
1316
  // src/prompt/data-content.ts
1286
- import { AISDKError as AISDKError23 } from "@ai-sdk/provider";
1317
+ import { AISDKError as AISDKError24 } from "@ai-sdk/provider";
1287
1318
  import {
1288
1319
  convertBase64ToUint8Array as convertBase64ToUint8Array2,
1289
1320
  convertUint8ArrayToBase64
@@ -1314,8 +1345,8 @@ var dataContentSchema = z.union([
1314
1345
  z.custom(
1315
1346
  // Buffer might not be available in some environments such as CloudFlare:
1316
1347
  (value) => {
1317
- var _a22, _b;
1318
- return (_b = (_a22 = globalThis.Buffer) == null ? void 0 : _a22.isBuffer(value)) != null ? _b : false;
1348
+ var _a23, _b;
1349
+ return (_b = (_a23 = globalThis.Buffer) == null ? void 0 : _a23.isBuffer(value)) != null ? _b : false;
1319
1350
  },
1320
1351
  { message: "Must be a Buffer" }
1321
1352
  )
@@ -1338,7 +1369,7 @@ function convertToLanguageModelV3DataContent(content) {
1338
1369
  content.toString()
1339
1370
  );
1340
1371
  if (dataUrlMediaType == null || base64Content == null) {
1341
- throw new AISDKError23({
1372
+ throw new AISDKError24({
1342
1373
  name: "InvalidDataContentError",
1343
1374
  message: `Invalid data URL format in content ${content.toString()}`
1344
1375
  });
@@ -1629,7 +1660,7 @@ function convertToLanguageModelMessage({
1629
1660
  }
1630
1661
  }
1631
1662
  async function downloadAssets(messages, download2, supportedUrls) {
1632
- var _a22;
1663
+ var _a23;
1633
1664
  const downloadableFiles = [];
1634
1665
  for (const message of messages) {
1635
1666
  if (message.role === "user" && Array.isArray(message.content)) {
@@ -1637,7 +1668,7 @@ async function downloadAssets(messages, download2, supportedUrls) {
1637
1668
  if (part.type === "image" || part.type === "file") {
1638
1669
  downloadableFiles.push({
1639
1670
  data: part.type === "image" ? part.image : part.data,
1640
- mediaType: (_a22 = part.mediaType) != null ? _a22 : part.type === "image" ? "image/*" : void 0
1671
+ mediaType: (_a23 = part.mediaType) != null ? _a23 : part.type === "image" ? "image/*" : void 0
1641
1672
  });
1642
1673
  }
1643
1674
  }
@@ -1689,7 +1720,7 @@ async function downloadAssets(messages, download2, supportedUrls) {
1689
1720
  );
1690
1721
  }
1691
1722
  function convertPartToLanguageModelPart(part, downloadedAssets) {
1692
- var _a22;
1723
+ var _a23;
1693
1724
  if (part.type === "text") {
1694
1725
  return {
1695
1726
  type: "text",
@@ -1722,7 +1753,7 @@ function convertPartToLanguageModelPart(part, downloadedAssets) {
1722
1753
  switch (type) {
1723
1754
  case "image": {
1724
1755
  if (data instanceof Uint8Array || typeof data === "string") {
1725
- mediaType = (_a22 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a22 : mediaType;
1756
+ mediaType = (_a23 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a23 : mediaType;
1726
1757
  }
1727
1758
  return {
1728
1759
  type: "file",
@@ -1757,14 +1788,14 @@ function mapToolResultOutput({
1757
1788
  return {
1758
1789
  type: "content",
1759
1790
  value: output.value.map((item) => {
1760
- var _a22, _b;
1791
+ var _a23, _b;
1761
1792
  if (item.type === "image-url") {
1762
1793
  const downloadedFile = downloadedAssets[new URL(item.url).toString()];
1763
1794
  if (downloadedFile) {
1764
1795
  return {
1765
1796
  type: "image-data",
1766
1797
  data: convertDataContentToBase64String(downloadedFile.data),
1767
- mediaType: (_a22 = downloadedFile.mediaType) != null ? _a22 : "image/*",
1798
+ mediaType: (_a23 = downloadedFile.mediaType) != null ? _a23 : "image/*",
1768
1799
  providerOptions: item.providerOptions
1769
1800
  };
1770
1801
  }
@@ -1938,10 +1969,10 @@ async function prepareToolsAndToolChoice({
1938
1969
  };
1939
1970
  }
1940
1971
  const filteredTools = activeTools != null ? Object.entries(tools).filter(
1941
- ([name22]) => activeTools.includes(name22)
1972
+ ([name23]) => activeTools.includes(name23)
1942
1973
  ) : Object.entries(tools);
1943
1974
  const languageModelTools = [];
1944
- for (const [name22, tool2] of filteredTools) {
1975
+ for (const [name23, tool2] of filteredTools) {
1945
1976
  const toolType = tool2.type;
1946
1977
  switch (toolType) {
1947
1978
  case void 0:
@@ -1949,7 +1980,7 @@ async function prepareToolsAndToolChoice({
1949
1980
  case "function":
1950
1981
  languageModelTools.push({
1951
1982
  type: "function",
1952
- name: name22,
1983
+ name: name23,
1953
1984
  description: tool2.description,
1954
1985
  inputSchema: await asSchema(tool2.inputSchema).jsonSchema,
1955
1986
  ...tool2.inputExamples != null ? { inputExamples: tool2.inputExamples } : {},
@@ -1960,7 +1991,7 @@ async function prepareToolsAndToolChoice({
1960
1991
  case "provider":
1961
1992
  languageModelTools.push({
1962
1993
  type: "provider",
1963
- name: name22,
1994
+ name: name23,
1964
1995
  id: tool2.id,
1965
1996
  args: tool2.args
1966
1997
  });
@@ -2260,14 +2291,14 @@ async function standardizePrompt({
2260
2291
 
2261
2292
  // src/prompt/wrap-gateway-error.ts
2262
2293
  import { GatewayAuthenticationError } from "@ai-sdk/gateway";
2263
- import { AISDKError as AISDKError24 } from "@ai-sdk/provider";
2294
+ import { AISDKError as AISDKError25 } from "@ai-sdk/provider";
2264
2295
  function wrapGatewayError(error) {
2265
2296
  if (!GatewayAuthenticationError.isInstance(error))
2266
2297
  return error;
2267
2298
  const isProductionEnv = (process == null ? void 0 : process.env.NODE_ENV) === "production";
2268
2299
  const moreInfoURL = "https://ai-sdk.dev/unauthenticated-ai-gateway";
2269
2300
  if (isProductionEnv) {
2270
- return new AISDKError24({
2301
+ return new AISDKError25({
2271
2302
  name: "GatewayError",
2272
2303
  message: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`
2273
2304
  });
@@ -2308,7 +2339,7 @@ function getBaseTelemetryAttributes({
2308
2339
  telemetry,
2309
2340
  headers
2310
2341
  }) {
2311
- var _a22;
2342
+ var _a23;
2312
2343
  return {
2313
2344
  "ai.model.provider": model.provider,
2314
2345
  "ai.model.id": model.modelId,
@@ -2327,7 +2358,7 @@ function getBaseTelemetryAttributes({
2327
2358
  return attributes;
2328
2359
  }, {}),
2329
2360
  // add metadata as attributes:
2330
- ...Object.entries((_a22 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a22 : {}).reduce(
2361
+ ...Object.entries((_a23 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a23 : {}).reduce(
2331
2362
  (attributes, [key, value]) => {
2332
2363
  attributes[`ai.telemetry.metadata.${key}`] = value;
2333
2364
  return attributes;
@@ -2352,7 +2383,7 @@ var noopTracer = {
2352
2383
  startSpan() {
2353
2384
  return noopSpan;
2354
2385
  },
2355
- startActiveSpan(name22, arg1, arg2, arg3) {
2386
+ startActiveSpan(name23, arg1, arg2, arg3) {
2356
2387
  if (typeof arg1 === "function") {
2357
2388
  return arg1(noopSpan);
2358
2389
  }
@@ -2425,7 +2456,7 @@ import {
2425
2456
  context
2426
2457
  } from "@opentelemetry/api";
2427
2458
  async function recordSpan({
2428
- name: name22,
2459
+ name: name23,
2429
2460
  tracer,
2430
2461
  attributes,
2431
2462
  fn,
@@ -2433,7 +2464,7 @@ async function recordSpan({
2433
2464
  endOnError = endWhenDone
2434
2465
  }) {
2435
2466
  return tracer.startActiveSpan(
2436
- name22,
2467
+ name23,
2437
2468
  { attributes: await attributes },
2438
2469
  async (span) => {
2439
2470
  const ctx = context.active();
@@ -2563,15 +2594,15 @@ function registerTelemetryIntegration(integration) {
2563
2594
  globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(integration);
2564
2595
  }
2565
2596
  function getGlobalTelemetryIntegrations() {
2566
- var _a22;
2567
- return (_a22 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a22 : [];
2597
+ var _a23;
2598
+ return (_a23 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a23 : [];
2568
2599
  }
2569
2600
 
2570
2601
  // src/telemetry/get-global-telemetry-integration.ts
2571
2602
  function bindTelemetryIntegration(integration) {
2572
- var _a22, _b, _c, _d, _e, _f;
2603
+ var _a23, _b, _c, _d, _e, _f;
2573
2604
  return {
2574
- onStart: (_a22 = integration.onStart) == null ? void 0 : _a22.bind(integration),
2605
+ onStart: (_a23 = integration.onStart) == null ? void 0 : _a23.bind(integration),
2575
2606
  onStepStart: (_b = integration.onStepStart) == null ? void 0 : _b.bind(integration),
2576
2607
  onToolCallStart: (_c = integration.onToolCallStart) == null ? void 0 : _c.bind(integration),
2577
2608
  onToolCallFinish: (_d = integration.onToolCallFinish) == null ? void 0 : _d.bind(integration),
@@ -2655,12 +2686,12 @@ function createNullLanguageModelUsage() {
2655
2686
  };
2656
2687
  }
2657
2688
  function addLanguageModelUsage(usage1, usage2) {
2658
- var _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2689
+ var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j;
2659
2690
  return {
2660
2691
  inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2661
2692
  inputTokenDetails: {
2662
2693
  noCacheTokens: addTokenCounts(
2663
- (_a22 = usage1.inputTokenDetails) == null ? void 0 : _a22.noCacheTokens,
2694
+ (_a23 = usage1.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens,
2664
2695
  (_b = usage2.inputTokenDetails) == null ? void 0 : _b.noCacheTokens
2665
2696
  ),
2666
2697
  cacheReadTokens: addTokenCounts(
@@ -2889,8 +2920,8 @@ import { executeTool } from "@ai-sdk/provider-utils";
2889
2920
 
2890
2921
  // src/util/now.ts
2891
2922
  function now() {
2892
- var _a22, _b;
2893
- return (_b = (_a22 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a22.now()) != null ? _b : Date.now();
2923
+ var _a23, _b;
2924
+ return (_b = (_a23 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a23.now()) != null ? _b : Date.now();
2894
2925
  }
2895
2926
 
2896
2927
  // src/generate-text/execute-tool-call.ts
@@ -2908,7 +2939,7 @@ async function executeToolCall({
2908
2939
  onToolCallStart,
2909
2940
  onToolCallFinish
2910
2941
  }) {
2911
- var _a22;
2942
+ var _a23;
2912
2943
  const { toolName, toolCallId, input } = toolCall;
2913
2944
  const tool2 = tools == null ? void 0 : tools[toolName];
2914
2945
  if ((tool2 == null ? void 0 : tool2.execute) == null) {
@@ -2934,7 +2965,7 @@ async function executeToolCall({
2934
2965
  telemetry
2935
2966
  }),
2936
2967
  ...Object.fromEntries(
2937
- Object.entries((_a22 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a22 : {}).map(([key, value]) => [
2968
+ Object.entries((_a23 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a23 : {}).map(([key, value]) => [
2938
2969
  `ai.telemetry.metadata.${key}`,
2939
2970
  value
2940
2971
  ])
@@ -3063,7 +3094,7 @@ function filterActiveTools({
3063
3094
  }
3064
3095
  return Object.fromEntries(
3065
3096
  Object.entries(tools).filter(
3066
- ([name22]) => activeTools.includes(name22)
3097
+ ([name23]) => activeTools.includes(name23)
3067
3098
  )
3068
3099
  );
3069
3100
  }
@@ -3235,7 +3266,7 @@ async function validateApprovedToolApprovals({
3235
3266
  experimental_context,
3236
3267
  toolApprovalSecret
3237
3268
  }) {
3238
- var _a22;
3269
+ var _a23;
3239
3270
  const approved = [];
3240
3271
  const denied = [];
3241
3272
  const invalid = [];
@@ -3297,7 +3328,7 @@ async function validateApprovedToolApprovals({
3297
3328
  approvalResponse: {
3298
3329
  ...approval.approvalResponse,
3299
3330
  approved: false,
3300
- reason: (_a22 = approval.approvalResponse.reason) != null ? _a22 : `Tool "${toolCall.toolName}" does not require approval`
3331
+ reason: (_a23 = approval.approvalResponse.reason) != null ? _a23 : `Tool "${toolCall.toolName}" does not require approval`
3301
3332
  }
3302
3333
  });
3303
3334
  }
@@ -3700,7 +3731,7 @@ var text = () => ({
3700
3731
  });
3701
3732
  var object = ({
3702
3733
  schema: inputSchema,
3703
- name: name22,
3734
+ name: name23,
3704
3735
  description
3705
3736
  }) => {
3706
3737
  const schema = asSchema3(inputSchema);
@@ -3709,7 +3740,7 @@ var object = ({
3709
3740
  responseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({
3710
3741
  type: "json",
3711
3742
  schema: jsonSchema2,
3712
- ...name22 != null && { name: name22 },
3743
+ ...name23 != null && { name: name23 },
3713
3744
  ...description != null && { description }
3714
3745
  })),
3715
3746
  async parseCompleteOutput({ text: text2 }, context2) {
@@ -3763,7 +3794,7 @@ var object = ({
3763
3794
  };
3764
3795
  var array = ({
3765
3796
  element: inputElementSchema,
3766
- name: name22,
3797
+ name: name23,
3767
3798
  description
3768
3799
  }) => {
3769
3800
  const elementSchema = asSchema3(inputElementSchema);
@@ -3783,7 +3814,7 @@ var array = ({
3783
3814
  required: ["elements"],
3784
3815
  additionalProperties: false
3785
3816
  },
3786
- ...name22 != null && { name: name22 },
3817
+ ...name23 != null && { name: name23 },
3787
3818
  ...description != null && { description }
3788
3819
  };
3789
3820
  }),
@@ -3877,7 +3908,7 @@ var array = ({
3877
3908
  };
3878
3909
  var choice = ({
3879
3910
  options: choiceOptions,
3880
- name: name22,
3911
+ name: name23,
3881
3912
  description
3882
3913
  }) => {
3883
3914
  return {
@@ -3894,7 +3925,7 @@ var choice = ({
3894
3925
  required: ["result"],
3895
3926
  additionalProperties: false
3896
3927
  },
3897
- ...name22 != null && { name: name22 },
3928
+ ...name23 != null && { name: name23 },
3898
3929
  ...description != null && { description }
3899
3930
  }),
3900
3931
  async parseCompleteOutput({ text: text2 }, context2) {
@@ -3955,14 +3986,14 @@ var choice = ({
3955
3986
  };
3956
3987
  };
3957
3988
  var json = ({
3958
- name: name22,
3989
+ name: name23,
3959
3990
  description
3960
3991
  } = {}) => {
3961
3992
  return {
3962
3993
  name: "json",
3963
3994
  responseFormat: Promise.resolve({
3964
3995
  type: "json",
3965
- ...name22 != null && { name: name22 },
3996
+ ...name23 != null && { name: name23 },
3966
3997
  ...description != null && { description }
3967
3998
  }),
3968
3999
  async parseCompleteOutput({ text: text2 }, context2) {
@@ -4137,9 +4168,9 @@ function prepareStepCallSettings({
4137
4168
  callSettings,
4138
4169
  stepSettings
4139
4170
  }) {
4140
- var _a22, _b, _c, _d, _e, _f, _g, _h;
4171
+ var _a23, _b, _c, _d, _e, _f, _g, _h;
4141
4172
  return prepareCallSettings({
4142
- maxOutputTokens: (_a22 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a22 : callSettings.maxOutputTokens,
4173
+ maxOutputTokens: (_a23 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a23 : callSettings.maxOutputTokens,
4143
4174
  temperature: (_b = stepSettings == null ? void 0 : stepSettings.temperature) != null ? _b : callSettings.temperature,
4144
4175
  topP: (_c = stepSettings == null ? void 0 : stepSettings.topP) != null ? _c : callSettings.topP,
4145
4176
  topK: (_d = stepSettings == null ? void 0 : stepSettings.topK) != null ? _d : callSettings.topK,
@@ -4233,8 +4264,8 @@ function isLoopFinished() {
4233
4264
  }
4234
4265
  function hasToolCall(toolName) {
4235
4266
  return ({ steps }) => {
4236
- var _a22, _b, _c;
4237
- return (_c = (_b = (_a22 = steps[steps.length - 1]) == null ? void 0 : _a22.toolCalls) == null ? void 0 : _b.some(
4267
+ var _a23, _b, _c;
4268
+ return (_c = (_b = (_a23 = steps[steps.length - 1]) == null ? void 0 : _a23.toolCalls) == null ? void 0 : _b.some(
4238
4269
  (toolCall) => toolCall.toolName === toolName
4239
4270
  )) != null ? _c : false;
4240
4271
  };
@@ -4564,7 +4595,7 @@ async function generateText({
4564
4595
  }),
4565
4596
  tracer,
4566
4597
  fn: async (span) => {
4567
- var _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
4598
+ var _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
4568
4599
  const initialMessages = initialPrompt.messages;
4569
4600
  const responseMessages = [];
4570
4601
  const {
@@ -4689,7 +4720,7 @@ async function generateText({
4689
4720
  experimental_context
4690
4721
  }));
4691
4722
  const stepModel = resolveLanguageModel(
4692
- (_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : model
4723
+ (_a23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a23 : model
4693
4724
  );
4694
4725
  const stepModelInfo = {
4695
4726
  provider: stepModel.provider,
@@ -4789,7 +4820,7 @@ async function generateText({
4789
4820
  }),
4790
4821
  tracer,
4791
4822
  fn: async (span2) => {
4792
- var _a23, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
4823
+ var _a24, _b2, _c2, _d2, _e2, _f2, _g2, _h2;
4793
4824
  const result = await stepModel.doGenerate({
4794
4825
  ...stepCallSettings,
4795
4826
  tools: stepTools,
@@ -4801,7 +4832,7 @@ async function generateText({
4801
4832
  headers: headersWithUserAgent
4802
4833
  });
4803
4834
  const responseData = {
4804
- id: (_b2 = (_a23 = result.response) == null ? void 0 : _a23.id) != null ? _b2 : generateId2(),
4835
+ id: (_b2 = (_a24 = result.response) == null ? void 0 : _a24.id) != null ? _b2 : generateId2(),
4805
4836
  timestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : /* @__PURE__ */ new Date(),
4806
4837
  modelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,
4807
4838
  headers: (_g2 = result.response) == null ? void 0 : _g2.headers,
@@ -4869,6 +4900,18 @@ async function generateText({
4869
4900
  })
4870
4901
  )
4871
4902
  );
4903
+ const enforcedToolChoice = (stepToolChoice == null ? void 0 : stepToolChoice.type) === "required" || (stepToolChoice == null ? void 0 : stepToolChoice.type) === "tool" ? stepToolChoice : void 0;
4904
+ if (enforcedToolChoice != null && !stepToolCalls.some(
4905
+ (toolCall) => enforcedToolChoice.type === "required" || toolCall.toolName === enforcedToolChoice.toolName
4906
+ )) {
4907
+ throw new ToolChoiceViolationError({
4908
+ toolChoice: enforcedToolChoice,
4909
+ finishReason: currentModelResponse.finishReason.unified,
4910
+ provider: stepModel.provider,
4911
+ modelId: stepModel.modelId,
4912
+ content: currentModelResponse.content
4913
+ });
4914
+ }
4872
4915
  const toolApprovalRequests = {};
4873
4916
  for (const toolCall of stepToolCalls) {
4874
4917
  if (toolCall.invalid) {
@@ -5793,7 +5836,7 @@ function processUIMessageStream({
5793
5836
  new TransformStream({
5794
5837
  async transform(chunk, controller) {
5795
5838
  await runUpdateMessageJob(async ({ state, write }) => {
5796
- var _a22, _b, _c, _d;
5839
+ var _a23, _b, _c, _d;
5797
5840
  function getCurrentStepParts() {
5798
5841
  const parts = state.message.parts;
5799
5842
  let currentStepStartIndex = parts.length - 1;
@@ -5830,7 +5873,7 @@ function processUIMessageStream({
5830
5873
  return toolInvocation;
5831
5874
  }
5832
5875
  function updateToolPart(options, existingPart) {
5833
- var _a23;
5876
+ var _a24;
5834
5877
  const part = existingPart != null ? existingPart : getCurrentStepParts().find(
5835
5878
  (part2) => isStaticToolUIPart(part2) && part2.toolCallId === options.toolCallId
5836
5879
  );
@@ -5849,7 +5892,7 @@ function processUIMessageStream({
5849
5892
  if (options.toolMetadata !== void 0) {
5850
5893
  anyPart.toolMetadata = options.toolMetadata;
5851
5894
  }
5852
- anyPart.providerExecuted = (_a23 = anyOptions.providerExecuted) != null ? _a23 : part.providerExecuted;
5895
+ anyPart.providerExecuted = (_a24 = anyOptions.providerExecuted) != null ? _a24 : part.providerExecuted;
5853
5896
  const providerMetadata = anyOptions.providerMetadata;
5854
5897
  if (providerMetadata != null) {
5855
5898
  if (options.state === "output-available" || options.state === "output-error") {
@@ -5878,7 +5921,7 @@ function processUIMessageStream({
5878
5921
  }
5879
5922
  }
5880
5923
  function updateDynamicToolPart(options, existingPart) {
5881
- var _a23, _b2;
5924
+ var _a24, _b2;
5882
5925
  const part = existingPart != null ? existingPart : getCurrentStepParts().find(
5883
5926
  (part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId
5884
5927
  );
@@ -5890,7 +5933,7 @@ function processUIMessageStream({
5890
5933
  anyPart.input = anyOptions.input;
5891
5934
  anyPart.output = anyOptions.output;
5892
5935
  anyPart.errorText = anyOptions.errorText;
5893
- anyPart.rawInput = (_a23 = anyOptions.rawInput) != null ? _a23 : anyPart.rawInput;
5936
+ anyPart.rawInput = (_a24 = anyOptions.rawInput) != null ? _a24 : anyPart.rawInput;
5894
5937
  anyPart.preliminary = anyOptions.preliminary;
5895
5938
  if (options.title !== void 0) {
5896
5939
  anyPart.title = options.title;
@@ -5965,7 +6008,7 @@ function processUIMessageStream({
5965
6008
  });
5966
6009
  }
5967
6010
  textPart.text += chunk.delta;
5968
- textPart.providerMetadata = (_a22 = chunk.providerMetadata) != null ? _a22 : textPart.providerMetadata;
6011
+ textPart.providerMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textPart.providerMetadata;
5969
6012
  write();
5970
6013
  break;
5971
6014
  }
@@ -6372,7 +6415,8 @@ function handleUIMessageStreamFinish({
6372
6415
  onStepFinish,
6373
6416
  onFinish,
6374
6417
  onError,
6375
- stream
6418
+ stream,
6419
+ getOutcome
6376
6420
  }) {
6377
6421
  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
6378
6422
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
@@ -6381,19 +6425,34 @@ function handleUIMessageStreamFinish({
6381
6425
  messageId = lastMessage.id;
6382
6426
  }
6383
6427
  let isAborted = false;
6428
+ let hasProcessingFailure = false;
6429
+ let processingError;
6430
+ const recordProcessingFailure = (error) => {
6431
+ hasProcessingFailure = true;
6432
+ processingError = error;
6433
+ };
6384
6434
  const idInjectedStream = stream.pipeThrough(
6385
6435
  new TransformStream({
6386
6436
  transform(chunk, controller) {
6387
- if (chunk.type === "start") {
6388
- const startChunk = chunk;
6389
- if (startChunk.messageId == null && messageId != null) {
6390
- startChunk.messageId = messageId;
6437
+ try {
6438
+ let outputChunk = chunk;
6439
+ if (chunk.type === "start") {
6440
+ const startChunk = chunk;
6441
+ if (startChunk.messageId == null && messageId != null) {
6442
+ outputChunk = {
6443
+ ...startChunk,
6444
+ messageId
6445
+ };
6446
+ }
6391
6447
  }
6448
+ if (chunk.type === "abort") {
6449
+ isAborted = true;
6450
+ }
6451
+ controller.enqueue(outputChunk);
6452
+ } catch (error) {
6453
+ recordProcessingFailure(error);
6454
+ throw error;
6392
6455
  }
6393
- if (chunk.type === "abort") {
6394
- isAborted = true;
6395
- }
6396
- controller.enqueue(chunk);
6397
6456
  }
6398
6457
  })
6399
6458
  );
@@ -6406,19 +6465,28 @@ function handleUIMessageStreamFinish({
6406
6465
  // will be overridden by the stream
6407
6466
  });
6408
6467
  const runUpdateMessageJob = async (job) => {
6409
- await job({ state, write: () => {
6410
- } });
6468
+ try {
6469
+ await job({ state, write: () => {
6470
+ } });
6471
+ } catch (error) {
6472
+ recordProcessingFailure(error);
6473
+ throw error;
6474
+ }
6411
6475
  };
6412
6476
  let finishCalled = false;
6413
6477
  const callOnFinish = async () => {
6478
+ var _a23;
6414
6479
  if (finishCalled || !onFinish) {
6415
6480
  return;
6416
6481
  }
6417
6482
  finishCalled = true;
6418
6483
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
6484
+ const declaredOutcome = (_a23 = getOutcome == null ? void 0 : getOutcome()) != null ? _a23 : { status: "unknown" };
6485
+ const outcome = hasProcessingFailure ? { status: "failed", error: processingError } : declaredOutcome.status === "unknown" && isAborted ? { status: "aborted" } : declaredOutcome;
6419
6486
  await onFinish({
6420
- isAborted,
6487
+ isAborted: isAborted || outcome.status === "aborted",
6421
6488
  isContinuation,
6489
+ outcome,
6422
6490
  responseMessage: state.message,
6423
6491
  messages: [
6424
6492
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
@@ -6442,7 +6510,13 @@ function handleUIMessageStreamFinish({
6442
6510
  ]
6443
6511
  });
6444
6512
  } catch (error) {
6445
- onError(error);
6513
+ try {
6514
+ onError(error);
6515
+ } catch (onErrorError) {
6516
+ recordProcessingFailure(onErrorError);
6517
+ await callOnFinish();
6518
+ throw onErrorError;
6519
+ }
6446
6520
  }
6447
6521
  };
6448
6522
  return processUIMessageStream({
@@ -6501,13 +6575,13 @@ function createAsyncIterableStream(source) {
6501
6575
  const reader = this.getReader();
6502
6576
  let finished = false;
6503
6577
  async function cleanup(cancelStream) {
6504
- var _a22;
6578
+ var _a23;
6505
6579
  if (finished)
6506
6580
  return;
6507
6581
  finished = true;
6508
6582
  try {
6509
6583
  if (cancelStream) {
6510
- await ((_a22 = reader.cancel) == null ? void 0 : _a22.call(reader));
6584
+ await ((_a23 = reader.cancel) == null ? void 0 : _a23.call(reader));
6511
6585
  }
6512
6586
  } finally {
6513
6587
  try {
@@ -6622,7 +6696,7 @@ function createStitchableStream() {
6622
6696
  controller == null ? void 0 : controller.close();
6623
6697
  };
6624
6698
  const processPull = async () => {
6625
- var _a22;
6699
+ var _a23;
6626
6700
  if (isCancelled) {
6627
6701
  return;
6628
6702
  }
@@ -6655,7 +6729,7 @@ function createStitchableStream() {
6655
6729
  if (isCancelled) {
6656
6730
  return;
6657
6731
  }
6658
- (_a22 = currentStream.onError) == null ? void 0 : _a22.call(currentStream, error);
6732
+ (_a23 = currentStream.onError) == null ? void 0 : _a23.call(currentStream, error);
6659
6733
  controller == null ? void 0 : controller.error(error);
6660
6734
  innerStreams.shift();
6661
6735
  terminate();
@@ -6679,9 +6753,9 @@ function createStitchableStream() {
6679
6753
  }
6680
6754
  }),
6681
6755
  addStream: (innerStream, callbacks) => {
6682
- var _a22;
6756
+ var _a23;
6683
6757
  if (isCancelled) {
6684
- (_a22 = callbacks == null ? void 0 : callbacks.onCancel) == null ? void 0 : _a22.call(callbacks);
6758
+ (_a23 = callbacks == null ? void 0 : callbacks.onCancel) == null ? void 0 : _a23.call(callbacks);
6685
6759
  void innerStream.cancel().catch(() => {
6686
6760
  });
6687
6761
  return;
@@ -7162,7 +7236,7 @@ function createOutputTransformStream(output) {
7162
7236
  }
7163
7237
  return new TransformStream({
7164
7238
  async transform(chunk, controller) {
7165
- var _a22;
7239
+ var _a23;
7166
7240
  if (chunk.type === "finish-step" && textChunk.length > 0) {
7167
7241
  publishTextChunk({ controller });
7168
7242
  }
@@ -7189,7 +7263,7 @@ function createOutputTransformStream(output) {
7189
7263
  }
7190
7264
  text2 += chunk.text;
7191
7265
  textChunk += chunk.text;
7192
- textProviderMetadata = (_a22 = chunk.providerMetadata) != null ? _a22 : textProviderMetadata;
7266
+ textProviderMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textProviderMetadata;
7193
7267
  if (chunk.text.length === 0 && chunk.providerMetadata != null) {
7194
7268
  controller.enqueue({ part: chunk, partialOutput: void 0 });
7195
7269
  return;
@@ -7295,7 +7369,7 @@ var DefaultStreamTextResult = class {
7295
7369
  let activeReasoningContent = createIdMap();
7296
7370
  const eventProcessor = new TransformStream({
7297
7371
  async transform(chunk, controller) {
7298
- var _a22, _b, _c, _d;
7372
+ var _a23, _b, _c, _d;
7299
7373
  controller.enqueue(chunk);
7300
7374
  const { part } = chunk;
7301
7375
  if (part.type === "text-delta" || part.type === "reasoning-delta" || part.type === "source" || part.type === "tool-call" || part.type === "tool-result" || part.type === "tool-input-start" || part.type === "tool-input-delta" || part.type === "raw") {
@@ -7335,7 +7409,7 @@ var DefaultStreamTextResult = class {
7335
7409
  return;
7336
7410
  }
7337
7411
  activeText.text += part.text;
7338
- activeText.providerMetadata = (_a22 = part.providerMetadata) != null ? _a22 : activeText.providerMetadata;
7412
+ activeText.providerMetadata = (_a23 = part.providerMetadata) != null ? _a23 : activeText.providerMetadata;
7339
7413
  }
7340
7414
  if (part.type === "text-end") {
7341
7415
  const activeText = activeTextContent[part.id];
@@ -7461,7 +7535,7 @@ var DefaultStreamTextResult = class {
7461
7535
  }
7462
7536
  },
7463
7537
  async flush(controller) {
7464
- var _a22, _b, _c, _d, _e, _f, _g;
7538
+ var _a23, _b, _c, _d, _e, _f, _g;
7465
7539
  try {
7466
7540
  if (recordedSteps.length === 0 || recordedNoOutputError != null) {
7467
7541
  const error = (abortSignal == null ? void 0 : abortSignal.aborted) ? abortSignal.reason : recordedNoOutputError != null ? recordedNoOutputError : new NoOutputGeneratedError({
@@ -7525,15 +7599,15 @@ var DefaultStreamTextResult = class {
7525
7599
  },
7526
7600
  "ai.response.toolCalls": {
7527
7601
  output: () => {
7528
- var _a23;
7529
- return ((_a23 = finalStep.toolCalls) == null ? void 0 : _a23.length) ? JSON.stringify(finalStep.toolCalls) : void 0;
7602
+ var _a24;
7603
+ return ((_a24 = finalStep.toolCalls) == null ? void 0 : _a24.length) ? JSON.stringify(finalStep.toolCalls) : void 0;
7530
7604
  }
7531
7605
  },
7532
7606
  "ai.response.providerMetadata": JSON.stringify(
7533
7607
  finalStep.providerMetadata
7534
7608
  ),
7535
7609
  "ai.usage.inputTokens": totalUsage.inputTokens,
7536
- "ai.usage.inputTokenDetails.noCacheTokens": (_a22 = totalUsage.inputTokenDetails) == null ? void 0 : _a22.noCacheTokens,
7610
+ "ai.usage.inputTokenDetails.noCacheTokens": (_a23 = totalUsage.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens,
7537
7611
  "ai.usage.inputTokenDetails.cacheReadTokens": (_b = totalUsage.inputTokenDetails) == null ? void 0 : _b.cacheReadTokens,
7538
7612
  "ai.usage.inputTokenDetails.cacheWriteTokens": (_c = totalUsage.inputTokenDetails) == null ? void 0 : _c.cacheWriteTokens,
7539
7613
  "ai.usage.outputTokens": totalUsage.outputTokens,
@@ -7823,7 +7897,7 @@ var DefaultStreamTextResult = class {
7823
7897
  responseMessages,
7824
7898
  usage
7825
7899
  }) {
7826
- var _a22, _b, _c, _d, _e, _f, _g, _h, _i;
7900
+ var _a23, _b, _c, _d, _e, _f, _g, _h, _i;
7827
7901
  const includeRawChunks2 = self.includeRawChunks;
7828
7902
  const stepTimeoutId = setAbortTimeout({
7829
7903
  abortController: stepAbortController,
@@ -7874,7 +7948,7 @@ var DefaultStreamTextResult = class {
7874
7948
  experimental_context
7875
7949
  }));
7876
7950
  const stepModel = resolveLanguageModel(
7877
- (_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : model
7951
+ (_a23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a23 : model
7878
7952
  );
7879
7953
  const stepModelInfo = {
7880
7954
  provider: stepModel.provider,
@@ -8044,7 +8118,7 @@ var DefaultStreamTextResult = class {
8044
8118
  streamWithToolResults.pipeThrough(
8045
8119
  new TransformStream({
8046
8120
  async transform(chunk, controller) {
8047
- var _a23, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2;
8121
+ var _a24, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2;
8048
8122
  resetChunkTimeout();
8049
8123
  if (chunk.type === "stream-start") {
8050
8124
  warnings = chunk.warnings;
@@ -8083,7 +8157,7 @@ var DefaultStreamTextResult = class {
8083
8157
  case "text-end": {
8084
8158
  controller.enqueue({
8085
8159
  ...chunk,
8086
- id: (_a23 = textPartIds.get(chunk.id)) != null ? _a23 : chunk.id
8160
+ id: (_a24 = textPartIds.get(chunk.id)) != null ? _a24 : chunk.id
8087
8161
  });
8088
8162
  textPartIds.delete(chunk.id);
8089
8163
  break;
@@ -8230,7 +8304,7 @@ var DefaultStreamTextResult = class {
8230
8304
  },
8231
8305
  // invoke onFinish callback and resolve toolResults promise when the stream is about to close:
8232
8306
  async flush(controller) {
8233
- var _a23, _b2, _c2, _d2, _e2, _f2, _g2;
8307
+ var _a24, _b2, _c2, _d2, _e2, _f2, _g2;
8234
8308
  if (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {
8235
8309
  controller.enqueue({
8236
8310
  type: "error",
@@ -8257,7 +8331,7 @@ var DefaultStreamTextResult = class {
8257
8331
  "ai.response.model": stepResponse.modelId,
8258
8332
  "ai.response.timestamp": stepResponse.timestamp.toISOString(),
8259
8333
  "ai.usage.inputTokens": stepUsage.inputTokens,
8260
- "ai.usage.inputTokenDetails.noCacheTokens": (_a23 = stepUsage.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens,
8334
+ "ai.usage.inputTokenDetails.noCacheTokens": (_a24 = stepUsage.inputTokenDetails) == null ? void 0 : _a24.noCacheTokens,
8261
8335
  "ai.usage.inputTokenDetails.cacheReadTokens": (_b2 = stepUsage.inputTokenDetails) == null ? void 0 : _b2.cacheReadTokens,
8262
8336
  "ai.usage.inputTokenDetails.cacheWriteTokens": (_c2 = stepUsage.inputTokenDetails) == null ? void 0 : _c2.cacheWriteTokens,
8263
8337
  "ai.usage.outputTokens": stepUsage.outputTokens,
@@ -8534,19 +8608,19 @@ var DefaultStreamTextResult = class {
8534
8608
  this._steps.reject(error);
8535
8609
  }
8536
8610
  async consumeStream(options) {
8537
- var _a22;
8611
+ var _a23;
8538
8612
  try {
8539
8613
  await consumeStream({
8540
8614
  stream: this.fullStream,
8541
8615
  onError: (error) => {
8542
- var _a23;
8616
+ var _a24;
8543
8617
  this.rejectResultPromises(error);
8544
- (_a23 = options == null ? void 0 : options.onError) == null ? void 0 : _a23.call(options, error);
8618
+ (_a24 = options == null ? void 0 : options.onError) == null ? void 0 : _a24.call(options, error);
8545
8619
  }
8546
8620
  });
8547
8621
  } catch (error) {
8548
8622
  this.rejectResultPromises(error);
8549
- (_a22 = options == null ? void 0 : options.onError) == null ? void 0 : _a22.call(options, error);
8623
+ (_a23 = options == null ? void 0 : options.onError) == null ? void 0 : _a23.call(options, error);
8550
8624
  }
8551
8625
  }
8552
8626
  get experimental_partialOutputStream() {
@@ -8566,8 +8640,8 @@ var DefaultStreamTextResult = class {
8566
8640
  );
8567
8641
  }
8568
8642
  get elementStream() {
8569
- var _a22, _b, _c;
8570
- const transform = (_a22 = this.outputSpecification) == null ? void 0 : _a22.createElementStreamTransform();
8643
+ var _a23, _b, _c;
8644
+ const transform = (_a23 = this.outputSpecification) == null ? void 0 : _a23.createElementStreamTransform();
8571
8645
  if (transform == null) {
8572
8646
  throw new UnsupportedFunctionalityError2({
8573
8647
  functionality: `element streams in ${(_c = (_b = this.outputSpecification) == null ? void 0 : _b.name) != null ? _c : "text"} mode`
@@ -8577,8 +8651,8 @@ var DefaultStreamTextResult = class {
8577
8651
  }
8578
8652
  get output() {
8579
8653
  return this.finalStep.then((step) => {
8580
- var _a22;
8581
- const output = (_a22 = this.outputSpecification) != null ? _a22 : text();
8654
+ var _a23;
8655
+ const output = (_a23 = this.outputSpecification) != null ? _a23 : text();
8582
8656
  return output.parseCompleteOutput(
8583
8657
  { text: step.text },
8584
8658
  {
@@ -8601,19 +8675,74 @@ var DefaultStreamTextResult = class {
8601
8675
  onError = () => "An error occurred."
8602
8676
  // prevent leaking server error details to the client by default
8603
8677
  } = {}) {
8678
+ let outcome = { status: "unknown" };
8679
+ let hasFatalFailure = false;
8680
+ const setSourceOutcome = (newOutcome) => {
8681
+ if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) {
8682
+ outcome = newOutcome;
8683
+ }
8684
+ };
8685
+ const failOutcome = (error) => {
8686
+ hasFatalFailure = true;
8687
+ outcome = { status: "failed", error };
8688
+ };
8604
8689
  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({
8605
8690
  originalMessages,
8606
8691
  responseMessageId: generateMessageId
8607
8692
  }) : void 0;
8608
8693
  const isDynamic = (part) => {
8609
- var _a22;
8610
- const tool2 = (_a22 = this.tools) == null ? void 0 : _a22[part.toolName];
8694
+ var _a23;
8695
+ const tool2 = (_a23 = this.tools) == null ? void 0 : _a23[part.toolName];
8611
8696
  if (tool2 == null) {
8612
8697
  return part.dynamic;
8613
8698
  }
8614
8699
  return (tool2 == null ? void 0 : tool2.type) === "dynamic" ? true : void 0;
8615
8700
  };
8616
- const baseStream = this.fullStream.pipeThrough(
8701
+ const trackFatalFailures = (stream) => {
8702
+ const reader = stream.getReader();
8703
+ let readerReleased = false;
8704
+ let streamCancelled = false;
8705
+ const releaseReader = () => {
8706
+ if (!readerReleased) {
8707
+ reader.releaseLock();
8708
+ readerReleased = true;
8709
+ }
8710
+ };
8711
+ return new ReadableStream({
8712
+ async pull(controller) {
8713
+ try {
8714
+ const { done, value } = await reader.read();
8715
+ if (done) {
8716
+ releaseReader();
8717
+ if (!streamCancelled) {
8718
+ controller.close();
8719
+ }
8720
+ } else {
8721
+ controller.enqueue(value);
8722
+ }
8723
+ } catch (error) {
8724
+ releaseReader();
8725
+ if (!streamCancelled) {
8726
+ failOutcome(error);
8727
+ controller.error(error);
8728
+ }
8729
+ }
8730
+ },
8731
+ async cancel(reason) {
8732
+ streamCancelled = true;
8733
+ if (readerReleased) {
8734
+ return;
8735
+ }
8736
+ try {
8737
+ await reader.cancel(reason);
8738
+ } finally {
8739
+ releaseReader();
8740
+ }
8741
+ }
8742
+ });
8743
+ };
8744
+ const sourceStream = trackFatalFailures(this.fullStream);
8745
+ const convertedStream = sourceStream.pipeThrough(
8617
8746
  new TransformStream({
8618
8747
  transform: async (part, controller) => {
8619
8748
  const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
@@ -8850,16 +8979,25 @@ var DefaultStreamTextResult = class {
8850
8979
  messageMetadata: messageMetadataValue
8851
8980
  });
8852
8981
  }
8982
+ if (part.type === "finish") {
8983
+ setSourceOutcome({ status: "completed" });
8984
+ } else if (part.type === "abort") {
8985
+ setSourceOutcome({ status: "aborted" });
8986
+ } else if (part.type === "error") {
8987
+ setSourceOutcome({ status: "failed", error: part.error });
8988
+ }
8853
8989
  }
8854
8990
  })
8855
8991
  );
8992
+ const baseStream = trackFatalFailures(convertedStream);
8856
8993
  return createAsyncIterableStream(
8857
8994
  handleUIMessageStreamFinish({
8858
8995
  stream: baseStream,
8859
8996
  messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),
8860
8997
  originalMessages,
8861
8998
  onFinish,
8862
- onError
8999
+ onError,
9000
+ getOutcome: () => outcome
8863
9001
  })
8864
9002
  );
8865
9003
  }
@@ -8952,7 +9090,7 @@ var ToolLoopAgent = class {
8952
9090
  return this.settings.tools;
8953
9091
  }
8954
9092
  async prepareCall(options) {
8955
- var _a22, _b, _c, _d;
9093
+ var _a23, _b, _c, _d;
8956
9094
  if (this.settings.callOptionsSchema != null && options.options !== void 0) {
8957
9095
  const validatedOptions = await validateTypes2({
8958
9096
  value: options.options,
@@ -8964,7 +9102,7 @@ var ToolLoopAgent = class {
8964
9102
  const { onStepFinish: _settingsOnStepFinish, ...settingsWithoutCallback } = this.settings;
8965
9103
  const baseCallArgs = {
8966
9104
  ...settingsWithoutCallback,
8967
- stopWhen: (_a22 = this.settings.stopWhen) != null ? _a22 : stepCountIs(20),
9105
+ stopWhen: (_a23 = this.settings.stopWhen) != null ? _a23 : stepCountIs(20),
8968
9106
  ...options
8969
9107
  };
8970
9108
  const preparedCallArgs = (_d = await ((_c = (_b = this.settings).prepareCall) == null ? void 0 : _c.call(
@@ -9052,6 +9190,7 @@ function createUIMessageStream({
9052
9190
  }) {
9053
9191
  let controller;
9054
9192
  const ongoingStreamPromises = [];
9193
+ let outcome = { status: "unknown" };
9055
9194
  const stream = new ReadableStream({
9056
9195
  start(controllerArg) {
9057
9196
  controller = controllerArg;
@@ -9063,6 +9202,35 @@ function createUIMessageStream({
9063
9202
  } catch (error) {
9064
9203
  }
9065
9204
  }
9205
+ function setOutcome(newOutcome) {
9206
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") {
9207
+ outcome = newOutcome;
9208
+ }
9209
+ }
9210
+ function failOutcome(error) {
9211
+ outcome = { status: "failed", error };
9212
+ }
9213
+ function safeError(error) {
9214
+ try {
9215
+ controller.error(error);
9216
+ } catch (e) {
9217
+ }
9218
+ }
9219
+ function handleError(error) {
9220
+ failOutcome(error);
9221
+ let errorText;
9222
+ try {
9223
+ errorText = onError(error);
9224
+ } catch (onErrorError) {
9225
+ failOutcome(onErrorError);
9226
+ safeError(onErrorError);
9227
+ return;
9228
+ }
9229
+ safeEnqueue({
9230
+ type: "error",
9231
+ errorText
9232
+ });
9233
+ }
9066
9234
  try {
9067
9235
  const result = execute({
9068
9236
  writer: {
@@ -9080,38 +9248,29 @@ function createUIMessageStream({
9080
9248
  safeEnqueue(value);
9081
9249
  }
9082
9250
  })().catch((error) => {
9083
- safeEnqueue({
9084
- type: "error",
9085
- errorText: onError(error)
9086
- });
9251
+ handleError(error);
9087
9252
  })
9088
9253
  );
9089
9254
  },
9255
+ setOutcome,
9090
9256
  onError
9091
9257
  }
9092
9258
  });
9093
9259
  if (result) {
9094
9260
  ongoingStreamPromises.push(
9095
9261
  result.catch((error) => {
9096
- safeEnqueue({
9097
- type: "error",
9098
- errorText: onError(error)
9099
- });
9262
+ handleError(error);
9100
9263
  })
9101
9264
  );
9102
9265
  }
9103
9266
  } catch (error) {
9104
- safeEnqueue({
9105
- type: "error",
9106
- errorText: onError(error)
9107
- });
9267
+ handleError(error);
9108
9268
  }
9109
- const waitForStreams = new Promise(async (resolve3) => {
9269
+ const waitForStreams = (async () => {
9110
9270
  while (ongoingStreamPromises.length > 0) {
9111
9271
  await ongoingStreamPromises.shift();
9112
9272
  }
9113
- resolve3();
9114
- });
9273
+ })();
9115
9274
  waitForStreams.finally(() => {
9116
9275
  try {
9117
9276
  controller.close();
@@ -9124,7 +9283,8 @@ function createUIMessageStream({
9124
9283
  originalMessages,
9125
9284
  onStepFinish,
9126
9285
  onFinish,
9127
- onError
9286
+ onError,
9287
+ getOutcome: () => outcome
9128
9288
  });
9129
9289
  }
9130
9290
 
@@ -9156,7 +9316,7 @@ function readUIMessageStream({
9156
9316
  onError,
9157
9317
  terminateOnError = false
9158
9318
  }) {
9159
- var _a22;
9319
+ var _a23;
9160
9320
  let controller;
9161
9321
  let hasErrored = false;
9162
9322
  const outputStream = new ReadableStream({
@@ -9165,7 +9325,7 @@ function readUIMessageStream({
9165
9325
  }
9166
9326
  });
9167
9327
  const state = createStreamingUIMessageState({
9168
- messageId: (_a22 = message == null ? void 0 : message.id) != null ? _a22 : "",
9328
+ messageId: (_a23 = message == null ? void 0 : message.id) != null ? _a23 : "",
9169
9329
  lastMessage: message
9170
9330
  });
9171
9331
  const handleError = (error) => {
@@ -9234,7 +9394,7 @@ async function convertToModelMessages(messages, options) {
9234
9394
  modelMessages.push({
9235
9395
  role: "user",
9236
9396
  content: message.parts.map((part) => {
9237
- var _a22;
9397
+ var _a23;
9238
9398
  if (isTextUIPart(part)) {
9239
9399
  return {
9240
9400
  type: "text",
@@ -9252,7 +9412,7 @@ async function convertToModelMessages(messages, options) {
9252
9412
  };
9253
9413
  }
9254
9414
  if (isDataUIPart(part)) {
9255
- return (_a22 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a22.call(
9415
+ return (_a23 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a23.call(
9256
9416
  options,
9257
9417
  part
9258
9418
  );
@@ -9265,7 +9425,7 @@ async function convertToModelMessages(messages, options) {
9265
9425
  if (message.parts != null) {
9266
9426
  let block = [];
9267
9427
  async function processBlock() {
9268
- var _a22, _b, _c, _d, _e, _f, _g, _h;
9428
+ var _a23, _b, _c, _d, _e, _f, _g, _h;
9269
9429
  if (block.length === 0) {
9270
9430
  return;
9271
9431
  }
@@ -9298,7 +9458,7 @@ async function convertToModelMessages(messages, options) {
9298
9458
  type: "tool-call",
9299
9459
  toolCallId: part.toolCallId,
9300
9460
  toolName,
9301
- input: part.state === "output-error" ? (_a22 = part.input) != null ? _a22 : "rawInput" in part ? part.rawInput : void 0 : part.input,
9461
+ input: part.state === "output-error" ? (_a23 = part.input) != null ? _a23 : "rawInput" in part ? part.rawInput : void 0 : part.input,
9302
9462
  providerExecuted: part.providerExecuted,
9303
9463
  ...part.callProviderMetadata != null ? { providerOptions: part.callProviderMetadata } : {}
9304
9464
  });
@@ -9348,8 +9508,8 @@ async function convertToModelMessages(messages, options) {
9348
9508
  }
9349
9509
  const toolParts = block.filter(
9350
9510
  (part) => {
9351
- var _a23;
9352
- return isToolUIPart(part) && (part.providerExecuted !== true || ((_a23 = part.approval) == null ? void 0 : _a23.approved) != null);
9511
+ var _a24;
9512
+ return isToolUIPart(part) && (part.providerExecuted !== true || ((_a24 = part.approval) == null ? void 0 : _a24.approved) != null);
9353
9513
  }
9354
9514
  );
9355
9515
  if (toolParts.length > 0) {
@@ -9442,6 +9602,7 @@ import {
9442
9602
  } from "@ai-sdk/provider";
9443
9603
  import {
9444
9604
  lazySchema as lazySchema2,
9605
+ safeValidateTypes as safeValidateTypes5,
9445
9606
  validateTypes as validateTypes3,
9446
9607
  zodSchema as zodSchema2
9447
9608
  } from "@ai-sdk/provider-utils";
@@ -9450,6 +9611,17 @@ var toolMetadataSchema2 = z8.record(
9450
9611
  z8.string(),
9451
9612
  jsonValueSchema.optional()
9452
9613
  );
9614
+ function isEmptyObject(value) {
9615
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
9616
+ }
9617
+ function asDynamicToolPart(toolPart) {
9618
+ const { type, ...part } = toolPart;
9619
+ return {
9620
+ ...part,
9621
+ type: "dynamic-tool",
9622
+ toolName: type.slice(5)
9623
+ };
9624
+ }
9453
9625
  var uiMessagesSchema = lazySchema2(
9454
9626
  () => zodSchema2(
9455
9627
  z8.array(
@@ -9753,11 +9925,13 @@ var uiMessagesSchema = lazySchema2(
9753
9925
  ).nonempty("Messages array must not be empty")
9754
9926
  )
9755
9927
  );
9756
- async function safeValidateUIMessages({
9928
+ async function safeValidateUIMessagesInternal({
9757
9929
  messages,
9758
9930
  metadataSchema,
9759
9931
  dataSchemas,
9760
9932
  tools
9933
+ }, {
9934
+ convertMissingTerminalToolsToDynamic
9761
9935
  }) {
9762
9936
  try {
9763
9937
  if (messages == null) {
@@ -9786,7 +9960,8 @@ async function safeValidateUIMessages({
9786
9960
  });
9787
9961
  }
9788
9962
  }
9789
- if (dataSchemas || tools) {
9963
+ const shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;
9964
+ if (dataSchemas || shouldValidateToolParts) {
9790
9965
  for (const [msgIdx, message] of validatedMessages.entries()) {
9791
9966
  for (const [partIdx, part] of message.parts.entries()) {
9792
9967
  if (dataSchemas && part.type.startsWith("data-")) {
@@ -9817,11 +9992,17 @@ async function safeValidateUIMessages({
9817
9992
  }
9818
9993
  });
9819
9994
  }
9820
- if (tools && part.type.startsWith("tool-")) {
9995
+ if (shouldValidateToolParts && part.type.startsWith("tool-")) {
9821
9996
  const toolPart = part;
9822
9997
  const toolName = toolPart.type.slice(5);
9823
- const tool2 = tools[toolName];
9824
- if (!tool2 && (toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied")) {
9998
+ const tool2 = tools == null ? void 0 : tools[toolName];
9999
+ const isTerminal = toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied";
10000
+ if (!tool2 && isTerminal) {
10001
+ if (tools != null || convertMissingTerminalToolsToDynamic) {
10002
+ message.parts[partIdx] = asDynamicToolPart(
10003
+ toolPart
10004
+ );
10005
+ }
9825
10006
  continue;
9826
10007
  }
9827
10008
  if (!tool2) {
@@ -9838,15 +10019,39 @@ async function safeValidateUIMessages({
9838
10019
  })
9839
10020
  };
9840
10021
  }
9841
- if (toolPart.state === "input-available") {
9842
- await validateTypes3({
10022
+ const inputValidationContext = {
10023
+ field: `messages[${msgIdx}].parts[${partIdx}].input`,
10024
+ entityName: toolName,
10025
+ entityId: toolPart.toolCallId
10026
+ };
10027
+ let convertToDynamic = false;
10028
+ if (toolPart.state === "output-error") {
10029
+ if (toolPart.input !== void 0) {
10030
+ const result = await safeValidateTypes5({
10031
+ value: toolPart.input,
10032
+ schema: tool2.inputSchema,
10033
+ context: inputValidationContext
10034
+ });
10035
+ convertToDynamic = !result.success;
10036
+ }
10037
+ } else if (toolPart.state === "output-available") {
10038
+ const result = await safeValidateTypes5({
9843
10039
  value: toolPart.input,
9844
10040
  schema: tool2.inputSchema,
9845
- context: {
9846
- field: `messages[${msgIdx}].parts[${partIdx}].input`,
9847
- entityName: toolName,
9848
- entityId: toolPart.toolCallId
10041
+ context: inputValidationContext
10042
+ });
10043
+ if (!result.success) {
10044
+ if (isEmptyObject(toolPart.input)) {
10045
+ convertToDynamic = true;
10046
+ } else {
10047
+ throw result.error;
9849
10048
  }
10049
+ }
10050
+ } else if (toolPart.state === "input-available" || toolPart.state === "approval-requested" || toolPart.state === "approval-responded" || toolPart.state === "output-denied") {
10051
+ await validateTypes3({
10052
+ value: toolPart.input,
10053
+ schema: tool2.inputSchema,
10054
+ context: inputValidationContext
9850
10055
  });
9851
10056
  }
9852
10057
  if (toolPart.state === "output-available" && tool2.outputSchema) {
@@ -9860,6 +10065,11 @@ async function safeValidateUIMessages({
9860
10065
  }
9861
10066
  });
9862
10067
  }
10068
+ if (convertToDynamic) {
10069
+ message.parts[partIdx] = asDynamicToolPart(
10070
+ toolPart
10071
+ );
10072
+ }
9863
10073
  }
9864
10074
  }
9865
10075
  }
@@ -9876,17 +10086,23 @@ async function safeValidateUIMessages({
9876
10086
  };
9877
10087
  }
9878
10088
  }
9879
- async function validateUIMessages({
9880
- messages,
9881
- metadataSchema,
9882
- dataSchemas,
9883
- tools
9884
- }) {
9885
- const response = await safeValidateUIMessages({
9886
- messages,
9887
- metadataSchema,
9888
- dataSchemas,
9889
- tools
10089
+ async function safeValidateUIMessages(options) {
10090
+ return safeValidateUIMessagesInternal(options, {
10091
+ convertMissingTerminalToolsToDynamic: false
10092
+ });
10093
+ }
10094
+ async function validateUIMessages(options) {
10095
+ const response = await safeValidateUIMessages(options);
10096
+ if (!response.success)
10097
+ throw response.error;
10098
+ return response.data;
10099
+ }
10100
+ async function validateUIMessagesForAgent(options) {
10101
+ const response = await safeValidateUIMessagesInternal(options, {
10102
+ // Agent tool sets can include ephemeral tools (for example, tools from a
10103
+ // disconnected MCP server), so terminal history is converted to dynamic
10104
+ // tool parts when those tools are no longer registered.
10105
+ convertMissingTerminalToolsToDynamic: true
9890
10106
  });
9891
10107
  if (!response.success)
9892
10108
  throw response.error;
@@ -9904,8 +10120,8 @@ async function createAgentUIStream({
9904
10120
  onStepFinish,
9905
10121
  ...uiMessageStreamOptions
9906
10122
  }) {
9907
- var _a22;
9908
- const validatedMessages = await validateUIMessages({
10123
+ var _a23;
10124
+ const validatedMessages = await validateUIMessagesForAgent({
9909
10125
  messages: uiMessages,
9910
10126
  tools: agent.tools
9911
10127
  });
@@ -9923,7 +10139,7 @@ async function createAgentUIStream({
9923
10139
  return result.toUIMessageStream({
9924
10140
  ...uiMessageStreamOptions,
9925
10141
  // TODO reading `originalMessages` is here for bc, always use `validatedMessages` in v7
9926
- originalMessages: (_a22 = uiMessageStreamOptions.originalMessages) != null ? _a22 : validatedMessages
10142
+ originalMessages: (_a23 = uiMessageStreamOptions.originalMessages) != null ? _a23 : validatedMessages
9927
10143
  });
9928
10144
  }
9929
10145
 
@@ -10023,7 +10239,7 @@ async function embed({
10023
10239
  }),
10024
10240
  tracer,
10025
10241
  fn: async (doEmbedSpan) => {
10026
- var _a22, _b;
10242
+ var _a23, _b;
10027
10243
  const modelResponse = await model.doEmbed({
10028
10244
  values: [value],
10029
10245
  abortSignal,
@@ -10031,7 +10247,7 @@ async function embed({
10031
10247
  providerOptions
10032
10248
  });
10033
10249
  const embedding2 = modelResponse.embeddings[0];
10034
- const usage2 = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };
10250
+ const usage2 = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };
10035
10251
  doEmbedSpan.setAttributes(
10036
10252
  await selectTelemetryAttributes({
10037
10253
  telemetry,
@@ -10153,7 +10369,7 @@ async function embedMany({
10153
10369
  }),
10154
10370
  tracer,
10155
10371
  fn: async (span) => {
10156
- var _a22;
10372
+ var _a23;
10157
10373
  const [
10158
10374
  maxEmbeddingsPerCall,
10159
10375
  maxInputBytesPerCall,
@@ -10185,7 +10401,7 @@ async function embedMany({
10185
10401
  }),
10186
10402
  tracer,
10187
10403
  fn: async (doEmbedSpan) => {
10188
- var _a23, _b;
10404
+ var _a24, _b;
10189
10405
  const modelResponse = await model.doEmbed({
10190
10406
  values,
10191
10407
  abortSignal,
@@ -10193,7 +10409,7 @@ async function embedMany({
10193
10409
  providerOptions
10194
10410
  });
10195
10411
  const embeddings3 = modelResponse.embeddings;
10196
- const usage2 = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };
10412
+ const usage2 = (_a24 = modelResponse.usage) != null ? _a24 : { tokens: NaN };
10197
10413
  doEmbedSpan.setAttributes(
10198
10414
  await selectTelemetryAttributes({
10199
10415
  telemetry,
@@ -10278,7 +10494,7 @@ async function embedMany({
10278
10494
  }),
10279
10495
  tracer,
10280
10496
  fn: async (doEmbedSpan) => {
10281
- var _a23, _b;
10497
+ var _a24, _b;
10282
10498
  const modelResponse = await model.doEmbed({
10283
10499
  values: chunk,
10284
10500
  abortSignal,
@@ -10286,7 +10502,7 @@ async function embedMany({
10286
10502
  providerOptions
10287
10503
  });
10288
10504
  const embeddings2 = modelResponse.embeddings;
10289
- const usage = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };
10505
+ const usage = (_a24 = modelResponse.usage) != null ? _a24 : { tokens: NaN };
10290
10506
  doEmbedSpan.setAttributes(
10291
10507
  await selectTelemetryAttributes({
10292
10508
  telemetry,
@@ -10325,7 +10541,7 @@ async function embedMany({
10325
10541
  result.providerMetadata
10326
10542
  )) {
10327
10543
  providerMetadata[providerName] = {
10328
- ...(_a22 = providerMetadata[providerName]) != null ? _a22 : {},
10544
+ ...(_a23 = providerMetadata[providerName]) != null ? _a23 : {},
10329
10545
  ...metadata
10330
10546
  };
10331
10547
  }
@@ -10420,7 +10636,7 @@ async function generateImage({
10420
10636
  abortSignal,
10421
10637
  headers
10422
10638
  }) {
10423
- var _a22, _b;
10639
+ var _a23, _b;
10424
10640
  const model = resolveImageModel(modelArg);
10425
10641
  const headersWithUserAgent = withUserAgentSuffix5(
10426
10642
  headers != null ? headers : {},
@@ -10430,7 +10646,7 @@ async function generateImage({
10430
10646
  maxRetries: maxRetriesArg,
10431
10647
  abortSignal
10432
10648
  });
10433
- const maxImagesPerCallWithDefault = (_a22 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a22 : 1;
10649
+ const maxImagesPerCallWithDefault = (_a23 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a23 : 1;
10434
10650
  const callCount = Math.ceil(n / maxImagesPerCallWithDefault);
10435
10651
  const callImageCounts = Array.from({ length: callCount }, (_, i) => {
10436
10652
  if (i < callCount - 1) {
@@ -10471,13 +10687,13 @@ async function generateImage({
10471
10687
  images.push(
10472
10688
  ...result.images.map(
10473
10689
  (image) => {
10474
- var _a23;
10690
+ var _a24;
10475
10691
  return new DefaultGeneratedFile({
10476
10692
  data: image,
10477
- mediaType: (_a23 = detectMediaType({
10693
+ mediaType: (_a24 = detectMediaType({
10478
10694
  data: image,
10479
10695
  signatures: imageMediaTypeSignatures
10480
- })) != null ? _a23 : "image/png"
10696
+ })) != null ? _a24 : "image/png"
10481
10697
  });
10482
10698
  }
10483
10699
  )
@@ -10605,7 +10821,7 @@ import {
10605
10821
  } from "@ai-sdk/provider";
10606
10822
  import {
10607
10823
  asSchema as asSchema5,
10608
- safeValidateTypes as safeValidateTypes5
10824
+ safeValidateTypes as safeValidateTypes6
10609
10825
  } from "@ai-sdk/provider-utils";
10610
10826
  var noSchemaOutputStrategy = {
10611
10827
  type: "no-schema",
@@ -10645,7 +10861,7 @@ var objectOutputStrategy = (schema) => ({
10645
10861
  };
10646
10862
  },
10647
10863
  async validateFinalResult(value) {
10648
- return safeValidateTypes5({ value, schema });
10864
+ return safeValidateTypes6({ value, schema });
10649
10865
  },
10650
10866
  createElementStream() {
10651
10867
  throw new UnsupportedFunctionalityError3({
@@ -10677,7 +10893,7 @@ var arrayOutputStrategy = (schema) => {
10677
10893
  isFirstDelta,
10678
10894
  isFinalDelta
10679
10895
  }) {
10680
- var _a22;
10896
+ var _a23;
10681
10897
  if (!isJSONObject(value) || !isJSONArray(value.elements)) {
10682
10898
  return {
10683
10899
  success: false,
@@ -10691,7 +10907,7 @@ var arrayOutputStrategy = (schema) => {
10691
10907
  const resultArray = [];
10692
10908
  for (let i = 0; i < inputArray.length; i++) {
10693
10909
  const element = inputArray[i];
10694
- const result = await safeValidateTypes5({ value: element, schema });
10910
+ const result = await safeValidateTypes6({ value: element, schema });
10695
10911
  if (i === inputArray.length - 1 && !isFinalDelta) {
10696
10912
  continue;
10697
10913
  }
@@ -10700,7 +10916,7 @@ var arrayOutputStrategy = (schema) => {
10700
10916
  }
10701
10917
  resultArray.push(result.value);
10702
10918
  }
10703
- const publishedElementCount = (_a22 = latestObject == null ? void 0 : latestObject.length) != null ? _a22 : 0;
10919
+ const publishedElementCount = (_a23 = latestObject == null ? void 0 : latestObject.length) != null ? _a23 : 0;
10704
10920
  let textDelta = "";
10705
10921
  if (isFirstDelta) {
10706
10922
  textDelta += "[";
@@ -10733,7 +10949,7 @@ var arrayOutputStrategy = (schema) => {
10733
10949
  const inputArray = value.elements;
10734
10950
  const resultArray = [];
10735
10951
  for (const element of inputArray) {
10736
- const result = await safeValidateTypes5({ value: element, schema });
10952
+ const result = await safeValidateTypes6({ value: element, schema });
10737
10953
  if (!result.success) {
10738
10954
  return result;
10739
10955
  }
@@ -11123,7 +11339,7 @@ async function generateObject(options) {
11123
11339
  }),
11124
11340
  tracer,
11125
11341
  fn: async (span) => {
11126
- var _a22;
11342
+ var _a23;
11127
11343
  let result;
11128
11344
  let finishReason;
11129
11345
  let usage;
@@ -11170,7 +11386,7 @@ async function generateObject(options) {
11170
11386
  }),
11171
11387
  tracer,
11172
11388
  fn: async (span2) => {
11173
- var _a23, _b, _c, _d, _e, _f, _g, _h;
11389
+ var _a24, _b, _c, _d, _e, _f, _g, _h;
11174
11390
  const result2 = await model.doGenerate({
11175
11391
  responseFormat: {
11176
11392
  type: "json",
@@ -11185,7 +11401,7 @@ async function generateObject(options) {
11185
11401
  headers: headersWithUserAgent
11186
11402
  });
11187
11403
  const responseData = {
11188
- id: (_b = (_a23 = result2.response) == null ? void 0 : _a23.id) != null ? _b : generateId2(),
11404
+ id: (_b = (_a24 = result2.response) == null ? void 0 : _a24.id) != null ? _b : generateId2(),
11189
11405
  timestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),
11190
11406
  modelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,
11191
11407
  headers: (_g = result2.response) == null ? void 0 : _g.headers,
@@ -11241,7 +11457,7 @@ async function generateObject(options) {
11241
11457
  usage = asLanguageModelUsage(generateResult.usage);
11242
11458
  warnings = generateResult.warnings;
11243
11459
  resultProviderMetadata = generateResult.providerMetadata;
11244
- request = (_a22 = generateResult.request) != null ? _a22 : {};
11460
+ request = (_a23 = generateResult.request) != null ? _a23 : {};
11245
11461
  response = generateResult.responseData;
11246
11462
  reasoning = generateResult.reasoning;
11247
11463
  logWarnings({
@@ -11304,9 +11520,9 @@ var DefaultGenerateObjectResult = class {
11304
11520
  this.reasoning = options.reasoning;
11305
11521
  }
11306
11522
  toJsonResponse(init) {
11307
- var _a22;
11523
+ var _a23;
11308
11524
  return new Response(JSON.stringify(this.object), {
11309
- status: (_a22 = init == null ? void 0 : init.status) != null ? _a22 : 200,
11525
+ status: (_a23 = init == null ? void 0 : init.status) != null ? _a23 : 200,
11310
11526
  headers: prepareHeaders(init == null ? void 0 : init.headers, {
11311
11527
  "content-type": "application/json; charset=utf-8"
11312
11528
  })
@@ -11440,8 +11656,8 @@ function simulateReadableStream({
11440
11656
  chunkDelayInMs = 0,
11441
11657
  _internal
11442
11658
  }) {
11443
- var _a22;
11444
- const delay = (_a22 = _internal == null ? void 0 : _internal.delay) != null ? _a22 : delayFunction;
11659
+ var _a23;
11660
+ const delay = (_a23 = _internal == null ? void 0 : _internal.delay) != null ? _a23 : delayFunction;
11445
11661
  let index = 0;
11446
11662
  return new ReadableStream({
11447
11663
  async pull(controller) {
@@ -11715,7 +11931,7 @@ var DefaultStreamObjectResult = class {
11715
11931
  const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(
11716
11932
  new TransformStream({
11717
11933
  async transform(chunk, controller) {
11718
- var _a22, _b, _c;
11934
+ var _a23, _b, _c;
11719
11935
  if (typeof chunk === "object" && chunk.type === "stream-start") {
11720
11936
  warnings = chunk.warnings;
11721
11937
  return;
@@ -11765,7 +11981,7 @@ var DefaultStreamObjectResult = class {
11765
11981
  switch (chunk.type) {
11766
11982
  case "response-metadata": {
11767
11983
  fullResponse = {
11768
- id: (_a22 = chunk.id) != null ? _a22 : fullResponse.id,
11984
+ id: (_a23 = chunk.id) != null ? _a23 : fullResponse.id,
11769
11985
  timestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,
11770
11986
  modelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId
11771
11987
  };
@@ -12081,7 +12297,7 @@ async function generateSpeech({
12081
12297
  abortSignal,
12082
12298
  headers
12083
12299
  }) {
12084
- var _a22;
12300
+ var _a23;
12085
12301
  const resolvedModel = resolveSpeechModel(model);
12086
12302
  if (!resolvedModel) {
12087
12303
  throw new Error("Model could not be resolved");
@@ -12118,10 +12334,10 @@ async function generateSpeech({
12118
12334
  return new DefaultSpeechResult({
12119
12335
  audio: new DefaultGeneratedAudioFile({
12120
12336
  data: result.audio,
12121
- mediaType: (_a22 = detectMediaType({
12337
+ mediaType: (_a23 = detectMediaType({
12122
12338
  data: result.audio,
12123
12339
  signatures: audioMediaTypeSignatures
12124
- })) != null ? _a22 : "audio/mp3"
12340
+ })) != null ? _a23 : "audio/mp3"
12125
12341
  }),
12126
12342
  warnings: result.warnings,
12127
12343
  responses: [result.response],
@@ -12130,11 +12346,11 @@ async function generateSpeech({
12130
12346
  }
12131
12347
  var DefaultSpeechResult = class {
12132
12348
  constructor(options) {
12133
- var _a22;
12349
+ var _a23;
12134
12350
  this.audio = options.audio;
12135
12351
  this.warnings = options.warnings;
12136
12352
  this.responses = options.responses;
12137
- this.providerMetadata = (_a22 = options.providerMetadata) != null ? _a22 : {};
12353
+ this.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};
12138
12354
  }
12139
12355
  };
12140
12356
 
@@ -12357,7 +12573,7 @@ async function experimental_generateVideo({
12357
12573
  headers,
12358
12574
  download: downloadFn = defaultDownload
12359
12575
  }) {
12360
- var _a22, _b;
12576
+ var _a23, _b;
12361
12577
  const model = resolveVideoModel(modelArg);
12362
12578
  const headersWithUserAgent = withUserAgentSuffix8(
12363
12579
  headers != null ? headers : {},
@@ -12384,9 +12600,9 @@ async function experimental_generateVideo({
12384
12600
  message: "inputReferences were ignored because frameImages were provided; frameImages and inputReferences cannot be combined."
12385
12601
  });
12386
12602
  }
12387
- const firstFrameImage = (_a22 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find(
12603
+ const firstFrameImage = (_a23 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find(
12388
12604
  (frame) => frame.frameType === "first_frame"
12389
- )) == null ? void 0 : _a22.image;
12605
+ )) == null ? void 0 : _a23.image;
12390
12606
  if (image != null && firstFrameImage != null) {
12391
12607
  warnings.push({
12392
12608
  type: "other",
@@ -12530,8 +12746,8 @@ function normalizePrompt2(promptArg) {
12530
12746
  };
12531
12747
  }
12532
12748
  function detectFileMediaType(data, restrictToImages) {
12533
- var _a22;
12534
- const detected = restrictToImages ? detectMediaType({ data, signatures: imageMediaTypeSignatures }) : (_a22 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a22 : detectMediaType({ data, signatures: videoMediaTypeSignatures });
12749
+ var _a23;
12750
+ const detected = restrictToImages ? detectMediaType({ data, signatures: imageMediaTypeSignatures }) : (_a23 = detectMediaType({ data, signatures: imageMediaTypeSignatures })) != null ? _a23 : detectMediaType({ data, signatures: videoMediaTypeSignatures });
12535
12751
  return detected != null ? detected : "image/png";
12536
12752
  }
12537
12753
  function normalizeImageData(dataContent, { restrictToImages = true } = {}) {
@@ -12625,8 +12841,8 @@ function stripMarkdownCodeFenceSuffix(text2) {
12625
12841
  return text2.replace(/\n?```\s*$/, "").trimEnd();
12626
12842
  }
12627
12843
  function extractJsonMiddleware(options) {
12628
- var _a22;
12629
- const transform = (_a22 = options == null ? void 0 : options.transform) != null ? _a22 : defaultTransform;
12844
+ var _a23;
12845
+ const transform = (_a23 = options == null ? void 0 : options.transform) != null ? _a23 : defaultTransform;
12630
12846
  const hasCustomTransform = (options == null ? void 0 : options.transform) !== void 0;
12631
12847
  return {
12632
12848
  specificationVersion: "v3",
@@ -13002,13 +13218,13 @@ function addToolInputExamplesMiddleware({
13002
13218
  return {
13003
13219
  specificationVersion: "v3",
13004
13220
  transformParams: async ({ params }) => {
13005
- var _a22;
13006
- if (!((_a22 = params.tools) == null ? void 0 : _a22.length)) {
13221
+ var _a23;
13222
+ if (!((_a23 = params.tools) == null ? void 0 : _a23.length)) {
13007
13223
  return params;
13008
13224
  }
13009
13225
  const transformedTools = params.tools.map((tool2) => {
13010
- var _a23;
13011
- if (tool2.type !== "function" || !((_a23 = tool2.inputExamples) == null ? void 0 : _a23.length)) {
13226
+ var _a24;
13227
+ if (tool2.type !== "function" || !((_a24 = tool2.inputExamples) == null ? void 0 : _a24.length)) {
13012
13228
  return tool2;
13013
13229
  }
13014
13230
  const formattedExamples = tool2.inputExamples.map((example, index) => format(example, index)).join("\n");
@@ -13055,7 +13271,7 @@ var doWrap = ({
13055
13271
  modelId,
13056
13272
  providerId
13057
13273
  }) => {
13058
- var _a22, _b, _c;
13274
+ var _a23, _b, _c;
13059
13275
  async function doTransform({
13060
13276
  params,
13061
13277
  type
@@ -13064,7 +13280,7 @@ var doWrap = ({
13064
13280
  }
13065
13281
  return {
13066
13282
  specificationVersion: "v3",
13067
- provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : model.provider,
13283
+ provider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,
13068
13284
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
13069
13285
  supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
13070
13286
  async doGenerate(params) {
@@ -13112,7 +13328,7 @@ var doWrap2 = ({
13112
13328
  modelId,
13113
13329
  providerId
13114
13330
  }) => {
13115
- var _a22, _b, _c, _d;
13331
+ var _a23, _b, _c, _d;
13116
13332
  async function doTransform({
13117
13333
  params
13118
13334
  }) {
@@ -13120,7 +13336,7 @@ var doWrap2 = ({
13120
13336
  }
13121
13337
  return {
13122
13338
  specificationVersion: "v3",
13123
- provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : model.provider,
13339
+ provider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,
13124
13340
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
13125
13341
  maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,
13126
13342
  [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2]: getEmbeddingModelMaxInputBytesPerCall(model),
@@ -13160,11 +13376,11 @@ var doWrap3 = ({
13160
13376
  modelId,
13161
13377
  providerId
13162
13378
  }) => {
13163
- var _a22, _b, _c;
13379
+ var _a23, _b, _c;
13164
13380
  async function doTransform({ params }) {
13165
13381
  return transformParams ? await transformParams({ params, model }) : params;
13166
13382
  }
13167
- const maxImagesPerCallRaw = (_a22 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a22 : model.maxImagesPerCall;
13383
+ const maxImagesPerCallRaw = (_a23 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a23 : model.maxImagesPerCall;
13168
13384
  const maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;
13169
13385
  return {
13170
13386
  specificationVersion: "v3",
@@ -13314,11 +13530,11 @@ function customProvider({
13314
13530
  var experimental_customProvider = customProvider;
13315
13531
 
13316
13532
  // src/registry/no-such-provider-error.ts
13317
- import { AISDKError as AISDKError25, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
13318
- var name21 = "AI_NoSuchProviderError";
13319
- var marker21 = `vercel.ai.error.${name21}`;
13320
- var symbol21 = Symbol.for(marker21);
13321
- var _a21;
13533
+ import { AISDKError as AISDKError26, NoSuchModelError as NoSuchModelError3 } from "@ai-sdk/provider";
13534
+ var name22 = "AI_NoSuchProviderError";
13535
+ var marker22 = `vercel.ai.error.${name22}`;
13536
+ var symbol22 = Symbol.for(marker22);
13537
+ var _a22;
13322
13538
  var NoSuchProviderError = class extends NoSuchModelError3 {
13323
13539
  constructor({
13324
13540
  modelId,
@@ -13327,16 +13543,16 @@ var NoSuchProviderError = class extends NoSuchModelError3 {
13327
13543
  availableProviders,
13328
13544
  message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})`
13329
13545
  }) {
13330
- super({ errorName: name21, modelId, modelType, message });
13331
- this[_a21] = true;
13546
+ super({ errorName: name22, modelId, modelType, message });
13547
+ this[_a22] = true;
13332
13548
  this.providerId = providerId;
13333
13549
  this.availableProviders = availableProviders;
13334
13550
  }
13335
13551
  static isInstance(error) {
13336
- return AISDKError25.hasMarker(error, marker21);
13552
+ return AISDKError26.hasMarker(error, marker22);
13337
13553
  }
13338
13554
  };
13339
- _a21 = symbol21;
13555
+ _a22 = symbol22;
13340
13556
 
13341
13557
  // src/registry/provider-registry.ts
13342
13558
  import {
@@ -13399,10 +13615,10 @@ var DefaultProviderRegistry = class {
13399
13615
  return [id.slice(0, index), id.slice(index + this.separator.length)];
13400
13616
  }
13401
13617
  languageModel(id) {
13402
- var _a22, _b;
13618
+ var _a23, _b;
13403
13619
  const [providerId, modelId] = this.splitId(id, "languageModel");
13404
- let model = (_b = (_a22 = this.getProvider(providerId, "languageModel")).languageModel) == null ? void 0 : _b.call(
13405
- _a22,
13620
+ let model = (_b = (_a23 = this.getProvider(providerId, "languageModel")).languageModel) == null ? void 0 : _b.call(
13621
+ _a23,
13406
13622
  modelId
13407
13623
  );
13408
13624
  if (model == null) {
@@ -13417,10 +13633,10 @@ var DefaultProviderRegistry = class {
13417
13633
  return model;
13418
13634
  }
13419
13635
  embeddingModel(id) {
13420
- var _a22;
13636
+ var _a23;
13421
13637
  const [providerId, modelId] = this.splitId(id, "embeddingModel");
13422
13638
  const provider = this.getProvider(providerId, "embeddingModel");
13423
- const model = (_a22 = provider.embeddingModel) == null ? void 0 : _a22.call(provider, modelId);
13639
+ const model = (_a23 = provider.embeddingModel) == null ? void 0 : _a23.call(provider, modelId);
13424
13640
  if (model == null) {
13425
13641
  throw new NoSuchModelError4({
13426
13642
  modelId: id,
@@ -13430,10 +13646,10 @@ var DefaultProviderRegistry = class {
13430
13646
  return model;
13431
13647
  }
13432
13648
  imageModel(id) {
13433
- var _a22;
13649
+ var _a23;
13434
13650
  const [providerId, modelId] = this.splitId(id, "imageModel");
13435
13651
  const provider = this.getProvider(providerId, "imageModel");
13436
- let model = (_a22 = provider.imageModel) == null ? void 0 : _a22.call(provider, modelId);
13652
+ let model = (_a23 = provider.imageModel) == null ? void 0 : _a23.call(provider, modelId);
13437
13653
  if (model == null) {
13438
13654
  throw new NoSuchModelError4({ modelId: id, modelType: "imageModel" });
13439
13655
  }
@@ -13446,10 +13662,10 @@ var DefaultProviderRegistry = class {
13446
13662
  return model;
13447
13663
  }
13448
13664
  transcriptionModel(id) {
13449
- var _a22;
13665
+ var _a23;
13450
13666
  const [providerId, modelId] = this.splitId(id, "transcriptionModel");
13451
13667
  const provider = this.getProvider(providerId, "transcriptionModel");
13452
- const model = (_a22 = provider.transcriptionModel) == null ? void 0 : _a22.call(provider, modelId);
13668
+ const model = (_a23 = provider.transcriptionModel) == null ? void 0 : _a23.call(provider, modelId);
13453
13669
  if (model == null) {
13454
13670
  throw new NoSuchModelError4({
13455
13671
  modelId: id,
@@ -13459,20 +13675,20 @@ var DefaultProviderRegistry = class {
13459
13675
  return model;
13460
13676
  }
13461
13677
  speechModel(id) {
13462
- var _a22;
13678
+ var _a23;
13463
13679
  const [providerId, modelId] = this.splitId(id, "speechModel");
13464
13680
  const provider = this.getProvider(providerId, "speechModel");
13465
- const model = (_a22 = provider.speechModel) == null ? void 0 : _a22.call(provider, modelId);
13681
+ const model = (_a23 = provider.speechModel) == null ? void 0 : _a23.call(provider, modelId);
13466
13682
  if (model == null) {
13467
13683
  throw new NoSuchModelError4({ modelId: id, modelType: "speechModel" });
13468
13684
  }
13469
13685
  return model;
13470
13686
  }
13471
13687
  rerankingModel(id) {
13472
- var _a22;
13688
+ var _a23;
13473
13689
  const [providerId, modelId] = this.splitId(id, "rerankingModel");
13474
13690
  const provider = this.getProvider(providerId, "rerankingModel");
13475
- const model = (_a22 = provider.rerankingModel) == null ? void 0 : _a22.call(provider, modelId);
13691
+ const model = (_a23 = provider.rerankingModel) == null ? void 0 : _a23.call(provider, modelId);
13476
13692
  if (model == null) {
13477
13693
  throw new NoSuchModelError4({ modelId: id, modelType: "rerankingModel" });
13478
13694
  }
@@ -13530,7 +13746,7 @@ async function rerank({
13530
13746
  }),
13531
13747
  tracer,
13532
13748
  fn: async () => {
13533
- var _a22, _b;
13749
+ var _a23, _b;
13534
13750
  const { ranking, response, providerMetadata, warnings } = await retry(
13535
13751
  () => recordSpan({
13536
13752
  name: "ai.rerank.doRerank",
@@ -13594,7 +13810,7 @@ async function rerank({
13594
13810
  providerMetadata,
13595
13811
  response: {
13596
13812
  id: response == null ? void 0 : response.id,
13597
- timestamp: (_a22 = response == null ? void 0 : response.timestamp) != null ? _a22 : /* @__PURE__ */ new Date(),
13813
+ timestamp: (_a23 = response == null ? void 0 : response.timestamp) != null ? _a23 : /* @__PURE__ */ new Date(),
13598
13814
  modelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,
13599
13815
  headers: response == null ? void 0 : response.headers,
13600
13816
  body: response == null ? void 0 : response.body
@@ -13644,16 +13860,16 @@ async function transcribe({
13644
13860
  const audioData = audio instanceof URL ? (await downloadFn({ url: audio, abortSignal })).data : convertDataContentToUint8Array(audio);
13645
13861
  const result = await retry(
13646
13862
  () => {
13647
- var _a22;
13863
+ var _a23;
13648
13864
  return resolvedModel.doGenerate({
13649
13865
  audio: audioData,
13650
13866
  abortSignal,
13651
13867
  headers: headersWithUserAgent,
13652
13868
  providerOptions,
13653
- mediaType: (_a22 = detectMediaType({
13869
+ mediaType: (_a23 = detectMediaType({
13654
13870
  data: audioData,
13655
13871
  signatures: audioMediaTypeSignatures
13656
- })) != null ? _a22 : "audio/wav"
13872
+ })) != null ? _a23 : "audio/wav"
13657
13873
  });
13658
13874
  }
13659
13875
  );
@@ -13677,14 +13893,14 @@ async function transcribe({
13677
13893
  }
13678
13894
  var DefaultTranscriptionResult = class {
13679
13895
  constructor(options) {
13680
- var _a22;
13896
+ var _a23;
13681
13897
  this.text = options.text;
13682
13898
  this.segments = options.segments;
13683
13899
  this.language = options.language;
13684
13900
  this.durationInSeconds = options.durationInSeconds;
13685
13901
  this.warnings = options.warnings;
13686
13902
  this.responses = options.responses;
13687
- this.providerMetadata = (_a22 = options.providerMetadata) != null ? _a22 : {};
13903
+ this.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};
13688
13904
  }
13689
13905
  };
13690
13906
 
@@ -13727,7 +13943,7 @@ async function callCompletionApi({
13727
13943
  onError,
13728
13944
  fetch: fetch2 = getOriginalFetch()
13729
13945
  }) {
13730
- var _a22;
13946
+ var _a23;
13731
13947
  try {
13732
13948
  setLoading(true);
13733
13949
  setError(void 0);
@@ -13755,7 +13971,7 @@ async function callCompletionApi({
13755
13971
  });
13756
13972
  if (!response.ok) {
13757
13973
  throw new Error(
13758
- (_a22 = await response.text()) != null ? _a22 : "Failed to fetch the chat response."
13974
+ (_a23 = await response.text()) != null ? _a23 : "Failed to fetch the chat response."
13759
13975
  );
13760
13976
  }
13761
13977
  if (!response.body) {
@@ -13841,12 +14057,12 @@ async function convertFileListToFileUIParts(files) {
13841
14057
  }
13842
14058
  return Promise.all(
13843
14059
  Array.from(files).map(async (file) => {
13844
- const { name: name22, type } = file;
14060
+ const { name: name23, type } = file;
13845
14061
  const dataUrl = await new Promise((resolve3, reject) => {
13846
14062
  const reader = new FileReader();
13847
14063
  reader.onload = (readerEvent) => {
13848
- var _a22;
13849
- resolve3((_a22 = readerEvent.target) == null ? void 0 : _a22.result);
14064
+ var _a23;
14065
+ resolve3((_a23 = readerEvent.target) == null ? void 0 : _a23.result);
13850
14066
  };
13851
14067
  reader.onerror = (error) => reject(error);
13852
14068
  reader.readAsDataURL(file);
@@ -13854,7 +14070,7 @@ async function convertFileListToFileUIParts(files) {
13854
14070
  return {
13855
14071
  type: "file",
13856
14072
  mediaType: type,
13857
- filename: name22,
14073
+ filename: name23,
13858
14074
  url: dataUrl
13859
14075
  };
13860
14076
  })
@@ -13891,7 +14107,7 @@ var HttpChatTransport = class {
13891
14107
  abortSignal,
13892
14108
  ...options
13893
14109
  }) {
13894
- var _a22, _b, _c, _d, _e;
14110
+ var _a23, _b, _c, _d, _e;
13895
14111
  const resolvedBody = await resolve2(this.body);
13896
14112
  const resolvedHeaders = await resolve2(this.headers);
13897
14113
  const resolvedCredentials = await resolve2(this.credentials);
@@ -13899,7 +14115,7 @@ var HttpChatTransport = class {
13899
14115
  ...normalizeHeaders(resolvedHeaders),
13900
14116
  ...normalizeHeaders(options.headers)
13901
14117
  };
13902
- const preparedRequest = await ((_a22 = this.prepareSendMessagesRequest) == null ? void 0 : _a22.call(this, {
14118
+ const preparedRequest = await ((_a23 = this.prepareSendMessagesRequest) == null ? void 0 : _a23.call(this, {
13903
14119
  api: this.api,
13904
14120
  id: options.chatId,
13905
14121
  messages: options.messages,
@@ -13943,7 +14159,7 @@ var HttpChatTransport = class {
13943
14159
  return this.processResponseStream(response.body);
13944
14160
  }
13945
14161
  async reconnectToStream(options) {
13946
- var _a22, _b, _c, _d, _e;
14162
+ var _a23, _b, _c, _d, _e;
13947
14163
  const resolvedBody = await resolve2(this.body);
13948
14164
  const resolvedHeaders = await resolve2(this.headers);
13949
14165
  const resolvedCredentials = await resolve2(this.credentials);
@@ -13951,7 +14167,7 @@ var HttpChatTransport = class {
13951
14167
  ...normalizeHeaders(resolvedHeaders),
13952
14168
  ...normalizeHeaders(options.headers)
13953
14169
  };
13954
- const preparedRequest = await ((_a22 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a22.call(this, {
14170
+ const preparedRequest = await ((_a23 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a23.call(this, {
13955
14171
  api: this.api,
13956
14172
  id: options.chatId,
13957
14173
  body: { ...resolvedBody, ...options.body },
@@ -14031,11 +14247,11 @@ var AbstractChat = class {
14031
14247
  * If a messageId is provided, the message will be replaced.
14032
14248
  */
14033
14249
  this.sendMessage = async (message, options) => {
14034
- var _a22, _b, _c, _d;
14250
+ var _a23, _b, _c, _d;
14035
14251
  if (message == null) {
14036
14252
  await this.makeRequest({
14037
14253
  trigger: "submit-message",
14038
- messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,
14254
+ messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
14039
14255
  ...options
14040
14256
  });
14041
14257
  return;
@@ -14145,11 +14361,11 @@ var AbstractChat = class {
14145
14361
  }
14146
14362
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14147
14363
  this.shouldSendAutomatically().then((shouldSend) => {
14148
- var _a22;
14364
+ var _a23;
14149
14365
  if (shouldSend) {
14150
14366
  this.makeRequest({
14151
14367
  trigger: "submit-message",
14152
- messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,
14368
+ messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
14153
14369
  ...options
14154
14370
  });
14155
14371
  }
@@ -14175,11 +14391,11 @@ var AbstractChat = class {
14175
14391
  }
14176
14392
  if (this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen) {
14177
14393
  this.shouldSendAutomatically().then((shouldSend) => {
14178
- var _a22;
14394
+ var _a23;
14179
14395
  if (shouldSend) {
14180
14396
  this.makeRequest({
14181
14397
  trigger: "submit-message",
14182
- messageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,
14398
+ messageId: (_a23 = this.lastMessage) == null ? void 0 : _a23.id,
14183
14399
  ...options
14184
14400
  });
14185
14401
  }
@@ -14192,8 +14408,8 @@ var AbstractChat = class {
14192
14408
  * Abort the current request immediately, keep the generated tokens if any.
14193
14409
  */
14194
14410
  this.stop = async () => {
14195
- var _a22, _b;
14196
- (_a22 = this.activeResumeRequest) == null ? void 0 : _a22.abortController.abort();
14411
+ var _a23, _b;
14412
+ (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14197
14413
  (_b = this.activeResponse) == null ? void 0 : _b.abortController.abort();
14198
14414
  };
14199
14415
  this.id = id;
@@ -14258,11 +14474,11 @@ var AbstractChat = class {
14258
14474
  body,
14259
14475
  messageId
14260
14476
  }) {
14261
- var _a22, _b, _c;
14477
+ var _a23, _b, _c;
14262
14478
  const abortController = new AbortController();
14263
14479
  const activeResumeRequest = trigger === "resume-stream" ? { abortController } : void 0;
14264
14480
  if (activeResumeRequest) {
14265
- (_a22 = this.activeResumeRequest) == null ? void 0 : _a22.abortController.abort();
14481
+ (_a23 = this.activeResumeRequest) == null ? void 0 : _a23.abortController.abort();
14266
14482
  this.activeResumeRequest = activeResumeRequest;
14267
14483
  }
14268
14484
  const isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;
@@ -14358,14 +14574,14 @@ var AbstractChat = class {
14358
14574
  return job({
14359
14575
  state: response.state,
14360
14576
  write: ({ updateStatus = true } = {}) => {
14361
- var _a23;
14577
+ var _a24;
14362
14578
  if (response.abortController.signal.aborted) {
14363
14579
  return;
14364
14580
  }
14365
14581
  if (updateStatus) {
14366
14582
  this.setStatus({ status: "streaming" });
14367
14583
  }
14368
- const replaceLastMessage = response.state.message.id === ((_a23 = this.lastMessage) == null ? void 0 : _a23.id);
14584
+ const replaceLastMessage = response.state.message.id === ((_a24 = this.lastMessage) == null ? void 0 : _a24.id);
14369
14585
  if (replaceLastMessage) {
14370
14586
  this.state.replaceMessage(
14371
14587
  this.state.messages.length - 1,
@@ -14469,7 +14685,7 @@ var DirectChatTransport = class {
14469
14685
  messages,
14470
14686
  abortSignal
14471
14687
  }) {
14472
- const validatedMessages = await validateUIMessages({
14688
+ const validatedMessages = await validateUIMessagesForAgent({
14473
14689
  messages,
14474
14690
  tools: this.agent.tools
14475
14691
  });
@@ -14573,7 +14789,7 @@ var TextStreamChatTransport = class extends HttpChatTransport {
14573
14789
  }
14574
14790
  };
14575
14791
  export {
14576
- AISDKError22 as AISDKError,
14792
+ AISDKError23 as AISDKError,
14577
14793
  APICallError,
14578
14794
  AbstractChat,
14579
14795
  DefaultChatTransport,
@@ -14615,6 +14831,7 @@ export {
14615
14831
  TooManyEmbeddingValuesForCallError,
14616
14832
  ToolCallNotFoundForApprovalError,
14617
14833
  ToolCallRepairError,
14834
+ ToolChoiceViolationError,
14618
14835
  ToolLoopAgent,
14619
14836
  TypeValidationError,
14620
14837
  UIMessageStreamError,