ai 7.0.128 → 7.0.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/index.d.ts +19 -4
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +173 -39
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +10 -2
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +68 -16
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/06-provider-options.mdx +11 -10
  11. package/docs/03-agents/02-building-agents.mdx +16 -11
  12. package/docs/03-agents/07-workflow-agent.mdx +3 -3
  13. package/docs/03-ai-sdk-core/17-runtime-and-tool-context.mdx +18 -14
  14. package/docs/03-ai-sdk-core/25-settings.mdx +3 -2
  15. package/docs/03-ai-sdk-core/26-reasoning.mdx +12 -5
  16. package/docs/03-ai-sdk-core/32-decisions.mdx +20 -20
  17. package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -0
  18. package/docs/04-ai-sdk-ui/21-error-handling.mdx +28 -3
  19. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +2 -2
  20. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +3 -3
  21. package/docs/07-reference/01-ai-sdk-core/14-decide.mdx +2 -1
  22. package/docs/07-reference/05-ai-sdk-errors/ai-decision-refusal-error.mdx +33 -0
  23. package/package.json +15 -15
  24. package/src/decide/decide.ts +11 -0
  25. package/src/decide/validate-decision.ts +1 -0
  26. package/src/error/index.ts +1 -0
  27. package/src/generate-object/generate-object.ts +10 -0
  28. package/src/generate-object/stream-object.ts +10 -0
  29. package/src/generate-speech/index.ts +13 -1
  30. package/src/generate-text/generate-text.ts +3 -1
  31. package/src/generate-text/stream-text.ts +22 -5
  32. package/src/generate-text/tool-approval-signature.ts +7 -4
  33. package/src/global.ts +2 -1
  34. package/src/logger/deprecations.ts +72 -0
  35. package/src/logger/log-warnings.ts +25 -3
  36. package/src/model/as-language-model-v3.ts +4 -0
  37. package/src/prompt/convert-to-language-model-prompt.ts +7 -1
  38. package/src/realtime/encode-realtime-frame.ts +7 -2
  39. package/src/transcribe/index.ts +13 -1
  40. package/src/types/index.ts +1 -0
  41. package/src/types/language-model.ts +9 -1
  42. package/src/types/usage.ts +21 -0
  43. package/src/ui/chat.ts +16 -8
  44. package/src/ui/convert-to-model-messages.ts +40 -8
  45. package/src/ui/http-chat-transport.ts +5 -3
  46. package/src/ui/process-text-stream.ts +5 -1
  47. package/src/ui/text-stream-chat-transport.ts +3 -1
  48. package/src/ui/ui-messages.ts +8 -0
  49. package/src/ui/unavailable-tool.ts +17 -0
  50. package/src/ui/validate-ui-messages.ts +10 -2
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { GatewayAuthenticationError, GatewayError, createGateway, gateway, gateway as gateway$1 } from "@ai-sdk/gateway";
3
3
  import { DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise, DownloadError, DownloadError as DownloadError$1, EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, asArray, asSchema, asSchema as asSchema$1, cancelResponseBody, convertBase64ToUint8Array, convertUint8ArrayToBase64, createIdGenerator, createIdGenerator as createIdGenerator$1, delay, detectMediaType, dynamicTool, executeTool, experimental_getToolCaller, experimental_toolCaller, fetchUntrustedUrl, filterNullable, generateId, generateId as generateId$1, getErrorMessage, getRuntimeEnvironmentUserAgent, isAbortError, isBuffer, isExecutableTool, isFullMediaType, isNonNullable, isProviderReference, isProviderStreamError, isUrlSupported, jsonSchema, jsonSchema as jsonSchema$1, lazySchema, normalizeHeaders, parseJsonEventStream, parseJsonEventStream as parseJsonEventStream$1, readResponseWithSizeLimit, resolve, retryWithExponentialBackoff, safeParseJSON, safeValidateTypes, tool, tool as tool$1, validateTypes, withUserAgentSuffix, zodSchema, zodSchema as zodSchema$1 } from "@ai-sdk/provider-utils";
