@rbbtsn0w/adg 0.8.0-beta.4 → 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.
- package/dist/src/commands/multiselect-skills.js +3 -2
- package/dist/vendor/skills/src/add.js +92 -15
- package/dist/vendor/skills/src/agents.js +60 -0
- package/dist/vendor/skills/src/archive.js +311 -0
- package/dist/vendor/skills/src/blob.js +58 -22
- package/dist/vendor/skills/src/cli.js +21 -1
- package/dist/vendor/skills/src/constants.js +2 -0
- package/dist/vendor/skills/src/detect-agent.js +24 -1
- package/dist/vendor/skills/src/download-source.js +221 -0
- package/dist/vendor/skills/src/find.js +6 -5
- package/dist/vendor/skills/src/git.js +39 -13
- package/dist/vendor/skills/src/github-host.js +34 -0
- package/dist/vendor/skills/src/install.js +6 -1
- package/dist/vendor/skills/src/installer.js +8 -4
- package/dist/vendor/skills/src/list.js +28 -12
- package/dist/vendor/skills/src/local-lock.js +29 -4
- package/dist/vendor/skills/src/prompts/search-multiselect.js +274 -62
- package/dist/vendor/skills/src/providers/index.js +1 -1
- package/dist/vendor/skills/src/providers/wellknown.js +88 -90
- package/dist/vendor/skills/src/remove.js +98 -11
- package/dist/vendor/skills/src/skills.js +23 -19
- package/dist/vendor/skills/src/source-parser.js +73 -10
- package/dist/vendor/skills/src/sync.js +3 -3
- package/dist/vendor/skills/src/test-utils.js +74 -5
- package/dist/vendor/skills/src/update-source.js +56 -8
- package/dist/vendor/skills/src/update.js +355 -155
- package/dist/vendor/skills/src/use.js +41 -4
- package/package.json +3 -2
- package/vendor/skills/PROVENANCE.md +18 -4
|
@@ -10,8 +10,11 @@
|
|
|
10
10
|
* 3. skills.sh/api/download → fetch full file contents from cached blob
|
|
11
11
|
*/
|
|
12
12
|
import { createHash } from 'node:crypto';
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
13
14
|
import { parseFrontmatter } from "./frontmatter.js";
|
|
14
15
|
import { sanitizeMetadata } from "./sanitize.js";
|
|
16
|
+
import { getGitHubHost } from "./github-host.js";
|
|
17
|
+
import { DEFAULT_SKILL_CONTAINER_DEPTH } from "./constants.js";
|
|
15
18
|
// ─── Constants ───
|
|
16
19
|
const DOWNLOAD_BASE_URL = process.env.SKILLS_DOWNLOAD_URL || 'https://skills.sh';
|
|
17
20
|
// Repos that self-host their downloads on the blob fast-path
|
|
@@ -22,6 +25,7 @@ export const BLOB_ALLOWED_REPOS = {
|
|
|
22
25
|
};
|
|
23
26
|
/** Timeout for individual HTTP fetches (ms) */
|
|
24
27
|
const FETCH_TIMEOUT = 10_000;
|
|
28
|
+
const GH_API_MAX_BUFFER = 16 * 1024 * 1024;
|
|
25
29
|
// ─── Slug computation ───
|
|
26
30
|
/**
|
|
27
31
|
* Convert a skill name to a URL-safe slug.
|
|
@@ -47,7 +51,9 @@ export function resetRepoTreeAuthState() {
|
|
|
47
51
|
}
|
|
48
52
|
async function fetchTreeBranch(ownerRepo, branch, token) {
|
|
49
53
|
try {
|
|
50
|
-
const
|
|
54
|
+
const githubHost = getGitHubHost();
|
|
55
|
+
const apiBase = githubHost === 'github.com' ? 'https://api.github.com' : `https://${githubHost}/api/v3`;
|
|
56
|
+
const url = `${apiBase}/repos/${ownerRepo}/git/trees/${encodeURIComponent(branch)}?recursive=1`;
|
|
51
57
|
const headers = {
|
|
52
58
|
Accept: 'application/vnd.github.v3+json',
|
|
53
59
|
'User-Agent': 'skills-cli',
|
|
@@ -80,6 +86,49 @@ async function fetchTreeBranch(ownerRepo, branch, token) {
|
|
|
80
86
|
return { tree: null, rateLimited: false, authMayHelp: false };
|
|
81
87
|
}
|
|
82
88
|
}
|
|
89
|
+
async function fetchTreeWithToken(ownerRepo, branches, getToken) {
|
|
90
|
+
const token = getToken();
|
|
91
|
+
if (!token)
|
|
92
|
+
return null;
|
|
93
|
+
for (const branch of branches) {
|
|
94
|
+
const result = await fetchTreeBranch(ownerRepo, branch, token);
|
|
95
|
+
if (result.tree)
|
|
96
|
+
return result.tree;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
async function fetchTreeWithGitHubCli(ownerRepo, branches) {
|
|
101
|
+
for (const branch of branches) {
|
|
102
|
+
try {
|
|
103
|
+
const endpoint = `repos/${ownerRepo}/git/trees/${encodeURIComponent(branch)}?recursive=1`;
|
|
104
|
+
const stdout = await new Promise((resolve, reject) => {
|
|
105
|
+
execFile('gh', ['api', endpoint, '--method', 'GET', '--hostname', getGitHubHost()], {
|
|
106
|
+
encoding: 'utf8',
|
|
107
|
+
timeout: FETCH_TIMEOUT,
|
|
108
|
+
maxBuffer: GH_API_MAX_BUFFER,
|
|
109
|
+
windowsHide: true,
|
|
110
|
+
env: { ...process.env, GH_PROMPT_DISABLED: '1' },
|
|
111
|
+
}, (error, output) => (error ? reject(error) : resolve(output)));
|
|
112
|
+
});
|
|
113
|
+
const data = JSON.parse(stdout);
|
|
114
|
+
if (typeof data.sha !== 'string' || !Array.isArray(data.tree))
|
|
115
|
+
continue;
|
|
116
|
+
return { sha: data.sha, branch, tree: data.tree };
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
// Try the next branch, then let the caller fall back to git clone.
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
async function fetchTreeWithAvailableAuth(ownerRepo, branches, getToken) {
|
|
125
|
+
if (getToken) {
|
|
126
|
+
const tree = await fetchTreeWithToken(ownerRepo, branches, getToken);
|
|
127
|
+
if (tree)
|
|
128
|
+
return tree;
|
|
129
|
+
}
|
|
130
|
+
return fetchTreeWithGitHubCli(ownerRepo, branches);
|
|
131
|
+
}
|
|
83
132
|
/**
|
|
84
133
|
* Fetch the full recursive tree for a GitHub repo.
|
|
85
134
|
* Returns the tree data including all entries, or null on failure.
|
|
@@ -96,16 +145,8 @@ export async function fetchRepoTree(ownerRepo, ref, getToken) {
|
|
|
96
145
|
const branches = ref ? [ref] : ['HEAD', 'main', 'master'];
|
|
97
146
|
// Fast path: once we've seen a rate limit in this process, don't bother
|
|
98
147
|
// retrying unauth on subsequent calls. Go straight to auth.
|
|
99
|
-
if (_rateLimitedThisSession
|
|
100
|
-
|
|
101
|
-
if (!token)
|
|
102
|
-
return null;
|
|
103
|
-
for (const branch of branches) {
|
|
104
|
-
const result = await fetchTreeBranch(ownerRepo, branch, token);
|
|
105
|
-
if (result.tree)
|
|
106
|
-
return result.tree;
|
|
107
|
-
}
|
|
108
|
-
return null;
|
|
148
|
+
if (_rateLimitedThisSession) {
|
|
149
|
+
return fetchTreeWithAvailableAuth(ownerRepo, branches, getToken);
|
|
109
150
|
}
|
|
110
151
|
// First pass: unauthenticated.
|
|
111
152
|
let rateLimited = false;
|
|
@@ -122,26 +163,21 @@ export async function fetchRepoTree(ownerRepo, ref, getToken) {
|
|
|
122
163
|
}
|
|
123
164
|
// ADG patch: remember a possible-private signal, but keep trying the other
|
|
124
165
|
// candidate branches unauthenticated first (the repo may just lack `main`).
|
|
125
|
-
if (result.authMayHelp)
|
|
166
|
+
if (result.authMayHelp) {
|
|
126
167
|
authMayHelp = true;
|
|
168
|
+
break;
|
|
169
|
+
}
|
|
127
170
|
}
|
|
128
171
|
// ADG patch: fall back to an authenticated retry on EITHER a rate limit or a
|
|
129
172
|
// private/forbidden response. Upstream only retried on rate limit, so private
|
|
130
173
|
// repos never used the token and always failed.
|
|
131
|
-
if ((!rateLimited && !authMayHelp) || !getToken)
|
|
174
|
+
if ((!rateLimited && !authMayHelp) || (!getToken && getGitHubHost() === 'github.com')) {
|
|
132
175
|
return null;
|
|
176
|
+
}
|
|
133
177
|
// Only a rate limit is a process-wide condition worth short-circuiting later.
|
|
134
178
|
if (rateLimited)
|
|
135
179
|
_rateLimitedThisSession = true;
|
|
136
|
-
|
|
137
|
-
if (!token)
|
|
138
|
-
return null;
|
|
139
|
-
for (const branch of branches) {
|
|
140
|
-
const result = await fetchTreeBranch(ownerRepo, branch, token);
|
|
141
|
-
if (result.tree)
|
|
142
|
-
return result.tree;
|
|
143
|
-
}
|
|
144
|
-
return null;
|
|
180
|
+
return fetchTreeWithAvailableAuth(ownerRepo, branches, getToken);
|
|
145
181
|
}
|
|
146
182
|
/**
|
|
147
183
|
* Extract the folder hash (tree SHA) for a specific skill path from a repo tree.
|
|
@@ -264,6 +264,19 @@ async function main() {
|
|
|
264
264
|
}
|
|
265
265
|
const command = args[0];
|
|
266
266
|
const restArgs = args.slice(1);
|
|
267
|
+
// Subcommand help must short-circuit before dispatch so that commands such
|
|
268
|
+
// as `skills update --help` never execute side effects.
|
|
269
|
+
if (command !== '--help' &&
|
|
270
|
+
command !== '-h' &&
|
|
271
|
+
command !== '--version' &&
|
|
272
|
+
command !== '-v' &&
|
|
273
|
+
(restArgs.includes('--help') || restArgs.includes('-h'))) {
|
|
274
|
+
if (command === 'remove' || command === 'rm' || command === 'r')
|
|
275
|
+
showRemoveHelp();
|
|
276
|
+
else
|
|
277
|
+
showHelp();
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
267
280
|
switch (command) {
|
|
268
281
|
case 'find':
|
|
269
282
|
case 'search':
|
|
@@ -292,7 +305,13 @@ async function main() {
|
|
|
292
305
|
case 'add': {
|
|
293
306
|
if (!inAgent)
|
|
294
307
|
showLogo();
|
|
295
|
-
const { source: addSource, options: addOpts } = parseAddOptions(restArgs);
|
|
308
|
+
const { source: addSource, options: addOpts, errors } = parseAddOptions(restArgs);
|
|
309
|
+
if (errors.length > 0) {
|
|
310
|
+
for (const error of errors)
|
|
311
|
+
console.error(`Error: ${error}`);
|
|
312
|
+
process.exitCode = 1;
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
296
315
|
await runAdd(addSource, addOpts);
|
|
297
316
|
break;
|
|
298
317
|
}
|
|
@@ -339,6 +358,7 @@ async function main() {
|
|
|
339
358
|
default:
|
|
340
359
|
console.log(`Unknown command: ${command}`);
|
|
341
360
|
console.log(`Run ${BOLD}skills --help${RESET} for usage.`);
|
|
361
|
+
process.exitCode = 1;
|
|
342
362
|
}
|
|
343
363
|
}
|
|
344
364
|
main()
|
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
import { determineAgent } from '@vercel/detect-agent';
|
|
2
2
|
import { setDetectedAgent } from "./telemetry.js";
|
|
3
3
|
let cachedResult = null;
|
|
4
|
+
/**
|
|
5
|
+
* @vercel/detect-agent treats any CURSOR_TRACE_ID as a Cursor agent, but that
|
|
6
|
+
* variable is also present in Cursor's integrated terminal for regular user
|
|
7
|
+
* sessions. Require stronger execution signals before enabling agent mode.
|
|
8
|
+
*/
|
|
9
|
+
function hasStrongCursorAgentSignal() {
|
|
10
|
+
return (Boolean(process.env.CURSOR_AGENT?.trim()) ||
|
|
11
|
+
process.env.CURSOR_EXTENSION_HOST_ROLE === 'agent-exec');
|
|
12
|
+
}
|
|
13
|
+
function refineAgentResult(result) {
|
|
14
|
+
if (!result.isAgent || !result.agent) {
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
if (result.agent.name === 'cursor' || result.agent.name === 'cursor-cli') {
|
|
18
|
+
if (!hasStrongCursorAgentSignal()) {
|
|
19
|
+
return { isAgent: false, agent: undefined };
|
|
20
|
+
}
|
|
21
|
+
if (result.agent.name === 'cursor') {
|
|
22
|
+
return { isAgent: true, agent: { name: 'cursor-cli' } };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
4
27
|
/**
|
|
5
28
|
* Map from @vercel/detect-agent names to skills-cli AgentType identifiers.
|
|
6
29
|
* Only includes agents that exist in both systems.
|
|
@@ -26,7 +49,7 @@ const agentNameToType = {
|
|
|
26
49
|
export async function detectAgent() {
|
|
27
50
|
if (cachedResult)
|
|
28
51
|
return cachedResult;
|
|
29
|
-
cachedResult = await determineAgent();
|
|
52
|
+
cachedResult = refineAgentResult(await determineAgent());
|
|
30
53
|
if (cachedResult.isAgent) {
|
|
31
54
|
setDetectedAgent(cachedResult.agent.name);
|
|
32
55
|
}
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { dirname, join, normalize, resolve, sep } from 'node:path';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
6
|
+
import * as tar from 'tar';
|
|
7
|
+
import { ArchiveValidationError, readZipArchive } from "./archive.js";
|
|
8
|
+
import { parseFrontmatter } from "./frontmatter.js";
|
|
9
|
+
const DEFAULT_DOWNLOAD_MAX_BYTES = 10 * 1024 * 1024;
|
|
10
|
+
const DEFAULT_EXTRACT_MAX_BYTES = 25 * 1024 * 1024;
|
|
11
|
+
const DEFAULT_EXTRACT_MAX_FILES = 1000;
|
|
12
|
+
const FETCH_TIMEOUT_MS = 30_000;
|
|
13
|
+
function getPositiveIntegerEnv(name, fallback) {
|
|
14
|
+
const raw = process.env[name];
|
|
15
|
+
if (!raw)
|
|
16
|
+
return fallback;
|
|
17
|
+
const parsed = Number.parseInt(raw, 10);
|
|
18
|
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
|
19
|
+
}
|
|
20
|
+
function getDownloadLimits() {
|
|
21
|
+
return {
|
|
22
|
+
downloadMaxBytes: getPositiveIntegerEnv('SKILLS_DOWNLOAD_MAX_BYTES', DEFAULT_DOWNLOAD_MAX_BYTES),
|
|
23
|
+
extractMaxBytes: getPositiveIntegerEnv('SKILLS_EXTRACT_MAX_BYTES', DEFAULT_EXTRACT_MAX_BYTES),
|
|
24
|
+
extractMaxFiles: getPositiveIntegerEnv('SKILLS_EXTRACT_MAX_FILES', DEFAULT_EXTRACT_MAX_FILES),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function isPathSafe(basePath, targetPath) {
|
|
28
|
+
const normalizedBase = normalize(resolve(basePath));
|
|
29
|
+
const normalizedTarget = normalize(resolve(targetPath));
|
|
30
|
+
return normalizedTarget.startsWith(normalizedBase + sep) || normalizedTarget === normalizedBase;
|
|
31
|
+
}
|
|
32
|
+
function validateArchivePath(path) {
|
|
33
|
+
const normalized = path.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
34
|
+
if (!normalized || normalized.endsWith('/'))
|
|
35
|
+
return normalized;
|
|
36
|
+
if (normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized))
|
|
37
|
+
return null;
|
|
38
|
+
if (normalized.split('/').includes('..'))
|
|
39
|
+
return null;
|
|
40
|
+
return normalized;
|
|
41
|
+
}
|
|
42
|
+
function incrementEntry(state, size, limits) {
|
|
43
|
+
state.entries += 1;
|
|
44
|
+
if (state.entries > limits.extractMaxFiles) {
|
|
45
|
+
throw new ArchiveValidationError(`Archive contains too many files (${state.entries}). Maximum is ${limits.extractMaxFiles}. Set SKILLS_EXTRACT_MAX_FILES to override.`);
|
|
46
|
+
}
|
|
47
|
+
state.bytes += size;
|
|
48
|
+
if (state.bytes > limits.extractMaxBytes) {
|
|
49
|
+
throw new ArchiveValidationError(`Archive extracts to more than ${limits.extractMaxBytes} bytes. Set SKILLS_EXTRACT_MAX_BYTES to override.`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async function downloadToFile(url, targetFile, limits) {
|
|
53
|
+
const response = await fetch(url, {
|
|
54
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
|
55
|
+
redirect: 'follow',
|
|
56
|
+
});
|
|
57
|
+
if (!response.ok) {
|
|
58
|
+
throw new Error(`Download failed with HTTP ${response.status}`);
|
|
59
|
+
}
|
|
60
|
+
const contentLength = response.headers.get('content-length');
|
|
61
|
+
if (contentLength) {
|
|
62
|
+
const parsed = Number.parseInt(contentLength, 10);
|
|
63
|
+
if (Number.isFinite(parsed) && parsed > limits.downloadMaxBytes) {
|
|
64
|
+
throw new Error(`Download is larger than ${limits.downloadMaxBytes} bytes. Set SKILLS_DOWNLOAD_MAX_BYTES to override.`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if (!response.body) {
|
|
68
|
+
throw new Error('Download response has no body');
|
|
69
|
+
}
|
|
70
|
+
let downloaded = 0;
|
|
71
|
+
const limitStream = new TransformStream({
|
|
72
|
+
transform(chunk, controller) {
|
|
73
|
+
downloaded += chunk.byteLength;
|
|
74
|
+
if (downloaded > limits.downloadMaxBytes) {
|
|
75
|
+
throw new Error(`Download is larger than ${limits.downloadMaxBytes} bytes. Set SKILLS_DOWNLOAD_MAX_BYTES to override.`);
|
|
76
|
+
}
|
|
77
|
+
controller.enqueue(chunk);
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
await pipeline(response.body.pipeThrough(limitStream), createWriteStream(targetFile));
|
|
81
|
+
}
|
|
82
|
+
async function isValidSkillMarkdown(filePath) {
|
|
83
|
+
try {
|
|
84
|
+
const content = await readFile(filePath, 'utf-8');
|
|
85
|
+
const { data } = parseFrontmatter(content);
|
|
86
|
+
return typeof data.name === 'string' && typeof data.description === 'string';
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
async function extractZip(filePath, extractDir, limits) {
|
|
93
|
+
const files = readZipArchive(await readFile(filePath), {
|
|
94
|
+
maxExtractedBytes: limits.extractMaxBytes,
|
|
95
|
+
maxEntries: limits.extractMaxFiles,
|
|
96
|
+
});
|
|
97
|
+
for (const [path, contents] of files) {
|
|
98
|
+
const targetPath = join(extractDir, path);
|
|
99
|
+
if (!isPathSafe(extractDir, targetPath)) {
|
|
100
|
+
throw new ArchiveValidationError(`Archive contains unsafe path: ${path}`);
|
|
101
|
+
}
|
|
102
|
+
await mkdir(dirname(targetPath), { recursive: true });
|
|
103
|
+
await writeFile(targetPath, contents);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function getTarEntryType(entry) {
|
|
107
|
+
if (entry instanceof tar.ReadEntry) {
|
|
108
|
+
return entry.type;
|
|
109
|
+
}
|
|
110
|
+
if (entry.isFile())
|
|
111
|
+
return 'File';
|
|
112
|
+
if (entry.isDirectory())
|
|
113
|
+
return 'Directory';
|
|
114
|
+
return '';
|
|
115
|
+
}
|
|
116
|
+
function isTarEntryFile(entry) {
|
|
117
|
+
const type = getTarEntryType(entry);
|
|
118
|
+
return type === 'File' || type === 'OldFile' || type === 'ContiguousFile';
|
|
119
|
+
}
|
|
120
|
+
async function extractTar(filePath, extractDir, limits) {
|
|
121
|
+
const state = { bytes: 0, entries: 0 };
|
|
122
|
+
let validationError;
|
|
123
|
+
await tar.x({
|
|
124
|
+
strict: true,
|
|
125
|
+
filter(entryPath, entry) {
|
|
126
|
+
if (validationError)
|
|
127
|
+
return false;
|
|
128
|
+
try {
|
|
129
|
+
const safePath = validateArchivePath(entryPath);
|
|
130
|
+
if (safePath === null) {
|
|
131
|
+
throw new ArchiveValidationError(`Archive contains unsafe path: ${entryPath}`);
|
|
132
|
+
}
|
|
133
|
+
const targetPath = join(extractDir, safePath);
|
|
134
|
+
if (!isPathSafe(extractDir, targetPath)) {
|
|
135
|
+
throw new ArchiveValidationError(`Archive contains unsafe path: ${entryPath}`);
|
|
136
|
+
}
|
|
137
|
+
incrementEntry(state, entry.size, limits);
|
|
138
|
+
if (isTarEntryFile(entry)) {
|
|
139
|
+
return true;
|
|
140
|
+
}
|
|
141
|
+
return getTarEntryType(entry) === 'Directory';
|
|
142
|
+
}
|
|
143
|
+
catch (error) {
|
|
144
|
+
if (error instanceof ArchiveValidationError) {
|
|
145
|
+
validationError = error;
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
cwd: extractDir,
|
|
152
|
+
preservePaths: false,
|
|
153
|
+
noChmod: true,
|
|
154
|
+
file: filePath,
|
|
155
|
+
});
|
|
156
|
+
if (validationError) {
|
|
157
|
+
throw validationError;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async function tryExtractArchive(filePath, extractDir, limits) {
|
|
161
|
+
const header = await readFile(filePath).then((buffer) => buffer.subarray(0, 512));
|
|
162
|
+
const isZip = header[0] === 0x50 && header[1] === 0x4b;
|
|
163
|
+
const isGzip = header[0] === 0x1f && header[1] === 0x8b;
|
|
164
|
+
try {
|
|
165
|
+
if (isZip) {
|
|
166
|
+
await extractZip(filePath, extractDir, limits);
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
if (isGzip) {
|
|
170
|
+
await extractTar(filePath, extractDir, limits);
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
await extractTar(filePath, extractDir, limits);
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
await rm(extractDir, { recursive: true, force: true }).catch(() => { });
|
|
178
|
+
await mkdir(extractDir, { recursive: true });
|
|
179
|
+
if (error instanceof ArchiveValidationError) {
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
async function getSingleTopLevelDirectory(dir) {
|
|
186
|
+
const { readdir } = await import('node:fs/promises');
|
|
187
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
188
|
+
const visibleEntries = entries.filter((entry) => entry.name !== '__MACOSX');
|
|
189
|
+
if (visibleEntries.length !== 1 || !visibleEntries[0].isDirectory())
|
|
190
|
+
return null;
|
|
191
|
+
return join(dir, visibleEntries[0].name);
|
|
192
|
+
}
|
|
193
|
+
export async function downloadSource(url) {
|
|
194
|
+
const limits = getDownloadLimits();
|
|
195
|
+
const tempDir = await mkdtemp(join(tmpdir(), 'skills-download-'));
|
|
196
|
+
const downloadedFile = join(tempDir, 'source.download');
|
|
197
|
+
const extractDir = join(tempDir, 'extract');
|
|
198
|
+
try {
|
|
199
|
+
await downloadToFile(url, downloadedFile, limits);
|
|
200
|
+
const downloadedStats = await stat(downloadedFile);
|
|
201
|
+
if (downloadedStats.size === 0) {
|
|
202
|
+
throw new Error('Downloaded URL is empty');
|
|
203
|
+
}
|
|
204
|
+
if (await isValidSkillMarkdown(downloadedFile)) {
|
|
205
|
+
const skillDir = join(tempDir, 'skill');
|
|
206
|
+
await mkdir(skillDir, { recursive: true });
|
|
207
|
+
await writeFile(join(skillDir, 'SKILL.md'), await readFile(downloadedFile));
|
|
208
|
+
return { rootDir: skillDir, tempDir, kind: 'skill-md' };
|
|
209
|
+
}
|
|
210
|
+
await mkdir(extractDir, { recursive: true });
|
|
211
|
+
if (await tryExtractArchive(downloadedFile, extractDir, limits)) {
|
|
212
|
+
const rootDir = (await getSingleTopLevelDirectory(extractDir)) ?? extractDir;
|
|
213
|
+
return { rootDir, tempDir, kind: 'archive' };
|
|
214
|
+
}
|
|
215
|
+
throw new Error('Downloaded URL is not a valid SKILL.md file or supported archive');
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
await rm(tempDir, { recursive: true, force: true }).catch(() => { });
|
|
219
|
+
throw error;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
@@ -13,6 +13,7 @@ const MAGENTA = '\x1b[35m';
|
|
|
13
13
|
const YELLOW = '\x1b[33m';
|
|
14
14
|
// API endpoint for skills search
|
|
15
15
|
const SEARCH_API_BASE = process.env.SKILLS_API_URL || 'https://skills.sh';
|
|
16
|
+
const SEARCH_RESULT_LIMIT = '20';
|
|
16
17
|
function formatInstalls(count) {
|
|
17
18
|
if (!count || count <= 0)
|
|
18
19
|
return '';
|
|
@@ -64,7 +65,7 @@ export function parseFindOptions(args) {
|
|
|
64
65
|
// Search via API
|
|
65
66
|
export async function searchSkillsAPI(query, owner) {
|
|
66
67
|
try {
|
|
67
|
-
const params = new URLSearchParams({ q: query, limit:
|
|
68
|
+
const params = new URLSearchParams({ q: query, limit: SEARCH_RESULT_LIMIT });
|
|
68
69
|
if (owner)
|
|
69
70
|
params.set('owner', owner);
|
|
70
71
|
const url = `${SEARCH_API_BASE}/api/search?${params.toString()}`;
|
|
@@ -126,7 +127,7 @@ async function runSearchPrompt(initialQuery = '', owner) {
|
|
|
126
127
|
lines.push(`${DIM}Start typing to search (min 2 chars)${RESET}`);
|
|
127
128
|
}
|
|
128
129
|
else if (results.length === 0 && loading) {
|
|
129
|
-
lines.push(`${DIM}Searching
|
|
130
|
+
lines.push(`${DIM}Searching…${RESET}`);
|
|
130
131
|
}
|
|
131
132
|
else if (results.length === 0) {
|
|
132
133
|
lines.push(`${DIM}No skills found${RESET}`);
|
|
@@ -142,7 +143,7 @@ async function runSearchPrompt(initialQuery = '', owner) {
|
|
|
142
143
|
const source = skill.source ? ` ${DIM}${skill.source}${RESET}` : '';
|
|
143
144
|
const installs = formatInstalls(skill.installs);
|
|
144
145
|
const installsBadge = installs ? ` ${CYAN}${installs}${RESET}` : '';
|
|
145
|
-
const loadingIndicator = loading && i === 0 ? ` ${DIM}
|
|
146
|
+
const loadingIndicator = loading && i === 0 ? ` ${DIM}…${RESET}` : '';
|
|
146
147
|
lines.push(` ${arrow} ${name}${source}${installsBadge}${loadingIndicator}`);
|
|
147
148
|
}
|
|
148
149
|
}
|
|
@@ -294,7 +295,7 @@ ${DIM} 2) npx skills add <owner/repo@skill>${RESET}`;
|
|
|
294
295
|
}
|
|
295
296
|
console.log(`${DIM}Install with${RESET} npx skills add <owner/repo@skill>`);
|
|
296
297
|
console.log();
|
|
297
|
-
for (const skill of results
|
|
298
|
+
for (const skill of results) {
|
|
298
299
|
const pkg = skill.source || skill.slug;
|
|
299
300
|
const installs = formatInstalls(skill.installs);
|
|
300
301
|
console.log(`${TEXT}${pkg}@${skill.name}${RESET}${installs ? ` ${CYAN}${installs}${RESET}` : ''}`);
|
|
@@ -327,7 +328,7 @@ ${DIM} 2) npx skills add <owner/repo@skill>${RESET}`;
|
|
|
327
328
|
const pkg = selected.source || selected.slug;
|
|
328
329
|
const skillName = selected.name;
|
|
329
330
|
console.log();
|
|
330
|
-
console.log(`${TEXT}Installing ${BOLD}${skillName}${RESET} from ${DIM}${pkg}${RESET}
|
|
331
|
+
console.log(`${TEXT}Installing ${BOLD}${skillName}${RESET} from ${DIM}${pkg}${RESET}…`);
|
|
331
332
|
console.log();
|
|
332
333
|
// Run add directly since we're in the same CLI
|
|
333
334
|
const { source, options: addOptions } = parseAddOptions([pkg, '--skill', skillName]);
|
|
@@ -7,7 +7,9 @@ import { mkdtemp, mkdir, rm } from 'fs/promises';
|
|
|
7
7
|
import { tmpdir } from 'os';
|
|
8
8
|
import { execFile } from 'child_process';
|
|
9
9
|
import { promisify } from 'util';
|
|
10
|
+
import { isGitHubHost } from "./github-host.js";
|
|
10
11
|
const DEFAULT_CLONE_TIMEOUT_MS = 300_000; // 5 minutes
|
|
12
|
+
const ALLOWED_GIT_PROTOCOLS = 'https:http:ssh:git:file';
|
|
11
13
|
const CLONE_TIMEOUT_MS = (() => {
|
|
12
14
|
const raw = process.env.SKILLS_CLONE_TIMEOUT_MS;
|
|
13
15
|
if (!raw)
|
|
@@ -51,20 +53,21 @@ export class GitCloneError extends Error {
|
|
|
51
53
|
}
|
|
52
54
|
}
|
|
53
55
|
export function parseGitHubRepoUrl(url) {
|
|
54
|
-
const sshMatch = url.match(/^git@
|
|
55
|
-
if (sshMatch) {
|
|
56
|
-
const
|
|
57
|
-
const
|
|
56
|
+
const sshMatch = url.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/i);
|
|
57
|
+
if (sshMatch && isGitHubHost(sshMatch[1])) {
|
|
58
|
+
const host = sshMatch[1];
|
|
59
|
+
const owner = sshMatch[2];
|
|
60
|
+
const repo = sshMatch[3];
|
|
58
61
|
return {
|
|
59
62
|
owner,
|
|
60
63
|
repo,
|
|
61
64
|
slug: `${owner}/${repo}`,
|
|
62
|
-
sshUrl: `git
|
|
65
|
+
sshUrl: `git@${host}:${owner}/${repo}.git`,
|
|
63
66
|
};
|
|
64
67
|
}
|
|
65
68
|
try {
|
|
66
69
|
const parsed = new URL(url);
|
|
67
|
-
if (parsed.
|
|
70
|
+
if (!isGitHubHost(parsed.host))
|
|
68
71
|
return null;
|
|
69
72
|
const match = parsed.pathname.match(/^\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/);
|
|
70
73
|
if (!match)
|
|
@@ -75,7 +78,7 @@ export function parseGitHubRepoUrl(url) {
|
|
|
75
78
|
owner,
|
|
76
79
|
repo,
|
|
77
80
|
slug: `${owner}/${repo}`,
|
|
78
|
-
sshUrl: `git
|
|
81
|
+
sshUrl: `git@${parsed.host}:${owner}/${repo}.git`,
|
|
79
82
|
};
|
|
80
83
|
}
|
|
81
84
|
catch {
|
|
@@ -85,7 +88,7 @@ export function parseGitHubRepoUrl(url) {
|
|
|
85
88
|
export function isGitHubHttpsCloneUrl(url) {
|
|
86
89
|
try {
|
|
87
90
|
const parsed = new URL(url);
|
|
88
|
-
return parsed.protocol === 'https:' && parsed.
|
|
91
|
+
return parsed.protocol === 'https:' && isGitHubHost(parsed.host);
|
|
89
92
|
}
|
|
90
93
|
catch {
|
|
91
94
|
return false;
|
|
@@ -124,6 +127,7 @@ function createGitEnvironment(extraEnv) {
|
|
|
124
127
|
return {
|
|
125
128
|
...gitEnv,
|
|
126
129
|
GIT_TERMINAL_PROMPT: '0',
|
|
130
|
+
GIT_ALLOW_PROTOCOL: ALLOWED_GIT_PROTOCOLS,
|
|
127
131
|
// When git-lfs IS installed, tell it not to download LFS content during
|
|
128
132
|
// checkout. See #952 for context and empirical impact.
|
|
129
133
|
GIT_LFS_SKIP_SMUDGE: '1',
|
|
@@ -178,7 +182,8 @@ async function resetTempDir(dir) {
|
|
|
178
182
|
async function tryGhClone(repo, tempDir, ref) {
|
|
179
183
|
let cloneTarget = repo.slug;
|
|
180
184
|
try {
|
|
181
|
-
const
|
|
185
|
+
const host = repo.sshUrl.match(/^git@([^:]+):/)?.[1] || 'github.com';
|
|
186
|
+
const { stdout, stderr } = await execFileAsync('gh', ['auth', 'status', '-h', host], {
|
|
182
187
|
timeout: 5000,
|
|
183
188
|
env: createGitEnvironment(),
|
|
184
189
|
});
|
|
@@ -193,29 +198,50 @@ async function tryGhClone(repo, tempDir, ref) {
|
|
|
193
198
|
const gitFlags = ref ? ['--depth=1', '--branch', ref] : ['--depth=1'];
|
|
194
199
|
await execFileAsync('gh', ['repo', 'clone', cloneTarget, tempDir, '--', ...gitFlags], {
|
|
195
200
|
timeout: CLONE_TIMEOUT_MS,
|
|
196
|
-
env: createGitEnvironment(),
|
|
201
|
+
env: createGitEnvironment({ GIT_ALLOW_PROTOCOL: ALLOWED_GIT_PROTOCOLS }),
|
|
197
202
|
});
|
|
198
203
|
return true;
|
|
199
204
|
}
|
|
200
205
|
function buildGitHubAuthError(url, repo, message) {
|
|
206
|
+
const githubHost = repo?.sshUrl.match(/^git@([^:]+):/)?.[1] || 'github.com';
|
|
201
207
|
if (repo && isGitHubSsoAuthError(message)) {
|
|
202
208
|
return (`GitHub blocked HTTPS access to ${url} because the organization enforces SAML SSO.\n` +
|
|
203
209
|
` skills tried your existing git credentials and available fallbacks, but none succeeded.\n` +
|
|
204
210
|
` - Re-authorize your GitHub credentials/app for that org's SSO policy\n` +
|
|
205
211
|
` - Or rerun with SSH: npx skills add ${repo.sshUrl}\n` +
|
|
206
|
-
` - Verify access with: gh auth status -h
|
|
212
|
+
` - Verify access with: gh auth status -h ${githubHost} or ssh -T git@${githubHost}`);
|
|
207
213
|
}
|
|
208
214
|
if (repo) {
|
|
209
215
|
return (`Authentication failed for ${url}.\n` +
|
|
210
216
|
` - For private repos, ensure you have access\n` +
|
|
211
217
|
` - Retry with SSH: npx skills add ${repo.sshUrl}\n` +
|
|
212
|
-
` - Check access with: gh auth status -h
|
|
218
|
+
` - Check access with: gh auth status -h ${githubHost} or ssh -T git@${githubHost}`);
|
|
213
219
|
}
|
|
214
220
|
return (`Authentication failed for ${url}.\n` +
|
|
215
221
|
` - For private repos, ensure you have access\n` +
|
|
216
|
-
` - For SSH: Check your keys with 'ssh -T git
|
|
222
|
+
` - For SSH: Check your keys with 'ssh -T git@${githubHost}'\n` +
|
|
217
223
|
` - For HTTPS: Run 'gh auth login' or configure git credentials`);
|
|
218
224
|
}
|
|
225
|
+
/** Resolve the Git tree object for a locked skill path in a cloned repository. */
|
|
226
|
+
export async function getGitTreeHash(repoDir, skillPath) {
|
|
227
|
+
const normalizedPath = skillPath.replace(/\\/g, '/');
|
|
228
|
+
const segments = normalizedPath.split('/');
|
|
229
|
+
segments.pop();
|
|
230
|
+
const folderPath = segments.join('/');
|
|
231
|
+
const revision = folderPath ? `HEAD:${folderPath}` : 'HEAD^{tree}';
|
|
232
|
+
try {
|
|
233
|
+
const { stdout } = await execFileAsync('git', ['-C', repoDir, 'rev-parse', '--verify', '--end-of-options', revision], {
|
|
234
|
+
encoding: 'utf8',
|
|
235
|
+
timeout: CLONE_TIMEOUT_MS,
|
|
236
|
+
env: createGitEnvironment({ GIT_OPTIONAL_LOCKS: '0' }),
|
|
237
|
+
});
|
|
238
|
+
const hash = stdout.trim();
|
|
239
|
+
return /^[0-9a-f]{40}$/i.test(hash) ? hash.toLowerCase() : null;
|
|
240
|
+
}
|
|
241
|
+
catch {
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
219
245
|
export async function cloneRepo(url, ref) {
|
|
220
246
|
const tempDir = await mkdtemp(join(tmpdir(), 'skills-'));
|
|
221
247
|
const cloneOptions = ref ? ['--depth', '1', '--branch', ref] : ['--depth', '1'];
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const DEFAULT_GITHUB_HOST = 'github.com';
|
|
2
|
+
/**
|
|
3
|
+
* Return the GitHub host selected by the GitHub CLI.
|
|
4
|
+
*
|
|
5
|
+
* GH_HOST is expected to be a hostname, not a URL.
|
|
6
|
+
* Invalid values fall back to github.com instead of being interpolated into
|
|
7
|
+
* clone URLs.
|
|
8
|
+
*/
|
|
9
|
+
export function getGitHubHost() {
|
|
10
|
+
const configuredHost = process.env.GH_HOST?.trim();
|
|
11
|
+
if (!configuredHost) {
|
|
12
|
+
return DEFAULT_GITHUB_HOST;
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
const parsed = new URL(`https://${configuredHost}`);
|
|
16
|
+
if (parsed.username ||
|
|
17
|
+
parsed.password ||
|
|
18
|
+
parsed.port ||
|
|
19
|
+
parsed.pathname !== '/' ||
|
|
20
|
+
parsed.search ||
|
|
21
|
+
parsed.hash) {
|
|
22
|
+
return DEFAULT_GITHUB_HOST;
|
|
23
|
+
}
|
|
24
|
+
return parsed.hostname;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return DEFAULT_GITHUB_HOST;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Whether a host is GitHub.com or the configured GitHub Enterprise host. */
|
|
31
|
+
export function isGitHubHost(host) {
|
|
32
|
+
const normalizedHost = host.toLowerCase();
|
|
33
|
+
return normalizedHost === DEFAULT_GITHUB_HOST || normalizedHost === getGitHubHost().toLowerCase();
|
|
34
|
+
}
|
|
@@ -4,6 +4,7 @@ import { readLocalLock } from "./local-lock.js";
|
|
|
4
4
|
import { runAdd } from "./add.js";
|
|
5
5
|
import { runSync, parseSyncOptions } from "./sync.js";
|
|
6
6
|
import { getUniversalAgents } from "./agents.js";
|
|
7
|
+
import { buildLocalUpdateSource } from "./update-source.js";
|
|
7
8
|
/**
|
|
8
9
|
* Install all skills from the local skills-lock.json.
|
|
9
10
|
* Groups skills by source and calls `runAdd` for each group.
|
|
@@ -32,7 +33,11 @@ export async function runInstallFromLock(args) {
|
|
|
32
33
|
nodeModuleSkills.push(skillName);
|
|
33
34
|
continue;
|
|
34
35
|
}
|
|
35
|
-
const installSource = entry
|
|
36
|
+
const installSource = buildLocalUpdateSource(entry);
|
|
37
|
+
if (!installSource) {
|
|
38
|
+
p.log.error(`Cannot restore ${pc.cyan(skillName)}: skills-lock.json is missing sourceUrl for this generic Git source`);
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
36
41
|
const existing = bySource.get(installSource);
|
|
37
42
|
if (existing) {
|
|
38
43
|
existing.skills.push(skillName);
|