@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,43 @@
1
+ import type { LocalSession } from "./session.ts";
2
+ /**
3
+ * The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
4
+ * activity first. Each load asks for the budget again, so a changed setting applies to the
5
+ * next load.
6
+ *
7
+ * Every load checks each session file and reads only those that changed since the saved
8
+ * index. Lookups serve the cached list and reload it in the background. The owner disposes
9
+ * the catalog on session shutdown; a load that finishes later is discarded.
10
+ */
11
+ export declare class SessionCatalog {
12
+ private readonly onBackgroundError;
13
+ private readonly budget;
14
+ private readonly textLimit;
15
+ private readonly abort;
16
+ private readonly index;
17
+ private readonly pi;
18
+ private readonly external;
19
+ private sessions;
20
+ private loaded;
21
+ private loadedAt;
22
+ private loading;
23
+ /** `budget` gives the bytes the session index may keep. */
24
+ constructor(sessionDir: string, onBackgroundError: (error: unknown) => void, budget?: () => Promise<number>, textLimit?: () => Promise<number>);
25
+ /** The cached list, empty before the first load. A stale list starts a background reload. */
26
+ snapshot(): readonly LocalSession[];
27
+ /** Waits only for the first load; later lookups return the cached list at once. */
28
+ list(): Promise<readonly LocalSession[]>;
29
+ /**
30
+ * Settles when the first load does or when `signal` aborts. Whoever started the load
31
+ * handles its failure, so a waiting caller only reads snapshot() again.
32
+ *
33
+ * A failed first load is retried here. snapshot() only retries a stale list, and `@@`
34
+ * would otherwise stay empty for a minute after a transient read error.
35
+ */
36
+ whenLoaded(signal: AbortSignal): Promise<void>;
37
+ /** Concurrent callers share one load. */
38
+ reload(): Promise<readonly LocalSession[]>;
39
+ dispose(): void;
40
+ private load;
41
+ private refreshInBackground;
42
+ private report;
43
+ }
@@ -0,0 +1,117 @@
1
+ import { SESSION_TEXT_LIMIT } from "./budget.js";
2
+ import { ExternalSessions } from "./external.js";
3
+ import { PiSessions } from "./pi.js";
4
+ import { INDEX_BUDGET_BYTES, SessionIndex, sessionIndexFile } from "./session-index.js";
5
+ /** A list older than this is reloaded in the background on the next lookup. */
6
+ const REFRESH_AFTER_MS = 60_000;
7
+ /**
8
+ * The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
9
+ * activity first. Each load asks for the budget again, so a changed setting applies to the
10
+ * next load.
11
+ *
12
+ * Every load checks each session file and reads only those that changed since the saved
13
+ * index. Lookups serve the cached list and reload it in the background. The owner disposes
14
+ * the catalog on session shutdown; a load that finishes later is discarded.
15
+ */
16
+ export class SessionCatalog {
17
+ onBackgroundError;
18
+ budget;
19
+ textLimit;
20
+ abort = new AbortController();
21
+ index = new SessionIndex(sessionIndexFile());
22
+ pi;
23
+ external = new ExternalSessions();
24
+ sessions = [];
25
+ loaded = false;
26
+ loadedAt = 0;
27
+ loading;
28
+ /** `budget` gives the bytes the session index may keep. */
29
+ constructor(sessionDir, onBackgroundError, budget = async () => INDEX_BUDGET_BYTES, textLimit = async () => SESSION_TEXT_LIMIT) {
30
+ this.pi = new PiSessions(sessionDir);
31
+ this.onBackgroundError = onBackgroundError;
32
+ this.budget = budget;
33
+ this.textLimit = textLimit;
34
+ }
35
+ /** The cached list, empty before the first load. A stale list starts a background reload. */
36
+ snapshot() {
37
+ if (Date.now() - this.loadedAt > REFRESH_AFTER_MS)
38
+ this.refreshInBackground();
39
+ return this.sessions;
40
+ }
41
+ /** Waits only for the first load; later lookups return the cached list at once. */
42
+ async list() {
43
+ return this.loaded ? this.snapshot() : this.reload();
44
+ }
45
+ /**
46
+ * Settles when the first load does or when `signal` aborts. Whoever started the load
47
+ * handles its failure, so a waiting caller only reads snapshot() again.
48
+ *
49
+ * A failed first load is retried here. snapshot() only retries a stale list, and `@@`
50
+ * would otherwise stay empty for a minute after a transient read error.
51
+ */
52
+ async whenLoaded(signal) {
53
+ if (this.loaded)
54
+ return;
55
+ this.refreshInBackground();
56
+ const loading = this.loading;
57
+ if (!loading || signal.aborted)
58
+ return;
59
+ await new Promise((resolve) => {
60
+ const settle = () => {
61
+ signal.removeEventListener("abort", settle);
62
+ resolve();
63
+ };
64
+ signal.addEventListener("abort", settle, { once: true });
65
+ loading.then(settle, settle);
66
+ });
67
+ }
68
+ /** Concurrent callers share one load. */
69
+ reload() {
70
+ this.loadedAt = Date.now();
71
+ this.loading ??= this.load().finally(() => {
72
+ this.loading = undefined;
73
+ });
74
+ return this.loading;
75
+ }
76
+ dispose() {
77
+ this.abort.abort();
78
+ this.external.clear();
79
+ }
80
+ async load() {
81
+ const signal = this.abort.signal;
82
+ // A failed index only costs a full read; the scan below writes a new one.
83
+ await this.index.load(signal).catch((error) => this.report(error));
84
+ // Settings that cannot be read are reported where they are edited; the session list
85
+ // keeps working with the default size instead.
86
+ this.index.budget = await this.budget().catch(() => INDEX_BUDGET_BYTES);
87
+ this.index.textLimit = await this.textLimit().catch(() => SESSION_TEXT_LIMIT);
88
+ const [pi, external] = await Promise.all([
89
+ this.pi.list(signal),
90
+ this.external.list(signal, this.onBackgroundError),
91
+ ]);
92
+ // Pi first, so sessions with equal activity times keep listAll's order.
93
+ const { sessions: listed, errors } = await this.index.scan([...pi, ...external], signal);
94
+ signal.throwIfAborted();
95
+ if (errors.length > 0) {
96
+ this.report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
97
+ }
98
+ await this.index.save().catch((error) => this.report(error));
99
+ signal.throwIfAborted();
100
+ const sessions = listed.sort((left, right) => right.modified.getTime() - left.modified.getTime());
101
+ this.sessions = sessions;
102
+ this.loaded = true;
103
+ return sessions;
104
+ }
105
+ refreshInBackground() {
106
+ if (this.loading || this.abort.signal.aborted)
107
+ return;
108
+ this.reload().catch((error) => {
109
+ if (!this.abort.signal.aborted)
110
+ this.onBackgroundError(error);
111
+ });
112
+ }
113
+ report(error) {
114
+ this.abort.signal.throwIfAborted();
115
+ this.onBackgroundError(error);
116
+ }
117
+ }
@@ -0,0 +1,2 @@
1
+ import type { ExternalSession } from "./session.ts";
2
+ export declare function parseClaudeSession(content: string, path: string): ExternalSession | undefined;
@@ -0,0 +1,118 @@
1
+ import { date, jsonl, object, sessionId, string, textContent } from "./jsonl.js";
2
+ import { cleanBody, cleanLine } from "./text.js";
3
+ export function parseClaudeSession(content, path) {
4
+ const entries = new Map();
5
+ const segments = [];
6
+ let id;
7
+ let cwd;
8
+ let created;
9
+ let modified;
10
+ let customTitle;
11
+ let aiTitle;
12
+ let leafId = null;
13
+ let hasMainEntry = false;
14
+ let hasSidechain = false;
15
+ for (const record of jsonl(content, path)) {
16
+ if (record.isSidechain === true) {
17
+ hasSidechain = true;
18
+ continue;
19
+ }
20
+ if (record.type === "custom-title")
21
+ customTitle = string(record.customTitle, "customTitle");
22
+ if (record.type === "ai-title")
23
+ aiTitle = string(record.aiTitle, "aiTitle");
24
+ if (typeof record.cwd === "string")
25
+ cwd = record.cwd;
26
+ if (typeof record.sessionId === "string") {
27
+ if (id !== undefined && id !== record.sessionId) {
28
+ throw new Error("Claude Code file contains multiple session ids");
29
+ }
30
+ id = sessionId(record.sessionId, "entry.sessionId");
31
+ }
32
+ if (record.timestamp !== undefined) {
33
+ const timestamp = date(record.timestamp, "entry.timestamp");
34
+ if (!created || timestamp < created)
35
+ created = timestamp;
36
+ if (!modified || timestamp > modified)
37
+ modified = timestamp;
38
+ }
39
+ if (record.uuid === undefined || record.parentUuid === undefined)
40
+ continue;
41
+ hasMainEntry = true;
42
+ const uuid = string(record.uuid, "entry.uuid");
43
+ const parent = record.parentUuid === null ? null : string(record.parentUuid, "entry.parentUuid");
44
+ const entry = { id: uuid, parent };
45
+ if (record.type === "user" || record.type === "assistant") {
46
+ const message = object(record.message);
47
+ const text = cleanBody(typeof message.content === "string"
48
+ ? message.content
49
+ : textContent(message.content, ["text"]));
50
+ if (text && record.isMeta !== true) {
51
+ entry.message = {
52
+ role: record.isCompactSummary === true ? "summary" : record.type,
53
+ text,
54
+ };
55
+ }
56
+ }
57
+ entries.set(uuid, entry);
58
+ leafId = uuid;
59
+ if (record.type === "system" && record.subtype === "compact_boundary") {
60
+ const metadata = object(record.compactMetadata);
61
+ if (metadata.preservedSegment !== undefined) {
62
+ const segment = object(metadata.preservedSegment);
63
+ segments.push({
64
+ head: string(segment.headUuid, "preservedSegment.headUuid"),
65
+ anchor: string(segment.anchorUuid, "preservedSegment.anchorUuid"),
66
+ tail: string(segment.tailUuid, "preservedSegment.tailUuid"),
67
+ });
68
+ }
69
+ }
70
+ }
71
+ if (!hasMainEntry && (id !== undefined || hasSidechain))
72
+ return undefined;
73
+ if (!id || cwd === undefined || !created || !modified) {
74
+ throw new Error("Not a supported Claude Code session");
75
+ }
76
+ // Compaction preserves an older segment without rewriting its on-disk parent links.
77
+ for (const segment of segments) {
78
+ const head = entries.get(segment.head);
79
+ if (!head || !entries.has(segment.anchor) || !entries.has(segment.tail)) {
80
+ throw new Error("Claude Code compaction references a missing preserved segment");
81
+ }
82
+ for (const entry of entries.values()) {
83
+ if (entry.parent === segment.anchor)
84
+ entry.parent = segment.tail;
85
+ }
86
+ head.parent = segment.anchor;
87
+ }
88
+ const messages = [];
89
+ const visited = new Set();
90
+ for (let cursor = leafId; cursor !== null;) {
91
+ if (visited.has(cursor))
92
+ throw new Error("Claude Code session contains a parent cycle");
93
+ visited.add(cursor);
94
+ const entry = entries.get(cursor);
95
+ if (!entry)
96
+ throw new Error(`Claude Code session is missing parent ${cursor}`);
97
+ if (entry.message)
98
+ messages.push(entry.message);
99
+ cursor = entry.parent;
100
+ }
101
+ messages.reverse();
102
+ return {
103
+ session: {
104
+ source: "claude",
105
+ path,
106
+ id,
107
+ cwd,
108
+ created,
109
+ modified,
110
+ name: customTitle ?? aiTitle,
111
+ messageCount: messages.filter((message) => message.role !== "summary").length,
112
+ firstMessage: cleanLine(messages.find((message) => message.role === "user")?.text ?? ""),
113
+ allMessagesText: messages.map((message) => message.text).join("\n"),
114
+ },
115
+ messages,
116
+ leafId,
117
+ };
118
+ }
@@ -0,0 +1,3 @@
1
+ import type { ExternalSession } from "./session.ts";
2
+ /** Codex persists both response items and UI events; only response items carry conversation text. */
3
+ export declare function parseCodexSession(content: string, path: string): ExternalSession | undefined;
@@ -0,0 +1,135 @@
1
+ import { date, jsonl, object, sessionId, string, textContent } from "./jsonl.js";
2
+ import { cleanBody, cleanLine } from "./text.js";
3
+ /** Codex persists both response items and UI events; only response items carry conversation text. */
4
+ export function parseCodexSession(content, path) {
5
+ const records = jsonl(content, path);
6
+ const first = records.next().value;
7
+ if (first?.type !== "session_meta")
8
+ throw new Error("Not a supported Codex rollout");
9
+ const meta = object(first.payload);
10
+ const source = meta.source;
11
+ if (meta.thread_source === "subagent" ||
12
+ (typeof source === "object" && source !== null && "subagent" in source)) {
13
+ return undefined;
14
+ }
15
+ const id = sessionId(meta.id, "session_meta.id");
16
+ const cwd = string(meta.cwd, "session_meta.cwd");
17
+ const created = date(meta.timestamp, "session_meta.timestamp");
18
+ let modified = created;
19
+ let history = null;
20
+ // Persistent heads let rollback restore history across a compaction without copying every turn.
21
+ const turns = [];
22
+ let inTurn = false;
23
+ let turnHasUser = false;
24
+ let leafId = null;
25
+ const append = (message) => {
26
+ history = { message, previous: history };
27
+ };
28
+ for (const record of records) {
29
+ if (record.timestamp !== undefined) {
30
+ const timestamp = date(record.timestamp, "rollout.timestamp");
31
+ if (timestamp > modified)
32
+ modified = timestamp;
33
+ }
34
+ if (record.type === "response_item") {
35
+ const item = object(record.payload);
36
+ const message = responseMessage(item);
37
+ if (message) {
38
+ if (message.role === "user") {
39
+ if (!inTurn || !turnHasUser)
40
+ turns.push(history);
41
+ turnHasUser = true;
42
+ }
43
+ append(message);
44
+ leafId = typeof item.id === "string" ? item.id : null;
45
+ }
46
+ }
47
+ else if (record.type === "compacted") {
48
+ const compacted = object(record.payload);
49
+ if (!Array.isArray(compacted.replacement_history)) {
50
+ throw new Error("Unsupported Codex compaction without replacement_history");
51
+ }
52
+ const summary = string(compacted.message, "compacted.message");
53
+ const checkpointOnly = turns.length === 0;
54
+ let hasSummary = false;
55
+ history = null;
56
+ for (const raw of compacted.replacement_history) {
57
+ const message = responseMessage(object(raw), summary);
58
+ if (!message)
59
+ continue;
60
+ if (checkpointOnly && message.role === "user")
61
+ turns.push(history);
62
+ if (message.role === "summary")
63
+ hasSummary = true;
64
+ append(message);
65
+ }
66
+ if (summary.trim() && !hasSummary)
67
+ append({ role: "summary", text: cleanBody(summary) });
68
+ leafId = null;
69
+ }
70
+ else if (record.type === "event_msg") {
71
+ const event = object(record.payload);
72
+ if (event.type === "task_started") {
73
+ inTurn = true;
74
+ turnHasUser = false;
75
+ }
76
+ else if (event.type === "task_complete" || event.type === "turn_aborted") {
77
+ inTurn = false;
78
+ }
79
+ else if (event.type === "thread_rolled_back") {
80
+ const count = event.num_turns;
81
+ if (typeof count !== "number" || !Number.isSafeInteger(count) || count < 0) {
82
+ throw new Error("Invalid Codex rollback num_turns");
83
+ }
84
+ for (let index = 0; index < count && turns.length > 0; index++) {
85
+ history = turns.pop();
86
+ }
87
+ inTurn = false;
88
+ leafId = null;
89
+ }
90
+ }
91
+ }
92
+ const messages = [];
93
+ for (let node = history; node; node = node.previous) {
94
+ messages.push(node.message);
95
+ }
96
+ messages.reverse();
97
+ return {
98
+ session: {
99
+ source: "codex",
100
+ path,
101
+ id,
102
+ cwd,
103
+ created,
104
+ modified,
105
+ messageCount: messages.filter((message) => message.role !== "summary").length,
106
+ firstMessage: cleanLine(messages.find((message) => message.role === "user")?.text ?? ""),
107
+ allMessagesText: messages.map((message) => message.text).join("\n"),
108
+ },
109
+ messages,
110
+ leafId,
111
+ };
112
+ }
113
+ function responseMessage(item, summary) {
114
+ if (item.type !== "message" ||
115
+ (item.role !== "user" && item.role !== "assistant") ||
116
+ item.channel === "analysis") {
117
+ return undefined;
118
+ }
119
+ let content = item.content;
120
+ if (item.role === "user" && item.internal_chat_message_metadata_passthrough !== undefined) {
121
+ const metadata = object(item.internal_chat_message_metadata_passthrough);
122
+ if (Array.isArray(metadata.content_item_kinds) && Array.isArray(content)) {
123
+ // Desktop stores injected AGENTS.md and environment context as user-role content too.
124
+ const kinds = metadata.content_item_kinds;
125
+ content = content.filter((_part, index) => string(kinds[index], "content_item_kinds").startsWith("user."));
126
+ }
127
+ }
128
+ const text = cleanBody(textContent(content, ["input_text", "output_text"]));
129
+ if (!text)
130
+ return undefined;
131
+ const isSummary = summary !== undefined &&
132
+ ((summary !== "" && text === cleanBody(summary)) ||
133
+ text.startsWith("Another language model started to solve this problem and produced a summary"));
134
+ return { role: isSummary ? "summary" : item.role, text };
135
+ }
@@ -0,0 +1,15 @@
1
+ import { type ExternalSession, type SessionSource } from "./session.ts";
2
+ import type { SessionFile } from "./session-index.ts";
3
+ type ExternalSource = Exclude<SessionSource, "pi">;
4
+ /** Codex and Claude Code session files; the Codex title index is cached per Pi session. */
5
+ export declare class ExternalSessions {
6
+ private readonly codexHome;
7
+ private readonly claudeHome;
8
+ private titleIndex;
9
+ list(signal: AbortSignal, report: (error: unknown) => void): Promise<SessionFile[]>;
10
+ clear(): void;
11
+ private paths;
12
+ private codexNames;
13
+ }
14
+ export declare function parseExternalSession(source: ExternalSource, content: string, path: string): ExternalSession | undefined;
15
+ export {};
@@ -0,0 +1,145 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { parseClaudeSession } from "./claude.js";
5
+ import { parseCodexSession } from "./codex.js";
6
+ import { jsonl, string } from "./jsonl.js";
7
+ import { SOURCE_NAMES } from "./session.js";
8
+ /** Codex and Claude Code session files; the Codex title index is cached per Pi session. */
9
+ export class ExternalSessions {
10
+ codexHome = resolve(process.env["CODEX_HOME"] ?? join(homedir(), ".codex"));
11
+ claudeHome = resolve(process.env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude"));
12
+ titleIndex;
13
+ async list(signal, report) {
14
+ const errors = [];
15
+ const sources = ["codex", "claude"];
16
+ const results = await Promise.all(sources.map(async (source) => {
17
+ try {
18
+ const paths = await this.paths(source);
19
+ const names = source === "codex" ? await this.codexNames(signal) : undefined;
20
+ const currentVersion = source === "codex" ? this.titleIndex?.version : undefined;
21
+ const files = await Promise.all(paths.map(async (path) => {
22
+ try {
23
+ return externalFile(source, path, await stat(path), names, currentVersion);
24
+ }
25
+ catch (error) {
26
+ // Removed since the directory was listed.
27
+ if (error.code !== "ENOENT") {
28
+ errors.push(fileError(source, path, error));
29
+ }
30
+ return undefined;
31
+ }
32
+ }));
33
+ return files.filter((file) => file !== undefined);
34
+ }
35
+ catch (error) {
36
+ signal.throwIfAborted();
37
+ errors.push(fileError(source, source === "codex" ? this.codexHome : this.claudeHome, error));
38
+ return [];
39
+ }
40
+ }));
41
+ signal.throwIfAborted();
42
+ if (errors.length > 0) {
43
+ report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
44
+ }
45
+ return results.flat();
46
+ }
47
+ clear() {
48
+ this.titleIndex = undefined;
49
+ }
50
+ async paths(source) {
51
+ const root = join(source === "codex" ? this.codexHome : this.claudeHome, source === "codex" ? "sessions" : "projects");
52
+ let projects;
53
+ try {
54
+ if (source === "codex") {
55
+ return (await readdir(root, { recursive: true }))
56
+ .filter((file) => /^rollout-.+\.jsonl$/.test(basename(file)))
57
+ .map((file) => join(root, file));
58
+ }
59
+ projects = (await readdir(root, { withFileTypes: true }))
60
+ .filter((entry) => entry.isDirectory())
61
+ .map((entry) => join(root, entry.name));
62
+ }
63
+ catch (error) {
64
+ // Neither external tool is required to be installed; only an absent store is empty.
65
+ if (error.code === "ENOENT")
66
+ return [];
67
+ throw error;
68
+ }
69
+ // Subagents and tool-result stores are nested below the main files; never traverse them.
70
+ const files = await Promise.all(projects.map(async (project) => (await readdir(project, { withFileTypes: true }))
71
+ .filter((entry) => entry.isFile() &&
72
+ entry.name.endsWith(".jsonl") &&
73
+ !entry.name.startsWith("agent-"))
74
+ .map((entry) => join(project, entry.name))));
75
+ return files.flat();
76
+ }
77
+ async codexNames(signal) {
78
+ const path = join(this.codexHome, "session_index.jsonl");
79
+ let content;
80
+ let version;
81
+ try {
82
+ const stats = await stat(path);
83
+ version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
84
+ if (this.titleIndex?.version === version)
85
+ return this.titleIndex.names;
86
+ content = await readFile(path, { encoding: "utf8", signal });
87
+ }
88
+ catch (error) {
89
+ // The title index is optional; the rollout itself owns the session and its messages.
90
+ if (error.code === "ENOENT") {
91
+ this.titleIndex = undefined;
92
+ return new Map();
93
+ }
94
+ throw error;
95
+ }
96
+ const names = new Map();
97
+ try {
98
+ for (const record of jsonl(content, path)) {
99
+ names.set(string(record.id, "session_index.id"), string(record.thread_name, "thread_name"));
100
+ }
101
+ }
102
+ catch {
103
+ // TODO: Record Codex title parser errors in Core Log when it is available.
104
+ names.clear();
105
+ }
106
+ if (!signal.aborted)
107
+ this.titleIndex = { version, names };
108
+ return names;
109
+ }
110
+ }
111
+ function externalFile(source, path, stats, codexNames, currentVersion) {
112
+ return {
113
+ path,
114
+ stats,
115
+ label: SOURCE_NAMES[source],
116
+ currentVersion,
117
+ async read(signal) {
118
+ const content = await readFile(path, { encoding: "utf8", signal });
119
+ return parseExternalSession(source, content, path)?.session;
120
+ },
121
+ // Codex keeps titles in its own index, so a rename does not change the rollout.
122
+ current: codexNames
123
+ ? (session) => {
124
+ const name = codexNames.get(session.id);
125
+ // The same object keeps autocomplete's search cache for the session.
126
+ return name === session.name ? session : { ...session, name };
127
+ }
128
+ : undefined,
129
+ };
130
+ }
131
+ export function parseExternalSession(source, content, path) {
132
+ try {
133
+ return source === "codex"
134
+ ? parseCodexSession(content, path)
135
+ : parseClaudeSession(content, path);
136
+ }
137
+ catch {
138
+ // TODO: Record Codex and Claude Code parser errors in Core Log when it is available.
139
+ return undefined;
140
+ }
141
+ }
142
+ function fileError(source, path, error) {
143
+ const message = error instanceof Error ? error.message : String(error);
144
+ return new Error(`${SOURCE_NAMES[source]}: ${path}: ${message}`, { cause: error });
145
+ }
@@ -0,0 +1,17 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { ResourceScope } from "../resources/resources.ts";
3
+ export interface MentionOptions {
4
+ /**
5
+ * Bytes the session index may keep, asked again on every load of the session list.
6
+ * Without it, or when it rejects, the index keeps INDEX_BUDGET_BYTES.
7
+ */
8
+ indexBudget?(ctx: ExtensionContext): Promise<number>;
9
+ /** Characters kept per text field, asked again on every session-list load. */
10
+ indexTextLimit?(ctx: ExtensionContext): Promise<number>;
11
+ }
12
+ /**
13
+ * `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
14
+ * session becomes a source-specific token. On submit, each such token becomes an `@` reference to
15
+ * a filtered copy of that session, which the model reads when it needs the background.
16
+ */
17
+ export declare function installMentions(pi: ExtensionAPI, resources: ResourceScope, options?: MentionOptions): void;