create-deepagent-server 0.1.0 → 1.0.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.
Files changed (175) hide show
  1. package/README.md +83 -8
  2. package/package.json +1 -1
  3. package/src/args.js +6 -4
  4. package/src/cli.js +1 -4
  5. package/src/dependencies.js +1 -1
  6. package/src/prompts.js +1 -0
  7. package/src/registry.js +8 -8
  8. package/src/scaffold.js +21 -7
  9. package/src/setup.js +2 -0
  10. package/src/version.js +1 -1
  11. package/src/versions.js +1 -1
  12. package/templates/deepagent/js/scripts/check.js +34 -11
  13. package/templates/deepagent/js/scripts/dev.js +9 -0
  14. package/templates/deepagent/js/src/agents/factory.js +2 -1
  15. package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
  16. package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
  17. package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
  18. package/templates/deepagent/js/src/agents/state/types.js +1 -0
  19. package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
  20. package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
  21. package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
  22. package/templates/deepagent/js/src/agents/supervisor.js +12 -4
  23. package/templates/deepagent/js/src/api/app.js +7 -0
  24. package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
  25. package/templates/deepagent/js/src/api/middleware/error.js +4 -0
  26. package/templates/deepagent/js/src/api/routes/agent.js +19 -49
  27. package/templates/deepagent/js/src/api/routes/health.js +12 -3
  28. package/templates/deepagent/js/src/api/routes/session.js +28 -48
  29. package/templates/deepagent/js/src/app.js +31 -12
  30. package/templates/deepagent/js/src/backends/composite.js +2 -0
  31. package/templates/deepagent/js/src/backends/filesystem.js +1 -0
  32. package/templates/deepagent/js/src/backends/index.js +35 -3
  33. package/templates/deepagent/js/src/backends/sandbox.js +3 -0
  34. package/templates/deepagent/js/src/config/agent.js +1 -0
  35. package/templates/deepagent/js/src/config/database.js +19 -0
  36. package/templates/deepagent/js/src/config/env.js +46 -23
  37. package/templates/deepagent/js/src/config/index.js +13 -3
  38. package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
  39. package/templates/deepagent/js/src/graph/compile.js +1 -0
  40. package/templates/deepagent/js/src/graph/store.js +10 -2
  41. package/templates/deepagent/js/src/index.js +9 -2
  42. package/templates/deepagent/js/src/memory/index.js +2 -0
  43. package/templates/deepagent/js/src/memory/manager.js +21 -10
  44. package/templates/deepagent/js/src/memory/store.js +7 -0
  45. package/templates/deepagent/js/src/middleware/approval.js +6 -1
  46. package/templates/deepagent/js/src/middleware/context.js +5 -0
  47. package/templates/deepagent/js/src/middleware/logging.js +47 -43
  48. package/templates/deepagent/js/src/middleware/security.js +7 -0
  49. package/templates/deepagent/js/src/model/config.js +38 -0
  50. package/templates/deepagent/js/src/model/index.js +9 -0
  51. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  52. package/templates/deepagent/js/src/model/presets.js +71 -0
  53. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  54. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  55. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  56. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  57. package/templates/deepagent/js/src/schemas/agent.js +7 -0
  58. package/templates/deepagent/js/src/schemas/common.js +5 -0
  59. package/templates/deepagent/js/src/schemas/locale.js +1 -0
  60. package/templates/deepagent/js/src/schemas/session.js +4 -0
  61. package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
  62. package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
  63. package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
  64. package/templates/deepagent/js/src/skills/index.js +4 -0
  65. package/templates/deepagent/js/src/skills/loader.js +20 -10
  66. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  67. package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
  68. package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
  69. package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
  70. package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
  71. package/templates/deepagent/js/src/tools/database/index.js +1 -1
  72. package/templates/deepagent/js/src/tools/database/query.js +44 -32
  73. package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
  74. package/templates/deepagent/js/src/tools/index.js +6 -11
  75. package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
  76. package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
  77. package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
  78. package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
  79. package/templates/deepagent/js/src/utils/errors.js +9 -0
  80. package/templates/deepagent/js/src/utils/helpers.js +15 -0
  81. package/templates/deepagent/js/src/utils/validation.js +15 -0
  82. package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
  83. package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
  84. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  85. package/templates/deepagent/js/tests/integration/api.test.js +18 -3
  86. package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
  87. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  88. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  89. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  90. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  91. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +5 -1
  93. package/templates/deepagent/shared/README.md +101 -14
  94. package/templates/deepagent/shared/_env.example +40 -10
  95. package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
  96. package/templates/deepagent/shared/resources/AGENTS.md +1 -1
  97. package/templates/deepagent/ts/scripts/check.ts +19 -11
  98. package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
  99. package/templates/deepagent/ts/src/agents/factory.ts +1 -1
  100. package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
  101. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
  102. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
  103. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
  104. package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
  105. package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
  106. package/templates/deepagent/ts/src/api/app.ts +4 -4
  107. package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
  108. package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
  109. package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
  110. package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
  111. package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
  112. package/templates/deepagent/ts/src/app.ts +19 -12
  113. package/templates/deepagent/ts/src/backends/index.ts +41 -7
  114. package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
  115. package/templates/deepagent/ts/src/config/database.ts +21 -0
  116. package/templates/deepagent/ts/src/config/env.ts +32 -28
  117. package/templates/deepagent/ts/src/config/index.ts +12 -4
  118. package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
  119. package/templates/deepagent/ts/src/graph/store.ts +5 -2
  120. package/templates/deepagent/ts/src/index.ts +2 -2
  121. package/templates/deepagent/ts/src/memory/manager.ts +12 -10
  122. package/templates/deepagent/ts/src/memory/store.ts +2 -0
  123. package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
  124. package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
  125. package/templates/deepagent/ts/src/middleware/security.ts +1 -0
  126. package/templates/deepagent/ts/src/model/config.ts +56 -0
  127. package/templates/deepagent/ts/src/model/index.ts +14 -0
  128. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  129. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  130. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  131. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  132. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  133. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  134. package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
  135. package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
  136. package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
  137. package/templates/deepagent/ts/src/skills/loader.ts +6 -10
  138. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  139. package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
  140. package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
  141. package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
  142. package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
  143. package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
  144. package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
  145. package/templates/deepagent/ts/src/tools/index.ts +10 -8
  146. package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
  147. package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
  148. package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
  149. package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
  150. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  151. package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
  152. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
  153. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  154. package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
  155. package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
  156. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  157. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  158. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  159. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  160. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  161. package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
  162. package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
  163. package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
  164. package/templates/deepagent/js/src/config/model.js +0 -34
  165. package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
  166. package/templates/deepagent/js/src/tools/search/index.js +0 -1
  167. package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
  168. package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
  169. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
  170. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
  171. package/templates/deepagent/ts/src/config/model.ts +0 -49
  172. package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
  173. package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
  174. package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
  175. /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
