Skip to content

The agent that grows with you

feat(terminal): recoverable truncation — spill full output + report pre-truncation size

Teknium80631c4aeaa3
diff --git a/tests/tools/test_terminal_truncation_spill.py b/tests/tools/test_terminal_truncation_spill.py
new file mode 100644
index 00000000000..f14d0da5333
--- /dev/null
+++ b/tests/tools/test_terminal_truncation_spill.py
@@ -0,0 +1,67 @@
+"""Tests for terminal truncation spill + metadata (deferred retrieval)."""
+
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from tools.terminal_tool import terminal_tool
+
+
+def small_cap(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ import tools.tool_output_limits as lim
+ monkeypatch.setattr(lim, "_cached_limits", {
+ "max_bytes": 2000, "max_lines": 2000, "max_line_length": 2000,
+ })
+ return tmp_path
+
+
+class TestTruncationSpill:
+ def test_truncated_output_has_metadata_and_spill(self, small_cap):
+ r = json.loads(terminal_tool(
+ "python3 -c \"print('marker_head'); [print(f'row_{i}', 'x'*80) for i in range(200)]; print('marker_tail')\"",
+ task_id="t-spill-1"))
+ assert r["exit_code"] == 0
+ assert "OUTPUT TRUNCATED" in r["output"]
+ assert r["output_total_chars"] > 2000
+ p = Path(r["full_output_path"])
+ assert p.exists()
+ full = p.read_text()
+ assert "marker_head" in full and "marker_tail" in full
+ # The spill contains rows that were cut from the visible window.
+ assert "row_100 " in full
+ assert "read_file" in r["truncation_note"]
+
+ def test_small_output_has_no_metadata(self, small_cap):
+ r = json.loads(terminal_tool("echo tiny", task_id="t-spill-2"))
+ assert r["exit_code"] == 0
+ assert "full_output_path" not in r
+ assert "output_total_chars" not in r
+
+ def test_spill_is_redacted(self, small_cap):
+ r = json.loads(terminal_tool(
+ "python3 -c \"print('sk-proj-' + 'a1B2c3D4e5F6g7H8i9J0' * 3); [print('pad', 'y'*90) for i in range(200)]\"",
+ task_id="t-spill-3"))
+ p = Path(r["full_output_path"])
+ full = p.read_text()
+ assert "a1B2c3D4e5F6g7H8i9J0a1B2c3D4e5F6g7H8i9J0" not in full
+
+ def test_old_spills_cleaned(self, small_cap, tmp_path):
+ spill_dir = tmp_path / ".hermes" / "cache" / "terminal-output"
+ spill_dir.mkdir(parents=True, exist_ok=True)
+ stale = spill_dir / "out-1-2-dead.log"
+ stale.write_text("old")
+ os.utime(stale, (1, 1))
+ json.loads(terminal_tool(
+ "python3 -c \"[print('z'*90) for i in range(200)]\"", task_id="t-spill-4"))
+ assert not stale.exists()
+
+ def test_failed_command_still_gets_spill(self, small_cap):
+ r = json.loads(terminal_tool(
+ "python3 -c \"[print('e'*90) for i in range(200)]; import sys; sys.exit(3)\"",
+ task_id="t-spill-5"))
+ assert r["exit_code"] == 3
+ assert Path(r["full_output_path"]).exists()
diff --git a/tools/environments/base.py b/tools/environments/base.py
index 4c5029bcd13..a4b106b0041 100644
--- a/tools/environments/base.py
+++ b/tools/environments/base.py
@@ -53,8 +53,19 @@ _UNBOUNDED_CAPTURE_CHARS = 2**63 - 1
class _BoundedOutputCollector:
- """Retain a bounded 40/60 head-tail window of streamed text."""
- def __init__(self, max_chars: int):
+ """Retain a bounded 40/60 head-tail window of streamed text.
+
+ When ``spill_path`` is set, the collector also tees the FULL stream to
+ that file once eviction begins (up to ``_SPILL_CAP_CHARS``), so a
+ truncated foreground result is recoverable without re-running the
+ command. Memory stays bounded either way — the spill is disk-only.
+ """
+
+ # Hard ceiling on spill file size. Beyond this the file stops growing
+ # (marker appended); protects disk from pathological runaway output.
+ _SPILL_CAP_CHARS = 5_000_000
+
+ def __init__(self, max_chars: int, spill_path: "Path | None" = None):
self.max_chars = max(1, int(max_chars))
self._head_limit = int(self.max_chars * 0.4)
self._tail_limit = self.max_chars - self._head_limit
@@ -64,6 +75,47 @@ class _BoundedOutputCollector:
self._tail_chars = 0
self._total_chars = 0
self._lock = threading.Lock()
+ self._spill_path = spill_path
+ self._spill_fh: IO[str] | None = None
+ self._spill_chars = 0
+ self._spill_capped = False
+
+ def _maybe_spill(self, text: str) -> None:
+ """Tee ``text`` to the spill file (opened lazily on first overflow)."""
+ if self._spill_path is None or self._spill_capped:
+ return
+ try:
+ if self._spill_fh is None:
+ self._spill_path.parent.mkdir(parents=True, exist_ok=True)
+ self._spill_fh = open(self._spill_path, "w", encoding="utf-8", errors="replace")
+ # Backfill everything retained so far so the file holds the
+ # stream from byte 0, not just from the overflow point.
+ backlog = "".join(self._head) + "".join(self._tail)
+ self._spill_fh.write(backlog)
+ self._spill_chars = len(backlog)
+ budget = self._SPILL_CAP_CHARS - self._spill_chars
+ if budget <= 0 or len(text) > budget:
+ self._spill_fh.write(text[:max(0, budget)])
+ self._spill_fh.write("\n... [spill capped at 5,000,000 chars] ...\n")
+ self._spill_capped = True
+ else:
+ self._spill_fh.write(text)
+ self._spill_chars += len(text)
+ except OSError:
+ # Disk trouble must never break command execution.
+ self._spill_capped = True
+
+ def close_spill(self) -> "str | None":
+ """Close the spill file and return its path if it was used."""
+ with self._lock:
+ if self._spill_fh is None:
+ return None
+ try:
+ self._spill_fh.close()
+ except OSError:
+ pass
+ self._spill_fh = None
+ return str(self._spill_path)
@property
def buffered_chars(self) -> int:
@@ -80,6 +132,13 @@ class _BoundedOutputCollector:
return
with self._lock:
text_len = len(text)
+ # Spill tee: activates at the first overflow (backfilling what's
+ # retained so far), then mirrors every subsequent chunk.
+ if self._spill_path is not None and (
+ self._spill_fh is not None
+ or self._total_chars + text_len > self.max_chars
+ ):
+ self._maybe_spill(text)
self._total_chars += text_len
start = 0
@@ -860,7 +919,26 @@ class BaseEnvironment(ABC):
# segment, no eviction) so behavior matches the historical
# accumulate-everything semantics.
capture_limit = _UNBOUNDED_CAPTURE_CHARS
- output = _BoundedOutputCollector(capture_limit)
+ spill_path = None
+ if bounded_capture:
+ # Foreground terminal path: tee overflow to a spill file so a
+ # truncated result is recoverable without re-running (the file
+ # only gets created if output actually exceeds the cap).
+ try:
+ spill_dir = get_hermes_home() / "cache" / "terminal-output"
+ spill_path = spill_dir / f"out-{int(time.time())}-{os.getpid()}-{id(proc) & 0xffff:x}.log"
+ # Opportunistic cleanup of spills older than 7 days.
+ if spill_dir.is_dir():
+ cutoff = time.time() - 7 * 86400
+ for old in spill_dir.glob("out-*.log"):
+ try:
+ if old.stat().st_mtime < cutoff:
+ old.unlink()
+ except OSError:
+ pass
+ except Exception:
+ spill_path = None
+ output = _BoundedOutputCollector(capture_limit, spill_path=spill_path)
# Non-blocking drain via select().
#
@@ -1027,10 +1105,11 @@ class BaseEnvironment(ABC):
)
self._kill_process(proc)
drain_thread.join(timeout=2)
- return {
- "output": output.render(suffix="\n[Command interrupted]"),
- "returncode": 130,
- }
+ return self._finalize_wait_result(
+ output,
+ output.render(suffix="\n[Command interrupted]"),
+ 130,
+ )
if time.monotonic() > deadline:
if _DEBUG_INTERRUPT:
logger.info(
@@ -1041,12 +1120,13 @@ class BaseEnvironment(ABC):
self._kill_process(proc)
drain_thread.join(timeout=2)
timeout_msg = f"\n[Command timed out after {timeout}s]"
- return {
- "output": output.render(suffix=timeout_msg).lstrip()
+ return self._finalize_wait_result(
+ output,
+ output.render(suffix=timeout_msg).lstrip()
if output.total_chars == 0
else output.render(suffix=timeout_msg),
- "returncode": 124,
- }
+ 124,
+ )
# Periodic activity touch so the gateway knows we're alive
touch_activity_if_due(_activity_state, "terminal command running")
@@ -1120,7 +1200,18 @@ class BaseEnvironment(ABC):
proc.returncode,
)
- return {"output": output.render(), "returncode": proc.returncode}
+ return self._finalize_wait_result(output, output.render(), proc.returncode)
+
+ @staticmethod
+ def _finalize_wait_result(collector: "_BoundedOutputCollector",
+ rendered: str, returncode: int | None) -> dict:
+ """Assemble a wait result, attaching spill metadata when overflow occurred."""
+ result = {"output": rendered, "returncode": returncode}
+ spill = collector.close_spill()
+ if spill:
+ result["output_total_chars"] = collector.total_chars
+ result["full_output_path"] = spill
+ return result
def _kill_process(self, proc: ProcessHandle):
"""Terminate a process. Subclasses may override for process-group kill."""
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index c585c71d5e2..8b89393b678 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -2979,6 +2979,10 @@ def terminal_tool(
# Extract output
output = result.get("output", "")
returncode = result.get("returncode", 0)
+ # Spill metadata from the bounded collector: present only when
+ # output overflowed the capture window (see _wait_for_process).
+ spill_total_chars = result.get("output_total_chars")
+ spill_file_path = result.get("full_output_path")
# Add helpful message for sudo failures in messaging context
output = _handle_sudo_failure(output, env_type)
@@ -3082,6 +3086,34 @@ def terminal_tool(
result_dict["cwd"] = str(post_cwd)
except Exception:
pass
+ # Truncation metadata (codex/opencode/goose pattern): report the
+ # pre-truncation size and a spill-file handle so the model can
+ # retrieve the omitted middle with read_file/search_files instead
+ # of re-running the command. The spill was written raw by the
+ # collector; redact it here with the same pass as the visible
+ # output so no secret persists unmasked on disk.
+ if spill_file_path:
+ try:
+ _sp = Path(spill_file_path)
+ raw_spill = _sp.read_text(encoding="utf-8", errors="replace")
+ _sp.write_text(
+ redact_terminal_output(strip_ansi(raw_spill), command),
+ encoding="utf-8", errors="replace",
+ )
+ result_dict["output_total_chars"] = spill_total_chars
+ result_dict["full_output_path"] = spill_file_path
+ result_dict["truncation_note"] = (
+ "Output exceeded the capture window (head+tail shown). "
+ f"Full output ({spill_total_chars:,} chars) saved to "
+ f"{spill_file_path} — search it with search_files or page it "
+ "with read_file instead of re-running the command."
+ )
+ except Exception:
+ logger.debug("spill redaction failed; dropping spill handle", exc_info=True)
+ try:
+ Path(spill_file_path).unlink()
+ except OSError:
+ pass
try:
from agent.verification_evidence import record_terminal_result