@ai-sdk/provider-utils 5.0.0-beta.30 → 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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SharedV4FileDataUrl, SharedV4FileDataReference, SharedV4FileDataText, SharedV4ProviderOptions, SharedV4ProviderReference, JSONValue, ImageModelV4File, LanguageModelV4FunctionTool, LanguageModelV4ProviderTool, AISDKError, JSONSchema7, JSONParseError, TypeValidationError, APICallError, LanguageModelV4Prompt, LanguageModelV4CallOptions, SharedV4Warning, SharedV4ProviderMetadata, LanguageModelV4FilePart, JSONObject, LanguageModelV4StreamPart, 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
2
  export { getErrorMessage } from '@ai-sdk/provider';
3
3
  import { StandardSchemaV1, StandardJSONSchemaV1 } from '@standard-schema/spec';
4
4
  export * from '@standard-schema/spec';
@@ -348,6 +348,45 @@ type ToolResultOutput = {
348
348
  */
349
349
  providerOptions?: ProviderOptions;
350
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
+ */
351
390
  type: 'file-data';
352
391
  /**
353
392
  * Base-64 encoded media data.
@@ -367,6 +406,10 @@ type ToolResultOutput = {
367
406
  */
368
407
  providerOptions?: ProviderOptions;
369
408
  } | {
409
+ /**
410
+ * @deprecated Use 'file' with mediaType and tagged data instead:
411
+ * `{ type: 'file', mediaType, data: { type: 'url', url: new URL(url) } }`.
412
+ */
370
413
  type: 'file-url';
371
414
  /**
372
415
  * URL of the file.
@@ -383,7 +426,8 @@ type ToolResultOutput = {
383
426
  providerOptions?: ProviderOptions;
384
427
  } | {
385
428
  /**
386
- * @deprecated Use file-reference instead.
429
+ * @deprecated Use 'file' with tagged data instead:
430
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
387
431
  */
388
432
  type: 'file-id';
389
433
  /**
@@ -400,6 +444,10 @@ type ToolResultOutput = {
400
444
  */
401
445
  providerOptions?: ProviderOptions;
402
446
  } | {
447
+ /**
448
+ * @deprecated Use 'file' with tagged data instead:
449
+ * `{ type: 'file', mediaType, data: { type: 'reference', reference } }`.
450
+ */
403
451
  type: 'file-reference';
404
452
  /**
405
453
  * Provider-specific references for the file.
@@ -412,7 +460,9 @@ type ToolResultOutput = {
412
460
  providerOptions?: ProviderOptions;
413
461
  } | {
414
462
  /**
415
- * @deprecated Use file-data instead.
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 } }`.
416
466
  */
417
467
  type: 'image-data';
418
468
  /**
@@ -430,7 +480,9 @@ type ToolResultOutput = {
430
480
  providerOptions?: ProviderOptions;
431
481
  } | {
432
482
  /**
433
- * @deprecated Use file-url instead.
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) } }`.
434
486
  */
435
487
  type: 'image-url';
436
488
  /**
@@ -443,7 +495,9 @@ type ToolResultOutput = {
443
495
  providerOptions?: ProviderOptions;
444
496
  } | {
445
497
  /**
446
- * @deprecated Use file-reference instead.
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 } }`.
447
501
  */
448
502
  type: 'image-file-id';
449
503
  /**
@@ -461,7 +515,9 @@ type ToolResultOutput = {
461
515
  providerOptions?: ProviderOptions;
462
516
  } | {
463
517
  /**
464
- * @deprecated Use file-reference instead.
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 } }`.
465
521
  */
466
522
  type: 'image-file-reference';
467
523
  /**
@@ -682,6 +738,51 @@ declare class DownloadError extends AISDKError {
682
738
  static isInstance(error: unknown): error is DownloadError;
683
739
  }
684
740
 
741
+ /**
742
+ * Fetches a URL while enforcing the SSRF download guard on every hop.
743
+ *
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.
749
+ *
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.
763
+ */
764
+ declare function fetchWithValidatedRedirects({ url, headers, abortSignal, maxRedirects, }: {
765
+ url: string;
766
+ headers?: HeadersInit;
767
+ abortSignal?: AbortSignal;
768
+ maxRedirects?: number;
769
+ }): Promise<Response>;
770
+
771
+ /**
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).
774
+ *
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
+
685
786
  /**
686
787
  * Extracts the headers from a response object and returns them as a key-value object.
687
788
  *
@@ -900,6 +1001,16 @@ declare function injectJsonInstructionIntoMessages({ messages, schema, schemaPre
900
1001
 
901
1002
  declare function isAbortError(error: unknown): error is Error;
902
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
+
903
1014
  /**
904
1015
  * Type-guard for Node.js `Buffer` instances.
905
1016
  *
@@ -908,6 +1019,20 @@ declare function isAbortError(error: unknown): error is Error;
908
1019
  */
909
1020
  declare function isBuffer(value: unknown): value is Buffer;
910
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
+
911
1036
  /**
912
1037
  * Type guard that checks whether a value is not `null` or `undefined`.
913
1038
  *
@@ -1100,15 +1225,18 @@ declare const postToApi: <T>({ url, headers, body, successfulResponseHandler, fa
1100
1225
  */
1101
1226
  type Context = Record<string, unknown>;
1102
1227
 
1103
- type NeverOptional<N, T> = 0 extends 1 & N ? Partial<T> : [N] extends [never] ? Partial<Record<keyof T, undefined>> : T;
1104
-
1105
1228
  /**
1106
- * Top-level context properties that contain sensitive data and should be
1107
- * excluded from telemetry.
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']>;
1233
+ };
1234
+ /**
1235
+ * Checks whether a tool exposes an execute function.
1108
1236
  */
1109
- type SensitiveContext<CONTEXT extends Context | unknown | never> = {
1110
- [KEY in keyof CONTEXT]?: boolean;
1111
- } | undefined;
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;
1112
1240
 
1113
1241
  /**
1114
1242
  * Tool approval request prompt part.
@@ -1129,6 +1257,11 @@ type ToolApprovalRequest = {
1129
1257
  * @default false
1130
1258
  */
1131
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;
1132
1265
  };
