From 82360f200b4ee02ad9bae39c6e26aed987f1bea9 Mon Sep 17 00:00:00 2001 From: KyleChen26 Date: Tue, 10 Feb 2026 12:33:31 +0800 Subject: [PATCH] fix: prevent FD leaks in child process cleanup - Destroy stdio streams (stdin/stdout/stderr) after process exit - Remove event listeners to prevent memory leaks - Clean up child process reference in moveToFinished() - Also fixes model override handling in agent.ts Fixes EBADF errors caused by accumulating file descriptors from sub-agent spawns. --- src/agents/bash-process-registry.ts | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/agents/bash-process-registry.ts b/src/agents/bash-process-registry.ts index 5d48da89ce5..dd3ace1d2a5 100644 --- a/src/agents/bash-process-registry.ts +++ b/src/agents/bash-process-registry.ts @@ -157,6 +157,38 @@ export function markBackgrounded(session: ProcessSession) { function moveToFinished(session: ProcessSession, status: ProcessStatus) { runningSessions.delete(session.id); + + // Clean up child process stdio streams to prevent FD leaks + if (session.child) { + // Destroy stdio streams to release file descriptors + session.child.stdin?.destroy?.(); + session.child.stdout?.destroy?.(); + session.child.stderr?.destroy?.(); + + // Remove all event listeners to prevent memory leaks + session.child.removeAllListeners(); + + // Clear the reference + delete session.child; + } + + // Clean up stdin wrapper - call destroy if available, otherwise just remove reference + if (session.stdin) { + // Try to call destroy/end method if exists + if (typeof session.stdin.destroy === "function") { + session.stdin.destroy(); + } else if (typeof session.stdin.end === "function") { + session.stdin.end(); + } + // Only set flag if writable + try { + (session.stdin as { destroyed?: boolean }).destroyed = true; + } catch { + // Ignore if read-only + } + delete session.stdin; + } + if (!session.backgrounded) { return; }