promptlike 0.4.1 → 0.6.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.
@@ -0,0 +1,250 @@
1
+ "use strict";
2
+ /**
3
+ * `ple import --scan` — bring the prompts you already keep on disk into PLE
4
+ * (W1-2 — strategy F15, "activation = investment").
5
+ *
6
+ * ple import --scan --dry-run # preview: tool, path, title, size, status
7
+ * ple import --scan # preview + pick (1,3-5 / all)
8
+ * ple import --scan --all # no questions (scripts, agents)
9
+ * ple import --scan --project api # into one repo
10
+ *
11
+ * Signed out → the local store (local-first, same as `ple save`).
12
+ * Signed in → the account, with provenance so a re-run skips what already
13
+ * came in (sha256 of the body; the server double-checks).
14
+ *
15
+ * Nothing is read that the secret guard refuses (see lib/secretGuard.ts), and
16
+ * nothing is uploaded without either an explicit pick or `--all`.
17
+ */
18
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
19
+ if (k2 === undefined) k2 = k;
20
+ var desc = Object.getOwnPropertyDescriptor(m, k);
21
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
22
+ desc = { enumerable: true, get: function() { return m[k]; } };
23
+ }
24
+ Object.defineProperty(o, k2, desc);
25
+ }) : (function(o, m, k, k2) {
26
+ if (k2 === undefined) k2 = k;
27
+ o[k2] = m[k];
28
+ }));
29
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
30
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
31
+ }) : function(o, v) {
32
+ o["default"] = v;
33
+ });
34
+ var __importStar = (this && this.__importStar) || (function () {
35
+ var ownKeys = function(o) {
36
+ ownKeys = Object.getOwnPropertyNames || function (o) {
37
+ var ar = [];
38
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
39
+ return ar;
40
+ };
41
+ return ownKeys(o);
42
+ };
43
+ return function (mod) {
44
+ if (mod && mod.__esModule) return mod;
45
+ var result = {};
46
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
47
+ __setModuleDefault(result, mod);
48
+ return result;
49
+ };
50
+ })();
51
+ Object.defineProperty(exports, "__esModule", { value: true });
52
+ exports.parseSelection = parseSelection;
53
+ exports.importCommand = importCommand;
54
+ const readline = __importStar(require("readline"));
55
+ const store = __importStar(require("../lib/localStore"));
56
+ const api_client_1 = require("../lib/api-client");
57
+ const promptResolver_1 = require("../lib/promptResolver");
58
+ const scanners_1 = require("../lib/scanners");
59
+ const local_1 = require("./local");
60
+ const format_1 = require("../lib/format");
61
+ const constants_1 = require("../lib/constants");
62
+ /** The import endpoint caps one request at 50 records. */
63
+ const BATCH = 50;
64
+ /**
65
+ * Parse a pick like `1,3-5`, `all`, or empty (cancel). Returns 0-based
66
+ * indices, `null` for cancel; throws on anything out of range or malformed.
67
+ */
68
+ function parseSelection(input, count) {
69
+ const v = input.trim().toLowerCase();
70
+ if (v === '' || v === 'q' || v === 'n' || v === 'none')
71
+ return null;
72
+ if (v === 'a' || v === 'all' || v === '*')
73
+ return Array.from({ length: count }, (_, i) => i);
74
+ const picked = new Set();
75
+ for (const part of v.split(/[\s,]+/).filter(Boolean)) {
76
+ const range = part.match(/^(\d+)-(\d+)$/);
77
+ const single = part.match(/^(\d+)$/);
78
+ if (range) {
79
+ const a = Number(range[1]);
80
+ const b = Number(range[2]);
81
+ if (a < 1 || b > count || a > b)
82
+ throw new Error(`'${part}' is out of range (1-${count}).`);
83
+ for (let i = a; i <= b; i++)
84
+ picked.add(i - 1);
85
+ }
86
+ else if (single) {
87
+ const n = Number(single[1]);
88
+ if (n < 1 || n > count)
89
+ throw new Error(`'${part}' is out of range (1-${count}).`);
90
+ picked.add(n - 1);
91
+ }
92
+ else {
93
+ throw new Error(`Could not read '${part}'. Use numbers like 1,3-5 or 'all'.`);
94
+ }
95
+ }
96
+ return [...picked].sort((x, y) => x - y);
97
+ }
98
+ function formatSize(bytes) {
99
+ return bytes < 1024 ? `${bytes} B` : `${(bytes / 1024).toFixed(1)} KB`;
100
+ }
101
+ function defaultAsk(question) {
102
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
103
+ return new Promise((resolve) => {
104
+ rl.question(question, (answer) => {
105
+ rl.close();
106
+ resolve(answer);
107
+ });
108
+ });
109
+ }
110
+ /** Local slug that does not overwrite a different existing prompt. */
111
+ function freeSlug(title) {
112
+ const base = store.slugify(title.replace(/[/\\:]+/g, '-'));
113
+ let slug = base;
114
+ for (let n = 2; store.exists(slug); n++)
115
+ slug = `${base}-${n}`;
116
+ return slug;
117
+ }
118
+ function toImportable(cand) {
119
+ return {
120
+ title: cand.title,
121
+ description: cand.description || undefined,
122
+ content: cand.body,
123
+ tags: cand.tags,
124
+ origin: {
125
+ tool: cand.tool,
126
+ kind: cand.kind,
127
+ path: cand.displayPath,
128
+ sha256: cand.sha256,
129
+ ...(Object.keys(cand.meta).length > 0 ? { meta: cand.meta } : {}),
130
+ },
131
+ };
132
+ }
133
+ async function importCommand(options = {}, deps = {}) {
134
+ if (!options.scan) {
135
+ throw new Error('Nothing to import. Use `ple import --scan` to find prompts in your agent folders.');
136
+ }
137
+ const signedOut = (0, local_1.isSignedOut)();
138
+ const destination = signedOut ? 'your local store' : 'your account';
139
+ const result = (0, scanners_1.scanAgentFiles)(deps.scan);
140
+ // What is already there: account → provenance hashes; local → body hashes.
141
+ let known;
142
+ if (signedOut) {
143
+ known = new Set(store.list().map((p) => (0, scanners_1.hashBody)(p.body)));
144
+ }
145
+ else {
146
+ await (0, api_client_1.ensureAuthed)();
147
+ known = await (0, api_client_1.getImportedHashes)();
148
+ }
149
+ const fresh = result.candidates.filter((cand) => !known.has(cand.sha256));
150
+ const already = result.candidates.length - fresh.length;
151
+ if (result.candidates.length === 0 && result.skipped.length === 0) {
152
+ console.log(format_1.c.muted('No agent prompt files found here or in your home folder.'));
153
+ console.log(format_1.c.muted('Looked in .claude/commands, .claude/skills, .cursor/commands, ~/.codex/prompts, .github/prompts, AGENTS.md, CLAUDE.md.'));
154
+ return;
155
+ }
156
+ console.log(format_1.c.title(`Found ${result.candidates.length} prompt file${result.candidates.length === 1 ? '' : 's'}`) +
157
+ format_1.c.muted(` → ${destination}`));
158
+ fresh.forEach((cand, i) => {
159
+ console.log(` ${format_1.c.accent(String(i + 1).padStart(3))} ${cand.tool.padEnd(11)} ${cand.kind.padEnd(7)} ` +
160
+ `${(0, format_1.truncate)(cand.title, 40).padEnd(40)} ${format_1.c.muted(formatSize(cand.bytes).padStart(8))} ${format_1.c.muted(cand.displayPath)}`);
161
+ });
162
+ if (already > 0) {
163
+ console.log(format_1.c.muted(` … and ${already} already imported (same content) — skipped`));
164
+ }
165
+ if (result.duplicates.length > 0) {
166
+ console.log(format_1.c.muted(` … ${result.duplicates.length} identical cop${result.duplicates.length === 1 ? 'y' : 'ies'} in another folder — counted once`));
167
+ }
168
+ for (const s of result.skipped) {
169
+ console.log(format_1.c.warn(` ⚠ ${s.displayPath}: ${s.reason}`));
170
+ }
171
+ if (fresh.length === 0) {
172
+ console.log(format_1.c.success('\nNothing new to import.'));
173
+ return;
174
+ }
175
+ if (options.dryRun) {
176
+ console.log(format_1.c.muted(`\nDry run — nothing imported. Run \`ple import --scan\` to pick, or add --all.`));
177
+ return;
178
+ }
179
+ let selected;
180
+ if (options.all) {
181
+ selected = fresh;
182
+ }
183
+ else {
184
+ const interactive = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
185
+ if (!interactive) {
186
+ console.log(format_1.c.muted(`\nNot a terminal — re-run with --all to import these ${fresh.length}, or --dry-run to only look.`));
187
+ return;
188
+ }
189
+ const answer = await (deps.ask ?? defaultAsk)(`\nImport which? [all | 1,3-5 | Enter to cancel]: `);
190
+ const picked = parseSelection(answer, fresh.length);
191
+ if (!picked || picked.length === 0) {
192
+ console.log(format_1.c.muted('Cancelled — nothing imported.'));
193
+ return;
194
+ }
195
+ selected = picked.map((i) => fresh[i]);
196
+ }
197
+ if (signedOut) {
198
+ for (const cand of selected) {
199
+ store.save({ slug: freeSlug(cand.title), title: cand.title, description: cand.description, tags: cand.tags, body: cand.body });
200
+ }
201
+ console.log(format_1.c.success(`✓ Imported ${selected.length} prompt${selected.length === 1 ? '' : 's'} into ${store.promptsDir()}`));
202
+ console.log(format_1.c.muted('Sign in and run `ple sync` to carry them to your account (history, web, agents).'));
203
+ return;
204
+ }
205
+ const projectId = options.project ? await (0, promptResolver_1.resolveProjectId)(options.project) : undefined;
206
+ // Say the plan limit out loud BEFORE uploading, not after a partial result.
207
+ const headroom = await (0, api_client_1.getAccountHeadroom)();
208
+ if (headroom.promptsRemaining !== null && selected.length > headroom.promptsRemaining) {
209
+ console.log(format_1.c.warn(`Your plan has room for ${headroom.promptsRemaining} more prompt${headroom.promptsRemaining === 1 ? '' : 's'}; ` +
210
+ `the first ${headroom.promptsRemaining} of ${selected.length} will be imported.`));
211
+ }
212
+ const payload = selected.map(toImportable);
213
+ let imported = 0;
214
+ let skippedDuplicate = 0;
215
+ let truncatedByQuota = 0;
216
+ let failed = 0;
217
+ let abortMessage = null;
218
+ for (let i = 0; i < payload.length; i += BATCH) {
219
+ try {
220
+ const res = await (0, api_client_1.importPrompts)(payload.slice(i, i + BATCH), {
221
+ source: 'import',
222
+ projectId,
223
+ fallbackToExistingProject: !projectId,
224
+ });
225
+ imported += res.imported;
226
+ skippedDuplicate += res.skippedDuplicate;
227
+ truncatedByQuota += res.truncatedByQuota;
228
+ failed += res.failed + res.skippedInvalid;
229
+ }
230
+ catch (err) {
231
+ abortMessage = err instanceof Error ? err.message : String(err);
232
+ truncatedByQuota += payload.length - i;
233
+ break;
234
+ }
235
+ }
236
+ console.log(format_1.c.success(`✓ Imported ${imported} prompt${imported === 1 ? '' : 's'} into your account`));
237
+ if (skippedDuplicate > 0)
238
+ console.log(format_1.c.muted(` ${skippedDuplicate} already there — skipped`));
239
+ if (abortMessage)
240
+ console.log(format_1.c.warn(`⚠ Stopped early: ${abortMessage}`));
241
+ if (truncatedByQuota > 0) {
242
+ console.log(format_1.c.warn(`⚠ ${truncatedByQuota} not imported — plan prompt limit reached.`));
243
+ console.log(format_1.c.muted(` Start the 14-day Pro trial to bring the rest: ${constants_1.WEB_APP_URL}/pricing`));
244
+ console.log(format_1.c.muted(' Then run `ple import --scan` again — what already came in is skipped.'));
245
+ }
246
+ if (failed > 0)
247
+ console.log(format_1.c.warn(`⚠ ${failed} failed. Re-run \`ple import --scan\` to retry those.`));
248
+ if (imported > 0)
249
+ console.log(format_1.c.muted(`Open them at ${constants_1.WEB_APP_URL}/dashboard or \`ple list\`.`));
250
+ }
@@ -5,6 +5,7 @@ const api_client_1 = require("../lib/api-client");
5
5
  const local_1 = require("./local");
