Agent Zero AI framework
windows tty
frdel786f51ca270b
diff --git a/python/helpers/runtime.py b/python/helpers/runtime.pyindex 53c998bc1..2120b36cf 100644--- a/python/helpers/runtime.py+++ b/python/helpers/runtime.py@@ -7,9 +7,10 @@ from python.helpers import dotenv, rfc, settings, filesimport asyncioimport threadingimport queue+import sys-T = TypeVar('T')-R = TypeVar('R')+T = TypeVar("T")+R = TypeVar("R")parser = argparse.ArgumentParser()args = {}@@ -41,31 +42,38 @@ def initialize():key = key.lstrip("-")args[key] = value+def get_arg(name: str):global argsreturn args.get(name, None)+def has_arg(name: str):global argsreturn name in args+def is_dockerized() -> bool:return bool(get_arg("dockerized"))+def is_development() -> bool:return not is_dockerized()+def get_local_url():if is_dockerized():return "host.docker.internal"return "127.0.0.1"+def get_runtime_id() -> str:global runtime_idif not runtime_id:- runtime_id = secrets.token_hex(8)+ runtime_id = secrets.token_hex(8)return runtime_id+def get_persistent_id() -> str:id = dotenv.get_dotenv_value("A0_PERSISTENT_RUNTIME_ID")if not id:@@ -73,19 +81,28 @@ def get_persistent_id() -> str:dotenv.save_dotenv_value("A0_PERSISTENT_RUNTIME_ID", id)return id+@overload-async def call_development_function(func: Callable[..., Awaitable[T]], *args, **kwargs) -> T: ...+async def call_development_function(+ func: Callable[..., Awaitable[T]], *args, **kwargs+) -> T: ...+@overloadasync def call_development_function(func: Callable[..., T], *args, **kwargs) -> T: ...-async def call_development_function(func: Union[Callable[..., T], Callable[..., Awaitable[T]]], *args, **kwargs) -> T:++async def call_development_function(+ func: Union[Callable[..., T], Callable[..., Awaitable[T]]], *args, **kwargs+) -> T:if is_development():url = _get_rfc_url()password = _get_rfc_password()# Normalize path components to build a valid Python module path across OSes- module_path = Path(files.deabsolute_path(func.__code__.co_filename)).with_suffix("")- module = ".".join(module_path.parts) # __module__ is not reliable+ module_path = Path(+ files.deabsolute_path(func.__code__.co_filename)+ ).with_suffix("")+ module = ".".join(module_path.parts) # __module__ is not reliableresult = await rfc.call_rfc(url=url,password=password,@@ -99,7 +116,7 @@ async def call_development_function(func: Union[Callable[..., T], Callable[...,if inspect.iscoroutinefunction(func):return await func(*args, **kwargs)else:- return func(*args, **kwargs) # type: ignore+ return func(*args, **kwargs) # type: ignoreasync def handle_rfc(rfc_call: rfc.RFCCall):@@ -117,45 +134,61 @@ def _get_rfc_url() -> str:set = settings.get_settings()url = set["rfc_url"]if not "://" in url:- url = "http://"+url+ url = "http://" + urlif url.endswith("/"):url = url[:-1]- url = url+":"+str(set["rfc_port_http"])+ url = url + ":" + str(set["rfc_port_http"])url += "/rfc"return url-def call_development_function_sync(func: Union[Callable[..., T], Callable[..., Awaitable[T]]], *args, **kwargs) -> T:+def call_development_function_sync(+ func: Union[Callable[..., T], Callable[..., Awaitable[T]]], *args, **kwargs+) -> T:# run async function in sync mannerresult_queue = queue.Queue()-+def run_in_thread():result = asyncio.run(call_development_function(func, *args, **kwargs))result_queue.put(result)-+thread = threading.Thread(target=run_in_thread)thread.start()thread.join(timeout=30) # wait for thread with timeout-+if thread.is_alive():raise TimeoutError("Function call timed out after 30 seconds")-+result = result_queue.get_nowait()return cast(T, result)def get_web_ui_port():web_ui_port = (- get_arg("port")- or int(dotenv.get_dotenv_value("WEB_UI_PORT", 0))- or 5000+ get_arg("port") or int(dotenv.get_dotenv_value("WEB_UI_PORT", 0)) or 5000)return web_ui_port+def get_tunnel_api_port():tunnel_api_port = (get_arg("tunnel_api_port")or int(dotenv.get_dotenv_value("TUNNEL_API_PORT", 0))or 55520)- return tunnel_api_port\ No newline at end of file+ return tunnel_api_port+++def get_platform():+ return sys.platform+++def is_windows():+ return get_platform() == "win32"+++def get_terminal_executable():+ if is_windows():+ return "powershell.exe"+ else:+ return "/bin/bash"diff --git a/python/helpers/shell_local.py b/python/helpers/shell_local.pyindex 226d78021..dcc14398d 100644--- a/python/helpers/shell_local.py+++ b/python/helpers/shell_local.py@@ -1,9 +1,10 @@+import platformimport selectimport subprocessimport timeimport sysfrom typing import Optional, Tuple-from python.helpers import tty_session+from python.helpers import tty_session, runtimefrom python.helpers.shell_ssh import clean_stringclass LocalInteractiveSession:@@ -13,7 +14,7 @@ class LocalInteractiveSession:self.cwd = cwdasync def connect(self):- self.session = tty_session.TTYSession("/bin/bash", cwd=self.cwd)+ self.session = tty_session.TTYSession(runtime.get_terminal_executable(), cwd=self.cwd)await self.session.start()await self.session.read_full_until_idle(idle_timeout=1, total_timeout=1)diff --git a/python/helpers/tty_session.py b/python/helpers/tty_session.pyindex 4fbc33086..d6a3f91a6 100644--- a/python/helpers/tty_session.py+++ b/python/helpers/tty_session.py@@ -204,55 +204,66 @@ async def _spawn_posix_pty(cmd, cwd, env, echo):async def _spawn_winpty(cmd, cwd, env, echo):- # A quick way to silence command echo in cmd.exe is /Q (quiet)- if not echo and cmd.strip().lower().startswith("cmd") and "/q" not in cmd.lower():- cmd = cmd.replace("cmd.exe", "cmd.exe /Q")+ # Clean PowerShell startup: no logo, no profile, bypass execution policy for deterministic behavior+ if cmd.strip().lower().startswith("powershell"):+ if "-nolog" not in cmd.lower():+ cmd = cmd.replace("powershell.exe", "powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass", 1)cols, rows = 80, 25- pty = winpty.PTY(cols, rows) # type: ignore- # winpty expects env as None or list of "KEY=VALUE" strings, not a dict- winpty_env = None if env is None else [f"{k}={v}" for k, v in env.items()]- child = pty.spawn(cmd, cwd=cwd or os.getcwd(), env=winpty_env)-- master_r_fd = msvcrt.open_osfhandle(child.conout_pipe, os.O_RDONLY) # type: ignore- master_w_fd = msvcrt.open_osfhandle(child.conin_pipe, 0) # type: ignore+ child = winpty.PtyProcess.spawn(cmd, dimensions=(rows, cols), cwd=cwd or os.getcwd(), env=env) # type: ignoreloop = asyncio.get_running_loop()reader = asyncio.StreamReader()- def _on_data():- try:- data = os.read(master_r_fd, 1 << 16)- except OSError:- data = b""- if data:- reader.feed_data(data)- else:- reader.feed_eof()- loop.remove_reader(master_r_fd)+ async def _on_data():+ while child.isalive():+ try:+ # Run blocking read in executor to not block event loop+ data = await loop.run_in_executor(None, child.read, 1 << 16)+ if data:+ reader.feed_data(data.encode('utf-8') if isinstance(data, str) else data)+ except EOFError:+ break+ except Exception:+ await asyncio.sleep(0.01)+ reader.feed_eof()- loop.add_reader(master_r_fd, _on_data)+ # Start pumping output in background+ asyncio.create_task(_on_data())class _Stdin:def write(self, d):- os.write(master_w_fd, d)+ # Use winpty's write method, not os.write+ if isinstance(d, bytes):+ d = d.decode('utf-8', errors='replace')+ # Windows needs \r\n for proper line endings+ if _IS_WIN:+ d = d.replace('\n', '\r\n')+ child.write(d)async def drain(self):- await asyncio.sleep(0)+ await asyncio.sleep(0.01) # Give write time to complete- class _Proc(asyncio.subprocess.Process):+ class _Proc:def __init__(self):self.stdin = _Stdin() # type: ignoreself.stdout = readerself.pid = child.pid+ self.returncode = Noneasync def wait(self):while child.isalive():await asyncio.sleep(0.2)+ self.returncode = 0return 0+ def terminate(self):+ if child.isalive():+ child.terminate()+def kill(self):- child.kill()+ if child.isalive():+ child.kill()return _Proc()@@ -261,7 +272,7 @@ async def _spawn_winpty(cmd, cwd, env, echo):if __name__ == "__main__":async def interactive_shell():- shell_cmd, prompt_hint = ("cmd.exe", "$") if _IS_WIN else ("/bin/bash", "$")+ shell_cmd, prompt_hint = ("powershell.exe", ">") if _IS_WIN else ("/bin/bash", "$")# echo=False → suppress the shell’s own echo of commandsterm = TTYSession(shell_cmd)diff --git a/python/tools/code_execution_tool.py b/python/tools/code_execution_tool.pyindex 6e993e522..a37056057 100644--- a/python/tools/code_execution_tool.py+++ b/python/tools/code_execution_tool.py@@ -3,7 +3,7 @@ from dataclasses import dataclassimport shleximport timefrom python.helpers.tool import Tool, Response-from python.helpers import files, rfc_exchange, projects+from python.helpers import files, rfc_exchange, projects, runtimefrom python.helpers.print_style import PrintStylefrom python.helpers.shell_local import LocalInteractiveSessionfrom python.helpers.shell_ssh import SSHInteractiveSession@@ -12,7 +12,6 @@ from python.helpers.strings import truncate_text as truncate_text_stringfrom python.helpers.messages import truncate_text as truncate_text_agentimport re-# Timeouts for python, nodejs, and terminal runtimes.CODE_EXEC_TIMEOUTS: dict[str, int] = {"first_output_timeout": 30,@@ -48,6 +47,7 @@ class CodeExecution(Tool):re.compile(r"\\(venv\\).+[$#] ?$"), # (venv) ...$ or (venv) ...#re.compile(r"root@[^:]+:[^#]+# ?$"), # root@container:~#re.compile(r"[a-zA-Z0-9_.-]+@[^:]+:[^$#]+[$#] ?$"), # user@host:~$+ re.compile(r"\(?.*\)?\s*PS\s+[^>]+> ?$"), # PowerShell prompt like (base) PS C:\...>]# potential dialog detectiondialog_patterns = [@@ -173,7 +173,7 @@ class CodeExecution(Tool):async def execute_terminal_command(self, session: int, command: str, reset: bool = False):- prefix = "bash> " + self.format_command_for_output(command) + "\n\n"+ prefix = ("bash>" if not runtime.is_windows() or self.agent.config.code_exec_ssh_enabled else "PS>") + self.format_command_for_output(command) + "\n\n"return await self.terminal_session(session, command, reset, prefix)async def terminal_session(@@ -467,7 +467,7 @@ class CodeExecution(Tool):# remove any single byte \xXX escapesoutput = re.sub(r"(?<!\\)\\x[0-9A-Fa-f]{2}", "", output)# Strip every line of output before truncation- output = "\n".join(line.strip() for line in output.splitlines())+ # output = "\n".join(line.strip() for line in output.splitlines())output = truncate_text_agent(agent=self.agent, output=output, threshold=1000000) # ~1MB, larger outputs should be dumped to file, not read from terminalreturn outputdiff --git a/requirements.txt b/requirements.txtindex bad799968..2bb36bdd3 100644--- a/requirements.txt+++ b/requirements.txt@@ -48,3 +48,4 @@ exchangelib>=5.4.3pytest>=8.4.2pytest-asyncio>=1.2.0pytest-mock>=3.15.1+pywinpty==3.0.2; sys_platform == "win32"\ No newline at end of file