create-deepagent-server 0.0.0-stage → 0.2.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 (204) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +292 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +195 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +86 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +181 -0
  11. package/src/setup.js +79 -0
  12. package/src/ui.js +43 -0
  13. package/src/version.js +1 -0
  14. package/src/versions.js +29 -0
  15. package/templates/deepagent/js/deployment/Dockerfile +19 -0
  16. package/templates/deepagent/js/scripts/check.js +97 -0
  17. package/templates/deepagent/js/scripts/dev.js +40 -0
  18. package/templates/deepagent/js/src/agents/factory.js +11 -0
  19. package/templates/deepagent/js/src/agents/index.js +4 -0
  20. package/templates/deepagent/js/src/agents/prompts/index.js +2 -0
  21. package/templates/deepagent/js/src/agents/prompts/loader.js +53 -0
  22. package/templates/deepagent/js/src/agents/prompts/subagents/analyst.md +17 -0
  23. package/templates/deepagent/js/src/agents/prompts/subagents/coder.md +17 -0
  24. package/templates/deepagent/js/src/agents/prompts/supervisor.js +21 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.md +41 -0
  26. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  27. package/templates/deepagent/js/src/agents/state/types.js +11 -0
  28. package/templates/deepagent/js/src/agents/subagents/analyst.js +12 -0
  29. package/templates/deepagent/js/src/agents/subagents/coder.js +12 -0
  30. package/templates/deepagent/js/src/agents/subagents/index.js +9 -0
  31. package/templates/deepagent/js/src/agents/supervisor.js +64 -0
  32. package/templates/deepagent/js/src/api/app.js +29 -0
  33. package/templates/deepagent/js/src/api/middleware/auth.js +36 -0
  34. package/templates/deepagent/js/src/api/middleware/error.js +30 -0
  35. package/templates/deepagent/js/src/api/routes/agent.js +43 -0
  36. package/templates/deepagent/js/src/api/routes/health.js +40 -0
  37. package/templates/deepagent/js/src/api/routes/session.js +42 -0
  38. package/templates/deepagent/js/src/app.js +98 -0
  39. package/templates/deepagent/js/src/backends/composite.js +22 -0
  40. package/templates/deepagent/js/src/backends/filesystem.js +9 -0
  41. package/templates/deepagent/js/src/backends/index.js +60 -0
  42. package/templates/deepagent/js/src/backends/sandbox.js +26 -0
  43. package/templates/deepagent/js/src/config/agent.js +14 -0
  44. package/templates/deepagent/js/src/config/database.js +19 -0
  45. package/templates/deepagent/js/src/config/env.js +96 -0
  46. package/templates/deepagent/js/src/config/index.js +45 -0
  47. package/templates/deepagent/js/src/graph/checkpointer.js +28 -0
  48. package/templates/deepagent/js/src/graph/compile.js +9 -0
  49. package/templates/deepagent/js/src/graph/index.js +3 -0
  50. package/templates/deepagent/js/src/graph/store.js +28 -0
  51. package/templates/deepagent/js/src/index.js +39 -0
  52. package/templates/deepagent/js/src/memory/index.js +8 -0
  53. package/templates/deepagent/js/src/memory/manager.js +50 -0
  54. package/templates/deepagent/js/src/memory/store.js +43 -0
  55. package/templates/deepagent/js/src/middleware/approval.js +47 -0
  56. package/templates/deepagent/js/src/middleware/context.js +35 -0
  57. package/templates/deepagent/js/src/middleware/index.js +9 -0
  58. package/templates/deepagent/js/src/middleware/logging.js +70 -0
  59. package/templates/deepagent/js/src/middleware/security.js +58 -0
  60. package/templates/deepagent/js/src/model/config.js +38 -0
  61. package/templates/deepagent/js/src/model/index.js +9 -0
  62. package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
  63. package/templates/deepagent/js/src/model/presets.js +71 -0
  64. package/templates/deepagent/js/src/sandbox/config.js +12 -0
  65. package/templates/deepagent/js/src/sandbox/index.js +3 -0
  66. package/templates/deepagent/js/src/sandbox/manager.js +161 -0
  67. package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
  68. package/templates/deepagent/js/src/schemas/agent.js +40 -0
  69. package/templates/deepagent/js/src/schemas/common.js +24 -0
  70. package/templates/deepagent/js/src/schemas/locale.js +4 -0
  71. package/templates/deepagent/js/src/schemas/session.js +27 -0
  72. package/templates/deepagent/js/src/services/agent.js +136 -0
  73. package/templates/deepagent/js/src/services/memory.js +33 -0
  74. package/templates/deepagent/js/src/services/session.js +118 -0
  75. package/templates/deepagent/js/src/skills/index.js +21 -0
  76. package/templates/deepagent/js/src/skills/loader.js +75 -0
  77. package/templates/deepagent/js/src/storage/database/client.js +57 -0
  78. package/templates/deepagent/js/src/storage/database/migrations/001_init.sql +20 -0
  79. package/templates/deepagent/js/src/storage/logger/index.js +21 -0
  80. package/templates/deepagent/js/src/storage/redis/client.js +51 -0
  81. package/templates/deepagent/js/src/storage/shutdown/index.js +58 -0
  82. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  83. package/templates/deepagent/js/src/tools/database/query.js +74 -0
  84. package/templates/deepagent/js/src/tools/filesystem/index.js +102 -0
  85. package/templates/deepagent/js/src/tools/index.js +25 -0
  86. package/templates/deepagent/js/src/tools/mcp/client.js +42 -0
  87. package/templates/deepagent/js/src/tools/mcp/connections.js +64 -0
  88. package/templates/deepagent/js/src/tools/mcp/index.js +10 -0
  89. package/templates/deepagent/js/src/tools/mcp/registry.js +36 -0
  90. package/templates/deepagent/js/src/utils/errors.js +73 -0
  91. package/templates/deepagent/js/src/utils/helpers.js +57 -0
  92. package/templates/deepagent/js/src/utils/validation.js +15 -0
  93. package/templates/deepagent/js/tests/agents/prompts.test.js +30 -0
  94. package/templates/deepagent/js/tests/agents/supervisor.test.js +42 -0
  95. package/templates/deepagent/js/tests/config/database.test.js +40 -0
  96. package/templates/deepagent/js/tests/integration/api.test.js +114 -0
  97. package/templates/deepagent/js/tests/middleware/security.test.js +27 -0
  98. package/templates/deepagent/js/tests/model/config.test.js +61 -0
  99. package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
  100. package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
  101. package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
  102. package/templates/deepagent/js/tests/services/session.test.js +41 -0
  103. package/templates/deepagent/js/tests/tools/query.test.js +27 -0
  104. package/templates/deepagent/shared/README.md +249 -0
  105. package/templates/deepagent/shared/_editorconfig +12 -0
  106. package/templates/deepagent/shared/_env.example +86 -0
  107. package/templates/deepagent/shared/_gitignore +22 -0
  108. package/templates/deepagent/shared/deployment/docker-compose.yml +60 -0
  109. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  110. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  111. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  112. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  113. package/templates/deepagent/shared/workspaces/README.md +5 -0
  114. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  115. package/templates/deepagent/ts/scripts/check.ts +99 -0
  116. package/templates/deepagent/ts/scripts/copy-assets.ts +37 -0
  117. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  118. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  119. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  120. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  121. package/templates/deepagent/ts/src/agents/prompts/loader.ts +53 -0
  122. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  123. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  124. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +41 -0
  125. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  126. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  127. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  128. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +18 -0
  129. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  130. package/templates/deepagent/ts/src/agents/subagents/index.ts +9 -0
  131. package/templates/deepagent/ts/src/agents/supervisor.ts +82 -0
  132. package/templates/deepagent/ts/src/api/app.ts +48 -0
  133. package/templates/deepagent/ts/src/api/middleware/auth.ts +38 -0
  134. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  135. package/templates/deepagent/ts/src/api/routes/agent.ts +48 -0
  136. package/templates/deepagent/ts/src/api/routes/health.ts +47 -0
  137. package/templates/deepagent/ts/src/api/routes/session.ts +47 -0
  138. package/templates/deepagent/ts/src/app.ts +111 -0
  139. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  140. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  141. package/templates/deepagent/ts/src/backends/index.ts +76 -0
  142. package/templates/deepagent/ts/src/backends/sandbox.ts +33 -0
  143. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  144. package/templates/deepagent/ts/src/config/database.ts +21 -0
  145. package/templates/deepagent/ts/src/config/env.ts +106 -0
  146. package/templates/deepagent/ts/src/config/index.ts +84 -0
  147. package/templates/deepagent/ts/src/graph/checkpointer.ts +29 -0
  148. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  149. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  150. package/templates/deepagent/ts/src/graph/store.ts +29 -0
  151. package/templates/deepagent/ts/src/index.ts +39 -0
  152. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  153. package/templates/deepagent/ts/src/memory/manager.ts +76 -0
  154. package/templates/deepagent/ts/src/memory/store.ts +59 -0
  155. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  156. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  157. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  158. package/templates/deepagent/ts/src/middleware/logging.ts +71 -0
  159. package/templates/deepagent/ts/src/middleware/security.ts +61 -0
  160. package/templates/deepagent/ts/src/model/config.ts +56 -0
  161. package/templates/deepagent/ts/src/model/index.ts +14 -0
  162. package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
  163. package/templates/deepagent/ts/src/model/presets.ts +82 -0
  164. package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
  165. package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
  166. package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
  167. package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
  168. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  169. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  170. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  171. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  172. package/templates/deepagent/ts/src/services/agent.ts +170 -0
  173. package/templates/deepagent/ts/src/services/memory.ts +43 -0
  174. package/templates/deepagent/ts/src/services/session.ts +158 -0
  175. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  176. package/templates/deepagent/ts/src/skills/loader.ts +90 -0
  177. package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
  178. package/templates/deepagent/ts/src/storage/database/migrations/001_init.sql +20 -0
  179. package/templates/deepagent/ts/src/storage/logger/index.ts +25 -0
  180. package/templates/deepagent/ts/src/storage/redis/client.ts +57 -0
  181. package/templates/deepagent/ts/src/storage/shutdown/index.ts +82 -0
  182. package/templates/deepagent/ts/src/tools/database/index.ts +5 -0
  183. package/templates/deepagent/ts/src/tools/database/query.ts +79 -0
  184. package/templates/deepagent/ts/src/tools/filesystem/index.ts +110 -0
  185. package/templates/deepagent/ts/src/tools/index.ts +43 -0
  186. package/templates/deepagent/ts/src/tools/mcp/client.ts +54 -0
  187. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  188. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  189. package/templates/deepagent/ts/src/tools/mcp/registry.ts +45 -0
  190. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  191. package/templates/deepagent/ts/src/utils/helpers.ts +57 -0
  192. package/templates/deepagent/ts/src/utils/validation.ts +17 -0
  193. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  194. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  195. package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
  196. package/templates/deepagent/ts/tests/integration/api.test.ts +122 -0
  197. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  198. package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
  199. package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
  200. package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
  201. package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
  202. package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
  203. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  204. package/templates/deepagent/ts/tsconfig.json +19 -0
