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.
@@ -0,0 +1,280 @@
1
+ /**
2
+ * 带「功能行」的多选 Checkbox:与 @inquirer/checkbox 行为一致,
3
+ * 但列表末尾的 `__back__` / `__exit__` 为功能项——仅支持方向键聚焦 + 回车触发,
4
+ * 不参与空格勾选;普通选项仍用空格多选、回车提交。
5
+ *
6
+ * 用于避免 stock Checkbox 把返回/退出做成 disabled(回车报错)或可勾选(与产品预期不符),
7
+ * 同时避免自管 stdin raw 与 @inquirer 竞态。
8
+ */
9
+ import { cursorHide } from "@inquirer/ansi";
10
+ import {
11
+ Separator,
12
+ ValidationError,
13
+ createPrompt,
14
+ isDownKey,
15
+ isEnterKey,
16
+ isNumberKey,
17
+ isSpaceKey,
18
+ isUpKey,
19
+ makeTheme,
20
+ useKeypress,
21
+ useMemo,
22
+ usePagination,
23
+ usePrefix,
24
+ useState,
25
+ } from "@inquirer/core";
26
+ import figures from "@inquirer/figures";
27
+ import { styleText } from "node:util";
28
+
29
+ /** 与 ui.js 中 parseCheckboxResult 约定的导航返回值 */
30
+ export const NAV_BACK = "__back__";
31
+ export const NAV_EXIT = "__exit__";
32
+
33
+ const checkboxTheme = {
34
+ icon: {
35
+ checked: styleText("green", figures.circleFilled),
36
+ unchecked: figures.circle,
37
+ cursor: figures.pointer,
38
+ disabledChecked: styleText("green", figures.circleDouble),
39
+ disabledUnchecked: "-",
40
+ },
41
+ style: {
42
+ disabled: (text) => styleText("dim", text),
43
+ renderSelectedChoices: (selectedChoices) => selectedChoices.map((choice) => choice.short).join(", "),
44
+ description: (text) => styleText("cyan", text),
45
+ keysHelpTip: (keys) =>
46
+ keys.map(([key, action]) => `${styleText("bold", key)} ${styleText("dim", action)}`).join(styleText("dim", " • ")),
47
+ },
48
+ i18n: {
49
+ disabledError: "This option is disabled and cannot be toggled.",
50
+ /** 焦点在功能行时用户按了空格:提示改用回车 */
51
+ actionRowUseEnter: "此项为功能操作,请按回车确认",
52
+ },
53
+ keybindings: [],
54
+ };
55
+
56
+ /**
57
+ * @param {unknown} item
58
+ * @returns {boolean}
59
+ */
60
+ function isActionRow(item) {
61
+ if (Separator.isSeparator(item) || item == null || typeof item !== "object") return false;
62
+ const v = /** @type {{ value?: unknown }} */ (item).value;
63
+ return v === NAV_BACK || v === NAV_EXIT;
64
+ }
65
+
66
+ function isSelectable(item) {
67
+ return !Separator.isSeparator(item) && !item.disabled && !isActionRow(item);
68
+ }
69
+
70
+ function isNavigable(item) {
71
+ return !Separator.isSeparator(item);
72
+ }
73
+
74
+ function isChecked(item) {
75
+ return !Separator.isSeparator(item) && item.checked;
76
+ }
77
+
78
+ function toggle(item) {
79
+ return isSelectable(item) ? { ...item, checked: !item.checked } : item;
80
+ }
81
+
82
+ function check(checked) {
83
+ return function (item) {
84
+ return isSelectable(item) ? { ...item, checked } : item;
85
+ };
86
+ }
87
+
88
+ function normalizeChoices(choices) {
89
+ return choices.map((choice) => {
90
+ if (Separator.isSeparator(choice)) return choice;
91
+ if (typeof choice !== "object" || choice === null || !("value" in choice)) {
92
+ const name = String(choice);
93
+ return {
94
+ value: choice,
95
+ name,
96
+ short: name,
97
+ checkedName: name,
98
+ disabled: false,
99
+ checked: false,
100
+ };
101
+ }
102
+ const name = choice.name ?? String(choice.value);
103
+ const normalizedChoice = {
104
+ value: choice.value,
105
+ name,
106
+ short: choice.short ?? name,
107
+ checkedName: choice.checkedName ?? name,
108
+ disabled: choice.disabled ?? false,
109
+ checked: choice.checked ?? false,
110
+ };
111
+ if (choice.description) {
112
+ normalizedChoice.description = choice.description;
113
+ }
114
+ return normalizedChoice;
115
+ });
116
+ }
117
+
118
+ export default createPrompt((config, done) => {
119
+ const { pageSize = 7, loop = true, required, validate = () => true } = config;
120
+ const shortcuts = { all: "a", invert: "i", ...config.shortcuts };
121
+ const theme = makeTheme(checkboxTheme, config.theme);
122
+ const { keybindings } = theme;
123
+ const [status, setStatus] = useState("idle");
124
+ const prefix = usePrefix({ status, theme });
125
+ const [items, setItems] = useState(normalizeChoices(config.choices));
126
+ const bounds = useMemo(() => {
127
+ const first = items.findIndex(isNavigable);
128
+ const last = items.findLastIndex(isNavigable);
129
+ if (first === -1) {
130
+ throw new ValidationError("[checkbox-with-action-rows] No navigable choices.");
131
+ }
132
+ return { first, last };
133
+ }, [items]);
134
+ const [active, setActive] = useState(bounds.first);
135
+ const [errorMsg, setError] = useState();
136
+ /** 若为 `__back__` / `__exit__`,表示用户在高亮功能行上按回车结束,用于 done 态展示文案 */
137
+ const [navSubmitValue, setNavSubmitValue] = useState(/** @type {string | null} */ (null));
138
+
139
+ useKeypress(async (key) => {
140
+ if (isEnterKey(key)) {
141
+ const activeItem = items[active];
142
+ // 功能行:回车立即结束 prompt,返回单元素数组供 parseCheckboxResult 识别
143
+ if (activeItem && !Separator.isSeparator(activeItem) && isActionRow(activeItem)) {
144
+ setError(undefined);
145
+ setNavSubmitValue(activeItem.value);
146
+ setStatus("done");
147
+ done([activeItem.value]);
148
+ return;
149
+ }
150
+
151
+ const selection = items.filter(isChecked);
152
+ const isValid = await validate([...selection]);
153
+ if (required && !selection.length) {
154
+ setError("At least one choice must be selected");
155
+ } else if (isValid === true) {
156
+ setNavSubmitValue(null);
157
+ setStatus("done");
158
+ done(selection.map((choice) => choice.value));
159
+ } else {
160
+ setError(isValid || "You must select a valid value");
161
+ }
162
+ } else if (isUpKey(key, keybindings) || isDownKey(key, keybindings)) {
163
+ if (errorMsg) {
164
+ setError(undefined);
165
+ }
166
+ if (
167
+ loop ||
168
+ (isUpKey(key, keybindings) && active !== bounds.first) ||
169
+ (isDownKey(key, keybindings) && active !== bounds.last)
170
+ ) {
171
+ const offset = isUpKey(key, keybindings) ? -1 : 1;
172
+ let next = active;
173
+ do {
174
+ next = (next + offset + items.length) % items.length;
175
+ } while (!isNavigable(items[next]));
176
+ setActive(next);
177
+ }
178
+ } else if (isSpaceKey(key)) {
179
+ const activeItem = items[active];
180
+ if (activeItem && !Separator.isSeparator(activeItem)) {
181
+ if (isActionRow(activeItem)) {
182
+ setError(theme.i18n.actionRowUseEnter ?? "此项为功能操作,请按回车确认");
183
+ } else if (activeItem.disabled) {
184
+ setError(theme.i18n.disabledError);
185
+ } else {
186
+ setError(undefined);
187
+ setItems(items.map((choice, i) => (i === active ? toggle(choice) : choice)));
188
+ }
189
+ }
190
+ } else if (key.name === shortcuts.all) {
191
+ const selectAll = items.some((choice) => isSelectable(choice) && !choice.checked);
192
+ setItems(items.map(check(selectAll)));
193
+ } else if (key.name === shortcuts.invert) {
194
+ setItems(items.map(toggle));
195
+ } else if (isNumberKey(key)) {
196
+ const selectedIndex = Number(key.name) - 1;
197
+ let selectableIndex = -1;
198
+ const position = items.findIndex((item) => {
199
+ if (Separator.isSeparator(item)) return false;
200
+ selectableIndex++;
201
+ return selectableIndex === selectedIndex;
202
+ });
203
+ const selectedItem = items[position];
204
+ if (selectedItem && isSelectable(selectedItem)) {
205
+ setActive(position);
206
+ setItems(items.map((choice, i) => (i === position ? toggle(choice) : choice)));
207
+ } else if (selectedItem && isActionRow(selectedItem)) {
208
+ setActive(position);
209
+ }
210
+ }
211
+ });
212
+
213
+ const message = theme.style.message(config.message, status);
214
+ let description;
215
+ const page = usePagination({
216
+ items,
217
+ active,
218
+ renderItem({ item, isActive }) {
219
+ if (Separator.isSeparator(item)) {
220
+ return ` ${item.separator}`;
221
+ }
222
+ const cursor = isActive ? theme.icon.cursor : " ";
223
+ if (item.disabled) {
224
+ const disabledLabel = typeof item.disabled === "string" ? item.disabled : "(disabled)";
225
+ const checkbox = item.checked ? theme.icon.disabledChecked : theme.icon.disabledUnchecked;
226
+ return theme.style.disabled(`${cursor}${checkbox} ${item.name} ${disabledLabel}`);
227
+ }
228
+ // 功能行:不占「○ + 空格」列——文案紧跟指针,与勾选行里圆圈所在列对齐(视觉上更靠左)
229
+ if (isActionRow(item)) {
230
+ if (isActive) {
231
+ description = item.description;
232
+ }
233
+ const color = isActive ? theme.style.highlight : (x) => x;
234
+ return color(`${cursor}${item.name}`);
235
+ }
236
+ if (isActive) {
237
+ description = item.description;
238
+ }
239
+ const checkbox = item.checked ? theme.icon.checked : theme.icon.unchecked;
240
+ const name = item.checked ? item.checkedName : item.name;
241
+ const color = isActive ? theme.style.highlight : (x) => x;
242
+ return color(`${cursor}${checkbox} ${name}`);
243
+ },
244
+ pageSize,
245
+ loop,
246
+ });
247
+
248
+ if (status === "done") {
249
+ if (navSubmitValue === NAV_BACK) {
250
+ return [prefix, message, theme.style.answer("↩ 返回")].filter(Boolean).join(" ");
251
+ }
252
+ if (navSubmitValue === NAV_EXIT) {
253
+ return [prefix, message, theme.style.answer("✕ 退出")].filter(Boolean).join(" ");
254
+ }
255
+ const selection = items.filter(isChecked);
256
+ const answer = theme.style.answer(theme.style.renderSelectedChoices(selection, items));
257
+ return [prefix, message, answer].filter(Boolean).join(" ");
258
+ }
259
+
260
+ const keys = [
261
+ ["↑↓", "移动"],
262
+ ["space", "多选"],
263
+ ];
264
+ if (shortcuts.all) keys.push([shortcuts.all, "all"]);
265
+ if (shortcuts.invert) keys.push([shortcuts.invert, "invert"]);
266
+ keys.push(["⏎", "提交多选 / 执行功能行"]);
267
+ const helpLine = theme.style.keysHelpTip(keys);
268
+ const lines = [
269
+ [prefix, message].filter(Boolean).join(" "),
270
+ page,
271
+ " ",
272
+ description ? theme.style.description(description) : "",
273
+ errorMsg ? theme.style.error(errorMsg) : "",
274
+ helpLine,
275
+ ]
276
+ .filter(Boolean)
277
+ .join("\n")
278
+ .trimEnd();
279
+ return `${lines}${cursorHide}`;
280
+ });
@@ -0,0 +1,195 @@
1
+ import { homedir } from "os";
2
+ import { join } from "path";
3
+ import { existsSync, readdirSync, readFileSync, statSync } from "fs";
4
+ import { commandExists } from "../utils/platform.js";
5
+
6
+ // ── Tools ──
7
+
8
+ export const TOOLS = [
9
+ {
10
+ id: "claude-code",
11
+ name: "Claude Code",
12
+ command: "claude",
13
+ installMode: "file",
14
+ skillsDir: () => join(homedir(), ".claude", "commands"),
15
+ installHint: "npm install -g @anthropic-ai/claude-code",
16
+ },
17
+ {
18
+ id: "cursor",
19
+ name: "Cursor",
20
+ command: "cursor",
21
+ installMode: "file",
22
+ skillsDir: () => join(homedir(), ".cursor", "commands"),
23
+ installHint: "Download from https://cursor.com",
24
+ },
25
+ {
26
+ id: "opencode",
27
+ name: "OpenCode",
28
+ command: "opencode",
29
+ installMode: "dir",
30
+ skillsDir: () => join(homedir(), ".opencode", "skills"),
31
+ installHint: "npm install -g opencode-ai",
32
+ },
33
+ {
34
+ id: "trae",
35
+ name: "Trae",
36
+ command: "trae",
37
+ installMode: "file",
38
+ skillsDir: () => join(homedir(), ".trae", "commands"),
39
+ installHint: "Download from https://trae.ai",
40
+ },
41
+ {
42
+ id: "openclaw",
43
+ name: "OpenClaw",
44
+ command: "openclaw",
45
+ installMode: "dir",
46
+ skillsDir: () => join(homedir(), ".openclaw", "skills"),
47
+ installHint: "npm install -g openclaw",
48
+ },
49
+ {
50
+ id: "nanobot",
51
+ name: "Nanobot",
52
+ command: "nanobot",
53
+ installMode: "dir",
54
+ skillsDir: () => join(homedir(), ".nanobot", "skills"),
55
+ installHint: "pip install nanobot",
56
+ },
57
+ {
58
+ id: "hermes-agent",
59
+ name: "Hermes Agent",
60
+ command: "hermes",
61
+ installMode: "dir",
62
+ skillsDir: () => join(homedir(), ".hermes", "skills"),
63
+ installHint: "pip install hermes-ai",
64
+ },
65
+ {
66
+ id: "zeroclaw",
67
+ name: "ZeroClaw",
68
+ command: "zeroclaw",
69
+ installMode: "dir",
70
+ skillsDir: () => join(homedir(), ".zeroclaw", "skills"),
71
+ installHint: "npm install -g zeroclaw",
72
+ },
73
+ ];
74
+
75
+ // ── Skill auto-discovery ──
76
+
77
+ /**
78
+ * Get the package root directory.
79
+ * import.meta.dirname = <luminae-helper>/src/lib
80
+ * Package root = <luminae-helper>/
81
+ */
82
+ function getPackageDir() {
83
+ const selfDir = import.meta.dirname;
84
+ if (selfDir.endsWith("/src/lib") || selfDir.endsWith("\\src\\lib")) {
85
+ return join(selfDir, "..", "..");
86
+ }
87
+ if (selfDir.endsWith("/src") || selfDir.endsWith("\\src")) {
88
+ return join(selfDir, "..");
89
+ }
90
+ return selfDir;
91
+ }
92
+
93
+ /**
94
+ * Parse YAML frontmatter from SKILL.md content.
95
+ * Only extracts `name` and `description`.
96
+ */
97
+ function parseSkillMeta(skillId, content) {
98
+ let name = null;
99
+ let description = null;
100
+
101
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
102
+ if (fmMatch) {
103
+ for (const line of fmMatch[1].split("\n")) {
104
+ const m = line.match(/^(\w+):\s*(.+)/);
105
+ if (m) {
106
+ if (m[1] === "name") name = m[2].trim();
107
+ if (m[1] === "description") description = m[2].trim();
108
+ }
109
+ }
110
+ }
111
+
112
+ // Default name: skillId without "skill-" prefix, capitalize words
113
+ if (!name) {
114
+ name = skillId
115
+ .replace(/^skill-/, "")
116
+ .replace(/(^|-)(\w)/g, (_, p, c) => (p === "-" ? " " : "") + c.toUpperCase());
117
+ }
118
+
119
+ // Default description: first blockquote line
120
+ if (!description) {
121
+ const bq = content.match(/^>\s*(.+)/m);
122
+ if (bq) description = bq[1].trim();
123
+ }
124
+
125
+ return { name, description };
126
+ }
127
+
128
+ /**
129
+ * Generate destPath for a skill+tool combo based on installMode.
130
+ * - file mode: <skillsDir>/<shortName>.md
131
+ * - dir mode: <skillsDir>/<skillId>/
132
+ */
133
+ function generateDestPath(tool, skillId) {
134
+ const shortName = skillId.replace(/^skill-/, "");
135
+ if (tool.installMode === "dir") {
136
+ return () => join(tool.skillsDir(), skillId);
137
+ }
138
+ return () => join(tool.skillsDir(), `${shortName}.md`);
139
+ }
140
+
141
+ /**
142
+ * Scan skills/ directory and build SKILLS array automatically.
143
+ * Each subdirectory containing a SKILL.md is a valid skill.
144
+ */
145
+ export function discoverSkills() {
146
+ const skillsRoot = join(getPackageDir(), "skills");
147
+ if (!existsSync(skillsRoot)) return [];
148
+
149
+ const skills = [];
150
+ for (const entry of readdirSync(skillsRoot)) {
151
+ const skillPath = join(skillsRoot, entry);
152
+ if (!statSync(skillPath).isDirectory()) continue;
153
+
154
+ const skillFile = join(skillPath, "SKILL.md");
155
+ if (!existsSync(skillFile)) continue;
156
+
157
+ const skillId = entry;
158
+ const content = readFileSync(skillFile, "utf-8");
159
+ const { name, description } = parseSkillMeta(skillId, content);
160
+
161
+ skills.push({
162
+ id: skillId,
163
+ name,
164
+ description,
165
+ installTargets: TOOLS.map((tool) => ({
166
+ toolId: tool.id,
167
+ destPath: generateDestPath(tool, skillId),
168
+ })),
169
+ });
170
+ }
171
+
172
+ return skills;
173
+ }
174
+
175
+ export const SKILLS = discoverSkills();
176
+
177
+ // ── Helpers ──
178
+
179
+ /**
180
+ * Detect which tools are installed on this machine.
181
+ */
182
+ export function detectInstalledTools() {
183
+ return TOOLS.map((tool) => ({
184
+ ...tool,
185
+ installed: commandExists(tool.command),
186
+ }));
187
+ }
188
+
189
+ /**
190
+ * Find skill source directory bundled inside this package.
191
+ * Skills are at <luminae-helper>/skills/<skillId>/
192
+ */
193
+ export function getSkillSourcePath(skillId) {
194
+ return join(getPackageDir(), "skills", skillId);
195
+ }
@@ -0,0 +1,104 @@
1
+ import { existsSync, mkdirSync, copyFileSync, readdirSync, rmSync, unlinkSync } from "fs";
2
+ import { dirname, join } from "path";
3
+ import { getSkillSourcePath } from "./constants.js";
4
+
5
+ function ensureDir(filePath) {
6
+ const dir = dirname(filePath);
7
+ if (!existsSync(dir)) {
8
+ mkdirSync(dir, { recursive: true });
9
+ }
10
+ }
11
+
12
+ function copyFile(src, dest) {
13
+ ensureDir(dest);
14
+ copyFileSync(src, dest);
15
+ }
16
+
17
+ function copyDir(src, dest) {
18
+ if (!existsSync(src)) throw new Error(`Source dir not found: ${src}`);
19
+ if (!existsSync(dest)) {
20
+ mkdirSync(dest, { recursive: true });
21
+ }
22
+ const entries = readdirSync(src, { withFileTypes: true });
23
+ for (const entry of entries) {
24
+ const srcPath = join(src, entry.name);
25
+ const destPath = join(dest, entry.name);
26
+ if (entry.isDirectory()) {
27
+ copyDir(srcPath, destPath);
28
+ } else {
29
+ copyFile(srcPath, destPath);
30
+ }
31
+ }
32
+ }
33
+
34
+ /**
35
+ * Install a skill to a specific tool destination.
36
+ * @param {object} skill - skill object from constants.js
37
+ * @param {object} tool - tool object from constants.js
38
+ * @returns {{ success: boolean, message: string }}
39
+ */
40
+ export function installSkillToTool(skill, tool) {
41
+ // Look up the correct destPath from installTargets
42
+ const target = skill.installTargets?.find(tgt => tgt.toolId === tool.id);
43
+ if (!target) {
44
+ return { success: false, message: `Skill does not support ${tool.name}` };
45
+ }
46
+
47
+ const sourceDir = getSkillSourcePath(skill.id);
48
+
49
+ if (!existsSync(sourceDir)) {
50
+ return { success: false, message: `Skill source not found: ${sourceDir}` };
51
+ }
52
+
53
+ const destPath = target.destPath();
54
+ const destDir = dirname(destPath);
55
+
56
+ if (!existsSync(destDir)) {
57
+ mkdirSync(destDir, { recursive: true });
58
+ }
59
+
60
+ const srcSkillFile = join(sourceDir, "SKILL.md");
61
+ if (!existsSync(srcSkillFile)) {
62
+ return { success: false, message: `SKILL.md not found in ${sourceDir}` };
63
+ }
64
+
65
+ const isDirBased = tool.installMode === "dir";
66
+
67
+ if (isDirBased) {
68
+ const destSkillDir = destPath;
69
+ copyDir(sourceDir, destSkillDir);
70
+ return { success: true, message: `Installed to ${destSkillDir}` };
71
+ } else {
72
+ copyFile(srcSkillFile, destPath);
73
+ return { success: true, message: `Installed to ${destPath}` };
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Uninstall a skill from a specific tool.
79
+ */
80
+ export function uninstallSkillFromTool(skill, tool) {
81
+ const target = skill.installTargets?.find(tgt => tgt.toolId === tool.id);
82
+ if (!target) {
83
+ return { success: false, message: `Skill does not support ${tool.name}` };
84
+ }
85
+
86
+ const destPath = target.destPath();
87
+ const isDirBased = tool.installMode === "dir";
88
+
89
+ if (isDirBased) {
90
+ if (existsSync(destPath)) {
91
+ rmSync(destPath, { recursive: true, force: true });
92
+ return { success: true, message: `Uninstalled from ${destPath}` };
93
+ } else {
94
+ return { success: false, message: "Not installed" };
95
+ }
96
+ } else {
97
+ if (existsSync(destPath)) {
98
+ unlinkSync(destPath);
99
+ return { success: true, message: `Uninstalled from ${destPath}` };
100
+ } else {
101
+ return { success: false, message: "Not installed" };
102
+ }
103
+ }
104
+ }