@foliox/transparent-compact-pi 0.0.0-stage → 0.8.3

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,1440 @@
1
+ /**
2
+ * transparent-compact — transparent compaction with session-backed recovery.
3
+ *
4
+ * Builds a deterministic checkpoint without writing local transcript dumps. context_lookup renders the current raw
5
+ * session branch in memory at call time, including earlier compactions,
6
+ * thinking, full tool outputs, and tool-call arguments. Pi normally persists
7
+ * this history under ~/.pi/agent/sessions/; custom session locations and
8
+ * ephemeral sessions work too. Only the active branch is searched.
9
+ *
10
+ * Does not register dump_context or /dump-context, and does not read, write,
11
+ * or prune old dumps.
12
+ *
13
+ * Optional env settings:
14
+ * MECH_COMPACT_MAX_SUMMARY_CHARS initial character budget override (takes precedence over percent)
15
+ * MECH_COMPACT_MAX_SUMMARY_PERCENT initial percentage of model context (default 25; >0, <=100)
16
+ * MECH_COMPACT_LOOKUP_MODEL "provider/modelId" for the lookup subagent
17
+ * MECH_COMPACT_LOOKUP_TURNS max substantive search turns (default 10).
18
+ * Valid continuation-only turns are exempt;
19
+ * total search-phase calls capped at 3x this,
20
+ * plus one final write-up on exhaustion
21
+ * MECH_COMPACT_LOOKUP_MAX_CALLS consecutive lookup limit (default 1;
22
+ * 0 = unlimited). Non-recovery tool results,
23
+ * bash executions, or user messages reset it.
24
+ * Fallback tools neither count nor reset it.
25
+ * MECH_COMPACT_LOOKUP_SESSION_FILE absolute session JSONL path to search
26
+ * instead of the current branch (study override)
27
+ */
28
+
29
+ import * as fs from "node:fs";
30
+ import * as path from "node:path";
31
+ import { Type } from "typebox";
32
+ import { contentText, normalizeContext, uuidv7 } from "@earendil-works/pi-ai";
33
+ import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-works/pi-ai";
34
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
35
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
36
+ import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
37
+
38
+ // ============================================================================
39
+ // Configuration
40
+ // ============================================================================
41
+
42
+ const MECH_KIND = "mech-compact";
43
+ const METHOD_ENTRY = "transparent-compact:compaction-method";
44
+ type CompactionMethod = "verbatim" | "summary";
45
+
46
+ const SUMMARY_COMPACTION_WARNING = "Applying summary compaction weakens the verbatim guarantee. You may switch back to verbatim compaction before summary compaction runs to leave the guarantee unchanged. If summary compaction runs (manually or automatically), it replaces older active context with a model-generated summary, which may omit or reinterpret details. Switching back afterward does not undo this: only subsequent verbatim spans retain the guarantee. Original history remains recoverable through context_lookup, but is no longer a direct expansion of the active context.";
47
+ const MIXED_CONTEXT_WARNING = "**Mixed context: earlier material is model-summarized, not verbatim.** The verbatim guarantee applies only to the labelled verbatim spans and uncompacted tail. The model-summary base may omit or reinterpret details; use `context_lookup` to recover original history.";
48
+
49
+ // Read from the active branch rather than cached state: reload, resume, fork,
50
+ // and tree navigation all inherit only the choices on their own path.
51
+ function compactionMethod(entries: SessionEntry[]): CompactionMethod {
52
+ for (let i = entries.length - 1; i >= 0; i--) {
53
+ const entry = entries[i];
54
+ if (entry.type !== "custom" || entry.customType !== METHOD_ENTRY) continue;
55
+ const method = (entry.data as { method?: unknown } | undefined)?.method;
56
+ if (method === "verbatim" || method === "summary") return method;
57
+ }
58
+ return "verbatim";
59
+ }
60
+
61
+ function intFromEnv(name: string, fallback: number): number {
62
+ const raw = process.env[name];
63
+ if (!raw) return fallback;
64
+ const n = Number.parseInt(raw, 10);
65
+ return Number.isFinite(n) && n > 0 ? n : fallback;
66
+ }
67
+
68
+ function percentFromEnv(name: string, fallback: number): number {
69
+ const n = Number(process.env[name]);
70
+ return Number.isFinite(n) && n > 0 && n <= 100 ? n : fallback;
71
+ }
72
+
73
+ function lookupMaxCallsFromEnv(): number {
74
+ const raw = process.env.MECH_COMPACT_LOOKUP_MAX_CALLS?.trim();
75
+ const n = raw && /^\d+$/.test(raw) ? Number(raw) : NaN;
76
+ return Number.isSafeInteger(n) && n >= 0 ? n : 1;
77
+ }
78
+
79
+ const cfg = {
80
+ defaultCapBudget: (process.env.MECH_COMPACT_MAX_SUMMARY_CHARS
81
+ ? { unit: "chars", value: intFromEnv("MECH_COMPACT_MAX_SUMMARY_CHARS", 80_000) }
82
+ : { unit: "percent", value: percentFromEnv("MECH_COMPACT_MAX_SUMMARY_PERCENT", 25) }) as CapBudget,
83
+ lookupTurns: intFromEnv("MECH_COMPACT_LOOKUP_TURNS", 10),
84
+ lookupMaxCalls: lookupMaxCallsFromEnv(),
85
+ lookupModel: process.env.MECH_COMPACT_LOOKUP_MODEL?.trim() || undefined,
86
+ argSnippetChars: 160,
87
+ listMaxChars: 12_000,
88
+ grepMaxChars: 12_000,
89
+ showEntryMaxChars: 24_000,
90
+ lookupAnswerMaxChars: 12_000,
91
+ };
92
+
93
+ // Cap policy is session/branch state, separate from the compaction method.
94
+ const CAP_ENTRY = "transparent-compact:cap-compaction";
95
+ type CapMode = "on" | "off" | "warn";
96
+ interface CapBudget { unit: "chars" | "tokens" | "percent"; value: number }
97
+ interface CapSettings { mode: CapMode; budget: CapBudget }
98
+
99
+ function validCapBudget(value: unknown): value is CapBudget {
100
+ if (!value || typeof value !== "object") return false;
101
+ const { unit, value: n } = value as CapBudget;
102
+ if (typeof n !== "number" || !Number.isFinite(n) || n <= 0) return false;
103
+ if (unit === "percent") return n <= 100;
104
+ return Number.isSafeInteger(n) && (unit === "chars" || (unit === "tokens" && n <= Number.MAX_SAFE_INTEGER / 4));
105
+ }
106
+
107
+ function parseCapBudget(text: string): CapBudget | undefined {
108
+ const match = /^(\d+(?:\.\d+)?)(c|t|%)$/.exec(text);
109
+ if (!match) return;
110
+ const budget: CapBudget = { value: Number(match[1]), unit: match[2] === "c" ? "chars" : match[2] === "t" ? "tokens" : "percent" };
111
+ return validCapBudget(budget) ? budget : undefined;
112
+ }
113
+
114
+ function capSettings(entries: SessionEntry[]): CapSettings {
115
+ for (let i = entries.length - 1; i >= 0; i--) {
116
+ const entry = entries[i];
117
+ if (entry.type !== "custom" || entry.customType !== CAP_ENTRY) continue;
118
+ const state = entry.data as CapSettings | undefined;
119
+ if (state && ["on", "off", "warn"].includes(state.mode) && validCapBudget(state.budget)) return state;
120
+ }
121
+ return { mode: "warn", budget: { ...cfg.defaultCapBudget } };
122
+ }
123
+
124
+ function capBudgetText(budget: CapBudget): string {
125
+ return `${budget.value}${budget.unit === "chars" ? "c" : budget.unit === "tokens" ? "t" : "%"}`;
126
+ }
127
+
128
+ function capBudgetChars(budget: CapBudget, contextWindow?: number): number | undefined {
129
+ if (budget.unit === "chars") return budget.value;
130
+ if (budget.unit === "tokens") return budget.value * 4;
131
+ if (!contextWindow || !Number.isSafeInteger(contextWindow) || contextWindow <= 0) return;
132
+ const tokens = Math.max(1, Math.floor(contextWindow * budget.value / 100));
133
+ return tokens <= Number.MAX_SAFE_INTEGER / 4 ? tokens * 4 : undefined;
134
+ }
135
+
136
+ function capDescription(state: CapSettings, contextWindow?: number): string {
137
+ const chars = capBudgetChars(state.budget, contextWindow);
138
+ const resolved = chars === undefined ? "model context window unavailable" : state.budget.unit === "chars"
139
+ ? `${chars.toLocaleString()} chars`
140
+ : `${(chars / 4).toLocaleString()} estimated tokens at 4 chars/token; ${chars.toLocaleString()} chars`;
141
+ return `Verbatim compaction cap: ${state.mode}; budget ${capBudgetText(state.budget)} (${resolved}).`;
142
+ }
143
+
144
+ function persistCap(pi: ExtensionAPI, previous: CapSettings, next: CapSettings): void {
145
+ if (previous.mode !== next.mode || previous.budget.unit !== next.budget.unit || previous.budget.value !== next.budget.value)
146
+ pi.appendEntry(CAP_ENTRY, next);
147
+ }
148
+
149
+ // undefined means uncapped; null means cancel (never fall through to summary).
150
+ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal: AbortSignal | undefined,
151
+ reason: string, size: { overhead: number; lineChars: number }): Promise<number | undefined | null> {
152
+ try {
153
+ let state = capSettings(ctx.sessionManager.getBranch());
154
+ for (;;) {
155
+ if (signal?.aborted) return null;
156
+ if (state.mode === "off") return undefined;
157
+ const limit = capBudgetChars(state.budget, ctx.model?.contextWindow);
158
+ if (limit === undefined) {
159
+ ctx.ui.notify("transparent-compact: cannot resolve percentage cap without the model's context window; choose a c/t budget or turn the cap off.", "error");
160
+ return null;
161
+ }
162
+ // Exactly the existing cap's test, including its minimum 500-char line budget.
163
+ const needsTrim = size.lineChars > Math.max(500, limit - size.overhead);
164
+ if (state.mode !== "warn" || !needsTrim) return limit;
165
+ const warning = `Verbatim compaction would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation-section chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
166
+ if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
167
+ ctx.ui.notify(`${warning} Applying the cap because no interactive UI is available.`, "warning");
168
+ return limit;
169
+ }
170
+ const risk = reason === "overflow"
171
+ ? "Overflow recovery: disabling the cap may leave too much context for the retry."
172
+ : "Disabling the cap may leave too much context for the model.";
173
+ const choice = await ctx.ui.select(`${warning}\n${risk}`, [
174
+ "Apply trimming", "Disable cap for this session", "Change budget", "Cancel compaction",
175
+ ], { signal });
176
+ if (signal?.aborted) return null;
177
+ if (choice === "Apply trimming") return limit;
178
+ if (choice === "Disable cap for this session") {
179
+ const next: CapSettings = { ...state, mode: "off" };
180
+ persistCap(pi, state, next);
181
+ ctx.ui.notify(capDescription(next, ctx.model?.contextWindow), "info");
182
+ return undefined;
183
+ }
184
+ if (choice !== "Change budget") return null;
185
+ for (;;) {
186
+ if (typeof ctx.ui.input !== "function") return null;
187
+ const input = await ctx.ui.input("Compaction budget: <chars>c, <estimated tokens>t, or <context window>%", capBudgetText(state.budget), { signal });
188
+ if (signal?.aborted || input === undefined) return null;
189
+ const budget = parseCapBudget(input.trim());
190
+ if (!budget) {
191
+ ctx.ui.notify("Invalid budget: use a positive integer with c/t, or a percentage greater than 0 and at most 100% (e.g. 80000c, 20000t, 25%).", "error");
192
+ continue;
193
+ }
194
+ const next = { ...state, budget };
195
+ persistCap(pi, state, next);
196
+ state = next;
197
+ ctx.ui.notify(capDescription(state, ctx.model?.contextWindow), "info");
198
+ break; // Recheck: a smaller/new budget may still require trimming.
199
+ }
200
+ }
201
+ } catch (err) {
202
+ if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); compaction cancelled`, "error");
203
+ return null;
204
+ }
205
+ }
206
+
207
+ function errMsg(err: unknown): string {
208
+ return err instanceof Error ? err.message : String(err);
209
+ }
210
+
211
+ // ============================================================================
212
+ // Content helpers
213
+ // ============================================================================
214
+
215
+ interface TextOut {
216
+ text: string;
217
+ images: number;
218
+ }
219
+
220
+ function textOf(content: unknown): TextOut {
221
+ if (typeof content === "string") return { text: content, images: 0 };
222
+ if (Array.isArray(content)) {
223
+ let text = "";
224
+ let images = 0;
225
+ for (const block of content) {
226
+ if (block && block.type === "text" && typeof block.text === "string") text += block.text;
227
+ else if (block && block.type === "image") images++;
228
+ }
229
+ if (images > 0) text += `\n[${images} image(s) attached — binary, not inlined in transcript]`;
230
+ return { text, images };
231
+ }
232
+ return { text: "", images: 0 };
233
+ }
234
+
235
+ function truncateHead(text: string, max: number): string {
236
+ if (text.length <= max) return text;
237
+ const dropped = text.length - max;
238
+ return `${text.slice(0, max)}\n…[+${dropped} chars truncated]`;
239
+ }
240
+
241
+ // ============================================================================
242
+ // Transcript: full-fidelity branch serialization (untruncated, entry-anchored)
243
+ // ============================================================================
244
+
245
+ const HR = "=".repeat(78);
246
+
247
+ /**
248
+ * Serialize one message into PHYSICAL lines (no element may contain \n, so
249
+ * array positions map 1:1 to file lines) plus, for assistant messages, the
250
+ * relative position of each section marker line.
251
+ */
252
+ function serializeAgentMessage(msg: AgentMessage): { lines: string[]; sections?: { kind: string; rel: number }[] } {
253
+ const m = msg as unknown as Record<string, any>;
254
+ const lines: string[] = [];
255
+ const sections: { kind: string; rel: number }[] = [];
256
+ switch (msg.role) {
257
+ case "user":
258
+ case "toolResult": {
259
+ const { text } = textOf(m.content);
260
+ lines.push(...text.split("\n"));
261
+ break;
262
+ }
263
+ case "assistant": {
264
+ for (const block of m.content ?? []) {
265
+ if (block.type === "thinking") {
266
+ sections.push({ kind: "thinking", rel: lines.length });
267
+ lines.push("[thinking]", ...String(block.thinking ?? "").split("\n"));
268
+ } else if (block.type === "text") {
269
+ sections.push({ kind: "text", rel: lines.length });
270
+ lines.push("[text]", ...String(block.text ?? "").split("\n"));
271
+ } else if (block.type === "toolCall") {
272
+ sections.push({ kind: "toolCall", rel: lines.length });
273
+ lines.push(`[toolCall] ${block.name}`, ...JSON.stringify(block.arguments ?? {}, null, 2).split("\n"));
274
+ }
275
+ }
276
+ break;
277
+ }
278
+ case "bashExecution": {
279
+ lines.push(...`$ ${String(m.command ?? "")}`.split("\n"), "[output]", ...String(m.output ?? "").split("\n"));
280
+ break;
281
+ }
282
+ case "custom": {
283
+ lines.push(...textOf(m.content).text.split("\n"));
284
+ break;
285
+ }
286
+ default:
287
+ lines.push(...JSON.stringify(msg, null, 2).split("\n"));
288
+ }
289
+ return sections.length > 0 ? { lines, sections } : { lines };
290
+ }
291
+
292
+ interface TranscriptIndexSection {
293
+ kind: string;
294
+ /** 1-based line number of the section marker line */
295
+ startLine: number;
296
+ }
297
+
298
+ interface TranscriptIndexEntry {
299
+ id: string;
300
+ type: string;
301
+ role?: string;
302
+ /** 1-based line number of the ENTRY header line */
303
+ startLine: number;
304
+ /** 1-based line number of the last line of the block (inclusive) */
305
+ endLine: number;
306
+ sections?: TranscriptIndexSection[];
307
+ }
308
+
309
+ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index: TranscriptIndexEntry[] } {
310
+ const lines: string[] = [
311
+ "# pi session transcript — full raw branch",
312
+ "# Each block starts with an ENTRY header; entry ids match the session JSONL.",
313
+ "# Thinking blocks and tool outputs are complete (not truncated).",
314
+ "",
315
+ ];
316
+ interface BlockRec {
317
+ id: string;
318
+ type: string;
319
+ role?: string;
320
+ hrIdx: number;
321
+ sections?: { kind: string; rel: number }[];
322
+ }
323
+ const blocks: BlockRec[] = [];
324
+ for (const entry of entries) {
325
+ const t = (entry as { timestamp?: string }).timestamp ?? "";
326
+ const hrIdx = lines.length;
327
+ lines.push(HR);
328
+ let role: string | undefined;
329
+ let sections: { kind: string; rel: number }[] | undefined;
330
+ switch (entry.type) {
331
+ case "session": {
332
+ const e = entry as SessionEntry & { version?: number; id?: string; cwd?: string; parentSession?: string };
333
+ lines.push(`ENTRY <header> session v${e.version ?? 1} id=${e.id ?? "?"}`);
334
+ lines.push(` cwd=${e.cwd ?? "?"}${e.parentSession ? ` parentSession=${e.parentSession}` : ""}`);
335
+ break;
336
+ }
337
+ case "message": {
338
+ const m = entry.message as unknown as Record<string, any>;
339
+ if (m.role === "system") {
340
+ const sectionNames = m.sections ? Object.keys(m.sections).join(", ") : "(content only)";
341
+ lines.push(`ENTRY ${entry.id} system ${t}`);
342
+ lines.push(` (system prompt checkpoint — sections: ${sectionNames}; full text in session JSONL)`);
343
+ role = m.role;
344
+ } else {
345
+ const extra =
346
+ m.role === "toolResult"
347
+ ? ` (${m.toolName ?? "?"}, isError=${m.isError ? "true" : "false"})`
348
+ : m.role === "assistant"
349
+ ? ` (model=${m.provider ?? "?"}/${m.model ?? "?"}, stop=${m.stopReason ?? "?"})`
350
+ : "";
351
+ lines.push(`ENTRY ${entry.id} ${m.role}${extra} ${t}`);
352
+ const ser = serializeAgentMessage(entry.message);
353
+ lines.push(...ser.lines);
354
+ role = m.role;
355
+ sections = ser.sections;
356
+ }
357
+ break;
358
+ }
359
+ case "compaction": {
360
+ const e = entry as SessionEntry & { tokensBefore?: number; firstKeptEntryId?: string; summary?: string; details?: { dumpDir?: string } };
361
+ lines.push(`ENTRY ${entry.id} compaction ${t} tokensBefore=${e.tokensBefore ?? "?"} firstKeptEntryId=${e.firstKeptEntryId ?? "?"}`);
362
+ if (e.details?.dumpDir) lines.push(` previous dump: ${e.details.dumpDir}`);
363
+ lines.push("[summary]");
364
+ lines.push(...String(e.summary ?? "").split("\n"));
365
+ break;
366
+ }
367
+ case "branch_summary": {
368
+ const e = entry as SessionEntry & { fromId?: string; summary?: string };
369
+ lines.push(`ENTRY ${entry.id} branch_summary ${t} fromId=${e.fromId ?? "?"}`);
370
+ lines.push(...String(e.summary ?? "").split("\n"));
371
+ break;
372
+ }
373
+ case "custom_message": {
374
+ const e = entry as SessionEntry & { customType?: string; content?: unknown };
375
+ lines.push(`ENTRY ${entry.id} custom_message (${e.customType ?? "?"}) ${t}`);
376
+ lines.push(...textOf(e.content).text.split("\n"));
377
+ break;
378
+ }
379
+ case "model_change":
380
+ lines.push(`ENTRY ${entry.id} model_change ${t} -> ${(entry as any).provider}/${(entry as any).modelId}`);
381
+ break;
382
+ case "thinking_level_change":
383
+ lines.push(`ENTRY ${entry.id} thinking_level_change ${t} -> ${(entry as any).thinkingLevel}`);
384
+ break;
385
+ case "usage":
386
+ lines.push(`ENTRY ${entry.id} usage (${(entry as any).kind ?? "?"}) ${t} (not in LLM context)`);
387
+ break;
388
+ case "custom":
389
+ lines.push(`ENTRY ${entry.id} custom (${(entry as any).customType ?? "?"}) ${t} (not in LLM context)`);
390
+ break;
391
+ case "label":
392
+ lines.push(`ENTRY ${entry.id} label ${t} target=${(entry as any).targetId} label=${(entry as any).label ?? "(cleared)"}`);
393
+ break;
394
+ case "context_edit":
395
+ lines.push(
396
+ `ENTRY ${entry.id} context_edit ${t} target=${(entry as any).targetId} replacement=${(entry as any).replacement === null ? "omitted" : "replaced"}`,
397
+ );
398
+ break;
399
+ case "session_info":
400
+ lines.push(`ENTRY ${entry.id} session_info ${t} name=${(entry as any).name ?? ""}`);
401
+ break;
402
+ default:
403
+ lines.push(`ENTRY ${entry.id} ${(entry as { type: string }).type} ${t} (unhandled entry type)`);
404
+ }
405
+ lines.push("");
406
+ blocks.push({ id: entry.id, type: entry.type, role, hrIdx, sections });
407
+ }
408
+ const index: TranscriptIndexEntry[] = blocks.map((b, i) => {
409
+ const e: TranscriptIndexEntry = {
410
+ id: b.id,
411
+ type: b.type,
412
+ startLine: b.hrIdx + 2, // header line (1-based)
413
+ endLine: i + 1 < blocks.length ? blocks[i + 1].hrIdx : lines.length, // last line of block, inclusive
414
+ };
415
+ if (b.role) e.role = b.role;
416
+ if (b.sections && b.sections.length > 0) e.sections = b.sections.map((s) => ({ kind: s.kind, startLine: b.hrIdx + s.rel + 3 }));
417
+ return e;
418
+ });
419
+ return { lines, index };
420
+ }
421
+
422
+ // ============================================================================
423
+ // Mechanical summary (what replaces the model summary in the session)
424
+ // ============================================================================
425
+
426
+ function toolCallSignature(name: string, args: Record<string, unknown> | undefined): string {
427
+ const parts: string[] = [];
428
+ for (const [k, v] of Object.entries(args ?? {})) {
429
+ let s: string;
430
+ try {
431
+ s = JSON.stringify(v) ?? String(v);
432
+ } catch {
433
+ s = String(v);
434
+ }
435
+ if (s.length > cfg.argSnippetChars) s = `${s.slice(0, cfg.argSnippetChars)}…[+${s.length - cfg.argSnippetChars} chars]`;
436
+ parts.push(`${k}=${s}`);
437
+ }
438
+ return `${name}(${parts.join(", ")})`;
439
+ }
440
+
441
+ function summarizeMessages(messages: AgentMessage[]): string[] {
442
+ // Pair calls with later results in Pi's selected messages only. Never infer
443
+ // outcomes from result text, assistant claims, or another branch/the kept tail.
444
+ const outcomes = new Map<object, "ok" | "error">();
445
+ const pending = new Map<string, { block: object; name: string } | null>();
446
+ for (const msg of messages) {
447
+ const m = msg as unknown as Record<string, any>;
448
+ if (m.role === "assistant") {
449
+ for (const block of m.content ?? []) {
450
+ if (block.type !== "toolCall" || typeof block.id !== "string" || !block.id) continue;
451
+ // Concurrent duplicate IDs cannot be attributed safely. Sequential
452
+ // reuse is fine once the preceding call's result has been consumed.
453
+ pending.set(block.id, pending.has(block.id) ? null : { block, name: block.name });
454
+ }
455
+ } else if (m.role === "toolResult") {
456
+ const call = pending.get(m.toolCallId);
457
+ if (!call || call.name !== m.toolName) continue;
458
+ if (typeof m.isError === "boolean") outcomes.set(call.block, m.isError ? "error" : "ok");
459
+ pending.delete(m.toolCallId);
460
+ }
461
+ }
462
+ const lines: string[] = [];
463
+ for (const msg of messages) {
464
+ const m = msg as unknown as Record<string, any>;
465
+ switch (msg.role) {
466
+ case "user": {
467
+ const { text, images } = textOf(m.content);
468
+ if (text.trim() || images > 0) lines.push(`[User]: ${text}`);
469
+ break;
470
+ }
471
+ case "assistant": {
472
+ let prose = "";
473
+ const calls: string[] = [];
474
+ for (const block of m.content ?? []) {
475
+ if (block.type === "text") prose += (prose ? "\n" : "") + String(block.text ?? "");
476
+ else if (block.type === "toolCall")
477
+ calls.push(`${toolCallSignature(String(block.name), block.arguments)} [${outcomes.get(block) ?? "unknown"}; output removed]`);
478
+ // thinking blocks: removed by design (kept in the session)
479
+ }
480
+ if (prose.trim()) lines.push(`[Assistant]: ${prose.trim()}`);
481
+ if (calls.length > 0) lines.push(`[Assistant tool calls]: ${calls.join("; ")}`);
482
+ break;
483
+ }
484
+ case "toolResult":
485
+ // removed by design (kept in the session)
486
+ break;
487
+ case "bashExecution":
488
+ lines.push(`[BashExecution]: $ ${String(m.command ?? "")} (output removed — use context_lookup)`);
489
+ break;
490
+ case "custom":
491
+ lines.push(`[Custom]: ${textOf(m.content).text}`);
492
+ break;
493
+ case "branchSummary":
494
+ case "compactionSummary":
495
+ lines.push(`[${msg.role === "branchSummary" ? "Branch summary" : "Compaction summary"}]: ${String(m.summary ?? "")}`);
496
+ break;
497
+ default:
498
+ break;
499
+ }
500
+ }
501
+ return lines;
502
+ }
503
+
504
+ const SECTION_HEADER = "### Compacted conversation (oldest first)";
505
+ const SPAN_CLOSE = "</compacted-span>";
506
+ const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
507
+ const SPAN_TRIMMED_ATTR = ' trimmed="true"';
508
+ const BASE_CLOSE = "</compacted-base>";
509
+
510
+ function spanOpen(n: number, compactedAt: string, reason: string, covers?: string): string {
511
+ // covers = [first summarised message, last summarised message]; the span
512
+ // ends at pi's cut point, which is earlier than the compaction time.
513
+ // Spans written before from/to existed render without covers.
514
+ return `<compacted-span n="${n}"${covers ? ` covers="${covers}"` : ""} compacted-at="${compactedAt}" trigger="${reason}">`;
515
+ }
516
+
517
+ /**
518
+ * The base = the most recent compaction entry on the branch that is NOT a
519
+ * mech-compact entry with details.span — i.e. a model-generated summary or a
520
+ * legacy (nested-format) mech checkpoint. Everything before it is covered by
521
+ * its opaque summary text. Spans = mech entries with details.span after the
522
+ * base, oldest first. Spans before the base are deliberately NOT re-rendered
523
+ * (the base is opaque; the session holds the raw history).
524
+ */
525
+ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
526
+ base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
527
+ spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[];
528
+ } {
529
+ const spanDetails = (e: SessionEntry) => {
530
+ if (e.type !== "compaction") return undefined;
531
+ const d = (e as { details?: Record<string, any> }).details;
532
+ if (!d || d.kind !== MECH_KIND || !Array.isArray(d.span?.lines)) return undefined;
533
+ return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown; lines: string[] };
534
+ };
535
+ let baseIdx = -1;
536
+ for (let i = branchEntries.length - 1; i >= 0; i--) {
537
+ if (branchEntries[i].type !== "compaction") continue;
538
+ if (!spanDetails(branchEntries[i])) {
539
+ baseIdx = i;
540
+ break;
541
+ }
542
+ }
543
+ const baseEntry = baseIdx >= 0 ? branchEntries[baseIdx] : null;
544
+ const base = baseEntry
545
+ ? {
546
+ kind: (((baseEntry as { details?: { kind?: string } }).details?.kind === MECH_KIND) as boolean ? "legacy-checkpoint" : "model-summary") as
547
+ | "model-summary"
548
+ | "legacy-checkpoint",
549
+ at: (baseEntry as { timestamp?: string }).timestamp ?? "",
550
+ summary: (baseEntry as { summary?: string }).summary ?? "",
551
+ }
552
+ : null;
553
+ const spans: { at: string; reason: string; from?: string; to?: string; lines: string[] }[] = [];
554
+ for (let i = Math.max(baseIdx + 1, 0); i < branchEntries.length; i++) {
555
+ const sd = spanDetails(branchEntries[i]);
556
+ if (sd)
557
+ spans.push({
558
+ at: String(sd.at ?? (branchEntries[i] as { timestamp?: string }).timestamp ?? ""),
559
+ reason: String(sd.reason ?? "unknown"),
560
+ // from/to are absent on spans written before they existed — render
561
+ // without covers rather than guessing.
562
+ from: typeof sd.from === "string" && sd.from !== "" ? sd.from : undefined,
563
+ to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
564
+ lines: sd.lines,
565
+ });
566
+ }
567
+ return { base, spans };
568
+ }
569
+
570
+ /**
571
+ * Size guard across ordered spans (oldest first): if the total line budget is
572
+ * exceeded, (1) drop the oldest non-user lines, (2) stub each oversized user
573
+ * line at most once in a single forward pass (never re-stub → no loops),
574
+ * (3) drop the oldest remaining lines until under budget. Everything dropped
575
+ * remains in the session.
576
+ */
577
+ function capSpans(spans: string[][], budget: number): string[][] {
578
+ const items: { span: number; line: string }[] = spans.flatMap((lines, span) => lines.map((line) => ({ span, line })));
579
+ let size = items.reduce((a, it) => a + it.line.length + 1, 0);
580
+ const over = () => size > budget;
581
+ const remove = (i: number) => {
582
+ size -= items[i].line.length + 1;
583
+ items.splice(i, 1);
584
+ };
585
+
586
+ // 1) drop oldest non-user lines (flat order = span order = oldest first;
587
+ // terminates: each pass removes a line or advances i)
588
+ for (let i = 0; i < items.length && over(); ) {
589
+ if (items[i].line.startsWith("[User]:")) i++;
590
+ else remove(i);
591
+ }
592
+ // 2) stub user lines, oldest first, each at most once (terminates: single forward pass)
593
+ for (let i = 0; i < items.length && over(); i++) {
594
+ const line = items[i].line;
595
+ if (!line.startsWith("[User]:") || line.length <= 120) continue;
596
+ const stub = `${line.slice(0, 120)}…[truncated +${line.length - 120} chars — use context_lookup]`;
597
+ if (stub.length >= line.length) continue; // stubbing would not shrink it; step 3 drops it
598
+ size += stub.length - line.length;
599
+ items[i] = { ...items[i], line: stub };
600
+ }
601
+ // 3) drop oldest remaining lines until under budget (terminates: removes one per iteration)
602
+ while (over() && items.length > 0) remove(0);
603
+
604
+ return spans.map((_, span) => items.filter((it) => it.span === span).map((it) => it.line));
605
+ }
606
+
607
+ const REORIENT_BLOCK = `**Re-orient before continuing.** Compaction may have removed information needed to follow the project instructions:
608
+ 1. Re-read documents required by the applicable instructions (such as files referenced by AGENTS.md / CLAUDE.md), even if you read them before compaction. Re-acquire any other information needed for the current task that is no longer in context. This means restoring inputs, not repeating completed work: do not redo writes, edits, or other state-changing actions merely because their results were dropped. If needed, recover those results with \`context_lookup\`, or verify current state.
609
+ 2. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
610
+ 3. Re-read any file you are about to modify — do not trust content you only remember from before the compaction.
611
+ 4. **Treat other pre-compaction knowledge as unverified too.** Thinking and tool outputs were removed. Anything you know only from them — or from earlier assistant prose describing them — is a note, not evidence. Before you state it as fact or base a decision on it, re-read the source or ask \`context_lookup\`. If you cannot verify it, say explicitly that it is unverified.
612
+
613
+ **Recovering dropped details.** Information removed from your active context is preserved in the session, including earlier thinking and tool outputs. Prefer \`context_lookup\` with a specific question: a subagent searches the transcript in its own context and returns relevant findings. If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`; follow their pagination instructions for more detail. Do not read or grep raw session JSONL files or old dumps through filesystem tools in this conversation — use these recovery tools instead.`;
614
+
615
+ const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool signatures and file lists do not contain command output, file contents, or rules from read documents; if a claim depends on that removed evidence, use `context_lookup` or re-read the source before relying on it.";
616
+
617
+ async function buildMechanicalSummary(opts: {
618
+ reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
619
+ tokensBefore: number;
620
+ branchEntries: SessionEntry[];
621
+ now: string;
622
+ spanLines: string[]; // this compaction's own span, un-capped
623
+ spanFrom?: string; // ISO timestamp of the first summarised message
624
+ spanTo?: string; // ISO timestamp of the last summarised message
625
+ firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
626
+ readFiles: string[];
627
+ modifiedFiles: string[];
628
+ notify: (msg: string) => void;
629
+ chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
630
+ }): Promise<string | undefined> {
631
+ const { base, spans } = collectBaseAndSpans(opts.branchEntries);
632
+ const allSpans = [...spans, { at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo, lines: opts.spanLines }];
633
+ const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
634
+
635
+ // Size guard: the budget applies to the WHOLE conversation section (base +
636
+ // all spans). The fixed tag overhead is computed exactly (tags are known
637
+ // strings), so the rendered section is guaranteed <= budget. The base block
638
+ // itself is NOT capped — if it alone exceeds the budget, warn.
639
+ const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
640
+ let overhead = SECTION_HEADER.length + 2;
641
+ if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
642
+ overhead += allSpans.reduce(
643
+ (a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
644
+ 0,
645
+ );
646
+ // Closing line: where the verbatim (uncompacted) tail begins. Spans end at
647
+ // pi's cut point, which is earlier than the compaction time — the tail is
648
+ // named by the first kept entry's timestamp (no time if it cannot be found).
649
+ const keptEntry = opts.firstKeptEntryId ? opts.branchEntries.find((e) => e.id === opts.firstKeptEntryId) : undefined;
650
+ const keptTime = (keptEntry as { timestamp?: unknown } | undefined)?.timestamp;
651
+ const closingLine =
652
+ typeof keptTime === "string" && keptTime !== ""
653
+ ? `Conversation from ${keptTime} onward continues verbatim below — it was not compacted.`
654
+ : `Conversation continues verbatim below — it was not compacted.`;
655
+ overhead += closingLine.length + 2;
656
+ const lines = allSpans.map((s) => s.lines);
657
+ const lineChars = lines.reduce((total, span) => total + span.reduce((n, line) => n + line.length + 1, 0), 0);
658
+ const maxChars = await opts.chooseCap({ overhead, lineChars });
659
+ if (maxChars === null) return undefined;
660
+ if (maxChars !== undefined && base && base.summary.length > maxChars)
661
+ opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
662
+ const capped = maxChars === undefined ? lines : capSpans(lines, Math.max(500, maxChars - overhead));
663
+
664
+ const blocks: string[] = [];
665
+ if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
666
+ capped.forEach((lines, i) => {
667
+ const s = allSpans[i];
668
+ const open = spanOpen(i + 1, s.at, s.reason, coversOf(s));
669
+ blocks.push(
670
+ lines.length > 0 ? `${open}\n${lines.join("\n")}\n${SPAN_CLOSE}` : `${open.slice(0, -1)}${SPAN_TRIMMED_ATTR}>\n${SPAN_TRIMMED_NOTE}\n${SPAN_CLOSE}`,
671
+ );
672
+ });
673
+
674
+ const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
675
+ const parts: string[] = [];
676
+ parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
677
+ if (base?.kind === "model-summary") {
678
+ parts.push(MIXED_CONTEXT_WARNING);
679
+ opts.notify(MIXED_CONTEXT_WARNING);
680
+ }
681
+ parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
682
+ parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming; tool calls are kept as one-line signatures (arguments truncated). Assistant thinking and tool outputs are removed. Retained prose is a record of what was said, not verification of its claims.");
683
+ parts.push("- Tool status: ok = result not flagged as an error; error = result flagged as an error; unknown = no safely matched result/status. Output content is removed in all cases. ok does not prove a command or tests passed. Calls without a status in older spans have unknown outcomes.");
684
+ parts.push(
685
+ "- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that; everything after the last span is uncompacted.",
686
+ );
687
+ parts.push("- The full transcript before this point is kept in the session; use `context_lookup` to recover details (including thinking and tool outputs).");
688
+ parts.push("");
689
+ parts.push(REORIENT_BLOCK);
690
+ parts.push("");
691
+ parts.push(SECTION_HEADER);
692
+ parts.push("");
693
+ parts.push(blocks.length > 0 ? blocks.join("\n\n") : "(no user or assistant prose in these spans — use context_lookup)");
694
+ // The file lists describe the compacted spans, so they belong above the
695
+ // verbatim boundary line. That closing line is the LAST line of the
696
+ // checkpoint; everything after it is pi's retained verbatim tail.
697
+ const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
698
+ if (hasFileLists) parts.push("");
699
+ if (opts.readFiles.length > 0)
700
+ parts.push(`<read-files note="read before compaction; content removed — re-read or use context_lookup">\n${opts.readFiles.map((file) => `${file} (content removed)`).join("\n")}\n</read-files>`);
701
+ if (opts.modifiedFiles.length > 0)
702
+ parts.push(`<modified-files note="modified before compaction; current contents NOT in context">\n${opts.modifiedFiles.join("\n")}\n</modified-files>`);
703
+ parts.push("");
704
+ parts.push(EVIDENCE_BOUNDARY_RULE);
705
+ parts.push("");
706
+ parts.push(closingLine);
707
+
708
+ return parts.join("\n");
709
+ }
710
+
711
+ // ============================================================================
712
+ // context_lookup subagent: searches the transcript in its own context
713
+ // ============================================================================
714
+
715
+ interface Transcript {
716
+ /** Logical transcript name for subagent citations; never a filesystem path. */
717
+ name: string;
718
+ file: string;
719
+ /** Rendered raw branch, with physical lines and an authoritative entry index. */
720
+ lines: string[];
721
+ index: TranscriptIndexEntry[];
722
+ }
723
+
724
+ /** Entry/section owning a physical line. Only the renderer index is trusted:
725
+ * ENTRY-like text and rules inside tool output cannot spoof attribution. */
726
+ function entryAt(lines: string[], idx: number, index: TranscriptIndexEntry[]): { id: string; header: string; section?: string } | undefined {
727
+ const lineNo = idx + 1;
728
+ let lo = 0;
729
+ let hi = index.length - 1;
730
+ let found = -1;
731
+ while (lo <= hi) {
732
+ const mid = (lo + hi) >> 1;
733
+ if (index[mid].startLine <= lineNo) {
734
+ found = mid;
735
+ lo = mid + 1;
736
+ } else {
737
+ hi = mid - 1;
738
+ }
739
+ }
740
+ if (found < 0) return undefined;
741
+ const e = index[found];
742
+ if (lineNo > e.endLine) return undefined;
743
+ let section: string | undefined;
744
+ for (const s of e.sections ?? []) if (s.startLine <= lineNo) section = s.kind;
745
+ return { id: e.id, header: lines[e.startLine - 1] ?? "", section };
746
+ }
747
+
748
+ // Keep page boundaries between Unicode characters, never inside a surrogate pair.
749
+ function characterBoundary(text: string, start: number, end: number): number {
750
+ const prev = text.charCodeAt(end - 1), next = text.charCodeAt(end);
751
+ return end > start && prev >= 0xd800 && prev <= 0xdbff && next >= 0xdc00 && next <= 0xdfff ? end - 1 : end;
752
+ }
753
+
754
+ // An entry-id boundary pins a paginated listing/search while new tool calls
755
+ // and results append to the branch. It is not a snapshot or a filesystem path.
756
+ function transcriptWindow(transcripts: Transcript[], file?: string, throughEntry?: string): Transcript[] {
757
+ const targets = file ? transcripts.filter((d) => d.name === file) : transcripts;
758
+ if (!throughEntry) return targets;
759
+ const bounded: Transcript[] = [];
760
+ for (const d of targets) {
761
+ const at = d.index.findIndex((e) => e.id === throughEntry);
762
+ if (at >= 0) bounded.push({ ...d, lines: d.lines.slice(0, d.index[at].endLine), index: d.index.slice(0, at + 1) });
763
+ }
764
+ if (!bounded.length) throw new Error(`Pagination boundary ENTRY "${throughEntry}" is not on this transcript branch. Restart at offset=0 (and charOffset=0 for grep) without throughEntry.`);
765
+ return bounded;
766
+ }
767
+
768
+ // Offsets count JavaScript string characters (UTF-16 code units), not tokens.
769
+ // Pagination never discards a suffix: even a single enormous physical line is
770
+ // accessible. Only response payloads are capped; small status/cursor notes are extra.
771
+ interface PageCursor { offset: number; charOffset?: number; throughEntry?: string }
772
+ type OnContinuation = (cursor: PageCursor) => void;
773
+
774
+ function pageText(text: string, opts: { offset?: number; maxChars: number; maxLines?: number; attribution: string; continuation?: string; onContinuation?: OnContinuation }): string {
775
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
776
+ if (offset >= text.length) return `No more content at offset=${offset} (${text.length} total characters).`;
777
+ let end = Math.min(text.length, offset + opts.maxChars);
778
+ if (opts.maxLines !== undefined) {
779
+ let lines = 0;
780
+ for (let i = offset; i < end; i++) {
781
+ if (text[i] === "\n" && ++lines >= opts.maxLines) { end = i + 1; break; }
782
+ }
783
+ }
784
+ end = characterBoundary(text, offset, end);
785
+ const prefix = offset > 0 ? `[Continuation: ${truncateHead(opts.attribution, 1_000)}; offset=${offset}]\n` : "";
786
+ const body = text.slice(offset, end);
787
+ const notice = end < text.length
788
+ ? `\n[Page limited: characters ${offset}–${end - 1} of ${text.length}; ${text.length - end} characters remain. Continue with the same parameters and offset=${end}${opts.continuation ?? ""}.]`
789
+ : "";
790
+ if (end < text.length && end > offset) opts.onContinuation?.({ offset: end });
791
+ return prefix + body + notice;
792
+ }
793
+
794
+ function listEntries(transcripts: Transcript[], opts: { file?: string; offset?: number; throughEntry?: string } = {}, onContinuation?: OnContinuation): string {
795
+ const targets = transcriptWindow(transcripts, opts.file, opts.throughEntry);
796
+ const throughEntry = targets.length === 1 ? targets[0].index.at(-1)?.id : undefined;
797
+ const parts: string[] = [];
798
+ for (const d of targets) {
799
+ const rows = d.index.map((e) => {
800
+ const header = d.lines[e.startLine - 1] ?? "";
801
+ const next = d.lines[e.startLine] ?? "";
802
+ const preview = next.trim() !== "" && !next.startsWith(HR) ? ` ${next.trim().slice(0, 90)}` : "";
803
+ return `${header}${preview}`;
804
+ });
805
+ parts.push(`### ${d.name} (${rows.length} entries)\n${rows.join("\n")}`);
806
+ }
807
+ return parts.length ? pageText(parts.join("\n\n"), {
808
+ offset: opts.offset, maxChars: cfg.listMaxChars, attribution: `entry listing for ${targets.map((t) => t.name).join(", ")}`,
809
+ continuation: throughEntry ? `, throughEntry=${JSON.stringify(throughEntry)}` : "",
810
+ onContinuation: (cursor) => onContinuation?.({ ...cursor, throughEntry }),
811
+ }) : "(no transcript entries)";
812
+ }
813
+
814
+ interface GrepOptions { pattern: string; file?: string; before?: number; after?: number; maxMatches?: number; offset?: number; charOffset?: number; throughEntry?: string }
815
+ function grepTranscript(transcripts: Transcript[], opts: GrepOptions, onContinuation?: OnContinuation): string {
816
+ const targets = transcriptWindow(transcripts, opts.file, opts.throughEntry);
817
+ const throughEntry = targets.length === 1 ? targets[0].index.at(-1)?.id : undefined;
818
+ let re: RegExp;
819
+ try {
820
+ re = new RegExp(opts.pattern, "i");
821
+ } catch {
822
+ re = new RegExp(opts.pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "i");
823
+ }
824
+ const before = Math.max(0, Math.floor(opts.before ?? 2));
825
+ const after = Math.max(0, Math.floor(opts.after ?? 6));
826
+ const maxMatches = Math.max(1, Math.floor(opts.maxMatches ?? 15));
827
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
828
+ const startCharOffset = Math.max(0, Math.floor(opts.charOffset ?? 0));
829
+ let charOffset = startCharOffset;
830
+ const hits: { transcript: Transcript; line: number }[] = [];
831
+ for (const d of targets) {
832
+ for (let i = 0; i < d.lines.length; i++) if (re.test(d.lines[i])) hits.push({ transcript: d, line: i });
833
+ }
834
+ if (hits.length === 0) return `No matches for /${opts.pattern}/ in ${targets.map((t) => t.name).join(", ") || "(no transcripts)"}.`;
835
+ if (offset >= hits.length) return `No more matches at offset=${offset} (${hits.length} total matches).`;
836
+
837
+ const out: string[] = [];
838
+ let size = 0;
839
+ let next = offset;
840
+ for (; next < hits.length && next < offset + maxMatches; next++) {
841
+ const { transcript: d, line: i } = hits[next];
842
+ const entry = entryAt(d.lines, i, d.index);
843
+ const header = truncateHead(`--- ${d.name} line ${i + 1}${entry ? ` << ${entry.header}${entry.section ? ` [${entry.section}]` : ""}` : ""}`, 1_000);
844
+ const from = Math.max(0, i - before);
845
+ const to = Math.min(d.lines.length - 1, i + after);
846
+ const body = d.lines.slice(from, to + 1).map((l, n) => (n + from === i ? `>> ${l}` : ` ${l}`)).join("\n");
847
+ if (charOffset >= body.length) return `Invalid charOffset=${charOffset} for match offset=${next}: the current rendered context has only ${body.length} characters. charOffset is valid only with the same pattern, file, before/after, and throughEntry as the page that issued it. Restart this match at offset=${next} with charOffset=0, keeping your intended search/context parameters.`;
848
+ const prefix = `${header}${charOffset ? ` [match offset=${next}, charOffset=${charOffset}]` : ""}\n`;
849
+ const available = cfg.grepMaxChars - size - prefix.length - (out.length ? 2 : 0);
850
+ if (available <= 0) break;
851
+ const end = characterBoundary(body, charOffset, Math.min(body.length, charOffset + available));
852
+ if (end === charOffset) break;
853
+ const chunk = prefix + body.slice(charOffset, end);
854
+ out.push(chunk);
855
+ size += chunk.length + (out.length > 1 ? 2 : 0);
856
+ if (end < body.length) { charOffset = end; break; }
857
+ charOffset = 0;
858
+ }
859
+ const notice = next < hits.length
860
+ ? `\n[Page limited: ${hits.length} total matches; ${hits.length - next} matches remain${charOffset ? " (including the partially shown match)" : ""}. Continue with the same parameters and offset=${next}, charOffset=${charOffset}${throughEntry ? `, throughEntry=${JSON.stringify(throughEntry)}` : ""}.]`
861
+ : "";
862
+ if (next < hits.length && (next > offset || charOffset > startCharOffset)) {
863
+ onContinuation?.({ offset: next, charOffset, throughEntry });
864
+ }
865
+ return out.join("\n\n") + notice;
866
+ }
867
+
868
+ function showEntry(transcripts: Transcript[], opts: { id: string; file?: string; maxLines?: number; offset?: number }, onContinuation?: OnContinuation): string {
869
+ const targets = opts.file ? transcripts.filter((d) => d.name === opts.file) : transcripts;
870
+ const out: string[] = [];
871
+ const headers: string[] = [];
872
+ for (const d of targets) {
873
+ const e = d.index.find((x) => x.id === opts.id);
874
+ if (!e) continue;
875
+ const block = d.lines.slice(e.startLine - 2, e.endLine); // includes the rule before the header
876
+ out.push(`### ${d.name}\n${block.join("\n")}`);
877
+ headers.push(`${d.name}: ${d.lines[e.startLine - 1]}`);
878
+ }
879
+ return out.length ? pageText(out.join("\n\n"), {
880
+ offset: opts.offset, maxChars: cfg.showEntryMaxChars,
881
+ maxLines: Math.max(1, Math.floor(opts.maxLines ?? 400)), attribution: headers.join("; "), onContinuation,
882
+ }) : `No entry with id "${opts.id}" found.`;
883
+ }
884
+
885
+ // Identical paging parameters in the subagent and direct tools; only the
886
+ // subagent accepts a logical transcript name (not a filesystem path).
887
+ const OFFSET_FIELD = Type.Optional(Type.Integer({ minimum: 0, description: "Character offset (UTF-16 units, default 0). Use the next offset reported by the previous page." }));
888
+ const FILE_FIELD = Type.Optional(Type.String({ description: "Logical transcript name. Omit for all." }));
889
+ const THROUGH_ENTRY_FIELD = Type.Optional(Type.String({ description: "Last ENTRY id included in this paginated listing/search. Keep the reported throughEntry on subsequent pages to exclude newly appended calls/results; omit to start a fresh search." }));
890
+ const LIST_FIELDS = { offset: OFFSET_FIELD, throughEntry: THROUGH_ENTRY_FIELD };
891
+ const GREP_FIELDS = {
892
+ pattern: Type.String({ description: "JS regex, case-insensitive" }),
893
+ before: Type.Optional(Type.Integer({ minimum: 0, description: "Context lines before (default 2)" })),
894
+ after: Type.Optional(Type.Integer({ minimum: 0, description: "Context lines after (default 6)" })),
895
+ maxMatches: Type.Optional(Type.Integer({ minimum: 1, description: "Max matches per page (default 15); character limit also applies" })),
896
+ offset: Type.Optional(Type.Integer({ minimum: 0, description: "Match offset (0-based, default 0). Use the next offset reported by the previous page." })),
897
+ charOffset: Type.Optional(Type.Integer({ minimum: 0, description: "Character offset within that match's context (default 0). Keep pattern, file, before/after and throughEntry unchanged when continuing; otherwise restart the match with charOffset=0." })),
898
+ throughEntry: THROUGH_ENTRY_FIELD,
899
+ };
900
+ const SHOW_FIELDS = {
901
+ id: Type.String({ description: "Entry id" }),
902
+ maxLines: Type.Optional(Type.Integer({ minimum: 1, description: "Max lines per page (default 400); character limit also applies" })),
903
+ offset: OFFSET_FIELD,
904
+ };
905
+
906
+ const LOOKUP_FALLBACK_NOTE =
907
+ "If more detail is needed for this query, use context_list_entries, context_grep, or context_show_entry rather than immediately repeating context_lookup.";
908
+
909
+ // Append outside the truncated findings so the next-step guidance survives
910
+ // even a long write-up. Normal successful answers remain unchanged.
911
+ function lookupPartialFindings(text: string, marker: string): string {
912
+ const status = truncateHead(marker, 1_000); // Provider error messages can be large too.
913
+ const budget = cfg.lookupAnswerMaxChars - status.length - LOOKUP_FALLBACK_NOTE.length - 2;
914
+ return `${truncateHead(text, budget)}\n${status}\n${LOOKUP_FALLBACK_NOTE}`;
915
+ }
916
+
917
+ const LOOKUP_WRITEUP_PROMPT =
918
+ "Search is finished; no further tool calls are allowed. Report what you found so far: the facts you confirmed (with ENTRY ids), " +
919
+ "what you couldn't find, and where you'd look next.";
920
+
921
+ const LOOKUP_SYSTEM_PROMPT = `You are a context-lookup subagent for a coding agent whose main context was compacted by verbatim compaction. The full pre-compaction transcript — including assistant thinking blocks and complete tool outputs that were REMOVED from the main context — is in the transcript files named in the request.
922
+
923
+ You have three tools:
924
+ - list_entries: paginated overview of entries (id, role, timestamp, preview)
925
+ - grep: paginated transcript search; matches come with surrounding lines and authoritative ENTRY attribution
926
+ - show_entry: retrieve an entry by id in bounded pages
927
+
928
+ Search tools bound each response, not the underlying history. A partial page is not the entire evidence, but you do NOT need to exhaust every page. Follow continuation parameters only when omitted content is needed to answer the question, keeping all other search/context parameters unchanged. Narrow an overly broad search rather than paging through irrelevant matches. Stop paging once you have sufficient relevant evidence.
929
+
930
+ Work efficiently: start with list_entries if you don't know where to look, then grep for concrete terms, then show_entry for exact content. When you are confident you have what is needed, stop calling tools and output your final answer as plain text.
931
+
932
+ Final answer rules (your final message is the ONLY text the main agent sees):
933
+ - Return only the important findings. Do not narrate your search process.
934
+ - Quote exact error messages, paths, values, and code verbatim where they matter.
935
+ - Cite the ENTRY id (and file) for each finding so the main agent can verify.
936
+ - If the transcript does not contain the answer, say exactly what is missing.
937
+
938
+ Provenance rules — label each finding with its source type:
939
+ - "user instruction" — what the user asked, pasted, or confirmed
940
+ - "observed tool output" — what a tool actually returned at the time (ground truth)
941
+ - "reasoning at the time (thinking)" — what the agent believed or hypothesized then; NOT verified fact
942
+ Grep attributions include a section tag like [thinking] / [text] / [toolCall]. When a finding rests on old thinking, say explicitly that it was reasoning-at-the-time, so the main agent does not treat it as established fact.`;
943
+
944
+ // Canonical effective parameters identify a specific issued page, not merely
945
+ // a positive offset. Defaults may be made explicit without changing a query.
946
+ function lookupPageKey(name: string, args: Record<string, any>): string | undefined {
947
+ const number = (key: string, fallback: number, min = 0): number | undefined => {
948
+ const value = args[key] ?? fallback;
949
+ return Number.isSafeInteger(value) && value >= min ? value : undefined;
950
+ };
951
+ const string = (key: string): string | null | undefined => {
952
+ const value = args[key];
953
+ return value == null ? null : typeof value === "string" ? value : undefined;
954
+ };
955
+ let fields: unknown[];
956
+ switch (name) {
957
+ case "list_entries":
958
+ fields = [string("file"), number("offset", 0), string("throughEntry")];
959
+ break;
960
+ case "grep":
961
+ fields = [typeof args.pattern === "string" ? args.pattern : undefined, string("file"),
962
+ number("before", 2), number("after", 6), number("maxMatches", 15, 1),
963
+ number("offset", 0), number("charOffset", 0), string("throughEntry")];
964
+ break;
965
+ case "show_entry":
966
+ fields = [typeof args.id === "string" ? args.id : undefined, string("file"),
967
+ number("maxLines", 400, 1), number("offset", 0)];
968
+ break;
969
+ default:
970
+ return undefined;
971
+ }
972
+ return fields.includes(undefined) ? undefined : JSON.stringify([name, ...fields]);
973
+ }
974
+
975
+ async function runLookupSubagent(opts: {
976
+ question: string;
977
+ transcripts: Transcript[];
978
+ model: Model;
979
+ registry: ModelRegistry;
980
+ signal: AbortSignal | undefined;
981
+ }): Promise<string> {
982
+ const toc = truncateHead(listEntries(opts.transcripts).split("\n").slice(0, 60).join("\n"), 4_000);
983
+
984
+ const tools: AiTool[] = [
985
+ {
986
+ name: "list_entries",
987
+ description: "List ENTRY headers and previews in pages of up to 12000 payload characters, plus cursor notes. If additional previews are needed, follow all reported continuation parameters (offset and throughEntry). Optional file restricts to a logical transcript name.",
988
+ parameters: Type.Object({ ...LIST_FIELDS, file: FILE_FIELD }),
989
+ },
990
+ {
991
+ name: "grep",
992
+ description: "Regex-search transcript lines with surrounding context and authoritative entry attribution. Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) only if omitted matches/context are needed. pattern is a JS regex (case-insensitive).",
993
+ parameters: Type.Object({ ...GREP_FIELDS, file: FILE_FIELD }),
994
+ },
995
+ {
996
+ name: "show_entry",
997
+ description: "Retrieve an indexed entry by ENTRY id in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset only if omitted content is needed; a page may not contain the entire entry.",
998
+ parameters: Type.Object({ ...SHOW_FIELDS, file: FILE_FIELD }),
999
+ },
1000
+ ];
1001
+
1002
+ const messages: AiMessage[] = [
1003
+ {
1004
+ role: "user",
1005
+ content:
1006
+ `Question: ${opts.question}\n\n` +
1007
+ `Transcript files (full raw session branch; ENTRY blocks are anchored by entry id):\n` +
1008
+ opts.transcripts.map((d) => `- ${d.file}`).join("\n") +
1009
+ `\n\nTranscript overview (first entries; list_entries can retrieve additional previews if needed):\n${toc}`,
1010
+ timestamp: Date.now(),
1011
+ },
1012
+ ];
1013
+
1014
+ // Ephemeral admission state only: no telemetry, saved trace, or cursor
1015
+ // parsing from untrusted transcript text. Each issued cursor is single-use.
1016
+ const continuations = new Set<string>();
1017
+ const dispatch = (name: string, args: Record<string, any>): string => {
1018
+ const issued: OnContinuation = (cursor) => {
1019
+ const key = lookupPageKey(name, { ...args, ...cursor });
1020
+ if (key) continuations.add(key);
1021
+ };
1022
+ try {
1023
+ switch (name) {
1024
+ case "list_entries":
1025
+ return listEntries(opts.transcripts, args, issued);
1026
+ case "grep":
1027
+ return grepTranscript(opts.transcripts, args, issued);
1028
+ case "show_entry":
1029
+ return showEntry(opts.transcripts, args, issued);
1030
+ default:
1031
+ return `Unknown tool: ${name}`;
1032
+ }
1033
+ } catch (err) {
1034
+ return `Tool error: ${errMsg(err)}`;
1035
+ }
1036
+ };
1037
+
1038
+ const sessionId = uuidv7();
1039
+ // Continuations do not spend the substantive-search budget, but still cost
1040
+ // inference. Bound ALL search-phase model calls, plus one final write-up.
1041
+ const maxModelCalls = Math.min(Number.MAX_SAFE_INTEGER, cfg.lookupTurns * 3);
1042
+ const searchLimit = `${cfg.lookupTurns}-turn limit`;
1043
+ let limit = `${maxModelCalls}-call total limit`;
1044
+ let searchTurns = 0;
1045
+ let pagingOnlyNotified = false;
1046
+ let lastText = "";
1047
+ for (let turn = 0; turn < maxModelCalls; turn++) {
1048
+ if (searchTurns >= cfg.lookupTurns) {
1049
+ if (continuations.size === 0) { limit = searchLimit; break; }
1050
+ if (!pagingOnlyNotified) {
1051
+ messages.push({ role: "user", content: "The substantive search-turn budget is exhausted. Only follow previously issued continuation pages if needed, or answer now. Do not start new searches.", timestamp: Date.now() });
1052
+ pagingOnlyNotified = true;
1053
+ }
1054
+ }
1055
+ const resp = await opts.registry.complete(
1056
+ opts.model,
1057
+ normalizeContext({ systemPrompt: LOOKUP_SYSTEM_PROMPT, messages, tools }),
1058
+ { signal: opts.signal, sessionId, maxTokens: 4096 },
1059
+ );
1060
+ if (resp.stopReason === "aborted") return "(lookup subagent aborted)";
1061
+ if (resp.stopReason === "error") return `(lookup subagent error: ${resp.errorMessage ?? "unknown"})`;
1062
+
1063
+ const toolCalls = resp.content.filter((b) => b.type === "toolCall");
1064
+ const text = contentText(resp.content);
1065
+ if (text) lastText = text;
1066
+
1067
+ if (toolCalls.length === 0) {
1068
+ return truncateHead(text || "(subagent returned no answer)", cfg.lookupAnswerMaxChars);
1069
+ }
1070
+
1071
+ // Check the whole batch against cursors issued BEFORE this response.
1072
+ // New queries, changed parameters, invented/replayed cursors and duplicate
1073
+ // continuations consume a search turn, even alongside a valid continuation.
1074
+ const available = new Set(continuations);
1075
+ const keys = toolCalls.map((call) => lookupPageKey(String(call.name), (call.arguments ?? {}) as Record<string, any>));
1076
+ const continuationOnly = keys.every((key) => key !== undefined && available.delete(key));
1077
+ if (!continuationOnly) {
1078
+ if (searchTurns >= cfg.lookupTurns) { limit = searchLimit; break; }
1079
+ searchTurns++;
1080
+ }
1081
+ // Consume before dispatch, so a sibling cannot consume a newly issued page.
1082
+ for (const key of keys) if (key) continuations.delete(key);
1083
+ messages.push(resp);
1084
+ for (const call of toolCalls) {
1085
+ const args = (call.arguments ?? {}) as Record<string, any>;
1086
+ const result = dispatch(String(call.name), args);
1087
+ messages.push({
1088
+ role: "toolResult",
1089
+ toolCallId: call.id,
1090
+ toolName: String(call.name),
1091
+ content: [{ type: "text", text: result }],
1092
+ isError: false,
1093
+ timestamp: Date.now(),
1094
+ });
1095
+ }
1096
+ }
1097
+
1098
+ // Either budget is exhausted: one extra tool-free write-up still returns
1099
+ // usable partial findings without extending searching or paging indefinitely.
1100
+ messages.push({ role: "user", content: LOOKUP_WRITEUP_PROMPT, timestamp: Date.now() });
1101
+ const marker = `[subagent reached the ${limit}; this is its write-up of partial findings]`;
1102
+ let writeupError = "";
1103
+ try {
1104
+ const resp = await opts.registry.complete(
1105
+ opts.model,
1106
+ normalizeContext({ systemPrompt: LOOKUP_SYSTEM_PROMPT, messages }),
1107
+ { signal: opts.signal, sessionId, maxTokens: 4096 },
1108
+ );
1109
+ const text = resp.stopReason === "aborted" || resp.stopReason === "error" ? "" : contentText(resp.content);
1110
+ if (text) return lookupPartialFindings(text, marker);
1111
+ } catch (err) {
1112
+ writeupError = errMsg(err);
1113
+ }
1114
+ const why = writeupError ? `; write-up failed: ${writeupError}` : "";
1115
+ return lookupPartialFindings(lastText, `[subagent reached the ${limit}; findings may be incomplete${why}]`);
1116
+ }
1117
+
1118
+ // ============================================================================
1119
+ // Session-backed transcript (rendered only when a recovery tool is called)
1120
+ // ============================================================================
1121
+
1122
+ function sessionTranscript(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }): Transcript {
1123
+ const override = process.env.MECH_COMPACT_LOOKUP_SESSION_FILE?.trim();
1124
+ let entries: SessionEntry[];
1125
+ if (override) {
1126
+ // Fail closed: never silently search the pruned fork when an override is
1127
+ // misconfigured. Guard open() because pi initializes empty/missing files.
1128
+ if (!path.isAbsolute(override)) throw new Error("MECH_COMPACT_LOOKUP_SESSION_FILE must be an absolute path.");
1129
+ const stat = fs.statSync(override);
1130
+ if (!stat.isFile() || stat.size === 0) throw new Error("MECH_COMPACT_LOOKUP_SESSION_FILE must name a non-empty session JSONL file.");
1131
+ entries = SessionManager.open(override).getBranch();
1132
+ } else {
1133
+ // getBranch() is raw history, unlike buildSessionContext(): compaction
1134
+ // and context edits never remove earlier thinking or tool results here.
1135
+ entries = ctx.sessionManager.getBranch();
1136
+ }
1137
+ const { lines, index } = branchToTranscript(entries);
1138
+ return { name: "session", file: "session", lines, index };
1139
+ }
1140
+
1141
+ // ============================================================================
1142
+ // Main-agent fallback: the same transcript search functions as the subagent
1143
+ // ============================================================================
1144
+
1145
+ const FALLBACK_TOOL_NAMES = new Set(["context_list_entries", "context_grep", "context_show_entry"]);
1146
+
1147
+ /** Count prior lookup attempts since the last user/ordinary-work/bash boundary.
1148
+ * Fallback results, text, and thinking neither increase nor reset the count. Deduplicate call/result ids, and include
1149
+ * earlier siblings in the current assistant message even before results exist:
1150
+ * two parallel lookups cannot both claim the first slot. Later siblings are
1151
+ * excluded. Raw branch state follows reload, resume, compaction, and forks. */
1152
+ function consecutiveLookups(ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, toolCallId: string): number {
1153
+ const entries = ctx.sessionManager.getBranch();
1154
+ const calls = new Set<string>();
1155
+ for (let i = entries.length - 1; i >= 0; i--) {
1156
+ const e = entries[i];
1157
+ if (e.type !== "message") continue;
1158
+ const m = e.message;
1159
+ if (m.role === "user" || m.role === "bashExecution") break;
1160
+ if (m.role === "toolResult") {
1161
+ if (FALLBACK_TOOL_NAMES.has(m.toolName)) continue;
1162
+ if (m.toolName !== "context_lookup") break;
1163
+ calls.add(m.toolCallId);
1164
+ } else if (m.role === "assistant") {
1165
+ for (const b of m.content) {
1166
+ if (b.type !== "toolCall") continue;
1167
+ if (b.id === toolCallId) break;
1168
+ if (b.name === "context_lookup") calls.add(b.id);
1169
+ }
1170
+ }
1171
+ }
1172
+ return calls.size;
1173
+ }
1174
+
1175
+ function registerDirectTools(pi: ExtensionAPI): void {
1176
+ const pre = "Fallback after context_lookup, when its findings are incomplete: ";
1177
+ const run = (ctx: { sessionManager: { getBranch: () => SessionEntry[] } }, f: (t: Transcript[]) => string) => {
1178
+ try {
1179
+ const transcript = sessionTranscript(ctx);
1180
+ if (transcript.index.length === 0) return { content: [{ type: "text" as const, text: "No entries found on the session branch." }], details: undefined };
1181
+ return { content: [{ type: "text" as const, text: f([transcript]) }], details: undefined };
1182
+ } catch (err) {
1183
+ return { content: [{ type: "text" as const, text: `Tool error: ${errMsg(err)}` }], details: undefined };
1184
+ }
1185
+ };
1186
+ pi.registerTool({
1187
+ name: "context_list_entries",
1188
+ label: "Context: list entries",
1189
+ description: pre + "List raw session ENTRY headers and previews, including compacted entries, in pages of up to 12000 payload characters, plus cursor notes. Follow all reported continuation parameters (offset and throughEntry).",
1190
+ promptSnippet: "Fallback: list session entries when subagent findings are incomplete",
1191
+ parameters: Type.Object(LIST_FIELDS),
1192
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1193
+ return run(ctx, (t) => listEntries(t, params));
1194
+ },
1195
+ });
1196
+ pi.registerTool({
1197
+ name: "context_grep",
1198
+ label: "Context: grep",
1199
+ description: pre + "Regex-search the full raw session branch, including compacted thinking and tool outputs, with surrounding lines and authoritative entry attribution. pattern is a JS regex (case-insensitive). Up to 12000 payload characters per page, plus cursor notes. Follow all reported continuation parameters (offset, charOffset, throughEntry) for remaining matches or oversized lines. Historical thinking is not verified fact.",
1200
+ promptSnippet: "Fallback: search session evidence when subagent findings are incomplete",
1201
+ parameters: Type.Object(GREP_FIELDS),
1202
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1203
+ return run(ctx, (t) => grepTranscript(t, params));
1204
+ },
1205
+ });
1206
+ pi.registerTool({
1207
+ name: "context_show_entry",
1208
+ label: "Context: show entry",
1209
+ description: pre + "Retrieve an indexed session entry by ENTRY id (from context_list_entries or context_grep) in pages of up to 24000 payload characters and maxLines lines, plus attribution/cursor notes. Follow the reported offset for the rest; a page may not contain the entire entry.",
1210
+ promptSnippet: "Fallback: retrieve session entry pages when subagent findings are incomplete",
1211
+ parameters: Type.Object(SHOW_FIELDS),
1212
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1213
+ return run(ctx, (t) => showEntry(t, params));
1214
+ },
1215
+ });
1216
+ }
1217
+
1218
+ // ============================================================================
1219
+ // Extension
1220
+ // ============================================================================
1221
+
1222
+ export default function (pi: ExtensionAPI) {
1223
+ // Method selection never changes Pi's auto-compaction enabled setting.
1224
+ pi.registerCommand("compaction-method", {
1225
+ description: "Show or set the session compaction method: verbatim|summary (manual and automatic)",
1226
+ getArgumentCompletions: (prefix) => ["verbatim", "summary"]
1227
+ .filter((method) => method.startsWith(prefix))
1228
+ .map((method) => ({ value: method, label: method })),
1229
+ handler: async (args, ctx) => {
1230
+ const requested = args.trim();
1231
+ if (requested && requested !== "verbatim" && requested !== "summary") {
1232
+ ctx.ui.notify("Usage: /compaction-method [verbatim|summary]", "error");
1233
+ return;
1234
+ }
1235
+ const entries = ctx.sessionManager.getBranch();
1236
+ const previous = compactionMethod(entries);
1237
+ const method = requested || previous;
1238
+ const changed = method !== previous;
1239
+ if (changed) pi.appendEntry(METHOD_ENTRY, { method });
1240
+ ctx.ui.notify(`Compaction method: ${method} (manual, automatic, and overflow recovery).`, "info");
1241
+ if (changed && method === "summary") ctx.ui.notify(SUMMARY_COMPACTION_WARNING, "warning");
1242
+ else if (changed && collectBaseAndSpans(entries).base?.kind === "model-summary") ctx.ui.notify(MIXED_CONTEXT_WARNING, "warning");
1243
+ },
1244
+ });
1245
+
1246
+ pi.registerCommand("cap-compaction", {
1247
+ description: "Show or set verbatim compaction cap: on|off|warn [80000c|20000t|25%]",
1248
+ getArgumentCompletions: (prefix) => {
1249
+ const mode = /^(on|off|warn)\s/.exec(prefix)?.[1];
1250
+ const values = mode ? ["80000c", "20000t", "25%"].map((budget) => `${mode} ${budget}`)
1251
+ : ["on", "off", "warn", "80000c", "20000t", "25%"];
1252
+ return values.filter((value) => value.startsWith(prefix)).map((value) => ({ value, label: value }));
1253
+ },
1254
+ handler: async (args, ctx) => {
1255
+ const previous = capSettings(ctx.sessionManager.getBranch());
1256
+ const words = args.trim().split(/\s+/).filter(Boolean);
1257
+ const mode = ["on", "off", "warn"].includes(words[0]) ? words.shift() as CapMode : previous.mode;
1258
+ const budget = words.length === 0 ? previous.budget : words.length === 1 ? parseCapBudget(words[0]) : undefined;
1259
+ if (!budget) {
1260
+ ctx.ui.notify("Usage: /cap-compaction [on|off|warn] [<chars>c|<estimated tokens>t|<percent>%]; percentages must be >0 and <=100.", "error");
1261
+ return;
1262
+ }
1263
+ const next = { mode, budget };
1264
+ persistCap(pi, previous, next);
1265
+ ctx.ui.notify(`${capDescription(next, ctx.model?.contextWindow)} Applies only to verbatim compaction.`, "info");
1266
+ },
1267
+ });
1268
+
1269
+ pi.on("session_start", (_event, ctx) => {
1270
+ const entries = ctx.sessionManager.getBranch();
1271
+ if (compactionMethod(entries) === "verbatim" && collectBaseAndSpans(entries).base?.kind === "model-summary") {
1272
+ ctx.ui.notify(MIXED_CONTEXT_WARNING, "warning");
1273
+ }
1274
+
1275
+ // Amend the built-in command's autocomplete description, not its handler.
1276
+ // Older Pi versions without this API keep their original description.
1277
+ if (ctx.mode !== "tui" || typeof ctx.ui.addAutocompleteProvider !== "function") return;
1278
+ ctx.ui.addAutocompleteProvider((current) => ({
1279
+ get triggerCharacters() { return current.triggerCharacters; },
1280
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
1281
+ const suggestions = await current.getSuggestions(lines, cursorLine, cursorCol, options);
1282
+ if (!suggestions || !/^\/\S*$/.test(suggestions.prefix)) return suggestions;
1283
+ const method = compactionMethod(ctx.sessionManager.getBranch());
1284
+ return {
1285
+ ...suggestions,
1286
+ items: suggestions.items.map((item) => item.value === "compact"
1287
+ ? { ...item, description: method === "verbatim"
1288
+ ? "Manually compact with transparent-compact"
1289
+ : "Manually compact with summary compaction" }
1290
+ : item),
1291
+ };
1292
+ },
1293
+ applyCompletion: (...args) => current.applyCompletion(...args),
1294
+ shouldTriggerFileCompletion: (...args) => current.shouldTriggerFileCompletion?.(...args) ?? true,
1295
+ }));
1296
+ });
1297
+
1298
+ // --------------------------------------------------------------------------
1299
+ // Mechanical compaction
1300
+ // --------------------------------------------------------------------------
1301
+ pi.on("session_before_compact", async (event, ctx) => {
1302
+ const { preparation, branchEntries, reason, signal } = event;
1303
+ if (!preparation) return;
1304
+ if (signal?.aborted) return;
1305
+ if (preparation.messagesToSummarize.length === 0 && preparation.turnPrefixMessages.length === 0) return;
1306
+ if (compactionMethod(ctx.sessionManager.getBranch()) === "summary") {
1307
+ return; // No override: Pi runs its normal model-generated compaction.
1308
+ }
1309
+
1310
+ // No disk snapshot: pi retains the full raw branch in its session.
1311
+
1312
+ // 1) Cumulative file lists: pi only carries lists from pi-generated
1313
+ // compactions (fromHook=false), so we carry our own forward.
1314
+ try {
1315
+ const fileOps = preparation.fileOps as { read: Set<string>; written: Set<string>; edited: Set<string> } | undefined;
1316
+ if (fileOps) {
1317
+ for (let i = branchEntries.length - 1; i >= 0; i--) {
1318
+ const e = branchEntries[i];
1319
+ if (e.type === "compaction") {
1320
+ const d = (e as { details?: { kind?: string; readFiles?: string[]; modifiedFiles?: string[] } }).details;
1321
+ if (d?.kind === MECH_KIND) {
1322
+ for (const f of d.readFiles ?? []) fileOps.read.add(f);
1323
+ for (const f of d.modifiedFiles ?? []) fileOps.edited.add(f);
1324
+ break;
1325
+ }
1326
+ }
1327
+ }
1328
+ }
1329
+
1330
+ const modified = new Set([...(fileOps?.edited ?? []), ...(fileOps?.written ?? [])]);
1331
+ const modifiedFiles = [...modified].sort();
1332
+ const readFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
1333
+
1334
+ // 2) The new span. Pi's preparation span is [previous cut, current cut)
1335
+ // — it includes the previous compaction's retained tail (verified
1336
+ // against prepareCompaction: the projection places the retained tail
1337
+ // right after the previous compaction entry and boundaryStart sits at
1338
+ // it), so consecutive spans tile: nothing is summarized twice or
1339
+ // missed. No entry-id bookkeeping is needed; the next preparation is
1340
+ // authoritative.
1341
+ const nowIso = new Date().toISOString();
1342
+ const allMessages = [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages];
1343
+ // Span coverage range: first/last summarised message timestamps (pi
1344
+ // message timestamps are epoch ms; ISO strings are accepted too).
1345
+ const toIso = (ts: unknown): string | undefined => {
1346
+ const t = typeof ts === "number" ? ts : typeof ts === "string" && ts !== "" ? Date.parse(ts) : NaN;
1347
+ return Number.isFinite(t) ? new Date(t).toISOString() : undefined;
1348
+ };
1349
+ const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
1350
+ const spanFrom = toIso(msgTs(allMessages[0]));
1351
+ const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
1352
+ const spanLines = summarizeMessages(allMessages);
1353
+
1354
+ // 3) Build the mechanical summary (no LLM call).
1355
+ const summary = await buildMechanicalSummary({
1356
+ reason, // pi's raw reason, passed through unchanged
1357
+ tokensBefore: preparation.tokensBefore,
1358
+ branchEntries,
1359
+ now: nowIso,
1360
+ spanLines,
1361
+ spanFrom,
1362
+ spanTo,
1363
+ firstKeptEntryId: preparation.firstKeptEntryId,
1364
+ readFiles,
1365
+ modifiedFiles,
1366
+ notify: (m) => ctx.ui?.notify?.(m, "warning"),
1367
+ chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
1368
+ });
1369
+ if (summary === undefined || signal?.aborted) return { cancel: true };
1370
+
1371
+ ctx.ui?.notify?.(
1372
+ `transparent-compact: ~${preparation.tokensBefore.toLocaleString()} tokens -> verbatim checkpoint; full transcript kept in the session`,
1373
+ "info",
1374
+ );
1375
+
1376
+ return {
1377
+ compaction: {
1378
+ summary,
1379
+ firstKeptEntryId: preparation.firstKeptEntryId,
1380
+ tokensBefore: preparation.tokensBefore,
1381
+ details: {
1382
+ kind: MECH_KIND,
1383
+ readFiles,
1384
+ modifiedFiles,
1385
+ // Only this compaction's own span (un-capped lines). Earlier spans
1386
+ // are re-rendered from the earlier entries' details — no nesting.
1387
+ span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore, lines: spanLines },
1388
+ },
1389
+ },
1390
+ };
1391
+ } catch (err) {
1392
+ ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); falling back to Pi's summary compaction`, "error");
1393
+ return;
1394
+ }
1395
+ });
1396
+
1397
+ // --------------------------------------------------------------------------
1398
+ // context_lookup tool: subagent research over the raw session branch
1399
+ // --------------------------------------------------------------------------
1400
+ registerDirectTools(pi);
1401
+ pi.registerTool({
1402
+ name: "context_lookup",
1403
+ label: "Context lookup",
1404
+ executionMode: "sequential",
1405
+ description:
1406
+ "Recover information preserved in the session but removed from your active context by verbatim compaction—including thinking, tool outputs, error text, file contents, and earlier decisions. Spawns a subagent that searches the full raw session branch (across all compactions) in its OWN context and returns only relevant findings. Does not search abandoned branches or other sessions. Prefer this tool first; if findings are incomplete, use the bounded context_list_entries, context_grep, and context_show_entry fallback tools. Follow their pagination instructions. Do not read or grep raw session JSONL files or old dumps through filesystem tools. Repeated lookup calls without a non-recovery tool result, user message, or bash execution are limited. The three fallback tools neither increase nor reset the lookup count; narration and thinking do not reset it either.",
1407
+ promptSnippet: "Ask a subagent to research dropped context in the session transcript",
1408
+ parameters: Type.Object({
1409
+ question: Type.String({ description: "What to find in the dropped context. Be specific (exact error text, file, decision, command output…)." }),
1410
+ }),
1411
+ async execute(toolCallId, params, signal, _onUpdate, ctx) {
1412
+ if (cfg.lookupMaxCalls > 0 && consecutiveLookups(ctx, toolCallId) >= cfg.lookupMaxCalls) {
1413
+ return {
1414
+ content: [{ type: "text", text: `context_lookup consecutive-call limit reached (${cfg.lookupMaxCalls}). ${LOOKUP_FALLBACK_NOTE}` }],
1415
+ details: undefined,
1416
+ };
1417
+ }
1418
+ let model: Model | undefined;
1419
+ if (cfg.lookupModel) {
1420
+ const slash = cfg.lookupModel.indexOf("/");
1421
+ if (slash > 0) model = ctx.modelRegistry.find(cfg.lookupModel.slice(0, slash), cfg.lookupModel.slice(slash + 1));
1422
+ }
1423
+ model = model ?? ctx.model;
1424
+ if (!model) {
1425
+ return { content: [{ type: "text", text: "context_lookup needs a model (session model or MECH_COMPACT_LOOKUP_MODEL)." }], details: undefined };
1426
+ }
1427
+
1428
+ try {
1429
+ if (signal?.aborted) return { content: [{ type: "text", text: "(lookup subagent aborted)" }], details: undefined };
1430
+ const transcript = sessionTranscript(ctx);
1431
+ if (transcript.index.length === 0)
1432
+ return { content: [{ type: "text", text: "No entries found on the session branch." }], details: undefined };
1433
+ const answer = await runLookupSubagent({ question: params.question, transcripts: [transcript], model, registry: ctx.modelRegistry, signal });
1434
+ return { content: [{ type: "text", text: answer }], details: undefined };
1435
+ } catch (err) {
1436
+ return { content: [{ type: "text", text: `context_lookup failed: ${errMsg(err)}` }], details: undefined };
1437
+ }
1438
+ },
1439
+ });
1440
+ }