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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +218 -2
  3. package/bin/create-deepagent-server.js +27 -0
  4. package/package.json +50 -4
  5. package/src/args.js +193 -0
  6. package/src/cli.js +269 -0
  7. package/src/dependencies.js +34 -0
  8. package/src/prompts.js +85 -0
  9. package/src/registry.js +68 -0
  10. package/src/scaffold.js +182 -0
  11. package/src/setup.js +77 -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 +74 -0
  17. package/templates/deepagent/js/scripts/dev.js +31 -0
  18. package/templates/deepagent/js/src/agents/factory.js +10 -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 +44 -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/subagents/researcher.md +16 -0
  25. package/templates/deepagent/js/src/agents/prompts/supervisor.js +17 -0
  26. package/templates/deepagent/js/src/agents/prompts/supervisor.md +42 -0
  27. package/templates/deepagent/js/src/agents/state/index.js +1 -0
  28. package/templates/deepagent/js/src/agents/state/types.js +10 -0
  29. package/templates/deepagent/js/src/agents/subagents/analyst.js +11 -0
  30. package/templates/deepagent/js/src/agents/subagents/coder.js +11 -0
  31. package/templates/deepagent/js/src/agents/subagents/index.js +8 -0
  32. package/templates/deepagent/js/src/agents/subagents/researcher.js +12 -0
  33. package/templates/deepagent/js/src/agents/supervisor.js +56 -0
  34. package/templates/deepagent/js/src/api/app.js +22 -0
  35. package/templates/deepagent/js/src/api/middleware/auth.js +27 -0
  36. package/templates/deepagent/js/src/api/middleware/error.js +26 -0
  37. package/templates/deepagent/js/src/api/routes/agent.js +73 -0
  38. package/templates/deepagent/js/src/api/routes/health.js +31 -0
  39. package/templates/deepagent/js/src/api/routes/session.js +62 -0
  40. package/templates/deepagent/js/src/app.js +79 -0
  41. package/templates/deepagent/js/src/backends/composite.js +20 -0
  42. package/templates/deepagent/js/src/backends/filesystem.js +8 -0
  43. package/templates/deepagent/js/src/backends/index.js +28 -0
  44. package/templates/deepagent/js/src/backends/sandbox.js +23 -0
  45. package/templates/deepagent/js/src/config/agent.js +13 -0
  46. package/templates/deepagent/js/src/config/env.js +73 -0
  47. package/templates/deepagent/js/src/config/index.js +35 -0
  48. package/templates/deepagent/js/src/config/model.js +34 -0
  49. package/templates/deepagent/js/src/graph/checkpointer.js +20 -0
  50. package/templates/deepagent/js/src/graph/compile.js +8 -0
  51. package/templates/deepagent/js/src/graph/index.js +3 -0
  52. package/templates/deepagent/js/src/graph/store.js +20 -0
  53. package/templates/deepagent/js/src/index.js +32 -0
  54. package/templates/deepagent/js/src/infrastructure/database/client.js +43 -0
  55. package/templates/deepagent/js/src/infrastructure/database/migrations/001_init.sql +20 -0
  56. package/templates/deepagent/js/src/infrastructure/logger/index.js +19 -0
  57. package/templates/deepagent/js/src/infrastructure/redis/client.js +45 -0
  58. package/templates/deepagent/js/src/infrastructure/shutdown/index.js +51 -0
  59. package/templates/deepagent/js/src/memory/index.js +6 -0
  60. package/templates/deepagent/js/src/memory/manager.js +39 -0
  61. package/templates/deepagent/js/src/memory/store.js +36 -0
  62. package/templates/deepagent/js/src/middleware/approval.js +42 -0
  63. package/templates/deepagent/js/src/middleware/context.js +30 -0
  64. package/templates/deepagent/js/src/middleware/index.js +9 -0
  65. package/templates/deepagent/js/src/middleware/logging.js +66 -0
  66. package/templates/deepagent/js/src/middleware/security.js +51 -0
  67. package/templates/deepagent/js/src/schemas/agent.js +33 -0
  68. package/templates/deepagent/js/src/schemas/common.js +19 -0
  69. package/templates/deepagent/js/src/schemas/locale.js +3 -0
  70. package/templates/deepagent/js/src/schemas/session.js +23 -0
  71. package/templates/deepagent/js/src/services/agent.service.js +117 -0
  72. package/templates/deepagent/js/src/services/memory.service.js +27 -0
  73. package/templates/deepagent/js/src/services/session.service.js +92 -0
  74. package/templates/deepagent/js/src/skills/index.js +17 -0
  75. package/templates/deepagent/js/src/skills/loader.js +65 -0
  76. package/templates/deepagent/js/src/tools/database/index.js +1 -0
  77. package/templates/deepagent/js/src/tools/database/query.js +62 -0
  78. package/templates/deepagent/js/src/tools/filesystem/index.js +86 -0
  79. package/templates/deepagent/js/src/tools/index.js +30 -0
  80. package/templates/deepagent/js/src/tools/mcp/client.js +35 -0
  81. package/templates/deepagent/js/src/tools/mcp/connections.js +54 -0
  82. package/templates/deepagent/js/src/tools/mcp/index.js +8 -0
  83. package/templates/deepagent/js/src/tools/mcp/registry.js +32 -0
  84. package/templates/deepagent/js/src/tools/search/index.js +1 -0
  85. package/templates/deepagent/js/src/tools/search/web-search.js +54 -0
  86. package/templates/deepagent/js/src/utils/errors.js +64 -0
  87. package/templates/deepagent/js/src/utils/helpers.js +42 -0
  88. package/templates/deepagent/js/tests/agents/prompts.test.js +24 -0
  89. package/templates/deepagent/js/tests/agents/supervisor.test.js +34 -0
  90. package/templates/deepagent/js/tests/integration/api.test.js +99 -0
  91. package/templates/deepagent/js/tests/middleware/security.test.js +24 -0
  92. package/templates/deepagent/js/tests/tools/query.test.js +23 -0
  93. package/templates/deepagent/shared/README.md +162 -0
  94. package/templates/deepagent/shared/_editorconfig +12 -0
  95. package/templates/deepagent/shared/_env.example +56 -0
  96. package/templates/deepagent/shared/_gitignore +22 -0
  97. package/templates/deepagent/shared/deployment/docker-compose.yml +56 -0
  98. package/templates/deepagent/shared/resources/AGENTS.md +32 -0
  99. package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
  100. package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
  101. package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
  102. package/templates/deepagent/shared/skills/research/SKILL.md +31 -0
  103. package/templates/deepagent/shared/workspaces/README.md +5 -0
  104. package/templates/deepagent/ts/deployment/Dockerfile +25 -0
  105. package/templates/deepagent/ts/scripts/check.ts +91 -0
  106. package/templates/deepagent/ts/scripts/copy-assets.ts +35 -0
  107. package/templates/deepagent/ts/scripts/dev.ts +40 -0
  108. package/templates/deepagent/ts/src/agents/factory.ts +11 -0
  109. package/templates/deepagent/ts/src/agents/index.ts +4 -0
  110. package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
  111. package/templates/deepagent/ts/src/agents/prompts/loader.ts +52 -0
  112. package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
  113. package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
  114. package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +16 -0
  115. package/templates/deepagent/ts/src/agents/prompts/supervisor.md +42 -0
  116. package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
  117. package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
  118. package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
  119. package/templates/deepagent/ts/src/agents/subagents/analyst.ts +14 -0
  120. package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
  121. package/templates/deepagent/ts/src/agents/subagents/index.ts +10 -0
  122. package/templates/deepagent/ts/src/agents/subagents/researcher.ts +15 -0
  123. package/templates/deepagent/ts/src/agents/supervisor.ts +80 -0
  124. package/templates/deepagent/ts/src/api/app.ts +48 -0
  125. package/templates/deepagent/ts/src/api/middleware/auth.ts +37 -0
  126. package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
  127. package/templates/deepagent/ts/src/api/routes/agent.ts +93 -0
  128. package/templates/deepagent/ts/src/api/routes/health.ts +45 -0
  129. package/templates/deepagent/ts/src/api/routes/session.ts +77 -0
  130. package/templates/deepagent/ts/src/app.ts +104 -0
  131. package/templates/deepagent/ts/src/backends/composite.ts +34 -0
  132. package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
  133. package/templates/deepagent/ts/src/backends/index.ts +42 -0
  134. package/templates/deepagent/ts/src/backends/sandbox.ts +32 -0
  135. package/templates/deepagent/ts/src/config/agent.ts +37 -0
  136. package/templates/deepagent/ts/src/config/env.ts +102 -0
  137. package/templates/deepagent/ts/src/config/index.ts +76 -0
  138. package/templates/deepagent/ts/src/config/model.ts +49 -0
  139. package/templates/deepagent/ts/src/graph/checkpointer.ts +26 -0
  140. package/templates/deepagent/ts/src/graph/compile.ts +15 -0
  141. package/templates/deepagent/ts/src/graph/index.ts +3 -0
  142. package/templates/deepagent/ts/src/graph/store.ts +26 -0
  143. package/templates/deepagent/ts/src/index.ts +39 -0
  144. package/templates/deepagent/ts/src/infrastructure/database/client.ts +61 -0
  145. package/templates/deepagent/ts/src/infrastructure/database/migrations/001_init.sql +20 -0
  146. package/templates/deepagent/ts/src/infrastructure/logger/index.ts +25 -0
  147. package/templates/deepagent/ts/src/infrastructure/redis/client.ts +64 -0
  148. package/templates/deepagent/ts/src/infrastructure/shutdown/index.ts +85 -0
  149. package/templates/deepagent/ts/src/memory/index.ts +11 -0
  150. package/templates/deepagent/ts/src/memory/manager.ts +74 -0
  151. package/templates/deepagent/ts/src/memory/store.ts +57 -0
  152. package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
  153. package/templates/deepagent/ts/src/middleware/context.ts +37 -0
  154. package/templates/deepagent/ts/src/middleware/index.ts +9 -0
  155. package/templates/deepagent/ts/src/middleware/logging.ts +72 -0
  156. package/templates/deepagent/ts/src/middleware/security.ts +60 -0
  157. package/templates/deepagent/ts/src/schemas/agent.ts +48 -0
  158. package/templates/deepagent/ts/src/schemas/common.ts +26 -0
  159. package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
  160. package/templates/deepagent/ts/src/schemas/session.ts +31 -0
  161. package/templates/deepagent/ts/src/services/agent.service.ts +170 -0
  162. package/templates/deepagent/ts/src/services/memory.service.ts +43 -0
  163. package/templates/deepagent/ts/src/services/session.service.ts +148 -0
  164. package/templates/deepagent/ts/src/skills/index.ts +26 -0
  165. package/templates/deepagent/ts/src/skills/loader.ts +94 -0
  166. package/templates/deepagent/ts/src/tools/database/index.ts +1 -0
  167. package/templates/deepagent/ts/src/tools/database/query.ts +71 -0
  168. package/templates/deepagent/ts/src/tools/filesystem/index.ts +108 -0
  169. package/templates/deepagent/ts/src/tools/index.ts +41 -0
  170. package/templates/deepagent/ts/src/tools/mcp/client.ts +53 -0
  171. package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
  172. package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
  173. package/templates/deepagent/ts/src/tools/mcp/registry.ts +48 -0
  174. package/templates/deepagent/ts/src/tools/search/index.ts +1 -0
  175. package/templates/deepagent/ts/src/tools/search/web-search.ts +82 -0
  176. package/templates/deepagent/ts/src/utils/errors.ts +95 -0
  177. package/templates/deepagent/ts/src/utils/helpers.ts +52 -0
  178. package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
  179. package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
  180. package/templates/deepagent/ts/tests/integration/api.test.ts +123 -0
  181. package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
  182. package/templates/deepagent/ts/tests/tools/query.test.ts +27 -0
  183. package/templates/deepagent/ts/tsconfig.json +19 -0
