cloudaxe-opencode/packages/opencode/src/tool/bash.ts

71 lines
1.8 KiB
TypeScript
Raw Normal View History

2025-05-31 18:41:00 +00:00
import { z } from "zod"
import { Tool } from "./tool"
2025-06-04 17:12:13 +00:00
import DESCRIPTION from "./bash.txt"
2025-05-19 23:29:38 +00:00
2025-05-31 18:41:00 +00:00
const MAX_OUTPUT_LENGTH = 30000
2025-05-19 23:29:38 +00:00
const BANNED_COMMANDS = [
"alias",
"curl",
"curlie",
"wget",
"axel",
"aria2c",
"nc",
"telnet",
"lynx",
"w3m",
"links",
"httpie",
"xh",
"http-prompt",
"chrome",
"firefox",
"safari",
2025-05-31 18:41:00 +00:00
]
const DEFAULT_TIMEOUT = 1 * 60 * 1000
const MAX_TIMEOUT = 10 * 60 * 1000
2025-05-19 23:29:38 +00:00
2025-05-31 21:12:16 +00:00
export const BashTool = Tool.define({
id: "opencode.bash",
2025-05-19 23:29:38 +00:00
description: DESCRIPTION,
parameters: z.object({
2025-06-04 17:12:13 +00:00
command: z.string().describe("The command to execute"),
2025-05-19 23:29:38 +00:00
timeout: z
.number()
.min(0)
.max(MAX_TIMEOUT)
.describe("Optional timeout in milliseconds")
2025-06-10 00:24:18 +00:00
.nullable(),
2025-06-04 17:12:13 +00:00
description: z
.string()
.describe(
"Clear, concise description of what this command does in 5-10 words. Examples:\nInput: ls\nOutput: Lists files in current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: mkdir foo\nOutput: Creates directory 'foo'",
),
2025-05-19 23:29:38 +00:00
}),
2025-05-21 14:30:39 +00:00
async execute(params) {
2025-05-31 18:41:00 +00:00
const timeout = Math.min(params.timeout ?? DEFAULT_TIMEOUT, MAX_TIMEOUT)
2025-05-19 23:29:38 +00:00
if (BANNED_COMMANDS.some((item) => params.command.startsWith(item)))
2025-05-31 18:41:00 +00:00
throw new Error(`Command '${params.command}' is not allowed`)
2025-05-19 23:29:38 +00:00
2025-06-03 17:08:47 +00:00
const process = Bun.spawn({
2025-05-19 23:29:38 +00:00
cmd: ["bash", "-c", params.command],
maxBuffer: MAX_OUTPUT_LENGTH,
timeout: timeout,
stdout: "pipe",
stderr: "pipe",
2025-05-31 18:41:00 +00:00
})
2025-06-03 17:08:47 +00:00
await process.exited
const stdout = await new Response(process.stdout).text()
const stderr = await new Response(process.stderr).text()
2025-06-03 17:08:47 +00:00
2025-05-19 23:29:38 +00:00
return {
2025-06-03 17:08:47 +00:00
metadata: {
stderr,
stdout,
2025-06-04 17:12:13 +00:00
description: params.description,
2025-06-03 17:08:47 +00:00
},
output: stdout.replaceAll(/\x1b\[[0-9;]*m/g, ""),
2025-05-31 18:41:00 +00:00
}
2025-05-19 23:29:38 +00:00
},
2025-05-31 18:41:00 +00:00
})