@lune_99/pi-lune-extensions-core 0.2.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.
@@ -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
+ }
@@ -716,11 +716,15 @@ class SettingsPanel implements Component, Focusable {
716
716
  // Side-by-side preview needs room; below this width it is stacked under the list.
717
717
  const split = width >= 88 && !this.input && !!field?.preview;
718
718
  const bodyWidth = split ? Math.floor((width - 3) / 2) : width;
719
- let body = this.input
720
- ? this.input.render(bodyWidth)
721
- : this.customEditor
722
- ? this.renderCustomEditor(bodyWidth)
723
- : (this.choiceEditor?.renderBody(bodyWidth) ?? this.list?.render(bodyWidth) ?? []);
719
+ let body = [
720
+ ...(this.input
721
+ ? this.input.render(bodyWidth)
722
+ : this.customEditor
723
+ ? this.renderCustomEditor(bodyWidth)
724
+ : (this.choiceEditor?.renderBody(bodyWidth) ??
725
+ this.list?.render(bodyWidth) ??
726
+ [])),
727
+ ];
724
728
  if (!this.sections.length)
725
729
  body = [this.theme.fg("muted", "No extensions have registered settings.")];
726
730
  else if (this.section?.unavailable !== undefined)
@@ -821,7 +825,7 @@ class SettingsPanel implements Component, Focusable {
821
825
  }
822
826
 
823
827
  // A throwing editor render must not take down the shared frame; Esc still closes it.
824
- private renderCustomEditor(width: number): string[] {
828
+ private renderCustomEditor(width: number): readonly string[] {
825
829
  try {
826
830
  return this.customEditor!.render(width);
827
831
  } catch (error) {