@ai-sdk/provider-utils 5.0.0-beta.4 → 5.0.0-beta.49

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 (117) hide show
  1. package/CHANGELOG.md +373 -11
  2. package/dist/index.d.ts +1460 -553
  3. package/dist/index.js +1044 -361
  4. package/dist/index.js.map +1 -1
  5. package/dist/test/index.d.ts +2 -1
  6. package/dist/test/index.js +18 -37
  7. package/dist/test/index.js.map +1 -1
  8. package/package.json +16 -16
  9. package/src/add-additional-properties-to-json-schema.ts +1 -1
  10. package/src/as-array.ts +12 -0
  11. package/src/cancel-response-body.ts +19 -0
  12. package/src/convert-image-model-file-to-data-uri.ts +1 -1
  13. package/src/convert-inline-file-data-to-uint8-array.ts +30 -0
  14. package/src/create-tool-name-mapping.ts +1 -1
  15. package/src/detect-media-type.ts +312 -0
  16. package/src/download-blob.ts +8 -9
  17. package/src/extract-lines.ts +31 -0
  18. package/src/fetch-with-validated-redirects.ts +87 -0
  19. package/src/filter-nullable.ts +11 -0
  20. package/src/get-error-message.ts +1 -15
  21. package/src/get-from-api.ts +2 -2
  22. package/src/has-required-key.ts +6 -0
  23. package/src/index.ts +47 -12
  24. package/src/inject-json-instruction.ts +1 -1
  25. package/src/is-browser-runtime.ts +13 -0
  26. package/src/is-buffer.ts +9 -0
  27. package/src/is-json-serializable.ts +29 -0
  28. package/src/is-provider-reference.ts +21 -0
  29. package/src/is-same-origin.ts +19 -0
  30. package/src/is-url-supported.ts +17 -2
  31. package/src/load-api-key.ts +1 -1
  32. package/src/load-setting.ts +1 -1
  33. package/src/map-reasoning-to-provider.ts +108 -0
  34. package/src/maybe-promise-like.ts +3 -0
  35. package/src/parse-json-event-stream.ts +3 -3
  36. package/src/parse-json.ts +3 -3
  37. package/src/parse-provider-options.ts +1 -1
  38. package/src/post-to-api.ts +4 -4
  39. package/src/provider-defined-tool-factory.ts +129 -0
  40. package/src/provider-executed-tool-factory.ts +69 -0
  41. package/src/read-response-with-size-limit.ts +4 -0
  42. package/src/resolve-full-media-type.ts +49 -0
  43. package/src/resolve-provider-reference.ts +26 -0
  44. package/src/resolve.ts +16 -1
  45. package/src/response-handler.ts +3 -3
  46. package/src/schema.ts +11 -4
  47. package/src/secure-json-parse.ts +1 -1
  48. package/src/serialize-model-options.ts +63 -0
  49. package/src/streaming-tool-call-tracker.ts +241 -0
  50. package/src/test/convert-response-stream-to-array.ts +1 -1
  51. package/src/test/is-node-version.ts +22 -1
  52. package/src/to-json-schema/zod3-to-json-schema/options.ts +3 -3
  53. package/src/to-json-schema/zod3-to-json-schema/parse-def.ts +3 -3
  54. package/src/to-json-schema/zod3-to-json-schema/parse-types.ts +22 -22
  55. package/src/to-json-schema/zod3-to-json-schema/parsers/array.ts +3 -3
  56. package/src/to-json-schema/zod3-to-json-schema/parsers/bigint.ts +1 -1
  57. package/src/to-json-schema/zod3-to-json-schema/parsers/branded.ts +2 -2
  58. package/src/to-json-schema/zod3-to-json-schema/parsers/catch.ts +2 -2
  59. package/src/to-json-schema/zod3-to-json-schema/parsers/date.ts +4 -4
  60. package/src/to-json-schema/zod3-to-json-schema/parsers/default.ts +3 -3
  61. package/src/to-json-schema/zod3-to-json-schema/parsers/effects.ts +3 -3
  62. package/src/to-json-schema/zod3-to-json-schema/parsers/enum.ts +1 -1
  63. package/src/to-json-schema/zod3-to-json-schema/parsers/intersection.ts +5 -5
  64. package/src/to-json-schema/zod3-to-json-schema/parsers/literal.ts +1 -1
  65. package/src/to-json-schema/zod3-to-json-schema/parsers/map.ts +4 -5
  66. package/src/to-json-schema/zod3-to-json-schema/parsers/native-enum.ts +1 -1
  67. package/src/to-json-schema/zod3-to-json-schema/parsers/never.ts +1 -2
  68. package/src/to-json-schema/zod3-to-json-schema/parsers/nullable.ts +4 -4
  69. package/src/to-json-schema/zod3-to-json-schema/parsers/number.ts +1 -1
  70. package/src/to-json-schema/zod3-to-json-schema/parsers/object.ts +3 -3
  71. package/src/to-json-schema/zod3-to-json-schema/parsers/optional.ts +3 -3
  72. package/src/to-json-schema/zod3-to-json-schema/parsers/pipeline.ts +10 -8
  73. package/src/to-json-schema/zod3-to-json-schema/parsers/promise.ts +3 -3
  74. package/src/to-json-schema/zod3-to-json-schema/parsers/readonly.ts +2 -2
  75. package/src/to-json-schema/zod3-to-json-schema/parsers/record.ts +9 -10
  76. package/src/to-json-schema/zod3-to-json-schema/parsers/set.ts +3 -3
  77. package/src/to-json-schema/zod3-to-json-schema/parsers/string.ts +2 -2
  78. package/src/to-json-schema/zod3-to-json-schema/parsers/tuple.ts +3 -3
  79. package/src/to-json-schema/zod3-to-json-schema/parsers/undefined.ts +1 -2
  80. package/src/to-json-schema/zod3-to-json-schema/parsers/union.ts +3 -3
  81. package/src/to-json-schema/zod3-to-json-schema/parsers/unknown.ts +1 -2
  82. package/src/to-json-schema/zod3-to-json-schema/refs.ts +3 -3
  83. package/src/to-json-schema/zod3-to-json-schema/select-parser.ts +2 -2
  84. package/src/to-json-schema/zod3-to-json-schema/zod3-to-json-schema.ts +3 -3
  85. package/src/types/assistant-model-message.ts +5 -3
  86. package/src/types/content-part.ts +158 -19
  87. package/src/types/context.ts +4 -0
  88. package/src/types/executable-tool.ts +17 -0
  89. package/src/types/execute-tool.ts +29 -9
  90. package/src/types/file-data.ts +48 -0
  91. package/src/types/index.ts +29 -11
  92. package/src/types/infer-tool-context.ts +41 -0
  93. package/src/types/infer-tool-input.ts +7 -0
  94. package/src/types/infer-tool-output.ts +7 -0
  95. package/src/types/infer-tool-set-context.ts +44 -0
  96. package/src/types/model-message.ts +4 -4
  97. package/src/types/never-optional.ts +7 -0
  98. package/src/types/provider-options.ts +1 -1
  99. package/src/types/provider-reference.ts +10 -0
  100. package/src/types/sandbox.ts +217 -0
  101. package/src/types/system-model-message.ts +1 -1
  102. package/src/types/tool-approval-request.ts +13 -0
  103. package/src/types/tool-execute-function.ts +56 -0
  104. package/src/types/tool-model-message.ts +3 -3
  105. package/src/types/tool-needs-approval-function.ts +39 -0
  106. package/src/types/tool-set.ts +22 -0
  107. package/src/types/tool.ts +278 -225
  108. package/src/types/user-model-message.ts +2 -2
  109. package/src/validate-download-url.ts +120 -33
  110. package/src/validate-types.ts +5 -3
  111. package/dist/index.d.mts +0 -1455
  112. package/dist/index.mjs +0 -2754
  113. package/dist/index.mjs.map +0 -1
  114. package/dist/test/index.d.mts +0 -17
  115. package/dist/test/index.mjs +0 -77
  116. package/dist/test/index.mjs.map +0 -1
  117. package/src/provider-tool-factory.ts +0 -125
package/dist/index.d.ts CHANGED
@@ -1,10 +1,22 @@
1
- import { LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, ImageModelV4File, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, JSONValue, APICallError, LanguageModelV4Prompt, SharedV4ProviderOptions, TypeValidationContext } from '@ai-sdk/provider';
1
+ import { SharedV4FileDataUrl, SharedV4FileDataReference, SharedV4FileDataText, SharedV4ProviderOptions, SharedV4ProviderReference, JSONValue, ImageModelV4File, LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, JSONObject, LanguageModelV4FilePart, LanguageModelV4StreamPart, SharedV4ProviderMetadata, TypeValidationContext } from '@ai-sdk/provider';
2
+ export { getErrorMessage } from '@ai-sdk/provider';
2
3
  import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';
3
4
  export * from '@standard-schema/spec';
4
5
  import * as z3 from 'zod/v3';
5
6
  import * as z4 from 'zod/v4';
7
+ export { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE } from '@workflow/serde';
6
8
  export { EventSourceMessage, EventSourceParserStream } from 'eventsource-parser/stream';
7
9
 
10
+ /**
11
+ * A value that can be provided either as a single item, an array of items,
12
+ * or be left undefined.
13
+ */
14
+ type Arrayable<T> = T | T[] | undefined;
15
+ /**
16
+ * Normalizes a possibly undefined or non-array value into an array.
17
+ */
18
+ declare function asArray<T>(value: Arrayable<T>): T[];
19
+
8
20
  declare function combineHeaders(...headers: Array<Record<string, string | undefined> | undefined>): Record<string, string | undefined>;
9
21
 
10
22
  /**
@@ -16,6 +28,579 @@ declare function combineHeaders(...headers: Array<Record<string, string | undefi
16
28
  */
17
29
  declare function convertAsyncIteratorToReadableStream<T>(iterator: AsyncIterator<T>): ReadableStream<T>;
18
30
 
