fix(bash): honor explicit working directories

This commit is contained in:
jb
2026-09-04 16:47:41 -04:00
parent 3d68f7c6bf
commit 328faa03e0
13 changed files with 316 additions and 21 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 JB
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+21
View File
@@ -0,0 +1,21 @@
# @jbcode/pi-bash-cwd
Pi extension that adds an optional `cwd` argument to the built-in `bash` tool. Absolute paths are used directly, relative paths resolve from the Pi session directory, and omitted paths retain the session directory. The extension validates the directory before starting the command, preventing an ignored or invalid `cwd` from running in Pi's process directory.
The override delegates execution and rendering to Pi's built-in Bash implementation. Existing `command` and `timeout` calls remain compatible.
## Install
```bash
pi install npm:@jbcode/pi-bash-cwd
```
Restart Pi or run `/reload` after installation. Pi warns that the extension replaces the built-in `bash` tool; that warning is expected.
Use this package with Pi 0.84.x. Remove it after moving to a Pi release that honors `ctx.cwd` and can be imported by extensions without undeclared runtime dependencies.
## Verify
```bash
bun run --filter '@jbcode/pi-bash-cwd' test
```
+112
View File
@@ -0,0 +1,112 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
import { createContextualBashTool } from "./index.ts";
function git(cwd: string, ...args: string[]): void {
execFileSync("git", args, { cwd, stdio: "pipe" });
}
function getOutput(
result: Awaited<ReturnType<ReturnType<typeof createContextualBashTool>["execute"]>>,
): string {
return result.content
.filter((item) => item.type === "text")
.map((item) => item.text)
.join("")
.trim();
}
async function executeIn(
sessionCwd: string,
command: string,
cwd?: string,
) {
const params = cwd === undefined ? { command } : { command, cwd };
return createContextualBashTool().execute(
"bash-cwd-test",
params,
undefined,
undefined,
{
cwd: sessionCwd,
sessionManager: {
getSessionId: () => "bash-cwd-test-session",
getSessionFile: () => undefined,
},
} as ExtensionContext,
);
}
test("bash honors hidden-worktree and nested-package cwd arguments", async (t) => {
const repository = await mkdtemp(join(tmpdir(), "pi-bash-cwd-"));
t.after(() => rm(repository, { recursive: true, force: true }));
await writeFile(join(repository, ".gitignore"), ".worktrees/\n");
await mkdir(join(repository, "extensions", "fixture"), { recursive: true });
await writeFile(
join(repository, "extensions", "fixture", "package.json"),
'{"private":true}\n',
);
git(repository, "init", "--initial-branch=main");
git(repository, "config", "user.name", "Bash cwd test");
git(repository, "config", "user.email", "bash-cwd@example.invalid");
git(repository, "add", ".");
git(repository, "commit", "-m", "fixture");
const worktree = join(repository, ".worktrees", "feature");
git(repository, "worktree", "add", "-b", "feature", worktree, "main");
const packageDirectory = join(worktree, "extensions", "fixture");
assert.equal(getOutput(await executeIn(repository, "pwd")), repository);
assert.equal(
getOutput(await executeIn(repository, 'printf %s "$PI_SESSION_ID"')),
"bash-cwd-test-session",
);
assert.equal(getOutput(await executeIn(repository, "pwd", worktree)), worktree);
assert.equal(
getOutput(
await executeIn(
repository,
"pwd",
".worktrees/feature/extensions/fixture",
),
),
packageDirectory,
);
const missingDirectory = join(worktree, "missing");
const sentinel = join(repository, "should-not-run");
await assert.rejects(
executeIn(repository, "touch should-not-run", missingDirectory),
/Working directory does not exist/,
);
await assert.rejects(access(sentinel));
});
test("bash exposes cwd without changing existing arguments", () => {
const schema = createContextualBashTool().parameters;
assert.deepEqual(Object.keys(schema.properties), ["command", "cwd", "timeout"]);
assert.deepEqual(schema.required, ["command"]);
});
test("bash fails before execution when Pi omits the tool context", async () => {
const tool = createContextualBashTool();
await assert.rejects(
tool.execute(
"bash-cwd-test",
{ command: "pwd" },
undefined,
undefined,
undefined as unknown as ExtensionContext,
),
/Bash execution context is unavailable/,
);
});
+89
View File
@@ -0,0 +1,89 @@
import { stat } from "node:fs/promises";
import { resolve } from "node:path";
import {
createBashToolDefinition,
type ExtensionAPI,
type ExtensionContext,
} from "@earendil-works/pi-coding-agent";
import { type Static, Type } from "typebox";
const bashCwdParameters = Type.Object({
command: Type.String({ description: "Shell command to execute" }),
cwd: Type.Optional(
Type.String({
description:
"Working directory. Relative paths resolve from the session working directory.",
}),
),
timeout: Type.Optional(
Type.Number({ description: "Timeout in seconds (optional, no default timeout)" }),
),
});
type BashCwdInput = Static<typeof bashCwdParameters>;
type BuiltInBashDefinition = ReturnType<typeof createBashToolDefinition>;
type BuiltInBashExecute = BuiltInBashDefinition["execute"];
async function resolveWorkingDirectory(
sessionCwd: string,
requestedCwd: string | undefined,
): Promise<string> {
const cwd = resolve(sessionCwd, requestedCwd ?? ".");
let metadata;
try {
metadata = await stat(cwd);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
throw new Error(
`Working directory does not exist: ${cwd}\nCannot execute bash commands.`,
);
}
throw error;
}
if (!metadata.isDirectory()) {
throw new Error(
`Working directory is not a directory: ${cwd}\nCannot execute bash commands.`,
);
}
return cwd;
}
export function createContextualBashTool() {
const baseTool = createBashToolDefinition(process.cwd());
return {
...baseTool,
description:
`${baseTool.description} The optional cwd may be absolute or relative to the session working directory.`,
parameters: bashCwdParameters,
async execute(
toolCallId: Parameters<BuiltInBashExecute>[0],
params: BashCwdInput,
signal: Parameters<BuiltInBashExecute>[2],
onUpdate: Parameters<BuiltInBashExecute>[3],
ctx: ExtensionContext,
) {
if (!ctx) {
throw new Error("Bash execution context is unavailable");
}
const cwd = await resolveWorkingDirectory(ctx.cwd, params.cwd);
const contextualTool = createBashToolDefinition(cwd);
return contextualTool.execute(
toolCallId,
{ command: params.command, timeout: params.timeout },
signal,
onUpdate,
ctx,
);
},
};
}
export default function bashCwd(pi: ExtensionAPI): void {
pi.registerTool(createContextualBashTool());
}
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@jbcode/pi-bash-cwd",
"version": "0.1.0",
"description": "Pi Bash override that honors the current tool execution working directory.",
"type": "module",
"license": "MIT",
"engines": { "node": ">=22.19.0" },
"keywords": ["pi-package", "pi-extension"],
"files": ["index.ts", "README.md", "LICENSE"],
"pi": { "extensions": ["./index.ts"] },
"scripts": {
"test": "node --test --experimental-strip-types index.test.ts"
},
"peerDependencies": {
"@earendil-works/pi-coding-agent": "catalog:pi-peer",
"typebox": "catalog:pi-peer"
},
"devDependencies": {
"@earendil-works/pi-coding-agent": "catalog:",
"typebox": "catalog:",
"typescript": "catalog:"
},
"publishConfig": {
"registry": "https://git.jb.codes/api/packages/jb/npm/"
},
"repository": {
"type": "git",
"url": "git+ssh://git@git.jb.codes:7722/jb/harness-tools.git",
"directory": "extensions/bash-cwd"
}
}