opencode-prompt-logger 0.1.0 → 0.2.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/dist/index.js CHANGED
@@ -1,13 +1,64 @@
1
1
  // @bun
2
2
  // src/index.ts
3
+ import { statSync as statSync3 } from "fs";
3
4
  import { Plugin } from "@opencode/plugin";
4
5
 
5
6
  // src/core.ts
6
- import { appendFileSync, mkdirSync, renameSync, statSync } from "fs";
7
+ var DEFAULT_DISK_BUDGET = 256 * 1024 * 1024;
8
+ var CONTEXT_KINDS = ["context", "compaction", "generate", "title"];
9
+
10
+ // src/log/limits.ts
11
+ var DEFAULT_PAGE = 50;
12
+ var MAX_PAGE = 200;
13
+ var MAX_RECORD_BYTES = 2 * 1024 * 1024;
14
+ var MAX_FULL_RECORD_BYTES = 16 * 1024 * 1024;
15
+ var MAX_SEARCH_BYTES = 128 * 1024 * 1024;
16
+ var MAX_SEARCH_MS = 2000;
17
+ var MAX_SEARCH_QUERY = 500;
18
+ var MAX_SEARCH_RESULTS = 100;
19
+ var EVENT_COALESCE_MS = 1000;
20
+ function clampInteger(value, min, max, fallback) {
21
+ if (typeof value !== "number" || !Number.isFinite(value))
22
+ return fallback;
23
+ return Math.min(max, Math.max(min, Math.round(value)));
24
+ }
25
+ function clampPage(value) {
26
+ return clampInteger(value, 1, MAX_PAGE, DEFAULT_PAGE);
27
+ }
28
+ function clampReadBytes(value) {
29
+ return clampInteger(value, 1024, MAX_FULL_RECORD_BYTES, MAX_RECORD_BYTES);
30
+ }
31
+ function clampSearchBytes(value) {
32
+ return clampInteger(value, 1024 * 1024, MAX_SEARCH_BYTES, MAX_SEARCH_BYTES);
33
+ }
34
+ function clampSearchMs(value) {
35
+ return clampInteger(value, 100, MAX_SEARCH_MS, MAX_SEARCH_MS);
36
+ }
37
+ function boundedString(value, maxLength) {
38
+ if (typeof value !== "string")
39
+ return;
40
+ const trimmed = value.trim();
41
+ if (trimmed === "")
42
+ return;
43
+ return trimmed.length > maxLength ? trimmed.slice(0, maxLength) : trimmed;
44
+ }
45
+
46
+ // src/log/errors.ts
47
+ class LogError extends Error {
48
+ code;
49
+ constructor(code, message) {
50
+ super(message);
51
+ this.name = "LogError";
52
+ this.code = code;
53
+ }
54
+ }
55
+
56
+ // src/log/paths.ts
57
+ import { chmodSync, lstatSync, statSync } from "fs";
7
58
  import { homedir } from "os";
