Skip to main content

Bash Tools

Execute bash commands using either local system execution or secure sandboxed environments with comprehensive command management capabilities.

Overview

The Bash Tools provide a unified interface for executing bash commands across different environments:
  • Local Execution: Direct execution on the local system
  • Sandbox Execution: Secure execution in isolated E2B containers
  • Multi-Command Support: Execute multiple commands in sequence
  • Real-time Streaming: Live output monitoring with callbacks

Quick Start

Local Execution

import { createLocalBashContext, createBashTool } from '@ag-kit/tools';

const context = createLocalBashContext({
  cwd: '/path/to/working/directory',
  env: { CUSTOM_VAR: 'value' }
});

const bashTool = createBashTool(context);
const result = await bashTool.invoke({
  command: 'echo "Hello World!"'
});

Sandbox Execution

import { createSandboxBashContext, createBashTool } from '@ag-kit/tools';

const context = createSandboxBashContext({
  sandbox: sandboxInstance,
  cwd: '/home/user'
});

const bashTool = createBashTool(context);
const result = await bashTool.invoke({
  command: 'ls -la'
});

Core Features

Single Command Execution

const result = await bashTool.invoke({
  command: 'find . -name "*.ts" | head -5',
  cwd: '/project/src',
  env: { NODE_ENV: 'development' },
  timeout: 10000
});

Multi-Command Execution

import { createMultiCommandTool } from '@ag-kit/tools';

const multiTool = createMultiCommandTool(context);
const result = await multiTool.invoke({
  commands: [
    'mkdir -p /tmp/test',
    'echo "Hello" > /tmp/test/file.txt',
    'cat /tmp/test/file.txt'
  ],
  continue_on_error: false
});

Real-time Output Streaming

const result = await bashTool.invoke({
  command: 'for i in {1..5}; do echo "Step $i"; sleep 1; done',
  onStdout: (data) => console.log(`OUT: ${data}`),
  onStderr: (data) => console.error(`ERR: ${data}`)
});

Interactive Commands

const result = await bashTool.invoke({
  command: 'python3 -c "name = input(\'Name: \'); print(f\'Hello {name}!\')"',
  input: 'Alice\n',
  timeout: 5000
});

Command Builders

Pre-built command generators for common operations:
import { CommandBuilders } from '@ag-kit/tools';

// File operations
const listCommand = CommandBuilders.listFiles('/home/user', {
  all: true, long: true, human: true
});

const findCommand = CommandBuilders.findFiles('*.ts', './src');
const grepCommand = CommandBuilders.grep('TODO', '*.js', {
  recursive: true, ignoreCase: true
});

// Directory operations
const mkdirCommand = CommandBuilders.mkdir('/path/to/dir', { parents: true });
const copyCommand = CommandBuilders.copy('source', 'dest', { recursive: true });
const removeCommand = CommandBuilders.remove('/tmp/file', { force: true });

// Execute built commands
const result = await bashTool.invoke({ command: listCommand });

Security Features

Command Validation

import { validateCommand } from '@ag-kit/tools';

const validation = validateCommand('rm -rf /');
if (!validation.isValid) {
  console.error(`Dangerous command: ${validation.reason}`);
}

Argument Escaping

import { escapeShellArg, buildCommand } from '@ag-kit/tools';

const userInput = "file with spaces & special chars";
const command = buildCommand('ls', ['-la', userInput]);
// Result: "ls '-la' 'file with spaces & special chars'"

API Reference

Context Creation

// Local context
createLocalBashContext(options?: {
  cwd?: string;
  env?: NodeJS.ProcessEnv;
  defaultTimeout?: number;
})

// Sandbox context
createSandboxBashContext(options: {
  sandbox: Sandbox;
  cwd?: string;
  env?: Record<string, string>;
  defaultTimeout?: number;
})

Input Interfaces

interface BashToolInput {
  command: string;
  cwd?: string;
  env?: Record<string, string>;
  timeout?: number;
  input?: string;
  onStdout?: (data: string) => void;
  onStderr?: (data: string) => void;
}

interface MultiCommandInput {
  commands: string[];
  cwd?: string;
  env?: Record<string, string>;
  timeout?: number;
  continue_on_error?: boolean;
}

Response Interfaces

interface BashToolResponse {
  command: string;
  exit_code: number | null;
  stdout: string;
  stderr: string;
  working_directory: string;
}

interface MultiCommandResponse {
  commands: string[];
  results: Array<{
    command: string;
    success: boolean;
    exit_code: number | null;
    stdout: string;
    stderr: string;
    execution_time: number;
  }>;
  successful_commands: number;
  failed_commands: number;
  working_directory: string;
}

Utility Functions

import { 
  parseCommandOutput, 
  formatExecutionTime,
  validateCommand,
  escapeShellArg 
} from '@ag-kit/tools';

const parsed = parseCommandOutput(stdout, stderr);
const timeStr = formatExecutionTime(1500); // "1.50s"

Examples

Development Workflow

const buildResult = await multiTool.invoke({
  commands: [
    'npm install',
    'npm run build',
    'npm test'
  ],
  continue_on_error: false,
  timeout: 120000
});

File System Operations

const setupResult = await multiTool.invoke({
  commands: [
    'mkdir -p project/{src,tests,docs}',
    'touch project/src/index.ts',
    'echo "# Project" > project/README.md'
  ]
});

Error Handling

try {
  const result = await bashTool.invoke({
    command: 'risky-command',
    timeout: 5000
  });

  if (!result.success) {
    console.error('Command failed:', result.data.stderr);
    console.error('Exit code:', result.data.exit_code);
  }
} catch (error) {
  console.error('Execution error:', error.message);
}