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
@@ -2,7 +2,8 @@ import { randomUUID } from "node:crypto";
2
2
 
3
3
  import type { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph";
4
4
 
5
- import type { CompiledAgent } from "../graph/compile.js";
5
+ import type { CompiledAgent } from "../graph/index.js";
6
+ import type { SandboxManager } from "../sandbox/index.js";
6
7
  import type { CreateSessionInput, SessionSummary } from "../schemas/session.js";
7
8
  import { NotFoundError } from "../utils/errors.js";
8
9
 
@@ -22,6 +23,8 @@ export interface SessionServiceDependencies {
22
23
  graph: CompiledAgent;
23
24
  checkpointer: BaseCheckpointSaver;
24
25
  store: BaseStore;
26
+ /** 提供后,删除会话会同时释放该会话的沙箱。 */
27
+ sandboxes?: SandboxManager;
25
28
  }
26
29
 
27
30
  export interface EnsureSessionInput {
@@ -42,14 +45,16 @@ export interface TouchSessionInput {
42
45
  * 该服务在 HTTP API 层把两者组合起来。
43
46
  */
44
47
  export class SessionService {
45
- readonly #graph: CompiledAgent;
46
- readonly #checkpointer: BaseCheckpointSaver;
47
- readonly #store: BaseStore;
48
-
49
- constructor({ graph, checkpointer, store }: SessionServiceDependencies) {
50
- this.#graph = graph;
51
- this.#checkpointer = checkpointer;
52
- this.#store = store;
48
+ private readonly graph: CompiledAgent;
49
+ private readonly checkpointer: BaseCheckpointSaver;
50
+ private readonly store: BaseStore;
51
+ private readonly sandboxes?: SandboxManager;
52
+
53
+ constructor({ graph, checkpointer, store, sandboxes }: SessionServiceDependencies) {
54
+ this.graph = graph;
55
+ this.checkpointer = checkpointer;
56
+ this.store = store;
57
+ this.sandboxes = sandboxes;
53
58
  }
54
59
 
55
60
  async create(input: CreateSessionInput): Promise<SessionSummary> {
@@ -67,13 +72,14 @@ export class SessionService {
67
72
  metadata: input.metadata,
68
73
  };
69
74
 
70
- await this.#store.put(namespace(input.tenantId), threadId, record);
75
+ await this.store.put(namespace(input.tenantId), threadId, record);
76
+
71
77
  return { ...record };
72
78
  }
73
79
 
74
80
  /** 会话记录不存在时创建(幂等)。 */
75
81
  async ensure({ threadId, tenantId, userId }: EnsureSessionInput): Promise<void> {
76
- const existing = await this.#store.get(namespace(tenantId), threadId);
82
+ const existing = await this.store.get(namespace(tenantId), threadId);
77
83
  if (existing) return;
78
84
 
79
85
  await this.create({
@@ -86,11 +92,12 @@ export class SessionService {
86
92
  }
87
93
 
88
94
  async touch({ threadId, tenantId, lastMessage }: TouchSessionInput): Promise<void> {
89
- const item = await this.#store.get(namespace(tenantId), threadId);
95
+ const item = await this.store.get(namespace(tenantId), threadId);
90
96
  if (!item) return;
91
97
 
92
98
  const record = item.value as unknown as SessionRecord;
93
- await this.#store.put(namespace(tenantId), threadId, {
99
+
100
+ await this.store.put(namespace(tenantId), threadId, {
94
101
  ...record,
95
102
  updatedAt: new Date().toISOString(),
96
103
  messageCount: record.messageCount + 2,
@@ -99,13 +106,14 @@ export class SessionService {
99
106
  }
100
107
 
101
108
  async get(threadId: string, tenantId = "default"): Promise<SessionSummary> {
102
- const item = await this.#store.get(namespace(tenantId), threadId);
109
+ const item = await this.store.get(namespace(tenantId), threadId);
103
110
  if (!item) {
104
111
  throw new NotFoundError(`未找到会话 "${threadId}"。`);
105
112
  }
106
113
 
107
114
  const record = item.value as unknown as SessionRecord;
108
- const state = await this.#graph.getState({
115
+
116
+ const state = await this.graph.getState({
109
117
  configurable: { thread_id: threadId },
110
118
  });
111
119
  const values = state.values as { messages?: unknown[] } | undefined;
@@ -120,7 +128,7 @@ export class SessionService {
120
128
  tenantId = "default",
121
129
  limit = 20,
122
130
  ): Promise<{ sessions: SessionSummary[]; total: number }> {
123
- const items = await this.#store.search(namespace(tenantId), { limit });
131
+ const items = await this.store.search(namespace(tenantId), { limit });
124
132
 
125
133
  const sessions = items.map(({ value }) => ({
126
134
  ...(value as unknown as SessionRecord),
@@ -130,15 +138,17 @@ export class SessionService {
130
138
  }
131
139
 
132
140
  async remove(threadId: string, tenantId = "default"): Promise<void> {
133
- await this.#checkpointer.deleteThread(threadId);
134
- await this.#store.delete(namespace(tenantId), threadId);
141
+ await this.checkpointer.deleteThread(threadId);
142
+ await this.store.delete(namespace(tenantId), threadId);
143
+ await this.sandboxes?.release(threadId);
135
144
  }
136
145
 
137
146
  async history(threadId: string): Promise<unknown[]> {
138
- const state = await this.#graph.getState({
147
+ const state = await this.graph.getState({
139
148
  configurable: { thread_id: threadId },
140
149
  });
141
150
  const values = state.values as { messages?: unknown[] } | undefined;
151
+
142
152
  return values?.messages ?? [];
143
153
  }
144
154
  }
@@ -46,23 +46,19 @@ export const parseSkillFrontmatter = (content: string): SkillFrontmatter => {
46
46
  };
47
47
 
48
48
  /** 读取目录;目录不存在时返回空数组。 */
49
- const readDirectory = async (directory: string): Promise<Dirent[]> => {
50
- try {
51
- return await fs.readdir(directory, { withFileTypes: true });
52
- } catch (error) {
49
+ const readDirectory = (directory: string): Promise<Dirent[]> => {
50
+ return fs.readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
53
51
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
54
52
  throw error;
55
- }
53
+ });
56
54
  };
57
55
 
58
56
  /** 读取文本文件;文件不存在时返回 null。 */
59
- const readTextFile = async (file: string): Promise<string | null> => {
60
- try {
61
- return await fs.readFile(file, "utf8");
62
- } catch (error) {
57
+ const readTextFile = (file: string): Promise<string | null> => {
58
+ return fs.readFile(file, "utf8").catch((error: unknown) => {
63
59
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
64
60
  throw error;
65
- }
61
+ });
66
62
  };
67
63
 
68
64
  /**
@@ -0,0 +1,65 @@
1
+ import { performance } from "node:perf_hooks";
2
+
3
+ import { Pool, type PoolClient } from "pg";
4
+
5
+ import { ConfigurationError } from "../../utils/errors.js";
6
+ import { errorMessage } from "../../utils/helpers.js";
7
+
8
+ let pool: Pool | undefined;
9
+
10
+ /** 懒加载共享的 PostgreSQL 连接池。 */
11
+ export const getPool = (connectionString = process.env.DATABASE_URL): Pool => {
12
+ if (!connectionString) {
13
+ throw new ConfigurationError(
14
+ "未配置 PostgreSQL 连接信息。请设置 DATABASE_URL 或 POSTGRES_* 后使用数据库功能。",
15
+ );
16
+ }
17
+
18
+ pool ??= new Pool({
19
+ connectionString,
20
+ max: 10,
21
+ idleTimeoutMillis: 30_000,
22
+ connectionTimeoutMillis: 5_000,
23
+ });
24
+
25
+ return pool;
26
+ };
27
+
28
+ export interface DatabaseHealth {
29
+ ok: boolean;
30
+ latencyMs?: number;
31
+ error?: string;
32
+ }
33
+
34
+ const probe = async (connectionString: string): Promise<DatabaseHealth> => {
35
+ const client: PoolClient = await getPool(connectionString).connect();
36
+ const startedAt = performance.now();
37
+
38
+ return client
39
+ .query("select 1")
40
+ .then(() => ({ ok: true, latencyMs: Math.round(performance.now() - startedAt) }))
41
+ .finally(() => client.release());
42
+ };
43
+
44
+ /** 健康检查只返回状态,不向上抛错:连接或查询失败都折算成 `ok: false`。 */
45
+ export const checkDatabase = async (
46
+ connectionString = process.env.DATABASE_URL,
47
+ ): Promise<DatabaseHealth> => {
48
+ if (!connectionString) {
49
+ return { ok: false, error: "未配置 PostgreSQL 连接信息" };
50
+ }
51
+
52
+ return probe(connectionString).catch((error: unknown) => ({
53
+ ok: false,
54
+ error: errorMessage(error),
55
+ }));
56
+ };
57
+
58
+ export const closeDatabase = async (): Promise<void> => {
59
+ if (!pool) return;
60
+
61
+ const current = pool;
62
+ pool = undefined;
63
+
64
+ await current.end();
65
+ };
@@ -5,7 +5,7 @@
5
5
  -- 所需的表;本迁移只用于应用自有的表结构。
6
6
  --
7
7
  -- 使用 psql 或你常用的迁移工具执行:
8
- -- psql "$DATABASE_URL" -f src/infrastructure/database/migrations/001_init.sql
8
+ -- psql "$DATABASE_URL" -f src/storage/database/migrations/001_init.sql
9
9
 
10
10
  CREATE TABLE IF NOT EXISTS agent_audit_log (
11
11
  id BIGSERIAL PRIMARY KEY,
@@ -3,6 +3,7 @@ import { performance } from "node:perf_hooks";
3
3
  import { Redis } from "ioredis";
4
4
 
5
5
  import { ConfigurationError } from "../../utils/errors.js";
6
+ import { errorMessage } from "../../utils/helpers.js";
6
7
 
7
8
  let client: Redis | undefined;
8
9
 
@@ -27,27 +28,23 @@ export interface RedisHealth {
27
28
  error?: string;
28
29
  }
29
30
 
31
+ const probe = async (): Promise<RedisHealth> => {
32
+ const redis = getRedis();
33
+ if (redis.status === "wait") await redis.connect();
34
+
35
+ const startedAt = performance.now();
36
+ await redis.ping();
37
+
38
+ return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
39
+ };
40
+
41
+ /** 健康检查只返回状态,不向上抛错:连接或 ping 失败都折算成 `ok: false`。 */
30
42
  export const checkRedis = async (): Promise<RedisHealth> => {
31
43
  if (!process.env.REDIS_URL) {
32
44
  return { ok: false, error: "未配置 REDIS_URL" };
33
45
  }
34
46
 
35
- try {
36
- const redis = getRedis();
37
- if (redis.status === "wait") {
38
- await redis.connect();
39
- }
40
-
41
- const startedAt = performance.now();
42
- await redis.ping();
43
-
44
- return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
45
- } catch (error) {
46
- return {
47
- ok: false,
48
- error: error instanceof Error ? error.message : String(error),
49
- };
50
- }
47
+ return probe().catch((error: unknown) => ({ ok: false, error: errorMessage(error) }));
51
48
  };
52
49
 
53
50
  export const closeRedis = async (): Promise<void> => {
@@ -56,9 +53,5 @@ export const closeRedis = async (): Promise<void> => {
56
53
  const current = client;
57
54
  client = undefined;
58
55
 
59
- try {
60
- await current.quit();
61
- } catch {
62
- current.disconnect();
63
- }
56
+ await current.quit().catch(() => current.disconnect());
64
57
  };
@@ -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) {