Enhance ShellTool with &&, ||, |, etc

This commit is contained in:
Alex Gleason committed 2025-09-11 20:54:11 -05:00
1 parent 943a4e592b
commit 4039e1e355
29 files changed
+539 -151

No files matched your search

+8 -7
View File
@@ -4,20 +4,21 @@
export interface ShellCommand {
/** The name of the command (e.g., 'cat', 'ls', 'cd') */
name: string;
/** Brief description of what the command does */
description: string;
/** Usage syntax for the command */
usage: string;
/**
* Execute the command with the given arguments
* @param args Array of command arguments (excluding the command name itself)
* @param cwd Current working directory
* @param input Optional input for pipe operations
* @returns Promise resolving to the command output or error message
*/
execute(args: string[], cwd: string): Promise<ShellCommandResult>;
execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult>;
}
/**
@@ -26,13 +27,13 @@ export interface ShellCommand {
export interface ShellCommandResult {
/** Exit code (0 for success, non-zero for error) */
exitCode: number;
/** Standard output content */
stdout: string;
/** Standard error content */
stderr: string;
/** New working directory (for commands like 'cd' that change directory) */
newCwd?: string;
}
+8 -3
View File
@@ -18,7 +18,12 @@ export class CatCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
// If input is provided (from pipe), return it
if (input !== undefined) {
return createSuccessResult(input);
}
// If no arguments provided, show usage
if (args.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
@@ -35,10 +40,10 @@ export class CatCommand implements ShellCommand {
}
const absolutePath = join(cwd, filePath);
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
+1 -1
View File
@@ -18,7 +18,7 @@ export class CdCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
let targetPath: string;
+1 -1
View File
@@ -10,7 +10,7 @@ export class ClearCommand implements ShellCommand {
description = 'Clear terminal screen';
usage = 'clear';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
// clear doesn't accept any arguments
if (args.length > 0) {
return createErrorResult(`${this.name}: arguments not supported`);
+2 -2
View File
@@ -18,7 +18,7 @@ export class CpCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length < 2) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
@@ -74,7 +74,7 @@ export class CpCommand implements ShellCommand {
if (!options.recursive) {
return createErrorResult(`${this.name}: -r not specified; omitting directory '${source}'`);
}
// Recursive directory copy
await this.copyDirectoryRecursive(sourceAbsolutePath, targetPath);
} else {
+14 -7
View File
@@ -18,7 +18,7 @@ export class CutCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
@@ -26,15 +26,21 @@ export class CutCommand implements ShellCommand {
return createErrorResult(`${this.name}: you must specify a list of bytes, characters, or fields`);
}
const lines: string[] = [];
let lines: string[] = [];
if (files.length === 0) {
// If input is provided (from pipe), process that input
if (input !== undefined) {
lines = input.split('\n');
// Remove the last empty line if the input ends with a newline
if (lines.length > 0 && lines[lines.length - 1] === '') {
lines.pop();
}
} else if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
} else {
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
@@ -70,6 +76,7 @@ export class CutCommand implements ShellCommand {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
}
// Process lines
+1 -1
View File
@@ -10,7 +10,7 @@ export class DateCommand implements ShellCommand {
description = 'Display current date and time';
usage = 'date [+FORMAT]';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
const now = new Date();
+1 -1
View File
@@ -18,7 +18,7 @@ export class DiffCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
+1 -1
View File
@@ -10,7 +10,7 @@ export class EchoCommand implements ShellCommand {
description = 'Display text';
usage = 'echo [text...]';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
// Join all arguments with spaces, like real echo
const output = args.join(' ');
+1 -1
View File
@@ -10,7 +10,7 @@ export class EnvCommand implements ShellCommand {
description = 'Display environment variables';
usage = 'env';
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
// env doesn't accept arguments in this simple implementation
if (args.length > 0) {
return createErrorResult(`${this.name}: arguments not supported in this implementation`);
+1 -1
View File
@@ -18,7 +18,7 @@ export class FindCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
const { paths, options } = this.parseArgs(args);
const searchPaths = paths.length > 0 ? paths : ['.']; // Default to current directory
+53 -21
View File
@@ -18,24 +18,56 @@ export class GrepCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing pattern\nUsage: ${this.usage}`);
}
const { options, pattern, files } = this.parseArgs(args);
if (!pattern) {
return createErrorResult(`${this.name}: missing pattern\nUsage: ${this.usage}`);
}
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
try {
const regex = new RegExp(pattern, options.ignoreCase ? 'gi' : 'g');
const outputs: string[] = [];
let foundMatches = false;
// If input is provided (from pipe), search in that input
if (input !== undefined) {
const lines = input.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (regex.test(line)) {
let output = '';
if (options.showLineNumbers) {
output += `${i + 1}:`;
}
output += line;
outputs.push(output);
foundMatches = true;
}
// Reset regex lastIndex for global regex
regex.lastIndex = 0;
}
if (!foundMatches) {
return {
exitCode: 1,
stdout: '',
stderr: '',
};
}
return createSuccessResult(outputs.join('\n') + (outputs.length > 0 ? '\n' : ''));
}
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
for (const filePath of targetFiles) {
try {
if (filePath === '-') {
@@ -48,10 +80,10 @@ export class GrepCommand implements ShellCommand {
}
const absolutePath = join(cwd, filePath);
// Check if path exists
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
if (options.recursive) {
// Recursively search directory
@@ -104,8 +136,8 @@ export class GrepCommand implements ShellCommand {
}
private async searchFile(
filePath: string,
regex: RegExp,
filePath: string,
regex: RegExp,
options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean },
displayName: string | null
): Promise<string[]> {
@@ -118,19 +150,19 @@ export class GrepCommand implements ShellCommand {
const line = lines[i];
if (regex.test(line)) {
let output = '';
if (displayName) {
output += `${displayName}:`;
}
if (options.showLineNumbers) {
output += `${i + 1}:`;
}
output += line;
matches.push(output);
}
// Reset regex lastIndex for global regex
regex.lastIndex = 0;
}
@@ -153,13 +185,13 @@ export class GrepCommand implements ShellCommand {
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
if (entry.isFile()) {
// Get relative path from base cwd for display
const relativePath = entryPath.startsWith(baseCwd)
const relativePath = entryPath.startsWith(baseCwd)
? entryPath.slice(baseCwd.length + 1)
: entryPath;
const fileMatches = await this.searchFile(entryPath, regex, options, relativePath);
matches.push(...fileMatches);
} else if (entry.isDirectory() && options.recursive) {
@@ -174,10 +206,10 @@ export class GrepCommand implements ShellCommand {
}
}
private parseArgs(args: string[]): {
options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean };
pattern: string | null;
files: string[]
private parseArgs(args: string[]): {
options: { ignoreCase: boolean; showLineNumbers: boolean; recursive: boolean };
pattern: string | null;
files: string[]
} {
const options = { ignoreCase: false, showLineNumbers: false, recursive: false };
const files: string[] = [];
@@ -186,7 +218,7 @@ export class GrepCommand implements ShellCommand {
while (i < args.length) {
const arg = args[i];
if (arg.startsWith('-') && arg !== '-') {
// Parse options
for (let j = 1; j < arg.length; j++) {
@@ -215,7 +247,7 @@ export class GrepCommand implements ShellCommand {
files.push(arg);
}
}
i++;
}
+17 -8
View File
@@ -18,8 +18,17 @@ export class HeadCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
const { options, files } = this.parseArgs(args);
// If input is provided (from pipe), process that input
if (input !== undefined) {
const lines = input.split('\n');
const selectedLines = lines.slice(0, options.lines);
const result = selectedLines.join('\n');
return createSuccessResult(result + (result && !result.endsWith('\n') ? '\n' : ''));
}
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
try {
@@ -37,10 +46,10 @@ export class HeadCommand implements ShellCommand {
}
const absolutePath = join(cwd, filePath);
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
@@ -48,15 +57,15 @@ export class HeadCommand implements ShellCommand {
// Read file content
const content = await this.fs.readFile(absolutePath, 'utf8');
const lines = content.split('\n');
// Take first n lines (but don't add extra newline if file doesn't end with one)
const selectedLines = lines.slice(0, options.lines);
// If we're showing multiple files, add a header
if (targetFiles.length > 1) {
outputs.push(`==> ${filePath} <==`);
}
// Join lines and preserve original line endings
const result = selectedLines.join('\n');
outputs.push(result);
@@ -95,7 +104,7 @@ export class HeadCommand implements ShellCommand {
while (i < args.length) {
const arg = args[i];
if (arg === '-n') {
// Next argument should be the number of lines
i++;
@@ -116,7 +125,7 @@ export class HeadCommand implements ShellCommand {
} else {
files.push(arg);
}
i++;
}
+10 -10
View File
@@ -18,7 +18,7 @@ export class LsCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
try {
// Parse options and paths
const { options, paths } = this.parseArgs(args);
@@ -48,10 +48,10 @@ export class LsCommand implements ShellCommand {
} else if (stats.isDirectory()) {
// List directory contents
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
// Filter hidden files unless -a flag is used
const filteredEntries = options.all ? entries : entries.filter(entry => !entry.name.startsWith('.'));
// Sort entries: directories first (if not -l), then alphabetically
filteredEntries.sort((a, b) => {
if (!options.long) {
@@ -68,19 +68,19 @@ export class LsCommand implements ShellCommand {
if (options.long) {
// Long format listing
const longEntries: string[] = [];
for (const entry of filteredEntries) {
try {
const entryPath = join(absolutePath, entry.name);
const entryStats = await this.fs.stat(entryPath);
const size = entryStats.size || 0;
const mtime = entryStats.mtimeMs ?
new Date(entryStats.mtimeMs).toISOString().slice(0, 16).replace('T', ' ') :
const mtime = entryStats.mtimeMs ?
new Date(entryStats.mtimeMs).toISOString().slice(0, 16).replace('T', ' ') :
'unknown ';
const permissions = entry.isDirectory() ? 'drwxr-xr-x' : '-rw-r--r--';
const name = entry.isDirectory() ? entry.name + '/' : entry.name;
longEntries.push(`${permissions} 1 user user ${size.toString().padStart(8)} ${mtime} ${name}`);
} catch {
// If we can't stat the entry, show basic info
@@ -89,11 +89,11 @@ export class LsCommand implements ShellCommand {
longEntries.push(`${permissions} 1 user user 0 unknown ${name}`);
}
}
outputs.push(longEntries.join('\n'));
} else {
// Simple format
const names = filteredEntries.map(entry =>
const names = filteredEntries.map(entry =>
entry.isDirectory() ? entry.name + '/' : entry.name
);
outputs.push(names.join(' '));
+8 -8
View File
@@ -18,7 +18,7 @@ export class MkdirCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing operand\nUsage: ${this.usage}`);
}
@@ -38,7 +38,7 @@ export class MkdirCommand implements ShellCommand {
}
const absolutePath = join(cwd, dirPath);
if (options.parents) {
// Create parent directories as needed (-p option)
await this.createDirectoryRecursive(absolutePath, dirPath);
@@ -54,9 +54,9 @@ export class MkdirCommand implements ShellCommand {
}
} catch (error) {
// Directory doesn't exist, try to create it
if (error instanceof Error &&
if (error instanceof Error &&
(error.message.includes('ENOENT') || error.message.includes('not found'))) {
// Check if parent directory exists
const parentDir = dirname(absolutePath);
try {
@@ -67,7 +67,7 @@ export class MkdirCommand implements ShellCommand {
} catch {
return createErrorResult(`${this.name}: cannot create directory '${dirPath}': No such file or directory`);
}
// Create the directory
await this.fs.mkdir(absolutePath);
} else {
@@ -112,15 +112,15 @@ export class MkdirCommand implements ShellCommand {
}
} catch (error) {
// Directory doesn't exist, try to create it
if (error instanceof Error &&
if (error instanceof Error &&
(error.message.includes('ENOENT') || error.message.includes('not found'))) {
// Try to create parent directory first
const parentDir = dirname(absolutePath);
if (parentDir !== absolutePath) { // Avoid infinite recursion
await this.createDirectoryRecursive(parentDir, dirname(originalPath));
}
// Now create this directory
await this.fs.mkdir(absolutePath);
} else {
+1 -1
View File
@@ -18,7 +18,7 @@ export class MvCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length < 2) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
+1 -1
View File
@@ -10,7 +10,7 @@ export class PwdCommand implements ShellCommand {
description = 'Print working directory';
usage = 'pwd';
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
// pwd doesn't accept any arguments in standard Linux
if (args.length > 0) {
return createErrorResult(`${this.name}: too many arguments`);
+4 -4
View File
@@ -18,7 +18,7 @@ export class RmCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing operand\nUsage: ${this.usage}`);
}
@@ -43,7 +43,7 @@ export class RmCommand implements ShellCommand {
}
const absolutePath = join(cwd, path);
try {
const stats = await this.fs.stat(absolutePath);
@@ -51,7 +51,7 @@ export class RmCommand implements ShellCommand {
if (!options.recursive) {
return createErrorResult(`${this.name}: cannot remove '${path}': Is a directory`);
}
// Recursive directory removal
await this.removeDirectoryRecursive(absolutePath);
} else {
@@ -96,7 +96,7 @@ export class RmCommand implements ShellCommand {
// Remove all contents first
for (const entry of entries) {
const entryPath = join(dirPath, entry.name);
if (entry.isDirectory()) {
await this.removeDirectoryRecursive(entryPath);
} else {
+9 -6
View File
@@ -18,18 +18,20 @@ export class SortCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
try {
const { options, files } = this.parseArgs(args);
let lines: string[] = [];
if (files.length === 0) {
// If input is provided (from pipe), sort that input
if (input !== undefined) {
lines = input.split('\n');
} else if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
} else {
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
@@ -65,6 +67,7 @@ export class SortCommand implements ShellCommand {
return createErrorResult(`${this.name}: open failed: ${file}: Unknown error`);
}
}
}
}
// Sort the lines
+18 -9
View File
@@ -18,8 +18,17 @@ export class TailCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
const { options, files } = this.parseArgs(args);
// If input is provided (from pipe), process that input
if (input !== undefined) {
const lines = input.split('\n');
const selectedLines = lines.slice(-options.lines);
const result = selectedLines.join('\n');
return createSuccessResult(result + (result && !result.endsWith('\n') ? '\n' : ''));
}
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
try {
@@ -37,10 +46,10 @@ export class TailCommand implements ShellCommand {
}
const absolutePath = join(cwd, filePath);
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
@@ -48,20 +57,20 @@ export class TailCommand implements ShellCommand {
// Read file content
const content = await this.fs.readFile(absolutePath, 'utf8');
const lines = content.split('\n');
// Remove the last empty line if the file ends with a newline
if (lines.length > 0 && lines[lines.length - 1] === '') {
lines.pop();
}
// Take last n lines
const selectedLines = lines.slice(-options.lines);
// If we're showing multiple files, add a header
if (targetFiles.length > 1) {
outputs.push(`==> ${filePath} <==`);
}
// Join lines and add final newline
const result = selectedLines.join('\n');
outputs.push(result);
@@ -100,7 +109,7 @@ export class TailCommand implements ShellCommand {
while (i < args.length) {
const arg = args[i];
if (arg === '-n') {
// Next argument should be the number of lines
i++;
@@ -121,7 +130,7 @@ export class TailCommand implements ShellCommand {
} else {
files.push(arg);
}
i++;
}
+8 -8
View File
@@ -18,7 +18,7 @@ export class TouchCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
}
@@ -32,25 +32,25 @@ export class TouchCommand implements ShellCommand {
}
const absolutePath = join(cwd, filePath);
try {
// Check if file exists
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
// File exists, update timestamp (in real systems)
// For this implementation, we'll just leave it as is since
// LightningFS doesn't have a direct way to update timestamps
// without modifying the file content
} catch (error) {
// File doesn't exist, create it
if (error instanceof Error &&
if (error instanceof Error &&
(error.message.includes('ENOENT') || error.message.includes('not found'))) {
// Ensure parent directory exists
const parentDir = dirname(absolutePath);
try {
@@ -59,7 +59,7 @@ export class TouchCommand implements ShellCommand {
// Parent directory doesn't exist
return createErrorResult(`${this.name}: cannot touch '${filePath}': No such file or directory`);
}
// Create empty file
await this.fs.writeFile(absolutePath, '', 'utf8');
} else {
+9 -6
View File
@@ -18,7 +18,7 @@ export class TrCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
try {
const { options, sets, files } = this.parseArgs(args);
@@ -32,13 +32,15 @@ export class TrCommand implements ShellCommand {
let content = '';
if (files.length === 0) {
// If input is provided (from pipe), use that input
if (input !== undefined) {
content = input;
} else if (files.length === 0) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
// Read all files
for (const file of files) {
} else {
// Read all files
for (const file of files) {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
@@ -67,6 +69,7 @@ export class TrCommand implements ShellCommand {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
}
// Process content
+8 -5
View File
@@ -18,17 +18,19 @@ export class UniqCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
try {
const { options, file } = this.parseArgs(args);
let lines: string[] = [];
if (!file) {
// If input is provided (from pipe), process that input
if (input !== undefined) {
lines = input.split('\n');
} else if (!file) {
// Read from stdin (not implemented in this context, return empty)
return createSuccessResult('');
}
try {
} else {
try {
// Handle absolute paths
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
@@ -60,6 +62,7 @@ export class UniqCommand implements ShellCommand {
} else {
return createErrorResult(`${this.name}: ${file}: Unknown error`);
}
}
}
// Process lines for uniqueness
+23 -2
View File
@@ -18,9 +18,8 @@ export class WcCommand implements ShellCommand {
this.fs = fs;
}
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
const { options, files } = this.parseArgs(args);
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
// If no specific options, show all counts
if (!options.lines && !options.words && !options.chars) {
@@ -29,6 +28,20 @@ export class WcCommand implements ShellCommand {
options.chars = true;
}
// If input is provided (from pipe), count that input
if (input !== undefined) {
const counts = this.countContent(input);
const output: string[] = [];
if (options.lines) output.push(counts.lines.toString());
if (options.words) output.push(counts.words.toString());
if (options.chars) output.push(counts.chars.toString());
return createSuccessResult(output.join(' ') + '\n');
}
const targetFiles = files.length > 0 ? files : ['-']; // stdin if no files
try {
const results: Array<{ lines: number; words: number; chars: number; name: string }> = [];
let totalLines = 0;
@@ -162,4 +175,12 @@ export class WcCommand implements ShellCommand {
return { options, files };
}
private countContent(content: string): { lines: number; words: number; chars: number } {
const lines = content.split('\n').length - (content.endsWith('\n') ? 1 : 0);
const words = content.trim() ? content.trim().split(/\s+/).length : 0;
const chars = content.length;
return { lines, words, chars };
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ export class WhichCommand implements ShellCommand {
this.commands = commands;
}
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
if (args.length === 0) {
return createErrorResult(`${this.name}: missing operand`);
}
+1 -1
View File
@@ -10,7 +10,7 @@ export class WhoamiCommand implements ShellCommand {
description = 'Display current username';
usage = 'whoami';
async execute(args: string[], _cwd: string): Promise<ShellCommandResult> {
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
// whoami doesn't accept any arguments
if (args.length > 0) {
return createErrorResult(`${this.name}: extra operand '${args[0]}'`);
+42
View File
@@ -63,6 +63,48 @@ export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) {
command: 'unknown-command arg1 arg2'
});
console.log(unknownResult);
// Example 9: Compound commands with &&
console.log('\n--- Example 9: Compound commands with && ---');
const andResult = await shell.execute({
command: 'pwd && echo "Current directory listed above"'
});
console.log(andResult);
// Example 10: Compound commands with ||
console.log('\n--- Example 10: Compound commands with || ---');
const orResult = await shell.execute({
command: 'cat nonexistent.txt || echo "File not found, showing fallback message"'
});
console.log(orResult);
// Example 11: Sequential commands with ;
console.log('\n--- Example 11: Sequential commands with ; ---');
const sequentialResult = await shell.execute({
command: 'echo "First command"; echo "Second command"; pwd'
});
console.log(sequentialResult);
// Example 12: Pipe commands
console.log('\n--- Example 12: Pipe commands ---');
const pipeResult = await shell.execute({
command: 'echo "line1\nline2\nline3\nline4\nline5" | head -n 3'
});
console.log(pipeResult);
// Example 13: Complex pipe chain
console.log('\n--- Example 13: Complex pipe chain ---');
const complexPipeResult = await shell.execute({
command: 'echo "apple\nbanana\napple\ncherry\nbanana\napple" | sort | uniq'
});
console.log(complexPipeResult);
// Example 14: Mixed compound operators
console.log('\n--- Example 14: Mixed compound operators ---');
const mixedResult = await shell.execute({
command: 'echo "Processing..." && echo "data1\ndata2\ndata3" | wc -l && echo "Done!"'
});
console.log(mixedResult);
}
/**
+63 -1
View File
@@ -28,7 +28,7 @@ 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, diff, which, whoami, date, env, clear');
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, diff, which, whoami, date, env, clear. Supports compound commands with &&, ||, ;, and | operators');
expect(shellTool.inputSchema).toBeDefined();
});
@@ -160,4 +160,66 @@ describe('ShellTool', () => {
expect(result).toBe('(no output)');
expect(shellTool.getCurrentWorkingDirectory()).toBe('/test/dir/subdir');
});
describe('compound commands', () => {
it('should execute commands with && operator (success case)', async () => {
const result = await shellTool.execute({ command: 'pwd && echo hello' });
expect(result).toContain(testCwd);
expect(result).toContain('hello');
});
it('should execute commands with && operator (failure case)', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await shellTool.execute({ command: 'cat nonexistent.txt && echo should not run' });
expect(result).toContain('No such file or directory');
expect(result).not.toContain('should not run');
});
it('should execute commands with || operator (success case)', async () => {
const result = await shellTool.execute({ command: 'pwd || echo fallback' });
expect(result).toContain(testCwd);
expect(result).not.toContain('fallback');
});
it('should execute commands with || operator (failure case)', async () => {
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
const result = await shellTool.execute({ command: 'cat nonexistent.txt || echo fallback' });
expect(result).toContain('No such file or directory');
expect(result).toContain('fallback');
});
it('should execute commands with ; operator', async () => {
const result = await shellTool.execute({ command: 'echo first; echo second' });
expect(result).toContain('first');
expect(result).toContain('second');
});
it('should execute commands with pipe operator', async () => {
const result = await shellTool.execute({ command: 'echo "hello world" | cat' });
expect(result).toContain('hello world');
});
it('should handle complex compound commands', async () => {
const result = await shellTool.execute({ command: 'echo "line1\nline2\nline3" | head -n 2' });
expect(result).toContain('line1');
expect(result).toContain('line2');
expect(result).not.toContain('line3');
});
it('should parse quoted strings in compound commands', async () => {
const result = await shellTool.execute({ command: 'echo "hello && world" && echo success' });
expect(result).toContain('hello && world');
expect(result).toContain('success');
});
});
});
+224 -33
View File
@@ -42,11 +42,11 @@ export class ShellTool implements Tool<ShellToolParams> {
private cwd: string;
private commands: Map<string, ShellCommand>;
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, diff, which, whoami, date, env, clear";
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, diff, which, whoami, date, env, clear. Supports compound commands with &&, ||, ;, and | operators";
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"'
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "echo hello; echo world"'
),
});
@@ -129,6 +129,114 @@ export class ShellTool implements Tool<ShellToolParams> {
return { name, args };
}
/**
* 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
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;
}
/**
* 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 } = 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
};
}
try {
// Execute the command
const result = await command.execute(cmdArgs, this.cwd, input);
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<string> {
const { command: commandStr } = args;
@@ -136,53 +244,136 @@ export class ShellTool implements Tool<ShellToolParams> {
return "Error: Empty command";
}
const { name, args: cmdArgs } = this.parseCommand(commandStr);
// Parse compound commands
const commands = this.parseCompoundCommand(commandStr);
if (!name) {
if (commands.length === 0) {
return "Error: No command specified";
}
// Check if command exists
const command = this.commands.get(name);
if (!command) {
const availableCommands = Array.from(this.commands.keys()).join(', ');
return `Error: Command '${name}' not found\nAvailable commands: ${availableCommands}`;
// If it's a simple command (no operators), use the optimized single command execution
if (commands.length === 1) {
return this.executeSimpleCommand(commands[0].command);
}
try {
// Execute the command
const result = await command.execute(cmdArgs, this.cwd);
// Execute compound commands
return this.executeCompoundCommands(commands);
}
// Update working directory if command changed it (e.g., cd)
/**
* 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)';
}
/**
* 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;
}
// Format output
let output = '';
lastExitCode = result.exitCode;
if (result.stdout) {
output += result.stdout;
// 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 = '';
}
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)';
} catch (error) {
return `Error executing command '${name}': ${error instanceof Error ? error.message : 'Unknown error'}`;
}
// Handle final pipe output
if (pipeInput) {
outputs.push(pipeInput);
}
return outputs.length > 0 ? outputs.join('\n') : '(no output)';
}
/**
* Get the current working directory
*/