Refactor tool timeout handling and error management

- Updated timeout settings for various tools to improve responsiveness and prevent blocking the agent loop.
- Enhanced error handling in tools to provide clearer feedback on invalid paths and execution failures.
- Implemented abort signal support in multiple tools, allowing for graceful cancellation of long-running operations.
- Adjusted the `walk` function to respect abort signals and limit the number of files processed, preventing hangs during directory traversals.
- Improved the `grepTool`, `globTool`, and `fileSearchTool` to handle timeouts and abort signals effectively, enhancing overall tool performance.
This commit is contained in:
Pawan Osman
2026-07-15 16:35:26 +03:00
parent 76993e645b
commit 7f000c254c
6 changed files with 491 additions and 195 deletions
+5 -4
View File
@@ -621,25 +621,26 @@ export async function runAgent(opts: RunAgentOptions): Promise<void> {
};
if (signal.aborted) onParentAbort();
else signal.addEventListener("abort", onParentAbort, { once: true });
// Abort the tool slightly before the race rejects so cleanup can run.
// Abort slightly before the race rejects so tools can clean up.
let toolTimer: ReturnType<typeof setTimeout> | undefined;
if (limitMs > 0) {
toolTimer = setTimeout(() => {
try { toolAc.abort(); } catch { /* ignore */ }
}, limitMs);
}, Math.max(500, limitMs - 400));
}
let r: Awaited<ReturnType<typeof tool.execute>>;
try {
r = await withToolTimeout(
tool.execute(input, toolAc.signal, call.id, toolCtx),
Promise.resolve().then(() => tool.execute(input, toolAc.signal, call.id, toolCtx)),
limitMs,
call.name,
);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
try { toolAc.abort(); } catch { /* ignore */ }
r = {
output: msg.startsWith("timeout:")
? `error: ${msg}. The tool was aborted so the agent can continue — retry with a narrower scope or shorter command.`
? `error: ${msg}. Tool aborted - retry with a narrower scope or shorter command.`
: `error: ${msg}`,
};
} finally {
+58 -33
View File
@@ -82,48 +82,73 @@ export const readFileTool = defineTool("Read", false, async (input) => {
// ---- ListDir ----
export const listDirTool = defineTool("ListDir", false, async (input) => {
const p = safePath(input.path ?? ".");
const entries = await fs.readdir(p, { withFileTypes: true });
const out =
entries
.filter((e) => !IGNORE.has(e.name))
.map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
.join("\n") || "(empty)";
return { output: out };
try {
const p = safePath(input.path ?? ".");
const entries = await fs.readdir(p, { withFileTypes: true });
const out =
entries
.filter((e) => !IGNORE.has(e.name))
.slice(0, 2_000)
.map((e) => (e.isDirectory() ? `${e.name}/` : e.name))
.join("\n") || "(empty)";
return { output: out };
} catch (e) {
return { output: `error: ListDir failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
// ---- Glob ----
export const globTool = defineTool("Glob", false, async (input, abortSignal) => {
const root = input.target_directory ? safePath(input.target_directory) : getWorkspaceRoot();
// Include ignored dirs so patterns like "**/node_modules/**" can match.
const all: string[] = [];
await walk(root, all, 0, true, abortSignal);
// Prepend "**/" when the pattern isn't already rooted (schema behavior).
let pattern: string = String(input.glob_pattern ?? "");
if (pattern && !pattern.startsWith("**/")) pattern = "**/" + pattern;
const re = globToRe(pattern);
try {
const root = input.target_directory ? safePath(input.target_directory) : getWorkspaceRoot();
// Only walk ignored dirs when the pattern explicitly targets them
// (e.g. "**/node_modules/**") — otherwise node_modules hangs the tool.
let pattern: string = String(input.glob_pattern ?? "");
if (pattern && !pattern.startsWith("**/")) pattern = "**/" + pattern;
const wantsIgnored = /node_modules|\.git|[/\\]dist[/\\]|[/\\]out[/\\]|[/\\]build[/\\]/.test(pattern);
const all: string[] = [];
await walk(root, all, 0, wantsIgnored, abortSignal, 20_000);
if (abortSignal?.aborted) return { output: "(glob aborted)" };
const re = globToRe(pattern);
// Filter, then return matches sorted by modification time (schema promise).
const matched = all.filter((f) => re.test(path.relative(root, f).split(path.sep).join("/")));
const sorted = await sortByMtime(matched);
const hits = sorted.slice(0, 200).map((f) => path.relative(root, f).split(path.sep).join("/"));
return { output: hits.join("\n") || "(no matches)" };
const matched = all.filter((f) => {
try {
return re.test(path.relative(root, f).split(path.sep).join("/"));
} catch {
return false;
}
});
// Cap mtime sort work — huge match sets made Glob look stuck.
const toSort = matched.slice(0, 2_000);
const sorted = await sortByMtime(toSort);
const hits = sorted.slice(0, 200).map((f) => path.relative(root, f).split(path.sep).join("/"));
const extra = matched.length > hits.length ? `\n… (${matched.length - hits.length} more)` : "";
return { output: (hits.join("\n") || "(no matches)") + extra };
} catch (e) {
return { output: `error: Glob failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
// ---- FileSearch (fuzzy filename search) ----
export const fileSearchTool = defineTool("FileSearch", false, async (input, abortSignal) => {
const root = getWorkspaceRoot();
const all: string[] = [];
await walk(root, all, 0, false, abortSignal);
const q = String(input.query || "").toLowerCase();
const rel = all.map((f) => path.relative(root, f).split(path.sep).join("/"));
const scored = rel
.map((f) => ({ f, score: fuzzyScore(f.toLowerCase(), q) }))
.filter((x) => x.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, 30)
.map((x) => x.f);
return { output: scored.join("\n") || "(no matches)" };
try {
const root = getWorkspaceRoot();
const all: string[] = [];
await walk(root, all, 0, false, abortSignal, 20_000);
if (abortSignal?.aborted) return { output: "(FileSearch aborted)" };
const q = String(input.query || "").toLowerCase();
if (!q) return { output: "(empty query)" };
const rel = all.map((f) => path.relative(root, f).split(path.sep).join("/"));
const scored = rel
.map((f) => ({ f, score: fuzzyScore(f.toLowerCase(), q) }))
.filter((x) => x.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, 30)
.map((x) => x.f);
return { output: scored.join("\n") || "(no matches)" };
} catch (e) {
return { output: `error: FileSearch failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
// ---- StrReplace / Write (shared edit handler) ----
+75 -22
View File
@@ -39,14 +39,18 @@ const TYPE_EXTS: Record<string, string[]> = {
// ---- Grep (ripgrep with a node fallback) ----
export const grepTool = defineTool("Grep", false, async (input, abortSignal) => {
try {
if (abortSignal?.aborted) return { output: "(grep aborted)" };
const root = getWorkspaceRoot();
const mode: string = input.output_mode || "content";
const target = input.path ? safePath(input.path) : ".";
const cap = Math.max(1, Math.min(Number(input.head_limit) || 200, 5000));
const cap = Math.max(1, Math.min(Number(input.head_limit) || 200, 2000));
const skip = Math.max(0, Number(input.offset) || 0);
const pattern = String(input.pattern ?? "");
if (!pattern) return { output: "error: pattern is required" };
if (await rgAvailable()) {
const args = ["--color=never"];
const args = ["--color=never", "--hidden", "--glob", "!**/.git/**", "--glob", "!**/node_modules/**"];
if (mode === "files_with_matches") {
args.push("--files-with-matches");
} else if (mode === "count") {
@@ -61,26 +65,50 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
if (input.multiline) args.push("-U", "--multiline-dotall");
if (input.glob) args.push("--glob", String(input.glob));
if (input.type) args.push("--type", String(input.type));
args.push("--", input.pattern, target);
args.push("--", pattern, target);
const out = await new Promise<string>((res) => {
let settled = false;
let o = "";
const c = spawn("rg", args, { cwd: root, signal: abortSignal });
let c: ReturnType<typeof spawn>;
const finish = (v: string) => {
if (settled) return;
settled = true;
clearTimeout(timer);
try { abortSignal?.removeEventListener("abort", onAbort); } catch { /* ignore */ }
res(v);
};
const onAbort = () => {
try { c.kill("SIGTERM"); } catch { /* ignore */ }
finish(o ? o.slice(0, 50_000) + "\n(grep aborted)" : "(grep aborted)");
};
// Hard kill hung rg even if AbortSignal is missing/ignored.
const timer = setTimeout(() => {
try { c.kill("SIGTERM"); } catch { /* ignore */ }
try { c.kill("SIGKILL"); } catch {
try { c.kill("SIGTERM"); } catch { /* ignore */ }
}
finish(o ? o.slice(0, 50_000) + "\n(grep timed out)" : "(grep timed out)");
}, 25_000);
c.stdout?.on("data", (d) => (o += d));
}, 15_000);
try {
c = spawn("rg", args, { cwd: root, windowsHide: true });
} catch (e) {
finish(`(grep failed: ${e instanceof Error ? e.message : String(e)})`);
return;
}
if (abortSignal?.aborted) {
onAbort();
return;
}
abortSignal?.addEventListener("abort", onAbort, { once: true });
c.stdout?.on("data", (d) => {
o += d;
// Bound memory if rg floods output.
if (o.length > 2_000_000) {
try { c.kill("SIGTERM"); } catch { /* ignore */ }
}
});
c.stderr?.on("data", () => { /* ignore */ });
c.on("error", () => finish("(grep failed)"));
c.on("error", (e) => finish(`(grep failed: ${e instanceof Error ? e.message : String(e)})`));
c.on("close", () => {
let lines = o.split("\n").filter(Boolean);
if (skip) lines = lines.slice(skip);
@@ -93,12 +121,21 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
// Node fallback (no ripgrep available). Honor path/glob/type/-A/-B/-C/multiline.
const scopeRoot = input.path ? safePath(input.path) : root;
const all: string[] = [];
await walk(scopeRoot, all, 0, false, abortSignal);
await walk(scopeRoot, all, 0, false, abortSignal, 15_000);
if (abortSignal?.aborted) return { output: "(grep aborted)" };
const flags = input["-i"] ? "i" : "";
const lineRe = new RegExp(input.pattern, flags);
const multiRe = input.multiline ? new RegExp(input.pattern, flags + "s") : null;
const globRe = input.glob ? globToRe(String(input.glob).startsWith("**/") ? String(input.glob) : "**/" + String(input.glob)) : null;
let lineRe: RegExp;
let multiRe: RegExp | null = null;
try {
const flags = input["-i"] ? "i" : "";
lineRe = new RegExp(pattern, flags);
multiRe = input.multiline ? new RegExp(pattern, flags + "s") : null;
} catch (e) {
return { output: `error: invalid pattern: ${e instanceof Error ? e.message : String(e)}` };
}
const globRe = input.glob
? globToRe(String(input.glob).startsWith("**/") ? String(input.glob) : "**/" + String(input.glob))
: null;
const typeExts = input.type ? TYPE_EXTS[String(input.type)] : null;
const aCtx = Math.max(0, Number(input["-A"] ?? input["-C"] ?? 0));
const bCtx = Math.max(0, Number(input["-B"] ?? input["-C"] ?? 0));
@@ -106,13 +143,15 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
const hitsByFile: Record<string, string[]> = {};
const countByFile: Record<string, number> = {};
const order: string[] = [];
for (const f of all.slice(0, 5000)) {
for (const f of all.slice(0, 3000)) {
if (abortSignal?.aborted) return { output: "(grep aborted)" };
const rel = path.relative(root, f).split(path.sep).join("/");
if (globRe && !globRe.test(rel)) continue;
if (typeExts && !typeExts.includes(path.extname(f).toLowerCase())) continue;
let txt: string;
try {
const st = await fs.stat(f);
if (st.size > 1_000_000) continue; // skip huge files in fallback
txt = await fs.readFile(f, "utf8");
} catch {
continue; // binary / unreadable
@@ -128,17 +167,18 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
if (multiRe) {
if (multiRe.test(txt)) {
countByFile[rel] = (countByFile[rel] ?? 0) + 1;
push(`${rel}:${txt}`);
push(`${rel}:${txt.slice(0, 500)}`);
}
continue;
}
const lines = txt.split("\n");
lines.forEach((l, idx) => {
if (!lineRe.test(l)) return;
for (let idx = 0; idx < lines.length; idx++) {
const l = lines[idx];
if (!lineRe.test(l)) continue;
countByFile[rel] = (countByFile[rel] ?? 0) + 1;
if (mode !== "content") {
push(`${rel}:${idx + 1}:${l}`);
return;
continue;
}
for (let b = bCtx; b >= 1; b--) {
if (idx - b >= 0) push(`${rel}-${idx + 1 - b}-${lines[idx - b]}`);
@@ -147,7 +187,7 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
for (let a = 1; a <= aCtx; a++) {
if (idx + a < lines.length) push(`${rel}-${idx + 1 + a}-${lines[idx + a]}`);
}
});
}
}
let result: string[];
@@ -159,6 +199,9 @@ export const grepTool = defineTool("Grep", false, async (input, abortSignal) =>
const shown = result.slice(0, cap);
if (!shown.length) return { output: "(no matches)" };
return { output: shown.join("\n") + (truncated ? `\n... (at least ${result.length} matches, truncated)` : "") };
} catch (e) {
return { output: `error: Grep failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
// ---- SemanticSearch ----
@@ -179,12 +222,15 @@ function keywordFallback(input: any, abortSignal?: AbortSignal, callId?: string,
}
export const semanticSearchTool = defineTool("SemanticSearch", false, async (input, abortSignal, callId, ctx) => {
try {
if (abortSignal?.aborted) return { output: "(search aborted)" };
const query = String(input.query || "").trim();
if (!query) return { output: "(no query)" };
const root = getWorkspaceRoot();
// Build/refresh index on demand (incremental; cheap if already fresh).
if (isIndexingEnabled() && !isIndexing()) buildIndex(root).catch(() => {});
// Never await a full rebuild here — that hung explore tools for minutes.
if (isIndexingEnabled() && !isIndexing()) void buildIndex(root).catch(() => {});
// Scope by target_directories (prefix match on workspace-relative paths).
const dirs: string[] = Array.isArray(input.target_directories) ? input.target_directories : [];
@@ -207,15 +253,19 @@ export const semanticSearchTool = defineTool("SemanticSearch", false, async (inp
.map((h) => `${h.path}:${h.start}-${h.end} (score ${h.score.toFixed(3)})\n${h.text}`)
.join("\n\n---\n\n");
return { output: out };
} catch (e) {
return { output: `error: SemanticSearch failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
// ---- SearchDocs (user-indexed external documentation) ----
export const searchDocsTool = defineTool("SearchDocs", false, async (input) => {
try {
const query = String(input.query || "").trim();
if (!query) return { output: "(no query)" };
const k = Math.max(1, Math.min(Number(input.num_results) || 6, 12));
const sources = listDocSources().filter((d) => (d.pages ?? 0) > 0);
if (!sources.length) return { output: "(no indexed doc sources — the user can add them in Settings > Indexing & Docs)" };
if (!sources.length) return { output: "(no indexed doc sources - add them in Settings > Indexing & Docs)" };
const want = String(input.doc || "").trim().toLowerCase();
const targets = want
@@ -235,7 +285,10 @@ export const searchDocsTool = defineTool("SearchDocs", false, async (input) => {
if (!top.length) return { output: "(no matching excerpts)" };
return {
output: top
.map((h) => `[${h.doc}] ${h.title} — ${h.url} (score ${h.score.toFixed(3)})\n${h.text}`)
.map((h) => `[${h.doc}] ${h.title} - ${h.url} (score ${h.score.toFixed(3)})\n${h.text}`)
.join("\n\n---\n\n"),
};
} catch (e) {
return { output: `error: SearchDocs failed: ${e instanceof Error ? e.message : String(e)}` };
}
});
+147 -59
View File
@@ -51,34 +51,34 @@ export const IGNORE = new Set([
// blocking the agent loop forever. Task/AskQuestion are excluded (own budgets).
// ---------------------------------------------------------------------------
export const TOOL_TIMEOUT_MS: Record<string, number> = {
// Shell/AwaitShell cap their own foreground wait (90s/120s); the outer
// timeout is a safety net above that so it never fires before the tool's.
Shell: 120_000,
AwaitShell: 150_000,
Grep: 30_000,
Glob: 30_000,
FileSearch: 20_000,
SemanticSearch: 45_000,
SearchDocs: 30_000,
ListDir: 15_000,
Read: 30_000,
ReadLints: 20_000,
WebSearch: 25_000,
WebFetch: 30_000,
StrReplace: 30_000,
Write: 30_000,
Delete: 15_000,
EditNotebook: 30_000,
CallMcpTool: 60_000,
FetchMcpResource: 45_000,
ListMcpResources: 20_000,
// Outer safety net: slightly above each tool's own cap so the tool can
// clean up (kill process / mark done) before the loop aborts it.
Shell: 45_000,
AwaitShell: 60_000,
Grep: 20_000,
Glob: 20_000,
FileSearch: 15_000,
SemanticSearch: 30_000,
SearchDocs: 25_000,
ListDir: 10_000,
Read: 20_000,
ReadLints: 15_000,
WebSearch: 20_000,
WebFetch: 25_000,
StrReplace: 20_000,
Write: 20_000,
Delete: 10_000,
EditNotebook: 20_000,
CallMcpTool: 45_000,
FetchMcpResource: 30_000,
ListMcpResources: 15_000,
TodoWrite: 5_000,
TodoRead: 5_000,
WritePlan: 15_000,
WritePlan: 10_000,
SwitchMode: 5_000,
};
/** Default when a tool has no explicit entry. */
export const DEFAULT_TOOL_TIMEOUT_MS = 60_000;
export const DEFAULT_TOOL_TIMEOUT_MS = 30_000;
/** Tools that manage their own lifetime (user wait / nested agent). */
export const NO_TOOL_TIMEOUT = new Set(["Task", "AskQuestion"]);
@@ -107,17 +107,19 @@ export function setToolTimeoutOverrides(sec: Record<string, number> | undefined)
* whose message starts with "timeout:" so the loop can surface it cleanly.
* Does not cancel the underlying work by itself — pass a linked AbortSignal
* into the tool when possible (Shell/Grep honor it).
* Always settles (never hangs) even if `p` never resolves.
*/
export function withToolTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {
if (!ms || ms <= 0) return p;
// Guard against a never-settling promise with no explicit limit.
const limit = !ms || ms <= 0 ? 120_000 : ms;
return new Promise<T>((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
reject(new Error(`timeout: ${label} exceeded ${Math.round(ms / 1000)}s`));
}, ms);
p.then(
reject(new Error(`timeout: ${label} exceeded ${Math.round(limit / 1000)}s`));
}, limit);
Promise.resolve(p).then(
(v) => {
if (settled) return;
settled = true;
@@ -128,7 +130,7 @@ export function withToolTimeout<T>(p: Promise<T>, ms: number, label: string): Pr
if (settled) return;
settled = true;
clearTimeout(timer);
reject(e);
reject(e instanceof Error ? e : new Error(String(e)));
},
);
});
@@ -226,6 +228,7 @@ export function firstDiffLine(before: string, after: string): number {
/**
* Recursively collect file paths under `dir` (depth-capped). IGNORE dirs
* (node_modules, .git, build caches, …) are skipped unless `includeIgnored` is true.
* Always respects AbortSignal and maxFiles so explore tools cannot hang forever.
*/
export async function walk(
dir: string,
@@ -234,9 +237,9 @@ export async function walk(
includeIgnored = false,
signal?: AbortSignal,
/** Soft cap so huge trees cannot hang the tool forever. */
maxFiles = 50_000,
maxFiles = 20_000,
): Promise<void> {
if (depth > 12 || out.length >= maxFiles) return;
if (depth > 10 || out.length >= maxFiles) return;
if (signal?.aborted) return;
let entries;
try {
@@ -247,11 +250,21 @@ export async function walk(
for (const e of entries) {
if (signal?.aborted || out.length >= maxFiles) return;
if (!includeIgnored && IGNORE.has(e.name)) continue;
// Always skip the heaviest trees even when includeIgnored (Glob edge cases).
if (e.name === "node_modules" || e.name === ".git") {
if (!includeIgnored) continue;
// Still skip .git internals; allow node_modules only when explicitly requested.
if (e.name === ".git") continue;
}
const full = path.join(dir, e.name);
if (e.isDirectory()) {
await walk(full, out, depth + 1, includeIgnored, signal, maxFiles);
} else {
out.push(full);
try {
if (e.isDirectory()) {
await walk(full, out, depth + 1, includeIgnored, signal, maxFiles);
} else if (e.isFile() || e.isSymbolicLink()) {
out.push(full);
}
} catch {
/* permission / race — skip entry */
}
}
}
@@ -308,12 +321,32 @@ export function slugify(s: string): string {
);
}
/** Whether ripgrep is available on PATH. */
/** Whether ripgrep is available on PATH (cached; 3s probe timeout). */
let rgCached: boolean | null = null;
export function rgAvailable(): Promise<boolean> {
if (rgCached != null) return Promise.resolve(rgCached);
return new Promise((res) => {
const c = spawn("rg", ["--version"]);
c.on("error", () => res(false));
c.on("close", (code) => res(code === 0));
let settled = false;
const finish = (v: boolean) => {
if (settled) return;
settled = true;
clearTimeout(timer);
rgCached = v;
res(v);
};
const timer = setTimeout(() => {
try { c.kill(); } catch { /* ignore */ }
finish(false);
}, 3_000);
let c: ReturnType<typeof spawn>;
try {
c = spawn("rg", ["--version"]);
} catch {
finish(false);
return;
}
c.on("error", () => finish(false));
c.on("close", (code) => finish(code === 0));
});
}
@@ -380,19 +413,47 @@ const shellSessions = new Map<string, ShellSession>();
function spawnSessionShell(cwd: string): ChildProcess {
if (process.platform === "win32") {
return spawn("powershell.exe", ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", "-"], { cwd });
// -File - reads stdin as a script; NonInteractive avoids prompts that hang.
return spawn(
"powershell.exe",
["-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", "-"],
{ cwd, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] },
);
}
return spawn("bash", ["-i"], { cwd });
// Non-interactive bash (no -i): interactive mode can hang on job control / PS1.
return spawn("bash", ["--noprofile", "--norc"], {
cwd,
stdio: ["pipe", "pipe", "pipe"],
env: { ...process.env, TERM: "dumb", PS1: "", PS2: "" },
});
}
/** Get (or lazily create) the persistent shell session for a run key. */
export function getShellSession(key: string, cwd: string): ShellSession {
let s = shellSessions.get(key);
if (s && !s.proc.killed && s.proc.exitCode === null) return s;
if (s && !s.proc.killed && s.proc.exitCode === null && s.proc.stdin && !s.proc.stdin.destroyed) {
return s;
}
if (s) {
try { s.proc.kill(); } catch { /* ignore */ }
shellSessions.delete(key);
}
const proc = spawnSessionShell(cwd);
s = { proc, queue: Promise.resolve(), buffer: "" };
proc.stdout?.on("data", (d) => (s!.buffer += d));
proc.stderr?.on("data", (d) => (s!.buffer += d));
proc.stdout?.on("data", (d) => {
try { s!.buffer += d.toString(); } catch { /* ignore */ }
});
proc.stderr?.on("data", (d) => {
try { s!.buffer += d.toString(); } catch { /* ignore */ }
});
proc.on("error", () => {
/* keep buffer; next getShellSession recreates */
});
proc.on("exit", () => {
/* session is dead; next command will respawn */
});
// Prevent unhandled 'error' on stdin from crashing the extension host.
proc.stdin?.on("error", () => { /* ignore broken pipe */ });
shellSessions.set(key, s);
return s;
}
@@ -402,29 +463,56 @@ export function disposeShellSession(key: string): void {
const s = shellSessions.get(key);
if (s) {
try {
s.proc.kill();
} catch {}
if (process.platform === "win32") s.proc.kill();
else s.proc.kill("SIGKILL");
} catch { /* ignore */ }
shellSessions.delete(key);
}
}
/** Wait until the shell finishes, `pattern` matches its output, or `ms` elapses. */
/**
* Wait until the shell finishes, `pattern` matches its output, or `ms` elapses.
* Always resolves (never rejects). `ms <= 0` = one immediate pump + return.
*/
export function waitForShell(sh: BgShell, ms: number, pattern?: RegExp, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
const deadline = Date.now() + Math.max(0, ms);
const tick = () => {
try { sh.pump?.(); } catch { /* ignore */ }
if (signal?.aborted) {
if (!sh.done) {
sh.output += "\n(aborted)";
sh.done = true;
}
return resolve();
}
if (sh.done || (pattern && pattern.test(sh.output)) || Date.now() >= deadline) return resolve();
setTimeout(tick, 100);
let settled = false;
const finish = () => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
if (interval) clearInterval(interval);
signal?.removeEventListener("abort", onAbort);
resolve();
};
tick();
const onAbort = () => {
if (!sh.done) {
sh.output += "\n(aborted)";
sh.done = true;
}
finish();
};
if (signal?.aborted) {
onAbort();
return;
}
signal?.addEventListener("abort", onAbort, { once: true });
const deadline = Date.now() + Math.max(0, ms);
const check = () => {
try { sh.pump?.(); } catch { /* ignore */ }
if (sh.done) return finish();
if (pattern) {
try {
if (pattern.test(sh.output)) return finish();
} catch { /* bad pattern mid-wait */ }
}
if (ms <= 0 || Date.now() >= deadline) return finish();
};
// Hard wall-clock: never tick forever even if setInterval stalls.
const timer = setTimeout(finish, Math.max(ms, 0) + 250);
const interval = setInterval(check, 50);
check();
});
}
+186 -57
View File
@@ -16,12 +16,17 @@ import {
renderShell,
pushShellOutput,
getShellSession,
disposeShellSession,
type BgShell,
type ShellNotify,
} from "./shared";
const SENTINEL = "__OC_SHELL_DONE__";
const isWin = process.platform === "win32";
/** Default foreground wait for simple commands; hard max keeps the loop responsive. */
const DEFAULT_BLOCK_MS = 15_000;
const MAX_BLOCK_MS = 30_000;
const MAX_AWAIT_MS = 45_000;
/** Build a notify_on_output config from the tool input, if present. */
function buildNotify(input: any, ctx: any): ShellNotify | undefined {
@@ -42,25 +47,70 @@ function buildNotify(input: any, ctx: any): ShellNotify | undefined {
};
}
/**
* Frame a command so the session always prints a unique sentinel with exit code.
* PowerShell: use `if ($?)` — `$LASTEXITCODE` is often $null for native/cmdlets
* and would never emit a sentinel (classic hang).
*/
function wrapCommand(command: string, cd: string): string {
if (isWin) {
const loc = cd
? `Push-Location -LiteralPath '${cd.replace(/'/g, "''")}'; try { `
: "";
const endLoc = cd ? ` } finally { Pop-Location } ` : " ";
// Always write the sentinel, even if the command throws.
// Use [Console]::Out so the line is not stuck in PowerShell's output pipeline.
return (
`${loc}${command}${endLoc}\n` +
`if ($?) { [Console]::Out.WriteLine("${SENTINEL}:0") } else { ` +
`$__oc = if ($null -ne $LASTEXITCODE -and "$LASTEXITCODE" -ne "") { $LASTEXITCODE } else { 1 }; ` +
`[Console]::Out.WriteLine("${SENTINEL}:$__oc") }\n`
);
}
const push = cd ? `pushd '${cd.replace(/'/g, `'\\''`)}' >/dev/null 2>&1 || true\n` : "";
const pop = cd ? `popd >/dev/null 2>&1 || true\n` : "";
return (
`${push}${command}\n` +
`__oc_rc=$?\n` +
`${pop}` +
`echo "${SENTINEL}:$__oc_rc"\n`
);
}
// ---- Shell (stateful session; backgrounds a command past block_until_ms) ----
// A persistent shell per run keeps cwd/env across calls. Each command is framed
// by a sentinel echo so we can detect completion and capture the exit code.
export const runTerminalTool = defineTool("Shell", true, async (input, abortSignal, _callId, ctx) => {
const root = getWorkspaceRoot();
// Cap foreground wait: default 30s, hard max 90s so a hung command cannot
// block the agent loop. block_until_ms=0 still backgrounds immediately.
const rawBlock = typeof input.block_until_ms === "number" ? input.block_until_ms : 30_000;
const blockMs = rawBlock <= 0 ? 0 : Math.min(Math.max(0, rawBlock), 90_000);
const command = String(input.command ?? "");
const rawBlock = typeof input.block_until_ms === "number" ? input.block_until_ms : DEFAULT_BLOCK_MS;
const blockMs = rawBlock <= 0 ? 0 : Math.min(Math.max(0, rawBlock), MAX_BLOCK_MS);
const command = String(input.command ?? "").trim();
if (!command) return { output: "error: command is required" };
// Prune finished shells older than 10 minutes to bound the registry.
for (const [k, v] of bgShells) {
if (v.done && Date.now() - v.startedAt > 600_000) bgShells.delete(k);
}
// Persistent session keyed per run (falls back to a shared key if absent).
const sessionKey = (ctx as any)?.shellSessionKey ?? "default";
const session = getShellSession(sessionKey, root);
let session = getShellSession(sessionKey, root);
// Serialize commands on this session so sentinels don't interleave.
// Always settle the queue slot even if this command errors/times out.
let releaseQueue!: () => void;
const prev = session.queue.catch(() => {});
session.queue = new Promise<void>((r) => {
releaseQueue = r;
});
try {
// Never block forever on a stuck prior command's queue slot.
await Promise.race([
prev,
new Promise<void>((r) => setTimeout(r, MAX_BLOCK_MS + 5_000)),
]);
} catch {
/* ignore prior failure */
}
// Session may have been replaced while we waited.
session = getShellSession(sessionKey, root);
const sh: BgShell = {
id: nextShellId(),
@@ -74,92 +124,160 @@ export const runTerminalTool = defineTool("Shell", true, async (input, abortSign
};
bgShells.set(sh.id, sh);
// Mark where this command's output begins so we can slice the session buffer.
const startLen = session.buffer.length;
let lastSeen = startLen;
const sentinelRe = new RegExp(SENTINEL + ":(-?\\d+)");
// Drain this command's slice of the session buffer into the BgShell and
// detect the sentinel (printed with the exit code) marking completion.
// Stored on `sh` so AwaitShell can keep draining after we background.
sh.pump = () => {
if (session.buffer.length > lastSeen) {
pushShellOutput(sh, session.buffer.slice(lastSeen));
lastSeen = session.buffer.length;
}
const m = sh.output.match(sentinelRe);
if (m && !sh.done) {
sh.exitCode = Number(m[1]);
sh.done = true;
try {
if (session.buffer.length > lastSeen) {
pushShellOutput(sh, session.buffer.slice(lastSeen));
lastSeen = session.buffer.length;
}
const m = sh.output.match(sentinelRe);
if (m && !sh.done) {
sh.exitCode = Number(m[1]);
sh.done = true;
}
// Dead process with no sentinel → force complete so we never hang.
if (!sh.done && (session.proc.killed || session.proc.exitCode != null)) {
sh.exitCode = session.proc.exitCode ?? 1;
sh.done = true;
sh.output += "\n(shell session exited)";
}
} catch (e) {
if (!sh.done) {
sh.done = true;
sh.exitCode = 1;
sh.output += `\n(pump error: ${e instanceof Error ? e.message : String(e)})`;
}
}
};
const pumpTimer = setInterval(() => sh.pump?.(), 100);
const killSession = () => {
try {
if (process.platform === "win32") session.proc.kill();
else session.proc.kill("SIGTERM");
} catch { /* ignore */ }
disposeShellSession(sessionKey);
} catch {
/* ignore */
}
};
const onAbort = () => {
if (!sh.done) {
sh.output += "\n(aborted)";
sh.done = true;
sh.exitCode = sh.exitCode ?? 130;
}
killSession();
};
abortSignal?.addEventListener("abort", onAbort);
// Optional per-command working directory (a `cd` that does not persist).
const cd = input.working_directory ? safePath(input.working_directory) : "";
const wrapped = isWin
? `${cd ? `Push-Location -LiteralPath '${cd.replace(/'/g, "''")}'; ` : ""}${command}${cd ? "; Pop-Location" : ""}\nWrite-Output "${SENTINEL}:$LASTEXITCODE"\n`
: `${cd ? `pushd '${cd.replace(/'/g, "'\\''")}' && ` : ""}${command}\n__oc_rc=$?\n${cd ? "popd >/dev/null 2>&1\n" : ""}echo "${SENTINEL}:$__oc_rc"\n`;
const wrapped = wrapCommand(command, cd);
try {
session.proc.stdin?.write(wrapped);
const stdin = session.proc.stdin;
if (!stdin || stdin.destroyed) {
killSession();
session = getShellSession(sessionKey, root);
sh.proc = session.proc;
}
const ok = session.proc.stdin?.write(wrapped);
if (ok === false) {
// Backpressure: wait briefly for drain, then continue (pump still works).
await new Promise<void>((r) => {
const t = setTimeout(r, 2_000);
session.proc.stdin?.once("drain", () => {
clearTimeout(t);
r();
});
});
}
} catch (e) {
clearInterval(pumpTimer);
abortSignal?.removeEventListener("abort", onAbort);
sh.done = true;
return { output: `error: shell write failed: ${e instanceof Error ? e.message : String(e)}` };
sh.exitCode = 1;
releaseQueue();
return {
output: `error: shell write failed: ${e instanceof Error ? e.message : String(e)}`,
};
}
await waitForShell(sh, blockMs, undefined, abortSignal);
sh.pump?.();
clearInterval(pumpTimer);
abortSignal?.removeEventListener("abort", onAbort);
try {
await waitForShell(sh, blockMs, undefined, abortSignal);
try {
sh.pump?.();
} catch {
/* ignore */
}
// Hard timeout with no sentinel: mark done so AwaitShell does not hang, and
// note that the process may still be running in the session.
if (!sh.done && blockMs > 0) {
sh.output += `\n(timeout after ${blockMs}ms — command still running in background shell ${sh.id}; use AwaitShell or cancel)`;
// Timed out with no sentinel: do NOT leave a hung command poisoning the
// session — kill and respawn so the next Shell call is clean.
if (!sh.done && blockMs > 0) {
sh.output += `\n(timeout after ${blockMs}ms — session reset; re-run with a shorter command or block_until_ms=0 to background)`;
sh.done = true;
sh.exitCode = sh.exitCode ?? 124;
killSession();
} else if (!sh.done && blockMs === 0) {
// Immediate background: keep pumping via interval until done/timeout later.
const bgPump = setInterval(() => {
try {
sh.pump?.();
} catch {
/* ignore */
}
if (sh.done) clearInterval(bgPump);
}, 100);
// Hard stop background pump after 10 min.
setTimeout(() => clearInterval(bgPump), 600_000).unref?.();
}
// Strip the sentinel line from the rendered body.
sh.output = sh.output.replace(new RegExp("\\n?" + SENTINEL + ":-?\\d+\\s*"), "");
return { output: renderShell(sh) };
} catch (e) {
if (!sh.done) {
sh.done = true;
sh.exitCode = 1;
sh.output += `\n(error: ${e instanceof Error ? e.message : String(e)})`;
}
killSession();
return { output: renderShell(sh) };
} finally {
abortSignal?.removeEventListener("abort", onAbort);
releaseQueue();
}
// Strip the sentinel line from the rendered body.
sh.output = sh.output.replace(new RegExp("\\n?" + SENTINEL + ":-?\\d+\\s*"), "");
return { output: renderShell(sh) };
});
// ---- AwaitShell (poll a backgrounded shell, or just sleep) ----
export const awaitShellTool = defineTool("AwaitShell", false, async (input) => {
const blockMs = typeof input?.block_until_ms === "number" ? input.block_until_ms : 30_000;
export const awaitShellTool = defineTool("AwaitShell", false, async (input, abortSignal) => {
const raw = typeof input?.block_until_ms === "number" ? input.block_until_ms : 15_000;
const blockMs = raw <= 0 ? 0 : Math.min(raw, MAX_AWAIT_MS);
const id = input?.shell_id ? String(input.shell_id) : "";
// No shell id: sleep for the full duration (renders nicely vs. sleeping in the
// shell). shell_id is required for a non-blocking status check (block_until_ms 0).
if (!id) {
if (blockMs <= 0) return { output: "error: shell_id is required when block_until_ms is 0" };
await new Promise((r) => setTimeout(r, blockMs));
await new Promise<void>((r) => {
const t = setTimeout(r, blockMs);
const onAbort = () => {
clearTimeout(t);
r();
};
if (abortSignal?.aborted) {
clearTimeout(t);
r();
return;
}
abortSignal?.addEventListener("abort", onAbort, { once: true });
});
return { output: `Slept for ${blockMs}ms.` };
}
const sh = bgShells.get(id);
if (!sh) {
// A common misuse is passing a Task/subagent call id (e.g. "toolu_…"). Subagents
// are NOT shells; they stream their own events and are awaited automatically
// before the turn ends, so there is nothing to poll here.
if (/^toolu_|^call_/i.test(id)) {
return { output: `error: "${id}" looks like a subagent/Task call id, not a background shell. Subagents are not shells — do not poll them with AwaitShell. They stream results on their own and are awaited automatically before your turn ends; just continue or finish.` };
return {
output: `error: "${id}" looks like a subagent/Task call id, not a background shell. Subagents are not shells — do not poll them with AwaitShell.`,
};
}
return { output: `error: no background shell with id ${id}` };
}
@@ -172,8 +290,19 @@ export const awaitShellTool = defineTool("AwaitShell", false, async (input) => {
return { output: `error: invalid pattern: ${e instanceof Error ? e.message : String(e)}` };
}
}
// Cap AwaitShell polls too so a stuck bg job cannot hang the loop forever.
const capped = blockMs <= 0 ? 0 : Math.min(blockMs, 120_000);
await waitForShell(sh, capped, pattern);
return { output: renderShell(sh) };
try {
await waitForShell(sh, blockMs, pattern, abortSignal);
try {
sh.pump?.();
} catch {
/* ignore */
}
sh.output = sh.output.replace(new RegExp("\\n?" + SENTINEL + ":-?\\d+\\s*"), "");
return { output: renderShell(sh) };
} catch (e) {
return {
output: `error: AwaitShell failed: ${e instanceof Error ? e.message : String(e)}`,
};
}
});
+20 -20
View File
@@ -80,28 +80,28 @@ const NAV: { id: Section; label: string; icon: IconName; sep?: boolean }[] = [
/** Built-in tool hard timeouts (seconds). Keep in sync with src/agent/tools/shared.ts. */
const TOOL_TIMEOUT_DEFAULTS: { name: string; sec: number }[] = [
{ name: "Shell", sec: 120 },
{ name: "AwaitShell", sec: 150 },
{ name: "Grep", sec: 30 },
{ name: "Glob", sec: 30 },
{ name: "FileSearch", sec: 20 },
{ name: "SemanticSearch", sec: 45 },
{ name: "SearchDocs", sec: 30 },
{ name: "ListDir", sec: 15 },
{ name: "Read", sec: 30 },
{ name: "ReadLints", sec: 20 },
{ name: "WebSearch", sec: 25 },
{ name: "WebFetch", sec: 30 },
{ name: "StrReplace", sec: 30 },
{ name: "Write", sec: 30 },
{ name: "Delete", sec: 15 },
{ name: "EditNotebook", sec: 30 },
{ name: "CallMcpTool", sec: 60 },
{ name: "FetchMcpResource", sec: 45 },
{ name: "ListMcpResources", sec: 20 },
{ name: "Shell", sec: 45 },
{ name: "AwaitShell", sec: 60 },
{ name: "Grep", sec: 20 },
{ name: "Glob", sec: 20 },
{ name: "FileSearch", sec: 15 },
{ name: "SemanticSearch", sec: 30 },
{ name: "SearchDocs", sec: 25 },
{ name: "ListDir", sec: 10 },
{ name: "Read", sec: 20 },
{ name: "ReadLints", sec: 15 },
{ name: "WebSearch", sec: 20 },
{ name: "WebFetch", sec: 25 },
{ name: "StrReplace", sec: 20 },
{ name: "Write", sec: 20 },
{ name: "Delete", sec: 10 },
{ name: "EditNotebook", sec: 20 },
{ name: "CallMcpTool", sec: 45 },
{ name: "FetchMcpResource", sec: 30 },
{ name: "ListMcpResources", sec: 15 },
{ name: "TodoWrite", sec: 5 },
{ name: "TodoRead", sec: 5 },
{ name: "WritePlan", sec: 15 },
{ name: "WritePlan", sec: 10 },
{ name: "SwitchMode", sec: 5 },
];