31
+ /**
32
+ * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
33
+ */
34
+ type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
35
+
36
+ /**
37
+ * File data variant containing raw bytes (`Uint8Array`, `ArrayBuffer`, or
38
+ * `Buffer`) or a base64-encoded string.
39
+ *
40
+ * This is slightly more permissive than `SharedV4FileDataData`.
41
+ */
42
+ interface FileDataData {
43
+ type: 'data';
44
+ data: DataContent;
45
+ }
46
+ /**
47
+ * File data variant containing a URL that points to the file.
48
+ */
49
+ type FileDataUrl = SharedV4FileDataUrl;
50
+ /**
51
+ * File data variant containing a provider reference (`{ [provider]: id }`).
52
+ */
53
+ type FileDataReference = SharedV4FileDataReference;
54
+ /**
55
+ * File data variant containing inline text content (e.g. an inline text
56
+ * document).
57
+ */
58
+ type FileDataText = SharedV4FileDataText;
59
+ /**
60
+ * File data as a tagged discriminated union:
61
+ *
62
+ * - `{ type: 'data', data }`: raw bytes (`Uint8Array`, `ArrayBuffer`, or
63
+ * `Buffer`) or a base64-encoded string.
64
+ * - `{ type: 'url', url }`: a URL that points to the file.
65
+ * - `{ type: 'reference', reference }`: a provider reference (`{ [provider]: id }`).
66
+ * - `{ type: 'text', text }`: inline text content (e.g. an inline text document).
67
+ */
68
+ type FileData = FileDataData | FileDataUrl | FileDataReference | FileDataText;
69
+
70
+ /**
71
+ * Additional provider-specific options.
72
+ *
73
+ * They are passed through to the provider from the AI SDK and enable
74
+ * provider-specific functionality that can be fully encapsulated in the provider.
75
+ */
76
+ type ProviderOptions = SharedV4ProviderOptions;
77
+
78
+ /**
79
+ * A mapping of provider names to provider-specific file identifiers.
80
+ *
81
+ * Provider references allow files to be identified across different
82
+ * providers without re-uploading, by storing each provider's own
83
+ * identifier for the same logical file.
84
+ */
85
+ type ProviderReference = SharedV4ProviderReference;
86
+
87
+ /**
88
+ * Text content part of a prompt. It contains a string of text.
89
+ */
90
+ interface TextPart {
91
+ type: 'text';
92
+ /**
93
+ * The text content.
94
+ */
95
+ text: string;
96
+ /**
97
+ * Additional provider-specific metadata. They are passed through
98
+ * to the provider from the AI SDK and enable provider-specific
99
+ * functionality that can be fully encapsulated in the provider.
100
+ */
101
+ providerOptions?: ProviderOptions;
102
+ }
103
+ /**
104
+ * Image content part of a prompt. It contains an image.
105
+ *
106
+ * @deprecated Use `FilePart` with `mediaType: 'image'` instead:
107
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
108
+ */
109
+ interface ImagePart {
110
+ type: 'image';
111
+ /**
112
+ * Image data. Can either be:
113
+ *
114
+ * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
115
+ * - URL: a URL that points to the image
116
+ * - ProviderReference: a provider reference from `uploadFile`
117
+ */
118
+ image: DataContent | URL | ProviderReference;
119
+ /**
120
+ * Optional IANA media type of the image.
121
+ *
122
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
123
+ */
124
+ mediaType?: string;
125
+ /**
126
+ * Additional provider-specific metadata. They are passed through
127
+ * to the provider from the AI SDK and enable provider-specific
128
+ * functionality that can be fully encapsulated in the provider.
129
+ */
130
+ providerOptions?: ProviderOptions;
131
+ }
132
+ /**
133
+ * File content part of a prompt. It contains a file.
134
+ */
135
+ interface FilePart {
136
+ type: 'file';
137
+ /**
138
+ * File data. Either a tagged shape or a bare shorthand:
139
+ *
140
+ * - `{ type: 'data', data }` or bare `DataContent`: raw bytes
141
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
142
+ * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file
143
+ * - `{ type: 'reference', reference }` or bare `ProviderReference`:
144
+ * a provider reference from `uploadFile`
145
+ * - `{ type: 'text', text }`: inline text content (tagged only)
146
+ */
147
+ data: FileData | DataContent | URL | ProviderReference;
148
+ /**
149
+ * Optional filename of the file.
150
+ */
151
+ filename?: string;
152
+ /**
153
+ * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just
154
+ * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`).
155
+ *
156
+ * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the
157
+ * top-level segment alone (e.g. `image`). Providers can use the helpers in
158
+ * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`,
159
+ * `detectMediaType`) to resolve the field according to their API
160
+ * requirements.
161
+ *
162
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
163
+ */
164
+ mediaType: string;
165
+ /**
166
+ * Additional provider-specific metadata. They are passed through
167
+ * to the provider from the AI SDK and enable provider-specific
168
+ * functionality that can be fully encapsulated in the provider.
169
+ */
170
+ providerOptions?: ProviderOptions;
171
+ }
172
+ /**
173
+ * Reasoning content part of a prompt. It contains a reasoning.
174
+ */
175
+ interface ReasoningPart {
176
+ type: 'reasoning';
177
+ /**
178
+ * The reasoning text.
179
+ */
180
+ text: string;
181
+ /**
182
+ * Additional provider-specific metadata. They are passed through
183
+ * to the provider from the AI SDK and enable provider-specific
184
+ * functionality that can be fully encapsulated in the provider.
185
+ */
186
+ providerOptions?: ProviderOptions;
187
+ }
188
+ /**
189
+ * Custom content part of a prompt. It contains no standardized payload beyond
190
+ * provider-specific options.
191
+ */
192
+ interface CustomPart {
193
+ type: 'custom';
194
+ /**
195
+ * The kind of custom content, in the format `{provider}.{provider-type}`.
196
+ */
197
+ kind: `${string}.${string}`;
198
+ /**
199
+ * Additional provider-specific metadata. They are passed through
200
+ * to the provider from the AI SDK and enable provider-specific
201
+ * functionality that can be fully encapsulated in the provider.
202
+ */
203
+ providerOptions?: ProviderOptions;
204
+ }
205
+ /**
206
+ * Reasoning file content part of a prompt. It contains a file generated as part of reasoning.
207
+ */
208
+ interface ReasoningFilePart {
209
+ type: 'reasoning-file';
210
+ /**
211
+ * Reasoning file data.
212
+ *
213
+ * Reasoning files originate from a model's reasoning output and are always
214
+ * raw bytes or a fetchable URL. Unlike `FilePart.data`, the `reference` and
215
+ * `text` shapes are not supported here: provider references describe files
216
+ * uploaded by the user (not produced as model output), and reasoning text is
217
+ * carried by `ReasoningPart` rather than as a file.
218
+ *
219
+ * Either a tagged shape or a bare shorthand:
220
+ *
221
+ * - `{ type: 'data', data }` or bare `DataContent`: raw bytes
222
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
223
+ * - `{ type: 'url', url }` or bare `URL`: a URL that points to the file
224
+ */
225
+ data: FileDataData | FileDataUrl | DataContent | URL;
226
+ /**
227
+ * IANA media type of the file.
228
+ *
229
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
230
+ */
231
+ mediaType: string;
232
+ /**
233
+ * Additional provider-specific metadata. They are passed through
234
+ * to the provider from the AI SDK and enable provider-specific
235
+ * functionality that can be fully encapsulated in the provider.
236
+ */
237
+ providerOptions?: ProviderOptions;
238
+ }
239
+ /**
240
+ * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
241
+ */
242
+ interface ToolCallPart {
243
+ type: 'tool-call';
244
+ /**
245
+ * ID of the tool call. This ID is used to match the tool call with the tool result.
246
+ */
247
+ toolCallId: string;
248
+ /**
249
+ * Name of the tool that is being called.
250
+ */
251
+ toolName: string;
252
+ /**
253
+ * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
254
+ */
255
+ input: unknown;
256
+ /**
257
+ * Additional provider-specific metadata. They are passed through
258
+ * to the provider from the AI SDK and enable provider-specific
259
+ * functionality that can be fully encapsulated in the provider.
260
+ */
261
+ providerOptions?: ProviderOptions;
262
+ /**
263
+ * Whether the tool call was executed by the provider.
264
+ */
265
+ providerExecuted?: boolean;
266
+ }
267
+ /**
268
+ * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
269
+ */
270
+ interface ToolResultPart {
271
+ type: 'tool-result';
272
+ /**
273
+ * ID of the tool call that this result is associated with.
274
+ */
275
+ toolCallId: string;
276
+ /**
277
+ * Name of the tool that generated this result.
278
+ */
279
+ toolName: string;
280
+ /**
281
+ * Result of the tool call. This is a JSON-serializable object.
282
+ */
283
+ output: ToolResultOutput;
284
+ /**
285
+ * Additional provider-specific metadata. They are passed through
286
+ * to the provider from the AI SDK and enable provider-specific
287
+ * functionality that can be fully encapsulated in the provider.
288
+ */
289
+ providerOptions?: ProviderOptions;
290
+ }
291
+ /**
292
+ * Output of a tool result.
293
+ */
294
+ type ToolResultOutput = {
295
+ /**
296
+ * Text tool output that should be directly sent to the API.
297
+ */
298
+ type: 'text';
299
+ value: string;
300
+ /**
301
+ * Provider-specific options.
302
+ */
303
+ providerOptions?: ProviderOptions;
304
+ } | {
305
+ type: 'json';
306
+ value: JSONValue;
307
+ /**
308
+ * Provider-specific options.
309
+ */
310
+ providerOptions?: ProviderOptions;
311
+ } | {
312
+ /**
313
+ * Type when the user has denied the execution of the tool call.
314
+ */
315
+ type: 'execution-denied';
316
+ /**
317
+ * Optional reason for the execution denial.
318
+ */
319
+ reason?: string;
320
+ /**
321
+ * Provider-specific options.
322
+ */
323
+ providerOptions?: ProviderOptions;
324
+ } | {
325
+ type: 'error-text';
326
+ value: string;
327
+ /**
328
+ * Provider-specific options.
329
+ */
330
+ providerOptions?: ProviderOptions;
331
+ } | {
332
+ type: 'error-json';
333
+ value: JSONValue;
334
+ /**
335
+ * Provider-specific options.
336
+ */
337
+ providerOptions?: ProviderOptions;
338
+ } | {
339
+ type: 'content';
340
+ value: Array<{
341
+ type: 'text';
342
+ /**
343
+ * Text content.
344
+ */
345
+ text: string;
346
+ /**
347
+ * Provider-specific options.
348
+ */
349
+ providerOptions?: ProviderOptions;
350
+ } | {
351
+ type: 'file';
352
+ /**
353
+ * File data as a tagged discriminated union:
354
+ *
355
+ * - `{ type: 'data', data }`: raw bytes
356
+ * (base64 string, Uint8Array, ArrayBuffer, Buffer)
357
+ * - `{ type: 'url', url }`: a URL that points to the file
358
+ * - `{ type: 'reference', reference }`: a provider reference
359
+ * from `uploadFile`
360
+ * - `{ type: 'text', text }`: inline text content (e.g. an inline
361
+ * text document)
362
+ */
363
+ data: FileData;
364
+ /**
365
+ * Either a full IANA media type (`type/subtype`, e.g. `image/png`) or just
366
+ * the top-level IANA segment (e.g. `image`, `audio`, `video`, `text`).
367
+ *
368
+ * `*`-subtype wildcards (e.g. `image/*`) are normalized as equivalent to the
369
+ * top-level segment alone (e.g. `image`). Providers can use the helpers in
370
+ * `@ai-sdk/provider-utils` (`isFullMediaType`, `getTopLevelMediaType`,
371
+ * `detectMediaType`) to resolve the field according to their API
372
+ * requirements.
373
+ *
374
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
375
+ */
376
+ mediaType: string;
377
+ /**
378
+ * Optional filename of the file.
379
+ */
380
+ filename?: string;
381
+ /**
382
+ * Provider-specific options.
383
+ */
384
+ providerOptions?: ProviderOptions;
385
+ } | {
386
+ /**
387
+ * @deprecated Use 'file' with mediaType + tagged data instead:
388
+ * `{ type: 'file', mediaType, data: { type: 'data', data } }`.
389
+ */
390
+ type: 'file-data';
391
+ /**
392
+ * Base-64 encoded media data.
393
+ */
394
+ data: string;
395
+ /**
396
+ * IANA media type.
397
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
398
+ */
399
+ mediaType: string;
400
+ /**
401
+ * Optional filename of the file.
402
+ */
403
+ filename?: string;
404
+ /**
405
+ * Provider-specific options.
406
+ */
407
+ providerOptions?: ProviderOptions;
408
+ } | {
409
+ /**
410
+ * @deprecated Use 'file' with mediaType and tagged data instead:
411
+ * `{ type: 'file', mediaType, data: { type: 'url', url: new URL(url) } }`.
412
+ */
413
+ type: 'file-url';
414
+ /**
415
+ * URL of the file.
416
+ */
417
+ url: string;
418
+ /**
419
+ * IANA media type.
420
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
421
+ */
422
+ mediaType?: string;
423
+ /**
424
+ * Provider-specific options.
425
+ */
426
+ providerOptions?: ProviderOptions;
427
+ } | {
428
+ /**
429
+ * @deprecated Use 'file' with tagged data instead:
430
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
431
+ */
432
+ type: 'file-id';
433
+ /**
434
+ * ID of the file.
435
+ *
436
+ * If you use multiple providers, you need to
437
+ * specify the provider specific ids using
438
+ * the Record option. The key is the provider
439
+ * name, e.g. 'openai' or 'anthropic'.
440
+ */
441
+ fileId: string | Record<string, string>;
442
+ /**
443
+ * Provider-specific options.
444
+ */
445
+ providerOptions?: ProviderOptions;
446
+ } | {
447
+ /**
448
+ * @deprecated Use 'file' with tagged data instead:
449
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
450
+ */
451
+ type: 'file-reference';
452
+ /**
453
+ * Provider-specific references for the file.
454
+ * The key is the provider name, e.g. 'openai' or 'anthropic'.
455
+ */
456
+ providerReference: ProviderReference;
457
+ /**
458
+ * Provider-specific options.
459
+ */
460
+ providerOptions?: ProviderOptions;
461
+ } | {
462
+ /**
463
+ * @deprecated Use 'file' with mediaType (e.g. 'image' or a specific
464
+ * `image/*` subtype) and tagged data instead:
465
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
466
+ */
467
+ type: 'image-data';
468
+ /**
469
+ * Base-64 encoded image data.
470
+ */
471
+ data: string;
472
+ /**
473
+ * IANA media type.
474
+ * @see https://www.iana.org/assignments/media-types/media-types.xhtml
475
+ */
476
+ mediaType: string;
477
+ /**
478
+ * Provider-specific options.
479
+ */
480
+ providerOptions?: ProviderOptions;
481
+ } | {
482
+ /**
483
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
484
+ * `image/*` subtype) and tagged data instead:
485
+ * `{ type: 'file', mediaType: 'image', data: { type: 'url', url: new URL(url) } }`.
486
+ */
487
+ type: 'image-url';
488
+ /**
489
+ * URL of the image.
490
+ */
491
+ url: string;
492
+ /**
493
+ * Provider-specific options.
494
+ */
495
+ providerOptions?: ProviderOptions;
496
+ } | {
497
+ /**
498
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
499
+ * `image/*` subtype) and tagged data instead:
500
+ * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`.
501
+ */
502
+ type: 'image-file-id';
503
+ /**
504
+ * Image that is referenced using a provider file id.
505
+ *
506
+ * If you use multiple providers, you need to
507
+ * specify the provider specific ids using
508
+ * the Record option. The key is the provider
509
+ * name, e.g. 'openai' or 'anthropic'.
510
+ */
511
+ fileId: string | Record<string, string>;
512
+ /**
513
+ * Provider-specific options.
514
+ */
515
+ providerOptions?: ProviderOptions;
516
+ } | {
517
+ /**
518
+ * @deprecated Use 'file' with `mediaType: 'image'` (or a specific
519
+ * `image/*` subtype) and tagged data instead:
520
+ * `{ type: 'file', mediaType: 'image', data: { type: 'reference', reference } }`.
521
+ */
522
+ type: 'image-file-reference';
523
+ /**
524
+ * Provider-specific references for the image file.
525
+ * The key is the provider name, e.g. 'openai' or 'anthropic'.
526
+ */
527
+ providerReference: ProviderReference;
528
+ /**
529
+ * Provider-specific options.
530
+ */
531
+ providerOptions?: ProviderOptions;
532
+ } | {
533
+ /**
534
+ * Custom content part. This can be used to implement
535
+ * provider-specific content parts.
536
+ */
537
+ type: 'custom';
538
+ /**
539
+ * Provider-specific options.
540
+ */
541
+ providerOptions?: ProviderOptions;
542
+ }>;
543
+ };
544
+
545
+ type InlineFileData = Extract<FilePart['data'], {
546
+ type: 'data';
547
+ } | {
548
+ type: 'text';
549
+ }>;
550
+ /**
551
+ * Converts inline file data (a tagged `data` or `text` shape) into raw bytes.
552
+ *
553
+ * - `{ type: 'text', text }` → UTF-8 encoded bytes
554
+ * - `{ type: 'data', data: Uint8Array | Buffer }` → returned as-is
555
+ * - `{ type: 'data', data: ArrayBuffer }` → wrapped in a `Uint8Array`
556
+ * - `{ type: 'data', data: string }` → decoded as base64
557
+ */
558
+ declare function convertInlineFileDataToUint8Array(data: InlineFileData): Uint8Array;
559
+
560
+ /**
561
+ * Convert an ImageModelV4File to a URL or data URI string.
562
+ *
563
+ * If the file is a URL, it returns the URL as-is.
564
+ * If the file is base64 data, it returns a data URI with the base64 data.
565
+ * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
566
+ */
567
+ declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
568
+
569
+ /**
570
+ * Converts an input object to FormData for multipart/form-data requests.
571
+ *
572
+ * Handles the following cases:
573
+ * - `null` or `undefined` values are skipped
574
+ * - Arrays with a single element are appended as a single value
575
+ * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
576
+ * unless `useArrayBrackets` is set to `false`
577
+ * - All other values are appended directly
578
+ *
579
+ * @param input - The input object to convert. Use a generic type for type validation.
580
+ * @param options - Optional configuration object.
581
+ * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
582
+ * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
583
+ * @returns A FormData object containing the input values.
584
+ *
585
+ * @example
586
+ * ```ts
587
+ * type MyInput = {
588
+ * model: string;
589
+ * prompt: string;
590
+ * images: Blob[];
591
+ * };
592
+ *
593
+ * const formData = convertToFormData<MyInput>({
594
+ * model: 'gpt-image-1',
595
+ * prompt: 'A cat',
596
+ * images: [blob1, blob2],
597
+ * });
598
+ * ```
599
+ */
600
+ declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
601
+ useArrayBrackets?: boolean;
602
+ }): FormData;
603
+
19
604
  /**
20
605
  * Interface for mapping between custom tool names and provider tool names.
21
606
  */
