@foliox/transparent-compact-pi 0.10.0 → 0.11.2

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.
@@ -33,7 +33,10 @@ 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, commandPreview, renderToolLine, renderToolStub, NORMAL_PREVIEW_CHARS, TIGHTENED_ATTR } from "./lib/checkpoint-cap.js";
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";
37
40
  import type { ToolLines, ToolStub } from "./lib/checkpoint-cap.js";
38
41
  import { FILTER_EXPLANATION, PREFLAG_ENTRY, AUTO_FILTER_ENTRY, FILTER_REVISION_ENTRY, autoFilterEnabled, preflaggedTurns,
39
42
  filterSpans, pickFilteredTurns, turnOwners } from "./lib/turn-filter.js";
@@ -472,67 +475,6 @@ function branchToTranscript(entries: SessionEntry[]): { lines: string[]; index:
472
475
  // Mechanical summary (what replaces the model summary in the session)
473
476
  // ============================================================================
474
477
 
475
- // Display-only shortening: never change raw arguments or resolve symlinks.
476
- function checkpointPath(value: string, cwd: string): string {
477
- const prefix = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
478
- if (value === cwd) return ".";
479
- return value.startsWith(prefix) ? value.slice(prefix.length) : value;
480
- }
481
-
482
- function checkpointCommand(command: string, cwd: string): string {
483
- const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
484
- // Match complete path prefixes, not sibling directories or URL fragments.
485
- return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, "g"), "$1.");
486
- }
487
-
488
- function argumentSnippet(value: unknown): string {
489
- let s: string;
490
- try {
491
- s = JSON.stringify(value) ?? String(value);
492
- } catch {
493
- s = String(value);
494
- }
495
- return s.length > cfg.argSnippetChars ? `${s.slice(0, cfg.argSnippetChars)}…` : s;
496
- }
497
-
498
- function toolSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): ToolStub {
499
- const a = args ?? {};
500
- if (!["read", "write", "edit", "bash"].includes(name))
501
- return { prefix: `${name}(${Object.entries(a).map(([k, v]) => `${k}=${argumentSnippet(v)}`).join(", ")})`, suffix: "" };
502
- const parts: string[] = [];
503
- let command: ToolStub["command"];
504
- const fileTool = ["read", "write", "edit"].includes(name) && typeof a.path === "string";
505
- let base = fileTool ? `${name} ${JSON.stringify(checkpointPath(a.path as string, cwd))}` : name;
506
- const range = name === "read" && fileTool &&
507
- (a.offset === undefined || (Number.isSafeInteger(a.offset) && (a.offset as number) > 0)) &&
508
- (a.limit === undefined || (Number.isSafeInteger(a.limit) && (a.limit as number) > 0));
509
- if (range && (a.offset !== undefined || a.limit !== undefined)) {
510
- const start = (a.offset as number | undefined) ?? 1;
511
- const end = a.limit === undefined ? "" : start + (a.limit as number) - 1;
512
- base += `:${start}-${end}`; // Requested range, not a claim about returned lines.
513
- }
514
- for (const [k, v] of Object.entries(a)) {
515
- if (fileTool && k === "path") continue;
516
- if (range && (k === "offset" || k === "limit")) continue;
517
- if (name === "bash" && k === "timeout") continue;
518
- if (name === "bash" && k === "command" && typeof v === "string")
519
- command = commandPreview(JSON.stringify(checkpointCommand(v, cwd)));
520
- else if (name === "write" && k === "content" && typeof v === "string")
521
- parts.push(`(${v.length} chars)`);
522
- else if (name === "edit" && k === "edits" && Array.isArray(v))
523
- parts.push(`×${v.length}`);
524
- else if (name === "edit" && (k === "oldText" || k === "newText") && typeof v === "string")
525
- parts.push(`${k}=<${v.length} chars>`);
526
- else parts.push(`${k}=${argumentSnippet(v)}`);
527
- }
528
- return command ? { prefix: `${base} `, command, suffix: parts.length ? ` ${parts.join(" ")}` : "" }
529
- : { prefix: [base, ...parts].join(" "), suffix: "" };
530
- }
531
-
532
- function toolCallSignature(name: string, args: Record<string, unknown> | undefined, cwd: string): string {
533
- return renderToolStub(toolSignature(name, args, cwd));
534
- }
535
-
536
478
  // Conservative lexical categories for selected output observations. These do
537
479
  // not parse shell syntax or establish whether a command succeeded.