package/src/cli.js ADDED
@@ -0,0 +1,269 @@
1
+ import path from "node:path";
2
+
3
+ import { HELP_TEXT, PACKAGE_MANAGERS, UsageError, parseArgs } from "./args.js";
4
+ import { packagesFor } from "./dependencies.js";
5
+ import { createPrompter, isInteractive } from "./prompts.js";
6
+ import { bundledVersions, resolveVersions } from "./registry.js";
7
+ import { ensureEmptyTarget, scaffold } from "./scaffold.js";
8
+ import {
9
+ detectPackageManager,
10
+ initGit,
11
+ installCommandText,
12
+ runInstall,
13
+ runScriptText,
14
+ } from "./setup.js";
15
+ import { banner, blank, bold, dim, green, info, step, success, warn } from "./ui.js";
16
+ import { VERSION } from "./version.js";
17
+
18
+ export const toPackageName = (input) => {
19
+ const name = String(input)
20
+ .trim()
21
+ .toLowerCase()
22
+ .replace(/[^a-z0-9._~-]+/g, "-")
23
+ .replace(/^[._-]+|[._-]+$/g, "")
24
+ .replace(/[._-]{2,}/g, "-")
25
+ .slice(0, 214);
26
+
27
+ if (!name) {
28
+ throw new UsageError(`无法从 "${input}" 推导出合法的包名。请使用包含字母或数字的项目名。`);
29
+ }
30
+
31
+ return name;
32
+ };
33
+
34
+ const quote = (value) => {
35
+ return /\s/.test(value) ? JSON.stringify(value) : value;
36
+ };
37
+
38
+ const displayPath = (targetDir, cwd = process.cwd()) => {
39
+ const relative = path.relative(cwd, targetDir);
40
+ return relative === "" ? "." : relative;
41
+ };
42
+
43
+ const printNextSteps = ({ targetDir, cwd, packageManager, installed, language }) => {
44
+ const relative = displayPath(targetDir, cwd);
45
+
46
+ blank();
47
+ console.log(
48
+ `${green("完成!")} 你的 Deep Agents 项目${language === "ts" ? "(TypeScript)" : ""}已就绪。`,
49
+ );
50
+ blank();
51
+ console.log(bold("接下来:"));
52
+
53
+ if (relative !== ".") {
54
+ console.log(` cd ${quote(relative)}`);
55
+ }
56
+
57
+ if (!installed) {
58
+ console.log(` ${installCommandText(packageManager)}`);
59
+ }
60
+
61
+ const copyEnvCommand =
62
+ process.platform === "win32" ? "copy .env.example .env" : "cp .env.example .env";
63
+
64
+ console.log(` ${copyEnvCommand} ${dim("# 填入 OPENAI_API_KEY 或 ANTHROPIC_API_KEY")}`);
65
+ console.log(` ${runScriptText(packageManager, "check")} ${dim("# 可选:环境预检")}`);
66
+ console.log(
67
+ ` ${runScriptText(packageManager, "dev")} ${dim("# http://localhost:3000/health")}`,
68
+ );
69
+ console.log(` ${runScriptText(packageManager, "agent")} ${dim("# 交互式终端会话")}`);
70
+
71
+ blank();
72
+ console.log(
73
+ dim(
74
+ "API 提供 POST /api/agents/invoke、POST /api/agents/stream、POST /api/agents/resume 以及会话接口。",
75
+ ),
76
+ );
77
+ console.log(dim("文档:https://docs.langchain.com/oss/javascript/deepagents/overview"));
78
+ blank();
79
+ };
80
+
81
+ const chooseVersions = async (packages, useLatest) => {
82
+ if (!useLatest) {
83
+ step("使用 CLI 内置版本(--no-latest)。");
84
+ return bundledVersions(packages);
85
+ }
86
+
87
+ step("正在从 npm 解析最新的 Deep Agents 依赖版本…");
88
+ const { versions, usedFallback } = await resolveVersions(packages);
89
+
90
+ if (usedFallback.length > 0) {
91
+ warn(`无法从 npm registry 获取 ${usedFallback.join("、")} 的最新版本,改用内置版本。`);
92
+ } else {
93
+ success("已解析最新发布版本。");
94
+ }
95
+
96
+ const headline = ["deepagents", "@langchain/core", "@langchain/langgraph"]
97
+ .map((name) => `${name} ${dim(versions[name])}`)
98
+ .join(dim(" · "));
99
+ info(headline);
100
+
101
+ return versions;
102
+ };
103
+
104
+ /**
105
+ * CLI 主流程,返回进程退出码。
106
+ */
107
+ export const main = async (argv = process.argv.slice(2)) => {
108
+ const { options, positionals } = parseArgs(argv);
109
+
110
+ if (options.help) {
111
+ console.log(HELP_TEXT);
112
+ return 0;
113
+ }
114
+
115
+ if (options.version) {
116
+ console.log(VERSION);
117
+ return 0;
118
+ }
119
+
120
+ const cwd = process.cwd();
121
+ const interactive = isInteractive() && !options.yes;
122
+ const prompter = interactive ? createPrompter() : null;
123
+
124
+ try {
125
+ banner("create-deepagent-server", VERSION);
126
+
127
+ let projectArgument = positionals[0];
128
+
129
+ if (!projectArgument) {
130
+ if (!interactive) {
131
+ throw new UsageError(
132
+ [
133
+ "缺少项目名。",
134
+ "用法:create-deepagent-server <项目名> [选项]",
135
+ '运行 "create-deepagent-server --help" 查看详情。',
136
+ ].join("\n"),
137
+ );
138
+ }
139
+
140
+ projectArgument = await prompter.text("项目目录", {
141
+ defaultValue: "my-deepagent",
142
+ });
143
+ }
144
+
145
+ const targetDir = path.resolve(cwd, projectArgument);
146
+ const looksLikePath =
147
+ projectArgument === "." ||
148
+ projectArgument.includes("/") ||
149
+ projectArgument.includes(path.sep);
150
+ const packageSource = looksLikePath ? path.basename(targetDir) : projectArgument;
151
+ const packageName = toPackageName(packageSource);
152
+
153
+ // 先校验目标目录,避免用户答完所有问题后才失败。
154
+ await ensureEmptyTarget(targetDir, { force: options.force });
155
+
156
+ const language =
157
+ options.language ??
158
+ (interactive
159
+ ? await prompter.select(
160
+ "项目语言",
161
+ [
162
+ {
163
+ label: "JavaScript",
164
+ value: "js",
165
+ hint: "推荐",
166
+ },
167
+ {
168
+ label: "TypeScript",
169
+ value: "ts",
170
+ hint: "类型检查",
171
+ },
172
+ ],
173
+ { defaultIndex: 0 },
174
+ )
175
+ : "js");
176
+
177
+ const detected = detectPackageManager({ cwd });
178
+ const packageManager =
179
+ options.pm ??
180
+ (interactive
181
+ ? await prompter.select(
182
+ "包管理器",
183
+ PACKAGE_MANAGERS.map((name) => ({
184
+ label: name,
185
+ value: name,
186
+ hint: name === detected ? "已检测" : undefined,
187
+ })),
188
+ {
189
+ defaultIndex: Math.max(0, PACKAGE_MANAGERS.indexOf(detected)),
190
+ },
191
+ )
192
+ : detected);
193
+
194
+ const install =
195
+ options.install ??
196
+ (interactive
197
+ ? await prompter.confirm("是否立即安装依赖?", {
198
+ defaultValue: true,
199
+ })
200
+ : true);
201
+
202
+ const git =
203
+ options.git ??
204
+ (interactive
205
+ ? await prompter.confirm("是否初始化 Git 仓库?", {
206
+ defaultValue: true,
207
+ })
208
+ : true);
209
+
210
+ prompter?.close();
211
+
212
+ const packages = packagesFor(language);
213
+ const versions = await chooseVersions(packages, options.latest);
214
+
215
+ step(
216
+ `正在生成 ${bold(packageName)}(${
217
+ language === "ts" ? "TypeScript" : "JavaScript"
218
+ })到 ${displayPath(targetDir, cwd)}…`,
219
+ );
220
+
221
+ const { files } = await scaffold({
222
+ targetDir,
223
+ packageName,
224
+ language,
225
+ template: options.template,
226
+ versions,
227
+ force: options.force,
228
+ });
229
+
230
+ success(`已创建 ${files.length} 个文件。`);
231
+
232
+ let installed = false;
233
+ if (install) {
234
+ step(`正在使用 ${packageManager} 安装依赖…`);
235
+ try {
236
+ runInstall(packageManager, targetDir);
237
+ installed = true;
238
+ success("依赖安装完成。");
239
+ } catch (error) {
240
+ warn(`依赖安装失败:${error.message}`);
241
+ warn(`请在项目目录中运行 "${installCommandText(packageManager)}" 重试。`);
242
+ }
243
+ } else {
244
+ info("已跳过依赖安装(--no-install)。");
245
+ }
246
+
247
+ if (git) {
248
+ if (initGit(targetDir)) {
249
+ success("已初始化 Git 仓库。");
250
+ } else {
251
+ warn("无法初始化 Git 仓库(请确认已安装 git)。");
252
+ }
253
+ } else {
254
+ info("已跳过 Git 初始化(--no-git)。");
255
+ }
256
+
257
+ printNextSteps({
258
+ targetDir,
259
+ cwd,
260
+ packageManager,
261
+ installed,
262
+ language,
263
+ });
264
+
265
+ return 0;
266
+ } finally {
267
+ prompter?.close();
268
+ }
269
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * 每个生成项目都会安装的依赖。
3
+ * 版本在生成项目时从 npm 解析,保证模板始终使用当前发布版本。
4
+ */
5
+ export const RUNTIME_PACKAGES = [
6
+ "@langchain/anthropic",
7
+ "@langchain/core",
8
+ "@langchain/langgraph",
9
+ "@langchain/langgraph-checkpoint",
10
+ "@langchain/langgraph-checkpoint-postgres",
11
+ "@langchain/mcp-adapters",
12
+ "@langchain/openai",
13
+ "deepagents",
14
+ "dotenv",
15
+ "express",
16
+ "ioredis",
17
+ "langchain",
18
+ "pg",
19
+ "pino",
20
+ "pino-pretty",
21
+ "zod",
22
+ ];
23
+
24
+ export const TYPESCRIPT_PACKAGES = [
25
+ "typescript",
26
+ "tsx",
27
+ "@types/node",
28
+ "@types/express",
29
+ "@types/pg",
30
+ ];
31
+
32
+ export const packagesFor = (language) => {
33
+ return language === "ts" ? [...RUNTIME_PACKAGES, ...TYPESCRIPT_PACKAGES] : RUNTIME_PACKAGES;
34
+ };
package/src/prompts.js ADDED
@@ -0,0 +1,85 @@
1
+ import { stdin, stdout } from "node:process";
2
+ import { createInterface } from "node:readline/promises";
3
+
4
+ import { cyan, dim, warn } from "./ui.js";
5
+
6
+ export const isInteractive = () => {
7
+ return Boolean(stdin.isTTY) && Boolean(stdout.isTTY);
8
+ };
9
+
10
+ /**
11
+ * 不依赖第三方库的交互提示。使用数字菜单而不是方向键选择,
12
+ * 这样在任何终端(包括 SSH)中都能正常使用。
13
+ */
14
+ export const createPrompter = ({ input = stdin, output = stdout } = {}) => {
15
+ const rl = createInterface({ input, output });
16
+ let closed = false;
17
+
18
+ const ask = async (question) => (await rl.question(question)).trim();
19
+
20
+ return {
21
+ text: async (message, { defaultValue = "", validate } = {}) => {
22
+ const suffix = defaultValue ? dim(` (${defaultValue})`) : "";
23
+
24
+ for (;;) {
25
+ const answer = await ask(`${cyan("?")} ${message}${suffix} `);
26
+ const value = answer || defaultValue;
27
+
28
+ if (!value) {
29
+ warn("此项不能为空。");
30
+ continue;
31
+ }
32
+
33
+ const problem = validate?.(value);
34
+ if (problem) {
35
+ warn(problem);
36
+ continue;
37
+ }
38
+
39
+ return value;
40
+ }
41
+ },
42
+
43
+ select: async (message, options, { defaultIndex = 0 } = {}) => {
44
+ console.log(`${cyan("?")} ${message}`);
45
+ options.forEach((option, index) => {
46
+ const pointer = index === defaultIndex ? cyan("❯") : " ";
47
+ const hint = option.hint ? dim(` — ${option.hint}`) : "";
48
+ console.log(` ${pointer} ${index + 1}. ${option.label}${hint}`);
49
+ });
50
+
51
+ for (;;) {
52
+ const answer = await ask(dim(` 请选择 1-${options.length} [${defaultIndex + 1}]:`));
53
+
54
+ if (!answer) return options[defaultIndex].value;
55
+
56
+ const index = Number(answer);
57
+ if (Number.isInteger(index) && index >= 1 && index <= options.length) {
58
+ return options[index - 1].value;
59
+ }
60
+
61
+ warn(`请输入 1 到 ${options.length} 之间的数字。`);
62
+ }
63
+ },
64
+
65
+ confirm: async (message, { defaultValue = true } = {}) => {
66
+ const hint = defaultValue ? "Y/n" : "y/N";
67
+
68
+ for (;;) {
69
+ const answer = (await ask(`${cyan("?")} ${message} ${dim(`(${hint})`)} `)).toLowerCase();
70
+
71
+ if (!answer) return defaultValue;
72
+ if (answer === "y" || answer === "yes") return true;
73
+ if (answer === "n" || answer === "no") return false;
74
+
75
+ warn("请输入 y 或 n。");
76
+ }
77
+ },
78
+
79
+ close: () => {
80
+ if (closed) return;
81
+ closed = true;
82
+ rl.close();
83
+ },
84
+ };
85
+ };
@@ -0,0 +1,68 @@
1
+ import { FALLBACK_VERSIONS } from "./versions.js";
2
+
3
+ const REGISTRY = (
4
+ process.env.DEEPAGENT_CLI_REGISTRY ||
5
+ process.env.npm_config_registry ||
6
+ "https://registry.npmjs.org"
7
+ ).replace(/\/+$/, "");
8
+
9
+ /** 对包名做 URL 编码(作用域中的斜杠必须保留编码)。 */
10
+ const encodePackageName = (name) => {
11
+ return name.replace("/", "%2F");
12
+ };
13
+
14
+ const fetchLatestVersion = async (name, timeoutMs) => {
15
+ const response = await fetch(`${REGISTRY}/${encodePackageName(name)}/latest`, {
16
+ headers: { accept: "application/json" },
17
+ signal: AbortSignal.timeout(timeoutMs),
18
+ });
19
+
20
+ if (!response.ok) {
21
+ throw new Error(`npm registry 返回 HTTP ${response.status}`);
22
+ }
23
+
24
+ const manifest = await response.json();
25
+ if (typeof manifest.version !== "string" || manifest.version.length === 0) {
26
+ throw new Error("registry 响应中缺少 version 字段");
27
+ }
28
+
29
+ return manifest.version;
30
+ };
31
+
32
+ /**
33
+ * 解析每个依赖的最新发布版本。
34
+ * 所有请求并行执行;离线或失败时回退到内置版本。
35
+ */
36
+ export const resolveVersions = async (packages, { timeoutMs = 5000 } = {}) => {
37
+ const resolved = await Promise.all(
38
+ packages.map(async (name) => {
39
+ try {
40
+ return { name, version: await fetchLatestVersion(name, timeoutMs), isFallback: false };
41
+ } catch {
42
+ const fallback = FALLBACK_VERSIONS[name];
43
+ if (!fallback) {
44
+ throw new Error(`无法解析 ${name} 的版本,且没有内置回退版本。`);
45
+ }
46
+ return { name, version: fallback, isFallback: true };
47
+ }
48
+ }),
49
+ );
50
+
51
+ return {
52
+ versions: Object.fromEntries(resolved.map(({ name, version }) => [name, version])),
53
+ usedFallback: resolved.filter(({ isFallback }) => isFallback).map(({ name }) => name),
54
+ };
55
+ };
56
+
57
+ /** 内置版本,在传入 --no-latest 时使用。 */
58
+ export const bundledVersions = (packages) => {
59
+ return Object.fromEntries(
60
+ packages.map((name) => {
61
+ const version = FALLBACK_VERSIONS[name];
62
+ if (!version) {
63
+ throw new Error(`没有为 ${name} 内置回退版本。`);
64
+ }
65
+ return [name, version];
66
+ }),
67
+ );
68
+ };
@@ -0,0 +1,182 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ import { RUNTIME_PACKAGES, TYPESCRIPT_PACKAGES } from "./dependencies.js";
6
+
7
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
8
+ const TEMPLATES_DIR = path.join(HERE, "..", "templates");
9
+
10
+ export const TEMPLATES = ["deepagent"];
11
+
12
+ const TEMPLATE_FILENAMES = new Map([
13
+ ["_gitignore", ".gitignore"],
14
+ ["_env.example", ".env.example"],
15
+ ["_editorconfig", ".editorconfig"],
16
+ ]);
17
+
18
+ const mapTemplateFilename = (name) => {
19
+ return TEMPLATE_FILENAMES.get(name) ?? name;
20
+ };
21
+
22
+ const walk = async (directory, prefix = "") => {
23
+ const entries = await fs.readdir(directory, { withFileTypes: true });
24
+
25
+ const nested = await Promise.all(
26
+ entries.map(async (entry) => {
27
+ const relativePath = prefix ? path.join(prefix, entry.name) : entry.name;
28
+
29
+ if (entry.isDirectory()) {
30
+ return walk(path.join(directory, entry.name), relativePath);
31
+ }
32
+
33
+ return entry.isFile() ? [relativePath] : [];
34
+ }),
35
+ );
36
+
37
+ return nested.flat();
38
+ };
39
+
40
+ export const ensureEmptyTarget = async (targetDir, { force = false } = {}) => {
41
+ let stats;
42
+
43
+ try {
44
+ stats = await fs.stat(targetDir);
45
+ } catch (error) {
46
+ if (error.code === "ENOENT") return;
47
+ throw error;
48
+ }
49
+
50
+ if (!stats.isDirectory()) {
51
+ throw new Error(`目标路径不是目录:${targetDir}`);
52
+ }
53
+
54
+ const entries = await fs.readdir(targetDir);
55
+ if (entries.length > 0 && !force) {
56
+ throw new Error(`目标目录非空:${targetDir}\n如需继续写入,请添加 --force。`);
57
+ }
58
+ };
59
+
60
+ const assertVersions = (versions, language) => {
61
+ const required = [...RUNTIME_PACKAGES, ...(language === "ts" ? TYPESCRIPT_PACKAGES : [])];
62
+ const missing = required.filter((name) => !versions?.[name]);
63
+
64
+ if (missing.length > 0) {
65
+ throw new Error(`缺少依赖 ${missing.join("、")} 的版本信息。`);
66
+ }
67
+ };
68
+
69
+ const TYPESCRIPT_SCRIPTS = {
70
+ dev: "tsx watch src/index.ts",
71
+ build: "tsc -p tsconfig.json && tsx scripts/copy-assets.ts",
72
+ start: "node dist/index.js",
73
+ agent: "tsx scripts/dev.ts",
74
+ check: "tsx scripts/check.ts",
75
+ typecheck: "tsc --noEmit",
76
+ test: 'node --import tsx --test "tests/**/*.test.ts"',
77
+ };
78
+
79
+ const JAVASCRIPT_SCRIPTS = {
80
+ dev: "node --watch src/index.js",
81
+ start: "node src/index.js",
82
+ agent: "node scripts/dev.js",
83
+ check: "node scripts/check.js",
84
+ test: 'node --test "tests/**/*.test.js"',
85
+ };
86
+
87
+ export const buildPackageJson = ({ packageName, language, versions }) => {
88
+ const dependencies = Object.fromEntries(
89
+ RUNTIME_PACKAGES.map((name) => [name, `^${versions[name]}`]),
90
+ );
91
+
92
+ const typescriptDependencies = Object.fromEntries(
93
+ TYPESCRIPT_PACKAGES.map((name) => [name, `^${versions[name]}`]),
94
+ );
95
+
96
+ const devDependencies = language === "ts" ? typescriptDependencies : {};
97
+
98
+ const scripts = language === "ts" ? TYPESCRIPT_SCRIPTS : JAVASCRIPT_SCRIPTS;
99
+
100
+ const manifest = {
101
+ name: packageName,
102
+ version: "0.1.0",
103
+ private: true,
104
+ type: "module",
105
+ description: `${packageName} —— 由 create-deepagent-server 生成的 Deep Agents 项目。`,
106
+ engines: { node: ">=22.6.0" },
107
+ scripts,
108
+ dependencies,
109
+ ...(language === "ts" ? { devDependencies } : {}),
110
+ };
111
+
112
+ return manifest;
113
+ };
114
+
115
+ /**
116
+ * 根据内置模板生成项目。
117
+ * package.json 由代码生成,确保依赖版本与脚本和所选语言保持一致。
118
+ */
119
+ export const scaffold = async ({
120
+ targetDir,
121
+ packageName,
122
+ language = "js",
123
+ template = "deepagent",
124
+ versions,
125
+ force = false,
126
+ }) => {
127
+ if (!TEMPLATES.includes(template)) {
128
+ throw new Error(`未知模板 "${template}"。可用模板:${TEMPLATES.join("、")}。`);
129
+ }
130
+
131
+ if (language !== "js" && language !== "ts") {
132
+ throw new Error(`不支持的语言:"${language}"。`);
133
+ }
134
+
135
+ if (!packageName) {
136
+ throw new Error("缺少包名。");
137
+ }
138
+
139
+ assertVersions(versions, language);
140
+ await ensureEmptyTarget(targetDir, { force });
141
+
142
+ // 先写入共享文件,再用语言专属文件覆盖同名文件。
143
+ const templateRoot = path.join(TEMPLATES_DIR, template);
144
+
145
+ const entries = await Promise.all(
146
+ [path.join(templateRoot, "shared"), path.join(templateRoot, language)].map(async (directory) =>
147
+ (await walk(directory)).map((relativePath) => {
148
+ const [first, ...rest] = relativePath.split(path.sep);
149
+ return [path.join(mapTemplateFilename(first), ...rest), path.join(directory, relativePath)];
150
+ }),
151
+ ),
152
+ );
153
+
154
+ const fileMap = new Map(entries.flat());
155
+
156
+ const writtenFiles = await Promise.all(
157
+ [...fileMap].map(async ([outputRelativePath, source]) => {
158
+ const destination = path.join(targetDir, outputRelativePath);
159
+ const content = (await fs.readFile(source, "utf8")).replaceAll(
160
+ "__PROJECT_NAME__",
161
+ packageName,
162
+ );
163
+
164
+ await fs.mkdir(path.dirname(destination), { recursive: true });
165
+ await fs.writeFile(destination, content, "utf8");
166
+ return outputRelativePath;
167
+ }),
168
+ );
169
+
170
+ const packageJson = buildPackageJson({ packageName, language, versions });
171
+ await fs.writeFile(
172
+ path.join(targetDir, "package.json"),
173
+ `${JSON.stringify(packageJson, null, 2)}\n`,
174
+ "utf8",
175
+ );
176
+ writtenFiles.push("package.json");
177
+
178
+ return {
179
+ targetDir,
180
+ files: writtenFiles.sort(),
181
+ };
182
+ };