create-deepagent-server 0.0.0-stage → 0.1.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +193 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +85 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +182 -0
  11. package/src/setup.js +77 -0
  12. package/src/ui.js +43 -0
  13. package/src/version.js +1 -0
  14. package/src/versions.js +29 -0
  15. package/templates/deepagent/js/deployment/Dockerfile +19 -0
  16. package/templates/deepagent/js/scripts/check.js +74 -0
  17. package/templates/deepagent/js/scripts/dev.js +31 -0
  18. package/templates/deepagent/js/src/agents/factory.js +10 -0
  19. package/templates/deepagent/js/src/agents/index.js +4 -0
  20. package/templates/deepagent/js/src/agents/prompts/index.js +2 -0
  21. package/templates/deepagent/js/src/agents/prompts/loader.js +44 -0
  22. package/templates/deepagent/js/src/agents/prompts/subagents/analyst.md +17 -0
  23. package/templates/deepagent/js/src/agents/prompts/subagents/coder.md +17 -0
  24. package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +16 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.js +17 -0
  26. package/templates/deepagent/js/src/agents/prompts/supervisor.md +42 -0
  27. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  28. package/templates/deepagent/js/src/agents/state/types.js +10 -0
  29. package/templates/deepagent/js/src/agents/subagents/analyst.js +11 -0
  30. package/templates/deepagent/js/src/agents/subagents/coder.js +11 -0
  31. package/templates/deepagent/js/src/agents/subagents/index.js +8 -0
  32. package/templates/deepagent/js/src/agents/subagents/researcher.js +12 -0
  33. package/templates/deepagent/js/src/agents/supervisor.js +56 -0
  34. package/templates/deepagent/js/src/api/app.js +22 -0
  35. package/templates/deepagent/js/src/api/middleware/auth.js +27 -0
  36. package/templates/deepagent/js/src/api/middleware/error.js +26 -0
  37. package/templates/deepagent/js/src/api/routes/agent.js +73 -0
  38. package/templates/deepagent/js/src/api/routes/health.js +31 -0
  39. package/templates/deepagent/js/src/api/routes/session.js +62 -0
  40. package/templates/deepagent/js/src/app.js +79 -0
  41. package/templates/deepagent/js/src/backends/composite.js +20 -0
  42. package/templates/deepagent/js/src/backends/filesystem.js +8 -0
  43. package/templates/deepagent/js/src/backends/index.js +28 -0
  44. package/templates/deepagent/js/src/backends/sandbox.js +23 -0
  45. package/templates/deepagent/js/src/config/agent.js +13 -0
  46. package/templates/deepagent/js/src/config/env.js +73 -0
  47. package/templates/deepagent/js/src/config/index.js +35 -0
  48. package/templates/deepagent/js/src/config/model.js +34 -0
  49. package/templates/deepagent/js/src/graph/checkpointer.js +20 -0
  50. package/templates/deepagent/js/src/graph/compile.js +8 -0
  51. package/templates/deepagent/js/src/graph/index.js +3 -0
  52. package/templates/deepagent/js/src/graph/store.js +20 -0
  53. package/templates/deepagent/js/src/index.js +32 -0
  54. package/templates/deepagent/js/src/infrastructure/database/client.js +43 -0
  55. package/templates/deepagent/js/src/infrastructure/database/migrations/001_init.sql +20 -0
  56. package/templates/deepagent/js/src/infrastructure/logger/index.js +19 -0
  57. package/templates/deepagent/js/src/infrastructure/redis/client.js +45 -0
  58. package/templates/deepagent/js/src/infrastructure/shutdown/index.js +51 -0
  59. package/templates/deepagent/js/src/memory/index.js +6 -0
  60. package/templates/deepagent/js/src/memory/manager.js +39 -0
  61. package/templates/deepagent/js/src/memory/store.js +36 -0
  62. package/templates/deepagent/js/src/middleware/approval.js +42 -0
  63. package/templates/deepagent/js/src/middleware/context.js +30 -0
  64. package/templates/deepagent/js/src/middleware/index.js +9 -0
  65. package/templates/deepagent/js/src/middleware/logging.js +66 -0
  66. package/templates/deepagent/js/src/middleware/security.js +51 -0
  67. package/templates/deepagent/js/src/schemas/agent.js +33 -0
  68. package/templates/deepagent/js/src/schemas/common.js +19 -0
  69. package/templates/deepagent/js/src/schemas/locale.js +3 -0
  70. package/templates/deepagent/js/src/schemas/session.js +23 -0
  71. package/templates/deepagent/js/src/services/agent.service.js +117 -0
  72. package/templates/deepagent/js/src/services/memory.service.js +27 -0
  73. package/templates/deepagent/js/src/services/session.service.js +92 -0
  74. package/templates/deepagent/js/src/skills/index.js +17 -0
  75. package/templates/deepagent/js/src/skills/loader.js +65 -0
  76. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  77. package/templates/deepagent/js/src/tools/database/query.js +62 -0
  78. package/templates/deepagent/js/src/tools/filesystem/index.js +86 -0
  79. package/templates/deepagent/js/src/tools/index.js +30 -0
  80. package/templates/deepagent/js/src/tools/mcp/client.js +35 -0
  81. package/templates/deepagent/js/src/tools/mcp/connections.js +54 -0
  82. package/templates/deepagent/js/src/tools/mcp/index.js +8 -0
  83. package/templates/deepagent/js/src/tools/mcp/registry.js +32 -0
  84. package/templates/deepagent/js/src/tools/search/index.js +1 -0
  85. package/templates/deepagent/js/src/tools/search/web-search.js +54 -0
  86. package/templates/deepagent/js/src/utils/errors.js +64 -0
  87. package/templates/deepagent/js/src/utils/helpers.js +42 -0
  88. package/templates/deepagent/js/tests/agents/prompts.test.js +24 -0
  89. package/templates/deepagent/js/tests/agents/supervisor.test.js +34 -0
  90. package/templates/deepagent/js/tests/integration/api.test.js +99 -0
  91. package/templates/deepagent/js/tests/middleware/security.test.js +24 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +23 -0
  93. package/templates/deepagent/shared/README.md +162 -0
  94. package/templates/deepagent/shared/_editorconfig +12 -0
  95. package/templates/deepagent/shared/_env.example +56 -0
  96. package/templates/deepagent/shared/_gitignore +22 -0
  97. package/templates/deepagent/shared/deployment/docker-compose.yml +56 -0
  98. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  99. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  100. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  101. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  102. package/templates/deepagent/shared/skills/research/SKILL.md +31 -0
  103. package/templates/deepagent/shared/workspaces/README.md +5 -0
  104. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  105. package/templates/deepagent/ts/scripts/check.ts +91 -0
  106. package/templates/deepagent/ts/scripts/copy-assets.ts +35 -0
  107. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  108. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  109. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  110. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  111. package/templates/deepagent/ts/src/agents/prompts/loader.ts +52 -0
  112. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  113. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  114. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +16 -0
  115. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +42 -0
  116. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  117. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  118. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  119. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +14 -0
  120. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  121. package/templates/deepagent/ts/src/agents/subagents/index.ts +10 -0
  122. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +15 -0
  123. package/templates/deepagent/ts/src/agents/supervisor.ts +80 -0
  124. package/templates/deepagent/ts/src/api/app.ts +48 -0
  125. package/templates/deepagent/ts/src/api/middleware/auth.ts +37 -0
  126. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  127. package/templates/deepagent/ts/src/api/routes/agent.ts +93 -0
  128. package/templates/deepagent/ts/src/api/routes/health.ts +45 -0
  129. package/templates/deepagent/ts/src/api/routes/session.ts +77 -0
  130. package/templates/deepagent/ts/src/app.ts +104 -0
  131. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  132. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  133. package/templates/deepagent/ts/src/backends/index.ts +42 -0
  134. package/templates/deepagent/ts/src/backends/sandbox.ts +32 -0
  135. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  136. package/templates/deepagent/ts/src/config/env.ts +102 -0
  137. package/templates/deepagent/ts/src/config/index.ts +76 -0
  138. package/templates/deepagent/ts/src/config/model.ts +49 -0
  139. package/templates/deepagent/ts/src/graph/checkpointer.ts +26 -0
  140. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  141. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  142. package/templates/deepagent/ts/src/graph/store.ts +26 -0
  143. package/templates/deepagent/ts/src/index.ts +39 -0
  144. package/templates/deepagent/ts/src/infrastructure/database/client.ts +61 -0
  145. package/templates/deepagent/ts/src/infrastructure/database/migrations/001_init.sql +20 -0
  146. package/templates/deepagent/ts/src/infrastructure/logger/index.ts +25 -0
  147. package/templates/deepagent/ts/src/infrastructure/redis/client.ts +64 -0
  148. package/templates/deepagent/ts/src/infrastructure/shutdown/index.ts +85 -0
  149. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  150. package/templates/deepagent/ts/src/memory/manager.ts +74 -0
  151. package/templates/deepagent/ts/src/memory/store.ts +57 -0
  152. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  153. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  154. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  155. package/templates/deepagent/ts/src/middleware/logging.ts +72 -0
  156. package/templates/deepagent/ts/src/middleware/security.ts +60 -0
  157. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  158. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  159. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  160. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  161. package/templates/deepagent/ts/src/services/agent.service.ts +170 -0
  162. package/templates/deepagent/ts/src/services/memory.service.ts +43 -0
  163. package/templates/deepagent/ts/src/services/session.service.ts +148 -0
  164. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  165. package/templates/deepagent/ts/src/skills/loader.ts +94 -0
  166. package/templates/deepagent/ts/src/tools/database/index.ts +1 -0
  167. package/templates/deepagent/ts/src/tools/database/query.ts +71 -0
  168. package/templates/deepagent/ts/src/tools/filesystem/index.ts +108 -0
  169. package/templates/deepagent/ts/src/tools/index.ts +41 -0
  170. package/templates/deepagent/ts/src/tools/mcp/client.ts +53 -0
  171. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  172. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  173. package/templates/deepagent/ts/src/tools/mcp/registry.ts +48 -0
  174. package/templates/deepagent/ts/src/tools/search/index.ts +1 -0
  175. package/templates/deepagent/ts/src/tools/search/web-search.ts +82 -0
  176. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  177. package/templates/deepagent/ts/src/utils/helpers.ts +52 -0
  178. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  179. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  180. package/templates/deepagent/ts/tests/integration/api.test.ts +123 -0
  181. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  182. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  183. package/templates/deepagent/ts/tsconfig.json +19 -0
