The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(terminal): lifecycle _unregister_env + _quiet; guards guidance table, shared _blocked_json, lifted script reader
Teknium2fe6fd9b6c24
diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.pyindex d7cc2dba829..d8092714368 100644--- a/tools/terminal_tool_guards.py+++ b/tools/terminal_tool_guards.py@@ -38,9 +38,7 @@ def _is_safe_workdir_char(ch: str) -> bool:def _validate_workdir(workdir: str) -> str | None:"""Error message if *workdir* has a disallowed character, else None.Allowlist rather than deny-list so novel metacharacters can't slip through."""- if not workdir:- return None- for ch in workdir:+ for ch in workdir or "":if not _is_safe_workdir_char(ch):return (f"Blocked: workdir contains disallowed character {repr(ch)}. "@@ -61,6 +59,11 @@ def _safe_command_preview(command: Any, limit: int = 200) -> str:return f"<{type(command).__name__}>"+def _blocked_json(error: str, status: str) -> str:+ """The guard result envelope: exit_code 1 + *error* + *status*."""+ return json.dumps({"output": "", "exit_code": 1, "error": error, "status": status}, ensure_ascii=False)++_SHELL_LEVEL_BACKGROUND_RE = re.compile(r"(?:^|[;&|]\s*|&&\s*|\|\|\s*|\$\(\s*)(?:nohup|disown|setsid)\b", re.IGNORECASE | re.MULTILINE)@@ -80,19 +83,41 @@ def _strip_quotes(command: str) -> str:result = strip_inert_heredoc_bodies(command)result = re.sub(r"'[^']*'", "''", result)result = re.sub(r'"(?:[^"\\]|\\.)*"', '""', result)- result = re.sub(r"`[^`]*`", "``", result)- return result---_LONG_LIVED_FOREGROUND_PATTERNS = (- re.compile(r"\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b", re.IGNORECASE),- re.compile(r"\bdocker\s+compose\s+up\b", re.IGNORECASE),- re.compile(r"\bnext\s+dev\b", re.IGNORECASE),- re.compile(r"\bvite(?:\s|$)", re.IGNORECASE),- re.compile(r"\bnodemon\b", re.IGNORECASE),- re.compile(r"\buvicorn\b", re.IGNORECASE),- re.compile(r"\bgunicorn\b", re.IGNORECASE),- re.compile(r"\bpython(?:3)?\s+-m\s+http\.server\b", re.IGNORECASE),+ return re.sub(r"`[^`]*`", "``", result)+++_LONG_LIVED_FOREGROUND_PATTERNS = tuple(re.compile(p, re.IGNORECASE) for p in (+ r"\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|watch)\b",+ r"\bdocker\s+compose\s+up\b",+ r"\bnext\s+dev\b",+ r"\bvite(?:\s|$)",+ r"\bnodemon\b",+ r"\buvicorn\b",+ r"\bgunicorn\b",+ r"\bpython(?:3)?\s+-m\s+http\.server\b",+))++# Ordered (predicate on the unquoted command, guidance) — first hit wins.+_FOREGROUND_GUIDANCE = (+ (+ _SHELL_LEVEL_BACKGROUND_RE.search,+ "Foreground command uses shell-level background wrappers (nohup/disown/setsid). "+ "Re-send WITHOUT the wrapper as terminal(command=\"<cmd>\", background=true, "+ "notify_on_complete=true) so Hermes tracks the process, then run readiness "+ "checks and tests in separate commands.",+ ),+ (+ lambda s: _INLINE_BACKGROUND_AMP_RE.search(s) or _TRAILING_BACKGROUND_AMP_RE.search(s),+ "Foreground command uses '&' backgrounding. Re-send WITHOUT the '&' as "+ "terminal(command=\"<cmd>\", background=true) — add notify_on_complete=true "+ "for bounded jobs — then run health checks and tests in follow-up terminal calls.",+ ),+ (+ lambda s: any(p.search(s) for p in _LONG_LIVED_FOREGROUND_PATTERNS),+ "This foreground command appears to start a long-lived server/watch process. "+ "Run it with background=true, verify readiness (health endpoint/log signal), "+ "then execute tests in a separate command.",+ ),)@@ -112,32 +137,41 @@ def _foreground_background_guidance(command: str) -> str | None:backgrounding (it should be a managed background session), else None."""if _looks_like_help_or_version_command(command):return None-unquoted = _strip_quotes(command)+ return next((msg for hit, msg in _FOREGROUND_GUIDANCE if hit(unquoted)), None)- if _SHELL_LEVEL_BACKGROUND_RE.search(unquoted):- return (- "Foreground command uses shell-level background wrappers (nohup/disown/setsid). "- "Re-send WITHOUT the wrapper as terminal(command=\"<cmd>\", background=true, "- "notify_on_complete=true) so Hermes tracks the process, then run readiness "- "checks and tests in separate commands."- )-- if _INLINE_BACKGROUND_AMP_RE.search(unquoted) or _TRAILING_BACKGROUND_AMP_RE.search(unquoted):- return (- "Foreground command uses '&' backgrounding. Re-send WITHOUT the '&' as "- "terminal(command=\"<cmd>\", background=true) — add notify_on_complete=true "- "for bounded jobs — then run health checks and tests in follow-up terminal calls."- )-- for pattern in _LONG_LIVED_FOREGROUND_PATTERNS:- if pattern.search(unquoted):- return (- "This foreground command appears to start a long-lived server/watch process. "- "Run it with background=true, verify readiness (health endpoint/log signal), "- "then execute tests in a separate command."- )+def _read_script_for_guard(env: Any, guard_cwd: str, script_path: str, max_bytes: int) -> Optional[str]:+ """Best-effort script read: host filesystem first, then a bounded+ ``env.execute('head -c ... < path')`` for remote backends. Binary content+ (NUL byte) is not a script: feeding it to the guard tokenizes machine code+ into bogus paths and crashes the scanner, so it yields None."""+ if env is None:+ return None+ try:+ local_path = Path(script_path).expanduser()+ if not local_path.is_absolute():+ local_path = Path(guard_cwd) / local_path+ if local_path.is_file():+ metadata = local_path.stat()+ if stat.S_ISREG(metadata.st_mode) and metadata.st_size <= max_bytes:+ data = local_path.read_bytes()+ if len(data) <= max_bytes:+ return None if b"\x00" in data else data.decode("utf-8", errors="replace")+ except Exception:+ pass+ # Remote backend: bound the read at the source with `head -c` so an+ # oversized binary never crosses the wire (an unbounded `cat` once+ # pinned the gateway's tool thread for 30+ min on a shlex scan). One+ # byte over budget is enough for lifecycle_guard to fail closed. The+ # `< path` redirect keeps leading-dash paths out of argv.+ try:+ result = env.execute(f"head -c {max_bytes + 1} < {shlex.quote(script_path)}")+ if result.get("returncode", -1) == 0:+ output = result.get("output", "")+ return None if output and "\x00" in output else output+ except Exception:+ passreturn None@@ -174,85 +208,32 @@ def gateway_lifecycle_block(contains_launchctl_submit_command,)if contains_launchctl_submit_command(command):- return json.dumps({- "output": "",- "exit_code": 1,- "error": (- "Blocked: launchctl submit/bootstrap registers a persistent "- "KeepAlive job and is unsafe from inside the gateway process. "- "Use Hermes cron for one-shot delayed work, or install an "- "explicit LaunchAgent from a separate shell."- ),- "status": "error",- }, ensure_ascii=False)+ return _blocked_json(+ "Blocked: launchctl submit/bootstrap registers a persistent "+ "KeepAlive job and is unsafe from inside the gateway process. "+ "Use Hermes cron for one-shot delayed work, or install an "+ "explicit LaunchAgent from a separate shell.",+ "error",+ )guard_cwd_base = get_session_cwd(session_key)if guard_cwd_base is None:guard_cwd_base = getattr(env, "cwd", None) or cwdguard_cwd = _resolve_command_cwd(- workdir=workdir,- default_cwd=guard_cwd_base,- session_key=session_key,- env_type=env_type,+ workdir=workdir, default_cwd=guard_cwd_base, session_key=session_key, env_type=env_type,)-- def _read_script_in_env(script_path: str) -> Optional[str]:- """Best-effort script read: host filesystem first, then a bounded- ``env.execute('head -c ... < path')`` for remote backends."""- if env is None:- return None- try:- local_path = Path(script_path).expanduser()- if not local_path.is_absolute():- local_path = Path(guard_cwd) / local_path- if local_path.is_file():- metadata = local_path.stat()- if stat.S_ISREG(metadata.st_mode) and metadata.st_size <= _MAX_REFERENCED_SCRIPT_BYTES:- data = local_path.read_bytes()- if len(data) <= _MAX_REFERENCED_SCRIPT_BYTES:- if b"\x00" in data:- # Binary, not a script: feeding it to the guard- # tokenizes machine code into bogus paths and- # crashes the scanner. Nothing to scan.- return None- return data.decode("utf-8", errors="replace")- except Exception:- pass- # Remote backend: bound the read at the source with `head -c` so an- # oversized binary never crosses the wire (an unbounded `cat` once- # pinned the gateway's tool thread for 30+ min on a shlex scan). One- # byte over budget is enough for lifecycle_guard to fail closed. The- # `< path` redirect keeps leading-dash paths out of argv.- try:- result = env.execute(- f"head -c {_MAX_REFERENCED_SCRIPT_BYTES + 1} "- f"< {shlex.quote(script_path)}"- )- if result.get("returncode", -1) == 0:- output = result.get("output", "")- if output and "\x00" in output: # binary, see above- return None- return output- except Exception:- pass- return None-if contains_gateway_lifecycle_command_or_referenced_script(command,cwd=guard_cwd,- read_remote_script=_read_script_in_env,+ read_remote_script=lambda p: _read_script_for_guard(env, guard_cwd, p, _MAX_REFERENCED_SCRIPT_BYTES),):- return json.dumps({- "output": "",- "exit_code": 1,- "error": (- "Blocked: command or referenced script cannot restart, stop, or "- "uninstall the gateway from inside the gateway process. The gateway would "- "kill this command before it could complete (SIGTERM propagates "- "to child processes). Run `hermes gateway restart` from a "- "separate shell outside the running gateway."- ),- "status": "error",- }, ensure_ascii=False)+ return _blocked_json(+ "Blocked: command or referenced script cannot restart, stop, or "+ "uninstall the gateway from inside the gateway process. The gateway would "+ "kill this command before it could complete (SIGTERM propagates "+ "to child processes). Run `hermes gateway restart` from a "+ "separate shell outside the running gateway.",+ "error",+ )return None@@ -276,21 +257,9 @@ def self_repo_block(if not guard_active():return None- guard_cwd = _resolve_command_cwd(- workdir=workdir,- default_cwd=cwd,- session_key=session_key,- )+ guard_cwd = _resolve_command_cwd(workdir=workdir, default_cwd=cwd, session_key=session_key)hit, msg = detect_self_repo_git_mutation(command, guard_cwd)if not hit:return None- logger.warning(- "Blocked self-repo git mutation (command: %s)",- _safe_command_preview(command),- )- return json.dumps({- "output": "",- "exit_code": 1,- "error": msg,- "status": "blocked",- }, ensure_ascii=False)+ logger.warning("Blocked self-repo git mutation (command: %s)", _safe_command_preview(command))+ return _blocked_json(msg, "blocked")diff --git a/tools/terminal_tool_lifecycle.py b/tools/terminal_tool_lifecycle.pyindex 6ff876084fc..7ef977abd92 100644--- a/tools/terminal_tool_lifecycle.py+++ b/tools/terminal_tool_lifecycle.py@@ -7,6 +7,7 @@ Split out of ``tools/terminal_tool.py``; every public/patched name is re-importeso ``tools.terminal_tool.<name>`` keeps resolving (and monkeypatching) as before."""+import globimport loggingimport inspectimport shutil@@ -19,6 +20,7 @@ from tools.terminal_tool_backends import (_container_config_from_config,_ssh_config_from_config,)+from tools.terminal_tool_config import _quiet# Log-record parity with the origin module.logger = logging.getLogger("tools.terminal_tool")@@ -31,35 +33,33 @@ _disk_usage_cache: dict = {"timestamp": 0.0, "result": False}_DISK_USAGE_CACHE_TTL = 300.0 # seconds+def _scratch_paths():+ return glob.glob(str(_get_scratch_dir() / "hermes-*"))++def _check_disk_usage_warning():"""True when hermes scratch dirs exceed the warning threshold (cached, advisory)."""from tools.terminal_tool import DISK_USAGE_WARNING_THRESHOLD_GB- import time as _time_mod- now = _time_mod.monotonic()- if now - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL:+ if time.monotonic() - _disk_usage_cache["timestamp"] < _DISK_USAGE_CACHE_TTL:return _disk_usage_cache["result"]try:- scratch_dir = _get_scratch_dir()total_bytes = 0- import glob- for path in glob.glob(str(scratch_dir / "hermes-*")):+ for path in _scratch_paths():for f in Path(path).rglob('*'):if f.is_file():- try:+ with _quiet("Could not stat file %s", f, exc=OSError):total_bytes += f.stat().st_size- except OSError as e:- logger.debug("Could not stat file %s: %s", f, e)total_gb = total_bytes / (1024 ** 3)exceeded = total_gb > DISK_USAGE_WARNING_THRESHOLD_GBif exceeded:logger.warning("Disk usage (%.1fGB) exceeds threshold (%.0fGB). Consider running cleanup_all_environments().",total_gb, DISK_USAGE_WARNING_THRESHOLD_GB)- _disk_usage_cache["timestamp"] = _time_mod.monotonic()+ _disk_usage_cache["timestamp"] = time.monotonic()_disk_usage_cache["result"] = exceededreturn exceeded- except Exception as e:- logger.debug("Disk usage warning check failed: %s", e, exc_info=True)+ except Exception:# Don't update cache on error so the next call retries.+ logger.debug("Disk usage warning check failed", exc_info=True)return False@@ -115,6 +115,23 @@ def _clear_file_ops_cache(task_id: str) -> None:pass+def _unregister_env(task_id: str):+ """Pop *task_id* from the env cache, activity map and creation locks; return+ the env (or None). Callers run the (slow) teardown OUTSIDE the lock —+ Modal/Docker teardown can block 10-15s and would stall every concurrent+ terminal/file tool call."""+ from tools.terminal_tool import (+ _active_environments, _creation_locks, _creation_locks_lock, _env_lock,+ _last_activity,+ )+ with _env_lock:+ env = _active_environments.pop(task_id, None)+ _last_activity.pop(task_id, None)+ with _creation_locks_lock:+ _creation_locks.pop(task_id, None)+ return env++def _cleanup_inactive_envs(lifetime_seconds: int = 300):"""Clean up environments that have been inactive for longer than lifetime_seconds."""from tools.terminal_tool import (@@ -132,27 +149,20 @@ def _cleanup_inactive_envs(lifetime_seconds: int = 300):except ImportError:pass- # Phase 1: unregister stale entries under the lock. Do NOT call- # env.cleanup() inside the lock — Modal/Docker teardown can block 10-15s- # and would stall every concurrent terminal/file tool call.- envs_to_stop = [] # list of (task_id, env) pairs-+ # Phase 1: unregister stale entries atomically under the lock; phase 2:+ # stop them outside it (see _unregister_env for why).with _env_lock:- for task_id, last_time in list(_last_activity.items()):- if current_time - last_time > lifetime_seconds:- env = _active_environments.pop(task_id, None)- _last_activity.pop(task_id, None)- if env is not None:- envs_to_stop.append((task_id, env))-+ stale = [t for t, last in list(_last_activity.items()) if current_time - last > lifetime_seconds]+ envs_to_stop = [(t, _active_environments.pop(t, None)) for t in stale]+ for t in stale:+ _last_activity.pop(t, None)with _creation_locks_lock:- for task_id, _ in envs_to_stop:- _creation_locks.pop(task_id, None)-- # Phase 2: stop the sandboxes outside the lock.+ for t in stale:+ _creation_locks.pop(t, None)for task_id, env in envs_to_stop:- _clear_file_ops_cache(task_id)- _teardown_env(env, task_id)+ if env is not None:+ _clear_file_ops_cache(task_id)+ _teardown_env(env, task_id)def get_active_env(task_id: str):@@ -190,8 +200,7 @@ def ensure_task_env(task_id: Optional[str] = None):_last_activity[effective_task_id] = time.time()return existing- overrides = resolve_task_overrides(task_id)- image = _select_image(env_type, overrides, config)+ image = _select_image(env_type, resolve_task_overrides(task_id), config)_start_cleanup_thread()@@ -238,34 +247,26 @@ def is_persistent_env(task_id: str) -> bool:env = get_active_env(task_id)if env is None:return False- if getattr(env, "_session_scoped", False):- return True- return bool(getattr(env, "_persistent", False))+ return bool(getattr(env, "_session_scoped", False) or getattr(env, "_persistent", False))def cleanup_all_environments():"""Clean up ALL active environments. Use with caution."""from tools.terminal_tool import _active_environments, cleanup_vm- task_ids = list(_active_environments.keys())cleaned = 0-- for task_id in task_ids:+ for task_id in list(_active_environments.keys()):try:cleanup_vm(task_id)cleaned += 1except Exception as e:logger.error("Error cleaning %s: %s", task_id, e, exc_info=True)-+# Also clean any orphaned directories- scratch_dir = _get_scratch_dir()- import glob- for path in glob.glob(str(scratch_dir / "hermes-*")):- try:+ for path in _scratch_paths():+ with _quiet("Failed to remove orphaned path %s", path, exc=OSError):shutil.rmtree(path, ignore_errors=True)logger.info("Removed orphaned: %s", path)- except OSError as e:- logger.debug("Failed to remove orphaned path %s: %s", path, e)-+if cleaned > 0:logger.info("Cleaned %d environments", cleaned)return cleaned@@ -284,20 +285,8 @@ def cleanup_vm(task_id: str, *, force_remove: bool = False):directly, so persist-mode idle envs are likewise no-op'd; only the orphanreaper at next startup reclaims them."""- from tools.terminal_tool import (- _active_environments, _creation_locks, _creation_locks_lock, _env_lock,- _last_activity,- )- # Unregister under the lock; run the (slow) cleanup outside it.- with _env_lock:- env = _active_environments.pop(task_id, None)- _last_activity.pop(task_id, None)-- with _creation_locks_lock:- _creation_locks.pop(task_id, None)-+ env = _unregister_env(task_id)_clear_file_ops_cache(task_id)-if env is None:return_teardown_env(@@ -323,7 +312,5 @@ def _evict_environment_for_task(task_id: Optional[str]) -> None:if env is not None:evicted.append(env)for env in evicted:- try:+ with _quiet("cleanup of degraded environment failed"):env.cleanup()- except Exception:- logger.debug("cleanup of degraded environment failed", exc_info=True)