repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

feat(cmprss): bound retrieval and add A/B benchmark

dabecc2355d52f181559102a54e648ccc1b143ab

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (11)

+1324 / −26 text lines

Diff layout

CHANGELOG.md

Modified

+1 / −0 text lines

3838- Fix repeated Decay compactions so paraphrased memories reuse the same identity without being counted as new occurrences
3939- Add Continuity to automatically resume the current task after context compaction while yielding to queued messages and active Goal or Tune runs
4040- Fix Continuity so it resumes user intent only when actionable work remains and stops instead of rerunning completed checks, retrying known blockers, or inventing follow-up work
41- Make cmprss retrieval use bounded exact UTF-8 ranges, capped at 8192 bytes per call, with continuation offsets and replay-persistent savings accounting
4142- Fix The System README artifact path docs to show plural directories
4243- Make `/system init` deterministic with confirmation; it creates schema v3 config, plural artifact directories, and core files directly
4344- Add an optional project title to The System config; `/system init` writes it from the project directory name and rendered books use it

docs/super/specs/2026-07-03-cmprss-pi-extension-design.md

Modified

+18 / −9 text lines

121121- Store the original compressed block under a hash.
122122- Emit a marker with hash, original size, compressed size, and omitted count.
123- Register a `cmprss_retrieve` tool that returns the exact original block by hash.
123- Register a `cmprss_retrieve` tool that returns bounded exact UTF-8 ranges by hash and byte offset.
125125No injected provider tools.
126126No response-handler loop.
186186Default mode: enabled.
187187Default threshold: `20000` UTF-8 bytes.
188188Default persisted retrieval store capacity: `64` blocks per session branch.
189Default maximum retrieved bytes: unlimited for exact hash retrieval, because retrieval is explicit.
189Default and maximum retrieved bytes per call: `8192`.
190Retrieval reports the next UTF-8 boundary when more bytes remain.
191192### Compressible tools
242243```ts
244245 hash: string;
246 offset?: number; // UTF-8 byte offset, default 0
247 limit?: number; // 1..8192, default 8192
246249```
248251Result:
250- Exact original text for the hash.
251- Metadata: hash, original bytes, compressed bytes, compressor, source tool, created time.
253- Exact original text from the requested UTF-8 byte range.
254- A continuation marker when more bytes remain.
255- Metadata: hash, offset, next offset, requested limit, returned bytes, total bytes, and continuation state.
253257If the hash is unknown, throw or return an error result clearly saying `cmprss: unknown hash`.
254258Do not fake success.
260264```text
261265[cmprss: <tool> <originalBytes>B → <compressedBytes>B, saved ~<tokens>t, hash=<hash>]
262Use cmprss_retrieve(hash="<hash>") for exact original text.
266Use cmprss_retrieve(hash="<hash>") for bounded exact UTF-8 ranges.
263267```
265269For `read`, append:
304308type CmprssStateEvent =
305309 | { op: "enabled"; enabled: boolean; at: number }
306310 | { op: "clear"; at: number }
307 | { op: "block"; meta: CmprssBlockMeta; originalText: string; at: number };
311 | { op: "block"; meta: CmprssBlockMeta; originalText: string; at: number }
312 | { op: "retrieve"; hash: string; contextBytes: number; at: number };
308313```
310315The original text is persisted in the custom entry for every compressed block.
600605`cmprss` stores exact tool output in process memory.
601606That may include secrets already exposed to the model by a tool result.
602607It must not print stored originals in stats, UI, or details.
603Only `cmprss_retrieve(hash)` returns the exact original.
608Only `cmprss_retrieve(hash, offset, limit)` returns exact original ranges.
609Each returned range reduces reported savings by its full tool-result byte size.
605611Do not scan files independently in v1.
606612Only handle Pi tool outputs already produced.
616622- Small results pass through unchanged.
617623- Disabled mode passes through unchanged.
618624- Oversized text compresses and stores retrievable original.
619- Retrieval returns exact original for a known hash.
625- Retrieval returns exact bounded UTF-8 ranges for a known hash.
626- Retrieval never exceeds `8192` original bytes per call.
627- Retrieval accounting survives session replay and reduces reported savings.
628- Retrieval tool UI renders hash, offset, limit, range metadata, and expanded-only content.
620629- Retrieval miss fails loud.
621630- Existing details are preserved.
622631- Explicit `read` windows are not compressed.
670679- Loading the extension does not start a server or spawn a process.
671680- `cmprss_retrieve` works without network access.
672681- A large `bash` output is compressed before the next model turn.
673- The original large output can be retrieved by hash after restarting Pi.
682- The original large output can be retrieved in bounded ranges by hash after restarting Pi.
674683- Explicit `read offset/limit` output is never compressed.
675684- `mise run ci` passes.

extensions/cmprss/README.md

Modified

+25 / −3 text lines

2121Pi tools:
23- `cmprss_retrieve` — retrieve exact original text by hash.
23- `cmprss_retrieve` — retrieve bounded exact UTF-8 ranges by hash, byte offset, and byte limit.
2525Pi hooks:
4545## Behavior
4747`cmprss` compresses large text tool results before the next model turn.
48It stores the exact original in Pi session history, so restarting Pi can still retrieve the hidden bytes.
48It stores the exact original in Pi session history, so restarting Pi can still retrieve hidden ranges.
49Retrieval defaults to byte offset `0` and returns at most `8192` bytes per call.
50Continuation metadata supplies the next UTF-8 boundary, while retrieval bytes reduce reported savings.
4951For pre-truncated Pi bash results, it persists `details.fullOutputPath` content when available.
5153Default compressors:
6971```text
7072[cmprss: bash 58000B → 7000B, saved ~12000t, hash=abc123]
71Use cmprss_retrieve(hash="abc123") for exact original text.
73Use cmprss_retrieve(hash="abc123") for bounded exact UTF-8 ranges.
7274```
76## A/B evaluation
78Run the isolated one-shot baseline and current extension against deterministic fixtures for all six compressors:
80```text
81mise //extensions/cmprss:ab
82```
84After changing cmprss, run only the modified case and compare its persistent result with prior runs:
86```text
87mise //extensions/cmprss:ab -- --case modified
88```
90The default subject and blinded judge model is `openai-codex/gpt-5.6-luna`.
91Use `--model`, `--judge-model`, `--thinking`, or `--repeats` to override the fixed run parameters.
92The runner disables discovered extensions, skills, prompts, themes, context files, sessions, and RTK.
93It records provider usage, compression bytes, retrieval bytes, exact-answer score, blinded judge score, fixtures, events, and the tested extension source under `$XDG_STATE_HOME/pi/cmprss-ab`.
94Run `--dry-run` to inspect fixture sizes, expected compressors, and the prompt without calling a model.
7496No server.
7597No proxy.
7698No Python.

extensions/cmprss/__bench__/ab.ts

Added
new file mode 100644

+714 / −0 text lines

1import { spawn } from "node:child_process";
2import { createHash } from "node:crypto";
3import {
4 appendFile,
5 cp,
6 mkdir,
7 mkdtemp,
8 readFile,
9 rm,
10 writeFile,
11} from "node:fs/promises";
12import { homedir, tmpdir } from "node:os";
13import { dirname, join, resolve } from "node:path";
14import { fileURLToPath } from "node:url";
16const MAX_FIXTURE_BYTES = 50_000;
17const CMPRSS_THRESHOLD_BYTES = 20_000;
18const CASES = ["baseline", "current", "modified"] as const;
19type CaseName = (typeof CASES)[number];
21type Usage = {
22 input: number;
23 output: number;
24 cacheRead: number;
25 cacheWrite: number;
26 totalTokens: number;
27};
29type Benchmark = {
30 files: Record<string, string>;
31 prompt: string;
32 expected: Record<string, string>;
33 expectedCompressors: Record<string, string>;
34};
36type EventSummary = {
37 usage: Usage;
38 compression: {
39 blocks: number;
40 originalBytes: number;
41 compressedBytes: number;
42 retrievals: number;
43 retrievedContextBytes: number;
44 netSavedBytes: number;
45 };
46 toolCalls: Record<string, number>;
47 finalText: string;
48 provider?: string;
49 model?: string;
50};
52type HardScore = {
53 score: number;
54 correct: number;
55 total: number;
56 fields: Record<string, boolean>;
57 parsed?: Record<string, unknown>;
58};
60function repeated(label: string, count: number, width: number): string[] {
61 return Array.from({ length: count }, (_, index) =>
62 `${label} ${String(index + 1).padStart(3, "0")} `.padEnd(width, "x"),
63 );
64}
66export function createBenchmark(): Benchmark {
67 const expected = {
68 jsonCode: "JX-7391-ORBIT",
69 searchNeedle: "SEARCH-CEDAR-482",
70 diffNewValue: "DIFF-QUARTZ-913",
71 stackRootCause: "STACK-EMBER-267",
72 logFailure: "LOG-ANCHOR-644",
73 logTail: "TAIL-SILVER-508",
74 textMiddle: "TEXT-MARIGOLD-351",
75 };
77 const records = Array.from({ length: 120 }, (_, index) => ({
78 id: index + 1,
79 status: "ready",
80 payload: `record-${index + 1}-${"j".repeat(145)}`,
81 ...(index === 59 ? { releaseCode: expected.jsonCode } : {}),
82 }));
83 const json = JSON.stringify({ benchmark: "cmprss-json", records }, null, 2);
85 const search = Array.from({ length: 190 }, (_, index) => {
86 const body =
87 index === 94
88 ? `needle=${expected.searchNeedle}`
89 : `ordinary match ${index + 1} ${"s".repeat(112)}`;
90 return `src/catalog.ts:${index + 1}:${body}`;
91 }).join("\n");
93 const diffLines = [
94 "diff --git a/config.ts b/config.ts",
95 "--- a/config.ts",
96 "+++ b/config.ts",
97 ];
98 for (let index = 0; index < 145; index++) {
99 diffLines.push(`@@ -${index + 1},1 +${index + 1},1 @@`);
100 diffLines.push(
101 `-export const value${index + 1} = "old-${"d".repeat(55)}";`,
102 );
103 const value =
104 index === 19
105 ? expected.diffNewValue
106 : `new-${index + 1}-${"d".repeat(55)}`;
107 diffLines.push(`+export const value${index + 1} = "${value}";`);
108 }
109 const diff = diffLines.join("\n");
111 const stackLines = ["Error: benchmark top-level exception"];
112 for (let index = 0; index < 285; index++) {
113 stackLines.push(
114 ` at dependencyFunction${index + 1} (/vendor/package-${index % 17}/generated-file-${index + 1}.js:${index + 10}:42) ${"q".repeat(25)}`,
115 );
116 }
117 stackLines.push(`Caused by: Error: ${expected.stackRootCause}`);
118 const stacktrace = stackLines.join("\n");
120 const logLines = repeated("build activity", 310, 96);
121 logLines[154] = `ERROR build failed: ${expected.logFailure}`;
122 logLines[309] = `completion token: ${expected.logTail}`;
123 const log = logLines.join("\n");
125 const narrativeLines = repeated("calm narrative segment", 315, 96);
126 narrativeLines[157] = `middle token: ${expected.textMiddle}`;
127 const narrative = narrativeLines.join("\n");
129 const files = {
130 "fixtures/data.json": json,
131 "fixtures/search.txt": search,
132 "fixtures/change.diff": diff,
133 "fixtures/stacktrace.txt": stacktrace,
134 "fixtures/build.log": log,
135 "fixtures/narrative.txt": narrative,
136 };
137 for (const [path, content] of Object.entries(files)) {
138 const size = Buffer.byteLength(content);
139 if (size <= CMPRSS_THRESHOLD_BYTES || size >= MAX_FIXTURE_BYTES)
140 throw new Error(`invalid benchmark fixture size: ${path}=${size}B`);
141 }
143 return {
144 files,
145 expected,
146 expectedCompressors: {
147 "fixtures/data.json": "json",
148 "fixtures/search.txt": "search",
149 "fixtures/change.diff": "diff",
150 "fixtures/stacktrace.txt": "stacktrace",
151 "fixtures/build.log": "log",
152 "fixtures/narrative.txt": "text",
153 },
154 prompt: `Read these six files exactly once each, using the read tool with only its path parameter and no offset or limit: fixtures/data.json, fixtures/search.txt, fixtures/change.diff, fixtures/stacktrace.txt, fixtures/build.log, fixtures/narrative.txt.
156After every read completes, recover the exact requested values. Use cmprss_retrieve when available and necessary. Return only one JSON object with exactly these string keys: jsonCode, searchNeedle, diffNewValue, stackRootCause, logFailure, logTail, textMiddle. Do not guess, omit keys, add commentary, or wrap the JSON in Markdown.`,
157 };
158}
160function parseJsonObject(text: string): Record<string, unknown> | undefined {
161 const trimmed = text.trim();
162 const unfenced = trimmed
163 .replace(/^```(?:json)?\s*/iu, "")
164 .replace(/\s*```$/u, "")
165 .trim();
166 for (const candidate of [
167 unfenced,
168 unfenced.slice(unfenced.indexOf("{"), unfenced.lastIndexOf("}") + 1),
169 ]) {
170 if (!candidate) continue;
171 try {
172 const parsed = JSON.parse(candidate);
173 if (
174 parsed !== null &&
175 typeof parsed === "object" &&
176 !Array.isArray(parsed)
177 )
178 return parsed as Record<string, unknown>;
179 } catch {}
180 }
181 return undefined;
182}
184export function compareWithHistory(
185 result: Record<string, any>,
186 history: Array<Record<string, any>>,
187): Array<{
188 case: "baseline" | "current";
189 tokenDelta: number;
190 tokenDeltaPercent: number;
191 hardDelta: number;
192 judgeDelta: number;
193}> {
194 const targetCases =
195 result.case === "modified"
196 ? (["baseline", "current"] as const)
197 : result.case === "current"
198 ? (["baseline"] as const)
199 : [];
200 return targetCases.flatMap((caseName) => {
201 const reference = history.findLast((entry) => entry.case === caseName);
202 if (!reference) return [];
203 const tokens = number(result.subject?.usage?.totalTokens);
204 const referenceTokens = number(reference.subject?.usage?.totalTokens);
205 return [
206 {
207 case: caseName,
208 tokenDelta: tokens - referenceTokens,
209 tokenDeltaPercent:
210 referenceTokens === 0
211 ? 0
212 : Math.round(
213 ((tokens - referenceTokens) / referenceTokens) * 1_000,
214 ) / 10,
215 hardDelta:
216 number(result.subject?.hardScore?.score) -
217 number(reference.subject?.hardScore?.score),
218 judgeDelta:
219 number(result.judge?.result?.score) -
220 number(reference.judge?.result?.score),
221 },
222 ];
223 });
224}
226export function scoreCandidate(
227 text: string,
228 expected: Record<string, string>,
229): HardScore {
230 const parsed = parseJsonObject(text);
231 const fields = Object.fromEntries(
232 Object.entries(expected).map(([key, value]) => [
233 key,
234 parsed?.[key] === value,
235 ]),
236 );
237 const total = Object.keys(expected).length;
238 const correct = Object.values(fields).filter(Boolean).length;
239 return {
240 score: Math.round((correct / total) * 100),
241 correct,
242 total,
243 fields,
244 parsed,
245 };
246}
248function textContent(content: unknown): string {
249 if (!Array.isArray(content)) return "";
250 return content
251 .filter(
252 (part): part is { type: "text"; text: string } =>
253 part !== null &&
254 typeof part === "object" &&
255 (part as { type?: unknown }).type === "text" &&
256 typeof (part as { text?: unknown }).text === "string",
257 )
258 .map((part) => part.text)
259 .join("\n");
260}
262function number(value: unknown): number {
263 return typeof value === "number" && Number.isFinite(value) ? value : 0;
264}
266export function summarizeEvents(events: unknown[]): EventSummary {
267 const usage: Usage = {
268 input: 0,
269 output: 0,
270 cacheRead: 0,
271 cacheWrite: 0,
272 totalTokens: 0,
273 };
274 const compression = {
275 blocks: 0,
276 originalBytes: 0,
277 compressedBytes: 0,
278 retrievals: 0,
279 retrievedContextBytes: 0,
280 netSavedBytes: 0,
281 };
282 const toolCalls: Record<string, number> = {};
283 let finalText = "";
284 let provider: string | undefined;
285 let model: string | undefined;
287 for (const event of events) {
288 if (event === null || typeof event !== "object") continue;
289 const record = event as Record<string, any>;
290 if (record.type === "message_end" && record.message?.role === "assistant") {
291 const current = record.message.usage ?? {};
292 usage.input += number(current.input);
293 usage.output += number(current.output);
294 usage.cacheRead += number(current.cacheRead);
295 usage.cacheWrite += number(current.cacheWrite);
296 usage.totalTokens += number(current.totalTokens);
297 finalText = textContent(record.message.content);
298 provider = record.message.provider ?? provider;
299 model = record.message.model ?? model;
300 }
301 if (record.type !== "tool_execution_end") continue;
302 const toolName = String(record.toolName ?? "unknown");
303 toolCalls[toolName] = (toolCalls[toolName] ?? 0) + 1;
304 const details = record.result?.details;
305 if (details?.cmprss) {
306 compression.blocks++;
307 compression.originalBytes += number(details.cmprss.originalBytes);
308 compression.compressedBytes += number(details.cmprss.compressedBytes);
309 }
310 if (toolName === "cmprss_retrieve") {
311 compression.retrievals++;
312 compression.retrievedContextBytes += Buffer.byteLength(
313 textContent(record.result?.content),
314 );
315 }
316 }
317 compression.netSavedBytes =
318 compression.originalBytes -
319 compression.compressedBytes -
320 compression.retrievedContextBytes;
321 return { usage, compression, toolCalls, finalText, provider, model };
322}
324type CliOptions = {
325 cases: CaseName[];
326 model: string;
327 judgeModel: string;
328 thinking: string;
329 repeats: number;
330 dryRun: boolean;
331};
333function parseArgs(args: string[]): CliOptions {
334 const options: CliOptions = {
335 cases: [],
336 model: "openai-codex/gpt-5.6-luna",
337 judgeModel: "openai-codex/gpt-5.6-luna",
338 thinking: "off",
339 repeats: 1,
340 dryRun: false,
341 };
342 for (let index = 0; index < args.length; index++) {
343 const arg = args[index];
344 if (arg === "--case") {
345 const value = args[++index] as CaseName | undefined;
346 if (!value || !CASES.includes(value))
347 throw new Error(`--case must be one of: ${CASES.join(", ")}`);
348 options.cases.push(value);
349 } else if (arg === "--model") options.model = args[++index] ?? "";
350 else if (arg === "--judge-model") options.judgeModel = args[++index] ?? "";
351 else if (arg === "--thinking") options.thinking = args[++index] ?? "";
352 else if (arg === "--repeats") {
353 options.repeats = Number(args[++index]);
354 if (!Number.isInteger(options.repeats) || options.repeats < 1)
355 throw new Error("--repeats must be a positive integer");
356 } else if (arg === "--dry-run") options.dryRun = true;
357 else throw new Error(`unknown argument: ${arg}`);
358 }
359 if (options.cases.length === 0) options.cases = ["baseline", "current"];
360 return options;
361}
363function hash(text: string | Buffer): string {
364 return createHash("sha256").update(text).digest("hex");
365}
367async function writeBenchmark(
368 root: string,
369 benchmark: Benchmark,
370): Promise<void> {
371 for (const [path, content] of Object.entries(benchmark.files)) {
372 const target = join(root, path);
373 await mkdir(dirname(target), { recursive: true });
374 await writeFile(target, content);
375 }
376 await mkdir(join(root, ".pi"), { recursive: true });
377 await writeFile(
378 join(root, ".pi", "settings.json"),
379 `${JSON.stringify(
380 {
381 cmprss: {
382 enabled: true,
383 thresholdBytes: CMPRSS_THRESHOLD_BYTES,
384 maxStoredBlocks: 64,
385 status: false,
386 tools: ["read"],
387 },
388 },
389 null,
390 2,
391 )}\n`,
392 );
393}
395type PiRun = {
396 events: unknown[];
397 durationMs: number;
398 stderr: string;
399};
401async function runPi(
402 args: string[],
403 cwd: string,
404 eventsPath: string,
405 stderrPath: string,
406): Promise<PiRun> {
407 const started = performance.now();
408 const child = spawn(process.env.PI_BENCH_PI ?? "pi", args, {
409 cwd,
410 env: {
411 ...process.env,
412 PI_SKIP_VERSION_CHECK: "1",
413 RTK_DISABLED: "1",
414 },
415 stdio: ["ignore", "pipe", "pipe"],
416 });
417 const events: unknown[] = [];
418 let stdout = "";
419 let stderr = "";
420 child.stdout.setEncoding("utf8");
421 child.stderr.setEncoding("utf8");
422 child.stdout.on("data", (chunk: string) => {
423 stdout += chunk;
424 });
425 child.stderr.on("data", (chunk: string) => {
426 stderr += chunk;
427 });
428 const code = await new Promise<number | null>((resolveCode, reject) => {
429 child.once("error", reject);
430 child.once("close", resolveCode);
431 });
432 await writeFile(eventsPath, stdout);
433 await writeFile(stderrPath, stderr);
434 for (const line of stdout.split("\n")) {
435 if (!line.trim()) continue;
436 try {
437 events.push(JSON.parse(line));
438 } catch {
439 throw new Error(`pi emitted non-JSON output: ${line.slice(0, 200)}`);
440 }
441 }
442 if (code !== 0) throw new Error(`pi exited ${code}: ${stderr.trim()}`);
443 return { events, durationMs: performance.now() - started, stderr };
444}
446function commonPiArgs(model: string, thinking: string): string[] {
447 return [
448 "--mode",
449 "json",
450 "--no-session",
451 "--no-extensions",
452 "--no-skills",
453 "--no-prompt-templates",
454 "--no-themes",
455 "--no-context-files",
456 "--approve",
457 "--offline",
458 "--model",
459 model,
460 "--thinking",
461 thinking,
462 ];
463}
465async function gitHead(cwd: string): Promise<string | undefined> {
466 const child = spawn("git", ["rev-parse", "HEAD"], {
467 cwd,
468 stdio: ["ignore", "pipe", "ignore"],
469 });
470 let stdout = "";
471 child.stdout.setEncoding("utf8");
472 child.stdout.on("data", (chunk: string) => {
473 stdout += chunk;
474 });
475 const code = await new Promise<number | null>((resolveCode) =>
476 child.once("close", resolveCode),
477 );
478 return code === 0 ? stdout.trim() : undefined;
479}
481async function runJudge(
482 candidate: string,
483 benchmark: Benchmark,
484 options: CliOptions,
485 cwd: string,
486 resultDir: string,
487): Promise<{ parsed?: Record<string, unknown>; summary: EventSummary }> {
488 const prompt = `Grade the candidate against the expected answer field by field. Allow semantically equivalent wording, but not missing or invented values. Return only JSON with keys score (integer 0..100), fieldScores (object mapping every expected key to 0 or 1), and reason (one short string).\n\nExpected:\n${JSON.stringify(benchmark.expected)}\n\nCandidate:\n${JSON.stringify(candidate)}`;
489 const run = await runPi(
490 [
491 ...commonPiArgs(options.judgeModel, "off"),
492 "--no-tools",
493 "--system-prompt",
494 "You are a blinded benchmark judge. Follow the grading prompt exactly.",
495 prompt,
496 ],
497 cwd,
498 join(resultDir, "judge-events.jsonl"),
499 join(resultDir, "judge-stderr.txt"),
500 );
501 return {
502 parsed: parseJsonObject(summarizeEvents(run.events).finalText),
503 summary: summarizeEvents(run.events),
504 };
505}
507function stateRoot(): string {
508 return join(
509 process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"),
510 "pi",
511 "cmprss-ab",
512 );
513}
515function timestamp(): string {
516 return new Date().toISOString().replaceAll(":", "-");
517}
519async function runCase(
520 caseName: CaseName,
521 repeat: number,
522 options: CliOptions,
523 benchmark: Benchmark,
524 repoRoot: string,
525 extensionPath: string,
526 historyPath: string,
527): Promise<Record<string, any>> {
528 const runId = `${timestamp()}_${caseName}_${repeat}`;
529 const resultDir = join(dirname(historyPath), "runs", runId);
530 await mkdir(resultDir, { recursive: true });
531 const fixtureRoot = await mkdtemp(join(tmpdir(), "cmprss-ab-"));
532 try {
533 await writeBenchmark(fixtureRoot, benchmark);
534 await cp(join(fixtureRoot, "fixtures"), join(resultDir, "fixtures"), {
535 recursive: true,
536 });
537 const args = [
538 ...commonPiArgs(options.model, options.thinking),
539 "--tools",
540 "read,cmprss_retrieve",
541 "--system-prompt",
542 "You are running a controlled retrieval benchmark. Follow the user prompt exactly and use no unrequested tools.",
543 ];
544 let extensionSha256: string | undefined;
545 if (caseName !== "baseline") {
546 const source = await readFile(extensionPath);
547 extensionSha256 = hash(source);
548 await writeFile(join(resultDir, "cmprss.ts"), source);
549 args.push("--extension", extensionPath);
550 }
551 args.push(benchmark.prompt);
552 const subject = await runPi(
553 args,
554 fixtureRoot,
555 join(resultDir, "subject-events.jsonl"),
556 join(resultDir, "subject-stderr.txt"),
557 );
558 const summary = summarizeEvents(subject.events);
559 const hardScore = scoreCandidate(summary.finalText, benchmark.expected);
560 const judge = await runJudge(
561 summary.finalText,
562 benchmark,
563 options,
564 fixtureRoot,
565 resultDir,
566 );
567 const fixtureHashes = Object.fromEntries(
568 Object.entries(benchmark.files).map(([path, content]) => [
569 path,
570 hash(content),
571 ]),
572 );
573 const result = {
574 schemaVersion: 1,
575 runId,
576 case: caseName,
577 repeat,
578 createdAt: new Date().toISOString(),
579 modelRequested: options.model,
580 judgeModelRequested: options.judgeModel,
581 thinking: options.thinking,
582 gitHead: await gitHead(repoRoot),
583 extensionSha256,
584 prompt: benchmark.prompt,
585 promptSha256: hash(benchmark.prompt),
586 expected: benchmark.expected,
587 fixtureHashes,
588 subject: {
589 ...summary,
590 durationMs: Math.round(subject.durationMs),
591 hardScore,
592 },
593 judge: {
594 result: judge.parsed,
595 usage: judge.summary.usage,
596 provider: judge.summary.provider,
597 model: judge.summary.model,
598 },
599 artifacts: resultDir,
600 };
601 await writeFile(
602 join(resultDir, "result.json"),
603 `${JSON.stringify(result, null, 2)}\n`,
604 );
605 await appendFile(historyPath, `${JSON.stringify(result)}\n`);
606 return result;
607 } finally {
608 await rm(fixtureRoot, { recursive: true, force: true });
609 }
610}
612function signed(value: number): string {
613 return value > 0 ? `+${value}` : String(value);
614}
616function printResult(
617 result: Record<string, any>,
618 history: Array<Record<string, any>>,
619): void {
620 const subject = result.subject;
621 const soft = number(result.judge?.result?.score);
622 console.log(
623 [
624 result.case.padEnd(8),
625 `tokens=${String(subject.usage.totalTokens).padStart(7)}`,
626 `hard=${String(subject.hardScore.score).padStart(3)}`,
627 `judge=${String(soft).padStart(3)}`,
628 `net=${String(subject.compression.netSavedBytes).padStart(8)}B`,
629 `retrieve=${subject.compression.retrievals}`,
630 `time=${(subject.durationMs / 1000).toFixed(1)}s`,
631 ].join(" "),
632 );
633 for (const comparison of compareWithHistory(result, history)) {
634 console.log(
635 ` vs ${comparison.case}: tokens=${signed(comparison.tokenDelta)} (${signed(comparison.tokenDeltaPercent)}%) hard=${signed(comparison.hardDelta)} judge=${signed(comparison.judgeDelta)}`,
636 );
637 }
638}
640async function readHistory(path: string): Promise<Array<Record<string, any>>> {
641 let text: string;
642 try {
643 text = await readFile(path, "utf8");
644 } catch (error) {
645 if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
646 throw error;
647 }
648 return text
649 .split("\n")
650 .filter(Boolean)
651 .map((line) => JSON.parse(line) as Record<string, any>);
652}
654async function main(): Promise<void> {
655 const options = parseArgs(process.argv.slice(2));
656 const benchmark = createBenchmark();
657 if (options.dryRun) {
658 console.log(
659 JSON.stringify(
660 {
661 cases: options.cases,
662 model: options.model,
663 judgeModel: options.judgeModel,
664 fixtureBytes: Object.fromEntries(
665 Object.entries(benchmark.files).map(([path, content]) => [
666 path,
667 Buffer.byteLength(content),
668 ]),
669 ),
670 expectedCompressors: benchmark.expectedCompressors,
671 prompt: benchmark.prompt,
672 },
673 null,
674 2,
675 ),
676 );
677 return;
678 }
680 const extensionDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
681 const repoRoot = resolve(extensionDir, "../..");
682 const extensionPath = join(extensionDir, "index.ts");
683 const root = stateRoot();
684 const historyPath = join(root, "history.jsonl");
685 await mkdir(root, { recursive: true });
686 const history = await readHistory(historyPath);
687 console.log(
688 `cmprss A/B · model=${options.model} · judge=${options.judgeModel}`,
689 );
690 for (const caseName of options.cases) {
691 for (let repeat = 1; repeat <= options.repeats; repeat++) {
692 const result = await runCase(
693 caseName,
694 repeat,
695 options,
696 benchmark,
697 repoRoot,
698 extensionPath,
699 historyPath,
700 );
701 printResult(result, history);
702 history.push(result);
703 }
704 }
705 console.log(`history: ${historyPath}`);
706}
708const invokedPath = process.argv[1] ? resolve(process.argv[1]) : "";
709if (invokedPath === fileURLToPath(import.meta.url)) {
710 main().catch((error) => {
711 console.error(error instanceof Error ? error.message : String(error));
712 process.exitCode = 1;
713 });
714}

extensions/cmprss/__tests__/ab.test.ts

Added
new file mode 100644

+206 / −0 text lines

1import { Buffer } from "node:buffer";
2import { describe, expect, test } from "vitest";
3import {
4 compareWithHistory,
5 createBenchmark,
6 scoreCandidate,
7 summarizeEvents,
8} from "../__bench__/ab.ts";
9import { __test } from "../index.ts";
11const benchmark = createBenchmark();
13describe("cmprss A/B benchmark", () => {
14 test("deterministically exercises every compressor below Pi's read cap", () => {
15 for (const [path, expectedCompressor] of Object.entries(
16 benchmark.expectedCompressors,
17 )) {
18 const content = benchmark.files[path];
19 expect(content, path).toBeDefined();
20 const size = Buffer.byteLength(content);
21 expect(size, `${path} exceeds cmprss threshold`).toBeGreaterThan(20_000);
22 expect(size, `${path} exceeds Pi read cap`).toBeLessThan(50_000);
23 expect(__test.compressContent(content).compressor, path).toBe(
24 expectedCompressor,
25 );
26 }
27 });
29 test("embeds every expected value exactly in its fixture", () => {
30 expect(benchmark.files["fixtures/data.json"]).toContain(
31 `"releaseCode": "${benchmark.expected.jsonCode}"`,
32 );
33 expect(benchmark.files["fixtures/search.txt"]).toContain(
34 `needle=${benchmark.expected.searchNeedle}`,
35 );
36 expect(benchmark.files["fixtures/change.diff"]).toContain(
37 `+export const value20 = "${benchmark.expected.diffNewValue}";`,
38 );
39 expect(benchmark.files["fixtures/stacktrace.txt"]).toContain(
40 `Caused by: Error: ${benchmark.expected.stackRootCause}`,
41 );
42 expect(benchmark.files["fixtures/build.log"]).toContain(
43 `ERROR build failed: ${benchmark.expected.logFailure}`,
44 );
45 expect(benchmark.files["fixtures/build.log"]).toContain(
46 `completion token: ${benchmark.expected.logTail}`,
47 );
48 expect(benchmark.files["fixtures/narrative.txt"]).toContain(
49 `middle token: ${benchmark.expected.textMiddle}`,
50 );
51 });
53 test("requires retrieval for omitted facts while preserving structural signals", () => {
54 const compressed = Object.fromEntries(
55 Object.entries(benchmark.files).map(([path, content]) => [
56 path,
57 __test.compressContent(content).text,
58 ]),
59 );
61 expect(compressed["fixtures/data.json"]).not.toContain(
62 benchmark.expected.jsonCode,
63 );
64 expect(compressed["fixtures/search.txt"]).not.toContain(
65 benchmark.expected.searchNeedle,
66 );
67 expect(compressed["fixtures/narrative.txt"]).not.toContain(
68 benchmark.expected.textMiddle,
69 );
70 expect(compressed["fixtures/change.diff"]).toContain(
71 benchmark.expected.diffNewValue,
72 );
73 expect(compressed["fixtures/stacktrace.txt"]).toContain(
74 benchmark.expected.stackRootCause,
75 );
76 expect(compressed["fixtures/build.log"]).toContain(
77 benchmark.expected.logFailure,
78 );
79 expect(compressed["fixtures/build.log"]).toContain(
80 benchmark.expected.logTail,
81 );
82 });
84 test("hard-scores exact and fenced JSON answers", () => {
85 const exact = JSON.stringify(benchmark.expected);
86 const fenced = `\`\`\`json\n${exact}\n\`\`\``;
87 expect(scoreCandidate(exact, benchmark.expected).score).toBe(100);
88 expect(scoreCandidate(fenced, benchmark.expected).score).toBe(100);
90 const wrong = { ...benchmark.expected, textMiddle: "wrong" };
91 const score = scoreCandidate(JSON.stringify(wrong), benchmark.expected);
92 expect(score.correct).toBe(Object.keys(benchmark.expected).length - 1);
93 expect(score.score).toBeLessThan(100);
94 });
96 test("compares modified runs with the latest persisted controls", () => {
97 const result = {
98 case: "modified",
99 subject: { usage: { totalTokens: 60 }, hardScore: { score: 100 } },
100 judge: { result: { score: 90 } },
101 };
102 const history = [
103 {
104 case: "current",
105 subject: { usage: { totalTokens: 100 }, hardScore: { score: 90 } },
106 judge: { result: { score: 80 } },
107 },
108 {
109 case: "baseline",
110 subject: { usage: { totalTokens: 120 }, hardScore: { score: 100 } },
111 judge: { result: { score: 100 } },
112 },
113 ];
115 expect(compareWithHistory(result, history)).toEqual([
116 {
117 case: "baseline",
118 tokenDelta: -60,
119 tokenDeltaPercent: -50,
120 hardDelta: 0,
121 judgeDelta: -10,
122 },
123 {
124 case: "current",
125 tokenDelta: -40,
126 tokenDeltaPercent: -40,
127 hardDelta: 10,
128 judgeDelta: 10,
129 },
130 ]);
131 });
133 test("summarizes provider usage, compression, retrieval, and final answer", () => {
134 const events = [
135 {
136 type: "message_end",
137 message: {
138 role: "assistant",
139 provider: "test",
140 model: "luna",
141 content: [{ type: "text", text: "working" }],
142 usage: {
143 input: 100,
144 output: 10,
145 cacheRead: 20,
146 cacheWrite: 5,
147 totalTokens: 135,
148 },
149 },
150 },
151 {
152 type: "tool_execution_end",
153 toolName: "read",
154 result: {
155 content: [{ type: "text", text: "summary" }],
156 details: {
157 cmprss: { originalBytes: 30_000, compressedBytes: 1_000 },
158 },
159 },
160 },
161 {
162 type: "tool_execution_end",
163 toolName: "cmprss_retrieve",
164 result: {
165 content: [{ type: "text", text: "retrieved" }],
166 details: { returnedBytes: 9 },
167 },
168 },
169 {
170 type: "message_end",
171 message: {
172 role: "assistant",
173 provider: "test",
174 model: "luna",
175 content: [{ type: "text", text: "final" }],
176 usage: {
177 input: 200,
178 output: 20,
179 cacheRead: 40,
180 cacheWrite: 0,
181 totalTokens: 260,
182 },
183 },
184 },
185 ];
187 const summary = summarizeEvents(events);
188 expect(summary.usage).toEqual({
189 input: 300,
190 output: 30,
191 cacheRead: 60,
192 cacheWrite: 5,
193 totalTokens: 395,
194 });
195 expect(summary.compression).toMatchObject({
196 blocks: 1,
197 originalBytes: 30_000,
198 compressedBytes: 1_000,
199 retrievals: 1,
200 netSavedBytes: 29_000 - Buffer.byteLength("retrieved"),
201 });
202 expect(summary.finalText).toBe("final");
203 expect(summary.provider).toBe("test");
204 expect(summary.model).toBe("luna");
205 });
206});

