promptlike 0.5.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,19 +12,66 @@
12
12
  * - attach the bearer token, resolve URLs against API_BASE_URL
13
13
  * - proactive refresh (expiring token) + reactive refresh on 401, retry once
14
14
  * - map 429 / error bodies to clean, user-facing Error messages
15
+ * - bound every request with a timeout (O5 / PLE-03): a server that keeps the
16
+ * connection open without answering must not hang a command forever
15
17
  */
16
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.USE_SURFACES = exports.RequestTimeoutError = exports.USE_EVENT_TIMEOUT_MS = exports.IMPORT_TIMEOUT_MS = exports.WRITE_TIMEOUT_MS = exports.READ_TIMEOUT_MS = void 0;
17
20
  exports.login = login;
18
21
  exports.ensureAuthed = ensureAuthed;
19
22
  exports.listPrompts = listPrompts;
20
23
  exports.importPrompts = importPrompts;
24
+ exports.getImportedHashes = getImportedHashes;
25
+ exports.getAccountHeadroom = getAccountHeadroom;
21
26
  exports.listProjects = listProjects;
22
27
  exports.getPromptById = getPromptById;
28
+ exports.getPromptHistory = getPromptHistory;
29
+ exports.rollbackPrompt = rollbackPrompt;
30
+ exports.buildUseEventBody = buildUseEventBody;
23
31
  exports.recordPromptUse = recordPromptUse;
32
+ exports.getUsageInsights = getUsageInsights;
24
33
  const constants_1 = require("./constants");
25
34
  const config_1 = require("./config");
26
35
  const NOT_LOGGED_IN = 'Not logged in. Run `ple login` first.';
27
36
  const SESSION_EXPIRED = 'Session expired. Log in again: `ple login`';
37
+ /**
38
+ * İstek zaman aşımları (O5 / PLE-03). Süre yalnız başlıkları değil gövde
39
+ * okumasını da kapsar (aynı sinyal). Otomatik tekrar deneme YOK: zaman aşımına
40
+ * uğrayan bir yazma sunucuda tamamlanmış olabilir, körü körüne tekrar çift kayıt
41
+ * yapabilir; bu yüzden yazma iletisi "önce kontrol et" der.
42
+ */
43
+ /** GET istekleri (liste, detay, içgörü): hafif okumalar. */
44
+ exports.READ_TIMEOUT_MS = 15000;
45
+ /** GET dışı istekler (giriş, yenileme, geri alma). */
46
+ exports.WRITE_TIMEOUT_MS = 30000;
47
+ /** Toplu içe aktarma: istek başına 50 kayda kadar, kayıt başına birkaç sorgu. */
48
+ exports.IMPORT_TIMEOUT_MS = 120000;
49
+ /** Kullanım kaydı (fire-and-forget): asılı sunucu komutun çıkışını bekletmesin. */
50
+ exports.USE_EVENT_TIMEOUT_MS = 5000;
51
+ /** Zaman aşımı hatası — `refreshSession` bunu "oturum bitti"ye çevirmesin diye ayrı sınıf. */
52
+ class RequestTimeoutError extends Error {
53
+ constructor(timeoutMs, method) {
54
+ const advice = method === 'GET'
55
+ ? 'Check your connection and try again.'
56
+ : 'The server may still have completed the request; check before retrying.';
57
+ super(`No response from ${constants_1.API_BASE_URL} within ${Math.round(timeoutMs / 1000)}s. ${advice}`);
58
+ this.name = 'RequestTimeoutError';
59
+ }
60
+ }
61
+ exports.RequestTimeoutError = RequestTimeoutError;
62
+ /**
63
+ * Hata süre aşımından mı geldi? Önce sinyalin kendisine bakılır: eski Node /
64
+ * undici sürümlerinde gövde okuması yarıda kesilince hata `TimeoutError` yerine
65
+ * `TypeError: terminated` gibi başka biçimde gelebilir; sinyal `aborted` ise
66
+ * sebep süre dolmasıdır, hatanın biçimi önemsizdir. Ad kontrolü yedektir
67
+ * (AbortSignal.timeout → `TimeoutError`, iptal → `AbortError`).
68
+ */
69
+ function isTimeout(err, signal) {
70
+ if (signal.aborted)
71
+ return true;
72
+ const name = err?.name;
73
+ return name === 'TimeoutError' || name === 'AbortError';
74
+ }
28
75
  /**
29
76
  * Fallback messages for server error codes. The API almost always sends a
30
77
  * human-readable `error` string; this map is only used when a response carries
@@ -105,7 +152,10 @@ async function refreshSession() {
105
152
  auth: false,
106
153
  });
107
154
  }
108
- catch {
155
+ catch (err) {
156
+ // Asılı sunucu "oturumun bitti, yeniden giriş yap" demek değildir.
157
+ if (err instanceof RequestTimeoutError)
158
+ throw err;
109
159
  throw new Error(SESSION_EXPIRED);
110
160
  }
111
161
  persist(data);
@@ -113,6 +163,8 @@ async function refreshSession() {
113
163
  /** Core request helper. See module doc for behavior. */
