The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(hooks): reap the hook process tree when _spawn is interrupted
yotamleobca94759d581
diff --git a/agent/shell_hooks.py b/agent/shell_hooks.pyindex 6832b308562..486efa9343a 100644--- a/agent/shell_hooks.py+++ b/agent/shell_hooks.py@@ -317,10 +317,14 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]:return failed(next((msg for cls, msg in _POPEN_ERRORS if isinstance(exc, cls)), str(exc)))try:stdout, stderr = proc.communicate(input=stdin_json, timeout=spec.timeout)- except Exception as exc:+ except BaseException as exc:+ # BaseException, not Exception: Ctrl+C raises KeyboardInterrupt here, and the hook leads its own+ # process group (above), so the terminal's SIGINT never reaches it — it would keep running.kill_process_tree(proc) # the whole tree — forked helpers holding the pipes would stall the drainwith suppress(Exception):proc.communicate(timeout=1)+ if not isinstance(exc, Exception): # KeyboardInterrupt / SystemExit: reap the hook, then propagate+ raiseif not isinstance(exc, subprocess.TimeoutExpired): # pragma: no cover — defensivereturn failed(str(exc))result.update(timed_out=True, elapsed_seconds=round(time.monotonic() - t0, 3))diff --git a/tests/agent/test_shell_hooks_tree_kill.py b/tests/agent/test_shell_hooks_tree_kill.pyindex 942f51e9203..a6c26588a28 100644--- a/tests/agent/test_shell_hooks_tree_kill.py+++ b/tests/agent/test_shell_hooks_tree_kill.py@@ -13,8 +13,10 @@ semantics cannot be mocked."""import os+import signalimport sysimport textwrap+import threadingimport timeimport pytest@@ -154,6 +156,42 @@ def test_fast_path_contract_unchanged(tmp_path):assert r["timed_out"] is False+def test_interrupt_kills_hook_and_propagates(tmp_path):+ """Ctrl+C during a hook must reap the hook, then let KeyboardInterrupt through.++ The hook leads its own process group, so the terminal's SIGINT never+ reaches it: only ``_spawn``'s own cleanup can stop it.+ """+ marker = tmp_path / "hook.pid"+ script = tmp_path / "hook.sh"+ script.write_text(f"#!/bin/bash\necho $$ > {marker}\nsleep 300\n")+ script.chmod(0o755)++ def interrupt_once_running():+ """Interrupt only once the hook is up, so the signal lands inside _spawn."""+ deadline = time.monotonic() + 5.0+ while time.monotonic() < deadline:+ if marker.exists() and marker.read_text().strip():+ os.kill(os.getpid(), signal.SIGINT)+ return+ time.sleep(0.05)++ interrupter = threading.Thread(target=interrupt_once_running, daemon=True)+ interrupter.start()+ with pytest.raises(KeyboardInterrupt):+ _spawn(_spec(str(script), timeout=300), "{}")+ interrupter.join(timeout=5)++ hook_pid = _read_marker(marker)+ deadline = time.monotonic() + 3.0+ while time.monotonic() < deadline and _pid_alive(hook_pid):+ time.sleep(0.05)+ alive = _pid_alive(hook_pid)+ if alive: # cleanup so a failure doesn't leak a 300s sleeper+ os.kill(hook_pid, 9)+ assert not alive, f"hook {hook_pid} survived the interrupt"++def test_missing_command_still_fails_open():r = _spawn(_spec("/nonexistent/hook-command-xyz", timeout=2), "{}")assert r["error"] == "command not found"