From 25b9725b541abef1ddcc278944d12bbf67d58d99 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 8 Jul 2026 02:19:33 -0400 Subject: [PATCH 1/9] fix(sdk): disambiguate `read_file` line gutters --- .../deepagents_code/tui/widgets/messages.py | 25 ++++---- .../unit_tests/tui/widgets/test_messages.py | 12 ++-- .../deepagents/backends/protocol.py | 2 +- libs/deepagents/deepagents/backends/utils.py | 28 ++++----- .../deepagents/middleware/filesystem.py | 2 +- .../tests/unit_tests/test_end_to_end.py | 10 +-- .../tests/unit_tests/test_middleware.py | 61 +++++++++++-------- 7 files changed, 73 insertions(+), 67 deletions(-) diff --git a/libs/code/deepagents_code/tui/widgets/messages.py b/libs/code/deepagents_code/tui/widgets/messages.py index c707be6960e..7911d7c106e 100644 --- a/libs/code/deepagents_code/tui/widgets/messages.py +++ b/libs/code/deepagents_code/tui/widgets/messages.py @@ -1957,18 +1957,19 @@ def _format_ls_output( # noqa: PLR6301 # Grouped as method for widget cohesion @staticmethod def _compact_line_gutter(output: str) -> str: - r"""Tighten `read_file`'s cat -n line-number gutter for display. - - The tool emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified - number plus a tab — so even single-digit line numbers carry five - leading spaces and the tab pushes content to a distant tab stop. The - model needs that raw format for edits, but the TUI renders a compact - gutter instead: numbers right-justified to the widest number actually - present, then two spaces, mirroring how grep/glob results sit flush - left. Source indentation after the gutter is preserved untouched. - - Lines that don't match the cat -n shape (e.g. test fixtures or - non-numbered output) are passed through unchanged. + r"""Tighten legacy `read_file` cat-n line-number gutters for display. + + Older tool output used `f"{line_num:6d}\t{line}"` — a 6-wide + right-justified number plus a tab — so even single-digit line numbers + carried five leading spaces and the tab pushed content to a distant tab + stop. The TUI renders that legacy gutter in the newer compact shape: + numbers right-justified to the widest number actually present, then two + spaces, mirroring how grep/glob results sit flush left. Source + indentation after the gutter is preserved untouched. + + Lines that don't match the legacy cat-n shape (e.g. current compact + read output, test fixtures, or non-numbered output) are passed through + unchanged. Returns: The output with compacted gutters, or the original string if no diff --git a/libs/code/tests/unit_tests/tui/widgets/test_messages.py b/libs/code/tests/unit_tests/tui/widgets/test_messages.py index 38a322c8fab..53022b97be5 100644 --- a/libs/code/tests/unit_tests/tui/widgets/test_messages.py +++ b/libs/code/tests/unit_tests/tui/widgets/test_messages.py @@ -2760,14 +2760,14 @@ def test_format_file_output_preview_budget_hit_on_separator(self) -> None: def test_format_output_compacts_line_number_gutter(self) -> None: r"""Line-number gutters are tightened, all rows aligned to one column. - `read_file` emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified - number plus a tab — which renders far from the line numbers and (when - the first row's padding was stripped) misaligned. The TUI recomputes a - compact gutter: numbers right-justified to the widest number present, - two spaces, then the original source indentation. + Legacy `read_file` output used `f"{line_num:6d}\t{line}"` — a 6-wide + right-justified number plus a tab — which renders far from the line + numbers and (when the first row's padding was stripped) misaligned. The + TUI recomputes a compact gutter: numbers right-justified to the widest + number present, two spaces, then the original source indentation. """ msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) - # cat -n style: 6-wide right-justified number + tab + source line. + # Legacy cat-n style: 6-wide right-justified number + tab + source line. output = ' 1\t"""doc"""\n 2\t\n 3\t indented' result = msg._format_output(output, is_preview=False) diff --git a/libs/deepagents/deepagents/backends/protocol.py b/libs/deepagents/deepagents/backends/protocol.py index cd9b36abd6c..ce07bd48b88 100644 --- a/libs/deepagents/deepagents/backends/protocol.py +++ b/libs/deepagents/deepagents/backends/protocol.py @@ -419,7 +419,7 @@ def read( limit: Maximum number of lines to read. Returns: - String containing file content formatted with line numbers (`cat -n` format), + String containing file content formatted with line numbers, starting at line 1. Lines longer than 2000 characters are truncated. diff --git a/libs/deepagents/deepagents/backends/utils.py b/libs/deepagents/deepagents/backends/utils.py index 54b2cd64055..7490ce915cf 100644 --- a/libs/deepagents/deepagents/backends/utils.py +++ b/libs/deepagents/deepagents/backends/utils.py @@ -70,7 +70,6 @@ """ MAX_LINE_LENGTH = 5000 -LINE_NUMBER_WIDTH = 6 TOOL_RESULT_TOKEN_LIMIT = 20000 # Same threshold as eviction TRUNCATION_GUIDANCE = "... [results truncated, try being more specific with your parameters]" @@ -203,10 +202,11 @@ def format_content_with_line_numbers( content: str | list[str], start_line: int = 1, ) -> str: - """Format file content with line numbers (`cat -n` style). + """Format file content with line numbers. Chunks lines longer than `MAX_LINE_LENGTH` with continuation markers - (e.g., `5.1`, `5.2`). + (e.g., `5.1`, `5.2`). Line markers are separated from source content + with two spaces so source tabs cannot be confused with a gutter separator. Args: content: File content as string or list of lines @@ -222,28 +222,26 @@ def format_content_with_line_numbers( else: lines = content - result_lines = [] + rows: list[tuple[str, str]] = [] + marker_width = 0 for i, line in enumerate(lines): line_num = i + start_line if len(line) <= MAX_LINE_LENGTH: - result_lines.append(f"{line_num:{LINE_NUMBER_WIDTH}d}\t{line}") + marker = str(line_num) + rows.append((marker, line)) + marker_width = max(marker_width, len(marker)) else: - # Split long line into chunks with continuation markers num_chunks = (len(line) + MAX_LINE_LENGTH - 1) // MAX_LINE_LENGTH for chunk_idx in range(num_chunks): start = chunk_idx * MAX_LINE_LENGTH end = min(start + MAX_LINE_LENGTH, len(line)) chunk = line[start:end] - if chunk_idx == 0: - # First chunk: use normal line number - result_lines.append(f"{line_num:{LINE_NUMBER_WIDTH}d}\t{chunk}") - else: - # Continuation chunks: use decimal notation (e.g., 5.1, 5.2) - continuation_marker = f"{line_num}.{chunk_idx}" - result_lines.append(f"{continuation_marker:>{LINE_NUMBER_WIDTH}}\t{chunk}") - - return "\n".join(result_lines) + marker = str(line_num) if chunk_idx == 0 else f"{line_num}.{chunk_idx}" + rows.append((marker, chunk)) + marker_width = max(marker_width, len(marker)) + + return "\n".join(f"{marker:>{marker_width}} {line}" for marker, line in rows) def check_empty_content(content: str) -> str | None: diff --git a/libs/deepagents/deepagents/middleware/filesystem.py b/libs/deepagents/deepagents/middleware/filesystem.py index 6ea29998816..6e24b6b431c 100644 --- a/libs/deepagents/deepagents/middleware/filesystem.py +++ b/libs/deepagents/deepagents/middleware/filesystem.py @@ -775,7 +775,7 @@ class ExecuteSchema(BaseModel): - Read more sections: read_file(file_path="...", offset=100, limit=200) for next 200 lines - Omit `limit` to use the default window; increase it only when necessary for editing - Specify offset and limit: read_file(file_path="...", offset=0, limit=100) reads first 100 lines -- Results are returned using cat -n format, with line numbers starting at 1 +- Results are returned with line numbers starting at 1, followed by two spaces and the source content - Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget. - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents. diff --git a/libs/deepagents/tests/unit_tests/test_end_to_end.py b/libs/deepagents/tests/unit_tests/test_end_to_end.py index eb2e4fa65d9..56c74487368 100644 --- a/libs/deepagents/tests/unit_tests/test_end_to_end.py +++ b/libs/deepagents/tests/unit_tests/test_end_to_end.py @@ -475,7 +475,7 @@ def test_deep_agent_truncate_lines(self, tmp_path: Path, backend: BackendProtoco assert "short line 0" in file_content assert "xxx" in file_content # All four wrapped chunks of source line 2 render in order. - for marker in ("2\t", "2.1\t", "2.2\t", "2.3\t"): + for marker in (" 2 ", "2.1 ", "2.2 ", "2.3 "): assert marker in file_content, f"missing continuation marker {marker!r}" # Source line 3 is the third source line and must be included. assert "short line 2" in file_content @@ -1313,11 +1313,11 @@ def test_deep_agent_read_file_pagination_does_not_skip_wrapped_lines(self, tmp_p # All three continuation chunks of the wrapped line 2 must render in # order, before `important instruction`, with nothing dropped at the # page boundary. - for marker in ("2\t", "2.1\t", "2.2\t"): + for marker in (" 2 ", "2.1 ", "2.2 "): assert marker in combined, f"missing continuation marker {marker!r}" - idx_first = combined.index("2\t") - idx_cont1 = combined.index("2.1\t") - idx_cont2 = combined.index("2.2\t") + idx_first = combined.index(" 2 ") + idx_cont1 = combined.index("2.1 ") + idx_cont2 = combined.index("2.2 ") idx_next = combined.index("important instruction") assert idx_first < idx_cont1 < idx_cont2 < idx_next diff --git a/libs/deepagents/tests/unit_tests/test_middleware.py b/libs/deepagents/tests/unit_tests/test_middleware.py index 02fc73f05de..9ec0af614fa 100644 --- a/libs/deepagents/tests/unit_tests/test_middleware.py +++ b/libs/deepagents/tests/unit_tests/test_middleware.py @@ -1254,9 +1254,16 @@ def test_format_content_with_line_numbers_short_lines(self): lines = result.split("\n") assert len(lines) == 3 - assert " 1\tshort line 1" in lines[0] - assert " 2\tshort line 2" in lines[1] - assert " 3\tshort line 3" in lines[2] + assert "1 short line 1" in lines[0] + assert "2 short line 2" in lines[1] + assert "3 short line 3" in lines[2] + + def test_format_content_with_line_numbers_preserves_source_tabs(self): + """Test that source tabs remain source content after the gutter.""" + content = ["\tif config:", "\t\tbilling_cfg = {}"] + result = format_content_with_line_numbers(content, start_line=1) + + assert result.split("\n") == ["1 \tif config:", "2 \t\tbilling_cfg = {}"] def test_format_content_with_line_numbers_long_line_with_continuation(self): """Test that long lines (>5000 chars) are split with continuation markers.""" @@ -1266,18 +1273,18 @@ def test_format_content_with_line_numbers_long_line_with_continuation(self): lines = result.split("\n") assert len(lines) == 7 # 1 short + 5 continuation (2, 2.1, 2.2, 2.3, 2.4) + 1 short - assert " 1\tshort line" in lines[0] - assert " 2\t" in lines[1] + assert " 1 short line" in lines[0] + assert " 2 " in lines[1] assert lines[1].count("a") == 5000 - assert " 2.1\t" in lines[2] + assert "2.1 " in lines[2] assert lines[2].count("a") == 5000 - assert " 2.2\t" in lines[3] + assert "2.2 " in lines[3] assert lines[3].count("a") == 5000 - assert " 2.3\t" in lines[4] + assert "2.3 " in lines[4] assert lines[4].count("a") == 5000 - assert " 2.4\t" in lines[5] + assert "2.4 " in lines[5] assert lines[5].count("a") == 5000 - assert " 3\tanother short line" in lines[6] + assert " 3 another short line" in lines[6] def test_format_content_with_line_numbers_multiple_long_lines(self): """Test multiple long lines in sequence with proper line numbering.""" @@ -1287,18 +1294,18 @@ def test_format_content_with_line_numbers_multiple_long_lines(self): result = format_content_with_line_numbers(content, start_line=5) lines = result.split("\n") assert len(lines) == 7 # 3 (line 5, 5.1, 5.2) + 1 middle + 3 (line 7, 7.1, 7.2) - assert " 5\t" in lines[0] + assert " 5 " in lines[0] assert lines[0].count("x") == 5000 - assert " 5.1\t" in lines[1] + assert "5.1 " in lines[1] assert lines[1].count("x") == 5000 - assert " 5.2\t" in lines[2] + assert "5.2 " in lines[2] assert lines[2].count("x") == 5000 - assert " 6\tmiddle" in lines[3] - assert " 7\t" in lines[4] + assert " 6 middle" in lines[3] + assert " 7 " in lines[4] assert lines[4].count("y") == 5000 - assert " 7.1\t" in lines[5] + assert "7.1 " in lines[5] assert lines[5].count("y") == 5000 - assert " 7.2\t" in lines[6] + assert "7.2 " in lines[6] assert lines[6].count("y") == 5000 def test_format_content_with_line_numbers_exact_limit(self): @@ -1309,7 +1316,7 @@ def test_format_content_with_line_numbers_exact_limit(self): lines = result.split("\n") assert len(lines) == 1 - assert " 1\t" in lines[0] + assert "1 " in lines[0] assert lines[0].count("b") == 5000 def test_read_file_with_long_lines_shows_continuation_markers(self): @@ -1322,14 +1329,14 @@ def test_read_file_with_long_lines_shows_continuation_markers(self): result = format_content_with_line_numbers(sliced, start_line=1) lines = result.split("\n") assert len(lines) == 5 # 1 first + 3 continuation (2, 2.1, 2.2) + 1 third - assert " 1\tfirst line" in lines[0] - assert " 2\t" in lines[1] + assert " 1 first line" in lines[0] + assert " 2 " in lines[1] assert lines[1].count("z") == 5000 - assert " 2.1\t" in lines[2] + assert "2.1 " in lines[2] assert lines[2].count("z") == 5000 - assert " 2.2\t" in lines[3] + assert "2.2 " in lines[3] assert lines[3].count("z") == 5000 - assert " 3\tthird line" in lines[4] + assert " 3 third line" in lines[4] def test_read_file_with_offset_and_long_lines(self): """Test that read_file with offset handles long lines correctly.""" @@ -1341,13 +1348,13 @@ def test_read_file_with_offset_and_long_lines(self): result = format_content_with_line_numbers(sliced, start_line=3) lines = result.split("\n") assert len(lines) == 4 # 3 continuation (3, 3.1, 3.2) + 1 line4 - assert " 3\t" in lines[0] + assert " 3 " in lines[0] assert lines[0].count("m") == 5000 - assert " 3.1\t" in lines[1] + assert "3.1 " in lines[1] assert lines[1].count("m") == 5000 - assert " 3.2\t" in lines[2] + assert "3.2 " in lines[2] assert lines[2].count("m") == 2000 - assert " 4\tline4" in lines[3] + assert " 4 line4" in lines[3] def test_intercept_short_toolmessage(self): """Test that small ToolMessages pass through unchanged.""" From d9a54ef87e3aaeb668f9e1f340f7f31fe7f0033f Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 8 Jul 2026 22:11:45 -0400 Subject: [PATCH 2/9] chore(code): remove code changes from sdk PR --- .../deepagents_code/tui/widgets/messages.py | 25 +++++++++---------- .../unit_tests/tui/widgets/test_messages.py | 12 ++++----- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/libs/code/deepagents_code/tui/widgets/messages.py b/libs/code/deepagents_code/tui/widgets/messages.py index 5df1f3df3eb..0249c1fe265 100644 --- a/libs/code/deepagents_code/tui/widgets/messages.py +++ b/libs/code/deepagents_code/tui/widgets/messages.py @@ -1982,19 +1982,18 @@ def _format_ls_output( # noqa: PLR6301 # Grouped as method for widget cohesion @staticmethod def _compact_line_gutter(output: str) -> str: - r"""Tighten legacy `read_file` cat-n line-number gutters for display. - - Older tool output used `f"{line_num:6d}\t{line}"` — a 6-wide - right-justified number plus a tab — so even single-digit line numbers - carried five leading spaces and the tab pushed content to a distant tab - stop. The TUI renders that legacy gutter in the newer compact shape: - numbers right-justified to the widest number actually present, then two - spaces, mirroring how grep/glob results sit flush left. Source - indentation after the gutter is preserved untouched. - - Lines that don't match the legacy cat-n shape (e.g. current compact - read output, test fixtures, or non-numbered output) are passed through - unchanged. + r"""Tighten `read_file`'s cat -n line-number gutter for display. + + The tool emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified + number plus a tab — so even single-digit line numbers carry five + leading spaces and the tab pushes content to a distant tab stop. The + model needs that raw format for edits, but the TUI renders a compact + gutter instead: numbers right-justified to the widest number actually + present, then two spaces, mirroring how grep/glob results sit flush + left. Source indentation after the gutter is preserved untouched. + + Lines that don't match the cat -n shape (e.g. test fixtures or + non-numbered output) are passed through unchanged. Returns: The output with compacted gutters, or the original string if no diff --git a/libs/code/tests/unit_tests/tui/widgets/test_messages.py b/libs/code/tests/unit_tests/tui/widgets/test_messages.py index 53022b97be5..38a322c8fab 100644 --- a/libs/code/tests/unit_tests/tui/widgets/test_messages.py +++ b/libs/code/tests/unit_tests/tui/widgets/test_messages.py @@ -2760,14 +2760,14 @@ def test_format_file_output_preview_budget_hit_on_separator(self) -> None: def test_format_output_compacts_line_number_gutter(self) -> None: r"""Line-number gutters are tightened, all rows aligned to one column. - Legacy `read_file` output used `f"{line_num:6d}\t{line}"` — a 6-wide - right-justified number plus a tab — which renders far from the line - numbers and (when the first row's padding was stripped) misaligned. The - TUI recomputes a compact gutter: numbers right-justified to the widest - number present, two spaces, then the original source indentation. + `read_file` emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified + number plus a tab — which renders far from the line numbers and (when + the first row's padding was stripped) misaligned. The TUI recomputes a + compact gutter: numbers right-justified to the widest number present, + two spaces, then the original source indentation. """ msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) - # Legacy cat-n style: 6-wide right-justified number + tab + source line. + # cat -n style: 6-wide right-justified number + tab + source line. output = ' 1\t"""doc"""\n 2\t\n 3\t indented' result = msg._format_output(output, is_preview=False) From 6c7dc2fc1a8528d692ad6d1857a19de541eb0628 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Wed, 8 Jul 2026 23:54:05 -0400 Subject: [PATCH 3/9] cr --- .../deepagents/backends/protocol.py | 5 +- .../deepagents/middleware/filesystem.py | 1 - .../harness/_nvidia_nemotron_3_ultra.py | 7 +- libs/deepagents/pyproject.toml | 1 + .../tests/unit_tests/smoke_tests/conftest.py | 21 ++ .../custom_system_message_tools.json | 6 +- .../system_prompt_with_execute_tools.json | 6 +- .../system_prompt_with_media_extra_tools.json | 305 ++++++++++++++++++ ...m_prompt_with_memory_and_skills_tools.json | 6 +- ...stem_prompt_with_routed_backend_tools.json | 6 +- ...t_with_sync_and_async_subagents_tools.json | 6 +- .../system_prompt_without_execute_tools.json | 6 +- .../smoke_tests/test_system_prompt.py | 30 ++ .../tests/unit_tests/test_middleware.py | 59 +++- 14 files changed, 437 insertions(+), 28 deletions(-) create mode 100644 libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json diff --git a/libs/deepagents/deepagents/backends/protocol.py b/libs/deepagents/deepagents/backends/protocol.py index ce07bd48b88..ecaaeff85da 100644 --- a/libs/deepagents/deepagents/backends/protocol.py +++ b/libs/deepagents/deepagents/backends/protocol.py @@ -420,9 +420,10 @@ def read( Returns: String containing file content formatted with line numbers, - starting at line 1. + starting at `offset + 1`. - Lines longer than 2000 characters are truncated. + Lines longer than 5000 characters are split into multiple rows + with continuation markers (e.g., `5.1`, `5.2`). Returns an error string if the file doesn't exist or can't be read. """ diff --git a/libs/deepagents/deepagents/middleware/filesystem.py b/libs/deepagents/deepagents/middleware/filesystem.py index 6e24b6b431c..6651feab6d7 100644 --- a/libs/deepagents/deepagents/middleware/filesystem.py +++ b/libs/deepagents/deepagents/middleware/filesystem.py @@ -534,7 +534,6 @@ def _format_glob_tool_result(paths: list[str], *, truncated: bool) -> str: EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents" GLOB_TIMEOUT = 10.0 # seconds -LINE_NUMBER_WIDTH = 6 SEARCH_TRUNCATION_NOTE = ( "Note: the search stopped early because it hit its time limit. The matches above are valid but incomplete. " "Narrow the search (a more specific pattern or a narrower path) to see the rest." diff --git a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py index a6d5ac54745..1e32f862945 100644 --- a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py +++ b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py @@ -136,6 +136,11 @@ class ReadFileContinuationNoticeMiddleware(AgentMiddleware): name = "ReadFileContinuationNoticeMiddleware" + @staticmethod + def _is_numbered_read_file_row(row: str) -> bool: + """Return whether `row` looks like a formatted `read_file` source line.""" + return re.match(r"^\s*\d+(?:\.\d+)?(?:\t|\s{2,})", row) is not None + @staticmethod def _annotate( request: ToolCallRequest, @@ -159,7 +164,7 @@ def _annotate( except (TypeError, ValueError): limit = _DEFAULT_READ_LIMIT - n_lines = sum(1 for row in content.split("\n") if "\t" in row and row.split("\t", 1)[0].strip().isdigit()) + n_lines = sum(1 for row in content.split("\n") if ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row(row)) if n_lines < limit: return result diff --git a/libs/deepagents/pyproject.toml b/libs/deepagents/pyproject.toml index 1eff01b4619..31150bcfcd6 100644 --- a/libs/deepagents/pyproject.toml +++ b/libs/deepagents/pyproject.toml @@ -156,6 +156,7 @@ filterwarnings = [ ] markers = [ "benchmark: wall-time benchmarks for construction performance", + "video_extra: pin the read_file video gate on to snapshot the [video]-extra variant", ] [tool.ty.environment] diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/conftest.py b/libs/deepagents/tests/unit_tests/smoke_tests/conftest.py index 6f97a7817e5..3cd5ca0b35c 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/conftest.py +++ b/libs/deepagents/tests/unit_tests/smoke_tests/conftest.py @@ -4,6 +4,8 @@ import pytest +from deepagents.middleware import filesystem + def pytest_addoption(parser: pytest.Parser) -> None: parser.addoption( @@ -24,3 +26,22 @@ def snapshots_dir() -> Path: @pytest.fixture def update_snapshots(request: pytest.FixtureRequest) -> bool: return bool(request.config.getoption("--update-snapshots")) + + +@pytest.fixture(autouse=True) +def _pin_video_dependencies(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None: + """Pin the `read_file` video gate so prompt snapshots are env-independent. + + `read_file`'s description switches between a text-only and a video-aware + variant based on `video_dependencies_available()` (the optional `[video]` + extra: PyAV + Pillow). Whether that extra is installed varies by environment, + so without pinning the gate, the same test would snapshot different wording on + different machines and `--update-snapshots` could silently swap variants. + + The gate defaults to off (the text-only base install); a test marked + `video_extra` pins it on to cover the `[video]`-extra variant. Rendering the + description never touches PyAV, so forcing either state is safe regardless of + what is installed. + """ + enabled = request.node.get_closest_marker("video_extra") is not None + monkeypatch.setattr(filesystem, "video_dependencies_available", lambda: enabled) diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json index 6dcceb029b6..d3bca4e9c18 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json index 365603baac6..11954ce6271 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json new file mode 100644 index 00000000000..9ef7dcd2c4f --- /dev/null +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json @@ -0,0 +1,305 @@ +[ + { + "function": { + "description": "Use this tool to create and manage a structured task list for your current work session. This helps you track progress and organize complex tasks.\n\nOnly use this tool if you think it will be helpful in staying organized. If the user's request is trivial and takes less than 3 steps, it is better to NOT use this tool and just do the task directly.\n\n## When to Use This Tool\n\nUse this tool in these scenarios:\n\n1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions\n2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations\n3. User explicitly requests todo list - When the user directly asks you to use the todo list\n4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)\n5. The plan may need future revisions or updates based on results from the first few steps\n\n## How to Use This Tool\n\n1. When you start working on a task - Mark it as in_progress BEFORE beginning work.\n2. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation.\n3. You can also update future tasks, such as deleting them if they are no longer necessary, or adding new tasks that are necessary. Don't change previously completed tasks.\n4. You can make several updates to the todo list at once. For example, when you complete a task, you can mark the next task you need to start as in_progress.\n\n## When NOT to Use This Tool\n\nIt is important to skip using this tool when:\n1. There is only a single, straightforward task\n2. The task is trivial and tracking it provides no benefit\n3. The task can be completed in less than 3 trivial steps\n4. The task is purely conversational or informational\n\n## Task States and Management\n\n1. **Task States**: Use these states to track progress:\n - pending: Task not yet started\n - in_progress: Currently working on (you can have multiple tasks in_progress at a time if they are not related to each other and can be run in parallel)\n - completed: Task finished successfully\n\n2. **Task Management**:\n - Update task status in real-time as you work\n - Mark tasks complete IMMEDIATELY after finishing (don't batch completions)\n - Complete current tasks before starting new ones\n - Remove tasks that are no longer relevant from the list entirely\n - IMPORTANT: When you write this todo list, you should mark your first task (or tasks) as in_progress immediately!.\n - IMPORTANT: Unless all tasks are completed, you should always have at least one task in_progress.\n\n3. **Task Completion Requirements**:\n - ONLY mark a task as completed when you have FULLY accomplished it\n - If you encounter errors, blockers, or cannot finish, keep the task as in_progress\n - When blocked, create a new task describing what needs to be resolved\n - Never mark a task as completed if:\n - There are unresolved issues or errors\n - Work is partial or incomplete\n - You encountered blockers that prevent completion\n - You couldn't find necessary resources or dependencies\n - Quality standards haven't been met\n\n4. **Task Breakdown**:\n - Create specific, actionable items\n - Break complex tasks into smaller, manageable steps\n - Use clear, descriptive task names\n\nBeing proactive with task management ensures you complete all requirements successfully\nRemember: If you only need to make a few tool calls to complete a task, and it is clear what you need to do, it is better to just do the task directly and NOT call this tool at all.\n\n## When You Finish\n\n`write_todos` tracks your work; it does not deliver the answer. Whatever the user asked for \u2014 computations, summaries, comparisons, data \u2014 must appear as text content in a message after your final `write_todos` call. Marking the last todo complete is not itself an answer to the user.", + "name": "write_todos", + "parameters": { + "properties": { + "todos": { + "items": { + "description": "A single todo item with content and status.", + "properties": { + "content": { + "type": "string" + }, + "status": { + "enum": [ + "pending", + "in_progress", + "completed" + ], + "type": "string" + } + }, + "required": [ + "content", + "status" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "todos" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Lists all files in a directory.\n\nThis is useful for exploring the filesystem and finding the right file to read or edit.\nYou should almost ALWAYS use this tool before using the read_file or edit_file tools.", + "name": "ls", + "parameters": { + "properties": { + "path": { + "description": "Absolute path to the directory to list. Must be absolute, not relative.", + "type": "string" + } + }, + "required": [ + "path" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "name": "read_file", + "parameters": { + "properties": { + "file_path": { + "description": "Absolute path to the file to read. Must be absolute, not relative.", + "type": "string" + }, + "limit": { + "default": 100, + "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "type": "integer" + }, + "offset": { + "default": 0, + "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "type": "integer" + } + }, + "required": [ + "file_path" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Writes content to a file. Creates the file if it does not exist; replaces it entirely if it does.\n\nUsage:\n- Use this tool when you intend to create a new file or replace the whole file. You do not need to read the file first.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.", + "name": "write_file", + "parameters": { + "properties": { + "content": { + "description": "The text content to write to the file. This parameter is required.", + "type": "string" + }, + "file_path": { + "description": "Absolute path where the file should be written. Must be absolute, not relative.", + "type": "string" + } + }, + "required": [ + "file_path", + "content" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Performs exact string replacements in files.\n\nUsage:\n- You must read the file before editing. This tool will error if you attempt an edit without reading the file first.\n- When editing, preserve the exact indentation (tabs/spaces) from the read output. Never include line number prefixes in old_string or new_string.\n- ALWAYS prefer editing existing files over creating new ones.\n- Only use emojis if the user explicitly requests it.", + "name": "edit_file", + "parameters": { + "properties": { + "file_path": { + "description": "Absolute path to the file to edit. Must be absolute, not relative.", + "type": "string" + }, + "new_string": { + "description": "The text to replace old_string with. Must be different from old_string.", + "type": "string" + }, + "old_string": { + "description": "The exact text to find and replace. Must be unique in the file unless replace_all is True.", + "type": "string" + }, + "replace_all": { + "default": false, + "description": "If True, replace all occurrences of old_string. If False (default), old_string must be unique.", + "type": "boolean" + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Deletes a file or directory from the filesystem.\n\nUsage:\n- Permanently removes the file or directory at the given absolute path.\n- Deleting a directory removes it and everything inside it, recursively. Prefer\n deleting a directory in one call over deleting each file individually.\n- This cannot be undone, so only delete paths you are sure are no longer needed.", + "name": "delete", + "parameters": { + "properties": { + "file_path": { + "description": "Absolute path to the file to delete. Must be absolute, not relative.", + "type": "string" + } + }, + "required": [ + "file_path" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Find files matching a glob pattern.\n\nSupports standard glob patterns: `*` (any characters), `**` (any directories), `?` (single character).\nReturns a list of absolute file paths that match the pattern.\n\nExamples:\n- `**/*.py` - Find all Python files\n- `*.txt` - Find all text files in the backend's default root\n- `/subdir/**/*.md` - Find all markdown files under /subdir", + "name": "glob", + "parameters": { + "properties": { + "path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Base directory to search from. Defaults to the backend's default root." + }, + "pattern": { + "description": "Glob pattern to match files (e.g., '**/*.py', '*.txt', '/subdir/**/*.md').", + "type": "string" + } + }, + "required": [ + "pattern" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Search for a LITERAL text pattern across files (NOT regex).\n\nReturns matching files or content based on output_mode. The pattern is matched\nverbatim: regex metacharacters are treated as ordinary characters, NOT operators.\n\nDo NOT pass a regex. In particular:\n- To match any of several strings, run a SEPARATE grep for each one. There is no\n `|` alternation: `grep(pattern=\"foo|bar\")` looks for the literal text \"foo|bar\".\n- Do not use wildcards (`.*`) or escapes (`\\.`); they match those characters literally.\n- If you genuinely need regex, use the execute tool with `rg ''` instead.\n\nExamples:\n- Search all files: `grep(pattern=\"TODO\")`\n- Search Python files only: `grep(pattern=\"import\", glob=\"*.py\")`\n- Show matching lines: `grep(pattern=\"error\", output_mode=\"content\")`\n- Literal special chars are fine: `grep(pattern=\"def __init__(self):\")`", + "name": "grep", + "parameters": { + "properties": { + "glob": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Glob pattern (NOT regex) limiting which files are searched (e.g. '*.py', '*.ts'). A pattern without '/' matches the file name at any depth; a pattern containing '/' matches the search-root-relative path (e.g. 'src/**/*.py'). This is an in-tool file filter, not a call to the separate glob tool. Brace expansion (e.g. '*.{ts,tsx}') is not supported on all backends; run a separate search per extension for reliable results." + }, + "output_mode": { + "default": "files_with_matches", + "description": "Shape of the returned text. 'files_with_matches' (default): newline-separated matching file paths. 'content': matching lines grouped by file under a ':' header, each line indented and formatted ': ' (only the matched line, no surrounding context). 'count': one ': ' line per file.", + "enum": [ + "files_with_matches", + "content", + "count" + ], + "type": "string" + }, + "path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Directory to search in. Defaults to current working directory." + }, + "pattern": { + "description": "Text pattern to search for (literal string, not regex).", + "type": "string" + } + }, + "required": [ + "pattern" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Executes a shell command in an isolated sandbox environment.\n\nUsage:\nExecutes a given command in the sandbox environment with proper handling and security measures.\nBefore executing the command, please follow these steps:\n1. Directory Verification:\n - If the command will create new directories or files, first use the ls tool to verify the parent directory exists and is the correct location\n - For example, before running \"mkdir foo/bar\", first use ls to check that \"foo\" exists and is the intended parent directory\n2. Command Execution:\n - Always quote file paths that contain spaces with double quotes (e.g., cd \"path with spaces/file.txt\")\n - Examples of proper quoting:\n - cd \"/Users/name/My Documents\" (correct)\n - cd /Users/name/My Documents (incorrect - will fail)\n - python \"/path/with spaces/script.py\" (correct)\n - python /path/with spaces/script.py (incorrect - will fail)\n - After ensuring proper quoting, execute the command\n - Capture the output of the command\nUsage notes:\n - Commands run in an isolated sandbox environment\n - Returns combined stdout/stderr output with exit code\n - If the output is very large, it may be truncated\n - For long-running commands, use the optional timeout parameter to override the default timeout (e.g., execute(command=\"make build\", timeout=300))\n - A timeout of 0 may disable timeouts on backends that support no-timeout execution\n - VERY IMPORTANT: You MUST avoid using search commands like find and grep. Instead use the grep, glob tools to search. You MUST avoid read tools like cat, head, tail, and use read_file to read files.\n - When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings)\n - Use '&&' when commands depend on each other (e.g., \"mkdir dir && cd dir\")\n - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail\n - Try to maintain your current working directory throughout the session by using absolute paths and avoiding usage of cd\n\nExamples:\n Good examples:\n - execute(command=\"pytest /foo/bar/tests\")\n - execute(command=\"python /path/to/script.py\")\n - execute(command=\"npm install && npm test\")\n - execute(command=\"make build\", timeout=300)\n\n Bad examples (avoid these):\n - execute(command=\"cd /foo/bar && pytest tests\") # Use absolute path instead\n - execute(command=\"cat file.txt\") # Use read_file tool instead\n - execute(command=\"find . -name '*.py'\") # Use glob tool instead\n - execute(command=\"grep -r 'pattern' .\") # Use grep tool instead\n\nNote: This tool is only available if the backend supports execution (SandboxBackendProtocol).\nIf execution is not supported, the tool will return an error message.", + "name": "execute", + "parameters": { + "properties": { + "command": { + "description": "Shell command to execute in the sandbox environment.", + "type": "string" + }, + "timeout": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional timeout in seconds for this command. Overrides the default timeout. Use 0 for no-timeout execution on backends that support it." + } + }, + "required": [ + "command" + ], + "type": "object" + } + }, + "type": "function" + }, + { + "function": { + "description": "Launch an ephemeral subagent to handle complex, multi-step independent tasks with isolated context windows.\n\nAvailable agent types and the tools they have access to:\n- general-purpose: General-purpose agent for researching complex questions, searching for files and content, and executing multi-step tasks. When you are searching for a keyword or file and are not confident that you will find the right match in the first few tries use this agent to perform the search for you. This agent has access to all tools as the main agent.\n\nWhen using the Task tool, you must specify a subagent_type parameter to select which agent type to use.\n\n## Usage notes:\n1. Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n2. When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n3. Each agent invocation is stateless. You will not be able to send additional messages to the agent, nor will the agent be able to communicate with you outside of its final report. Therefore, your prompt should contain a highly detailed task description for the agent to perform autonomously and you should specify exactly what information the agent should return back to you in its final and only message to you.\n4. The agent's outputs should generally be trusted\n5. Clearly tell the agent whether you expect it to create content, perform analysis, or just do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent\n6. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.\n7. When only the general-purpose agent is provided, you should use it for all tasks. It is great for isolating context and token usage, and completing specific, complex tasks, as it has all the same capabilities as the main agent.\n\n### Example usage of the general-purpose agent:\n\n\n\"general-purpose\": use this agent for general purpose tasks, it has access to all tools as the main agent.\n\n\n\nUser: \"I want to conduct research on the accomplishments of Lebron James, Michael Jordan, and Kobe Bryant, and then compare them.\"\nAssistant: *Uses the task tool in parallel to conduct isolated research on each of the three players*\nAssistant: *Synthesizes the results of the three isolated research tasks and responds to the User*\n\nResearch is a complex, multi-step task in it of itself.\nThe research of each individual player is not dependent on the research of the other players.\nThe assistant uses the task tool to break down the complex objective into three isolated tasks.\nEach research task only needs to worry about context and tokens about one player, then returns synthesized information about each player as the Tool Result.\nThis means each research task can dive deep and spend tokens and context deeply researching each player, but the final result is synthesized information, and saves us tokens in the long run when comparing the players to each other.\n\n\n\n\nUser: \"Analyze a single large code repository for security vulnerabilities and generate a report.\"\nAssistant: *Launches a single `task` subagent for the repository analysis*\nAssistant: *Receives report and integrates results into final summary*\n\nSubagent is used to isolate a large, context-heavy task, even though there is only one. This prevents the main thread from being overloaded with details.\nIf the user then asks followup questions, we have a concise report to reference instead of the entire history of analysis and tool calls, which is good and saves us time and money.\n\n\n\n\nUser: \"Schedule two meetings for me and prepare agendas for each.\"\nAssistant: *Calls the task tool in parallel to launch two `task` subagents (one per meeting) to prepare agendas*\nAssistant: *Returns final schedules and agendas*\n\nTasks are simple individually, but subagents help silo agenda preparation.\nEach subagent only needs to worry about the agenda for one meeting.\n\n\n\n\nUser: \"I want to order a pizza from Dominos, order a burger from McDonald's, and order a salad from Subway.\"\nAssistant: *Calls tools directly in parallel to order a pizza from Dominos, a burger from McDonald's, and a salad from Subway*\n\nThe assistant did not use the task tool because the objective is super simple and clear and only requires a few trivial tool calls.\nIt is better to just complete the task directly and NOT use the `task` tool.\n\n\n\n### Example usage with custom agents:\n\n\n\"content-reviewer\": use this agent after you are done creating significant content or documents\n\"greeting-responder\": use this agent when to respond to user greetings with a friendly joke\n\"research-analyst\": use this agent to conduct thorough research on complex topics\n\n\n\nuser: \"Please write a function that checks if a number is prime\"\nassistant: Sure let me write a function that checks if a number is prime\nassistant: First let me use the Write tool to write a function that checks if a number is prime\nassistant: I'm going to use the Write tool to write the following code:\n\nfunction isPrime(n) {\n if (n <= 1) return false\n for (let i = 2; i * i <= n; i++) {\n if (n % i === 0) return false\n }\n return true\n}\n\n\nSince significant content was created and the task was completed, now use the content-reviewer agent to review the work\n\nassistant: Now let me use the content-reviewer agent to review the code\nassistant: Uses the Task tool to launch with the content-reviewer agent\n\n\n\nuser: \"Can you help me research the environmental impact of different renewable energy sources and create a comprehensive report?\"\n\nThis is a complex research task that would benefit from using the research-analyst agent to conduct thorough analysis\n\nassistant: I'll help you research the environmental impact of renewable energy sources. Let me use the research-analyst agent to conduct comprehensive research on this topic.\nassistant: Uses the Task tool to launch with the research-analyst agent, providing detailed instructions about what research to conduct and what format the report should take\n\n\n\nuser: \"Hello\"\n\nSince the user is greeting, use the greeting-responder agent to respond with a friendly joke\n\nassistant: \"I'm going to use the Task tool to launch with the greeting-responder agent\"\n", + "name": "task", + "parameters": { + "properties": { + "description": { + "description": "A detailed description of the task for the subagent to perform autonomously. Include all necessary context and specify the expected output format.", + "type": "string" + }, + "subagent_type": { + "description": "The type of subagent to use. Must be one of the available agent types listed in the tool description.", + "type": "string" + } + }, + "required": [ + "description", + "subagent_type" + ], + "type": "object" + } + }, + "type": "function" + } +] diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json index 6dcceb029b6..d3bca4e9c18 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json index 365603baac6..11954ce6271 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json index d83b47335e1..18e6ddfedfe 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json index 6dcceb029b6..d3bca4e9c18 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned using cat -n format, with line numbers starting at 1\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { @@ -69,12 +69,12 @@ }, "limit": { "default": 100, - "description": "Maximum number of lines to read for text files. For videos, seconds of source to sample.", + "description": "Maximum number of lines to read. Use for pagination of large files.", "type": "integer" }, "offset": { "default": 0, - "description": "Line number to start reading from for text files (0-indexed). For videos, seconds into the source to start sampling.", + "description": "Line number to start reading from (0-indexed). Use for pagination of large files.", "type": "integer" } }, diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/test_system_prompt.py b/libs/deepagents/tests/unit_tests/smoke_tests/test_system_prompt.py index 2043043062d..7786c31aef0 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/test_system_prompt.py +++ b/libs/deepagents/tests/unit_tests/smoke_tests/test_system_prompt.py @@ -4,6 +4,7 @@ from pathlib import Path from typing import Any +import pytest from langchain_core.messages import AIMessage, HumanMessage, SystemMessage from langchain_core.utils.function_calling import convert_to_openai_tool from langgraph.store.memory import InMemoryStore @@ -112,6 +113,35 @@ def test_system_prompt_snapshot_with_execute(snapshots_dir: Path, *, update_snap ) +@pytest.mark.video_extra +def test_system_prompt_with_media_extra(snapshots_dir: Path, *, update_snapshots: bool) -> None: + """Snapshot the `read_file` tool when the optional `[video]` extra is installed. + + The base `*_tools.json` snapshots capture the text-only `read_file` + description (the default install). When PyAV + Pillow are present, + `read_file` instead advertises the video-aware description and + seconds-based `offset`/`limit`. The `video_extra` marker pins that gate on + (see the smoke conftest), so this variant stays covered regardless of + whether the extra is actually installed in the test environment. The video + wording only affects `read_file`, so one representative config is enough. + """ + model = _smoke_model() + backend = LocalShellBackend(root_dir=Path.cwd(), virtual_mode=True) + agent = create_deep_agent(model=model, backend=backend) + + _invoke_for_snapshot(agent, {"messages": [HumanMessage(content="hi")]}) + + history = model.call_history + assert len(history) >= 1 + + _assert_tools_snapshot( + snapshots_dir, + "system_prompt_with_media_extra_tools.json", + history[0]["tools"], + update_snapshots=update_snapshots, + ) + + def test_system_prompt_snapshot_with_routed_backend(snapshots_dir: Path, *, update_snapshots: bool) -> None: """Snapshot the materialized prompt for all route classifications (issue #3050). diff --git a/libs/deepagents/tests/unit_tests/test_middleware.py b/libs/deepagents/tests/unit_tests/test_middleware.py index 9ec0af614fa..4e2f1c0c87c 100644 --- a/libs/deepagents/tests/unit_tests/test_middleware.py +++ b/libs/deepagents/tests/unit_tests/test_middleware.py @@ -1248,15 +1248,50 @@ def test_update_file_data_preserves_long_lines(self): assert updated_file_data["created_at"] == initial_file_data["created_at"] def test_format_content_with_line_numbers_short_lines(self): - """Test that short lines (<=10000 chars) are displayed normally.""" + """Test that short lines (<=5000 chars) are displayed normally.""" content = ["short line 1", "short line 2", "short line 3"] result = format_content_with_line_numbers(content, start_line=1) + assert result.split("\n") == [ + "1 short line 1", + "2 short line 2", + "3 short line 3", + ] + + def test_format_content_with_line_numbers_empty_and_single(self): + """Empty content yields an empty string; a single line needs no padding.""" + assert format_content_with_line_numbers("") == "" + assert format_content_with_line_numbers([]) == "" + assert format_content_with_line_numbers(["only"]) == "1 only" + + def test_format_content_with_line_numbers_aligns_across_magnitude(self): + """Markers right-justify to a shared width when line counts cross 9->10. + + The gutter is exactly `marker_width + 2` spaces, so an over-wide gutter + (a `marker_width` bug) is caught here that substring checks would miss. + """ + content = [f"line{i}" for i in range(12)] + result = format_content_with_line_numbers(content, start_line=1) + lines = result.split("\n") - assert len(lines) == 3 - assert "1 short line 1" in lines[0] - assert "2 short line 2" in lines[1] - assert "3 short line 3" in lines[2] + # Widest marker is "12" (width 2), so single-digit markers get one pad. + assert lines[0] == " 1 line0" + assert lines[8] == " 9 line8" + assert lines[9] == "10 line9" + assert lines[11] == "12 line11" + + def test_format_content_with_line_numbers_offset_crosses_magnitude(self): + """A `start_line` offset that pushes numbers past 9 widens the gutter.""" + content = ["a", "b", "c", "d", "e"] + result = format_content_with_line_numbers(content, start_line=8) + + assert result.split("\n") == [ + " 8 a", + " 9 b", + "10 c", + "11 d", + "12 e", + ] def test_format_content_with_line_numbers_preserves_source_tabs(self): """Test that source tabs remain source content after the gutter.""" @@ -1265,6 +1300,18 @@ def test_format_content_with_line_numbers_preserves_source_tabs(self): assert result.split("\n") == ["1 \tif config:", "2 \t\tbilling_cfg = {}"] + def test_format_content_with_line_numbers_preserves_source_spaces(self): + """Leading source spaces survive intact after the two-space gutter. + + The gutter itself is spaces, so this documents that space-indented + source is preserved byte-for-byte even though the boundary is not + marked by a distinct separator character. + """ + content = [" def foo():", " return 1"] + result = format_content_with_line_numbers(content, start_line=1) + + assert result.split("\n") == ["1 def foo():", "2 return 1"] + def test_format_content_with_line_numbers_long_line_with_continuation(self): """Test that long lines (>5000 chars) are split with continuation markers.""" long_line = "a" * 25000 @@ -1316,7 +1363,7 @@ def test_format_content_with_line_numbers_exact_limit(self): lines = result.split("\n") assert len(lines) == 1 - assert "1 " in lines[0] + assert lines[0].startswith("1 b") assert lines[0].count("b") == 5000 def test_read_file_with_long_lines_shows_continuation_markers(self): From e85f8a1b070af1b53d64fdf78df9b86195080268 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Thu, 9 Jul 2026 00:03:07 -0400 Subject: [PATCH 4/9] cr --- .../smoke_tests/snapshots/README.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md new file mode 100644 index 00000000000..48dac9f20c5 --- /dev/null +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md @@ -0,0 +1,26 @@ +# System prompt smoke snapshots + +These files are golden snapshots for the prompts and tool schemas produced by `tests/unit_tests/smoke_tests/test_system_prompt.py`. + +Each snapshot is self-contained: the tests compare the complete rendered prompt or complete tool list for one agent configuration. A `_with_*` name means that scenario includes the named feature; it does not mean the file stores a diff against a shared base snapshot. + +Use focused snapshots for individual prompt/tool features, and add combination snapshots only when features interact in prompt or tool rendering. A full powerset of every feature combination would mostly duplicate shared prompt text and make expected wording changes noisy. + +## Files + +| Snapshot | Shell `execute` tool? | What it covers | +| --- | --- | --- | +| `system_prompt_with_execute.md` | Yes | Full system prompt for a local shell backend. | +| `system_prompt_with_execute_tools.json` | Yes | Tool schemas for the local shell backend, including `execute`. | +| `system_prompt_with_media_extra_tools.json` | Yes | Tool schemas when the optional media/video extra is enabled; this mainly covers the video-aware `read_file` description and schema. | +| `system_prompt_without_execute.md` | No | Full system prompt for a filesystem-only backend. | +| `system_prompt_without_execute_tools.json` | No | Tool schemas for the filesystem-only backend, without `execute`. | +| `custom_system_message.md` | No | Full prompt when the caller passes a custom `system_prompt`. | +| `custom_system_message_tools.json` | No | Tool schemas for the custom-prompt setup; the custom prompt should not change the tool surface. | +| `system_prompt_with_routed_backend.md` | Yes | Full prompt for a `CompositeBackend` with host-mapped, non-virtual, and unmapped virtual routes. | +| `system_prompt_with_routed_backend_tools.json` | Yes | Tool schemas for the routed-backend setup, including `execute` from the local shell default backend. | +| `system_prompt_with_sandbox_default.md` | Sandbox-capable backend | Full prompt when the default backend is a remote/sandbox shell. Local filesystem routes should not be described as local shell-accessible host paths. | +| `system_prompt_with_sync_and_async_subagents.md` | No | Full prompt when both local/sync subagents and remote/async subagents are configured. | +| `system_prompt_with_sync_and_async_subagents_tools.json` | No | Tool schemas for the sync+async subagent setup, including async task-management tools. | +| `system_prompt_with_memory_and_skills.md` | No | Full prompt when memory files and skills directories are present. | +| `system_prompt_with_memory_and_skills_tools.json` | No | Tool schemas for the memory+skills setup; memory and skills should affect prompt context, not the core filesystem tool surface. | From 7abc5adefaf1e9445be2e8b51f7850360807d1b0 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Mon, 13 Jul 2026 17:07:38 -0400 Subject: [PATCH 5/9] cr --- .../harness/_nvidia_nemotron_3_ultra.py | 2 +- .../unit_tests/test_nemotron_ultra_profile.py | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py index 1e32f862945..bffeb002afa 100644 --- a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py +++ b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py @@ -139,7 +139,7 @@ class ReadFileContinuationNoticeMiddleware(AgentMiddleware): @staticmethod def _is_numbered_read_file_row(row: str) -> bool: """Return whether `row` looks like a formatted `read_file` source line.""" - return re.match(r"^\s*\d+(?:\.\d+)?(?:\t|\s{2,})", row) is not None + return re.match(r"^\s*\d+(?:\t|\s{2,})", row) is not None @staticmethod def _annotate( diff --git a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py index d0d6dd9d64c..5d20fe40a06 100644 --- a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py +++ b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py @@ -135,6 +135,23 @@ def handler(request: ToolCallRequest) -> ToolMessage: # noqa: ARG001 assert "offset=12" in result.content +def test_read_file_continuation_notice_ignores_wrapped_rows() -> None: + """Wrapped chunks should not count toward the source-line limit.""" + middleware = ReadFileContinuationNoticeMiddleware() + content = " 1 first chunk\n1.1 second chunk\n1.2 third chunk" + + def handler(request: ToolCallRequest) -> ToolMessage: # noqa: ARG001 + return ToolMessage(content=content, tool_call_id="call_1") + + result = middleware.wrap_tool_call( + _request("read_file", {"file_path": "/x.txt", "limit": 2}), + handler, + ) + + assert isinstance(result, ToolMessage) + assert result.content == content + + def test_read_file_continuation_notice_uses_shim_default_limit() -> None: """The continuation notice should describe the same limit sent to `read_file`.""" shim = NemotronToolCallShim() From e65bd82fd2495c13f2837ca6c34fa9cc94d99f19 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Mon, 13 Jul 2026 17:14:52 -0400 Subject: [PATCH 6/9] cr --- libs/code/tests/unit_tests/test_agent.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/code/tests/unit_tests/test_agent.py b/libs/code/tests/unit_tests/test_agent.py index 4e9ab4bba6f..f7fbbab614f 100644 --- a/libs/code/tests/unit_tests/test_agent.py +++ b/libs/code/tests/unit_tests/test_agent.py @@ -3324,8 +3324,8 @@ def test_rubric_grader_read_tool_only_reads_large_results( runtime=runtime, ) - assert "1\tfirst" in allowed.content - assert "2\tsecond" in allowed.content + assert "1 first" in allowed.content + assert "2 second" in allowed.content assert "can only read" in denied def test_appends_interpreter_middleware_when_enabled(self, tmp_path: Path) -> None: From 71f708768584c2542e80770df6912a50123f1d83 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Mon, 13 Jul 2026 17:49:43 -0400 Subject: [PATCH 7/9] cr --- .../deepagents_code/tui/widgets/messages.py | 46 ++++++++------- .../unit_tests/tui/widgets/test_messages.py | 54 ++++++++++++++---- libs/deepagents/deepagents/backends/utils.py | 4 ++ .../harness/_nvidia_nemotron_3_ultra.py | 9 ++- .../smoke_tests/snapshots/README.md | 2 +- .../tests/unit_tests/test_middleware.py | 57 +++++++++++-------- .../unit_tests/test_nemotron_ultra_profile.py | 19 +++++++ 7 files changed, 132 insertions(+), 59 deletions(-) diff --git a/libs/code/deepagents_code/tui/widgets/messages.py b/libs/code/deepagents_code/tui/widgets/messages.py index 31927bcecec..5008a47f913 100644 --- a/libs/code/deepagents_code/tui/widgets/messages.py +++ b/libs/code/deepagents_code/tui/widgets/messages.py @@ -1983,17 +1983,18 @@ def _format_ls_output( # noqa: PLR6301 # Grouped as method for widget cohesion @staticmethod def _compact_line_gutter(output: str) -> str: - r"""Tighten `read_file`'s cat -n line-number gutter for display. - - The tool emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified - number plus a tab — so even single-digit line numbers carry five - leading spaces and the tab pushes content to a distant tab stop. The - model needs that raw format for edits, but the TUI renders a compact - gutter instead: numbers right-justified to the widest number actually - present, then two spaces, mirroring how grep/glob results sit flush - left. Source indentation after the gutter is preserved untouched. - - Lines that don't match the cat -n shape (e.g. test fixtures or + r"""Tighten `read_file`'s line-number gutter for display. + + `read_file` prefixes each row with a right-justified line marker — `N`, + or `N.M` for a wrapped-line continuation — then two spaces, then the + original source content. (Deprecated string backends may still emit the + older `cat -n` gutter: a wide right-justified number and a tab.) The + model needs the raw gutter for edits, but the TUI re-justifies markers + to the widest marker actually present, then two spaces, mirroring how + grep/glob results sit flush left. Source indentation after the gutter is + preserved untouched. + + Lines that don't match a gutter shape (e.g. test fixtures or non-numbered output) are passed through unchanged. Returns: @@ -2001,20 +2002,21 @@ def _compact_line_gutter(output: str) -> str: line-numbered content was found. """ lines = output.split("\n") - # Split each line on its gutter tab into (number, source). The gutter - # tab is always the first one; any tabs in `text` are real source - # indentation and stay put. The head must be a bare `N` or `N.M` (the - # latter is a wrapped-line continuation marker) — both sides of the dot - # are required, so a stray `.5` head marks a non-gutter line. + # Strip a leading gutter into (marker, source). The marker is a bare `N` + # or `N.M` (the latter a wrapped-line continuation) — both sides of the + # dot required, so a stray `.5` head is not a gutter. The separator is + # exactly two spaces (current format) or a single tab (legacy cat -n). + # Only the separator is consumed, and padding is spaces-only, so source + # indentation — including leading tabs — after the gutter stays put. + gutter = re.compile(r"^ *(\d+(?:\.\d+)?)(?: |\t)(.*)$") parsed: list[tuple[str, str] | None] = [] width = 0 for line in lines: - head, tab, text = line.partition("\t") - num = head.strip() - whole, dot, frac = num.partition(".") - if tab and whole.isdigit() and (not dot or frac.isdigit()): - parsed.append((num, text)) - width = max(width, len(num)) + match = gutter.match(line) + if match: + marker = match.group(1) + parsed.append((marker, match.group(2))) + width = max(width, len(marker)) else: parsed.append(None) diff --git a/libs/code/tests/unit_tests/tui/widgets/test_messages.py b/libs/code/tests/unit_tests/tui/widgets/test_messages.py index c0eca723801..fcb1b7d36ad 100644 --- a/libs/code/tests/unit_tests/tui/widgets/test_messages.py +++ b/libs/code/tests/unit_tests/tui/widgets/test_messages.py @@ -2794,14 +2794,14 @@ def test_format_file_output_preview_budget_hit_on_separator(self) -> None: assert result.truncation == "2 more lines" - def test_format_output_compacts_line_number_gutter(self) -> None: - r"""Line-number gutters are tightened, all rows aligned to one column. - - `read_file` emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified - number plus a tab — which renders far from the line numbers and (when - the first row's padding was stripped) misaligned. The TUI recomputes a - compact gutter: numbers right-justified to the widest number present, - two spaces, then the original source indentation. + def test_format_output_compacts_legacy_cat_n_gutter(self) -> None: + r"""Legacy `cat -n` gutters are tightened, all rows aligned to one column. + + Deprecated string backends still emit `f"{line_num:6d}\t{line}"` — a + 6-wide right-justified number plus a tab — which renders far from the + line numbers and (when the first row's padding was stripped) misaligned. + The TUI recomputes a compact gutter: numbers right-justified to the + widest number present, two spaces, then the original source indentation. """ msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) # cat -n style: 6-wide right-justified number + tab + source line. @@ -2812,6 +2812,23 @@ def test_format_output_compacts_line_number_gutter(self) -> None: # indentation (the 4 spaces on line 3) preserved verbatim. assert result.content.plain == '1 """doc"""\n2 \n3 indented' + def test_format_output_leaves_current_two_space_gutter_intact(self) -> None: + r"""The current SDK gutter is already compact, so compaction is a no-op. + + `read_file` now emits `f"{marker:>width} {line}"` — a right-justified + marker, two spaces, then source. Re-justifying to the widest marker + reproduces the same string, and crucially a tab-indented source line + keeps its leading tab (the two-space separator, not the source tab, is + consumed). Regression guard: the old tab-splitting gutter dropped that + indentation, re-introducing the ambiguity this format fixes. + """ + msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) + # Two-digit max marker => width 2; line 2 is tab-indented source. + output = " 9 def build_config():\n10 \treturn {}" + result = msg._format_output(output, is_preview=False) + + assert result.content.plain == " 9 def build_config():\n10 \treturn {}" + def test_compact_line_gutter_right_justifies_to_widest_number(self) -> None: r"""Multi-digit line numbers set a uniform, right-justified gutter.""" # Lines 9 and 10: single- vs double-digit numbers must align right. @@ -2832,17 +2849,30 @@ def test_compact_line_gutter_handles_continuation_markers(self) -> None: assert compacted == " 1 first\n1.1 wrapped" - def test_compact_line_gutter_preserves_source_tabs(self) -> None: - r"""Only the first (gutter) tab is consumed; source tabs stay put. + def test_compact_line_gutter_preserves_source_tabs_legacy(self) -> None: + r"""Only the gutter tab is consumed; a legacy row's source tab stays put. - Tab-indented source means a tab immediately after the gutter tab. - `partition` splits on the first tab only, so the source tab survives. + Tab-indented source means a tab immediately after the gutter tab. The + gutter regex consumes only the separator, so the source tab survives. """ output = " 1\t\tdef foo():" compacted = ToolCallMessage._compact_line_gutter(output) assert compacted == "1 \tdef foo():" + def test_compact_line_gutter_preserves_source_tabs_current(self) -> None: + r"""A current-format row's leading source tab survives compaction. + + The current gutter separator is two spaces, so a tab-indented source + line reads as `"N \tsource"`. Only the two spaces are consumed; the + source tab must remain. This is the regression guard for the tab- + splitting gutter that used to drop it. + """ + output = "1 def foo():\n2 \treturn 1" + compacted = ToolCallMessage._compact_line_gutter(output) + + assert compacted == "1 def foo():\n2 \treturn 1" + def test_compact_line_gutter_passes_through_non_numbered(self) -> None: """Output without a cat -n gutter is returned unchanged.""" output = "plain text\nno line numbers here" diff --git a/libs/deepagents/deepagents/backends/utils.py b/libs/deepagents/deepagents/backends/utils.py index 7490ce915cf..50f95276cce 100644 --- a/libs/deepagents/deepagents/backends/utils.py +++ b/libs/deepagents/deepagents/backends/utils.py @@ -241,6 +241,10 @@ def format_content_with_line_numbers( rows.append((marker, chunk)) marker_width = max(marker_width, len(marker)) + # The two-space marker/source separator is a load-bearing contract: + # `ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row` counts + # source rows by matching it. Changing the separator here without updating + # that regex silently breaks the continuation notice. return "\n".join(f"{marker:>{marker_width}} {line}" for marker, line in rows) diff --git a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py index bffeb002afa..773cf9c8f89 100644 --- a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py +++ b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py @@ -138,7 +138,14 @@ class ReadFileContinuationNoticeMiddleware(AgentMiddleware): @staticmethod def _is_numbered_read_file_row(row: str) -> bool: - """Return whether `row` looks like a formatted `read_file` source line.""" + """Return whether `row` looks like a formatted `read_file` source line. + + Matches a primary source marker (`N`) followed by the current two-space + separator (`format_content_with_line_numbers`) or the legacy `cat -n` + tab. Continuation rows (`N.M`) fail — the `.` follows the digits, so + they are not counted toward the source-line limit. Kept in sync with the + separator emitted by `format_content_with_line_numbers`. + """ return re.match(r"^\s*\d+(?:\t|\s{2,})", row) is not None @staticmethod diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md index 48dac9f20c5..9efdfcafcf5 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md @@ -12,7 +12,7 @@ Use focused snapshots for individual prompt/tool features, and add combination s | --- | --- | --- | | `system_prompt_with_execute.md` | Yes | Full system prompt for a local shell backend. | | `system_prompt_with_execute_tools.json` | Yes | Tool schemas for the local shell backend, including `execute`. | -| `system_prompt_with_media_extra_tools.json` | Yes | Tool schemas when the optional media/video extra is enabled; this mainly covers the video-aware `read_file` description and schema. | +| `system_prompt_with_media_extra_tools.json` | Yes | Tool schemas when the optional `[video]` extra is enabled; this mainly covers the video-aware `read_file` description and schema. | | `system_prompt_without_execute.md` | No | Full system prompt for a filesystem-only backend. | | `system_prompt_without_execute_tools.json` | No | Tool schemas for the filesystem-only backend, without `execute`. | | `custom_system_message.md` | No | Full prompt when the caller passes a custom `system_prompt`. | diff --git a/libs/deepagents/tests/unit_tests/test_middleware.py b/libs/deepagents/tests/unit_tests/test_middleware.py index 4e2f1c0c87c..622821d61d4 100644 --- a/libs/deepagents/tests/unit_tests/test_middleware.py +++ b/libs/deepagents/tests/unit_tests/test_middleware.py @@ -1264,6 +1264,17 @@ def test_format_content_with_line_numbers_empty_and_single(self): assert format_content_with_line_numbers([]) == "" assert format_content_with_line_numbers(["only"]) == "1 only" + def test_format_content_with_line_numbers_blank_line_in_middle(self): + """A blank source line keeps its own gutter row, ending at the separator. + + The row is `marker + " "` with empty content — trailing whitespace that + a careless refactor could strip or drop entirely. Exact equality guards + the row's presence and shape. + """ + result = format_content_with_line_numbers(["code", "", "more"], start_line=1) + + assert result.split("\n") == ["1 code", "2 ", "3 more"] + def test_format_content_with_line_numbers_aligns_across_magnitude(self): """Markers right-justify to a shared width when line counts cross 9->10. @@ -1320,18 +1331,18 @@ def test_format_content_with_line_numbers_long_line_with_continuation(self): lines = result.split("\n") assert len(lines) == 7 # 1 short + 5 continuation (2, 2.1, 2.2, 2.3, 2.4) + 1 short - assert " 1 short line" in lines[0] - assert " 2 " in lines[1] + assert lines[0] == " 1 short line" + assert lines[1].startswith(" 2 ") assert lines[1].count("a") == 5000 - assert "2.1 " in lines[2] + assert lines[2].startswith("2.1 ") assert lines[2].count("a") == 5000 - assert "2.2 " in lines[3] + assert lines[3].startswith("2.2 ") assert lines[3].count("a") == 5000 - assert "2.3 " in lines[4] + assert lines[4].startswith("2.3 ") assert lines[4].count("a") == 5000 - assert "2.4 " in lines[5] + assert lines[5].startswith("2.4 ") assert lines[5].count("a") == 5000 - assert " 3 another short line" in lines[6] + assert lines[6] == " 3 another short line" def test_format_content_with_line_numbers_multiple_long_lines(self): """Test multiple long lines in sequence with proper line numbering.""" @@ -1341,18 +1352,18 @@ def test_format_content_with_line_numbers_multiple_long_lines(self): result = format_content_with_line_numbers(content, start_line=5) lines = result.split("\n") assert len(lines) == 7 # 3 (line 5, 5.1, 5.2) + 1 middle + 3 (line 7, 7.1, 7.2) - assert " 5 " in lines[0] + assert lines[0].startswith(" 5 ") assert lines[0].count("x") == 5000 - assert "5.1 " in lines[1] + assert lines[1].startswith("5.1 ") assert lines[1].count("x") == 5000 - assert "5.2 " in lines[2] + assert lines[2].startswith("5.2 ") assert lines[2].count("x") == 5000 - assert " 6 middle" in lines[3] - assert " 7 " in lines[4] + assert lines[3] == " 6 middle" + assert lines[4].startswith(" 7 ") assert lines[4].count("y") == 5000 - assert "7.1 " in lines[5] + assert lines[5].startswith("7.1 ") assert lines[5].count("y") == 5000 - assert "7.2 " in lines[6] + assert lines[6].startswith("7.2 ") assert lines[6].count("y") == 5000 def test_format_content_with_line_numbers_exact_limit(self): @@ -1376,14 +1387,14 @@ def test_read_file_with_long_lines_shows_continuation_markers(self): result = format_content_with_line_numbers(sliced, start_line=1) lines = result.split("\n") assert len(lines) == 5 # 1 first + 3 continuation (2, 2.1, 2.2) + 1 third - assert " 1 first line" in lines[0] - assert " 2 " in lines[1] + assert lines[0] == " 1 first line" + assert lines[1].startswith(" 2 ") assert lines[1].count("z") == 5000 - assert "2.1 " in lines[2] + assert lines[2].startswith("2.1 ") assert lines[2].count("z") == 5000 - assert "2.2 " in lines[3] + assert lines[3].startswith("2.2 ") assert lines[3].count("z") == 5000 - assert " 3 third line" in lines[4] + assert lines[4] == " 3 third line" def test_read_file_with_offset_and_long_lines(self): """Test that read_file with offset handles long lines correctly.""" @@ -1395,13 +1406,13 @@ def test_read_file_with_offset_and_long_lines(self): result = format_content_with_line_numbers(sliced, start_line=3) lines = result.split("\n") assert len(lines) == 4 # 3 continuation (3, 3.1, 3.2) + 1 line4 - assert " 3 " in lines[0] + assert lines[0].startswith(" 3 ") assert lines[0].count("m") == 5000 - assert "3.1 " in lines[1] + assert lines[1].startswith("3.1 ") assert lines[1].count("m") == 5000 - assert "3.2 " in lines[2] + assert lines[2].startswith("3.2 ") assert lines[2].count("m") == 2000 - assert " 4 line4" in lines[3] + assert lines[3] == " 4 line4" def test_intercept_short_toolmessage(self): """Test that small ToolMessages pass through unchanged.""" diff --git a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py index 5d20fe40a06..59cb474a910 100644 --- a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py +++ b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py @@ -152,6 +152,25 @@ def handler(request: ToolCallRequest) -> ToolMessage: # noqa: ARG001 assert result.content == content +def test_is_numbered_read_file_row_contract() -> None: + """Pin which rows count as source lines for the continuation heuristic. + + Primary markers with the current two-space separator or the legacy `cat -n` + tab count; padded markers count; continuation (`N.M`) rows and plain text do + not. Kept in sync with `format_content_with_line_numbers`' separator. + """ + is_row = ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row + + # Source rows: current two-space, right-justify padding, and legacy tab. + assert is_row("1 source") + assert is_row(" 10 source") + assert is_row("1\tsource") + # Continuation rows and non-gutter text are not source lines. + assert not is_row("1.1 wrapped") + assert not is_row("plain text with no gutter") + assert not is_row("") + + def test_read_file_continuation_notice_uses_shim_default_limit() -> None: """The continuation notice should describe the same limit sent to `read_file`.""" shim = NemotronToolCallShim() From 0b8dfe281e79d00f84e92a210ec06d66da2c23a0 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Mon, 13 Jul 2026 23:23:49 -0400 Subject: [PATCH 8/9] cr --- .../deepagents_code/tui/widgets/messages.py | 32 +++++++++------ .../unit_tests/tui/widgets/test_messages.py | 20 +++++++++- .../deepagents/backends/protocol.py | 17 ++++---- libs/deepagents/deepagents/backends/utils.py | 39 ++++++++++--------- .../deepagents/middleware/filesystem.py | 2 +- .../harness/_nvidia_nemotron_3_ultra.py | 17 ++++---- .../custom_system_message_tools.json | 2 +- .../system_prompt_with_execute_tools.json | 2 +- .../system_prompt_with_media_extra_tools.json | 2 +- ...m_prompt_with_memory_and_skills_tools.json | 2 +- ...stem_prompt_with_routed_backend_tools.json | 2 +- ...t_with_sync_and_async_subagents_tools.json | 2 +- .../system_prompt_without_execute_tools.json | 2 +- .../tests/unit_tests/test_end_to_end.py | 6 +-- .../unit_tests/test_nemotron_ultra_profile.py | 30 +++++++++++++- 15 files changed, 118 insertions(+), 59 deletions(-) diff --git a/libs/code/deepagents_code/tui/widgets/messages.py b/libs/code/deepagents_code/tui/widgets/messages.py index 156102482e1..b633c07fb3b 100644 --- a/libs/code/deepagents_code/tui/widgets/messages.py +++ b/libs/code/deepagents_code/tui/widgets/messages.py @@ -158,6 +158,19 @@ class FormattedOutput: """Strip the SDK's `[Command succeeded with exit code 0]` trailer from tool output.""" +_READ_FILE_GUTTER_RE = re.compile(r"^ *(\d+(?:\.\d+)?)(?: |\t)(.*)$") +"""Match a `read_file` gutter row into (marker, source). + +The marker is a bare `N` or `N.M` (the latter a wrapped-line continuation) — +both sides of the dot required, so a stray `.5` head is not a gutter. The +separator is exactly two spaces (current format) or a single tab (legacy +`cat -n`). Only the separator is consumed and leading padding is spaces-only, so +source indentation — including leading tabs — after the gutter stays put. Kept in +sync with the separator emitted by deepagents' `format_content_with_line_numbers` +(the authoritative producer). See `ToolCallMessage._compact_line_gutter`. +""" + + def _strip_success_exit_line(text: str) -> str: """Remove the `[Command succeeded with exit code 0]` trailer. @@ -1994,28 +2007,23 @@ def _compact_line_gutter(output: str) -> str: grep/glob results sit flush left. Source indentation after the gutter is preserved untouched. - Lines that don't match a gutter shape (e.g. test fixtures or - non-numbered output) are passed through unchanged. + The gutter shape is `_READ_FILE_GUTTER_RE`, kept in sync with deepagents' + `format_content_with_line_numbers` (the authoritative producer). Lines + that don't match a gutter shape (e.g. test fixtures or non-numbered + output) are passed through unchanged. Returns: The output with compacted gutters, or the original string if no line-numbered content was found. """ lines = output.split("\n") - # Strip a leading gutter into (marker, source). The marker is a bare `N` - # or `N.M` (the latter a wrapped-line continuation) — both sides of the - # dot required, so a stray `.5` head is not a gutter. The separator is - # exactly two spaces (current format) or a single tab (legacy cat -n). - # Only the separator is consumed, and padding is spaces-only, so source - # indentation — including leading tabs — after the gutter stays put. - gutter = re.compile(r"^ *(\d+(?:\.\d+)?)(?: |\t)(.*)$") parsed: list[tuple[str, str] | None] = [] width = 0 for line in lines: - match = gutter.match(line) + match = _READ_FILE_GUTTER_RE.match(line) if match: - marker = match.group(1) - parsed.append((marker, match.group(2))) + marker, source = match.groups() + parsed.append((marker, source)) width = max(width, len(marker)) else: parsed.append(None) diff --git a/libs/code/tests/unit_tests/tui/widgets/test_messages.py b/libs/code/tests/unit_tests/tui/widgets/test_messages.py index fcb1b7d36ad..0d530ec6d6e 100644 --- a/libs/code/tests/unit_tests/tui/widgets/test_messages.py +++ b/libs/code/tests/unit_tests/tui/widgets/test_messages.py @@ -6,6 +6,7 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from deepagents.backends.utils import format_content_with_line_numbers from rich.style import Style from textual.app import App, ComposeResult from textual.content import Content @@ -2873,8 +2874,25 @@ def test_compact_line_gutter_preserves_source_tabs_current(self) -> None: assert compacted == "1 def foo():\n2 \treturn 1" + def test_compact_line_gutter_parses_real_producer_output(self) -> None: + r"""Round-trip guard against producer/consumer separator drift. + + Feeds real `format_content_with_line_numbers` output (the authoritative + producer, in the deepagents package) through the TUI parser. If the + producer separator ever changes without this parser following, the exact + assertion fails in CI instead of the gutter silently failing to compact + (or, on a widened separator, leaking a phantom space into every source + line). Line 2 is tab-indented source — the ambiguity this format fixes. + """ + output = format_content_with_line_numbers( + ["def f():", "\treturn 1"], start_line=1 + ) + compacted = ToolCallMessage._compact_line_gutter(output) + + assert compacted == "1 def f():\n2 \treturn 1" + def test_compact_line_gutter_passes_through_non_numbered(self) -> None: - """Output without a cat -n gutter is returned unchanged.""" + """Output without a gutter is returned unchanged.""" output = "plain text\nno line numbers here" assert ToolCallMessage._compact_line_gutter(output) == output diff --git a/libs/deepagents/deepagents/backends/protocol.py b/libs/deepagents/deepagents/backends/protocol.py index efa6c4da52e..6d6123cbeec 100644 --- a/libs/deepagents/deepagents/backends/protocol.py +++ b/libs/deepagents/deepagents/backends/protocol.py @@ -436,7 +436,7 @@ def read( offset: int = 0, limit: int = 2000, ) -> ReadResult: - """Read file content with line numbers. + """Read file content for the requested line range. Args: file_path: Absolute path to the file to read. Must start with `'/'`. @@ -444,13 +444,14 @@ def read( limit: Maximum number of lines to read. Returns: - String containing file content formatted with line numbers, - starting at `offset + 1`. - - Lines longer than 5000 characters are split into multiple rows - with continuation markers (e.g., `5.1`, `5.2`). - - Returns an error string if the file doesn't exist or can't be read. + `ReadResult` with raw (unformatted) content for the requested window, + or an error if the file doesn't exist or can't be read. + + Line-number formatting is applied downstream by the filesystem + middleware (`format_content_with_line_numbers`), not by backends: + it adds the gutter, starts numbering at `offset + 1`, and splits + lines longer than 5000 characters into continuation rows + (e.g., `5.1`, `5.2`). """ raise NotImplementedError diff --git a/libs/deepagents/deepagents/backends/utils.py b/libs/deepagents/deepagents/backends/utils.py index 5dbb17dfb71..966d8150c70 100644 --- a/libs/deepagents/deepagents/backends/utils.py +++ b/libs/deepagents/deepagents/backends/utils.py @@ -226,25 +226,28 @@ def format_content_with_line_numbers( marker_width = 0 for i, line in enumerate(lines): line_num = i + start_line - - if len(line) <= MAX_LINE_LENGTH: - marker = str(line_num) - rows.append((marker, line)) + # One slice per MAX_LINE_LENGTH chunk; short lines yield a single chunk. + # `or [line]` keeps a row for a blank line, whose empty range would + # otherwise drop it, so it still gets a gutter. + chunks = [line[s : s + MAX_LINE_LENGTH] for s in range(0, len(line), MAX_LINE_LENGTH)] or [line] + + for chunk_idx, chunk in enumerate(chunks): + marker = str(line_num) if chunk_idx == 0 else f"{line_num}.{chunk_idx}" + rows.append((marker, chunk)) marker_width = max(marker_width, len(marker)) - else: - num_chunks = (len(line) + MAX_LINE_LENGTH - 1) // MAX_LINE_LENGTH - for chunk_idx in range(num_chunks): - start = chunk_idx * MAX_LINE_LENGTH - end = min(start + MAX_LINE_LENGTH, len(line)) - chunk = line[start:end] - marker = str(line_num) if chunk_idx == 0 else f"{line_num}.{chunk_idx}" - rows.append((marker, chunk)) - marker_width = max(marker_width, len(marker)) - - # The two-space marker/source separator is a load-bearing contract: - # `ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row` counts - # source rows by matching it. Changing the separator here without updating - # that regex silently breaks the continuation notice. + + # The two-space marker/source separator is a load-bearing contract shared by + # two downstream parsers that must stay in sync with the separator emitted + # here: + # - `ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row` + # (profiles/harness/_nvidia_nemotron_3_ultra.py) counts source rows to + # decide whether to append the continuation notice. + # - `ToolCallMessage._compact_line_gutter` (the deepagents-code TUI, in a + # separate package: libs/code/.../tui/widgets/messages.py) re-justifies + # the gutter for display. + # Both also tolerate the legacy `cat -n` tab. Shrinking this separator below + # two spaces (or otherwise diverging) would silently break them; the + # producer->consumer round-trip tests in both packages guard against that. return "\n".join(f"{marker:>{marker_width}} {line}" for marker, line in rows) diff --git a/libs/deepagents/deepagents/middleware/filesystem.py b/libs/deepagents/deepagents/middleware/filesystem.py index 6651feab6d7..2d53bf7706a 100644 --- a/libs/deepagents/deepagents/middleware/filesystem.py +++ b/libs/deepagents/deepagents/middleware/filesystem.py @@ -774,7 +774,7 @@ class ExecuteSchema(BaseModel): - Read more sections: read_file(file_path="...", offset=100, limit=200) for next 200 lines - Omit `limit` to use the default window; increase it only when necessary for editing - Specify offset and limit: read_file(file_path="...", offset=0, limit=100) reads first 100 lines -- Results are returned with line numbers starting at 1, followed by two spaces and the source content +- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content - Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget. - You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful. - If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents. diff --git a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py index 773cf9c8f89..fb51ca58c04 100644 --- a/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py +++ b/libs/deepagents/deepagents/profiles/harness/_nvidia_nemotron_3_ultra.py @@ -140,13 +140,15 @@ class ReadFileContinuationNoticeMiddleware(AgentMiddleware): def _is_numbered_read_file_row(row: str) -> bool: """Return whether `row` looks like a formatted `read_file` source line. - Matches a primary source marker (`N`) followed by the current two-space - separator (`format_content_with_line_numbers`) or the legacy `cat -n` - tab. Continuation rows (`N.M`) fail — the `.` follows the digits, so - they are not counted toward the source-line limit. Kept in sync with the - separator emitted by `format_content_with_line_numbers`. + Matches a primary source marker (`N`), optional spaces-only right-justify + padding in front of it, then the current two-space separator (emitted by + `format_content_with_line_numbers`) or the legacy `cat -n` tab. + Continuation rows (`N.M`) fail — the `.` follows the digits, so they are + not counted toward the source-line limit. The separator clause is matched + exactly (two spaces or a tab), in lockstep with the producer and with the + TUI `_compact_line_gutter` parser. """ - return re.match(r"^\s*\d+(?:\t|\s{2,})", row) is not None + return re.match(r"^ *\d+(?: |\t)", row) is not None @staticmethod def _annotate( @@ -171,7 +173,8 @@ def _annotate( except (TypeError, ValueError): limit = _DEFAULT_READ_LIMIT - n_lines = sum(1 for row in content.split("\n") if ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row(row)) + is_source_row = ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row + n_lines = sum(1 for row in content.split("\n") if is_source_row(row)) if n_lines < limit: return result diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json index d3bca4e9c18..c4cf550494c 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/custom_system_message_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json index 11954ce6271..5be76833848 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_execute_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json index 9ef7dcd2c4f..258a939925d 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_media_extra_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- For text files, by default it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- For videos, `offset`/`limit` are interpreted as seconds (default window 100 s; sampled at a fixed rate). Use smaller windows when you need more temporal detail.\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json index d3bca4e9c18..c4cf550494c 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_memory_and_skills_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json index 11954ce6271..5be76833848 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_routed_backend_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json index 18e6ddfedfe..da3067543f0 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_with_sync_and_async_subagents_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json index d3bca4e9c18..c4cf550494c 100644 --- a/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json +++ b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/system_prompt_without_execute_tools.json @@ -59,7 +59,7 @@ }, { "function": { - "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at 1, followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", + "description": "Reads a file from the filesystem.\n\nAssume this tool is able to read all files. If the User provides a path to a file assume that path is valid. It is okay to read a file that does not exist; an error will be returned.\n\nUsage:\n- By default, it reads up to 100 lines starting from the beginning of the file\n- **IMPORTANT for large files and codebase exploration**: Use pagination with offset and limit parameters to avoid context overflow\n - First scan: read_file(file_path=\"...\", limit=100) to see file structure\n - Read more sections: read_file(file_path=\"...\", offset=100, limit=200) for next 200 lines\n - Omit `limit` to use the default window; increase it only when necessary for editing\n- Specify offset and limit: read_file(file_path=\"...\", offset=0, limit=100) reads first 100 lines\n- Results are returned with line numbers starting at the first line read (`offset` + 1, so 1 by default), followed by two spaces and the source content\n- Lines longer than 5,000 characters will be split into multiple lines with continuation markers (e.g., 5.1, 5.2, etc.). `limit` applies to source lines, so continuation rows do not consume the budget.\n- You have the capability to call multiple tools in a single response. It is always better to speculatively read multiple files as a batch that are potentially useful.\n- If you read a file that exists but has empty contents you will receive a system reminder warning in place of file contents.\n- Image files (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`, etc.), audio and video files, and PDFs are returned as multimodal content blocks (see https://docs.langchain.com/oss/python/langchain/messages#multimodal).\n\nFor multimodal reads (image, audio, video, PDF, etc.):\n- Use `read_file(file_path=...)`\n- For images and PDFs, pagination via `offset`/`limit` is text-only - supply `file_path` only\n- If file details were compacted from history, call `read_file` again on the same path\n\n- You should ALWAYS make sure a file has been read before editing it.", "name": "read_file", "parameters": { "properties": { diff --git a/libs/deepagents/tests/unit_tests/test_end_to_end.py b/libs/deepagents/tests/unit_tests/test_end_to_end.py index 56c74487368..1c7d6401364 100644 --- a/libs/deepagents/tests/unit_tests/test_end_to_end.py +++ b/libs/deepagents/tests/unit_tests/test_end_to_end.py @@ -1310,9 +1310,9 @@ def test_deep_agent_read_file_pagination_does_not_skip_wrapped_lines(self, tmp_p combined = tool_messages[0].content + tool_messages[1].content assert "important instruction" in combined assert "line4" in combined - # All three continuation chunks of the wrapped line 2 must render in - # order, before `important instruction`, with nothing dropped at the - # page boundary. + # The primary row and both continuation chunks of the wrapped line 2 + # must render in order, before `important instruction`, with nothing + # dropped at the page boundary. for marker in (" 2 ", "2.1 ", "2.2 "): assert marker in combined, f"missing continuation marker {marker!r}" idx_first = combined.index(" 2 ") diff --git a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py index 59cb474a910..17388273761 100644 --- a/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py +++ b/libs/deepagents/tests/unit_tests/test_nemotron_ultra_profile.py @@ -9,6 +9,7 @@ from langchain.tools import ToolRuntime from langchain_core.messages import AIMessage, HumanMessage, ToolMessage +from deepagents.backends.utils import format_content_with_line_numbers from deepagents.profiles.harness._nvidia_nemotron_3_ultra import ( _DEFAULT_READ_LIMIT, _EMPTY_TOOL_PLACEHOLDER, @@ -123,7 +124,7 @@ def test_read_file_continuation_notice_marks_exact_limit_results() -> None: middleware = ReadFileContinuationNoticeMiddleware() def handler(request: ToolCallRequest) -> ToolMessage: # noqa: ARG001 - return ToolMessage(content="1\talpha\n2\tbeta\n3\tgamma", tool_call_id="call_1") + return ToolMessage(content="1 alpha\n2 beta\n3 gamma", tool_call_id="call_1") result = middleware.wrap_tool_call( _request("read_file", {"file_path": "/x.txt", "limit": 3, "offset": 9}), @@ -165,12 +166,37 @@ def test_is_numbered_read_file_row_contract() -> None: assert is_row("1 source") assert is_row(" 10 source") assert is_row("1\tsource") - # Continuation rows and non-gutter text are not source lines. + # A single space is not the separator: guards against the regex loosening + # back to `\s+`/`\s{2,}`, which would count malformed rows. + assert not is_row("1 source") + # Continuation rows (unpadded and padded) and non-gutter text are not source + # lines. assert not is_row("1.1 wrapped") + assert not is_row(" 5.1 wrapped") assert not is_row("plain text with no gutter") assert not is_row("") +def test_is_numbered_read_file_row_matches_real_producer_output() -> None: + """Round-trip guard: the nemotron heuristic must count real producer output. + + Feeds actual `format_content_with_line_numbers` output (short lines plus a + wrapped long line) through `_is_numbered_read_file_row`. If the producer + separator ever changes without this heuristic following, the count breaks + here in CI instead of silently disabling the continuation notice in + production. The two consumers hardcode fixtures elsewhere; only this test + connects producer to consumer. + """ + is_row = ReadFileContinuationNoticeMiddleware._is_numbered_read_file_row + # Source lines 1-3 are short; line 4 wraps into three chunks (4, 4.1, 4.2). + content = format_content_with_line_numbers(["a", "b", "c", "z" * (2 * 5000 + 1)], start_line=1) + rows = content.split("\n") + + # Exactly the four primary source markers count; the two continuation rows + # (4.1, 4.2) do not. + assert sum(1 for row in rows if is_row(row)) == 4 + + def test_read_file_continuation_notice_uses_shim_default_limit() -> None: """The continuation notice should describe the same limit sent to `read_file`.""" shim = NemotronToolCallShim() From 5f14586fcdc30a8a765ebd9e180da4daf39ab0d5 Mon Sep 17 00:00:00 2001 From: Mason Daugherty Date: Mon, 13 Jul 2026 23:33:52 -0400 Subject: [PATCH 9/9] chore(code): remove dcode TUI changes from SDK PR --- .../deepagents_code/tui/widgets/messages.py | 56 ++++++--------- .../unit_tests/tui/widgets/test_messages.py | 72 ++++--------------- 2 files changed, 35 insertions(+), 93 deletions(-) diff --git a/libs/code/deepagents_code/tui/widgets/messages.py b/libs/code/deepagents_code/tui/widgets/messages.py index b633c07fb3b..895a864afaf 100644 --- a/libs/code/deepagents_code/tui/widgets/messages.py +++ b/libs/code/deepagents_code/tui/widgets/messages.py @@ -158,19 +158,6 @@ class FormattedOutput: """Strip the SDK's `[Command succeeded with exit code 0]` trailer from tool output.""" -_READ_FILE_GUTTER_RE = re.compile(r"^ *(\d+(?:\.\d+)?)(?: |\t)(.*)$") -"""Match a `read_file` gutter row into (marker, source). - -The marker is a bare `N` or `N.M` (the latter a wrapped-line continuation) — -both sides of the dot required, so a stray `.5` head is not a gutter. The -separator is exactly two spaces (current format) or a single tab (legacy -`cat -n`). Only the separator is consumed and leading padding is spaces-only, so -source indentation — including leading tabs — after the gutter stays put. Kept in -sync with the separator emitted by deepagents' `format_content_with_line_numbers` -(the authoritative producer). See `ToolCallMessage._compact_line_gutter`. -""" - - def _strip_success_exit_line(text: str) -> str: """Remove the `[Command succeeded with exit code 0]` trailer. @@ -1996,35 +1983,38 @@ def _format_ls_output( # noqa: PLR6301 # Grouped as method for widget cohesion @staticmethod def _compact_line_gutter(output: str) -> str: - r"""Tighten `read_file`'s line-number gutter for display. - - `read_file` prefixes each row with a right-justified line marker — `N`, - or `N.M` for a wrapped-line continuation — then two spaces, then the - original source content. (Deprecated string backends may still emit the - older `cat -n` gutter: a wide right-justified number and a tab.) The - model needs the raw gutter for edits, but the TUI re-justifies markers - to the widest marker actually present, then two spaces, mirroring how - grep/glob results sit flush left. Source indentation after the gutter is - preserved untouched. - - The gutter shape is `_READ_FILE_GUTTER_RE`, kept in sync with deepagents' - `format_content_with_line_numbers` (the authoritative producer). Lines - that don't match a gutter shape (e.g. test fixtures or non-numbered - output) are passed through unchanged. + r"""Tighten `read_file`'s cat -n line-number gutter for display. + + The tool emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified + number plus a tab — so even single-digit line numbers carry five + leading spaces and the tab pushes content to a distant tab stop. The + model needs that raw format for edits, but the TUI renders a compact + gutter instead: numbers right-justified to the widest number actually + present, then two spaces, mirroring how grep/glob results sit flush + left. Source indentation after the gutter is preserved untouched. + + Lines that don't match the cat -n shape (e.g. test fixtures or + non-numbered output) are passed through unchanged. Returns: The output with compacted gutters, or the original string if no line-numbered content was found. """ lines = output.split("\n") + # Split each line on its gutter tab into (number, source). The gutter + # tab is always the first one; any tabs in `text` are real source + # indentation and stay put. The head must be a bare `N` or `N.M` (the + # latter is a wrapped-line continuation marker) — both sides of the dot + # are required, so a stray `.5` head marks a non-gutter line. parsed: list[tuple[str, str] | None] = [] width = 0 for line in lines: - match = _READ_FILE_GUTTER_RE.match(line) - if match: - marker, source = match.groups() - parsed.append((marker, source)) - width = max(width, len(marker)) + head, tab, text = line.partition("\t") + num = head.strip() + whole, dot, frac = num.partition(".") + if tab and whole.isdigit() and (not dot or frac.isdigit()): + parsed.append((num, text)) + width = max(width, len(num)) else: parsed.append(None) diff --git a/libs/code/tests/unit_tests/tui/widgets/test_messages.py b/libs/code/tests/unit_tests/tui/widgets/test_messages.py index 0d530ec6d6e..c0eca723801 100644 --- a/libs/code/tests/unit_tests/tui/widgets/test_messages.py +++ b/libs/code/tests/unit_tests/tui/widgets/test_messages.py @@ -6,7 +6,6 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest -from deepagents.backends.utils import format_content_with_line_numbers from rich.style import Style from textual.app import App, ComposeResult from textual.content import Content @@ -2795,14 +2794,14 @@ def test_format_file_output_preview_budget_hit_on_separator(self) -> None: assert result.truncation == "2 more lines" - def test_format_output_compacts_legacy_cat_n_gutter(self) -> None: - r"""Legacy `cat -n` gutters are tightened, all rows aligned to one column. + def test_format_output_compacts_line_number_gutter(self) -> None: + r"""Line-number gutters are tightened, all rows aligned to one column. - Deprecated string backends still emit `f"{line_num:6d}\t{line}"` — a - 6-wide right-justified number plus a tab — which renders far from the - line numbers and (when the first row's padding was stripped) misaligned. - The TUI recomputes a compact gutter: numbers right-justified to the - widest number present, two spaces, then the original source indentation. + `read_file` emits `f"{line_num:6d}\t{line}"` — a 6-wide right-justified + number plus a tab — which renders far from the line numbers and (when + the first row's padding was stripped) misaligned. The TUI recomputes a + compact gutter: numbers right-justified to the widest number present, + two spaces, then the original source indentation. """ msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) # cat -n style: 6-wide right-justified number + tab + source line. @@ -2813,23 +2812,6 @@ def test_format_output_compacts_legacy_cat_n_gutter(self) -> None: # indentation (the 4 spaces on line 3) preserved verbatim. assert result.content.plain == '1 """doc"""\n2 \n3 indented' - def test_format_output_leaves_current_two_space_gutter_intact(self) -> None: - r"""The current SDK gutter is already compact, so compaction is a no-op. - - `read_file` now emits `f"{marker:>width} {line}"` — a right-justified - marker, two spaces, then source. Re-justifying to the widest marker - reproduces the same string, and crucially a tab-indented source line - keeps its leading tab (the two-space separator, not the source tab, is - consumed). Regression guard: the old tab-splitting gutter dropped that - indentation, re-introducing the ambiguity this format fixes. - """ - msg = ToolCallMessage("read_file", {"path": "/tmp/a.py"}) - # Two-digit max marker => width 2; line 2 is tab-indented source. - output = " 9 def build_config():\n10 \treturn {}" - result = msg._format_output(output, is_preview=False) - - assert result.content.plain == " 9 def build_config():\n10 \treturn {}" - def test_compact_line_gutter_right_justifies_to_widest_number(self) -> None: r"""Multi-digit line numbers set a uniform, right-justified gutter.""" # Lines 9 and 10: single- vs double-digit numbers must align right. @@ -2850,49 +2832,19 @@ def test_compact_line_gutter_handles_continuation_markers(self) -> None: assert compacted == " 1 first\n1.1 wrapped" - def test_compact_line_gutter_preserves_source_tabs_legacy(self) -> None: - r"""Only the gutter tab is consumed; a legacy row's source tab stays put. + def test_compact_line_gutter_preserves_source_tabs(self) -> None: + r"""Only the first (gutter) tab is consumed; source tabs stay put. - Tab-indented source means a tab immediately after the gutter tab. The - gutter regex consumes only the separator, so the source tab survives. + Tab-indented source means a tab immediately after the gutter tab. + `partition` splits on the first tab only, so the source tab survives. """ output = " 1\t\tdef foo():" compacted = ToolCallMessage._compact_line_gutter(output) assert compacted == "1 \tdef foo():" - def test_compact_line_gutter_preserves_source_tabs_current(self) -> None: - r"""A current-format row's leading source tab survives compaction. - - The current gutter separator is two spaces, so a tab-indented source - line reads as `"N \tsource"`. Only the two spaces are consumed; the - source tab must remain. This is the regression guard for the tab- - splitting gutter that used to drop it. - """ - output = "1 def foo():\n2 \treturn 1" - compacted = ToolCallMessage._compact_line_gutter(output) - - assert compacted == "1 def foo():\n2 \treturn 1" - - def test_compact_line_gutter_parses_real_producer_output(self) -> None: - r"""Round-trip guard against producer/consumer separator drift. - - Feeds real `format_content_with_line_numbers` output (the authoritative - producer, in the deepagents package) through the TUI parser. If the - producer separator ever changes without this parser following, the exact - assertion fails in CI instead of the gutter silently failing to compact - (or, on a widened separator, leaking a phantom space into every source - line). Line 2 is tab-indented source — the ambiguity this format fixes. - """ - output = format_content_with_line_numbers( - ["def f():", "\treturn 1"], start_line=1 - ) - compacted = ToolCallMessage._compact_line_gutter(output) - - assert compacted == "1 def f():\n2 \treturn 1" - def test_compact_line_gutter_passes_through_non_numbered(self) -> None: - """Output without a gutter is returned unchanged.""" + """Output without a cat -n gutter is returned unchanged.""" output = "plain text\nno line numbers here" assert ToolCallMessage._compact_line_gutter(output) == output