Skip to content

Deep Agents 解读

项目信息

核心使用场景

  • 长时间复杂任务自动执行(规划→执行→验证)
  • 终端 AI 编码助手(类似 Claude Code)
  • 多 Agent 协作(主 Agent + 专用子 Agent)
  • 企业级 Agent 部署(流式输出 + 持久化 + 监控)

1. 项目概览

1.1 项目定位与核心价值

Deep Agents 是一个"开箱即用的带电池 Agent 框架"——一个有主见的 (opinionated)、即时可用的 AI Agent 运行环境,用户可以扩展、覆写或替换任意组件。

一句话定位在 LangGraph 运行时之上构建的全功能 Agent harness,内置规划、文件系统、子代理、上下文管理和技能系统

核心原则

  • 有主见 (Opinionated) — 默认配置针对长时间、多步骤任务进行调优
  • 可扩展 (Extensible) — 无需 fork 即可覆写或替换任意组件
  • 模型无关 (Model-agnostic) — 支持任何支持工具调用的 LLM
  • 生产就绪 (Production-ready) — 基于 LangGraph 构建(流式输出、持久化、检查点)

1.2 目标用户与使用场景

用户类型使用方式典型场景
AI 应用开发者Python SDK (create_deep_agent())构建自定义 Agent 应用
终端用户dcode CLI (Textual TUI)编码辅助、文件操作、Shell 访问
平台工程师deepagents-cli 部署工具部署到 LangGraph Platform
AI 研究人员SDK + EvalsAgent 行为和性能评估

核心使用场景

  • 长时间复杂任务自动执行(规划→执行→验证)
  • 终端 AI 编码助手(类似 Claude Code)
  • 多 Agent 协作(主 Agent + 专用子 Agent)
  • 企业级 Agent 部署(流式输出 + 持久化 + 监控)

1.3 核心技术亮点

  1. Delta Channel 消息归约器 — 将消息检查点存储从 O(N²) 降为 O(N)
  2. 智能上下文管理 — 自动摘要 + 大文件卸载到磁盘
  3. 可插拔后端系统 — 5 种存储后端 (内存/磁盘/沙箱/持久/组合)
  4. 中间件排除保护机制 — 核心中间件不可被意外排除
  5. Harness Profile 系统 — 针对每个模型定制行为参数
  6. 自动化发布流程 — 基于 Conventional Commits 的 release-please

1.4 技术栈与选型对比

层级选型替代方案选择原因
Agent 运行时LangGraph自建循环流式输出、检查点、中断、持久化
LLM 抽象LangChain直接调用 API20+ 提供商统一接口
终端 UITextualprompt-toolkit丰富组件、CSS 布局、鼠标交互
包管理uvpip/poetryMonorepo 支持, editable installs
代码质量ruff + tyflake8/mypy速度 (Rust) + 一体化

2. 快速开始

更多使用示例可参考 deepagents 示例

2.1 SDK 使用

bash
uv add deepagents
python
from deepagents import create_deep_agent

agent = create_deep_agent(
    model="openai:gpt-5.5",
    system_prompt="You are a research assistant.",
)
result = agent.invoke({"messages": "Research LangGraph and write a summary"})
print(result)

2.2 终端使用 (dcode)

bash
# 安装
curl -LsSf https://langch.in/dcode | bash

# 交互模式
dcode -m "fix the bug in auth.py"

# 管道模式
cat error.log | dcode -n "analyze these errors" --quiet

# 恢复会话
dcode -r <thread-id>

2.3 部署到 LangGraph Platform

bash
deepagents init my-agent
cd my-agent
deepagents dev    # 本地开发
deepagents deploy # 部署

3. 整体架构设计

3.1 架构概述

Deep Agents 采用分层中间件管道架构 (Layered Middleware Pipeline Architecture)。系统由三层组成:

  • 用户接入层:CLI 终端 (dcode)、Python SDK (create_deep_agent())、ACP/HTTP 服务器
  • Agent 组装层:中间件管道、模型解析、Profile 系统、后端协议
  • 运行时层:LangGraph StateGraph 运行时 + 可插拔后端 (内存/磁盘/沙箱/存储)

3.2 整体架构图

text
+====================================================================+
|                        用户接入层 (User Layer)                       |
|                                                                     |
|  +------------------+  +------------------+  +------------------+   |
|  |  dcode CLI (TUI) |  |  Python SDK API  |  |  ACP Server      |   |
|  |  (Textual App)   |  | create_deep_agent|  |  (HTTP/stdio)    |   |
|  +--------+---------+  +--------+---------+  +--------+---------+   |
|           |                     |                     |              |
+===========|=====================|=====================|==============+
            |       langgraph-sdk | (HTTP)              | stdin/HTTP
            v                     v                     v
+====================================================================+
|                    Agent 组装层 (Assembly Layer)                     |
|                                                                     |
|  +-------------------------------------------------------------+   |
|  |              create_deep_agent() / create_cli_agent()         |   |
|  |                                                              |   |
|  |  Step 1: Resolve Model ───> Step 2: Resolve Profile          |   |
|  |  Step 3: Build Backend ──> Step 4: Build Subagents           |   |
|  |  Step 5: Assemble Middleware Pipeline ──> Step 6: compile()  |   |
|  +-------------------------------------------------------------+   |
|                                                                     |
+====================================================================+
            |
            v
