@ai-sdk/provider-utils 5.0.0-canary.40 → 5.0.0-canary.43

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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # @ai-sdk/provider-utils
2
2
 
3
+ ## 5.0.0-canary.43
4
+
5
+ ### Patch Changes
6
+
7
+ - 7fc6bd6: Raise minimum supported Node.js version to 22. Supported versions: 22, 24, and 26.
8
+ - Updated dependencies [7fc6bd6]
9
+ - @ai-sdk/provider@4.0.0-canary.17
10
+
11
+ ## 5.0.0-canary.42
12
+
13
+ ### Patch Changes
14
+
15
+ - a6617c5: feat(provider-utils): add `readFile` and `writeFile` plus convenience wrappers to `Experimental_Sandbox` abstraction
16
+
17
+ ## 5.0.0-canary.41
18
+
19
+ ### Patch Changes
20
+
21
+ - 28dfa06: fix: support tools with optional context
22
+ - e93fa91: rename Sandbox.executeCommand to Sandbox.runCommand
23
+
3
24
  ## 5.0.0-canary.40
4
25
 
5
26
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -738,6 +738,21 @@ declare class DownloadError extends AISDKError {
738
738
  static isInstance(error: unknown): error is DownloadError;
739
739
  }
740
740
 
741
+ /**
742
+ * Extracts a 1-based inclusive line range from `text`, auto-detecting the
743
+ * file's line ending (`\r\n`, `\n`, or `\r`, in that priority).
744
+ *
745
+ * Mixed line endings are not supported: detection picks one and uses it for
746
+ * both the split and the rejoin, so files that mix conventions will not slice
747
+ * cleanly. When neither `startLine` nor `endLine` is provided, the input is
748
+ * returned unchanged. `endLine` past EOF clamps to the last line.
749
+ */
750
+ declare function extractLines({ text, startLine, endLine, }: {
751
+ text: string;
752
+ startLine?: number;
753
+ endLine?: number;
754
+ }): string;
755
+
741
756
  /**
742
757
  * Extracts the headers from a response object and returns them as a key-value object.
743
758
  *
@@ -1283,7 +1298,7 @@ type UserContent = string | Array<TextPart | ImagePart | FilePart>;
1283
1298
  type ModelMessage = SystemModelMessage | UserModelMessage | AssistantModelMessage | ToolModelMessage;
1284
1299
 
1285
1300
  /**
1286
- * Sandbox environment that can execute commands.
1301
+ * Sandbox environment that can execute commands and read/write files.
1287
1302
  */
