ai 7.0.171 → 7.0.173

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 (34) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/index.d.ts +40 -30
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +54 -27
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +153 -55
  7. package/dist/internal/index.d.ts.map +1 -1
  8. package/dist/internal/index.js +53 -16
  9. package/dist/internal/index.js.map +1 -1
  10. package/docs/02-foundations/03-prompts.mdx +1 -1
  11. package/docs/03-agents/04-loop-control.mdx +1 -1
  12. package/docs/03-agents/06-tool-approvals.mdx +1 -1
  13. package/docs/03-agents/07-workflow-agent.mdx +187 -14
  14. package/docs/03-ai-sdk-core/05-generating-text.mdx +7 -2
  15. package/docs/03-ai-sdk-core/10-generating-structured-data.mdx +4 -0
  16. package/docs/03-ai-sdk-core/16-mcp-tools.mdx +3 -0
  17. package/docs/03-ai-sdk-core/26-reasoning.mdx +3 -3
  18. package/docs/03-ai-sdk-core/32-decisions.mdx +13 -2
  19. package/docs/03-ai-sdk-core/33-extractions.mdx +58 -0
  20. package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -0
  21. package/docs/03-ai-sdk-core/36-transcription.mdx +3 -0
  22. package/docs/03-ai-sdk-core/37-speech.mdx +3 -0
  23. package/docs/06-advanced/11-secure-url-fetching.mdx +10 -1
  24. package/docs/07-reference/01-ai-sdk-core/14-decide.mdx +20 -15
  25. package/docs/07-reference/01-ai-sdk-core/14-extract.mdx +17 -12
  26. package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +6 -0
  27. package/docs/07-reference/01-ai-sdk-core/33-safe-validate-ui-messages.mdx +3 -0
  28. package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +115 -7
  29. package/package.json +11 -11
  30. package/src/agent/default-stop-condition.ts +28 -13
  31. package/src/decide/decide.ts +12 -1
  32. package/src/decide/decision-state.ts +29 -6
  33. package/src/extract/extract.ts +12 -1
  34. package/src/generate-text/validate-tool-approvals.ts +23 -19
@@ -14,18 +14,23 @@ Extracts a nonempty map of typed fields from one state. See
14
14
 
15
15
  ## Parameters
16
16
 
