promptlike 0.10.1 → 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.
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  /**
3
3
  * `ple save <title>` — write a prompt to the local store. **No account needed.**
4
+ * With `--project <repo>` and a session it saves INTO THE ACCOUNT instead, and is safe to run again
5
+ * (see lib/accountSave.ts: same title in the repo → no second prompt; new text → a new version;
6
+ * same text → "unchanged"). Without a session `--project` still saves locally, with a warning.
4
7
  *
5
8
  * This is the command that makes `npm i -g promptlike` worth something on its
6
9
  * own. Body comes from `-m/--message`, or from stdin when piped:
@@ -49,6 +52,11 @@ const store = __importStar(require("../lib/localStore"));
49
52
  const history = __importStar(require("../lib/localHistory"));
50
53
  const format_1 = require("../lib/format");
51
54
  const promptVariables_1 = require("../lib/promptVariables");
55
+ const api_client_1 = require("../lib/api-client");
56
+ const accountSave_1 = require("../lib/accountSave");
57
+ const promptResolver_1 = require("../lib/promptResolver");
58
+ const libraryCache_1 = require("../lib/libraryCache");
59
+ const local_1 = require("./local");
52
60
  /**
53
61
  * Same caps the web API enforces (title 200 / body 100K / description 1000).
54
62
  * The CLI mirrors them instead of letting `ple sync` discover the mismatch:
@@ -118,6 +126,22 @@ async function saveCommand(title, options = {}) {
118
126
  process.exitCode = 1;
119
127
  return;
120
128
  }
129
+ if (options.project !== undefined) {
130
+ const project = options.project.trim();
131
+ if (!project) {
132
+ console.error(format_1.c.error('--project is empty. Give a repo name, slug or id (see `ple repo list`).'));
133
+ process.exitCode = 1;
134
+ return;
135
+ }
136
+ if (!(0, local_1.isSignedOut)()) {
137
+ await saveIntoAccount(cleanTitle, body, project, options);
138
+ return;
139
+ }
140
+ // No session: do what `ple save` always did, but say that the account was NOT written —
141
+ // a silent local-only save would read as "it is in the repo".
142
+ console.error(format_1.c.warn(`⚠ --project needs an account: saved on this machine only, NOT in repo '${project}'.`));
143
+ console.error(format_1.c.muted(' Sign in with `ple login`, then run the same command again — it will not create a duplicate.'));
144
+ }
121
145
  const slug = store.slugFor(cleanTitle);
122
146
  const previous = store.read(slug);
123
147
  // Overwriting someone's prompt silently is the one unrecoverable thing this
@@ -151,3 +175,50 @@ async function saveCommand(title, options = {}) {
151
175
  console.log(format_1.c.muted(` use it: ple copy "${saved.slug}"`));
152
176
  }
153
177
  }
178
+ /** `--project` with a session: write to the account; the local store is not touched. */
179
+ async function saveIntoAccount(title, body, projectRef, options) {
180
+ const tags = (0, accountSave_1.cleanTags)(options.tag ?? []);
181
+ (0, accountSave_1.assertTagLengths)(tags);
182
+ const description = options.description === undefined ? undefined : options.description.trim();
183
+ await (0, api_client_1.ensureAuthed)();
184
+ // A wrong repo name stops here, before anything is sent.
185
+ const projectId = await (0, promptResolver_1.resolveProjectId)(projectRef);
186
+ const projectName = (await (0, api_client_1.listProjects)()).find((p) => p.id === projectId)?.name ?? projectRef;
187
+ const out = await (0, accountSave_1.saveToAccount)({ title, body, description, tags, projectId, projectName });
188
+ printAccountOutcome(out, title, projectName, projectRef);
189
+ if (out.status === 'created' || out.status === 'updated')
190
+ (0, libraryCache_1.startBackgroundRefresh)({ force: true });
191
+ }
192
+ function printAccountOutcome(out, title, repo, projectRef) {
193
+ const shown = (0, format_1.safeText)(title);
194
+ const repoName = (0, format_1.safeText)(repo);
195
+ if (out.status === 'ambiguous') {
196
+ console.error(format_1.c.error(`${out.candidates.length} prompts in '${repoName}' are titled "${shown}" and none has this text — not changing any of them.`));
197
+ for (const p of out.candidates.slice(0, 10))
198
+ console.error(format_1.c.muted(` ${(0, accountSave_1.candidateLine)(p)}`));
199
+ console.error(format_1.c.muted('Edit the one you mean with `ple improve <short id>` or on the web, or give this one a different title.'));
200
+ process.exitCode = 1;
201
+ return;
202
+ }
203
+ const id = out.id.slice(0, 8);
204
+ if (out.status === 'created') {
205
+ console.log(format_1.c.success(`✓ Saved to ${repoName}: ${shown}`) + format_1.c.muted(` (${id}${out.version ? `, v${out.version}` : ''})`));
206
+ }
207
+ else if (out.status === 'updated') {
208
+ const was = out.previousVersion ? ` (was v${out.previousVersion})` : '';
209
+ console.log(format_1.c.success(`✓ New version of "${shown}" in ${repoName}: v${out.version ?? '?'}${was}`) + format_1.c.muted(` (${id}) — earlier versions are kept`));
210
+ }
211
+ else {
212
+ console.log(`= Unchanged: "${shown}" in ${repoName} already has this text${out.version ? ` (v${out.version})` : ''} — no new version.` + format_1.c.muted(` (${id})`));
213
+ }
214
+ if (out.status !== 'created' && out.descriptionUpdated)
215
+ console.log(format_1.c.muted(' description updated (no new version)'));
216
+ if (out.tagsAdded.length > 0)
217
+ console.log(format_1.c.muted(` tags added: ${out.tagsAdded.map((t) => (0, format_1.safeText)(t)).join(', ')}`));
218
+ if (out.tagsFailed.length > 0) {
219
+ for (const f of out.tagsFailed)
220
+ console.error(format_1.c.warn(`⚠ tag '${(0, format_1.safeText)(f.tag)}' was not added: ${(0, format_1.safeText)(f.message)}`));
221
+ console.error(format_1.c.muted(` Run the same command again to retry them: ple save "${shown}" --project ${projectRef}`));
222
+ process.exitCode = 1;
223
+ }
224
+ }
@@ -39,6 +39,7 @@ const local_1 = require("./local");
39
39
  const format_1 = require("../lib/format");