538
480
  function commandHints(command: string): { tests: boolean; network: boolean; historical: boolean } {
@@ -613,7 +555,7 @@ function bashOutputLabel(command: string, result: Record<string, any>): string {
613
555
  return labels.join("; ");
614
556
  }
615
557
 
616
- function summarizeMessages(messages: AgentMessage[], cwd: string, owners?: (string | null)[]): TurnSpan {
558
+ async function summarizeMessages(messages: AgentMessage[], renderer: ToolRenderer, owners?: (string | null)[]): Promise<TurnSpan> {
617
559
  const results = pairedToolResults(messages);
618
560
  const lines: string[] = [], turnIds: (string | null)[] = [];
619
561
  const tools: ToolLines = { version: 2, lines: [] };
@@ -637,9 +579,7 @@ function summarizeMessages(messages: AgentMessage[], cwd: string, owners?: (stri
637
579
  const status = typeof result?.isError !== "boolean" ? " [unknown]" : result.isError ? " [tool error]" : "";
638
580
  const command = name === "bash" && typeof args.command === "string" ? args.command : undefined;
639
581
  const label = result && command !== undefined ? bashOutputLabel(command, result) : "";
640
- const stub = toolSignature(name, args, cwd);
641
- stub.suffix += status + (label ? ` → ${label}` : "");
642
- calls.push(stub);
582
+ calls.push(await renderer.render(name, args, status + (label ? ` → ${label}` : "")));
643
583
  }
644
584
  // thinking blocks: removed by design (kept in the session)
645
585
  }
@@ -653,14 +593,18 @@ function summarizeMessages(messages: AgentMessage[], cwd: string, owners?: (stri
653
593
  case "toolResult":
654
594
  // removed by design (kept in the session)
655
595
  break;
656
- case "bashExecution":
657
- lines.push(`[BashExecution]: ${toolCallSignature("bash", { command: String(m.command ?? "") }, cwd)} [output removed]`);
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));
658
601
  break;
602
+ }
659
603
  case "custom":
660
604
  // Our instruction envelope is regenerated, not conversation prose.
661
605
  // Keep originals in raw history, but never carry old checklists into spans.
662
606
  if (m.customType !== REORIENT_MESSAGE)
663
- lines.push(`[Custom message]: ${toolCallSignature("custom", { type: m.customType }, cwd)} [content removed — use context_lookup]`);
607
+ lines.push(`[Custom message]: ${renderToolStub(await renderer.render("custom", { type: m.customType }))} [content removed — use context_lookup]`);
664
608
  break;
665
609
  case "branchSummary":
666
610
  case "compactionSummary":
@@ -792,16 +736,6 @@ ${r.text.join("\n")}
792
736
  ].join("\n\n");
793
737
  }
794
738
 
795
- // File annotations describe evidence, not a guarantee of filesystem freshness.
796
- // Use Pi's projection for visibility, but recorded mutations can invalidate a
797
- // snapshot even when the mutation's message was subsequently omitted.
798
- interface FileEvidence {
799
- kind: "read" | "write";
800
- completeness?: "full" | "partial" | "unknown";
801
- changed?: "edit" | "write";
802
- orderUncertain?: boolean;
803
- }
804
-
805
739
  function fileEvidenceKey(file: string, cwd: string): string {
806
740
  // Lexical normalization only: no stat/realpath, and no symlink-equivalence claim.
807
741
  let normalized = file.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000]/g, " ").replace(/^@/, "");
@@ -813,87 +747,6 @@ function fileEvidenceKey(file: string, cwd: string): string {
813
747
  return path.resolve(cwd, normalized);
814
748
  }
815
749
 