@@ -82,58 +667,44 @@ declare class DelayedPromise<T> {
82
667
  }
83
668
 
84
669
  /**
85
- * Extracts the headers from a response object and returns them as a key-value object.
670
+ * Detect the IANA media type of a file from its raw bytes or base64 string.
86
671
  *
87
- * @param response - The response object to extract headers from.
88
- * @returns The headers as a key-value object.
89
- */
90
- declare function extractResponseHeaders(response: Response): {
91
- [k: string]: string;
92
- };
93
-
94
- /**
95
- * Convert an ImageModelV4File to a URL or data URI string.
96
- *
97
- * If the file is a URL, it returns the URL as-is.
98
- * If the file is base64 data, it returns a data URI with the base64 data.
99
- * If the file is a Uint8Array, it converts it to base64 and returns a data URI.
100
- */
101
- declare function convertImageModelFileToDataUri(file: ImageModelV4File): string;
102
-
103
- /**
104
- * Converts an input object to FormData for multipart/form-data requests.
105
- *
106
- * Handles the following cases:
107
- * - `null` or `undefined` values are skipped
108
- * - Arrays with a single element are appended as a single value
109
- * - Arrays with multiple elements are appended with `[]` suffix (e.g., `image[]`)
110
- * unless `useArrayBrackets` is set to `false`
111
- * - All other values are appended directly
112
- *
113
- * @param input - The input object to convert. Use a generic type for type validation.
114
- * @param options - Optional configuration object.
115
- * @param options.useArrayBrackets - Whether to add `[]` suffix for multi-element arrays.
116
- * Defaults to `true`. Set to `false` for APIs that expect repeated keys without brackets.
117
- * @returns A FormData object containing the input values.
118
- *
119
- * @example
120
- * ```ts
121
- * type MyInput = {
122
- * model: string;
123
- * prompt: string;
124
- * images: Blob[];
125
- * };
672
+ * - When `topLevelType` is omitted, every known signature is considered
673
+ * (image, audio, video, and application). Returns `undefined` when the
674
+ * bytes do not match any known signature.
675
+ * - When `topLevelType` is provided, only signatures for that top-level
676
+ * segment are considered. Returns `undefined` for unsupported segments
677
+ * (e.g. `"text"`) or when no signature matches.
678
+ */
679
+ declare function detectMediaType({ data, topLevelType, }: {
680
+ data: Uint8Array | string;
681
+ topLevelType?: string;
682
+ }): string | undefined;
683
+ /**
684
+ * Returns the top-level segment of a media type (the portion before `/`).
126
685
  *
127
- * const formData = convertToFormData<MyInput>({
128
- * model: 'gpt-image-1',
129
- * prompt: 'A cat',
130
- * images: [blob1, blob2],
131
- * });
132
- * ```
686
+ * Examples:
687
+ * - `"image/png"` -> `"image"`
688
+ * - `"image/*"` -> `"image"`
689
+ * - `"image"` -> `"image"`
690
+ * - `"image/"` -> `"image"`
691
+ * - `""` -> `""`
692
+ * - `"/"` -> `""`
133
693
  */
134
- declare function convertToFormData<T extends Record<string, unknown>>(input: T, options?: {
135
- useArrayBrackets?: boolean;
136
- }): FormData;
694
+ declare function getTopLevelMediaType(mediaType: string): string;
695
+ /**
696
+ * Returns `true` only when the given media type has a non-empty, non-wildcard
697
+ * subtype (i.e. matches the form `type/subtype`, and `subtype` is not `*`).
698
+ *
699
+ * Examples:
700
+ * - `"image/png"` -> `true`
701
+ * - `"image/*"` -> `false`
702
+ * - `"image"` -> `false`
703
+ * - `"image/"` -> `false`
704
+ * - `""` -> `false`
705
+ * - `"/"` -> `false`
706
+ */
707
+ declare function isFullMediaType(mediaType: string): boolean;
137
708
 
138
709
  /**
139
710
  * Download a file from a URL and return it as a Blob.
@@ -168,41 +739,73 @@ declare class DownloadError extends AISDKError {
168
739
  }
169
740
 
170
741
  /**
171
- * Default maximum download size: 2 GiB.
742
+ * Fetches a URL while enforcing the SSRF download guard on every hop.
172
743
  *
173
- * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
174
- * body internally, then creates the JS ArrayBuffer), so very large downloads
175
- * risk exceeding the default V8 heap limit on 64-bit systems and terminating
176
- * the process with an out-of-memory error.
744
+ * Redirects are followed manually (`redirect: 'manual'`) so each hop is
745
+ * validated with {@link validateDownloadUrl} *before* it is requested. Relying
746
+ * on the default `redirect: 'follow'` would issue the request to a redirect
747
+ * target (e.g. an internal address) before we ever see its URL, defeating the
748
+ * SSRF guard.
177
749
  *
178
- * Setting this limit converts an unrecoverable OOM crash into a catchable
179
- * `DownloadError`.
750
+ * A `redirect: 'manual'` request yields an unreadable opaque response in the
751
+ * browser (and in other spec-compliant fetch implementations), so the redirect
752
+ * target cannot be validated here. In a real browser this is safe to follow
753
+ * natively because SSRF is not reachable (fetch is constrained by CORS and
754
+ * cannot reach a server's internal network or cloud-metadata). On any other
755
+ * runtime we cannot validate the hop, so we fail closed rather than follow it
756
+ * blindly and bypass the SSRF guard.
757
+ *
758
+ * The returned response is the final (non-redirect) response. The caller is
759
+ * responsible for checking `response.ok` and reading the body.
760
+ *
761
+ * @throws DownloadError if a hop is unsafe, the redirect limit is exceeded, or
762
+ * a redirect cannot be validated on a non-browser runtime.
180
763
  */
181
- declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
764
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
765
+ url: string;
766
+ headers?: HeadersInit;
767
+ abortSignal?: AbortSignal;
768
+ maxRedirects?: number;
769
+ }): Promise<Response>;
770
+
182
771
  /**
183
- * Reads a fetch Response body with a size limit to prevent memory exhaustion.
772
+ * Extracts a 1-based inclusive line range from `text`, auto-detecting the
773
+ * file's line ending (`\r\n`, `\n`, or `\r`, in that priority).
184
774
  *
185
- * Checks the Content-Length header for early rejection, then reads the body
186
- * incrementally via ReadableStream and aborts with a DownloadError when the
187
- * limit is exceeded.
775
+ * Mixed line endings are not supported: detection picks one and uses it for
776
+ * both the split and the rejoin, so files that mix conventions will not slice
777
+ * cleanly. When neither `startLine` nor `endLine` is provided, the input is
778
+ * returned unchanged. `endLine` past EOF clamps to the last line.
779
+ */
780
+ declare function extractLines({ text, startLine, endLine, }: {
781
+ text: string;
782
+ startLine?: number;
783
+ endLine?: number;
784
+ }): string;
785
+
786
+ /**
787
+ * Extracts the headers from a response object and returns them as a key-value object.
188
788
  *
189
- * @param response - The fetch Response to read.
190
- * @param url - The URL being downloaded (used in error messages).
191
- * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
192
- * @returns A Uint8Array containing the response body.
193
- * @throws DownloadError if the response exceeds maxBytes.
789
+ * @param response - The response object to extract headers from.
790
+ * @returns The headers as a key-value object.
194
791
  */
195
- declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
196
- response: Response;
197
- url: string;
198
- maxBytes?: number;
199
- }): Promise<Uint8Array>;
792
+ declare function extractResponseHeaders(response: Response): {
793
+ [k: string]: string;
794
+ };
200
795
 
201
796
  /**
202
797
  * Fetch function type (standardizes the version of fetch used).
203
798
  */
204
799
  type FetchFunction = typeof globalThis.fetch;
205
800
 
801
+ /**
802
+ * Filters `null` and `undefined` values out of a list of values.
803
+ *
804
+ * @param values - The values to filter.
805
+ * @returns A new array containing only non-nullish values.
806
+ */
807
+ declare function filterNullable<T>(...values: Array<T | undefined | null>): Array<T>;
808
+
206
809
  /**
207
810
  * Creates an ID generator.
208
811
  * The total length of the ID is the sum of the prefix, separator, and random part length.
@@ -229,8 +832,6 @@ type IdGenerator = () => string;
229
832
  */
230
833
  declare const generateId: IdGenerator;
231
834
 
232
- declare function getErrorMessage(error: unknown | undefined): string;
233
-
234
835
  /**
235
836
  * Used to mark schemas so we can support both Zod and custom schemas.
236
837
  */
