Skip to content

The agent that grows with you

fix(terminal): a foreground command ending in a lone trailing & runs as a tracked background process instead of being refused

Tekniumd5c74fc1857c
diff --git a/agent/terminal_approval_batch.py b/agent/terminal_approval_batch.py
index 664536b5abb..a347abb01c6 100644
--- a/agent/terminal_approval_batch.py
+++ b/agent/terminal_approval_batch.py
@@ -57,7 +57,11 @@ class _TerminalSlot:
turn_id=getattr(self.batch.agent, "_current_turn_id", "") or "",
)
try:
- self.guard_key = (ref.args["command"], config["env_type"], tt._docker_has_host_access(config))
+ # Key on what will actually run: a foreground `cmd &` executes as `cmd`.
+ command = ref.args["command"]
+ if not ref.args.get("background"):
+ command = tt.trailing_amp_background_command(command) or command
+ self.guard_key = (command, config["env_type"], tt._docker_has_host_access(config))
self.decision = tt._check_all_guards(*self.guard_key)
finally:
reset_current_observability_context(tokens)
diff --git a/tests/tools/test_terminal_foreground_timeout_cap.py b/tests/tools/test_terminal_foreground_timeout_cap.py
index 956ba1c8a05..d80a8f463ac 100644
--- a/tests/tools/test_terminal_foreground_timeout_cap.py
+++ b/tests/tools/test_terminal_foreground_timeout_cap.py
@@ -50,7 +50,7 @@ class TestForegroundTimeoutCap:
deadline = time.time() + 10
while not marker.exists() and time.time() < deadline:
time.sleep(0.05)
- assert marker.read_text().count("x") == 1 # ran exactly once, in the background
+ assert marker.read_text(encoding="utf-8-sig").count("x") == 1 # ran exactly once, in the background
def test_zero_timeout_rejected(self):
"""timeout=0 must be rejected, not silently coerced to the default."""
@@ -149,7 +149,7 @@ class TestPromotionKeepsTheDetachmentGuard:
with patch("tools.terminal_tool._get_env_config", return_value=_make_env_config()), \
patch("tools.terminal_tool._start_cleanup_thread"):
- result = json.loads(terminal_tool(command="sleep 5 &", timeout=9999))
+ result = json.loads(terminal_tool(command="sleep 5 & echo started", timeout=9999))
result2 = json.loads(terminal_tool(command="nohup make test", timeout=9999))
assert "'&' backgrounding" in result["error"]
assert "nohup" in result2["error"]
diff --git a/tests/tools/test_terminal_trailing_amp_auto_background.py b/tests/tools/test_terminal_trailing_amp_auto_background.py
new file mode 100644
index 00000000000..18da3d98b2a
--- /dev/null
+++ b/tests/tools/test_terminal_trailing_amp_auto_background.py
@@ -0,0 +1,68 @@
+"""A foreground command whose ONLY backgrounding is a trailing `&` runs as terminal(background=true).
+
+Refusing it cost a full model turn to resend the same command with background=true (488 refusals in
+30 days of one user's sessions). Ambiguous shapes (inline `a & b`, nohup/disown/setsid, long-lived
+servers without `&`) keep the refusal: the caller may expect later commands to run after a check.
+"""
+import json
+import time
+from unittest.mock import patch
+
+import pytest
+
+
+def _env_config(cwd):
+ return {
+ "env_type": "local", "timeout": 180, "cwd": str(cwd), "host_cwd": None, "modal_mode": "auto",
+ "docker_image": "", "singularity_image": "", "modal_image": "", "daytona_image": "",
+ }
+
+
+def test_trailing_amp_runs_as_tracked_background_through_the_same_guards(tmp_path, monkeypatch):
+ """Real local backend + registry: one tracked session, the payload runs once, the approval
+ guard sees the command that actually runs, and the result says what Hermes did."""
+ from tools.process_registry import process_registry
+ from tools.terminal_tool import terminal_tool
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "hh"))
+ marker = tmp_path / "ran"
+ seen = []
+
+ def guard(command, env_type, **kw):
+ seen.append(command)
+ return {"approved": True}
+
+ with patch("tools.terminal_tool._get_env_config", return_value=_env_config(tmp_path)), \
+ patch("tools.terminal_tool._start_cleanup_thread"), \
+ patch("tools.terminal_tool._check_all_guards", side_effect=guard):
+ result = json.loads(terminal_tool(command=f"echo x >> {marker} && sleep 0.2 &"))
+
+ assert result.get("error") is None, result
+ assert result["session_id"].startswith("proc_")
+ assert "trailing & was converted to background=true" in result["auto_backgrounded"]
+ assert "hint" not in result # the silent-bg hint would tell it to re-launch a second copy
+ assert seen == [f"echo x >> {marker} && sleep 0.2"]
+ session = process_registry.get(result["session_id"])
+ assert session.command == f"echo x >> {marker} && sleep 0.2"
+ deadline = time.time() + 10
+ while not marker.exists() and time.time() < deadline:
+ time.sleep(0.05)
+ assert marker.read_text(encoding="utf-8-sig").count("x") == 1
+
+
[email protected]("command, expected", [
+ ("python3 -m http.server 8765 & curl -s localhost:8765", "'&' backgrounding"),
+ ("sleep 1 & sleep 2 &", "'&' backgrounding"),
+ ("nohup ./worker.sh > /dev/null 2>&1 &", "nohup/disown/setsid"),
+ ("python3 -m http.server 8765", "long-lived server"),
+ # Approval keys on the `&` here (gateway outside its service manager): no conversion.
+ ("hermes gateway run &", "'&' backgrounding"),
+])
+def test_ambiguous_backgrounding_is_still_refused_unchanged(tmp_path, command, expected):
+ from tools.terminal_tool import terminal_tool
+
+ with patch("tools.terminal_tool._get_env_config", return_value=_env_config(tmp_path)), \
+ patch("tools.terminal_tool._start_cleanup_thread"), \
+ patch("tools.terminal_tool._acquire_env", side_effect=AssertionError("must not run")):
+ result = json.loads(terminal_tool(command=command))
+ assert expected in result["error"]
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 21b849aa5d9..594ee075a51 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -850,7 +850,7 @@ def _command_requires_pipe_stdin(command: str) -> bool:
from tools.terminal_tool_guards import (
_foreground_background_guidance, _safe_command_preview, _validate_workdir,
- gateway_lifecycle_block, self_repo_block,
+ gateway_lifecycle_block, self_repo_block, trailing_amp_background_command,
)
from tools.terminal_tool_background import _YIELDED_NOTE, spawn_background_process, yield_to_background_handler
from tools.terminal_tool_result import finalize_foreground_result
@@ -1059,6 +1059,9 @@ class _ExecPlan:
# Set when a foreground call asked for more than FOREGROUND_MAX_TIMEOUT and was promoted to a
# tracked background process instead of being refused (the requested seconds, for the note).
promoted_from_foreground_timeout: Optional[int] = None
+ # Set when a foreground `cmd &` (the trailing `&` its only backgrounding) is run as
+ # terminal(command="cmd", background=true) instead of being refused: the command to run.
+ auto_background_command: Optional[str] = None
_PROMOTED_NOTE = (
@@ -1141,16 +1144,22 @@ def _plan_execution(
# need the command itself rewritten, which the tool cannot do safely.
# The detachment guidance applies whether or not the call is promoted: a promoted `cmd &`
# would start a tracked shell that exits at once while its payload runs untracked.
- guidance = _foreground_background_guidance(command)
- if guidance:
- raise _Rejected(_error_json(guidance, status="error"))
- if timeout and timeout > FOREGROUND_MAX_TIMEOUT:
- promoted = timeout
+ # Exception: a lone TRAILING `&` is unambiguous (the caller asked for exactly what
+ # background=true does), so run it that way instead of spending a model turn on a resend.
+ auto_bg = trailing_amp_background_command(command)
+ if auto_bg is None:
+ guidance = _foreground_background_guidance(command)
+ if guidance:
+ raise _Rejected(_error_json(guidance, status="error"))
+ if timeout and timeout > FOREGROUND_MAX_TIMEOUT:
+ promoted = timeout
+ else:
+ auto_bg = None
return _ExecPlan(
config=config, env_type=env_type, effective_task_id=effective_task_id,
image=image, cwd=cwd, host_cwd=host_cwd, effective_timeout=timeout or config["timeout"],
- promoted_from_foreground_timeout=promoted,
+ promoted_from_foreground_timeout=promoted, auto_background_command=auto_bg,
)
@@ -1176,6 +1185,28 @@ def _with_promoted_note(result_json: str, requested_timeout: int) -> str:
return json.dumps(data, ensure_ascii=False)
+_AUTO_BACKGROUND_NOTE = (
+ "Ran in the background (the trailing & was converted to background=true; Hermes tracks the "
+ "process). Do NOT re-run it. Use process_manage (poll/log/wait/kill, session_id above) to check it."
+)
+
+
+def _with_auto_background_note(result_json: str) -> str:
+ """Attach the trailing-`&` conversion note to a spawn result (unchanged on error). The silent-
+ background hint is dropped: it says to re-launch with notify, which would start a second copy."""
+ try:
+ data = json.loads(result_json)
+ except (TypeError, ValueError):
+ return result_json
+ if not isinstance(data, dict) or data.get("error"):
+ return result_json
+ from tools.terminal_tool_background import _SILENT_BACKGROUND_HINT
+ if data.get("hint") == _SILENT_BACKGROUND_HINT:
+ data.pop("hint")
+ data["auto_backgrounded"] = _AUTO_BACKGROUND_NOTE
+ return json.dumps(data, ensure_ascii=False)
+
+
def _acquire_env(plan: _ExecPlan, task_id: Optional[str]) -> Any:
"""Cached env for the task, else create it under the per-task creation lock.
@@ -1400,6 +1431,11 @@ def terminal_tool(
plan = _plan_execution(
command, task_id=task_id, timeout=timeout, background=background, _host_local=_host_local,
)
+ auto_bg = getattr(plan, "auto_background_command", None)
+ if auto_bg is not None:
+ # From here on this IS a background=true call for the stripped command: every guard
+ # below (lifecycle, workdir, self-repo, dangerous-command approval) sees what runs.
+ command, background = auto_bg, True
env = _acquire_env(plan, task_id)
env_type, cwd, effective_task_id = plan.env_type, plan.cwd, plan.effective_task_id
@@ -1464,6 +1500,8 @@ def terminal_tool(
)
if plan.promoted_from_foreground_timeout is not None:
result = _with_promoted_note(result, plan.promoted_from_foreground_timeout)
+ elif auto_bg is not None:
+ result = _with_auto_background_note(result)
return _metered(None if _host_local else plan, result)
return _metered(None if _host_local else plan, _run_foreground(
command, env, plan,
diff --git a/tools/terminal_tool_guards.py b/tools/terminal_tool_guards.py
index da0e00f74d3..0413bb5dc82 100644
--- a/tools/terminal_tool_guards.py
+++ b/tools/terminal_tool_guards.py
@@ -141,6 +141,44 @@ def _foreground_background_guidance(command: str) -> str | None:
return next((msg for hit, msg in _FOREGROUND_GUIDANCE if hit(unquoted)), None)
+# `&` spellings that are not backgrounding: and-lists, fd redirects (`2>&1`, `>&2`, `&>`, `&>>`,
+# `<&3`) and the stderr pipe `|&`.
+_NON_BACKGROUND_AMP_RE = re.compile(r"&&|\d*[<>]&(?:\d+|-)?|&>>?|\|&")
+_TRAILING_AMP_ONLY_RE = re.compile(r"\s&\s*$")
+
+
+def trailing_amp_background_command(command: str) -> str | None:
+ """The command without its trailing `&` when that `&` is its ONLY backgrounding, else None.
+
+ Only the unambiguous shape converts: one line, one and-or list or pipeline (`a && b | c &`
+ backgrounds the whole list in bash, exactly what background=true runs), nothing after the
+ `&`. Inline `a & b`, `;` sequences, multi-line scripts/heredocs and nohup/disown/setsid keep
+ the refusal: there the caller may expect later commands to run after a readiness check, so
+ the tool cannot rewrite them safely. Quoted `&` (and inert heredoc bodies) never count.
+ """
+ if not isinstance(command, str) or _looks_like_help_or_version_command(command):
+ return None
+ unquoted = _strip_quotes(command)
+ if not _TRAILING_AMP_ONLY_RE.search(unquoted) or not command.rstrip().endswith("&"):
+ return None
+ body = unquoted.rstrip()[:-1]
+ if "\n" in body or "\r" in body or ";" in body or "#" in body or _SHELL_LEVEL_BACKGROUND_RE.search(body):
+ return None
+ if "&" in _NON_BACKGROUND_AMP_RE.sub("", body):
+ return None
+ stripped = command.rstrip()[:-1].rstrip()
+ if not stripped:
+ return None
+ # Approval runs on what executes (the stripped command). Some dangerous patterns key on the
+ # `&` itself (`hermes gateway run &` = gateway outside its service manager), so convert only
+ # when both spellings get the same verdict; otherwise the old refusal stands.
+ from tools.approval_detection import detect_dangerous_command, detect_hardline_command
+ if (detect_hardline_command(command)[0] != detect_hardline_command(stripped)[0]
+ or detect_dangerous_command(command)[0] != detect_dangerous_command(stripped)[0]):
+ return None
+ return stripped
+
+
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
diff --git a/website/docs/user-guide/features/tools.md b/website/docs/user-guide/features/tools.md
index 3e1194b841c..a3298a1ff45 100644
--- a/website/docs/user-guide/features/tools.md
+++ b/website/docs/user-guide/features/tools.md
@@ -235,6 +235,15 @@ process(action="write", session_id="proc_abc123", data="y") # Send input
PTY mode (`pty=true`) enables interactive CLI tools like Codex and Claude Code.
+A foreground command whose only backgrounding is a trailing `&` (for example
+`python3 -m http.server 8765 &` or `cd app && npm start > app.log 2>&1 &`) runs
+as `background=true` with the `&` removed, and the result carries an
+`auto_backgrounded` note with the `session_id`. It goes through the same
+approval checks as any background command. Shapes that mix in other commands
+(`server & curl ...`, `a; b &`, multi-line scripts) and `nohup`/`disown`/`setsid`
+wrappers are still refused with guidance, because Hermes cannot safely tell
+which part should keep running.
+
Completed background commands retain their exit status and captured output in the
active profile. Resume the conversation that launched the command (or its
compressed continuation), then use the original `session_id` with