@rbbtsn0w/adg 0.10.1 → 0.11.0-beta.1

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 (45) hide show
  1. package/README.md +9 -0
  2. package/dist/src/adapters/antigravity-hooks.js +4 -2
  3. package/dist/src/commands/adapt.js +2 -2
  4. package/dist/src/commands/install/install-one.js +76 -5
  5. package/dist/src/commands/install.js +10 -2
  6. package/dist/src/commands/marketplace.js +6 -1
  7. package/dist/src/commands/update.js +4 -1
  8. package/dist/src/materialize.js +1 -1
  9. package/dist/src/plugin-changes.js +22 -0
  10. package/dist/src/render/plugins.js +21 -3
  11. package/dist/src/sources.js +3 -1
  12. package/dist/vendor/skills/src/add.js +597 -281
  13. package/dist/vendor/skills/src/agents.js +42 -7
  14. package/dist/vendor/skills/src/blob.js +96 -42
  15. package/dist/vendor/skills/src/cli.js +64 -36
  16. package/dist/vendor/skills/src/detect-agent.js +1 -1
  17. package/dist/vendor/skills/src/download-source.js +11 -8
  18. package/dist/vendor/skills/src/find.js +5 -5
  19. package/dist/vendor/skills/src/frontmatter.js +1 -1
  20. package/dist/vendor/skills/src/git-tree.js +1 -1
  21. package/dist/vendor/skills/src/git.js +84 -3
  22. package/dist/vendor/skills/src/install.js +27 -16
  23. package/dist/vendor/skills/src/installer.js +68 -42
  24. package/dist/vendor/skills/src/list.js +5 -5
  25. package/dist/vendor/skills/src/local-lock.js +18 -7
  26. package/dist/vendor/skills/src/notion-test.js +440 -0
  27. package/dist/vendor/skills/src/prompts/search-multiselect.js +22 -0
  28. package/dist/vendor/skills/src/providers/index.js +2 -2
  29. package/dist/vendor/skills/src/providers/wellknown.js +4 -4
  30. package/dist/vendor/skills/src/remove.js +37 -16
  31. package/dist/vendor/skills/src/skill-lock.js +2 -2
  32. package/dist/vendor/skills/src/skill-relocation.js +56 -0
  33. package/dist/vendor/skills/src/skills-field.js +50 -0
  34. package/dist/vendor/skills/src/skills.js +78 -58
  35. package/dist/vendor/skills/src/source-parser.js +76 -2
  36. package/dist/vendor/skills/src/sync.js +610 -190
  37. package/dist/vendor/skills/src/telemetry.js +1 -1
  38. package/dist/vendor/skills/src/test-utils.js +6 -9
  39. package/dist/vendor/skills/src/update.js +147 -62
  40. package/dist/vendor/skills/src/use.js +13 -12
  41. package/docs/agents-spec.md +5 -0
  42. package/docs/plugin-update-semantics.md +152 -0
  43. package/package.json +7 -7
  44. package/vendor/skills/PROVENANCE.md +130 -10
  45. package/vendor/skills/ThirdPartyNoticeText.txt +4 -4
