@rbbtsn0w/adg 0.8.0-beta.3 → 0.8.0-beta.5

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,10 +1,32 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { gunzipSync, inflateRawSync } from 'node:zlib';
2
+ import { gunzipSync } from 'node:zlib';
3
+ import { readZipArchive } from "../archive.js";
3
4
  import { parseFrontmatter } from "../frontmatter.js";
4
5
  import { sanitizeMetadata } from "../sanitize.js";
6
+ import { shouldInstallInternalSkills } from "../skills.js";
5
7
  const DISCOVERY_SCHEMA_V2 = 'https://schemas.agentskills.io/discovery/0.2.0/schema.json';
6
8
  const MAX_ARCHIVE_UNPACKED_BYTES = 50 * 1024 * 1024;
7
9
  const MAX_ARCHIVE_FILES = 1000;
10
+ const DISCOVERY_TIMEOUT_MS = 10_000;
11
+ /**
12
+ * Thrown when a path-scoped URL (for example https://host/s/my-list) has no
13
+ * usable skills under that path while the host does publish a root index.
14
+ * Falling back to the root index in that situation used to install the
15
+ * host's entire catalog, so the caller must surface the unresolved scope
16
+ * instead of installing anything.
17
+ */
18
+ export class WellKnownScopeNotFoundError extends Error {
19
+ scopePath;
20
+ rootUrl;
21
+ constructor(scopePath, rootUrl) {
22
+ super(`No skills found for the scoped path '${scopePath}' on ${rootUrl}. ` +
23
+ `Not falling back to the root skills index because that would install every skill the host publishes. ` +
24
+ `Check the URL, or run 'skills add ${rootUrl}' to install from the root index.`);
25
+ this.name = 'WellKnownScopeNotFoundError';
26
+ this.scopePath = scopePath;
27
+ this.rootUrl = rootUrl;
28
+ }
29
+ }
8
30
  /**
9
31
  * Well-known skills provider using RFC 8615 well-known URIs.
10
32
  *
@@ -56,14 +78,15 @@ export class WellKnownProvider {
56
78
  * /.well-known/skills/index.json. For each path, tries path-relative
57
79
  * first, then root .well-known.
58
80
  */
