@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
package/docs/settings.md CHANGED
@@ -59,7 +59,7 @@ keys.
59
59
 
60
60
  ### Schema evolution
61
61
 
62
- The current version is `migrations.length + 1`. Stored data at version *n* is passed through
62
+ The current version is `migrations.length + 1`. Stored data at version _n_ is passed through
63
63
  `migrations[n - 1]`, then onward, when the file is loaded; the upgraded file is written back
64
64
  with its new `$version`. A migration receives an isolated copy of one scope's overrides
65
65
  (no defaults, no `$` metadata) and returns the next version's overrides; keep it
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lune_99/pi-lune-extensions-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Shared infrastructure for the Lune series of Pi extensions",
5
5
  "type": "module",
6
6
  "exports": {
@@ -102,9 +102,9 @@
102
102
  },
103
103
  "dependencies": {},
104
104
  "devDependencies": {
105
- "@earendil-works/pi-ai": "^1.0.4",
106
- "@earendil-works/pi-coding-agent": "^1.0.4",
107
- "@earendil-works/pi-tui": "^1.0.0",
105
+ "@earendil-works/pi-ai": "1.3.0",
106
+ "@earendil-works/pi-coding-agent": "1.3.0",
107
+ "@earendil-works/pi-tui": "1.3.0",
108
108
  "@types/node": "^22.20.2",
109
109
  "typescript": "5.9.3"
110
110
  },