@@ -0,0 +1,440 @@
1
+ import * as p from '@clack/prompts';
2
+ import pc from 'picocolors';
3
+ import { spawn } from 'node:child_process';
4
+ import { SpanKind } from '@opentelemetry/api';
5
+ import { annotateSubprocess } from '../../../src/subprocess.js';
6
+ import { getTracer } from '../../../src/telemetry.js';
7
+ import { cp, mkdir, mkdtemp, writeFile } from 'node:fs/promises';
8
+ import { tmpdir } from 'node:os';
9
+ import { join, relative, sep } from 'node:path';
10
+ import { downloadSource } from './download-source.js';
11
+ import { cleanupTempDir } from './git.js';
12
+ import { sanitizeName } from './installer.js';
13
+ import { sanitizeMetadata, stripTerminalEscapes } from './sanitize.js';
14
+ import { searchMultiselect } from './prompts/search-multiselect.js';
15
+ import { discoverSkills } from './skills.js';
16
+ const NOTION_API_VERSION = '2026-03-11';
17
+ const NTN_TIMEOUT_MS = 30_000;
18
+ const NTN_MAX_BUFFER_BYTES = 10 * 1024 * 1024;
19
+ const NOTION_DOWNLOAD_MAX_BYTES = 50 * 1024 * 1024;
20
+ const NOTION_EXTRACT_MAX_BYTES = 100 * 1024 * 1024;
21
+ const NOTION_EXTRACT_MAX_FILES = 5000;
22
+ function isRecord(value) {
23
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ }
25
+ function assertString(value, field) {
26
+ if (typeof value !== 'string' || value.length === 0) {
27
+ throw new Error(`Notion Agent Plugins response is missing ${field}`);
28
+ }
29
+ return value;
30
+ }
31
+ function optionalMetadata(value, field) {
32
+ if (value === undefined || value === null)
33
+ return '';
34
+ if (typeof value !== 'string') {
35
+ throw new Error(`Notion Agent Plugins response has an invalid ${field}`);
36
+ }
37
+ return sanitizeMetadata(value);
38
+ }
39
+ function parsePack(value) {
40
+ if (!isRecord(value)) {
41
+ throw new Error('Notion Agent Plugins response contains an invalid pack');
42
+ }
43
+ if (typeof value.name !== 'string') {
44
+ throw new Error('Notion Agent Plugins response is missing pack.name');
45
+ }
46
+ const name = sanitizeMetadata(value.name);
47
+ if (!name)
48
+ return null;
49
+ return {
50
+ id: assertString(value.id, 'pack.id'),
51
+ name,
52
+ description: optionalMetadata(value.description, 'pack.description'),
53
+ version_id: assertString(value.version_id, 'pack.version_id'),
54
+ };
55
+ }
56
+ function parsePackList(value) {
57
+ if (!isRecord(value) || !Array.isArray(value.results)) {
58
+ throw new Error('Notion Agent Plugins list response is invalid');
59
+ }
60
+ if (typeof value.has_more !== 'boolean') {
61
+ throw new Error('Notion Agent Plugins list response is missing has_more');
62
+ }
63
+ const nextCursor = value.next_cursor;
64
+ if (nextCursor !== null && typeof nextCursor !== 'string') {
65
+ throw new Error('Notion Agent Plugins list response has an invalid next_cursor');
66
+ }
67
+ const results = value.results.map(parsePack).filter((pack) => pack !== null);
68
+ return {
69
+ results,
70
+ next_cursor: nextCursor,
71
+ has_more: value.has_more,
72
+ };
73
+ }
74
+ function parseDirectory(value, label) {
75
+ if (!isRecord(value)) {
76
+ throw new Error(`Notion ${label} directory response is invalid`);
77
+ }
78
+ return {
79
+ id: assertString(value.id, `${label} directory id`),
80
+ version_id: assertString(value.version_id, `${label} directory version_id`),
81
+ url: assertString(value.url, `${label} directory url`),
82
+ };
83
+ }
84
+ function downloadNotionDirectory(url) {
85
+ return downloadSource(url, {
86
+ downloadMaxBytes: NOTION_DOWNLOAD_MAX_BYTES,
87
+ extractMaxBytes: NOTION_EXTRACT_MAX_BYTES,
88
+ extractMaxFiles: NOTION_EXTRACT_MAX_FILES,
89
+ });
90
+ }
91
+ function debugNtn(args) {
92
+ if (process.env.SKILLS_DEBUG === '1') {
93
+ console.error(`[notion] ntn ${args.join(' ')}`);
94
+ }
95
+ }
96
+ export async function runNtnApi(args) {
97
+ debugNtn(args);
98
+ // ADG patch: reuse the shared, privacy-safe subprocess telemetry contract.
99
+ return getTracer().startActiveSpan('ntn', { kind: SpanKind.CLIENT }, async (span) => {
100
+ const result = { status: null, signal: null };
101
+ try {
102
+ return await new Promise((resolve, reject) => {
103
+ const child = spawn('ntn', args, {
104
+ env: process.env,
105
+ stdio: ['ignore', 'pipe', 'pipe'],
106
+ });
107
+ result.pid = child.pid;
108
+ const stdoutChunks = [];
109
+ const stderrChunks = [];
110
+ let outputBytes = 0;
111
+ let settled = false;
112
+ const finish = (callback) => {
113
+ if (settled)
114
+ return;
115
+ settled = true;
116
+ clearTimeout(timeout);
117
+ callback();
118
+ };
119
+ const fail = (message, code) => finish(() => {
120
+ if (code)
121
+ result.error = Object.assign(new Error('Notion subprocess failed'), { code });
122
+ reject(new Error(message));
123
+ });
124
+ const append = (chunks, chunk) => {
125
+ outputBytes += chunk.length;
126
+ if (outputBytes > NTN_MAX_BUFFER_BYTES) {
127
+ child.kill('SIGTERM');
128
+ fail('ntn api output exceeded 10 MiB', 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER');
129
+ return;
130
+ }
131
+ chunks.push(chunk);
132
+ };
133
+ const timeout = setTimeout(() => {
134
+ child.kill('SIGTERM');
135
+ fail(`ntn api timed out after ${NTN_TIMEOUT_MS / 1000} seconds`, 'ETIMEDOUT');
136
+ }, NTN_TIMEOUT_MS);
137
+ child.stdout.on('data', (chunk) => append(stdoutChunks, chunk));
138
+ child.stderr.on('data', (chunk) => append(stderrChunks, chunk));
139
+ child.on('error', (error) => {
140
+ if (settled)
141
+ return;
142
+ result.error = error;
143
+ if (error.code === 'ENOENT') {
144
+ fail('Notion CLI (ntn) is required. Install it from:\nhttps://developers.notion.com/cli/get-started/overview\nThen run `ntn login`.');
145
+ return;
146
+ }
147
+ fail(`Unable to start ntn: ${stripTerminalEscapes(error.message)}`);
148
+ });
149
+ child.on('close', (code, signal) => {
150
+ if (settled)
151
+ return;
152
+ result.status = code ?? (signal ? null : 1);
153
+ result.signal = signal;
154
+ const stdout = Buffer.concat(stdoutChunks).toString('utf8');
155
+ const stderr = stripTerminalEscapes(Buffer.concat(stderrChunks).toString('utf8')).trim();
156
+ if (code === 0) {
157
+ finish(() => resolve(stdout));
158
+ return;
159
+ }
160
+ fail(`ntn api failed${stderr ? `: ${stderr}` : ` with exit code ${code ?? 'unknown'}`}`);
161
+ });
162
+ });
163
+ }
164
+ catch (error) {
165
+ result.error ??= error instanceof Error ? error : new Error('Notion subprocess failed');
166
+ throw error;
167
+ }
168
+ finally {
169
+ annotateSubprocess(span, 'ntn', args, result);
170
+ span.end();
171
+ }
172
+ });
173
+ }
174
+ async function fetchNotionJson(args, label, runNtn = runNtnApi) {
175
+ const output = await runNtn(['api', ...args, '--notion-version', NOTION_API_VERSION]);
176
+ try {
177
+ return JSON.parse(output);
178
+ }
179
+ catch (error) {
180
+ if (error instanceof SyntaxError) {
181
+ throw new Error(`ntn returned invalid JSON for ${label}`);
182
+ }
183
+ throw error;
184
+ }
185
+ }
186
+ export async function fetchNotionPacks(options = {}) {
187
+ const runNtn = options.runNtn ?? runNtnApi;
188
+ const packs = [];
189
+ const seenCursors = new Set();
190
+ let cursor = null;
191
+ do {
192
+ const args = ['/v1/ai/plugins', 'page_size==100'];
193
+ if (cursor)
194
+ args.push(`start_cursor==${cursor}`);
195
+ const value = await fetchNotionJson(args, 'the Notion packs list', runNtn);
196
+ const page = parsePackList(value);
197
+ packs.push(...page.results);
198
+ if (!page.has_more)
199
+ break;
200
+ if (!page.next_cursor || seenCursors.has(page.next_cursor)) {
201
+ throw new Error('Notion Agent Plugins pagination returned an invalid cursor');
202
+ }
203
+ cursor = page.next_cursor;
204
+ seenCursors.add(cursor);
205
+ } while (cursor);
206
+ return packs;
207
+ }
208
+ export async function fetchNotionPackDirectory(pack, options = {}) {
209
+ const value = await fetchNotionJson([`/v1/ai/plugins/${encodeURIComponent(pack.id)}`], `Notion pack ${JSON.stringify(pack.name)}`, options.runNtn);
210
+ const directory = parseDirectory(value, 'pack');
211
+ if (directory.id !== pack.id || directory.version_id !== pack.version_id) {
212
+ throw new Error(`Notion pack ${JSON.stringify(pack.name)} changed while preparing installation`);
213
+ }
214
+ return directory;
215
+ }
216
+ /** Workspace `ntn` is authenticated against. Null on any failure, so a probe
217
+ * can never block an install. */
218
+ export async function fetchNotionWorkspaceName(options = {}) {
219
+ const runNtn = options.runNtn ?? runNtnApi;
220
+ try {
221
+ const args = ['api', '/v1/users/me', '--notion-version', NOTION_API_VERSION];
222
+ const value = JSON.parse(await runNtn(args));
223
+ if (!isRecord(value) || !isRecord(value.bot))
224
+ return null;
225
+ const name = value.bot.workspace_name;
226
+ return typeof name === 'string' && name.length > 0 ? sanitizeMetadata(name) : null;
227
+ }
228
+ catch {
229
+ return null;
230
+ }
231
+ }
232
+ function inWorkspace(workspace) {
233
+ return workspace ? ` in workspace ${pc.cyan(workspace)}` : '';
234
+ }
235
+ export function isNotionSource(source) {
236
+ return source.toLowerCase() === 'notion';
237
+ }
238
+ const NOTION_HOSTNAME = /(^|\.)notion\.(so|com)$/;
239
+ const NOTION_PAGE_ID = /(?:^|-)([0-9a-f]{32}|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
240
+ function formatPageId(rawId) {
241
+ const hex = rawId.replace(/-/g, '');
242
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
243
+ }
244
+ /** Page ID from a Notion page URL, else null so other source formats still
245
+ * fall through to the ordinary handling. */
246
+ export function parseNotionSkillUrl(source) {
247
+ let url;
248
+ try {
249
+ url = new URL(source);
250
+ }
251
+ catch {
252
+ return null;
253
+ }
254
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
255
+ return null;
256
+ if (!NOTION_HOSTNAME.test(url.hostname.toLowerCase()))
257
+ return null;
258
+ const lastSegment = url.pathname.split('/').filter(Boolean).pop();
259
+ if (!lastSegment)
260
+ return null;
261
+ let decoded;
262
+ try {
263
+ decoded = decodeURIComponent(lastSegment);
264
+ }
265
+ catch {
266
+ decoded = lastSegment;
267
+ }
268
+ const match = decoded.toLowerCase().match(NOTION_PAGE_ID);
269
+ return match ? formatPageId(match[1]) : null;
270
+ }
271
+ export async function fetchNotionSkillDirectory(pageId, options = {}) {
272
+ const value = await fetchNotionJson([`/v1/ai/skills/${encodeURIComponent(pageId)}`], `Notion skill ${pageId}`, options.runNtn);
273
+ return parseDirectory(value, 'skill');
274
+ }
275
+ /** The archive's one top-level directory holds SKILL.md, so the extracted root
276
+ * is already usable as a local source. */
277
+ export async function prepareNotionSkillSource(pageId, options = {}) {
278
+ const download = options.download ?? downloadNotionDirectory;
279
+ const spinner = p.spinner();
280
+ spinner.start('Fetching Notion skill with ntn…');
281
+ try {
282
+ const [directory, workspace] = await Promise.all([
283
+ fetchNotionSkillDirectory(pageId, { runNtn: options.runNtn }),
284
+ fetchNotionWorkspaceName({ runNtn: options.runNtn }),
285
+ ]);
286
+ const downloaded = await download(directory.url);
287
+ spinner.stop(`Downloaded skill from Notion${inWorkspace(workspace)}`);
288
+ return { rootDir: downloaded.rootDir, tempDir: downloaded.tempDir };
289
+ }
290
+ catch (error) {
291
+ spinner.stop(pc.red('Failed to prepare Notion skill'));
292
+ throw error;
293
+ }
294
+ }
295
+ function normalizeSelector(value) {
296
+ return value
297
+ .toLowerCase()
298
+ .replace(/[^a-z0-9]+/g, '-')
299
+ .replace(/^-|-$/g, '');
300
+ }
301
+ function filterPacks(packs, selectors) {
302
+ if (selectors.includes('*'))
303
+ return packs;
304
+ const normalized = new Set(selectors.map(normalizeSelector));
305
+ return packs.filter((pack) => normalized.has(normalizeSelector(pack.name)) || normalized.has(pack.id.toLowerCase()));
306
+ }
307
+ function sortedPacks(packs) {
308
+ return [...packs].sort((a, b) => a.name.localeCompare(b.name));
309
+ }
310
+ function printAvailablePacks(packs) {
311
+ console.log();
312
+ p.log.step(pc.bold('Available Notion packs'));
313
+ for (const pack of sortedPacks(packs)) {
314
+ p.log.message(pc.cyan(pack.name));
315
+ if (pack.description)
316
+ p.log.message(` ${pc.dim(pack.description)}`);
317
+ }
318
+ }
319
+ export async function prepareNotionPackSource(options = {}) {
320
+ const spinner = p.spinner();
321
+ spinner.start('Fetching Notion packs with ntn…');
322
+ let packs;
323
+ let workspace = null;
324
+ try {
325
+ [packs, workspace] = await Promise.all([
326
+ fetchNotionPacks({ runNtn: options.runNtn }),
327
+ fetchNotionWorkspaceName({ runNtn: options.runNtn }),
328
+ ]);
329
+ }
330
+ catch (error) {
331
+ spinner.stop(pc.red('Failed to load Notion packs'));
332
+ throw error;
333
+ }
334
+ spinner.stop(`Found ${pc.green(packs.length)} Notion pack${packs.length === 1 ? '' : 's'}${inWorkspace(workspace)}`);
335
+ if (packs.length === 0) {
336
+ throw new Error('Notion returned no packs for the authenticated workspace');
337
+ }
338
+ if (options.list) {
339
+ printAvailablePacks(packs);
340
+ p.outro(pc.dim('Select a pack by running the command without --list.'));
341
+ return null;
342
+ }
343
+ let selectedPacks;
344
+ if (options.skill && options.skill.length > 0) {
345
+ selectedPacks = filterPacks(packs, options.skill);
346
+ if (selectedPacks.length === 0) {
347
+ throw new Error(`No matching Notion packs found for: ${options.skill.join(', ')}`);
348
+ }
349
+ }
350
+ else if (options.yes || !process.stdin.isTTY) {
351
+ selectedPacks = packs;
352
+ }
353
+ else {
354
+ const selected = await searchMultiselect({
355
+ message: `Select Notion packs to install ${pc.dim('(space to toggle)')}`,
356
+ items: sortedPacks(packs).map((pack) => ({
357
+ value: pack,
358
+ label: pack.name,
359
+ detail: pack.description || 'Notion plugin pack',
360
+ })),
361
+ required: true,
362
+ maxVisible: 20,
363
+ searchable: false,
364
+ showDetail: true,
365
+ showSelectedSummary: false,
366
+ });
367
+ if (typeof selected === 'symbol') {
368
+ p.cancel('Selection cancelled');
369
+ return null;
370
+ }
371
+ selectedPacks = selected;
372
+ }
373
+ p.note(selectedPacks.map((pack) => pc.cyan(pack.name)).join('\n'), `Selected ${selectedPacks.length} Notion pack${selectedPacks.length === 1 ? '' : 's'}`);
374
+ const stagingDir = await mkdtemp(join(tmpdir(), 'skills-notion-'));
375
+ const packsDir = join(stagingDir, 'packs');
376
+ const manifestPlugins = [];
377
+ const download = options.download ?? downloadNotionDirectory;
378
+ const discover = options.discover ?? discoverSkills;
379
+ let skillCount = 0;
380
+ spinner.start('Preparing selected Notion packs…');
381
+ try {
382
+ await mkdir(packsDir, { recursive: true });
383
+ for (const [index, pack] of selectedPacks.entries()) {
384
+ let downloaded = null;
385
+ try {
386
+ const directory = await fetchNotionPackDirectory(pack, { runNtn: options.runNtn });
387
+ downloaded = await download(directory.url);
388
+ const skills = await discover(downloaded.rootDir, undefined, {
389
+ includeInternal: true,
390
+ fullDepth: true,
391
+ });
392
+ if (skills.length === 0) {
393
+ throw new Error('pack contains no valid skills');
394
+ }
395
+ const directoryName = `pack-${index + 1}-${sanitizeName(pack.name).slice(0, 100)}`;
396
+ const targetDir = join(packsDir, directoryName);
397
+ await cp(downloaded.rootDir, targetDir, {
398
+ recursive: true,
399
+ force: false,
400
+ errorOnExist: true,
401
+ });
402
+ manifestPlugins.push({
403
+ name: pack.name,
404
+ source: `./${directoryName}`,
405
+ skills: skills.map((skill) => {
406
+ const skillPath = relative(downloaded.rootDir, skill.path).split(sep).join('/');
407
+ return skillPath ? `./${skillPath}` : './.';
408
+ }),
409
+ });
410
+ skillCount += skills.length;
411
+ }
412
+ catch (error) {
413
+ const detail = error instanceof Error ? error.message : 'Unknown error';
414
+ throw new Error(`Failed to prepare Notion pack ${JSON.stringify(pack.name)}: ${detail}`);
415
+ }
416
+ finally {
417
+ if (downloaded)
418
+ await cleanupTempDir(downloaded.tempDir).catch(() => { });
419
+ }
420
+ }
421
+ const manifestDir = join(stagingDir, '.claude-plugin');
422
+ await mkdir(manifestDir, { recursive: true });
423
+ await writeFile(join(manifestDir, 'marketplace.json'), `${JSON.stringify({
424
+ metadata: { pluginRoot: './packs' },
425
+ plugins: manifestPlugins,
426
+ }, null, 2)}\n`, 'utf8');
427
+ spinner.stop(`Prepared ${pc.green(selectedPacks.length)} Notion pack${selectedPacks.length === 1 ? '' : 's'} with ${pc.green(skillCount)} skill${skillCount === 1 ? '' : 's'}`);
428
+ return {
429
+ rootDir: stagingDir,
430
+ tempDir: stagingDir,
431
+ packCount: selectedPacks.length,
432
+ skillCount,
433
+ };
434
+ }
435
+ catch (error) {
436
+ spinner.stop(pc.red('Failed to prepare Notion packs'));
437
+ await cleanupTempDir(stagingDir).catch(() => { });
438
+ throw error;
439
+ }
440
+ }
@@ -428,27 +428,41 @@ export async function searchMultiselect(options) {
428
428
  lastRenderHeight = countVisualRowsForLines(lines, process.stdout.columns);
429
429
  };
430
430
  const cleanup = () => {
431
+ rl.removeListener('close', closeHandler);
431
432
  process.stdin.removeListener('keypress', keypressHandler);
432
433
  if (process.stdin.isTTY) {
433
434
  process.stdin.setRawMode(false);
434
435
  }
435
436
  rl.close();
436
437
  };
438
+ let settled = false;
437
439
  const submit = () => {
440
+ if (settled)
441
+ return;
438
442
  // If required and no locked items, don't allow submitting with no selection
439
443
  if (required && selected.size === 0 && lockedValues.length === 0) {
440
444
  return;
441
445
  }
446
+ settled = true;
442
447
  render('submit');
443
448
  cleanup();
444
449
  // Include locked values in the result
445
450
  resolve([...lockedValues, ...Array.from(selected)]);
446
451
  };
447
452
  const cancel = () => {
453
+ if (settled)
454
+ return;
455
+ settled = true;
448
456
  render('cancel');
449
457
  cleanup();
450
458
  resolve(cancelSymbol);
451
459
  };
460
+ // Treat end of input as a cancel. Without this, a non-TTY stdin (CI,
461
+ // piped input) that reaches EOF leaves the promise pending forever and
462
+ // the process exits 0 as if the prompt had succeeded.
463
+ const closeHandler = () => {
464
+ cancel();
465
+ };
452
466
  // Handle keypresses
453
467
  const keypressHandler = (_str, key) => {
454
468
  if (!key)
@@ -518,6 +532,14 @@ export async function searchMultiselect(options) {
518
532
  }
519
533
  };
520
534
  process.stdin.on('keypress', keypressHandler);
535
+ rl.on('close', closeHandler);
536
+ // stdin may have already reached EOF before this prompt attached (an
537
+ // earlier readline consumer, such as a spinner, reads the stream), in
538
+ // which case the interface above never emits 'close'.
539
+ if (process.stdin.readableEnded || process.stdin.destroyed) {
540
+ cancel();
541
+ return;
542
+ }
521
543
  // Initial render
522
544
  render();
523
545
  });