@@ -0,0 +1,216 @@
1
+ import {
2
+ ConnectionConfig,
3
+ Sandbox,
4
+ SandboxApiException,
5
+ type CommandExecution,
6
+ } from "@alibaba-group/opensandbox";
7
+ import {
8
+ BaseSandbox,
9
+ type ExecuteResponse,
10
+ type FileDownloadResponse,
11
+ type FileOperationError,
12
+ type FileUploadResponse,
13
+ } from "deepagents";
14
+
15
+ import { errorMessage } from "../utils/helpers.js";
16
+ import type { SandboxConfig } from "./config.js";
17
+
18
+ const MAX_OUTPUT_CHARS = 100_000;
19
+
20
+ export interface OpenSandboxBackendOptions {
21
+ sandbox: Sandbox;
22
+ workspaceRoot?: string;
23
+ /** 沙箱是否由当前进程创建;复用已有沙箱时设为 false,销毁时只关闭连接。 */
24
+ owned?: boolean;
25
+ }
26
+
27
+ const parentDirectory = (filePath: string): string => {
28
+ const index = filePath.lastIndexOf("/");
29
+ return index <= 0 ? "/" : filePath.slice(0, index);
30
+ };
31
+
32
+ const fileError = (error: unknown): FileOperationError => {
33
+ if (error instanceof SandboxApiException) {
34
+ if (error.statusCode === 404) return "file_not_found";
35
+ if (error.statusCode === 403) return "permission_denied";
36
+ if (error.statusCode === 400) return "invalid_path";
37
+ }
38
+
39
+ const message = errorMessage(error).toLowerCase();
40
+ if (message.includes("not found") || message.includes("no such file")) return "file_not_found";
41
+ if (message.includes("permission")) return "permission_denied";
42
+ if (message.includes("directory")) return "is_directory";
43
+
44
+ return "invalid_path";
45
+ };
46
+
47
+ const isMissingSession = (error: unknown): boolean => {
48
+ if (error instanceof SandboxApiException && error.statusCode === 404) return true;
49
+
50
+ const message = errorMessage(error).toLowerCase();
51
+ return (
52
+ message.includes("session") &&
53
+ ["not found", "expired", "invalid"].some((hint) => message.includes(hint))
54
+ );
55
+ };
56
+
57
+ const formatExecution = (execution: CommandExecution): ExecuteResponse => {
58
+ const stdout = execution.logs.stdout.map((message) => message.text);
59
+ const stderr = execution.logs.stderr.map((message) => `[stderr] ${message.text}`);
60
+ const output = [...stdout, ...stderr].join("\n");
61
+ const truncated = output.length > MAX_OUTPUT_CHARS;
62
+ const exitCode = execution.exitCode ?? execution.error?.exitCode ?? (execution.error ? 1 : 0);
63
+
64
+ return {
65
+ output: truncated ? `${output.slice(0, MAX_OUTPUT_CHARS)}\n… 输出已截断` : output,
66
+ exitCode,
67
+ truncated,
68
+ };
69
+ };
70
+
71
+ /**
72
+ * 把 OpenSandbox 沙箱接入 deepagents。
73
+ *
74
+ * 一个后端实例持有同一个远程沙箱:`execute` 在沙箱内维护一个持久 bash session,
75
+ * 因此 `cd`、`export`、函数定义等状态会跨命令保留;命令按顺序串行执行,
76
+ * 避免并发命令互相覆盖 shell 状态。文件读写仍走 `sandbox.files`,
77
+ * `ls` / `read` / `grep` / `glob` / `edit` 由 `BaseSandbox` 复用 session 完成。
78
+ */
79
+ export class OpenSandboxBackend extends BaseSandbox {
80
+ readonly id: string;
81
+
82
+ private readonly sandbox: Sandbox;
83
+ private readonly workspaceRoot: string;
84
+ private readonly owned: boolean;
85
+
86
+ private session: Promise<string> | undefined;
87
+ private queue: Promise<void> = Promise.resolve();
88
+
89
+ constructor({ sandbox, workspaceRoot = "/workspace", owned = true }: OpenSandboxBackendOptions) {
90
+ super();
91
+ this.sandbox = sandbox;
92
+ this.workspaceRoot = workspaceRoot;
93
+ this.owned = owned;
94
+ this.id = sandbox.id;
95
+ }
96
+
97
+ execute(command: string): Promise<ExecuteResponse> {
98
+ const result = this.queue.then(() => this.runInSession(command));
99
+
100
+ this.queue = result.then(
101
+ () => undefined,
102
+ () => undefined,
103
+ );
104
+
105
+ return result;
106
+ }
107
+
108
+ async uploadFiles(files: Array<[string, Uint8Array]>): Promise<FileUploadResponse[]> {
109
+ return Promise.all(
110
+ files.map(([filePath, content]) => {
111
+ const directory = parentDirectory(filePath);
112
+ const prepare = directory === "/" ? Promise.resolve() : this.ensureDirectory(directory);
113
+
114
+ return prepare
115
+ .then(() =>
116
+ this.sandbox.files.writeFiles([{ path: filePath, data: content, mode: 0o644 }]),
117
+ )
118
+ .then(
119
+ () => ({ path: filePath, error: null }),
120
+ (error: unknown) => ({ path: filePath, error: fileError(error) }),
121
+ );
122
+ }),
123
+ );
124
+ }
125
+
126
+ async downloadFiles(paths: string[]): Promise<FileDownloadResponse[]> {
127
+ return Promise.all(
128
+ paths.map((filePath) => {
129
+ return this.sandbox.files.readBytes(filePath).then(
130
+ (content) => ({ path: filePath, content, error: null }),
131
+ (error: unknown) => ({ path: filePath, content: null, error: fileError(error) }),
132
+ );
133
+ }),
134
+ );
135
+ }
136
+
137
+ /** 续期沙箱 TTL;服务端已回收时抛错(通常 404),由 SandboxManager 决定是否重建。 */
138
+ async renew(timeoutSeconds: number): Promise<void> {
139
+ await this.sandbox.renew(timeoutSeconds);
140
+ }
141
+
142
+ /** 关闭会话、终止(仅限自建)沙箱并释放 SDK 连接资源。 */
143
+ async destroy(): Promise<void> {
144
+ const session = await this.session?.catch(() => undefined);
145
+ if (session) {
146
+ await this.sandbox.commands.deleteSession(session).catch(() => undefined);
147
+ }
148
+
149
+ if (this.owned) {
150
+ await this.sandbox.kill().catch(() => undefined);
151
+ }
152
+
153
+ await this.sandbox.close().catch(() => undefined);
154
+ }
155
+
156
+ private runInSession(command: string): Promise<ExecuteResponse> {
157
+ return this.executeInSession(command).catch((error: unknown) => {
158
+ if (!isMissingSession(error)) throw error;
159
+
160
+ this.session = undefined;
161
+ return this.executeInSession(command);
162
+ });
163
+ }
164
+
165
+ private async executeInSession(command: string): Promise<ExecuteResponse> {
166
+ const sessionId = await this.ensureSession();
167
+ const execution = await this.sandbox.commands.runInSession(sessionId, command);
168
+
169
+ return formatExecution(execution);
170
+ }
171
+
172
+ private ensureSession(): Promise<string> {
173
+ this.session ??= this.sandbox.commands
174
+ .createSession({ workingDirectory: this.workspaceRoot })
175
+ .catch((error: unknown) => {
176
+ this.session = undefined;
177
+ throw error;
178
+ });
179
+
180
+ return this.session;
181
+ }
182
+
183
+ private ensureDirectory(directory: string): Promise<void> {
184
+ return this.sandbox.files.createDirectories([{ path: directory, mode: 0o755 }]);
185
+ }
186
+ }
187
+
188
+ /** 创建(或连接)OpenSandbox 沙箱,并预热工作目录。 */
189
+ export const createOpenSandboxBackend = async (
190
+ config: SandboxConfig,
191
+ ): Promise<OpenSandboxBackend> => {
192
+ const connectionConfig = new ConnectionConfig({
193
+ domain: config.domain,
194
+ protocol: config.protocol,
195
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
196
+ });
197
+
198
+ const sandbox = config.sandboxId
199
+ ? await Sandbox.connect({ connectionConfig, sandboxId: config.sandboxId })
200
+ : await Sandbox.create({
201
+ connectionConfig,
202
+ image: config.image,
203
+ timeoutSeconds: config.timeoutSeconds ?? null,
204
+ });
205
+
206
+ const owned = !config.sandboxId;
207
+
208
+ return sandbox.files.createDirectories([{ path: config.workspaceRoot, mode: 0o755 }]).then(
209
+ () => new OpenSandboxBackend({ sandbox, workspaceRoot: config.workspaceRoot, owned }),
210
+ async (error: unknown) => {
211
+ if (owned) await sandbox.kill().catch(() => undefined);
212
+ await sandbox.close().catch(() => undefined);
213
+ throw error;
214
+ },
215
+ );
216
+ };
@@ -2,11 +2,11 @@ import { randomUUID } from "node:crypto";
2
2
 
