@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.
@@ -1,77 +1,53 @@
1
+ import type { Stats } from "node:fs";
1
2
  import { readFile, readdir, stat } from "node:fs/promises";
2
3
  import { homedir } from "node:os";
3
4
  import { basename, join, resolve } from "node:path";
4
5
  import { parseClaudeSession } from "./claude.ts";
5
6
  import { parseCodexSession } from "./codex.ts";
6
7
  import { jsonl, string } from "./jsonl.ts";
7
- import {
8
- SOURCE_NAMES,
9
- type ExternalSession,
10
- type LocalSession,
11
- type SessionSource,
12
- } from "./session.ts";
8
+ import { SOURCE_NAMES, type ExternalSession, type SessionSource } from "./session.ts";
9
+ import type { SessionFile } from "./session-index.ts";
13
10
 
14
11
  type ExternalSource = Exclude<SessionSource, "pi">;
15
12
 
16
- interface CachedSession {
17
- version: string;
18
- session?: LocalSession;
19
- }
20
-
21
- /** File metadata caches belong to the running Pi session, just like the combined catalog. */
13
+ /** Codex and Claude Code session files; the Codex title index is cached per Pi session. */
22
14
  export class ExternalSessions {
23
15
  private readonly codexHome = resolve(process.env["CODEX_HOME"] ?? join(homedir(), ".codex"));
24
16
  private readonly claudeHome = resolve(
25
17
  process.env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude"),
26
18
  );
27
- private readonly cached = new Map<string, CachedSession>();
28
19
  private titleIndex: { version: string; names: Map<string, string> } | undefined;
29
20
 
30
- async list(signal: AbortSignal, report: (error: unknown) => void): Promise<LocalSession[]> {
21
+ async list(signal: AbortSignal, report: (error: unknown) => void): Promise<SessionFile[]> {
31
22
  const errors: Error[] = [];
32
- const seen = new Set<string>();
33
23
  const sources: ExternalSource[] = ["codex", "claude"];
34
24
  const results = await Promise.all(
35
25
  sources.map(async (source) => {
36
26
  try {
37
27
  const paths = await this.paths(source);
38
- const names = source === "codex" ? await this.codexNames(signal) : new Map();
39
- const sessions: LocalSession[] = [];
40
- // One file per source at a time bounds memory when rollouts contain large tool results.
41
- for (const path of paths) {
42
- signal.throwIfAborted();
43
- seen.add(path);
44
- try {
45
- const stats = await stat(path);
46
- const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
47
- let cached = this.cached.get(path);
48
- if (cached?.version !== version) {
49
- cached = { version };
50
- const content = await readFile(path, { encoding: "utf8", signal });
51
- cached.session = parseExternalSession(
28
+ const names = source === "codex" ? await this.codexNames(signal) : undefined;
29
+ const currentVersion =
30
+ source === "codex" ? this.titleIndex?.version : undefined;
31
+ const files = await Promise.all(
32
+ paths.map(async (path) => {
33
+ try {
34
+ return externalFile(
52
35
  source,
53
- content,
54
36
  path,
55
- )?.session;
56
- if (!signal.aborted) this.cached.set(path, cached);
57
- }
58
- if (cached.session) {
59
- const name =
60
- source === "codex"
61
- ? names.get(cached.session.id)
62
- : cached.session.name;
63
- if (name !== cached.session.name) {
64
- cached.session = { ...cached.session, name };
37
+ await stat(path),
38
+ names,
39
+ currentVersion,
40
+ );
41
+ } catch (error) {
42
+ // Removed since the directory was listed.
43
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
44
+ errors.push(fileError(source, path, error));
65
45
  }
66
- // Stable objects preserve autocomplete's existing WeakMap search cache.
67
- sessions.push(cached.session);
46
+ return undefined;
68
47
  }
69
- } catch (error) {
70
- signal.throwIfAborted();
71
- errors.push(fileError(source, path, error));
72
- }
73
- }
74
- return sessions;
48
+ }),
49
+ );
50
+ return files.filter((file) => file !== undefined);
75
51
  } catch (error) {
76
52
  signal.throwIfAborted();
77
53
  errors.push(
@@ -86,9 +62,6 @@ export class ExternalSessions {
86
62
  }),
87
63
  );
88
64
  signal.throwIfAborted();
89
- for (const path of this.cached.keys()) {
90
- if (!seen.has(path)) this.cached.delete(path);
91
- }
92
65
  if (errors.length > 0) {
93
66
  report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
94
67
  }
@@ -96,7 +69,6 @@ export class ExternalSessions {
96
69
  }
97
70
 
98
71
  clear(): void {
99
- this.cached.clear();
100
72
  this.titleIndex = undefined;
101
73
  }
102
74
 
@@ -170,6 +142,33 @@ export class ExternalSessions {
170
142
  }
171
143
  }
172
144
 
145
+ function externalFile(
146
+ source: ExternalSource,
147
+ path: string,
148
+ stats: Stats,
149
+ codexNames: ReadonlyMap<string, string> | undefined,
150
+ currentVersion: string | undefined,
151
+ ): SessionFile {
152
+ return {
153
+ path,
154
+ stats,
155
+ label: SOURCE_NAMES[source],
156
+ currentVersion,
157
+ async read(signal) {
158
+ const content = await readFile(path, { encoding: "utf8", signal });
159
+ return parseExternalSession(source, content, path)?.session;
160
+ },
161
+ // Codex keeps titles in its own index, so a rename does not change the rollout.
162
+ current: codexNames
163
+ ? (session) => {
164
+ const name = codexNames.get(session.id);
165
+ // The same object keeps autocomplete's search cache for the session.
166
+ return name === session.name ? session : { ...session, name };
167
+ }
168
+ : undefined,
169
+ };
170
+ }
171
+
173
172
  export function parseExternalSession(
174
173
  source: ExternalSource,
175
174
  content: string,
@@ -16,12 +16,26 @@ import {
16
16
  import { ExternalSessionParseError, type LocalSession } from "./session.ts";
17
17
  import { buildTranscript } from "./transcript.ts";
18
18
 
19
+ export interface MentionOptions {
20
+ /**
21
+ * Bytes the session index may keep, asked again on every load of the session list.
22
+ * Without it, or when it rejects, the index keeps INDEX_BUDGET_BYTES.
23
+ */
24
+ indexBudget?(ctx: ExtensionContext): Promise<number>;
25
+ /** Characters kept per text field, asked again on every session-list load. */
26
+ indexTextLimit?(ctx: ExtensionContext): Promise<number>;
27
+ }
28
+
19
29
  /**
20
30
  * `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
21
31
  * session becomes a source-specific token. On submit, each such token becomes an `@` reference to
22
32
  * a filtered copy of that session, which the model reads when it needs the background.
23
33
  */
24
- export function installMentions(pi: ExtensionAPI, resources: ResourceScope): void {
34
+ export function installMentions(
35
+ pi: ExtensionAPI,
36
+ resources: ResourceScope,
37
+ options: MentionOptions = {},
38
+ ): void {
25
39
  let catalog: SessionCatalog | undefined;
26
40
  const transcripts = new TranscriptCache();
27
41
  const retire = () => {
@@ -38,7 +52,13 @@ export function installMentions(pi: ExtensionAPI, resources: ResourceScope): voi
38
52
  if (catalog !== sessions) return;
39
53
  ctx.ui.notify(`Session list failed: ${errorMessage(error)}`, "error");
40
54
  };
41
- const sessions = new SessionCatalog(ctx.sessionManager.getSessionDir(), report);
55
+ const { indexBudget, indexTextLimit } = options;
56
+ const sessions = new SessionCatalog(
57
+ ctx.sessionManager.getSessionDir(),
58
+ report,
59
+ indexBudget && (() => indexBudget(ctx)),
60
+ indexTextLimit && (() => indexTextLimit(ctx)),
61
+ );
42
62
  catalog = sessions;
43
63
  if (ctx.mode !== "tui") return;
44
64
  // Pi drops autocomplete wrappers when it replaces the session, so add one per start.
@@ -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
+ }