@lune_99/pi-lune-extensions-core 0.1.0 → 0.2.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +117 -36
  3. package/dist/core/panel.d.ts +6 -1
  4. package/dist/core/panel.js +26 -1
  5. package/dist/core/settings.d.ts +9 -1
  6. package/dist/core/settings.js +36 -2
  7. package/dist/dock/registry.js +1 -0
  8. package/dist/extension.js +10 -2
  9. package/dist/mention/autocomplete.d.ts +25 -0
  10. package/dist/mention/autocomplete.js +140 -0
  11. package/dist/mention/budget.d.ts +8 -0
  12. package/dist/mention/budget.js +10 -0
  13. package/dist/mention/catalog.d.ts +43 -0
  14. package/dist/mention/catalog.js +117 -0
  15. package/dist/mention/claude.d.ts +2 -0
  16. package/dist/mention/claude.js +118 -0
  17. package/dist/mention/codex.d.ts +3 -0
  18. package/dist/mention/codex.js +135 -0
  19. package/dist/mention/external.d.ts +15 -0
  20. package/dist/mention/external.js +145 -0
  21. package/dist/mention/index.d.ts +17 -0
  22. package/dist/mention/index.js +151 -0
  23. package/dist/mention/jsonl.d.ts +9 -0
  24. package/dist/mention/jsonl.js +54 -0
  25. package/dist/mention/mention.d.ts +19 -0
  26. package/dist/mention/mention.js +60 -0
  27. package/dist/mention/pi.d.ts +11 -0
  28. package/dist/mention/pi.js +172 -0
  29. package/dist/mention/session-index.d.ts +66 -0
  30. package/dist/mention/session-index.js +303 -0
  31. package/dist/mention/session.d.ts +18 -0
  32. package/dist/mention/session.js +8 -0
  33. package/dist/mention/text.d.ts +12 -0
  34. package/dist/mention/text.js +47 -0
  35. package/dist/mention/transcript.d.ts +10 -0
  36. package/dist/mention/transcript.js +129 -0
  37. package/dist/panel/defined-section.js +34 -8
  38. package/dist/panel/definition.d.ts +26 -1
  39. package/dist/panel/definition.js +32 -2
  40. package/dist/panel/index.d.ts +3 -2
  41. package/dist/panel/index.js +1 -0
  42. package/dist/panel/panel.js +109 -29
  43. package/dist/panel/section.d.ts +49 -3
  44. package/dist/panel/section.js +59 -12
  45. package/dist/resources/scoped-extension.js +1 -0
  46. package/dist/settings/file-store.js +1 -0
  47. package/docs/dock.md +9 -3
  48. package/docs/panel.md +69 -2
  49. package/docs/public-api-design.md +9 -9
  50. package/docs/recipes.md +3 -8
  51. package/docs/settings.md +1 -1
  52. package/package.json +4 -4
  53. package/src/core/panel.ts +29 -1
  54. package/src/core/settings.ts +42 -2
  55. package/src/dock/registry.ts +1 -0
  56. package/src/extension.ts +11 -2
  57. package/src/mention/autocomplete.ts +177 -0
  58. package/src/mention/budget.ts +11 -0
  59. package/src/mention/catalog.ts +133 -0
  60. package/src/mention/claude.ts +127 -0
  61. package/src/mention/codex.ts +144 -0
  62. package/src/mention/external.ts +190 -0
  63. package/src/mention/index.ts +193 -0
  64. package/src/mention/jsonl.ts +56 -0
  65. package/src/mention/mention.ts +90 -0
  66. package/src/mention/pi.ts +192 -0
  67. package/src/mention/session-index.ts +356 -0
  68. package/src/mention/session.ts +27 -0
  69. package/src/mention/text.ts +52 -0
  70. package/src/mention/transcript.ts +155 -0
  71. package/src/panel/defined-section.ts +40 -7
  72. package/src/panel/definition.ts +67 -2
  73. package/src/panel/index.ts +4 -0
  74. package/src/panel/panel.ts +115 -29
  75. package/src/panel/section.ts +111 -15
  76. package/src/resources/scoped-extension.ts +1 -0
  77. package/src/settings/file-store.ts +1 -0
