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,48 @@
1
+ import express, { type Express } from "express";
2
+
3
+ import type { AppConfig } from "../config/index.js";
4
+ import type { Logger } from "../storage/logger/index.js";
5
+ import type { McpToolRegistry } from "../tools/mcp/index.js";
6
+ import type { AgentService } from "../services/agent.js";
7
+ import type { MemoryService } from "../services/memory.js";
8
+ import type { SessionService } from "../services/session.js";
9
+ import { createAuthMiddleware } from "./middleware/auth.js";
10
+ import { createErrorHandler, notFoundHandler } from "./middleware/error.js";
11
+ import { createAgentRouter } from "./routes/agent.js";
12
+ import { createHealthRouter } from "./routes/health.js";
13
+ import { createSessionRouter } from "./routes/session.js";
14
+
15
+ export interface ApiServices {
16
+ agent: AgentService;
17
+ sessions: SessionService;
18
+ memory: MemoryService;
19
+ }
20
+
21
+ export interface ApiDependencies {
22
+ config: AppConfig;
23
+ logger: Logger;
24
+ services: ApiServices;
25
+ mcp?: McpToolRegistry;
26
+ }
27
+
28
+ /**
29
+ * Agent API 的 Express 应用。健康检查保持公开;
30
+ * 配置 AGENT_API_KEY 后,/api 下的接口需要携带 Bearer Token。
31
+ */
32
+ export const createApiApp = ({ config, logger, services, mcp }: ApiDependencies): Express => {
33
+ const app = express();
34
+
35
+ app.disable("x-powered-by");
36
+ app.use(express.json({ limit: "2mb" }));
37
+
38
+ app.use("/health", createHealthRouter({ config, ...(mcp ? { mcp } : {}) }));
39
+
40
+ app.use(createAuthMiddleware(config.env.AGENT_API_KEY));
41
+ app.use("/api/agents", createAgentRouter({ agent: services.agent }));
42
+ app.use("/api/sessions", createSessionRouter({ sessions: services.sessions }));
43
+
44
+ app.use(notFoundHandler);
45
+ app.use(createErrorHandler(logger));
46
+
47
+ return app;
48
+ };
@@ -0,0 +1,38 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+
3
+ import type { RequestHandler } from "express";
4
+
5
+ import { UnauthorizedError } from "../../utils/errors.js";
6
+
7
+ const BEARER_PREFIX = "Bearer ";
8
+
9
+ const safeEqual = (provided: string, expected: string): boolean => {
10
+ const actual = Buffer.from(provided);
11
+ const target = Buffer.from(expected);
12
+
13
+ if (actual.length !== target.length) return false;
14
+
15
+ return timingSafeEqual(actual, target);
16
+ };
17
+
18
+ /**
19
+ * 可选的 Bearer Token 鉴权。未设置 AGENT_API_KEY 时 API 完全开放
20
+ * (适合本地开发,切勿用于公网部署)。
21
+ */
22
+ export const createAuthMiddleware = (apiKey?: string): RequestHandler => {
23
+ if (!apiKey) {
24
+ return (_req, _res, next) => next();
25
+ }
26
+
27
+ return (req, _res, next) => {
28
+ const header = req.header("authorization") ?? "";
29
+ const token = header.startsWith(BEARER_PREFIX) ? header.slice(BEARER_PREFIX.length).trim() : "";
30
+
31
+ if (!token || !safeEqual(token, apiKey)) {
32
+ next(new UnauthorizedError());
33
+ return;
34
+ }
35
+
36
+ next();
37
+ };
38
+ };
@@ -0,0 +1,33 @@
1
+ import type { ErrorRequestHandler, RequestHandler } from "express";
2
+
3
+ import type { Logger } from "../../storage/logger/index.js";
4
+ import { NotFoundError, toErrorResponse } from "../../utils/errors.js";
5
+
6
+ export const notFoundHandler: RequestHandler = (req, _res, next) => {
7
+ next(new NotFoundError(`未找到路由 ${req.method} ${req.path}。`));
8
+ };
9
+
10
+ export const createErrorHandler = (logger: Logger): ErrorRequestHandler => {
11
+ return (error, req, res, _next) => {
12
+ const { status, body } = toErrorResponse(error);
13
+
14
+ if (status >= 500) {
15
+ logger.error(
16
+ {
17
+ method: req.method,
18
+ path: req.path,
19
+ status,
20
+ error: error instanceof Error ? error.stack : String(error),
21
+ },
22
+ "请求处理失败",
23
+ );
24
+ } else {
25
+ logger.warn(
26
+ { method: req.method, path: req.path, status, code: body.error.code },
27
+ "请求被拒绝",
28
+ );
29
+ }
30
+
31
+ res.status(status).json(body);
32
+ };
33
+ };
@@ -0,0 +1,48 @@
1
+ import { Router } from "express";
2
+
3
+ import { invokeAgentSchema, resumeAgentSchema } from "../../schemas/agent.js";
4
+ import type { AgentService } from "../../services/agent.js";
5
+ import { errorMessage } from "../../utils/helpers.js";
6
+ import { parseRequest } from "../../utils/validation.js";
7
+
8
+ export interface AgentRouterDependencies {
9
+ agent: AgentService;
10
+ }
11
+
12
+ export const createAgentRouter = ({ agent }: AgentRouterDependencies): Router => {
13
+ const router = Router();
14
+
15
+ // Express 5 会把 async handler 的拒绝交给错误中间件,这里不需要再包 try/catch。
16
+ router.post("/invoke", async (req, res) => {
17
+ res.json(await agent.invoke(parseRequest(invokeAgentSchema, req.body)));
18
+ });
19
+
20
+ router.post("/resume", async (req, res) => {
21
+ res.json(await agent.resume(parseRequest(resumeAgentSchema, req.body)));
22
+ });
23
+
24
+ router.post("/stream", async (req, res) => {
25
+ const input = parseRequest(invokeAgentSchema, req.body);
26
+ const controller = new AbortController();
27
+ req.on("close", () => controller.abort());
28
+
29
+ res.status(200);
30
+ res.setHeader("Content-Type", "text/event-stream");
31
+ res.setHeader("Cache-Control", "no-cache, no-transform");
32
+ res.setHeader("Connection", "keep-alive");
33
+ res.flushHeaders();
34
+
35
+ try {
36
+ for await (const event of agent.stream(input, { signal: controller.signal })) {
37
+ res.write(`event: ${event.event}\ndata: ${JSON.stringify(event.data)}\n\n`);
38
+ }
39
+ res.write("event: done\ndata: {}\n\n");
40
+ } catch (error) {
41
+ res.write(`event: error\ndata: ${JSON.stringify({ message: errorMessage(error) })}\n\n`);
42
+ } finally {
43
+ res.end();
44
+ }
45
+ });
46
+
47
+ return router;
48
+ };
@@ -0,0 +1,47 @@
1
+ import { Router } from "express";
2
+
3
+ import type { AppConfig } from "../../config/index.js";
4
+ import type { McpToolRegistry } from "../../tools/mcp/index.js";
5
+ import { checkDatabase } from "../../storage/database/client.js";
6
+ import { checkRedis } from "../../storage/redis/client.js";
7
+
8
+ export interface HealthRouterDependencies {
9
+ config: AppConfig;
10
+ mcp?: McpToolRegistry;
11
+ }
12
+
13
+ export const createHealthRouter = ({ config, mcp }: HealthRouterDependencies): Router => {
14
+ const router = Router();
15
+
16
+ router.get("/", (_req, res) => {
17
+ res.json({
18
+ status: "ok",
19
+ service: "deepagent",
20
+ agent: config.agent.name,
21
+ model: `${config.model.provider}/${config.model.name}`,
22
+ uptimeSeconds: Math.round(process.uptime()),
23
+ });
24
+ });
25
+
26
+ router.get("/ready", async (_req, res) => {
27
+ const [database, redis] = await Promise.all([
28
+ config.database.url
29
+ ? checkDatabase(config.database.url)
30
+ : Promise.resolve({ ok: true, skipped: true }),
31
+ config.redis.url ? checkRedis() : Promise.resolve({ ok: true, skipped: true }),
32
+ ]);
33
+
34
+ const ready = (!config.database.url || database.ok) && (!config.redis.url || redis.ok);
35
+
36
+ res.status(ready ? 200 : 503).json({
37
+ status: ready ? "ready" : "degraded",
38
+ checks: {
39
+ database,
40
+ redis,
41
+ mcp: { servers: mcp?.serverNames ?? [] },
42
+ },
43
+ });
44
+ });
45
+
46
+ return router;
47
+ };
@@ -0,0 +1,47 @@
1
+ import { Router } from "express";
2
+
3
+ import { createSessionSchema } from "../../schemas/session.js";
4
+ import type { SessionService } from "../../services/session.js";
5
+ import { parseRequest } from "../../utils/validation.js";
6
+
7
+ export interface SessionRouterDependencies {
8
+ sessions: SessionService;
9
+ }
10
+
11
+ const tenantFrom = (value: unknown): string => {
12
+ return typeof value === "string" && value.length > 0 ? value : "default";
13
+ };
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
+
20
+ export const createSessionRouter = ({ sessions }: SessionRouterDependencies): Router => {
21
+ const router = Router();
22
+
23
+ router.post("/", async (req, res) => {
24
+ const session = await sessions.create(parseRequest(createSessionSchema, req.body ?? {}));
25
+ res.status(201).json(session);
26
+ });
27
+
28
+ router.get("/", async (req, res) => {
29
+ const result = await sessions.list(tenantFrom(req.query.tenantId), limitFrom(req.query.limit));
30
+ res.json(result);
31
+ });
32
+
33
+ router.get("/:threadId", async (req, res) => {
34
+ res.json(await sessions.get(req.params.threadId, tenantFrom(req.query.tenantId)));
35
+ });
36
+
37
+ router.get("/:threadId/messages", async (req, res) => {
38
+ res.json({ messages: await sessions.history(req.params.threadId) });
39
+ });
40
+
41
+ router.delete("/:threadId", async (req, res) => {
42
+ await sessions.remove(req.params.threadId, tenantFrom(req.query.tenantId));
43
+ res.status(204).end();
44
+ });
45
+
46
+ return router;
47
+ };
@@ -0,0 +1,111 @@
1
+ import fs from "node:fs/promises";
2
+
3
+ import type { Express } from "express";
4
+
5
+ import { createSupervisorAgent } from "./agents/index.js";
6
+ import { createApiApp } from "./api/app.js";
7
+ import { createBackend } from "./backends/index.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";
13
+ import { createMemoryManager } from "./memory/index.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
+ import { loadSkills, validateSkills } from "./skills/index.js";
19
+ import { createDefaultTools } from "./tools/index.js";
20
+ import { createMcpToolRegistry } from "./tools/index.js";
21
+
22
+ export interface Application {
23
+ app: Express;
24
+ logger: Logger;
25
+ services: {
26
+ agent: AgentService;
27
+ sessions: SessionService;
28
+ memory: MemoryService;
29
+ };
30
+ close: () => Promise<void>;
31
+ }
32
+
33
+ /**
34
+ * 应用装配:配置 → 基础设施 → Agent 运行时 → 服务 → HTTP 应用。
35
+ * 这里不启动服务,因此测试、脚本和 HTTP 入口可以复用同一套装配。
36
+ */
37
+ export const createApplication = async (config: AppConfig = loadConfig()): Promise<Application> => {
38
+ const logger = createLogger(config);
39
+
40
+ await fs.mkdir(config.paths.workspaces, { recursive: true });
41
+ await fs.mkdir(config.paths.resources, { recursive: true });
42
+
43
+ const skills = await loadSkills({ rootDir: config.paths.skills });
44
+ for (const warning of validateSkills(skills)) {
45
+ logger.warn(warning);
46
+ }
47
+
48
+ logger.info({ skills: skills.map((skill) => skill.name) }, "技能加载完成");
49
+
50
+ const store = await createStore(config);
51
+ const checkpointer = await createCheckpointer(config);
52
+ const backend = await createBackend(config);
53
+ const mcp = await createMcpToolRegistry();
54
+
55
+ const tools = createDefaultTools({
56
+ workspaceRoot: config.paths.workspaces,
57
+ databaseUrl: config.database.url,
58
+ additionalTools: mcp.tools,
59
+ });
60
+
61
+ const agent = createSupervisorAgent({
62
+ config,
63
+ model: createChatModel(config.model),
64
+ backend: backend.backend,
65
+ checkpointer,
66
+ store,
67
+ logger,
68
+ tools,
69
+ });
70
+
71
+ const sessions = new SessionService({
72
+ graph: agent,
73
+ checkpointer,
74
+ store,
75
+ sandboxes: backend.sandboxes,
76
+ });
77
+ const agentService = new AgentService({ agent, config, sessions });
78
+ const memoryService = new MemoryService(createMemoryManager(store));
79
+
80
+ const app = createApiApp({
81
+ config,
82
+ logger,
83
+ mcp,
84
+ services: {
85
+ agent: agentService,
86
+ sessions,
87
+ memory: memoryService,
88
+ },
89
+ });
90
+
91
+ let closed = false;
92
+
93
+ return {
94
+ app,
95
+ logger,
96
+ services: {
97
+ agent: agentService,
98
+ sessions,
99
+ memory: memoryService,
100
+ },
101
+ close: async () => {
102
+ if (closed) return;
103
+ closed = true;
104
+
105
+ await mcp.close();
106
+ await backend.dispose();
107
+ await closeDatabase();
108
+ await closeRedis();
109
+ },
110
+ };
111
+ };
@@ -0,0 +1,34 @@
1
+ import { CompositeBackend, StateBackend, StoreBackend, type BackendProtocolV2 } from "deepagents";
2
+
3
+ import { createFilesystemBackend } from "./filesystem.js";
4
+
5
+ export interface CompositeBackendOptions {
6
+ defaultBackend?: BackendProtocolV2;
7
+ paths: {
8
+ workspaces: string;
9
+ resources: string;
10
+ skills: string;
11
+ };
12
+ }
13
+
14
+ /**
15
+ * 把 Agent 需要的所有资源挂载到同一个虚拟文件系统:
16
+ *
17
+ * /workspace/ 草稿与产物(落磁盘)
18
+ * /resources/ AGENTS.md 与只读知识库(落磁盘)
19
+ * /skills/ SKILL.md 目录(落磁盘)
20
+ * /memories/ 长期记忆(LangGraph BaseStore)
21
+ *
22
+ * 其余路径落到默认后端(默认是临时状态)。
23
+ */
24
+ export const createCompositeBackend = ({
25
+ defaultBackend = new StateBackend(),
26
+ paths,
27
+ }: CompositeBackendOptions): CompositeBackend => {
28
+ return new CompositeBackend(defaultBackend, {
29
+ "/workspace/": createFilesystemBackend({ rootDir: paths.workspaces }),
30
+ "/resources/": createFilesystemBackend({ rootDir: paths.resources }),
31
+ "/skills/": createFilesystemBackend({ rootDir: paths.skills }),
32
+ "/memories/": new StoreBackend(),
33
+ });
34
+ };
@@ -0,0 +1,19 @@
1
+ import { FilesystemBackend } from "deepagents";
2
+
3
+ export interface WorkspaceBackendOptions {
4
+ rootDir: string;
5
+ virtualMode?: boolean;
6
+ maxFileSizeMb?: number;
7
+ }
8
+
9
+ /**
10
+ * 虚拟路径被限制在 `rootDir` 内的文件系统后端。
11
+ * Agent 看到的是 `/notes.md`,实际文件位于 `<rootDir>/notes.md`。
12
+ */
13
+ export const createFilesystemBackend = ({
14
+ rootDir,
15
+ virtualMode = true,
16
+ maxFileSizeMb = 10,
17
+ }: WorkspaceBackendOptions): FilesystemBackend => {
18
+ return new FilesystemBackend({ rootDir, virtualMode, maxFileSizeMb });
19
+ };
@@ -0,0 +1,76 @@
1
+ import {
2
+ CompositeBackend,
3
+ StateBackend,
4
+ StoreBackend,
5
+ type AnyBackendProtocol,
6
+ type BackendFactory,
7
+ } from "deepagents";
8
+
9
+ import type { AppConfig } from "../config/index.js";
10
+ import { SandboxManager, threadIdFromRuntime } from "../sandbox/index.js";
11
+ import { createCompositeBackend } from "./composite.js";
12
+ import { createFilesystemBackend } from "./filesystem.js";
13
+ import { createSandboxBackend } from "./sandbox.js";
14
+
15
+ export interface BackendBundle {
16
+ /** 普通后端实例,或按运行时(会话)动态解析的工厂。 */
17
+ backend: AnyBackendProtocol | BackendFactory;
18
+ /** `SANDBOX_ENABLED=true` 时存在,用于删除会话时释放对应沙箱。 */
19
+ sandboxes?: SandboxManager;
20
+ dispose: () => Promise<void>;
21
+ }
22
+
23
+ /**
24
+ * 构建主 Agent 和所有子 Agent 共用的后端。
25
+ *
26
+ * `SANDBOX_ENABLED=true` 时返回一个工厂:按 `threadId` 为每个会话惰性创建并复用
27
+ * 一个 OpenSandbox 沙箱(`/workspace/` 与 `execute` 落在沙箱内),
28
+ * `/resources/`、`/skills/` 仍读本地只读文件,`/memories/` 继续使用 LangGraph store。
29
+ * 未开启时回退到本地文件系统后端,`ENABLE_SHELL=true` 时再挂上宿主机 shell。
30
+ */
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
+
54
+ const rootDir = config.paths.workspaces;
55
+ const shell = config.agent.enableShell ? await createSandboxBackend({ rootDir }) : null;
56
+
57
+ const backend = createCompositeBackend({
58
+ ...(shell ? { defaultBackend: shell } : {}),
59
+ paths: {
60
+ workspaces: config.paths.workspaces,
61
+ resources: config.paths.resources,
62
+ skills: config.paths.skills,
63
+ },
64
+ });
65
+
66
+ return {
67
+ backend,
68
+ dispose: async () => {
69
+ await shell?.close();
70
+ },
71
+ };
72
+ };
73
+
74
+ export { createCompositeBackend } from "./composite.js";
75
+ export { createFilesystemBackend } from "./filesystem.js";
76
+ export { createSandboxBackend } from "./sandbox.js";
@@ -0,0 +1,33 @@
1
+ import { LocalShellBackend } from "deepagents";
2
+
3
+ export interface SandboxBackendOptions {
4
+ rootDir: string;
5
+ virtualMode?: boolean;
6
+ timeoutSeconds?: number;
7
+ maxOutputBytes?: number;
8
+ }
9
+
10
+ /**
11
+ * 本地 shell 后端。在文件系统工具之上增加 `execute` 工具,
12
+ * 命令会以当前进程的权限在宿主机执行。
13
+ *
14
+ * 生产环境请保持 ENABLE_SHELL=false,或替换为真正的沙箱
15
+ * (LangSmithSandbox、容器、远程执行器等)。
16
+ */
17
+ export const createSandboxBackend = async ({
18
+ rootDir,
19
+ virtualMode = true,
20
+ timeoutSeconds = 60,
21
+ maxOutputBytes = 100_000,
22
+ }: SandboxBackendOptions): Promise<LocalShellBackend> => {
23
+ const backend = new LocalShellBackend({
24
+ rootDir,
25
+ virtualMode,
26
+ timeout: timeoutSeconds,
27
+ maxOutputBytes,
28
+ });
29
+
30
+ await backend.initialize();
31
+
32
+ return backend;
33
+ };
@@ -0,0 +1,37 @@
1
+ import type { Env } from "./env.js";
2
+
3
+ export type ApprovalMode = Env["APPROVAL_MODE"];
4
+
5
+ export interface AgentConfig {
6
+ /** Agent 名称,出现在提示词和链路追踪中。 */
7
+ name: string;
8
+ /** Agent 职责的可读描述。 */
9
+ description: string;
10
+ /** 每次运行允许的最大 LangGraph 超级步数。 */
11
+ recursionLimit: number;
12
+ /** 哪些工具调用需要通过 `interruptOn` 等待人工审批。 */
13
+ approvals: ApprovalMode;
14
+ /** 挂载可执行 shell 的后端并暴露 `execute` 工具。 */
15
+ enableShell: boolean;
16
+ /** 加载进系统提示词的 AGENTS.md 文件。 */
17
+ memoryFiles: string[];
18
+ /** 扫描 `SKILL.md` 的后端目录。 */
19
+ skillDirectories: string[];
20
+ /** 追加到主 Agent 提示词末尾的额外说明。 */
21
+ systemPromptAppendix?: string;
22
+ }
23
+
24
+ export const DEFAULT_AGENT_DESCRIPTION =
25
+ "负责规划任务、把工作分派给专职子 Agent,并维护工作区文件的主 Agent。";
26
+
27
+ export const resolveAgentConfig = (env: Env): AgentConfig => {
28
+ return {
29
+ name: env.AGENT_NAME,
30
+ description: DEFAULT_AGENT_DESCRIPTION,
31
+ recursionLimit: env.AGENT_RECURSION_LIMIT,
32
+ approvals: env.APPROVAL_MODE,
33
+ enableShell: env.ENABLE_SHELL,
34
+ memoryFiles: ["/resources/AGENTS.md"],
35
+ skillDirectories: ["/skills/"],
36
+ };
37
+ };
@@ -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
+ };