Agent Zero AI framework
refactor: Extract code execution tool to plugin
linuztx63651deb9ec9
diff --git a/agent.py b/agent.pyindex f56647ceb..b8d1e81d3 100644--- a/agent.py+++ b/agent.py@@ -319,11 +319,6 @@ class AgentConfig:browser_http_headers: dict[str, str] = field(default_factory=dict) # Custom HTTP headers for browser requests- code_exec_ssh_enabled: bool = True- code_exec_ssh_addr: str = "localhost"- code_exec_ssh_port: int = 55022- code_exec_ssh_user: str = "root"- code_exec_ssh_pass: str = ""additional: Dict[str, Any] = field(default_factory=dict)diff --git a/docker/run/fs/exe/run_A0.sh b/docker/run/fs/exe/run_A0.shindex 16e4f115f..5c4124490 100644--- a/docker/run/fs/exe/run_A0.sh+++ b/docker/run/fs/exe/run_A0.sh@@ -11,8 +11,3 @@ exec python /a0/run_ui.py \--dockerized=true \--port=80 \--host="0.0.0.0"- # --code_exec_ssh_enabled=true \- # --code_exec_ssh_addr="localhost" \- # --code_exec_ssh_port=22 \- # --code_exec_ssh_user="root" \- # --code_exec_ssh_pass="toor"diff --git a/docker/run/fs/exe/run_tunnel_api.sh b/docker/run/fs/exe/run_tunnel_api.shindex 321697ea8..88c4ac4e5 100644--- a/docker/run/fs/exe/run_tunnel_api.sh+++ b/docker/run/fs/exe/run_tunnel_api.sh@@ -15,10 +15,4 @@ exec python /a0/run_tunnel.py \--dockerized=true \--port=80 \--tunnel_api_port=55520 \- --host="0.0.0.0" \- --code_exec_docker_enabled=false \- --code_exec_ssh_enabled=true \- # --code_exec_ssh_addr="localhost" \- # --code_exec_ssh_port=22 \- # --code_exec_ssh_user="root" \- # --code_exec_ssh_pass="toor"+ --host="0.0.0.0"diff --git a/helpers/settings.py b/helpers/settings.pyindex 4b77322cc..64f34a552 100644--- a/helpers/settings.py+++ b/helpers/settings.py@@ -112,9 +112,7 @@ class Settings(TypedDict):rfc_url: strrfc_password: strrfc_port_http: int- rfc_port_ssh: int- shell_interface: Literal['local','ssh']websocket_server_restart_enabled: booluvicorn_access_logs_enabled: bool@@ -189,7 +187,6 @@ class ModelProvider(ProvidersFO):class SettingsOutputAdditional(TypedDict):chat_providers: list[ModelProvider]embedding_providers: list[ModelProvider]- shell_interfaces: list[FieldOption]agent_subdirs: list[FieldOption]knowledge_subdirs: list[FieldOption]stt_models: list[FieldOption]@@ -231,7 +228,6 @@ def convert_out(settings: Settings) -> SettingsOutput:additional = SettingsOutputAdditional(chat_providers=get_providers("chat"),embedding_providers=get_providers("embedding"),- shell_interfaces=[{"value": "local", "label": "Local Python TTY"}, {"value": "ssh", "label": "SSH"}],is_dockerized=runtime.is_dockerized(),agent_subdirs=[{"value": item["key"], "label": item["label"]}for item in subagents.get_all_agents_list()@@ -269,7 +265,6 @@ def convert_out(settings: Settings) -> SettingsOutput:additional["chat_providers"] = _ensure_option_present(additional.get("chat_providers"), current.get("util_model_provider"))additional["chat_providers"] = _ensure_option_present(additional.get("chat_providers"), current.get("browser_model_provider"))additional["embedding_providers"] = _ensure_option_present(additional.get("embedding_providers"), current.get("embed_model_provider"))- additional["shell_interfaces"] = _ensure_option_present(additional.get("shell_interfaces"), current.get("shell_interface"))additional["agent_subdirs"] = _ensure_option_present(additional.get("agent_subdirs"), current.get("agent_profile"))additional["knowledge_subdirs"] = _ensure_option_present(additional.get("knowledge_subdirs"), current.get("agent_knowledge_subdir"))additional["stt_models"] = _ensure_option_present(additional.get("stt_models"), current.get("stt_model_size"))@@ -549,8 +544,6 @@ def get_default_settings() -> Settings:rfc_url=get_default_value("rfc_url", "localhost"),rfc_password="",rfc_port_http=get_default_value("rfc_port_http", 55080),- rfc_port_ssh=get_default_value("rfc_port_ssh", 55022),- shell_interface=get_default_value("shell_interface", "local" if runtime.is_dockerized() else "ssh"),websocket_server_restart_enabled=get_default_value("websocket_server_restart_enabled", True),uvicorn_access_logs_enabled=get_default_value("uvicorn_access_logs_enabled", False),stt_model_size=get_default_value("stt_model_size", "base"),@@ -750,27 +743,9 @@ def set_root_password(password: str):def get_runtime_config(set: Settings):- if runtime.is_dockerized():- return {- "code_exec_ssh_enabled": set["shell_interface"] == "ssh",- "code_exec_ssh_addr": "localhost",- "code_exec_ssh_port": 22,- "code_exec_ssh_user": "root",- }- else:- host = set["rfc_url"]- if "//" in host:- host = host.split("//")[1]- if ":" in host:- host, port = host.split(":")- if host.endswith("/"):- host = host[:-1]- return {- "code_exec_ssh_enabled": set["shell_interface"] == "ssh",- "code_exec_ssh_addr": host,- "code_exec_ssh_port": set["rfc_port_ssh"],- "code_exec_ssh_user": "root",- }+ # SSH config is now managed by the code_execution plugin.+ # This function is kept for backward compatibility but returns an empty dict.+ return {}def create_auth_token() -> str:diff --git a/initialize.py b/initialize.pyindex b38da9877..8cc2d1790 100644--- a/initialize.py+++ b/initialize.py@@ -82,13 +82,8 @@ def initialize_agent(override_settings: dict | None = None):knowledge_subdirs=[current_settings["agent_knowledge_subdir"], "default"],mcp_servers=current_settings["mcp_servers"],browser_http_headers=current_settings["browser_http_headers"],- # code_exec params get initialized in _set_runtime_config- # additional = {},)- # update SSH and docker settings- _set_runtime_config(config, current_settings)-# update config with runtime args_args_override(config)@@ -175,8 +170,4 @@ def _args_override(config):setattr(config, key, value)-def _set_runtime_config(config: AgentConfig, set: settings.Settings):- ssh_conf = settings.get_runtime_config(set)- for key, value in ssh_conf.items():- if hasattr(config, key):- setattr(config, key, value)+diff --git a/plugins/code_execution/default_config.yaml b/plugins/code_execution/default_config.yamlnew file mode 100644index 000000000..d4d8f0307--- /dev/null+++ b/plugins/code_execution/default_config.yaml@@ -0,0 +1,36 @@+# Shell interface: false = local TTY, true = SSH+ssh_enabled: false++# SSH credentials (used when ssh_enabled is true)+ssh_addr: localhost+ssh_port: 22+ssh_user: root+ssh_pass: ""++# Timeouts for python/nodejs/terminal runtimes (seconds)+code_exec_first_output_timeout: 30+code_exec_between_output_timeout: 15+code_exec_max_exec_timeout: 180+code_exec_dialog_timeout: 5++# Timeouts for "output" runtime (seconds)+output_first_output_timeout: 90+output_between_output_timeout: 45+output_max_exec_timeout: 300+output_dialog_timeout: 5++# Shell prompt detection patterns (one regex per line)+# When matched, output is returned immediately without waiting for timeout+prompt_patterns: |+ (\(venv\)).+[$#] ?$+ root@[^:]+:[^#]+# ?$+ [a-zA-Z0-9_.-]+@[^:]+:[^$#]+[$#] ?$+ \(?.*\)?\s*PS\s+[^>]+> ?$++# Dialog detection patterns (one regex per line, case-insensitive)+# When matched after dialog_timeout, control is returned to the agent+dialog_patterns: |+ Y/N+ yes/no+ :\s*$+ \?\s*$diff --git a/plugins/code_execution/extensions/python/system_prompt/_20_code_execution_prompt.py b/plugins/code_execution/extensions/python/system_prompt/_20_code_execution_prompt.pynew file mode 100644index 000000000..5917dc6df--- /dev/null+++ b/plugins/code_execution/extensions/python/system_prompt/_20_code_execution_prompt.py@@ -0,0 +1,14 @@+from helpers.extension import Extension+from agent import LoopData+++class CodeExecutionPrompt(Extension):++ async def execute(+ self,+ system_prompt: list[str] = [],+ loop_data: LoopData = LoopData(),+ **kwargs,+ ):+ prompt = self.agent.read_prompt("agent.system.tool.code_exe.md")+ system_prompt.append(prompt)diff --git a/plugins/code_execution/extensions/webui/get_message_handler/code-exe-handler.js b/plugins/code_execution/extensions/webui/get_message_handler/code-exe-handler.jsnew file mode 100644index 000000000..70d5d9e4c--- /dev/null+++ b/plugins/code_execution/extensions/webui/get_message_handler/code-exe-handler.js@@ -0,0 +1,7 @@+import { drawMessageCodeExe } from "/js/messages.js";++export default async function registerCodeExeHandler(extData) {+ if (extData?.type === "code_exe") {+ extData.handler = drawMessageCodeExe;+ }+}diff --git a/plugins/code_execution/helpers/__init__.py b/plugins/code_execution/helpers/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/helpers/shell_local.py b/plugins/code_execution/helpers/shell_local.pysimilarity index 88%rename from helpers/shell_local.pyrename to plugins/code_execution/helpers/shell_local.pyindex fc238842f..d81b1628d 100644--- a/helpers/shell_local.py+++ b/plugins/code_execution/helpers/shell_local.py@@ -4,8 +4,9 @@ import subprocessimport timeimport sysfrom typing import Optional, Tuple-from helpers import tty_session, runtime-from helpers.shell_ssh import clean_string+from helpers import runtime+from plugins.code_execution.helpers import tty_session+from plugins.code_execution.helpers.shell_ssh import clean_stringclass LocalInteractiveSession:def __init__(self, cwd: str|None = None):diff --git a/helpers/shell_ssh.py b/plugins/code_execution/helpers/shell_ssh.pysimilarity index 100%rename from helpers/shell_ssh.pyrename to plugins/code_execution/helpers/shell_ssh.pydiff --git a/helpers/tty_session.py b/plugins/code_execution/helpers/tty_session.pysimilarity index 100%rename from helpers/tty_session.pyrename to plugins/code_execution/helpers/tty_session.pydiff --git a/plugins/code_execution/plugin.yaml b/plugins/code_execution/plugin.yamlnew file mode 100644index 000000000..ed9386bb3--- /dev/null+++ b/plugins/code_execution/plugin.yaml@@ -0,0 +1,8 @@+name: Code Execution+description: Provides terminal, Python, and Node.js code execution via local TTY or SSH.+version: 1.0.0+always_enabled: true+settings_sections:+ - agent+per_project_config: true+per_agent_config: truediff --git a/prompts/agent.system.tool.code_exe.md b/plugins/code_execution/prompts/agent.system.tool.code_exe.mdsimilarity index 100%rename from prompts/agent.system.tool.code_exe.mdrename to plugins/code_execution/prompts/agent.system.tool.code_exe.mddiff --git a/prompts/fw.code.info.md b/plugins/code_execution/prompts/fw.code.info.mdsimilarity index 100%rename from prompts/fw.code.info.mdrename to plugins/code_execution/prompts/fw.code.info.mddiff --git a/prompts/fw.code.max_time.md b/plugins/code_execution/prompts/fw.code.max_time.mdsimilarity index 100%rename from prompts/fw.code.max_time.mdrename to plugins/code_execution/prompts/fw.code.max_time.mddiff --git a/prompts/fw.code.no_out_time.md b/plugins/code_execution/prompts/fw.code.no_out_time.mdsimilarity index 100%rename from prompts/fw.code.no_out_time.mdrename to plugins/code_execution/prompts/fw.code.no_out_time.mddiff --git a/prompts/fw.code.no_output.md b/plugins/code_execution/prompts/fw.code.no_output.mdsimilarity index 100%rename from prompts/fw.code.no_output.mdrename to plugins/code_execution/prompts/fw.code.no_output.mddiff --git a/prompts/fw.code.pause_dialog.md b/plugins/code_execution/prompts/fw.code.pause_dialog.mdsimilarity index 100%rename from prompts/fw.code.pause_dialog.mdrename to plugins/code_execution/prompts/fw.code.pause_dialog.mddiff --git a/prompts/fw.code.pause_time.md b/plugins/code_execution/prompts/fw.code.pause_time.mdsimilarity index 100%rename from prompts/fw.code.pause_time.mdrename to plugins/code_execution/prompts/fw.code.pause_time.mddiff --git a/prompts/fw.code.reset.md b/plugins/code_execution/prompts/fw.code.reset.mdsimilarity index 100%rename from prompts/fw.code.reset.mdrename to plugins/code_execution/prompts/fw.code.reset.mddiff --git a/prompts/fw.code.running.md b/plugins/code_execution/prompts/fw.code.running.mdsimilarity index 100%rename from prompts/fw.code.running.mdrename to plugins/code_execution/prompts/fw.code.running.mddiff --git a/prompts/fw.code.runtime_wrong.md b/plugins/code_execution/prompts/fw.code.runtime_wrong.mdsimilarity index 100%rename from prompts/fw.code.runtime_wrong.mdrename to plugins/code_execution/prompts/fw.code.runtime_wrong.mddiff --git a/tools/code_execution_tool.py b/plugins/code_execution/tools/code_execution_tool.pysimilarity index 77%rename from tools/code_execution_tool.pyrename to plugins/code_execution/tools/code_execution_tool.pyindex 44ba61d8f..cae33a230 100644--- a/tools/code_execution_tool.py+++ b/plugins/code_execution/tools/code_execution_tool.py@@ -1,31 +1,93 @@import asynciofrom dataclasses import dataclass+import reimport shleximport time+from helpers.tool import Tool, Response-from helpers import files, rfc_exchange, projects, runtime, settings+from helpers import files, projects, runtime, settingsfrom helpers.print_style import PrintStyle-from helpers.shell_local import LocalInteractiveSession-from helpers.shell_ssh import SSHInteractiveSessionfrom helpers.strings import truncate_text as truncate_text_stringfrom helpers.messages import truncate_text as truncate_text_agent-import re+from helpers import plugins++from plugins.code_execution.helpers.shell_local import LocalInteractiveSession+from plugins.code_execution.helpers.shell_ssh import SSHInteractiveSession+++def _get_config(agent) -> dict:+ cfg = plugins.get_plugin_config("code_execution", agent=agent) or {}++ # SSH / TTY switch+ ssh_enabled = bool(cfg.get("ssh_enabled", False))++ # SSH credentials+ ssh_addr = str(cfg.get("ssh_addr", "localhost"))+ ssh_port = int(cfg.get("ssh_port", 22))+ ssh_user = str(cfg.get("ssh_user", "root"))+ ssh_pass = str(cfg.get("ssh_pass", ""))++ # Timeouts for python/nodejs/terminal runtimes+ code_exec_timeouts = {+ "first_output_timeout": int(cfg.get("code_exec_first_output_timeout", 30)),+ "between_output_timeout": int(cfg.get("code_exec_between_output_timeout", 15)),+ "max_exec_timeout": int(cfg.get("code_exec_max_exec_timeout", 180)),+ "dialog_timeout": int(cfg.get("code_exec_dialog_timeout", 5)),+ }++ # Timeouts for "output" runtime+ output_timeouts = {+ "first_output_timeout": int(cfg.get("output_first_output_timeout", 90)),+ "between_output_timeout": int(cfg.get("output_between_output_timeout", 45)),+ "max_exec_timeout": int(cfg.get("output_max_exec_timeout", 300)),+ "dialog_timeout": int(cfg.get("output_dialog_timeout", 5)),+ }++ # Prompt patterns (one regex per line, or a list)+ prompt_patterns_raw = cfg.get(+ "prompt_patterns",+ r"(\(venv\)).+[$#] ?$" + "\n"+ + r"root@[^:]+:[^#]+# ?$" + "\n"+ + r"[a-zA-Z0-9_.-]+@[^:]+:[^$#]+[$#] ?$" + "\n"+ + r"\(?.*\)?\s*PS\s+[^>]+> ?$",+ )+ if isinstance(prompt_patterns_raw, list):+ prompt_lines = [str(p) for p in prompt_patterns_raw]+ else:+ prompt_lines = str(prompt_patterns_raw).splitlines()+ prompt_patterns = [+ re.compile(p.strip())+ for p in prompt_lines+ if p.strip()+ ]++ # Dialog patterns (one regex per line, or a list)+ dialog_patterns_raw = cfg.get(+ "dialog_patterns",+ "Y/N\nyes/no\n:\\s*$\n\\?\\s*$",+ )+ if isinstance(dialog_patterns_raw, list):+ dialog_lines = [str(p) for p in dialog_patterns_raw]+ else:+ dialog_lines = str(dialog_patterns_raw).splitlines()+ dialog_patterns = [+ re.compile(p.strip(), re.IGNORECASE)+ for p in dialog_lines+ if p.strip()+ ]++ return {+ "ssh_enabled": ssh_enabled,+ "ssh_addr": ssh_addr,+ "ssh_port": ssh_port,+ "ssh_user": ssh_user,+ "ssh_pass": ssh_pass,+ "code_exec_timeouts": code_exec_timeouts,+ "output_timeouts": output_timeouts,+ "prompt_patterns": prompt_patterns,+ "dialog_patterns": dialog_patterns,+ }-# Timeouts for python, nodejs, and terminal runtimes.-CODE_EXEC_TIMEOUTS: dict[str, int] = {- "first_output_timeout": 30,- "between_output_timeout": 15,- "max_exec_timeout": 180,- "dialog_timeout": 5,-}--# Timeouts for output runtime.-OUTPUT_TIMEOUTS: dict[str, int] = {- "first_output_timeout": 90,- "between_output_timeout": 45,- "max_exec_timeout": 300,- "dialog_timeout": 5,-}@dataclassclass ShellWrap:@@ -33,6 +95,7 @@ class ShellWrap:session: LocalInteractiveSession | SSHInteractiveSessionrunning: bool+@dataclassclass State:ssh_enabled: bool@@ -41,51 +104,37 @@ class State:class CodeExecution(Tool):- # 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:~$- re.compile(r"\(?.*\)?\s*PS\s+[^>]+> ?$"), # PowerShell prompt like (base) PS C:\...>- ]- # 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) -> Response:await self.agent.handle_intervention() # wait for intervention and handle it, if paused- runtime = self.args.get("runtime", "").lower().strip()+ runtime_arg = self.args.get("runtime", "").lower().strip()session = int(self.args.get("session", 0))self.allow_running = bool(self.args.get("allow_running", False))- reset = bool(self.args.get("reset", False) or runtime == "reset")+ reset = bool(self.args.get("reset", False) or runtime_arg == "reset")- if runtime == "python":+ if runtime_arg == "python":response = await self.execute_python_code(code=self.args["code"], session=session, reset=reset)- elif runtime == "nodejs":+ elif runtime_arg == "nodejs":response = await self.execute_nodejs_code(code=self.args["code"], session=session, reset=reset)- elif runtime == "terminal":+ elif runtime_arg == "terminal":response = await self.execute_terminal_command(command=self.args["code"], session=session, reset=reset)- elif runtime == "output":+ elif runtime_arg == "output":+ cfg = _get_config(self.agent)response = await self.get_terminal_output(- session=session, timeouts=OUTPUT_TIMEOUTS+ session=session, timeouts=cfg["output_timeouts"])- elif runtime == "reset":+ elif runtime_arg == "reset":response = await self.reset_terminal(session=session)else:response = self.agent.read_prompt(- "fw.code.runtime_wrong.md", runtime=runtime+ "fw.code.runtime_wrong.md", runtime=runtime_arg)if not response:@@ -105,7 +154,6 @@ class CodeExecution(Tool):def get_heading(self, text: str = ""):if not text:text = f"{self.name} - {self.args['runtime'] if 'runtime' in self.args else 'unknown'}"- # text = truncate_text_string(text, 60) # don't truncate here, log.py takes care of itsession = self.args.get("session", None)session_text = f"[{session}] " if session or session == 0 else ""return f"icon://terminal {session_text}{text}"@@ -115,9 +163,11 @@ class CodeExecution(Tool):async def prepare_state(self, reset=False, session: int | None = None):self.state: State | None = self.agent.get_data("_cet_state")+ cfg = _get_config(self.agent)+ ssh_enabled = cfg["ssh_enabled"]+# always reset state when ssh_enabled changes- if not self.state or self.state.ssh_enabled != self.agent.config.code_exec_ssh_enabled:- # initialize shells dictionary if not exists+ if not self.state or self.state.ssh_enabled != ssh_enabled:shells: dict[int, ShellWrap] = {}else:shells = self.state.shells.copy()@@ -132,21 +182,16 @@ class CodeExecution(Tool):await shells[s].session.close()shells = {}- # initialize local or remote interactive shell interface for session 0 if needed+ # initialize local or remote interactive shell interface for session if neededif session is not None and session not in shells:cwd = await self.ensure_cwd()- if self.agent.config.code_exec_ssh_enabled:- pswd = (- self.agent.config.code_exec_ssh_pass- if self.agent.config.code_exec_ssh_pass- else await rfc_exchange.get_root_password()- )+ if ssh_enabled:shell = SSHInteractiveSession(self.agent.context.log,- self.agent.config.code_exec_ssh_addr,- self.agent.config.code_exec_ssh_port,- self.agent.config.code_exec_ssh_user,- pswd,+ cfg["ssh_addr"],+ cfg["ssh_port"],+ cfg["ssh_user"],+ cfg["ssh_pass"],cwd=cwd,)else:@@ -155,7 +200,7 @@ class CodeExecution(Tool):shells[session] = ShellWrap(id=session, session=shell, running=False)await shell.connect()- self.state = State(shells=shells, ssh_enabled=self.agent.config.code_exec_ssh_enabled)+ self.state = State(shells=shells, ssh_enabled=ssh_enabled)self.agent.set_data("_cet_state", self.state)return self.state@@ -174,13 +219,17 @@ class CodeExecution(Tool):async def execute_terminal_command(self, session: int, command: str, reset: bool = False):- 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"+ cfg = _get_config(self.agent)+ prefix = (+ ("bash>" if not runtime.is_windows() or cfg["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(self, session: int, command: str, reset: bool = False, prefix: str = "", timeouts: dict | None = None):-self.state = await self.prepare_state(reset=reset, session=session)await self.agent.handle_intervention() # wait for intervention and handle it, if paused@@ -189,11 +238,12 @@ class CodeExecution(Tool):if not self.allow_running:if response := await self.handle_running_session(session):return response-++ cfg = _get_config(self.agent)+# try again on lost connectionfor i in range(2):try:-self.state.shells[session].running = Trueawait self.state.shells[session].session.send_command(command)@@ -210,11 +260,14 @@ class CodeExecution(Tool):PrintStyle(background_color="white", font_color="#1B4F72", bold=True).print(f"{self.agent.agent_name} code execution output{locl}")- return await self.get_terminal_output(session=session, prefix=prefix, timeouts=(timeouts or CODE_EXEC_TIMEOUTS))+ return await self.get_terminal_output(+ session=session,+ prefix=prefix,+ timeouts=(timeouts or cfg["code_exec_timeouts"]),+ )except Exception as e:if i == 1:- # try again on lost connectionPrintStyle.error(str(e))await self.prepare_state(reset=True, session=session)continue@@ -222,13 +275,8 @@ class CodeExecution(Tool):raise edef format_command_for_output(self, command: str):- # truncate long commandsshort_cmd = command[:200]- # normalize whitespace for cleaner outputshort_cmd = " ".join(short_cmd.split())- # replace any sequence of ', ", or ` with a single '- # short_cmd = re.sub(r"['\"`]+", "'", short_cmd) # no need anymore- # final lengthshort_cmd = truncate_text_string(short_cmd, 100)return f"{short_cmd}"@@ -236,16 +284,14 @@ class CodeExecution(Tool):self,session=0,reset_full_output=True,- first_output_timeout=30, # Wait up to x seconds for first output- between_output_timeout=15, # Wait up to x seconds between outputs- dialog_timeout=5, # potential dialog detection timeout- max_exec_timeout=180, # hard cap on total runtime+ first_output_timeout=30,+ between_output_timeout=15,+ dialog_timeout=5,+ max_exec_timeout=180,sleep_time=0.5,prefix="",timeouts: dict | None = None,):-- # if not self.state:self.state = await self.prepare_state(session=session)# Override timeouts if a dict is provided@@ -255,6 +301,10 @@ class CodeExecution(Tool):dialog_timeout = timeouts.get("dialog_timeout", dialog_timeout)max_exec_timeout = timeouts.get("max_exec_timeout", max_exec_timeout)+ cfg = _get_config(self.agent)+ prompt_patterns = cfg["prompt_patterns"]+ dialog_patterns = cfg["dialog_patterns"]+start_time = time.time()last_output_time = start_timefull_output = ""@@ -277,7 +327,6 @@ class CodeExecution(Tool):now = time.time()if partial_output:PrintStyle(font_color="#85C1E9").stream(partial_output)- # full_output += partial_output # Append new outputtruncated_output = self.fix_full_output(full_output)self.set_progress(truncated_output)heading = self.get_heading_from_output(truncated_output, 0)@@ -291,7 +340,7 @@ class CodeExecution(Tool):)last_lines.reverse()for idx, line in enumerate(last_lines):- for pat in self.prompt_patterns:+ for pat in prompt_patterns:if pat.search(line.strip()):PrintStyle.info("Detected shell prompt, returning output early."@@ -343,12 +392,11 @@ class CodeExecution(Tool):# potential dialog detectionif now - last_output_time > dialog_timeout:- # Check for dialog prompt at the end of outputlast_lines = (truncated_output.splitlines()[-2:] if truncated_output else [])for line in last_lines:- for pat in self.dialog_patterns:+ for pat in dialog_patterns:if pat.search(line.strip()):PrintStyle.info("Detected dialog prompt, returning output early."@@ -374,14 +422,18 @@ class CodeExecution(Tool):async def handle_running_session(self,session=0,- reset_full_output=True,+ reset_full_output=True,prefix=""):if not self.state or session not in self.state.shells:return Noneif not self.state.shells[session].running:return None-++ cfg = _get_config(self.agent)+ prompt_patterns = cfg["prompt_patterns"]+ dialog_patterns = cfg["dialog_patterns"]+full_output, _ = await self.state.shells[session].session.read_output(timeout=1, reset_full_output=reset_full_output)@@ -394,7 +446,7 @@ class CodeExecution(Tool):)last_lines.reverse()for idx, line in enumerate(last_lines):- for pat in self.prompt_patterns:+ for pat in prompt_patterns:if pat.search(line.strip()):PrintStyle.info("Detected shell prompt, returning output early."@@ -402,9 +454,9 @@ class CodeExecution(Tool):self.mark_session_idle(session)return None- has_dialog = False+ has_dialog = Falsefor line in last_lines:- for pat in self.dialog_patterns:+ for pat in dialog_patterns:if pat.search(line.strip()):has_dialog = Truebreak@@ -412,7 +464,7 @@ class CodeExecution(Tool):breakif has_dialog:- sys_info = self.agent.read_prompt("fw.code.pause_dialog.md", timeout=1)+ 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)@@ -422,14 +474,12 @@ class CodeExecution(Tool):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 finishedif self.state and session in self.state.shells:self.state.shells[session].running = Falseasync def reset_terminal(self, session=0, reason: str | None = None):- # Print the reason for the reset to the console if providedif reason:PrintStyle(font_color="#FFA500", bold=True).print(f"Resetting terminal session {session}... Reason: {reason}"@@ -439,7 +489,6 @@ class CodeExecution(Tool):f"Resetting terminal session {session}...")- # Only reset the specified session while preserving othersawait self.prepare_state(reset=True, session=session)response = self.agent.read_prompt("fw.code.info.md", info=self.agent.read_prompt("fw.code.reset.md")@@ -453,9 +502,7 @@ class CodeExecution(Tool):if not output:return self.get_heading() + done_icon- # find last non-empty line with skiplines = output.splitlines()- # Start from len(lines) - skip_lines - 1 down to 0for i in range(len(lines) - skip_lines - 1, -1, -1):line = lines[i].strip()if not line:@@ -465,11 +512,8 @@ class CodeExecution(Tool):return self.get_heading() + done_icondef fix_full_output(self, output: str):- # 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 = truncate_text_agent(agent=self.agent, output=output, threshold=1000000) # ~1MB, larger outputs should be dumped to file, not read from terminal+ output = truncate_text_agent(agent=self.agent, output=output, threshold=1000000)return outputasync def ensure_cwd(self) -> str | None:@@ -487,9 +531,7 @@ class CodeExecution(Tool):await runtime.call_development_function(make_dir, normalized)return normalized+def make_dir(path: str):import osos.makedirs(path, exist_ok=True)---\ No newline at end of filediff --git a/plugins/code_execution/webui/config.html b/plugins/code_execution/webui/config.htmlnew file mode 100644index 000000000..56fc69be4--- /dev/null+++ b/plugins/code_execution/webui/config.html@@ -0,0 +1,202 @@+<html>+<head>+ <title>Code Execution</title>+</head>++<body>+ <div x-data>+ <template x-if="$store.pluginSettings.settings">+ <div>+ <div class="section-title">Code Execution</div>+ <div class="section-description">+ Configuration for the code execution tool. Controls the shell interface, SSH credentials, execution timeouts, and prompt/dialog detection patterns.+ </div>++ <!-- Shell Interface -->+ <div class="field">+ <div class="field-label">+ <div class="field-title">Use SSH</div>+ <div class="field-description">+ When enabled, code execution connects via SSH using the credentials below. When disabled, a local Python TTY is used.+ </div>+ </div>+ <div class="field-control">+ <label class="toggle">+ <input type="checkbox" x-model="$store.pluginSettings.settings.ssh_enabled" />+ <span class="toggler"></span>+ </label>+ </div>+ </div>++ <!-- SSH credentials (shown only when SSH is enabled) -->+ <template x-if="$store.pluginSettings.settings.ssh_enabled">+ <div>+ <div class="field">+ <div class="field-label">+ <div class="field-title">SSH Address</div>+ <div class="field-description">Hostname or IP of the SSH target.</div>+ </div>+ <div class="field-control">+ <input type="text" x-model="$store.pluginSettings.settings.ssh_addr" placeholder="localhost" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">SSH Port</div>+ <div class="field-description">SSH port on the target host.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" max="65535" x-model.number="$store.pluginSettings.settings.ssh_port" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">SSH User</div>+ <div class="field-description">Username for SSH login.</div>+ </div>+ <div class="field-control">+ <input type="text" x-model="$store.pluginSettings.settings.ssh_user" placeholder="root" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">SSH Password</div>+ <div class="field-description">Password for SSH login.</div>+ </div>+ <div class="field-control">+ <input type="password" autocomplete="off" x-model="$store.pluginSettings.settings.ssh_pass" />+ </div>+ </div>+ </div>+ </template>++ <!-- Execution timeouts -->+ <div class="section-title">Execution Timeouts</div>+ <div class="section-description">+ Timeouts (in seconds) for python, nodejs, and terminal runtimes.+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">First output timeout</div>+ <div class="field-description">Seconds to wait for the first output before returning control to the agent.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.code_exec_first_output_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Between output timeout</div>+ <div class="field-description">Seconds to wait between output chunks before returning control.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.code_exec_between_output_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Max execution timeout</div>+ <div class="field-description">Hard cap on total execution time in seconds.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.code_exec_max_exec_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Dialog detection timeout</div>+ <div class="field-description">Seconds of idle output before checking for dialog prompts.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.code_exec_dialog_timeout" />+ </div>+ </div>++ <!-- Output runtime timeouts -->+ <div class="section-title">Output Runtime Timeouts</div>+ <div class="section-description">+ Timeouts (in seconds) for the "output" runtime (waiting for long-running processes).+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">First output timeout</div>+ <div class="field-description">Seconds to wait for the first output.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.output_first_output_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Between output timeout</div>+ <div class="field-description">Seconds to wait between output chunks.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.output_between_output_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Max execution timeout</div>+ <div class="field-description">Hard cap on total wait time in seconds.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.output_max_exec_timeout" />+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Dialog detection timeout</div>+ <div class="field-description">Seconds of idle output before checking for dialog prompts.</div>+ </div>+ <div class="field-control">+ <input type="number" min="1" x-model.number="$store.pluginSettings.settings.output_dialog_timeout" />+ </div>+ </div>++ <!-- Patterns -->+ <div class="section-title">Detection Patterns</div>+ <div class="section-description">+ Regular expressions used to detect shell prompts and interactive dialogs. One pattern per line.+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Prompt patterns</div>+ <div class="field-description">+ When any pattern matches the last output lines, execution is considered complete and output is returned immediately.+ </div>+ </div>+ <div class="field-control">+ <textarea rows="5" x-model="$store.pluginSettings.settings.prompt_patterns"></textarea>+ </div>+ </div>++ <div class="field">+ <div class="field-label">+ <div class="field-title">Dialog patterns</div>+ <div class="field-description">+ When any pattern matches after the dialog timeout, control is returned to the agent to handle the interactive prompt.+ </div>+ </div>+ <div class="field-control">+ <textarea rows="4" x-model="$store.pluginSettings.settings.dialog_patterns"></textarea>+ </div>+ </div>+ </div>+ </template>+ </div>+</body>++</html>diff --git a/tools/input.py b/tools/input.pyindex 9c85e4a82..6d91ba0cc 100644--- a/tools/input.py+++ b/tools/input.py@@ -1,6 +1,6 @@from agent import Agent, UserMessagefrom helpers.tool import Tool, Response-from tools.code_execution_tool import CodeExecution+from plugins.code_execution.tools.code_execution_tool import CodeExecutionclass Input(Tool):diff --git a/webui/components/settings/developer/dev.html b/webui/components/settings/developer/dev.htmlindex e158dccf4..9887a475d 100644--- a/webui/components/settings/developer/dev.html+++ b/webui/components/settings/developer/dev.html@@ -12,22 +12,6 @@Parameters for A0 framework development. RFCs (remote function calls) are used to call functions on another A0 instance. You can develop and debug A0 natively on your local system while redirecting some functions to A0 instance in docker. This is crucial for development as A0 needs to run in standardized environment to support all features.</div>- <div class="field">- <div class="field-label">- <div class="field-title">Shell Interface</div>- <div class="field-description">- Terminal interface used for Code Execution Tool. Local Python TTY works locally in both dockerized and development environments. SSH always connects to dockerized environment (automatically at localhost or RFC host address).- </div>- </div>- <div class="field-control">- <select x-model="$store.settings.settings.shell_interface">- <template x-for="option in $store.settings.additional?.shell_interfaces" :key="option.value">- <option :value="option.value" :selected="option.value === $store.settings.settings.shell_interface" x-text="option.label"></option>- </template>- </select>- </div>- </div>-<template x-if="!$store.settings.additional?.is_dockerized"><div><div class="field">@@ -68,15 +52,6 @@</div></div>- <div class="field">- <div class="field-label">- <div class="field-title">RFC SSH port</div>- <div class="field-description">SSH port for dockerized instance of A0.</div>- </div>- <div class="field-control">- <input type="number" x-model.number="$store.settings.settings.rfc_port_ssh" />- </div>- </div></div></template>