create-deepagent-server 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (175) hide show
  1. package/README.md +82 -8
  2. package/package.json +1 -1
  3. package/src/args.js +6 -4
  4. package/src/cli.js +1 -1
  5. package/src/dependencies.js +1 -1
  6. package/src/prompts.js +1 -0
  7. package/src/registry.js +8 -8
  8. package/src/scaffold.js +6 -7
  9. package/src/setup.js +2 -0
  10. package/src/version.js +1 -1
  11. package/src/versions.js +1 -1
  12. package/templates/deepagent/js/scripts/check.js +34 -11
  13. package/templates/deepagent/js/scripts/dev.js +9 -0
  14. package/templates/deepagent/js/src/agents/factory.js +2 -1
  15. package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
  16. package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
  17. package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
  18. package/templates/deepagent/js/src/agents/state/types.js +1 -0
  19. package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
  20. package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
  21. package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
  22. package/templates/deepagent/js/src/agents/supervisor.js +12 -4
  23. package/templates/deepagent/js/src/api/app.js +7 -0
  24. package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
  25. package/templates/deepagent/js/src/api/middleware/error.js +4 -0
  26. package/templates/deepagent/js/src/api/routes/agent.js +19 -49
  27. package/templates/deepagent/js/src/api/routes/health.js +12 -3
  28. package/templates/deepagent/js/src/api/routes/session.js +28 -48
  29. package/templates/deepagent/js/src/app.js +31 -12
  30. package/templates/deepagent/js/src/backends/composite.js +2 -0
  31. package/templates/deepagent/js/src/backends/filesystem.js +1 -0
  32. package/templates/deepagent/js/src/backends/index.js +35 -3
  33. package/templates/deepagent/js/src/backends/sandbox.js +3 -0
  34. package/templates/deepagent/js/src/config/agent.js +1 -0
  35. package/templates/deepagent/js/src/config/database.js +19 -0
  36. package/templates/deepagent/js/src/config/env.js +46 -23
  37. package/templates/deepagent/js/src/config/index.js +13 -3
  38. package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
  39. package/templates/deepagent/js/src/graph/compile.js +1 -0
  40. package/templates/deepagent/js/src/graph/store.js +10 -2
  41. package/templates/deepagent/js/src/index.js +9 -2
  42. package/templates/deepagent/js/src/memory/index.js +2 -0
  43. package/templates/deepagent/js/src/memory/manager.js +21 -10
  44. package/templates/deepagent/js/src/memory/store.js +7 -0
  45. package/templates/deepagent/js/src/middleware/approval.js +6 -1
  46. package/templates/deepagent/js/src/middleware/context.js +5 -0
  47. package/templates/deepagent/js/src/middleware/logging.js +47 -43
  48. package/templates/deepagent/js/src/middleware/security.js +7 -0
  49. package/templates/deepagent/js/src/model/config.js +38 -0
  50. package/templates/deepagent/js/src/model/index.js +9 -0
  51. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  52. package/templates/deepagent/js/src/model/presets.js +71 -0
  53. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  54. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  55. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  56. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  57. package/templates/deepagent/js/src/schemas/agent.js +7 -0
  58. package/templates/deepagent/js/src/schemas/common.js +5 -0
  59. package/templates/deepagent/js/src/schemas/locale.js +1 -0
  60. package/templates/deepagent/js/src/schemas/session.js +4 -0
  61. package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
  62. package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
  63. package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
  64. package/templates/deepagent/js/src/skills/index.js +4 -0
  65. package/templates/deepagent/js/src/skills/loader.js +20 -10
  66. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  67. package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
  68. package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
  69. package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
  70. package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
  71. package/templates/deepagent/js/src/tools/database/index.js +1 -1
  72. package/templates/deepagent/js/src/tools/database/query.js +44 -32
  73. package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
  74. package/templates/deepagent/js/src/tools/index.js +6 -11
  75. package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
  76. package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
  77. package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
  78. package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
  79. package/templates/deepagent/js/src/utils/errors.js +9 -0
  80. package/templates/deepagent/js/src/utils/helpers.js +15 -0
  81. package/templates/deepagent/js/src/utils/validation.js +15 -0
  82. package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
  83. package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
  84. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  85. package/templates/deepagent/js/tests/integration/api.test.js +18 -3
  86. package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
  87. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  88. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  89. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  90. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  91. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +5 -1
  93. package/templates/deepagent/shared/README.md +101 -14
  94. package/templates/deepagent/shared/_env.example +40 -10
  95. package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
  96. package/templates/deepagent/shared/resources/AGENTS.md +1 -1
  97. package/templates/deepagent/ts/scripts/check.ts +19 -11
  98. package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
  99. package/templates/deepagent/ts/src/agents/factory.ts +1 -1
  100. package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
  101. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
  102. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
  103. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
  104. package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
  105. package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
  106. package/templates/deepagent/ts/src/api/app.ts +4 -4
  107. package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
  108. package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
  109. package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
  110. package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
  111. package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
  112. package/templates/deepagent/ts/src/app.ts +19 -12
  113. package/templates/deepagent/ts/src/backends/index.ts +41 -7
  114. package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
  115. package/templates/deepagent/ts/src/config/database.ts +21 -0
  116. package/templates/deepagent/ts/src/config/env.ts +32 -28
  117. package/templates/deepagent/ts/src/config/index.ts +12 -4
  118. package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
  119. package/templates/deepagent/ts/src/graph/store.ts +5 -2
  120. package/templates/deepagent/ts/src/index.ts +2 -2
  121. package/templates/deepagent/ts/src/memory/manager.ts +12 -10
  122. package/templates/deepagent/ts/src/memory/store.ts +2 -0
  123. package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
  124. package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
  125. package/templates/deepagent/ts/src/middleware/security.ts +1 -0
  126. package/templates/deepagent/ts/src/model/config.ts +56 -0
  127. package/templates/deepagent/ts/src/model/index.ts +14 -0
  128. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  129. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  130. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  131. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  132. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  133. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  134. package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
  135. package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
  136. package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
  137. package/templates/deepagent/ts/src/skills/loader.ts +6 -10
  138. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  139. package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
  140. package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
  141. package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
  142. package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
  143. package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
  144. package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
  145. package/templates/deepagent/ts/src/tools/index.ts +10 -8
  146. package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
  147. package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
  148. package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
  149. package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
  150. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  151. package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
  152. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
  153. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  154. package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
  155. package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
  156. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  157. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  158. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  159. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  160. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  161. package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
  162. package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
  163. package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
  164. package/templates/deepagent/js/src/config/model.js +0 -34
  165. package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
  166. package/templates/deepagent/js/src/tools/search/index.js +0 -1
  167. package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
  168. package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
  169. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
  170. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
  171. package/templates/deepagent/ts/src/config/model.ts +0 -49
  172. package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
  173. package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
  174. package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
  175. /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