6
6
  const constants_1 = require("../lib/constants");
7
7
  const format_1 = require("../lib/format");
8
+ const libraryCache_1 = require("../lib/libraryCache");
8
9
  /**
9
10
  * `ple list [--tag X] [--limit N]` — list the user's prompts.
10
11
  *
@@ -21,6 +22,9 @@ async function listCommand(options) {
21
22
  }
22
23
  await (0, api_client_1.ensureAuthed)();
23
24
  const prompts = await (0, api_client_1.listPrompts)({ tag: options.tag, limit });
25
+ // Keep the suggestion cache (W1-5) in step with the account — detached,
26
+ // at most once a minute, never slows this command down.
27
+ (0, libraryCache_1.startBackgroundRefresh)();
24
28
  if (prompts.length === 0) {
25
29
  if (options.tag) {
26
30
  console.log(format_1.c.muted(`No prompts matched tag '${options.tag}'.`));
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ /**
3
+ * `ple log <name>` — version history in the terminal (W1-4).
4
+ *
5
+ * v5 1.0.4 rollback 2h ago Rolled back to v2
6
+ * * marks the current version.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.logCommand = logCommand;
10
+ const api_client_1 = require("../lib/api-client");
11
+ const format_1 = require("../lib/format");
12
+ const history_1 = require("./history");
13
+ async function logCommand(name, options = {}) {
14
+ const prompt = await (0, history_1.resolveForHistory)(name, options.project);
15
+ if (!prompt) {
16
+ process.exitCode = 1;
17
+ return;
18
+ }
19
+ const history = await (0, api_client_1.getPromptHistory)(prompt.id);
20
+ const limit = Math.max(1, Math.min(Number.parseInt(options.limit ?? '20', 10) || 20, 100));
21
+ const versions = (0, history_1.sortNewestFirst)(history.versions).slice(0, limit);
22
+ if (options.json) {
23
+ console.log(JSON.stringify(versions.map((v) => ({
24
+ version: v.version_number,
25
+ semver: (0, history_1.semverOf)(v),
26
+ source: v.source ?? null,
27
+ created_at: v.created_at,
28
+ changelog: v.changelog ?? null,
29
+ current: v.id === history.current_version_id,
30
+ })), null, 2));
31
+ return;
32
+ }
33
+ console.log(format_1.c.title(history.title) + format_1.c.muted(` ${history.versions.length} version${history.versions.length === 1 ? '' : 's'}`));
34
+ if (versions.length === 0) {
35
+ console.log(format_1.c.muted(' No versions yet.'));
36
+ return;
37
+ }
38
+ for (const v of versions) {
39
+ const mark = v.id === history.current_version_id ? format_1.c.success('*') : ' ';
40
+ console.log(`${mark} ${format_1.c.accent(`v${v.version_number}`.padEnd(5))} ${(0, history_1.semverOf)(v).padEnd(9)} ` +
41
+ `${format_1.c.muted((v.source ?? '').padEnd(9))} ${format_1.c.muted((0, format_1.timeAgo)(v.created_at).padEnd(8))} ` +
42
+ (0, format_1.truncate)((v.changelog ?? '').replace(/\s+/g, ' '), 60));
43
+ }
44
+ if (history.versions.length > versions.length) {
45
+ console.log(format_1.c.muted(` … ${history.versions.length - versions.length} older (use --limit)`));
46
+ }
47
+ console.log(format_1.c.muted(`\nCompare: ple diff "${history.title}" <a> <b> · Restore: ple rollback "${history.title}" <version>`));
48
+ }
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ /**
3
+ * `ple rollback <name> <version> [--yes]` — restore an old version (W1-4).
4
+ *
5
+ * Non-destructive, same as the web: the chosen version is copied forward as
6
+ * a NEW version; nothing is deleted, so a rollback can itself be rolled back.
7
+ * Asks first on a terminal; scripts must pass `--yes`.
8
+ */
9
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
13
+ desc = { enumerable: true, get: function() { return m[k]; } };
14
+ }
15
+ Object.defineProperty(o, k2, desc);
16
+ }) : (function(o, m, k, k2) {
17
+ if (k2 === undefined) k2 = k;
18
+ o[k2] = m[k];
19
+ }));
20
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
21
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
22
+ }) : function(o, v) {
23
+ o["default"] = v;
24
+ });
25
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
42
+ Object.defineProperty(exports, "__esModule", { value: true });
43
+ exports.rollbackCommand = rollbackCommand;
44
+ const readline = __importStar(require("readline"));
45
+ const api_client_1 = require("../lib/api-client");
46
+ const format_1 = require("../lib/format");
47
+ const history_1 = require("./history");
48
+ function defaultConfirm(question) {
49
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
50
+ return new Promise((resolve) => {
51
+ rl.question(question, (answer) => {
52
+ rl.close();
53
+ resolve(/^y(es)?$/i.test(answer.trim()));
54
+ });
55
+ });
56
+ }
57
+ async function rollbackCommand(name, ref, options = {}, deps = {}) {
58
+ const prompt = await (0, history_1.resolveForHistory)(name, options.project);
59
+ if (!prompt) {
60
+ process.exitCode = 1;
61
+ return;
62
+ }
63
+ const history = await (0, api_client_1.getPromptHistory)(prompt.id);
64
+ const target = (0, history_1.findVersion)(history.versions, ref);
65
+ if (!target)
66
+ throw (0, history_1.versionNotFound)(ref, history.versions);
67
+ const current = (0, history_1.currentVersion)(history);
68
+ if (current && current.id === target.id) {
69
+ console.log(format_1.c.muted(`v${target.version_number} is already the current version — nothing to do.`));
70
+ return;
71
+ }
72
+ if (!options.yes) {
73
+ const interactive = deps.isTTY ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
74
+ if (!interactive) {
75
+ throw new Error('Refusing to roll back without confirmation. Re-run with --yes.');
76
+ }
77
+ const ok = await (deps.confirm ?? defaultConfirm)(`Restore '${history.title}' to v${target.version_number} (${(0, history_1.semverOf)(target)})? ` +
78
+ `This adds a new version; nothing is deleted. [y/N] `);
79
+ if (!ok) {
80
+ console.log(format_1.c.muted('Cancelled.'));
81
+ return;
82
+ }
83
+ }
84
+ const res = await (0, api_client_1.rollbackPrompt)(history.id, target.id);
85
+ const newNo = res.new_version_number != null ? `v${res.new_version_number}` : 'a new version';
86
+ console.log(format_1.c.success(`✓ Restored v${target.version_number} as ${newNo}`) + format_1.c.muted(` — ${history.title}`));
87
+ console.log(format_1.c.muted(`Undo with: ple rollback "${history.title}" ${current ? `v${current.version_number}` : '<version>'}`));
88
+ }
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ /**
3
+ * `ple stats [--range 7|30|365]` — the Insights panel in the terminal (W1-1).
4
+ *
5
+ * Same numbers as /dashboard/insights: uses in the window, where they came
6
+ * from (web / CLI / agents), the most used prompts and the ones gathering
7
+ * dust. Free accounts get a 7-day view; asking for more says so plainly
8
+ * instead of silently shrinking the window.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.parseRange = parseRange;
12
+ exports.renderStats = renderStats;
13
+ exports.statsCommand = statsCommand;
14
+ const api_client_1 = require("../lib/api-client");
15
+ const local_1 = require("./local");
16
+ const format_1 = require("../lib/format");
17
+ const libraryCache_1 = require("../lib/libraryCache");
18
+ const RANGES = [7, 30, 365];
19
+ const SURFACE_LABELS = {
20
+ web: 'Web',
21
+ cli: 'CLI',
22
+ mcp_tool: 'MCP tool',
23
+ mcp_prompt: 'MCP slash',
24
+ mcp_resource: 'MCP @-mention',
25
+ extension: 'Extension',
26
+ hook: 'Agent hook',
27
+ repo: 'Repo',
28
+ api: 'API',
29
+ unknown: 'Other',
30
+ };
31
+ /** Parse `--range`; accepts 7/30/365 (also "12m"/"1y" for the year). */
32
+ function parseRange(value) {
33
+ if (!value)
34
+ return 7;
35
+ const v = value.trim().toLowerCase();
36
+ if (v === '12m' || v === '1y' || v === 'year')
37
+ return 365;
38
+ const n = Number.parseInt(v, 10);
39
+ if (RANGES.includes(n))
40
+ return n;
41
+ throw new Error(`--range must be one of ${RANGES.join(', ')}.`);
42
+ }
43
+ function bar(count, max, width = 20) {
44
+ const n = max > 0 ? Math.max(1, Math.round((count / max) * width)) : 0;
45
+ return '█'.repeat(n);
46
+ }
47
+ function renderStats(s) {
48
+ const out = [];
49
+ const window = s.range_days === 365 ? '12 months' : `${s.range_days} days`;
50
+ out.push(format_1.c.title(`Usage — last ${window}`));
51
+ if (s.locked) {
52
+ out.push(format_1.c.warn(`Free keeps a 7-day view (you asked for ${s.requested_days}). Your history is kept — Pro unlocks it.`));
53
+ }
54
+ if (s.total === 0) {
55
+ out.push(format_1.c.muted('No uses in this period yet. `ple get <name>` and `ple copy <name>` count here.'));
56
+ }
57
+ else {
58
+ const nonWeb = Math.round((s.non_web / s.total) * 100);
59
+ out.push(`${format_1.c.label('Uses')} ${s.total}`);
60
+ out.push(`${format_1.c.label('Outside the web')} ${nonWeb}%`);
61
+ if (s.suggestion > 0)
62
+ out.push(`${format_1.c.label('From suggestions')} ${s.suggestion}`);
63
+ out.push('');
64
+ out.push(format_1.c.label('Where'));
65
+ const max = Math.max(...s.by_surface.map((x) => x.count));
66
+ for (const x of s.by_surface) {
67
+ const label = (SURFACE_LABELS[x.surface] ?? x.surface).padEnd(14);
68
+ out.push(` ${label} ${String(x.count).padStart(5)} ${format_1.c.accent(bar(x.count, max))}`);
69
+ }
70
+ if (s.by_client.length > 0) {
71
+ out.push(format_1.c.muted(` agents: ${s.by_client.map((x) => `${x.client} (${x.count})`).join(', ')}`));
72
+ }
73
+ out.push('');
74
+ out.push(format_1.c.label('Most used'));
75
+ s.top_prompts.forEach((p, i) => {
76
+ out.push(` ${String(i + 1).padStart(2)}. ${p.title} ${format_1.c.muted(`${p.count}×`)}`);
77
+ });
78
+ }
79
+ if (s.unused_30d.length > 0) {
80
+ out.push('');
81
+ out.push(format_1.c.label('Not used in 30 days'));
82
+ for (const p of s.unused_30d) {
83
+ out.push(` ${p.title} ${format_1.c.muted(p.last_used_at ? `last ${(0, format_1.timeAgo)(p.last_used_at)}` : 'never used')}`);
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+ async function statsCommand(options = {}) {
89
+ const range = parseRange(options.range);
90
+ if ((0, local_1.isSignedOut)()) {
91
+ throw new Error('Usage stats live in your account. Run `ple login` first (local prompts are not tracked).');
92
+ }
93
+ await (0, api_client_1.ensureAuthed)();
94
+ const insights = await (0, api_client_1.getUsageInsights)(range);
95
+ if (!insights || !insights.available) {
96
+ console.log(format_1.c.muted('Usage tracking is not switched on for your account yet — check back soon.'));
97
+ return;
98
+ }
99
+ // Suggestion impressions are counted on this machine only (W1-5): the
100
+ // server sees an accepted suggestion (via=suggestion), never a shown one.
101
+ const shown = (0, libraryCache_1.readState)().impressions;
102
+ if (options.json) {
103
+ console.log(JSON.stringify({ ...insights, local_suggestions_shown: shown }, null, 2));
104
+ return;
105
+ }
106
+ for (const line of renderStats(insights))
107
+ console.log(line);
108
+ if (shown > 0) {
109
+ const rate = Math.round((insights.suggestion / shown) * 100);
110
+ console.log(format_1.c.muted(`\nSuggestions shown on this machine: ${shown} · picked up: ${insights.suggestion} (${rate}%, this window)`));
111
+ }
112
+ }