@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.
- package/CHANGELOG.md +75 -0
- package/README.md +80 -174
- package/docs/DESIGN.md +247 -16
- package/extensions/index.ts +561 -119
- package/extensions/lib/checkpoint-cap.ts +38 -33
- package/extensions/lib/tool-stubs/display.mjs +21 -0
- package/extensions/lib/tool-stubs/inputs.mjs +12 -0
- package/extensions/lib/tool-stubs/locations.mjs +42 -0
- package/extensions/lib/tool-stubs/parse.mjs +39 -0
- package/extensions/lib/tool-stubs/parser/LICENSE.Go +27 -0
- package/extensions/lib/tool-stubs/parser/LICENSE.mvdan-sh +27 -0
- package/extensions/lib/tool-stubs/parser/NOTICE.md +13 -0
- package/extensions/lib/tool-stubs/parser/PATENTS.Go +22 -0
- package/extensions/lib/tool-stubs/parser/build.json +12 -0
- package/extensions/lib/tool-stubs/parser/go.mod +5 -0
- package/extensions/lib/tool-stubs/parser/go.sum +2 -0
- package/extensions/lib/tool-stubs/parser/main.go +36 -0
- package/extensions/lib/tool-stubs/parser/shell.wasm +0 -0
- package/extensions/lib/tool-stubs/parser/wasm_exec.js +575 -0
- package/extensions/lib/tool-stubs/renderer.mjs +53 -0
- package/extensions/lib/tool-stubs/shell.mjs +251 -0
- package/extensions/lib/turn-context.ts +209 -0
- package/extensions/lib/turn-filter.ts +346 -0
- package/package.json +7 -2
- package/skills/context-retrieval/SKILL.md +0 -5
package/extensions/index.ts
CHANGED
|
@@ -33,8 +33,17 @@ import type { Message as AiMessage, Model, Tool as AiTool } from "@earendil-work
|
|
|
33
33
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
34
34
|
import { buildSessionProjection, SessionManager } from "@earendil-works/pi-coding-agent";
|
|
35
35
|
import type { ExtensionAPI, ExtensionContext, ModelRegistry, SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
36
|
-
import { capSpans,
|
|
37
|
-
import
|
|
36
|
+
import { capSpans, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
|
|
37
|
+
import { ToolRenderer, TOOL_DISPLAY_EXPLANATION } from "./lib/tool-stubs/renderer.mjs";
|
|
38
|
+
import { checkpointPath } from "./lib/tool-stubs/display.mjs";
|
|
39
|
+
import { Locations } from "./lib/tool-stubs/locations.mjs";
|
|
40
|
+
import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
|
|
41
|
+
import { FILTER_EXPLANATION, PREFLAG_ENTRY, AUTO_FILTER_ENTRY, FILTER_REVISION_ENTRY, autoFilterEnabled, preflaggedTurns,
|
|
42
|
+
filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
|
|
43
|
+
import type { FilterTurn, TurnSpan } from "./lib/turn-filter.js";
|
|
44
|
+
import { FIDELITY_EXPLANATION, fidelityMessages, fidelitySpans, locateSlots, expandCheckpoint,
|
|
45
|
+
messageTokens, previewMessages, checkCheckpointBudget, checkContextBudget, isExpandedCheckpoint, checkpointContextMessages, retainedTailMessages, estimateContext } from "./lib/turn-context.js";
|
|
46
|
+
import type { ContextEstimate, NoticeTokens, TurnFidelities, TurnSelection, TurnSlot } from "./lib/turn-context.js";
|
|
38
47
|
|
|
39
48
|
// ============================================================================
|
|
40
49
|
// Configuration
|
|
@@ -149,7 +158,7 @@ function persistCap(pi: ExtensionAPI, previous: CapSettings, next: CapSettings):
|
|
|
149
158
|
|
|
150
159
|
// undefined means uncapped; null means cancel (never fall through to summary).
|
|
151
160
|
async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal: AbortSignal | undefined,
|
|
152
|
-
reason: string, size: { overhead: number; lineChars: number }): Promise<number | undefined | null> {
|
|
161
|
+
reason: string, size: { overhead: number; lineChars: number }, operation = "compaction"): Promise<number | undefined | null> {
|
|
153
162
|
try {
|
|
154
163
|
let state = capSettings(ctx.sessionManager.getBranch());
|
|
155
164
|
for (;;) {
|
|
@@ -163,7 +172,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
|
|
|
163
172
|
// Exactly the existing cap's test, including its minimum 500-char line budget.
|
|
164
173
|
const needsTrim = size.lineChars > Math.max(500, limit - size.overhead);
|
|
165
174
|
if (state.mode !== "warn" || !needsTrim) return limit;
|
|
166
|
-
const warning = `Verbatim
|
|
175
|
+
const warning = `Verbatim ${operation} would trim content: ~${(size.overhead + size.lineChars).toLocaleString()} conversation/retained-read chars; budget ${capBudgetText(state.budget)} (${limit.toLocaleString()} chars).`;
|
|
167
176
|
if (!ctx.hasUI || typeof ctx.ui.select !== "function") {
|
|
168
177
|
ctx.ui.notify(`${warning} Applying the cap because no interactive UI is available.`, "warning");
|
|
169
178
|
return limit;
|
|
@@ -172,7 +181,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
|
|
|
172
181
|
? "Overflow recovery: disabling the cap may leave too much context for the retry."
|
|
173
182
|
: "Disabling the cap may leave too much context for the model.";
|
|
174
183
|
const choice = await ctx.ui.select(`${warning}\n${risk}`, [
|
|
175
|
-
"Apply trimming", "Disable cap for this session", "Change budget",
|
|
184
|
+
"Apply trimming", "Disable cap for this session", "Change budget", `Cancel ${operation}`,
|
|
176
185
|
], { signal });
|
|
177
186
|
if (signal?.aborted) return null;
|
|
178
187
|
if (choice === "Apply trimming") return limit;
|
|
@@ -200,7 +209,7 @@ async function chooseCapBudget(pi: ExtensionAPI, ctx: ExtensionContext, signal:
|
|
|
200
209
|
}
|
|
201
210
|
}
|
|
202
211
|
} catch (err) {
|
|
203
|
-
if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)});
|
|
212
|
+
if (!signal?.aborted) ctx.ui?.notify?.(`transparent-compact: unable to resolve cap decision (${errMsg(err)}); ${operation} cancelled`, "error");
|
|
204
213
|
return null;
|
|
205
214
|
}
|
|
206
215
|
}
|
|
@@ -466,67 +475,6 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
|
|
|
466
475
|
// Mechanical summary (what replaces the model summary in the session)
|
|
467
476
|
// ============================================================================
|
|
468
477
|
|
|
469
|
-
// Display-only shortening: never change raw arguments or resolve symlinks.
|
|
470
|
-
function checkpointPath(value: string, cwd: string): string {
|
|
471
|
-
const prefix = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
|
|
472
|
-
if (value === cwd) return ".";
|
|
473
|
-
return value.startsWith(prefix) ? value.slice(prefix.length) : value;
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
function checkpointCommand(command: string, cwd: string): string {
|
|
477
|
-
const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
478
|
-
// Match complete path prefixes, not sibling directories or URL fragments.
|
|
479
|
-
return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, "g"), "$1.");
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
function argumentSnippet(value: unknown): string {
|
|
483
|
-
let s: string;
|
|
484
|
-
try {
|
|
485
|
-
s = JSON.stringify(value) ?? String(value);
|
|
486
|
-
} catch {
|
|
487
|
-
s = String(value);
|
|
488
|
-
}
|
|
489
|
-
return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
function toolSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): ToolStub {
|
|
493
|
-
const a = args ?? {};
|
|
494
|
-
if (!["read", "write", "edit", "bash"].includes(name))
|
|
495
|
-
return { prefix: `${name}(${Object.entries(a).map(([k, v]) => `${k}=${argumentSnippet(v)}`).join(", ")})`, suffix: "" };
|
|
496
|
-
const parts: string[] = [];
|
|
497
|
-
let command: ToolStub["command"];
|
|
498
|
-
const fileTool = ["read", "write", "edit"].includes(name) && typeof a.path === "string";
|
|
499
|
-
let base = fileTool ? `${name} ${JSON.stringify(checkpointPath(a.path as string, cwd))}` : name;
|
|
500
|
-
const range = name === "read" && fileTool &&
|
|
501
|
-
(a.offset === undefined || (Number.isSafeInteger(a.offset) && (a.offset as number) > 0)) &&
|
|
502
|
-
(a.limit === undefined || (Number.isSafeInteger(a.limit) && (a.limit as number) > 0));
|
|
503
|
-
if (range && (a.offset !== undefined || a.limit !== undefined)) {
|
|
504
|
-
const start = (a.offset as number | undefined) ?? 1;
|
|
505
|
-
const end = a.limit === undefined ? "" : start + (a.limit as number) - 1;
|
|
506
|
-
base += `:${start}-${end}`; // Requested range, not a claim about returned lines.
|
|
507
|
-
}
|
|
508
|
-
for (const [k, v] of Object.entries(a)) {
|
|
509
|
-
if (fileTool && k === "path") continue;
|
|
510
|
-
if (range && (k === "offset" || k === "limit")) continue;
|
|
511
|
-
if (name === "bash" && k === "timeout") continue;
|
|
512
|
-
if (name === "bash" && k === "command" && typeof v === "string")
|
|
513
|
-
command = commandPreview(JSON.stringify(checkpointCommand(v, cwd)));
|
|
514
|
-
else if (name === "write" && k === "content" && typeof v === "string")
|
|
515
|
-
parts.push(`(${v.length} chars)`);
|
|
516
|
-
else if (name === "edit" && k === "edits" && Array.isArray(v))
|
|
517
|
-
parts.push(`×${v.length}`);
|
|
518
|
-
else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
|
|
519
|
-
parts.push(`${k}=<${v.length} chars>`);
|
|
520
|
-
else parts.push(`${k}=${argumentSnippet(v)}`);
|
|
521
|
-
}
|
|
522
|
-
return command ? { prefix: `${base} `, command, suffix: parts.length ? ` ${parts.join(" ")}` : "" }
|
|
523
|
-
: { prefix: [base, ...parts].join(" "), suffix: "" };
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
|
|
527
|
-
return renderToolStub(toolSignature(name, args, cwd));
|
|
528
|
-
}
|
|
529
|
-
|
|
530
478
|
// Conservative lexical categories for selected output observations. These do
|
|
531
479
|
// not parse shell syntax or establish whether a command succeeded.
|
|
532
480
|
function commandHints(command: string): { tests: boolean; network: boolean; historical: boolean } {
|
|
@@ -607,11 +555,12 @@ function bashOutputLabel(command: string, result: Record<string, any>): string {
|
|
|
607
555
|
return labels.join("; ");
|
|
608
556
|
}
|
|
609
557
|
|
|
610
|
-
function summarizeMessages(messages: AgentMessage[],
|
|
558
|
+
async function summarizeMessages(messages: AgentMessage[], renderer: ToolRenderer, owners?: (string | null)[]): Promise<TurnSpan> {
|
|
611
559
|
const results = pairedToolResults(messages);
|
|
612
|
-
const lines: string[] = [];
|
|
560
|
+
const lines: string[] = [], turnIds: (string | null)[] = [];
|
|
613
561
|
const tools: ToolLines = { version: 2, lines: [] };
|
|
614
|
-
for (const msg of messages) {
|
|
562
|
+
for (const [messageIndex, msg] of messages.entries()) {
|
|
563
|
+
const start = lines.length;
|
|
615
564
|
const m = msg as unknown as Record<string, any>;
|
|
616
565
|
switch (msg.role) {
|
|
617
566
|
case "user": {
|
|
@@ -630,9 +579,7 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
|
|
|
630
579
|
const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
|
|
631
580
|
const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
|
|
632
581
|
const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
|
|
633
|
-
|
|
634
|
-
stub.suffix += status + (label ? ` → ${label}` : "");
|
|
635
|
-
calls.push(stub);
|
|
582
|
+
calls.push(await renderer.render(name, args, status + (label ? ` → ${label}` : "")));
|
|
636
583
|
}
|
|
637
584
|
// thinking blocks: removed by design (kept in the session)
|
|
638
585
|
}
|
|
@@ -646,14 +593,18 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
|
|
|
646
593
|
case "toolResult":
|
|
647
594
|
// removed by design (kept in the session)
|
|
648
595
|
break;
|
|
649
|
-
case "bashExecution":
|
|
650
|
-
|
|
596
|
+
case "bashExecution": {
|
|
597
|
+
const calls = [await renderer.render("bash", { command: String(m.command ?? "") }, " [output removed]")];
|
|
598
|
+
const prefix = "[BashExecution]: ";
|
|
599
|
+
tools.lines.push({ index: lines.length, calls, mergeable: false, prefix });
|
|
600
|
+
lines.push(renderToolLine(calls, NORMAL_PREVIEW_CHARS, prefix));
|
|
651
601
|
break;
|
|
602
|
+
}
|
|
652
603
|
case "custom":
|
|
653
604
|
// Our instruction envelope is regenerated, not conversation prose.
|
|
654
605
|
// Keep originals in raw history, but never carry old checklists into spans.
|
|
655
606
|
if (m.customType !== REORIENT_MESSAGE)
|
|
656
|
-
lines.push(`[Custom message]: ${
|
|
607
|
+
lines.push(`[Custom message]: ${renderToolStub(await renderer.render("custom", { type: m.customType }))} [content removed — use context_lookup]`);
|
|
657
608
|
break;
|
|
658
609
|
case "branchSummary":
|
|
659
610
|
case "compactionSummary":
|
|
@@ -662,8 +613,9 @@ function summarizeMessages(messages: AgentMessage[], cwd: string): SpanContent {
|
|
|
662
613
|
default:
|
|
663
614
|
break;
|
|
664
615
|
}
|
|
616
|
+
for (let i = start; i < lines.length; i++) turnIds.push(owners?.[messageIndex] ?? null);
|
|
665
617
|
}
|
|
666
|
-
return { lines, ...(tools.lines.length ? { tools } : {}) };
|
|
618
|
+
return { lines, ...(owners ? { turnIds } : {}), ...(tools.lines.length ? { tools } : {}) };
|
|
667
619
|
}
|
|
668
620
|
|
|
669
621
|
// Startup reference retention is a lexical heuristic, not an interpretation of
|
|
@@ -907,7 +859,8 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
|
|
|
907
859
|
* base, oldest first. Spans before the base are deliberately NOT re-rendered
|
|
908
860
|
* (the base is opaque; the session holds the raw history).
|
|
909
861
|
*/
|
|
910
|
-
|
|
862
|
+
interface LocationEntry { id: string; key: string; kind: string; value: string; display: string }
|
|
863
|
+
type StoredSpan = TurnSpan & { at: string; reason: string; from?: string; to?: string };
|
|
911
864
|
|
|
912
865
|
function collectBaseAndSpans(branchEntries: SessionEntry[]): {
|
|
913
866
|
base: { kind: "model-summary" | "legacy-checkpoint"; at: string; summary: string } | null;
|
|
@@ -917,7 +870,7 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
|
|
|
917
870
|
if (e.type !== "compaction") return undefined;
|
|
918
871
|
const d = (e as { details?: Record<string, any> }).details;
|
|
919
872
|
if (!d || d.kind !== MECH_KIND || !Array.isArray(d.span?.lines)) return undefined;
|
|
920
|
-
return d.span as { at?: unknown; reason?: unknown; from?: unknown; to?: unknown
|
|
873
|
+
return d.span as TurnSpan & { at?: unknown; reason?: unknown; from?: unknown; to?: unknown };
|
|
921
874
|
};
|
|
922
875
|
let baseIdx = -1;
|
|
923
876
|
for (let i = branchEntries.length - 1; i >= 0; i--) {
|
|
@@ -950,11 +903,163 @@ function collectBaseAndSpans(branchEntries: SessionEntry[]): {
|
|
|
950
903
|
to: typeof sd.to === "string" && sd.to !== "" ? sd.to : undefined,
|
|
951
904
|
lines: sd.lines,
|
|
952
905
|
tools: sd.tools,
|
|
906
|
+
turnIds: sd.turnIds,
|
|
953
907
|
});
|
|
954
908
|
}
|
|
955
909
|
return { base, spans };
|
|
956
910
|
}
|
|
957
911
|
|
|
912
|
+
interface FilterRevision {
|
|
913
|
+
compactionId: string;
|
|
914
|
+
summary: string;
|
|
915
|
+
filteredTurnIds: string[];
|
|
916
|
+
keptAsideTurnIds: string[];
|
|
917
|
+
fidelity?: TurnFidelities;
|
|
918
|
+
slots?: TurnSlot[];
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
|
|
922
|
+
return (latestVerbatimCompaction(entries)?.details as { locations?: LocationEntry[] } | undefined)?.locations ?? [];
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function latestFilterRevision(entries: SessionEntry[]) {
|
|
926
|
+
const compaction = latestVerbatimCompaction(entries);
|
|
927
|
+
if (!compaction) return;
|
|
928
|
+
const entry = entries.slice(entries.indexOf(compaction) + 1).findLast((entry) =>
|
|
929
|
+
entry.type === "custom" && entry.customType === FILTER_REVISION_ENTRY &&
|
|
930
|
+
(entry.data as FilterRevision)?.compactionId === compaction.id);
|
|
931
|
+
return entry?.type === "custom" ? entry as typeof entry & { data: FilterRevision } : undefined;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function filteredTurns(entries: SessionEntry[]): string[] {
|
|
935
|
+
return latestFilterRevision(entries)?.data.filteredTurnIds ??
|
|
936
|
+
(latestVerbatimCompaction(entries)?.details as { filteredTurnIds?: string[] } | undefined)?.filteredTurnIds ?? [];
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
function keptAsideTurns(entries: SessionEntry[]): string[] {
|
|
940
|
+
return latestFilterRevision(entries)?.data.keptAsideTurnIds ??
|
|
941
|
+
(latestVerbatimCompaction(entries)?.details as { keptAsideTurnIds?: string[] } | undefined)?.keptAsideTurnIds ?? [];
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
function turnFidelities(entries: SessionEntry[]): TurnFidelities {
|
|
945
|
+
const revision = latestFilterRevision(entries);
|
|
946
|
+
return revision ? revision.data.fidelity ?? {} :
|
|
947
|
+
(latestVerbatimCompaction(entries)?.details as { fidelity?: TurnFidelities } | undefined)?.fidelity ?? {};
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
function projectCheckpoint(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
|
|
951
|
+
const compaction = latestVerbatimCompaction(entries), revision = latestFilterRevision(entries);
|
|
952
|
+
const fidelity = turnFidelities(entries);
|
|
953
|
+
if (!compaction || (!revision && !Object.keys(fidelity).length)) return messages;
|
|
954
|
+
const saved = revision?.data ?? compaction.details as { slots?: TurnSlot[] };
|
|
955
|
+
if (messages.some((message) => isExpandedCheckpoint(message, revision?.data.summary ?? compaction.summary))) return messages;
|
|
956
|
+
// Expand only the active checkpoint using generated offsets, not historical
|
|
957
|
+
// text patterns. Original records and the retained tail remain untouched.
|
|
958
|
+
return messages.flatMap((message) => message.role === "compactionSummary"
|
|
959
|
+
? expandCheckpoint(message, revision?.data.summary ?? message.summary, saved.slots ?? [], fidelity, entries, compaction.firstKeptEntryId)
|
|
960
|
+
: [message]);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// Match Pi's prepared messages to their source entries, including explicit
|
|
964
|
+
// context replacements and generated custom messages. No raw bodies are stored.
|
|
965
|
+
function preparedTurnOwners(entries: SessionEntry[], messages: AgentMessage[]): (string | null)[] {
|
|
966
|
+
const owners = turnOwners(entries);
|
|
967
|
+
const queues = new Map<string, (string | null)[]>();
|
|
968
|
+
for (const projected of buildSessionProjection(entries).entries) {
|
|
969
|
+
if (projected.sourceEntry.type === "compaction") continue;
|
|
970
|
+
for (const message of projected.messages) {
|
|
971
|
+
const key = JSON.stringify(message);
|
|
972
|
+
const queue = queues.get(key) ?? [];
|
|
973
|
+
queue.push(owners.get(projected.sourceEntry.id) ?? null);
|
|
974
|
+
queues.set(key, queue);
|
|
975
|
+
}
|
|
976
|
+
}
|
|
977
|
+
return messages.map((message) => queues.get(JSON.stringify(message))?.shift() ?? null);
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
function filterChoices(entries: SessionEntry[], spans: TurnSpan[], excluded: Set<string>, firstKeptEntryId: string,
|
|
981
|
+
retained: StartupReads, selected = excluded, fidelity: TurnFidelities = turnFidelities(entries)): FilterTurn[] {
|
|
982
|
+
const owners = turnOwners(entries), flagged = preflaggedTurns(entries);
|
|
983
|
+
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
984
|
+
const tailOwners = new Set(entries.slice(cut).filter((entry) => entry.type === "message" || entry.type === "custom_message" || entry.type === "branch_summary")
|
|
985
|
+
.map((entry) => owners.get(entry.id)));
|
|
986
|
+
const lines = new Map<string, string[]>();
|
|
987
|
+
for (const span of spans) span.lines.forEach((line, index) => {
|
|
988
|
+
const owner = span.turnIds?.[index];
|
|
989
|
+
if (owner) { const group = lines.get(owner) ?? []; group.push(line); lines.set(owner, group); }
|
|
990
|
+
});
|
|
991
|
+
for (const read of retained.reads) {
|
|
992
|
+
const owner = owners.get(read.entryId);
|
|
993
|
+
if (owner && entries.findIndex((entry) => entry.id === read.entryId) < cut)
|
|
994
|
+
lines.get(owner)?.push(`[Retained startup read: ${read.path}]\n${read.text.join("\n")}`);
|
|
995
|
+
}
|
|
996
|
+
return entries.filter((entry) => entry.type === "message" && entry.message.role === "user").map((entry) => {
|
|
997
|
+
const content = lines.get(entry.id) ?? [];
|
|
998
|
+
const deferred = tailOwners.has(entry.id);
|
|
999
|
+
const unavailable = deferred ? (flagged.has(entry.id) ? undefined : "in retained recent tail")
|
|
1000
|
+
: content.length === 0 ? "not individually represented in checkpoint" : undefined;
|
|
1001
|
+
const cache = new Map<string, { tokens: number; lines: string[] }>();
|
|
1002
|
+
return { id: entry.id, fidelity: fidelity[entry.id], fidelityInfo: (mode) => {
|
|
1003
|
+
if (!cache.has(mode)) {
|
|
1004
|
+
const messages = fidelityMessages(entries, { [entry.id]: mode }, firstKeptEntryId).get(entry.id)!;
|
|
1005
|
+
cache.set(mode, { tokens: messageTokens(messages), lines: previewMessages(messages) });
|
|
1006
|
+
}
|
|
1007
|
+
return cache.get(mode)!;
|
|
1008
|
+
}, label: content[0] ?? `[User]: ${entry.type === "message" ? textOf((entry.message as any).content).text : ""}`,
|
|
1009
|
+
lines: content, selected: excluded.has(entry.id) || (!unavailable && selected.has(entry.id)),
|
|
1010
|
+
filtered: excluded.has(entry.id), deferred, unavailable };
|
|
1011
|
+
});
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
function applyTurnSelection(choices: FilterTurn[], result: TurnSelection, preflags: Set<string>,
|
|
1015
|
+
excluded: Set<string>, keptAsides: Set<string>, fidelity: TurnFidelities): void {
|
|
1016
|
+
const selected = new Set(result.pruned);
|
|
1017
|
+
for (const turn of choices) {
|
|
1018
|
+
if (turn.unavailable) continue;
|
|
1019
|
+
if (!turn.deferred) {
|
|
1020
|
+
if (selected.has(turn.id)) excluded.add(turn.id); else excluded.delete(turn.id);
|
|
1021
|
+
if (!selected.has(turn.id) && result.fidelity[turn.id]) fidelity[turn.id] = result.fidelity[turn.id];
|
|
1022
|
+
else delete fidelity[turn.id];
|
|
1023
|
+
}
|
|
1024
|
+
if (preflags.has(turn.id)) {
|
|
1025
|
+
if (selected.has(turn.id)) keptAsides.delete(turn.id); else keptAsides.add(turn.id);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// Remove file-list traces belonging only to excluded turns. A path also used
|
|
1031
|
+
// by a kept turn stays listed; filtering is not a claim that mutations were undone.
|
|
1032
|
+
function excludedFilePaths(entries: SessionEntry[], excluded: Set<string>, firstKeptEntryId: string, cwd: string): Set<string> {
|
|
1033
|
+
const owners = turnOwners(entries), removed = new Set<string>(), kept = new Set<string>();
|
|
1034
|
+
const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
|
|
1035
|
+
for (const entry of entries.slice(0, cut)) {
|
|
1036
|
+
if (entry.type !== "message") continue;
|
|
1037
|
+
const m = entry.message as any;
|
|
1038
|
+
const calls = m.role === "assistant" ? (m.content ?? []).filter((b: any) => b.type === "toolCall")
|
|
1039
|
+
: m.role === "toolResult" ? m.nestedCalls?.calls ?? [] : [];
|
|
1040
|
+
for (const call of calls) {
|
|
1041
|
+
if (!["read", "write", "edit"].includes(call.name) || typeof call.arguments?.path !== "string") continue;
|
|
1042
|
+
(excluded.has(owners.get(entry.id) ?? "") ? removed : kept).add(fileEvidenceKey(call.arguments.path, cwd));
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return new Set([...removed].filter((file) => !kept.has(file)));
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
function checkpointEvidence(entries: SessionEntry[], firstKeptEntryId: string, cwd: string,
|
|
1049
|
+
startup: StartupReads, readFiles: string[], modifiedFiles: string[], excluded: Set<string>, fidelity: TurnFidelities = {}) {
|
|
1050
|
+
if (!excluded.size && !Object.keys(fidelity).length) return { startupReads: startup, readFiles, modifiedFiles };
|
|
1051
|
+
const owners = turnOwners(entries);
|
|
1052
|
+
const removedPaths = excludedFilePaths(entries, excluded, firstKeptEntryId, cwd);
|
|
1053
|
+
return {
|
|
1054
|
+
startupReads: { ...startup, reads: startup.reads.filter((read) => {
|
|
1055
|
+
const owner = owners.get(read.entryId) ?? "";
|
|
1056
|
+
return !excluded.has(owner) && !fidelity[owner];
|
|
1057
|
+
}) },
|
|
1058
|
+
readFiles: readFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
1059
|
+
modifiedFiles: modifiedFiles.filter((file) => !removedPaths.has(fileEvidenceKey(file, cwd))),
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
958
1063
|
const RECOVERY_HISTORY_NOTE = "Compaction hides earlier details from your current view. The original conversation history, including recorded tool outputs and your reasoning, is preserved in the session and can be retrieved.";
|
|
959
1064
|
const RECOVERY_SOURCE_GUIDANCE = "Re-read project files for their current contents. Prefer lookup for what was observed earlier or to avoid repeating slow external research or expensive computations; cheap local rereads and recomputations remain reasonable.";
|
|
960
1065
|
const RECOVERY_SCOPE_RULE = "Use the recovery tools for history established by this conversation or its checkpoint, not project discovery, requirements never supplied, other sessions, or abandoned branches.";
|
|
@@ -965,9 +1070,10 @@ const REORIENT_BLOCK = `**Post-compaction re-orientation.** ${RECOVERY_HISTORY_N
|
|
|
965
1070
|
2. If this is a Git repository, run \`git status\` and review uncommitted work. Re-verify build/test state if you are about to rely on it.
|
|
966
1071
|
3. **Distinguish earlier claims from supporting evidence.** Retained assistant prose records what was said, not independent verification. If a task-relevant claim has uncertain provenance or conflicts with new evidence, check its supporting output (using \`context_lookup\` if hidden) or the current source before treating it as established; label unresolved claims unverified. Retrieved reasoning remains a historical hypothesis, and historical outputs do not establish current file or build/test state.`;
|
|
967
1072
|
|
|
1073
|
+
const REVISION_NOTE_PREFIX = "- Turn context revised: ";
|
|
968
1074
|
const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier part of this conversation has been compacted into the checkpoint below. This is not the full transcript. ${RECOVERY_HISTORY_NOTE}`;
|
|
969
1075
|
|
|
970
|
-
const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.**
|
|
1076
|
+
const RECOVERY_INSTRUCTIONS = `**Recovering hidden details.** Use \`context_lookup\` with a specific historical question: a subagent searches this conversation's full session history and returns relevant findings. Use the recovery tools for history established by this conversation or its checkpoint, not for project discovery or exploration of other sessions. If its findings are incomplete, use the bounded fallback tools \`context_list_entries\`, \`context_grep\`, and \`context_show_entry\`.`;
|
|
971
1077
|
|
|
972
1078
|
const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs and file lists omit supporting details. Most output and detailed payloads are omitted. Inline observations are historical, not verification of unshown details or current state. Use `context_lookup` for omitted observations or provenance; inspect sources for current state.";
|
|
973
1079
|
|
|
@@ -982,18 +1088,19 @@ function latestVerbatimCompaction(entries: SessionEntry[]) {
|
|
|
982
1088
|
}
|
|
983
1089
|
}
|
|
984
1090
|
|
|
985
|
-
function reorientationMessage(compactionId: string) {
|
|
986
|
-
return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}\n\n${RECOVERY_RECAP}`,
|
|
987
|
-
display: false, details: { compactionId } };
|
|
1091
|
+
function reorientationMessage(compactionId: string, filtered = false, revisionId = compactionId, fidelity = false) {
|
|
1092
|
+
return { customType: REORIENT_MESSAGE, content: `${REORIENT_BLOCK}${filtered ? `\n\n${FILTER_EXPLANATION}` : ""}${fidelity ? `\n\n${FIDELITY_EXPLANATION}` : ""}\n\n${RECOVERY_RECAP}`,
|
|
1093
|
+
display: false, details: { compactionId, ...(revisionId !== compactionId ? { revisionId } : {}) } };
|
|
988
1094
|
}
|
|
989
1095
|
|
|
990
1096
|
function isReorientation(msg: AgentMessage): boolean {
|
|
991
1097
|
return msg.role === "custom" && msg.customType === REORIENT_MESSAGE;
|
|
992
1098
|
}
|
|
993
1099
|
|
|
994
|
-
function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
|
|
995
|
-
|
|
996
|
-
|
|
1100
|
+
function reorientationFor(msg: AgentMessage, compactionId: string, revisionId: string): boolean {
|
|
1101
|
+
const details = msg.role === "custom" ? msg.details as { compactionId?: string; revisionId?: string } | undefined : undefined;
|
|
1102
|
+
return isReorientation(msg) && details?.compactionId === compactionId &&
|
|
1103
|
+
(details.revisionId ?? details.compactionId) === revisionId;
|
|
997
1104
|
}
|
|
998
1105
|
|
|
999
1106
|
/** Keep one current, persisted checklist. Obsolete managed messages can still be
|
|
@@ -1002,12 +1109,13 @@ function reorientationFor(msg: AgentMessage, compactionId: string): boolean {
|
|
|
1002
1109
|
* Later requests keep it in history before the work that followed it. */
|
|
1003
1110
|
function projectReorientation(messages: AgentMessage[], entries: SessionEntry[]): AgentMessage[] {
|
|
1004
1111
|
const compaction = latestVerbatimCompaction(entries);
|
|
1112
|
+
const anchor = latestFilterRevision(entries) ?? compaction;
|
|
1005
1113
|
let selected = -1;
|
|
1006
1114
|
for (let i = 0; i < messages.length; i++)
|
|
1007
|
-
if (compaction && reorientationFor(messages[i], compaction.id)) selected = i;
|
|
1115
|
+
if (compaction && reorientationFor(messages[i], compaction.id, anchor!.id)) selected = i;
|
|
1008
1116
|
const result = messages.filter((m, i) => !isReorientation(m) || i === selected);
|
|
1009
1117
|
if (selected < 0 || !compaction) return result;
|
|
1010
|
-
const answered = entries.slice(entries.indexOf(
|
|
1118
|
+
const answered = entries.slice(entries.indexOf(anchor!) + 1).some((e) =>
|
|
1011
1119
|
e.type === "message" && e.message.role === "assistant" &&
|
|
1012
1120
|
e.message.stopReason !== "aborted" && e.message.stopReason !== "error");
|
|
1013
1121
|
if (!answered) {
|
|
@@ -1017,13 +1125,45 @@ function projectReorientation(messages: AgentMessage[], entries: SessionEntry[])
|
|
|
1017
1125
|
return result;
|
|
1018
1126
|
}
|
|
1019
1127
|
|
|
1128
|
+
/** Attribute generated notice costs without touching quoted historical text.
|
|
1129
|
+
* Notices occur only in the generated prefix, before SECTION_HEADER. Using the
|
|
1130
|
+
* real estimator on counterfactual messages keeps counts tied to current text.
|
|
1131
|
+
*/
|
|
1132
|
+
function contextNoticeTokens(messages: AgentMessage[], reminder: AgentMessage): NoticeTokens {
|
|
1133
|
+
const first = messages.find((message) => message.role === "compactionSummary");
|
|
1134
|
+
if (!first || first.role !== "compactionSummary" || reminder.role !== "custom" || typeof reminder.content !== "string")
|
|
1135
|
+
throw new Error("Cannot identify generated context notices.");
|
|
1136
|
+
const end = first.summary.indexOf(SECTION_HEADER);
|
|
1137
|
+
if (end < 0) throw new Error("Cannot identify the checkpoint introduction.");
|
|
1138
|
+
let header = first.summary.slice(0, end), content = reminder.content;
|
|
1139
|
+
const body = first.summary.slice(end);
|
|
1140
|
+
const revision = header.split("\n").find((line) => line.startsWith(REVISION_NOTE_PREFIX)) ?? "";
|
|
1141
|
+
const notes: NoticeTokens = { pruning: 0, revision: 0, fidelity: 0 };
|
|
1142
|
+
const parts: [keyof NoticeTokens, string][] = [["pruning", FILTER_EXPLANATION], ["revision", revision], ["fidelity", FIDELITY_EXPLANATION]];
|
|
1143
|
+
for (const [kind, text] of parts) {
|
|
1144
|
+
if (!text) continue;
|
|
1145
|
+
const before = messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
|
|
1146
|
+
header = header.replace(`${text}\n`, "");
|
|
1147
|
+
if (kind !== "revision") content = content.replace(`\n\n${text}`, "");
|
|
1148
|
+
notes[kind] = before - messageTokens([{ ...first, summary: header + body }, { ...reminder, content }]);
|
|
1149
|
+
}
|
|
1150
|
+
return notes;
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1020
1153
|
async function buildMechanicalSummary(opts: {
|
|
1021
1154
|
reason: string; // pi's raw reason: "manual" | "threshold" | "overflow"
|
|
1022
1155
|
tokensBefore: number;
|
|
1023
1156
|
branchEntries: SessionEntry[];
|
|
1024
1157
|
now: string;
|
|
1025
1158
|
spanLines: string[]; // this compaction's own span, un-capped
|
|
1026
|
-
|
|
1159
|
+
revisedAt?: string; // rebuild existing spans only; no new compaction or boundary
|
|
1160
|
+
spanTools?: ToolLines; // display records; no raw command/program payloads
|
|
1161
|
+
locations?: LocationEntry[];
|
|
1162
|
+
spanTurnIds?: (string | null)[];
|
|
1163
|
+
filteredTurnIds?: string[];
|
|
1164
|
+
fidelity?: TurnFidelities;
|
|
1165
|
+
slots?: TurnSlot[]; // generated output placements; no raw payloads
|
|
1166
|
+
presentation?: { shortened: boolean }; // optional presentation-accounting output
|
|
1027
1167
|
spanFrom?: string; // ISO timestamp of the first summarised message
|
|
1028
1168
|
spanTo?: string; // ISO timestamp of the last summarised message
|
|
1029
1169
|
firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
|
|
@@ -1035,8 +1175,25 @@ async function buildMechanicalSummary(opts: {
|
|
|
1035
1175
|
chooseCap: (size: { overhead: number; lineChars: number }) => Promise<number | undefined | null>;
|
|
1036
1176
|
}): Promise<string | undefined> {
|
|
1037
1177
|
const { base, spans } = collectBaseAndSpans(opts.branchEntries);
|
|
1038
|
-
const
|
|
1039
|
-
|
|
1178
|
+
const fidelity = opts.fidelity ?? {};
|
|
1179
|
+
const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
|
|
1180
|
+
const nativeMessages = [...native.values()].flat();
|
|
1181
|
+
const nativeChars = messageTokens(nativeMessages) * 4;
|
|
1182
|
+
const nativeResults = pairedToolResults(nativeMessages), nativeReadPaths = new Set<string>();
|
|
1183
|
+
for (const message of nativeMessages) if (message.role === "assistant") for (const block of message.content) {
|
|
1184
|
+
if (block.type === "toolCall" && block.name === "read" && typeof block.arguments?.path === "string" && nativeResults.get(block)?.isError === false)
|
|
1185
|
+
nativeReadPaths.add(fileEvidenceKey(block.arguments.path, opts.cwd));
|
|
1186
|
+
}
|
|
1187
|
+
const rendered = fidelitySpans(filterSpans(opts.revisedAt ? spans : [...spans, {
|
|
1188
|
+
at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
|
|
1189
|
+
lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
|
|
1190
|
+
}], new Set(opts.filteredTurnIds)), fidelity);
|
|
1191
|
+
const allSpans = rendered.spans;
|
|
1192
|
+
const locations = new Locations(opts.cwd, opts.locations ?? checkpointLocations(opts.branchEntries));
|
|
1193
|
+
const fileIds = [...opts.readFiles, ...opts.modifiedFiles].map((file) => locations.ref(file, opts.cwd, 'path', true).id);
|
|
1194
|
+
const dictionary = (ids: string[]) => locations.render(new Set([...fileIds, ...ids]));
|
|
1195
|
+
const dictionaryCost = (ids: string[]) => { const text = dictionary(ids); return text ? text.length + 2 : 0; };
|
|
1196
|
+
const allLocationIds = allSpans.flatMap((span) => span.tools?.lines.flatMap((line) => line.calls.flatMap((call) => call.locations ?? [])) ?? []);
|
|
1040
1197
|
const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
|
|
1041
1198
|
|
|
1042
1199
|
// Size guard: the budget covers the conversation section plus retained reads.
|
|
@@ -1044,7 +1201,7 @@ async function buildMechanicalSummary(opts: {
|
|
|
1044
1201
|
// exceed the budget by itself; warn rather than silently dropping evidence.
|
|
1045
1202
|
const baseOpen = base ? `<compacted-base kind="${base.kind}" compacted-at="${base.at}">` : "";
|
|
1046
1203
|
const retainedReads = renderStartupReads(opts.startupReads, opts.branchEntries, opts.firstKeptEntryId);
|
|
1047
|
-
let overhead = SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
|
|
1204
|
+
let overhead = nativeChars + SECTION_HEADER.length + 2 + (retainedReads ? retainedReads.length + 2 : 0);
|
|
1048
1205
|
if (base) overhead += baseOpen.length + 1 + BASE_CLOSE.length + 2 + base.summary.length;
|
|
1049
1206
|
overhead += allSpans.reduce(
|
|
1050
1207
|
(a, s, i) => a + spanOpen(i + 1, s.at, s.reason, coversOf(s)).length + SPAN_TRIMMED_ATTR.length + TIGHTENED_ATTR.length + 2 + SPAN_TRIMMED_NOTE.length + 1 + SPAN_CLOSE.length + 2,
|
|
@@ -1062,13 +1219,18 @@ async function buildMechanicalSummary(opts: {
|
|
|
1062
1219
|
overhead += closingLine.length + 2;
|
|
1063
1220
|
const lines = allSpans.map((s) => s.lines);
|
|
1064
1221
|
const lineChars = lines.reduce((total, span) => total + span.reduce((n, line) => n + line.length + 1, 0), 0);
|
|
1065
|
-
const maxChars = await opts.chooseCap({ overhead, lineChars });
|
|
1222
|
+
const maxChars = await opts.chooseCap({ overhead: overhead + dictionaryCost(allLocationIds), lineChars });
|
|
1066
1223
|
if (maxChars === null) return undefined;
|
|
1067
1224
|
if (maxChars !== undefined && base && base.summary.length > maxChars)
|
|
1068
1225
|
opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
|
|
1069
1226
|
if (maxChars !== undefined && retainedReads.length > maxChars)
|
|
1070
1227
|
opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
|
|
1071
|
-
|
|
1228
|
+
if (maxChars !== undefined && dictionaryCost([]) > maxChars)
|
|
1229
|
+
opts.notify(`transparent-compact: location definitions required by file lists exceed the budget; they are kept to avoid dangling references`);
|
|
1230
|
+
if (maxChars !== undefined && nativeChars > maxChars)
|
|
1231
|
+
opts.notify(`transparent-compact: full-fidelity turns alone are ~${nativeChars.toLocaleString()} estimated chars (budget ${maxChars.toLocaleString()}); they are kept un-capped. Only PROSE can be trimmed.`);
|
|
1232
|
+
const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost);
|
|
1233
|
+
if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
|
|
1072
1234
|
|
|
1073
1235
|
const blocks: string[] = [];
|
|
1074
1236
|
if (base) blocks.push(`${baseOpen}\n${base.summary.replace(/\n+$/, "")}\n${BASE_CLOSE}`);
|
|
@@ -1085,18 +1247,20 @@ async function buildMechanicalSummary(opts: {
|
|
|
1085
1247
|
].join("\n"));
|
|
1086
1248
|
});
|
|
1087
1249
|
|
|
1088
|
-
const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + 1;
|
|
1250
|
+
const compactionCount = opts.branchEntries.filter((e) => e.type === "compaction").length + (opts.revisedAt ? 0 : 1);
|
|
1089
1251
|
const parts: string[] = [];
|
|
1090
1252
|
parts.push(`## Verbatim compaction checkpoint (compaction ${compactionCount} on this branch)`);
|
|
1091
1253
|
parts.push(CHECKPOINT_EXPLANATION);
|
|
1254
|
+
if (opts.filteredTurnIds?.length) parts.push(FILTER_EXPLANATION);
|
|
1255
|
+
if (native.size) parts.push(FIDELITY_EXPLANATION);
|
|
1092
1256
|
if (base?.kind === "model-summary") {
|
|
1093
1257
|
parts.push(MIXED_CONTEXT_WARNING);
|
|
1094
1258
|
opts.notify(MIXED_CONTEXT_WARNING);
|
|
1095
1259
|
}
|
|
1096
1260
|
parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
|
|
1097
|
-
parts.push(
|
|
1261
|
+
if (opts.revisedAt) parts.push(`${REVISION_NOTE_PREFIX}${opts.revisedAt}. No additional history was compacted; the verbatim boundary is unchanged.`);
|
|
1262
|
+
parts.push(TOOL_DISPLAY_EXPLANATION);
|
|
1098
1263
|
parts.push("- [tool error] means the result was flagged as an error; [unknown] means no safely matched result/status. Unlabelled does NOT establish exit 0 or passing tests. → exit N is a reported shell status; output: quotes/extracts selected output, not an inferred verdict. Everything shown is historical. Legacy [ok] only means not flagged as a tool error; legacy calls without status are unknown.");
|
|
1099
|
-
parts.push("- Under size pressure, `tools-tightened` marks 120/80-character previews or grouped tool-only lines. Conversation prose and tool calls are retained unless `trimmed` is also marked. Tightening stops as soon as the budget fits; outcome observations and identifying file paths are not shortened by these stages.");
|
|
1100
1264
|
parts.push("- Newly compacted custom messages are kept only as type stubs (long types abbreviated); their content is removed and remains recoverable in the session through context_lookup. Stored canonical spans are unchanged; their presentation may tighten under the cap.");
|
|
1101
1265
|
parts.push(
|
|
1102
1266
|
"- pi keeps the most recent part of the conversation verbatim (its `keepRecentTokens` setting). The spans below cover only what came *before* that. The retained verbatim conversation begins after the explicit boundary marker at the end of this checkpoint.",
|
|
@@ -1121,8 +1285,9 @@ async function buildMechanicalSummary(opts: {
|
|
|
1121
1285
|
const key = fileEvidenceKey(file, opts.cwd);
|
|
1122
1286
|
const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
|
|
1123
1287
|
? "startup read output retained in checkpoint or tail; may be partial"
|
|
1288
|
+
: nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
|
|
1124
1289
|
: modified && knownTail ? "no read-tool output in tail" : undefined);
|
|
1125
|
-
return `${
|
|
1290
|
+
return `${locations.ref(file, opts.cwd, 'path', true).id}${label ? ` (${label})` : ""}`;
|
|
1126
1291
|
};
|
|
1127
1292
|
parts.push("", FILE_LIST_EXPLANATION);
|
|
1128
1293
|
if (opts.readFiles.length > 0)
|
|
@@ -1130,12 +1295,17 @@ async function buildMechanicalSummary(opts: {
|
|
|
1130
1295
|
if (opts.modifiedFiles.length > 0)
|
|
1131
1296
|
parts.push(`<modified-files note="modified in compacted history">\n${opts.modifiedFiles.map((file) => fileLine(file, true)).join("\n")}\n</modified-files>`);
|
|
1132
1297
|
}
|
|
1298
|
+
const locationTable = dictionary(capped.locationIds);
|
|
1299
|
+
if (locationTable) parts.push("", locationTable);
|
|
1133
1300
|
parts.push("");
|
|
1134
1301
|
parts.push(EVIDENCE_BOUNDARY_RULE);
|
|
1135
1302
|
parts.push("");
|
|
1136
1303
|
parts.push(closingLine);
|
|
1137
1304
|
|
|
1138
|
-
|
|
1305
|
+
const summary = parts.join("\n");
|
|
1306
|
+
if (native.size && !opts.slots) throw new Error("Missing full-fidelity placement output.");
|
|
1307
|
+
opts.slots?.push(...locateSlots(summary, rendered.markers, fidelity));
|
|
1308
|
+
return summary;
|
|
1139
1309
|
}
|
|
1140
1310
|
|
|
1141
1311
|
// ============================================================================
|
|
@@ -1662,15 +1832,39 @@ function registerDirectTools(pi: ExtensionAPI): void {
|
|
|
1662
1832
|
// ============================================================================
|
|
1663
1833
|
|
|
1664
1834
|
export default function (pi: ExtensionAPI) {
|
|
1835
|
+
// Only bridge a specific /filter-later (or /fl) submission to its actual persisted user
|
|
1836
|
+
// message. The next input clears a failed/handled submission, so it cannot
|
|
1837
|
+
// accidentally flag a later ordinary prompt. Durable state uses raw entries.
|
|
1838
|
+
let requestedAside: { sessionId: string; text: string } | undefined;
|
|
1839
|
+
let asideInputSession: string | undefined;
|
|
1840
|
+
const clearAsideSubmission = () => { requestedAside = undefined; asideInputSession = undefined; };
|
|
1841
|
+
pi.on("input", (event, ctx) => {
|
|
1842
|
+
asideInputSession = event.source === "extension" && requestedAside?.sessionId === ctx.sessionManager.getSessionId() &&
|
|
1843
|
+
requestedAside.text === event.text ? requestedAside.sessionId : undefined;
|
|
1844
|
+
requestedAside = undefined;
|
|
1845
|
+
});
|
|
1846
|
+
pi.on("message_end", (event, ctx) => {
|
|
1847
|
+
if (event.message.role !== "user" || asideInputSession !== ctx.sessionManager.getSessionId()) return;
|
|
1848
|
+
asideInputSession = undefined;
|
|
1849
|
+
// Pi persists this user message immediately after message_end handlers.
|
|
1850
|
+
pi.appendEntry(PREFLAG_ENTRY, { timestamp: event.message.timestamp });
|
|
1851
|
+
});
|
|
1852
|
+
pi.on("session_shutdown", clearAsideSubmission);
|
|
1853
|
+
pi.on("session_tree", clearAsideSubmission);
|
|
1854
|
+
|
|
1665
1855
|
// Starting/resuming a run persists the checklist AFTER the starting user
|
|
1666
1856
|
// message. Existing branch history, not an in-memory flag, prevents repeats.
|
|
1667
1857
|
pi.on("before_agent_start", (_event, ctx) => {
|
|
1668
1858
|
const entries = ctx.sessionManager.getBranch();
|
|
1669
1859
|
const compaction = latestVerbatimCompaction(entries);
|
|
1670
1860
|
if (!compaction) return;
|
|
1671
|
-
const
|
|
1672
|
-
|
|
1673
|
-
|
|
1861
|
+
const revisionId = latestFilterRevision(entries)?.id ?? compaction.id;
|
|
1862
|
+
const found = entries.some((e) => {
|
|
1863
|
+
if (e.type !== "custom_message" || e.customType !== REORIENT_MESSAGE) return false;
|
|
1864
|
+
const details = e.details as { compactionId?: string; revisionId?: string } | undefined;
|
|
1865
|
+
return details?.compactionId === compaction.id && (details.revisionId ?? details.compactionId) === revisionId;
|
|
1866
|
+
});
|
|
1867
|
+
if (!found) return { message: reorientationMessage(compaction.id, filteredTurns(entries).length > 0, revisionId, Object.keys(turnFidelities(entries)).length > 0) };
|
|
1674
1868
|
});
|
|
1675
1869
|
|
|
1676
1870
|
// Between-turn compaction and overflow continuation do not necessarily pass
|
|
@@ -1680,16 +1874,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
1680
1874
|
pi.on("session_compact", (event, ctx) => {
|
|
1681
1875
|
if ((event.compactionEntry.details as { kind?: string } | undefined)?.kind !== MECH_KIND) return;
|
|
1682
1876
|
if (event.willRetry || ctx.signal)
|
|
1683
|
-
pi.sendMessage(reorientationMessage(event.compactionEntry.id
|
|
1877
|
+
pi.sendMessage(reorientationMessage(event.compactionEntry.id,
|
|
1878
|
+
((event.compactionEntry.details as { filteredTurnIds?: string[] }).filteredTurnIds?.length ?? 0) > 0, event.compactionEntry.id,
|
|
1879
|
+
Object.keys((event.compactionEntry.details as { fidelity?: TurnFidelities }).fidelity ?? {}).length > 0), { deliverAs: "steer" });
|
|
1684
1880
|
});
|
|
1685
1881
|
|
|
1686
1882
|
// Run after ordinary transforms and system/tool restoration. Preserve all
|
|
1687
1883
|
// non-managed messages, remove old checklists even if they survive in the tail,
|
|
1688
1884
|
// and keep the current one active on subsequent requests (not just the first).
|
|
1689
1885
|
pi.on("context_with_system", (event, ctx) => {
|
|
1690
|
-
const
|
|
1691
|
-
|
|
1692
|
-
|
|
1886
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1887
|
+
try {
|
|
1888
|
+
const messages = projectReorientation(projectCheckpoint(event.messages, entries), entries);
|
|
1889
|
+
if (Object.keys(turnFidelities(entries)).length) checkContextBudget(messages, ctx);
|
|
1890
|
+
if (messages.length !== event.messages.length || messages.some((m, i) => m !== event.messages[i])) return { messages };
|
|
1891
|
+
} catch (error) {
|
|
1892
|
+
ctx.ui.notify(`Full-fidelity context blocked: ${errMsg(error)}`, "error");
|
|
1893
|
+
ctx.abort(); // Hook errors alone do not cancel Pi requests. Abort explicitly.
|
|
1894
|
+
throw error;
|
|
1895
|
+
}
|
|
1693
1896
|
});
|
|
1694
1897
|
|
|
1695
1898
|
// Method selection never changes Pi's auto-compaction enabled setting.
|
|
@@ -1738,7 +1941,190 @@ export default function (pi: ExtensionAPI) {
|
|
|
1738
1941
|
},
|
|
1739
1942
|
});
|
|
1740
1943
|
|
|
1944
|
+
for (const name of ["filter-later", "fl"]) pi.registerCommand(name, {
|
|
1945
|
+
description: "Submit a normal user turn pre-flagged for future checkpoint filtering",
|
|
1946
|
+
handler: async (args, ctx) => {
|
|
1947
|
+
if (!args.trim()) { ctx.ui.notify(`Usage: /${name} <message>`, "error"); return; }
|
|
1948
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1949
|
+
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before submitting an aside.", "warning"); return;
|
|
1950
|
+
}
|
|
1951
|
+
if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
|
|
1952
|
+
ctx.ui.notify(`/${name} requires verbatim compaction. Use /compaction-method verbatim first.`, "error"); return;
|
|
1953
|
+
}
|
|
1954
|
+
clearAsideSubmission();
|
|
1955
|
+
requestedAside = { sessionId: ctx.sessionManager.getSessionId(), text: args };
|
|
1956
|
+
try {
|
|
1957
|
+
pi.sendUserMessage(args);
|
|
1958
|
+
} catch (error) {
|
|
1959
|
+
clearAsideSubmission();
|
|
1960
|
+
throw error;
|
|
1961
|
+
}
|
|
1962
|
+
},
|
|
1963
|
+
});
|
|
1964
|
+
|
|
1965
|
+
pi.registerCommand("filter-auto", {
|
|
1966
|
+
description: "Show or set automatic application of pre-flagged asides: on|off (default off)",
|
|
1967
|
+
getArgumentCompletions: (prefix) => ["on", "off"].filter((value) => value.startsWith(prefix))
|
|
1968
|
+
.map((value) => ({ value, label: value })),
|
|
1969
|
+
handler: async (args, ctx) => {
|
|
1970
|
+
const value = args.trim();
|
|
1971
|
+
if (value && value !== "on" && value !== "off") { ctx.ui.notify("Usage: /filter-auto [on|off]", "error"); return; }
|
|
1972
|
+
const previous = autoFilterEnabled(ctx.sessionManager.getBranch());
|
|
1973
|
+
const enabled = value ? value === "on" : previous;
|
|
1974
|
+
if (enabled !== previous) pi.appendEntry(AUTO_FILTER_ENTRY, { enabled });
|
|
1975
|
+
ctx.ui.notify(`Automatic aside filtering: ${enabled ? "on" : "off"}. Applies user pre-flags during verbatim threshold/overflow compaction; no picker or automatic relevance judgments.`, "info");
|
|
1976
|
+
},
|
|
1977
|
+
});
|
|
1978
|
+
|
|
1979
|
+
const filterTurns = {
|
|
1980
|
+
description: "Choose checkpoint turn modes: pruned, prose, prose+tools or full; no compaction",
|
|
1981
|
+
handler: async (args: string, ctx: ExtensionContext) => {
|
|
1982
|
+
if (args.trim()) { ctx.ui.notify("Usage: /filter-turns", "error"); return; }
|
|
1983
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
1984
|
+
ctx.ui.notify("/filter-turns requires the interactive terminal UI.", "error"); return;
|
|
1985
|
+
}
|
|
1986
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
1987
|
+
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
1988
|
+
}
|
|
1989
|
+
const entries = ctx.sessionManager.getBranch();
|
|
1990
|
+
const compaction = latestVerbatimCompaction(entries);
|
|
1991
|
+
if (compactionMethod(entries) !== "verbatim" || !compaction) {
|
|
1992
|
+
ctx.ui.notify("/filter-turns requires an existing verbatim checkpoint. Use /compact-filtered to create one.", "error"); return;
|
|
1993
|
+
}
|
|
1994
|
+
const canonical = compaction.details as { span: StoredSpan; startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[] };
|
|
1995
|
+
if (!canonical.span || !canonical.startupReads) {
|
|
1996
|
+
ctx.ui.notify("This checkpoint has no editable canonical spans. Use /compact-filtered first.", "error"); return;
|
|
1997
|
+
}
|
|
1998
|
+
const sessionId = ctx.sessionManager.getSessionId();
|
|
1999
|
+
const revisionId = latestFilterRevision(entries)?.id;
|
|
2000
|
+
const signal = new AbortController().signal;
|
|
2001
|
+
try {
|
|
2002
|
+
const previousExcluded = filteredTurns(entries), previousKept = keptAsideTurns(entries);
|
|
2003
|
+
const excluded = new Set(previousExcluded), keptAsides = new Set(previousKept);
|
|
2004
|
+
const previousFidelity = turnFidelities(entries), fidelity = { ...previousFidelity }, slots: TurnSlot[] = [];
|
|
2005
|
+
const preflags = preflaggedTurns(entries);
|
|
2006
|
+
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2007
|
+
const choices = filterChoices(entries, collectBaseAndSpans(entries).spans, excluded,
|
|
2008
|
+
compaction.firstKeptEntryId, canonical.startupReads, proposed);
|
|
2009
|
+
const unchanged = (pruned: Set<string>, kept: Set<string>, modes: TurnFidelities) =>
|
|
2010
|
+
pruned.size === previousExcluded.length && previousExcluded.every((id) => pruned.has(id)) &&
|
|
2011
|
+
kept.size === previousKept.length && previousKept.every((id) => kept.has(id)) &&
|
|
2012
|
+
JSON.stringify(Object.entries(modes).sort()) === JSON.stringify(Object.entries(previousFidelity).sort());
|
|
2013
|
+
const cap = capSettings(entries);
|
|
2014
|
+
const renderCheckpoint = (pruned: Set<string>, modes: TurnFidelities, placements: TurnSlot[], preview: boolean, presentation?: { shortened: boolean }) => buildMechanicalSummary({
|
|
2015
|
+
reason: canonical.span.reason, tokensBefore: compaction.tokensBefore, branchEntries: entries,
|
|
2016
|
+
now: canonical.span.at, revisedAt: new Date().toISOString(), spanLines: [], filteredTurnIds: [...pruned], fidelity: modes, slots: placements, presentation,
|
|
2017
|
+
firstKeptEntryId: compaction.firstKeptEntryId,
|
|
2018
|
+
...checkpointEvidence(entries, compaction.firstKeptEntryId, ctx.cwd,
|
|
2019
|
+
canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, pruned, modes),
|
|
2020
|
+
cwd: ctx.cwd, notify: preview ? () => {} : (message) => ctx.ui.notify(message, "warning"),
|
|
2021
|
+
chooseCap: preview ? async () => {
|
|
2022
|
+
if (cap.mode === "off") return undefined;
|
|
2023
|
+
const limit = capBudgetChars(cap.budget, ctx.model?.contextWindow);
|
|
2024
|
+
if (limit === undefined) throw new Error("Cannot preview a percentage cap without the model's context window.");
|
|
2025
|
+
return limit; // Warn-mode previews assume applying the current cap; never open a dialog or persist policy here.
|
|
2026
|
+
} : (size) => chooseCapBudget(pi, ctx, signal, "manual", size, "checkpoint update"),
|
|
2027
|
+
});
|
|
2028
|
+
const activeTools = new Set(pi.getActiveTools());
|
|
2029
|
+
const system: AgentMessage = { role: "system", content: ctx.getSystemPrompt(), timestamp: 0,
|
|
2030
|
+
toolsAdded: pi.getAllTools().filter((tool) => activeTools.has(tool.name))
|
|
2031
|
+
.map(({ name, description, parameters }) => ({ name, description, parameters })) };
|
|
2032
|
+
const tailTokens = messageTokens(retainedTailMessages(entries, compaction.firstKeptEntryId));
|
|
2033
|
+
const measure = (summary: string, placements: TurnSlot[], modes: TurnFidelities, pruned: Set<string>, shortening?: ContextEstimate["shortening"]): ContextEstimate => {
|
|
2034
|
+
const reminder: AgentMessage = { ...reorientationMessage(compaction.id, pruned.size > 0,
|
|
2035
|
+
revisionId ?? compaction.id, Object.keys(modes).length > 0), role: "custom", timestamp: 0 };
|
|
2036
|
+
const messages = checkpointContextMessages(summary, placements, modes, entries, compaction.firstKeptEntryId);
|
|
2037
|
+
return { ...estimateContext([system, ...messages, reminder], ctx), tailTokens,
|
|
2038
|
+
noticeTokens: contextNoticeTokens(messages, reminder), shortening };
|
|
2039
|
+
};
|
|
2040
|
+
const saved = latestFilterRevision(entries)?.data ?? { summary: compaction.summary,
|
|
2041
|
+
slots: (compaction.details as { slots?: TurnSlot[] }).slots };
|
|
2042
|
+
let baseline: Promise<ContextEstimate | undefined> | undefined;
|
|
2043
|
+
const estimateSelection = async (selection: TurnSelection): Promise<ContextEstimate> => {
|
|
2044
|
+
baseline ??= Promise.resolve().then(() => measure(saved.summary, saved.slots ?? [], previousFidelity, new Set(previousExcluded))).catch(() => undefined);
|
|
2045
|
+
const pruned = new Set(previousExcluded), kept = new Set(previousKept), modes = { ...previousFidelity }, placements: TurnSlot[] = [];
|
|
2046
|
+
applyTurnSelection(choices, selection, preflags, pruned, kept, modes);
|
|
2047
|
+
const original = await baseline;
|
|
2048
|
+
if (unchanged(pruned, kept, modes)) return { ...(original ?? measure(saved.summary, saved.slots ?? [], previousFidelity, pruned)), delta: original ? 0 : undefined };
|
|
2049
|
+
const presentation = { shortened: false };
|
|
2050
|
+
const summary = await renderCheckpoint(pruned, modes, placements, true, presentation);
|
|
2051
|
+
if (summary === undefined) throw new Error("Checkpoint preview cancelled.");
|
|
2052
|
+
const estimated = measure(summary, placements, modes, pruned,
|
|
2053
|
+
presentation.shortened ? cap.mode === "warn" ? "confirmation" : "automatic" : undefined);
|
|
2054
|
+
return { ...estimated, delta: original ? estimated.tokens - original.tokens : undefined,
|
|
2055
|
+
noticeDelta: original?.noticeTokens && estimated.noticeTokens ? {
|
|
2056
|
+
pruning: (previousExcluded.length > 0) === (pruned.size > 0) ? 0 : estimated.noticeTokens.pruning - original.noticeTokens.pruning,
|
|
2057
|
+
revision: revisionId ? 0 : estimated.noticeTokens.revision - original.noticeTokens.revision,
|
|
2058
|
+
fidelity: Boolean(Object.keys(previousFidelity).length) === Boolean(Object.keys(modes).length) ? 0 : estimated.noticeTokens.fidelity - original.noticeTokens.fidelity,
|
|
2059
|
+
} : undefined };
|
|
2060
|
+
};
|
|
2061
|
+
const result = await pickFilteredTurns(ctx, choices, signal, estimateSelection);
|
|
2062
|
+
if (result === undefined) return;
|
|
2063
|
+
applyTurnSelection(choices, result, preflags, excluded, keptAsides, fidelity);
|
|
2064
|
+
if (unchanged(excluded, keptAsides, fidelity)) {
|
|
2065
|
+
ctx.ui.notify("No checkpoint turn-mode changes.", "info"); return;
|
|
2066
|
+
}
|
|
2067
|
+
const summary = await renderCheckpoint(excluded, fidelity, slots, false);
|
|
2068
|
+
if (summary === undefined) return;
|
|
2069
|
+
checkCheckpointBudget(summary, slots, fidelity, entries, compaction.firstKeptEntryId, ctx);
|
|
2070
|
+
const current = ctx.sessionManager.getBranch();
|
|
2071
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || latestVerbatimCompaction(current)?.id !== compaction.id ||
|
|
2072
|
+
latestFilterRevision(current)?.id !== revisionId) {
|
|
2073
|
+
ctx.ui.notify("Session/checkpoint changed; filtering update cancelled.", "warning"); return;
|
|
2074
|
+
}
|
|
2075
|
+
pi.appendEntry(FILTER_REVISION_ENTRY, { compactionId: compaction.id, summary,
|
|
2076
|
+
filteredTurnIds: [...excluded], keptAsideTurnIds: [...keptAsides],
|
|
2077
|
+
...(Object.keys(fidelity).length ? { fidelity, slots } : {}) } satisfies FilterRevision);
|
|
2078
|
+
ctx.ui.notify("Checkpoint turn modes updated. No additional history compacted; recent messages and boundary unchanged.", "info");
|
|
2079
|
+
} catch (error) {
|
|
2080
|
+
ctx.ui.notify(`Checkpoint turn update cancelled: ${errMsg(error)}`, "error");
|
|
2081
|
+
}
|
|
2082
|
+
},
|
|
2083
|
+
};
|
|
2084
|
+
|
|
2085
|
+
pi.registerCommand("compact-filtered", {
|
|
2086
|
+
description: "Run ordinary compaction, then open checkpoint turn controls",
|
|
2087
|
+
handler: async (args, ctx) => {
|
|
2088
|
+
if (args.trim()) { ctx.ui.notify("Usage: /compact-filtered", "error"); return; }
|
|
2089
|
+
if (ctx.mode !== "tui" || !ctx.hasUI) {
|
|
2090
|
+
ctx.ui.notify("/compact-filtered requires the interactive terminal UI.", "error"); return;
|
|
2091
|
+
}
|
|
2092
|
+
if (!ctx.isIdle() || ctx.hasPendingMessages()) {
|
|
2093
|
+
ctx.ui.notify("Wait until the agent is idle and queued messages have been handled before filtering turns.", "warning"); return;
|
|
2094
|
+
}
|
|
2095
|
+
if (compactionMethod(ctx.sessionManager.getBranch()) !== "verbatim") {
|
|
2096
|
+
ctx.ui.notify("/compact-filtered requires verbatim compaction. Use /compaction-method verbatim first.", "error"); return;
|
|
2097
|
+
}
|
|
2098
|
+
const sessionId = ctx.sessionManager.getSessionId(), leafId = ctx.sessionManager.getLeafId();
|
|
2099
|
+
try {
|
|
2100
|
+
// compact() is callback-based. Wait for completion, not merely dispatch,
|
|
2101
|
+
// so the editor sees the saved checkpoint and the host is idle again.
|
|
2102
|
+
const result = await new Promise<{ summary: string; firstKeptEntryId: string }>((resolve, reject) => {
|
|
2103
|
+
ctx.compact({ onComplete: resolve, onError: reject });
|
|
2104
|
+
});
|
|
2105
|
+
const entries = ctx.sessionManager.getBranch(), current = latestVerbatimCompaction(entries);
|
|
2106
|
+
if (ctx.sessionManager.getSessionId() !== sessionId || !current || current.summary !== result.summary ||
|
|
2107
|
+
current.firstKeptEntryId !== result.firstKeptEntryId || (leafId && !entries.some((entry) => entry.id === leafId))) {
|
|
2108
|
+
ctx.ui.notify("Session/checkpoint changed; turn controls not opened.", "warning"); return;
|
|
2109
|
+
}
|
|
2110
|
+
} catch (error) {
|
|
2111
|
+
// These are Pi's current no-op outcomes, not general compaction failures.
|
|
2112
|
+
// Only an unchanged session with an existing checkpoint can be edited.
|
|
2113
|
+
const noOp = error instanceof Error && (error.message === "Already compacted" || error.message === "Nothing to compact (session too small)");
|
|
2114
|
+
if (!noOp || ctx.sessionManager.getSessionId() !== sessionId || ctx.sessionManager.getLeafId() !== leafId ||
|
|
2115
|
+
!latestVerbatimCompaction(ctx.sessionManager.getBranch())) {
|
|
2116
|
+
ctx.ui.notify(`Compaction before turn editing failed: ${errMsg(error)}`, "error"); return;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
// The common editor rechecks idle/UI/method state. Escape here leaves the
|
|
2120
|
+
// already completed compaction intact; only the proposed revision is lost.
|
|
2121
|
+
await filterTurns.handler("", ctx);
|
|
2122
|
+
},
|
|
2123
|
+
});
|
|
2124
|
+
pi.registerCommand("filter-turns", filterTurns);
|
|
2125
|
+
|
|
1741
2126
|
pi.on("session_start", (_event, ctx) => {
|
|
2127
|
+
clearAsideSubmission();
|
|
1742
2128
|
const entries = ctx.sessionManager.getBranch();
|
|
1743
2129
|
if (compactionMethod(entries) === "verbatim" && collectBaseAndSpans(entries).base?.kind === "model-summary") {
|
|
1744
2130
|
ctx.ui.notify(MIXED_CONTEXT_WARNING, "warning");
|
|
@@ -1772,10 +2158,40 @@ export default function (pi: ExtensionAPI) {
|
|
|
1772
2158
|
// --------------------------------------------------------------------------
|
|
1773
2159
|
pi.on("session_before_compact", async (event, ctx) => {
|
|
1774
2160
|
const { preparation, branchEntries, reason, signal } = event;
|
|
2161
|
+
const automaticFiltering = reason !== "manual" && autoFilterEnabled(branchEntries);
|
|
1775
2162
|
if (!preparation) return;
|
|
1776
2163
|
if (signal?.aborted) return;
|
|
1777
2164
|
if (preparation.messagesToSummarize.length === 0 && preparation.turnPrefixMessages.length === 0) return;
|
|
1778
2165
|
if (compactionMethod(ctx.sessionManager.getBranch()) === "summary") {
|
|
2166
|
+
const revision = latestFilterRevision(branchEntries);
|
|
2167
|
+
if (revision || Object.keys(turnFidelities(branchEntries)).length) {
|
|
2168
|
+
// Pi prepares from the saved compaction, not our request projection.
|
|
2169
|
+
// Summary mode must consume the revised checkpoint too, rather than
|
|
2170
|
+
// resurrecting filtered text or dropping standalone restorations.
|
|
2171
|
+
const active = latestVerbatimCompaction(branchEntries)!;
|
|
2172
|
+
preparation.previousSummary = projectCheckpoint([{ role: "compactionSummary", summary: active.summary, tokensBefore: active.tokensBefore, timestamp: 0 }], branchEntries)
|
|
2173
|
+
.map((message) => message.role === "compactionSummary" ? message.summary : previewMessages([message]).join("\n")).join("\n\n");
|
|
2174
|
+
const canonical = latestVerbatimCompaction(branchEntries)!.details as {
|
|
2175
|
+
startupReads: StartupReads; readFiles: string[]; modifiedFiles: string[];
|
|
2176
|
+
};
|
|
2177
|
+
const visible = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2178
|
+
canonical.startupReads, canonical.readFiles, canonical.modifiedFiles, new Set(filteredTurns(branchEntries)));
|
|
2179
|
+
const ops = preparation.fileOps;
|
|
2180
|
+
ops.read = new Set(visible.readFiles);
|
|
2181
|
+
ops.edited = new Set(visible.modifiedFiles);
|
|
2182
|
+
ops.written = new Set();
|
|
2183
|
+
for (const message of [...preparation.messagesToSummarize, ...preparation.turnPrefixMessages]) {
|
|
2184
|
+
const calls = message.role === "assistant" ? message.content.filter((block) => block.type === "toolCall")
|
|
2185
|
+
: message.role === "toolResult" ? message.nestedCalls?.calls ?? [] : [];
|
|
2186
|
+
for (const call of calls) {
|
|
2187
|
+
const file = (call.arguments as { path?: unknown } | undefined)?.path;
|
|
2188
|
+
if (typeof file !== "string" || !file) continue;
|
|
2189
|
+
if (call.name === "read") ops.read.add(file);
|
|
2190
|
+
else if (call.name === "write") ops.written.add(file);
|
|
2191
|
+
else if (call.name === "edit") ops.edited.add(file);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
1779
2195
|
return; // No override: Pi runs its normal model-generated compaction.
|
|
1780
2196
|
}
|
|
1781
2197
|
|
|
@@ -1800,8 +2216,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1800
2216
|
}
|
|
1801
2217
|
|
|
1802
2218
|
const modified = new Set([...(fileOps?.edited ?? []), ...(fileOps?.written ?? [])]);
|
|
1803
|
-
const
|
|
1804
|
-
const
|
|
2219
|
+
const canonicalModifiedFiles = [...modified].sort();
|
|
2220
|
+
const canonicalReadFiles = [...(fileOps?.read ?? [])].filter((f) => !modified.has(f)).sort();
|
|
1805
2221
|
|
|
1806
2222
|
// 2) The new span. Pi's preparation span is [previous cut, current cut)
|
|
1807
2223
|
// — it includes the previous compaction's retained tail (verified
|
|
@@ -1821,12 +2237,28 @@ export default function (pi: ExtensionAPI) {
|
|
|
1821
2237
|
const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
|
|
1822
2238
|
const spanFrom = toIso(msgTs(allMessages[0]));
|
|
1823
2239
|
const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
|
|
1824
|
-
const
|
|
2240
|
+
const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
|
|
2241
|
+
for (const file of [...canonicalReadFiles, ...canonicalModifiedFiles]) renderer.locations.ref(file, ctx.cwd, 'path', true);
|
|
2242
|
+
const span = await summarizeMessages(allMessages, renderer, preparedTurnOwners(branchEntries, allMessages));
|
|
1825
2243
|
const spanLines = span.lines;
|
|
1826
2244
|
|
|
1827
2245
|
// 3) Freeze startup references after the second user prompt, then carry
|
|
1828
2246
|
// their original outputs forward outside the trimmable conversation spans.
|
|
1829
|
-
const
|
|
2247
|
+
const canonicalRetained = startupReads(branchEntries, ctx);
|
|
2248
|
+
const excluded = new Set(filteredTurns(branchEntries));
|
|
2249
|
+
const keptAsides = new Set(keptAsideTurns(branchEntries));
|
|
2250
|
+
const fidelity = { ...turnFidelities(branchEntries) }, slots: TurnSlot[] = [];
|
|
2251
|
+
if (automaticFiltering) {
|
|
2252
|
+
const preflags = preflaggedTurns(branchEntries);
|
|
2253
|
+
const proposed = new Set([...excluded, ...[...preflags].filter((id) => !keptAsides.has(id))]);
|
|
2254
|
+
const choices = filterChoices(branchEntries, [...collectBaseAndSpans(branchEntries).spans, span],
|
|
2255
|
+
excluded, preparation.firstKeptEntryId, canonicalRetained, proposed);
|
|
2256
|
+
for (const turn of choices)
|
|
2257
|
+
if (!turn.unavailable && !turn.deferred && proposed.has(turn.id)) excluded.add(turn.id);
|
|
2258
|
+
}
|
|
2259
|
+
const filteredTurnIds = [...excluded];
|
|
2260
|
+
const evidence = checkpointEvidence(branchEntries, preparation.firstKeptEntryId, ctx.cwd,
|
|
2261
|
+
canonicalRetained, canonicalReadFiles, canonicalModifiedFiles, excluded, fidelity);
|
|
1830
2262
|
const summary = await buildMechanicalSummary({
|
|
1831
2263
|
reason, // pi's raw reason, passed through unchanged
|
|
1832
2264
|
tokensBefore: preparation.tokensBefore,
|
|
@@ -1834,17 +2266,19 @@ export default function (pi: ExtensionAPI) {
|
|
|
1834
2266
|
now: nowIso,
|
|
1835
2267
|
spanLines,
|
|
1836
2268
|
spanTools: span.tools,
|
|
2269
|
+
locations: renderer.locations.entries,
|
|
2270
|
+
spanTurnIds: span.turnIds,
|
|
2271
|
+
filteredTurnIds, fidelity, slots,
|
|
1837
2272
|
spanFrom,
|
|
1838
2273
|
spanTo,
|
|
1839
2274
|
firstKeptEntryId: preparation.firstKeptEntryId,
|
|
1840
|
-
|
|
1841
|
-
modifiedFiles,
|
|
1842
|
-
startupReads: retained,
|
|
2275
|
+
...evidence,
|
|
1843
2276
|
cwd: ctx.cwd,
|
|
1844
2277
|
notify: (m) => ctx.ui?.notify?.(m, "warning"),
|
|
1845
2278
|
chooseCap: (size) => chooseCapBudget(pi, ctx, signal, reason, size),
|
|
1846
2279
|
});
|
|
1847
2280
|
if (summary === undefined || signal?.aborted) return { cancel: true };
|
|
2281
|
+
checkCheckpointBudget(summary, slots, fidelity, branchEntries, preparation.firstKeptEntryId, ctx);
|
|
1848
2282
|
|
|
1849
2283
|
ctx.ui?.notify?.(
|
|
1850
2284
|
`transparent-compact: ~${preparation.tokensBefore.toLocaleString()} tokens -> verbatim checkpoint; full transcript kept in the session`,
|
|
@@ -1858,19 +2292,27 @@ export default function (pi: ExtensionAPI) {
|
|
|
1858
2292
|
tokensBefore: preparation.tokensBefore,
|
|
1859
2293
|
details: {
|
|
1860
2294
|
kind: MECH_KIND,
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
2295
|
+
// Canonical metadata stays reversible; only the rendered checkpoint
|
|
2296
|
+
// masks file paths/startup reads owned by excluded turns.
|
|
2297
|
+
readFiles: canonicalReadFiles,
|
|
2298
|
+
modifiedFiles: canonicalModifiedFiles,
|
|
2299
|
+
startupReads: canonicalRetained,
|
|
2300
|
+
locations: renderer.locations.entries,
|
|
2301
|
+
...(filteredTurnIds.length ? { filteredTurnIds } : {}),
|
|
2302
|
+
...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
|
|
2303
|
+
...(Object.keys(fidelity).length ? { fidelity, slots } : {}),
|
|
1864
2304
|
// Only this compaction's own span (un-capped lines). Earlier spans
|
|
1865
2305
|
// are re-rendered from the earlier entries' details — no nesting.
|
|
1866
2306
|
span: { at: nowIso, from: spanFrom, to: spanTo, reason, tokensBefore: preparation.tokensBefore,
|
|
1867
|
-
lines: spanLines, ...(span.tools ? { tools: span.tools } : {}) },
|
|
2307
|
+
lines: spanLines, turnIds: span.turnIds, ...(span.tools ? { tools: span.tools } : {}) },
|
|
1868
2308
|
},
|
|
1869
2309
|
},
|
|
1870
2310
|
};
|
|
1871
2311
|
} catch (err) {
|
|
1872
|
-
|
|
1873
|
-
|
|
2312
|
+
// Never replace a filtered checkpoint with an unfiltered model summary.
|
|
2313
|
+
const preserveFiltering = automaticFiltering || filteredTurns(branchEntries).length > 0 || Object.keys(turnFidelities(branchEntries)).length > 0;
|
|
2314
|
+
ctx.ui?.notify?.(`transparent-compact: failed to build checkpoint (${errMsg(err)}); ${preserveFiltering ? "compaction cancelled" : "falling back to Pi's summary compaction"}`, "error");
|
|
2315
|
+
return preserveFiltering ? { cancel: true } : undefined;
|
|
1874
2316
|
}
|
|
1875
2317
|
});
|
|
1876
2318
|
|