Agent Zero AI framework
dec's updates
frdela00c433658f9
diff --cc docker/run/fs/ins/install_A0.shindex 2685dc66e,246abe954..04fba1a5b--- a/docker/run/fs/ins/install_A0.sh+++ b/docker/run/fs/ins/install_A0.sh@@@ -7,23 -10,44 +10,47 @@@ if [ -z "$1" ]; thefiBRANCH="$1"- # clone project repo branch- git clone -b "$BRANCH" "https://github.com/frdel/agent-zero" "/git/agent-zero"+ git clone -b "$BRANCH" "https://github.com/frdel/agent-zero" "/git/agent-zero" || {+ echo "CRITICAL ERROR: Failed to clone repository. Branch: $BRANCH"+ exit 1+ }- # setup python environment. "/ins/setup_venv.sh" "$@"- # Ensure the virtual environment and pip setup- pip install --upgrade pip ipython requests+ pip install --upgrade pip ipython requests || {+ echo "CRITICAL ERROR: Failed to upgrade pip or install ipython/requests."+ exit 1+ }++ pip install -v torch --index-url https://download.pytorch.org/whl/cpu || {+ echo "CRITICAL ERROR: Failed to install PyTorch."+ exit 1+ }++ pip install -v mcp==1.3.0 || {+ echo "ERROR: Failed during separate attempt to install mcp==1.3.0. Will proceed to full requirements.txt install anyway."+ }+ python -c "import mcp; from mcp import ClientSession; print(f'DEBUG: mcp and mcp.ClientSession imported successfully after separate install. mcp path: {mcp.__file__}')" || {+ echo "ERROR: mcp package or mcp.ClientSession NOT importable after separate mcp==1.3.0 installation attempt. Full requirements.txt will run next."+ }- # Install some packages in specific variants- pip install torch --index-url https://download.pytorch.org/whl/cpu+ pip install -v -r /git/agent-zero/requirements.txt || {+ echo "CRITICAL ERROR: Failed to install A0 requirements from requirements.txt."+ exit 1+ }- # Install remaining A0 python packages- pip install -r /git/agent-zero/requirements.txt+ python -c "import mcp; from mcp import ClientSession; print(f'DEBUG: mcp and mcp.ClientSession imported successfully after requirements.txt. mcp path: {mcp.__file__}')" || {+ echo "CRITICAL ERROR: mcp package or mcp.ClientSession not found or failed to import after requirements.txt processing."+ exit 1+ }+# install playwright+bash /ins/install_playwright.sh "$@"+# Preload A0- python /git/agent-zero/preload.py --dockerized=true+ python /git/agent-zero/preload.py --dockerized=true++ echo "install_A0.sh completed successfully."++ # install playwright+ bash /ins/install_playwright.sh "$@"diff --cc python/helpers/dirty_json.pyindex e52082e43,b124ba74d..f25631536--- a/python/helpers/dirty_json.py+++ b/python/helpers/dirty_json.py@@@ -284,12 -249,13 +284,16 @@@ class DirtyJsondef _parse_number(self):number_str = ""- while self.current_char is not None and (self.current_char.isdigit() or self.current_char in ['-', '+', '.', 'e', 'E']):+ while self.current_char is not None and (+ self.current_char.isdigit()+ or self.current_char in ["-", "+", ".", "e", "E"]+ ):number_str += self.current_charself._advance()+ # Only try to convert if number_str is a valid number+ if number_str in ('', '+', '-'):+ # Not a valid number, treat as string or handle error+ return number_str.strip() # or raise ValueError("Invalid number format")try:return int(number_str)except ValueError:diff --cc python/tools/code_execution_tool.pyindex d580a5d96,112f62fe5..eeece7efd--- a/python/tools/code_execution_tool.py+++ b/python/tools/code_execution_tool.py@@@ -8,7 -8,7 +8,8 @@@ from python.helpers.print_style importfrom python.helpers.shell_local import LocalInteractiveSessionfrom python.helpers.shell_ssh import SSHInteractiveSessionfrom python.helpers.docker import DockerContainerManager+from python.helpers.messages import truncate_text+ import re@dataclass@@@ -197,42 -208,110 +214,62 @@@ class CodeExecution(Tool)self,session=0,reset_full_output=True,- wait_with_output=3,- wait_without_output=10,- max_exec_time=60,+ first_output_timeout=30, # Wait up to 60s for first output+ between_output_timeout=10, # Wait up to 10s between outputs+ sleep_time=0.1,):- idle = 0- SLEEP_TIME = 0.1+ """+ Waits for terminal output with a sliding window idle timeout:+ - Waits up to first_output_timeout (default 60s) for the first output.+ - After any output, waits up to between_output_timeout (default 10s) for more output.+ - Each new output resets the between_output_timeout timer.+ - No hard cap on total runtime.+ - If no output for between_output_timeout after last output, or no output at all for first_output_timeout, returns.+ - If a common shell prompt is detected, returns immediately.+ """+ # 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:~$+ ]+start_time = time.time()+ last_output_time = start_timefull_output = ""- got_output = False- # --- Configuration for repetition detection ---- chunk_size = 128 # Size of the block to check for repetition- repeat_threshold = 5 # How many times the block must repeat consecutively-- while True:- await asyncio.sleep(sleep_time)- current_full_output, partial_output = await self.state.shells[session].read_output(- timeout=between_output_timeout, reset_full_output=reset_full_output++ while max_exec_time <= 0 or time.time() - start_time < max_exec_time:+ await asyncio.sleep(SLEEP_TIME) # Wait for some output to be generated+ full_output, partial_output = await self.state.shells[session].read_output(+ timeout=1, reset_full_output=reset_full_output)- reset_full_output = False # only reset once+ reset_full_output = False- await self.agent.handle_intervention() # wait for intervention and handle it, if paused+ await self.agent.handle_intervention()+ now = time.time()if partial_output:PrintStyle(font_color="#85C1E9").stream(partial_output)- full_output += partial_output # Append new output- self.log.update(content=full_output)- last_output_time = now- got_output = True-- # --- Check for repeating output pattern ---- required_len = chunk_size * repeat_threshold- if len(full_output) >= required_len:- check_segment = full_output[-required_len:]- last_chunk = full_output[-chunk_size:]- expected_segment = last_chunk * repeat_threshold- if check_segment == expected_segment:- loop_detected_msg = f"Detected repeating output pattern (last {chunk_size} chars repeated {repeat_threshold} times), likely an infinite loop."- PrintStyle.error(f"{loop_detected_msg} Resetting session {session}.")-- # --- Truncate output for feedback ---- max_output_length = 2048- truncated_output = full_output[-max_output_length:]- if len(full_output) > max_output_length:- summary_prefix = f"[... Output truncated to last {max_output_length} characters ...]\n"- truncated_output = summary_prefix + truncated_output- else:- summary_prefix = ""- # --- End of truncation ----- self.log.update(content=truncated_output + f"\n--- LOOP DETECTED --- Session {session} reset.")- # Automatically reset the problematic session- reset_reason = f"Detected repeating output pattern (last {chunk_size} chars repeated {repeat_threshold} times)"- await self.reset_terminal(session=session, reason=reset_reason)- # Return informative message to the agent with truncated output and pattern- return f"{truncated_output}\n--- LOOP DETECTED & SESSION RESET ---\n{loop_detected_msg}\nRepeating pattern identified: '{last_chunk[:128]}{'...' if len(last_chunk)>128 else ''}'\nThe terminal session {session} was automatically reset.\nPlease review the code or command that caused the loop to prevent recurrence."- # --- End of repetition check ------ # Check for shell prompt at the end of output- last_lines = full_output.splitlines()[-3:] if full_output else []- for line in last_lines:- for pat in prompt_patterns:- if pat.search(line.strip()):- PrintStyle(font_color="#229954").print("Detected shell prompt, returning output early.")- return full_output-- if not got_output:- # Waiting for first output- if now - start_time > first_output_timeout:- PrintStyle.error(f"No output for {first_output_timeout}s after start, returning.")- break+ truncated_output = truncate_text(self.agent, full_output, 10_000)+ self.log.update(content=truncated_output)+ idle = 0else:- idle += 1- if (full_output and idle > wait_with_output / SLEEP_TIME) or (- not full_output and idle > wait_without_output / SLEEP_TIME- ):+ # Waiting for more output after first output+ if now - last_output_time > between_output_timeout:+ PrintStyle.error(f"No output for {between_output_timeout}s after last output, returning.")break+return full_output- async def reset_terminal(self, session=0):- if session in self.state.shells:- self.state.shells[session].close()- del self.state.shells[session]- await self.prepare_state(reset=True)- response = self.agent.read_prompt("fw.code_reset.md")+ async def reset_terminal(self, session=0, reason: str | None = None):+ # Print the reason for the reset to the console if provided+ if reason:+ PrintStyle(font_color="#FFA500", bold=True).print(f"Resetting terminal session {session}... Reason: {reason}")+ else:+ PrintStyle(font_color="#FFA500", bold=True).print(f"Resetting terminal session {session}...")++ # Only reset the specified session while preserving others+ await self.prepare_state(reset=True, session=session)+ response = self.agent.read_prompt("fw.code_reset.md") # Standard message for agent historyself.log.update(content=response)- return response+ return responsediff --cc python/tools/input.pyindex 5f04c65ad,12dcf1cf5..7de338b4b--- a/python/tools/input.py+++ b/python/tools/input.py@@@ -5,13 -5,10 +5,13 @@@ from python.tools.code_execution_tool iclass Input(Tool):- async def execute(self, keyboard="", **kwargs):+ async def execute(self, keyboard="", session=0, **kwargs):# normalize keyboard inputkeyboard = keyboard.rstrip()- keyboard += "\\n"+ keyboard += "\n"++ # terminal session number+ session = int(self.args.get("session", 0))# forward keyboard input to code execution toolargs = {"runtime": "terminal", "code": keyboard, "session": session}