816
- function readCompleteness(args: Record<string, any>, message: Record<string, any>, replaced: boolean): "full" | "partial" | "unknown" {
817
- const blocks = message.content;
818
- if (replaced || !Array.isArray(blocks) || blocks.length !== 1 || blocks[0].type !== "text" || typeof blocks[0].text !== "string") return "unknown";
819
- const text = blocks[0].text;
820
- if (/^Read image file \[/.test(text)) return "unknown";
821
- const truncation = message.details?.truncation;
822
- if (truncation?.firstLineExceedsLimit) return "unknown"; // Only a warning, not file contents.
823
- // Pi's read tool supplies these notices for both default and explicit limits.
824
- if (truncation?.truncated === true || /\[(?:Showing lines [^\n]*Use offset=\d+ to continue\.|\d+ more lines in file\. Use offset=\d+ to continue\.)\]\s*$/.test(text)) return "partial";
825
- const offset = args.offset ?? 1;
826
- if (!Number.isInteger(offset) || offset < 1 || (args.limit != null && (!Number.isInteger(args.limit) || args.limit < 1))) return "unknown";
827
- if (offset > 1) return "partial";
828
- // A limit is not proof of partialness: without a continuation notice Pi reached EOF.
829
- // Unknown argument schemas are not assumed to have Pi's read semantics.
830
- return Object.keys(args).every((key) => ["path", "offset", "limit"].includes(key)) ? "full" : "unknown";
831
- }
832
-
833
- function retainedFileEvidence(entries: SessionEntry[], firstKeptEntryId: string | undefined, cwd: string): Map<string, FileEvidence> {
834
- const evidence = new Map<string, FileEvidence>();
835
- const cut = entries.findIndex((entry) => entry.id === firstKeptEntryId);
836
- if (cut < 0) return evidence;
837
- const visible = new Map(buildSessionProjection(entries).entries.map((entry) => [entry.sourceEntry.id, entry.messages]));
838
- const pending = new Map<string, { name: string; args: Record<string, any>; visible: boolean; orderUncertain: boolean } | null>();
839
- const changed = (name: "edit" | "write", args: Record<string, any>) => {
840
- if (typeof args.path !== "string") return;
841
- const previous = evidence.get(fileEvidenceKey(args.path, cwd));
842
- if (previous) previous.changed = name;
843
- };
844
- for (const entry of entries.slice(cut)) {
845
- if (entry.type !== "message") continue;
846
- const raw = entry.message as unknown as Record<string, any>;
847
- const projected = visible.get(entry.id)?.find((message) => message.role === raw.role) as Record<string, any> | undefined;
848
- if (raw.role === "assistant") {
849
- const blocks = Array.isArray(raw.content) ? raw.content : [];
850
- for (const block of blocks) {
851
- if (block.type !== "toolCall" || typeof block.id !== "string") continue;
852
- // Sibling calls may execute concurrently; result order is not read/write order.
853
- const orderUncertain = typeof block.arguments?.path === "string" && blocks.some((other: any) =>
854
- other !== block && other.type === "toolCall" && ["write", "edit"].includes(other.name) &&
855
- typeof other.arguments?.path === "string" &&
856
- fileEvidenceKey(other.arguments.path, cwd) === fileEvidenceKey(block.arguments.path, cwd));
857
- const shown = projected?.content?.filter?.((b: any) => b.type === "toolCall" && b.id === block.id);
858
- const sameCall = shown?.length === 1 && shown[0].name === block.name &&
859
- JSON.stringify(shown[0].arguments) === JSON.stringify(block.arguments);
860
- pending.set(block.id, pending.has(block.id) ? null : { name: block.name, args: block.arguments ?? {}, visible: sameCall, orderUncertain });
861
- }
862
- } else if (raw.role === "toolResult") {
863
- const call = pending.get(raw.toolCallId);
864
- pending.delete(raw.toolCallId);
865
- if (call && call.name === raw.toolName && typeof call.args.path === "string" && raw.isError === false) {
866
- const key = fileEvidenceKey(call.args.path, cwd);
867
- if (call.name === "write" || call.name === "edit") changed(call.name, call.args);
868
- if (call.visible && projected && call.name === "read") {
869
- const completeness = readCompleteness(call.args, projected, projected.content !== raw.content);
870
- const previous = evidence.get(key);
871
- // A later partial read does not hide an earlier complete snapshot.
872
- if (!previous || previous.changed || previous.orderUncertain || (previous.kind === "read" && previous.completeness !== "full"))
873
- evidence.set(key, { kind: "read", completeness, orderUncertain: call.orderUncertain });
874
- } else if (call.visible && call.name === "write" && typeof call.args.content === "string") {
875
- evidence.set(key, { kind: "write", orderUncertain: call.orderUncertain });
876
- }
877
- }
878
- // Nested calls have metadata but no model-visible read outputs or write payloads.
879
- for (const nested of raw.nestedCalls?.calls ?? []) {
880
- if (nested.status === "ok" && (nested.name === "edit" || nested.name === "write")) changed(nested.name, nested.arguments ?? {});
881
- }
882
- }
883
- }
884
- return evidence;
885
- }
886
-
887
- function fileEvidenceLabel(evidence: FileEvidence | undefined): string | undefined {
888
- if (!evidence) return;
889
- if (evidence.orderUncertain) return `${evidence.kind} in tail; order uncertain`;
890
- if (evidence.changed) return `${evidence.kind} in tail, then ${evidence.changed === "edit" ? "edited" : "written"}`;
891
- if (evidence.kind === "write") return "write content in tail";
892
- return evidence.completeness === "unknown" ? "read output in tail" : `${evidence.completeness} read in tail`;
893
- }
894
-
895
- const FILE_LIST_EXPLANATION = "File lists record earlier operations. Read/write annotations describe retained evidence as of this checkpoint, not live filesystem state; unannotated paths do not establish content visibility.";
896
-
897
750
  const SECTION_HEADER = "### Compacted conversation (oldest first)";
898
751
  const SPAN_CLOSE = "</compacted-span>";
899
752
  const SPAN_TRIMMED_NOTE = "(trimmed for size — use context_lookup)";
@@ -915,6 +768,7 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
915
768
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
916
769
  * (the base is opaque; the session holds the raw history).
917
770
  */
771
+ interface LocationEntry { id: string; key: string; kind: string; value: string; display: string }
918
772
  type StoredSpan = TurnSpan & { at: string; reason: string; from?: string; to?: string };
919
773
 
920
774
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
@@ -973,6 +827,10 @@ interface FilterRevision {
973
827
  slots?: TurnSlot[];
974
828
  }
975
829
 
830
+ function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
831
+ return (latestVerbatimCompaction(entries)?.details as { locations?: LocationEntry[] } | undefined)?.locations ?? [];
832
+ }
833
+
976
834
  function latestFilterRevision(entries: SessionEntry[]) {
977
835
  const compaction = latestVerbatimCompaction(entries);
978
836
  if (!compaction) return;
@@ -1126,7 +984,7 @@ const CHECKPOINT_EXPLANATION = `**Compacted conversation follows.** The earlier
1126
984
 
1127
985
  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\`.`;
1128
986
 
1129
- 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.";
987
+ const EVIDENCE_BOUNDARY_RULE = "**Evidence boundary:** Tool stubs 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.";
1130
988
 
1131
989
  const REORIENT_MESSAGE = "transparent-compact:reorient";
1132
990
  const RECOVERY_RECAP = `**Recovery recap.** ${RECOVERY_SCOPE_RULE} For unfamiliar project details or missing requirements, inspect project files or ask the user instead. If lookup findings are incomplete, use \`context_list_entries\`, \`context_grep\`, or \`context_show_entry\`, following pagination instructions. ${RECOVERY_FILESYSTEM_RULE} Keep these evidence/recovery rules in force as work continues.`;
@@ -1208,7 +1066,8 @@ async function buildMechanicalSummary(opts: {
1208
1066
  now: string;
1209
1067
  spanLines: string[]; // this compaction's own span, un-capped
1210
1068
  revisedAt?: string; // rebuild existing spans only; no new compaction or boundary
1211
- spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
1069
+ spanTools?: ToolLines; // display records; no raw command/program payloads
1070
+ locations?: LocationEntry[];
1212
1071
  spanTurnIds?: (string | null)[];
1213
1072
  filteredTurnIds?: string[];
1214
1073
  fidelity?: TurnFidelities;
@@ -1217,8 +1076,6 @@ async function buildMechanicalSummary(opts: {
1217
1076
  spanFrom?: string; // ISO timestamp of the first summarised message
1218
1077
  spanTo?: string; // ISO timestamp of the last summarised message
1219
1078
  firstKeptEntryId?: string; // start of the verbatim (uncompacted) tail
1220
- readFiles: string[];
1221
- modifiedFiles: string[];
1222
1079
  startupReads: StartupReads;
1223
1080
  cwd: string;
1224
1081
  notify: (msg: string) => void;
@@ -1229,16 +1086,15 @@ async function buildMechanicalSummary(opts: {
1229
1086
  const native = Object.keys(fidelity).length ? fidelityMessages(opts.branchEntries, fidelity, opts.firstKeptEntryId!) : new Map<string, AgentMessage[]>();
1230
1087
  const nativeMessages = [...native.values()].flat();
1231
1088
  const nativeChars = messageTokens(nativeMessages) * 4;
1232
- const nativeResults = pairedToolResults(nativeMessages), nativeReadPaths = new Set<string>();
1233
- for (const message of nativeMessages) if (message.role === "assistant") for (const block of message.content) {
1234
- if (block.type === "toolCall" && block.name === "read" && typeof block.arguments?.path === "string" && nativeResults.get(block)?.isError === false)
1235
- nativeReadPaths.add(fileEvidenceKey(block.arguments.path, opts.cwd));
1236
- }
1237
1089
  const rendered = fidelitySpans(filterSpans(opts.revisedAt ? spans : [...spans, {
1238
1090
  at: opts.now, reason: opts.reason, from: opts.spanFrom, to: opts.spanTo,
1239
1091
  lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
1240
1092
  }], new Set(opts.filteredTurnIds)), fidelity);
1241
1093
  const allSpans = rendered.spans;
1094
+ const locations = new Locations(opts.cwd, opts.locations ?? checkpointLocations(opts.branchEntries));
1095
+ const dictionary = (ids: string[]) => locations.render(new Set(ids));
1096
+ const dictionaryCost = (ids: string[]) => { const text = dictionary(ids); return text ? text.length + 2 : 0; };
1097
+ const allLocationIds = allSpans.flatMap((span) => span.tools?.lines.flatMap((line) => line.calls.flatMap((call) => call.locations ?? [])) ?? []);
1242
1098
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
1243
1099
 
1244
1100
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -1264,7 +1120,7 @@ async function buildMechanicalSummary(opts: {
1264
1120
  overhead += closingLine.length + 2;
1265
1121
  const lines = allSpans.map((s) => s.lines);
1266
1122
  const lineChars = lines.reduce((total, span) => total + span.reduce((n, line) => n + line.length + 1, 0), 0);
1267
- const maxChars = await opts.chooseCap({ overhead, lineChars });
1123
+ const maxChars = await opts.chooseCap({ overhead: overhead + dictionaryCost(allLocationIds), lineChars });
1268
1124
  if (maxChars === null) return undefined;
1269
1125
  if (maxChars !== undefined && base && base.summary.length > maxChars)
1270
1126
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
@@ -1272,7 +1128,7 @@ async function buildMechanicalSummary(opts: {
1272
1128
  opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
1273
1129
  if (maxChars !== undefined && nativeChars > maxChars)
1274
1130
  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.`);
1275
- const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
1131
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost);
1276
1132
  if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
1277
1133
 
1278
1134
  const blocks: string[] = [];
@@ -1302,7 +1158,7 @@ async function buildMechanicalSummary(opts: {
1302
1158
  }
1303
1159
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
1304
1160
  if (opts.revisedAt) parts.push(`${REVISION_NOTE_PREFIX}${opts.revisedAt}. No additional history was compacted; the verbatim boundary is unchanged.`);
1305
- parts.push("- In the compacted spans, user and assistant prose is kept verbatim, subject to budget trimming. Retained prose is a record of what was said, not verification of its claims. Tool signatures are display notation, not replayable shell commands: paths under the working directory become relative (`.` in commands); read ranges are requested lines; write/edit payloads become sizes/counts. New bash previews keep the first 160 encoded characters, followed by … when truncated, with escaped newlines. Thinking and most output are removed; selected output observations remain after →.");
1161
+ parts.push(TOOL_DISPLAY_EXPLANATION);
1306
1162
  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.");
1307
1163
  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.");
1308
1164
  parts.push(
@@ -1315,29 +1171,11 @@ async function buildMechanicalSummary(opts: {
1315
1171
  parts.push(SECTION_HEADER);
1316
1172
  parts.push("");
1317
1173
  parts.push(blocks.length > 0 ? blocks.join("\n\n") : "(no user or assistant prose in these spans — use context_lookup)");
1318
- // The file lists describe the compacted spans, so they belong above the
1319
- // verbatim boundary line. That closing line is the LAST line of the
1320
- // checkpoint; everything after it is pi's retained verbatim tail.
1174
+ // Retained reads and the location dictionary describe compacted history,
1175
+ // above the LAST checkpoint line; everything after it is Pi's verbatim tail.
1321
1176
  if (retainedReads) parts.push("", retainedReads);
1322
- const retainedPaths = new Set(opts.startupReads.reads.map((r) => fileEvidenceKey(r.path, opts.cwd)));
1323
- const hasFileLists = opts.readFiles.length > 0 || opts.modifiedFiles.length > 0;
1324
- if (hasFileLists) {
1325
- const evidence = retainedFileEvidence(opts.branchEntries, opts.firstKeptEntryId, opts.cwd);
1326
- const knownTail = opts.branchEntries.some((entry) => entry.id === opts.firstKeptEntryId);
1327
- const fileLine = (file: string, modified: boolean): string => {
1328
- const key = fileEvidenceKey(file, opts.cwd);
1329
- const label = fileEvidenceLabel(evidence.get(key)) ?? (retainedPaths.has(key)
1330
- ? "startup read output retained in checkpoint or tail; may be partial"
1331
- : nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
1332
- : modified && knownTail ? "no read-tool output in tail" : undefined);
1333
- return `${checkpointPath(file, opts.cwd)}${label ? ` (${label})` : ""}`;
1334
- };
1335
- parts.push("", FILE_LIST_EXPLANATION);
1336
- if (opts.readFiles.length > 0)
1337
- parts.push(`<read-files note="reads in compacted history; unless annotated, no retained read-tool output identified">\n${opts.readFiles.map((file) => fileLine(file, false)).join("\n")}\n</read-files>`);
1338
- if (opts.modifiedFiles.length > 0)
1339
- parts.push(`<modified-files note="modified in compacted history">\n${opts.modifiedFiles.map((file) => fileLine(file, true)).join("\n")}\n</modified-files>`);
1340
- }
1177
+ const locationTable = dictionary(capped.locationIds);
1178
+ if (locationTable) parts.push("", locationTable);
1341
1179
  parts.push("");
1342
1180
  parts.push(EVIDENCE_BOUNDARY_RULE);
1343
1181
  parts.push("");
@@ -2278,7 +2116,8 @@ export default function (pi: ExtensionAPI) {
2278
2116
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
2279
2117
  const spanFrom = toIso(msgTs(allMessages[0]));
2280
2118
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
2281
- const span = summarizeMessages(allMessages, ctx.cwd, preparedTurnOwners(branchEntries, allMessages));
2119
+ const renderer = new ToolRenderer(ctx.cwd, { entries: checkpointLocations(branchEntries) });
2120
+ const span = await summarizeMessages(allMessages, renderer, preparedTurnOwners(branchEntries, allMessages));
2282
2121
  const spanLines = span.lines;
2283
2122
 
2284
2123
  // 3) Freeze startup references after the second user prompt, then carry
@@ -2305,6 +2144,7 @@ export default function (pi: ExtensionAPI) {
2305
2144
  now: nowIso,
2306
2145
  spanLines,
2307
2146
  spanTools: span.tools,
2147
+ locations: renderer.locations.entries,
2308
2148
  spanTurnIds: span.turnIds,
2309
2149
  filteredTurnIds, fidelity, slots,
2310
2150
  spanFrom,
@@ -2335,6 +2175,7 @@ export default function (pi: ExtensionAPI) {
2335
2175
  readFiles: canonicalReadFiles,
2336
2176
  modifiedFiles: canonicalModifiedFiles,
2337
2177
  startupReads: canonicalRetained,
2178
+ locations: renderer.locations.entries,
2338
2179
  ...(filteredTurnIds.length ? { filteredTurnIds } : {}),
2339
2180
  ...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
2340
2181
  ...(Object.keys(fidelity).length ? { fidelity, slots } : {}),
@@ -3,7 +3,8 @@
3
3
  */
4
4
  export const TOOL_PREFIX = "[Tools]: ";
5
5
  export const FILTER_MARKER = "[Turn manually filtered]";
6
- export const NORMAL_PREVIEW_CHARS = 160;
6
+ import { NORMAL_PREVIEW_CHARS, headPrefix, commandPreview } from "./tool-stubs/display.mjs";
7
+ export { NORMAL_PREVIEW_CHARS, commandPreview };
7
8
  export const TIGHTENED_ATTR = ' tools-tightened="true"';
8
9
 
9
10
  // Encoded display fragments, NOT full commands or executable arguments.
@@ -13,34 +14,27 @@ export interface ToolStub {
13
14
  prefix: string;
14
15
  command?: CommandPreview;
15
16
  suffix: string;
17
+ /** Authoritative dictionary references, never inferred by scanning prose. */
18
+ locations?: string[];
16
19
  }
17
20
  export interface ToolLine {
18
21
  index: number;
19
22
  calls: ToolStub[];
20
23
  /** Both adjacent messages must be tool-only before prefixes may be folded. */
21
24
  mergeable: boolean;
25
+ prefix?: string;
22
26
  }
23
27
  export interface ToolLines { version: 2; lines: ToolLine[] }
24
28
  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
- }
29
+ export interface CappedSpans { lines: string[][]; tightened: boolean[]; trimmed: boolean[]; locationIds: string[] }
36
30
  export function renderCommand(preview: CommandPreview, max = NORMAL_PREVIEW_CHARS): string {
37
31
  return headPrefix(preview.head, max) + (preview.truncated || preview.head.length > max ? "…" : "");
38
32
  }
39
33
  export function renderToolStub(stub: ToolStub, max = NORMAL_PREVIEW_CHARS): string {
40
34
  return stub.prefix + (stub.command ? renderCommand(stub.command, max) : "") + stub.suffix;
41
35
  }
42
- export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS): string {
43
- return TOOL_PREFIX + calls.map((call) => renderToolStub(call, max)).join("; ");
36
+ export function renderToolLine(calls: ToolStub[], max = NORMAL_PREVIEW_CHARS, prefix = TOOL_PREFIX): string {
37
+ return prefix + calls.map((call) => renderToolStub(call, max)).join("; ");
44
38
  }
45
39
 
46
40
  // Stored records are optional/versioned. Require exact canonical round-tripping
@@ -55,9 +49,11 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
55
49
  if (!record || !Number.isSafeInteger(record.index) || record.index < 0 || record.index >= span.lines.length) continue;
56
50
  if (seen.has(record.index)) { records.delete(record.index); continue; }
57
51
  seen.add(record.index);
58
- if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length) continue;
52
+ if (typeof record.mergeable !== "boolean" || !Array.isArray(record.calls) || !record.calls.length ||
53
+ (record.prefix !== undefined && record.prefix !== TOOL_PREFIX && record.prefix !== "[BashExecution]: ")) continue;
59
54
  const valid = record.calls.every((call) => {
60
55
  if (!call || typeof call.prefix !== "string" || typeof call.suffix !== "string") return false;
56
+ if (call.locations !== undefined && (!Array.isArray(call.locations) || !call.locations.every((id) => typeof id === "string" && /^@\d+$/.test(id)))) return false;
61
57
  const p = call.command;
62
58
  if (p === undefined) return true;
63
59
  if (!p || typeof p.head !== "string") return false;
@@ -65,7 +61,7 @@ function toolRecords(span: SpanContent): Map<number, ToolLine> {
65
61
  (p.truncated === undefined || typeof p.truncated === "boolean") &&
66
62
  (p.truncated !== true || p.head.length >= NORMAL_PREVIEW_CHARS - 1);
67
63
  });
68
- if (valid && renderToolLine(record.calls) === span.lines[record.index]) records.set(record.index, record);
64
+ if (valid && renderToolLine(record.calls, NORMAL_PREVIEW_CHARS, record.prefix) === span.lines[record.index]) records.set(record.index, record);
69
65
  }
70
66
  } catch { return new Map(); }
71
67
  return records;
@@ -78,6 +74,7 @@ interface Row {
78
74
  calls?: ToolStub[];
79
75
  mergeable: boolean;
80
76
  preview: number;
77
+ prefix: string;
81
78
  foldPrefix: boolean;
82
79
  tightened: boolean;
83
80
  }
@@ -86,22 +83,26 @@ interface Row {
86
83
  * tool-only prefixes, and finally the historical destructive cap.
87
84
  * Every rung walks oldest first, across all spans (not just the new one).
88
85
  */
89
- export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
86
+ export function capSpans(spans: SpanContent[], budget = Infinity, extraChars: (ids: string[]) => number = () => 0): CappedSpans {
90
87
  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);
88
+ const records = spans.map(toolRecords);
89
+ const references = (calls: ToolStub[]) => [...new Set(calls.flatMap((call) => call.locations ?? []))];
90
+ const initialIds = references(records.flatMap((map) => [...map.values()].flatMap((record) => record.calls)));
91
+ let size = spans.reduce((n, span) => n + span.lines.reduce((s, line) => s + line.length + 1, 0), 0) + extraChars(initialIds);
92
+ if (size <= budget) return { lines: spans.map((s) => s.lines.slice()), tightened, trimmed, locationIds: initialIds };
93
+ const states = spans.map((span, spanIndex) => {
94
+ const ownRecords = records[spanIndex];
95
95
  return span.lines.map((text, index): Row => {
96
- const record = records.get(index);
96
+ const record = ownRecords.get(index);
97
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 };
98
+ preview: NORMAL_PREVIEW_CHARS, prefix: record?.prefix ?? TOOL_PREFIX, foldPrefix: false, tightened: false };
99
99
  });
100
100
  });
101
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;
102
+ rows[i].mergeable && rows[i - 1].mergeable && rows[i].prefix === TOOL_PREFIX && rows[i - 1].prefix === TOOL_PREFIX && rows[i].index === rows[i - 1].index + 1;
103
+ const currentIds = () => references(states.flatMap((rows) => rows.flatMap((row) => row.calls ?? [])));
103
104
  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
+ s + row.text.length + 1 - (joined(rows, i) ? TOOL_PREFIX.length - 1 : 0), 0), 0) + extraChars(currentIds());
105
106
  const finish = (): CappedSpans => ({
106
107
  lines: states.map((rows, span) => {
107
108
  const lines: string[] = [];
@@ -112,9 +113,9 @@ export function capSpans(spans: SpanContent[], budget = Infinity): CappedSpans {
112
113
  if (row.tightened || joined(rows, i)) tightened[span] = true;
113
114
  }
114
115
  return lines;
115
- }), tightened, trimmed,
116
+ }), tightened, trimmed, locationIds: currentIds(),
116
117
  });
117
- const render = (row: Row) => renderToolLine(row.calls!, row.preview);
118
+ const render = (row: Row) => renderToolLine(row.calls!, row.preview, row.prefix);
118
119
  const update = (row: Row) => {
119
120
  const text = render(row);
120
121
  if (text.length < row.text.length) {
@@ -0,0 +1,21 @@
1
+ export const NORMAL_PREVIEW_CHARS = 160;
2
+ export function headPrefix(text, max) {
3
+ let end = Math.min(text.length, max);
4
+ if (/[\uD800-\uDBFF]/.test(text[end - 1])) end--;
5
+ return text.slice(0, end);
6
+ }
7
+ export function commandPreview(encoded) {
8
+ return encoded.length <= NORMAL_PREVIEW_CHARS ? { head: encoded }
9
+ : { head: headPrefix(encoded, NORMAL_PREVIEW_CHARS), truncated: true };
10
+ }
11
+ export function argumentSnippet(value) {
12
+ let text;
13
+ try { text = JSON.stringify(value) ?? String(value); } catch { text = String(value); }
14
+ return text.length > NORMAL_PREVIEW_CHARS ? text.slice(0, NORMAL_PREVIEW_CHARS) + '…' : text;
15
+ }
16
+ export const checkpointPath = (value, cwd) => value === cwd ? '.'
17
+ : value.startsWith(cwd.endsWith('/') ? cwd : cwd + '/') ? value.slice(cwd.endsWith('/') ? cwd.length : cwd.length + 1) : value;
18
+ export function checkpointCommand(command, cwd) {
19
+ const escaped = cwd.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
20
+ return command.replace(new RegExp(`(^|[\\s"'=<>|;&(])${escaped}(?=$|[/\\s"'<>|;&)])`, 'g'), '$1.');
21
+ }
@@ -0,0 +1,12 @@
1
+ // Known tools select payload, never infer which arbitrary extension fields are
2
+ // metadata. Unknown tools retain an agnostic bounded argument display.
3
+ const PAYLOAD_FIELDS = new Map([
4
+ ['bash', new Set(['command'])],
5
+ ['read', new Set(['path', 'offset', 'limit'])],
6
+ ['write', new Set(['path', 'content'])],
7
+ ['edit', new Set(['path', 'edits', 'oldText', 'newText'])],
8
+ ]);
9
+ export function selectToolInputs(name, args = {}) {
10
+ const fields = PAYLOAD_FIELDS.get(name);
11
+ return fields ? Object.fromEntries(Object.entries(args ?? {}).filter(([key]) => fields.has(key))) : undefined;
12
+ }
@@ -0,0 +1,42 @@
1
+ import path from 'node:path';
2
+
3
+ /** Append-only, checkpoint-scoped identities. No filesystem access or expansion. */
4
+ export class Locations {
5
+ constructor(cwd, entries = []) {
6
+ this.cwd = cwd;
7
+ this.entries = entries.map(entry => ({ ...entry }));
8
+ this.byKey = new Map(this.entries.map(entry => [entry.key, entry]));
9
+ }
10
+
11
+ describe(value, cwd = this.cwd, kind = 'path', literal = false) {
12
+ if (/^[a-z][a-z\d+.-]*:\/\//i.test(value)) kind = 'url';
13
+ const relative = cwd && value.startsWith(cwd + '/') ? value.slice(cwd.length + 1) : value === cwd ? '' : value;
14
+ const dynamic = !literal && /[$`*?{}\[\]~]/.test(relative);
15
+ // Unknown working directories remain explicitly scoped, never guessed.
16
+ const resolved = kind !== 'path' ? value : dynamic || (!cwd && !path.posix.isAbsolute(value))
17
+ ? `${cwd ?? '?'} :: ${value}` : path.posix.resolve(cwd ?? '/', value);
18
+ const scope = cwd === this.cwd ? '.' : cwd?.startsWith(this.cwd + '/') ? cwd.slice(this.cwd.length + 1) : cwd ?? '?';
19
+ const display = kind !== 'path' ? value : dynamic || (!cwd && !path.posix.isAbsolute(value)) ? `${scope} :: ${value}`
20
+ : resolved === this.cwd ? '.' : resolved.startsWith(this.cwd + '/') ? resolved.slice(this.cwd.length + 1) : resolved;
21
+ return { key: `${kind}:${resolved}`, kind, value: resolved, display };
22
+ }
23
+
24
+ ref(value, cwd = this.cwd, kind = 'path', literal = false) {
25
+ const description = this.describe(value, cwd, kind, literal);
26
+ let entry = this.byKey.get(description.key);
27
+ if (!entry) {
28
+ entry = { id: `@${this.entries.length + 1}`, ...description };
29
+ this.entries.push(entry);
30
+ this.byKey.set(entry.key, entry);
31
+ }
32
+ return entry;
33
+ }
34
+
35
+ render(ids) {
36
+ const entries = ids ? this.entries.filter(entry => ids.has(entry.id)) : this.entries;
37
+ if (!entries.length) return '';
38
+ return ['<locations note="lexical references, not verified accesses; ? means unknown cwd">',
39
+ ...entries.map(entry => `${entry.id} ${entry.kind !== 'path' ? entry.kind.toUpperCase() + ' ' : ''}${JSON.stringify(entry.display)}`),
40
+ '</locations>'].join('\n');
41
+ }
42
+ }
@@ -0,0 +1,39 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import vm from 'node:vm';
3
+ import { webcrypto } from 'node:crypto';
4
+
5
+ let runtime;
6
+ async function loadParser() {
7
+ const [wasm, support] = await Promise.all([
8
+ readFile(new URL('./parser/shell.wasm', import.meta.url)),
9
+ readFile(new URL('./parser/wasm_exec.js', import.meta.url), 'utf8'),
10
+ ]);
11
+ let register;
12
+ const ready = new Promise(resolve => { register = resolve; });
13
+ // Go's unmodified support script installs globals. Keep them local to this
14
+ // runtime so extension reloads do not change Pi's globals or other extensions.
15
+ const scope = vm.createContext({ TextEncoder, TextDecoder, WebAssembly,
16
+ crypto: webcrypto, performance, console, setTimeout, clearTimeout,
17
+ registerShellParser: register });
18
+ vm.runInContext(support, scope, { filename: 'wasm_exec.js' });
19
+ const go = new scope.Go();
20
+ const { instance } = await WebAssembly.instantiate(wasm, go.importObject);
21
+ // run remains pending while registered JS callbacks are available. Race it
22
+ // against registration so an initialization failure cannot leave us waiting.
23
+ const exited = go.run(instance).then(() => { throw new Error('shell parser runtime exited'); });
24
+ const parse = await Promise.race([ready, exited]);
25
+ return { parse, go }; // Keep the instance alive for later callbacks.
26
+ }
27
+
28
+ /** mvdan/sh's official typed JSON, without schema conversion or shell execution.
29
+ * Input bounds are checked before starting WASM. No binary on PATH, downloads,
30
+ * target-file access, or subprocesses are involved at runtime.
31
+ */
32
+ export async function parseShell(command, { maxBytes = 262144 } = {}) {
33
+ if (typeof command !== 'string') throw new TypeError('shell input must be a string');
34
+ if (Buffer.byteLength(command, 'utf8') > maxBytes) throw new Error('shell input byte budget exceeded');
35
+ const { parse } = await (runtime ??= loadParser());
36
+ const result = parse(command);
37
+ if (result.error) throw new SyntaxError(result.error);
38
+ return JSON.parse(result.json);
39
+ }