Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351import { 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<PersistedExecOutput, "ref" | "createdAt">,): Promise<string> { 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<PersistedExecOutput> { 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, };}