Where Should a Deep Agent Keep Its Files and Big Results?

8 min read

The problem

An agent on a long task produces a lot of stuff. Search results, log dumps, draft paragraphs, notes to itself. In a plain agent loop all of it goes into one place: the message list. Every new model call sends that whole list again. After a few big tool results the context is full of text the model no longer needs, and the important parts get lost in the middle.

There is a second problem. When the run ends, the work is gone. Nothing was saved anywhere you can open, and nothing carries over to the next conversation.

People solve this the same way: they write things down. A deep agent gets a virtual filesystem for the same reason. It can save a big result to a file, keep only a short note in context, and read the file back later, one slice at a time.

The open question is where those files should live. In memory for this one run? On your real disk? In a database that survives across users and threads? In 0.7.42, deepagents answers with backends. This part runs each one, then adds two things that make the filesystem safe and useful: permission rules and large result offloading.

The tools the model sees

Every deep agent gets the same file tools, whatever backend sits under them: ls, read_file, write_file, edit_file, glob and grep, and delete. The model calls them with paths that start with /. It never knows whether /notes/plan.md is a Python dict, a file on disk, or a row in a store. The backend decides that.

flowchart LR
  M[Model] -->|tool call| T[File tools]
  T --> P{Permission rules}
  P -->|deny| E[Error back to model]
  P -->|allow| B[Backend]
  B --> S[StateBackend: graph state]
  B --> F[FilesystemBackend: real disk]
  B --> K[StoreBackend: LangGraph store]
  B --> C[CompositeBackend: routes by path]

How this code was tested

Every block below ran on deepagents 0.7.42, langchain 1.5.2, langchain-core 1.8.5, langgraph 1.2.24 and Python 3.12.3. The article shows model="anthropic:claude-sonnet-4-6". All outputs quoted in this part came from a scripted fake chat model that emits fixed tool calls, so the backend wiring is the only thing being tested. No output in this part came from a real model. The tool results, errors, file lists and token counts are what the real deepagents code returned for those calls.

StateBackend: files that live in the thread

StateBackend is the default. Files are stored in the agent's state under a files key, next to messages. With a checkpointer, they last as long as the thread.

python
from deepagents import create_deep_agent
from deepagents.backends import StateBackend
from langgraph.checkpoint.memory import InMemorySaver

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    backend=StateBackend(),
    checkpointer=InMemorySaver(),
)
cfg = {"configurable": {"thread_id": "t1"}}
out = agent.invoke({"messages": [{"role": "user", "content": "Make a plan file."}]}, cfg)
print(list(out["files"].keys()))

The scripted model wrote /notes/plan.md, edited one line, then listed, globbed, grepped and read it. The tool results:

text
[write_file] 'Updated file /notes/plan.md'
[edit_file] "Successfully replaced 1 instance(s) of the string in '/notes/plan.md'"
[ls] "['/notes/plan.md']"
[glob] "['/notes/plan.md']"
[grep] '/notes/plan.md'
[read_file] '@@ lines 1-2 of 2 @@\nstep 1: read\nstep 2: write the report'
state['files'] keys: ['/notes/plan.md']
stored record: {'content': 'step 1: read\nstep 2: write the report\n', 'encoding': 'utf-8', 'created_at': ..., 'modified_at': ...}

Then we asked again on the same thread, and on a new one:

text
turn 2, same thread, read_file -> ['@@ lines 1-2 of 2 @@', 'step 1: read', 'step 2: write the report']
new thread t2, read_file -> Error: File '/notes/plan.md' not found
t2 files: []

That is the whole contract. Same thread, the file is there. New thread, the filesystem starts empty. This is the right home for scratch work: plans, drafts, big intermediate results.

FilesystemBackend: real files on disk

FilesystemBackend maps the agent's paths onto a real folder. Use it when a person or another program needs to open the files.

python
from deepagents.backends import FilesystemBackend

agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    backend=FilesystemBackend(root_dir="./agent-root", virtual_mode=True),
)

With virtual_mode=True, /report.md means ./agent-root/report.md. In 0.7.42 virtual_mode defaults to True. The scripted model wrote a report, tried to read /../../etc/passwd, and deleted the report:

text
[write_file] Updated file /report.md
[read_file] Error: Path traversal not allowed: /../../etc/passwd
[delete] Deleted /report.md
files in state: []
on disk after run: []

Note files in state: []. Nothing went into graph state, because this backend writes straight to disk. A second run wrote /docs/report.md and we read it with plain Python:

text
real path: agent-root-.../docs/report.md
cat: # Report | All good.

A warning from the library's own docstring: virtual_mode=True blocks .., ~ and paths outside the root, but "it does not provide sandboxing or process isolation". It is a path guard, not a security boundary. With virtual_mode=False, absolute paths are used as they are, which the source describes as giving "no security against an agent choosing paths outside root_dir".

