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
@@ -0,0 +1,82 @@
1
+ /**
2
+ * OpenAI 兼容服务商预设。
3
+ *
4
+ * 模板统一通过 OpenAI 兼容协议(`POST {baseUrl}/chat/completions`)接入模型,
5
+ * 因此这里只维护各家的接口地址与默认模型。只要服务实现了同一套协议,
6
+ * 增加一个预设就能接入,不需要引入新的 SDK。
7
+ */
8
+ export const MODEL_PROVIDERS = [
9
+ "openai",
10
+ "deepseek",
11
+ "moonshot",
12
+ "minimax",
13
+ "qwen",
14
+ "zhipu",
15
+ "openrouter",
16
+ "ollama",
17
+ "vllm",
18
+ "custom",
19
+ ] as const;
20
+
21
+ export type ModelProvider = (typeof MODEL_PROVIDERS)[number];
22
+
23
+ export interface ModelPreset {
24
+ /** 展示用名称,出现在日志与文档中。 */
25
+ label: string;
26
+ /** 兼容 OpenAI 的接口地址;留空表示必须由 `MODEL_BASE_URL` 指定。 */
27
+ baseUrl: string;
28
+ /** 未设置 `MODEL_NAME` 时使用的模型名;留空表示必须显式指定。 */
29
+ defaultModel?: string;
30
+ }
31
+
32
+ export const OPENAI_COMPATIBLE_PRESETS: Record<ModelProvider, ModelPreset> = {
33
+ openai: {
34
+ label: "OpenAI",
35
+ baseUrl: "https://api.openai.com/v1",
36
+ defaultModel: "gpt-4.1-mini",
37
+ },
38
+ deepseek: {
39
+ label: "DeepSeek",
40
+ baseUrl: "https://api.deepseek.com/v1",
41
+ defaultModel: "deepseek-chat",
42
+ },
43
+ moonshot: {
44
+ label: "Moonshot Kimi",
45
+ baseUrl: "https://api.moonshot.cn/v1",
46
+ defaultModel: "kimi-latest",
47
+ },
48
+ minimax: {
49
+ label: "MiniMax",
50
+ // 国内站为 api.minimaxi.com,国际站使用 https://api.minimax.io/v1。
51
+ baseUrl: "https://api.minimaxi.com/v1",
52
+ defaultModel: "MiniMax-M3",
53
+ },
54
+ qwen: {
55
+ label: "通义千问(阿里云百炼)",
56
+ baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
57
+ defaultModel: "qwen-plus",
58
+ },
59
+ zhipu: {
60
+ label: "智谱 GLM",
61
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
62
+ defaultModel: "glm-4.6",
63
+ },
64
+ openrouter: {
65
+ label: "OpenRouter",
66
+ baseUrl: "https://openrouter.ai/api/v1",
67
+ defaultModel: "openai/gpt-4.1-mini",
68
+ },
69
+ ollama: {
70
+ label: "Ollama(本地)",
71
+ baseUrl: "http://localhost:11434/v1",
72
+ defaultModel: "qwen3:8b",
73
+ },
74
+ vllm: {
75
+ label: "vLLM(本地)",
76
+ baseUrl: "http://localhost:8000/v1",
77
+ },
78
+ custom: {
79
+ label: "自定义 OpenAI 兼容服务",
80
+ baseUrl: "",
81
+ },
82
+ };
@@ -0,0 +1,30 @@
1
+ import type { Env } from "../config/env.js";
2
+
3
+ export interface SandboxConfig {
4
+ /** 是否启用 OpenSandbox:开启后按会话(threadId)惰性创建并复用沙箱。 */
5
+ enabled: boolean;
6
+ /** OpenSandbox 服务地址(host:port)。 */
7
+ domain: string;
8
+ protocol: "http" | "https";
9
+ apiKey?: string;
10
+ /** 共享模式:设置后所有会话连接同一个已有沙箱,而不是按会话新建。 */
11
+ sandboxId?: string;
12
+ image: string;
13
+ /** 沙箱 TTL(秒):使用中按 TTL/3 自动续期;留空(0)表示不设置服务端 TTL。 */
14
+ timeoutSeconds?: number;
15
+ /** 沙箱内的工作目录,也是 execute 的默认 cwd。 */
16
+ workspaceRoot: string;
17
+ }
18
+
19
+ export const resolveSandboxConfig = (env: Env): SandboxConfig => {
20
+ return {
21
+ enabled: env.SANDBOX_ENABLED,
22
+ domain: env.OPEN_SANDBOX_DOMAIN,
23
+ protocol: env.OPEN_SANDBOX_PROTOCOL,
24
+ ...(env.OPEN_SANDBOX_API_KEY ? { apiKey: env.OPEN_SANDBOX_API_KEY } : {}),
25
+ ...(env.OPEN_SANDBOX_ID ? { sandboxId: env.OPEN_SANDBOX_ID } : {}),
26
+ image: env.SANDBOX_IMAGE,
27
+ ...(env.SANDBOX_TIMEOUT_SECONDS > 0 ? { timeoutSeconds: env.SANDBOX_TIMEOUT_SECONDS } : {}),
28
+ workspaceRoot: env.SANDBOX_WORKSPACE_ROOT,
29
+ };
30
+ };
@@ -0,0 +1,7 @@
1
+ export { resolveSandboxConfig, type SandboxConfig } from "./config.js";
2
+ export { SandboxManager, threadIdFromRuntime, type SandboxManagerOptions } from "./manager.js";
3
+ export {
4
+ createOpenSandboxBackend,
5
+ OpenSandboxBackend,
6
+ type OpenSandboxBackendOptions,
7
+ } from "./opensandbox.js";
@@ -0,0 +1,176 @@
1
+ import { SandboxApiException } from "@alibaba-group/opensandbox";
2
+
3
+ import { errorMessage, isRecord } from "../utils/helpers.js";
4
+ import type { SandboxConfig } from "./config.js";
5
+ import { createOpenSandboxBackend, type OpenSandboxBackend } from "./opensandbox.js";
6
+
7
+ export interface SandboxManagerOptions {
8
+ /** 便于测试替换沙箱创建逻辑。 */
9
+ create?: (config: SandboxConfig) => Promise<OpenSandboxBackend>;
10
+ /** 便于测试替换时钟。 */
11
+ now?: () => number;
12
+ }
13
+
14
+ /** 从工具运行时中取出会话 ID;memory/skills 中间件只传 state 时返回 undefined。 */
15
+ export const threadIdFromRuntime = (runtime: unknown): string | undefined => {
16
+ if (!isRecord(runtime)) return undefined;
17
+
18
+ const context = runtime.context;
19
+ if (isRecord(context) && typeof context.threadId === "string" && context.threadId !== "") {
20
+ return context.threadId;
21
+ }
22
+
23
+ const config = runtime.config;
24
+ if (!isRecord(config)) return undefined;
25
+
26
+ const configurable = config.configurable;
27
+ if (!isRecord(configurable)) return undefined;
28
+
29
+ const threadId = configurable.thread_id;
30
+ return typeof threadId === "string" && threadId !== "" ? threadId : undefined;
31
+ };
32
+
33
+ /** 续期节奏:TTL 的 1/3,且不少于 1 秒。 */
34
+ const renewIntervalMs = (timeoutSeconds: number): number =>
35
+ Math.max(1_000, (timeoutSeconds * 1_000) / 3);
36
+
37
+ /** 判断沙箱是否已被服务端回收(过期、被 kill 或已不存在)。 */
38
+ const isGone = (error: unknown): boolean => {
39
+ if (error instanceof SandboxApiException && error.statusCode === 404) return true;
40
+
41
+ const message = errorMessage(error).toLowerCase();
42
+ return ["not found", "no such", "terminated", "expired", "killed"].some((hint) =>
43
+ message.includes(hint),
44
+ );
45
+ };
46
+
47
+ /**
48
+ * 按会话管理 OpenSandbox 沙箱。
49
+ *
50
+ * - 默认每个 `threadId` 首次使用时创建一个沙箱,该会话后续的消息、工具调用
51
+ * 与子 Agent 都复用同一个后端;
52
+ * - 配置了 `SANDBOX_TIMEOUT_SECONDS` 时,每次使用间隔超过 TTL 的 1/3 会调用
53
+ * `renew` 续期,活跃会话不会被服务端回收;续期发现沙箱已不存在时自动重建;
54
+ * - 配置 `OPEN_SANDBOX_ID` 时退化为「所有会话共享一个已存在的沙箱」,不续期;
55
+ * - 删除会话时调用 `release(threadId)`,进程退出时 `closeAll()`。
56
+ */
57
+ export class SandboxManager {
58
+ private readonly config: SandboxConfig;
59
+ private readonly createSandbox: (config: SandboxConfig) => Promise<OpenSandboxBackend>;
60
+ private readonly now: () => number;
61
+ private readonly sandboxes = new Map<string, Promise<OpenSandboxBackend>>();
62
+ private readonly renewedAt = new Map<string, number>();
63
+ private shared: Promise<OpenSandboxBackend> | undefined;
64
+
65
+ constructor(
66
+ config: SandboxConfig,
67
+ { create = createOpenSandboxBackend, now = Date.now }: SandboxManagerOptions = {},
68
+ ) {
69
+ this.config = config;
70
+ this.createSandbox = create;
71
+ this.now = now;
72
+ }
73
+
74
+ /** 当前持有(或正在创建)的沙箱数量。 */
75
+ get size(): number {
76
+ return this.sandboxes.size + (this.shared ? 1 : 0);
77
+ }
78
+
79
+ get(threadId: string): Promise<OpenSandboxBackend> {
80
+ if (this.config.sandboxId) {
81
+ this.shared ??= this.createSandbox(this.config).catch((error: unknown) => {
82
+ this.shared = undefined;
83
+ throw error;
84
+ });
85
+
86
+ return this.shared;
87
+ }
88
+
89
+ const existing = this.sandboxes.get(threadId);
90
+ if (existing) return this.keepAlive(threadId, existing);
91
+
92
+ return this.create(threadId);
93
+ }
94
+
95
+ /** 释放某个会话的沙箱;共享沙箱模式下不处理。 */
96
+ async release(threadId: string): Promise<void> {
97
+ if (this.config.sandboxId) return;
98
+
99
+ const pending = this.sandboxes.get(threadId);
100
+ this.sandboxes.delete(threadId);
101
+ this.renewedAt.delete(threadId);
102
+ if (!pending) return;
103
+
104
+ const sandbox = await pending.catch(() => undefined);
105
+ await sandbox?.destroy();
106
+ }
107
+
108
+ /** 关闭所有沙箱(应用退出时调用)。 */
109
+ async closeAll(): Promise<void> {
110
+ const pending = this.config.sandboxId ? [this.shared] : [...this.sandboxes.values()];
111
+
112
+ this.shared = undefined;
113
+ this.sandboxes.clear();
114
+ this.renewedAt.clear();
115
+
116
+ const sandboxes = await Promise.all(
117
+ pending.map((item) => item?.catch(() => undefined) ?? Promise.resolve(undefined)),
118
+ );
119
+
120
+ await Promise.all(sandboxes.map((sandbox) => sandbox?.destroy() ?? Promise.resolve()));
121
+ }
122
+
123
+ private create(threadId: string): Promise<OpenSandboxBackend> {
124
+ const created = this.createSandbox(this.config)
125
+ .then((sandbox) => {
126
+ this.renewedAt.set(threadId, this.now());
127
+ return sandbox;
128
+ })
129
+ .catch((error: unknown) => {
130
+ this.sandboxes.delete(threadId);
131
+ this.renewedAt.delete(threadId);
132
+ throw error;
133
+ });
134
+
135
+ this.sandboxes.set(threadId, created);
136
+ return created;
137
+ }
138
+
139
+ /**
140
+ * 使用中的沙箱按 TTL 的 1/3 续期,避免活跃会话被过期回收;
141
+ * 续期失败但沙箱仍在时继续复用,确认已被回收时重建。
142
+ */
143
+ private keepAlive(
144
+ threadId: string,
145
+ pending: Promise<OpenSandboxBackend>,
146
+ ): Promise<OpenSandboxBackend> {
147
+ const timeoutSeconds = this.config.timeoutSeconds;
148
+ if (!timeoutSeconds) return pending;
149
+
150
+ const now = this.now();
151
+ const renewedAt = this.renewedAt.get(threadId) ?? 0;
152
+ if (now - renewedAt < renewIntervalMs(timeoutSeconds)) return pending;
153
+
154
+ this.renewedAt.set(threadId, now);
155
+
156
+ return pending.then(async (sandbox) => {
157
+ return sandbox.renew(timeoutSeconds).then(
158
+ () => sandbox,
159
+ (error: unknown) => {
160
+ if (!isGone(error)) return sandbox;
161
+
162
+ return this.rebuild(threadId, sandbox);
163
+ },
164
+ );
165
+ });
166
+ }
167
+
168
+ /** 丢弃已失效的沙箱并立即创建一个新的。 */
169
+ private rebuild(threadId: string, stale: OpenSandboxBackend): Promise<OpenSandboxBackend> {
170
+ this.sandboxes.delete(threadId);
171
+ this.renewedAt.delete(threadId);
172
+ void stale.destroy().catch(() => undefined);
173
+
174
+ return this.create(threadId);
175
+ }
176
+ }
@@ -0,0 +1,216 @@
1
+ import {
2
+ ConnectionConfig,
3
+ Sandbox,
4
+ SandboxApiException,
5
+ type CommandExecution,
6
+ } from "@alibaba-group/opensandbox";
7
+ import {
8
+ BaseSandbox,
9
+ type ExecuteResponse,
10
+ type FileDownloadResponse,
11
+ type FileOperationError,
12
+ type FileUploadResponse,
13
+ } from "deepagents";
14
+
15
+ import { errorMessage } from "../utils/helpers.js";
16
+ import type { SandboxConfig } from "./config.js";
17
+
18
+ const MAX_OUTPUT_CHARS = 100_000;
19
+
20
+ export interface OpenSandboxBackendOptions {
21
+ sandbox: Sandbox;
22
+ workspaceRoot?: string;
23
+ /** 沙箱是否由当前进程创建;复用已有沙箱时设为 false,销毁时只关闭连接。 */
24
+ owned?: boolean;
25
+ }
26
+
27
+ const parentDirectory = (filePath: string): string => {
28
+ const index = filePath.lastIndexOf("/");
29
+ return index <= 0 ? "/" : filePath.slice(0, index);
30
+ };
31
+
32
+ const fileError = (error: unknown): FileOperationError => {
33
+ if (error instanceof SandboxApiException) {
34
+ if (error.statusCode === 404) return "file_not_found";
35
+ if (error.statusCode === 403) return "permission_denied";
36
+ if (error.statusCode === 400) return "invalid_path";
37
+ }
38
+
39
+ const message = errorMessage(error).toLowerCase();
40
+ if (message.includes("not found") || message.includes("no such file")) return "file_not_found";
41
+ if (message.includes("permission")) return "permission_denied";
42
+ if (message.includes("directory")) return "is_directory";
43
+
44
+ return "invalid_path";
45
+ };
46
+
47
+ const isMissingSession = (error: unknown): boolean => {
48
+ if (error instanceof SandboxApiException && error.statusCode === 404) return true;
49
+
50
+ const message = errorMessage(error).toLowerCase();
51
+ return (
52
+ message.includes("session") &&
53
+ ["not found", "expired", "invalid"].some((hint) => message.includes(hint))
54
+ );
55
+ };
56
+
57
+ const formatExecution = (execution: CommandExecution): ExecuteResponse => {
58
+ const stdout = execution.logs.stdout.map((message) => message.text);
59
+ const stderr = execution.logs.stderr.map((message) => `[stderr] ${message.text}`);
60
+ const output = [...stdout, ...stderr].join("\n");
61
+ const truncated = output.length > MAX_OUTPUT_CHARS;
62
+ const exitCode = execution.exitCode ?? execution.error?.exitCode ?? (execution.error ? 1 : 0);
63
+
64
+ return {
65
+ output: truncated ? `${output.slice(0, MAX_OUTPUT_CHARS)}\n… 输出已截断` : output,
66
+ exitCode,
67
+ truncated,
68
+ };
69
+ };
70
+
71
+ /**
72
+ * 把 OpenSandbox 沙箱接入 deepagents。
73
+ *
74
+ * 一个后端实例持有同一个远程沙箱:`execute` 在沙箱内维护一个持久 bash session,
75
+ * 因此 `cd`、`export`、函数定义等状态会跨命令保留;命令按顺序串行执行,
76
+ * 避免并发命令互相覆盖 shell 状态。文件读写仍走 `sandbox.files`,
77
+ * `ls` / `read` / `grep` / `glob` / `edit` 由 `BaseSandbox` 复用 session 完成。
78
+ */
79
+ export class OpenSandboxBackend extends BaseSandbox {
80
+ readonly id: string;
81
+
82
+ private readonly sandbox: Sandbox;
83
+ private readonly workspaceRoot: string;
84
+ private readonly owned: boolean;
85
+
86
+ private session: Promise<string> | undefined;
87
+ private queue: Promise<void> = Promise.resolve();
88
+
89
+ constructor({ sandbox, workspaceRoot = "/workspace", owned = true }: OpenSandboxBackendOptions) {
90
+ super();
91
+ this.sandbox = sandbox;
92
+ this.workspaceRoot = workspaceRoot;
93
+ this.owned = owned;
94
+ this.id = sandbox.id;
95
+ }
96
+
97
+ execute(command: string): Promise<ExecuteResponse> {
98
+ const result = this.queue.then(() => this.runInSession(command));
99
+
100
+ this.queue = result.then(
101
+ () => undefined,
102
+ () => undefined,
103
+ );
104
+
105
+ return result;
106
+ }
107
+
108
+ async uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]> {
109
+ return Promise.all(
110
+ files.map(([filePath, content]) => {
111
+ const directory = parentDirectory(filePath);
112
+ const prepare = directory === "/" ? Promise.resolve() : this.ensureDirectory(directory);
113
+
114
+ return prepare
115
+ .then(() =>
116
+ this.sandbox.files.writeFiles([{ path: filePath, data: content, mode: 0o644 }]),
117
+ )
118
+ .then(
119
+ () => ({ path: filePath, error: null }),
120
+ (error: unknown) => ({ path: filePath, error: fileError(error) }),
121
+ );
122
+ }),
123
+ );
124
+ }
125
+
126
+ async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {
127
+ return Promise.all(
128
+ paths.map((filePath) => {
129
+ return this.sandbox.files.readBytes(filePath).then(
130
+ (content) => ({ path: filePath, content, error: null }),
131
+ (error: unknown) => ({ path: filePath, content: null, error: fileError(error) }),
132
+ );
133
+ }),
134
+ );
135
+ }
136
+
137
+ /** 续期沙箱 TTL;服务端已回收时抛错(通常 404),由 SandboxManager 决定是否重建。 */
138
+ async renew(timeoutSeconds: number): Promise<void> {
139
+ await this.sandbox.renew(timeoutSeconds);
140
+ }
141
+
142
+ /** 关闭会话、终止(仅限自建)沙箱并释放 SDK 连接资源。 */
143
+ async destroy(): Promise<void> {
144
+ const session = await this.session?.catch(() => undefined);
145
+ if (session) {
146
+ await this.sandbox.commands.deleteSession(session).catch(() => undefined);
147
+ }
148
+
149
+ if (this.owned) {
150
+ await this.sandbox.kill().catch(() => undefined);
151
+ }
152
+
153
+ await this.sandbox.close().catch(() => undefined);
154
+ }
155
+
156
+ private runInSession(command: string): Promise<ExecuteResponse> {
157
+ return this.executeInSession(command).catch((error: unknown) => {
158
+ if (!isMissingSession(error)) throw error;
159
+
160
+ this.session = undefined;
161
+ return this.executeInSession(command);
162
+ });
163
+ }
164
+
165
+ private async executeInSession(command: string): Promise<ExecuteResponse> {
166
+ const sessionId = await this.ensureSession();
167
+ const execution = await this.sandbox.commands.runInSession(sessionId, command);
168
+
169
+ return formatExecution(execution);
170
+ }
171
+
172
+ private ensureSession(): Promise<string> {
173
+ this.session ??= this.sandbox.commands
174
+ .createSession({ workingDirectory: this.workspaceRoot })
175
+ .catch((error: unknown) => {
176
+ this.session = undefined;
177
+ throw error;
178
+ });
179
+
180
+ return this.session;
181
+ }
182
+
183
+ private ensureDirectory(directory: string): Promise<void> {
184
+ return this.sandbox.files.createDirectories([{ path: directory, mode: 0o755 }]);
185
+ }
186
+ }
187
+
188
+ /** 创建(或连接)OpenSandbox 沙箱,并预热工作目录。 */
189
+ export const createOpenSandboxBackend = async (
190
+ config: SandboxConfig,
191
+ ): Promise<OpenSandboxBackend> => {
192
+ const connectionConfig = new ConnectionConfig({
193
+ domain: config.domain,
194
+ protocol: config.protocol,
195
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
196
+ });
197
+
198
+ const sandbox = config.sandboxId
199
+ ? await Sandbox.connect({ connectionConfig, sandboxId: config.sandboxId })
200
+ : await Sandbox.create({
201
+ connectionConfig,
202
+ image: config.image,
203
+ timeoutSeconds: config.timeoutSeconds ?? null,
204
+ });
205
+
206
+ const owned = !config.sandboxId;
207
+
208
+ return sandbox.files.createDirectories([{ path: config.workspaceRoot, mode: 0o755 }]).then(
209
+ () => new OpenSandboxBackend({ sandbox, workspaceRoot: config.workspaceRoot, owned }),
210
+ async (error: unknown) => {
211
+ if (owned) await sandbox.kill().catch(() => undefined);
212
+ await sandbox.close().catch(() => undefined);
213
+ throw error;
214
+ },
215
+ );
216
+ };
@@ -2,11 +2,11 @@ import { randomUUID } from "node:crypto";
2
2
 
