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
@@ -1,22 +1,29 @@
1
1
  import express from "express";
2
+
2
3
  import { createAuthMiddleware } from "./middleware/auth.js";
3
4
  import { createErrorHandler, notFoundHandler } from "./middleware/error.js";
4
5
  import { createAgentRouter } from "./routes/agent.js";
5
6
  import { createHealthRouter } from "./routes/health.js";
6
7
  import { createSessionRouter } from "./routes/session.js";
8
+
7
9
  /**
8
10
  * Agent API 的 Express 应用。健康检查保持公开;
9
11
  * 配置 AGENT_API_KEY 后,/api 下的接口需要携带 Bearer Token。
10
12
  */
11
13
  export const createApiApp = ({ config, logger, services, mcp }) => {
12
14
  const app = express();
15
+
13
16
  app.disable("x-powered-by");
14
17
  app.use(express.json({ limit: "2mb" }));
18
+
15
19
  app.use("/health", createHealthRouter({ config, ...(mcp ? { mcp } : {}) }));
20
+
16
21
  app.use(createAuthMiddleware(config.env.AGENT_API_KEY));
17
22
  app.use("/api/agents", createAgentRouter({ agent: services.agent }));
18
23
  app.use("/api/sessions", createSessionRouter({ sessions: services.sessions }));
24
+
19
25
  app.use(notFoundHandler);
20
26
  app.use(createErrorHandler(logger));
27
+
21
28
  return app;
22
29
  };
@@ -1,12 +1,18 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
+
2
3
  import { UnauthorizedError } from "../../utils/errors.js";
4
+
3
5
  const BEARER_PREFIX = "Bearer ";
6
+
4
7
  const safeEqual = (provided, expected) => {
5
8
  const actual = Buffer.from(provided);
6
9
  const target = Buffer.from(expected);
10
+
7
11
  if (actual.length !== target.length) return false;
12
+
8
13
  return timingSafeEqual(actual, target);
9
14
  };
