Skip to content

The agent that grows with you

fix: transform_terminal_output fires for background-process output too

teknium10ff5fa93a964
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index e2b6071dd6d..b79a0891bb2 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1903,10 +1903,14 @@ class GatewayNotificationsMixin:
"""Last ``limit`` chars of process output through the secret redactors (unconditional floor)."""
from gateway.run import _redact_gateway_user_facing_secrets
from tools.ansi_strip import strip_ansi
+ from tools.process_registry import transform_process_output
new_output = strip_ansi(session.output_buffer[-limit:]) if session.output_buffer else ""
if new_output:
from agent.redact import redact_terminal_output
- new_output = redact_terminal_output(new_output, getattr(session, "command", "") or "")
+ _command = getattr(session, "command", "") or ""
+ new_output = transform_process_output(new_output, command=_command, returncode=session.exit_code,
+ task_id=getattr(session, "task_id", "") or "")
+ new_output = redact_terminal_output(new_output, _command)
# redact_terminal_output() is unforced (raw when security.redact_secrets is off); this goes
# straight to the adapter, so apply the same unconditional floor as agent-notify.
new_output = _redact_gateway_user_facing_secrets(new_output)
@@ -1939,8 +1943,11 @@ class GatewayNotificationsMixin:
from gateway.run import _redact_gateway_user_facing_secrets
from agent.redact import redact_terminal_output
from tools.ansi_strip import strip_ansi
+ from tools.process_registry import transform_process_output
_command = getattr(session, "command", "") or ""
_raw = strip_ansi(session.output_buffer) if session.output_buffer else ""
+ _raw = transform_process_output(_raw, command=_command, returncode=session.exit_code,
+ task_id=getattr(session, "task_id", "") or "") if _raw else _raw
_raw = redact_terminal_output(_raw, _command)
# Keep the last ~2000 chars snapped to a line boundary, with a marker when cut.
_LIMIT = 2000
diff --git a/tests/tools/test_process_registry.py b/tests/tools/test_process_registry.py
index 7aae151fbfa..dfac3336ade 100644
--- a/tests/tools/test_process_registry.py
+++ b/tests/tools/test_process_registry.py
@@ -2044,6 +2044,51 @@ class TestHandleProcessRedaction:
assert "zzzopaque1234567890abcdef" in out["output"]
+class TestHandleProcessTransformHook:
+ """Background-process output goes through the same ``transform_terminal_output`` plugin seam
+ as the foreground ``terminal`` result — issue #70760 — hook FIRST, redaction AFTER, so a
+ replacement the plugin returns is still masked (the ordering the foreground path documents)."""
+
+ def _setup(self, monkeypatch, output, *, hook):
+ import agent.redact as _r
+ monkeypatch.setattr(_r, "_REDACT_ENABLED", True)
+ monkeypatch.setattr("hermes_cli.lifecycle.invoke_hook", hook)
+ from tools import process_registry as pr
+ reg = ProcessRegistry()
+ sess = _make_session(sid="proc_xform1", command="python app.py")
+ sess.output_buffer = output
+ sess.exited = True
+ sess.exit_code = 3
+ reg._running[sess.id] = sess
+ monkeypatch.setattr(pr, "process_registry", reg)
+ return pr, sess
+
+ def test_poll_wait_log_kill_results_are_transformed(self, monkeypatch):
+ seen = []
+
+ def hook(hook_name, **kw):
+ seen.append((hook_name, kw.get("command"), kw.get("returncode"), kw.get("task_id")))
+ return ["REWRITTEN:" + kw["output"]] if hook_name == "transform_terminal_output" else []
+
+ pr, sess = self._setup(monkeypatch, "raw line\n", hook=hook)
+ for action, key in (("poll", "output_preview"), ("log", "output"), ("wait", "output"), ("kill", "output")):
+ out = json.loads(pr._handle_process({"action": action, "session_id": sess.id}, task_id="task-bg"))
+ assert out[key].startswith("REWRITTEN:raw line"), (action, out)
+ assert [s for s in seen if s[0] == "transform_terminal_output"]
+ # The hook sees the command, the recorded exit code (None while running) and the caller's task_id.
+ assert ("transform_terminal_output", "python app.py", 3, "task-bg") in seen
+
+ def test_hook_replacement_is_still_redacted(self, monkeypatch):
+ secret = "sk-proj-abc123def456ghi789jkl012mno345"
+ pr, sess = self._setup(
+ monkeypatch, "plain output",
+ hook=lambda hook_name, **kw: [f"OPENAI_API_KEY={secret}"] if hook_name == "transform_terminal_output" else [],
+ )
+ out = json.loads(pr._handle_process({"action": "log", "session_id": sess.id}))
+ assert secret not in out["output"]
+ assert "OPENAI_API_KEY=" in out["output"]
+
+
# =========================================================================
# Reader loop: orphaned grandchild holding the stdout pipe (issue #68915)
# =========================================================================
diff --git a/tools/process_registry.py b/tools/process_registry.py
index be771756c08..ae924176c79 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -2488,11 +2488,22 @@ PROCESS_SCHEMA = {
}
-def _redact_process_result(result: dict) -> dict:
- """Redact secrets from background-process output before it reaches the model,
- session.db and CLI, mirroring the foreground ``terminal`` redaction so the two
- surfaces can't diverge. Respects ``security.redact_secrets``; ``redact_terminal_output``
- picks ``code_file`` from the recorded command. The command itself is redacted too.
+def transform_process_output(output: str, *, command: str, returncode: Optional[int], task_id: str = "") -> str:
+ """``transform_terminal_output`` seam for background-process output — the poll/wait/log/kill
+ results and the completion/heartbeat/watch notifications — so a plugin that rewrites terminal
+ output sees the same command output whether it ran in the foreground or not (#70760).
+ Same helper as the foreground path; callers redact AFTER it, never before, so a replacement
+ the plugin returns is still masked. ``returncode`` is None while the process is running and
+ ``env_type`` is not recorded per process, so it is passed empty."""
+ from tools.terminal_tool_result import _apply_output_transform_hook
+ return _apply_output_transform_hook(command, output, returncode, task_id or "", "")
+
+
+def _redact_process_result(result: dict, *, task_id: str = "") -> dict:
+ """Transform, then redact secrets from background-process output before it reaches the
+ model, session.db and CLI, mirroring the foreground ``terminal`` pipeline (hook first,
+ redaction after) so the two surfaces can't diverge. Respects ``security.redact_secrets``;
+ ``redact_terminal_output`` picks ``code_file`` from the recorded command.
The command string itself is also redacted in case it carried an inline credential. See #43025.
"""
@@ -2501,8 +2512,10 @@ def _redact_process_result(result: dict) -> dict:
from agent.redact import redact_sensitive_text, redact_terminal_output
command = result.get("command") or ""
+ task_id = task_id or str(result.get("task_id") or "")
for key in ("output", "output_preview"):
if isinstance(value := result.get(key), str) and value:
+ value = transform_process_output(value, command=command, returncode=result.get("exit_code"), task_id=task_id)
result[key] = redact_terminal_output(value, command)
if isinstance(command, str) and command:
result["command"] = redact_sensitive_text(command, code_file=True)
@@ -2592,7 +2605,7 @@ def _handle_process(args, **kw):
return tool_error(f"session_id is required for {action}")
handler, redact = _SESSION_ACTIONS[action]
result = handler(session_id, args)
- return json.dumps(_redact_process_result(result) if redact else result, ensure_ascii=False)
+ return json.dumps(_redact_process_result(result, task_id=kw.get("task_id") or "") if redact else result, ensure_ascii=False)
return tool_error(f"Unknown process action: {action}. Use: list, poll, log, wait, kill, write, submit, close, handoff")
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index f05a308db3c..67189fb4636 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -1520,6 +1520,8 @@ Applies to every tool. For terminal-only rewriting see `transform_terminal_outpu
Fires inside the `terminal` tool after foreground process capture has already been bounded by the environment, and before the final output limit. It lets plugins replace the captured stdout/stderr; the replacement is still subject to the final output limit.
+It also fires for background-process output on its way to the model or the chat: the `process_manage` `poll` / `wait` / `log` / `kill` results (and `list` previews) and the completion, heartbeat and watch-pattern notifications. There `returncode` is `None` while the process is still running and `env_type` is an empty string (the environment is not recorded per process). In both cases the hook runs *before* secret redaction, so a replacement that still carries a credential is masked.
+
**Callback signature:**
```python