@@ -384,6 +985,13 @@ declare const getFromApi: <T>({ url, headers, successfulResponseHandler, failedR
384
985
 
385
986
  declare function getRuntimeEnvironmentUserAgent(globalThisAny?: any): string;
386
987
 
988
+ /**
989
+ * Checks if an object has required keys.
990
+ * @param OBJECT - The object to check.
991
+ * @returns True if the object has required keys, false otherwise.
992
+ */
993
+ type HasRequiredKey<OBJECT> = {} extends OBJECT ? false : true;
994
+
387
995
  declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix, }: {
388
996
  messages: LanguageModelV4Prompt;
389
997
  schema?: JSONSchema7;
@@ -393,6 +1001,38 @@ declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPre
393
1001
 
394
1002
  declare function isAbortError(error: unknown): error is Error;
395
1003
 
1004
+ /**
1005
+ * Returns `true` when running in a browser.
1006
+ *
1007
+ * Detection keys on the presence of a global `window`, matching the browser
1008
+ * check used elsewhere in this package (see `getRuntimeEnvironmentUserAgent`)
1009
+ * so the SDK has a single, consistent definition of "browser". Server runtimes
1010
+ * (Node.js, Deno, Bun, edge/workers) do not define `window`.
1011
+ */
1012
+ declare function isBrowserRuntime(globalThisAny?: any): boolean;
1013
+
1014
+ /**
1015
+ * Type-guard for Node.js `Buffer` instances.
1016
+ *
1017
+ * Uses optional chaining on `globalThis.Buffer` so it returns `false` in
1018
+ * runtimes where `Buffer` is not available (e.g. CloudFlare Workers).
1019
+ */
1020
+ declare function isBuffer(value: unknown): value is Buffer;
1021
+
1022
+ /**
1023
+ * Returns true when `url` has the same origin (scheme + host + port) as
1024
+ * `baseUrl`.
1025
+ *
1026
+ * Used to decide whether provider credentials may be attached to a request to a
1027
+ * URL taken from a provider response (e.g. a polling or media-download URL).
1028
+ * Credentials must only be sent to the provider's own origin; a response that
1029
+ * names a foreign host (a CDN, or an attacker-controlled host if the response
1030
+ * is tampered with) must not receive the API key.
1031
+ *
1032
+ * Returns false if either value is not a valid absolute URL (fail-closed).
1033
+ */
1034
+ declare function isSameOrigin(url: string, baseUrl: string): boolean;
1035
+
396
1036
  /**
397
1037
  * Type guard that checks whether a value is not `null` or `undefined`.
398
1038
  *
@@ -402,10 +1042,19 @@ declare function isAbortError(error: unknown): error is Error;
402
1042
  */
403
1043
  declare function isNonNullable<T>(value: T | undefined | null): value is NonNullable<T>;
404
1044
 
1045
+ /**
1046
+ * Checks whether a value is a provider reference (a mapping of provider names
1047
+ * to provider-specific identifiers) as opposed to raw bytes, a URL, or a
1048
+ * tagged `{ type: ... }` object.
1049
+ */
1050
+ declare function isProviderReference(data: unknown): data is SharedV4ProviderReference;
1051
+
405
1052
  /**
406
1053
  * Checks if the given URL is supported natively by the model.
407
1054
  *
408
- * @param mediaType - The media type of the URL. Case-sensitive.
1055
+ * @param mediaType - The media type of the URL. Case-sensitive. May be a full
1056
+ * `type/subtype`, a wildcard `type/*`, or just the
1057
+ * top-level segment (e.g. `image`).
409
1058
  * @param url - The URL to check.
410
1059
  * @param supportedUrls - A record where keys are case-sensitive media types (or '*')
411
1060
  * and values are arrays of RegExp patterns for URLs.
@@ -454,6 +1103,44 @@ declare function loadSetting({ settingValue, environmentVariableName, settingNam
454
1103
  description: string;
455
1104
  }): string;
456
1105
 
1106
+ type ReasoningLevel = Exclude<LanguageModelV4CallOptions['reasoning'], 'none' | 'provider-default' | undefined>;
1107
+ declare function isCustomReasoning(reasoning: LanguageModelV4CallOptions['reasoning']): reasoning is Exclude<LanguageModelV4CallOptions['reasoning'], 'provider-default' | undefined>;
1108
+ /**
1109
+ * Maps a top-level reasoning level to a provider-specific effort string using
1110
+ * the given effort map. Pushes a compatibility warning if the reasoning level
1111
+ * maps to a different string, or an unsupported warning if the level is not
1112
+ * present in the map.
1113
+ *
1114
+ * @returns The mapped effort string, or `undefined` if the level is not
1115
+ * supported.
1116
+ */
1117
+ declare function mapReasoningToProviderEffort<T extends string>({ reasoning, effortMap, warnings, }: {
1118
+ reasoning: ReasoningLevel;
1119
+ effortMap: Partial<Record<ReasoningLevel, T>>;
1120
+ warnings: SharedV4Warning[];
1121
+ }): T | undefined;
1122
+ /**
1123
+ * Maps a top-level reasoning level to an absolute token budget by multiplying
1124
+ * the model's max output tokens by a percentage from the budget percentages
1125
+ * map. The result is clamped between `minReasoningBudget` (default 1024) and
1126
+ * `maxReasoningBudget`. Pushes an unsupported warning if the level is not
1127
+ * present in the budget percentages map.
1128
+ *
1129
+ * @returns The computed token budget, or `undefined` if the level is not
1130
+ * supported.
1131
+ */
1132
+ declare function mapReasoningToProviderBudget({ reasoning, maxOutputTokens, maxReasoningBudget, minReasoningBudget, budgetPercentages, warnings, }: {
1133
+ reasoning: ReasoningLevel;
1134
+ maxOutputTokens: number;
1135
+ maxReasoningBudget: number;
1136
+ minReasoningBudget?: number;
1137
+ budgetPercentages?: Partial<Record<ReasoningLevel, number>>;
1138
+ warnings: SharedV4Warning[];
1139
+ }): number | undefined;
1140
+
1141
+ /**
1142
+ * A value that can be provided either synchronously or as a promise-like.
1143
+ */
457
1144
  type MaybePromiseLike<T> = T | PromiseLike<T>;
458
1145
 
459
1146
  /**
@@ -529,357 +1216,27 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
529
1216
  fetch?: FetchFunction;
530
1217
  }) => Promise<{
531
1218
  value: T;
532
- rawValue?: unknown;
533
- responseHeaders?: Record<string, string>;
534
- }>;
535
-
536
- /**
537
- * Data content. Can either be a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer.
538
- */
539
- type DataContent = string | Uint8Array | ArrayBuffer | Buffer;
540
-
541
- /**
542
- * Additional provider-specific options.
543
- *
544
- * They are passed through to the provider from the AI SDK and enable
545
- * provider-specific functionality that can be fully encapsulated in the provider.
546
- */
547
- type ProviderOptions = SharedV4ProviderOptions;
548
-
549
- /**
550
- * Text content part of a prompt. It contains a string of text.
551
- */
552
- interface TextPart {
553
- type: 'text';
554
- /**
555
- * The text content.
556
- */
557
- text: string;
558
- /**
559
- * Additional provider-specific metadata. They are passed through
560
- * to the provider from the AI SDK and enable provider-specific
561
- * functionality that can be fully encapsulated in the provider.
562
- */
563
- providerOptions?: ProviderOptions;
564
- }
565
- /**
566
- * Image content part of a prompt. It contains an image.
567
- */
568
- interface ImagePart {
569
- type: 'image';
570
- /**
571
- * Image data. Can either be:
572
- *
573
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
574
- * - URL: a URL that points to the image
575
- */
576
- image: DataContent | URL;
577
- /**
578
- * Optional IANA media type of the image.
579
- *
580
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
581
- */
582
- mediaType?: string;
583
- /**
584
- * Additional provider-specific metadata. They are passed through
585
- * to the provider from the AI SDK and enable provider-specific
586
- * functionality that can be fully encapsulated in the provider.
587
- */
588
- providerOptions?: ProviderOptions;
589
- }
590
- /**
591
- * File content part of a prompt. It contains a file.
592
- */
593
- interface FilePart {
594
- type: 'file';
595
- /**
596
- * File data. Can either be:
597
- *
598
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
599
- * - URL: a URL that points to the image
600
- */
601
- data: DataContent | URL;
602
- /**
603
- * Optional filename of the file.
604
- */
605
- filename?: string;
606
- /**
607
- * IANA media type of the file.
608
- *
609
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
610
- */
611
- mediaType: string;
612
- /**
613
- * Additional provider-specific metadata. They are passed through
614
- * to the provider from the AI SDK and enable provider-specific
615
- * functionality that can be fully encapsulated in the provider.
616
- */
617
- providerOptions?: ProviderOptions;
618
- }
619
- /**
620
- * Reasoning content part of a prompt. It contains a reasoning.
621
- */
622
- interface ReasoningPart {
623
- type: 'reasoning';
624
- /**
625
- * The reasoning text.
626
- */
627
- text: string;
628
- /**
629
- * Additional provider-specific metadata. They are passed through
630
- * to the provider from the AI SDK and enable provider-specific
631
- * functionality that can be fully encapsulated in the provider.
632
- */
633
- providerOptions?: ProviderOptions;
634
- }
635
- /**
636
- * Reasoning file content part of a prompt. It contains a file generated as part of reasoning.
637
- */
638
- interface ReasoningFilePart {
639
- type: 'reasoning-file';
640
- /**
641
- * File data. Can either be:
642
- *
643
- * - data: a base64-encoded string, a Uint8Array, an ArrayBuffer, or a Buffer
644
- * - URL: a URL that points to the file
645
- */
646
- data: DataContent | URL;
647
- /**
648
- * IANA media type of the file.
649
- *
650
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
651
- */
652
- mediaType: string;
653
- /**
654
- * Additional provider-specific metadata. They are passed through
655
- * to the provider from the AI SDK and enable provider-specific
656
- * functionality that can be fully encapsulated in the provider.
657
- */
658
- providerOptions?: ProviderOptions;
659
- }
660
- /**
661
- * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).
662
- */
663
- interface ToolCallPart {
664
- type: 'tool-call';
665
- /**
666
- * ID of the tool call. This ID is used to match the tool call with the tool result.
667
- */
668
- toolCallId: string;
669
- /**
670
- * Name of the tool that is being called.
671
- */
672
- toolName: string;
673
- /**
674
- * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.
675
- */
676
- input: unknown;
677
- /**
678
- * Additional provider-specific metadata. They are passed through
679
- * to the provider from the AI SDK and enable provider-specific
680
- * functionality that can be fully encapsulated in the provider.
681
- */
682
- providerOptions?: ProviderOptions;
683
- /**
684
- * Whether the tool call was executed by the provider.
685
- */
686
- providerExecuted?: boolean;
687
- }
688
- /**
689
- * Tool result content part of a prompt. It contains the result of the tool call with the matching ID.
690
- */
691
- interface ToolResultPart {
692
- type: 'tool-result';
693
- /**
694
- * ID of the tool call that this result is associated with.
695
- */
696
- toolCallId: string;
697
- /**
698
- * Name of the tool that generated this result.
699
- */
700
- toolName: string;
701
- /**
702
- * Result of the tool call. This is a JSON-serializable object.
703
- */
704
- output: ToolResultOutput;
705
- /**
706
- * Additional provider-specific metadata. They are passed through
707
- * to the provider from the AI SDK and enable provider-specific
708
- * functionality that can be fully encapsulated in the provider.
709
- */
710
- providerOptions?: ProviderOptions;
711
- }
1219
+ rawValue?: unknown;
1220
+ responseHeaders?: Record<string, string>;
1221
+ }>;
1222
+
712
1223
  /**
713
- * Output of a tool result.
1224
+ * A context object that is passed into tool execution.
714
1225
  */
715
- type ToolResultOutput = {
716
- /**
717
- * Text tool output that should be directly sent to the API.
718
- */
719
- type: 'text';
720
- value: string;
721
- /**
722
- * Provider-specific options.
723
- */
724
- providerOptions?: ProviderOptions;
725
- } | {
726
- type: 'json';
727
- value: JSONValue;
728
- /**
729
- * Provider-specific options.
730
- */
731
- providerOptions?: ProviderOptions;
732
- } | {
733
- /**
734
- * Type when the user has denied the execution of the tool call.
735
- */
736
- type: 'execution-denied';
737
- /**
738
- * Optional reason for the execution denial.
739
- */
740
- reason?: string;
741
- /**
742
- * Provider-specific options.
743
- */
744
- providerOptions?: ProviderOptions;
745
- } | {
746
- type: 'error-text';
747
- value: string;
748
- /**
749
- * Provider-specific options.
750
- */
751
- providerOptions?: ProviderOptions;
752
- } | {
753
- type: 'error-json';
754
- value: JSONValue;
755
- /**
756
- * Provider-specific options.
757
- */
758
- providerOptions?: ProviderOptions;
759
- } | {
760
- type: 'content';
761
- value: Array<{
762
- type: 'text';
763
- /**
764
- * Text content.
765
- */
766
- text: string;
767
- /**
768
- * Provider-specific options.
769
- */
770
- providerOptions?: ProviderOptions;
771
- } | {
772
- /**
773
- * @deprecated Use image-data or file-data instead.
774
- */
775
- type: 'media';
776
- data: string;
777
- mediaType: string;
778
- } | {
779
- type: 'file-data';
780
- /**
781
- * Base-64 encoded media data.
782
- */
783
- data: string;
784
- /**
785
- * IANA media type.
786
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
787
- */
788
- mediaType: string;
789
- /**
790
- * Optional filename of the file.
791
- */
792
- filename?: string;
793
- /**
794
- * Provider-specific options.
795
- */
796
- providerOptions?: ProviderOptions;
797
- } | {
798
- type: 'file-url';
799
- /**
800
- * URL of the file.
801
- */
802
- url: string;
803
- /**
804
- * Provider-specific options.
805
- */
806
- providerOptions?: ProviderOptions;
807
- } | {
808
- type: 'file-id';
809
- /**
810
- * ID of the file.
811
- *
812
- * If you use multiple providers, you need to
813
- * specify the provider specific ids using
814
- * the Record option. The key is the provider
815
- * name, e.g. 'openai' or 'anthropic'.
816
- */
817
- fileId: string | Record<string, string>;
818
- /**
819
- * Provider-specific options.
820
- */
821
- providerOptions?: ProviderOptions;
822
- } | {
823
- /**
824
- * Images that are referenced using base64 encoded data.
825
- */
826
- type: 'image-data';
827
- /**
828
- * Base-64 encoded image data.
829
- */
830
- data: string;
831
- /**
832
- * IANA media type.
833
- * @see https://www.iana.org/assignments/media-types/media-types.xhtml
834
- */
835
- mediaType: string;
836
- /**
837
- * Provider-specific options.
838
- */
839
- providerOptions?: ProviderOptions;
840
- } | {
841
- /**
842
- * Images that are referenced using a URL.
843
- */
844
- type: 'image-url';
845
- /**
846
- * URL of the image.
847
- */
848
- url: string;
849
- /**
850
- * Provider-specific options.
851
- */
852
- providerOptions?: ProviderOptions;
853
- } | {
854
- /**
855
- * Images that are referenced using a provider file id.
856
- */
857
- type: 'image-file-id';
858
- /**
859
- * Image that is referenced using a provider file id.
860
- *
861
- * If you use multiple providers, you need to
862
- * specify the provider specific ids using
863
- * the Record option. The key is the provider
864
- * name, e.g. 'openai' or 'anthropic'.
865
- */
866
- fileId: string | Record<string, string>;
867
- /**
868
- * Provider-specific options.
869
- */
870
- providerOptions?: ProviderOptions;
871
- } | {
872
- /**
873
- * Custom content part. This can be used to implement
874
- * provider-specific content parts.
875
- */
876
- type: 'custom';
877
- /**
878
- * Provider-specific options.
879
- */
880
- providerOptions?: ProviderOptions;
881
- }>;
1226
+ type Context = Record<string, unknown>;
1227
+
1228
+ /**
1229
+ * A tool that is guaranteed to expose an execute function.
1230
+ */
1231
+ type ExecutableTool<TOOL extends Tool = Tool> = TOOL & {
1232
+ execute: NonNullable<TOOL['execute']>;
882
1233
  };
1234
+ /**
1235
+ * Checks whether a tool exposes an execute function.
1236
+ */
1237
+ declare function isExecutableTool<TOOL extends Tool>(tool: TOOL | undefined): tool is ExecutableTool<TOOL>;
1238
+
1239
+ type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
883
1240
 
884
1241
  /**
885
1242
  * Tool approval request prompt part.
@@ -894,6 +1251,17 @@ type ToolApprovalRequest = {
894
1251
  * ID of the tool call that the approval request is for.
895
1252
  */
896
1253
  toolCallId: string;
1254
+ /**
1255
+ * Flag indicating whether the tool was automatically approved or denied.
1256
+ *
1257
+ * @default false
1258
+ */
1259
+ isAutomatic?: boolean;
1260
+ /**
1261
+ * HMAC-SHA256 signature binding this approval to its tool call.
1262
+ * Present only when `experimental_toolApprovalSecret` is configured.
1263
+ */
1264
+ signature?: string;
897
1265
  };
898
1266
 
899
1267
  /**
@@ -913,7 +1281,7 @@ type AssistantModelMessage = {
913
1281
  * Content of an assistant message.
914
1282
  * It can be a string or an array of text, image, reasoning, redacted reasoning, and tool call parts.
915
1283
  */
916
- type AssistantContent = string | Array<TextPart | FilePart | ReasoningPart | ReasoningFilePart | ToolCallPart | ToolResultPart | ToolApprovalRequest>;
1284
+ type AssistantContent = string | Array<TextPart | CustomPart | FilePart | ReasoningPart | ReasoningFilePart | ToolCallPart | ToolResultPart | ToolApprovalRequest>;
917
1285
 
918
1286
  /**
919
1287
  * A system message. It can contain system information.
@@ -1000,9 +1368,189 @@ type UserContent = string | Array<TextPart | ImagePart | FilePart>;
1000
1368
  type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
1001
1369
 
1002
1370
  /**
1003
- * Additional options that are sent into each tool call.
1371
+ * Options for executing a command in the sandbox via `run` or `spawn`.
1372
+ */
1373
+ type SandboxProcessOptions = {
1374
+ /**
1375
+ * Command to execute in the sandbox.
1376
+ */
1377
+ command: string;
1378
+ /**
1379
+ * Working directory to execute the command in.
1380
+ */
1381
+ workingDirectory?: string;
1382
+ /**
1383
+ * Environment variables to set for this command. Merged with the
1384
+ * sandbox's default environment; values here take precedence.
1385
+ * Supporting environment variables as an option is preferable from a
1386
+ * security perspective, e.g. to avoid them leaking in logs.
1387
+ */
1388
+ env?: Record<string, string>;
1389
+ /**
1390
+ * Signal that can be used to abort the command. When aborted, the running
1391
+ * process is killed; for `spawn`, `wait()` rejects with the abort reason.
1392
+ */
1393
+ abortSignal?: AbortSignal;
1394
+ };
1395
+ /**
1396
+ * Options for reading a file from the sandbox.
1397
+ */
1398
+ type ReadFileOptions = {
1399
+ /**
1400
+ * Path of the file to read.
1401
+ */
1402
+ path: string;
1403
+ /**
1404
+ * Signal that can be used to abort the read.
1405
+ */
1406
+ abortSignal?: AbortSignal;
1407
+ };
1408
+ /**
1409
+ * Options for writing a file to the sandbox. `CONTENT` is the payload written
1410
+ * to the file: a byte stream, raw bytes, or a string.
1411
+ */
1412
+ type WriteFileOptions<CONTENT> = {
1413
+ /**
1414
+ * Path of the file to write.
1415
+ */
1416
+ path: string;
1417
+ /**
1418
+ * Content to write to the file.
1419
+ */
1420
+ content: CONTENT;
1421
+ /**
1422
+ * Signal that can be used to abort the write.
1423
+ */
1424
+ abortSignal?: AbortSignal;
1425
+ };
1426
+ /**
1427
+ * Sandbox session that can execute commands and read/write files.
1428
+ */
1429
+ type SandboxSession = {
1430
+ /**
1431
+ * Description of the sandbox environment that can be added to the agent's instructions
1432
+ * so that the agent knows about relevant details such as the root directory, exposed
1433
+ * ports, the public hostname, etc.
1434
+ */
1435
+ readonly description: string;
1436
+ /**
1437
+ * Read one file from the sandbox as a stream of bytes. Resolves to `null`
1438
+ * when the file does not exist.
1439
+ *
1440
+ * Relative path handling is implementation-defined. This is the lowest-level
1441
+ * read primitive; prefer `readBinaryFile` or `readTextFile` unless you need
1442
+ * to stream bytes.
1443
+ */
1444
+ readonly readFile: (options: ReadFileOptions) => PromiseLike<ReadableStream<Uint8Array> | null>;
1445
+ /**
1446
+ * Read one file from the sandbox as raw bytes. Resolves to `null` when the
1447
+ * file does not exist.
1448
+ */
1449
+ readonly readBinaryFile: (options: ReadFileOptions) => PromiseLike<Uint8Array | null>;
1450
+ /**
1451
+ * Read one text file from the sandbox, decoded using the requested encoding.
1452
+ * Resolves to `null` when the file does not exist.
1453
+ *
1454
+ * Line ranges are 1-based and inclusive. When `endLine` is past EOF the read
1455
+ * returns through EOF without error.
1456
+ */
1457
+ readonly readTextFile: (options: ReadFileOptions & {
1458
+ /**
1459
+ * Text encoding used to decode the file bytes. Defaults to `"utf-8"`.
1460
+ */
1461
+ encoding?: string;
1462
+ /**
1463
+ * 1-based inclusive start line. Defaults to 1.
1464
+ */
1465
+ startLine?: number;
1466
+ /**
1467
+ * 1-based inclusive end line. When past the file's line count, the read
1468
+ * returns through EOF without error.
1469
+ */
1470
+ endLine?: number;
1471
+ }) => PromiseLike<string | null>;
1472
+ /**
1473
+ * Write one file to the sandbox from a stream of bytes. Creates parent
1474
+ * directories recursively and overwrites any existing file.
1475
+ *
1476
+ * This is the lowest-level write primitive; prefer `writeBinaryFile` or
1477
+ * `writeTextFile` when the full content is already materialized in memory.
1478
+ */
1479
+ readonly writeFile: (options: WriteFileOptions<ReadableStream<Uint8Array>>) => PromiseLike<void>;
1480
+ /**
1481
+ * Write one file to the sandbox from raw bytes. Creates parent directories
1482
+ * recursively and overwrites any existing file.
1483
+ */
1484
+ readonly writeBinaryFile: (options: WriteFileOptions<Uint8Array>) => PromiseLike<void>;
1485
+ /**
1486
+ * Write one file to the sandbox from a string, encoded using the requested
1487
+ * encoding. Creates parent directories recursively and overwrites any
1488
+ * existing file.
1489
+ */
1490
+ readonly writeTextFile: (options: WriteFileOptions<string> & {
1491
+ /**
1492
+ * Text encoding used to encode the string to bytes. Defaults to `"utf-8"`.
1493
+ */
1494
+ encoding?: string;
1495
+ }) => PromiseLike<void>;
1496
+ /**
1497
+ * Spawn a long-running process in the sandbox. Returns immediately with a
1498
+ * handle that streams stdout/stderr, can be waited on, and can be killed.
1499
+ *
1500
+ * `run` is conceptually a thin wrapper over this primitive: spawn,
1501
+ * collect both streams to strings, await `wait()`, return the result.
1502
+ */
1503
+ readonly spawn: (options: SandboxProcessOptions) => PromiseLike<SandboxProcess>;
1504
+ /**
1505
+ * Run a command in the sandbox.
1506
+ */
1507
+ readonly run: (options: SandboxProcessOptions) => PromiseLike<{
1508
+ /**
1509
+ * Exit code returned by the command.
1510
+ */
1511
+ exitCode: number;
1512
+ /**
1513
+ * Standard output produced by the command.
1514
+ */
1515
+ stdout: string;
1516
+ /**
1517
+ * Standard error produced by the command.
1518
+ */
1519
+ stderr: string;
1520
+ }>;
1521
+ };
1522
+ /**
1523
+ * Handle to a long-running process started via `SandboxSession.spawn`.
1524
+ */
1525
+ type SandboxProcess = {
1526
+ /**
1527
+ * Process identifier, if the sandbox implementation exposes one.
1528
+ */
1529
+ readonly pid?: number;
1530
+ /**
1531
+ * Stream of bytes written by the process to standard output.
1532
+ */
1533
+ readonly stdout: ReadableStream<Uint8Array>;
1534
+ /**
1535
+ * Stream of bytes written by the process to standard error.
1536
+ */
1537
+ readonly stderr: ReadableStream<Uint8Array>;
1538
+ /**
1539
+ * Resolve when the process exits, yielding its exit code.
1540
+ */
1541
+ wait(): PromiseLike<{
1542
+ exitCode: number;
1543
+ }>;
1544
+ /**
1545
+ * Terminate the process. Idempotent.
1546
+ */
1547
+ kill(): PromiseLike<void>;
1548
+ };
1549
+
1550
+ /**
1551
+ * Additional options that are sent into each tool execution.
1004
1552
  */
1005
- interface ToolExecutionOptions {
1553
+ interface ToolExecutionOptions<CONTEXT extends Context | unknown | never> {
1006
1554
  /**
1007
1555
  * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1008
1556
  */
@@ -1017,7 +1565,8 @@ interface ToolExecutionOptions {
1017
1565
  */
1018
1566
  abortSignal?: AbortSignal;
1019
1567
  /**
1020
- * User-defined context.
1568
+ * Tool context as defined by the tool's context schema.
1569
+ * The tool context is specific to the tool and is passed to the tool execution.
1021
1570
  *
1022
1571
  * Treat the context object as immutable inside tools.
1023
1572
  * Mutating the context object can lead to race conditions and unexpected results
@@ -1025,15 +1574,24 @@ interface ToolExecutionOptions {
1025
1574
  *
1026
1575
  * If you need to mutate the context, analyze the tool calls and results
1027
1576
  * in `prepareStep` and update it there.
1028
- *
1029
- * Experimental (can break in patch releases).
1030
1577
  */
1031
- experimental_context?: unknown;
1578
+ context: CONTEXT;
1579
+ /**
1580
+ * The sandbox environment that the tool is operating in.
1581
+ */
1582
+ experimental_sandbox?: SandboxSession;
1032
1583
  }
1584
+ /**
1585
+ * Function that executes the tool and returns either a single result or a stream of results.
1586
+ */
1587
+ type ToolExecuteFunction<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: ToolExecutionOptions<CONTEXT>) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
1588
+
1033
1589
  /**
1034
1590
  * Function that is called to determine if the tool needs approval before it can be executed.
1591
+ *
1592
+ * @deprecated Tool approval is handled on a `generateText` / `streamText` level now.
1035
1593
  */
1036
- type ToolNeedsApprovalFunction<INPUT> = (input: INPUT, options: {
1594
+ type ToolNeedsApprovalFunction<INPUT, CONTEXT extends Context | unknown | never> = (input: INPUT, options: {
1037
1595
  /**
1038
1596
  * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1039
1597
  */
@@ -1044,15 +1602,29 @@ type ToolNeedsApprovalFunction<INPUT> = (input: INPUT, options: {
1044
1602
  */
1045
1603
  messages: ModelMessage[];
1046
1604
  /**
1047
- * Additional context.
1605
+ * Tool context as defined by the tool's context schema.
1606
+ * The tool context is specific to the tool and is passed to the tool execution.
1048
1607
  *
1049
- * Experimental (can break in patch releases).
1608
+ * Treat the context object as immutable inside tools.
1609
+ * Mutating the context object can lead to race conditions and unexpected results
1610
+ * when tools are called in parallel.
1611
+ *
1612
+ * If you need to mutate the context, analyze the tool calls and results
1613
+ * in `prepareStep` and update it there.
1050
1614
  */
1051
- experimental_context?: unknown;
1615
+ context: CONTEXT;
1052
1616
  }) => boolean | PromiseLike<boolean>;
1053
- type ToolExecuteFunction<INPUT, OUTPUT> = (input: INPUT, options: ToolExecutionOptions) => AsyncIterable<OUTPUT> | PromiseLike<OUTPUT> | OUTPUT;
1054
- type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
1055
- type ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<OUTPUT, {
1617
+
1618
+ /**
1619
+ * Helper type to determine the outputSchema and execute function properties of a tool.
1620
+ */
1621
+ type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context | unknown | never> = NeverOptional<OUTPUT, {
1622
+ /**
1623
+ * The optional schema of the output that the tool produces.
1624
+ *
1625
+ * If not provided, the output shape will be inferred from the execute function.
1626
+ */
1627
+ outputSchema?: FlexibleSchema<OUTPUT>;
1056
1628
  /**
1057
1629
  * An async function that is called with the arguments from the tool call and produces a result.
1058
1630
  * If not provided, the tool will not be executed automatically.
@@ -1060,27 +1632,24 @@ type ToolOutputProperties<INPUT, OUTPUT> = NeverOptional<OUTPUT, {
1060
1632
  * @args is the input of the tool call.
1061
1633
  * @options.abortSignal is a signal that can be used to abort the tool call.
1062
1634
  */
1063
- execute: ToolExecuteFunction<INPUT, OUTPUT>;
1064
- outputSchema?: FlexibleSchema<OUTPUT>;
1635
+ execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1065
1636
  } | {
1637
+ /**
1638
+ * The schema of the output that the tool produces.
1639
+ *
1640
+ * Required when no execute function is provided.
1641
+ */
1066
1642
  outputSchema: FlexibleSchema<OUTPUT>;
1067
1643
  execute?: never;
1068
1644
  }>;
1069
1645
  /**
1070
- * A tool contains the description and the schema of the input that the tool expects.
1071
- * This enables the language model to generate the input.
1072
- *
1073
- * The tool can also contain an optional execute function for the actual execution function of the tool.
1646
+ * Common properties shared by all tool kinds.
1074
1647
  */
1075
- type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any> = {
1076
- /**
1077
- * An optional description of what the tool does.
1078
- * Will be used by the language model to decide whether to use the tool.
1079
- * Not used for provider-defined tools.
1080
- */
1081
- description?: string;
1648
+ type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = {
1082
1649
  /**
1083
1650
  * An optional title of the tool.
1651
+ *
1652
+ * @deprecated Use `providerMetadata` for source-specific tool display metadata.
1084
1653
  */
1085
1654
  title?: string;
1086
1655
  /**
@@ -1089,6 +1658,16 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1089
1658
  * functionality that can be fully encapsulated in the provider.
1090
1659
  */
1091
1660
  providerOptions?: ProviderOptions;
1661
+ /**
1662
+ * Optional metadata about the tool itself (e.g. its source).
1663
+ *
1664
+ * Unlike `providerOptions`, this metadata is not sent to the language
1665
+ * model. Instead, it is propagated onto the resulting tool call's
1666
+ * `toolMetadata` so consumers can read it from tool call / result parts
1667
+ * and UI message parts. This is useful for sources of dynamic tools (e.g.
1668
+ * an MCP server) to identify themselves.
1669
+ */
1670
+ metadata?: JSONObject;
1092
1671
  /**
1093
1672
  * The schema of the input that the tool expects.
1094
1673
  * The language model will use this to generate the input.
@@ -1098,44 +1677,38 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1098
1677
  */
1099
1678
  inputSchema: FlexibleSchema<INPUT>;
1100
1679
  /**
1101
- * An optional list of input examples that show the language
1102
- * model what the input should look like.
1680
+ * An optional schema describing the context that the tool expects.
1681
+ *
1682
+ * The context is passed to execute function as part of the execution options.
1103
1683
  */
1104
- inputExamples?: Array<{
1105
- input: NoInfer<INPUT>;
1106
- }>;
1684
+ contextSchema?: FlexibleSchema<CONTEXT>;
1107
1685
  /**
1108
1686
  * Whether the tool needs approval before it can be executed.
1109
- */
1110
- needsApproval?: boolean | ToolNeedsApprovalFunction<[INPUT] extends [never] ? unknown : INPUT>;
1111
- /**
1112
- * Strict mode setting for the tool.
1113
1687
  *
1114
- * Providers that support strict mode will use this setting to determine
1115
- * how the input should be generated. Strict mode will always produce
1116
- * valid inputs, but it might limit what input schemas are supported.
1688
+ * @deprecated Tool approval is handled on a `generateText` / `streamText` level now.
1117
1689
  */
1118
- strict?: boolean;
1690
+ needsApproval?: boolean | ToolNeedsApprovalFunction<[
1691
+ INPUT
1692
+ ] extends [never] ? unknown : INPUT, NoInfer<CONTEXT>>;
1119
1693
  /**
1120
1694
  * Optional function that is called when the argument streaming starts.
1121
1695
  * Only called when the tool is used in a streaming context.
1122
1696
  */
1123
- onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
1697
+ onInputStart?: (options: ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1124
1698
  /**
1125
1699
  * Optional function that is called when an argument streaming delta is available.
1126
1700
  * Only called when the tool is used in a streaming context.
1127
1701
  */
1128
1702
  onInputDelta?: (options: {
1129
1703
  inputTextDelta: string;
1130
- } & ToolExecutionOptions) => void | PromiseLike<void>;
1704
+ } & ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1131
1705
  /**
1132
1706
  * Optional function that is called when a tool call can be started,
1133
1707
  * even if the execute function is not provided.
1134
1708
  */
1135
1709
  onInputAvailable?: (options: {
1136
1710
  input: [INPUT] extends [never] ? unknown : INPUT;
1137
- } & ToolExecutionOptions) => void | PromiseLike<void>;
1138
- } & ToolOutputProperties<INPUT, OUTPUT> & {
1711
+ } & ToolExecutionOptions<NoInfer<CONTEXT>>) => void | PromiseLike<void>;
1139
1712
  /**
1140
1713
  * Optional conversion function that maps the tool result to an output that can be used by the language model.
1141
1714
  *
@@ -1157,21 +1730,64 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1157
1730
  */
1158
1731
  output: 0 extends 1 & OUTPUT ? any : [OUTPUT] extends [never] ? any : NoInfer<OUTPUT>;
1159
1732
  }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1160
- } & ({
1733
+ } & ToolOutputProperties<INPUT, OUTPUT, NoInfer<CONTEXT>>;
1734
+ /**
1735
+ * Common properties shared by function-style tools.
1736
+ */
1737
+ type BaseFunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseTool<INPUT, OUTPUT, CONTEXT> & {
1161
1738
  /**
1162
- * Tool with user-defined input and output schemas.
1739
+ * Optional description of what the tool does.
1740
+ *
1741
+ * Included in the tool definition sent to the language model so it can
1742
+ * decide when and how to call the tool.
1743
+ *
1744
+ * Provide a string for a fixed description, or a function that returns a
1745
+ * string from the current `context` (and optional `experimental_sandbox`) when the
1746
+ * description should vary per call.
1163
1747
  */
1164
- type?: undefined | 'function';
1165
- } | {
1748
+ description?: string | ((options: {
1749
+ context: NoInfer<CONTEXT>;
1750
+ experimental_sandbox?: SandboxSession;
1751
+ }) => string);
1166
1752
  /**
1167
- * Tool that is defined at runtime (e.g. an MCP tool).
1168
- * The types of input and output are not known at development time.
1753
+ * Strict mode setting for the tool.
1754
+ *
1755
+ * Providers that support strict mode will use this setting to determine
1756
+ * how the input should be generated. Strict mode will always produce
1757
+ * valid inputs, but it might limit what input schemas are supported.
1169
1758
  */
1170
- type: 'dynamic';
1171
- } | {
1759
+ strict?: boolean;
1172
1760
  /**
1173
- * Tool with provider-defined input and output schemas.
1761
+ * An optional list of input examples that show the language
1762
+ * model what the input should look like.
1174
1763
  */
1764
+ inputExamples?: Array<{
1765
+ input: NoInfer<INPUT>;
1766
+ }>;
1767
+ id?: never;
1768
+ isProviderExecuted?: never;
1769
+ args?: never;
1770
+ supportsDeferredResults?: never;
1771
+ };
1772
+ /**
1773
+ * Tool with user-defined input and output schemas that is executed by the AI SDK.
1774
+ */
1775
+ type FunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {
1776
+ type?: undefined | 'function';
1777
+ };
1778
+ /**
1779
+ * Tool that is defined at runtime.
1780
+ * The types of input and output are not known at development time.
1781
+ *
1782
+ * For example, MCP tools that are not known at development time.
1783
+ */
1784
+ type DynamicTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseFunctionTool<INPUT, OUTPUT, CONTEXT> & {
1785
+ type: 'dynamic';
1786
+ };
1787
+ /**
1788
+ * Common properties shared by provider tools.
1789
+ */
1790
+ type BaseProviderTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseTool<INPUT, OUTPUT, CONTEXT> & {
1175
1791
  type: 'provider';
1176
1792
  /**
1177
1793
  * The ID of the tool. Must follow the format `<provider-name>.<unique-tool-name>`.
@@ -1181,6 +1797,34 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1181
1797
  * The arguments for configuring the tool. Must match the expected arguments defined by the provider for this tool.
1182
1798
  */
1183
1799
  args: Record<string, unknown>;
1800
+ description?: never;
1801
+ strict?: never;
1802
+ inputExamples?: never;
1803
+ };
1804
+ /**
1805
+ * Tool with provider-defined input and output schemas that is executed by the
1806
+ * user.
1807
+ *
1808
+ * For example, shell tools that are executed in a local shell, but have provider-defined input and output schemas.
1809
+ */
1810
+ type ProviderDefinedTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {
1811
+ /**
1812
+ * Flag that indicates whether the tool is executed by the provider.
1813
+ */
1814
+ isProviderExecuted: false;
1815
+ supportsDeferredResults?: never;
1816
+ };
1817
+ /**
1818
+ * Tool with provider-defined input and output schemas that is executed by the
1819
+ * provider.
1820
+ *
1821
+ * For example, web search tools and code execution tools that are executed by the provider itself.
1822
+ */
1823
+ type ProviderExecutedTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = BaseProviderTool<INPUT, OUTPUT, CONTEXT> & {
1824
+ /**
1825
+ * Flag that indicates whether the tool is executed by the provider.
1826
+ */
1827
+ isProviderExecuted: true;
1184
1828
  /**
1185
1829
  * Whether this provider-executed tool supports deferred results.
1186
1830
  *
@@ -1195,79 +1839,75 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1195
1839
  * @default false
1196
1840
  */
1197
1841
  supportsDeferredResults?: boolean;
1198
- });
1199
- /**
1200
- * Infer the input type of a tool.
1201
- */
1202
- type InferToolInput<TOOL extends Tool> = TOOL extends Tool<infer INPUT, any> ? INPUT : never;
1842
+ };
1203
1843
  /**
1204
- * Infer the output type of a tool.
1844
+ * A tool can either be user-defined or provider-defined.
1845
+ *
1846
+ * It contains the schemas and metadata needed for the language model to call
1847
+ * the tool and can include an execute function for tools that are executed by
1848
+ * the AI SDK.
1205
1849
  */
1206
- type InferToolOutput<TOOL extends Tool> = TOOL extends Tool<any, infer OUTPUT> ? OUTPUT : never;
1850
+ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = FunctionTool<INPUT, OUTPUT, CONTEXT> | DynamicTool<INPUT, OUTPUT, CONTEXT> | ProviderDefinedTool<INPUT, OUTPUT, CONTEXT> | ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;
1207
1851
  /**
1208
- * Helper function for inferring the execute args of a tool.
1852
+ * Infer the tool type from a tool object.
1853
+ *
1854
+ * This is useful for type inference when working with tool objects.
1855
+ *
1856
+ * When the input has an `execute` function, the return type narrows to
1857
+ * `ExecutableTool<Tool<...>>` so that `.execute` is non-nullable without
1858
+ * needing `isExecutableTool` or a `!` assertion at the call site.
1209
1859
  */
1210
- declare function tool<INPUT, OUTPUT>(tool: Tool<INPUT, OUTPUT>): Tool<INPUT, OUTPUT>;
1211
- declare function tool<INPUT>(tool: Tool<INPUT, never>): Tool<INPUT, never>;
1212
- declare function tool<OUTPUT>(tool: Tool<never, OUTPUT>): Tool<never, OUTPUT>;
1213
- declare function tool(tool: Tool<never, never>): Tool<never, never>;
1860
+ declare function tool<INPUT, OUTPUT, CONTEXT extends Context>(tool: Tool<INPUT, OUTPUT, CONTEXT> & {
1861
+ execute: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1862
+ }): ExecutableTool<Tool<INPUT, OUTPUT, CONTEXT>>;
1863
+ declare function tool<INPUT, OUTPUT, CONTEXT extends Context>(tool: Tool<INPUT, OUTPUT, CONTEXT>): Tool<INPUT, OUTPUT, CONTEXT>;
1864
+ declare function tool<INPUT, CONTEXT extends Context>(tool: Tool<INPUT, never, CONTEXT>): Tool<INPUT, never, CONTEXT>;
1865
+ declare function tool<OUTPUT, CONTEXT extends Context>(tool: Tool<never, OUTPUT, CONTEXT>): Tool<never, OUTPUT, CONTEXT>;
1866
+ declare function tool<CONTEXT extends Context>(tool: Tool<never, never, CONTEXT>): Tool<never, never, CONTEXT>;
1214
1867
  /**
1215
- * Defines a dynamic tool.
1868
+ * Define a dynamic tool.
1216
1869
  */
1217
- declare function dynamicTool(tool: {
1218
- description?: string;
1219
- title?: string;
1220
- providerOptions?: ProviderOptions;
1221
- inputSchema: FlexibleSchema<unknown>;
1222
- execute: ToolExecuteFunction<unknown, unknown>;
1223
- /**
1224
- * Optional conversion function that maps the tool result to an output that can be used by the language model.
1225
- *
1226
- * If not provided, the tool result will be sent as a JSON object.
1227
- */
1228
- toModelOutput?: (options: {
1229
- /**
1230
- * The ID of the tool call. You can use it e.g. when sending tool-call related information with stream data.
1231
- */
1232
- toolCallId: string;
1233
- /**
1234
- * The input of the tool call.
1235
- */
1236
- input: unknown;
1237
- /**
1238
- * The output of the tool call.
1239
- */
1240
- output: unknown;
1241
- }) => ToolResultOutput | PromiseLike<ToolResultOutput>;
1242
- /**
1243
- * Whether the tool needs approval before it can be executed.
1244
- */
1245
- needsApproval?: boolean | ToolNeedsApprovalFunction<unknown>;
1246
- }): Tool<unknown, unknown> & {
1247
- type: 'dynamic';
1248
- };
1870
+ declare function dynamicTool(tool: Omit<DynamicTool<unknown, unknown, Context>, 'type'>): DynamicTool<unknown, unknown, Context>;
1249
1871
 
1250
- type ProviderToolFactory<INPUT, ARGS extends object> = <OUTPUT>(options: ARGS & {
1251
- execute?: ToolExecuteFunction<INPUT, OUTPUT>;
1252
- needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];
1253
- toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
1254
- onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
1255
- onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
1256
- onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
1257
- }) => Tool<INPUT, OUTPUT>;
1258
- declare function createProviderToolFactory<INPUT, ARGS extends object>({ id, inputSchema, }: {
1872
+ /**
1873
+ * A provider-defined tool is a tool for which the provider defines the input
1874
+ * and output schemas, but does not execute the tool.
1875
+ */
1876
+ type ProviderDefinedToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}> = <OUTPUT>(options: ARGS & {
1877
+ execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1878
+ needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1879
+ toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1880
+ onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1881
+ onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1882
+ onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1883
+ }) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;
1884
+ declare function createProviderDefinedToolFactory<INPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, }: {
1885
+ id: `${string}.${string}`;
1886
+ inputSchema: FlexibleSchema<INPUT>;
1887
+ }): ProviderDefinedToolFactory<INPUT, ARGS, CONTEXT>;
1888
+ type ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1889
+ execute?: ToolExecuteFunction<INPUT, OUTPUT, CONTEXT>;
1890
+ needsApproval?: Tool<INPUT, OUTPUT, CONTEXT>['needsApproval'];
1891
+ toModelOutput?: Tool<INPUT, OUTPUT, CONTEXT>['toModelOutput'];
1892
+ onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1893
+ onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1894
+ onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1895
+ }) => ProviderDefinedTool<INPUT, OUTPUT, CONTEXT>;
1896
+ declare function createProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, }: {
1259
1897
  id: `${string}.${string}`;
1260
1898
  inputSchema: FlexibleSchema<INPUT>;
1261
- }): ProviderToolFactory<INPUT, ARGS>;
1262
- type ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object> = (options: ARGS & {
1263
- execute?: ToolExecuteFunction<INPUT, OUTPUT>;
1264
- needsApproval?: Tool<INPUT, OUTPUT>['needsApproval'];
1265
- toModelOutput?: Tool<INPUT, OUTPUT>['toModelOutput'];
1266
- onInputStart?: Tool<INPUT, OUTPUT>['onInputStart'];
1267
- onInputDelta?: Tool<INPUT, OUTPUT>['onInputDelta'];
1268
- onInputAvailable?: Tool<INPUT, OUTPUT>['onInputAvailable'];
1269
- }) => Tool<INPUT, OUTPUT>;
1270
- declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS extends object>({ id, inputSchema, outputSchema, supportsDeferredResults, }: {
1899
+ outputSchema: FlexibleSchema<OUTPUT>;
1900
+ }): ProviderDefinedToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS, CONTEXT>;
1901
+
1902
+ /**
1903
+ * A provider-executed tool is a tool for which the provider executes the tool.
1904
+ */
1905
+ type ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}> = (options: ARGS & {
1906
+ onInputStart?: Tool<INPUT, OUTPUT, CONTEXT>['onInputStart'];
1907
+ onInputDelta?: Tool<INPUT, OUTPUT, CONTEXT>['onInputDelta'];
1908
+ onInputAvailable?: Tool<INPUT, OUTPUT, CONTEXT>['onInputAvailable'];
1909
+ }) => ProviderExecutedTool<INPUT, OUTPUT, CONTEXT>;
1910
+ declare function createProviderExecutedToolFactory<INPUT, OUTPUT, ARGS extends object, CONTEXT extends Context = {}>({ id, inputSchema, outputSchema, supportsDeferredResults, }: {
1271
1911
  id: `${string}.${string}`;
1272
1912
  inputSchema: FlexibleSchema<INPUT>;
1273
1913
  outputSchema: FlexibleSchema<OUTPUT>;
@@ -1282,7 +1922,52 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1282
1922
  * @default false
1283
1923
  */
1284
1924
  supportsDeferredResults?: boolean;
1285
- }): ProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS>;
1925
+ }): ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS, CONTEXT>;
1926
+
1927
+ /**
1928
+ * Cancels a response body to release the underlying connection.
1929
+ *
1930
+ * When a fetch Response is rejected without consuming its body (e.g. a failed
1931
+ * status code, an open-redirect rejection, or a Content-Length that exceeds the
1932
+ * size limit), the underlying TCP socket is not returned to the connection pool
1933
+ * and may stay open until the process runs out of file descriptors. Cancelling
1934
+ * the body avoids this leak.
1935
+ *
1936
+ * Errors thrown while cancelling are ignored: the body may already be locked,
1937
+ * disturbed, or absent, none of which should mask the original rejection.
1938
+ */
1939
+ declare function cancelResponseBody(response: Response): Promise<void>;
1940
+
1941
+ /**
1942
+ * Default maximum download size: 2 GiB.
1943
+ *
1944
+ * `fetch().arrayBuffer()` has ~2x peak memory overhead (undici buffers the
1945
+ * body internally, then creates the JS ArrayBuffer), so very large downloads
1946
+ * risk exceeding the default V8 heap limit on 64-bit systems and terminating
1947
+ * the process with an out-of-memory error.
1948
+ *
1949
+ * Setting this limit converts an unrecoverable OOM crash into a catchable
1950
+ * `DownloadError`.
1951
+ */
1952
+ declare const DEFAULT_MAX_DOWNLOAD_SIZE: number;
1953
+ /**
1954
+ * Reads a fetch Response body with a size limit to prevent memory exhaustion.
1955
+ *
1956
+ * Checks the Content-Length header for early rejection, then reads the body
1957
+ * incrementally via ReadableStream and aborts with a DownloadError when the
1958
+ * limit is exceeded.
1959
+ *
1960
+ * @param response - The fetch Response to read.
1961
+ * @param url - The URL being downloaded (used in error messages).
1962
+ * @param maxBytes - Maximum allowed bytes. Defaults to DEFAULT_MAX_DOWNLOAD_SIZE.
1963
+ * @returns A Uint8Array containing the response body.
1964
+ * @throws DownloadError if the response exceeds maxBytes.
1965
+ */
1966
+ declare function readResponseWithSizeLimit({ response, url, maxBytes, }: {
1967
+ response: Response;
1968
+ url: string;
1969
+ maxBytes?: number;
1970
+ }): Promise<Uint8Array>;
1286
1971
 
