The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): bound file/process reads in @ context reference expansion
beardthelion0accda1f763c
diff --git a/agent/context_references.py b/agent/context_references.pyindex 7c7f3160629..2e04134d559 100644--- a/agent/context_references.py+++ b/agent/context_references.py@@ -9,12 +9,13 @@ import mimetypesimport osimport reimport subprocess+import threadingfrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Awaitable, Callable-from agent.model_metadata import estimate_tokens_rough+from agent.model_metadata import CHARS_PER_TOKEN, estimate_tokens_roughfrom hermes_cli._subprocess_compat import IS_WINDOWS, harden_git_argv, noninteractive_git_env, windows_hide_flagsfrom hermes_cli.sizefmt import format_bytes@@ -95,6 +96,14 @@ _SENSITIVE_HOME_FILES = tuple(Path(p) for p in (".profile", ".bash_profile", ".zprofile", ".netrc", ".pgpass", ".npmrc", ".pypirc",))_TEXT_EXTENSIONS = (".py", ".md", ".txt", ".json", ".yaml", ".yml", ".toml", ".js", ".ts")+# Bound the work one message can force: each expanded ref reads at most a bounded prefix /+# window, and at most this many refs are expanded per message.+_MAX_EXPANDED_REFERENCES = 16+# Folder-listing line counts stop paying I/O past this size; bigger files report bytes only.+_LINE_COUNT_MAX_BYTES = 4 * 1024 * 1024+# Per-command stdout/stderr ceiling for the ``git``/``rg`` helpers; past it the child is+# killed and the nonzero returncode routes the caller to its fallback path.+_MAX_QUIET_OUTPUT_BYTES = 4 * 1024 * 1024_FENCE_LANGUAGES = {".py": "python", ".js": "javascript", ".ts": "typescript", ".tsx": "tsx", ".jsx": "jsx",".json": "json", ".md": "markdown", ".sh": "bash", ".yml": "yaml", ".yaml": "yaml", ".toml": "toml",@@ -203,10 +212,14 @@ async def preprocess_context_references_async(tasks = (_expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path,max_inline_tokens=hard_limit)- for ref in refs+ for ref in refs[:_MAX_EXPANDED_REFERENCES])expanded = await asyncio.gather(*tasks)warnings = [warning for warning, _ in expanded if warning]+ warnings.extend(+ f"{ref.raw}: not expanded (maximum {_MAX_EXPANDED_REFERENCES} @-references per message)"+ for ref in refs[_MAX_EXPANDED_REFERENCES:]+ )blocks = [block for _, block in expanded if block]injected_tokens = sum(estimate_tokens_rough(block) for block in blocks)result = ContextReferenceResult(@@ -286,9 +299,48 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Pa# A bare "not supported" warning was a dead end (the model gave up); the file IS# on disk where the agent's tools run, so hand it an actionable block instead.return None, _binary_reference_block(ref, path)- text = path.read_text(encoding="utf-8")if ref.line_start is not None:- text = "\n".join(text.splitlines()[max(ref.line_start - 1, 0):ref.line_end or ref.line_start])+ # A ranged ref wants a slice, not the file: stream to the window so a GB-scale+ # file serves :1-5 without being materialized. Lines are read in bounded pieces+ # (budget + 1) so even a single-line giant (minified JSON, one-line logs) cannot+ # force an unbounded string into memory; skipped lines are discarded, not kept.+ char_budget = None if max_inline_tokens is None else max_inline_tokens * CHARS_PER_TOKEN+ line_cap = None if char_budget is None else char_budget + 1++ def _next_line(fh, collect: bool) -> str | None:+ pieces, seen = [], False+ while True:+ piece = fh.readline() if line_cap is None else fh.readline(line_cap)+ if not piece:+ break+ seen = True+ if collect:+ pieces.append(piece)+ if piece.endswith("\n"):+ break+ return ("".join(pieces) if collect else "") if seen else None++ parts, total_chars = [], 0+ with path.open(encoding="utf-8") as fh:+ for _ in range(max(ref.line_start - 1, 0)):+ if _next_line(fh, collect=False) is None:+ break+ for _ in range((ref.line_end or ref.line_start) - ref.line_start + 1):+ line = _next_line(fh, collect=True)+ if line is None:+ break+ total_chars += len(line)+ if char_budget is not None and total_chars > char_budget:+ return None, _oversized_text_reference_block(ref, path, total_chars // CHARS_PER_TOKEN)+ parts.append(line)+ text = "".join(parts)+ else:+ # estimate_tokens_rough >= bytes/CHARS_PER_TOKEN for every encoding mix, so a+ # file past that byte ceiling is certainly oversized; refuse without reading it.+ size = path.stat().st_size+ if max_inline_tokens is not None and size > max_inline_tokens * CHARS_PER_TOKEN:+ return None, _oversized_text_reference_block(ref, path, size // CHARS_PER_TOKEN)+ text = path.read_text(encoding="utf-8")lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "")text_tokens = estimate_tokens_rough(text)# Check BEFORE building the fenced block: an oversized file is not going to be@@ -303,10 +355,48 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Padef _run_quiet(cmd: list[str], cwd: Path, timeout: int, env: dict | None = None) -> subprocess.CompletedProcess:- """subprocess.run with captured text output, no stdin, and no console flash on Windows."""+ """Captured text output with bounded pipes, no stdin, and no console flash on Windows.++ ``capture_output=True`` buffers the child's entire stdout — an unbounded ``git diff``+ or ``rg --files`` would materialize a hostile-size stream in memory. Each pipe is+ drained up to ``_MAX_QUIET_OUTPUT_BYTES``; past it the child is killed and its+ nonzero returncode routes callers to their existing fallback paths.+ """popen_kwargs: dict = {"creationflags": windows_hide_flags()} if IS_WINDOWS else {}- return subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, encoding='utf-8', errors='replace',- timeout=timeout, stdin=subprocess.DEVNULL, **popen_kwargs, **({} if env is None else {"env": env}))+ proc = subprocess.Popen(+ cmd, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,+ **popen_kwargs, **({} if env is None else {"env": env}))++ def _drain(stream, sink: list[bytes]) -> None:+ total = 0+ while True:+ chunk = stream.read1(1 << 16)+ if not chunk:+ return+ total += len(chunk)+ if total <= _MAX_QUIET_OUTPUT_BYTES:+ sink.append(chunk)+ else:+ proc.kill()+ return++ sinks: list[list[bytes]] = [[], []]+ threads = [+ threading.Thread(target=_drain, args=(stream, sink), daemon=True)+ for stream, sink in zip((proc.stdout, proc.stderr), sinks)+ ]+ for thread in threads:+ thread.start()+ try:+ proc.wait(timeout=timeout)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.wait()+ raise subprocess.TimeoutExpired(cmd, timeout)+ for thread in threads:+ thread.join()+ stdout, stderr = (b"".join(sink).decode("utf-8", "replace") for sink in sinks)+ return subprocess.CompletedProcess(cmd, proc.returncode, stdout, stderr)def _expand_git_reference(ref: ContextReference, cwd: Path, args: list[str], label: str) -> Expansion:@@ -400,9 +490,10 @@ def _parse_file_reference_value(value: str) -> tuple[str, int | None, int | Nonedef _is_binary_file(path: Path) -> bool:mime = mimetypes.guess_type(path.name)[0]- return bool(mime and not mime.startswith("text/") and not path.name.endswith(_TEXT_EXTENSIONS)) or (- b"\x00" in path.read_bytes()[:4096]- )+ if mime and not mime.startswith("text/") and not path.name.endswith(_TEXT_EXTENSIONS):+ return True+ with path.open("rb") as fh: # sniff only; read_bytes() materialized the whole file+ return b"\x00" in fh.read(4096)def _build_folder_listing(path: Path, cwd: Path, limit: int = 200) -> str:@@ -495,9 +586,19 @@ def _oversized_text_reference_block(ref: ContextReference, path: Path, text_tokedef _file_metadata(path: Path) -> str:- if not _is_binary_file(path):- try:- return f"{path.read_text(encoding='utf-8').count(chr(10)) + 1} lines"- except Exception:- pass- return f"{path.stat().st_size} bytes"+ try:+ size = path.stat().st_size+ except OSError:+ return "unknown size"+ # A listing line is a summary, not content: past the cap, byte size conveys the+ # same "how big is this" without a full scan per entry.+ if _is_binary_file(path) or size > _LINE_COUNT_MAX_BYTES:+ return f"{size} bytes"+ try:+ with path.open("rb") as fh:+ # UTF-8 never embeds 0x0A inside a multibyte sequence, so counting bytes+ # matches a decoded newline count while streaming instead of read_text.+ lines = sum(chunk.count(b"\n") for chunk in iter(lambda: fh.read(1 << 20), b""))+ return f"{lines + 1} lines"+ except Exception:+ return f"{size} bytes"diff --git a/tests/agent/test_context_references.py b/tests/agent/test_context_references.pyindex 7c005eaf26a..1db00cd73a9 100644--- a/tests/agent/test_context_references.py+++ b/tests/agent/test_context_references.py@@ -165,6 +165,135 @@ def test_file_line_range_is_applied_before_oversized_fallback(tmp_path: Path):assert "too large to inline safely" not in result.message+def test_oversized_file_refused_without_full_read(tmp_path: Path, monkeypatch):+ from agent import context_references+ from agent.context_references import preprocess_context_references++ payload = tmp_path / "huge.txt"+ payload.write_text("x" * 100_000, encoding="utf-8")++ def _boom(*args, **kwargs):+ raise AssertionError("oversized file was read in full")++ monkeypatch.setattr(Path, "read_text", _boom)+ result = preprocess_context_references(+ f"Inspect @file:{payload.name}", cwd=tmp_path, context_length=1_000,+ )+ assert "too large to inline safely" in result.message+ assert str(payload) in result.message+++def test_line_range_ref_streams_only_the_window(tmp_path: Path, monkeypatch):+ from agent.context_references import preprocess_context_references++ def _boom(*args, **kwargs):+ raise AssertionError("ranged ref read the whole file")++ monkeypatch.setattr(Path, "read_text", _boom)+ small = tmp_path / "small.txt"+ small.write_text("first\nsecond\nthird\nfourth\n", encoding="utf-8")+ result = preprocess_context_references(+ f"Inspect @file:{small.name}:2-3", cwd=tmp_path, context_length=1_000,+ )+ assert "second\nthird" in result.message+ assert "first" not in result.message+ assert "fourth" not in result.message+++def test_binary_sniff_reads_prefix_only(tmp_path: Path):+ from agent.context_references import _is_binary_file++ # .txt keeps the mime guess on the text side so the byte sniff runs.+ payload = tmp_path / "data.txt"+ payload.write_bytes(b"\x00" * 10 + b"x" * 1_000_000)+ read_calls = []+ orig_open = Path.open++ def _counting_open(self, *args, **kwargs):+ fh = orig_open(self, *args, **kwargs)+ if "b" in (args[0] if args else kwargs.get("mode", "r")):+ orig_read = fh.read+ def _read(*a, **k):+ data = orig_read(*a, **k)+ read_calls.append(len(data))+ return data+ fh.read = _read+ return fh++ with patch.object(Path, "open", _counting_open):+ assert _is_binary_file(payload)+ assert read_calls and max(read_calls) <= 4096+++def test_folder_listing_caps_line_count_io(tmp_path: Path, monkeypatch):+ from agent import context_references+ from agent.context_references import preprocess_context_references++ assets = tmp_path / "assets"+ assets.mkdir()+ big = assets / "big.txt"+ big.write_bytes(b"line\n" * (context_references._LINE_COUNT_MAX_BYTES // 5 + 2))+ (assets / "small.txt").write_text("a\nb\n", encoding="utf-8")++ result = preprocess_context_references("list @folder:assets", cwd=tmp_path, context_length=10_000_000)+ assert "big.txt" in result.message and "bytes" in result.message+ assert "3 lines" in result.message # small file still reports a line count+++def test_line_range_bounds_reads_on_single_line_file(tmp_path: Path, monkeypatch):+ from agent.context_references import preprocess_context_references++ payload = tmp_path / "oneline.txt"+ payload.write_text("x" * 100_000, encoding="utf-8") # one giant line, no newline++ read_sizes = []+ orig_open = Path.open++ def _counting_open(self, *args, **kwargs):+ fh = orig_open(self, *args, **kwargs)+ mode = args[0] if args else kwargs.get("mode", "r")+ if "b" not in mode:+ orig_readline = fh.readline+ fh.readline = lambda *a, **k: (read_sizes.append(a[0] if a else -1), orig_readline(*a, **k))[1]+ return fh++ monkeypatch.setattr(Path, "open", _counting_open)+ result = preprocess_context_references(+ f"Inspect @file:{payload.name}:1-1", cwd=tmp_path, context_length=1_000,+ )+ assert "too large to inline safely" in result.message+ # hard_limit = 500 tokens -> char budget 2000 -> each readline bounded at 2001+ assert read_sizes and max(read_sizes) <= 2001+++def test_run_quiet_caps_child_output(tmp_path: Path):+ import sys+ from agent.context_references import _MAX_QUIET_OUTPUT_BYTES, _run_quiet++ huge = _run_quiet(+ [sys.executable, "-c", f"import sys; sys.stdout.write('x' * {_MAX_QUIET_OUTPUT_BYTES + 1000})"],+ tmp_path, 30,+ )+ assert huge.returncode != 0+ assert len(huge.stdout) <= _MAX_QUIET_OUTPUT_BYTES++ ok = _run_quiet([sys.executable, "-c", "print('hello')"], tmp_path, 30)+ assert ok.returncode == 0 and "hello" in ok.stdout+++def test_reference_count_is_capped(tmp_path: Path):+ from agent.context_references import _MAX_EXPANDED_REFERENCES, preprocess_context_references++ for i in range(_MAX_EXPANDED_REFERENCES + 4):+ (tmp_path / f"f{i}.txt").write_text("data", encoding="utf-8")+ result = preprocess_context_references(+ " ".join(f"@file:f{i}.txt" for i in range(_MAX_EXPANDED_REFERENCES + 4)),+ cwd=tmp_path, context_length=10_000_000,+ )+ skipped = [w for w in result.warnings if "not expanded" in w]+ assert len(skipped) == 4++def test_multiple_individually_safe_files_still_obey_aggregate_limit(tmp_path: Path):from agent.context_references import preprocess_context_references