114
164
  async function apiFetch(path, opts = {}) {
115
165
  const { method = 'GET', body, query, auth = true } = opts;
166
+ const timeoutMs = opts.timeoutMs ?? (method === 'GET' ? exports.READ_TIMEOUT_MS : exports.WRITE_TIMEOUT_MS);
167
+ const signal = AbortSignal.timeout(timeoutMs);
116
168
  const headers = {
117
169
  'Content-Type': 'application/json',
118
170
  // REV-6: sunucu CLI surumunu bilsin — eski CLI + degismis API semasi
@@ -128,9 +180,13 @@ async function apiFetch(path, opts = {}) {
128
180
  method,
129
181
  headers,
130
182
  body: body === undefined ? undefined : JSON.stringify(body),
183
+ // Süre başlıkla sınırlı değil: gövde okuması da aynı sinyalle kesilir.
184
+ signal,
131
185
  });
132
186
  }
133
187
  catch (err) {
188
+ if (isTimeout(err, signal))
189
+ throw new RequestTimeoutError(timeoutMs, method);
134
190
  throw new Error(`Cannot reach ${constants_1.API_BASE_URL}. Check your connection. (${err instanceof Error ? err.message : String(err)})`);
135
191
  }
136
192
  // Reactive refresh: expired/invalid access token → refresh once, retry once.
@@ -147,7 +203,15 @@ async function apiFetch(path, opts = {}) {
147
203
  if (!res.ok) {
148
204
  throw await toError(res);
149
205
  }
150
- return (await res.json());
206
+ try {
207
+ return (await res.json());
208
+ }
209
+ catch (err) {
210
+ // Başlıklar geldi, gövde yarıda kaldı ve süre doldu.
211
+ if (isTimeout(err, signal))
212
+ throw new RequestTimeoutError(timeoutMs, method);
213
+ throw err;
214
+ }
151
215
  }
152
216
  // ---------------------------------------------------------------------------
153
217
  // Public surface used by commands / the resolver
