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
@@ -1,15 +1,20 @@
1
1
  import fs from "node:fs/promises";
2
2
  import nodePath from "node:path";
3
+
3
4
  import { tool } from "@langchain/core/tools";
4
5
  import { z } from "zod";
6
+
5
7
  const resolveInsideRoot = (rootDir, target) => {
6
8
  const root = nodePath.resolve(rootDir);
7
9
  const resolved = nodePath.resolve(root, target);
10
+
8
11
  if (resolved !== root && !resolved.startsWith(`${root}${nodePath.sep}`)) {
9
12
  throw new Error(`路径越出了工作区根目录:${target}`);
10
13
  }
14
+
11
15
  return resolved;
12
16
  };
17
+
13
18
  /**
14
19
  * 面向应用自有文件的额外工作区工具。Deep Agents 已内置对后端的
15
20
  * read_file/write_file/edit_file;这些工具限定在 `workspaces/` 内,
@@ -20,11 +25,13 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
20
25
  filePath: z.string().min(1).describe("相对于工作区根目录的路径。"),
21
26
  maxBytes: z.number().int().positive().default(maxReadBytes),
22
27
  });
28
+
23
29
  const readFile = tool(
24
30
  async ({ filePath, maxBytes }) => {
25
31
  const resolved = resolveInsideRoot(rootDir, filePath);
26
32
  const content = await fs.readFile(resolved, "utf8");
27
33
  if (content.length <= maxBytes) return content;
34
+
28
35
  return `${content.slice(0, maxBytes)}\n… 已在 ${maxBytes} 个字符处截断`;
29
36
  },
30
37
  {
@@ -33,20 +40,24 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
33
40
  schema: readSchema,
34
41
  },
35
42
  );
43
+
36
44
  const writeSchema = z.object({
37
45
  filePath: z.string().min(1),
38
46
  content: z.string(),
39
47
  append: z.boolean().default(false),
40
48
  });
49
+
41
50
  const writeFile = tool(
42
51
  async ({ filePath, content, append }) => {
43
52
  const resolved = resolveInsideRoot(rootDir, filePath);
44
53
  await fs.mkdir(nodePath.dirname(resolved), { recursive: true });
54
+
45
55
  if (append) {
46
56
  await fs.appendFile(resolved, content, "utf8");
47
57
  } else {
48
58
  await fs.writeFile(resolved, content, "utf8");
49
59
  }
60
+
50
61
  return `已写入 ${content.length} 个字符到 ${filePath}`;
51
62
  },
52
63
  {
@@ -55,10 +66,12 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
55
66
  schema: writeSchema,
56
67
  },
57
68
  );
69
+
58
70
  const listSchema = z.object({
59
71
  directory: z.string().default("."),
60
72
  recursive: z.boolean().default(false),
61
73
  });
74
+
62
75
  const listFiles = tool(
63
76
  async ({ directory, recursive }) => {
64
77
  const resolved = resolveInsideRoot(rootDir, directory);
@@ -66,6 +79,7 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
66
79
  recursive,
67
80
  withFileTypes: true,
68
81
  });
82
+
69
83
  const files = entries
70
84
  .map((entry) => ({
71
85
  name: entry.name,
@@ -74,6 +88,7 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
74
88
  }))
75
89
  .sort((a, b) => a.path.localeCompare(b.path))
76
90
  .slice(0, 500);
91
+
77
92
  return JSON.stringify({ root: directory, files }, null, 2);
78
93
  },
79
94
  {
@@ -82,5 +97,6 @@ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
82
97
  schema: listSchema,
83
98
  },
84
99
  );
100
+
85
101
  return [readFile, writeFile, listFiles];
86
102
  };
@@ -1,7 +1,7 @@
1
- import { queryDatabaseTool } from "./database/index.js";
1
+ import { createQueryDatabaseTool } from "./database/index.js";
2
2
  import { createWorkspaceTools } from "./filesystem/index.js";
3
- import { webSearchTool } from "./search/index.js";
4
- export { assertReadOnlyQuery, queryDatabaseTool } from "./database/index.js";
3
+
4
+ export { assertReadOnlyQuery, createQueryDatabaseTool } from "./database/index.js";
5
5
  export { createWorkspaceTools } from "./filesystem/index.js";
6
6
  export {
7
7
  createMcpAdapter,
@@ -11,19 +11,14 @@ export {
11
11
  McpToolRegistry,
12
12
  mcpServerSchema,
13
13
  } from "./mcp/index.js";
14
- export { createWebSearchTool, webSearchTool } from "./search/index.js";
14
+
15
15
  /**
16
16
  * 主 Agent 和子 Agent 可用的工具,位于 Deep Agents 内置工具
17
17
  * (write_todos、read_file、write_file、task 等)之上。
18
18
  */
