import * as path from "node:path"; import { isUsableDirectory } from "@/helpers/usable-directory"; import { getCurrentWorkingDirectory } from "@/runtime-context"; import { resolveForegroundYieldMs } from "@/tools/foreground-yield"; import { captureSecretRedactions, createSecretStreamScrubber, type SecretStreamScrubber, scrubSecretsFromString, } from "@/tools/secret-substitution"; import { addToMessageQueue } from "@/utils/message-queue-bridge.js"; import { formatTaskNotification, type NotificationScope, resolveNotificationScope, } from "@/utils/task-notifications.js"; import { noteExpectedWorktreeForLauncher } from "@/websocket/listener/worktree-ownership"; import { appendToOutputFile, assertBackgroundProcessCapacity, backgroundProcesses, createBackgroundOutputFile, getNextExecSessionId, notifyBackgroundProcessStateChanged, scheduleBackgroundProcessCleanup, scrubCompletedBackgroundOutput, } from "./process_manager.js"; import { getShellEnv } from "./shell-env.js"; import { buildPowerShellCommand, buildShellLaunchers, selectAvailableShellLauncher, } from "./shell-launchers.js"; import { type RunningShellProcess, ShellExecutionError, type ShellProcessHandle, startShellProcess, } from "./shell-runner.js"; import { applyShellSandbox } from "./shell-sandbox.js"; import { LIMITS, truncateByChars } from "./truncation.js"; import { validateRequiredParams } from "./validation.js"; import { assertSafeWindowsCommand } from "./windows-command-safety.js"; const DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250; const MIN_YIELD_TIME_MS = 250; const MIN_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 5_000; const MAX_YIELD_TIME_MS = 30_000; const MAX_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 300_000; const DEFAULT_MAX_OUTPUT_TOKENS = 10_000; const MAX_INLINE_OUTPUT_CHARS = LIMITS.BASH_OUTPUT_CHARS; const MAX_SESSION_OUTPUT_CHARS = 1_000_000; const EXEC_SESSION_CLEANUP_MS = 5 * 60 * 1000; const INTERRUPT = "\u0003"; interface ExecCommandArgs { cmd: string; description?: string; workdir?: string; shell?: string; tty?: boolean; yield_time_ms?: number; max_output_tokens?: number; login?: boolean; // Upstream Codex also exposes sandbox-escalation fields here: // sandbox_permissions, justification, prefix_rule, additional_permissions. // Letta Code intentionally omits them from the model-facing schema because // this harness has no Codex sandbox override / permission-profile layer; // the regular Letta Code approval system still gates command execution. signal?: AbortSignal; onOutput?: (chunk: string, stream: "stdout" | "stderr") => void; secretEnv?: Record; variableEnv?: Record; parentScope?: { agentId: string; conversationId: string }; } interface WriteStdinArgs { session_id: number | string; chars?: string; yield_time_ms?: number; max_output_tokens?: number; signal?: AbortSignal; onOutput?: (chunk: string, stream: "stdout" | "stderr") => void; } interface ExecCommandResult { status?: "error"; output: string; } type ExecSessionStatus = "running" | "completed" | "failed"; interface ExecSession { id: string; command: string; description?: string; output: string; outputFile: string; chunks: ExecOutputChunk[]; readOffset: number; status: ExecSessionStatus; exitCode: number | null; terminationSignal?: string | number | null; tty: boolean; secrets: Readonly>; streamScrubbers: { stdout: SecretStreamScrubber; stderr: SecretStreamScrubber; }; notificationScope?: NotificationScope; notificationArmed: boolean; completionDelivered: boolean; activeWriteStdinCalls: number; completionDetail?: string; outputWriteFailed?: boolean; cleanupTimer?: ReturnType; } type ExecOutputChunk = { text: string; stream: "stdout" | "stderr"; start: number; end: number; }; const execSessions = new Map(); function createAbortError(): Error { const error = new Error("The operation was aborted"); error.name = "AbortError"; return error; } function throwIfAborted(signal: AbortSignal | undefined): void { if (signal?.aborted) { throw createAbortError(); } } function sleep(ms: number, signal?: AbortSignal): Promise { if (!signal) { return new Promise((resolve) => setTimeout(resolve, ms)); } throwIfAborted(signal); return new Promise((resolve, reject) => { const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); resolve(); }, ms); const onAbort = () => { clearTimeout(timer); signal.removeEventListener("abort", onAbort); reject(createAbortError()); }; signal.addEventListener("abort", onAbort, { once: true }); }); } function clampYieldTime(value: number | undefined, fallback: number): number { const time = Number.isFinite(value) ? Number(value) : fallback; return Math.max(MIN_YIELD_TIME_MS, Math.min(time, MAX_YIELD_TIME_MS)); } function clampWriteStdinYieldTime( value: number | undefined, input: string, ): number { const time = Math.max( MIN_YIELD_TIME_MS, Number.isFinite(value) ? Number(value) : DEFAULT_WRITE_STDIN_YIELD_TIME_MS, ); if (input.length === 0) { return Math.max( MIN_EMPTY_WRITE_STDIN_YIELD_TIME_MS, Math.min(time, MAX_EMPTY_WRITE_STDIN_YIELD_TIME_MS), ); } return Math.min(time, MAX_YIELD_TIME_MS); } function estimateTokenCount(text: string): number { return Math.ceil(Buffer.byteLength(text, "utf8") / 4); } function maxCharsForTokens(maxOutputTokens?: number): number { const maxTokens = maxOutputTokens && maxOutputTokens > 0 ? maxOutputTokens : DEFAULT_MAX_OUTPUT_TOKENS; return Math.min(Math.max(1, maxTokens * 4), MAX_INLINE_OUTPUT_CHARS); } function truncateOutput( text: string, maxOutputTokens: number | undefined, secrets: Readonly>, ): string { return truncateByChars( scrubSecretsFromString(text, secrets), maxCharsForTokens(maxOutputTokens), "exec_command", { workingDirectory: getCurrentWorkingDirectory(), secrets, }, ).content; } function appendSessionOutput( session: ExecSession, text: string, stream: "stdout" | "stderr", ): void { const start = session.output.length; session.output += text; const end = session.output.length; session.chunks.push({ text, stream, start, end }); if (session.output.length <= MAX_SESSION_OUTPUT_CHARS) { return; } const removedChars = session.output.length - MAX_SESSION_OUTPUT_CHARS; session.output = session.output.slice(removedChars); session.readOffset = Math.max(0, session.readOffset - removedChars); session.chunks = session.chunks .map((chunk) => ({ ...chunk, start: chunk.start - removedChars, end: chunk.end - removedChars, })) .filter((chunk) => chunk.end > 0) .map((chunk) => { if (chunk.start >= 0) { return chunk; } return { ...chunk, text: chunk.text.slice(-chunk.end), start: 0, }; }); } function getSessionOutputChunks( session: ExecSession, startOffset: number, endOffset: number, ): ExecOutputChunk[] { const chunks: ExecOutputChunk[] = []; for (const chunk of session.chunks) { if (chunk.end <= startOffset || chunk.start >= endOffset) { continue; } const sliceStart = Math.max(0, startOffset - chunk.start); const sliceEnd = Math.min(chunk.text.length, endOffset - chunk.start); const text = chunk.text.slice(sliceStart, sliceEnd); if (text) { chunks.push({ text, stream: chunk.stream, start: Math.max(chunk.start, startOffset), end: Math.min(chunk.end, endOffset), }); } } return chunks; } function scheduleExecSessionCleanup(sessionId: string): void { const session = execSessions.get(sessionId); if (!session || session.status === "running") { return; } if (session.cleanupTimer) { clearTimeout(session.cleanupTimer); } session.cleanupTimer = setTimeout(() => { const current = execSessions.get(sessionId); if (current === session && current.status !== "running") { execSessions.delete(sessionId); } }, EXEC_SESSION_CLEANUP_MS); if ( typeof session.cleanupTimer === "object" && "unref" in session.cleanupTimer ) { session.cleanupTimer.unref(); } } function releaseExecSession(session: ExecSession): void { if (session.cleanupTimer) { clearTimeout(session.cleanupTimer); session.cleanupTimer = undefined; } execSessions.delete(session.id); } function formatExecOutput(params: { chunkId: string; wallTimeMs: number; exitCode: number | null; sessionId: string | null; terminationSignal?: string | number | null; output: string; originalTokenCount: number; maxOutputTokens?: number; secrets: Readonly>; }): string { const sections = [ `Chunk ID: ${params.chunkId}`, `Wall time: ${(params.wallTimeMs / 1000).toFixed(4)} seconds`, ]; if (params.exitCode !== null) { sections.push(`Process exited with code ${params.exitCode}`); } if (params.exitCode === null && params.sessionId === null) { const signal = params.terminationSignal ? ` (${params.terminationSignal})` : ""; sections.push( `Command was terminated${signal}; it may not have completed.`, ); } if (params.sessionId !== null) { sections.push(`Process running with session ID ${params.sessionId}`); sections.push( "You will be notified when the process completes. Do not poll unless you need the output before continuing.", ); } sections.push(`Original token count: ${params.originalTokenCount}`); sections.push("Output:"); sections.push( truncateOutput(params.output, params.maxOutputTokens, params.secrets), ); return sections.join("\n"); } function generateChunkId(): string { return Array.from({ length: 6 }, () => Math.floor(Math.random() * 16).toString(16), ).join(""); } function shellCommandFlag(shellName: string, login: boolean): string { if (!login) return "-c"; const normalized = shellName.replace(/\\/g, "/").toLowerCase(); if (normalized.includes("bash") || normalized.includes("zsh")) { return "-lc"; } return "-c"; } function isPowerShell(shell: string): boolean { const normalized = shell.replace(/\\/g, "/").toLowerCase(); return normalized.includes("powershell") || normalized.includes("pwsh"); } function isCmd(shell: string): boolean { const normalized = shell.replace(/\\/g, "/").toLowerCase(); return normalized.endsWith("cmd.exe") || normalized.endsWith("/cmd"); } function buildExplicitShellLauncher( shell: string, cmd: string, login: boolean, envAliases?: string[], ): string[] { if (process.platform === "win32") { if (isPowerShell(shell)) { return [ shell, "-NoProfile", "-Command", buildPowerShellCommand(cmd, envAliases), ]; } if (isCmd(shell)) { return [shell, "/d", "/s", "/c", cmd]; } } return [shell, shellCommandFlag(shell, login), cmd]; } function buildExecLaunchers(args: ExecCommandArgs): string[][] { const login = args.login ?? true; const envAliases = args.secretEnv || args.variableEnv ? Object.keys({ ...args.variableEnv, ...args.secretEnv }) : undefined; if (!args.shell?.trim() || isPowerShell(args.shell)) { assertSafeWindowsCommand(args.cmd, { cwd: resolveShellWorkdir(args.workdir), env: { ...getShellEnv(), ...args.variableEnv, ...args.secretEnv }, }); } if (args.shell?.trim()) { return [ buildExplicitShellLauncher( args.shell.trim(), args.cmd, login, envAliases, ), ]; } return buildShellLaunchers(args.cmd, { login, powershellEnvAliases: envAliases, }); } function createSessionOutputAppender(params: { session: ExecSession; outputFile: string; }): (text: string, stream: "stdout" | "stderr") => void { return (text: string, stream: "stdout" | "stderr") => { // The per-stream scrubber holds back potential partial secret matches so // a credential split across output chunks stays redacted in the session // buffer and the output file. const sanitizedText = params.session.streamScrubbers[stream].push(text); if (!sanitizedText) return; appendSessionOutput(params.session, sanitizedText, stream); const wrote = appendToOutputFile(params.outputFile, sanitizedText); if (!wrote && params.session.status === "running") { params.session.outputWriteFailed = true; appendSessionOutput( params.session, "\n[output file write failed; output may be incomplete]\n", "stderr", ); markSessionFailed( params.session, "Output file write failed; output may be incomplete", ); const bgProc = backgroundProcesses.get(params.session.id); if (bgProc) { try { bgProc.process.kill("SIGTERM"); } catch { // Process may have already exited. } } } }; } function notifyExecCompletion(session: ExecSession): void { if ( !session.notificationArmed || session.completionDelivered || session.activeWriteStdinCalls > 0 ) { return; } const backgroundProcess = backgroundProcesses.get(session.id); if (backgroundProcess?.completionNotificationSuppressed) { session.completionDelivered = true; return; } session.completionDelivered = true; const status = session.status === "completed" ? "completed" : "failed"; const unreadOutput = session.output.slice(session.readOffset) || "(no new output)"; const { content: result } = truncateByChars( scrubSecretsFromString( [ `$ ${session.command}`, `Session ID: ${session.id}`, session.completionDetail, unreadOutput, ] .filter(Boolean) .join("\n\n"), session.secrets, ), LIMITS.BASH_NOTIFICATION_CHARS, "exec_command", { useMiddleTruncation: true }, ); const durationMs = backgroundProcess?.startTime ? Math.max(0, Date.now() - backgroundProcess.startTime.getTime()) : undefined; addToMessageQueue({ kind: "task_notification", text: formatTaskNotification({ taskId: `exec_${session.id}`, status, summary: `Exec command "${session.description?.trim() || session.command}" ${status}`, result, outputFile: session.outputFile, usage: durationMs === undefined ? undefined : { durationMs }, }), ...session.notificationScope, }); } /** * Emit any bytes the stream scrubbers held back as potential partial secret * matches. The process's completion promise settles after its final output * events, so on session close/fail this is the last chance to route the * remainder into the same sinks as ordinary output. */ function flushSessionStreamScrubbers(session: ExecSession): void { for (const stream of ["stdout", "stderr"] as const) { const rest = session.streamScrubbers[stream].flush(); if (!rest) continue; appendSessionOutput(session, rest, stream); appendToOutputFile(session.outputFile, rest); } } function markSessionFailed(session: ExecSession, detail: string): void { if (session.status !== "running") return; flushSessionStreamScrubbers(session); session.status = "failed"; session.completionDetail = detail; const bgProcess = backgroundProcesses.get(session.id); if (bgProcess) { bgProcess.status = "failed"; scrubCompletedBackgroundOutput(bgProcess); scheduleBackgroundProcessCleanup(session.id); } notifyExecCompletion(session); // Publish even when the notification was suppressed or deferred. if (bgProcess) notifyBackgroundProcessStateChanged(bgProcess.runtimeScope); scheduleExecSessionCleanup(session.id); } function markSessionClosed( session: ExecSession, code: number | null, signal?: string | number | null, ): void { if (session.status !== "running") return; flushSessionStreamScrubbers(session); session.status = code === 0 && !session.outputWriteFailed ? "completed" : "failed"; session.exitCode = code; session.terminationSignal = signal; session.completionDetail = code === null ? "Terminated by signal before exiting" : `Exit code: ${code}`; const bgProcess = backgroundProcesses.get(session.id); if (bgProcess) { bgProcess.status = session.status; bgProcess.exitCode = code; scrubCompletedBackgroundOutput(bgProcess); scheduleBackgroundProcessCleanup(session.id); } notifyExecCompletion(session); // Publish even when the notification was suppressed or deferred. if (bgProcess) notifyBackgroundProcessStateChanged(bgProcess.runtimeScope); scheduleExecSessionCleanup(session.id); } async function waitForSessionOutput(params: { session: ExecSession; startOffset: number; yieldTimeMs: number; signal?: AbortSignal; onOutput?: (chunk: string, stream: "stdout" | "stderr") => void; }): Promise<{ output: string; wallTimeMs: number }> { const startTime = Date.now(); const deadline = startTime + params.yieldTimeMs; let emittedOffset = params.startOffset; throwIfAborted(params.signal); while (Date.now() < deadline && params.session.status === "running") { if (params.onOutput && params.session.output.length > emittedOffset) { for (const chunk of getSessionOutputChunks( params.session, emittedOffset, params.session.output.length, )) { params.onOutput(chunk.text, chunk.stream); } emittedOffset = params.session.output.length; } await sleep(25, params.signal); } throwIfAborted(params.signal); if (params.onOutput && params.session.output.length > emittedOffset) { for (const chunk of getSessionOutputChunks( params.session, emittedOffset, params.session.output.length, )) { params.onOutput(chunk.text, chunk.stream); } } const endOffset = params.session.output.length; const output = params.session.output.slice(params.startOffset, endOffset); params.session.readOffset = endOffset; return { output, wallTimeMs: Date.now() - startTime }; } function resolveShellWorkdir(workdir?: string): string { const defaultCwd = getCurrentWorkingDirectory(); const requestedCwd = workdir ? path.isAbsolute(workdir) ? workdir : path.resolve(defaultCwd, workdir) : defaultCwd; return isUsableDirectory(requestedCwd) ? requestedCwd : defaultCwd; } async function startExecSession(args: ExecCommandArgs): Promise { assertBackgroundProcessCapacity(); const id = getNextExecSessionId(); const outputFile = createBackgroundOutputFile(`exec_${id}`); const cwd = resolveShellWorkdir(args.workdir); const env = { ...getShellEnv(), ...args.variableEnv, ...args.secretEnv }; const redactions = captureSecretRedactions( args.parentScope?.agentId, args.secretEnv ?? {}, ); const launchers = buildExecLaunchers(args); const rawLauncher = selectAvailableShellLauncher(launchers, env); if (!rawLauncher) { throw new Error("Command must be a non-empty string"); } // Confine the session (pipe or PTY) under the cross-agent shell sandbox. // The spawn helpers re-note the launcher for worktree ownership, but the // wrapper hides the inner shell from that inspection, so note the unwrapped // launcher here first. const sandboxed = applyShellSandbox(rawLauncher, cwd, env); if (sandboxed.backend) { noteExpectedWorktreeForLauncher(rawLauncher, cwd); } const launcher = sandboxed.launcher; const spawnEnv = sandboxed.env; const session: ExecSession = { id, command: args.cmd, description: args.description, output: "", outputFile, chunks: [], readOffset: 0, status: "running", exitCode: null, tty: args.tty ?? false, secrets: redactions, streamScrubbers: { stdout: createSecretStreamScrubber(redactions), stderr: createSecretStreamScrubber(redactions), }, notificationScope: resolveNotificationScope(args.parentScope), notificationArmed: false, completionDelivered: false, activeWriteStdinCalls: 0, }; execSessions.set(id, session); const appendOutput = createSessionOutputAppender({ session, outputFile, }); let runningProcess: RunningShellProcess; try { runningProcess = startShellProcess(launcher, { cwd, env: spawnEnv, timeoutMs: 0, sourceCommand: args.cmd, signal: args.signal, tty: session.tty, captureOutput: false, onOutput: appendOutput, }); } catch (error) { execSessions.delete(id); throw error; } backgroundProcesses.set(id, { process: runningProcess.process, completion: runningProcess.completion, terminate: runningProcess.terminate, command: args.cmd, status: session.status, exitCode: session.exitCode, startTime: new Date(), outputFile, runtimeScope: args.parentScope, secrets: session.secrets, }); if (session.status !== "running") { try { runningProcess.process.kill("SIGTERM"); } catch { // Process may have already exited. } scheduleBackgroundProcessCleanup(id); } void runningProcess.completion.then( ({ exitCode, signal }) => markSessionClosed(session, exitCode, signal), (error: unknown) => { if (error instanceof ShellExecutionError) { appendOutput(error.message, "stderr"); } markSessionFailed( session, `Error: ${error instanceof Error ? error.message : String(error)}`, ); }, ); return session; } export async function exec_command( args: ExecCommandArgs, ): Promise { validateRequiredParams(args, ["cmd"], "exec_command"); if (!args.cmd || typeof args.cmd !== "string") { throw new Error("cmd must be a non-empty string"); } const session = await startExecSession(args); const yieldTimeMs = clampYieldTime( args.yield_time_ms, resolveForegroundYieldMs(), ); const { output, wallTimeMs } = await waitForSessionOutput({ session, startOffset: 0, yieldTimeMs, signal: args.signal, onOutput: args.onOutput, }); const sessionId = session.status === "running" ? session.id : null; if (sessionId !== null) { session.notificationArmed = true; } const formattedOutput = formatExecOutput({ chunkId: generateChunkId(), wallTimeMs, exitCode: session.exitCode, terminationSignal: session.terminationSignal, sessionId, output, originalTokenCount: estimateTokenCount(output), maxOutputTokens: args.max_output_tokens, secrets: session.secrets, }); if (sessionId === null) { releaseExecSession(session); } return { ...(session.status !== "running" && session.exitCode === null ? { status: "error" as const } : {}), output: scrubSecretsFromString(formattedOutput, session.secrets), }; } export async function write_stdin( args: WriteStdinArgs, ): Promise { validateRequiredParams(args, ["session_id"], "write_stdin"); const sessionId = String(args.session_id); const session = execSessions.get(sessionId); const backgroundProcess = backgroundProcesses.get(sessionId); if (!session || !backgroundProcess) { throw new Error(`Unknown process id ${sessionId}`); } const chars = args.chars ?? ""; if (chars && !session.tty) { if (chars === INTERRUPT) { (backgroundProcess.process as ShellProcessHandle).interrupt(); } else { throw new Error( "stdin is closed for this session; rerun exec_command with tty=true to keep stdin open", ); } } session.activeWriteStdinCalls++; let output: string; let wallTimeMs: number; let waitCompleted = false; try { if (chars && session.tty) { (backgroundProcess.process as ShellProcessHandle).write(chars); await sleep(100, args.signal); } const startOffset = session.readOffset; const yieldTimeMs = clampWriteStdinYieldTime(args.yield_time_ms, chars); ({ output, wallTimeMs } = await waitForSessionOutput({ session, startOffset, yieldTimeMs, signal: args.signal, onOutput: args.onOutput, })); waitCompleted = true; } finally { session.activeWriteStdinCalls--; if (session.status !== "running") { if (waitCompleted) { session.completionDelivered = true; } else { notifyExecCompletion(session); } } } const nextSessionId = session.status === "running" ? session.id : null; const formattedOutput = formatExecOutput({ chunkId: generateChunkId(), wallTimeMs, exitCode: session.exitCode, terminationSignal: session.terminationSignal, sessionId: nextSessionId, output, originalTokenCount: estimateTokenCount(output), maxOutputTokens: args.max_output_tokens, secrets: session.secrets, }); if (nextSessionId === null) { releaseExecSession(session); } return { ...(session.status !== "running" && session.exitCode === null ? { status: "error" as const } : {}), output: scrubSecretsFromString(formattedOutput, session.secrets), }; } export function __clearExecSessionsForTests(): void { for (const session of execSessions.values()) { if (session.cleanupTimer) { clearTimeout(session.cleanupTimer); } } execSessions.clear(); } export function __getExecSessionForTests( sessionId: string, ): ExecSession | undefined { return execSessions.get(sessionId); }