ai 6.0.329 → 6.0.331

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.
@@ -164,7 +164,7 @@ function detectMediaType({
164
164
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
165
165
 
166
166
  // src/version.ts
167
- var VERSION = true ? "6.0.329" : "0.0.0-test";
167
+ var VERSION = true ? "6.0.331" : "0.0.0-test";
168
168
 
169
169
  // src/util/download/download.ts
170
170
  var download = async ({
@@ -144,7 +144,7 @@ import {
144
144
  } from "@ai-sdk/provider-utils";
145
145
 
146
146
  // src/version.ts
147
- var VERSION = true ? "6.0.329" : "0.0.0-test";
147
+ var VERSION = true ? "6.0.331" : "0.0.0-test";
148
148
 
149
149
  // src/util/download/download.ts
150
150
  var download = async ({
@@ -155,6 +155,7 @@ Here are the capabilities of popular models:
155
155
  | [Anthropic](/providers/ai-sdk-providers/anthropic) | `claude-opus-4-0` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
156
156
  | [Anthropic](/providers/ai-sdk-providers/anthropic) | `claude-sonnet-4-0` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
157
157
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-4-carbon` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
158
+ | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-4-hydrogen` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
158
159
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3.8-flash` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
159
160
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3.1-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
160
161
  | [Google Generative AI](/providers/ai-sdk-providers/google-generative-ai) | `gemini-3-pro-preview` | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> | <Check size={18} /> |
@@ -726,16 +726,15 @@ With `streamText`, you can control how error messages and usage information are
726
726
 
727
727
  ### Error Messages
728
728
 
729
- By default, the error message is masked for security reasons.
730
- The default error message is "An error occurred."
731
-
732
- Tool execution errors marked `providerExecuted: true` are an exception. They
733
- bypass the UI stream's `onError` callback: strings are forwarded unchanged, and
734
- other error values are serialized with `JSON.stringify`. This preserves provider
735
- error codes when chat history is converted back into model messages. Stream
736
- errors and invalid tool calls still use `onError`, even for provider-executed
737
- tools. Do not rely on this callback to redact provider-executed tool execution
738
- errors before they reach the client.
729
+ Stream errors are masked by default. The default message is "An error occurred."
730
+
731
+ Failed tool calls keep the error text that the model received, so stored UI
732
+ messages preserve the history sent back on later requests. A custom `onError`
733
+ also handles failed tool calls by default and may replace that text. Set
734
+ `redactToolErrors: false` when your callback should handle stream errors only.
735
+ Tool execution errors marked `providerExecuted: true` always bypass `onError`.
736
+ See [Errors](/docs/ai-sdk-ui/chatbot-tool-usage#errors) for safe tool errors
737
+ and redaction details.
739
738
 
740
739
  You can forward error messages or send your own error message by providing an `onError` function:
741
740
 
@@ -687,37 +687,51 @@ export async function POST(req: Request) {
687
687
 
688
688
  ## Errors
689
689
 
690
- Language models can make errors when calling tools.
691
- By default, these errors are masked for security reasons, and show up as "An error occurred" in the UI.
692
-
693
- Tool execution errors marked `providerExecuted: true` bypass this masking and the
694
- UI stream's `onError` callback. String errors pass through unchanged; other error
695
- values are serialized with `JSON.stringify`. The original error data is needed
696
- when converting persisted UI messages back into model messages, for example to
697
- preserve Anthropic tool error codes. The callback still handles invalid tool
698
- calls and stream errors, regardless of whether a tool is provider-executed.
699
-
700
- To customize masked errors, pass `onError` to `result.toUIMessageStream()` or
701
- `result.toUIMessageStreamResponse()`. This callback does not redact
702
- provider-executed tool execution errors sent to the client.
690
+ Language models can make invalid tool calls, and tools can fail while they run.
691
+
692
+ By default, failed tool-call errors are sent to the client with the same text
693
+ that `streamText` uses for the model's tool result. During a multi-step call,
694
+ the model receives that text too. Preserving it in UI messages keeps the
695
+ history consistent on later requests.
696
+
697
+ <Note type="warning">
698
+ Tool errors can contain server details such as host names, file paths, or
699
+ credentials. A tool call can also end the model request: the client may receive
700
+ the error before the model has received it in a later step. To keep details
701
+ away from the model and the client, catch the error in the tool's
702
+ `execute` function and throw an error with a safe message.
703
+ </Note>
703
704
 
704
705
  ```tsx
705
- export function errorHandler(error: unknown) {
706
- if (error == null) {
707
- return 'unknown error';
708
- }
706
+ const weatherTool = tool({
707
+ description: 'Get the weather in a location',
708
+ inputSchema: z.object({ location: z.string() }),
709
+ execute: async ({ location }) => {
710
+ try {
711
+ return await getWeather(location);
712
+ } catch (error) {
713
+ console.error(error);
714
+ throw new Error('The weather service is unavailable.');
715
+ }
716
+ },
717
+ });
718
+ ```
709
719
 
710
- if (typeof error === 'string') {
711
- return error;
712
- }
720
+ The `execute` function does not run for an invalid tool call. Its validation
721
+ error may include the input generated by the model or details from the input
722
+ schema. Set `redactToolErrors: true` to replace this text before it reaches
723
+ the client.
713
724
 
714
- if (error instanceof Error) {
715
- return error.message;
716
- }
725
+ Tool execution errors marked `providerExecuted: true` are always sent
726
+ unchanged. String errors pass through; other values are serialized with
727
+ `JSON.stringify` to preserve provider error data. Invalid tool calls of
728
+ provider-executed tools use `onError`.
717
729
 
718
- return JSON.stringify(error);
719
- }
720
- ```
730
+ ### Redacting tool errors
731
+
732
+ Set `redactToolErrors: true` to replace failed tool-call errors with the result
733
+ of `onError`. When no callback is provided, the replacement is
734
+ "An error occurred."
721
735
 
722
736
  ```tsx
723
737
  const result = streamText({
@@ -725,18 +739,41 @@ const result = streamText({
725
739
  });
726
740
 
727
741
  return result.toUIMessageStreamResponse({
728
- onError: errorHandler,
742
+ redactToolErrors: true,
729
743
  });
730
744
  ```
731
745
 
732
- In case you are using `createUIMessageResponse`, you can use the `onError` function when calling `toUIMessageResponse`:
746
+ When you provide a custom `onError`, it handles failed tool calls by default.
747
+ Set `redactToolErrors: false` to use it for stream errors only. Provider-
748
+ executed tool execution errors are never redacted.
749
+
750
+ Redacting a failed tool-call error changes the history sent to the model on a
751
+ later request. Models that bind reasoning to earlier messages can reject that
752
+ history. To avoid this, set `sendReasoning: false`. For Anthropic's temporary
753
+ recovery option, see [Changing tools or instructions](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking/change-tools-or-instructions).
754
+
755
+ ### Tool error text and message history
756
+
757
+ During a server-side multi-step call, the model receives the full error text
758
+ before it continues. If you redact that text for the UI, converting the stored
759
+ messages with `convertToModelMessages` changes the tool result in the next
760
+ request. Models that bind reasoning to earlier messages can reject the changed
761
+ history. With Anthropic adaptive thinking, `thinking.blockBinding.prefixMismatchBehavior`
762
+ can be set to `drop_block` to drop reasoning that no longer matches. A call
763
+ that ends after the failed tool may send the error text to the client before
764
+ the model has received it.
765
+
766
+ ### Stream errors
767
+
768
+ Errors from the model provider are masked by default and appear as
769
+ "An error occurred." in the UI. Customize them with `onError`:
733
770
 
734
771
  ```tsx
735
- const response = createUIMessageResponse({
736
- // ...
737
- async execute(dataStream) {
738
- // ...
772
+ return result.toUIMessageStreamResponse({
773
+ onError: error => {
774
+ console.error(error);
775
+ return 'The request failed.';
739
776
  },
740
- onError: error => `Custom error: ${error.message}`,
777
+ redactToolErrors: false,
741
778
  });
742
779
  ```
@@ -3571,7 +3571,14 @@ To see `streamText` in action, check out [these examples](#examples).
3571
3571
  type: '(error: unknown) => string',
3572
3572
  isOptional: true,
3573
3573
  description:
3574
- 'Process an error, e.g. to log it. Returns the error message to include in the data stream. Defaults to () => "An error occurred." Tool execution errors marked providerExecuted: true bypass this callback: strings pass through unchanged and other values are JSON-stringified to preserve provider error data for model-message round trips. Stream errors and invalid tool calls still use this callback.',
3574
+ 'Process stream errors. Also handles failed tool calls when redactToolErrors is enabled, which defaults to true when onError is provided. Provider-executed tool execution errors bypass this callback; invalid tool calls of provider-executed tools still use it.',
3575
+ },
3576
+ {
3577
+ name: 'redactToolErrors',
3578
+ type: 'boolean',
3579
+ isOptional: true,
3580
+ description:
3581
+ 'Replace failed tool-call error text with the result of onError. Defaults to true when onError is provided, and false otherwise.',
3575
3582
  },
3576
3583
  {
3577
3584
  name: 'consumeSseStream',
@@ -7,6 +7,15 @@ description: API Reference for pruneMessages.
7
7
 
8
8
  The `pruneMessages` function is used to prune or filter an array of `ModelMessage` objects. This is useful for reducing message context (to save tokens), removing intermediate reasoning, or trimming tool calls and empty messages before sending to an LLM.
9
9
 
10
+ <Note>
11
+ OpenAI Responses models may drop reasoning items after edits to their
12
+ preceding context. Pruning earlier history can therefore increase reasoning
13
+ work. Also preserve empty system messages carrying positioned configuration
14
+ updates; `emptyMessages: 'remove'` removes them. See [preserving reasoning
15
+ across
16
+ turns](/providers/ai-sdk-providers/openai#preserving-reasoning-across-turns).
17
+ </Note>
18
+
10
19
  ```ts filename="app/api/chat/route.ts"
11
20
  import { pruneMessages, streamText } from 'ai';
12
21
  __PROVIDER_IMPORT__;
@@ -14,6 +14,8 @@ I am using [`useChat`](/docs/reference/ai-sdk-ui/use-chat) and I get the error "
14
14
  Error messages from `streamText` are masked by default when using `toDataStreamResponse` for security reasons (secure-by-default).
15
15
  This prevents leaking sensitive information to the client.
16
16
 
17
+ Failed tool calls keep the error text the model received by default. A custom `onError` also handles failed tool calls; set `redactToolErrors: false` to handle stream errors only. See [tool error handling](/docs/ai-sdk-ui/chatbot-tool-usage#errors).
18
+
17
19
  ## Solution
18
20
 
19
21
  To forward error details to the client or to log errors, use the `getErrorMessage` function when calling `toDataStreamResponse`.
@@ -42,7 +44,7 @@ const result = streamText({
42
44
  });
43
45
 
44
46
  return result.toUIMessageStreamResponse({
45
- getErrorMessage: errorHandler,
47
+ onError: errorHandler,
46
48
  });
47
49
  ```
48
50
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "6.0.329",
3
+ "version": "6.0.331",
4
4
  "description": "AI SDK by Vercel - build apps like ChatGPT, Claude, Gemini, and more with a single interface for any model using the Vercel AI Gateway or go direct to OpenAI, Anthropic, Google, or any other model provider.",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@opentelemetry/api": "^1.9.0",
48
- "@ai-sdk/gateway": "3.0.235",
48
+ "@ai-sdk/gateway": "3.0.236",
49
49
  "@ai-sdk/provider": "3.0.19",
50
50
  "@ai-sdk/provider-utils": "4.0.66"
51
51
  },
@@ -58,7 +58,8 @@
58
58
  "tsx": "^4.19.2",
59
59
  "typescript": "5.8.3",
60
60
  "zod": "3.25.76",
61
- "@ai-sdk/google": "3.0.145",
61
+ "@ai-sdk/google": "3.0.146",
62
+ "@ai-sdk/openai": "3.0.142",
62
63
  "@ai-sdk/perplexity": "3.1.12",
63
64
  "@ai-sdk/test-server": "1.0.6",
64
65
  "@vercel/ai-tsconfig": "0.0.0"
@@ -24,6 +24,10 @@ import {
24
24
  createAsyncIterableStream,
25
25
  type AsyncIterableStream,
26
26
  } from '../util/async-iterable-stream';
27
+ import {
28
+ createArrayOutputStreamParser,
29
+ type ArrayOutputStreamParser,
30
+ } from '../util/array-output-stream';
27
31
  import type { DeepPartial } from '../util/deep-partial';
28
32
  import type { ObjectStreamPart } from './stream-object-result';
29
33
 
@@ -32,6 +36,8 @@ export interface OutputStrategy<PARTIAL, RESULT, ELEMENT_STREAM> {
32
36
 
33
37
  jsonSchema(): Promise<JSONSchema7 | undefined>;
34
38
 
39
+ createArrayStreamParser?(): ArrayOutputStreamParser<any>;
40
+
35
41
  validatePartialResult({
36
42
  value,
37
43
  textDelta,
@@ -136,6 +142,8 @@ const arrayOutputStrategy = <ELEMENT>(
136
142
  return {
137
143
  type: 'array',
138
144
 
145
+ createArrayStreamParser: () => createArrayOutputStreamParser(schema, false),
146
+
139
147
  // wrap in object that contains array of elements, since most LLMs will not
140
148
  // be able to generate an array directly:
141
149
  // possible future optimization: use arrays directly when model supports grammar-guided generation
@@ -600,6 +600,7 @@ class DefaultStreamObjectResult<
600
600
  let terminalError: { error: unknown } | undefined;
601
601
 
602
602
  // pipe chunks through a transformation stream that extracts metadata:
603
+ let arrayStreamParser = outputStrategy.createArrayStreamParser?.();
603
604
  let accumulatedText = '';
604
605
  let textDelta = '';
605
606
  let fullResponse: {
@@ -655,6 +656,27 @@ class DefaultStreamObjectResult<
655
656
  accumulatedText += chunk;
656
657
  textDelta += chunk;
657
658
 
659
+ if (arrayStreamParser != null) {
660
+ const result = await arrayStreamParser(chunk);
661
+ if (result !== 'fallback') {
662
+ if (result != null) {
663
+ latestObject = result.partial as PARTIAL;
664
+ controller.enqueue({
665
+ type: 'object',
666
+ object: latestObject,
667
+ });
668
+ controller.enqueue({
669
+ type: 'text-delta',
670
+ textDelta: result.textDelta,
671
+ });
672
+ textDelta = '';
673
+ isFirstDelta = false;
674
+ }
675
+ return;
676
+ }
677
+ arrayStreamParser = undefined;
678
+ }
679
+
658
680
  const { value: currentObjectJson, state: parseState } =
659
681
  await parsePartialJson(accumulatedText);
660
682
 
@@ -14,6 +14,10 @@ import { NoObjectGeneratedError } from '../error/no-object-generated-error';
14
14
  import type { FinishReason } from '../types/language-model';
15
15
  import type { LanguageModelResponseMetadata } from '../types/language-model-response-metadata';
16
16
  import type { LanguageModelUsage } from '../types/usage';
17
+ import {
18
+ createArrayOutputStreamParser,
19
+ arrayStreamParserFactories,
20
+ } from '../util/array-output-stream';
17
21
  import type { DeepPartial } from '../util/deep-partial';
18
22
  import { parsePartialJson } from '../util/parse-partial-json';
19
23
  import type { EnrichedStreamPart } from './stream-text';
@@ -130,12 +134,10 @@ export const object = <OBJECT>({
130
134
 
131
135
  if (!parseResult.success) {
132
136
  throw new NoObjectGeneratedError({
137
+ ...context,
133
138
  message: 'No object generated: could not parse the response.',
134
139
  cause: parseResult.error,
135
140
  text,
136
- response: context.response,
137
- usage: context.usage,
138
- finishReason: context.finishReason,
139
141
  });
140
142
  }
141
143
 
@@ -146,12 +148,10 @@ export const object = <OBJECT>({
146
148
 
147
149
  if (!validationResult.success) {
148
150
  throw new NoObjectGeneratedError({
151
+ ...context,
149
152
  message: 'No object generated: response did not match schema.',
150
153
  cause: validationResult.error,
151
154
  text,
152
- response: context.response,
153
- usage: context.usage,
154
- finishReason: context.finishReason,
155
155
  });
156
156
  }
157
157
 
@@ -212,7 +212,7 @@ export const array = <ELEMENT>({
212
212
  }): Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> => {
213
213
  const elementSchema = asSchema(inputElementSchema);
214
214
 
215
- return {
215
+ const output: Output<Array<ELEMENT>, Array<ELEMENT>, ELEMENT> = {
216
216
  name: 'array',
217
217
 
218
218
  // JSON schema that describes an array of elements:
@@ -248,12 +248,10 @@ export const array = <ELEMENT>({
248
248
 
249
249
  if (!parseResult.success) {
250
250
  throw new NoObjectGeneratedError({
251
+ ...context,
251
252
  message: 'No object generated: could not parse the response.',
252
253
  cause: parseResult.error,
253
254
  text,
254
- response: context.response,
255
- usage: context.usage,
256
- finishReason: context.finishReason,
257
255
  });
258
256
  }
259
257
 
@@ -266,15 +264,13 @@ export const array = <ELEMENT>({
266
264
  !Array.isArray(outerValue.elements)
267
265
  ) {
268
266
  throw new NoObjectGeneratedError({
267
+ ...context,
269
268
  message: 'No object generated: response did not match schema.',
270
269
  cause: new TypeValidationError({
271
270
  value: outerValue,
272
271
  cause: 'response must be an object with an elements array',
273
272
  }),
274
273
  text,
275
- response: context.response,
276
- usage: context.usage,
277
- finishReason: context.finishReason,
278
274
  });
279
275
  }
280
276
 
@@ -287,12 +283,10 @@ export const array = <ELEMENT>({
287
283
 
288
284
  if (!validationResult.success) {
289
285
  throw new NoObjectGeneratedError({
286
+ ...context,
290
287
  message: 'No object generated: response did not match schema.',
291
288
  cause: validationResult.error,
292
289
  text,
293
- response: context.response,
294
- usage: context.usage,
295
- finishReason: context.finishReason,
296
290
  });
297
291
  }
298
292
 
@@ -369,6 +363,14 @@ export const array = <ELEMENT>({
369
363
  });
370
364
  },
371
365
  };
366
+
367
+ const parsePartialOutput = output.parsePartialOutput;
368
+ arrayStreamParserFactories.set(output, () =>
369
+ output.parsePartialOutput === parsePartialOutput
370
+ ? createArrayOutputStreamParser(elementSchema, true)
371
+ : undefined,
372
+ );
373
+ return output;
372
374
  };
373
375
 
374
376
  /**
@@ -429,12 +431,10 @@ export const choice = <CHOICE extends string>({
429
431
 
430
432
  if (!parseResult.success) {
431
433
  throw new NoObjectGeneratedError({
434
+ ...context,
432
435
  message: 'No object generated: could not parse the response.',
433
436
  cause: parseResult.error,
434
437
  text,
435
- response: context.response,
436
- usage: context.usage,
437
- finishReason: context.finishReason,
438
438
  });
439
439
  }
440
440
 
@@ -448,15 +448,13 @@ export const choice = <CHOICE extends string>({
448
448
  !choiceOptions.includes(outerValue.result as any)
449
449
  ) {
450
450
  throw new NoObjectGeneratedError({
451
+ ...context,
451
452
  message: 'No object generated: response did not match schema.',
452
453
  cause: new TypeValidationError({
453
454
  value: outerValue,
454
455
  cause: 'response must be an object that contains a choice value.',
455
456
  }),
456
457
  text,
457
- response: context.response,
458
- usage: context.usage,
459
- finishReason: context.finishReason,
460
458
  });
461
459
  }
462
460
 
@@ -556,12 +554,10 @@ export const json = ({
556
554
 
557
555
  if (!parseResult.success) {
558
556
  throw new NoObjectGeneratedError({
557
+ ...context,
559
558
  message: 'No object generated: could not parse the response.',
560
559
  cause: parseResult.error,
561
560
  text,
562
- response: context.response,
563
- usage: context.usage,
564
- finishReason: context.finishReason,
565
561
  });
566
562
  }
567
563
 
@@ -99,14 +99,33 @@ export type UIMessageStreamOptions<UI_MESSAGE extends UIMessage> = {
99
99
  /**
100
100
  * Process an error, e.g. to log it. Default to `() => 'An error occurred.'`.
101
101
  *
102
+ * This callback handles stream errors. It also handles failed tool calls
103
+ * (tool execution errors and invalid tool calls) when `redactToolErrors` is
104
+ * enabled, which is the default when this callback is provided.
105
+ *
102
106
  * Tool execution errors marked `providerExecuted: true` bypass this callback.
103
107
  * Their strings pass through unchanged; other values are JSON-stringified to
104
- * preserve provider error data for model-message round trips. Stream errors
105
- * and invalid tool calls still use it.
108
+ * preserve provider error data for model-message round trips. Invalid tool
109
+ * calls of provider-executed tools always use it.
106
110
  *
107
111
  * @returns error message to include in the data stream.
108
112
  */
109
113
  onError?: (error: unknown) => string;
114
+
115
+ /**
116
+ * Replace the error text of failed tool calls (tool execution errors and
117
+ * invalid tool calls) with the result of `onError`.
118
+ *
119
+ * By default, the client receives the same error text as the model. UI
120
+ * messages are sent back to the model on the next request, so a different
121
+ * text changes the history that the model's reasoning and answers are based
122
+ * on. Some models reject such a history, for example Anthropic models with
123
+ * preserved thinking. To keep error details away from the client, throw a
124
+ * safe error from the tool's `execute` function.
125
+ *
126
+ * Defaults to `true` when `onError` is provided, and `false` otherwise.
127
+ */
128
+ redactToolErrors?: boolean;
110
129
  };
111
130
 
112
131
  export type ConsumeStreamOptions = {
@@ -100,6 +100,7 @@ import type { ContentPart } from './content-part';
100
100
  import { executeToolCall } from './execute-tool-call';
101
101
  import { filterActiveTools } from './filter-active-tools';
102
102
  import { text, type Output } from './output';
103
+ import { createArrayStreamParser } from '../util/array-output-stream';
103
104
  import type {
104
105
  InferCompleteOutput,
105
106
  InferElementOutput,
@@ -667,10 +668,14 @@ function createOutputTransformStream<
667
668
  let text = '';
668
669
  let textChunk = '';
669
670
  let textProviderMetadata: ProviderMetadata | undefined = undefined;
671
+ let arrayStreamParser = createArrayStreamParser(output);
672
+ let lastArrayPartial: InferPartialOutput<OUTPUT> | undefined;
670
673
  let lastPublishedValue: string | undefined = undefined;
671
674
  let hasPublishedValue = false;
672
675
 
673
676
  function resetOutputState() {
677
+ arrayStreamParser = createArrayStreamParser(output);
678
+ lastArrayPartial = undefined;
674
679
  firstTextChunkId = undefined;
675
680
  text = '';
676
681
  textChunk = '';
@@ -753,6 +758,24 @@ function createOutputTransformStream<
753
758
  return;
754
759
  }
755
760
 
761
+ // Built-in arrays publish only changed snapshots, so growing arrays do
762
+ // not need to be reparsed, revalidated, or stringified on every chunk.
763
+ if (arrayStreamParser != null) {
764
+ const result = await arrayStreamParser(chunk.text);
765
+ if (result !== 'fallback') {
766
+ if (result != null) {
767
+ lastArrayPartial = result.partial as InferPartialOutput<OUTPUT>;
768
+ publishTextChunk({ controller, partialOutput: lastArrayPartial });
769
+ }
770
+ return;
771
+ }
772
+ arrayStreamParser = undefined;
773
+ if (lastArrayPartial != null) {
774
+ lastPublishedValue = JSON.stringify(lastArrayPartial);
775
+ hasPublishedValue = true;
776
+ }
777
+ }
778
+
756
779
  // only publish if partial json can be parsed:
757
780
  const result = await output.parsePartialOutput({ text });
758
781
 
@@ -2718,10 +2741,26 @@ class DefaultStreamTextResult<
2718
2741
  sendSources = false,
2719
2742
  sendStart = true,
2720
2743
  sendFinish = true,
2721
- onError = () => 'An error occurred.', // masks errors except provider-executed tool execution errors
2744
+ onError: onErrorOption,
2745
+ redactToolErrors = onErrorOption != null,
2722
2746
  }: UIMessageStreamOptions<UI_MESSAGE> = {}): AsyncIterableStream<
2723
2747
  InferUIMessageChunk<UI_MESSAGE>
2724
2748
  > {
2749
+ const onError = onErrorOption ?? (() => 'An error occurred.');
2750
+ // UI messages become the next request's history, so keep this text aligned
2751
+ // with what the model received unless the application opts into redaction.
2752
+ const getToolErrorText = (error: unknown) => {
2753
+ if (redactToolErrors) {
2754
+ return onError(error);
2755
+ }
2756
+
2757
+ try {
2758
+ return getErrorMessage(error) ?? onError(error);
2759
+ } catch {
2760
+ return onError(error);
2761
+ }
2762
+ };
2763
+
2725
2764
  let outcome: UIMessageStreamOutcome = { status: 'unknown' };
2726
2765
  let hasFatalFailure = false;
2727
2766
 
@@ -2981,7 +3020,9 @@ class DefaultStreamTextResult<
2981
3020
  ? { toolMetadata: part.toolMetadata }
2982
3021
  : {}),
2983
3022
  ...(dynamic != null ? { dynamic } : {}),
2984
- errorText: onError(part.error),
3023
+ errorText: part.providerExecuted
3024
+ ? onError(part.error)
3025
+ : getToolErrorText(part.error),
2985
3026
  ...(part.title != null ? { title: part.title } : {}),
2986
3027
  });
2987
3028
  } else {
@@ -3065,7 +3106,7 @@ class DefaultStreamTextResult<
3065
3106
  ? typeof part.error === 'string'
3066
3107
  ? part.error
3067
3108
  : JSON.stringify(part.error)
3068
- : onError(part.error),
3109
+ : getToolErrorText(part.error),
3069
3110
  ...(part.providerExecuted != null
3070
3111
  ? { providerExecuted: part.providerExecuted }
3071
3112
  : {}),
@@ -3205,6 +3246,7 @@ class DefaultStreamTextResult<
3205
3246
  sendFinish,
3206
3247
  sendStart,
3207
3248
  onError,
3249
+ redactToolErrors,
3208
3250
  ...init
3209
3251
  }: UIMessageStreamResponseInit & UIMessageStreamOptions<UI_MESSAGE> = {},
3210
3252
  ) {
@@ -3220,6 +3262,7 @@ class DefaultStreamTextResult<
3220
3262
  sendFinish,
3221
3263
  sendStart,
3222
3264
  onError,
3265
+ redactToolErrors,
3223
3266
  }),
3224
3267
  ...init,
3225
3268
  });
@@ -3243,6 +3286,7 @@ class DefaultStreamTextResult<
3243
3286
  sendFinish,
3244
3287
  sendStart,
3245
3288
  onError,
3289
+ redactToolErrors,
3246
3290
  ...init
3247
3291
  }: UIMessageStreamResponseInit &
3248
3292
  UIMessageStreamOptions<UI_MESSAGE> = {}): Response {
@@ -3257,6 +3301,7 @@ class DefaultStreamTextResult<
3257
3301
  sendFinish,
3258
3302
  sendStart,
3259
3303
  onError,
3304
+ redactToolErrors,
3260
3305
  }),
3261
3306
  ...init,
3262
3307
  });