Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
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
11 changes: 3 additions & 8 deletions libs/deepagents/deepagents/backends/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,26 +446,21 @@ def write(
file_path: str,
content: str,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

write has two modes:

  1. overwrite
  2. append

This implements (1) which is probably correct

) -> WriteResult:
"""Create a new file with content.
"""Write content to a file, creating it or overwriting it if it already exists.

Args:
file_path: Path where the new file will be created.
file_path: Path where the file will be written.
content: Text content to write to the file.

Returns:
`WriteResult` with path on success, or error message if the file
already exists or write fails.
`WriteResult` with path on success, or error message on write failure.
"""
try:
resolved_path = self._resolve_path(file_path)
except (OSError, RuntimeError) as e:
return WriteResult(error=f"Error writing file '{file_path}': {e}")

try:
if resolved_path.exists():
msg = f"Cannot write to {file_path} because it already exists. Read and then make an edit, or write to a new path."
return WriteResult(error=msg)

# Create parent directories if needed
resolved_path.parent.mkdir(parents=True, exist_ok=True)

Expand Down
4 changes: 2 additions & 2 deletions libs/deepagents/deepagents/backends/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,10 +558,10 @@ def write(
file_path: str,
content: str,
) -> WriteResult:
"""Write content to a new file in the filesystem, error if file exists.
"""Write content to a file, creating it or overwriting it if it already exists.

Args:
file_path: Absolute path where the file should be created.
file_path: Absolute path where the file should be written.

Must start with '/'.
content: String content to write to the file.
Expand Down
27 changes: 11 additions & 16 deletions libs/deepagents/deepagents/backends/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,12 @@
"""

_WRITE_CHECK_TEMPLATE = """python3 -c "
import os, sys, base64
import os, base64

path = base64.b64decode('{path_b64}').decode('utf-8')
if os.path.exists(path):
print('Error: File already exists: ' + repr(path))
sys.exit(1)
os.makedirs(os.path.dirname(path) or '.', exist_ok=True)
" 2>&1"""
"""Preflight check for write operations: verify the target file does not already
exist and create parent directories.
"""Preflight for write operations: create parent directories for the target path if it doesn't exist.

Only the (small) base64-encoded path is interpolated — file content is
transferred separately via `upload_files()`.
Expand Down Expand Up @@ -544,21 +540,20 @@ def read(
)

def _write_preflight(self, file_path: str) -> WriteResult | None:
"""Run the existence check + parent-directory creation for `write()`.
"""Create parent directories for `write()`.

Subclasses overriding `write()` (e.g., to use a native SDK transport)
should call this first so they preserve the same "fail if file exists"
and parent-mkdir semantics as `BaseSandbox.write()`. There is a TOCTOU
window between this check and the actual write — an inherent limitation
of splitting the operation across two backend calls.
should call this first so they preserve the parent-mkdir semantics of
`BaseSandbox.write()`. There is a TOCTOU window between this and the
actual write — an inherent limitation of splitting the operation across
two backend calls.

Args:
file_path: Absolute path for the file about to be written.

Returns:
`None` if the preflight passes (target does not exist, parents
created); a populated `WriteResult` with `error` set if the
check fails.
`None` if the preflight passes (parents created); a populated
`WriteResult` with `error` set if the preflight fails.
"""
path_b64 = base64.b64encode(file_path.encode("utf-8")).decode("ascii")
check_cmd = _WRITE_CHECK_TEMPLATE.format(path_b64=path_b64)
Expand All @@ -573,10 +568,10 @@ def write(
file_path: str,
content: str,
) -> WriteResult:
"""Create a new file, failing if it already exists.
"""Write content to a file, creating or overwriting it if it already exists.

Args:
file_path: Absolute path for the new file.
file_path: Absolute path for the file.
content: UTF-8 text content to write.

Returns:
Expand Down
20 changes: 9 additions & 11 deletions libs/deepagents/deepagents/backends/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,20 +596,19 @@ def write(
file_path: str,
content: str,
) -> WriteResult:
"""Create a new file with content.
"""Write content to a file, creating it or overwriting it if it already exists.

Returns WriteResult on success or error.
"""
store = self._get_store()
namespace = self._get_namespace()

# Check if file exists
existing = store.get(namespace, file_path)
if existing is not None:
return WriteResult(error=f"Cannot write to {file_path} because it already exists. Read and then make an edit, or write to a new path.")

# Create new file
file_data = create_file_data(content)
existing_file_data = self._convert_store_item_to_file_data(existing)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Old behavior was inefficient in terms of network requests. Current behavior is consistent with old behavior. We can revisit whether we want to preserve creation timestamp. (The cost of this can be 10-100 ms of latency.)