+====================================================================+
|                    中间件管道 (Middleware Pipeline)                  |
|                                                                     |
|  [TodoListMiddleware] ───────────────────────────────────────>     |
|  [SkillsMiddleware] (可选: if skills are configured) ─────────>     |
|  [FilesystemMiddleware] (必需: 文件工具 + 权限执行) ───────────>     |
|  [SubAgentMiddleware] (必需: 子代理 task 工具) ────────────────>     |
|  [SummarizationMiddleware] (自动摘要 + 大文件卸载) ────────────>     |
|  [PatchToolCallsMiddleware] (工具调用修正) ───────────────────>     |
|  [AsyncSubAgentMiddleware] (可选: 异步远程子代理) ─────────────>     |
|  ───────────────────── User Middleware ───────────────────────>     |
|  [HarnessProfile.extra_middleware] (Profile 定制中间件) ──────>     |
|  [_ToolExclusionMiddleware] (可选: 工具排除) ─────────────────>     |
|  [AnthropicPromptCachingMiddleware] (无条件: 提示缓存) ────────>     |
|  [MemoryMiddleware] (可选: 跨会话内存 AGENTS.md) ─────────────>     |
|  [HumanInTheLoopMiddleware] (可选: 人机交互中断) ─────────────>     |
|                                                                     |
+====================================================================+
            |
            v
+====================================================================+
|                    运行时层 (Runtime Layer)                          |
|                                                                     |
|  +----------------------------+  +------------------------------+   |
|  | LangGraph StateGraph       |  | 可插拔后端 (Pluggable Backend)|   |
|  | - Streaming                |  |                              |   |
|  | - Checkpointing            |  | StateBackend ─── (内存)      |   |
|  | - Persistence              |  | FilesystemBackend (本地磁盘)  |   |
|  | - Interrupt (HITL)         |  | CompositeBackend (多层组合)  |   |
|  +----------------------------+  | StoreBackend ──── (持久)     |   |
|                                   | SandboxBackend ─── (远程)    |   |
|                                   +------------------------------+   |
+====================================================================+

3.3 目录结构

shell
deepagents/
├── libs/                                           # 【核心基建】Monorepo 核心包目录 (6个独立版本包)
   ├── deepagents/                                 # 【核心基建】SDK - Agent 框架核心 (v0.6.8)
   ├── deepagents/
   ├── __init__.py                         # 【核心基建】公开 API: create_deep_agent, Middleware, Profiles 导出
   ├── graph.py                            # 【核心基建】Agent 组装引擎 - create_deep_agent() 主入口
   ├── _version.py                         # 【配置】版本号 (由 release-please 管理)
   ├── _models.py                          # 【工具集】resolve_model() - 模型字符串→实例转换
   ├── _tools.py                           # 【工具集】_apply_tool_description_overrides() - 工具描述覆写
   ├── _messages_reducer.py                # 【核心基建】_messages_delta_reducer() - Delta Channel 合并 (O(N))
   ├── _excluded_middleware.py              # 【核心基建】中间件排除/验证/覆盖检查逻辑
   ├── _api/                               # 【工具集】内部 API 基础设施
   └── deprecation.py                  # 【工具集】@deprecated 装饰器 + warn_deprecated()
   ├── backends/                           # 【核心基建】可插拔后端实现体系 (6种后端)
   ├── __init__.py                     # 【核心基建】StateBackend 导出
   ├── protocol.py                     # 【核心基建】BackendProtocol + SandboxBackendProtocol (880行)
   ├── state.py                        # 【核心基建】StateBackend - 运行时内存后端 (支持 v1/v2 格式)
   ├── filesystem.py                   # 【核心基建】FilesystemBackend - 本地磁盘后端 (ripgrep + Python fallback)
   ├── composite.py                    # 【核心基建】CompositeBackend - 默认→运行时→持久三层回退链
   ├── store.py                        # 【核心基建】StoreBackend - LangGraph Store 持久化后端
   ├── sandbox.py                      # 【核心基建】BaseSandbox - 通过 execute() 委派所有文件操作的基类
   ├── local_shell.py                  # 【业务模块】LocalShellBackend - 本地 Shell 执行 (支持virtual_mode)
   ├── langsmith.py                    # 【业务模块】LangSmithSandbox - LangSmith 托管沙箱
   ├── context_hub.py                  # 【业务模块】ContextHub - 外部上下文提供者
   └── utils.py                        # 【工具集】后端通用工具 (validate_path, sanitize_tool_call_id等)
   ├── middleware/                         # 【核心基建】Agent 中间件体系 (14个中间件)
   ├── __init__.py                     # 【核心基建】中间件公共 API 导出
   ├── filesystem.py                   # 【核心基建】FilesystemMiddleware - 文件工具注入 + 权限执行
   ├── subagents.py                    # 【核心基建】SubAgentMiddleware - task 工具 + 子代理生命周期
   ├── async_subagents.py              # 【核心基建】AsyncSubAgentMiddleware - 远程后台子代理 (LangSmith Deployment)
   ├── memory.py                       # 【核心基建】MemoryMiddleware - AGENTS.md 跨会话内存注入
   ├── summarization.py                # 【核心基建】SummarizationMiddleware - 上下文压缩 + 大文件卸载
   ├── skills.py                       # 【核心基建】SkillsMiddleware - 技能目录加载与提示注入
   ├── permissions.py                  # 【核心基建】权限检查中间件
   ├── rubric.py                       # 【业务模块】RubricMiddleware - 自动评分评估
   ├── patch_tool_calls.py             # 【工具集】PatchToolCallsMiddleware - 工具调用修正
   ├── _state.py                       # 【工具集】private_state_field_names() - 私有状态字段提取
   ├── _fs_interrupt.py                # 【工具集】_build_interrupt_on_from_permissions()
   ├── _message_eviction.py            # 【工具集】大型工具消息卸载引擎
   ├── _overflow_clip.py               # 【工具集】消息数量溢出裁剪
   ├── _tool_exclusion.py              # 【工具集】_ToolExclusionMiddleware - Profile 工具排除
   └── _utils.py                       # 【工具集】append_to_system_message() 等通用函数
   └── profiles/                           # 【核心基建】模型行为配置档案 (Profile) 系统
       ├── _builtin_profiles.py            # 【核心基建】内置 Profile 自动注册
       ├── _keys.py                        # 【配置】Profile 配置键名常量
       ├── harness/                        # 【核心基建】HarnessProfile - 定义 Agent 行为的模型调优配置
   ├── harness_profiles.py         # 【核心基建】HarnessProfile / HarnessProfileConfig 数据结构
   ├── _anthropic_sonnet_4_6.py    # 【核心基建】Claude Sonnet 4.6 Profile
   ├── _anthropic_opus_4_7.py      # 【核心基建】Claude Opus 4.7 Profile
   ├── _anthropic_haiku_4_5.py     # 【核心基建】Claude Haiku 4.5 Profile
   └── _openai_codex.py            # 【核心基建】OpenAI Codex Profile
       └── provider/                       # 【核心基建】ProviderProfile - 提供商级别参数配置
           ├── provider_profiles.py        # 【核心基建】ProviderProfile 定义 + register_provider_profile()
           ├── _openai.py                  # 【核心基建】OpenAI Provider Profile
           └── _openrouter.py              # 【核心基建】OpenRouter Provider Profile
   ├── tests/                                  # 【质量保证】SDK 测试套件 (unit + benchmarks)
   ├── scripts/                                # 【工具集】SDK 构建/发布/检查脚本
   ├── pyproject.toml                          # 【配置】SDK Python 包配置 (setuptools, Python>=3.11)
   └── Makefile                                # 【配置】SDK 构建目标 (test, lint, format, bench)

   ├── code/                                       # 【业务模块】Deep Agents Code - 终端 TUI 应用 (v0.1.10)
   ├── deepagents_code/
   ├── __init__.py                         # 【核心基建】导出 cli_main 入口
   ├── __main__.py                         # 【核心基建】python -m deepagents_code 支持
   ├── main.py                             # 【核心基建】cli_main() - CLI 主入口 (2780行, 完整生命周期)
   ├── app.py                              # 【核心基建】run_textual_app() - Textual TUI 应用主循环
   ├── agent.py                            # 【核心基建】create_cli_agent() - Agent 图创建 + 默认工具组装
   ├── server.py                           # 【业务模块】LangGraph Server 进程管理 (子进程生命周期)
   ├── server_graph.py                     # 【核心基建】服务器端 Agent Graph 构建逻辑
   ├── server_manager.py                   # 【业务模块】LangGraph Server 管理器 (启动/停止/健康检查)
   ├── config.py                           # 【核心基建】全局配置 (settings, console, 模型检测, 沙箱配置)
   ├── configurable_model.py               # 【核心基建】可配置模型包装器 (支持运行时参数切换)
   ├── model_config.py                     # 【业务模块】模型选择/持久化 (default, recent, agent-level)
   ├── tools.py                            # 【业务模块】fetch_url + web_search (Tavily) 自定义工具
   ├── mcp_tools.py                        # 【业务模块】MCP 工具发现/加载/合并 (Claude Desktop 格式)
   ├── mcp_auth.py                         # 【业务模块】MCP OAuth 认证流程管理
   ├── mcp_oauth_ui.py                     # 【UI 视图】MCP OAuth 终端 UI 界面
   ├── mcp_trust.py                        # 【业务模块】MCP 信任管理 (项目级服务器审批)
   ├── mcp_disabled.py                     # 【业务模块】MCP 禁用/错误状态处理
   ├── mcp_commands.py                     # 【业务模块】mcp login / mcp config CLI 命令
   ├── mcp_login_service.py                # 【业务模块】MCP 登录后台服务
   ├── mcp_providers/                      # 【业务模块】MCP 提供商特定集成
   ├── command_registry.py                 # 【核心基建】斜杠命令注册表 (/agents, /skills, /threads 等)
   ├── subagents.py                        # 【业务模块】异步子代理配置 (异步 subagent 定义)
   ├── textui_adapter.py                   # 【UI 视图】Textual 事件 ↔ Agent 事件的双向适配器
   ├── editor.py                           # 【业务模块】外部编辑器集成 ($VISUAL/$EDITOR)
   ├── file_ops.py                         # 【工具集】文件操作辅助函数
   ├── formatting.py                       # 【UI 视图】Rich 格式化辅助 (markdown→Rich 渲染)
   ├── output.py                           # 【UI 视图】输出格式化 (文本/JSON 双模式)
   ├── ui.py                               # 【UI 视图】帮助界面渲染 (show_help, show_agents_help等)
   ├── theme.py                            # 【UI 视图】App 主题定义 (亮/暗模式颜色)
   ├── widgets/                            # 【UI 视图】Textual 自定义小部件集合
   ├── input.py                            # 【UI 视图】用户输入处理 (多行输入, 历史)
   ├── onboarding.py                       # 【UI 视图】新手引导向导
   ├── notifications.py                    # 【UI 视图】通知中心 (依赖缺失/更新提醒)
   ├── non_interactive.py                  # 【业务模块】run_non_interactive() - 管道/CI 模式
   ├── remote_client.py                    # 【业务模块】LangGraph Platform 远程客户端
   ├── sessions.py                         # 【业务模块】会话/线程 CRUD (list, delete, resume)
   ├── _session_stats.py                   # 【工具集】会话统计数据类型 (SessionStats)
   ├── resume_state.py                     # 【业务模块】会话恢复状态管理
   ├── hooks.py                            # 【业务模块】Hooks 系统 (shell session hooks)
   ├── state_migration.py                  # 【工具集】旧状态格式 → 新格式迁移
   ├── skills/                             # 【业务模块】技能目录 (用户/项目/内置三层)
   ├── built_in_skills/                    # 【业务模块】内置技能实现 (shell, coding 等)
   ├── integrations/                       # 【业务模块】沙箱集成工厂 (daytona/modal/agentcore/runloop)
   ├── ask_user.py                         # 【核心基建】用户交互审批系统 (AskUser)
   ├── auth_store.py                       # 【业务模块】OAuth 凭证加密存储
   ├── auth_display.py                     # 【UI 视图】认证状态视觉效果
   ├── event_bus.py                        # 【核心基建】进程间事件总线
   ├── update_check.py                     # 【工具集】自动更新检查/安装 (PyPI + 去重)
   ├── _constants.py                       # 【配置】魔术常量 (DEFAULT_AGENT_NAME 等)
   ├── _env_vars.py                        # 【配置】环境变量注册表
   ├── _debug.py                           # 【工具集】调试开关 (DEBUG_* 环境变量)
   ├── _git.py                             # 【工具集】Git 仓库检测与操作
   ├── _startup_error.py                   # 【工具集】启动错误友好展示
   ├── _server_config.py                   # 【配置】服务器配置生成
   ├── _cli_context.py                     # 【工具集】CLI 上下文 (cwd, git branch)
   ├── _textual_patches.py                 # 【工具集】Textual 上游 bug 补丁
   ├── _testing_models.py                  # 【工具集】测试用模型辅助
   ├── _version.py                         # 【配置】CLI 版本号
   ├── extras_info.py                      # 【工具集】可选依赖检测 (provider extras)
   ├── local_context.py                    # 【工具集】本地项目上下文检测
   ├── project_utils.py                    # 【工具集】项目根目录/配置文件发现
   ├── terminal_escape.py                  # 【工具集】终端 ANSI 转义序列处理
   ├── terminal_capabilities.py            # 【工具集】终端能力检测 (颜色/Unicode/宽度)
   ├── iterm_cursor_guide.py               # 【工具集】iTerm2 光标导航
   ├── unicode_security.py                 # 【工具集】Unicode 安全扫描 (混淆字符检测)
   ├── filesystem_empty_result.py          # 【工具集】空结果友好提示
   ├── media_utils.py                      # 【工具集】媒体文件 (图片) 处理
   ├── clipboard.py                        # 【工具集】系统剪贴板集成 (pyperclip)
   ├── offload.py                          # 【工具集】内容卸载到磁盘
   ├── default_agent_prompt.md             # 【配置】默认 Agent 系统提示模板
   ├── system_prompt.md                    # 【配置】系统提示 Markdown 文件
   ├── app.tcss                            # 【UI 视图】Textual CSS 主题样式表
   └── py.typed                            # 【配置】PEP 561 类型包标记
   ├── tests/                                  # 【质量保证】CLI 测试 (unit + integration)
   ├── scripts/                                # 【工具集】CLI 构建/安装/检查脚本
   ├── examples/                               # 【配置】CLI 配置示例
   └── pyproject.toml                          # 【配置】CLI Python 包配置 (hatchling, 40+ 依赖)

   ├── cli/                                        # 【业务模块】Deep Agents CLI - 部署工具链 (v0.2.1)
   ├── deepagents_cli/
   ├── __init__.py                         # 【核心基建】导出 cli_main
   ├── main.py                             # 【核心基建】CLI 入口 (argparse: init/dev/deploy 子命令)
   ├── _version.py                         # 【配置】CLI 部署工具版本号
   ├── config.py                           # 【配置】._load_dotenv() 环境变量加载
   ├── model_config.py                     # 【配置】resolve_env_var() DEEPAGENTS_CLI_ 前缀处理
   └── deploy/                             # 【业务模块】部署管道 (commands, bundler, config, templates)
   ├── tests/                                  # 【质量保证】CLI 工具测试
   ├── scripts/                                # 【工具集】CLI 构建脚本
   ├── examples/                               # 【配置】CLI 示例项目
   └── pyproject.toml                          # 【配置】CLI 工具包配置 (hatchling)

   ├── acp/                                        # 【业务模块】Agent Context Protocol (v0.0.8)
   ├── deepagents_acp/                         # 【核心基建】ACP 服务器 (AgentServerACP)
   ├── tests/                                  # 【质量保证】ACP 测试
   ├── examples/                               # 【配置】ACP 交互示例
   ├── static/                                 # 【UI 视图】静态资源
   └── pyproject.toml                          # 【配置】ACP 包配置

   ├── evals/                                      # 【质量保证】评估套件 + Harbor 平台集成
   ├── deepagents_evals/                       # 【核心基建】评估 CLI (雷达图, trial summary)
   ├── deepagents_harbor/                      # 【核心基建】Harbor LangSmith 评估集成 (backend, metadata, stats)
   ├── tests/evals/                            # 【质量保证】评估测试用例 (file operations, tool usage, followup)
   ├── scripts/                                # 【工具集】评估运行/分析/雷达图生成脚本
   ├── pyproject.toml                          # 【配置】Evals 包配置
   └── EVAL_CATALOG.md                         # 【配置】评估用例目录

   ├── partners/                                   # 【业务模块】合作伙伴沙箱集成
   ├── daytona/                                # 【业务模块】Daytona 开发环境沙箱
   ├── modal/                                  # 【业务模块】Modal 无服务器 GPU 沙箱
   ├── quickjs/                                # 【业务模块】QuickJS JavaScript 解释器 (通过 langchain-quickjs)
   └── runloop/                                # 【业务模块】Runloop AI 工作负载沙箱

   ├── Makefile                                    # 【配置】Monorepo 级构建目标 (test-all, lint-all, bench-all)
   └── README.md                                   # 【配置】libs/ 目录说明

