Skip to content

Agent Zero AI framework

Fix native Windows TTY cleanup

Alessandro95ba588abc0d
diff --git a/plugins/_code_execution/AGENTS.md b/plugins/_code_execution/AGENTS.md
index fbf54eefa..0e5de63bc 100644
--- a/plugins/_code_execution/AGENTS.md
+++ b/plugins/_code_execution/AGENTS.md
@@ -22,6 +22,7 @@
- Terminal reset/close must not hang on foreground commands or shells that ignore SIGTERM.
- POSIX PTY I/O is nonblocking. The existing write/drain interface buffers partial writes and yields while the terminal is full; cancellation discards the shell only while POSIX input bytes remain unsent. Fully drained sends retain the shell and its state.
- TTY destruction uses best-effort kill, never nested event-loop execution; explicit close retains awaited cleanup.
+- Windows cleanup uses the native process methods without looking up POSIX-only signals; the pywinpty adapter passes SIGTERM for forced termination. POSIX close retains process-group TERM-then-KILL escalation.
- Local and SSH session wrappers must synchronously release their owned process or connection resources when discarded.
- Explicitly target local versus SSH execution runtimes.
- The tool's `allow_running` flag is framework-set (for example by the `input` tool's terminal dispatch); it is not a model-facing arg and stays undocumented in prompts.
diff --git a/plugins/_code_execution/helpers/tty_session.py b/plugins/_code_execution/helpers/tty_session.py
index 688b36cfb..292f0b349 100644
--- a/plugins/_code_execution/helpers/tty_session.py
+++ b/plugins/_code_execution/helpers/tty_session.py
@@ -76,11 +76,11 @@ class TTYSession:
# Terminate the process if it exists
if self._proc:
if getattr(self._proc, "returncode", None) is None:
- self._signal_process(signal.SIGTERM)
+ self._signal_process()
try:
await asyncio.wait_for(self._proc.wait(), _CLOSE_TIMEOUT_SECONDS)
except asyncio.TimeoutError:
- self._signal_process(signal.SIGKILL)
+ self._signal_process(force=True)
try:
await asyncio.wait_for(self._proc.wait(), _CLOSE_TIMEOUT_SECONDS)
except Exception:
@@ -92,22 +92,22 @@ class TTYSession:
self._proc = None
self._pump_task = None
- def _signal_process(self, sig):
+ def _signal_process(self, force=False):
if self._proc is None:
return
try:
if _IS_WIN:
- if sig == signal.SIGKILL:
+ if force:
self._proc.kill()
else:
self._proc.terminate()
return
- os.killpg(self._proc.pid, sig)
+ os.killpg(self._proc.pid, signal.SIGKILL if force else signal.SIGTERM)
except ProcessLookupError:
pass
except Exception:
try:
- if sig == signal.SIGKILL:
+ if force:
self._proc.kill()
else:
self._proc.terminate()
@@ -203,7 +203,7 @@ class TTYSession:
# Only attempt to kill if the process is still running
if getattr(self._proc, "returncode", None) is None:
- self._signal_process(signal.SIGKILL)
+ self._signal_process(force=True)
self._release_pty_master()
async def read(self, timeout=None):
@@ -419,7 +419,7 @@ async def _spawn_winpty(cmd, cwd, env, echo):
def kill(self):
if child.isalive():
- child.kill()
+ child.kill(signal.SIGTERM)
return _Proc()
diff --git a/tests/test_tty_session_io.py b/tests/test_tty_session_io.py
index 77a6c66a4..c567db4b8 100644
--- a/tests/test_tty_session_io.py
+++ b/tests/test_tty_session_io.py
@@ -7,6 +7,7 @@ from pathlib import Path
import signal
import subprocess
import sys
+from types import SimpleNamespace
import pytest
@@ -184,5 +185,58 @@ def test_tty_io_keeps_shared_loop_responsive(case):
pass
[email protected]('operation', ['close', 'resistant_close', 'kill', 'destructor'])
+def test_windows_cleanup_without_posix_signals(monkeypatch, operation):
+ from plugins._code_execution.helpers import tty_session
+
+ calls = []
+
+ class Child:
+ pid = 123
+ alive = True
+
+ def isalive(self):
+ return self.alive
+
+ def read(self, size):
+ raise EOFError
+
+ def terminate(self):
+ calls.append('terminate')
+ if operation != 'resistant_close':
+ self.alive = False
+
+ def kill(self, sig):
+ assert sig == 15
+ calls.append('kill')
+ self.alive = False
+
+ child = Child()
+ monkeypatch.setattr(tty_session, '_IS_WIN', True)
+ monkeypatch.setattr(tty_session, 'signal', SimpleNamespace(SIGTERM=15))
+ monkeypatch.setattr(tty_session, '_CLOSE_TIMEOUT_SECONDS', .01)
+ monkeypatch.setattr(tty_session, 'winpty', SimpleNamespace(
+ PtyProcess=SimpleNamespace(spawn=lambda *args, **kwargs: child)), raising=False)
+
+ async def run():
+ session = TTYSession('powershell.exe')
+ await session.start()
+ try:
+ if operation in ('close', 'resistant_close'):
+ await session.close()
+ elif operation == 'kill':
+ session.kill()
+ else:
+ session.__del__()
+ assert not child.alive
+ assert calls == (['terminate', 'kill'] if operation == 'resistant_close'
+ else ['terminate'] if operation == 'close' else ['kill'])
+ finally:
+ child.alive = False
+ await session.close()
+
+ asyncio.run(run())
+
+
if __name__ == '__main__':
asyncio.run(globals()[sys.argv[1]]())