@@ -2,7 +2,7 @@ import { z } from "zod";
22 import { restoreTerminal } from "../cli/output.ts";
33 import { stripAnsi } from "../internal/ansi.ts";
44 import { buildFileEditShellPrelude } from "../internal/file-edit/command.ts";
5-import type { ToolDef } from "../llm-api/types.ts";
5+import type { ToolDef, ToolExecuteOptions } from "../llm-api/types.ts";
66
77 const ShellSchema = z.object({
88 command: z.string().describe("Shell command to execute"),
@@ -41,7 +41,10 @@ export interface ShellOutput {
4141
4242 const MAX_OUTPUT_BYTES = 10_000; // 10KB per stream
4343
44-export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
44+export async function runShellCommand(
45+ input: ShellInput,
46+ options?: ToolExecuteOptions,
47+): Promise<ShellOutput> {
4548 const cwd = input.cwd ?? process.cwd();
4649 const timeout = input.timeout ?? undefined;
4750 const inputEnv = input.env ?? undefined;
@@ -75,27 +78,41 @@ export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
7578 },
7679 );
7780
78- const timer = timeout
79- ? setTimeout(() => {
80- timedOut = true;
81+ function killProc(): void {
82+ try {
83+ proc.kill("SIGTERM");
84+ setTimeout(() => {
8185 try {
82- proc.kill("SIGTERM");
83- setTimeout(() => {
84- try {
85- proc.kill("SIGKILL");
86- } catch {
87- /* already dead */
88- }
89- }, 2000);
86+ proc.kill("SIGKILL");
9087 } catch {
91- /* already done */
92- }
93- for (const reader of readers) {
94- reader.cancel().catch(() => {});
88+ /* already dead */
9589 }
90+ }, 2000);
91+ } catch {
92+ /* already done */
93+ }
94+ for (const reader of readers) {
95+ reader.cancel().catch(() => {});
96+ }
97+ }
98+
99+ const timer = timeout
100+ ? setTimeout(() => {
101+ timedOut = true;
102+ killProc();
96103 }, timeout)
97104 : undefined;
98105
106+ const abortSignal = options?.signal;
107+ const onAbort = () => {
108+ killProc();
109+ };
110+ if (abortSignal?.aborted) {
111+ onAbort();
112+ } else {
113+ abortSignal?.addEventListener("abort", onAbort, { once: true });
114+ }
115+
99116 async function collectStream(
100117 stream: ReadableStream<Uint8Array>,
101118 ): Promise<string> {
@@ -144,6 +161,7 @@ export async function runShellCommand(input: ShellInput): Promise<ShellOutput> {
144161 exitCode = await proc.exited;
145162 } finally {
146163 if (timer) clearTimeout(timer);
164+ abortSignal?.removeEventListener("abort", onAbort);
147165 restoreTerminal();
148166 if (wasRaw) {
149167 try {
@@ -175,5 +193,5 @@ export const shellTool: ToolDef<ShellInput, ShellOutput> = {
175193 "Use this for reading/searching code, running tests, builds, git commands, and invoking `mc-edit` for partial file edits. " +
176194 "Prefer non-interactive commands. Avoid commands that run indefinitely.",
177195 schema: ShellSchema,
178- execute: runShellCommand,
196+ execute: (input, options) => runShellCommand(input, options),
179197 };