@@ -9,7 +9,15 @@
99 * @module
1010 */
1111
12-import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12+import {
13+ existsSync,
14+ mkdirSync,
15+ mkdtempSync,
16+ readFileSync,
17+ rmSync,
18+ writeFileSync,
19+} from "node:fs";
20+import { tmpdir } from "node:os";
1321 import { dirname, extname, isAbsolute, join } from "node:path";
1422 import type { ImageContent, TextContent, Tool } from "@mariozechner/pi-ai";
1523 import { Type } from "@mariozechner/pi-ai";
@@ -490,6 +498,8 @@ interface ShellOpts {
490498 onUpdate?: ToolUpdateCallback;
491499 }
492500
501+type ShellProcess = ReturnType<typeof Bun.spawn>;
502+
493503 const DEFAULT_MAX_LINES = 1000;
494504 const DEFAULT_MAX_BYTES = 50_000;
495505 const SHELL_UPDATE_INTERVAL_MS = 75;
@@ -837,26 +847,94 @@ function normalizeShellCommand(command: string): string {
837847 }
838848 }
839849
840-/** Read a spawned shell stream into a string, reporting progressive updates. */
841-async function consumeShellStream(
842- stream: ReadableStream<Uint8Array>,
843- onChunk: (chunk: string) => void,
844-): Promise<string> {
845- const reader = stream.getReader();
846- const decoder = new TextDecoder();
847- let output = "";
850+interface ShellCaptureFiles {
851+ stdoutPath: string;
852+ stderrPath: string;
853+ cleanup: () => void;
854+}
848855
849- while (true) {
850- const { done, value } = await reader.read();
851- if (done) {
852- output += decoder.decode();
853- return output;
856+function createShellCaptureFiles(): ShellCaptureFiles {
857+ const dir = mkdtempSync(join(tmpdir(), "mini-coder-shell-"));
858+ return {
859+ stdoutPath: join(dir, "stdout.log"),
860+ stderrPath: join(dir, "stderr.log"),
861+ cleanup: () => {
862+ try {
863+ rmSync(dir, { recursive: true, force: true });
864+ } catch {
865+ // Best-effort cleanup. Background processes may still hold the files open.
866+ }
867+ },
868+ };
869+}
870+
871+function readShellCapture(path: string): string {
872+ try {
873+ return readFileSync(path, "utf-8");
874+ } catch {
875+ return "";
876+ }
877+}
878+
879+function readShellCaptureOutput(
880+ capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
881+): { stdout: string; stderr: string } {
882+ return {
883+ stdout: readShellCapture(capture.stdoutPath),
884+ stderr: readShellCapture(capture.stderrPath),
885+ };
886+}
887+
888+function buildShellSpawnOptions(
889+ cwd: string,
890+ capture: Pick<ShellCaptureFiles, "stdoutPath" | "stderrPath">,
891+): Parameters<typeof Bun.spawn>[1] {
892+ return {
893+ cwd,
894+ stdout: Bun.file(capture.stdoutPath),
895+ stderr: Bun.file(capture.stderrPath),
896+ ...(process.platform === "win32" ? {} : { detached: true }),
897+ };
898+}
899+
900+function abortShellProcess(proc: ShellProcess): void {
901+ if (proc.killed || proc.exitCode !== null) {
902+ return;
903+ }
904+
905+ if (process.platform !== "win32") {
906+ try {
907+ process.kill(-proc.pid, "SIGTERM");
908+ return;
909+ } catch {
910+ // Fall through to a direct kill when the process group is unavailable.
854911 }
912+ }
913+
914+ proc.kill("SIGTERM");
915+}
855916
856- const chunk = decoder.decode(value, { stream: true });
857- output += chunk;
858- onChunk(chunk);
917+function registerShellAbort(
918+ signal: AbortSignal | undefined,
919+ proc: ShellProcess,
920+): (() => void) | null {
921+ if (!signal) {
922+ return null;
859923 }
924+
925+ const abortListener = (): void => {
926+ abortShellProcess(proc);
927+ };
928+
929+ if (signal.aborted) {
930+ abortShellProcess(proc);
931+ return null;
932+ }
933+
934+ signal.addEventListener("abort", abortListener, { once: true });
935+ return () => {
936+ signal.removeEventListener("abort", abortListener);
937+ };
860938 }
861939
862940 /**
@@ -879,93 +957,59 @@ export async function executeShell(
879957 const shell = process.env.SHELL || "/bin/sh";
880958 const maxLines = opts?.maxLines ?? DEFAULT_MAX_LINES;
881959 const maxBytes = opts?.maxBytes ?? DEFAULT_MAX_BYTES;
882- let updateTimer: ReturnType<typeof setTimeout> | null = null;
960+ const capture = createShellCaptureFiles();
961+ let updateTimer: ReturnType<typeof setInterval> | null = null;
962+ let cleanupAbort: (() => void) | null = null;
963+ let lastReportedOutput = "";
883964
884965 try {
885- const spawnOpts: Parameters<typeof Bun.spawn>[1] = {
886- cwd,
887- stdout: "pipe",
888- stderr: "pipe",
889- };
890- if (opts?.signal) spawnOpts.signal = opts.signal;
891- const command = normalizeShellCommand(args.command);
892- const proc = Bun.spawn([shell, "-c", command], spawnOpts);
893-
894- let stdoutBuf = "";
895- let stderrBuf = "";
896- let lastReportedOutput = "";
897- let lastReportAt = 0;
898-
899- const clearPendingUpdate = (): void => {
900- if (updateTimer) {
901- clearTimeout(updateTimer);
902- updateTimer = null;
903- }
904- };
905-
906- const buildProgressOutput = (): string => {
966+ const buildOutput = (trimEnd: boolean): string => {
967+ const { stdout, stderr } = readShellCaptureOutput(capture);
907968 return truncateOutput(
908- formatShellOutput(stdoutBuf, stderrBuf),
969+ formatShellOutput(
970+ trimEnd ? stdout.trimEnd() : stdout,
971+ trimEnd ? stderr.trimEnd() : stderr,
972+ ),
909973 maxLines,
910974 maxBytes,
911975 );
912976 };
913977
914978 const emitUpdate = (): void => {
915- clearPendingUpdate();
916979 if (!opts?.onUpdate) {
917980 return;
918981 }
919982
920- const output = buildProgressOutput();
983+ const output = buildOutput(false);
921984 if (!output || output === lastReportedOutput) {
922985 return;
923986 }
924987
925988 lastReportedOutput = output;
926- lastReportAt = Date.now();
927989 opts.onUpdate(textResult(output, false));
928990 };
929991
930- const scheduleUpdate = (): void => {
931- if (!opts?.onUpdate) {
932- return;
933- }
992+ const command = normalizeShellCommand(args.command);
993+ const proc = Bun.spawn(
994+ [shell, "-c", command],
995+ buildShellSpawnOptions(cwd, capture),
996+ );
997+ cleanupAbort = registerShellAbort(opts?.signal, proc);
934998
935- const elapsed = Date.now() - lastReportAt;
936- if (elapsed >= SHELL_UPDATE_INTERVAL_MS) {
937- emitUpdate();
938- return;
939- }
940- if (updateTimer) {
941- return;
942- }
999+ if (opts?.onUpdate) {
1000+ updateTimer = setInterval(emitUpdate, SHELL_UPDATE_INTERVAL_MS);
1001+ }
9431002
944- updateTimer = setTimeout(() => {
945- emitUpdate();
946- }, SHELL_UPDATE_INTERVAL_MS - elapsed);
947- };
1003+ const exitCode = await proc.exited;
9481004
949- const [stdout, stderr, exitCode] = await Promise.all([
950- consumeShellStream(proc.stdout as ReadableStream<Uint8Array>, (chunk) => {
951- stdoutBuf += chunk;
952- scheduleUpdate();
953- }),
954- consumeShellStream(proc.stderr as ReadableStream<Uint8Array>, (chunk) => {
955- stderrBuf += chunk;
956- scheduleUpdate();
957- }),
958- proc.exited,
959- ]);
960-
961- clearPendingUpdate();
962- const output = truncateOutput(
963- formatShellOutput(stdout.trimEnd(), stderr.trimEnd()),
964- maxLines,
965- maxBytes,
966- );
1005+ if (updateTimer) {
1006+ clearInterval(updateTimer);
1007+ updateTimer = null;
1008+ }
1009+ cleanupAbort?.();
1010+
1011+ const output = buildOutput(true);
9671012 if (opts?.onUpdate && output && output !== lastReportedOutput) {
968- lastReportedOutput = output;
9691013 opts.onUpdate(textResult(output, false));
9701014 }
9711015
@@ -973,12 +1017,15 @@ export async function executeShell(
9731017 const body = output || "(no output)";
9741018 return textResult(`Exit code: ${exitCode}\n${body}`, isError);
9751019 } catch (err) {
1020+ cleanupAbort?.();
9761021 if (updateTimer) {
977- clearTimeout(updateTimer);
1022+ clearInterval(updateTimer);
9781023 updateTimer = null;
9791024 }
9801025 const message = err instanceof Error ? err.message : String(err);
9811026 return textResult(`Shell error: ${message}`, true);
1027+ } finally {
1028+ capture.cleanup();
9821029 }
9831030 }
9841031