@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.
- package/CHANGELOG.md +77 -0
- package/README.md +117 -36
- package/dist/core/panel.d.ts +6 -1
- package/dist/core/panel.js +26 -1
- package/dist/core/settings.d.ts +9 -1
- package/dist/core/settings.js +36 -2
- package/dist/dock/registry.js +1 -0
- package/dist/extension.js +10 -2
- package/dist/mention/autocomplete.d.ts +25 -0
- package/dist/mention/autocomplete.js +140 -0
- package/dist/mention/budget.d.ts +8 -0
- package/dist/mention/budget.js +10 -0
- package/dist/mention/catalog.d.ts +43 -0
- package/dist/mention/catalog.js +117 -0
- package/dist/mention/claude.d.ts +2 -0
- package/dist/mention/claude.js +118 -0
- package/dist/mention/codex.d.ts +3 -0
- package/dist/mention/codex.js +135 -0
- package/dist/mention/external.d.ts +15 -0
- package/dist/mention/external.js +145 -0
- package/dist/mention/index.d.ts +17 -0
- package/dist/mention/index.js +151 -0
- package/dist/mention/jsonl.d.ts +9 -0
- package/dist/mention/jsonl.js +54 -0
- package/dist/mention/mention.d.ts +19 -0
- package/dist/mention/mention.js +60 -0
- package/dist/mention/pi.d.ts +11 -0
- package/dist/mention/pi.js +172 -0
- package/dist/mention/session-index.d.ts +66 -0
- package/dist/mention/session-index.js +303 -0
- package/dist/mention/session.d.ts +18 -0
- package/dist/mention/session.js +8 -0
- package/dist/mention/text.d.ts +12 -0
- package/dist/mention/text.js +47 -0
- package/dist/mention/transcript.d.ts +10 -0
- package/dist/mention/transcript.js +129 -0
- package/dist/panel/defined-section.js +34 -8
- package/dist/panel/definition.d.ts +26 -1
- package/dist/panel/definition.js +32 -2
- package/dist/panel/index.d.ts +3 -2
- package/dist/panel/index.js +1 -0
- package/dist/panel/panel.js +109 -29
- package/dist/panel/section.d.ts +49 -3
- package/dist/panel/section.js +59 -12
- package/dist/resources/scoped-extension.js +1 -0
- package/dist/settings/file-store.js +1 -0
- package/docs/dock.md +9 -3
- package/docs/panel.md +69 -2
- package/docs/public-api-design.md +9 -9
- package/docs/recipes.md +3 -8
- package/docs/settings.md +1 -1
- package/package.json +4 -4
- package/src/core/panel.ts +29 -1
- package/src/core/settings.ts +42 -2
- package/src/dock/registry.ts +1 -0
- package/src/extension.ts +11 -2
- package/src/mention/autocomplete.ts +177 -0
- package/src/mention/budget.ts +11 -0
- package/src/mention/catalog.ts +133 -0
- package/src/mention/claude.ts +127 -0
- package/src/mention/codex.ts +144 -0
- package/src/mention/external.ts +190 -0
- package/src/mention/index.ts +193 -0
- package/src/mention/jsonl.ts +56 -0
- package/src/mention/mention.ts +90 -0
- package/src/mention/pi.ts +192 -0
- package/src/mention/session-index.ts +356 -0
- package/src/mention/session.ts +27 -0
- package/src/mention/text.ts +52 -0
- package/src/mention/transcript.ts +155 -0
- package/src/panel/defined-section.ts +40 -7
- package/src/panel/definition.ts +67 -2
- package/src/panel/index.ts +4 -0
- package/src/panel/panel.ts +115 -29
- package/src/panel/section.ts +111 -15
- package/src/resources/scoped-extension.ts +1 -0
- package/src/settings/file-store.ts +1 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { date, jsonl, object, sessionId, string, textContent } from "./jsonl.ts";
|
|
2
|
+
import type { ConversationMessage, ExternalSession } from "./session.ts";
|
|
3
|
+
import { cleanBody, cleanLine } from "./text.ts";
|
|
4
|
+
|
|
5
|
+
interface Entry {
|
|
6
|
+
id: string;
|
|
7
|
+
parent: string | null;
|
|
8
|
+
message?: ConversationMessage;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface PreservedSegment {
|
|
12
|
+
head: string;
|
|
13
|
+
anchor: string;
|
|
14
|
+
tail: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function parseClaudeSession(content: string, path: string): ExternalSession | undefined {
|
|
18
|
+
const entries = new Map<string, Entry>();
|
|
19
|
+
const segments: PreservedSegment[] = [];
|
|
20
|
+
let id: string | undefined;
|
|
21
|
+
let cwd: string | undefined;
|
|
22
|
+
let created: Date | undefined;
|
|
23
|
+
let modified: Date | undefined;
|
|
24
|
+
let customTitle: string | undefined;
|
|
25
|
+
let aiTitle: string | undefined;
|
|
26
|
+
let leafId: string | null = null;
|
|
27
|
+
let hasMainEntry = false;
|
|
28
|
+
let hasSidechain = false;
|
|
29
|
+
|
|
30
|
+
for (const record of jsonl(content, path)) {
|
|
31
|
+
if (record.isSidechain === true) {
|
|
32
|
+
hasSidechain = true;
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
if (record.type === "custom-title") customTitle = string(record.customTitle, "customTitle");
|
|
36
|
+
if (record.type === "ai-title") aiTitle = string(record.aiTitle, "aiTitle");
|
|
37
|
+
if (typeof record.cwd === "string") cwd = record.cwd;
|
|
38
|
+
if (typeof record.sessionId === "string") {
|
|
39
|
+
if (id !== undefined && id !== record.sessionId) {
|
|
40
|
+
throw new Error("Claude Code file contains multiple session ids");
|
|
41
|
+
}
|
|
42
|
+
id = sessionId(record.sessionId, "entry.sessionId");
|
|
43
|
+
}
|
|
44
|
+
if (record.timestamp !== undefined) {
|
|
45
|
+
const timestamp = date(record.timestamp, "entry.timestamp");
|
|
46
|
+
if (!created || timestamp < created) created = timestamp;
|
|
47
|
+
if (!modified || timestamp > modified) modified = timestamp;
|
|
48
|
+
}
|
|
49
|
+
if (record.uuid === undefined || record.parentUuid === undefined) continue;
|
|
50
|
+
hasMainEntry = true;
|
|
51
|
+
const uuid = string(record.uuid, "entry.uuid");
|
|
52
|
+
const parent =
|
|
53
|
+
record.parentUuid === null ? null : string(record.parentUuid, "entry.parentUuid");
|
|
54
|
+
const entry: Entry = { id: uuid, parent };
|
|
55
|
+
if (record.type === "user" || record.type === "assistant") {
|
|
56
|
+
const message = object(record.message);
|
|
57
|
+
const text = cleanBody(
|
|
58
|
+
typeof message.content === "string"
|
|
59
|
+
? message.content
|
|
60
|
+
: textContent(message.content, ["text"]),
|
|
61
|
+
);
|
|
62
|
+
if (text && record.isMeta !== true) {
|
|
63
|
+
entry.message = {
|
|
64
|
+
role: record.isCompactSummary === true ? "summary" : record.type,
|
|
65
|
+
text,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
entries.set(uuid, entry);
|
|
70
|
+
leafId = uuid;
|
|
71
|
+
if (record.type === "system" && record.subtype === "compact_boundary") {
|
|
72
|
+
const metadata = object(record.compactMetadata);
|
|
73
|
+
if (metadata.preservedSegment !== undefined) {
|
|
74
|
+
const segment = object(metadata.preservedSegment);
|
|
75
|
+
segments.push({
|
|
76
|
+
head: string(segment.headUuid, "preservedSegment.headUuid"),
|
|
77
|
+
anchor: string(segment.anchorUuid, "preservedSegment.anchorUuid"),
|
|
78
|
+
tail: string(segment.tailUuid, "preservedSegment.tailUuid"),
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (!hasMainEntry && (id !== undefined || hasSidechain)) return undefined;
|
|
84
|
+
if (!id || cwd === undefined || !created || !modified) {
|
|
85
|
+
throw new Error("Not a supported Claude Code session");
|
|
86
|
+
}
|
|
87
|
+
// Compaction preserves an older segment without rewriting its on-disk parent links.
|
|
88
|
+
for (const segment of segments) {
|
|
89
|
+
const head = entries.get(segment.head);
|
|
90
|
+
if (!head || !entries.has(segment.anchor) || !entries.has(segment.tail)) {
|
|
91
|
+
throw new Error("Claude Code compaction references a missing preserved segment");
|
|
92
|
+
}
|
|
93
|
+
for (const entry of entries.values()) {
|
|
94
|
+
if (entry.parent === segment.anchor) entry.parent = segment.tail;
|
|
95
|
+
}
|
|
96
|
+
head.parent = segment.anchor;
|
|
97
|
+
}
|
|
98
|
+
const messages: ConversationMessage[] = [];
|
|
99
|
+
const visited = new Set<string>();
|
|
100
|
+
for (let cursor = leafId; cursor !== null; ) {
|
|
101
|
+
if (visited.has(cursor)) throw new Error("Claude Code session contains a parent cycle");
|
|
102
|
+
visited.add(cursor);
|
|
103
|
+
const entry = entries.get(cursor);
|
|
104
|
+
if (!entry) throw new Error(`Claude Code session is missing parent ${cursor}`);
|
|
105
|
+
if (entry.message) messages.push(entry.message);
|
|
106
|
+
cursor = entry.parent;
|
|
107
|
+
}
|
|
108
|
+
messages.reverse();
|
|
109
|
+
return {
|
|
110
|
+
session: {
|
|
111
|
+
source: "claude",
|
|
112
|
+
path,
|
|
113
|
+
id,
|
|
114
|
+
cwd,
|
|
115
|
+
created,
|
|
116
|
+
modified,
|
|
117
|
+
name: customTitle ?? aiTitle,
|
|
118
|
+
messageCount: messages.filter((message) => message.role !== "summary").length,
|
|
119
|
+
firstMessage: cleanLine(
|
|
120
|
+
messages.find((message) => message.role === "user")?.text ?? "",
|
|
121
|
+
),
|
|
122
|
+
allMessagesText: messages.map((message) => message.text).join("\n"),
|
|
123
|
+
},
|
|
124
|
+
messages,
|
|
125
|
+
leafId,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { date, jsonl, object, sessionId, string, textContent, type JsonObject } from "./jsonl.ts";
|
|
2
|
+
import type { ConversationMessage, ExternalSession } from "./session.ts";
|
|
3
|
+
import { cleanBody, cleanLine } from "./text.ts";
|
|
4
|
+
|
|
5
|
+
interface HistoryNode {
|
|
6
|
+
message: ConversationMessage;
|
|
7
|
+
previous: HistoryNode | null;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Codex persists both response items and UI events; only response items carry conversation text. */
|
|
11
|
+
export function parseCodexSession(content: string, path: string): ExternalSession | undefined {
|
|
12
|
+
const records = jsonl(content, path);
|
|
13
|
+
const first = records.next().value;
|
|
14
|
+
if (first?.type !== "session_meta") throw new Error("Not a supported Codex rollout");
|
|
15
|
+
const meta = object(first.payload);
|
|
16
|
+
const source = meta.source;
|
|
17
|
+
if (
|
|
18
|
+
meta.thread_source === "subagent" ||
|
|
19
|
+
(typeof source === "object" && source !== null && "subagent" in source)
|
|
20
|
+
) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
const id = sessionId(meta.id, "session_meta.id");
|
|
24
|
+
const cwd = string(meta.cwd, "session_meta.cwd");
|
|
25
|
+
const created = date(meta.timestamp, "session_meta.timestamp");
|
|
26
|
+
let modified = created;
|
|
27
|
+
let history: HistoryNode | null = null;
|
|
28
|
+
// Persistent heads let rollback restore history across a compaction without copying every turn.
|
|
29
|
+
const turns: (HistoryNode | null)[] = [];
|
|
30
|
+
let inTurn = false;
|
|
31
|
+
let turnHasUser = false;
|
|
32
|
+
let leafId: string | null = null;
|
|
33
|
+
const append = (message: ConversationMessage) => {
|
|
34
|
+
history = { message, previous: history };
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
for (const record of records) {
|
|
38
|
+
if (record.timestamp !== undefined) {
|
|
39
|
+
const timestamp = date(record.timestamp, "rollout.timestamp");
|
|
40
|
+
if (timestamp > modified) modified = timestamp;
|
|
41
|
+
}
|
|
42
|
+
if (record.type === "response_item") {
|
|
43
|
+
const item = object(record.payload);
|
|
44
|
+
const message = responseMessage(item);
|
|
45
|
+
if (message) {
|
|
46
|
+
if (message.role === "user") {
|
|
47
|
+
if (!inTurn || !turnHasUser) turns.push(history);
|
|
48
|
+
turnHasUser = true;
|
|
49
|
+
}
|
|
50
|
+
append(message);
|
|
51
|
+
leafId = typeof item.id === "string" ? item.id : null;
|
|
52
|
+
}
|
|
53
|
+
} else if (record.type === "compacted") {
|
|
54
|
+
const compacted = object(record.payload);
|
|
55
|
+
if (!Array.isArray(compacted.replacement_history)) {
|
|
56
|
+
throw new Error("Unsupported Codex compaction without replacement_history");
|
|
57
|
+
}
|
|
58
|
+
const summary = string(compacted.message, "compacted.message");
|
|
59
|
+
const checkpointOnly = turns.length === 0;
|
|
60
|
+
let hasSummary = false;
|
|
61
|
+
history = null;
|
|
62
|
+
for (const raw of compacted.replacement_history) {
|
|
63
|
+
const message = responseMessage(object(raw), summary);
|
|
64
|
+
if (!message) continue;
|
|
65
|
+
if (checkpointOnly && message.role === "user") turns.push(history);
|
|
66
|
+
if (message.role === "summary") hasSummary = true;
|
|
67
|
+
append(message);
|
|
68
|
+
}
|
|
69
|
+
if (summary.trim() && !hasSummary)
|
|
70
|
+
append({ role: "summary", text: cleanBody(summary) });
|
|
71
|
+
leafId = null;
|
|
72
|
+
} else if (record.type === "event_msg") {
|
|
73
|
+
const event = object(record.payload);
|
|
74
|
+
if (event.type === "task_started") {
|
|
75
|
+
inTurn = true;
|
|
76
|
+
turnHasUser = false;
|
|
77
|
+
} else if (event.type === "task_complete" || event.type === "turn_aborted") {
|
|
78
|
+
inTurn = false;
|
|
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: ConversationMessage[] = [];
|
|
93
|
+
for (let node: HistoryNode | null = 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(
|
|
107
|
+
messages.find((message) => message.role === "user")?.text ?? "",
|
|
108
|
+
),
|
|
109
|
+
allMessagesText: messages.map((message) => message.text).join("\n"),
|
|
110
|
+
},
|
|
111
|
+
messages,
|
|
112
|
+
leafId,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function responseMessage(item: JsonObject, summary?: string): ConversationMessage | undefined {
|
|
117
|
+
if (
|
|
118
|
+
item.type !== "message" ||
|
|
119
|
+
(item.role !== "user" && item.role !== "assistant") ||
|
|
120
|
+
item.channel === "analysis"
|
|
121
|
+
) {
|
|
122
|
+
return undefined;
|
|
123
|
+
}
|
|
124
|
+
let content = item.content;
|
|
125
|
+
if (item.role === "user" && item.internal_chat_message_metadata_passthrough !== undefined) {
|
|
126
|
+
const metadata = object(item.internal_chat_message_metadata_passthrough);
|
|
127
|
+
if (Array.isArray(metadata.content_item_kinds) && Array.isArray(content)) {
|
|
128
|
+
// Desktop stores injected AGENTS.md and environment context as user-role content too.
|
|
129
|
+
const kinds = metadata.content_item_kinds;
|
|
130
|
+
content = content.filter((_part, index) =>
|
|
131
|
+
string(kinds[index], "content_item_kinds").startsWith("user."),
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
const text = cleanBody(textContent(content, ["input_text", "output_text"]));
|
|
136
|
+
if (!text) return undefined;
|
|
137
|
+
const isSummary =
|
|
138
|
+
summary !== undefined &&
|
|
139
|
+
((summary !== "" && text === cleanBody(summary)) ||
|
|
140
|
+
text.startsWith(
|
|
141
|
+
"Another language model started to solve this problem and produced a summary",
|
|
142
|
+
));
|
|
143
|
+
return { role: isSummary ? "summary" : item.role, text };
|
|
144
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import type { Stats } from "node:fs";
|
|
2
|
+
import { readFile, readdir, stat } from "node:fs/promises";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { basename, join, resolve } from "node:path";
|
|
5
|
+
import { parseClaudeSession } from "./claude.ts";
|
|
6
|
+
import { parseCodexSession } from "./codex.ts";
|
|
7
|
+
import { jsonl, string } from "./jsonl.ts";
|
|
8
|
+
import { SOURCE_NAMES, type ExternalSession, type SessionSource } from "./session.ts";
|
|
9
|
+
import type { SessionFile } from "./session-index.ts";
|
|
10
|
+
|
|
11
|
+
type ExternalSource = Exclude<SessionSource, "pi">;
|
|
12
|
+
|
|
13
|
+
/** Codex and Claude Code session files; the Codex title index is cached per Pi session. */
|
|
14
|
+
export class ExternalSessions {
|
|
15
|
+
private readonly codexHome = resolve(process.env["CODEX_HOME"] ?? join(homedir(), ".codex"));
|
|
16
|
+
private readonly claudeHome = resolve(
|
|
17
|
+
process.env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude"),
|
|
18
|
+
);
|
|
19
|
+
private titleIndex: { version: string; names: Map<string, string> } | undefined;
|
|
20
|
+
|
|
21
|
+
async list(signal: AbortSignal, report: (error: unknown) => void): Promise<SessionFile[]> {
|
|
22
|
+
const errors: Error[] = [];
|
|
23
|
+
const sources: ExternalSource[] = ["codex", "claude"];
|
|
24
|
+
const results = await Promise.all(
|
|
25
|
+
sources.map(async (source) => {
|
|
26
|
+
try {
|
|
27
|
+
const paths = await this.paths(source);
|
|
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(
|
|
35
|
+
source,
|
|
36
|
+
path,
|
|
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));
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
50
|
+
return files.filter((file) => file !== undefined);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
signal.throwIfAborted();
|
|
53
|
+
errors.push(
|
|
54
|
+
fileError(
|
|
55
|
+
source,
|
|
56
|
+
source === "codex" ? this.codexHome : this.claudeHome,
|
|
57
|
+
error,
|
|
58
|
+
),
|
|
59
|
+
);
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
signal.throwIfAborted();
|
|
65
|
+
if (errors.length > 0) {
|
|
66
|
+
report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
|
|
67
|
+
}
|
|
68
|
+
return results.flat();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
clear(): void {
|
|
72
|
+
this.titleIndex = undefined;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
private async paths(source: ExternalSource): Promise<string[]> {
|
|
76
|
+
const root = join(
|
|
77
|
+
source === "codex" ? this.codexHome : this.claudeHome,
|
|
78
|
+
source === "codex" ? "sessions" : "projects",
|
|
79
|
+
);
|
|
80
|
+
let projects: string[];
|
|
81
|
+
try {
|
|
82
|
+
if (source === "codex") {
|
|
83
|
+
return (await readdir(root, { recursive: true }))
|
|
84
|
+
.filter((file) => /^rollout-.+\.jsonl$/.test(basename(file)))
|
|
85
|
+
.map((file) => join(root, file));
|
|
86
|
+
}
|
|
87
|
+
projects = (await readdir(root, { withFileTypes: true }))
|
|
88
|
+
.filter((entry) => entry.isDirectory())
|
|
89
|
+
.map((entry) => join(root, entry.name));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
// Neither external tool is required to be installed; only an absent store is empty.
|
|
92
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
// Subagents and tool-result stores are nested below the main files; never traverse them.
|
|
96
|
+
const files = await Promise.all(
|
|
97
|
+
projects.map(async (project) =>
|
|
98
|
+
(await readdir(project, { withFileTypes: true }))
|
|
99
|
+
.filter(
|
|
100
|
+
(entry) =>
|
|
101
|
+
entry.isFile() &&
|
|
102
|
+
entry.name.endsWith(".jsonl") &&
|
|
103
|
+
!entry.name.startsWith("agent-"),
|
|
104
|
+
)
|
|
105
|
+
.map((entry) => join(project, entry.name)),
|
|
106
|
+
),
|
|
107
|
+
);
|
|
108
|
+
return files.flat();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
private async codexNames(signal: AbortSignal): Promise<Map<string, string>> {
|
|
112
|
+
const path = join(this.codexHome, "session_index.jsonl");
|
|
113
|
+
let content: string;
|
|
114
|
+
let version: string;
|
|
115
|
+
try {
|
|
116
|
+
const stats = await stat(path);
|
|
117
|
+
version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
|
|
118
|
+
if (this.titleIndex?.version === version) return this.titleIndex.names;
|
|
119
|
+
content = await readFile(path, { encoding: "utf8", signal });
|
|
120
|
+
} catch (error) {
|
|
121
|
+
// The title index is optional; the rollout itself owns the session and its messages.
|
|
122
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
123
|
+
this.titleIndex = undefined;
|
|
124
|
+
return new Map();
|
|
125
|
+
}
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
const names = new Map<string, string>();
|
|
129
|
+
try {
|
|
130
|
+
for (const record of jsonl(content, path)) {
|
|
131
|
+
names.set(
|
|
132
|
+
string(record.id, "session_index.id"),
|
|
133
|
+
string(record.thread_name, "thread_name"),
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
} catch {
|
|
137
|
+
// TODO: Record Codex title parser errors in Core Log when it is available.
|
|
138
|
+
names.clear();
|
|
139
|
+
}
|
|
140
|
+
if (!signal.aborted) this.titleIndex = { version, names };
|
|
141
|
+
return names;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
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
|
+
|
|
172
|
+
export function parseExternalSession(
|
|
173
|
+
source: ExternalSource,
|
|
174
|
+
content: string,
|
|
175
|
+
path: string,
|
|
176
|
+
): ExternalSession | undefined {
|
|
177
|
+
try {
|
|
178
|
+
return source === "codex"
|
|
179
|
+
? parseCodexSession(content, path)
|
|
180
|
+
: parseClaudeSession(content, path);
|
|
181
|
+
} catch {
|
|
182
|
+
// TODO: Record Codex and Claude Code parser errors in Core Log when it is available.
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function fileError(source: ExternalSource, path: string, error: unknown): Error {
|
|
188
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
189
|
+
return new Error(`${SOURCE_NAMES[source]}: ${path}: ${message}`, { cause: error });
|
|
190
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { access, mkdir, readFile, stat, writeFile } from "node:fs/promises";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
import type { ResourceScope } from "../resources/resources.ts";
|
|
7
|
+
import { createMentionAutocomplete } from "./autocomplete.ts";
|
|
8
|
+
import { SessionCatalog } from "./catalog.ts";
|
|
9
|
+
import {
|
|
10
|
+
fileReference,
|
|
11
|
+
findMentions,
|
|
12
|
+
replaceMentions,
|
|
13
|
+
resolveMention,
|
|
14
|
+
type Mention,
|
|
15
|
+
} from "./mention.ts";
|
|
16
|
+
import { ExternalSessionParseError, type LocalSession } from "./session.ts";
|
|
17
|
+
import { buildTranscript } from "./transcript.ts";
|
|
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
|
+
|
|
29
|
+
/**
|
|
30
|
+
* `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
|
|
31
|
+
* session becomes a source-specific token. On submit, each such token becomes an `@` reference to
|
|
32
|
+
* a filtered copy of that session, which the model reads when it needs the background.
|
|
33
|
+
*/
|
|
34
|
+
export function installMentions(
|
|
35
|
+
pi: ExtensionAPI,
|
|
36
|
+
resources: ResourceScope,
|
|
37
|
+
options: MentionOptions = {},
|
|
38
|
+
): void {
|
|
39
|
+
let catalog: SessionCatalog | undefined;
|
|
40
|
+
const transcripts = new TranscriptCache();
|
|
41
|
+
const retire = () => {
|
|
42
|
+
catalog?.dispose();
|
|
43
|
+
catalog = undefined;
|
|
44
|
+
};
|
|
45
|
+
resources.defer(retire);
|
|
46
|
+
|
|
47
|
+
resources.defer(
|
|
48
|
+
pi.on("session_start", (_event, ctx) => {
|
|
49
|
+
retire();
|
|
50
|
+
const report = (error: unknown) => {
|
|
51
|
+
// A retired scan can settle after Pi invalidates its session context.
|
|
52
|
+
if (catalog !== sessions) return;
|
|
53
|
+
ctx.ui.notify(`Session list failed: ${errorMessage(error)}`, "error");
|
|
54
|
+
};
|
|
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
|
+
);
|
|
62
|
+
catalog = sessions;
|
|
63
|
+
if (ctx.mode !== "tui") return;
|
|
64
|
+
// Pi drops autocomplete wrappers when it replaces the session, so add one per start.
|
|
65
|
+
ctx.ui.addAutocompleteProvider((current) =>
|
|
66
|
+
createMentionAutocomplete(current, {
|
|
67
|
+
catalog: sessions,
|
|
68
|
+
currentSessionFile: ctx.sessionManager.getSessionFile(),
|
|
69
|
+
}),
|
|
70
|
+
);
|
|
71
|
+
// Read the sessions now, so the first `@` already lists them.
|
|
72
|
+
sessions.reload().catch(report);
|
|
73
|
+
}),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
resources.defer(
|
|
77
|
+
pi.on("input", async (event, ctx) => {
|
|
78
|
+
const mentions = findMentions(event.text);
|
|
79
|
+
if (mentions.length === 0) return { action: "continue" };
|
|
80
|
+
try {
|
|
81
|
+
if (!catalog) throw new Error("Session mentions have no active session");
|
|
82
|
+
const files = new Map<string, string | undefined>();
|
|
83
|
+
for (const mention of mentions) {
|
|
84
|
+
if (files.has(mention.token)) continue;
|
|
85
|
+
const session = await findSession(catalog, mention);
|
|
86
|
+
files.set(mention.token, await transcripts.file(session));
|
|
87
|
+
}
|
|
88
|
+
return {
|
|
89
|
+
action: "transform",
|
|
90
|
+
text: replaceMentions(event.text, mentions, (mention) => {
|
|
91
|
+
const file = files.get(mention.token);
|
|
92
|
+
return file === undefined ? mention.token : fileReference(file);
|
|
93
|
+
}),
|
|
94
|
+
images: event.images,
|
|
95
|
+
};
|
|
96
|
+
} catch (error) {
|
|
97
|
+
return refuseInput(ctx, event.text, error);
|
|
98
|
+
}
|
|
99
|
+
}),
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function findSession(catalog: SessionCatalog, mention: Mention): Promise<LocalSession> {
|
|
104
|
+
const cached = await catalog.list();
|
|
105
|
+
if (
|
|
106
|
+
cached.some(
|
|
107
|
+
(session) =>
|
|
108
|
+
session.source === mention.source && session.id.startsWith(mention.idPrefix),
|
|
109
|
+
)
|
|
110
|
+
) {
|
|
111
|
+
return resolveMention(mention, cached);
|
|
112
|
+
}
|
|
113
|
+
// A typed id can name a session that is newer than the cached list.
|
|
114
|
+
return resolveMention(mention, await catalog.reload());
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface TranscriptFiles {
|
|
118
|
+
file: string;
|
|
119
|
+
rawFile: string;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Building a copy parses the whole session file, so a session that has not changed since its
|
|
124
|
+
* last mention reuses the copy written then.
|
|
125
|
+
*/
|
|
126
|
+
class TranscriptCache {
|
|
127
|
+
private readonly written = new Map<string, { version: string; files?: TranscriptFiles }>();
|
|
128
|
+
|
|
129
|
+
async file(session: LocalSession): Promise<string | undefined> {
|
|
130
|
+
const stats = await stat(session.path);
|
|
131
|
+
const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}:${session.name ?? ""}`;
|
|
132
|
+
const cached = this.written.get(session.path);
|
|
133
|
+
if (cached?.version === version) {
|
|
134
|
+
if (!cached.files) return undefined;
|
|
135
|
+
if ((await exists(cached.files.file)) && (await exists(cached.files.rawFile))) {
|
|
136
|
+
return cached.files.file;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
try {
|
|
140
|
+
const files = await writeTranscript(session);
|
|
141
|
+
this.written.set(session.path, { version, files });
|
|
142
|
+
return files.file;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (!(error instanceof ExternalSessionParseError)) throw error;
|
|
145
|
+
// TODO: Record invalid external reference snapshots in Core Log when it is available.
|
|
146
|
+
this.written.set(session.path, { version });
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function writeTranscript(session: LocalSession): Promise<TranscriptFiles> {
|
|
153
|
+
const content = await readFile(session.path);
|
|
154
|
+
const directory = join(tmpdir(), "pi-lune-session-refs");
|
|
155
|
+
await mkdir(directory, { recursive: true });
|
|
156
|
+
// Hash the full snapshot: metadata can change without moving the active branch's leaf.
|
|
157
|
+
const hash = createHash("sha256")
|
|
158
|
+
.update(content)
|
|
159
|
+
.update("\0")
|
|
160
|
+
.update(session.name ?? "")
|
|
161
|
+
.digest("hex");
|
|
162
|
+
const name = `${session.source}.${session.id}.${hash}`;
|
|
163
|
+
const rawFile = join(directory, `${name}.jsonl`);
|
|
164
|
+
await writeFile(rawFile, content, { mode: 0o600 });
|
|
165
|
+
const transcript = buildTranscript({ ...session, path: rawFile });
|
|
166
|
+
const file = join(directory, `${name}.md`);
|
|
167
|
+
await writeFile(file, transcript.markdown, { encoding: "utf8", mode: 0o600 });
|
|
168
|
+
return { file, rawFile };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function exists(path: string): Promise<boolean> {
|
|
172
|
+
try {
|
|
173
|
+
await access(path);
|
|
174
|
+
return true;
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* With a UI, a prompt whose session reference fails is not sent, and the text goes back to the
|
|
182
|
+
* editor to correct. Without one the error is raised; pi reports it and sends the original text.
|
|
183
|
+
*/
|
|
184
|
+
function refuseInput(ctx: ExtensionContext, text: string, error: unknown): { action: "handled" } {
|
|
185
|
+
if (!ctx.hasUI) throw error;
|
|
186
|
+
ctx.ui.notify(`Prompt not sent. ${errorMessage(error)}`, "error");
|
|
187
|
+
ctx.ui.setEditorText(text);
|
|
188
|
+
return { action: "handled" };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function errorMessage(error: unknown): string {
|
|
192
|
+
return error instanceof Error ? error.message : String(error);
|
|
193
|
+
}
|