Bash工具集
提供通过本地系统执行或安全沙箱环境执行bash命令的统一接口,具备全面的命令管理能力。概述
Bash工具集提供跨环境执行bash命令的统一接口:- 本地执行:直接在本地系统上执行
- 沙箱执行:在隔离的E2B容器中安全执行
- 多命令支持:按顺序执行多个命令
- 实时流式传输:通过回调实时监控输出
快速入门
本地执行
复制
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!"'
});
沙箱执行
复制
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'
});
核心功能
单命令执行
复制
const result = await bashTool.invoke({
command: 'find . -name "*.ts" | head -5',
cwd: '/project/src',
env: { NODE_ENV: 'development' },
timeout: 10000
});
多命令执行
复制
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
});
实时输出流
复制
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}`)
});
交互式命令
复制
const result = await bashTool.invoke({
command: 'python3 -c "name = input(\'Name: \'); print(f\'Hello {name}!\')"',
input: 'Alice\n',
timeout: 5000
});
命令构建器
预置常见操作的命令生成器:复制
import { CommandBuilders } from '@ag-kit/tools';
// 文件操作
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
});
// 目录操作
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 });
// 执行构建的命令
const result = await bashTool.invoke({ command: listCommand });
安全特性
命令验证
复制
import { validateCommand } from '@ag-kit/tools';
const validation = validateCommand('rm -rf /');
if (!validation.isValid) {
console.error(`危险命令: ${validation.reason}`);
}
参数转义
复制
import { escapeShellArg, buildCommand } from '@ag-kit/tools';
const userInput = "file with spaces & special chars";
const command = buildCommand('ls', ['-la', userInput]);
// 结果: "ls '-la' 'file with spaces & special chars'"
应用程序接口参考
上下文创建
复制
// 本地上下文
createLocalBashContext(options?: {
cwd?: string;
env?: NodeJS.ProcessEnv;
defaultTimeout?: number;
})
// 沙箱上下文
createSandboxBashContext(options: {
sandbox: Sandbox;
cwd?: string;
env?: Record<string, string>;
defaultTimeout?: number;
})
输入接口
复制
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;
}
响应接口
复制
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;
}
实用函数
复制
import {
parseCommandOutput,
formatExecutionTime,
validateCommand,
escapeShellArg
} from '@ag-kit/tools';
const parsed = parseCommandOutput(stdout, stderr);
const timeStr = formatExecutionTime(1500); // "1.50s"
示例
开发工作流
复制
const buildResult = await multiTool.invoke({
commands: [
'npm install',
'npm run build',
'npm test'
],
continue_on_error: false,
timeout: 120000
});
文件系统操作
复制
const setupResult = await multiTool.invoke({
commands: [
'mkdir -p project/{src,tests,docs}',
'touch project/src/index.ts',
'echo "# Project" > project/README.md'
]
});
错误处理
复制
try {
const result = await bashTool.invoke({
command: 'risky-command',
timeout: 5000
});
if (!result.success) {
console.error('命令执行失败:', result.data.stderr);
console.error('退出码:', result.data.exit_code);
}
} catch (error) {
console.error('执行错误:', error.message);
}