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.
- package/LICENSE +21 -0
- package/README.md +292 -2
- package/bin/create-deepagent-server.js +27 -0
- package/package.json +50 -4
- package/src/args.js +195 -0
- package/src/cli.js +269 -0
- package/src/dependencies.js +34 -0
- package/src/prompts.js +86 -0
- package/src/registry.js +68 -0
- package/src/scaffold.js +181 -0
- package/src/setup.js +79 -0
- package/src/ui.js +43 -0
- package/src/version.js +1 -0
- package/src/versions.js +29 -0
- package/templates/deepagent/js/deployment/Dockerfile +19 -0
- package/templates/deepagent/js/scripts/check.js +97 -0
- package/templates/deepagent/js/scripts/dev.js +40 -0
- package/templates/deepagent/js/src/agents/factory.js +11 -0
- package/templates/deepagent/js/src/agents/index.js +4 -0
- package/templates/deepagent/js/src/agents/prompts/index.js +2 -0
- package/templates/deepagent/js/src/agents/prompts/loader.js +53 -0
- package/templates/deepagent/js/src/agents/prompts/subagents/analyst.md +17 -0
- package/templates/deepagent/js/src/agents/prompts/subagents/coder.md +17 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.js +21 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.md +41 -0
- package/templates/deepagent/js/src/agents/state/index.js +1 -0
- package/templates/deepagent/js/src/agents/state/types.js +11 -0
- package/templates/deepagent/js/src/agents/subagents/analyst.js +12 -0
- package/templates/deepagent/js/src/agents/subagents/coder.js +12 -0
- package/templates/deepagent/js/src/agents/subagents/index.js +9 -0
- package/templates/deepagent/js/src/agents/supervisor.js +64 -0
- package/templates/deepagent/js/src/api/app.js +29 -0
- package/templates/deepagent/js/src/api/middleware/auth.js +36 -0
- package/templates/deepagent/js/src/api/middleware/error.js +30 -0
- package/templates/deepagent/js/src/api/routes/agent.js +43 -0
- package/templates/deepagent/js/src/api/routes/health.js +40 -0
- package/templates/deepagent/js/src/api/routes/session.js +42 -0
- package/templates/deepagent/js/src/app.js +98 -0
- package/templates/deepagent/js/src/backends/composite.js +22 -0
- package/templates/deepagent/js/src/backends/filesystem.js +9 -0
- package/templates/deepagent/js/src/backends/index.js +60 -0
- package/templates/deepagent/js/src/backends/sandbox.js +26 -0
- package/templates/deepagent/js/src/config/agent.js +14 -0
- package/templates/deepagent/js/src/config/database.js +19 -0
- package/templates/deepagent/js/src/config/env.js +96 -0
- package/templates/deepagent/js/src/config/index.js +45 -0
- package/templates/deepagent/js/src/graph/checkpointer.js +28 -0
- package/templates/deepagent/js/src/graph/compile.js +9 -0
- package/templates/deepagent/js/src/graph/index.js +3 -0
- package/templates/deepagent/js/src/graph/store.js +28 -0
- package/templates/deepagent/js/src/index.js +39 -0
- package/templates/deepagent/js/src/memory/index.js +8 -0
- package/templates/deepagent/js/src/memory/manager.js +50 -0
- package/templates/deepagent/js/src/memory/store.js +43 -0
- package/templates/deepagent/js/src/middleware/approval.js +47 -0
- package/templates/deepagent/js/src/middleware/context.js +35 -0
- package/templates/deepagent/js/src/middleware/index.js +9 -0
- package/templates/deepagent/js/src/middleware/logging.js +70 -0
- package/templates/deepagent/js/src/middleware/security.js +58 -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 +40 -0
- package/templates/deepagent/js/src/schemas/common.js +24 -0
- package/templates/deepagent/js/src/schemas/locale.js +4 -0
- package/templates/deepagent/js/src/schemas/session.js +27 -0
- package/templates/deepagent/js/src/services/agent.js +136 -0
- package/templates/deepagent/js/src/services/memory.js +33 -0
- package/templates/deepagent/js/src/services/session.js +118 -0
- package/templates/deepagent/js/src/skills/index.js +21 -0
- package/templates/deepagent/js/src/skills/loader.js +75 -0
- package/templates/deepagent/js/src/storage/database/client.js +57 -0
- package/templates/deepagent/js/src/storage/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/js/src/storage/logger/index.js +21 -0
- package/templates/deepagent/js/src/storage/redis/client.js +51 -0
- package/templates/deepagent/js/src/storage/shutdown/index.js +58 -0
- package/templates/deepagent/js/src/tools/database/index.js +1 -0
- package/templates/deepagent/js/src/tools/database/query.js +74 -0
- package/templates/deepagent/js/src/tools/filesystem/index.js +102 -0
- package/templates/deepagent/js/src/tools/index.js +25 -0
- package/templates/deepagent/js/src/tools/mcp/client.js +42 -0
- package/templates/deepagent/js/src/tools/mcp/connections.js +64 -0
- package/templates/deepagent/js/src/tools/mcp/index.js +10 -0
- package/templates/deepagent/js/src/tools/mcp/registry.js +36 -0
- package/templates/deepagent/js/src/utils/errors.js +73 -0
- package/templates/deepagent/js/src/utils/helpers.js +57 -0
- package/templates/deepagent/js/src/utils/validation.js +15 -0
- package/templates/deepagent/js/tests/agents/prompts.test.js +30 -0
- package/templates/deepagent/js/tests/agents/supervisor.test.js +42 -0
- package/templates/deepagent/js/tests/config/database.test.js +40 -0
- package/templates/deepagent/js/tests/integration/api.test.js +114 -0
- package/templates/deepagent/js/tests/middleware/security.test.js +27 -0
- 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 +27 -0
- package/templates/deepagent/shared/README.md +249 -0
- package/templates/deepagent/shared/_editorconfig +12 -0
- package/templates/deepagent/shared/_env.example +86 -0
- package/templates/deepagent/shared/_gitignore +22 -0
- package/templates/deepagent/shared/deployment/docker-compose.yml +60 -0
- package/templates/deepagent/shared/resources/AGENTS.md +32 -0
- package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
- package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
- package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
- package/templates/deepagent/shared/workspaces/README.md +5 -0
- package/templates/deepagent/ts/deployment/Dockerfile +25 -0
- package/templates/deepagent/ts/scripts/check.ts +99 -0
- package/templates/deepagent/ts/scripts/copy-assets.ts +37 -0
- package/templates/deepagent/ts/scripts/dev.ts +40 -0
- package/templates/deepagent/ts/src/agents/factory.ts +11 -0
- package/templates/deepagent/ts/src/agents/index.ts +4 -0
- package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
- package/templates/deepagent/ts/src/agents/prompts/loader.ts +53 -0
- package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
- package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.md +41 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
- package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
- package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
- package/templates/deepagent/ts/src/agents/subagents/analyst.ts +18 -0
- package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
- package/templates/deepagent/ts/src/agents/subagents/index.ts +9 -0
- package/templates/deepagent/ts/src/agents/supervisor.ts +82 -0
- package/templates/deepagent/ts/src/api/app.ts +48 -0
- package/templates/deepagent/ts/src/api/middleware/auth.ts +38 -0
- package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
- package/templates/deepagent/ts/src/api/routes/agent.ts +48 -0
- package/templates/deepagent/ts/src/api/routes/health.ts +47 -0
- package/templates/deepagent/ts/src/api/routes/session.ts +47 -0
- package/templates/deepagent/ts/src/app.ts +111 -0
- package/templates/deepagent/ts/src/backends/composite.ts +34 -0
- package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
- package/templates/deepagent/ts/src/backends/index.ts +76 -0
- package/templates/deepagent/ts/src/backends/sandbox.ts +33 -0
- package/templates/deepagent/ts/src/config/agent.ts +37 -0
- package/templates/deepagent/ts/src/config/database.ts +21 -0
- package/templates/deepagent/ts/src/config/env.ts +106 -0
- package/templates/deepagent/ts/src/config/index.ts +84 -0
- package/templates/deepagent/ts/src/graph/checkpointer.ts +29 -0
- package/templates/deepagent/ts/src/graph/compile.ts +15 -0
- package/templates/deepagent/ts/src/graph/index.ts +3 -0
- package/templates/deepagent/ts/src/graph/store.ts +29 -0
- package/templates/deepagent/ts/src/index.ts +39 -0
- package/templates/deepagent/ts/src/memory/index.ts +11 -0
- package/templates/deepagent/ts/src/memory/manager.ts +76 -0
- package/templates/deepagent/ts/src/memory/store.ts +59 -0
- package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
- package/templates/deepagent/ts/src/middleware/context.ts +37 -0
- package/templates/deepagent/ts/src/middleware/index.ts +9 -0
- package/templates/deepagent/ts/src/middleware/logging.ts +71 -0
- package/templates/deepagent/ts/src/middleware/security.ts +61 -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/schemas/agent.ts +48 -0
- package/templates/deepagent/ts/src/schemas/common.ts +26 -0
- package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
- package/templates/deepagent/ts/src/schemas/session.ts +31 -0
- package/templates/deepagent/ts/src/services/agent.ts +170 -0
- package/templates/deepagent/ts/src/services/memory.ts +43 -0
- package/templates/deepagent/ts/src/services/session.ts +158 -0
- package/templates/deepagent/ts/src/skills/index.ts +26 -0
- package/templates/deepagent/ts/src/skills/loader.ts +90 -0
- package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
- package/templates/deepagent/ts/src/storage/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/ts/src/storage/logger/index.ts +25 -0
- package/templates/deepagent/ts/src/storage/redis/client.ts +57 -0
- package/templates/deepagent/ts/src/storage/shutdown/index.ts +82 -0
- package/templates/deepagent/ts/src/tools/database/index.ts +5 -0
- package/templates/deepagent/ts/src/tools/database/query.ts +79 -0
- package/templates/deepagent/ts/src/tools/filesystem/index.ts +110 -0
- package/templates/deepagent/ts/src/tools/index.ts +43 -0
- package/templates/deepagent/ts/src/tools/mcp/client.ts +54 -0
- package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
- package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
- package/templates/deepagent/ts/src/tools/mcp/registry.ts +45 -0
- package/templates/deepagent/ts/src/utils/errors.ts +95 -0
- package/templates/deepagent/ts/src/utils/helpers.ts +57 -0
- package/templates/deepagent/ts/src/utils/validation.ts +17 -0
- package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
- package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
- package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
- package/templates/deepagent/ts/tests/integration/api.test.ts +122 -0
- package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
- 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 +27 -0
- package/templates/deepagent/ts/tsconfig.json +19 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import "../schemas/locale.js";
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
import { MODEL_PROVIDERS } from "../model/index.js";
|
|
6
|
+
import { ConfigurationError } from "../utils/errors.js";
|
|
7
|
+
|
|
8
|
+
const booleanFlag = z
|
|
9
|
+
.union([z.boolean(), z.string()])
|
|
10
|
+
.default("false")
|
|
11
|
+
.transform((value) =>
|
|
12
|
+
typeof value === "boolean" ? value : ["1", "true", "yes", "on"].includes(value.toLowerCase()),
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
const optionalString = z
|
|
16
|
+
.string()
|
|
17
|
+
.trim()
|
|
18
|
+
.optional()
|
|
19
|
+
.transform((value) => (value === "" ? undefined : value));
|
|
20
|
+
|
|
21
|
+
export const envSchema = z.object({
|
|
22
|
+
NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
|
|
23
|
+
HOST: z.string().default("0.0.0.0"),
|
|
24
|
+
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
|
|
25
|
+
LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace", "silent"]).default("info"),
|
|
26
|
+
|
|
27
|
+
// 模型统一通过 OpenAI 兼容协议接入,服务商预设见 src/model/presets。
|
|
28
|
+
MODEL_PROVIDER: z.enum(MODEL_PROVIDERS).default("minimax"),
|
|
29
|
+
MODEL_NAME: optionalString,
|
|
30
|
+
MODEL_BASE_URL: optionalString,
|
|
31
|
+
MODEL_API_KEY: optionalString,
|
|
32
|
+
MODEL_TEMPERATURE: z.coerce.number().min(0).max(2).default(0.2),
|
|
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
|
+
|
|
37
|
+
AGENT_NAME: z.string().default("deepagent"),
|
|
38
|
+
AGENT_API_KEY: optionalString,
|
|
39
|
+
AGENT_RECURSION_LIMIT: z.coerce.number().int().min(1).max(1000).default(50),
|
|
40
|
+
APPROVAL_MODE: z.enum(["none", "sensitive", "all"]).default("sensitive"),
|
|
41
|
+
ENABLE_SHELL: booleanFlag,
|
|
42
|
+
WORKSPACE_ROOT: z.string().default("workspaces"),
|
|
43
|
+
RESOURCES_ROOT: z.string().default("resources"),
|
|
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
|
+
|
|
57
|
+
CHECKPOINTER: z.enum(["memory", "postgres"]).default("memory"),
|
|
58
|
+
STORE: z.enum(["memory", "postgres"]).default("memory"),
|
|
59
|
+
|
|
60
|
+
// PostgreSQL:CHECKPOINTER/STORE 为 postgres 时由分项拼装连接串,DATABASE_URL 优先。
|
|
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
|
+
|
|
68
|
+
REDIS_URL: optionalString,
|
|
69
|
+
|
|
70
|
+
LANGSMITH_TRACING: booleanFlag,
|
|
71
|
+
LANGSMITH_API_KEY: optionalString,
|
|
72
|
+
LANGSMITH_PROJECT: z.string().default("deepagent"),
|
|
73
|
+
|
|
74
|
+
MCP_SERVERS: optionalString,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
export type Env = z.infer<typeof envSchema>;
|
|
78
|
+
|
|
79
|
+
export interface LoadEnvOptions {
|
|
80
|
+
/** 缺少 MODEL_API_KEY 时直接报错。 */
|
|
81
|
+
requireModelCredentials?: boolean;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const loadEnv = (
|
|
85
|
+
source: NodeJS.ProcessEnv = process.env,
|
|
86
|
+
{ requireModelCredentials = true }: LoadEnvOptions = {},
|
|
87
|
+
): Env => {
|
|
88
|
+
const parsed = envSchema.safeParse(source);
|
|
89
|
+
|
|
90
|
+
if (!parsed.success) {
|
|
91
|
+
const issues = parsed.error.issues
|
|
92
|
+
.map((issue) => `${issue.path.join(".") || "env"}: ${issue.message}`)
|
|
93
|
+
.join("; ");
|
|
94
|
+
throw new ConfigurationError(`环境变量配置无效:${issues}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const env = parsed.data;
|
|
98
|
+
|
|
99
|
+
if (requireModelCredentials && env.NODE_ENV !== "test" && !env.MODEL_API_KEY) {
|
|
100
|
+
throw new ConfigurationError(
|
|
101
|
+
"必须设置 MODEL_API_KEY(可复制 .env.example 为 .env);本地 OpenAI 兼容服务可填任意非空值。",
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return env;
|
|
106
|
+
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
|
|
3
|
+
import { resolveModelConfig, type ModelConfig } from "../model/index.js";
|
|
4
|
+
|
|
5
|
+
import { resolveSandboxConfig, type SandboxConfig } from "../sandbox/config.js";
|
|
6
|
+
|
|
7
|
+
import { resolveAgentConfig, type AgentConfig } from "./agent.js";
|
|
8
|
+
import { resolveDatabaseUrl } from "./database.js";
|
|
9
|
+
import { loadEnv, type Env } from "./env.js";
|
|
10
|
+
|
|
11
|
+
export type { AgentConfig, ApprovalMode } from "./agent.js";
|
|
12
|
+
export type { Env } from "./env.js";
|
|
13
|
+
export type { ModelConfig } from "../model/index.js";
|
|
14
|
+
export type { SandboxConfig } from "../sandbox/config.js";
|
|
15
|
+
export { loadEnv } from "./env.js";
|
|
16
|
+
|
|
17
|
+
export interface AppPaths {
|
|
18
|
+
root: string;
|
|
19
|
+
workspaces: string;
|
|
20
|
+
resources: string;
|
|
21
|
+
skills: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface AppConfig {
|
|
25
|
+
env: Env;
|
|
26
|
+
server: {
|
|
27
|
+
host: string;
|
|
28
|
+
port: number;
|
|
29
|
+
};
|
|
30
|
+
paths: AppPaths;
|
|
31
|
+
model: ModelConfig;
|
|
32
|
+
agent: AgentConfig;
|
|
33
|
+
sandbox: SandboxConfig;
|
|
34
|
+
database: {
|
|
35
|
+
url?: string;
|
|
36
|
+
};
|
|
37
|
+
redis: {
|
|
38
|
+
url?: string;
|
|
39
|
+
};
|
|
40
|
+
logging: {
|
|
41
|
+
level: Env["LOG_LEVEL"];
|
|
42
|
+
pretty: boolean;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface LoadConfigOptions {
|
|
47
|
+
cwd?: string;
|
|
48
|
+
env?: Env;
|
|
49
|
+
requireModelCredentials?: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 把环境变量转换为带类型、使用绝对路径的应用配置,全局只在这里处理。
|
|
54
|
+
*/
|
|
55
|
+
export const loadConfig = (options: LoadConfigOptions = {}): AppConfig => {
|
|
56
|
+
const root = path.resolve(options.cwd ?? process.cwd());
|
|
57
|
+
const env =
|
|
58
|
+
options.env ??
|
|
59
|
+
loadEnv(process.env, {
|
|
60
|
+
requireModelCredentials: options.requireModelCredentials ?? true,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
const databaseUrl = resolveDatabaseUrl(env);
|
|
64
|
+
|
|
65
|
+
return {
|
|
66
|
+
env,
|
|
67
|
+
server: { host: env.HOST, port: env.PORT },
|
|
68
|
+
paths: {
|
|
69
|
+
root,
|
|
70
|
+
workspaces: path.resolve(root, env.WORKSPACE_ROOT),
|
|
71
|
+
resources: path.resolve(root, env.RESOURCES_ROOT),
|
|
72
|
+
skills: path.resolve(root, env.SKILLS_ROOT),
|
|
73
|
+
},
|
|
74
|
+
model: resolveModelConfig(env),
|
|
75
|
+
agent: resolveAgentConfig(env),
|
|
76
|
+
sandbox: resolveSandboxConfig(env),
|
|
77
|
+
database: { ...(databaseUrl ? { url: databaseUrl } : {}) },
|
|
78
|
+
redis: { ...(env.REDIS_URL ? { url: env.REDIS_URL } : {}) },
|
|
79
|
+
logging: {
|
|
80
|
+
level: env.LOG_LEVEL,
|
|
81
|
+
pretty: env.NODE_ENV === "development",
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { MemorySaver, type BaseCheckpointSaver } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
import type { AppConfig } from "../config/index.js";
|
|
4
|
+
import { ConfigurationError } from "../utils/errors.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Checkpointer 以 `thread_id` 为单位持久化会话状态。
|
|
8
|
+
*
|
|
9
|
+
* - memory:进程内存,零配置(默认)
|
|
10
|
+
* - postgres:持久化,需要 PostgreSQL 连接信息与 checkpoint 表
|
|
11
|
+
*/
|
|
12
|
+
export const createCheckpointer = async (config: AppConfig): Promise<BaseCheckpointSaver> => {
|
|
13
|
+
if (config.env.CHECKPOINTER !== "postgres") {
|
|
14
|
+
return new MemorySaver();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (!config.database.url) {
|
|
18
|
+
throw new ConfigurationError(
|
|
19
|
+
"CHECKPOINTER=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const { PostgresSaver } = await import("@langchain/langgraph-checkpoint-postgres");
|
|
24
|
+
|
|
25
|
+
const saver = PostgresSaver.fromConnString(config.database.url);
|
|
26
|
+
await saver.setup();
|
|
27
|
+
|
|
28
|
+
return saver;
|
|
29
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { createDeepAgent } from "deepagents";
|
|
2
|
+
|
|
3
|
+
/** `createDeepAgent` 接受的参数,复用为工厂的输入。 */
|
|
4
|
+
export type AgentOptions = NonNullable<Parameters<typeof createDeepAgent>[0]>;
|
|
5
|
+
|
|
6
|
+
/** Deep Agents 返回的、已编译的 LangGraph 可运行对象。 */
|
|
7
|
+
export type CompiledAgent = ReturnType<typeof createDeepAgent>;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* 唯一调用 `createDeepAgent` 的地方。集中在这里便于替换运行时
|
|
11
|
+
* (例如用自定义 `StateGraph` 包裹 Agent)。
|
|
12
|
+
*/
|
|
13
|
+
export const compileAgentGraph = (options: AgentOptions): CompiledAgent => {
|
|
14
|
+
return createDeepAgent(options);
|
|
15
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { InMemoryStore, type BaseStore } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
import type { AppConfig } from "../config/index.js";
|
|
4
|
+
import { ConfigurationError } from "../utils/errors.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Store 用于长期记忆和 `/memories/` 后端挂载。
|
|
8
|
+
*
|
|
9
|
+
* - memory:进程内存(默认)
|
|
10
|
+
* - postgres:持久化,需要 PostgreSQL 连接信息与 store 表
|
|
11
|
+
*/
|
|
12
|
+
export const createStore = async (config: AppConfig): Promise<BaseStore> => {
|
|
13
|
+
if (config.env.STORE !== "postgres") {
|
|
14
|
+
return new InMemoryStore();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
if (!config.database.url) {
|
|
18
|
+
throw new ConfigurationError(
|
|
19
|
+
"STORE=postgres 时必须配置 PostgreSQL 连接信息(DATABASE_URL 或 POSTGRES_*)。",
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const { PostgresStore } = await import("@langchain/langgraph-checkpoint-postgres/store");
|
|
24
|
+
|
|
25
|
+
const store = PostgresStore.fromConnString(config.database.url);
|
|
26
|
+
await store.setup();
|
|
27
|
+
|
|
28
|
+
return store;
|
|
29
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
|
|
3
|
+
import { createApplication } from "./app.js";
|
|
4
|
+
import { loadConfig } from "./config/index.js";
|
|
5
|
+
import { createLogger } from "./storage/logger/index.js";
|
|
6
|
+
import { createShutdownManager } from "./storage/shutdown/index.js";
|
|
7
|
+
|
|
8
|
+
const config = loadConfig();
|
|
9
|
+
const logger = createLogger(config);
|
|
10
|
+
const shutdown = createShutdownManager({ logger });
|
|
11
|
+
|
|
12
|
+
const application = await createApplication(config);
|
|
13
|
+
|
|
14
|
+
const server = application.app.listen(config.server.port, config.server.host, () => {
|
|
15
|
+
logger.info(
|
|
16
|
+
{
|
|
17
|
+
host: config.server.host,
|
|
18
|
+
port: config.server.port,
|
|
19
|
+
model: `${config.model.provider}/${config.model.name}`,
|
|
20
|
+
},
|
|
21
|
+
"DeepAgent API 已启动",
|
|
22
|
+
);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
server.on("error", (error) => {
|
|
26
|
+
logger.error({ error: error.message }, "HTTP 服务启动失败");
|
|
27
|
+
void shutdown.shutdown("server-error").finally(() => process.exit(1));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
shutdown.register({
|
|
31
|
+
name: "http",
|
|
32
|
+
close: () =>
|
|
33
|
+
new Promise<void>((resolve) => {
|
|
34
|
+
server.close(() => resolve());
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
shutdown.register({ name: "application", close: application.close });
|
|
39
|
+
shutdown.install();
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { BaseStore } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
import { MemoryManager } from "./manager.js";
|
|
4
|
+
|
|
5
|
+
export type { MemoryRecord } from "./store.js";
|
|
6
|
+
export { MemoryManager };
|
|
7
|
+
export { MemoryStore } from "./store.js";
|
|
8
|
+
|
|
9
|
+
export const createMemoryManager = (store: BaseStore): MemoryManager => {
|
|
10
|
+
return new MemoryManager({ store });
|
|
11
|
+
};
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { BaseStore } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
import { MemoryStore, type MemoryRecord } from "./store.js";
|
|
4
|
+
|
|
5
|
+
export interface MemoryManagerOptions {
|
|
6
|
+
store: BaseStore;
|
|
7
|
+
rootNamespace?: string[];
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface MemoryTarget {
|
|
11
|
+
tenantId: string;
|
|
12
|
+
userId?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 领域级长期记忆:按租户/用户隔离的偏好与事实,
|
|
17
|
+
* 存储在挂载于 `/memories/` 的同一个 BaseStore 中。
|
|
18
|
+
*/
|
|
19
|
+
export class MemoryManager {
|
|
20
|
+
private readonly memory: MemoryStore;
|
|
21
|
+
private readonly root: string[];
|
|
22
|
+
|
|
23
|
+
constructor({ store, rootNamespace = ["memories"] }: MemoryManagerOptions) {
|
|
24
|
+
this.memory = new MemoryStore(store);
|
|
25
|
+
this.root = rootNamespace;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
namespaceFor({ tenantId, userId }: MemoryTarget): string[] {
|
|
29
|
+
assertSegment(tenantId, "tenantId");
|
|
30
|
+
|
|
31
|
+
const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
|
|
32
|
+
return [...this.root, tenantId, segment];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async rememberPreference(
|
|
36
|
+
target: MemoryTarget,
|
|
37
|
+
key: string,
|
|
38
|
+
value: Record<string, unknown>,
|
|
39
|
+
): Promise<void> {
|
|
40
|
+
await this.memory.put(this.namespaceFor(target), `preference:${key}`, value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async rememberFact(
|
|
44
|
+
target: MemoryTarget,
|
|
45
|
+
key: string,
|
|
46
|
+
value: Record<string, unknown>,
|
|
47
|
+
): Promise<void> {
|
|
48
|
+
await this.memory.put(this.namespaceFor(target), `fact:${key}`, value);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async recall<T = Record<string, unknown>>(
|
|
52
|
+
target: MemoryTarget,
|
|
53
|
+
key: string,
|
|
54
|
+
): Promise<MemoryRecord<T> | null> {
|
|
55
|
+
return this.memory.get<T>(this.namespaceFor(target), key);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async list<T = Record<string, unknown>>(
|
|
59
|
+
target: MemoryTarget,
|
|
60
|
+
limit = 50,
|
|
61
|
+
): Promise<MemoryRecord<T>[]> {
|
|
62
|
+
return this.memory.search<T>(this.namespaceFor(target), limit);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async forget(target: MemoryTarget, key: string): Promise<void> {
|
|
66
|
+
await this.memory.delete(this.namespaceFor(target), key);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const assertSegment = (value: string, label: string): string => {
|
|
71
|
+
if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
|
|
72
|
+
throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return value;
|
|
76
|
+
};
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { BaseStore, Item } from "@langchain/langgraph";
|
|
2
|
+
|
|
3
|
+
export interface MemoryRecord<T = Record<string, unknown>> {
|
|
4
|
+
key: string;
|
|
5
|
+
namespace: string[];
|
|
6
|
+
value: T;
|
|
7
|
+
updatedAt?: string;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 对 LangGraph `BaseStore`(InMemoryStore 或 PostgresStore)的轻量类型封装,
|
|
12
|
+
* 让应用其他部分不必直接处理 store 的底层细节。
|
|
13
|
+
*/
|
|
14
|
+
export class MemoryStore {
|
|
15
|
+
constructor(private readonly store: BaseStore) {}
|
|
16
|
+
|
|
17
|
+
async put<T extends Record<string, unknown>>(
|
|
18
|
+
namespace: string[],
|
|
19
|
+
key: string,
|
|
20
|
+
value: T,
|
|
21
|
+
): Promise<void> {
|
|
22
|
+
await this.store.put(namespace, key, {
|
|
23
|
+
...value,
|
|
24
|
+
updatedAt: new Date().toISOString(),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async get<T = Record<string, unknown>>(
|
|
29
|
+
namespace: string[],
|
|
30
|
+
key: string,
|
|
31
|
+
): Promise<MemoryRecord<T> | null> {
|
|
32
|
+
const item = await this.store.get(namespace, key);
|
|
33
|
+
if (!item) return null;
|
|
34
|
+
|
|
35
|
+
return toRecord<T>(item);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async search<T = Record<string, unknown>>(
|
|
39
|
+
namespacePrefix: string[],
|
|
40
|
+
limit = 20,
|
|
41
|
+
): Promise<MemoryRecord<T>[]> {
|
|
42
|
+
const items = await this.store.search(namespacePrefix, { limit });
|
|
43
|
+
|
|
44
|
+
return items.map((item) => toRecord<T>(item));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async delete(namespace: string[], key: string): Promise<void> {
|
|
48
|
+
await this.store.delete(namespace, key);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const toRecord = <T>(item: Item): MemoryRecord<T> => {
|
|
53
|
+
return {
|
|
54
|
+
key: item.key,
|
|
55
|
+
namespace: item.namespace,
|
|
56
|
+
value: item.value as T,
|
|
57
|
+
...(item.updatedAt ? { updatedAt: new Date(item.updatedAt).toISOString() } : {}),
|
|
58
|
+
};
|
|
59
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ApprovalMode } from "../config/index.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 会修改状态或操作基础设施的工具。它们会通过 `interruptOn` 暂停,
|
|
5
|
+
* 等待人工批准后再执行。
|
|
6
|
+
*/
|
|
7
|
+
export const SENSITIVE_TOOLS = [
|
|
8
|
+
"write_file",
|
|
9
|
+
"edit_file",
|
|
10
|
+
"delete",
|
|
11
|
+
"execute",
|
|
12
|
+
"write_workspace_file",
|
|
13
|
+
"query_database",
|
|
14
|
+
] as const;
|
|
15
|
+
|
|
16
|
+
/** 模板已知的全部工具名称。 */
|
|
17
|
+
export const KNOWN_TOOLS = [
|
|
18
|
+
...SENSITIVE_TOOLS,
|
|
19
|
+
"read_file",
|
|
20
|
+
"read_workspace_file",
|
|
21
|
+
"list_workspace_files",
|
|
22
|
+
"ls",
|
|
23
|
+
"glob",
|
|
24
|
+
"grep",
|
|
25
|
+
"write_todos",
|
|
26
|
+
"task",
|
|
27
|
+
] as const;
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 构建 `createDeepAgent` 使用的 `interruptOn` 映射。
|
|
31
|
+
*
|
|
32
|
+
* - none:不启用审批
|
|
33
|
+
* - sensitive:修改类工具执行前暂停(默认)
|
|
34
|
+
* - all:所有已知工具执行前都暂停
|
|
35
|
+
*/
|
|
36
|
+
export const createApprovalPolicy = (mode: ApprovalMode): Record<string, boolean> => {
|
|
37
|
+
if (mode === "none") return {};
|
|
38
|
+
|
|
39
|
+
const tools = mode === "all" ? [...KNOWN_TOOLS] : [...SENSITIVE_TOOLS];
|
|
40
|
+
|
|
41
|
+
return Object.fromEntries(tools.map((tool) => [tool, true]));
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const requiresApproval = (mode: ApprovalMode, toolName: string): boolean => {
|
|
45
|
+
if (mode === "none") return false;
|
|
46
|
+
if (mode === "all") return (KNOWN_TOOLS as readonly string[]).includes(toolName);
|
|
47
|
+
|
|
48
|
+
return (SENSITIVE_TOOLS as readonly string[]).includes(toolName);
|
|
49
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
export const runtimeContextSchema = z.object({
|
|
5
|
+
tenantId: z.string().default("default"),
|
|
6
|
+
userId: z.string().optional(),
|
|
7
|
+
threadId: z.string().optional(),
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
export type RuntimeContext = z.infer<typeof runtimeContextSchema>;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 把每次请求的上下文注入系统提示词。上下文由 API 通过
|
|
14
|
+
* `config.context` 提供,不会随会话持久化。
|
|
15
|
+
*/
|
|
16
|
+
export const createContextMiddleware = () => {
|
|
17
|
+
return createMiddleware({
|
|
18
|
+
name: "ContextMiddleware",
|
|
19
|
+
contextSchema: runtimeContextSchema,
|
|
20
|
+
|
|
21
|
+
wrapModelCall: async (request, handler) => {
|
|
22
|
+
const context = runtimeContextSchema.parse(request.runtime.context ?? {});
|
|
23
|
+
const lines = [
|
|
24
|
+
"## 运行时上下文",
|
|
25
|
+
`- 租户:${context.tenantId}`,
|
|
26
|
+
...(context.userId ? [`- 用户:${context.userId}`] : []),
|
|
27
|
+
...(context.threadId ? [`- 会话:${context.threadId}`] : []),
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const systemPrompt = [request.systemPrompt, lines.join("\n")]
|
|
31
|
+
.filter((part): part is string => Boolean(part && part.trim()))
|
|
32
|
+
.join("\n\n");
|
|
33
|
+
|
|
34
|
+
return handler({ ...request, systemPrompt, systemMessage: undefined });
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createApprovalPolicy,
|
|
3
|
+
KNOWN_TOOLS,
|
|
4
|
+
requiresApproval,
|
|
5
|
+
SENSITIVE_TOOLS,
|
|
6
|
+
} from "./approval.js";
|
|
7
|
+
export { createContextMiddleware, runtimeContextSchema, type RuntimeContext } from "./context.js";
|
|
8
|
+
export { createLoggingMiddleware } from "./logging.js";
|
|
9
|
+
export { createSecurityMiddleware, DANGEROUS_PATTERNS, findSecurityViolation } from "./security.js";
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
|
|
3
|
+
import type { Logger } from "../storage/logger/index.js";
|
|
4
|
+
import { errorMessage, truncate } from "../utils/helpers.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 为每次模型和工具调用输出结构化日志。
|
|
8
|
+
* 对 payload 做截断,避免大段工具输出淹没日志。
|
|
9
|
+
*/
|
|
10
|
+
export const createLoggingMiddleware = (logger: Logger) => {
|
|
11
|
+
return createMiddleware({
|
|
12
|
+
name: "LoggingMiddleware",
|
|
13
|
+
|
|
14
|
+
wrapModelCall: async (request, handler) => {
|
|
15
|
+
const startedAt = Date.now();
|
|
16
|
+
|
|
17
|
+
return Promise.resolve(handler(request)).then(
|
|
18
|
+
(response) => {
|
|
19
|
+
logger.debug(
|
|
20
|
+
{
|
|
21
|
+
model: request.model?.getName?.() ?? "未知",
|
|
22
|
+
durationMs: Date.now() - startedAt,
|
|
23
|
+
toolCalls: response.tool_calls?.length ?? 0,
|
|
24
|
+
},
|
|
25
|
+
"模型调用完成",
|
|
26
|
+
);
|
|
27
|
+
return response;
|
|
28
|
+
},
|
|
29
|
+
(error: unknown) => {
|
|
30
|
+
logger.error(
|
|
31
|
+
{ durationMs: Date.now() - startedAt, error: errorMessage(error) },
|
|
32
|
+
"模型调用失败",
|
|
33
|
+
);
|
|
34
|
+
throw error;
|
|
35
|
+
},
|
|
36
|
+
);
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
wrapToolCall: async (request, handler) => {
|
|
40
|
+
const startedAt = Date.now();
|
|
41
|
+
logger.debug(
|
|
42
|
+
{
|
|
43
|
+
tool: request.toolCall.name,
|
|
44
|
+
args: truncate(JSON.stringify(request.toolCall.args ?? {}), 500),
|
|
45
|
+
},
|
|
46
|
+
"工具调用开始",
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
return Promise.resolve(handler(request)).then(
|
|
50
|
+
(result) => {
|
|
51
|
+
logger.debug(
|
|
52
|
+
{ tool: request.toolCall.name, durationMs: Date.now() - startedAt },
|
|
53
|
+
"工具调用完成",
|
|
54
|
+
);
|
|
55
|
+
return result;
|
|
56
|
+
},
|
|
57
|
+
(error: unknown) => {
|
|
58
|
+
logger.error(
|
|
59
|
+
{
|
|
60
|
+
tool: request.toolCall.name,
|
|
61
|
+
durationMs: Date.now() - startedAt,
|
|
62
|
+
error: errorMessage(error),
|
|
63
|
+
},
|
|
64
|
+
"工具调用失败",
|
|
65
|
+
);
|
|
66
|
+
throw error;
|
|
67
|
+
},
|
|
68
|
+
);
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
};
|