Skip to content

Agent Zero AI framework

fix(code_execution): recover from closed PTY sessions

Agent Zero Locala0f0c2e8d2ca
diff --git a/plugins/_code_execution/helpers/tty_session.py b/plugins/_code_execution/helpers/tty_session.py
index d39537ae1..bd8013d79 100644
--- a/plugins/_code_execution/helpers/tty_session.py
+++ b/plugins/_code_execution/helpers/tty_session.py
@@ -97,10 +97,20 @@ class TTYSession:
async def send(self, data: str | bytes):
if self._proc is None:
raise RuntimeError("TTYSpawn is not started")
+ if self._pty_master is None and not _IS_WIN:
+ raise RuntimeError("TTYSpawn PTY is closed")
+ if getattr(self._proc, "returncode", None) is not None:
+ raise RuntimeError("TTYSpawn process has exited")
if isinstance(data, str):
data = data.encode(self.encoding)
- self._proc.stdin.write(data) # type: ignore
- await self._proc.stdin.drain() # type: ignore
+ try:
+ self._proc.stdin.write(data) # type: ignore
+ await self._proc.stdin.drain() # type: ignore
+ except OSError as e:
+ if e.errno in (errno.EBADF, errno.EIO, errno.EINVAL):
+ self._pty_master = None
+ raise RuntimeError("TTYSpawn PTY is closed") from e
+ raise
async def sendline(self, line: str):
await self.send(line + "\n")
diff --git a/plugins/_code_execution/tools/code_execution_tool.py b/plugins/_code_execution/tools/code_execution_tool.py
index 6ebec1d61..45566b00f 100644
--- a/plugins/_code_execution/tools/code_execution_tool.py
+++ b/plugins/_code_execution/tools/code_execution_tool.py
@@ -194,12 +194,11 @@ class CodeExecution(Tool):
)
except Exception as e:
- if i == 1:
- PrintStyle.error(str(e))
- await self.prepare_state(cfg, reset=True, session=session)
+ PrintStyle.error(str(e))
+ await self.prepare_state(cfg, reset=True, session=session)
+ if i == 0:
continue
- else:
- raise e
+ raise e
def format_command_for_output(self, command: str):
short_cmd = command[:250]