@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.
Files changed (62) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +100 -34
  3. package/dist/dock/registry.js +1 -0
  4. package/dist/extension.js +6 -2
  5. package/dist/mention/autocomplete.d.ts +23 -0
  6. package/dist/mention/autocomplete.js +135 -0
  7. package/dist/mention/catalog.d.ts +26 -0
  8. package/dist/mention/catalog.js +76 -0
  9. package/dist/mention/claude.d.ts +2 -0
  10. package/dist/mention/claude.js +118 -0
  11. package/dist/mention/codex.d.ts +3 -0
  12. package/dist/mention/codex.js +135 -0
  13. package/dist/mention/external.d.ts +15 -0
  14. package/dist/mention/external.js +151 -0
  15. package/dist/mention/index.d.ts +8 -0
  16. package/dist/mention/index.js +150 -0
  17. package/dist/mention/jsonl.d.ts +9 -0
  18. package/dist/mention/jsonl.js +54 -0
  19. package/dist/mention/mention.d.ts +19 -0
  20. package/dist/mention/mention.js +60 -0
  21. package/dist/mention/session.d.ts +18 -0
  22. package/dist/mention/session.js +8 -0
  23. package/dist/mention/text.d.ts +12 -0
  24. package/dist/mention/text.js +47 -0
  25. package/dist/mention/transcript.d.ts +10 -0
  26. package/dist/mention/transcript.js +129 -0
  27. package/dist/panel/defined-section.js +34 -8
  28. package/dist/panel/definition.d.ts +26 -1
  29. package/dist/panel/definition.js +32 -2
  30. package/dist/panel/index.d.ts +3 -2
  31. package/dist/panel/index.js +1 -0
  32. package/dist/panel/panel.js +100 -24
  33. package/dist/panel/section.d.ts +49 -3
  34. package/dist/panel/section.js +59 -12
  35. package/dist/resources/scoped-extension.js +1 -0
  36. package/dist/settings/file-store.js +1 -0
  37. package/docs/dock.md +9 -3
  38. package/docs/panel.md +69 -2
  39. package/docs/public-api-design.md +9 -9
  40. package/docs/recipes.md +3 -8
  41. package/docs/settings.md +1 -1
  42. package/package.json +4 -4
  43. package/src/dock/registry.ts +1 -0
  44. package/src/extension.ts +6 -2
  45. package/src/mention/autocomplete.ts +173 -0
  46. package/src/mention/catalog.ts +84 -0
  47. package/src/mention/claude.ts +127 -0
  48. package/src/mention/codex.ts +144 -0
  49. package/src/mention/external.ts +191 -0
  50. package/src/mention/index.ts +173 -0
  51. package/src/mention/jsonl.ts +56 -0
  52. package/src/mention/mention.ts +90 -0
  53. package/src/mention/session.ts +27 -0
  54. package/src/mention/text.ts +52 -0
  55. package/src/mention/transcript.ts +155 -0
  56. package/src/panel/defined-section.ts +40 -7
  57. package/src/panel/definition.ts +67 -2
  58. package/src/panel/index.ts +4 -0
  59. package/src/panel/panel.ts +105 -23
  60. package/src/panel/section.ts +111 -15
  61. package/src/resources/scoped-extension.ts +1 -0
  62. package/src/settings/file-store.ts +1 -0
