create-deepagent-server 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +83 -8
  2. package/package.json +1 -1
  3. package/src/args.js +6 -4
  4. package/src/cli.js +1 -4
  5. package/src/dependencies.js +1 -1
  6. package/src/prompts.js +1 -0
  7. package/src/registry.js +8 -8
  8. package/src/scaffold.js +21 -7
  9. package/src/setup.js +2 -0
  10. package/src/version.js +1 -1
  11. package/src/versions.js +1 -1
  12. package/templates/deepagent/js/scripts/check.js +34 -11
  13. package/templates/deepagent/js/scripts/dev.js +9 -0
  14. package/templates/deepagent/js/src/agents/factory.js +2 -1
  15. package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
  16. package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
  17. package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
  18. package/templates/deepagent/js/src/agents/state/types.js +1 -0
  19. package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
  20. package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
  21. package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
  22. package/templates/deepagent/js/src/agents/supervisor.js +12 -4
  23. package/templates/deepagent/js/src/api/app.js +7 -0
  24. package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
  25. package/templates/deepagent/js/src/api/middleware/error.js +4 -0
  26. package/templates/deepagent/js/src/api/routes/agent.js +19 -49
  27. package/templates/deepagent/js/src/api/routes/health.js +12 -3
  28. package/templates/deepagent/js/src/api/routes/session.js +28 -48
  29. package/templates/deepagent/js/src/app.js +31 -12
  30. package/templates/deepagent/js/src/backends/composite.js +2 -0
  31. package/templates/deepagent/js/src/backends/filesystem.js +1 -0
  32. package/templates/deepagent/js/src/backends/index.js +35 -3
  33. package/templates/deepagent/js/src/backends/sandbox.js +3 -0
  34. package/templates/deepagent/js/src/config/agent.js +1 -0
  35. package/templates/deepagent/js/src/config/database.js +19 -0
  36. package/templates/deepagent/js/src/config/env.js +46 -23
  37. package/templates/deepagent/js/src/config/index.js +13 -3
  38. package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
  39. package/templates/deepagent/js/src/graph/compile.js +1 -0
  40. package/templates/deepagent/js/src/graph/store.js +10 -2
  41. package/templates/deepagent/js/src/index.js +9 -2
  42. package/templates/deepagent/js/src/memory/index.js +2 -0
  43. package/templates/deepagent/js/src/memory/manager.js +21 -10
  44. package/templates/deepagent/js/src/memory/store.js +7 -0
  45. package/templates/deepagent/js/src/middleware/approval.js +6 -1
  46. package/templates/deepagent/js/src/middleware/context.js +5 -0
  47. package/templates/deepagent/js/src/middleware/logging.js +47 -43
  48. package/templates/deepagent/js/src/middleware/security.js +7 -0
  49. package/templates/deepagent/js/src/model/config.js +38 -0
  50. package/templates/deepagent/js/src/model/index.js +9 -0
  51. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  52. package/templates/deepagent/js/src/model/presets.js +71 -0
  53. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  54. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  55. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  56. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  57. package/templates/deepagent/js/src/schemas/agent.js +7 -0
  58. package/templates/deepagent/js/src/schemas/common.js +5 -0
  59. package/templates/deepagent/js/src/schemas/locale.js +1 -0
  60. package/templates/deepagent/js/src/schemas/session.js +4 -0
  61. package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
  62. package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
  63. package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
  64. package/templates/deepagent/js/src/skills/index.js +4 -0
  65. package/templates/deepagent/js/src/skills/loader.js +20 -10
  66. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  67. package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
  68. package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
  69. package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
  70. package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
  71. package/templates/deepagent/js/src/tools/database/index.js +1 -1
  72. package/templates/deepagent/js/src/tools/database/query.js +44 -32
  73. package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
  74. package/templates/deepagent/js/src/tools/index.js +6 -11
  75. package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
  76. package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
  77. package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
  78. package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
  79. package/templates/deepagent/js/src/utils/errors.js +9 -0
  80. package/templates/deepagent/js/src/utils/helpers.js +15 -0
  81. package/templates/deepagent/js/src/utils/validation.js +15 -0
  82. package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
  83. package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
  84. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  85. package/templates/deepagent/js/tests/integration/api.test.js +18 -3
  86. package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
  87. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  88. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  89. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  90. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  91. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +5 -1
  93. package/templates/deepagent/shared/README.md +101 -14
  94. package/templates/deepagent/shared/_env.example +40 -10
  95. package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
  96. package/templates/deepagent/shared/resources/AGENTS.md +1 -1
  97. package/templates/deepagent/ts/scripts/check.ts +19 -11
  98. package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
  99. package/templates/deepagent/ts/src/agents/factory.ts +1 -1
  100. package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
  101. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
  102. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
  103. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
  104. package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
  105. package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
  106. package/templates/deepagent/ts/src/api/app.ts +4 -4
  107. package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
  108. package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
  109. package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
  110. package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
  111. package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
  112. package/templates/deepagent/ts/src/app.ts +19 -12
  113. package/templates/deepagent/ts/src/backends/index.ts +41 -7
  114. package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
  115. package/templates/deepagent/ts/src/config/database.ts +21 -0
  116. package/templates/deepagent/ts/src/config/env.ts +32 -28
  117. package/templates/deepagent/ts/src/config/index.ts +12 -4
  118. package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
  119. package/templates/deepagent/ts/src/graph/store.ts +5 -2
  120. package/templates/deepagent/ts/src/index.ts +2 -2
  121. package/templates/deepagent/ts/src/memory/manager.ts +12 -10
  122. package/templates/deepagent/ts/src/memory/store.ts +2 -0
  123. package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
  124. package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
  125. package/templates/deepagent/ts/src/middleware/security.ts +1 -0
  126. package/templates/deepagent/ts/src/model/config.ts +56 -0
  127. package/templates/deepagent/ts/src/model/index.ts +14 -0
  128. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  129. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  130. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  131. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  132. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  133. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  134. package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
  135. package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
  136. package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
  137. package/templates/deepagent/ts/src/skills/loader.ts +6 -10
  138. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  139. package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
  140. package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
  141. package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
  142. package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
  143. package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
  144. package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
  145. package/templates/deepagent/ts/src/tools/index.ts +10 -8
  146. package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
  147. package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
  148. package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
  149. package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
  150. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  151. package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
  152. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
  153. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  154. package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
  155. package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
  156. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  157. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  158. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  159. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  160. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  161. package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
  162. package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
  163. package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
  164. package/templates/deepagent/js/src/config/model.js +0 -34
  165. package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
  166. package/templates/deepagent/js/src/tools/search/index.js +0 -1
  167. package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
  168. package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
  169. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
  170. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
  171. package/templates/deepagent/ts/src/config/model.ts +0 -49
  172. package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
  173. package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
  174. package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
  175. /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