1287
1972
  /**
1288
1973
  * Removes entries from a record where the value is null or undefined.
@@ -1291,6 +1976,21 @@ declare function createProviderToolFactoryWithOutputSchema<INPUT, OUTPUT, ARGS e
1291
1976
  */
1292
1977
  declare function removeUndefinedEntries<T>(record: Record<string, T | undefined>): Record<string, T>;
1293
1978
 
1979
+ /**
1980
+ * A value or a lazy provider of a value, each of which may be synchronous or asynchronous.
1981
+ *
1982
+ * @template T The resolved type after {@link resolve} runs.
1983
+ *
1984
+ * One of:
1985
+ * - A plain value of type {@link T}
1986
+ * - A {@link PromiseLike} of {@link T} (e.g. a `Promise<T>`)
1987
+ * - A zero-argument function that returns a plain {@link T}
1988
+ * - A zero-argument function that returns a {@link PromiseLike} of {@link T}
1989
+ *
1990
+ * The function form is only invoked when passed to {@link resolve}; it is not distinguished from
1991
+ * a {@link T} that happens to be a function—callers should wrap function values if disambiguation
1992
+ * is required.
1993
+ */
1294
1994
  type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1295
1995
  /**
1296
1996
  * Resolves a value that could be a raw value, a Promise, a function returning a value,
@@ -1298,6 +1998,134 @@ type Resolvable<T> = MaybePromiseLike<T> | (() => MaybePromiseLike<T>);
1298
1998
  */