1288
1303
  type Experimental_Sandbox = {
1289
1304
  /**
@@ -1293,9 +1308,9 @@ type Experimental_Sandbox = {
1293
1308
  */
1294
1309
  readonly description: string;
1295
1310
  /**
1296
- * Execute a command in the sandbox.
1311
+ * Run a command in the sandbox.
1297
1312
  */
1298
- readonly executeCommand: (options: {
1313
+ readonly runCommand: (options: {
1299
1314
  /**
1300
1315
  * Command to execute in the sandbox.
1301
1316
  */
@@ -1322,6 +1337,130 @@ type Experimental_Sandbox = {
1322
1337
  */
1323
1338
  stderr: string;
1324
1339
  }>;
1340
+ /**
1341
+ * Read one file from the sandbox as a stream of bytes. Resolves to `null`
1342
+ * when the file does not exist.
1343
+ *
1344
+ * Relative path handling is implementation-defined. This is the lowest-level
1345
+ * read primitive; prefer `readBinaryFile` or `readTextFile` unless you need
1346
+ * to stream bytes.
1347
+ */
1348
+ readonly readFile: (options: {
1349
+ /**
1350
+ * Path of the file to read.
1351
+ */
1352
+ path: string;
1353
+ /**
1354
+ * Signal that can be used to abort the read.
1355
+ */
1356
+ abortSignal?: AbortSignal;
1357
+ }) => PromiseLike<ReadableStream<Uint8Array> | null>;
1358
+ /**
1359
+ * Read one file from the sandbox as raw bytes. Resolves to `null` when the
1360
+ * file does not exist.
1361
+ */
1362
+ readonly readBinaryFile: (options: {
1363
+ /**
1364
+ * Path of the file to read.
1365
+ */
1366
+ path: string;
1367
+ /**
1368
+ * Signal that can be used to abort the read.
1369
+ */
1370
+ abortSignal?: AbortSignal;
1371
+ }) => PromiseLike<Uint8Array | null>;
1372
+ /**
1373
+ * Read one text file from the sandbox, decoded using the requested encoding.
1374
+ * Resolves to `null` when the file does not exist.
1375
+ *
1376
+ * Line ranges are 1-based and inclusive. When `endLine` is past EOF the read
1377
+ * returns through EOF without error.
1378
+ */
1379
+ readonly readTextFile: (options: {
1380
+ /**
1381
+ * Path of the file to read.
1382
+ */
1383
+ path: string;
1384
+ /**
1385
+ * Text encoding used to decode the file bytes. Defaults to `"utf-8"`.
1386
+ */
1387
+ encoding?: string;
1388
+ /**
1389
+ * 1-based inclusive start line. Defaults to 1.
1390
+ */
1391
+ startLine?: number;
1392
+ /**
1393
+ * 1-based inclusive end line. When past the file's line count, the read
1394
+ * returns through EOF without error.
1395
+ */
1396
+ endLine?: number;
1397
+ /**
1398
+ * Signal that can be used to abort the read.
1399
+ */
1400
+ abortSignal?: AbortSignal;
1401
+ }) => PromiseLike<string | null>;
1402
+ /**
1403
+ * Write one file to the sandbox from a stream of bytes. Creates parent
1404
+ * directories recursively and overwrites any existing file.
1405
+ *
1406
+ * This is the lowest-level write primitive; prefer `writeBinaryFile` or
1407
+ * `writeTextFile` when the full content is already materialized in memory.
1408
+ */
1409
+ readonly writeFile: (options: {
1410
+ /**
1411
+ * Path of the file to write.
1412
+ */
1413
+ path: string;
1414
+ /**
1415
+ * Stream of bytes to write.
1416
+ */
1417
+ content: ReadableStream<Uint8Array>;
1418
+ /**
1419
+ * Signal that can be used to abort the write.
1420
+ */
1421
+ abortSignal?: AbortSignal;
1422
+ }) => PromiseLike<void>;
1423
+ /**
1424
+ * Write one file to the sandbox from raw bytes. Creates parent directories
1425
+ * recursively and overwrites any existing file.
1426
+ */
1427
+ readonly writeBinaryFile: (options: {
1428
+ /**
1429
+ * Path of the file to write.
1430
+ */
1431
+ path: string;
1432
+ /**
1433
+ * Raw bytes to write.
1434
+ */
1435
+ content: Uint8Array;
1436
+ /**
1437
+ * Signal that can be used to abort the write.
1438
+ */
1439
+ abortSignal?: AbortSignal;
1440
+ }) => PromiseLike<void>;
1441
+ /**
1442
+ * Write one file to the sandbox from a string, encoded using the requested
1443
+ * encoding. Creates parent directories recursively and overwrites any
1444
+ * existing file.
1445
+ */
1446
+ readonly writeTextFile: (options: {
1447
+ /**
1448
+ * Path of the file to write.
1449
+ */
1450
+ path: string;
1451
+ /**
1452
+ * Text content to write.
1453
+ */
1454
+ content: string;
1455
+ /**
1456
+ * Text encoding used to encode the string to bytes. Defaults to `"utf-8"`.
1457
+ */
1458
+ encoding?: string;
1459
+ /**
1460
+ * Signal that can be used to abort the write.
1461
+ */
1462
+ abortSignal?: AbortSignal;
1463
+ }) => PromiseLike<void>;
1325
1464
  };
1326
1465
 
1327
1466
  /**
@@ -1971,10 +2110,25 @@ type ExecutableTool<TOOL extends Tool = Tool> = TOOL & {
1971
2110
  */
1972
2111
  declare function isExecutableTool<TOOL extends Tool>(tool: TOOL | undefined): tool is ExecutableTool<TOOL>;
1973
2112
 
2113
+ /**
2114
+ * Detects the `any` type so untyped tools can be treated as having no explicit
2115
+ * context type.
2116
+ */
2117
+ type IsAny<T> = 0 extends 1 & T ? true : false;
2118
+ /**
2119
+ * Detects exact empty object contexts, including `{}` combined with
2120
+ * `undefined`, which do not provide tool-specific context properties.
2121
+ */
2122
+ type IsEmptyObject<T> = keyof NonNullable<T> extends never ? true : false;
2123
+ /**
2124
+ * Detects context types that come from omitted or broad context declarations
2125
+ * rather than a concrete tool context schema.
2126
+ */
2127
+ 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;
1974
2128
  /**
1975
2129
  * Infer the context type of a tool.
1976
2130
  */
1977
- type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? HasRequiredKey<CONTEXT> extends true ? CONTEXT : never : never;
2131
+ type InferToolContext<TOOL extends Tool> = TOOL extends Tool<any, any, infer CONTEXT> ? IsUntypedContext<CONTEXT> extends true ? never : CONTEXT : never;
1978
2132
 
1979
2133
  /**
1980
2134
  * Infer the input type of a tool.
@@ -2017,16 +2171,36 @@ declare function executeTool<TOOL extends Tool>({ tool, input, options, }: {
2017
2171
  */
2018
2172
  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'>>;
2019
2173
 
2174
+ /**
2175
+ * Builds the required portion of the tool context map for tools whose context
2176
+ * type does not include `undefined`.
2177
+ */
2178
+ type RequiredToolSetContext<TOOLS extends ToolSet> = {
2179
+ [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : undefined extends InferToolContext<NoInfer<TOOLS[K]>> ? never : K]: InferToolContext<NoInfer<TOOLS[K]>>;
2180
+ };
2181
+ /**
2182
+ * Builds the optional portion of the tool context map for tools whose context
2183
+ * object itself may be `undefined`.
2184
+ */
2185
+ type OptionalToolSetContext<TOOLS extends ToolSet> = {
2186
+ [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : undefined extends InferToolContext<NoInfer<TOOLS[K]>> ? K : never]?: InferToolContext<NoInfer<TOOLS[K]>>;
2187
+ };
2188
+ /**
2189
+ * Flattens intersected mapped types so type equality assertions and editor
2190
+ * hovers show the resulting object shape.
2191
+ */
2192
+ type Normalize<OBJECT> = {
2193
+ [KEY in keyof OBJECT]: OBJECT[KEY];
2194
+ };
2020
2195
  /**
2021
2196
  * Infer the context type for a tool set.
2022
2197
  *
2023
- * The inferred type maps each tool name to its required context type.
2198
+ * The inferred type maps each contextual tool name to its context type.
2024
2199
  *
2025
- * Tools without required context properties are omitted from the result.
2200
+ * Tools without concrete context are omitted. Tool contexts that include
2201
+ * `undefined` are represented as optional properties.
2026
2202
  */
2027
- type InferToolSetContext<TOOLS extends ToolSet> = {
2028
- [K in keyof TOOLS as InferToolContext<NoInfer<TOOLS[K]>> extends never ? never : K]: InferToolContext<NoInfer<TOOLS[K]>>;
2029
- };
2203
+ type InferToolSetContext<TOOLS extends ToolSet> = Normalize<RequiredToolSetContext<TOOLS> & OptionalToolSetContext<TOOLS>>;
2030
2204
 
2031
2205
  /**
2032
2206
  * Typed tool call that is returned by generateText and streamText.
@@ -2087,4 +2261,4 @@ interface ToolResult<NAME extends string, INPUT, OUTPUT> {
2087
2261
  dynamic?: boolean;
2088
2262
  }
2089
2263
 
2090
- export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type Experimental_Sandbox, 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, 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 };
2264
+ export { type Arrayable, type AssistantContent, type AssistantModelMessage, type Context, type CustomPart, DEFAULT_MAX_DOWNLOAD_SIZE, type DataContent, DelayedPromise, DownloadError, type DynamicTool, type ExecutableTool, type Experimental_Sandbox, 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, 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, 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 };
package/dist/index.js CHANGED
@@ -701,6 +701,20 @@ async function downloadBlob(url, options) {
701
701
  }
702
702
  }
703
703
 
704
+ // src/extract-lines.ts
705
+ function extractLines({
706
+ text,
707
+ startLine,
708
+ endLine
709
+ }) {
710
+ if (startLine == null && endLine == null) return text;
711
+ const lineEnding = text.includes("\r\n") ? "\r\n" : text.includes("\n") ? "\n" : text.includes("\r") ? "\r" : "\n";
712
+ const lines = text.split(lineEnding);
713
+ const start = Math.max(1, startLine != null ? startLine : 1) - 1;
714
+ const end = Math.min(lines.length, endLine != null ? endLine : lines.length);
715
+ return lines.slice(start, end).join(lineEnding);
716
+ }
717
+
704
718
  // src/extract-response-headers.ts
705
719
  function extractResponseHeaders(response) {
706
720
  return Object.fromEntries([...response.headers]);
@@ -862,7 +876,7 @@ function withUserAgentSuffix(headers, ...userAgentSuffixParts) {
862
876
  }
863
877
 
864
878
  // src/version.ts
865
- var VERSION = true ? "5.0.0-canary.40" : "0.0.0-test";
879
+ var VERSION = true ? "5.0.0-canary.43" : "0.0.0-test";
866
880
 
867
881
  // src/get-from-api.ts
868
882
  var getOriginalFetch = () => globalThis.fetch;
@@ -3349,6 +3363,7 @@ export {
3349
3363
  downloadBlob,
3350
3364
  dynamicTool,
3351
3365
  executeTool,
3366
+ extractLines,
3352
3367
  extractResponseHeaders,
3353
3368
  filterNullable,
3354
3369
  generateId,