skiller 0.9.13 → 0.10.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.
@@ -1,907 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.readEnabledPlugins = readEnabledPlugins;
37
- exports.readInstalledPluginsIndex = readInstalledPluginsIndex;
38
- exports.resolvePluginInstall = resolvePluginInstall;
39
- exports.discoverPluginSkillDirs = discoverPluginSkillDirs;
40
- exports.discoverPluginCommandFiles = discoverPluginCommandFiles;
41
- exports.discoverPluginAgentFiles = discoverPluginAgentFiles;
42
- exports.syncClaudePluginsToSkillsDirs = syncClaudePluginsToSkillsDirs;
43
- const fs = __importStar(require("fs/promises"));
44
- const os = __importStar(require("os"));
45
- const path = __importStar(require("path"));
46
- const yaml = __importStar(require("js-yaml"));
47
- const constants_1 = require("../constants");
48
- const FrontmatterParser_1 = require("./FrontmatterParser");
49
- const SkillsUtils_1 = require("./SkillsUtils");
50
- const SkillsManifest_1 = require("./SkillsManifest");
51
- const LEGACY_MARKER_FILENAME = '.skiller-plugin.json';
52
- function getUserHomeDir() {
53
- // Prefer env vars so tests (and users) can override deterministically.
54
- return process.env.HOME || process.env.USERPROFILE || os.homedir();
55
- }
56
- function sanitizeId(value) {
57
- return value.replace(/[^A-Za-z0-9._-]+/g, '_');
58
- }
59
- function parseDate(dateStr) {
60
- if (!dateStr)
61
- return 0;
62
- const t = Date.parse(dateStr);
63
- return Number.isFinite(t) ? t : 0;
64
- }
65
- async function fileExists(p) {
66
- try {
67
- await fs.access(p);
68
- return true;
69
- }
70
- catch {
71
- return false;
72
- }
73
- }
74
- async function dirExists(p) {
75
- try {
76
- return (await fs.stat(p)).isDirectory();
77
- }
78
- catch {
79
- return false;
80
- }
81
- }
82
- function makeItemKey(pluginId, sourceKind, sourceRelPath) {
83
- return `${pluginId}::${sourceKind}::${sourceRelPath}`;
84
- }
85
- async function readEnabledPlugins(projectRoot) {
86
- const settingsPath = path.join(projectRoot, '.claude', 'settings.json');
87
- let raw;
88
- try {
89
- raw = JSON.parse(await fs.readFile(settingsPath, 'utf8'));
90
- }
91
- catch {
92
- return null;
93
- }
94
- if (!raw || typeof raw !== 'object')
95
- return [];
96
- const enabledPlugins = raw.enabledPlugins;
97
- if (!enabledPlugins || typeof enabledPlugins !== 'object')
98
- return [];
99
- return Object.entries(enabledPlugins)
100
- .filter(([, v]) => v === true)
101
- .map(([k]) => k);
102
- }
103
- async function readInstalledPluginsIndex(claudeDir) {
104
- const indexPath = path.join(claudeDir, 'plugins', 'installed_plugins.json');
105
- try {
106
- const raw = JSON.parse(await fs.readFile(indexPath, 'utf8'));
107
- if (!raw || typeof raw !== 'object')
108
- return null;
109
- const obj = raw;
110
- if (!obj.plugins || typeof obj.plugins !== 'object')
111
- return null;
112
- return raw;
113
- }
114
- catch {
115
- return null;
116
- }
117
- }
118
- function parsePluginId(pluginId) {
119
- // `pluginId` format is typically `<pluginName>@<marketplaceId>`.
120
- // Split by the last `@` so scoped names like `@org/foo@market` work.
121
- const at = pluginId.lastIndexOf('@');
122
- if (at <= 0 || at === pluginId.length - 1)
123
- return null;
124
- return {
125
- pluginName: pluginId.slice(0, at),
126
- marketplaceId: pluginId.slice(at + 1),
127
- };
128
- }
129
- async function resolvePluginMarketplaceRoot(pluginId, claudeDir) {
130
- const parsed = parsePluginId(pluginId);
131
- if (!parsed)
132
- return null;
133
- const marketplaceRoot = path.join(claudeDir, 'plugins', 'marketplaces', parsed.marketplaceId);
134
- const candidates = [
135
- path.join(marketplaceRoot, 'plugins', parsed.pluginName),
136
- path.join(marketplaceRoot, 'external_plugins', parsed.pluginName),
137
- path.join(marketplaceRoot, '.claude-plugin', 'plugins', parsed.pluginName),
138
- path.join(marketplaceRoot, '.claude-plugin', 'external_plugins', parsed.pluginName),
139
- ];
140
- for (const candidate of candidates) {
141
- if (await dirExists(candidate))
142
- return candidate;
143
- }
144
- return null;
145
- }
146
- async function hasPluginContent(root) {
147
- const candidates = [
148
- path.join(root, 'skills'),
149
- path.join(root, 'commands'),
150
- path.join(root, 'agents'),
151
- ];
152
- for (const candidate of candidates) {
153
- if (await dirExists(candidate))
154
- return true;
155
- }
156
- return false;
157
- }
158
- async function readPluginPackageManifestEntries(installPath) {
159
- const packageJsonPath = path.join(installPath, 'package.json');
160
- try {
161
- const raw = JSON.parse(await fs.readFile(packageJsonPath, 'utf8'));
162
- if (!Array.isArray(raw.plugins))
163
- return [];
164
- return raw.plugins.filter((entry) => Boolean(entry) && typeof entry === 'object');
165
- }
166
- catch {
167
- return [];
168
- }
169
- }
170
- async function resolveInstalledPluginSourceRoot(pluginId, installPath) {
171
- const manifestEntries = await readPluginPackageManifestEntries(installPath);
172
- const parsedPluginId = parsePluginId(pluginId);
173
- const matchingEntry = manifestEntries.find((entry) => entry.name === parsedPluginId?.pluginName) ?? (manifestEntries.length === 1 ? manifestEntries[0] : null);
174
- const rawSource = typeof matchingEntry?.source === 'string' &&
175
- matchingEntry.source.trim() !== ''
176
- ? matchingEntry.source
177
- : '.';
178
- const sourceRoot = path.resolve(installPath, rawSource);
179
- const normalizedInstallPath = path.resolve(installPath);
180
- const isWithinInstallPath = sourceRoot === normalizedInstallPath ||
181
- sourceRoot.startsWith(normalizedInstallPath + path.sep);
182
- if (isWithinInstallPath && (await hasPluginContent(sourceRoot))) {
183
- return sourceRoot;
184
- }
185
- if (await hasPluginContent(installPath)) {
186
- return installPath;
187
- }
188
- return null;
189
- }
190
- function resolvePluginInstall(pluginId, projectRoot, index) {
191
- const entries = index.plugins?.[pluginId];
192
- if (!entries || !Array.isArray(entries) || entries.length === 0)
193
- return null;
194
- const resolvedProjectRoot = path.resolve(projectRoot);
195
- const projectCandidates = entries
196
- .filter((e) => e && e.scope === 'project' && typeof e.projectPath === 'string')
197
- .filter((e) => {
198
- const pp = path.resolve(e.projectPath);
199
- return (resolvedProjectRoot === pp ||
200
- resolvedProjectRoot.startsWith(pp + path.sep));
201
- })
202
- .map((e) => ({
203
- entry: e,
204
- projectPath: path.resolve(e.projectPath),
205
- }));
206
- // Prefer the most specific projectPath match, then newest timestamp.
207
- if (projectCandidates.length > 0) {
208
- projectCandidates.sort((a, b) => {
209
- if (a.projectPath.length !== b.projectPath.length) {
210
- return b.projectPath.length - a.projectPath.length;
211
- }
212
- const at = parseDate(a.entry.lastUpdated) || parseDate(a.entry.installedAt);
213
- const bt = parseDate(b.entry.lastUpdated) || parseDate(b.entry.installedAt);
214
- return bt - at;
215
- });
216
- const chosen = projectCandidates[0].entry;
217
- return {
218
- pluginId,
219
- installPath: chosen.installPath,
220
- version: chosen.version,
221
- };
222
- }
223
- const userCandidates = entries.filter((e) => e && e.scope === 'user');
224
- if (userCandidates.length === 0) {
225
- // Fallback: if the plugin is installed for a different project but enabled
226
- // here, still use the newest available install. This avoids noisy
227
- // "not installed" warnings for plugins that don't ship skills/commands.
228
- const anyCandidates = entries.filter((e) => e && typeof e.installPath === 'string' && e.installPath.length > 0);
229
- if (anyCandidates.length === 0)
230
- return null;
231
- anyCandidates.sort((a, b) => {
232
- const at = parseDate(a.lastUpdated) || parseDate(a.installedAt);
233
- const bt = parseDate(b.lastUpdated) || parseDate(b.installedAt);
234
- return bt - at;
235
- });
236
- return {
237
- pluginId,
238
- installPath: anyCandidates[0].installPath,
239
- version: anyCandidates[0].version,
240
- };
241
- }
242
- userCandidates.sort((a, b) => {
243
- const at = parseDate(a.lastUpdated) || parseDate(a.installedAt);
244
- const bt = parseDate(b.lastUpdated) || parseDate(b.installedAt);
245
- return bt - at;
246
- });
247
- return {
248
- pluginId,
249
- installPath: userCandidates[0].installPath,
250
- version: userCandidates[0].version,
251
- };
252
- }
253
- async function discoverPluginSkillDirs(installPath) {
254
- const skillsRoot = path.join(installPath, 'skills');
255
- if (!(await fileExists(skillsRoot)))
256
- return [];
257
- const results = [];
258
- async function walk(current, depth) {
259
- if (depth >= constants_1.MAX_RECURSION_DEPTH)
260
- return;
261
- let entries;
262
- try {
263
- entries = await fs.readdir(current, { withFileTypes: true });
264
- }
265
- catch {
266
- return;
267
- }
268
- // Skill root if contains SKILL.md
269
- const hasSkillMd = entries.some((e) => e.isFile() && e.name === 'SKILL.md');
270
- if (hasSkillMd) {
271
- const relId = path.relative(skillsRoot, current).replace(/\\/g, '/');
272
- results.push({ relId, dir: current });
273
- return;
274
- }
275
- for (const entry of entries) {
276
- if (!entry.isDirectory())
277
- continue;
278
- await walk(path.join(current, entry.name), depth + 1);
279
- }
280
- }
281
- await walk(skillsRoot, 0);
282
- return results;
283
- }
284
- async function discoverPluginCommandFiles(installPath) {
285
- const commandsRoot = path.join(installPath, 'commands');
286
- if (!(await fileExists(commandsRoot)))
287
- return [];
288
- const results = [];
289
- async function walk(current, depth) {
290
- if (depth >= constants_1.MAX_RECURSION_DEPTH)
291
- return;
292
- let entries;
293
- try {
294
- entries = await fs.readdir(current, { withFileTypes: true });
295
- }
296
- catch {
297
- return;
298
- }
299
- for (const entry of entries) {
300
- const full = path.join(current, entry.name);
301
- if (entry.isDirectory()) {
302
- await walk(full, depth + 1);
303
- continue;
304
- }
305
- if (!entry.isFile() || !entry.name.endsWith('.md'))
306
- continue;
307
- const rel = path.relative(commandsRoot, full).replace(/\\/g, '/');
308
- results.push({ rel, file: full });
309
- }
310
- }
311
- await walk(commandsRoot, 0);
312
- return results;
313
- }
314
- async function discoverPluginAgentFiles(installPath) {
315
- const agentsRoot = path.join(installPath, 'agents');
316
- if (!(await fileExists(agentsRoot)))
317
- return [];
318
- const results = [];
319
- async function walk(current, depth) {
320
- if (depth >= constants_1.MAX_RECURSION_DEPTH)
321
- return;
322
- let entries;
323
- try {
324
- entries = await fs.readdir(current, { withFileTypes: true });
325
- }
326
- catch {
327
- return;
328
- }
329
- for (const entry of entries) {
330
- const full = path.join(current, entry.name);
331
- if (entry.isDirectory()) {
332
- await walk(full, depth + 1);
333
- continue;
334
- }
335
- if (!entry.isFile() || !entry.name.endsWith('.md'))
336
- continue;
337
- let content;
338
- try {
339
- content = await fs.readFile(full, 'utf8');
340
- }
341
- catch {
342
- continue;
343
- }
344
- const parsed = (0, FrontmatterParser_1.parseFrontmatter)(content);
345
- const fmName = parsed.rawFrontmatter && typeof parsed.rawFrontmatter.name === 'string'
346
- ? parsed.rawFrontmatter.name
347
- : parsed.frontmatter?.name;
348
- if (typeof fmName !== 'string' || fmName.trim() === '')
349
- continue;
350
- const rel = path.relative(agentsRoot, full).replace(/\\/g, '/');
351
- results.push({ name: fmName.trim(), file: full, rel });
352
- }
353
- }
354
- await walk(agentsRoot, 0);
355
- return results;
356
- }
357
- function generateBaseNameFromRelId(relId) {
358
- const normalized = relId.replace(/\\/g, '/');
359
- const segments = normalized.split('/').filter(Boolean);
360
- return segments.map(sanitizeId).join('-');
361
- }
362
- function generateBaseNameFromCommandRelPath(commandRelPath) {
363
- const normalized = commandRelPath.replace(/\\/g, '/');
364
- const withoutExt = normalized.endsWith('.md')
365
- ? normalized.slice(0, -'.md'.length)
366
- : normalized;
367
- const segments = withoutExt.split('/').filter(Boolean);
368
- return segments.map(sanitizeId).join('-');
369
- }
370
- function pluginBaseNamespacePrefix(pluginId) {
371
- const parsed = parsePluginId(pluginId);
372
- if (parsed)
373
- return sanitizeId(parsed.pluginName);
374
- return sanitizeId(pluginId);
375
- }
376
- function computePluginNamespacePrefixes(pluginIds) {
377
- const out = new Map();
378
- const pluginIdsByBase = new Map();
379
- for (const pluginId of pluginIds) {
380
- const base = pluginBaseNamespacePrefix(pluginId);
381
- const bucket = pluginIdsByBase.get(base) ?? [];
382
- bucket.push(pluginId);
383
- pluginIdsByBase.set(base, bucket);
384
- }
385
- for (const [base, ids] of pluginIdsByBase.entries()) {
386
- ids.sort((a, b) => a.localeCompare(b));
387
- if (ids.length === 1) {
388
- out.set(ids[0], base);
389
- continue;
390
- }
391
- // If multiple enabled plugins share the same plugin name, disambiguate
392
- // without including the marketplace in the folder name.
393
- ids.forEach((id, idx) => {
394
- out.set(id, idx === 0 ? base : `${base}-${idx + 1}`);
395
- });
396
- }
397
- return out;
398
- }
399
- async function readLegacyMarkerFile(dir) {
400
- const markerPath = path.join(dir, LEGACY_MARKER_FILENAME);
401
- try {
402
- const raw = JSON.parse(await fs.readFile(markerPath, 'utf8'));
403
- if (!raw || typeof raw !== 'object')
404
- return null;
405
- const obj = raw;
406
- if (typeof obj.pluginId !== 'string')
407
- return null;
408
- if (typeof obj.generatedName !== 'string')
409
- return null;
410
- if (obj.sourceKind !== 'skill' &&
411
- obj.sourceKind !== 'command' &&
412
- obj.sourceKind !== 'agent')
413
- return null;
414
- if (typeof obj.sourceRelPath !== 'string')
415
- return null;
416
- const pluginVersion = typeof obj.pluginVersion === 'string' ? obj.pluginVersion : undefined;
417
- return {
418
- pluginId: obj.pluginId,
419
- pluginVersion,
420
- sourceKind: obj.sourceKind,
421
- sourceRelPath: obj.sourceRelPath,
422
- generatedName: obj.generatedName,
423
- };
424
- }
425
- catch {
426
- return null;
427
- }
428
- }
429
- async function removeLegacyMarkerFile(dir, dryRun) {
430
- const markerPath = path.join(dir, LEGACY_MARKER_FILENAME);
431
- if (dryRun)
432
- return;
433
- try {
434
- await fs.unlink(markerPath);
435
- }
436
- catch {
437
- // ignore
438
- }
439
- }
440
- async function loadManagedEntries(projectRoot, targetSkillsDir, dryRun) {
441
- const allEntries = await (0, SkillsManifest_1.loadSkillsManifestEntries)(projectRoot, targetSkillsDir);
442
- const pluginEntries = [];
443
- const otherEntries = [];
444
- for (const entry of allEntries) {
445
- if ((0, SkillsManifest_1.isPluginManifestEntry)(entry)) {
446
- pluginEntries.push(entry);
447
- }
448
- else {
449
- otherEntries.push(entry);
450
- }
451
- }
452
- // Migration: absorb legacy per-skill markers and remove them so they don't
453
- // show up in every skill folder.
454
- let dirents;
455
- try {
456
- dirents = await fs.readdir(targetSkillsDir, { withFileTypes: true });
457
- }
458
- catch {
459
- return { pluginEntries, otherEntries };
460
- }
461
- for (const dirent of dirents) {
462
- if (!dirent.isDirectory())
463
- continue;
464
- const folder = path.join(targetSkillsDir, dirent.name);
465
- const legacy = await readLegacyMarkerFile(folder);
466
- if (!legacy)
467
- continue;
468
- const managed = {
469
- sourceType: 'plugin',
470
- pluginId: legacy.pluginId,
471
- pluginVersion: legacy.pluginVersion,
472
- sourceKind: legacy.sourceKind,
473
- sourceRelPath: legacy.sourceRelPath,
474
- destRelPath: dirent.name,
475
- };
476
- const already = pluginEntries.some((e) => e.destRelPath === managed.destRelPath &&
477
- e.pluginId === managed.pluginId &&
478
- e.sourceKind === managed.sourceKind &&
479
- e.sourceRelPath === managed.sourceRelPath);
480
- if (!already) {
481
- pluginEntries.push(managed);
482
- }
483
- await removeLegacyMarkerFile(folder, dryRun);
484
- }
485
- return { pluginEntries, otherEntries };
486
- }
487
- async function discoverLocalSkillNames(projectRoot) {
488
- return new Set(await (0, SkillsManifest_1.loadLocalSkillNames)(projectRoot));
489
- }
490
- async function discoverLocalCommandNames(projectRoot) {
491
- const localCommandsDir = path.join(projectRoot, '.claude', 'commands');
492
- if (!(await fileExists(localCommandsDir)))
493
- return new Set();
494
- const names = new Set();
495
- async function walk(current, depth) {
496
- if (depth >= constants_1.MAX_RECURSION_DEPTH)
497
- return;
498
- let entries;
499
- try {
500
- entries = await fs.readdir(current, { withFileTypes: true });
501
- }
502
- catch {
503
- return;
504
- }
505
- for (const entry of entries) {
506
- const full = path.join(current, entry.name);
507
- if (entry.isDirectory()) {
508
- await walk(full, depth + 1);
509
- continue;
510
- }
511
- if (!entry.isFile() || !entry.name.endsWith('.md'))
512
- continue;
513
- const rel = path.relative(localCommandsDir, full).replace(/\\/g, '/');
514
- const withoutExt = rel.endsWith('.md')
515
- ? rel.slice(0, -'.md'.length)
516
- : rel;
517
- const segments = withoutExt.split('/').filter(Boolean);
518
- names.add(segments.map(sanitizeId).join('-'));
519
- }
520
- }
521
- await walk(localCommandsDir, 0);
522
- return names;
523
- }
524
- async function discoverLocalAgentNames(projectRoot) {
525
- const localAgentsDir = path.join(projectRoot, '.claude', 'agents');
526
- if (!(await fileExists(localAgentsDir)))
527
- return new Set();
528
- const names = new Set();
529
- async function walk(current, depth) {
530
- if (depth >= constants_1.MAX_RECURSION_DEPTH)
531
- return;
532
- let entries;
533
- try {
534
- entries = await fs.readdir(current, { withFileTypes: true });
535
- }
536
- catch {
537
- return;
538
- }
539
- for (const entry of entries) {
540
- const full = path.join(current, entry.name);
541
- if (entry.isDirectory()) {
542
- await walk(full, depth + 1);
543
- continue;
544
- }
545
- if (!entry.isFile() || !entry.name.endsWith('.md'))
546
- continue;
547
- let content;
548
- try {
549
- content = await fs.readFile(full, 'utf8');
550
- }
551
- catch {
552
- continue;
553
- }
554
- const parsed = (0, FrontmatterParser_1.parseFrontmatter)(content);
555
- const fmName = parsed.rawFrontmatter && typeof parsed.rawFrontmatter.name === 'string'
556
- ? parsed.rawFrontmatter.name
557
- : parsed.frontmatter?.name;
558
- if (typeof fmName !== 'string' || fmName.trim() === '')
559
- continue;
560
- names.add(sanitizeId(fmName.trim()));
561
- }
562
- }
563
- await walk(localAgentsDir, 0);
564
- return names;
565
- }
566
- async function ensureDir(dir, dryRun) {
567
- if (dryRun)
568
- return;
569
- await fs.mkdir(dir, { recursive: true });
570
- }
571
- async function removeDir(dir, dryRun) {
572
- if (dryRun)
573
- return;
574
- await fs.rm(dir, { recursive: true, force: true });
575
- }
576
- async function rewriteSkillMdName(skillMdPath, name, pluginId, dryRun) {
577
- let content;
578
- try {
579
- content = await fs.readFile(skillMdPath, 'utf8');
580
- }
581
- catch {
582
- return;
583
- }
584
- const { rawFrontmatter, body } = (0, FrontmatterParser_1.parseFrontmatter)(content);
585
- const fm = rawFrontmatter
586
- ? { ...rawFrontmatter }
587
- : {};
588
- fm.name = name;
589
- if (typeof fm.description !== 'string' || fm.description.trim() === '') {
590
- fm.description = `Plugin skill from ${pluginId}`;
591
- }
592
- const next = `---\n${yaml
593
- .dump(fm, { lineWidth: -1, noRefs: true })
594
- .trim()}\n---\n\n${body}\n`;
595
- if (dryRun)
596
- return;
597
- await fs.writeFile(skillMdPath, next, 'utf8');
598
- }
599
- async function writeMarkdownAsSkill(srcMarkdownPath, destDir, generatedName, pluginId, kindLabel, dryRun) {
600
- const content = await fs.readFile(srcMarkdownPath, 'utf8');
601
- const { rawFrontmatter, body } = (0, FrontmatterParser_1.parseFrontmatter)(content);
602
- const fm = rawFrontmatter
603
- ? { ...rawFrontmatter }
604
- : {};
605
- fm.name = generatedName;
606
- if (typeof fm.description !== 'string' || fm.description.trim() === '') {
607
- fm.description = `${kindLabel} from ${pluginId}: ${path.basename(srcMarkdownPath, '.md')}`;
608
- }
609
- const next = `---\n${yaml
610
- .dump(fm, { lineWidth: -1, noRefs: true })
611
- .trim()}\n---\n\n${body}\n`;
612
- if (dryRun)
613
- return;
614
- await fs.writeFile(path.join(destDir, 'SKILL.md'), next, 'utf8');
615
- }
616
- async function syncClaudePluginsToSkillsDirs(args) {
617
- const { projectRoot, targetSkillsDirs, verbose, dryRun } = args;
618
- const enabledPlugins = await readEnabledPlugins(projectRoot);
619
- if (enabledPlugins === null) {
620
- // Fail-safe: no project settings.json (or invalid) => no sync, no cleanup.
621
- return;
622
- }
623
- const claudeDir = path.join(getUserHomeDir(), '.claude');
624
- const index = await readInstalledPluginsIndex(claudeDir);
625
- const localSkillNames = await discoverLocalSkillNames(projectRoot);
626
- const localCommandNames = await discoverLocalCommandNames(projectRoot);
627
- const localAgentNames = await discoverLocalAgentNames(projectRoot);
628
- const localReservedNames = new Set([
629
- ...localSkillNames,
630
- ...localCommandNames,
631
- ...localAgentNames,
632
- ]);
633
- const resolvedSources = [];
634
- const unresolvedEnabled = new Set();
635
- for (const pluginId of enabledPlugins) {
636
- const resolved = index
637
- ? resolvePluginInstall(pluginId, projectRoot, index)
638
- : null;
639
- const marketplaceRoot = await resolvePluginMarketplaceRoot(pluginId, claudeDir);
640
- const pluginRoot = (marketplaceRoot && (await hasPluginContent(marketplaceRoot))
641
- ? marketplaceRoot
642
- : null) ??
643
- (resolved
644
- ? await resolveInstalledPluginSourceRoot(pluginId, resolved.installPath)
645
- : null);
646
- if (!pluginRoot) {
647
- unresolvedEnabled.add(pluginId);
648
- const hasIndexEntry = Boolean(index?.plugins?.[pluginId]?.length);
649
- if (hasIndexEntry) {
650
- (0, constants_1.logVerboseInfo)(`[plugins] Enabled plugin has no syncable content, skipping: ${pluginId}`, verbose, dryRun);
651
- }
652
- else {
653
- (0, constants_1.logWarn)(`[plugins] Enabled plugin not installed: ${pluginId}`, dryRun);
654
- }
655
- continue;
656
- }
657
- resolvedSources.push({
658
- pluginId,
659
- pluginRoot,
660
- version: resolved?.version,
661
- });
662
- }
663
- const expectedItems = [];
664
- for (const plugin of resolvedSources) {
665
- const skillDirs = await discoverPluginSkillDirs(plugin.pluginRoot);
666
- for (const s of skillDirs) {
667
- const baseName = generateBaseNameFromRelId(s.relId);
668
- const sourceRelPath = `skills/${s.relId}`;
669
- expectedItems.push({
670
- itemKey: makeItemKey(plugin.pluginId, 'skill', sourceRelPath),
671
- pluginId: plugin.pluginId,
672
- pluginVersion: plugin.version,
673
- kind: 'skill',
674
- sourcePath: s.dir,
675
- sourceRelPath,
676
- baseName,
677
- });
678
- }
679
- const commandFiles = await discoverPluginCommandFiles(plugin.pluginRoot);
680
- for (const c of commandFiles) {
681
- const baseName = generateBaseNameFromCommandRelPath(c.rel);
682
- const sourceRelPath = `commands/${c.rel}`;
683
- expectedItems.push({
684
- itemKey: makeItemKey(plugin.pluginId, 'command', sourceRelPath),
685
- pluginId: plugin.pluginId,
686
- pluginVersion: plugin.version,
687
- kind: 'command',
688
- sourcePath: c.file,
689
- sourceRelPath,
690
- baseName,
691
- });
692
- }
693
- const agentFiles = await discoverPluginAgentFiles(plugin.pluginRoot);
694
- for (const a of agentFiles) {
695
- const baseName = sanitizeId(a.name);
696
- const sourceRelPath = `agents/${a.rel}`;
697
- expectedItems.push({
698
- itemKey: makeItemKey(plugin.pluginId, 'agent', sourceRelPath),
699
- pluginId: plugin.pluginId,
700
- pluginVersion: plugin.version,
701
- kind: 'agent',
702
- sourcePath: a.file,
703
- sourceRelPath,
704
- baseName,
705
- });
706
- }
707
- }
708
- const sortedItems = [...expectedItems].sort((a, b) => {
709
- const ak = `${a.baseName}::${a.pluginId}::${a.kind}::${a.sourceRelPath}`;
710
- const bk = `${b.baseName}::${b.pluginId}::${b.kind}::${b.sourceRelPath}`;
711
- return ak.localeCompare(bk);
712
- });
713
- const pluginNamespacePrefixByPluginId = computePluginNamespacePrefixes([
714
- ...new Set(resolvedSources.map((p) => p.pluginId)),
715
- ]);
716
- // Sync into each target skills dir.
717
- for (const targetSkillsDir of targetSkillsDirs) {
718
- const targetExists = await fileExists(targetSkillsDir);
719
- if (!targetExists && sortedItems.length === 0)
720
- continue;
721
- let managedEntries = [];
722
- let otherEntries = [];
723
- if (targetExists) {
724
- const loaded = await loadManagedEntries(projectRoot, targetSkillsDir, dryRun);
725
- managedEntries = loaded.pluginEntries;
726
- otherEntries = loaded.otherEntries;
727
- }
728
- // Map previous destinations by itemKey for stability.
729
- const prevDestByItemKey = new Map();
730
- for (const entry of managedEntries) {
731
- prevDestByItemKey.set(makeItemKey(entry.pluginId, entry.sourceKind, entry.sourceRelPath), entry.destRelPath);
732
- }
733
- const managedDest = new Set(managedEntries.map((e) => e.destRelPath));
734
- // Reserve: local skills always win. Also reserve any existing non-managed folders.
735
- const reserved = new Set(localReservedNames);
736
- if (targetExists) {
737
- let dirents = [];
738
- try {
739
- dirents = await fs.readdir(targetSkillsDir, { withFileTypes: true });
740
- }
741
- catch {
742
- dirents = [];
743
- }
744
- for (const d of dirents) {
745
- if (!d.isDirectory())
746
- continue;
747
- if (!managedDest.has(d.name)) {
748
- reserved.add(d.name);
749
- }
750
- }
751
- }
752
- // Assign destinations.
753
- const taken = new Set(reserved);
754
- const assignedDestByItemKey = new Map();
755
- // First pass: preserve previous dest if available.
756
- for (const item of sortedItems) {
757
- const prev = prevDestByItemKey.get(item.itemKey);
758
- if (!prev)
759
- continue;
760
- const desiredPrefix = pluginNamespacePrefixByPluginId.get(item.pluginId) ??
761
- sanitizeId(item.pluginId);
762
- const currentNamespacedBase = `${desiredPrefix}-${item.baseName}`;
763
- // Migration: previous versions used `${pluginId}__${name}`, then
764
- // `${pluginId}-${name}`. If we changed the namespace prefix (for example
765
- // to omit marketplace), don't preserve the old destination so the item
766
- // can be renamed.
767
- if (prev.startsWith(`${sanitizeId(item.pluginId)}__`))
768
- continue;
769
- if (prev.startsWith(`${sanitizeId(item.pluginId)}-`) &&
770
- desiredPrefix !== sanitizeId(item.pluginId))
771
- continue;
772
- // If the item was previously namespaced only because its base name was
773
- // unavailable, drop that sticky destination once the base name is free.
774
- if ((prev === currentNamespacedBase ||
775
- prev.startsWith(`${currentNamespacedBase}-`)) &&
776
- !taken.has(item.baseName)) {
777
- continue;
778
- }
779
- if (reserved.has(item.baseName) &&
780
- (prev === currentNamespacedBase ||
781
- prev.startsWith(`${currentNamespacedBase}-`))) {
782
- continue;
783
- }
784
- if (taken.has(prev))
785
- continue;
786
- assignedDestByItemKey.set(item.itemKey, prev);
787
- taken.add(prev);
788
- }
789
- // Second pass: use baseName if possible, otherwise namespace.
790
- for (const item of sortedItems) {
791
- if (assignedDestByItemKey.has(item.itemKey))
792
- continue;
793
- const base = item.baseName;
794
- if (!taken.has(base)) {
795
- assignedDestByItemKey.set(item.itemKey, base);
796
- taken.add(base);
797
- continue;
798
- }
799
- if (reserved.has(base)) {
800
- continue;
801
- }
802
- const namespacedBase = `${pluginNamespacePrefixByPluginId.get(item.pluginId) ?? sanitizeId(item.pluginId)}-${base}`;
803
- let candidate = namespacedBase;
804
- let i = 2;
805
- while (taken.has(candidate)) {
806
- candidate = `${namespacedBase}-${i++}`;
807
- }
808
- assignedDestByItemKey.set(item.itemKey, candidate);
809
- taken.add(candidate);
810
- }
811
- const assignedItems = sortedItems.flatMap((item) => {
812
- const destRelPath = assignedDestByItemKey.get(item.itemKey);
813
- if (!destRelPath)
814
- return [];
815
- return [{ ...item, destRelPath }];
816
- });
817
- // Install/update expected items
818
- if (assignedItems.length > 0) {
819
- await ensureDir(targetSkillsDir, dryRun);
820
- }
821
- for (const item of assignedItems) {
822
- const destRelPath = item.destRelPath;
823
- const destDir = path.join(targetSkillsDir, destRelPath);
824
- if (await fileExists(destDir)) {
825
- // Only overwrite if it's skiller-managed for this target.
826
- if (!managedDest.has(destRelPath)) {
827
- // Should not happen due to reserved/taken logic; keep as a safety net.
828
- (0, constants_1.logWarn)(`[plugins] Destination exists but is not skiller-managed, skipping: ${destDir}`, dryRun);
829
- continue;
830
- }
831
- (0, constants_1.logVerboseInfo)(dryRun
832
- ? `DRY RUN: Would update plugin skill '${destRelPath}' in ${targetSkillsDir}`
833
- : `Updating plugin skill '${destRelPath}' in ${targetSkillsDir}`, verbose, dryRun);
834
- await removeDir(destDir, dryRun);
835
- }
836
- if (item.kind === 'skill') {
837
- (0, constants_1.logVerboseInfo)(dryRun
838
- ? `DRY RUN: Would install plugin skill '${destRelPath}' to ${targetSkillsDir}`
839
- : `Installing plugin skill '${destRelPath}' to ${targetSkillsDir}`, verbose, dryRun);
840
- if (!dryRun) {
841
- await (0, SkillsUtils_1.copySkillsDirectory)(item.sourcePath, destDir);
842
- }
843
- await rewriteSkillMdName(path.join(destDir, 'SKILL.md'), destRelPath, item.pluginId, dryRun);
844
- // Remove any leftover legacy marker file from older versions.
845
- await removeLegacyMarkerFile(destDir, dryRun);
846
- }
847
- else {
848
- const kindLabel = item.kind === 'command' ? 'command' : 'agent';
849
- (0, constants_1.logVerboseInfo)(dryRun
850
- ? `DRY RUN: Would install plugin ${kindLabel} '${destRelPath}' as skill to ${targetSkillsDir}`
851
- : `Installing plugin ${kindLabel} '${destRelPath}' as skill to ${targetSkillsDir}`, verbose, dryRun);
852
- await ensureDir(destDir, dryRun);
853
- if (!dryRun) {
854
- await writeMarkdownAsSkill(item.sourcePath, destDir, destRelPath, item.pluginId, item.kind === 'command' ? 'Command' : 'Agent', dryRun);
855
- }
856
- await removeLegacyMarkerFile(destDir, dryRun);
857
- }
858
- }
859
- // Cleanup stale managed folders (from manifest/legacy).
860
- const expectedDest = new Set(assignedItems.map((i) => i.destRelPath));
861
- const nextEntries = [];
862
- for (const entry of managedEntries) {
863
- const isEnabled = enabledPlugins.includes(entry.pluginId);
864
- const unresolved = unresolvedEnabled.has(entry.pluginId);
865
- const shouldKeepBecauseUnresolved = isEnabled && unresolved;
866
- if (shouldKeepBecauseUnresolved) {
867
- nextEntries.push(entry);
868
- continue;
869
- }
870
- if (!isEnabled) {
871
- if (reserved.has(entry.destRelPath)) {
872
- // Local/user took over the name; stop managing it but don't delete.
873
- continue;
874
- }
875
- (0, constants_1.logVerboseInfo)(dryRun
876
- ? `DRY RUN: Would remove stale plugin skill '${entry.destRelPath}' from ${targetSkillsDir}`
877
- : `Removing stale plugin skill '${entry.destRelPath}' from ${targetSkillsDir}`, verbose, dryRun);
878
- await removeDir(path.join(targetSkillsDir, entry.destRelPath), dryRun);
879
- continue;
880
- }
881
- if (!expectedDest.has(entry.destRelPath)) {
882
- if (reserved.has(entry.destRelPath)) {
883
- // Local/user took over the name; stop managing it but don't delete.
884
- continue;
885
- }
886
- (0, constants_1.logVerboseInfo)(dryRun
887
- ? `DRY RUN: Would remove stale plugin skill '${entry.destRelPath}' from ${targetSkillsDir}`
888
- : `Removing stale plugin skill '${entry.destRelPath}' from ${targetSkillsDir}`, verbose, dryRun);
889
- await removeDir(path.join(targetSkillsDir, entry.destRelPath), dryRun);
890
- continue;
891
- }
892
- // Still expected; we'll re-add it below as part of nextEntries generation.
893
- }
894
- // Add expected entries for installed items
895
- for (const item of assignedItems) {
896
- nextEntries.push({
897
- sourceType: 'plugin',
898
- pluginId: item.pluginId,
899
- pluginVersion: item.pluginVersion,
900
- sourceKind: item.kind,
901
- sourceRelPath: item.sourceRelPath,
902
- destRelPath: item.destRelPath,
903
- });
904
- }
905
- await (0, SkillsManifest_1.writeSkillsManifestEntries)(projectRoot, targetSkillsDir, [...otherEntries, ...nextEntries], dryRun);
906
- }
907
- }