UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

349 lines • 12.9 kB
/** * Bash command execution with streaming support and cancellation. * * This module provides a unified bash execution implementation used by: * - AgentSession.executeBash() for interactive and RPC modes * - Direct calls from modes that need bash execution */ import { randomBytes } from "node:crypto"; import { createWriteStream } from "node:fs"; import { rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { stripAnsi } from "../utils/ansi.js"; import { sanitizeBinaryOutput } from "../utils/shell.js"; import { SecretOutputRedactor } from "./tools/secret-output-redactor.js"; import { DEFAULT_MAX_BYTES, truncateTail } from "./tools/truncate.js"; const NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS = 5_000; // ============================================================================ // Implementation // ============================================================================ /** * Execute a bash command using custom BashOperations. * Used for remote execution (SSH, containers, etc.). */ export async function executeBashWithOperations(command, cwd, operations, options) { const outputChunks = []; const callbackAbortController = new AbortController(); const executionSignal = options?.signal ? AbortSignal.any([options.signal, callbackAbortController.signal]) : callbackAbortController.signal; let callbackError; let hasCallbackError = false; let callbacksAbandoned = false; const callbackPromises = new Set(); const waitForCallbacks = async (allowAbandonment) => { if (callbackPromises.size === 0) return true; const settled = Promise.allSettled([...callbackPromises]).then(() => true); let timeout; const bounded = new Promise((resolve) => { timeout = setTimeout(resolve, allowAbandonment ? 100 : NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS, false); timeout.unref?.(); }); try { return await Promise.race([settled, bounded]); } finally { if (timeout) clearTimeout(timeout); } }; let outputChunkStart = 0; let outputBytes = 0; const maxOutputBytes = DEFAULT_MAX_BYTES * 2; let tempFilePath; let tempFileStream; let tempFileError; let totalBytes = 0; const compactOutputChunks = () => { if (outputChunkStart < 64) { return; } outputChunks.splice(0, outputChunkStart); outputChunkStart = 0; }; const outputText = () => outputChunks.slice(outputChunkStart).join(""); const ensureTempFile = () => { if (tempFilePath) { return; } const id = randomBytes(8).toString("hex"); tempFilePath = join(tmpdir(), `pi-bash-${id}.log`); tempFileStream = createWriteStream(tempFilePath); tempFileStream.on("error", (error) => { tempFileError ??= error; }); for (let i = outputChunkStart; i < outputChunks.length; i++) { const chunk = outputChunks[i]; if (chunk !== undefined) { tempFileStream.write(chunk); } } }; const closeTempFileStream = async () => { const stream = tempFileStream; tempFileStream = undefined; if (!stream) { return; } if (tempFileError) { await new Promise((resolve) => { if (stream.closed) { resolve(); return; } stream.once("close", resolve); stream.destroy(); }); throw tempFileError; } await new Promise((resolve, reject) => { let finished = false; let closed = false; let streamError; const settle = () => { if (!closed) { return; } stream.off("finish", onFinish); stream.off("error", onError); stream.off("close", onClose); if (streamError) { reject(streamError); } else if (finished) { resolve(); } else { reject(new Error("Bash spill stream closed before finish")); } }; const onError = (error) => { streamError ??= error; }; const onFinish = () => { finished = true; }; const onClose = () => { closed = true; if (!finished && !stream.destroyed) { stream.destroy(); } settle(); }; stream.once("error", onError); stream.once("finish", onFinish); stream.once("close", onClose); stream.end(); }); }; const removeTempFile = async () => { if (!tempFilePath) { return; } const path = tempFilePath; await rm(path, { force: true }); tempFilePath = undefined; }; const closeTempFileAndCleanup = async (primaryError) => { let finalError = primaryError; try { await closeTempFileStream(); } catch (closeError) { finalError = new AggregateError([primaryError, closeError], "Bash output cleanup failed"); } try { await removeTempFile(); } catch (unlinkError) { finalError = new AggregateError([finalError, unlinkError], "Bash output cleanup failed"); } throw finalError; }; const decoder = new TextDecoder(); const streams = options?.redactSecretsInOutput === true ? new Map() : undefined; const appendText = (decoded, byteLength = Buffer.byteLength(decoded)) => { if (callbackAbortController.signal.aborted) return; totalBytes += byteLength; // Sanitize: strip ANSI, replace binary garbage, normalize newlines const text = sanitizeBinaryOutput(stripAnsi(decoded)).replace(/\r/g, ""); // Start writing to temp file if exceeds threshold if (totalBytes > DEFAULT_MAX_BYTES) { ensureTempFile(); } if (tempFileStream) { tempFileStream.write(text); } outputChunks.push(text); outputBytes += text.length; while (outputBytes > maxOutputBytes && outputChunkStart < outputChunks.length - 1) { const removed = outputChunks[outputChunkStart]; if (removed === undefined) { break; } outputBytes -= removed.length; outputChunkStart++; } compactOutputChunks(); // Stream to callback if (options?.onChunk) { try { const callbackResult = options.onChunk(text); if (callbackResult && typeof callbackResult.then === "function") { const callbackPromise = Promise.resolve(callbackResult).then(() => undefined, (error) => { if (!hasCallbackError) { callbackError = error; hasCallbackError = true; } if (callbacksAbandoned) { process.emitWarning(`Bash output callback rejected after the command timeout: ${error instanceof Error ? error.message : String(error)}`, { code: "BASH_CALLBACK_ERROR" }); } callbackAbortController.abort(); throw error; }); callbackPromises.add(callbackPromise); void callbackPromise.catch(() => { }).finally(() => callbackPromises.delete(callbackPromise)); return callbackPromise; } } catch (error) { if (!hasCallbackError) { callbackError = error; hasCallbackError = true; } callbackAbortController.abort(); throw error; } } }; const onData = (data, stream = "stdout") => { if (!streams) return appendText(decoder.decode(data, { stream: true }), data.length); let state = streams.get(stream); if (!state) { state = { decoder: new TextDecoder(), redactor: new SecretOutputRedactor() }; streams.set(stream, state); } const text = state.redactor.push(state.decoder.decode(data, { stream: true })); if (text) return appendText(text); }; let outputFinished = false; const finishDecoder = () => { if (outputFinished) return; outputFinished = true; if (streams) { for (const state of streams.values()) { const text = state.redactor.push(state.decoder.decode()) + state.redactor.finish(); if (text) appendText(text); } } else { const finalText = decoder.decode(); if (finalText.length > 0) appendText(finalText); } }; const prepareFinalOutput = async () => { try { finishDecoder(); const fullOutput = outputText(); const truncationResult = truncateTail(fullOutput); if (truncationResult.truncated) { ensureTempFile(); } return { fullOutput, truncationResult }; } catch (error) { return await closeTempFileAndCleanup(error); } }; let result; try { result = await operations.exec(command, cwd, { onData, signal: executionSignal, redactSecretsInOutput: options?.redactSecretsInOutput === true, ...(options?.env === undefined ? {} : { env: options.env }), }); } catch (err) { if (options?.signal?.aborted && !hasCallbackError) { try { finishDecoder(); } catch (error) { return await closeTempFileAndCleanup(error); } } await waitForCallbacks(options?.signal?.aborted === true); // Check if it was an abort if (hasCallbackError) { return await closeTempFileAndCleanup(callbackError); } if (options?.signal?.aborted) { const { fullOutput, truncationResult } = await prepareFinalOutput(); try { await closeTempFileStream(); } catch (error) { return await closeTempFileAndCleanup(error); } try { await removeTempFile(); } catch (cleanupError) { throw new AggregateError([cleanupError], "Bash output cleanup failed"); } return { output: truncationResult.truncated ? truncationResult.content : fullOutput, exitCode: undefined, cancelled: true, truncated: truncationResult.truncated, }; } return await closeTempFileAndCleanup(err); } // Normal completion has a generous bound for observer callbacks: unlike the // cancellation path, it must not hang forever on an observer that never // settles, while still allowing legitimately slow callbacks to finish. A // callback that exceeds the public bound is an execution failure, not silent // abandonment, so its spill is cleaned before the caller is released. try { finishDecoder(); } catch (error) { return await closeTempFileAndCleanup(error); } const callbacksSettled = await waitForCallbacks(false); if (!callbacksSettled) { callbacksAbandoned = true; return await closeTempFileAndCleanup(new Error(`Bash output callback did not settle within ${NORMAL_CALLBACK_SETTLEMENT_TIMEOUT_MS}ms`)); } if (hasCallbackError) { return await closeTempFileAndCleanup(callbackError); } const { fullOutput, truncationResult } = await prepareFinalOutput(); try { await closeTempFileStream(); } catch (error) { return await closeTempFileAndCleanup(error); } const cancelled = options?.signal?.aborted ?? false; return { output: truncationResult.truncated ? truncationResult.content : fullOutput, exitCode: cancelled ? undefined : (result.exitCode ?? undefined), cancelled, truncated: truncationResult.truncated, fullOutputPath: tempFilePath, }; } //# sourceMappingURL=bash-executor.js.map