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,61 @@
1
+ import { ToolMessage } from "@langchain/core/messages";
2
+ import { createMiddleware } from "langchain";
3
+
4
+ /**
5
+ * 针对破坏性 shell/SQL 载荷的启发式规则。这是纵深防御,不是沙箱:
6
+ * 请以最小权限运行 Agent。
7
+ */
8
+ export const DANGEROUS_PATTERNS: ReadonlyArray<{
9
+ pattern: RegExp;
10
+ reason: string;
11
+ }> = [
12
+ {
13
+ pattern: /\brm\s+-(?:[a-z]*r[a-z]*f|[a-z]*f[a-z]*r)\s+\/(?:\s|$)/i,
14
+ reason: "递归删除根目录",
15
+ },
16
+ { pattern: /\bmkfs(?:\.\w+)?\b/i, reason: "格式化文件系统" },
17
+ { pattern: /:\(\)\s*\{\s*:\|:\s*&\s*\};:/, reason: "fork 炸弹" },
18
+ { pattern: /\bdd\s+if=.*\bof=\/dev\/[sh]d/i, reason: "直接写磁盘" },
19
+ {
20
+ pattern: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|k)?sh\b/i,
21
+ reason: "把下载内容管道给 shell 执行",
22
+ },
23
+ { pattern: /\bchmod\s+-R\s+777\s+\//i, reason: "根目录权限设为 777" },
24
+ { pattern: /\bshutdown\b|\breboot\b/i, reason: "关闭主机" },
25
+ { pattern: /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i, reason: "破坏性 SQL" },
26
+ { pattern: /\bTRUNCATE\s+TABLE\b/i, reason: "破坏性 SQL" },
27
+ ];
28
+
29
+ export const findSecurityViolation = (value: string): string | null => {
30
+ for (const { pattern, reason } of DANGEROUS_PATTERNS) {
31
+ if (pattern.test(value)) return reason;
32
+ }
33
+
34
+ return null;
35
+ };
36
+
37
+ /**
38
+ * 在工具执行前拒绝危险参数。模型会收到一条解释拦截原因的工具消息,
39
+ * 从而改用更安全的方式。
40
+ */
41
+ export const createSecurityMiddleware = () => {
42
+ return createMiddleware({
43
+ name: "SecurityMiddleware",
44
+
45
+ wrapToolCall: async (request, handler) => {
46
+ const serializedArgs = JSON.stringify(request.toolCall.args ?? {});
47
+ const violation = findSecurityViolation(serializedArgs);
48
+
49
+ if (violation) {
50
+ return new ToolMessage({
51
+ content: `已被安全策略拦截:${violation}。请选择更安全的方式。`,
52
+ tool_call_id: request.toolCall.id ?? "未知",
53
+ name: request.toolCall.name,
54
+ status: "error",
55
+ });
56
+ }
57
+
58
+ return handler(request);
59
+ },
60
+ });
61
+ };
@@ -0,0 +1,56 @@
1
+ import type { Env } from "../config/index.js";
2
+ import { ConfigurationError } from "../utils/errors.js";
3
+ import { OPENAI_COMPATIBLE_PRESETS, type ModelProvider } from "./presets.js";
4
+
5
+ /** 未配置时的生成上限;MiniMax M3 最高支持 128K(含思考 token)。 */
6
+ export const DEFAULT_MAX_COMPLETION_TOKENS = 32_768;
7
+
8
+ /** 构建聊天模型所需的全部参数,集中在一处解析。 */
9
+ export interface ModelConfig {
10
+ /** 预设名,决定默认接口地址与默认模型。 */
11
+ provider: ModelProvider;
12
+ /** 服务商展示名,用于日志与预检输出。 */
13
+ label: string;
14
+ /** 传给 `model` 字段的模型名。 */
15
+ name: string;
16
+ /** 兼容 OpenAI 的接口地址,例如 `https://api.deepseek.com/v1`。 */
17
+ baseUrl: string;
18
+ /** 接口凭证;本地服务(Ollama、vLLM)可填任意非空值。 */
19
+ apiKey: string;
20
+ temperature: number;
21
+ /** 单次生成上限(含思考 token)。 */
22
+ maxCompletionTokens: number;
23
+ }
24
+
25
+ /**
26
+ * 把环境变量解析成模型配置。
27
+ * `MODEL_BASE_URL` 优先于预设地址,用于自建网关、代理或私有化部署。
28
+ */
29
+ export const resolveModelConfig = (env: Env): ModelConfig => {
30
+ const preset = OPENAI_COMPATIBLE_PRESETS[env.MODEL_PROVIDER];
31
+ const baseUrl = env.MODEL_BASE_URL ?? preset.baseUrl;
32
+ const name = env.MODEL_NAME ?? preset.defaultModel;
33
+
34
+ if (!baseUrl) {
35
+ throw new ConfigurationError(
36
+ `MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_BASE_URL(兼容 OpenAI 的接口地址)。`,
37
+ );
38
+ }
39
+
40
+ if (!name) {
41
+ throw new ConfigurationError(
42
+ `MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_NAME(例如 qwen-plus、glm-4.6)。`,
43
+ );
44
+ }
45
+
46
+ return {
47
+ provider: env.MODEL_PROVIDER,
48
+ label: preset.label,
49
+ name,
50
+ baseUrl,
51
+ apiKey: env.MODEL_API_KEY ?? "",
52
+ temperature: env.MODEL_TEMPERATURE,
53
+ maxCompletionTokens:
54
+ env.MODEL_MAX_COMPLETION_TOKENS ?? env.MODEL_MAX_TOKENS ?? DEFAULT_MAX_COMPLETION_TOKENS,
55
+ };
56
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 模型层统一出口。
3
+ *
4
+ * 模板只保留一条接入路径:OpenAI 兼容协议。切换服务商改环境变量即可,
5
+ * 需要自定义时调整 `openai-compatible` 模块中 `ChatOpenAI` 的构造参数。
6
+ */
7
+ export { resolveModelConfig, type ModelConfig } from "./config.js";
8
+ export { createChatModel } from "./openai-compatible.js";
9
+ export {
10
+ MODEL_PROVIDERS,
11
+ OPENAI_COMPATIBLE_PRESETS,
12
+ type ModelPreset,
13
+ type ModelProvider,
14
+ } from "./presets.js";
@@ -0,0 +1,21 @@
1
+ import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
2
+ import { ChatOpenAI } from "@langchain/openai";
3
+
4
+ import type { ModelConfig } from "./config.js";
5
+
6
+ /**
7
+ * 用 OpenAI 兼容协议创建聊天模型。
8
+ *
9
+ * 所有请求都走 `POST {baseUrl}/chat/completions`,因此 OpenAI、DeepSeek、
10
+ * 通义千问、Kimi、智谱、OpenRouter、vLLM、Ollama 等共用同一份实现;
11
+ * 接入新服务通常只需要设置 `MODEL_BASE_URL` 与 `MODEL_NAME`。
12
+ */
13
+ export const createChatModel = (config: ModelConfig): BaseChatModel => {
14
+ return new ChatOpenAI({
15
+ model: config.name,
16
+ temperature: config.temperature,
17
+ maxCompletionTokens: config.maxCompletionTokens,
18
+ configuration: { baseURL: config.baseUrl },
19
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
20
+ });
21
+ };
@@ -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
+ };