@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,182 @@
|
|
|
1
|
+
/** Pure checkpoint presentation and progressive size guard. No Pi, filesystem,
|
|
2
|
+
* model calls, or session mutation. Canonical span lines/records are never edited.
|
|
3
|
+
*/
|
|
4
|
+
export const TOOL_PREFIX = "[Tools]: ";
|
|
5
|
+
export const FILTER_MARKER = "[Turn manually filtered]";
|
|
6
|
+
export const NORMAL_PREVIEW_CHARS = 160;
|
|
7
|
+
export const TIGHTENED_ATTR = ' tools-tightened="true"';
|
|
8
|
+
|
|
9
|
+
// Encoded display fragments, NOT full commands or executable arguments.
|
|
10
|
+
// Retain the original prefix for every smaller head-only preview.
|
|
11
|
+
export interface CommandPreview { head: string; truncated?: boolean }
|
|
12
|
+
export interface ToolStub {
|
|
13
|
+
prefix: string;
|
|
14
|
+
command?: CommandPreview;
|
|
15
|
+
suffix: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ToolLine {
|
|
18
|
+
index: number;
|
|
19
|
+
calls: ToolStub[];
|
|
20
|
+
/** Both adjacent messages must be tool-only before prefixes may be folded. */
|
|
21
|
+
mergeable: boolean;
|
|
22
|
+
}
|
|
23
|
+
export interface ToolLines { version: 2; lines: ToolLine[] }
|
|
24
|
+
export interface SpanContent { lines: string[]; tools?: ToolLines; protectedLines?: number[] }
|
|
25
|
+
export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[] }
|
|
26
|
+
|
|
27
|
+
function headPrefix(text: string, max: number): string {
|
|
28
|
+
let end = Math.min(text.length, max);
|
|
29
|
+
if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
|
|
30
|
+
return text.slice(0, end);
|
|
31
|
+
}
|
|
32
|
+
export function commandPreview(encoded: string): CommandPreview {
|
|
33
|
+
return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
|
|
34
|
+
: { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
|
|
35
|
+
}
|
|
36
|
+
export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
|
|
37
|
+
return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
|
|
38
|
+
}
|
|
39
|
+
export function renderToolStub(stub: ToolStub, max = NORMAL_PREVIEW_CHARS): string {
|
|
40
|
+
return stub.prefix + (stub.command ? renderCommand(stub.command, max) : "") + stub.suffix;
|
|
41
|
+
}
|
|
42
|
+
export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS): string {
|
|
43
|
+
return TOOL_PREFIX + calls.map((call) => renderToolStub(call, max)).join("; ");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Stored records are optional/versioned. Require exact canonical round-tripping
|
|
47
|
+
// before using one; missing or invalid records leave text opaque.
|
|
48
|
+
function toolRecords(span: SpanContent): Map<number, ToolLine> {
|
|
49
|
+
const records = new Map<number, ToolLine>();
|
|
50
|
+
try {
|
|
51
|
+
const tools = span.tools;
|
|
52
|
+
if (!tools || tools.version !== 2 || !Array.isArray(tools.lines)) return records;
|
|
53
|
+
const seen = new Set<number>();
|
|
54
|
+
for (const record of tools.lines) {
|
|
55
|
+
if (!record || !Number.isSafeInteger(record.index) || record.index < 0 || record.index >= span.lines.length) continue;
|
|
56
|
+
if (seen.has(record.index)) { records.delete(record.index); continue; }
|
|
57
|
+
seen.add(record.index);
|
|
58
|
+
if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length) continue;
|
|
59
|
+
const valid = record.calls.every((call) => {
|
|
60
|
+
if (!call || typeof call.prefix !== "string" || typeof call.suffix !== "string") return false;
|
|
61
|
+
const p = call.command;
|
|
62
|
+
if (p === undefined) return true;
|
|
63
|
+
if (!p || typeof p.head !== "string") return false;
|
|
64
|
+
return p.head.length <= NORMAL_PREVIEW_CHARS &&
|
|
65
|
+
(p.truncated === undefined || typeof p.truncated === "boolean") &&
|
|
66
|
+
(p.truncated !== true || p.head.length >= NORMAL_PREVIEW_CHARS - 1);
|
|
67
|
+
});
|
|
68
|
+
if (valid && renderToolLine(record.calls) === span.lines[record.index]) records.set(record.index, record);
|
|
69
|
+
}
|
|
70
|
+
} catch { return new Map(); }
|
|
71
|
+
return records;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
interface Row {
|
|
75
|
+
index: number;
|
|
76
|
+
protected: boolean;
|
|
77
|
+
text: string;
|
|
78
|
+
calls?: ToolStub[];
|
|
79
|
+
mergeable: boolean;
|
|
80
|
+
preview: number;
|
|
81
|
+
foldPrefix: boolean;
|
|
82
|
+
tightened: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Stop as soon as the budget fits: 120-char previews, then 80, adjacent
|
|
86
|
+
* tool-only prefixes, and finally the historical destructive cap.
|
|
87
|
+
* Every rung walks oldest first, across all spans (not just the new one).
|
|
88
|
+
*/
|
|
89
|
+
export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
|
|
90
|
+
const tightened = spans.map(() => false), trimmed = spans.map(() => false);
|
|
91
|
+
let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0);
|
|
92
|
+
if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed };
|
|
93
|
+
const states = spans.map((span) => {
|
|
94
|
+
const records = toolRecords(span);
|
|
95
|
+
return span.lines.map((text, index): Row => {
|
|
96
|
+
const record = records.get(index);
|
|
97
|
+
return { index, protected: span.protectedLines?.includes(index) ?? false, text, calls: record?.calls.slice(), mergeable: record?.mergeable ?? false,
|
|
98
|
+
preview: NORMAL_PREVIEW_CHARS, foldPrefix: false, tightened: false };
|
|
99
|
+
});
|
|
100
|
+
});
|
|
101
|
+
const joined = (rows: Row[], i: number) => i > 0 && rows[i].foldPrefix && rows[i].calls && rows[i - 1].calls &&
|
|
102
|
+
rows[i].mergeable && rows[i - 1].mergeable && rows[i].index === rows[i - 1].index + 1;
|
|
103
|
+
const measure = () => states.reduce((n, rows) => n + rows.reduce((s, row, i) =>
|
|
104
|
+
s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0);
|
|
105
|
+
const finish = (): CappedSpans => ({
|
|
106
|
+
lines: states.map((rows, span) => {
|
|
107
|
+
const lines: string[] = [];
|
|
108
|
+
for (let i = 0; i < rows.length; i++) {
|
|
109
|
+
const row = rows[i];
|
|
110
|
+
if (joined(rows, i)) lines[lines.length - 1] += `; ${row.text.slice(TOOL_PREFIX.length)}`;
|
|
111
|
+
else lines.push(row.text);
|
|
112
|
+
if (row.tightened || joined(rows, i)) tightened[span] = true;
|
|
113
|
+
}
|
|
114
|
+
return lines;
|
|
115
|
+
}), tightened, trimmed,
|
|
116
|
+
});
|
|
117
|
+
const render = (row: Row) => renderToolLine(row.calls!, row.preview);
|
|
118
|
+
const update = (row: Row) => {
|
|
119
|
+
const text = render(row);
|
|
120
|
+
if (text.length < row.text.length) {
|
|
121
|
+
size += text.length - row.text.length;
|
|
122
|
+
row.text = text;
|
|
123
|
+
row.tightened = true;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
for (const max of [120, 80]) {
|
|
127
|
+
for (const rows of states) for (const row of rows) {
|
|
128
|
+
if (!row.calls?.some((call) => call.command)) continue;
|
|
129
|
+
row.preview = max;
|
|
130
|
+
update(row);
|
|
131
|
+
if (size <= budget) return finish();
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (const rows of states) for (let i = 1; i < rows.length; i++) {
|
|
135
|
+
const row = rows[i];
|
|
136
|
+
row.foldPrefix = true;
|
|
137
|
+
if (joined(rows, i)) size -= TOOL_PREFIX.length - 1;
|
|
138
|
+
if (size <= budget) return finish();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// No presentation-only rung fits. Keep calls independently removable even
|
|
142
|
+
// when their prefixes are folded; never cap a giant concatenated tool line.
|
|
143
|
+
for (let span = 0; span < states.length && size > budget; span++) {
|
|
144
|
+
const rows = states[span];
|
|
145
|
+
for (let i = 0; i < rows.length && size > budget;) {
|
|
146
|
+
const row = rows[i];
|
|
147
|
+
if (row.protected || row.text.startsWith("[User]:") || row.text === FILTER_MARKER) { i++; continue; }
|
|
148
|
+
if (row.calls && row.calls.length > 1) {
|
|
149
|
+
row.calls.shift();
|
|
150
|
+
row.text = render(row);
|
|
151
|
+
} else rows.splice(i, 1);
|
|
152
|
+
trimmed[span] = true;
|
|
153
|
+
size = measure();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// Stub each oversized user line once. Canonical lines remain untouched, so
|
|
157
|
+
// later checkpoints never shorten an already shortened presentation again.
|
|
158
|
+
for (let span = 0; span < states.length && size > budget; span++) {
|
|
159
|
+
for (const row of states[span]) {
|
|
160
|
+
if (size <= budget) break;
|
|
161
|
+
const line = row.text;
|
|
162
|
+
if (row.protected || !line.startsWith("[User]:") || line.length <= 120) continue;
|
|
163
|
+
let end = 120;
|
|
164
|
+
if (/[\uD800-\uDBFF]/.test(line[end - 1])) end--;
|
|
165
|
+
const stub = `${line.slice(0, end)}…[truncated +${line.length - end} chars — use context_lookup]`;
|
|
166
|
+
if (stub.length >= line.length) continue;
|
|
167
|
+
row.text = stub;
|
|
168
|
+
trimmed[span] = true;
|
|
169
|
+
size = measure();
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
for (let span = 0; span < states.length && size > budget; span++) {
|
|
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);
|
|
177
|
+
trimmed[span] = true;
|
|
178
|
+
size = measure();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return finish();
|
|
182
|
+
}
|
|
@@ -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
|
+
}
|