@@ -1,4 +1,4 @@
1
1
  // Export registry functions
2
- export { registry, registerProvider, findProvider, getProviders } from "./registry.js";
2
+ export { registry, registerProvider, findProvider, getProviders } from './registry.js';
3
3
  // Export individual providers
4
- export { WellKnownProvider, WellKnownScopeNotFoundError, wellKnownProvider, computeWellKnownSkillDigest, } from "./wellknown.js";
4
+ export { WellKnownProvider, WellKnownScopeNotFoundError, wellKnownProvider, computeWellKnownSkillDigest, } from './wellknown.js';
@@ -1,9 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { gunzipSync } from 'node:zlib';
3
- import { readZipArchive } from "../archive.js";
4
- import { parseFrontmatter } from "../frontmatter.js";
5
- import { sanitizeMetadata } from "../sanitize.js";
6
- import { shouldInstallInternalSkills } from "../skills.js";
3
+ import { readZipArchive } from '../archive.js';
4
+ import { parseFrontmatter } from '../frontmatter.js';
5
+ import { sanitizeMetadata } from '../sanitize.js';
6
+ import { shouldInstallInternalSkills } from '../skills.js';
7
7
  const DISCOVERY_SCHEMA_V2 = 'https://schemas.agentskills.io/discovery/0.2.0/schema.json';