@@ -2,8 +2,8 @@ import { Router } from "express";
2
2
 
3
3
  import type { AppConfig } from "../../config/index.js";
4
4
  import type { McpToolRegistry } from "../../tools/mcp/index.js";
5
- import { checkDatabase } from "../../infrastructure/database/client.js";
6
- import { checkRedis } from "../../infrastructure/redis/client.js";
5
+ import { checkDatabase } from "../../storage/database/client.js";
6
+ import { checkRedis } from "../../storage/redis/client.js";
7
7
 
8
8
  export interface HealthRouterDependencies {
9
9
  config: AppConfig;
@@ -25,7 +25,9 @@ export const createHealthRouter = ({ config, mcp }: HealthRouterDependencies): R
25
25
 
26
26
  router.get("/ready", async (_req, res) => {
27
27
  const [database, redis] = await Promise.all([
28
- config.database.url ? checkDatabase() : Promise.resolve({ ok: true, skipped: true }),
28
+ config.database.url
29
+ ? checkDatabase(config.database.url)
30
+ : Promise.resolve({ ok: true, skipped: true }),
29
31
  config.redis.url ? checkRedis() : Promise.resolve({ ok: true, skipped: true }),
30
32
  ]);
31
33
 
@@ -1,8 +1,8 @@
1
1
  import { Router } from "express";
2
2
 
3
- import { createSessionSchema, type CreateSessionInput } from "../../schemas/session.js";
4
- import type { SessionService } from "../../services/session.service.js";
5
- import { ValidationError } from "../../utils/errors.js";
3
+ import { createSessionSchema } from "../../schemas/session.js";
4
+ import type { SessionService } from "../../services/session.js";
5
+ import { parseRequest } from "../../utils/validation.js";
6
6
 
7
7
  export interface SessionRouterDependencies {
8
8
  sessions: SessionService;
@@ -12,65 +12,35 @@ const tenantFrom = (value: unknown): string => {
12
12
  return typeof value === "string" && value.length > 0 ? value : "default";
13
13
  };
14
14
 
15
+ const limitFrom = (value: unknown): number => {
16
+ const limit = Number(value ?? 20);
17
+ return Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20;
18
+ };
19
+
15
20
  export const createSessionRouter = ({ sessions }: SessionRouterDependencies): Router => {
16
21
  const router = Router();
17
22
 
18
- router.post("/", async (req, res, next) => {
19
- try {
20
- const parsed = createSessionSchema.safeParse(req.body ?? {});
21
- if (!parsed.success) {
22
- throw new ValidationError("请求体格式错误。", {
23
- issues: parsed.error.issues,
24
- });
25
- }
26
-
27
- const input: CreateSessionInput = parsed.data;
28
- const session = await sessions.create(input);
29
- res.status(201).json(session);
30
- } catch (error) {
31
- next(error);
32
- }
23
+ router.post("/", async (req, res) => {
24
+ const session = await sessions.create(parseRequest(createSessionSchema, req.body ?? {}));
25
+ res.status(201).json(session);
33
26
  });
34
27
 
35
- router.get("/", async (req, res, next) => {
36
- try {
37
- const tenantId = tenantFrom(req.query.tenantId);
38
- const limit = Number(req.query.limit ?? 20);
39
- const result = await sessions.list(
40
- tenantId,
41
- Number.isFinite(limit) ? Math.min(Math.max(limit, 1), 100) : 20,
42
- );
43
- res.json(result);
44
- } catch (error) {
45
- next(error);
46
- }
28
+ router.get("/", async (req, res) => {
29
+ const result = await sessions.list(tenantFrom(req.query.tenantId), limitFrom(req.query.limit));
30
+ res.json(result);
47
31
  });
48
32
 
49
- router.get("/:threadId", async (req, res, next) => {
50
- try {
51
- const session = await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId));
52
- res.json(session);
53
- } catch (error) {
54
- next(error);
55
- }
33
+ router.get("/:threadId", async (req, res) => {
34
+ res.json(await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId)));
56
35
  });
57
36
 
58
- router.get("/:threadId/messages", async (req, res, next) => {
59
- try {
60
- const messages = await sessions.history(req.params.threadId);
61
- res.json({ messages });
62
- } catch (error) {
63
- next(error);
64
- }
37
+ router.get("/:threadId/messages", async (req, res) => {
38
+ res.json({ messages: await sessions.history(req.params.threadId) });
65
39
  });
66
40
 
67
- router.delete("/:threadId", async (req, res, next) => {
68
- try {
69
- await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
70
- res.status(204).end();
71
- } catch (error) {
72
- next(error);
73
- }
41
+ router.delete("/:threadId", async (req, res) => {
42
+ await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
43
+ res.status(204).end();
74
44
  });
75
45
 
76
46
  return router;
@@ -2,22 +2,22 @@ import fs from "node:fs/promises";
2
2
 
3
3
  import type { Express } from "express";
4
4
 
5
- import { createSupervisorAgent } from "./agents/supervisor.js";
5
+ import { createSupervisorAgent } from "./agents/index.js";
6
6
  import { createApiApp } from "./api/app.js";
7
7
  import { createBackend } from "./backends/index.js";
8
- import { createChatModel, loadConfig, type AppConfig } from "./config/index.js";
9
- import { createCheckpointer } from "./graph/checkpointer.js";
10
- import { createStore } from "./graph/store.js";
11
- import { closeDatabase } from "./infrastructure/database/client.js";
12
- import { createLogger, type Logger } from "./infrastructure/logger/index.js";
13
- import { closeRedis } from "./infrastructure/redis/client.js";
8
+ import { loadConfig, type AppConfig } from "./config/index.js";
9
+ import { createCheckpointer, createStore } from "./graph/index.js";
10
+ import { closeDatabase } from "./storage/database/client.js";
11
+ import { createLogger, type Logger } from "./storage/logger/index.js";
12
+ import { closeRedis } from "./storage/redis/client.js";
14
13
  import { createMemoryManager } from "./memory/index.js";
15
- import { AgentService } from "./services/agent.service.js";
16
- import { MemoryService } from "./services/memory.service.js";
17
- import { SessionService } from "./services/session.service.js";
14
+ import { createChatModel } from "./model/index.js";
15
+ import { AgentService } from "./services/agent.js";
16
+ import { MemoryService } from "./services/memory.js";
17
+ import { SessionService } from "./services/session.js";
18
18
  import { loadSkills, validateSkills } from "./skills/index.js";
19
19
  import { createDefaultTools } from "./tools/index.js";
20
- import { createMcpToolRegistry } from "./tools/mcp/index.js";
20
+ import { createMcpToolRegistry } from "./tools/index.js";
21
21
 
22
22
  export interface Application {
23
23
  app: Express;
@@ -44,6 +44,7 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
44
44
  for (const warning of validateSkills(skills)) {
45
45
  logger.warn(warning);
46
46
  }
47
+
47
48
  logger.info({ skills: skills.map((skill) => skill.name) }, "技能加载完成");
48
49
 
49
50
  const store = await createStore(config);
@@ -53,6 +54,7 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
53
54
 
54
55
  const tools = createDefaultTools({
55
56
  workspaceRoot: config.paths.workspaces,
57
+ databaseUrl: config.database.url,
56
58
  additionalTools: mcp.tools,
57
59
  });
58
60
 
@@ -66,7 +68,12 @@ export const createApplication = async (config: AppConfig = loadConfig()): Promi
66
68
  tools,
67
69
  });
68
70
 
69
- const sessions = new SessionService({ graph: agent, checkpointer, store });
71
+ const sessions = new SessionService({
72
+ graph: agent,
73
+ checkpointer,
74
+ store,
75
+ sandboxes: backend.sandboxes,
76
+ });
70
77
  const agentService = new AgentService({ agent, config, sessions });
71
78
  const memoryService = new MemoryService(createMemoryManager(store));
72
79
 
@@ -1,21 +1,56 @@
1
- import type { CompositeBackend } from "deepagents";
1
+ import {
2
+ CompositeBackend,
3
+ StateBackend,
4
+ StoreBackend,
5
+ type AnyBackendProtocol,
6
+ type BackendFactory,
7
+ } from "deepagents";
2
8
 
3
9
  import type { AppConfig } from "../config/index.js";
10
+ import { SandboxManager, threadIdFromRuntime } from "../sandbox/index.js";
4
11
  import { createCompositeBackend } from "./composite.js";
12
+ import { createFilesystemBackend } from "./filesystem.js";
5
13
  import { createSandboxBackend } from "./sandbox.js";
6
14
 
7
15
  export interface BackendBundle {
8
- backend: CompositeBackend;
9
- /** 仅在 ENABLE_SHELL=true 时存在。 */
10
- shell: Awaited<ReturnType<typeof createSandboxBackend>> | null;
16
+ /** 普通后端实例,或按运行时(会话)动态解析的工厂。 */
17
+ backend: AnyBackendProtocol | BackendFactory;
18
+ /** `SANDBOX_ENABLED=true` 时存在,用于删除会话时释放对应沙箱。 */
19
+ sandboxes?: SandboxManager;
11
20
  dispose: () => Promise<void>;
12
21
  }
13
22
 
14
23
  /**
15
- * 构建主 Agent 和所有子 Agent 共用的组合后端。
16
- * Shell 访问会执行宿主机命令,因此默认关闭。
24
+ * 构建主 Agent 和所有子 Agent 共用的后端。
25
+ *
26
+ * `SANDBOX_ENABLED=true` 时返回一个工厂:按 `threadId` 为每个会话惰性创建并复用
27
+ * 一个 OpenSandbox 沙箱(`/workspace/` 与 `execute` 落在沙箱内),
28
+ * `/resources/`、`/skills/` 仍读本地只读文件,`/memories/` 继续使用 LangGraph store。
29
+ * 未开启时回退到本地文件系统后端,`ENABLE_SHELL=true` 时再挂上宿主机 shell。
17
30
  */
18
31
  export const createBackend = async (config: AppConfig): Promise<BackendBundle> => {
32
+ if (config.sandbox.enabled) {
33
+ const sandboxes = new SandboxManager(config.sandbox);
34
+
35
+ // memory / skills 中间件解析 backend 时只带 state、没有 threadId;
36
+ // 它们只读 /resources 和 /skills,回退到本地只读后端即可。
37
+ const fallback = createCompositeBackend({
38
+ defaultBackend: new StateBackend(),
39
+ paths: {
40
+ workspaces: config.paths.workspaces,
41
+ resources: config.paths.resources,
42
+ skills: config.paths.skills,
43
+ },
44
+ });
45
+
46
+ const backend: BackendFactory = (runtime) => {
47
+ const threadId = threadIdFromRuntime(runtime);
48
+ return threadId ? sandboxes.get(threadId) : fallback;
49
+ };
50
+
51
+ return { backend, sandboxes, dispose: () => sandboxes.closeAll() };
52
+ }
53
+
19
54
  const rootDir = config.paths.workspaces;
20
55
  const shell = config.agent.enableShell ? await createSandboxBackend({ rootDir }) : null;
21
56
 
@@ -30,7 +65,6 @@ export const createBackend = async (config: AppConfig): Promise<BackendBundle> =
30
65
 
31
66
  return {
32
67
  backend,
33
- shell,
34
68
  dispose: async () => {
35
69
  await shell?.close();
36
70
  },
@@ -28,5 +28,6 @@ export const createSandboxBackend = async ({
28
28
  });
29
29
 
30
30
  await backend.initialize();
31
+
31
32
  return backend;
32
33
  };
@@ -0,0 +1,21 @@
1
+ import type { Env } from "./env.js";
2
+
3
+ /**
4
+ * 解析 PostgreSQL 连接串。
5
+ *
6
+ * - `DATABASE_URL` 优先,适合托管数据库或需要额外连接参数的场景;
7
+ * - 否则在 `CHECKPOINTER` 或 `STORE` 使用 postgres 时,用 `POSTGRES_*` 分项拼装;
8
+ * - 内存模式下返回 `undefined`,避免误连数据库。
9
+ */
10
+ export const resolveDatabaseUrl = (env: Env): string | undefined => {
11
+ if (env.DATABASE_URL) return env.DATABASE_URL;
12
+
13
+ const postgresEnabled = env.CHECKPOINTER === "postgres" || env.STORE === "postgres";
14
+ if (!postgresEnabled) return undefined;
15
+
16
+ const username = encodeURIComponent(env.POSTGRES_USERNAME);
17
+ const password = env.POSTGRES_PASSWORD ? `:${encodeURIComponent(env.POSTGRES_PASSWORD)}` : "";
18
+ const database = encodeURIComponent(env.POSTGRES_DATABASE);
19
+
20
+ return `postgresql://${username}${password}@${env.POSTGRES_HOST}:${env.POSTGRES_PORT}/${database}`;
21
+ };
@@ -2,6 +2,7 @@ import "../schemas/locale.js";
2
2
 
3
3
  import { z } from "zod";
4
4
 
5
+ import { MODEL_PROVIDERS } from "../model/index.js";
5
6
  import { ConfigurationError } from "../utils/errors.js";
6
7
 
7
8
  const booleanFlag = z
@@ -23,15 +24,15 @@ export const envSchema = z.object({
23
24
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
24
25
  LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
25
26
 
26
- MODEL_PROVIDER: z.enum(["openai", "anthropic"]).default("openai"),
27
+ // 模型统一通过 OpenAI 兼容协议接入,服务商预设见 src/model/presets。
28
+ MODEL_PROVIDER: z.enum(MODEL_PROVIDERS).default("minimax"),
27
29
  MODEL_NAME: optionalString,
30
+ MODEL_BASE_URL: optionalString,
31
+ MODEL_API_KEY: optionalString,
28
32
  MODEL_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.2),
29
- MODEL_MAX_TOKENS: z.coerce.number().int().positive().default(4096),
30
-
31
- OPENAI_API_KEY: optionalString,
32
- OPENAI_BASE_URL: optionalString,
33
- ANTHROPIC_API_KEY: optionalString,
34
- 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(),
35
36
 
36
37
  AGENT_NAME: z.string().default("deepagent"),
37
38
  AGENT_API_KEY: optionalString,
@@ -42,9 +43,28 @@ export const envSchema = z.object({
42
43
  RESOURCES_ROOT: z.string().default("resources"),
43
44
  SKILLS_ROOT: z.string().default("skills"),
44
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
+
45
57
  CHECKPOINTER: z.enum(["memory", "postgres"]).default("memory"),
46
58
  STORE: z.enum(["memory", "postgres"]).default("memory"),
59
+
60
+ // PostgreSQL:CHECKPOINTER/STORE 为 postgres 时由分项拼装连接串,DATABASE_URL 优先。
47
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
+
48
68
  REDIS_URL: optionalString,
49
69
 
50
70
  LANGSMITH_TRACING: booleanFlag,
@@ -57,7 +77,7 @@ export const envSchema = z.object({
57
77
  export type Env = z.infer<typeof envSchema>;
58
78
 
59
79
  export interface LoadEnvOptions {
60
- /** 缺少所选模型提供商的 API Key 时直接报错。 */
80
+ /** 缺少 MODEL_API_KEY 时直接报错。 */
61
81
  requireModelCredentials?: boolean;
62
82
  }
63
83
 
@@ -76,26 +96,10 @@ export const loadEnv = (
76
96
 
77
97
  const env = parsed.data;
78
98
 
79
- if (requireModelCredentials && env.NODE_ENV !== "test") {
80
- if (env.MODEL_PROVIDER === "openai" && !env.OPENAI_API_KEY) {
81
- throw new ConfigurationError(
82
- "MODEL_PROVIDER=openai 时必须设置 OPENAI_API_KEY(可复制 .env.example 为 .env)。",
83
- );
84
- }
85
-
86
- if (env.MODEL_PROVIDER === "anthropic" && !env.ANTHROPIC_API_KEY) {
87
- throw new ConfigurationError(
88
- "MODEL_PROVIDER=anthropic 时必须设置 ANTHROPIC_API_KEY(可复制 .env.example 为 .env)。",
89
- );
90
- }
91
- }
92
-
93
- if (env.CHECKPOINTER === "postgres" && !env.DATABASE_URL) {
94
- throw new ConfigurationError("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
95
- }
96
-
97
- if (env.STORE === "postgres" && !env.DATABASE_URL) {
98
- throw new ConfigurationError("STORE=postgres 时必须设置 DATABASE_URL。");
99
+ if (requireModelCredentials && env.NODE_ENV !== "test" && !env.MODEL_API_KEY) {
100
+ throw new ConfigurationError(
101
+ "必须设置 MODEL_API_KEY(可复制 .env.example 为 .env);本地 OpenAI 兼容服务可填任意非空值。",
102
+ );
99
103
  }
100
104
 
101
105
  return env;
@@ -1,14 +1,18 @@
1
1
  import path from "node:path";
2
2
 
3
+ import { resolveModelConfig, type ModelConfig } from "../model/index.js";
4
+
5
+ import { resolveSandboxConfig, type SandboxConfig } from "../sandbox/config.js";
6
+
3
7
  import { resolveAgentConfig, type AgentConfig } from "./agent.js";
8
+ import { resolveDatabaseUrl } from "./database.js";
4
9
  import { loadEnv, type Env } from "./env.js";
5
- import { resolveModelConfig, type ModelConfig } from "./model.js";
6
10
 
7
11
  export type { AgentConfig, ApprovalMode } from "./agent.js";
8
12
  export type { Env } from "./env.js";
9
- export type { ModelConfig } from "./model.js";
13
+ export type { ModelConfig } from "../model/index.js";
14
+ export type { SandboxConfig } from "../sandbox/config.js";
10
15
  export { loadEnv } from "./env.js";
11
- export { createChatModel, DEFAULT_MODELS } from "./model.js";
12
16
 
13
17
  export interface AppPaths {
14
18
  root: string;
@@ -26,6 +30,7 @@ export interface AppConfig {
26
30
  paths: AppPaths;
27
31
  model: ModelConfig;
28
32
  agent: AgentConfig;
33
+ sandbox: SandboxConfig;
29
34
  database: {
30
35
  url?: string;
31
36
  };
@@ -55,6 +60,8 @@ export const loadConfig = (options: LoadConfigOptions = {}): AppConfig => {
55
60
  requireModelCredentials: options.requireModelCredentials ?? true,
56
61
  });
57
62
 
63
+ const databaseUrl = resolveDatabaseUrl(env);
64
+
58
65
  return {
59
66
  env,
60
67
  server: { host: env.HOST, port: env.PORT },
@@ -66,7 +73,8 @@ export const loadConfig = (options: LoadConfigOptions = {}): AppConfig => {
66
73
  },
67
74
  model: resolveModelConfig(env),
68
75
  agent: resolveAgentConfig(env),
69
- database: { ...(env.DATABASE_URL ? { url: env.DATABASE_URL } : {}) },
76
+ sandbox: resolveSandboxConfig(env),
77
+ database: { ...(databaseUrl ? { url: databaseUrl } : {}) },
70
78
  redis: { ...(env.REDIS_URL ? { url: env.REDIS_URL } : {}) },
71
79
  logging: {
72
80
  level: env.LOG_LEVEL,
@@ -7,7 +7,7 @@ import { ConfigurationError } from "../utils/errors.js";
7
7
  * Checkpointer 以 `thread_id` 为单位持久化会话状态。
8
8
  *
9
9
  * - memory:进程内存,零配置(默认)
10
- * - postgres:持久化,需要 DATABASE_URL 和 checkpoint 表
10
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 checkpoint 表
11
11
  */
12
12
  export const createCheckpointer = async (config: AppConfig): Promise<BaseCheckpointSaver> => {
13
13
  if (config.env.CHECKPOINTER !== "postgres") {
@@ -15,12 +15,15 @@ export const createCheckpointer = async (config: AppConfig): Promise<BaseCheckpo
15
15
  }
16
16
 
17
17
  if (!config.database.url) {
18
- throw new ConfigurationError("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
18
+ throw new ConfigurationError(
19
+ "CHECKPOINTER=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
20
+ );
19
21
  }
20
22
 
21
23
  const { PostgresSaver } = await import("@langchain/langgraph-checkpoint-postgres");
22
24
 
23
25
  const saver = PostgresSaver.fromConnString(config.database.url);
24
26
  await saver.setup();
27
+
25
28
  return saver;
26
29
  };
@@ -7,7 +7,7 @@ import { ConfigurationError } from "../utils/errors.js";
7
7
  * Store 用于长期记忆和 `/memories/` 后端挂载。
8
8
  *
9
9
  * - memory:进程内存(默认)
10
- * - postgres:持久化,需要 DATABASE_URL 和 store 表
10
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 store 表
11
11
  */
12
12
  export const createStore = async (config: AppConfig): Promise<BaseStore> => {
13
13
  if (config.env.STORE !== "postgres") {
@@ -15,12 +15,15 @@ export const createStore = async (config: AppConfig): Promise<BaseStore> => {
15
15
  }
16
16
 
17
17
  if (!config.database.url) {
18
- throw new ConfigurationError("STORE=postgres 时必须设置 DATABASE_URL。");
18
+ throw new ConfigurationError(
19
+ "STORE=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
20
+ );
19
21
  }
20
22
 
21
23
  const { PostgresStore } = await import("@langchain/langgraph-checkpoint-postgres/store");
22
24
 
23
25
  const store = PostgresStore.fromConnString(config.database.url);
24
26
  await store.setup();
27
+
25
28
  return store;
26
29
  };
@@ -2,8 +2,8 @@ import "dotenv/config";
2
2
 
3
3
  import { createApplication } from "./app.js";
4
4
  import { loadConfig } from "./config/index.js";
5
- import { createLogger } from "./infrastructure/logger/index.js";
6
- import { createShutdownManager } from "./infrastructure/shutdown/index.js";
5
+ import { createLogger } from "./storage/logger/index.js";
6
+ import { createShutdownManager } from "./storage/shutdown/index.js";
7
7
 
8
8
  const config = loadConfig();
9
9
  const logger = createLogger(config);
@@ -17,18 +17,19 @@ export interface MemoryTarget {
17
17
  * 存储在挂载于 `/memories/` 的同一个 BaseStore 中。
18
18
  */
19
19
  export class MemoryManager {
20
- readonly #memory: MemoryStore;
21
- readonly #root: string[];
20
+ private readonly memory: MemoryStore;
21
+ private readonly root: string[];
22
22
 
23
23
  constructor({ store, rootNamespace = ["memories"] }: MemoryManagerOptions) {
24
- this.#memory = new MemoryStore(store);
25
- this.#root = rootNamespace;
24
+ this.memory = new MemoryStore(store);
25
+ this.root = rootNamespace;
26
26
  }
27
27
 
28
28
  namespaceFor({ tenantId, userId }: MemoryTarget): string[] {
29
29
  assertSegment(tenantId, "tenantId");
30
+
30
31
  const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
31
- return [...this.#root, tenantId, segment];
32
+ return [...this.root, tenantId, segment];
32
33
  }
33
34
 
34
35
  async rememberPreference(
@@ -36,7 +37,7 @@ export class MemoryManager {
36
37
  key: string,
37
38
  value: Record<string, unknown>,
38
39
  ): Promise<void> {
39
- await this.#memory.put(this.namespaceFor(target), `preference:${key}`, value);
40
+ await this.memory.put(this.namespaceFor(target), `preference:${key}`, value);
40
41
  }
41
42
 
42
43
  async rememberFact(
@@ -44,25 +45,25 @@ export class MemoryManager {
44
45
  key: string,
45
46
  value: Record<string, unknown>,
46
47
  ): Promise<void> {
47
- await this.#memory.put(this.namespaceFor(target), `fact:${key}`, value);
48
+ await this.memory.put(this.namespaceFor(target), `fact:${key}`, value);
48
49
  }
49
50
 
50
51
  async recall<T = Record<string, unknown>>(
51
52
  target: MemoryTarget,
52
53
  key: string,
53
54
  ): Promise<MemoryRecord<T> | null> {
54
- return this.#memory.get<T>(this.namespaceFor(target), key);
55
+ return this.memory.get<T>(this.namespaceFor(target), key);
55
56
  }
56
57
 
57
58
  async list<T = Record<string, unknown>>(
58
59
  target: MemoryTarget,
59
60
  limit = 50,
60
61
  ): Promise<MemoryRecord<T>[]> {
61
- return this.#memory.search<T>(this.namespaceFor(target), limit);
62
+ return this.memory.search<T>(this.namespaceFor(target), limit);
62
63
  }
63
64
 
64
65
  async forget(target: MemoryTarget, key: string): Promise<void> {
65
- await this.#memory.delete(this.namespaceFor(target), key);
66
+ await this.memory.delete(this.namespaceFor(target), key);
66
67
  }
67
68
  }
68
69
 
@@ -70,5 +71,6 @@ const assertSegment = (value: string, label: string): string => {
70
71
  if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
71
72
  throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
72
73
  }
74
+
73
75
  return value;
74
76
  };
@@ -31,6 +31,7 @@ export class MemoryStore {
31
31
  ): Promise<MemoryRecord<T> | null> {
32
32
  const item = await this.store.get(namespace, key);
33
33
  if (!item) return null;
34
+
34
35
  return toRecord<T>(item);
35
36
  }
36
37
 
@@ -39,6 +40,7 @@ export class MemoryStore {
39
40
  limit = 20,
40
41
  ): Promise<MemoryRecord<T>[]> {
41
42
  const items = await this.store.search(namespacePrefix, { limit });
43
+
42
44
  return items.map((item) => toRecord<T>(item));
43
45
  }
44
46
 
@@ -1,4 +1,4 @@
1
- import type { ApprovalMode } from "../config/agent.js";
1
+ import type { ApprovalMode } from "../config/index.js";
2
2
 
3
3
  /**
4
4
  * 会修改状态或操作基础设施的工具。它们会通过 `interruptOn` 暂停,
@@ -16,7 +16,6 @@ export const SENSITIVE_TOOLS = [
16
16
  /** 模板已知的全部工具名称。 */
17
17
  export const KNOWN_TOOLS = [
18
18
  ...SENSITIVE_TOOLS,
19
- "web_search",
20
19
  "read_file",
21
20
  "read_workspace_file",
22
21
  "list_workspace_files",
@@ -45,5 +44,6 @@ export const createApprovalPolicy = (mode: ApprovalMode): Record<string, boolean
45
44
  export const requiresApproval = (mode: ApprovalMode, toolName: string): boolean => {
46
45
  if (mode === "none") return false;
47
46
  if (mode === "all") return (KNOWN_TOOLS as readonly string[]).includes(toolName);
47
+
48
48
  return (SENSITIVE_TOOLS as readonly string[]).includes(toolName);
49
49
  };