file_data = update_file_data(existing_file_data, content)
else:
file_data = create_file_data(content)
store_value = self._convert_file_data_to_store_value(file_data)
store.put(namespace, file_path, store_value)
return WriteResult(path=file_path)
Expand All @@ -626,13 +625,12 @@ async def awrite(
store = self._get_store()
namespace = self._get_namespace()

# Check if file exists using async method
existing = await store.aget(namespace, file_path)
if existing is not None:
return WriteResult(error=f"Cannot write to {file_path} because it already exists. Read and then make an edit, or write to a new path.")

# Create new file using async method
file_data = create_file_data(content)
existing_file_data = self._convert_store_item_to_file_data(existing)
file_data = update_file_data(existing_file_data, content)
else:
file_data = create_file_data(content)
store_value = self._convert_file_data_to_store_value(file_data)
await store.aput(namespace, file_path, store_value)
return WriteResult(path=file_path)
Expand Down
13 changes: 7 additions & 6 deletions libs/deepagents/deepagents/middleware/filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,8 @@ class ReadFileSchema(BaseModel):
class WriteFileSchema(BaseModel):
"""Input schema for the `write_file` tool."""

file_path: str = Field(description="Absolute path where the file should be created. Must be absolute, not relative.")
file_path: str = Field(description="Absolute path where the file should be written. Must be absolute, not relative.")

content: str = Field(description="The text content to write to the file. This parameter is required.")


Expand Down Expand Up @@ -462,11 +463,11 @@ class ExecuteSchema(BaseModel):
- Only use emojis if the user explicitly requests it."""


WRITE_FILE_TOOL_DESCRIPTION = """Writes to a new file in the filesystem.
WRITE_FILE_TOOL_DESCRIPTION = """Writes content to a file. Creates the file if it does not exist; replaces it entirely if it does.
Comment thread
imnishitha marked this conversation as resolved.
Resolved

Usage:
- The write_file tool will create the a new file.
- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.
Comment thread
imnishitha marked this conversation as resolved.
Resolved
- 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.
- Prefer edit_file when making targeted changes to an existing file while leaving the rest intact.
"""

DELETE_TOOL_DESCRIPTION = """Deletes a file or directory from the filesystem.
Expand Down Expand Up @@ -1113,7 +1114,7 @@ def _create_write_file_tool(self) -> BaseTool:
tool_description = self._custom_tool_descriptions.get("write_file") or WRITE_FILE_TOOL_DESCRIPTION

def sync_write_file(
file_path: Annotated[str, "Absolute path where the file should be created. Must be absolute, not relative."],
file_path: Annotated[str, "Absolute path where the file should be written. Must be absolute, not relative."],
content: Annotated[str, "The text content to write to the file. This parameter is required."],
runtime: ToolRuntime[None, FilesystemState],
) -> ToolMessage:
Expand Down Expand Up @@ -1152,7 +1153,7 @@ def sync_write_file(
)

async def async_write_file(
file_path: Annotated[str, "Absolute path where the file should be created. Must be absolute, not relative."],
file_path: Annotated[str, "Absolute path where the file should be written. Must be absolute, not relative."],
content: Annotated[str, "The text content to write to the file. This parameter is required."],
runtime: ToolRuntime[None, FilesystemState],
) -> ToolMessage:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ def test_write_file_longterm(self):
assert isinstance(content, str), f"Expected str content, got {type(content)}"
assert "fiery" in content or "Fiery" in content

def test_write_file_fail_already_exists_in_local(self):
def test_write_file_overwrites_existing_in_local(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure these integration tests ever run fwiw

checkpointer = MemorySaver()
store = InMemoryStore()
agent = create_agent(
Expand Down Expand Up @@ -376,7 +376,8 @@ def test_write_file_fail_already_exists_in_local(self):
messages = response["messages"]
write_file_message = next(message for message in messages if message.type == "tool" and message.name == "write_file")
assert write_file_message is not None
assert "Cannot write" in write_file_message.content
assert write_file_message.status == "success"
assert "fiery" in response["files"]["/charmander.txt"]["content"].lower() or "Fiery" in response["files"]["/charmander.txt"]["content"]

def test_edit_file_longterm(self):
checkpointer = MemorySaver()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -537,17 +537,17 @@ def test_sandbox_write_with_special_content() -> None:
assert sandbox._uploaded[0][1] == content.encode("utf-8")


def test_sandbox_write_returns_error_on_existing_file() -> None:
"""Test that write() returns an error when the check command fails."""
def test_sandbox_write_returns_error_on_preflight_failure() -> None:
Comment thread
imnishitha marked this conversation as resolved.
Resolved
"""Test that write() returns an error and skips upload when the preflight fails."""
sandbox = MockSandbox()

def fail_execute(command: str, *, timeout: int | None = None) -> ExecuteResponse: # noqa: ARG001
sandbox.last_command = command
return ExecuteResponse(output="Error: File already exists", exit_code=1)
return ExecuteResponse(output="Error: Permission denied", exit_code=1)

sandbox.execute = fail_execute

result = sandbox.write("/test/existing.txt", "content")
result = sandbox.write("/test/protected.txt", "content")
assert result.error is not None
assert "Error:" in result.error
assert len(sandbox._uploaded) == 0 # upload should not have been called
Expand Down
12 changes: 5 additions & 7 deletions libs/deepagents/tests/unit_tests/backends/test_store_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,24 +51,22 @@ def test_store_backend_crud_and_search():
assert any(i["path"] == "/docs/readme.md" for i in g2)


def test_store_backend_write_rejects_existing_file():
def test_store_backend_write_overwrites_existing_file():
mem_store = InMemoryStore()
be = StoreBackend(store=mem_store, namespace=lambda _ctx: ("filesystem",))

# Create the file
result = be.write("/charmander.txt", "Hello world")
assert result.error is None

# Attempt to overwrite — should fail
# Overwrite should succeed
result = be.write("/charmander.txt", "New content")
assert result.error is not None
assert "Cannot write" in result.error
assert "already exists" in result.error
assert result.error is None

# Original content preserved
# New content visible
read_result = be.read("/charmander.txt")
assert read_result.file_data is not None
assert "Hello world" in read_result.file_data["content"]
assert "New content" in read_result.file_data["content"]


def test_store_backend_ls_nested_directories():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
{
"function": {
"description": "Writes to a new file in the filesystem.\n\nUsage:\n- The write_file tool will create the a new file.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.",
"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 edit_file when making targeted changes to an existing file while leaving the rest intact.",
"name": "write_file",
"parameters": {
"properties": {
Expand All @@ -97,7 +97,7 @@
"type": "string"
},
"file_path": {
"description": "Absolute path where the file should be created. Must be absolute, not relative.",
"description": "Absolute path where the file should be written. Must be absolute, not relative.",
"type": "string"
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
{
"function": {
"description": "Writes to a new file in the filesystem.\n\nUsage:\n- The write_file tool will create the a new file.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.",
"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 edit_file when making targeted changes to an existing file while leaving the rest intact.",
"name": "write_file",
"parameters": {
"properties": {
Expand All @@ -97,7 +97,7 @@
"type": "string"
},
"file_path": {
"description": "Absolute path where the file should be created. Must be absolute, not relative.",
"description": "Absolute path where the file should be written. Must be absolute, not relative.",
"type": "string"
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
{
"function": {
"description": "Writes to a new file in the filesystem.\n\nUsage:\n- The write_file tool will create the a new file.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.",
"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 edit_file when making targeted changes to an existing file while leaving the rest intact.",
"name": "write_file",
"parameters": {
"properties": {
Expand All @@ -97,7 +97,7 @@
"type": "string"
},
"file_path": {
"description": "Absolute path where the file should be created. Must be absolute, not relative.",
"description": "Absolute path where the file should be written. Must be absolute, not relative.",
"type": "string"
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
{
"function": {
"description": "Writes to a new file in the filesystem.\n\nUsage:\n- The write_file tool will create the a new file.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.",
"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 edit_file when making targeted changes to an existing file while leaving the rest intact.",
"name": "write_file",
"parameters": {
"properties": {
Expand All @@ -97,7 +97,7 @@
"type": "string"
},
"file_path": {
"description": "Absolute path where the file should be created. Must be absolute, not relative.",
"description": "Absolute path where the file should be written. Must be absolute, not relative.",
"type": "string"
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@
},
{
"function": {
"description": "Writes to a new file in the filesystem.\n\nUsage:\n- The write_file tool will create the a new file.\n- Prefer to edit existing files (with the edit_file tool) over creating new ones when possible.",
"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 edit_file when making targeted changes to an existing file while leaving the rest intact.",
"name": "write_file",
"parameters": {
"properties": {
Expand All @@ -97,7 +97,7 @@
"type": "string"
},
"file_path": {
"description": "Absolute path where the file should be created. Must be absolute, not relative.",
"description": "Absolute path where the file should be written. Must be absolute, not relative.",
"type": "string"
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,20 +281,19 @@ def test_write_creates_parent_dirs(self, sandbox: LocalSubprocessSandbox) -> Non
exec_result = sandbox.execute(f"cat {test_path}")
assert exec_result.output.strip() == content

def test_write_existing_file_fails(self, sandbox: LocalSubprocessSandbox) -> None:
"""Test that writing to an existing file returns an error."""
def test_write_existing_file_overwrites(self, sandbox: LocalSubprocessSandbox) -> None:
"""Test that writing to an existing file overwrites it."""
test_path = "/tmp/test_sandbox_ops/existing.txt"
# Create file first
sandbox.write(test_path, "First content")

# Try to write again
# Write again should overwrite
result = sandbox.write(test_path, "Second content")

assert result.error is not None
assert "already exists" in result.error.lower()
# Verify original content unchanged
assert result.error is None
# Verify new content
exec_result = sandbox.execute(f"cat {test_path}")
assert exec_result.output.strip() == "First content"
assert exec_result.output.strip() == "Second content"

def test_write_special_characters(self, sandbox: LocalSubprocessSandbox) -> None:
"""Test writing content with special characters and escape sequences."""
Expand Down
Loading