diff --git a/libs/code/tests/unit_tests/test_agent.py b/libs/code/tests/unit_tests/test_agent.py index 4f927271f8d..1534f9adf65 100644 --- a/libs/code/tests/unit_tests/test_agent.py +++ b/libs/code/tests/unit_tests/test_agent.py @@ -3609,8 +3609,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: diff --git a/libs/deepagents/deepagents/backends/protocol.py b/libs/deepagents/deepagents/backends/protocol.py index c528cc38fa9..b93f47d7dad 100644 --- a/libs/deepagents/deepagents/backends/protocol.py +++ b/libs/deepagents/deepagents/backends/protocol.py @@ -483,7 +483,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 `'/'`. @@ -491,12 +491,14 @@ def read( limit: Maximum number of lines to read. Returns: - String containing file content formatted with line numbers (`cat -n` format), - starting at line 1. - - Lines longer than 2000 characters are truncated. - - 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 19e58ddb396..91a88abc0e2 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,33 @@ 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}") - 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) + # 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)) + + # 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) 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 e807eac5adb..0597530cf2f 100644 --- a/libs/deepagents/deepagents/middleware/filesystem.py +++ b/libs/deepagents/deepagents/middleware/filesystem.py @@ -569,7 +569,6 @@ def _remaining_lines_notice(read_result: ReadResult) -> 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." @@ -910,7 +909,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 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 a6d5ac54745..fb51ca58c04 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,20 @@ 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. + + 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"^ *\d+(?: |\t)", row) is not None + @staticmethod def _annotate( request: ToolCallRequest, @@ -159,7 +173,8 @@ 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()) + 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/pyproject.toml b/libs/deepagents/pyproject.toml index dc944b4f6f1..a3b1dffaf0b 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/README.md b/libs/deepagents/tests/unit_tests/smoke_tests/snapshots/README.md new file mode 100644 index 00000000000..9efdfcafcf5 --- /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 `[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. | 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..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- 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 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": { @@ -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..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- 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 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": { @@ -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..258a939925d --- /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 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": { + "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..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- 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 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": { @@ -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..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- 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 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": { @@ -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..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- 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 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": { @@ -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..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- 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 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": { @@ -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_end_to_end.py b/libs/deepagents/tests/unit_tests/test_end_to_end.py index 161638498ba..5aaf4110c88 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 @@ -1314,14 +1314,14 @@ 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. - for marker in ("2\t", "2.1\t", "2.2\t"): + # 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\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 947232cd523..d9f417f6041 100644 --- a/libs/deepagents/tests/unit_tests/test_middleware.py +++ b/libs/deepagents/tests/unit_tests/test_middleware.py @@ -1248,15 +1248,80 @@ 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_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. + + 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\tshort line 1" in lines[0] - assert " 2\tshort line 2" in lines[1] - assert " 3\tshort 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.""" + 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_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.""" @@ -1266,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\tshort line" in lines[0] - assert " 2\t" in lines[1] + assert lines[0] == " 1 short line" + assert lines[1].startswith(" 2 ") assert lines[1].count("a") == 5000 - assert " 2.1\t" in lines[2] + assert lines[2].startswith("2.1 ") assert lines[2].count("a") == 5000 - assert " 2.2\t" in lines[3] + assert lines[3].startswith("2.2 ") assert lines[3].count("a") == 5000 - assert " 2.3\t" in lines[4] + assert lines[4].startswith("2.3 ") assert lines[4].count("a") == 5000 - assert " 2.4\t" in lines[5] + assert lines[5].startswith("2.4 ") assert lines[5].count("a") == 5000 - assert " 3\tanother 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.""" @@ -1287,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\t" in lines[0] + assert lines[0].startswith(" 5 ") assert lines[0].count("x") == 5000 - assert " 5.1\t" in lines[1] + assert lines[1].startswith("5.1 ") assert lines[1].count("x") == 5000 - assert " 5.2\t" in lines[2] + assert lines[2].startswith("5.2 ") assert lines[2].count("x") == 5000 - assert " 6\tmiddle" in lines[3] - assert " 7\t" in lines[4] + assert lines[3] == " 6 middle" + assert lines[4].startswith(" 7 ") assert lines[4].count("y") == 5000 - assert " 7.1\t" in lines[5] + assert lines[5].startswith("7.1 ") assert lines[5].count("y") == 5000 - assert " 7.2\t" 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): @@ -1309,7 +1374,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 lines[0].startswith("1 b") assert lines[0].count("b") == 5000 def test_read_file_with_long_lines_shows_continuation_markers(self): @@ -1322,14 +1387,14 @@ def test_read_file_with_long_lines_shows_continuation_markers(self): result = format_content_with_line_numbers(sliced.file_data["content"], 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 lines[0] == " 1 first line" + assert lines[1].startswith(" 2 ") assert lines[1].count("z") == 5000 - assert " 2.1\t" in lines[2] + assert lines[2].startswith("2.1 ") assert lines[2].count("z") == 5000 - assert " 2.2\t" in lines[3] + assert lines[3].startswith("2.2 ") assert lines[3].count("z") == 5000 - assert " 3\tthird 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.""" @@ -1341,13 +1406,13 @@ def test_read_file_with_offset_and_long_lines(self): result = format_content_with_line_numbers(sliced.file_data["content"], 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 lines[0].startswith(" 3 ") assert lines[0].count("m") == 5000 - assert " 3.1\t" in lines[1] + assert lines[1].startswith("3.1 ") assert lines[1].count("m") == 5000 - assert " 3.2\t" in lines[2] + assert lines[2].startswith("3.2 ") assert lines[2].count("m") == 2000 - assert " 4\tline4" in lines[3] + assert lines[3] == " 4 line4" def test_read_file_partial_window_includes_remaining_lines_notice(self): files = { 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..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}), @@ -135,6 +136,67 @@ 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_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") + # 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()