@foliox/transparent-compact-pi 0.9.3 → 0.10.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.
@@ -2,6 +2,7 @@
2
2
  * model calls, or session mutation. Canonical span lines/records are never edited.
3
3
  */
4
4
  export const TOOL_PREFIX = "[Tools]: ";
5
+ export const FILTER_MARKER = "[Turn manually filtered]";
5
6
  export const NORMAL_PREVIEW_CHARS = 160;
6
7
  export const TIGHTENED_ATTR = ' tools-tightened="true"';
7
8
 
@@ -20,7 +21,7 @@ export interface ToolLine {
20
21
  mergeable: boolean;
21
22
  }
22
23
  export interface ToolLines { version: 2; lines: ToolLine[] }
23
- export interface SpanContent { lines: string[]; tools?: ToolLines }
24
+ export interface SpanContent { lines: string[]; tools?: ToolLines; protectedLines?: number[] }
24
25
  export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[] }
25
26
 
26
27
  function headPrefix(text: string, max: number): string {
@@ -72,6 +73,7 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
72
73
 
73
74
  interface Row {
74
75
  index: number;
76
+ protected: boolean;
75
77
  text: string;
76
78
  calls?: ToolStub[];
77
79
  mergeable: boolean;
@@ -92,7 +94,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
92
94
  const records = toolRecords(span);
93
95
  return span.lines.map((text, index): Row => {
94
96
  const record = records.get(index);
95
- return { index, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
97
+ return { index, protected: span.protectedLines?.includes(index) ?? false, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
96
98
  preview: NORMAL_PREVIEW_CHARS, foldPrefix: false, tightened: false };
97
99
  });
98
100
  });
@@ -142,7 +144,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
142
144
  const rows = states[span];
143
145
  for (let i = 0; i < rows.length && size > budget;) {
144
146
  const row = rows[i];
145
- if (row.text.startsWith("[User]:")) { i++; continue; }
147
+ if (row.protected || row.text.startsWith("[User]:") || row.text === FILTER_MARKER) { i++; continue; }
146
148
  if (row.calls && row.calls.length > 1) {
147
149
  row.calls.shift();
148
150
  row.text = render(row);
@@ -157,7 +159,7 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
157
159
  for (const row of states[span]) {
158
160
  if (size <= budget) break;
159
161
  const line = row.text;
160
- if (!line.startsWith("[User]:") || line.length <= 120) continue;
162
+ if (row.protected || !line.startsWith("[User]:") || line.length <= 120) continue;
161
163
  let end = 120;
162
164
  if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
163
165
  const stub = `${line.slice(0, end)}…[truncated +${line.length - end} chars — use context_lookup]`;
@@ -168,8 +170,10 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
168
170
  }
169
171
  }
170
172
  for (let span = 0; span < states.length && size > budget; span++) {
171
- while (states[span].length && size > budget) {
172
- states[span].shift();
173
+ while (size > budget) {
174
+ const index = states[span].findIndex((row) => !row.protected && row.text !== FILTER_MARKER);
175
+ if (index < 0) break;
176
+ states[span].splice(index, 1);
173
177
  trimmed[span] = true;
174
178
  size = measure();
175
179
  }
@@ -0,0 +1,209 @@
1
+ import { uuidv7 } from "@earendil-works/pi-ai";
2
+ import { buildSessionProjection, estimateTokens } from "@earendil-works/pi-coding-agent";
3
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
5
+ import type { TurnSpan } from "./turn-filter.js";
6
+
7
+ export type Fidelity = "tools" | "full";
8
+ export type TurnMode = "pruned" | "prose" | Fidelity;
9
+ export type TurnFidelities = Record<string, Fidelity>;
10
+ export interface TurnSelection { pruned: string[]; fidelity: TurnFidelities }
11
+ export interface TurnSlot { turnId: string; mode: Fidelity; offset: number; marker: string }
12
+ export const MODE_LABELS: Record<TurnMode, string> = { pruned: "PRUNED", prose: "PROSE", tools: "PROSE+TOOLS", full: "FULL" };
13
+ export const MODE_SYMBOLS: Record<TurnMode, string> = { pruned: "X", prose: " ", tools: "○", full: "■" };
14
+ export const FIDELITY_EXPLANATION = "Selected PROSE+TOOLS/FULL turns are inserted as original context messages at their labelled positions, replacing their compacted copies. PROSE+TOOLS replaces recorded thinking blocks with [Thinking omitted]; FULL retains all recorded thinking. They are not shortened by the prose cap. Provider/model compatibility transformations still apply. Historical content and thinking are not verification of current facts.";
15
+ /** Raw user boundaries define whole turns, independent of context edits. */
16
+ export function turnOwners(entries: SessionEntry[]): Map<string, string | null> {
17
+ let owner: string | null = null;
18
+ return new Map(entries.map((entry) => {
19
+ if (entry.type === "message" && entry.message.role === "user") owner = entry.id;
20
+ return [entry.id, owner];
21
+ }));
22
+ }
23
+ const managed = (m: AgentMessage) => m.role === "custom" && m.customType === "transparent-compact:reorient";
24
+
25
+ /** Disable only compaction in Pi's projection, preserving the branch topology,
26
+ * custom-message conversion and explicit context edits. No raw body is copied
27
+ * into checkpoint metadata, and omitted/replaced content is never resurrected.
28
+ */
29
+ export function originalProjection(entries: SessionEntry[]) {
30
+ const uncompacted = entries.map((entry): SessionEntry => entry.type === "compaction"
31
+ ? { id: entry.id, parentId: entry.parentId, timestamp: entry.timestamp, type: "custom", customType: "transparent-compact:projection-boundary", data: null }
32
+ : entry);
33
+ return buildSessionProjection(uncompacted).entries;
34
+ }
35
+
36
+ function validateTools(messages: AgentMessage[], id: string): void {
37
+ const pending = new Map<string, string>(), seen = new Set<string>();
38
+ for (const msg of messages) {
39
+ if (msg.role === "assistant") {
40
+ if (pending.size) throw new Error(`Turn ${id} has incomplete tool-call/result groups; choose PROSE instead.`);
41
+ for (const block of msg.content) if (block.type === "toolCall") {
42
+ if (seen.has(block.id)) throw new Error(`Turn ${id} has ambiguous tool-call ids; choose PROSE instead.`);
43
+ seen.add(block.id); pending.set(block.id, block.name);
44
+ }
45
+ } else if (msg.role === "toolResult") {
46
+ if (pending.get(msg.toolCallId) !== msg.toolName)
47
+ throw new Error(`Turn ${id} has an orphaned tool result (possibly from a context edit); choose PROSE instead.`);
48
+ pending.delete(msg.toolCallId);
49
+ }
50
+ }
51
+ if (pending.size) throw new Error(`Turn ${id} has incomplete tool-call/result groups; choose PROSE instead.`);
52
+ }
53
+
54
+ export function fidelityMessages(entries: SessionEntry[], fidelity: TurnFidelities, boundary: string): Map<string, AgentMessage[]> {
55
+ const owners = turnOwners(entries), cut = entries.findIndex((e) => e.id === boundary);
56
+ if (cut < 0) throw new Error("Cannot locate the retained context boundary.");
57
+ const groups = new Map(Object.keys(fidelity).map((id) => [id, [] as AgentMessage[]]));
58
+ const positions = new Map(entries.map((entry, index) => [entry.id, index]));
59
+ for (const { sourceEntry, messages } of originalProjection(entries)) {
60
+ const id = owners.get(sourceEntry.id);
61
+ if (!id || !groups.has(id)) continue;
62
+ const content = messages.filter((m) => m.role !== "system" && !managed(m) && !(m.role === "bashExecution" && m.excludeFromContext));
63
+ if (!content.length) continue;
64
+ if (positions.get(sourceEntry.id)! >= cut) throw new Error(`Turn ${id} still overlaps the retained recent tail.`);
65
+ groups.get(id)!.push(...content);
66
+ }
67
+ for (const [id, messages] of groups) {
68
+ if (fidelity[id] !== "tools" && fidelity[id] !== "full") throw new Error(`Unknown fidelity mode for turn ${id}.`);
69
+ if (!messages.length || messages[0].role !== "user") throw new Error(`Original user turn ${id} is unavailable or explicitly omitted.`);
70
+ validateTools(messages, id);
71
+ if (fidelity[id] === "tools") groups.set(id, messages.map((msg) => msg.role !== "assistant" ? msg : { ...msg,
72
+ content: msg.content.map((block) => block.type === "thinking" ? { type: "text" as const, text: "[Thinking omitted]" } : block) }));
73
+ }
74
+ return groups;
75
+ }
76
+
77
+ /** Replace every compacted copy, across span boundaries, with one protected
78
+ * slot. The random marker is generated, not interpreted from historical text.
79
+ */
80
+ export function fidelitySpans<T extends TurnSpan>(spans: T[], fidelity: TurnFidelities) {
81
+ const markers = new Map<string, string>();
82
+ const result = spans.map((span) => {
83
+ const lines: string[] = [], turnIds: (string | null)[] = [], protectedLines: number[] = [], indices = new Map<number, number>();
84
+ span.lines.forEach((line, index) => {
85
+ const owner = span.turnIds?.[index] ?? null;
86
+ if (owner && fidelity[owner]) {
87
+ if (!markers.has(owner)) {
88
+ const marker = `[Full-fidelity turn ${owner}: ${MODE_LABELS[fidelity[owner]]}; slot ${uuidv7()}]`;
89
+ markers.set(owner, marker); protectedLines.push(lines.length); lines.push(marker); turnIds.push(owner);
90
+ }
91
+ } else { indices.set(index, lines.length); lines.push(line); turnIds.push(owner); }
92
+ });
93
+ const tools = span.tools && { ...span.tools, lines: span.tools.lines.filter((r) => indices.has(r.index))
94
+ .map((r) => ({ ...r, index: indices.get(r.index)! })) };
95
+ return { ...span, lines, turnIds, tools, protectedLines };
96
+ });
97
+ for (const id of Object.keys(fidelity)) if (!markers.has(id)) throw new Error(`Turn ${id} has no editable checkpoint position.`);
98
+ return { spans: result, markers };
99
+ }
100
+
101
+ export function locateSlots(summary: string, markers: Map<string, string>, fidelity: TurnFidelities): TurnSlot[] {
102
+ return [...markers].map(([turnId, marker]) => {
103
+ const offset = summary.indexOf(marker);
104
+ if (offset < 0 || offset !== summary.lastIndexOf(marker)) throw new Error(`Full-fidelity placement for ${turnId} was lost or duplicated.`);
105
+ return { turnId, mode: fidelity[turnId], offset, marker };
106
+ }).sort((a, b) => a.offset - b.offset);
107
+ }
108
+
109
+ const expanded = new WeakMap<AgentMessage, string>();
110
+ export function isExpandedCheckpoint(message: AgentMessage, summary: string): boolean {
111
+ const previous = expanded.get(message);
112
+ if (previous !== undefined && previous !== summary) throw new Error("Stale full-fidelity projection; rebuild context from the session before continuing.");
113
+ return previous === summary;
114
+ }
115
+
116
+ export function expandCheckpoint(message: Extract<AgentMessage, { role: "compactionSummary" }>, summary: string,
117
+ slots: TurnSlot[], fidelity: TurnFidelities, entries: SessionEntry[], boundary: string): AgentMessage[] {
118
+ if (!Object.keys(fidelity).length) return [{ ...message, summary }];
119
+ const groups = fidelityMessages(entries, fidelity, boundary), output: AgentMessage[] = [], seen = new Set<string>();
120
+ let from = 0, ending = "";
121
+ for (const slot of slots) {
122
+ if (!Number.isSafeInteger(slot.offset) || typeof slot.marker !== "string" || !slot.marker || slot.offset < from || summary.slice(slot.offset, slot.offset + slot.marker.length) !== slot.marker ||
123
+ slot.mode !== fidelity[slot.turnId] || seen.has(slot.turnId) || !groups.has(slot.turnId))
124
+ throw new Error("Full-fidelity checkpoint placements are inconsistent; revise turn modes before continuing.");
125
+ output.push({ ...message, summary: ending + summary.slice(from, slot.offset) + `\n[Full-fidelity turn ${slot.turnId}: ${MODE_LABELS[slot.mode]}]\n` });
126
+ // Request-local copies: later transforms must not mutate saved records.
127
+ output.push(...groups.get(slot.turnId)!.map((item) => structuredClone(item)));
128
+ ending = `\n[End full-fidelity turn ${slot.turnId}]\n`;
129
+ seen.add(slot.turnId); from = slot.offset + slot.marker.length;
130
+ }
131
+ if (seen.size !== groups.size) throw new Error("Full-fidelity checkpoint has missing placements; revise turn modes before continuing.");
132
+ output.push({ ...message, summary: ending + summary.slice(from) });
133
+ for (const item of output) if (item.role === "compactionSummary") expanded.set(item, summary);
134
+ return output;
135
+ }
136
+
137
+ export interface NoticeTokens { pruning: number; revision: number; fidelity: number }
138
+ export interface ContextEstimate {
139
+ tokens: number;
140
+ contextWindow?: number;
141
+ reserve: number;
142
+ headroom?: number;
143
+ delta?: number;
144
+ tailTokens?: number;
145
+ noticeTokens?: NoticeTokens;
146
+ noticeDelta?: NoticeTokens;
147
+ shortening?: "automatic" | "confirmation";
148
+ }
149
+ export type ContextEstimator = (selection: TurnSelection) => Promise<ContextEstimate>;
150
+ export const contextReserve = (ctx: ExtensionContext) => Math.min(ctx.model?.maxTokens || 16384, 16384) + 4096;
151
+ export function estimateContext(messages: AgentMessage[], ctx: ExtensionContext): ContextEstimate {
152
+ const tokens = messageTokens(messages), contextWindow = ctx.model?.contextWindow, reserve = contextReserve(ctx);
153
+ return { tokens, contextWindow, reserve, headroom: contextWindow ? contextWindow - tokens - reserve : undefined };
154
+ }
155
+
156
+ export const messageTokens = (messages: AgentMessage[]) => messages.reduce((sum, m) => sum + (m.role === "bashExecution" && m.excludeFromContext ? 0 : estimateTokens(m) + 8), 0);
157
+
158
+ /** Estimates, not a provider tokenizer. Keep output/framing headroom and check
159
+ * again on each actual request, including its restored system/tool messages.
160
+ */
161
+ export function checkContextBudget(messages: AgentMessage[], ctx: ExtensionContext, includeSystem = false): number {
162
+ const window = ctx.model?.contextWindow;
163
+ if (!window) throw new Error("Cannot budget full-fidelity turns without the model's context window.");
164
+ const tokens = messageTokens(messages) + (includeSystem ? Math.ceil((ctx.getSystemPrompt?.() ?? "").length / 4) : 0);
165
+ const reserve = contextReserve(ctx);
166
+ if (tokens + reserve > window) throw new Error(`Full-fidelity context needs ~${tokens.toLocaleString()} input tokens plus ${reserve.toLocaleString()} reserved tokens (window ${window.toLocaleString()}). Change PROSE+TOOLS/FULL turns to PROSE or PRUNED with /filter-turns. Nothing was silently shortened.`);
167
+ return tokens;
168
+ }
169
+
170
+ export function retainedTailMessages(entries: SessionEntry[], boundary: string): AgentMessage[] {
171
+ const cut = entries.findIndex((e) => e.id === boundary);
172
+ if (cut < 0) throw new Error("Cannot locate the retained context boundary.");
173
+ const tailIds = new Set(entries.slice(cut).map((entry) => entry.id));
174
+ return originalProjection(entries).filter(({ sourceEntry }) => tailIds.has(sourceEntry.id))
175
+ .flatMap(({ messages }) => messages).filter((m) => m.role !== "system" && !managed(m));
176
+ }
177
+
178
+ export function checkpointContextMessages(summary: string, slots: TurnSlot[], fidelity: TurnFidelities,
179
+ entries: SessionEntry[], boundary: string): AgentMessage[] {
180
+ const summaryMessage = { role: "compactionSummary" as const, summary, tokensBefore: 0, timestamp: 0 };
181
+ const tail = retainedTailMessages(entries, boundary);
182
+ return [...expandCheckpoint(summaryMessage, summary, slots, fidelity, entries, boundary), ...tail];
183
+ }
184
+
185
+ export function checkCheckpointBudget(summary: string, slots: TurnSlot[], fidelity: TurnFidelities,
186
+ entries: SessionEntry[], boundary: string, ctx: ExtensionContext): void {
187
+ if (Object.keys(fidelity).length) checkContextBudget(checkpointContextMessages(summary, slots, fidelity, entries, boundary), ctx, true);
188
+ }
189
+
190
+ /** UI-only, complete text/arguments/output preview; image bytes are identified,
191
+ * not drawn or dumped as base64. Native image blocks are retained in context.
192
+ */
193
+ export function previewMessages(messages: AgentMessage[]): string[] {
194
+ const lines: string[] = [];
195
+ for (const msg of messages) {
196
+ lines.push(msg.role === "toolResult" ? `[Tool result ${msg.toolName} (${msg.toolCallId})${msg.isError ? "; error" : ""}]:` : `[${msg.role}]:`);
197
+ if ("content" in msg) {
198
+ if (typeof msg.content === "string") lines.push(...msg.content.split("\n"));
199
+ else for (const block of msg.content) {
200
+ if (block.type === "text") lines.push(...block.text.split("\n"));
201
+ else if (block.type === "thinking") lines.push("[Thinking]", ...block.thinking.split("\n"), ...(block.redacted ? ["[Opaque/redacted thinking retained]"] : []));
202
+ else if (block.type === "toolCall") lines.push(`[Tool call ${block.name} (${block.id})]: ${JSON.stringify(block.arguments)}`);
203
+ else if (block.type === "image") lines.push(`[Image attachment: ${block.mimeType}]`);
204
+ }
205
+ } else if (msg.role === "bashExecution") lines.push(msg.command, ...msg.output.split("\n"));
206
+ else if (msg.role === "branchSummary") lines.push(msg.summary);
207
+ }
208
+ return lines;
209
+ }
@@ -0,0 +1,346 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { matchesKey, Key, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
3
+ import type { ExtensionContext, SessionEntry } from "@earendil-works/pi-coding-agent";
4
+ import { FILTER_MARKER } from "./checkpoint-cap.js";
5
+ import type { SpanContent, ToolLines } from "./checkpoint-cap.js";
6
+ export { FILTER_MARKER } from "./checkpoint-cap.js";
7
+ export { turnOwners } from "./turn-context.js";
8
+ import { MODE_LABELS, MODE_SYMBOLS } from "./turn-context.js";
9
+ import type { ContextEstimate, ContextEstimator, Fidelity, TurnFidelities, TurnMode, TurnSelection } from "./turn-context.js";
10
+
11
+ export const PREFLAG_ENTRY = "transparent-compact:aside-turn";
12
+ export const AUTO_FILTER_ENTRY = "transparent-compact:auto-filter";
13
+ export const FILTER_REVISION_ENTRY = "transparent-compact:filter-revision";
14
+
15
+ export function autoFilterEnabled(entries: SessionEntry[]): boolean {
16
+ const entry = entries.findLast((entry) => entry.type === "custom" && entry.customType === AUTO_FILTER_ENTRY);
17
+ return entry?.type === "custom" && (entry.data as { enabled?: boolean })?.enabled === true;
18
+ }
19
+
20
+ /** Written immediately before the aside's user message is persisted. Consume
21
+ * once at that raw boundary; the timestamp guards against an interrupted append.
22
+ */
23
+ export function preflaggedTurns(entries: SessionEntry[]): Set<string> {
24
+ const flagged = new Set<string>();
25
+ let pending: number | undefined;
26
+ for (const entry of entries) {
27
+ if (entry.type === "custom" && entry.customType === PREFLAG_ENTRY)
28
+ pending = (entry.data as { timestamp?: number })?.timestamp;
29
+ else if (entry.type === "message" && entry.message.role === "user") {
30
+ if (pending !== undefined && entry.message.timestamp === pending) flagged.add(entry.id);
31
+ pending = undefined;
32
+ }
33
+ }
34
+ return flagged;
35
+ }
36
+ export const FILTER_EXPLANATION = "`[Turn manually filtered]` marks a user turn and its following agent/tool activity that the user chose to exclude as low-value context. Its contents remain retrievable from the full history. Do not recover filtered turns unless needed for the current task.";
37
+ export interface TurnSpan extends SpanContent { turnIds?: (string | null)[] }
38
+
39
+ /** Drop canonical lines before capping, retaining tool-record indices exactly.
40
+ * A turn can cross compaction spans; emit only one marker at its first position.
41
+ */
42
+ export function filterSpans<T extends TurnSpan>(spans: T[], excluded: Set<string>): T[] {
43
+ if (excluded.size === 0) return spans;
44
+ const marked = new Set<string>();
45
+ return spans.map((span) => {
46
+ const lines: string[] = [], turnIds: (string | null)[] = [];
47
+ const indices = new Map<number, number>();
48
+ span.lines.forEach((line, index) => {
49
+ const owner = span.turnIds?.[index] ?? null;
50
+ if (owner && excluded.has(owner)) {
51
+ if (!marked.has(owner)) {
52
+ marked.add(owner);
53
+ lines.push(FILTER_MARKER);
54
+ turnIds.push(owner);
55
+ }
56
+ } else {
57
+ indices.set(index, lines.length);
58
+ lines.push(line);
59
+ turnIds.push(owner);
60
+ }
61
+ });
62
+ const tools: ToolLines | undefined = span.tools && { ...span.tools, lines: span.tools.lines
63
+ .filter((record) => indices.has(record.index))
64
+ .map((record) => ({ ...record, index: indices.get(record.index)! })) };
65
+ return { ...span, lines, turnIds, tools };
66
+ });
67
+ }
68
+
69
+ export interface FilterTurn {
70
+ id: string;
71
+ label: string;
72
+ lines: string[];
73
+ selected?: boolean;
74
+ filtered?: boolean;
75
+ fidelity?: Fidelity;
76
+ fidelityInfo?: (mode: Fidelity) => { tokens: number; lines: string[] };
77
+ deferred?: boolean;
78
+ unavailable?: string;
79
+ }
80
+
81
+ const displayText = (text: string) => stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, "");
82
+
83
+ /** Tree-like whole-turn selection followed by a scrollable, complete preview.
84
+ * Subentries are inspection-only: space always toggles their owning user turn.
85
+ */
86
+ export async function pickFilteredTurns(ctx: ExtensionContext, turns: FilterTurn[], signal: AbortSignal,
87
+ estimate?: ContextEstimator): Promise<TurnSelection | undefined> {
88
+ return ctx.ui.custom<TurnSelection | undefined>((tui, theme, kb, done) => {
89
+ const selected = new Set(turns.filter((turn) => turn.selected).map((turn) => turn.id));
90
+ const fidelity: TurnFidelities = Object.fromEntries(turns.filter((turn) => turn.fidelity && !selected.has(turn.id)).map((turn) => [turn.id, turn.fidelity!]));
91
+ const originalMode = (turn: FilterTurn): TurnMode => turn.filtered ? "pruned" : turn.fidelity ?? "prose";
92
+ const modeOf = (turn: FilterTurn): TurnMode => selected.has(turn.id) ? "pruned" : fidelity[turn.id] ?? "prose";
93
+ const setMode = (turn: FilterTurn, mode: TurnMode) => {
94
+ if (mode === "pruned") selected.add(turn.id); else selected.delete(turn.id);
95
+ if (mode === "tools" || mode === "full") fidelity[turn.id] = mode; else delete fidelity[turn.id];
96
+ refreshEstimate();
97
+ };
98
+ const selection = (): TurnSelection => ({ pruned: [...selected], fidelity: { ...fidelity } });
99
+ let notice: string | undefined;
100
+ let disposed = false, generation = 0, queued = false, estimating = false;
101
+ let estimated: ContextEstimate | undefined, estimateError = estimate ? "" : "Context estimator unavailable";
102
+ const refreshEstimate = () => {
103
+ if (!estimate || disposed) return;
104
+ generation++; estimating = true; estimateError = "";
105
+ if (queued) return;
106
+ queued = true;
107
+ queueMicrotask(() => {
108
+ queued = false;
109
+ if (disposed) return;
110
+ const request = generation, proposed = selection();
111
+ Promise.resolve().then(() => disposed || request !== generation ? undefined : estimate(proposed)).then((value) => {
112
+ if (disposed || request !== generation || !value) return;
113
+ estimated = value; estimating = false; tui.requestRender();
114
+ }).catch((error) => {
115
+ if (disposed || request !== generation) return;
116
+ estimated = undefined; estimating = false;
117
+ estimateError = displayText(error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ");
118
+ tui.requestRender();
119
+ });
120
+ });
121
+ };
122
+ const sizeReadout = (width: number): { lines: string[]; color: "accent" | "warning" | "error" | "muted" } => {
123
+ if (estimating && !estimated) return { lines: ["Estimated context: calculating tokens…", "Includes checkpoint, native turns, tail and system/tools."], color: "muted" };
124
+ if (!estimated) return { lines: ["Estimated context: unavailable", estimateError], color: "warning" };
125
+ const { tokens, contextWindow, reserve, headroom, delta, tailTokens, noticeDelta, shortening } = estimated;
126
+ const overhead = noticeDelta ? noticeDelta.pruning + noticeDelta.revision + noticeDelta.fidelity : 0;
127
+ const scaffolding = (format: (n: number) => string) => overhead
128
+ ? ` · ${overhead < 0 ? "−" : "+"}~${format(Math.abs(overhead))} scaffolding` : "";
129
+ const longTotal = `Estimated context: ~${tokens.toLocaleString()}${contextWindow ? ` / ${contextWindow.toLocaleString()}` : ""} tokens` +
130
+ `${contextWindow ? ` (${(100 * tokens / contextWindow).toFixed(1)}%)` : ""} · incl. ${tailTokens === undefined ? "tail" : `~${tailTokens.toLocaleString()} tail`}` +
131
+ scaffolding((n) => n.toLocaleString());
132
+ const short = width < 70 || visibleWidth(longTotal) > width;
133
+ const number = (n: number) => !short ? n.toLocaleString() : n >= 1e6 ? `${(n / 1e6).toFixed(1).replace(/\.0$/, "")}m`
134
+ : n >= 1e3 ? `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k` : n.toLocaleString();
135
+ const total = short ? `Est. ~${number(tokens)}${contextWindow ? `/${number(contextWindow)} ${(100 * tokens / contextWindow).toFixed(0)}%` : " tokens"}` +
136
+ ` incl. ${tailTokens === undefined ? "tail" : `~${number(tailTokens)} tail`}${scaffolding(number)}` : longTotal;
137
+ const signed = (n: number) => `${n < 0 ? "−" : "+"}${number(Math.abs(n))}`;
138
+ const change = delta === undefined ? "Net Δ unknown" : `Net Δ ${signed(delta)}`;
139
+ const room = headroom === undefined ? "window unknown" : headroom < 0 ? `OVER ${number(-headroom)}` : `free ${number(headroom)}`;
140
+ const lines = [total, `${change} · ${room} · ${short ? "rsv" : "reserve"} ${number(reserve)}`];
141
+ if (shortening) lines.push(shortening === "confirmation"
142
+ ? "Size limit shortened this preview; saving asks for confirmation."
143
+ : "Size limit shortened this preview.");
144
+ return { lines, color: headroom !== undefined && headroom < 0 ? "error" : "accent" };
145
+ };
146
+ const expanded = new Set<string>();
147
+ type PreviewLine = { text: string; kind: "heading" | "content" | "note" };
148
+ let cursor = 0, top = 0, review: PreviewLine[] | undefined, scroll = 0;
149
+ let wrappedReview: { width: number; source: PreviewLine[]; lines: PreviewLine[] } | undefined;
150
+ const rows = () => turns.flatMap((turn, index) => {
151
+ let details: string[] = [];
152
+ if (expanded.has(turn.id)) {
153
+ details = turn.lines.slice(1);
154
+ const mode = modeOf(turn);
155
+ if (mode === "tools" || mode === "full") {
156
+ try { details = turn.fidelityInfo?.(mode).lines ?? details; }
157
+ catch (error) { details = [String(error), ...details]; }
158
+ }
159
+ }
160
+ return [{ turn, number: index + 1, child: false, text: turn.label },
161
+ ...details.map((text) => ({ turn, number: index + 1, child: true, text }))];
162
+ });
163
+ const pageSize = () => Math.max(1, tui.terminal.rows - (tui.terminal.rows >= 16 ? 10 + sizeReadout(100).lines.length : 9));
164
+ const stateOf = (turn: FilterTurn): { label: string; color: "dim" | "warning" | "success" | "text" | "accent"; hint: string } => {
165
+ const checked = selected.has(turn.id);
166
+ if (turn.unavailable) return { label: "Locked", color: "dim", hint: `Locked — ${turn.unavailable}` };
167
+ if (turn.deferred) return checked
168
+ ? { label: "Pending", color: "warning", hint: "Pending pruning — recent tail unchanged; f only toggles the flag" }
169
+ : { label: "PROSE", color: "success", hint: "Keep — pending exclusion cancelled" };
170
+ const mode = modeOf(turn);
171
+ if (mode === "tools" || mode === "full") return { label: MODE_LABELS[mode], color: "accent",
172
+ hint: mode === "tools" ? "PROSE+TOOLS — complete tools; thinking markers only" : "FULL — all recorded content, including thinking" };
173
+ if (checked) return { label: "PRUNED", color: "warning", hint: turn.filtered
174
+ ? "Already pruned — Space restores PROSE; f cycles modes" : "Prune — replace this whole turn with a marker" };
175
+ return { label: "PROSE", color: turn.filtered || turn.selected ? "success" : "text", hint: turn.filtered
176
+ ? "Restore — compacted prose returns to the checkpoint" : turn.selected ? "Keep — pre-flag cancelled" : "PROSE — our standard mechanical compaction" };
177
+ };
178
+ const changeSummary = () => {
179
+ let exclude = 0, restore = 0, pending = 0, keep = 0, tools = 0, full = 0;
180
+ for (const turn of turns) {
181
+ if (turn.unavailable) continue;
182
+ const checked = selected.has(turn.id), mode = modeOf(turn);
183
+ if (mode === "tools") { if (mode !== originalMode(turn)) tools++; continue; }
184
+ if (mode === "full") { if (mode !== originalMode(turn)) full++; continue; }
185
+ if (checked && turn.deferred) pending++;
186
+ else if (checked && !turn.filtered) exclude++;
187
+ else if (!checked && turn.filtered) restore++;
188
+ else if (!checked && turn.selected) keep++;
189
+ }
190
+ return `${exclude} pruned · ${restore} restored · ${keep} keep · ${pending} pending · ${tools} tools · ${full} full`;
191
+ };
192
+ const finish = (value: TurnSelection | undefined) => { disposed = true; generation++; signal.removeEventListener("abort", abort); done(value); };
193
+ const abort = () => finish(undefined);
194
+ signal.addEventListener("abort", abort, { once: true });
195
+ if (signal.aborted) queueMicrotask(abort);
196
+ refreshEstimate();
197
+ return {
198
+ render(width: number): string[] {
199
+ const height = pageSize(), roomy = tui.terminal.rows >= 16, framed = width >= 8;
200
+ const innerWidth = Math.max(1, width - (framed ? 4 : 0));
201
+ const pad = (text: string) => {
202
+ const clipped = truncateToWidth(text, innerWidth);
203
+ return clipped + " ".repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
204
+ };
205
+ const line = (text: string, focused = false) => {
206
+ const content = focused ? theme.bg("selectedBg", pad(text)) : pad(text);
207
+ return framed ? theme.fg("borderMuted", "│ ") + content + theme.fg("borderMuted", " │") : content;
208
+ };
209
+ const rule = (label: string, position: "top" | "middle" | "bottom" = "middle") => {
210
+ if (!framed) return truncateToWidth(label, width);
211
+ const [left, right] = position === "top" ? ["╭", "╮"] : position === "bottom" ? ["╰", "╯"] : ["├", "┤"];
212
+ const caption = truncateToWidth(label ? `─ ${label} ` : "", width - 2);
213
+ return theme.fg("borderMuted", left) + caption +
214
+ theme.fg("borderMuted", "─".repeat(Math.max(0, width - 2 - visibleWidth(caption))) + right);
215
+ };
216
+ const key = (name: string, action: string) => theme.fg("accent", theme.bold(name)) + theme.fg("muted", ` ${action}`);
217
+ const title = review ? "Turn context · 2/2 Review" : "Turn context · 1/2 Select";
218
+ const out = [rule(theme.fg("accent", theme.bold(title)), "top")];
219
+ if (roomy) out.push(line(theme.fg("muted", review
220
+ ? "PROSE is size-capped. PROSE+TOOLS/FULL are never silently shortened."
221
+ : "Choose each whole turn's context mode. Nothing changes until you confirm.")));
222
+ if (roomy) out.push(line(review ? theme.fg("accent", changeSummary())
223
+ : theme.fg("warning", "[X] Pruned") + theme.fg("muted", " [ ] Prose ") + theme.fg("accent", "[○] Prose+tools [■] Full") +
224
+ theme.fg("dim", " [-] Locked")));
225
+ const readout = sizeReadout(innerWidth);
226
+ out.push(line(theme.fg(readout.color, readout.lines[0])));
227
+ if (roomy) {
228
+ out.push(line(theme.fg(readout.color, readout.lines[1])));
229
+ for (const text of readout.lines.slice(2)) out.push(line(theme.fg(text.startsWith("Size limit") ? "warning" : "muted", text)));
230
+ }
231
+ let footer: string;
232
+ if (review) {
233
+ if (wrappedReview?.width !== innerWidth || wrappedReview.source !== review)
234
+ wrappedReview = { width: innerWidth, source: review, lines: review.flatMap((item) =>
235
+ wrapTextWithAnsi(displayText(item.text), innerWidth).map((text) => ({ ...item, text }))) };
236
+ const wrapped = wrappedReview.lines;
237
+ scroll = Math.max(0, Math.min(scroll, wrapped.length - height));
238
+ out.push(rule(theme.fg("muted", `Change preview · ${scroll + 1}–${Math.min(scroll + height, wrapped.length)} / ${wrapped.length} lines`)));
239
+ for (const item of wrapped.slice(scroll, scroll + height))
240
+ out.push(line(theme.fg(item.kind === "heading" ? "accent" : item.kind === "note" ? "muted" : "text",
241
+ item.kind === "heading" ? theme.bold(item.text) : item.text)));
242
+ footer = "Original session history remains unchanged";
243
+ } else {
244
+ const visible = rows();
245
+ cursor = Math.max(0, Math.min(cursor, visible.length - 1));
246
+ top = Math.max(0, Math.min(top, cursor, visible.length - height));
247
+ if (cursor >= top + height) top = cursor - height + 1;
248
+ out.push(rule(theme.fg("muted", `User turns · ${visible.length ? top + 1 : 0}–${Math.min(top + height, visible.length)} / ${visible.length} rows · ${selected.size} pruned`)));
249
+ for (let i = top; i < Math.min(top + height, visible.length); i++) {
250
+ const { turn, number, child, text } = visible[i], state = stateOf(turn), focused = i === cursor;
251
+ const pointer = theme.fg("accent", focused ? "› " : " ");
252
+ const content = displayText(text).replace(/\s+/g, " ").replace(child ? /^\[([^\]]+)\]:\s*/ : /^\[User\]:\s*/, child ? "$1 " : "");
253
+ let row: string;
254
+ if (child) row = pointer + theme.fg("dim", " └ ") + theme.fg(focused ? "text" : "muted", content);
255
+ else {
256
+ const checkbox = `[${turn.unavailable ? "-" : MODE_SYMBOLS[modeOf(turn)]}]`;
257
+ row = pointer + theme.fg("dim", `${expanded.has(turn.id) ? "▾" : "▸"} `) + theme.fg(state.color, checkbox) + " " +
258
+ (innerWidth >= 24 ? theme.fg("dim", `${String(number).padStart(String(turns.length).length)} `) : "") +
259
+ (innerWidth >= 60 ? theme.fg(state.color, state.label.toUpperCase().padEnd(13)) : "") +
260
+ theme.fg(turn.unavailable ? "dim" : "text", content);
261
+ }
262
+ out.push(line(row, focused));
263
+ }
264
+ if (!visible.length) out.push(line(theme.fg("dim", "No user turns to display.")));
265
+ const current = visible[cursor];
266
+ footer = notice ?? (current ? current.child ? "Agent detail — Space/f changes its whole user turn" : stateOf(current.turn).hint : "Original history stays recoverable");
267
+ }
268
+ out.push(rule(theme.fg("muted", "Controls")));
269
+ out.push(line(review
270
+ ? `${key("↑/↓", "Scroll")} ${theme.fg("accent", theme.bold("PgUp/PgDn"))} ${theme.fg("accent", theme.bold("Home/End"))}`
271
+ : `${key("↑/↓", "Move")} ${key("Space", "Prune")} ${key("f", "Mode")} ${key("←/→", "Fold")}`));
272
+ out.push(line(review
273
+ ? `${key("Enter", "Confirm & save")} ${key("Esc", "Back")}`
274
+ : `${key("Enter", "Review changes")} ${key("Esc", "Cancel")}`));
275
+ out.push(rule(theme.fg("dim", footer), "bottom"));
276
+ return out.map((text) => truncateToWidth(text, width));
277
+ },
278
+ handleInput(data: string) {
279
+ const page = pageSize();
280
+ if (kb.matches(data, "tui.select.cancel")) {
281
+ if (review) { review = undefined; scroll = 0; } else { finish(undefined); return; }
282
+ } else if (review) {
283
+ if (kb.matches(data, "tui.select.confirm")) { finish(selection()); return; }
284
+ if (kb.matches(data, "tui.select.up")) scroll--;
285
+ else if (kb.matches(data, "tui.select.down")) scroll++;
286
+ else if (matchesKey(data, Key.pageUp)) scroll -= page;
287
+ else if (matchesKey(data, Key.pageDown)) scroll += page;
288
+ else if (matchesKey(data, Key.home)) scroll = 0;
289
+ else if (matchesKey(data, Key.end)) scroll = Number.MAX_SAFE_INTEGER;
290
+ } else {
291
+ const visible = rows(), current = visible[cursor];
292
+ notice = undefined;
293
+ if (kb.matches(data, "tui.select.up")) cursor = Math.max(0, cursor - 1);
294
+ else if (kb.matches(data, "tui.select.down")) cursor = Math.min(visible.length - 1, cursor + 1);
295
+ else if (matchesKey(data, Key.pageUp)) cursor = Math.max(0, cursor - page);
296
+ else if (matchesKey(data, Key.pageDown)) cursor = Math.min(visible.length - 1, cursor + page);
297
+ else if (matchesKey(data, Key.home)) cursor = 0;
298
+ else if (matchesKey(data, Key.end)) cursor = visible.length - 1;
299
+ else if (current && matchesKey(data, Key.right)) expanded.add(current.turn.id);
300
+ else if (current && matchesKey(data, Key.left)) {
301
+ expanded.delete(current.turn.id);
302
+ cursor = rows().findIndex((row) => row.turn.id === current.turn.id);
303
+ } else if (current && matchesKey(data, Key.space) && !current.turn.unavailable) {
304
+ setMode(current.turn, selected.has(current.turn.id) ? "prose" : "pruned");
305
+ cursor = visible.findIndex((row) => row.turn.id === current.turn.id);
306
+ } else if (current && matchesKey(data, "f") && !current.turn.unavailable) {
307
+ const cycle: TurnMode[] = current.turn.deferred ? ["pruned", "prose"] : ["pruned", "prose", "tools", "full"];
308
+ const next = cycle[(cycle.indexOf(modeOf(current.turn)) + 1) % cycle.length];
309
+ try {
310
+ if (next === "tools" || next === "full") current.turn.fidelityInfo?.(next);
311
+ setMode(current.turn, next);
312
+ cursor = visible.findIndex((row) => row.turn.id === current.turn.id);
313
+ } catch (error) { notice = error instanceof Error ? error.message : String(error); }
314
+ } else if (kb.matches(data, "tui.select.confirm")) {
315
+ const changes = turns.filter((turn) => !turn.unavailable &&
316
+ (modeOf(turn) !== originalMode(turn) || (!!turn.selected && !selected.has(turn.id))));
317
+ review = [
318
+ ...changes.flatMap((turn): PreviewLine[] => {
319
+ const checked = selected.has(turn.id), mode = modeOf(turn);
320
+ const action = turn.deferred && checked ? "Pending exclusion (recent tail unchanged)"
321
+ : checked ? "Prune" : turn.filtered ? "Restore" : turn.selected && mode === "prose" ? "Cancel pre-flag (keep turn)" : "Change mode";
322
+ const before = originalMode(turn);
323
+ const asContent = (lines: string[]): PreviewLine[] => lines.flatMap((line) => line.split("\n")).map((text) => ({ text, kind: "content" }));
324
+ let content: PreviewLine[];
325
+ if ((before === "tools" || before === "full") && (mode === "pruned" || mode === "prose")) {
326
+ let previous: string[];
327
+ try { previous = turn.fidelityInfo?.(before).lines ?? turn.lines; }
328
+ catch (error) { previous = [`Original native group unavailable: ${String(error)}`]; }
329
+ content = [{ text: "Current native content being removed:", kind: "note" }, ...asContent(previous)];
330
+ if (mode === "prose") content.push({ text: "Retained as PROSE (subject to the cap):", kind: "note" }, ...asContent(turn.lines));
331
+ } else content = asContent(turn.deferred ? [turn.label] : mode === "tools" || mode === "full" ? turn.fidelityInfo?.(mode).lines ?? turn.lines : turn.lines);
332
+ return [{ text: `${action}: turn ${turn.id} (${MODE_LABELS[before]} → ${MODE_LABELS[mode]})`, kind: "heading" },
333
+ ...content, { text: "", kind: "content" }];
334
+ }),
335
+ ...(changes.length ? [] : [{ kind: "note" as const, text: selected.size ? "No changes; previously filtered turns remain excluded."
336
+ : "No filtering changes. Keep the current checkpoint." }])];
337
+ scroll = 0;
338
+ }
339
+ }
340
+ tui.requestRender();
341
+ },
342
+ invalidate() { wrappedReview = undefined; },
343
+ dispose() { disposed = true; generation++; signal.removeEventListener("abort", abort); },
344
+ };
345
+ });
346
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foliox/transparent-compact-pi",
3
- "version": "0.9.3",
3
+ "version": "0.10.0",
4
4
  "description": "Deterministic, verbatim-preserving compaction for Pi, with session-backed subagent context recovery.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -45,6 +45,7 @@
45
45
  "@earendil-works/pi-ai": "*",
46
46
  "@earendil-works/pi-agent-core": "*",
47
47
  "@earendil-works/pi-coding-agent": "*",
48
+ "@earendil-works/pi-tui": "*",
48
49
  "typebox": "*"
49
50
  },
50
51
  "engines": {
@@ -12,11 +12,6 @@ history, including recorded tool outputs and your reasoning, is preserved in the
12
12
  session and can be retrieved. Retained startup reads and the uncompacted tail
13
13
  remain available as evidence; recover only hidden information needed for the task.
14
14
 
15
- Under size pressure, `tools-tightened` on its own marks reduced tool previews
16
- or grouped tool-only lines, without omitted conversation prose or calls. If
17
- `trimmed` is also present, content was omitted or user text was shortened. Neither means that the original evidence
18
- was never recorded; recover task-relevant missing detail through the tools below.
19
-
20
15
  Use the recovery tools for history established by this conversation or its checkpoint,
21
16
  not project discovery, requirements never supplied, other sessions, or abandoned branches.
22
17
  For unfamiliar project details or missing requirements, inspect project files or