8
- import { dirname, join } from "path";
9
- function defaultFile(env = process.env, platform = process.platform) {
10
- const name = join("opencode", "prompts.ndjson");
59
+ import { dirname, isAbsolute, join, resolve } from "path";
60
+ function defaultDir(env = process.env, platform = process.platform) {
61
+ const name = join("opencode", "prompt-logger");
11
62
  if (platform === "win32") {
12
63
  return join(env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local"), name);
13
64
  }
@@ -16,106 +67,2266 @@ function defaultFile(env = process.env, platform = process.platform) {
16
67
  }
17
68
  return join(env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), name);
18
69
  }
19
- var DEFAULT_ROTATE_BYTES = 256 * 1024 * 1024;
20
- var CONTEXT_KINDS = ["context", "compaction", "generate", "title"];
21
- function resolveFile(options) {
22
- return options.file ?? defaultFile();
70
+ function expandHome(path, home = homedir()) {
71
+ if (path === "~")
72
+ return home;
73
+ if (path.startsWith("~/") || path.startsWith("~\\"))
74
+ return join(home, path.slice(2));
75
+ return path;
23
76
  }
24
- function isEnabled(options) {
25
- return options.enabled !== false;
77
+ function resolveLogDirectory(configured, base, env = process.env, platform = process.platform) {
78
+ if (configured === undefined || configured === "")
79
+ return resolve(defaultDir(env, platform));
80
+ const expanded = expandHome(configured);
81
+ return isAbsolute(expanded) ? resolve(expanded) : resolve(base ?? process.cwd(), expanded);
26
82
  }
27
- function shouldLogHttp(options) {
28
- return options.http !== false;
83
+ var POSIX = process.platform !== "win32";
84
+ function hardenDirectory(dir) {
85
+ if (!POSIX)
86
+ return;
87
+ try {
88
+ chmodSync(dir, 448);
89
+ } catch {}
29
90
  }
30
- function resolveRotateBytes(options) {
31
- const value = options.rotateBytes;
32
- if (value === false)
33
- return 0;
34
- if (value === undefined)
35
- return DEFAULT_ROTATE_BYTES;
36
- return value > 0 ? Math.floor(value) : 0;
91
+ function hardenFile(file) {
92
+ if (!POSIX)
93
+ return;
94
+ try {
95
+ if (statSync(file).isFile())
96
+ chmodSync(file, 384);
97
+ } catch {}
37
98
  }
38
- function existingSize(file) {
99
+ function inspectPath(file) {
100
+ let stats;
39
101
  try {
40
- return statSync(file).size;
102
+ stats = statSync(file);
41
103
  } catch {
42
- return 0;
104
+ return {
105
+ exists: false,
106
+ regular: false,
107
+ symlink: false,
108
+ mode: null,
109
+ directoryMode: null
110
+ };
43
111
  }
112
+ let symlink = false;
113
+ try {
114
+ symlink = lstatSync(file).isSymbolicLink();
115
+ } catch {}
116
+ let directoryMode = null;
117
+ try {
118
+ directoryMode = statSync(dirname(file)).mode & 511;
119
+ } catch {}
120
+ return {
121
+ exists: true,
122
+ regular: stats.isFile(),
123
+ symlink,
124
+ mode: stats.mode & 511,
125
+ directoryMode
126
+ };
44
127
  }
45
- function createWriter(file, rotateBytes = DEFAULT_ROTATE_BYTES) {
46
- mkdirSync(dirname(file), { recursive: true, mode: 448 });
47
- const backup = `${file}.1`;
48
- return (record) => {
49
- try {
50
- const line = JSON.stringify({ at: new Date().toISOString(), ...record }) + `
128
+
129
+ // src/log/v2.ts
130
+ import { createHash as createHash2, randomUUID } from "crypto";
131
+ import {
132
+ appendFileSync,
133
+ closeSync,
134
+ existsSync,
135
+ mkdirSync,
136
+ openSync,
137
+ readFileSync,
138
+ readdirSync,
139
+ readSync,
140
+ renameSync,
141
+ rmSync,
142
+ statSync as statSync2,
143
+ writeFileSync
144
+ } from "fs";
145
+ import { join as join2 } from "path";
146
+
147
+ // src/log/body.ts
148
+ import { createHash } from "crypto";
149
+ import { brotliDecompressSync, gunzipSync, inflateSync } from "zlib";
150
+ var MAX_BODY_BYTES = 32 * 1024 * 1024;
151
+ var MAX_DECODED_BYTES = 64 * 1024 * 1024;
152
+ function hasMagic(bytes, magic) {
153
+ if (bytes.length < magic.length)
154
+ return false;
155
+ for (let index = 0;index < magic.length; index += 1) {
156
+ if (bytes[index] !== magic[index])
157
+ return false;
158
+ }
159
+ return true;
160
+ }
161
+ function normalizeEncoding(header, bytes) {
162
+ const value = header?.toLowerCase().trim();
163
+ if (hasMagic(bytes, [31, 139]))
164
+ return "gzip";
165
+ if (hasMagic(bytes, [40, 181, 47, 253]))
166
+ return "zstd";
167
+ if (value === "gzip" || value === "x-gzip")
168
+ return "gzip";
169
+ if (value === "deflate")
170
+ return "deflate";
171
+ if (value === "br" || value === "brotli")
172
+ return "br";
173
+ if (value === "zstd")
174
+ return "zstd";
175
+ if (value === "identity" || value === undefined || value === "")
176
+ return "identity";
177
+ return "unknown";
178
+ }
179
+ function zstdDecompress(bytes) {
180
+ const bun = globalThis;
181
+ const decompress = bun.Bun?.zstdDecompressSync;
182
+ if (decompress === undefined)
183
+ return null;
184
+ return Buffer.from(decompress(bytes));
185
+ }
186
+ function decompress(bytes, encoding) {
187
+ const options = { maxOutputLength: MAX_DECODED_BYTES };
188
+ switch (encoding) {
189
+ case "identity":
190
+ return bytes;
191
+ case "gzip":
192
+ return gunzipSync(bytes, options);
193
+ case "deflate":
194
+ return inflateSync(bytes, options);
195
+ case "br":
196
+ return brotliDecompressSync(bytes, options);
197
+ case "zstd":
198
+ return zstdDecompress(bytes);
199
+ default:
200
+ return null;
201
+ }
202
+ }
203
+ function decodeUtf8(bytes) {
204
+ try {
205
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
206
+ } catch {
207
+ return null;
208
+ }
209
+ }
210
+ function decodeStoredBody(bytes, encoding) {
211
+ let decoded = null;
212
+ try {
213
+ decoded = decompress(bytes, encoding);
214
+ } catch {
215
+ decoded = null;
216
+ }
217
+ if (decoded === null) {
218
+ return { text: null, base64: bytes.toString("base64"), decodedBytes: null };
219
+ }
220
+ const text = decodeUtf8(decoded);
221
+ return {
222
+ text,
223
+ base64: text === null ? decoded.toString("base64") : null,
224
+ decodedBytes: decoded.length
225
+ };
226
+ }
227
+ function sliceUtf8(text, maxBytes) {
228
+ if (maxBytes <= 0)
229
+ return "";
230
+ const bytes = Buffer.from(text, "utf8");
231
+ if (bytes.length <= maxBytes)
232
+ return text;
233
+ let end = maxBytes;
234
+ while (end > 0 && (bytes[end] & 192) === 128)
235
+ end -= 1;
236
+ return bytes.subarray(0, end).toString("utf8");
237
+ }
238
+ async function captureBodyBytes(request) {
239
+ let complete;
240
+ try {
241
+ const clone = request.clone();
242
+ if (typeof clone.arrayBuffer === "function") {
243
+ complete = Buffer.from(await clone.arrayBuffer());
244
+ } else {
245
+ complete = Buffer.from(await clone.text(), "utf8");
246
+ }
247
+ } catch (error) {
248
+ throw new Error(`unreadable request body: ${error instanceof Error ? error.message : String(error)}`);
249
+ }
250
+ const encoding = normalizeEncoding(request.headers.get("content-encoding"), complete);
251
+ const truncated = complete.length > MAX_BODY_BYTES;
252
+ const bytes = truncated ? complete.subarray(0, MAX_BODY_BYTES) : complete;
253
+ const hash = createHash("sha256").update(complete).digest("hex");
254
+ return {
255
+ bytes,
256
+ encoding,
257
+ contentType: request.headers.get("content-type"),
258
+ bodyBytes: complete.length,
259
+ truncated,
260
+ hash
261
+ };
262
+ }
263
+
264
+ // src/log/summary.ts
265
+ function modelRef(value) {
266
+ if (value === null || typeof value !== "object")
267
+ return null;
268
+ const record = value;
269
+ const model = {};
270
+ if (typeof record.providerID === "string")
271
+ model.providerID = record.providerID;
272
+ if (typeof record.id === "string")
273
+ model.id = record.id;
274
+ if (typeof record.variant === "string")
275
+ model.variant = record.variant;
276
+ return Object.keys(model).length === 0 ? null : model;
277
+ }
278
+
279
+ // src/log/v2.ts
280
+ var V2 = 2;
281
+ var SESSION_DIR = "sessions";
282
+ var MESSAGES_FILE = "messages.ndjson";
283
+ var SYSTEMS_FILE = "systems.ndjson";
284
+ var REQUESTS_FILE = "requests.ndjson";
285
+ var BODIES_DIR = "bodies";
286
+ function resolveRetention(settings) {
287
+ return {
288
+ maxTotalBytes: settings.diskBudget > 0 ? settings.diskBudget : Number.POSITIVE_INFINITY,
289
+ maxAgeDays: settings.retentionMaxAgeDays,
290
+ maxSessions: settings.retentionMaxSessions > 0 ? settings.retentionMaxSessions : Number.POSITIVE_INFINITY
291
+ };
292
+ }
293
+ var caches = new Map;
294
+ var readCaches = new Map;
295
+ var searchCaches = new Map;
296
+ var armedV2 = new Set;
297
+ function armV2(root) {
298
+ armedV2.add(root);
299
+ }
300
+ function isV2Armed(root) {
301
+ return armedV2.has(root);
302
+ }
303
+ function disarmV2(root) {
304
+ armedV2.delete(root);
305
+ }
306
+ var MAX_READ_CACHES = 8;
307
+ var MAX_READ_CACHE_BYTES = 64 * 1024 * 1024;
308
+ var MAX_SESSION_MAP_BYTES = 64 * 1024 * 1024;
309
+ var STREAM_CHUNK_BYTES = 1024 * 1024;
310
+ function sha256(value) {
311
+ return createHash2("sha256").update(value).digest("hex");
312
+ }
313
+ function safeDirName(sessionID) {
314
+ const safe = sessionID.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80);
315
+ const suffix = sha256(sessionID).slice(0, 16);
316
+ return `${safe === "" || safe === "." || safe === ".." ? "session" : safe}-${suffix}`;
317
+ }
318
+ function sessionsRoot(root) {
319
+ return join2(root, SESSION_DIR);
320
+ }
321
+ function sessionDir(root, sessionDirName) {
322
+ return join2(sessionsRoot(root), sessionDirName);
323
+ }
324
+ function line(value) {
325
+ return `${JSON.stringify(value)}
51
326
  `;
52
- const size = Buffer.byteLength(line, "utf8");
53
- const current = existingSize(file);
54
- if (rotateBytes > 0 && current > 0 && current + size > rotateBytes) {
55
- try {
56
- renameSync(file, backup);
57
- } catch (error) {
58
- console.error(`prompt-logger: rotation failed: ${String(error)}`);
327
+ }
328
+ function hashSet(file) {
329
+ try {
330
+ const text = readFileSync(file, "utf8");
331
+ const set = new Set;
332
+ for (const entry of text.split(`
333
+ `)) {
334
+ const match = /^\{"v":2,"hash":"([^"]+)"/.exec(entry);
335
+ if (match?.[1] !== undefined)
336
+ set.add(match[1]);
337
+ }
338
+ return set;
339
+ } catch {
340
+ return new Set;
341
+ }
342
+ }
343
+ var hardenedFiles = new Set;
344
+ function appendLines(file, lines) {
345
+ if (lines.length === 0)
346
+ return;
347
+ appendFileSync(file, lines.join(`
348
+ `) + `
349
+ `, { mode: 384 });
350
+ if (!hardenedFiles.has(file)) {
351
+ hardenFile(file);
352
+ hardenedFiles.add(file);
353
+ }
354
+ }
355
+ function ensureSessionRoot(root) {
356
+ mkdirSync(root, { recursive: true, mode: 448 });
357
+ hardenDirectory(root);
358
+ const dir = sessionsRoot(root);
359
+ mkdirSync(dir, { recursive: true, mode: 448 });
360
+ hardenDirectory(dir);
361
+ return dir;
362
+ }
363
+ function ensureSessionDir(root, sessionID) {
364
+ ensureSessionRoot(root);
365
+ const dir = join2(sessionsRoot(root), safeDirName(sessionID));
366
+ mkdirSync(dir, { recursive: true, mode: 448 });
367
+ hardenDirectory(dir);
368
+ return dir;
369
+ }
370
+ var PENDING_TTL_MS = 5 * 60 * 1000;
371
+ function httpKind(kind) {
372
+ return kind === "context" ? "primary" : kind;
373
+ }
374
+ function createV2Writer(root, options = {}) {
375
+ const sessions = new Map;
376
+ const active = new Set;
377
+ const MAX_CACHED_SESSIONS = 32;
378
+ const fail = (error) => {
379
+ try {
380
+ options.onError?.(error);
381
+ } catch {}
382
+ };
383
+ const evict = () => {
384
+ if (sessions.size <= MAX_CACHED_SESSIONS)
385
+ return;
386
+ const now = Date.now();
387
+ for (const [id, writer] of sessions) {
388
+ let live = false;
389
+ for (const [kind, queue] of writer.pending) {
390
+ while (queue.length > 0 && now - queue[0].at > PENDING_TTL_MS)
391
+ queue.shift();
392
+ if (queue.length === 0)
393
+ writer.pending.delete(kind);
394
+ else
395
+ live = true;
396
+ }
397
+ if (live)
398
+ continue;
399
+ sessions.delete(id);
400
+ return;
401
+ }
402
+ };
403
+ const session = (sessionID) => {
404
+ const existing = sessions.get(sessionID);
405
+ if (existing !== undefined) {
406
+ if (!existsSync(existing.dir)) {
407
+ sessions.delete(sessionID);
408
+ } else {
409
+ sessions.delete(sessionID);
410
+ sessions.set(sessionID, existing);
411
+ return existing;
412
+ }
413
+ }
414
+ const dir = ensureSessionDir(root, sessionID);
415
+ active.add(safeDirName(sessionID));
416
+ const next = {
417
+ dir,
418
+ requestsFile: join2(dir, REQUESTS_FILE),
419
+ systemsFile: join2(dir, SYSTEMS_FILE),
420
+ messagesFile: join2(dir, MESSAGES_FILE),
421
+ bodiesDir: join2(dir, BODIES_DIR),
422
+ knownSystems: null,
423
+ knownMessages: null,
424
+ pending: new Map
425
+ };
426
+ sessions.set(sessionID, next);
427
+ evict();
428
+ return next;
429
+ };
430
+ const writeAssembled = (kind, event) => {
431
+ try {
432
+ const current = session(event.sessionID);
433
+ current.knownSystems ??= hashSet(current.systemsFile);
434
+ current.knownMessages ??= hashSet(current.messagesFile);
435
+ const systemJson = JSON.stringify(event.system ?? []);
436
+ const systemHash = sha256(systemJson);
437
+ const systemLines = [];
438
+ if (!current.knownSystems.has(systemHash)) {
439
+ systemLines.push(`{"v":2,"hash":"${systemHash}","system":${systemJson}}`);
440
+ current.knownSystems.add(systemHash);
441
+ }
442
+ const messages = Array.isArray(event.messages) ? event.messages : [];
443
+ const messageHashes = [];
444
+ const messageLines = [];
445
+ let messageBytes = 0;
446
+ for (const message of messages) {
447
+ const json = JSON.stringify(message) ?? "null";
448
+ const hash = sha256(json);
449
+ messageHashes.push(hash);
450
+ messageBytes += Buffer.byteLength(json, "utf8");
451
+ if (!current.knownMessages.has(hash)) {
452
+ messageLines.push(`{"v":2,"hash":"${hash}","message":${json}}`);
453
+ current.knownMessages.add(hash);
59
454
  }
60
455
  }
61
- appendFileSync(file, line);
456
+ const tools = event.tools === undefined ? [] : Object.keys(event.tools);
457
+ const bytes = Buffer.byteLength(systemJson, "utf8") + messageBytes + tools.reduce((total, tool) => total + Buffer.byteLength(tool, "utf8"), 0);
458
+ appendLines(current.systemsFile, systemLines);
459
+ appendLines(current.messagesFile, messageLines);
460
+ const requestID = randomUUID();
461
+ const at = new Date().toISOString();
462
+ const request = {
463
+ v: V2,
464
+ type: "assembled",
465
+ requestID,
466
+ at,
467
+ kind,
468
+ sessionID: event.sessionID,
469
+ ...typeof event.agent === "string" ? { agent: event.agent } : {},
470
+ ...event.model === undefined ? {} : { model: event.model },
471
+ systemHash,
472
+ messageHashes,
473
+ tools,
474
+ messages: messages.length,
475
+ bytes
476
+ };
477
+ appendLines(current.requestsFile, [line(request)]);
478
+ const queue = current.pending.get(httpKind(kind)) ?? [];
479
+ queue.push({ id: requestID, at: Date.now() });
480
+ if (queue.length > 16)
481
+ queue.shift();
482
+ current.pending.set(httpKind(kind), queue);
483
+ options.onWrite?.({ at });
62
484
  } catch (error) {
63
- console.error(`prompt-logger: ${String(error)}`);
485
+ fail(error);
64
486
  }
65
487
  };
488
+ const writeHttp = async (event) => {
489
+ try {
490
+ const current = session(event.sessionID);
491
+ const captured = await captureBodyBytes(event.request);
492
+ mkdirSync(current.bodiesDir, { recursive: true, mode: 448 });
493
+ hardenDirectory(current.bodiesDir);
494
+ const bodyFile = join2(current.bodiesDir, `${captured.hash}.bin`);
495
+ if (!existsSync(bodyFile)) {
496
+ const temporary = join2(current.bodiesDir, `${captured.hash}.${randomUUID()}.tmp`);
497
+ writeFileSync(temporary, captured.bytes, { mode: 384 });
498
+ renameSync(temporary, bodyFile);
499
+ hardenFile(bodyFile);
500
+ }
501
+ const queue = current.pending.get(event.kind) ?? [];
502
+ const now = Date.now();
503
+ while (queue.length > 0 && now - queue[0].at > PENDING_TTL_MS)
504
+ queue.shift();
505
+ const requestID = queue.shift()?.id ?? randomUUID();
506
+ if (queue.length === 0)
507
+ current.pending.delete(event.kind);
508
+ else
509
+ current.pending.set(event.kind, queue);
510
+ const at = new Date().toISOString();
511
+ const request = {
512
+ v: V2,
513
+ type: "http",
514
+ requestID,
515
+ at,
516
+ kind: event.kind,
517
+ sessionID: event.sessionID,
518
+ ...typeof event.agent === "string" ? { agent: event.agent } : {},
519
+ ...event.model === undefined ? {} : { model: event.model },
520
+ url: event.request.url,
521
+ bodyHash: captured.hash,
522
+ bodyEncoding: captured.encoding,
523
+ contentType: captured.contentType,
524
+ bodyBytes: captured.bodyBytes,
525
+ decodedBytes: null,
526
+ ...captured.truncated ? { truncated: true } : {},
527
+ bytes: captured.bodyBytes
528
+ };
529
+ appendLines(current.requestsFile, [line(request)]);
530
+ options.onWrite?.({ at });
531
+ } catch (error) {
532
+ fail(error);
533
+ }
534
+ };
535
+ return { writeAssembled, writeHttp, active };
66
536
  }
67
- function assembledRecord(kind, event) {
537
+ function emptyCache(root) {
68
538
  return {
69
- type: "assembled",
70
- kind,
71
- sessionID: event.sessionID,
72
- agent: event.agent,
73
- model: event.model,
74
- system: event.system,
75
- messages: event.messages,
76
- tools: event.tools ? Object.keys(event.tools) : []
539
+ root,
540
+ sessions: new Map,
541
+ byKey: new Map,
542
+ sorted: [],
543
+ requestBytes: 0,
544
+ lastScanMs: 0,
545
+ error: null
77
546
  };
78
547
  }
79
- async function httpRecord(event) {
80
- let body;
548
+ function parseRequestFile(file, sessionDirName) {
549
+ const entries = new Map;
550
+ let text;
81
551
  try {
82
- body = await event.request.clone().text();
83
- } catch (error) {
84
- body = `unreadable: ${String(error)}`;
552
+ text = readFileSync(file, "utf8");
553
+ } catch {
554
+ return entries;
555
+ }
556
+ for (const raw of text.split(`
557
+ `)) {
558
+ if (raw === "")
559
+ continue;
560
+ let parsed;
561
+ try {
562
+ parsed = JSON.parse(raw);
563
+ } catch {
564
+ continue;
565
+ }
566
+ if (parsed.v !== V2)
567
+ continue;
568
+ if (parsed.type === "assembled") {
569
+ const assembled = parsed;
570
+ if (typeof assembled.requestID !== "string" || typeof assembled.at !== "string") {
571
+ continue;
572
+ }
573
+ const key = `v2:${sessionDirName}:${assembled.requestID}`;
574
+ const existing = entries.get(assembled.requestID);
575
+ const entry = {
576
+ key,
577
+ cursor: `${assembled.at}|${assembled.requestID}`,
578
+ sessionDir: sessionDirName,
579
+ sessionID: assembled.sessionID,
580
+ requestID: assembled.requestID,
581
+ at: assembled.at,
582
+ kind: assembled.kind,
583
+ type: "assembled",
584
+ agent: typeof assembled.agent === "string" ? assembled.agent : null,
585
+ model: modelRef(assembled.model),
586
+ bytes: assembled.bytes,
587
+ messages: assembled.messages,
588
+ hasBody: existing?.http != null,
589
+ bodyBytes: existing?.bodyBytes ?? null,
590
+ assembled,
591
+ http: existing?.http ?? null
592
+ };
593
+ entries.set(assembled.requestID, entry);
594
+ } else if (parsed.type === "http") {
595
+ const http = parsed;
596
+ if (typeof http.requestID !== "string" || typeof http.at !== "string") {
597
+ continue;
598
+ }
599
+ const existing = entries.get(http.requestID);
600
+ const key = existing?.key ?? `v2:${sessionDirName}:${http.requestID}`;
601
+ const entry = {
602
+ key,
603
+ cursor: `${http.at}|${http.requestID}`,
604
+ sessionDir: sessionDirName,
605
+ sessionID: http.sessionID,
606
+ requestID: http.requestID,
607
+ at: existing?.assembled === null || existing?.assembled === undefined ? http.at : existing.at,
608
+ kind: existing?.assembled === null || existing?.assembled === undefined ? http.kind : existing.kind,
609
+ type: existing?.assembled === null || existing?.assembled === undefined ? "http" : "assembled",
610
+ agent: existing?.assembled === null || existing?.assembled === undefined ? typeof http.agent === "string" ? http.agent : null : existing.agent,
611
+ model: existing?.assembled === null || existing?.assembled === undefined ? modelRef(http.model) : existing.model,
612
+ bytes: existing?.assembled === null || existing?.assembled === undefined ? http.bytes : existing.bytes,
613
+ messages: existing?.messages ?? null,
614
+ hasBody: true,
615
+ bodyBytes: http.bodyBytes,
616
+ assembled: existing?.assembled ?? null,
617
+ http
618
+ };
619
+ entries.set(http.requestID, entry);
620
+ }
621
+ }
622
+ return entries;
623
+ }
624
+ function invalidateV2(root) {
625
+ caches.delete(root);
626
+ const prefix = join2(root, "");
627
+ for (const key of readCaches.keys()) {
628
+ if (key.startsWith(prefix))
629
+ readCaches.delete(key);
630
+ }
631
+ for (const key of searchCaches.keys()) {
632
+ if (key.startsWith(`${root}|`))
633
+ searchCaches.delete(key);
634
+ }
635
+ }
636
+ function ensureV2(root) {
637
+ let cache = caches.get(root);
638
+ if (cache === undefined) {
639
+ cache = emptyCache(root);
640
+ caches.set(root, cache);
641
+ }
642
+ const started = performance.now();
643
+ const next = new Map;
644
+ let changed = false;
645
+ let requestBytes = 0;
646
+ let directories = [];
647
+ try {
648
+ directories = readdirSync(sessionsRoot(root), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
649
+ } catch {
650
+ directories = [];
651
+ }
652
+ for (const dirName of directories) {
653
+ const file = join2(sessionsRoot(root), dirName, REQUESTS_FILE);
654
+ let stats;
655
+ try {
656
+ stats = statSync2(file);
657
+ } catch {
658
+ continue;
659
+ }
660
+ if (!stats.isFile())
661
+ continue;
662
+ requestBytes += stats.size;
663
+ const existing = cache.sessions.get(dirName);
664
+ if (existing !== undefined && existing.size === stats.size) {
665
+ next.set(dirName, existing);
666
+ continue;
667
+ }
668
+ next.set(dirName, {
669
+ dir: dirName,
670
+ file,
671
+ size: stats.size,
672
+ entries: parseRequestFile(file, dirName)
673
+ });
674
+ changed = true;
675
+ }
676
+ if (next.size !== cache.sessions.size)
677
+ changed = true;
678
+ if (!changed) {
679
+ cache.requestBytes = requestBytes;
680
+ cache.lastScanMs = Math.round(performance.now() - started);
681
+ return cache;
682
+ }
683
+ const byKey = new Map;
684
+ const sorted = [];
685
+ for (const session of next.values()) {
686
+ for (const entry of session.entries.values()) {
687
+ byKey.set(entry.key, entry);
688
+ sorted.push(entry);
689
+ }
690
+ }
691
+ sorted.sort((left, right) => {
692
+ if (left.at !== right.at)
693
+ return left.at < right.at ? 1 : -1;
694
+ return left.requestID < right.requestID ? 1 : left.requestID > right.requestID ? -1 : 0;
695
+ });
696
+ cache.sessions = next;
697
+ cache.byKey = byKey;
698
+ cache.sorted = sorted;
699
+ cache.requestBytes = requestBytes;
700
+ cache.error = null;
701
+ cache.lastScanMs = Math.round(performance.now() - started);
702
+ return cache;
703
+ }
704
+ function matches(entry, filters) {
705
+ if (filters.sessionID !== undefined && entry.sessionID !== filters.sessionID)
706
+ return false;
707
+ if (filters.kind !== undefined && entry.kind !== filters.kind)
708
+ return false;
709
+ if (filters.agent !== undefined && entry.agent !== filters.agent)
710
+ return false;
711
+ if (filters.type === "assembled" && entry.assembled === null)
712
+ return false;
713
+ if (filters.type === "http" && !entry.hasBody)
714
+ return false;
715
+ const modelLabel = entry.model === null ? "" : [entry.model.providerID, entry.model.id, entry.model.variant].filter(Boolean).join("/");
716
+ if (filters.model !== undefined && !modelLabel.toLowerCase().includes(filters.model.toLowerCase()))
717
+ return false;
718
+ if (filters.query !== undefined) {
719
+ const haystack = [entry.at, entry.type, entry.kind, entry.sessionID, entry.agent, modelLabel, entry.http?.url].filter((value) => typeof value === "string").join(" ").toLowerCase();
720
+ if (!haystack.includes(filters.query.toLowerCase()))
721
+ return false;
722
+ }
723
+ return true;
724
+ }
725
+ function summaryOf(entry) {
726
+ return {
727
+ key: entry.key,
728
+ cursor: entry.cursor,
729
+ bytes: entry.bytes,
730
+ at: entry.at,
731
+ type: entry.type,
732
+ kind: entry.kind,
733
+ sessionID: entry.sessionID,
734
+ agent: entry.agent,
735
+ model: entry.model,
736
+ url: entry.http?.url ?? null,
737
+ ...entry.messages === null ? {} : { messages: entry.messages },
738
+ ...entry.bodyBytes === null ? {} : { bodyBytes: entry.bodyBytes },
739
+ hasBody: entry.hasBody
740
+ };
741
+ }
742
+ function v2List(root, input) {
743
+ armV2(root);
744
+ const cache = ensureV2(root);
745
+ const limit = clampPage(input.limit);
746
+ const entries = [];
747
+ let hasMore = false;
748
+ for (const entry of cache.sorted) {
749
+ if (input.cursor !== undefined && entry.cursor >= input.cursor)
750
+ continue;
751
+ if (!matches(entry, input))
752
+ continue;
753
+ entries.push(summaryOf(entry));
754
+ if (entries.length > limit) {
755
+ hasMore = true;
756
+ entries.pop();
757
+ break;
758
+ }
759
+ }
760
+ return {
761
+ entries,
762
+ hasMore,
763
+ records: cache.sorted.length,
764
+ error: cache.error
765
+ };
766
+ }
767
+ function snippetOf(text, needle, ignoreCase) {
768
+ const haystack = ignoreCase ? text.toLowerCase() : text;
769
+ const at = haystack.indexOf(ignoreCase ? needle.toLowerCase() : needle);
770
+ if (at < 0)
771
+ return "";
772
+ const start = Math.max(0, at - 60);
773
+ const end = Math.min(text.length, at + needle.length + 80);
774
+ const body = text.slice(start, end).replace(/\s+/g, " ").trim();
775
+ return `${start > 0 ? "\u2026" : ""}${body}${end < text.length ? "\u2026" : ""}`;
776
+ }
777
+ function metadataText(entry) {
778
+ const model = entry.model === null ? "" : [entry.model.providerID, entry.model.id, entry.model.variant].filter(Boolean).join("/");
779
+ return [entry.at, entry.type, entry.kind, entry.sessionID, entry.agent, model, entry.http?.url].filter((value) => typeof value === "string" && value !== "").join(" ");
780
+ }
781
+ function v2Search(root, input, signal) {
782
+ armV2(root);
783
+ const cache = ensureV2(root);
784
+ const query = boundedString(input.query, MAX_SEARCH_QUERY);
785
+ if (query === undefined)
786
+ throw new LogError("bad_request", "query must not be empty");
787
+ const cacheKey = [
788
+ root,
789
+ cache.requestBytes,
790
+ input.sessionID ?? "",
791
+ input.type ?? "",
792
+ input.kind ?? "",
793
+ input.agent ?? "",
794
+ input.model ?? "",
795
+ input.limit ?? "",
796
+ input.budgetBytes ?? "",
797
+ input.budgetMs ?? "",
798
+ input.ignoreCase === true ? "i" : "s",
799
+ query
800
+ ].join("|");
801
+ const cached = searchCaches.get(cacheKey);
802
+ if (cached !== undefined && Date.now() - cached.at < 5000)
803
+ return cached.output;
804
+ const limit = clampInteger(input.limit, 1, MAX_SEARCH_RESULTS, 50);
805
+ const budgetBytes = clampSearchBytes(input.budgetBytes);
806
+ const budgetMs = clampSearchMs(input.budgetMs);
807
+ const filters = { ...input, query: undefined };
808
+ const ignoreCase = input.ignoreCase === true;
809
+ const needle = ignoreCase ? query.toLowerCase() : query;
810
+ const matchesOut = [];
811
+ let scannedBytes = 0;
812
+ let skipped = 0;
813
+ let partial = false;
814
+ const started = performance.now();
815
+ const sessionMaps = new Map;
816
+ for (const entry of cache.sorted) {
817
+ if (signal?.aborted === true || performance.now() - started >= budgetMs || scannedBytes >= budgetBytes) {
818
+ partial = true;
819
+ break;
820
+ }
821
+ if (!matches(entry, filters))
822
+ continue;
823
+ const metadata = metadataText(entry);
824
+ const metadataHaystack = ignoreCase ? metadata.toLowerCase() : metadata;
825
+ if (metadataHaystack.includes(needle)) {
826
+ matchesOut.push({ entry: summaryOf(entry), snippet: snippetOf(metadata, query, ignoreCase) });
827
+ if (matchesOut.length >= limit) {
828
+ partial = true;
829
+ break;
830
+ }
831
+ continue;
832
+ }
833
+ let snippet = "";
834
+ if (entry.assembled !== null) {
835
+ let maps = sessionMaps.get(entry.sessionDir);
836
+ if (maps === undefined) {
837
+ maps = sessionMapBytes(root, entry.sessionDir) <= MAX_SESSION_MAP_BYTES ? mapsFor(root, entry.sessionDir) : null;
838
+ sessionMaps.set(entry.sessionDir, maps);
839
+ }
840
+ if (maps === null) {
841
+ skipped += 1;
842
+ } else {
843
+ const system = maps.systems.get(entry.assembled.systemHash);
844
+ if (system !== undefined) {
845
+ const text = JSON.stringify(system) ?? "";
846
+ scannedBytes += Buffer.byteLength(text, "utf8");
847
+ snippet = snippetOf(text, query, ignoreCase);
848
+ } else {
849
+ skipped += 1;
850
+ }
851
+ if (snippet === "") {
852
+ for (const hash of entry.assembled.messageHashes) {
853
+ const message = maps.messages.get(hash);
854
+ if (message === undefined) {
855
+ skipped += 1;
856
+ continue;
857
+ }
858
+ const text = JSON.stringify(message) ?? "";
859
+ scannedBytes += Buffer.byteLength(text, "utf8");
860
+ snippet = snippetOf(text, query, ignoreCase);
861
+ if (snippet !== "")
862
+ break;
863
+ if (scannedBytes >= budgetBytes || performance.now() - started >= budgetMs)
864
+ break;
865
+ }
866
+ }
867
+ }
868
+ }
869
+ if (snippet === "" && entry.http !== null) {
870
+ const stored = readBody(root, entry.sessionDir, entry.http.bodyHash);
871
+ if (stored === null) {
872
+ skipped += 1;
873
+ } else {
874
+ const decoded = decodeStoredBody(stored, entry.http.bodyEncoding);
875
+ if (decoded.text === null) {
876
+ skipped += 1;
877
+ } else {
878
+ scannedBytes += Buffer.byteLength(decoded.text, "utf8");
879
+ snippet = snippetOf(decoded.text, query, ignoreCase);
880
+ }
881
+ }
882
+ }
883
+ if (snippet !== "") {
884
+ matchesOut.push({ entry: summaryOf(entry), snippet });
885
+ if (matchesOut.length >= limit) {
886
+ partial = true;
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ const output = {
892
+ matches: matchesOut,
893
+ partial,
894
+ scannedBytes,
895
+ skipped,
896
+ error: cache.error
897
+ };
898
+ searchCaches.set(cacheKey, { at: Date.now(), output });
899
+ while (searchCaches.size > 8) {
900
+ const oldest = searchCaches.keys().next().value;
901
+ if (oldest === undefined)
902
+ break;
903
+ searchCaches.delete(oldest);
904
+ }
905
+ return output;
906
+ }
907
+ function mapCache(root, sessionDirName) {
908
+ const key = join2(root, sessionDirName);
909
+ const existing = readCaches.get(key);
910
+ if (existing !== undefined) {
911
+ readCaches.delete(key);
912
+ readCaches.set(key, existing);
913
+ return existing;
914
+ }
915
+ const cache = {
916
+ key,
917
+ systemsFile: join2(sessionDir(root, sessionDirName), SYSTEMS_FILE),
918
+ messagesFile: join2(sessionDir(root, sessionDirName), MESSAGES_FILE),
919
+ systemsSize: -1,
920
+ messagesSize: -1,
921
+ systems: null,
922
+ messages: null,
923
+ bytes: 0
924
+ };
925
+ readCaches.set(key, cache);
926
+ while (readCaches.size > MAX_READ_CACHES) {
927
+ const oldest = readCaches.keys().next().value;
928
+ if (oldest === undefined)
929
+ break;
930
+ readCaches.delete(oldest);
931
+ }
932
+ return cache;
933
+ }
934
+ function trimReadCaches(protect) {
935
+ let total = 0;
936
+ for (const cache of readCaches.values())
937
+ total += cache.bytes;
938
+ for (const [key, cache] of readCaches) {
939
+ if (readCaches.size <= 1 || total <= MAX_READ_CACHE_BYTES)
940
+ break;
941
+ if (key === protect)
942
+ continue;
943
+ readCaches.delete(key);
944
+ total -= cache.bytes;
945
+ }
946
+ }
947
+ function loadMap(file, field) {
948
+ const map = new Map;
949
+ let text;
950
+ try {
951
+ text = readFileSync(file, "utf8");
952
+ } catch {
953
+ return map;
954
+ }
955
+ for (const entry of text.split(`
956
+ `)) {
957
+ if (entry === "")
958
+ continue;
959
+ try {
960
+ const parsed = JSON.parse(entry);
961
+ if (parsed.v !== V2 || typeof parsed.hash !== "string")
962
+ continue;
963
+ map.set(parsed.hash, parsed[field]);
964
+ } catch {}
965
+ }
966
+ return map;
967
+ }
968
+ function mapsFor(root, sessionDirName) {
969
+ const cache = mapCache(root, sessionDirName);
970
+ let systemsSize = -1;
971
+ let messagesSize = -1;
972
+ try {
973
+ systemsSize = statSync2(cache.systemsFile).size;
974
+ messagesSize = statSync2(cache.messagesFile).size;
975
+ } catch {}
976
+ if (cache.systems === null || cache.systemsSize !== systemsSize) {
977
+ cache.systems = loadMap(cache.systemsFile, "system");
978
+ cache.systemsSize = systemsSize;
979
+ }
980
+ if (cache.messages === null || cache.messagesSize !== messagesSize) {
981
+ cache.messages = loadMap(cache.messagesFile, "message");
982
+ cache.messagesSize = messagesSize;
983
+ }
984
+ cache.bytes = Math.max(0, systemsSize) + Math.max(0, messagesSize);
985
+ trimReadCaches(cache.key);
986
+ return { systems: cache.systems, messages: cache.messages };
987
+ }
988
+ function readBody(root, sessionDirName, bodyHash) {
989
+ if (!/^[a-f0-9]{64}$/.test(bodyHash))
990
+ return null;
991
+ try {
992
+ return readFileSync(join2(sessionDir(root, sessionDirName), BODIES_DIR, `${bodyHash}.bin`));
993
+ } catch {
994
+ return null;
995
+ }
996
+ }
997
+ function readValuesFromDisk(file, field, wanted) {
998
+ const found = new Map;
999
+ if (wanted.size === 0)
1000
+ return found;
1001
+ let fd;
1002
+ try {
1003
+ fd = openSync(file, "r");
1004
+ const buffer = Buffer.allocUnsafe(STREAM_CHUNK_BYTES);
1005
+ let carry = Buffer.alloc(0);
1006
+ while (true) {
1007
+ const bytesRead = readSync(fd, buffer, 0, buffer.length, null);
1008
+ if (bytesRead === 0)
1009
+ break;
1010
+ const chunk = carry.length === 0 ? buffer.subarray(0, bytesRead) : Buffer.concat([carry, buffer.subarray(0, bytesRead)]);
1011
+ let start = 0;
1012
+ while (true) {
1013
+ const newline = chunk.indexOf(10, start);
1014
+ if (newline === -1)
1015
+ break;
1016
+ const line = chunk.toString("utf8", start, newline);
1017
+ const hash = /^\{"v":2,"hash":"([a-f0-9]{64})"/.exec(line)?.[1];
1018
+ if (hash !== undefined && wanted.has(hash) && !found.has(hash)) {
1019
+ try {
1020
+ const parsed = JSON.parse(line);
1021
+ if (parsed.v === V2)
1022
+ found.set(hash, parsed[field]);
1023
+ } catch {}
1024
+ if (found.size === wanted.size)
1025
+ return found;
1026
+ }
1027
+ start = newline + 1;
1028
+ }
1029
+ carry = Buffer.from(chunk.subarray(start));
1030
+ }
1031
+ if (carry.length > 0) {
1032
+ const line = carry.toString("utf8");
1033
+ const hash = /^\{"v":2,"hash":"([a-f0-9]{64})"/.exec(line)?.[1];
1034
+ if (hash !== undefined && wanted.has(hash) && !found.has(hash)) {
1035
+ try {
1036
+ const parsed = JSON.parse(line);
1037
+ if (parsed.v === V2)
1038
+ found.set(hash, parsed[field]);
1039
+ } catch {}
1040
+ }
1041
+ }
1042
+ } catch {} finally {
1043
+ if (fd !== undefined)
1044
+ closeSync(fd);
1045
+ }
1046
+ return found;
1047
+ }
1048
+ function sessionMapBytes(root, sessionDirName) {
1049
+ let total = 0;
1050
+ try {
1051
+ total += statSync2(join2(sessionDir(root, sessionDirName), SYSTEMS_FILE)).size;
1052
+ } catch {}
1053
+ try {
1054
+ total += statSync2(join2(sessionDir(root, sessionDirName), MESSAGES_FILE)).size;
1055
+ } catch {}
1056
+ return total;
1057
+ }
1058
+ function mapsForRead(root, entry, maxMapBytes) {
1059
+ if (entry.assembled === null)
1060
+ return null;
1061
+ if (sessionMapBytes(root, entry.sessionDir) <= maxMapBytes) {
1062
+ return mapsFor(root, entry.sessionDir);
1063
+ }
1064
+ const systems = readValuesFromDisk(join2(sessionDir(root, entry.sessionDir), SYSTEMS_FILE), "system", new Set([entry.assembled.systemHash]));
1065
+ const messages = readValuesFromDisk(join2(sessionDir(root, entry.sessionDir), MESSAGES_FILE), "message", new Set(entry.assembled.messageHashes));
1066
+ return { systems, messages };
1067
+ }
1068
+ function assembleSystem(entry, maps, max) {
1069
+ const stored = entry.assembled === null || maps === null ? undefined : maps.systems.get(entry.assembled.systemHash);
1070
+ let system = stored ?? [];
1071
+ let used = Buffer.byteLength(JSON.stringify(system), "utf8");
1072
+ if (used <= max)
1073
+ return { system, used, truncated: false, budgetTruncated: false };
1074
+ const text = sliceUtf8(JSON.stringify(system), Math.max(0, max - 64));
1075
+ system = [{ type: "text", text }];
1076
+ used = Buffer.byteLength(text, "utf8");
1077
+ return { system, used, truncated: true, budgetTruncated: true };
1078
+ }
1079
+ function assembleMessages(entry, maps, max, used) {
1080
+ const messages = [];
1081
+ let truncated = false;
1082
+ let budgetTruncated = false;
1083
+ if (entry.assembled === null || maps === null) {
1084
+ return { messages, used, truncated, budgetTruncated };
1085
+ }
1086
+ for (const hash of entry.assembled.messageHashes) {
1087
+ const message = maps.messages.get(hash);
1088
+ if (message === undefined) {
1089
+ truncated = true;
1090
+ continue;
1091
+ }
1092
+ const size = Buffer.byteLength(JSON.stringify(message), "utf8");
1093
+ if (used + size > max) {
1094
+ truncated = true;
1095
+ budgetTruncated = true;
1096
+ break;
1097
+ }
1098
+ messages.push(message);
1099
+ used += size;
1100
+ }
1101
+ return { messages, used, truncated, budgetTruncated };
1102
+ }
1103
+ function assembleHttp(entry, root, max, used) {
1104
+ if (entry.http === null) {
1105
+ return { http: null, used, truncated: false, budgetTruncated: false, bodyLogicalBytes: null };
1106
+ }
1107
+ const stored = readBody(root, entry.sessionDir, entry.http.bodyHash);
1108
+ if (stored === null) {
1109
+ return {
1110
+ http: {
1111
+ url: entry.http.url,
1112
+ bodyUnavailable: true,
1113
+ bodyEncoding: entry.http.bodyEncoding,
1114
+ bodyBytes: entry.http.bodyBytes
1115
+ },
1116
+ used,
1117
+ truncated: false,
1118
+ budgetTruncated: false,
1119
+ bodyLogicalBytes: null
1120
+ };
85
1121
  }
1122
+ const decoded = decodeStoredBody(stored, entry.http.bodyEncoding);
1123
+ const decodedBodyBytes = decoded.decodedBytes ?? (decoded.text !== null ? Buffer.byteLength(decoded.text, "utf8") : decoded.base64?.length ?? 0);
1124
+ const bodyLogicalBytes = entry.http.truncated === true ? entry.http.bodyBytes : decodedBodyBytes;
1125
+ let body = decoded.text;
1126
+ let bodyBase64 = decoded.base64;
1127
+ const bodyCapped = entry.http.truncated === true;
1128
+ let bodyTruncated = bodyCapped;
1129
+ let budgetTruncated = false;
1130
+ const remaining = Math.max(0, max - used);
1131
+ if (body !== null) {
1132
+ const bodyBytes = Buffer.byteLength(body, "utf8");
1133
+ if (bodyBytes > remaining) {
1134
+ body = sliceUtf8(body, remaining);
1135
+ bodyTruncated = true;
1136
+ budgetTruncated = true;
1137
+ }
1138
+ } else if (bodyBase64 !== null) {
1139
+ const kept = Math.min(bodyBase64.length, remaining);
1140
+ if (kept < bodyBase64.length) {
1141
+ bodyBase64 = bodyBase64.slice(0, kept);
1142
+ bodyTruncated = true;
1143
+ budgetTruncated = true;
1144
+ }
1145
+ }
1146
+ const http = {
1147
+ url: entry.http.url,
1148
+ ...body === null ? {} : { body },
1149
+ ...bodyBase64 === null ? {} : { bodyBase64 },
1150
+ bodyEncoding: entry.http.bodyEncoding,
1151
+ ...entry.http.contentType === undefined ? {} : { contentType: entry.http.contentType },
1152
+ bodyBytes: entry.http.bodyBytes,
1153
+ ...decoded.decodedBytes === null ? {} : { decodedBytes: decoded.decodedBytes },
1154
+ ...bodyCapped ? { bodyCapped: true } : {},
1155
+ ...bodyTruncated ? { bodyTruncated: true } : {}
1156
+ };
86
1157
  return {
87
- type: "http",
88
- kind: event.kind,
89
- sessionID: event.sessionID,
90
- agent: event.agent,
91
- model: event.model,
92
- url: event.request.url,
93
- body
1158
+ http,
1159
+ used: used + (body === null ? bodyBase64?.length ?? 0 : Buffer.byteLength(body, "utf8")),
1160
+ truncated: bodyTruncated,
1161
+ budgetTruncated,
1162
+ bodyLogicalBytes
1163
+ };
1164
+ }
1165
+ function buildRecord(entry, system, messages, http) {
1166
+ return {
1167
+ type: entry.assembled === null ? "http" : "assembled",
1168
+ at: entry.at,
1169
+ kind: entry.kind,
1170
+ sessionID: entry.sessionID,
1171
+ ...entry.agent === null ? {} : { agent: entry.agent },
1172
+ ...entry.model === null ? {} : { model: entry.model },
1173
+ ...entry.assembled === null ? {} : {
1174
+ system,
1175
+ messages,
1176
+ tools: entry.assembled.tools,
1177
+ messageCount: entry.assembled.messages,
1178
+ bytes: entry.assembled.bytes
1179
+ },
1180
+ ...entry.http === null ? {} : { url: entry.http.url },
1181
+ ...entry.assembled === null && http !== null ? http : {},
1182
+ ...entry.assembled !== null && http !== null ? { http } : {}
1183
+ };
1184
+ }
1185
+ function fullBytesOf(entry, bodyLogicalBytes) {
1186
+ const httpBytes = entry.http === null ? 0 : bodyLogicalBytes ?? entry.http.bodyBytes;
1187
+ return entry.assembled === null ? entry.http === null ? entry.bytes : httpBytes : entry.bytes + httpBytes;
1188
+ }
1189
+ function v2Read(root, key, maxBytes = MAX_RECORD_BYTES, options = {}) {
1190
+ armV2(root);
1191
+ const cache = ensureV2(root);
1192
+ const entry = cache.byKey.get(key);
1193
+ if (entry === undefined) {
1194
+ return { record: null, bytes: 0, truncated: false, moreAvailable: false, fullBytes: 0, notFound: true };
1195
+ }
1196
+ const max = clampReadBytes(maxBytes);
1197
+ const maps = mapsForRead(root, entry, options.maxMapBytes ?? MAX_SESSION_MAP_BYTES);
1198
+ const system = assembleSystem(entry, maps, max);
1199
+ const messages = assembleMessages(entry, maps, max, system.used);
1200
+ const http = assembleHttp(entry, root, max, messages.used);
1201
+ const record = buildRecord(entry, system.system, messages.messages, http.http);
1202
+ const budgetTruncated = system.budgetTruncated || messages.budgetTruncated || http.budgetTruncated;
1203
+ return {
1204
+ record,
1205
+ bytes: entry.bytes,
1206
+ truncated: system.truncated || messages.truncated || http.truncated,
1207
+ moreAvailable: budgetTruncated && max < MAX_FULL_RECORD_BYTES,
1208
+ fullBytes: fullBytesOf(entry, http.bodyLogicalBytes),
1209
+ notFound: false,
1210
+ paths: {
1211
+ session: sessionDir(root, entry.sessionDir),
1212
+ requests: join2(sessionDir(root, entry.sessionDir), REQUESTS_FILE),
1213
+ ...entry.http === null ? {} : { body: join2(sessionDir(root, entry.sessionDir), BODIES_DIR, `${entry.http.bodyHash}.bin`) }
1214
+ }
1215
+ };
1216
+ }
1217
+ function storageBytes(root) {
1218
+ const now = Date.now();
1219
+ const key = `storage:${root}`;
1220
+ const previous = storageCache.get(key);
1221
+ if (previous !== undefined && now - previous.at < 30000)
1222
+ return previous.bytes;
1223
+ let total = 0;
1224
+ try {
1225
+ for (const session of readdirSync(sessionsRoot(root), { withFileTypes: true })) {
1226
+ if (!session.isDirectory())
1227
+ continue;
1228
+ const dir = join2(sessionsRoot(root), session.name);
1229
+ for (const file of readdirSync(dir, { withFileTypes: true })) {
1230
+ if (file.isFile()) {
1231
+ try {
1232
+ total += statSync2(join2(dir, file.name)).size;
1233
+ } catch {}
1234
+ } else if (file.isDirectory()) {
1235
+ for (const child of readdirSync(join2(dir, file.name), { withFileTypes: true })) {
1236
+ if (!child.isFile())
1237
+ continue;
1238
+ try {
1239
+ total += statSync2(join2(dir, file.name, child.name)).size;
1240
+ } catch {}
1241
+ }
1242
+ }
1243
+ }
1244
+ }
1245
+ } catch {
1246
+ total = 0;
1247
+ }
1248
+ storageCache.set(key, { at: now, bytes: total });
1249
+ return total;
1250
+ }
1251
+ var storageCache = new Map;
1252
+ function v2Status(root) {
1253
+ const cache = ensureV2(root);
1254
+ const bytes = storageBytes(root);
1255
+ const path = inspectPath(root);
1256
+ const warnings = [];
1257
+ let directory = false;
1258
+ try {
1259
+ directory = statSync2(root).isDirectory();
1260
+ } catch {}
1261
+ if (process.platform !== "win32" && path.mode !== null && (path.mode & 63) !== 0)
1262
+ warnings.push("directory-permissions");
1263
+ if (path.symlink)
1264
+ warnings.push("symlink");
1265
+ if (path.exists && !directory)
1266
+ warnings.push("not-regular");
1267
+ return {
1268
+ bytes,
1269
+ sessions: cache.sessions.size,
1270
+ requests: cache.sorted.length,
1271
+ requestBytes: cache.requestBytes,
1272
+ lastScanMs: cache.lastScanMs,
1273
+ error: cache.error,
1274
+ warnings
1275
+ };
1276
+ }
1277
+ function v2Delete(root, target, sessionID) {
1278
+ let freed = 0;
1279
+ const remove = (dir) => {
1280
+ try {
1281
+ for (const file of readdirSync(dir, { withFileTypes: true })) {
1282
+ if (file.isFile()) {
1283
+ try {
1284
+ freed += statSync2(join2(dir, file.name)).size;
1285
+ } catch {}
1286
+ } else if (file.isDirectory()) {
1287
+ for (const child of readdirSync(join2(dir, file.name), { withFileTypes: true })) {
1288
+ if (!child.isFile())
1289
+ continue;
1290
+ try {
1291
+ freed += statSync2(join2(dir, file.name, child.name)).size;
1292
+ } catch {}
1293
+ }
1294
+ }
1295
+ }
1296
+ rmSync(dir, { recursive: true, force: true });
1297
+ } catch {}
1298
+ };
1299
+ if (target === "all") {
1300
+ try {
1301
+ for (const entry of readdirSync(sessionsRoot(root), { withFileTypes: true })) {
1302
+ if (entry.isDirectory())
1303
+ remove(join2(sessionsRoot(root), entry.name));
1304
+ }
1305
+ } catch {}
1306
+ } else if (sessionID !== undefined) {
1307
+ remove(join2(sessionsRoot(root), safeDirName(sessionID)));
1308
+ }
1309
+ invalidateV2(root);
1310
+ storageCache.delete(`storage:${root}`);
1311
+ return freed;
1312
+ }
1313
+ var ACTIVE_GRACE_MS = 15 * 60 * 1000;
1314
+ function v2Prune(root, retention, active) {
1315
+ let directories = [];
1316
+ try {
1317
+ directories = readdirSync(sessionsRoot(root), { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
1318
+ } catch {
1319
+ return { removed: 0, bytesFreed: 0 };
1320
+ }
1321
+ const sessions = [];
1322
+ for (const name of directories) {
1323
+ const dir = join2(sessionsRoot(root), name);
1324
+ let mtime = 0;
1325
+ let bytes = 0;
1326
+ try {
1327
+ mtime = statSync2(dir).mtimeMs;
1328
+ for (const file of readdirSync(dir, { withFileTypes: true })) {
1329
+ if (file.isFile()) {
1330
+ const stats = statSync2(join2(dir, file.name));
1331
+ bytes += stats.size;
1332
+ mtime = Math.max(mtime, stats.mtimeMs);
1333
+ } else if (file.isDirectory()) {
1334
+ for (const child of readdirSync(join2(dir, file.name), { withFileTypes: true })) {
1335
+ if (!child.isFile())
1336
+ continue;
1337
+ const stats = statSync2(join2(dir, file.name, child.name));
1338
+ bytes += stats.size;
1339
+ mtime = Math.max(mtime, stats.mtimeMs);
1340
+ }
1341
+ }
1342
+ }
1343
+ } catch {
1344
+ continue;
1345
+ }
1346
+ sessions.push({ name, dir, mtime, bytes });
1347
+ }
1348
+ sessions.sort((left, right) => left.mtime - right.mtime);
1349
+ const now = Date.now();
1350
+ const maxAge = retention.maxAgeDays * 24 * 60 * 60 * 1000;
1351
+ let total = sessions.reduce((sum, session) => sum + session.bytes, 0);
1352
+ let remaining = sessions.length;
1353
+ let removed = 0;
1354
+ let bytesFreed = 0;
1355
+ for (const session of sessions) {
1356
+ const tooOld = maxAge > 0 && now - session.mtime > maxAge;
1357
+ const tooMany = remaining > retention.maxSessions;
1358
+ const tooLarge = total > retention.maxTotalBytes;
1359
+ if (!tooOld && !tooMany && !tooLarge)
1360
+ break;
1361
+ if (active.has(session.name) && now - session.mtime < ACTIVE_GRACE_MS)
1362
+ continue;
1363
+ rmSync(session.dir, { recursive: true, force: true });
1364
+ total -= session.bytes;
1365
+ remaining -= 1;
1366
+ bytesFreed += session.bytes;
1367
+ removed += 1;
1368
+ }
1369
+ if (removed > 0) {
1370
+ invalidateV2(root);
1371
+ storageCache.delete(`storage:${root}`);
1372
+ }
1373
+ return { removed, bytesFreed };
1374
+ }
1375
+
1376
+ // src/rpc.ts
1377
+ import { Rpc } from "@opencode/plugin/rpc";
1378
+
1379
+ // src/settings.ts
1380
+ var SETTINGS_KEY = "settings";
1381
+ var MAX_SETTINGS_DISK_BUDGET = 8 * 1024 * 1024 * 1024;
1382
+ var MAX_SETTINGS_RETENTION_DAYS = 3650;
1383
+ var MAX_SETTINGS_RETENTION_SESSIONS = 1e4;
1384
+ var MAX_SETTINGS_DIRECTORY = 4096;
1385
+ var DEFAULT_SETTINGS = {
1386
+ enabled: true,
1387
+ http: false,
1388
+ diskBudget: DEFAULT_DISK_BUDGET,
1389
+ retentionMaxAgeDays: 30,
1390
+ retentionMaxSessions: 200,
1391
+ directory: "",
1392
+ maintenance: true
1393
+ };
1394
+ function defaultSettings() {
1395
+ return { ...DEFAULT_SETTINGS };
1396
+ }
1397
+ function isRecord(value) {
1398
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1399
+ }
1400
+ function isBoundedInteger(value, max) {
1401
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && Math.floor(value) === value && value <= max;
1402
+ }
1403
+ function boundedInteger(value, max, fallback) {
1404
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
1405
+ return fallback;
1406
+ return Math.min(max, Math.floor(value));
1407
+ }
1408
+ function directoryValue(value) {
1409
+ if (typeof value !== "string")
1410
+ return;
1411
+ return value.trim().slice(0, MAX_SETTINGS_DIRECTORY);
1412
+ }
1413
+ function overlay(target, value) {
1414
+ if (!isRecord(value))
1415
+ return target;
1416
+ const next = { ...target };
1417
+ if (typeof value.enabled === "boolean")
1418
+ next.enabled = value.enabled;
1419
+ if (typeof value.http === "boolean")
1420
+ next.http = value.http;
1421
+ next.diskBudget = boundedInteger(value.diskBudget, MAX_SETTINGS_DISK_BUDGET, next.diskBudget);
1422
+ next.retentionMaxAgeDays = boundedInteger(value.retentionMaxAgeDays, MAX_SETTINGS_RETENTION_DAYS, next.retentionMaxAgeDays);
1423
+ next.retentionMaxSessions = boundedInteger(value.retentionMaxSessions, MAX_SETTINGS_RETENTION_SESSIONS, next.retentionMaxSessions);
1424
+ const directory = directoryValue(value.directory);
1425
+ if (directory !== undefined)
1426
+ next.directory = directory;
1427
+ if (typeof value.maintenance === "boolean")
1428
+ next.maintenance = value.maintenance;
1429
+ return next;
1430
+ }
1431
+ function sanitizeSettings(value) {
1432
+ return overlay(defaultSettings(), value);
1433
+ }
1434
+ function isValidSettings(value) {
1435
+ if (!isRecord(value))
1436
+ return false;
1437
+ if (typeof value.enabled !== "boolean" || typeof value.http !== "boolean")
1438
+ return false;
1439
+ if (typeof value.maintenance !== "boolean")
1440
+ return false;
1441
+ if (typeof value.directory !== "string" || value.directory.length > MAX_SETTINGS_DIRECTORY)
1442
+ return false;
1443
+ return isBoundedInteger(value.diskBudget, MAX_SETTINGS_DISK_BUDGET) && isBoundedInteger(value.retentionMaxAgeDays, MAX_SETTINGS_RETENTION_DAYS) && isBoundedInteger(value.retentionMaxSessions, MAX_SETTINGS_RETENTION_SESSIONS);
1444
+ }
1445
+ function settingsFromEnvelope(value) {
1446
+ return sanitizeSettings(isRecord(value) ? value.settings : undefined);
1447
+ }
1448
+ function pickSettings(value) {
1449
+ return {
1450
+ enabled: value.enabled,
1451
+ http: value.http,
1452
+ diskBudget: value.diskBudget,
1453
+ retentionMaxAgeDays: value.retentionMaxAgeDays,
1454
+ retentionMaxSessions: value.retentionMaxSessions,
1455
+ directory: value.directory,
1456
+ maintenance: value.maintenance
1457
+ };
1458
+ }
1459
+
1460
+ // src/rpc.ts
1461
+ var CONTRACT_VERSION = 6;
1462
+ var nullableString = { type: ["string", "null"] };
1463
+ var modelSchema = {
1464
+ anyOf: [
1465
+ { type: "null" },
1466
+ {
1467
+ type: "object",
1468
+ properties: {
1469
+ providerID: { type: "string" },
1470
+ id: { type: "string" },
1471
+ variant: { type: "string" }
1472
+ },
1473
+ additionalProperties: false
1474
+ }
1475
+ ]
1476
+ };
1477
+ var summarySchema = {
1478
+ type: "object",
1479
+ properties: {
1480
+ key: { type: "string" },
1481
+ cursor: { type: "string" },
1482
+ bytes: { type: "number" },
1483
+ at: nullableString,
1484
+ type: nullableString,
1485
+ kind: nullableString,
1486
+ sessionID: nullableString,
1487
+ agent: nullableString,
1488
+ model: modelSchema,
1489
+ url: nullableString,
1490
+ messages: { type: "number" },
1491
+ bodyBytes: { type: "number" },
1492
+ hasBody: { type: "boolean" }
1493
+ },
1494
+ required: ["key", "cursor", "bytes", "at", "type", "kind", "sessionID", "agent", "model", "url"],
1495
+ additionalProperties: false
1496
+ };
1497
+ var storeStatusSchema = {
1498
+ type: "object",
1499
+ properties: {
1500
+ path: { type: "string" },
1501
+ exists: { type: "boolean" },
1502
+ bytes: { type: "number" },
1503
+ mtimeMs: { anyOf: [{ type: "number" }, { type: "null" }] },
1504
+ directory: { type: "boolean" },
1505
+ symlink: { type: "boolean" },
1506
+ mode: { anyOf: [{ type: "number" }, { type: "null" }] },
1507
+ directoryMode: { anyOf: [{ type: "number" }, { type: "null" }] },
1508
+ warnings: { type: "array", items: { type: "string" } }
1509
+ },
1510
+ required: ["path", "exists", "bytes", "mtimeMs", "directory", "symlink", "mode", "directoryMode", "warnings"],
1511
+ additionalProperties: false
1512
+ };
1513
+ var cacheSchema = {
1514
+ type: "object",
1515
+ properties: {
1516
+ requests: { type: "number" },
1517
+ requestBytes: { type: "number" },
1518
+ lastScanMs: { type: "number" },
1519
+ error: nullableString
1520
+ },
1521
+ required: ["requests", "requestBytes", "lastScanMs", "error"],
1522
+ additionalProperties: false
1523
+ };
1524
+ var settingsSchema = {
1525
+ type: "object",
1526
+ properties: {
1527
+ enabled: { type: "boolean" },
1528
+ http: { type: "boolean" },
1529
+ diskBudget: { type: "number", minimum: 0, maximum: MAX_SETTINGS_DISK_BUDGET },
1530
+ retentionMaxAgeDays: { type: "number", minimum: 0, maximum: MAX_SETTINGS_RETENTION_DAYS },
1531
+ retentionMaxSessions: { type: "number", minimum: 0, maximum: MAX_SETTINGS_RETENTION_SESSIONS },
1532
+ directory: { type: "string", maxLength: MAX_SETTINGS_DIRECTORY },
1533
+ maintenance: { type: "boolean" }
1534
+ },
1535
+ required: [
1536
+ "enabled",
1537
+ "http",
1538
+ "diskBudget",
1539
+ "retentionMaxAgeDays",
1540
+ "retentionMaxSessions",
1541
+ "directory",
1542
+ "maintenance"
1543
+ ],
1544
+ additionalProperties: false
1545
+ };
1546
+ var statusSettingsSchema = {
1547
+ type: "object",
1548
+ properties: {
1549
+ ...settingsSchema.properties,
1550
+ retention: {
1551
+ type: "object",
1552
+ properties: {
1553
+ maxTotalBytes: { anyOf: [{ type: "number" }, { type: "null" }] },
1554
+ maxAgeDays: { type: "number" },
1555
+ maxSessions: { anyOf: [{ type: "number" }, { type: "null" }] }
1556
+ },
1557
+ required: ["maxTotalBytes", "maxAgeDays", "maxSessions"],
1558
+ additionalProperties: false
1559
+ }
1560
+ },
1561
+ required: [...settingsSchema.required, "retention"],
1562
+ additionalProperties: false
1563
+ };
1564
+ var sessionScopeSchema = {
1565
+ type: "object",
1566
+ properties: {
1567
+ mode: { type: "string", enum: ["all", "only"] },
1568
+ sessions: { type: "array", items: { type: "string", maxLength: 200 } },
1569
+ max: { type: "number" }
1570
+ },
1571
+ required: ["mode", "sessions", "max"],
1572
+ additionalProperties: false
1573
+ };
1574
+ var settingsResponseSchema = {
1575
+ type: "object",
1576
+ properties: {
1577
+ settings: settingsSchema,
1578
+ sessionScope: sessionScopeSchema
1579
+ },
1580
+ required: ["settings", "sessionScope"],
1581
+ additionalProperties: false
1582
+ };
1583
+ var errorSchema = {
1584
+ type: "object",
1585
+ properties: { message: { type: "string" } },
1586
+ additionalProperties: false
1587
+ };
1588
+ var errors = {
1589
+ io: errorSchema,
1590
+ not_found: errorSchema,
1591
+ bad_request: errorSchema,
1592
+ forbidden: errorSchema
1593
+ };
1594
+ var filtersSchema = {
1595
+ sessionID: { type: "string", maxLength: 200 },
1596
+ type: { type: "string", maxLength: 80 },
1597
+ kind: { type: "string", maxLength: 80 },
1598
+ agent: { type: "string", maxLength: 200 },
1599
+ model: { type: "string", maxLength: 200 },
1600
+ query: { type: "string", maxLength: 200 }
1601
+ };
1602
+ var PromptLogger = Rpc.define({
1603
+ id: "prompt-logger",
1604
+ methods: {
1605
+ status: {
1606
+ input: { type: "object", properties: {}, additionalProperties: false },
1607
+ output: {
1608
+ type: "object",
1609
+ properties: {
1610
+ version: { type: "number" },
1611
+ store: storeStatusSchema,
1612
+ settings: statusSettingsSchema,
1613
+ sessionScope: sessionScopeSchema,
1614
+ cache: cacheSchema,
1615
+ lastWriteAt: { anyOf: [{ type: "string" }, { type: "null" }] },
1616
+ lastWriteError: {
1617
+ anyOf: [
1618
+ { type: "null" },
1619
+ {
1620
+ type: "object",
1621
+ properties: {
1622
+ at: { type: "string" },
1623
+ code: { type: "string" },
1624
+ message: { type: "string" }
1625
+ },
1626
+ required: ["at", "message"],
1627
+ additionalProperties: false
1628
+ }
1629
+ ]
1630
+ }
1631
+ },
1632
+ required: ["version", "store", "settings", "sessionScope", "cache", "lastWriteAt", "lastWriteError"],
1633
+ additionalProperties: false
1634
+ },
1635
+ errors
1636
+ },
1637
+ list: {
1638
+ input: {
1639
+ type: "object",
1640
+ properties: {
1641
+ ...filtersSchema,
1642
+ limit: { type: "number" },
1643
+ cursor: { type: "string" }
1644
+ },
1645
+ additionalProperties: false
1646
+ },
1647
+ output: {
1648
+ type: "object",
1649
+ properties: {
1650
+ entries: { type: "array", items: summarySchema },
1651
+ hasMore: { type: "boolean" },
1652
+ records: { type: "number" },
1653
+ error: nullableString
1654
+ },
1655
+ required: ["entries", "hasMore", "records", "error"],
1656
+ additionalProperties: false
1657
+ },
1658
+ errors
1659
+ },
1660
+ read: {
1661
+ input: {
1662
+ type: "object",
1663
+ properties: {
1664
+ key: { type: "string", maxLength: 300 },
1665
+ maxBytes: { type: "number" }
1666
+ },
1667
+ required: ["key"],
1668
+ additionalProperties: false
1669
+ },
1670
+ output: {
1671
+ type: "object",
1672
+ properties: {
1673
+ record: {},
1674
+ bytes: { type: "number" },
1675
+ truncated: { type: "boolean" },
1676
+ moreAvailable: { type: "boolean" },
1677
+ fullBytes: { type: "number" },
1678
+ paths: {
1679
+ type: "object",
1680
+ properties: {
1681
+ session: { type: "string" },
1682
+ requests: { type: "string" },
1683
+ body: { type: "string" }
1684
+ },
1685
+ additionalProperties: false
1686
+ }
1687
+ },
1688
+ required: ["record", "bytes", "truncated"],
1689
+ additionalProperties: false
1690
+ },
1691
+ errors
1692
+ },
1693
+ search: {
1694
+ input: {
1695
+ type: "object",
1696
+ properties: {
1697
+ ...filtersSchema,
1698
+ query: { type: "string", minLength: 1, maxLength: 500 },
1699
+ limit: { type: "number" },
1700
+ ignoreCase: { type: "boolean" },
1701
+ budgetBytes: { type: "number" },
1702
+ budgetMs: { type: "number" }
1703
+ },
1704
+ required: ["query"],
1705
+ additionalProperties: false
1706
+ },
1707
+ output: {
1708
+ type: "object",
1709
+ properties: {
1710
+ matches: {
1711
+ type: "array",
1712
+ items: {
1713
+ type: "object",
1714
+ properties: { entry: summarySchema, snippet: { type: "string" } },
1715
+ required: ["entry", "snippet"],
1716
+ additionalProperties: false
1717
+ }
1718
+ },
1719
+ partial: { type: "boolean" },
1720
+ scannedBytes: { type: "number" },
1721
+ skipped: { type: "number" },
1722
+ error: nullableString
1723
+ },
1724
+ required: ["matches", "partial", "scannedBytes", "skipped", "error"],
1725
+ additionalProperties: false
1726
+ },
1727
+ errors
1728
+ },
1729
+ truncate: {
1730
+ input: {
1731
+ type: "object",
1732
+ properties: {
1733
+ target: { type: "string", enum: ["current", "all"] },
1734
+ sessionID: { type: "string", maxLength: 200 },
1735
+ confirm: { type: "boolean", enum: [true] }
1736
+ },
1737
+ required: ["target", "confirm"],
1738
+ additionalProperties: false
1739
+ },
1740
+ output: {
1741
+ type: "object",
1742
+ properties: {
1743
+ target: { type: "string", enum: ["current", "all"] },
1744
+ bytesFreed: { type: "number" }
1745
+ },
1746
+ required: ["target", "bytesFreed"],
1747
+ additionalProperties: false
1748
+ },
1749
+ errors
1750
+ },
1751
+ getSettings: {
1752
+ input: { type: "object", properties: {}, additionalProperties: false },
1753
+ output: settingsResponseSchema,
1754
+ errors
1755
+ },
1756
+ setSettings: {
1757
+ input: {
1758
+ type: "object",
1759
+ properties: { settings: settingsSchema },
1760
+ required: ["settings"],
1761
+ additionalProperties: false
1762
+ },
1763
+ output: settingsResponseSchema,
1764
+ errors
1765
+ },
1766
+ resetSettings: {
1767
+ input: { type: "object", properties: {}, additionalProperties: false },
1768
+ output: settingsResponseSchema,
1769
+ errors
1770
+ },
1771
+ updateSessionScope: {
1772
+ input: {
1773
+ type: "object",
1774
+ properties: {
1775
+ mode: { type: "string", enum: ["all", "only"] },
1776
+ action: { type: "string", enum: ["only", "disarm", "clear"] },
1777
+ sessionID: { type: "string", maxLength: 200 }
1778
+ },
1779
+ additionalProperties: false
1780
+ },
1781
+ output: {
1782
+ type: "object",
1783
+ properties: {
1784
+ sessionScope: sessionScopeSchema,
1785
+ settings: settingsSchema
1786
+ },
1787
+ required: ["sessionScope", "settings"],
1788
+ additionalProperties: false
1789
+ },
1790
+ errors
1791
+ }
1792
+ },
1793
+ events: {
1794
+ changed: {
1795
+ schema: {
1796
+ type: "object",
1797
+ properties: {
1798
+ store: { type: "string" },
1799
+ reason: { type: "string", enum: ["append", "truncate", "error"] },
1800
+ at: { type: "string" }
1801
+ },
1802
+ required: ["store", "reason", "at"],
1803
+ additionalProperties: false
1804
+ }
1805
+ },
1806
+ settingsChanged: {
1807
+ schema: settingsResponseSchema
1808
+ }
1809
+ }
1810
+ });
1811
+
1812
+ // src/session-scope.ts
1813
+ var SESSION_SCOPE_KEY = "sessionScope";
1814
+ var MAX_SESSION_SCOPE = 50;
1815
+ function emptySessionScope() {
1816
+ return { mode: "all", sessions: [], max: MAX_SESSION_SCOPE };
1817
+ }
1818
+ function parseSessionScope(value) {
1819
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1820
+ return emptySessionScope();
1821
+ }
1822
+ const record = value;
1823
+ const sessions = [];
1824
+ const seen = new Set;
1825
+ if (Array.isArray(record.sessions)) {
1826
+ for (const entry of record.sessions) {
1827
+ if (typeof entry !== "string")
1828
+ continue;
1829
+ const sessionID = entry.trim();
1830
+ if (sessionID === "" || sessionID.length > 200 || seen.has(sessionID))
1831
+ continue;
1832
+ seen.add(sessionID);
1833
+ sessions.push(sessionID);
1834
+ if (sessions.length >= MAX_SESSION_SCOPE)
1835
+ break;
1836
+ }
1837
+ }
1838
+ return {
1839
+ mode: record.mode === "only" ? "only" : "all",
1840
+ sessions,
1841
+ max: MAX_SESSION_SCOPE
1842
+ };
1843
+ }
1844
+ function sessionAllowed(scope, sessionID) {
1845
+ if (sessionID === undefined || sessionID === "")
1846
+ return false;
1847
+ return scope.mode === "all" || scope.sessions.includes(sessionID);
1848
+ }
1849
+ function isSelected(scope, sessionID) {
1850
+ if (scope === undefined || scope.mode !== "only" || sessionID === undefined)
1851
+ return false;
1852
+ return scope.sessions.includes(sessionID);
1853
+ }
1854
+ function scopeLabel(scope, enabled, sessionID) {
1855
+ if (!enabled)
1856
+ return "off";
1857
+ if (scope === undefined)
1858
+ return "unavailable";
1859
+ if (scope.mode === "all")
1860
+ return "all sessions";
1861
+ if (scope.sessions.length === 0)
1862
+ return "paused";
1863
+ if (sessionID !== undefined && isSelected(scope, sessionID))
1864
+ return "this session";
1865
+ return scope.sessions.length === 1 ? "1 session" : `${scope.sessions.length} sessions`;
1866
+ }
1867
+ function onlySession(scope, sessionID) {
1868
+ return { mode: "only", sessions: [sessionID], max: scope.max };
1869
+ }
1870
+ function removeSession(scope, sessionID) {
1871
+ return {
1872
+ mode: scope.mode,
1873
+ sessions: scope.sessions.filter((entry) => entry !== sessionID),
1874
+ max: scope.max
1875
+ };
1876
+ }
1877
+ function clearSessions(scope) {
1878
+ return { mode: "only", sessions: [], max: scope.max };
1879
+ }
1880
+ function allSessions(scope) {
1881
+ return { mode: "all", sessions: [], max: scope.max };
1882
+ }
1883
+ function changeSessionScope(scope, change) {
1884
+ const sessionID = change.sessionID?.trim() ?? "";
1885
+ if (change.action === "only")
1886
+ return sessionID === "" ? scope : onlySession(scope, sessionID);
1887
+ if (change.action === "disarm")
1888
+ return sessionID === "" ? scope : removeSession(scope, sessionID);
1889
+ if (change.action === "clear")
1890
+ return clearSessions(scope);
1891
+ if (change.mode === "all")
1892
+ return allSessions(scope);
1893
+ return { ...scope, mode: "only" };
1894
+ }
1895
+
1896
+ // src/runtime-state.ts
1897
+ var RUNTIME_REFRESH_MS = 1000;
1898
+ function createSlot(initial, read, parse, options) {
1899
+ let value = initial;
1900
+ let readAt = Number.NEGATIVE_INFINITY;
1901
+ let revision = 0;
1902
+ let inFlight = null;
1903
+ let inFlightId = 0;
1904
+ let callSeq = 0;
1905
+ let lastReadStart = 0;
1906
+ let lastError = null;
1907
+ const apply = (next) => {
1908
+ value = next;
1909
+ };
1910
+ const refresh = async (force = false) => {
1911
+ if (!force && options.now() - readAt < options.ttlMs)
1912
+ return;
1913
+ const call = ++callSeq;
1914
+ if (inFlight !== null) {
1915
+ await inFlight.catch(() => {});
1916
+ if (!force)
1917
+ return;
1918
+ if (lastReadStart > call)
1919
+ return;
1920
+ }
1921
+ if (!force && options.now() - readAt < options.ttlMs)
1922
+ return;
1923
+ const startedRevision = revision;
1924
+ const id = ++callSeq;
1925
+ lastReadStart = id;
1926
+ inFlightId = id;
1927
+ readAt = options.now();
1928
+ const pending = (async () => {
1929
+ try {
1930
+ const next = parse(await read());
1931
+ lastError = null;
1932
+ if (startedRevision !== revision)
1933
+ return;
1934
+ apply(next);
1935
+ } catch (error) {
1936
+ const message = error instanceof Error ? error.message : String(error);
1937
+ if (message !== lastError) {
1938
+ lastError = message;
1939
+ options.onError?.(error);
1940
+ }
1941
+ } finally {
1942
+ if (inFlightId === id) {
1943
+ inFlight = null;
1944
+ inFlightId = 0;
1945
+ }
1946
+ }
1947
+ })();
1948
+ inFlight = pending;
1949
+ return pending;
1950
+ };
1951
+ const set = (next) => {
1952
+ revision += 1;
1953
+ readAt = options.now();
1954
+ lastError = null;
1955
+ apply(next);
1956
+ };
1957
+ return {
1958
+ get value() {
1959
+ return value;
1960
+ },
1961
+ refresh,
1962
+ set,
1963
+ reset: () => set(initial)
1964
+ };
1965
+ }
1966
+ function createRuntimeState(initial, read, state = {}) {
1967
+ const ttlMs = state.ttlMs ?? RUNTIME_REFRESH_MS;
1968
+ const now = state.now ?? Date.now;
1969
+ const settings = createSlot(initial, read.settings, sanitizeSettings, {
1970
+ ttlMs,
1971
+ now,
1972
+ onError: (error) => state.onError?.("settings", error)
1973
+ });
1974
+ const scope = createSlot(emptySessionScope(), read.scope, parseSessionScope, {
1975
+ ttlMs,
1976
+ now,
1977
+ onError: (error) => state.onError?.("scope", error)
1978
+ });
1979
+ return {
1980
+ get settings() {
1981
+ return settings.value;
1982
+ },
1983
+ get scope() {
1984
+ return scope.value;
1985
+ },
1986
+ async refresh(force = false) {
1987
+ await Promise.all([settings.refresh(force), scope.refresh(force)]);
1988
+ },
1989
+ applySettings(next) {
1990
+ settings.set(next);
1991
+ },
1992
+ applyScope(next) {
1993
+ scope.set(next);
1994
+ },
1995
+ reset() {
1996
+ settings.reset();
1997
+ scope.reset();
1998
+ }
94
1999
  };
95
2000
  }
96
2001
 
97
2002
  // src/index.ts
2003
+ function rpcFailure(context, error) {
2004
+ if (error instanceof LogError) {
2005
+ return context.error(error.code, error.message, {});
2006
+ }
2007
+ return context.error("io", "the prompt store is unavailable", {});
2008
+ }
2009
+ function validSessionScopeInput(input) {
2010
+ if (input.mode !== undefined && input.mode !== "all" && input.mode !== "only")
2011
+ return false;
2012
+ if (input.action !== undefined && input.action !== "only" && input.action !== "disarm" && input.action !== "clear") {
2013
+ return false;
2014
+ }
2015
+ if (input.mode !== undefined && input.action !== undefined)
2016
+ return false;
2017
+ if (input.mode === undefined && input.action === undefined)
2018
+ return false;
2019
+ if (input.sessionID !== undefined) {
2020
+ if (typeof input.sessionID !== "string" || input.sessionID.length > 200)
2021
+ return false;
2022
+ }
2023
+ if (input.action === "only" || input.action === "disarm") {
2024
+ if (typeof input.sessionID !== "string" || input.sessionID.trim() === "")
2025
+ return false;
2026
+ }
2027
+ return true;
2028
+ }
98
2029
  var src_default = Plugin.define({
99
2030
  id: "prompt-logger",
100
2031
  async setup(ctx) {
101
- const options = ctx.options ?? {};
102
- if (!isEnabled(options))
103
- return;
104
- const write = createWriter(resolveFile(options), resolveRotateBytes(options));
105
- for (const kind of CONTEXT_KINDS) {
106
- await ctx.session.hook(kind, (event) => {
107
- write(assembledRecord(kind, event));
108
- });
2032
+ let initialSettings;
2033
+ try {
2034
+ const stored = await ctx.storage.get(SETTINGS_KEY);
2035
+ initialSettings = sanitizeSettings(stored);
2036
+ if (stored === undefined || !isValidSettings(stored)) {
2037
+ try {
2038
+ await ctx.storage.set(SETTINGS_KEY, initialSettings);
2039
+ } catch (error) {
2040
+ console.error(`prompt-logger: could not persist the initial settings: ${String(error)}`);
2041
+ }
2042
+ }
2043
+ } catch (error) {
2044
+ console.error(`prompt-logger: could not read settings: ${String(error)}`);
2045
+ initialSettings = sanitizeSettings(undefined);
109
2046
  }
110
- if (shouldLogHttp(options)) {
111
- await ctx.session.hook("http.request", async (event) => {
112
- write(await httpRecord(event));
113
- });
2047
+ const root = resolveLogDirectory(initialSettings.directory === "" ? undefined : initialSettings.directory, ctx.location?.directory);
2048
+ const runtime = createRuntimeState(initialSettings, {
2049
+ settings: async () => {
2050
+ const stored = await ctx.storage.get(SETTINGS_KEY);
2051
+ if (stored !== undefined)
2052
+ return stored;
2053
+ return initialSettings;
2054
+ },
2055
+ scope: () => ctx.storage.get(SESSION_SCOPE_KEY)
2056
+ }, {
2057
+ onError: (source, error) => {
2058
+ const label = source === "settings" ? "settings" : "the session scope";
2059
+ console.error(`prompt-logger: could not read ${label}: ${String(error)}`);
2060
+ }
2061
+ });
2062
+ await runtime.refresh(true);
2063
+ let lastWriteAt = null;
2064
+ let lastWriteError = null;
2065
+ let events = null;
2066
+ let notifyTimer = null;
2067
+ let pendingReason = null;
2068
+ const notify = (reason) => {
2069
+ if (!isV2Armed(root))
2070
+ return;
2071
+ pendingReason = reason;
2072
+ if (notifyTimer !== null)
2073
+ return;
2074
+ notifyTimer = setTimeout(() => {
2075
+ notifyTimer = null;
2076
+ const pending = pendingReason;
2077
+ pendingReason = null;
2078
+ if (events === null || pending === null)
2079
+ return;
2080
+ events.emit("changed", { store: root, reason: pending, at: new Date().toISOString() }).catch(() => {});
2081
+ }, EVENT_COALESCE_MS);
2082
+ notifyTimer.unref?.();
2083
+ };
2084
+ const emitSettings = async () => {
2085
+ if (events === null)
2086
+ return;
2087
+ try {
2088
+ await events.emit("settingsChanged", {
2089
+ settings: runtime.settings,
2090
+ sessionScope: runtime.scope
2091
+ });
2092
+ } catch {}
2093
+ };
2094
+ const reportError = (error) => {
2095
+ lastWriteError = {
2096
+ at: new Date().toISOString(),
2097
+ message: error instanceof Error ? error.message : String(error)
2098
+ };
2099
+ notify("error");
2100
+ };
2101
+ const writer = createV2Writer(root, {
2102
+ onWrite: (written) => {
2103
+ lastWriteAt = written.at;
2104
+ lastWriteError = null;
2105
+ notify("append");
2106
+ },
2107
+ onError: reportError
2108
+ });
2109
+ const registrations = [];
2110
+ for (const kind of CONTEXT_KINDS) {
2111
+ registrations.push(await ctx.session.hook(kind, async (event) => {
2112
+ await runtime.refresh();
2113
+ if (!runtime.settings.enabled)
2114
+ return;
2115
+ if (!sessionAllowed(runtime.scope, event.sessionID))
2116
+ return;
2117
+ writer.writeAssembled(kind, event);
2118
+ }));
114
2119
  }
2120
+ registrations.push(await ctx.session.hook("http.request", async (event) => {
2121
+ await runtime.refresh();
2122
+ if (!runtime.settings.enabled || !runtime.settings.http)
2123
+ return;
2124
+ if (!sessionAllowed(runtime.scope, event.sessionID))
2125
+ return;
2126
+ await writer.writeHttp(event);
2127
+ }));
2128
+ const retentionPolicy = () => resolveRetention(runtime.settings);
2129
+ const prune = async () => {
2130
+ await runtime.refresh();
2131
+ if (!runtime.settings.enabled)
2132
+ return;
2133
+ try {
2134
+ v2Prune(root, retentionPolicy(), writer.active);
2135
+ } catch (error) {
2136
+ console.error(`prompt-logger: retention failed: ${String(error)}`);
2137
+ }
2138
+ };
2139
+ const initialPrune = setTimeout(() => void prune(), 5000);
2140
+ initialPrune.unref?.();
2141
+ const pruneTimer = setInterval(() => void prune(), 60 * 60 * 1000);
2142
+ pruneTimer.unref?.();
2143
+ const registration = await ctx.rpc.register(PromptLogger, {
2144
+ status: async () => {
2145
+ await runtime.refresh(true);
2146
+ const settings = runtime.settings;
2147
+ const info = v2Status(root);
2148
+ const policy = retentionPolicy();
2149
+ const state = inspectPath(root);
2150
+ const stats = (() => {
2151
+ try {
2152
+ return statSync3(root);
2153
+ } catch {
2154
+ return null;
2155
+ }
2156
+ })();
2157
+ return {
2158
+ version: CONTRACT_VERSION,
2159
+ store: {
2160
+ path: root,
2161
+ exists: stats !== null,
2162
+ bytes: info.bytes,
2163
+ mtimeMs: stats?.mtimeMs ?? null,
2164
+ directory: stats?.isDirectory() ?? false,
2165
+ symlink: state.symlink,
2166
+ mode: state.mode,
2167
+ directoryMode: state.directoryMode,
2168
+ warnings: info.warnings
2169
+ },
2170
+ settings: {
2171
+ ...settings,
2172
+ retention: {
2173
+ maxTotalBytes: Number.isFinite(policy.maxTotalBytes) ? policy.maxTotalBytes : null,
2174
+ maxAgeDays: policy.maxAgeDays,
2175
+ maxSessions: Number.isFinite(policy.maxSessions) ? policy.maxSessions : null
2176
+ }
2177
+ },
2178
+ sessionScope: runtime.scope,
2179
+ cache: {
2180
+ requests: info.requests,
2181
+ requestBytes: info.requestBytes,
2182
+ lastScanMs: info.lastScanMs,
2183
+ error: info.error
2184
+ },
2185
+ lastWriteAt,
2186
+ lastWriteError
2187
+ };
2188
+ },
2189
+ list: async (input) => {
2190
+ return v2List(root, input);
2191
+ },
2192
+ read: async (input, context) => {
2193
+ try {
2194
+ const key = input.key;
2195
+ if (key === undefined) {
2196
+ return context.error("bad_request", "a read needs a key", {});
2197
+ }
2198
+ const result = v2Read(root, key, input.maxBytes);
2199
+ if (result.notFound)
2200
+ return context.error("not_found", "log entry not found", {});
2201
+ return {
2202
+ record: result.record,
2203
+ bytes: result.bytes,
2204
+ truncated: result.truncated,
2205
+ moreAvailable: result.moreAvailable,
2206
+ fullBytes: result.fullBytes,
2207
+ paths: result.paths
2208
+ };
2209
+ } catch (error) {
2210
+ return rpcFailure(context, error);
2211
+ }
2212
+ },
2213
+ search: async (input, context) => {
2214
+ try {
2215
+ return await v2Search(root, input, context.signal);
2216
+ } catch (error) {
2217
+ return rpcFailure(context, error);
2218
+ }
2219
+ },
2220
+ truncate: async (input, context) => {
2221
+ if (!runtime.settings.maintenance) {
2222
+ return context.error("forbidden", "delete actions are disabled", {});
2223
+ }
2224
+ try {
2225
+ const request = input;
2226
+ if (request.target === "current" && request.sessionID === undefined) {
2227
+ return context.error("bad_request", "sessionID is required to delete one session", {});
2228
+ }
2229
+ const bytesFreed = v2Delete(root, request.target, request.sessionID);
2230
+ invalidateV2(root);
2231
+ notify("truncate");
2232
+ return { target: request.target, bytesFreed };
2233
+ } catch (error) {
2234
+ return rpcFailure(context, error);
2235
+ }
2236
+ },
2237
+ getSettings: async () => {
2238
+ await runtime.refresh(true);
2239
+ return { settings: runtime.settings, sessionScope: runtime.scope };
2240
+ },
2241
+ setSettings: async (input, context) => {
2242
+ const request = input.settings;
2243
+ if (!isValidSettings(request))
2244
+ return context.error("bad_request", "invalid settings", {});
2245
+ const next = sanitizeSettings(request);
2246
+ await runtime.refresh(true);
2247
+ try {
2248
+ await ctx.storage.set(SETTINGS_KEY, next);
2249
+ } catch (error) {
2250
+ console.error(`prompt-logger: could not persist settings: ${String(error)}`);
2251
+ return context.error("io", "could not persist settings", {});
2252
+ }
2253
+ const wasEnabled = runtime.settings.enabled;
2254
+ runtime.applySettings(next);
2255
+ if (!wasEnabled && next.enabled)
2256
+ prune();
2257
+ await emitSettings();
2258
+ return { settings: runtime.settings, sessionScope: runtime.scope };
2259
+ },
2260
+ resetSettings: async (_input, context) => {
2261
+ const next = defaultSettings();
2262
+ try {
2263
+ await ctx.storage.set(SETTINGS_KEY, next);
2264
+ await ctx.storage.remove(SESSION_SCOPE_KEY);
2265
+ } catch (error) {
2266
+ console.error(`prompt-logger: could not reset settings: ${String(error)}`);
2267
+ return context.error("io", "could not reset settings", {});
2268
+ }
2269
+ const wasEnabled = runtime.settings.enabled;
2270
+ runtime.applySettings(next);
2271
+ runtime.applyScope(emptySessionScope());
2272
+ if (!wasEnabled && next.enabled)
2273
+ prune();
2274
+ await emitSettings();
2275
+ return { settings: runtime.settings, sessionScope: runtime.scope };
2276
+ },
2277
+ updateSessionScope: async (input, context) => {
2278
+ const request = input;
2279
+ if (!validSessionScopeInput(request)) {
2280
+ return context.error("bad_request", "invalid session scope", {});
2281
+ }
2282
+ await runtime.refresh(true);
2283
+ const next = changeSessionScope(runtime.scope, request);
2284
+ try {
2285
+ await ctx.storage.set(SESSION_SCOPE_KEY, { mode: next.mode, sessions: next.sessions });
2286
+ } catch (error) {
2287
+ console.error(`prompt-logger: could not persist the session scope: ${String(error)}`);
2288
+ return context.error("io", "could not persist the session scope", {});
2289
+ }
2290
+ runtime.applyScope(next);
2291
+ const wasEnabled = runtime.settings.enabled;
2292
+ if (request.action === "only" && !runtime.settings.enabled) {
2293
+ const nextSettings = { ...runtime.settings, enabled: true };
2294
+ try {
2295
+ await ctx.storage.set(SETTINGS_KEY, nextSettings);
2296
+ } catch (error) {
2297
+ console.error(`prompt-logger: could not persist settings: ${String(error)}`);
2298
+ return context.error("io", "could not persist settings", {});
2299
+ }
2300
+ runtime.applySettings(nextSettings);
2301
+ }
2302
+ if (!wasEnabled && runtime.settings.enabled)
2303
+ prune();
2304
+ await emitSettings();
2305
+ return { sessionScope: runtime.scope, settings: runtime.settings };
2306
+ }
2307
+ }).catch((error) => {
2308
+ console.error(`prompt-logger: could not register the viewer rpc: ${String(error)}`);
2309
+ return null;
2310
+ });
2311
+ if (registration !== null)
2312
+ events = registration.events;
2313
+ return async () => {
2314
+ if (notifyTimer !== null) {
2315
+ clearTimeout(notifyTimer);
2316
+ notifyTimer = null;
2317
+ }
2318
+ clearInterval(pruneTimer);
2319
+ clearTimeout(initialPrune);
2320
+ invalidateV2(root);
2321
+ disarmV2(root);
2322
+ await registration?.dispose();
2323
+ for (const hook of registrations)
2324
+ await hook.dispose();
2325
+ };
115
2326
  }
116
2327
  });
117
2328
  export {
118
2329
  src_default as default
119
2330
  };
120
2331
 
121
- //# debugId=31CC535C2A05F23364756E2164756E21
2332
+ //# debugId=917613547F8D31BB64756E2164756E21