StoreBackend: files that outlive the thread

StoreBackend keeps files in a LangGraph store. A store is shared across threads, so this is where long-term memory goes. You pick a namespace with a function of the runtime, for example one namespace per user.

python
from deepagents.backends import StoreBackend
from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
agent = create_deep_agent(
    model="anthropic:claude-sonnet-4-6",
    backend=StoreBackend(namespace=lambda rt: ("demo-user", "filesystem")),
    store=store,
    checkpointer=InMemorySaver(),
)

On thread A the scripted model wrote /prefs.md. On thread B it read it back:

text
thread B read_file -> @@ lines 1-1 of 1 @@ | User likes short answers.
files key in thread B state: []
store item: ('demo-user', 'filesystem') /prefs.md {'content': 'User likes short answers.\n'}

The file crossed threads, and it never touched graph state. InMemoryStore is lost when the process exits. In production you would pass a store backed by a database. Part 9 builds long-term memory on this.

CompositeBackend: one tree, many homes

Real agents want all three. Scratch files should vanish with the thread. Memories should persist. Project files should be real files. CompositeBackend routes each path to a backend by its prefix. The source says routes are matched "longest first", and anything that matches no route goes to the default.

Hand-drawn diagram: the agent's write_file call enters CompositeBackend, a diamond routes by path prefix, the default goes to StateBackend for /scratch.md which lasts one thread, /memories/ goes to StoreBackend for all threads, and /project/ goes to FilesystemBackend on real disk; permissions are checked before any backend is called

python
from deepagents.backends import CompositeBackend

backend = CompositeBackend(
    default=StateBackend(),
    routes={
        "/memories/": StoreBackend(namespace=lambda rt: ("demo-user",)),
        "/project/": FilesystemBackend(root_dir="./project", virtual_mode=True),
    },
)
agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", backend=backend, store=store)