8
8
  const MAX_ARCHIVE_UNPACKED_BYTES = 50 * 1024 * 1024;
9
9
  const MAX_ARCHIVE_FILES = 1000;
@@ -2,12 +2,13 @@ import * as p from '@clack/prompts';
2
2
  import pc from 'picocolors';
3
3
  import { readdir, rm, lstat } from 'fs/promises';
4
4
  import { join } from 'path';
5
- import { agents, detectInstalledAgents, getEveSubagents } from "./agents.js";
6
- import { track } from "./telemetry.js";
7
- import { detectAgent } from "./detect-agent.js";
8
- import { removeSkillFromLock, getSkillFromLock, readSkillLock } from "./skill-lock.js";
9
- import { readLocalLock, removeSkillFromLocalLock } from "./local-lock.js";
10
- import { getInstallPath, getCanonicalPath, getCanonicalSkillsDir, getEveSubagentSkillsDir, sanitizeName, } from "./installer.js";
5
+ import { agents, detectInstalledAgents, getEveSubagents } from './agents.js';
6
+ import { track } from './telemetry.js';
7
+ import { detectAgent } from './detect-agent.js';
8
+ import { removeSkillFromLock, getSkillFromLock, readSkillLock } from './skill-lock.js';
9
+ import { readLocalLock, removeSkillFromLocalLock } from './local-lock.js';
10
+ import { hasSkillMd } from './skills.js';
11
+ import { getInstallPath, getCanonicalPath, getCanonicalSkillsDir, getEveSubagentSkillsDir, sanitizeName, } from './installer.js';
11
12
  /**
12
13
  * Resolve requested skill names to canonical removal targets.
13
14
  *
@@ -21,7 +22,7 @@ import { getInstallPath, getCanonicalPath, getCanonicalSkillsDir, getEveSubagent
21
22
  * re-sanitizes) and lock removal (which needs the exact key) both target the
22
23
  * right thing.
23
24
  */
