@foliox/transparent-compact-pi 0.10.0 → 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.
@@ -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":
@@ -915,6 +859,7 @@ function spanOpen(n: number, compactedAt: string, reason: string, covers?: strin
915
859
  * base, oldest first. Spans before the base are deliberately NOT re-rendered
916
860
  * (the base is opaque; the session holds the raw history).
917
861
  */
862
+ interface LocationEntry { id: string; key: string; kind: string; value: string; display: string }
918
863
  type StoredSpan = TurnSpan & { at: string; reason: string; from?: string; to?: string };
919
864
 
920
865
  function collectBaseAndSpans(branchEntries: SessionEntry[]): {
@@ -973,6 +918,10 @@ interface FilterRevision {
973
918
  slots?: TurnSlot[];
974
919
  }
975
920
 
921
+ function checkpointLocations(entries: SessionEntry[]): LocationEntry[] {
922
+ return (latestVerbatimCompaction(entries)?.details as { locations?: LocationEntry[] } | undefined)?.locations ?? [];
923
+ }
924
+
976
925
  function latestFilterRevision(entries: SessionEntry[]) {
977
926
  const compaction = latestVerbatimCompaction(entries);
978
927
  if (!compaction) return;
@@ -1208,7 +1157,8 @@ async function buildMechanicalSummary(opts: {
1208
1157
  now: string;
1209
1158
  spanLines: string[]; // this compaction's own span, un-capped
1210
1159
  revisedAt?: string; // rebuild existing spans only; no new compaction or boundary
1211
- spanTools?: ToolLines; // versioned, bounded display records; no raw payloads
1160
+ spanTools?: ToolLines; // display records; no raw command/program payloads
1161
+ locations?: LocationEntry[];
1212
1162
  spanTurnIds?: (string | null)[];
1213
1163
  filteredTurnIds?: string[];
1214
1164
  fidelity?: TurnFidelities;
@@ -1239,6 +1189,11 @@ async function buildMechanicalSummary(opts: {
1239
1189
  lines: opts.spanLines, tools: opts.spanTools, turnIds: opts.spanTurnIds,
1240
1190
  }], new Set(opts.filteredTurnIds)), fidelity);
1241
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 ?? [])) ?? []);
1242
1197
  const coversOf = (s: { from?: string; to?: string }): string | undefined => (s.from && s.to ? `${s.from} → ${s.to}` : undefined);
1243
1198
 
1244
1199
  // Size guard: the budget covers the conversation section plus retained reads.
@@ -1264,15 +1219,17 @@ async function buildMechanicalSummary(opts: {
1264
1219
  overhead += closingLine.length + 2;
1265
1220
  const lines = allSpans.map((s) => s.lines);
1266
1221
  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 });
1222
+ const maxChars = await opts.chooseCap({ overhead: overhead + dictionaryCost(allLocationIds), lineChars });
1268
1223
  if (maxChars === null) return undefined;
1269
1224
  if (maxChars !== undefined && base && base.summary.length > maxChars)
1270
1225
  opts.notify(`transparent-compact: the base block alone is ${base.summary.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); it is kept un-capped`);
1271
1226
  if (maxChars !== undefined && retainedReads.length > maxChars)
1272
1227
  opts.notify(`transparent-compact: retained startup reads alone are ${retainedReads.length.toLocaleString()} chars (budget ${maxChars.toLocaleString()}); they are kept un-capped`);
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`);
1273
1230
  if (maxChars !== undefined && nativeChars > maxChars)
1274
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.`);
1275
- const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead));
1232
+ const capped = capSpans(allSpans, maxChars === undefined ? undefined : Math.max(500, maxChars - overhead), dictionaryCost);
1276
1233
  if (opts.presentation) opts.presentation.shortened = capped.trimmed.some(Boolean) || capped.tightened.some(Boolean);
1277
1234
 
1278
1235
  const blocks: string[] = [];