1133
1266
 
1134
1267
  /**
@@ -1234,6 +1367,186 @@ type UserContent = string | Array<TextPart | ImagePart | FilePart>;
1234
1367
  */
1235
1368
  type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
1236
1369
 
1370
+ /**
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
+
1237
1550
  /**
1238
1551
  * Additional options that are sent into each tool execution.
1239
1552
  */
@@ -1263,6 +1576,10 @@ interface ToolExecutionOptions<CONTEXT extends Context | unknown | never> {
1263
1576
  * in `prepareStep` and update it there.
1264
1577
  */
1265
1578
  context: CONTEXT;
1579
+ /**
1580
+ * The sandbox environment that the tool is operating in.
1581
+ */
1582
+ experimental_sandbox?: SandboxSession;
1266
1583
  }
1267
1584
  /**
1268
1585
  * Function that executes the tool and returns either a single result or a stream of results.
@@ -1331,6 +1648,8 @@ type ToolOutputProperties<INPUT, OUTPUT, CONTEXT extends Context | unknown | nev
1331
1648
  type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONValue | unknown | never = any, CONTEXT extends Context | unknown | never = any> = {
1332
1649
  /**
1333
1650
  * An optional title of the tool.
1651
+ *
1652
+ * @deprecated Use `providerMetadata` for source-specific tool display metadata.
1334
1653
  */
1335
1654
  title?: string;
1336
1655
  /**
@@ -1344,11 +1663,11 @@ type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JS
1344
1663
  *
1345
1664
  * Unlike `providerOptions`, this metadata is not sent to the language
1346
1665
  * model. Instead, it is propagated onto the resulting tool call's
1347
- * `providerMetadata` so consumers can read it from tool call / result
1348
- * parts and UI message parts. This is useful for sources of dynamic
1349
- * tools (e.g. an MCP server) to identify themselves.
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.
1350
1669
  */
