import { mkdir, readFile, writeFile } from "fs/promises"; import path from "path"; import { randomUUID } from "crypto"; export type ExecMode = "shell" | "argv"; export type ExecCommandKind = "read" | "search" | "list" | "mutate" | "destructive"; export type ExecRisk = "low" | "medium" | "high" | "critical"; export type PersistedExecOutput = { ref: string; command: string; mode: ExecMode; workdir?: string; stdout: string; stderr: string; exitCode: number; createdAt: string; }; export type ExecAnalysis = { mode: ExecMode; commandText: string; summary: string; kind: ExecCommandKind; risk: ExecRisk; noOutputExpected: boolean; normalizedPrefix?: string; semanticMessage?: string; semanticSuccess: boolean; }; const OUTPUT_DIR = "/tmp/aether-exec-results"; const SUMMARY_MAX_LENGTH = 96; const SEARCH_COMMANDS = new Set(["find", "grep", "rg", "ag", "ack", "locate", "which", "whereis"]); const READ_COMMANDS = new Set([ "cat", "head", "tail", "less", "more", "wc", "stat", "file", "strings", "jq", "awk", "cut", "sort", "uniq", "tr", "git", ]); const LIST_COMMANDS = new Set(["ls", "tree", "du"]); const NEUTRAL_COMMANDS = new Set(["echo", "printf", "true", "false", ":"]); const SILENT_COMMANDS = new Set([ "mv", "cp", "rm", "mkdir", "rmdir", "chmod", "chown", "chgrp", "touch", "ln", "cd", "export", "unset", "wait", ]); const DESTRUCTIVE_COMMANDS = new Set([ "rm", "rmdir", "dd", "mkfs", "fdisk", "parted", "shutdown", "reboot", "halt", ]); const HIGH_RISK_COMMANDS = new Set([ "npm", "pnpm", "yarn", "pip", "apk", "apt", "apt-get", "brew", "curl", "wget", "git", "docker", "go", "cargo", "make", "node", "python", "python3", "bun", ]); function truncate(text: string, max = SUMMARY_MAX_LENGTH): string { return text.length > max ? `${text.slice(0, max - 3)}...` : text; } function splitCommand(command: string): string[] { return command .split(/\s*(?:\|\||&&|;|\|)\s*/g) .map((part) => part.trim()) .filter(Boolean); } function tokenize(command: string): string[] { return command.trim().split(/\s+/).filter(Boolean); } function isEnvAssignment(token: string): boolean { return /^[A-Za-z_][A-Za-z0-9_]*=/.test(token); } function extractBaseCommand(command: string): string { const tokens = tokenize(command); let index = 0; while (index < tokens.length && isEnvAssignment(tokens[index]!)) { index += 1; } return tokens[index] || ""; } function extractSignificantCommands(commandText: string): string[] { const parts = splitCommand(commandText); const commands: string[] = []; for (const part of parts) { const baseCommand = extractBaseCommand(part); if (!baseCommand || NEUTRAL_COMMANDS.has(baseCommand)) { continue; } commands.push(baseCommand); } return commands; } function classifyCommandKind(commandText: string): ExecCommandKind { const commands = extractSignificantCommands(commandText); if (commands.length === 0) { return "read"; } if (commands.some((command) => DESTRUCTIVE_COMMANDS.has(command))) { return "destructive"; } const allInspectOnly = commands.every((command) => SEARCH_COMMANDS.has(command) || READ_COMMANDS.has(command) || LIST_COMMANDS.has(command), ); if (allInspectOnly) { if (commands.some((command) => SEARCH_COMMANDS.has(command))) { return "search"; } if (commands.some((command) => LIST_COMMANDS.has(command))) { return "list"; } return "read"; } return "mutate"; } function classifyRisk(commandText: string, kind: ExecCommandKind): ExecRisk { if (kind === "destructive") { return "critical"; } if (kind === "read" || kind === "search" || kind === "list") { return "low"; } const commands = extractSignificantCommands(commandText); return commands.some((command) => HIGH_RISK_COMMANDS.has(command)) ? "high" : "medium"; } function isSilentCommand(commandText: string): boolean { const commands = extractSignificantCommands(commandText); return commands.length > 0 && commands.every((command) => SILENT_COMMANDS.has(command)); } function normalizedPrefix(commandText: string): string | undefined { const parts = splitCommand(commandText); const first = parts[0]; if (!first) { return undefined; } const tokens = tokenize(first); let index = 0; while (index < tokens.length && isEnvAssignment(tokens[index]!)) { index += 1; } const base = tokens[index]; if (!base) { return undefined; } const subcommand = tokens[index + 1]; if (subcommand && /^[a-z][a-z0-9-]*$/.test(subcommand) && !subcommand.startsWith("-")) { return `${base} ${subcommand}`; } return base; } // Translates raw exit codes into semantic success for commands where non-zero isn't a failure // (e.g. grep exit 1 means "no matches", not an error). function semanticOutcome(commandText: string, exitCode: number): { semanticSuccess: boolean; semanticMessage?: string } { const commands = extractSignificantCommands(commandText); const lastCommand = commands[commands.length - 1]; if (!lastCommand) { return { semanticSuccess: exitCode === 0 }; } switch (lastCommand) { case "grep": case "rg": return { semanticSuccess: exitCode < 2, semanticMessage: exitCode === 1 ? "No matches found" : undefined, }; case "find": return { semanticSuccess: exitCode < 2, semanticMessage: exitCode === 1 ? "Some directories were inaccessible" : undefined, }; case "diff": return { semanticSuccess: exitCode < 2, semanticMessage: exitCode === 1 ? "Files differ" : undefined, }; case "test": case "[": return { semanticSuccess: exitCode < 2, semanticMessage: exitCode === 1 ? "Condition is false" : undefined, }; default: return { semanticSuccess: exitCode === 0 }; } } export function commandToText(mode: ExecMode, command: string | string[]): string { if (mode === "shell") { return typeof command === "string" ? command : command.join(" "); } if (Array.isArray(command)) { return command.join(" "); } return command; } // Classifies a command (kind, risk, expected-silence, semantic outcome) so callers can // gate execution, choose UI framing, and interpret exit codes correctly. export function analyzeExecCommand( mode: ExecMode, command: string | string[], exitCode = 0, ): ExecAnalysis { const commandText = commandToText(mode, command); const kind = classifyCommandKind(commandText); const risk = classifyRisk(commandText, kind); const noOutputExpected = isSilentCommand(commandText); const semantic = semanticOutcome(commandText, exitCode); return { mode, commandText, summary: truncate(commandText), kind, risk, noOutputExpected, normalizedPrefix: normalizedPrefix(commandText), semanticMessage: semantic.semanticMessage, semanticSuccess: semantic.semanticSuccess, }; } export async function persistExecOutput( payload: Omit, ): Promise { const ref = randomUUID(); await mkdir(OUTPUT_DIR, { recursive: true }); const fullPayload: PersistedExecOutput = { ref, createdAt: new Date().toISOString(), ...payload, }; await writeFile(path.join(OUTPUT_DIR, `${ref}.json`), JSON.stringify(fullPayload), "utf8"); return ref; } export async function readPersistedExecOutput(ref: string): Promise { if (!/^[a-f0-9-]+$/i.test(ref)) { throw new Error("Invalid persisted output ref"); } const raw = await readFile(path.join(OUTPUT_DIR, `${ref}.json`), "utf8"); return JSON.parse(raw) as PersistedExecOutput; } // Writes oversized stdout/stderr to disk and returns a ref, so huge command outputs don't // blow up the HTTP response. Callers fetch the full output later via readPersistedExecOutput. export async function maybePersistLargeOutput(args: { mode: ExecMode; command: string | string[]; workdir?: string; stdout: string; stderr: string; exitCode: number; maxBytes: number; }): Promise<{ stdout: string; stderr: string; truncated: boolean; persistedOutputRef?: string; }> { const { mode, command, workdir, stdout, stderr, exitCode, maxBytes } = args; const truncatedStdout = stdout.length > maxBytes; const truncatedStderr = stderr.length > maxBytes; const truncated = truncatedStdout || truncatedStderr; if (!truncated) { return { stdout, stderr, truncated: false }; } const persistedOutputRef = await persistExecOutput({ command: commandToText(mode, command), mode, workdir, stdout, stderr, exitCode, }); return { stdout: truncatedStdout ? `${stdout.slice(0, maxBytes)}\n...[truncated]` : stdout, stderr: truncatedStderr ? `${stderr.slice(0, maxBytes)}\n...[truncated]` : stderr, truncated: true, persistedOutputRef, }; }