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,45 @@
|
|
|
1
|
+
import { performance } from "node:perf_hooks";
|
|
2
|
+
import { Redis } from "ioredis";
|
|
3
|
+
import { ConfigurationError } from "../../utils/errors.js";
|
|
4
|
+
let client;
|
|
5
|
+
/** 懒加载共享的 Redis 客户端(首次执行命令时才建立连接)。 */
|
|
6
|
+
export const getRedis = (url = process.env.REDIS_URL) => {
|
|
7
|
+
if (!url) {
|
|
8
|
+
throw new ConfigurationError("未配置 REDIS_URL。请先在 .env 中设置后再使用 Redis 功能。");
|
|
9
|
+
}
|
|
10
|
+
client ??= new Redis(url, {
|
|
11
|
+
lazyConnect: true,
|
|
12
|
+
maxRetriesPerRequest: 1,
|
|
13
|
+
enableOfflineQueue: false,
|
|
14
|
+
});
|
|
15
|
+
return client;
|
|
16
|
+
};
|
|
17
|
+
export const checkRedis = async () => {
|
|
18
|
+
if (!process.env.REDIS_URL) {
|
|
19
|
+
return { ok: false, error: "未配置 REDIS_URL" };
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const redis = getRedis();
|
|
23
|
+
if (redis.status === "wait") {
|
|
24
|
+
await redis.connect();
|
|
25
|
+
}
|
|
26
|
+
const startedAt = performance.now();
|
|
27
|
+
await redis.ping();
|
|
28
|
+
return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
|
|
29
|
+
} catch (error) {
|
|
30
|
+
return {
|
|
31
|
+
ok: false,
|
|
32
|
+
error: error instanceof Error ? error.message : String(error),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
export const closeRedis = async () => {
|
|
37
|
+
if (!client) return;
|
|
38
|
+
const current = client;
|
|
39
|
+
client = undefined;
|
|
40
|
+
try {
|
|
41
|
+
await current.quit();
|
|
42
|
+
} catch {
|
|
43
|
+
current.disconnect();
|
|
44
|
+
}
|
|
45
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const withTimeout = (promise, timeoutMs) => {
|
|
2
|
+
let timer;
|
|
3
|
+
const timeout = new Promise((_, reject) => {
|
|
4
|
+
timer = setTimeout(() => reject(new Error(`hook 执行超时(${timeoutMs}ms)`)), timeoutMs);
|
|
5
|
+
});
|
|
6
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
7
|
+
if (timer) clearTimeout(timer);
|
|
8
|
+
});
|
|
9
|
+
};
|
|
10
|
+
export const createShutdownManager = ({ logger, timeoutMs = 10_000 }) => {
|
|
11
|
+
const hooks = [];
|
|
12
|
+
let pending;
|
|
13
|
+
const run = async (reason) => {
|
|
14
|
+
logger.info({ reason, hooks: hooks.map((hook) => hook.name) }, "开始关闭");
|
|
15
|
+
await Promise.allSettled(
|
|
16
|
+
hooks.map(async (hook) => {
|
|
17
|
+
try {
|
|
18
|
+
await withTimeout(Promise.resolve(hook.close()), timeoutMs);
|
|
19
|
+
logger.info({ hook: hook.name }, "已关闭");
|
|
20
|
+
} catch (error) {
|
|
21
|
+
logger.warn(
|
|
22
|
+
{ hook: hook.name, error: error instanceof Error ? error.message : error },
|
|
23
|
+
"关闭资源失败",
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
}),
|
|
27
|
+
);
|
|
28
|
+
logger.info("关闭完成");
|
|
29
|
+
};
|
|
30
|
+
const manager = {
|
|
31
|
+
register: (hook) => {
|
|
32
|
+
hooks.push(hook);
|
|
33
|
+
return () => {
|
|
34
|
+
const index = hooks.findIndex((item) => item === hook);
|
|
35
|
+
if (index >= 0) hooks.splice(index, 1);
|
|
36
|
+
};
|
|
37
|
+
},
|
|
38
|
+
shutdown: (reason = "shutdown") => {
|
|
39
|
+
pending ??= run(reason);
|
|
40
|
+
return pending;
|
|
41
|
+
},
|
|
42
|
+
install: () => {
|
|
43
|
+
for (const signal of ["SIGINT", "SIGTERM"]) {
|
|
44
|
+
process.once(signal, () => {
|
|
45
|
+
void manager.shutdown(signal).finally(() => process.exit(0));
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
return manager;
|
|
51
|
+
};
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { MemoryStore } from "./store.js";
|
|
2
|
+
/**
|
|
3
|
+
* 领域级长期记忆:按租户/用户隔离的偏好与事实,
|
|
4
|
+
* 存储在挂载于 `/memories/` 的同一个 BaseStore 中。
|
|
5
|
+
*/
|
|
6
|
+
export class MemoryManager {
|
|
7
|
+
#memory;
|
|
8
|
+
#root;
|
|
9
|
+
constructor({ store, rootNamespace = ["memories"] }) {
|
|
10
|
+
this.#memory = new MemoryStore(store);
|
|
11
|
+
this.#root = rootNamespace;
|
|
12
|
+
}
|
|
13
|
+
namespaceFor({ tenantId, userId }) {
|
|
14
|
+
assertSegment(tenantId, "tenantId");
|
|
15
|
+
const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
|
|
16
|
+
return [...this.#root, tenantId, segment];
|
|
17
|
+
}
|
|
18
|
+
async rememberPreference(target, key, value) {
|
|
19
|
+
await this.#memory.put(this.namespaceFor(target), `preference:${key}`, value);
|
|
20
|
+
}
|
|
21
|
+
async rememberFact(target, key, value) {
|
|
22
|
+
await this.#memory.put(this.namespaceFor(target), `fact:${key}`, value);
|
|
23
|
+
}
|
|
24
|
+
async recall(target, key) {
|
|
25
|
+
return this.#memory.get(this.namespaceFor(target), key);
|
|
26
|
+
}
|
|
27
|
+
async list(target, limit = 50) {
|
|
28
|
+
return this.#memory.search(this.namespaceFor(target), limit);
|
|
29
|
+
}
|
|
30
|
+
async forget(target, key) {
|
|
31
|
+
await this.#memory.delete(this.namespaceFor(target), key);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const assertSegment = (value, label) => {
|
|
35
|
+
if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
|
|
36
|
+
throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 对 LangGraph `BaseStore`(InMemoryStore 或 PostgresStore)的轻量类型封装,
|
|
3
|
+
* 让应用其他部分不必直接处理 store 的底层细节。
|
|
4
|
+
*/
|
|
5
|
+
export class MemoryStore {
|
|
6
|
+
store;
|
|
7
|
+
constructor(store) {
|
|
8
|
+
this.store = store;
|
|
9
|
+
}
|
|
10
|
+
async put(namespace, key, value) {
|
|
11
|
+
await this.store.put(namespace, key, {
|
|
12
|
+
...value,
|
|
13
|
+
updatedAt: new Date().toISOString(),
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
async get(namespace, key) {
|
|
17
|
+
const item = await this.store.get(namespace, key);
|
|
18
|
+
if (!item) return null;
|
|
19
|
+
return toRecord(item);
|
|
20
|
+
}
|
|
21
|
+
async search(namespacePrefix, limit = 20) {
|
|
22
|
+
const items = await this.store.search(namespacePrefix, { limit });
|
|
23
|
+
return items.map((item) => toRecord(item));
|
|
24
|
+
}
|
|
25
|
+
async delete(namespace, key) {
|
|
26
|
+
await this.store.delete(namespace, key);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const toRecord = (item) => {
|
|
30
|
+
return {
|
|
31
|
+
key: item.key,
|
|
32
|
+
namespace: item.namespace,
|
|
33
|
+
value: item.value,
|
|
34
|
+
...(item.updatedAt ? { updatedAt: new Date(item.updatedAt).toISOString() } : {}),
|
|
35
|
+
};
|
|
36
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会修改状态或操作基础设施的工具。它们会通过 `interruptOn` 暂停,
|
|
3
|
+
* 等待人工批准后再执行。
|
|
4
|
+
*/
|
|
5
|
+
export const SENSITIVE_TOOLS = [
|
|
6
|
+
"write_file",
|
|
7
|
+
"edit_file",
|
|
8
|
+
"delete",
|
|
9
|
+
"execute",
|
|
10
|
+
"write_workspace_file",
|
|
11
|
+
"query_database",
|
|
12
|
+
];
|
|
13
|
+
/** 模板已知的全部工具名称。 */
|
|
14
|
+
export const KNOWN_TOOLS = [
|
|
15
|
+
...SENSITIVE_TOOLS,
|
|
16
|
+
"web_search",
|
|
17
|
+
"read_file",
|
|
18
|
+
"read_workspace_file",
|
|
19
|
+
"list_workspace_files",
|
|
20
|
+
"ls",
|
|
21
|
+
"glob",
|
|
22
|
+
"grep",
|
|
23
|
+
"write_todos",
|
|
24
|
+
"task",
|
|
25
|
+
];
|
|
26
|
+
/**
|
|
27
|
+
* 构建 `createDeepAgent` 使用的 `interruptOn` 映射。
|
|
28
|
+
*
|
|
29
|
+
* - none:不启用审批
|
|
30
|
+
* - sensitive:修改类工具执行前暂停(默认)
|
|
31
|
+
* - all:所有已知工具执行前都暂停
|
|
32
|
+
*/
|
|
33
|
+
export const createApprovalPolicy = (mode) => {
|
|
34
|
+
if (mode === "none") return {};
|
|
35
|
+
const tools = mode === "all" ? [...KNOWN_TOOLS] : [...SENSITIVE_TOOLS];
|
|
36
|
+
return Object.fromEntries(tools.map((tool) => [tool, true]));
|
|
37
|
+
};
|
|
38
|
+
export const requiresApproval = (mode, toolName) => {
|
|
39
|
+
if (mode === "none") return false;
|
|
40
|
+
if (mode === "all") return KNOWN_TOOLS.includes(toolName);
|
|
41
|
+
return SENSITIVE_TOOLS.includes(toolName);
|
|
42
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
export const runtimeContextSchema = z.object({
|
|
4
|
+
tenantId: z.string().default("default"),
|
|
5
|
+
userId: z.string().optional(),
|
|
6
|
+
threadId: z.string().optional(),
|
|
7
|
+
});
|
|
8
|
+
/**
|
|
9
|
+
* 把每次请求的上下文注入系统提示词。上下文由 API 通过
|
|
10
|
+
* `config.context` 提供,不会随会话持久化。
|
|
11
|
+
*/
|
|
12
|
+
export const createContextMiddleware = () => {
|
|
13
|
+
return createMiddleware({
|
|
14
|
+
name: "ContextMiddleware",
|
|
15
|
+
contextSchema: runtimeContextSchema,
|
|
16
|
+
wrapModelCall: async (request, handler) => {
|
|
17
|
+
const context = runtimeContextSchema.parse(request.runtime.context ?? {});
|
|
18
|
+
const lines = [
|
|
19
|
+
"## 运行时上下文",
|
|
20
|
+
`- 租户:${context.tenantId}`,
|
|
21
|
+
...(context.userId ? [`- 用户:${context.userId}`] : []),
|
|
22
|
+
...(context.threadId ? [`- 会话:${context.threadId}`] : []),
|
|
23
|
+
];
|
|
24
|
+
const systemPrompt = [request.systemPrompt, lines.join("\n")]
|
|
25
|
+
.filter((part) => Boolean(part && part.trim()))
|
|
26
|
+
.join("\n\n");
|
|
27
|
+
return handler({ ...request, systemPrompt, systemMessage: undefined });
|
|
28
|
+
},
|
|
29
|
+
});
|
|
30
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createApprovalPolicy,
|
|
3
|
+
KNOWN_TOOLS,
|
|
4
|
+
requiresApproval,
|
|
5
|
+
SENSITIVE_TOOLS,
|
|
6
|
+
} from "./approval.js";
|
|
7
|
+
export { createContextMiddleware, runtimeContextSchema } from "./context.js";
|
|
8
|
+
export { createLoggingMiddleware } from "./logging.js";
|
|
9
|
+
export { createSecurityMiddleware, DANGEROUS_PATTERNS, findSecurityViolation } from "./security.js";
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
import { truncate } from "../utils/helpers.js";
|
|
3
|
+
/**
|
|
4
|
+
* 为每次模型和工具调用输出结构化日志。
|
|
5
|
+
* 对 payload 做截断,避免大段工具输出淹没日志。
|
|
6
|
+
*/
|
|
7
|
+
export const createLoggingMiddleware = (logger) => {
|
|
8
|
+
return createMiddleware({
|
|
9
|
+
name: "LoggingMiddleware",
|
|
10
|
+
wrapModelCall: async (request, handler) => {
|
|
11
|
+
const startedAt = Date.now();
|
|
12
|
+
try {
|
|
13
|
+
const response = await handler(request);
|
|
14
|
+
logger.debug(
|
|
15
|
+
{
|
|
16
|
+
model: request.model?.getName?.() ?? "未知",
|
|
17
|
+
durationMs: Date.now() - startedAt,
|
|
18
|
+
toolCalls: response.tool_calls?.length ?? 0,
|
|
19
|
+
},
|
|
20
|
+
"模型调用完成",
|
|
21
|
+
);
|
|
22
|
+
return response;
|
|
23
|
+
} catch (error) {
|
|
24
|
+
logger.error(
|
|
25
|
+
{
|
|
26
|
+
durationMs: Date.now() - startedAt,
|
|
27
|
+
error: error instanceof Error ? error.message : String(error),
|
|
28
|
+
},
|
|
29
|
+
"模型调用失败",
|
|
30
|
+
);
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
wrapToolCall: async (request, handler) => {
|
|
35
|
+
const startedAt = Date.now();
|
|
36
|
+
logger.debug(
|
|
37
|
+
{
|
|
38
|
+
tool: request.toolCall.name,
|
|
39
|
+
args: truncate(JSON.stringify(request.toolCall.args ?? {}), 500),
|
|
40
|
+
},
|
|
41
|
+
"工具调用开始",
|
|
42
|
+
);
|
|
43
|
+
try {
|
|
44
|
+
const result = await handler(request);
|
|
45
|
+
logger.debug(
|
|
46
|
+
{
|
|
47
|
+
tool: request.toolCall.name,
|
|
48
|
+
durationMs: Date.now() - startedAt,
|
|
49
|
+
},
|
|
50
|
+
"工具调用完成",
|
|
51
|
+
);
|
|
52
|
+
return result;
|
|
53
|
+
} catch (error) {
|
|
54
|
+
logger.error(
|
|
55
|
+
{
|
|
56
|
+
tool: request.toolCall.name,
|
|
57
|
+
durationMs: Date.now() - startedAt,
|
|
58
|
+
error: error instanceof Error ? error.message : String(error),
|
|
59
|
+
},
|
|
60
|
+
"工具调用失败",
|
|
61
|
+
);
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { ToolMessage } from "@langchain/core/messages";
|
|
2
|
+
import { createMiddleware } from "langchain";
|
|
3
|
+
/**
|
|
4
|
+
* 针对破坏性 shell/SQL 载荷的启发式规则。这是纵深防御,不是沙箱:
|
|
5
|
+
* 请以最小权限运行 Agent。
|
|
6
|
+
*/
|
|
7
|
+
export const DANGEROUS_PATTERNS = [
|
|
8
|
+
{
|
|
9
|
+
pattern: /\brm\s+-(?:[a-z]*r[a-z]*f|[a-z]*f[a-z]*r)\s+\/(?:\s|$)/i,
|
|
10
|
+
reason: "递归删除根目录",
|
|
11
|
+
},
|
|
12
|
+
{ pattern: /\bmkfs(?:\.\w+)?\b/i, reason: "格式化文件系统" },
|
|
13
|
+
{ pattern: /:\(\)\s*\{\s*:\|:\s*&\s*\};:/, reason: "fork 炸弹" },
|
|
14
|
+
{ pattern: /\bdd\s+if=.*\bof=\/dev\/[sh]d/i, reason: "直接写磁盘" },
|
|
15
|
+
{
|
|
16
|
+
pattern: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|k)?sh\b/i,
|
|
17
|
+
reason: "把下载内容管道给 shell 执行",
|
|
18
|
+
},
|
|
19
|
+
{ pattern: /\bchmod\s+-R\s+777\s+\//i, reason: "根目录权限设为 777" },
|
|
20
|
+
{ pattern: /\bshutdown\b|\breboot\b/i, reason: "关闭主机" },
|
|
21
|
+
{ pattern: /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i, reason: "破坏性 SQL" },
|
|
22
|
+
{ pattern: /\bTRUNCATE\s+TABLE\b/i, reason: "破坏性 SQL" },
|
|
23
|
+
];
|
|
24
|
+
export const findSecurityViolation = (value) => {
|
|
25
|
+
for (const { pattern, reason } of DANGEROUS_PATTERNS) {
|
|
26
|
+
if (pattern.test(value)) return reason;
|
|
27
|
+
}
|
|
28
|
+
return null;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* 在工具执行前拒绝危险参数。模型会收到一条解释拦截原因的工具消息,
|
|
32
|
+
* 从而改用更安全的方式。
|
|
33
|
+
*/
|
|
34
|
+
export const createSecurityMiddleware = () => {
|
|
35
|
+
return createMiddleware({
|
|
36
|
+
name: "SecurityMiddleware",
|
|
37
|
+
wrapToolCall: async (request, handler) => {
|
|
38
|
+
const serializedArgs = JSON.stringify(request.toolCall.args ?? {});
|
|
39
|
+
const violation = findSecurityViolation(serializedArgs);
|
|
40
|
+
if (violation) {
|
|
41
|
+
return new ToolMessage({
|
|
42
|
+
content: `已被安全策略拦截:${violation}。请选择更安全的方式。`,
|
|
43
|
+
tool_call_id: request.toolCall.id ?? "未知",
|
|
44
|
+
name: request.toolCall.name,
|
|
45
|
+
status: "error",
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
return handler(request);
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { threadIdSchema } from "./common.js";
|
|
3
|
+
export const invokeAgentSchema = z.object({
|
|
4
|
+
message: z.string().min(1).max(32_000),
|
|
5
|
+
threadId: threadIdSchema.optional(),
|
|
6
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
7
|
+
userId: z.string().min(1).max(128).optional(),
|
|
8
|
+
objective: z.string().max(2_000).optional(),
|
|
9
|
+
});
|
|
10
|
+
export const messageSchema = z.object({
|
|
11
|
+
role: z.string(),
|
|
12
|
+
content: z.unknown(),
|
|
13
|
+
});
|
|
14
|
+
export const invokeAgentResponseSchema = z.object({
|
|
15
|
+
threadId: z.string(),
|
|
16
|
+
text: z.string(),
|
|
17
|
+
messages: z.array(messageSchema),
|
|
18
|
+
});
|
|
19
|
+
export const approvalDecisionSchema = z.discriminatedUnion("type", [
|
|
20
|
+
z.object({ type: z.literal("approve") }),
|
|
21
|
+
z.object({ type: z.literal("reject"), message: z.string().max(2_000).optional() }),
|
|
22
|
+
z.object({ type: z.literal("respond"), message: z.string().max(8_000) }),
|
|
23
|
+
]);
|
|
24
|
+
export const resumeAgentSchema = z.object({
|
|
25
|
+
threadId: threadIdSchema,
|
|
26
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
27
|
+
userId: z.string().min(1).max(128).optional(),
|
|
28
|
+
decisions: z.array(approvalDecisionSchema).min(1),
|
|
29
|
+
});
|
|
30
|
+
export const streamEventSchema = z.object({
|
|
31
|
+
event: z.enum(["token", "values", "error", "done"]),
|
|
32
|
+
data: z.unknown(),
|
|
33
|
+
});
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import "./locale.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
export const idSchema = z.string().uuid();
|
|
4
|
+
export const threadIdSchema = z
|
|
5
|
+
.string()
|
|
6
|
+
.min(1)
|
|
7
|
+
.max(128)
|
|
8
|
+
.regex(/^[a-zA-Z0-9._:-]+$/, "会话 ID 只能包含字母、数字、点、下划线、冒号和短横线。");
|
|
9
|
+
export const paginationSchema = z.object({
|
|
10
|
+
limit: z.coerce.number().int().min(1).max(100).default(20),
|
|
11
|
+
offset: z.coerce.number().int().min(0).default(0),
|
|
12
|
+
});
|
|
13
|
+
export const apiErrorSchema = z.object({
|
|
14
|
+
error: z.object({
|
|
15
|
+
code: z.string(),
|
|
16
|
+
message: z.string(),
|
|
17
|
+
details: z.record(z.string(), z.unknown()).optional(),
|
|
18
|
+
}),
|
|
19
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { threadIdSchema } from "./common.js";
|
|
3
|
+
export const createSessionSchema = z.object({
|
|
4
|
+
threadId: threadIdSchema.optional(),
|
|
5
|
+
title: z.string().min(1).max(200).default("未命名会话"),
|
|
6
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
7
|
+
userId: z.string().min(1).max(128).optional(),
|
|
8
|
+
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
9
|
+
});
|
|
10
|
+
export const sessionSummarySchema = z.object({
|
|
11
|
+
threadId: z.string(),
|
|
12
|
+
title: z.string(),
|
|
13
|
+
tenantId: z.string(),
|
|
14
|
+
userId: z.string().optional(),
|
|
15
|
+
createdAt: z.string(),
|
|
16
|
+
updatedAt: z.string(),
|
|
17
|
+
messageCount: z.number().int().nonnegative(),
|
|
18
|
+
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
19
|
+
});
|
|
20
|
+
export const sessionListSchema = z.object({
|
|
21
|
+
sessions: z.array(sessionSummarySchema),
|
|
22
|
+
total: z.number().int().nonnegative(),
|
|
23
|
+
});
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { Command } from "@langchain/langgraph";
|
|
3
|
+
import { lastMessageText } from "../utils/helpers.js";
|
|
4
|
+
/**
|
|
5
|
+
* 应用层 Agent API:构建 invoke 输入,附加会话、租户和运行时上下文,
|
|
6
|
+
* 并把结果整理为适合 HTTP 客户端的形式。
|
|
7
|
+
*/
|
|
8
|
+
export class AgentService {
|
|
9
|
+
#agent;
|
|
10
|
+
#config;
|
|
11
|
+
#sessions;
|
|
12
|
+
constructor({ agent, config, sessions }) {
|
|
13
|
+
this.#agent = agent;
|
|
14
|
+
this.#config = config;
|
|
15
|
+
this.#sessions = sessions;
|
|
16
|
+
}
|
|
17
|
+
get graph() {
|
|
18
|
+
return this.#agent;
|
|
19
|
+
}
|
|
20
|
+
async invoke(input, { signal } = {}) {
|
|
21
|
+
const threadId = input.threadId ?? randomUUID();
|
|
22
|
+
await this.#sessions?.ensure({
|
|
23
|
+
threadId,
|
|
24
|
+
tenantId: input.tenantId,
|
|
25
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
26
|
+
});
|
|
27
|
+
const result = await this.#agent.invoke(
|
|
28
|
+
{
|
|
29
|
+
messages: [{ role: "user", content: input.message }],
|
|
30
|
+
tenantId: input.tenantId,
|
|
31
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
32
|
+
objective: input.objective ?? input.message,
|
|
33
|
+
},
|
|
34
|
+
{
|
|
35
|
+
configurable: { thread_id: threadId },
|
|
36
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
37
|
+
context: {
|
|
38
|
+
tenantId: input.tenantId,
|
|
39
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
40
|
+
threadId,
|
|
41
|
+
},
|
|
42
|
+
...(signal ? { signal } : {}),
|
|
43
|
+
},
|
|
44
|
+
);
|
|
45
|
+
return this.#finish(threadId, input.tenantId, result);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* 恢复因审批而暂停的运行。decisions 会按顺序匹配待处理的工具调用
|
|
49
|
+
* (approve、reject 或 respond)。
|
|
50
|
+
*/
|
|
51
|
+
async resume(input, { signal } = {}) {
|
|
52
|
+
const result = await this.#agent.invoke(
|
|
53
|
+
new Command({ resume: { decisions: input.decisions } }),
|
|
54
|
+
{
|
|
55
|
+
configurable: { thread_id: input.threadId },
|
|
56
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
57
|
+
context: {
|
|
58
|
+
tenantId: input.tenantId,
|
|
59
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
60
|
+
threadId: input.threadId,
|
|
61
|
+
},
|
|
62
|
+
...(signal ? { signal } : {}),
|
|
63
|
+
},
|
|
64
|
+
);
|
|
65
|
+
return this.#finish(input.threadId, input.tenantId, result);
|
|
66
|
+
}
|
|
67
|
+
async #finish(threadId, tenantId, result) {
|
|
68
|
+
const messages = Array.isArray(result.messages) ? result.messages : [];
|
|
69
|
+
const text = lastMessageText(messages);
|
|
70
|
+
const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
|
|
71
|
+
await this.#sessions?.touch({
|
|
72
|
+
threadId,
|
|
73
|
+
tenantId,
|
|
74
|
+
lastMessage: text,
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
threadId,
|
|
78
|
+
text,
|
|
79
|
+
messages,
|
|
80
|
+
...(interrupts.length > 0 ? { interrupts } : {}),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** 以状态快照流式输出 Agent 的工作过程(适配 SSE)。 */
|
|
84
|
+
async *stream(input, { signal } = {}) {
|
|
85
|
+
const threadId = input.threadId ?? randomUUID();
|
|
86
|
+
await this.#sessions?.ensure({
|
|
87
|
+
threadId,
|
|
88
|
+
tenantId: input.tenantId,
|
|
89
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
90
|
+
});
|
|
91
|
+
const stream = await this.#agent.stream(
|
|
92
|
+
{
|
|
93
|
+
messages: [{ role: "user", content: input.message }],
|
|
94
|
+
tenantId: input.tenantId,
|
|
95
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
96
|
+
objective: input.objective ?? input.message,
|
|
97
|
+
},
|
|
98
|
+
{
|
|
99
|
+
configurable: { thread_id: threadId },
|
|
100
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
101
|
+
streamMode: "values",
|
|
102
|
+
context: {
|
|
103
|
+
tenantId: input.tenantId,
|
|
104
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
105
|
+
threadId,
|
|
106
|
+
},
|
|
107
|
+
...(signal ? { signal } : {}),
|
|
108
|
+
},
|
|
109
|
+
);
|
|
110
|
+
for await (const chunk of stream) {
|
|
111
|
+
yield { event: "values", data: chunk };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async state(threadId) {
|
|
115
|
+
return this.#agent.getState({ configurable: { thread_id: threadId } });
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面向 HTTP 的记忆服务。封装 `MemoryManager`,
|
|
3
|
+
* 让路由层不需要了解命名空间和 store 细节。
|
|
4
|
+
*/
|
|
5
|
+
export class MemoryService {
|
|
6
|
+
#memory;
|
|
7
|
+
constructor(memory) {
|
|
8
|
+
this.#memory = memory;
|
|
9
|
+
}
|
|
10
|
+
async remember({ tenantId, userId, key, value, kind = "fact" }) {
|
|
11
|
+
const target = { tenantId, ...(userId ? { userId } : {}) };
|
|
12
|
+
if (kind === "preference") {
|
|
13
|
+
await this.#memory.rememberPreference(target, key, value);
|
|
14
|
+
} else {
|
|
15
|
+
await this.#memory.rememberFact(target, key, value);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
async recall(tenantId, key, userId) {
|
|
19
|
+
return this.#memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
|
|
20
|
+
}
|
|
21
|
+
async list(tenantId, userId, limit = 50) {
|
|
22
|
+
return this.#memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
|
|
23
|
+
}
|
|
24
|
+
async forget(tenantId, key, userId) {
|
|
25
|
+
await this.#memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
|
|
26
|
+
}
|
|
27
|
+
}
|