create-deepagent-server 0.0.0-stage → 0.1.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 +218 -2
- package/bin/create-deepagent-server.js +27 -0
- package/package.json +50 -4
- package/src/args.js +193 -0
- package/src/cli.js +269 -0
- package/src/dependencies.js +34 -0
- package/src/prompts.js +85 -0
- package/src/registry.js +68 -0
- package/src/scaffold.js +182 -0
- package/src/setup.js +77 -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 +74 -0
- package/templates/deepagent/js/scripts/dev.js +31 -0
- package/templates/deepagent/js/src/agents/factory.js +10 -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 +44 -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/subagents/researcher.md +16 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.js +17 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.md +42 -0
- package/templates/deepagent/js/src/agents/state/index.js +1 -0
- package/templates/deepagent/js/src/agents/state/types.js +10 -0
- package/templates/deepagent/js/src/agents/subagents/analyst.js +11 -0
- package/templates/deepagent/js/src/agents/subagents/coder.js +11 -0
- package/templates/deepagent/js/src/agents/subagents/index.js +8 -0
- package/templates/deepagent/js/src/agents/subagents/researcher.js +12 -0
- package/templates/deepagent/js/src/agents/supervisor.js +56 -0
- package/templates/deepagent/js/src/api/app.js +22 -0
- package/templates/deepagent/js/src/api/middleware/auth.js +27 -0
- package/templates/deepagent/js/src/api/middleware/error.js +26 -0
- package/templates/deepagent/js/src/api/routes/agent.js +73 -0
- package/templates/deepagent/js/src/api/routes/health.js +31 -0
- package/templates/deepagent/js/src/api/routes/session.js +62 -0
- package/templates/deepagent/js/src/app.js +79 -0
- package/templates/deepagent/js/src/backends/composite.js +20 -0
- package/templates/deepagent/js/src/backends/filesystem.js +8 -0
- package/templates/deepagent/js/src/backends/index.js +28 -0
- package/templates/deepagent/js/src/backends/sandbox.js +23 -0
- package/templates/deepagent/js/src/config/agent.js +13 -0
- package/templates/deepagent/js/src/config/env.js +73 -0
- package/templates/deepagent/js/src/config/index.js +35 -0
- package/templates/deepagent/js/src/config/model.js +34 -0
- package/templates/deepagent/js/src/graph/checkpointer.js +20 -0
- package/templates/deepagent/js/src/graph/compile.js +8 -0
- package/templates/deepagent/js/src/graph/index.js +3 -0
- package/templates/deepagent/js/src/graph/store.js +20 -0
- package/templates/deepagent/js/src/index.js +32 -0
- package/templates/deepagent/js/src/infrastructure/database/client.js +43 -0
- package/templates/deepagent/js/src/infrastructure/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/js/src/infrastructure/logger/index.js +19 -0
- package/templates/deepagent/js/src/infrastructure/redis/client.js +45 -0
- package/templates/deepagent/js/src/infrastructure/shutdown/index.js +51 -0
- package/templates/deepagent/js/src/memory/index.js +6 -0
- package/templates/deepagent/js/src/memory/manager.js +39 -0
- package/templates/deepagent/js/src/memory/store.js +36 -0
- package/templates/deepagent/js/src/middleware/approval.js +42 -0
- package/templates/deepagent/js/src/middleware/context.js +30 -0
- package/templates/deepagent/js/src/middleware/index.js +9 -0
- package/templates/deepagent/js/src/middleware/logging.js +66 -0
- package/templates/deepagent/js/src/middleware/security.js +51 -0
- package/templates/deepagent/js/src/schemas/agent.js +33 -0
- package/templates/deepagent/js/src/schemas/common.js +19 -0
- package/templates/deepagent/js/src/schemas/locale.js +3 -0
- package/templates/deepagent/js/src/schemas/session.js +23 -0
- package/templates/deepagent/js/src/services/agent.service.js +117 -0
- package/templates/deepagent/js/src/services/memory.service.js +27 -0
- package/templates/deepagent/js/src/services/session.service.js +92 -0
- package/templates/deepagent/js/src/skills/index.js +17 -0
- package/templates/deepagent/js/src/skills/loader.js +65 -0
- package/templates/deepagent/js/src/tools/database/index.js +1 -0
- package/templates/deepagent/js/src/tools/database/query.js +62 -0
- package/templates/deepagent/js/src/tools/filesystem/index.js +86 -0
- package/templates/deepagent/js/src/tools/index.js +30 -0
- package/templates/deepagent/js/src/tools/mcp/client.js +35 -0
- package/templates/deepagent/js/src/tools/mcp/connections.js +54 -0
- package/templates/deepagent/js/src/tools/mcp/index.js +8 -0
- package/templates/deepagent/js/src/tools/mcp/registry.js +32 -0
- package/templates/deepagent/js/src/tools/search/index.js +1 -0
- package/templates/deepagent/js/src/tools/search/web-search.js +54 -0
- package/templates/deepagent/js/src/utils/errors.js +64 -0
- package/templates/deepagent/js/src/utils/helpers.js +42 -0
- package/templates/deepagent/js/tests/agents/prompts.test.js +24 -0
- package/templates/deepagent/js/tests/agents/supervisor.test.js +34 -0
- package/templates/deepagent/js/tests/integration/api.test.js +99 -0
- package/templates/deepagent/js/tests/middleware/security.test.js +24 -0
- package/templates/deepagent/js/tests/tools/query.test.js +23 -0
- package/templates/deepagent/shared/README.md +162 -0
- package/templates/deepagent/shared/_editorconfig +12 -0
- package/templates/deepagent/shared/_env.example +56 -0
- package/templates/deepagent/shared/_gitignore +22 -0
- package/templates/deepagent/shared/deployment/docker-compose.yml +56 -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/skills/research/SKILL.md +31 -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 +91 -0
- package/templates/deepagent/ts/scripts/copy-assets.ts +35 -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 +52 -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/subagents/researcher.md +16 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.md +42 -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 +14 -0
- package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
- package/templates/deepagent/ts/src/agents/subagents/index.ts +10 -0
- package/templates/deepagent/ts/src/agents/subagents/researcher.ts +15 -0
- package/templates/deepagent/ts/src/agents/supervisor.ts +80 -0
- package/templates/deepagent/ts/src/api/app.ts +48 -0
- package/templates/deepagent/ts/src/api/middleware/auth.ts +37 -0
- package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
- package/templates/deepagent/ts/src/api/routes/agent.ts +93 -0
- package/templates/deepagent/ts/src/api/routes/health.ts +45 -0
- package/templates/deepagent/ts/src/api/routes/session.ts +77 -0
- package/templates/deepagent/ts/src/app.ts +104 -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 +42 -0
- package/templates/deepagent/ts/src/backends/sandbox.ts +32 -0
- package/templates/deepagent/ts/src/config/agent.ts +37 -0
- package/templates/deepagent/ts/src/config/env.ts +102 -0
- package/templates/deepagent/ts/src/config/index.ts +76 -0
- package/templates/deepagent/ts/src/config/model.ts +49 -0
- package/templates/deepagent/ts/src/graph/checkpointer.ts +26 -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 +26 -0
- package/templates/deepagent/ts/src/index.ts +39 -0
- package/templates/deepagent/ts/src/infrastructure/database/client.ts +61 -0
- package/templates/deepagent/ts/src/infrastructure/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/ts/src/infrastructure/logger/index.ts +25 -0
- package/templates/deepagent/ts/src/infrastructure/redis/client.ts +64 -0
- package/templates/deepagent/ts/src/infrastructure/shutdown/index.ts +85 -0
- package/templates/deepagent/ts/src/memory/index.ts +11 -0
- package/templates/deepagent/ts/src/memory/manager.ts +74 -0
- package/templates/deepagent/ts/src/memory/store.ts +57 -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 +72 -0
- package/templates/deepagent/ts/src/middleware/security.ts +60 -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.service.ts +170 -0
- package/templates/deepagent/ts/src/services/memory.service.ts +43 -0
- package/templates/deepagent/ts/src/services/session.service.ts +148 -0
- package/templates/deepagent/ts/src/skills/index.ts +26 -0
- package/templates/deepagent/ts/src/skills/loader.ts +94 -0
- package/templates/deepagent/ts/src/tools/database/index.ts +1 -0
- package/templates/deepagent/ts/src/tools/database/query.ts +71 -0
- package/templates/deepagent/ts/src/tools/filesystem/index.ts +108 -0
- package/templates/deepagent/ts/src/tools/index.ts +41 -0
- package/templates/deepagent/ts/src/tools/mcp/client.ts +53 -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 +48 -0
- package/templates/deepagent/ts/src/tools/search/index.ts +1 -0
- package/templates/deepagent/ts/src/tools/search/web-search.ts +82 -0
- package/templates/deepagent/ts/src/utils/errors.ts +95 -0
- package/templates/deepagent/ts/src/utils/helpers.ts +52 -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/integration/api.test.ts +123 -0
- package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
- package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
- package/templates/deepagent/ts/tsconfig.json +19 -0
package/src/setup.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const LOCKFILES = [
|
|
6
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
7
|
+
["yarn.lock", "yarn"],
|
|
8
|
+
["bun.lockb", "bun"],
|
|
9
|
+
["bun.lock", "bun"],
|
|
10
|
+
["package-lock.json", "npm"],
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
/** 优先识别调用 CLI 的包管理器,其次根据 lockfile 推断。 */
|
|
14
|
+
export const detectPackageManager = ({ cwd = process.cwd(), env = process.env } = {}) => {
|
|
15
|
+
const userAgent = env.npm_config_user_agent ?? "";
|
|
16
|
+
|
|
17
|
+
for (const packageManager of ["pnpm", "yarn", "bun", "npm"]) {
|
|
18
|
+
if (userAgent.startsWith(`${packageManager}/`)) return packageManager;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
for (const [lockfile, packageManager] of LOCKFILES) {
|
|
22
|
+
if (existsSync(path.join(cwd, lockfile))) return packageManager;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return "npm";
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const installCommand = (packageManager) => {
|
|
29
|
+
const command = process.platform === "win32" ? `${packageManager}.cmd` : packageManager;
|
|
30
|
+
|
|
31
|
+
switch (packageManager) {
|
|
32
|
+
case "npm":
|
|
33
|
+
case "pnpm":
|
|
34
|
+
case "yarn":
|
|
35
|
+
case "bun":
|
|
36
|
+
return { command, args: ["install"] };
|
|
37
|
+
default:
|
|
38
|
+
throw new Error(`不支持的包管理器:${packageManager}`);
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const installCommandText = (packageManager) => {
|
|
43
|
+
return `${packageManager} install`;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
export const runInstall = (packageManager, cwd) => {
|
|
47
|
+
const { command, args } = installCommand(packageManager);
|
|
48
|
+
const result = spawnSync(command, args, { cwd, stdio: "inherit" });
|
|
49
|
+
|
|
50
|
+
if (result.error) {
|
|
51
|
+
const missingHint = `未在 PATH 中找到 "${packageManager}"。`;
|
|
52
|
+
const detail = result.error.code === "ENOENT" ? missingHint : result.error.message;
|
|
53
|
+
|
|
54
|
+
throw new Error(detail);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (result.status !== 0) {
|
|
58
|
+
throw new Error(`${installCommandText(packageManager)} 执行失败,退出码 ${result.status}。`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export const initGit = (cwd) => {
|
|
63
|
+
const result = spawnSync("git", ["init", "--quiet"], {
|
|
64
|
+
cwd,
|
|
65
|
+
stdio: "ignore",
|
|
66
|
+
});
|
|
67
|
+
return !result.error && result.status === 0;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export const runScriptText = (packageManager, script) => {
|
|
71
|
+
// `yarn check` 和 `npm check` 是内置命令,因此 npm、yarn、bun 统一走 `run`;
|
|
72
|
+
// pnpm 的简写不存在歧义。
|
|
73
|
+
if (packageManager === "pnpm") {
|
|
74
|
+
return `${packageManager} ${script}`;
|
|
75
|
+
}
|
|
76
|
+
return `${packageManager} run ${script}`;
|
|
77
|
+
};
|
package/src/ui.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
const colorEnabled =
|
|
2
|
+
Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
|
3
|
+
|
|
4
|
+
const style = (open, close) => (text) =>
|
|
5
|
+
colorEnabled ? `\u001b[${open}m${text}\u001b[${close}m` : String(text);
|
|
6
|
+
|
|
7
|
+
export const bold = style(1, 22);
|
|
8
|
+
export const dim = style(2, 22);
|
|
9
|
+
export const cyan = style(36, 39);
|
|
10
|
+
export const green = style(32, 39);
|
|
11
|
+
export const yellow = style(33, 39);
|
|
12
|
+
export const red = style(31, 39);
|
|
13
|
+
|
|
14
|
+
export const banner = (name, version) => {
|
|
15
|
+
console.log("");
|
|
16
|
+
console.log(`${bold(cyan(name))} ${dim(`v${version}`)}`);
|
|
17
|
+
console.log(dim("快速创建 Deep Agents 项目:任务规划、文件系统、子 Agent 与持久化。"));
|
|
18
|
+
console.log("");
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export const step = (message) => {
|
|
22
|
+
console.log(`${cyan("◇")} ${message}`);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const success = (message) => {
|
|
26
|
+
console.log(`${green("✔")} ${message}`);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const info = (message) => {
|
|
30
|
+
console.log(`${cyan("•")} ${message}`);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export const warn = (message) => {
|
|
34
|
+
console.log(`${yellow("▲")} ${message}`);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const error = (message) => {
|
|
38
|
+
console.error(`${red("✖")} ${message}`);
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export const blank = () => {
|
|
42
|
+
console.log("");
|
|
43
|
+
};
|
package/src/version.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.1.0";
|
package/src/versions.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 无法访问 npm registry 时使用的兜底版本(离线、代理、私有源缺少依赖等)。
|
|
3
|
+
*
|
|
4
|
+
* 正常生成项目时会在运行时从 registry 解析 `latest`;这里的值仅作回退,
|
|
5
|
+
* 随 CLI 发版一起更新。
|
|
6
|
+
*/
|
|
7
|
+
export const FALLBACK_VERSIONS = {
|
|
8
|
+
"@langchain/anthropic": "1.6.4",
|
|
9
|
+
"@langchain/core": "1.4.0",
|
|
10
|
+
"@langchain/langgraph": "1.7.3",
|
|
11
|
+
"@langchain/langgraph-checkpoint": "1.2.2",
|
|
12
|
+
"@langchain/langgraph-checkpoint-postgres": "1.1.2",
|
|
13
|
+
"@langchain/mcp-adapters": "2.0.3",
|
|
14
|
+
"@langchain/openai": "1.8.4",
|
|
15
|
+
deepagents: "1.16.4",
|
|
16
|
+
dotenv: "18.0.10",
|
|
17
|
+
express: "5.3.0",
|
|
18
|
+
ioredis: "6.0.0",
|
|
19
|
+
langchain: "1.6.5",
|
|
20
|
+
pg: "8.23.1",
|
|
21
|
+
pino: "10.4.0",
|
|
22
|
+
"pino-pretty": "13.2.0",
|
|
23
|
+
zod: "4.6.7",
|
|
24
|
+
typescript: "5.9.3",
|
|
25
|
+
tsx: "4.23.15",
|
|
26
|
+
"@types/node": "26.6.6",
|
|
27
|
+
"@types/express": "5.0.6",
|
|
28
|
+
"@types/pg": "8.23.1",
|
|
29
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# 安装生产依赖
|
|
2
|
+
FROM node:22-alpine AS deps
|
|
3
|
+
WORKDIR /app
|
|
4
|
+
COPY package.json ./
|
|
5
|
+
RUN npm install --omit=dev
|
|
6
|
+
|
|
7
|
+
# JavaScript 项目直接从 src/ 运行,无需构建
|
|
8
|
+
FROM node:22-alpine AS runtime
|
|
9
|
+
WORKDIR /app
|
|
10
|
+
ENV NODE_ENV=production
|
|
11
|
+
COPY --from=deps /app/node_modules ./node_modules
|
|
12
|
+
COPY package.json ./
|
|
13
|
+
COPY src ./src
|
|
14
|
+
COPY scripts ./scripts
|
|
15
|
+
COPY resources ./resources
|
|
16
|
+
COPY skills ./skills
|
|
17
|
+
COPY workspaces ./workspaces
|
|
18
|
+
EXPOSE 3000
|
|
19
|
+
CMD ["node", "src/index.js"]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import { loadConfig } from "../src/config/index.js";
|
|
4
|
+
import { loadEnv } from "../src/config/env.js";
|
|
5
|
+
import { checkDatabase } from "../src/infrastructure/database/client.js";
|
|
6
|
+
import { checkRedis } from "../src/infrastructure/redis/client.js";
|
|
7
|
+
import { discoverSkills, validateSkills } from "../src/skills/index.js";
|
|
8
|
+
/**
|
|
9
|
+
* 启动前检查:模型凭证、目录、技能以及可选基础设施。
|
|
10
|
+
* 必需项缺失时以非零状态码退出。
|
|
11
|
+
*/
|
|
12
|
+
const env = loadEnv(process.env, { requireModelCredentials: false });
|
|
13
|
+
const config = loadConfig({ env });
|
|
14
|
+
let failures = 0;
|
|
15
|
+
const report = (label, ok, detail = "") => {
|
|
16
|
+
console.log(`${ok ? "✔" : "✖"} ${label}${detail ? ` — ${detail}` : ""}`);
|
|
17
|
+
if (!ok) failures += 1;
|
|
18
|
+
};
|
|
19
|
+
const note = (message) => {
|
|
20
|
+
console.log(` ▲ ${message}`);
|
|
21
|
+
};
|
|
22
|
+
const providerKey = env.MODEL_PROVIDER === "anthropic" ? env.ANTHROPIC_API_KEY : env.OPENAI_API_KEY;
|
|
23
|
+
report(
|
|
24
|
+
`${env.MODEL_PROVIDER} 凭证`,
|
|
25
|
+
Boolean(providerKey),
|
|
26
|
+
providerKey ? "已配置" : "未配置(请设置 OPENAI_API_KEY 或 ANTHROPIC_API_KEY)",
|
|
27
|
+
);
|
|
28
|
+
for (const [label, directory] of Object.entries({
|
|
29
|
+
workspaces: config.paths.workspaces,
|
|
30
|
+
resources: config.paths.resources,
|
|
31
|
+
skills: config.paths.skills,
|
|
32
|
+
})) {
|
|
33
|
+
const stats = await fs.stat(directory).catch(() => null);
|
|
34
|
+
report(`${label} 目录`, Boolean(stats?.isDirectory()), directory);
|
|
35
|
+
}
|
|
36
|
+
const skills = await discoverSkills(config.paths.skills);
|
|
37
|
+
report(
|
|
38
|
+
"技能",
|
|
39
|
+
skills.length > 0,
|
|
40
|
+
skills.map((skill) => skill.name).join("、") || "未找到 SKILL.md",
|
|
41
|
+
);
|
|
42
|
+
for (const warning of validateSkills(skills)) {
|
|
43
|
+
note(warning);
|
|
44
|
+
}
|
|
45
|
+
const resourcesFile = `${config.paths.resources}/AGENTS.md`;
|
|
46
|
+
const hasAgentsFile = await fs
|
|
47
|
+
.stat(resourcesFile)
|
|
48
|
+
.then((stats) => stats.isFile())
|
|
49
|
+
.catch(() => false);
|
|
50
|
+
report("AGENTS.md", hasAgentsFile, resourcesFile);
|
|
51
|
+
if (config.database.url) {
|
|
52
|
+
const health = await checkDatabase();
|
|
53
|
+
report("postgres", health.ok, health.ok ? `${health.latencyMs}ms` : (health.error ?? "不可用"));
|
|
54
|
+
} else {
|
|
55
|
+
console.log("• postgres —— 未配置(使用内存 checkpointer/store)");
|
|
56
|
+
}
|
|
57
|
+
if (config.redis.url) {
|
|
58
|
+
const health = await checkRedis();
|
|
59
|
+
report("redis", health.ok, health.ok ? `${health.latencyMs}ms` : (health.error ?? "不可用"));
|
|
60
|
+
} else {
|
|
61
|
+
console.log("• redis —— 未配置(可选)");
|
|
62
|
+
}
|
|
63
|
+
if (env.TAVILY_API_KEY) {
|
|
64
|
+
console.log("• Web 搜索 —— 已配置 Tavily Key");
|
|
65
|
+
} else {
|
|
66
|
+
console.log("• Web 搜索 —— 未启用(设置 TAVILY_API_KEY 后启用)");
|
|
67
|
+
}
|
|
68
|
+
console.log("");
|
|
69
|
+
if (failures > 0) {
|
|
70
|
+
console.error(`${failures} 项检查未通过。`);
|
|
71
|
+
process.exitCode = 1;
|
|
72
|
+
} else {
|
|
73
|
+
console.log("全部检查通过。");
|
|
74
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
import { createInterface } from "node:readline/promises";
|
|
3
|
+
import { stdin, stdout } from "node:process";
|
|
4
|
+
import { createApplication } from "../src/app.js";
|
|
5
|
+
import { loadConfig } from "../src/config/index.js";
|
|
6
|
+
/**
|
|
7
|
+
* 主 Agent 的交互式终端。
|
|
8
|
+
* 使用 `npm run agent` 启动(不会启动 HTTP 服务)。
|
|
9
|
+
*/
|
|
10
|
+
const config = loadConfig();
|
|
11
|
+
const application = await createApplication(config);
|
|
12
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
13
|
+
let threadId;
|
|
14
|
+
console.log(`\nDeep Agent "${config.agent.name}" 已就绪。输入 exit 退出。\n`);
|
|
15
|
+
try {
|
|
16
|
+
for (;;) {
|
|
17
|
+
const line = (await rl.question("你 > ")).trim();
|
|
18
|
+
if (!line) continue;
|
|
19
|
+
if (["exit", "quit", ":q"].includes(line.toLowerCase())) break;
|
|
20
|
+
const result = await application.services.agent.invoke({
|
|
21
|
+
message: line,
|
|
22
|
+
tenantId: "local",
|
|
23
|
+
...(threadId ? { threadId } : {}),
|
|
24
|
+
});
|
|
25
|
+
threadId = result.threadId;
|
|
26
|
+
console.log(`\nAgent > ${result.text || "(无文本回复)"}\n`);
|
|
27
|
+
}
|
|
28
|
+
} finally {
|
|
29
|
+
rl.close();
|
|
30
|
+
await application.close();
|
|
31
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { compileAgentGraph } from "../graph/compile.js";
|
|
2
|
+
/**
|
|
3
|
+
* 对 `compileAgentGraph` 的轻量封装:共享默认配置(模型、后端、
|
|
4
|
+
* checkpointer、中间件)只定义一次,所有 Agent 复用。
|
|
5
|
+
*/
|
|
6
|
+
export const createAgentFactory = (defaults = {}) => {
|
|
7
|
+
return (overrides = {}) => {
|
|
8
|
+
return compileAgentGraph({ ...defaults, ...overrides });
|
|
9
|
+
};
|
|
10
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
const VALID_NAME = /^[a-z0-9][a-z0-9/_-]*$/i;
|
|
4
|
+
const cache = new Map();
|
|
5
|
+
/**
|
|
6
|
+
* 加载与本模块同目录的 Markdown 提示词。TypeScript 构建时由
|
|
7
|
+
* `scripts/copy-assets.ts` 把 `.md` 复制到 `dist/`,因此开发和生产的
|
|
8
|
+
* 相对路径保持一致。
|
|
9
|
+
*/
|
|
10
|
+
export const loadPrompt = (name) => {
|
|
11
|
+
if (!VALID_NAME.test(name) || name.includes("..")) {
|
|
12
|
+
throw new Error(`非法的提示词名称:${name}`);
|
|
13
|
+
}
|
|
14
|
+
const cached = cache.get(name);
|
|
15
|
+
if (cached !== undefined) return cached;
|
|
16
|
+
const file = fileURLToPath(new URL(`${name}.md`, import.meta.url));
|
|
17
|
+
try {
|
|
18
|
+
const content = readFileSync(file, "utf8").trim();
|
|
19
|
+
cache.set(name, content);
|
|
20
|
+
return content;
|
|
21
|
+
} catch (error) {
|
|
22
|
+
throw new Error(`无法从 ${file} 加载提示词 "${name}"。`, {
|
|
23
|
+
cause: error,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* 替换提示词中的 `{{variable}}` 占位符。缺少变量时直接报错,
|
|
29
|
+
* 让拼写错误在启动时暴露,而不是把 `{{team}}` 原样发给模型。
|
|
30
|
+
*/
|
|
31
|
+
export const renderPrompt = (template, variables) => {
|
|
32
|
+
const rendered = template.replace(/\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g, (_match, key) => {
|
|
33
|
+
const value = variables[key];
|
|
34
|
+
if (value === undefined) {
|
|
35
|
+
throw new Error(`缺少提示词变量 "${key}"。`);
|
|
36
|
+
}
|
|
37
|
+
return value;
|
|
38
|
+
});
|
|
39
|
+
const unrendered = rendered.match(/\{\{\s*[a-zA-Z0-9_]+\s*\}\}/);
|
|
40
|
+
if (unrendered) {
|
|
41
|
+
throw new Error(`存在未渲染的提示词变量 ${unrendered[0]}。`);
|
|
42
|
+
}
|
|
43
|
+
return rendered;
|
|
44
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
你是 analyst(分析)子 Agent。你负责把数据转化为可执行的结论。
|
|
2
|
+
|
|
3
|
+
## 工作流程
|
|
4
|
+
|
|
5
|
+
1. 明确要回答的问题,以及衡量它的指标。
|
|
6
|
+
2. 写 join 或聚合前,先用 `query_database` 查看表结构。
|
|
7
|
+
3. 编写小而清晰的查询,使用参数、明确的列名和 `LIMIT`。
|
|
8
|
+
4. 先校验数据(行数、空值、日期范围),再相信结果。
|
|
9
|
+
5. 需要时把表格或图表保存到 `/workspace/analysis/`。
|
|
10
|
+
6. 返回:结论、关键数字、产生这些数字的查询,以及注意事项。
|
|
11
|
+
|
|
12
|
+
## 规则
|
|
13
|
+
|
|
14
|
+
- 只使用只读 SQL,绝不尝试写入或 DDL。
|
|
15
|
+
- 不要用单个数据点或不完整区间推断趋势。
|
|
16
|
+
- 措辞上区分相关性与因果关系。
|
|
17
|
+
- 数据缺失或有歧义时,明确列出缺什么,不要自行填补。
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
你是 coder(编码)子 Agent。你负责在工作区中完成小而可验证的代码改动。
|
|
2
|
+
|
|
3
|
+
## 工作流程
|
|
4
|
+
|
|
5
|
+
1. 修改前先读相关文件,使用 `ls`、`glob`、`grep` 定位。
|
|
6
|
+
2. 用一句话说明要做的改动,然后实施能达成目标的最小修改。
|
|
7
|
+
3. 修改已有文件优先用 `edit_file`,新建文件用 `write_file`。
|
|
8
|
+
4. 修改后重新读取文件,确认改动已正确落盘。
|
|
9
|
+
5. 如果启用了 shell 后端,运行项目的 lint、类型检查或测试,并报告准确的命令和结果。
|
|
10
|
+
6. 返回总结:改了哪些文件、改了什么、如何验证。
|
|
11
|
+
|
|
12
|
+
## 规则
|
|
13
|
+
|
|
14
|
+
- 不要重写无关代码、整体格式化文件,或未经要求删除文件。
|
|
15
|
+
- 保持 ESM 和现代 JavaScript/TypeScript 风格;相对导入必须带 `.js` 扩展名。
|
|
16
|
+
- 没有实际运行并看到结果,就不要声称检查通过。
|
|
17
|
+
- 改动有风险或需求不明确时,停下来说明取舍,不要猜测。
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
你是 researcher(研究)子 Agent。你负责收集可验证的信息,并整理成主 Agent 可信赖的笔记。
|
|
2
|
+
|
|
3
|
+
## 工作流程
|
|
4
|
+
|
|
5
|
+
1. 把问题拆成 2-5 个具体的子问题。
|
|
6
|
+
2. 使用 `web_search` 搜索。优先选择一手来源(官方文档、论文、源码),而不是聚合站点。
|
|
7
|
+
3. 阅读最有价值的来源,只提取能回答子问题的事实。
|
|
8
|
+
4. 把笔记写入 `/workspace/research/<主题>.md`,包含简短摘要和来源列表。
|
|
9
|
+
5. 返回摘要和文件路径。
|
|
10
|
+
|
|
11
|
+
## 规则
|
|
12
|
+
|
|
13
|
+
- 每个事实性结论都必须附 URL。无法验证的来源要明确说明。
|
|
14
|
+
- 时间敏感的信息要记录发布日期,并标注可能过时的内容。
|
|
15
|
+
- 控制引用篇幅,不要大段复制原文。
|
|
16
|
+
- 搜索工具不可用时明确说明,并标注所给信息为“未经验证”。
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { loadPrompt, renderPrompt } from "./loader.js";
|
|
2
|
+
const NO_APPROVAL_POLICY = "工具调用无需人工审批,直接执行。";
|
|
3
|
+
const APPROVAL_POLICY =
|
|
4
|
+
"有副作用的工具调用会暂停以等待人工审批。请说明为什么需要该工具,然后等待决定。";
|
|
5
|
+
/**
|
|
6
|
+
* 主 Agent 提示词正文在 `supervisor.md` 中,
|
|
7
|
+
* 这里只组装动态片段(Agent 名称、团队列表、审批策略)。
|
|
8
|
+
*/
|
|
9
|
+
export const buildSupervisorPrompt = ({ name, subagents, approvalMode }) => {
|
|
10
|
+
const team = subagents.map((agent) => `- **${agent.name}** — ${agent.description}`).join("\n");
|
|
11
|
+
const approvalPolicy = approvalMode === "none" ? NO_APPROVAL_POLICY : APPROVAL_POLICY;
|
|
12
|
+
return renderPrompt(loadPrompt("supervisor"), {
|
|
13
|
+
agentName: name,
|
|
14
|
+
team,
|
|
15
|
+
approvalPolicy,
|
|
16
|
+
});
|
|
17
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
你是 {{agentName}},一个基于 LangGraph 的 Deep Agents 工作区的主 Agent(Supervisor)。
|
|
2
|
+
|
|
3
|
+
你对用户请求的最终结果负责:规划、分派、验收,然后给出答复。
|
|
4
|
+
|
|
5
|
+
## 工作循环
|
|
6
|
+
|
|
7
|
+
1. 用一句话复述目标,并列出明确的交付物。
|
|
8
|
+
2. 调用 `write_todos` 制定简短、有序的计划,并随进展更新。
|
|
9
|
+
3. 用 `task` 工具把可独立开展的工作分派出去。给每个子 Agent 明确的范围、输入和期望输出。
|
|
10
|
+
4. 子 Agent 返回后,对照交付物检查结果。发现缺口就让它补齐,而不是自己重做。
|
|
11
|
+
5. 把需要保留的产物写入 `/workspace/`,然后为用户总结结果。
|
|
12
|
+
|
|
13
|
+
## 你的团队
|
|
14
|
+
|
|
15
|
+
{{team}}
|
|
16
|
+
|
|
17
|
+
当子 Agent 更合适时再分派;任务很小或需要完整对话上下文时,直接自己完成。
|
|
18
|
+
|
|
19
|
+
## 文件系统
|
|
20
|
+
|
|
21
|
+
- `/workspace/` —— 草稿和最终交付物,唯一可写区域。
|
|
22
|
+
- `/resources/` —— `AGENTS.md` 和知识文件。开始前先阅读。
|
|
23
|
+
- `/skills/` —— SKILL.md 说明。当技能描述与任务匹配时加载对应技能。
|
|
24
|
+
- `/memories/` —— 跨会话的长期记忆。读取相关内容,只写入需要长期保留的事实。
|
|
25
|
+
|
|
26
|
+
使用内置文件系统工具(`ls`、`read_file`、`write_file`、`edit_file`、`glob`、`grep`)查看文件,不要猜测文件内容。给用户展示绝对虚拟路径(例如 `/workspace/report.md`)。
|
|
27
|
+
|
|
28
|
+
## 研究与数据
|
|
29
|
+
|
|
30
|
+
- `web_search` 返回标题、URL 和摘要。引用你实际使用的 URL,绝不编造来源。
|
|
31
|
+
- `query_database` 执行只读 SQL。先看表结构,并控制结果集大小。
|
|
32
|
+
|
|
33
|
+
## 审批策略
|
|
34
|
+
|
|
35
|
+
{{approvalPolicy}}
|
|
36
|
+
|
|
37
|
+
## 规则
|
|
38
|
+
|
|
39
|
+
- 绝不伪造工具输出、文件内容、查询结果或引用。
|
|
40
|
+
- 选择满足需求的最小改动,不要重写无关文件。
|
|
41
|
+
- 工具失败时先读错误、调整参数,最多重试两次;仍失败则如实报告阻塞点。
|
|
42
|
+
- 最终答复保持简洁:做了什么、交付物在哪里、还剩什么。
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { agentStateSchema } from "./types.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
/**
|
|
3
|
+
* 每个会话携带的自定义状态。Deep Agents 已提供 `messages`、`files` 和
|
|
4
|
+
* `todos`;这里补充多租户上下文,供服务和中间件读取。
|
|
5
|
+
*/
|
|
6
|
+
export const agentStateSchema = z.object({
|
|
7
|
+
tenantId: z.string().default("default"),
|
|
8
|
+
userId: z.string().optional(),
|
|
9
|
+
objective: z.string().default(""),
|
|
10
|
+
});
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { queryDatabaseTool } from "../../tools/database/index.js";
|
|
2
|
+
import { loadPrompt } from "../prompts/index.js";
|
|
3
|
+
export const createAnalystSubagent = () => {
|
|
4
|
+
return {
|
|
5
|
+
name: "analyst",
|
|
6
|
+
description: "用只读 SQL 回答数据问题,校验数字,并把表格或摘要写入 /workspace/analysis/。",
|
|
7
|
+
systemPrompt: loadPrompt("subagents/analyst"),
|
|
8
|
+
tools: [queryDatabaseTool],
|
|
9
|
+
skills: ["/skills/analysis/"],
|
|
10
|
+
};
|
|
11
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { loadPrompt } from "../prompts/index.js";
|
|
2
|
+
export const createCoderSubagent = () => {
|
|
3
|
+
return {
|
|
4
|
+
name: "coder",
|
|
5
|
+
description:
|
|
6
|
+
"在 /workspace/ 中完成聚焦的代码修改:先读后改,启用 shell 后端时运行检查,并准确报告改动内容。",
|
|
7
|
+
systemPrompt: loadPrompt("subagents/coder"),
|
|
8
|
+
tools: [],
|
|
9
|
+
skills: ["/skills/coding/"],
|
|
10
|
+
};
|
|
11
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { createAnalystSubagent } from "./analyst.js";
|
|
2
|
+
import { createCoderSubagent } from "./coder.js";
|
|
3
|
+
import { createResearcherSubagent } from "./researcher.js";
|
|
4
|
+
export { createAnalystSubagent, createCoderSubagent, createResearcherSubagent };
|
|
5
|
+
/** 默认专家团队,顺序即展示给主 Agent 的顺序。 */
|
|
6
|
+
export const createDefaultSubagents = () => {
|
|
7
|
+
return [createResearcherSubagent(), createCoderSubagent(), createAnalystSubagent()];
|
|
8
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { webSearchTool } from "../../tools/search/index.js";
|
|
2
|
+
import { loadPrompt } from "../prompts/index.js";
|
|
3
|
+
export const createResearcherSubagent = () => {
|
|
4
|
+
return {
|
|
5
|
+
name: "researcher",
|
|
6
|
+
description:
|
|
7
|
+
"从网络收集可验证的信息,阅读来源,并把带引用的研究笔记写入 /workspace/research/。",
|
|
8
|
+
systemPrompt: loadPrompt("subagents/researcher"),
|
|
9
|
+
tools: [webSearchTool],
|
|
10
|
+
skills: ["/skills/research/"],
|
|
11
|
+
};
|
|
12
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createContextMiddleware,
|
|
3
|
+
createLoggingMiddleware,
|
|
4
|
+
createSecurityMiddleware,
|
|
5
|
+
} from "../middleware/index.js";
|
|
6
|
+
import { createApprovalPolicy } from "../middleware/approval.js";
|
|
7
|
+
import { createAgentFactory } from "./factory.js";
|
|
8
|
+
import { buildSupervisorPrompt } from "./prompts/supervisor.js";
|
|
9
|
+
import { createDefaultSubagents } from "./subagents/index.js";
|
|
10
|
+
import { agentStateSchema } from "./state/index.js";
|
|
11
|
+
/**
|
|
12
|
+
* 装配主 Agent:共享运行时(模型、后端、checkpointer、store、中间件),
|
|
13
|
+
* 以及它的提示词、工具、子 Agent、记忆和技能。
|
|
14
|
+
*/
|
|
15
|
+
export const createSupervisorAgent = ({
|
|
16
|
+
config,
|
|
17
|
+
model,
|
|
18
|
+
backend,
|
|
19
|
+
checkpointer,
|
|
20
|
+
store,
|
|
21
|
+
logger,
|
|
22
|
+
tools,
|
|
23
|
+
}) => {
|
|
24
|
+
const subagents = createDefaultSubagents();
|
|
25
|
+
// 依赖里用具体的工具类型,交给 Agent 时再收窄为它接受的联合类型。
|
|
26
|
+
const agentTools = tools;
|
|
27
|
+
const middleware = [
|
|
28
|
+
createLoggingMiddleware(logger),
|
|
29
|
+
createSecurityMiddleware(),
|
|
30
|
+
createContextMiddleware(),
|
|
31
|
+
];
|
|
32
|
+
const createAgent = createAgentFactory({
|
|
33
|
+
model,
|
|
34
|
+
backend,
|
|
35
|
+
checkpointer,
|
|
36
|
+
store,
|
|
37
|
+
stateSchema: agentStateSchema,
|
|
38
|
+
middleware,
|
|
39
|
+
});
|
|
40
|
+
return createAgent({
|
|
41
|
+
name: config.agent.name,
|
|
42
|
+
systemPrompt: buildSupervisorPrompt({
|
|
43
|
+
name: config.agent.name,
|
|
44
|
+
subagents: subagents.map(({ name, description }) => ({
|
|
45
|
+
name,
|
|
46
|
+
description,
|
|
47
|
+
})),
|
|
48
|
+
approvalMode: config.agent.approvals,
|
|
49
|
+
}),
|
|
50
|
+
tools: agentTools,
|
|
51
|
+
subagents,
|
|
52
|
+
interruptOn: createApprovalPolicy(config.agent.approvals),
|
|
53
|
+
memory: config.agent.memoryFiles,
|
|
54
|
+
skills: config.agent.skillDirectories,
|
|
55
|
+
});
|
|
56
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import express from "express";
|
|
2
|
+
import { createAuthMiddleware } from "./middleware/auth.js";
|
|
3
|
+
import { createErrorHandler, notFoundHandler } from "./middleware/error.js";
|
|
4
|
+
import { createAgentRouter } from "./routes/agent.js";
|
|
5
|
+
import { createHealthRouter } from "./routes/health.js";
|
|
6
|
+
import { createSessionRouter } from "./routes/session.js";
|
|
7
|
+
/**
|
|
8
|
+
* Agent API 的 Express 应用。健康检查保持公开;
|
|
9
|
+
* 配置 AGENT_API_KEY 后,/api 下的接口需要携带 Bearer Token。
|
|
10
|
+
*/
|
|
11
|
+
export const createApiApp = ({ config, logger, services, mcp }) => {
|
|
12
|
+
const app = express();
|
|
13
|
+
app.disable("x-powered-by");
|
|
14
|
+
app.use(express.json({ limit: "2mb" }));
|
|
15
|
+
app.use("/health", createHealthRouter({ config, ...(mcp ? { mcp } : {}) }));
|
|
16
|
+
app.use(createAuthMiddleware(config.env.AGENT_API_KEY));
|
|
17
|
+
app.use("/api/agents", createAgentRouter({ agent: services.agent }));
|
|
18
|
+
app.use("/api/sessions", createSessionRouter({ sessions: services.sessions }));
|
|
19
|
+
app.use(notFoundHandler);
|
|
20
|
+
app.use(createErrorHandler(logger));
|
|
21
|
+
return app;
|
|
22
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { UnauthorizedError } from "../../utils/errors.js";
|
|
3
|
+
const BEARER_PREFIX = "Bearer ";
|
|
4
|
+
const safeEqual = (provided, expected) => {
|
|
5
|
+
const actual = Buffer.from(provided);
|
|
6
|
+
const target = Buffer.from(expected);
|
|
7
|
+
if (actual.length !== target.length) return false;
|
|
8
|
+
return timingSafeEqual(actual, target);
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* 可选的 Bearer Token 鉴权。未设置 AGENT_API_KEY 时 API 完全开放
|
|
12
|
+
* (适合本地开发,切勿用于公网部署)。
|
|
13
|
+
*/
|
|
14
|
+
export const createAuthMiddleware = (apiKey) => {
|
|
15
|
+
if (!apiKey) {
|
|
16
|
+
return (_req, _res, next) => next();
|
|
17
|
+
}
|
|
18
|
+
return (req, _res, next) => {
|
|
19
|
+
const header = req.header("authorization") ?? "";
|
|
20
|
+
const token = header.startsWith(BEARER_PREFIX) ? header.slice(BEARER_PREFIX.length).trim() : "";
|
|
21
|
+
if (!token || !safeEqual(token, apiKey)) {
|
|
22
|
+
next(new UnauthorizedError());
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
next();
|
|
26
|
+
};
|
|
27
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { NotFoundError, toErrorResponse } from "../../utils/errors.js";
|
|
2
|
+
export const notFoundHandler = (req, _res, next) => {
|
|
3
|
+
next(new NotFoundError(`未找到路由 ${req.method} ${req.path}。`));
|
|
4
|
+
};
|
|
5
|
+
export const createErrorHandler = (logger) => {
|
|
6
|
+
return (error, req, res, _next) => {
|
|
7
|
+
const { status, body } = toErrorResponse(error);
|
|
8
|
+
if (status >= 500) {
|
|
9
|
+
logger.error(
|
|
10
|
+
{
|
|
11
|
+
method: req.method,
|
|
12
|
+
path: req.path,
|
|
13
|
+
status,
|
|
14
|
+
error: error instanceof Error ? error.stack : String(error),
|
|
15
|
+
},
|
|
16
|
+
"请求处理失败",
|
|
17
|
+
);
|
|
18
|
+
} else {
|
|
19
|
+
logger.warn(
|
|
20
|
+
{ method: req.method, path: req.path, status, code: body.error.code },
|
|
21
|
+
"请求被拒绝",
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
res.status(status).json(body);
|
|
25
|
+
};
|
|
26
|
+
};
|