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,72 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
|
|
3
|
+
import type { Logger } from "../infrastructure/logger/index.js";
|
|
4
|
+
import { truncate } from "../utils/helpers.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 为每次模型和工具调用输出结构化日志。
|
|
8
|
+
* 对 payload 做截断,避免大段工具输出淹没日志。
|
|
9
|
+
*/
|
|
10
|
+
export const createLoggingMiddleware = (logger: Logger) => {
|
|
11
|
+
return createMiddleware({
|
|
12
|
+
name: "LoggingMiddleware",
|
|
13
|
+
|
|
14
|
+
wrapModelCall: async (request, handler) => {
|
|
15
|
+
const startedAt = Date.now();
|
|
16
|
+
try {
|
|
17
|
+
const response = await handler(request);
|
|
18
|
+
logger.debug(
|
|
19
|
+
{
|
|
20
|
+
model: request.model?.getName?.() ?? "未知",
|
|
21
|
+
durationMs: Date.now() - startedAt,
|
|
22
|
+
toolCalls: response.tool_calls?.length ?? 0,
|
|
23
|
+
},
|
|
24
|
+
"模型调用完成",
|
|
25
|
+
);
|
|
26
|
+
return response;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
logger.error(
|
|
29
|
+
{
|
|
30
|
+
durationMs: Date.now() - startedAt,
|
|
31
|
+
error: error instanceof Error ? error.message : String(error),
|
|
32
|
+
},
|
|
33
|
+
"模型调用失败",
|
|
34
|
+
);
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
|
|
39
|
+
wrapToolCall: async (request, handler) => {
|
|
40
|
+
const startedAt = Date.now();
|
|
41
|
+
logger.debug(
|
|
42
|
+
{
|
|
43
|
+
tool: request.toolCall.name,
|
|
44
|
+
args: truncate(JSON.stringify(request.toolCall.args ?? {}), 500),
|
|
45
|
+
},
|
|
46
|
+
"工具调用开始",
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
try {
|
|
50
|
+
const result = await handler(request);
|
|
51
|
+
logger.debug(
|
|
52
|
+
{
|
|
53
|
+
tool: request.toolCall.name,
|
|
54
|
+
durationMs: Date.now() - startedAt,
|
|
55
|
+
},
|
|
56
|
+
"工具调用完成",
|
|
57
|
+
);
|
|
58
|
+
return result;
|
|
59
|
+
} catch (error) {
|
|
60
|
+
logger.error(
|
|
61
|
+
{
|
|
62
|
+
tool: request.toolCall.name,
|
|
63
|
+
durationMs: Date.now() - startedAt,
|
|
64
|
+
error: error instanceof Error ? error.message : String(error),
|
|
65
|
+
},
|
|
66
|
+
"工具调用失败",
|
|
67
|
+
);
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { ToolMessage } from "@langchain/core/messages";
|
|
2
|
+
import { createMiddleware } from "langchain";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 针对破坏性 shell/SQL 载荷的启发式规则。这是纵深防御,不是沙箱:
|
|
6
|
+
* 请以最小权限运行 Agent。
|
|
7
|
+
*/
|
|
8
|
+
export const DANGEROUS_PATTERNS: ReadonlyArray<{
|
|
9
|
+
pattern: RegExp;
|
|
10
|
+
reason: string;
|
|
11
|
+
}> = [
|
|
12
|
+
{
|
|
13
|
+
pattern: /\brm\s+-(?:[a-z]*r[a-z]*f|[a-z]*f[a-z]*r)\s+\/(?:\s|$)/i,
|
|
14
|
+
reason: "递归删除根目录",
|
|
15
|
+
},
|
|
16
|
+
{ pattern: /\bmkfs(?:\.\w+)?\b/i, reason: "格式化文件系统" },
|
|
17
|
+
{ pattern: /:\(\)\s*\{\s*:\|:\s*&\s*\};:/, reason: "fork 炸弹" },
|
|
18
|
+
{ pattern: /\bdd\s+if=.*\bof=\/dev\/[sh]d/i, reason: "直接写磁盘" },
|
|
19
|
+
{
|
|
20
|
+
pattern: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|k)?sh\b/i,
|
|
21
|
+
reason: "把下载内容管道给 shell 执行",
|
|
22
|
+
},
|
|
23
|
+
{ pattern: /\bchmod\s+-R\s+777\s+\//i, reason: "根目录权限设为 777" },
|
|
24
|
+
{ pattern: /\bshutdown\b|\breboot\b/i, reason: "关闭主机" },
|
|
25
|
+
{ pattern: /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i, reason: "破坏性 SQL" },
|
|
26
|
+
{ pattern: /\bTRUNCATE\s+TABLE\b/i, reason: "破坏性 SQL" },
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
export const findSecurityViolation = (value: string): string | null => {
|
|
30
|
+
for (const { pattern, reason } of DANGEROUS_PATTERNS) {
|
|
31
|
+
if (pattern.test(value)) return reason;
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 在工具执行前拒绝危险参数。模型会收到一条解释拦截原因的工具消息,
|
|
38
|
+
* 从而改用更安全的方式。
|
|
39
|
+
*/
|
|
40
|
+
export const createSecurityMiddleware = () => {
|
|
41
|
+
return createMiddleware({
|
|
42
|
+
name: "SecurityMiddleware",
|
|
43
|
+
|
|
44
|
+
wrapToolCall: async (request, handler) => {
|
|
45
|
+
const serializedArgs = JSON.stringify(request.toolCall.args ?? {});
|
|
46
|
+
const violation = findSecurityViolation(serializedArgs);
|
|
47
|
+
|
|
48
|
+
if (violation) {
|
|
49
|
+
return new ToolMessage({
|
|
50
|
+
content: `已被安全策略拦截:${violation}。请选择更安全的方式。`,
|
|
51
|
+
tool_call_id: request.toolCall.id ?? "未知",
|
|
52
|
+
name: request.toolCall.name,
|
|
53
|
+
status: "error",
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return handler(request);
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
import { threadIdSchema } from "./common.js";
|
|
4
|
+
|
|
5
|
+
export const invokeAgentSchema = z.object({
|
|
6
|
+
message: z.string().min(1).max(32_000),
|
|
7
|
+
threadId: threadIdSchema.optional(),
|
|
8
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
9
|
+
userId: z.string().min(1).max(128).optional(),
|
|
10
|
+
objective: z.string().max(2_000).optional(),
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export type InvokeAgentInput = z.infer<typeof invokeAgentSchema>;
|
|
14
|
+
|
|
15
|
+
export const messageSchema = z.object({
|
|
16
|
+
role: z.string(),
|
|
17
|
+
content: z.unknown(),
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
export const invokeAgentResponseSchema = z.object({
|
|
21
|
+
threadId: z.string(),
|
|
22
|
+
text: z.string(),
|
|
23
|
+
messages: z.array(messageSchema),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export type InvokeAgentResponse = z.infer<typeof invokeAgentResponseSchema>;
|
|
27
|
+
|
|
28
|
+
export const approvalDecisionSchema = z.discriminatedUnion("type", [
|
|
29
|
+
z.object({ type: z.literal("approve") }),
|
|
30
|
+
z.object({ type: z.literal("reject"), message: z.string().max(2_000).optional() }),
|
|
31
|
+
z.object({ type: z.literal("respond"), message: z.string().max(8_000) }),
|
|
32
|
+
]);
|
|
33
|
+
|
|
34
|
+
export type ApprovalDecision = z.infer<typeof approvalDecisionSchema>;
|
|
35
|
+
|
|
36
|
+
export const resumeAgentSchema = z.object({
|
|
37
|
+
threadId: threadIdSchema,
|
|
38
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
39
|
+
userId: z.string().min(1).max(128).optional(),
|
|
40
|
+
decisions: z.array(approvalDecisionSchema).min(1),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
export type ResumeAgentInput = z.infer<typeof resumeAgentSchema>;
|
|
44
|
+
|
|
45
|
+
export const streamEventSchema = z.object({
|
|
46
|
+
event: z.enum(["token", "values", "error", "done"]),
|
|
47
|
+
data: z.unknown(),
|
|
48
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import "./locale.js";
|
|
2
|
+
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
|
|
5
|
+
export const idSchema = z.string().uuid();
|
|
6
|
+
|
|
7
|
+
export const threadIdSchema = z
|
|
8
|
+
.string()
|
|
9
|
+
.min(1)
|
|
10
|
+
.max(128)
|
|
11
|
+
.regex(/^[a-zA-Z0-9._:-]+$/, "会话 ID 只能包含字母、数字、点、下划线、冒号和短横线。");
|
|
12
|
+
|
|
13
|
+
export const paginationSchema = z.object({
|
|
14
|
+
limit: z.coerce.number().int().min(1).max(100).default(20),
|
|
15
|
+
offset: z.coerce.number().int().min(0).default(0),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export const apiErrorSchema = z.object({
|
|
19
|
+
error: z.object({
|
|
20
|
+
code: z.string(),
|
|
21
|
+
message: z.string(),
|
|
22
|
+
details: z.record(z.string(), z.unknown()).optional(),
|
|
23
|
+
}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export type Pagination = z.infer<typeof paginationSchema>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
import { threadIdSchema } from "./common.js";
|
|
4
|
+
|
|
5
|
+
export const createSessionSchema = z.object({
|
|
6
|
+
threadId: threadIdSchema.optional(),
|
|
7
|
+
title: z.string().min(1).max(200).default("未命名会话"),
|
|
8
|
+
tenantId: z.string().min(1).max(128).default("default"),
|
|
9
|
+
userId: z.string().min(1).max(128).optional(),
|
|
10
|
+
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
export type CreateSessionInput = z.infer<typeof createSessionSchema>;
|
|
14
|
+
|
|
15
|
+
export const sessionSummarySchema = z.object({
|
|
16
|
+
threadId: z.string(),
|
|
17
|
+
title: z.string(),
|
|
18
|
+
tenantId: z.string(),
|
|
19
|
+
userId: z.string().optional(),
|
|
20
|
+
createdAt: z.string(),
|
|
21
|
+
updatedAt: z.string(),
|
|
22
|
+
messageCount: z.number().int().nonnegative(),
|
|
23
|
+
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export type SessionSummary = z.infer<typeof sessionSummarySchema>;
|
|
27
|
+
|
|
28
|
+
export const sessionListSchema = z.object({
|
|
29
|
+
sessions: z.array(sessionSummarySchema),
|
|
30
|
+
total: z.number().int().nonnegative(),
|
|
31
|
+
});
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import { Command } from "@langchain/langgraph";
|
|
4
|
+
|
|
5
|
+
import type { CompiledAgent } from "../graph/compile.js";
|
|
6
|
+
import type { AppConfig } from "../config/index.js";
|
|
7
|
+
import type { InvokeAgentInput, ResumeAgentInput } from "../schemas/agent.js";
|
|
8
|
+
import { lastMessageText } from "../utils/helpers.js";
|
|
9
|
+
import type { SessionService } from "./session.service.js";
|
|
10
|
+
|
|
11
|
+
export interface AgentServiceDependencies {
|
|
12
|
+
agent: CompiledAgent;
|
|
13
|
+
config: AppConfig;
|
|
14
|
+
sessions?: SessionService;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface InvokeAgentResult {
|
|
18
|
+
threadId: string;
|
|
19
|
+
text: string;
|
|
20
|
+
messages: unknown[];
|
|
21
|
+
/** 运行因审批门暂停时存在。 */
|
|
22
|
+
interrupts?: unknown[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface AgentStreamEvent {
|
|
26
|
+
event: "values";
|
|
27
|
+
data: unknown;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface RunOptions {
|
|
31
|
+
signal?: AbortSignal;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 应用层 Agent API:构建 invoke 输入,附加会话、租户和运行时上下文,
|
|
36
|
+
* 并把结果整理为适合 HTTP 客户端的形式。
|
|
37
|
+
*/
|
|
38
|
+
export class AgentService {
|
|
39
|
+
readonly #agent: CompiledAgent;
|
|
40
|
+
readonly #config: AppConfig;
|
|
41
|
+
readonly #sessions?: SessionService;
|
|
42
|
+
|
|
43
|
+
constructor({ agent, config, sessions }: AgentServiceDependencies) {
|
|
44
|
+
this.#agent = agent;
|
|
45
|
+
this.#config = config;
|
|
46
|
+
this.#sessions = sessions;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
get graph(): CompiledAgent {
|
|
50
|
+
return this.#agent;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async invoke(input: InvokeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
|
|
54
|
+
const threadId = input.threadId ?? randomUUID();
|
|
55
|
+
|
|
56
|
+
await this.#sessions?.ensure({
|
|
57
|
+
threadId,
|
|
58
|
+
tenantId: input.tenantId,
|
|
59
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const result = await this.#agent.invoke(
|
|
63
|
+
{
|
|
64
|
+
messages: [{ role: "user", content: input.message }],
|
|
65
|
+
tenantId: input.tenantId,
|
|
66
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
67
|
+
objective: input.objective ?? input.message,
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
configurable: { thread_id: threadId },
|
|
71
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
72
|
+
context: {
|
|
73
|
+
tenantId: input.tenantId,
|
|
74
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
75
|
+
threadId,
|
|
76
|
+
},
|
|
77
|
+
...(signal ? { signal } : {}),
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
return this.#finish(threadId, input.tenantId, result);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 恢复因审批而暂停的运行。decisions 会按顺序匹配待处理的工具调用
|
|
86
|
+
* (approve、reject 或 respond)。
|
|
87
|
+
*/
|
|
88
|
+
async resume(input: ResumeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
|
|
89
|
+
const result = await this.#agent.invoke(
|
|
90
|
+
new Command({ resume: { decisions: input.decisions } }),
|
|
91
|
+
{
|
|
92
|
+
configurable: { thread_id: input.threadId },
|
|
93
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
94
|
+
context: {
|
|
95
|
+
tenantId: input.tenantId,
|
|
96
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
97
|
+
threadId: input.threadId,
|
|
98
|
+
},
|
|
99
|
+
...(signal ? { signal } : {}),
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
return this.#finish(input.threadId, input.tenantId, result);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async #finish(
|
|
107
|
+
threadId: string,
|
|
108
|
+
tenantId: string,
|
|
109
|
+
result: { messages?: unknown[]; __interrupt__?: unknown },
|
|
110
|
+
): Promise<InvokeAgentResult> {
|
|
111
|
+
const messages = Array.isArray(result.messages) ? result.messages : [];
|
|
112
|
+
const text = lastMessageText(messages);
|
|
113
|
+
const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
|
|
114
|
+
|
|
115
|
+
await this.#sessions?.touch({
|
|
116
|
+
threadId,
|
|
117
|
+
tenantId,
|
|
118
|
+
lastMessage: text,
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
return {
|
|
122
|
+
threadId,
|
|
123
|
+
text,
|
|
124
|
+
messages,
|
|
125
|
+
...(interrupts.length > 0 ? { interrupts } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** 以状态快照流式输出 Agent 的工作过程(适配 SSE)。 */
|
|
130
|
+
async *stream(
|
|
131
|
+
input: InvokeAgentInput,
|
|
132
|
+
{ signal }: RunOptions = {},
|
|
133
|
+
): AsyncGenerator<AgentStreamEvent> {
|
|
134
|
+
const threadId = input.threadId ?? randomUUID();
|
|
135
|
+
|
|
136
|
+
await this.#sessions?.ensure({
|
|
137
|
+
threadId,
|
|
138
|
+
tenantId: input.tenantId,
|
|
139
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
const stream = await this.#agent.stream(
|
|
143
|
+
{
|
|
144
|
+
messages: [{ role: "user", content: input.message }],
|
|
145
|
+
tenantId: input.tenantId,
|
|
146
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
147
|
+
objective: input.objective ?? input.message,
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
configurable: { thread_id: threadId },
|
|
151
|
+
recursionLimit: this.#config.agent.recursionLimit,
|
|
152
|
+
streamMode: "values",
|
|
153
|
+
context: {
|
|
154
|
+
tenantId: input.tenantId,
|
|
155
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
156
|
+
threadId,
|
|
157
|
+
},
|
|
158
|
+
...(signal ? { signal } : {}),
|
|
159
|
+
},
|
|
160
|
+
);
|
|
161
|
+
|
|
162
|
+
for await (const chunk of stream as AsyncIterable<unknown>) {
|
|
163
|
+
yield { event: "values", data: chunk };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async state(threadId: string): Promise<unknown> {
|
|
168
|
+
return this.#agent.getState({ configurable: { thread_id: threadId } });
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { MemoryManager, MemoryRecord } from "../memory/index.js";
|
|
2
|
+
|
|
3
|
+
export interface RememberInput {
|
|
4
|
+
tenantId: string;
|
|
5
|
+
userId?: string;
|
|
6
|
+
key: string;
|
|
7
|
+
value: Record<string, unknown>;
|
|
8
|
+
kind?: "preference" | "fact";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 面向 HTTP 的记忆服务。封装 `MemoryManager`,
|
|
13
|
+
* 让路由层不需要了解命名空间和 store 细节。
|
|
14
|
+
*/
|
|
15
|
+
export class MemoryService {
|
|
16
|
+
readonly #memory: MemoryManager;
|
|
17
|
+
|
|
18
|
+
constructor(memory: MemoryManager) {
|
|
19
|
+
this.#memory = memory;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async remember({ tenantId, userId, key, value, kind = "fact" }: RememberInput): Promise<void> {
|
|
23
|
+
const target = { tenantId, ...(userId ? { userId } : {}) };
|
|
24
|
+
|
|
25
|
+
if (kind === "preference") {
|
|
26
|
+
await this.#memory.rememberPreference(target, key, value);
|
|
27
|
+
} else {
|
|
28
|
+
await this.#memory.rememberFact(target, key, value);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async recall(tenantId: string, key: string, userId?: string): Promise<MemoryRecord | null> {
|
|
33
|
+
return this.#memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async list(tenantId: string, userId?: string, limit = 50): Promise<MemoryRecord[]> {
|
|
37
|
+
return this.#memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async forget(tenantId: string, key: string, userId?: string): Promise<void> {
|
|
41
|
+
await this.#memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
import type { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph";
|
|
4
|
+
|
|
5
|
+
import type { CompiledAgent } from "../graph/compile.js";
|
|
6
|
+
import type { CreateSessionInput, SessionSummary } from "../schemas/session.js";
|
|
7
|
+
import { NotFoundError } from "../utils/errors.js";
|
|
8
|
+
|
|
9
|
+
interface SessionRecord {
|
|
10
|
+
threadId: string;
|
|
11
|
+
title: string;
|
|
12
|
+
tenantId: string;
|
|
13
|
+
userId?: string;
|
|
14
|
+
createdAt: string;
|
|
15
|
+
updatedAt: string;
|
|
16
|
+
lastMessage?: string;
|
|
17
|
+
messageCount: number;
|
|
18
|
+
metadata: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface SessionServiceDependencies {
|
|
22
|
+
graph: CompiledAgent;
|
|
23
|
+
checkpointer: BaseCheckpointSaver;
|
|
24
|
+
store: BaseStore;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface EnsureSessionInput {
|
|
28
|
+
threadId: string;
|
|
29
|
+
tenantId: string;
|
|
30
|
+
userId?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface TouchSessionInput {
|
|
34
|
+
threadId: string;
|
|
35
|
+
tenantId: string;
|
|
36
|
+
lastMessage?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* 会话元数据存放在 LangGraph store 的
|
|
41
|
+
* `["sessions", tenantId, threadId]` 下;对话本身存放在 checkpointer 中。
|
|
42
|
+
* 该服务在 HTTP API 层把两者组合起来。
|
|
43
|
+
*/
|
|
44
|
+
export class SessionService {
|
|
45
|
+
readonly #graph: CompiledAgent;
|
|
46
|
+
readonly #checkpointer: BaseCheckpointSaver;
|
|
47
|
+
readonly #store: BaseStore;
|
|
48
|
+
|
|
49
|
+
constructor({ graph, checkpointer, store }: SessionServiceDependencies) {
|
|
50
|
+
this.#graph = graph;
|
|
51
|
+
this.#checkpointer = checkpointer;
|
|
52
|
+
this.#store = store;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async create(input: CreateSessionInput): Promise<SessionSummary> {
|
|
56
|
+
const threadId = input.threadId ?? randomUUID();
|
|
57
|
+
const now = new Date().toISOString();
|
|
58
|
+
|
|
59
|
+
const record: SessionRecord = {
|
|
60
|
+
threadId,
|
|
61
|
+
title: input.title,
|
|
62
|
+
tenantId: input.tenantId,
|
|
63
|
+
...(input.userId ? { userId: input.userId } : {}),
|
|
64
|
+
createdAt: now,
|
|
65
|
+
updatedAt: now,
|
|
66
|
+
messageCount: 0,
|
|
67
|
+
metadata: input.metadata,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
await this.#store.put(namespace(input.tenantId), threadId, record);
|
|
71
|
+
return { ...record };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** 会话记录不存在时创建(幂等)。 */
|
|
75
|
+
async ensure({ threadId, tenantId, userId }: EnsureSessionInput): Promise<void> {
|
|
76
|
+
const existing = await this.#store.get(namespace(tenantId), threadId);
|
|
77
|
+
if (existing) return;
|
|
78
|
+
|
|
79
|
+
await this.create({
|
|
80
|
+
threadId,
|
|
81
|
+
tenantId,
|
|
82
|
+
title: `Session ${threadId.slice(0, 8)}`,
|
|
83
|
+
metadata: {},
|
|
84
|
+
...(userId ? { userId } : {}),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async touch({ threadId, tenantId, lastMessage }: TouchSessionInput): Promise<void> {
|
|
89
|
+
const item = await this.#store.get(namespace(tenantId), threadId);
|
|
90
|
+
if (!item) return;
|
|
91
|
+
|
|
92
|
+
const record = item.value as unknown as SessionRecord;
|
|
93
|
+
await this.#store.put(namespace(tenantId), threadId, {
|
|
94
|
+
...record,
|
|
95
|
+
updatedAt: new Date().toISOString(),
|
|
96
|
+
messageCount: record.messageCount + 2,
|
|
97
|
+
...(lastMessage ? { lastMessage: lastMessage.slice(0, 1_000) } : {}),
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async get(threadId: string, tenantId = "default"): Promise<SessionSummary> {
|
|
102
|
+
const item = await this.#store.get(namespace(tenantId), threadId);
|
|
103
|
+
if (!item) {
|
|
104
|
+
throw new NotFoundError(`未找到会话 "${threadId}"。`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const record = item.value as unknown as SessionRecord;
|
|
108
|
+
const state = await this.#graph.getState({
|
|
109
|
+
configurable: { thread_id: threadId },
|
|
110
|
+
});
|
|
111
|
+
const values = state.values as { messages?: unknown[] } | undefined;
|
|
112
|
+
|
|
113
|
+
return {
|
|
114
|
+
...record,
|
|
115
|
+
messageCount: values?.messages?.length ?? record.messageCount,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async list(
|
|
120
|
+
tenantId = "default",
|
|
121
|
+
limit = 20,
|
|
122
|
+
): Promise<{ sessions: SessionSummary[]; total: number }> {
|
|
123
|
+
const items = await this.#store.search(namespace(tenantId), { limit });
|
|
124
|
+
|
|
125
|
+
const sessions = items.map(({ value }) => ({
|
|
126
|
+
...(value as unknown as SessionRecord),
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
return { sessions, total: sessions.length };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async remove(threadId: string, tenantId = "default"): Promise<void> {
|
|
133
|
+
await this.#checkpointer.deleteThread(threadId);
|
|
134
|
+
await this.#store.delete(namespace(tenantId), threadId);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async history(threadId: string): Promise<unknown[]> {
|
|
138
|
+
const state = await this.#graph.getState({
|
|
139
|
+
configurable: { thread_id: threadId },
|
|
140
|
+
});
|
|
141
|
+
const values = state.values as { messages?: unknown[] } | undefined;
|
|
142
|
+
return values?.messages ?? [];
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const namespace = (tenantId: string): string[] => {
|
|
147
|
+
return ["sessions", tenantId];
|
|
148
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { discoverSkills, type SkillMetadata } from "./loader.js";
|
|
2
|
+
|
|
3
|
+
export type { SkillMetadata } from "./loader.js";
|
|
4
|
+
export { discoverSkills, parseSkillFrontmatter } from "./loader.js";
|
|
5
|
+
|
|
6
|
+
/** Deep Agents skills 中间件扫描的虚拟后端路径。 */
|
|
7
|
+
export const DEFAULT_SKILL_SOURCES = ["/skills/"] as const;
|
|
8
|
+
|
|
9
|
+
export interface LoadSkillsOptions {
|
|
10
|
+
rootDir: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 从磁盘发现技能(用于启动校验和 `scripts/check`)。 */
|
|
14
|
+
export const loadSkills = async ({ rootDir }: LoadSkillsOptions): Promise<SkillMetadata[]> => {
|
|
15
|
+
return discoverSkills(rootDir);
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 为缺少 description 的技能返回可读警告。
|
|
20
|
+
* 模型正是依赖 description 来选择技能。
|
|
21
|
+
*/
|
|
22
|
+
export const validateSkills = (skills: readonly SkillMetadata[]): string[] => {
|
|
23
|
+
return skills
|
|
24
|
+
.filter((skill) => skill.description.trim().length === 0)
|
|
25
|
+
.map((skill) => `技能 "${skill.name}" 缺少 description(${skill.file})`);
|
|
26
|
+
};
|