From 4039e1e3550e70dffe13b3b5be32d8b223e04aa1 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 11 Sep 2025 20:54:11 -0500 Subject: [PATCH] Enhance ShellTool with &&, ||, |, etc --- src/lib/commands/ShellCommand.ts | 15 +- src/lib/commands/cat.ts | 11 +- src/lib/commands/cd.ts | 2 +- src/lib/commands/clear.ts | 2 +- src/lib/commands/cp.ts | 4 +- src/lib/commands/cut.ts | 21 ++- src/lib/commands/date.ts | 2 +- src/lib/commands/diff.ts | 2 +- src/lib/commands/echo.ts | 2 +- src/lib/commands/env.ts | 2 +- src/lib/commands/find.ts | 2 +- src/lib/commands/grep.ts | 74 ++++++--- src/lib/commands/head.ts | 25 ++- src/lib/commands/ls.ts | 20 +-- src/lib/commands/mkdir.ts | 16 +- src/lib/commands/mv.ts | 2 +- src/lib/commands/pwd.ts | 2 +- src/lib/commands/rm.ts | 8 +- src/lib/commands/sort.ts | 15 +- src/lib/commands/tail.ts | 27 ++- src/lib/commands/touch.ts | 16 +- src/lib/commands/tr.ts | 15 +- src/lib/commands/uniq.ts | 13 +- src/lib/commands/wc.ts | 25 ++- src/lib/commands/which.ts | 2 +- src/lib/commands/whoami.ts | 2 +- src/lib/tools/ShellTool.example.ts | 42 +++++ src/lib/tools/ShellTool.test.ts | 64 ++++++- src/lib/tools/ShellTool.ts | 257 +++++++++++++++++++++++++---- 29 files changed, 539 insertions(+), 151 deletions(-) diff --git a/src/lib/commands/ShellCommand.ts b/src/lib/commands/ShellCommand.ts index 118a2f21..52c34404 100644 --- a/src/lib/commands/ShellCommand.ts +++ b/src/lib/commands/ShellCommand.ts @@ -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; + execute(args: string[], cwd: string, input?: string): Promise; } /** @@ -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; } diff --git a/src/lib/commands/cat.ts b/src/lib/commands/cat.ts index fb165152..eb409072 100644 --- a/src/lib/commands/cat.ts +++ b/src/lib/commands/cat.ts @@ -18,7 +18,12 @@ export class CatCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { + // 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`); } diff --git a/src/lib/commands/cd.ts b/src/lib/commands/cd.ts index 989c105e..19dbbd44 100644 --- a/src/lib/commands/cd.ts +++ b/src/lib/commands/cd.ts @@ -18,7 +18,7 @@ export class CdCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { try { let targetPath: string; diff --git a/src/lib/commands/clear.ts b/src/lib/commands/clear.ts index 8d6a3fdc..9f3ce7bd 100644 --- a/src/lib/commands/clear.ts +++ b/src/lib/commands/clear.ts @@ -10,7 +10,7 @@ export class ClearCommand implements ShellCommand { description = 'Clear terminal screen'; usage = 'clear'; - async execute(args: string[], _cwd: string): Promise { + async execute(args: string[], _cwd: string, _input?: string): Promise { // clear doesn't accept any arguments if (args.length > 0) { return createErrorResult(`${this.name}: arguments not supported`); diff --git a/src/lib/commands/cp.ts b/src/lib/commands/cp.ts index b723a3ae..ef3793e7 100644 --- a/src/lib/commands/cp.ts +++ b/src/lib/commands/cp.ts @@ -18,7 +18,7 @@ export class CpCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { 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 { diff --git a/src/lib/commands/cut.ts b/src/lib/commands/cut.ts index 80235af3..cfd537be 100644 --- a/src/lib/commands/cut.ts +++ b/src/lib/commands/cut.ts @@ -18,7 +18,7 @@ export class CutCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 diff --git a/src/lib/commands/date.ts b/src/lib/commands/date.ts index b7e24936..c0a63890 100644 --- a/src/lib/commands/date.ts +++ b/src/lib/commands/date.ts @@ -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 { + async execute(args: string[], _cwd: string, _input?: string): Promise { try { const now = new Date(); diff --git a/src/lib/commands/diff.ts b/src/lib/commands/diff.ts index 4eb4f723..a3d0fef0 100644 --- a/src/lib/commands/diff.ts +++ b/src/lib/commands/diff.ts @@ -18,7 +18,7 @@ export class DiffCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { try { const { options, files } = this.parseArgs(args); diff --git a/src/lib/commands/echo.ts b/src/lib/commands/echo.ts index c2855615..a47f939d 100644 --- a/src/lib/commands/echo.ts +++ b/src/lib/commands/echo.ts @@ -10,7 +10,7 @@ export class EchoCommand implements ShellCommand { description = 'Display text'; usage = 'echo [text...]'; - async execute(args: string[], _cwd: string): Promise { + async execute(args: string[], _cwd: string, _input?: string): Promise { // Join all arguments with spaces, like real echo const output = args.join(' '); diff --git a/src/lib/commands/env.ts b/src/lib/commands/env.ts index 7fac3092..aae5b3c9 100644 --- a/src/lib/commands/env.ts +++ b/src/lib/commands/env.ts @@ -10,7 +10,7 @@ export class EnvCommand implements ShellCommand { description = 'Display environment variables'; usage = 'env'; - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { // env doesn't accept arguments in this simple implementation if (args.length > 0) { return createErrorResult(`${this.name}: arguments not supported in this implementation`); diff --git a/src/lib/commands/find.ts b/src/lib/commands/find.ts index 3e68e579..da461167 100644 --- a/src/lib/commands/find.ts +++ b/src/lib/commands/find.ts @@ -18,7 +18,7 @@ export class FindCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { const { paths, options } = this.parseArgs(args); const searchPaths = paths.length > 0 ? paths : ['.']; // Default to current directory diff --git a/src/lib/commands/grep.ts b/src/lib/commands/grep.ts index 31253085..3298f7cf 100644 --- a/src/lib/commands/grep.ts +++ b/src/lib/commands/grep.ts @@ -18,24 +18,56 @@ export class GrepCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 { @@ -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++; } diff --git a/src/lib/commands/head.ts b/src/lib/commands/head.ts index 2b71483a..b3821c48 100644 --- a/src/lib/commands/head.ts +++ b/src/lib/commands/head.ts @@ -18,8 +18,17 @@ export class HeadCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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++; } diff --git a/src/lib/commands/ls.ts b/src/lib/commands/ls.ts index fac6001d..58bff599 100644 --- a/src/lib/commands/ls.ts +++ b/src/lib/commands/ls.ts @@ -18,7 +18,7 @@ export class LsCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { 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(' ')); diff --git a/src/lib/commands/mkdir.ts b/src/lib/commands/mkdir.ts index 3f5cb107..458dc534 100644 --- a/src/lib/commands/mkdir.ts +++ b/src/lib/commands/mkdir.ts @@ -18,7 +18,7 @@ export class MkdirCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { 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 { diff --git a/src/lib/commands/mv.ts b/src/lib/commands/mv.ts index 910afa08..b7f9de4f 100644 --- a/src/lib/commands/mv.ts +++ b/src/lib/commands/mv.ts @@ -18,7 +18,7 @@ export class MvCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { if (args.length < 2) { return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`); } diff --git a/src/lib/commands/pwd.ts b/src/lib/commands/pwd.ts index 5d062b8e..fa835825 100644 --- a/src/lib/commands/pwd.ts +++ b/src/lib/commands/pwd.ts @@ -10,7 +10,7 @@ export class PwdCommand implements ShellCommand { description = 'Print working directory'; usage = 'pwd'; - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { // pwd doesn't accept any arguments in standard Linux if (args.length > 0) { return createErrorResult(`${this.name}: too many arguments`); diff --git a/src/lib/commands/rm.ts b/src/lib/commands/rm.ts index cc49d285..d4d35a35 100644 --- a/src/lib/commands/rm.ts +++ b/src/lib/commands/rm.ts @@ -18,7 +18,7 @@ export class RmCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { 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 { diff --git a/src/lib/commands/sort.ts b/src/lib/commands/sort.ts index 5966bcd7..c32adad7 100644 --- a/src/lib/commands/sort.ts +++ b/src/lib/commands/sort.ts @@ -18,18 +18,20 @@ export class SortCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 diff --git a/src/lib/commands/tail.ts b/src/lib/commands/tail.ts index b115cb95..5ed16c9c 100644 --- a/src/lib/commands/tail.ts +++ b/src/lib/commands/tail.ts @@ -18,8 +18,17 @@ export class TailCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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++; } diff --git a/src/lib/commands/touch.ts b/src/lib/commands/touch.ts index ea65c796..6d854149 100644 --- a/src/lib/commands/touch.ts +++ b/src/lib/commands/touch.ts @@ -18,7 +18,7 @@ export class TouchCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, _input?: string): Promise { 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 { diff --git a/src/lib/commands/tr.ts b/src/lib/commands/tr.ts index 5a010117..05210b07 100644 --- a/src/lib/commands/tr.ts +++ b/src/lib/commands/tr.ts @@ -18,7 +18,7 @@ export class TrCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 diff --git a/src/lib/commands/uniq.ts b/src/lib/commands/uniq.ts index 9c65a9cf..5a9146ac 100644 --- a/src/lib/commands/uniq.ts +++ b/src/lib/commands/uniq.ts @@ -18,17 +18,19 @@ export class UniqCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 diff --git a/src/lib/commands/wc.ts b/src/lib/commands/wc.ts index 2b9be9c5..62434ec8 100644 --- a/src/lib/commands/wc.ts +++ b/src/lib/commands/wc.ts @@ -18,9 +18,8 @@ export class WcCommand implements ShellCommand { this.fs = fs; } - async execute(args: string[], cwd: string): Promise { + async execute(args: string[], cwd: string, input?: string): Promise { 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 }; + } } \ No newline at end of file diff --git a/src/lib/commands/which.ts b/src/lib/commands/which.ts index 14f43b8b..337ef7c2 100644 --- a/src/lib/commands/which.ts +++ b/src/lib/commands/which.ts @@ -16,7 +16,7 @@ export class WhichCommand implements ShellCommand { this.commands = commands; } - async execute(args: string[], _cwd: string): Promise { + async execute(args: string[], _cwd: string, _input?: string): Promise { if (args.length === 0) { return createErrorResult(`${this.name}: missing operand`); } diff --git a/src/lib/commands/whoami.ts b/src/lib/commands/whoami.ts index d24d2fea..80e2944b 100644 --- a/src/lib/commands/whoami.ts +++ b/src/lib/commands/whoami.ts @@ -10,7 +10,7 @@ export class WhoamiCommand implements ShellCommand { description = 'Display current username'; usage = 'whoami'; - async execute(args: string[], _cwd: string): Promise { + async execute(args: string[], _cwd: string, _input?: string): Promise { // whoami doesn't accept any arguments if (args.length > 0) { return createErrorResult(`${this.name}: extra operand '${args[0]}'`); diff --git a/src/lib/tools/ShellTool.example.ts b/src/lib/tools/ShellTool.example.ts index 39c82394..984a459c 100644 --- a/src/lib/tools/ShellTool.example.ts +++ b/src/lib/tools/ShellTool.example.ts @@ -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); } /** diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 65a8084e..b9897e2a 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -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'); + }); + }); }); \ No newline at end of file diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index 0571c8d3..7cf6e4dc 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -42,11 +42,11 @@ export class ShellTool implements Tool { private cwd: string; private commands: Map; - 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 { 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 { const { command: commandStr } = args; @@ -136,53 +244,136 @@ export class ShellTool implements Tool { 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 { + 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 { + 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 */