@@ -195,19 +259,48 @@ async function listPrompts(params = {}) {
195
259
  * the caller batches and reports whatever came back rather than assuming
196
260
  * everything landed.
197
261
  */
198
- async function importPrompts(prompts) {
262
+ async function importPrompts(prompts, options = {}) {
199
263
  const res = await apiFetch('/api/prompts/import', {
200
264
  method: 'POST',
201
- body: { prompts },
265
+ body: { prompts, ...options },
266
+ timeoutMs: exports.IMPORT_TIMEOUT_MS,
202
267
  });
203
268
  return {
204
269
  imported: res.imported ?? 0,
205
270
  failed: res.failed ?? 0,
206
271
  skippedInvalid: res.skippedInvalid ?? 0,
207
272
  truncatedByQuota: res.truncatedByQuota ?? 0,
273
+ skippedDuplicate: res.skippedDuplicate ?? 0,
274
+ projectId: res.projectId,
208
275
  tagsApplied: res.tagsApplied,
209
276
  };
210
277
  }
278
+ /**
279
+ * GET /api/prompts/import — sha256 of everything already brought in with
280
+ * `ple import --scan`. Older servers (no GET handler) → empty set, so the
281
+ * preview just cannot mark "already imported"; the POST still dedupes.
282
+ */
283
+ async function getImportedHashes() {
284
+ try {
285
+ const res = await apiFetch('/api/prompts/import');
286
+ return new Set(res.knownHashes ?? []);
287
+ }
288
+ catch {
289
+ return new Set();
290
+ }
291
+ }
292
+ async function getAccountHeadroom() {
293
+ try {
294
+ const res = await apiFetch('/api/account/limits');
295
+ return {
296
+ promptsRemaining: res.usage?.promptsRemaining ?? null,
297
+ isPro: res.plan?.isPro === true,
298
+ };
299
+ }
300
+ catch {
301
+ return { promptsRemaining: null, isPro: false };
302
+ }
303
+ }
211
304
  /** GET /api/projects — list the user's accessible repos (for --project resolution). */
212
305
  async function listProjects() {
213
306
  const res = await apiFetch('/api/projects', {
@@ -227,14 +320,66 @@ async function getPromptById(id) {
227
320
  throw err;
228
321
  }
229
322
  }
323
+ /** GET /api/prompts/{id} → history for `ple log/diff/rollback`. */
324
+ async function getPromptHistory(id) {
325
+ const res = await apiFetch(`/api/prompts/${id}`);
326
+ if (!res.prompt)
327
+ throw new Error('Prompt not found.');
328
+ return {
329
+ id: res.prompt.id,
330
+ title: res.prompt.title,
331
+ current_version_id: res.prompt.current_version_id ?? null,
332
+ versions: Array.isArray(res.prompt.versions) ? res.prompt.versions : [],
333
+ };
334
+ }
335
+ /**
336
+ * POST /api/prompts/{id}/rollback — restores a version as a NEW version
337
+ * (nothing is deleted; the history keeps growing).
338
+ */
339
+ async function rollbackPrompt(id, versionId) {
340
+ return apiFetch(`/api/prompts/${id}/rollback`, {
341
+ method: 'POST',
342
+ body: { versionId },
343
+ });
344
+ }
345
+ /** Kullanım yüzeyleri — sunucudaki `USE_SURFACES` ile aynı küme (W1-1). */
346
+ exports.USE_SURFACES = [
347
+ 'web', 'cli', 'mcp_tool', 'mcp_prompt', 'mcp_resource', 'extension', 'hook', 'repo', 'api', 'unknown',
348
+ ];
349
+ /**
350
+ * Build the use-event body. `PLE_SURFACE` / `PLE_VIA` let a wrapper (e.g. an
351
+ * agent hook calling `ple get`) attribute the use correctly; unknown values
352
+ * fall back to the CLI defaults rather than failing the command.
353
+ */
354
+ function buildUseEventBody(opts = {}, env = process.env) {
355
+ const envSurface = env.PLE_SURFACE?.trim().toLowerCase();
356
+ const surface = exports.USE_SURFACES.includes(envSurface ?? '')
357
+ ? envSurface
358
+ : 'cli';
359
+ const via = env.PLE_VIA?.trim().toLowerCase() === 'suggestion' ? 'suggestion' : 'direct';
360
+ const body = { surface, client: `ple-cli/${constants_1.CLI_VERSION}`, via };
361
+ if (typeof opts.version === 'number' && Number.isInteger(opts.version) && opts.version > 0) {
362
+ body.version = opts.version;
363
+ }
364
+ return body;
365
+ }
230
366
  /**
231
- * Kullanım kaydı (REV-6) — `ple copy/get/show` sonrası fire-and-forget.
232
- * Most Used + ⌘K sıralaması eskiden yalnız web kopyalarını sayıyordu; ana
233
- * reuse yüzeyi terminal olduğundan metrik köreliyordu. Hata YUTULUR:
234
- * telemetri asıl komutu asla kırmaz.
367
+ * Kullanım kaydı (REV-6 → W1-1) — `ple copy/get/show` sonrası fire-and-forget.
368
+ * Gövde yüzeyi (`surface: 'cli'`) ve istemciyi taşır; sunucu olay defterine
369
+ * yazar (defter yoksa eski sayaca düşer). Hata YUTULUR: telemetri asıl
370
+ * komutu asla kırmaz.
235
371
  */
236
- function recordPromptUse(promptId) {
237
- apiFetch(`/api/prompts/${promptId}/use`, { method: 'POST' }).catch(() => {
372
+ function recordPromptUse(promptId, opts = {}) {
373
+ apiFetch(`/api/prompts/${promptId}/use`, {
374
+ method: 'POST',
375
+ body: buildUseEventBody(opts),
376
+ timeoutMs: exports.USE_EVENT_TIMEOUT_MS,
377
+ }).catch(() => {
238
378
  /* sessiz — telemetri */
239
379
  });
240
380
  }
381
+ /** GET /api/insights?range= — usage summary for `ple stats`. */
382
+ async function getUsageInsights(range) {
383
+ const res = await apiFetch('/api/insights', { query: { range } });
384
+ return res.insights ?? null;
385
+ }
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ /**
3
+ * Line-based unified diff for `ple diff` (W1-4). No dependency (the CLI is
4
+ * commander + chalk only): Myers' O((N+M)·D) shortest-edit-script, then
5
+ * hunks with N lines of context — the same shape `git diff` prints, so it
6
+ * pipes into `delta`, `less -R` or a patch reviewer unchanged.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.splitLines = splitLines;
10
+ exports.diffLines = diffLines;
11
+ exports.unifiedDiff = unifiedDiff;
12
+ /** Split into lines; a trailing newline does not create an empty last line. */
13
+ function splitLines(text) {
14
+ const normalized = text.replace(/\r\n/g, '\n');
15
+ if (normalized === '')
16
+ return [];
17
+ const lines = normalized.split('\n');
18
+ if (lines[lines.length - 1] === '')
19
+ lines.pop();
20
+ return lines;
21
+ }
22
+ /** Myers diff → ordered edit script. */
23
+ function diffLines(a, b) {
24
+ const n = a.length;
25
+ const m = b.length;
26
+ const max = n + m;
27
+ const offset = max;
28
+ const v = new Int32Array(2 * max + 2);
29
+ const trace = [];
30
+ let found = false;
31
+ for (let d = 0; d <= max && !found; d++) {
32
+ trace.push(v.slice());
33
+ for (let k = -d; k <= d; k += 2) {
34
+ let x;
35
+ if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) {
36
+ x = v[offset + k + 1]; // down (insertion)
37
+ }
38
+ else {
39
+ x = v[offset + k - 1] + 1; // right (deletion)
40
+ }
41
+ let y = x - k;
42
+ while (x < n && y < m && a[x] === b[y]) {
43
+ x++;
44
+ y++;
45
+ }
46
+ v[offset + k] = x;
47
+ if (x >= n && y >= m) {
48
+ found = true;
49
+ break;
50
+ }
51
+ }
52
+ }
53
+ trace.push(v.slice());
54
+ // Backtrack from (n, m) through the saved frontiers.
55
+ const ops = [];
56
+ let x = n;
57
+ let y = m;
58
+ for (let d = trace.length - 2; d >= 0 && (x > 0 || y > 0); d--) {
59
+ const vd = trace[d];
60
+ const k = x - y;
61
+ let prevK;
62
+ if (k === -d || (k !== d && vd[offset + k - 1] < vd[offset + k + 1])) {
63
+ prevK = k + 1;
64
+ }
65
+ else {
66
+ prevK = k - 1;
67
+ }
68
+ const prevX = vd[offset + prevK];
69
+ const prevY = prevX - prevK;
70
+ while (x > prevX && y > prevY) {
71
+ ops.push({ type: 'equal', line: a[x - 1] });
72
+ x--;
73
+ y--;
74
+ }
75
+ if (d === 0)
76
+ break;
77
+ if (x === prevX) {
78
+ ops.push({ type: 'add', line: b[y - 1] });
79
+ }
80
+ else {
81
+ ops.push({ type: 'del', line: a[x - 1] });
82
+ }
83
+ x = prevX;
84
+ y = prevY;
85
+ }
86
+ while (x > 0 && y > 0) {
87
+ ops.push({ type: 'equal', line: a[x - 1] });
88
+ x--;
89
+ y--;
90
+ }
91
+ return ops.reverse();
92
+ }
93
+ /**
94
+ * Render a unified diff. Returns [] when the texts are identical so the
95
+ * caller can print its own "no changes" message.
96
+ */
97
+ function unifiedDiff(from, to, opts) {
98
+ const a = splitLines(from);
99
+ const b = splitLines(to);
100
+ const ops = diffLines(a, b);
101
+ if (ops.every((o) => o.type === 'equal'))
102
+ return [];
103
+ const ctx = opts.context ?? 3;
104
+ const id = (s) => s;
105
+ const col = opts.colors ?? { header: id, hunk: id, add: id, del: id };
106
+ // Indices of changed ops; group into hunks whose context windows touch.
107
+ const changed = ops.map((o, i) => (o.type === 'equal' ? -1 : i)).filter((i) => i >= 0);
108
+ const groups = [];
109
+ for (const i of changed) {
110
+ const start = Math.max(0, i - ctx);
111
+ const end = Math.min(ops.length - 1, i + ctx);
112
+ const last = groups[groups.length - 1];
113
+ if (last && start <= last[1] + 1)
114
+ last[1] = end;
115
+ else
116
+ groups.push([start, end]);
117
+ }
118
+ // Line numbers before each op.
119
+ const aLineAt = [];
120
+ const bLineAt = [];
121
+ let ai = 1;
122
+ let bi = 1;
123
+ for (const o of ops) {
124
+ aLineAt.push(ai);
125
+ bLineAt.push(bi);
126
+ if (o.type !== 'add')
127
+ ai++;
128
+ if (o.type !== 'del')
129
+ bi++;
130
+ }
131
+ const out = [col.header(`--- ${opts.fromLabel}`), col.header(`+++ ${opts.toLabel}`)];
132
+ for (const [start, end] of groups) {
133
+ const slice = ops.slice(start, end + 1);
134
+ const aCount = slice.filter((o) => o.type !== 'add').length;
135
+ const bCount = slice.filter((o) => o.type !== 'del').length;
136
+ const aStart = aCount === 0 ? aLineAt[start] - 1 : aLineAt[start];
137
+ const bStart = bCount === 0 ? bLineAt[start] - 1 : bLineAt[start];
138
+ out.push(col.hunk(`@@ -${aStart},${aCount} +${bStart},${bCount} @@`));
139
+ for (const o of slice) {
140
+ if (o.type === 'equal')
141
+ out.push(` ${o.line}`);
142
+ else if (o.type === 'del')
143
+ out.push(col.del(`-${o.line}`));
144
+ else
145
+ out.push(col.add(`+${o.line}`));
146
+ }
147
+ }
148
+ return out;
149
+ }
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ /**
3
+ * Minimal YAML-frontmatter reader for agent files (commands, SKILL.md,
4
+ * `.prompt.md`). Not a YAML parser — agent frontmatter is flat `key: value`
5
+ * lines plus the occasional list (`tags: [a, b]` or `- item` lines), and a
6
+ * full YAML dependency is off-limits for this CLI (commander + chalk only).
7
+ *
8
+ * Anything it cannot understand stays a raw string; nothing throws.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.parseFrontmatter = parseFrontmatter;
12
+ function unquote(v) {
13
+ const t = v.trim();
14
+ if ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'"))) {
15
+ return t.slice(1, -1);
16
+ }
17
+ return t;
18
+ }
19
+ function parseFrontmatter(raw) {
20
+ const text = raw.replace(/^/, '').replace(/\r\n/g, '\n');
21
+ const empty = { fields: {}, lists: {}, body: text };
22
+ if (!text.startsWith('---\n'))
23
+ return empty;
24
+ const end = text.indexOf('\n---', 3);
25
+ if (end === -1)
26
+ return empty;
27
+ const header = text.slice(4, end);
28
+ const afterClose = text.slice(end + 4);
29
+ const body = afterClose.replace(/^[^\n]*\n?/, ''); // rest of the closing line
30
+ const fields = {};
31
+ const lists = {};
32
+ let currentListKey = null;
33
+ for (const line of header.split('\n')) {
34
+ const item = line.match(/^\s+-\s+(.*)$/) ?? line.match(/^-\s+(.*)$/);
35
+ if (item && currentListKey) {
36
+ lists[currentListKey].push(unquote(item[1]));
37
+ fields[currentListKey] = lists[currentListKey].join(', ');
38
+ continue;
39
+ }
40
+ const kv = line.match(/^([A-Za-z0-9_-]+):[ \t]*(.*)$/);
41
+ if (!kv) {
42
+ currentListKey = null;
43
+ continue;
44
+ }
45
+ const key = kv[1].toLowerCase();
46
+ const value = kv[2].trim();
47
+ if (value === '') {
48
+ currentListKey = key;
49
+ lists[key] = [];
50
+ fields[key] = '';
51
+ continue;
52
+ }
53
+ currentListKey = null;
54
+ if (value.startsWith('[') && value.endsWith(']')) {
55
+ lists[key] = value
56
+ .slice(1, -1)
57
+ .split(',')
58
+ .map((s) => unquote(s))
59
+ .filter(Boolean);
60
+ fields[key] = lists[key].join(', ');
61
+ }
62
+ else {
63
+ fields[key] = unquote(value);
64
+ }
65
+ }
66
+ return { fields, lists, body };
67
+ }
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ /**
3
+ * Local library cache for suggestions (W1-5) —
4
+ * `~/.config/promptlike/cache/library.json`.
5
+ *
6
+ * Why a cache: the Claude Code `UserPromptSubmit` hook runs before EVERY
7
+ * message and blocks it until it exits, so matching must be local and fast.
8
+ * The user's text never leaves the machine; the cache is refreshed from the
9
+ * account by `ple list` / `ple sync` / `ple suggest`, and in the background
10
+ * (detached, never awaited by the hook) once it is older than 10 minutes.
11
+ *
12
+ * Signed out, suggestions come straight from the local store (`~/.promptlike`)
13
+ * — no cache and no network at all.
14
+ *
15
+ * Also here: per-session "already suggested" memory (the hook never repeats a
16
+ * prompt within one Claude Code session) and the local impression counter
17
+ * `ple stats` shows (impressions stay on this machine; only an accepted
18
+ * suggestion reaches the server, as a `via=suggestion` use).
19
+ */
20
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ var desc = Object.getOwnPropertyDescriptor(m, k);
23
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
+ desc = { enumerable: true, get: function() { return m[k]; } };
25
+ }
26
+ Object.defineProperty(o, k2, desc);
27
+ }) : (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ o[k2] = m[k];
30
+ }));
31
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
33
+ }) : function(o, v) {
34
+ o["default"] = v;
35
+ });
36
+ var __importStar = (this && this.__importStar) || (function () {
37
+ var ownKeys = function(o) {
38
+ ownKeys = Object.getOwnPropertyNames || function (o) {
39
+ var ar = [];
40
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41
+ return ar;
42
+ };
43
+ return ownKeys(o);
44
+ };
45
+ return function (mod) {
46
+ if (mod && mod.__esModule) return mod;
47
+ var result = {};
48
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
49
+ __setModuleDefault(result, mod);
50
+ return result;
51
+ };
52
+ })();
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.CACHE_TTL_MS = void 0;
55
+ exports.cacheDir = cacheDir;
56
+ exports.readCache = readCache;
57
+ exports.isFresh = isFresh;
58
+ exports.entriesFromAccount = entriesFromAccount;
59
+ exports.entriesFromLocal = entriesFromLocal;
60
+ exports.writeCache = writeCache;
61
+ exports.fetchAccountEntries = fetchAccountEntries;
62
+ exports.startBackgroundRefresh = startBackgroundRefresh;
63
+ exports.readState = readState;
64
+ exports.shownIn = shownIn;
65
+ exports.recordShown = recordShown;
66
+ const child_process_1 = require("child_process");
67
+ const fs = __importStar(require("fs"));
68
+ const path = __importStar(require("path"));
69
+ const format_1 = require("./format");
70
+ const rank_1 = require("./rank");
71
+ const settings_1 = require("./settings");
72
+ exports.CACHE_TTL_MS = 10 * 60 * 1000;
73
+ /** Background refreshes are at most one per minute (lock file mtime). */
74
+ const REFRESH_LOCK_MS = 60 * 1000;
75
+ const MAX_SESSIONS = 20;
76
+ /** Library pages fetched for the cache: 5 × 100 = 500 prompts. */
77
+ const MAX_PAGES = 5;
78
+ const PAGE_SIZE = 100;
79
+ function cacheDir() {
80
+ return path.join((0, settings_1.configDir)(), 'cache');
81
+ }
82
+ function cacheFile() {
83
+ return path.join(cacheDir(), 'library.json');
84
+ }
85
+ function writePrivate(file, data) {
86
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
87
+ // Write-then-rename: a hook reading mid-write never sees half a file.
88
+ const tmp = `${file}.${process.pid}.tmp`;
89
+ fs.writeFileSync(tmp, JSON.stringify(data), { mode: 0o600 });
90
+ fs.renameSync(tmp, file);
91
+ }
92
+ /** Cached library for `userId`, or null (missing, corrupt, or another account's). */
93
+ function readCache(userId) {
94
+ try {
95
+ const raw = JSON.parse(fs.readFileSync(cacheFile(), 'utf-8'));
96
+ if (raw.v !== 1 || raw.user_id !== userId || !Array.isArray(raw.entries))
97
+ return null;
98
+ return raw;
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ function isFresh(cache, now = Date.now()) {
105
+ return now - cache.fetched_at < exports.CACHE_TTL_MS;
106
+ }
107
+ function entriesFromAccount(prompts) {
108
+ return prompts.map((p) => ({
109
+ id: p.id,
110
+ name: p.title,
111
+ title: p.title,
112
+ description: p.description ?? null,
113
+ tags: (p.tags ?? []).map((t) => t.name).filter(Boolean),
114
+ body: (0, format_1.joinPromptParts)(p.current_version ?? {}).slice(0, rank_1.BODY_HEAD),
115
+ uses: typeof p.use_count === 'number' ? p.use_count : null,
116
+ repo: p.project_name ?? null,
117
+ }));
118
+ }
119
+ function entriesFromLocal(prompts) {
120
+ return prompts.map((p) => ({
121
+ id: p.slug,
122
+ name: p.slug,
123
+ title: p.title,
124
+ description: p.description || null,
125
+ tags: p.tags,
126
+ body: p.body.slice(0, rank_1.BODY_HEAD),
127
+ uses: null,
128
+ }));
129
+ }
130
+ /** Store a fresh account snapshot. */
131
+ function writeCache(userId, entries, now = Date.now()) {
132
+ const cache = { v: 1, source: 'account', user_id: userId, fetched_at: now, entries };
133
+ writePrivate(cacheFile(), cache);
134
+ return cache;
135
+ }
136
+ /** Fetch the whole library (≤500) page by page. */
137
+ async function fetchAccountEntries(list) {
138
+ const all = [];
139
+ for (let page = 1; page <= MAX_PAGES; page++) {
140
+ const rows = await list({ limit: PAGE_SIZE, page });
141
+ all.push(...rows);
142
+ if (rows.length < PAGE_SIZE)
143
+ break;
144
+ }
145
+ return entriesFromAccount(all);
146
+ }
147
+ const defaultSpawner = (execPath, args) => {
148
+ const child = (0, child_process_1.spawn)(execPath, args, { detached: true, stdio: 'ignore' });
149
+ child.on('error', () => undefined);
150
+ child.unref();
151
+ };
152
+ /**
153
+ * Kick off `ple suggest --refresh-cache` detached (never awaited). At most
154
+ * one per minute unless forced, so a burst of messages does not fork a burst
155
+ * of refreshes. Returns true when a refresh was started.
156
+ */
157
+ function startBackgroundRefresh(opts = {}) {
158
+ const now = opts.now ?? Date.now();
159
+ const script = process.argv[1];
160
+ if (!script)
161
+ return false;
162
+ const lock = path.join(cacheDir(), 'refresh.lock');
163
+ if (!opts.force) {
164
+ try {
165
+ const age = now - fs.statSync(lock).mtimeMs;
166
+ if (age >= 0 && age < REFRESH_LOCK_MS)
167
+ return false;
168
+ }
169
+ catch {
170
+ // no lock yet
171
+ }
172
+ }
173
+ try {
174
+ fs.mkdirSync(cacheDir(), { recursive: true, mode: 0o700 });
175
+ fs.writeFileSync(lock, String(now), { mode: 0o600 });
176
+ (opts.spawner ?? defaultSpawner)(process.execPath, [script, 'suggest', '--refresh-cache']);
177
+ return true;
178
+ }
179
+ catch {
180
+ return false;
181
+ }
182
+ }
183
+ function stateFile() {
184
+ return path.join(cacheDir(), 'suggest-state.json');
185
+ }
186
+ function readState() {
187
+ try {
188
+ const raw = JSON.parse(fs.readFileSync(stateFile(), 'utf-8'));
189
+ return {
190
+ impressions: typeof raw.impressions === 'number' && raw.impressions >= 0 ? raw.impressions : 0,
191
+ sessions: raw.sessions && typeof raw.sessions === 'object' ? raw.sessions : {},
192
+ };
193
+ }
194
+ catch {
195
+ return { impressions: 0, sessions: {} };
196
+ }
197
+ }
198
+ /** Ids already suggested in this session. */
199
+ function shownIn(state, sessionId) {
200
+ if (!sessionId)
201
+ return new Set();
202
+ return new Set(state.sessions[sessionId]?.shown ?? []);
203
+ }
204
+ /** Record that `ids` were shown: bump the counter, remember them for the session, keep 20 sessions. */
205
+ function recordShown(state, sessionId, ids, now = Date.now()) {
206
+ const sessions = { ...state.sessions };
207
+ if (sessionId) {
208
+ const prev = sessions[sessionId]?.shown ?? [];
209
+ sessions[sessionId] = { at: now, shown: [...new Set([...prev, ...ids])] };
210
+ }
211
+ const kept = Object.entries(sessions)
212
+ .sort((a, b) => b[1].at - a[1].at)
213
+ .slice(0, MAX_SESSIONS);
214
+ const next = { impressions: state.impressions + ids.length, sessions: Object.fromEntries(kept) };
215
+ try {
216
+ writePrivate(stateFile(), next);
217
+ }
218
+ catch {
219
+ // a read-only home must not break the hook
220
+ }
221
+ return next;
222
+ }