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,57 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
|
|
3
|
+
import { Pool } from "pg";
|
|
4
|
+
|
|
5
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
6
|
+
import { errorMessage } from "../../utils/helpers.js";
|
|
7
|
+
|
|
8
|
+
let pool;
|
|
9
|
+
|
|
10
|
+
/** 懒加载共享的 PostgreSQL 连接池。 */
|
|
11
|
+
export const getPool = (connectionString = process.env.DATABASE_URL) => {
|
|
12
|
+
if (!connectionString) {
|
|
13
|
+
throw new ConfigurationError(
|
|
14
|
+
"未配置 PostgreSQL 连接信息。请设置 DATABASE_URL 或 POSTGRES_* 后使用数据库功能。",
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
pool ??= new Pool({
|
|
19
|
+
connectionString,
|
|
20
|
+
max: 10,
|
|
21
|
+
idleTimeoutMillis: 30_000,
|
|
22
|
+
connectionTimeoutMillis: 5_000,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
return pool;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const probe = async (connectionString) => {
|
|
29
|
+
const client = await getPool(connectionString).connect();
|
|
30
|
+
const startedAt = performance.now();
|
|
31
|
+
|
|
32
|
+
return client
|
|
33
|
+
.query("select 1")
|
|
34
|
+
.then(() => ({ ok: true, latencyMs: Math.round(performance.now() - startedAt) }))
|
|
35
|
+
.finally(() => client.release());
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** 健康检查只返回状态,不向上抛错:连接或查询失败都折算成 `ok: false`。 */
|
|
39
|
+
export const checkDatabase = async (connectionString = process.env.DATABASE_URL) => {
|
|
40
|
+
if (!connectionString) {
|
|
41
|
+
return { ok: false, error: "未配置 PostgreSQL 连接信息" };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return probe(connectionString).catch((error) => ({
|
|
45
|
+
ok: false,
|
|
46
|
+
error: errorMessage(error),
|
|
47
|
+
}));
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
export const closeDatabase = async () => {
|
|
51
|
+
if (!pool) return;
|
|
52
|
+
|
|
53
|
+
const current = pool;
|
|
54
|
+
pool = undefined;
|
|
55
|
+
|
|
56
|
+
await current.end();
|
|
57
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
-- 可选的业务表。
|
|
2
|
+
--
|
|
3
|
+
-- LangGraph 的 PostgresSaver 和 PostgresStore 在设置
|
|
4
|
+
-- CHECKPOINTER=postgres / STORE=postgres 后,会通过 `.setup()` 自行创建并迁移
|
|
5
|
+
-- 所需的表;本迁移只用于应用自有的表结构。
|
|
6
|
+
--
|
|
7
|
+
-- 使用 psql 或你常用的迁移工具执行:
|
|
8
|
+
-- psql "$DATABASE_URL" -f src/storage/database/migrations/001_init.sql
|
|
9
|
+
|
|
10
|
+
CREATE TABLE IF NOT EXISTS agent_audit_log (
|
|
11
|
+
id BIGSERIAL PRIMARY KEY,
|
|
12
|
+
tenant_id TEXT NOT NULL DEFAULT 'default',
|
|
13
|
+
thread_id TEXT NOT NULL,
|
|
14
|
+
event TEXT NOT NULL,
|
|
15
|
+
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
|
16
|
+
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
17
|
+
);
|
|
18
|
+
|
|
19
|
+
CREATE INDEX IF NOT EXISTS agent_audit_log_thread_idx
|
|
20
|
+
ON agent_audit_log (tenant_id, thread_id, created_at DESC);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import pino from "pino";
|
|
2
|
+
|
|
3
|
+
/** `LOG_PRETTY=true` 时使用的 pino-pretty 传输配置。 */
|
|
4
|
+
const PRETTY_TRANSPORT = {
|
|
5
|
+
transport: {
|
|
6
|
+
target: "pino-pretty",
|
|
7
|
+
options: {
|
|
8
|
+
colorize: true,
|
|
9
|
+
translateTime: "SYS:standard",
|
|
10
|
+
ignore: "pid,hostname",
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const createLogger = (config) => {
|
|
16
|
+
return pino({
|
|
17
|
+
level: config.logging.level,
|
|
18
|
+
base: { service: "deepagent", env: config.env.NODE_ENV },
|
|
19
|
+
...(config.logging.pretty ? PRETTY_TRANSPORT : {}),
|
|
20
|
+
});
|
|
21
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
|
|
3
|
+
import { Redis } from "ioredis";
|
|
4
|
+
|
|
5
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
6
|
+
import { errorMessage } from "../../utils/helpers.js";
|
|
7
|
+
|
|
8
|
+
let client;
|
|
9
|
+
|
|
10
|
+
/** 懒加载共享的 Redis 客户端(首次执行命令时才建立连接)。 */
|
|
11
|
+
export const getRedis = (url = process.env.REDIS_URL) => {
|
|
12
|
+
if (!url) {
|
|
13
|
+
throw new ConfigurationError("未配置 REDIS_URL。请先在 .env 中设置后再使用 Redis 功能。");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
client ??= new Redis(url, {
|
|
17
|
+
lazyConnect: true,
|
|
18
|
+
maxRetriesPerRequest: 1,
|
|
19
|
+
enableOfflineQueue: false,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
return client;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const probe = async () => {
|
|
26
|
+
const redis = getRedis();
|
|
27
|
+
if (redis.status === "wait") await redis.connect();
|
|
28
|
+
|
|
29
|
+
const startedAt = performance.now();
|
|
30
|
+
await redis.ping();
|
|
31
|
+
|
|
32
|
+
return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** 健康检查只返回状态,不向上抛错:连接或 ping 失败都折算成 `ok: false`。 */
|
|
36
|
+
export const checkRedis = async () => {
|
|
37
|
+
if (!process.env.REDIS_URL) {
|
|
38
|
+
return { ok: false, error: "未配置 REDIS_URL" };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
return probe().catch((error) => ({ ok: false, error: errorMessage(error) }));
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
export const closeRedis = async () => {
|
|
45
|
+
if (!client) return;
|
|
46
|
+
|
|
47
|
+
const current = client;
|
|
48
|
+
client = undefined;
|
|
49
|
+
|
|
50
|
+
await current.quit().catch(() => current.disconnect());
|
|
51
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { errorMessage } from "../../utils/helpers.js";
|
|
2
|
+
|
|
3
|
+
const withTimeout = (promise, timeoutMs) => {
|
|
4
|
+
let timer;
|
|
5
|
+
|
|
6
|
+
const timeout = new Promise((_, reject) => {
|
|
7
|
+
timer = setTimeout(() => reject(new Error(`hook 执行超时(${timeoutMs}ms)`)), timeoutMs);
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
11
|
+
if (timer) clearTimeout(timer);
|
|
12
|
+
});
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const createShutdownManager = ({ logger, timeoutMs = 10_000 }) => {
|
|
16
|
+
const hooks = [];
|
|
17
|
+
let pending;
|
|
18
|
+
|
|
19
|
+
const closeHook = (hook) => {
|
|
20
|
+
return withTimeout(Promise.resolve(hook.close()), timeoutMs).then(
|
|
21
|
+
() => logger.info({ hook: hook.name }, "已关闭"),
|
|
22
|
+
(error) => logger.warn({ hook: hook.name, error: errorMessage(error) }, "关闭资源失败"),
|
|
23
|
+
);
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const run = async (reason) => {
|
|
27
|
+
logger.info({ reason, hooks: hooks.map((hook) => hook.name) }, "开始关闭");
|
|
28
|
+
|
|
29
|
+
await Promise.all(hooks.map(closeHook));
|
|
30
|
+
|
|
31
|
+
logger.info("关闭完成");
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const manager = {
|
|
35
|
+
register: (hook) => {
|
|
36
|
+
hooks.push(hook);
|
|
37
|
+
return () => {
|
|
38
|
+
const index = hooks.findIndex((item) => item === hook);
|
|
39
|
+
if (index >= 0) hooks.splice(index, 1);
|
|
40
|
+
};
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
shutdown: (reason = "shutdown") => {
|
|
44
|
+
pending ??= run(reason);
|
|
45
|
+
return pending;
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
install: () => {
|
|
49
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
50
|
+
process.once(signal, () => {
|
|
51
|
+
void manager.shutdown(signal).finally(() => process.exit(0));
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
return manager;
|
|
58
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { assertReadOnlyQuery, createQueryDatabaseTool } from "./query.js";
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { tool } from "@langchain/core/tools";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
import { getPool } from "../../storage/database/client.js";
|
|
5
|
+
|
|
6
|
+
const READ_ONLY_START = /^\s*(?:select|with)\b/i;
|
|
7
|
+
const FORBIDDEN_KEYWORDS =
|
|
8
|
+
/\b(insert|update|delete|drop|alter|truncate|create|grant|revoke|copy|vacuum|reindex|call|do)\b/i;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 对模型生成的 SQL 做前置校验。查询同时运行在 READ ONLY 事务中,
|
|
12
|
+
* 即使绕过校验也无法修改数据。
|
|
13
|
+
*/
|
|
14
|
+
export const assertReadOnlyQuery = (sql) => {
|
|
15
|
+
const statement = sql.trim().replace(/;\s*$/, "");
|
|
16
|
+
|
|
17
|
+
if (!READ_ONLY_START.test(statement)) {
|
|
18
|
+
throw new Error("只允许 SELECT 和 WITH 查询。");
|
|
19
|
+
}
|
|
20
|
+
if (statement.includes(";")) {
|
|
21
|
+
throw new Error("只允许单条 SQL 语句。");
|
|
22
|
+
}
|
|
23
|
+
if (FORBIDDEN_KEYWORDS.test(statement)) {
|
|
24
|
+
throw new Error("查询包含写入或 DDL 关键字,已拒绝执行。");
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const querySchema = z.object({
|
|
29
|
+
sql: z.string().min(1).describe("单条只读 SQL 语句(SELECT 或 WITH)。"),
|
|
30
|
+
params: z
|
|
31
|
+
.array(z.union([z.string(), z.number(), z.boolean(), z.null()]))
|
|
32
|
+
.default([])
|
|
33
|
+
.describe("与 $1、$2…… 占位符对应的位置参数。"),
|
|
34
|
+
limit: z.number().int().min(1).max(500).default(100),
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/** 只读、参数化的 PostgreSQL 查询工具。 */
|
|
38
|
+
export const createQueryDatabaseTool = ({ connectionString } = {}) => {
|
|
39
|
+
return tool(
|
|
40
|
+
async ({ sql, params, limit }) => {
|
|
41
|
+
assertReadOnlyQuery(sql);
|
|
42
|
+
|
|
43
|
+
const client = await getPool(connectionString).connect();
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
await client.query("BEGIN TRANSACTION READ ONLY");
|
|
47
|
+
await client.query("SET LOCAL statement_timeout = '10s'");
|
|
48
|
+
|
|
49
|
+
const result = await client.query(sql, params);
|
|
50
|
+
await client.query("COMMIT");
|
|
51
|
+
|
|
52
|
+
return JSON.stringify(
|
|
53
|
+
{
|
|
54
|
+
rowCount: result.rowCount,
|
|
55
|
+
truncated: result.rows.length > limit,
|
|
56
|
+
rows: result.rows.slice(0, limit),
|
|
57
|
+
},
|
|
58
|
+
null,
|
|
59
|
+
2,
|
|
60
|
+
);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
await client.query("ROLLBACK").catch(() => undefined);
|
|
63
|
+
throw error;
|
|
64
|
+
} finally {
|
|
65
|
+
client.release();
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: "query_database",
|
|
70
|
+
description: "对应用 PostgreSQL 执行单条只读 SQL,并以 JSON 返回结果行。",
|
|
71
|
+
schema: querySchema,
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
};
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import nodePath from "node:path";
|
|
3
|
+
|
|
4
|
+
import { tool } from "@langchain/core/tools";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
|
|
7
|
+
const resolveInsideRoot = (rootDir, target) => {
|
|
8
|
+
const root = nodePath.resolve(rootDir);
|
|
9
|
+
const resolved = nodePath.resolve(root, target);
|
|
10
|
+
|
|
11
|
+
if (resolved !== root && !resolved.startsWith(`${root}${nodePath.sep}`)) {
|
|
12
|
+
throw new Error(`路径越出了工作区根目录:${target}`);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
return resolved;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 面向应用自有文件的额外工作区工具。Deep Agents 已内置对后端的
|
|
20
|
+
* read_file/write_file/edit_file;这些工具限定在 `workspaces/` 内,
|
|
21
|
+
* 方便服务层(而不是模型)安全地读取产物。
|
|
22
|
+
*/
|
|
23
|
+
export const createWorkspaceTools = ({ rootDir, maxReadBytes = 200_000 }) => {
|
|
24
|
+
const readSchema = z.object({
|
|
25
|
+
filePath: z.string().min(1).describe("相对于工作区根目录的路径。"),
|
|
26
|
+
maxBytes: z.number().int().positive().default(maxReadBytes),
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const readFile = tool(
|
|
30
|
+
async ({ filePath, maxBytes }) => {
|
|
31
|
+
const resolved = resolveInsideRoot(rootDir, filePath);
|
|
32
|
+
const content = await fs.readFile(resolved, "utf8");
|
|
33
|
+
if (content.length <= maxBytes) return content;
|
|
34
|
+
|
|
35
|
+
return `${content.slice(0, maxBytes)}\n… 已在 ${maxBytes} 个字符处截断`;
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: "read_workspace_file",
|
|
39
|
+
description: "按相对于工作区根目录的路径读取 Agent 工作区中的文件。",
|
|
40
|
+
schema: readSchema,
|
|
41
|
+
},
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
const writeSchema = z.object({
|
|
45
|
+
filePath: z.string().min(1),
|
|
46
|
+
content: z.string(),
|
|
47
|
+
append: z.boolean().default(false),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
const writeFile = tool(
|
|
51
|
+
async ({ filePath, content, append }) => {
|
|
52
|
+
const resolved = resolveInsideRoot(rootDir, filePath);
|
|
53
|
+
await fs.mkdir(nodePath.dirname(resolved), { recursive: true });
|
|
54
|
+
|
|
55
|
+
if (append) {
|
|
56
|
+
await fs.appendFile(resolved, content, "utf8");
|
|
57
|
+
} else {
|
|
58
|
+
await fs.writeFile(resolved, content, "utf8");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return `已写入 ${content.length} 个字符到 ${filePath}`;
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: "write_workspace_file",
|
|
65
|
+
description: "在 Agent 工作区中创建或覆盖文件,也可以选择追加内容。",
|
|
66
|
+
schema: writeSchema,
|
|
67
|
+
},
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
const listSchema = z.object({
|
|
71
|
+
directory: z.string().default("."),
|
|
72
|
+
recursive: z.boolean().default(false),
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const listFiles = tool(
|
|
76
|
+
async ({ directory, recursive }) => {
|
|
77
|
+
const resolved = resolveInsideRoot(rootDir, directory);
|
|
78
|
+
const entries = await fs.readdir(resolved, {
|
|
79
|
+
recursive,
|
|
80
|
+
withFileTypes: true,
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const files = entries
|
|
84
|
+
.map((entry) => ({
|
|
85
|
+
name: entry.name,
|
|
86
|
+
path: nodePath.relative(rootDir, nodePath.join(entry.parentPath, entry.name)),
|
|
87
|
+
type: entry.isDirectory() ? "目录" : "文件",
|
|
88
|
+
}))
|
|
89
|
+
.sort((a, b) => a.path.localeCompare(b.path))
|
|
90
|
+
.slice(0, 500);
|
|
91
|
+
|
|
92
|
+
return JSON.stringify({ root: directory, files }, null, 2);
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: "list_workspace_files",
|
|
96
|
+
description: "列出 Agent 工作区中的文件和目录,不读取文件内容。",
|
|
97
|
+
schema: listSchema,
|
|
98
|
+
},
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
return [readFile, writeFile, listFiles];
|
|
102
|
+
};
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createQueryDatabaseTool } from "./database/index.js";
|
|
2
|
+
import { createWorkspaceTools } from "./filesystem/index.js";
|
|
3
|
+
|
|
4
|
+
export { assertReadOnlyQuery, createQueryDatabaseTool } from "./database/index.js";
|
|
5
|
+
export { createWorkspaceTools } from "./filesystem/index.js";
|
|
6
|
+
export {
|
|
7
|
+
createMcpAdapter,
|
|
8
|
+
createMcpToolRegistry,
|
|
9
|
+
loadMcpConnections,
|
|
10
|
+
loadMcpTools,
|
|
11
|
+
McpToolRegistry,
|
|
12
|
+
mcpServerSchema,
|
|
13
|
+
} from "./mcp/index.js";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 主 Agent 和子 Agent 可用的工具,位于 Deep Agents 内置工具
|
|
17
|
+
* (write_todos、read_file、write_file、task 等)之上。
|
|
18
|
+
*/
|
|
19
|
+
export const createDefaultTools = ({ workspaceRoot, databaseUrl, additionalTools = [] }) => {
|
|
20
|
+
return [
|
|
21
|
+
...(databaseUrl ? [createQueryDatabaseTool({ connectionString: databaseUrl })] : []),
|
|
22
|
+
...createWorkspaceTools({ rootDir: workspaceRoot }),
|
|
23
|
+
...additionalTools,
|
|
24
|
+
];
|
|
25
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { MCPAdapter } from "@langchain/mcp-adapters";
|
|
2
|
+
|
|
3
|
+
const toAdapterServers = (connections) => {
|
|
4
|
+
const servers = {};
|
|
5
|
+
|
|
6
|
+
for (const [name, connection] of Object.entries(connections)) {
|
|
7
|
+
if (connection.transport === "stdio") {
|
|
8
|
+
servers[name] = {
|
|
9
|
+
transport: "stdio",
|
|
10
|
+
command: connection.command,
|
|
11
|
+
args: connection.args,
|
|
12
|
+
env: connection.env,
|
|
13
|
+
};
|
|
14
|
+
} else if (connection.transport === "http") {
|
|
15
|
+
servers[name] = { transport: "http", url: connection.url };
|
|
16
|
+
} else {
|
|
17
|
+
servers[name] = { transport: "sse", url: connection.url };
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return servers;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** 创建多服务器 MCP 适配器;连接按需建立。 */
|
|
25
|
+
export const createMcpAdapter = (connections) => {
|
|
26
|
+
return new MCPAdapter({
|
|
27
|
+
servers: toAdapterServers(connections),
|
|
28
|
+
onConnectionError: "ignore",
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** 加载已配置的 MCP 服务器暴露的全部工具。 */
|
|
33
|
+
export const loadMcpTools = async (connections) => {
|
|
34
|
+
if (Object.keys(connections).length === 0) {
|
|
35
|
+
return { adapter: null, tools: [] };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const adapter = createMcpAdapter(connections);
|
|
39
|
+
const tools = await adapter.listTools();
|
|
40
|
+
|
|
41
|
+
return { adapter, tools };
|
|
42
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
4
|
+
import { errorMessage } from "../../utils/helpers.js";
|
|
5
|
+
|
|
6
|
+
const stdioConnectionSchema = z.object({
|
|
7
|
+
transport: z.literal("stdio"),
|
|
8
|
+
command: z.string().min(1),
|
|
9
|
+
args: z.array(z.string()).default([]),
|
|
10
|
+
env: z.record(z.string(), z.string()).default({}),
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
const httpConnectionSchema = z.object({
|
|
14
|
+
transport: z.literal("http"),
|
|
15
|
+
url: z.string().min(1),
|
|
16
|
+
headers: z.record(z.string(), z.string()).default({}),
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const sseConnectionSchema = z.object({
|
|
20
|
+
transport: z.literal("sse"),
|
|
21
|
+
url: z.string().min(1),
|
|
22
|
+
headers: z.record(z.string(), z.string()).default({}),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
export const mcpServerSchema = z.discriminatedUnion("transport", [
|
|
26
|
+
stdioConnectionSchema,
|
|
27
|
+
httpConnectionSchema,
|
|
28
|
+
sseConnectionSchema,
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 从 `MCP_SERVERS`(JSON)或已解析的对象中读取 MCP 连接配置。
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* MCP_SERVERS='{"filesystem":{"transport":"stdio","command":"npx","args":["-y","@modelcontextprotocol/server-filesystem","."]}}'
|
|
36
|
+
*/
|
|
37
|
+
export const loadMcpConnections = (raw = process.env.MCP_SERVERS) => {
|
|
38
|
+
if (!raw || raw.trim() === "") return {};
|
|
39
|
+
|
|
40
|
+
let parsed;
|
|
41
|
+
try {
|
|
42
|
+
parsed = JSON.parse(raw);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new ConfigurationError(`MCP_SERVERS 必须是合法的 JSON:${errorMessage(error)}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
48
|
+
throw new ConfigurationError("MCP_SERVERS 必须是以服务器名称为键的对象。");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const entries = Object.entries(parsed).map(([name, value]) => {
|
|
52
|
+
const result = mcpServerSchema.safeParse(value);
|
|
53
|
+
if (!result.success) {
|
|
54
|
+
const issues = result.error.issues
|
|
55
|
+
.map((issue) => `${issue.path.join(".") || name}: ${issue.message}`)
|
|
56
|
+
.join("; ");
|
|
57
|
+
throw new ConfigurationError(`MCP 服务器 "${name}" 配置无效:${issues}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return [name, result.data];
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
return Object.fromEntries(entries);
|
|
64
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { McpToolRegistry } from "./registry.js";
|
|
2
|
+
|
|
3
|
+
export { createMcpAdapter, loadMcpTools } from "./client.js";
|
|
4
|
+
export { loadMcpConnections, mcpServerSchema } from "./connections.js";
|
|
5
|
+
export { McpToolRegistry };
|
|
6
|
+
|
|
7
|
+
/** 启动时加载一次 MCP 工具;未配置时返回空注册表。 */
|
|
8
|
+
export const createMcpToolRegistry = async () => {
|
|
9
|
+
return McpToolRegistry.create();
|
|
10
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { loadMcpTools } from "./client.js";
|
|
2
|
+
import { loadMcpConnections } from "./connections.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 持有整个进程生命周期的 MCP 适配器。启动时加载一次工具并交给主 Agent;
|
|
6
|
+
* 关闭时断开连接。
|
|
7
|
+
*/
|
|
8
|
+
export class McpToolRegistry {
|
|
9
|
+
tools;
|
|
10
|
+
adapter;
|
|
11
|
+
servers;
|
|
12
|
+
|
|
13
|
+
constructor(adapter, tools, servers) {
|
|
14
|
+
this.adapter = adapter;
|
|
15
|
+
this.tools = tools;
|
|
16
|
+
this.servers = servers;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
static async create(connections = loadMcpConnections()) {
|
|
20
|
+
if (Object.keys(connections).length === 0) {
|
|
21
|
+
return new McpToolRegistry(null, [], []);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const { adapter, tools } = await loadMcpTools(connections);
|
|
25
|
+
|
|
26
|
+
return new McpToolRegistry(adapter, tools, Object.keys(connections));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
get serverNames() {
|
|
30
|
+
return [...this.servers];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async close() {
|
|
34
|
+
await this.adapter?.close();
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 可以安全通过 HTTP API 暴露的错误基类。
|
|
3
|
+
* 非 AppError 的错误统一按 500 处理。
|
|
4
|
+
*/
|
|
5
|
+
export class AppError extends Error {
|
|
6
|
+
status;
|
|
7
|
+
code;
|
|
8
|
+
details;
|
|
9
|
+
|
|
10
|
+
constructor(message, options = {}) {
|
|
11
|
+
super(message, { cause: options.cause });
|
|
12
|
+
this.name = new.target.name;
|
|
13
|
+
this.status = options.status ?? 500;
|
|
14
|
+
this.code = options.code ?? "INTERNAL_ERROR";
|
|
15
|
+
this.details = options.details;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
toJSON() {
|
|
19
|
+
return {
|
|
20
|
+
error: {
|
|
21
|
+
code: this.code,
|
|
22
|
+
message: this.message,
|
|
23
|
+
...(this.details ? { details: this.details } : {}),
|
|
24
|
+
},
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class ConfigurationError extends AppError {
|
|
30
|
+
constructor(message, details) {
|
|
31
|
+
super(message, { status: 500, code: "CONFIGURATION_ERROR", details });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export class ValidationError extends AppError {
|
|
36
|
+
constructor(message, details) {
|
|
37
|
+
super(message, { status: 400, code: "VALIDATION_ERROR", details });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class UnauthorizedError extends AppError {
|
|
42
|
+
constructor(message = "缺少凭证或凭证无效。") {
|
|
43
|
+
super(message, { status: 401, code: "UNAUTHORIZED" });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export class NotFoundError extends AppError {
|
|
48
|
+
constructor(message = "资源不存在。") {
|
|
49
|
+
super(message, { status: 404, code: "NOT_FOUND" });
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export class ConflictError extends AppError {
|
|
54
|
+
constructor(message = "资源冲突。") {
|
|
55
|
+
super(message, { status: 409, code: "CONFLICT" });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const toErrorResponse = (error) => {
|
|
60
|
+
if (error instanceof AppError) {
|
|
61
|
+
return { status: error.status, body: error.toJSON() };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
status: 500,
|
|
66
|
+
body: {
|
|
67
|
+
error: {
|
|
68
|
+
code: "INTERNAL_ERROR",
|
|
69
|
+
message: error instanceof Error ? error.message : "发生了未预期的错误。",
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
};
|