import type { ExecMode } from '../services/execution-core'; const MAX_SHELL_COMMAND_CHARS = 4096; const MAX_ARGV_ELEMENTS = 20; const MAX_ARGV_ELEMENT_CHARS = 1024; export function inferMode(command: unknown, mode: unknown): ExecMode | null { if (mode === 'shell' || mode === 'argv') return mode; if (typeof command === 'string') return 'shell'; if (Array.isArray(command)) return 'argv'; return null; } // Validates and normalizes an exec payload into an argv array. In shell mode the string // is wrapped as `sh -lc ` so the caller still runs argv-style against docker exec. export function parseExecCommand(command: unknown, mode: ExecMode): string[] | { error: string } { if (mode === 'shell') { if (typeof command !== 'string') { return { error: 'shell mode requires command to be a string' }; } if (!command.trim()) { return { error: 'command must not be empty' }; } if (command.length > MAX_SHELL_COMMAND_CHARS) { return { error: `Command too long (max ${MAX_SHELL_COMMAND_CHARS} chars)` }; } if (command.includes('\0')) { return { error: 'Command contains invalid characters' }; } return ['sh', '-lc', command]; } if (!Array.isArray(command) || !command.every((cmd: unknown) => typeof cmd === 'string')) { return { error: 'argv mode requires command to be an array of strings' }; } if (command.length === 0) { return { error: 'command must not be empty' }; } if (command.length > MAX_ARGV_ELEMENTS) { return { error: `Too many command elements (max ${MAX_ARGV_ELEMENTS})` }; } if (command.some((cmd: string) => cmd.length > MAX_ARGV_ELEMENT_CHARS)) { return { error: `Command element too long (max ${MAX_ARGV_ELEMENT_CHARS} chars)` }; } return command; } export function commandText(command: unknown): string { return Array.isArray(command) ? command.join(' ') : String(command); }