40
40
  const promptSource_1 = require("../lib/promptSource");
41
41
  const store = __importStar(require("../lib/localStore"));
42
+ const feedbackHint_1 = require("../lib/feedbackHint");
42
43
  /** Local-only matches shown before "…and N more". */
43
44
  const LOCAL_ONLY_SHOWN = 10;
44
45
  /**
@@ -60,7 +61,8 @@ async function searchCommand(keyword) {
60
61
  return;
61
62
  }
62
63
  if ((0, local_1.isSignedOut)()) {
63
- (0, local_1.localSearch)(trimmed);
64
+ if (!(0, local_1.localSearch)(trimmed))
65
+ (0, feedbackHint_1.printFeedbackHint)();
64
66
  return;
65
67
  }
66
68
  await (0, api_client_1.ensureAuthed)();
@@ -71,6 +73,7 @@ async function searchCommand(keyword) {
71
73
  const onlyHere = (0, promptSource_1.localOnly)((0, promptSource_1.accountTitleSet)(rows, false).titles, store.search(trimmed));
72
74
  if (rows.length === 0 && onlyHere.length === 0) {
73
75
  console.log(format_1.c.muted(`No prompts matched '${trimmed}'.`));
76
+ (0, feedbackHint_1.printFeedbackHint)();
74
77
  return;
75
78
  }
76
79
  if (rows.length === 0) {
@@ -52,12 +52,13 @@ var __importStar = (this && this.__importStar) || (function () {
52
52
  })();
53
53
  Object.defineProperty(exports, "__esModule", { value: true });
54
54
  exports.NOTE_TITLE_MAX = exports.HOOK_BUDGET_MS = exports.HOOK_MIN_CHARS = void 0;
55
+ exports.filterEntries = filterEntries;
55
56
  exports.stripPasted = stripPasted;
56
57
  exports.hookShouldSkip = hookShouldSkip;
57
58
  exports.noteLabel = noteLabel;
58
59
  exports.isShellSafeSlug = isShellSafeSlug;
59
60
  exports.renderHookBlock = renderHookBlock;
60
- exports.useCommandFor = useCommandFor;
61
+ exports.getCommandFor = getCommandFor;
61
62
  exports.runHook = runHook;
62
63
  exports.refreshLibraryCache = refreshLibraryCache;
63
64
  exports.suggestCommand = suggestCommand;
@@ -66,8 +67,30 @@ const config_1 = require("../lib/config");
66
67
  const format_1 = require("../lib/format");
67
68
  const libraryCache_1 = require("../lib/libraryCache");
68
69
  const store = __importStar(require("../lib/localStore"));
70
+ const promptResolver_1 = require("../lib/promptResolver");
69
71
  const rank_1 = require("../lib/rank");
70
72
  const settings_1 = require("../lib/settings");
73
+ const tagFilter_1 = require("../lib/tagFilter");
74
+ const local_1 = require("./local");
75
+ /** Entries that pass the filter. Pure; the ranker then runs on this subset only. */
76
+ function filterEntries(entries, filter) {
77
+ const tags = filter.tags ?? [];
78
+ const repo = filter.repo;
79
+ return entries.filter((e) => {
80
+ if (tags.length > 0) {
81
+ const have = e.tags ?? [];
82
+ const ok = filter.ignoreCase ? (0, tagFilter_1.hasAllLocalTags)(have, tags) : tags.every((t) => have.includes(t));
83
+ if (!ok)
84
+ return false;
85
+ }
86
+ if (repo) {
87
+ if (e.repoId)
88
+ return e.repoId.toLowerCase() === repo.id.toLowerCase();
89
+ return repo.name !== undefined && e.repo === repo.name;
90
+ }
91
+ return true;
92
+ });
93
+ }
71
94
  /** Hook input must be at least this long to be worth matching. */
