@@ -35,139 +35,135 @@ export interface ShellOutput {
3535
3636 const MAX_OUTPUT_BYTES = 10_000; // 10KB per stream
3737
38-export const shellTool: ToolDef<ShellInput, ShellOutput> = {
39- name: "shell",
40- description:
41- "Execute a shell command. Returns stdout, stderr, and exit code. " +
42- "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
43- "Prefer non-interactive commands. Avoid commands that run indefinitely.",
44- schema: ShellSchema,
45- execute: async (input) => {
46- const cwd = input.cwd ?? process.cwd();
47- const timeout = input.timeout ?? 30_000;
48- const env: Record<string, string | undefined> = Object.assign(
49- {},
50- process.env as Record<string, string | undefined>,
51- input.env ?? {},
52- );
53-
54- let timedOut = false;
55- const readers: { cancel: () => Promise<void> }[] = [];
56-
57- const wasRaw = process.stdin.isTTY ? process.stdin.isRaw : false;
58-
59- const proc = Bun.spawn(
60- ["bash", "-c", `${buildFileEditShellPrelude()}\n${input.command}`],
61- {
62- cwd,
63- env,
64- stdout: "pipe",
65- stderr: "pipe",
66- },
67- );
68-
69- // Set up timeout
70- const timer = setTimeout(() => {
71- timedOut = true;
72- try {
73- proc.kill("SIGTERM");
74- setTimeout(() => {
75- try {
76- proc.kill("SIGKILL");
77- } catch {
78- /* already dead */
79- }
80- }, 2000);
81- } catch {
82- /* already done */
83- }
84- for (const r of readers) {
85- r.cancel().catch(() => {});
86- }
87- }, timeout);
88-
89- // Collect output with size limit; forward each decoded chunk to onOutput.
90- async function collectStream(
91- stream: ReadableStream<Uint8Array>,
92- onChunk?: (text: string) => void,
93- ): Promise<string> {
94- const reader = stream.getReader();
95- readers.push(reader);
96- const chunks: Uint8Array[] = [];
97- let totalBytes = 0;
98- let truncated = false;
99- const decoder = new TextDecoder();
100-
101- while (true) {
38+export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
39+ const cwd = input.cwd ?? process.cwd();
40+ const timeout = input.timeout ?? 30_000;
41+ const env: Record<string, string | undefined> = Object.assign(
42+ {},
43+ process.env as Record<string, string | undefined>,
44+ input.env ?? {},
45+ );
46+
47+ let timedOut = false;
48+ const readers: { cancel: () => Promise<void> }[] = [];
49+ const wasRaw = process.stdin.isTTY ? process.stdin.isRaw : false;
50+
51+ const proc = Bun.spawn(
52+ ["bash", "-c", `${buildFileEditShellPrelude()}\n${input.command}`],
53+ {
54+ cwd,
55+ env,
56+ stdout: "pipe",
57+ stderr: "pipe",
58+ },
59+ );
60+
61+ const timer = setTimeout(() => {
62+ timedOut = true;
63+ try {
64+ proc.kill("SIGTERM");
65+ setTimeout(() => {
10266 try {
103- const { done, value } = await reader.read();
104- if (done) break;
105- if (value) {
106- onChunk?.(decoder.decode(value, { stream: true }));
107- if (totalBytes + value.length > MAX_OUTPUT_BYTES) {
108- chunks.push(value.slice(0, MAX_OUTPUT_BYTES - totalBytes));
109- truncated = true;
110- reader.cancel().catch(() => {});
111- break;
112- }
113- chunks.push(value);
114- totalBytes += value.length;
115- }
116- } catch (_err) {
117- // Reader was cancelled or stream errored
118- break;
67+ proc.kill("SIGKILL");
68+ } catch {
69+ /* already dead */
11970 }
120- }
121-
122- const text = Buffer.concat(chunks).toString("utf-8");
123- return truncated ? `${text}\n[output truncated]` : text;
71+ }, 2000);
72+ } catch {
73+ /* already done */
12474 }
75+ for (const reader of readers) {
76+ reader.cancel().catch(() => {});
77+ }
78+ }, timeout);
79+
80+ async function collectStream(
81+ stream: ReadableStream<Uint8Array>,
82+ onChunk?: (text: string) => void,
83+ ): Promise<string> {
84+ const reader = stream.getReader();
85+ readers.push(reader);
86+ const chunks: Uint8Array[] = [];
87+ let totalBytes = 0;
88+ let truncated = false;
89+ const decoder = new TextDecoder();
90+
91+ while (true) {
92+ try {
93+ const { done, value } = await reader.read();
94+ if (done) break;
95+ if (!value) continue;
96+
97+ onChunk?.(decoder.decode(value, { stream: true }));
98+ if (totalBytes + value.length > MAX_OUTPUT_BYTES) {
99+ chunks.push(value.slice(0, MAX_OUTPUT_BYTES - totalBytes));
100+ truncated = true;
101+ reader.cancel().catch(() => {});
102+ break;
103+ }
125104
126- let stdout = "";
127- let stderr = "";
128- let exitCode = 1;
129- const onOutput = input.onOutput;
130- const hasOutputHandler = typeof onOutput === "function";
131- let streamedAnyOutput = false;
132- let streamedEndsWithNewline = true;
133- const emitOutput = (chunk: string): void => {
134- if (!chunk || !hasOutputHandler) return;
135- streamedAnyOutput = true;
136- streamedEndsWithNewline = /[\r\n]$/.test(chunk);
137- onOutput(chunk);
138- };
139-
140- try {
141- [stdout, stderr] = await Promise.all([
142- collectStream(proc.stdout, hasOutputHandler ? emitOutput : undefined),
143- collectStream(proc.stderr, hasOutputHandler ? emitOutput : undefined),
144- ]);
145- if (streamedAnyOutput && !streamedEndsWithNewline) {
146- emitOutput("\n");
105+ chunks.push(value);
106+ totalBytes += value.length;
107+ } catch {
108+ break;
147109 }
110+ }
148111
149- exitCode = await proc.exited;
150- } finally {
151- clearTimeout(timer);
152- // Ensure the terminal is in a sane state if the spawn caused any
153- // raw-mode or cursor-visibility side-effects
154- restoreTerminal();
155- if (wasRaw) {
156- try {
157- process.stdin.setRawMode(true);
158- } catch {
159- /* ignore */
160- }
112+ const text = Buffer.concat(chunks).toString("utf-8");
113+ return truncated ? `${text}\n[output truncated]` : text;
114+ }
115+
116+ let stdout = "";
117+ let stderr = "";
118+ let exitCode = 1;
119+ const onOutput = input.onOutput;
120+ const hasOutputHandler = typeof onOutput === "function";
121+ let streamedAnyOutput = false;
122+ let streamedEndsWithNewline = true;
123+ const emitOutput = (chunk: string): void => {
124+ if (!chunk || !hasOutputHandler) return;
125+ streamedAnyOutput = true;
126+ streamedEndsWithNewline = /[\r\n]$/.test(chunk);
127+ onOutput(chunk);
128+ };
129+
130+ try {
131+ [stdout, stderr] = await Promise.all([
132+ collectStream(proc.stdout, hasOutputHandler ? emitOutput : undefined),
133+ collectStream(proc.stderr, hasOutputHandler ? emitOutput : undefined),
134+ ]);
135+ if (streamedAnyOutput && !streamedEndsWithNewline) {
136+ emitOutput("\n");
137+ }
138+ exitCode = await proc.exited;
139+ } finally {
140+ clearTimeout(timer);
141+ restoreTerminal();
142+ if (wasRaw) {
143+ try {
144+ process.stdin.setRawMode(true);
145+ } catch {
146+ /* ignore */
161147 }
162148 }
149+ }
150+
151+ return {
152+ stdout: stdout.trimEnd(),
153+ stderr: stderr.trimEnd(),
154+ exitCode,
155+ success: exitCode === 0,
156+ timedOut,
157+ streamedOutput: streamedAnyOutput,
158+ };
159+}
163160
164- return {
165- stdout: stdout.trimEnd(),
166- stderr: stderr.trimEnd(),
167- exitCode,
168- success: exitCode === 0,
169- timedOut,
170- streamedOutput: streamedAnyOutput,
171- };
172- },
161+export const shellTool: ToolDef<ShellInput, ShellOutput> = {
162+ name: "shell",
163+ description:
164+ "Execute a shell command. Returns stdout, stderr, and exit code. " +
165+ "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
166+ "Prefer non-interactive commands. Avoid commands that run indefinitely.",
167+ schema: ShellSchema,
168+ execute: runShellCommand,
173169 };