1299
1999
  declare function resolve<T>(value: Resolvable<T>): Promise<T>;
1300
2000
 
2001
+ /**
2002
+ * Resolves a file part's media type to a full `type/subtype` form required by
2003
+ * providers whose API demands the full IANA media type.
2004
+ *
2005
+ * - If `part.mediaType` is already a full media type (e.g. `image/png`), it is
2006
+ * returned as-is.
2007
+ * - Otherwise, when inline bytes are available (`part.data.type === 'data'`),
2008
+ * the subtype is sniffed from the bytes using the signature table that
2009
+ * corresponds to the top-level segment.
2010
+ * - When neither applies (e.g. top-level-only with a URL source, or bytes that
2011
+ * cannot be detected), an `UnsupportedFunctionalityError` is thrown.
2012
+ */
2013
+ declare function resolveFullMediaType({ part, }: {
2014
+ part: LanguageModelV4FilePart;
2015
+ }): string;
2016
+
2017
+ /**
2018
+ * Resolves a provider reference to the provider-specific identifier for the
2019
+ * given provider. Throws `NoSuchProviderReferenceError` if the provider is not
2020
+ * found in the reference mapping.
2021
+ */
2022
+ declare function resolveProviderReference({ reference, provider, }: {
2023
+ reference: SharedV4ProviderReference;
2024
+ provider: string;
2025
+ }): string;
2026
+
2027
+ /**
2028
+ * Serializes a model instance for workflow step boundaries.
2029
+ * Returns the `modelId` plus the JSON-serializable config properties.
2030
+ *
2031
+ * Non-serializable values are omitted. As a special case, a
2032
+ * function-valued `headers` property is resolved during serialization
2033
+ * and included if the returned value is JSON-serializable.
2034
+ *
2035
+ * Used as the body of `static [WORKFLOW_SERIALIZE]` in provider models.
2036
+ *
2037
+ * @example
2038
+ * ```ts
2039
+ * static [WORKFLOW_SERIALIZE](model: MyLanguageModel) {
2040
+ * return serializeModelOptions({
2041
+ * modelId: model.modelId,
2042
+ * config: model.config,
2043
+ * });
2044
+ * }
2045
+ * ```
2046
+ */
2047
+ declare function serializeModelOptions<CONFIG extends {
2048
+ headers?: Resolvable<Record<string, string | undefined>>;
2049
+ }>(options: {
2050
+ modelId: string;
2051
+ config: CONFIG;
2052
+ }): {
2053
+ modelId: string;
2054
+ config: JSONObject;
2055
+ };
2056
+
2057
+ /**
2058
+ * Minimal interface for a streaming tool call delta from an OpenAI-compatible API.
2059
+ */
2060
+ interface StreamingToolCallDelta {
2061
+ index?: number | null;
2062
+ id?: string | null;
2063
+ type?: string | null;
2064
+ function?: {
2065
+ name?: string | null;
2066
+ arguments?: string | null;
2067
+ } | null;
2068
+ }
2069
+ interface StreamingToolCallTrackerOptions<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
2070
+ /**
2071
+ * ID generator function for tool call IDs.
2072
+ * Defaults to the standard generateId.
2073
+ */
2074
+ generateId?: () => string;
2075
+ /**
2076
+ * How to validate the `type` field on new tool call deltas.
2077
+ * - `'none'`: no validation (default)
2078
+ * - `'if-present'`: throw if type is present and not `'function'`
2079
+ * - `'required'`: throw if type is not exactly `'function'`
2080
+ */
2081
+ typeValidation?: 'none' | 'if-present' | 'required';
2082
+ /**
2083
+ * Extract provider-specific metadata from a tool call delta.
2084
+ * Called once when a new tool call is detected.
2085
+ * The returned metadata is stored on the tool call and passed to
2086
+ * `buildToolCallProviderMetadata` when the tool call is finalized.
2087
+ */
2088
+ extractMetadata?: (delta: DELTA) => SharedV4ProviderMetadata | undefined;
2089
+ /**
2090
+ * Build the `providerMetadata` object for a `tool-call` event.
2091
+ * Receives the metadata previously extracted via `extractMetadata`.
2092
+ * If `undefined` is returned, no `providerMetadata` is included in the event.
2093
+ */
2094
+ buildToolCallProviderMetadata?: (metadata: SharedV4ProviderMetadata | undefined) => SharedV4ProviderMetadata | undefined;
2095
+ }
2096
+ type StreamingToolCallTrackerController = Pick<TransformStreamDefaultController<LanguageModelV4StreamPart>, 'enqueue'>;
2097
+ /**
2098
+ * Tracks streaming tool call state across multiple deltas from an
2099
+ * OpenAI-compatible chat completion stream. Handles argument accumulation,
2100
+ * emits tool-input-start/delta/end and tool-call events, and finalizes
2101
+ * unfinished tool calls on flush.
2102
+ *
2103
+ * Used by openai, openai-compatible, groq, deepseek, and alibaba providers.
2104
+ */
2105
+ declare class StreamingToolCallTracker<DELTA extends StreamingToolCallDelta = StreamingToolCallDelta> {
2106
+ private toolCalls;
2107
+ private readonly controller;
2108
+ private readonly _generateId;
2109
+ private readonly typeValidation;
2110
+ private readonly extractMetadata?;
2111
+ private readonly buildToolCallProviderMetadata?;
2112
+ constructor(controller: StreamingToolCallTrackerController, options?: StreamingToolCallTrackerOptions<DELTA>);
2113
+ /**
2114
+ * Process a tool call delta from a streaming response chunk.
2115
+ * Emits tool-input-start, tool-input-delta, tool-input-end, and tool-call
2116
+ * events as appropriate.
2117
+ */
2118
+ processDelta(toolCallDelta: DELTA): void;
2119
+ /**
2120
+ * Finalize any unfinished tool calls. Should be called during the stream's
2121
+ * flush handler to ensure all tool calls are properly completed.
2122
+ */
2123
+ flush(): void;
2124
+ private processNewToolCall;
2125
+ private processExistingToolCall;
2126
+ private finishToolCall;
2127
+ }
2128
+
1301
2129
  /**
1302
2130
  * Strips file extension segments from a filename.
1303
2131
  *
@@ -1316,6 +2144,10 @@ declare function convertToBase64(value: string | Uint8Array): string;
1316
2144
  * Validates that a URL is safe to download from, blocking private/internal addresses
1317
2145
  * to prevent SSRF attacks.
1318
2146
  *
2147
+ * Note: this performs string/literal-IP checks only. It does not resolve DNS, so a
2148
+ * hostname that resolves to a private address is not blocked here (see callers, which
2149
+ * should additionally constrain egress at the network layer when handling untrusted URLs).
2150
+ *
1319
2151
  * @param url - The URL string to validate.
1320
2152
  * @throws DownloadError if the URL is unsafe.
1321
2153
  */