├── examples/                                       # 【配置】16 个示例 Agent 项目
   ├── async-subagent-server/                      # 【业务模块】异步子代理 LangGraph Server 示例
   ├── better-harness/                             # 【业务模块】BetterHarnessPlugin - 自定义 Agent 装配
   ├── content-builder-agent/                      # 【业务模块】多子代理内容构建器
   ├── deep_research/                              # 【业务模块】深度研究 Agent
   ├── deploy-coding-agent/                        # 【业务模块】可部署的编程 Agent
   ├── deploy-content-writer/                      # 【业务模块】可部署的内容写作 Agent
   ├── deploy-gtm-agent/                           # 【业务模块】可部署的 GTM 策略 Agent
   ├── downloading_agents/                         # 【业务模块】预配置 Agent 下载示例
   ├── llm-wiki/                                   # 【业务模块】LLM Wiki - RAG 知识库构建器
   ├── nvidia_deep_agent/                          # 【业务模块】NVIDIA 硬件优化 Agent
   ├── ralph_mode/                                 # 【业务模块】Ralph Mode - 架构审查工作流
   ├── repl_swarm/                                 # 【业务模块】REPL Swarm - 多 Agent 协作
   ├── text-to-sql-agent/                          # 【业务模块】自然语言→SQL Agent
   └── README.md                                   # 【配置】示例目录说明

├── .github/                                        # 【配置】CI/CD (20+ workflows, auto-labeling, PR lint)
   ├── workflows/                                  # 【配置】CI/CD 工作流 (ci.yml, release.yml, pr_lint.yml 等)
   ├── actions/                                    # 【配置】可复用 Actions
   ├── scripts/                                    # 【工具集】CI 辅助脚本
   ├── ISSUE_TEMPLATE/                             # 【配置】Issue 模板 (bug, feature, privileged)
   └── PULL_REQUEST_TEMPLATE.md                    # 【配置】PR 描述模板

├── AGENTS.md                                       # 【配置】AI Agent 开发手册 (365行,含架构/CI/CD/测试规范)
├── README.md                                       # 【配置】项目英文 README
├── README-CN.md                                    # 【配置】项目中文 README (本次分析生成)
├── LICENSE                                         # 【配置】MIT 许可证
├── .mcp.json                                       # 【配置】MCP 工具配置 (docs MCP server)
├── release-please-config.json                      # 【配置】Release Please 自动化配置 (6+ 包独立发布)
└── .release-please-manifest.json                   # 【配置】Release 版本清单

4. 模块依赖与调用关系

4.1 全局入口与核心路由

逻辑说明:用户通过三种方式调用系统:

  1. SDK 模式:直接调用 create_deep_agent() → LangChain create_agent() → 返回 CompiledStateGraph
  2. CLI 交互模式dcodecli_main()run_textual_cli_async() → 启动 LangGraph Server 子进程 → Textual TUI 通过 langgraph-sdk HTTP 连接
  3. CLI 非交互模式dcode -n "task"run_non_interactive() → 直接内存图执行
  4. ACP 模式dcode --acp_run_acp_cli_async() → ACP stdio 服务器

调用拓扑

text
cli_main() (Bootstrap)
 +-- parse_args()
 +-- _resolve_agent_arg()
 +-- _run_startup_auto_update()
 +-- cli_main() dispatch:
      |
      +---> (--acp)          --> _run_acp_cli_async()
      |                          +-- create_model()
      |                          +-- resolve_and_load_mcp_tools()
      |                          +-- create_cli_agent()
      |                          |    +-- create_deep_agent()
      |                          |         +-- resolve_model()
      |                          |         +-- _harness_profile_for_model()
      |                          |         +-- FilesystemMiddleware(backend=...)
      |                          |         +-- SubAgentMiddleware(subagents=...)
      |                          |         +-- SkillsMiddleware(sources=...)
      |                          |         +-- MemoryMiddleware(sources=...)
      |                          |         +-- SummarizationMiddleware()
      |                          |         +-- HumanInTheLoopMiddleware()
      |                          |         +-- LangChain create_agent() -> CompiledStateGraph
      |                          +-- AgentServerACP(graph)
      |
      +---> (-n MESSAGE)      --> run_non_interactive()
      |                          +-- create_model()
      |                          +-- create_cli_agent()
      |                          +-- agent.ainvoke({"messages": [HumanMessage(msg)]})
      |
      +---> (interactive TUI) --> run_textual_cli_async()
                                 +-- Launch langgraph dev server (subprocess)
                                 +-- Textual App (app.py)
                                      +-- ServerManager (server lifecycle)
                                      +-- TextualAdapter (event ↔ agent bridge)
                                      +-- Widgets (input, transcript, sidebar...)
                                      +-- Slash Command Registry

4.2 核心业务实体与关联

实体定义

  • Agent: 核心执行单元,封装了模型、工具和中间件管道
  • Middleware: Agent 行为插件,拦截 LLM 请求、注入提示、过滤工具
  • Backend: 存储抽象,提供统一的文件操作接口
  • SubAgent: 子代理定义,可通过 task 工具调用
  • HarnessProfile: 模型行为配置,包含提示模板、工具描述覆写、排除规则
  • ProviderProfile: 提供商参数配置,如 API 端点、最大 Token 数
  • Skill: 可动态加载的代理技能包
  • Thread/Session: 会话持久化单元,包含完整对话历史

实体引用拓扑

text
[Agent] 1 ─────> N [Middleware]
   |
   +── 1 ─────> 1 [Backend]
   |
   +── 1 ─────> 0..N [SubAgent]
   |                |
   |                +── 1 ─────> 1 [Middleware Stack]
   |
   +── 1 ─────> 0..1 [HarnessProfile]
   |
   +── 1 ─────> 0..1 [ProviderProfile]
   |
   +── 0..N ───> [Skill]
   |
   +── 0..N ───> [Thread/Session]

[Middleware]
   +── FilesystemMiddleware ───> 1 [Backend]
   +── SubAgentMiddleware  ───> N [SubAgent] (CompiledStateGraph)
   +── SkillsMiddleware    ───> N [Skill]
   +── MemoryMiddleware    ───> N [AGENTS.md files]
   +── SummarizationMiddleware -> 1 [Backend] (for offloading)

[Backend] (Protocol)
   +── StateBackend        (内存运行时状态)
   +── FilesystemBackend   (本地磁盘文件操作)
   +── CompositeBackend    (多层后端组合: 默认→运行时→持久)
   +── StoreBackend        (LangGraph Store 持久化)
   +── SandboxBackend      (远程容器执行)

5. 核心模块详解

模块一:Agent 组装引擎 (graph.py - create_deep_agent())

  • 模块名称:Agent 组装引擎 (Agent Assembly Engine)

  • 设计说明:这是整个系统的核心入口函数。它采用了 Builder 模式

    • 收集所有配置参数 (模型、工具、中间件、子代理、技能、权限等),按照严格的顺序组装中间件管道,
    • 最终调用 LangChain 的 create_agent() 编译为 CompiledStateGraph
  • 关键设计决策包括:

    • (1) 通过 _REQUIRED_MIDDLEWARE 机制保护核心中间件不可被排除;
    • (2) 系统提示由 USER → BASE/CUSTOM → SUFFIX 三段拼接;
    • (3) 递归处理子代理规范,为每个子代理构建独立的中间件栈。
  • 内部结构图

text
+------------------------------------------------------------------+
|                   create_deep_agent() 主流程                       |
+------------------------------------------------------------------+
|                                                                   |
|  Step 1: Resolve Model                                            |
|  +----------------------------+                                   |
|  | model=None → _build_default_model() → ChatAnthropic(sonnet)    |
|  | model=str → init_chat_model(str) / resolve_model()             |
|  | model=ChatModel → as-is                                        |
|  +----------------------------+                                   |
|            |                                                      |
|            v                                                      |
|  Step 2: Resolve Profile                                          |
|  +----------------------------+                                   |
|  | _harness_profile_for_model(model) → HarnessProfile             |
|  | _validate_excluded_middleware_config(profile)                   |
|  +----------------------------+                                   |
|            |                                                      |
|            v                                                      |
|  Step 3: Build Backend                                            |
|  +----------------------------+                                   |
|  | backend = backend or StateBackend()                            |
|  +----------------------------+                                   |
|            |                                                      |
|            v                                                      |
|  Step 4: Process Subagents                                        |
|  +-----------------------------------------------------------+   |
|  | For each spec:                                             |   |
|  | - Separate Sync vs Async subagents                         |   |
|  | - For Sync: build subagent middleware stack                |   |
|  |   TodoList → Filesystem → Summarization →                  |   |
|  |   PatchToolCalls → Skills(opt) → ProfileMiddleware          |   |
|  |   → Exclusion → PromptCaching                              |   |
|  | - Auto-add general-purpose subagent if not disabled        |   |
|  +-----------------------------------------------------------+   |
|            |                                                      |
|            v                                                      |
|  Step 5: Assemble Main Middleware Pipeline                        |
|  +-----------------------------------------------------------+   |
|  | Base: TodoList → Skills(optional) → Filesystem →            |   |
|  |        SubAgent → Summarization → PatchToolCalls            |   |
|  |        → AsyncSubAgent(optional)                            |   |
|  | User: <caller-supplied middleware>                          |   |
|  | Tail: Profile.extra_middleware → ToolExclusion →            |   |
|  |        PromptCaching → Memory(optional) → HITL(optional)     |   |
|  +-----------------------------------------------------------+   |
|            |                                                      |
|            v                                                      |
|  Step 6: Compile                                                  |
|  +-----------------------------------------------------------+   |
|  | create_agent(model, prompt, tools, middleware, ...)         |   |
|  |   .with_config(recursion_limit=9999, metadata={...})       |   |
|  | → CompiledStateGraph[AgentState, ContextT, ...]             |   |
|  +-----------------------------------------------------------+   |
|                                                                   |
+------------------------------------------------------------------+

模块二:FilesystemMiddleware (middleware/filesystem.py)

  • 模块名称:文件系统中间件

  • 设计说明:这是 Agent 最核心的工具提供者。它通过 wrap_model_call() 钩子向 LLM 动态注入 6 个文件操作工具 (ls, read_file, write_file, edit_file, glob, grep),并根据后端能力动态添加 execute (Shell 执行) 和 fs_download/fs_upload (文件传输) 工具。实现了细粒度的 FilesystemPermission 权限系统:规则按声明顺序匹配,支持 allow/deny/interrupt 三种模式。大文件 (>10MB) 自动卸载到磁盘并通过"内容预览"保留在上下文中。

  • 内部结构图

text
+----------------------------+
|   FilesystemMiddleware      |
+----------------------------+
|                             |
|  wrap_model_call() hook     |
|  +------------------------+ |
|  | 1. Inject fs tools     | |
|  |    - ls                | |
|  |    - read_file         | |
|  |    - write_file        | |
|  |    - edit_file         | |
|  |    - glob              | |
|  |    - grep              | |
|  |    - execute (if sand) | |
|  | 2. Apply Permissions   | |
|  | 3. Modify sys prompt   | |
|  +------------------------+ |
|           |                 |
|           v                 |
|  +------------------------+ |
|  | Backend Protocol       | |  ───>  Backend.ls()
|  | (abstraction layer)    | |  ───>  Backend.read()
|  +------------------------+ |  ───>  Backend.write()
|           |                 |  ───>  Backend.edit()
|           v                 |  ───>  Backend.grep()
|  +------------------------+ |  ───>  Backend.glob()
|  | Content Management     | |
|  | - _offload_large_content| |
|  | - _create_content_preview| |
|  | - truncate_if_too_long  | |
|  +------------------------+ |
+----------------------------+

模块三:SubAgentMiddleware (middleware/subagents.py)

  • 模块名称:子代理中间件

  • 设计说明:实现了 Agent 分层委派模式。暴露一个 task 工具给主 Agent,当 LLM 调用 task(subagent_name, description, prompt) 时,中间件创建一个隔离的 CompiledStateGraph 子代理实例并执行。子代理拥有独立的上下文窗口(不污染主 Agent 的消息历史)。支持三种规格:(1) SubAgent (声明式),(2) CompiledSubAgent (预编译的图),(3) AsyncSubAgent (远程后台任务)。默认为所有 Agent 添加一个 general-purpose 子代理。

  • 内部结构图

text
+----------------------------------------------------------+
|                  SubAgentMiddleware                       |
+----------------------------------------------------------+
|                                                           |
|  task_tool(name, description, prompt)                     |
|  +----------------------------------------------------+  |
|  | 1. Find subagent spec by name                      |  |
|  | 2. Build compiled graph (if SubAgent)              |  |
|  |    - create_agent(model, prompt, tools, middleware) |  |
|  | 3. Execute with isolation:                         |  |
|  |    - Fresh thread_id (context isolation)           |  |
|  |    - LangSmith tracing context propagation         |  |
|  |    - recursion_limit inheritance                   |  |
|  | 4. Return subagent result to parent                |  |
|  +----------------------------------------------------+  |
|                                                           |
|  SubAgent Types:                                          |
|  +----------------------------------------------------+  |
|  | [SubAgent]          Declarative spec                |  |
|  | [CompiledSubAgent]  Pre-compiled runnable           |  |
|  | [AsyncSubAgent]     Remote LangSmith deployment     |  |
|  | [GeneralPurpose]    Auto-added default subagent     |  |
|  +----------------------------------------------------+  |
+----------------------------------------------------------+

模块四:SummarizationMiddleware (middleware/summarization.py)

  • 模块名称:上下文摘要中间件

  • 设计说明:自动管理 Agent 的上下文窗口。当检测到消息历史接近模型上下文上限时(默认 75% 阈值 或 170K tokens),执行以下操作:(1) 将旧消息压缩为 LLM 生成的摘要,(2) 将大型工具输出卸载到后端存储(通过 _offload_tool_message_content),(3) 在消息中注入"内容已卸载"的占位符和索引。支持两种策略:SummarizationToolMiddleware (通过 summarize 工具由模型主动调用) 和 SummarizationMiddleware (自动触发)。

  • 内部结构图 (plainText)

text
+----------------------------------------------------------+
|              SummarizationMiddleware                      |
+----------------------------------------------------------+
|                                                           |
|  wrap_model_call() hook                                   |
|  +----------------------------------------------------+  |
|  | 1. Count tokens in current messages                 |  |
|  | 2. If nearing context limit:                        |  |
|  |    a. Archive old messages → generate summary       |  |
|  |    b. Offload large tool outputs → disk             |  |
|  |    c. Inject summary + placeholders                 |  |
|  | 3. Return truncated+summarized messages             |  |
|  +----------------------------------------------------+  |
|           |                                               |
|           v                                               |
|  +----------------------------------------------------+  |
|  | Offload Engine                                      |  |
|  | - _offload_tool_message_content(content)            |  |
|  | - _create_content_preview(content, max_lines)       |  |
|  | - check_empty_content()                             |  |
|  | - Too large? → writes to backend → returns preview  |  |
|  +----------------------------------------------------+  |
+----------------------------------------------------------+

模块五:可插拔后端系统 (backends/)

  • 模块名称:后端协议与实现体系

  • 设计说明:通过 BackendProtocol 抽象类定义统一的文件操作接口:(ls, read, write, edit, grep, glob, upload_files, download_files)。SandboxBackendProtocol 扩展了 execute() Shell 执行能力。五种后端实现支持不同使用场景:StateBackend (内存,测试用)、FilesystemBackend (本地磁盘)、CompositeBackend (默认→运行时→持久三层组合)、StoreBackend (LangGraph Store)、BaseSandbox (远程执行)。协议通过弃用路径 (deprecation path) 平滑迁移旧 API。

  • 内部结构图

text
+--------------------------------------------------------------+
|                    Backend Protocol Hierarchy                  |
+--------------------------------------------------------------+
|                                                               |
|  <<abstract>> BackendProtocol                                 |
|  +----------------------------------------------------------+ |
|  | + ls(path) → LsResult                                    | |
|  | + read(path, offset, limit) → ReadResult                 | |
|  | + write(path, content) → WriteResult                     | |
|  | + edit(path, old, new, replace_all) → EditResult         | |
|  | + grep(pattern, path, glob) → GrepResult                 | |
|  | + glob(pattern, path) → GlobResult                       | |
|  | + upload_files(files) → list[FileUploadResponse]         | |
|  | + download_files(paths) → list[FileDownloadResponse]     | |
|  | + async variants: als, aread, awrite, aedit, agrep, aglob| |
|  +----------------------------+------------------------------+ |
|                               |                                |
|               <<extends>>     |                                |
|  +----------------------------v------------------------------+ |
|  | <<abstract>> SandboxBackendProtocol                      | |
|  | + execute(command, timeout) → ExecuteResponse            | |
|  | + aexecute(command, timeout) → ExecuteResponse           | |
|  | + id: str                                                | |
|  +----------------------------+------------------------------+ |
|                               |                                |
+===============================|================================+
                                |
        +-----------------------+-----------------------+
        |                       |                       |
        v                       v                       v
+---------------+     +-----------------+     +------------------+
| StateBackend  |     | FilesystemBackend|    | CompositeBackend |
| (内存, 默认)  |     | (本地磁盘)       |    | (多层组合)       |
+---------------+     +-----------------+     +------------------+
        |                       |                       |
        v                       v                       v
+---------------+     +-----------------+     +------------------+
| StoreBackend  |     | Sandbox Backends|    | ContextHubBackend|
| (LangGraph    |     | (远程容器执行)  |    | (Context Hub)    |
|  Store持久化) |     +-----------------+     +------------------+
+---------------+

6. 关键数据流程

场景一:SDK 模式 - 创建 Agent 并执行任务

场景说明:用户通过 Python SDK 创建 Deep Agent 并调用 agent.invoke() 执行一个文件操作任务。此场景展示了从 API 调用到 LLM 交互的完整流程。

  • 流转时序图

场景二:CLI 交互模式 - dcode 启动到执行任务

场景说明:用户在终端运行 dcode -m "fix the bug in auth.py",经历了启动检查、模型配置、LangGraph Server 启动、TUI 渲染和 Agent 执行的完整流程。

流转时序图

场景三:子代理委派模式

场景说明:主 Agent 收到一个复杂的研究任务,使用 task 工具将子任务委派给 general-purpose 子代理,子代理拥有独立的上下文窗口。

流转时序图

7. 接口与契约规范

7.1 核心内部模块契约 (TypeScript-style Interfaces)

typescript
/**
 * 后端协议 - 文件操作核心契约
 */
interface BackendProtocol {
  ls(path: string): LsResult;
  read(filePath: string, offset?: number, limit?: number): ReadResult;
  write(filePath: string, content: string): WriteResult;
  edit(filePath: string, oldString: string, newString: string, replaceAll?: boolean): EditResult;
  grep(pattern: string, path?: string, glob?: string): GrepResult;
  glob(pattern: string, path?: string): GlobResult;
  uploadFiles(files: Array<[string, Uint8Array]>): FileUploadResponse[];
  downloadFiles(paths: string[]): FileDownloadResponse[];
}

/**
 * 沙箱后端协议 - 添加 Shell 执行能力
 */
interface SandboxBackendProtocol extends BackendProtocol {
  readonly id: string;
  execute(command: string, timeout?: number): ExecuteResponse;
}

/**
 * Agent 中间件核心契约
 */
interface AgentMiddleware<TState, TContext, TResponse> {
  /** 拦截 LLM 请求,注入工具/提示/过滤 */
  wrapModelCall?(
    request: ModelRequest,
    handler: (req: ModelRequest) => Promise<ModelResponse>
  ): Promise<ModelResponse>;

  /** 中间件专用状态 Schema */
  state_schema?: StateSchema;

  /** 中间件提供的工具列表 */
  tools?: Tool[];
}

/**
 * 子代理规格
 */
interface SubAgent {
  name: string;           // 唯一标识符
  description: string;    // 功能描述
  system_prompt: string;  // 系统指令
  tools?: Tool[];          // 工具列表 (默认继承父代理)
  model?: string | BaseChatModel;  // 模型覆写
  middleware?: AgentMiddleware[];   // 额外中间件
  interrupt_on?: Record<string, boolean | InterruptOnConfig>;
  skills?: string[];      // 技能源路径
  permissions?: FilesystemPermission[];  // 文件系统权限
}

/**
 * 文件系统权限规则
 */
interface FilesystemPermission {
  operations: Array<"read" | "write">;
  paths: string[];
  mode: "allow" | "deny" | "interrupt";
}

/**
 * Harness Profile
 */
interface HarnessProfile {
  base_system_prompt?: string;       // 基础系统提示 (替代默认 BASE)
  system_prompt_suffix?: string;     // 系统提示后缀
  excluded_tools?: string[];          // 排除工具列表
  excluded_middleware?: Array<string | AgentMiddlewareType>;  // 排除中间件
  tool_description_overrides?: Record<string, string>;  // 工具描述覆写
  extra_middleware?: AgentMiddleware[];  // 额外中间件
  general_purpose_subagent?: GeneralPurposeSubagentProfile;
}

7.2 对外 API 契约 (create_deep_agent 参数规范)

yaml
# create_deep_agent() 函数签名契约
function: create_deep_agent
description: 创建完整配置的 Deep Agent

parameters:
  - name: model
    type: str | BaseChatModel
    required: true
    description: >
      LLM 模型。支持 provider:model 格式字符串 (如 'openai:gpt-5.5')
      或预初始化的 BaseChatModel 实例

  - name: tools
    type: Sequence[BaseTool | Callable | dict]
    required: false
    description: 额外工具列表 (与内置工具合并)

  - name: system_prompt
    type: str | SystemMessage | None
    required: false
    description: 自定义系统指令 (置于默认提示之前)

  - name: middleware
    type: Sequence[AgentMiddleware]
    required: false
    description: 额外中间件 (置于基础栈之后, 尾部栈之前)

  - name: subagents
    type: Sequence[SubAgent | CompiledSubAgent | AsyncSubAgent]
    required: false
    description: 子代理定义列表

  - name: skills
    type: list[str]
    required: false
    description: 技能源路径列表 (POSIX 路径, 相对于 backend 根目录)

  - name: memory
    type: list[str]
    required: false
    description: 内存文件路径列表 (AGENTS.md 文件)

  - name: permissions
    type: list[FilesystemPermission]
    required: false
    description: 文件系统权限规则 (按声明顺序匹配)

  - name: backend
    type: BackendProtocol | BackendFactory
    required: false
    description: 可插拔存储后端 (默认 StateBackend)

  - name: interrupt_on
    type: dict[str, bool | InterruptOnConfig]
    required: false
    description: 工具级别的人机交互中断配置

  - name: checkpointer
    type: Checkpointer | None
    required: false
    description: LangGraph 检查点 (启用持久化)

  - name: store
    type: BaseStore | None
    required: false
    description: LangGraph Store (用于 StoreBackend)

returns:
  type: CompiledStateGraph[AgentState, ContextT, ...]
  description: 已编译的 LangGraph StateGraph
  config:
    recursion_limit: 9999
    metadata:
      ls_integration: "deepagents"
      versions:
        deepagents: "<version>"