3
3
  import { Command } from "@langchain/langgraph";
4
4
 
5
- import type { CompiledAgent } from "../graph/compile.js";
5
+ import type { CompiledAgent } from "../graph/index.js";
6
6
  import type { AppConfig } from "../config/index.js";
7
7
  import type { InvokeAgentInput, ResumeAgentInput } from "../schemas/agent.js";
8
8
  import { lastMessageText } from "../utils/helpers.js";
9
- import type { SessionService } from "./session.service.js";
9
+ import type { SessionService } from "./session.js";
10
10
 
11
11
  export interface AgentServiceDependencies {
12
12
  agent: CompiledAgent;
@@ -36,30 +36,30 @@ export interface RunOptions {
36
36
  * 并把结果整理为适合 HTTP 客户端的形式。
37
37
  */
38
38
  export class AgentService {
39
- readonly #agent: CompiledAgent;
40
- readonly #config: AppConfig;
41
- readonly #sessions?: SessionService;
39
+ private readonly agent: CompiledAgent;
40
+ private readonly config: AppConfig;
41
+ private readonly sessions?: SessionService;
42
42
 
43
43
  constructor({ agent, config, sessions }: AgentServiceDependencies) {
44
- this.#agent = agent;
45
- this.#config = config;
46
- this.#sessions = sessions;
44
+ this.agent = agent;
45
+ this.config = config;
46
+ this.sessions = sessions;
47
47
  }
48
48
 
49
49
  get graph(): CompiledAgent {
50
- return this.#agent;
50
+ return this.agent;
51
51
  }
52
52
 
53
53
  async invoke(input: InvokeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
54
54
  const threadId = input.threadId ?? randomUUID();
55
55
 
56
- await this.#sessions?.ensure({
56
+ await this.sessions?.ensure({
57
57
  threadId,
58
58
  tenantId: input.tenantId,
59
59
  ...(input.userId ? { userId: input.userId } : {}),
60
60
  });
61
61
 
62
- const result = await this.#agent.invoke(
62
+ const result = await this.agent.invoke(
63
63
  {
64
64
  messages: [{ role: "user", content: input.message }],
65
65
  tenantId: input.tenantId,
@@ -68,7 +68,7 @@ export class AgentService {
68
68
  },
69
69
  {
70
70
  configurable: { thread_id: threadId },
71
- recursionLimit: this.#config.agent.recursionLimit,
71
+ recursionLimit: this.config.agent.recursionLimit,
72
72
  context: {
73
73
  tenantId: input.tenantId,
74
74
  ...(input.userId ? { userId: input.userId } : {}),
@@ -78,7 +78,7 @@ export class AgentService {
78
78
  },
79
79
  );
80
80
 
81
- return this.#finish(threadId, input.tenantId, result);
81
+ return this.finish(threadId, input.tenantId, result);
82
82
  }
83
83
 
84
84
  /**
@@ -86,11 +86,11 @@ export class AgentService {
86
86
  * (approve、reject 或 respond)。
87
87
  */
88
88
  async resume(input: ResumeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
89
- const result = await this.#agent.invoke(
89
+ const result = await this.agent.invoke(
90
90
  new Command({ resume: { decisions: input.decisions } }),
91
91
  {
92
92
  configurable: { thread_id: input.threadId },
93
- recursionLimit: this.#config.agent.recursionLimit,
93
+ recursionLimit: this.config.agent.recursionLimit,
94
94
  context: {
95
95
  tenantId: input.tenantId,
96
96
  ...(input.userId ? { userId: input.userId } : {}),
@@ -100,10 +100,10 @@ export class AgentService {
100
100
  },
101
101
  );
102
102
 
103
- return this.#finish(input.threadId, input.tenantId, result);
103
+ return this.finish(input.threadId, input.tenantId, result);
104
104
  }
105
105
 
106
- async #finish(
106
+ private async finish(
107
107
  threadId: string,
108
108
  tenantId: string,
109
109
  result: { messages?: unknown[]; __interrupt__?: unknown },
@@ -112,7 +112,7 @@ export class AgentService {
112
112
  const text = lastMessageText(messages);
113
113
  const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
114
114
 
115
- await this.#sessions?.touch({
115
+ await this.sessions?.touch({
116
116
  threadId,
117
117
  tenantId,
118
118
  lastMessage: text,
@@ -133,13 +133,13 @@ export class AgentService {
133
133
  ): AsyncGenerator<AgentStreamEvent> {
134
134
  const threadId = input.threadId ?? randomUUID();
135
135
 
136
- await this.#sessions?.ensure({
136
+ await this.sessions?.ensure({
137
137
  threadId,
138
138
  tenantId: input.tenantId,
139
139
  ...(input.userId ? { userId: input.userId } : {}),
140
140
  });
141
141
 
142
- const stream = await this.#agent.stream(
142
+ const stream = await this.agent.stream(
143
143
  {
144
144
  messages: [{ role: "user", content: input.message }],
145
145
  tenantId: input.tenantId,
@@ -148,7 +148,7 @@ export class AgentService {
148
148
  },
149
149
  {
150
150
  configurable: { thread_id: threadId },
151
- recursionLimit: this.#config.agent.recursionLimit,
151
+ recursionLimit: this.config.agent.recursionLimit,
152
152
  streamMode: "values",
153
153
  context: {
154
154
  tenantId: input.tenantId,
@@ -165,6 +165,6 @@ export class AgentService {
165
165
  }
166
166
 
167
167
  async state(threadId: string): Promise<unknown> {
168
- return this.#agent.getState({ configurable: { thread_id: threadId } });
168
+ return this.agent.getState({ configurable: { thread_id: threadId } });
169
169
  }
170
170
  }
@@ -13,31 +13,31 @@ export interface RememberInput {
13
13
  * 让路由层不需要了解命名空间和 store 细节。
14
14
  */
15
15
  export class MemoryService {
16
- readonly #memory: MemoryManager;
16
+ private readonly memory: MemoryManager;
17
17
 
18
18
  constructor(memory: MemoryManager) {
19
- this.#memory = memory;
19
+ this.memory = memory;
20
20
  }
21
21
 
22
22
  async remember({ tenantId, userId, key, value, kind = "fact" }: RememberInput): Promise<void> {
23
23
  const target = { tenantId, ...(userId ? { userId } : {}) };
24
24
 
25
25
  if (kind === "preference") {
26
- await this.#memory.rememberPreference(target, key, value);
26
+ await this.memory.rememberPreference(target, key, value);
27
27
  } else {
28
- await this.#memory.rememberFact(target, key, value);
28
+ await this.memory.rememberFact(target, key, value);
29
29
  }
30
30
  }
31
31
 
32
32
  async recall(tenantId: string, key: string, userId?: string): Promise<MemoryRecord | null> {
33
- return this.#memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
33
+ return this.memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
34
34
  }
35
35
 
36
36
  async list(tenantId: string, userId?: string, limit = 50): Promise<MemoryRecord[]> {
37
- return this.#memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
37
+ return this.memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
38
38
  }
39
39
 
40
40
  async forget(tenantId: string, key: string, userId?: string): Promise<void> {
41
- await this.#memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
41
+ await this.memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
42
42
  }
43
43
  }