Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): protect Codex exec file reads on the Responses path (#3621)

Tejas Chopra2c56a1b3a7b9
diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.py
index 42edd7024..b6e8cf36e 100644
--- a/headroom/proxy/handlers/openai.py
+++ b/headroom/proxy/handlers/openai.py
@@ -2157,10 +2157,13 @@ class OpenAIHandlerMixin:
# _tool_call_command_text helper:
# - function_call.arguments (Copilot bash, Codex exec_command, …)
# - local_shell_call.action (native Responses shell; argv or string)
+ # - custom_tool_call.input (Codex code-mode `exec`: JavaScript calling
+ # tools.exec_command({"cmd": …}))
# Content is gated per-output by _read_output_should_be_protected so
# confidently non-code DATA reads (lockfiles, JSON, logs, search) stay
# compressible, exactly like the chat path.
from headroom.transforms.content_router import (
+ _custom_tool_call_commands,
_is_read_command,
_read_output_should_be_protected,
_tool_call_command_text,
@@ -2177,6 +2180,17 @@ class OpenAIHandlerMixin:
command = _tool_call_command_text(item.get("arguments"))
elif item_type == "local_shell_call":
command = _tool_call_command_text(item.get("action"))
+ elif item_type == "custom_tool_call":
+ # One script can run several commands; its single output is a
+ # read when any of them is (over-protecting only costs savings).
+ command = next(
+ (
+ c
+ for c in _custom_tool_call_commands(item.get("input"))
+ if _is_read_command(c)
+ ),
+ "",
+ )
else:
continue
call_id = item.get("call_id")
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.py
index ebe21afbe..9734db464 100644
--- a/headroom/transforms/content_router.py
+++ b/headroom/transforms/content_router.py
@@ -567,6 +567,40 @@ def _tool_call_command_text(raw: Any) -> str:
return cmd if isinstance(cmd, str) else ""
+_EXEC_COMMAND_CALL_RE = re.compile(r"\bexec_command\s*\(")
+
+
+def _custom_tool_call_commands(raw: Any) -> list[str]:
+ """Extract shell commands from a Codex code-mode ``exec`` custom tool call.
+
+ Codex sends shell commands as a Responses ``custom_tool_call`` named ``exec``
+ whose ``input`` is a JavaScript snippet rather than JSON arguments::
+
+ const r = await tools.exec_command({"cmd": "sed -n '1,80p' f.py", "workdir": "…"});
+ text(r.output);
+
+ Returns every ``cmd`` passed to ``exec_command``, in order. Returns ``[]`` when
+ the input is not that shape; an argument object that is not strict JSON is
+ skipped, which leaves the output compressible exactly as before.
+ """
+ if not isinstance(raw, str) or "exec_command" not in raw:
+ return []
+ decoder = json.JSONDecoder()
+ commands: list[str] = []
+ for match in _EXEC_COMMAND_CALL_RE.finditer(raw):
+ start = raw.find("{", match.end())
+ if start < 0 or raw[match.end() : start].strip():
+ continue
+ try:
+ args, _end = decoder.raw_decode(raw, start)
+ except ValueError:
+ continue
+ command = _tool_call_command_text(args)
+ if command:
+ commands.append(command)
+ return commands
+
+
def _fenced_shell_command(content: Any) -> str:
"""Extract the shell command from a TEXT-BASED agent's fenced code block.
diff --git a/tests/test_openai_responses_read_protection.py b/tests/test_openai_responses_read_protection.py
index 36ed3691d..39ce2dd15 100644
--- a/tests/test_openai_responses_read_protection.py
+++ b/tests/test_openai_responses_read_protection.py
@@ -529,3 +529,109 @@ def test_responses_read_scan_tolerates_non_dict_and_missing_call_id(monkeypatch)
assert modified is True
assert new_payload["input"][0] == "a bare string item"
assert new_payload["input"][3]["output"] == "kept words"
+
+
+def _codex_exec_call(call_id: str, *commands: str) -> dict:
+ """Codex code-mode `exec` custom tool call, as Codex 0.15x sends it."""
+ import json as _json
+
+ script = "".join(
+ "const r{i} = await tools.exec_command({args});\ntext(r{i}.output);\n".format(
+ i=i,
+ args=_json.dumps({"cmd": cmd, "workdir": "/repo", "yield_time_ms": 10000}),
+ )
+ for i, cmd in enumerate(commands)
+ )
+ return {"type": "custom_tool_call", "call_id": call_id, "name": "exec", "input": script}
+
+
+def _codex_exec_output(call_id: str, text: str) -> dict:
+ return {
+ "type": "custom_tool_call_output",
+ "call_id": call_id,
+ "output": [
+ {"type": "input_text", "text": "Script completed\nWall time 0.1 seconds\nOutput:\n"},
+ {"type": "input_text", "text": text},
+ ],
+ }
+
+
+def test_custom_tool_call_commands_parses_codex_exec_input():
+ from headroom.transforms.content_router import _custom_tool_call_commands
+
+ call = _codex_exec_call("c", "sed -n '1,80p' tenacity/wait.py", "rg -n 'def f' src")
+ assert _custom_tool_call_commands(call["input"]) == [
+ "sed -n '1,80p' tenacity/wait.py",
+ "rg -n 'def f' src",
+ ]
+ # Braces and quotes inside the command must not break the JSON scan.
+ awk = _codex_exec_call("c", "awk 'NR >= 3 {printf \"%4d: %s\\n\", NR, $0}' f.py")
+ assert _custom_tool_call_commands(awk["input"]) == [
+ "awk 'NR >= 3 {printf \"%4d: %s\\n\", NR, $0}' f.py"
+ ]
+
+
+def test_custom_tool_call_commands_ignores_other_shapes():
+ from headroom.transforms.content_router import _custom_tool_call_commands
+
+ assert _custom_tool_call_commands(None) == []
+ assert _custom_tool_call_commands({"cmd": "cat f"}) == []
+ assert _custom_tool_call_commands("*** Begin Patch\n*** Update File: f.py\n") == []
+ assert _custom_tool_call_commands("tools.exec_command(notJson)") == []
+ assert _custom_tool_call_commands("tools.exec_command({cmd: 'cat f'})") == []
+
+
+def test_responses_codex_exec_read_stays_verbatim(monkeypatch):
+ """Codex's `exec` custom tool: a sed/nl file read must reach the model verbatim."""
+ monkeypatch.setenv("HEADROOM_PROTECT_READS", "1")
+ handler = _handler_with_router(_lossy_router())
+ output = _codex_exec_output("call_exec", _NL_OUTPUT)
+ payload = {
+ "model": "gpt-5",
+ "input": [
+ _codex_exec_call("call_exec", "nl -ba tenacity/wait.py | sed -n '20,115p'"),
+ output,
+ ],
+ }
+
+ new_payload, _modified, _s, _t, _u, _c, _a = _run(handler, payload)
+
+ assert new_payload["input"][1] == output
+
+
+def test_responses_codex_exec_script_with_a_read_among_commands_stays_verbatim(monkeypatch):
+ """One script, one output: protect it when any command in the script is a read."""
+ monkeypatch.setenv("HEADROOM_PROTECT_READS", "1")
+ handler = _handler_with_router(_lossy_router())
+ output = _codex_exec_output("call_multi", _NL_OUTPUT)
+ payload = {
+ "model": "gpt-5",
+ "input": [
+ _codex_exec_call(
+ "call_multi", "git status --short", "sed -n '1,130p' tenacity/wait.py"
+ ),
+ output,
+ ],
+ }
+
+ new_payload, _modified, _s, _t, _u, _c, _a = _run(handler, payload)
+
+ assert new_payload["input"][1] == output
+
+
+def test_responses_codex_exec_test_output_still_compresses(monkeypatch):
+ """Control: a Codex `exec` running tests is not a read and stays compressible."""
+ monkeypatch.setenv("HEADROOM_PROTECT_READS", "1")
+ handler = _handler_with_router(_lossy_router())
+ payload = {
+ "model": "gpt-5",
+ "input": [
+ _codex_exec_call("call_pytest", "python3 -m pytest -q tests/test_wait.py"),
+ _codex_exec_output("call_pytest", _NL_OUTPUT),
+ ],
+ }
+
+ new_payload, modified, _s, _t, _u, _c, _a = _run(handler, payload)
+
+ assert modified is True
+ assert new_payload["input"][1] != _codex_exec_output("call_pytest", _NL_OUTPUT)