24
- export function resolveSkillsToRemove(requested, folderNames, lockKeys = []) {
25
+ export function resolveSkillsToRemove(requested, folderNames, lockKeys = [], sourceByKey = {}) {
25
26
  const identityBySanitized = new Map();
26
27
  for (const folder of folderNames) {
27
28
  identityBySanitized.set(sanitizeName(folder), folder);
@@ -33,8 +34,15 @@ export function resolveSkillsToRemove(requested, folderNames, lockKeys = []) {
33
34
  const matched = new Set();
34
35
  for (const name of requested) {
35
36
  const hit = identityBySanitized.get(sanitizeName(name));
36
- if (hit)
37
+ if (hit) {
37
38
  matched.add(hit);
39
+ continue;
40
+ }
41
+ // Not a skill name: treat it as an exact lock source and take every skill from it.
42
+ for (const key of lockKeys) {
43
+ if (sourceByKey[key] === name)
44
+ matched.add(key);
45
+ }
38
46
  }
39
47
  return Array.from(matched);
40
48
  }
@@ -71,9 +79,20 @@ export async function removeCommand(skillNames, options) {
71
79
  try {
72
80
  const entries = await readdir(dir, { withFileTypes: true });
73
81
  for (const entry of entries) {
74
- if (entry.isDirectory()) {
75
- skillNamesSet.add(entry.name);
76
- }
82
+ // Dot-directories belong to the agent, not to us: sanitizeName() strips
83
+ // leading dots, so a skill can never be installed under such a name and
84
+ // removal could never address one either. Offering Codex's bundled
85
+ // `$CODEX_HOME/skills/.system` was always a dead entry.
86
+ if (!entry.isDirectory() || entry.name.startsWith('.'))
87
+ continue;
88
+ // A directory is only a skill if it holds a SKILL.md, which is what
89
+ // listInstalledSkills() already requires. Without this, any directory
90
+ // in a scanned path counted as installed — including the contents of a
91
+ // source repo's `skills/` folder, which is also OpenClaw's project
92
+ // install dir and so is always scanned.
93
+ if (!(await hasSkillMd(join(dir, entry.name))))
94
+ continue;
95
+ skillNamesSet.add(entry.name);
77
96
  }
78
97
  }
79
98
  catch (err) {
@@ -105,12 +124,12 @@ export async function removeCommand(skillNames, options) {
105
124
  // Read lock file keys up front. These are needed both to decide whether there is
106
125
  // anything to remove (a skill may be missing from disk but still leave a stale lock
107
126
  // 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);
127
+ const lockEntries = isGlobal ? (await readSkillLock()).skills : (await readLocalLock(cwd)).skills;
128
+ const lockSkillsKeys = Object.keys(lockEntries);
129
+ const sourceByKey = Object.fromEntries(lockSkillsKeys.map((key) => [key, lockEntries[key]?.source]));
111
130
  const requestedSkills = options.all ? [...installedSkills, ...lockSkillsKeys] : skillNames;
112
131
  const resolvedRequestedSkills = options.all || skillNames.length > 0
113
- ? resolveSkillsToRemove(requestedSkills, installedSkills, lockSkillsKeys)
132
+ ? resolveSkillsToRemove(requestedSkills, installedSkills, lockSkillsKeys, sourceByKey)
114
133
  : [];
115
134
  if (installedSkills.length === 0 && resolvedRequestedSkills.length === 0) {
116
135
  p.outro(pc.yellow('No skills found to remove.'));
@@ -280,7 +299,9 @@ export async function removeCommand(skillNames, options) {
280
299
  if (successful.length > 0) {
281
300
  const bySource = new Map();
282
301
  for (const r of successful) {
283
- const source = r.source || 'local';
302
+ // A local lock entry's source is an absolute path on the user's machine; telemetry only
303
+ // ever receives the generic 'local' for it.
304
+ const source = r.sourceType === 'local' ? 'local' : r.source || 'local';
284
305
  const existing = bySource.get(source) || { skills: [] };
285
306
  existing.skills.push(r.skill);
286
307
  existing.sourceType = r.sourceType;
@@ -3,7 +3,7 @@ import { join, dirname } from 'path';
3
3
  import { homedir } from 'os';
4
4
  import { createHash } from 'crypto';
5
5
  import pc from 'picocolors';
6
- import { runSubprocessSync } from "../../../src/subprocess.js";
6
+ import { runSubprocessSync } from '../../../src/subprocess.js';
7
7
  const AGENTS_DIR = '.agents';
8
8
  const LOCK_FILE = '.skill-lock.json';
9
9
  const CURRENT_VERSION = 3; // Bumped from 2 to 3 for folder hash support (GitHub tree SHA)
@@ -135,7 +135,7 @@ export function getGitHubToken() {
135
135
  * @returns The tree SHA for the skill folder, or null if not found
136
136
  */
137
137
  export async function fetchSkillFolderHash(ownerRepo, skillPath, getToken, ref) {
138
- const { fetchRepoTree, getSkillFolderHashFromTree } = await import("./blob.js");
138
+ const { fetchRepoTree, getSkillFolderHashFromTree } = await import('./blob.js');
139
139
  const tree = await fetchRepoTree(ownerRepo, ref, getToken ?? undefined);
140
140
  if (!tree)
141
141
  return null;