@foliox/transparent-compact-pi 0.9.3 → 0.11.1

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,251 @@
1
+ import path from 'node:path';
2
+ import { parseShell as parse } from './parse.mjs';
3
+
4
+ const PATH_COMMANDS = new Set(['cat', 'head', 'tail', 'wc', 'ls', 'tree', 'stat', 'file', 'du',
5
+ 'cp', 'mv', 'install', 'rm', 'mkdir', 'touch', 'tee', 'diff', 'cmp', 'readlink', 'realpath']);
6
+ const SUBCOMMANDS = new Set(['git', 'cargo', 'npm', 'pnpm', 'yarn', 'go', 'docker', 'tmux', 'uv']);
7
+ const VALUE_FLAGS = new Set(['-m', '-j', '--max-count', '--context',
8
+ '--glob', '-g', '--include', '--exclude', '--exclude-dir', '--color', '--max-time', '--connect-timeout',
9
+ '-H', '--header', '-w', '--write-out', '-X', '--request', '-u', '--user', '--features', '--bin',
10
+ '--dt', '--duration', '--record-every', '--target', '--model', '--provider']);
11
+ const PATH_FLAGS = new Set(['-o', '--output', '-T', '--upload-file', '-K', '--config',
12
+ '--cacert', '--cert', '--key', '--output-dir', '--directory', '--manifest-path']);
13
+ const SCRIPT_FLAGS = new Set(['-c', '-e', '--eval']);
14
+ const GIT_PATH_COMMANDS = new Set(['add', 'diff', 'status', 'restore', 'rm', 'mv', 'ls-files', 'checkout']);
15
+ const DATA_FLAGS = new Set(['-d', '--data', '--data-binary', '--data-raw', '--data-urlencode']);
16
+ const INTERPRETER = /^(?:python[\d.]*|node|ruby|perl|bash|sh)$/;
17
+ const MAX_AST_NODES = 2048;
18
+ const MAX_BODY_MENTIONS = 8;
19
+ const looksLikeLocation = value => !!value && !/[\n\r\x00]/.test(value) &&
20
+ (/^[a-z][a-z\d+.-]*:\/\//i.test(value) ||
21
+ (!/[;|<>()=:]/.test(value) && (/^(?:\.{1,2}(?:\/|$)|\/|~\/)/.test(value) ||
22
+ /\//.test(value) || /\.[a-z][a-z\d_-]{0,12}$/i.test(value))));
23
+
24
+ // AST positions are UTF-8 byte offsets, not JS string indices.
25
+ const sourceText = (source, node) => source.subarray(node.Pos.Offset, node.End.Offset).toString('utf8');
26
+ const expression = (source, node) => {
27
+ const raw = sourceText(source, node);
28
+ return /^(["']).*\1$/s.test(raw) ? raw.slice(1, -1) : raw;
29
+ };
30
+ function literal(word) {
31
+ if (!word?.Parts) return null;
32
+ let out = '';
33
+ for (const part of word.Parts) {
34
+ if (part.Type === 'Lit') out += (part.Value ?? '').replace(/\\([^\n])/g, '$1').replace(/\\\n/g, '');
35
+ else if (part.Type === 'SglQuoted' && !part.Dollar) out += part.Value ?? '';
36
+ else if (part.Type === 'DblQuoted' && !part.Dollar) {
37
+ let text = '';
38
+ for (const item of part.Parts ?? []) {
39
+ if (item.Type !== 'Lit') return null;
40
+ text += (item.Value ?? '').replace(/\\([$`"\\])/g, '$1').replace(/\\\n/g, '');
41
+ }
42
+ out += text;
43
+ } else return null;
44
+ }
45
+ return out;
46
+ }
47
+
48
+ /** Pure static description: never runs commands, opens paths, or expands globs. */
49
+ export async function shellSkeleton(command, locations) {
50
+ const ast = await parse(command);
51
+ const source = Buffer.from(command);
52
+ const refs = new Set();
53
+ let visited = 0;
54
+ const tick = () => { if (++visited > MAX_AST_NODES) throw new Error('AST node budget exceeded'); };
55
+ const location = (value, state, kind = 'path') => {
56
+ const entry = locations.ref(value, state.cwd, kind);
57
+ refs.add(entry.id);
58
+ return entry.id;
59
+ };
60
+ const join = statements => statements.filter(Boolean).join('; ');
61
+ const copy = state => ({ ...state });
62
+
63
+ function mentions(body, state) {
64
+ const found = new Set();
65
+ // Literal-looking quoted strings only; intentionally not a Python/JS parser.
66
+ for (const match of body.slice(0, 65536).matchAll(/(["'])([^"'\\\n]*(?:\\.[^"'\\\n]*)*)\1/g)) {
67
+ const value = match[2];
68
+ if (looksLikeLocation(value)) found.add(value);
69
+ if (found.size > MAX_BODY_MENTIONS) break;
70
+ }
71
+ const selected = [...found].slice(0, MAX_BODY_MENTIONS).map(value => location(value, state));
72
+ return selected.length ? ` mentions ${selected.join(',')}${found.size > MAX_BODY_MENTIONS ? ',…' : ''}` : '';
73
+ }
74
+
75
+ function nested(node, state) {
76
+ if (!node || typeof node !== 'object') return [];
77
+ // Upstream JSON includes several source-position fields per node. They are
78
+ // coordinates, not nested syntax, and must not consume the AST node budget.
79
+ if (typeof node.Offset === 'number' && typeof node.Line === 'number' && typeof node.Col === 'number') return [];
80
+ tick();
81
+ if (node.Type === 'CmdSubst' || node.Type === 'ProcSubst')
82
+ return [`${node.Type === 'CmdSubst' ? '$(' : node.Op}${list(node.Stmts, copy(state))})`];
83
+ return Object.values(node).flatMap(value => Array.isArray(value)
84
+ ? value.flatMap(item => nested(item, state)) : value && typeof value === 'object' ? nested(value, state) : []);
85
+ }
86
+
87
+ function call(node, state) {
88
+ const words = node.Args ?? [];
89
+ const values = words.map(literal);
90
+ const name = values[0] === null ? '[dynamic command]' : path.posix.basename(values[0] ?? '[assign]');
91
+ if (name.length > 160) throw new Error('command name exceeds display budget');
92
+ let text = name;
93
+ if (values[0]?.includes('/')) text += `[${location(values[0], state)}]`;
94
+ if (name === 'timeout' && /^\d+(?:\.\d+)?[smhd]?$/.test(values[1] ?? '') && words.length > 2)
95
+ return `${text} ${call({ ...node, Args: words.slice(2) }, state)}`;
96
+ if (name === 'uv' && values[1] === 'run' && values[2] && !values[2].startsWith('-'))
97
+ return `${text} run ${call({ ...node, Args: words.slice(2) }, state)}`;
98
+ if (name === 'env' && values[1] && !values[1].startsWith('-')) {
99
+ const start = values.findIndex((value, index) => index > 0 && value && !value.includes('='));
100
+ if (start > 0) return `${text} ${call({ ...node, Args: words.slice(start) }, state)}`;
101
+ }
102
+ let pattern = ['sed', 'awk', 'grep', 'rg'].includes(name);
103
+ let afterDash = false, needsSubcommand = SUBCOMMANDS.has(name), verb = null;
104
+ let cdTarget = null;
105
+ for (let i = 1; i < words.length; i++) {
106
+ const value = values[i], raw = expression(source, words[i]);
107
+ if (value === '--') { afterDash = true; continue; }
108
+ if (value?.startsWith('-') && !afterDash) {
109
+ if (name === 'find') break; // Roots precede the find expression.
110
+ const equal = value.indexOf('=');
111
+ const flag = equal < 0 ? value : value.slice(0, equal);
112
+ const argument = equal < 0 ? values[i + 1] : value.slice(equal + 1);
113
+ if (INTERPRETER.test(name) && (SCRIPT_FLAGS.has(flag) || (name === 'node' && flag === '-p'))) {
114
+ if (argument !== undefined) {
115
+ text += ` [inline${mentions(argument ?? sourceText(source, words[i + 1]), state)}]`;
116
+ if (equal < 0) i++;
117
+ }
118
+ } else if ((PATH_FLAGS.has(flag) && (!/^-[oTK]$/.test(flag) || name === 'curl')) ||
119
+ (flag === '-f' && ['sed', 'awk', 'grep', 'rg'].includes(name))) {
120
+ if (argument !== undefined) text += ` ${location(argument ?? expression(source, words[i + 1]), state)}`;
121
+ if (equal < 0) i++;
122
+ if (flag === '-f') pattern = false;
123
+ } else if (DATA_FLAGS.has(flag) && name === 'curl') {
124
+ if (argument?.startsWith('@')) text += ` ${location(argument.slice(1), state)}`;
125
+ if (equal < 0) i++;
126
+ } else if (flag === '-e' && pattern) {
127
+ pattern = false;
128
+ if (equal < 0) i++;
129
+ } else if (VALUE_FLAGS.has(flag) || (['-n', '-c'].includes(flag) && ['head', 'tail'].includes(name)) ||
130
+ (['-A', '-B', '-C'].includes(flag) && ['grep', 'rg'].includes(name)) ||
131
+ (flag === '-c' && name === 'git') || (flag === '-t' && name === 'tmux') || (flag === '-v' && name === 'awk')) {
132
+ if (equal < 0) i++;
133
+ }
134
+ continue;
135
+ }
136
+ if (needsSubcommand && value && /^[\w-]+$/.test(value)) {
137
+ text += ` ${value}`;
138
+ needsSubcommand = false;
139
+ verb = value;
140
+ } else if (pattern) pattern = false;
141
+ else if (name === 'curl' && value && /^(?:[a-z][a-z\d+.-]*:\/\/|(?:[\w-]+\.)+[a-z]{2,}(?:[:/]|$)|localhost(?=[:/]|$))/i.test(value))
142
+ text += ` ${location(value, state, 'url')}`;
143
+ else if (name === 'git' && value && /^[^:]+:.+/.test(value) && verb === 'show')
144
+ text += ` ${location(value, state, 'git')}`;
145
+ else if (value !== '-' && value !== null && (name === 'cd' || PATH_COMMANDS.has(name) ||
146
+ ['sed', 'awk', 'grep', 'rg', 'find'].includes(name) ||
147
+ (name === 'git' ? afterDash || (GIT_PATH_COMMANDS.has(verb) && (verb === 'add' || looksLikeLocation(value)))
148
+ : looksLikeLocation(value)))) {
149
+ text += ` ${location(value, state)}`;
150
+ if (name === 'cd') cdTarget = value;
151
+ } else if (value === null && looksLikeLocation(raw) && !raw.includes('$(') && !raw.includes('`')) {
152
+ text += ` ${location(raw, state)}`;
153
+ }
154
+ }
155
+ // Substitutions may be in arguments that were otherwise discarded as flags/patterns.
156
+ for (const word of words) for (const expansion of nested(word, state)) text += ` ${expansion}`;
157
+ for (const assignment of node.Assigns ?? []) {
158
+ for (const expansion of nested(assignment, state)) text += ` ${expansion}`;
159
+ }
160
+ if (name === 'cd') {
161
+ state.cwd = cdTarget && !/[$`*?{}\[\]~]/.test(cdTarget) && (state.cwd || cdTarget.startsWith('/'))
162
+ ? path.posix.resolve(state.cwd ?? '/', cdTarget) : null;
163
+ }
164
+ return text;
165
+ }
166
+
167
+ function stmt(node, state) {
168
+ tick();
169
+ if (!node) return '';
170
+ const initial = copy(state);
171
+ let text = render(node.Cmd, node.Background ? copy(state) : state);
172
+ if (node.Negated) text = `! ${text}`;
173
+ // Redirections resolve before a command changes cwd.
174
+ for (const redirect of node.Redirs ?? []) {
175
+ if (redirect.Hdoc) {
176
+ const body = literal(redirect.Hdoc) ?? sourceText(source, redirect.Hdoc);
177
+ text += ` [body${mentions(body, initial)}]`;
178
+ for (const expansion of nested(redirect.Hdoc, initial)) text += ` ${expansion}`;
179
+ } else {
180
+ const value = literal(redirect.Word), raw = expression(source, redirect.Word);
181
+ const expansions = nested(redirect.Word, initial);
182
+ const fd = redirect.N?.Value ?? '';
183
+ if (redirect.Op === '<<<') {
184
+ text += ` <<<[stdin${mentions(value ?? raw, initial)}]`;
185
+ } else {
186
+ const destination = /[<>]&/.test(redirect.Op) && /^\d+-?$|^-$/.test(value ?? '')
187
+ ? value : value === null && expansions.length ? '[dynamic]' : location(value ?? raw, initial);
188
+ text += ` ${fd}${redirect.Op}${destination}`;
189
+ }
190
+ for (const expansion of expansions) text += ` ${expansion}`;
191
+ }
192
+ }
193
+ if (node.Background) text += ' &';
194
+ return text;
195
+ }
196
+
197
+ function list(nodes = [], state) { return join(nodes.map(node => stmt(node, state))); }
198
+ function render(node, state, type = node?.Type) {
199
+ tick();
200
+ if (!node) return '[assignment]';
201
+ switch (type) {
202
+ case 'CallExpr': return call(node, state);
203
+ case 'BinaryCmd': {
204
+ const before = copy(state), leftState = copy(state);
205
+ const left = stmt(node.X, leftState);
206
+ const rightState = copy(node.Op === '&&' ? leftState : before);
207
+ const right = stmt(node.Y, rightState);
208
+ // An enclosing && RHS is reached only after the left chain succeeded.
209
+ // Track that lexical success-path cwd; no claim about observed execution.
210
+ state.cwd = node.Op === '&&' ? rightState.cwd : leftState.cwd === rightState.cwd ? leftState.cwd : null;
211
+ if (node.Op === '|' || node.Op === '|&') state.cwd = before.cwd;
212
+ return `${left} ${node.Op} ${right}`;
213
+ }
214
+ case 'Subshell': return `(${list(node.Stmts, copy(state))})`;
215
+ case 'Block': return `{${list(node.Stmts, state)}}`;
216
+ case 'IfClause': {
217
+ const yes = copy(state), no = copy(state);
218
+ const condition = list(node.Cond, yes);
219
+ const then = list(node.Then, yes);
220
+ // Else is a concrete *IfClause, so upstream JSON omits its Type.
221
+ const otherwise = node.Else ? render(node.Else, no, 'IfClause') : '';
222
+ state.cwd = yes.cwd === no.cwd ? yes.cwd : null;
223
+ return condition ? `if{${condition}} then{${then}}${otherwise ? ` else{${otherwise}}` : ''}` : then;
224
+ }
225
+ case 'ForClause': {
226
+ const loopState = copy(state);
227
+ const body = list(node.Do, loopState);
228
+ if (loopState.cwd !== state.cwd) state.cwd = null;
229
+ return `for{${body}}`;
230
+ }
231
+ case 'WhileClause': {
232
+ const local = copy(state), condition = list(node.Cond, local), body = list(node.Do, local);
233
+ if (local.cwd !== state.cwd) state.cwd = null;
234
+ return `${node.Until ? 'until' : 'while'}{${condition}} do{${body}}`;
235
+ }
236
+ case 'CaseClause': {
237
+ const body = (node.Items ?? []).map(item => `{${list(item.Stmts, copy(state))}}`).join('; ');
238
+ state.cwd = null;
239
+ return `case{${body}}`;
240
+ }
241
+ case 'FuncDecl': return `function ${node.Name.Value}{${stmt(node.Body, { cwd: null })}}`;
242
+ case 'TimeClause': return `time ${stmt(node.Stmt, state)}`;
243
+ case 'TestClause': return '[[test]]';
244
+ case 'ArithmCmd': return '((arithmetic))';
245
+ default: throw new Error(`unsupported AST node: ${type}`);
246
+ }
247
+ }
248
+
249
+ const text = list(ast.Stmts, { cwd: locations.cwd });
250
+ return { text, refs: [...refs] };
251
+ }
@@ -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
+ }