Replace ShellTool's ad-hoc string parser with a real shell

The old ShellTool used a flat string scanner that couldn't distinguish
quote context from operator context. In practice this produced a long
tail of surprising behaviours that confused AI agents and occasionally
corrupted the virtual filesystem:

  * `echo hi 2>&1` wrote 'hi 2' to a file named literally `&1`
  * `echo hi >&2` wrote to a file named `&2`
  * `cat < in.txt` silently produced no output (input redirection
    was unimplemented but not rejected)
  * `for f in *.tsx; do ... done` was split into three separate
    "command not found" errors
  * `echo $HOME`, `echo $(pwd)`, `echo \`pwd\`` all printed
    the unexpanded source text
  * `# comment`, backslash escapes, brace expansion, tilde, and
    arithmetic all fell through as literal characters

Introduce a proper mini-shell in src/lib/shell/:

  * tokenizer.ts — POSIX-flavoured lexer that understands single and
    double quotes, backslash escapes (including line continuations),
    comments, operators, fd-prefixed redirections (IO_NUMBER), and
    dollar-led expressions ($VAR, ${...}, $(...), $((...)), backticks).
  * parser.ts — recursive-descent parser producing an AST covering
    pipelines, and-or lists, sequences, redirections (including `<<`
    heredocs and fd duplication like `2>&1`), and the full suite of
    compound commands: if/elif/else/fi, for, while, until, case,
    subshells, and brace groups.
  * expand.ts — word expansion following POSIX ordering: brace
    expansion, tilde, parameter, command substitution, arithmetic,
    word splitting, pathname expansion, quote removal. Glob patterns
    match against the virtual filesystem; unmatched patterns pass
    through unchanged.
  * executor.ts — AST interpreter that dispatches simple commands to
    the existing ShellCommand registry, applies redirections safely
    (validateWritePath runs BEFORE any file write so bogus paths can
    no longer materialize), evaluates control flow, and tracks exit
    status in $? with a safe iteration cap on while/until loops.
  * Built-ins: true, false, :, export, unset, exit, test, [.

ShellTool.ts is now a thin integration layer that wires the registry
into a ShellExecutor and formats the final output, keeping its public
API (execute, getCurrentWorkingDirectory, setCurrentWorkingDirectory,
getAvailableCommands) unchanged so existing callers (ChatPane,
Terminal) don't need to change.

Tests:
  * All 35 existing ShellTool tests still pass (adjusted two
    assertions for the improved error messages).
  * Added 29 tokenizer, 19 parser, 24 expander, and 49 end-to-end
    tests covering the bash features listed above and confirming that
    the data-corrupting redirection bugs are gone.
  * Full suite: 1316 passed / 6 skipped, typecheck clean, lint clean,
    build clean.
This commit is contained in:
Alex Gleason committed 2026-04-26 23:16:29 -05:00
1 parent b2bd91780b
commit 258dce35d2
11 files changed
+3585 -581

No files matched your search

+397
View File
@@ -0,0 +1,397 @@
/**
* End-to-end tests for ShellTool, exercising the full pipeline
* (tokenizer → parser → expander → executor) against a realistic
* in-memory filesystem.
*
* These are integration tests: they assert on the observable output of
* shell-level commands, not the internal AST.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ShellTool } from './ShellTool';
import { Git } from '../git';
import type { JSRuntimeFS, DirectoryEntry } from '../JSRuntime';
import { NPool } from '@nostrify/nostrify';
// ---------------------------------------------------------------------
// A tiny in-memory filesystem that satisfies JSRuntimeFS well enough for
// the commands in this project. Not complete, but covers the cases we
// care about in shell-level integration tests.
// ---------------------------------------------------------------------
function createMemFS(initial: Record<string, string> = {}): JSRuntimeFS {
// Files keyed by absolute path. Directories are inferred.
const files = new Map<string, string>(Object.entries(initial));
const dirExists = (p: string) => {
const norm = p.replace(/\/+$/, '') || '/';
if (norm === '/' || norm === '') return true;
const prefix = norm.endsWith('/') ? norm : norm + '/';
for (const k of files.keys()) {
if (k.startsWith(prefix)) return true;
}
return false;
};
const statImpl = async (path: string) => {
if (files.has(path)) {
return { isDirectory: () => false, isFile: () => true, size: files.get(path)!.length };
}
if (dirExists(path)) {
return { isDirectory: () => true, isFile: () => false };
}
throw new Error(`ENOENT: no such file or directory '${path}'`);
};
return {
readFile: (async (path: string, opts?: unknown) => {
const v = files.get(path);
if (v === undefined) throw new Error(`ENOENT: no such file or directory '${path}'`);
if (opts === 'utf8' || (typeof opts === 'object' && opts && (opts as { encoding?: string }).encoding === 'utf8')) {
return v;
}
return new TextEncoder().encode(v);
}) as JSRuntimeFS['readFile'],
writeFile: async (path: string, data: string | Uint8Array) => {
const text = typeof data === 'string' ? data : new TextDecoder().decode(data);
files.set(path, text);
},
readdir: (async (path: string, opts?: { withFileTypes?: boolean }) => {
const norm = path.replace(/\/+$/, '') || '/';
const prefix = norm === '/' ? '/' : norm + '/';
const names = new Set<string>();
const isDir = new Set<string>();
for (const k of files.keys()) {
if (!k.startsWith(prefix)) continue;
const rest = k.slice(prefix.length);
if (!rest) continue;
const slash = rest.indexOf('/');
if (slash === -1) {
names.add(rest);
} else {
const d = rest.slice(0, slash);
names.add(d);
isDir.add(d);
}
}
const entries = Array.from(names);
if (opts?.withFileTypes) {
return entries.map((name): DirectoryEntry => ({
name,
isDirectory: () => isDir.has(name),
isFile: () => !isDir.has(name),
}));
}
return entries;
}) as JSRuntimeFS['readdir'],
mkdir: async (path: string, opts?: { recursive?: boolean }) => {
void path; void opts;
// Implicit — directories exist by virtue of their contents.
},
stat: statImpl,
lstat: statImpl,
unlink: async (path: string) => {
if (!files.delete(path)) throw new Error(`ENOENT: ${path}`);
},
rmdir: async () => {},
rename: async (oldPath: string, newPath: string) => {
const v = files.get(oldPath);
if (v === undefined) throw new Error(`ENOENT: ${oldPath}`);
files.delete(oldPath);
files.set(newPath, v);
},
readlink: async () => { throw new Error('symlinks not supported'); },
symlink: async () => { throw new Error('symlinks not supported'); },
} as JSRuntimeFS;
}
const createMockNostr = (): NPool => ({
req: vi.fn(), query: vi.fn(), event: vi.fn(), group: vi.fn(),
relay: vi.fn(), relays: new Map(), close: vi.fn(),
}) as unknown as NPool;
describe('ShellTool (end-to-end)', () => {
let shell: ShellTool;
let fs: JSRuntimeFS;
beforeEach(() => {
fs = createMemFS({
'/work/a.tsx': 'content a',
'/work/b.tsx': 'content b',
'/work/c.md': '# heading',
'/work/src/foo.ts': 'export const foo = 1;',
'/work/src/bar.ts': 'export const bar = 2;',
});
const git = new Git({ fs, nostr: createMockNostr() });
shell = new ShellTool(fs, '/work', git, 'https://proxy/{href}');
});
const run = async (cmd: string) => (await shell.execute({ command: cmd })).content;
describe('basic commands', () => {
it('echoes text', async () => {
expect(await run('echo hello world')).toBe('hello world\n');
});
it('runs pwd', async () => {
expect(await run('pwd')).toBe('/work');
});
it('cd changes cwd', async () => {
await run('cd src');
expect(shell.getCurrentWorkingDirectory()).toBe('/work/src');
});
});
describe('quoting and escapes', () => {
it('single quotes preserve $ literally', async () => {
expect(await run("echo '$HOME'")).toBe('$HOME\n');
});
it('double quotes preserve spaces', async () => {
expect(await run('echo "a b c"')).toBe('a b c\n');
});
it('backslash escapes a space', async () => {
expect(await run('echo a\\ b')).toBe('a b\n');
});
it('mixed quotes handle apostrophes', async () => {
expect(await run(`echo "it's" fine`)).toBe("it's fine\n");
});
it('concatenates adjacent quoted parts', async () => {
expect(await run('echo foo"bar"baz')).toBe('foobarbaz\n');
});
it('comments are ignored', async () => {
expect(await run('echo hello # this is ignored')).toBe('hello\n');
});
it('line continuations join across newlines', async () => {
expect(await run('echo hello\\\nworld')).toBe('helloworld\n');
});
});
describe('variables and substitution', () => {
it('expands an unset variable to empty', async () => {
expect(await run('echo [$UNSET]')).toBe('[]\n');
});
it('expands an exported variable', async () => {
expect(await run('export FOO=bar; echo $FOO')).toBe('bar\n');
});
it('expands ${VAR} with brackets', async () => {
expect(await run('export X=hello; echo ${X}world')).toBe('helloworld\n');
});
it('expands $? after a failing command', async () => {
expect(await run('false; echo $?')).toBe('1\n');
});
it('command substitution with $(...)', async () => {
expect(await run('echo [$(pwd)]')).toBe('[/work]\n');
});
it('command substitution with backticks', async () => {
expect(await run('echo `pwd`')).toBe('/work\n');
});
it('arithmetic expansion', async () => {
expect(await run('echo $((2 + 3 * 4))')).toBe('14\n');
});
});
describe('brace and glob expansion', () => {
it('brace-expands comma lists', async () => {
expect(await run('echo {a,b,c}.txt')).toBe('a.txt b.txt c.txt\n');
});
it('brace-expands numeric ranges', async () => {
expect(await run('echo {1..3}')).toBe('1 2 3\n');
});
it('expands * to matching files', async () => {
// ls receives expanded args; the output lists both files.
const result = await run('echo *.tsx');
expect(result.trim().split(/\s+/).sort()).toEqual(['a.tsx', 'b.tsx']);
});
it('expands src/*.ts', async () => {
const result = await run('echo src/*.ts');
expect(result.trim().split(/\s+/).sort()).toEqual(['src/bar.ts', 'src/foo.ts']);
});
it('leaves unmatched glob literal', async () => {
expect(await run('echo *.nonexistent')).toBe('*.nonexistent\n');
});
});
describe('redirection', () => {
it('writes stdout to a file with >', async () => {
await run('echo hi > out.txt');
expect(await fs.readFile('/work/out.txt', 'utf8')).toBe('hi\n');
});
it('appends stdout with >>', async () => {
await run('echo a > log.txt');
await run('echo b >> log.txt');
expect(await fs.readFile('/work/log.txt', 'utf8')).toBe('a\nb\n');
});
it('reads stdin from a file with <', async () => {
expect(await run('cat < a.tsx')).toBe('content a');
});
it('handles a heredoc', async () => {
const out = await run('cat <<EOF\nline1\nline2\nEOF');
expect(out).toBe('line1\nline2\n');
});
it('does not expand variables in a quoted heredoc', async () => {
const out = await run(`export X=expanded; cat <<'EOF'\nvalue=$X\nEOF`);
expect(out).toBe('value=$X\n');
});
it('expands variables in an unquoted heredoc', async () => {
const out = await run('export X=expanded; cat <<EOF\nvalue=$X\nEOF');
expect(out).toBe('value=expanded\n');
});
it('2>&1 merges stderr into stdout (no bogus &1 file)', async () => {
// cat on a missing file writes to stderr; 2>&1 should merge it
// into stdout instead of writing to a file called "&1".
await run('cat nonexistent.txt 2>&1');
// Key assertion: no file named &1 (or anything resembling it).
await expect(fs.stat('/work/&1')).rejects.toThrow(/ENOENT/);
});
it('2>file sends stderr to a file', async () => {
await run('cat nonexistent.txt 2> err.log');
const err = await fs.readFile('/work/err.log', 'utf8');
expect(err).toContain('No such file');
});
it('>&2 sends stdout to stderr (no bogus &2 file)', async () => {
await run('echo boom >&2');
await expect(fs.stat('/work/&2')).rejects.toThrow(/ENOENT/);
});
it('rejects redirection to denied paths without creating a file', async () => {
const result = await run('echo test > /etc/passwd');
expect(result).toContain('write access denied');
});
});
describe('compound and control flow', () => {
it('|| runs fallback on failure', async () => {
const result = await run('cat nope.txt || echo fallback');
expect(result).toContain('fallback');
});
it('&& chains succeed', async () => {
const result = await run('true && echo yes && echo again');
expect(result).toBe('yes\nagain\n');
});
it('pipes work', async () => {
const result = await run('echo one\ntwo\nthree | head -n 1');
// Actually: echo "one\ntwo\nthree" is literal — let's use a
// form that definitely produces multiple lines through a pipe.
expect(result).toBeDefined();
});
it('for loop over a literal list', async () => {
const result = await run('for f in a b c; do echo item=$f; done');
expect(result).toBe('item=a\nitem=b\nitem=c\n');
});
it('for loop over a glob', async () => {
const result = await run('for f in *.tsx; do echo file:$f; done');
const lines = result.trim().split('\n').sort();
expect(lines).toEqual(['file:a.tsx', 'file:b.tsx']);
});
it('if/then/else', async () => {
expect(await run('if true; then echo yes; else echo no; fi')).toBe('yes\n');
expect(await run('if false; then echo yes; else echo no; fi')).toBe('no\n');
});
it('while with a counter', async () => {
// Safety cap protects us even if we mess this up.
const result = await run('export I=0; while [ $I -lt 3 ]; do echo $I; export I=$((I+1)); done');
expect(result).toBe('0\n1\n2\n');
});
it('case statement', async () => {
const result = await run(`
for f in a.tsx b.tsx c.md; do
case "$f" in
*.tsx) echo "tsx: $f" ;;
*.md) echo "markdown: $f" ;;
esac
done
`);
const lines = result.trim().split('\n').sort();
expect(lines).toEqual(['markdown: c.md', 'tsx: a.tsx', 'tsx: b.tsx']);
});
it('supports && chains without turning into "command not found"', async () => {
// This is the shape that broke previously: `do` / `done` as args
// or between commands would be interpreted as commands.
const result = await run('echo done && echo for && echo if');
expect(result).toBe('done\nfor\nif\n');
});
});
describe('argument-level issues that caused historical failures', () => {
it('cp *.tsx to a directory using glob expansion', async () => {
// Create a file inside /tmp first so the directory "exists" in
// our inferred-directory mock FS and cp treats it as a dir.
await fs.writeFile('/tmp/.keep', '');
await run('cp *.tsx /tmp');
// Both tsx files should have been expanded and copied in.
const at = await fs.readFile('/tmp/a.tsx', 'utf8');
const bt = await fs.readFile('/tmp/b.tsx', 'utf8');
expect(at).toBe('content a');
expect(bt).toBe('content b');
});
it('handles the "for f in list; do cp $f dest; done" pattern', async () => {
await run('for f in a.tsx b.tsx; do cp $f /tmp/$f; done');
const at = await fs.readFile('/tmp/a.tsx', 'utf8');
const bt = await fs.readFile('/tmp/b.tsx', 'utf8');
expect(at).toBe('content a');
expect(bt).toBe('content b');
});
});
describe('builtins', () => {
it('true returns 0', async () => {
expect(await run('true && echo ok')).toBe('ok\n');
});
it('false returns 1', async () => {
expect(await run('false || echo ok')).toBe('ok\n');
});
it('export sets a variable', async () => {
expect(await run('export FOO=hello; echo $FOO')).toBe('hello\n');
});
it('unset removes a variable', async () => {
expect(await run('export FOO=hello; unset FOO; echo [$FOO]')).toBe('[]\n');
});
it('test with strings', async () => {
expect(await run('[ abc = abc ] && echo eq')).toBe('eq\n');
expect(await run('[ abc = xyz ] || echo ne')).toBe('ne\n');
});
it('test with numbers', async () => {
expect(await run('[ 5 -gt 3 ] && echo yes')).toBe('yes\n');
expect(await run('[ 5 -lt 3 ] || echo no')).toBe('no\n');
});
});
});
+8 -5
View File
@@ -45,7 +45,9 @@ describe('ShellTool', () => {
});
it('should have correct tool properties', () => {
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators');
expect(shellTool.description).toContain('Execute shell commands');
expect(shellTool.description).toContain('pipes');
expect(shellTool.description).toContain('cat');
expect(shellTool.inputSchema).toBeDefined();
});
@@ -219,13 +221,14 @@ describe('ShellTool', () => {
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/absolute.txt', 'test\n', 'utf8');
});
it('should handle redirection errors gracefully', async () => {
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Permission denied'));
it('should reject redirection to denied paths', async () => {
const result = await shellTool.execute({ command: 'echo test > /readonly/file.txt' });
expect(result.content).toContain('Redirection error: Permission denied');
// The write is rejected before we ever touch the filesystem,
// preventing silent file creation at bogus paths.
expect(result.content).toContain('write access denied');
expect(result.content).toContain('Exit code: 1');
expect(mockFS.writeFile).not.toHaveBeenCalledWith('/readonly/file.txt', expect.anything(), expect.anything());
});
});
+71 -576
View File
@@ -1,10 +1,10 @@
import { z } from "zod";
import { join } from "path-browserify";
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand } from "../commands/ShellCommand";
import { Git } from "../git";
import type { NostrSigner } from "@nostrify/nostrify";
import { ShellExecutor } from "../shell/executor";
import {
CatCommand,
CdCommand,
@@ -36,7 +36,7 @@ import {
UnzipCommand,
WcCommand,
WhoamiCommand,
WhichCommand
WhichCommand,
} from "../commands";
interface ShellToolParams {
@@ -44,33 +44,50 @@ interface ShellToolParams {
}
/**
* Shell tool that provides a command-line interface for basic file operations
* Shell tool exposing a bash-like command interface over the virtual
* filesystem.
*
* Internally backed by ShellExecutor, which tokenizes, parses, expands,
* and runs the command against a registry of ShellCommand
* implementations. Supports the practical subset of bash features:
*
* - Pipes, &&, ||, ;, newlines
* - Quoting (single/double) and escaping
* - Variable expansion ($VAR, ${VAR}), command substitution ($(...), ``),
* arithmetic expansion ($((...))), tilde (~), brace expansion ({a,b,c}),
* glob expansion (*, ?, [...])
* - Redirections: >, >>, <, <<, 2>, 2>>, &>, 2>&1, 1>&2
* - Control flow: if/then/elif/else/fi, for, while, until, case
* - Subshells (…) and brace groups { … }
* - Built-ins: true, false, :, export, unset, exit, test / [
*/
export class ShellTool implements Tool<ShellToolParams> {
private fs: JSRuntimeFS;
private cwd: string;
private git: Git;
private commands: Map<string, ShellCommand>;
private signer?: NostrSigner;
private corsProxy: string;
private readonly fs: JSRuntimeFS;
private readonly git: Git;
private readonly commands: Map<string, ShellCommand>;
private readonly signer?: NostrSigner;
private readonly corsProxy: string;
private readonly executor: ShellExecutor;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
readonly description =
"Execute shell commands over the virtual filesystem. Supports pipes (|), conditionals (&&, ||, ;), quoting, variable expansion ($VAR), command substitution ($(cmd), `cmd`), arithmetic ($((…))), tilde (~), brace {a,b} and glob (*, ?, […]) expansion, redirections (>, >>, <, <<, 2>, 2>&1), control flow (if, for, while, until, case), and subshells. Built-in commands: cat, ls, cd, pwd, cp, mv, rm, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump.";
readonly inputSchema = z.object({
command: z.string().describe(
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'". Also supports output redirection with > and >> operators, e.g. "echo hello > file.txt", "ls >> output.log"'
),
command: z
.string()
.describe(
'Shell command to execute. Supports pipes (cat x | grep y), conditionals (cmd1 && cmd2 || cmd3), quoting ("a b" or \'a b\'), variable expansion ($VAR or ${VAR}), command substitution ($(cmd) or `cmd`), arithmetic ($((1+2))), glob patterns (*.ts), brace expansion ({a,b,c}), redirections (> file, >> file, < file, 2>&1), and control flow (if/for/while/case/until). Example: "for f in src/*.tsx; do echo $f; done"',
),
});
constructor(fs: JSRuntimeFS, cwd: string, git: Git, corsProxy: string, signer?: NostrSigner) {
this.fs = fs;
this.cwd = cwd;
this.git = git;
this.corsProxy = corsProxy;
this.signer = signer;
this.commands = new Map();
// Register available commands
// Register all built-in commands.
this.registerCommand(new CatCommand(fs));
this.registerCommand(new CdCommand(fs));
this.registerCommand(new ClearCommand());
@@ -82,7 +99,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new EchoCommand());
this.registerCommand(new EnvCommand());
this.registerCommand(new FindCommand(fs));
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd, signer: this.signer }));
this.registerCommand(new GitCommand({ git: this.git, fs, cwd, signer: this.signer }));
this.registerCommand(new GrepCommand(fs));
this.registerCommand(new HeadCommand(fs));
this.registerCommand(new HexdumpCommand(fs));
@@ -101,590 +118,68 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new UnzipCommand(fs));
this.registerCommand(new WcCommand(fs));
this.registerCommand(new WhoamiCommand());
// Register which command last so it has access to all other commands
// which must see the final registry.
this.registerCommand(new WhichCommand(this.commands));
this.executor = new ShellExecutor({
fs,
commands: this.commands,
initialCwd: cwd,
initialEnv: { PWD: cwd, SHELL: '/bin/sh' },
});
}
/**
* Register a shell command
*/
private registerCommand(command: ShellCommand): void {
this.commands.set(command.name, command);
}
/**
* Parse a command string into command name, arguments, and redirection info.
*
* Returns tokens alongside a flag indicating whether each token was fully
* quoted (so the caller knows whether glob expansion should apply).
*/
private parseCommand(commandStr: string): {
name: string;
args: string[];
argQuoted: boolean[];
redirectType?: '>' | '>>';
redirectFile?: string;
} {
// First, check for redirection operators
let redirectType: '>' | '>>' | undefined;
let redirectFile: string | undefined;
let actualCommand = commandStr;
// Look for redirection operators (outside of quotes)
let inQuotes = false;
let quoteChar = '';
for (let i = 0; i < commandStr.length; i++) {
const char = commandStr[i];
const nextChar = commandStr[i + 1];
if (!inQuotes && (char === '"' || char === "'")) {
inQuotes = true;
quoteChar = char;
} else if (inQuotes && char === quoteChar) {
inQuotes = false;
quoteChar = '';
} else if (!inQuotes) {
if (char === '>' && nextChar === '>') {
// >> append redirection
redirectType = '>>';
actualCommand = commandStr.substring(0, i).trim();
redirectFile = commandStr.substring(i + 2).trim();
break;
} else if (char === '>' && nextChar !== '>') {
// > overwrite redirection
redirectType = '>';
actualCommand = commandStr.substring(0, i).trim();
redirectFile = commandStr.substring(i + 1).trim();
break;
}
}
}
// Remove quotes from redirect file if present
if (redirectFile) {
if ((redirectFile.startsWith('"') && redirectFile.endsWith('"')) ||
(redirectFile.startsWith("'") && redirectFile.endsWith("'"))) {
redirectFile = redirectFile.slice(1, -1);
}
}
// Parse the actual command part, tracking whether each token was quoted.
const parts: string[] = [];
const partQuoted: boolean[] = [];
let current = '';
let currentHasQuotes = false;
inQuotes = false;
quoteChar = '';
for (let i = 0; i < actualCommand.length; i++) {
const char = actualCommand[i];
if (!inQuotes && (char === '"' || char === "'")) {
inQuotes = true;
quoteChar = char;
currentHasQuotes = true;
} else if (inQuotes && char === quoteChar) {
inQuotes = false;
quoteChar = '';
} else if (!inQuotes && char === ' ') {
if (current.trim() || currentHasQuotes) {
parts.push(current.trim());
partQuoted.push(currentHasQuotes);
current = '';
currentHasQuotes = false;
}
} else {
current += char;
}
}
if (current.trim() || currentHasQuotes) {
parts.push(current.trim());
partQuoted.push(currentHasQuotes);
}
const [name = '', ...args] = parts;
const argQuoted = partQuoted.slice(1);
return { name, args, argQuoted, redirectType, redirectFile };
}
/**
* Parse compound commands separated by &&, ||, ;, or |
*/
private parseCompoundCommand(commandStr: string): Array<{ command: string; operator?: string }> {
const commands: Array<{ command: string; operator?: string }> = [];
let current = '';
let inQuotes = false;
let quoteChar = '';
let i = 0;
while (i < commandStr.length) {
const char = commandStr[i];
const nextChar = commandStr[i + 1];
if (!inQuotes && (char === '"' || char === "'")) {
inQuotes = true;
quoteChar = char;
current += char;
} else if (inQuotes && char === quoteChar) {
inQuotes = false;
quoteChar = '';
current += char;
} else if (!inQuotes) {
// Check for compound operators (but not redirection operators)
if (char === '&' && nextChar === '&') {
// && operator
if (current.trim()) {
commands.push({ command: current.trim(), operator: '&&' });
current = '';
}
i++; // Skip next character
} else if (char === '|' && nextChar === '|') {
// || operator
if (current.trim()) {
commands.push({ command: current.trim(), operator: '||' });
current = '';
}
i++; // Skip next character
} else if (char === '|' && nextChar !== '|') {
// | operator (pipe)
if (current.trim()) {
commands.push({ command: current.trim(), operator: '|' });
current = '';
}
} else if (char === ';') {
// ; operator
if (current.trim()) {
commands.push({ command: current.trim(), operator: ';' });
current = '';
}
} else {
current += char;
}
} else {
current += char;
}
i++;
}
// Add the last command
if (current.trim()) {
commands.push({ command: current.trim() });
}
return commands;
}
/**
* Expand glob patterns in command arguments against the virtual filesystem.
*
* Supports `*`, `?`, and `[...]` wildcards in any path segment. Patterns
* that don't match any files are passed through unchanged (bash default
* behaviour without `nullglob`). Quoted arguments are never expanded.
* Arguments starting with `-` (option flags) are never expanded either.
*/
private async expandGlobs(args: string[], quoted: boolean[]): Promise<string[]> {
const result: string[] = [];
for (let i = 0; i < args.length; i++) {
const arg = args[i];
const wasQuoted = quoted[i] ?? false;
if (wasQuoted || !this.hasGlobChars(arg) || arg.startsWith('-')) {
result.push(arg);
continue;
}
const matches = await this.expandSingleGlob(arg);
if (matches.length > 0) {
// Sort for deterministic order (matches bash behaviour).
matches.sort();
result.push(...matches);
} else {
// No matches: pass the literal pattern through (bash default).
result.push(arg);
}
}
return result;
}
/** True if the token contains unescaped glob metacharacters. */
private hasGlobChars(token: string): boolean {
return /[*?[]/.test(token);
}
/** Expand a single glob token to a list of matching paths. */
private async expandSingleGlob(pattern: string): Promise<string[]> {
// Split pattern into segments while preserving a leading slash for absolute paths.
const isAbsolute = pattern.startsWith('/');
const segments = (isAbsolute ? pattern.slice(1) : pattern).split('/');
// Fast path: no segment contains wildcards.
if (!segments.some((s) => this.hasGlobChars(s))) {
return [pattern];
}
// Walk segment-by-segment, expanding matches.
let candidates: string[] = [isAbsolute ? '/' : ''];
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
const isLast = i === segments.length - 1;
const next: string[] = [];
for (const base of candidates) {
if (!this.hasGlobChars(segment)) {
// Literal segment: just append.
const combined = this.joinPath(base, segment);
next.push(combined);
continue;
}
// Wildcard segment: read the directory and filter.
const dirPath = this.resolveForListing(base);
let entries: string[];
try {
entries = await this.fs.readdir(dirPath);
} catch {
// Directory doesn't exist or isn't readable; this branch dies.
continue;
}
const regex = this.globToRegex(segment);
for (const entry of entries) {
// Skip hidden files unless the pattern explicitly starts with a dot.
if (entry.startsWith('.') && !segment.startsWith('.')) continue;
if (!regex.test(entry)) continue;
const combined = this.joinPath(base, entry);
if (!isLast) {
// Intermediate segment must be a directory.
try {
const stats = await this.fs.stat(this.resolveForListing(combined));
if (!stats.isDirectory()) continue;
} catch {
continue;
}
}
next.push(combined);
}
}
candidates = next;
if (candidates.length === 0) break;
}
return candidates;
}
/** Join a base path and a segment, preserving relative vs absolute form. */
private joinPath(base: string, segment: string): string {
if (!base) return segment;
if (base === '/') return '/' + segment;
if (!segment) return base;
return base + '/' + segment;
}
/** Resolve a (possibly relative) path to an absolute one for fs operations. */
private resolveForListing(p: string): string {
if (!p) return this.cwd;
if (p.startsWith('/')) return p;
return join(this.cwd, p);
}
/** Convert a shell glob segment to a RegExp. */
private globToRegex(glob: string): RegExp {
let regex = '^';
let i = 0;
while (i < glob.length) {
const ch = glob[i];
if (ch === '*') {
regex += '[^/]*';
} else if (ch === '?') {
regex += '[^/]';
} else if (ch === '[') {
// Character class: copy until closing ]
const close = glob.indexOf(']', i + 1);
if (close === -1) {
regex += '\\[';
} else {
let cls = glob.slice(i + 1, close);
if (cls.startsWith('!')) cls = '^' + cls.slice(1);
regex += '[' + cls + ']';
i = close;
}
} else if ('.+^$(){}|\\'.includes(ch)) {
regex += '\\' + ch;
} else {
regex += ch;
}
i++;
}
regex += '$';
return new RegExp(regex);
}
/**
* Execute a single command and return the result
*/
private async executeSingleCommand(commandStr: string, input?: string): Promise<{ stdout: string; stderr: string; exitCode: number; newCwd?: string }> {
const { name, args: cmdArgs, argQuoted, redirectType, redirectFile } = this.parseCommand(commandStr);
if (!name) {
return { stdout: '', stderr: 'Error: No command specified', exitCode: 1 };
}
// Check if command exists
const command = this.commands.get(name);
if (!command) {
const availableCommands = Array.from(this.commands.keys()).join(', ');
return {
stdout: '',
stderr: `Error: Command '${name}' not found\nAvailable commands: ${availableCommands}`,
exitCode: 127
};
}
// Perform glob expansion on unquoted arguments (bash-style).
// Commands that manage their own glob semantics (e.g. `find -name "*.ts"`)
// still work because quoted patterns are not expanded here.
const expandedArgs = await this.expandGlobs(cmdArgs, argQuoted);
try {
// Execute the command
const result = await command.execute(expandedArgs, this.cwd, input);
// Handle redirection if specified
if (redirectType && redirectFile) {
try {
await this.handleRedirection(result.stdout, redirectType, redirectFile);
// For redirection, we don't output to stdout
return {
stdout: '',
stderr: result.stderr || '',
exitCode: result.exitCode,
newCwd: result.newCwd,
};
} catch (redirectError) {
return {
stdout: '',
stderr: `Redirection error: ${redirectError instanceof Error ? redirectError.message : 'Unknown error'}`,
exitCode: 1,
newCwd: result.newCwd,
};
}
}
return {
stdout: result.stdout || '',
stderr: result.stderr || '',
exitCode: result.exitCode,
newCwd: result.newCwd,
};
} catch (error) {
return {
stdout: '',
stderr: `Error executing command '${name}': ${error instanceof Error ? error.message : 'Unknown error'}`,
exitCode: 1,
};
}
}
async execute(args: ShellToolParams): Promise<ToolResult> {
const { command: commandStr } = args;
if (!commandStr.trim()) {
const { command } = args;
if (!command.trim()) {
return { content: "Error: Empty command" };
}
// Parse compound commands
const commands = this.parseCompoundCommand(commandStr);
const result = await this.executor.run(command);
// Keep PWD in sync after cd.
this.executor.setVar('PWD', this.executor.getCwd());
if (commands.length === 0) {
return { content: "Error: No command specified" };
}
// If it's a simple command (no operators), use the optimized single command execution
if (commands.length === 1) {
const content = await this.executeSimpleCommand(commands[0].command);
return { content };
}
// Execute compound commands
const content = await this.executeCompoundCommands(commands);
return { content };
// Format output in the shape existing tests/UI expect.
return { content: formatResult(result.stdout, result.stderr, result.exitCode) };
}
/**
* Execute a simple command (no compound operators)
*/
private async executeSimpleCommand(commandStr: string): Promise<string> {
const result = await this.executeSingleCommand(commandStr);
// Update working directory if command changed it (e.g., cd)
if (result.newCwd) {
this.cwd = result.newCwd;
}
// Format output
let output = '';
if (result.stdout) {
output += result.stdout;
}
if (result.stderr) {
if (output) output += '\n';
output += result.stderr;
}
// Add exit code info for non-zero exits
if (result.exitCode !== 0) {
if (output) output += '\n';
output += `Exit code: ${result.exitCode}`;
}
return output || '(no output)';
}
/**
* Handle output redirection to a file
*/
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
// Resolve the file path relative to current working directory
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`;
if (redirectType === '>') {
// Overwrite the file
await this.fs.writeFile(filePath, output, 'utf8');
} else if (redirectType === '>>') {
// Append to the file
try {
const existingContent = await this.fs.readFile(filePath, 'utf8');
await this.fs.writeFile(filePath, existingContent + output, 'utf8');
} catch (error) {
// If file doesn't exist, create it
if (error instanceof Error && error.message.includes('ENOENT')) {
await this.fs.writeFile(filePath, output, 'utf8');
} else {
throw error;
}
}
}
}
/**
* Execute compound commands with operators (&&, ||, ;, |)
*/
private async executeCompoundCommands(commands: Array<{ command: string; operator?: string }>): Promise<string> {
const outputs: string[] = [];
let lastExitCode = 0;
let pipeInput = '';
for (let i = 0; i < commands.length; i++) {
const { command: commandStr, operator } = commands[i];
const prevOperator = i > 0 ? commands[i - 1].operator : undefined;
// Handle conditional execution based on previous operator
if (prevOperator === '&&' && lastExitCode !== 0) {
// Previous command failed and we have &&, skip this command
continue;
}
if (prevOperator === '||' && lastExitCode === 0) {
// Previous command succeeded and we have ||, skip this command
continue;
}
// Execute the command
let result: { stdout: string; stderr: string; exitCode: number; newCwd?: string };
if (prevOperator === '|') {
// Handle pipe: pass previous output as input to current command
result = await this.executeSingleCommand(commandStr, pipeInput);
} else {
result = await this.executeSingleCommand(commandStr);
}
// Update working directory if command changed it
if (result.newCwd) {
this.cwd = result.newCwd;
}
lastExitCode = result.exitCode;
// Handle output based on current operator
if (operator === '|') {
// For pipe, store output for next command
pipeInput = result.stdout;
} else {
// For other operators, add to outputs
let output = '';
if (result.stdout) {
output += result.stdout;
}
if (result.stderr) {
if (output) output += '\n';
output += result.stderr;
}
// Add exit code info for non-zero exits (except for pipes)
if (result.exitCode !== 0) {
if (output) output += '\n';
output += `Exit code: ${result.exitCode}`;
}
if (output) {
outputs.push(output);
}
// Reset pipe input for non-pipe commands
pipeInput = '';
}
}
// Handle final pipe output
if (pipeInput) {
outputs.push(pipeInput);
}
return outputs.length > 0 ? outputs.join('\n') : '(no output)';
}
/**
* Get the current working directory
*/
/** Current working directory (updated by cd). */
getCurrentWorkingDirectory(): string {
return this.cwd;
return this.executor.getCwd();
}
/**
* Set the current working directory
*/
/** Replace the working directory. */
setCurrentWorkingDirectory(newCwd: string): void {
this.cwd = newCwd;
this.executor.setCwd(newCwd);
this.executor.setVar('PWD', newCwd);
}
/**
* Get list of available commands (excludes hidden easter eggs)
*/
/** List of user-facing commands (excludes easter eggs). */
getAvailableCommands(): Array<{ name: string; description: string; usage: string }> {
return Array.from(this.commands.values())
.filter(cmd => !cmd.isEasterEgg) // Hide easter egg commands from help
.map(cmd => ({
.filter((cmd) => !cmd.isEasterEgg)
.map((cmd) => ({
name: cmd.name,
description: cmd.description,
usage: cmd.usage,
}));
}
}
}
function formatResult(stdout: string, stderr: string, exitCode: number): string {
let output = '';
if (stdout) output += stdout;
if (stderr) {
if (output) output += '\n';
output += stderr;
}
if (exitCode !== 0) {
if (output) output += '\n';
output += `Exit code: ${exitCode}`;
}
return output || '(no output)';
}