@lune_99/pi-lune-extensions-core 0.1.0 → 0.2.0
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 +40 -0
- package/README.md +100 -34
- package/dist/dock/registry.js +1 -0
- package/dist/extension.js +6 -2
- package/dist/mention/autocomplete.d.ts +23 -0
- package/dist/mention/autocomplete.js +135 -0
- package/dist/mention/catalog.d.ts +26 -0
- package/dist/mention/catalog.js +76 -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 +151 -0
- package/dist/mention/index.d.ts +8 -0
- package/dist/mention/index.js +150 -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/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 +100 -24
- 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/dock/registry.ts +1 -0
- package/src/extension.ts +6 -2
- package/src/mention/autocomplete.ts +173 -0
- package/src/mention/catalog.ts +84 -0
- package/src/mention/claude.ts +127 -0
- package/src/mention/codex.ts +144 -0
- package/src/mention/external.ts +191 -0
- package/src/mention/index.ts +173 -0
- package/src/mention/jsonl.ts +56 -0
- package/src/mention/mention.ts +90 -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 +105 -23
- 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,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,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 LocalSession, type SessionSource } from "./session.ts";
|
|
2
|
+
type ExternalSource = Exclude<SessionSource, "pi">;
|
|
3
|
+
/** File metadata caches belong to the running Pi session, just like the combined catalog. */
|
|
4
|
+
export declare class ExternalSessions {
|
|
5
|
+
private readonly codexHome;
|
|
6
|
+
private readonly claudeHome;
|
|
7
|
+
private readonly cached;
|
|
8
|
+
private titleIndex;
|
|
9
|
+
list(signal: AbortSignal, report: (error: unknown) => void): Promise<LocalSession[]>;
|
|
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,151 @@
|
|
|
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
|
+
/** File metadata caches belong to the running Pi session, just like the combined catalog. */
|
|
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
|
+
cached = new Map();
|
|
13
|
+
titleIndex;
|
|
14
|
+
async list(signal, report) {
|
|
15
|
+
const errors = [];
|
|
16
|
+
const seen = new Set();
|
|
17
|
+
const sources = ["codex", "claude"];
|
|
18
|
+
const results = await Promise.all(sources.map(async (source) => {
|
|
19
|
+
try {
|
|
20
|
+
const paths = await this.paths(source);
|
|
21
|
+
const names = source === "codex" ? await this.codexNames(signal) : new Map();
|
|
22
|
+
const sessions = [];
|
|
23
|
+
// One file per source at a time bounds memory when rollouts contain large tool results.
|
|
24
|
+
for (const path of paths) {
|
|
25
|
+
signal.throwIfAborted();
|
|
26
|
+
seen.add(path);
|
|
27
|
+
try {
|
|
28
|
+
const stats = await stat(path);
|
|
29
|
+
const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
|
|
30
|
+
let cached = this.cached.get(path);
|
|
31
|
+
if (cached?.version !== version) {
|
|
32
|
+
cached = { version };
|
|
33
|
+
const content = await readFile(path, { encoding: "utf8", signal });
|
|
34
|
+
cached.session = parseExternalSession(source, content, path)?.session;
|
|
35
|
+
if (!signal.aborted)
|
|
36
|
+
this.cached.set(path, cached);
|
|
37
|
+
}
|
|
38
|
+
if (cached.session) {
|
|
39
|
+
const name = source === "codex"
|
|
40
|
+
? names.get(cached.session.id)
|
|
41
|
+
: cached.session.name;
|
|
42
|
+
if (name !== cached.session.name) {
|
|
43
|
+
cached.session = { ...cached.session, name };
|
|
44
|
+
}
|
|
45
|
+
// Stable objects preserve autocomplete's existing WeakMap search cache.
|
|
46
|
+
sessions.push(cached.session);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
signal.throwIfAborted();
|
|
51
|
+
errors.push(fileError(source, path, error));
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return sessions;
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
signal.throwIfAborted();
|
|
58
|
+
errors.push(fileError(source, source === "codex" ? this.codexHome : this.claudeHome, error));
|
|
59
|
+
return [];
|
|
60
|
+
}
|
|
61
|
+
}));
|
|
62
|
+
signal.throwIfAborted();
|
|
63
|
+
for (const path of this.cached.keys()) {
|
|
64
|
+
if (!seen.has(path))
|
|
65
|
+
this.cached.delete(path);
|
|
66
|
+
}
|
|
67
|
+
if (errors.length > 0) {
|
|
68
|
+
report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
|
|
69
|
+
}
|
|
70
|
+
return results.flat();
|
|
71
|
+
}
|
|
72
|
+
clear() {
|
|
73
|
+
this.cached.clear();
|
|
74
|
+
this.titleIndex = undefined;
|
|
75
|
+
}
|
|
76
|
+
async paths(source) {
|
|
77
|
+
const root = join(source === "codex" ? this.codexHome : this.claudeHome, source === "codex" ? "sessions" : "projects");
|
|
78
|
+
let projects;
|
|
79
|
+
try {
|
|
80
|
+
if (source === "codex") {
|
|
81
|
+
return (await readdir(root, { recursive: true }))
|
|
82
|
+
.filter((file) => /^rollout-.+\.jsonl$/.test(basename(file)))
|
|
83
|
+
.map((file) => join(root, file));
|
|
84
|
+
}
|
|
85
|
+
projects = (await readdir(root, { withFileTypes: true }))
|
|
86
|
+
.filter((entry) => entry.isDirectory())
|
|
87
|
+
.map((entry) => join(root, entry.name));
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
// Neither external tool is required to be installed; only an absent store is empty.
|
|
91
|
+
if (error.code === "ENOENT")
|
|
92
|
+
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(projects.map(async (project) => (await readdir(project, { withFileTypes: true }))
|
|
97
|
+
.filter((entry) => entry.isFile() &&
|
|
98
|
+
entry.name.endsWith(".jsonl") &&
|
|
99
|
+
!entry.name.startsWith("agent-"))
|
|
100
|
+
.map((entry) => join(project, entry.name))));
|
|
101
|
+
return files.flat();
|
|
102
|
+
}
|
|
103
|
+
async codexNames(signal) {
|
|
104
|
+
const path = join(this.codexHome, "session_index.jsonl");
|
|
105
|
+
let content;
|
|
106
|
+
let version;
|
|
107
|
+
try {
|
|
108
|
+
const stats = await stat(path);
|
|
109
|
+
version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
|
|
110
|
+
if (this.titleIndex?.version === version)
|
|
111
|
+
return this.titleIndex.names;
|
|
112
|
+
content = await readFile(path, { encoding: "utf8", signal });
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
// The title index is optional; the rollout itself owns the session and its messages.
|
|
116
|
+
if (error.code === "ENOENT") {
|
|
117
|
+
this.titleIndex = undefined;
|
|
118
|
+
return new Map();
|
|
119
|
+
}
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
const names = new Map();
|
|
123
|
+
try {
|
|
124
|
+
for (const record of jsonl(content, path)) {
|
|
125
|
+
names.set(string(record.id, "session_index.id"), string(record.thread_name, "thread_name"));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
// TODO: Record Codex title parser errors in Core Log when it is available.
|
|
130
|
+
names.clear();
|
|
131
|
+
}
|
|
132
|
+
if (!signal.aborted)
|
|
133
|
+
this.titleIndex = { version, names };
|
|
134
|
+
return names;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function parseExternalSession(source, content, path) {
|
|
138
|
+
try {
|
|
139
|
+
return source === "codex"
|
|
140
|
+
? parseCodexSession(content, path)
|
|
141
|
+
: parseClaudeSession(content, path);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
// TODO: Record Codex and Claude Code parser errors in Core Log when it is available.
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
function fileError(source, path, error) {
|
|
149
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
150
|
+
return new Error(`${SOURCE_NAMES[source]}: ${path}: ${message}`, { cause: error });
|
|
151
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { ResourceScope } from "../resources/resources.ts";
|
|
3
|
+
/**
|
|
4
|
+
* `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
|
|
5
|
+
* session becomes a source-specific token. On submit, each such token becomes an `@` reference to
|
|
6
|
+
* a filtered copy of that session, which the model reads when it needs the background.
|
|
7
|
+
*/
|
|
8
|
+
export declare function installMentions(pi: ExtensionAPI, resources: ResourceScope): void;
|
|
@@ -0,0 +1,150 @@
|
|
|
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 { createMentionAutocomplete } from "./autocomplete.js";
|
|
6
|
+
import { SessionCatalog } from "./catalog.js";
|
|
7
|
+
import { fileReference, findMentions, replaceMentions, resolveMention, } from "./mention.js";
|
|
8
|
+
import { ExternalSessionParseError } from "./session.js";
|
|
9
|
+
import { buildTranscript } from "./transcript.js";
|
|
10
|
+
/**
|
|
11
|
+
* `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
|
|
12
|
+
* session becomes a source-specific token. On submit, each such token becomes an `@` reference to
|
|
13
|
+
* a filtered copy of that session, which the model reads when it needs the background.
|
|
14
|
+
*/
|
|
15
|
+
export function installMentions(pi, resources) {
|
|
16
|
+
let catalog;
|
|
17
|
+
const transcripts = new TranscriptCache();
|
|
18
|
+
const retire = () => {
|
|
19
|
+
catalog?.dispose();
|
|
20
|
+
catalog = undefined;
|
|
21
|
+
};
|
|
22
|
+
resources.defer(retire);
|
|
23
|
+
resources.defer(pi.on("session_start", (_event, ctx) => {
|
|
24
|
+
retire();
|
|
25
|
+
const report = (error) => {
|
|
26
|
+
// A retired scan can settle after Pi invalidates its session context.
|
|
27
|
+
if (catalog !== sessions)
|
|
28
|
+
return;
|
|
29
|
+
ctx.ui.notify(`Session list failed: ${errorMessage(error)}`, "error");
|
|
30
|
+
};
|
|
31
|
+
const sessions = new SessionCatalog(ctx.sessionManager.getSessionDir(), report);
|
|
32
|
+
catalog = sessions;
|
|
33
|
+
if (ctx.mode !== "tui")
|
|
34
|
+
return;
|
|
35
|
+
// Pi drops autocomplete wrappers when it replaces the session, so add one per start.
|
|
36
|
+
ctx.ui.addAutocompleteProvider((current) => createMentionAutocomplete(current, {
|
|
37
|
+
catalog: sessions,
|
|
38
|
+
currentSessionFile: ctx.sessionManager.getSessionFile(),
|
|
39
|
+
}));
|
|
40
|
+
// Read the sessions now, so the first `@` already lists them.
|
|
41
|
+
sessions.reload().catch(report);
|
|
42
|
+
}));
|
|
43
|
+
resources.defer(pi.on("input", async (event, ctx) => {
|
|
44
|
+
const mentions = findMentions(event.text);
|
|
45
|
+
if (mentions.length === 0)
|
|
46
|
+
return { action: "continue" };
|
|
47
|
+
try {
|
|
48
|
+
if (!catalog)
|
|
49
|
+
throw new Error("Session mentions have no active session");
|
|
50
|
+
const files = new Map();
|
|
51
|
+
for (const mention of mentions) {
|
|
52
|
+
if (files.has(mention.token))
|
|
53
|
+
continue;
|
|
54
|
+
const session = await findSession(catalog, mention);
|
|
55
|
+
files.set(mention.token, await transcripts.file(session));
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
action: "transform",
|
|
59
|
+
text: replaceMentions(event.text, mentions, (mention) => {
|
|
60
|
+
const file = files.get(mention.token);
|
|
61
|
+
return file === undefined ? mention.token : fileReference(file);
|
|
62
|
+
}),
|
|
63
|
+
images: event.images,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
return refuseInput(ctx, event.text, error);
|
|
68
|
+
}
|
|
69
|
+
}));
|
|
70
|
+
}
|
|
71
|
+
async function findSession(catalog, mention) {
|
|
72
|
+
const cached = await catalog.list();
|
|
73
|
+
if (cached.some((session) => session.source === mention.source && session.id.startsWith(mention.idPrefix))) {
|
|
74
|
+
return resolveMention(mention, cached);
|
|
75
|
+
}
|
|
76
|
+
// A typed id can name a session that is newer than the cached list.
|
|
77
|
+
return resolveMention(mention, await catalog.reload());
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Building a copy parses the whole session file, so a session that has not changed since its
|
|
81
|
+
* last mention reuses the copy written then.
|
|
82
|
+
*/
|
|
83
|
+
class TranscriptCache {
|
|
84
|
+
written = new Map();
|
|
85
|
+
async file(session) {
|
|
86
|
+
const stats = await stat(session.path);
|
|
87
|
+
const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}:${session.name ?? ""}`;
|
|
88
|
+
const cached = this.written.get(session.path);
|
|
89
|
+
if (cached?.version === version) {
|
|
90
|
+
if (!cached.files)
|
|
91
|
+
return undefined;
|
|
92
|
+
if ((await exists(cached.files.file)) && (await exists(cached.files.rawFile))) {
|
|
93
|
+
return cached.files.file;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
const files = await writeTranscript(session);
|
|
98
|
+
this.written.set(session.path, { version, files });
|
|
99
|
+
return files.file;
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (!(error instanceof ExternalSessionParseError))
|
|
103
|
+
throw error;
|
|
104
|
+
// TODO: Record invalid external reference snapshots in Core Log when it is available.
|
|
105
|
+
this.written.set(session.path, { version });
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function writeTranscript(session) {
|
|
111
|
+
const content = await readFile(session.path);
|
|
112
|
+
const directory = join(tmpdir(), "pi-lune-session-refs");
|
|
113
|
+
await mkdir(directory, { recursive: true });
|
|
114
|
+
// Hash the full snapshot: metadata can change without moving the active branch's leaf.
|
|
115
|
+
const hash = createHash("sha256")
|
|
116
|
+
.update(content)
|
|
117
|
+
.update("\0")
|
|
118
|
+
.update(session.name ?? "")
|
|
119
|
+
.digest("hex");
|
|
120
|
+
const name = `${session.source}.${session.id}.${hash}`;
|
|
121
|
+
const rawFile = join(directory, `${name}.jsonl`);
|
|
122
|
+
await writeFile(rawFile, content, { mode: 0o600 });
|
|
123
|
+
const transcript = buildTranscript({ ...session, path: rawFile });
|
|
124
|
+
const file = join(directory, `${name}.md`);
|
|
125
|
+
await writeFile(file, transcript.markdown, { encoding: "utf8", mode: 0o600 });
|
|
126
|
+
return { file, rawFile };
|
|
127
|
+
}
|
|
128
|
+
async function exists(path) {
|
|
129
|
+
try {
|
|
130
|
+
await access(path);
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* With a UI, a prompt whose session reference fails is not sent, and the text goes back to the
|
|
139
|
+
* editor to correct. Without one the error is raised; pi reports it and sends the original text.
|
|
140
|
+
*/
|
|
141
|
+
function refuseInput(ctx, text, error) {
|
|
142
|
+
if (!ctx.hasUI)
|
|
143
|
+
throw error;
|
|
144
|
+
ctx.ui.notify(`Prompt not sent. ${errorMessage(error)}`, "error");
|
|
145
|
+
ctx.ui.setEditorText(text);
|
|
146
|
+
return { action: "handled" };
|
|
147
|
+
}
|
|
148
|
+
function errorMessage(error) {
|
|
149
|
+
return error instanceof Error ? error.message : String(error);
|
|
150
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type JsonObject = Record<string, unknown>;
|
|
2
|
+
export declare function object(value: unknown): JsonObject;
|
|
3
|
+
/** Parse one record at a time so large tool payloads are not all retained with the messages. */
|
|
4
|
+
export declare function jsonl(content: string, path: string): Generator<JsonObject>;
|
|
5
|
+
export declare function string(value: unknown, field: string): string;
|
|
6
|
+
export declare function sessionId(value: unknown, field: string): string;
|
|
7
|
+
export declare function date(value: unknown, field: string): Date;
|
|
8
|
+
/** Only text blocks belong in the reference; images, thinking and tool payloads stay in JSONL. */
|
|
9
|
+
export declare function textContent(value: unknown, types: readonly string[]): string;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export function object(value) {
|
|
2
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
3
|
+
throw new Error("Expected a JSON object");
|
|
4
|
+
}
|
|
5
|
+
return value;
|
|
6
|
+
}
|
|
7
|
+
/** Parse one record at a time so large tool payloads are not all retained with the messages. */
|
|
8
|
+
export function* jsonl(content, path) {
|
|
9
|
+
let start = 0;
|
|
10
|
+
let line = 0;
|
|
11
|
+
while (start < content.length) {
|
|
12
|
+
const end = content.indexOf("\n", start);
|
|
13
|
+
const text = content.slice(start, end === -1 ? content.length : end);
|
|
14
|
+
start = end === -1 ? content.length : end + 1;
|
|
15
|
+
line++;
|
|
16
|
+
if (!text.trim())
|
|
17
|
+
continue;
|
|
18
|
+
try {
|
|
19
|
+
yield object(JSON.parse(text));
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
throw new Error(`Invalid JSONL at ${path}:${line}`, { cause: error });
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
export function string(value, field) {
|
|
27
|
+
if (typeof value !== "string")
|
|
28
|
+
throw new Error(`Expected a string for ${field}`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
export function sessionId(value, field) {
|
|
32
|
+
const id = string(value, field);
|
|
33
|
+
// Ids become mention tokens and temporary filenames, so path separators are never valid.
|
|
34
|
+
if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
|
|
35
|
+
throw new Error(`Invalid session id for ${field}`);
|
|
36
|
+
}
|
|
37
|
+
return id;
|
|
38
|
+
}
|
|
39
|
+
export function date(value, field) {
|
|
40
|
+
const parsed = new Date(string(value, field));
|
|
41
|
+
if (!Number.isFinite(parsed.getTime()))
|
|
42
|
+
throw new Error(`Invalid date for ${field}`);
|
|
43
|
+
return parsed;
|
|
44
|
+
}
|
|
45
|
+
/** Only text blocks belong in the reference; images, thinking and tool payloads stay in JSONL. */
|
|
46
|
+
export function textContent(value, types) {
|
|
47
|
+
if (!Array.isArray(value))
|
|
48
|
+
throw new Error("Expected an array of content blocks");
|
|
49
|
+
return value
|
|
50
|
+
.map((part) => object(part))
|
|
51
|
+
.filter((part) => types.includes(string(part.type, "content.type")))
|
|
52
|
+
.map((part) => string(part.text, "content.text"))
|
|
53
|
+
.join("\n");
|
|
54
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { LocalSession, SessionSource } from "./session.ts";
|
|
2
|
+
export declare const TOKEN_PREFIX = "@session:";
|
|
3
|
+
export interface Mention {
|
|
4
|
+
/** Offset of the source-specific token in the text. */
|
|
5
|
+
index: number;
|
|
6
|
+
token: string;
|
|
7
|
+
source: SessionSource;
|
|
8
|
+
idPrefix: string;
|
|
9
|
+
}
|
|
10
|
+
/** The shortest id prefix, from MIN_ID_LENGTH up, that names only this session. */
|
|
11
|
+
export declare function shortSessionId(id: string, sessions: readonly LocalSession[]): string;
|
|
12
|
+
export declare function mentionToken(session: LocalSession, sessions: readonly LocalSession[]): string;
|
|
13
|
+
export declare function findMentions(text: string): Mention[];
|
|
14
|
+
/** Throws when the prefix names no session or more than one. */
|
|
15
|
+
export declare function resolveMention(mention: Pick<Mention, "source" | "idPrefix">, sessions: readonly LocalSession[]): LocalSession;
|
|
16
|
+
/** Replace each mention with the editor text for its file, keeping all other text. */
|
|
17
|
+
export declare function replaceMentions(text: string, mentions: readonly Mention[], replacement: (mention: Mention) => string): string;
|
|
18
|
+
/** Pi's `@` file reference, quoted like its own completion when the path has whitespace. */
|
|
19
|
+
export declare function fileReference(path: string): string;
|