From 1c8a59575ea9da8a59986f295e7906d128ff6a4f Mon Sep 17 00:00:00 2001 From: Greg Anders Date: Fri, 30 Oct 2026 16:26:34 -0500 Subject: [PATCH] Restore the bash cwd parameter --- agent/extensions/sandbox/background.ts | 5 +- agent/extensions/sandbox/command.ts | 10 ++- agent/extensions/sandbox/index.ts | 35 +++++++---- .../sandbox/test/background.test.ts | 62 ++++++++++++++----- .../sandbox/test/definition.test.ts | 6 +- .../subagent/test/background.test.ts | 6 +- agent/skills/jj/SKILL.md | 6 +- 7 files changed, 93 insertions(+), 37 deletions(-) diff --git a/agent/extensions/sandbox/background.ts b/agent/extensions/sandbox/background.ts index abd7fa5..83e942b 100644 --- a/agent/extensions/sandbox/background.ts +++ b/agent/extensions/sandbox/background.ts @@ -10,6 +10,7 @@ import { } from "@earendil-works/pi-coding-agent"; import { type Static, Type } from "typebox"; import { Check } from "typebox/value"; +import { resolveCommandCwd } from "./command.ts"; export const MAX_BACKGROUND_COMMAND_BYTES = 16 * 1024; export const MAX_BACKGROUND_TASKS = 4; @@ -23,6 +24,7 @@ const TRUNCATION_NOTICE_BYTES = 512; export interface BackgroundCommand { command: string; timeout?: number; + cwd?: string; remote?: string; } @@ -324,7 +326,7 @@ export function formatBackgroundTask(task: BackgroundTask, taskOutput = task.out export async function executeBashCommand( operations: BashOperations, - cwd: string, + baseCwd: string, toolCallId: string, params: BackgroundCommand, signal: AbortSignal | undefined, @@ -333,6 +335,7 @@ export async function executeBashCommand( onBackgroundOutput?: (output: string) => void, onBackgroundExit?: (exitCode: number | null) => void, ): Promise { + const cwd = resolveCommandCwd(baseCwd, params.cwd); const bash = createBashToolDefinition(cwd, { operations: onBackgroundOutput ? memoryOnlyOperations(operations, onBackgroundOutput, onBackgroundExit) diff --git a/agent/extensions/sandbox/command.ts b/agent/extensions/sandbox/command.ts index 617ab8d..707efeb 100644 --- a/agent/extensions/sandbox/command.ts +++ b/agent/extensions/sandbox/command.ts @@ -1,5 +1,6 @@ import { accessSync, constants, statSync } from "node:fs"; import { createRequire } from "node:module"; +import { homedir } from "node:os"; import { basename, delimiter, resolve } from "node:path"; import { Language, Parser, type Node as SyntaxNode } from "web-tree-sitter"; @@ -123,6 +124,10 @@ export function normalizedShellLiteral(value: string): string { return value.replace(/\\([\s\S])/g, "$1").replace(/["']/g, ""); } +export function resolveCommandCwd(baseCwd: string, dir?: string | null): string { + return resolve(baseCwd, dir ?? "."); +} + const CD_PREFIX = /^\s*cd\s+((?:[^\s\\;&|<>()'"`$*?[\]{}]|\\.)+|'[^']*'|"(?:[^"\\`$]|\\.)*")\s*&&\s*/; @@ -130,7 +135,10 @@ const CD_PREFIX = export function splitCdPrefix(command: string): { dir: string; rest: string } | undefined { const match = CD_PREFIX.exec(command); return match - ? { dir: normalizedShellLiteral(match[1]!), rest: command.slice(match[0].length) } + ? { + dir: normalizedShellLiteral(match[1]!).replace(/^~(?=\/|$)/, homedir()), + rest: command.slice(match[0].length), + } : undefined; } diff --git a/agent/extensions/sandbox/index.ts b/agent/extensions/sandbox/index.ts index 3043c86..59f9dd9 100644 --- a/agent/extensions/sandbox/index.ts +++ b/agent/extensions/sandbox/index.ts @@ -1,7 +1,6 @@ import { randomBytes } from "node:crypto"; import { existsSync } from "node:fs"; -import { homedir } from "node:os"; -import { join, resolve } from "node:path"; +import { join } from "node:path"; import { SandboxManager, type SandboxRuntimeConfig } from "@anthropic-ai/sandbox-runtime"; import { type AgentToolResult, @@ -42,6 +41,7 @@ import { formatRemoteLabel, REMOTE, type RemoteBashRequest } from "../remote/con import { prepareSandboxCA, uninstallSandboxCA } from "./ca.ts"; import { parseBashCommand, + resolveCommandCwd, resolveHostCommands, splitCdPrefix, type ResolvedHostCommands, @@ -90,6 +90,7 @@ const RENDERER_REQUEST = Type.Object({ }); const COMMAND = Type.String({ description: "Shell command to execute" }); const COMMAND_TIMEOUT = Type.Number({ description: "Timeout in seconds" }); +const COMMAND_CWD = Type.String({ description: "Working directory for this command" }); const BACKGROUND = Type.Literal(true, { description: "Start the command and return a task ID without waiting", }); @@ -104,6 +105,7 @@ const COMMAND_PARAMETERS = Type.Object( { command: COMMAND, timeout: Type.Optional(COMMAND_TIMEOUT), + cwd: Type.Optional(COMMAND_CWD), background: Type.Optional(BACKGROUND), remote: REMOTE, }, @@ -114,6 +116,7 @@ export const SANDBOX_BASH_PARAMETERS = Type.Object( { command: Type.Optional(COMMAND), timeout: Type.Optional(COMMAND_TIMEOUT), + cwd: Type.Optional(COMMAND_CWD), background: Type.Optional(BACKGROUND), remote: REMOTE, task: Type.Optional(TASK), @@ -678,24 +681,32 @@ export default function sandboxExtension(pi: ExtensionAPI) { } const remote = args.remote || undefined; - const cdPrefix = splitCdPrefix(args.command ?? ""); - if ( - cdPrefix && - (remote || resolve(cwd, cdPrefix.dir.replace(/^~(?=\/|$)/, homedir())) !== cwd) - ) { - shell.addChild(new Text(theme.fg("muted", `# Running in ${cdPrefix.dir}`), 0, 0)); - } + const cdPrefix = remote ? undefined : splitCdPrefix(args.command ?? ""); + // A partial cwd resolves to a different directory while its value is streaming. + // Restored rows never get argsComplete, so a final result also counts. + const cwdKnown = context.argsComplete || context.executionStarted || !context.isPartial; + const requestedCwd = cwdKnown ? args.cwd : undefined; + // Rendering does not know the remote login cwd, so a remote directory shows as given. + const runningIn = remote + ? requestedCwd + : resolveCommandCwd(resolveCommandCwd(cwd, requestedCwd), cdPrefix?.dir); const commandArgs = { command: cdPrefix?.rest ?? args.command ?? "", timeout: args.timeout, }; - const header = renderBashCall(commandArgs, theme, { + // Labels go on the first header line, which is the cwd line when it is shown. + const header = new Container(); + if (runningIn && runningIn !== cwd) { + header.addChild(new Text(theme.fg("dim", `# Running in ${runningIn}`), 0, 0)); + header.addChild(new Spacer(1)); + } + renderState.call = renderBashCall(commandArgs, theme, { ...context, args: commandArgs, executionStarted: args.background ? false : context.executionStarted, lastComponent: renderState.call, }); - renderState.call = header; + header.addChild(renderState.call); const toolCallId = context.toolCallId; shell.addChild({ render(width) { @@ -904,6 +915,7 @@ export default function sandboxExtension(pi: ExtensionAPI) { { command: params.command, timeout: params.timeout, + cwd: params.cwd, remote: params.remote, }, signal, @@ -934,6 +946,7 @@ export default function sandboxExtension(pi: ExtensionAPI) { { command: sandboxCommand ?? params.command, timeout: params.timeout, + cwd: params.cwd, }, signal, onUpdate, diff --git a/agent/extensions/sandbox/test/background.test.ts b/agent/extensions/sandbox/test/background.test.ts index 61304a8..6c6bb5a 100644 --- a/agent/extensions/sandbox/test/background.test.ts +++ b/agent/extensions/sandbox/test/background.test.ts @@ -45,6 +45,7 @@ interface TestToolContext { interface TestToolParams { command?: string; timeout?: number; + cwd?: string; remote?: string | null; background?: true; limit?: number; @@ -545,7 +546,7 @@ test("registers /task and rejects mixed execution forms", async (t) => { [{ command: "cd /tmp/* && builder check" }, "$ cd /tmp/* && builder check"], [ { command: "cd '/other dir' &&\n builder check" }, - "# Running in /other dir\n$ builder check", + "# Running in /other dir\n\n$ builder check", ], ] as const) { const callContext = { ...renderContext, args, state: {}, toolCallId: "call" }; @@ -558,14 +559,38 @@ test("registers /task and rejects mixed execution forms", async (t) => { ); } - const remoteArgs = { command: "builder check", remote: "lab" }; - const remoteContext = { ...renderContext, args: remoteArgs, argsComplete: true, state: {} }; - const remoteLines = stripVTControlCharacters( - rendered(tool.renderCall(remoteArgs, theme, remoteContext)), - ) - .split("\n") - .map((line) => line.trimEnd().replace(/ {2,}/g, " ")); - assert.ok(remoteLines.includes("$ builder check 󰒋 lab"), remoteLines.join("\n")); + for (const [args, expected] of [ + [ + { command: "builder check", remote: null, cwd: "package" }, + `# Running in ${join(process.cwd(), "package")}`, + ], + [ + { command: "cd lib && builder check", remote: null, cwd: "package" }, + `# Running in ${join(process.cwd(), "package", "lib")}`, + ], + [{ command: "builder check", remote: "lab" }, "$ builder check 󰒋 lab"], + [{ command: "builder check", remote: "lab", cwd: "src" }, "# Running in src 󰒋 lab"], + ] as const) { + const cwdContext = { ...renderContext, args, argsComplete: true, state: {} }; + const lines = stripVTControlCharacters(rendered(tool.renderCall(args, theme, cwdContext))) + .split("\n") + .map((line) => line.trimEnd().replace(/ {2,}/g, " ")); + assert.ok(lines.includes(expected), lines.join("\n")); + } + + const cwdArgs = { command: "builder check", cwd: "package" }; + for (const [state, shown] of [ + [{ argsComplete: false, executionStarted: false, isPartial: true }, false], + [{ argsComplete: true, executionStarted: false, isPartial: true }, true], + [{ argsComplete: false, executionStarted: false, isPartial: false }, true], + ] as const) { + const cwdContext = { ...renderContext, ...state, args: cwdArgs, state: {} }; + assert.equal( + rendered(tool.renderCall(cwdArgs, theme, cwdContext)).includes("# Running in"), + shown, + JSON.stringify(state), + ); + } const hiddenContext = { ...renderContext, @@ -911,10 +936,10 @@ test("evicts only the oldest completed task record", async () => { }); test("foreground and background execution share operations and background output stays bounded", async () => { - const calls: string[] = []; + const calls: Array<{ command: string; cwd: string }> = []; const operations: BashOperations = { - async exec(command, _cwd, options) { - calls.push(command); + async exec(command, cwd, options) { + calls.push({ command, cwd }); const lines = Array.from( { length: MAX_BACKGROUND_OUTPUT_LINES + 100 }, (_, index) => `line-${index}-${"x".repeat(30)}`, @@ -929,7 +954,7 @@ test("foreground and background execution share operations and background output operations, ctx.cwd, "foreground", - { command: "builder check", timeout: 60 }, + { command: "builder check", timeout: 60, cwd: "package" }, undefined, undefined, ctx, @@ -958,10 +983,17 @@ test("foreground and background execution share operations and background output }, { countChanged: () => undefined, finished: () => undefined }, ); - const task = tasks.start({ command: "builder test", timeout: 60 }, undefined); + const task = tasks.start({ command: "builder test", timeout: 60, cwd: "package" }, undefined); await task.done; - assert.deepEqual(calls, ["builder check", "builder test"]); + assert.equal(calls.length, 2); + assert.deepEqual( + calls.map(({ command, cwd }) => ({ command, cwd })), + [ + { command: "builder check", cwd: "/workspace/package" }, + { command: "builder test", cwd: "/workspace/package" }, + ], + ); assert.equal(task.state, "completed"); assert.equal(backgroundResult?.details?.fullOutputPath, undefined); for (const control of ["\u001B", "\u0007", "\r", "\u0085"]) { diff --git a/agent/extensions/sandbox/test/definition.test.ts b/agent/extensions/sandbox/test/definition.test.ts index c02b706..a5a5b1a 100644 --- a/agent/extensions/sandbox/test/definition.test.ts +++ b/agent/extensions/sandbox/test/definition.test.ts @@ -206,14 +206,14 @@ test( ); await command.handler("allow-command printf", ctx); assert.equal((await run("printf allowed")).content[0].text, "allowed"); - const remote = { command: "printf allowed", timeout: 10, remote: "lab" }; + const remote = { command: "printf allowed", timeout: 10, remote: "lab", cwd: "src" }; assert.equal( (await bash.execute("remote", remote, undefined, undefined, ctx)).content[0].text, "remote output", ); assert.deepEqual(remoteCalls[0], { command: "printf allowed", - cwd: "/remote/home", + cwd: "/remote/home/src", }); await assert.rejects( bash.execute( @@ -256,7 +256,7 @@ test( ctx, ); assert.match(status.content[0].text ?? "", /on lab.*completed/); - assert.equal(remoteCalls.at(-1)?.cwd, "/remote/home"); + assert.equal(remoteCalls.at(-1)?.cwd, "/remote/home/src"); await assert.rejects(run("printf forbidden"), /Fixture restriction/); await command.handler("deny-command printf Temporary reason", ctx); await assert.rejects(run("printf allowed"), /Temporary reason/); diff --git a/agent/extensions/subagent/test/background.test.ts b/agent/extensions/subagent/test/background.test.ts index a375d6e..8bbd9f0 100644 --- a/agent/extensions/subagent/test/background.test.ts +++ b/agent/extensions/subagent/test/background.test.ts @@ -700,7 +700,7 @@ for (const renderer of ["native", "custom"]) { const command = `env -u TMPDIR ./scripts/check.sh ${"界".repeat(140)}`; writeFileSync( f.fakePi, - `console.log(JSON.stringify(${JSON.stringify({ type: "tool_execution_start", toolName: "bash", args: { command, timeout: 30 } })}));\nsetInterval(() => {}, 1000);`, + `console.log(JSON.stringify(${JSON.stringify({ type: "tool_execution_start", toolName: "bash", args: { command, cwd: "/project/scripts", timeout: 30 } })}));\nsetInterval(() => {}, 1000);`, ); // oxlint-disable typescript/no-unsafe-type-assertion -- This fixture supplies the colors used by the widget and bash renderer. const nativeTheme = new Theme( @@ -711,7 +711,7 @@ for (const renderer of ["native", "custom"]) { // oxlint-enable typescript/no-unsafe-type-assertion const extension = loadExtension((channel, request) => { if (channel === "tool-renderer:resolve" && request.name === "bash") { - assert.deepEqual(request.args, { command, timeout: 30 }); + assert.deepEqual(request.args, { command, cwd: "/project/scripts", timeout: 30 }); } if ( renderer === "custom" && @@ -722,7 +722,7 @@ for (const renderer of ["native", "custom"]) { renderShell: "self", renderCall: () => { const box = new Box(1, 1, (text) => nativeTheme.bg("toolPendingBg", text)); - box.addChild(new Text(`$ ${command}`, 0, 0)); + box.addChild(new Text(`# Running in /project/scripts\n$ ${command}`, 0, 0)); return box; }, }; diff --git a/agent/skills/jj/SKILL.md b/agent/skills/jj/SKILL.md index 653fd11..4d92fe5 100644 --- a/agent/skills/jj/SKILL.md +++ b/agent/skills/jj/SKILL.md @@ -21,9 +21,9 @@ Quote revset expressions in the shell. ## Snapshots and sandbox -Run jj commands in the target workspace, for example `cd && jj st`. -A read-only child's permission error does not prove that the parent cannot -write. If a jj command is denied, stop and report the exact error. +Set the bash tool's `cwd` to the target workspace. A read-only child's +permission error does not prove that the parent cannot write. If a jj command +is denied, stop and report the exact error. `--ignore-working-copy` skips snapshots and working-copy updates. It can omit unsnapshotted edits. Use it only when inspecting stored revisions is sufficient, -- knotmirror 0.0.1