@ai-sdk/tool-bash 0.0.0-stage → 1.0.0
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 +14 -0
- package/LICENSE +13 -0
- package/README.md +101 -2
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +65 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -3
- package/src/bash-tool.ts +116 -0
- package/src/index.ts +1 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# @ai-sdk/tool-bash
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- f64657e: feat(tool-bash): add the first-party bash tool
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- Updated dependencies [0c2a9de]
|
|
12
|
+
- Updated dependencies [3785b2e]
|
|
13
|
+
- Updated dependencies [ab8eb61]
|
|
14
|
+
- 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,3 +1,102 @@
|
|
|
1
|
-
#
|
|
1
|
+
# AI SDK Bash Tool
|
|
2
2
|
|
|
3
|
-
|
|
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 { 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
|
+
`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 { 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
|
+
See the [Bash Tool documentation](https://ai-sdk.dev/docs/ai-sdk-core/tools#bash-tool)
|
|
102
|
+
for options and file handling.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
*/
|
|
27
|
+
export declare function createBashTool({ sandbox, workingDirectory, maxOutputLength }: {
|
|
28
|
+
sandbox: Experimental_SandboxSession;
|
|
29
|
+
workingDirectory?: string;
|
|
30
|
+
maxOutputLength?: number;
|
|
31
|
+
}): Promise<Tool<BashInput, BashOutput, {}> & {
|
|
32
|
+
execute: ToolExecuteFunction<BashInput, BashOutput, {}>;
|
|
33
|
+
}>;
|
|
34
|
+
//#endregion
|
|
35
|
+
//# 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;;;;;;;;;;;;;;wBAuBoB,iBACpB,SACA,kBACA;EAEA,SAASA;EACT;EACA;IACE,QACF,KAAK,WAAW;EACd,SAAS,oBAAoB,WAAW"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
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
|
+
*/
|
|
28
|
+
async function createBashTool({ sandbox, workingDirectory, maxOutputLength = 3e4 }) {
|
|
29
|
+
if (!Number.isSafeInteger(maxOutputLength) || maxOutputLength < 1) throw new InvalidArgumentError({
|
|
30
|
+
parameter: "maxOutputLength",
|
|
31
|
+
value: maxOutputLength,
|
|
32
|
+
message: "Must be a positive safe integer."
|
|
33
|
+
});
|
|
34
|
+
if (workingDirectory !== void 0 && !posix.isAbsolute(workingDirectory)) throw new InvalidArgumentError({
|
|
35
|
+
parameter: "workingDirectory",
|
|
36
|
+
value: workingDirectory,
|
|
37
|
+
message: "Must be an absolute path in the sandbox."
|
|
38
|
+
});
|
|
39
|
+
if (workingDirectory !== void 0) workingDirectory = posix.normalize(workingDirectory);
|
|
40
|
+
if (workingDirectory !== void 0) {
|
|
41
|
+
const directoryResult = await sandbox.run({ command: `mkdir -p -- '${workingDirectory.replace(/'/g, "'\\''")}'` });
|
|
42
|
+
if (directoryResult.exitCode !== 0) throw new Error(`Failed to create working directory: ${directoryResult.stderr}`);
|
|
43
|
+
}
|
|
44
|
+
return tool({
|
|
45
|
+
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,
|
|
46
|
+
inputSchema,
|
|
47
|
+
outputSchema,
|
|
48
|
+
execute: async ({ command }, { abortSignal }) => {
|
|
49
|
+
const { stdout, stderr, exitCode } = await sandbox.run({
|
|
50
|
+
command,
|
|
51
|
+
...workingDirectory !== void 0 ? { workingDirectory } : {},
|
|
52
|
+
abortSignal
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
stdout: limitOutput(stdout, maxOutputLength),
|
|
56
|
+
stderr: limitOutput(stderr, maxOutputLength),
|
|
57
|
+
exitCode
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
//#endregion
|
|
63
|
+
export { createBashTool };
|
|
64
|
+
|
|
65
|
+
//# 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 */\nexport async function createBashTool({\n sandbox,\n workingDirectory,\n maxOutputLength = 30_000,\n}: {\n sandbox: SandboxSession;\n workingDirectory?: string;\n maxOutputLength?: number;\n}): Promise<\n Tool<BashInput, BashOutput, {}> & {\n execute: ToolExecuteFunction<BashInput, BashOutput, {}>;\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 { stdout, stderr, exitCode } = await sandbox.run({\n command,\n ...(workingDirectory !== undefined ? { workingDirectory } : {}),\n abortSignal,\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;;;;;;;;;;;;;;AAeA,eAAsB,eAAe,EACnC,SACA,kBACA,kBAAkB,OASlB;CACA,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,EAAE,QAAQ,QAAQ,aAAa,MAAM,QAAQ,IAAI;IACrD;IACA,GAAI,qBAAqB,KAAA,IAAY,EAAE,iBAAiB,IAAI,CAAC;IAC7D;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,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/tool-bash",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Provider-independent bash tool for the AI SDK",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"sideEffects": false,
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"source": "./src/index.ts",
|
|
11
|
+
"files": [
|
|
12
|
+
"dist/**/*",
|
|
13
|
+
"src",
|
|
14
|
+
"!src/**/*.test.ts",
|
|
15
|
+
"!src/**/*.test-d.ts",
|
|
16
|
+
"CHANGELOG.md",
|
|
17
|
+
"README.md"
|
|
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.146"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"@ai-sdk/sandbox-just-bash": "1.0.157",
|
|
35
|
+
"@ai-sdk/sandbox-vercel": "1.0.157",
|
|
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.146",
|
|
40
|
+
"tsdown": "^0.23.0",
|
|
41
|
+
"typescript": "6.0.3"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=22.13.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public",
|
|
48
|
+
"provenance": true
|
|
49
|
+
},
|
|
50
|
+
"homepage": "https://ai-sdk.dev/docs",
|
|
51
|
+
"repository": {
|
|
52
|
+
"type": "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"
|
|
67
|
+
}
|
|
6
68
|
}
|
package/src/bash-tool.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
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
|
+
*/
|
|
46
|
+
export async function createBashTool({
|
|
47
|
+
sandbox,
|
|
48
|
+
workingDirectory,
|
|
49
|
+
maxOutputLength = 30_000,
|
|
50
|
+
}: {
|
|
51
|
+
sandbox: SandboxSession;
|
|
52
|
+
workingDirectory?: string;
|
|
53
|
+
maxOutputLength?: number;
|
|
54
|
+
}): Promise<
|
|
55
|
+
Tool<BashInput, BashOutput, {}> & {
|
|
56
|
+
execute: ToolExecuteFunction<BashInput, BashOutput, {}>;
|
|
57
|
+
}
|
|
58
|
+
> {
|
|
59
|
+
if (!Number.isSafeInteger(maxOutputLength) || maxOutputLength < 1) {
|
|
60
|
+
throw new InvalidArgumentError({
|
|
61
|
+
parameter: 'maxOutputLength',
|
|
62
|
+
value: maxOutputLength,
|
|
63
|
+
message: 'Must be a positive safe integer.',
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (workingDirectory !== undefined && !posix.isAbsolute(workingDirectory)) {
|
|
68
|
+
throw new InvalidArgumentError({
|
|
69
|
+
parameter: 'workingDirectory',
|
|
70
|
+
value: workingDirectory,
|
|
71
|
+
message: 'Must be an absolute path in the sandbox.',
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (workingDirectory !== undefined) {
|
|
76
|
+
workingDirectory = posix.normalize(workingDirectory);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (workingDirectory !== undefined) {
|
|
80
|
+
const directoryResult = await sandbox.run({
|
|
81
|
+
command: `mkdir -p -- '${workingDirectory.replace(/'/g, "'\\''")}'`,
|
|
82
|
+
});
|
|
83
|
+
if (directoryResult.exitCode !== 0) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Failed to create working directory: ${directoryResult.stderr}`,
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return tool<BashInput, BashOutput, {}>({
|
|
91
|
+
description:
|
|
92
|
+
'Run Bash commands in the sandbox. ' +
|
|
93
|
+
(workingDirectory !== undefined
|
|
94
|
+
? `Every command starts in ${workingDirectory}. `
|
|
95
|
+
: "Commands run in the sandbox's default working directory. ") +
|
|
96
|
+
'Use ls to discover files and commands such as cat, grep, sort, awk, ' +
|
|
97
|
+
'and jq to inspect and transform them. Pipes and redirections are supported. ' +
|
|
98
|
+
'Returns stdout, stderr, and exitCode; long output is truncated.\n' +
|
|
99
|
+
sandbox.description,
|
|
100
|
+
inputSchema,
|
|
101
|
+
outputSchema,
|
|
102
|
+
execute: async ({ command }, { abortSignal }) => {
|
|
103
|
+
const { stdout, stderr, exitCode } = await sandbox.run({
|
|
104
|
+
command,
|
|
105
|
+
...(workingDirectory !== undefined ? { workingDirectory } : {}),
|
|
106
|
+
abortSignal,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
stdout: limitOutput(stdout, maxOutputLength),
|
|
111
|
+
stderr: limitOutput(stderr, maxOutputLength),
|
|
112
|
+
exitCode,
|
|
113
|
+
};
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { createBashTool } from './bash-tool';
|