72
95
  exports.HOOK_MIN_CHARS = 20;
73
96
  /** Hard wall-clock budget for hook mode (Claude Code waits on us). */
@@ -194,7 +217,7 @@ function renderHookBlock(ranked, signedIn) {
194
217
  * or a slug (signed out): used as is only when it holds letters, digits, spaces, `.`, `_`, `-`
195
218
  * (safe inside double quotes); otherwise the prompt's id when it has one; otherwise no command.
196
219
  */
197
- function useCommandFor(item) {
220
+ function getCommandFor(item) {
198
221
  if (/^[\p{L}\p{N}][\p{L}\p{N} ._-]*$/u.test(item.name))
199
222
  return `ple get "${item.name}"`;
200
223
  if (ACCOUNT_ID_RE.test(item.id))
@@ -307,7 +330,17 @@ async function suggestCommand(words, options = {}) {
307
330
  entries = (0, libraryCache_1.readCache)(config.user_id)?.entries ?? [];
308
331
  }
309
332
  }
310
- const ranked = (0, rank_1.rankLibrary)(entries, text, limit);
333
+ const tags = (0, tagFilter_1.parseTagFilter)(options.tag);
334
+ if (!config)
335
+ (0, local_1.noteIgnoredProject)(options.project);
336
+ const repo = config && options.project ? await (0, promptResolver_1.resolveProject)(options.project) : undefined;
337
+ const pool = tags.length > 0 || repo ? filterEntries(entries, { tags, repo, ignoreCase: !config }) : entries;
338
+ if (pool.length === 0 && entries.length > 0 && !options.json) {
339
+ const what = [tags.length > 0 ? (0, tagFilter_1.describeTags)(tags) : '', repo ? `repo '${options.project}'` : ''].filter(Boolean).join(' in ');
340
+ console.log(format_1.c.muted(`No saved prompts matched ${what}.`));
341
+ return;
342
+ }
343
+ const ranked = (0, rank_1.rankLibrary)(pool, text, limit);
311
344
  if (options.json) {
312
345
  console.log(JSON.stringify(ranked.map(({ item, score }) => ({
313
346
  id: item.id,
@@ -329,6 +362,6 @@ async function suggestCommand(words, options = {}) {
329
362
  if (item.description)
330
363
  console.log(format_1.c.muted(` ${item.description}`));
331
364
  }
332
- const command = useCommandFor(ranked[0].item);
365
+ const command = getCommandFor(ranked[0].item);
333
366
  console.log(format_1.c.muted(command ? `\nUse one: ${command}` : '\nUse one: its name has characters a shell would act on, so find it with `ple list`.'));
334
367
  }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOT_SIGNED_IN = void 0;
4
+ exports.describeTrialEnd = describeTrialEnd;
5
+ exports.renderWhoami = renderWhoami;
6
+ exports.whoamiJson = whoamiJson;
7
+ exports.whoamiCommand = whoamiCommand;
8
+ const api_client_1 = require("../lib/api-client");
9
+ const config_1 = require("../lib/config");
10
+ const format_1 = require("../lib/format");
11
+ const local_1 = require("./local");
12
+ exports.NOT_SIGNED_IN = 'Not signed in. Run `ple login`.';
13
+ const DAY_MS = 86400000;
14
+ /** "23 / 25", or "23 (no limit)" when the plan has none, or just "23" when the limit is not reported. */
15
+ function quota(used, limit, unlimited) {
16
+ if (used === null)
17
+ return limit === null ? unlimited : `? / ${limit}`;
18
+ return limit === null ? `${used} ${format_1.c.muted(`(${unlimited})`)}` : `${used} / ${limit}`;
19
+ }
20
+ /** "ends 2026-11-12 (in 13 days)" for a trial that is still running; "ended …" afterwards. */
21
+ function describeTrialEnd(iso, now = Date.now()) {
22
+ const end = Date.parse(iso);
23
+ const date = new Date(end).toISOString().slice(0, 10);
24
+ const days = Math.ceil((end - now) / DAY_MS);
25
+ if (days < 0)
26
+ return `ended ${date}`;
27
+ if (days === 0)
28
+ return `ends ${date} (today)`;
29
+ return `ends ${date} (in ${days} day${days === 1 ? '' : 's'})`;
30
+ }
31
+ /** Plain lines for a terminal. The session token is never part of this. */
32
+ function renderWhoami(email, limits, now = Date.now()) {
33
+ const { plan, usage } = limits;
34
+ const rows = [
35
+ ['Plan', plan.name],
36
+ ['Prompts', quota(usage.promptCount, plan.promptLimit, 'no limit')],
37
+ ['Repos', quota(usage.projectCount, plan.projectLimit, 'no limit')],
38
+ // The endpoint reports the per-prompt cap only, not how close each prompt is to it.
39
+ ['Versions', plan.versionLimitPerPrompt === null ? 'no limit' : `up to ${plan.versionLimitPerPrompt} per prompt`],
40
+ ];
41
+ if (plan.trialEndsAt)
42
+ rows.push(['Trial', describeTrialEnd(plan.trialEndsAt, now)]);
43
+ return [format_1.c.title(email || 'signed in'), ...rows.map(([k, v]) => `${format_1.c.label(k.padEnd(10))}${v}`)];
44
+ }
45
+ /** One JSON object for scripts. No token, no refresh token — only account facts. */
46
+ function whoamiJson(email, limits) {
47
+ const { plan, usage } = limits;
48
+ return {
49
+ signed_in: true,
50
+ email,
51
+ plan: { id: plan.id, name: plan.name, is_pro: plan.isPro },
52
+ usage: { prompts: usage.promptCount, repos: usage.projectCount },
53
+ limits: { prompts: plan.promptLimit, repos: plan.projectLimit, versions_per_prompt: plan.versionLimitPerPrompt },
54
+ trial_ends_at: plan.trialEndsAt,
55
+ };
56
+ }
57
+ /**
58
+ * `ple whoami` (alias `account`) — which account is this terminal signed in as, on which plan, and how much
59
+ * of it is used. Only your own account; the email is shown in full. Plan and counts come from
60
+ * GET /api/account/limits (the endpoint the web app's limit checks use). Signed out: one line, exit code 1.
61
+ */
62
+ async function whoamiCommand(options = {}) {
63
+ if ((0, local_1.isSignedOut)()) {
64
+ if (options.json)
65
+ console.log(JSON.stringify({ signed_in: false }));
66
+ else
67
+ console.error(exports.NOT_SIGNED_IN);
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ await (0, api_client_1.ensureAuthed)();
72
+ const limits = await (0, api_client_1.getAccountLimits)();
73
+ const email = (0, format_1.safeText)((0, config_1.readConfig)()?.email ?? '');
74
+ if (options.json) {
75
+ console.log(JSON.stringify(whoamiJson(email, limits)));
76
+ return;
77
+ }
78
+ for (const line of renderWhoami(email, limits))
79
+ console.log(line);
80
+ }
package/dist/help.js CHANGED
@@ -12,9 +12,9 @@ const commander_1 = require("commander");
12
12
  exports.COMMAND_GROUPS = [
13
13
  { title: 'Prompts', commands: ['save', 'get', 'show', 'copy', 'list', 'search', 'log', 'diff', 'rollback', 'tag', 'improve', 'loop'] },
14
14
  { title: 'Repos', commands: ['repo'] },
15
- { title: 'Account', commands: ['login', 'logout'] },
15
+ { title: 'Account', commands: ['login', 'logout', 'whoami'] },
16
16
  { title: 'Import / export / sync', commands: ['import', 'export', 'sync'] },
17
- { title: 'Insights & settings', commands: ['stats', 'suggest', 'config'] },
17
+ { title: 'Insights & settings', commands: ['stats', 'suggest', 'config', 'feedback'] },
18
18
  ];
19
19
  const EXAMPLES = [
20
20
  'ple save "code review" -m "Review this diff: {{diff}}" # no account needed',
@@ -26,6 +26,8 @@ const EXIT_CODES = [
26
26
  '0 success',
27
27
  '1 fix it yourself: bad input, not signed in, not found, not allowed, plan limit',
28
28
  '2 try again later: no network, timeout, rate limit, server error',
29
+ ' (an unknown command also exits 2: a usage error, retrying will not help)',
30
+ ' (`ple feedback` has its own table, see `ple feedback --help`)',
29
31
  ];
30
32
  function formatRootHelp(cmd, helper) {
31
33
  // configureHelp() is inherited by subcommands; only the root gets the grouped layout.
package/dist/index.js CHANGED
@@ -6,13 +6,17 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  const program_1 = require("./program");
8
8
  const updateCheck_1 = require("./lib/updateCheck");
9
+ const feedbackQueue_1 = require("./lib/feedbackQueue");
9
10
  (0, program_1.buildProgram)()
10
11
  .parseAsync(process.argv)
11
- .then(() => {
12
+ .then(async () => {
12
13
  // Once per run, after the command succeeded: at most one stderr line a day about a newer version, and a
13
14
  // detached background lookup when one is due. Never waits for the network, never throws, silent in
14
15
  // pipes, CI and when switched off (see lib/updateCheck.ts).
15
16
  (0, updateCheck_1.afterCommand)();
17
+ // Reports that `ple feedback` could not deliver are retried here, silently, within 2 seconds, at most every
18
+ // 15 minutes and never after the offline commands (see lib/feedbackQueue.ts). Never throws.
19
+ await (0, feedbackQueue_1.flushAfterCommand)();
16
20
  })
17
21
  .catch((err) => {
18
22
  // Commands handle their own errors; this only catches a bug in the wiring itself.
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /**
3
+ * `ple save <title> --project <repo>` — save one prompt INTO THE ACCOUNT, and be safe to run again.
4
+ *
5
+ * `ple sync` uploads whatever text the local files hold, so running it after an edit created a second
6
+ * prompt with the same title. This does the opposite: the title inside the repo is the identity.
7
+ *
8
+ * no prompt with that title in the repo → create it (v1)
9
+ * one, and the text is different → add a NEW version (nothing is overwritten, labels stay put)
10
+ * one, and the text is the same → "unchanged": nothing is sent
11
+ * several, none with this text → stop and list them (never guess which one to change)
12
+ *
13
+ * Only the fields the caller gave are touched. A description that differs is patched on the prompt (no
14
+ * version — the description is not part of a version); tags are only ever ADDED. Titles are compared
15
+ * with {@link normalizeTitle} (case, spacing and Unicode-compatibility insensitive), the same rule the
16
+ * rest of the CLI uses to tell "is this the same prompt".
17
+ *
18
+ * Callers run `ensureAuthed()` first. Server calls: `GET /api/prompts?search=&projectId=`,
19
+ * `POST /api/prompts` (create / new version), `PATCH /api/prompts/{id}`, `POST /api/prompts/{id}/tags`.
20
+ */
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.MAX_TAG_LENGTH = void 0;
23
+ exports.cleanTags = cleanTags;
24
+ exports.assertTagLengths = assertTagLengths;
25
+ exports.saveToAccount = saveToAccount;
26
+ exports.candidateLine = candidateLine;
27
+ const api_client_1 = require("./api-client");
28
+ const format_1 = require("./format");
29
+ const loopApi_1 = require("./loopApi");
30
+ const promptSource_1 = require("./promptSource");
31
+ /** Same cap the web API enforces on a tag name. */
32
+ exports.MAX_TAG_LENGTH = 50;
33
+ /** Tag names as typed: comma-separated allowed (like the local store), trimmed, de-duplicated ignoring case. */
34
+ function cleanTags(raw) {
35
+ const out = [];
36
+ for (const t of raw.flatMap((r) => r.split(','))) {
37
+ const tag = t.trim();
38
+ if (tag && !out.some((o) => o.toLowerCase() === tag.toLowerCase()))
39
+ out.push(tag);
40
+ }
41
+ return out;
42
+ }
43
+ /** Throws the message to show when a tag cannot be sent (the server would reject it anyway). */
44
+ function assertTagLengths(tags) {
45
+ const long = tags.find((t) => t.length > exports.MAX_TAG_LENGTH);
46
+ if (long)
47
+ throw new Error(`Tag '${(0, format_1.safeText)(long).slice(0, 20)}…' is too long (max ${exports.MAX_TAG_LENGTH} characters).`);
48
+ }
49
+ /** Text as compared for "did it change": line endings and the ends trimmed, nothing else. */
50
+ function sameText(a, b) {
51
+ const norm = (s) => s.replace(/\r\n?/g, '\n').trim();
52
+ return norm(a) === norm(b);
53
+ }
54
+ function versionOf(p) {
55
+ const n = p.current_version?.version_number;
56
+ return typeof n === 'number' ? n : null;
57
+ }
58
+ /** Tags the prompt does not have yet (names compared ignoring case). */
59
+ function missingTags(wanted, have) {
60
+ const present = new Set((have.tags ?? []).map((t) => t.name.toLowerCase()));
61
+ return wanted.filter((t) => !present.has(t.toLowerCase()));
62
+ }
63
+ async function addTags(promptId, tags) {
64
+ const added = [];
65
+ const failed = [];
66
+ for (const tag of tags) {
67
+ try {
68
+ await (0, loopApi_1.addTagByName)(promptId, tag);
69
+ added.push(tag);
70
+ }
71
+ catch (err) {
72
+ failed.push({ tag, message: err instanceof Error ? err.message : String(err) });
73
+ }
74
+ }
75
+ return { added, failed };
76
+ }
77
+ /** Server cap per page (GET /api/prompts maxLimit) and the walk's upper bound: 20 pages = 2000 prompts of one repo. */
78
+ const PAGE_LIMIT = 100;
79
+ const MAX_PAGES = 20;
80
+ /**
81
+ * Prompts of the repo whose title is this one. The server's search is the cheap first try (same as the
82
+ * MCP `save_prompt`), but it is an ILIKE: it cannot tell "BAŞLANGICI" from "başlangıcı" (dotless ı) or
83
+ * see through a different spacing. Creating is the one step that cannot be undone, so when the search
84
+ * finds nothing the repo is walked page by page and compared with {@link normalizeTitle} before a
85
+ * second prompt is made.
86
+ */
87
+ async function findSameTitle(title, projectId) {
88
+ const key = (0, promptSource_1.normalizeTitle)(title);
89
+ const byTitle = (rows) => rows.filter((p) => (0, promptSource_1.normalizeTitle)(p.title) === key);
90
+ const searched = byTitle(await (0, api_client_1.listPrompts)({ search: title.trim().replace(/\s+/g, ' '), projectId, limit: PAGE_LIMIT }));
91
+ if (searched.length > 0)
92
+ return searched;
93
+ const found = [];
94
+ const seen = new Set();
95
+ for (let page = 1; page <= MAX_PAGES; page++) {
96
+ const rows = await (0, api_client_1.listPrompts)({ projectId, limit: PAGE_LIMIT, page });
97
+ const fresh = rows.filter((p) => !seen.has(p.id));
98
+ if (fresh.length === 0)
99
+ break; // server ignored `page` and sent the same rows again
100
+ for (const p of fresh)
101
+ seen.add(p.id);
102
+ found.push(...byTitle(fresh));
103
+ if (rows.length < PAGE_LIMIT)
104
+ break; // last page
105
+ }
106
+ return found;
107
+ }
108
+ async function saveToAccount(input) {
109
+ const sameTitle = await findSameTitle(input.title, input.projectId);
110
+ if (sameTitle.length === 0) {
111
+ const saved = await (0, loopApi_1.createPrompt)({
112
+ projectId: input.projectId,
113
+ title: input.title,
114
+ description: input.description,
115
+ body: input.body,
116
+ changelog: 'Saved with ple save',
117
+ });
118
+ if (!saved.promptId)
119
+ throw new Error('The server saved the prompt but sent an unexpected response. Run `ple list --project` to check.');
120
+ const tags = await addTags(saved.promptId, input.tags);
121
+ return { status: 'created', id: saved.promptId, version: saved.versionNumber ?? 1, tagsAdded: tags.added, tagsFailed: tags.failed };
122
+ }
123
+ // The one that already holds this text wins; otherwise a single match is the one to version.
124
+ const identical = sameTitle.find((p) => sameText((0, format_1.joinPromptParts)(p.current_version ?? {}), input.body));
125
+ const target = identical ?? (sameTitle.length === 1 ? sameTitle[0] : undefined);
126
+ if (!target)
127
+ return { status: 'ambiguous', candidates: sameTitle };
128
+ // Description: only when given and different. No version — PATCH changes the prompt, not a version.
129
+ let descriptionUpdated = false;
130
+ if (input.description !== undefined && input.description !== (target.description ?? '')) {
131
+ await (0, loopApi_1.patchDescription)(target.id, input.description);
132
+ descriptionUpdated = true;
133
+ }
134
+ const tags = await addTags(target.id, missingTags(input.tags, target));
135
+ if (identical) {
136
+ return {
137
+ status: 'unchanged',
138
+ id: target.id,
139
+ version: versionOf(target),
140
+ descriptionUpdated,
141
+ tagsAdded: tags.added,
142
+ tagsFailed: tags.failed,
143
+ };
144
+ }
145
+ const saved = await (0, loopApi_1.saveVersion)(target.id, { roleText: '', descriptionText: '', contextText: input.body }, 'Updated with ple save', 'cli');
146
+ return {
147
+ status: 'updated',
148
+ id: target.id,
149
+ version: saved.versionNumber ?? null,
150
+ previousVersion: versionOf(target),
151
+ descriptionUpdated,
152
+ tagsAdded: tags.added,
153
+ tagsFailed: tags.failed,
154
+ };
155
+ }
156
+ /** One candidate line for the "several prompts share this title" stop. */
157
+ function candidateLine(p) {
158
+ return `${(0, format_1.shortId)(p.id)} ${(0, format_1.safeText)(p.title)}`;
159
+ }
@@ -26,6 +26,7 @@ exports.listPrompts = listPrompts;
26
26
  exports.importPrompts = importPrompts;
27
27
  exports.getImportedHashes = getImportedHashes;
28
28
  exports.getAccountHeadroom = getAccountHeadroom;
29
+ exports.getAccountLimits = getAccountLimits;
29
30
  exports.listProjects = listProjects;
30
31
  exports.toRepoDetail = toRepoDetail;
31
32
  exports.listProjectsDetailed = listProjectsDetailed;
@@ -442,6 +443,33 @@ async function getAccountHeadroom() {
442
443
  return { promptsRemaining: null, isPro: false };
443
444
  }
444
445
  }
446
+ /** A count or a limit: a finite number ≥ 0, anything else (missing, null, text) is "not reported". */
447
+ function countOrNull(v) {
448
+ return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : null;
449
+ }
450
+ /**
451
+ * GET /api/account/limits for `ple whoami`. Unlike {@link getAccountHeadroom} this does NOT swallow errors
452
+ * (the caller must tell "signed out / offline" from "free plan"), and it checks the shape: the plan name is
453
+ * server text and goes through {@link safeText}.
454
+ */
455
+ async function getAccountLimits() {
456
+ const res = await apiFetch('/api/account/limits');
457
+ const plan = res.plan ?? {};
458
+ const usage = res.usage ?? {};
459
+ const trial = typeof plan.trialEndsAt === 'string' && !Number.isNaN(Date.parse(plan.trialEndsAt)) ? plan.trialEndsAt : null;
460
+ return {
461
+ plan: {
462
+ id: typeof plan.id === 'string' ? plan.id : null,
463
+ name: typeof plan.name === 'string' && plan.name.trim() ? (0, format_1.safeText)(plan.name) : plan.isPro === true ? 'Pro' : 'Free',
464
+ isPro: plan.isPro === true,
465
+ promptLimit: countOrNull(plan.promptLimit),
466
+ versionLimitPerPrompt: countOrNull(plan.versionLimitPerPrompt),
467
+ projectLimit: countOrNull(plan.projectLimit),
468
+ trialEndsAt: trial,
469
+ },
470
+ usage: { promptCount: countOrNull(usage.promptCount), projectCount: countOrNull(usage.projectCount) },
471
+ };
472
+ }
445
473
  /** GET /api/projects — list the user's accessible repos (for --project resolution). */
446
474
  async function listProjects() {
447
475
  const res = await apiFetch('/api/projects', {
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ /**
3
+ * HTTP for `ple feedback`: POST /api/feedback (the session is optional) and the owner's
4
+ * GET /api/feedback · PATCH /api/feedback/{id}.
5
+ *
6
+ * Kept out of `api-client.ts` on purpose: a report must go out WITHOUT a session, a failed send is
7
+ * queued instead of thrown, and the status codes map to the feedback exit codes rather than to the
8
+ * generic 1/2. It reuses the same rules as the rest of the CLI: the base URL is validated before any
9
+ * request is built, every request has a timeout, redirects are never followed (a 3xx would replay the
10
+ * body, and the bearer token, at an address the server picked), and a token is only ever sent to the
11
+ * configured API origin. Nothing here throws; every outcome is a value.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.FEEDBACK_STATUSES = exports.OWNER_TIMEOUT_MS = exports.SUBMIT_TIMEOUT_MS = void 0;
15
+ exports.request = request;
16
+ exports.serverMessage = serverMessage;
17
+ exports.serverDetails = serverDetails;
18
+ exports.toSendResult = toSendResult;
19
+ exports.sendFeedback = sendFeedback;
20
+ const constants_1 = require("./constants");
21
+ const format_1 = require("./format");
22
+ exports.SUBMIT_TIMEOUT_MS = 15000;
23
+ exports.OWNER_TIMEOUT_MS = 15000;
24
+ exports.FEEDBACK_STATUSES = ['new', 'triaged', 'done', 'wontfix'];
25
+ const MAX_RETRY_AFTER_S = 86400;
26
+ function clampRetryAfter(value) {
27
+ const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d{1,6}$/.test(value.trim()) ? Number(value) : NaN;
28
+ return Number.isFinite(n) && n >= 0 ? Math.min(Math.floor(n), MAX_RETRY_AFTER_S) : undefined;
29
+ }
30
+ function isTimeout(err, signal) {
31
+ if (signal.aborted)
32
+ return true;
33
+ const name = err?.name;
34
+ return name === 'TimeoutError' || name === 'AbortError';
35
+ }
36
+ async function request(input) {
37
+ if (constants_1.API_BASE_URL_ERROR)
38
+ return { kind: 'config', message: (0, format_1.safeText)(constants_1.API_BASE_URL_ERROR) };
39
+ const url = new URL(constants_1.API_BASE_URL + input.path);
40
+ for (const [k, v] of Object.entries(input.query ?? {})) {
41
+ if (v !== undefined && v !== '')
42
+ url.searchParams.set(k, String(v));
43
+ }
44
+ const headers = { Accept: 'application/json', 'X-CLI-Version': constants_1.CLI_VERSION };
45
+ if (input.body !== undefined)
46
+ headers['Content-Type'] = 'application/json';
47
+ if (input.token)
48
+ headers.Authorization = `Bearer ${input.token}`;
49
+ const signal = AbortSignal.timeout(Math.max(1, Math.floor(input.timeoutMs)));
50
+ let res;
51
+ try {
52
+ res = await (input.fetchImpl ?? fetch)(url.toString(), {
53
+ method: input.method,
54
+ headers,
55
+ body: input.body === undefined ? undefined : JSON.stringify(input.body),
56
+ signal,
57
+ redirect: 'manual',
58
+ });
59
+ }
60
+ catch (err) {
61
+ if (isTimeout(err, signal)) {
62
+ return { kind: 'unreachable', message: `No response from ${constants_1.API_BASE_URL} within ${Math.round(input.timeoutMs / 1000)}s.` };
63
+ }
64
+ return { kind: 'unreachable', message: (0, format_1.safeText)(`Cannot reach ${constants_1.API_BASE_URL}. ${err instanceof Error ? err.message : String(err)}`).slice(0, 300) };
65
+ }
66
+ if (res.status >= 300 && res.status < 400) {
67
+ return { kind: 'unreachable', message: `The server answered with a redirect (HTTP ${res.status}); the CLI does not follow redirects. Check PROMPTLIKE_API_URL (currently ${constants_1.API_BASE_URL}).` };
68
+ }
69
+ let body = {};
70
+ try {
71
+ const parsed = await res.json();
72
+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))
73
+ body = parsed;
74
+ }
75
+ catch {
76
+ // Not JSON, or cut off mid-body: the status alone decides.
77
+ }
78
+ const retryAfter = clampRetryAfter(body.retry_after) ?? clampRetryAfter(res.headers.get('retry-after') ?? undefined);
79
+ return { kind: 'response', status: res.status, body, retryAfter };
80
+ }
81
+ /** The server's `error` text, made terminal-safe and short; `fallback` when there is none. */
82
+ function serverMessage(body, fallback) {
83
+ const e = body.error;
84
+ return typeof e === 'string' && e.trim() ? (0, format_1.safeText)(e).trim().slice(0, 300) : fallback;
85
+ }
86
+ /** `details` of a 400, flattened to one safe line (it may be an array, an object or a string). */
87
+ function serverDetails(body) {
88
+ const d = body.details;
89
+ if (d === undefined || d === null)
90
+ return '';
91
+ let text;
92
+ try {
93
+ text = typeof d === 'string' ? d : JSON.stringify(d);
94
+ }
95
+ catch {
96
+ return '';
97
+ }
98
+ return (0, format_1.safeText)(text).slice(0, 300);
99
+ }
100
+ function toSendResult(out) {
101
+ if (out.kind === 'config')
102
+ return { kind: 'config', message: out.message };
103
+ if (out.kind === 'unreachable')
104
+ return { kind: 'unavailable', message: out.message };
105
+ const { status, body } = out;
106
+ if (status === 201 || status === 200) {
107
+ const id = typeof body.id === 'string' || typeof body.id === 'number' ? (0, format_1.safeText)(String(body.id)).slice(0, 64) : undefined;
108
+ return { kind: 'sent', id: id || undefined };
109
+ }
110
+ if (status === 400 || status === 413 || status === 422) {
111
+ const fallback = status === 413 ? 'The report is too large.' : 'The server rejected the report.';
112
+ const details = serverDetails(body);
113
+ return { kind: 'invalid', status, message: serverMessage(body, fallback) + (details ? ` (${details})` : '') };
114
+ }
115
+ if (status === 429)
116
+ return { kind: 'rate_limited', retryAfter: out.retryAfter };
117
+ if (status === 401 || status === 403)
118
+ return { kind: 'auth', status };
119
+ if (status >= 500 || status === 404 || status === 408) {
120
+ return { kind: 'unavailable', message: `The server answered HTTP ${status}.` };
121
+ }
122
+ return { kind: 'unexpected', status, message: serverMessage(body, `The server answered HTTP ${status}.`) };
123
+ }
124
+ /** POST one report. With a `token` the report is tied to the account; a 401/403 is returned for the caller to retry anonymously. */
125
+ async function sendFeedback(payload, opts = {}) {
126
+ return toSendResult(await request({
127
+ method: 'POST',
128
+ path: '/api/feedback',
129
+ body: payload,
130
+ token: opts.token,
131
+ timeoutMs: opts.timeoutMs ?? exports.SUBMIT_TIMEOUT_MS,
132
+ fetchImpl: opts.fetchImpl,
133
+ }));
134
+ }