@@ -0,0 +1,195 @@
1
+ import { ConnectionConfig, Sandbox, SandboxApiException } from "@alibaba-group/opensandbox";
2
+ import { BaseSandbox } from "deepagents";
3
+
4
+ import { errorMessage } from "../utils/helpers.js";
5
+
6
+ const MAX_OUTPUT_CHARS = 100_000;
7
+
8
+ const parentDirectory = (filePath) => {
9
+ const index = filePath.lastIndexOf("/");
10
+ return index <= 0 ? "/" : filePath.slice(0, index);
11
+ };
12
+
13
+ const fileError = (error) => {
14
+ if (error instanceof SandboxApiException) {
15
+ if (error.statusCode === 404) return "file_not_found";
16
+ if (error.statusCode === 403) return "permission_denied";
17
+ if (error.statusCode === 400) return "invalid_path";
18
+ }
19
+
20
+ const message = errorMessage(error).toLowerCase();
21
+ if (message.includes("not found") || message.includes("no such file")) return "file_not_found";
22
+ if (message.includes("permission")) return "permission_denied";
23
+ if (message.includes("directory")) return "is_directory";
24
+
25
+ return "invalid_path";
26
+ };
27
+
28
+ const isMissingSession = (error) => {
29
+ if (error instanceof SandboxApiException && error.statusCode === 404) return true;
30
+
31
+ const message = errorMessage(error).toLowerCase();
32
+ return (
33
+ message.includes("session") &&
34
+ ["not found", "expired", "invalid"].some((hint) => message.includes(hint))
35
+ );
36
+ };
37
+
38
+ const formatExecution = (execution) => {
39
+ const stdout = execution.logs.stdout.map((message) => message.text);
40
+ const stderr = execution.logs.stderr.map((message) => `[stderr] ${message.text}`);
41
+ const output = [...stdout, ...stderr].join("\n");
42
+ const truncated = output.length > MAX_OUTPUT_CHARS;
43
+ const exitCode = execution.exitCode ?? execution.error?.exitCode ?? (execution.error ? 1 : 0);
44
+
45
+ return {
46
+ output: truncated ? `${output.slice(0, MAX_OUTPUT_CHARS)}\n… 输出已截断` : output,
47
+ exitCode,
48
+ truncated,
49
+ };
50
+ };
51
+
52
+ /**
53
+ * 把 OpenSandbox 沙箱接入 deepagents。
54
+ *
55
+ * 一个后端实例持有同一个远程沙箱:`execute` 在沙箱内维护一个持久 bash session,
56
+ * 因此 `cd`、`export`、函数定义等状态会跨命令保留;命令按顺序串行执行,
57
+ * 避免并发命令互相覆盖 shell 状态。文件读写仍走 `sandbox.files`,
58
+ * `ls` / `read` / `grep` / `glob` / `edit` 由 `BaseSandbox` 复用 session 完成。
59
+ */
60
+ export class OpenSandboxBackend extends BaseSandbox {
61
+ id;
62
+
63
+ sandbox;
64
+ workspaceRoot;
65
+ owned;
66
+
67
+ session;
68
+ queue = Promise.resolve();
69
+
70
+ constructor({ sandbox, workspaceRoot = "/workspace", owned = true }) {
71
+ super();
72
+ this.sandbox = sandbox;
73
+ this.workspaceRoot = workspaceRoot;
74
+ this.owned = owned;
75
+ this.id = sandbox.id;
76
+ }
77
+
78
+ execute(command) {
79
+ const result = this.queue.then(() => this.runInSession(command));
80
+
81
+ this.queue = result.then(
82
+ () => undefined,
83
+ () => undefined,
84
+ );
85
+
86
+ return result;
87
+ }
88
+
89
+ async uploadFiles(files) {
90
+ return Promise.all(
91
+ files.map(([filePath, content]) => {
92
+ const directory = parentDirectory(filePath);
93
+ const prepare = directory === "/" ? Promise.resolve() : this.ensureDirectory(directory);
94
+
95
+ return prepare
96
+ .then(() =>
97
+ this.sandbox.files.writeFiles([{ path: filePath, data: content, mode: 0o644 }]),
98
+ )
99
+ .then(
100
+ () => ({ path: filePath, error: null }),
101
+ (error) => ({ path: filePath, error: fileError(error) }),
102
+ );
103
+ }),
104
+ );
105
+ }
106
+
107
+ async downloadFiles(paths) {
108
+ return Promise.all(
109
+ paths.map((filePath) => {
110
+ return this.sandbox.files.readBytes(filePath).then(
111
+ (content) => ({ path: filePath, content, error: null }),
112
+ (error) => ({ path: filePath, content: null, error: fileError(error) }),
113
+ );
114
+ }),
115
+ );
116
+ }
117
+
118
+ /** 续期沙箱 TTL;服务端已回收时抛错(通常 404),由 SandboxManager 决定是否重建。 */
119
+ async renew(timeoutSeconds) {
120
+ await this.sandbox.renew(timeoutSeconds);
121
+ }
122
+
123
+ /** 关闭会话、终止(仅限自建)沙箱并释放 SDK 连接资源。 */
124
+ async destroy() {
125
+ const session = await this.session?.catch(() => undefined);
126
+ if (session) {
127
+ await this.sandbox.commands.deleteSession(session).catch(() => undefined);
128
+ }
129
+
130
+ if (this.owned) {
131
+ await this.sandbox.kill().catch(() => undefined);
132
+ }
133
+
134
+ await this.sandbox.close().catch(() => undefined);
135
+ }
136
+
137
+ runInSession(command) {
138
+ return this.executeInSession(command).catch((error) => {
139
+ if (!isMissingSession(error)) throw error;
140
+
141
+ this.session = undefined;
142
+ return this.executeInSession(command);
143
+ });
144
+ }
145
+
146
+ async executeInSession(command) {
147
+ const sessionId = await this.ensureSession();
148
+ const execution = await this.sandbox.commands.runInSession(sessionId, command);
149
+
150
+ return formatExecution(execution);
151
+ }
152
+
153
+ ensureSession() {
154
+ this.session ??= this.sandbox.commands
155
+ .createSession({ workingDirectory: this.workspaceRoot })
156
+ .catch((error) => {
157
+ this.session = undefined;
158
+ throw error;
159
+ });
160
+
161
+ return this.session;
162
+ }
163
+
164
+ ensureDirectory(directory) {
165
+ return this.sandbox.files.createDirectories([{ path: directory, mode: 0o755 }]);
166
+ }
167
+ }
168
+
169
+ /** 创建(或连接)OpenSandbox 沙箱,并预热工作目录。 */
170
+ export const createOpenSandboxBackend = async (config) => {
171
+ const connectionConfig = new ConnectionConfig({
172
+ domain: config.domain,
173
+ protocol: config.protocol,
174
+ ...(config.apiKey ? { apiKey: config.apiKey } : {}),
175
+ });
176
+
177
+ const sandbox = config.sandboxId
178
+ ? await Sandbox.connect({ connectionConfig, sandboxId: config.sandboxId })
179
+ : await Sandbox.create({
180
+ connectionConfig,
181
+ image: config.image,
182
+ timeoutSeconds: config.timeoutSeconds ?? null,
183
+ });
184
+
185
+ const owned = !config.sandboxId;
186
+
187
+ return sandbox.files.createDirectories([{ path: config.workspaceRoot, mode: 0o755 }]).then(
188
+ () => new OpenSandboxBackend({ sandbox, workspaceRoot: config.workspaceRoot, owned }),
189
+ async (error) => {
190
+ if (owned) await sandbox.kill().catch(() => undefined);
191
+ await sandbox.close().catch(() => undefined);
192
+ throw error;
193
+ },
194
+ );
195
+ };
@@ -0,0 +1,40 @@
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 const messageSchema = z.object({
14
+ role: z.string(),
15
+ content: z.unknown(),
16
+ });
17
+
18
+ export const invokeAgentResponseSchema = z.object({
19
+ threadId: z.string(),
20
+ text: z.string(),
21
+ messages: z.array(messageSchema),
22
+ });
23
+
24
+ export const approvalDecisionSchema = z.discriminatedUnion("type", [
25
+ z.object({ type: z.literal("approve") }),
26
+ z.object({ type: z.literal("reject"), message: z.string().max(2_000).optional() }),
27
+ z.object({ type: z.literal("respond"), message: z.string().max(8_000) }),
28
+ ]);
29
+
30
+ export const resumeAgentSchema = z.object({
31
+ threadId: threadIdSchema,
32
+ tenantId: z.string().min(1).max(128).default("default"),
33
+ userId: z.string().min(1).max(128).optional(),
34
+ decisions: z.array(approvalDecisionSchema).min(1),
35
+ });
36
+
37
+ export const streamEventSchema = z.object({
38
+ event: z.enum(["token", "values", "error", "done"]),
39
+ data: z.unknown(),
40
+ });
@@ -0,0 +1,24 @@
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
+ });
@@ -0,0 +1,4 @@
1
+ import { z } from "zod";
2
+
3
+ // 全局启用中文校验提示,所有 Zod schema 共用。
4
+ z.config(z.locales.zhCN());
@@ -0,0 +1,27 @@
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 const sessionSummarySchema = z.object({
14
+ threadId: z.string(),
15
+ title: z.string(),
16
+ tenantId: z.string(),
17
+ userId: z.string().optional(),
18
+ createdAt: z.string(),
19
+ updatedAt: z.string(),
20
+ messageCount: z.number().int().nonnegative(),
21
+ metadata: z.record(z.string(), z.unknown()).default({}),
22
+ });
23
+
24
+ export const sessionListSchema = z.object({
25
+ sessions: z.array(sessionSummarySchema),
26
+ total: z.number().int().nonnegative(),
27
+ });
@@ -0,0 +1,136 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { Command } from "@langchain/langgraph";
4
+
5
+ import { lastMessageText } from "../utils/helpers.js";
6
+
7
+ /**
8
+ * 应用层 Agent API:构建 invoke 输入,附加会话、租户和运行时上下文,
9
+ * 并把结果整理为适合 HTTP 客户端的形式。
10
+ */
11
+ export class AgentService {
12
+ agent;
13
+ config;
14
+ sessions;
15
+
16
+ constructor({ agent, config, sessions }) {
17
+ this.agent = agent;
18
+ this.config = config;
19
+ this.sessions = sessions;
20
+ }
21
+
22
+ get graph() {
23
+ return this.agent;
24
+ }
25
+
26
+ async invoke(input, { signal } = {}) {
27
+ const threadId = input.threadId ?? randomUUID();
28
+
29
+ await this.sessions?.ensure({
30
+ threadId,
31
+ tenantId: input.tenantId,
32
+ ...(input.userId ? { userId: input.userId } : {}),
33
+ });
34
+
35
+ const result = await this.agent.invoke(
36
+ {
37
+ messages: [{ role: "user", content: input.message }],
38
+ tenantId: input.tenantId,
39
+ ...(input.userId ? { userId: input.userId } : {}),
40
+ objective: input.objective ?? input.message,
41
+ },
42
+ {
43
+ configurable: { thread_id: threadId },
44
+ recursionLimit: this.config.agent.recursionLimit,
45
+ context: {
46
+ tenantId: input.tenantId,
47
+ ...(input.userId ? { userId: input.userId } : {}),
48
+ threadId,
49
+ },
50
+ ...(signal ? { signal } : {}),
51
+ },
52
+ );
53
+
54
+ return this.finish(threadId, input.tenantId, result);
55
+ }
56
+
57
+ /**
58
+ * 恢复因审批而暂停的运行。decisions 会按顺序匹配待处理的工具调用
59
+ * (approve、reject 或 respond)。
60
+ */
61
+ async resume(input, { signal } = {}) {
62
+ const result = await this.agent.invoke(
63
+ new Command({ resume: { decisions: input.decisions } }),
64
+ {
65
+ configurable: { thread_id: input.threadId },
66
+ recursionLimit: this.config.agent.recursionLimit,
67
+ context: {
68
+ tenantId: input.tenantId,
69
+ ...(input.userId ? { userId: input.userId } : {}),
70
+ threadId: input.threadId,
71
+ },
72
+ ...(signal ? { signal } : {}),
73
+ },
74
+ );
75
+
76
+ return this.finish(input.threadId, input.tenantId, result);
77
+ }
78
+
79
+ async finish(threadId, tenantId, result) {
80
+ const messages = Array.isArray(result.messages) ? result.messages : [];
81
+ const text = lastMessageText(messages);
82
+ const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
83
+
84
+ await this.sessions?.touch({
85
+ threadId,
86
+ tenantId,
87
+ lastMessage: text,
88
+ });
89
+
90
+ return {
91
+ threadId,
92
+ text,
93
+ messages,
94
+ ...(interrupts.length > 0 ? { interrupts } : {}),
95
+ };
96
+ }
97
+
98
+ /** 以状态快照流式输出 Agent 的工作过程(适配 SSE)。 */
99
+ async *stream(input, { signal } = {}) {
100
+ const threadId = input.threadId ?? randomUUID();
101
+
102
+ await this.sessions?.ensure({
103
+ threadId,
104
+ tenantId: input.tenantId,
105
+ ...(input.userId ? { userId: input.userId } : {}),
106
+ });
107
+
108
+ const stream = await this.agent.stream(
109
+ {
110
+ messages: [{ role: "user", content: input.message }],
111
+ tenantId: input.tenantId,
112
+ ...(input.userId ? { userId: input.userId } : {}),
113
+ objective: input.objective ?? input.message,
114
+ },
115
+ {
116
+ configurable: { thread_id: threadId },
117
+ recursionLimit: this.config.agent.recursionLimit,
118
+ streamMode: "values",
119
+ context: {
120
+ tenantId: input.tenantId,
121
+ ...(input.userId ? { userId: input.userId } : {}),
122
+ threadId,
123
+ },
124
+ ...(signal ? { signal } : {}),
125
+ },
126
+ );
127
+
128
+ for await (const chunk of stream) {
129
+ yield { event: "values", data: chunk };
130
+ }
131
+ }
132
+
133
+ async state(threadId) {
134
+ return this.agent.getState({ configurable: { thread_id: threadId } });
135
+ }
136
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * 面向 HTTP 的记忆服务。封装 `MemoryManager`,
3
+ * 让路由层不需要了解命名空间和 store 细节。
4
+ */
5
+ export class MemoryService {
6
+ memory;
7
+
8
+ constructor(memory) {
9
+ this.memory = memory;
10
+ }
11
+
12
+ async remember({ tenantId, userId, key, value, kind = "fact" }) {
13
+ const target = { tenantId, ...(userId ? { userId } : {}) };
14
+
15
+ if (kind === "preference") {
16
+ await this.memory.rememberPreference(target, key, value);
17
+ } else {
18
+ await this.memory.rememberFact(target, key, value);
19
+ }
20
+ }
21
+
22
+ async recall(tenantId, key, userId) {
23
+ return this.memory.recall({ tenantId, ...(userId ? { userId } : {}) }, key);
24
+ }
25
+
26
+ async list(tenantId, userId, limit = 50) {
27
+ return this.memory.list({ tenantId, ...(userId ? { userId } : {}) }, limit);
28
+ }
29
+
30
+ async forget(tenantId, key, userId) {
31
+ await this.memory.forget({ tenantId, ...(userId ? { userId } : {}) }, key);
32
+ }
33
+ }
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ import { NotFoundError } from "../utils/errors.js";
4
+
5
+ /**
6
+ * 会话元数据存放在 LangGraph store 的
7
+ * `["sessions", tenantId, threadId]` 下;对话本身存放在 checkpointer 中。
8
+ * 该服务在 HTTP API 层把两者组合起来。
9
+ */
10
+ export class SessionService {
11
+ graph;
12
+ checkpointer;
13
+ store;
14
+ sandboxes;
15
+
16
+ constructor({ graph, checkpointer, store, sandboxes }) {
17
+ this.graph = graph;
18
+ this.checkpointer = checkpointer;
19
+ this.store = store;
20
+ this.sandboxes = sandboxes;
21
+ }
22
+
23
+ async create(input) {
24
+ const threadId = input.threadId ?? randomUUID();
25
+ const now = new Date().toISOString();
26
+
27
+ const record = {
28
+ threadId,
29
+ title: input.title,
30
+ tenantId: input.tenantId,
31
+ ...(input.userId ? { userId: input.userId } : {}),
32
+ createdAt: now,
33
+ updatedAt: now,
34
+ messageCount: 0,
35
+ metadata: input.metadata,
36
+ };
37
+
38
+ await this.store.put(namespace(input.tenantId), threadId, record);
39
+
40
+ return { ...record };
41
+ }
42
+
43
+ /** 会话记录不存在时创建(幂等)。 */
44
+ async ensure({ threadId, tenantId, userId }) {
45
+ const existing = await this.store.get(namespace(tenantId), threadId);
46
+ if (existing) return;
47
+
48
+ await this.create({
49
+ threadId,
50
+ tenantId,
51
+ title: `Session ${threadId.slice(0, 8)}`,
52
+ metadata: {},
53
+ ...(userId ? { userId } : {}),
54
+ });
55
+ }
56
+
57
+ async touch({ threadId, tenantId, lastMessage }) {
58
+ const item = await this.store.get(namespace(tenantId), threadId);
59
+ if (!item) return;
60
+
61
+ const record = item.value;
62
+
63
+ await this.store.put(namespace(tenantId), threadId, {
64
+ ...record,
65
+ updatedAt: new Date().toISOString(),
66
+ messageCount: record.messageCount + 2,
67
+ ...(lastMessage ? { lastMessage: lastMessage.slice(0, 1_000) } : {}),
68
+ });
69
+ }
70
+
71
+ async get(threadId, tenantId = "default") {
72
+ const item = await this.store.get(namespace(tenantId), threadId);
73
+ if (!item) {
74
+ throw new NotFoundError(`未找到会话 "${threadId}"。`);
75
+ }
76
+
77
+ const record = item.value;
78
+
79
+ const state = await this.graph.getState({
80
+ configurable: { thread_id: threadId },
81
+ });
82
+ const values = state.values;
83
+
84
+ return {
85
+ ...record,
86
+ messageCount: values?.messages?.length ?? record.messageCount,
87
+ };
88
+ }
89
+
90
+ async list(tenantId = "default", limit = 20) {
91
+ const items = await this.store.search(namespace(tenantId), { limit });
92
+
93
+ const sessions = items.map(({ value }) => ({
94
+ ...value,
95
+ }));
96
+
97
+ return { sessions, total: sessions.length };
98
+ }
99
+
100
+ async remove(threadId, tenantId = "default") {
101
+ await this.checkpointer.deleteThread(threadId);
102
+ await this.store.delete(namespace(tenantId), threadId);
103
+ await this.sandboxes?.release(threadId);
104
+ }
105
+
106
+ async history(threadId) {
107
+ const state = await this.graph.getState({
108
+ configurable: { thread_id: threadId },
109
+ });
110
+ const values = state.values;
111
+
112
+ return values?.messages ?? [];
113
+ }
114
+ }
115
+
116
+ const namespace = (tenantId) => {
117
+ return ["sessions", tenantId];
118
+ };
@@ -0,0 +1,21 @@
1
+ import { discoverSkills } from "./loader.js";
2
+
3
+ export { discoverSkills, parseSkillFrontmatter } from "./loader.js";
4
+
5
+ /** Deep Agents skills 中间件扫描的虚拟后端路径。 */
6
+ export const DEFAULT_SKILL_SOURCES = ["/skills/"];
7
+
8
+ /** 从磁盘发现技能(用于启动校验和 `scripts/check`)。 */
9
+ export const loadSkills = async ({ rootDir }) => {
10
+ return discoverSkills(rootDir);
11
+ };
12
+
13
+ /**
14
+ * 为缺少 description 的技能返回可读警告。
15
+ * 模型正是依赖 description 来选择技能。
16
+ */
17
+ export const validateSkills = (skills) => {
18
+ return skills
19
+ .filter((skill) => skill.description.trim().length === 0)
20
+ .map((skill) => `技能 "${skill.name}" 缺少 description(${skill.file})`);
21
+ };
@@ -0,0 +1,75 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ /** 不依赖 YAML 库,解析 SKILL.md 的 frontmatter。 */
5
+ export const parseSkillFrontmatter = (content) => {
6
+ if (!content.startsWith("---")) return {};
7
+
8
+ const end = content.indexOf("\n---", 3);
9
+ if (end === -1) return {};
10
+
11
+ const frontmatter = content.slice(3, end);
12
+ const fields = {};
13
+
14
+ for (const line of frontmatter.split("\n")) {
15
+ const separator = line.indexOf(":");
16
+ if (separator === -1) continue;
17
+
18
+ const key = line.slice(0, separator).trim();
19
+ const value = line
20
+ .slice(separator + 1)
21
+ .trim()
22
+ .replace(/^["']|["']$/g, "");
23
+
24
+ if (key) fields[key] = value;
25
+ }
26
+
27
+ return {
28
+ ...(fields.name ? { name: fields.name } : {}),
29
+ ...(fields.description ? { description: fields.description } : {}),
30
+ };
31
+ };
32
+
33
+ /** 读取目录;目录不存在时返回空数组。 */
34
+ const readDirectory = (directory) => {
35
+ return fs.readdir(directory, { withFileTypes: true }).catch((error) => {
36
+ if (error.code === "ENOENT") return [];
37
+ throw error;
38
+ });
39
+ };
40
+
41
+ /** 读取文本文件;文件不存在时返回 null。 */
42
+ const readTextFile = (file) => {
43
+ return fs.readFile(file, "utf8").catch((error) => {
44
+ if (error.code === "ENOENT") return null;
45
+ throw error;
46
+ });
47
+ };
48
+
49
+ /**
50
+ * 扫描 `rootDir` 下包含 SKILL.md 的子目录。
51
+ * 目录不存在时返回空数组,保证没有技能时也能启动。
52
+ */
53
+ export const discoverSkills = async (rootDir) => {
54
+ const entries = await readDirectory(rootDir);
55
+ const skills = [];
56
+
57
+ for (const entry of entries) {
58
+ if (!entry.isDirectory()) continue;
59
+
60
+ const directory = path.join(rootDir, entry.name);
61
+ const file = path.join(directory, "SKILL.md");
62
+ const content = await readTextFile(file);
63
+ if (content === null) continue;
64
+
65
+ const metadata = parseSkillFrontmatter(content);
66
+ skills.push({
67
+ name: metadata.name ?? entry.name,
68
+ description: metadata.description ?? "",
69
+ directory,
70
+ file,
71
+ });
72
+ }
73
+
74
+ return skills.sort((a, b) => a.name.localeCompare(b.name));
75
+ };