4
- import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidArgumentError as InvalidArgumentError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
4
+ import { AISDKError, AISDKError as AISDKError$1, APICallError, APICallError as APICallError$1, EmptyResponseBodyError, EmptyResponseBodyError as EmptyResponseBodyError$1, Experimental_DecisionRefusalError, Experimental_DecisionRefusalError as Experimental_DecisionRefusalError$1, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_DecisionUnsupportedQuestionTypeError as Experimental_DecisionUnsupportedQuestionTypeError$1, InvalidArgumentError as InvalidArgumentError$1, InvalidPromptError, InvalidPromptError as InvalidPromptError$1, InvalidResponseDataError, InvalidResponseDataError as InvalidResponseDataError$1, JSONParseError, JSONParseError as JSONParseError$1, LoadAPIKeyError, LoadSettingError, NoContentGeneratedError, NoSuchModelError, NoSuchModelError as NoSuchModelError$1, NoSuchProviderReferenceError, TooManyEmbeddingValuesForCallError, TypeValidationError, TypeValidationError as TypeValidationError$1, UnsupportedFunctionalityError, UnsupportedFunctionalityError as UnsupportedFunctionalityError$1, getErrorMessage as getErrorMessage$1, isJSONArray, isJSONObject } from "@ai-sdk/provider";
5
5
  import { array, boolean, custom, discriminatedUnion, enum as enum$1, instanceof as instanceof$1, lazy, literal, looseObject, never, null as null$1, number, object, record, string, union, unknown } from "zod/v4";
6
6
  //#region src/error/invalid-argument-error.ts
7
7
  const name$23 = "AI_InvalidArgumentError";