@@ -1376,18 +2208,98 @@ declare function withUserAgentSuffix(headers: HeadersInit | Record<string, strin
1376
2208
 
1377
2209
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
1378
2210
 
1379
- declare function executeTool<INPUT, OUTPUT>({ execute, input, options, }: {
1380
- execute: ToolExecuteFunction<INPUT, OUTPUT>;
1381
- input: INPUT;
1382
- options: ToolExecutionOptions;
2211
+ /**
2212
+ * Detects the `any` type so untyped tools can be treated as having no explicit
2213
+ * context type.
2214
+ */
2215
+ type IsAny<T> = 0 extends 1 & T ? true : false;
2216
+ /**
2217
+ * Detects exact empty object contexts, including `{}` combined with
2218
+ * `undefined`, which do not provide tool-specific context properties.
2219
+ */
2220
+ type IsEmptyObject<T> = keyof NonNullable<T> extends never ? true : false;
2221
+ /**
2222
+ * Detects context types that come from omitted or broad context declarations
2223
+ * rather than a concrete tool context schema.
2224
+ */
2225
+ type IsUntypedContext<CONTEXT> = IsAny<CONTEXT> extends true ? true : unknown extends CONTEXT ? true : IsEmptyObject<CONTEXT> extends true ? true : string extends keyof CONTEXT ? CONTEXT extends Context ? true : false : false;
2226
+ /**
2227
+ * Infer the context type of a tool.
2228
+ */
2229
+ type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? IsUntypedContext<CONTEXT> extends true ? never : CONTEXT : never;
2230
+
2231
+ /**
2232
+ * Infer the input type of a tool.
2233
+ */
2234
+ type InferToolInput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<infer INPUT, any, any> ? INPUT : never;
2235
+
2236
+ /**
2237
+ * Infer the output type of a tool.
2238
+ */
2239
+ type InferToolOutput<TOOL extends Tool<any, any, any>> = TOOL extends Tool<any, infer OUTPUT, any> ? OUTPUT : never;
2240
+
2241
+ /**
2242
+ * Executes a tool function and normalizes its results into a stream of outputs.
2243
+ *
2244
+ * - If the tool's `execute` function returns an `AsyncIterable`, each yielded value is emitted as
2245
+ * `{ type: "preliminary", output }`. After iteration completes, the last yielded value is emitted
2246
+ * again as `{ type: "final", output }`.
2247
+ * - If the tool returns a direct value or Promise, a single `{ type: "final", output }` is yielded.
2248
+ *
2249
+ * @param params.tool The tool whose `execute` function should be invoked.
2250
+ * @param params.input The input value to pass to the tool.
2251
+ * @param params.options Additional options for tool execution.
2252
+ * @yields A preliminary output for each streamed value, followed by a final output, or a single final
2253
+ * output for non-streaming tools.
2254
+ */
2255
+ declare function executeTool<TOOL extends Tool>({ tool, input, options, }: {
2256
+ tool: ExecutableTool<TOOL>;
2257
+ input: InferToolInput<TOOL>;
2258
+ options: ToolExecutionOptions<InferToolContext<TOOL>>;
1383
2259
  }): AsyncGenerator<{
1384
2260
  type: 'preliminary';
1385
- output: OUTPUT;
2261
+ output: InferToolOutput<TOOL>;
1386
2262
  } | {
1387
2263
  type: 'final';
1388
- output: OUTPUT;
2264
+ output: InferToolOutput<TOOL>;
1389
2265
  }>;
1390
2266
 
2267
+ /**
2268
+ * A mapping of tool names to tool definitions.
2269
+ */
2270
+ type ToolSet = Record<string, (Tool<never, never, any> | Tool<any, any, any> | Tool<any, never, any> | Tool<never, any, any>) & Pick<Tool<any, any, any>, 'execute' | 'onInputAvailable' | 'onInputStart' | 'onInputDelta' | 'needsApproval'>>;
2271
+
2272
+ /**
2273
+ * Builds the required portion of the tool context map for tools whose context
2274
+ * type does not include `undefined`.
2275
+ */
2276
+ type RequiredToolSetContext<TOOLS extends ToolSet> = {
2277
+ [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : undefined extends InferToolContext<NoInfer<TOOLS[K]>> ? never : K]: InferToolContext<NoInfer<TOOLS[K]>>;
2278
+ };
2279
+ /**
2280
+ * Builds the optional portion of the tool context map for tools whose context
2281
+ * object itself may be `undefined`.
2282
+ */
2283
+ type OptionalToolSetContext<TOOLS extends ToolSet> = {
2284
+ [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : undefined extends InferToolContext<NoInfer<TOOLS[K]>> ? K : never]?: InferToolContext<NoInfer<TOOLS[K]>>;
2285
+ };
2286
+ /**
2287
+ * Flattens intersected mapped types so type equality assertions and editor
2288
+ * hovers show the resulting object shape.
2289
+ */
2290
+ type Normalize<OBJECT> = {
2291
+ [KEY in keyof OBJECT]: OBJECT[KEY];
2292
+ };
2293
+ /**
2294
+ * Infer the context type for a tool set.
2295
+ *
2296
+ * The inferred type maps each contextual tool name to its context type.
2297
+ *
2298
+ * Tools without concrete context are omitted. Tool contexts that include
2299
+ * `undefined` are represented as optional properties.
2300
+ */
2301
+ type InferToolSetContext<TOOLS extends ToolSet> = Normalize<RequiredToolSetContext<TOOLS> & OptionalToolSetContext<TOOLS>>;
2302
+
1391
2303
  /**
1392
2304
  * Typed tool call that is returned by generateText and streamText.
1393
2305
  * It contains the tool call ID, the tool name, and the tool arguments.
@@ -1447,9 +2359,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1447
2359
  dynamic?: boolean;
1448
2360
  }
1449
2361
 
1450
- /**
1451
- * @deprecated Use ToolExecutionOptions instead.
1452
- */
1453
- type ToolCallOptions = ToolExecutionOptions;
1454
-
1455
- export { type AssistantContent, type AssistantModelMessage, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type FetchFunction, type FilePart, type FlexibleSchema, type IdGenerator, type ImagePart, type InferSchema, type InferToolInput, type InferToolOutput, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderOptions, type ProviderToolFactory, type ProviderToolFactoryWithOutputSchema, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallOptions, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asSchema, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderToolFactory, createProviderToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, generateId, getErrorMessage, getFromApi, getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages, isAbortError, isNonNullable, isParsableJson, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, safeParseJSON, safeValidateTypes, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };
2362
+ export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type SandboxProcess as Experimental_SandboxProcess, type SandboxSession as Experimental_SandboxSession, type FetchFunction, type FileData, type FileDataData, type FileDataReference, type FileDataText, type FileDataUrl, type FilePart, type FlexibleSchema, type FunctionTool, type HasRequiredKey, type IdGenerator, type ImagePart, type InferSchema, type InferToolContext, type InferToolInput, type InferToolOutput, type InferToolSetContext, type LazySchema, type MaybePromiseLike, type ModelMessage, type ParseResult, type ProviderDefinedTool, type ProviderDefinedToolFactory, type ProviderDefinedToolFactoryWithOutputSchema, type ProviderExecutedTool, type ProviderExecutedToolFactory, type ProviderOptions, type ProviderReference, type ReasoningFilePart, type ReasoningPart, type Resolvable, type ResponseHandler, type Schema, type StreamingToolCallDelta, StreamingToolCallTracker, type StreamingToolCallTrackerOptions, type SystemModelMessage, type TextPart, type Tool, type ToolApprovalRequest, type ToolApprovalResponse, type ToolCall, type ToolCallPart, type ToolContent, type ToolExecuteFunction, type ToolExecutionOptions, type ToolModelMessage, type ToolNameMapping, type ToolNeedsApprovalFunction, type ToolResult, type ToolResultOutput, type ToolResultPart, type ToolSet, type UserContent, type UserModelMessage, VERSION, type ValidationResult, asArray, asSchema, cancelResponseBody, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, detectMediaType, downloadBlob, dynamicTool, executeTool, extractLines, extractResponseHeaders, fetchWithValidatedRedirects, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, injectJsonInstructionIntoMessages, isAbortError, isBrowserRuntime, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, isSameOrigin, isUrlSupported, jsonSchema, lazySchema, loadApiKey, loadOptionalSetting, loadSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, mediaTypeToExtension, normalizeHeaders, parseJSON, parseJsonEventStream, parseProviderOptions, postFormDataToApi, postJsonToApi, postToApi, readResponseWithSizeLimit, removeUndefinedEntries, resolve, resolveFullMediaType, resolveProviderReference, safeParseJSON, safeValidateTypes, serializeModelOptions, stripFileExtension, tool, validateDownloadUrl, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema };