create-deepagent-server 0.0.0-stage → 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 (204) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +195 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +86 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +181 -0
  11. package/src/setup.js +79 -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 +97 -0
  17. package/templates/deepagent/js/scripts/dev.js +40 -0
  18. package/templates/deepagent/js/src/agents/factory.js +11 -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 +53 -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/supervisor.js +21 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.md +41 -0
  26. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  27. package/templates/deepagent/js/src/agents/state/types.js +11 -0
  28. package/templates/deepagent/js/src/agents/subagents/analyst.js +12 -0
  29. package/templates/deepagent/js/src/agents/subagents/coder.js +12 -0
  30. package/templates/deepagent/js/src/agents/subagents/index.js +9 -0
  31. package/templates/deepagent/js/src/agents/supervisor.js +64 -0
  32. package/templates/deepagent/js/src/api/app.js +29 -0
  33. package/templates/deepagent/js/src/api/middleware/auth.js +36 -0
  34. package/templates/deepagent/js/src/api/middleware/error.js +30 -0
  35. package/templates/deepagent/js/src/api/routes/agent.js +43 -0
  36. package/templates/deepagent/js/src/api/routes/health.js +40 -0
  37. package/templates/deepagent/js/src/api/routes/session.js +42 -0
  38. package/templates/deepagent/js/src/app.js +98 -0
  39. package/templates/deepagent/js/src/backends/composite.js +22 -0
  40. package/templates/deepagent/js/src/backends/filesystem.js +9 -0
  41. package/templates/deepagent/js/src/backends/index.js +60 -0
  42. package/templates/deepagent/js/src/backends/sandbox.js +26 -0
  43. package/templates/deepagent/js/src/config/agent.js +14 -0
  44. package/templates/deepagent/js/src/config/database.js +19 -0
  45. package/templates/deepagent/js/src/config/env.js +96 -0
  46. package/templates/deepagent/js/src/config/index.js +45 -0
  47. package/templates/deepagent/js/src/graph/checkpointer.js +28 -0
  48. package/templates/deepagent/js/src/graph/compile.js +9 -0
  49. package/templates/deepagent/js/src/graph/index.js +3 -0
  50. package/templates/deepagent/js/src/graph/store.js +28 -0
  51. package/templates/deepagent/js/src/index.js +39 -0
  52. package/templates/deepagent/js/src/memory/index.js +8 -0
  53. package/templates/deepagent/js/src/memory/manager.js +50 -0
  54. package/templates/deepagent/js/src/memory/store.js +43 -0
  55. package/templates/deepagent/js/src/middleware/approval.js +47 -0
  56. package/templates/deepagent/js/src/middleware/context.js +35 -0
  57. package/templates/deepagent/js/src/middleware/index.js +9 -0
  58. package/templates/deepagent/js/src/middleware/logging.js +70 -0
  59. package/templates/deepagent/js/src/middleware/security.js +58 -0
  60. package/templates/deepagent/js/src/model/config.js +38 -0
  61. package/templates/deepagent/js/src/model/index.js +9 -0
  62. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  63. package/templates/deepagent/js/src/model/presets.js +71 -0
  64. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  65. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  66. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  67. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  68. package/templates/deepagent/js/src/schemas/agent.js +40 -0
  69. package/templates/deepagent/js/src/schemas/common.js +24 -0
  70. package/templates/deepagent/js/src/schemas/locale.js +4 -0
  71. package/templates/deepagent/js/src/schemas/session.js +27 -0
  72. package/templates/deepagent/js/src/services/agent.js +136 -0
  73. package/templates/deepagent/js/src/services/memory.js +33 -0
  74. package/templates/deepagent/js/src/services/session.js +118 -0
  75. package/templates/deepagent/js/src/skills/index.js +21 -0
  76. package/templates/deepagent/js/src/skills/loader.js +75 -0
  77. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  78. package/templates/deepagent/js/src/storage/database/migrations/001_init.sql +20 -0
  79. package/templates/deepagent/js/src/storage/logger/index.js +21 -0
  80. package/templates/deepagent/js/src/storage/redis/client.js +51 -0
  81. package/templates/deepagent/js/src/storage/shutdown/index.js +58 -0
  82. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  83. package/templates/deepagent/js/src/tools/database/query.js +74 -0
  84. package/templates/deepagent/js/src/tools/filesystem/index.js +102 -0
  85. package/templates/deepagent/js/src/tools/index.js +25 -0
  86. package/templates/deepagent/js/src/tools/mcp/client.js +42 -0
  87. package/templates/deepagent/js/src/tools/mcp/connections.js +64 -0
  88. package/templates/deepagent/js/src/tools/mcp/index.js +10 -0
  89. package/templates/deepagent/js/src/tools/mcp/registry.js +36 -0
  90. package/templates/deepagent/js/src/utils/errors.js +73 -0
  91. package/templates/deepagent/js/src/utils/helpers.js +57 -0
  92. package/templates/deepagent/js/src/utils/validation.js +15 -0
  93. package/templates/deepagent/js/tests/agents/prompts.test.js +30 -0
  94. package/templates/deepagent/js/tests/agents/supervisor.test.js +42 -0
  95. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  96. package/templates/deepagent/js/tests/integration/api.test.js +114 -0
  97. package/templates/deepagent/js/tests/middleware/security.test.js +27 -0
  98. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  99. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  100. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  101. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  102. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  103. package/templates/deepagent/js/tests/tools/query.test.js +27 -0
  104. package/templates/deepagent/shared/README.md +249 -0
  105. package/templates/deepagent/shared/_editorconfig +12 -0
  106. package/templates/deepagent/shared/_env.example +86 -0
  107. package/templates/deepagent/shared/_gitignore +22 -0
  108. package/templates/deepagent/shared/deployment/docker-compose.yml +60 -0
  109. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  110. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  111. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  112. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  113. package/templates/deepagent/shared/workspaces/README.md +5 -0
  114. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  115. package/templates/deepagent/ts/scripts/check.ts +99 -0
  116. package/templates/deepagent/ts/scripts/copy-assets.ts +37 -0
  117. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  118. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  119. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  120. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  121. package/templates/deepagent/ts/src/agents/prompts/loader.ts +53 -0
  122. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  123. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  124. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +41 -0
  125. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  126. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  127. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  128. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +18 -0
  129. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  130. package/templates/deepagent/ts/src/agents/subagents/index.ts +9 -0
  131. package/templates/deepagent/ts/src/agents/supervisor.ts +82 -0
  132. package/templates/deepagent/ts/src/api/app.ts +48 -0
  133. package/templates/deepagent/ts/src/api/middleware/auth.ts +38 -0
  134. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  135. package/templates/deepagent/ts/src/api/routes/agent.ts +48 -0
  136. package/templates/deepagent/ts/src/api/routes/health.ts +47 -0
  137. package/templates/deepagent/ts/src/api/routes/session.ts +47 -0
  138. package/templates/deepagent/ts/src/app.ts +111 -0
  139. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  140. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  141. package/templates/deepagent/ts/src/backends/index.ts +76 -0
  142. package/templates/deepagent/ts/src/backends/sandbox.ts +33 -0
  143. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  144. package/templates/deepagent/ts/src/config/database.ts +21 -0
  145. package/templates/deepagent/ts/src/config/env.ts +106 -0
  146. package/templates/deepagent/ts/src/config/index.ts +84 -0
  147. package/templates/deepagent/ts/src/graph/checkpointer.ts +29 -0
  148. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  149. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  150. package/templates/deepagent/ts/src/graph/store.ts +29 -0
  151. package/templates/deepagent/ts/src/index.ts +39 -0
  152. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  153. package/templates/deepagent/ts/src/memory/manager.ts +76 -0
  154. package/templates/deepagent/ts/src/memory/store.ts +59 -0
  155. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  156. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  157. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  158. package/templates/deepagent/ts/src/middleware/logging.ts +71 -0
  159. package/templates/deepagent/ts/src/middleware/security.ts +61 -0
  160. package/templates/deepagent/ts/src/model/config.ts +56 -0
  161. package/templates/deepagent/ts/src/model/index.ts +14 -0
  162. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  163. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  164. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  165. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  166. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  167. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  168. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  169. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  170. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  171. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  172. package/templates/deepagent/ts/src/services/agent.ts +170 -0
  173. package/templates/deepagent/ts/src/services/memory.ts +43 -0
  174. package/templates/deepagent/ts/src/services/session.ts +158 -0
  175. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  176. package/templates/deepagent/ts/src/skills/loader.ts +90 -0
  177. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  178. package/templates/deepagent/ts/src/storage/database/migrations/001_init.sql +20 -0
  179. package/templates/deepagent/ts/src/storage/logger/index.ts +25 -0
  180. package/templates/deepagent/ts/src/storage/redis/client.ts +57 -0
  181. package/templates/deepagent/ts/src/storage/shutdown/index.ts +82 -0
  182. package/templates/deepagent/ts/src/tools/database/index.ts +5 -0
  183. package/templates/deepagent/ts/src/tools/database/query.ts +79 -0
  184. package/templates/deepagent/ts/src/tools/filesystem/index.ts +110 -0
  185. package/templates/deepagent/ts/src/tools/index.ts +43 -0
  186. package/templates/deepagent/ts/src/tools/mcp/client.ts +54 -0
  187. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  188. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  189. package/templates/deepagent/ts/src/tools/mcp/registry.ts +45 -0
  190. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  191. package/templates/deepagent/ts/src/utils/helpers.ts +57 -0
  192. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  193. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  194. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  195. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  196. package/templates/deepagent/ts/tests/integration/api.test.ts +122 -0
  197. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  198. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  199. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  200. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  201. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  202. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  203. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  204. package/templates/deepagent/ts/tsconfig.json +19 -0