15
+
10
16
  /**
11
17
  * 可选的 Bearer Token 鉴权。未设置 AGENT_API_KEY 时 API 完全开放
12
18
  * (适合本地开发,切勿用于公网部署)。
@@ -15,13 +21,16 @@ export const createAuthMiddleware = (apiKey) => {
15
21
  if (!apiKey) {
16
22
  return (_req, _res, next) => next();
17
23
  }
24
+
18
25
  return (req, _res, next) => {
19
26
  const header = req.header("authorization") ?? "";
20
27
  const token = header.startsWith(BEARER_PREFIX) ? header.slice(BEARER_PREFIX.length).trim() : "";
28
+
21
29
  if (!token || !safeEqual(token, apiKey)) {
22
30
  next(new UnauthorizedError());
23
31
  return;
24
32
  }
33
+
25
34
  next();
26
35
  };
27
36
  };
@@ -1,10 +1,13 @@
1
1
  import { NotFoundError, toErrorResponse } from "../../utils/errors.js";
2
+
2
3
  export const notFoundHandler = (req, _res, next) => {
3
4
  next(new NotFoundError(`未找到路由 ${req.method} ${req.path}。`));
4
5
  };
6
+
5
7
  export const createErrorHandler = (logger) => {
6
8
  return (error, req, res, _next) => {
7
9
  const { status, body } = toErrorResponse(error);
10
+
8
11
  if (status >= 500) {
9
12
  logger.error(
10
13
  {
@@ -21,6 +24,7 @@ export const createErrorHandler = (logger) => {
21
24
  "请求被拒绝",
22
25
  );
23
26
  }
27
+
24
28
  res.status(status).json(body);
25
29
  };
26
30
  };
@@ -1,73 +1,43 @@
1
1
  import { Router } from "express";
2
+
2
3
  import { invokeAgentSchema, resumeAgentSchema } from "../../schemas/agent.js";
3
- import { ValidationError } from "../../utils/errors.js";
4
+ import { errorMessage } from "../../utils/helpers.js";
5
+ import { parseRequest } from "../../utils/validation.js";
6
+
4
7
  export const createAgentRouter = ({ agent }) => {
5
8
  const router = Router();
6
- router.post("/invoke", async (req, res, next) => {
7
- try {
8
- const parsed = invokeAgentSchema.safeParse(req.body);
9
- if (!parsed.success) {
10
- throw new ValidationError("请求体格式错误。", {
11
- issues: parsed.error.issues,
12
- });
13
- }
14
- const result = await agent.invoke(parsed.data);
15
- res.json(result);
16
- } catch (error) {
17
- next(error);
18
- }
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)));
19
13
  });
20
- router.post("/resume", async (req, res, next) => {
21
- try {
22
- const parsed = resumeAgentSchema.safeParse(req.body);
23
- if (!parsed.success) {
24
- throw new ValidationError("请求体格式错误。", {
25
- issues: parsed.error.issues,
26
- });
27
- }
28
- const result = await agent.resume(parsed.data);
29
- res.json(result);
30
- } catch (error) {
31
- next(error);
32
- }
14
+
15
+ router.post("/resume", async (req, res) => {
16
+ res.json(await agent.resume(parseRequest(resumeAgentSchema, req.body)));
33
17
  });
34
- router.post("/stream", async (req, res, next) => {
35
- const parsed = invokeAgentSchema.safeParse(req.body);
36
- if (!parsed.success) {
37
- next(
38
- new ValidationError("请求体格式错误。", {
39
- issues: parsed.error.issues,
40
- }),
41
- );
42
- return;
43
- }
18
+
19
+ router.post("/stream", async (req, res) => {
20
+ const input = parseRequest(invokeAgentSchema, req.body);
44
21
  const controller = new AbortController();
45
22
  req.on("close", () => controller.abort());
23
+
46
24
  res.status(200);
47
25
  res.setHeader("Content-Type", "text/event-stream");
48
26
  res.setHeader("Cache-Control", "no-cache, no-transform");
49
27
  res.setHeader("Connection", "keep-alive");
50
28
  res.flushHeaders();
29
+
51
30
  try {
52
- for await (const event of agent.stream(parsed.data, {
53
- signal: controller.signal,
54
- })) {
31
+ for await (const event of agent.stream(input, { signal: controller.signal })) {
55
32
  res.write(`event: ${event.event}\ndata: ${JSON.stringify(event.data)}\n\n`);
56
33
  }
57
34
  res.write("event: done\ndata: {}\n\n");
58
35
  } catch (error) {
59
- if (!res.headersSent) {
60
- next(error);
61
- return;
62
- }
63
- res.write(
64
- `event: error\ndata: ${JSON.stringify({
65
- message: error instanceof Error ? error.message : String(error),
66
- })}\n\n`,
67
- );
36
+ res.write(`event: error\ndata: ${JSON.stringify({ message: errorMessage(error) })}\n\n`);
68
37
  } finally {
69
38
  res.end();
70
39
  }
71
40
  });
41
+
72
42
  return router;
73
43
  };
@@ -1,8 +1,11 @@
1
1
  import { Router } from "express";
2
- import { checkDatabase } from "../../infrastructure/database/client.js";
3
- import { checkRedis } from "../../infrastructure/redis/client.js";
2
+
3
+ import { checkDatabase } from "../../storage/database/client.js";
4
+ import { checkRedis } from "../../storage/redis/client.js";
5
+
4
6
  export const createHealthRouter = ({ config, mcp }) => {
5
7
  const router = Router();
8
+
6
9
  router.get("/", (_req, res) => {
7
10
  res.json({
8
11
  status: "ok",
@@ -12,12 +15,17 @@ export const createHealthRouter = ({ config, mcp }) => {
12
15
  uptimeSeconds: Math.round(process.uptime()),
13
16
  });
14
17
  });
18
+
15
19
  router.get("/ready", async (_req, res) => {
16
20
  const [database, redis] = await Promise.all([
17
- config.database.url ? checkDatabase() : Promise.resolve({ ok: true, skipped: true }),
21
+ config.database.url
22
+ ? checkDatabase(config.database.url)
23
+ : Promise.resolve({ ok: true, skipped: true }),
18
24
  config.redis.url ? checkRedis() : Promise.resolve({ ok: true, skipped: true }),
19
25
  ]);
26
+
20
27
  const ready = (!config.database.url || database.ok) && (!config.redis.url || redis.ok);
28
+
21
29
  res.status(ready ? 200 : 503).json({
22
30
  status: ready ? "ready" : "degraded",
23
31
  checks: {
@@ -27,5 +35,6 @@ export const createHealthRouter = ({ config, mcp }) => {
27
35
  },
28
36
  });
29
37
  });
38
+
30
39
  return router;
31
40
  };
@@ -1,62 +1,42 @@
1
1
  import { Router } from "express";
2
+
2
3
  import { createSessionSchema } from "../../schemas/session.js";
3
- import { ValidationError } from "../../utils/errors.js";
4
+ import { parseRequest } from "../../utils/validation.js";
5
+
4
6
  const tenantFrom = (value) => {
5
7
  return typeof value === "string" && value.length > 0 ? value : "default";
6
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
+
7
15
  export const createSessionRouter = ({ sessions }) => {
8
16
  const router = Router();
9
- router.post("/", async (req, res, next) => {
10
- try {
11
- const parsed = createSessionSchema.safeParse(req.body ?? {});
12
- if (!parsed.success) {
13
- throw new ValidationError("请求体格式错误。", {
14
- issues: parsed.error.issues,
15
- });
16
- }
17
- const input = parsed.data;
18
- const session = await sessions.create(input);
19
- res.status(201).json(session);
20
- } catch (error) {
21
- next(error);
22
- }
17
+
18
+ router.post("/", async (req, res) => {
19
+ const session = await sessions.create(parseRequest(createSessionSchema, req.body ?? {}));
20
+ res.status(201).json(session);
23
21
  });
24
- router.get("/", async (req, res, next) => {
25
- try {
26
- const tenantId = tenantFrom(req.query.tenantId);
27
- const limit = Number(req.query.limit ?? 20);
28
- const result = await sessions.list(
29
- tenantId,
30
- Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20,
31
- );
32
- res.json(result);
33
- } catch (error) {
34
- next(error);
35
- }
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);
36
26
  });
37
- router.get("/:threadId", async (req, res, next) => {
38
- try {
39
- const session = await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId));
40
- res.json(session);
41
- } catch (error) {
42
- next(error);
43
- }
27
+
28
+ router.get("/:threadId", async (req, res) => {
29
+ res.json(await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId)));
44
30
  });
45
- router.get("/:threadId/messages", async (req, res, next) => {
46
- try {
47
- const messages = await sessions.history(req.params.threadId);
48
- res.json({ messages });
49
- } catch (error) {
50
- next(error);
51
- }
31
+
32
+ router.get("/:threadId/messages", async (req, res) => {
33
+ res.json({ messages: await sessions.history(req.params.threadId) });
52
34
  });
53
- router.delete("/:threadId", async (req, res, next) => {
54
- try {
55
- await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
56
- res.status(204).end();
57
- } catch (error) {
58
- next(error);
59
- }
35
+
36
+ router.delete("/:threadId", async (req, res) => {
37
+ await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
38
+ res.status(204).end();
60
39
  });
40
+
61
41
  return router;
62
42
  };
@@ -1,41 +1,50 @@
1
1
  import fs from "node:fs/promises";
2
- import { createSupervisorAgent } from "./agents/supervisor.js";
2
+
3
+ import { createSupervisorAgent } from "./agents/index.js";
3
4
  import { createApiApp } from "./api/app.js";
4
5
  import { createBackend } from "./backends/index.js";
5
- import { createChatModel, loadConfig } from "./config/index.js";
6
- import { createCheckpointer } from "./graph/checkpointer.js";
7
- import { createStore } from "./graph/store.js";
8
- import { closeDatabase } from "./infrastructure/database/client.js";
9
- import { createLogger } from "./infrastructure/logger/index.js";
10
- import { closeRedis } from "./infrastructure/redis/client.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
11
  import { createMemoryManager } from "./memory/index.js";
12
- import { AgentService } from "./services/agent.service.js";
13
- import { MemoryService } from "./services/memory.service.js";
14
- import { SessionService } from "./services/session.service.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";
15
16
  import { loadSkills, validateSkills } from "./skills/index.js";
16
17
  import { createDefaultTools } from "./tools/index.js";
17
- import { createMcpToolRegistry } from "./tools/mcp/index.js";
18
+ import { createMcpToolRegistry } from "./tools/index.js";
19
+
18
20
  /**
19
21
  * 应用装配:配置 → 基础设施 → Agent 运行时 → 服务 → HTTP 应用。
20
22
  * 这里不启动服务,因此测试、脚本和 HTTP 入口可以复用同一套装配。
21
23
  */