extensions/cmprss/__tests__/cmprss.test.ts

Modified

+107 / −0 text lines

77const {
88 DEFAULT_CONFIG,
9 MAX_RETRIEVE_BYTES,
910 compressToolResult,
1011 createRuntime,
1112 formatStatusText,
1213 replayState,
14 retrieveToolResult,
1315 runCommand,
1416} = __test;
5658 blocks: 1,
5759 originalBytes: 400_000,
5860 compressedBytes: 200_000,
61 retrievedBytes: 0,
5962 };
6164 expect(formatStatusText(runtime, { contextWindow: 200_000 })).toBe(
124127 });
125128 });
130 test("retrieves bounded UTF-8 byte ranges with an actionable continuation", () => {
131 const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
132 const original = `${"x".repeat(MAX_RETRIEVE_BYTES - 1)}😀tail`;
133 const compressed = compressToolResult(runtime, {
134 toolName: "bash",
135 input: {},
136 content: [{ type: "text", text: original }],
137 isError: false,
138 });
139 const hash = cmprssDetails(compressed).hash;
141 const first = retrieveToolResult(runtime, hash);
142 const firstDetails = first.details as any;
143 expect(firstDetails).toMatchObject({
144 hash,
145 offset: 0,
146 nextOffset: MAX_RETRIEVE_BYTES - 1,
147 returnedBytes: MAX_RETRIEVE_BYTES - 1,
148 hasMore: true,
149 });
150 expect(first.content[0].text).not.toBe(original);
151 expect(first.content[0].text).toContain(`offset=${MAX_RETRIEVE_BYTES - 1}`);
153 const second = retrieveToolResult(runtime, hash, firstDetails.nextOffset);
154 expect(second.content[0].text).toBe("😀tail");
155 expect(second.details).toMatchObject({
156 offset: MAX_RETRIEVE_BYTES - 1,
157 hasMore: false,
158 });
159 });
161 test("rejects oversized and non-boundary retrieval ranges", () => {
162 const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 1 });
163 const compressed = compressToolResult(runtime, {
164 toolName: "bash",
165 input: {},
166 content: [{ type: "text", text: `a😀${"b".repeat(20_000)}` }],
167 isError: false,
168 });
169 const hash = cmprssDetails(compressed).hash;
171 expect(() =>
172 retrieveToolResult(runtime, hash, 0, MAX_RETRIEVE_BYTES + 1),
173 ).toThrow(`limit must be at most ${MAX_RETRIEVE_BYTES}`);
174 expect(() => retrieveToolResult(runtime, hash, 2, 10)).toThrow(
175 "offset must be a UTF-8 boundary",
176 );
177 expect(() => retrieveToolResult(runtime, hash, 1, 1)).toThrow(
178 "limit must include a complete UTF-8 character",
179 );
180 });
182 test("retrieval reduces reported savings and replays that accounting", () => {
183 const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
184 const compressed = compressToolResult(runtime, {
185 toolName: "bash",
186 input: {},
187 content: [{ type: "text", text: bigText(3_000) }],
188 isError: false,
189 });
190 const hash = cmprssDetails(compressed).hash;
191 const savedBefore = runCommand(runtime, "status");
193 const retrieved = retrieveToolResult(runtime, hash, 0, 1_000);
194 const savedAfter = runCommand(runtime, "status");
196 expect(savedAfter).not.toBe(savedBefore);
197 expect(runtime.stats.retrievedBytes).toBe(
198 Buffer.byteLength(retrieved.content[0].text),
199 );
200 expect(runtime.entries.at(-1)).toMatchObject({
201 op: "retrieve",
202 hash,
203 contextBytes: runtime.stats.retrievedBytes,
204 });
206 const replayed = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
207 replayState(
208 replayed,
209 runtime.entries.map((data) => ({
210 type: "custom",
211 customType: "cmprss-state",
212 data,
213 })),
214 );
215 expect(runCommand(replayed, "status")).toBe(savedAfter);
216 });
127218 test("replay restores persisted originals after restart", () => {
128219 const first = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 200 });
129220 const original = bigText();
190281 ).toBeDefined();
191282 });
284 test("never recompresses retrieval results", () => {
285 const runtime = createRuntime({
286 ...DEFAULT_CONFIG,
287 thresholdBytes: 10,
288 tools: ["custom"],
289 });
290 expect(
291 compressToolResult(runtime, {
292 toolName: "cmprss_retrieve",
293 input: { hash: "abc" },
294 content: [{ type: "text", text: bigText() }],
295 isError: false,
296 }),
297 ).toBeUndefined();
298 });
193300 test("does not compress explicit read windows or mutation tools", () => {
194301 const runtime = createRuntime({ ...DEFAULT_CONFIG, thresholdBytes: 10 });
195302 for (const event of [

extensions/cmprss/__tests__/harness.test.ts

Modified

+71 / −1 text lines

1import { describe, expect, test } from "vitest";
1import { initTheme } from "@earendil-works/pi-coding-agent";
2import { beforeAll, describe, expect, test } from "vitest";
23import cmprssExtension from "../index.ts";
5function theme() {
6 return {
7 fg: (_style: string, text: string) => text,
8 bold: (text: string) => text,
9 } as any;
10}
12function render(component: { render(width: number): string[] }): string {
13 return component.render(120).join("\n");
14}
16beforeAll(() => initTheme("default", false));
418describe("cmprss harness", () => {
519 test("registers Pi surfaces", () => {
620 const events: string[] = [];
2943 expect(tools).toEqual(["cmprss_retrieve"]);
3044 expect(commands).toEqual(["cmprss"]);
3145 });
47 test("renders every retrieval parameter and hides content until expanded", () => {
48 let tool: any;
49 cmprssExtension({
50 on() {},
51 registerTool(definition: unknown) {
52 tool = definition;
53 },
54 registerCommand() {},
55 appendEntry() {},
56 } as any);
58 const call = render(
59 tool.renderCall(
60 { hash: "0123456789abcdef", offset: 128, limit: 256 },
61 theme(),
62 {},
63 ),
64 );
65 expect(call).toContain("0123456789abcdef");
66 expect(call).toContain("offset=128");
67 expect(call).toContain("limit=256");
69 const result = {
70 content: [{ type: "text", text: "secret retrieved content" }],
71 details: {
72 hash: "0123456789abcdef",
73 offset: 128,
74 nextOffset: 384,
75 returnedBytes: 256,
76 totalBytes: 1_024,
77 hasMore: true,
78 },
79 };
80 const collapsed = render(
81 tool.renderResult(
82 result,
83 { expanded: false, isPartial: false },
84 theme(),
85 {},
86 ),
87 );
88 const expanded = render(
89 tool.renderResult(
90 result,
91 { expanded: true, isPartial: false },
92 theme(),
93 {},
94 ),
95 );
97 expect(collapsed).toContain("256B");
98 expect(collapsed).toContain("128-383 of 1024");
99 expect(collapsed).not.toContain("secret retrieved content");
100 expect(expanded).toContain("secret retrieved content");
101 });
32102});

extensions/cmprss/index.ts

Modified

+171 / −13 text lines

33import {
44 type ContextUsage,
55 type ExtensionAPI,
6 keyHint,
67 SettingsManager,
78} from "@earendil-works/pi-coding-agent";
9import { Text } from "@earendil-works/pi-tui";
810import { Type } from "typebox";
1012const ENTRY_TYPE = "cmprss-state";
4547type StateEvent =
4648 | { op: "enabled"; enabled: boolean; at: number }
4749 | { op: "clear"; at: number }
48 | { op: "block"; meta: BlockMeta; originalText: string; at: number };
50 | { op: "block"; meta: BlockMeta; originalText: string; at: number }
51 | { op: "retrieve"; hash: string; contextBytes: number; at: number };
4952type Runtime = {
5053 config: CmprssConfig;
5154 enabled: boolean;
5255 blocks: Map<string, { meta: BlockMeta; originalText: string }>;
5356 entries: StateEvent[];
54 stats: { blocks: number; originalBytes: number; compressedBytes: number };
57 stats: {
58 blocks: number;
59 originalBytes: number;
60 compressedBytes: number;
61 retrievedBytes: number;
62 };
5563 append?: (event: StateEvent) => void;
5664 retrieve(hash: string): string;
5765};
67type RetrieveDetails = {
68 hash: string;
69 offset: number;
70 nextOffset: number;
71 limit: number;
72 returnedBytes: number;
73 totalBytes: number;
74 hasMore: boolean;
75};
5977type Compression = {
6078 compressor: Compressor;
6179 text: string;
6280};
82export const MAX_RETRIEVE_BYTES = 8_192;
6484export const DEFAULT_CONFIG: CmprssConfig = {
6585 enabled: true,
6686 thresholdBytes: 20_000,
94114 return Buffer.byteLength(text, "utf8");
117function isUtf8Continuation(byte: number | undefined): boolean {
118 return byte !== undefined && (byte & 0xc0) === 0x80;
119}
97121function readPersistedOutput(path: string): string {
98122 try {
99123 return readFileSync(path, "utf8");
338362 enabled: config.enabled,
339363 blocks: new Map(),
340364 entries: [],
341 stats: { blocks: 0, originalBytes: 0, compressedBytes: 0 },
365 stats: {
366 blocks: 0,
367 originalBytes: 0,
368 compressedBytes: 0,
369 retrievedBytes: 0,
370 },
342371 append,
343372 retrieve(hash: string) {
344373 const block = runtime.blocks.get(hash);
362391 }
363392 if (event.op === "clear") {
364393 runtime.blocks.clear();
365 runtime.stats = { blocks: 0, originalBytes: 0, compressedBytes: 0 };
394 runtime.stats = {
395 blocks: 0,
396 originalBytes: 0,
397 compressedBytes: 0,
398 retrievedBytes: 0,
399 };
400 return;
401 }
402 if (event.op === "retrieve") {
403 runtime.stats.retrievedBytes += event.contextBytes;
366404 return;
367405 }
368406 const { meta, originalText } = event;
387425 if (data.op === "enabled" && typeof data.enabled === "boolean")
388426 return { op: "enabled", enabled: data.enabled, at: data.at };
389427 if (data.op === "clear") return { op: "clear", at: data.at };
428 if (
429 data.op === "retrieve" &&
430 typeof data.hash === "string" &&
431 typeof data.contextBytes === "number" &&
432 Number.isFinite(data.contextBytes) &&
433 data.contextBytes >= 0
434 )
435 return {
436 op: "retrieve",
437 hash: data.hash,
438 contextBytes: data.contextBytes,
439 at: data.at,
440 };
390441 if (
391442 data.op === "block" &&
392443 isRecord(data.meta) &&
411462function compressible(runtime: Runtime, event: ToolResultEventLike): boolean {
412463 if (!runtime.enabled || event.isError) return false;
413464 const tool = String(event.toolName ?? "");
414 if (["edit", "write"].includes(tool)) return false;
465 if (["cmprss_retrieve", "edit", "write"].includes(tool)) return false;
415466 if (
416467 tool === "read" &&
417468 (event.input?.offset !== undefined ||
440491 if (originalBytes <= runtime.config.thresholdBytes) return undefined;
441492 const compression = compressContent(originalText);
442493 const hash = hashText(originalText);
443 const marker = `[cmprss: ${String(event.toolName)} ${originalBytes}B → ${bytes(compression.text)}B, saved ~${Math.max(0, Math.floor((originalBytes - bytes(compression.text)) / 4))}t, hash=${hash}]\nUse cmprss_retrieve(hash="${hash}") for exact original text.`;
494 const marker = `[cmprss: ${String(event.toolName)} ${originalBytes}B → ${bytes(compression.text)}B, saved ~${Math.max(0, Math.floor((originalBytes - bytes(compression.text)) / 4))}t, hash=${hash}]\nUse cmprss_retrieve(hash="${hash}") for bounded exact UTF-8 ranges.`;
444495 const readWarning =
445496 event.toolName === "read"
446497 ? "\nBefore editing hidden content, retrieve exact text or use read offset/limit."
469520 };
523export function retrieveToolResult(
524 runtime: Runtime,
525 hash: string,
526 offset = 0,
527 limit = MAX_RETRIEVE_BYTES,
528): {
529 content: [{ type: "text"; text: string }];
530 details: RetrieveDetails;
531} {
532 if (!Number.isInteger(offset) || offset < 0)
533 throw new Error("cmprss: offset must be a non-negative integer");
534 if (!Number.isInteger(limit) || limit < 1)
535 throw new Error("cmprss: limit must be a positive integer");
536 if (limit > MAX_RETRIEVE_BYTES)
537 throw new Error(`cmprss: limit must be at most ${MAX_RETRIEVE_BYTES}`);
539 const original = Buffer.from(runtime.retrieve(hash), "utf8");
540 if (offset >= original.length)
541 throw new Error(
542 `cmprss: offset ${offset} is beyond end of block (${original.length} bytes)`,
543 );
544 if (offset > 0 && isUtf8Continuation(original[offset]))
545 throw new Error("cmprss: offset must be a UTF-8 boundary");
547 let nextOffset = Math.min(offset + limit, original.length);
548 while (
549 nextOffset > offset &&
550 nextOffset < original.length &&
551 isUtf8Continuation(original[nextOffset])
552 )
553 nextOffset--;
554 if (nextOffset === offset)
555 throw new Error("cmprss: limit must include a complete UTF-8 character");
557 const chunk = original.subarray(offset, nextOffset).toString("utf8");
558 const hasMore = nextOffset < original.length;
559 const continuation = hasMore
560 ? `\n\n[cmprss: bytes ${offset}-${nextOffset - 1} of ${original.length}. Continue with cmprss_retrieve(hash="${hash}", offset=${nextOffset}, limit=${limit}).]`
561 : "";
562 const text = `${chunk}${continuation}`;
563 const contextBytes = bytes(text);
564 const at = Date.now();
565 record(runtime, { op: "retrieve", hash, contextBytes, at });
567 return {
568 content: [{ type: "text", text }],
569 details: {
570 hash,
571 offset,
572 nextOffset,
573 limit,
574 returnedBytes: nextOffset - offset,
575 totalBytes: original.length,
576 hasMore,
577 },
578 };
579}
472581export function runCommand(runtime: Runtime, args: string): string {
473582 const command = args.trim() || "status";
474583 if (command === "on") {
494603 return Math.max(
495604 0,
496605 Math.floor(
497 (runtime.stats.originalBytes - runtime.stats.compressedBytes) / 4,
606 (runtime.stats.originalBytes -
607 runtime.stats.compressedBytes -
608 runtime.stats.retrievedBytes) /
609 4,
498610 ),
499611 );
571683 pi.registerTool({
572684 name: "cmprss_retrieve",
573685 label: "cmprss retrieve",
574 description: "Retrieve exact original text for a cmprss hash.",
686 description: `Retrieve an exact UTF-8 byte range from a cmprss block. Returns at most ${MAX_RETRIEVE_BYTES} bytes and includes the next offset when more remains.`,
575687 parameters: Type.Object({
576688 hash: Type.String({
577689 description: "cmprss hash from the compressed marker",
578690 }),
691 offset: Type.Optional(
692 Type.Integer({
693 description: "UTF-8 byte offset, starting at 0",
694 minimum: 0,
695 }),
696 ),
697 limit: Type.Optional(
698 Type.Integer({
699 description: `Maximum bytes to return, defaults to ${MAX_RETRIEVE_BYTES}`,
700 minimum: 1,
701 maximum: MAX_RETRIEVE_BYTES,
702 }),
703 ),
579704 }),
705 renderCall(args, theme) {
706 const offset = args.offset ?? 0;
707 const limit = args.limit ?? MAX_RETRIEVE_BYTES;
708 return new Text(
709 `${theme.fg("toolTitle", theme.bold("cmprss_retrieve"))} ${theme.fg("accent", args.hash)} ${theme.fg("dim", `offset=${offset} limit=${limit}`)}`,
710 0,
711 0,
712 );
713 },
714 renderResult(result, { expanded }, theme, context) {
715 const details = result.details as RetrieveDetails | undefined;
716 const content = result.content[0];
717 const text = content?.type === "text" ? content.text : "";
718 if (!details) {
719 return new Text(
720 theme.fg(context.isError ? "error" : "muted", text),
721 0,
722 0,
723 );
724 }
725 const end = details.nextOffset - 1;
726 let summary = theme.fg(
727 "success",
728 `✓ ${details.returnedBytes}B · ${details.offset}-${end} of ${details.totalBytes}`,
729 );
730 if (!expanded)
731 summary += ` ${theme.fg("dim", `(${keyHint("app.tools.expand", "to expand")})`)}`;
732 else if (text) summary += `\n${theme.fg("toolOutput", text)}`;
733 return new Text(summary, 0, 0);
734 },
580735 async execute(_toolCallId, params) {
581 const text = runtime.retrieve(params.hash);
582 return {
583 content: [{ type: "text", text }],
584 details: { hash: params.hash, cmprssRetrieve: true },
585 };
736 return retrieveToolResult(
737 runtime,
738 params.hash,
739 params.offset,
740 params.limit,
741 );
586742 },
587743 });
599755export const __test = {
600756 DEFAULT_CONFIG,
757 MAX_RETRIEVE_BYTES,
601758 compressToolResult,
602759 createRuntime,
603760 replayState,
761 retrieveToolResult,
604762 runCommand,
605763 compressContent,
606764 formatStatusText,

extensions/cmprss/mise.toml

Added
new file mode 100644

+9 / −0 text lines

1[tasks.ab]
2description = "Run persistent cmprss model A/B evaluation"
3depends = ["//:install"]
4usage = '''
5arg "[args]" var=#true
6'''
7run = '''
8node --no-warnings --experimental-strip-types __bench__/ab.ts{% for arg in usage.args %} "{{ arg }}"{% endfor %}
9'''

extensions/cmprss/package.json

Modified

+1 / −0 text lines

99 },
1010 "peerDependencies": {
1111 "@earendil-works/pi-coding-agent": "*",
12 "@earendil-works/pi-tui": "*",
1213 "typebox": "*"
1314 },
1415 "license": "MIT",

package-lock.json

Modified

+1 / −0 text lines

6262 },
6363 "peerDependencies": {
6464 "@earendil-works/pi-coding-agent": "*",
65 "@earendil-works/pi-tui": "*",
6566 "typebox": "*"
6667 }
6768 },