@@ -0,0 +1,56 @@
1
+ export type JsonObject = Record<string, unknown>;
2
+
3
+ export function object(value: unknown): JsonObject {
4
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
5
+ throw new Error("Expected a JSON object");
6
+ }
7
+ return value as JsonObject;
8
+ }
9
+
10
+ /** Parse one record at a time so large tool payloads are not all retained with the messages. */
11
+ export function* jsonl(content: string, path: string): Generator<JsonObject> {
12
+ let start = 0;
13
+ let line = 0;
14
+ while (start < content.length) {
15
+ const end = content.indexOf("\n", start);
16
+ const text = content.slice(start, end === -1 ? content.length : end);
17
+ start = end === -1 ? content.length : end + 1;
18
+ line++;
19
+ if (!text.trim()) continue;
20
+ try {
21
+ yield object(JSON.parse(text));
22
+ } catch (error) {
23
+ throw new Error(`Invalid JSONL at ${path}:${line}`, { cause: error });
24
+ }
25
+ }
26
+ }
27
+
28
+ export function string(value: unknown, field: string): string {
29
+ if (typeof value !== "string") throw new Error(`Expected a string for ${field}`);
30
+ return value;
31
+ }
32
+
33
+ export function sessionId(value: unknown, field: string): string {
34
+ const id = string(value, field);
35
+ // Ids become mention tokens and temporary filenames, so path separators are never valid.
36
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
37
+ throw new Error(`Invalid session id for ${field}`);
38
+ }
39
+ return id;
40
+ }
41
+
42
+ export function date(value: unknown, field: string): Date {
43
+ const parsed = new Date(string(value, field));
44
+ if (!Number.isFinite(parsed.getTime())) throw new Error(`Invalid date for ${field}`);
45
+ return parsed;
46
+ }
47
+
48
+ /** Only text blocks belong in the reference; images, thinking and tool payloads stay in JSONL. */
49
+ export function textContent(value: unknown, types: readonly string[]): string {
50
+ if (!Array.isArray(value)) throw new Error("Expected an array of content blocks");
51
+ return value
52
+ .map((part: unknown) => object(part))
53
+ .filter((part) => types.includes(string(part.type, "content.type")))
54
+ .map((part) => string(part.text, "content.text"))
55
+ .join("\n");
56
+ }
@@ -0,0 +1,90 @@
1
+ import type { LocalSession, SessionSource } from "./session.ts";
2
+ import { TOKEN_BOUNDARY } from "./text.ts";
3
+
4
+ export const TOKEN_PREFIX = "@session:";
5
+ const TOKEN_PREFIXES: Record<SessionSource, string> = {
6
+ pi: TOKEN_PREFIX,
7
+ codex: "@codex:",
8
+ claude: "@claude:",
9
+ };
10
+
11
+ /** UUIDv7 ids carry the creation time in their first 12 hex digits (`01a14931-31bb`). */
12
+ const MIN_ID_LENGTH = 13;
13
+
14
+ // Session ids follow pi's assertValidSessionId(): alphanumeric at both ends, `._-` inside.
15
+ const mentionPattern = new RegExp(
16
+ `(?<=${TOKEN_BOUNDARY})@(session|codex|claude):([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)`,
17
+ "gu",
18
+ );
19
+
20
+ export interface Mention {
21
+ /** Offset of the source-specific token in the text. */
22
+ index: number;
23
+ token: string;
24
+ source: SessionSource;
25
+ idPrefix: string;
26
+ }
27
+
28
+ /** The shortest id prefix, from MIN_ID_LENGTH up, that names only this session. */
29
+ export function shortSessionId(id: string, sessions: readonly LocalSession[]): string {
30
+ for (let length = Math.min(MIN_ID_LENGTH, id.length); length < id.length; length++) {
31
+ const prefix = id.slice(0, length);
32
+ if (!/[A-Za-z0-9]$/.test(prefix)) continue;
33
+ if (sessions.every((other) => other.id === id || !other.id.startsWith(prefix))) {
34
+ return prefix;
35
+ }
36
+ }
37
+ return id;
38
+ }
39
+
40
+ export function mentionToken(session: LocalSession, sessions: readonly LocalSession[]): string {
41
+ const sameSource = sessions.filter((other) => other.source === session.source);
42
+ return `${TOKEN_PREFIXES[session.source]}${shortSessionId(session.id, sameSource)}`;
43
+ }
44
+
45
+ export function findMentions(text: string): Mention[] {
46
+ return [...text.matchAll(mentionPattern)].map((match) => ({
47
+ index: match.index,
48
+ token: match[0],
49
+ source: match[1] === "session" ? "pi" : (match[1] as SessionSource),
50
+ idPrefix: match[2]!,
51
+ }));
52
+ }
53
+
54
+ /** Throws when the prefix names no session or more than one. */
55
+ export function resolveMention(
56
+ mention: Pick<Mention, "source" | "idPrefix">,
57
+ sessions: readonly LocalSession[],
58
+ ): LocalSession {
59
+ const { source, idPrefix } = mention;
60
+ const token = `${TOKEN_PREFIXES[source]}${idPrefix}`;
61
+ const matches = sessions.filter(
62
+ (session) => session.source === source && session.id.startsWith(idPrefix),
63
+ );
64
+ if (matches.length === 1) return matches[0]!;
65
+ throw new Error(
66
+ matches.length === 0
67
+ ? `No local session matches ${token}`
68
+ : `${token} matches ${matches.length} sessions; type more of the id`,
69
+ );
70
+ }
71
+
72
+ /** Replace each mention with the editor text for its file, keeping all other text. */
73
+ export function replaceMentions(
74
+ text: string,
75
+ mentions: readonly Mention[],
76
+ replacement: (mention: Mention) => string,
77
+ ): string {
78
+ let result = "";
79
+ let offset = 0;
80
+ for (const mention of mentions) {
81
+ result += text.slice(offset, mention.index) + replacement(mention);
82
+ offset = mention.index + mention.token.length;
83
+ }
84
+ return result + text.slice(offset);
85
+ }
86
+
87
+ /** Pi's `@` file reference, quoted like its own completion when the path has whitespace. */
88
+ export function fileReference(path: string): string {
89
+ return /\s/u.test(path) ? `@"${path}"` : `@${path}`;
90
+ }
@@ -0,0 +1,192 @@
1
+ import { createReadStream, type Stats } from "node:fs";
2
+ import { readdir, stat } from "node:fs/promises";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import type { SessionFile } from "./session-index.ts";
7
+ import type { LocalSession } from "./session.ts";
8
+
9
+ /**
10
+ * Pi session files whose sessions have the fields `SessionManager.listAll` builds.
11
+ * listAll keeps no cache and reads every file again on each call; these are read through
12
+ * the index.
13
+ */
14
+ export class PiSessions {
15
+ private readonly sessionDir: string;
16
+
17
+ constructor(sessionDir: string) {
18
+ this.sessionDir = sessionDir;
19
+ }
20
+
21
+ async list(signal: AbortSignal): Promise<SessionFile[]> {
22
+ return (await sessionFiles(this.sessionDir, signal)).map(({ path, stats }) => ({
23
+ path,
24
+ stats,
25
+ label: "Pi",
26
+ read: (readSignal) => readSession(path, stats, readSignal),
27
+ }));
28
+ }
29
+ }
30
+
31
+ interface StatFile {
32
+ path: string;
33
+ stats: Stats;
34
+ }
35
+
36
+ /**
37
+ * Matches the "all" scope of /resume: the default store keeps one folder per project under
38
+ * the agent's sessions root, and a custom session directory holds every session itself.
39
+ * The order is listAll's, so sessions with equal activity times keep its order.
40
+ */
41
+ async function sessionFiles(sessionDir: string, signal: AbortSignal): Promise<StatFile[]> {
42
+ const root = join(getAgentDir(), "sessions");
43
+ if (sessionDir !== "" && resolve(dirname(sessionDir)) !== resolve(root)) {
44
+ const names = (await jsonlFiles(sessionDir)).sort((a, b) => b.localeCompare(a));
45
+ return withStats(
46
+ names.map((name) => join(sessionDir, name)),
47
+ signal,
48
+ );
49
+ }
50
+ let projects: string[];
51
+ try {
52
+ projects = (await readdir(root, { withFileTypes: true }))
53
+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
54
+ .map((entry) => join(root, entry.name));
55
+ } catch (error) {
56
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
57
+ throw error;
58
+ }
59
+ const paths = await Promise.all(
60
+ projects.map(async (project) =>
61
+ (await jsonlFiles(project)).map((name) => join(project, name)),
62
+ ),
63
+ );
64
+ const files = await withStats(paths.flat(), signal);
65
+ return files.sort(
66
+ (a, b) =>
67
+ b.stats.mtimeMs - a.stats.mtimeMs || basename(b.path).localeCompare(basename(a.path)),
68
+ );
69
+ }
70
+
71
+ async function jsonlFiles(directory: string): Promise<string[]> {
72
+ try {
73
+ return (await readdir(directory)).filter((name) => name.endsWith(".jsonl"));
74
+ } catch (error) {
75
+ // A project entry may be a link to a file, and a custom store may not exist yet.
76
+ const code = (error as NodeJS.ErrnoException).code;
77
+ if (code === "ENOENT" || code === "ENOTDIR") return [];
78
+ throw error;
79
+ }
80
+ }
81
+
82
+ async function withStats(paths: readonly string[], signal: AbortSignal): Promise<StatFile[]> {
83
+ const files = await Promise.all(
84
+ paths.map(async (path) => {
85
+ try {
86
+ return { path, stats: await stat(path) };
87
+ } catch (error) {
88
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
89
+ throw error;
90
+ }
91
+ }),
92
+ );
93
+ signal.throwIfAborted();
94
+ return files.filter((file) => file !== undefined);
95
+ }
96
+
97
+ /** Pi's buildSessionInfo, field for field; undefined where it returns null. */
98
+ async function readSession(
99
+ path: string,
100
+ stats: Stats,
101
+ signal: AbortSignal,
102
+ ): Promise<LocalSession | undefined> {
103
+ let header: Record<string, unknown> | undefined;
104
+ let name: string | undefined;
105
+ let messageCount = 0;
106
+ let firstMessage = "";
107
+ let lastActivity: number | undefined;
108
+ const texts: string[] = [];
109
+ const lines = createInterface({
110
+ input: createReadStream(path, { encoding: "utf8", signal }),
111
+ crlfDelay: Infinity,
112
+ });
113
+ for await (const line of lines) {
114
+ const entry = parseLine(line);
115
+ if (!entry) continue;
116
+ if (!header) {
117
+ if (entry["type"] !== "session" || typeof entry["id"] !== "string") return undefined;
118
+ header = entry;
119
+ continue;
120
+ }
121
+ if (entry["type"] === "session_info") {
122
+ const value = entry["name"];
123
+ name = (typeof value === "string" ? value.trim() : "") || undefined;
124
+ }
125
+ if (entry["type"] !== "message") continue;
126
+ messageCount++;
127
+ const message = entry["message"];
128
+ if (!isRecord(message) || !("content" in message)) continue;
129
+ if (message["role"] !== "user" && message["role"] !== "assistant") continue;
130
+ const timestamp = message["timestamp"];
131
+ const activity = typeof timestamp === "number" ? timestamp : timeOf(entry["timestamp"]);
132
+ if (activity !== undefined) lastActivity = Math.max(lastActivity ?? 0, activity);
133
+ const text = textOf(message["content"]);
134
+ if (!text) continue;
135
+ texts.push(text);
136
+ if (!firstMessage && message["role"] === "user") firstMessage = text;
137
+ }
138
+ if (!header) return undefined;
139
+ const headerTime =
140
+ typeof header["timestamp"] === "string" ? timeOf(header["timestamp"]) : undefined;
141
+ const parent = header["parentSession"];
142
+ return {
143
+ source: "pi",
144
+ path,
145
+ id: header["id"] as string,
146
+ cwd: typeof header["cwd"] === "string" ? header["cwd"] : "",
147
+ name,
148
+ parentSessionPath: typeof parent === "string" ? parent : undefined,
149
+ created: new Date(header["timestamp"] as string),
150
+ modified:
151
+ lastActivity !== undefined && lastActivity > 0
152
+ ? new Date(lastActivity)
153
+ : headerTime !== undefined
154
+ ? new Date(headerTime)
155
+ : stats.mtime,
156
+ messageCount,
157
+ firstMessage: firstMessage || "(no messages)",
158
+ allMessagesText: texts.join(" "),
159
+ };
160
+ }
161
+
162
+ // Pi skips malformed lines too; the last line can be cut off while Pi appends to the file.
163
+ function parseLine(line: string): Record<string, unknown> | undefined {
164
+ if (!line.trim()) return undefined;
165
+ try {
166
+ const entry: unknown = JSON.parse(line);
167
+ return isRecord(entry) ? entry : undefined;
168
+ } catch {
169
+ return undefined;
170
+ }
171
+ }
172
+
173
+ function textOf(content: unknown): string {
174
+ if (typeof content === "string") return content;
175
+ if (!Array.isArray(content)) return "";
176
+ return content
177
+ .filter(
178
+ (block): block is Record<string, unknown> =>
179
+ isRecord(block) && block["type"] === "text",
180
+ )
181
+ .map((block) => block["text"])
182
+ .join(" ");
183
+ }
184
+
185
+ function timeOf(value: unknown): number | undefined {
186
+ const time = new Date(value as string).getTime();
187
+ return Number.isNaN(time) ? undefined : time;
188
+ }
189
+
190
+ function isRecord(value: unknown): value is Record<string, unknown> {
191
+ return typeof value === "object" && value !== null && !Array.isArray(value);
192
+ }
@@ -0,0 +1,356 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import type { Stats } from "node:fs";
3
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { dirname, join } from "node:path";
5
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6
+ import { INDEX_BUDGET_MB, megabytes, SESSION_TEXT_LIMIT } from "./budget.ts";
7
+ import { SOURCE_NAMES, type LocalSession } from "./session.ts";
8
+
9
+ /** Raise when the stored shape or what a reader takes from a session file changes. */
10
+ const FORMAT = 3;
11
+ /**
12
+ * The default budget; Core settings let the user change it. The newest sessions whose entries
13
+ * fit are indexed and listed; older ones are neither read nor listed.
14
+ */
15
+ export const INDEX_BUDGET_BYTES = megabytes(INDEX_BUDGET_MB);
16
+ const STRING_FIELDS = ["path", "id", "cwd", "firstMessage", "allMessagesText"] as const;
17
+ const OPTIONAL_STRING_FIELDS = ["name", "parentSessionPath"] as const;
18
+ const DATE_FIELDS = ["created", "modified"] as const;
19
+
20
+ export function sessionIndexFile(agentDir = getAgentDir()): string {
21
+ return join(agentDir, "lune-cache", "session-index.json");
22
+ }
23
+
24
+ /** A file with the same inode, size and modification time reads the same. */
25
+ export function fileVersion(stats: Stats): string {
26
+ return `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
27
+ }
28
+
29
+ /** A session file a source found, read only when the index has no entry for its version. */
30
+ export interface SessionFile {
31
+ readonly path: string;
32
+ readonly stats: Stats;
33
+ /** Names the source in read errors. */
34
+ readonly label: string;
35
+ /** The session in the file; undefined when the file holds none to list. */
36
+ read(signal: AbortSignal): Promise<LocalSession | undefined>;
37
+ /** The session with state kept outside its file, such as a Codex title, applied. */
38
+ current?(session: LocalSession): LocalSession;
39
+ /** Invalidates an omitted entry's size when state outside its file changes. */
40
+ readonly currentVersion?: string;
41
+ }
42
+
43
+ export interface SessionScan {
44
+ /** The listed sessions, in the order of the files. */
45
+ sessions: LocalSession[];
46
+ errors: Error[];
47
+ }
48
+
49
+ interface IndexEntry {
50
+ version: string;
51
+ /** Absent for a file without a listable session, so it is not read again until it changes. */
52
+ session?: LocalSession;
53
+ /**
54
+ * Set for the first file that did not fit the budget. Only its size is kept, so later
55
+ * scans stop there without reading it until it changes or room is freed.
56
+ */
57
+ omitted?: true;
58
+ currentVersion?: string;
59
+ /** Bytes the full entry takes in JSON, including a separating comma. */
60
+ bytes: number;
61
+ }
62
+
63
+ /**
64
+ * What the catalog read from each session file, saved so that a new Pi session or process
65
+ * reads only the files that changed since. Listing reads every file in full, and the session
66
+ * stores reach gigabytes because of tool output the list never uses.
67
+ *
68
+ * Every load and every changed scan reads or writes the whole index, so it holds only the
69
+ * newest sessions that fit its budget, with their text clipped to the configured limit.
70
+ *
71
+ * Several Pi processes share the file. Each writes a complete index and renames it into
72
+ * place, so readers always see a whole index and the last writer wins.
73
+ */
74
+ export class SessionIndex {
75
+ private readonly file: string;
76
+ /**
77
+ * Bytes the entries of a scan may take. A smaller budget drops the oldest entries at the
78
+ * next scan; a larger one reads the files the last scan left out.
79
+ */
80
+ budget: number;
81
+ textLimit: number;
82
+ private entries = new Map<string, IndexEntry>();
83
+ private indexedTextLimit: number | undefined;
84
+ private loaded = false;
85
+ private changed = false;
86
+
87
+ constructor(file: string, budget = INDEX_BUDGET_BYTES, textLimit = SESSION_TEXT_LIMIT) {
88
+ this.file = file;
89
+ this.budget = budget;
90
+ this.textLimit = textLimit;
91
+ }
92
+
93
+ /**
94
+ * Reads the saved index once. A missing file or another format starts empty; an invalid
95
+ * one is reported and replaced by the next save.
96
+ */
97
+ async load(signal: AbortSignal): Promise<void> {
98
+ if (this.loaded) return;
99
+ this.loaded = true;
100
+ let content: string;
101
+ try {
102
+ content = await readFile(this.file, { encoding: "utf8", signal });
103
+ } catch (error) {
104
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
105
+ throw error;
106
+ }
107
+ try {
108
+ const stored = parseIndex(content);
109
+ if (stored) {
110
+ this.entries = stored.entries;
111
+ this.indexedTextLimit = stored.textLimit;
112
+ } else {
113
+ this.changed = true;
114
+ }
115
+ } catch (error) {
116
+ this.changed = true;
117
+ const reason = error instanceof Error ? error.message : String(error);
118
+ throw new Error(`${this.file}: unreadable session index, rebuilding it: ${reason}`, {
119
+ cause: error,
120
+ });
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Lists the sessions of the newest files, by modification time, until the next one does
126
+ * not fit the budget. Files the index lacks are read one at a time, which bounds memory
127
+ * for large rollouts and keeps the order. Entries for every other file are dropped.
128
+ */
129
+ async scan(files: readonly SessionFile[], signal: AbortSignal): Promise<SessionScan> {
130
+ signal.throwIfAborted();
131
+ if (this.indexedTextLimit !== this.textLimit) {
132
+ // A larger limit needs text that the saved entries no longer contain.
133
+ this.changed ||= this.indexedTextLimit !== undefined;
134
+ this.entries.clear();
135
+ this.indexedTextLimit = this.textLimit;
136
+ }
137
+ const sessions = new Array<LocalSession | undefined>(files.length);
138
+ const errors: Error[] = [];
139
+ const kept = new Map<string, IndexEntry>();
140
+ const newestFirst = files
141
+ .map((_, position) => position)
142
+ .sort((left, right) => files[right]!.stats.mtimeMs - files[left]!.stats.mtimeMs);
143
+ let used = Buffer.byteLength(serializeIndex(new Map(), this.textLimit));
144
+ for (const position of newestFirst) {
145
+ signal.throwIfAborted();
146
+ const file = files[position]!;
147
+ const version = fileVersion(file.stats);
148
+ const stored = this.entries.get(file.path);
149
+ let entry = stored?.version === version ? stored : undefined;
150
+ if (
151
+ !entry ||
152
+ (entry.omitted &&
153
+ (used + entry.bytes - Number(kept.size === 0) <= this.budget ||
154
+ entry.currentVersion !== file.currentVersion))
155
+ ) {
156
+ let session: LocalSession | undefined;
157
+ try {
158
+ session = await file.read(signal);
159
+ } catch (error) {
160
+ signal.throwIfAborted();
161
+ // Removed since the directory was listed.
162
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
163
+ const message = error instanceof Error ? error.message : String(error);
164
+ errors.push(
165
+ new Error(`${file.label}: ${file.path}: ${message}`, { cause: error }),
166
+ );
167
+ continue;
168
+ }
169
+ entry = indexEntry(file.path, version, session && clipped(session, this.textLimit));
170
+ }
171
+ if (entry.session && file.current) {
172
+ const session = file.current(entry.session);
173
+ if (session !== entry.session) entry = indexEntry(file.path, version, session);
174
+ }
175
+ const separator = Number(kept.size === 0);
176
+ if (used + entry.bytes - separator > this.budget) {
177
+ if (!entry.omitted) {
178
+ entry = {
179
+ version,
180
+ omitted: true,
181
+ bytes: entry.bytes,
182
+ currentVersion: file.currentVersion,
183
+ };
184
+ }
185
+ const markerBytes = serializedEntryBytes(file.path, {
186
+ version,
187
+ omittedBytes: entry.bytes,
188
+ currentVersion: entry.currentVersion,
189
+ });
190
+ // A boundary marker must not push the index beyond its configured size.
191
+ if (used + markerBytes - separator <= this.budget) kept.set(file.path, entry);
192
+ break;
193
+ }
194
+ used += entry.bytes - separator;
195
+ kept.set(file.path, entry);
196
+ sessions[position] = entry.session;
197
+ }
198
+ if (
199
+ kept.size !== this.entries.size ||
200
+ [...kept].some(([path, entry]) => this.entries.get(path) !== entry)
201
+ ) {
202
+ this.changed = true;
203
+ }
204
+ this.entries = kept;
205
+ return { sessions: sessions.filter((session) => session !== undefined), errors };
206
+ }
207
+
208
+ /** Writes the index if the last scan changed it. */
209
+ async save(): Promise<void> {
210
+ if (!this.changed) return;
211
+ const content = serializeIndex(this.entries, this.textLimit);
212
+ await mkdir(dirname(this.file), { recursive: true, mode: 0o700 });
213
+ const temporary = `${this.file}.${process.pid}.${randomUUID()}.tmp`;
214
+ try {
215
+ // Owner-only: the index holds the message text of every listed session.
216
+ await writeFile(temporary, content, { encoding: "utf8", mode: 0o600 });
217
+ await rename(temporary, this.file);
218
+ } catch (error) {
219
+ await rm(temporary, { force: true });
220
+ throw error;
221
+ }
222
+ this.changed = false;
223
+ }
224
+ }
225
+
226
+ function indexEntry(path: string, version: string, session?: LocalSession): IndexEntry {
227
+ return session
228
+ ? { version, session, bytes: entryBytes(path, version, session) }
229
+ : { version, bytes: entryBytes(path, version) };
230
+ }
231
+
232
+ function entryBytes(path: string, version: string, session?: LocalSession): number {
233
+ return serializedEntryBytes(
234
+ path,
235
+ session ? { version, session: storedSession(session) } : { version },
236
+ );
237
+ }
238
+
239
+ function serializedEntryBytes(path: string, value: unknown): number {
240
+ return Buffer.byteLength(JSON.stringify(path)) + Buffer.byteLength(JSON.stringify(value)) + 2;
241
+ }
242
+
243
+ function clipped(session: LocalSession, limit: number): LocalSession {
244
+ const firstMessage = clip(session.firstMessage, limit);
245
+ const allMessagesText = clip(session.allMessagesText, limit);
246
+ return firstMessage === session.firstMessage && allMessagesText === session.allMessagesText
247
+ ? session
248
+ : { ...session, firstMessage, allMessagesText };
249
+ }
250
+
251
+ function clip(text: string, limit: number): string {
252
+ if (text.length <= limit) return text;
253
+ const last = text.charCodeAt(limit - 1);
254
+ // Never keep half of a surrogate pair.
255
+ return text.slice(0, last >= 0xd800 && last <= 0xdbff ? limit - 1 : limit);
256
+ }
257
+
258
+ function serializeIndex(entries: ReadonlyMap<string, IndexEntry>, textLimit: number): string {
259
+ const files: Record<string, unknown> = {};
260
+ for (const [path, { version, session, omitted, bytes, currentVersion }] of entries) {
261
+ files[path] = omitted
262
+ ? { version, omittedBytes: bytes, currentVersion }
263
+ : session
264
+ ? { version, session: storedSession(session) }
265
+ : { version };
266
+ }
267
+ return JSON.stringify({ format: FORMAT, textLimit, files });
268
+ }
269
+
270
+ // JSON drops undefined values, but the readers set `name` and `parentSessionPath` keys that
271
+ // may hold undefined. Null keeps the key, so a stored session equals a fresh read.
272
+ function storedSession(session: LocalSession): Record<string, unknown> {
273
+ return Object.fromEntries(
274
+ Object.entries(session).map(([key, value]) => [
275
+ key,
276
+ value instanceof Date ? value.getTime() : (value ?? null),
277
+ ]),
278
+ );
279
+ }
280
+
281
+ function parseIndex(
282
+ content: string,
283
+ ): { entries: Map<string, IndexEntry>; textLimit: number } | undefined {
284
+ const entries = new Map<string, IndexEntry>();
285
+ const stored: unknown = JSON.parse(content);
286
+ if (!isRecord(stored) || typeof stored["format"] !== "number") {
287
+ throw new Error("missing format");
288
+ }
289
+ if (stored["format"] !== FORMAT) return undefined;
290
+ const textLimit = stored["textLimit"];
291
+ if (typeof textLimit !== "number" || !Number.isInteger(textLimit) || textLimit < 1) {
292
+ throw new Error("invalid textLimit");
293
+ }
294
+ const files = stored["files"];
295
+ if (!isRecord(files)) throw new Error("missing files");
296
+ for (const [path, value] of Object.entries(files)) {
297
+ if (!isRecord(value) || typeof value["version"] !== "string") {
298
+ throw new Error(`invalid entry for ${path}`);
299
+ }
300
+ const version = value["version"];
301
+ const omittedBytes = value["omittedBytes"];
302
+ if (omittedBytes !== undefined) {
303
+ if (typeof omittedBytes !== "number" || !(omittedBytes >= 0)) {
304
+ throw new Error(`invalid omittedBytes for ${path}`);
305
+ }
306
+ const currentVersion = value["currentVersion"];
307
+ if (currentVersion !== undefined && typeof currentVersion !== "string") {
308
+ throw new Error(`invalid currentVersion for ${path}`);
309
+ }
310
+ entries.set(path, { version, omitted: true, bytes: omittedBytes, currentVersion });
311
+ continue;
312
+ }
313
+ entries.set(
314
+ path,
315
+ indexEntry(
316
+ path,
317
+ version,
318
+ value["session"] === undefined
319
+ ? undefined
320
+ : restoredSession(value["session"], path),
321
+ ),
322
+ );
323
+ }
324
+ return { entries, textLimit };
325
+ }
326
+
327
+ function restoredSession(value: unknown, path: string): LocalSession {
328
+ const invalid = (field: string) => new Error(`invalid ${field} for ${path}`);
329
+ if (!isRecord(value)) throw invalid("session");
330
+ const session: Record<string, unknown> = { ...value };
331
+ for (const field of STRING_FIELDS) {
332
+ if (typeof value[field] !== "string") throw invalid(field);
333
+ }
334
+ if (typeof value["messageCount"] !== "number") throw invalid("messageCount");
335
+ const source = value["source"];
336
+ if (typeof source !== "string" || !Object.hasOwn(SOURCE_NAMES, source)) {
337
+ throw invalid("source");
338
+ }
339
+ for (const field of OPTIONAL_STRING_FIELDS) {
340
+ if (!Object.hasOwn(value, field)) continue;
341
+ const text = value[field];
342
+ if (text !== null && typeof text !== "string") throw invalid(field);
343
+ session[field] = text ?? undefined;
344
+ }
345
+ for (const field of DATE_FIELDS) {
346
+ const time = value[field];
347
+ // An invalid date is stored as NaN, which JSON writes as null.
348
+ if (time !== null && typeof time !== "number") throw invalid(field);
349
+ session[field] = new Date(time ?? Number.NaN);
350
+ }
351
+ return session as unknown as LocalSession;
352
+ }
353
+
354
+ function isRecord(value: unknown): value is Record<string, unknown> {
355
+ return typeof value === "object" && value !== null && !Array.isArray(value);
356
+ }