3
3
  import { Command } from "@langchain/langgraph";
4
4
 
5
- import type { CompiledAgent } from "../graph/compile.js";
5
+ import type { CompiledAgent } from "../graph/index.js";
6
6
  import type { AppConfig } from "../config/index.js";
7
7
  import type { InvokeAgentInput, ResumeAgentInput } from "../schemas/agent.js";
8
8
  import { lastMessageText } from "../utils/helpers.js";
9
- import type { SessionService } from "./session.service.js";
9
+ import type { SessionService } from "./session.js";
10
10
 
11
11
  export interface AgentServiceDependencies {
12
12
  agent: CompiledAgent;
@@ -36,30 +36,30 @@ export interface RunOptions {
36
36
  * 并把结果整理为适合 HTTP 客户端的形式。
37
37
  */
38
38
  export class AgentService {
39
- readonly #agent: CompiledAgent;
40
- readonly #config: AppConfig;
41
- readonly #sessions?: SessionService;
39
+ private readonly agent: CompiledAgent;
40
+ private readonly config: AppConfig;
41
+ private readonly sessions?: SessionService;
42
42
 
43
43
  constructor({ agent, config, sessions }: AgentServiceDependencies) {
44
- this.#agent = agent;
45
- this.#config = config;
46
- this.#sessions = sessions;
44
+ this.agent = agent;
45
+ this.config = config;
46
+ this.sessions = sessions;
47
47
  }
48
48
 
49
49
  get graph(): CompiledAgent {
50
- return this.#agent;
50
+ return this.agent;
51
51
  }
52
52
 
53
53
  async invoke(input: InvokeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
54
54
  const threadId = input.threadId ?? randomUUID();
55
55
 
56
- await this.#sessions?.ensure({
56
+ await this.sessions?.ensure({
57
57
  threadId,
58
58
  tenantId: input.tenantId,
59
59
  ...(input.userId ? { userId: input.userId } : {}),
60
60
  });
61
61
 
62
- const result = await this.#agent.invoke(
62
+ const result = await this.agent.invoke(
63
63
  {
64
64
  messages: [{ role: "user", content: input.message }],
65
65
  tenantId: input.tenantId,
@@ -68,7 +68,7 @@ export class AgentService {
68
68
  },
69
69
  {
70
70
  configurable: { thread_id: threadId },
71
- recursionLimit: this.#config.agent.recursionLimit,
71
+ recursionLimit: this.config.agent.recursionLimit,
72
72
  context: {
73
73
  tenantId: input.tenantId,
74
74
  ...(input.userId ? { userId: input.userId } : {}),
@@ -78,7 +78,7 @@ export class AgentService {
78
78
  },
79
79
  );
80
80
 
81
- return this.#finish(threadId, input.tenantId, result);
81
+ return this.finish(threadId, input.tenantId, result);
82
82
  }
83
83
 
84
84
  /**
@@ -86,11 +86,11 @@ export class AgentService {
86
86
  * (approve、reject 或 respond)。
87
87
  */
88
88
  async resume(input: ResumeAgentInput, { signal }: RunOptions = {}): Promise<InvokeAgentResult> {
89
- const result = await this.#agent.invoke(
89
+ const result = await this.agent.invoke(
90
90
  new Command({ resume: { decisions: input.decisions } }),
91
91
  {
92
92
  configurable: { thread_id: input.threadId },
93
- recursionLimit: this.#config.agent.recursionLimit,
93
+ recursionLimit: this.config.agent.recursionLimit,
94
94
  context: {
95
95
  tenantId: input.tenantId,
96
96
  ...(input.userId ? { userId: input.userId } : {}),
@@ -100,10 +100,10 @@ export class AgentService {
100
100
  },
101
101
  );
102
102
 
103
- return this.#finish(input.threadId, input.tenantId, result);
103
+ return this.finish(input.threadId, input.tenantId, result);
104
104
  }
105
105
 
106
- async #finish(
106
+ private async finish(
107
107
  threadId: string,
108
108
  tenantId: string,
109
109
  result: { messages?: unknown[]; __interrupt__?: unknown },
@@ -112,7 +112,7 @@ export class AgentService {
112
112
  const text = lastMessageText(messages);
113
113
  const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
114
114
 
115
- await this.#sessions?.touch({
115
+ await this.sessions?.touch({
116
116
  threadId,
117
117
  tenantId,
118
118
  lastMessage: text,
@@ -133,13 +133,13 @@ export class AgentService {
133
133
  ): AsyncGenerator<AgentStreamEvent> {
134
134
  const threadId = input.threadId ?? randomUUID();
135
135
 
136
- await this.#sessions?.ensure({
136
+ await this.sessions?.ensure({
137
137
  threadId,
138
138
  tenantId: input.tenantId,
139
139
  ...(input.userId ? { userId: input.userId } : {}),
140
140
  });
141
141
 
142
- const stream = await this.#agent.stream(
142
+ const stream = await this.agent.stream(
143
143
  {
144
144
  messages: [{ role: "user", content: input.message }],
145
145
  tenantId: input.tenantId,
@@ -148,7 +148,7 @@ export class AgentService {
148
148
  },
149
149
  {
150
150
  configurable: { thread_id: threadId },
151
- recursionLimit: this.#config.agent.recursionLimit,
151
+ recursionLimit: this.config.agent.recursionLimit,
152
152
  streamMode: "values",
153
153
  context: {
154
154
  tenantId: input.tenantId,
@@ -165,6 +165,6 @@ export class AgentService {
165
165
  }
166
166
 
167
167
  async state(threadId: string): Promise<unknown> {
168
- return this.#agent.getState({ configurable: { thread_id: threadId } });
168
+ return this.agent.getState({ configurable: { thread_id: threadId } });
169
169
  }
170
170
  }
@@ -13,31 +13,31 @@ export interface RememberInput {
13
13
  * 让路由层不需要了解命名空间和 store 细节。
14
14
  */
15
15
  export class MemoryService {
16
- readonly #memory: MemoryManager;
16
+ private readonly memory: MemoryManager;
17
17
 
18
18
  constructor(memory: MemoryManager) {
19
- this.#memory = memory;
19
+ this.memory = memory;
20
20
  }
21
21
 
22
22
  async remember({ tenantId, userId, key, value, kind = "fact" }: RememberInput): Promise<void> {
23
23
  const target = { tenantId, ...(userId ? { userId } : {}) };
24
24
 
25
25
  if (kind === "preference") {
26
- await this.#memory.rememberPreference(target, key, value);
26
+ await this.memory.rememberPreference(target, key, value);
27
27
  } else {
28
- await this.#memory.rememberFact(target, key, value);
28
+ await this.memory.rememberFact(target, key, value);
29
29
  }
30
30
  }
31
31
 
32
32
  async recall(tenantId: string, key: string, userId?: string): Promise<MemoryRecord | null> {
33
- return this.#memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
33
+ return this.memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
34
34
  }
35
35
 
36
36
  async list(tenantId: string, userId?: string, limit = 50): Promise<MemoryRecord[]> {
37
- return this.#memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
37
+ return this.memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
38
38
  }
39
39
 
40
40
  async forget(tenantId: string, key: string, userId?: string): Promise<void> {
41
- await this.#memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
41
+ await this.memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
42
42
  }
43
43
  }
@@ -2,7 +2,8 @@ import { randomUUID } from "node:crypto";
2
2
 
3
3
  import type { BaseCheckpointSaver, BaseStore } from "@langchain/langgraph";
4
4
 
5
- import type { CompiledAgent } from "../graph/compile.js";
5
+ import type { CompiledAgent } from "../graph/index.js";
6
+ import type { SandboxManager } from "../sandbox/index.js";
6
7
  import type { CreateSessionInput, SessionSummary } from "../schemas/session.js";
7
8
  import { NotFoundError } from "../utils/errors.js";
8
9
 
@@ -22,6 +23,8 @@ export interface SessionServiceDependencies {
22
23
  graph: CompiledAgent;
23
24
  checkpointer: BaseCheckpointSaver;
24
25
  store: BaseStore;
26
+ /** 提供后,删除会话会同时释放该会话的沙箱。 */
27
+ sandboxes?: SandboxManager;
25
28
  }
26
29
 
27
30
  export interface EnsureSessionInput {
@@ -42,14 +45,16 @@ export interface TouchSessionInput {
42
45
  * 该服务在 HTTP API 层把两者组合起来。
43
46
  */
44
47
  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;
48
+ private readonly graph: CompiledAgent;
49
+ private readonly checkpointer: BaseCheckpointSaver;
50
+ private readonly store: BaseStore;
51
+ private readonly sandboxes?: SandboxManager;
52
+
53
+ constructor({ graph, checkpointer, store, sandboxes }: SessionServiceDependencies) {
54
+ this.graph = graph;
55
+ this.checkpointer = checkpointer;
56
+ this.store = store;
57
+ this.sandboxes = sandboxes;
53
58
  }
54
59
 
55
60
  async create(input: CreateSessionInput): Promise<SessionSummary> {
@@ -67,13 +72,14 @@ export class SessionService {
67
72
  metadata: input.metadata,
68
73
  };
69
74
 
70
- await this.#store.put(namespace(input.tenantId), threadId, record);
75
+ await this.store.put(namespace(input.tenantId), threadId, record);
76
+
71
77
  return { ...record };
72
78
  }
73
79
 
74
80
  /** 会话记录不存在时创建(幂等)。 */
75
81
  async ensure({ threadId, tenantId, userId }: EnsureSessionInput): Promise<void> {
76
- const existing = await this.#store.get(namespace(tenantId), threadId);
82
+ const existing = await this.store.get(namespace(tenantId), threadId);
77
83
  if (existing) return;
78
84
 
79
85
  await this.create({
@@ -86,11 +92,12 @@ export class SessionService {
86
92
  }
87
93
 
88
94
  async touch({ threadId, tenantId, lastMessage }: TouchSessionInput): Promise<void> {
89
- const item = await this.#store.get(namespace(tenantId), threadId);
95
+ const item = await this.store.get(namespace(tenantId), threadId);
90
96
  if (!item) return;
91
97
 
92
98
  const record = item.value as unknown as SessionRecord;
93
- await this.#store.put(namespace(tenantId), threadId, {
99
+
100
+ await this.store.put(namespace(tenantId), threadId, {
94
101
  ...record,
95
102
  updatedAt: new Date().toISOString(),
96
103
  messageCount: record.messageCount + 2,
@@ -99,13 +106,14 @@ export class SessionService {
99
106
  }
100
107
 
101
108
  async get(threadId: string, tenantId = "default"): Promise<SessionSummary> {
102
- const item = await this.#store.get(namespace(tenantId), threadId);
109
+ const item = await this.store.get(namespace(tenantId), threadId);
103
110
  if (!item) {
104
111
  throw new NotFoundError(`未找到会话 "${threadId}"。`);
105
112
  }
106
113
 
107
114
  const record = item.value as unknown as SessionRecord;
108
- const state = await this.#graph.getState({
115
+
116
+ const state = await this.graph.getState({
109
117
  configurable: { thread_id: threadId },
110
118
  });
111
119
  const values = state.values as { messages?: unknown[] } | undefined;
@@ -120,7 +128,7 @@ export class SessionService {
120
128
  tenantId = "default",
121
129
  limit = 20,
122
130
  ): Promise<{ sessions: SessionSummary[]; total: number }> {
123
- const items = await this.#store.search(namespace(tenantId), { limit });
131
+ const items = await this.store.search(namespace(tenantId), { limit });
124
132
 
125
133
  const sessions = items.map(({ value }) => ({
126
134
  ...(value as unknown as SessionRecord),
@@ -130,15 +138,17 @@ export class SessionService {
130
138
  }
131
139
 
132
140
  async remove(threadId: string, tenantId = "default"): Promise<void> {
133
- await this.#checkpointer.deleteThread(threadId);
134
- await this.#store.delete(namespace(tenantId), threadId);
141
+ await this.checkpointer.deleteThread(threadId);
142
+ await this.store.delete(namespace(tenantId), threadId);
143
+ await this.sandboxes?.release(threadId);
135
144
  }
136
145
 
137
146
  async history(threadId: string): Promise<unknown[]> {
138
- const state = await this.#graph.getState({
147
+ const state = await this.graph.getState({
139
148
  configurable: { thread_id: threadId },
140
149
  });
141
150
  const values = state.values as { messages?: unknown[] } | undefined;
151
+
142
152
  return values?.messages ?? [];
143
153
  }
144
154
  }
@@ -46,23 +46,19 @@ export const parseSkillFrontmatter = (content: string): SkillFrontmatter => {
46
46
  };
47
47
 
48
48
  /** 读取目录;目录不存在时返回空数组。 */
49
- const readDirectory = async (directory: string): Promise<Dirent[]> => {
50
- try {
51
- return await fs.readdir(directory, { withFileTypes: true });
52
- } catch (error) {
49
+ const readDirectory = (directory: string): Promise<Dirent[]> => {
50
+ return fs.readdir(directory, { withFileTypes: true }).catch((error: unknown) => {
53
51
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
54
52
  throw error;
55
- }
53
+ });
56
54
  };
57
55
 
58
56
  /** 读取文本文件;文件不存在时返回 null。 */
59
- const readTextFile = async (file: string): Promise<string | null> => {
60
- try {
61
- return await fs.readFile(file, "utf8");
62
- } catch (error) {
57
+ const readTextFile = (file: string): Promise<string | null> => {
58
+ return fs.readFile(file, "utf8").catch((error: unknown) => {
63
59
  if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
64
60
  throw error;
65
- }
61
+ });
66
62
  };
67
63
 
68
64
  /**
@@ -0,0 +1,65 @@
1
+ import { performance } from "node:perf_hooks";
2
+
3
+ import { Pool, type PoolClient } from "pg";
4
+
5
+ import { ConfigurationError } from "../../utils/errors.js";
6
+ import { errorMessage } from "../../utils/helpers.js";
7
+
8
+ let pool: Pool | undefined;
9
+
10
+ /** 懒加载共享的 PostgreSQL 连接池。 */
11
+ export const getPool = (connectionString = process.env.DATABASE_URL): Pool => {
12
+ if (!connectionString) {
13
+ throw new ConfigurationError(
14
+ "未配置 PostgreSQL 连接信息。请设置 DATABASE_URL 或 POSTGRES_* 后使用数据库功能。",
15
+ );
16
+ }
17
+
18
+ pool ??= new Pool({
19
+ connectionString,
20
+ max: 10,
21
+ idleTimeoutMillis: 30_000,
22
+ connectionTimeoutMillis: 5_000,
23
+ });
24
+
25
+ return pool;
26
+ };
27
+
28
+ export interface DatabaseHealth {
29
+ ok: boolean;
30
+ latencyMs?: number;
31
+ error?: string;
32
+ }
33
+
34
+ const probe = async (connectionString: string): Promise<DatabaseHealth> => {
35
+ const client: PoolClient = await getPool(connectionString).connect();
36
+ const startedAt = performance.now();
37
+
38
+ return client
39
+ .query("select 1")
40
+ .then(() => ({ ok: true, latencyMs: Math.round(performance.now() - startedAt) }))
41
+ .finally(() => client.release());
42
+ };
43
+
44
+ /** 健康检查只返回状态,不向上抛错:连接或查询失败都折算成 `ok: false`。 */
45
+ export const checkDatabase = async (
46
+ connectionString = process.env.DATABASE_URL,
47
+ ): Promise<DatabaseHealth> => {
48
+ if (!connectionString) {
49
+ return { ok: false, error: "未配置 PostgreSQL 连接信息" };
50
+ }
51
+
52
+ return probe(connectionString).catch((error: unknown) => ({
53
+ ok: false,
54
+ error: errorMessage(error),
55
+ }));
56
+ };
57
+
58
+ export const closeDatabase = async (): Promise<void> => {
59
+ if (!pool) return;
60
+
61
+ const current = pool;
62
+ pool = undefined;
63
+
64
+ await current.end();
65
+ };
@@ -5,7 +5,7 @@
5
5
  -- 所需的表;本迁移只用于应用自有的表结构。
6
6
  --
7
7
  -- 使用 psql 或你常用的迁移工具执行:
8
- -- psql "$DATABASE_URL" -f src/infrastructure/database/migrations/001_init.sql
8
+ -- psql "$DATABASE_URL" -f src/storage/database/migrations/001_init.sql
9
9
 
10
10
  CREATE TABLE IF NOT EXISTS agent_audit_log (
11
11
  id BIGSERIAL PRIMARY KEY,
@@ -3,6 +3,7 @@ import { performance } from "node:perf_hooks";
3
3
  import { Redis } from "ioredis";
4
4
 
5
5
  import { ConfigurationError } from "../../utils/errors.js";
6
+ import { errorMessage } from "../../utils/helpers.js";
6
7
 
7
8
  let client: Redis | undefined;
8
9
 
@@ -27,27 +28,23 @@ export interface RedisHealth {
27
28
  error?: string;
28
29
  }
29
30
 
31
+ const probe = async (): Promise<RedisHealth> => {
32
+ const redis = getRedis();
33
+ if (redis.status === "wait") await redis.connect();
34
+
35
+ const startedAt = performance.now();
36
+ await redis.ping();
37
+
38
+ return { ok: true, latencyMs: Math.round(performance.now() - startedAt) };
39
+ };
40
+
41
+ /** 健康检查只返回状态,不向上抛错:连接或 ping 失败都折算成 `ok: false`。 */
30
42
  export const checkRedis = async (): Promise<RedisHealth> => {
31
43
  if (!process.env.REDIS_URL) {
32
44
  return { ok: false, error: "未配置 REDIS_URL" };
33
45
  }
34
46
 
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
- }
47
+ return probe().catch((error: unknown) => ({ ok: false, error: errorMessage(error) }));
51
48
  };
52
49
 
53
50
  export const closeRedis = async (): Promise<void> => {
@@ -56,9 +53,5 @@ export const closeRedis = async (): Promise<void> => {
56
53
  const current = client;
57
54
  client = undefined;
58
55
 
59
- try {
60
- await current.quit();
61
- } catch {
62
- current.disconnect();
63
- }
56
+ await current.quit().catch(() => current.disconnect());
64
57
  };