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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(learn): drop the echoed prompt from a failed cli's error (#3928)
gglucassf00d42561402
diff --git a/headroom/learn/analyzer.py b/headroom/learn/analyzer.pyindex 799aec7d7..dc5075383 100644--- a/headroom/learn/analyzer.py+++ b/headroom/learn/analyzer.py@@ -642,7 +642,11 @@ def _output_snippet(text: str, limit: int = _MAX_SNIPPET_LEN) -> str:def _failure_detail(- stderr: str | None, stdout: str | None, *, result_text: str | None = None+ stderr: str | None,+ stdout: str | None,+ *,+ result_text: str | None = None,+ prompt: str | None = None,) -> str:"""Build the operator-facing reason for a non-zero CLI exit.@@ -656,17 +660,39 @@ def _failure_detail(than headed because CLI backends emit the error last (a streaming backend'swhole event log precedes it).+ A CLI that echoes its stdin prompt to stderr (``codex exec`` prints the whole+ prompt ahead of its own error) would otherwise fill the head-of-stderr cut+ with our system prompt and never reach the reason. The echo is replaced with+ a marker and only the end of what follows it is kept, which also keeps the+ session digest out of the message.+Args:stderr: Captured stderr, if any.stdout: Captured stdout, if any.result_text: Pre-extracted reason (claude-cli's final ``result`` field),used in place of the raw stdout tail when available.+ prompt: The prompt sent on stdin, dropped from stderr when echoed there.Returns:A non-empty snippet, or ``"(no output captured)"`` when both streams wereempty, so the message is never a dangling colon."""parts: list[str] = []+ # Text-mode pipes read the echo back with universal newlines.+ echo = prompt.replace("\r\n", "\n").replace("\r", "\n").strip() if prompt else ""+ if stderr and echo and echo in stderr:+ head, _, after = stderr.strip().partition(echo)+ marker = "[prompt omitted]\n"+ after = after.strip()+ # At least half the cap goes to what follows the echo, so a long+ # banner ahead of it cannot push the CLI's verdict out.+ room = max(_MAX_SNIPPET_LEN - len(head) - len(marker), _MAX_SNIPPET_LEN // 2)+ head = head[: _MAX_SNIPPET_LEN - room - len(marker)] + marker+ if len(after) > room:+ # Keep whole lines where possible: the CLI's verdict is the last one.+ cut = after[len(after) - room :]+ after = cut.partition("\n")[2] or cut+ stderr = head + afterif stderr and stderr.strip():parts.append(stderr.strip()[:_MAX_SNIPPET_LEN])tail = result_text if result_text and result_text.strip() else stdout@@ -754,7 +780,7 @@ def _call_cli_llm() from Noneif result.returncode != 0:- detail = _failure_detail(result.stderr, result.stdout)+ detail = _failure_detail(result.stderr, result.stdout, prompt=prompt)raise RuntimeError(f"`{' '.join(cmd)}` failed (exit {result.returncode}):\n{detail}")# Log stderr warnings even on success (auth refreshes, deprecation notices).@@ -924,7 +950,7 @@ def _call_claude_cli_streaming(# the human-readable reason ("API Error: ...", "Not logged in", usage# limits).detail = _failure_detail(- "".join(stderr_lines), "".join(stdout_lines), result_text=final_result+ "".join(stderr_lines), "".join(stdout_lines), result_text=final_result, prompt=prompt)raise RuntimeError(f"`{' '.join(cmd)}` failed (exit {proc.returncode}):\n{detail}")diff --git a/tests/test_learn/test_analyzer.py b/tests/test_learn/test_analyzer.pyindex 51a203c85..7c8a4e11e 100644--- a/tests/test_learn/test_analyzer.py+++ b/tests/test_learn/test_analyzer.py@@ -1064,6 +1064,50 @@ class TestCallCliLlm:_call_cli_llm("test digest", "codex-cli")assert long_stderr not in str(exc_info.value)+ @patch("headroom.learn.analyzer.subprocess.run")+ def test_codex_failure_drops_prompt_echo_and_keeps_reason(self, mock_run: MagicMock):+ # `codex exec` echoes the whole stdin prompt to stderr ahead of its own+ # error, so a head-of-stderr excerpt is the banner plus our system prompt+ # and never the reason. Shape captured from codex-cli 0.156.1.+ def _codex(cmd, *, input, **kwargs):+ stderr = (+ "Reading prompt from stdin...\nOpenAI Codex v0.156.1\n--------\n"+ "model: gpt-5\n--------\nuser\n" + input + "\n\n"+ )+ stderr += "ERROR: Reconnecting... 1/5\n" * 100+ stderr += "ERROR: unexpected status 401 Unauthorized: Missing bearer\n"+ return MagicMock(returncode=1, stdout="", stderr=stderr)++ mock_run.side_effect = _codex+ with pytest.raises(RuntimeError) as exc_info:+ _call_cli_llm("SECRET-SESSION-DIGEST", "codex-cli")+ message = str(exc_info.value)+ assert message.endswith("ERROR: unexpected status 401 Unauthorized: Missing bearer")+ assert "[prompt omitted]" in message+ assert "SECRET-SESSION-DIGEST" not in message+ assert "OpenAI Codex v0.156.1" in message+ # Whole lines only, still inside the snippet cap.+ assert "\nERROR: Reconnecting... 1/5\n" in message+ assert len(message) < 2200++ @patch("headroom.learn.analyzer.subprocess.run")+ def test_codex_failure_keeps_reason_behind_a_long_banner(self, mock_run: MagicMock):+ # Diagnostics ahead of the echo longer than the whole snippet cap must+ # not push the CLI's final error out of the message.+ def _codex(cmd, *, input, **kwargs):+ stderr = "WARN startup diagnostic line\n" * 100 + input + "\n"+ stderr += "ERROR: unknown model gpt-x\n"+ return MagicMock(returncode=1, stdout="", stderr=stderr)++ mock_run.side_effect = _codex+ with pytest.raises(RuntimeError) as exc_info:+ _call_cli_llm("SECRET-SESSION-DIGEST", "codex-cli")+ message = str(exc_info.value)+ assert message.endswith("[prompt omitted]\nERROR: unknown model gpt-x")+ assert message.startswith("`codex exec")+ assert "SECRET-SESSION-DIGEST" not in message+ assert len(message) < 2200+def test_unknown_cli_model_raises(self):with pytest.raises(ValueError, match="Unknown CLI model"):_call_cli_llm("test digest", "unknown-cli")