Skip to content

DeepAgentsJS 解读

项目信息

  • 项目名称:DeepAgentsJS
  • 项目描述:DeepAgentsJS 是 LangChain 开源的 TypeScript AI Agent 脚手架,基于 LangGraph 构建。
  • 项目地址:
  • 官方文档:

1. 项目概览

1.1 项目定位与核心价值

DeepAgentsJS 是一个"电池全含"(batteries-included) 的 AI Agent 脚手架——基于 LangGraph 构建的开箱即用型智能代理运行时框架。它是 LangChain 生态中的 TypeScript Agent 解决方案,与 Python 版 langchain-ai/deepagents 保持接口兼容。

解决的核心痛点

  1. Agent 开发门槛高:开发者需要手动编排提示词、工具调用、上下文管理等多层逻辑,DeepAgentsJS 将这些复杂性封装为开箱即用的中间件,一行代码即可启动完整 Agent。
  2. 长任务上下文丢失:长时间运行的任务会导致上下文窗口爆满,内置摘要中间件和文件系统后端自动将历史卸载到文件/存储中。
  3. 多 Agent 协作困难:子任务分发、上下文隔离、结果聚合是复杂工程,提供同步/异步子 Agent 中间件,支持隔离上下文窗口的层级化任务委派。

1.2 目标用户与使用场景

  • AI 应用开发者需要快速搭建具备文件操作、任务规划、子任务委派能力的 Agent 应用
  • LangChain/LangGraph 生态用户:希望利用熟悉的 LangGraph 图编译、流式传输、检查点等能力。
  • IDE/平台集成商:通过 ACP 协议将 DeepAgentsJS 集成到 Zed、JetBrains 等 IDE 中。
  • 开源贡献者:MIT 许可,完全开源可扩展。

1.3 核心技术亮点

能力说明
任务规划write_todos 工具用于任务拆解和进度追踪
文件系统7 个工具 (ls/read/write/edit/glob/grep/execute) 通过可插拔后端操作
子代理task 工具用于隔离上下文窗口的任务委派,支持同步/异步
智能默认值内置提示词和中间件立即可用
上下文管理基于摘要中间件的自动 token 监控和对话历史卸载
技能系统SKILL.md 文件驱动的可扩展技能加载
IDE 集成通过 ACP 协议支持 Zed、JetBrains 等 IDE
沙箱支持多种沙箱后端 (LangSmith/Daytona/Deno/Modal/QuickJS)

1.4 技术栈与选型对比

核心技术栈

层级技术用途
运行时Node.js / 浏览器TypeScript 6.0+
AI 框架LangChain 1.4+, LangGraph 1.3+Agent 创建、图编译、流式传输、检查点
类型系统TypeScript 6.0+, Zod 4.3+编译时 + 运行时双重验证
构建tsdown, oxlint, oxfmt打包、代码检查、格式化
测试Vitest 4.0+单元/集成测试
协议ACP 0.18+IDE-Agent 标准化通信

选型对比与权衡

决策点选择权衡分析
运行时平台LangGraph (而非直调 LLM API)获得图编译/流式/检查点能力,代价是 SDK 依赖
架构模式中间件模式 (类似 Koa.js 洋葱模型)高可扩展性和可组合性,相比硬编码更灵活
存储后端可插拔协议 V1/V2 双版本向后兼容,逐步引入新特性
IDE 集成ACP 协议 (非自定义协议)跨 IDE 兼容,一套实现支持多种编辑器
跨语言与 Python 版 1:1 接口兼容减少迁移成本,文档复用

2. 整体架构设计

2.1 架构概述

DeepAgentsJS 采用分层中间件架构,底层依赖 LangGraph 作为图执行引擎。整个系统分为五层:

  • 用户接口层createDeepAgent() API 和 ACP 协议服务端
  • 中间件层:可组合的中间件管道(文件系统、子代理、摘要、技能、记忆等)
  • 后端抽象层:BackendProtocol V1/V2,统一文件操作接口
  • 后端实现层:State/Store/Filesystem/Composite/ContextHub/Sandbox 等多种后端
  • 基础设施层:LangGraph(图编译/流式/检查点)、LangChain(Agent 创建/工具调用)

2.2 整体架构图

text
+------------------------------------------------------------------+
|                      用户接口层 (User API Layer)                    |
|  [createDeepAgent()]  <-->  [ACP Server (Zed/JetBrains/CLI)]      |
+-------------------------------+----------------------------------+
                                | (Agent Config + Middleware)
                                v
+------------------------------------------------------------------+
|                     中间件层 (Middleware Pipeline)                  |
|  +----------+  +----------+  +--------------+  +------------+     |
|  | FS Mid-  |  | SubAgent  |  | Summariza-  |  | Skills     |     |
|  | dleware  |  | Middleware|  | tion Middle- |  | Middleware  |     |
|  |          |  |           |  | ware         |  |            |     |
|  | ls/read/ |  | task()    |  | history      |  | SKILL.md   |     |
|  | write/   |  | sync+async|  | offloading   |  | loader     |     |
|  | edit/    |  | subagents |  | to backend   |  | injection  |     |
|  | glob/grep|  |           |  |              |  |            |     |
|  +-----+----+  +-----+-----+  +------+-------+  +-----+------+     |
|        |             |               |                 |            |
|  +-----+----+  +-----+-----+  +------+-------+  +-----+------+     |
|  | Memory    |  | PatchTool |  | Cache       |  | Custom      |     |
|  | Middleware|  | Calls Mid |  | Middleware   |  | Middleware  |     |
|  +----------+  +----------+  +--------------+  +------------+     |
+-------------------------------+----------------------------------+
                                | (BackendProtocol V1/V2)
                                v
+------------------------------------------------------------------+
|                    后端抽象层 (Backend Abstraction)                  |
|  +------------------------------------------------------------+   |
|  |              BackendProtocol V1 / V2 (Interface)            |   |
|  |  ls() | read() | write() | edit() | glob() | grep()        |   |
|  |  SandboxBackendProtocol: execute() | upload() | download()  |   |
|  +------------------------------------------------------------+   |
+-------------------------------+----------------------------------+
                                |
                                v
+------------------------------------------------------------------+
|                   后端实现层 (Backend Implementations)              |
|  +-----------+  +-----------+  +--------------+  +-----------+    |
|  | State     |  | Store     |  | Filesystem   |  | Composite  |    |
|  | Backend   |  | Backend   |  | Backend      |  | Backend    |    |
|  | (LangGraph|  | (LangGraph|  | (local disk) |  | (multi-BE  |    |
|  |  state)   |  |  store)   |  |              |  |  router)   |    |
|  +-----------+  +-----------+  +--------------+  +-----------+    |
|  +-----------+  +-----------+  +--------------+                   |
|  | ContextHub|  | LocalShell|  | LangSmith    |                   |
|  | Backend   |  | Backend   |  | Sandbox      |                   |
|  | (ctx hub  |  | (local    |  | (cloud       |                   |
|  |  service) |  |  shell)   |  |  sandbox)    |                   |
|  +-----------+  +-----------+  +--------------+                   |
+-------------------------------+----------------------------------+
                                |
                                v
+------------------------------------------------------------------+
|                基础设施层 (Infrastructure)                           |
|  [LangGraph] <--> [LangChain] <--> [Anthropic/OpenAI/...]        |
|  Graph compile   Agent create    Chat models                     |
|  Streaming       Tool calling    Prompt caching                  |
|  Checkpointing   State mgmt     Response format                  |
+------------------------------------------------------------------+

2.3 目录结构

shell
deepagentsjs/
├── .agents/                          # 【配置】Agent 自定义配置
├── .changeset/                       # 【配置】Changeset 版本发布管理
├── .github/                          # 【配置】CI/CD 工作流
├── .vscode/                          # 【配置】编辑器配置
├── evals/                            # 【工具集】评估与基准测试套件(18 组)
   ├── all/                          # 【工具集】全量综合评估
   ├── basic/                        # 【工具集】基础功能评估
   ├── external-benchmarks/          # 【工具集】外部基准对比
   ├── files/                        # 【工具集】文件操作评估
   ├── followup-quality/             # 【工具集】跟进质量评估
   ├── hitl/                         # 【工具集】Human-in-the-Loop 评估
   ├── memory/                       # 【工具集】记忆能力评估
   ├── memory-agent-bench/           # 【工具集】记忆 Agent 基准
   ├── memory-multiturn/             # 【工具集】多轮对话记忆评估
   ├── oolong/                       # 【工具集】Oolong 评估
   ├── skills/                       # 【工具集】技能系统评估
   ├── subagents/                    # 【工具集】子代理评估
   ├── summarization/                # 【工具集】摘要能力评估
   ├── tau2-airline/                 # 【工具集】航空场景评估
   ├── todos/                        # 【工具集】任务规划评估
   ├── tool-selection/               # 【工具集】工具选择评估
   ├── tool-usage-relational/        # 【工具集】工具使用关系评估
   └── README.md                     # 【配置】评估说明
├── examples/                         # 【配置】12 个示例项目
   ├── acp-server/                   # 【业务模块】ACP 服务端集成示例
   ├── async-subagent-server/        # 【业务模块】异步子代理服务端示例
   ├── async-subagents/              # 【业务模块】异步子代理示例
   ├── backends/                     # 【业务模块】自定义后端示例
   ├── hierarchical/                 # 【业务模块】层级代理示例
   ├── memory/                       # 【业务模块】记忆功能示例
   ├── repl/                         # 【业务模块】交互式 REPL 示例
   ├── research/                     # 【业务模块】深度研究 Agent 示例
   ├── sandbox/                      # 【业务模块】沙箱集成示例
   ├── skills/                       # 【业务模块】技能系统示例
   ├── skills-memory/                # 【业务模块】技能+记忆联合示例
   └── streaming/                    # 【业务模块】流式传输示例
├── internal/                         # 【工具集】内部工具
   └── eval-harness/                 # 【工具集】评估测试框架
       └── src/
           ├── deepagent.ts          # 【工具集】创建用于评估的 DeepAgent 实例
           ├── index.ts              # 【工具集】模块导出入口
           ├── matchers.ts           # 【工具集】LLM 输出断言匹配器(约 65KB)
           └── runners.ts            # 【工具集】评估执行器
├── libs/                             # 【核心基建】Monorepo 核心包
   ├── acp/                          # 【核心基建】ACP 协议服务端(IDE 集成)
   └── src/
       ├── acp-filesystem-backend.ts  # 【核心基建】代理 ACP 文件操作的沙箱后端
       ├── adapter.ts            # 【核心基建】ACP ↔ LangChain 消息格式适配
       ├── cli.ts                # 【核心基建】CLI 二进制入口(deepagents-acp)
       ├── index.ts              # 【核心基建】包导出入口
       ├── logger.ts             # 【工具集】结构化日志工具
       ├── server.ts             # 【核心基建】ACP Agent 服务端(41KB 主逻辑)
       └── types.ts              # 【核心基建】ACP 配置与类型定义
   ├── deepagents/                   # 【核心基建】Deep Agents 核心库
   └── src/
       ├── agent.ts              # 【核心基建】createDeepAgent() 主入口函数
       ├── backends/             # 【核心基建】可插拔存储后端系统
   ├── composite.ts      # 【核心基建】CompositeBackend — 多后端组合路由
   ├── context-hub.ts    # 【核心基建】ContextHubBackend — 上下文中心集成
   ├── filesystem.ts     # 【核心基建】FilesystemBackend — 本地磁盘后端
   ├── index.ts          # 【核心基建】后端模块 Barrel 导出
   ├── langsmith.ts      # 【核心基建】LangSmithSandbox — 云端沙箱后端
   ├── local-shell.ts    # 【核心基建】LocalShellBackend — 本地 shell 执行
   ├── protocol.ts       # 【核心基建】BackendProtocol V1/V2 定义与类型守卫
   ├── sandbox.ts        # 【核心基建】BaseSandbox — 沙箱抽象基类
   ├── state.ts          # 【核心基建】StateBackend — LangGraph 状态后端
   ├── store.ts          # 【核心基建】StoreBackend — LangGraph Store 后端
   ├── utils.ts          # 【工具集】后端工具函数(截断、格式化等)
   ├── v1/               # 【核心基建】V1 协议适配层(已弃用)
   └── v2/               # 【核心基建】V2 协议适配层(当前版本)
       ├── browser.ts            # 【核心基建】浏览器入口点(排除 Node 专用导出)
       ├── config.ts             # 【核心基建】配置管理(路径解析、设置创建)
       ├── errors.ts             # 【核心基建】ConfigurationError 错误类型
       ├── index.ts              # 【核心基建】主入口 Barrel(约 200 个导出)
       ├── middleware/           # 【核心基建】中间件系统(洋葱模型扩展点)
   ├── agent-memory.ts   # 【核心基建】Agent 记忆中间件(跨会话记忆)
   ├── async_subagents.ts # 【核心基建】异步子代理中间件(远程子代理)
   ├── cache.ts          # 【核心基建】Anthropic 缓存断点中间件
   ├── completion_callback.ts # 【核心基建】异步子代理完成回调中间件
   ├── fs.ts             # 【核心基建】文件系统中间件(ls/read/write/edit/glob/grep/execute)
   ├── index.ts          # 【核心基建】中间件模块 Barrel 导出
   ├── memory.ts         # 【核心基建】记忆中间件(会话内记忆)
   ├── patch_tool_calls.ts # 【核心基建】跨模型工具调用兼容修补
   ├── skills.ts         # 【核心基建】技能中间件(加载 SKILL.md 文件)
   ├── subagents.ts      # 【核心基建】同步子代理中间件(task 工具)
   ├── summarization.ts  # 【核心基建】摘要中间件(上下文历史卸载)
   ├── types.ts          # 【核心基建】中间件共享类型
   └── utils.ts          # 【工具集】中间件工具(appendToSystemMessage 等)
       ├── node.ts               # 【核心基建】Node.js 入口点
       ├── permissions/          # 【核心基建】文件系统权限控制
   ├── enforce.ts        # 【核心基建】权限强制执行逻辑
   ├── index.ts          # 【核心基建】权限模块导出入口
   └── types.ts          # 【核心基建】权限类型(Operation/Mode)
       ├── profiles/             # 【核心基建】Harness 模型配置系统
   ├── harness/          # 【核心基建】Profile 核心(类型、创建、序列化、注册表、合并)
   ├── index.ts          # 【核心基建】Profile 模块导出入口
   └── keys.ts           # 【核心基建】Profile 密钥验证
       ├── skills/               # 【核心基建】技能文件加载器
   ├── index.ts          # 【核心基建】技能模块导出入口
   └── loader.ts         # 【核心基建】listSkills / parseSkillMetadata
       ├── stream.ts             # 【核心基建】流式处理(SubagentTransformer)
       ├── testing/              # 【工具集】测试辅助工具
       ├── types.ts              # 【核心基建】完整类型系统(DeepAgent 泛型推导,约 23KB)
       ├── utils.ts              # 【工具集】模型检测工具(isAnthropicModel 等)
       └── values.ts             # 【核心基建】共享 LangGraph 状态值(filesValue)
   ├── providers/                    # 【业务模块】第三方沙箱提供者
   ├── daytona/                  # 【业务模块】Daytona 安全沙箱集成
   ├── deno/                     # 【业务模块】Deno 运行时沙箱
   ├── modal/                    # 【业务模块】Modal 云端沙箱
   ├── node-vfs/                 # 【业务模块】Node.js 虚拟文件系统沙箱
   └── quickjs/                  # 【业务模块】QuickJS 嵌入式沙箱
   └── standard-tests/               # 【工具集】沙箱标准一致性测试
       └── src/
           ├── adapter.ts            # 【工具集】沙箱适配器包装
           ├── index.ts              # 【工具集】模块导出入口
           ├── sandbox.ts            # 【工具集】沙箱核心测试逻辑
           ├── types.ts              # 【工具集】测试类型定义
           └── vitest.ts             # 【工具集】Vitest 插件工具
├── .codespellignore                  # 【配置】拼写检查忽略列表
├── .env.example                      # 【配置】环境变量模板
├── .gitattributes                    # 【配置】Git 换行符等属性
├── .gitignore                        # 【配置】Git 忽略规则
├── .nvmrc                            # 【配置】Node.js 版本指定
├── .oxfmtrc.jsonc                    # 【配置】Oxfmt 格式化规则
├── .oxlintrc.jsonc                   # 【配置】Oxlint 代码检查规则
├── LICENSE                           # 【配置】MIT 开源许可证
├── README.md                         # 【配置】项目说明(→ libs/deepagents/README.md 软链接)
├── README-CN.md                      # 【配置】中文翻译版 README(新增)
├── package.json                      # 【配置】Monorepo 根 workspace 配置
├── pnpm-lock.yaml                    # 【配置】pnpm 依赖锁定文件
├── pnpm-workspace.yaml               # 【配置】pnpm workspace 包路径定义
└── tsconfig.json                     # 【配置】TypeScript 根编译配置

3. 模块依赖与调用关系

3.1 全局入口与核心路由

逻辑说明:用户调用 createDeepAgent() 时,函数按固定顺序组装中间件管道,解析 Harness Profile 获取模型特定配置,检测 Anthropic 模型以启用缓存中间件,处理子代理规格(同步/异步分离),最终通过 LangChain 的 createAgent() 编译为 LangGraph 图。ACP 服务端则在此之上封装了 IDE 协议层。

调用拓扑

text
index.ts (Barrel Export)
 +-- createDeepAgent() ── agent.ts
      |
      +---> resolveHarnessProfile() ── profiles/harness/registry.ts
      |        识别模型 → 加载内置 profile → 合并用户 profile
      |
      +---> isAnthropicModel() ── utils.ts
      |        检测模型类型 → 决定是否注入缓存中间件
      |
      +---> [中间件组装] (按固定顺序)
      |    |
      |    +---> createFilesystemMiddleware() ── middleware/fs.ts
      |    |         注册 ls/read_file/write_file/edit_file/glob/grep/execute
      |    |
      |    +---> createSubAgentMiddleware() ── middleware/subagents.ts
      |    |         注册 task() 工具 → 隔离上下文子代理
      |    |
      |    +---> createSummarizationMiddleware() ── middleware/summarization.ts
      |    |         上下文卸载 → 写入 /conversation_history/{thread_id}.md
      |    |
      |    +---> createSkillsMiddleware() ── middleware/skills.ts
      |    |         加载 SKILL.md → 注入系统提示
      |    |
      |    +---> createMemoryMiddleware() ── middleware/memory.ts
      |    |         会话内记忆管理
      |    |
      |    +---> createPatchToolCallsMiddleware() ── middleware/patch_tool_calls.ts
      |    |         跨模型工具调用格式兼容
      |    |
      |    +---> [Anthropic 缓存] (条件注入)
      |    |         anthropicPromptCachingMiddleware()
      |    |         createCacheBreakpointMiddleware()
      |    |
      |    +---> [用户自定义中间件]
      |
      +---> createAgent() ── langchain
               编译为 LangGraph 图 → 返回 DeepAgent 实例

[ACP 路径]
deepagents-acp CLI ── cli.ts
 +---> DeepAgentsServer ── server.ts
      |
      +---> createDeepAgent() ── 同上路径
      +---> ACPFilesystemBackend ── 代理文件操作到 ACP 客户端
      +---> adapter.ts ── ACP 消息 ↔ LangChain 消息转换

3.2 核心业务实体与关联

实体定义

  • DeepAgent:编译后的 Agent 实例,包含完整的中间件管道、工具集和 LangGraph 图
  • Middleware:可组合的中间件单元,通过 createMiddleware() 创建,可注册工具、钩子函数
  • BackendProtocol:文件操作抽象接口,定义 ls/read/write/edit/glob/grep 等标准操作
  • SubAgent:隔离上下文窗口的子代理,通过 task() 工具调用,可为同步或异步
  • HarnessProfile:模型特定配置档案,包含提示词覆盖、工具描述、子代理配置
  • Skill:通过 SKILL.md 文件定义的技能元数据
  • Permission:文件系统操作权限控制(read/write/edit 等模式的 allow/deny 规则)

**实体引用拓扑 **:

text
[DeepAgent] 1 -----> N [Middleware]
                           |
                           +-- 1 -----> 1 [BackendProtocol] (通过 FilesystemMiddleware)
                           |
                           +-- 1 -----> N [SubAgent] (通过 SubAgentMiddleware)
                           |                |
                           |                +-- 1 -----> N [Middleware] (子代理中间件管道)
                           |                +-- 1 -----> N [Skill] (子代理专属技能)
                           |
                           +-- 1 -----> 1 [HarnessProfile] (通过 resolveHarnessProfile)
                           |                |
                           |                +-- 1 -----> 1 [GeneralPurposeSubagentConfig]
                           |                +-- N -----> N [ToolDescriptionOverride]
                           |
                           +-- 1 -----> N [Skill] (通过 SkillsMiddleware)
                           +-- N -----> N [Permission] (通过 FilesystemMiddleware)
                           +-- 1 -----> 1 [SummarizationConfig] (通过 SummarizationMiddleware)

[BackendProtocol] 1 <-----> N [BackendImplementation]
                                  |
                                  +-- StateBackend (LangGraph State)
                                  +-- StoreBackend (LangGraph Store)
                                  +-- FilesystemBackend (Local Disk)
                                  +-- CompositeBackend (Multi-BE Router)
                                  +-- ContextHubBackend (Context Hub Service)
                                  +-- LocalShellBackend (Local Shell)
                                  +-- LangSmithSandbox (Cloud Sandbox)
                                  +-- BaseSandbox (Abstract Class)

[ACP Server] 1 -----> 1 [DeepAgent]
[ACP Server] 1 -----> 1 [ACPFilesystemBackend]

4. 核心模块详解

模块一:Agent 工厂 (agent.ts)

  • 模块名称:createDeepAgent — 核心 Agent 创建工厂
  • 设计说明:这是整个库的"组装流水线"。采用工厂模式 + 构建器模式的变体——接收散列配置参数,按固定顺序组装中间件管道,解决工具名冲突检测、子代理规格归一化、Anthropic 模型检测与缓存注入等横切关注点。返回类型通过 TypeScript 泛型推导实现完整的类型安全。
  • 内部结构图 (plainText)
text
+------------------------------------------+
|          createDeepAgent(params)          |
+------------------+-----------------------+
                   |
     +-------------v-------------+
     |  1. 工具名冲突检测          |
     |     BUILTIN_TOOL_NAMES vs  |
     |     user tools             |
     +-------------+-------------+
                   |
     +-------------v-------------+
     |  2. Harness Profile 解析    |
     |     resolveHarnessProfile()|
     |     + toolOverrides 应用   |
     +-------------+-------------+
                   |
     +-------------v-------------+
     |  3. Anthropic 检测         |
     |     isAnthropicModel()     |
     |     → cacheMiddleware[]    |
     +-------------+-------------+
                   |
     +-------------v-------------+
     |  4. 子代理规格归一化        |
     |     AsyncSubAgents 分离    |
     |     normalizeSubagentSpec  |
     |     (注入默认中间件管道)    |
     +-------------+-------------+
                   |
     +-------------v-------------+
     |  5. 主中间件管道组装        |
     |     [todoList, FS,         |
     |      SubAgents, HITL?,     |
     |      Summarization,        |
     |      PatchToolCalls,       |
     |      Skills?, Memory?,     |
     |      Cache?, Custom...]    |
     +-------------+-------------+
                   |
     +-------------v-------------+
     |  6. createAgent()          |
     |     → LangGraph 图编译     |
     |     → DeepAgent 实例       |
     +---------------------------+

模块二:中间件系统 (middleware/)

  • 模块名称:可组合中间件管道
  • 设计说明:采用洋葱模型 (Onion Model) 的中间件模式。每个中间件通过 createMiddleware() 创建,可注册工具、定义钩子函数(beforeModelafterModel 等)。中间件按确定顺序组装,后续中间件可以依赖前置中间件注入的状态和工具。文件系统中间件是所有文件操作的基础,子代理中间件在此基础上提供任务委派能力。
  • 内部结构图 (plainText)
text
+-----------------------------------------------------------+
|                  Middleware Pipeline                       |
|  (按固定顺序组装,类似 Koa.js 洋葱模型)                     |
+-----------------------------------------------------------+

  Request ──────────────────────────────────────────> Response
    |                                                    ^
    v                                                    |
+---+---+  +----+----+  +-----+-----+  +----+----+  +---+---+
| todo  |  |   FS    |  | SubAgent  |  | Summar- |  | Custom |
| List  |->| Middle- |->| Middle-   |->| ization |->| Middle-|
| Middle|  |  ware   |  |  ware     |  | Middle- |  |  ware  |
| ware  |  |         |  |           |  |  ware   |  |        |
+-------+  +----+----+  +-----+-----+  +----+----+  +--------+
                |              |              |
                v              v              v
          +-----+-----+ +-----+-----+ +------+------+
          | Backend   | | task()    | | /conversa-  |
          | Protocol  | | tool call | | tion_history|
          | (V1/V2)   | | → isolated| | /{id}.md    |
          +-----------+ | subagent  | +-------------+
                        +-----------+

  内置工具注册表:
  +------------------------------------------------------------------+
  | FS Middleware     | SubAgent MW    | Summarization MW | Skills MW |
  | ls               | task           | (history         | (SKILL.md |
  | read_file        | (同步子代理)    |  offloading       |  injection|
  | write_file       |                |  to backend)      |  into     |
  | edit_file        | AsyncSubAgent  |                   |  prompt)  |
  | glob             | (异步子代理)    |                   |           |
  | grep             |                |                   |           |
  | execute (sandbox)|                |                   |           |
  +------------------------------------------------------------------+

模块三:后端协议系统 (backends/)

  • 模块名称:Pluggable Backend Protocol
  • 设计说明:采用策略模式 (Strategy Pattern) + 适配器模式 (Adapter Pattern)。后端协议定义了文件操作的统一接口,不同后端实现提供不同的存储策略。V1/V2 协议版本化确保了向后兼容。resolveBackend() 工厂函数支持从函数、对象或类实例创建后端。CompositeBackend 实现多后端路由,BaseSandbox 抽象类定义了沙箱后端的扩展点。
  • 内部结构图 (plainText)
text
+------------------------------------------------------------------+
|                    Backend Protocol System                         |
+------------------------------------------------------------------+

+---------------------------+     +--------------------------------+
| BackendProtocol V1        |     | BackendProtocol V2             |
| (deprecated, compat only) |     | (current, feature-complete)    |
| ls/read/write/edit/       |     | ls/read/write/edit/            |
| glob/grep                 |     | glob/grep + execute/upload/    |
|                           |     | download (Sandbox extension)   |
+---------------------------+     +--------------------------------+
              |                              |
              +--------------+---------------+
                             |
                    +--------v--------+
                    |  resolveBackend |
                    |  (Factory Fn)   |
                    +--------+--------+
                             |
        +--------------------+--------------------+
        |                    |                    |
+-------v------+  +----------v---------+  +------v---------+
| StateBackend |  | StoreBackend       |  | FilesystemBack |
| (LangGraph   |  | (LangGraph Store   |  | end            |
|  State)      |  |  w/ namespace)     |  | (Local Disk)   |
+--------------+  +--------------------+  +----------------+
        |                    |                    |
+-------v------+  +----------v---------+  +------v---------+
| Composite    |  | ContextHubBackend  |  | LangSmith      |
| Backend      |  | (Context Hub       |  | Sandbox        |
| (Multi-BE    |  |  Service Client)   |  | (Cloud Sandbox)|
|  Router)     |  +--------------------+  +----------------+
+--------------+
        |
        +-- 路由规则: 根据路径前缀或文件类型选择后端

+-------------------+
| BaseSandbox       |<---- 沙箱后端的抽象基类
| (Abstract Class)  |
| + execute()       |---- LocalShellBackend (本地执行)
| + upload()        |---- LangSmithSandbox (云端沙箱)
| + download()      |---- Daytona/Deno/Modal/QuickJS (providers/)
+-------------------+

模块四:Harness Profile 系统 (profiles/)

  • 模块名称:模型配置注册与分发
  • 设计说明:采用注册表模式 (Registry Pattern) + 策略模式。内置多个模型特定的 HarnessProfile(Claude、GPT 等),通过模型标识符匹配加载。用户可注册自定义 Profile。Profile 包含提示词覆盖、工具描述重写、通用子代理配置等,使同一套代码能针对不同模型优化行为。
  • 内部结构图 (plainText)
text
+------------------------------------------------------------------+
|                   Harness Profile System                           |
+------------------------------------------------------------------+

+---------------------------+     +--------------------------------+
| resolveHarnessProfile()   |---->| Profile Registry               |
| (Entry point, called by   |     | (Map<key, HarnessProfile>)     |
|  createDeepAgent)         |     |                                |
+---------------------------+     | Built-in profiles:             |
                                  | - anthropic:claude-sonnet-4-6  |
                                  | - anthropic:claude-opus-4-8    |
                                  | - anthropic:claude-haiku-4-5   |
                                  | - openai:gpt-5                 |
                                  | - ... more                     |
                                  +--------------------------------+
                                            |
                          +-----------------+-----------------+
                          |                                   |
                 +--------v--------+              +-----------v---------+
                 | Built-in Profile|              | User-Registered     |
                 | (ensureBuiltins |              | Profile             |
                 |  Loaded)        |              | (registerHarness-   |
                 +--------+--------+              |  Profile)           |
                          |                       +---------------------+
                          |
                 +--------v--------+
                 | HarnessProfile  |
                 | - systemPrompt  |  (模型特定提示词)
                 |   overrides     |
                 | - toolDesc      |  (工具描述重写)
                 |   overrides     |
                 | - generalPurpose|  (通用子代理配置)
                 |   Subagent      |
                 | - middleware    |
                 |   defaults      |
                 +-----------------+
                          |
                 +--------v--------+
                 | mergeProfiles() |
                 | (内置 + 用户    |
                 |  合并策略)       |
                 +-----------------+

模块五:ACP 服务端 (acp/)

  • 模块名称:Agent Client Protocol 集成
  • 设计说明:采用外观模式 (Facade Pattern),在 DeepAgent 上封装 ACP 协议层。DeepAgentsServer 管理多个会话,每个会话包含独立的 DeepAgent 实例和 ACPFilesystemBackend。通过 adapter.ts 完成 ACP 内容块与 LangChain 消息的双向转换。支持 initializenewSessionpromptcancel 等 ACP 标准方法。
  • 内部结构图 (plainText)
text
+------------------------------------------------------------------+
|                     ACP Server Architecture                        |
+------------------------------------------------------------------+

  Zed / JetBrains / CLI
         |
         | (ACP Protocol over ndJSON)
         v
+--------+---------+
| DeepAgentsServer |  (Facade over DeepAgent)
| - sessions: Map  |
| - config         |
+--------+---------+
         |
         +---> initialize()      → 返回 Agent 能力声明
         +---> newSession()       → 创建 DeepAgent + 会话状态
         +---> loadSession()      → 恢复历史会话
         +---> prompt()           → Agent 调用 + 流式返回
         +---> cancel()           → 中断运行中的调用
         +---> authenticate()     → API Key 认证
         |
         v
+--------+---------+     +----------------------+
| createDeepAgent()|     | ACPFilesystemBackend |
| (DeepAgent 实例) |     | (代理文件操作到       |
+------------------+     |  ACP 客户端)          |
         |               +----------------------+
         |                         |
         v                         v
+--------+---------+     +----------------------+
| adapter.ts        |     | ACP Client (IDE)     |
| ACP Block <->     |     | 实际文件系统操作      |
| LangChain Message |     +----------------------+
+------------------+

5. 关键数据流程

场景一:标准 Agent 调用与文件操作

场景说明:用户向 DeepAgent 发出指令,要求研究某个主题并将结果写入文件,这是最典型的端到端数据流。

流转时序图

场景二:上下文卸载 (Summarization)

场景说明长对话导致 token 使用接近模型上限时,SummarizationMiddleware 自动触发历史消息卸载到后端存储

  • 流转时序图

场景三:ACP IDE 集成

场景说明:Zed IDE 通过 ACP 协议连接 DeepAgentsJS 服务端,在编辑器内执行 Agent 任务。

流转时序图

6. 接口与契约规范 (Interface & Contract Specs)

6.1 核心内部模块契约 (TypeScript Interfaces)

typescript
/**
 * DeepAgent 创建参数完整契约
 * 所有参数均为可选,提供合理默认值
 */
interface CreateDeepAgentParams {
  /** LLM 模型,支持字符串标识符或模型实例 */
  model?: string | LanguageModelLike;
  /** 用户自定义工具列表 */
  tools?: (ClientTool | ServerTool)[];
  /** 自定义系统提示词(追加到默认提示词之后) */
  systemPrompt?: string | SystemMessage;
  /** 自定义状态 Schema(与中间件状态合并) */
  stateSchema?: AnyStateSchema | InteropZodObject;
  /** 自定义中间件列表(追加到内置中间件之后) */
  middleware?: AgentMiddleware[];
  /** 子代理定义列表(同步或异步) */
  subagents?: AnySubAgent[];
  /** 结构化响应格式 */
  responseFormat?: SupportedResponseFormat;
  /** 上下文 Schema */
  contextSchema?: InteropZodObject;
  /** LangGraph 检查点存储器 */
  checkpointer?: BaseCheckpointSaver;
  /** LangGraph Store */
  store?: BaseStore;
  /** 文件系统后端工厂(默认: StateBackend) */
  backend?: BackendFactory;
  /** Human-in-the-Loop 中断配置 */
  interruptOn?: InterruptOnConfig;
  /** Agent 名称 */
  name?: string;
  /** 跨会话记忆配置 */
  memory?: MemoryMiddlewareOptions;
  /** 技能源配置 */
  skills?: SkillsMiddlewareOptions["sources"];
  /** 文件系统权限列表 */
  permissions?: FilesystemPermission[];
  /** 流式传输转换器 */
  streamTransformers?: (() => StreamTransformer<any>)[];
}

/**
 * 后端协议 V2 核心接口
 * 所有文件操作返回结构化结果,统一错误处理
 */
interface BackendProtocolV2 {
  ls(path: string, runtime: BackendRuntime): Promise<LsResult>;
  read(path: string, runtime: BackendRuntime): Promise<ReadResult>;
  readRaw(path: string, runtime: BackendRuntime): Promise<ReadRawResult>;
  write(path: string, content: string | Uint8Array, runtime: BackendRuntime): Promise<WriteResult>;
  edit(path: string, oldStr: string, newStr: string, runtime: BackendRuntime): Promise<EditResult>;
  glob(patterns: string[], runtime: BackendRuntime): Promise<GlobResult>;
  grep(pattern: string, path: string, runtime: BackendRuntime): Promise<GrepResult>;
}

/**
 * 沙箱后端协议扩展 (V2)
 */
interface SandboxBackendProtocolV2 extends BackendProtocolV2 {
  execute(command: string, runtime: BackendRuntime): Promise<ExecuteResponse>;
  upload(files: FileData[], runtime: BackendRuntime): Promise<FileUploadResponse>;
  download(paths: string[], runtime: BackendRuntime): Promise<FileDownloadResponse>;
}

/**
 * 子代理定义
 */
interface SubAgent {
  /** 子代理唯一名称 */
  name: string;
  /** 子代理描述(供主 Agent 选择时参考) */
  description: string;
  /** 子代理系统提示词 */
  prompt: string;
  /** 子代理专属工具(不继承主 Agent 工具) */
  tools?: StructuredTool[];
  /** 子代理专属中间件 */
  middleware?: AgentMiddleware[];
  /** 子代理专属技能 */
  skills?: SkillsMiddlewareOptions["sources"];
  /** 子代理权限(默认继承主 Agent 权限) */
  permissions?: FilesystemPermission[];
  /** 是否为主 Agent 的默认子代理 */
  isDefault?: boolean;
  /** 模型标识符(可不指定,继承主 Agent) */
  model?: string;
}

/**
 * 异步子代理定义 (扩展 SubAgent)
 */
interface AsyncSubAgent extends SubAgent {
  /** LangGraph 图 ID(用于远程执行) */
  graphId: string;
}

6.2 ACP 协议核心类型

typescript
/**
 * ACP 服务端配置
 */
interface DeepAgentsServerOptions {
  /** 一次可同时运行的 Agent 调用数上限 */
  maxConcurrent?: number;
  /** 默认 DeepAgent 配置(传递给 createDeepAgent) */
  defaultConfig?: DeepAgentConfig;
  /** ACP 能力声明 */
  capabilities?: ACPCapabilities;
  /** 认证方法列表 */
  authMethods?: ACPAuthMethod[];
  /** 日志器实例 */
  logger?: Logger;
}

/**
 * ACP 会话状态
 */
interface SessionState {
  /** 会话 ID */
  sessionId: string;
  /** DeepAgent 实例 */
  agent: DeepAgent;
  /** ACP 文件系统后端(桥接到 IDE 文件系统) */
  backend: ACPFilesystemBackend;
  /** LangGraph 检查点配置 */
  checkpointer?: BaseCheckpointSaver;
  /** 当前运行取消信号 */
  abortController?: AbortController;
  /** 当前流运行流 */
  currentRun?: DeepAgentRunStream;
}

6.3 文件操作结果类型契约

typescript
/** 目录列表结果 */
interface LsResult {
  error?: string;
  files?: FileInfo[];
}

/** 文件读取结果 */
interface ReadResult {
  error?: string;
  content?: string | Uint8Array;
  mimeType?: string;
}

/** 文件写入结果 */
interface WriteResult {
  error?: string;
  path?: string;
}

/** 文件编辑结果 */
interface EditResult {
  error?: string;
  path?: string;
}

/** 通配符匹配结果 */
interface GlobResult {
  error?: string;
  matches?: string[];
}

/** 文本搜索/正则匹配结果 */
interface GrepResult {
  error?: string;
  matches?: GrepMatch[];
}

/** grep 单条匹配项 */
interface GrepMatch {
  path: string;
  line: number;
  text: string;
}

/** 沙箱执行结果 */
interface ExecuteResponse {
  error?: string;
  stdout?: string;
  stderr?: string;
  exitCode?: number;
}

7. 快速开始

7.1 环境配置

bash
# 要求 Node.js >= 18, pnpm >= 10
pnpm install
pnpm build

7.2 安装与运行

bash
npm install deepagents

# 或使用 ACP 服务端
npx deepagents-acp

7.3 典型用例

typescript
import { createDeepAgent } from "deepagents";

// 1. 最小配置 —— 使用所有默认值
const agent = createDeepAgent();
const result = await agent.invoke({
  messages: [{ role: "user", content: "Research LangGraph and write a summary to summary.md" }],
});

// 2. 自定义模型和工具
import { ChatOpenAI } from "@langchain/openai";
const customAgent = createDeepAgent({
  model: new ChatOpenAI({ model: "gpt-5", temperature: 0 }),
  tools: [myCustomTool],
  systemPrompt: "You are a research assistant.",
});

// 3. 自定义后端 (文件持久化)
import { FilesystemBackend } from "deepagents";
const persistentAgent = createDeepAgent({
  backend: () => new FilesystemBackend({ rootDir: "/data/agent-files" }),
});