proper-base 0.2.7 → 0.3.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.
@@ -0,0 +1,497 @@
1
+ /**
2
+ * Fast session metadata for the `/resume` picker.
3
+ *
4
+ * Pi's `SessionManager.list` builds each `SessionInfo` by streaming every line
5
+ * of every session file, `JSON.parse`-ing it, and concatenating every message's
6
+ * text into `allMessagesText`. Only the picker's search reads that field, so a
7
+ * project with hundreds of megabytes of transcripts waits seconds before the
8
+ * first row is drawn.
9
+ *
10
+ * These readers replace that with two cheap passes. Session entries are one
11
+ * JSON object per line, so a byte-prefix test classifies a line without
12
+ * decoding it: the head is read until the first user message, then the file is
13
+ * scanned as raw bytes to count messages and locate the newest rename.
14
+ * `allMessagesText` starts empty and is refilled by a detached backfill, so
15
+ * search recovers on its own instead of blocking the picker.
16
+ */
17
+
18
+ import { createReadStream } from "node:fs";
19
+ import { open, readdir, stat } from "node:fs/promises";
20
+ import { join, resolve } from "node:path";
21
+ import { createInterface } from "node:readline";
22
+
23
+ import { projectKey } from "./store.ts";
24
+
25
+ /** Structurally compatible with pi's `SessionInfo`. */
26
+ export type SessionInfo = {
27
+ path: string;
28
+ id: string;
29
+ cwd: string;
30
+ name?: string | undefined;
31
+ parentSessionPath?: string | undefined;
32
+ created: Date;
33
+ modified: Date;
34
+ messageCount: number;
35
+ firstMessage: string;
36
+ allMessagesText: string;
37
+ };
38
+
39
+ export type ProgressCallback = (loaded: number, total: number) => void;
40
+
41
+ const SESSION_PREFIX = '{"type":"session"';
42
+ const MESSAGE_PREFIX = '{"type":"message"';
43
+ const NAME_PREFIX = '{"type":"session_info"';
44
+ const MESSAGE_BYTES = Buffer.from(`\n${MESSAGE_PREFIX}`);
45
+ const NAME_BYTES = Buffer.from(`\n${NAME_PREFIX}`);
46
+ const CHUNK_BYTES = 1 << 20;
47
+
48
+ /**
49
+ * Bytes of an entry inspected for its role and write time.
50
+ *
51
+ * Both sit before the message body: `{"type":"message","id":…,"parentId":…,
52
+ * "timestamp":…,"message":{"role":…`.
53
+ */
54
+ const ENTRY_HEAD_BYTES = 256;
55
+
56
+ /** Matches pi's own concurrency, so disk access patterns do not change. */
57
+ const MAX_CONCURRENT_READS = 10;
58
+
59
+ /**
60
+ * Bytes read while looking for the first user message.
61
+ *
62
+ * The first thing a user typed precedes every response it caused, so this only
63
+ * bounds files that never received one.
64
+ */
65
+ const MAX_HEAD_BYTES = 4 << 20;
66
+
67
+ /** Upper bound for re-reading one rename entry, which holds a short name. */
68
+ const NAME_ENTRY_BYTES = 8192;
69
+
70
+ type JsonRecord = Record<string, unknown>;
71
+
72
+ function parseLine(line: string): JsonRecord | undefined {
73
+ try {
74
+ const parsed: unknown = JSON.parse(line);
75
+ return parsed && typeof parsed === "object"
76
+ ? (parsed as JsonRecord)
77
+ : undefined;
78
+ } catch {
79
+ return undefined;
80
+ }
81
+ }
82
+
83
+ function messageOf(entry: JsonRecord): JsonRecord | undefined {
84
+ const message = entry.message;
85
+ return message && typeof message === "object"
86
+ ? (message as JsonRecord)
87
+ : undefined;
88
+ }
89
+
90
+ /** Pi joins text blocks with a space and passes string content through. */
91
+ export function extractText(message: JsonRecord): string {
92
+ const content = message.content;
93
+ if (typeof content === "string") return content;
94
+ if (!Array.isArray(content)) return "";
95
+ const texts: string[] = [];
96
+ for (const block of content) {
97
+ if (!block || typeof block !== "object") continue;
98
+ const part = block as JsonRecord;
99
+ if (part.type === "text" && typeof part.text === "string")
100
+ texts.push(part.text);
101
+ }
102
+ return texts.join(" ");
103
+ }
104
+
105
+ type Head = { header: JsonRecord; firstMessage: string };
106
+
107
+ /**
108
+ * Read the session header and the first user message.
109
+ *
110
+ * Stops as soon as both are known, so the cost is the head of the file rather
111
+ * than its length.
112
+ */
113
+ async function readHead(filePath: string): Promise<Head | undefined> {
114
+ // Closing the interface leaves its input open, and this returns early for
115
+ // almost every file, so the stream itself has to be destroyed.
116
+ const input = createReadStream(filePath, { encoding: "utf8" });
117
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
118
+ try {
119
+ let header: JsonRecord | undefined;
120
+ let read = 0;
121
+ for await (const line of lines) {
122
+ if (!line) continue;
123
+ if (!header) {
124
+ // A first line that is not a session header means this is not a
125
+ // session file, and pi drops those from the list.
126
+ if (!line.startsWith(SESSION_PREFIX)) return undefined;
127
+ header = parseLine(line);
128
+ if (!header) return undefined;
129
+ continue;
130
+ }
131
+ read += line.length;
132
+ if (read > MAX_HEAD_BYTES) break;
133
+ if (!line.startsWith(MESSAGE_PREFIX)) continue;
134
+ const message = messageOf(parseLine(line) ?? {});
135
+ if (message?.role !== "user") continue;
136
+ const text = extractText(message);
137
+ if (text) return { header, firstMessage: text };
138
+ }
139
+ return header ? { header, firstMessage: "" } : undefined;
140
+ } finally {
141
+ lines.close();
142
+ input.destroy();
143
+ }
144
+ }
145
+
146
+ type Scan = {
147
+ messageCount: number;
148
+ lastNameOffset: number;
149
+ lastActivity: number | undefined;
150
+ };
151
+
152
+ /**
153
+ * Read one entry's write time, if it is a message pi counts as activity.
154
+ *
155
+ * `head` is the start of an entry; the body beyond it is not needed. Pi prefers
156
+ * the message's own start time, which sits after the content and would cost a
157
+ * full-line read, so this uses the entry's write time instead — later by the
158
+ * duration of the response, which is seconds.
159
+ */
160
+ function entryActivityTime(head: string): number | undefined {
161
+ const roleAt = head.indexOf('"role":"');
162
+ if (roleAt < 0) return undefined;
163
+ const role = head.slice(roleAt + 8, head.indexOf('"', roleAt + 8));
164
+ if (role !== "user" && role !== "assistant") return undefined;
165
+ const timeAt = head.indexOf('"timestamp":"');
166
+ if (timeAt < 0 || timeAt > roleAt) return undefined;
167
+ const parsed = new Date(
168
+ head.slice(timeAt + 13, head.indexOf('"', timeAt + 13)),
169
+ ).getTime();
170
+ return Number.isNaN(parsed) ? undefined : parsed;
171
+ }
172
+
173
+ /**
174
+ * Count message entries, locate the newest rename, and track last activity.
175
+ *
176
+ * Nothing is decoded and no line is assembled: single entries reach tens of
177
+ * megabytes, so buffering one would cost more than the scan it serves. Every
178
+ * needle includes the preceding newline, which anchors it to a line start and
179
+ * keeps it from matching text inside a JSON string.
180
+ */
181
+ async function scanFile(filePath: string): Promise<Scan> {
182
+ let messageCount = 0;
183
+ let lastNameOffset = -1;
184
+ let lastActivity: number | undefined;
185
+ let offset = 0;
186
+ let carry = Buffer.alloc(0);
187
+
188
+ // Consecutive buffers overlap by one entry head, so an entry whose head is
189
+ // cut short here is left for the next buffer, where it is whole. Because
190
+ // `limit` stops one byte before the overlap begins, no entry is taken twice.
191
+ const take = (buffer: Buffer, base: number, limit: number): void => {
192
+ for (let at = 0; at <= limit; ) {
193
+ const found = buffer.indexOf(MESSAGE_BYTES, at);
194
+ if (found < 0 || found > limit) break;
195
+ at = found + MESSAGE_BYTES.length;
196
+ messageCount++;
197
+ const time = entryActivityTime(
198
+ buffer.toString("utf8", found, found + ENTRY_HEAD_BYTES),
199
+ );
200
+ if (time !== undefined && time > (lastActivity ?? 0)) lastActivity = time;
201
+ }
202
+ // Renames are re-read from the file by offset, so a short head is fine.
203
+ for (let at = 0; ; ) {
204
+ const found = buffer.indexOf(NAME_BYTES, at);
205
+ if (found < 0) break;
206
+ lastNameOffset = base + found + 1;
207
+ at = found + NAME_BYTES.length;
208
+ }
209
+ };
210
+
211
+ for await (const chunk of createReadStream(filePath, {
212
+ highWaterMark: CHUNK_BYTES,
213
+ }) as AsyncIterable<Buffer>) {
214
+ const buffer = carry.length > 0 ? Buffer.concat([carry, chunk]) : chunk;
215
+ const base = offset - carry.length;
216
+ take(buffer, base, buffer.length - ENTRY_HEAD_BYTES - 1);
217
+ offset += chunk.length;
218
+ // Only the overlap carries, so a single huge entry never accumulates.
219
+ carry = Buffer.from(
220
+ buffer.subarray(Math.max(0, buffer.length - ENTRY_HEAD_BYTES)),
221
+ );
222
+ }
223
+ // At end of file a short head is all there is.
224
+ take(carry, offset - carry.length, carry.length);
225
+ return { messageCount, lastNameOffset, lastActivity };
226
+ }
227
+
228
+ /** Re-read one rename entry. Renames are rare, so this costs one small read. */
229
+ async function readName(
230
+ filePath: string,
231
+ offset: number,
232
+ ): Promise<string | undefined> {
233
+ const handle = await open(filePath, "r");
234
+ try {
235
+ const buffer = Buffer.alloc(NAME_ENTRY_BYTES);
236
+ const { bytesRead } = await handle.read(
237
+ buffer,
238
+ 0,
239
+ NAME_ENTRY_BYTES,
240
+ offset,
241
+ );
242
+ const text = buffer.subarray(0, bytesRead).toString("utf8");
243
+ const end = text.indexOf("\n");
244
+ const entry = parseLine(end < 0 ? text : text.slice(0, end));
245
+ if (typeof entry?.name !== "string") return undefined;
246
+ return entry.name.trim() || undefined;
247
+ } finally {
248
+ await handle.close();
249
+ }
250
+ }
251
+
252
+ /**
253
+ * Read one session file's picker metadata.
254
+ *
255
+ * Returns `null` for anything without a session header, matching how pi drops
256
+ * those files from the list.
257
+ */
258
+ export async function readSessionInfo(
259
+ filePath: string,
260
+ ): Promise<SessionInfo | null> {
261
+ try {
262
+ const [stats, head] = await Promise.all([
263
+ stat(filePath),
264
+ readHead(filePath),
265
+ ]);
266
+ if (!head) return null;
267
+ const { header } = head;
268
+ const scan = await scanFile(filePath);
269
+ const name =
270
+ scan.lastNameOffset >= 0
271
+ ? await readName(filePath, scan.lastNameOffset)
272
+ : undefined;
273
+
274
+ const created =
275
+ typeof header.timestamp === "string"
276
+ ? new Date(header.timestamp)
277
+ : stats.mtime;
278
+ // The file's own mtime is not a substitute: branching from a session
279
+ // appends to it hours after its last message.
280
+ const modified =
281
+ scan.lastActivity !== undefined && scan.lastActivity > 0
282
+ ? new Date(scan.lastActivity)
283
+ : Number.isNaN(created.getTime())
284
+ ? stats.mtime
285
+ : created;
286
+
287
+ return {
288
+ path: filePath,
289
+ id: typeof header.id === "string" ? header.id : "",
290
+ cwd: typeof header.cwd === "string" ? header.cwd : "",
291
+ name,
292
+ parentSessionPath:
293
+ typeof header.parentSession === "string"
294
+ ? header.parentSession
295
+ : undefined,
296
+ created,
297
+ modified,
298
+ messageCount: scan.messageCount,
299
+ firstMessage: head.firstMessage || "(no messages)",
300
+ allMessagesText: "",
301
+ };
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
306
+
307
+ /** Concatenated message text, matching what pi's picker search expects. */
308
+ export async function readSearchText(filePath: string): Promise<string> {
309
+ const parts: string[] = [];
310
+ const input = createReadStream(filePath, { encoding: "utf8" });
311
+ const lines = createInterface({ input, crlfDelay: Number.POSITIVE_INFINITY });
312
+ try {
313
+ for await (const line of lines) {
314
+ if (!line.startsWith(MESSAGE_PREFIX)) continue;
315
+ const message = messageOf(parseLine(line) ?? {});
316
+ if (!message) continue;
317
+ if (message.role !== "user" && message.role !== "assistant") continue;
318
+ const text = extractText(message);
319
+ if (text) parts.push(text);
320
+ }
321
+ } catch {
322
+ // A partial read still beats the empty placeholder for search.
323
+ } finally {
324
+ lines.close();
325
+ input.destroy();
326
+ }
327
+ return parts.join(" ");
328
+ }
329
+
330
+ /** Run `task` over `items` with pi's bounded concurrency. */
331
+ async function mapConcurrent<T>(
332
+ items: string[],
333
+ task: (item: string) => Promise<T>,
334
+ onDone?: () => void,
335
+ ): Promise<T[]> {
336
+ const results = new Array<T>(items.length);
337
+ let next = 0;
338
+ const worker = async (): Promise<void> => {
339
+ for (;;) {
340
+ const index = next++;
341
+ const item = items[index];
342
+ if (item === undefined) return;
343
+ results[index] = await task(item);
344
+ onDone?.();
345
+ }
346
+ };
347
+ await Promise.all(
348
+ Array.from(
349
+ { length: Math.min(MAX_CONCURRENT_READS, items.length) },
350
+ worker,
351
+ ),
352
+ );
353
+ return results;
354
+ }
355
+
356
+ async function sessionFiles(dir: string): Promise<string[]> {
357
+ try {
358
+ return (await readdir(dir))
359
+ .filter((file) => file.endsWith(".jsonl"))
360
+ .map((file) => join(dir, file));
361
+ } catch {
362
+ return [];
363
+ }
364
+ }
365
+
366
+ function byNewest(a: SessionInfo, b: SessionInfo): number {
367
+ return b.modified.getTime() - a.modified.getTime();
368
+ }
369
+
370
+ async function collect(
371
+ files: string[],
372
+ onProgress?: ProgressCallback,
373
+ ): Promise<SessionInfo[]> {
374
+ let loaded = 0;
375
+ const results = await mapConcurrent(files, readSessionInfo, () => {
376
+ loaded++;
377
+ onProgress?.(loaded, files.length);
378
+ });
379
+ return results.filter((info): info is SessionInfo => info !== null);
380
+ }
381
+
382
+ /** Pi's session directory for a working directory. Pi resolves the cwd first. */
383
+ export function projectSessionDir(agentDir: string, cwd: string): string {
384
+ return join(resolve(agentDir), "sessions", projectKey(resolve(cwd)));
385
+ }
386
+
387
+ /** Drop-in replacements for `SessionManager.list` and `SessionManager.listAll`. */
388
+ export function createSessionListers(agentDir: string) {
389
+ const list = async (
390
+ cwd: string,
391
+ sessionDir?: string,
392
+ onProgress?: ProgressCallback,
393
+ ): Promise<SessionInfo[]> => {
394
+ const defaultDir = projectSessionDir(agentDir, cwd);
395
+ const dir = sessionDir ? resolve(sessionDir) : defaultDir;
396
+ // A custom session directory can hold sessions from other projects.
397
+ const filterCwd = sessionDir !== undefined && dir !== defaultDir;
398
+ const resolvedCwd = resolve(cwd);
399
+ const sessions = await collect(await sessionFiles(dir), onProgress);
400
+ return sessions
401
+ .filter(
402
+ (session) =>
403
+ !filterCwd || (!!session.cwd && resolve(session.cwd) === resolvedCwd),
404
+ )
405
+ .sort(byNewest);
406
+ };
407
+
408
+ const listAll = async (
409
+ sessionDirOrProgress?: string | ProgressCallback,
410
+ maybeProgress?: ProgressCallback,
411
+ ): Promise<SessionInfo[]> => {
412
+ const customDir =
413
+ typeof sessionDirOrProgress === "string"
414
+ ? sessionDirOrProgress
415
+ : undefined;
416
+ const onProgress =
417
+ typeof sessionDirOrProgress === "function"
418
+ ? sessionDirOrProgress
419
+ : maybeProgress;
420
+ if (customDir) {
421
+ const sessions = await collect(
422
+ await sessionFiles(resolve(customDir)),
423
+ onProgress,
424
+ );
425
+ return sessions.sort(byNewest);
426
+ }
427
+ const root = join(resolve(agentDir), "sessions");
428
+ let projects: string[];
429
+ try {
430
+ projects = (await readdir(root, { withFileTypes: true }))
431
+ .filter((entry) => entry.isDirectory() || entry.isSymbolicLink())
432
+ .map((entry) => join(root, entry.name));
433
+ } catch {
434
+ return [];
435
+ }
436
+ const files = (await Promise.all(projects.map(sessionFiles))).flat();
437
+ const sessions = await collect(files, onProgress);
438
+ return sessions.sort(byNewest);
439
+ };
440
+
441
+ return { list, listAll };
442
+ }
443
+
444
+ /**
445
+ * Refill `allMessagesText` on sessions the picker already holds.
446
+ *
447
+ * The picker reads that field on every keystroke, so mutating the objects it
448
+ * was handed restores full-text search without the loader ever waiting for it.
449
+ * Sessions arrive newest-first, which is the order the picker shows them in.
450
+ */
451
+ export function backfillSearchText(sessions: SessionInfo[]): () => void {
452
+ let cancelled = false;
453
+ void (async () => {
454
+ for (const session of sessions) {
455
+ if (cancelled) return;
456
+ session.allMessagesText = await readSearchText(session.path);
457
+ }
458
+ })();
459
+ return () => {
460
+ cancelled = true;
461
+ };
462
+ }
463
+
464
+ type Listers = { list: unknown; listAll: unknown };
465
+
466
+ const FAST_SESSION_LIST = Symbol.for("pi-proper-base.fast-session-list");
467
+
468
+ /**
469
+ * Point pi's session listing at the fast readers.
470
+ *
471
+ * Pi's `SessionManager` is a module singleton reached through static property
472
+ * lookups, so replacing the two listing methods covers `/resume` without
473
+ * touching the picker. Installation is idempotent: the class outlives every
474
+ * session, so a reload must not stack wrappers.
475
+ */
476
+ export function installFastSessionList(target: object, agentDir: string): void {
477
+ const tagged = target as Listers & { [FAST_SESSION_LIST]?: true };
478
+ if (tagged[FAST_SESSION_LIST]) return;
479
+ const fast = createSessionListers(agentDir);
480
+ let cancelBackfill: (() => void) | undefined;
481
+ const served = (sessions: SessionInfo[]): SessionInfo[] => {
482
+ // Only the newest listing is worth completing; a rescan replaces it.
483
+ cancelBackfill?.();
484
+ cancelBackfill = backfillSearchText(sessions);
485
+ return sessions;
486
+ };
487
+ tagged.list = (
488
+ cwd: string,
489
+ sessionDir?: string,
490
+ onProgress?: ProgressCallback,
491
+ ) => fast.list(cwd, sessionDir, onProgress).then(served);
492
+ tagged.listAll = (
493
+ sessionDirOrProgress?: string | ProgressCallback,
494
+ onProgress?: ProgressCallback,
495
+ ) => fast.listAll(sessionDirOrProgress, onProgress).then(served);
496
+ tagged[FAST_SESSION_LIST] = true;
497
+ }
@@ -0,0 +1,200 @@
1
+ import { parseSkillBlock } from "@earendil-works/pi-coding-agent";
2
+
3
+ /**
4
+ * Characters kept from a single skill body when it is carried across a
5
+ * compaction. Roughly four characters per token, matching the estimate Pi's
6
+ * own compaction uses.
7
+ */
8
+ const MAX_SKILL_CHARS = 16000;
9
+ /** Combined character budget for every skill carried across one compaction. */
10
+ const MAX_CARRY_CHARS = 24000;
11
+ const TRUNCATED = "\n\n[skill content truncated to fit the context budget]";
12
+
13
+ type ContextMessage = {
14
+ role: string;
15
+ content?: unknown;
16
+ };
17
+ type TextPart = { type: "text"; text: string };
18
+ type SessionEntry = {
19
+ type: string;
20
+ message?: { role?: string; content?: unknown };
21
+ };
22
+ type Invocation = { name: string; block: string };
23
+
24
+ function isTextPart(value: unknown): value is TextPart {
25
+ return (
26
+ typeof value === "object" &&
27
+ value !== null &&
28
+ (value as { type?: unknown }).type === "text" &&
29
+ typeof (value as { text?: unknown }).text === "string"
30
+ );
31
+ }
32
+
33
+ /**
34
+ * Pi renders a skill invocation as one text part holding the block followed by
35
+ * the user's own request, so both live in a single message.
36
+ */
37
+ function readInvocation(
38
+ text: string,
39
+ ): { name: string; block: string; request: string } | undefined {
40
+ const parsed = parseSkillBlock(text);
41
+ if (!parsed) return undefined;
42
+ return {
43
+ name: parsed.name,
44
+ block: `<skill name="${parsed.name}" location="${parsed.location}">\n${parsed.content}\n</skill>`,
45
+ request: parsed.userMessage ?? "",
46
+ };
47
+ }
48
+
49
+ function messageInvocation(
50
+ message: ContextMessage | SessionEntry["message"],
51
+ ): ReturnType<typeof readInvocation> {
52
+ const content = message?.content;
53
+ if (typeof content === "string") return readInvocation(content);
54
+ if (!Array.isArray(content)) return undefined;
55
+ for (const part of content) {
56
+ if (!isTextPart(part)) continue;
57
+ const invocation = readInvocation(part.text);
58
+ if (invocation) return invocation;
59
+ }
60
+ return undefined;
61
+ }
62
+
63
+ function replaceInvocationText(
64
+ message: ContextMessage,
65
+ replacement: string,
66
+ ): ContextMessage {
67
+ const content = message.content;
68
+ if (typeof content === "string") {
69
+ return { ...message, content: replacement };
70
+ }
71
+ if (!Array.isArray(content)) return message;
72
+ let done = false;
73
+ const next = content.map((part) => {
74
+ if (done || !isTextPart(part) || !parseSkillBlock(part.text)) return part;
75
+ done = true;
76
+ return { ...part, text: replacement };
77
+ });
78
+ return done ? { ...message, content: next } : message;
79
+ }
80
+
81
+ function prependText(message: ContextMessage, prefix: string): ContextMessage {
82
+ const content = message.content;
83
+ if (typeof content === "string") {
84
+ return { ...message, content: `${prefix}${content}` };
85
+ }
86
+ if (!Array.isArray(content)) return message;
87
+ const index = content.findIndex(isTextPart);
88
+ if (index < 0) {
89
+ return {
90
+ ...message,
91
+ content: [{ type: "text", text: prefix }, ...content],
92
+ };
93
+ }
94
+ const part = content[index] as TextPart;
95
+ const next = [...content];
96
+ next[index] = { ...part, text: `${prefix}${part.text}` };
97
+ return { ...message, content: next };
98
+ }
99
+
100
+ function truncate(block: string, limit: number): string {
101
+ return block.length <= limit ? block : block.slice(0, limit) + TRUNCATED;
102
+ }
103
+
104
+ /**
105
+ * Keep every invoked skill present exactly once in the outgoing context.
106
+ *
107
+ * Pi inlines the whole `SKILL.md` body into a user message and then treats that
108
+ * message like any other: re-invoking a skill appends a second full copy, and
109
+ * compaction summarizes the copy away while the model keeps working under
110
+ * instructions it can no longer read. This collapses repeats to a short note
111
+ * and carries the most recent body across a compaction boundary, bounded by a
112
+ * character budget so the restored text cannot re-trigger the compaction that
113
+ * just ran.
114
+ *
115
+ * The first copy is never rewritten, so the cached request prefix stays byte
116
+ * stable across turns.
117
+ */
118
+ export function pinSkillContext<T extends ContextMessage>(
119
+ messages: T[],
120
+ branch: SessionEntry[],
121
+ ): T[] {
122
+ const seen = new Set<string>();
123
+ let changed = false;
124
+
125
+ let next = messages.map((message) => {
126
+ if (message.role !== "user") return message;
127
+ const invocation = messageInvocation(message);
128
+ if (!invocation) return message;
129
+ if (!seen.has(invocation.block)) {
130
+ seen.add(invocation.block);
131
+ return message;
132
+ }
133
+ changed = true;
134
+ const note = `[skill "${invocation.name}" is already loaded earlier in this conversation]`;
135
+ return replaceInvocationText(
136
+ message,
137
+ invocation.request ? `${note}\n\n${invocation.request}` : note,
138
+ ) as T;
139
+ });
140
+
141
+ const carried = carryAcrossCompaction(next, branch, seen);
142
+ if (!carried) return changed ? next : messages;
143
+
144
+ const anchor = restoreAnchor(next);
145
+ if (anchor < 0) return changed ? next : messages;
146
+ next = [...next];
147
+ next[anchor] = prependText(next[anchor] as ContextMessage, carried) as T;
148
+ return next;
149
+ }
150
+
151
+ /**
152
+ * Collect the newest body of each skill that the branch invoked but the
153
+ * compacted context no longer carries, newest first until the budget runs out.
154
+ */
155
+ function carryAcrossCompaction(
156
+ messages: ContextMessage[],
157
+ branch: SessionEntry[],
158
+ present: Set<string>,
159
+ ): string | undefined {
160
+ if (!messages.some((message) => message.role === "compactionSummary")) {
161
+ return undefined;
162
+ }
163
+ const missing = new Map<string, Invocation>();
164
+ for (const entry of branch) {
165
+ if (entry.type !== "message" || entry.message?.role !== "user") continue;
166
+ const invocation = messageInvocation(entry.message);
167
+ if (!invocation) continue;
168
+ // A skill file edited mid-session yields a new body, so the newest state
169
+ // of each name decides: a present body cancels an earlier missing one.
170
+ if (present.has(invocation.block)) missing.delete(invocation.name);
171
+ else missing.set(invocation.name, invocation);
172
+ }
173
+ if (!missing.size) return undefined;
174
+
175
+ const blocks: string[] = [];
176
+ let used = 0;
177
+ for (const invocation of [...missing.values()].reverse()) {
178
+ const block = truncate(invocation.block, MAX_SKILL_CHARS);
179
+ if (used + block.length > MAX_CARRY_CHARS) continue;
180
+ used += block.length;
181
+ blocks.unshift(block);
182
+ }
183
+ return blocks.length ? `${blocks.join("\n\n")}\n\n` : undefined;
184
+ }
185
+
186
+ /** The first user turn after the newest compaction summary. */
187
+ function restoreAnchor(messages: ContextMessage[]): number {
188
+ let summary = -1;
189
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
190
+ if (messages[index]?.role === "compactionSummary") {
191
+ summary = index;
192
+ break;
193
+ }
194
+ }
195
+ if (summary < 0) return -1;
196
+ for (let index = summary + 1; index < messages.length; index += 1) {
197
+ if (messages[index]?.role === "user") return index;
198
+ }
199
+ return -1;
200
+ }