@@ -0,0 +1,191 @@
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.ts";
5
+ import { parseCodexSession } from "./codex.ts";
6
+ import { jsonl, string } from "./jsonl.ts";
7
+ import {
8
+ SOURCE_NAMES,
9
+ type ExternalSession,
10
+ type LocalSession,
11
+ type SessionSource,
12
+ } from "./session.ts";
13
+
14
+ type ExternalSource = Exclude<SessionSource, "pi">;
15
+
16
+ interface CachedSession {
17
+ version: string;
18
+ session?: LocalSession;
19
+ }
20
+
21
+ /** File metadata caches belong to the running Pi session, just like the combined catalog. */
22
+ export class ExternalSessions {
23
+ private readonly codexHome = resolve(process.env["CODEX_HOME"] ?? join(homedir(), ".codex"));
24
+ private readonly claudeHome = resolve(
25
+ process.env["CLAUDE_CONFIG_DIR"] ?? join(homedir(), ".claude"),
26
+ );
27
+ private readonly cached = new Map<string, CachedSession>();
28
+ private titleIndex: { version: string; names: Map<string, string> } | undefined;
29
+
30
+ async list(signal: AbortSignal, report: (error: unknown) => void): Promise<LocalSession[]> {
31
+ const errors: Error[] = [];
32
+ const seen = new Set<string>();
33
+ const sources: ExternalSource[] = ["codex", "claude"];
34
+ const results = await Promise.all(
35
+ sources.map(async (source) => {
36
+ try {
37
+ const paths = await this.paths(source);
38
+ const names = source === "codex" ? await this.codexNames(signal) : new Map();
39
+ const sessions: LocalSession[] = [];
40
+ // One file per source at a time bounds memory when rollouts contain large tool results.
41
+ for (const path of paths) {
42
+ signal.throwIfAborted();
43
+ seen.add(path);
44
+ try {
45
+ const stats = await stat(path);
46
+ const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
47
+ let cached = this.cached.get(path);
48
+ if (cached?.version !== version) {
49
+ cached = { version };
50
+ const content = await readFile(path, { encoding: "utf8", signal });
51
+ cached.session = parseExternalSession(
52
+ source,
53
+ content,
54
+ path,
55
+ )?.session;
56
+ if (!signal.aborted) this.cached.set(path, cached);
57
+ }
58
+ if (cached.session) {
59
+ const name =
60
+ source === "codex"
61
+ ? names.get(cached.session.id)
62
+ : cached.session.name;
63
+ if (name !== cached.session.name) {
64
+ cached.session = { ...cached.session, name };
65
+ }
66
+ // Stable objects preserve autocomplete's existing WeakMap search cache.
67
+ sessions.push(cached.session);
68
+ }
69
+ } catch (error) {
70
+ signal.throwIfAborted();
71
+ errors.push(fileError(source, path, error));
72
+ }
73
+ }
74
+ return sessions;
75
+ } catch (error) {
76
+ signal.throwIfAborted();
77
+ errors.push(
78
+ fileError(
79
+ source,
80
+ source === "codex" ? this.codexHome : this.claudeHome,
81
+ error,
82
+ ),
83
+ );
84
+ return [];
85
+ }
86
+ }),
87
+ );
88
+ signal.throwIfAborted();
89
+ for (const path of this.cached.keys()) {
90
+ if (!seen.has(path)) this.cached.delete(path);
91
+ }
92
+ if (errors.length > 0) {
93
+ report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
94
+ }
95
+ return results.flat();
96
+ }
97
+
98
+ clear(): void {
99
+ this.cached.clear();
100
+ this.titleIndex = undefined;
101
+ }
102
+
103
+ private async paths(source: ExternalSource): Promise<string[]> {
104
+ const root = join(
105
+ source === "codex" ? this.codexHome : this.claudeHome,
106
+ source === "codex" ? "sessions" : "projects",
107
+ );
108
+ let projects: string[];
109
+ try {
110
+ if (source === "codex") {
111
+ return (await readdir(root, { recursive: true }))
112
+ .filter((file) => /^rollout-.+\.jsonl$/.test(basename(file)))
113
+ .map((file) => join(root, file));
114
+ }
115
+ projects = (await readdir(root, { withFileTypes: true }))
116
+ .filter((entry) => entry.isDirectory())
117
+ .map((entry) => join(root, entry.name));
118
+ } catch (error) {
119
+ // Neither external tool is required to be installed; only an absent store is empty.
120
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
121
+ throw error;
122
+ }
123
+ // Subagents and tool-result stores are nested below the main files; never traverse them.
124
+ const files = await Promise.all(
125
+ projects.map(async (project) =>
126
+ (await readdir(project, { withFileTypes: true }))
127
+ .filter(
128
+ (entry) =>
129
+ entry.isFile() &&
130
+ entry.name.endsWith(".jsonl") &&
131
+ !entry.name.startsWith("agent-"),
132
+ )
133
+ .map((entry) => join(project, entry.name)),
134
+ ),
135
+ );
136
+ return files.flat();
137
+ }
138
+
139
+ private async codexNames(signal: AbortSignal): Promise<Map<string, string>> {
140
+ const path = join(this.codexHome, "session_index.jsonl");
141
+ let content: string;
142
+ let version: string;
143
+ try {
144
+ const stats = await stat(path);
145
+ version = `${stats.ino}:${stats.size}:${stats.mtimeMs}`;
146
+ if (this.titleIndex?.version === version) return this.titleIndex.names;
147
+ content = await readFile(path, { encoding: "utf8", signal });
148
+ } catch (error) {
149
+ // The title index is optional; the rollout itself owns the session and its messages.
150
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
151
+ this.titleIndex = undefined;
152
+ return new Map();
153
+ }
154
+ throw error;
155
+ }
156
+ const names = new Map<string, string>();
157
+ try {
158
+ for (const record of jsonl(content, path)) {
159
+ names.set(
160
+ string(record.id, "session_index.id"),
161
+ string(record.thread_name, "thread_name"),
162
+ );
163
+ }
164
+ } catch {
165
+ // TODO: Record Codex title parser errors in Core Log when it is available.
166
+ names.clear();
167
+ }
168
+ if (!signal.aborted) this.titleIndex = { version, names };
169
+ return names;
170
+ }
171
+ }
172
+
173
+ export function parseExternalSession(
174
+ source: ExternalSource,
175
+ content: string,
176
+ path: string,
177
+ ): ExternalSession | undefined {
178
+ try {
179
+ return source === "codex"
180
+ ? parseCodexSession(content, path)
181
+ : parseClaudeSession(content, path);
182
+ } catch {
183
+ // TODO: Record Codex and Claude Code parser errors in Core Log when it is available.
184
+ return undefined;
185
+ }
186
+ }
187
+
188
+ function fileError(source: ExternalSource, path: string, error: unknown): Error {
189
+ const message = error instanceof Error ? error.message : String(error);
190
+ return new Error(`${SOURCE_NAMES[source]}: ${path}: ${message}`, { cause: error });
191
+ }
@@ -0,0 +1,173 @@
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
+ /**
20
+ * `@` lists local sessions with pi's file matches, and `@@` lists sessions only. A picked
21
+ * session becomes a source-specific token. On submit, each such token becomes an `@` reference to
22
+ * a filtered copy of that session, which the model reads when it needs the background.
23
+ */
24
+ export function installMentions(pi: ExtensionAPI, resources: ResourceScope): void {
25
+ let catalog: SessionCatalog | undefined;
26
+ const transcripts = new TranscriptCache();
27
+ const retire = () => {
28
+ catalog?.dispose();
29
+ catalog = undefined;
30
+ };
31
+ resources.defer(retire);
32
+
33
+ resources.defer(
34
+ pi.on("session_start", (_event, ctx) => {
35
+ retire();
36
+ const report = (error: unknown) => {
37
+ // A retired scan can settle after Pi invalidates its session context.
38
+ if (catalog !== sessions) return;
39
+ ctx.ui.notify(`Session list failed: ${errorMessage(error)}`, "error");
40
+ };
41
+ const sessions = new SessionCatalog(ctx.sessionManager.getSessionDir(), report);
42
+ catalog = sessions;
43
+ if (ctx.mode !== "tui") return;
44
+ // Pi drops autocomplete wrappers when it replaces the session, so add one per start.
45
+ ctx.ui.addAutocompleteProvider((current) =>
46
+ createMentionAutocomplete(current, {
47
+ catalog: sessions,
48
+ currentSessionFile: ctx.sessionManager.getSessionFile(),
49
+ }),
50
+ );
51
+ // Read the sessions now, so the first `@` already lists them.
52
+ sessions.reload().catch(report);
53
+ }),
54
+ );
55
+
56
+ resources.defer(
57
+ pi.on("input", async (event, ctx) => {
58
+ const mentions = findMentions(event.text);
59
+ if (mentions.length === 0) return { action: "continue" };
60
+ try {
61
+ if (!catalog) throw new Error("Session mentions have no active session");
62
+ const files = new Map<string, string | undefined>();
63
+ for (const mention of mentions) {
64
+ if (files.has(mention.token)) continue;
65
+ const session = await findSession(catalog, mention);
66
+ files.set(mention.token, await transcripts.file(session));
67
+ }
68
+ return {
69
+ action: "transform",
70
+ text: replaceMentions(event.text, mentions, (mention) => {
71
+ const file = files.get(mention.token);
72
+ return file === undefined ? mention.token : fileReference(file);
73
+ }),
74
+ images: event.images,
75
+ };
76
+ } catch (error) {
77
+ return refuseInput(ctx, event.text, error);
78
+ }
79
+ }),
80
+ );
81
+ }
82
+
83
+ async function findSession(catalog: SessionCatalog, mention: Mention): Promise<LocalSession> {
84
+ const cached = await catalog.list();
85
+ if (
86
+ cached.some(
87
+ (session) =>
88
+ session.source === mention.source && session.id.startsWith(mention.idPrefix),
89
+ )
90
+ ) {
91
+ return resolveMention(mention, cached);
92
+ }
93
+ // A typed id can name a session that is newer than the cached list.
94
+ return resolveMention(mention, await catalog.reload());
95
+ }
96
+
97
+ interface TranscriptFiles {
98
+ file: string;
99
+ rawFile: string;
100
+ }
101
+
102
+ /**
103
+ * Building a copy parses the whole session file, so a session that has not changed since its
104
+ * last mention reuses the copy written then.
105
+ */
106
+ class TranscriptCache {
107
+ private readonly written = new Map<string, { version: string; files?: TranscriptFiles }>();
108
+
109
+ async file(session: LocalSession): Promise<string | undefined> {
110
+ const stats = await stat(session.path);
111
+ const version = `${stats.ino}:${stats.size}:${stats.mtimeMs}:${session.name ?? ""}`;
112
+ const cached = this.written.get(session.path);
113
+ if (cached?.version === version) {
114
+ if (!cached.files) return undefined;
115
+ if ((await exists(cached.files.file)) && (await exists(cached.files.rawFile))) {
116
+ return cached.files.file;
117
+ }
118
+ }
119
+ try {
120
+ const files = await writeTranscript(session);
121
+ this.written.set(session.path, { version, files });
122
+ return files.file;
123
+ } catch (error) {
124
+ if (!(error instanceof ExternalSessionParseError)) throw error;
125
+ // TODO: Record invalid external reference snapshots in Core Log when it is available.
126
+ this.written.set(session.path, { version });
127
+ return undefined;
128
+ }
129
+ }
130
+ }
131
+
132
+ async function writeTranscript(session: LocalSession): Promise<TranscriptFiles> {
133
+ const content = await readFile(session.path);
134
+ const directory = join(tmpdir(), "pi-lune-session-refs");
135
+ await mkdir(directory, { recursive: true });
136
+ // Hash the full snapshot: metadata can change without moving the active branch's leaf.
137
+ const hash = createHash("sha256")
138
+ .update(content)
139
+ .update("\0")
140
+ .update(session.name ?? "")
141
+ .digest("hex");
142
+ const name = `${session.source}.${session.id}.${hash}`;
143
+ const rawFile = join(directory, `${name}.jsonl`);
144
+ await writeFile(rawFile, content, { mode: 0o600 });
145
+ const transcript = buildTranscript({ ...session, path: rawFile });
146
+ const file = join(directory, `${name}.md`);
147
+ await writeFile(file, transcript.markdown, { encoding: "utf8", mode: 0o600 });
148
+ return { file, rawFile };
149
+ }
150
+
151
+ async function exists(path: string): Promise<boolean> {
152
+ try {
153
+ await access(path);
154
+ return true;
155
+ } catch {
156
+ return false;
157
+ }
158
+ }
159
+
160
+ /**
161
+ * With a UI, a prompt whose session reference fails is not sent, and the text goes back to the
162
+ * editor to correct. Without one the error is raised; pi reports it and sends the original text.
163
+ */
164
+ function refuseInput(ctx: ExtensionContext, text: string, error: unknown): { action: "handled" } {
165
+ if (!ctx.hasUI) throw error;
166
+ ctx.ui.notify(`Prompt not sent. ${errorMessage(error)}`, "error");
167
+ ctx.ui.setEditorText(text);
168
+ return { action: "handled" };
169
+ }
170
+
171
+ function errorMessage(error: unknown): string {
172
+ return error instanceof Error ? error.message : String(error);
173
+ }
@@ -0,0 +1,56 @@
1
+ export type JsonObject = Record<string, unknown>;
2
+
3
+ export function object(value: unknown): JsonObject {
4
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
5
+ throw new Error("Expected a JSON object");
6
+ }
7
+ return value as JsonObject;
8
+ }
9
+
10
+ /** Parse one record at a time so large tool payloads are not all retained with the messages. */
11
+ export function* jsonl(content: string, path: string): Generator<JsonObject> {
12
+ let start = 0;
13
+ let line = 0;
14
+ while (start < content.length) {
15
+ const end = content.indexOf("\n", start);
16
+ const text = content.slice(start, end === -1 ? content.length : end);
17
+ start = end === -1 ? content.length : end + 1;
18
+ line++;
19
+ if (!text.trim()) continue;
20
+ try {
21
+ yield object(JSON.parse(text));
22
+ } catch (error) {
23
+ throw new Error(`Invalid JSONL at ${path}:${line}`, { cause: error });
24
+ }
25
+ }
26
+ }
27
+
28
+ export function string(value: unknown, field: string): string {
29
+ if (typeof value !== "string") throw new Error(`Expected a string for ${field}`);
30
+ return value;
31
+ }
32
+
33
+ export function sessionId(value: unknown, field: string): string {
34
+ const id = string(value, field);
35
+ // Ids become mention tokens and temporary filenames, so path separators are never valid.
36
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/.test(id)) {
37
+ throw new Error(`Invalid session id for ${field}`);
38
+ }
39
+ return id;
40
+ }
41
+
42
+ export function date(value: unknown, field: string): Date {
43
+ const parsed = new Date(string(value, field));
44
+ if (!Number.isFinite(parsed.getTime())) throw new Error(`Invalid date for ${field}`);
45
+ return parsed;
46
+ }
47
+
48
+ /** Only text blocks belong in the reference; images, thinking and tool payloads stay in JSONL. */
49
+ export function textContent(value: unknown, types: readonly string[]): string {
50
+ if (!Array.isArray(value)) throw new Error("Expected an array of content blocks");
51
+ return value
52
+ .map((part: unknown) => object(part))
53
+ .filter((part) => types.includes(string(part.type, "content.type")))
54
+ .map((part) => string(part.text, "content.text"))
55
+ .join("\n");
56
+ }
@@ -0,0 +1,90 @@
1
+ import type { LocalSession, SessionSource } from "./session.ts";
2
+ import { TOKEN_BOUNDARY } from "./text.ts";
3
+
4
+ export const TOKEN_PREFIX = "@session:";
5
+ const TOKEN_PREFIXES: Record<SessionSource, string> = {
6
+ pi: TOKEN_PREFIX,
7
+ codex: "@codex:",
8
+ claude: "@claude:",
9
+ };
10
+
11
+ /** UUIDv7 ids carry the creation time in their first 12 hex digits (`01a14931-31bb`). */
12
+ const MIN_ID_LENGTH = 13;
13
+
14
+ // Session ids follow pi's assertValidSessionId(): alphanumeric at both ends, `._-` inside.
15
+ const mentionPattern = new RegExp(
16
+ `(?<=${TOKEN_BOUNDARY})@(session|codex|claude):([A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?)`,
17
+ "gu",
18
+ );
19
+
20
+ export interface Mention {
21
+ /** Offset of the source-specific token in the text. */
22
+ index: number;
23
+ token: string;
24
+ source: SessionSource;
25
+ idPrefix: string;
26
+ }
27
+
28
+ /** The shortest id prefix, from MIN_ID_LENGTH up, that names only this session. */
29
+ export function shortSessionId(id: string, sessions: readonly LocalSession[]): string {
30
+ for (let length = Math.min(MIN_ID_LENGTH, id.length); length < id.length; length++) {
31
+ const prefix = id.slice(0, length);
32
+ if (!/[A-Za-z0-9]$/.test(prefix)) continue;
33
+ if (sessions.every((other) => other.id === id || !other.id.startsWith(prefix))) {
34
+ return prefix;
35
+ }
36
+ }
37
+ return id;
38
+ }
39
+
40
+ export function mentionToken(session: LocalSession, sessions: readonly LocalSession[]): string {
41
+ const sameSource = sessions.filter((other) => other.source === session.source);
42
+ return `${TOKEN_PREFIXES[session.source]}${shortSessionId(session.id, sameSource)}`;
43
+ }
44
+
45
+ export function findMentions(text: string): Mention[] {
46
+ return [...text.matchAll(mentionPattern)].map((match) => ({
47
+ index: match.index,
48
+ token: match[0],
49
+ source: match[1] === "session" ? "pi" : (match[1] as SessionSource),
50
+ idPrefix: match[2]!,
51
+ }));
52
+ }
53
+
54
+ /** Throws when the prefix names no session or more than one. */
55
+ export function resolveMention(
56
+ mention: Pick<Mention, "source" | "idPrefix">,
57
+ sessions: readonly LocalSession[],
58
+ ): LocalSession {
59
+ const { source, idPrefix } = mention;
60
+ const token = `${TOKEN_PREFIXES[source]}${idPrefix}`;
61
+ const matches = sessions.filter(
62
+ (session) => session.source === source && session.id.startsWith(idPrefix),
63
+ );
64
+ if (matches.length === 1) return matches[0]!;
65
+ throw new Error(
66
+ matches.length === 0
67
+ ? `No local session matches ${token}`
68
+ : `${token} matches ${matches.length} sessions; type more of the id`,
69
+ );
70
+ }
71
+
72
+ /** Replace each mention with the editor text for its file, keeping all other text. */
73
+ export function replaceMentions(
74
+ text: string,
75
+ mentions: readonly Mention[],
76
+ replacement: (mention: Mention) => string,
77
+ ): string {
78
+ let result = "";
79
+ let offset = 0;
80
+ for (const mention of mentions) {
81
+ result += text.slice(offset, mention.index) + replacement(mention);
82
+ offset = mention.index + mention.token.length;
83
+ }
84
+ return result + text.slice(offset);
85
+ }
86
+
87
+ /** Pi's `@` file reference, quoted like its own completion when the path has whitespace. */
88
+ export function fileReference(path: string): string {
89
+ return /\s/u.test(path) ? `@"${path}"` : `@${path}`;
90
+ }
@@ -0,0 +1,27 @@
1
+ import type { SessionInfo } from "@earendil-works/pi-coding-agent";
2
+
3
+ export type SessionSource = "pi" | "codex" | "claude";
4
+
5
+ export interface LocalSession extends SessionInfo {
6
+ source: SessionSource;
7
+ }
8
+
9
+ export const SOURCE_NAMES: Record<SessionSource, string> = {
10
+ pi: "pi",
11
+ codex: "Codex",
12
+ claude: "Claude Code",
13
+ };
14
+
15
+ export interface ConversationMessage {
16
+ role: "user" | "assistant" | "summary";
17
+ text: string;
18
+ }
19
+
20
+ export interface ExternalSession {
21
+ session: LocalSession;
22
+ messages: ConversationMessage[];
23
+ leafId: string | null;
24
+ }
25
+
26
+ /** Marks an external reference that must be skipped without interrupting prompt submission. */
27
+ export class ExternalSessionParseError extends Error {}
@@ -0,0 +1,52 @@
1
+ import { basename } from "node:path";
2
+ import type { SessionInfo } from "@earendil-works/pi-coding-agent";
3
+ import { stripTerminalSequences } from "@earendil-works/pi-tui";
4
+
5
+ // pi-tui's completion separators (whitespace or CJK punctuation) and token boundary; neither is
6
+ // exported.
7
+ const CJK_PUNCTUATION =
8
+ "(?:(?=\\p{Punctuation})[\\p{Script_Extensions=Han}\\p{Script_Extensions=Hiragana}\\p{Script_Extensions=Katakana}\\p{Script_Extensions=Hangul}\\p{Script_Extensions=Bopomofo}]|[,.:;!?()[]{}“”‘’…—])";
9
+ export const SEPARATOR = `(?:\\s|${CJK_PUNCTUATION})`;
10
+ export const TOKEN_BOUNDARY = `(?:^|${SEPARATOR})[([{<\`"']*`;
11
+
12
+ /** Session text is untrusted: drop terminal sequences and control characters. */
13
+ export function cleanBody(text: string): string {
14
+ return stripTerminalSequences(text)
15
+ .replace(/[\p{Cc}\p{Cf}]/gu, (character) =>
16
+ character === "\n" || character === "\t" ? character : " ",
17
+ )
18
+ .replace(/\n{3,}/g, "\n\n")
19
+ .trim();
20
+ }
21
+
22
+ export function cleanLine(text: string): string {
23
+ return cleanBody(text).replace(/\s+/gu, " ");
24
+ }
25
+
26
+ /** Truncate by code point so CJK text and emoji are never split. */
27
+ export function clip(text: string, limit: number): string {
28
+ const characters = Array.from(text);
29
+ if (characters.length <= limit) return text;
30
+ return `${characters.slice(0, limit).join("")} … [${characters.length - limit} more characters]`;
31
+ }
32
+
33
+ export function sessionTitle(session: SessionInfo): string {
34
+ return cleanLine(session.name || session.firstMessage) || session.id;
35
+ }
36
+
37
+ export function projectName(session: SessionInfo): string {
38
+ return basename(session.cwd) || session.cwd || "unknown project";
39
+ }
40
+
41
+ /** Compact age for a fixed-width column: `now`, `12m`, `5h`, `3d`, `6w`, `2y`. */
42
+ export function formatAge(milliseconds: number): string {
43
+ const minutes = Math.floor(milliseconds / 60_000);
44
+ if (minutes < 1) return "now";
45
+ if (minutes < 60) return `${minutes}m`;
46
+ const hours = Math.floor(minutes / 60);
47
+ if (hours < 24) return `${hours}h`;
48
+ const days = Math.floor(hours / 24);
49
+ if (days < 14) return `${days}d`;
50
+ if (days < 365) return `${Math.floor(days / 7)}w`;
51
+ return `${Math.floor(days / 365)}y`;
52
+ }