@foliox/transparent-compact-pi 0.8.9 → 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.
- package/CHANGELOG.md +146 -2
- package/README.md +135 -46
- package/docs/DESIGN.md +309 -34
- package/extensions/index.ts +731 -135
- package/extensions/lib/checkpoint-cap.ts +182 -0
- package/extensions/lib/turn-context.ts +209 -0
- package/extensions/lib/turn-filter.ts +346 -0
- package/package.json +2 -1
- package/skills/context-retrieval/SKILL.md +22 -5
|
@@ -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.
|
|
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": {
|
|
@@ -25,7 +25,7 @@ This skill pairs with the `@foliox/transparent-compact-pi` extension, which prov
|
|
|
25
25
|
|
|
26
26
|
- **Verbatim compaction** — a deterministic checkpoint retains user messages, assistant prose, and compact tool-call signatures. Thinking and most tool outputs are removed from the active model context, not from the raw session history. Selected startup read outputs remain verbatim in the checkpoint or uncompacted tail. Earlier spans are re-rendered flat, with recovery guidance before them and an evidence-boundary warning after them. Persistent task-relevant recovery reminders and a recap follow the retained tail; later compactions replace the old generated reminders rather than duplicating them. An inherited opaque base is kept when needed.
|
|
27
27
|
- **`context_lookup`** — the preferred first step for this recovery workflow: a subagent searches the full raw session branch in its **own** context and returns relevant findings. At lookup time, the extension mechanically renders the branch into entry-anchored text with an authoritative entry/section index, in memory.
|
|
28
|
-
- **Bounded
|
|
28
|
+
- **Bounded direct tools** — use `context_show_entry` for a specific detail hidden by compaction at a known ENTRY id returned by a recovery tool. If lookup findings are incomplete, use `context_list_entries` to locate an entry, `context_grep` to find a narrow passage, or `context_show_entry` to inspect a known entry. Their raw results enter this conversation; retrieve only what the question needs. For recovery of details hidden by compaction, these are the permitted direct tools, not filesystem access to session files.
|
|
29
29
|
|
|
30
30
|
Pi normally saves sessions under `~/.pi/agent/sessions/`; custom session locations also work. In-memory sessions retain history only while the process lives and cannot be resumed after exit.
|
|
31
31
|
|
|
@@ -37,6 +37,10 @@ If `context_lookup` is not in your tool list, say that subagent recovery is unav
|
|
|
37
37
|
- You are unsure where an earlier finding came from, what a command actually printed, or why you reached a conclusion.
|
|
38
38
|
- Earlier notes conflict with new evidence and you need to check the historical evidence behind them.
|
|
39
39
|
|
|
40
|
+
Tool stubs and file lists do not preserve the full supporting material. Most output
|
|
41
|
+
and detailed payloads are omitted. Inline observations are historical, not verification
|
|
42
|
+
of unshown details or current state. Unlabelled calls do not establish exit 0 or passing tests.
|
|
43
|
+
|
|
40
44
|
Ask `context_lookup` a **specific historical question** to recover hidden supporting
|
|
41
45
|
evidence. This can avoid repeating slow or unreliable research. For example:
|
|
42
46
|
"Where did our earlier Holi 2026 date come from: a
|
|
@@ -55,6 +59,13 @@ published source or our own computation? Include the observed output and ENTRY i
|
|
|
55
59
|
context_lookup({ question: "What exact error did the earlier test run return for the N=7 case? Include the ENTRY id and observed tool output." })
|
|
56
60
|
```
|
|
57
61
|
|
|
62
|
+
You may include an ENTRY id from an earlier recovery result in the question to
|
|
63
|
+
narrow the search. If you already know the ENTRY id and only need a specific
|
|
64
|
+
passage, `context_show_entry` can read that entry directly. Prefer
|
|
65
|
+
`context_lookup` when search or interpretation is needed. For post-compaction
|
|
66
|
+
recovery, continue paging only if the requested detail is missing, incomplete, or
|
|
67
|
+
needs more context to resolve ambiguity; stop once the question is answered.
|
|
68
|
+
|
|
58
69
|
For `context_lookup`, only supply `question`. Lookup covers all earlier compactions on the current branch automatically. It does **not** search abandoned branches or unrelated sessions. If the detail is absent, report that limitation instead of claiming it was recovered or widening this recovery search through filesystem tools.
|
|
59
70
|
|
|
60
71
|
A study harness may configure `MECH_COMPACT_LOOKUP_SESSION_FILE` to make the extension search a full session rather than a pruned fork. This is extension configuration, not a tool argument or a file the main agent should read. Do not discover or change the override to broaden a lookup.
|
|
@@ -69,10 +80,12 @@ the same recovery episode. Narration and thinking do not reset it either. Only
|
|
|
69
80
|
a tool result outside the four recovery tools, a user message, or a bash
|
|
70
81
|
execution resets the limit.
|
|
71
82
|
|
|
72
|
-
Search responses are pages, not necessarily complete evidence.
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
83
|
+
Search responses are pages, not necessarily complete evidence. Continue only
|
|
84
|
+
when the needed detail is missing, incomplete, or needs more context to resolve
|
|
85
|
+
ambiguity; do not exhaust every match or entry merely because a continuation is
|
|
86
|
+
available. A partial search does not establish that something never happened.
|
|
87
|
+
Keep other parameters unchanged and use all continuation parameters printed at
|
|
88
|
+
the end of a limited page:
|
|
76
89
|
|
|
77
90
|
- Listings and entry retrieval: `offset` counts characters (UTF-16 code units)
|
|
78
91
|
in the rendered listing or entry, starting at 0.
|
|
@@ -80,6 +93,10 @@ all continuation parameters printed at the end of a limited page:
|
|
|
80
93
|
the context of an oversized match. Grep reports how many matches remain.
|
|
81
94
|
- `maxLines` and `maxMatches` limit a page, not the backing history. Increasing
|
|
82
95
|
them does not remove the character guard. Use the reported cursor instead.
|
|
96
|
+
- `context_show_entry` defaults to a single entry. `includeRelated=true` adds
|
|
97
|
+
unambiguously matched tool call/result entries in chronological order. Keep
|
|
98
|
+
this flag unchanged when paging. A result expands to its originating assistant,
|
|
99
|
+
not sibling outputs; an assistant expands to its matched results.
|
|
83
100
|
|
|
84
101
|
Listing/grep cursors also report `throughEntry`: retain this original last-entry
|
|
85
102
|
id on subsequent pages, so newly appended calls/results cannot keep expanding
|