59
- async fetchIndex(baseUrl) {
60
- const candidates = await this.fetchIndexCandidates(baseUrl);
81
+ async fetchIndex(baseUrl, options) {
82
+ const candidates = await this.fetchIndexCandidates(baseUrl, options);
61
83
  return candidates[0] ?? null;
62
84
  }
63
- async fetchIndexCandidates(baseUrl) {
85
+ async fetchIndexCandidates(baseUrl, options) {
64
86
  try {
65
87
  const parsed = new URL(baseUrl);
66
88
  const basePath = parsed.pathname.replace(/\/$/, '');
89
+ const signal = AbortSignal.timeout(DISCOVERY_TIMEOUT_MS);
67
90
  const urlsToTry = [];
68
91
  for (const wellKnownPath of this.WELL_KNOWN_PATHS) {
69
92
  urlsToTry.push({
@@ -82,7 +105,10 @@ export class WellKnownProvider {
82
105
  const candidates = [];
83
106
  for (const { indexUrl, baseUrl: resolvedBase, wellKnownPath } of urlsToTry) {
84
107
  try {
85
- const response = await fetch(indexUrl);
108
+ const response = await fetch(indexUrl, {
109
+ signal,
110
+ ...(options?.updateCheck ? { headers: { 'X-Skills-Update-Check': '1' } } : {}),
111
+ });
86
112
  if (!response.ok)
87
113
  continue;
88
114
  const rawIndex = (await response.json());
@@ -398,20 +424,55 @@ export class WellKnownProvider {
398
424
  indexEntry: input.indexEntry,
399
425
  };
400
426
  }
401
- /** Fetch all skills from a well-known endpoint. */
402
- async fetchAllSkills(url) {
427
+ /**
428
+ * Get the path scope of a URL, if any. A URL such as https://host/s/my-list
429
+ * is scoped to '/s/my-list'; a bare origin has no scope.
430
+ */
431
+ getScope(url) {
432
+ try {
433
+ const parsed = new URL(url);
434
+ const scopePath = parsed.pathname.replace(/\/$/, '');
435
+ if (!scopePath)
436
+ return null;
437
+ return { scopePath, rootBaseUrl: `${parsed.protocol}//${parsed.host}` };
438
+ }
439
+ catch {
440
+ return null;
441
+ }
442
+ }
443
+ /**
444
+ * Fetch all skills from a well-known endpoint.
445
+ *
446
+ * When the URL is scoped to a path, only path-relative indexes are used.
447
+ * If the scope yields no skills but the host publishes a root index, this
448
+ * throws {@link WellKnownScopeNotFoundError} instead of silently widening
449
+ * to the root index and returning the host's entire catalog.
450
+ */
451
+ async fetchAllSkills(url, options = {}) {
403
452
  try {
404
453
  const candidates = await this.fetchIndexCandidates(url);
405
- for (const result of candidates) {
454
+ const scope = this.getScope(url);
455
+ const scopedCandidates = scope
456
+ ? candidates.filter((c) => c.resolvedBaseUrl !== scope.rootBaseUrl)
457
+ : candidates;
458
+ const includeInternal = options.includeInternal || shouldInstallInternalSkills();
459
+ for (const result of scopedCandidates) {
406
460
  const skillPromises = result.entries.map((entry) => this.fetchSkillByEntry(entry));
407
461
  const results = await Promise.all(skillPromises);
408
- const skills = results.filter((s) => s !== null);
462
+ const skills = results
463
+ .filter((s) => s !== null)
464
+ .filter((skill) => includeInternal || skill.metadata?.internal !== true);
409
465
  if (skills.length > 0)
410
466
  return skills;
411
467
  }
468
+ if (scope && scopedCandidates.length < candidates.length) {
469
+ throw new WellKnownScopeNotFoundError(scope.scopePath, scope.rootBaseUrl);
470
+ }
412
471
  return [];
413
472
  }
414
- catch {
473
+ catch (error) {
474
+ if (error instanceof WellKnownScopeNotFoundError)
475
+ throw error;
415
476
  return [];
416
477
  }
417
478
  }
@@ -420,7 +481,10 @@ export class WellKnownProvider {
420
481
  }
421
482
  extractArchive(bytes, artifactUrl, contentType) {
422
483
  if (this.isZipArchive(bytes, artifactUrl, contentType)) {
423
- return this.extractZip(bytes);
484
+ return new Map(readZipArchive(bytes, {
485
+ maxExtractedBytes: MAX_ARCHIVE_UNPACKED_BYTES,
486
+ maxEntries: MAX_ARCHIVE_FILES,
487
+ }));
424
488
  }
425
489
  if (this.isTarGzArchive(bytes, artifactUrl, contentType)) {
426
490
  return this.extractTarGz(bytes);
@@ -507,85 +571,6 @@ export class WellKnownProvider {
507
571
  const nul = slice.indexOf(0);
508
572
  return new TextDecoder().decode(nul >= 0 ? slice.subarray(0, nul) : slice);
509
573
  }
510
- extractZip(bytes) {
511
- const buffer = Buffer.from(bytes);
512
- const eocdOffset = this.findZipEndOfCentralDirectory(buffer);
513
- if (eocdOffset < 0)
514
- throw new Error('Invalid zip archive');
515
- const totalEntries = buffer.readUInt16LE(eocdOffset + 10);
516
- const centralDirectoryOffset = buffer.readUInt32LE(eocdOffset + 16);
517
- const files = new Map();
518
- const runningTotal = { bytes: 0 };
519
- let offset = centralDirectoryOffset;
520
- for (let i = 0; i < totalEntries; i++) {
521
- if (buffer.readUInt32LE(offset) !== 0x02014b50)
522
- throw new Error('Invalid zip directory');
523
- const flags = buffer.readUInt16LE(offset + 8);
524
- const method = buffer.readUInt16LE(offset + 10);
525
- const compressedSize = buffer.readUInt32LE(offset + 20);
526
- const uncompressedSize = buffer.readUInt32LE(offset + 24);
527
- const fileNameLength = buffer.readUInt16LE(offset + 28);
528
- const extraLength = buffer.readUInt16LE(offset + 30);
529
- const commentLength = buffer.readUInt16LE(offset + 32);
530
- const externalAttributes = buffer.readUInt32LE(offset + 38);
531
- const localHeaderOffset = buffer.readUInt32LE(offset + 42);
532
- const nameStart = offset + 46;
533
- const rawName = buffer.subarray(nameStart, nameStart + fileNameLength);
534
- const fileName = new TextDecoder(flags & 0x800 ? 'utf-8' : undefined).decode(rawName);
535
- offset = nameStart + fileNameLength + extraLength + commentLength;
536
- // Directories are allowed but not installed as files.
537
- if (fileName.endsWith('/'))
538
- continue;
539
- // Reject encrypted entries, symlinks, and hard links. ZIP external attributes store
540
- // POSIX mode bits in the upper 16 bits for common UNIX-producing tools.
541
- if (flags & 0x1)
542
- throw new Error('Encrypted zip entries are not supported');
543
- const unixMode = externalAttributes >>> 16;
544
- const fileType = unixMode & 0o170000;
545
- if (fileType === 0o120000 || fileType === 0o10000) {
546
- throw new Error('Archive links are not supported');
547
- }
548
- if (buffer.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
549
- throw new Error('Invalid zip local header');
550
- }
551
- const localFileNameLength = buffer.readUInt16LE(localHeaderOffset + 26);
552
- const localExtraLength = buffer.readUInt16LE(localHeaderOffset + 28);
553
- const dataStart = localHeaderOffset + 30 + localFileNameLength + localExtraLength;
554
- const compressed = buffer.subarray(dataStart, dataStart + compressedSize);
555
- // ADG patch: reject zip bombs before decompressing. The central directory
556
- // declares the uncompressed size, so check it against the running budget
557
- // up front — inflateRawSync would otherwise allocate the full (potentially
558
- // multi-GB) output and OOM the process before addArchiveFile's check runs.
559
- if (runningTotal.bytes + uncompressedSize > MAX_ARCHIVE_UNPACKED_BYTES) {
560
- throw new Error('Archive exceeds maximum unpacked size');
561
- }
562
- let content;
563
- if (method === 0) {
564
- content = compressed;
565
- }
566
- else if (method === 8) {
567
- content = inflateRawSync(compressed);
568
- }
569
- else {
570
- throw new Error(`Unsupported zip compression method: ${method}`);
571
- }
572
- if (content.byteLength !== uncompressedSize) {
573
- throw new Error('Zip entry size mismatch');
574
- }
575
- this.addArchiveFile(files, fileName, new Uint8Array(content), runningTotal);
576
- }
577
- if (!files.has('SKILL.md'))
578
- throw new Error('Archive missing root SKILL.md');
579
- return files;
580
- }
581
- findZipEndOfCentralDirectory(buffer) {
582
- const minOffset = Math.max(0, buffer.length - 0xffff - 22);
583
- for (let offset = buffer.length - 22; offset >= minOffset; offset--) {
584
- if (buffer.readUInt32LE(offset) === 0x06054b50)
585
- return offset;
586
- }
587
- return -1;
588
- }
589
574
  /**
590
575
  * Convert a user-facing URL to a skill URL.
591
576
  * For well-known, this extracts the base domain and constructs the proper path.
@@ -629,4 +614,17 @@ export class WellKnownProvider {
629
614
  return result !== null;
630
615
  }
631
616
  }
617
+ export function computeWellKnownSkillDigest(skill) {
618
+ if ('digest' in skill.indexEntry && skill.indexEntry.digest) {
619
+ return skill.indexEntry.digest;
620
+ }
621
+ const hash = createHash('sha256');
622
+ for (const path of Array.from(skill.files.keys()).sort()) {
623
+ hash.update(path);
624
+ hash.update('\0');
625
+ hash.update(skill.files.get(path));
626
+ hash.update('\0');
627
+ }
628
+ return `sha256:${hash.digest('hex')}`;
629
+ }
632
630
  export const wellKnownProvider = new WellKnownProvider();
@@ -5,8 +5,39 @@ import { join } from 'path';
5
5
  import { agents, detectInstalledAgents, getEveSubagents } from "./agents.js";
6
6
  import { track } from "./telemetry.js";
7
7
  import { detectAgent } from "./detect-agent.js";
8
- import { removeSkillFromLock, getSkillFromLock } from "./skill-lock.js";
8
+ import { removeSkillFromLock, getSkillFromLock, readSkillLock } from "./skill-lock.js";
9
+ import { readLocalLock, removeSkillFromLocalLock } from "./local-lock.js";
9
10
  import { getInstallPath, getCanonicalPath, getCanonicalSkillsDir, getEveSubagentSkillsDir, sanitizeName, } from "./installer.js";
11
+ /**
12
+ * Resolve requested skill names to canonical removal targets.
13
+ *
14
+ * On-disk folder names are the result of sanitizeName() at install time, but
15
+ * lock-file keys keep the original name, which may contain characters
16
+ * sanitizeName() rewrites — e.g. the ':' in plugin skills such as "ce:review"
17
+ * maps to the folder "ce-review". Matching purely on folder names therefore
18
+ * misses lock-only or name-mismatched skills (and stale lock entries whose
19
+ * folder is already gone). Every candidate is canonicalized by its sanitized
20
+ * name, preferring the lock key, so downstream disk cleanup (which
21
+ * re-sanitizes) and lock removal (which needs the exact key) both target the
22
+ * right thing.
23
+ */
24
+ export function resolveSkillsToRemove(requested, folderNames, lockKeys = []) {
25
+ const identityBySanitized = new Map();
26
+ for (const folder of folderNames) {
27
+ identityBySanitized.set(sanitizeName(folder), folder);
28
+ }
29
+ // Lock keys win: they carry the exact key needed for lock removal.
30
+ for (const key of lockKeys) {
31
+ identityBySanitized.set(sanitizeName(key), key);
32
+ }
33
+ const matched = new Set();
34
+ for (const name of requested) {
35
+ const hit = identityBySanitized.get(sanitizeName(name));
36
+ if (hit)
37
+ matched.add(hit);
38
+ }
39
+ return Array.from(matched);
40
+ }
10
41
  export async function removeCommand(skillNames, options) {
11
42
  // Auto-enable non-interactive mode when running inside an AI agent
12
43
  const agentResult = await detectAgent();
@@ -16,10 +47,25 @@ export async function removeCommand(skillNames, options) {
16
47
  ' ' +
17
48
  'Agent detected — removing non-interactively');
18
49
  }
50
+ // `--skill '*'` is the documented synonym for selecting every skill.
51
+ if (skillNames.includes('*')) {
52
+ options.all = true;
53
+ skillNames = skillNames.filter((name) => name !== '*');
54
+ }
55
+ // Footgun: `remove --skill foo --all` used to ignore `foo` and wipe everything,
56
+ // because `--all` replaced the requested list with every installed skill.
57
+ // Refuse the combination so agents/scripts cannot accidentally mass-delete.
58
+ const namedSkills = skillNames.filter((name) => name !== '*');
59
+ if (options.all && namedSkills.length > 0) {
60
+ p.log.error('Cannot combine --all with specific skill names.');
61
+ p.log.info('Use `skills remove --all` to remove every skill, or omit --all to remove only the named skills.');
62
+ p.log.info(`Example: skills remove ${namedSkills[0]} -y`);
63
+ process.exit(1);
64
+ }
19
65
  const isGlobal = options.global ?? false;
20
66
  const cwd = process.cwd();
21
67
  const spinner = p.spinner();
22
- spinner.start('Scanning for installed skills...');
68
+ spinner.start('Scanning for installed skills…');
23
69
  const skillNamesSet = new Set();
24
70
  const scanDir = async (dir) => {
25
71
  try {
@@ -56,7 +102,17 @@ export async function removeCommand(skillNames, options) {
56
102
  }
57
103
  const installedSkills = Array.from(skillNamesSet).sort();
58
104
  spinner.stop(`Found ${installedSkills.length} unique installed skill(s)`);
59
- if (installedSkills.length === 0) {
105
+ // Read lock file keys up front. These are needed both to decide whether there is
106
+ // anything to remove (a skill may be missing from disk but still leave a stale lock
107
+ // entry) and to clean up those stale entries below.
108
+ const lockSkillsKeys = isGlobal
109
+ ? Object.keys((await readSkillLock()).skills)
110
+ : Object.keys((await readLocalLock(cwd)).skills);
111
+ const requestedSkills = options.all ? [...installedSkills, ...lockSkillsKeys] : skillNames;
112
+ const resolvedRequestedSkills = options.all || skillNames.length > 0
113
+ ? resolveSkillsToRemove(requestedSkills, installedSkills, lockSkillsKeys)
114
+ : [];
115
+ if (installedSkills.length === 0 && resolvedRequestedSkills.length === 0) {
60
116
  p.outro(pc.yellow('No skills found to remove.'));
61
117
  return;
62
118
  }
@@ -72,10 +128,10 @@ export async function removeCommand(skillNames, options) {
72
128
  }
73
129
  let selectedSkills = [];
74
130
  if (options.all) {
75
- selectedSkills = installedSkills;
131
+ selectedSkills = resolvedRequestedSkills;
76
132
  }
77
133
  else if (skillNames.length > 0) {
78
- selectedSkills = installedSkills.filter((s) => skillNames.some((name) => name.toLowerCase() === s.toLowerCase()));
134
+ selectedSkills = resolvedRequestedSkills;
79
135
  if (selectedSkills.length === 0) {
80
136
  p.log.error(`No matching skills found for: ${skillNames.join(', ')}`);
81
137
  return;
@@ -95,7 +151,7 @@ export async function removeCommand(skillNames, options) {
95
151
  p.cancel('Removal cancelled');
96
152
  process.exit(0);
97
153
  }
98
- selectedSkills = selected;
154
+ selectedSkills = resolveSkillsToRemove(selected, installedSkills, lockSkillsKeys);
99
155
  }
100
156
  let targetAgents;
101
157
  if (options.agent && options.agent.length > 0) {
@@ -123,7 +179,7 @@ export async function removeCommand(skillNames, options) {
123
179
  process.exit(0);
124
180
  }
125
181
  }
126
- spinner.start('Removing skills...');
182
+ spinner.start('Removing skills…');
127
183
  const results = [];
128
184
  for (const skillName of selectedSkills) {
129
185
  try {
@@ -180,11 +236,27 @@ export async function removeCommand(skillNames, options) {
180
236
  if (!isStillUsed) {
181
237
  await rm(canonicalPath, { recursive: true, force: true });
182
238
  }
183
- const lockEntry = isGlobal ? await getSkillFromLock(skillName) : null;
184
- const effectiveSource = lockEntry?.source || 'local';
185
- const effectiveSourceType = lockEntry?.sourceType || 'local';
239
+ let effectiveSource = 'local';
240
+ let effectiveSourceType = 'local';
241
+ // The lock entry tracks the canonical path, so it survives for as long as
242
+ // that path does. Dropping it while another installed agent still links
243
+ // the skill leaves the skill in place but no longer updatable (#1718).
186
244
  if (isGlobal) {
187
- await removeSkillFromLock(skillName);
245
+ const lockEntry = await getSkillFromLock(skillName);
246
+ effectiveSource = lockEntry?.source || 'local';
247
+ effectiveSourceType = lockEntry?.sourceType || 'local';
248
+ if (!isStillUsed) {
249
+ await removeSkillFromLock(skillName);
250
+ }
251
+ }
252
+ else {
253
+ const localLock = await readLocalLock(cwd);
254
+ const lockEntry = localLock.skills[skillName];
255
+ effectiveSource = lockEntry?.source || 'local';
256
+ effectiveSourceType = lockEntry?.sourceType || 'local';
257
+ if (!isStillUsed) {
258
+ await removeSkillFromLocalLock(skillName, cwd);
259
+ }
188
260
  }
189
261
  results.push({
190
262
  skill: skillName,
@@ -240,6 +312,10 @@ export async function removeCommand(skillNames, options) {
240
312
  /**
241
313
  * Parse command line options for the remove command.
242
314
  * Separates skill names from options flags.
315
+ *
316
+ * Supports both positional names (`skills remove foo`) and `-s/--skill`
317
+ * (documented in the CLI help). Unknown flags that start with `-` are ignored
318
+ * so we do not treat `--skill` as a skill name when the flag is misspelled.
243
319
  */
244
320
  export function parseRemoveOptions(args) {
245
321
  const options = {};
@@ -254,6 +330,17 @@ export function parseRemoveOptions(args) {
254
330
  }
255
331
  else if (arg === '--all') {
256
332
  options.all = true;
333
+ options.yes = true;
334
+ }
335
+ else if (arg === '-s' || arg === '--skill') {
336
+ i++;
337
+ let nextArg = args[i];
338
+ while (i < args.length && nextArg && !nextArg.startsWith('-')) {
339
+ skills.push(nextArg);
340
+ i++;
341
+ nextArg = args[i];
342
+ }
343
+ i--; // Back up one since the loop will increment
257
344
  }
258
345
  else if (arg === '-a' || arg === '--agent') {
259
346
  options.agent = options.agent || [];
@@ -1,9 +1,10 @@
1
1
  import { readdir, readFile, stat } from 'fs/promises';
2
2
  import { join, basename, dirname, resolve, normalize, sep, relative } from 'path';
3
3
  import { parseFrontmatter } from "./frontmatter.js";
4
- import { sanitizeMetadata } from "./sanitize.js";
4
+ import { sanitizeMetadata, stripTerminalEscapes } from "./sanitize.js";
5
5
  import { getPluginSkillPaths, getPluginGroupings } from "./plugin-manifest.js";
6
6
  import { readLocalLock } from "./local-lock.js";
7
+ import { DEFAULT_SKILL_CONTAINER_DEPTH } from "./constants.js";
7
8
  const SKIP_DIRS = ['node_modules', '.git', 'dist', 'build', '__pycache__'];
8
9
  const AGENT_PROJECT_SKILL_DIRS = [
9
10
  '.agents/skills',
@@ -15,24 +16,32 @@ const AGENT_PROJECT_SKILL_DIRS = [
15
16
  '.continue/skills',
16
17
  '.github/skills',
17
18
  '.goose/skills',
19
+ '.grok/skills',
18
20
  '.iflow/skills',
19
21
  '.junie/skills',
20
22
  '.kilocode/skills',
23
+ '.kimchi/skills',
21
24
  '.kiro/skills',
22
25
  '.mux/skills',
26
+ '.minimax/skills',
23
27
  '.neovate/skills',
24
28
  '.opencode/skills',
25
29
  '.openhands/skills',
26
30
  '.pi/skills',
31
+ '.posit/assistant/skills',
27
32
  '.qoder/skills',
28
33
  '.roo/skills',
29
34
  '.trae/skills',
30
35
  '.windsurf/skills',
36
+ '.zcode/skills',
31
37
  '.zencoder/skills',
32
38
  ];
33
39
  function normalizeSkillName(name) {
34
40
  return name.toLowerCase().replace(/[\s_]+/g, '-');
35
41
  }
42
+ function warnSkippedSkill(skillMdPath, reason) {
43
+ console.warn(`⚠ Skipped ${sanitizeMetadata(skillMdPath)} — ${stripTerminalEscapes(reason)}`);
44
+ }
36
45
  function normalizeRelativePath(path) {
37
46
  return path.split(sep).join('/').replace(/\/+/g, '/');
38
47
  }
@@ -59,10 +68,12 @@ export async function parseSkillMd(skillMdPath, options) {
59
68
  const content = await readFile(skillMdPath, 'utf-8');
60
69
  const { data } = parseFrontmatter(content);
61
70
  if (!data.name || !data.description) {
71
+ warnSkippedSkill(skillMdPath, 'missing name or description');
62
72
  return null;
63
73
  }
64
74
  // Ensure name and description are strings (YAML can parse numbers, booleans, etc.)
65
75
  if (typeof data.name !== 'string' || typeof data.description !== 'string') {
76
+ warnSkippedSkill(skillMdPath, 'name and description must be strings');
66
77
  return null;
67
78
  }
68
79
  // ADG patch: narrow `metadata` from the loosely-typed frontmatter (`unknown`)
@@ -86,7 +97,8 @@ export async function parseSkillMd(skillMdPath, options) {
86
97
  metadata,
87
98
  };
88
99
  }
89
- catch {
100
+ catch (error) {
101
+ warnSkippedSkill(skillMdPath, `failed to parse skill: ${error.message}`);
90
102
  return null;
91
103
  }
92
104
  }
@@ -177,8 +189,8 @@ export async function discoverSkills(basePath, subpath, options) {
177
189
  join(searchPath, 'skills/.system'),
178
190
  ...AGENT_PROJECT_SKILL_DIRS.map((dir) => join(searchPath, dir)),
179
191
  ];
180
- // Known skill container dirs are walked one extra level deep so layouts
181
- // like `skills/<category>/<skill>/SKILL.md` are discovered without
192
+ // Known skill container dirs are walked up to the configured depth so layouts
193
+ // like `skills/<category>/<category>/<skill>/SKILL.md` are discovered without
182
194
  // requiring `--full-depth`. The repo root (first entry) keeps its
183
195
  // existing depth-1 behavior to avoid surfacing unrelated `SKILL.md`
184
196
  // files (e.g. `examples/foo/SKILL.md`), and plugin-manifest-declared
@@ -199,7 +211,7 @@ export async function discoverSkills(basePath, subpath, options) {
199
211
  seenNames.add(skill.name);
200
212
  return true;
201
213
  };
202
- for (const dir of prioritySearchDirs) {
214
+ const walkSkillDirs = async (dir, maxDepth, depth = 1) => {
203
215
  const walkDeep = deepContainerDirs.has(dir);
204
216
  try {
205
217
  const entries = await readdir(dir, { withFileTypes: true });
@@ -211,27 +223,19 @@ export async function discoverSkills(basePath, subpath, options) {
211
223
  // Don't descend past a discovered SKILL.md (matches the existing
212
224
  // flat-layout semantics) and don't go deeper inside non-container
213
225
  // priority dirs.
214
- if (foundAtChild || !walkDeep)
226
+ if (foundAtChild || !walkDeep || depth >= maxDepth)
215
227
  continue;
216
228
  if (SKIP_DIRS.includes(entry.name))
217
229
  continue;
218
- // Walk one extra level for catalog layouts.
219
- try {
220
- const grandEntries = await readdir(childDir, { withFileTypes: true });
221
- for (const grand of grandEntries) {
222
- if (!grand.isDirectory() || SKIP_DIRS.includes(grand.name))
223
- continue;
224
- await tryAddSkillAt(join(childDir, grand.name));
225
- }
226
- }
227
- catch {
228
- // Child dir unreadable; skip silently.
229
- }
230
+ await walkSkillDirs(childDir, maxDepth, depth + 1);
230
231
  }
231
232
  }
232
233
  catch {
233
- // Directory doesn't exist
234
+ // Directory doesn't exist or is unreadable.
234
235
  }
236
+ };
237
+ for (const dir of prioritySearchDirs) {
238
+ await walkSkillDirs(dir, deepContainerDirs.has(dir) ? DEFAULT_SKILL_CONTAINER_DEPTH : 1);
235
239
  }
236
240
  // Fall back to recursive search if nothing found, or if fullDepth is set
237
241
  if (skills.length === 0 || options?.fullDepth) {