@@ -140,6 +140,7 @@ export function createDockRegistry(): DockRegistry {
140
140
  try {
141
141
  notifyPresence(state.contributions.values(), false);
142
142
  } catch (cleanupError) {
143
+ // eslint-disable-next-line preserve-caught-error -- AggregateError.errors retains both failures.
143
144
  throw new AggregateError(
144
145
  [error, cleanupError],
145
146
  "Lune dock host attachment and cleanup failed",
package/src/extension.ts CHANGED
@@ -1,15 +1,18 @@
1
1
  /**
2
- * Optional Pi package entry for the shared command and Core's own settings section.
2
+ * Optional Pi package entry for the shared command, Core's own settings section and `@`
3
+ * session mentions.
3
4
  *
4
5
  * SDK consumers do not need this extension for Host discovery or settings storage.
5
6
  * Consumer plugins register their own sections; this entry owns only Core's Settings
6
- * binding and Panel registration. It opts into /panel/tui and terminal peers.
7
+ * binding and Panel registration. It opts into /panel/tui and terminal peers. Session
8
+ * mentions live only behind this entry, so importing the SDK never activates them.
7
9
  */
8
10
  import { corePanel } from "./core/panel.ts";
9
11
  import { coreSettings } from "./core/settings.ts";
10
12
  import { registerSettingsPanel } from "./panel/registration.ts";
11
13
  import { openSettingsPanel } from "./panel/tui.ts";
12
14
  import { scopedExtension } from "./resources/scoped-extension.ts";
15
+ import { installMentions } from "./mention/index.ts";
13
16
  import { bindSettings } from "./settings/binding.ts";
14
17
 
15
18
  /**
@@ -32,4 +35,5 @@ export default scopedExtension((pi, resources) => {
32
35
  await openSettingsPanel(ctx, { section: args.trim() || undefined });
33
36
  },
34
37
  });
38
+ installMentions(pi, resources);
35
39
  });
@@ -0,0 +1,173 @@
1
+ import type { AutocompleteItem, AutocompleteProvider } from "@earendil-works/pi-tui";
2
+ import type { SessionCatalog } from "./catalog.ts";
3
+ import { mentionToken } from "./mention.ts";
4
+ import { SOURCE_NAMES, type LocalSession } from "./session.ts";
5
+ import { formatAge, projectName, SEPARATOR, sessionTitle, TOKEN_BOUNDARY } from "./text.ts";
6
+
7
+ /** `@@query` lists sessions only and searches their messages too. */
8
+ export const SESSION_TRIGGER = "@@";
9
+ /** Source tags are padded to the widest one so the age and project columns line up. */
10
+ const SOURCE_TAG_WIDTH = Math.max(...Object.keys(SOURCE_NAMES).map((source) => source.length + 2));
11
+ /** Session rows in the list for a plain `@query`. */
12
+ const SESSION_ROWS = 3;
13
+ /** Rows for `@@query`; the search itself covers every local session. */
14
+ const SESSION_LIST_ROWS = 50;
15
+ /** An `@` at a word start, up to the cursor. A quote after it is pi's quoted path syntax. */
16
+ const AT_WORD = new RegExp(`${TOKEN_BOUNDARY}(@(?:(?!${SEPARATOR})[^"])*)$`, "u");
17
+
18
+ export interface MentionAutocompleteOptions {
19
+ catalog: SessionCatalog;
20
+ /** The running session's file, left out of the list. */
21
+ currentSessionFile: string | undefined;
22
+ }
23
+
24
+ /**
25
+ * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
26
+ * Everything that is not an `@` token goes to the provider underneath.
27
+ *
28
+ * Nothing here waits for the session list: the rows come from what the catalog has read. The
29
+ * editor runs one request at a time, so a slow request would delay every later keystroke.
30
+ */
31
+ export function createMentionAutocomplete(
32
+ current: AutocompleteProvider,
33
+ options: MentionAutocompleteOptions,
34
+ ): AutocompleteProvider {
35
+ // The editor passes back the item objects it received, so membership marks session rows.
36
+ const sessionRows = new WeakSet<AutocompleteItem>();
37
+ const sessionItems = (query: string, limit: number, searchText: boolean) => {
38
+ const sessions = options.catalog.snapshot();
39
+ const now = Date.now();
40
+ return matchSessions(sessions, query, options.currentSessionFile, searchText)
41
+ .slice(0, limit)
42
+ .map((session) => {
43
+ const item = sessionItem(session, sessions, now);
44
+ sessionRows.add(item);
45
+ return item;
46
+ });
47
+ };
48
+
49
+ return {
50
+ triggerCharacters: current.triggerCharacters,
51
+ shouldTriggerFileCompletion: current.shouldTriggerFileCompletion
52
+ ? (lines, cursorLine, cursorCol) =>
53
+ current.shouldTriggerFileCompletion!(lines, cursorLine, cursorCol)
54
+ : undefined,
55
+
56
+ async getSuggestions(lines, cursorLine, cursorCol, request) {
57
+ const prefix = AT_WORD.exec((lines[cursorLine] ?? "").slice(0, cursorCol))?.[1];
58
+ if (!prefix) return current.getSuggestions(lines, cursorLine, cursorCol, request);
59
+ if (prefix.startsWith(SESSION_TRIGGER)) {
60
+ const query = prefix.slice(SESSION_TRIGGER.length);
61
+ const items = sessionItems(query, SESSION_LIST_ROWS, true);
62
+ return items.length > 0 ? { items, prefix } : null;
63
+ }
64
+ const query = prefix.slice(1);
65
+ // A folder in the query names a path.
66
+ const sessions = query.includes("/") ? [] : sessionItems(query, SESSION_ROWS, false);
67
+ const files = await current.getSuggestions(lines, cursorLine, cursorCol, request);
68
+ if (request.signal.aborted) return null;
69
+ // No rows to add, or the provider underneath read a different token.
70
+ if (sessions.length === 0 || (files && files.prefix !== prefix)) return files;
71
+ const items = withSessions(files?.items ?? [], sessions, query);
72
+ return items.length > 0 ? { items, prefix } : null;
73
+ },
74
+
75
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
76
+ if (!sessionRows.has(item)) {
77
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
78
+ }
79
+ const line = lines[cursorLine] ?? "";
80
+ const start = cursorCol - prefix.length;
81
+ const inserted = `${item.value} `;
82
+ const next = [...lines];
83
+ next[cursorLine] = line.slice(0, start) + inserted + line.slice(cursorCol);
84
+ return { lines: next, cursorLine, cursorCol: start + inserted.length };
85
+ },
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Sessions come first, except after files whose name contains the query. The editor selects the
91
+ * first row, so Tab after a typed file name still picks that file and not a session.
92
+ */
93
+ function withSessions(
94
+ files: readonly AutocompleteItem[],
95
+ sessions: readonly AutocompleteItem[],
96
+ query: string,
97
+ ): AutocompleteItem[] {
98
+ const needle = query.toLowerCase();
99
+ const named = needle
100
+ ? files.filter((item) => item.label.replace(/\/$/, "").toLowerCase().includes(needle))
101
+ : [];
102
+ const others = files.filter((item) => !named.includes(item));
103
+ return [...named, ...sessions, ...others];
104
+ }
105
+
106
+ interface SessionSearch {
107
+ id: string;
108
+ title: string;
109
+ project: string;
110
+ source: string;
111
+ text?: string;
112
+ }
113
+
114
+ // The catalog keeps one list until its next reload, so the lower-case copies are made once per
115
+ // session and list, not once per keystroke.
116
+ const searches = new WeakMap<LocalSession, SessionSearch>();
117
+
118
+ function searchOf(session: LocalSession): SessionSearch {
119
+ let search = searches.get(session);
120
+ if (!search) {
121
+ search = {
122
+ id: session.id.toLowerCase(),
123
+ title: sessionTitle(session).toLowerCase(),
124
+ project: projectName(session).toLowerCase(),
125
+ source: SOURCE_NAMES[session.source].toLowerCase(),
126
+ };
127
+ searches.set(session, search);
128
+ }
129
+ return search;
130
+ }
131
+
132
+ /**
133
+ * Id and title matches rank above project matches, which rank above matches in the session's
134
+ * messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
135
+ */
136
+ export function matchSessions(
137
+ sessions: readonly LocalSession[],
138
+ query: string,
139
+ excludePath: string | undefined,
140
+ searchText: boolean,
141
+ ): LocalSession[] {
142
+ const needle = query.toLowerCase();
143
+ return sessions
144
+ .filter((session) => session.path !== excludePath && session.messageCount > 0)
145
+ .map((session) => ({ session, rank: needle ? matchRank(session, needle, searchText) : 1 }))
146
+ .filter(({ rank }) => rank > 0)
147
+ .sort((a, b) => b.rank - a.rank)
148
+ .map(({ session }) => session);
149
+ }
150
+
151
+ function matchRank(session: LocalSession, needle: string, searchText: boolean): number {
152
+ const search = searchOf(session);
153
+ if (search.id.startsWith(needle) || search.title.includes(needle)) return 3;
154
+ if (search.project.includes(needle) || search.source.includes(needle)) return 2;
155
+ if (!searchText) return 0;
156
+ search.text ??= session.allMessagesText.toLowerCase();
157
+ return search.text.includes(needle) ? 1 : 0;
158
+ }
159
+
160
+ /** Source, age and project fill pi's label column, which leaves the wide one for the title. */
161
+ function sessionItem(
162
+ session: LocalSession,
163
+ sessions: readonly LocalSession[],
164
+ now: number,
165
+ ): AutocompleteItem {
166
+ const source = `[${session.source}]`.padEnd(SOURCE_TAG_WIDTH);
167
+ const age = formatAge(now - session.modified.getTime()).padStart(3);
168
+ return {
169
+ value: mentionToken(session, sessions),
170
+ label: `${source} ${age} ${projectName(session)}`,
171
+ description: sessionTitle(session),
172
+ };
173
+ }
@@ -0,0 +1,84 @@
1
+ import { dirname, join, resolve } from "node:path";
2
+ import { getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
3
+ import { ExternalSessions } from "./external.ts";
4
+ import type { LocalSession } from "./session.ts";
5
+
6
+ /** A list older than this is reloaded in the background on the next lookup. */
7
+ const REFRESH_AFTER_MS = 60_000;
8
+
9
+ /**
10
+ * Local Pi, Codex and Claude Code main sessions, newest activity first.
11
+ *
12
+ * Listing reads every session file (about a second for a few hundred sessions), so lookups
13
+ * serve the cached list and reload it in the background. The owner disposes the catalog on
14
+ * session shutdown; a load that finishes later is discarded.
15
+ */
16
+ export class SessionCatalog {
17
+ private readonly sessionDir: string;
18
+ private readonly onBackgroundError: (error: unknown) => void;
19
+ private readonly abort = new AbortController();
20
+ private readonly external = new ExternalSessions();
21
+ private sessions: readonly LocalSession[] = [];
22
+ private loaded = false;
23
+ private loadedAt = 0;
24
+ private loading: Promise<readonly LocalSession[]> | undefined;
25
+
26
+ constructor(sessionDir: string, onBackgroundError: (error: unknown) => void) {
27
+ this.sessionDir = sessionDir;
28
+ this.onBackgroundError = onBackgroundError;
29
+ }
30
+
31
+ /** The cached list, empty before the first load. A stale list starts a background reload. */
32
+ snapshot(): readonly LocalSession[] {
33
+ const stale = Date.now() - this.loadedAt > REFRESH_AFTER_MS;
34
+ if (stale && !this.loading && !this.abort.signal.aborted) {
35
+ this.reload().catch((error: unknown) => {
36
+ if (!this.abort.signal.aborted) this.onBackgroundError(error);
37
+ });
38
+ }
39
+ return this.sessions;
40
+ }
41
+
42
+ /** Waits only for the first load; later lookups return the cached list at once. */
43
+ async list(): Promise<readonly LocalSession[]> {
44
+ return this.loaded ? this.snapshot() : this.reload();
45
+ }
46
+
47
+ /** Concurrent callers share one load. */
48
+ reload(): Promise<readonly LocalSession[]> {
49
+ this.loadedAt = Date.now();
50
+ this.loading ??= Promise.all([
51
+ listSessions(this.sessionDir, this.abort.signal),
52
+ this.external.list(this.abort.signal, this.onBackgroundError),
53
+ ])
54
+ .then(([pi, external]) => {
55
+ this.abort.signal.throwIfAborted();
56
+ const sessions = [
57
+ ...pi.map((session): LocalSession => ({ ...session, source: "pi" })),
58
+ ...external,
59
+ ].sort((left, right) => right.modified.getTime() - left.modified.getTime());
60
+ this.sessions = sessions;
61
+ this.loaded = true;
62
+ return sessions;
63
+ })
64
+ .finally(() => {
65
+ this.loading = undefined;
66
+ });
67
+ return this.loading;
68
+ }
69
+
70
+ dispose(): void {
71
+ this.abort.abort();
72
+ this.external.clear();
73
+ }
74
+ }
75
+
76
+ function listSessions(sessionDir: string, signal: AbortSignal) {
77
+ // Matches the "all" scope of /resume: the default store keeps one folder per project under
78
+ // the agent's sessions root, and a custom session directory holds every session itself.
79
+ const root = join(getAgentDir(), "sessions");
80
+ const custom = sessionDir !== "" && resolve(dirname(sessionDir)) !== resolve(root);
81
+ return custom
82
+ ? SessionManager.listAll(sessionDir, undefined, signal)
83
+ : SessionManager.listAll(undefined, signal);
84
+ }
@@ -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
+ }