create-deepagent-server 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +83 -8
- package/package.json +1 -1
- package/src/args.js +6 -4
- package/src/cli.js +1 -4
- package/src/dependencies.js +1 -1
- package/src/prompts.js +1 -0
- package/src/registry.js +8 -8
- package/src/scaffold.js +21 -7
- package/src/setup.js +2 -0
- package/src/version.js +1 -1
- package/src/versions.js +1 -1
- package/templates/deepagent/js/scripts/check.js +34 -11
- package/templates/deepagent/js/scripts/dev.js +9 -0
- package/templates/deepagent/js/src/agents/factory.js +2 -1
- package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
- package/templates/deepagent/js/src/agents/state/types.js +1 -0
- package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
- package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
- package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
- package/templates/deepagent/js/src/agents/supervisor.js +12 -4
- package/templates/deepagent/js/src/api/app.js +7 -0
- package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
- package/templates/deepagent/js/src/api/middleware/error.js +4 -0
- package/templates/deepagent/js/src/api/routes/agent.js +19 -49
- package/templates/deepagent/js/src/api/routes/health.js +12 -3
- package/templates/deepagent/js/src/api/routes/session.js +28 -48
- package/templates/deepagent/js/src/app.js +31 -12
- package/templates/deepagent/js/src/backends/composite.js +2 -0
- package/templates/deepagent/js/src/backends/filesystem.js +1 -0
- package/templates/deepagent/js/src/backends/index.js +35 -3
- package/templates/deepagent/js/src/backends/sandbox.js +3 -0
- package/templates/deepagent/js/src/config/agent.js +1 -0
- package/templates/deepagent/js/src/config/database.js +19 -0
- package/templates/deepagent/js/src/config/env.js +46 -23
- package/templates/deepagent/js/src/config/index.js +13 -3
- package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
- package/templates/deepagent/js/src/graph/compile.js +1 -0
- package/templates/deepagent/js/src/graph/store.js +10 -2
- package/templates/deepagent/js/src/index.js +9 -2
- package/templates/deepagent/js/src/memory/index.js +2 -0
- package/templates/deepagent/js/src/memory/manager.js +21 -10
- package/templates/deepagent/js/src/memory/store.js +7 -0
- package/templates/deepagent/js/src/middleware/approval.js +6 -1
- package/templates/deepagent/js/src/middleware/context.js +5 -0
- package/templates/deepagent/js/src/middleware/logging.js +47 -43
- package/templates/deepagent/js/src/middleware/security.js +7 -0
- package/templates/deepagent/js/src/model/config.js +38 -0
- package/templates/deepagent/js/src/model/index.js +9 -0
- package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
- package/templates/deepagent/js/src/model/presets.js +71 -0
- package/templates/deepagent/js/src/sandbox/config.js +12 -0
- package/templates/deepagent/js/src/sandbox/index.js +3 -0
- package/templates/deepagent/js/src/sandbox/manager.js +161 -0
- package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
- package/templates/deepagent/js/src/schemas/agent.js +7 -0
- package/templates/deepagent/js/src/schemas/common.js +5 -0
- package/templates/deepagent/js/src/schemas/locale.js +1 -0
- package/templates/deepagent/js/src/schemas/session.js +4 -0
- package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
- package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
- package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
- package/templates/deepagent/js/src/skills/index.js +4 -0
- package/templates/deepagent/js/src/skills/loader.js +20 -10
- package/templates/deepagent/js/src/storage/database/client.js +57 -0
- package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
- package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
- package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
- package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
- package/templates/deepagent/js/src/tools/database/index.js +1 -1
- package/templates/deepagent/js/src/tools/database/query.js +44 -32
- package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
- package/templates/deepagent/js/src/tools/index.js +6 -11
- package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
- package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
- package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
- package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
- package/templates/deepagent/js/src/utils/errors.js +9 -0
- package/templates/deepagent/js/src/utils/helpers.js +15 -0
- package/templates/deepagent/js/src/utils/validation.js +15 -0
- package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
- package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
- package/templates/deepagent/js/tests/config/database.test.js +40 -0
- package/templates/deepagent/js/tests/integration/api.test.js +18 -3
- package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
- package/templates/deepagent/js/tests/model/config.test.js +61 -0
- package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
- package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
- package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
- package/templates/deepagent/js/tests/services/session.test.js +41 -0
- package/templates/deepagent/js/tests/tools/query.test.js +5 -1
- package/templates/deepagent/shared/README.md +101 -14
- package/templates/deepagent/shared/_env.example +40 -10
- package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
- package/templates/deepagent/shared/resources/AGENTS.md +1 -1
- package/templates/deepagent/ts/scripts/check.ts +19 -11
- package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
- package/templates/deepagent/ts/src/agents/factory.ts +1 -1
- package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
- package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
- package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
- package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
- package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
- package/templates/deepagent/ts/src/api/app.ts +4 -4
- package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
- package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
- package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
- package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
- package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
- package/templates/deepagent/ts/src/app.ts +19 -12
- package/templates/deepagent/ts/src/backends/index.ts +41 -7
- package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
- package/templates/deepagent/ts/src/config/database.ts +21 -0
- package/templates/deepagent/ts/src/config/env.ts +32 -28
- package/templates/deepagent/ts/src/config/index.ts +12 -4
- package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
- package/templates/deepagent/ts/src/graph/store.ts +5 -2
- package/templates/deepagent/ts/src/index.ts +2 -2
- package/templates/deepagent/ts/src/memory/manager.ts +12 -10
- package/templates/deepagent/ts/src/memory/store.ts +2 -0
- package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
- package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
- package/templates/deepagent/ts/src/middleware/security.ts +1 -0
- package/templates/deepagent/ts/src/model/config.ts +56 -0
- package/templates/deepagent/ts/src/model/index.ts +14 -0
- package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
- package/templates/deepagent/ts/src/model/presets.ts +82 -0
- package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
- package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
- package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
- package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
- package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
- package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
- package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
- package/templates/deepagent/ts/src/skills/loader.ts +6 -10
- package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
- package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
- package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
- package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
- package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
- package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
- package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
- package/templates/deepagent/ts/src/tools/index.ts +10 -8
- package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
- package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
- package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
- package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
- package/templates/deepagent/ts/src/utils/validation.ts +17 -0
- package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
- package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
- package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
- package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
- package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
- package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
- package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
- package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
- package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
- package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
- package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
- package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
- package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
- package/templates/deepagent/js/src/config/model.js +0 -34
- package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
- package/templates/deepagent/js/src/tools/search/index.js +0 -1
- package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
- package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
- package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
- package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
- package/templates/deepagent/ts/src/config/model.ts +0 -49
- package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
- package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
- package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
- /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
|
@@ -1,30 +1,39 @@
|
|
|
1
1
|
import "../schemas/locale.js";
|
|
2
|
+
|
|
2
3
|
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
import { MODEL_PROVIDERS } from "../model/index.js";
|
|
3
6
|
import { ConfigurationError } from "../utils/errors.js";
|
|
7
|
+
|
|
4
8
|
const booleanFlag = z
|
|
5
9
|
.union([z.boolean(), z.string()])
|
|
6
10
|
.default("false")
|
|
7
11
|
.transform((value) =>
|
|
8
12
|
typeof value === "boolean" ? value : ["1", "true", "yes", "on"].includes(value.toLowerCase()),
|
|
9
13
|
);
|
|
14
|
+
|
|
10
15
|
const optionalString = z
|
|
11
16
|
.string()
|
|
12
17
|
.trim()
|
|
13
18
|
.optional()
|
|
14
19
|
.transform((value) => (value === "" ? undefined : value));
|
|
20
|
+
|
|
15
21
|
export const envSchema = z.object({
|
|
16
22
|
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
|
|
17
23
|
HOST: z.string().default("0.0.0.0"),
|
|
18
24
|
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
|
|
19
25
|
LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
|
|
20
|
-
|
|
26
|
+
|
|
27
|
+
// 模型统一通过 OpenAI 兼容协议接入,服务商预设见 src/model/presets。
|
|
28
|
+
MODEL_PROVIDER: z.enum(MODEL_PROVIDERS).default("minimax"),
|
|
21
29
|
MODEL_NAME: optionalString,
|
|
30
|
+
MODEL_BASE_URL: optionalString,
|
|
31
|
+
MODEL_API_KEY: optionalString,
|
|
22
32
|
MODEL_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.2),
|
|
23
|
-
MODEL_MAX_TOKENS
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
TAVILY_API_KEY: optionalString,
|
|
33
|
+
// 生成上限(含思考 token);M3 最高 128K。MODEL_MAX_TOKENS 为旧变量,仍兼容。
|
|
34
|
+
MODEL_MAX_COMPLETION_TOKENS: z.coerce.number().int().positive().optional(),
|
|
35
|
+
MODEL_MAX_TOKENS: z.coerce.number().int().positive().optional(),
|
|
36
|
+
|
|
28
37
|
AGENT_NAME: z.string().default("deepagent"),
|
|
29
38
|
AGENT_API_KEY: optionalString,
|
|
30
39
|
AGENT_RECURSION_LIMIT: z.coerce.number().int().min(1).max(1000).default(50),
|
|
@@ -33,41 +42,55 @@ export const envSchema = z.object({
|
|
|
33
42
|
WORKSPACE_ROOT: z.string().default("workspaces"),
|
|
34
43
|
RESOURCES_ROOT: z.string().default("resources"),
|
|
35
44
|
SKILLS_ROOT: z.string().default("skills"),
|
|
45
|
+
|
|
46
|
+
// OpenSandbox:SANDBOX_ENABLED=true 时按会话(threadId)惰性创建并复用远程沙箱。
|
|
47
|
+
SANDBOX_ENABLED: booleanFlag,
|
|
48
|
+
OPEN_SANDBOX_DOMAIN: z.string().min(1).default("localhost:8080"),
|
|
49
|
+
OPEN_SANDBOX_PROTOCOL: z.enum(["http", "https"]).default("http"),
|
|
50
|
+
OPEN_SANDBOX_API_KEY: optionalString,
|
|
51
|
+
OPEN_SANDBOX_ID: optionalString,
|
|
52
|
+
SANDBOX_IMAGE: z.string().min(1).default("python:3.12"),
|
|
53
|
+
// 沙箱 TTL(秒):使用中按 TTL/3 自动续期,空闲到期后由服务端回收;0 表示不设置 TTL。
|
|
54
|
+
SANDBOX_TIMEOUT_SECONDS: z.coerce.number().int().min(0).default(1800),
|
|
55
|
+
SANDBOX_WORKSPACE_ROOT: z.string().min(1).default("/workspace"),
|
|
56
|
+
|
|
36
57
|
CHECKPOINTER: z.enum(["memory", "postgres"]).default("memory"),
|
|
37
58
|
STORE: z.enum(["memory", "postgres"]).default("memory"),
|
|
59
|
+
|
|
60
|
+
// PostgreSQL:CHECKPOINTER/STORE 为 postgres 时由分项拼装连接串,DATABASE_URL 优先。
|
|
38
61
|
DATABASE_URL: optionalString,
|
|
62
|
+
POSTGRES_HOST: z.string().min(1).default("localhost"),
|
|
63
|
+
POSTGRES_PORT: z.coerce.number().int().min(1).max(65535).default(5432),
|
|
64
|
+
POSTGRES_USERNAME: z.string().min(1).default("postgres"),
|
|
65
|
+
POSTGRES_PASSWORD: z.string().default("postgres"),
|
|
66
|
+
POSTGRES_DATABASE: z.string().min(1).default("deepagent"),
|
|
67
|
+
|
|
39
68
|
REDIS_URL: optionalString,
|
|
69
|
+
|
|
40
70
|
LANGSMITH_TRACING: booleanFlag,
|
|
41
71
|
LANGSMITH_API_KEY: optionalString,
|
|
42
72
|
LANGSMITH_PROJECT: z.string().default("deepagent"),
|
|
73
|
+
|
|
43
74
|
MCP_SERVERS: optionalString,
|
|
44
75
|
});
|
|
76
|
+
|
|
45
77
|
export const loadEnv = (source = process.env, { requireModelCredentials = true } = {}) => {
|
|
46
78
|
const parsed = envSchema.safeParse(source);
|
|
79
|
+
|
|
47
80
|
if (!parsed.success) {
|
|
48
81
|
const issues = parsed.error.issues
|
|
49
82
|
.map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`)
|
|
50
83
|
.join("; ");
|
|
51
84
|
throw new ConfigurationError(`环境变量配置无效:${issues}`);
|
|
52
85
|
}
|
|
86
|
+
|
|
53
87
|
const env = parsed.data;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
}
|
|
60
|
-
if (env.MODEL_PROVIDER === "anthropic" && !env.ANTHROPIC_API_KEY) {
|
|
61
|
-
throw new ConfigurationError(
|
|
62
|
-
"MODEL_PROVIDER=anthropic 时必须设置 ANTHROPIC_API_KEY(可复制 .env.example 为 .env)。",
|
|
63
|
-
);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
if (env.CHECKPOINTER === "postgres" && !env.DATABASE_URL) {
|
|
67
|
-
throw new ConfigurationError("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
|
|
68
|
-
}
|
|
69
|
-
if (env.STORE === "postgres" && !env.DATABASE_URL) {
|
|
70
|
-
throw new ConfigurationError("STORE=postgres 时必须设置 DATABASE_URL。");
|
|
88
|
+
|
|
89
|
+
if (requireModelCredentials && env.NODE_ENV !== "test" && !env.MODEL_API_KEY) {
|
|
90
|
+
throw new ConfigurationError(
|
|
91
|
+
"必须设置 MODEL_API_KEY(可复制 .env.example 为 .env);本地 OpenAI 兼容服务可填任意非空值。",
|
|
92
|
+
);
|
|
71
93
|
}
|
|
94
|
+
|
|
72
95
|
return env;
|
|
73
96
|
};
|
|
@@ -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
|
-
|
|
10
|
+
|
|
5
11
|
export { loadEnv } from "./env.js";
|
|
6
|
-
|
|
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
|
-
|
|
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:持久化,需要
|
|
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(
|
|
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,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:持久化,需要
|
|
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(
|
|
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 "./
|
|
5
|
-
import { createShutdownManager } from "./
|
|
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,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
|
-
|
|
8
|
-
|
|
8
|
+
memory;
|
|
9
|
+
root;
|
|
10
|
+
|
|
9
11
|
constructor({ store, rootNamespace = ["memories"] }) {
|
|
10
|
-
this
|
|
11
|
-
this
|
|
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
|
|
20
|
+
return [...this.root, tenantId, segment];
|
|
17
21
|
}
|
|
22
|
+
|
|
18
23
|
async rememberPreference(target, key, value) {
|
|
19
|
-
await this
|
|
24
|
+
await this.memory.put(this.namespaceFor(target), `preference:${key}`, value);
|
|
20
25
|
}
|
|
26
|
+
|
|
21
27
|
async rememberFact(target, key, value) {
|
|
22
|
-
await this
|
|
28
|
+
await this.memory.put(this.namespaceFor(target), `fact:${key}`, value);
|
|
23
29
|
}
|
|
30
|
+
|
|
24
31
|
async recall(target, key) {
|
|
25
|
-
return this
|
|
32
|
+
return this.memory.get(this.namespaceFor(target), key);
|
|
26
33
|
}
|
|
34
|
+
|
|
27
35
|
async list(target, limit = 50) {
|
|
28
|
-
return this
|
|
36
|
+
return this.memory.search(this.namespaceFor(target), limit);
|
|
29
37
|
}
|
|
38
|
+
|
|
30
39
|
async forget(target, key) {
|
|
31
|
-
await this
|
|
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
|
-
|
|
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
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
tool: request.toolCall.name,
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
+
};
|