From createAgent to DeepAgents: Middleware, Virtual File Permissions, and Subagents in Node.js
Practical JavaScript / Node.js guide based on LangChain 1.6, LangGraph 1.7, and DeepAgents 1.16
Foreword: Why "can write an Agent" and "can deliver an Agent" are two different things
If you take a chat model plus a few tools to build a "check weather" or "check time" demo, many frameworks can do it in a dozen lines of code.
But complex agents quickly run into another set of problems:
- When should the model stop?
- If a tool call fails, should it retry?
- How do you correctly splice the messages generated by multiple tool calls back into the context?
- What if the conversation is too long or the tool returns content that is too large for the context window?
- If a task needs to be planned first and then executed step by step, where does execution state live?
- Which files can be read, which can only be written, and which operations must be denied?
- How does the main agent hand off independent tasks to subagents without polluting the main context?
- In production, how do you observe model call counts, tool latency, failure reasons, and interrupted recovery?
If you implement all of these from scratch, you will spend a lot of time on state management, loop routing, persistence, context compression, and permission boundaries.
The relationship between LangChain, LangGraph, and DeepAgents can be intuited with the following diagram:
Business Agent
|
v
DeepAgents Harness
Planning / File Workspace / Subagents / Summary Compression / Memory / Permissions
|
v
LangChain Agent Abstraction
createAgent / messages / model / tools / middleware
|
v
LangGraph Runtime
State Machine / Conditional Routing / Loops / Checkpointer / Store / Streaming Execution
This is not a strict four-layer inheritance relationship, but a cognitive model split by "responsibility":
- LangChain provides AI application building blocks: models, messages, tools, structured output,
createAgent, and Middleware. - LangGraph provides a stateful workflow runtime: state channels, nodes, edges, conditional routing, loops, persistence, and human interrupts.
- DeepAgents sits on top of LangChain Agent and LangGraph to provide a "batteries-included" Agent Harness that pre-packages complex capabilities such as file system, subagents, and summary compression.
- Business Agents only need to combine domain tools, business prompts, permission policies, and acceptance logic.
This article does not stop at conceptual explanations. We start from the simplest createAgent, then gradually add Middleware, state metrics, context injection, request interception, tool wrapping, move into DeepAgents' virtual file system and subagents, and finally discuss the boundaries that need to be filled in for production deployment.
The examples in this article use Node.js ESM and can be saved directly as .mjs files to run.
1. Set up the minimal runtime environment
1.1 Install dependencies
The core dependencies for the examples in this article are:
{
"type": "module",
"dependencies": {
"@langchain/langgraph": "^1.7.4",
"@langchain/openai": "^1.8.4",
"deepagents": "^1.16.5",
"dotenv": "^18.0.10",
"langchain": "^1.6.6",
"zod": "^4.6.7"
}
}
Installation command:
pnpm add langchain @langchain/langgraph @langchain/openai deepagents dotenv zod
DeepAgents uses the LangChain runtime packages as peer dependencies, so on the application side you should try to keep only one version of these packages to avoid problems caused by duplicate installs, such as instanceof, message type, or Command type inconsistencies.
1.2 Configure the model
In your local .env:
MODEL_NAME=your-model-name
OPENAI_API_KEY=your-api-key
OPENAI_BASE_URL=https://your-compatible-endpoint/v1
A reusable model initialization:
import "dotenv/config";
import { ChatOpenAI } from "@langchain/openai";
export const model = new ChatOpenAI({
model: process.env.MODEL_NAME,
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: process.env.OPENAI_BASE_URL,
},
temperature: 0,
});
If your service is compatible with the OpenAI Chat Completions protocol, you usually only need to replace baseURL, the model name, and the key.
But note: as long as the agent needs tool calling, the model itself must correctly support tool calling. A model that can chat does not mean it can reliably produce well-formed tool calls.
2. createAgent: wrapping the minimal agent loop
2.1 An agent that actually calls tools
First define a time tool:
import { z } from "zod";
import { createAgent, tool, HumanMessage } from "langchain";
import { model } from "./model.mjs";
const getCurrentTime = tool(
() => new Date().toISOString(),
{
name: "get_current_time",
description: "Return the current UTC time as an ISO 8601 string",
schema: z.object({}),
}
);
const agent = createAgent({
model,
tools: [getCurrentTime],
systemPrompt: "You are a rigorous assistant. When real-time information is needed, prefer to call the tool.",
});
const result = await agent.invoke({
messages: [new HumanMessage("What time is it now? Please return UTC time.")],
});
console.log(result.messages.at(-1)?.content);
The most important thing in this code is not invoke, but what createAgent does for you behind the scenes:
- Takes the initial
messages; - Passes the
systemPromptand tool definitions to the model; - Calls the model;
- Checks whether the returned
AIMessagecontainstool_calls; - If there are tool calls, executes the corresponding tool and generates a
ToolMessage; - Puts the tool results back into the message history and calls the model again;
- Ends when the model no longer requests tools.
This loop can be represented as pseudocode:
messages = user input
while true:
response = model(messages, tools, system_prompt)
messages += response
if response.tool_calls is empty:
break
for tool_call in response.tool_calls:
tool_message = execute(tool_call)
messages += tool_message
return messages
The real implementation also handles parallel tools, exceptions, routing, limits, and persistence, but the core loop is exactly this.
2.2 Key parameters of createAgent
| Parameter | Purpose | Common misconception |
|---|---|---|
model |
Chat model or model identifier | Tool-enabled agents must use a model that supports tool calling |
tools |
Top-level tool list | Tool names cannot be duplicated, parameter schemas must be clearly described |
systemPrompt |
Static system prompt | Dynamic context is better placed in Middleware |
middleware |
Lifecycle extension | Not a synonym for "tool list"; it can change requests, results, state, and routing |
stateSchema |
Custom persistent state | State is preserved across steps and invocations, but needs to be designed by business logic |
contextSchema |
Single-run context | Context is read-only and is not automatically persisted |
responseFormat |
Structured output | Suitable when the final result needs to be consumed by a program |
checkpointer |
Run checkpoints | Very important for human interrupts, resumption, and multi-turn sessions |
store |
Cross-thread long-term storage | Different from state within a single conversation |
The most effective way to understand createAgent is to see it as an "extensible ReAct loop", not a black box.
The outer developer only needs to provide the model, tools, and prompt. When you need logging, permissions, retries, caching, routing, or context compression, you insert them into the loop through Middleware.
3. What exactly is Middleware
3.1 Understanding it with the "onion model"
Middleware can be understood as interceptors inserted into the agent lifecycle:
User request
|
├─ beforeAgent
|
├─ model call loop
| ├─ beforeModel
| ├─ wrapModelCall pre-processing
| ├─ actual model call
| ├─ wrapModelCall post-processing
| └─ afterModel
|
├─ if there are tool_calls
| └─ wrapToolCall pre-processing
| ├─ actual tool execution
| └─ wrapToolCall post-processing
|
└─ afterAgent
When multiple wrapModelCall or wrapToolCall coexist, their behavior resembles the "onion model": the outer layer enters first, the inner layer enters later; on return, the order reverses.
Therefore, the order of Middleware is itself part of the business logic. Especially when multiple middlewares modify messages, system prompts, or end the flow early, you should fix the order and write tests.
3.2 Lifecycle hook quick reference
| Hook | Timing | Typical use |
|---|---|---|
beforeAgent |
Once at the start of each agent run | Initialization, authentication, injecting initial state |
beforeModel |
Before every model call | Message validation, input interception, context organization |
wrapModelCall |
Wraps every model call | Change prompt, switch model, change tools, cache, retry |
afterModel |
After model returns, before tool execution | Validate output, count calls, fix tool arguments |
wrapToolCall |
Wraps every tool execution | Permission checks, argument cleaning, result wrapping, error recovery |
afterAgent |
Once at the end of each agent run | Aggregate metrics, save results, clean up resources |
Several common misconceptions need correction:
beforeModelruns before each model call, not just once for the entire agent.afterModelruns after the model returns, but before tools execute.wrapToolCallis not "swapping in a different tool"; it intercepts the tool call request and decides whether to invoke the originalhandler.beforeAgentandafterAgentare the start and end at eachinvokegranularity.
3.3 The difference between stateSchema and contextSchema
Middleware can extend state and also declare read-only context:
import { z } from "zod";
import { createMiddleware } from "langchain";
const metricsMiddleware = createMiddleware({
name: "MetricsMiddleware",
stateSchema: z.object({
modelCallCount: z.number().default(0),
}),
contextSchema: z.object({
tenantId: z.string(),
userExpertise: z.enum(["beginner", "expert"]).default("beginner"),
}),
});
The difference:
stateSchemais part of the agent state, can be modified by hooks, flows with the LangGraph state; with a Checkpointer configured, it can be persisted per thread.contextSchemadescribes the external context of the current run, is read-only, and does not automatically become persistent cross-turn state.
In short:
Needs to be written, accumulated, or restored by the Agent -> stateSchema
Passed in by the host application and read-only -> contextSchema
For example, "how many times the model was called in this turn" fits state; "current tenant, current user permissions, user preferences" fits context.
4. Practice 1: Using Middleware for observability
Start with the most common need: log the start of the agent, each model call, the model's returned content, and the final call count.
import { z } from "zod";
import {
createAgent,
createMiddleware,
HumanMessage,
} from "langchain";
import { model } from "./model.mjs";
const loggingMiddleware = createMiddleware({
name: "LoggingMiddleware",
stateSchema: z.object({
modelCallCount: z.number().default(0),
}),
beforeAgent: (state) => {
console.log("[Logging] Agent started, initial message count:", state.messages.length);
},
beforeModel: (state) => {
console.log(
`[Logging] About to call model, message count: ${state.messages.length}, ` +
`previous model calls: ${state.modelCallCount}`
);
},
afterModel: (state) => {
const lastMessage = state.messages.at(-1);
const preview =
typeof lastMessage?.content === "string"
? lastMessage.content.slice(0, 280)
: JSON.stringify(lastMessage?.content ?? "").slice(0, 280);
console.log("[Logging] Model returned:", preview);
return {
modelCallCount: state.modelCallCount + 1,
};
},
afterAgent: (state) => {
console.log(
`[Logging] Agent finished, total model calls: ${state.modelCallCount}`
);
},
});
const agent = createAgent({
model,
tools: [],
systemPrompt: "You are a concise, rigorous assistant.",
middleware: [loggingMiddleware],
});
const result = await agent.invoke({
messages: [
new HumanMessage("Explain in one sentence what LangChain Middleware is."),
],
});
console.log("Final reply:", result.messages.at(-1)?.content);
console.log("Call count in returned state:", result.modelCallCount);
Two points worth noting here.
First, z.number().default(0) gives the middleware state a default value, so you don't need to manually pass modelCallCount when calling invoke.
Second, the object returned by afterModel is merged into the agent state, so the final invoke result can also read modelCallCount.
If you treat Middleware as merely a "logging decorator", you underestimate it. The state updates it returns, exceptions it throws, and routing commands it issues all actually change agent behavior.
5. Practice 2: Dynamically rewriting system context with wrapModelCall
Suppose the same agent needs to attach different rules in different business scenarios. The most direct way is to statically change systemPrompt, but that rebuilds the agent for every request.
A more flexible approach is to modify the model request inside wrapModelCall:
import { createMiddleware } from "langchain";
const addContextMiddleware = createMiddleware({
name: "AddContextMiddleware",
wrapModelCall: async (request, handler) => {
console.log("[Context] Appending business rules to this model request");
return handler({
...request,
systemMessage: request.systemMessage.concat(
"\n\nAdditional rule: state the conclusion first, then explain the reasoning in one sentence."
),
});
},
});
request.systemMessage is a SystemMessage; concat creates a new system message. Do not directly mutate the message object contents; using a new request object is safer and easier to reason about.
This hook can also do many other things:
- Switch models based on
request.runtime.context; - Redact user input;
- Filter available tools by tenant;
- Trim messages when close to the context limit;
- Retry with a fallback model after model failure;
- Check cache hits before the call.
One principle: wrap functions handle cross-cutting logic; core business tools should not be stuffed into Middleware. Domain actions should still be Tools; Middleware controls how those actions are executed.
6. Practice 3: Short-circuiting before the model call
Some requests should never reach the model. For example, if sensitive markers appear in the input, the user lacks permission, or the system is under maintenance, you want to return directly without invoking the model.
import {
AIMessage,
createMiddleware,
} from "langchain";
const blockedContentMiddleware = createMiddleware({
name: "BlockedContentMiddleware",
beforeModel: {
canJumpTo: ["end"],
hook: (state) => {
const lastMessage = state.messages.at(-1);
const text =
typeof lastMessage?.content === "string"
? lastMessage.content
: JSON.stringify(lastMessage?.content ?? "");
if (/\bBLOCKED\b/i.test(text)) {
console.log("[Blocked] Interception marker detected, skipping model call");
return {
messages: [
new AIMessage("This request has been intercepted by Middleware and cannot be processed."),
],
jumpTo: "end",
};
}
},
},
});
Three details here.
First, canJumpTo: ["end"] is the middleware declaring to the runtime which targets it might jump to. Without the declaration, returning a corresponding jumpTo is unreliable.
Second, merely returning an AIMessage is not always enough. To make that message the final answer the caller sees, you need to write it back into messages and explicitly jump to the end node.
Third, the original demo's input was Block, but the condition checks includes("BLOCKED"), which do not match, so that example never actually triggers interception. This article uniformly uses BLOCKED and ignores case. Real business logic should also handle whitespace, invisible characters, and synonyms, and ideally judge on structured fields rather than natural-language keywords that are easy to miss.
This kind of short-circuit logic fits well in beforeModel, because it ends the flow before the model incurs cost.
7. Practice 4: Counting and wrapping tool results with wrapToolCall
Middleware can not only modify model requests, but also wrap every tool call.
This example does four things:
- Registers a time tool directly on the Middleware;
- Logs tool name and arguments;
- Appends a uniform marker after the tool result;
- Updates the tool invocation count and message state via
Command.
import { z } from "zod";
import { Command } from "@langchain/langgraph";
import {
createAgent,
createMiddleware,
HumanMessage,
ToolMessage,
tool,
} from "langchain";
import { model } from "./model.mjs";
const getCurrentTime = tool(
() => new Date().toISOString(),
{
name: "get_current_time",
description: "Return the current UTC time as an ISO 8601 string",
schema: z.object({}),
}
);
const extendedToolsMiddleware = createMiddleware({
name: "ExtendedToolsMiddleware",
stateSchema: z.object({
toolInvocationCount: z.number().default(0),
}),
// Middleware can also inject tools into the Agent
tools: [getCurrentTime],
wrapToolCall: async (request, handler) => {
const toolName = request.tool?.name ?? request.toolCall.name;
console.log("[Tool] About to execute:", toolName, request.toolCall.args);
const result = await handler(request);
if (!ToolMessage.isInstance(result)) {
return result;
}
const wrappedResult = new ToolMessage({
content: `${result.content}\n[wrapToolCall] wrapped by Middleware`,
tool_call_id: result.tool_call_id,
name: result.name,
});
return new Command({
update: {
toolInvocationCount: request.state.toolInvocationCount + 1,
messages: [wrappedResult],
},
});
},
afterAgent: (state) => {
console.log(
`[Tool] Agent finished, total tool calls: ${state.toolInvocationCount}`
);
},
});
const agent = createAgent({
model,
// getCurrentTime is injected by Middleware, so this can be empty
tools: [],
systemPrompt: "You are an assistant. When real-time is needed, you must call the tool.",
middleware: [extendedToolsMiddleware],
});
const result = await agent.invoke({
messages: [new HumanMessage("Give me the current time")],
});
console.log(result.messages);
console.log("Tool call count:", result.toolInvocationCount);
The most notable thing in this example is Command.
A normal handler returns ToolMessage; if we return a custom Command, we can simultaneously update:
messages: the tool result the model will see in the next round;- custom state fields: such as call count, status labels, business IDs;
- routing information: in more complex scenarios, deciding the next node.
7.1 When replacing a ToolMessage, you must preserve tool_call_id
When you rebuild a ToolMessage inside wrapToolCall, be sure to preserve the original result's tool_call_id.
Because the model's previous AIMessage contains a tool call ID, the subsequent ToolMessage must use the same ID to match. Otherwise the next model request may directly fail with a format error, especially for services like OpenAI, Anthropic, and Gemini that are strict about tool-call pairing.
7.2 A simple +1 may not be reliable under parallel tool calls
The counting example above is suitable as an introduction. If the model returns multiple parallel tool calls in the same round, multiple execution branches may read the same old state and then write back count + 1, resulting in overwrites.
Production recommendations:
- Use an external metrics system to count by event;
- Use LangGraph reducers to merge concurrent state updates;
- Or append call records to a separate event list instead of relying on a read-modify-write of a single number.
This is also a typical trade-off in Middleware design: the closer the logic gets to runtime state, the more you must pay attention to concurrency and persistence semantics.
8. From createAgent to DeepAgents
At this point, createAgent + Middleware can already cover many single-agent needs.
But complex agents also run into file workspaces, task planning, subagents, context compression, long-term memory, and permission control. DeepAgents' value is that it packages these capabilities into a Harness.
DeepAgents is not a replacement for LangGraph, nor is it a black box that "automatically completes your business". It is more like a production-ready operating console prepared for complex agents.
8.1 A minimal DeepAgent
import { createDeepAgent } from "deepagents";
import { model } from "./model.mjs";
const agent = createDeepAgent({
model,
systemPrompt: "You are an assistant good at research and file organization.",
});
const result = await agent.invoke({
messages: [
{
role: "user",
content: "Research the core capabilities of LangGraph and write the results to summary.md.",
},
],
});
console.log(result.messages.at(-1)?.content);
createDeepAgent() still returns LangChain's ReactAgent form, compiled underneath into a LangGraph graph. So LangGraph capabilities such as Checkpointer, Store, Studio, LangSmith, and streaming execution remain usable.
The default assembly for local [email protected] roughly includes:
- File system Middleware;
- Subagent Middleware and the
tasktool; - Context summary Middleware;
- Tool-call and tool-result pairing repair Middleware;
- Optional Skills, Memory, prompt caching, human interrupts, and model refusal handling;
- A higher default recursion limit to support long tasks.
Different model Harness Profiles may add planning and other capabilities. To ensure business agents always have todo planning, you can explicitly add todoListMiddleware(), rather than relying only on the model's default behavior.
8.2 What DeepAgents saves you is not "prompts", but runtime complexity
| Capability | Problem it solves | Why implementing it yourself is painful |
|---|---|---|
| File system tools | Read/write working memory, generate intermediate artifacts | Path resolution, virtual root, size limits, permissions, symlinks |
| Task planning | Break down long tasks and track progress | Tool schema, state updates, parallel conflicts, when to stop |
| Subagents | Isolate context, process independent tasks in parallel | Task description, context inheritance, permission boundaries, result return |
| Summary compression | Context too long | Summary thresholds, retention window, old message offloading, recovery |
| Tool pairing repair | Fix missing or orphaned ToolMessage | Different models have different tool-call formats and strictness |
| Long-term memory | Save preferences and knowledge across sessions | Store, namespaces, loading timing, pollution control |
These capabilities are interrelated. Making a single file read/write tool is easy; making it work stably with state, permissions, context compression, and subagents is hard.
9. Practice 5: A permissioned virtual file workspace
The following code best demonstrates DeepAgents' value: the agent can operate on files like a /, but the real files are confined to a fixed directory.
import "dotenv/config";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { ChatOpenAI } from "@langchain/openai";
import {
createFilesystemMiddleware,
FilesystemBackend,
} from "deepagents";
import {
createAgent,
HumanMessage,
ToolMessage,
} from "langchain";
const model = new ChatOpenAI({
model: process.env.MODEL_NAME,
apiKey: process.env.OPENAI_API_KEY,
configuration: {
baseURL: process.env.OPENAI_BASE_URL,
},
temperature: 0,
});
const workspaceDir = path.join(
path.dirname(fileURLToPath(import.meta.url)),
"workspace"
);
fs.mkdirSync(workspaceDir, { recursive: true });
fs.writeFileSync(
path.join(workspaceDir, "secret.txt"),
"confidential: do not read",
"utf8"
);
// First matching rule wins; if none matches, the default is allow
const permissions = [
{
operations: ["read"],
paths: ["/secret.txt"],
mode: "deny",
},
{
operations: ["read", "write"],
paths: ["/notes/**", "/todo.md"],
mode: "allow",
},
{
operations: ["read", "write"],
paths: ["/**"],
mode: "deny",
},
];
const agent = createAgent({
model,
tools: [],
systemPrompt: `
You are a file organization assistant.
The workspace root path is /.
Only use ls, read_file, write_file, edit_file, glob, grep to operate on files.
All paths must start with /.
`,
middleware: [
createFilesystemMiddleware({
// Only expose the needed tools, disable execute and delete at the tool level
tools: ["ls", "read_file", "write_file", "edit_file", "glob", "grep"],
permissions,
backend: new FilesystemBackend({
rootDir: workspaceDir,
virtualMode: true,
}),
}),
],
});
const result = await agent.invoke(
{
messages: [
new HumanMessage(
"First read /secret.txt, then write the content to /todo.md, and explain whether it succeeded."
),
],
},
{
recursionLimit: 20,
}
);
console.log(result.messages);
const denied = result.messages.some(
(message) =>
ToolMessage.isInstance(message) &&
message.status === "error" &&
/permission denied/i.test(String(message.content))
);
console.log(denied ? "Permission check worked as expected" : "Expected permission denial not observed");
9.1 The significance of virtualMode
Setting:
new FilesystemBackend({
rootDir: workspaceDir,
virtualMode: true,
});
After this, the model sees a virtual root /, and actual paths map to inside workspaceDir.
The implications:
- The model does not need to know the server's real path;
- All file operations are constrained to the business workspace;
- Different users or tasks can mount different workspaces;
- Prompts are more stable and won't break when deployment machine paths change.
9.2 Real semantics of permission rules
The current version of file system permissions has several key rules:
- Only
readandwriteoperations are supported; - Rules are checked in declaration order;
- The first rule that matches both "operation type + path glob" takes effect;
- If no rule matches, the default is to allow;
- Paths are normalized first, and
FilesystemBackendalso checks the actual target of symlinks.
Therefore, production policies should usually be organized in this order:
Most specific deny rules
|
Explicit allow rules
|
Global fallback deny
Writing only "deny this file" without a fallback rule can leave many paths accessible by default.
9.3 Permission parameters should be on the Middleware, not the Backend
The sample source had a // permissions comment next to the FilesystemBackend constructor, but in the current API the actual permission check happens at:
createFilesystemMiddleware({
permissions,
backend: new FilesystemBackend({
rootDir: workspaceDir,
virtualMode: true,
}),
});
FilesystemBackend is responsible for actual file access; createFilesystemMiddleware is responsible for tool registration, path policy, and permission checks. The two have different responsibilities.
9.4 execute is another security boundary
File path permissions only constrain file system tools; they should not be mistaken for general sandbox permissions.
If the Backend supports command execution, execute may bypass path-declared read permissions. The current DeepAgents API explicitly warns that configuring path permissions on an executable backend creates a configuration risk. You should usually explicitly disable execute, or let a truly isolated sandbox and operating system permission system bear the security boundary.
DeepAgents' security principle is not "trust the model to follow the prompt", but "only give the model tools it is allowed to use, and enforce constraints at the tool and sandbox layer".
10. How to choose among files, state, and long-term memory
Complex agents often stuff everything into messages, and the context explodes. DeepAgents provides multiple storage layers, which should be distinguished by lifecycle.
| Storage | Lifecycle | Suitable for |
|---|---|---|
| Agent State | One thread, restorable with Checkpointer | Current task progress, counter fields, todo status |
StateBackend |
Default file state, usually flows with thread and checkpoints | Temporary files for the current session |
FilesystemBackend |
Real disk | Workspace artifacts, user uploads, large intermediate results |
StoreBackend |
Cross-thread, long-term | User preferences, organization knowledge, cross-session memory |
| Subagent context | Single delegation | Independent research, code analysis, batch searches |
A practical decision rule:
Content the next model turn must see verbatim -> messages
Materials the agent needs to read/write during work -> filesystem
Stable facts retained across tasks -> store / memory
Tasks that can be completed independently and whose process can be discarded -> subagent
Don't put dozens of pages of documents directly into every round of messages. A better practice is to write them to files and let the model read them on demand via grep, glob, and read_file.
Similarly, don't treat long-term user preferences as current task state. Long-term facts should go into Store or memory files; the tenant information needed for the current run can be passed via contextSchema.
11. Practice 6: Isolating context with subagents
When the main agent handles all tasks, two problems commonly appear:
- The research process produces a large number of intermediate messages, bloating the main context quickly;
- Multiple independent tasks execute serially, wasting time.
The core value of subagents is giving independent tasks their own context window and only returning the final result to the main agent.
import { z } from "zod";
import { createDeepAgent } from "deepagents";
import { model } from "./model.mjs";
import { webSearch } from "./tools/web-search.mjs";
const researcher = {
name: "researcher",
description:
"Responsible for researching complex topics. The input must be complete enough, and the output is a structured summary and list of sources.",
systemPrompt: `
You are a research assistant.
First break down the problem, then search for materials, and return only conclusions, key evidence, and sources.
Do not repeat the search process.
`,
tools: [webSearch],
responseFormat: z.object({
summary: z.string(),
keyPoints: z.array(z.string()),
sources: z.array(z.string()),
confidence: z.number().min(0).max(1),
}),
};
const agent = createDeepAgent({
model,
tools: [webSearch],
subagents: [researcher],
systemPrompt: `
You are the main coordinating agent.
Handle simple tasks that can be completed independently directly.
When large amounts of search or multiple independent research tasks are needed, use the task tool to delegate to the appropriate subagent.
`,
});
const result = await agent.invoke({
messages: [
{
role: "user",
content:
"Research DeepAgents' file system, subagent, and context compression capabilities, give conclusions for each, and summarize.",
},
],
});
console.log(result.messages.at(-1)?.content);
Here the task tool is automatically provided by the SubAgent Middleware. The main model delegates through two key fields:
description: the complete task description;subagent_type: the target subagent name.
11.1 The difference between isolated and fork
Currently DeepAgents subagents default to isolated mode:
- They only see the task description of this delegation;
- They do not see the main agent's full conversation;
- Intermediate processes stay in their own context;
- They return one result when finished.
The other mode, fork, inherits the parent conversation, suitable for background tasks that "continue based on the current discussion". But fork copies the context, which increases token cost and cache miss risk, so it should not be the default.
11.2 Subagent task descriptions must be self-contained
In isolated mode, a call like this is meaningless:
"Continue researching the question from earlier."
Because the subagent does not know what "the question from earlier" is. A good task description should include background, goal, input, constraints, and output format.
11.3 Subagent permissions are replaced, not merged
This is an easy pitfall:
- If a subagent does not declare
permissions, it inherits the parent agent's permissions; - If it declares
permissions, those rules fully replace the parent agent's permissions, rather than being layered on top.
So when configuring permissions for a subagent separately, you need to write out the complete whitelist, blacklist, and fallback rules it needs.
12. How DeepAgents' default runtime stack integrates with LangGraph
Because createDeepAgent ultimately returns a native LangGraph agent, you can plug into existing runtime capabilities.
12.1 Checkpointer: supports recovery and human interrupts
const agent = createDeepAgent({
model,
checkpointer: true,
interruptOn: {
send_email: {
allowedDecisions: ["approve", "edit", "reject"],
},
},
});
High-risk tools should not rely only on "prompts reminding the model to be cautious". A more reliable approach is:
- Wrap dangerous actions into explicit tools;
- Require human approval in
interruptOn; - Use Checkpointer to save the graph state before the interrupt;
- After approval or parameter edits, resume from the original thread.
Human interrupts are not a logging feature; they are part of the workflow. The business needs to define who can approve, what to do on approval timeout, and what the alternative path is after rejection.
12.2 Store: cross-session long-term memory
checkpointer is more about "how to resume the same conversation thread", while store is more about "how to share long-term facts across different threads".
A typical division:
thread_id = current session
checkpointer = execution context of this session
store = long-term knowledge at user, organization, or project level
filesystem = workspace for this task
Don't persist everything. Long-term memory needs write policies, deduplication policies, expiration policies, and deletion capabilities, otherwise the agent will treat stale facts as current facts.
12.3 Streaming execution and observability
DeepAgents can use LangGraph's streaming interface, or its more agent-oriented projection interface to observe messages, tool calls, and subagents.
For production systems, at minimum you should record:
- Model call counts and tokens;
- Each tool call's input, output, latency, and errors;
- Subagent delegation tasks and final results;
- Interrupt, resume, and rejection records;
- Recursion step count and context compression events;
- Structured output validation failures;
- Business dimensions like tenant, user, and task.
It's recommended to use LangSmith or an existing OpenTelemetry system for unified tracing, rather than only console.log in Middleware.
13. Several boundaries that must be filled in for production
13.1 Use execution limits to prevent infinite loops
recursionLimit is the circuit breaker for graph runs, not a performance tuning knob.
Introductory examples can set it small:
const result = await agent.invoke(
{ messages: [new HumanMessage("Complete the task")] },
{ recursionLimit: 20 }
);
DeepAgents sets a large default recursion limit for long tasks, but the business should still combine model call limits, tool call limits, timeout, and cancellation signals into a total budget.
13.2 Distinguish "model failure" from "tool failure"
Retry strategies for model calls differ from those for tool execution:
- Rate limiting and network jitter suit model retries;
- Retrying the same tool after parameter validation failure usually makes no sense;
- Retrying after a temporary file read failure can work;
- Non-idempotent tools like payment, email, or delete must not be blindly retried.
Retries need a count, backoff, and idempotency keys.
13.3 Prompts are not a permission system
The following is only a "soft constraint":
Please do not read secret.txt.
Real constraints include at least:
- Do not expose tools the model does not need;
- Perform policy checks in
wrapToolCallor the filesystem Middleware; - Use a virtual root directory;
- Set explicit fallback
denyin file permissions; - Put command execution in an isolated sandbox;
- Enable human approval for high-risk operations;
- Inject secrets server-side, never into the model context.
13.4 Don't stuff all context into state
"Can be persisted" does not mean "should be persisted".
Large files, binary content, repeated tool returns, and intermediate search results belong in the file system. Only the summaries and references truly needed for the next reasoning step should stay in message history.
13.5 Define failure strategies for structured output
Structured output is great for feeding agent results to downstream programs, but the model does not guarantee it will always match the schema perfectly.
The business needs to decide:
- How many retries after validation failure;
- Whether to return partial results;
- Whether to enter a manual processing queue;
- Whether to log raw output for analysis;
- Whether the fallback model supports the same output format.
13.6 Write tests for Middleware
Middleware often carries security, budget, and routing logic, and cannot rely only on manual observation of logs.
At minimum, cover:
- Whether hooks execute in the expected rounds;
- Whether the final message after short-circuiting is correct;
- Whether
tool_call_idis preserved in tool results; - Whether the order of multiple Middleware matches expectations;
- Whether state updates are merged correctly;
- Whether exceptions are incorrectly swallowed;
- Whether counters and permissions remain reliable under parallel actions.
14. When to use createAgent and when to use DeepAgents
A simple decision table:
| Scenario | Recommended approach |
|---|---|
| Single-turn Q&A, text classification | Call the model directly |
| Few tools, single agent, strong customization | createAgent |
| Tools + budget + logging + permission policy | createAgent + Middleware |
| Long tasks, file workspace, context compression | createDeepAgent |
| Independent research, parallel tasks, isolated contexts | DeepAgents subagents |
| High-risk actions requiring human approval | Agent + Checkpointer + HITL |
| Highly deterministic business processes | Explicit LangGraph graph, Agent only handles open-ended nodes |
| Extremely high compliance/audit requirements | LangGraph + external policy engine + sandbox + audit storage |
A common misconception is that as long as a task is complex, the agent should decide everything on its own.
A better design is usually hybrid:
- Fixed, repeatable, highly audited steps are done by LangGraph nodes or ordinary code;
- Steps that need natural language understanding, dynamic tool selection, or result synthesis are given to the Agent;
- Dangerous boundaries are enforced via permissions, approval, and sandboxing;
- Acceptance is done by independent code or rules, not by letting the same model verify its own correctness.
15. A recommended code organization approach
Writing all logic in a single index.mjs is only suitable for demos. For production, split it like this:
src/
├─ model.mjs
├─ agents/
| ├─ research-agent.mjs
| └─ workspace-agent.mjs
├─ middleware/
| ├─ logging.mjs
| ├─ guardrails.mjs
| └─ metrics.mjs
├─ tools/
| ├─ search.mjs
| └─ database.mjs
├─ policies/
| └─ filesystem-permissions.mjs
├─ runtime/
| ├─ checkpointer.mjs
| └─ store.mjs
└─ index.mjs
Several principles:
- Centralize model configuration, avoid each agent reading environment variables separately;
- Keep permission policies as separate files for testing and auditing;
- Middleware holds only cross-cutting capabilities; domain actions live in Tools;
- Subagent
descriptionandsystemPromptshould be as explicit as API documentation; - Checkpointer, Store, and Backend lifecycles are created uniformly by the application runtime;
- Never hardcode secrets, tenant policies, or production paths in source code.
16. Final complete mental model
If you compress this entire article into a few sentences:
createAgentwraps a "model call, tool execution, message return" loop;- Middleware is the extension point inserted into this loop; it can read and update state, rewrite model requests, wrap tool results, short-circuit, and route;
- DeepAgents is a Harness on top of
createAgentand LangGraph, pre-combining complex capabilities like file system, subagents, and summary compression; - The essence of complex agents is not writing a longer prompt, but designing clear boundaries for state, tools, permissions, context, and recovery;
- Production ultimately needs systems that are observable, limitable, resumable, and auditable, not a task demo that happens to run occasionally.
Remember this division of labor:
LangChain gives building blocks
LangGraph gives runtime
DeepAgents gives assembly bench for complex agents
Middleware gives cross-cutting extensions
Tool gives domain capability
Policy gives security boundary
Tests give iteration confidence
Starting with createAgent helps you see the basic operating principles of an Agent. When files, planning, context compression, and subagents start appearing repeatedly, then introduce DeepAgents, so you keep controllability and avoid reinventing infrastructure.
The threshold for complex agents is often not "making the model call a tool once", but making it continuously complete tasks in an environment with boundaries, budget, memory, and recovery. Once you understand these boundaries, looking back at createAgent and Middleware, they are no longer an API checklist, but a clear cross-section for designing production-grade agents.
References
- LangChain JavaScript Agents
- LangChain JavaScript Middleware
- LangGraph JavaScript Overview
- Deep Agents JavaScript Overview
- Deep Agents JavaScript GitHub
Version note: The examples in this article are based on
[email protected],@langchain/[email protected],[email protected]. Agent frameworks are still evolving rapidly. After upgrading, prioritize checking the type definitions for Middleware hooks, permission configuration, and Backend APIs.