create-deepagent-server 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +83 -8
  2. package/package.json +1 -1
  3. package/src/args.js +6 -4
  4. package/src/cli.js +1 -4
  5. package/src/dependencies.js +1 -1
  6. package/src/prompts.js +1 -0
  7. package/src/registry.js +8 -8
  8. package/src/scaffold.js +21 -7
  9. package/src/setup.js +2 -0
  10. package/src/version.js +1 -1
  11. package/src/versions.js +1 -1
  12. package/templates/deepagent/js/scripts/check.js +34 -11
  13. package/templates/deepagent/js/scripts/dev.js +9 -0
  14. package/templates/deepagent/js/src/agents/factory.js +2 -1
  15. package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
  16. package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
  17. package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
  18. package/templates/deepagent/js/src/agents/state/types.js +1 -0
  19. package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
  20. package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
  21. package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
  22. package/templates/deepagent/js/src/agents/supervisor.js +12 -4
  23. package/templates/deepagent/js/src/api/app.js +7 -0
  24. package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
  25. package/templates/deepagent/js/src/api/middleware/error.js +4 -0
  26. package/templates/deepagent/js/src/api/routes/agent.js +19 -49
  27. package/templates/deepagent/js/src/api/routes/health.js +12 -3
  28. package/templates/deepagent/js/src/api/routes/session.js +28 -48
  29. package/templates/deepagent/js/src/app.js +31 -12
  30. package/templates/deepagent/js/src/backends/composite.js +2 -0
  31. package/templates/deepagent/js/src/backends/filesystem.js +1 -0
  32. package/templates/deepagent/js/src/backends/index.js +35 -3
  33. package/templates/deepagent/js/src/backends/sandbox.js +3 -0
  34. package/templates/deepagent/js/src/config/agent.js +1 -0
  35. package/templates/deepagent/js/src/config/database.js +19 -0
  36. package/templates/deepagent/js/src/config/env.js +46 -23
  37. package/templates/deepagent/js/src/config/index.js +13 -3
  38. package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
  39. package/templates/deepagent/js/src/graph/compile.js +1 -0
  40. package/templates/deepagent/js/src/graph/store.js +10 -2
  41. package/templates/deepagent/js/src/index.js +9 -2
  42. package/templates/deepagent/js/src/memory/index.js +2 -0
  43. package/templates/deepagent/js/src/memory/manager.js +21 -10
  44. package/templates/deepagent/js/src/memory/store.js +7 -0
  45. package/templates/deepagent/js/src/middleware/approval.js +6 -1
  46. package/templates/deepagent/js/src/middleware/context.js +5 -0
  47. package/templates/deepagent/js/src/middleware/logging.js +47 -43
  48. package/templates/deepagent/js/src/middleware/security.js +7 -0
  49. package/templates/deepagent/js/src/model/config.js +38 -0
  50. package/templates/deepagent/js/src/model/index.js +9 -0
  51. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  52. package/templates/deepagent/js/src/model/presets.js +71 -0
  53. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  54. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  55. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  56. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  57. package/templates/deepagent/js/src/schemas/agent.js +7 -0
  58. package/templates/deepagent/js/src/schemas/common.js +5 -0
  59. package/templates/deepagent/js/src/schemas/locale.js +1 -0
  60. package/templates/deepagent/js/src/schemas/session.js +4 -0
  61. package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
  62. package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
  63. package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
  64. package/templates/deepagent/js/src/skills/index.js +4 -0
  65. package/templates/deepagent/js/src/skills/loader.js +20 -10
  66. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  67. package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
  68. package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
  69. package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
  70. package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
  71. package/templates/deepagent/js/src/tools/database/index.js +1 -1
  72. package/templates/deepagent/js/src/tools/database/query.js +44 -32
  73. package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
  74. package/templates/deepagent/js/src/tools/index.js +6 -11
  75. package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
  76. package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
  77. package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
  78. package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
  79. package/templates/deepagent/js/src/utils/errors.js +9 -0
  80. package/templates/deepagent/js/src/utils/helpers.js +15 -0
  81. package/templates/deepagent/js/src/utils/validation.js +15 -0
  82. package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
  83. package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
  84. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  85. package/templates/deepagent/js/tests/integration/api.test.js +18 -3
  86. package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
  87. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  88. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  89. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  90. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  91. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +5 -1
  93. package/templates/deepagent/shared/README.md +101 -14
  94. package/templates/deepagent/shared/_env.example +40 -10
  95. package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
  96. package/templates/deepagent/shared/resources/AGENTS.md +1 -1
  97. package/templates/deepagent/ts/scripts/check.ts +19 -11
  98. package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
  99. package/templates/deepagent/ts/src/agents/factory.ts +1 -1
  100. package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
  101. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
  102. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
  103. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
  104. package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
  105. package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
  106. package/templates/deepagent/ts/src/api/app.ts +4 -4
  107. package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
  108. package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
  109. package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
  110. package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
  111. package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
  112. package/templates/deepagent/ts/src/app.ts +19 -12
  113. package/templates/deepagent/ts/src/backends/index.ts +41 -7
  114. package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
  115. package/templates/deepagent/ts/src/config/database.ts +21 -0
  116. package/templates/deepagent/ts/src/config/env.ts +32 -28
  117. package/templates/deepagent/ts/src/config/index.ts +12 -4
  118. package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
  119. package/templates/deepagent/ts/src/graph/store.ts +5 -2
  120. package/templates/deepagent/ts/src/index.ts +2 -2
  121. package/templates/deepagent/ts/src/memory/manager.ts +12 -10
  122. package/templates/deepagent/ts/src/memory/store.ts +2 -0
  123. package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
  124. package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
  125. package/templates/deepagent/ts/src/middleware/security.ts +1 -0
  126. package/templates/deepagent/ts/src/model/config.ts +56 -0
  127. package/templates/deepagent/ts/src/model/index.ts +14 -0
  128. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  129. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  130. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  131. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  132. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  133. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  134. package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
  135. package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
  136. package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
  137. package/templates/deepagent/ts/src/skills/loader.ts +6 -10
  138. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  139. package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
  140. package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
  141. package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
  142. package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
  143. package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
  144. package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
  145. package/templates/deepagent/ts/src/tools/index.ts +10 -8
  146. package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
  147. package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
  148. package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
  149. package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
  150. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  151. package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
  152. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
  153. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  154. package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
  155. package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
  156. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  157. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  158. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  159. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  160. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  161. package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
  162. package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
  163. package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
  164. package/templates/deepagent/js/src/config/model.js +0 -34
  165. package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
  166. package/templates/deepagent/js/src/tools/search/index.js +0 -1
  167. package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
  168. package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
  169. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
  170. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
  171. package/templates/deepagent/ts/src/config/model.ts +0 -49
  172. package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
  173. package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
  174. package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
  175. /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
@@ -4,13 +4,15 @@
4
4
 
5
5
  - 仅使用 ESM、现代 ES6+ 语法,Node.js 22.6+
6
6
  - 默认 JavaScript,可选 TypeScript
7
+ - 模型统一走 OpenAI 兼容协议,默认 MiniMax M3;改环境变量即可切换 OpenAI / DeepSeek / Kimi / MiniMax / 通义千问 / 智谱 / OpenRouter / vLLM / Ollama
8
+ - 可选 OpenSandbox 远程沙箱:`SANDBOX_ENABLED=true` 时 `execute` 与 `/workspace/` 都落在隔离环境中
7
9
  - LangGraph checkpointer + store(默认内存,可切换 PostgreSQL)
8
10
  - Express 5 API:Bearer 鉴权、SSE 流式输出、结构化日志
9
11
 
10
12
  ## 快速开始
11
13
 
12
14
  ```bash
13
- cp .env.example .env # 填入 OPENAI_API_KEY 或 ANTHROPIC_API_KEY
15
+ # .env 已自动生成,填入 MODEL_API_KEY 即可(示例默认 MiniMax M3)
14
16
  npm run check # 可选:启动前环境检查
15
17
  npm run dev # http://localhost:3000/health
16
18
  ```
@@ -47,18 +49,20 @@ curl -X POST http://localhost:3000/api/agents/invoke \
47
49
  src/
48
50
  ├── index.ts|js 入口:配置 → 应用 → HTTP 服务
49
51
  ├── app.ts 应用装配(测试和脚本复用同一套装配)
50
- ├── config/ 环境变量、模型与 Agent 配置
52
+ ├── config/ 环境变量与 Agent 配置
53
+ ├── model/ 模型配置:OpenAI 兼容接入、服务商预设
51
54
  ├── agents/ 主 Agent、子 Agent、提示词、自定义状态
52
- ├── tools/ Web 搜索、只读 SQL、工作区文件、MCP
55
+ ├── tools/ 只读 SQL、工作区文件、MCP
53
56
  ├── middleware/ 日志、安全、审批、运行时上下文
54
57
  ├── backends/ 文件系统 / 沙箱 / 组合后端
58
+ ├── sandbox/ OpenSandbox 远程沙箱(可选执行后端)
55
59
  ├── memory/ 长期记忆(BaseStore)封装
56
60
  ├── skills/ SKILL.md 发现与校验
57
61
  ├── graph/ createDeepAgent 编译、checkpointer、store
58
62
  ├── services/ Agent、会话、记忆服务
59
63
  ├── api/ Express 应用、路由与中间件
60
64
  ├── schemas/ Zod 请求/响应结构
61
- ├── infrastructure/ PostgreSQL、Redis、pino 日志、优雅关闭
65
+ ├── storage/ PostgreSQL、Redis、pino 日志、优雅关闭
62
66
  └── utils/
63
67
  resources/ AGENTS.md + 知识库,挂载到 /resources/
64
68
  skills/ SKILL.md,挂载到 /skills/
@@ -72,9 +76,9 @@ deployment/ Dockerfile + docker-compose
72
76
 
73
77
  `src/app.ts` 通过 `createSupervisorAgent` 构建一个主 Agent:
74
78
 
75
- - **模型** —— `src/config/model.ts`(OpenAI 或 Anthropic,整个进程共用一个实例)。
76
- - **后端** —— `src/backends/composite.ts` 把 `/workspace/`、`/resources/`、`/skills/` 挂载到磁盘,把 `/memories/` 挂载到 LangGraph store。`ENABLE_SHELL=true` 时默认后端切换为 `LocalShellBackend` 并暴露 `execute`。
77
- - **子 Agent** —— `researcher`(Tavily 搜索)、`coder`(工作区改代码)、`analyst`(只读 SQL)。它们都是声明式 `SubAgent`,各自拥有独立上下文窗口。
79
+ - **模型** —— `src/model/`:`resolveModelConfig()` 解析环境变量,`createChatModel()` 用 `ChatOpenAI` 指向任意 OpenAI 兼容地址,整个进程共用一个实例。服务商预设见 `src/model/presets`。
80
+ - **后端** —— `src/backends/composite.ts` 把 `/workspace/`、`/resources/`、`/skills/` 挂载到磁盘,把 `/memories/` 挂载到 LangGraph store。`ENABLE_SHELL=true` 时默认后端切换为 `LocalShellBackend` 并暴露 `execute`;`SANDBOX_ENABLED=true` 时后端按 `threadId` 切换为对应会话的 OpenSandbox,`/workspace/` 与 `execute` 都落在该会话的远程沙箱内。
81
+ - **子 Agent** —— `coder`(工作区改代码)、`analyst`(只读 SQL)。它们都是声明式 `SubAgent`,各自拥有独立上下文窗口。
78
82
  - **提示词** —— `src/agents/prompts/` 下的纯 Markdown。`loadPrompt()` 读取文件,`renderPrompt()` 填充 `{{占位符}}`;TypeScript 项目构建时会把 `.md` 复制到 `dist/`。提示词在 Agent 构建时读取,修改后需重启 dev server。
79
83
  - **中间件** —— 调用日志、危险工具拦截、按请求注入租户/用户上下文。
80
84
  - **审批** —— `APPROVAL_MODE=sensitive`(默认)会通过 `interruptOn` 暂停有副作用的工具。中断响应包含 `interrupts`,用同一个 `threadId` 调用 `POST /api/agents/resume` 批准后继续。
@@ -119,24 +123,75 @@ curl -N -X POST http://localhost:3000/api/agents/stream \
119
123
 
120
124
  | 变量 | 默认值 | 说明 |
121
125
  | --- | --- | --- |
122
- | `MODEL_PROVIDER` | `openai` | `openai` 或 `anthropic` |
123
- | `MODEL_NAME` | 按提供商选择 | `gpt-4.1-mini` / `claude-sonnet-4-5` |
126
+ | `MODEL_PROVIDER` | `minimax` | 预设地址:`openai`、`deepseek`、`moonshot`、`minimax`、`qwen`、`zhipu`、`openrouter`、`ollama`、`vllm`、`custom` |
127
+ | `MODEL_NAME` | 按预设选择 | 模型名,默认 `MiniMax-M3`;切换服务商时同步修改 |
128
+ | `MODEL_MAX_COMPLETION_TOKENS` | `32768` | 生成上限(含思考 token);M3 最高 128K |
129
+ | `MODEL_BASE_URL` | 预设地址 | 覆盖预设,用于自建网关、代理或私有化部署 |
130
+ | `MODEL_API_KEY` | — | 所接入服务的 Key;本地服务可填任意非空值 |
124
131
  | `APPROVAL_MODE` | `sensitive` | `none`、`sensitive`、`all` |
125
132
  | `ENABLE_SHELL` | `false` | 是否在宿主机暴露 `execute` |
126
- | `CHECKPOINTER` / `STORE` | `memory` | 设为 `postgres` 需要 `DATABASE_URL` |
127
- | `TAVILY_API_KEY` | — | 启用 `web_search` |
133
+ | `SANDBOX_ENABLED` | `false` | 开启 OpenSandbox 远程沙箱,作为执行后端(按会话惰性创建) |
134
+ | `OPEN_SANDBOX_DOMAIN` / `OPEN_SANDBOX_API_KEY` | `localhost:8080` / — | OpenSandbox 服务地址与 API Key |
135
+ | `OPEN_SANDBOX_PROTOCOL` | `http` | `http` 或 `https` |
136
+ | `OPEN_SANDBOX_ID` | — | 共享模式:所有会话连接同一个已有沙箱,退出时只关闭连接 |
137
+ | `SANDBOX_IMAGE` / `SANDBOX_TIMEOUT_SECONDS` | `python:3.12` / `1800` | 沙箱镜像与 TTL(秒);使用中按 TTL/3 续期,`0` 表示不过期 |
138
+ | `SANDBOX_WORKSPACE_ROOT` | `/workspace` | 沙箱工作目录,也是 `execute` 的默认 cwd |
139
+ | `CHECKPOINTER` / `STORE` | `memory` | 设为 `postgres` 时启用 PostgreSQL 持久化 |
140
+ | `POSTGRES_HOST` / `POSTGRES_PORT` | `localhost` / `5432` | PostgreSQL 地址 |
141
+ | `POSTGRES_USERNAME` / `POSTGRES_PASSWORD` | `postgres` / `postgres` | PostgreSQL 凭证 |
142
+ | `POSTGRES_DATABASE` | `deepagent` | PostgreSQL 数据库名 |
143
+ | `DATABASE_URL` | — | 可选完整连接串,优先于上面的 `POSTGRES_*` |
128
144
  | `MCP_SERVERS` | — | MCP 服务器的 JSON 映射 |
129
145
  | `LANGSMITH_TRACING` | `false` | 配合 `LANGSMITH_API_KEY` 开启链路追踪 |
130
146
 
147
+ ### 接入模型
148
+
149
+ 模型层只依赖 OpenAI 兼容协议(`POST {baseUrl}/chat/completions`),更换服务商不需要改代码:
150
+
151
+ ```bash
152
+ # DeepSeek
153
+ MODEL_PROVIDER=deepseek
154
+ MODEL_NAME=deepseek-chat
155
+ MODEL_API_KEY=sk-...
156
+
157
+ # MiniMax(国内站;国际站用 MODEL_BASE_URL=https://api.minimax.io/v1)
158
+ MODEL_PROVIDER=minimax
159
+ MODEL_NAME=MiniMax-M3
160
+ MODEL_API_KEY=sk-...
161
+
162
+ # 通义千问(阿里云百炼)
163
+ MODEL_PROVIDER=qwen
164
+ MODEL_NAME=qwen-plus
165
+ MODEL_API_KEY=sk-...
166
+
167
+ # 本地 Ollama:Key 可填任意非空值
168
+ MODEL_PROVIDER=ollama
169
+ MODEL_NAME=qwen3:8b
170
+ MODEL_API_KEY=ollama
171
+ ```
172
+
173
+ 自建网关或私有化部署用 `MODEL_PROVIDER=custom` 并同时指定 `MODEL_BASE_URL` 与 `MODEL_NAME`。
174
+ 预设列表和默认模型在 `src/model/presets`;需要额外参数(超时、重试、自定义请求头等)时,调整 `src/model/openai-compatible` 里 `ChatOpenAI` 的构造参数即可。
175
+
131
176
  ### PostgreSQL
132
177
 
133
- 设置 `CHECKPOINTER=postgres`、`STORE=postgres`,然后启动数据库:
178
+ 设置 `CHECKPOINTER=postgres` 或 `STORE=postgres` 后,服务会用 `POSTGRES_*` 分项拼装连接信息;同时设置 `DATABASE_URL` 时优先使用完整连接串。
179
+
180
+ | 变量 | 默认值 |
181
+ | --- | --- |
182
+ | `POSTGRES_HOST` | `localhost` |
183
+ | `POSTGRES_PORT` | `5432` |
184
+ | `POSTGRES_USERNAME` | `postgres` |
185
+ | `POSTGRES_PASSWORD` | `postgres` |
186
+ | `POSTGRES_DATABASE` | `deepagent` |
187
+
188
+ 本地启动数据库:
134
189
 
135
190
  ```bash
136
191
  docker compose -f deployment/docker-compose.yml up -d postgres
137
192
  ```
138
193
 
139
- `PostgresSaver.setup()` / `PostgresStore.setup()` 会在启动时自动建表。`src/infrastructure/database/migrations/001_init.sql` 提供了一个可选的审计日志表。
194
+ `PostgresSaver.setup()` / `PostgresStore.setup()` 会在启动时自动建表。`src/storage/database/migrations/001_init.sql` 提供了一个可选的审计日志表。
140
195
 
141
196
  ### MCP
142
197
 
@@ -146,6 +201,38 @@ MCP_SERVERS='{"filesystem":{"transport":"stdio","command":"npx","args":["-y","@m
146
201
 
147
202
  工具会在启动时加载,并合并进主 Agent 的工具列表。
148
203
 
204
+ ### 沙箱(OpenSandbox)
205
+
206
+ [OpenSandbox](https://open-sandbox.ai/) 为 Agent 提供隔离的代码执行环境。先启动服务(默认 `http://127.0.0.1:8080`):
207
+
208
+ ```bash
209
+ uvx opensandbox-server init-config ~/.sandbox.toml --example docker
210
+ uvx opensandbox-server
211
+ ```
212
+
213
+ 然后在 `.env` 中开启:
214
+
215
+ ```bash
216
+ SANDBOX_ENABLED=true
217
+ OPEN_SANDBOX_DOMAIN=localhost:8080
218
+ SANDBOX_IMAGE=python:3.12
219
+ SANDBOX_TIMEOUT_SECONDS=1800
220
+ ```
221
+
222
+ 开启后:
223
+
224
+ - **按会话隔离**:每个 `threadId` 第一次运行 Agent 时惰性创建一个沙箱(不是在服务启动时),该会话后续的消息、工具调用和子 Agent 都复用同一个后端;不同会话互不影响;
225
+ - `/workspace/` 与 `execute` 在各自会话的沙箱内执行;`AGENTS.md`、`SKILL.md` 仍在启动时从本地读取并注入提示词,`/memories/` 继续使用 LangGraph store;
226
+ - 开启沙箱后 `ENABLE_SHELL` 不再生效,宿主机的 `execute` 不会被暴露;
227
+ - `execute` 在该会话的沙箱内维护一个持久 bash session,`cd`、`export`、函数定义等状态跨命令保留;同一会话的命令串行排队,避免互相覆盖 shell 状态;
228
+ - **过期与续期**:沙箱默认 TTL 1800 秒,每次使用间隔超过 TTL 的三分之一会调用 `renew` 续期,所以活跃会话不会被回收;空闲超过 TTL 由服务端回收,下次访问自动重建(沙箱内的 `/workspace` 内容随之丢失);
229
+ - `DELETE /api/sessions/:threadId` 会释放对应沙箱;进程退出时销毁所有沙箱;
230
+ - 设置 `OPEN_SANDBOX_ID` 时切换为共享模式:所有会话连接同一个已有沙箱,退出时只关闭连接、不会 `kill` 它。
231
+
232
+ > `SANDBOX_TIMEOUT_SECONDS=0` 表示不设置服务端 TTL,完全由应用在删除会话 / 退出时清理;进程崩溃时会留下无人回收的沙箱,生产环境建议保留默认 TTL。
233
+
234
+ 实现位于 `src/sandbox/`:`OpenSandboxBackend` 继承 deepagents 的 `BaseSandbox`,只实现 `execute` 与文件上传/下载,`ls`、`read`、`grep` 等由 `BaseSandbox` 复用同一 session 完成。
235
+
149
236
  ## Docker
150
237
 
151
238
  ```bash
@@ -157,6 +244,6 @@ docker compose -f deployment/docker-compose.yml up --build
157
244
  Deep Agents 遵循“信任模型”的策略:工具允许什么,Agent 就能做什么。模板提供了一些纵深防御(危险命令拦截、只读 SQL 事务、审批、工作区隔离),但真正的边界必须在部署层保证:
158
245
 
159
246
  - 除非运行在一次性容器中,否则保持 `ENABLE_SHELL=false`。
160
- - `DATABASE_URL` 使用只读数据库角色。
247
+ - PostgreSQL 连接使用只读数据库角色。
161
248
  - 对公网部署时,在 API 前增加鉴权与限流。
162
249
  - 仔细审查新增的 `SKILL.md` 和 `AGENTS.md`,它们会成为模型指令。
@@ -7,15 +7,23 @@ PORT=3000
7
7
  LOG_LEVEL=info
8
8
 
9
9
  # ---------------------------------------------------------------------------
10
- # 模型(openai | anthropic),请填写对应的 API Key
10
+ # 模型:统一通过 OpenAI 兼容协议接入
11
+ #
12
+ # 默认使用 MiniMax M3(国内站 https://api.minimaxi.com/v1)
13
+ # MODEL_PROVIDER 选择预设地址:openai | deepseek | moonshot | minimax | qwen |
14
+ # zhipu | openrouter | ollama | vllm | custom(预设见 src/model/presets)
11
15
  # ---------------------------------------------------------------------------
12
- MODEL_PROVIDER=openai
13
- MODEL_NAME=gpt-4.1-mini
16
+ MODEL_PROVIDER=minimax
17
+ # 不填时使用预设的默认模型;换服务商时请一并修改
18
+ MODEL_NAME=MiniMax-M3
14
19
  MODEL_TEMPERATURE=0.2
15
- MODEL_MAX_TOKENS=4096
16
- OPENAI_API_KEY=
17
- # OPENAI_BASE_URL=https://api.openai.com/v1
18
- # ANTHROPIC_API_KEY=
20
+ # 单次生成上限(含思考 token);M3 最高 128K,长文/长代码场景可调大
21
+ MODEL_MAX_COMPLETION_TOKENS=32768
22
+ # 所接入服务的 API Key;本地服务(Ollama、vLLM)可填任意非空值
23
+ MODEL_API_KEY=
24
+ # 覆盖预设地址,用于自建网关、代理或私有化部署
25
+ # MiniMax 国际站为 https://api.minimax.io/v1
26
+ # MODEL_BASE_URL=https://api.minimaxi.com/v1
19
27
 
20
28
  # ---------------------------------------------------------------------------
21
29
  # Agent
@@ -32,20 +40,42 @@ WORKSPACE_ROOT=workspaces
32
40
  RESOURCES_ROOT=resources
33
41
  SKILLS_ROOT=skills
34
42
 
43
+ # ---------------------------------------------------------------------------
44
+ # 沙箱(OpenSandbox):开启后按会话(threadId)惰性创建并复用远程沙箱
45
+ # ---------------------------------------------------------------------------
46
+ SANDBOX_ENABLED=false
47
+ OPEN_SANDBOX_DOMAIN=localhost:8080
48
+ OPEN_SANDBOX_PROTOCOL=http
49
+ OPEN_SANDBOX_API_KEY=
50
+ # 共享已有沙箱:设置 ID 后所有会话连接同一个沙箱,退出时不会 kill 它
51
+ # OPEN_SANDBOX_ID=
52
+ SANDBOX_IMAGE=python:3.12
53
+ # 沙箱 TTL(秒):使用中按 TTL/3 自动续期,空闲超过该时长由服务端回收;
54
+ # 到期后再次访问会自动重建(沙箱内的 /workspace 内容随之丢失)。0 表示不设置 TTL。
55
+ SANDBOX_TIMEOUT_SECONDS=1800
56
+ SANDBOX_WORKSPACE_ROOT=/workspace
57
+
35
58
  # ---------------------------------------------------------------------------
36
59
  # 工具
37
60
  # ---------------------------------------------------------------------------
38
- TAVILY_API_KEY=
39
61
  # MCP 服务器 JSON 配置,例如:
40
62
  # MCP_SERVERS={"filesystem":{"transport":"stdio","command":"npx","args":["-y","@modelcontextprotocol/server-filesystem","."]}}
41
63
 
42
64
  # ---------------------------------------------------------------------------
43
- # 持久化
65
+ # 持久化:PostgreSQL / Redis
66
+ #
67
+ # CHECKPOINTER/STORE 设为 postgres 时,用下面的 POSTGRES_* 分项拼装连接串;
68
+ # 若同时设置 DATABASE_URL,则以 DATABASE_URL 为准。
44
69
  # ---------------------------------------------------------------------------
45
70
  # memory | postgres
46
71
  CHECKPOINTER=memory
47
72
  STORE=memory
48
- DATABASE_URL=
73
+ # DATABASE_URL=postgresql://postgres:postgres@localhost:5432/deepagent
74
+ POSTGRES_HOST=localhost
75
+ POSTGRES_PORT=5432
76
+ POSTGRES_USERNAME=postgres
77
+ POSTGRES_PASSWORD=postgres
78
+ POSTGRES_DATABASE=deepagent
49
79
  REDIS_URL=
50
80
 
51
81
  # ---------------------------------------------------------------------------
@@ -11,7 +11,11 @@ services:
11
11
  environment:
12
12
  NODE_ENV: production
13
13
  HOST: 0.0.0.0
14
- DATABASE_URL: postgres://deepagent:deepagent@postgres:5432/deepagent
14
+ POSTGRES_HOST: postgres
15
+ POSTGRES_PORT: "5432"
16
+ POSTGRES_USERNAME: postgres
17
+ POSTGRES_PASSWORD: postgres
18
+ POSTGRES_DATABASE: deepagent
15
19
  REDIS_URL: redis://redis:6379
16
20
  CHECKPOINTER: postgres
17
21
  STORE: postgres
@@ -25,15 +29,15 @@ services:
25
29
  postgres:
26
30
  image: postgres:17-alpine
27
31
  environment:
28
- POSTGRES_USER: deepagent
29
- POSTGRES_PASSWORD: deepagent
32
+ POSTGRES_USER: postgres
33
+ POSTGRES_PASSWORD: postgres
30
34
  POSTGRES_DB: deepagent
31
35
  ports:
32
36
  - "5432:5432"
33
37
  volumes:
34
38
  - postgres-data:/var/lib/postgresql/data
35
39
  healthcheck:
36
- test: ["CMD-SHELL", "pg_isready -U deepagent -d deepagent"]
40
+ test: ["CMD-SHELL", "pg_isready -U postgres -d deepagent"]
37
41
  interval: 5s
38
42
  timeout: 5s
39
43
  retries: 10
@@ -6,7 +6,7 @@
6
6
 
7
7
  - Deep Agents + LangGraph 的 ESM 服务。
8
8
  - 入口:`src/index.ts`(或 `.js`);应用装配:`src/app.ts`(或 `.js`)。
9
- - 主 Agent 会把任务分派给 `researcher`、`coder`、`analyst` 三个子 Agent。
9
+ - 主 Agent 会把任务分派给 `coder`、`analyst` 两个子 Agent。
10
10
 
11
11
  ## 常用命令
12
12
 
@@ -2,10 +2,9 @@ import "dotenv/config";
2
2
 
3
3
  import fs from "node:fs/promises";
4
4
 
5
- import { loadConfig } from "../src/config/index.js";
6
- import { loadEnv } from "../src/config/env.js";
7
- import { checkDatabase } from "../src/infrastructure/database/client.js";
8
- import { checkRedis } from "../src/infrastructure/redis/client.js";
5
+ import { loadConfig, loadEnv } from "../src/config/index.js";
6
+ import { checkDatabase } from "../src/storage/database/client.js";
7
+ import { checkRedis } from "../src/storage/redis/client.js";
9
8
  import { discoverSkills, validateSkills } from "../src/skills/index.js";
10
9
 
11
10
  /**
@@ -26,12 +25,12 @@ const note = (message: string): void => {
26
25
  console.log(` ▲ ${message}`);
27
26
  };
28
27
 
29
- const providerKey = env.MODEL_PROVIDER === "anthropic" ? env.ANTHROPIC_API_KEY : env.OPENAI_API_KEY;
28
+ const providerKey = env.MODEL_API_KEY;
30
29
 
31
30
  report(
32
- `${env.MODEL_PROVIDER} 凭证`,
31
+ `模型 ${config.model.label}/${config.model.name}`,
33
32
  Boolean(providerKey),
34
- providerKey ? "已配置" : "未配置(请设置 OPENAI_API_KEY 或 ANTHROPIC_API_KEY)",
33
+ providerKey ? config.model.baseUrl : `${config.model.baseUrl} — 未配置 MODEL_API_KEY`,
35
34
  );
36
35
 
37
36
  for (const [label, directory] of Object.entries({
@@ -59,10 +58,11 @@ const hasAgentsFile = await fs
59
58
  .stat(resourcesFile)
60
59
  .then((stats) => stats.isFile())
61
60
  .catch(() => false);
61
+
62
62
  report("AGENTS.md", hasAgentsFile, resourcesFile);
63
63
 
64
64
  if (config.database.url) {
65
- const health = await checkDatabase();
65
+ const health = await checkDatabase(config.database.url);
66
66
  report("postgres", health.ok, health.ok ? `${health.latencyMs}ms` : (health.error ?? "不可用"));
67
67
  } else {
68
68
  console.log("• postgres —— 未配置(使用内存 checkpointer/store)");
@@ -75,10 +75,18 @@ if (config.redis.url) {
75
75
  console.log("• redis —— 未配置(可选)");
76
76
  }
77
77
 
78
- if (env.TAVILY_API_KEY) {
79
- console.log("• Web 搜索 —— 已配置 Tavily Key");
78
+ if (config.sandbox.enabled) {
79
+ const ttl = config.sandbox.timeoutSeconds
80
+ ? `TTL ${config.sandbox.timeoutSeconds}s`
81
+ : "TTL 关闭";
82
+ const target = config.sandbox.sandboxId
83
+ ? `共享 ${config.sandbox.sandboxId},${ttl}`
84
+ : `按会话创建,镜像 ${config.sandbox.image},${ttl}`;
85
+ console.log(
86
+ `• 沙箱 —— OpenSandbox ${config.sandbox.protocol}://${config.sandbox.domain}(${target})`,
87
+ );
80
88
  } else {
81
- console.log("• Web 搜索 —— 未启用(设置 TAVILY_API_KEY 后启用)");
89
+ console.log("• 沙箱 —— 未启用(设置 SANDBOX_ENABLED=true 后启用)");
82
90
  }
83
91
 
84
92
  console.log("");
@@ -14,6 +14,7 @@ const ASSET_EXTENSIONS = new Set([".md", ".sql"]);
14
14
  const copyAssets = async (sourceDir: string, targetDir: string): Promise<number> => {
15
15
  const entries = await readdir(sourceDir, { withFileTypes: true });
16
16
  await mkdir(targetDir, { recursive: true });
17
+
17
18
  let copied = 0;
18
19
 
19
20
  for (const entry of entries) {
@@ -32,4 +33,5 @@ const copyAssets = async (sourceDir: string, targetDir: string): Promise<number>
32
33
  };
33
34
 
34
35
  const copied = await copyAssets(SOURCE, TARGET);
36
+
35
37
  console.log(`已将 ${copied} 个资源文件复制到 dist/。`);
@@ -1,4 +1,4 @@
1
- import { compileAgentGraph, type AgentOptions, type CompiledAgent } from "../graph/compile.js";
1
+ import { compileAgentGraph, type AgentOptions, type CompiledAgent } from "../graph/index.js";
2
2
 
3
3
  /**
4
4
  * 对 `compileAgentGraph` 的轻量封装:共享默认配置(模型、后端、
@@ -22,6 +22,7 @@ export const loadPrompt = (name: string): string => {
22
22
  try {
23
23
  const content = readFileSync(file, "utf8").trim();
24
24
  cache.set(name, content);
25
+
25
26
  return content;
26
27
  } catch (error) {
27
28
  throw new Error(`无法从 ${file} 加载提示词 "${name}"。`, {
@@ -25,9 +25,8 @@
25
25
 
26
26
  使用内置文件系统工具(`ls`、`read_file`、`write_file`、`edit_file`、`glob`、`grep`)查看文件,不要猜测文件内容。给用户展示绝对虚拟路径(例如 `/workspace/report.md`)。
27
27
 
28
- ## 研究与数据
28
+ ## 数据
29
29
 
30
- - `web_search` 返回标题、URL 和摘要。引用你实际使用的 URL,绝不编造来源。
31
30
  - `query_database` 执行只读 SQL。先看表结构,并控制结果集大小。
32
31
 
33
32
  ## 审批策略
@@ -1,4 +1,4 @@
1
- import type { AgentConfig } from "../../config/agent.js";
1
+ import type { AgentConfig } from "../../config/index.js";
2
2
 
3
3
  import { loadPrompt, renderPrompt } from "./loader.js";
4
4
 
@@ -1,14 +1,18 @@
1
1
  import type { SubAgent } from "deepagents";
2
2
 
3
- import { queryDatabaseTool } from "../../tools/database/index.js";
3
+ import { createQueryDatabaseTool } from "../../tools/database/index.js";
4
4
  import { loadPrompt } from "../prompts/index.js";
5
5
 
6
- export const createAnalystSubagent = (): SubAgent => {
6
+ export interface AnalystSubagentOptions {
7
+ databaseUrl?: string;
8
+ }
9
+
10
+ export const createAnalystSubagent = ({ databaseUrl }: AnalystSubagentOptions = {}): SubAgent => {
7
11
  return {
8
12
  name: "analyst",
9
13
  description: "用只读 SQL 回答数据问题,校验数字,并把表格或摘要写入 /workspace/analysis/。",
10
14
  systemPrompt: loadPrompt("subagents/analyst"),
11
- tools: [queryDatabaseTool],
15
+ tools: databaseUrl ? [createQueryDatabaseTool({ connectionString: databaseUrl })] : [],
12
16
  skills: ["/skills/analysis/"],
13
17
  };
14
18
  };
@@ -1,10 +1,9 @@
1
- import { createAnalystSubagent } from "./analyst.js";
1
+ import { createAnalystSubagent, type AnalystSubagentOptions } from "./analyst.js";
2
2
  import { createCoderSubagent } from "./coder.js";
3
- import { createResearcherSubagent } from "./researcher.js";
4
3
 
5
- export { createAnalystSubagent, createCoderSubagent, createResearcherSubagent };
4
+ export { createAnalystSubagent, createCoderSubagent, type AnalystSubagentOptions };
6
5
 
7
6
  /** 默认专家团队,顺序即展示给主 Agent 的顺序。 */
8
- export const createDefaultSubagents = () => {
9
- return [createResearcherSubagent(), createCoderSubagent(), createAnalystSubagent()];
7
+ export const createDefaultSubagents = ({ databaseUrl }: AnalystSubagentOptions = {}) => {
8
+ return [createCoderSubagent(), createAnalystSubagent({ databaseUrl })];
10
9
  };
@@ -1,27 +1,26 @@
1
1
  import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
2
2
  import type { StructuredToolInterface } from "@langchain/core/tools";
3
3
  import type { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph";
4
- import type { CompositeBackend } from "deepagents";
4
+ import type { AnyBackendProtocol, BackendFactory } from "deepagents";
5
5
 
6
6
  import type { AppConfig } from "../config/index.js";
7
- import type { Logger } from "../infrastructure/logger/index.js";
8
- import type { CompiledAgent } from "../graph/compile.js";
7
+ import type { Logger } from "../storage/logger/index.js";
8
+ import type { AgentOptions, CompiledAgent } from "../graph/index.js";
9
9
  import {
10
+ createApprovalPolicy,
10
11
  createContextMiddleware,
11
12
  createLoggingMiddleware,
12
13
  createSecurityMiddleware,
13
14
  } from "../middleware/index.js";
14
- import { createApprovalPolicy } from "../middleware/approval.js";
15
- import type { AgentOptions } from "../graph/compile.js";
16
15
  import { createAgentFactory } from "./factory.js";
17
- import { buildSupervisorPrompt } from "./prompts/supervisor.js";
16
+ import { buildSupervisorPrompt } from "./prompts/index.js";
18
17
  import { createDefaultSubagents } from "./subagents/index.js";
19
18
  import { agentStateSchema } from "./state/index.js";
20
19
 
21
20
  export interface SupervisorDependencies {
22
21
  config: AppConfig;
23
22
  model: BaseChatModel;
24
- backend: CompositeBackend;
23
+ backend: AnyBackendProtocol | BackendFactory;
25
24
  checkpointer: BaseCheckpointSaver;
26
25
  store: BaseStore;
27
26
  logger: Logger;
@@ -41,7 +40,7 @@ export const createSupervisorAgent = ({
41
40
  logger,
42
41
  tools,
43
42
  }: SupervisorDependencies): CompiledAgent => {
44
- const subagents = createDefaultSubagents();
43
+ const subagents = createDefaultSubagents({ databaseUrl: config.database.url });
45
44
 
46
45
  // 依赖里用具体的工具类型,交给 Agent 时再收窄为它接受的联合类型。
47
46
  const agentTools = tools as AgentOptions["tools"];
@@ -52,9 +51,12 @@ export const createSupervisorAgent = ({
52
51
  createContextMiddleware(),
53
52
  ];
54
53
 
54
+ // 工厂允许返回 Promise,公开类型只声明了同步工厂,运行时由 deepagents 解析。
55
+ const agentBackend = backend as unknown as AgentOptions["backend"];
56
+
55
57
  const createAgent = createAgentFactory({
56
58
  model,
57
- backend,
59
+ backend: agentBackend,
58
60
  checkpointer,
59
61
  store,
60
62
  stateSchema: agentStateSchema,
@@ -1,11 +1,11 @@
1
1
  import express, { type Express } from "express";
2
2
 
3
3
  import type { AppConfig } from "../config/index.js";
4
- import type { Logger } from "../infrastructure/logger/index.js";
4
+ import type { Logger } from "../storage/logger/index.js";
5
5
  import type { McpToolRegistry } from "../tools/mcp/index.js";
6
- import type { AgentService } from "../services/agent.service.js";
7
- import type { MemoryService } from "../services/memory.service.js";
8
- import type { SessionService } from "../services/session.service.js";
6
+ import type { AgentService } from "../services/agent.js";
7
+ import type { MemoryService } from "../services/memory.js";
8
+ import type { SessionService } from "../services/session.js";
9
9
  import { createAuthMiddleware } from "./middleware/auth.js";
10
10
  import { createErrorHandler, notFoundHandler } from "./middleware/error.js";
11
11
  import { createAgentRouter } from "./routes/agent.js";
@@ -11,6 +11,7 @@ const safeEqual = (provided: string, expected: string): boolean => {
11
11
  const target = Buffer.from(expected);
12
12
 
13
13
  if (actual.length !== target.length) return false;
14
+
14
15
  return timingSafeEqual(actual, target);
15
16
  };
16
17
 
@@ -1,6 +1,6 @@
1
1
  import type { ErrorRequestHandler, RequestHandler } from "express";
2
2
 
3
- import type { Logger } from "../../infrastructure/logger/index.js";
3
+ import type { Logger } from "../../storage/logger/index.js";
4
4
  import { NotFoundError, toErrorResponse } from "../../utils/errors.js";
5
5
 
6
6
  export const notFoundHandler: RequestHandler = (req, _res, next) => {
@@ -1,12 +1,9 @@
1
1
  import { Router } from "express";
2
2
 
3
- import {
4
- invokeAgentSchema,
5
- resumeAgentSchema,
6
- type InvokeAgentInput,
7
- } from "../../schemas/agent.js";
8
- import type { AgentService } from "../../services/agent.service.js";
9
- import { ValidationError } from "../../utils/errors.js";
3
+ import { invokeAgentSchema, resumeAgentSchema } from "../../schemas/agent.js";
4
+ import type { AgentService } from "../../services/agent.js";
5
+ import { errorMessage } from "../../utils/helpers.js";
6
+ import { parseRequest } from "../../utils/validation.js";
10
7
 
11
8
  export interface AgentRouterDependencies {
12
9
  agent: AgentService;
@@ -15,49 +12,17 @@ export interface AgentRouterDependencies {
15
12
  export const createAgentRouter = ({ agent }: AgentRouterDependencies): Router => {
16
13
  const router = Router();
17
14
 
18
- router.post("/invoke", async (req, res, next) => {
19
- try {
20
- const parsed = invokeAgentSchema.safeParse(req.body);
21
- if (!parsed.success) {
22
- throw new ValidationError("请求体格式错误。", {
23
- issues: parsed.error.issues,
24
- });
25
- }
26
-
27
- const result = await agent.invoke(parsed.data);
28
- res.json(result);
29
- } catch (error) {
30
- next(error);
31
- }
15
+ // Express 5 会把 async handler 的拒绝交给错误中间件,这里不需要再包 try/catch。
16
+ router.post("/invoke", async (req, res) => {
17
+ res.json(await agent.invoke(parseRequest(invokeAgentSchema, req.body)));
32
18
  });
33
19
 
34
- router.post("/resume", async (req, res, next) => {
35
- try {
36
- const parsed = resumeAgentSchema.safeParse(req.body);
37
- if (!parsed.success) {
38
- throw new ValidationError("请求体格式错误。", {
39
- issues: parsed.error.issues,
40
- });
41
- }
42
-
43
- const result = await agent.resume(parsed.data);
44
- res.json(result);
45
- } catch (error) {
46
- next(error);
47
- }
20
+ router.post("/resume", async (req, res) => {
21
+ res.json(await agent.resume(parseRequest(resumeAgentSchema, req.body)));
48
22
  });
49
23
 
50
- router.post("/stream", async (req, res, next) => {
51
- const parsed = invokeAgentSchema.safeParse(req.body);
52
- if (!parsed.success) {
53
- next(
54
- new ValidationError("请求体格式错误。", {
55
- issues: parsed.error.issues,
56
- }),
57
- );
58
- return;
59
- }
60
-
24
+ router.post("/stream", async (req, res) => {
25
+ const input = parseRequest(invokeAgentSchema, req.body);
61
26
  const controller = new AbortController();
62
27
  req.on("close", () => controller.abort());
63
28
 
@@ -68,22 +33,12 @@ export const createAgentRouter = ({ agent }: AgentRouterDependencies): Router =>
68
33
  res.flushHeaders();
69
34
 
70
35
  try {
71
- for await (const event of agent.stream(parsed.data as InvokeAgentInput, {
72
- signal: controller.signal,
73
- })) {
36
+ for await (const event of agent.stream(input, { signal: controller.signal })) {
74
37
  res.write(`event: ${event.event}\ndata: ${JSON.stringify(event.data)}\n\n`);
75
38
  }
76
39
  res.write("event: done\ndata: {}\n\n");
77
40
  } catch (error) {
78
- if (!res.headersSent) {
79
- next(error);
80
- return;
81
- }
82
- res.write(
83
- `event: error\ndata: ${JSON.stringify({
84
- message: error instanceof Error ? error.message : String(error),
85
- })}\n\n`,
86
- );
41
+ res.write(`event: error\ndata: ${JSON.stringify({ message: errorMessage(error) })}\n\n`);
87
42
  } finally {
88
43
  res.end();
89
44
  }