17
- | Parameter | Type | Description |
18
- | ----------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
19
- | `model` | `Experimental_ExtractionModel` | Required experimental v4 extraction model instance. |
20
- | `state` | `Experimental_ExtractionState` | Required string, JSON object, or ordered array of text, file, and JSON parts. |
21
- | `fields` | `Record<string, Experimental_ExtractionField>` | Required nonempty field map. |
22
- | `referenceDate` | `string` | Optional `YYYY-MM-DD` date that anchors relative dates. |
23
- | `maxOutputTokens` | `number` | Optional maximum output tokens, an integer >= 1. |
24
- | `reasoning` | `'provider-default' \| 'none' \| 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | Optional reasoning effort for supported models. |
25
- | `maxRetries` | `number` | Nonnegative integer; defaults to 2. |
26
- | `abortSignal` | `AbortSignal` | Cancels the extraction request. |
27
- | `headers` | `Record<string, string>` | Additional HTTP headers. |
28
- | `providerOptions` | `ProviderOptions` | Provider-specific options. |
17
+ | Parameter | Type | Description |
18
+ | ----------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
19
+ | `model` | `Experimental_ExtractionModel` | Required experimental v4 extraction model instance. |
20
+ | `state` | `Experimental_ExtractionState` | Required string, JSON object, or ordered array of text, file, and JSON parts. |
21
+ | `fields` | `Record<string, Experimental_ExtractionField>` | Required nonempty field map. |
22
+ | `referenceDate` | `string` | Optional `YYYY-MM-DD` date that anchors relative dates. |
23
+ | `maxOutputTokens` | `number` | Optional maximum output tokens, an integer >= 1. |
24
+ | `reasoning` | `'provider-default' \| 'none' \| 'minimal' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'` | Optional reasoning effort for supported models. |
25
+ | `maxRetries` | `number` | Nonnegative integer; defaults to 2. |
26
+ | `abortSignal` | `AbortSignal` | Cancels the extraction request. |
27
+ | `experimental_download` | `Experimental_DownloadFunction` | Required for remote file URLs in state. Use `createDownload({ fetch })` with a DNS-protected transport for untrusted URLs. |
28
+ | `headers` | `Record<string, string>` | Additional HTTP headers. |
29
+ | `providerOptions` | `ProviderOptions` | Provider-specific options. |
30
+
31
+ Remote file URLs are rejected with `DownloadError` unless `experimental_download`
32
+ is supplied. The model's `fetch` option does not apply to these downloads. See
33
+ [Secure URL Fetching](/docs/advanced/secure-url-fetching#core-file-downloads).
29
34
 
30
35
  ## Fields
31
36
 
@@ -7,6 +7,12 @@ description: API Reference for validateUIMessages
7
7
 
8
8
  `validateUIMessages` is an async function that validates UI messages against schemas for metadata, data parts, and tools. It ensures type safety and data integrity for your message arrays before processing or rendering.
9
9
 
10
+ Structural validation stops at the first invalid element in message and part arrays.
11
+ Part types and tool states select the applicable schema before its fields are validated.
12
+ The error retains the failing element's path without accumulating errors for every
13
+ malformed element. Valid message and part arrays have no SDK-imposed count limit;
14
+ apply request size and message history limits appropriate for your application.
15
+
10
16
  ## Basic Usage
11
17
 
12
18
  Simple validation without custom schemas:
@@ -7,6 +7,9 @@ description: API Reference for safeValidateUIMessages
7
7
 
8
8
  `safeValidateUIMessages` is an async function that validates UI messages like [`validateUIMessages`](/docs/reference/ai-sdk-core/validate-ui-messages), but instead of throwing it returns an object with a `success` key and either `data` or `error`.
9
9
 
10
+ Structural validation stops at the first invalid element in message and part
11
+ arrays, retaining its path in the returned error.
12
+
10
13
  ## Basic Usage
11
14
 
12
15
  Simple validation without custom schemas:
@@ -9,6 +9,8 @@ Creates a durable, resumable AI agent for use inside a workflow. `WorkflowAgent`
9
9
 
10
10
  Unlike [`ToolLoopAgent`](/docs/reference/ai-sdk-core/tool-loop-agent) from the `ai` package, `WorkflowAgent` is designed to survive process restarts, pause for human approval, and integrate with the Workflow DevKit's step mechanism.
11
11
 
12
+ `WorkflowAgent` does not implement the `Agent` interface, and its options, callbacks, and results differ from `ToolLoopAgent`. See [Differences from ToolLoopAgent](/docs/agents/workflow-agent#differences-from-toolloopagent) for the list.
13
+
12
14
  `WorkflowAgent` supports `runtimeContext` for shared agent state and `toolsContext` for per-tool context. Because these values can cross workflow and step boundaries, keep them serializable durable data. Unlike `ToolLoopAgent`, do not place functions, class instances, symbols, database clients, or SDK clients in context; pass identifiers or configuration and recreate non-serializable resources inside step functions.
13
15
 
14
16
  ```ts
@@ -115,6 +117,13 @@ To see `WorkflowAgent` in action, check out [these examples](#examples).
115
117
  description:
116
118
  'Default set of active tools. Limits which tools the model can call without changing tool call and result types. Per-stream values override this default.',
117
119
  },
120
+ {
121
+ name: 'toolOrder',
122
+ type: 'ToolOrder<TTools>',
123
+ isOptional: true,
124
+ description:
125
+ 'Controls the order in which tools are sent to the provider. The list can be partial. Tools not listed in `toolOrder` are sent after the listed tools, sorted alphabetically. Tool names are restricted to the string keys of the tool set.',
126
+ },
118
127
  {
119
128
  name: 'output',
120
129
  type: 'OutputSpecification',
@@ -129,6 +138,13 @@ To see `WorkflowAgent` in action, check out [these examples](#examples).
129
138
  description:
130
139
  "Default function to repair tool calls that fail to parse. Mark the function with 'use step' when used in a workflow. Per-stream values override this default.",
131
140
  },
141
+ {
142
+ name: 'experimental_refineToolInput',
143
+ type: 'ToolInputRefinement<TTools>',
144
+ isOptional: true,
145
+ description:
146
+ 'Optional mapping of tool names to functions that refine parsed tool inputs. Each function receives the typed input for its tool and must return the same input type shape. The refined input is used for tool execution, output parts, lifecycle callbacks, and telemetry in both `generate()` and `stream()`. Per-stream values override this default.',
147
+ },
132
148
  {
133
149
  name: 'experimental_download',
134
150
  type: 'DownloadFunction',
@@ -143,6 +159,13 @@ To see `WorkflowAgent` in action, check out [these examples](#examples).
143
159
  description:
144
160
  'Default sandbox session passed to tool descriptions and execution as `experimental_sandbox`, and exposed to `prepareStep`. Per-stream values override this default.',
145
161
  },
162
+ {
163
+ name: 'toolApproval',
164
+ type: 'ToolApprovalConfiguration<TTools, TRuntimeContext>',
165
+ isOptional: true,
166
+ description:
167
+ "Default approval configuration for tool calls. Pass a `GenericToolApprovalFunction` to handle all tool calls in one callback with `toolCall`, `tools`, `toolsContext`, `messages`, and `runtimeContext`, or pass a per-tool object where each key can be a status (`'not-applicable'`, `'approved'`, `'denied'`, or `'user-approval'`), an object form such as `{ type: 'denied', reason: 'blocked by policy' }`, or a `SingleToolApprovalFunction` that receives the tool input and options `toolCallId`, `messages`, `toolContext`, and `runtimeContext`. This setting takes precedence over a tool's `needsApproval` default. The functions in the configuration run in workflow context, outside of the durable model steps, and are never passed across a step boundary. Per-stream values override this default.",
168
+ },
146
169
  {
147
170
  name: 'experimental_toolApprovalSecret',
148
171
  type: 'WorkflowToolApprovalSecret',
@@ -394,6 +417,20 @@ To see `WorkflowAgent` in action, check out [these examples](#examples).
394
417
  description:
395
418
  'Callback called when all agent steps are finished and the response is complete. Receives steps, messages, text, finish reason, total usage, and context. If also specified in `stream()`, both callbacks fire (constructor first).',
396
419
  },
420
+ {
421
+ name: 'onError',
422
+ type: 'WorkflowAgentOnErrorCallback',
423
+ isOptional: true,
424
+ description:
425
+ 'Callback called when an error occurs. Aborts are not reported. If also specified in `generate()` or `stream()`, both callbacks fire (constructor first). Errors thrown by the callback are ignored.',
426
+ },
427
+ {
428
+ name: 'onAbort',
429
+ type: 'WorkflowAgentOnAbortCallback',
430
+ isOptional: true,
431
+ description:
432
+ 'Callback called when the operation is aborted. Receives all previously finished steps. If also specified in `generate()` or `stream()`, both callbacks fire (constructor first). Errors thrown by the callback are ignored.',
433
+ },
397
434
  {
398
435
  name: 'maxOutputTokens',
399
436
  type: 'number',
@@ -462,6 +499,27 @@ To see `WorkflowAgent` in action, check out [these examples](#examples).
462
499
  isOptional: true,
463
500
  description: 'Additional provider-specific configuration.',
464
501
  },
502
+ {
503
+ name: 'reasoning',
504
+ type: "LanguageModelV4CallOptions['reasoning']",
505
+ isOptional: true,
506
+ description:
507
+ 'Reasoning effort for the model. Controls how much reasoning the model performs before it generates a response.',
508
+ },
509
+ {
510
+ name: 'abortSignal',
511
+ type: 'AbortSignal',
512
+ isOptional: true,
513
+ description:
514
+ 'Default abort signal for every call on this agent. An `abortSignal` passed to `generate()` or `stream()` overrides it.',
515
+ },
516
+ {
517
+ name: 'allowSystemInMessages',
518
+ type: 'boolean',
519
+ isOptional: true,
520
+ description:
521
+ 'Whether system messages are allowed in the `prompt` or `messages` fields. When `false`, system messages in `prompt` or `messages` are rejected and must be provided through `instructions`. Default: false.',
522
+ },
465
523
  ]}
466
524
  />
467
525
 
@@ -532,6 +590,8 @@ const result = await agent.stream({
532
590
  });
533
591
  ```
534
592
 
593
+ In addition to the options in the table, `stream()` accepts the generation settings of the constructor (`maxOutputTokens`, `temperature`, `topP`, `topK`, `presencePenalty`, `frequencyPenalty`, `stopSequences`, `seed`, `reasoning`, `maxRetries`, `headers`, `providerOptions`) and `abortSignal`. A value passed to `stream()` overrides the constructor value.
594
+
535
595
  <PropertiesTable
536
596
  content={[
537
597
  {
@@ -589,6 +649,13 @@ const result = await agent.stream({
589
649
  isOptional: true,
590
650
  description: 'Limits the subset of tools available for this call without changing tool call and result types.',
591
651
  },
652
+ {
653
+ name: 'toolOrder',
654
+ type: 'ToolOrder<TTools>',
655
+ isOptional: true,
656
+ description:
657
+ 'Controls the order in which tools are sent to the provider. The list can be partial. Tools not listed in `toolOrder` are sent after the listed tools, sorted alphabetically. Tool names are restricted to the string keys of the tool set.',
658
+ },
592
659
  {
593
660
  name: 'output',
594
661
  type: 'OutputSpecification',
@@ -598,9 +665,9 @@ const result = await agent.stream({
598
665
  },
599
666
  {
600
667
  name: 'timeout',
601
- type: 'number',
668
+ type: 'WorkflowAgentTimeoutConfiguration',
602
669
  isOptional: true,
603
- description: 'Model-call deadline in milliseconds. Inside a workflow, the absolute deadline is checked at dispatch and retry and remains in effect across suspension. It does not cancel a tool waiting on a Workflow hook; use run.cancel() to stop the suspended run.',
670
+ description: 'Timeout for model calls. A number, or `totalMs` in the object form, is one deadline in milliseconds for the whole run. Inside a workflow, the absolute deadline is checked at dispatch and retry and remains in effect across suspension. `stepMs` limits each model call. `firstChunkMs` limits the wait for the first output of each model call, and `chunkMs` limits the wait between two outputs. A timeout does not cancel a tool waiting on a Workflow hook; use run.cancel() to stop the suspended run.',
604
671
  },
605
672
  {
606
673
  name: 'sendFinish',
@@ -626,6 +693,13 @@ const result = await agent.stream({
626
693
  isOptional: true,
627
694
  description: "Callback to attempt automatic recovery when a tool call cannot be parsed. Mark the function with 'use step' when used in a workflow.",
628
695
  },
696
+ {
697
+ name: 'experimental_refineToolInput',
698
+ type: 'ToolInputRefinement<TTools>',
699
+ isOptional: true,
700
+ description:
701
+ 'Optional mapping of tool names to functions that refine parsed tool inputs. Each function receives the typed input for its tool and must return the same input type shape. The refined input is used for tool execution, output parts, lifecycle callbacks, and telemetry in both `generate()` and `stream()`. Overrides the constructor default.',
702
+ },
629
703
  {
630
704
  name: 'experimental_download',
631
705
  type: 'DownloadFunction',
@@ -640,6 +714,13 @@ const result = await agent.stream({
640
714
  description:
641
715
  'Sandbox session passed to tool descriptions and execution as `experimental_sandbox`, and exposed to `prepareStep`. Overrides the constructor default.',
642
716
  },
717
+ {
718
+ name: 'toolApproval',
719
+ type: 'ToolApprovalConfiguration<TTools, TRuntimeContext>',
720
+ isOptional: true,
721
+ description:
722
+ "Approval configuration for tool calls. Pass a `GenericToolApprovalFunction` to handle all tool calls in one callback with `toolCall`, `tools`, `toolsContext`, `messages`, and `runtimeContext`, or pass a per-tool object where each key can be a status (`'not-applicable'`, `'approved'`, `'denied'`, or `'user-approval'`), an object form such as `{ type: 'denied', reason: 'blocked by policy' }`, or a `SingleToolApprovalFunction` that receives the tool input and options `toolCallId`, `messages`, `toolContext`, and `runtimeContext`. This setting takes precedence over a tool's `needsApproval` default. The functions in the configuration run in workflow context, outside of the durable model steps, and are never passed across a step boundary. Overrides the constructor default.",
723
+ },
643
724
  {
644
725
  name: 'experimental_toolApprovalSecret',
645
726
  type: 'WorkflowToolApprovalSecret',
@@ -741,13 +822,15 @@ const result = await agent.stream({
741
822
  name: 'onError',
742
823
  type: 'WorkflowAgentOnErrorCallback',
743
824
  isOptional: true,
744
- description: 'Callback invoked when an error occurs during streaming.',
825
+ description:
826
+ 'Callback invoked when an error occurs. Aborts are not reported. If also specified in the constructor, both callbacks fire (constructor first). Errors thrown by the callback are ignored.',
745
827
  },
746
828
  {
747
829
  name: 'onAbort',
748
830
  type: 'WorkflowAgentOnAbortCallback',
749
831
  isOptional: true,
750
- description: 'Callback invoked when the operation is aborted. Receives all previously finished steps.',
832
+ description:
833
+ 'Callback invoked when the operation is aborted. Receives all previously finished steps. If also specified in the constructor, both callbacks fire (constructor first). Errors thrown by the callback are ignored.',
751
834
  },
752
835
 
753
836
  ]}
@@ -781,6 +864,16 @@ Returns a `Promise<WorkflowAgentStreamResult>` with the following properties:
781
864
  description:
782
865
  'Tool results from the last step. Only includes results for tools that were executed.',
783
866
  },
867
+ {
868
+ name: 'finishReason',
869
+ type: 'FinishReason',
870
+ description: 'The finish reason of the last step.',
871
+ },
872
+ {
873
+ name: 'totalUsage',
874
+ type: 'LanguageModelUsage',
875
+ description: 'The token usage of all steps combined.',
876
+ },
784
877
  {
785
878
  name: 'error',
786
879
  type: 'unknown | undefined',
@@ -861,6 +954,21 @@ type ActiveTools<TTools extends ToolSet> =
861
954
 
862
955
  Limits a workflow agent call to the listed tool names. `undefined` means no tool restriction is applied.
863
956
 
957
+ ### `WorkflowAgentTimeoutConfiguration`
958
+
959
+ ```ts
960
+ type WorkflowAgentTimeoutConfiguration =
961
+ | number
962
+ | {
963
+ totalMs?: number;
964
+ stepMs?: number;
965
+ firstChunkMs?: number;
966
+ chunkMs?: number;
967
+ };
968
+ ```
969
+
970
+ The `timeout` option of `generate()` and `stream()`. A number is the total deadline in milliseconds. `generate()` uses `totalMs` and `stepMs`. `stream()` uses all four values. See [Deadlines, cancellation, and replay](/docs/agents/workflow-agent#deadlines-cancellation-and-replay).
971
+
864
972
  ### `InferWorkflowAgentUIMessage`
865
973
 
866
974
  Infers the UI message type for a `WorkflowAgent` instance. Optionally accepts a second type argument for custom message metadata.
@@ -1028,9 +1136,9 @@ console.log(result.output);
1028
1136
 
1029
1137
  ### Agent with Tool Approval
1030
1138
 
1031
- For `WorkflowAgent`, tool approval is configured on the tool definition with
1032
- `needsApproval`. For `generateText`, `streamText`, and `ToolLoopAgent`, use
1033
- `toolApproval` instead.
1139
+ Tool approval is configured on the tool definition with `needsApproval` or on
1140
+ the agent with `toolApproval`. The `toolApproval` configuration takes precedence
1141
+ over `needsApproval`.
1034
1142
 
1035
1143
  ```ts
1036
1144
  import { WorkflowAgent } from '@ai-sdk/workflow';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai",
3
- "version": "7.0.171",
3
+ "version": "7.0.173",
4
4
  "type": "module",
5
5
  "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.",
6
6
  "license": "Apache-2.0",
@@ -42,20 +42,20 @@
42
42
  }
43
43
  },
44
44
  "dependencies": {
45
- "@ai-sdk/gateway": "4.0.144",
45
+ "@ai-sdk/gateway": "4.0.146",
46
46
  "@ai-sdk/provider": "4.0.38",
47
- "@ai-sdk/provider-utils": "5.0.80"
47
+ "@ai-sdk/provider-utils": "5.0.81"
48
48
  },
49
49
  "devDependencies": {
50
- "@ai-sdk/amazon-bedrock": "5.0.140",
51
- "@ai-sdk/deepseek": "3.0.85",
52
- "@ai-sdk/google": "4.0.119",
53
- "@ai-sdk/groq": "4.0.82",
54
- "@ai-sdk/huggingface": "2.0.91",
55
- "@ai-sdk/moonshotai": "3.0.91",
56
- "@ai-sdk/openai": "4.0.116",
50
+ "@ai-sdk/amazon-bedrock": "5.0.142",
51
+ "@ai-sdk/deepseek": "3.0.87",
52
+ "@ai-sdk/google": "4.0.121",
53
+ "@ai-sdk/groq": "4.0.84",
54
+ "@ai-sdk/huggingface": "2.0.93",
55
+ "@ai-sdk/moonshotai": "3.0.93",
56
+ "@ai-sdk/openai": "4.0.118",
57
57
  "@ai-sdk/test-server": "2.0.4",
58
- "@ai-sdk/xai": "5.0.44",
58
+ "@ai-sdk/xai": "5.0.46",
59
59
  "@edge-runtime/vm": "^5.0.0",
60
60
  "@smithy/eventstream-codec": "^4.3.3",
61
61
  "@smithy/util-utf8": "^4.3.3",
@@ -1,6 +1,33 @@
1
1
  import { logWarnings } from '../logger/log-warnings';
2
2
  import type { StopCondition } from '../generate-text/stop-condition';
3
3
 
4
+ /**
5
+ * Logs the warning for the default stopWhen condition.
6
+ */
7
+ export function logDefaultStopConditionWarning({
8
+ stepCount,
9
+ provider,
10
+ modelId,
11
+ }: {
12
+ stepCount: number;
13
+ provider: string;
14
+ modelId: string;
15
+ }): void {
16
+ logWarnings({
17
+ provider,
18
+ model: modelId,
19
+ warnings: [
20
+ {
21
+ type: 'other',
22
+ message:
23
+ `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). ` +
24
+ 'To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. ' +
25
+ 'Learn more: https://ai-sdk.dev/docs/agents/loop-control',
26
+ },
27
+ ],
28
+ });
29
+ }
30
+
4
31
  /**
5
32
  * Stop conditions are only evaluated when the tool loop can otherwise continue,
6
33
  * so logging here avoids warning when a call finishes naturally at the limit.
@@ -14,19 +41,7 @@ export function createDefaultStopCondition(
14
41
  }
15
42
 
16
43
  const { provider, modelId } = steps[steps.length - 1].model;
17
- logWarnings({
18
- provider,
19
- model: modelId,
20
- warnings: [
21
- {
22
- type: 'other',
23
- message:
24
- `The tool loop stopped because it reached the default stopWhen condition, isStepCount(${stepCount}). ` +
25
- 'To allow more steps, set stopWhen to isStepCount(...) with a higher limit or provide a custom stop condition. ' +
26
- 'Learn more: https://ai-sdk.dev/docs/agents/loop-control',
27
- },
28
- ],
29
- });
44
+ logDefaultStopConditionWarning({ stepCount, provider, modelId });
30
45
 
31
46
  return true;
32
47
  };
@@ -15,6 +15,7 @@ import { resolveDecisionModel } from '../model/resolve-model';
15
15
  import { logWarnings } from '../logger/log-warnings';
16
16
  import type { TelemetryOptions } from '../telemetry/telemetry-options';
17
17
  import type { Callback } from '../util/callback';
18
+ import type { DownloadFunction } from '../util/download/download-function';
18
19
  import { notify } from '../util/notify';
19
20
  import { prepareRetries } from '../util/prepare-retries';
20
21
  import { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';
@@ -44,6 +45,7 @@ export async function decide<
44
45
  reasoning,
45
46
  maxRetries,
46
47
  abortSignal,
48
+ experimental_download: download,
47
49
  headers,
48
50
  providerOptions = {},
49
51
  telemetry,
@@ -63,6 +65,11 @@ export async function decide<
63
65
  /** Maximum retries for transient provider failures. Defaults to 2. */
64
66
  maxRetries?: number;
65
67
  abortSignal?: AbortSignal;
68
+ /**
69
+ * Download function required for URL-backed file state. Use createDownload({ fetch })
70
+ * with a DNS-protected transport for untrusted URLs. The model's fetch is not used.
71
+ */
72
+ experimental_download?: DownloadFunction;
66
73
  headers?: Record<string, string>;
67
74
  providerOptions?: ProviderOptions;
68
75
  /** Optional telemetry configuration. */
@@ -130,7 +137,11 @@ export async function decide<
130
137
  });
131
138
 
132
139
  try {
133
- const preparedState = await prepareDecisionState(state, abortSignal);
140
+ const preparedState = await prepareDecisionState({
141
+ state,
142
+ abortSignal,
143
+ download,
144
+ });
134
145
  const modelCallEvent = {
135
146
  callId,
136
147
  operationId: 'ai.decide.doDecide' as const,
@@ -3,8 +3,13 @@ import type {
3
3
  JSONObject,
4
4
  JSONValue,
5
5
  } from '@ai-sdk/provider';
6
- import type { FilePart, TextPart } from '@ai-sdk/provider-utils';
6
+ import {
7
+ DownloadError,
8
+ type FilePart,
9
+ type TextPart,
10
+ } from '@ai-sdk/provider-utils';
7
11
  import { convertToLanguageModelPrompt } from '../prompt/convert-to-language-model-prompt';
12
+ import type { DownloadFunction } from '../util/download/download-function';
8
13
 
9
14
  /** Shared text, JSON data, or ordered multimodal parts for a decision. */
10
15
  export type DecisionState =
@@ -23,10 +28,15 @@ function isDecisionStateParts(
23
28
  return Array.isArray(state);
24
29
  }
25
30
 
26
- export async function prepareDecisionState(
27
- state: DecisionState,
28
- abortSignal?: AbortSignal,
29
- ): Promise<DecisionModelV4State> {
31
+ export async function prepareDecisionState({
32
+ state,
33
+ abortSignal,
34
+ download,
35
+ }: {
36
+ state: DecisionState;
37
+ abortSignal?: AbortSignal;
38
+ download?: DownloadFunction;
39
+ }): Promise<DecisionModelV4State> {
30
40
  if (typeof state === 'string') {
31
41
  return [{ type: 'text', text: state }];
32
42
  }
@@ -49,7 +59,20 @@ export async function prepareDecisionState(
49
59
  messages: [{ role: 'user', content: files }],
50
60
  },
51
61
  supportedUrls: {},
52
- download: undefined,
62
+ // Do not silently fetch URL state through the runtime's global fetch.
63
+ // URL/literal-IP validation alone cannot protect against private DNS answers.
64
+ download:
65
+ download ??
66
+ (async requests => {
67
+ if (requests.length > 0) {
68
+ throw new DownloadError({
69
+ url: requests[0].url.toString(),
70
+ message:
71
+ 'URL file state requires experimental_download. For untrusted URLs, use createDownload({ fetch }) with a transport that validates DNS at connection time.',
72
+ });
73
+ }
74
+ return [];
75
+ }),
53
76
  abortSignal,
54
77
  });
55
78
  const message = prompt[0];
@@ -15,6 +15,7 @@ import {
15
15
  import { logWarnings } from '../logger/log-warnings';
16
16
  import { resolveExtractionModel } from '../model/resolve-model';
17
17
  import { prepareLanguageModelCallOptions } from '../prompt/prepare-language-model-call-options';
18
+ import type { DownloadFunction } from '../util/download/download-function';
18
19
  import { prepareRetries } from '../util/prepare-retries';
19
20
  import { VERSION } from '../version';
20
21
  import type { ExtractionModel, ExtractionResult } from './extraction-result';
@@ -35,6 +36,7 @@ export async function extract<
35
36
  reasoning,
36
37
  maxRetries,
37
38
  abortSignal,
39
+ experimental_download: download,
38
40
  headers,
39
41
  providerOptions = {},
40
42
  }: {
@@ -51,6 +53,11 @@ export async function extract<
51
53
  /** Maximum retries for transient provider failures. Defaults to 2. */
52
54
  maxRetries?: number;
53
55
  abortSignal?: AbortSignal;
56
+ /**
57
+ * Download function required for URL-backed file state. Use createDownload({ fetch })
58
+ * with a DNS-protected transport for untrusted URLs. The model's fetch is not used.
59
+ */
60
+ experimental_download?: DownloadFunction;
54
61
  headers?: Record<string, string>;
55
62
  providerOptions?: ProviderOptions;
56
63
  }): Promise<ExtractionResult<FIELDS>> {
@@ -71,7 +78,11 @@ export async function extract<
71
78
  }
72
79
 
73
80
  const { retry } = prepareRetries({ maxRetries, abortSignal });
74
- const preparedState = await prepareDecisionState(state, abortSignal);
81
+ const preparedState = await prepareDecisionState({
82
+ state,
83
+ abortSignal,
84
+ download,
85
+ });
75
86
  const result = await retry(async () => {
76
87
  abortSignal?.throwIfAborted();
77
88
  return await model.doExtract({
@@ -111,22 +111,27 @@ export async function validateApprovedToolApprovals<
111
111
  }
112
112
 
113
113
  if (isExecutableTool(tool) && tool.inputSchema != null) {
114
- const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(
115
- approvalRequest,
116
- 'inputSchemaInput',
117
- );
118
- const validation = await safeValidateTypes({
119
- value: hasInputSchemaInput
120
- ? approvalRequest.inputSchemaInput
121
- : toolCall.input,
122
- schema: asSchema(tool.inputSchema),
123
- });
124
-
125
114
  let validationError: unknown;
126
- if (!validation.success) {
127
- validationError = validation.error;
128
- } else {
129
- try {
115
+ try {
116
+ // Preserve the approved input before validators or refiners can mutate
117
+ // it, and give them an independent copy of the schema input.
118
+ const approvedInput = structuredClone(toolCall.input);
119
+ const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(
120
+ approvalRequest,
121
+ 'inputSchemaInput',
122
+ );
123
+ const validation = await safeValidateTypes({
124
+ value: structuredClone(
125
+ hasInputSchemaInput
126
+ ? approvalRequest.inputSchemaInput
127
+ : toolCall.input,
128
+ ),
129
+ schema: asSchema(tool.inputSchema),
130
+ });
131
+
132
+ if (!validation.success) {
133
+ validationError = validation.error;
134
+ } else {
130
135
  const revalidatedToolCall = await refineParsedToolCallInput({
131
136
  toolCall: {
132
137
  ...toolCall,
@@ -135,9 +140,8 @@ export async function validateApprovedToolApprovals<
135
140
  refineToolInput,
136
141
  });
137
142
 
138
- // Clone both inputs into the current realm before comparing them.
143
+ // Normalize the revalidated input to the snapshot's realm.
139
144
  const revalidatedInput = structuredClone(revalidatedToolCall.input);
140
- const approvedInput = structuredClone(toolCall.input);
141
145
 
142
146
  // Revalidation must never change the operation that was approved,
143
147
  // including when older or projected history omits the schema input.
@@ -146,9 +150,9 @@ export async function validateApprovedToolApprovals<
146
150
  'Approved tool input does not match the validated schema output.',
147
151
  );
148
152
  }
149
- } catch (error) {
150
- validationError = error;
151
153
  }
154
+ } catch (error) {
155
+ validationError = error;
152
156
  }
153
157
 
154
158
  if (validationError != null) {