The scripted model wrote three files in one turn, then ran ls / and glob **/*.md:

text
[write_file] Updated file /scratch.md
[write_file] Updated file /memories/style.md
[write_file] Updated file /project/README.md
[ls] ['/memories/', '/project/', '/scratch.md']
[glob] ['/memories/style.md', '/project/README.md', '/scratch.md']
in graph state  : ['/scratch.md']
in the store    : [(('demo-user',), '/style.md')]
on disk         : ['README.md']

The model sees one tree. Underneath, each file went to a different place. The route prefix is stripped before the call reaches the backend: the store key is /style.md, not /memories/style.md, and the file on disk is README.md at the project root.

Here is one write through that stack, step by step:

sequenceDiagram
  participant A as Agent loop
  participant L as LLM
  participant T as write_file
  participant P as Permissions
  participant C as Composite
  participant S as StoreBackend
  A->>L: messages + tools
  L-->>A: write_file /memories/style.md
  A->>T: run tool
  T->>P: check write on path
  P-->>T: allowed
  T->>C: write /memories/style.md
  C->>S: write /style.md
  S-->>C: ok
  C-->>T: ok
  T-->>A: Updated file /memories/style.md
  A->>L: tool result added

Permissions: first match wins

A filesystem the model can write to is a filesystem the model can break. create_deep_agent takes permissions=, a list of FilesystemPermission rules. Each rule has operations (read, write), glob paths, and a mode: allow, deny, or interrupt to pause for a human. The docstring for create_deep_agent is exact: "Rules are evaluated in declaration order; the first match wins. If no rule matches, the call is allowed."

That last sentence matters. With no catch-all rule, everything you did not list is allowed. So we end with a deny for /**:

python
from deepagents import create_deep_agent, FilesystemPermission

rules = [
    FilesystemPermission(operations=["read", "write"], paths=["/secrets/**"], mode="deny"),
    FilesystemPermission(operations=["write"], paths=["/policy/**"], mode="deny"),
    FilesystemPermission(operations=["read"], paths=["/policy/**"], mode="allow"),
    FilesystemPermission(operations=["read", "write"], paths=["/workspace/**"], mode="allow"),
    FilesystemPermission(operations=["read", "write"], paths=["/**"], mode="deny"),
]
agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", permissions=rules)

We seeded /policy/rules.md and /secrets/api.txt in state, and the scripted model tried six calls:

text
[write_file /workspace/draft.md] Updated file /workspace/draft.md
[read_file /policy/rules.md] @@ lines 1-1 of 1 @@
Be kind.
[edit_file /policy/rules.md] Error: permission denied for write on /policy/rules.md
[read_file /secrets/api.txt] Error: permission denied for read on /secrets/api.txt
[write_file /etc/cron.txt] Error: permission denied for write on /etc/cron.txt
[ls /] Error: permission denied for read on /
policy file after run: Be kind.

Three things to notice. edit_file counts as a write. A denied call does not crash the run: the model gets an error string and can try something else. And ls / was denied too, because listing the root is a read on /, which only the catch-all matched. If you want the model to browse, add an allow for reading / before the catch-all.

Two limits from the source. Permissions apply at the tool level for the built-in file tools, and "Direct backend usage does not currently incorporate permissions". Subagents inherit the parent's rules unless their spec sets its own permissions, which "replaces the parent's rules entirely". Part 8 uses mode="interrupt" for approvals.

Offloading large tool results

Now back to the first problem: one tool returns a huge blob. Offloading is built into FilesystemMiddleware. Its tool_token_limit_before_evict defaults to 20000, and the check multiplies by 4 characters per token, so any tool result over 80,000 characters is written to /large_tool_results/<tool_call_id>. The model gets a preview instead. The file tools themselves (ls, glob, grep, read_file, edit_file, write_file, delete) are excluded from this, so a read_file never gets offloaded in a loop.

Hand-drawn diagram: fetch_logs returns 157,889 characters; a diamond checks whether it is over 20,000 tokens times 4 characters; if yes, the full text is written to /large_tool_results/c1 and the context gets a 436 token head and tail preview, which the model can follow up with read_file or grep; if no, a small result goes in as is

We gave the agent a tool that returns 3,000 log lines:

python
from langchain_core.tools import tool

@tool
def fetch_logs(service: str) -> str:
    """Return the raw log dump for a service."""
    return "\n".join(
        f"2026-11-28T10:{i // 60 % 60:02d}:{i % 60:02d} {service} GET /api/items/{i} 200 12ms"
        for i in range(3000)
    )

agent = create_deep_agent(model="anthropic:claude-sonnet-4-6", tools=[fetch_logs])

The scripted model called fetch_logs, then ls /large_tool_results, then grep for the last request. What landed in context:

text
raw tool output chars: 157889
--- [fetch_logs] 1186 chars in context
Tool result too large, the result of this tool call c1 was saved in the filesystem at this path: /large_tool_results/c1
...
1  2026-11-28T10:00:00 web GET /api/items/0 200 12ms
...
... [2990 lines truncated] ...
...
3000  2026-11-28T10:49:59 web GET /api/items/2999 200 12ms

--- [ls] 26 chars in context
['/large_tool_results/c1']
--- [grep] 84 chars in context
/large_tool_results/c1:
  3000: 2026-11-28T10:49:59 web GET /api/items/2999 200 12ms
file in state: /large_tool_results/c1 157889 chars

The full 157,889 characters are safe in a file. The message tells the model to read it with offset and limit, and grep found the exact line it needed. We counted tokens with tiktoken's o200k_base encoding, a stand-in, since every model's tokenizer differs:

Tokens in context for one big tool result (o200k_base count)
Raw tool output76999Offloaded preview436
Data from the sources listed below.

Without offloading, every later model call in that run would resend about 77,000 tokens of logs. With it, the cost is 436 tokens plus whatever slices the model chooses to read.

Sandbox backends add one more tool

All four backends above only store files. None of them can run code. The execute tool is registered on every deep agent, but the library hides it from the model when the backend cannot run commands. A backend that implements SandboxBackendProtocol adds execute for shell commands, and the file tools then work inside that sandbox. Running model-written code is a different risk from writing files, so it gets its own part: Part 10 builds a sandbox backend on gVisor and measures what the isolation costs.

Which backend to pick

  • Scratch work for one task: StateBackend, the default.
  • Files a human or a build tool must open: FilesystemBackend with virtual_mode=True, plus permissions.
  • Memory across threads and users: StoreBackend with a namespace per user.
  • A real agent: CompositeBackend with StateBackend as the default and routes for the rest.
  • Running code: a sandbox backend, never FilesystemBackend on your own machine.

Next, Part 6 uses this shared filesystem as the hand-off point between a main agent and its subagents.

Try this

bash
python -m venv .venv && . .venv/bin/activate
pip install deepagents==0.7.42 langgraph==1.2.24 tiktoken
python -c "import deepagents, inspect; from deepagents.middleware.filesystem import FilesystemMiddleware as F; print(inspect.signature(F.__init__))"
python -c "from deepagents.backends import CompositeBackend, StateBackend, StoreBackend, FilesystemBackend; print('backends ok')"
python -c "import deepagents, pathlib; p = pathlib.Path(deepagents.__file__).parent / 'middleware' / 'filesystem.py'; print([l.strip() for l in p.read_text().splitlines() if 'tool_token_limit_before_evict: int' in l])"

Sources