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
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { ChatAnthropic } from "@langchain/anthropic";
|
|
2
|
+
import type { BaseChatModel } from "@langchain/core/language_models/chat_models";
|
|
3
|
+
import { ChatOpenAI } from "@langchain/openai";
|
|
4
|
+
|
|
5
|
+
import type { Env } from "./env.js";
|
|
6
|
+
|
|
7
|
+
export interface ModelConfig {
|
|
8
|
+
provider: "openai" | "anthropic";
|
|
9
|
+
name: string;
|
|
10
|
+
temperature: number;
|
|
11
|
+
maxTokens: number;
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const DEFAULT_MODELS = {
|
|
16
|
+
openai: "gpt-4.1-mini",
|
|
17
|
+
anthropic: "claude-sonnet-4-5",
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
export const resolveModelConfig = (env: Env): ModelConfig => {
|
|
21
|
+
return {
|
|
22
|
+
provider: env.MODEL_PROVIDER,
|
|
23
|
+
name: env.MODEL_NAME ?? DEFAULT_MODELS[env.MODEL_PROVIDER],
|
|
24
|
+
temperature: env.MODEL_TEMPERATURE,
|
|
25
|
+
maxTokens: env.MODEL_MAX_TOKENS,
|
|
26
|
+
...(env.OPENAI_BASE_URL ? { baseUrl: env.OPENAI_BASE_URL } : {}),
|
|
27
|
+
};
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 构建主 Agent 和所有子 Agent 共用的聊天模型。
|
|
32
|
+
* 要接入其他提供商(Bedrock、Vertex、Ollama 等),替换此函数即可。
|
|
33
|
+
*/
|
|
34
|
+
export const createChatModel = (config: ModelConfig): BaseChatModel => {
|
|
35
|
+
if (config.provider === "anthropic") {
|
|
36
|
+
return new ChatAnthropic({
|
|
37
|
+
model: config.name,
|
|
38
|
+
temperature: config.temperature,
|
|
39
|
+
maxTokens: config.maxTokens,
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return new ChatOpenAI({
|
|
44
|
+
model: config.name,
|
|
45
|
+
temperature: config.temperature,
|
|
46
|
+
maxTokens: config.maxTokens,
|
|
47
|
+
...(config.baseUrl ? { configuration: { baseURL: config.baseUrl } } : {}),
|
|
48
|
+
});
|
|
49
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
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:持久化,需要 DATABASE_URL 和 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("CHECKPOINTER=postgres 时必须设置 DATABASE_URL。");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const { PostgresSaver } = await import("@langchain/langgraph-checkpoint-postgres");
|
|
22
|
+
|
|
23
|
+
const saver = PostgresSaver.fromConnString(config.database.url);
|
|
24
|
+
await saver.setup();
|
|
25
|
+
return saver;
|
|
26
|
+
};
|
|
@@ -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,26 @@
|
|
|
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:持久化,需要 DATABASE_URL 和 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("STORE=postgres 时必须设置 DATABASE_URL。");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const { PostgresStore } = await import("@langchain/langgraph-checkpoint-postgres/store");
|
|
22
|
+
|
|
23
|
+
const store = PostgresStore.fromConnString(config.database.url);
|
|
24
|
+
await store.setup();
|
|
25
|
+
return store;
|
|
26
|
+
};
|
|
@@ -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 "./infrastructure/logger/index.js";
|
|
6
|
+
import { createShutdownManager } from "./infrastructure/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,61 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
|
|
3
|
+
import { Pool, type PoolClient } from "pg";
|
|
4
|
+
|
|
5
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
6
|
+
|
|
7
|
+
let pool: Pool | undefined;
|
|
8
|
+
|
|
9
|
+
/** 懒加载共享的 PostgreSQL 连接池。 */
|
|
10
|
+
export const getPool = (connectionString = process.env.DATABASE_URL): Pool => {
|
|
11
|
+
if (!connectionString) {
|
|
12
|
+
throw new ConfigurationError("未配置 DATABASE_URL。请先在 .env 中设置后再使用数据库功能。");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
pool ??= new Pool({
|
|
16
|
+
connectionString,
|
|
17
|
+
max: 10,
|
|
18
|
+
idleTimeoutMillis: 30_000,
|
|
19
|
+
connectionTimeoutMillis: 5_000,
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
return pool;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export interface DatabaseHealth {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
latencyMs?: number;
|
|
28
|
+
error?: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export const checkDatabase = async (): Promise<DatabaseHealth> => {
|
|
32
|
+
if (!process.env.DATABASE_URL) {
|
|
33
|
+
return { ok: false, error: "未配置 DATABASE_URL" };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const startedAt = performance.now();
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
const client: PoolClient = await getPool().connect();
|
|
40
|
+
try {
|
|
41
|
+
await client.query("select 1");
|
|
42
|
+
} finally {
|
|
43
|
+
client.release();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
|
|
47
|
+
} catch (error) {
|
|
48
|
+
return {
|
|
49
|
+
ok: false,
|
|
50
|
+
error: error instanceof Error ? error.message : String(error),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
export const closeDatabase = async (): Promise<void> => {
|
|
56
|
+
if (!pool) return;
|
|
57
|
+
|
|
58
|
+
const current = pool;
|
|
59
|
+
pool = undefined;
|
|
60
|
+
await current.end();
|
|
61
|
+
};
|
|
@@ -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/infrastructure/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,25 @@
|
|
|
1
|
+
import pino, { type Logger } from "pino";
|
|
2
|
+
|
|
3
|
+
import type { AppConfig } from "../../config/index.js";
|
|
4
|
+
|
|
5
|
+
export type { Logger };
|
|
6
|
+
|
|
7
|
+
/** `LOG_PRETTY=true` 时使用的 pino-pretty 传输配置。 */
|
|
8
|
+
const PRETTY_TRANSPORT = {
|
|
9
|
+
transport: {
|
|
10
|
+
target: "pino-pretty",
|
|
11
|
+
options: {
|
|
12
|
+
colorize: true,
|
|
13
|
+
translateTime: "SYS:standard",
|
|
14
|
+
ignore: "pid,hostname",
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const createLogger = (config: Pick<AppConfig, "env" | "logging">): Logger => {
|
|
20
|
+
return pino({
|
|
21
|
+
level: config.logging.level,
|
|
22
|
+
base: { service: "deepagent", env: config.env.NODE_ENV },
|
|
23
|
+
...(config.logging.pretty ? PRETTY_TRANSPORT : {}),
|
|
24
|
+
});
|
|
25
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
|
|
3
|
+
import { Redis } from "ioredis";
|
|
4
|
+
|
|
5
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
6
|
+
|
|
7
|
+
let client: Redis | undefined;
|
|
8
|
+
|
|
9
|
+
/** 懒加载共享的 Redis 客户端(首次执行命令时才建立连接)。 */
|
|
10
|
+
export const getRedis = (url = process.env.REDIS_URL): Redis => {
|
|
11
|
+
if (!url) {
|
|
12
|
+
throw new ConfigurationError("未配置 REDIS_URL。请先在 .env 中设置后再使用 Redis 功能。");
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
client ??= new Redis(url, {
|
|
16
|
+
lazyConnect: true,
|
|
17
|
+
maxRetriesPerRequest: 1,
|
|
18
|
+
enableOfflineQueue: false,
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
return client;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export interface RedisHealth {
|
|
25
|
+
ok: boolean;
|
|
26
|
+
latencyMs?: number;
|
|
27
|
+
error?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const checkRedis = async (): Promise<RedisHealth> => {
|
|
31
|
+
if (!process.env.REDIS_URL) {
|
|
32
|
+
return { ok: false, error: "未配置 REDIS_URL" };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
try {
|
|
36
|
+
const redis = getRedis();
|
|
37
|
+
if (redis.status === "wait") {
|
|
38
|
+
await redis.connect();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const startedAt = performance.now();
|
|
42
|
+
await redis.ping();
|
|
43
|
+
|
|
44
|
+
return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
|
|
45
|
+
} catch (error) {
|
|
46
|
+
return {
|
|
47
|
+
ok: false,
|
|
48
|
+
error: error instanceof Error ? error.message : String(error),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const closeRedis = async (): Promise<void> => {
|
|
54
|
+
if (!client) return;
|
|
55
|
+
|
|
56
|
+
const current = client;
|
|
57
|
+
client = undefined;
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
await current.quit();
|
|
61
|
+
} catch {
|
|
62
|
+
current.disconnect();
|
|
63
|
+
}
|
|
64
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { Logger } from "../logger/index.js";
|
|
2
|
+
|
|
3
|
+
export interface ShutdownHook {
|
|
4
|
+
name: string;
|
|
5
|
+
close: () => Promise<void> | void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface ShutdownManager {
|
|
9
|
+
/** 注册一个随进程关闭而关闭的资源,返回取消注册函数。 */
|
|
10
|
+
register: (hook: ShutdownHook) => () => void;
|
|
11
|
+
/** 关闭所有已注册资源,只执行一次;多个信号并发调用也安全。 */
|
|
12
|
+
shutdown: (reason?: string) => Promise<void>;
|
|
13
|
+
/** 安装 SIGINT / SIGTERM 处理器。 */
|
|
14
|
+
install: () => void;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface ShutdownOptions {
|
|
18
|
+
logger: Logger;
|
|
19
|
+
timeoutMs?: number;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const withTimeout = (promise: Promise<void>, timeoutMs: number): Promise<void> => {
|
|
23
|
+
let timer: NodeJS.Timeout | undefined;
|
|
24
|
+
|
|
25
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
26
|
+
timer = setTimeout(() => reject(new Error(`hook 执行超时(${timeoutMs}ms)`)), timeoutMs);
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
30
|
+
if (timer) clearTimeout(timer);
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export const createShutdownManager = ({
|
|
35
|
+
logger,
|
|
36
|
+
timeoutMs = 10_000,
|
|
37
|
+
}: ShutdownOptions): ShutdownManager => {
|
|
38
|
+
const hooks: ShutdownHook[] = [];
|
|
39
|
+
let pending: Promise<void> | undefined;
|
|
40
|
+
|
|
41
|
+
const run = async (reason: string): Promise<void> => {
|
|
42
|
+
logger.info({ reason, hooks: hooks.map((hook) => hook.name) }, "开始关闭");
|
|
43
|
+
|
|
44
|
+
await Promise.allSettled(
|
|
45
|
+
hooks.map(async (hook) => {
|
|
46
|
+
try {
|
|
47
|
+
await withTimeout(Promise.resolve(hook.close()), timeoutMs);
|
|
48
|
+
logger.info({ hook: hook.name }, "已关闭");
|
|
49
|
+
} catch (error) {
|
|
50
|
+
logger.warn(
|
|
51
|
+
{ hook: hook.name, error: error instanceof Error ? error.message : error },
|
|
52
|
+
"关闭资源失败",
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}),
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
logger.info("关闭完成");
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
const manager: ShutdownManager = {
|
|
62
|
+
register: (hook) => {
|
|
63
|
+
hooks.push(hook);
|
|
64
|
+
return () => {
|
|
65
|
+
const index = hooks.findIndex((item) => item === hook);
|
|
66
|
+
if (index >= 0) hooks.splice(index, 1);
|
|
67
|
+
};
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
shutdown: (reason = "shutdown") => {
|
|
71
|
+
pending ??= run(reason);
|
|
72
|
+
return pending;
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
install: () => {
|
|
76
|
+
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
|
77
|
+
process.once(signal, () => {
|
|
78
|
+
void manager.shutdown(signal).finally(() => process.exit(0));
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
return manager;
|
|
85
|
+
};
|
|
@@ -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,74 @@
|
|
|
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
|
+
readonly #memory: MemoryStore;
|
|
21
|
+
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
|
+
const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
|
|
31
|
+
return [...this.#root, tenantId, segment];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async rememberPreference(
|
|
35
|
+
target: MemoryTarget,
|
|
36
|
+
key: string,
|
|
37
|
+
value: Record<string, unknown>,
|
|
38
|
+
): Promise<void> {
|
|
39
|
+
await this.#memory.put(this.namespaceFor(target), `preference:${key}`, value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async rememberFact(
|
|
43
|
+
target: MemoryTarget,
|
|
44
|
+
key: string,
|
|
45
|
+
value: Record<string, unknown>,
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
await this.#memory.put(this.namespaceFor(target), `fact:${key}`, value);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async recall<T = Record<string, unknown>>(
|
|
51
|
+
target: MemoryTarget,
|
|
52
|
+
key: string,
|
|
53
|
+
): Promise<MemoryRecord<T> | null> {
|
|
54
|
+
return this.#memory.get<T>(this.namespaceFor(target), key);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async list<T = Record<string, unknown>>(
|
|
58
|
+
target: MemoryTarget,
|
|
59
|
+
limit = 50,
|
|
60
|
+
): Promise<MemoryRecord<T>[]> {
|
|
61
|
+
return this.#memory.search<T>(this.namespaceFor(target), limit);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async forget(target: MemoryTarget, key: string): Promise<void> {
|
|
65
|
+
await this.#memory.delete(this.namespaceFor(target), key);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const assertSegment = (value: string, label: string): string => {
|
|
70
|
+
if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
|
|
71
|
+
throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
};
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
return toRecord<T>(item);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async search<T = Record<string, unknown>>(
|
|
38
|
+
namespacePrefix: string[],
|
|
39
|
+
limit = 20,
|
|
40
|
+
): Promise<MemoryRecord<T>[]> {
|
|
41
|
+
const items = await this.store.search(namespacePrefix, { limit });
|
|
42
|
+
return items.map((item) => toRecord<T>(item));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async delete(namespace: string[], key: string): Promise<void> {
|
|
46
|
+
await this.store.delete(namespace, key);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const toRecord = <T>(item: Item): MemoryRecord<T> => {
|
|
51
|
+
return {
|
|
52
|
+
key: item.key,
|
|
53
|
+
namespace: item.namespace,
|
|
54
|
+
value: item.value as T,
|
|
55
|
+
...(item.updatedAt ? { updatedAt: new Date(item.updatedAt).toISOString() } : {}),
|
|
56
|
+
};
|
|
57
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { ApprovalMode } from "../config/agent.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
|
+
"web_search",
|
|
20
|
+
"read_file",
|
|
21
|
+
"read_workspace_file",
|
|
22
|
+
"list_workspace_files",
|
|
23
|
+
"ls",
|
|
24
|
+
"glob",
|
|
25
|
+
"grep",
|
|
26
|
+
"write_todos",
|
|
27
|
+
"task",
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 构建 `createDeepAgent` 使用的 `interruptOn` 映射。
|
|
32
|
+
*
|
|
33
|
+
* - none:不启用审批
|
|
34
|
+
* - sensitive:修改类工具执行前暂停(默认)
|
|
35
|
+
* - all:所有已知工具执行前都暂停
|
|
36
|
+
*/
|
|
37
|
+
export const createApprovalPolicy = (mode: ApprovalMode): Record<string, boolean> => {
|
|
38
|
+
if (mode === "none") return {};
|
|
39
|
+
|
|
40
|
+
const tools = mode === "all" ? [...KNOWN_TOOLS] : [...SENSITIVE_TOOLS];
|
|
41
|
+
|
|
42
|
+
return Object.fromEntries(tools.map((tool) => [tool, true]));
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const requiresApproval = (mode: ApprovalMode, toolName: string): boolean => {
|
|
46
|
+
if (mode === "none") return false;
|
|
47
|
+
if (mode === "all") return (KNOWN_TOOLS as readonly string[]).includes(toolName);
|
|
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";
|