promptlike 0.5.0 → 0.6.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.
- package/CHANGELOG.md +59 -0
- package/README.md +101 -0
- package/dist/commands/config.js +41 -0
- package/dist/commands/diff.js +59 -0
- package/dist/commands/history.js +63 -0
- package/dist/commands/import.js +252 -0
- package/dist/commands/list.js +4 -0
- package/dist/commands/log.js +48 -0
- package/dist/commands/rollback.js +88 -0
- package/dist/commands/stats.js +112 -0
- package/dist/commands/suggest.js +244 -0
- package/dist/commands/sync.js +4 -0
- package/dist/index.js +59 -0
- package/dist/lib/api-client.js +155 -10
- package/dist/lib/diff.js +149 -0
- package/dist/lib/frontmatter.js +67 -0
- package/dist/lib/libraryCache.js +222 -0
- package/dist/lib/loopApi.js +35 -4
- package/dist/lib/promptResolver.js +36 -5
- package/dist/lib/promptVariables.js +4 -2
- package/dist/lib/rank.js +123 -0
- package/dist/lib/scanners/index.js +252 -0
- package/dist/lib/secretGuard.js +92 -0
- package/dist/lib/settings.js +105 -0
- package/package.json +1 -1
package/dist/lib/loopApi.js
CHANGED
|
@@ -9,10 +9,17 @@
|
|
|
9
9
|
* first, so the token is fresh).
|
|
10
10
|
*/
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.SAVE_TIMEOUT_MS = exports.VARIANTS_TIMEOUT_MS = void 0;
|
|
12
13
|
exports.requestVariants = requestVariants;
|
|
13
14
|
exports.saveWinner = saveWinner;
|
|
14
15
|
const constants_1 = require("./constants");
|
|
15
16
|
const config_1 = require("./config");
|
|
17
|
+
/**
|
|
18
|
+
* İstek zaman aşımları: sunucu takılırsa `ple loop` / `ple improve` sonsuza dek beklemesin.
|
|
19
|
+
* Varyant üretimi bir LLM çağrısı (genelde 10-40 sn), kayıt hafif bir yazma.
|
|
20
|
+
*/
|
|
21
|
+
exports.VARIANTS_TIMEOUT_MS = 120000;
|
|
22
|
+
exports.SAVE_TIMEOUT_MS = 30000;
|
|
16
23
|
const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
|
|
17
24
|
const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
|
|
18
25
|
/** The Pro upsell suffix — appended to every 403 from the loop endpoints. */
|
|
@@ -20,15 +27,32 @@ function proMessage(serverError) {
|
|
|
20
27
|
const base = serverError?.trim() || 'Loop requires Pro';
|
|
21
28
|
return `${base} — upgrade at ${constants_1.API_BASE_URL}/pricing`;
|
|
22
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Hata süre aşımından mı geldi? Önce sinyalin kendisine bakılır: eski Node /
|
|
32
|
+
* undici sürümlerinde gövde okuması yarıda kesilince hata `TimeoutError` yerine
|
|
33
|
+
* `TypeError: terminated` gibi başka biçimde gelebilir; sinyal `aborted` ise
|
|
34
|
+
* sebep süre dolmasıdır. Ad kontrolü yedektir (api-client.ts ile aynı kural).
|
|
35
|
+
*/
|
|
36
|
+
function isTimeout(err, signal) {
|
|
37
|
+
if (signal.aborted)
|
|
38
|
+
return true;
|
|
39
|
+
const name = err?.name;
|
|
40
|
+
return name === 'TimeoutError' || name === 'AbortError';
|
|
41
|
+
}
|
|
42
|
+
function timeoutError(timeoutMs) {
|
|
43
|
+
return new Error(`No response from ${constants_1.API_BASE_URL} within ${Math.round(timeoutMs / 1000)}s. ` +
|
|
44
|
+
'The server may still be working on it; wait a moment, then try again.');
|
|
45
|
+
}
|
|
23
46
|
/**
|
|
24
47
|
* Minimal bearer POST used by the two loop calls. Mirrors the error mapping
|
|
25
48
|
* of `api-client.ts` (network / 401 / 403 / 429 / error body) without the
|
|
26
49
|
* refresh-retry machinery — `ensureAuthed()` has already refreshed the token.
|
|
27
50
|
*/
|
|
28
|
-
async function bearerPost(path, body) {
|
|
51
|
+
async function bearerPost(path, body, timeoutMs) {
|
|
29
52
|
const config = (0, config_1.readConfig)();
|
|
30
53
|
if (!config)
|
|
31
54
|
throw new Error(NOT_LOGGED_IN);
|
|
55
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
32
56
|
let res;
|
|
33
57
|
try {
|
|
34
58
|
res = await fetch(constants_1.API_BASE_URL + path, {
|
|
@@ -38,9 +62,13 @@ async function bearerPost(path, body) {
|
|
|
38
62
|
Authorization: `Bearer ${config.access_token}`,
|
|
39
63
|
},
|
|
40
64
|
body: JSON.stringify(body),
|
|
65
|
+
// Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
|
|
66
|
+
signal,
|
|
41
67
|
});
|
|
42
68
|
}
|
|
43
69
|
catch (err) {
|
|
70
|
+
if (isTimeout(err, signal))
|
|
71
|
+
throw timeoutError(timeoutMs);
|
|
44
72
|
throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
|
|
45
73
|
}
|
|
46
74
|
if (res.status === 401)
|
|
@@ -49,7 +77,10 @@ async function bearerPost(path, body) {
|
|
|
49
77
|
try {
|
|
50
78
|
parsed = (await res.json());
|
|
51
79
|
}
|
|
52
|
-
catch {
|
|
80
|
+
catch (err) {
|
|
81
|
+
// Gövde yarıda kaldı ve süre doldu: "Request failed" değil, zaman aşımı de.
|
|
82
|
+
if (isTimeout(err, signal))
|
|
83
|
+
throw timeoutError(timeoutMs);
|
|
53
84
|
// Non-JSON body — fall through to the generic messages below.
|
|
54
85
|
}
|
|
55
86
|
// Pro gate → 403; tükenen AI token bütçesi → 402 (ApiErrors.insufficientTokens).
|
|
@@ -83,7 +114,7 @@ async function requestVariants(promptId, opts = {}) {
|
|
|
83
114
|
body.count = opts.count;
|
|
84
115
|
if (opts.focus !== undefined && opts.focus.trim() !== '')
|
|
85
116
|
body.focus = opts.focus.trim();
|
|
86
|
-
const res = await bearerPost(`/api/prompts/${promptId}/variants`, body);
|
|
117
|
+
const res = await bearerPost(`/api/prompts/${promptId}/variants`, body, exports.VARIANTS_TIMEOUT_MS);
|
|
87
118
|
return { variants: res.variants ?? [], tokensUsed: res.tokensUsed ?? 0 };
|
|
88
119
|
}
|
|
89
120
|
/**
|
|
@@ -100,5 +131,5 @@ async function saveWinner(promptId, variant, changelog) {
|
|
|
100
131
|
contextText: variant.context || '',
|
|
101
132
|
changelog,
|
|
102
133
|
source: 'cli',
|
|
103
|
-
});
|
|
134
|
+
}, exports.SAVE_TIMEOUT_MS);
|
|
104
135
|
}
|
|
@@ -7,6 +7,13 @@ const format_1 = require("./format");
|
|
|
7
7
|
const api_client_1 = require("./api-client");
|
|
8
8
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
9
9
|
const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
|
|
10
|
+
/** Server cap per page (GET /api/prompts maxLimit). */
|
|
11
|
+
const PAGE_LIMIT = 100;
|
|
12
|
+
/**
|
|
13
|
+
* Upper bound for the short-id walk: 20 pages x 100 = 2000 prompts (newest first). Keeps a
|
|
14
|
+
* worst-case lookup at 20 requests, well inside the per-minute read budget.
|
|
15
|
+
*/
|
|
16
|
+
const MAX_ID_PAGES = 20;
|
|
10
17
|
/**
|
|
11
18
|
* Resolve a `--project <value>` argument (UUID, exact name, or slug) to a
|
|
12
19
|
* project id. Throws a friendly error when it matches zero or multiple repos.
|
|
@@ -30,7 +37,8 @@ async function resolveProjectId(value) {
|
|
|
30
37
|
/**
|
|
31
38
|
* Resolve a user-supplied `<name>` argument to a single prompt.
|
|
32
39
|
* - Full UUID → direct detail lookup.
|
|
33
|
-
* - 8+ hex-char short-id prefix →
|
|
40
|
+
* - 8+ hex-char short-id prefix → walk the user's prompts page by page (newest
|
|
41
|
+
* first) and match the prefix client-side; stops at the first page with a hit.
|
|
34
42
|
* - Otherwise → title/description search (server-side, escaped), preferring
|
|
35
43
|
* title matches.
|
|
36
44
|
* - One match → return it. Multiple → print the candidates and return null.
|
|
@@ -55,11 +63,9 @@ async function resolvePromptByName(name, scope = {}) {
|
|
|
55
63
|
}
|
|
56
64
|
// Not found by id — fall through to a title search.
|
|
57
65
|
}
|
|
58
|
-
// 2) Short-id prefix (hex, 8+ chars, not a full UUID) →
|
|
66
|
+
// 2) Short-id prefix (hex, 8+ chars, not a full UUID) → walk the pages.
|
|
59
67
|
if (!UUID_RE.test(trimmed) && SHORT_ID_RE.test(trimmed)) {
|
|
60
|
-
const
|
|
61
|
-
const lower = trimmed.toLowerCase();
|
|
62
|
-
const matches = page.filter((p) => p.id.toLowerCase().startsWith(lower));
|
|
68
|
+
const matches = await findByShortId(trimmed, projectId);
|
|
63
69
|
if (matches.length === 1)
|
|
64
70
|
return matches[0];
|
|
65
71
|
if (matches.length > 1) {
|
|
@@ -87,6 +93,31 @@ async function resolvePromptByName(name, scope = {}) {
|
|
|
87
93
|
printAmbiguous(trimmed, pool);
|
|
88
94
|
return null;
|
|
89
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* Walks GET /api/prompts page by page (updated_at desc, stable id tie-break) and returns the
|
|
98
|
+
* prompts whose id starts with `prefix`. Stops at the first page that has a hit (that page's
|
|
99
|
+
* hits are all returned, so same-page ambiguity is still reported), on the last (short) page,
|
|
100
|
+
* after MAX_ID_PAGES, or if the server ignores `page` and repeats the first page.
|
|
101
|
+
* Before this, only the first 100 prompts were looked at, so a user with 100+ prompts got
|
|
102
|
+
* "not found" (or a wrong title-search fallback) for any older prompt's short id.
|
|
103
|
+
*/
|
|
104
|
+
async function findByShortId(prefix, projectId) {
|
|
105
|
+
const lower = prefix.toLowerCase();
|
|
106
|
+
let firstId;
|
|
107
|
+
for (let page = 1; page <= MAX_ID_PAGES; page++) {
|
|
108
|
+
const rows = await (0, api_client_1.listPrompts)({ limit: PAGE_LIMIT, page, projectId });
|
|
109
|
+
const matches = rows.filter((p) => p.id.toLowerCase().startsWith(lower));
|
|
110
|
+
if (matches.length > 0)
|
|
111
|
+
return matches;
|
|
112
|
+
if (rows.length < PAGE_LIMIT)
|
|
113
|
+
break; // last page
|
|
114
|
+
if (page === 1)
|
|
115
|
+
firstId = rows[0]?.id;
|
|
116
|
+
else if (rows[0]?.id === firstId)
|
|
117
|
+
break; // server ignored `page` → same rows again
|
|
118
|
+
}
|
|
119
|
+
return [];
|
|
120
|
+
}
|
|
90
121
|
function printAmbiguous(query, rows) {
|
|
91
122
|
console.error(format_1.c.warn(`'${query}' matched multiple prompts. Narrow with --project <repo>, or use a short id:`));
|
|
92
123
|
for (const r of rows.slice(0, 10)) {
|
|
@@ -36,7 +36,9 @@ function fillVariables(text, values) {
|
|
|
36
36
|
if (!text)
|
|
37
37
|
return '';
|
|
38
38
|
return text.replace(VARIABLE_PATTERN, (whole, name) => {
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
// Yalnız kendi anahtarları: {{constructor}} / {{toString}} gibi adlar
|
|
40
|
+
// Object.prototype'tan fonksiyon çekip metne "function Object()…" basmasın.
|
|
41
|
+
const value = Object.prototype.hasOwnProperty.call(values, name) ? values[name] : undefined;
|
|
42
|
+
return typeof value === 'string' && value !== '' ? value : whole;
|
|
41
43
|
});
|
|
42
44
|
}
|
package/dist/lib/rank.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Local suggestion ranking for `ple suggest` (W1-5, strategy F3).
|
|
4
|
+
*
|
|
5
|
+
* Pure and dependency-free: runs on the cached library with no network, so
|
|
6
|
+
* the Claude Code hook stays well under its time budget (p95 target 150 ms
|
|
7
|
+
* for 200 prompts — measured in rank.test.ts).
|
|
8
|
+
*
|
|
9
|
+
* Score is BM25-flavoured without the length normalisation (fields are
|
|
10
|
+
* short): Σ over task terms of idf(term) × field weight, where the weight is
|
|
11
|
+
* the best field the term hits — title ×3, tag ×2, description ×1, the first
|
|
12
|
+
* 600 characters of the body ×0.5 — plus a small log bonus for past use.
|
|
13
|
+
*
|
|
14
|
+
* Noise gate (a wrong nudge costs more than a missed one): a prompt qualifies
|
|
15
|
+
* only with a title or tag hit, or with at least two distinct terms matched.
|
|
16
|
+
* Tokenisation and stop words match the server's `src/lib/suggest.ts` so the
|
|
17
|
+
* CLI hook and MCP `suggest_prompts` agree on what a "term" is.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.MIN_SCORE = exports.BODY_HEAD = exports.MAX_TERMS = void 0;
|
|
21
|
+
exports.tokenize = tokenize;
|
|
22
|
+
exports.taskTerms = taskTerms;
|
|
23
|
+
exports.rankLibrary = rankLibrary;
|
|
24
|
+
const STOPWORDS = new Set([
|
|
25
|
+
'the', 'and', 'for', 'with', 'this', 'that', 'from', 'into', 'your', 'you', 'are', 'can', 'please',
|
|
26
|
+
'make', 'let', 'use', 'using', 'want', 'need', 'how', 'what', 'why', 'when', 'will', 'should', 'would',
|
|
27
|
+
'bir', 'bu', 've', 'ile', 'için', 'icin', 'şu', 'su', 'gibi', 'daha', 'çok', 'cok', 'olan', 'yap', 'lütfen', 'lutfen',
|
|
28
|
+
]);
|
|
29
|
+
exports.MAX_TERMS = 12;
|
|
30
|
+
/** Body characters considered — the head of a prompt says what it is for. */
|
|
31
|
+
exports.BODY_HEAD = 600;
|
|
32
|
+
/** Minimum score to be suggested at all. */
|
|
33
|
+
exports.MIN_SCORE = 2;
|
|
34
|
+
const WEIGHTS = { title: 3, tag: 2, description: 1, body: 0.5 };
|
|
35
|
+
/** Split text into lower-case word tokens (letters/digits, any script). */
|
|
36
|
+
function tokenize(text) {
|
|
37
|
+
return text
|
|
38
|
+
.toLocaleLowerCase('en-US')
|
|
39
|
+
.normalize('NFKC')
|
|
40
|
+
.split(/[^\p{L}\p{N}]+/u)
|
|
41
|
+
.filter(Boolean);
|
|
42
|
+
}
|
|
43
|
+
/** Task text → distinct search terms (≥3 chars, no stop words, max 12). */
|
|
44
|
+
function taskTerms(task) {
|
|
45
|
+
const words = tokenize(task).filter((w) => w.length >= 3 && !STOPWORDS.has(w));
|
|
46
|
+
return [...new Set(words)].slice(0, exports.MAX_TERMS);
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* A term hits a field token when one is a prefix of the other and the
|
|
50
|
+
* shorter side has ≥4 chars ("review" ~ "reviews", "refactor" ~ "refactoring"),
|
|
51
|
+
* or when they are equal.
|
|
52
|
+
*/
|
|
53
|
+
function hits(term, tokens) {
|
|
54
|
+
if (tokens.has(term))
|
|
55
|
+
return true;
|
|
56
|
+
for (const t of tokens) {
|
|
57
|
+
const [short, long] = t.length < term.length ? [t, term] : [term, t];
|
|
58
|
+
if (short.length >= 4 && long.startsWith(short))
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
return false;
|
|
62
|
+
}
|
|
63
|
+
function fieldsOf(item) {
|
|
64
|
+
return {
|
|
65
|
+
title: new Set(tokenize(item.title ?? '')),
|
|
66
|
+
tag: new Set((item.tags ?? []).flatMap((t) => tokenize(t))),
|
|
67
|
+
description: new Set(tokenize(item.description ?? '')),
|
|
68
|
+
body: new Set(tokenize((item.body ?? '').slice(0, exports.BODY_HEAD))),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Rank `items` for `task`; returns at most `limit` items above the noise gate. */
|
|
72
|
+
function rankLibrary(items, task, limit = 3) {
|
|
73
|
+
const terms = taskTerms(task);
|
|
74
|
+
if (terms.length === 0 || items.length === 0)
|
|
75
|
+
return [];
|
|
76
|
+
const fields = items.map(fieldsOf);
|
|
77
|
+
// Document frequency per term over the whole library → idf.
|
|
78
|
+
const n = items.length;
|
|
79
|
+
const idf = new Map();
|
|
80
|
+
for (const term of terms) {
|
|
81
|
+
let df = 0;
|
|
82
|
+
for (const f of fields) {
|
|
83
|
+
if (hits(term, f.title) || hits(term, f.tag) || hits(term, f.description) || hits(term, f.body))
|
|
84
|
+
df++;
|
|
85
|
+
}
|
|
86
|
+
// Smoothed so a 1-prompt library (or a term every prompt shares) still
|
|
87
|
+
// scores a title hit above MIN_SCORE — plain BM25 idf goes to ~0 there.
|
|
88
|
+
idf.set(term, Math.log(1 + (n + 1) / (df + 0.5)));
|
|
89
|
+
}
|
|
90
|
+
const ranked = [];
|
|
91
|
+
items.forEach((item, i) => {
|
|
92
|
+
const f = fields[i];
|
|
93
|
+
let score = 0;
|
|
94
|
+
let strongHit = false;
|
|
95
|
+
let matched = 0;
|
|
96
|
+
for (const term of terms) {
|
|
97
|
+
let w = 0;
|
|
98
|
+
if (hits(term, f.title))
|
|
99
|
+
w = WEIGHTS.title;
|
|
100
|
+
else if (hits(term, f.tag))
|
|
101
|
+
w = WEIGHTS.tag;
|
|
102
|
+
else if (hits(term, f.description))
|
|
103
|
+
w = WEIGHTS.description;
|
|
104
|
+
else if (hits(term, f.body))
|
|
105
|
+
w = WEIGHTS.body;
|
|
106
|
+
if (w === 0)
|
|
107
|
+
continue;
|
|
108
|
+
matched++;
|
|
109
|
+
if (w >= WEIGHTS.tag)
|
|
110
|
+
strongHit = true;
|
|
111
|
+
score += (idf.get(term) ?? 0) * w;
|
|
112
|
+
}
|
|
113
|
+
if (!strongHit && matched < 2)
|
|
114
|
+
return;
|
|
115
|
+
score += Math.log1p(Math.max(0, item.uses ?? 0)) * 0.3;
|
|
116
|
+
if (score < exports.MIN_SCORE)
|
|
117
|
+
return;
|
|
118
|
+
ranked.push({ item, score: Math.round(score * 100) / 100 });
|
|
119
|
+
});
|
|
120
|
+
return ranked
|
|
121
|
+
.sort((a, b) => b.score - a.score || (b.item.uses ?? 0) - (a.item.uses ?? 0))
|
|
122
|
+
.slice(0, Math.max(1, Math.min(limit, 10)));
|
|
123
|
+
}
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Agent-file scanners for `ple import --scan` (W1-2 — strategy F15).
|
|
4
|
+
*
|
|
5
|
+
* Finds the reusable instructions a developer already keeps on disk, in the
|
|
6
|
+
* places each agent reads them from:
|
|
7
|
+
*
|
|
8
|
+
* Claude Code ./.claude/commands/**\/*.md ~/.claude/commands/**\/*.md
|
|
9
|
+
* ./.claude/skills/*\/SKILL.md ~/.claude/skills/*\/SKILL.md
|
|
10
|
+
* Cursor ./.cursor/commands/*.md ~/.cursor/commands/*.md
|
|
11
|
+
* Codex ~/.codex/prompts/*.md
|
|
12
|
+
* Copilot ./.github/prompts/*.prompt.md
|
|
13
|
+
* Context ./AGENTS.md ./CLAUDE.md
|
|
14
|
+
*
|
|
15
|
+
* Table-driven: one entry per location, so adding a tool is one line.
|
|
16
|
+
* Every path goes through the secret guard (name check before opening, size
|
|
17
|
+
* check before reading, content check after) — see ./secretGuard.ts.
|
|
18
|
+
* Pure I/O on the local disk; nothing leaves the machine here.
|
|
19
|
+
*/
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.SCAN_TARGETS = void 0;
|
|
55
|
+
exports.hashBody = hashBody;
|
|
56
|
+
exports.scanAgentFiles = scanAgentFiles;
|
|
57
|
+
const crypto = __importStar(require("crypto"));
|
|
58
|
+
const fs = __importStar(require("fs"));
|
|
59
|
+
const os = __importStar(require("os"));
|
|
60
|
+
const path = __importStar(require("path"));
|
|
61
|
+
const frontmatter_1 = require("../frontmatter");
|
|
62
|
+
const secretGuard_1 = require("../secretGuard");
|
|
63
|
+
exports.SCAN_TARGETS = [
|
|
64
|
+
{ tool: 'claude-code', kind: 'command', root: 'cwd', pattern: { type: 'dir-md', dir: '.claude/commands', recursive: true } },
|
|
65
|
+
{ tool: 'claude-code', kind: 'command', root: 'home', pattern: { type: 'dir-md', dir: '.claude/commands', recursive: true } },
|
|
66
|
+
{ tool: 'claude-code', kind: 'skill', root: 'cwd', pattern: { type: 'skill-dirs', dir: '.claude/skills' } },
|
|
67
|
+
{ tool: 'claude-code', kind: 'skill', root: 'home', pattern: { type: 'skill-dirs', dir: '.claude/skills' } },
|
|
68
|
+
{ tool: 'cursor', kind: 'command', root: 'cwd', pattern: { type: 'dir-md', dir: '.cursor/commands', recursive: false } },
|
|
69
|
+
{ tool: 'cursor', kind: 'command', root: 'home', pattern: { type: 'dir-md', dir: '.cursor/commands', recursive: false } },
|
|
70
|
+
{ tool: 'codex', kind: 'prompt', root: 'home', pattern: { type: 'dir-md', dir: '.codex/prompts', recursive: false } },
|
|
71
|
+
{ tool: 'copilot', kind: 'prompt', root: 'cwd', pattern: { type: 'dir-md', dir: '.github/prompts', recursive: false, suffix: '.prompt.md' } },
|
|
72
|
+
{ tool: 'agents-md', kind: 'context', root: 'cwd', pattern: { type: 'file', file: 'AGENTS.md' } },
|
|
73
|
+
{ tool: 'agents-md', kind: 'context', root: 'cwd', pattern: { type: 'file', file: 'CLAUDE.md' } },
|
|
74
|
+
];
|
|
75
|
+
/** Recursion + volume guards — a scan must stay a one-second operation. */
|
|
76
|
+
const MAX_DEPTH = 4;
|
|
77
|
+
const MAX_FILES = 500;
|
|
78
|
+
const MAX_TAGS = 10;
|
|
79
|
+
const MAX_TITLE = 200;
|
|
80
|
+
const MAX_DESCRIPTION = 1000;
|
|
81
|
+
const KNOWN_KEYS = new Set(['name', 'title', 'description', 'tags']);
|
|
82
|
+
/** Line-ending + surrounding-whitespace insensitive hash of a prompt body. */
|
|
83
|
+
function hashBody(body) {
|
|
84
|
+
const normalized = body.replace(/\r\n/g, '\n').trim();
|
|
85
|
+
return crypto.createHash('sha256').update(normalized, 'utf8').digest('hex');
|
|
86
|
+
}
|
|
87
|
+
function listMdFiles(dir, recursive, suffix, depth = 0) {
|
|
88
|
+
let entries;
|
|
89
|
+
try {
|
|
90
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return [];
|
|
94
|
+
}
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
97
|
+
const full = path.join(dir, e.name);
|
|
98
|
+
if (e.isDirectory()) {
|
|
99
|
+
if (recursive && depth < MAX_DEPTH && !e.name.startsWith('.')) {
|
|
100
|
+
out.push(...listMdFiles(full, recursive, suffix, depth + 1));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
else if ((e.isFile() || e.isSymbolicLink()) && e.name.toLowerCase().endsWith(suffix)) {
|
|
104
|
+
out.push(full);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
function expand(target, base) {
|
|
110
|
+
const p = target.pattern;
|
|
111
|
+
if (p.type === 'file') {
|
|
112
|
+
const f = path.join(base, p.file);
|
|
113
|
+
return fs.existsSync(f) ? [f] : [];
|
|
114
|
+
}
|
|
115
|
+
if (p.type === 'skill-dirs') {
|
|
116
|
+
const dir = path.join(base, p.dir);
|
|
117
|
+
let entries;
|
|
118
|
+
try {
|
|
119
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
return entries
|
|
125
|
+
.filter((e) => e.isDirectory() || e.isSymbolicLink())
|
|
126
|
+
.map((e) => path.join(dir, e.name, 'SKILL.md'))
|
|
127
|
+
.filter((f) => fs.existsSync(f))
|
|
128
|
+
.sort();
|
|
129
|
+
}
|
|
130
|
+
return listMdFiles(path.join(base, p.dir), p.recursive, p.suffix ?? '.md');
|
|
131
|
+
}
|
|
132
|
+
function titleFor(target, file, base, fmName) {
|
|
133
|
+
if (fmName)
|
|
134
|
+
return fmName;
|
|
135
|
+
const p = target.pattern;
|
|
136
|
+
if (p.type === 'file')
|
|
137
|
+
return `${path.basename(file)} (${path.basename(base)})`;
|
|
138
|
+
if (p.type === 'skill-dirs')
|
|
139
|
+
return path.basename(path.dirname(file));
|
|
140
|
+
const rel = path.relative(path.join(base, p.dir), file).split(path.sep).join('/');
|
|
141
|
+
const suffix = p.suffix ?? '.md';
|
|
142
|
+
return rel.toLowerCase().endsWith(suffix) ? rel.slice(0, -suffix.length) : rel;
|
|
143
|
+
}
|
|
144
|
+
function displayPathFor(file, root, home, cwd) {
|
|
145
|
+
if (root === 'home')
|
|
146
|
+
return `~/${path.relative(home, file).split(path.sep).join('/')}`;
|
|
147
|
+
return path.relative(cwd, file).split(path.sep).join('/');
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Read one file through the guard. Returns the raw text, or a skip reason.
|
|
151
|
+
* Symlinks are followed only to a regular `.md` file that also passes the
|
|
152
|
+
* name + size checks, so a link cannot smuggle `~/.ssh/id_rsa` into a scan.
|
|
153
|
+
*/
|
|
154
|
+
function guardedRead(file) {
|
|
155
|
+
if ((0, secretGuard_1.isDeniedFileName)(file))
|
|
156
|
+
return { reason: 'sensitive file name — never read' };
|
|
157
|
+
let real;
|
|
158
|
+
try {
|
|
159
|
+
real = fs.realpathSync(file);
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
return { reason: 'unreadable' };
|
|
163
|
+
}
|
|
164
|
+
if ((0, secretGuard_1.isDeniedFileName)(real) || !real.toLowerCase().endsWith('.md')) {
|
|
165
|
+
return { reason: 'link to a non-markdown or sensitive file — never read' };
|
|
166
|
+
}
|
|
167
|
+
let stat;
|
|
168
|
+
try {
|
|
169
|
+
stat = fs.statSync(real);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
return { reason: 'unreadable' };
|
|
173
|
+
}
|
|
174
|
+
if (!stat.isFile())
|
|
175
|
+
return { reason: 'not a regular file' };
|
|
176
|
+
if (stat.size > secretGuard_1.MAX_SCAN_FILE_BYTES) {
|
|
177
|
+
return { reason: `larger than ${secretGuard_1.MAX_SCAN_FILE_BYTES / 1024} KB — skipped` };
|
|
178
|
+
}
|
|
179
|
+
try {
|
|
180
|
+
return { text: fs.readFileSync(real, 'utf-8'), bytes: stat.size };
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return { reason: 'unreadable' };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
function scanAgentFiles(options = {}) {
|
|
187
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
188
|
+
const home = path.resolve(options.home ?? os.homedir());
|
|
189
|
+
const candidates = [];
|
|
190
|
+
const skipped = [];
|
|
191
|
+
const duplicates = [];
|
|
192
|
+
const seenFiles = new Set();
|
|
193
|
+
const seenHashes = new Set();
|
|
194
|
+
let fileCount = 0;
|
|
195
|
+
scan: for (const target of exports.SCAN_TARGETS) {
|
|
196
|
+
const base = target.root === 'home' ? home : cwd;
|
|
197
|
+
// When cwd IS home, project and home targets overlap — scan once.
|
|
198
|
+
for (const file of expand(target, base)) {
|
|
199
|
+
const key = path.resolve(file);
|
|
200
|
+
if (seenFiles.has(key))
|
|
201
|
+
continue;
|
|
202
|
+
seenFiles.add(key);
|
|
203
|
+
if (++fileCount > MAX_FILES) {
|
|
204
|
+
skipped.push({ displayPath: displayPathFor(file, target.root, home, cwd), reason: `scan capped at ${MAX_FILES} files` });
|
|
205
|
+
break scan;
|
|
206
|
+
}
|
|
207
|
+
const displayPath = displayPathFor(file, target.root, home, cwd);
|
|
208
|
+
const read = guardedRead(file);
|
|
209
|
+
if ('reason' in read) {
|
|
210
|
+
skipped.push({ displayPath, reason: read.reason });
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
const secret = (0, secretGuard_1.findSecret)(read.text);
|
|
214
|
+
if (secret) {
|
|
215
|
+
skipped.push({ displayPath, reason: `looks like it contains a ${secret} — remove it, then re-run` });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
const fm = (0, frontmatter_1.parseFrontmatter)(read.text);
|
|
219
|
+
const body = fm.body.trim();
|
|
220
|
+
if (!body) {
|
|
221
|
+
skipped.push({ displayPath, reason: 'empty body' });
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
const fmTags = fm.lists.tags ?? (fm.fields.tags ? fm.fields.tags.split(',') : []);
|
|
225
|
+
const tags = [...new Set([...fmTags.map((t) => t.trim()).filter(Boolean), target.tool])].slice(0, MAX_TAGS);
|
|
226
|
+
const meta = {};
|
|
227
|
+
for (const [k, v] of Object.entries(fm.fields)) {
|
|
228
|
+
if (!KNOWN_KEYS.has(k) && v)
|
|
229
|
+
meta[k] = v;
|
|
230
|
+
}
|
|
231
|
+
const candidate = {
|
|
232
|
+
tool: target.tool,
|
|
233
|
+
kind: target.kind,
|
|
234
|
+
displayPath,
|
|
235
|
+
title: titleFor(target, file, base, fm.fields.name || fm.fields.title || '').slice(0, MAX_TITLE),
|
|
236
|
+
description: (fm.fields.description ?? '').slice(0, MAX_DESCRIPTION),
|
|
237
|
+
tags,
|
|
238
|
+
body,
|
|
239
|
+
meta,
|
|
240
|
+
bytes: read.bytes,
|
|
241
|
+
sha256: hashBody(body),
|
|
242
|
+
};
|
|
243
|
+
if (seenHashes.has(candidate.sha256)) {
|
|
244
|
+
duplicates.push(candidate);
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
seenHashes.add(candidate.sha256);
|
|
248
|
+
candidates.push(candidate);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return { candidates, skipped, duplicates };
|
|
252
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Secret guard for `ple import --scan` (W1-2).
|
|
4
|
+
*
|
|
5
|
+
* Two layers, both deliberately conservative:
|
|
6
|
+
* 1. NAME — files that are secrets by convention (`.env*`, `*.key`, `*.pem`,
|
|
7
|
+
* `credentials*`, SSH keys) are never even opened.
|
|
8
|
+
* 2. CONTENT — a file that *does* get read is dropped (and reported without
|
|
9
|
+
* echoing the match) when it contains something shaped like a live token.
|
|
10
|
+
*
|
|
11
|
+
* Importing uploads to the user's account, so a false positive (skip a file,
|
|
12
|
+
* say why) is always cheaper than a false negative (leak a key into a prompt
|
|
13
|
+
* that might one day be made public).
|
|
14
|
+
*/
|
|
15
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
16
|
+
if (k2 === undefined) k2 = k;
|
|
17
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
18
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
19
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
20
|
+
}
|
|
21
|
+
Object.defineProperty(o, k2, desc);
|
|
22
|
+
}) : (function(o, m, k, k2) {
|
|
23
|
+
if (k2 === undefined) k2 = k;
|
|
24
|
+
o[k2] = m[k];
|
|
25
|
+
}));
|
|
26
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
27
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
28
|
+
}) : function(o, v) {
|
|
29
|
+
o["default"] = v;
|
|
30
|
+
});
|
|
31
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
32
|
+
var ownKeys = function(o) {
|
|
33
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
34
|
+
var ar = [];
|
|
35
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
36
|
+
return ar;
|
|
37
|
+
};
|
|
38
|
+
return ownKeys(o);
|
|
39
|
+
};
|
|
40
|
+
return function (mod) {
|
|
41
|
+
if (mod && mod.__esModule) return mod;
|
|
42
|
+
var result = {};
|
|
43
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
44
|
+
__setModuleDefault(result, mod);
|
|
45
|
+
return result;
|
|
46
|
+
};
|
|
47
|
+
})();
|
|
48
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
49
|
+
exports.MAX_SCAN_FILE_BYTES = void 0;
|
|
50
|
+
exports.isDeniedFileName = isDeniedFileName;
|
|
51
|
+
exports.findSecret = findSecret;
|
|
52
|
+
const path = __importStar(require("path"));
|
|
53
|
+
/** Max size read from disk. Bigger files are skipped before reading. */
|
|
54
|
+
exports.MAX_SCAN_FILE_BYTES = 64 * 1024;
|
|
55
|
+
const DENY_NAME_PATTERNS = [
|
|
56
|
+
/^\.env(\..*)?$/i,
|
|
57
|
+
/\.key$/i,
|
|
58
|
+
/\.pem$/i,
|
|
59
|
+
/\.p12$/i,
|
|
60
|
+
/\.pfx$/i,
|
|
61
|
+
/^credentials/i,
|
|
62
|
+
/^id_(rsa|dsa|ecdsa|ed25519)/i,
|
|
63
|
+
/^\.netrc$/i,
|
|
64
|
+
/^\.npmrc$/i,
|
|
65
|
+
];
|
|
66
|
+
/** True when a file must never be opened, judged by its name alone. */
|
|
67
|
+
function isDeniedFileName(filePath) {
|
|
68
|
+
const base = path.basename(filePath);
|
|
69
|
+
return DENY_NAME_PATTERNS.some((re) => re.test(base));
|
|
70
|
+
}
|
|
71
|
+
const SECRET_PATTERNS = [
|
|
72
|
+
{ label: 'Anthropic/OpenAI API key', re: /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/ },
|
|
73
|
+
{ label: 'AWS access key', re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/ },
|
|
74
|
+
{ label: 'GitHub token', re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{30,}/ },
|
|
75
|
+
{ label: 'GitLab token', re: /\bglpat-[A-Za-z0-9_-]{20,}/ },
|
|
76
|
+
{ label: 'Slack token', re: /\bxox[abprs]-[A-Za-z0-9-]{10,}/ },
|
|
77
|
+
{ label: 'Google API key', re: /\bAIza[0-9A-Za-z_-]{35}\b/ },
|
|
78
|
+
{ label: 'Stripe key', re: /\b(?:sk|rk)_live_[A-Za-z0-9]{20,}/ },
|
|
79
|
+
{ label: 'private key', re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
|
|
80
|
+
{ label: 'JWT', re: /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/ },
|
|
81
|
+
];
|
|
82
|
+
/**
|
|
83
|
+
* Returns the *kind* of secret found (never the value), or null when clean.
|
|
84
|
+
* Callers print the label so the user knows which file to clean up.
|
|
85
|
+
*/
|
|
86
|
+
function findSecret(content) {
|
|
87
|
+
for (const { label, re } of SECRET_PATTERNS) {
|
|
88
|
+
if (re.test(content))
|
|
89
|
+
return label;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|