The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(terminal-tool): redact terminal error result fields
Coy Geek530d37820c6a
diff --git a/tests/tools/test_terminal_error_redaction.py b/tests/tools/test_terminal_error_redaction.pynew file mode 100644index 00000000000..ad68edaa809--- /dev/null+++ b/tests/tools/test_terminal_error_redaction.py@@ -0,0 +1,154 @@+"""Terminal tool result errors must not leak credential-shaped strings."""++import json+from types import SimpleNamespace++import agent.redact as redact+import tools.terminal_tool as terminal_tool+++SECRET = "OPENAI_API_KEY=sk-testterminalerrorredaction1234567890"+++def _minimal_terminal_config(cwd="/tmp"):+ return {+ "env_type": "local",+ "cwd": cwd,+ "timeout": 1,+ "host_cwd": None,+ "modal_mode": "auto",+ "docker_image": "",+ "singularity_image": "",+ "modal_image": "",+ "daytona_image": "",+ }+++def _patch_common(monkeypatch, env):+ monkeypatch.setattr(terminal_tool, "_active_environments", {"default": env})+ monkeypatch.setattr(terminal_tool, "_last_activity", {"default": 0})+ monkeypatch.setattr(terminal_tool, "_task_env_overrides", {})+ monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: _minimal_terminal_config())+ monkeypatch.setattr(terminal_tool, "_start_cleanup_thread", lambda: None)+ monkeypatch.setattr(terminal_tool, "_resolve_container_task_id", lambda value: value or "default")+ monkeypatch.setattr(+ terminal_tool,+ "_check_all_guards",+ lambda command, env_type, **kwargs: {"approved": True},+ )+++def assert_secret_redacted(payload, field):+ assert SECRET not in payload[field]+ assert "sk-testterminalerrorredaction1234567890" not in payload[field]+ assert "***" in payload[field]+++def test_foreground_retry_error_redacts_exception_text(monkeypatch):+ class FailingEnv:+ env = {}++ def execute(self, command, **kwargs):+ raise RuntimeError(f"backend failed with {SECRET}")++ _patch_common(monkeypatch, FailingEnv())+ monkeypatch.setattr(terminal_tool.time, "sleep", lambda seconds: None)++ result = json.loads(terminal_tool.terminal_tool(command="echo ok"))++ assert result["exit_code"] == -1+ assert_secret_redacted(result, "error")+++def test_successful_output_preserves_redaction_opt_out(monkeypatch):+ class Env:+ env = {}++ def execute(self, command, **kwargs):+ return {"output": f"{SECRET}\n", "returncode": 0}++ _patch_common(monkeypatch, Env())+ monkeypatch.setattr(redact, "_REDACT_ENABLED", False)++ result = json.loads(terminal_tool.terminal_tool(command="echo ok"))++ assert result["exit_code"] == 0+ assert result["output"] == SECRET+++def test_successful_output_keeps_command_aware_redactor(monkeypatch):+ class Env:+ env = {}++ def execute(self, command, **kwargs):+ return {"output": "ordinary output\n", "returncode": 0}++ calls = []++ def fake_redact_terminal_output(output, command):+ calls.append((output, command))+ return "command-aware output"++ _patch_common(monkeypatch, Env())+ monkeypatch.setattr(redact, "redact_terminal_output", fake_redact_terminal_output)++ result = json.loads(terminal_tool.terminal_tool(command="echo ok"))++ assert result["exit_code"] == 0+ assert result["output"] == "command-aware output"+ assert calls == [("ordinary output", "echo ok")]+++def test_environment_creation_import_error_redacts_exception_text(monkeypatch):+ _patch_common(monkeypatch, None)+ monkeypatch.setattr(terminal_tool, "_active_environments", {})+ monkeypatch.setattr(terminal_tool, "_creation_locks", {})++ def fail_create_environment(**kwargs):+ raise ImportError(f"backend import failed with {SECRET}")++ monkeypatch.setattr(terminal_tool, "_create_environment", fail_create_environment)++ result = json.loads(terminal_tool.terminal_tool(command="echo ok"))++ assert result["exit_code"] == -1+ assert result["status"] == "disabled"+ assert_secret_redacted(result, "error")+++def test_background_start_error_redacts_exception_text(monkeypatch):+ class Env:+ env = {}++ class FailingRegistry:+ pending_watchers = []++ def spawn_local(self, **kwargs):+ raise RuntimeError(f"spawn failed with {SECRET}")++ import tools.process_registry as process_registry_mod++ _patch_common(monkeypatch, Env())+ monkeypatch.setattr(process_registry_mod, "process_registry", FailingRegistry())++ result = json.loads(terminal_tool.terminal_tool(command="echo ok", background=True))++ assert result["exit_code"] == -1+ assert_secret_redacted(result, "error")+++def test_outer_exception_redacts_error_and_traceback(monkeypatch):+ env = SimpleNamespace(env={})+ _patch_common(monkeypatch, env)+ monkeypatch.setattr(+ terminal_tool,+ "_get_env_config",+ lambda: (_ for _ in ()).throw(RuntimeError(f"config failed with {SECRET}")),+ )++ result = json.loads(terminal_tool.terminal_tool(command="echo ok"))++ assert result["exit_code"] == -1+ assert result["status"] == "error"+ assert_secret_redacted(result, "error")+ assert_secret_redacted(result, "traceback")diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex 00f50bba995..f9dd09114fc 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -54,6 +54,13 @@ from utils import env_var_enabledlogger = logging.getLogger(__name__)+def _redact_terminal_error_text(value: Any) -> str:+ """Force-redact text before serializing a terminal error envelope."""+ from agent.redact import redact_sensitive_text++ return redact_sensitive_text("" if value is None else str(value), force=True)++# ---------------------------------------------------------------------------# Global interrupt event: set by the agent when a user interrupt arrives.# The terminal tool polls this during command execution so it can kill@@ -2561,7 +2568,9 @@ def terminal_tool(return json.dumps({"output": "","exit_code": -1,- "error": f"Terminal tool disabled: environment creation failed ({e})",+ "error": _redact_terminal_error_text(+ f"Terminal tool disabled: environment creation failed ({e})"+ ),"status": "disabled"}, ensure_ascii=False)@@ -3033,7 +3042,9 @@ def terminal_tool(return json.dumps({"output": "","exit_code": -1,- "error": f"Failed to start background process: {str(e)}"+ "error": _redact_terminal_error_text(+ f"Failed to start background process: {e}"+ )}, ensure_ascii=False)else:# Run foreground command with retry logic@@ -3093,7 +3104,9 @@ def terminal_tool(return json.dumps({"output": "","exit_code": -1,- "error": f"Command execution failed: {type(e).__name__}: {str(e)}"+ "error": _redact_terminal_error_text(+ f"Command execution failed: {type(e).__name__}: {e}"+ )}, ensure_ascii=False)# Got a result@@ -3305,7 +3318,6 @@ def terminal_tool(degraded_mode = os.getenv("TERMINAL_DEGRADED_MODE", "warn").strip().lower()if degraded_mode == "fail":import traceback- from agent.redact import redact_sensitive_texttb_str = traceback.format_exc()logger.error("terminal_tool exception:\n%s", tb_str)# Exception text can embed the failing command line (and any@@ -3313,8 +3325,8 @@ def terminal_tool(return json.dumps({"output": "","exit_code": -1,- "error": redact_sensitive_text(f"Failed to execute command: {str(e)}"),- "traceback": redact_sensitive_text(tb_str),+ "error": _redact_terminal_error_text(f"Failed to execute command: {e}"),+ "traceback": _redact_terminal_error_text(tb_str),"status": "error"}, ensure_ascii=False)@@ -3337,7 +3349,6 @@ def terminal_tool(except Exception as e:import traceback- from agent.redact import redact_sensitive_texttb_str = traceback.format_exc()logger.error("terminal_tool exception:\n%s", tb_str)# Exception text can embed the failing command line (and any@@ -3345,8 +3356,8 @@ def terminal_tool(return json.dumps({"output": "","exit_code": -1,- "error": redact_sensitive_text(f"Failed to execute command: {str(e)}"),- "traceback": redact_sensitive_text(tb_str),+ "error": _redact_terminal_error_text(f"Failed to execute command: {e}"),+ "traceback": _redact_terminal_error_text(tb_str),"status": "error"}, ensure_ascii=False)