19
- export const createDefaultTools = ({
20
- workspaceRoot,
21
- enableDatabase = Boolean(process.env.DATABASE_URL),
22
- additionalTools = [],
23
- }) => {
19
+ export const createDefaultTools = ({ workspaceRoot, databaseUrl, additionalTools = [] }) => {
24
20
  return [
25
- webSearchTool,
26
- ...(enableDatabase ? [queryDatabaseTool] : []),
21
+ ...(databaseUrl ? [createQueryDatabaseTool({ connectionString: databaseUrl })] : []),
27
22
  ...createWorkspaceTools({ rootDir: workspaceRoot }),
28
23
  ...additionalTools,
29
24
  ];
@@ -1,6 +1,8 @@
1
1
  import { MCPAdapter } from "@langchain/mcp-adapters";
2
+
2
3
  const toAdapterServers = (connections) => {
3
4
  const servers = {};
5
+
4
6
  for (const [name, connection] of Object.entries(connections)) {
5
7
  if (connection.transport === "stdio") {
6
8
  servers[name] = {
@@ -15,8 +17,10 @@ const toAdapterServers = (connections) => {
15
17
  servers[name] = { transport: "sse", url: connection.url };
16
18
  }
17
19
  }
20
+
18
21
  return servers;
19
22
  };
23
+
20
24
  /** 创建多服务器 MCP 适配器;连接按需建立。 */
21
25
  export const createMcpAdapter = (connections) => {
22
26
  return new MCPAdapter({
@@ -24,12 +28,15 @@ export const createMcpAdapter = (connections) => {
24
28
  onConnectionError: "ignore",
25
29
  });
26
30
  };
31
+
27
32
  /** 加载已配置的 MCP 服务器暴露的全部工具。 */
28
33
  export const loadMcpTools = async (connections) => {
29
34
  if (Object.keys(connections).length === 0) {
30
35
  return { adapter: null, tools: [] };
31
36
  }
37
+
32
38
  const adapter = createMcpAdapter(connections);
33
39
  const tools = await adapter.listTools();
40
+
34
41
  return { adapter, tools };
35
42
  };
@@ -1,26 +1,33 @@
1
1
  import { z } from "zod";
2
+
2
3
  import { ConfigurationError } from "../../utils/errors.js";
4
+ import { errorMessage } from "../../utils/helpers.js";
5
+
3
6
  const stdioConnectionSchema = z.object({
4
7
  transport: z.literal("stdio"),
5
8
  command: z.string().min(1),
6
9
  args: z.array(z.string()).default([]),
7
10
  env: z.record(z.string(), z.string()).default({}),
8
11
  });
12
+
9
13
  const httpConnectionSchema = z.object({
10
14
  transport: z.literal("http"),
11
15
  url: z.string().min(1),
12
16
  headers: z.record(z.string(), z.string()).default({}),
13
17
  });
18
+
14
19
  const sseConnectionSchema = z.object({
15
20
  transport: z.literal("sse"),
16
21
  url: z.string().min(1),
17
22
  headers: z.record(z.string(), z.string()).default({}),
18
23
  });
24
+
19
25
  export const mcpServerSchema = z.discriminatedUnion("transport", [
20
26
  stdioConnectionSchema,
21
27
  httpConnectionSchema,
22
28
  sseConnectionSchema,
23
29
  ]);
30
+
24
31
  /**
25
32
  * 从 `MCP_SERVERS`(JSON)或已解析的对象中读取 MCP 连接配置。
26
33
  *
@@ -29,17 +36,18 @@ export const mcpServerSchema = z.discriminatedUnion("transport", [
29
36
  */
30
37
  export const loadMcpConnections = (raw = process.env.MCP_SERVERS) => {
31
38
  if (!raw || raw.trim() === "") return {};
39
+
32
40
  let parsed;
33
41
  try {
34
42
  parsed = JSON.parse(raw);
35
43
  } catch (error) {
36
- throw new ConfigurationError(
37
- `MCP_SERVERS 必须是合法的 JSON:${error instanceof Error ? error.message : String(error)}`,
38
- );
44
+ throw new ConfigurationError(`MCP_SERVERS 必须是合法的 JSON:${errorMessage(error)}`);
39
45
  }
46
+
40
47
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
41
48
  throw new ConfigurationError("MCP_SERVERS 必须是以服务器名称为键的对象。");
42
49
  }
50
+
43
51
  const entries = Object.entries(parsed).map(([name, value]) => {
44
52
  const result = mcpServerSchema.safeParse(value);
45
53
  if (!result.success) {
@@ -48,7 +56,9 @@ export const loadMcpConnections = (raw = process.env.MCP_SERVERS) => {
48
56
  .join("; ");
49
57
  throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
50
58
  }
59
+
51
60
  return [name, result.data];
52
61
  });
62
+
53
63
  return Object.fromEntries(entries);
54
64
  };
@@ -1,7 +1,9 @@
1
1
  import { McpToolRegistry } from "./registry.js";
2
+
2
3
  export { createMcpAdapter, loadMcpTools } from "./client.js";
3
4
  export { loadMcpConnections, mcpServerSchema } from "./connections.js";
4
5
  export { McpToolRegistry };
6
+
5
7
  /** 启动时加载一次 MCP 工具;未配置时返回空注册表。 */
6
8
  export const createMcpToolRegistry = async () => {
7
9
  return McpToolRegistry.create();
@@ -1,32 +1,36 @@
1
1
  import { loadMcpTools } from "./client.js";
2
2
  import { loadMcpConnections } from "./connections.js";
3
+
3
4
  /**
4
5
  * 持有整个进程生命周期的 MCP 适配器。启动时加载一次工具并交给主 Agent;
5
6
  * 关闭时断开连接。
6
7
  */
7
8
  export class McpToolRegistry {
8
- #adapter;
9
- #tools;
10
- #servers;
9
+ tools;
10
+ adapter;
11
+ servers;
12
+
11
13
  constructor(adapter, tools, servers) {
12
- this.#adapter = adapter;
13
- this.#tools = tools;
14
- this.#servers = servers;
14
+ this.adapter = adapter;
15
+ this.tools = tools;
16
+ this.servers = servers;
15
17
  }
18
+
16
19
  static async create(connections = loadMcpConnections()) {
17
20
  if (Object.keys(connections).length === 0) {
18
21
  return new McpToolRegistry(null, [], []);
19
22
  }
23
+
20
24
  const { adapter, tools } = await loadMcpTools(connections);
25
+
21
26
  return new McpToolRegistry(adapter, tools, Object.keys(connections));
22
27
  }
23
- get tools() {
24
- return this.#tools;
25
- }
28
+
26
29
  get serverNames() {
27
- return [...this.#servers];
30
+ return [...this.servers];
28
31
  }
32
+
29
33
  async close() {
30
- await this.#adapter?.close();
34
+ await this.adapter?.close();
31
35
  }
32
36
  }
@@ -6,6 +6,7 @@ export class AppError extends Error {
6
6
  status;
7
7
  code;
8
8
  details;
9
+
9
10
  constructor(message, options = {}) {
10
11
  super(message, { cause: options.cause });
11
12
  this.name = new.target.name;
@@ -13,6 +14,7 @@ export class AppError extends Error {
13
14
  this.code = options.code ?? "INTERNAL_ERROR";
14
15
  this.details = options.details;
15
16
  }
17
+
16
18
  toJSON() {
17
19
  return {
18
20
  error: {
@@ -23,35 +25,42 @@ export class AppError extends Error {
23
25
  };
24
26
  }
25
27
  }
28
+
26
29
  export class ConfigurationError extends AppError {
27
30
  constructor(message, details) {
28
31
  super(message, { status: 500, code: "CONFIGURATION_ERROR", details });
29
32
  }
30
33
  }
34
+
31
35
  export class ValidationError extends AppError {
32
36
  constructor(message, details) {
33
37
  super(message, { status: 400, code: "VALIDATION_ERROR", details });
34
38
  }
35
39
  }
40
+
36
41
  export class UnauthorizedError extends AppError {
37
42
  constructor(message = "缺少凭证或凭证无效。") {
38
43
  super(message, { status: 401, code: "UNAUTHORIZED" });
39
44
  }
40
45
  }
46
+
41
47
  export class NotFoundError extends AppError {
42
48
  constructor(message = "资源不存在。") {
43
49
  super(message, { status: 404, code: "NOT_FOUND" });
44
50
  }
45
51
  }
52
+
46
53
  export class ConflictError extends AppError {
47
54
  constructor(message = "资源冲突。") {
48
55
  super(message, { status: 409, code: "CONFLICT" });
49
56
  }
50
57
  }
58
+
51
59
  export const toErrorResponse = (error) => {
52
60
  if (error instanceof AppError) {
53
61
  return { status: error.status, body: error.toJSON() };
54
62
  }
63
+
55
64
  return {
56
65
  status: 500,
57
66
  body: {
@@ -1,13 +1,21 @@
1
1
  export const isRecord = (value) => {
2
2
  return typeof value === "object" && value !== null && !Array.isArray(value);
3
3
  };
4
+
5
+ /** 把任意抛出值转换为可读的错误信息,避免每个调用点重复三目表达式。 */
6
+ export const errorMessage = (error) => {
7
+ return error instanceof Error ? error.message : String(error);
8
+ };
9
+
4
10
  export const sleep = (milliseconds) => {
5
11
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
6
12
  };
13
+
7
14
  export const truncate = (value, maxLength = 200) => {
8
15
  if (value.length <= maxLength) return value;
9
16
  return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
10
17
  };
18
+
11
19
  export const parseJson = (value, fallback) => {
12
20
  try {
13
21
  return JSON.parse(value);
@@ -15,28 +23,35 @@ export const parseJson = (value, fallback) => {
15
23
  return fallback;
16
24
  }
17
25
  };
26
+
18
27
  /**
19
28
  * 规范化 LangChain 的消息内容:可能是字符串,也可能是内容块数组
20
29
  * (`{ type: "text", text: "..." }`)。
21
30
  */
22
31
  export const extractText = (content) => {
23
32
  if (typeof content === "string") return content;
33
+
24
34
  if (Array.isArray(content)) {
25
35
  return content.map((block) => extractText(block)).join("");
26
36
  }
37
+
27
38
  if (isRecord(content) && typeof content.text === "string") {
28
39
  return content.text;
29
40
  }
41
+
30
42
  return "";
31
43
  };
44
+
32
45
  export const lastMessageText = (messages) => {
33
46
  const last = messages.at(-1);
34
47
  if (!isRecord(last)) return "";
35
48
  return extractText(last.content);
36
49
  };
50
+
37
51
  export const toIsoString = (value = new Date()) => {
38
52
  return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
39
53
  };
54
+
40
55
  export const unique = (values) => {
41
56
  return [...new Set(values)];
42
57
  };
@@ -0,0 +1,15 @@
1
+ import { ValidationError } from "./errors.js";
2
+
3
+ /**
4
+ * 解析请求体:失败时抛出带 issues 的 ValidationError,
5
+ * 由 Express 5 的错误中间件统一响应,路由里不再需要 try/catch。
6
+ */
7
+ export const parseRequest = (schema, value) => {
8
+ const result = schema.safeParse(value);
9
+
10
+ if (!result.success) {
11
+ throw new ValidationError("请求体格式错误。", { issues: result.error.issues });
12
+ }
13
+
14
+ return result.data;
15
+ };
@@ -1,11 +1,15 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
+
3
4
  import { loadPrompt, renderPrompt } from "../../src/agents/prompts/index.js";
5
+
4
6
  test("从磁盘加载 Markdown 提示词", () => {
5
- const prompt = loadPrompt("subagents/researcher");
6
- assert.match(prompt, /researcher/);
7
- assert.match(prompt, /研究/);
7
+ const prompt = loadPrompt("subagents/analyst");
8
+
9
+ assert.match(prompt, /analyst/);
10
+ assert.match(prompt, /SQL/);
8
11
  });
12
+
9
13
  test("渲染 {{variable}} 占位符", () => {
10
14
  assert.equal(
11
15
  renderPrompt("你好 {{name}},欢迎来到{{place}}。", {
@@ -15,9 +19,11 @@ test("渲染 {{variable}} 占位符", () => {
15
19
  "你好 Ada,欢迎来到工作区。",
16
20
  );
17
21
  });
22
+
18
23
  test("占位符缺少值时抛错", () => {
19
24
  assert.throws(() => renderPrompt("Hello {{name}}", {}), /缺少提示词变量 "name"/);
20
25
  });
26
+
21
27
  test("拒绝可能逃逸提示词目录的名称", () => {
22
28
  assert.throws(() => loadPrompt("../secrets"), /非法的提示词名称/);
23
29
  assert.throws(() => loadPrompt("subagents/../../secrets"), /非法的提示词名称/);
@@ -1,33 +1,41 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { buildSupervisorPrompt } from "../../src/agents/prompts/supervisor.js";
3
+
4
+ import { buildSupervisorPrompt } from "../../src/agents/prompts/index.js";
4
5
  import { createDefaultSubagents } from "../../src/agents/subagents/index.js";
5
6
  import { agentStateSchema } from "../../src/agents/state/index.js";
7
+
6
8
  test("主 Agent 提示词包含团队与审批策略", () => {
7
9
  const prompt = buildSupervisorPrompt({
8
10
  name: "test-supervisor",
9
- subagents: [{ name: "researcher", description: "负责搜索网络。" }],
11
+ subagents: [{ name: "analyst", description: "负责只读 SQL 分析。" }],
10
12
  approvalMode: "sensitive",
11
13
  });
14
+
12
15
  assert.match(prompt, /test-supervisor/);
13
- assert.match(prompt, /researcher/);
16
+ assert.match(prompt, /analyst/);
14
17
  assert.match(prompt, /write_todos/);
15
18
  assert.match(prompt, /人工审批/);
16
19
  assert.doesNotMatch(prompt, /\{\{/);
17
20
  });
18
- test("默认子 Agent 为 researcher、coder、analyst", () => {
21
+
22
+ test("默认子 Agent 为 coder、analyst", () => {
19
23
  const subagents = createDefaultSubagents();
24
+
20
25
  assert.deepEqual(
21
26
  subagents.map((subagent) => subagent.name),
22
- ["researcher", "coder", "analyst"],
27
+ ["coder", "analyst"],
23
28
  );
29
+
24
30
  for (const subagent of subagents) {
25
31
  assert.ok(subagent.description.length > 20);
26
32
  assert.ok(subagent.systemPrompt);
27
33
  }
28
34
  });
35
+
29
36
  test("自定义状态默认使用默认租户", () => {
30
37
  const state = agentStateSchema.parse({});
38
+
31
39
  assert.equal(state.tenantId, "default");
32
40
  assert.equal(state.objective, "");
33
41
  assert.equal(state.userId, undefined);
@@ -0,0 +1,40 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { resolveDatabaseUrl } from "../../src/config/database.js";
5
+ import { loadEnv } from "../../src/config/env.js";
6
+
7
+ const envFor = (source) => {
8
+ return loadEnv({ NODE_ENV: "test", ...source }, { requireModelCredentials: false });
9
+ };
10
+
11
+ test("内存模式不生成数据库连接串", () => {
12
+ assert.equal(resolveDatabaseUrl(envFor({ POSTGRES_HOST: "db.internal" })), undefined);
13
+ });
14
+
15
+ test("postgres 模式用 POSTGRES_* 分项拼装连接串", () => {
16
+ const url = resolveDatabaseUrl(
17
+ envFor({
18
+ CHECKPOINTER: "postgres",
19
+ POSTGRES_HOST: "db.internal",
20
+ POSTGRES_PORT: "6543",
21
+ POSTGRES_USERNAME: "agent user",
22
+ POSTGRES_PASSWORD: "p@ss:word",
23
+ POSTGRES_DATABASE: "agent_db",
24
+ }),
25
+ );
26
+
27
+ assert.equal(url, "postgresql://agent%20user:p%40ss%3Aword@db.internal:6543/agent_db");
28
+ });
29
+
30
+ test("DATABASE_URL 优先于分项配置", () => {
31
+ const url = resolveDatabaseUrl(
32
+ envFor({
33
+ DATABASE_URL: "postgresql://custom:secret@example.com:5432/app",
34
+ CHECKPOINTER: "postgres",
35
+ POSTGRES_HOST: "ignored.internal",
36
+ }),
37
+ );
38
+
39
+ assert.equal(url, "postgresql://custom:secret@example.com:5432/app");
40
+ });
@@ -1,14 +1,16 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { once } from "node:events";
3
3
  import test from "node:test";
4
+
4
5
  import { createApiApp } from "../../src/api/app.js";
5
- import { loadConfig } from "../../src/config/index.js";
6
- import { loadEnv } from "../../src/config/env.js";
7
- import { createLogger } from "../../src/infrastructure/logger/index.js";
6
+ import { loadConfig, loadEnv } from "../../src/config/index.js";
7
+ import { createLogger } from "../../src/storage/logger/index.js";
8
+
8
9
  const config = loadConfig({
9
10
  env: loadEnv({ NODE_ENV: "test", LOG_LEVEL: "silent" }, { requireModelCredentials: false }),
10
11
  });
11
12
  const logger = createLogger(config);
13
+
12
14
  const fakeAgent = {
13
15
  invoke: async (input) => ({
14
16
  threadId: "thread-1",
@@ -24,14 +26,17 @@ const fakeAgent = {
24
26
  yield { event: "values", data: { messages: [] } };
25
27
  },
26
28
  };
29
+
27
30
  const services = {
28
31
  agent: fakeAgent,
29
32
  sessions: {},
30
33
  memory: {},
31
34
  };
35
+
32
36
  const withServer = async (run) => {
33
37
  const app = createApiApp({ config, logger, services });
34
38
  const server = app.listen(0);
39
+
35
40
  try {
36
41
  await once(server, "listening");
37
42
  const { port } = server.address();
@@ -40,15 +45,18 @@ const withServer = async (run) => {
40
45
  await new Promise((resolve) => server.close(() => resolve()));
41
46
  }
42
47
  };
48
+
43
49
  test("GET /health 返回服务与模型信息", async () => {
44
50
  await withServer(async (baseUrl) => {
45
51
  const response = await fetch(`${baseUrl}/health`);
46
52
  assert.equal(response.status, 200);
53
+
47
54
  const body = await response.json();
48
55
  assert.equal(body.status, "ok");
49
56
  assert.equal(body.agent, config.agent.name);
50
57
  });
51
58
  });
59
+
52
60
  test("POST /api/agents/invoke 校验请求并转交 Agent 服务", async () => {
53
61
  await withServer(async (baseUrl) => {
54
62
  const response = await fetch(`${baseUrl}/api/agents/invoke`, {
@@ -56,12 +64,14 @@ test("POST /api/agents/invoke 校验请求并转交 Agent 服务", async () => {
56
64
  headers: { "content-type": "application/json" },
57
65
  body: JSON.stringify({ message: "hello" }),
58
66
  });
67
+
59
68
  assert.equal(response.status, 200);
60
69
  const body = await response.json();
61
70
  assert.equal(body.text, "echo: hello");
62
71
  assert.equal(body.threadId, "thread-1");
63
72
  });
64
73
  });
74
+
65
75
  test("POST /api/agents/resume 转发审批决定", async () => {
66
76
  await withServer(async (baseUrl) => {
67
77
  const response = await fetch(`${baseUrl}/api/agents/resume`, {
@@ -72,11 +82,13 @@ test("POST /api/agents/resume 转发审批决定", async () => {
72
82
  decisions: [{ type: "approve" }],
73
83
  }),
74
84
  });
85
+
75
86
  assert.equal(response.status, 200);
76
87
  const body = await response.json();
77
88
  assert.equal(body.text, "resumed: 1");
78
89
  });
79
90
  });
91
+
80
92
  test("POST /api/agents/invoke 拒绝空消息", async () => {
81
93
  await withServer(async (baseUrl) => {
82
94
  const response = await fetch(`${baseUrl}/api/agents/invoke`, {
@@ -84,15 +96,18 @@ test("POST /api/agents/invoke 拒绝空消息", async () => {
84
96
  headers: { "content-type": "application/json" },
85
97
  body: JSON.stringify({ message: "" }),
86
98
  });
99
+
87
100
  assert.equal(response.status, 400);
88
101
  const body = await response.json();
89
102
  assert.equal(body.error.code, "VALIDATION_ERROR");
90
103
  });
91
104
  });
105
+
92
106
  test("未知路由返回 JSON 404", async () => {
93
107
  await withServer(async (baseUrl) => {
94
108
  const response = await fetch(`${baseUrl}/does-not-exist`);
95
109
  assert.equal(response.status, 404);
110
+
96
111
  const body = await response.json();
97
112
  assert.equal(body.error.code, "NOT_FOUND");
98
113
  });
@@ -1,6 +1,8 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
- import { findSecurityViolation } from "../../src/middleware/security.js";
3
+
4
+ import { findSecurityViolation } from "../../src/middleware/index.js";
5
+
4
6
  test("拦截破坏性 shell 命令", () => {
5
7
  for (const command of [
6
8
  "rm -rf /",
@@ -12,6 +14,7 @@ test("拦截破坏性 shell 命令", () => {
12
14
  assert.ok(findSecurityViolation(command), `预期应判定为危险:${command}`);
13
15
  }
14
16
  });
17
+
15
18
  test("放行正常的工具参数", () => {
16
19
  for (const value of [
17
20
  '{"query":"deep agents documentation"}',