@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,151 @@
|
|
|
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, options = {}) {
|
|
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 { indexBudget, indexTextLimit } = options;
|
|
32
|
+
const sessions = new SessionCatalog(ctx.sessionManager.getSessionDir(), report, indexBudget && (() => indexBudget(ctx)), indexTextLimit && (() => indexTextLimit(ctx)));
|
|
33
|
+
catalog = sessions;
|
|
34
|
+
if (ctx.mode !== "tui")
|
|
35
|
+
return;
|
|
36
|
+
// Pi drops autocomplete wrappers when it replaces the session, so add one per start.
|
|
37
|
+
ctx.ui.addAutocompleteProvider((current) => createMentionAutocomplete(current, {
|
|
38
|
+
catalog: sessions,
|
|
39
|
+
currentSessionFile: ctx.sessionManager.getSessionFile(),
|
|
40
|
+
}));
|
|
41
|
+
// Read the sessions now, so the first `@` already lists them.
|
|
42
|
+
sessions.reload().catch(report);
|
|
43
|
+
}));
|
|
44
|
+
resources.defer(pi.on("input", async (event, ctx) => {
|
|
45
|
+
const mentions = findMentions(event.text);
|
|
46
|
+
if (mentions.length === 0)
|
|
47
|
+
return { action: "continue" };
|
|
48
|
+
try {
|
|
49
|
+
if (!catalog)
|
|
50
|
+
throw new Error("Session mentions have no active session");
|
|
51
|
+
const files = new Map();
|
|
52
|
+
for (const mention of mentions) {
|
|
53
|
+
if (files.has(mention.token))
|
|
54
|
+
continue;
|
|
55
|
+
const session = await findSession(catalog, mention);
|
|
56
|
+
files.set(mention.token, await transcripts.file(session));
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
action: "transform",
|
|
60
|
+
text: replaceMentions(event.text, mentions, (mention) => {
|
|
61
|
+
const file = files.get(mention.token);
|
|
62
|
+
return file === undefined ? mention.token : fileReference(file);
|
|
63
|
+
}),
|
|
64
|
+
images: event.images,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
return refuseInput(ctx, event.text, error);
|
|
69
|
+
}
|
|
70
|
+
}));
|
|
71
|
+
}
|
|
72
|
+
async function findSession(catalog, mention) {
|
|
73
|
+
const cached = await catalog.list();
|
|
74
|
+
if (cached.some((session) => session.source === mention.source && session.id.startsWith(mention.idPrefix))) {
|
|
75
|
+
return resolveMention(mention, cached);
|
|
76
|
+
}
|
|
77
|
+
// A typed id can name a session that is newer than the cached list.
|
|
78
|
+
return resolveMention(mention, await catalog.reload());
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Building a copy parses the whole session file, so a session that has not changed since its
|
|
82
|
+
* last mention reuses the copy written then.
|
|
83
|
+
*/
|
|
84
|
+
class TranscriptCache {
|
|
85
|
+
written = new Map();
|
|
86
|
+
async file(session) {
|
|
87
|
+
const stats = await stat(session.path);
|
|
88
|
+
const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}:${session.name ?? ""}`;
|
|
89
|
+
const cached = this.written.get(session.path);
|
|
90
|
+
if (cached?.version === version) {
|
|
91
|
+
if (!cached.files)
|
|
92
|
+
return undefined;
|
|
93
|
+
if ((await exists(cached.files.file)) && (await exists(cached.files.rawFile))) {
|
|
94
|
+
return cached.files.file;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
try {
|
|
98
|
+
const files = await writeTranscript(session);
|
|
99
|
+
this.written.set(session.path, { version, files });
|
|
100
|
+
return files.file;
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
if (!(error instanceof ExternalSessionParseError))
|
|
104
|
+
throw error;
|
|
105
|
+
// TODO: Record invalid external reference snapshots in Core Log when it is available.
|
|
106
|
+
this.written.set(session.path, { version });
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
async function writeTranscript(session) {
|
|
112
|
+
const content = await readFile(session.path);
|
|
113
|
+
const directory = join(tmpdir(), "pi-lune-session-refs");
|
|
114
|
+
await mkdir(directory, { recursive: true });
|
|
115
|
+
// Hash the full snapshot: metadata can change without moving the active branch's leaf.
|
|
116
|
+
const hash = createHash("sha256")
|
|
117
|
+
.update(content)
|
|
118
|
+
.update("\0")
|
|
119
|
+
.update(session.name ?? "")
|
|
120
|
+
.digest("hex");
|
|
121
|
+
const name = `${session.source}.${session.id}.${hash}`;
|
|
122
|
+
const rawFile = join(directory, `${name}.jsonl`);
|
|
123
|
+
await writeFile(rawFile, content, { mode: 0o600 });
|
|
124
|
+
const transcript = buildTranscript({ ...session, path: rawFile });
|
|
125
|
+
const file = join(directory, `${name}.md`);
|
|
126
|
+
await writeFile(file, transcript.markdown, { encoding: "utf8", mode: 0o600 });
|
|
127
|
+
return { file, rawFile };
|
|
128
|
+
}
|
|
129
|
+
async function exists(path) {
|
|
130
|
+
try {
|
|
131
|
+
await access(path);
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* With a UI, a prompt whose session reference fails is not sent, and the text goes back to the
|
|
140
|
+
* editor to correct. Without one the error is raised; pi reports it and sends the original text.
|
|
141
|
+
*/
|
|
142
|
+
function refuseInput(ctx, text, error) {
|
|
143
|
+
if (!ctx.hasUI)
|
|
144
|
+
throw error;
|
|
145
|
+
ctx.ui.notify(`Prompt not sent. ${errorMessage(error)}`, "error");
|
|
146
|
+
ctx.ui.setEditorText(text);
|
|
147
|
+
return { action: "handled" };
|
|
148
|
+
}
|
|
149
|
+
function errorMessage(error) {
|
|
150
|
+
return error instanceof Error ? error.message : String(error);
|
|
151
|
+
}
|
|
@@ -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;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { TOKEN_BOUNDARY } from "./text.js";
|
|
2
|
+
export const TOKEN_PREFIX = "@session:";
|
|
3
|
+
const TOKEN_PREFIXES = {
|
|
4
|
+
pi: TOKEN_PREFIX,
|
|
5
|
+
codex: "@codex:",
|
|
6
|
+
claude: "@claude:",
|
|
7
|
+
};
|
|
8
|
+
/** UUIDv7 ids carry the creation time in their first 12 hex digits (`01a14931-31bb`). */
|
|
9
|
+
const MIN_ID_LENGTH = 13;
|
|
10
|
+
// Session ids follow pi's assertValidSessionId(): alphanumeric at both ends, `._-` inside.
|
|
11
|
+
const mentionPattern = new RegExp(`(?<=${TOKEN_BOUNDARY})@(session|codex|claude):([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)`, "gu");
|
|
12
|
+
/** The shortest id prefix, from MIN_ID_LENGTH up, that names only this session. */
|
|
13
|
+
export function shortSessionId(id, sessions) {
|
|
14
|
+
for (let length = Math.min(MIN_ID_LENGTH, id.length); length < id.length; length++) {
|
|
15
|
+
const prefix = id.slice(0, length);
|
|
16
|
+
if (!/[A-Za-z0-9]$/.test(prefix))
|
|
17
|
+
continue;
|
|
18
|
+
if (sessions.every((other) => other.id === id || !other.id.startsWith(prefix))) {
|
|
19
|
+
return prefix;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return id;
|
|
23
|
+
}
|
|
24
|
+
export function mentionToken(session, sessions) {
|
|
25
|
+
const sameSource = sessions.filter((other) => other.source === session.source);
|
|
26
|
+
return `${TOKEN_PREFIXES[session.source]}${shortSessionId(session.id, sameSource)}`;
|
|
27
|
+
}
|
|
28
|
+
export function findMentions(text) {
|
|
29
|
+
return [...text.matchAll(mentionPattern)].map((match) => ({
|
|
30
|
+
index: match.index,
|
|
31
|
+
token: match[0],
|
|
32
|
+
source: match[1] === "session" ? "pi" : match[1],
|
|
33
|
+
idPrefix: match[2],
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
/** Throws when the prefix names no session or more than one. */
|
|
37
|
+
export function resolveMention(mention, sessions) {
|
|
38
|
+
const { source, idPrefix } = mention;
|
|
39
|
+
const token = `${TOKEN_PREFIXES[source]}${idPrefix}`;
|
|
40
|
+
const matches = sessions.filter((session) => session.source === source && session.id.startsWith(idPrefix));
|
|
41
|
+
if (matches.length === 1)
|
|
42
|
+
return matches[0];
|
|
43
|
+
throw new Error(matches.length === 0
|
|
44
|
+
? `No local session matches ${token}`
|
|
45
|
+
: `${token} matches ${matches.length} sessions; type more of the id`);
|
|
46
|
+
}
|
|
47
|
+
/** Replace each mention with the editor text for its file, keeping all other text. */
|
|
48
|
+
export function replaceMentions(text, mentions, replacement) {
|
|
49
|
+
let result = "";
|
|
50
|
+
let offset = 0;
|
|
51
|
+
for (const mention of mentions) {
|
|
52
|
+
result += text.slice(offset, mention.index) + replacement(mention);
|
|
53
|
+
offset = mention.index + mention.token.length;
|
|
54
|
+
}
|
|
55
|
+
return result + text.slice(offset);
|
|
56
|
+
}
|
|
57
|
+
/** Pi's `@` file reference, quoted like its own completion when the path has whitespace. */
|
|
58
|
+
export function fileReference(path) {
|
|
59
|
+
return /\s/u.test(path) ? `@"${path}"` : `@${path}`;
|
|
60
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { SessionFile } from "./session-index.ts";
|
|
2
|
+
/**
|
|
3
|
+
* Pi session files whose sessions have the fields `SessionManager.listAll` builds.
|
|
4
|
+
* listAll keeps no cache and reads every file again on each call; these are read through
|
|
5
|
+
* the index.
|
|
6
|
+
*/
|
|
7
|
+
export declare class PiSessions {
|
|
8
|
+
private readonly sessionDir;
|
|
9
|
+
constructor(sessionDir: string);
|
|
10
|
+
list(signal: AbortSignal): Promise<SessionFile[]>;
|
|
11
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createReadStream } from "node:fs";
|
|
2
|
+
import { readdir, stat } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
4
|
+
import { createInterface } from "node:readline";
|
|
5
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
6
|
+
/**
|
|
7
|
+
* Pi session files whose sessions have the fields `SessionManager.listAll` builds.
|
|
8
|
+
* listAll keeps no cache and reads every file again on each call; these are read through
|
|
9
|
+
* the index.
|
|
10
|
+
*/
|
|
11
|
+
export class PiSessions {
|
|
12
|
+
sessionDir;
|
|
13
|
+
constructor(sessionDir) {
|
|
14
|
+
this.sessionDir = sessionDir;
|
|
15
|
+
}
|
|
16
|
+
async list(signal) {
|
|
17
|
+
return (await sessionFiles(this.sessionDir, signal)).map(({ path, stats }) => ({
|
|
18
|
+
path,
|
|
19
|
+
stats,
|
|
20
|
+
label: "Pi",
|
|
21
|
+
read: (readSignal) => readSession(path, stats, readSignal),
|
|
22
|
+
}));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Matches the "all" scope of /resume: the default store keeps one folder per project under
|
|
27
|
+
* the agent's sessions root, and a custom session directory holds every session itself.
|
|
28
|
+
* The order is listAll's, so sessions with equal activity times keep its order.
|
|
29
|
+
*/
|
|
30
|
+
async function sessionFiles(sessionDir, signal) {
|
|
31
|
+
const root = join(getAgentDir(), "sessions");
|
|
32
|
+
if (sessionDir !== "" && resolve(dirname(sessionDir)) !== resolve(root)) {
|
|
33
|
+
const names = (await jsonlFiles(sessionDir)).sort((a, b) => b.localeCompare(a));
|
|
34
|
+
return withStats(names.map((name) => join(sessionDir, name)), signal);
|
|
35
|
+
}
|
|
36
|
+
let projects;
|
|
37
|
+
try {
|
|
38
|
+
projects = (await readdir(root, { withFileTypes: true }))
|
|
39
|
+
.filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
|
|
40
|
+
.map((entry) => join(root, entry.name));
|
|
41
|
+
}
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (error.code === "ENOENT")
|
|
44
|
+
return [];
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
const paths = await Promise.all(projects.map(async (project) => (await jsonlFiles(project)).map((name) => join(project, name))));
|
|
48
|
+
const files = await withStats(paths.flat(), signal);
|
|
49
|
+
return files.sort((a, b) => b.stats.mtimeMs - a.stats.mtimeMs || basename(b.path).localeCompare(basename(a.path)));
|
|
50
|
+
}
|
|
51
|
+
async function jsonlFiles(directory) {
|
|
52
|
+
try {
|
|
53
|
+
return (await readdir(directory)).filter((name) => name.endsWith(".jsonl"));
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
// A project entry may be a link to a file, and a custom store may not exist yet.
|
|
57
|
+
const code = error.code;
|
|
58
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
59
|
+
return [];
|
|
60
|
+
throw error;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async function withStats(paths, signal) {
|
|
64
|
+
const files = await Promise.all(paths.map(async (path) => {
|
|
65
|
+
try {
|
|
66
|
+
return { path, stats: await stat(path) };
|
|
67
|
+
}
|
|
68
|
+
catch (error) {
|
|
69
|
+
if (error.code === "ENOENT")
|
|
70
|
+
return undefined;
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}));
|
|
74
|
+
signal.throwIfAborted();
|
|
75
|
+
return files.filter((file) => file !== undefined);
|
|
76
|
+
}
|
|
77
|
+
/** Pi's buildSessionInfo, field for field; undefined where it returns null. */
|
|
78
|
+
async function readSession(path, stats, signal) {
|
|
79
|
+
let header;
|
|
80
|
+
let name;
|
|
81
|
+
let messageCount = 0;
|
|
82
|
+
let firstMessage = "";
|
|
83
|
+
let lastActivity;
|
|
84
|
+
const texts = [];
|
|
85
|
+
const lines = createInterface({
|
|
86
|
+
input: createReadStream(path, { encoding: "utf8", signal }),
|
|
87
|
+
crlfDelay: Infinity,
|
|
88
|
+
});
|
|
89
|
+
for await (const line of lines) {
|
|
90
|
+
const entry = parseLine(line);
|
|
91
|
+
if (!entry)
|
|
92
|
+
continue;
|
|
93
|
+
if (!header) {
|
|
94
|
+
if (entry["type"] !== "session" || typeof entry["id"] !== "string")
|
|
95
|
+
return undefined;
|
|
96
|
+
header = entry;
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (entry["type"] === "session_info") {
|
|
100
|
+
const value = entry["name"];
|
|
101
|
+
name = (typeof value === "string" ? value.trim() : "") || undefined;
|
|
102
|
+
}
|
|
103
|
+
if (entry["type"] !== "message")
|
|
104
|
+
continue;
|
|
105
|
+
messageCount++;
|
|
106
|
+
const message = entry["message"];
|
|
107
|
+
if (!isRecord(message) || !("content" in message))
|
|
108
|
+
continue;
|
|
109
|
+
if (message["role"] !== "user" && message["role"] !== "assistant")
|
|
110
|
+
continue;
|
|
111
|
+
const timestamp = message["timestamp"];
|
|
112
|
+
const activity = typeof timestamp === "number" ? timestamp : timeOf(entry["timestamp"]);
|
|
113
|
+
if (activity !== undefined)
|
|
114
|
+
lastActivity = Math.max(lastActivity ?? 0, activity);
|
|
115
|
+
const text = textOf(message["content"]);
|
|
116
|
+
if (!text)
|
|
117
|
+
continue;
|
|
118
|
+
texts.push(text);
|
|
119
|
+
if (!firstMessage && message["role"] === "user")
|
|
120
|
+
firstMessage = text;
|
|
121
|
+
}
|
|
122
|
+
if (!header)
|
|
123
|
+
return undefined;
|
|
124
|
+
const headerTime = typeof header["timestamp"] === "string" ? timeOf(header["timestamp"]) : undefined;
|
|
125
|
+
const parent = header["parentSession"];
|
|
126
|
+
return {
|
|
127
|
+
source: "pi",
|
|
128
|
+
path,
|
|
129
|
+
id: header["id"],
|
|
130
|
+
cwd: typeof header["cwd"] === "string" ? header["cwd"] : "",
|
|
131
|
+
name,
|
|
132
|
+
parentSessionPath: typeof parent === "string" ? parent : undefined,
|
|
133
|
+
created: new Date(header["timestamp"]),
|
|
134
|
+
modified: lastActivity !== undefined && lastActivity > 0
|
|
135
|
+
? new Date(lastActivity)
|
|
136
|
+
: headerTime !== undefined
|
|
137
|
+
? new Date(headerTime)
|
|
138
|
+
: stats.mtime,
|
|
139
|
+
messageCount,
|
|
140
|
+
firstMessage: firstMessage || "(no messages)",
|
|
141
|
+
allMessagesText: texts.join(" "),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
// Pi skips malformed lines too; the last line can be cut off while Pi appends to the file.
|
|
145
|
+
function parseLine(line) {
|
|
146
|
+
if (!line.trim())
|
|
147
|
+
return undefined;
|
|
148
|
+
try {
|
|
149
|
+
const entry = JSON.parse(line);
|
|
150
|
+
return isRecord(entry) ? entry : undefined;
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
return undefined;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function textOf(content) {
|
|
157
|
+
if (typeof content === "string")
|
|
158
|
+
return content;
|
|
159
|
+
if (!Array.isArray(content))
|
|
160
|
+
return "";
|
|
161
|
+
return content
|
|
162
|
+
.filter((block) => isRecord(block) && block["type"] === "text")
|
|
163
|
+
.map((block) => block["text"])
|
|
164
|
+
.join(" ");
|
|
165
|
+
}
|
|
166
|
+
function timeOf(value) {
|
|
167
|
+
const time = new Date(value).getTime();
|
|
168
|
+
return Number.isNaN(time) ? undefined : time;
|
|
169
|
+
}
|
|
170
|
+
function isRecord(value) {
|
|
171
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
172
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Stats } from "node:fs";
|
|
2
|
+
import { type LocalSession } from "./session.ts";
|
|
3
|
+
/**
|
|
4
|
+
* The default budget; Core settings let the user change it. The newest sessions whose entries
|
|
5
|
+
* fit are indexed and listed; older ones are neither read nor listed.
|
|
6
|
+
*/
|
|
7
|
+
export declare const INDEX_BUDGET_BYTES: number;
|
|
8
|
+
export declare function sessionIndexFile(agentDir?: string): string;
|
|
9
|
+
/** A file with the same inode, size and modification time reads the same. */
|
|
10
|
+
export declare function fileVersion(stats: Stats): string;
|
|
11
|
+
/** A session file a source found, read only when the index has no entry for its version. */
|
|
12
|
+
export interface SessionFile {
|
|
13
|
+
readonly path: string;
|
|
14
|
+
readonly stats: Stats;
|
|
15
|
+
/** Names the source in read errors. */
|
|
16
|
+
readonly label: string;
|
|
17
|
+
/** The session in the file; undefined when the file holds none to list. */
|
|
18
|
+
read(signal: AbortSignal): Promise<LocalSession | undefined>;
|
|
19
|
+
/** The session with state kept outside its file, such as a Codex title, applied. */
|
|
20
|
+
current?(session: LocalSession): LocalSession;
|
|
21
|
+
/** Invalidates an omitted entry's size when state outside its file changes. */
|
|
22
|
+
readonly currentVersion?: string;
|
|
23
|
+
}
|
|
24
|
+
export interface SessionScan {
|
|
25
|
+
/** The listed sessions, in the order of the files. */
|
|
26
|
+
sessions: LocalSession[];
|
|
27
|
+
errors: Error[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* What the catalog read from each session file, saved so that a new Pi session or process
|
|
31
|
+
* reads only the files that changed since. Listing reads every file in full, and the session
|
|
32
|
+
* stores reach gigabytes because of tool output the list never uses.
|
|
33
|
+
*
|
|
34
|
+
* Every load and every changed scan reads or writes the whole index, so it holds only the
|
|
35
|
+
* newest sessions that fit its budget, with their text clipped to the configured limit.
|
|
36
|
+
*
|
|
37
|
+
* Several Pi processes share the file. Each writes a complete index and renames it into
|
|
38
|
+
* place, so readers always see a whole index and the last writer wins.
|
|
39
|
+
*/
|
|
40
|
+
export declare class SessionIndex {
|
|
41
|
+
private readonly file;
|
|
42
|
+
/**
|
|
43
|
+
* Bytes the entries of a scan may take. A smaller budget drops the oldest entries at the
|
|
44
|
+
* next scan; a larger one reads the files the last scan left out.
|
|
45
|
+
*/
|
|
46
|
+
budget: number;
|
|
47
|
+
textLimit: number;
|
|
48
|
+
private entries;
|
|
49
|
+
private indexedTextLimit;
|
|
50
|
+
private loaded;
|
|
51
|
+
private changed;
|
|
52
|
+
constructor(file: string, budget?: number, textLimit?: number);
|
|
53
|
+
/**
|
|
54
|
+
* Reads the saved index once. A missing file or another format starts empty; an invalid
|
|
55
|
+
* one is reported and replaced by the next save.
|
|
56
|
+
*/
|
|
57
|
+
load(signal: AbortSignal): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Lists the sessions of the newest files, by modification time, until the next one does
|
|
60
|
+
* not fit the budget. Files the index lacks are read one at a time, which bounds memory
|
|
61
|
+
* for large rollouts and keeps the order. Entries for every other file are dropped.
|
|
62
|
+
*/
|
|
63
|
+
scan(files: readonly SessionFile[], signal: AbortSignal): Promise<SessionScan>;
|
|
64
|
+
/** Writes the index if the last scan changed it. */
|
|
65
|
+
save(): Promise<void>;
|
|
66
|
+
}
|