22
24
  export const createApplication = async (config = loadConfig()) => {
23
25
  const logger = createLogger(config);
26
+
24
27
  await fs.mkdir(config.paths.workspaces, { recursive: true });
25
28
  await fs.mkdir(config.paths.resources, { recursive: true });
29
+
26
30
  const skills = await loadSkills({ rootDir: config.paths.skills });
27
31
  for (const warning of validateSkills(skills)) {
28
32
  logger.warn(warning);
29
33
  }
34
+
30
35
  logger.info({ skills: skills.map((skill) => skill.name) }, "技能加载完成");
36
+
31
37
  const store = await createStore(config);
32
38
  const checkpointer = await createCheckpointer(config);
33
39
  const backend = await createBackend(config);
34
40
  const mcp = await createMcpToolRegistry();
41
+
35
42
  const tools = createDefaultTools({
36
43
  workspaceRoot: config.paths.workspaces,
44
+ databaseUrl: config.database.url,
37
45
  additionalTools: mcp.tools,
38
46
  });
47
+
39
48
  const agent = createSupervisorAgent({
40
49
  config,
41
50
  model: createChatModel(config.model),
@@ -45,9 +54,16 @@ export const createApplication = async (config = loadConfig()) => {
45
54
  logger,
46
55
  tools,
47
56
  });
48
- const sessions = new SessionService({ graph: agent, checkpointer, store });
57
+
58
+ const sessions = new SessionService({
59
+ graph: agent,
60
+ checkpointer,
61
+ store,
62
+ sandboxes: backend.sandboxes,
63
+ });
49
64
  const agentService = new AgentService({ agent, config, sessions });
50
65
  const memoryService = new MemoryService(createMemoryManager(store));
66
+
51
67
  const app = createApiApp({
52
68
  config,
53
69
  logger,
@@ -58,7 +74,9 @@ export const createApplication = async (config = loadConfig()) => {
58
74
  memory: memoryService,
59
75
  },
60
76
  });
77
+
61
78
  let closed = false;
79
+
62
80
  return {
63
81
  app,
64
82
  logger,
@@ -70,6 +88,7 @@ export const createApplication = async (config = loadConfig()) => {
70
88
  close: async () => {
71
89
  if (closed) return;
72
90
  closed = true;
91
+
73
92
  await mcp.close();
74
93
  await backend.dispose();
75
94
  await closeDatabase();
@@ -1,5 +1,7 @@
1
1
  import { CompositeBackend, StateBackend, StoreBackend } from "deepagents";
2
+
2
3
  import { createFilesystemBackend } from "./filesystem.js";
4
+
3
5
  /**
4
6
  * 把 Agent 需要的所有资源挂载到同一个虚拟文件系统:
5
7
  *
@@ -1,4 +1,5 @@
1
1
  import { FilesystemBackend } from "deepagents";
2
+
2
3
  /**
3
4
  * 虚拟路径被限制在 `rootDir` 内的文件系统后端。
4
5
  * Agent 看到的是 `/notes.md`,实际文件位于 `<rootDir>/notes.md`。
@@ -1,12 +1,43 @@
1
+ import { StateBackend } from "deepagents";
2
+
3
+ import { SandboxManager, threadIdFromRuntime } from "../sandbox/index.js";
1
4
  import { createCompositeBackend } from "./composite.js";
2
5
  import { createSandboxBackend } from "./sandbox.js";
6
+
3
7
  /**
4
- * 构建主 Agent 和所有子 Agent 共用的组合后端。
5
- * Shell 访问会执行宿主机命令,因此默认关闭。
8
+ * 构建主 Agent 和所有子 Agent 共用的后端。
9
+ *
10
+ * `SANDBOX_ENABLED=true` 时返回一个工厂:按 `threadId` 为每个会话惰性创建并复用
11
+ * 一个 OpenSandbox 沙箱(`/workspace/` 与 `execute` 落在沙箱内),
12
+ * `/resources/`、`/skills/` 仍读本地只读文件,`/memories/` 继续使用 LangGraph store。
13
+ * 未开启时回退到本地文件系统后端,`ENABLE_SHELL=true` 时再挂上宿主机 shell。
6
14
  */
7
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
+
8
38
  const rootDir = config.paths.workspaces;
9
39
  const shell = config.agent.enableShell ? await createSandboxBackend({ rootDir }) : null;
40
+
10
41
  const backend = createCompositeBackend({
11
42
  ...(shell ? { defaultBackend: shell } : {}),
12
43
  paths: {
@@ -15,14 +46,15 @@ export const createBackend = async (config) => {
15
46
  skills: config.paths.skills,
16
47
  },
17
48
  });
49
+
18
50
  return {
19
51
  backend,
20
- shell,
21
52
  dispose: async () => {
22
53
  await shell?.close();
23
54
  },
24
55
  };
25
56
  };
57
+
26
58
  export { createCompositeBackend } from "./composite.js";
27
59
  export { createFilesystemBackend } from "./filesystem.js";
28
60
  export { createSandboxBackend } from "./sandbox.js";
@@ -1,4 +1,5 @@
1
1
  import { LocalShellBackend } from "deepagents";
2
+
2
3
  /**
3
4
  * 本地 shell 后端。在文件系统工具之上增加 `execute` 工具,
4
5
  * 命令会以当前进程的权限在宿主机执行。
@@ -18,6 +19,8 @@ export const createSandboxBackend = async ({
18
19
  timeout: timeoutSeconds,
19
20
  maxOutputBytes,
20
21
  });
22
+
21
23
  await backend.initialize();
24
+
22
25
  return backend;
23
26
  };
@@ -1,5 +1,6 @@
1
1
  export const DEFAULT_AGENT_DESCRIPTION =
2
2
  "负责规划任务、把工作分派给专职子 Agent,并维护工作区文件的主 Agent。";
3
+
3
4
  export const resolveAgentConfig = (env) => {
4
5
  return {
5
6
  name: env.AGENT_NAME,
@@ -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
+ };
@@ -1,30 +1,39 @@
1
1
  import "../schemas/locale.js";
2
+
2
3
  import { z } from "zod";
4
+
5
+ import { MODEL_PROVIDERS } from "../model/index.js";
3
6
  import { ConfigurationError } from "../utils/errors.js";
7
+
4
8
  const booleanFlag = z
5
9
  .union([z.boolean(), z.string()])
6
10
  .default("false")
7
11
  .transform((value) =>
8
12
  typeof value === "boolean" ? value : ["1", "true", "yes", "on"].includes(value.toLowerCase()),
9
13
  );
14
+
10
15
  const optionalString = z
11
16
  .string()
12
17
  .trim()
13
18
  .optional()
14
19
  .transform((value) => (value === "" ? undefined : value));
20
+
15
21
  export const envSchema = z.object({
16
22
  NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
17
23
  HOST: z.string().default("0.0.0.0"),
18
24
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
19
25
  LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
20
- MODEL_PROVIDER: z.enum(["openai", "anthropic"]).default("openai"),
26
+
27
+ // 模型统一通过 OpenAI 兼容协议接入,服务商预设见 src/model/presets。
28
+ MODEL_PROVIDER: z.enum(MODEL_PROVIDERS).default("minimax"),
21
29
  MODEL_NAME: optionalString,
30
+ MODEL_BASE_URL: optionalString,
31
+ MODEL_API_KEY: optionalString,
22
32
  MODEL_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.2),
23
- MODEL_MAX_TOKENS: z.coerce.number().int().positive().default(4096),
24
- OPENAI_API_KEY: optionalString,
25
- OPENAI_BASE_URL: optionalString,
26
- ANTHROPIC_API_KEY: optionalString,
27
- TAVILY_API_KEY: optionalString,
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
+
28
37
  AGENT_NAME: z.string().default("deepagent"),
29
38
  AGENT_API_KEY: optionalString,
30
39
  AGENT_RECURSION_LIMIT: z.coerce.number().int().min(1).max(1000).default(50),
@@ -33,41 +42,55 @@ export const envSchema = z.object({
33
42
  WORKSPACE_ROOT: z.string().default("workspaces"),
34
43
  RESOURCES_ROOT: z.string().default("resources"),
35
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
+
36
57
  CHECKPOINTER: z.enum(["memory", "postgres"]).default("memory"),
37
58
  STORE: z.enum(["memory", "postgres"]).default("memory"),
59
+
60
+ // PostgreSQL:CHECKPOINTER/STORE 为 postgres 时由分项拼装连接串,DATABASE_URL 优先。
38
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
+
39
68
  REDIS_URL: optionalString,
69
+
40
70
  LANGSMITH_TRACING: booleanFlag,
41
71
  LANGSMITH_API_KEY: optionalString,
42
72
  LANGSMITH_PROJECT: z.string().default("deepagent"),
73
+
43
74
  MCP_SERVERS: optionalString,
44
75
  });
76
+
45
77
  export const loadEnv = (source = process.env, { requireModelCredentials = true } = {}) => {
46
78
  const parsed = envSchema.safeParse(source);
79
+
47
80
  if (!parsed.success) {
48
81
  const issues = parsed.error.issues
49
82
  .map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`)
50
83
  .join("; ");
51
84
  throw new ConfigurationError(`环境变量配置无效:${issues}`);
52
85
  }
86
+
53
87
  const env = parsed.data;
54
- if (requireModelCredentials && env.NODE_ENV !== "test") {
55
- if (env.MODEL_PROVIDER === "openai" && !env.OPENAI_API_KEY) {
56
- throw new ConfigurationError(
57
- "MODEL_PROVIDER=openai 时必须设置 OPENAI_API_KEY(可复制 .env.example 为 .env)。",
58
- );
59
- }
60
- if (env.MODEL_PROVIDER === "anthropic" && !env.ANTHROPIC_API_KEY) {
61
- throw new ConfigurationError(
62
- "MODEL_PROVIDER=anthropic 时必须设置 ANTHROPIC_API_KEY(可复制 .env.example 为 .env)。",
63
- );
64
- }
65
- }
66
- if (env.CHECKPOINTER === "postgres" && !env.DATABASE_URL) {
67
- throw new ConfigurationError("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
68
- }
69
- if (env.STORE === "postgres" && !env.DATABASE_URL) {
70
- throw new ConfigurationError("STORE=postgres 时必须设置 DATABASE_URL。");
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
+ );
71
93
  }
94
+
72
95
  return env;
73
96
  };