Skip to content
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
47a6bd9
add disable_tools
imnishitha Jun 26, 2026
9f6e1a7
tests
imnishitha Jun 26, 2026
5088fc2
doc strings
imnishitha Jun 26, 2026
4164fa6
Merge branch 'main' into nm/disable-tools
imnishitha Jun 26, 2026
ce2e951
Merge branch 'main' into nm/disable-tools
imnishitha Jun 26, 2026
664bcaf
Merge branch 'main' into nm/disable-tools
imnishitha Jun 26, 2026
bb80ae6
feat(sdk): add recursive filesystem delete support
mdrxy Jun 24, 2026
f305e98
allow override default middlewares
imnishitha Jun 23, 2026
213eb22
tests
imnishitha Jun 23, 2026
dfdef9b
handle subclasses mw with same names as default mw
imnishitha Jun 24, 2026
36cf864
test fix
imnishitha Jun 25, 2026
ed7998e
Apply suggestions from code review
imnishitha Jun 25, 2026
60e0070
add tool exclsuion after custom mw injection
imnishitha Jun 25, 2026
4d2c73a
refactor: pass FilesystemMiddleware directly to configure disable_tools
imnishitha Jun 29, 2026
2c8e191
Merge branch 'main' into nm/disable-tools
imnishitha Jun 30, 2026
a79a6d2
delete test files
imnishitha Jun 30, 2026
8e245bb
changed to 'enabled_tools'
imnishitha Jun 30, 2026
7f5886b
Merge branch 'main' into nm/disable-tools
imnishitha Jun 30, 2026
448bbbf
keep custom tools
imnishitha Jun 30, 2026
37a4cc5
Merge branch 'main' into nm/disable-tools
imnishitha Jun 30, 2026
28bfacc
lint fix
imnishitha Jun 30, 2026
e09529e
Merge branch 'main' into nm/disable-tools
imnishitha Jun 30, 2026
963b5ba
pass the fs mw as-is
imnishitha Jul 1, 2026
da87f2c
remove additional lines
imnishitha Jul 1, 2026
202f75d
autocomplete list
imnishitha Jul 1, 2026
e4f8dd8
Merge branch 'main' into nm/disable-tools
imnishitha Jul 1, 2026
3883373
Update libs/deepagents/deepagents/middleware/filesystem.py
imnishitha Jul 1, 2026
afdcb14
Merge branch 'main' into nm/disable-tools
imnishitha Jul 1, 2026
d855978
make FsToolName available for use
imnishitha Jul 1, 2026
4b64172
renamed to 'tools' and add end-to-end test
imnishitha Jul 2, 2026
3ec894a
Merge branch 'main' into nm/disable-tools
imnishitha Jul 2, 2026
08790e4
lint fix
imnishitha Jul 2, 2026
0312d11
nits
imnishitha Jul 2, 2026
455dbbd
nits
imnishitha Jul 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion libs/deepagents/deepagents/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from deepagents._version import __version__
from deepagents.graph import DeepAgentState, create_deep_agent
from deepagents.middleware.async_subagents import AsyncSubAgent, AsyncSubAgentMiddleware
from deepagents.middleware.filesystem import FilesystemMiddleware, FilesystemPermission
from deepagents.middleware.filesystem import FilesystemMiddleware, FilesystemPermission, FsToolName
from deepagents.middleware.memory import MemoryMiddleware
from deepagents.middleware.rubric import RubricMiddleware
from deepagents.middleware.subagents import (
Expand All @@ -29,6 +29,7 @@
"DeepAgentState",
"FilesystemMiddleware",
"FilesystemPermission",
"FsToolName",
"GeneralPurposeSubagentProfile",
"HarnessProfile",
"HarnessProfileConfig",
Expand Down
106 changes: 81 additions & 25 deletions libs/deepagents/deepagents/middleware/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import mimetypes
import threading
import uuid
from collections.abc import Awaitable, Callable, Mapping
from collections.abc import Awaitable, Callable, Collection, Mapping
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Annotated, Any, Literal, NotRequired, cast
Expand Down Expand Up @@ -582,30 +582,51 @@ class ExecuteSchema(BaseModel):
Note: This tool is only available if the backend supports execution (SandboxBackendProtocol).
If execution is not supported, the tool will return an error message."""

FsToolName = Literal["ls", "read_file", "write_file", "edit_file", "delete", "glob", "grep", "execute"]
"""Names of the built-in filesystem tools that can be passed to ``enabled_tools``."""

_FS_TOOL_ORDER: tuple[str, ...] = ("ls", "read_file", "write_file", "edit_file", "delete", "glob", "grep")
_ALL_FS_TOOL_NAMES: frozenset[str] = frozenset(_FS_TOOL_ORDER) | {"execute"}
_FS_TOOL_DESCRIPTION_LINES: dict[str, str] = {
"ls": "ls: list files in a directory (requires absolute path)",
"read_file": "read_file: read a file from the filesystem",
"write_file": "write_file: write to a file in the filesystem",
"edit_file": "edit_file: edit a file in the filesystem",
"delete": "delete: delete a file or directory (recursively) from the filesystem",
"glob": 'glob: find files matching a pattern (e.g., "**/*.py")',
"grep": "grep: search for text within files",
}


def _build_fs_tools_section(visible: set[str]) -> tuple[str, str]:
"""Return (header backtick list, bullet descriptions) for the given visible FS tools."""
ordered = [t for t in _FS_TOOL_ORDER if t in visible]
header = ", ".join(f"`{t}`" for t in ordered)
descriptions = "\n".join(f"- {_FS_TOOL_DESCRIPTION_LINES[t]}" for t in ordered)
return header, descriptions


_FILESYSTEM_SYSTEM_PROMPT_TEMPLATE = """## Following Conventions

- Read files before editing — understand existing content before making changes
- Mimic existing style, naming conventions, and patterns

## Filesystem Tools `ls`, `read_file`, `write_file`, `edit_file`, `delete`, `glob`, `grep`
## Filesystem Tools {tool_header}

You have access to a filesystem which you can interact with using these tools.
All file paths must start with a /. Follow the tool docs for the available tools, and use pagination (offset/limit) when reading large files.

- ls: list files in a directory (requires absolute path)
- read_file: read a file from the filesystem
- write_file: write to a file in the filesystem
- edit_file: edit a file in the filesystem
- delete: delete a file or directory (recursively) from the filesystem
- glob: find files matching a pattern (e.g., "**/*.py")
- grep: search for text within files
{tool_descriptions}

## Large Tool Results

When a tool result is too large, it may be offloaded into the filesystem instead of being returned inline. In those cases, use `read_file` to inspect the saved result in chunks, or use `grep` within `{large_tool_results_prefix}/` if you need to search across offloaded tool results and do not know the exact file path. Offloaded tool results are stored under `{large_tool_results_prefix}/<tool_call_id>`."""

_default_tool_header, _default_tool_descriptions = _build_fs_tools_section(set(_FS_TOOL_ORDER))
FILESYSTEM_SYSTEM_PROMPT = _FILESYSTEM_SYSTEM_PROMPT_TEMPLATE.format(
large_tool_results_prefix="/large_tool_results",
tool_header=_default_tool_header,
tool_descriptions=_default_tool_descriptions,
)

EXECUTION_SYSTEM_PROMPT = """## Execute Tool `execute`
Expand Down Expand Up @@ -889,6 +910,7 @@ def __init__(
tool_token_limit_before_evict: int | None = 20000,
human_message_token_limit_before_evict: int | None = 50000,
max_execute_timeout: int = 3600,
enabled_tools: Collection[FsToolName] | None = None,
Comment thread
imnishitha marked this conversation as resolved.
Resolved
_permissions: list[FilesystemPermission] | None = None,
) -> None:
"""Initialize the filesystem middleware.
Expand All @@ -906,13 +928,23 @@ def __init__(

Defaults to 3600 seconds (1 hour). Any per-command timeout
exceeding this value will be rejected with an error message.
enabled_tools: Allowlist of `FsToolName` values to expose
to the model. `None` (the default) enables all tools. When a
collection is provided, only the listed tools are included in
the model request; all others are hidden. `read_file` must be
included in any non-`None` allowlist. Backend capability
checks for `execute` and `delete` still apply; listing them
here when the backend does not support them is a no-op.
_permissions: Optional filesystem permission rules enforced directly
by this middleware's tool implementations.

Marked private for now because this is an internal
implementation detail and may move to the backend layer in a
future change.
"""
if enabled_tools is not None and "read_file" not in enabled_tools:
msg = "read_file must be included in enabled_tools; it is required by FilesystemMiddleware"
raise ValueError(msg)
if max_execute_timeout <= 0:
msg = f"max_execute_timeout must be positive, got {max_execute_timeout}"
raise ValueError(msg)
Expand Down Expand Up @@ -948,6 +980,7 @@ def __init__(
self._tool_token_limit_before_evict = tool_token_limit_before_evict
self._human_message_token_limit_before_evict = human_message_token_limit_before_evict
self._max_execute_timeout = max_execute_timeout
self._enabled_tools: frozenset[str] | None = frozenset(enabled_tools) if enabled_tools is not None else None
self._permissions = list(_permissions or [])

# Shared executor for enforcing GLOB_TIMEOUT on the sync glob tool.
Expand Down Expand Up @@ -982,7 +1015,15 @@ def _build_dynamic_system_prompt(self, *, include_execution: bool) -> str:
cached = self._dynamic_system_prompt_cache.get(include_execution)
if cached is not None:
return cached
prompt_parts = [_FILESYSTEM_SYSTEM_PROMPT_TEMPLATE.format(large_tool_results_prefix=self._large_tool_results_prefix)]
visible = set(self._enabled_tools) if self._enabled_tools is not None else set(_FS_TOOL_ORDER)
tool_header, tool_descriptions = _build_fs_tools_section(visible)
prompt_parts = [
_FILESYSTEM_SYSTEM_PROMPT_TEMPLATE.format(
large_tool_results_prefix=self._large_tool_results_prefix,
tool_header=tool_header,
tool_descriptions=tool_descriptions,
)
]
if include_execution:
prompt_parts.append(EXECUTION_SYSTEM_PROMPT)
system_prompt = "\n\n".join(prompt_parts).strip()
Expand Down Expand Up @@ -2097,39 +2138,54 @@ def _filter_unsupported_tools_and_apply_prompt(self, request: ModelRequest[Conte
Returns the request with unsupported tools removed and the filesystem
system prompt appended.
"""
tool_names = {(tool.name if hasattr(tool, "name") else tool.get("name")) for tool in request.tools}
tool_names: set[str | None] = cast(
"set[str | None]",
{(tool.name if hasattr(tool, "name") else tool.get("name")) for tool in request.tools},
)
has_execute_tool = "execute" in tool_names
has_delete_tool = "delete" in tool_names

# `execute` and `delete` are optional per backend; resolve the
# backend once and filter out any tool the backend can't serve.
if has_execute_tool or has_delete_tool:
# Tools excluded by the enabled_tools allowlist (empty when no allowlist is set).
# Only filesystem tools are subject to the allowlist — user-provided tools always pass through.
# `execute` and `delete` are also filtered when the backend can't serve them.
unsupported: set[str | None] = (
{name for name in tool_names if name in _ALL_FS_TOOL_NAMES and name not in self._enabled_tools}
if self._enabled_tools is not None
else set()
)
execution_active = False # tracks whether execute should get system-prompt instructions
backend = None
if has_delete_tool or has_execute_tool:
backend = self._get_backend(request.runtime) # ty: ignore[invalid-argument-type]
unsupported: set[str | None] = set()
if has_execute_tool and not supports_execution(backend):
unsupported.add("execute")
has_execute_tool = False
if has_delete_tool and not _supports_delete(backend):
if has_execute_tool and "execute" not in unsupported:
execution_active = supports_execution(backend)
if not execution_active:
unsupported.add("execute")
if has_delete_tool and "delete" not in unsupported and not _supports_delete(backend):
unsupported.add("delete")
if unsupported:
filtered_tools = [tool for tool in request.tools if (tool.name if hasattr(tool, "name") else tool.get("name")) not in unsupported]
request = request.override(tools=filtered_tools)
if unsupported:
filtered_tools = [tool for tool in request.tools if (tool.name if hasattr(tool, "name") else tool.get("name")) not in unsupported]
request = request.override(tools=filtered_tools)

# Use custom system prompt if provided, otherwise generate dynamically
if self._custom_system_prompt is not None:
system_prompt = self._custom_system_prompt
else:
# Build dynamic system prompt based on available tools
# Build dynamic system prompt reflecting only the tools that survived filtering
visible_fs = {n for n in (tool_names - unsupported) if n is not None}
tool_header, tool_descriptions = _build_fs_tools_section(visible_fs)
prompt_parts = [
_FILESYSTEM_SYSTEM_PROMPT_TEMPLATE.format(
large_tool_results_prefix=self._large_tool_results_prefix,
tool_header=tool_header,
tool_descriptions=tool_descriptions,
)
]

# Add execution instructions only if the execute tool survived filtering
if has_execute_tool:
if execution_active:
prompt_parts.append(EXECUTION_SYSTEM_PROMPT)
route_prompt = _route_host_path_prompt(backend)
route_prompt = _route_host_path_prompt(cast("BackendProtocol", backend))
if route_prompt:
prompt_parts.append(route_prompt)

Expand Down
5 changes: 4 additions & 1 deletion libs/deepagents/deepagents/middleware/subagents.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@ class SubAgent(TypedDict):

Use the format `'provider:model-name'` (e.g., `'openai:gpt-5.5'`).
middleware: Additional middleware for custom behavior, logging,
or rate limiting.
or rate limiting. To restrict filesystem tools, include a
`FilesystemMiddleware(enabled_tools=...)` instance here — it
will be used as the subagent's filesystem middleware instead of
the default one.
interrupt_on: Configure human-in-the-loop for specific tools.

Requires a checkpointer.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async def handler(request: ModelRequest) -> ModelResponse:
request = ModelRequest(
model=GenericFakeChatModel(messages=iter([AIMessage(content="ok")])),
messages=[HumanMessage(content="hi")],
tools=[],
tools=list(mw.tools),
)

await mw.awrap_model_call(request, handler)
Expand Down
Loading