### Advanced Usage Examples Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Demonstrates advanced configurations and usage patterns for bash-tool, including uploading directories, using Vercel Sandbox, persistent sandboxes, custom bash instances, and intercepting commands. ```APIDOC ## Upload a local directory ### Description Uploads a local directory to the sandbox environment, optionally filtering files using glob patterns. ### Method Not applicable (configuration option for `createBashTool`) ### Endpoint Not applicable ### Parameters #### `createBashTool` Options - **uploadDirectory** (object) - Optional - Configuration for uploading a directory. - **source** (string) - Required - The local path to the directory to upload. - **include** (string) - Optional - A glob pattern to filter which files to include (e.g., `**/*.{ts,json}`). ### Request Example ```typescript import { createBashTool } from "bash-tool"; const { bash } = await createBashTool({ uploadDirectory: { source: "./my-project", include: "**/*.{ts,json}", // optional glob filter }, }); ``` ## Use [@vercel/sandbox](https://vercel.com/docs/vercel-sandbox) for full VM ### Description Integrates bash-tool with `@vercel/sandbox` for a full virtual machine environment. ### Method Not applicable (configuration option for `createBashTool`) ### Endpoint Not applicable ### Parameters #### `createBashTool` Options - **sandbox** (Sandbox) - Optional - An instance of `Sandbox` from `@vercel/sandbox`. - **files** (object) - Optional - An object mapping file paths to their content to be created in the sandbox. ### Request Example ```typescript import { createBashTool } from "bash-tool"; import { Sandbox } from "@vercel/sandbox"; const sandbox = await Sandbox.create(); const { tools } = await createBashTool({ sandbox, files: { "index.ts": "console.log('hello');" }, }); ``` ## Persistent sandbox across serverless invocations ### Description Allows reconnecting to an existing sandbox across multiple serverless function invocations using `Sandbox.get`. ### Method Not applicable (usage pattern with `Sandbox.create` and `Sandbox.get`) ### Endpoint Not applicable ### Parameters #### `Sandbox.get` Options - **sandboxId** (string) - Required - The unique identifier of the sandbox to reconnect to. ### Request Example ```typescript import { Sandbox } from "@vercel/sandbox"; // First invocation: create sandbox and store the ID const newSandbox = await Sandbox.create(); const sandboxId = newSandbox.sandboxId; // Store sandboxId in database, session, or return to client // Subsequent invocations: reconnect to existing sandbox const existingSandbox = await Sandbox.get({ sandboxId }); const { tools } = await createBashTool({ sandbox: existingSandbox }); // All previous files and state are preserved ``` ## Use a custom just-bash instance ### Description Allows using a custom instance of `just-bash` with specific configurations, such as a working directory. ### Method Not applicable (configuration option for `createBashTool`) ### Endpoint Not applicable ### Parameters #### `createBashTool` Options - **sandbox** (Bash) - Optional - A custom instance of `Bash` from `just-bash`. - **destination** (string) - Optional - The destination path within the sandbox for uploaded files. ### Request Example ```typescript import { Bash } from "just-bash"; import { createBashTool } from "bash-tool"; const sandbox = new Bash({ cwd: "/app" }); const { tools } = await createBashTool({ sandbox, destination: "/app", }); ``` ## Intercept bash commands ### Description Provides lifecycle hooks (`onBeforeBashCall`, `onAfterBashCall`) to intercept and modify bash commands or their results. ### Method Not applicable (configuration options for `createBashTool`) ### Endpoint Not applicable ### Parameters #### `createBashTool` Options - **onBeforeBashCall** (function) - Optional - A callback function executed before a bash command is run. It can modify the command. - **Input:** `{ command: string }` - **Returns:** `{ command: string }` - The modified command or original command. - **onAfterBashCall** (function) - Optional - A callback function executed after a bash command has run. It can modify the result. - **Input:** `{ command: string, result: { stdout: string, stderr: string, exitCode: number } }` - **Returns:** `{ result: { stdout: string, stderr: string, exitCode: number } }` - The modified result or original result. ### Request Example ```typescript import { createBashTool } from "bash-tool"; const { tools } = await createBashTool({ onBeforeBashCall: ({ command }) => { console.log("Running:", command); // Optionally modify the command if (command.includes("rm -rf")) { return { command: "echo 'Blocked dangerous command'" }; } }, onAfterBashCall: ({ command, result }) => { console.log(`Exit code: ${result.exitCode}`); // Optionally modify the result return { result: { ...result, stdout: result.stdout.trim() } }; }, }); ``` ## Custom sandbox implementation ### Description Allows providing a completely custom sandbox implementation that adheres to the `Sandbox` interface. ### Method Not applicable (configuration option for `createBashTool`) ### Endpoint Not applicable ### Parameters #### `createBashTool` Options - **sandbox** (Sandbox) - Required - A custom object implementing the `Sandbox` interface with `executeCommand`, `readFile`, and `writeFile` methods. ### Request Example ```typescript import { createBashTool, Sandbox } from "bash-tool"; const customSandbox: Sandbox = { async executeCommand(command) { // Your implementation here return { stdout: "", stderr: "", exitCode: 0 }; }, async readFile(path) { // Your implementation here return ""; }, async writeFile(path, content) { // Your implementation here }, }; const { tools } = await createBashTool({ sandbox: customSandbox }); ``` ``` -------------------------------- ### Implement Custom Sandbox with LoggingSandbox Source: https://context7.com/vercel-labs/bash-tool/llms.txt Shows how to implement a custom sandbox backend by creating a class that conforms to the `Sandbox` interface. The `LoggingSandbox` example logs all operations to a remote service and simulates command execution. This allows for custom backend logic for command execution and file operations. Dependencies include 'bash-tool' and 'ai' SDKs. ```typescript import { createBashTool, Sandbox, CommandResult } from "bash-tool"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; // Custom sandbox that logs everything to a remote service class LoggingSandbox implements Sandbox { private fileSystem = new Map(); async executeCommand(command: string): Promise { console.log("Remote API - Executing:", command); // Simulate command execution if (command.includes("echo")) { const match = command.match(/echo ['"](.+)['"]/); return { stdout: match ? match[1] + "\n" : "", stderr: "", exitCode: 0 }; } if (command.includes("ls")) { const files = Array.from(this.fileSystem.keys()).join("\n"); return { stdout: files, stderr: "", exitCode: 0 }; } return { stdout: "", stderr: "Command not implemented", exitCode: 1 }; } async readFile(path: string): Promise { console.log("Remote API - Reading:", path); const content = this.fileSystem.get(path); if (!content) { throw new Error(`File not found: ${path}`); } return content; } async writeFiles(files: Array<{ path: string; content: string | Buffer }>): Promise { for (const file of files) { const content = typeof file.content === "string" ? file.content : file.content.toString("utf-8"); console.log("Remote API - Writing:", file.path); this.fileSystem.set(file.path, content); } } } // Use custom sandbox const customSandbox = new LoggingSandbox(); const { tools } = await createBashTool({ sandbox: customSandbox, files: { "config.json": JSON.stringify({ env: "production" }) } }); const result = await generateText({ model: openai("gpt-4-turbo"), tools, maxSteps: 3, prompt: "List all files" }); console.log(result.text); ``` -------------------------------- ### Install bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Installs the bash-tool npm package and the `just-bash` library for bash command execution. For full VM support, consider installing `@vercel/sandbox` or other sandbox products. ```bash npm install bash-tool just-bash ``` -------------------------------- ### Create bash-tool and use with AI agent Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Demonstrates how to create a bash-tool with initial files and integrate it into an AI agent. This setup allows the agent to interact with the filesystem and execute bash commands within a sandboxed environment. ```typescript import { createBashTool } from "bash-tool"; import { ToolLoopAgent, stepCountIs } from "ai"; const { tools } = await createBashTool({ files: { "src/index.ts": "export const x = 1;", "package.json": '{"name": "test"}', }, }); const agent = new ToolLoopAgent({ model, tools, // Or use just the bash tool as tools: {bash: tools.bash} stopWhen: stepCountIs(20), }); const result = await agent.generate({ prompt: "List files in src/", }); ``` -------------------------------- ### Discover Tools and Detect File Formats with bash-tool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Shows how to automatically discover available bash utilities in a sandbox, detect file formats (JSON, CSV), and get a list of tools suitable for specific formats. It also demonstrates creating a comprehensive tool prompt for AI, including format-specific tool recommendations. ```typescript import { createBashTool, discoverAvailableTools, detectFormat, getToolsForFormat, createToolPrompt, bashTools } from "bash-tool"; const { sandbox } = await createBashTool({ files: { "data.json": JSON.stringify({ items: [1, 2, 3] }), "config.yaml": "port: 3000\nhost: localhost", "users.csv": "id,name\n1,Alice\n2,Bob" } }); // Discover what tools are available in the sandbox const availableTools = await discoverAvailableTools(sandbox); console.log("Available tools:", Array.from(availableTools)); // Output: ["grep", "sed", "awk", "cat", "head", "tail", "jq", "yq", "xan", ...] // Detect file format const jsonFormat = detectFormat("data.json"); console.log("Format:", jsonFormat); // "json" const csvFormat = detectFormat("users.csv"); console.log("Format:", csvFormat); // "csv" // Get tools suitable for JSON const jsonTools = getToolsForFormat("json"); console.log("JSON tools:", jsonTools.map(t => t.name)); // Output: ["jq", "grep", "sed", "cat", "head", "tail"] // Get tools suitable for CSV const csvTools = getToolsForFormat("csv"); console.log("CSV tools:", csvTools.map(t => t.name)); // Output: ["xan", "awk", "cut", "sort", "uniq", "join", "paste", ...] // Create a comprehensive tool prompt const prompt = await createToolPrompt({ sandbox, filenames: ["data.json", "config.yaml", "users.csv"], isJustBash: true }); console.log("Tool prompt for AI:\n", prompt); // Output: // Available tools: awk, cat, curl, cut, grep, head, jq, sed, tail, xan, yq, and more // For JSON: jq, grep, sed // For YAML: yq, grep, sed // For CSV/TSV: yq, xan, awk await sandbox.stop?.(); ``` -------------------------------- ### View AI Agent Instructions for bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Shows how to access the AI agent instructions for `bash-tool` by displaying the content of the `AGENTS.md` file located within the installed `bash-tool` package. ```bash cat node_modules/bash-tool/dist/AGENTS.md ``` -------------------------------- ### Tool Execution Options for AI SDK Source: https://github.com/vercel-labs/bash-tool/blob/main/CLAUDE.md Example of how to provide ToolExecutionOptions when calling AI SDK tools, specifically for toolCallId and messages. ```typescript AI SDK tool execute calls require ToolExecutionOptions with toolCallId and messages. ``` -------------------------------- ### Implement a custom sandbox for bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Provides an example of creating a completely custom sandbox implementation that conforms to the `Sandbox` interface. This allows for full control over command execution, file reading, and writing within the bash-tool framework. ```typescript import { createBashTool, Sandbox } from "bash-tool"; const customSandbox: Sandbox = { async executeCommand(command) { // Your implementation here return { stdout: "", stderr: "", exitCode: 0 }; }, async readFile(path) { // Your implementation here return ""; }, async writeFile(path, content) { // Your implementation here }, }; const { tools } = await createBashTool({ sandbox: customSandbox }); ``` -------------------------------- ### Handle errors with bash-tool execution and readFile Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Provides examples of how to handle errors when executing bash commands and reading files using bash-tool. It demonstrates checking the `exitCode` for command failures and using try-catch blocks for file read errors. ```typescript const { tools, sandbox } = await createBashTool(); const result = await tools.bash.execute({ command: "ls /nonexistent" }); if (result.exitCode !== 0) { console.error("Command failed:", result.stderr); } // readFile throws on missing files try { await sandbox.readFile("/missing.txt"); } catch (e) { // "File not found: /missing.txt" or "Failed to read file: ..." } ``` -------------------------------- ### Search for Interfaces in Bash Tool Project Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md This command searches recursively for all lines starting with 'export interface' within the .d.ts files located in the node_modules/bash-tool/dist/ directory. It helps in identifying and locating interface definitions within the project's generated type definitions. ```bash grep -r "^export interface" node_modules/bash-tool/dist/*.d.ts ``` -------------------------------- ### Create Bash Tool with Inline Files (TypeScript) Source: https://context7.com/vercel-labs/bash-tool/llms.txt Demonstrates the basic usage of createBashTool by providing file content directly. It initializes the sandbox with specified files and then uses these tools with the AI SDK for text generation. Finally, it shows how to clean up the sandbox. ```typescript import { createBashTool } from "bash-tool"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; // Basic usage with inline files const { tools, sandbox } = await createBashTool({ files: { "src/index.ts": "export const greeting = 'Hello World';", "package.json": JSON.stringify({ name: "my-project", version: "1.0.0", type: "module" }, null, 2), "README.md": "# My Project\n\nA sample project." } }); // Use with AI SDK const result = await generateText({ model: openai("gpt-4-turbo"), tools, maxSteps: 10, prompt: "Analyze all TypeScript files and count the number of exports" }); console.log(result.text); // Cleanup when done await sandbox.stop?.(); ``` -------------------------------- ### Create Bash Tool with @vercel/sandbox (TypeScript) Source: https://context7.com/vercel-labs/bash-tool/llms.txt Illustrates using the @vercel/sandbox for full VM isolation. It demonstrates creating a new sandbox, initializing bash tools with files, performing an AI task, reconnecting to the existing sandbox later, continuing the work, and finally cleaning up the VM. ```typescript import { Sandbox } from "@vercel/sandbox"; import { createBashTool } from "bash-tool"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; // Create new sandbox const vmSandbox = await Sandbox.create(); console.log("Sandbox ID:", vmSandbox.sandboxId); // Create bash tools with the VM sandbox const { tools } = await createBashTool({ sandbox: vmSandbox, files: { "data.json": JSON.stringify({ users: [{ id: 1, name: "Alice" }] }) } }); // First agent task let result = await generateText({ model: openai("gpt-4-turbo"), tools, maxSteps: 5, prompt: "Parse data.json and create a CSV file named users.csv" }); console.log(result.text); // Reconnect to the same sandbox later (e.g., in another serverless function) const existingSandbox = await Sandbox.get({ sandboxId: vmSandbox.sandboxId }); const { tools: reconnectedTools } = await createBashTool({ sandbox: existingSandbox }); // Continue work in the same environment result = await generateText({ model: openai("gpt-4-turbo"), tools: reconnectedTools, maxSteps: 5, prompt: "Read users.csv and add a header row" }); console.log(result.text); // Cleanup await vmSandbox.kill(); ``` -------------------------------- ### Use OverlayFs with just-bash for Efficient File Handling Source: https://context7.com/vercel-labs/bash-tool/llms.txt Illustrates using `OverlayFs` with `just-bash` to create a copy-on-write filesystem overlay. This allows an AI agent to interact with files on disk without loading the entire project into memory, improving efficiency for large projects by writing changes in memory. ```typescript import { Bash, OverlayFs } from "just-bash"; import { createBashTool } from "bash-tool"; import { generateText } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; // Create OverlayFs overlay over real directory (reads from disk, writes in memory) const overlay = new OverlayFs({ root: "./large-project" }); const bashEnv = new Bash({ fs: overlay, cwd: overlay.getMountPoint() }); const { tools, sandbox } = await createBashTool({ sandbox: bashEnv }); // Agent can now work with files on disk without loading them all into memory const result = await generateText({ model: anthropic("claude-3-5-sonnet-20241022"), tools, maxSteps: 15, prompt: "Find all TypeScript files that import React and list their file sizes" }); console.log(result.text); await sandbox.stop?.(); ``` -------------------------------- ### Direct Bash Command Execution with bash-tool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Illustrates how to execute bash commands directly using the `bash.execute` method from `createBashTool` without involving the AI SDK. This is useful for scripting and automation tasks where direct command execution is needed. It shows how to pass command arguments and handle results, including standard output and error streams. Dependency: 'bash-tool'. ```typescript import { createBashTool } from "bash-tool"; const { bash, sandbox } = await createBashTool({ files: { "data.csv": "name,age\nAlice,30\nBob,25" } }); // Execute bash tool directly const result = await bash.execute( { command: "cat data.csv | grep Alice" }, { toolCallId: "call_123", messages: [] } ); console.log("Output:", result.stdout); console.log("Exit code:", result.exitCode); if (result.stderr) { console.error("Errors:", result.stderr); } await sandbox.stop?.(); ``` -------------------------------- ### Custom Tool Prompt Configuration with bash-tool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Demonstrates how to provide custom instructions to the bash sandbox instead of relying on auto-generated tool discovery. This involves using the `promptOptions.toolPrompt` and `extraInstructions` to define available commands, interpreters, and specific validation requirements for the AI. ```typescript import { createBashTool } from "bash-tool"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const { tools, sandbox } = await createBashTool({ files: { "app.py": "print('Hello from Python')", "script.js": "console.log('Hello from Node');" }, // Custom prompt instead of auto-generated promptOptions: { toolPrompt: ` This sandbox includes Python 3.11 and Node.js 20. Use 'python app.py' or 'node script.js' to run scripts. Available: jq, yq, curl, git `. trim() }, // Add extra instructions extraInstructions: "Always validate JSON with jq before processing." }); const result = await generateText({ model: openai("gpt-4-turbo"), tools, maxSteps: 5, prompt: "Run both scripts and capture their output" }); console.log(result.text); await sandbox.stop?.(); ``` -------------------------------- ### Initialize bash-tool and use with AI SDK Agent Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Demonstrates how to create a bash tool instance with initial files and integrate it into an AI SDK `ToolLoopAgent`. The agent can then be used to generate responses based on prompts, utilizing the bash tool for project analysis. ```typescript import { createBashTool } from "bash-tool"; import { ToolLoopAgent, stepCountIs } from "ai"; const { tools } = await createBashTool({ files: { "src/index.ts": "export const hello = 'world';", "package.json": '{"name": "my-project"}', }, }); const agent = new ToolLoopAgent({ model: yourModel, tools, // Or use just the bash tool as tools: {bash: tools.bash} stopWhen: stepCountIs(20), }); const result = await agent.generate({ prompt: "Analyze the project and create a summary report", }); ``` -------------------------------- ### Upload a local directory using bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Shows how to use the `uploadDirectory` option with `createBashTool` to upload a local directory's contents into the sandbox environment. An optional glob filter can be used to include specific files. ```typescript const { bash } = await createBashTool({ uploadDirectory: { source: "./my-project", include: "**/*.{ts,json}", // optional glob filter }, }); ``` -------------------------------- ### Create Bash Tool with Directory Upload (TypeScript) Source: https://context7.com/vercel-labs/bash-tool/llms.txt Shows how to upload an entire local directory into the sandbox using glob filtering for specific file types. It then uses the AI SDK to stream text results based on the uploaded files. The sandbox is cleaned up afterwards. ```typescript import { createBashTool } from "bash-tool"; import { streamText } from "ai"; import { anthropic } from "@ai-sdk/anthropic"; // Upload local directory with filtering const { tools, sandbox } = await createBashTool({ uploadDirectory: { source: "./my-project", include: "**/*.{ts,js,json,md}" // Only upload specific file types }, destination: "/workspace", maxFiles: 500 // Limit file count }); // Stream results from AI agent const stream = await streamText({ model: anthropic("claude-3-5-sonnet-20241022"), tools, maxSteps: 20, prompt: "Find all TODO comments and create a summary report" }); for await (const chunk of stream.textStream) { process.stdout.write(chunk); } await sandbox.stop?.(); ``` -------------------------------- ### Use @vercel/sandbox with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Illustrates how to integrate `@vercel/sandbox` with bash-tool for a more robust, full VM environment. This is recommended when the default `just-bash` simulation is insufficient for certain operations. ```typescript import { Sandbox } from "@vercel/sandbox"; const vm = await Sandbox.create(); const { tools } = await createBashTool({ sandbox: vm }); // Call vm.stop() when done ``` -------------------------------- ### Persist sandbox across serverless invocations with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Explains how to maintain a sandbox environment across multiple serverless invocations using `Sandbox.get`. This involves creating a sandbox in the first invocation, storing its ID, and then reconnecting to it in subsequent invocations. ```typescript import { Sandbox } from "@vercel/sandbox"; // First invocation: create sandbox and store the ID const newSandbox = await Sandbox.create(); const sandboxId = newSandbox.sandboxId; // Store sandboxId in database, session, or return to client // Subsequent invocations: reconnect to existing sandbox const existingSandbox = await Sandbox.get({ sandboxId }); const { tools } = await createBashTool({ sandbox: existingSandbox }); // All previous files and state are preserved ``` -------------------------------- ### Write and Overwrite Files with bash-tool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Demonstrates how to use the `writeFile` tool to create new files or update existing ones within a bash sandbox. It initializes a sandbox with a `package.json`, writes a new TypeScript file, and then updates the `package.json`. Finally, it verifies the written files using the `bash.execute` tool. ```typescript import { createBashTool } from "bash-tool"; const { tools, sandbox } = await createBashTool({ files: { "package.json": JSON.stringify({ name: "test" }) } }); // Write a new file const result1 = await tools.writeFile.execute( { path: "src/new-feature.ts", content: "export function newFeature() {\n return 'Hello';\n}" }, { toolCallId: "call_789", messages: [] } ); console.log("Write success:", result1.success); // Update existing file const result2 = await tools.writeFile.execute( { path: "package.json", content: JSON.stringify({ name: "test", version: "1.0.0", scripts: { build: "tsc" } }, null, 2) }, { toolCallId: "call_790", messages: [] } ); console.log("Update success:", result2.success); // Verify files were written const verify = await tools.bash.execute( { command: "find . -type f -name '*.ts' -o -name '*.json'" }, { toolCallId: "call_791", messages: [] } ); console.log("Files in sandbox:\n", verify.stdout); await sandbox.stop?.(); ``` -------------------------------- ### Use a custom just-bash instance with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Illustrates how to use a custom `just-bash` instance with specific configurations, such as setting the current working directory (`cwd`), when creating the bash tool. The custom sandbox is passed to `createBashTool`. ```typescript import { Bash } from "just-bash"; const sandbox = new Bash({ cwd: "/app" }); const { tools } = await createBashTool({ sandbox, destination: "/app", }); ``` -------------------------------- ### Bash Tool API Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md This section details the core tools provided by the bash-tool: bash, readFile, and writeFile. ```APIDOC ## Tool: bash ### Description Execute bash commands in the sandbox environment. This is often the primary tool for analysis agents. ### Method Not applicable (this is a tool function within the library) ### Endpoint Not applicable ### Parameters #### Input Parameters - **command** (string) - Required - The bash command to execute. ### Returns #### Success Response - **stdout** (string) - Standard output from the command. - **stderr** (string) - Standard error from the command. - **exitCode** (number) - Exit code of the command. ### Request Example ```json { "command": "ls -l" } ``` ### Response Example ```json { "stdout": "total 8\n-rw-r--r-- 1 user group 123 Jan 1 10:00 file.txt\n", "stderr": "", "exitCode": 0 } ``` ## Tool: readFile ### Description Read the contents of a file from the sandbox. ### Method Not applicable (this is a tool function within the library) ### Endpoint Not applicable ### Parameters #### Input Parameters - **path** (string) - Required - The path to the file to read. ### Returns #### Success Response - **content** (string) - The file contents. ### Request Example ```json { "path": "src/index.ts" } ``` ### Response Example ```json { "content": "export const hello = 'world';" } ``` ## Tool: writeFile ### Description Write content to a file in the sandbox. Parent directories are created if they do not exist. ### Method Not applicable (this is a tool function within the library) ### Endpoint Not applicable ### Parameters #### Input Parameters - **path** (string) - Required - The path where the file should be written. - **content** (string) - Required - The content to write to the file. ### Returns #### Success Response - **success** (boolean) - `true` if the write succeeded. ### Request Example ```json { "path": "new_file.txt", "content": "This is the content of the new file." } ``` ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Intercept and Modify Bash Commands with createBashTool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Demonstrates how to intercept and modify bash commands before and after execution using `onBeforeBashCall` and `onAfterBashCall` hooks. This is useful for logging, security, or transforming command results. It allows blocking dangerous commands and trimming output. Dependencies include 'bash-tool' and 'ai' SDKs. ```typescript import { createBashTool } from "bash-tool"; import { generateText } from "ai"; import { openai } from "@ai-sdk/openai"; const executedCommands: string[] = []; const { tools, sandbox } = await createBashTool({ files: { "data.txt": "line1\nline2\nline3" }, // Block dangerous commands onBeforeBashCall: ({ command }) => { console.log("🚀 Executing:", command); executedCommands.push(command); // Block destructive operations if (command.includes("rm -rf") || command.includes(":(){ :|:& };:")) { console.warn("⚠️ Blocked dangerous command"); return { command: "echo 'Error: Dangerous command blocked'" }; } // Allow command as-is return undefined; }, // Log and modify results onAfterBashCall: ({ command, result }) => { console.log(`✅ Exit code: ${result.exitCode}`); // Trim whitespace from output return { result: { ...result, stdout: result.stdout.trim(), stderr: result.stderr.trim() } }; }, // Truncate long output maxOutputLength: 10000 }); const result = await generateText({ model: openai("gpt-4-turbo"), tools, maxSteps: 5, prompt: "Count the lines in data.txt" }); console.log("Result:", result.text); console.log("Commands executed:", executedCommands); await sandbox.stop?.(); ``` -------------------------------- ### Upload local directory with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Shows how to use the `uploadDirectory` option to include local files into the bash-tool sandbox. This is useful for providing project context or specific files needed for agent execution. ```typescript const { bash } = await createBashTool({ uploadDirectory: { source: "./my-project", include: "**/*.ts" }, }); ``` -------------------------------- ### Read File Contents Programmatically with readFile Tool Source: https://context7.com/vercel-labs/bash-tool/llms.txt Demonstrates how to read file contents from the sandbox programmatically using the `tools.readFile.execute` method. This allows direct access to files within the sandboxed environment for further processing or analysis. It shows reading files using relative and absolute paths. Dependency: 'bash-tool'. ```typescript import { createBashTool } from "bash-tool"; const { tools, sandbox } = await createBashTool({ files: { "src/utils.ts": "export function add(a: number, b: number) { return a + b; }", "src/index.ts": "import { add } from './utils';\nconsole.log(add(2, 3));" } }); // Read file directly const result = await tools.readFile.execute( { path: "src/utils.ts" }, { toolCallId: "call_456", messages: [] } ); console.log("File content:", result.content); // Read with absolute path const result2 = await tools.readFile.execute( { path: "/workspace/src/index.ts" }, { toolCallId: "call_457", messages: [] } ); console.log("File content:", result2.content); await sandbox.stop?.(); ``` -------------------------------- ### Bash Tool Commands Source: https://github.com/vercel-labs/bash-tool/blob/main/CLAUDE.md This snippet lists the available npm commands for managing the bash-tool project, including building, type checking, testing, linting, and validation. ```bash pnpm build # Compile TypeScript to dist/ pnpm typecheck # Type check without emitting pnpm test # Run tests in watch mode pnpm test:run # Run tests once pnpm lint # Check with Biome pnpm lint:fix # Fix lint issues pnpm knip # Check for unused exports/dependencies pnpm validate # Run all checks (lint, knip, typecheck, test) ``` -------------------------------- ### Persistent sandbox across serverless invocations Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Explains how to maintain a persistent sandbox across multiple serverless function calls. This involves creating a sandbox, storing its ID, and then reconnecting to the existing sandbox in subsequent invocations. ```typescript import { Sandbox } from "@vercel/sandbox"; // First invocation: create and store sandboxId const newSandbox = await Sandbox.create(); const sandboxId = newSandbox.sandboxId; // store this // Later invocations: reconnect by ID const existingSandbox = await Sandbox.get({ sandboxId }); const { tools } = await createBashTool({ sandbox: existingSandbox }); // Previous files and state preserved ``` -------------------------------- ### View bash-tool TypeScript type definitions Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Instructs on how to view the TypeScript type definition files for bash-tool. This is useful for understanding the available exports, options, and their corresponding types. ```bash # View main exports cat node_modules/bash-tool/dist/index.d.ts # View all options and types cat node_modules/bash-tool/dist/types.d.ts ``` -------------------------------- ### Intercept bash commands with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/README.md Demonstrates intercepting bash commands before and after execution using `onBeforeBashCall` and `onAfterBashCall` callbacks. This allows for logging, modifying commands, or altering results, such as blocking dangerous commands or trimming output. ```typescript const { tools } = await createBashTool({ onBeforeBashCall: ({ command }) => { console.log("Running:", command); // Optionally modify the command if (command.includes("rm -rf")) { return { command: "echo 'Blocked dangerous command'" }; } }, onAfterBashCall: ({ command, result }) => { console.log(`Exit code: ${result.exitCode}`); // Optionally modify the result return { result: { ...result, stdout: result.stdout.trim() } }; }, }); ``` -------------------------------- ### Set custom destination directory with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Shows how to specify a custom `destination` directory for bash-tool. Files provided in the `files` option will be placed in this custom directory, and the working directory for commands will also default to it. ```typescript const { bash } = await createBashTool({ destination: "/home/user/app", files: { "main.ts": "console.log('hi');" }, }); // Files at /home/user/app/main.ts, cwd is /home/user/app ``` -------------------------------- ### Intercept bash commands with bash-tool Source: https://github.com/vercel-labs/bash-tool/blob/main/AGENTS.npm.md Demonstrates how to intercept and modify bash commands before execution or their results after execution using `onBeforeBashCall` and `onAfterBashCall` hooks. This allows for custom logging, validation, or manipulation of command interactions. ```typescript const { tools } = await createBashTool({ onBeforeBashCall: ({ command }) => { console.log("Running:", command); // Return modified command or undefined to proceed unchanged }, onAfterBashCall: ({ command, result }) => { console.log(`Exit: ${result.exitCode}`); // Return modified result or undefined to proceed unchanged }, }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.