promptlike 0.10.0 → 0.11.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 +65 -0
- package/README.md +129 -4
- package/dist/commands/feedback.js +351 -0
- package/dist/commands/local.js +3 -1
- package/dist/commands/localHistory.js +1 -1
- package/dist/commands/save.js +72 -1
- package/dist/commands/search.js +4 -1
- package/dist/commands/suggest.js +134 -11
- package/dist/commands/whoami.js +80 -0
- package/dist/help.js +4 -2
- package/dist/index.js +5 -1
- package/dist/lib/accountSave.js +159 -0
- package/dist/lib/api-client.js +28 -0
- package/dist/lib/feedbackApi.js +134 -0
- package/dist/lib/feedbackHint.js +15 -0
- package/dist/lib/feedbackInput.js +182 -0
- package/dist/lib/feedbackQueue.js +219 -0
- package/dist/lib/feedbackSource.js +53 -0
- package/dist/lib/libraryCache.js +1 -0
- package/dist/lib/localStore.js +49 -10
- package/dist/lib/loopApi.js +38 -2
- package/dist/lib/promptResolver.js +51 -5
- package/dist/lib/rank.js +24 -6
- package/dist/lib/titleMatch.js +32 -0
- package/dist/program.js +147 -5
- package/package.json +1 -1
package/dist/lib/localStore.js
CHANGED
|
@@ -64,7 +64,9 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
64
64
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
65
65
|
exports.localRoot = localRoot;
|
|
66
66
|
exports.promptsDir = promptsDir;
|
|
67
|
+
exports.legacySlugify = legacySlugify;
|
|
67
68
|
exports.slugify = slugify;
|
|
69
|
+
exports.slugFor = slugFor;
|
|
68
70
|
exports.serialize = serialize;
|
|
69
71
|
exports.parse = parse;
|
|
70
72
|
exports.filePath = filePath;
|
|
@@ -81,6 +83,8 @@ const os = __importStar(require("os"));
|
|
|
81
83
|
const path = __importStar(require("path"));
|
|
82
84
|
const fsSafe_1 = require("./fsSafe");
|
|
83
85
|
const promptTemplate_1 = require("./promptTemplate");
|
|
86
|
+
const titleMatch_1 = require("./titleMatch");
|
|
87
|
+
const rank_1 = require("./rank");
|
|
84
88
|
/** Frontmatter key ↔ `Upstream` property. Order = file order. */
|
|
85
89
|
const UPSTREAM_KEYS = [
|
|
86
90
|
['repo', 'upstream_repo'],
|
|
@@ -105,26 +109,54 @@ function localRoot() {
|
|
|
105
109
|
function promptsDir() {
|
|
106
110
|
return path.join(localRoot(), 'prompts');
|
|
107
111
|
}
|
|
112
|
+
/**
|
|
113
|
+
* The slug rule up to 0.10.0: only path-hostile characters were dropped, so shell-special
|
|
114
|
+
* ones (`$ ( ) ; ` ' & !`) survived into file names. Kept ONLY to find files that already
|
|
115
|
+
* exist under such a name — see {@link slugFor}. New files never use it.
|
|
116
|
+
*/
|
|
117
|
+
function legacySlugify(input) {
|
|
118
|
+
const cleaned = input
|
|
119
|
+
.toLowerCase()
|
|
120
|
+
.trim()
|
|
121
|
+
.replace(/[/\\:*?"<>|.]+/g, '') // path-hostile on macOS/Linux/Windows
|
|
122
|
+
.replace(/\s+/g, '-')
|
|
123
|
+
.replace(/-{2,}/g, '-')
|
|
124
|
+
.replace(/^-+|-+$/g, '');
|
|
125
|
+
return cleaned || 'prompt';
|
|
126
|
+
}
|
|
108
127
|
/**
|
|
109
128
|
* Turn a title into a filename-safe slug.
|
|
110
129
|
*
|
|
111
130
|
* Unicode letters are kept (`ş`, `ğ`, `é` are valid in filenames on every
|
|
112
131
|
* platform we support), so a Turkish title does not collapse into gibberish.
|
|
113
|
-
*
|
|
132
|
+
* Path-hostile characters are removed, and so are the ones a shell treats
|
|
133
|
+
* specially (`$ ( ) ; ` ' " \ < > | & * ! { }`): a slug ends up in commands people
|
|
134
|
+
* (and Claude) run, e.g. `ple get <slug>`, so it must never be able to start one.
|
|
114
135
|
*/
|
|
115
136
|
function slugify(input) {
|
|
116
137
|
const cleaned = input
|
|
117
138
|
.toLowerCase()
|
|
118
139
|
.trim()
|
|
119
|
-
.replace(/[/\\:*?"
|
|
140
|
+
.replace(/[/\\:*?"<>|.$()`;'&!{}]+/g, '') // path-hostile + shell-special
|
|
120
141
|
.replace(/\s+/g, '-')
|
|
121
142
|
.replace(/-{2,}/g, '-')
|
|
122
143
|
.replace(/^-+|-+$/g, '');
|
|
123
144
|
return cleaned || 'prompt';
|
|
124
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* The slug to save `title` under. Normally {@link slugify}; but when a file already exists under
|
|
148
|
+
* the pre-0.10.1 name (`fix-(bug).md`), that name wins, so saving the same title again still
|
|
149
|
+
* finds, updates and keeps the history of that prompt instead of silently creating a second one.
|
|
150
|
+
* Existing files are never renamed.
|
|
151
|
+
*/
|
|
152
|
+
function slugFor(title) {
|
|
153
|
+
const legacy = legacySlugify(title);
|
|
154
|
+
return legacy !== slugify(title) && exists(legacy) ? legacy : slugify(title);
|
|
155
|
+
}
|
|
125
156
|
function escapeValue(v) {
|
|
126
|
-
// Frontmatter is one value per line; a newline would silently truncate it.
|
|
127
|
-
|
|
157
|
+
// Frontmatter is one value per line; a newline would silently truncate it. The reader's `m` flag
|
|
158
|
+
// also treats a lone \r, U+2028 and U+2029 as line ends, so an imported title could plant a field.
|
|
159
|
+
return v.replace(/[\r\n\u2028\u2029]+/g, ' ').trim();
|
|
128
160
|
}
|
|
129
161
|
function serialize(p) {
|
|
130
162
|
// Empty fields are written without a trailing space — these files are meant
|
|
@@ -283,8 +315,10 @@ function list() {
|
|
|
283
315
|
.sort((a, b) => (b.updated || '').localeCompare(a.updated || ''));
|
|
284
316
|
}
|
|
285
317
|
/**
|
|
286
|
-
* Resolve a user-typed name to one prompt: exact slug, then exact title,
|
|
287
|
-
*
|
|
318
|
+
* Resolve a user-typed name to one prompt: exact slug, then exact title, then the same name ignoring
|
|
319
|
+
* case, Turkish letters and accents ("hat baslangici" = "Hat başlangıcı"), then a unique partial of
|
|
320
|
+
* title or slug (same folding). A step with several hits reports them as candidates — ambiguity is
|
|
321
|
+
* reported, never guessed — and a later, looser step is never tried once an earlier one hit.
|
|
288
322
|
*/
|
|
289
323
|
function resolve(name) {
|
|
290
324
|
const all = list();
|
|
@@ -299,19 +333,24 @@ function resolve(name) {
|
|
|
299
333
|
return { prompt: byTitle[0] };
|
|
300
334
|
if (byTitle.length > 1)
|
|
301
335
|
return { candidates: byTitle };
|
|
302
|
-
const
|
|
336
|
+
const folded = all.filter((p) => (0, titleMatch_1.foldedEquals)(p.title, name) || (0, titleMatch_1.foldedEquals)(p.slug, name));
|
|
337
|
+
if (folded.length === 1)
|
|
338
|
+
return { prompt: folded[0] };
|
|
339
|
+
if (folded.length > 1)
|
|
340
|
+
return { candidates: folded };
|
|
341
|
+
const partial = all.filter((p) => (0, titleMatch_1.foldedIncludes)(p.slug, name) || (0, titleMatch_1.foldedIncludes)(p.title, name));
|
|
303
342
|
if (partial.length === 1)
|
|
304
343
|
return { prompt: partial[0] };
|
|
305
344
|
if (partial.length > 1)
|
|
306
345
|
return { candidates: partial };
|
|
307
346
|
return null;
|
|
308
347
|
}
|
|
309
|
-
/** Free-text search over title, description, tags and body. */
|
|
348
|
+
/** Free-text search over title, description, tags and body — case, Turkish letters and accents folded ("baslangic" finds "başlangıç"). */
|
|
310
349
|
function search(query) {
|
|
311
|
-
const needle =
|
|
350
|
+
const needle = (0, rank_1.foldText)(query.trim());
|
|
312
351
|
if (!needle)
|
|
313
352
|
return [];
|
|
314
|
-
return list().filter((p) => [p.title, p.description, p.tags.join(' '), p.body].join('\n')
|
|
353
|
+
return list().filter((p) => (0, rank_1.foldText)([p.title, p.description, p.tags.join(' '), p.body].join('\n')).includes(needle));
|
|
315
354
|
}
|
|
316
355
|
/** Fill `{{variables}}`; report the ones left unfilled rather than shipping them. */
|
|
317
356
|
function fillVariables(body, values) {
|
package/dist/lib/loopApi.js
CHANGED
|
@@ -15,6 +15,9 @@ exports.bearerGet = bearerGet;
|
|
|
15
15
|
exports.requestVariants = requestVariants;
|
|
16
16
|
exports.saveVersion = saveVersion;
|
|
17
17
|
exports.saveWinner = saveWinner;
|
|
18
|
+
exports.createPrompt = createPrompt;
|
|
19
|
+
exports.patchDescription = patchDescription;
|
|
20
|
+
exports.addTagByName = addTagByName;
|
|
18
21
|
const constants_1 = require("./constants");
|
|
19
22
|
const config_1 = require("./config");
|
|
20
23
|
/**
|
|
@@ -66,10 +69,10 @@ async function bearerRequest(method, path, body, timeoutMs, forbidden) {
|
|
|
66
69
|
res = await fetch(constants_1.API_BASE_URL + path, {
|
|
67
70
|
method,
|
|
68
71
|
headers: {
|
|
69
|
-
...(method
|
|
72
|
+
...(method !== 'GET' ? { 'Content-Type': 'application/json' } : {}),
|
|
70
73
|
Authorization: `Bearer ${config.access_token}`,
|
|
71
74
|
},
|
|
72
|
-
body: method
|
|
75
|
+
body: method !== 'GET' ? JSON.stringify(body) : undefined,
|
|
73
76
|
// Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
|
|
74
77
|
signal,
|
|
75
78
|
redirect: 'manual',
|
|
@@ -185,3 +188,36 @@ async function saveWinner(promptId, variant, changelog) {
|
|
|
185
188
|
source: 'cli',
|
|
186
189
|
}, exports.SAVE_TIMEOUT_MS);
|
|
187
190
|
}
|
|
191
|
+
const createForbidden = (serverError, body) => typeof body.upgradeUrl === 'string'
|
|
192
|
+
? new Error(`${serverError?.trim() || 'Prompt limit reached on this plan.'} — upgrade at ${constants_1.API_BASE_URL}/pricing`)
|
|
193
|
+
: new Error(serverError?.trim() || 'You are not allowed to add prompts to this repo.');
|
|
194
|
+
const metaForbidden = (serverError) => new Error(serverError?.trim() || 'You are not allowed to change this prompt.');
|
|
195
|
+
/**
|
|
196
|
+
* Create a prompt (with its first version) in a repo through the save endpoint
|
|
197
|
+
* (`isNew`). A single-body prompt goes into `contextText` — the slot `ple sync`
|
|
198
|
+
* and the import route use — so it reads back exactly as written.
|
|
199
|
+
*/
|
|
200
|
+
async function createPrompt(input) {
|
|
201
|
+
return bearerRequest('POST', '/api/prompts', {
|
|
202
|
+
isNew: true,
|
|
203
|
+
projectId: input.projectId,
|
|
204
|
+
title: input.title,
|
|
205
|
+
description: input.description ?? '',
|
|
206
|
+
roleText: '',
|
|
207
|
+
descriptionText: '',
|
|
208
|
+
contextText: input.body,
|
|
209
|
+
changelog: input.changelog,
|
|
210
|
+
source: 'cli',
|
|
211
|
+
}, exports.SAVE_TIMEOUT_MS, createForbidden);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* PATCH /api/prompts/{id} — change the prompt-level description only. No version
|
|
215
|
+
* is created (the description is not part of a version) and nothing else moves.
|
|
216
|
+
*/
|
|
217
|
+
async function patchDescription(promptId, description) {
|
|
218
|
+
await bearerRequest('PATCH', `/api/prompts/${encodeURIComponent(promptId)}`, { description }, exports.SAVE_TIMEOUT_MS, metaForbidden);
|
|
219
|
+
}
|
|
220
|
+
/** POST /api/prompts/{id}/tags — attach a tag by name (found or created in the prompt's repo); already attached is a no-op. */
|
|
221
|
+
async function addTagByName(promptId, tagName) {
|
|
222
|
+
await bearerRequest('POST', `/api/prompts/${encodeURIComponent(promptId)}/tags`, { tagName }, exports.SAVE_TIMEOUT_MS, metaForbidden);
|
|
223
|
+
}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.resolveProjectId = resolveProjectId;
|
|
4
|
+
exports.resolveProject = resolveProject;
|
|
4
5
|
exports.resolvePromptByName = resolvePromptByName;
|
|
5
6
|
exports.lookupPromptByName = lookupPromptByName;
|
|
6
7
|
exports.fetchPromptContent = fetchPromptContent;
|
|
7
8
|
const format_1 = require("./format");
|
|
9
|
+
const titleMatch_1 = require("./titleMatch");
|
|
8
10
|
const api_client_1 = require("./api-client");
|
|
9
11
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
10
12
|
const SHORT_ID_RE = /^[0-9a-f]{8,}$/i;
|
|
@@ -20,20 +22,27 @@ const MAX_ID_PAGES = 20;
|
|
|
20
22
|
* project id. Throws a friendly error when it matches zero or multiple repos.
|
|
21
23
|
*/
|
|
22
24
|
async function resolveProjectId(value) {
|
|
25
|
+
return (await resolveProject(value)).id;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Same lookup as {@link resolveProjectId}, plus the repo's name when the lookup had to read the repo
|
|
29
|
+
* list (a bare UUID is trusted as is, with no request and no name).
|
|
30
|
+
*/
|
|
31
|
+
async function resolveProject(value) {
|
|
23
32
|
const trimmed = value.trim();
|
|
24
33
|
if (UUID_RE.test(trimmed))
|
|
25
|
-
return trimmed;
|
|
34
|
+
return { id: trimmed };
|
|
26
35
|
const projects = await (0, api_client_1.listProjects)();
|
|
27
36
|
const lower = trimmed.toLowerCase();
|
|
28
37
|
const matches = projects.filter((p) => p.name.toLowerCase() === lower || (p.slug ?? '').toLowerCase() === lower);
|
|
29
38
|
if (matches.length === 1)
|
|
30
|
-
return matches[0].id;
|
|
39
|
+
return { id: matches[0].id, name: matches[0].name };
|
|
31
40
|
if (matches.length === 0) {
|
|
32
41
|
// Same short id `ple repo list` prints (8+ hex characters).
|
|
33
42
|
if (SHORT_ID_RE.test(trimmed)) {
|
|
34
43
|
const byPrefix = projects.filter((p) => p.id.toLowerCase().startsWith(lower));
|
|
35
44
|
if (byPrefix.length === 1)
|
|
36
|
-
return byPrefix[0].id;
|
|
45
|
+
return { id: byPrefix[0].id, name: byPrefix[0].name };
|
|
37
46
|
if (byPrefix.length > 1) {
|
|
38
47
|
const hint = byPrefix.map((p) => `${(0, format_1.shortId)(p.id)} ${p.name}`).join(', ');
|
|
39
48
|
throw new Error(`'${trimmed}' matched multiple repos (${hint}). Use the full repo id.`);
|
|
@@ -101,7 +110,17 @@ async function lookupPromptByName(name, scope = {}) {
|
|
|
101
110
|
// 3) Title / description search.
|
|
102
111
|
const results = await (0, api_client_1.listPrompts)({ search: trimmed, limit: 100, projectId });
|
|
103
112
|
const lower = trimmed.toLowerCase();
|
|
104
|
-
|
|
113
|
+
let titleMatches = results.filter((p) => (0, titleMatch_1.foldedIncludes)(p.title, trimmed));
|
|
114
|
+
// A hex-only name was just looked up page by page as a short id; a second walk over the same
|
|
115
|
+
// prompts would find no title that the first one did not.
|
|
116
|
+
const alreadyWalked = !UUID_RE.test(trimmed) && SHORT_ID_RE.test(trimmed);
|
|
117
|
+
if (titleMatches.length === 0 && !alreadyWalked) {
|
|
118
|
+
// The server's search is an ILIKE on title + description: it cannot see through Turkish letters or
|
|
119
|
+
// accents ("hat baslangici" never finds "Hat başlangıcı"), and a description that happens to contain
|
|
120
|
+
// the typed text would otherwise win over a title that the server could not match. Look through the
|
|
121
|
+
// titles here (bounded), and only then fall back to the description matches.
|
|
122
|
+
titleMatches = (await listAllPrompts(projectId)).filter((p) => (0, titleMatch_1.foldedIncludes)(p.title, trimmed));
|
|
123
|
+
}
|
|
105
124
|
const pool = titleMatches.length > 0 ? titleMatches : results;
|
|
106
125
|
if (pool.length === 0) {
|
|
107
126
|
const where = projectId ? ' in the selected repo' : '';
|
|
@@ -109,13 +128,40 @@ async function lookupPromptByName(name, scope = {}) {
|
|
|
109
128
|
}
|
|
110
129
|
if (pool.length === 1)
|
|
111
130
|
return { kind: 'found', prompt: pool[0] };
|
|
112
|
-
// Disambiguate on an exact
|
|
131
|
+
// Disambiguate on an exact title match if unique: first the same text ignoring case, then also ignoring
|
|
132
|
+
// Turkish letters, accents and spacing.
|
|
113
133
|
const exact = pool.filter((p) => p.title.toLowerCase() === lower);
|
|
114
134
|
if (exact.length === 1)
|
|
115
135
|
return { kind: 'found', prompt: exact[0] };
|
|
136
|
+
if (exact.length === 0) {
|
|
137
|
+
const folded = pool.filter((p) => (0, titleMatch_1.foldedEquals)(p.title, trimmed));
|
|
138
|
+
if (folded.length === 1)
|
|
139
|
+
return { kind: 'found', prompt: folded[0] };
|
|
140
|
+
}
|
|
116
141
|
printAmbiguous(trimmed, pool);
|
|
117
142
|
return { kind: 'reported' };
|
|
118
143
|
}
|
|
144
|
+
/**
|
|
145
|
+
* Every prompt the account lets this user see (optionally one repo), newest first: 20 pages x 100 at most,
|
|
146
|
+
* the same bound and the same guard against a server that ignores `page` as {@link findByShortId}. Only
|
|
147
|
+
* used when the server's own search found no TITLE, so the common lookup stays one request.
|
|
148
|
+
*/
|
|
149
|
+
async function listAllPrompts(projectId) {
|
|
150
|
+
const all = [];
|
|
151
|
+
const seen = new Set();
|
|
152
|
+
for (let page = 1; page <= MAX_ID_PAGES; page++) {
|
|
153
|
+
const rows = await (0, api_client_1.listPrompts)({ limit: PAGE_LIMIT, page, projectId });
|
|
154
|
+
const fresh = rows.filter((p) => !seen.has(p.id));
|
|
155
|
+
if (fresh.length === 0)
|
|
156
|
+
break; // server ignored `page`: same rows again
|
|
157
|
+
for (const p of fresh)
|
|
158
|
+
seen.add(p.id);
|
|
159
|
+
all.push(...fresh);
|
|
160
|
+
if (rows.length < PAGE_LIMIT)
|
|
161
|
+
break; // last page
|
|
162
|
+
}
|
|
163
|
+
return all;
|
|
164
|
+
}
|
|
119
165
|
/**
|
|
120
166
|
* Walks GET /api/prompts page by page (updated_at desc, stable id tie-break) and returns the
|
|
121
167
|
* prompts whose id starts with `prefix`. Stops at the first page that has a hit (that page's
|
package/dist/lib/rank.js
CHANGED
|
@@ -12,7 +12,11 @@
|
|
|
12
12
|
* 600 characters of the body ×0.5 — plus a small log bonus for past use.
|
|
13
13
|
*
|
|
14
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
|
|
15
|
+
* only with a title or tag hit, or with at least two distinct terms matched —
|
|
16
|
+
* and, the longer the task, with proportionally more terms: one generic word
|
|
17
|
+
* ("write") in the title of an unrelated prompt must not carry a 5-term task
|
|
18
|
+
* (see {@link requiredMatches}). Matches scoring under {@link RELATIVE_CUT} of the best one
|
|
19
|
+
* are dropped too: when something fits well, a far weaker neighbour is noise.
|
|
16
20
|
* Case, Turkish letters and accents are folded away on both sides ("kök neden" =
|
|
17
21
|
* "kok neden", "İngilizce" = "ingilizce"). Folding, stop words and tokenisation are
|
|
18
22
|
* the SAME code as the server's `src/lib/suggest.ts` (MCP `suggest_prompts`): the
|
|
@@ -20,10 +24,11 @@
|
|
|
20
24
|
* src/lib/suggest.test.ts fails when the two copies drift.
|
|
21
25
|
*/
|
|
22
26
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
-
exports.MIN_SCORE = exports.BODY_HEAD = exports.MAX_TERMS = void 0;
|
|
27
|
+
exports.RELATIVE_CUT = exports.TERMS_PER_REQUIRED_MATCH = exports.MIN_SCORE = exports.BODY_HEAD = exports.MAX_TERMS = void 0;
|
|
24
28
|
exports.foldText = foldText;
|
|
25
29
|
exports.tokenize = tokenize;
|
|
26
30
|
exports.taskTerms = taskTerms;
|
|
31
|
+
exports.requiredMatches = requiredMatches;
|
|
27
32
|
exports.rankLibrary = rankLibrary;
|
|
28
33
|
// <fold-text:begin> — copy of the same block in src/lib/suggest.ts (byte-identical; src/lib/suggest.test.ts locks it)
|
|
29
34
|
/**
|
|
@@ -61,6 +66,18 @@ function taskTerms(task) {
|
|
|
61
66
|
exports.BODY_HEAD = 600;
|
|
62
67
|
/** Minimum score to be suggested at all. */
|
|
63
68
|
exports.MIN_SCORE = 2;
|
|
69
|
+
/** A task of up to this many terms needs one matched term; every further started group of this size, one more. */
|
|
70
|
+
exports.TERMS_PER_REQUIRED_MATCH = 4;
|
|
71
|
+
/** A match scoring below this share of the best match is dropped (the best one always stays). */
|
|
72
|
+
exports.RELATIVE_CUT = 0.5;
|
|
73
|
+
/**
|
|
74
|
+
* Distinct task terms a prompt has to match: 1 up to 4 terms, 2 for 5-8, 3 for 9-12 (the hook keeps ≤12).
|
|
75
|
+
* A long task can name one prompt by a single generic word without being about it; a short one cannot afford
|
|
76
|
+
* to demand more than one.
|
|
77
|
+
*/
|
|
78
|
+
function requiredMatches(termCount) {
|
|
79
|
+
return Math.max(1, Math.ceil(termCount / exports.TERMS_PER_REQUIRED_MATCH));
|
|
80
|
+
}
|
|
64
81
|
const WEIGHTS = { title: 3, tag: 2, description: 1, body: 0.5 };
|
|
65
82
|
/**
|
|
66
83
|
* A term hits a field token when one is a prefix of the other and the
|
|
@@ -91,6 +108,7 @@ function rankLibrary(items, task, limit = 3) {
|
|
|
91
108
|
if (terms.length === 0 || items.length === 0)
|
|
92
109
|
return [];
|
|
93
110
|
const fields = items.map(fieldsOf);
|
|
111
|
+
const needed = requiredMatches(terms.length);
|
|
94
112
|
// Document frequency per term over the whole library → idf.
|
|
95
113
|
const n = items.length;
|
|
96
114
|
const idf = new Map();
|
|
@@ -127,14 +145,14 @@ function rankLibrary(items, task, limit = 3) {
|
|
|
127
145
|
strongHit = true;
|
|
128
146
|
score += (idf.get(term) ?? 0) * w;
|
|
129
147
|
}
|
|
130
|
-
if (!strongHit && matched < 2)
|
|
148
|
+
if (matched < needed || (!strongHit && matched < 2))
|
|
131
149
|
return;
|
|
132
150
|
score += Math.log1p(Math.max(0, item.uses ?? 0)) * 0.3;
|
|
133
151
|
if (score < exports.MIN_SCORE)
|
|
134
152
|
return;
|
|
135
153
|
ranked.push({ item, score: Math.round(score * 100) / 100 });
|
|
136
154
|
});
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
155
|
+
ranked.sort((a, b) => b.score - a.score || (b.item.uses ?? 0) - (a.item.uses ?? 0));
|
|
156
|
+
const floor = ranked.length > 0 ? ranked[0].score * exports.RELATIVE_CUT : 0;
|
|
157
|
+
return ranked.filter((r) => r.score >= floor).slice(0, Math.max(1, Math.min(limit, 10)));
|
|
140
158
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* How a typed name is compared with a prompt title or slug.
|
|
4
|
+
*
|
|
5
|
+
* `ple get "hat baslangici"` must find "Hat başlangıcı", and `ple get "iş akışı"` must find "İş akışı özeti":
|
|
6
|
+
* JavaScript's `toLowerCase()` turns "İ" into "i" + a combining dot and leaves "ı" alone, so a plain
|
|
7
|
+
* lower-case compare misses every Turkish title typed without the letters or with a capital İ/I. The
|
|
8
|
+
* comparison key is the SAME fold the suggestion ranker uses (`foldText` in rank.ts, kept byte-identical
|
|
9
|
+
* with the server's `src/lib/suggest.ts` by a test there): case, Turkish letters and accents folded away.
|
|
10
|
+
* Whitespace runs collapse to one space and the ends are trimmed.
|
|
11
|
+
*
|
|
12
|
+
* The raw (unfolded) lower-case compare still goes first in every resolver, so an exact title always
|
|
13
|
+
* beats a looser match; this key is what makes the looser step see through letters.
|
|
14
|
+
*/
|
|
15
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
|
+
exports.foldKey = foldKey;
|
|
17
|
+
exports.foldedIncludes = foldedIncludes;
|
|
18
|
+
exports.foldedEquals = foldedEquals;
|
|
19
|
+
const rank_1 = require("./rank");
|
|
20
|
+
/** Comparison key of a title, slug or typed name. */
|
|
21
|
+
function foldKey(text) {
|
|
22
|
+
return (0, rank_1.foldText)(text).replace(/\s+/g, ' ').trim();
|
|
23
|
+
}
|
|
24
|
+
/** True when `typed` (partial allowed) is inside `haystack`, ignoring case, Turkish letters and accents. */
|
|
25
|
+
function foldedIncludes(haystack, typed) {
|
|
26
|
+
const needle = foldKey(typed);
|
|
27
|
+
return needle !== '' && foldKey(haystack).includes(needle);
|
|
28
|
+
}
|
|
29
|
+
/** True when the two texts are the same name, ignoring case, Turkish letters, accents and spacing. */
|
|
30
|
+
function foldedEquals(a, b) {
|
|
31
|
+
return foldKey(a) === foldKey(b);
|
|
32
|
+
}
|
package/dist/program.js
CHANGED
|
@@ -7,12 +7,14 @@
|
|
|
7
7
|
*/
|
|
8
8
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
9
|
exports.runWithErrorHandler = runWithErrorHandler;
|
|
10
|
+
exports.closestCommand = closestCommand;
|
|
10
11
|
exports.buildProgram = buildProgram;
|
|
11
12
|
const commander_1 = require("commander");
|
|
12
13
|
const constants_1 = require("./lib/constants");
|
|
13
14
|
const format_1 = require("./lib/format");
|
|
14
15
|
const login_1 = require("./commands/login");
|
|
15
16
|
const logout_1 = require("./commands/logout");
|
|
17
|
+
const whoami_1 = require("./commands/whoami");
|
|
16
18
|
const list_1 = require("./commands/list");
|
|
17
19
|
const copy_1 = require("./commands/copy");
|
|
18
20
|
const show_1 = require("./commands/show");
|
|
@@ -32,6 +34,10 @@ const tag_1 = require("./commands/tag");
|
|
|
32
34
|
const suggest_1 = require("./commands/suggest");
|
|
33
35
|
const config_1 = require("./commands/config");
|
|
34
36
|
const repo_1 = require("./commands/repo");
|
|
37
|
+
const feedback_1 = require("./commands/feedback");
|
|
38
|
+
const feedbackApi_1 = require("./lib/feedbackApi");
|
|
39
|
+
const feedbackInput_1 = require("./lib/feedbackInput");
|
|
40
|
+
const feedbackHint_1 = require("./lib/feedbackHint");
|
|
35
41
|
const errors_1 = require("./lib/errors");
|
|
36
42
|
const help_1 = require("./help");
|
|
37
43
|
/**
|
|
@@ -39,7 +45,7 @@ const help_1 = require("./help");
|
|
|
39
45
|
* command: 1 = fix your input/login/plan, 2 = network/server problem, retry later.
|
|
40
46
|
* A command that already set `process.exitCode` keeps its own code.
|
|
41
47
|
*/
|
|
42
|
-
function runWithErrorHandler(fn) {
|
|
48
|
+
function runWithErrorHandler(fn, opts = {}) {
|
|
43
49
|
return async (...args) => {
|
|
44
50
|
try {
|
|
45
51
|
await fn(...args);
|
|
@@ -47,10 +53,71 @@ function runWithErrorHandler(fn) {
|
|
|
47
53
|
catch (err) {
|
|
48
54
|
const message = err instanceof Error ? err.message : String(err);
|
|
49
55
|
console.error(format_1.c.error(`✗ ${message}`));
|
|
56
|
+
if (opts.hint)
|
|
57
|
+
(0, feedbackHint_1.printFeedbackHint)();
|
|
50
58
|
process.exit(process.exitCode || (0, errors_1.exitCodeFor)(err));
|
|
51
59
|
}
|
|
60
|
+
if (opts.hint === 'failure' && process.exitCode)
|
|
61
|
+
(0, feedbackHint_1.printFeedbackHint)();
|
|
52
62
|
};
|
|
53
63
|
}
|
|
64
|
+
/** Long names of the options that were typed on the command line (never their values). */
|
|
65
|
+
function typedFlagNames(cmd) {
|
|
66
|
+
return cmd.options
|
|
67
|
+
.filter((o) => cmd.getOptionValueSource(o.attributeName()) === 'cli')
|
|
68
|
+
.map((o) => o.long ?? '')
|
|
69
|
+
.filter(Boolean);
|
|
70
|
+
}
|
|
71
|
+
/** Optimal-string-alignment distance (insert, delete, substitute, swap neighbours) — typo-sized strings only. */
|
|
72
|
+
function editDistance(a, b) {
|
|
73
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...new Array(b.length).fill(0)]);
|
|
74
|
+
for (let j = 1; j <= b.length; j++)
|
|
75
|
+
d[0][j] = j;
|
|
76
|
+
for (let i = 1; i <= a.length; i++) {
|
|
77
|
+
for (let j = 1; j <= b.length; j++) {
|
|
78
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
79
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
80
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1])
|
|
81
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return d[a.length][b.length];
|
|
85
|
+
}
|
|
86
|
+
/** The registered command (or alias) that `typed` most likely meant — a typo or a prefix — or undefined. */
|
|
87
|
+
function closestCommand(typed, names) {
|
|
88
|
+
const t = typed.toLowerCase();
|
|
89
|
+
if (t.length < 2)
|
|
90
|
+
return undefined;
|
|
91
|
+
let best;
|
|
92
|
+
for (const name of names) {
|
|
93
|
+
// A real prefix ("sugg" → suggest) beats any typo; otherwise allow ~1 edit per 3 letters, at most 3.
|
|
94
|
+
const max = Math.min(3, Math.max(1, Math.floor(name.length / 3)));
|
|
95
|
+
const dist = name.startsWith(t) && t.length >= 3 ? 0 : editDistance(t, name);
|
|
96
|
+
if (dist > max)
|
|
97
|
+
continue;
|
|
98
|
+
if (!best || dist < best.score)
|
|
99
|
+
best = { name, score: dist };
|
|
100
|
+
}
|
|
101
|
+
return best?.name;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* An unknown sub-command is a usage error — exit 2, the same code `ple feedback` uses for bad usage — with the
|
|
105
|
+
* nearest command named and the way to the full list. Without this commander exits 1, the code every
|
|
106
|
+
* script reads as "your input or login is wrong". Bare `ple` and `ple --help` are not routed here.
|
|
107
|
+
*/
|
|
108
|
+
function failOnUnknownCommand(cmd) {
|
|
109
|
+
cmd.on('command:*', (operands) => {
|
|
110
|
+
const typed = operands[0] ?? '';
|
|
111
|
+
const names = cmd.commands.flatMap((s) => [s.name(), ...s.aliases()]).filter((n) => n !== 'help');
|
|
112
|
+
const guess = closestCommand(typed, names);
|
|
113
|
+
const path = cmd.parent ? `${cmd.parent.name()} ${cmd.name()}` : cmd.name();
|
|
114
|
+
const lines = [`error: unknown command '${typed}'`];
|
|
115
|
+
if (guess)
|
|
116
|
+
lines.push(`(Did you mean ${guess}?)`);
|
|
117
|
+
lines.push(`Run \`${path} --help\` to see the commands.`);
|
|
118
|
+
cmd.error(lines.join('\n'), { exitCode: 2, code: 'ple.unknownCommand' });
|
|
119
|
+
});
|
|
120
|
+
}
|
|
54
121
|
function buildProgram() {
|
|
55
122
|
const program = new commander_1.Command();
|
|
56
123
|
program
|
|
@@ -59,6 +126,7 @@ function buildProgram() {
|
|
|
59
126
|
.version(constants_1.CLI_VERSION)
|
|
60
127
|
.configureHelp({ formatHelp: help_1.formatRootHelp })
|
|
61
128
|
.showSuggestionAfterError();
|
|
129
|
+
failOnUnknownCommand(program);
|
|
62
130
|
const scope = (cmd) => cmd.option('--project <repo>', 'Limit to one repo (name, slug or id) — use when titles collide');
|
|
63
131
|
// ---- prompts ------------------------------------------------------------
|
|
64
132
|
program
|
|
@@ -68,7 +136,18 @@ function buildProgram() {
|
|
|
68
136
|
.option('-d, --description <text>', 'Short description')
|
|
69
137
|
.option('-t, --tag <name>', 'Tag (repeatable)', save_1.collectTag, [])
|
|
70
138
|
.option('-f, --force', 'Overwrite an existing local prompt')
|
|
71
|
-
.
|
|
139
|
+
.option('--project <repo>', 'Save into this repo of your account (name, slug or id) — needs `ple login`; safe to run again')
|
|
140
|
+
.addHelpText('after', [
|
|
141
|
+
'',
|
|
142
|
+
'Examples:',
|
|
143
|
+
' ple save "code review" -m "Review this diff: {{diff}}"',
|
|
144
|
+
' pbpaste | ple save "bug triage" --tag triage',
|
|
145
|
+
' ple save "code review" -m "..." --project my-prompts # into your account; run again to update',
|
|
146
|
+
'',
|
|
147
|
+
'With --project: the title inside the repo is the identity. A new title creates the prompt; the same title',
|
|
148
|
+
'with different text adds a new version (nothing is overwritten); the same text says "unchanged" and sends',
|
|
149
|
+
'nothing. Signed out, --project still saves locally and warns that the account was not written.',
|
|
150
|
+
].join('\n'))
|
|
72
151
|
.action(runWithErrorHandler(save_1.saveCommand));
|
|
73
152
|
scope(program
|
|
74
153
|
.command('get <name>')
|
|
@@ -77,7 +156,7 @@ function buildProgram() {
|
|
|
77
156
|
.option('-c, --copy', 'Also copy the output to the clipboard')
|
|
78
157
|
.option('-l, --label <name>', 'Read the version a deployment label points at (e.g. production)'))
|
|
79
158
|
.addHelpText('after', '\nExample:\n ple get "code review" --var diff="$(git diff)" | claude')
|
|
80
|
-
.action(runWithErrorHandler(get_1.getCommand));
|
|
159
|
+
.action(runWithErrorHandler(get_1.getCommand, { hint: 'failure' }));
|
|
81
160
|
scope(program.command('show <name>').description('Show a prompt in the terminal')).action(runWithErrorHandler(show_1.showCommand));
|
|
82
161
|
scope(program
|
|
83
162
|
.command('copy <name>')
|
|
@@ -94,7 +173,7 @@ function buildProgram() {
|
|
|
94
173
|
program
|
|
95
174
|
.command('search <keyword>')
|
|
96
175
|
.description('Search titles and descriptions; also finds prompts only on this machine (incl. body and tags)')
|
|
97
|
-
.action(runWithErrorHandler(search_1.searchCommand));
|
|
176
|
+
.action(runWithErrorHandler(search_1.searchCommand, { hint: 'throw' }));
|
|
98
177
|
scope(program
|
|
99
178
|
.command('log <name>')
|
|
100
179
|
.description('Version history of a prompt (* = current). Signed out: the local history')
|
|
@@ -131,6 +210,7 @@ function buildProgram() {
|
|
|
131
210
|
.command('repo')
|
|
132
211
|
.description('Create and manage repos (collections of prompts) in your account')
|
|
133
212
|
.addHelpText('after', '\nExamples:\n ple repo create "team-prompts" --description "Shared review prompts"\n ple repo list\n ple repo visibility team-prompts public --yes\n\nRepos are private unless you say --public. Deleting a repo is only possible on the web.');
|
|
213
|
+
failOnUnknownCommand(repo);
|
|
134
214
|
repo.command('create <name>')
|
|
135
215
|
.description('Create a repo (private by default)')
|
|
136
216
|
.option('--private', 'Only you and people you invite can see it (default)')
|
|
@@ -160,6 +240,13 @@ function buildProgram() {
|
|
|
160
240
|
.command('logout')
|
|
161
241
|
.description('Delete the local session file')
|
|
162
242
|
.action(runWithErrorHandler(logout_1.logoutCommand));
|
|
243
|
+
program
|
|
244
|
+
.command('whoami')
|
|
245
|
+
.alias('account')
|
|
246
|
+
.description('Show the signed-in account: email, plan, and how much of the plan limits you use')
|
|
247
|
+
.option('--json', 'Print as one JSON line')
|
|
248
|
+
.addHelpText('after', '\nSigned out it says so and exits with code 1. The session token is never printed.')
|
|
249
|
+
.action(runWithErrorHandler(whoami_1.whoamiCommand));
|
|
163
250
|
// ---- import / export / sync --------------------------------------------
|
|
164
251
|
program
|
|
165
252
|
.command('sync')
|
|
@@ -200,6 +287,57 @@ function buildProgram() {
|
|
|
200
287
|
.option('-o, --out <path>', 'agents-md: file to write (default stdout) · skill: parent folder (default .)')
|
|
201
288
|
.option('--zip', 'skill: write <name>.zip (upload in Claude) instead of a folder')
|
|
202
289
|
.option('-f, --force', 'Overwrite an existing file or folder (never through a symbolic link)')).action(runWithErrorHandler(export_1.exportCommand));
|
|
290
|
+
// ---- feedback -----------------------------------------------------------
|
|
291
|
+
const feedback = program
|
|
292
|
+
.command('feedback [message...]')
|
|
293
|
+
.description('Tell the maker what is missing, broken or confusing — no questions asked, works from agents')
|
|
294
|
+
.addOption(new commander_1.Option('--type <type>', `What kind of note: ${feedbackInput_1.FEEDBACK_TYPES.join(' | ')} (default ${feedbackInput_1.DEFAULT_FEEDBACK_TYPE})`))
|
|
295
|
+
.option('--prompt <title|id>', 'The prompt this is about (its title or id — the prompt text is never sent)')
|
|
296
|
+
.option('--email <address>', 'Where to answer you (optional)')
|
|
297
|
+
.option('--agent <name>', 'Mark the report as written by an AI agent with this name (auto-detected from the environment otherwise)')
|
|
298
|
+
.option('--json', 'Print the outcome as one JSON line on stdout')
|
|
299
|
+
// Usage errors (unknown flag, missing argument) must end with exit code 2, not commander's 1. Set BEFORE
|
|
300
|
+
// the subcommands below so they inherit it.
|
|
301
|
+
.exitOverride((err) => {
|
|
302
|
+
if (err.exitCode !== 0)
|
|
303
|
+
process.exit(2);
|
|
304
|
+
})
|
|
305
|
+
.addHelpText('after', [
|
|
306
|
+
'',
|
|
307
|
+
'Examples:',
|
|
308
|
+
' ple feedback "ple search should also look inside prompt bodies"',
|
|
309
|
+
' ple feedback --type bug --prompt "code review" "get printed the wrong version"',
|
|
310
|
+
' ple feedback --type missing --json "no way to rename a repo from the CLI"',
|
|
311
|
+
'',
|
|
312
|
+
'Sent: the type, your message, the prompt title/id and email if you gave them, whether a person or an',
|
|
313
|
+
'agent wrote it, and the ple version, OS + CPU, Node version and the command name with the flag NAMES',
|
|
314
|
+
'you used. Never a prompt body, a file, a path or a flag value. Signed in, the report is tied to your',
|
|
315
|
+
'account; signed out it is anonymous. Do not put secrets or personal data in the message: a message that',
|
|
316
|
+
'looks like a key or token is refused.',
|
|
317
|
+
'',
|
|
318
|
+
'If the server cannot be reached the report is saved to ~/.promptlike/feedback/queue.json (max 50) and',
|
|
319
|
+
'sent by a later `ple` command (at most every 15 minutes; PLE_FEEDBACK_QUEUE=off turns that off).',
|
|
320
|
+
'',
|
|
321
|
+
'Exit codes:',
|
|
322
|
+
...feedback_1.FEEDBACK_EXIT_CODES_HELP.map((l) => ` ${l}`),
|
|
323
|
+
'',
|
|
324
|
+
'Owner commands (need a session): `ple feedback list` and `ple feedback close <id> --commit <sha>`.',
|
|
325
|
+
].join('\n'))
|
|
326
|
+
.action(runWithErrorHandler(async (message, opts, cmd) => (0, feedback_1.feedbackCommand)(message ?? [], opts, { flagNames: typedFlagNames(cmd) })));
|
|
327
|
+
feedback
|
|
328
|
+
.command('list')
|
|
329
|
+
.description('List the feedback people sent (owner)')
|
|
330
|
+
.addOption(new commander_1.Option('--status <status>', `Only this status: ${feedbackApi_1.FEEDBACK_STATUSES.join(' | ')}`))
|
|
331
|
+
.option('-l, --limit <n>', 'Max rows (default 50)')
|
|
332
|
+
.option('--json', 'Print the items as JSON, exactly as the server returned them')
|
|
333
|
+
.action(runWithErrorHandler(async (opts, cmd) => (0, feedback_1.feedbackListCommand)({ ...opts, json: opts.json ?? cmd.optsWithGlobals().json === true })));
|
|
334
|
+
feedback
|
|
335
|
+
.command('close <id>')
|
|
336
|
+
.description('Mark a piece of feedback as done (or wontfix) with the commit that resolved it (owner)')
|
|
337
|
+
.option('--commit <sha>', 'The commit that resolved it (required for done)')
|
|
338
|
+
.addOption(new commander_1.Option('--status <status>', 'done (default) or wontfix'))
|
|
339
|
+
.option('--json', 'Print the result as one JSON line')
|
|
340
|
+
.action(runWithErrorHandler(async (id, opts, cmd) => (0, feedback_1.feedbackCloseCommand)(id, { ...opts, json: opts.json ?? cmd.optsWithGlobals().json === true })));
|
|
203
341
|
// ---- insights & settings ------------------------------------------------
|
|
204
342
|
program
|
|
205
343
|
.command('stats')
|
|
@@ -212,10 +350,14 @@ function buildProgram() {
|
|
|
212
350
|
.description('Which saved prompt fits this task? Local match — the text never leaves your machine')
|
|
213
351
|
.option('--json', 'Print matches as JSON')
|
|
214
352
|
.option('-l, --limit <n>', 'Max matches (default 3)', '3')
|
|
353
|
+
.option('-t, --tag <name>', 'Only prompts with this tag; repeat to require several (all must match)', save_1.collectTag, [])
|
|
354
|
+
.option('--project <repo>', 'Only prompts of this repo (name, slug or id) — needs `ple login`')
|
|
215
355
|
.option('--hook', 'Claude Code UserPromptSubmit mode: read hook JSON on stdin, print a short hint or nothing')
|
|
216
356
|
.option('--refresh-cache', 'Refresh the local library cache from your account and exit')
|
|
217
|
-
.action(runWithErrorHandler((text, opts) => (0, suggest_1.suggestCommand)(text ?? [], opts)))
|
|
357
|
+
.action(runWithErrorHandler((text, opts) => (0, suggest_1.suggestCommand)(text ?? [], opts)))
|
|
358
|
+
.addHelpText('after', '\nExamples:\n ple suggest "review this pull request"\n ple suggest "fix the flaky test" --tag debug\n ple suggest "weekly report" --project my-prompts');
|
|
218
359
|
const configCmd = program.command('config').description('CLI preferences (suggest on|off)');
|
|
360
|
+
failOnUnknownCommand(configCmd);
|
|
219
361
|
configCmd
|
|
220
362
|
.command('get [key]')
|
|
221
363
|
.description('Show a setting (or all)')
|
package/package.json
CHANGED