@@ -532,6 +532,35 @@ var RetryError = class extends AISDKError$1 {
532
532
  /** @deprecated Use `Experimental_DecisionUnsupportedQuestionTypeError` instead. */
533
533
  const Experimental_EvaluationUnsupportedQuestionTypeError = Experimental_DecisionUnsupportedQuestionTypeError$1;
534
534
  //#endregion
535
+ //#region src/logger/deprecations.ts
536
+ const deprecationCodes = /* @__PURE__ */ new Map([
537
+ ["generateObject", "AISDK_DEP_GENERATE_OBJECT"],
538
+ ["streamObject", "AISDK_DEP_STREAM_OBJECT"],
539
+ ["experimental_generateSpeech", "AISDK_DEP_EXPERIMENTAL_GENERATE_SPEECH"],
540
+ ["experimental_transcribe", "AISDK_DEP_EXPERIMENTAL_TRANSCRIBE"],
541
+ ["\"image\" content part", "AISDK_DEP_IMAGE_CONTENT_PART"],
542
+ ["\"tool-result\" content of type \"file-data\"", "AISDK_DEP_TOOL_RESULT_FILE_DATA"],
543
+ ["\"tool-result\" content of type \"file-url\"", "AISDK_DEP_TOOL_RESULT_FILE_URL"],
544
+ ["\"tool-result\" content of type \"file-id\"", "AISDK_DEP_TOOL_RESULT_FILE_ID"],
545
+ ["\"tool-result\" content of type \"file-reference\"", "AISDK_DEP_TOOL_RESULT_FILE_REFERENCE"],
546
+ ["\"tool-result\" content of type \"image-data\"", "AISDK_DEP_TOOL_RESULT_IMAGE_DATA"],
547
+ ["\"tool-result\" content of type \"image-url\"", "AISDK_DEP_TOOL_RESULT_IMAGE_URL"],
548
+ ["\"tool-result\" content of type \"image-file-id\"", "AISDK_DEP_TOOL_RESULT_IMAGE_FILE_ID"],
549
+ ["\"tool-result\" content of type \"image-file-reference\"", "AISDK_DEP_TOOL_RESULT_IMAGE_FILE_REFERENCE"],
550
+ ["rawInput in output-error UI message parts", "AISDK_DEP_UI_MESSAGE_RAW_INPUT"]
551
+ ]);
552
+ /**
553
+ * Escape punctuation and UTF-16 code units without losing case or collapsing
554
+ * distinct settings. Underscores are escaped too, so `__` separates code parts.
555
+ */
556
+ function encodeCodePart(value) {
557
+ return value.replace(/[^a-zA-Z0-9]/g, (character) => `_${character.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`);
558
+ }
559
+ function getDeprecationCode({ setting, provider }) {
560
+ if (provider == null) return deprecationCodes.get(setting) ?? `AISDK_DEP_SETTING_${encodeCodePart(setting)}`;
561
+ return `AISDK_DEP_PROVIDER_${encodeCodePart(provider)}__${encodeCodePart(setting)}`;
562
+ }
563
+ //#endregion
535
564
  //#region src/logger/log-warnings.ts
536
565
  /**
537
566
  * Formats a warning object into a human-readable string with clear AI SDK branding.
@@ -562,9 +591,13 @@ function formatWarning({ warning, provider, model }) {
562
591
  }
563
592
  const FIRST_WARNING_INFO_MESSAGE = "AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.";
564
593
  let hasLoggedBefore = false;
565
- function emitWarning({ message, type }) {
566
- if (typeof process !== "undefined" && typeof process.emitWarning === "function") process.emitWarning(message, { type });
567
- else console.warn(message);
594
+ const emittedDeprecationCodes = /* @__PURE__ */ new Set();
595
+ function emitWarning({ message, type, code }) {
596
+ if (typeof process !== "undefined" && typeof process.emitWarning === "function") process.emitWarning(message, code == null ? { type } : {
597
+ type,
598
+ code
599
+ });
600
+ else console.warn(code == null ? message : `[${code}] ${message}`);
568
601
  }
569
602
  /**
570
603
  * Logs warnings to the console or uses a custom logger if configured.
@@ -572,7 +605,9 @@ function emitWarning({ message, type }) {
572
605
  * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:
573
606
  * - If set to `false`, warnings are suppressed.
574
607
  * - If set to a function, that function is called with the warnings.
575
- * - Otherwise, warnings are logged to the console using `console.warn`.
608
+ * - Otherwise, warnings use `process.emitWarning` when available, falling back
609
+ * to `console.warn`. Deprecations have stable codes and are emitted once per
610
+ * code by the default logger. Custom loggers receive every warning.
576
611
  *
577
612
  * @param options - The options containing warnings and context.
578
613
  * @param options.warnings - The warnings to log.
@@ -594,14 +629,25 @@ const logWarnings = (options) => {
594
629
  type: "Warning"
595
630
  });
596
631
  }
597
- for (const warning of options.warnings) emitWarning({
598
- message: formatWarning({
599
- warning,
600
- provider: options.provider,
601
- model: options.model
602
- }),
603
- type: warning.type === "deprecated" ? "DeprecationWarning" : "Warning"
604
- });
632
+ for (const warning of options.warnings) {
633
+ const code = warning.type === "deprecated" ? getDeprecationCode({
634
+ setting: warning.setting,
635
+ provider: options.provider
636
+ }) : void 0;
637
+ if (code != null) {
638
+ if (emittedDeprecationCodes.has(code)) continue;
639
+ emittedDeprecationCodes.add(code);
640
+ }
641
+ emitWarning({
642
+ message: formatWarning({
643
+ warning,
644
+ provider: options.provider,
645
+ model: options.model
646
+ }),
647
+ type: warning.type === "deprecated" ? "DeprecationWarning" : "Warning",
648
+ code
649
+ });
650
+ }
605
651
  };
606
652
  //#endregion
607
653
  //#region src/util/log-v2-compatibility-warning.ts
@@ -724,7 +770,8 @@ function convertV2UsageToV3(usage) {
724
770
  total: usage.outputTokens,
725
771
  text: void 0,
726
772
  reasoning: usage.reasoningTokens
727
- }
773
+ },
774
+ raw: usage.totalTokens == null ? void 0 : { totalTokens: usage.totalTokens }
728
775
  };
729
776
  }
730
777
  //#endregion
@@ -1127,7 +1174,7 @@ function cloneValue(value) {
1127
1174
  }
1128
1175
  //#endregion
1129
1176
  //#region src/version.ts
1130
- const VERSION = "7.0.128";
1177
+ const VERSION = "7.0.130";
1131
1178
  //#endregion
1132
1179
  //#region src/util/download/download.ts
1133
1180
  /**
@@ -1383,7 +1430,7 @@ async function convertToLanguageModelPrompt({ prompt, supportedUrls, download, a
1383
1430
  const lastContentPart = lastCombinedMessage.content.at(-1);
1384
1431
  if (lastContentPart != null && lastCombinedMessage.providerOptions != null) lastContentPart.providerOptions = mergeObjects(lastCombinedMessage.providerOptions, lastContentPart.providerOptions);
1385
1432
  lastCombinedMessage.content.push(...message.content);
1386
- lastCombinedMessage.providerOptions = message.providerOptions;
1433
+ lastCombinedMessage.providerOptions = lastContentPart == null ? mergeObjects(lastCombinedMessage.providerOptions, message.providerOptions) : message.providerOptions;
1387
1434
  } else combinedMessages.push(message);
1388
1435
  }
1389
1436
  const toolCallIds = /* @__PURE__ */ new Set();
@@ -2497,6 +2544,7 @@ function createNullLanguageModelUsage() {
2497
2544
  };
2498
2545
  }
2499
2546
  function addLanguageModelUsage(usage1, usage2) {
2547
+ const raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;
2500
2548
  return {
2501
2549
  inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),
2502
2550
  inputTokenDetails: {
@@ -2509,9 +2557,13 @@ function addLanguageModelUsage(usage1, usage2) {
2509
2557
  textTokens: addTokenCounts(usage1.outputTokenDetails?.textTokens, usage2.outputTokenDetails?.textTokens),
2510
2558
  reasoningTokens: addTokenCounts(usage1.outputTokenDetails?.reasoningTokens, usage2.outputTokenDetails?.reasoningTokens)
2511
2559
  },
2512
- totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)
2560
+ totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),
2561
+ ...raw == null ? {} : { raw }
2513
2562
  };
2514
2563
  }
