UNPKG

@code-yeongyu/senpi

Version:

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

160 lines • 6.23 kB
import { spawn } from "node:child_process"; import { performance } from "node:perf_hooks"; import { waitForChildProcess } from "../../../../utils/child-process.js"; import { withCredentialProxy } from "../../../credential-proxy/runtime.js"; import { killProcessTree, trackDetachedChildPid, untrackDetachedChildPid } from "../../../../utils/shell.js"; import { applyHookOutputSafety, buildHookEnvironment, DEFAULT_STDERR_LIMIT_BYTES, DEFAULT_STDOUT_LIMIT_BYTES, resolveHookTimeoutSeconds, } from "./safety.js"; export async function runCommandHook(handler, input, options) { const command = selectCommandForPlatform(handler); const startedAt = performance.now(); const timeoutSeconds = resolveHookTimeoutSeconds(handler); if (options.signal?.aborted) { return buildResult({ aborted: true, command, cwd: options.cwd, exitCode: null, signal: null, startedAt, stderr: createEmptyStreamCapture("stderr"), stdout: createEmptyStreamCapture("stdout"), timedOut: false, timeoutSeconds, outputPolicy: options.outputPolicy, }); } const child = spawn(command, { cwd: options.cwd, detached: process.platform !== "win32", env: buildHookEnvironment({ envPassthrough: options.envPassthrough, handler, input, // Hooks run agent-triggered commands: declared credentials are withheld as for the bash tool (senpi#6820). sourceEnv: options.sourceEnv ?? withCredentialProxy(process.env), }), shell: true, stdio: ["pipe", "pipe", "pipe"], windowsHide: true, }); if (child.pid !== undefined) trackDetachedChildPid(child.pid); const stdout = createBoundedStreamCapture("stdout", options.outputPolicy); const stderr = createBoundedStreamCapture("stderr", options.outputPolicy); let exitSignal = null; let timedOut = false; let timeoutHandle; const killChild = () => { if (child.pid !== undefined) killProcessTree(child.pid); }; const onAbort = () => killChild(); try { child.stdout?.on("data", (chunk) => stdout.append(chunk)); child.stderr?.on("data", (chunk) => stderr.append(chunk)); child.once("exit", (_code, signal) => { exitSignal = signal; }); if (timeoutSeconds > 0) { timeoutHandle = setTimeout(() => { timedOut = true; killChild(); }, timeoutSeconds * 1000); } if (options.signal !== undefined) { if (options.signal.aborted) onAbort(); else options.signal.addEventListener("abort", onAbort, { once: true }); } // A hook may exit without reading its JSON input; the write then fails with EPIPE. That is the hook's choice and its // exit code is the result, so it must not surface as an uncaught exception in the engine. child.stdin?.on("error", (error) => { if (error.code !== "EPIPE") stderr.append(Buffer.from(`[senpi:hooks] writing hook input failed: ${error.message}\n`)); }); child.stdin?.end(JSON.stringify(input)); const exitCode = await waitForChildProcess(child); return buildResult({ aborted: options.signal?.aborted === true, command, cwd: options.cwd, exitCode: timedOut || options.signal?.aborted === true ? null : exitCode, signal: exitSignal, startedAt, stderr, stdout, timedOut, timeoutSeconds, outputPolicy: options.outputPolicy, }); } finally { if (child.pid !== undefined) untrackDetachedChildPid(child.pid); if (timeoutHandle !== undefined) clearTimeout(timeoutHandle); if (options.signal !== undefined) options.signal.removeEventListener("abort", onAbort); } } export function selectCommandForPlatform(handler, platform = process.platform) { if (platform === "win32" && handler.config.commandWindows !== undefined) { return handler.config.commandWindows; } return handler.config.command; } function buildResult(input) { const stdout = input.stdout.finalize(input.outputPolicy); const stderr = input.stderr.finalize(input.outputPolicy); return { aborted: input.aborted, command: input.command, cwd: input.cwd, durationMs: Math.max(0, performance.now() - input.startedAt), exitCode: input.exitCode, outputSafety: { stderr: stderr.safety, stdout: stdout.safety }, signal: input.signal, stderr: stderr.text, stdout: stdout.text, timedOut: input.timedOut, timeoutSeconds: input.timeoutSeconds, }; } function createBoundedStreamCapture(stream, policy) { const limit = stream === "stdout" ? (policy?.maxStdoutBytes ?? DEFAULT_STDOUT_LIMIT_BYTES) : (policy?.maxStderrBytes ?? DEFAULT_STDERR_LIMIT_BYTES); const chunks = []; let keptBytes = 0; let totalBytes = 0; return { append(chunk) { totalBytes += chunk.length; if (keptBytes >= limit) return; const bytesToKeep = Math.min(limit - keptBytes, chunk.length); chunks.push(Buffer.from(chunk.subarray(0, bytesToKeep))); keptBytes += bytesToKeep; }, finalize(finalPolicy) { let text = ""; for (const chunk of chunks) { text += chunk.toString("utf8"); } return applyHookOutputSafety(stream, text, finalPolicy, { originalBytes: totalBytes, truncated: totalBytes > keptBytes, }); }, }; } function createEmptyStreamCapture(stream) { return { append(_chunk) { }, finalize(policy) { return applyHookOutputSafety(stream, "", policy, { originalBytes: 0, truncated: false }); }, }; } //# sourceMappingURL=command-runner.js.map