@@ -1,9 +1,15 @@
1
1
  import path from "node:path";
2
+
3
+ import { resolveModelConfig } from "../model/index.js";
4
+
5
+ import { resolveSandboxConfig } from "../sandbox/config.js";
6
+
2
7
  import { resolveAgentConfig } from "./agent.js";
8
+ import { resolveDatabaseUrl } from "./database.js";
3
9
  import { loadEnv } from "./env.js";
4
- import { resolveModelConfig } from "./model.js";
10
+
5
11
  export { loadEnv } from "./env.js";
6
- export { createChatModel, DEFAULT_MODELS } from "./model.js";
12
+
7
13
  /**
8
14
  * 把环境变量转换为带类型、使用绝对路径的应用配置,全局只在这里处理。
9
15
  */
@@ -14,6 +20,9 @@ export const loadConfig = (options = {}) => {
14
20
  loadEnv(process.env, {
15
21
  requireModelCredentials: options.requireModelCredentials ?? true,
16
22
  });
23
+
24
+ const databaseUrl = resolveDatabaseUrl(env);
25
+
17
26
  return {
18
27
  env,
19
28
  server: { host: env.HOST, port: env.PORT },
@@ -25,7 +34,8 @@ export const loadConfig = (options = {}) => {
25
34
  },
26
35
  model: resolveModelConfig(env),
27
36
  agent: resolveAgentConfig(env),
28
- database: { ...(env.DATABASE_URL ? { url: env.DATABASE_URL } : {}) },
37
+ sandbox: resolveSandboxConfig(env),
38
+ database: { ...(databaseUrl ? { url: databaseUrl } : {}) },
29
39
  redis: { ...(env.REDIS_URL ? { url: env.REDIS_URL } : {}) },
30
40
  logging: {
31
41
  level: env.LOG_LEVEL,
@@ -1,20 +1,28 @@
1
1
  import { MemorySaver } from "@langchain/langgraph";
2
+
2
3
  import { ConfigurationError } from "../utils/errors.js";
4
+
3
5
  /**
4
6
  * Checkpointer 以 `thread_id` 为单位持久化会话状态。
5
7
  *
6
8
  * - memory:进程内存,零配置(默认)
7
- * - postgres:持久化,需要 DATABASE_URL 和 checkpoint 表
9
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 checkpoint 表
8
10
  */
9
11
  export const createCheckpointer = async (config) => {
10
12
  if (config.env.CHECKPOINTER !== "postgres") {
11
13
  return new MemorySaver();
12
14
  }
15
+
13
16
  if (!config.database.url) {
14
- throw new ConfigurationError("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
17
+ throw new ConfigurationError(
18
+ "CHECKPOINTER=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
19
+ );
15
20
  }
21
+
16
22
  const { PostgresSaver } = await import("@langchain/langgraph-checkpoint-postgres");
23
+
17
24
  const saver = PostgresSaver.fromConnString(config.database.url);
18
25
  await saver.setup();
26
+
19
27
  return saver;
20
28
  };
@@ -1,4 +1,5 @@
1
1
  import { createDeepAgent } from "deepagents";
2
+
2
3
  /**
3
4
  * 唯一调用 `createDeepAgent` 的地方。集中在这里便于替换运行时
4
5
  * (例如用自定义 `StateGraph` 包裹 Agent)。
@@ -1,20 +1,28 @@
1
1
  import { InMemoryStore } from "@langchain/langgraph";
2
+
2
3
  import { ConfigurationError } from "../utils/errors.js";
4
+
3
5
  /**
4
6
  * Store 用于长期记忆和 `/memories/` 后端挂载。
5
7
  *
6
8
  * - memory:进程内存(默认)
7
- * - postgres:持久化,需要 DATABASE_URL 和 store 表
9
+ * - postgres:持久化,需要 PostgreSQL 连接信息与 store 表
8
10
  */
9
11
  export const createStore = async (config) => {
10
12
  if (config.env.STORE !== "postgres") {
11
13
  return new InMemoryStore();
12
14
  }
15
+
13
16
  if (!config.database.url) {
14
- throw new ConfigurationError("STORE=postgres 时必须设置 DATABASE_URL。");
17
+ throw new ConfigurationError(
18
+ "STORE=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
19
+ );
15
20
  }
21
+
16
22
  const { PostgresStore } = await import("@langchain/langgraph-checkpoint-postgres/store");
23
+
17
24
  const store = PostgresStore.fromConnString(config.database.url);
18
25
  await store.setup();
26
+
19
27
  return store;
20
28
  };
@@ -1,12 +1,16 @@
1
1
  import "dotenv/config";
2
+
2
3
  import { createApplication } from "./app.js";
3
4
  import { loadConfig } from "./config/index.js";
4
- import { createLogger } from "./infrastructure/logger/index.js";
5
- import { createShutdownManager } from "./infrastructure/shutdown/index.js";
5
+ import { createLogger } from "./storage/logger/index.js";
6
+ import { createShutdownManager } from "./storage/shutdown/index.js";
7
+
6
8
  const config = loadConfig();
7
9
  const logger = createLogger(config);
8
10
  const shutdown = createShutdownManager({ logger });
11
+
9
12
  const application = await createApplication(config);
13
+
10
14
  const server = application.app.listen(config.server.port, config.server.host, () => {
11
15
  logger.info(
12
16
  {
@@ -17,10 +21,12 @@ const server = application.app.listen(config.server.port, config.server.host, ()
17
21
  "DeepAgent API 已启动",
18
22
  );
19
23
  });
24
+
20
25
  server.on("error", (error) => {
21
26
  logger.error({ error: error.message }, "HTTP 服务启动失败");
22
27
  void shutdown.shutdown("server-error").finally(() => process.exit(1));
23
28
  });
29
+
24
30
  shutdown.register({
25
31
  name: "http",
26
32
  close: () =>
@@ -28,5 +34,6 @@ shutdown.register({
28
34
  server.close(() => resolve());
29
35
  }),
30
36
  });
37
+
31
38
  shutdown.register({ name: "application", close: application.close });
32
39
  shutdown.install();
@@ -1,6 +1,8 @@
1
1
  import { MemoryManager } from "./manager.js";
2
+
2
3
  export { MemoryManager };
3
4
  export { MemoryStore } from "./store.js";
5
+
4
6
  export const createMemoryManager = (store) => {
5
7
  return new MemoryManager({ store });
6
8
  };
@@ -1,39 +1,50 @@
1
1
  import { MemoryStore } from "./store.js";
2
+
2
3
  /**
3
4
  * 领域级长期记忆:按租户/用户隔离的偏好与事实,
4
5
  * 存储在挂载于 `/memories/` 的同一个 BaseStore 中。
5
6
  */
6
7
  export class MemoryManager {
7
- #memory;
8
- #root;
8
+ memory;
9
+ root;
10
+
9
11
  constructor({ store, rootNamespace = ["memories"] }) {
10
- this.#memory = new MemoryStore(store);
11
- this.#root = rootNamespace;
12
+ this.memory = new MemoryStore(store);
13
+ this.root = rootNamespace;
12
14
  }
15
+
13
16
  namespaceFor({ tenantId, userId }) {
14
17
  assertSegment(tenantId, "tenantId");
18
+
15
19
  const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
16
- return [...this.#root, tenantId, segment];
20
+ return [...this.root, tenantId, segment];
17
21
  }
22
+
18
23
  async rememberPreference(target, key, value) {
19
- await this.#memory.put(this.namespaceFor(target), `preference:${key}`, value);
24
+ await this.memory.put(this.namespaceFor(target), `preference:${key}`, value);
20
25
  }
26
+
21
27
  async rememberFact(target, key, value) {
22
- await this.#memory.put(this.namespaceFor(target), `fact:${key}`, value);
28
+ await this.memory.put(this.namespaceFor(target), `fact:${key}`, value);
23
29
  }
30
+
24
31
  async recall(target, key) {
25
- return this.#memory.get(this.namespaceFor(target), key);
32
+ return this.memory.get(this.namespaceFor(target), key);
26
33
  }
34
+
27
35
  async list(target, limit = 50) {
28
- return this.#memory.search(this.namespaceFor(target), limit);
36
+ return this.memory.search(this.namespaceFor(target), limit);
29
37
  }
38
+
30
39
  async forget(target, key) {
31
- await this.#memory.delete(this.namespaceFor(target), key);
40
+ await this.memory.delete(this.namespaceFor(target), key);
32
41
  }
33
42
  }
43
+
34
44
  const assertSegment = (value, label) => {
35
45
  if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
36
46
  throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
37
47
  }
48
+
38
49
  return value;
39
50
  };
@@ -7,25 +7,32 @@ export class MemoryStore {
7
7
  constructor(store) {
8
8
  this.store = store;
9
9
  }
10
+
10
11
  async put(namespace, key, value) {
11
12
  await this.store.put(namespace, key, {
12
13
  ...value,
13
14
  updatedAt: new Date().toISOString(),
14
15
  });
15
16
  }
17
+
16
18
  async get(namespace, key) {
17
19
  const item = await this.store.get(namespace, key);
18
20
  if (!item) return null;
21
+
19
22
  return toRecord(item);
20
23
  }
24
+
21
25
  async search(namespacePrefix, limit = 20) {
22
26
  const items = await this.store.search(namespacePrefix, { limit });
27
+
23
28
  return items.map((item) => toRecord(item));
24
29
  }
30
+
25
31
  async delete(namespace, key) {
26
32
  await this.store.delete(namespace, key);
27
33
  }
28
34
  }
35
+
29
36
  const toRecord = (item) => {
30
37
  return {
31
38
  key: item.key,
@@ -10,10 +10,10 @@ export const SENSITIVE_TOOLS = [
10
10
  "write_workspace_file",
11
11
  "query_database",
12
12
  ];
13
+
13
14
  /** 模板已知的全部工具名称。 */
14
15
  export const KNOWN_TOOLS = [
15
16
  ...SENSITIVE_TOOLS,
16
- "web_search",
17
17
  "read_file",
18
18
  "read_workspace_file",
19
19
  "list_workspace_files",
@@ -23,6 +23,7 @@ export const KNOWN_TOOLS = [
23
23
  "write_todos",
24
24
  "task",
25
25
  ];
26
+
26
27
  /**
27
28
  * 构建 `createDeepAgent` 使用的 `interruptOn` 映射。
28
29
  *
@@ -32,11 +33,15 @@ export const KNOWN_TOOLS = [
32
33
  */
33
34
  export const createApprovalPolicy = (mode) => {
34
35
  if (mode === "none") return {};
36
+
35
37
  const tools = mode === "all" ? [...KNOWN_TOOLS] : [...SENSITIVE_TOOLS];
38
+
36
39
  return Object.fromEntries(tools.map((tool) => [tool, true]));
37
40
  };
41
+
38
42
  export const requiresApproval = (mode, toolName) => {
39
43
  if (mode === "none") return false;
40
44
  if (mode === "all") return KNOWN_TOOLS.includes(toolName);
45
+
41
46
  return SENSITIVE_TOOLS.includes(toolName);
42
47
  };
@@ -1,10 +1,12 @@
1
1
  import { createMiddleware } from "langchain";
2
2
  import { z } from "zod";
3
+
3
4
  export const runtimeContextSchema = z.object({
4
5
  tenantId: z.string().default("default"),
5
6
  userId: z.string().optional(),
6
7
  threadId: z.string().optional(),
7
8
  });
9
+
8
10
  /**
9
11
  * 把每次请求的上下文注入系统提示词。上下文由 API 通过
10
12
  * `config.context` 提供,不会随会话持久化。
@@ -13,6 +15,7 @@ export const createContextMiddleware = () => {
13
15
  return createMiddleware({
14
16
  name: "ContextMiddleware",
15
17
  contextSchema: runtimeContextSchema,
18
+
16
19
  wrapModelCall: async (request, handler) => {
17
20
  const context = runtimeContextSchema.parse(request.runtime.context ?? {});
18
21
  const lines = [
@@ -21,9 +24,11 @@ export const createContextMiddleware = () => {
21
24
  ...(context.userId ? [`- 用户:${context.userId}`] : []),
22
25
  ...(context.threadId ? [`- 会话:${context.threadId}`] : []),
23
26
  ];
27
+
24
28
  const systemPrompt = [request.systemPrompt, lines.join("\n")]
25
29
  .filter((part) => Boolean(part && part.trim()))
26
30
  .join("\n\n");
31
+
27
32
  return handler({ ...request, systemPrompt, systemMessage: undefined });
28
33
  },
29
34
  });
@@ -1,5 +1,7 @@
1
1
  import { createMiddleware } from "langchain";
2
- import { truncate } from "../utils/helpers.js";
2
+
3
+ import { errorMessage, truncate } from "../utils/helpers.js";
4
+
3
5
  /**
4
6
  * 为每次模型和工具调用输出结构化日志。
5
7
  * 对 payload 做截断,避免大段工具输出淹没日志。
@@ -7,30 +9,32 @@ import { truncate } from "../utils/helpers.js";
7
9
  export const createLoggingMiddleware = (logger) => {
8
10
  return createMiddleware({
9
11
  name: "LoggingMiddleware",
12
+
10
13
  wrapModelCall: async (request, handler) => {
11
14
  const startedAt = Date.now();
12
- try {
13
- const response = await handler(request);
14
- logger.debug(
15
- {
16
- model: request.model?.getName?.() ?? "未知",
17
- durationMs: Date.now() - startedAt,
18
- toolCalls: response.tool_calls?.length ?? 0,
19
- },
20
- "模型调用完成",
21
- );
22
- return response;
23
- } catch (error) {
24
- logger.error(
25
- {
26
- durationMs: Date.now() - startedAt,
27
- error: error instanceof Error ? error.message : String(error),
28
- },
29
- "模型调用失败",
30
- );
31
- throw error;
32
- }
15
+
16
+ return Promise.resolve(handler(request)).then(
17
+ (response) => {
18
+ logger.debug(
19
+ {
20
+ model: request.model?.getName?.() ?? "未知",
21
+ durationMs: Date.now() - startedAt,
22
+ toolCalls: response.tool_calls?.length ?? 0,
23
+ },
24
+ "模型调用完成",
25
+ );
26
+ return response;
27
+ },
28
+ (error) => {
29
+ logger.error(
30
+ { durationMs: Date.now() - startedAt, error: errorMessage(error) },
31
+ "模型调用失败",
32
+ );
33
+ throw error;
34
+ },
35
+ );
33
36
  },
37
+
34
38
  wrapToolCall: async (request, handler) => {
35
39
  const startedAt = Date.now();
36
40
  logger.debug(
@@ -40,27 +44,27 @@ export const createLoggingMiddleware = (logger) => {
40
44
  },
41
45
  "工具调用开始",
42
46
  );
43
- try {
44
- const result = await handler(request);
45
- logger.debug(
46
- {
47
- tool: request.toolCall.name,
48
- durationMs: Date.now() - startedAt,
49
- },
50
- "工具调用完成",
51
- );
52
- return result;
53
- } catch (error) {
54
- logger.error(
55
- {
56
- tool: request.toolCall.name,
57
- durationMs: Date.now() - startedAt,
58
- error: error instanceof Error ? error.message : String(error),
59
- },
60
- "工具调用失败",
61
- );
62
- throw error;
63
- }
47
+
48
+ return Promise.resolve(handler(request)).then(
49
+ (result) => {
50
+ logger.debug(
51
+ { tool: request.toolCall.name, durationMs: Date.now() - startedAt },
52
+ "工具调用完成",
53
+ );
54
+ return result;
55
+ },
56
+ (error) => {
57
+ logger.error(
58
+ {
59
+ tool: request.toolCall.name,
60
+ durationMs: Date.now() - startedAt,
61
+ error: errorMessage(error),
62
+ },
63
+ "工具调用失败",
64
+ );
65
+ throw error;
66
+ },
67
+ );
64
68
  },
65
69
  });
66
70
  };
@@ -1,5 +1,6 @@
1
1
  import { ToolMessage } from "@langchain/core/messages";
2
2
  import { createMiddleware } from "langchain";
3
+
3
4
  /**
4
5
  * 针对破坏性 shell/SQL 载荷的启发式规则。这是纵深防御,不是沙箱:
5
6
  * 请以最小权限运行 Agent。
@@ -21,12 +22,15 @@ export const DANGEROUS_PATTERNS = [
21
22
  { pattern: /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i, reason: "破坏性 SQL" },
22
23
  { pattern: /\bTRUNCATE\s+TABLE\b/i, reason: "破坏性 SQL" },
23
24
  ];
25
+
24
26
  export const findSecurityViolation = (value) => {
25
27
  for (const { pattern, reason } of DANGEROUS_PATTERNS) {
26
28
  if (pattern.test(value)) return reason;
27
29
  }
30
+
28
31
  return null;
29
32
  };
33
+
30
34
  /**
31
35
  * 在工具执行前拒绝危险参数。模型会收到一条解释拦截原因的工具消息,
32
36
  * 从而改用更安全的方式。
@@ -34,9 +38,11 @@ export const findSecurityViolation = (value) => {
34
38
  export const createSecurityMiddleware = () => {
35
39
  return createMiddleware({
36
40
  name: "SecurityMiddleware",
41
+
37
42
  wrapToolCall: async (request, handler) => {
38
43
  const serializedArgs = JSON.stringify(request.toolCall.args ?? {});
39
44
  const violation = findSecurityViolation(serializedArgs);
45
+
40
46
  if (violation) {
41
47
  return new ToolMessage({
42
48
  content: `已被安全策略拦截:${violation}。请选择更安全的方式。`,
@@ -45,6 +51,7 @@ export const createSecurityMiddleware = () => {
45
51
  status: "error",
46
52
  });
47
53
  }
54
+
48
55
  return handler(request);
49
56
  },
50
57
  });
@@ -0,0 +1,38 @@
1
+ import { ConfigurationError } from "../utils/errors.js";
2
+ import { OPENAI_COMPATIBLE_PRESETS } from "./presets.js";
3
+
4
+ /** 未配置时的生成上限;MiniMax M3 最高支持 128K(含思考 token)。 */
5
+ export const DEFAULT_MAX_COMPLETION_TOKENS = 32_768;
6
+
7
+ /**
8
+ * 把环境变量解析成模型配置。
9
+ * `MODEL_BASE_URL` 优先于预设地址,用于自建网关、代理或私有化部署。
10
+ */
11
+ export const resolveModelConfig = (env) => {
12
+ const preset = OPENAI_COMPATIBLE_PRESETS[env.MODEL_PROVIDER];
13
+ const baseUrl = env.MODEL_BASE_URL ?? preset.baseUrl;
14
+ const name = env.MODEL_NAME ?? preset.defaultModel;
15
+
16
+ if (!baseUrl) {
17
+ throw new ConfigurationError(
18
+ `MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_BASE_URL(兼容 OpenAI 的接口地址)。`,
19
+ );
20
+ }
21
+
22
+ if (!name) {
23
+ throw new ConfigurationError(
24
+ `MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_NAME(例如 qwen-plus、glm-4.6)。`,
25
+ );
26
+ }
27
+
28
+ return {
29
+ provider: env.MODEL_PROVIDER,
30
+ label: preset.label,
31
+ name,
32
+ baseUrl,
33
+ apiKey: env.MODEL_API_KEY ?? "",
34
+ temperature: env.MODEL_TEMPERATURE,
35
+ maxCompletionTokens:
36
+ env.MODEL_MAX_COMPLETION_TOKENS ?? env.MODEL_MAX_TOKENS ?? DEFAULT_MAX_COMPLETION_TOKENS,
37
+ };
38
+ };
@@ -0,0 +1,9 @@
1
+ /**
2
+ * 模型层统一出口。
3
+ *
4
+ * 模板只保留一条接入路径:OpenAI 兼容协议。切换服务商改环境变量即可,
5
+ * 需要自定义时调整 `openai-compatible` 模块中 `ChatOpenAI` 的构造参数。
6
+ */
7
+ export { resolveModelConfig } from "./config.js";
8
+ export { createChatModel } from "./openai-compatible.js";
9
+ export { MODEL_PROVIDERS, OPENAI_COMPATIBLE_PRESETS } from "./presets.js";
@@ -0,0 +1,18 @@
1
+ import { ChatOpenAI } from "@langchain/openai";
2
+
3
+ /**
4
+ * 用 OpenAI 兼容协议创建聊天模型。
5
+ *
6
+ * 所有请求都走 `POST {baseUrl}/chat/completions`,因此 OpenAI、DeepSeek、
7
+ * 通义千问、Kimi、智谱、OpenRouter、vLLM、Ollama 等共用同一份实现;
8
+ * 接入新服务通常只需要设置 `MODEL_BASE_URL` 与 `MODEL_NAME`。
9
+ */
10
+ export const createChatModel = (config) => {
11
+ return new ChatOpenAI({
12
+ model: config.name,
13
+ temperature: config.temperature,
14
+ maxCompletionTokens: config.maxCompletionTokens,
15
+ configuration: { baseURL: config.baseUrl },
16
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
17
+ });
18
+ };
@@ -0,0 +1,71 @@
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
+ ];
20
+
21
+ export const OPENAI_COMPATIBLE_PRESETS = {
22
+ openai: {
23
+ label: "OpenAI",
24
+ baseUrl: "https://api.openai.com/v1",
25
+ defaultModel: "gpt-4.1-mini",
26
+ },
27
+ deepseek: {
28
+ label: "DeepSeek",
29
+ baseUrl: "https://api.deepseek.com/v1",
30
+ defaultModel: "deepseek-chat",
31
+ },
32
+ moonshot: {
33
+ label: "Moonshot Kimi",
34
+ baseUrl: "https://api.moonshot.cn/v1",
35
+ defaultModel: "kimi-latest",
36
+ },
37
+ minimax: {
38
+ label: "MiniMax",
39
+ // 国内站为 api.minimaxi.com,国际站使用 https://api.minimax.io/v1。
40
+ baseUrl: "https://api.minimaxi.com/v1",
41
+ defaultModel: "MiniMax-M3",
42
+ },
43
+ qwen: {
44
+ label: "通义千问(阿里云百炼)",
45
+ baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
46
+ defaultModel: "qwen-plus",
47
+ },
48
+ zhipu: {
49
+ label: "智谱 GLM",
50
+ baseUrl: "https://open.bigmodel.cn/api/paas/v4",
51
+ defaultModel: "glm-4.6",
52
+ },
53
+ openrouter: {
54
+ label: "OpenRouter",
55
+ baseUrl: "https://openrouter.ai/api/v1",
56
+ defaultModel: "openai/gpt-4.1-mini",
57
+ },
58
+ ollama: {
59
+ label: "Ollama(本地)",
60
+ baseUrl: "http://localhost:11434/v1",
61
+ defaultModel: "qwen3:8b",
62
+ },
63
+ vllm: {
64
+ label: "vLLM(本地)",
65
+ baseUrl: "http://localhost:8000/v1",
66
+ },
67
+ custom: {
68
+ label: "自定义 OpenAI 兼容服务",
69
+ baseUrl: "",
70
+ },
71
+ };
@@ -0,0 +1,12 @@
1
+ export const resolveSandboxConfig = (env) => {
2
+ return {
3
+ enabled: env.SANDBOX_ENABLED,
4
+ domain: env.OPEN_SANDBOX_DOMAIN,
5
+ protocol: env.OPEN_SANDBOX_PROTOCOL,
6
+ ...(env.OPEN_SANDBOX_API_KEY ? { apiKey: env.OPEN_SANDBOX_API_KEY } : {}),
7
+ ...(env.OPEN_SANDBOX_ID ? { sandboxId: env.OPEN_SANDBOX_ID } : {}),
8
+ image: env.SANDBOX_IMAGE,
9
+ ...(env.SANDBOX_TIMEOUT_SECONDS > 0 ? { timeoutSeconds: env.SANDBOX_TIMEOUT_SECONDS } : {}),
10
+ workspaceRoot: env.SANDBOX_WORKSPACE_ROOT,
11
+ };
12
+ };
@@ -0,0 +1,3 @@
1
+ export { resolveSandboxConfig } from "./config.js";
2
+ export { SandboxManager, threadIdFromRuntime } from "./manager.js";
3
+ export { createOpenSandboxBackend, OpenSandboxBackend } from "./opensandbox.js";