promptlike 0.9.0 → 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.
- package/CHANGELOG.md +94 -0
- package/README.md +241 -27
- package/dist/commands/config.js +13 -0
- package/dist/commands/copy.js +10 -3
- package/dist/commands/get.js +11 -2
- package/dist/commands/import.js +30 -128
- package/dist/commands/importCheck.js +304 -0
- package/dist/commands/importGithub.js +171 -0
- package/dist/commands/list.js +83 -17
- package/dist/commands/local.js +31 -9
- package/dist/commands/login.js +6 -5
- package/dist/commands/search.js +73 -7
- package/dist/commands/show.js +11 -3
- package/dist/commands/sync.js +57 -13
- package/dist/index.js +7 -0
- package/dist/lib/errors.js +4 -0
- package/dist/lib/format.js +28 -0
- package/dist/lib/frontmatter.js +86 -4
- package/dist/lib/github.js +208 -0
- package/dist/lib/githubCache.js +118 -0
- package/dist/lib/githubHttp.js +197 -0
- package/dist/lib/githubImport.js +238 -0
- package/dist/lib/githubSelect.js +148 -0
- package/dist/lib/githubSnapshot.js +67 -0
- package/dist/lib/githubSpec.js +78 -0
- package/dist/lib/importOrigins.js +36 -0
- package/dist/lib/importShared.js +179 -0
- package/dist/lib/licenses.js +243 -0
- package/dist/lib/localStore.js +49 -0
- package/dist/lib/loopApi.js +63 -11
- package/dist/lib/promptResolver.js +22 -9
- package/dist/lib/promptSource.js +123 -0
- package/dist/lib/rank.js +30 -13
- package/dist/lib/settings.js +24 -3
- package/dist/lib/tagFilter.js +40 -0
- package/dist/lib/updateCheck.js +296 -0
- package/dist/lib/upstreamCheck.js +71 -0
- package/dist/program.js +26 -7
- package/package.json +1 -1
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* One HTTP request to GitHub, and what can go wrong with it. No token, ever:
|
|
4
|
+
* nothing here reads the environment or puts credentials or cookies on a
|
|
5
|
+
* request — what GitHub sees is the URL, the User-Agent below and the IP
|
|
6
|
+
* address it came from.
|
|
7
|
+
*
|
|
8
|
+
* Only two hosts are ever contacted:
|
|
9
|
+
* api.github.com repo info, ref → commit, recursive tree (counted: 60/hour per IP)
|
|
10
|
+
* raw.githubusercontent.com file contents at a commit (not counted)
|
|
11
|
+
*
|
|
12
|
+
* Redirects are not followed blindly: the API may redirect (a renamed repo) at
|
|
13
|
+
* most twice and only to api.github.com; raw downloads never redirect. One
|
|
14
|
+
* `AbortSignal.timeout` per request covers the body read too. A body is capped
|
|
15
|
+
* while it streams, not only after.
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.GithubError = exports.GITHUB_RAW = exports.GITHUB_API = void 0;
|
|
19
|
+
exports.resetHttpState = resetHttpState;
|
|
20
|
+
exports.request = request;
|
|
21
|
+
exports.parseJson = parseJson;
|
|
22
|
+
const constants_1 = require("./constants");
|
|
23
|
+
const format_1 = require("./format");
|
|
24
|
+
exports.GITHUB_API = 'https://api.github.com';
|
|
25
|
+
exports.GITHUB_RAW = 'https://raw.githubusercontent.com';
|
|
26
|
+
const API_VERSION = '2022-11-28';
|
|
27
|
+
/** Per request, response body included (one signal covers both). */
|
|
28
|
+
const REQUEST_TIMEOUT_MS = 15000;
|
|
29
|
+
const MAX_REDIRECTS = 2;
|
|
30
|
+
const MAX_RAW_RETRY_WAIT_S = 5;
|
|
31
|
+
/** Warn once per run when this few unauthenticated requests are left. */
|
|
32
|
+
const LOW_LIMIT = 10;
|
|
33
|
+
const REDIRECTS = new Set([301, 302, 307, 308]);
|
|
34
|
+
/** Anything that went wrong talking to GitHub. `retryable` → exit code 2 (see errors.ts). */
|
|
35
|
+
class GithubError extends Error {
|
|
36
|
+
constructor(message, opts = {}) {
|
|
37
|
+
super(message);
|
|
38
|
+
this.name = 'GithubError';
|
|
39
|
+
this.retryable = opts.retryable ?? false;
|
|
40
|
+
this.kind = opts.kind ?? 'other';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.GithubError = GithubError;
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// Rate-limit bookkeeping
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
let warnedLowLimit = false;
|
|
48
|
+
/** Tests only: forget the once-per-run state. */
|
|
49
|
+
function resetHttpState() {
|
|
50
|
+
warnedLowLimit = false;
|
|
51
|
+
}
|
|
52
|
+
function clock(epochSeconds) {
|
|
53
|
+
const d = new Date(epochSeconds * 1000);
|
|
54
|
+
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
|
|
55
|
+
}
|
|
56
|
+
function resetClock(headers) {
|
|
57
|
+
const reset = Number(headers.get('x-ratelimit-reset'));
|
|
58
|
+
return Number.isFinite(reset) && reset > 0 ? clock(reset) : null;
|
|
59
|
+
}
|
|
60
|
+
function noteRateLimit(headers) {
|
|
61
|
+
const raw = headers.get('x-ratelimit-remaining');
|
|
62
|
+
const remaining = raw === null ? NaN : Number(raw);
|
|
63
|
+
if (!Number.isFinite(remaining) || remaining >= LOW_LIMIT || warnedLowLimit)
|
|
64
|
+
return;
|
|
65
|
+
warnedLowLimit = true;
|
|
66
|
+
const reset = resetClock(headers);
|
|
67
|
+
console.error(format_1.c.muted(`GitHub allows 60 requests an hour without a token; ${remaining} left${reset ? `, resets at ${reset}` : ''}.`));
|
|
68
|
+
}
|
|
69
|
+
function failure(status, headers, spec) {
|
|
70
|
+
if (spec.missing?.statuses.includes(status))
|
|
71
|
+
return new GithubError(spec.missing.message, { kind: 'not_found' });
|
|
72
|
+
if ((status === 403 || status === 429) && headers.get('x-ratelimit-remaining') === '0') {
|
|
73
|
+
const reset = resetClock(headers);
|
|
74
|
+
return new GithubError(`GitHub's limit for requests without a token (60 an hour per IP address) is used up. ${reset ? `Try again after ${reset}.` : 'Try again later.'}`, { retryable: true, kind: 'rate_limit' });
|
|
75
|
+
}
|
|
76
|
+
if (status === 409)
|
|
77
|
+
return new GithubError('This repository is empty.');
|
|
78
|
+
if (status === 451)
|
|
79
|
+
return new GithubError('GitHub blocks this repository for legal reasons.');
|
|
80
|
+
return new GithubError(`GitHub returned ${status} for ${(0, format_1.safeText)(spec.what)}.`, {
|
|
81
|
+
retryable: status >= 500 || status === 429 || headers.has('retry-after'),
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
function networkError(err, signal) {
|
|
85
|
+
let detail = err instanceof Error ? err.message : String(err);
|
|
86
|
+
const cause = err instanceof Error ? err.cause : undefined;
|
|
87
|
+
if (cause instanceof Error && cause.message)
|
|
88
|
+
detail += `: ${cause.message}`;
|
|
89
|
+
if (signal.aborted)
|
|
90
|
+
detail = `no answer within ${REQUEST_TIMEOUT_MS / 1000} s`;
|
|
91
|
+
return new GithubError(`Cannot reach GitHub (${(0, format_1.safeText)(detail)}).`, { retryable: true, kind: 'network' });
|
|
92
|
+
}
|
|
93
|
+
/** A redirect target is followed only when it is https://api.github.com/… (relative paths resolve against the request). */
|
|
94
|
+
function apiRedirectTarget(location, from) {
|
|
95
|
+
if (!location)
|
|
96
|
+
return null;
|
|
97
|
+
try {
|
|
98
|
+
const u = new URL(location, from);
|
|
99
|
+
return u.origin === exports.GITHUB_API && !u.username && !u.password ? u.toString() : null;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async function discard(res) {
|
|
106
|
+
try {
|
|
107
|
+
await res.body?.cancel();
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
/* nothing left to free */
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async function readBody(res, spec) {
|
|
114
|
+
const declared = Number(res.headers.get('content-length'));
|
|
115
|
+
if (Number.isFinite(declared) && declared > spec.maxBytes) {
|
|
116
|
+
await discard(res);
|
|
117
|
+
throw spec.tooLarge;
|
|
118
|
+
}
|
|
119
|
+
if (!res.body)
|
|
120
|
+
return Buffer.alloc(0);
|
|
121
|
+
const reader = res.body.getReader();
|
|
122
|
+
const chunks = [];
|
|
123
|
+
let total = 0;
|
|
124
|
+
for (;;) {
|
|
125
|
+
const { done, value } = await reader.read();
|
|
126
|
+
if (done)
|
|
127
|
+
break;
|
|
128
|
+
total += value.byteLength;
|
|
129
|
+
if (total > spec.maxBytes) {
|
|
130
|
+
await reader.cancel().catch(() => undefined);
|
|
131
|
+
throw spec.tooLarge;
|
|
132
|
+
}
|
|
133
|
+
chunks.push(value);
|
|
134
|
+
}
|
|
135
|
+
return Buffer.concat(chunks);
|
|
136
|
+
}
|
|
137
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
138
|
+
function retryAfterMs(headers) {
|
|
139
|
+
const raw = (headers.get('retry-after') ?? '').trim();
|
|
140
|
+
const seconds = /^\d{1,6}$/.test(raw) ? Number(raw) : 1;
|
|
141
|
+
return Math.min(seconds, MAX_RAW_RETRY_WAIT_S) * 1000;
|
|
142
|
+
}
|
|
143
|
+
async function request(spec) {
|
|
144
|
+
let url = spec.url;
|
|
145
|
+
let hops = 0;
|
|
146
|
+
let waited = false;
|
|
147
|
+
for (;;) {
|
|
148
|
+
const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS);
|
|
149
|
+
try {
|
|
150
|
+
const res = await fetch(url, {
|
|
151
|
+
method: 'GET',
|
|
152
|
+
headers: {
|
|
153
|
+
'User-Agent': `promptlike-cli/${constants_1.CLI_VERSION}`,
|
|
154
|
+
Accept: spec.accept,
|
|
155
|
+
...(spec.api ? { 'X-GitHub-Api-Version': API_VERSION } : {}),
|
|
156
|
+
},
|
|
157
|
+
redirect: 'manual',
|
|
158
|
+
signal,
|
|
159
|
+
});
|
|
160
|
+
noteRateLimit(res.headers);
|
|
161
|
+
if (REDIRECTS.has(res.status)) {
|
|
162
|
+
await discard(res);
|
|
163
|
+
const next = spec.api && hops < MAX_REDIRECTS ? apiRedirectTarget(res.headers.get('location'), url) : null;
|
|
164
|
+
if (!next)
|
|
165
|
+
throw failure(res.status, res.headers, spec);
|
|
166
|
+
url = next;
|
|
167
|
+
hops++;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
// raw.githubusercontent.com asks for a pause with 429: once, never longer than a few seconds.
|
|
171
|
+
if (res.status === 429 && !spec.api && !waited) {
|
|
172
|
+
await discard(res);
|
|
173
|
+
waited = true;
|
|
174
|
+
await sleep(retryAfterMs(res.headers));
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (!res.ok) {
|
|
178
|
+
await discard(res);
|
|
179
|
+
throw failure(res.status, res.headers, spec);
|
|
180
|
+
}
|
|
181
|
+
return await readBody(res, spec);
|
|
182
|
+
}
|
|
183
|
+
catch (err) {
|
|
184
|
+
if (err instanceof GithubError)
|
|
185
|
+
throw err;
|
|
186
|
+
throw networkError(err, signal);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function parseJson(buf, what) {
|
|
191
|
+
try {
|
|
192
|
+
return JSON.parse(buf.toString('utf8'));
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
throw new GithubError(`GitHub sent an unexpected answer for ${(0, format_1.safeText)(what)}.`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The middle of `ple import github:…`: read the picked files, gate them, and
|
|
4
|
+
* build what is remembered about where each prompt came from.
|
|
5
|
+
*
|
|
6
|
+
* Every file passes the same gates, in this order: sensitive file name and size
|
|
7
|
+
* (./githubSelect.ts — never fetched), secret scan, empty body, license
|
|
8
|
+
* (./licenses.ts). A file that fails one is listed with the reason and never
|
|
9
|
+
* copied anywhere; downloads are kept in the cache only after a file passed all
|
|
10
|
+
* of them.
|
|
11
|
+
*
|
|
12
|
+
* Provenance has three faces, all built here:
|
|
13
|
+
* origin signed in: sent with the prompt (`prompt_origins.meta`), what `--check` reads back
|
|
14
|
+
* upstream signed out: `upstream_*` lines in the local file (see localStore.ts)
|
|
15
|
+
* description the attribution line appended to the prompt's description
|
|
16
|
+
*/
|
|
17
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
+
exports.trackedKey = exports.loadSnapshot = exports.selectPicks = exports.MAX_PICKS = exports.SPEC_HELP = exports.parseGithubSpec = void 0;
|
|
19
|
+
exports.readUpstream = readUpstream;
|
|
20
|
+
exports.prepareCandidate = prepareCandidate;
|
|
21
|
+
exports.attributionLine = attributionLine;
|
|
22
|
+
exports.buildDescription = buildDescription;
|
|
23
|
+
exports.refreshAttribution = refreshAttribution;
|
|
24
|
+
exports.originFromUpstream = originFromUpstream;
|
|
25
|
+
exports.buildOrigin = buildOrigin;
|
|
26
|
+
exports.buildUpstream = buildUpstream;
|
|
27
|
+
exports.mapLimit = mapLimit;
|
|
28
|
+
exports.collectItems = collectItems;
|
|
29
|
+
const frontmatter_1 = require("./frontmatter");
|
|
30
|
+
const github_1 = require("./github");
|
|
31
|
+
const githubSnapshot_1 = require("./githubSnapshot");
|
|
32
|
+
const githubSelect_1 = require("./githubSelect");
|
|
33
|
+
const format_1 = require("./format");
|
|
34
|
+
const promptTemplate_1 = require("./promptTemplate");
|
|
35
|
+
const scanners_1 = require("./scanners");
|
|
36
|
+
const secretGuard_1 = require("./secretGuard");
|
|
37
|
+
// The steps of an import, from the argument to the stored provenance, are reachable from here:
|
|
38
|
+
var githubSpec_1 = require("./githubSpec");
|
|
39
|
+
Object.defineProperty(exports, "parseGithubSpec", { enumerable: true, get: function () { return githubSpec_1.parseGithubSpec; } });
|
|
40
|
+
Object.defineProperty(exports, "SPEC_HELP", { enumerable: true, get: function () { return githubSpec_1.SPEC_HELP; } });
|
|
41
|
+
var githubSelect_2 = require("./githubSelect");
|
|
42
|
+
Object.defineProperty(exports, "MAX_PICKS", { enumerable: true, get: function () { return githubSelect_2.MAX_PICKS; } });
|
|
43
|
+
Object.defineProperty(exports, "selectPicks", { enumerable: true, get: function () { return githubSelect_2.selectPicks; } });
|
|
44
|
+
var githubSnapshot_2 = require("./githubSnapshot");
|
|
45
|
+
Object.defineProperty(exports, "loadSnapshot", { enumerable: true, get: function () { return githubSnapshot_2.loadSnapshot; } });
|
|
46
|
+
const MAX_TITLE = 200;
|
|
47
|
+
const MAX_DESCRIPTION = 1000;
|
|
48
|
+
const MAX_TAGS = 10;
|
|
49
|
+
const MAX_TAG = 50;
|
|
50
|
+
const KNOWN_KEYS = new Set(['name', 'title', 'description', 'tags', 'license']);
|
|
51
|
+
const oneLine = (s) => (0, format_1.safeText)(s).replace(/\s+/g, ' ').trim();
|
|
52
|
+
/** Text of a file the way import reads it: refuse secrets, strip frontmatter, refuse an empty body. */
|
|
53
|
+
function readUpstream(text) {
|
|
54
|
+
const secret = (0, secretGuard_1.findSecret)(text);
|
|
55
|
+
if (secret)
|
|
56
|
+
return { skip: `looks like it contains a ${secret} — not imported` };
|
|
57
|
+
const fm = (0, frontmatter_1.parseFrontmatter)(text);
|
|
58
|
+
const body = fm.body.trim();
|
|
59
|
+
if (!body)
|
|
60
|
+
return { skip: 'empty body' };
|
|
61
|
+
return { body, declaredLicense: fm.fields.license || undefined, fm };
|
|
62
|
+
}
|
|
63
|
+
function prepareCandidate(pick, text) {
|
|
64
|
+
const read = readUpstream(text);
|
|
65
|
+
if ('skip' in read)
|
|
66
|
+
return read;
|
|
67
|
+
const { body, fm } = read;
|
|
68
|
+
const named = pick.fixedTitle ? '' : oneLine(fm.fields.name || fm.fields.title || '');
|
|
69
|
+
const title = (named || oneLine(pick.titleHint)).slice(0, MAX_TITLE) || 'prompt';
|
|
70
|
+
const fmTags = (fm.lists.tags ?? (fm.fields.tags ? fm.fields.tags.split(',') : []))
|
|
71
|
+
.flatMap((t) => t.split(','))
|
|
72
|
+
.map((t) => oneLine(t).slice(0, MAX_TAG))
|
|
73
|
+
.filter(Boolean);
|
|
74
|
+
// The tool and `github` tags always survive the cap of 10.
|
|
75
|
+
const closing = [...new Set([pick.tool, 'github'])];
|
|
76
|
+
const tags = [...new Set(fmTags.filter((t) => !closing.includes(t)))].slice(0, MAX_TAGS - closing.length).concat(closing);
|
|
77
|
+
const extra = {};
|
|
78
|
+
for (const [k, v] of Object.entries(fm.fields)) {
|
|
79
|
+
if (!KNOWN_KEYS.has(k) && v)
|
|
80
|
+
extra[k] = oneLine(v);
|
|
81
|
+
}
|
|
82
|
+
const warnings = [];
|
|
83
|
+
if (body.includes('${{') || body.includes('{%')) {
|
|
84
|
+
warnings.push('uses ${{ }} / Jinja syntax — {{…}} will be read as PromptLikeEngineer variables');
|
|
85
|
+
}
|
|
86
|
+
return {
|
|
87
|
+
candidate: {
|
|
88
|
+
pick,
|
|
89
|
+
title,
|
|
90
|
+
description: oneLine(fm.fields.description ?? ''),
|
|
91
|
+
tags,
|
|
92
|
+
body,
|
|
93
|
+
extra,
|
|
94
|
+
declaredLicense: read.declaredLicense,
|
|
95
|
+
bytes: Buffer.byteLength(text, 'utf8'),
|
|
96
|
+
sha256: (0, scanners_1.hashBody)(body),
|
|
97
|
+
variables: (0, promptTemplate_1.extractVariables)(body),
|
|
98
|
+
warnings,
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// Provenance
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
const SEP = ' — ';
|
|
106
|
+
// Exactly what attributionLine writes: the link, the SPDX id, and an optional copyright notice.
|
|
107
|
+
const ATTRIBUTION = /(?:^| — )Source: github\.com\/\S+ · [A-Za-z0-9.+-]+(?: · (?:[Cc]opyright|©|\([Cc]\))[^\n]*)?$/;
|
|
108
|
+
/** `Source: github.com/o/r/blob/abc1234/path · MIT · Copyright …` */
|
|
109
|
+
function attributionLine(repo, commit, path, verdict) {
|
|
110
|
+
const link = (0, github_1.blobUrl)(repo, commit.slice(0, 7), path).replace(/^https:\/\//, '');
|
|
111
|
+
return `Source: ${link} · ${verdict.spdx}${verdict.copyright ? ` · ${verdict.copyright}` : ''}`;
|
|
112
|
+
}
|
|
113
|
+
/** The original description, trimmed so that description + attribution stay within the 1000-character limit. */
|
|
114
|
+
function buildDescription(original, attribution) {
|
|
115
|
+
if (!original)
|
|
116
|
+
return attribution.slice(0, MAX_DESCRIPTION);
|
|
117
|
+
const room = MAX_DESCRIPTION - SEP.length - attribution.length;
|
|
118
|
+
if (room <= 0)
|
|
119
|
+
return attribution.slice(0, MAX_DESCRIPTION);
|
|
120
|
+
const kept = original.length > room ? `${original.slice(0, Math.max(0, room - 1)).trimEnd()}…` : original;
|
|
121
|
+
return `${kept}${SEP}${attribution}`;
|
|
122
|
+
}
|
|
123
|
+
/** Swap the attribution at the end of an existing description; null when it has none (the person edited it away). */
|
|
124
|
+
function refreshAttribution(description, attribution) {
|
|
125
|
+
if (!ATTRIBUTION.test(description))
|
|
126
|
+
return null;
|
|
127
|
+
return buildDescription(description.replace(ATTRIBUTION, '').trimEnd(), attribution);
|
|
128
|
+
}
|
|
129
|
+
/** Server-side meta limits (src/lib/import-origin.ts): ≤ 20 keys, values ≤ 500, ≤ 4096 bytes — keep a margin. */
|
|
130
|
+
const META_BUDGET_BYTES = 3500;
|
|
131
|
+
const META_KEY = /^[A-Za-z0-9_-]{1,40}$/;
|
|
132
|
+
const RESERVED = new Set(['source', 'repo', 'ref', 'commit', 'blob', 'file', 'license', 'license_url', 'copyright', 'url']);
|
|
133
|
+
const bytesOf = (v) => Buffer.byteLength(JSON.stringify(v), 'utf8');
|
|
134
|
+
/** The keys `--check` needs to find the file again — never dropped. */
|
|
135
|
+
function baseMeta(up) {
|
|
136
|
+
const cut = (v) => v.slice(0, 500);
|
|
137
|
+
return {
|
|
138
|
+
source: 'github',
|
|
139
|
+
repo: up.repo,
|
|
140
|
+
ref: cut(up.ref),
|
|
141
|
+
commit: up.commit,
|
|
142
|
+
blob: up.blob,
|
|
143
|
+
file: cut(up.path),
|
|
144
|
+
license: cut(up.license),
|
|
145
|
+
...(up.licenseUrl ? { license_url: cut(up.licenseUrl) } : {}),
|
|
146
|
+
...(up.copyright ? { copyright: cut(up.copyright) } : {}),
|
|
147
|
+
url: cut(up.url),
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Provenance as the server stores it (`prompt_origins`): tool, kind, `github:<repo>/<path>`,
|
|
152
|
+
* the sha256 of the text, and `meta`. The keys `--check` reads are never dropped;
|
|
153
|
+
* `extra` (the file's other frontmatter keys) fills whatever room is left.
|
|
154
|
+
*/
|
|
155
|
+
function originFromUpstream(up, sha256, extra = {}) {
|
|
156
|
+
let meta = baseMeta(up);
|
|
157
|
+
for (const [k, v] of Object.entries(extra)) {
|
|
158
|
+
if (RESERVED.has(k) || !META_KEY.test(k) || Object.keys(meta).length >= 20)
|
|
159
|
+
continue;
|
|
160
|
+
const next = { ...meta, [k]: v.slice(0, 500) };
|
|
161
|
+
if (bytesOf(next) <= META_BUDGET_BYTES)
|
|
162
|
+
meta = next;
|
|
163
|
+
}
|
|
164
|
+
return { tool: up.tool, kind: up.kind, path: `github:${up.repo}/${up.path}`, sha256, meta };
|
|
165
|
+
}
|
|
166
|
+
function buildOrigin(snap, c, verdict, url) {
|
|
167
|
+
return originFromUpstream(buildUpstream(snap, c, verdict, url), c.sha256, c.extra);
|
|
168
|
+
}
|
|
169
|
+
function buildUpstream(snap, c, verdict, url) {
|
|
170
|
+
return {
|
|
171
|
+
repo: snap.repo,
|
|
172
|
+
ref: snap.ref,
|
|
173
|
+
commit: snap.commit,
|
|
174
|
+
blob: c.pick.blob,
|
|
175
|
+
path: c.pick.path,
|
|
176
|
+
license: verdict.spdx ?? '',
|
|
177
|
+
...(verdict.licenseUrl ? { licenseUrl: verdict.licenseUrl } : {}),
|
|
178
|
+
...(verdict.copyright ? { copyright: verdict.copyright } : {}),
|
|
179
|
+
tool: c.pick.tool,
|
|
180
|
+
kind: c.pick.kind,
|
|
181
|
+
url,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
/** Identity of an imported file for "already imported?" — GitHub treats owner and repo case-insensitively. */
|
|
185
|
+
const trackedKey = (repo, ref, file) => `${repo.toLowerCase()}@${ref}:${file}`;
|
|
186
|
+
exports.trackedKey = trackedKey;
|
|
187
|
+
/** Run `fn` over `items`, at most `limit` at a time; results in input order. */
|
|
188
|
+
async function mapLimit(items, limit, fn) {
|
|
189
|
+
const out = new Array(items.length);
|
|
190
|
+
let next = 0;
|
|
191
|
+
const worker = async () => {
|
|
192
|
+
while (next < items.length) {
|
|
193
|
+
const i = next++;
|
|
194
|
+
out[i] = await fn(items[i]);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Select, read and gate. Files are downloaded without being cached; only the
|
|
202
|
+
* ones that pass every gate are remembered, so nothing that was refused stays
|
|
203
|
+
* on disk. Network errors propagate.
|
|
204
|
+
*/
|
|
205
|
+
async function collectItems(snap, spec, concurrency = 4) {
|
|
206
|
+
const { picks, skipped } = (0, githubSelect_1.selectPicks)(snap, spec);
|
|
207
|
+
const items = [];
|
|
208
|
+
const blocked = [];
|
|
209
|
+
const results = await mapLimit(picks, concurrency, async (pick) => {
|
|
210
|
+
const text = await (0, githubSnapshot_1.readFile)(snap, pick.path, false);
|
|
211
|
+
if (text === null)
|
|
212
|
+
return { pick, skip: 'not a text file or larger than 64 KB — skipped' };
|
|
213
|
+
const prepared = prepareCandidate(pick, text);
|
|
214
|
+
if ('skip' in prepared)
|
|
215
|
+
return { pick, skip: prepared.skip };
|
|
216
|
+
const verdict = await (0, githubSnapshot_1.gate)(snap, pick.path, prepared.candidate.declaredLicense);
|
|
217
|
+
return { pick, candidate: prepared.candidate, verdict, text };
|
|
218
|
+
});
|
|
219
|
+
for (const r of results) {
|
|
220
|
+
if (r.skip !== undefined) {
|
|
221
|
+
skipped.push({ path: r.pick.path, reason: r.skip });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const url = (0, github_1.blobUrl)(snap.repo, snap.commit, r.pick.path);
|
|
225
|
+
if (!r.verdict.allowed) {
|
|
226
|
+
blocked.push({ path: r.pick.path, url, found: r.verdict.spdx });
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
(0, github_1.rememberRaw)(snap.owner, snap.name, snap.commit, r.pick.path, r.text);
|
|
230
|
+
items.push({
|
|
231
|
+
candidate: r.candidate,
|
|
232
|
+
verdict: r.verdict,
|
|
233
|
+
description: buildDescription(r.candidate.description, attributionLine(snap.repo, snap.commit, r.pick.path, r.verdict)),
|
|
234
|
+
url,
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
return { items, blocked, skipped };
|
|
238
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Which files of a repo count as prompts — the same places `ple import --scan`
|
|
4
|
+
* looks on disk, plus the shapes public repos use:
|
|
5
|
+
*
|
|
6
|
+
* SKILL.md (any depth ≤ 8) claude-code · skill
|
|
7
|
+
* *.prompt.md copilot · prompt
|
|
8
|
+
* .claude/commands/**.md claude-code · command
|
|
9
|
+
* .cursor/commands/**.md cursor · command
|
|
10
|
+
* *.mdc cursor · context
|
|
11
|
+
* …/patterns/<name>/system.md other · prompt (Fabric)
|
|
12
|
+
* AGENTS.md, CLAUDE.md agents-md · context (only at the requested path)
|
|
13
|
+
* one .md file named by the path other · prompt
|
|
14
|
+
*
|
|
15
|
+
* A path that is a file selects just that file. Nothing is fetched here: this
|
|
16
|
+
* works on the file list alone.
|
|
17
|
+
*/
|
|
18
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
19
|
+
exports.MAX_PICKS = void 0;
|
|
20
|
+
exports.selectPicks = selectPicks;
|
|
21
|
+
const format_1 = require("./format");
|
|
22
|
+
const secretGuard_1 = require("./secretGuard");
|
|
23
|
+
/** More than this under one path → ask for a narrower path instead of fetching them all. */
|
|
24
|
+
exports.MAX_PICKS = 200;
|
|
25
|
+
const MAX_SKILL_DEPTH = 8;
|
|
26
|
+
/**
|
|
27
|
+
* Server meta values are cut at 500 characters and the origin path (`github:<repo>/<path>`)
|
|
28
|
+
* at 512; a longer file path could not be matched again, so such a file is not imported.
|
|
29
|
+
*/
|
|
30
|
+
const MAX_FILE_PATH = 450;
|
|
31
|
+
const MAX_ORIGIN_PATH = 512;
|
|
32
|
+
const ODD_PATH = /[\u0000-\u001f\u007f-\u009f\\]/;
|
|
33
|
+
const baseOf = (p) => p.slice(p.lastIndexOf('/') + 1);
|
|
34
|
+
const dirOf = (p) => (p.includes('/') ? p.slice(0, p.lastIndexOf('/')) : '');
|
|
35
|
+
const stripExt = (name, ext) => name.replace(ext, '');
|
|
36
|
+
/** `…/<a>/<b>/rest` → the part after `<a>/<b>`, or null. */
|
|
37
|
+
function afterDirPair(segs, a, b) {
|
|
38
|
+
for (let i = 0; i + 2 < segs.length; i++) {
|
|
39
|
+
if (segs[i] === a && segs[i + 1] === b)
|
|
40
|
+
return segs.slice(i + 2);
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
function classify(path, ctx) {
|
|
45
|
+
const name = baseOf(path);
|
|
46
|
+
const segs = path.split('/');
|
|
47
|
+
if (name === 'SKILL.md' && ctx.depthBelowRoot <= MAX_SKILL_DEPTH) {
|
|
48
|
+
return { tool: 'claude-code', kind: 'skill', titleHint: baseOf(dirOf(path)) || ctx.repoName };
|
|
49
|
+
}
|
|
50
|
+
if (/\.prompt\.md$/i.test(name)) {
|
|
51
|
+
return { tool: 'copilot', kind: 'prompt', titleHint: stripExt(name, /\.prompt\.md$/i) };
|
|
52
|
+
}
|
|
53
|
+
if (/\.md$/i.test(name)) {
|
|
54
|
+
const claude = afterDirPair(segs, '.claude', 'commands');
|
|
55
|
+
if (claude)
|
|
56
|
+
return { tool: 'claude-code', kind: 'command', titleHint: stripExt(claude.join('/'), /\.md$/i) };
|
|
57
|
+
const cursor = afterDirPair(segs, '.cursor', 'commands');
|
|
58
|
+
if (cursor)
|
|
59
|
+
return { tool: 'cursor', kind: 'command', titleHint: stripExt(cursor.join('/'), /\.md$/i) };
|
|
60
|
+
}
|
|
61
|
+
if (/\.mdc$/i.test(name)) {
|
|
62
|
+
return { tool: 'cursor', kind: 'context', titleHint: stripExt(name, /\.mdc$/i) };
|
|
63
|
+
}
|
|
64
|
+
if (name === 'system.md' && segs.length >= 3 && segs[segs.length - 3] === 'patterns') {
|
|
65
|
+
return { tool: 'other', kind: 'prompt', titleHint: segs[segs.length - 2] };
|
|
66
|
+
}
|
|
67
|
+
if ((name === 'AGENTS.md' || name === 'CLAUDE.md') && (ctx.single || dirOf(path) === ctx.rootDir)) {
|
|
68
|
+
return { tool: 'agents-md', kind: 'context', titleHint: `${name} (${ctx.repoName})`, fixedTitle: true };
|
|
69
|
+
}
|
|
70
|
+
if (ctx.single && /\.md$/i.test(name)) {
|
|
71
|
+
return { tool: 'other', kind: 'prompt', titleHint: stripExt(name, /\.md$/i) };
|
|
72
|
+
}
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The prompt files under the requested path. Throws when nothing is there, when
|
|
77
|
+
* the path is a file that is not Markdown, or when there are more than
|
|
78
|
+
* {@link MAX_PICKS}. Files that match but must not be fetched (sensitive name,
|
|
79
|
+
* too large, odd path) are returned as `skipped` with the reason.
|
|
80
|
+
*/
|
|
81
|
+
function selectPicks(snap, spec) {
|
|
82
|
+
const root = spec.path;
|
|
83
|
+
const single = root !== '' && snap.byPath.has(root);
|
|
84
|
+
const prefix = root === '' ? '' : `${root}/`;
|
|
85
|
+
const where = `github.com/${snap.repo}@${(0, format_1.safeText)(snap.ref)}`;
|
|
86
|
+
const inside = single ? [snap.byPath.get(root)] : snap.entries.filter((e) => e.path.startsWith(prefix));
|
|
87
|
+
if (!single && root !== '' && inside.length === 0) {
|
|
88
|
+
throw new Error(`Nothing at '${(0, format_1.safeText)(root)}' in ${where}.`);
|
|
89
|
+
}
|
|
90
|
+
if (single && !/\.mdc?$/i.test(root)) {
|
|
91
|
+
throw new Error(`'${(0, format_1.safeText)(root)}' is not a Markdown file — only .md and .mdc files can be imported.`);
|
|
92
|
+
}
|
|
93
|
+
// Files per folder, for "(+N files not imported)" next to a skill.
|
|
94
|
+
const perDir = new Map();
|
|
95
|
+
for (const e of snap.entries) {
|
|
96
|
+
if (/^(LICENSE|LICENCE|COPYING|NOTICE)/i.test(baseOf(e.path)))
|
|
97
|
+
continue;
|
|
98
|
+
for (let d = dirOf(e.path);; d = dirOf(d)) {
|
|
99
|
+
perDir.set(d, (perDir.get(d) ?? 0) + 1);
|
|
100
|
+
if (d === '')
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const maxPath = Math.min(MAX_FILE_PATH, MAX_ORIGIN_PATH - `github:${snap.repo}/`.length);
|
|
105
|
+
const picks = [];
|
|
106
|
+
const skipped = [];
|
|
107
|
+
for (const e of inside) {
|
|
108
|
+
if (e.mode === '120000')
|
|
109
|
+
continue; // a symlink's content is its target path
|
|
110
|
+
const rel = single ? baseOf(e.path) : e.path.slice(prefix.length);
|
|
111
|
+
const cls = classify(e.path, {
|
|
112
|
+
repoName: snap.name,
|
|
113
|
+
rootDir: root,
|
|
114
|
+
single,
|
|
115
|
+
depthBelowRoot: rel.split('/').length - 1,
|
|
116
|
+
});
|
|
117
|
+
if (!cls)
|
|
118
|
+
continue;
|
|
119
|
+
if ((0, secretGuard_1.isDeniedFileName)(e.path)) {
|
|
120
|
+
skipped.push({ path: e.path, reason: 'sensitive file name — never read' });
|
|
121
|
+
}
|
|
122
|
+
else if (ODD_PATH.test(e.path) || e.path.length > maxPath) {
|
|
123
|
+
skipped.push({ path: e.path, reason: 'path too long or with control characters — skipped' });
|
|
124
|
+
}
|
|
125
|
+
else if (e.size !== undefined && e.size > secretGuard_1.MAX_SCAN_FILE_BYTES) {
|
|
126
|
+
skipped.push({ path: e.path, reason: `larger than ${secretGuard_1.MAX_SCAN_FILE_BYTES / 1024} KB — skipped` });
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
picks.push({
|
|
130
|
+
path: e.path,
|
|
131
|
+
blob: e.sha,
|
|
132
|
+
size: e.size,
|
|
133
|
+
tool: cls.tool,
|
|
134
|
+
kind: cls.kind,
|
|
135
|
+
titleHint: cls.titleHint,
|
|
136
|
+
fixedTitle: cls.fixedTitle === true,
|
|
137
|
+
extraFiles: cls.kind === 'skill' ? Math.max(0, (perDir.get(dirOf(e.path)) ?? 0) - 1) : 0,
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (picks.length > exports.MAX_PICKS) {
|
|
142
|
+
const hint = root ? `github:${snap.repo}/${root}/<folder>` : `github:${snap.repo}/<folder>`;
|
|
143
|
+
throw new Error(`Found ${picks.length} prompt files in ${where} — too many to import at once. Narrow it to a folder, e.g. ${hint}`);
|
|
144
|
+
}
|
|
145
|
+
// Code-unit order: the same on every machine (localeCompare depends on the ICU build).
|
|
146
|
+
picks.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
147
|
+
return { picks, skipped };
|
|
148
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A public repo at one commit, as `ple import` and `ple import --check` read it:
|
|
4
|
+
* repo info + the commit a ref points to + the list of files, plus the two
|
|
5
|
+
* helpers that read files from it (candidates, license files) and the license
|
|
6
|
+
* gate bound to it. The network and the cache live in ./github.ts.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.loadSnapshot = loadSnapshot;
|
|
10
|
+
exports.readFile = readFile;
|
|
11
|
+
exports.gate = gate;
|
|
12
|
+
const github_1 = require("./github");
|
|
13
|
+
const licenses_1 = require("./licenses");
|
|
14
|
+
/** repo → ref → commit → tree: three counted API calls at most, none when the cache has them. */
|
|
15
|
+
async function loadSnapshot(owner, name, ref) {
|
|
16
|
+
const info = await (0, github_1.getRepo)(owner, name);
|
|
17
|
+
const use = ref ?? info.defaultBranch;
|
|
18
|
+
const [o, n] = info.fullName.split('/');
|
|
19
|
+
const commit = await (0, github_1.resolveCommit)(o, n, use);
|
|
20
|
+
const tree = await (0, github_1.getTree)(o, n, commit);
|
|
21
|
+
return {
|
|
22
|
+
info,
|
|
23
|
+
repo: info.fullName,
|
|
24
|
+
owner: o,
|
|
25
|
+
name: n,
|
|
26
|
+
ref: use,
|
|
27
|
+
commit,
|
|
28
|
+
entries: tree.entries,
|
|
29
|
+
byPath: new Map(tree.entries.map((e) => [e.path, e])),
|
|
30
|
+
licenseFiles: (0, licenses_1.indexLicenseFiles)(tree.entries.map((e) => e.path)),
|
|
31
|
+
licenseText: new Map(),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* A repo file as text, or null when it is too large or not text. Network errors
|
|
36
|
+
* and the like throw. With `cache: false` the download is not kept on disk until
|
|
37
|
+
* the caller says so (see `rememberRaw`) — files that may still be refused stay off it.
|
|
38
|
+
*/
|
|
39
|
+
async function readFile(snap, path, cache) {
|
|
40
|
+
try {
|
|
41
|
+
return await (0, github_1.fetchRaw)(snap.owner, snap.name, snap.commit, path, { cache });
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (err instanceof github_1.GithubError && (err.kind === 'too_large' || err.kind === 'binary'))
|
|
45
|
+
return null;
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** License files are fetched (and cached) once per run, however many prompts sit under them. */
|
|
50
|
+
function readLicenseText(snap, path) {
|
|
51
|
+
let hit = snap.licenseText.get(path);
|
|
52
|
+
if (!hit) {
|
|
53
|
+
hit = readFile(snap, path, true);
|
|
54
|
+
snap.licenseText.set(path, hit);
|
|
55
|
+
}
|
|
56
|
+
return hit;
|
|
57
|
+
}
|
|
58
|
+
/** The license gate for one file at this snapshot (shared by import and `--check`). */
|
|
59
|
+
function gate(snap, path, declared) {
|
|
60
|
+
return (0, licenses_1.checkLicense)({
|
|
61
|
+
repo: snap.repo,
|
|
62
|
+
commit: snap.commit,
|
|
63
|
+
repoLicense: snap.info.licenseSpdx,
|
|
64
|
+
licenseFiles: snap.licenseFiles,
|
|
65
|
+
readText: (p) => readLicenseText(snap, p),
|
|
66
|
+
}, path, declared);
|
|
67
|
+
}
|