Skip to content

The agent that grows with you

fix(context): fall back for oversized file refs

Gillecfa1a90b8c6f
diff --git a/agent/context_references.py b/agent/context_references.py
index b20da47720a..9a8d53f34d9 100644
--- a/agent/context_references.py
+++ b/agent/context_references.py
@@ -195,7 +195,13 @@ async def preprocess_context_references_async(
# Expand concurrently (each ref is independent; several @url: refs would otherwise
# serialize web_extract round-trips). gather preserves order, so warnings/blocks
# are assembled in ref order; the token-budget check runs once afterwards.
- tasks = (_expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path) for ref in refs)
+ hard_limit = max(1, int(context_length * 0.50))
+ soft_limit = max(1, int(context_length * 0.25))
+ tasks = (
+ _expand_reference(ref, cwd_path, url_fetcher=url_fetcher, allowed_root=allowed_root_path,
+ max_inline_tokens=hard_limit)
+ for ref in refs
+ )
expanded = await asyncio.gather(*tasks)
warnings = [warning for warning, _ in expanded if warning]
blocks = [block for _, block in expanded if block]
@@ -204,8 +210,6 @@ async def preprocess_context_references_async(
message=message, original_message=message, references=refs, warnings=warnings, injected_tokens=injected_tokens
)
- hard_limit = max(1, int(context_length * 0.50))
- soft_limit = max(1, int(context_length * 0.25))
if injected_tokens > hard_limit:
warnings.append(f"@ context injection refused: {injected_tokens} tokens exceeds the 50% hard limit ({hard_limit}).")
result.blocked = True
@@ -235,11 +239,12 @@ _GIT_REFERENCE_ARGS: dict[str, Callable[[ContextReference], list[str]]] = {
async def _expand_reference(
- ref: ContextReference, cwd: Path, *, url_fetcher: UrlFetcher = None, allowed_root: Path | None = None
+ ref: ContextReference, cwd: Path, *, url_fetcher: UrlFetcher = None, allowed_root: Path | None = None,
+ max_inline_tokens: int | None = None,
) -> Expansion:
try:
if ref.kind in ("file", "folder"):
- return _expand_path_reference(ref, cwd, allowed_root=allowed_root)
+ return _expand_path_reference(ref, cwd, allowed_root=allowed_root, max_inline_tokens=max_inline_tokens)
if ref.kind in _GIT_REFERENCE_ARGS:
git_args = _GIT_REFERENCE_ARGS[ref.kind](ref)
return _expand_git_reference(ref, cwd, git_args, "git " + " ".join(git_args))
@@ -261,7 +266,8 @@ async def _expand_reference(
return f"{ref.raw}: unsupported reference type", None
-def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Path | None = None) -> Expansion:
+def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Path | None = None,
+ max_inline_tokens: int | None = None) -> Expansion:
"""``@file:`` / ``@folder:``: resolve, allow-check, then inline text / binary stub / listing."""
is_folder = ref.kind == "folder"
path = _resolve_path(cwd, ref.target, allowed_root=allowed_root)
@@ -281,7 +287,17 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Pa
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])
lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "")
- return None, f"πŸ“„ {ref.raw} ({estimate_tokens_rough(text)} tokens)\n```{lang}\n{text}\n```"
+ text_tokens = estimate_tokens_rough(text)
+ block = f"πŸ“„ {ref.raw} ({text_tokens} tokens)\n```{lang}\n{text}\n```"
+ if max_inline_tokens is not None and estimate_tokens_rough(block) > max_inline_tokens:
+ # One oversized file used to poison the aggregate check and refuse the whole
+ # turn (#61987); the file stays readable via the agent's tools instead.
+ return (
+ f"{ref.raw}: {text_tokens} tokens is too large to inline safely; "
+ "the agent received a tool-readable path instead",
+ _oversized_text_reference_block(ref, path, text_tokens),
+ )
+ return None, block
def _run_quiet(cmd: list[str], cwd: Path, timeout: int, env: dict | None = None) -> subprocess.CompletedProcess:
@@ -450,6 +466,27 @@ def _binary_reference_block(ref: ContextReference, path: Path) -> str:
)
+def _oversized_text_reference_block(ref: ContextReference, path: Path, text_tokens: int) -> str:
+ try:
+ size = format_bytes(path.stat().st_size)
+ except OSError:
+ size = "unknown size"
+ try:
+ from tools.terminal_tool import _ensure_terminal_env_bridged
+ _ensure_terminal_env_bridged()
+ from tools.credential_files import to_agent_visible_cache_path
+ visible = to_agent_visible_cache_path(str(path))
+ except Exception:
+ visible = str(path)
+ return (
+ f"πŸ“Ž {ref.raw} (text file, {size}, approximately {text_tokens} tokens) - "
+ "too large to inline safely. "
+ f"It is available on disk at `{visible}`. "
+ "Use read_file with a narrow line range, search_files, or terminal/code tools "
+ "to inspect only the relevant parts; do not load the entire file into context."
+ )
+
+
def _file_metadata(path: Path) -> str:
if not _is_binary_file(path):
try:
diff --git a/tests/agent/test_context_references.py b/tests/agent/test_context_references.py
index b58623584b8..06af50bf7e5 100644
--- a/tests/agent/test_context_references.py
+++ b/tests/agent/test_context_references.py
@@ -121,6 +121,65 @@ def test_missing_file_becomes_warning(sample_repo: Path):
assert "not found" in result.message.lower()
+def test_oversized_text_file_falls_back_to_tool_readable_path(tmp_path: Path):
+ from agent.context_references import preprocess_context_references
+
+ payload = tmp_path / "large.txt"
+ payload.write_text("FULL-CONTENT-MARKER\n" + ("x" * 8_000), encoding="utf-8")
+
+ result = preprocess_context_references(
+ f"Inspect @file:{payload.name}",
+ cwd=tmp_path,
+ context_length=1_000,
+ )
+
+ assert result.expanded
+ assert not result.blocked
+ assert str(payload) in result.message
+ assert "too large to inline safely" in result.message
+ assert "read_file" in result.message
+ assert "FULL-CONTENT-MARKER" not in result.message
+ assert any("tool-readable path instead" in warning for warning in result.warnings)
+
+
+def test_file_line_range_is_applied_before_oversized_fallback(tmp_path: Path):
+ from agent.context_references import preprocess_context_references
+
+ payload = tmp_path / "large.txt"
+ payload.write_text(
+ "first line\nsecond line\n" + "\n".join("x" * 200 for _ in range(100)),
+ encoding="utf-8",
+ )
+
+ result = preprocess_context_references(
+ f"Inspect @file:{payload.name}:1-2",
+ cwd=tmp_path,
+ context_length=1_000,
+ )
+
+ assert result.expanded
+ assert not result.blocked
+ assert "first line\nsecond line" in result.message
+ assert "too large to inline safely" not in result.message
+
+
+def test_multiple_individually_safe_files_still_obey_aggregate_limit(tmp_path: Path):
+ from agent.context_references import preprocess_context_references
+
+ for name in ("first.txt", "second.txt"):
+ (tmp_path / name).write_text("x" * 1_200, encoding="utf-8")
+
+ result = preprocess_context_references(
+ "Inspect @file:first.txt and @file:second.txt",
+ cwd=tmp_path,
+ context_length=1_000,
+ )
+
+ assert result.blocked
+ assert not result.expanded
+ assert "context injection refused" in "\n".join(result.warnings)
+
+
def test_binary_reference_block_maps_host_attachment_to_container_path(tmp_path: Path, monkeypatch):
"""Docker backend: a staged binary attachment's host path is rendered as the
bind-mounted in-container path so the agent's tools can read it.
@@ -151,6 +210,33 @@ def test_binary_reference_block_maps_host_attachment_to_container_path(tmp_path:
assert "binary file, not inlined" in result.message
+def test_oversized_text_reference_maps_host_attachment_to_container_path(
+ tmp_path: Path, monkeypatch
+):
+ from agent.context_references import preprocess_context_references
+
+ hermes_home = tmp_path / ".hermes"
+ attachments = hermes_home / "attachments"
+ attachments.mkdir(parents=True)
+ payload = attachments / "large.txt"
+ payload.write_text("x" * 8_000, encoding="utf-8")
+
+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+
+ result = preprocess_context_references(
+ f"Read the attachment @file:{payload}",
+ cwd=tmp_path,
+ context_length=1_000,
+ )
+
+ assert result.expanded
+ assert not result.blocked
+ attached_context = result.message.split("--- Attached Context ---", 1)[1]
+ assert "/root/.hermes/attachments/large.txt" in attached_context
+ assert "too large to inline safely" in result.message
+
+
def test_binary_reference_block_keeps_host_path_on_local_backend(tmp_path: Path, monkeypatch):
"""Local backend: no translation β€” the agent's tools run on the host."""
from agent.context_references import preprocess_context_references
diff --git a/tests/gateway/test_context_ref_expansion_runtime.py b/tests/gateway/test_context_ref_expansion_runtime.py
index e0afc8c71c5..a25974e6af9 100644
--- a/tests/gateway/test_context_ref_expansion_runtime.py
+++ b/tests/gateway/test_context_ref_expansion_runtime.py
@@ -190,3 +190,28 @@ async def test_at_reference_ignores_global_context_for_runtime_route_override(mo
event=MessageEvent(text="@file:note", source=source), source=source, history=[]
)
assert captured["config_context_length"] is None
+
+
+async def test_oversized_file_reference_reaches_gateway_as_tool_readable_path(
+ tmp_path, monkeypatch
+):
+ runner = _make_runner()
+ source = _source()
+ _patch_runtime_resolution(monkeypatch)
+
+ payload = tmp_path / "large.txt"
+ payload.write_text("FULL-CONTENT-MARKER\n" + ("x" * 300_000), encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_CWD", str(tmp_path))
+
+ result = await runner._prepare_inbound_message_text(
+ event=MessageEvent(text=f"Inspect @file:{payload.name}", source=source),
+ source=source,
+ history=[],
+ )
+
+ assert result is not None
+ assert str(payload) in result
+ assert "too large to inline safely" in result
+ assert "FULL-CONTENT-MARKER" not in result
+ assert "context injection refused" not in result