Skip to content

The agent that grows with you

fix(compression): a denied tool call is not summarized as if it ran

EloquentBrush0x1b9594ef14be
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index da00b7efe60..493dd5ad999 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -2010,10 +2010,36 @@ def _json_dict(text: Any) -> dict:
return parsed if isinstance(parsed, dict) else {}
+def _summarize_refused_tool_result(tool_name: str, args: dict, content: str) -> "str | None":
+ """Summary for a call an approval or write guard refused (``BLOCKED: ...`` / ``status``
+ ``blocked``/``pending_approval``), else None. The per-tool summarizers describe the call as done
+ ("ran ...", "wrote to ..."), which would turn a user's denial into a record of the action and
+ drop the "do not retry" instruction. Strictly below _PRUNE_MIN_CHARS, like the clarify summary,
+ so later prune passes keep it."""
+ payload = _json_dict(content)
+ status = payload.get("status")
+ error = payload.get("error") if isinstance(payload.get("error"), str) else ""
+ if not error and content.lstrip().startswith("BLOCKED"):
+ error = content.strip()
+ if status == "pending_approval":
+ outcome = "awaiting the user's approval, not run"
+ elif status == "blocked" or error.lstrip().startswith("BLOCKED"):
+ outcome = "BLOCKED, not run"
+ if "NOT consented" in error:
+ outcome += "; the user did NOT consent, do not retry or reach the same outcome another way"
+ else:
+ return None
+ target = _str_arg(args, "command") or _str_arg(args, "path")
+ target = f" `{target if len(target) <= 60 else target[:57] + '...'}`" if target else ""
+ return f"[{tool_name}]{target} {outcome}"[:_PRUNE_MIN_CHARS - 1]
+
+
def _summarize_tool_result_unguarded(tool_name: str, tool_args: str, tool_content: str) -> str:
"""Build the summary line (unguarded; see ``_summarize_tool_result``)."""
args = _json_dict(tool_args)
content = tool_content or ""
+ if (refused := _summarize_refused_tool_result(tool_name, args, content)) is not None:
+ return refused
content_len = len(content)
line_count = content.count("\n") + 1 if content.strip() else 0
summarizer = _TOOL_RESULT_SUMMARIZERS.get(tool_name)
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index 9b629d6f8ba..a0b188c9526 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -436,6 +436,74 @@ class TestSummarizeToolResultClarify:
assert "Choice B" in summary
+def _refusals():
+ """Refused-call results from the real producers: the approval gate messages in their terminal /
+ tool_error envelopes, and a pending gateway approval."""
+ from tools import approval
+ from tools.registry import tool_error
+ from tools.terminal_tool import _error_json
+
+ gate = approval._COMMAND_GATE
+ return [
+ ("terminal", {"command": "rm -rf build"},
+ _error_json(gate.cli_denied.format(description="", breaker=""), status="blocked")),
+ ("terminal", {"command": "rm -rf build"},
+ _error_json(gate.transport_denied.format(breaker=""), status="blocked")),
+ ("terminal", {"command": "rm -rf build"},
+ _error_json(gate.cli_timeout.format(breaker=""), status="blocked")),
+ ("write_file", {"path": "AGENTS.md", "content": "a\nb"},
+ tool_error("BLOCKED: write to protected agent-instruction file(s) (AGENTS.md) was denied by "
+ "the user. The user has NOT consented to this write. Do NOT retry it or attempt "
+ "the same edit via another path (terminal, execute_code, etc.).")),
+ ]
+
+
+class TestSummarizeToolResultRefusals:
+ """A refused call must not be summarized as done ("ran ...", "wrote to ..."): that turns the
+ user's denial into a record of the action and drops the do-not-retry instruction."""
+
+ @pytest.mark.parametrize("tool_name,args,content", _refusals(),
+ ids=["cli_denied", "transport_denied", "cli_timeout", "write_guard"])
+ def test_denial_summary_keeps_not_run_and_no_consent(self, tool_name, args, content):
+ summary = _summarize_tool_result(tool_name, json.dumps(args), content)
+
+ assert "BLOCKED, not run" in summary and "did NOT consent" in summary
+ assert "ran `" not in summary and "wrote to" not in summary
+ assert len(summary) <= _PRUNE_MIN_CHARS - 1
+
+ def test_pending_approval_is_not_run(self):
+ from tools.terminal_tool import _error_json
+
+ content = _error_json("", status="pending_approval")
+ summary = _summarize_tool_result("terminal", json.dumps({"command": "rm -rf build"}), content)
+
+ assert summary == "[terminal] `rm -rf build` awaiting the user's approval, not run"
+
+ def test_ordinary_result_summary_unchanged(self):
+ content = json.dumps({"output": "BLOCKED by nothing", "exit_code": 0, "error": None})
+ summary = _summarize_tool_result("terminal", json.dumps({"command": "make"}), content)
+
+ assert summary == "[terminal] ran `make` -> exit 0, 1 lines output"
+
+ def test_prune_keeps_denial_across_passes(self, compressor):
+ tool_name, args, content = _refusals()[0]
+ assert len(content) > _PRUNE_MIN_CHARS
+ messages = [
+ {"role": "assistant", "tool_calls": [{"id": "t1", "type": "function",
+ "function": {"name": tool_name, "arguments": json.dumps(args)}}]},
+ {"role": "tool", "tool_call_id": "t1", "content": content},
+ {"role": "user", "content": "recent request"},
+ {"role": "assistant", "content": "recent response"},
+ ]
+
+ pruned, count = compressor._prune_old_tool_results(messages, protect_tail_count=2)
+ summary = pruned[1]["content"]
+
+ assert count == 1 and "BLOCKED, not run" in summary and "did NOT consent" in summary
+ pruned_again, _ = compressor._prune_old_tool_results(pruned, protect_tail_count=2)
+ assert pruned_again[1]["content"] == summary
+
+
class TestShouldCompress:
def test_below_threshold(self, compressor):
compressor.last_prompt_tokens = 50000