@ai-sdk/tool-bash 0.0.0 → 1.0.2

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 ADDED
@@ -0,0 +1,29 @@
1
+ # @ai-sdk/tool-bash
2
+
3
+ ## 1.0.2
4
+
5
+ ### Patch Changes
6
+
7
+ - e5b95d3: Add an optional per-command `timeout` in milliseconds to the bash tool.
8
+ - ai@7.0.148
9
+
10
+ ## 1.0.1
11
+
12
+ ### Patch Changes
13
+
14
+ - d00577b: chore(tool-bash): mark the bash tool as experimental
15
+ - Updated dependencies [66e74dc]
16
+ - ai@7.0.147
17
+
18
+ ## 1.0.0
19
+
20
+ ### Major Changes
21
+
22
+ - f64657e: feat(tool-bash): add the first-party bash tool
23
+
24
+ ### Patch Changes
25
+
26
+ - Updated dependencies [0c2a9de]
27
+ - Updated dependencies [3785b2e]
28
+ - Updated dependencies [ab8eb61]
29
+ - ai@7.0.146
package/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Copyright 2023 Vercel, Inc.
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md CHANGED
@@ -1,4 +1,115 @@
1
- # @ai-sdk/tool-bash
1
+ # AI SDK Bash Tool
2
2
 
