/** * Shell Command Tool Module - Built-in LLM tool for executing shell commands * * Features: * - Execute shell commands in child processes with parameter support * - Capture stdout and stderr output * - Persist command execution history (command, parameters, results, exceptions) * - Return results to LLM for further processing * - Error handling and exception tracking * - Long-running command support with 10-minute default timeout * - Trusted working-directory enforcement from world/tool context * - Explicit rejection when LLM-supplied directory conflicts with trusted working directory * - Graceful error handling for invalid tool calls * - Universal parameter validation for consistent execution * - Explicit execution safety configuration using structured metadata * * Implementation Details: * - Uses Node.js child_process.spawn for command execution * - Executes commands through shell for PATH resolution and shell features * - Stores execution history in-memory (can be extended to persistent storage) * - Provides MCP-compatible tool interface for LLM integration * - Timeout support to prevent hanging processes (default: 10 minutes) * - Resource cleanup on process completion * - Resolves command cwd from trusted world/tool context, not LLM args * - Rejects directory mismatch instead of silently overriding requested path * - Returns error results instead of throwing to prevent agent crashes * - Uses universal validation framework for consistent parameter checking * * Recent Changes: * - 2026-03-12: Shared tool approval flow now persists durable approval prompt/resolution messages for replay-safe shell approval history. * - 2026-03-12: Added `toolPermission` enforcement: 'read' level blocks execution with an error result; 'ask' level forces every invocation through HITL approval regardless of risk tier. * - 2026-03-06: Added explicit canonical failure reasons for shell validation/policy failures so approval denials and validation errors no longer masquerade as non-zero exits. * - 2026-03-06: Unified shell continuation output on one bounded-preview result contract, removed `smart`-mode branching, and stopped persisting a synthetic assistant stdout mirror message after shell completion. * - 2026-03-06: Added canonical shell error-result formatting helper so upstream tool persistence can normalize shell failures without falling back to ad hoc error strings. * - 2026-03-05: Hardened timeout termination to target process groups/process trees (SIGTERM + SIGKILL fallback) and removed child-process builtin timeout to keep timeout outcomes deterministic in the tool layer. * - 2026-03-05: Switched shell timeout grace config to shared reliability config helper. * - 2026-03-01: Prevented `./` and `../` parameter tokens from being misclassified as `/` so non-skill shell paths remain unchanged. * - 2026-02-28: Generalized skill-relative path fallback to work with any folder prefix, removing `scripts/`-specific behavior. * - 2026-02-28: Added skill-aware script path resolution so `/scripts/` parameters are auto-resolved to absolute paths under the skill root directory. * - 2026-02-28: Added deterministic shell risk tiering (`allow`/`hitl_required`/`block`) with per-call HITL approve/deny gating via shared `requestToolApproval` helper for high-risk in-scope commands. * - 2026-02-24: Required explicit chatId context for stdout/stderr streaming event emission to preserve chat isolation under strict frontend filtering. * - 2026-02-21: Streamed stderr via legacy `tool-stream` events while streaming stdout as assistant SSE; persisted only finalized stdout assistant message after execution completes. * - 2026-02-21: Added assistant-style SSE start/chunk/end streaming for shell runtime output so command chunks are delivered as assistant stream events instead of `tool-stream` messages. * - 2026-02-21: Added minimal LLM shell-result mode (`status` + `exit_code` semantics) for tool-call continuations, excluding stdout/stderr transcript bodies. * - 2026-02-15: Moved core cwd-boundary enforcement into `executeShellCommand` via optional `trustedWorkingDirectory` execution option. * - 2026-02-15: Added optional `output_format=json` for machine-readable command results. * - 2026-02-15: Added optional `artifact_paths` support with SHA-256 hashing and byte-size metadata for files within trusted scope. * - 2026-02-14: Default trusted cwd now falls back to shared core default working directory (user home by default) instead of `./` when world variable is unset. * - 2026-02-14: Added inline-script execution guard (e.g. `sh -c`, `node -e`) to prevent embedded path bypass outside trusted cwd. * - 2026-02-14: Hardened cwd containment checks by canonicalizing absolute paths and validating additional path argument forms (`./`, `../`, and `--flag=/path`). * - 2026-02-13: Updated directory-request validation to allow requested folders inside world working_directory and reject only outside paths. * - 2026-02-13: Added command/parameter path scope validation so shell_cmd rejects path targets outside trusted world working_directory. * - 2026-02-13: Added strict directory-mismatch guard for shell_cmd; mismatched LLM directory requests now fail with explicit error. * - 2026-02-13: Fixed validation error result typing by including `executionId` when formatting failed shell_cmd calls. * - 2026-02-13: Stopped trusting LLM-provided `directory`; shell commands now resolve working directory from trusted world/tool context only. * - 2026-02-13: Added explicit command-cancellation detection and AbortError propagation in tool execution to prevent post-stop continuation. * - 2026-02-13: Added chat-scoped shell process tracking and stop controls for Electron stop-message support. * - 2026-02-08: Added streaming callback support for real-time output * * Added onStdout and onStderr callbacks to executeShellCommand options * * Callbacks invoked in real-time as data arrives from child process * * Maintains backwards compatibility - callbacks are optional * * Full output still accumulated and returned in CommandExecutionResult * - 2026-02-06: Removed legacy manual tool-decision metadata * - 2025-11-11: CRITICAL FIX - Quote parameters for shell execution * * Parameters with spaces/tabs/newlines now properly quoted before spawn * * Prevents shell from splitting multi-word parameters * * Applied to both execution AND display formatting * - 2025-11-10: Fixed shell execution - enabled shell: true to support PATH resolution and installed commands * - Integrated universal parameter validation for consistent tool execution * - Enhanced validation to check required parameters and auto-correct types * - Replaced custom validation with standardized validation framework * - Added graceful error handling for empty commands to prevent agent crashes * - Changed validation to return error results instead of throwing exceptions * - Updated tests to expect error results rather than thrown errors * - Added LLM guidance to ask user for directory when not provided * - Made directory parameter required for shell command execution * - Increased default timeout from 30s to 10 minutes (600000ms) for long-running commands * - Initial implementation for shell_cmd LLM tool */ import { type ShellProcessExecutionRecord, type ShellProcessStatusEvent, type ListShellProcessExecutionsOptions, type CancelShellProcessResult, type DeleteShellProcessResult } from './shell-process-registry.js'; /** * Command execution result */ export interface CommandExecutionResult { executionId: string; command: string; parameters: string[]; stdout: string; stderr: string; exitCode: number | null; signal: string | null; error?: string; failureReason?: ShellFailureReason; canceled?: boolean; timedOut?: boolean; executedAt: Date; duration: number; } export interface CommandExecutionArtifact { path: string; sha256: string; bytes: number; } export interface StructuredCommandExecutionResult { exit_code: number | null; stdout: string; stderr: string; timed_out: boolean; duration_ms: number; artifacts: CommandExecutionArtifact[]; stdout_truncated?: boolean; stderr_truncated?: boolean; } export type ShellFailureReason = 'timeout' | 'canceled' | 'non_zero_exit' | 'execution_error' | 'validation_error' | 'approval_denied'; export interface MinimalShellLLMResult { status: 'success' | 'failed'; exit_code: number | null; timed_out: boolean; canceled: boolean; reason?: ShellFailureReason; } export interface PreviewShellLLMResult extends MinimalShellLLMResult { stdout_preview?: string; stderr_preview?: string; stdout_truncated?: boolean; stderr_truncated?: boolean; stdout_redacted?: boolean; stderr_redacted?: boolean; } export type ShellCommandRiskTier = 'allow' | 'hitl_required' | 'block'; export interface ShellCommandRiskAssessment { tier: ShellCommandRiskTier; reason: string; tags: string[]; } interface OutputFormattingOptions { detail?: 'minimal' | 'full'; maxOutputChars?: number; } export declare function resolveTrustedShellWorkingDirectory(context?: { world?: { variables?: string; }; workingDirectory?: string; }): string; export declare function validateShellDirectoryRequest(requestedDirectory: unknown, trustedWorkingDirectory: string): { valid: true; } | { valid: false; error: string; }; export declare function classifyShellCommandRisk(command: unknown, parameters: unknown): ShellCommandRiskAssessment; export declare function validateShellCommandScope(command: unknown, parameters: unknown, trustedWorkingDirectory: string, additionalTrustedRoots?: string[]): { valid: true; } | { valid: false; error: string; }; export declare function resolveSkillScriptParameters(parameters: string[], runtimeSkillsRoot?: string, options?: { allowBareScriptsResolution?: boolean; }): { resolvedParameters: string[]; skillRoots: string[]; }; export declare function stopShellCommandsForChat(worldId: string, chatId: string): { killed: number; }; export declare function isCommandExecutionCanceled(result: CommandExecutionResult): boolean; /** * Execute a shell command with parameters and capture output * * @param command - The shell command to execute (e.g., 'ls', 'echo', 'cat') * @param parameters - Array of parameters for the command (e.g., ['-la', '/tmp']) * @param directory - Working directory for command execution (required) * @param options - Execution options * @returns Promise - Execution result with output and metadata */ export declare function executeShellCommand(command: string, parameters: string[] | undefined, directory: string, options?: { timeout?: number; onStdout?: (data: string) => void; onStderr?: (data: string) => void; abortSignal?: AbortSignal; worldId?: string; chatId?: string; onStatusChange?: (event: ShellProcessStatusEvent) => void; trustedWorkingDirectory?: string; }): Promise; export interface DeleteExecutionHistoryResult { executionId: string; outcome: DeleteShellProcessResult['outcome']; removedHistoryEntries: number; } export declare function getProcessExecution(executionId: string): ShellProcessExecutionRecord | null; export declare function listProcessExecutions(options?: ListShellProcessExecutionsOptions): ShellProcessExecutionRecord[]; export declare function cancelProcessExecution(executionId: string): CancelShellProcessResult; export declare function deleteProcessExecution(executionId: string): DeleteExecutionHistoryResult; export declare function subscribeProcessExecutionStatus(listener: (event: ShellProcessStatusEvent) => void): () => void; export declare function clearProcessExecutionStateForTests(): { historyCleared: number; registryExecutionCount: number; registryActiveCount: number; }; /** * Get command execution history * * @param limit - Maximum number of results to return (default: 100) * @returns Array of command execution results, most recent first */ export declare function getExecutionHistory(limit?: number): CommandExecutionResult[]; /** * Clear execution history * Useful for testing or memory management * * @returns Number of entries cleared */ export declare function clearExecutionHistory(): number; export declare function formatStructuredResult(result: CommandExecutionResult, artifacts?: CommandExecutionArtifact[], options?: OutputFormattingOptions): StructuredCommandExecutionResult; export declare function formatMinimalShellResult(result: CommandExecutionResult): MinimalShellLLMResult; export declare function formatMinimalShellResultForLLM(result: CommandExecutionResult): string; /** * Strip ANSI escape sequences and terminal control characters from shell output * before sending to the LLM. Raw terminal output often contains spinner animations * (◒◐◓◑), cursor-control codes (\x1b[?25l, \x1b[999D\x1b[J), and ANSI color codes * that confuse LLMs into thinking a process is still running when it has already * completed successfully (exit_code: 0). * * Strips: * - CSI sequences: \x1b[ ... final-byte (colors, cursor movement, erase, etc.) * - OSC sequences: \x1b] ... \x07 or \x1b\ (terminal title/hyperlinks) * - DCS/SOS/PM/APC sequences: \x1bP/\x1bX/\x1b^/\x1b_ ... \x1b\ * - Single-char Fe escapes: \x1b followed by non-[ byte * - Bare carriage returns used by spinner overwrites */ export declare function stripAnsiFromShellOutput(text: string): string; export declare function formatPreviewShellResult(result: CommandExecutionResult, options?: { maxOutputChars?: number; }): PreviewShellLLMResult; export declare function formatPreviewShellResultForLLM(result: CommandExecutionResult, options?: { maxOutputChars?: number; }): string; export declare function formatShellToolErrorResultForLLM(options: { command?: unknown; parameters?: unknown; error: unknown; failureReason?: ShellFailureReason; }): string; export declare function formatShellToolErrorEnvelopeContent(options: { command?: unknown; parameters?: unknown; error: unknown; failureReason?: ShellFailureReason; toolCallId?: string; }): string; /** * Format command execution result for LLM consumption * Provides a human-readable summary of the execution with improved markdown formatting * * @param result - Command execution result * @returns Formatted markdown string suitable for LLM and display */ export declare function formatResultForLLM(result: CommandExecutionResult, options?: OutputFormattingOptions): string; /** * Create MCP-compatible tool definition for shell_cmd * This tool can be registered with the MCP system for LLM use * * @returns MCP tool definition object */ export declare function createShellCmdToolDefinition(): { description: string; parameters: { type: string; properties: { command: { type: string; description: string; }; parameters: { type: string; items: { type: string; }; description: string; }; directory: { type: string; description: string; }; timeout: { type: string; description: string; }; output_format: { type: string; enum: string[]; description: string; }; output_detail: { type: string; enum: string[]; description: string; }; artifact_paths: { type: string; items: { type: string; }; description: string; }; }; required: string[]; additionalProperties: boolean; }; execute: (args: any, sequenceId?: string, parentToolCall?: string, context?: any) => Promise; }; export {};