Agent Zero AI framework
merge dev to handle-code-running-session
linuztx8ad6f89a756b
diff --cc python/helpers/shell_local.pyindex e610e78ed,cc0815f10..2f682b320--- a/python/helpers/shell_local.py+++ b/python/helpers/shell_local.py@@@ -6,46 -8,27 +8,29 @@@ from python.helpers.shell_ssh import clclass LocalInteractiveSession:def __init__(self):- self.process = None+ self.session: tty_session.TTYSession|None = Noneself.full_output = ''++ self.is_running = Falseasync def connect(self):- # Start a new subprocess with the appropriate shell for the OS- if sys.platform.startswith('win'):- # Windows- self.process = subprocess.Popen(- ['cmd.exe'],- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- bufsize=1- )- else:- # macOS and Linux- self.process = subprocess.Popen(- ['/bin/bash'],- stdin=subprocess.PIPE,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- text=True,- bufsize=1- )+ self.session = tty_session.TTYSession("/bin/bash")+ await self.session.start()+ await self.session.read_full_until_idle(idle_timeout=1, total_timeout=1)- def close(self):- if self.process:- self.process.terminate()- self.process.wait()+ async def close(self):+ if self.session:+ self.session.kill()+ # self.session.wait()- def send_command(self, command: str):- if not self.process:+ async def send_command(self, command: str):+ if not self.session:raise Exception("Shell not connected")self.full_output = ""- self.process.stdin.write(command + '\n') # type: ignore- self.process.stdin.flush() # type: ignore+ await self.session.sendline(command)++ self.is_running = Trueasync def read_output(self, timeout: float = 0, reset_full_output: bool = False) -> Tuple[str, Optional[str]]:- if not self.process:+ if not self.session:raise Exception("Shell not connected")if reset_full_output:diff --cc python/helpers/shell_ssh.pyindex d22e125fa,4d4afe1c3..09f0fb338--- a/python/helpers/shell_ssh.py+++ b/python/helpers/shell_ssh.py@@@ -27,10 -27,17 +27,18 @@@ class SSHInteractiveSessionself.full_output = b""self.last_command = b""self.trimmed_command_length = 0 # Initialize trimmed_command_length+ self.is_running = False- async def connect(self):- # try 3 times with wait and then except+ async def connect(self, keepalive_interval: int = 5):+ """+ Establish the SSH connection and start an interactive shell.++ Parameters+ ----------+ keepalive_interval : int+ Interval in **seconds** between keep-alive packets sent by Paramiko.+ A value ≤ 0 disables Paramiko’s keep-alive feature.+ """errors = 0while True:try:diff --cc python/tools/code_execution_tool.pyindex d187fc1f9,18d6f8c93..b67596600--- a/python/tools/code_execution_tool.py+++ b/python/tools/code_execution_tool.py@@@ -21,31 -20,12 +20,27 @@@ class Stateclass CodeExecution(Tool):- async def execute(self, **kwargs):+ # Common shell prompt regex patterns (add more as needed)+ prompt_patterns = [+ re.compile(r"\\(venv\\).+[$#] ?$"), # (venv) ...$ or (venv) ...#+ re.compile(r"root@[^:]+:[^#]+# ?$"), # root@container:~#+ re.compile(r"[a-zA-Z0-9_.-]+@[^:]+:[^$#]+[$#] ?$"), # user@host:~$+ ]+ # potential dialog detection+ dialog_patterns = [+ re.compile(r"Y/N", re.IGNORECASE), # Y/N anywhere in line+ re.compile(r"yes/no", re.IGNORECASE), # yes/no anywhere in line+ re.compile(r":\s*$"), # line ending with colon+ re.compile(r"\?\s*$"), # line ending with question mark+ ]+- async def execute(self, **kwargs):++ async def execute(self, **kwargs) -> Response:await self.agent.handle_intervention() # wait for intervention and handle it, if paused- await self.prepare_state()-- # os.chdir(files.get_abs_path("./work_dir")) #change CWD to work_dir-runtime = self.args.get("runtime", "").lower().strip()session = int(self.args.get("session", 0))+ self.allow_running = bool(self.args.get("allow_running", False))if runtime == "python":response = await self.execute_python_code(@@@ -171,13 -140,9 +155,15 @@@self, session: int, command: str, reset: bool = False, prefix: str = ""):+ self.state = await self.prepare_state(reset=reset, session=session)+await self.agent.handle_intervention() # wait for intervention and handle it, if paused++ # Check if session is running and handle it+ if not self.allow_running:+ if response := await self.handle_running_session(session):+ return response+# try again on lost connectionfor i in range(2):try:@@@ -246,21 -199,21 +220,8 @@@# if not self.state:self.state = await self.prepare_state(session=session)-- # Common shell prompt regex patterns (add more as needed)-- prompt_patterns = [-- re.compile(r"\\(venv\\).+[$#] ?$"), # (venv) ...$ or (venv) ...#-- re.compile(r"root@[^:]+:[^#]+# ?$"), # root@container:~#-- re.compile(r"[a-zA-Z0-9_.-]+@[^:]+:[^$#]+[$#] ?$"), # user@host:~$-- ]---- # potential dialog detection-- dialog_patterns = [-- re.compile(r"Y/N", re.IGNORECASE), # Y/N anywhere in line-- re.compile(r"yes/no", re.IGNORECASE), # yes/no anywhere in line-- re.compile(r":\s*$"), # line ending with colon-- re.compile(r"\?\s*$"), # line ending with question mark-- ]-+++start_time = time.time()last_output_time = start_timefull_output = ""@@@ -376,63 -328,6 +337,69 @@@)return response+ async def handle_running_session(+ self,+ session=0,+ reset_full_output=False,+ prefix=""+ ):++ state = getattr(self, "state", None)++ if not state:++ return None+ if not (- session in self.state.shells- and getattr(self.state.shells[session], "is_running", False)++ session in state.shells++ and getattr(state.shells[session], "is_running", False)+ ):+ return None+- full_output, _ = await self.state.shells[session].read_output(++ full_output, _ = await state.shells[session].read_output(+ timeout=1, reset_full_output=reset_full_output+ )+ truncated_output = self.fix_full_output(full_output)+ heading = self.get_heading_from_output(truncated_output, 0)++ last_lines = (+ truncated_output.splitlines()[-3:] if truncated_output else []+ )+ last_lines.reverse()+ for idx, line in enumerate(last_lines):+ for pat in self.prompt_patterns:+ if pat.search(line.strip()):+ PrintStyle.info(+ "Detected shell prompt, returning output early."+ )+ self.mark_session_idle(session)+ return None++ has_dialog = False+ for line in last_lines:+ for pat in self.dialog_patterns:+ if pat.search(line.strip()):+ has_dialog = True+ break+ if has_dialog:+ break++ if has_dialog:+ sys_info = self.agent.read_prompt("fw.code.pause_dialog.md", timeout=1)+ else:+ sys_info = self.agent.read_prompt("fw.code.running.md", session=session)++ response = self.agent.read_prompt("fw.code.info.md", info=sys_info)+ if truncated_output:+ response = truncated_output + "\n\n" + response+ PrintStyle(font_color="#FFA500", bold=True).print(response)+ self.log.update(content=prefix + response, heading=heading)+ return response++ def mark_session_idle(self, session: int = 0):+ # Mark session as idle - command finished- if session in self.state.shells:- self.state.shells[session].is_running = False++ state = getattr(self, "state", None)++ if state and session in state.shells:++ shell = state.shells[session]++ if hasattr(shell, "is_running"):++ shell.is_running = False+async def reset_terminal(self, session=0, reason: str | None = None):# Print the reason for the reset to the console if providedif reason: