create-deepagent-server 0.1.0 → 0.2.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 +82 -8
  2. package/package.json +1 -1
  3. package/src/args.js +6 -4
  4. package/src/cli.js +1 -1
  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 +6 -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
@@ -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
  }
@@ -2,8 +2,8 @@ import { Router } from "express";
2
2
 
3
3
  import type { AppConfig } from "../../config/index.js";
4
4
  import type { McpToolRegistry } from "../../tools/mcp/index.js";
5
- import { checkDatabase } from "../../infrastructure/database/client.js";
6
- import { checkRedis } from "../../infrastructure/redis/client.js";
5
+ import { checkDatabase } from "../../storage/database/client.js";
6
+ import { checkRedis } from "../../storage/redis/client.js";
7
7
 
8
8
  export interface HealthRouterDependencies {
9
9
  config: AppConfig;
@@ -25,7 +25,9 @@ export const createHealthRouter = ({ config, mcp }: HealthRouterDependencies): R
25
25
 
26
26
  router.get("/ready", async (_req, res) => {
27
27
  const [database, redis] = await Promise.all([
28
- config.database.url ? checkDatabase() : Promise.resolve({ ok: true, skipped: true }),
28
+ config.database.url
29
+ ? checkDatabase(config.database.url)
30
+ : Promise.resolve({ ok: true, skipped: true }),
29
31
  config.redis.url ? checkRedis() : Promise.resolve({ ok: true, skipped: true }),
30
32
  ]);
31
33
 
@@ -1,8 +1,8 @@
1
1
  import { Router } from "express";
2
2
 
3
- import { createSessionSchema, type CreateSessionInput } from "../../schemas/session.js";
4
- import type { SessionService } from "../../services/session.service.js";
5
- import { ValidationError } from "../../utils/errors.js";
3
+ import { createSessionSchema } from "../../schemas/session.js";
4
+ import type { SessionService } from "../../services/session.js";
5
+ import { parseRequest } from "../../utils/validation.js";
6
6
 
7
7
  export interface SessionRouterDependencies {
8
8
  sessions: SessionService;
@@ -12,65 +12,35 @@ const tenantFrom = (value: unknown): string => {
12
12
  return typeof value === "string" && value.length > 0 ? value : "default";
13
13
  };
14
14
 
15
+ const limitFrom = (value: unknown): number => {
16
+ const limit = Number(value ?? 20);
17
+ return Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20;
18
+ };
19
+
15
20
  export const createSessionRouter = ({ sessions }: SessionRouterDependencies): Router => {
16
21
  const router = Router();
17
22
 
18
- router.post("/", async (req, res, next) => {
19
- try {
20
- const parsed = createSessionSchema.safeParse(req.body ?? {});
21
- if (!parsed.success) {
22
- throw new ValidationError("请求体格式错误。", {
23
- issues: parsed.error.issues,
24
- });
25
- }
26
-
27
- const input: CreateSessionInput = parsed.data;
28
- const session = await sessions.create(input);
29
- res.status(201).json(session);
30
- } catch (error) {
31
- next(error);
32
- }
23
+ router.post("/", async (req, res) => {
24
+ const session = await sessions.create(parseRequest(createSessionSchema, req.body ?? {}));
25
+ res.status(201).json(session);
33
26
  });
34
27
 
35
- router.get("/", async (req, res, next) => {
36
- try {
37
- const tenantId = tenantFrom(req.query.tenantId);
38
- const limit = Number(req.query.limit ?? 20);
39
- const result = await sessions.list(
40
- tenantId,
41
- Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20,
42
- );
43
- res.json(result);
44
- } catch (error) {
45
- next(error);
46
- }
28
+ router.get("/", async (req, res) => {
29
+ const result = await sessions.list(tenantFrom(req.query.tenantId), limitFrom(req.query.limit));
30
+ res.json(result);
47
31
  });
48
32
 
49
- router.get("/:threadId", async (req, res, next) => {
50
- try {
51
- const session = await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId));
52
- res.json(session);
53
- } catch (error) {
54
- next(error);
55
- }
33
+ router.get("/:threadId", async (req, res) => {
34
+ res.json(await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId)));
56
35
  });
57
36
 
58
- router.get("/:threadId/messages", async (req, res, next) => {
59
- try {
60
- const messages = await sessions.history(req.params.threadId);
61
- res.json({ messages });
62
- } catch (error) {
63
- next(error);
64
- }
37
+ router.get("/:threadId/messages", async (req, res) => {
38
+ res.json({ messages: await sessions.history(req.params.threadId) });
65
39
  });
66
40
 
67
- router.delete("/:threadId", async (req, res, next) => {
68
- try {
69
- await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
70
- res.status(204).end();
71
- } catch (error) {
72
- next(error);
73
- }
41
+ router.delete("/:threadId", async (req, res) => {
42
+ await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
43
+ res.status(204).end();
74
44
  });
75
45
 
76
46
  return router;
@@ -2,22 +2,22 @@ import fs from "node:fs/promises";
2
2
 
3
3
  import type { Express } from "express";
4
4
 
5
- import { createSupervisorAgent } from "./agents/supervisor.js";
5
+ import { createSupervisorAgent } from "./agents/index.js";
6
6
  import { createApiApp } from "./api/app.js";
7
7
  import { createBackend } from "./backends/index.js";
8
- import { createChatModel, loadConfig, type AppConfig } from "./config/index.js";
9
- import { createCheckpointer } from "./graph/checkpointer.js";
10
- import { createStore } from "./graph/store.js";
11
- import { closeDatabase } from "./infrastructure/database/client.js";
12
- import { createLogger, type Logger } from "./infrastructure/logger/index.js";
13
- import { closeRedis } from "./infrastructure/redis/client.js";
8
+ import { loadConfig, type AppConfig } from "./config/index.js";
9
+ import { createCheckpointer, createStore } from "./graph/index.js";
10
+ import { closeDatabase } from "./storage/database/client.js";
11
+ import { createLogger, type Logger } from "./storage/logger/index.js";
12
+ import { closeRedis } from "./storage/redis/client.js";
14
13
  import { createMemoryManager } from "./memory/index.js";
15
- import { AgentService } from "./services/agent.service.js";
16
- import { MemoryService } from "./services/memory.service.js";
17
- import { SessionService } from "./services/session.service.js";
14
+ import { createChatModel } from "./model/index.js";
15
+ import { AgentService } from "./services/agent.js";
16
+ import { MemoryService } from "./services/memory.js";
17
+ import { SessionService } from "./services/session.js";
18
18
  import { loadSkills, validateSkills } from "./skills/index.js";
19
19
  import { createDefaultTools } from "./tools/index.js";
20
- import { createMcpToolRegistry } from "./tools/mcp/index.js";
20
+ import { createMcpToolRegistry } from "./tools/index.js";
21
21
 
22
22
  export interface Application {
23
23
  app: Express;
@@ -44,6 +44,7 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
44
44
  for (const warning of validateSkills(skills)) {
45
45
  logger.warn(warning);
46
46
  }
47
+
47
48
  logger.info({ skills: skills.map((skill) => skill.name) }, "技能加载完成");
48
49
 
49
50
  const store = await createStore(config);
@@ -53,6 +54,7 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
53
54
 
54
55
  const tools = createDefaultTools({
55
56
  workspaceRoot: config.paths.workspaces,
57
+ databaseUrl: config.database.url,
56
58
  additionalTools: mcp.tools,
57
59
  });
58
60
 
@@ -66,7 +68,12 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
66
68
  tools,
67
69
  });
68
70
 
69
- const sessions = new SessionService({ graph: agent, checkpointer, store });
71
+ const sessions = new SessionService({
72
+ graph: agent,
73
+ checkpointer,
74
+ store,
75
+ sandboxes: backend.sandboxes,
76
+ });
70
77
  const agentService = new AgentService({ agent, config, sessions });
71
78
  const memoryService = new MemoryService(createMemoryManager(store));
72
79