mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add virtual shell command
This commit is contained in:
9 files changed
+807
-4
No files matched your search
@@ -7,15 +7,11 @@ import { Send, Square, Loader2, ChevronDown } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
|
||||
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
import { TextEditorStrReplaceTool } from '@/lib/tools/TextEditorStrReplaceTool';
|
||||
@@ -31,6 +27,7 @@ import { NostrReadTagTool } from '@/lib/tools/NostrReadTagTool';
|
||||
import { NostrReadProtocolTool } from '@/lib/tools/NostrReadProtocolTool';
|
||||
import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
@@ -102,6 +99,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_protocol: new NostrReadProtocolTool(),
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(browserFS, cwd),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# Shell Commands
|
||||
|
||||
This directory contains pure TypeScript implementations of basic shell commands that can be executed through the `ShellTool`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### ShellCommand Interface
|
||||
|
||||
All commands implement the `ShellCommand` interface which defines:
|
||||
|
||||
- `name`: The command name (e.g., 'cat', 'ls', 'cd')
|
||||
- `description`: Brief description of what the command does
|
||||
- `usage`: Usage syntax for the command
|
||||
- `execute(args, cwd)`: Executes the command and returns a `ShellCommandResult`
|
||||
|
||||
### ShellCommandResult
|
||||
|
||||
Commands return a `ShellCommandResult` object containing:
|
||||
|
||||
- `exitCode`: 0 for success, non-zero for error
|
||||
- `stdout`: Standard output content
|
||||
- `stderr`: Standard error content
|
||||
- `newCwd`: Optional new working directory (for commands like 'cd')
|
||||
|
||||
## Available Commands
|
||||
|
||||
### cat
|
||||
|
||||
**Usage:** `cat [file...]`
|
||||
|
||||
Concatenate and display file contents. Supports multiple files which will be concatenated in order.
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
cat file.txt # Display single file
|
||||
cat file1.txt file2.txt # Concatenate multiple files
|
||||
```
|
||||
|
||||
**Features:**
|
||||
- Reads and displays file contents
|
||||
- Supports multiple files (concatenated output)
|
||||
- Proper error handling for missing files, directories, and permission issues
|
||||
- Rejects absolute paths for security
|
||||
|
||||
## Planned Commands
|
||||
|
||||
The following commands are planned for future implementation:
|
||||
|
||||
- **ls**: List directory contents
|
||||
- **cd**: Change directory
|
||||
- **pwd**: Print working directory
|
||||
- **rm**: Remove files and directories
|
||||
- **cp**: Copy files and directories
|
||||
- **mv**: Move/rename files and directories
|
||||
|
||||
## Usage with ShellTool
|
||||
|
||||
Commands are executed through the `ShellTool` which handles:
|
||||
|
||||
- Command parsing (including quoted arguments)
|
||||
- Command registration and lookup
|
||||
- Working directory management
|
||||
- Error formatting and output handling
|
||||
|
||||
```typescript
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
|
||||
// Create shell tool with filesystem and working directory
|
||||
const shell = new ShellTool(fs, '/project/root');
|
||||
|
||||
// Execute commands
|
||||
const result = await shell.execute({ command: 'cat package.json' });
|
||||
console.log(result); // File contents or error message
|
||||
```
|
||||
|
||||
## Adding New Commands
|
||||
|
||||
To add a new command:
|
||||
|
||||
1. Create a new file in this directory (e.g., `ls.ts`)
|
||||
2. Implement the `ShellCommand` interface
|
||||
3. Register the command in `ShellTool.ts` constructor
|
||||
4. Add exports to `index.ts`
|
||||
5. Write tests for the command
|
||||
|
||||
Example command structure:
|
||||
|
||||
```typescript
|
||||
import type { ShellCommand, ShellCommandResult } from './ShellCommand';
|
||||
import { createSuccessResult, createErrorResult } from './ShellCommand';
|
||||
|
||||
export class MyCommand implements ShellCommand {
|
||||
name = 'mycommand';
|
||||
description = 'Description of what the command does';
|
||||
usage = 'mycommand [options] [args]';
|
||||
|
||||
constructor(private fs: JSRuntimeFS) {}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
// Implementation here
|
||||
return createSuccessResult('output');
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Interface for shell command implementations
|
||||
*/
|
||||
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
|
||||
* @returns Promise resolving to the command output or error message
|
||||
*/
|
||||
execute(args: string[], cwd: string): Promise<ShellCommandResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of executing a shell command
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a successful command result
|
||||
*/
|
||||
export function createSuccessResult(stdout: string, newCwd?: string): ShellCommandResult {
|
||||
return {
|
||||
exitCode: 0,
|
||||
stdout,
|
||||
stderr: '',
|
||||
newCwd,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an error command result
|
||||
*/
|
||||
export function createErrorResult(stderr: string, exitCode: number = 1): ShellCommandResult {
|
||||
return {
|
||||
exitCode,
|
||||
stdout: '',
|
||||
stderr,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { CatCommand } from './cat';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('CatCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let catCommand: CatCommand;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
catCommand = new CatCommand(mockFS);
|
||||
});
|
||||
|
||||
it('should have correct command properties', () => {
|
||||
expect(catCommand.name).toBe('cat');
|
||||
expect(catCommand.description).toBe('Concatenate and display file contents');
|
||||
expect(catCommand.usage).toBe('cat [file...]');
|
||||
});
|
||||
|
||||
it('should return error when no arguments provided', async () => {
|
||||
const result = await catCommand.execute([], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing file operand');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should read and return file content', async () => {
|
||||
const fileContent = 'Hello, World!';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
|
||||
|
||||
const result = await catCommand.execute(['test.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(fileContent);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8');
|
||||
});
|
||||
|
||||
it('should concatenate multiple files', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockResolvedValueOnce('File 1 content\n')
|
||||
.mockResolvedValueOnce('File 2 content\n');
|
||||
|
||||
const result = await catCommand.execute(['file1.txt', 'file2.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('File 1 content\nFile 2 content\n');
|
||||
expect(result.stderr).toBe('');
|
||||
});
|
||||
|
||||
it('should return error for directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await catCommand.execute(['somedir'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should return error for non-existent file', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await catCommand.execute(['nonexistent.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await catCommand.execute(['/absolute/path.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle permission errors', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('EACCES: permission denied'));
|
||||
|
||||
const result = await catCommand.execute(['restricted.txt'], testCwd);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Permission denied');
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { join } from "@std/path";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'cat' command
|
||||
* Concatenate and display file contents
|
||||
*/
|
||||
export class CatCommand implements ShellCommand {
|
||||
name = 'cat';
|
||||
description = 'Concatenate and display file contents';
|
||||
usage = 'cat [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
// If no arguments provided, show usage
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const outputs: string[] = [];
|
||||
|
||||
for (const filePath of args) {
|
||||
try {
|
||||
// Handle absolute paths
|
||||
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
|
||||
return createErrorResult(`${this.name}: absolute paths are not supported: ${filePath}`);
|
||||
}
|
||||
|
||||
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`);
|
||||
}
|
||||
|
||||
// Read file content
|
||||
const content = await this.fs.readFile(absolutePath, 'utf8');
|
||||
outputs.push(content);
|
||||
|
||||
} catch (error) {
|
||||
// Handle file not found or permission errors
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Join all file contents
|
||||
const result = outputs.join('');
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { type ShellCommand, type ShellCommandResult, createSuccessResult, createErrorResult } from './ShellCommand';
|
||||
export { CatCommand } from './cat';
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* Example usage of the ShellTool
|
||||
*
|
||||
* This file demonstrates how to use the ShellTool to execute shell commands
|
||||
* in your application. The ShellTool provides a safe, sandboxed environment
|
||||
* for running basic file operations.
|
||||
*/
|
||||
|
||||
import { ShellTool } from './ShellTool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
/**
|
||||
* Example function showing how to use ShellTool
|
||||
*/
|
||||
export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) {
|
||||
// Create a shell tool instance
|
||||
const shell = new ShellTool(fs, projectRoot);
|
||||
|
||||
console.log('Available commands:', shell.getAvailableCommands());
|
||||
console.log('Current directory:', shell.getCurrentWorkingDirectory());
|
||||
|
||||
// Example 1: Display a file
|
||||
console.log('\n--- Example 1: Display package.json ---');
|
||||
const catResult = await shell.execute({ command: 'cat package.json' });
|
||||
console.log(catResult);
|
||||
|
||||
// Example 2: Try to display multiple files
|
||||
console.log('\n--- Example 2: Display multiple files ---');
|
||||
const multiFileResult = await shell.execute({
|
||||
command: 'cat package.json README.md'
|
||||
});
|
||||
console.log(multiFileResult);
|
||||
|
||||
// Example 3: Handle errors gracefully
|
||||
console.log('\n--- Example 3: Handle non-existent file ---');
|
||||
const errorResult = await shell.execute({
|
||||
command: 'cat nonexistent-file.txt'
|
||||
});
|
||||
console.log(errorResult);
|
||||
|
||||
// Example 4: Handle quoted filenames with spaces
|
||||
console.log('\n--- Example 4: Quoted filename ---');
|
||||
const quotedResult = await shell.execute({
|
||||
command: 'cat "file with spaces.txt"'
|
||||
});
|
||||
console.log(quotedResult);
|
||||
|
||||
// Example 5: Try unknown command
|
||||
console.log('\n--- Example 5: Unknown command ---');
|
||||
const unknownResult = await shell.execute({
|
||||
command: 'unknown-command arg1 arg2'
|
||||
});
|
||||
console.log(unknownResult);
|
||||
}
|
||||
|
||||
/**
|
||||
* Example React hook for using ShellTool
|
||||
*/
|
||||
export function useShell(fs: JSRuntimeFS, cwd: string) {
|
||||
const shell = new ShellTool(fs, cwd);
|
||||
|
||||
const executeCommand = async (command: string): Promise<string> => {
|
||||
try {
|
||||
return await shell.execute({ command });
|
||||
} catch (error) {
|
||||
return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
executeCommand,
|
||||
getCurrentDirectory: () => shell.getCurrentWorkingDirectory(),
|
||||
setCurrentDirectory: (newCwd: string) => shell.setCurrentWorkingDirectory(newCwd),
|
||||
getAvailableCommands: () => shell.getAvailableCommands(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Example integration with AI tools
|
||||
* Shows how the ShellTool can be used as part of an AI assistant
|
||||
*/
|
||||
export class AIShellIntegration {
|
||||
private shell: ShellTool;
|
||||
|
||||
constructor(fs: JSRuntimeFS, projectRoot: string) {
|
||||
this.shell = new ShellTool(fs, projectRoot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process natural language requests and convert to shell commands
|
||||
*/
|
||||
async processNaturalLanguageRequest(request: string): Promise<string> {
|
||||
const lowerRequest = request.toLowerCase();
|
||||
|
||||
// Simple pattern matching for demonstration
|
||||
if (lowerRequest.includes('show me') && lowerRequest.includes('file')) {
|
||||
// Extract filename from request
|
||||
const fileMatch = request.match(/file\s+["']?([^"'\s]+)["']?/i);
|
||||
if (fileMatch) {
|
||||
const filename = fileMatch[1];
|
||||
return await this.shell.execute({ command: `cat ${filename}` });
|
||||
}
|
||||
}
|
||||
|
||||
if (lowerRequest.includes('list') && lowerRequest.includes('command')) {
|
||||
const commands = this.shell.getAvailableCommands();
|
||||
return commands.map(cmd => `${cmd.name}: ${cmd.description}`).join('\n');
|
||||
}
|
||||
|
||||
if (lowerRequest.includes('current') && lowerRequest.includes('directory')) {
|
||||
return `Current directory: ${this.shell.getCurrentWorkingDirectory()}`;
|
||||
}
|
||||
|
||||
return 'I can help you with file operations. Try asking me to "show me a file" or "list available commands".';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Example CLI-like interface
|
||||
*/
|
||||
export class SimpleCLI {
|
||||
private shell: ShellTool;
|
||||
private history: string[] = [];
|
||||
|
||||
constructor(fs: JSRuntimeFS, projectRoot: string) {
|
||||
this.shell = new ShellTool(fs, projectRoot);
|
||||
}
|
||||
|
||||
async executeCommand(command: string): Promise<string> {
|
||||
this.history.push(command);
|
||||
|
||||
// Handle built-in commands
|
||||
if (command.trim() === 'help') {
|
||||
const commands = this.shell.getAvailableCommands();
|
||||
return [
|
||||
'Available commands:',
|
||||
...commands.map(cmd => ` ${cmd.usage} - ${cmd.description}`),
|
||||
'',
|
||||
'Built-in commands:',
|
||||
' help - Show this help message',
|
||||
' history - Show command history',
|
||||
' pwd - Show current directory',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
if (command.trim() === 'history') {
|
||||
return this.history.map((cmd, i) => `${i + 1}: ${cmd}`).join('\n');
|
||||
}
|
||||
|
||||
if (command.trim() === 'pwd') {
|
||||
return this.shell.getCurrentWorkingDirectory();
|
||||
}
|
||||
|
||||
// Execute through shell tool
|
||||
return await this.shell.execute({ command });
|
||||
}
|
||||
|
||||
getHistory(): string[] {
|
||||
return [...this.history];
|
||||
}
|
||||
|
||||
clearHistory(): void {
|
||||
this.history = [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { ShellTool } from './ShellTool';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('ShellTool', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let shellTool: ShellTool;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
shellTool = new ShellTool(mockFS, testCwd);
|
||||
});
|
||||
|
||||
it('should have correct tool properties', () => {
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv');
|
||||
expect(shellTool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
it('should return error for empty command', async () => {
|
||||
const result = await shellTool.execute({ command: '' });
|
||||
expect(result).toBe('Error: Empty command');
|
||||
});
|
||||
|
||||
it('should return error for whitespace-only command', async () => {
|
||||
const result = await shellTool.execute({ command: ' ' });
|
||||
expect(result).toBe('Error: Empty command');
|
||||
});
|
||||
|
||||
it('should return error for unknown command', async () => {
|
||||
const result = await shellTool.execute({ command: 'unknowncommand' });
|
||||
expect(result).toContain("Command 'unknowncommand' not found");
|
||||
expect(result).toContain('Available commands: cat');
|
||||
});
|
||||
|
||||
it('should execute cat command successfully', async () => {
|
||||
const fileContent = 'Hello, World!';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(fileContent);
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat test.txt' });
|
||||
|
||||
expect(result).toBe(fileContent);
|
||||
});
|
||||
|
||||
it('should parse commands with arguments correctly', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockResolvedValueOnce('File 1\n')
|
||||
.mockResolvedValueOnce('File 2\n');
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat file1.txt file2.txt' });
|
||||
|
||||
expect(result).toBe('File 1\nFile 2\n');
|
||||
});
|
||||
|
||||
it('should handle quoted arguments', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('Content');
|
||||
|
||||
await shellTool.execute({ command: 'cat "file with spaces.txt"' });
|
||||
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/file with spaces.txt', 'utf8');
|
||||
});
|
||||
|
||||
it('should return current working directory', () => {
|
||||
expect(shellTool.getCurrentWorkingDirectory()).toBe(testCwd);
|
||||
});
|
||||
|
||||
it('should allow setting working directory', () => {
|
||||
const newCwd = '/new/dir';
|
||||
shellTool.setCurrentWorkingDirectory(newCwd);
|
||||
expect(shellTool.getCurrentWorkingDirectory()).toBe(newCwd);
|
||||
});
|
||||
|
||||
it('should return available commands', () => {
|
||||
const commands = shellTool.getAvailableCommands();
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toEqual({
|
||||
name: 'cat',
|
||||
description: 'Concatenate and display file contents',
|
||||
usage: 'cat [file...]',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle command errors gracefully', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await shellTool.execute({ command: 'cat nonexistent.txt' });
|
||||
|
||||
expect(result).toContain('No such file or directory');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
});
|
||||
|
||||
it('should show stderr output', async () => {
|
||||
const result = await shellTool.execute({ command: 'cat' });
|
||||
|
||||
expect(result).toContain('missing file operand');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
import { z } from "zod";
|
||||
import type { Tool } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand } from "../commands/ShellCommand";
|
||||
import { CatCommand } from "../commands/cat";
|
||||
|
||||
interface ShellToolParams {
|
||||
command: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shell tool that provides a command-line interface for basic file operations
|
||||
*/
|
||||
export class ShellTool implements Tool<ShellToolParams> {
|
||||
private fs: JSRuntimeFS;
|
||||
private cwd: string;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv";
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
command: z.string().describe(
|
||||
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd"'
|
||||
),
|
||||
});
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string) {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
this.commands = new Map();
|
||||
|
||||
// Register available commands
|
||||
this.registerCommand(new CatCommand(fs));
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a shell command
|
||||
*/
|
||||
private registerCommand(command: ShellCommand): void {
|
||||
this.commands.set(command.name, command);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a command string into command name and arguments
|
||||
*/
|
||||
private parseCommand(commandStr: string): { name: string; args: string[] } {
|
||||
// Simple parsing - split by spaces, respecting quoted strings
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
let quoteChar = '';
|
||||
|
||||
for (let i = 0; i < commandStr.length; i++) {
|
||||
const char = commandStr[i];
|
||||
|
||||
if (!inQuotes && (char === '"' || char === "'")) {
|
||||
inQuotes = true;
|
||||
quoteChar = char;
|
||||
} else if (inQuotes && char === quoteChar) {
|
||||
inQuotes = false;
|
||||
quoteChar = '';
|
||||
} else if (!inQuotes && char === ' ') {
|
||||
if (current.trim()) {
|
||||
parts.push(current.trim());
|
||||
current = '';
|
||||
}
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
|
||||
if (current.trim()) {
|
||||
parts.push(current.trim());
|
||||
}
|
||||
|
||||
const [name = '', ...args] = parts;
|
||||
return { name, args };
|
||||
}
|
||||
|
||||
async execute(args: ShellToolParams): Promise<string> {
|
||||
const { command: commandStr } = args;
|
||||
|
||||
if (!commandStr.trim()) {
|
||||
return "Error: Empty command";
|
||||
}
|
||||
|
||||
const { name, args: cmdArgs } = this.parseCommand(commandStr);
|
||||
|
||||
if (!name) {
|
||||
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}`;
|
||||
}
|
||||
|
||||
try {
|
||||
// Execute the command
|
||||
const result = await command.execute(cmdArgs, this.cwd);
|
||||
|
||||
// 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)';
|
||||
|
||||
} catch (error) {
|
||||
return `Error executing command '${name}': ${error instanceof Error ? error.message : 'Unknown error'}`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current working directory
|
||||
*/
|
||||
getCurrentWorkingDirectory(): string {
|
||||
return this.cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the current working directory
|
||||
*/
|
||||
setCurrentWorkingDirectory(newCwd: string): void {
|
||||
this.cwd = newCwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get list of available commands
|
||||
*/
|
||||
getAvailableCommands(): Array<{ name: string; description: string; usage: string }> {
|
||||
return Array.from(this.commands.values()).map(cmd => ({
|
||||
name: cmd.name,
|
||||
description: cmd.description,
|
||||
usage: cmd.usage,
|
||||
}));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user