@frcloudsolutions/agent-skills 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 (38) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -2
  3. package/bin/agent-skills.mjs +8 -0
  4. package/package.json +42 -4
  5. package/plugins/docs-generator/skills/docs-generator/SKILL.md +68 -0
  6. package/plugins/docs-generator/skills/docs-generator/assets/README.md +8 -0
  7. package/plugins/docs-generator/skills/docs-generator/assets/fonts/OFL.txt +93 -0
  8. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Bold.ttf +0 -0
  9. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-BoldItalic.ttf +0 -0
  10. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Italic.ttf +0 -0
  11. package/plugins/docs-generator/skills/docs-generator/assets/fonts/PublicSans-Regular.ttf +0 -0
  12. package/plugins/docs-generator/skills/docs-generator/assets/paged.polyfill.min.js +4 -0
  13. package/plugins/docs-generator/skills/docs-generator/locales/en.json +14 -0
  14. package/plugins/docs-generator/skills/docs-generator/locales/es.json +14 -0
  15. package/plugins/docs-generator/skills/docs-generator/locales/pt-BR.json +14 -0
  16. package/plugins/docs-generator/skills/docs-generator/package-lock.json +1697 -0
  17. package/plugins/docs-generator/skills/docs-generator/package.json +28 -0
  18. package/plugins/docs-generator/skills/docs-generator/references/from-design-system.md +48 -0
  19. package/plugins/docs-generator/skills/docs-generator/references/source-format.md +96 -0
  20. package/plugins/docs-generator/skills/docs-generator/references/theme-format.md +77 -0
  21. package/plugins/docs-generator/skills/docs-generator/references/writing-guide.md +39 -0
  22. package/plugins/docs-generator/skills/docs-generator/scripts/docs.mjs +226 -0
  23. package/plugins/docs-generator/skills/docs-generator/scripts/lib/docx.mjs +377 -0
  24. package/plugins/docs-generator/skills/docs-generator/scripts/lib/html.mjs +273 -0
  25. package/plugins/docs-generator/skills/docs-generator/scripts/lib/images.mjs +25 -0
  26. package/plugins/docs-generator/skills/docs-generator/scripts/lib/office.mjs +184 -0
  27. package/plugins/docs-generator/skills/docs-generator/scripts/lib/pdf.mjs +70 -0
  28. package/plugins/docs-generator/skills/docs-generator/scripts/lib/source.mjs +270 -0
  29. package/plugins/docs-generator/skills/docs-generator/scripts/lib/theme.mjs +219 -0
  30. package/plugins/docs-generator/skills/docs-generator/themes/clean-modern.json +36 -0
  31. package/plugins/docs-generator/skills/docs-generator/themes/docs-theme.schema.json +119 -0
  32. package/src/cli/main.mjs +222 -0
  33. package/src/cli/prompt.mjs +142 -0
  34. package/src/lib/catalog.mjs +28 -0
  35. package/src/lib/frontmatter.mjs +23 -0
  36. package/src/lib/install.mjs +67 -0
  37. package/src/lib/tools.mjs +77 -0
  38. package/src/lib/validate.mjs +86 -0