@@ -1302,7 +1259,7 @@ async function buildMechanicalSummary(opts: {
1302
1259
  }
1303
1260
  parts.push(`- Latest: ${opts.now} (trigger: ${opts.reason}, ~${opts.tokensBefore.toLocaleString()} tokens before compaction)`);
1304
1261
  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 →.");
1262
+ parts.push(TOOL_DISPLAY_EXPLANATION);
1306
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.");
1307
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.");
1308
1265
  parts.push(
@@ -1330,7 +1287,7 @@ async function buildMechanicalSummary(opts: {
1330
1287
  ? "startup read output retained in checkpoint or tail; may be partial"
1331
1288
  : nativeReadPaths.has(key) ? "historical read output retained in a full-fidelity turn; re-read for current contents"
1332
1289
  : modified && knownTail ? "no read-tool output in tail" : undefined);
1333
- return `${checkpointPath(file, opts.cwd)}${label ? ` (${label})` : ""}`;
1290
+ return `${locations.ref(file, opts.cwd, 'path', true).id}${label ? ` (${label})` : ""}`;
1334
1291
  };
1335
1292
  parts.push("", FILE_LIST_EXPLANATION);
1336
1293
  if (opts.readFiles.length > 0)
@@ -1338,6 +1295,8 @@ async function buildMechanicalSummary(opts: {
1338
1295
  if (opts.modifiedFiles.length > 0)
1339
1296
  parts.push(`<modified-files note="modified in compacted history">\n${opts.modifiedFiles.map((file) => fileLine(file, true)).join("\n")}\n</modified-files>`);
1340
1297
  }
1298
+ const locationTable = dictionary(capped.locationIds);
1299
+ if (locationTable) parts.push("", locationTable);
1341
1300
  parts.push("");
1342
1301
  parts.push(EVIDENCE_BOUNDARY_RULE);
1343
1302
  parts.push("");
@@ -2278,7 +2237,9 @@ export default function (pi: ExtensionAPI) {
2278
2237
  const msgTs = (m: AgentMessage): unknown => (m as unknown as { timestamp?: unknown }).timestamp;
2279
2238
  const spanFrom = toIso(msgTs(allMessages[0]));
2280
2239
  const spanTo = toIso(msgTs(allMessages[allMessages.length - 1]));
2281
- const span = summarizeMessages(allMessages, ctx.cwd, preparedTurnOwners(branchEntries, allMessages));
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));
2282
2243
  const spanLines = span.lines;
2283
2244
 
2284
2245
  // 3) Freeze startup references after the second user prompt, then carry
@@ -2305,6 +2266,7 @@ export default function (pi: ExtensionAPI) {
2305
2266
  now: nowIso,
2306
2267
  spanLines,
2307
2268
  spanTools: span.tools,
2269
+ locations: renderer.locations.entries,
2308
2270
  spanTurnIds: span.turnIds,
2309
2271
  filteredTurnIds, fidelity, slots,
2310
2272
  spanFrom,
@@ -2335,6 +2297,7 @@ export default function (pi: ExtensionAPI) {
2335
2297
  readFiles: canonicalReadFiles,
2336
2298
  modifiedFiles: canonicalModifiedFiles,
2337
2299
  startupReads: canonicalRetained,
2300
+ locations: renderer.locations.entries,
2338
2301
  ...(filteredTurnIds.length ? { filteredTurnIds } : {}),
2339
2302
  ...(keptAsides.size ? { keptAsideTurnIds: [...keptAsides] } : {}),
2340
2303
  ...(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
+ }
@@ -0,0 +1,27 @@
1
+ Copyright 2009 The Go Authors.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of Google LLC nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2016, Daniel Martí. All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions are
5
+ met:
6
+
7
+ * Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ * Redistributions in binary form must reproduce the above
10
+ copyright notice, this list of conditions and the following disclaimer
11
+ in the documentation and/or other materials provided with the
12
+ distribution.
13
+ * Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived from
15
+ this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,13 @@
1
+ # Bundled shell parser
2
+
3
+ `shell.wasm` compiles our `main.go` bridge with the official `mvdan.cc/sh/v3`
4
+ parser and `syntax/typedjson` encoder. `go.mod` pins the upstream release;
5
+ `go.sum` records its checksums. No interpreter is imported.
6
+
7
+ - mvdan/sh: BSD 3-Clause; see `LICENSE.mvdan-sh`.
8
+ - Go runtime and standard library: see `LICENSE.Go` and `PATENTS.Go`.
9
+ - `wasm_exec.js` is copied unmodified from the matching official Go toolchain.
10
+ - `build.json` records the upstream/toolchain versions and generated asset hashes.
11
+
12
+ The bridge and JavaScript loader are part of transparent-compact, under its MIT
13
+ license. The bundled assets require no Go installation or runtime downloads.
@@ -0,0 +1,22 @@
1
+ Additional IP Rights Grant (Patents)
2
+
3
+ "This implementation" means the copyrightable works distributed by
4
+ Google as part of the Go project.
5
+
6
+ Google hereby grants to You a perpetual, worldwide, non-exclusive,
7
+ no-charge, royalty-free, irrevocable (except as stated in this section)
8
+ patent license to make, have made, use, offer to sell, sell, import,
9
+ transfer and otherwise run, modify and propagate the contents of this
10
+ implementation of Go, where such license applies only to those patent
11
+ claims, both currently owned or controlled by Google and acquired in
12
+ the future, licensable by Google that are necessarily infringed by this
13
+ implementation of Go. This grant does not include claims that would be
14
+ infringed only as a consequence of further modification of this
15
+ implementation. If you or your agent or exclusive licensee institute or
16
+ order or agree to the institution of patent litigation against any
17
+ entity (including a cross-claim or counterclaim in a lawsuit) alleging
18
+ that this implementation of Go or any code incorporated within this
19
+ implementation of Go constitutes direct or contributory patent
20
+ infringement, or inducement of patent infringement, then any patent
21
+ rights granted to you under this License for this implementation of Go
22
+ shall terminate as of the date such litigation is filed.
@@ -0,0 +1,12 @@
1
+ {
2
+ "module": "mvdan.cc/sh/v3",
3
+ "version": "v3.14.1",
4
+ "go": "go1.27.3",
5
+ "wasmSha256": "5a3863987dcd484b76f7e30ba2e1b0e7ec44733de2b9020ced47fce1a805759a",
6
+ "runtimeSha256": "0c949f4996f9a89698e4b5c586de32249c3b69b7baadb64d220073cc04acba14",
7
+ "sourceSha256": {
8
+ "main.go": "9e3e81b5b887ebeed4a9ce892f1aacb074f25f1d3bc9e566cb6f5c3934c2c84c",
9
+ "go.mod": "6abdd17a1fbbd701de015c52d58142fb7baefeb3afae0eb95369f0a7d3062bdd",
10
+ "go.sum": "816811ceede3e018d293b5097e3cfea283ce6205309d387c21fce95846e2215b"
11
+ }
12
+ }
@@ -0,0 +1,5 @@
1
+ module github.com/felixwoolford/transparent-compact-pi/shellparser
2
+
3
+ go 1.27.3
4
+
5
+ require mvdan.cc/sh/v3 v3.14.1
@@ -0,0 +1,2 @@
1
+ mvdan.cc/sh/v3 v3.14.1 h1:bXkhQWNHCs0KZEChF8hYS6FC+T2N9mUZLbQv9blditI=
2
+ mvdan.cc/sh/v3 v3.14.1/go.mod h1:syYCoFET8w9tvevxiXUtY8/ICrU+l26jHmhJDra3Vwo=
@@ -0,0 +1,36 @@
1
+ // The bridge deliberately uses upstream's AST encoder, not a custom AST schema.
2
+ // No interpreter, command execution, filesystem access, or shell expansion.
3
+ package main
4
+
5
+ import (
6
+ "bytes"
7
+ "fmt"
8
+ "strings"
9
+ "syscall/js"
10
+
11
+ "mvdan.cc/sh/v3/syntax"
12
+ "mvdan.cc/sh/v3/syntax/typedjson"
13
+ )
14
+
15
+ func parse(_ js.Value, args []js.Value) (result any) {
16
+ // Keep an unexpected upstream panic from terminating the cached WASM runtime.
17
+ defer func() {
18
+ if err := recover(); err != nil {
19
+ result = map[string]any{"error": fmt.Sprint(err)}
20
+ }
21
+ }()
22
+ file, err := syntax.NewParser(syntax.Variant(syntax.LangBash)).Parse(strings.NewReader(args[0].String()), "")
23
+ if err != nil {
24
+ return map[string]any{"error": err.Error()}
25
+ }
26
+ var out bytes.Buffer
27
+ if err := typedjson.Encode(&out, file); err != nil {
28
+ return map[string]any{"error": err.Error()}
29
+ }
30
+ return map[string]any{"json": out.String()}
31
+ }
32
+
33
+ func main() {
34
+ js.Global().Call("registerShellParser", js.FuncOf(parse))
35
+ select {}
36
+ }