luminae-helper 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib/ui.js ADDED
@@ -0,0 +1,382 @@
1
+ import chalk from "chalk";
2
+ import gradientString from "gradient-string";
3
+ import { select as Select, input, Separator } from "@inquirer/prompts";
4
+ import wcswidth from "wcwidth";
5
+ import checkboxWithActionRows from "./checkbox-with-action-rows.js";
6
+ import { SKILLS, TOOLS, detectInstalledTools } from "./constants.js";
7
+ import { installSkillToTool, uninstallSkillFromTool } from "./installer.js";
8
+
9
+ /**
10
+ * 传给所有 @inquirer prompt 的 context。
11
+ * `clearPromptOnDone: true` 会在 prompt 结束时用 ANSI 擦除整块 TUI 占用的行,
12
+ * 避免默认「只换行」导致旧菜单残留在终端上,与下一屏叠在一起(尤其快速按方向键时)。
13
+ * @type {{ clearPromptOnDone: boolean }}
14
+ */
15
+ const inquirerContext = { clearPromptOnDone: true };
16
+
17
+ /**
18
+ * 在关闭一个 inquirer prompt 之后、再 `printBanner` 或打开下一个 prompt 之前调用。
19
+ * 使用 `setImmediate` 推迟到当前轮询阶段之后,让 readline 的 `close`、MuteStream 的 flush
20
+ * 以及 stdin 里积压的字节先落稳(与 Inquirer.js #1303 讨论的背景一致),降低两屏叠画的概率。
21
+ * @returns {Promise<void>}
22
+ */
23
+ function afterPromptFlush() {
24
+ return new Promise((resolve) => {
25
+ setImmediate(resolve);
26
+ });
27
+ }
28
+
29
+ function printBanner() {
30
+ console.clear();
31
+ const banner = gradientString(["#4facfe", "#a855f7", "#f472b6"])(" LUMINAE HELPER ");
32
+ console.log("\n " + banner);
33
+ console.log(chalk.gray(" AI coding tools skill manager\n"));
34
+ }
35
+
36
+ /**
37
+ * Pad a choice label to a consistent display width so icons don't misalign.
38
+ */
39
+ function padChoice(text, targetWidth = 20) {
40
+ const stripped = text.replace(/\x1b\[[0-9;]*m/g, "");
41
+ const w = wcswidth(stripped);
42
+ const pad = w < 0 ? 0 : Math.max(0, targetWidth - w);
43
+ return text + " ".repeat(pad);
44
+ }
45
+
46
+ /**
47
+ * 解析带功能行的多选结果:`__back__` / `__exit__` 来自「焦点在该行时按回车」的即时提交;
48
+ * 普通 Skill/工具 id 来自多选勾选后回车。若数组中同时含功能值与普通 id,优先按功能处理。
49
+ *
50
+ * @param {unknown} ans
51
+ * @returns {"back"|"exit"|string[]}
52
+ */
53
+ function parseCheckboxResult(ans) {
54
+ if (ans === "exit" || ans === "__exit__") return "exit";
55
+ if (ans === "back" || ans === "__back__") return "back";
56
+ if (ans === "esc_timeout") return "back";
57
+ if (Array.isArray(ans)) {
58
+ if (ans.includes("__exit__")) return "exit";
59
+ if (ans.includes("__back__")) return "back";
60
+ return ans.filter((x) => x !== "__back__" && x !== "__exit__");
61
+ }
62
+ return "back";
63
+ }
64
+
65
+ /**
66
+ * 在列表末尾追加「返回 / 退出」两项(`value` 为 `__back__` / `__exit__`)。
67
+ * 由 `checkbox-with-action-rows` 渲染为功能行:方向键移上去后按回车即触发,空格不会勾选。
68
+ *
69
+ * @param {{ name: string, value: string }[]} items
70
+ * @param {string} backLabel
71
+ */
72
+ function withNavChoices(items, backLabel) {
73
+ return [
74
+ ...items,
75
+ new Separator(),
76
+ { name: chalk.yellow(backLabel), value: "__back__" },
77
+ { name: "✕ 退出", value: "__exit__" },
78
+ ];
79
+ }
80
+
81
+ /**
82
+ * 运行带功能行的多选 Checkbox(见 `checkbox-with-action-rows.js`)。
83
+ * Ctrl+C 时按项目惯例视为退出整段交互。
84
+ *
85
+ * @param {{ message: string, choices: unknown[], loop?: boolean, theme?: object }} config
86
+ * @returns {Promise<string[]>}
87
+ */
88
+ async function runCheckbox(config) {
89
+ return checkboxWithActionRows(config, inquirerContext).catch((err) => {
90
+ if (err?.name === "ExitPromptError") return ["__exit__"];
91
+ return ["__exit__"];
92
+ });
93
+ }
94
+
95
+ // ── Step 1: Select skills (checkbox multi-select) ──
96
+ async function stepSelectSkills() {
97
+ while (true) {
98
+ await afterPromptFlush();
99
+ printBanner();
100
+ console.log(chalk.cyan.bold("━━━ 选择 Skill ━━━\n"));
101
+
102
+ const skillChoices = SKILLS.map(s => ({
103
+ name: s.name + " - " + s.description,
104
+ value: s.id,
105
+ }));
106
+
107
+ const theme = {
108
+ prefix: chalk.cyan("◆"),
109
+ style: { highlight: (t) => chalk.cyan(t) },
110
+ };
111
+
112
+ const ans = await runCheckbox({
113
+ message: " 选择 Skill (空格多选,回车提交;底部「↩ 返回 / ✕ 退出」为功能行:移上去后按回车):",
114
+ choices: withNavChoices(skillChoices, "↩ 返回主菜单"),
115
+ loop: false,
116
+ theme,
117
+ });
118
+
119
+ const result = parseCheckboxResult(ans);
120
+
121
+ if (result === "back") return "back";
122
+ if (result === "exit") return "exit";
123
+
124
+ if (result.length === 0) {
125
+ console.log(chalk.yellow("\n 请至少选择一个 Skill"));
126
+ await new Promise(r => setTimeout(r, 1200));
127
+ continue;
128
+ }
129
+
130
+ return result;
131
+ }
132
+ }
133
+
134
+ // ── Step 2: Select tools (checkbox multi-select) ──
135
+ async function stepSelectTools(installedTools) {
136
+ while (true) {
137
+ await afterPromptFlush();
138
+ printBanner();
139
+ console.log(chalk.cyan.bold("━━━ 选择目标工具 ━━━\n"));
140
+
141
+ const toolChoices = installedTools.map(t => ({
142
+ name: t.name,
143
+ value: t.id,
144
+ }));
145
+
146
+ const theme = {
147
+ prefix: chalk.cyan("◆"),
148
+ style: { highlight: (t) => chalk.cyan(t) },
149
+ };
150
+
151
+ const ans = await runCheckbox({
152
+ message: " 选择工具 (空格多选,回车提交;底部「↩ 返回 / ✕ 退出」为功能行:移上去后按回车):",
153
+ choices: withNavChoices(toolChoices, "↩ 返回上一步"),
154
+ loop: false,
155
+ theme,
156
+ });
157
+
158
+ const result = parseCheckboxResult(ans);
159
+
160
+ if (result === "back") return "back";
161
+ if (result === "exit") return "exit";
162
+
163
+ if (result.length === 0) {
164
+ console.log(chalk.yellow("\n 请至少选择一个工具"));
165
+ await new Promise(r => setTimeout(r, 1200));
166
+ continue;
167
+ }
168
+
169
+ return result;
170
+ }
171
+ }
172
+
173
+ /**
174
+ * 将步骤间传递的 id 列表规范为 string[],避免竞态/异常路径传入非数组导致 .map 报错。
175
+ * @param {unknown} v
176
+ * @returns {string[]}
177
+ */
178
+ function asIdArray(v) {
179
+ if (!Array.isArray(v)) return [];
180
+ return v.filter((x) => typeof x === "string");
181
+ }
182
+
183
+ // ── Step 3: Preview + Confirm (Select with navigation) ──
184
+ async function stepPreviewConfirm(skillIds, toolIds, installedTools, isUninstall) {
185
+ const sids = asIdArray(skillIds);
186
+ const tids = asIdArray(toolIds);
187
+ await afterPromptFlush();
188
+ printBanner();
189
+ const actionLabel = isUninstall ? "卸载" : "安装";
190
+ console.log(chalk.cyan.bold("━━━ " + actionLabel + "预览 ━━━\n"));
191
+ const skillNames = sids.map(id => SKILLS.find(s => s.id === id)?.name).join(", ");
192
+ const toolNames = tids.map(id => installedTools.find(t => t.id === id)?.name).join(", ");
193
+ console.log(" " + chalk.bold("Skill:") + " " + skillNames);
194
+ console.log(" " + chalk.bold("工具:") + " " + toolNames);
195
+ console.log();
196
+
197
+ const ans = await Select(
198
+ {
199
+ message: " 确认" + actionLabel + "?",
200
+ choices: [
201
+ { name: "✓ 确认" + actionLabel, value: "confirm" },
202
+ { name: "↩ 返回上一步", value: "back" },
203
+ { name: "✕ 退出", value: "exit" },
204
+ ],
205
+ theme: { prefix: chalk.cyan("◆"), style: { highlight: (t) => chalk.cyan(t) } },
206
+ },
207
+ inquirerContext
208
+ ).catch(() => "back");
209
+
210
+ return ans;
211
+ }
212
+
213
+ // ── Step 4: Execute ──
214
+ async function stepExecute(skillIds, toolIds, installedTools, isUninstall) {
215
+ const sids = asIdArray(skillIds);
216
+ const tids = asIdArray(toolIds);
217
+ await afterPromptFlush();
218
+ printBanner();
219
+ console.log();
220
+ console.log(chalk.cyan.bold("━━━ 执行中 ━━━\n"));
221
+
222
+ let allSuccess = true;
223
+
224
+ for (const toolId of tids) {
225
+ const tool = TOOLS.find(t => t.id === toolId);
226
+ if (!tool) continue;
227
+
228
+ for (const skillId of sids) {
229
+ const skill = SKILLS.find(s => s.id === skillId);
230
+ if (!skill) continue;
231
+
232
+ const supported = skill.installTargets?.some(tgt => tgt.toolId === toolId);
233
+ if (!supported) {
234
+ console.log(chalk.gray(" - " + skill.name + " × " + tool.name + " (不支持)"));
235
+ continue;
236
+ }
237
+
238
+ if (isUninstall) {
239
+ const result = uninstallSkillFromTool(skill, tool);
240
+ if (result.success) {
241
+ console.log(chalk.green(" ✓ " + skill.name + " ✓ " + tool.name));
242
+ } else {
243
+ console.log(chalk.yellow(" - " + skill.name + " - " + tool.name + " (未安装)"));
244
+ }
245
+ } else {
246
+ const result = installSkillToTool(skill, tool);
247
+ if (result.success) {
248
+ console.log(chalk.green(" ✓ " + skill.name + " → " + tool.name));
249
+ } else {
250
+ console.log(chalk.red(" ✗ " + skill.name + " → " + tool.name + ": " + result.message));
251
+ allSuccess = false;
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ console.log();
258
+ if (allSuccess) {
259
+ console.log(chalk.green(" ✅ 操作完成!\n"));
260
+ } else {
261
+ console.log(chalk.yellow(" ⚠ 部分操作失败,请检查错误信息。\n"));
262
+ }
263
+
264
+ return allSuccess;
265
+ }
266
+
267
+ // ── Unified flow (install / uninstall) ──
268
+ async function runFlow(isUninstall) {
269
+ const installedTools = detectInstalledTools().filter(t => t.installed);
270
+ if (installedTools.length === 0) {
271
+ await afterPromptFlush();
272
+ printBanner();
273
+ console.log(chalk.yellow("\n ⚠ 未检测到任何已安装的 AI 工具\n"));
274
+ console.log(chalk.gray(" 请先安装以下工具之一:\n"));
275
+ TOOLS.forEach(t => {
276
+ console.log(" " + chalk.cyan(t.name) + ": " + chalk.gray(t.installHint));
277
+ });
278
+ console.log();
279
+ await input(
280
+ {
281
+ message: " 按回车返回主菜单...",
282
+ theme: { prefix: chalk.cyan("◆"), style: { highlight: (t) => chalk.cyan(t) } },
283
+ },
284
+ inquirerContext
285
+ ).catch(() => {});
286
+ return "back";
287
+ }
288
+
289
+ let step = 1;
290
+ let selectedSkillIds = null;
291
+ let selectedToolIds = null;
292
+
293
+ while (true) {
294
+ if (step === 1) {
295
+ const result = await stepSelectSkills();
296
+ if (result === "back") return "back";
297
+ if (result === "exit") return "exit";
298
+ selectedSkillIds = result;
299
+ step = 2;
300
+ } else if (step === 2) {
301
+ const result = await stepSelectTools(installedTools);
302
+ if (result === "back") { step = 1; continue; }
303
+ if (result === "exit") return "exit";
304
+ selectedToolIds = result;
305
+ step = 3;
306
+ } else if (step === 3) {
307
+ const result = await stepPreviewConfirm(selectedSkillIds, selectedToolIds, installedTools, isUninstall);
308
+ if (result === "back") { step = 2; continue; }
309
+ if (result === "exit") return "exit";
310
+ step = 4;
311
+ } else if (step === 4) {
312
+ let attempt = 0;
313
+ let allSuccess = false;
314
+ while (attempt < 3) {
315
+ allSuccess = await stepExecute(selectedSkillIds, selectedToolIds, installedTools, isUninstall);
316
+ if (allSuccess) break;
317
+ attempt++;
318
+ if (attempt < 3) {
319
+ console.log(chalk.yellow(` 第 ${attempt} 次重试...\n`));
320
+ }
321
+ }
322
+ if (allSuccess) {
323
+ await input(
324
+ {
325
+ message: " 按任意键退出...",
326
+ theme: { prefix: chalk.cyan("◆"), style: { highlight: (t) => chalk.cyan(t) } },
327
+ },
328
+ inquirerContext
329
+ ).catch(() => {});
330
+ return "exit";
331
+ } else {
332
+ console.log(chalk.red(" ❌ 重试 3 次后仍有失败,请手动检查。\n"));
333
+ await input(
334
+ {
335
+ message: " 按任意键返回主菜单...",
336
+ theme: { prefix: chalk.cyan("◆"), style: { highlight: (t) => chalk.cyan(t) } },
337
+ },
338
+ inquirerContext
339
+ ).catch(() => {});
340
+ return "back";
341
+ }
342
+ }
343
+ }
344
+ }
345
+
346
+ // ── Main ──
347
+ export async function runInteractive() {
348
+ let exit = false;
349
+
350
+ while (!exit) {
351
+ printBanner();
352
+
353
+ const action = await Select(
354
+ {
355
+ message: " 选择操作:",
356
+ choices: [
357
+ { name: padChoice("📦 安装 Skill", 20), value: "install" },
358
+ { name: padChoice("🗑 卸载 Skill", 20), value: "uninstall" },
359
+ { name: padChoice("✕ 退出", 20), value: "exit" },
360
+ ],
361
+ theme: { prefix: chalk.cyan("◆"), style: { highlight: (t) => chalk.cyan(t) } },
362
+ },
363
+ inquirerContext
364
+ ).catch(() => "exit");
365
+
366
+ if (action === "exit") {
367
+ break;
368
+ }
369
+
370
+ await afterPromptFlush();
371
+ const result = await runFlow(action === "uninstall");
372
+
373
+ if (result === "exit") {
374
+ exit = true;
375
+ }
376
+ await afterPromptFlush();
377
+ // "back" or "done" → loop continues, show main menu again
378
+ }
379
+
380
+ console.log(chalk.gray("\n 👋 Bye!\n"));
381
+ process.exit(0);
382
+ }
@@ -0,0 +1,31 @@
1
+ import { spawnSync } from "child_process";
2
+ import { platform } from "os";
3
+
4
+ export function commandExists(commandName) {
5
+ const lookup = getCommandLookup(platform(), commandName);
6
+ const result = spawnSync(lookup.command, lookup.args, {
7
+ encoding: "utf-8",
8
+ shell: false,
9
+ stdio: ["ignore", "pipe", "ignore"],
10
+ });
11
+ return result.status === 0;
12
+ }
13
+
14
+ export function runCommand(command, args = [], options = {}) {
15
+ const { encoding = "utf-8", inherit = false } = options;
16
+ const result = spawnSync(command, args, {
17
+ encoding,
18
+ shell: platform() === "win32",
19
+ stdio: inherit ? "inherit" : ["pipe", "pipe", "pipe"],
20
+ });
21
+ return {
22
+ status: result.status,
23
+ stdout: result.stdout?.toString() ?? "",
24
+ stderr: result.stderr?.toString() ?? "",
25
+ };
26
+ }
27
+
28
+ function getCommandLookup(plat, commandName) {
29
+ if (plat === "win32") return { command: "where", args: [commandName] };
30
+ return { command: "which", args: [commandName] };
31
+ }