@@ -0,0 +1,219 @@
1
+ // Theme loading, defaults and WCAG contrast checks.
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import Ajv from "ajv/dist/2020.js";
6
+
7
+ export const SKILL_ROOT = fileURLToPath(new URL("../..", import.meta.url));
8
+ export const THEMES_DIR = join(SKILL_ROOT, "themes");
9
+ export const FONTS_DIR = join(SKILL_ROOT, "assets", "fonts");
10
+ export const DEFAULT_THEME = "clean-modern";
11
+
12
+ /** Fonts shipped with the skill: family → face files. */
13
+ export const BUNDLED_FONTS = {
14
+ "Public Sans": {
15
+ regular: join(FONTS_DIR, "PublicSans-Regular.ttf"),
16
+ bold: join(FONTS_DIR, "PublicSans-Bold.ttf"),
17
+ italic: join(FONTS_DIR, "PublicSans-Italic.ttf"),
18
+ boldItalic: join(FONTS_DIR, "PublicSans-BoldItalic.ttf"),
19
+ },
20
+ };
21
+
22
+ /** Generic CSS families: always available, mapped to a common font in Office files. */
23
+ export const GENERIC_FONTS = { "sans-serif": "Arial", serif: "Georgia", monospace: "Consolas" };
24
+
25
+ /** Minimum WCAG 2.x contrast ratios checked on every theme. */
26
+ export const CONTRAST_RULES = [
27
+ { fg: "text", bg: "background", min: 4.5, use: "body text" },
28
+ { fg: "textMuted", bg: "background", min: 4.5, use: "secondary text" },
29
+ { fg: "accent", bg: "background", min: 3, use: "headings and links (large text)" },
30
+ { fg: "onAccent", bg: "accent", min: 4.5, use: "text on the cover band" },
31
+ { fg: "text", bg: "tableHeader", min: 4.5, use: "table header text" },
32
+ ];
33
+
34
+ const schema = JSON.parse(readFileSync(join(THEMES_DIR, "docs-theme.schema.json"), "utf8"));
35
+ const validateSchema = new Ajv({ allErrors: true, strict: false }).compile(schema);
36
+
37
+ export function bundledThemeNames() {
38
+ return ["clean-modern"];
39
+ }
40
+
41
+ /** Path of a bundled theme by name, or null. */
42
+ export function bundledThemePath(name) {
43
+ const p = join(THEMES_DIR, `${name}.json`);
44
+ return bundledThemeNames().includes(name) && existsSync(p) ? p : null;
45
+ }
46
+
47
+ function deepMerge(base, over) {
48
+ if (Array.isArray(over) || typeof over !== "object" || over === null) return over;
49
+ const out = { ...base };
50
+ for (const [k, v] of Object.entries(over)) {
51
+ out[k] = typeof v === "object" && v !== null && !Array.isArray(v) && typeof base?.[k] === "object" ? deepMerge(base[k], v) : v;
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // ---- color math (WCAG 2.x relative luminance) -------------------------------------------
57
+
58
+ export function hexToRgb(hex) {
59
+ const n = parseInt(hex.slice(1), 16);
60
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
61
+ }
62
+
63
+ export function rgbToHex([r, g, b]) {
64
+ return "#" + [r, g, b].map((v) => Math.round(Math.min(255, Math.max(0, v))).toString(16).padStart(2, "0")).join("").toUpperCase();
65
+ }
66
+
67
+ export function luminance(hex) {
68
+ const [r, g, b] = hexToRgb(hex).map((v) => {
69
+ const c = v / 255;
70
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
71
+ });
72
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
73
+ }
74
+
75
+ export function contrastRatio(a, b) {
76
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
77
+ return (hi + 0.05) / (lo + 0.05);
78
+ }
79
+
80
+ export function rgbToHsl([r, g, b]) {
81
+ r /= 255; g /= 255; b /= 255;
82
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
83
+ const l = (max + min) / 2;
84
+ if (max === min) return [0, 0, l];
85
+ const d = max - min;
86
+ const s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
87
+ const h = max === r ? (g - b) / d + (g < b ? 6 : 0) : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
88
+ return [h * 60, s, l];
89
+ }
90
+
91
+ export function hslToRgb([h, s, l]) {
92
+ const k = (n) => (n + h / 30) % 12;
93
+ const a = s * Math.min(l, 1 - l);
94
+ const f = (n) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
95
+ return [f(0) * 255, f(8) * 255, f(4) * 255];
96
+ }
97
+
98
+ /**
99
+ * Nearest color to `fg` (same hue and saturation, lightness moved) that reaches `min` against `bg`.
100
+ * Used to suggest a fix when a theme fails a contrast check.
101
+ */
102
+ export function nearestPassingColor(fg, bg, min) {
103
+ const [h, s, l] = rgbToHsl(hexToRgb(fg));
104
+ const darker = luminance(bg) > 0.18;
105
+ for (let step = 0; step <= 100; step++) {
106
+ const nl = darker ? l - step / 100 : l + step / 100;
107
+ if (nl < 0 || nl > 1) break;
108
+ const c = rgbToHex(hslToRgb([h, s, nl]));
109
+ if (contrastRatio(c, bg) >= min) return c;
110
+ }
111
+ return darker ? "#000000" : "#FFFFFF";
112
+ }
113
+
114
+ // ---- loading ----------------------------------------------------------------------------
115
+
116
+ /**
117
+ * Loads a theme by bundled name or file path, fills missing fields from clean-modern and checks it.
118
+ * @returns {{ theme: object|null, errors: string[], warnings: string[], source: string }}
119
+ */
120
+ export function loadTheme(ref = DEFAULT_THEME, { cwd = process.cwd() } = {}) {
121
+ const errors = [];
122
+ const warnings = [];
123
+ const path = bundledThemePath(ref) ?? (isAbsolute(ref) ? ref : resolve(cwd, ref));
124
+ if (!existsSync(path)) {
125
+ return { theme: null, errors: [`theme "${ref}" not found (bundled themes: ${bundledThemeNames().join(", ")})`], warnings, source: path };
126
+ }
127
+ let raw;
128
+ try {
129
+ raw = JSON.parse(readFileSync(path, "utf8"));
130
+ } catch (e) {
131
+ return { theme: null, errors: [`${path}: invalid JSON: ${e.message}`], warnings, source: path };
132
+ }
133
+ if (!validateSchema(raw)) {
134
+ for (const e of validateSchema.errors) {
135
+ const field = (e.instancePath || "/").slice(1).replaceAll("/", ".") || "(root)";
136
+ const detail = e.keyword === "pattern" && e.instancePath.includes("colors")
137
+ ? `must be a color like "#1F2328"`
138
+ : e.keyword === "additionalProperties" ? `unknown field "${e.params.additionalProperty}"` : e.message;
139
+ errors.push(`${field}: ${detail}`);
140
+ }
141
+ return { theme: null, errors, warnings, source: path };
142
+ }
143
+
144
+ const defaults = JSON.parse(readFileSync(join(THEMES_DIR, `${DEFAULT_THEME}.json`), "utf8"));
145
+ delete defaults.$schema;
146
+ const theme = deepMerge(defaults, raw);
147
+ delete theme.$schema;
148
+ if (!raw.name) theme.name = path === bundledThemePath(DEFAULT_THEME) ? DEFAULT_THEME : "custom";
149
+ theme.baseDir = dirname(path);
150
+
151
+ // Font files given by the theme
152
+ theme.fonts.files = (raw.fonts?.files ?? []).map((f) => ({
153
+ family: f.family,
154
+ weight: f.weight ?? "normal",
155
+ style: f.style ?? "normal",
156
+ path: resolve(theme.baseDir, f.path),
157
+ }));
158
+ for (const f of theme.fonts.files) {
159
+ if (!existsSync(f.path)) errors.push(`fonts.files: file not found: ${f.path}`);
160
+ else if (!/\.(ttf|otf|woff2?)$/i.test(f.path)) errors.push(`fonts.files: ${f.path} must be a .ttf, .otf, .woff or .woff2 file`);
161
+ }
162
+ const webOnly = [...new Set(theme.fonts.files.filter((f) => /\.woff2?$/i.test(f.path)).map((f) => f.family))]
163
+ .filter((family) => !theme.fonts.files.some((f) => f.family === family && /\.(ttf|otf)$/i.test(f.path)));
164
+ for (const family of webOnly)
165
+ warnings.push(`fonts.files: "${family}" has only WOFF/WOFF2 files; the PDF uses them, but Word cannot embed them, so the DOCX shows "${family}" only where it is installed (add .ttf or .otf files to embed it)`);
166
+ for (const role of ["heading", "body", "mono"]) {
167
+ const family = theme.fonts[role];
168
+ if (!fontAvailable(theme, family))
169
+ warnings.push(`fonts.${role}: "${family}" is not bundled and has no file in fonts.files; viewers will use their default font`);
170
+ }
171
+
172
+ if (theme.cover.logo) {
173
+ theme.cover.logo = resolve(theme.baseDir, theme.cover.logo);
174
+ if (!existsSync(theme.cover.logo)) errors.push(`cover.logo: file not found: ${theme.cover.logo}`);
175
+ else if (!/\.(png|jpe?g)$/i.test(theme.cover.logo)) errors.push("cover.logo: must be a PNG or JPEG file");
176
+ }
177
+
178
+ for (const r of CONTRAST_RULES) {
179
+ const fg = theme.colors[r.fg], bg = theme.colors[r.bg];
180
+ const ratio = contrastRatio(fg, bg);
181
+ if (ratio < r.min) {
182
+ errors.push(
183
+ `colors.${r.fg} ${fg} on colors.${r.bg} ${bg} has contrast ${ratio.toFixed(2)}:1, below ${r.min}:1 for ${r.use}` +
184
+ ` (nearest passing: ${nearestPassingColor(fg, bg, r.min)})`,
185
+ );
186
+ }
187
+ }
188
+ return { theme: errors.length ? null : theme, errors, warnings, source: path };
189
+ }
190
+
191
+ export function fontAvailable(theme, family) {
192
+ return Boolean(BUNDLED_FONTS[family] || GENERIC_FONTS[family] || theme.fonts.files?.some((f) => f.family === family));
193
+ }
194
+
195
+ /** Face files for a family: bundled or from the theme. Missing faces are undefined. */
196
+ export function fontFaces(theme, family) {
197
+ if (BUNDLED_FONTS[family]) return BUNDLED_FONTS[family];
198
+ const files = (theme.fonts.files ?? []).filter((f) => f.family === family);
199
+ const pick = (w, s) => files.find((f) => f.weight === w && f.style === s)?.path;
200
+ return { regular: pick("normal", "normal"), bold: pick("bold", "normal"), italic: pick("normal", "italic"), boldItalic: pick("bold", "italic") };
201
+ }
202
+
203
+ /** Name Office files should use for a theme font (generic CSS families map to common Office fonts). */
204
+ export function officeFont(family) {
205
+ return GENERIC_FONTS[family] ?? family;
206
+ }
207
+
208
+ /**
209
+ * Office accent colors 2–6: from the theme, or derived from the accent by rotating the hue and
210
+ * adjusting lightness until each reaches 3:1 against the background.
211
+ */
212
+ export function officeAccents(theme) {
213
+ if (theme.office?.accents) return theme.office.accents;
214
+ const [h, s, l] = rgbToHsl(hexToRgb(theme.colors.accent));
215
+ return [1, 2, 3, 4, 5].map((i) => {
216
+ const c = rgbToHex(hslToRgb([(h + i * 60) % 360, Math.max(s, 0.35), l]));
217
+ return contrastRatio(c, theme.colors.background) >= 3 ? c : nearestPassingColor(c, theme.colors.background, 3);
218
+ });
219
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "$schema": "./docs-theme.schema.json",
3
+ "name": "clean-modern",
4
+ "fonts": {
5
+ "heading": "Public Sans",
6
+ "body": "Public Sans",
7
+ "mono": "monospace"
8
+ },
9
+ "colors": {
10
+ "text": "#1F2328",
11
+ "textMuted": "#57606A",
12
+ "accent": "#0B6E79",
13
+ "onAccent": "#FFFFFF",
14
+ "background": "#FFFFFF",
15
+ "tableHeader": "#F6F8FA",
16
+ "border": "#D0D7DE"
17
+ },
18
+ "type": {
19
+ "body": 11,
20
+ "h1": 20,
21
+ "h2": 14,
22
+ "h3": 12,
23
+ "small": 9,
24
+ "title": 34,
25
+ "lineHeight": 1.4,
26
+ "paragraphSpacing": 6
27
+ },
28
+ "page": {
29
+ "size": "A4",
30
+ "margins": { "top": 28, "right": 36, "bottom": 28, "left": 36 }
31
+ },
32
+ "cover": {
33
+ "style": "accent-band"
34
+ },
35
+ "backCover": {}
36
+ }
@@ -0,0 +1,119 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://github.com/rezendesfelipe/agent-skills/plugins/docs-generator/skills/docs-generator/themes/docs-theme.schema.json",
4
+ "title": "docs-generator theme",
5
+ "description": "Look of the documents, Excel template and Office theme generated by the docs-generator skill. Fields left out are taken from the clean-modern theme.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "properties": {
9
+ "$schema": { "type": "string" },
10
+ "name": {
11
+ "description": "Theme name, also used as the file name of the .xltx and .thmx outputs.",
12
+ "type": "string",
13
+ "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"
14
+ },
15
+ "fonts": {
16
+ "type": "object",
17
+ "additionalProperties": false,
18
+ "properties": {
19
+ "heading": { "$ref": "#/$defs/fontName" },
20
+ "body": { "$ref": "#/$defs/fontName" },
21
+ "mono": { "$ref": "#/$defs/fontName" },
22
+ "files": {
23
+ "description": "Font files for fonts that are not bundled with the skill. Paths are relative to the theme file.",
24
+ "type": "array",
25
+ "items": {
26
+ "type": "object",
27
+ "additionalProperties": false,
28
+ "required": ["family", "path"],
29
+ "properties": {
30
+ "family": { "$ref": "#/$defs/fontName" },
31
+ "path": { "type": "string", "minLength": 1 },
32
+ "weight": { "enum": ["normal", "bold"], "default": "normal" },
33
+ "style": { "enum": ["normal", "italic"], "default": "normal" }
34
+ }
35
+ }
36
+ }
37
+ }
38
+ },
39
+ "colors": {
40
+ "type": "object",
41
+ "additionalProperties": false,
42
+ "properties": {
43
+ "text": { "$ref": "#/$defs/color", "description": "Body text" },
44
+ "textMuted": { "$ref": "#/$defs/color", "description": "Secondary text: footers, captions, cover details" },
45
+ "accent": { "$ref": "#/$defs/color", "description": "Headings, links, cover band" },
46
+ "onAccent": { "$ref": "#/$defs/color", "description": "Text drawn on the accent color" },
47
+ "background": { "$ref": "#/$defs/color", "description": "Page background" },
48
+ "tableHeader": { "$ref": "#/$defs/color", "description": "Background of table header rows and code blocks" },
49
+ "border": { "$ref": "#/$defs/color", "description": "Table rules and separators" }
50
+ }
51
+ },
52
+ "type": {
53
+ "description": "Type sizes in points.",
54
+ "type": "object",
55
+ "additionalProperties": false,
56
+ "properties": {
57
+ "body": { "type": "number", "minimum": 8, "maximum": 16 },
58
+ "h1": { "type": "number", "minimum": 10, "maximum": 40 },
59
+ "h2": { "type": "number", "minimum": 10, "maximum": 32 },
60
+ "h3": { "type": "number", "minimum": 8, "maximum": 24 },
61
+ "small": { "type": "number", "minimum": 6, "maximum": 12 },
62
+ "title": { "type": "number", "minimum": 16, "maximum": 72, "description": "Cover title" },
63
+ "lineHeight": { "type": "number", "minimum": 1, "maximum": 2, "description": "Multiple of the body size" },
64
+ "paragraphSpacing": { "type": "number", "minimum": 0, "maximum": 24, "description": "Space after a paragraph, in points" }
65
+ }
66
+ },
67
+ "page": {
68
+ "type": "object",
69
+ "additionalProperties": false,
70
+ "properties": {
71
+ "size": { "enum": ["A4", "Letter"] },
72
+ "margins": {
73
+ "description": "Page margins in millimetres.",
74
+ "type": "object",
75
+ "additionalProperties": false,
76
+ "properties": {
77
+ "top": { "type": "number", "minimum": 5, "maximum": 60 },
78
+ "right": { "type": "number", "minimum": 5, "maximum": 60 },
79
+ "bottom": { "type": "number", "minimum": 5, "maximum": 60 },
80
+ "left": { "type": "number", "minimum": 5, "maximum": 60 }
81
+ }
82
+ }
83
+ }
84
+ },
85
+ "cover": {
86
+ "type": "object",
87
+ "additionalProperties": false,
88
+ "properties": {
89
+ "style": { "enum": ["accent-band", "plain"] },
90
+ "logo": { "type": "string", "description": "PNG or JPEG file relative to the theme file" }
91
+ }
92
+ },
93
+ "backCover": {
94
+ "type": "object",
95
+ "additionalProperties": false,
96
+ "properties": {
97
+ "contact": { "type": "string" },
98
+ "license": { "type": "string" }
99
+ }
100
+ },
101
+ "office": {
102
+ "type": "object",
103
+ "additionalProperties": false,
104
+ "properties": {
105
+ "accents": {
106
+ "description": "Office accent colors 2 to 6. Derived from the accent color when left out.",
107
+ "type": "array",
108
+ "items": { "$ref": "#/$defs/color" },
109
+ "minItems": 5,
110
+ "maxItems": 5
111
+ }
112
+ }
113
+ }
114
+ },
115
+ "$defs": {
116
+ "color": { "type": "string", "pattern": "^#[0-9A-Fa-f]{6}$" },
117
+ "fontName": { "type": "string", "minLength": 1, "maxLength": 64 }
118
+ }
119
+ }
@@ -0,0 +1,222 @@
1
+ // agent-skills command line: list, add and remove skills for supported tools.
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { TOOLS, TOOL_IDS, SCOPES, detectTools, overlaps } from "../lib/tools.mjs";
7
+ import { findSkills } from "../lib/catalog.mjs";
8
+ import { OK_STATUSES, PACKAGE_NAME, install, installedSkills, planTargets, remove } from "../lib/install.mjs";
9
+ import * as prompts from "./prompt.mjs";
10
+
11
+ const PACKAGE_ROOT = fileURLToPath(new URL("../..", import.meta.url));
12
+
13
+ export const EXIT = { OK: 0, FAILED: 1, USAGE: 2 };
14
+
15
+ class UsageError extends Error {}
16
+
17
+ const HELP = `Usage: npx ${PACKAGE_NAME} <command> [options]
18
+
19
+ Commands:
20
+ list Show every skill available in this repository
21
+ add [<skill>...] Install skills into tools' skills folders
22
+ remove [<skill>...] Remove skills that agent-skills installed
23
+
24
+ Options:
25
+ --tool <ids> Comma-separated tools: ${TOOL_IDS.join(", ")}
26
+ --scope <scope> user (default, home folder) or project (current folder)
27
+ --force add: replace a skill folder that already exists
28
+ --yes, -y Skip the confirmation summary
29
+ --dry-run Show what would change, change nothing
30
+ --json Print a JSON result on stdout, messages on stderr
31
+ --help, -h Show this help
32
+ --version, -v Show the version
33
+
34
+ In a terminal, add and remove ask for any skill, tool or scope not given.
35
+
36
+ Tools and folders (user scope | project scope):
37
+ ${TOOL_IDS.map((id) => ` ${id.padEnd(8)} ~/${TOOLS[id].user} | ./${TOOLS[id].project}`).join("\n")}
38
+ `;
39
+
40
+ /**
41
+ * @param {string[]} argv arguments after the program name
42
+ * @param {object} [io] injectable streams and environment (tests)
43
+ * @returns {Promise<number>} exit code
44
+ */
45
+ export async function main(argv, io = {}) {
46
+ const stdout = io.stdout ?? process.stdout;
47
+ const stderr = io.stderr ?? process.stderr;
48
+ const stdin = io.stdin ?? process.stdin;
49
+ const env = { home: io.home ?? homedir(), cwd: io.cwd ?? process.cwd() };
50
+ const root = io.root ?? process.env.AGENT_SKILLS_ROOT ?? PACKAGE_ROOT;
51
+ const interactive = io.interactive ?? Boolean(stdin.isTTY && stderr.isTTY);
52
+ const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
53
+
54
+ let args;
55
+ try {
56
+ args = parseArgs({
57
+ args: argv,
58
+ allowPositionals: true,
59
+ options: {
60
+ tool: { type: "string" },
61
+ scope: { type: "string" },
62
+ force: { type: "boolean", default: false },
63
+ yes: { type: "boolean", short: "y", default: false },
64
+ "dry-run": { type: "boolean", default: false },
65
+ json: { type: "boolean", default: false },
66
+ help: { type: "boolean", short: "h", default: false },
67
+ version: { type: "boolean", short: "v", default: false },
68
+ },
69
+ });
70
+ } catch (e) {
71
+ stderr.write(`${e.message}\nRun with --help for usage.\n`);
72
+ return EXIT.USAGE;
73
+ }
74
+ const { values: opts, positionals } = args;
75
+ const [command, ...names] = positionals;
76
+ const json = opts.json;
77
+ const say = (line) => (json ? stderr : stdout).write(line + "\n");
78
+ const ask = { input: stdin, output: stderr };
79
+
80
+ if (opts.version) return stdout.write(version + "\n"), EXIT.OK;
81
+ if (opts.help || !command) {
82
+ (opts.help ? stdout : stderr).write(HELP);
83
+ return opts.help ? EXIT.OK : EXIT.USAGE;
84
+ }
85
+
86
+ const catalog = findSkills(root);
87
+ const byName = new Map(catalog.map((s) => [s.name, s]));
88
+
89
+ try {
90
+ if (command === "list") {
91
+ if (json) stdout.write(JSON.stringify(catalog.map(({ name, plugin, description }) => ({ name, plugin, description }))) + "\n");
92
+ else if (!catalog.length) stdout.write("No skills available yet.\n");
93
+ else {
94
+ const width = Math.max(...catalog.map((s) => s.name.length));
95
+ for (const s of catalog) stdout.write(`${s.name.padEnd(width)} ${s.plugin} ${s.description}\n`);
96
+ }
97
+ return EXIT.OK;
98
+ }
99
+ if (command !== "add" && command !== "remove") throw new UsageError(`Unknown command "${command}". Run with --help for usage.`);
100
+
101
+ const unknown = names.filter((n) => !byName.has(n));
102
+ if (unknown.length)
103
+ throw new UsageError(`Unknown skill: ${unknown.join(", ")}. Run "agent-skills list" to see the available skills.`);
104
+
105
+ // Tools
106
+ let tools = opts.tool ? [...new Set(opts.tool.split(",").map((a) => a.trim()).filter(Boolean))] : null;
107
+ if (tools) {
108
+ const bad = tools.filter((a) => !TOOLS[a]);
109
+ if (bad.length) throw new UsageError(`Unknown tool: ${bad.join(", ")}. Supported tools: ${TOOL_IDS.join(", ")}.`);
110
+ }
111
+ if (opts.scope && !SCOPES.includes(opts.scope))
112
+ throw new UsageError(`Unknown scope "${opts.scope}". Use "user" or "project".`);
113
+
114
+ const detected = detectTools(env.home);
115
+ const askTools = async () => {
116
+ if (tools) return tools;
117
+ if (!interactive)
118
+ throw new UsageError(
119
+ `Missing --tool. Detected tools: ${detected.join(", ") || "none"}. ` +
120
+ `Example: --tool ${detected[0] ?? "claude"}. Supported: ${TOOL_IDS.join(", ")}.`,
121
+ );
122
+ return prompts.checkbox({
123
+ ...ask,
124
+ message: command === "add" ? "Install for which tools?" : "Remove from which tools?",
125
+ choices: TOOL_IDS.map((id) => ({ value: id, label: TOOLS[id].label, hint: id, checked: detected.includes(id) })),
126
+ });
127
+ };
128
+ const askScope = async () => {
129
+ if (opts.scope) return opts.scope;
130
+ if (!interactive) return "user";
131
+ return prompts.select({
132
+ ...ask,
133
+ message: "Scope?",
134
+ initial: "user",
135
+ choices: [
136
+ { value: "user", label: "user", hint: "your home folder, all projects" },
137
+ { value: "project", label: "project", hint: `this folder (${env.cwd})` },
138
+ ],
139
+ });
140
+ };
141
+ const askSkills = async (choices, emptyMessage) => {
142
+ if (names.length) return names;
143
+ if (!interactive)
144
+ throw new UsageError(
145
+ `Missing skill name. Available skills: ${catalog.map((s) => s.name).join(", ") || "none"}.`,
146
+ );
147
+ if (!choices.length) return say(emptyMessage), [];
148
+ return prompts.checkbox({
149
+ ...ask,
150
+ message: command === "add" ? "Which skills do you want to install?" : "Which skills do you want to remove?",
151
+ choices: choices.map((s) => ({ value: s.name, label: s.name, hint: s.description })),
152
+ });
153
+ };
154
+
155
+ let skills, scope;
156
+ if (command === "add") {
157
+ skills = await askSkills(catalog, "No skills available yet.");
158
+ if (skills === null || !skills.length) return cancelled(stderr, skills);
159
+ tools = await askTools();
160
+ if (tools === null || !tools.length) return cancelled(stderr, tools);
161
+ scope = await askScope();
162
+ if (scope === null) return cancelled(stderr, null);
163
+ } else {
164
+ tools = await askTools();
165
+ if (tools === null || !tools.length) return cancelled(stderr, tools);
166
+ scope = await askScope();
167
+ if (scope === null) return cancelled(stderr, null);
168
+ const installed = installedSkills(catalog, tools, scope, env);
169
+ skills = await askSkills(installed, `No skills installed by agent-skills for ${tools.join(", ")} at ${scope} scope.`);
170
+ if (skills === null) return cancelled(stderr, null);
171
+ if (!skills.length) {
172
+ if (installed.length) return cancelled(stderr, []);
173
+ if (json) stdout.write(JSON.stringify({ ok: true, results: [], notes: [] }) + "\n");
174
+ return EXIT.OK;
175
+ }
176
+ }
177
+
178
+ const targets = planTargets(skills.map((n) => byName.get(n)), tools, scope, env);
179
+ const dryRun = opts["dry-run"];
180
+
181
+ if (interactive && !opts.yes && !dryRun) {
182
+ const verb = command === "add" ? "Install" : "Remove";
183
+ stderr.write(`\n${verb} ${skills.length} skill(s) for ${tools.join(", ")} at ${scope} scope:\n`);
184
+ for (const t of targets) stderr.write(` ${t.path}\n`);
185
+ const ok = await prompts.confirm({ ...ask, message: "Continue?" });
186
+ if (!ok) return cancelled(stderr, null);
187
+ }
188
+
189
+ const results = targets.map((t) => {
190
+ const r = command === "add" ? install(t, { force: opts.force, dryRun, version }) : remove(t, { dryRun });
191
+ return { skill: t.skill.name, tools: t.tools, path: t.path, ...r };
192
+ });
193
+ const ok = results.every((r) => OK_STATUSES.has(r.status));
194
+
195
+ const notes = [];
196
+ if (command === "add" && results.some((r) => OK_STATUSES.has(r.status))) {
197
+ for (const o of overlaps(tools, scope))
198
+ notes.push(`${TOOLS[o.reader].label} also reads ${o.path}, so it may list skills installed for ${o.other} twice.`);
199
+ for (const a of tools) if (TOOLS[a].note) notes.push(TOOLS[a].note);
200
+ }
201
+
202
+ if (json) stdout.write(JSON.stringify({ ok, results, notes }) + "\n");
203
+ else {
204
+ for (const r of results) stdout.write(`${r.status.padEnd(13)} ${r.path}${r.message ? ` (${r.message})` : ""}\n`);
205
+ }
206
+ for (const n of notes) say(`note: ${n}`);
207
+ return ok ? EXIT.OK : EXIT.FAILED;
208
+ } catch (e) {
209
+ if (e instanceof UsageError) {
210
+ if (json) stdout.write(JSON.stringify({ ok: false, error: e.message }) + "\n");
211
+ stderr.write(e.message + "\n");
212
+ return EXIT.USAGE;
213
+ }
214
+ throw e;
215
+ }
216
+ }
217
+
218
+ function cancelled(stderr, value) {
219
+ stderr.write(value === null ? "Cancelled.\n" : "Nothing selected. Cancelled.\n");
220
+ return EXIT.FAILED;
221
+ }
222
+