@@ -0,0 +1,92 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { NotFoundError } from "../utils/errors.js";
3
+ /**
4
+ * 会话元数据存放在 LangGraph store 的
5
+ * `["sessions", tenantId, threadId]` 下;对话本身存放在 checkpointer 中。
6
+ * 该服务在 HTTP API 层把两者组合起来。
7
+ */
8
+ export class SessionService {
9
+ #graph;
10
+ #checkpointer;
11
+ #store;
12
+ constructor({ graph, checkpointer, store }) {
13
+ this.#graph = graph;
14
+ this.#checkpointer = checkpointer;
15
+ this.#store = store;
16
+ }
17
+ async create(input) {
18
+ const threadId = input.threadId ?? randomUUID();
19
+ const now = new Date().toISOString();
20
+ const record = {
21
+ threadId,
22
+ title: input.title,
23
+ tenantId: input.tenantId,
24
+ ...(input.userId ? { userId: input.userId } : {}),
25
+ createdAt: now,
26
+ updatedAt: now,
27
+ messageCount: 0,
28
+ metadata: input.metadata,
29
+ };
30
+ await this.#store.put(namespace(input.tenantId), threadId, record);
31
+ return { ...record };
32
+ }
33
+ /** 会话记录不存在时创建(幂等)。 */
34
+ async ensure({ threadId, tenantId, userId }) {
35
+ const existing = await this.#store.get(namespace(tenantId), threadId);
36
+ if (existing) return;
37
+ await this.create({
38
+ threadId,
39
+ tenantId,
40
+ title: `Session ${threadId.slice(0, 8)}`,
41
+ metadata: {},
42
+ ...(userId ? { userId } : {}),
43
+ });
44
+ }
45
+ async touch({ threadId, tenantId, lastMessage }) {
46
+ const item = await this.#store.get(namespace(tenantId), threadId);
47
+ if (!item) return;
48
+ const record = item.value;
49
+ await this.#store.put(namespace(tenantId), threadId, {
50
+ ...record,
51
+ updatedAt: new Date().toISOString(),
52
+ messageCount: record.messageCount + 2,
53
+ ...(lastMessage ? { lastMessage: lastMessage.slice(0, 1_000) } : {}),
54
+ });
55
+ }
56
+ async get(threadId, tenantId = "default") {
57
+ const item = await this.#store.get(namespace(tenantId), threadId);
58
+ if (!item) {
59
+ throw new NotFoundError(`未找到会话 "${threadId}"。`);
60
+ }
61
+ const record = item.value;
62
+ const state = await this.#graph.getState({
63
+ configurable: { thread_id: threadId },
64
+ });
65
+ const values = state.values;
66
+ return {
67
+ ...record,
68
+ messageCount: values?.messages?.length ?? record.messageCount,
69
+ };
70
+ }
71
+ async list(tenantId = "default", limit = 20) {
72
+ const items = await this.#store.search(namespace(tenantId), { limit });
73
+ const sessions = items.map(({ value }) => ({
74
+ ...value,
75
+ }));
76
+ return { sessions, total: sessions.length };
77
+ }
78
+ async remove(threadId, tenantId = "default") {
79
+ await this.#checkpointer.deleteThread(threadId);
80
+ await this.#store.delete(namespace(tenantId), threadId);
81
+ }
82
+ async history(threadId) {
83
+ const state = await this.#graph.getState({
84
+ configurable: { thread_id: threadId },
85
+ });
86
+ const values = state.values;
87
+ return values?.messages ?? [];
88
+ }
89
+ }
90
+ const namespace = (tenantId) => {
91
+ return ["sessions", tenantId];
92
+ };
@@ -0,0 +1,17 @@
1
+ import { discoverSkills } from "./loader.js";
2
+ export { discoverSkills, parseSkillFrontmatter } from "./loader.js";
3
+ /** Deep Agents skills 中间件扫描的虚拟后端路径。 */
4
+ export const DEFAULT_SKILL_SOURCES = ["/skills/"];
5
+ /** 从磁盘发现技能(用于启动校验和 `scripts/check`)。 */
6
+ export const loadSkills = async ({ rootDir }) => {
7
+ return discoverSkills(rootDir);
8
+ };
9
+ /**
10
+ * 为缺少 description 的技能返回可读警告。
11
+ * 模型正是依赖 description 来选择技能。
12
+ */
13
+ export const validateSkills = (skills) => {
14
+ return skills
15
+ .filter((skill) => skill.description.trim().length === 0)
16
+ .map((skill) => `技能 "${skill.name}" 缺少 description(${skill.file})`);
17
+ };
@@ -0,0 +1,65 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ /** 不依赖 YAML 库,解析 SKILL.md 的 frontmatter。 */
4
+ export const parseSkillFrontmatter = (content) => {
5
+ if (!content.startsWith("---")) return {};
6
+ const end = content.indexOf("\n---", 3);
7
+ if (end === -1) return {};
8
+ const frontmatter = content.slice(3, end);
9
+ const fields = {};
10
+ for (const line of frontmatter.split("\n")) {
11
+ const separator = line.indexOf(":");
12
+ if (separator === -1) continue;
13
+ const key = line.slice(0, separator).trim();
14
+ const value = line
15
+ .slice(separator + 1)
16
+ .trim()
17
+ .replace(/^["']|["']$/g, "");
18
+ if (key) fields[key] = value;
19
+ }
20
+ return {
21
+ ...(fields.name ? { name: fields.name } : {}),
22
+ ...(fields.description ? { description: fields.description } : {}),
23
+ };
24
+ };
25
+ /** 读取目录;目录不存在时返回空数组。 */
26
+ const readDirectory = async (directory) => {
27
+ try {
28
+ return await fs.readdir(directory, { withFileTypes: true });
29
+ } catch (error) {
30
+ if (error.code === "ENOENT") return [];
31
+ throw error;
32
+ }
33
+ };
34
+ /** 读取文本文件;文件不存在时返回 null。 */
35
+ const readTextFile = async (file) => {
36
+ try {
37
+ return await fs.readFile(file, "utf8");
38
+ } catch (error) {
39
+ if (error.code === "ENOENT") return null;
40
+ throw error;
41
+ }
42
+ };
43
+ /**
44
+ * 扫描 `rootDir` 下包含 SKILL.md 的子目录。
45
+ * 目录不存在时返回空数组,保证没有技能时也能启动。
46
+ */
47
+ export const discoverSkills = async (rootDir) => {
48
+ const entries = await readDirectory(rootDir);
49
+ const skills = [];
50
+ for (const entry of entries) {
51
+ if (!entry.isDirectory()) continue;
52
+ const directory = path.join(rootDir, entry.name);
53
+ const file = path.join(directory, "SKILL.md");
54
+ const content = await readTextFile(file);
55
+ if (content === null) continue;
56
+ const metadata = parseSkillFrontmatter(content);
57
+ skills.push({
58
+ name: metadata.name ?? entry.name,
59
+ description: metadata.description ?? "",
60
+ directory,
61
+ file,
62
+ });
63
+ }
64
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
65
+ };
@@ -0,0 +1 @@
1
+ export { assertReadOnlyQuery, queryDatabaseTool } from "./query.js";
@@ -0,0 +1,62 @@
1
+ import { tool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+ import { getPool } from "../../infrastructure/database/client.js";
4
+ const READ_ONLY_START = /^\s*(?:select|with)\b/i;
5
+ const FORBIDDEN_KEYWORDS =
6
+ /\b(insert|update|delete|drop|alter|truncate|create|grant|revoke|copy|vacuum|reindex|call|do)\b/i;
7
+ /**
8
+ * 对模型生成的 SQL 做前置校验。查询同时运行在 READ ONLY 事务中,
9
+ * 即使绕过校验也无法修改数据。
10
+ */
11
+ export const assertReadOnlyQuery = (sql) => {
12
+ const statement = sql.trim().replace(/;\s*$/, "");
13
+ if (!READ_ONLY_START.test(statement)) {
14
+ throw new Error("只允许 SELECT 和 WITH 查询。");
15
+ }
16
+ if (statement.includes(";")) {
17
+ throw new Error("只允许单条 SQL 语句。");
18
+ }
19
+ if (FORBIDDEN_KEYWORDS.test(statement)) {
20
+ throw new Error("查询包含写入或 DDL 关键字,已拒绝执行。");
21
+ }
22
+ };
23
+ const querySchema = z.object({
24
+ sql: z.string().min(1).describe("单条只读 SQL 语句(SELECT 或 WITH)。"),
25
+ params: z
26
+ .array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
27
+ .default([])
28
+ .describe("与 $1、$2…… 占位符对应的位置参数。"),
29
+ limit: z.number().int().min(1).max(500).default(100),
30
+ });
31
+ /** 只读、参数化的 PostgreSQL 查询工具。 */
32
+ export const queryDatabaseTool = tool(
33
+ async ({ sql, params, limit }) => {
34
+ assertReadOnlyQuery(sql);
35
+ const client = await getPool().connect();
36
+ try {
37
+ await client.query("BEGIN TRANSACTION READ ONLY");
38
+ await client.query("SET LOCAL statement_timeout = '10s'");
39
+ const result = await client.query(sql, params);
40
+ await client.query("COMMIT");
41
+ return JSON.stringify(
42
+ {
43
+ rowCount: result.rowCount,
44
+ truncated: result.rows.length > limit,
45
+ rows: result.rows.slice(0, limit),
46
+ },
47
+ null,
48
+ 2,
49
+ );
50
+ } catch (error) {
51
+ await client.query("ROLLBACK").catch(() => undefined);
52
+ throw error;
53
+ } finally {
54
+ client.release();
55
+ }
56
+ },
57
+ {
58
+ name: "query_database",
59
+ description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
60
+ schema: querySchema,
61
+ },
62
+ );
@@ -0,0 +1,86 @@
1
+ import fs from "node:fs/promises";
2
+ import nodePath from "node:path";
3
+ import { tool } from "@langchain/core/tools";
4
+ import { z } from "zod";
5
+ const resolveInsideRoot = (rootDir, target) => {
6
+ const root = nodePath.resolve(rootDir);
7
+ const resolved = nodePath.resolve(root, target);
8
+ if (resolved !== root && !resolved.startsWith(`${root}${nodePath.sep}`)) {
9
+ throw new Error(`路径越出了工作区根目录:${target}`);
10
+ }
11
+ return resolved;
12
+ };
13
+ /**
14
+ * 面向应用自有文件的额外工作区工具。Deep Agents 已内置对后端的
15
+ * read_file/write_file/edit_file;这些工具限定在 `workspaces/` 内,
16
+ * 方便服务层(而不是模型)安全地读取产物。
17
+ */
18
+ export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
19
+ const readSchema = z.object({
20
+ filePath: z.string().min(1).describe("相对于工作区根目录的路径。"),
21
+ maxBytes: z.number().int().positive().default(maxReadBytes),
22
+ });
23
+ const readFile = tool(
24
+ async ({ filePath, maxBytes }) => {
25
+ const resolved = resolveInsideRoot(rootDir, filePath);
26
+ const content = await fs.readFile(resolved, "utf8");
27
+ if (content.length <= maxBytes) return content;
28
+ return `${content.slice(0, maxBytes)}\n… 已在 ${maxBytes} 个字符处截断`;
29
+ },
30
+ {
31
+ name: "read_workspace_file",
32
+ description: "按相对于工作区根目录的路径读取 Agent 工作区中的文件。",
33
+ schema: readSchema,
34
+ },
35
+ );
36
+ const writeSchema = z.object({
37
+ filePath: z.string().min(1),
38
+ content: z.string(),
39
+ append: z.boolean().default(false),
40
+ });
41
+ const writeFile = tool(
42
+ async ({ filePath, content, append }) => {
43
+ const resolved = resolveInsideRoot(rootDir, filePath);
44
+ await fs.mkdir(nodePath.dirname(resolved), { recursive: true });
45
+ if (append) {
46
+ await fs.appendFile(resolved, content, "utf8");
47
+ } else {
48
+ await fs.writeFile(resolved, content, "utf8");
49
+ }
50
+ return `已写入 ${content.length} 个字符到 ${filePath}`;
51
+ },
52
+ {
53
+ name: "write_workspace_file",
54
+ description: "在 Agent 工作区中创建或覆盖文件,也可以选择追加内容。",
55
+ schema: writeSchema,
56
+ },
57
+ );
58
+ const listSchema = z.object({
59
+ directory: z.string().default("."),
60
+ recursive: z.boolean().default(false),
61
+ });
62
+ const listFiles = tool(
63
+ async ({ directory, recursive }) => {
64
+ const resolved = resolveInsideRoot(rootDir, directory);
65
+ const entries = await fs.readdir(resolved, {
66
+ recursive,
67
+ withFileTypes: true,
68
+ });
69
+ const files = entries
70
+ .map((entry) => ({
71
+ name: entry.name,
72
+ path: nodePath.relative(rootDir, nodePath.join(entry.parentPath, entry.name)),
73
+ type: entry.isDirectory() ? "目录" : "文件",
74
+ }))
75
+ .sort((a, b) => a.path.localeCompare(b.path))
76
+ .slice(0, 500);
77
+ return JSON.stringify({ root: directory, files }, null, 2);
78
+ },
79
+ {
80
+ name: "list_workspace_files",
81
+ description: "列出 Agent 工作区中的文件和目录,不读取文件内容。",
82
+ schema: listSchema,
83
+ },
84
+ );
85
+ return [readFile, writeFile, listFiles];
86
+ };
@@ -0,0 +1,30 @@
1
+ import { queryDatabaseTool } from "./database/index.js";
2
+ import { createWorkspaceTools } from "./filesystem/index.js";
3
+ import { webSearchTool } from "./search/index.js";
4
+ export { assertReadOnlyQuery, queryDatabaseTool } from "./database/index.js";
5
+ export { createWorkspaceTools } from "./filesystem/index.js";
6
+ export {
7
+ createMcpAdapter,
8
+ createMcpToolRegistry,
9
+ loadMcpConnections,
10
+ loadMcpTools,
11
+ McpToolRegistry,
12
+ mcpServerSchema,
13
+ } from "./mcp/index.js";
14
+ export { createWebSearchTool, webSearchTool } from "./search/index.js";
15
+ /**
16
+ * 主 Agent 和子 Agent 可用的工具,位于 Deep Agents 内置工具
17
+ * (write_todos、read_file、write_file、task 等)之上。
18
+ */
19
+ export const createDefaultTools = ({
20
+ workspaceRoot,
21
+ enableDatabase = Boolean(process.env.DATABASE_URL),
22
+ additionalTools = [],
23
+ }) => {
24
+ return [
25
+ webSearchTool,
26
+ ...(enableDatabase ? [queryDatabaseTool] : []),
27
+ ...createWorkspaceTools({ rootDir: workspaceRoot }),
28
+ ...additionalTools,
29
+ ];
30
+ };
@@ -0,0 +1,35 @@
1
+ import { MCPAdapter } from "@langchain/mcp-adapters";
2
+ const toAdapterServers = (connections) => {
3
+ const servers = {};
4
+ for (const [name, connection] of Object.entries(connections)) {
5
+ if (connection.transport === "stdio") {
6
+ servers[name] = {
7
+ transport: "stdio",
8
+ command: connection.command,
9
+ args: connection.args,
10
+ env: connection.env,
11
+ };
12
+ } else if (connection.transport === "http") {
13
+ servers[name] = { transport: "http", url: connection.url };
14
+ } else {
15
+ servers[name] = { transport: "sse", url: connection.url };
16
+ }
17
+ }
18
+ return servers;
19
+ };
20
+ /** 创建多服务器 MCP 适配器;连接按需建立。 */
21
+ export const createMcpAdapter = (connections) => {
22
+ return new MCPAdapter({
23
+ servers: toAdapterServers(connections),
24
+ onConnectionError: "ignore",
25
+ });
26
+ };
27
+ /** 加载已配置的 MCP 服务器暴露的全部工具。 */
28
+ export const loadMcpTools = async (connections) => {
29
+ if (Object.keys(connections).length === 0) {
30
+ return { adapter: null, tools: [] };
31
+ }
32
+ const adapter = createMcpAdapter(connections);
33
+ const tools = await adapter.listTools();
34
+ return { adapter, tools };
35
+ };
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ import { ConfigurationError } from "../../utils/errors.js";
3
+ const stdioConnectionSchema = z.object({
4
+ transport: z.literal("stdio"),
5
+ command: z.string().min(1),
6
+ args: z.array(z.string()).default([]),
7
+ env: z.record(z.string(), z.string()).default({}),
8
+ });
9
+ const httpConnectionSchema = z.object({
10
+ transport: z.literal("http"),
11
+ url: z.string().min(1),
12
+ headers: z.record(z.string(), z.string()).default({}),
13
+ });
14
+ const sseConnectionSchema = z.object({
15
+ transport: z.literal("sse"),
16
+ url: z.string().min(1),
17
+ headers: z.record(z.string(), z.string()).default({}),
18
+ });
19
+ export const mcpServerSchema = z.discriminatedUnion("transport", [
20
+ stdioConnectionSchema,
21
+ httpConnectionSchema,
22
+ sseConnectionSchema,
23
+ ]);
24
+ /**
25
+ * 从 `MCP_SERVERS`(JSON)或已解析的对象中读取 MCP 连接配置。
26
+ *
27
+ * @example
28
+ * MCP_SERVERS='{"filesystem":{"transport":"stdio","command":"npx","args":["-y","@modelcontextprotocol/server-filesystem","."]}}'
29
+ */
30
+ export const loadMcpConnections = (raw = process.env.MCP_SERVERS) => {
31
+ if (!raw || raw.trim() === "") return {};
32
+ let parsed;
33
+ try {
34
+ parsed = JSON.parse(raw);
35
+ } catch (error) {
36
+ throw new ConfigurationError(
37
+ `MCP_SERVERS 必须是合法的 JSON:${error instanceof Error ? error.message : String(error)}`,
38
+ );
39
+ }
40
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
41
+ throw new ConfigurationError("MCP_SERVERS 必须是以服务器名称为键的对象。");
42
+ }
43
+ const entries = Object.entries(parsed).map(([name, value]) => {
44
+ const result = mcpServerSchema.safeParse(value);
45
+ if (!result.success) {
46
+ const issues = result.error.issues
47
+ .map((issue) => `${issue.path.join(".") || name}: ${issue.message}`)
48
+ .join("; ");
49
+ throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
50
+ }
51
+ return [name, result.data];
52
+ });
53
+ return Object.fromEntries(entries);
54
+ };
@@ -0,0 +1,8 @@
1
+ import { McpToolRegistry } from "./registry.js";
2
+ export { createMcpAdapter, loadMcpTools } from "./client.js";
3
+ export { loadMcpConnections, mcpServerSchema } from "./connections.js";
4
+ export { McpToolRegistry };
5
+ /** 启动时加载一次 MCP 工具;未配置时返回空注册表。 */
6
+ export const createMcpToolRegistry = async () => {
7
+ return McpToolRegistry.create();
8
+ };
@@ -0,0 +1,32 @@
1
+ import { loadMcpTools } from "./client.js";
2
+ import { loadMcpConnections } from "./connections.js";
3
+ /**
4
+ * 持有整个进程生命周期的 MCP 适配器。启动时加载一次工具并交给主 Agent;
5
+ * 关闭时断开连接。
6
+ */
7
+ export class McpToolRegistry {
8
+ #adapter;
9
+ #tools;
10
+ #servers;
11
+ constructor(adapter, tools, servers) {
12
+ this.#adapter = adapter;
13
+ this.#tools = tools;
14
+ this.#servers = servers;
15
+ }
16
+ static async create(connections = loadMcpConnections()) {
17
+ if (Object.keys(connections).length === 0) {
18
+ return new McpToolRegistry(null, [], []);
19
+ }
20
+ const { adapter, tools } = await loadMcpTools(connections);
21
+ return new McpToolRegistry(adapter, tools, Object.keys(connections));
22
+ }
23
+ get tools() {
24
+ return this.#tools;
25
+ }
26
+ get serverNames() {
27
+ return [...this.#servers];
28
+ }
29
+ async close() {
30
+ await this.#adapter?.close();
31
+ }
32
+ }
@@ -0,0 +1 @@
1
+ export { createWebSearchTool, webSearchTool } from "./web-search.js";
@@ -0,0 +1,54 @@
1
+ import { tool } from "@langchain/core/tools";
2
+ import { z } from "zod";
3
+ const TAVILY_ENDPOINT = "https://api.tavily.com/search";
4
+ const webSearchSchema = z.object({
5
+ query: z.string().min(2).describe("搜索关键词。"),
6
+ maxResults: z.number().int().min(1).max(10).default(5).describe("返回结果数量(1-10)。"),
7
+ });
8
+ /**
9
+ * 基于 Tavily 的 Web 搜索。API Key 延迟读取,因此即使未配置搜索也能注册
10
+ * 该工具;真正调用时会返回清晰错误,供模型报告。
11
+ */
12
+ export const createWebSearchTool = ({ apiKey, maxResults: defaultMaxResults = 5 } = {}) => {
13
+ return tool(
14
+ async ({ query, maxResults }) => {
15
+ const key = apiKey ?? process.env.TAVILY_API_KEY;
16
+ if (!key) {
17
+ throw new Error("未设置 TAVILY_API_KEY。请在 .env 中添加后启用 Web 搜索。");
18
+ }
19
+ const response = await fetch(TAVILY_ENDPOINT, {
20
+ method: "POST",
21
+ headers: { "content-type": "application/json" },
22
+ body: JSON.stringify({
23
+ api_key: key,
24
+ query,
25
+ max_results: Math.min(maxResults ?? defaultMaxResults, 10),
26
+ search_depth: "basic",
27
+ include_answer: false,
28
+ include_raw_content: false,
29
+ }),
30
+ signal: AbortSignal.timeout(20_000),
31
+ });
32
+ if (!response.ok) {
33
+ const detail = await response.text().catch(() => "");
34
+ throw new Error(
35
+ `Web 搜索失败,HTTP ${response.status}${detail ? `:${detail.slice(0, 300)}` : ""}`,
36
+ );
37
+ }
38
+ const data = await response.json();
39
+ const results = (data.results ?? []).map((result) => ({
40
+ title: result.title ?? "",
41
+ url: result.url ?? "",
42
+ snippet: result.content ?? "",
43
+ score: result.score ?? 0,
44
+ }));
45
+ return JSON.stringify({ query, results }, null, 2);
46
+ },
47
+ {
48
+ name: "web_search",
49
+ description: "搜索公开网络,返回标题、URL 和摘要。用于获取最新信息,并引用实际使用的来源。",
50
+ schema: webSearchSchema,
51
+ },
52
+ );
53
+ };
54
+ export const webSearchTool = createWebSearchTool();
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 可以安全通过 HTTP API 暴露的错误基类。
3
+ * 非 AppError 的错误统一按 500 处理。
4
+ */
5
+ export class AppError extends Error {
6
+ status;
7
+ code;
8
+ details;
9
+ constructor(message, options = {}) {
10
+ super(message, { cause: options.cause });
11
+ this.name = new.target.name;
12
+ this.status = options.status ?? 500;
13
+ this.code = options.code ?? "INTERNAL_ERROR";
14
+ this.details = options.details;
15
+ }
16
+ toJSON() {
17
+ return {
18
+ error: {
19
+ code: this.code,
20
+ message: this.message,
21
+ ...(this.details ? { details: this.details } : {}),
22
+ },
23
+ };
24
+ }
25
+ }
26
+ export class ConfigurationError extends AppError {
27
+ constructor(message, details) {
28
+ super(message, { status: 500, code: "CONFIGURATION_ERROR", details });
29
+ }
30
+ }
31
+ export class ValidationError extends AppError {
32
+ constructor(message, details) {
33
+ super(message, { status: 400, code: "VALIDATION_ERROR", details });
34
+ }
35
+ }
36
+ export class UnauthorizedError extends AppError {
37
+ constructor(message = "缺少凭证或凭证无效。") {
38
+ super(message, { status: 401, code: "UNAUTHORIZED" });
39
+ }
40
+ }
41
+ export class NotFoundError extends AppError {
42
+ constructor(message = "资源不存在。") {
43
+ super(message, { status: 404, code: "NOT_FOUND" });
44
+ }
45
+ }
46
+ export class ConflictError extends AppError {
47
+ constructor(message = "资源冲突。") {
48
+ super(message, { status: 409, code: "CONFLICT" });
49
+ }
50
+ }
51
+ export const toErrorResponse = (error) => {
52
+ if (error instanceof AppError) {
53
+ return { status: error.status, body: error.toJSON() };
54
+ }
55
+ return {
56
+ status: 500,
57
+ body: {
58
+ error: {
59
+ code: "INTERNAL_ERROR",
60
+ message: error instanceof Error ? error.message : "发生了未预期的错误。",
61
+ },
62
+ },
63
+ };
64
+ };
@@ -0,0 +1,42 @@
1
+ export const isRecord = (value) => {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ };
4
+ export const sleep = (milliseconds) => {
5
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
6
+ };
7
+ export const truncate = (value, maxLength = 200) => {
8
+ if (value.length <= maxLength) return value;
9
+ return `${value.slice(0, Math.max(0, maxLength - 1))}…`;
10
+ };
11
+ export const parseJson = (value, fallback) => {
12
+ try {
13
+ return JSON.parse(value);
14
+ } catch {
15
+ return fallback;
16
+ }
17
+ };
18
+ /**
19
+ * 规范化 LangChain 的消息内容:可能是字符串,也可能是内容块数组
20
+ * (`{ type: "text", text: "..." }`)。
21
+ */
22
+ export const extractText = (content) => {
23
+ if (typeof content === "string") return content;
24
+ if (Array.isArray(content)) {
25
+ return content.map((block) => extractText(block)).join("");
26
+ }
27
+ if (isRecord(content) && typeof content.text === "string") {
28
+ return content.text;
29
+ }
30
+ return "";
31
+ };
32
+ export const lastMessageText = (messages) => {
33
+ const last = messages.at(-1);
34
+ if (!isRecord(last)) return "";
35
+ return extractText(last.content);
36
+ };
37
+ export const toIsoString = (value = new Date()) => {
38
+ return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
39
+ };
40
+ export const unique = (values) => {
41
+ return [...new Set(values)];
42
+ };
@@ -0,0 +1,24 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { loadPrompt, renderPrompt } from "../../src/agents/prompts/index.js";
4
+ test("从磁盘加载 Markdown 提示词", () => {
5
+ const prompt = loadPrompt("subagents/researcher");
6
+ assert.match(prompt, /researcher/);
7
+ assert.match(prompt, /研究/);
8
+ });
9
+ test("渲染 {{variable}} 占位符", () => {
10
+ assert.equal(
11
+ renderPrompt("你好 {{name}},欢迎来到{{place}}。", {
12
+ name: "Ada",
13
+ place: "工作区",
14
+ }),
15
+ "你好 Ada,欢迎来到工作区。",
16
+ );
17
+ });
18
+ test("占位符缺少值时抛错", () => {
19
+ assert.throws(() => renderPrompt("Hello {{name}}", {}), /缺少提示词变量 "name"/);
20
+ });
21
+ test("拒绝可能逃逸提示词目录的名称", () => {
22
+ assert.throws(() => loadPrompt("../secrets"), /非法的提示词名称/);
23
+ assert.throws(() => loadPrompt("subagents/../../secrets"), /非法的提示词名称/);
24
+ });