跪拜 Guibai
← All articles
JavaScript · LangChain · DeepSeek

From createAgent to DeepAgents: Middleware, Virtual File Permissions, and Subagents in Node.js

By YIAN ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

Most agent tutorials stop at a single tool call. This one lays out the runtime machinery—middleware ordering, permission denials, subagent isolation, and checkpointing—that determines whether an agent survives contact with a production codebase.

Summary

This guide starts with the bare `createAgent` loop and then adds middleware hooks one by one: logging model calls, rewriting system prompts inside `wrapModelCall`, short-circuiting before the model runs, and wrapping tool results with `Command` state updates. Each hook is placed in the lifecycle, and the article is careful about state versus context, hook ordering, and preserving `tool_call_id` when rebuilding ToolMessages.

From there it moves into DeepAgents: a pre-assembled harness that adds a virtual filesystem with path-based permission rules, a `virtualMode` backend that hides real paths, and subagents that default to isolated context. The closing sections cover production boundaries: recursion limits, retry semantics, prompt-as-policy traps, structured output failure handling, middleware tests, and a decision table for when to use `createAgent`, DeepAgents, or an explicit LangGraph graph.

Takeaways
— createAgent wraps a loop: take messages, call the model, execute any tool calls, append results, and repeat until the model returns no tool calls.
— beforeModel runs before every model call, not once per agent run; afterAgent and beforeAgent are the only invoke-level hooks.
— stateSchema persists across steps and with a Checkpointer per thread; contextSchema is read-only for a single run and never persists automatically.
— Middleware order is business logic when multiple wrappers mutate messages or system prompts, so fix the order and write tests.
— wrapModelCall can modify the request (including systemMessage), switch models, filter tools, cache, or retry; it should not hold domain tools.
— Short-circuiting in beforeModel requires canJumpTo declaration and returning an AIMessage plus jumpTo: 'end' to make the message the final answer.
— wrapToolCall can return a Command to update messages, custom state fields, and routing in one step.
— When replacing a ToolMessage inside wrapToolCall, preserve the original tool_call_id or the next model call may fail format validation.
— A simple +1 counter is unreliable with parallel tool calls; use an external metrics system, LangGraph reducers, or an event list.
— Filesystem permissions check rules in order; the first matching operation-plus-path rule wins, and no match defaults to allow, so a global deny fallback is required.
— virtualMode makes the model see '/' as the root and maps real paths into the workspace directory, so prompts stay stable across machines.
— FilesystemBackend handles actual file access; createFilesystemMiddleware handles tool registration and permission checks.
— Path permissions do not constrain a backend's execute command; explicitly disable execute or rely on a real sandbox.
— DeepAgents subagents default to isolated mode, which sees only the task description and returns one result; fork mode inherits the parent conversation at higher token cost.
— Subagent permissions replace, not merge, parent permissions; declare the full whitelist, blacklist, and fallback.
— recursionLimit is a circuit breaker, not a tuning knob; pair it with model/tool call budgets, timeouts, and cancellation.
— Prompts are soft constraints; real safety comes from tool exposure, middleware policy checks, virtual roots, fallback denies, and sandboxes.
— Long-term facts belong in Store; current task state belongs in Agent State; large artifacts belong in the filesystem; don't put everything in messages.
— Write tests for middleware covering hook timing, short-circuit final messages, tool_call_id preservation, ordering, state merging, and parallel reliability.
— The decision table: simple Q&A uses direct model calls, few-tool custom agents use createAgent, complex long tasks use createDeepAgent, and deterministic workflows use explicit LangGraph graphs with agents only for open-ended nodes.
Conclusions

Middleware order becomes business logic when multiple wrappers mutate messages or system prompts, so tests should pin the order.

The article treats 'prompt is not a permission system' as a core principle: real safety comes from tool exposure, policy checks in middleware, and sandboxing.

DeepAgents doesn't replace LangGraph; it is a pre-assembled harness that still compiles to a native LangGraph agent, so Checkpointer, Store, LangSmith, and streaming remain available.

The isolated versus fork subagent distinction reflects a token-cost tradeoff: isolation keeps the main context small but forces self-contained task descriptions.

Most of what the article calls 'production boundaries' are not agent-specific; they are the usual distributed-systems concerns of retry semantics, idempotency, and audit, applied to a model-driven loop.

Concepts & terms
Middleware (LangChain)
Interceptors inserted into the agent lifecycle that can read/update state, rewrite model requests, wrap tool calls, short-circuit, or route. Hooks include beforeAgent, beforeModel, wrapModelCall, afterModel, wrapToolCall, and afterAgent.
stateSchema vs contextSchema
stateSchema defines agent state that can be modified by hooks and persists across steps (with a Checkpointer). contextSchema defines read-only external context passed in by the host application for a single run; it does not persist automatically.
wrapModelCall
A middleware hook that wraps each model call. It receives the request and a handler; it can modify the system message, switch models, filter tools, cache, or retry before calling the handler.
wrapToolCall
A middleware hook that wraps each tool execution. It can inspect arguments, enforce permissions, clean results, and return a Command to update messages, state, and routing.
virtualMode (FilesystemBackend)
A DeepAgents setting that maps a real directory to a virtual root '/'. The model sees only the virtual paths, hiding server real paths and confining file operations to the workspace.
isolated vs fork subagent mode
Isolated subagents only see the task description and return one result, keeping the main context small. Fork subagents inherit the parent conversation for deeper background work but cost more tokens.
Checkpointer
A LangGraph component that saves the graph execution state per thread, enabling human interrupts, resumption, and multi-turn conversation recovery.
Store
A LangGraph component for cross-thread, long-term storage of stable facts like user preferences or organizational knowledge, distinct from thread-local Checkpointer state.
Source: juejin.cn ↗ Google Translate ↗ Backup ↗