2564
+ function isNullLanguageModelUsage(usage) {
2565
+ return usage.inputTokens == null && usage.inputTokenDetails?.noCacheTokens == null && usage.inputTokenDetails?.cacheReadTokens == null && usage.inputTokenDetails?.cacheWriteTokens == null && usage.outputTokens == null && usage.outputTokenDetails?.textTokens == null && usage.outputTokenDetails?.reasoningTokens == null && usage.totalTokens == null && usage.raw == null;
2566
+ }
2515
2567
  function addTokenCounts(tokenCount1, tokenCount2) {
2516
2568
  return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);
2517
2569
  }
@@ -9194,13 +9246,21 @@ var DefaultStreamTextResult = class {
9194
9246
  this.addStream = stitchableStream.addStream;
9195
9247
  this.closeStream = stitchableStream.close;
9196
9248
  const reader = stitchableStream.stream.getReader();
9249
+ const cancelOnAbort = () => {
9250
+ this.rejectResultPromises(abortSignal?.reason);
9251
+ reader.cancel(abortSignal?.reason).catch(() => {});
9252
+ };
9253
+ const removeAbortListener = () => abortSignal?.removeEventListener("abort", cancelOnAbort);
9197
9254
  let stream = new ReadableStream({
9198
9255
  async start(controller) {
9199
9256
  controller.enqueue({ type: "start" });
9257
+ abortSignal?.addEventListener("abort", cancelOnAbort, { once: true });
9258
+ if (abortSignal?.aborted) cancelOnAbort();
9200
9259
  },
9201
9260
  async pull(controller) {
9202
9261
  async function abort() {
9203
9262
  isAborted = true;
9263
+ removeAbortListener();
9204
9264
  await notify({
9205
9265
  event: {
9206
9266
  callId,
@@ -9217,16 +9277,18 @@ var DefaultStreamTextResult = class {
9217
9277
  }
9218
9278
  try {
9219
9279
  const { done, value } = await reader.read();
9220
- if (done) {
9221
- controller.close();
9222
- return;
9223
- }
9224
9280
  if (abortSignal?.aborted) {
9225
9281
  await abort();
9226
9282
  return;
9227
9283
  }
9284
+ if (done) {
9285
+ removeAbortListener();
9286
+ controller.close();
9287
+ return;
9288
+ }
9228
9289
  controller.enqueue(value);
9229
9290
  } catch (error) {
9291
+ removeAbortListener();
9230
9292
  if (isAbortError(error) && abortSignal?.aborted) await abort();
9231
9293
  else {
9232
9294
  await telemetryDispatcher.onError?.({
@@ -9238,7 +9300,8 @@ var DefaultStreamTextResult = class {
9238
9300
  }
9239
9301
  },
9240
9302
  cancel(reason) {
9241
- return stitchableStream.stream.cancel(reason);
9303
+ removeAbortListener();
9304
+ return reader.cancel(reason);
9242
9305
  }
9243
9306
  });
9244
9307
  let isRunning = true;
@@ -10574,6 +10637,15 @@ function readUIMessageStream({ message, stream, onError, terminateOnError = fals
10574
10637
  return createAsyncIterableStream(outputStream);
10575
10638
  }
10576
10639
  //#endregion
10640
+ //#region src/ui/unavailable-tool.ts
10641
+ function markToolPartAsUnavailable(part) {
10642
+ part.dynamic = false;
10643
+ return part;
10644
+ }
10645
+ function isToolPartFromUnavailableTool(part) {
10646
+ return part.type === "dynamic-tool" && part.dynamic === false;
10647
+ }
10648
+ //#endregion
10577
10649
  //#region src/ui/warn-if-ui-message-has-deprecated-raw-input.ts
10578
10650
  const rawInputDeprecationWarning = {
10579
10651
  type: "deprecated",
@@ -10604,6 +10676,20 @@ async function convertToModelMessages(messages, options) {
10604
10676
  ...message,
10605
10677
  parts: message.parts.filter((part) => !isToolUIPart(part) || (part.state !== "approval-requested" || messageIndex >= lastUserMessageIndex) && (!options?.ignoreIncompleteToolCalls || part.state === "approval-responded" || part.state === "output-available" && part.preliminary !== true || part.state === "output-error" || part.state === "output-denied"))
10606
10678
  }));
10679
+ async function createModelOutput({ toolPart, toolName, output, errorMode }) {
10680
+ const tool = getOwn(options?.tools, toolName);
10681
+ if (errorMode === "none" && tool == null && isToolPartFromUnavailableTool(toolPart)) return {
10682
+ type: "text",
10683
+ value: "Tool output omitted because the tool is no longer available."
10684
+ };
10685
+ return createToolModelOutput({
10686
+ toolCallId: toolPart.toolCallId,
10687
+ input: toolPart.input,
10688
+ output,
10689
+ tool,
10690
+ errorMode
10691
+ });
10692
+ }
10607
10693
  for (const message of messages) switch (message.role) {
10608
10694
  case "system": {
10609
10695
  const textParts = message.parts.filter((part) => part.type === "text");
@@ -10717,11 +10803,10 @@ async function convertToModelMessages(messages, options) {
10717
10803
  type: "tool-result",
10718
10804
  toolCallId: part.toolCallId,
10719
10805
  toolName,
10720
- output: await createToolModelOutput({
10721
- toolCallId: part.toolCallId,
10722
- input: part.input,
10806
+ output: await createModelOutput({
10807
+ toolPart: part,
10808
+ toolName,
10723
10809
  output: part.state === "output-error" ? part.errorText : part.output,
10724
- tool: getOwn(options?.tools, toolName),
10725
10810
  errorMode: part.state === "output-error" ? "json" : "none"
10726
10811
  }),
10727
10812
  ...resultProviderMetadata != null ? { providerOptions: resultProviderMetadata } : {}
@@ -10778,11 +10863,10 @@ async function convertToModelMessages(messages, options) {
10778
10863
  type: "tool-result",
10779
10864
  toolCallId: toolPart.toolCallId,
10780
10865
  toolName,
10781
- output: await createToolModelOutput({
10782
- toolCallId: toolPart.toolCallId,
10783
- input: toolPart.input,
10866
+ output: await createModelOutput({
10867
+ toolPart,
10868
+ toolName,
10784
10869
  output: toolPart.state === "output-error" ? toolPart.errorText : toolPart.output,
10785
- tool: getOwn(options?.tools, toolName),
10786
10870
  errorMode: toolPart.state === "output-error" ? "text" : "none"
10787
10871
  }),
10788
10872
  ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}
@@ -10823,11 +10907,11 @@ function isEmptyObject(value) {
10823
10907
  }
10824
10908
  function asDynamicToolPart(toolPart) {
10825
10909
  const { type, ...part } = toolPart;
10826
- return {
10910
+ return markToolPartAsUnavailable({
10827
10911
  ...part,
10828
10912
  type: "dynamic-tool",
10829
10913
  toolName: type.slice(5)
10830
- };
10914
+ });
10831
10915
  }
10832
10916
  function getToolPartInputSchemaInput(toolPart) {
10833
10917
  return toolPart.approval != null && Object.prototype.hasOwnProperty.call(toolPart.approval, "inputSchemaInput") ? { value: toolPart.approval.inputSchemaInput } : void 0;
@@ -10913,6 +10997,7 @@ const uiMessagesSchema = lazySchema(() => {
10913
10997
  }),
10914
10998
  z.object({
10915
10999
  type: z.literal("dynamic-tool"),
11000
+ dynamic: z.literal(false).optional(),
10916
11001
  toolName: z.string(),
10917
11002
  toolCallId: z.string(),
10918
11003
  title: z.string().optional(),
@@ -10928,6 +11013,7 @@ const uiMessagesSchema = lazySchema(() => {
10928
11013
  }),
10929
11014
  z.object({
10930
11015
  type: z.literal("dynamic-tool"),
11016
+ dynamic: z.literal(false).optional(),
10931
11017
  toolName: z.string(),
10932
11018
  toolCallId: z.string(),
10933
11019
  title: z.string().optional(),
@@ -10942,6 +11028,7 @@ const uiMessagesSchema = lazySchema(() => {
10942
11028
  }),
10943
11029
  z.object({
10944
11030
  type: z.literal("dynamic-tool"),
11031
+ dynamic: z.literal(false).optional(),
10945
11032
  toolName: z.string(),
10946
11033
  toolCallId: z.string(),
10947
11034
  title: z.string().optional(),
@@ -10956,6 +11043,7 @@ const uiMessagesSchema = lazySchema(() => {
10956
11043
  }),
10957
11044
  z.object({
10958
11045
  type: z.literal("dynamic-tool"),
11046
+ dynamic: z.literal(false).optional(),
10959
11047
  toolName: z.string(),
10960
11048
  toolCallId: z.string(),
10961
11049
  title: z.string().optional(),
@@ -10970,6 +11058,7 @@ const uiMessagesSchema = lazySchema(() => {
10970
11058
  }),
10971
11059
  z.object({
10972
11060
  type: z.literal("dynamic-tool"),
11061
+ dynamic: z.literal(false).optional(),
10973
11062
  toolName: z.string(),
10974
11063
  toolCallId: z.string(),
10975
11064
  title: z.string().optional(),
@@ -10986,6 +11075,7 @@ const uiMessagesSchema = lazySchema(() => {
10986
11075
  }),
10987
11076
  z.object({
10988
11077
  type: z.literal("dynamic-tool"),
11078
+ dynamic: z.literal(false).optional(),
10989
11079
  toolName: z.string(),
10990
11080
  toolCallId: z.string(),
10991
11081
  title: z.string().optional(),
@@ -11002,6 +11092,7 @@ const uiMessagesSchema = lazySchema(() => {
11002
11092
  }),
11003
11093
  z.object({
11004
11094
  type: z.literal("dynamic-tool"),
11095
+ dynamic: z.literal(false).optional(),
11005
11096
  toolName: z.string(),
11006
11097
  toolCallId: z.string(),
11007
11098
  title: z.string().optional(),
@@ -12678,6 +12769,7 @@ function validateDecisionAnswers({ questions, answers, rounding }) {
12678
12769
  if (!isRecord(answers) || !hasExactKeys(answers, Object.keys(questions))) invalidAnswer(answers, "Decision must return exactly one answer for every question.");
12679
12770
  for (const [id, question] of Object.entries(questions)) {
12680
12771
  const answer = answers[id];
12772
+ if (isRecord(answer) && answer.type === "refusal") continue;
12681
12773
  if (!isRecord(answer) || answer.type !== question.type) invalidAnswer(answers, `Question "${id}" returned an answer with the wrong type.`);
12682
12774
  switch (question.type) {
12683
12775
  case "choice":
@@ -12777,6 +12869,12 @@ async function decide({ model: modelArg, state, questions, maxRetries, abortSign
12777
12869
  answers: result.answers,
12778
12870
  rounding: result.rounding
12779
12871
  });
12872
+ const refusedQuestionIds = Object.keys(questions).filter((id) => result.answers[id]?.type === "refusal");
12873
+ if (refusedQuestionIds.length > 0) throw new Experimental_DecisionRefusalError$1({
12874
+ questionIds: refusedQuestionIds,
12875
+ provider: model.provider,
12876
+ modelId: model.modelId
12877
+ });
12780
12878
  await notify({
12781
12879
  event: {
12782
12880
  ...modelCallEvent,
@@ -13288,6 +13386,11 @@ const originalGenerateId$1 = createIdGenerator$1({
13288
13386
  * @deprecated Use `generateText` with an `output` setting instead.
13289
13387
  */
13290
13388
  async function generateObject(options) {
13389
+ logWarnings({ warnings: [{
13390
+ type: "deprecated",
13391
+ setting: "generateObject",
13392
+ message: "Use generateText with an output setting instead."
13393
+ }] });
13291
13394
  const { model: modelArg, output = "object", instructions, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, experimental_repairText, repairText = experimental_repairText, experimental_telemetry, telemetry = experimental_telemetry, experimental_download: download, providerOptions, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onStepEnd, onStepFinish, onFinish, _internal: { generateId = originalGenerateId$1, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings } = options;
13292
13395
  const model = resolveLanguageModel(modelArg);
13293
13396
  const enumValues = "enum" in options ? options.enum : void 0;
@@ -13693,6 +13796,11 @@ async function markPromiseAsHandled(promise) {
13693
13796
  * @deprecated Use `streamText` with an `output` setting instead.
13694
13797
  */
13695
13798
  function streamObject(options) {
13799
+ logWarnings({ warnings: [{
13800
+ type: "deprecated",
13801
+ setting: "streamObject",
13802
+ message: "Use streamText with an output setting instead."
13803
+ }] });
13696
13804
  const { model, output = "object", instructions, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, experimental_repairText, repairText = experimental_repairText, experimental_telemetry, telemetry = experimental_telemetry, experimental_download: download, providerOptions, onStart, experimental_onStart, onStepStart, experimental_onStepStart, onStepEnd, onStepFinish, onError = ({ error }) => {
13697
13805
  console.error(error);
13698
13806
  }, onFinish, _internal: { generateId = originalGenerateId, currentDate = () => /* @__PURE__ */ new Date(), now: now$1 = now } = {}, ...settings } = options;
@@ -14343,7 +14451,14 @@ var DefaultSpeechResult = class {
14343
14451
  /**
14344
14452
  * @deprecated Use `generateSpeech` instead.
14345
14453
  */
14346
- const experimental_generateSpeech = generateSpeech;
14454
+ const experimental_generateSpeech = (options) => {
14455
+ logWarnings({ warnings: [{
14456
+ type: "deprecated",
14457
+ setting: "experimental_generateSpeech",
14458
+ message: "Use generateSpeech instead."
14459
+ }] });
14460
+ return generateSpeech(options);
14461
+ };
14347
14462
  //#endregion
14348
14463
  //#region src/generate-text/prune-messages.ts
14349
14464
  /**
@@ -16136,7 +16251,11 @@ const REALTIME_MAX_FRAME_BYTES = 131072;
16136
16251
  const REALTIME_MAX_BUFFERED_BYTES = 131072;
16137
16252
  /** Serialize once, measuring the exact payload passed to the browser. */
16138
16253
  function encodeRealtimeFrame(value) {
16139
- if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) return {
16254
+ if (value instanceof ArrayBuffer) return {
16255
+ data: value,
16256
+ byteLength: value.byteLength
16257
+ };
16258
+ if (ArrayBuffer.isView(value)) return {
16140
16259
  data: value,
16141
16260
  byteLength: value.byteLength
16142
16261
  };
@@ -19051,7 +19170,14 @@ function getBase64ByteLength(value) {
19051
19170
  /**
19052
19171
  * @deprecated Use `transcribe` instead.
19053
19172
  */
19054
- const experimental_transcribe = transcribe;
19173
+ const experimental_transcribe = (options) => {
19174
+ logWarnings({ warnings: [{
19175
+ type: "deprecated",
19176
+ setting: "experimental_transcribe",
19177
+ message: "Use transcribe instead."
19178
+ }] });
19179
+ return transcribe(options);
19180
+ };
19055
19181
  //#endregion
19056
19182
  //#region src/translate/stream-translate.ts
19057
19183
  /**
@@ -19366,7 +19492,9 @@ async function convertFileListToFileUIParts(files) {
19366
19492
  //#region src/ui/http-chat-transport.ts
19367
19493
  function appendPathToUrl(url, path) {
19368
19494
  const queryOrFragmentStart = url.search(/[?#]/);
19369
- return queryOrFragmentStart === -1 ? `${url}${path}` : `${url.slice(0, queryOrFragmentStart)}${path}${url.slice(queryOrFragmentStart)}`;
19495
+ const urlPath = queryOrFragmentStart === -1 ? url : url.slice(0, queryOrFragmentStart);
19496
+ const suffix = queryOrFragmentStart === -1 ? "" : url.slice(queryOrFragmentStart);
19497
+ return `${urlPath.endsWith("/") && path.startsWith("/") ? urlPath.slice(0, -1) : urlPath}${path}${suffix}`;
19370
19498
  }
19371
19499
  var HttpChatTransport = class {
19372
19500
  constructor({ api = "/api/chat", credentials, headers, body, fetch, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {
@@ -19696,7 +19824,10 @@ var AbstractChat = class {
19696
19824
  return this.state.status;
19697
19825
  }
19698
19826
  setStatus({ status, error }) {
19699
- if (this.status === status) return;
19827
+ if (this.status === status) {
19828
+ if (this.error !== error) this.state.error = error;
19829
+ return;
19830
+ }
19700
19831
  this.state.status = status;
19701
19832
  this.state.error = error;
19702
19833
  }
@@ -19874,7 +20005,10 @@ var AbstractChat = class {
19874
20005
  }
19875
20006
  if (!isCurrentRequest()) return null;
19876
20007
  isError = true;
19877
- if (err instanceof TypeError && (err.message.toLowerCase().includes("fetch") || err.message.toLowerCase().includes("network"))) isDisconnect = true;
20008
+ if (err instanceof TypeError) {
20009
+ const message = err.message.toLowerCase();
20010
+ isDisconnect = message.includes("fetch") || message.includes("network") || message === "load failed";
20011
+ }
19878
20012
  if (isDisconnect) this.resumableStreamState = activeResponse?.state;
19879
20013
  else if (this.resumableStreamState === activeResponse?.state) this.resumableStreamState = void 0;
19880
20014
  if (this.onError && err instanceof Error) this.onError(err);
@@ -20138,6 +20272,6 @@ async function uploadSkill({ api, files, displayTitle, providerOptions }) {
20138
20272
  });
20139
20273
  }
20140
20274
  //#endregion
20141
- export { AISDKError, AI_SDK_TELEMETRY_TRACING_CHANNEL, APICallError, AbstractChat, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DownloadError, EmptyResponseBodyError, AbstractRealtimeSession as Experimental_AbstractRealtimeSession, ToolLoopAgent as Experimental_Agent, ToolLoopAgent, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_EvaluationUnsupportedQuestionTypeError, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolApprovalSignatureError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, MissingToolResultsError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchProviderReferenceError, NoSuchToolError, NoTranscriptGeneratedError, NoTranslationGeneratedError, NoVideoGeneratedError, output_exports as Output, RetryError, SerialJobExecutor, StreamProviderError, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolChoiceViolationError, TypeValidationError, UIMessageStreamError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, addToolInputExamplesMiddleware, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertDataContentToBase64String, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultInstructionsMiddleware, defaultSettingsMiddleware, detectToolDrift, dynamicTool, embed, embedMany, cancelBatch as experimental_cancelBatch, experimental_createProviderRegistry, decide as experimental_decide, decodeRealtimeAudio as experimental_decodeRealtimeAudio, encodeRealtimeAudio as experimental_encodeRealtimeAudio, experimental_evaluate, filterActiveTools as experimental_filterActiveTools, experimental_generateSpeech, experimental_generateVideo, getBatchResults as experimental_getBatchResults, getBatchStatus as experimental_getBatchStatus, getRealtimeToolDefinitions as experimental_getRealtimeToolDefinitions, experimental_getVideoStatus, listBatches as experimental_listBatches, resampleAudio as experimental_resampleAudio, startBatch as experimental_startBatch, experimental_startVideo, streamLanguageModelCall as experimental_streamLanguageModelCall, streamTranscribe as experimental_streamTranscribe, streamTranslate as experimental_streamTranslate, experimental_toolCaller, experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, fingerprintTools, gateway, generateId, generateImage, generateObject, generateSpeech, generateText, getChunkTimeoutMs, getFirstChunkTimeoutMs, getStaticToolName, getStepTimeoutMs, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, getToolTimeoutMs, getTotalTimeoutMs, hasToolCall, isCustomContentUIPart, isDataUIPart, isDeepEqualData, isDynamicToolUIPart, isFileUIPart, isLoopFinished, isReasoningFileUIPart, isReasoningUIPart, isStaticToolUIPart, isStepCount, isStepCount as stepCountIs, isTextUIPart, isToolOutputErrorUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, registerTelemetry, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, toTextStream, toUIMessageChunk, toUIMessageStream, tool, toolModelMessageSchema, toolSearch, transcribe, uiMessageChunkSchema, uploadFile, uploadSkill, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider, zodSchema };
20275
+ export { AISDKError, AI_SDK_TELEMETRY_TRACING_CHANNEL, APICallError, AbstractChat, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DownloadError, EmptyResponseBodyError, AbstractRealtimeSession as Experimental_AbstractRealtimeSession, ToolLoopAgent as Experimental_Agent, ToolLoopAgent, Experimental_DecisionRefusalError, Experimental_DecisionUnsupportedQuestionTypeError, Experimental_EvaluationUnsupportedQuestionTypeError, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolApprovalSignatureError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, MissingToolResultsError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchProviderReferenceError, NoSuchToolError, NoTranscriptGeneratedError, NoTranslationGeneratedError, NoVideoGeneratedError, output_exports as Output, RetryError, SerialJobExecutor, StreamProviderError, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolChoiceViolationError, TypeValidationError, UIMessageStreamError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, addToolInputExamplesMiddleware, asSchema, assistantModelMessageSchema, callCompletionApi, consumeStream, convertDataContentToBase64String, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultInstructionsMiddleware, defaultSettingsMiddleware, detectToolDrift, dynamicTool, embed, embedMany, cancelBatch as experimental_cancelBatch, experimental_createProviderRegistry, decide as experimental_decide, decodeRealtimeAudio as experimental_decodeRealtimeAudio, encodeRealtimeAudio as experimental_encodeRealtimeAudio, experimental_evaluate, filterActiveTools as experimental_filterActiveTools, experimental_generateSpeech, experimental_generateVideo, getBatchResults as experimental_getBatchResults, getBatchStatus as experimental_getBatchStatus, getRealtimeToolDefinitions as experimental_getRealtimeToolDefinitions, experimental_getVideoStatus, listBatches as experimental_listBatches, resampleAudio as experimental_resampleAudio, startBatch as experimental_startBatch, experimental_startVideo, streamLanguageModelCall as experimental_streamLanguageModelCall, streamTranscribe as experimental_streamTranscribe, streamTranslate as experimental_streamTranslate, experimental_toolCaller, experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, fingerprintTools, gateway, generateId, generateImage, generateObject, generateSpeech, generateText, getChunkTimeoutMs, getFirstChunkTimeoutMs, getStaticToolName, getStepTimeoutMs, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, getToolTimeoutMs, getTotalTimeoutMs, hasToolCall, isCustomContentUIPart, isDataUIPart, isDeepEqualData, isDynamicToolUIPart, isFileUIPart, isLoopFinished, isReasoningFileUIPart, isReasoningUIPart, isStaticToolUIPart, isStepCount, isStepCount as stepCountIs, isTextUIPart, isToolOutputErrorUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, registerTelemetry, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, streamObject, streamText, systemModelMessageSchema, toTextStream, toUIMessageChunk, toUIMessageStream, tool, toolModelMessageSchema, toolSearch, transcribe, uiMessageChunkSchema, uploadFile, uploadSkill, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider, zodSchema };
20142
20276
 
20143
20277
  //# sourceMappingURL=index.js.map