@@ -0,0 +1,36 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+
3
+ import { UnauthorizedError } from "../../utils/errors.js";
4
+
5
+ const BEARER_PREFIX = "Bearer ";
6
+
7
+ const safeEqual = (provided, expected) => {
8
+ const actual = Buffer.from(provided);
9
+ const target = Buffer.from(expected);
10
+
11
+ if (actual.length !== target.length) return false;
12
+
13
+ return timingSafeEqual(actual, target);
14
+ };
15
+
16
+ /**
17
+ * 可选的 Bearer Token 鉴权。未设置 AGENT_API_KEY 时 API 完全开放
18
+ * (适合本地开发,切勿用于公网部署)。
19
+ */
20
+ export const createAuthMiddleware = (apiKey) => {
21
+ if (!apiKey) {
22
+ return (_req, _res, next) => next();
23
+ }
24
+
25
+ return (req, _res, next) => {
26
+ const header = req.header("authorization") ?? "";
27
+ const token = header.startsWith(BEARER_PREFIX) ? header.slice(BEARER_PREFIX.length).trim() : "";
28
+
29
+ if (!token || !safeEqual(token, apiKey)) {
30
+ next(new UnauthorizedError());
31
+ return;
32
+ }
33
+
34
+ next();
35
+ };
36
+ };
@@ -0,0 +1,30 @@
1
+ import { NotFoundError, toErrorResponse } from "../../utils/errors.js";
2
+
3
+ export const notFoundHandler = (req, _res, next) => {
4
+ next(new NotFoundError(`未找到路由 ${req.method} ${req.path}。`));
5
+ };
6
+
7
+ export const createErrorHandler = (logger) => {
8
+ return (error, req, res, _next) => {
9
+ const { status, body } = toErrorResponse(error);
10
+
11
+ if (status >= 500) {
12
+ logger.error(
13
+ {
14
+ method: req.method,
15
+ path: req.path,
16
+ status,
17
+ error: error instanceof Error ? error.stack : String(error),
18
+ },
19
+ "请求处理失败",
20
+ );
21
+ } else {
22
+ logger.warn(
23
+ { method: req.method, path: req.path, status, code: body.error.code },
24
+ "请求被拒绝",
25
+ );
26
+ }
27
+
28
+ res.status(status).json(body);
29
+ };
30
+ };
@@ -0,0 +1,43 @@
1
+ import { Router } from "express";
2
+
3
+ import { invokeAgentSchema, resumeAgentSchema } from "../../schemas/agent.js";
4
+ import { errorMessage } from "../../utils/helpers.js";
5
+ import { parseRequest } from "../../utils/validation.js";
6
+
7
+ export const createAgentRouter = ({ agent }) => {
8
+ const router = Router();
9
+
10
+ // Express 5 会把 async handler 的拒绝交给错误中间件,这里不需要再包 try/catch。
11
+ router.post("/invoke", async (req, res) => {
12
+ res.json(await agent.invoke(parseRequest(invokeAgentSchema, req.body)));
13
+ });
14
+
15
+ router.post("/resume", async (req, res) => {
16
+ res.json(await agent.resume(parseRequest(resumeAgentSchema, req.body)));
17
+ });
18
+
19
+ router.post("/stream", async (req, res) => {
20
+ const input = parseRequest(invokeAgentSchema, req.body);
21
+ const controller = new AbortController();
22
+ req.on("close", () => controller.abort());
23
+
24
+ res.status(200);
25
+ res.setHeader("Content-Type", "text/event-stream");
26
+ res.setHeader("Cache-Control", "no-cache, no-transform");
27
+ res.setHeader("Connection", "keep-alive");
28
+ res.flushHeaders();
29
+
30
+ try {
31
+ for await (const event of agent.stream(input, { signal: controller.signal })) {
32
+ res.write(`event: ${event.event}\ndata: ${JSON.stringify(event.data)}\n\n`);
33
+ }
34
+ res.write("event: done\ndata: {}\n\n");
35
+ } catch (error) {
36
+ res.write(`event: error\ndata: ${JSON.stringify({ message: errorMessage(error) })}\n\n`);
37
+ } finally {
38
+ res.end();
39
+ }
40
+ });
41
+
42
+ return router;
43
+ };
@@ -0,0 +1,40 @@
1
+ import { Router } from "express";
2
+
3
+ import { checkDatabase } from "../../storage/database/client.js";
4
+ import { checkRedis } from "../../storage/redis/client.js";
5
+
6
+ export const createHealthRouter = ({ config, mcp }) => {
7
+ const router = Router();
8
+
9
+ router.get("/", (_req, res) => {
10
+ res.json({
11
+ status: "ok",
12
+ service: "deepagent",
13
+ agent: config.agent.name,
14
+ model: `${config.model.provider}/${config.model.name}`,
15
+ uptimeSeconds: Math.round(process.uptime()),
16
+ });
17
+ });
18
+
19
+ router.get("/ready", async (_req, res) => {
20
+ const [database, redis] = await Promise.all([
21
+ config.database.url
22
+ ? checkDatabase(config.database.url)
23
+ : Promise.resolve({ ok: true, skipped: true }),
24
+ config.redis.url ? checkRedis() : Promise.resolve({ ok: true, skipped: true }),
25
+ ]);
26
+
27
+ const ready = (!config.database.url || database.ok) && (!config.redis.url || redis.ok);
28
+
29
+ res.status(ready ? 200 : 503).json({
30
+ status: ready ? "ready" : "degraded",
31
+ checks: {
32
+ database,
33
+ redis,
34
+ mcp: { servers: mcp?.serverNames ?? [] },
35
+ },
36
+ });
37
+ });
38
+
39
+ return router;
40
+ };
@@ -0,0 +1,42 @@
1
+ import { Router } from "express";
2
+
3
+ import { createSessionSchema } from "../../schemas/session.js";
4
+ import { parseRequest } from "../../utils/validation.js";
5
+
6
+ const tenantFrom = (value) => {
7
+ return typeof value === "string" && value.length > 0 ? value : "default";
8
+ };
9
+
10
+ const limitFrom = (value) => {
11
+ const limit = Number(value ?? 20);
12
+ return Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20;
13
+ };
14
+
15
+ export const createSessionRouter = ({ sessions }) => {
16
+ const router = Router();
17
+
18
+ router.post("/", async (req, res) => {
19
+ const session = await sessions.create(parseRequest(createSessionSchema, req.body ?? {}));
20
+ res.status(201).json(session);
21
+ });
22
+
23
+ router.get("/", async (req, res) => {
24
+ const result = await sessions.list(tenantFrom(req.query.tenantId), limitFrom(req.query.limit));
25
+ res.json(result);
26
+ });
27
+
28
+ router.get("/:threadId", async (req, res) => {
29
+ res.json(await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId)));
30
+ });
31
+
32
+ router.get("/:threadId/messages", async (req, res) => {
33
+ res.json({ messages: await sessions.history(req.params.threadId) });
34
+ });
35
+
36
+ router.delete("/:threadId", async (req, res) => {
37
+ await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
38
+ res.status(204).end();
39
+ });
40
+
41
+ return router;
42
+ };
@@ -0,0 +1,98 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ import { createSupervisorAgent } from "./agents/index.js";
4
+ import { createApiApp } from "./api/app.js";
5
+ import { createBackend } from "./backends/index.js";
6
+ import { loadConfig } from "./config/index.js";
7
+ import { createCheckpointer, createStore } from "./graph/index.js";
8
+ import { closeDatabase } from "./storage/database/client.js";
9
+ import { createLogger } from "./storage/logger/index.js";
10
+ import { closeRedis } from "./storage/redis/client.js";
11
+ import { createMemoryManager } from "./memory/index.js";
12
+ import { createChatModel } from "./model/index.js";
13
+ import { AgentService } from "./services/agent.js";
14
+ import { MemoryService } from "./services/memory.js";
15
+ import { SessionService } from "./services/session.js";
16
+ import { loadSkills, validateSkills } from "./skills/index.js";
17
+ import { createDefaultTools } from "./tools/index.js";
18
+ import { createMcpToolRegistry } from "./tools/index.js";
19
+
20
+ /**
21
+ * 应用装配:配置 → 基础设施 → Agent 运行时 → 服务 → HTTP 应用。
22
+ * 这里不启动服务,因此测试、脚本和 HTTP 入口可以复用同一套装配。
23
+ */
24
+ export const createApplication = async (config = loadConfig()) => {
25
+ const logger = createLogger(config);
26
+
27
+ await fs.mkdir(config.paths.workspaces, { recursive: true });
28
+ await fs.mkdir(config.paths.resources, { recursive: true });
29
+
30
+ const skills = await loadSkills({ rootDir: config.paths.skills });
31
+ for (const warning of validateSkills(skills)) {
32
+ logger.warn(warning);
33
+ }
34
+
35
+ logger.info({ skills: skills.map((skill) => skill.name) }, "技能加载完成");
36
+
37
+ const store = await createStore(config);
38
+ const checkpointer = await createCheckpointer(config);
39
+ const backend = await createBackend(config);
40
+ const mcp = await createMcpToolRegistry();
41
+
42
+ const tools = createDefaultTools({
43
+ workspaceRoot: config.paths.workspaces,
44
+ databaseUrl: config.database.url,
45
+ additionalTools: mcp.tools,
46
+ });
47
+
48
+ const agent = createSupervisorAgent({
49
+ config,
50
+ model: createChatModel(config.model),
51
+ backend: backend.backend,
52
+ checkpointer,
53
+ store,
54
+ logger,
55
+ tools,
56
+ });
57
+
58
+ const sessions = new SessionService({
59
+ graph: agent,
60
+ checkpointer,
61
+ store,
62
+ sandboxes: backend.sandboxes,
63
+ });
64
+ const agentService = new AgentService({ agent, config, sessions });
65
+ const memoryService = new MemoryService(createMemoryManager(store));
66
+
67
+ const app = createApiApp({
68
+ config,
69
+ logger,
70
+ mcp,
71
+ services: {
72
+ agent: agentService,
73
+ sessions,
74
+ memory: memoryService,
75
+ },
76
+ });
77
+
78
+ let closed = false;
79
+
80
+ return {
81
+ app,
82
+ logger,
83
+ services: {
84
+ agent: agentService,
85
+ sessions,
86
+ memory: memoryService,
87
+ },
88
+ close: async () => {
89
+ if (closed) return;
90
+ closed = true;
91
+
92
+ await mcp.close();
93
+ await backend.dispose();
94
+ await closeDatabase();
95
+ await closeRedis();
96
+ },
97
+ };
98
+ };
@@ -0,0 +1,22 @@
1
+ import { CompositeBackend, StateBackend, StoreBackend } from "deepagents";
2
+
3
+ import { createFilesystemBackend } from "./filesystem.js";
4
+
5
+ /**
6
+ * 把 Agent 需要的所有资源挂载到同一个虚拟文件系统:
7
+ *
8
+ * /workspace/ 草稿与产物(落磁盘)
9
+ * /resources/ AGENTS.md 与只读知识库(落磁盘)
10
+ * /skills/ SKILL.md 目录(落磁盘)
11
+ * /memories/ 长期记忆(LangGraph BaseStore)
12
+ *
13
+ * 其余路径落到默认后端(默认是临时状态)。
14
+ */
15
+ export const createCompositeBackend = ({ defaultBackend = new StateBackend(), paths }) => {
16
+ return new CompositeBackend(defaultBackend, {
17
+ "/workspace/": createFilesystemBackend({ rootDir: paths.workspaces }),
18
+ "/resources/": createFilesystemBackend({ rootDir: paths.resources }),
19
+ "/skills/": createFilesystemBackend({ rootDir: paths.skills }),
20
+ "/memories/": new StoreBackend(),
21
+ });
22
+ };
@@ -0,0 +1,9 @@
1
+ import { FilesystemBackend } from "deepagents";
2
+
3
+ /**
4
+ * 虚拟路径被限制在 `rootDir` 内的文件系统后端。
5
+ * Agent 看到的是 `/notes.md`,实际文件位于 `<rootDir>/notes.md`。
6
+ */
7
+ export const createFilesystemBackend = ({ rootDir, virtualMode = true, maxFileSizeMb = 10 }) => {
8
+ return new FilesystemBackend({ rootDir, virtualMode, maxFileSizeMb });
9
+ };
@@ -0,0 +1,60 @@
1
+ import { StateBackend } from "deepagents";
2
+
3
+ import { SandboxManager, threadIdFromRuntime } from "../sandbox/index.js";
4
+ import { createCompositeBackend } from "./composite.js";
5
+ import { createSandboxBackend } from "./sandbox.js";
6
+
7
+ /**
8
+ * 构建主 Agent 和所有子 Agent 共用的后端。
9
+ *
10
+ * `SANDBOX_ENABLED=true` 时返回一个工厂:按 `threadId` 为每个会话惰性创建并复用
11
+ * 一个 OpenSandbox 沙箱(`/workspace/` 与 `execute` 落在沙箱内),
12
+ * `/resources/`、`/skills/` 仍读本地只读文件,`/memories/` 继续使用 LangGraph store。
13
+ * 未开启时回退到本地文件系统后端,`ENABLE_SHELL=true` 时再挂上宿主机 shell。
14
+ */
15
+ export const createBackend = async (config) => {
16
+ if (config.sandbox.enabled) {
17
+ const sandboxes = new SandboxManager(config.sandbox);
18
+
19
+ // memory / skills 中间件解析 backend 时只带 state、没有 threadId;
20
+ // 它们只读 /resources 和 /skills,回退到本地只读后端即可。
21
+ const fallback = createCompositeBackend({
22
+ defaultBackend: new StateBackend(),
23
+ paths: {
24
+ workspaces: config.paths.workspaces,
25
+ resources: config.paths.resources,
26
+ skills: config.paths.skills,
27
+ },
28
+ });
29
+
30
+ const backend = (runtime) => {
31
+ const threadId = threadIdFromRuntime(runtime);
32
+ return threadId ? sandboxes.get(threadId) : fallback;
33
+ };
34
+
35
+ return { backend, sandboxes, dispose: () => sandboxes.closeAll() };
36
+ }
37
+
38
+ const rootDir = config.paths.workspaces;
39
+ const shell = config.agent.enableShell ? await createSandboxBackend({ rootDir }) : null;
40
+
41
+ const backend = createCompositeBackend({
42
+ ...(shell ? { defaultBackend: shell } : {}),
43
+ paths: {
44
+ workspaces: config.paths.workspaces,
45
+ resources: config.paths.resources,
46
+ skills: config.paths.skills,
47
+ },
48
+ });
49
+
50
+ return {
51
+ backend,
52
+ dispose: async () => {
53
+ await shell?.close();
54
+ },
55
+ };
56
+ };
57
+
58
+ export { createCompositeBackend } from "./composite.js";
59
+ export { createFilesystemBackend } from "./filesystem.js";
60
+ export { createSandboxBackend } from "./sandbox.js";
@@ -0,0 +1,26 @@
1
+ import { LocalShellBackend } from "deepagents";
2
+
3
+ /**
4
+ * 本地 shell 后端。在文件系统工具之上增加 `execute` 工具,
5
+ * 命令会以当前进程的权限在宿主机执行。
6
+ *
7
+ * 生产环境请保持 ENABLE_SHELL=false,或替换为真正的沙箱
8
+ * (LangSmithSandbox、容器、远程执行器等)。
9
+ */
10
+ export const createSandboxBackend = async ({
11
+ rootDir,
12
+ virtualMode = true,
13
+ timeoutSeconds = 60,
14
+ maxOutputBytes = 100_000,
15
+ }) => {
16
+ const backend = new LocalShellBackend({
17
+ rootDir,
18
+ virtualMode,
19
+ timeout: timeoutSeconds,
20
+ maxOutputBytes,
21
+ });
22
+
23
+ await backend.initialize();
24
+
25
+ return backend;
26
+ };
@@ -0,0 +1,14 @@
1
+ export const DEFAULT_AGENT_DESCRIPTION =
2
+ "负责规划任务、把工作分派给专职子 Agent,并维护工作区文件的主 Agent。";
3
+
4
+ export const resolveAgentConfig = (env) => {
5
+ return {
6
+ name: env.AGENT_NAME,
7
+ description: DEFAULT_AGENT_DESCRIPTION,
8
+ recursionLimit: env.AGENT_RECURSION_LIMIT,
9
+ approvals: env.APPROVAL_MODE,
10
+ enableShell: env.ENABLE_SHELL,
11
+ memoryFiles: ["/resources/AGENTS.md"],
12
+ skillDirectories: ["/skills/"],
13
+ };
14
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * 解析 PostgreSQL 连接串。
3
+ *
4
+ * - `DATABASE_URL` 优先,适合托管数据库或需要额外连接参数的场景;
5
+ * - 否则在 `CHECKPOINTER` 或 `STORE` 使用 postgres 时,用 `POSTGRES_*` 分项拼装;
6
+ * - 内存模式下返回 `undefined`,避免误连数据库。
7
+ */
8
+ export const resolveDatabaseUrl = (env) => {
9
+ if (env.DATABASE_URL) return env.DATABASE_URL;
10
+
11
+ const postgresEnabled = env.CHECKPOINTER === "postgres" || env.STORE === "postgres";
12
+ if (!postgresEnabled) return undefined;
13
+
14
+ const username = encodeURIComponent(env.POSTGRES_USERNAME);
15
+ const password = env.POSTGRES_PASSWORD ? `:${encodeURIComponent(env.POSTGRES_PASSWORD)}` : "";
16
+ const database = encodeURIComponent(env.POSTGRES_DATABASE);
17
+
18
+ return `postgresql://${username}${password}@${env.POSTGRES_HOST}:${env.POSTGRES_PORT}/${database}`;
19
+ };
@@ -0,0 +1,96 @@
1
+ import "../schemas/locale.js";
2
+
3
+ import { z } from "zod";
4
+
5
+ import { MODEL_PROVIDERS } from "../model/index.js";
6
+ import { ConfigurationError } from "../utils/errors.js";
7
+
8
+ const booleanFlag = z
9
+ .union([z.boolean(), z.string()])
10
+ .default("false")
11
+ .transform((value) =>
12
+ typeof value === "boolean" ? value : ["1", "true", "yes", "on"].includes(value.toLowerCase()),
13
+ );
14
+
15
+ const optionalString = z
16
+ .string()
17
+ .trim()
18
+ .optional()
19
+ .transform((value) => (value === "" ? undefined : value));
20
+
21
+ export const envSchema = z.object({
22
+ NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
23
+ HOST: z.string().default("0.0.0.0"),
24
+ PORT: z.coerce.number().int().min(1).max(65535).default(3000),
25
+ LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
26
+
27
+ // 模型统一通过 OpenAI 兼容协议接入,服务商预设见 src/model/presets。
28
+ MODEL_PROVIDER: z.enum(MODEL_PROVIDERS).default("minimax"),
29
+ MODEL_NAME: optionalString,
30
+ MODEL_BASE_URL: optionalString,
31
+ MODEL_API_KEY: optionalString,
32
+ MODEL_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.2),
33
+ // 生成上限(含思考 token);M3 最高 128K。MODEL_MAX_TOKENS 为旧变量,仍兼容。
34
+ MODEL_MAX_COMPLETION_TOKENS: z.coerce.number().int().positive().optional(),
35
+ MODEL_MAX_TOKENS: z.coerce.number().int().positive().optional(),
36
+
37
+ AGENT_NAME: z.string().default("deepagent"),
38
+ AGENT_API_KEY: optionalString,
39
+ AGENT_RECURSION_LIMIT: z.coerce.number().int().min(1).max(1000).default(50),
40
+ APPROVAL_MODE: z.enum(["none", "sensitive", "all"]).default("sensitive"),
41
+ ENABLE_SHELL: booleanFlag,
42
+ WORKSPACE_ROOT: z.string().default("workspaces"),
43
+ RESOURCES_ROOT: z.string().default("resources"),
44
+ SKILLS_ROOT: z.string().default("skills"),
45
+
46
+ // OpenSandbox:SANDBOX_ENABLED=true 时按会话(threadId)惰性创建并复用远程沙箱。
47
+ SANDBOX_ENABLED: booleanFlag,
48
+ OPEN_SANDBOX_DOMAIN: z.string().min(1).default("localhost:8080"),
49
+ OPEN_SANDBOX_PROTOCOL: z.enum(["http", "https"]).default("http"),
50
+ OPEN_SANDBOX_API_KEY: optionalString,
51
+ OPEN_SANDBOX_ID: optionalString,
52
+ SANDBOX_IMAGE: z.string().min(1).default("python:3.12"),
53
+ // 沙箱 TTL(秒):使用中按 TTL/3 自动续期,空闲到期后由服务端回收;0 表示不设置 TTL。
54
+ SANDBOX_TIMEOUT_SECONDS: z.coerce.number().int().min(0).default(1800),
55
+ SANDBOX_WORKSPACE_ROOT: z.string().min(1).default("/workspace"),
56
+
57
+ CHECKPOINTER: z.enum(["memory", "postgres"]).default("memory"),
58
+ STORE: z.enum(["memory", "postgres"]).default("memory"),
59
+
60
+ // PostgreSQL:CHECKPOINTER/STORE 为 postgres 时由分项拼装连接串,DATABASE_URL 优先。
61
+ DATABASE_URL: optionalString,
62
+ POSTGRES_HOST: z.string().min(1).default("localhost"),
63
+ POSTGRES_PORT: z.coerce.number().int().min(1).max(65535).default(5432),
64
+ POSTGRES_USERNAME: z.string().min(1).default("postgres"),
65
+ POSTGRES_PASSWORD: z.string().default("postgres"),
66
+ POSTGRES_DATABASE: z.string().min(1).default("deepagent"),
67
+
68
+ REDIS_URL: optionalString,
69
+
70
+ LANGSMITH_TRACING: booleanFlag,
71
+ LANGSMITH_API_KEY: optionalString,
72
+ LANGSMITH_PROJECT: z.string().default("deepagent"),
73
+
74
+ MCP_SERVERS: optionalString,
75
+ });
76
+
77
+ export const loadEnv = (source = process.env, { requireModelCredentials = true } = {}) => {
78
+ const parsed = envSchema.safeParse(source);
79
+
80
+ if (!parsed.success) {
81
+ const issues = parsed.error.issues
82
+ .map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`)
83
+ .join("; ");
84
+ throw new ConfigurationError(`环境变量配置无效:${issues}`);
85
+ }
86
+
87
+ const env = parsed.data;
88
+
89
+ if (requireModelCredentials && env.NODE_ENV !== "test" && !env.MODEL_API_KEY) {
90
+ throw new ConfigurationError(
91
+ "必须设置 MODEL_API_KEY(可复制 .env.example 为 .env);本地 OpenAI 兼容服务可填任意非空值。",
92
+ );
93
+ }
94
+
95
+ return env;
96
+ };
@@ -0,0 +1,45 @@
1
+ import path from "node:path";
2
+
3
+ import { resolveModelConfig } from "../model/index.js";
4
+
5
+ import { resolveSandboxConfig } from "../sandbox/config.js";
6
+
7
+ import { resolveAgentConfig } from "./agent.js";
8
+ import { resolveDatabaseUrl } from "./database.js";
9
+ import { loadEnv } from "./env.js";
10
+
11
+ export { loadEnv } from "./env.js";
12
+
13
+ /**
14
+ * 把环境变量转换为带类型、使用绝对路径的应用配置,全局只在这里处理。
15
+ */
16
+ export const loadConfig = (options = {}) => {
17
+ const root = path.resolve(options.cwd ?? process.cwd());
18
+ const env =
19
+ options.env ??
20
+ loadEnv(process.env, {
21
+ requireModelCredentials: options.requireModelCredentials ?? true,
22
+ });
23
+
24
+ const databaseUrl = resolveDatabaseUrl(env);
25
+
26
+ return {
27
+ env,
28
+ server: { host: env.HOST, port: env.PORT },
29
+ paths: {
30
+ root,
31
+ workspaces: path.resolve(root, env.WORKSPACE_ROOT),
32
+ resources: path.resolve(root, env.RESOURCES_ROOT),
33
+ skills: path.resolve(root, env.SKILLS_ROOT),
34
+ },
35
+ model: resolveModelConfig(env),
36
+ agent: resolveAgentConfig(env),
37
+ sandbox: resolveSandboxConfig(env),
38
+ database: { ...(databaseUrl ? { url: databaseUrl } : {}) },
39
+ redis: { ...(env.REDIS_URL ? { url: env.REDIS_URL } : {}) },
40
+ logging: {
41
+ level: env.LOG_LEVEL,
42
+ pretty: env.NODE_ENV === "development",
43
+ },
44
+ };
45
+ };
@@ -0,0 +1,28 @@
1
+ import { MemorySaver } from "@langchain/langgraph";
2
+
3
+ import { ConfigurationError } from "../utils/errors.js";
4
+
5
+ /**
6
+ * Checkpointer 以 `thread_id` 为单位持久化会话状态。
7
+ *
8
+ * - memory:进程内存,零配置(默认)
9
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 checkpoint 表
10
+ */
11
+ export const createCheckpointer = async (config) => {
12
+ if (config.env.CHECKPOINTER !== "postgres") {
13
+ return new MemorySaver();
14
+ }
15
+
16
+ if (!config.database.url) {
17
+ throw new ConfigurationError(
18
+ "CHECKPOINTER=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
19
+ );
20
+ }
21
+
22
+ const { PostgresSaver } = await import("@langchain/langgraph-checkpoint-postgres");
23
+
24
+ const saver = PostgresSaver.fromConnString(config.database.url);
25
+ await saver.setup();
26
+
27
+ return saver;
28
+ };
@@ -0,0 +1,9 @@
1
+ import { createDeepAgent } from "deepagents";
2
+
3
+ /**
4
+ * 唯一调用 `createDeepAgent` 的地方。集中在这里便于替换运行时
5
+ * (例如用自定义 `StateGraph` 包裹 Agent)。
6
+ */
7
+ export const compileAgentGraph = (options) => {
8
+ return createDeepAgent(options);
9
+ };
@@ -0,0 +1,3 @@
1
+ export { compileAgentGraph } from "./compile.js";
2
+ export { createCheckpointer } from "./checkpointer.js";
3
+ export { createStore } from "./store.js";
@@ -0,0 +1,28 @@
1
+ import { InMemoryStore } from "@langchain/langgraph";
2
+
3
+ import { ConfigurationError } from "../utils/errors.js";
4
+
5
+ /**
6
+ * Store 用于长期记忆和 `/memories/` 后端挂载。
7
+ *
8
+ * - memory:进程内存(默认)
9
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 store 表
10
+ */
11
+ export const createStore = async (config) => {
12
+ if (config.env.STORE !== "postgres") {
13
+ return new InMemoryStore();
14
+ }
15
+
16
+ if (!config.database.url) {
17
+ throw new ConfigurationError(
18
+ "STORE=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
19
+ );
20
+ }
21
+
22
+ const { PostgresStore } = await import("@langchain/langgraph-checkpoint-postgres/store");
23
+
24
+ const store = PostgresStore.fromConnString(config.database.url);
25
+ await store.setup();
26
+
27
+ return store;
28
+ };