3
- Seed package provisioned by the internal npm provisioning control plane.
4
- Releases are published from [`vercel/ai`](https://github.com/vercel/ai) via `release.yml` using npm Trusted Publishing.
3
+ A first-party, provider-independent bash tool for the [AI SDK](https://ai-sdk.dev/docs).
4
+
5
+ The `@ai-sdk/tool-bash` entry point provides a bash tool for any model supporting
6
+ function calling. Supply an `Experimental_SandboxSession` to choose where commands
7
+ run. Use `@ai-sdk/sandbox-just-bash` for an in-memory environment,
8
+ `@ai-sdk/sandbox-vercel` for Vercel Sandbox, or your own implementation.
9
+
10
+ The tool has no direct dependency on either runtime.
11
+
12
+ ## Installation
13
+
14
+ Install the tool and the sandbox adapter you want to use:
15
+
16
+ ```sh
17
+ pnpm add ai @ai-sdk/tool-bash @ai-sdk/sandbox-just-bash
18
+ ```
19
+
20
+ Requires Node.js 22.13 or newer.
21
+
22
+ ## Usage
23
+
24
+ ```ts
25
+ import { createJustBashNetworkSandboxSession } from '@ai-sdk/sandbox-just-bash';
26
+ import { experimental_createBashTool as createBashTool } from '@ai-sdk/tool-bash';
27
+ import { generateText, isStepCount } from 'ai';
28
+
29
+ const session = await createJustBashNetworkSandboxSession();
30
+
31
+ try {
32
+ const sandbox = session.restricted();
33
+ await sandbox.writeTextFile({
34
+ path: 'notes.txt',
35
+ content: 'Apples: 10\nPears: 20\n',
36
+ });
37
+ const bash = await createBashTool({ sandbox });
38
+
39
+ const result = await generateText({
40
+ model, // Your configured model with function calling support.
41
+ tools: { bash },
42
+ stopWhen: isStepCount(5),
43
+ prompt: 'Read notes.txt and write a summary to summary.txt.',
44
+ });
45
+
46
+ console.log(result.text);
47
+ console.log(await sandbox.readTextFile({ path: 'summary.txt' }));
48
+ } finally {
49
+ await session.destroy();
50
+ }
51
+ ```
52
+
53
+ `experimental_createBashTool()` returns the tool directly. Read generated files through the
54
+ supplied sandbox using `readTextFile({ path })`, which returns `null` if missing.
55
+ The just-bash adapter resolves relative read paths against its default directory.
56
+ When overriding `workingDirectory`, use absolute paths to read files there.
57
+
58
+ The caller owns the sandbox lifecycle. Tools sharing a session share files.
59
+ Seed files through `sandbox.writeTextFile({ path, content })` before running the
60
+ tool. Commands use the sandbox's default working directory. Set
61
+ `workingDirectory` to an absolute path to override it; explicit directories are
62
+ created if needed. Without an override, creating the tool runs no setup commands.
63
+ Commands, networking, and persistence depend on the sandbox.
64
+
65
+ ## Vercel Sandbox
66
+
67
+ Install `@ai-sdk/sandbox-vercel` and `@vercel/sandbox` to use an existing native
68
+ Vercel Sandbox. Wrap it with the adapter before passing it to the tool:
69
+
70
+ ```ts
71
+ import { createVercelSandboxSessionFromNativeSandbox } from '@ai-sdk/sandbox-vercel';
72
+ import { experimental_createBashTool as createBashTool } from '@ai-sdk/tool-bash';
73
+ import { Sandbox } from '@vercel/sandbox';
74
+
75
+ const nativeSandbox = await Sandbox.create();
76
+
77
+ try {
78
+ const sandbox = createVercelSandboxSessionFromNativeSandbox(nativeSandbox);
79
+ await sandbox.writeTextFile({
80
+ path: 'notes.txt',
81
+ content: 'Hello from Vercel Sandbox',
82
+ });
83
+ const bash = await createBashTool({ sandbox });
84
+
85
+ // Use bash with generateText, streamText, or ToolLoopAgent here.
86
+ } finally {
87
+ await nativeSandbox.stop();
88
+ }
89
+ ```
90
+
91
+ You can also create a managed session with
92
+ `createVercelNetworkSandboxSession()` from `@ai-sdk/sandbox-vercel` and pass
93
+ `session.restricted()`. For an existing native just-bash `Sandbox`, use
94
+ `createJustBashSandboxSessionFromNativeSandbox()` from `@ai-sdk/sandbox-just-bash`.
95
+ Raw runtime instances need their respective adapters; a custom
96
+ `Experimental_SandboxSession` can be passed directly.
97
+
98
+ Pass `maxOutputLength` to limit characters retained from each output stream
99
+ (default: 30,000). Cancellation is forwarded to the supplied session.
100
+
101
+ Pass `timeout` to set a timeout in milliseconds for each command execution:
102
+
103
+ ```ts
104
+ const bash = await createBashTool({ sandbox, timeout: 10_000 });
105
+ ```
106
+
107
+ The value must be an integer from `1` to `2147483647`. There is no tool-level
108
+ timeout by default. Each execution gets a fresh timeout; initialization and
109
+ waiting for the model or approval are excluded. The timeout is combined with
110
+ the caller's abort signal, and the sandbox must honor cancellation. The
111
+ sandbox's result or error is passed through (just-bash returns exit code `124`
112
+ when a running command is cancelled).
113
+
114
+ See the [Bash Tool documentation](https://ai-sdk.dev/docs/ai-sdk-core/tools#bash-tool)
115
+ for options and file handling.
@@ -0,0 +1,39 @@
1
+ import { Experimental_SandboxSession, Tool, ToolExecuteFunction } from "ai";
2
+ import { z } from "zod/v4";
3
+ //#region src/bash-tool.d.ts
4
+ type BashInput = z.infer<typeof inputSchema>;
5
+ type BashOutput = z.infer<typeof outputSchema>;
6
+ declare const inputSchema: z.ZodObject<{
7
+ command: z.ZodString;
8
+ }, z.core.$strip>;
9
+ declare const outputSchema: z.ZodObject<{
10
+ stdout: z.ZodString;
11
+ stderr: z.ZodString;
12
+ exitCode: z.ZodNumber;
13
+ }, z.core.$strip>;
14
+ /**
15
+ * Create a provider-independent bash tool backed by a supplied sandbox session.
16
+ *
17
+ * The caller owns the sandbox's lifecycle. Tools using the same session share
18
+ * its files. Available commands and persistence depend on the sandbox.
19
+ * Returns the tool; use the supplied sandbox for file access.
20
+ *
21
+ * @param sandbox - Sandbox session used for commands and file operations.
22
+ * @param workingDirectory - Optional absolute starting directory for every
23
+ * command, created if needed. When omitted, uses the sandbox's default directory.
24
+ * @param maxOutputLength - Maximum characters retained from each output stream
25
+ * before appending a truncation notice. Defaults to 30,000.
26
+ * @param timeout - Optional timeout in milliseconds for each command execution.
27
+ * Cancellation is forwarded to the sandbox along with the caller's abort signal.
28
+ */
29
+ declare function createBashTool({ sandbox, workingDirectory, maxOutputLength, timeout }: {
30
+ sandbox: Experimental_SandboxSession;
31
+ workingDirectory?: string;
32
+ maxOutputLength?: number;
33
+ timeout?: number;
34
+ }): Promise<Tool<BashInput, BashOutput, {}> & {
35
+ execute: ToolExecuteFunction<BashInput, BashOutput, {}>;
36
+ }>;
37
+ //#endregion
38
+ export { createBashTool as experimental_createBashTool };
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":["SandboxSession"],"sources":["../src/bash-tool.ts"],"mappings":";;;KAUK,YAAY,EAAE,aAAa;KAE3B,aAAa,EAAE,aAAa;cAE3B,aAAW,EAAA;;GAEf,EAAA,KAAA;cAEI,cAAY,EAAA;;;;GAIhB,EAAA,KAAA;;;;;;;;;;;;;;;;iBAyBoB,iBACpB,SACA,kBACA,iBACA;EAEA,SAASA;EACT;EACA;EACA;IACE,QACF,KAAK,WAAW;EACd,SAAS,oBAAoB,WAAW"}
package/dist/index.js ADDED
@@ -0,0 +1,74 @@
1
+ import { InvalidArgumentError, tool } from "ai";
2
+ import { posix } from "node:path";
3
+ import { z } from "zod/v4";
4
+ //#region src/bash-tool.ts
5
+ const inputSchema = z.object({ command: z.string().describe("The Bash command or script to execute.") });
6
+ const outputSchema = z.object({
7
+ stdout: z.string(),
8
+ stderr: z.string(),
9
+ exitCode: z.number()
10
+ });
11
+ function limitOutput(output, maxLength) {
12
+ if (output.length <= maxLength) return output;
13
+ return `${output.slice(0, maxLength)}\n[Output truncated: ${output.length - maxLength} characters omitted.]`;
14
+ }
15
+ /**
16
+ * Create a provider-independent bash tool backed by a supplied sandbox session.
17
+ *
18
+ * The caller owns the sandbox's lifecycle. Tools using the same session share
19
+ * its files. Available commands and persistence depend on the sandbox.
20
+ * Returns the tool; use the supplied sandbox for file access.
21
+ *
22
+ * @param sandbox - Sandbox session used for commands and file operations.
23
+ * @param workingDirectory - Optional absolute starting directory for every
24
+ * command, created if needed. When omitted, uses the sandbox's default directory.
25
+ * @param maxOutputLength - Maximum characters retained from each output stream
26
+ * before appending a truncation notice. Defaults to 30,000.
27
+ * @param timeout - Optional timeout in milliseconds for each command execution.
28
+ * Cancellation is forwarded to the sandbox along with the caller's abort signal.
29
+ */
30
+ async function createBashTool({ sandbox, workingDirectory, maxOutputLength = 3e4, timeout }) {
31
+ if (timeout !== void 0 && (!Number.isInteger(timeout) || timeout < 1 || timeout > 2147483647)) throw new InvalidArgumentError({
32
+ parameter: "timeout",
33
+ value: timeout,
34
+ message: "Must be an integer between 1 and 2147483647 milliseconds."
35
+ });
36
+ if (!Number.isSafeInteger(maxOutputLength) || maxOutputLength < 1) throw new InvalidArgumentError({
37
+ parameter: "maxOutputLength",
38
+ value: maxOutputLength,
39
+ message: "Must be a positive safe integer."
40
+ });
41
+ if (workingDirectory !== void 0 && !posix.isAbsolute(workingDirectory)) throw new InvalidArgumentError({
42
+ parameter: "workingDirectory",
43
+ value: workingDirectory,
44
+ message: "Must be an absolute path in the sandbox."
45
+ });
46
+ if (workingDirectory !== void 0) workingDirectory = posix.normalize(workingDirectory);
47
+ if (workingDirectory !== void 0) {
48
+ const directoryResult = await sandbox.run({ command: `mkdir -p -- '${workingDirectory.replace(/'/g, "'\\''")}'` });
49
+ if (directoryResult.exitCode !== 0) throw new Error(`Failed to create working directory: ${directoryResult.stderr}`);
50
+ }
51
+ return tool({
52
+ description: "Run Bash commands in the sandbox. " + (workingDirectory !== void 0 ? `Every command starts in ${workingDirectory}. ` : "Commands run in the sandbox's default working directory. ") + "Use ls to discover files and commands such as cat, grep, sort, awk, and jq to inspect and transform them. Pipes and redirections are supported. Returns stdout, stderr, and exitCode; long output is truncated.\n" + sandbox.description,
53
+ inputSchema,
54
+ outputSchema,
55
+ execute: async ({ command }, { abortSignal }) => {
56
+ const timeoutSignal = timeout === void 0 ? void 0 : AbortSignal.timeout(timeout);
57
+ const commandSignal = timeoutSignal === void 0 ? abortSignal : abortSignal === void 0 ? timeoutSignal : AbortSignal.any([abortSignal, timeoutSignal]);
58
+ const { stdout, stderr, exitCode } = await sandbox.run({
59
+ command,
60
+ ...workingDirectory !== void 0 ? { workingDirectory } : {},
61
+ abortSignal: commandSignal
62
+ });
63
+ return {
64
+ stdout: limitOutput(stdout, maxOutputLength),
65
+ stderr: limitOutput(stderr, maxOutputLength),
66
+ exitCode
67
+ };
68
+ }
69
+ });
70
+ }
71
+ //#endregion
72
+ export { createBashTool as experimental_createBashTool };
73
+
74
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/bash-tool.ts"],"sourcesContent":["import {\n InvalidArgumentError,\n tool,\n type Tool,\n type ToolExecuteFunction,\n type Experimental_SandboxSession as SandboxSession,\n} from 'ai';\nimport { posix } from 'node:path';\nimport { z } from 'zod/v4';\n\ntype BashInput = z.infer<typeof inputSchema>;\n\ntype BashOutput = z.infer<typeof outputSchema>;\n\nconst inputSchema = z.object({\n command: z.string().describe('The Bash command or script to execute.'),\n});\n\nconst outputSchema = z.object({\n stdout: z.string(),\n stderr: z.string(),\n exitCode: z.number(),\n});\n\nfunction limitOutput(output: string, maxLength: number): string {\n if (output.length <= maxLength) {\n return output;\n }\n\n return `${output.slice(0, maxLength)}\\n[Output truncated: ${output.length - maxLength} characters omitted.]`;\n}\n\n/**\n * Create a provider-independent bash tool backed by a supplied sandbox session.\n *\n * The caller owns the sandbox's lifecycle. Tools using the same session share\n * its files. Available commands and persistence depend on the sandbox.\n * Returns the tool; use the supplied sandbox for file access.\n *\n * @param sandbox - Sandbox session used for commands and file operations.\n * @param workingDirectory - Optional absolute starting directory for every\n * command, created if needed. When omitted, uses the sandbox's default directory.\n * @param maxOutputLength - Maximum characters retained from each output stream\n * before appending a truncation notice. Defaults to 30,000.\n * @param timeout - Optional timeout in milliseconds for each command execution.\n * Cancellation is forwarded to the sandbox along with the caller's abort signal.\n */\nexport async function createBashTool({\n sandbox,\n workingDirectory,\n maxOutputLength = 30_000,\n timeout,\n}: {\n sandbox: SandboxSession;\n workingDirectory?: string;\n maxOutputLength?: number;\n timeout?: number;\n}): Promise<\n Tool<BashInput, BashOutput, {}> & {\n execute: ToolExecuteFunction<BashInput, BashOutput, {}>;\n }\n> {\n if (\n timeout !== undefined &&\n (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483_647)\n ) {\n throw new InvalidArgumentError({\n parameter: 'timeout',\n value: timeout,\n message: 'Must be an integer between 1 and 2147483647 milliseconds.',\n });\n }\n\n if (!Number.isSafeInteger(maxOutputLength) || maxOutputLength < 1) {\n throw new InvalidArgumentError({\n parameter: 'maxOutputLength',\n value: maxOutputLength,\n message: 'Must be a positive safe integer.',\n });\n }\n\n if (workingDirectory !== undefined && !posix.isAbsolute(workingDirectory)) {\n throw new InvalidArgumentError({\n parameter: 'workingDirectory',\n value: workingDirectory,\n message: 'Must be an absolute path in the sandbox.',\n });\n }\n\n if (workingDirectory !== undefined) {\n workingDirectory = posix.normalize(workingDirectory);\n }\n\n if (workingDirectory !== undefined) {\n const directoryResult = await sandbox.run({\n command: `mkdir -p -- '${workingDirectory.replace(/'/g, \"'\\\\''\")}'`,\n });\n if (directoryResult.exitCode !== 0) {\n throw new Error(\n `Failed to create working directory: ${directoryResult.stderr}`,\n );\n }\n }\n\n return tool<BashInput, BashOutput, {}>({\n description:\n 'Run Bash commands in the sandbox. ' +\n (workingDirectory !== undefined\n ? `Every command starts in ${workingDirectory}. `\n : \"Commands run in the sandbox's default working directory. \") +\n 'Use ls to discover files and commands such as cat, grep, sort, awk, ' +\n 'and jq to inspect and transform them. Pipes and redirections are supported. ' +\n 'Returns stdout, stderr, and exitCode; long output is truncated.\\n' +\n sandbox.description,\n inputSchema,\n outputSchema,\n execute: async ({ command }, { abortSignal }) => {\n const timeoutSignal =\n timeout === undefined ? undefined : AbortSignal.timeout(timeout);\n const commandSignal =\n timeoutSignal === undefined\n ? abortSignal\n : abortSignal === undefined\n ? timeoutSignal\n : AbortSignal.any([abortSignal, timeoutSignal]);\n\n const { stdout, stderr, exitCode } = await sandbox.run({\n command,\n ...(workingDirectory !== undefined ? { workingDirectory } : {}),\n abortSignal: commandSignal,\n });\n\n return {\n stdout: limitOutput(stdout, maxOutputLength),\n stderr: limitOutput(stderr, maxOutputLength),\n exitCode,\n };\n },\n });\n}\n"],"mappings":";;;;AAcA,MAAM,cAAc,EAAE,OAAO,EAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS,wCAAwC,EACvE,CAAC;AAED,MAAM,eAAe,EAAE,OAAO;CAC5B,QAAQ,EAAE,OAAO;CACjB,QAAQ,EAAE,OAAO;CACjB,UAAU,EAAE,OAAO;AACrB,CAAC;AAED,SAAS,YAAY,QAAgB,WAA2B;CAC9D,IAAI,OAAO,UAAU,WACnB,OAAO;CAGT,OAAO,GAAG,OAAO,MAAM,GAAG,SAAS,EAAE,uBAAuB,OAAO,SAAS,UAAU;AACxF;;;;;;;;;;;;;;;;AAiBA,eAAsB,eAAe,EACnC,SACA,kBACA,kBAAkB,KAClB,WAUA;CACA,IACE,YAAY,KAAA,MACX,CAAC,OAAO,UAAU,OAAO,KAAK,UAAU,KAAK,UAAU,aAExD,MAAM,IAAI,qBAAqB;EAC7B,WAAW;EACX,OAAO;EACP,SAAS;CACX,CAAC;CAGH,IAAI,CAAC,OAAO,cAAc,eAAe,KAAK,kBAAkB,GAC9D,MAAM,IAAI,qBAAqB;EAC7B,WAAW;EACX,OAAO;EACP,SAAS;CACX,CAAC;CAGH,IAAI,qBAAqB,KAAA,KAAa,CAAC,MAAM,WAAW,gBAAgB,GACtE,MAAM,IAAI,qBAAqB;EAC7B,WAAW;EACX,OAAO;EACP,SAAS;CACX,CAAC;CAGH,IAAI,qBAAqB,KAAA,GACvB,mBAAmB,MAAM,UAAU,gBAAgB;CAGrD,IAAI,qBAAqB,KAAA,GAAW;EAClC,MAAM,kBAAkB,MAAM,QAAQ,IAAI,EACxC,SAAS,gBAAgB,iBAAiB,QAAQ,MAAM,OAAO,EAAE,GACnE,CAAC;EACD,IAAI,gBAAgB,aAAa,GAC/B,MAAM,IAAI,MACR,uCAAuC,gBAAgB,QACzD;CAEJ;CAEA,OAAO,KAAgC;EACrC,aACE,wCACC,qBAAqB,KAAA,IAClB,2BAA2B,iBAAiB,MAC5C,+DACJ,sNAGA,QAAQ;EACV;EACA;EACA,SAAS,OAAO,EAAE,WAAW,EAAE,kBAAkB;GAC/C,MAAM,gBACJ,YAAY,KAAA,IAAY,KAAA,IAAY,YAAY,QAAQ,OAAO;GACjE,MAAM,gBACJ,kBAAkB,KAAA,IACd,cACA,gBAAgB,KAAA,IACd,gBACA,YAAY,IAAI,CAAC,aAAa,aAAa,CAAC;GAEpD,MAAM,EAAE,QAAQ,QAAQ,aAAa,MAAM,QAAQ,IAAI;IACrD;IACA,GAAI,qBAAqB,KAAA,IAAY,EAAE,iBAAiB,IAAI,CAAC;IAC7D,aAAa;GACf,CAAC;GAED,OAAO;IACL,QAAQ,YAAY,QAAQ,eAAe;IAC3C,QAAQ,YAAY,QAAQ,eAAe;IAC3C;GACF;EACF;CACF,CAAC;AACH"}
package/package.json CHANGED
@@ -1,22 +1,68 @@
1
1
  {
2
2
  "name": "@ai-sdk/tool-bash",
3
- "version": "0.0.0",
4
- "description": "Seed for @ai-sdk/tool-bash, provisioned by the npm provisioning control plane.",
3
+ "version": "1.0.2",
4
+ "description": "Provider-independent bash tool for the AI SDK",
5
5
  "type": "module",
6
- "main": "./index.js",
7
- "exports": {
8
- ".": "./index.js"
9
- },
6
+ "license": "Apache-2.0",
7
+ "sideEffects": false,
8
+ "main": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "source": "./src/index.ts",
10
11
  "files": [
11
- "index.js",
12
+ "dist/**/*",
13
+ "src",
14
+ "!src/**/*.test.ts",
15
+ "!src/**/*.test-d.ts",
16
+ "CHANGELOG.md",
12
17
  "README.md"
13
18
  ],
19
+ "exports": {
20
+ "./package.json": "./package.json",
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "default": "./dist/index.js"
25
+ }
26
+ },
27
+ "dependencies": {
28
+ "zod": "3.25.76"
29
+ },
30
+ "peerDependencies": {
31
+ "ai": "^7.0.148"
32
+ },
33
+ "devDependencies": {
34
+ "@ai-sdk/sandbox-just-bash": "1.0.159",
35
+ "@ai-sdk/sandbox-vercel": "1.0.159",
36
+ "@types/node": "22.19.19",
37
+ "@vercel/ai-tsconfig": "0.0.0",
38
+ "@vercel/ai-tsdown-config": "0.0.0",
39
+ "ai": "7.0.148",
40
+ "tsdown": "^0.23.0",
41
+ "typescript": "6.0.3"
42
+ },
43
+ "engines": {
44
+ "node": ">=22.13.0"
45
+ },
14
46
  "publishConfig": {
15
47
  "access": "public",
16
- "registry": "https://registry.npmjs.org/"
48
+ "provenance": true
17
49
  },
50
+ "homepage": "https://ai-sdk.dev/docs",
18
51
  "repository": {
19
52
  "type": "git",
20
- "url": "https://github.com/vercel/ai.git"
53
+ "url": "https://github.com/vercel/ai",
54
+ "directory": "packages/tool-bash"
55
+ },
56
+ "bugs": {
57
+ "url": "https://github.com/vercel/ai/issues"
58
+ },
59
+ "scripts": {
60
+ "build": "pnpm clean && tsdown",
61
+ "build:watch": "tsdown --watch",
62
+ "clean": "del-cli *.tsbuildinfo",
63
+ "type-check": "tsc --build",
64
+ "test": "pnpm test:node",
65
+ "test:node": "vitest --config vitest.node.config.js --run",
66
+ "test:watch": "vitest --config vitest.node.config.js"
21
67
  }
22
- }
68
+ }
@@ -0,0 +1,140 @@
1
+ import {
2
+ InvalidArgumentError,
3
+ tool,
4
+ type Tool,
5
+ type ToolExecuteFunction,
6
+ type Experimental_SandboxSession as SandboxSession,
7
+ } from 'ai';
8
+ import { posix } from 'node:path';
9
+ import { z } from 'zod/v4';
10
+
11
+ type BashInput = z.infer<typeof inputSchema>;
12
+
13
+ type BashOutput = z.infer<typeof outputSchema>;
14
+
15
+ const inputSchema = z.object({
16
+ command: z.string().describe('The Bash command or script to execute.'),
17
+ });
18
+
19
+ const outputSchema = z.object({
20
+ stdout: z.string(),
21
+ stderr: z.string(),
22
+ exitCode: z.number(),
23
+ });
24
+
25
+ function limitOutput(output: string, maxLength: number): string {
26
+ if (output.length <= maxLength) {
27
+ return output;
28
+ }
29
+
30
+ return `${output.slice(0, maxLength)}\n[Output truncated: ${output.length - maxLength} characters omitted.]`;
31
+ }
32
+
33
+ /**
34
+ * Create a provider-independent bash tool backed by a supplied sandbox session.
35
+ *
36
+ * The caller owns the sandbox's lifecycle. Tools using the same session share
37
+ * its files. Available commands and persistence depend on the sandbox.
38
+ * Returns the tool; use the supplied sandbox for file access.
39
+ *
40
+ * @param sandbox - Sandbox session used for commands and file operations.
41
+ * @param workingDirectory - Optional absolute starting directory for every
42
+ * command, created if needed. When omitted, uses the sandbox's default directory.
43
+ * @param maxOutputLength - Maximum characters retained from each output stream
44
+ * before appending a truncation notice. Defaults to 30,000.
45
+ * @param timeout - Optional timeout in milliseconds for each command execution.
46
+ * Cancellation is forwarded to the sandbox along with the caller's abort signal.
47
+ */
48
+ export async function createBashTool({
49
+ sandbox,
50
+ workingDirectory,
51
+ maxOutputLength = 30_000,
52
+ timeout,
53
+ }: {
54
+ sandbox: SandboxSession;
55
+ workingDirectory?: string;
56
+ maxOutputLength?: number;
57
+ timeout?: number;
58
+ }): Promise<
59
+ Tool<BashInput, BashOutput, {}> & {
60
+ execute: ToolExecuteFunction<BashInput, BashOutput, {}>;
61
+ }
62
+ > {
63
+ if (
64
+ timeout !== undefined &&
65
+ (!Number.isInteger(timeout) || timeout < 1 || timeout > 2_147_483_647)
66
+ ) {
67
+ throw new InvalidArgumentError({
68
+ parameter: 'timeout',
69
+ value: timeout,
70
+ message: 'Must be an integer between 1 and 2147483647 milliseconds.',
71
+ });
72
+ }
73
+
74
+ if (!Number.isSafeInteger(maxOutputLength) || maxOutputLength < 1) {
75
+ throw new InvalidArgumentError({
76
+ parameter: 'maxOutputLength',
77
+ value: maxOutputLength,
78
+ message: 'Must be a positive safe integer.',
79
+ });
80
+ }
81
+
82
+ if (workingDirectory !== undefined && !posix.isAbsolute(workingDirectory)) {
83
+ throw new InvalidArgumentError({
84
+ parameter: 'workingDirectory',
85
+ value: workingDirectory,
86
+ message: 'Must be an absolute path in the sandbox.',
87
+ });
88
+ }
89
+
90
+ if (workingDirectory !== undefined) {
91
+ workingDirectory = posix.normalize(workingDirectory);
92
+ }
93
+
94
+ if (workingDirectory !== undefined) {
95
+ const directoryResult = await sandbox.run({
96
+ command: `mkdir -p -- '${workingDirectory.replace(/'/g, "'\\''")}'`,
97
+ });
98
+ if (directoryResult.exitCode !== 0) {
99
+ throw new Error(
100
+ `Failed to create working directory: ${directoryResult.stderr}`,
101
+ );
102
+ }
103
+ }
104
+
105
+ return tool<BashInput, BashOutput, {}>({
106
+ description:
107
+ 'Run Bash commands in the sandbox. ' +
108
+ (workingDirectory !== undefined
109
+ ? `Every command starts in ${workingDirectory}. `
110
+ : "Commands run in the sandbox's default working directory. ") +
111
+ 'Use ls to discover files and commands such as cat, grep, sort, awk, ' +
112
+ 'and jq to inspect and transform them. Pipes and redirections are supported. ' +
113
+ 'Returns stdout, stderr, and exitCode; long output is truncated.\n' +
114
+ sandbox.description,
115
+ inputSchema,
116
+ outputSchema,
117
+ execute: async ({ command }, { abortSignal }) => {
118
+ const timeoutSignal =
119
+ timeout === undefined ? undefined : AbortSignal.timeout(timeout);
120
+ const commandSignal =
121
+ timeoutSignal === undefined
122
+ ? abortSignal
123
+ : abortSignal === undefined
124
+ ? timeoutSignal
125
+ : AbortSignal.any([abortSignal, timeoutSignal]);
126
+
127
+ const { stdout, stderr, exitCode } = await sandbox.run({
128
+ command,
129
+ ...(workingDirectory !== undefined ? { workingDirectory } : {}),
130
+ abortSignal: commandSignal,
131
+ });
132
+
133
+ return {
134
+ stdout: limitOutput(stdout, maxOutputLength),
135
+ stderr: limitOutput(stderr, maxOutputLength),
136
+ exitCode,
137
+ };
138
+ },
139
+ });
140
+ }
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { createBashTool as experimental_createBashTool } from './bash-tool';
package/index.js DELETED
@@ -1 +0,0 @@
1
- export {};