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,4 +1,5 @@
1
1
  import type { Logger } from "../logger/index.js";
2
+ import { errorMessage } from "../../utils/helpers.js";
2
3
 
3
4
  export interface ShutdownHook {
4
5
  name: string;
@@ -38,22 +39,18 @@ export const createShutdownManager = ({
38
39
  const hooks: ShutdownHook[] = [];
39
40
  let pending: Promise<void> | undefined;
40
41
 
42
+ const closeHook = (hook: ShutdownHook): Promise<void> => {
43
+ return withTimeout(Promise.resolve(hook.close()), timeoutMs).then(
44
+ () => logger.info({ hook: hook.name }, "已关闭"),
45
+ (error: unknown) =>
46
+ logger.warn({ hook: hook.name, error: errorMessage(error) }, "关闭资源失败"),
47
+ );
48
+ };
49
+
41
50
  const run = async (reason: string): Promise<void> => {
42
51
  logger.info({ reason, hooks: hooks.map((hook) => hook.name) }, "开始关闭");
43
52
 
44
- await Promise.allSettled(
45
- hooks.map(async (hook) => {
46
- try {
47
- await withTimeout(Promise.resolve(hook.close()), timeoutMs);
48
- logger.info({ hook: hook.name }, "已关闭");
49
- } catch (error) {
50
- logger.warn(
51
- { hook: hook.name, error: error instanceof Error ? error.message : error },
52
- "关闭资源失败",
53
- );
54
- }
55
- }),
56
- );
53
+ await Promise.all(hooks.map(closeHook));
57
54
 
58
55
  logger.info("关闭完成");
59
56
  };
@@ -1 +1,5 @@
1
- export { assertReadOnlyQuery, queryDatabaseTool } from "./query.js";
1
+ export {
2
+ assertReadOnlyQuery,
3
+ createQueryDatabaseTool,
4
+ type QueryDatabaseToolOptions,
5
+ } from "./query.js";
@@ -1,7 +1,7 @@
1
1
  import { tool } from "@langchain/core/tools";
2
2
  import { z } from "zod";
3
3
 
4
- import { getPool } from "../../infrastructure/database/client.js";
4
+ import { getPool } from "../../storage/database/client.js";
5
5
 
6
6
  const READ_ONLY_START = /^\s*(?:select|with)\b/i;
7
7
  const FORBIDDEN_KEYWORDS =
@@ -34,38 +34,46 @@ const querySchema = z.object({
34
34
  limit: z.number().int().min(1).max(500).default(100),
35
35
  });
36
36
 
37
+ export interface QueryDatabaseToolOptions {
38
+ /** 未提供时回退到 DATABASE_URL 环境变量。 */
39
+ connectionString?: string;
40
+ }
41
+
37
42
  /** 只读、参数化的 PostgreSQL 查询工具。 */
38
- export const queryDatabaseTool = tool(
39
- async ({ sql, params, limit }: z.infer<typeof querySchema>) => {
40
- assertReadOnlyQuery(sql);
43
+ export const createQueryDatabaseTool = ({ connectionString }: QueryDatabaseToolOptions = {}) => {
44
+ return tool(
45
+ async ({ sql, params, limit }: z.infer<typeof querySchema>) => {
46
+ assertReadOnlyQuery(sql);
47
+
48
+ const client = await getPool(connectionString).connect();
41
49
 
42
- const client = await getPool().connect();
50
+ try {
51
+ await client.query("BEGIN TRANSACTION READ ONLY");
52
+ await client.query("SET LOCAL statement_timeout = '10s'");
43
53
 
44
- try {
45
- await client.query("BEGIN TRANSACTION READ ONLY");
46
- await client.query("SET LOCAL statement_timeout = '10s'");
47
- const result = await client.query(sql, params);
48
- await client.query("COMMIT");
54
+ const result = await client.query(sql, params);
55
+ await client.query("COMMIT");
49
56
 
50
- return JSON.stringify(
51
- {
52
- rowCount: result.rowCount,
53
- truncated: result.rows.length > limit,
54
- rows: result.rows.slice(0, limit),
55
- },
56
- null,
57
- 2,
58
- );
59
- } catch (error) {
60
- await client.query("ROLLBACK").catch(() => undefined);
61
- throw error;
62
- } finally {
63
- client.release();
64
- }
65
- },
66
- {
67
- name: "query_database",
68
- description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
69
- schema: querySchema,
70
- },
71
- );
57
+ return JSON.stringify(
58
+ {
59
+ rowCount: result.rowCount,
60
+ truncated: result.rows.length > limit,
61
+ rows: result.rows.slice(0, limit),
62
+ },
63
+ null,
64
+ 2,
65
+ );
66
+ } catch (error) {
67
+ await client.query("ROLLBACK").catch(() => undefined);
68
+ throw error;
69
+ } finally {
70
+ client.release();
71
+ }
72
+ },
73
+ {
74
+ name: "query_database",
75
+ description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
76
+ schema: querySchema,
77
+ },
78
+ );
79
+ };
@@ -59,11 +59,13 @@ export const createWorkspaceTools = ({
59
59
  async ({ filePath, content, append }: z.infer<typeof writeSchema>) => {
60
60
  const resolved = resolveInsideRoot(rootDir, filePath);
61
61
  await fs.mkdir(nodePath.dirname(resolved), { recursive: true });
62
+
62
63
  if (append) {
63
64
  await fs.appendFile(resolved, content, "utf8");
64
65
  } else {
65
66
  await fs.writeFile(resolved, content, "utf8");
66
67
  }
68
+
67
69
  return `已写入 ${content.length} 个字符到 ${filePath}`;
68
70
  },
69
71
  {
@@ -1,10 +1,13 @@
1
1
  import type { StructuredToolInterface } from "@langchain/core/tools";
2
2
 
3
- import { queryDatabaseTool } from "./database/index.js";
3
+ import { createQueryDatabaseTool } from "./database/index.js";
4
4
  import { createWorkspaceTools } from "./filesystem/index.js";
5
- import { webSearchTool } from "./search/index.js";
6
5
 
7
- export { assertReadOnlyQuery, queryDatabaseTool } from "./database/index.js";
6
+ export {
7
+ assertReadOnlyQuery,
8
+ createQueryDatabaseTool,
9
+ type QueryDatabaseToolOptions,
10
+ } from "./database/index.js";
8
11
  export { createWorkspaceTools } from "./filesystem/index.js";
9
12
  export {
10
13
  createMcpAdapter,
@@ -15,11 +18,11 @@ export {
15
18
  mcpServerSchema,
16
19
  type McpServerConnection,
17
20
  } from "./mcp/index.js";
18
- export { createWebSearchTool, webSearchTool } from "./search/index.js";
19
21
 
20
22
  export interface DefaultToolsOptions {
21
23
  workspaceRoot: string;
22
- enableDatabase?: boolean;
24
+ /** 配置后启用只读 SQL 工具;未配置时不注册。 */
25
+ databaseUrl?: string;
23
26
  additionalTools?: StructuredToolInterface[];
24
27
  }
25
28
 
@@ -29,12 +32,11 @@ export interface DefaultToolsOptions {
29
32
  */
30
33
  export const createDefaultTools = ({
31
34
  workspaceRoot,
32
- enableDatabase = Boolean(process.env.DATABASE_URL),
35
+ databaseUrl,
33
36
  additionalTools = [],
34
37
  }: DefaultToolsOptions): StructuredToolInterface[] => {
35
38
  return [
36
- webSearchTool,
37
- ...(enableDatabase ? [queryDatabaseTool] : []),
39
+ ...(databaseUrl ? [createQueryDatabaseTool({ connectionString: databaseUrl })] : []),
38
40
  ...createWorkspaceTools({ rootDir: workspaceRoot }),
39
41
  ...additionalTools,
40
42
  ];
@@ -49,5 +49,6 @@ export const loadMcpTools = async (
49
49
 
50
50
  const adapter = createMcpAdapter(connections);
51
51
  const tools = await adapter.listTools();
52
+
52
53
  return { adapter, tools };
53
54
  };
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
 
3
3
  import { ConfigurationError } from "../../utils/errors.js";
4
+ import { errorMessage } from "../../utils/helpers.js";
4
5
 
5
6
  const stdioConnectionSchema = z.object({
6
7
  transport: z.literal("stdio"),
@@ -44,9 +45,7 @@ export const loadMcpConnections = (
44
45
  try {
45
46
  parsed = JSON.parse(raw);
46
47
  } catch (error) {
47
- throw new ConfigurationError(
48
- `MCP_SERVERS 必须是合法的 JSON:${error instanceof Error ? error.message : String(error)}`,
49
- );
48
+ throw new ConfigurationError(`MCP_SERVERS 必须是合法的 JSON:${errorMessage(error)}`);
50
49
  }
51
50
 
52
51
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
@@ -61,6 +60,7 @@ export const loadMcpConnections = (
61
60
  .join("; ");
62
61
  throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
63
62
  }
63
+
64
64
  return [name, result.data];
65
65
  });
66
66
 
@@ -9,18 +9,18 @@ import { loadMcpConnections, type McpServerConnection } from "./connections.js";
9
9
  * 关闭时断开连接。
10
10
  */
11
11
  export class McpToolRegistry {
12
- readonly #adapter: MCPAdapter | null;
13
- readonly #tools: DynamicStructuredTool[];
14
- readonly #servers: string[];
12
+ readonly tools: DynamicStructuredTool[];
13
+ private readonly adapter: MCPAdapter | null;
14
+ private readonly servers: string[];
15
15
 
16
16
  private constructor(
17
17
  adapter: MCPAdapter | null,
18
18
  tools: DynamicStructuredTool[],
19
19
  servers: string[],
20
20
  ) {
21
- this.#adapter = adapter;
22
- this.#tools = tools;
23
- this.#servers = servers;
21
+ this.adapter = adapter;
22
+ this.tools = tools;
23
+ this.servers = servers;
24
24
  }
25
25
 
26
26
  static async create(
@@ -31,18 +31,15 @@ export class McpToolRegistry {
31
31
  }
32
32
 
33
33
  const { adapter, tools } = await loadMcpTools(connections);
34
- return new McpToolRegistry(adapter, tools, Object.keys(connections));
35
- }
36
34
 
37
- get tools(): DynamicStructuredTool[] {
38
- return this.#tools;
35
+ return new McpToolRegistry(adapter, tools, Object.keys(connections));
39
36
  }
40
37
 
41
38
  get serverNames(): string[] {
42
- return [...this.#servers];
39
+ return [...this.servers];
43
40
  }
44
41
 
45
42
  async close(): Promise<void> {
46
- await this.#adapter?.close();
43
+ await this.adapter?.close();
47
44
  }
48
45
  }
@@ -2,6 +2,11 @@ export const isRecord = (value: unknown): value is Record<string, unknown> => {
2
2
  return typeof value === "object" && value !== null && !Array.isArray(value);
3
3
  };
4
4
 
5
+ /** 把任意抛出值转换为可读的错误信息,避免每个调用点重复三目表达式。 */
6
+ export const errorMessage = (error: unknown): string => {
7
+ return error instanceof Error ? error.message : String(error);
8
+ };
9
+
5
10
  export const sleep = (milliseconds: number): Promise<void> => {
6
11
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
7
12
  };
@@ -0,0 +1,17 @@
1
+ import type { ZodType } from "zod";
2
+
3
+ import { ValidationError } from "./errors.js";
4
+
5
+ /**
6
+ * 解析请求体:失败时抛出带 issues 的 ValidationError,
7
+ * 由 Express 5 的错误中间件统一响应,路由里不再需要 try/catch。
8
+ */
9
+ export const parseRequest = <T>(schema: ZodType<T>, value: unknown): T => {
10
+ const result = schema.safeParse(value);
11
+
12
+ if (!result.success) {
13
+ throw new ValidationError("请求体格式错误。", { issues: result.error.issues });
14
+ }
15
+
16
+ return result.data;
17
+ };
@@ -4,10 +4,10 @@ import test from "node:test";
4
4
  import { loadPrompt, renderPrompt } from "../../src/agents/prompts/index.js";
5
5
 
6
6
  test("从磁盘加载 Markdown 提示词", () => {
7
- const prompt = loadPrompt("subagents/researcher");
7
+ const prompt = loadPrompt("subagents/analyst");
8
8
 
9
- assert.match(prompt, /researcher/);
10
- assert.match(prompt, /研究/);
9
+ assert.match(prompt, /analyst/);
10
+ assert.match(prompt, /SQL/);
11
11
  });
12
12
 
13
13
  test("渲染 {{variable}} 占位符", () => {
@@ -1,30 +1,30 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
 
4
- import { buildSupervisorPrompt } from "../../src/agents/prompts/supervisor.js";
4
+ import { buildSupervisorPrompt } from "../../src/agents/prompts/index.js";
5
5
  import { createDefaultSubagents } from "../../src/agents/subagents/index.js";
6
6
  import { agentStateSchema } from "../../src/agents/state/index.js";
7
7
 
8
8
  test("主 Agent 提示词包含团队与审批策略", () => {
9
9
  const prompt = buildSupervisorPrompt({
10
10
  name: "test-supervisor",
11
- subagents: [{ name: "researcher", description: "负责搜索网络。" }],
11
+ subagents: [{ name: "analyst", description: "负责只读 SQL 分析。" }],
12
12
  approvalMode: "sensitive",
13
13
  });
14
14
 
15
15
  assert.match(prompt, /test-supervisor/);
16
- assert.match(prompt, /researcher/);
16
+ assert.match(prompt, /analyst/);
17
17
  assert.match(prompt, /write_todos/);
18
18
  assert.match(prompt, /人工审批/);
19
19
  assert.doesNotMatch(prompt, /\{\{/);
20
20
  });
21
21
 
22
- test("默认子 Agent 为 researcher、coder、analyst", () => {
22
+ test("默认子 Agent 为 coder、analyst", () => {
23
23
  const subagents = createDefaultSubagents();
24
24
 
25
25
  assert.deepEqual(
26
26
  subagents.map((subagent) => subagent.name),
27
- ["researcher", "coder", "analyst"],
27
+ ["coder", "analyst"],
28
28
  );
29
29
 
30
30
  for (const subagent of subagents) {
@@ -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: Record<string, string>) => {
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
+ });
@@ -5,12 +5,11 @@ import type { Server } from "node:http";
5
5
  import test from "node:test";
6
6
 
7
7
  import { createApiApp } from "../../src/api/app.js";
8
- import { loadConfig } from "../../src/config/index.js";
9
- import { loadEnv } from "../../src/config/env.js";
10
- import { createLogger } from "../../src/infrastructure/logger/index.js";
11
- import type { AgentService } from "../../src/services/agent.service.js";
12
- import type { MemoryService } from "../../src/services/memory.service.js";
13
- import type { SessionService } from "../../src/services/session.service.js";
8
+ import { loadConfig, loadEnv } from "../../src/config/index.js";
9
+ import { createLogger } from "../../src/storage/logger/index.js";
10
+ import type { AgentService } from "../../src/services/agent.js";
11
+ import type { MemoryService } from "../../src/services/memory.js";
12
+ import type { SessionService } from "../../src/services/session.js";
14
13
 
15
14
  const config = loadConfig({
16
15
  env: loadEnv({ NODE_ENV: "test", LOG_LEVEL: "silent" }, { requireModelCredentials: false }),
@@ -1,7 +1,7 @@
1
1
  import assert from "node:assert/strict";
2
2
  import test from "node:test";
3
3
 
4
- import { findSecurityViolation } from "../../src/middleware/security.js";
4
+ import { findSecurityViolation } from "../../src/middleware/index.js";
5
5
 
6
6
  test("拦截破坏性 shell 命令", () => {
7
7
  for (const command of [
@@ -0,0 +1,61 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { loadEnv } from "../../src/config/index.js";
5
+ import { resolveModelConfig } from "../../src/model/index.js";
6
+
7
+ const envFor = (source: Record<string, string>) => {
8
+ return loadEnv({ NODE_ENV: "test", ...source }, { requireModelCredentials: false });
9
+ };
10
+
11
+ test("默认使用 MiniMax M3(OpenAI 兼容协议)", () => {
12
+ const config = resolveModelConfig(envFor({}));
13
+
14
+ assert.equal(config.provider, "minimax");
15
+ assert.equal(config.label, "MiniMax");
16
+ assert.equal(config.name, "MiniMax-M3");
17
+ assert.equal(config.baseUrl, "https://api.minimaxi.com/v1");
18
+ assert.equal(config.maxCompletionTokens, 32768);
19
+ });
20
+
21
+ test("预设切换服务商,并允许用 MODEL_* 覆盖", () => {
22
+ const config = resolveModelConfig(
23
+ envFor({
24
+ MODEL_PROVIDER: "deepseek",
25
+ MODEL_NAME: "deepseek-reasoner",
26
+ MODEL_BASE_URL: "https://gateway.internal/v1",
27
+ MODEL_API_KEY: "sk-test",
28
+ MODEL_TEMPERATURE: "0.5",
29
+ MODEL_MAX_COMPLETION_TOKENS: "1024",
30
+ }),
31
+ );
32
+
33
+ assert.equal(config.provider, "deepseek");
34
+ assert.equal(config.name, "deepseek-reasoner");
35
+ assert.equal(config.baseUrl, "https://gateway.internal/v1");
36
+ assert.equal(config.apiKey, "sk-test");
37
+ assert.equal(config.temperature, 0.5);
38
+ assert.equal(config.maxCompletionTokens, 1024);
39
+ });
40
+
41
+ test("旧变量 MODEL_MAX_TOKENS 仍然兼容,新变量优先", () => {
42
+ assert.equal(resolveModelConfig(envFor({ MODEL_MAX_TOKENS: "2048" })).maxCompletionTokens, 2048);
43
+
44
+ const config = resolveModelConfig(
45
+ envFor({ MODEL_MAX_COMPLETION_TOKENS: "8192", MODEL_MAX_TOKENS: "2048" }),
46
+ );
47
+ assert.equal(config.maxCompletionTokens, 8192);
48
+ });
49
+
50
+ test("MiniMax 预设使用国内 OpenAI 兼容地址", () => {
51
+ const config = resolveModelConfig(envFor({ MODEL_PROVIDER: "minimax" }));
52
+
53
+ assert.equal(config.label, "MiniMax");
54
+ assert.equal(config.name, "MiniMax-M3");
55
+ assert.equal(config.baseUrl, "https://api.minimaxi.com/v1");
56
+ });
57
+
58
+ test("缺少地址或模型名时给出明确的配置错误", () => {
59
+ assert.throws(() => resolveModelConfig(envFor({ MODEL_PROVIDER: "custom" })), /MODEL_BASE_URL/);
60
+ assert.throws(() => resolveModelConfig(envFor({ MODEL_PROVIDER: "vllm" })), /MODEL_NAME/);
61
+ });
@@ -0,0 +1,46 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+
4
+ import { loadEnv } from "../../src/config/index.js";
5
+ import { resolveSandboxConfig } from "../../src/sandbox/config.js";
6
+
7
+ const envFor = (source: Record<string, string>) => {
8
+ return loadEnv({ NODE_ENV: "test", ...source }, { requireModelCredentials: false });
9
+ };
10
+
11
+ test("默认不启用沙箱", () => {
12
+ const config = resolveSandboxConfig(envFor({}));
13
+
14
+ assert.equal(config.enabled, false);
15
+ assert.equal(config.domain, "localhost:8080");
16
+ assert.equal(config.protocol, "http");
17
+ assert.equal(config.image, "python:3.12");
18
+ assert.equal(config.timeoutSeconds, 1800);
19
+ assert.equal(config.workspaceRoot, "/workspace");
20
+ assert.equal(config.apiKey, undefined);
21
+ assert.equal(config.sandboxId, undefined);
22
+ });
23
+
24
+ test("启用沙箱时解析 OpenSandbox 配置", () => {
25
+ const config = resolveSandboxConfig(
26
+ envFor({
27
+ SANDBOX_ENABLED: "true",
28
+ OPEN_SANDBOX_DOMAIN: "sandbox.example.com",
29
+ OPEN_SANDBOX_PROTOCOL: "https",
30
+ OPEN_SANDBOX_API_KEY: "sk-test",
31
+ OPEN_SANDBOX_ID: "sbx-existing",
32
+ SANDBOX_IMAGE: "node:22",
33
+ SANDBOX_TIMEOUT_SECONDS: "600",
34
+ SANDBOX_WORKSPACE_ROOT: "/home/agent",
35
+ }),
36
+ );
37
+
38
+ assert.equal(config.enabled, true);
39
+ assert.equal(config.domain, "sandbox.example.com");
40
+ assert.equal(config.protocol, "https");
41
+ assert.equal(config.apiKey, "sk-test");
42
+ assert.equal(config.sandboxId, "sbx-existing");
43
+ assert.equal(config.image, "node:22");
44
+ assert.equal(config.timeoutSeconds, 600);
45
+ assert.equal(config.workspaceRoot, "/home/agent");
46
+ });