1351
- providerMetadata?: SharedV4ProviderMetadata;
1670
+ metadata?: JSONObject;
1352
1671
  /**
1353
1672
  * The schema of the input that the tool expects.
1354
1673
  * The language model will use this to generate the input.
@@ -1363,11 +1682,6 @@ type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JS
1363
1682
  * The context is passed to execute function as part of the execution options.
1364
1683
  */
1365
1684
  contextSchema?: FlexibleSchema<CONTEXT>;
1366
- /**
1367
- * Marks top-level context properties that contain sensitive data and should be excluded from telemetry.
1368
- * Properties marked as `true` are omitted from telemetry integrations.
1369
- */
1370
- sensitiveContext?: SensitiveContext<CONTEXT>;
1371
1685
  /**
1372
1686
  * Whether the tool needs approval before it can be executed.
1373
1687
  *
@@ -1422,10 +1736,19 @@ type BaseTool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JS
1422
1736
  */
1423
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> & {
1424
1738
  /**
1425
- * An optional description of what the tool does.
1426
- * Will be used by the language model to decide whether to use the tool.
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.
1427
1747
  */
1428
- description?: string;
1748
+ description?: string | ((options: {
1749
+ context: NoInfer<CONTEXT>;
1750
+ experimental_sandbox?: SandboxSession;
1751
+ }) => string);
1429
1752
  /**
1430
1753
  * Strict mode setting for the tool.
1431
1754
  *
@@ -1447,14 +1770,16 @@ type BaseFunctionTool<INPUT extends JSONValue | unknown | never = any, OUTPUT ex
1447
1770
  supportsDeferredResults?: never;
1448
1771
  };
1449
1772
  /**
1450
- * Tool with user-defined input and output schemas.
1773
+ * Tool with user-defined input and output schemas that is executed by the AI SDK.
1451
1774
  */
1452
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> & {
1453
1776
  type?: undefined | 'function';
1454
1777
  };
1455
1778
  /**
1456
- * Tool that is defined at runtime (e.g. an MCP tool).
1779
+ * Tool that is defined at runtime.
1457
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.
1458
1783
  */
1459
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> & {
1460
1785
  type: 'dynamic';
@@ -1479,6 +1804,8 @@ type BaseProviderTool<INPUT extends JSONValue | unknown | never = any, OUTPUT ex
1479
1804
  /**
1480
1805
  * Tool with provider-defined input and output schemas that is executed by the
1481
1806
  * user.
1807
+ *
1808
+ * For example, shell tools that are executed in a local shell, but have provider-defined input and output schemas.
1482
1809
  */
1483
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> & {
1484
1811
  /**
@@ -1490,6 +1817,8 @@ type ProviderDefinedTool<INPUT extends JSONValue | unknown | never = any, OUTPUT
1490
1817
  /**
1491
1818
  * Tool with provider-defined input and output schemas that is executed by the
1492
1819
  * provider.
1820
+ *
1821
+ * For example, web search tools and code execution tools that are executed by the provider itself.
1493
1822
  */
1494
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> & {
1495
1824
  /**
@@ -1523,7 +1852,14 @@ type Tool<INPUT extends JSONValue | unknown | never = any, OUTPUT extends JSONVa
1523
1852
  * Infer the tool type from a tool object.
1524
1853
  *
1525
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.
1526
1859
  */
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>>;
1527
1863
  declare function tool<INPUT, OUTPUT, CONTEXT extends Context>(tool: Tool<INPUT, OUTPUT, CONTEXT>): Tool<INPUT, OUTPUT, CONTEXT>;
1528
1864
  declare function tool<INPUT, CONTEXT extends Context>(tool: Tool<INPUT, never, CONTEXT>): Tool<INPUT, never, CONTEXT>;
1529
1865
  declare function tool<OUTPUT, CONTEXT extends Context>(tool: Tool<never, OUTPUT, CONTEXT>): Tool<never, OUTPUT, CONTEXT>;
@@ -1588,6 +1924,20 @@ declare function createProviderExecutedToolFactory<INPUT, OUTPUT, ARGS extends o
1588
1924
  supportsDeferredResults?: boolean;
1589
1925
  }): ProviderExecutedToolFactory<INPUT, OUTPUT, ARGS, CONTEXT>;
1590
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
+
1591
1941
  /**
1592
1942
  * Default maximum download size: 2 GiB.
1593
1943
  *
@@ -1794,6 +2144,10 @@ declare function convertToBase64(value: string | Uint8Array): string;
1794
2144
  * Validates that a URL is safe to download from, blocking private/internal addresses
1795
2145
  * to prevent SSRF attacks.
1796
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
+ *
1797
2151
  * @param url - The URL string to validate.
1798
2152
  * @throws DownloadError if the URL is unsafe.
1799
2153
  */
@@ -1855,20 +2209,24 @@ declare function withUserAgentSuffix(headers: HeadersInit | Record<string, strin
1855
2209
  declare function withoutTrailingSlash(url: string | undefined): string | undefined;
1856
2210
 
1857
2211
  /**
1858
- * A tool that is guaranteed to expose an execute function.
2212
+ * Detects the `any` type so untyped tools can be treated as having no explicit
2213
+ * context type.
1859
2214
  */
1860
- type ExecutableTool<TOOL extends Tool = Tool> = TOOL & {
1861
- execute: NonNullable<TOOL['execute']>;
1862
- };
2215
+ type IsAny<T> = 0 extends 1 & T ? true : false;
1863
2216
  /**
1864
- * Checks whether a tool exposes an execute function.
2217
+ * Detects exact empty object contexts, including `{}` combined with
2218
+ * `undefined`, which do not provide tool-specific context properties.
1865
2219
  */
1866
- declare function isExecutableTool<TOOL extends Tool>(tool: TOOL | undefined): tool is ExecutableTool<TOOL>;
1867
-
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;
1868
2226
  /**
1869
2227
  * Infer the context type of a tool.
1870
2228
  */
1871
- type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? HasRequiredKey<CONTEXT> extends true ? CONTEXT : never : never;
2229
+ type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? IsUntypedContext<CONTEXT> extends true ? never : CONTEXT : never;
1872
2230
 
1873
2231
  /**
1874
2232
  * Infer the input type of a tool.
@@ -1911,16 +2269,36 @@ declare function executeTool<TOOL extends Tool>({ tool, input, options, }: {
1911
2269
  */
1912
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'>>;
1913
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
+ };
1914
2293
  /**
1915
2294
  * Infer the context type for a tool set.
1916
2295
  *
1917
- * The inferred type maps each tool name to its required context type.
2296
+ * The inferred type maps each contextual tool name to its context type.
1918
2297
  *
1919
- * Tools without required context properties are omitted from the result.
2298
+ * Tools without concrete context are omitted. Tool contexts that include
2299
+ * `undefined` are represented as optional properties.
1920
2300
  */
1921
- type InferToolSetContext<TOOLS extends ToolSet> = {
1922
- [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : K]: InferToolContext<NoInfer<TOOLS[K]>>;
1923
- };
2301
+ type InferToolSetContext<TOOLS extends ToolSet> = Normalize<RequiredToolSetContext<TOOLS> & OptionalToolSetContext<TOOLS>>;
1924
2302
 
1925
2303
  /**
1926
2304
  * Typed tool call that is returned by generateText and streamText.
@@ -1981,4 +2359,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
1981
2359
  dynamic?: boolean;
1982
2360
  }
1983
2361
 
1984
- export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, 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 SensitiveContext, 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, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertImageModelFileToDataUri, convertInlineFileDataToUint8Array, convertToBase64, convertToFormData, convertUint8ArrayToBase64, createBinaryResponseHandler, createEventSourceResponseHandler, createIdGenerator, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema, createProviderExecutedToolFactory, createStatusCodeErrorResponseHandler, createToolNameMapping, delay, detectMediaType, downloadBlob, dynamicTool, executeTool, extractResponseHeaders, filterNullable, generateId, getFromApi, getRuntimeEnvironmentUserAgent, getTopLevelMediaType, injectJsonInstructionIntoMessages, isAbortError, isBuffer, isCustomReasoning, isExecutableTool, isFullMediaType, isNonNullable, isParsableJson, isProviderReference, 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 };
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 };