feat: refactor bash tool with shell-aware prompts for bash, pwsh+powershell, and cmd (#20039)

This commit is contained in:
Luke Parker 2026-05-03 09:18:48 +10:00 committed by GitHub
commit 3f459819ba
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 506 additions and 177 deletions

View file

@ -51,6 +51,7 @@ import { LoadAPIKeyError } from "ai"
import type { AssistantMessage, Event, OpencodeClient, SessionMessageResponse, ToolPart } from "@opencode-ai/sdk/v2" import type { AssistantMessage, Event, OpencodeClient, SessionMessageResponse, ToolPart } from "@opencode-ai/sdk/v2"
import { applyPatch } from "diff" import { applyPatch } from "diff"
import { InstallationVersion } from "@opencode-ai/core/installation/version" import { InstallationVersion } from "@opencode-ai/core/installation/version"
import { ShellID } from "@/tool/shell/id"
type ModeOption = { id: string; name: string; description?: string } type ModeOption = { id: string; name: string; description?: string }
type ModelOption = { modelId: string; name: string } type ModelOption = { modelId: string; name: string }
@ -144,7 +145,7 @@ export class Agent implements ACPAgent {
private sessionManager: ACPSessionManager private sessionManager: ACPSessionManager
private eventAbort = new AbortController() private eventAbort = new AbortController()
private eventStarted = false private eventStarted = false
private bashSnapshots = new Map<string, string>() private shellSnapshots = new Map<string, string>()
private toolStarts = new Set<string>() private toolStarts = new Set<string>()
private permissionQueues = new Map<string, Promise<void>>() private permissionQueues = new Map<string, Promise<void>>()
private permissionOptions: PermissionOption[] = [ private permissionOptions: PermissionOption[] = [
@ -283,16 +284,16 @@ export class Agent implements ACPAgent {
switch (part.state.status) { switch (part.state.status) {
case "pending": case "pending":
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
return return
case "running": case "running":
const output = this.bashOutput(part) const output = this.shellOutput(part)
const content: ToolCallContent[] = [] const content: ToolCallContent[] = []
if (output) { if (output) {
const hash = Hash.fast(output) const hash = Hash.fast(output)
if (part.tool === "bash") { if (part.tool === ShellID.ToolID) {
if (this.bashSnapshots.get(part.callID) === hash) { if (this.shellSnapshots.get(part.callID) === hash) {
await this.connection await this.connection
.sessionUpdate({ .sessionUpdate({
sessionId, sessionId,
@ -311,7 +312,7 @@ export class Agent implements ACPAgent {
}) })
return return
} }
this.bashSnapshots.set(part.callID, hash) this.shellSnapshots.set(part.callID, hash)
} }
content.push({ content.push({
type: "content", type: "content",
@ -342,7 +343,7 @@ export class Agent implements ACPAgent {
case "completed": { case "completed": {
this.toolStarts.delete(part.callID) this.toolStarts.delete(part.callID)
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
const kind = toToolKind(part.tool) const kind = toToolKind(part.tool)
const content: ToolCallContent[] = [ const content: ToolCallContent[] = [
{ {
@ -423,7 +424,7 @@ export class Agent implements ACPAgent {
} }
case "error": case "error":
this.toolStarts.delete(part.callID) this.toolStarts.delete(part.callID)
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
await this.connection await this.connection
.sessionUpdate({ .sessionUpdate({
sessionId, sessionId,
@ -837,10 +838,10 @@ export class Agent implements ACPAgent {
await this.toolStart(sessionId, part) await this.toolStart(sessionId, part)
switch (part.state.status) { switch (part.state.status) {
case "pending": case "pending":
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
break break
case "running": case "running":
const output = this.bashOutput(part) const output = this.shellOutput(part)
const runningContent: ToolCallContent[] = [] const runningContent: ToolCallContent[] = []
if (output) { if (output) {
runningContent.push({ runningContent.push({
@ -871,7 +872,7 @@ export class Agent implements ACPAgent {
break break
case "completed": case "completed":
this.toolStarts.delete(part.callID) this.toolStarts.delete(part.callID)
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
const kind = toToolKind(part.tool) const kind = toToolKind(part.tool)
const content: ToolCallContent[] = [ const content: ToolCallContent[] = [
{ {
@ -951,7 +952,7 @@ export class Agent implements ACPAgent {
break break
case "error": case "error":
this.toolStarts.delete(part.callID) this.toolStarts.delete(part.callID)
this.bashSnapshots.delete(part.callID) this.shellSnapshots.delete(part.callID)
await this.connection await this.connection
.sessionUpdate({ .sessionUpdate({
sessionId, sessionId,
@ -1105,8 +1106,8 @@ export class Agent implements ACPAgent {
} }
} }
private bashOutput(part: ToolPart) { private shellOutput(part: ToolPart) {
if (part.tool !== "bash") return if (part.tool !== ShellID.ToolID) return
if (!("metadata" in part.state) || !part.state.metadata || typeof part.state.metadata !== "object") return if (!("metadata" in part.state) || !part.state.metadata || typeof part.state.metadata !== "object") return
const output = part.state.metadata["output"] const output = part.state.metadata["output"]
if (typeof output !== "string") return if (typeof output !== "string") return
@ -1549,9 +1550,11 @@ export class Agent implements ACPAgent {
function toToolKind(toolName: string): ToolKind { function toToolKind(toolName: string): ToolKind {
const tool = toolName.toLocaleLowerCase() const tool = toolName.toLocaleLowerCase()
switch (tool) { switch (tool) {
case "bash": case ShellID.ToolID:
return "execute" return "execute"
case "webfetch": case "webfetch":
return "fetch" return "fetch"
@ -1576,6 +1579,7 @@ function toToolKind(toolName: string): ToolKind {
function toLocations(toolName: string, input: Record<string, any>): { path: string }[] { function toLocations(toolName: string, input: Record<string, any>): { path: string }[] {
const tool = toolName.toLocaleLowerCase() const tool = toolName.toLocaleLowerCase()
switch (tool) { switch (tool) {
case "read": case "read":
case "edit": case "edit":
@ -1584,7 +1588,7 @@ function toLocations(toolName: string, input: Record<string, any>): { path: stri
case "glob": case "glob":
case "grep": case "grep":
return input["path"] ? [{ path: input["path"] }] : [] return input["path"] ? [{ path: input["path"] }] : []
case "bash": case ShellID.ToolID:
return [] return []
default: default:
return [] return []

View file

@ -879,7 +879,7 @@ export const GithubRunCommand = cmd({
function subscribeSessionEvents() { function subscribeSessionEvents() {
const TOOL: Record<string, [string, string]> = { const TOOL: Record<string, [string, string]> = {
todowrite: ["Todo", UI.Style.TEXT_WARNING_BOLD], todowrite: ["Todo", UI.Style.TEXT_WARNING_BOLD],
bash: ["Bash", UI.Style.TEXT_DANGER_BOLD], bash: ["Shell", UI.Style.TEXT_DANGER_BOLD],
edit: ["Edit", UI.Style.TEXT_SUCCESS_BOLD], edit: ["Edit", UI.Style.TEXT_SUCCESS_BOLD],
glob: ["Glob", UI.Style.TEXT_INFO_BOLD], glob: ["Glob", UI.Style.TEXT_INFO_BOLD],
grep: ["Grep", UI.Style.TEXT_INFO_BOLD], grep: ["Grep", UI.Style.TEXT_INFO_BOLD],

View file

@ -22,7 +22,8 @@ import { WriteTool } from "../../tool/write"
import { WebSearchTool } from "../../tool/websearch" import { WebSearchTool } from "../../tool/websearch"
import { TaskTool } from "../../tool/task" import { TaskTool } from "../../tool/task"
import { SkillTool } from "../../tool/skill" import { SkillTool } from "../../tool/skill"
import { BashTool } from "../../tool/bash" import { ShellTool } from "../../tool/shell"
import { ShellID } from "../../tool/shell/id"
import { TodoWriteTool } from "../../tool/todo" import { TodoWriteTool } from "../../tool/todo"
import { Locale } from "@/util/locale" import { Locale } from "@/util/locale"
import { AppRuntime } from "@/effect/app-runtime" import { AppRuntime } from "@/effect/app-runtime"
@ -175,7 +176,7 @@ function skill(info: ToolProps<typeof SkillTool>) {
}) })
} }
function bash(info: ToolProps<typeof BashTool>) { function shell(info: ToolProps<typeof ShellTool>) {
const output = info.part.state.status === "completed" ? info.part.state.output?.trim() : undefined const output = info.part.state.status === "completed" ? info.part.state.output?.trim() : undefined
block( block(
{ {
@ -400,7 +401,7 @@ export const RunCommand = cmd({
async function execute(sdk: OpencodeClient) { async function execute(sdk: OpencodeClient) {
function tool(part: ToolPart) { function tool(part: ToolPart) {
try { try {
if (part.tool === "bash") return bash(props<typeof BashTool>(part)) if (part.tool === ShellID.ToolID) return shell(props<typeof ShellTool>(part))
if (part.tool === "glob") return glob(props<typeof GlobTool>(part)) if (part.tool === "glob") return glob(props<typeof GlobTool>(part))
if (part.tool === "grep") return grep(props<typeof GrepTool>(part)) if (part.tool === "grep") return grep(props<typeof GrepTool>(part))
if (part.tool === "read") return read(props<typeof ReadTool>(part)) if (part.tool === "read") return read(props<typeof ReadTool>(part))

View file

@ -37,7 +37,8 @@ import { Locale } from "@/util/locale"
import type { Tool } from "@/tool/tool" import type { Tool } from "@/tool/tool"
import type { ReadTool } from "@/tool/read" import type { ReadTool } from "@/tool/read"
import type { WriteTool } from "@/tool/write" import type { WriteTool } from "@/tool/write"
import { BashTool } from "@/tool/bash" import { ShellTool } from "@/tool/shell"
import { ShellID } from "@/tool/shell/id"
import type { GlobTool } from "@/tool/glob" import type { GlobTool } from "@/tool/glob"
import { TodoWriteTool } from "@/tool/todo" import { TodoWriteTool } from "@/tool/todo"
import type { GrepTool } from "@/tool/grep" import type { GrepTool } from "@/tool/grep"
@ -1552,8 +1553,8 @@ function ToolPart(props: { last: boolean; part: ToolPart; message: AssistantMess
return ( return (
<Show when={!shouldHide()}> <Show when={!shouldHide()}>
<Switch> <Switch>
<Match when={props.part.tool === "bash"}> <Match when={props.part.tool === ShellID.ToolID}>
<Bash {...toolprops} /> <Shell {...toolprops} />
</Match> </Match>
<Match when={props.part.tool === "glob"}> <Match when={props.part.tool === "glob"}>
<Glob {...toolprops} /> <Glob {...toolprops} />
@ -1784,7 +1785,7 @@ function BlockTool(props: {
) )
} }
function Bash(props: ToolProps<typeof BashTool>) { function Shell(props: ToolProps<typeof ShellTool>) {
const { theme } = useTheme() const { theme } = useTheme()
const sync = useSync() const sync = useSync()
const isRunning = createMemo(() => props.part.state.status === "running") const isRunning = createMemo(() => props.part.state.status === "running")

View file

@ -15,6 +15,7 @@ import { LANGUAGE_EXTENSIONS } from "@/lsp/language"
import { Keybind } from "@/util/keybind" import { Keybind } from "@/util/keybind"
import { Locale } from "@/util/locale" import { Locale } from "@/util/locale"
import { Global } from "@opencode-ai/core/global" import { Global } from "@opencode-ai/core/global"
import { ShellID } from "@/tool/shell/id"
import { useDialog } from "../../ui/dialog" import { useDialog } from "../../ui/dialog"
import { getScrollAcceleration } from "../../util/scroll" import { getScrollAcceleration } from "../../util/scroll"
import { useTuiConfig } from "../../context/tui-config" import { useTuiConfig } from "../../context/tui-config"
@ -287,7 +288,7 @@ export function PermissionPrompt(props: { request: PermissionRequest }) {
} }
} }
if (permission === "bash") { if (permission === ShellID.ToolID) {
const title = const title =
typeof data.description === "string" && data.description ? data.description : "Shell command" typeof data.description === "string" && data.description ? data.description : "Shell command"
const command = typeof data.command === "string" ? data.command : "" const command = typeof data.command === "string" ? data.command : ""

View file

@ -41,6 +41,7 @@ import { Permission } from "@/permission"
import { SessionStatus } from "./status" import { SessionStatus } from "./status"
import { LLM } from "./llm" import { LLM } from "./llm"
import { Shell } from "@/shell/shell" import { Shell } from "@/shell/shell"
import { ShellID } from "@/tool/shell/id"
import { AppFileSystem } from "@opencode-ai/core/filesystem" import { AppFileSystem } from "@opencode-ai/core/filesystem"
import { Truncate } from "@/tool/truncate" import { Truncate } from "@/tool/truncate"
import { decodeDataUrl } from "@/util/data-url" import { decodeDataUrl } from "@/util/data-url"
@ -789,7 +790,7 @@ NOTE: At any point in time through this workflow you should feel free to ask the
id: PartID.ascending(), id: PartID.ascending(),
messageID: msg.id, messageID: msg.id,
sessionID: input.sessionID, sessionID: input.sessionID,
tool: "bash", tool: ShellID.ToolID,
callID: ulid(), callID: ulid(),
state: { state: {
status: "running", status: "running",

View file

@ -1,7 +1,7 @@
import { PlanExitTool } from "./plan" import { PlanExitTool } from "./plan"
import { Session } from "@/session/session" import { Session } from "@/session/session"
import { QuestionTool } from "./question" import { QuestionTool } from "./question"
import { BashTool } from "./bash" import { ShellTool } from "./shell"
import { EditTool } from "./edit" import { EditTool } from "./edit"
import { GlobTool } from "./glob" import { GlobTool } from "./glob"
import { GrepTool } from "./grep" import { GrepTool } from "./grep"
@ -106,7 +106,7 @@ export const layer: Layer.Layer<
const plan = yield* PlanExitTool const plan = yield* PlanExitTool
const webfetch = yield* WebFetchTool const webfetch = yield* WebFetchTool
const websearch = yield* WebSearchTool const websearch = yield* WebSearchTool
const bash = yield* BashTool const shell = yield* ShellTool
const globtool = yield* GlobTool const globtool = yield* GlobTool
const writetool = yield* WriteTool const writetool = yield* WriteTool
const edit = yield* EditTool const edit = yield* EditTool
@ -195,7 +195,7 @@ export const layer: Layer.Layer<
const tool = yield* Effect.all({ const tool = yield* Effect.all({
invalid: Tool.init(invalid), invalid: Tool.init(invalid),
bash: Tool.init(bash), shell: Tool.init(shell),
read: Tool.init(read), read: Tool.init(read),
glob: Tool.init(globtool), glob: Tool.init(globtool),
grep: Tool.init(greptool), grep: Tool.init(greptool),
@ -217,7 +217,7 @@ export const layer: Layer.Layer<
builtin: [ builtin: [
tool.invalid, tool.invalid,
...(questionEnabled ? [tool.question] : []), ...(questionEnabled ? [tool.question] : []),
tool.bash, tool.shell,
tool.read, tool.read,
tool.glob, tool.glob,
tool.grep, tool.grep,

View file

@ -1,12 +1,11 @@
import { Schema } from "effect" import { Effect, Stream } from "effect"
import { PositiveInt } from "@/util/schema"
import os from "os" import os from "os"
import { createWriteStream } from "node:fs" import { createWriteStream } from "node:fs"
import * as Tool from "./tool" import * as Tool from "./tool"
import path from "path" import path from "path"
import DESCRIPTION from "./bash.txt"
import * as Log from "@opencode-ai/core/util/log" import * as Log from "@opencode-ai/core/util/log"
import { containsPath, type InstanceContext } from "../project/instance-context" import { containsPath, type InstanceContext } from "../project/instance-context"
import { InstanceState } from "@/effect/instance-state"
import { lazy } from "@/util/lazy" import { lazy } from "@/util/lazy"
import { Language, type Node } from "web-tree-sitter" import { Language, type Node } from "web-tree-sitter"
@ -14,20 +13,21 @@ import { AppFileSystem } from "@opencode-ai/core/filesystem"
import { fileURLToPath } from "url" import { fileURLToPath } from "url"
import { Config } from "@/config/config" import { Config } from "@/config/config"
import { Flag } from "@opencode-ai/core/flag/flag" import { Flag } from "@opencode-ai/core/flag/flag"
import { Global } from "@opencode-ai/core/global"
import { Shell } from "@/shell/shell" import { Shell } from "@/shell/shell"
import { ShellID } from "./shell/id"
import { BashArity } from "@/permission/arity"
import * as Truncate from "./truncate" import * as Truncate from "./truncate"
import { Plugin } from "@/plugin" import { Plugin } from "@/plugin"
import { Effect, Stream } from "effect"
import { ChildProcess } from "effect/unstable/process" import { ChildProcess } from "effect/unstable/process"
import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner" import { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner"
import { InstanceState } from "@/effect/instance-state" import { ShellPrompt, type Parameters } from "./shell/prompt"
import { BashArity } from "@/permission/arity"
export { Parameters } from "./shell/prompt"
const MAX_METADATA_LENGTH = 30_000 const MAX_METADATA_LENGTH = 30_000
const DEFAULT_TIMEOUT = Flag.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS || 2 * 60 * 1000 const DEFAULT_TIMEOUT = Flag.OPENCODE_EXPERIMENTAL_BASH_DEFAULT_TIMEOUT_MS || 2 * 60 * 1000
const CWD = new Set(["cd", "push-location", "set-location"]) const CWD = new Set(["cd", "chdir", "popd", "pushd", "push-location", "set-location"])
const FILES = new Set([ const FILES = new Set([
...CWD, ...CWD,
"rm", "rm",
@ -50,21 +50,10 @@ const FILES = new Set([
"new-item", "new-item",
"rename-item", "rename-item",
]) ])
const CMD_FILES = new Set(["copy", "del", "dir", "erase", "md", "mkdir", "move", "rd", "ren", "rename", "rmdir", "type"])
const FLAGS = new Set(["-destination", "-literalpath", "-path"]) const FLAGS = new Set(["-destination", "-literalpath", "-path"])
const SWITCHES = new Set(["-confirm", "-debug", "-force", "-nonewline", "-recurse", "-verbose", "-whatif"]) const SWITCHES = new Set(["-confirm", "-debug", "-force", "-nonewline", "-recurse", "-verbose", "-whatif"])
export const Parameters = Schema.Struct({
command: Schema.String.annotate({ description: "The command to execute" }),
timeout: Schema.optional(PositiveInt).annotate({ description: "Optional timeout in milliseconds" }),
workdir: Schema.optional(Schema.String).annotate({
description: `The working directory to run the command in. Defaults to the current directory. Use this instead of 'cd' commands.`,
}),
description: Schema.String.annotate({
description:
"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'",
}),
})
type Part = { type Part = {
type: string type: string
text: string text: string
@ -81,7 +70,7 @@ type Chunk = {
size: number size: number
} }
export const log = Log.create({ service: "bash-tool" }) export const log = Log.create({ service: "shell-tool" })
const resolveWasm = (asset: string) => { const resolveWasm = (asset: string) => {
if (asset.startsWith("file://")) return fileURLToPath(asset) if (asset.startsWith("file://")) return fileURLToPath(asset)
@ -187,11 +176,16 @@ function prefix(text: string) {
return text.slice(0, match.index) return text.slice(0, match.index)
} }
function pathArgs(list: Part[], ps: boolean) { function pathArgs(list: Part[], ps: boolean, cmd = false) {
if (!ps) { if (!ps) {
return list return list
.slice(1) .slice(1)
.filter((item) => !item.text.startsWith("-") && !(list[0]?.text === "chmod" && item.text.startsWith("+"))) .filter(
(item) =>
!item.text.startsWith("-") &&
!(cmd && item.text.startsWith("/")) &&
!(list[0]?.text === "chmod" && item.text.startsWith("+")),
)
.map((item) => item.text) .map((item) => item.text)
} }
@ -251,13 +245,13 @@ function tail(text: string, maxLines: number, maxBytes: number) {
} }
} }
const parse = Effect.fn("BashTool.parse")(function* (command: string, ps: boolean) { const parse = Effect.fn("ShellTool.parse")(function* (command: string, ps: boolean) {
const tree = yield* Effect.promise(() => parser().then((p) => (ps ? p.ps : p.bash).parse(command))) const tree = yield* Effect.promise(() => parser().then((p) => (ps ? p.ps : p.bash).parse(command)))
if (!tree) throw new Error("Failed to parse command") if (!tree) throw new Error("Failed to parse command")
return tree return tree
}) })
const ask = Effect.fn("BashTool.ask")(function* (ctx: Tool.Context, scan: Scan) { const ask = Effect.fn("ShellTool.ask")(function* (ctx: Tool.Context, scan: Scan) {
if (scan.dirs.size > 0) { if (scan.dirs.size > 0) {
const globs = Array.from(scan.dirs).map((dir) => { const globs = Array.from(scan.dirs).map((dir) => {
if (process.platform === "win32") return AppFileSystem.normalizePathPattern(path.join(dir, "*")) if (process.platform === "win32") return AppFileSystem.normalizePathPattern(path.join(dir, "*"))
@ -273,7 +267,7 @@ const ask = Effect.fn("BashTool.ask")(function* (ctx: Tool.Context, scan: Scan)
if (scan.patterns.size === 0) return if (scan.patterns.size === 0) return
yield* ctx.ask({ yield* ctx.ask({
permission: "bash", permission: ShellID.ToolID,
patterns: Array.from(scan.patterns), patterns: Array.from(scan.patterns),
always: Array.from(scan.always), always: Array.from(scan.always),
metadata: {}, metadata: {},
@ -325,9 +319,8 @@ const parser = lazy(async () => {
return { bash, ps } return { bash, ps }
}) })
// TODO: we may wanna rename this tool so it works better on other shells export const ShellTool = Tool.define(
export const BashTool = Tool.define( ShellID.ToolID,
"bash",
Effect.gen(function* () { Effect.gen(function* () {
const config = yield* Config.Service const config = yield* Config.Service
const spawner = yield* ChildProcessSpawner const spawner = yield* ChildProcessSpawner
@ -335,7 +328,7 @@ export const BashTool = Tool.define(
const trunc = yield* Truncate.Service const trunc = yield* Truncate.Service
const plugin = yield* Plugin.Service const plugin = yield* Plugin.Service
const cygpath = Effect.fn("BashTool.cygpath")(function* (shell: string, text: string) { const cygpath = Effect.fn("ShellTool.cygpath")(function* (shell: string, text: string) {
const lines = yield* spawner const lines = yield* spawner
.lines(ChildProcess.make(shell, ["-lc", 'cygpath -w -- "$1"', "_", text])) .lines(ChildProcess.make(shell, ["-lc", 'cygpath -w -- "$1"', "_", text]))
.pipe(Effect.catch(() => Effect.succeed([] as string[]))) .pipe(Effect.catch(() => Effect.succeed([] as string[])))
@ -344,7 +337,7 @@ export const BashTool = Tool.define(
return AppFileSystem.normalizePath(file) return AppFileSystem.normalizePath(file)
}) })
const resolvePath = Effect.fn("BashTool.resolvePath")(function* (text: string, root: string, shell: string) { const resolvePath = Effect.fn("ShellTool.resolvePath")(function* (text: string, root: string, shell: string) {
if (process.platform === "win32") { if (process.platform === "win32") {
if (Shell.posix(shell) && text.startsWith("/") && AppFileSystem.windowsPath(text) === text) { if (Shell.posix(shell) && text.startsWith("/") && AppFileSystem.windowsPath(text) === text) {
const file = yield* cygpath(shell, text) const file = yield* cygpath(shell, text)
@ -355,7 +348,7 @@ export const BashTool = Tool.define(
return path.resolve(root, text) return path.resolve(root, text)
}) })
const argPath = Effect.fn("BashTool.argPath")(function* (arg: string, cwd: string, ps: boolean, shell: string) { const argPath = Effect.fn("ShellTool.argPath")(function* (arg: string, cwd: string, ps: boolean, shell: string) {
const text = ps ? expand(arg, cwd, shell) : home(unquote(arg)) const text = ps ? expand(arg, cwd, shell) : home(unquote(arg))
const file = text && prefix(text) const file = text && prefix(text)
if (!file || dynamic(file, ps)) return if (!file || dynamic(file, ps)) return
@ -364,7 +357,7 @@ export const BashTool = Tool.define(
return yield* resolvePath(next, cwd, shell) return yield* resolvePath(next, cwd, shell)
}) })
const collect = Effect.fn("BashTool.collect")(function* ( const collect = Effect.fn("ShellTool.collect")(function* (
root: Node, root: Node,
cwd: string, cwd: string,
ps: boolean, ps: boolean,
@ -376,14 +369,15 @@ export const BashTool = Tool.define(
patterns: new Set<string>(), patterns: new Set<string>(),
always: new Set<string>(), always: new Set<string>(),
} }
const shellKind = ShellID.toKind(Shell.name(shell))
for (const node of commands(root)) { for (const node of commands(root)) {
const command = parts(node) const command = parts(node)
const tokens = command.map((item) => item.text) const tokens = command.map((item) => item.text)
const cmd = ps ? tokens[0]?.toLowerCase() : tokens[0] const cmd = ps || shellKind === "cmd" ? tokens[0]?.toLowerCase() : tokens[0]
if (cmd && FILES.has(cmd)) { if (cmd && (FILES.has(cmd) || (shellKind === "cmd" && CMD_FILES.has(cmd)))) {
for (const arg of pathArgs(command, ps)) { for (const arg of pathArgs(command, ps, shellKind === "cmd")) {
const resolved = yield* argPath(arg, cwd, ps, shell) const resolved = yield* argPath(arg, cwd, ps, shell)
log.info("resolved path", { arg, resolved }) log.info("resolved path", { arg, resolved })
if (!resolved || containsPath(resolved, instance)) continue if (!resolved || containsPath(resolved, instance)) continue
@ -401,7 +395,7 @@ export const BashTool = Tool.define(
return scan return scan
}) })
const shellEnv = Effect.fn("BashTool.shellEnv")(function* (ctx: Tool.Context, cwd: string) { const shellEnv = Effect.fn("ShellTool.shellEnv")(function* (ctx: Tool.Context, cwd: string) {
const extra = yield* plugin.trigger( const extra = yield* plugin.trigger(
"shell.env", "shell.env",
{ cwd, sessionID: ctx.sessionID, callID: ctx.callID }, { cwd, sessionID: ctx.sessionID, callID: ctx.callID },
@ -413,7 +407,7 @@ export const BashTool = Tool.define(
} }
}) })
const run = Effect.fn("BashTool.run")(function* ( const run = Effect.fn("ShellTool.run")(function* (
input: { input: {
shell: string shell: string
command: string command: string
@ -527,7 +521,7 @@ export const BashTool = Tool.define(
const meta: string[] = [] const meta: string[] = []
if (expired) { if (expired) {
meta.push( meta.push(
`bash tool terminated command after exceeding timeout ${input.timeout} ms. If this command is expected to take longer and is not waiting for interactive input, retry with a larger timeout value in milliseconds.`, `shell tool terminated command after exceeding timeout ${input.timeout} ms. If this command is expected to take longer and is not waiting for interactive input, retry with a larger timeout value in milliseconds.`,
) )
} }
if (aborted) meta.push("User aborted the command") if (aborted) meta.push("User aborted the command")
@ -546,7 +540,7 @@ export const BashTool = Tool.define(
} }
if (meta.length > 0) { if (meta.length > 0) {
output += "\n\n<bash_metadata>\n" + meta.join("\n") + "\n</bash_metadata>" output += "\n\n<shell_metadata>\n" + meta.join("\n") + "\n</shell_metadata>"
} }
if (sink) { if (sink) {
const stream = sink const stream = sink
@ -577,25 +571,14 @@ export const BashTool = Tool.define(
const cfg = yield* config.get() const cfg = yield* config.get()
const shell = Shell.acceptable(cfg.shell) const shell = Shell.acceptable(cfg.shell)
const name = Shell.name(shell) const name = Shell.name(shell)
const chain =
name === "powershell"
? "If the commands depend on each other and must run sequentially, avoid '&&' in this shell because Windows PowerShell 5.1 does not support it. Use PowerShell conditionals such as `cmd1; if ($?) { cmd2 }` when later commands must depend on earlier success."
: "If the commands depend on each other and must run sequentially, use a single Bash call with '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead."
log.info("bash tool using shell", { shell })
const limits = yield* trunc.limits() const limits = yield* trunc.limits()
const instance = yield* InstanceState.context const prompt = ShellPrompt.render(name, process.platform, limits)
log.info("shell tool using shell", { shell })
return { return {
description: DESCRIPTION.replaceAll("${directory}", instance.directory) description: prompt.description,
.replaceAll("${tmp}", Global.Path.tmp) parameters: prompt.parameters,
.replaceAll("${os}", process.platform) execute: (params: Parameters, ctx: Tool.Context) =>
.replaceAll("${shell}", name)
.replaceAll("${chaining}", chain)
.replaceAll("${maxLines}", String(limits.maxLines))
.replaceAll("${maxBytes}", String(limits.maxBytes)),
parameters: Parameters,
execute: (params: Schema.Schema.Type<typeof Parameters>, ctx: Tool.Context) =>
Effect.gen(function* () { Effect.gen(function* () {
const executeInstance = yield* InstanceState.context const executeInstance = yield* InstanceState.context
const cwd = params.workdir const cwd = params.workdir

View file

@ -0,0 +1,19 @@
const kinds = ["bash", "pwsh", "powershell", "cmd"] as const
export type Kind = (typeof kinds)[number]
const shellKinds = new Set<string>(kinds)
function isKind(value: string): value is Kind {
return shellKinds.has(value)
}
export function toKind(value: string): Kind {
return isKind(value) ? value : "bash"
}
// Keep the exposed tool ID and permission key as "bash" for compatibility with
// existing plugins, users, and saved permissions. Rename with opencode 2.0.
export const ToolID = "bash"
export type ToolID = typeof ToolID
export * as ShellID from "./id"

View file

@ -0,0 +1,297 @@
import { Schema } from "effect"
import DESCRIPTION from "./shell.txt"
import { PositiveInt } from "@/util/schema"
import { Global } from "@opencode-ai/core/global"
import { ShellID } from "./id"
const PS = new Set(["powershell", "pwsh"])
const CMD = new Set(["cmd"])
const descriptions = {
bash:
"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'",
powershell:
'Clear, concise description of what this command does in 5-10 words. Examples:\nInput: Get-ChildItem -LiteralPath "."\nOutput: Lists current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: New-Item -ItemType Directory -Path "tmp"\nOutput: Creates directory tmp',
cmd:
'Clear, concise description of what this command does in 5-10 words. Examples:\nInput: dir\nOutput: Lists current directory\n\nInput: if exist "package.json" type "package.json"\nOutput: Prints package.json when it exists\n\nInput: mkdir tmp\nOutput: Creates directory tmp',
}
export type Limits = {
maxLines: number
maxBytes: number
}
export function parameterSchema(description: string) {
return Schema.Struct({
command: Schema.String.annotate({ description: "The command to execute" }),
timeout: Schema.optional(PositiveInt).annotate({ description: "Optional timeout in milliseconds" }),
workdir: Schema.optional(Schema.String).annotate({
description: `The working directory to run the command in. Defaults to the current directory. Use this instead of 'cd' commands.`,
}),
description: Schema.String.annotate({ description }),
})
}
export const Parameters = parameterSchema(descriptions.bash)
export type Parameters = Schema.Schema.Type<typeof Parameters>
function renderPrompt(template: string, values: Record<string, string>) {
return template.replace(/\$\{(\w+)\}/g, (_, key: string) => {
const value = values[key]
if (value === undefined) throw new Error(`Missing shell prompt value: ${key}`)
return value
})
}
function shellDisplayName(name: string) {
if (name === "pwsh") return "PowerShell (7+)"
if (name === "powershell") return "Windows PowerShell (5.1)"
if (name === "cmd") return "cmd.exe"
return name
}
function powershellNotes(name: string) {
if (name === "pwsh") {
return `# PowerShell (7+) shell notes
- This cross-platform shell supports pipeline chain operators (\`&&\` and \`||\`).
- Use double quotes for interpolated strings (\`"Hello $name"\`), single quotes for verbatim strings.
- Prefer full cmdlet names like \`Get-ChildItem\`, \`Set-Content\`, \`Remove-Item\`, and \`New-Item\` over aliases.
- Use \`$(...)\` for subexpressions. Use \`@(...)\` for array expressions.
- To call a native executable whose path contains spaces, use the call operator: \`& "path/to/exe" args\`.
- Escape special characters with the PowerShell backtick character.`
}
if (name === "powershell") {
return `# Windows PowerShell (5.1) shell notes
- Use \`cmd1; if ($?) { cmd2 }\` to chain dependent commands.
- Use double quotes for interpolated strings (\`"Hello $name"\`), single quotes for verbatim strings.
- Prefer full cmdlet names like \`Get-ChildItem\`, \`Set-Content\`, \`Remove-Item\`, and \`New-Item\` over aliases.
- Use \`$(...)\` for subexpressions. Use \`@(...)\` for array expressions.
- To call a native executable whose path contains spaces, use the call operator: \`& "path/to/exe" args\`.
- Escape special characters with the PowerShell backtick character.`
}
return ""
}
function chainGuidance(name: string) {
if (name === "powershell") {
return "If the commands depend on each other and must run sequentially, avoid '&&' in this shell because Windows PowerShell (5.1) does not support it. Use PowerShell conditionals such as `cmd1; if ($?) { cmd2 }` when later commands must depend on earlier success."
}
if (PS.has(name)) {
return "If the commands depend on each other and must run sequentially, use a single bash tool call with '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like New-Item before Copy-Item, Write before bash for git operations, or git add before git commit), run these operations sequentially instead."
}
if (CMD.has(name)) {
return "If the commands depend on each other and must run sequentially, use a single bash tool call with `&&` to chain them together (e.g., `mkdir out && dir out`). For instance, if one operation must complete before another starts, run these operations sequentially instead."
}
return "If the commands depend on each other and must run sequentially, use a single Bash call with '&&' to chain them together (e.g., `git add . && git commit -m \"message\" && git push`). For instance, if one operation must complete before another starts (like mkdir before cp, Write before Bash for git operations, or git add before git commit), run these operations sequentially instead."
}
function bashCommandSection(chain: string, limits: Limits) {
return `Before executing the command, please follow these steps:
1. Directory Verification:
- If the command will create new directories or files, first use \`ls\` to verify the parent directory exists and is the correct location
- For example, before running "mkdir foo/bar", first use \`ls foo\` to check that "foo" exists and is the intended parent directory
2. Command Execution:
- Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
- Examples of proper quoting:
- mkdir "/Users/name/My Documents" (correct)
- mkdir /Users/name/My Documents (incorrect - will fail)
- python "/path/with spaces/script.py" (correct)
- python /path/with spaces/script.py (incorrect - will fail)
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- If the output exceeds ${limits.maxLines} lines or ${limits.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use \`head\`, \`tail\`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.
- Avoid using Bash with the \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
- File search: Use Glob (NOT find or ls)
- Content search: Use Grep (NOT grep or rg)
- Read files: Use Read (NOT cat/head/tail)
- Edit files: Use Edit (NOT sed/awk)
- Write files: Use Write (NOT echo >/cat <<EOF)
- Communication: Output text directly (NOT echo/printf)
- When issuing multiple commands:
- If the commands are independent and can run in parallel, make multiple bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two bash tool calls in parallel.
- ${chain}
- Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
- AVOID using \`cd <directory> && <command>\`. Use the \`workdir\` parameter to change directories instead.
<good-example>
Use workdir="/foo/bar" with command: pytest tests
</good-example>
<bad-example>
cd /foo/bar && pytest tests
</bad-example>`
}
function powershellCommandSection(name: string, chain: string, pathSep: string, limits: Limits) {
return `${powershellNotes(name)}
Before executing the command, please follow these steps:
1. Directory Verification:
- If the command will create new directories or files, first use \`Test-Path -LiteralPath <parent>\` to verify the parent directory exists and is the correct location
- For example, before creating \`foo${pathSep}bar\`, first use \`Test-Path -LiteralPath "foo"\` to check that \`foo\` exists and is the intended parent directory
2. Command Execution:
- Always quote file paths that contain spaces with double quotes (e.g., Remove-Item -LiteralPath "path with spaces${pathSep}file.txt")
- Examples of proper quoting:
- New-Item -ItemType Directory -Path "My Documents" (correct)
- New-Item -ItemType Directory -Path My Documents (incorrect - path is split)
- & "path with spaces${pathSep}script.ps1" (correct)
- path with spaces${pathSep}script.ps1 (incorrect - path is split and not invoked)
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- If the output exceeds ${limits.maxLines} lines or ${limits.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use \`Select-Object -First\`, \`Select-Object -Last\`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.
- Avoid using Shell with PowerShell file/content cmdlets unless explicitly instructed or when these cmdlets are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
- File search: Use Glob (NOT Get-ChildItem)
- Content search: Use Grep (NOT Select-String)
- Read files: Use Read (NOT Get-Content)
- Edit files: Use Edit (NOT Set-Content)
- Write files: Use Write (NOT Set-Content/Out-File or here-strings)
- Communication: Output text directly (NOT Write-Output/Write-Host)
- When issuing multiple commands:
- If the commands are independent and can run in parallel, make multiple bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two bash tool calls in parallel.
- ${chain}
- Use \`;\` only when you need to run commands sequentially but don't care if earlier commands fail
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
- AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
<good-example>
Use workdir="project${pathSep}subdir" with command: pytest tests
</good-example>
<bad-example>
${name === "powershell" ? `Set-Location -LiteralPath "project${pathSep}subdir"; if ($?) { pytest tests }` : `Set-Location -LiteralPath "project${pathSep}subdir" && pytest tests`}
</bad-example>`
}
function cmdCommandSection(chain: string, limits: Limits) {
return `# cmd.exe shell notes
- Use double quotes for paths with spaces.
- Use %VAR% for environment variables.
- Use \`if exist\` for existence checks.
- Use \`call\` when invoking batch files from another batch-style command.
Before executing the command, please follow these steps:
1. Directory Verification:
- If the command will create new directories or files, first use \`if exist\` to verify the parent directory exists and is the correct location
- For example, before creating \`foo\\bar\`, first use \`if exist "foo\\" dir "foo"\` to check that \`foo\` exists and is the intended parent directory
2. Command Execution:
- Always quote file paths that contain spaces with double quotes (e.g., del "path with spaces\\file.txt")
- Examples of proper quoting:
- mkdir "My Documents" (correct)
- mkdir My Documents (incorrect - path is split)
- call "path with spaces\\script.bat" (correct)
- path with spaces\\script.bat (incorrect - path is split and not invoked correctly)
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- If the output exceeds ${limits.maxLines} lines or ${limits.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use \`more\` or other pagination commands to limit output; the full output will already be captured to a file for more precise searching.
- Avoid using Shell with cmd.exe file/content commands unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
- File search: Use Glob (NOT dir /s)
- Content search: Use Grep (NOT findstr)
- Read files: Use Read (NOT type)
- Edit files: Use Edit (NOT copy)
- Write files: Use Write (NOT echo > file)
- Communication: Output text directly (NOT echo)
- When issuing multiple commands:
- If the commands are independent and can run in parallel, make multiple bash tool calls in a single message. For example, if you need to run "dir" and "where cmd", send a single message with two bash tool calls in parallel.
- ${chain}
- Use \`&\` only when you need to run commands sequentially but don't care if earlier commands fail
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
- AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
<good-example>
Use workdir="project\\subdir" with command: dir
</good-example>
<bad-example>
cd /d "project\\subdir" && dir
</bad-example>`
}
function profile(name: string, platform: NodeJS.Platform, limits: Limits) {
const isPowerShell = PS.has(name)
const chain = chainGuidance(name)
if (CMD.has(name)) {
return {
intro: `Executes a given ${shellDisplayName(name)} command with optional timeout, ensuring proper handling and security measures.`,
workdirSection:
"All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID changing directories inside the command - use `workdir` instead.",
commandSection: cmdCommandSection(chain, limits),
gitCommands: "git commands",
gitCommandRestriction: "git commands",
createPrInstruction: "Create PR using a temporary body file so cmd.exe quoting stays simple.",
createPrExample: `(\n echo ## Summary\n echo - ^<1-3 bullet points^>\n) > pr-body.txt\ngh pr create --title "the pr title" --body-file pr-body.txt`,
parameterDescription: descriptions.cmd,
}
}
if (isPowerShell) {
return {
intro: `Executes a given ${shellDisplayName(name)} command with optional timeout, ensuring proper handling and security measures.`,
workdirSection:
"All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID changing directories inside the command - use `workdir` instead.",
commandSection: powershellCommandSection(name, chain, platform === "win32" ? "\\" : "/", limits),
gitCommands: "git commands",
gitCommandRestriction: "git commands",
createPrInstruction: "Create PR using gh pr create with a PowerShell here-string to pass the body correctly.",
createPrExample: `gh pr create --title "the pr title" --body @'
## Summary
- <1-3 bullet points>
'@`,
parameterDescription: descriptions.powershell,
}
}
return {
intro:
"Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.",
workdirSection:
"All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",
commandSection: bashCommandSection(chain, limits),
gitCommands: "bash commands",
gitCommandRestriction: "git bash commands",
createPrInstruction:
"Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.",
createPrExample: `gh pr create --title "the pr title" --body "$(cat <<'EOF'
## Summary
<1-3 bullet points>`,
parameterDescription: descriptions.bash,
}
}
export function render(name: string, platform: NodeJS.Platform, limits: Limits) {
const selected = profile(name, platform, limits)
return {
description: renderPrompt(DESCRIPTION, {
intro: selected.intro,
os: platform,
shell: name,
tmp: Global.Path.tmp,
workdirSection: selected.workdirSection,
commandSection: selected.commandSection,
gitCommands: selected.gitCommands,
toolName: ShellID.ToolID,
gitCommandRestriction: selected.gitCommandRestriction,
createPrInstruction: selected.createPrInstruction,
createPrExample: selected.createPrExample,
}),
parameters: parameterSchema(selected.parameterDescription),
}
}
export * as ShellPrompt from "./prompt"

View file

@ -1,54 +1,14 @@
Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures. ${intro}
Be aware: OS: ${os}, Shell: ${shell} Be aware: OS: ${os}, Shell: ${shell}
All commands run in the current working directory by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead. ${workdirSection}
Use `${tmp}` for temporary work outside the workspace. This directory has already been created, already exists, and is pre-approved for external directory access. Use `${tmp}` for temporary work outside the workspace. This directory has already been created, already exists, and is pre-approved for external directory access.
IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead. IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file operations (reading, writing, editing, searching, finding files) - use the specialized tools for this instead.
Before executing the command, please follow these steps: ${commandSection}
1. Directory Verification:
- If the command will create new directories or files, first use `ls` to verify the parent directory exists and is the correct location
- For example, before running "mkdir foo/bar", first use `ls foo` to check that "foo" exists and is the intended parent directory
2. Command Execution:
- Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
- Examples of proper quoting:
- mkdir "/Users/name/My Documents" (correct)
- mkdir /Users/name/My Documents (incorrect - will fail)
- python "/path/with spaces/script.py" (correct)
- python /path/with spaces/script.py (incorrect - will fail)
- After ensuring proper quoting, execute the command.
- Capture the output of the command.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- If the output exceeds ${maxLines} lines or ${maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Do NOT use `head`, `tail`, or other truncation commands to limit output; the full output will already be captured to a file for more precise searching.
- Avoid using Bash with the `find`, `grep`, `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
- File search: Use Glob (NOT find or ls)
- Content search: Use Grep (NOT grep or rg)
- Read files: Use Read (NOT cat/head/tail)
- Edit files: Use Edit (NOT sed/awk)
- Write files: Use Write (NOT echo >/cat <<EOF)
- Communication: Output text directly (NOT echo/printf)
- When issuing multiple commands:
- If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel.
- ${chaining}
- Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
- DO NOT use newlines to separate commands (newlines are ok in quoted strings)
- AVOID using `cd <directory> && <command>`. Use the `workdir` parameter to change directories instead.
<good-example>
Use workdir="/foo/bar" with command: pytest tests
</good-example>
<bad-example>
cd /foo/bar && pytest tests
</bad-example>
# Committing changes with git # Committing changes with git
@ -67,7 +27,7 @@ Git Safety Protocol:
- CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push) - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
- NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive. - NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel, each using the Bash tool: 1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following ${gitCommands} in parallel, each using the ${toolName} tool:
- Run a git status command to see all untracked files. - Run a git status command to see all untracked files.
- Run a git diff command to see both staged and unstaged changes that will be committed. - Run a git diff command to see both staged and unstaged changes that will be committed.
- Run a git log command to see recent commit messages, so that you can follow this repository's commit message style. - Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
@ -84,18 +44,18 @@ Git Safety Protocol:
4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above) 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
Important notes: Important notes:
- NEVER run additional commands to read or explore code, besides git bash commands - NEVER run additional commands to read or explore code, besides ${gitCommandRestriction}
- NEVER use the TodoWrite or Task tools - NEVER use the TodoWrite or Task tools
- DO NOT push to the remote repository unless the user explicitly asks you to do so - DO NOT push to the remote repository unless the user explicitly asks you to do so
- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported. - IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit - If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
# Creating pull requests # Creating pull requests
Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a GitHub URL use the gh command to get the information needed. Use the gh command via the ${toolName} tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a GitHub URL use the gh command to get the information needed.
IMPORTANT: When the user asks you to create a pull request, follow these steps carefully: IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch: 1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following ${gitCommands} in parallel using the ${toolName} tool, in order to understand the current state of the branch since it diverged from the main branch:
- Run a git status command to see all untracked files - Run a git status command to see all untracked files
- Run a git diff command to see both staged and unstaged changes that will be committed - Run a git diff command to see both staged and unstaged changes that will be committed
- Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote - Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
@ -104,11 +64,9 @@ IMPORTANT: When the user asks you to create a pull request, follow these steps c
3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel: 3. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run multiple tool calls in parallel for optimal performance. run the following commands in parallel:
- Create new branch if needed - Create new branch if needed
- Push to remote with -u flag if needed - Push to remote with -u flag if needed
- Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting. - ${createPrInstruction}
<example> <example>
gh pr create --title "the pr title" --body "$(cat <<'EOF' ${createPrExample}
## Summary
<1-3 bullet points>
</example> </example>
Important: Important:

View file

@ -620,7 +620,7 @@ describe("session.message-v2.toModelMessage", () => {
status: "completed", status: "completed",
input: { cmd: "ls" }, input: { cmd: "ls" },
output: "abcdefghij", output: "abcdefghij",
title: "Bash", title: "Shell",
metadata: {}, metadata: {},
time: { start: 0, end: 1 }, time: { start: 0, end: 1 },
}, },
@ -740,9 +740,9 @@ describe("session.message-v2.toModelMessage", () => {
"12179", "12179",
"4575", "4575",
"", "",
"<bash_metadata>", "<shell_metadata>",
"User aborted the command", "User aborted the command",
"</bash_metadata>", "</shell_metadata>",
].join("\n") ].join("\n")
const input: MessageV2.WithParts[] = [ const input: MessageV2.WithParts[] = [

View file

@ -10,7 +10,6 @@ import { toJsonSchema } from "../../src/util/effect-zod"
// byte-identical regardless of whether a tool has migrated from zod to Schema. // byte-identical regardless of whether a tool has migrated from zod to Schema.
import { Parameters as ApplyPatch } from "../../src/tool/apply_patch" import { Parameters as ApplyPatch } from "../../src/tool/apply_patch"
import { Parameters as Bash } from "../../src/tool/bash"
import { Parameters as Edit } from "../../src/tool/edit" import { Parameters as Edit } from "../../src/tool/edit"
import { Parameters as Glob } from "../../src/tool/glob" import { Parameters as Glob } from "../../src/tool/glob"
import { Parameters as Grep } from "../../src/tool/grep" import { Parameters as Grep } from "../../src/tool/grep"
@ -19,6 +18,7 @@ import { Parameters as Lsp } from "../../src/tool/lsp"
import { Parameters as Plan } from "../../src/tool/plan" import { Parameters as Plan } from "../../src/tool/plan"
import { Parameters as Question } from "../../src/tool/question" import { Parameters as Question } from "../../src/tool/question"
import { Parameters as Read } from "../../src/tool/read" import { Parameters as Read } from "../../src/tool/read"
import { Parameters as Shell } from "../../src/tool/shell"
import { Parameters as Skill } from "../../src/tool/skill" import { Parameters as Skill } from "../../src/tool/skill"
import { Parameters as Task } from "../../src/tool/task" import { Parameters as Task } from "../../src/tool/task"
import { Parameters as Todo } from "../../src/tool/todo" import { Parameters as Todo } from "../../src/tool/todo"
@ -35,7 +35,7 @@ const accepts = (schema: Schema.Decoder<unknown>, input: unknown): boolean =>
describe("tool parameters", () => { describe("tool parameters", () => {
describe("JSON Schema (wire shape)", () => { describe("JSON Schema (wire shape)", () => {
test("apply_patch", () => expect(toJsonSchema(ApplyPatch)).toMatchSnapshot()) test("apply_patch", () => expect(toJsonSchema(ApplyPatch)).toMatchSnapshot())
test("bash", () => expect(toJsonSchema(Bash)).toMatchSnapshot()) test("bash", () => expect(toJsonSchema(Shell)).toMatchSnapshot())
test("edit", () => expect(toJsonSchema(Edit)).toMatchSnapshot()) test("edit", () => expect(toJsonSchema(Edit)).toMatchSnapshot())
test("glob", () => expect(toJsonSchema(Glob)).toMatchSnapshot()) test("glob", () => expect(toJsonSchema(Glob)).toMatchSnapshot())
test("grep", () => expect(toJsonSchema(Grep)).toMatchSnapshot()) test("grep", () => expect(toJsonSchema(Grep)).toMatchSnapshot())
@ -66,20 +66,20 @@ describe("tool parameters", () => {
}) })
}) })
describe("bash", () => { describe("shell", () => {
test("accepts minimum: command + description", () => { test("accepts minimum: command + description", () => {
expect(parse(Bash, { command: "ls", description: "list" })).toEqual({ command: "ls", description: "list" }) expect(parse(Shell, { command: "ls", description: "list" })).toEqual({ command: "ls", description: "list" })
}) })
test("accepts optional timeout + workdir", () => { test("accepts optional timeout + workdir", () => {
const parsed = parse(Bash, { command: "ls", description: "list", timeout: 5000, workdir: "/tmp" }) const parsed = parse(Shell, { command: "ls", description: "list", timeout: 5000, workdir: "/tmp" })
expect(parsed.timeout).toBe(5000) expect(parsed.timeout).toBe(5000)
expect(parsed.workdir).toBe("/tmp") expect(parsed.workdir).toBe("/tmp")
}) })
test("rejects missing description (required by zod)", () => { test("rejects missing description", () => {
expect(accepts(Bash, { command: "ls" })).toBe(false) expect(accepts(Shell, { command: "ls" })).toBe(false)
}) })
test("rejects missing command", () => { test("rejects missing command", () => {
expect(accepts(Bash, { description: "list" })).toBe(false) expect(accepts(Shell, { description: "list" })).toBe(false)
}) })
}) })

View file

@ -4,7 +4,7 @@ import os from "os"
import path from "path" import path from "path"
import { Config } from "@/config/config" import { Config } from "@/config/config"
import { Shell } from "../../src/shell/shell" import { Shell } from "../../src/shell/shell"
import { BashTool } from "../../src/tool/bash" import { ShellTool } from "../../src/tool/shell"
import { Instance } from "../../src/project/instance" import { Instance } from "../../src/project/instance"
import { Filesystem } from "@/util/filesystem" import { Filesystem } from "@/util/filesystem"
import { tmpdir } from "../fixture/fixture" import { tmpdir } from "../fixture/fixture"
@ -28,9 +28,11 @@ const runtime = ManagedRuntime.make(
) )
function initBash() { function initBash() {
return runtime.runPromise(BashTool.pipe(Effect.flatMap((info) => info.init()))) return runtime.runPromise(ShellTool.pipe(Effect.flatMap((info) => info.init())))
} }
const initShell = initBash
const ctx = { const ctx = {
sessionID: SessionID.make("ses_test"), sessionID: SessionID.make("ses_test"),
messageID: MessageID.make(""), messageID: MessageID.make(""),
@ -68,6 +70,7 @@ const shells = (() => {
})() })()
const PS = new Set(["pwsh", "powershell"]) const PS = new Set(["pwsh", "powershell"])
const ps = shells.filter((item) => PS.has(item.label)) const ps = shells.filter((item) => PS.has(item.label))
const cmdShell = shells.find((item) => item.label === "cmd")
const sh = () => Shell.name(Shell.acceptable()) const sh = () => Shell.name(Shell.acceptable())
const evalarg = (text: string) => (sh() === "cmd" ? quote(text) : squote(text)) const evalarg = (text: string) => (sh() === "cmd" ? quote(text) : squote(text))
@ -135,12 +138,12 @@ const mustTruncate = (result: {
) )
} }
describe("tool.bash", () => { describe("tool.shell", () => {
each("basic", async () => { each("basic", async () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
{ {
@ -184,13 +187,13 @@ describe("tool.bash", () => {
}) })
}) })
describe("tool.bash permissions", () => { describe("tool.shell permissions", () => {
each("asks for bash permission with correct pattern", async () => { each("asks for bash permission with correct pattern", async () => {
await using tmp = await tmpdir() await using tmp = await tmpdir()
await Instance.provide({ await Instance.provide({
directory: tmp.path, directory: tmp.path,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
bash.execute( bash.execute(
@ -213,7 +216,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: tmp.path, directory: tmp.path,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
bash.execute( bash.execute(
@ -239,7 +242,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
bash.execute( bash.execute(
@ -261,11 +264,43 @@ describe("tool.bash permissions", () => {
) )
} }
for (const item of ps) {
test(
`uses PowerShell cmdlet prefixes for always-allow prompts [${item.label}]`,
withShell(item, async () => {
await using tmp = await tmpdir()
await Instance.provide({
directory: tmp.path,
fn: async () => {
const bash = await initShell()
const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await expect(
Effect.runPromise(
bash.execute(
{
command: "Remove-Item -Recurse tmp",
description: "Remove a temp directory",
},
capture(requests, err),
),
),
).rejects.toThrow(err.message)
const bashReq = requests.find((r) => r.permission === "bash")
expect(bashReq).toBeDefined()
expect(bashReq!.always).toContain("Remove-Item *")
expect(bashReq!.always).not.toContain("Remove-Item -Recurse *")
},
})
}),
)
}
each("asks for external_directory permission for wildcard external paths", async () => { each("asks for external_directory permission for wildcard external paths", async () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const file = process.platform === "win32" ? `${process.env.WINDIR!.replaceAll("\\", "/")}/*` : "/etc/*" const file = process.platform === "win32" ? `${process.env.WINDIR!.replaceAll("\\", "/")}/*` : "/etc/*"
@ -301,7 +336,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const file = path.join(outerTmp.path, "outside.txt").replaceAll("\\", "/") const file = path.join(outerTmp.path, "outside.txt").replaceAll("\\", "/")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
@ -334,7 +369,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await expect( await expect(
@ -364,7 +399,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const file = `${process.env.WINDIR!.replaceAll("\\", "/")}/win.ini` const file = `${process.env.WINDIR!.replaceAll("\\", "/")}/win.ini`
await Effect.runPromise( await Effect.runPromise(
@ -396,7 +431,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: tmp.path, directory: tmp.path,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await expect( await expect(
@ -426,7 +461,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await expect( await expect(
@ -521,7 +556,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
const root = path.parse(process.env.WINDIR!).root.replace(/[\\/]+$/, "") const root = path.parse(process.env.WINDIR!).root.replace(/[\\/]+$/, "")
@ -680,7 +715,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
bash.execute( bash.execute(
@ -702,6 +737,35 @@ describe("tool.bash permissions", () => {
} }
} }
if (process.platform === "win32" && cmdShell) {
test(
"asks for external_directory permission for cmd file commands [cmd]",
withShell(cmdShell, async () => {
await Instance.provide({
directory: projectRoot,
fn: async () => {
const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise(
bash.execute(
{
command: `TYPE "${path.join(process.env.WINDIR!, "win.ini")}"`,
description: "Read Windows ini with cmd",
},
capture(requests),
),
)
const extDirReq = requests.find((r) => r.permission === "external_directory")
expect(extDirReq).toBeDefined()
expect(extDirReq!.patterns).toContain(
Filesystem.normalizePathPattern(path.join(process.env.WINDIR!, "*")),
)
},
})
}),
)
}
each("asks for external_directory permission when cd to parent", async () => { each("asks for external_directory permission when cd to parent", async () => {
await using tmp = await tmpdir() await using tmp = await tmpdir()
await Instance.provide({ await Instance.provide({
@ -945,7 +1009,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: tmp.path, directory: tmp.path,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await Effect.runPromise( await Effect.runPromise(
bash.execute( bash.execute(
@ -967,7 +1031,7 @@ describe("tool.bash permissions", () => {
await Instance.provide({ await Instance.provide({
directory: tmp.path, directory: tmp.path,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const err = new Error("stop after permission") const err = new Error("stop after permission")
const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = [] const requests: Array<Omit<Permission.Request, "id" | "sessionID" | "tool">> = []
await expect( await expect(
@ -1001,12 +1065,12 @@ describe("tool.bash permissions", () => {
}) })
}) })
describe("tool.bash abort", () => { describe("tool.shell abort", () => {
test("preserves output when aborted", async () => { test("preserves output when aborted", async () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const controller = new AbortController() const controller = new AbortController()
const collected: string[] = [] const collected: string[] = []
const res = await Effect.runPromise( const res = await Effect.runPromise(
@ -1040,7 +1104,7 @@ describe("tool.bash abort", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
{ {
@ -1052,7 +1116,7 @@ describe("tool.bash abort", () => {
), ),
) )
expect(result.output).toContain("started") expect(result.output).toContain("started")
expect(result.output).toContain("bash tool terminated command after exceeding timeout") expect(result.output).toContain("shell tool terminated command after exceeding timeout")
expect(result.output).toContain("retry with a larger timeout value in milliseconds") expect(result.output).toContain("retry with a larger timeout value in milliseconds")
}, },
}) })
@ -1062,7 +1126,7 @@ describe("tool.bash abort", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
{ {
@ -1083,7 +1147,7 @@ describe("tool.bash abort", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
{ {
@ -1128,12 +1192,12 @@ describe("tool.bash abort", () => {
}) })
}) })
describe("tool.bash truncation", () => { describe("tool.shell truncation", () => {
test("truncates output exceeding line limit", async () => { test("truncates output exceeding line limit", async () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const lineCount = Truncate.MAX_LINES + 500 const lineCount = Truncate.MAX_LINES + 500
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
@ -1155,7 +1219,7 @@ describe("tool.bash truncation", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const byteCount = Truncate.MAX_BYTES + 10000 const byteCount = Truncate.MAX_BYTES + 10000
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
@ -1177,7 +1241,7 @@ describe("tool.bash truncation", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(
{ {
@ -1197,7 +1261,7 @@ describe("tool.bash truncation", () => {
await Instance.provide({ await Instance.provide({
directory: projectRoot, directory: projectRoot,
fn: async () => { fn: async () => {
const bash = await initBash() const bash = await initShell()
const lineCount = Truncate.MAX_LINES + 100 const lineCount = Truncate.MAX_LINES + 100
const result = await Effect.runPromise( const result = await Effect.runPromise(
bash.execute( bash.execute(