import { createHash } from "node:crypto"; import { readFileSync } from "node:fs"; import { type ContextUsage, type ExtensionAPI, keyHint, SettingsManager, } from "@earendil-works/pi-coding-agent"; import { Text } from "@earendil-works/pi-tui"; import { Type } from "typebox"; const ENTRY_TYPE = "cmprss-state"; const STATUS_KEY = "cmprss"; const STATUS_ICON = ""; const ERROR_RE = /\b(error|fail|fatal|warn|exception|denied|timeout|missing|deprecated|critical|traceback|panic)\b/i; const SEARCH_RE = /^(?.+?)(?[:-])(?\d+)(?[:-])(?.*)$/; const STACK_RE = /\b(Traceback \(most recent call last\)|Exception:|Caused by:|Error:|panic:|at \S+ \(|\s+at \S+)/; type TextContent = { type?: unknown; text?: unknown }; type ToolResultEventLike = { toolName?: unknown; input?: Record; content?: unknown; details?: unknown; isError?: unknown; }; type CmprssConfig = { enabled: boolean; thresholdBytes: number; maxStoredBlocks: number; status: boolean; tools: string[]; }; type Compressor = "json" | "search" | "log" | "text" | "diff" | "stacktrace"; type BlockMeta = { hash: string; compressor: Compressor; originalBytes: number; compressedBytes: number; tokensSavedEstimate: number; sourceTool: string; createdAt: number; }; type StateEvent = | { op: "enabled"; enabled: boolean; at: number } | { op: "clear"; at: number } | { op: "block"; meta: BlockMeta; originalText: string; at: number } | { op: "retrieve"; hash: string; contextBytes: number; at: number }; type Runtime = { config: CmprssConfig; enabled: boolean; blocks: Map; entries: StateEvent[]; stats: { blocks: number; originalBytes: number; compressedBytes: number; retrievedBytes: number; }; append?: (event: StateEvent) => void; retrieve(hash: string): string; }; type RetrieveDetails = { hash: string; offset: number; nextOffset: number; limit: number; returnedBytes: number; totalBytes: number; hasMore: boolean; }; type Compression = { compressor: Compressor; text: string; }; export const MAX_RETRIEVE_BYTES = 8_192; export const DEFAULT_CONFIG: CmprssConfig = { enabled: true, thresholdBytes: 20_000, maxStoredBlocks: 64, status: true, tools: ["bash", "grep", "find", "ls", "read"], }; function isRecord(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } function fullOutputPath(details: unknown): string | undefined { return isRecord(details) && typeof details.fullOutputPath === "string" ? details.fullOutputPath : undefined; } function textOf(content: unknown): string { if (typeof content === "string") return content; if (!Array.isArray(content)) return String(content ?? ""); return (content as TextContent[]) .map((part) => part?.type === "text" && typeof part.text === "string" ? part.text : "", ) .filter(Boolean) .join("\n"); } function bytes(text: string): number { return Buffer.byteLength(text, "utf8"); } function isUtf8Continuation(byte: number | undefined): boolean { return byte !== undefined && (byte & 0xc0) === 0x80; } function readPersistedOutput(path: string): string { try { return readFileSync(path, "utf8"); } catch { return ""; } } function hashText(text: string): string { return createHash("sha256").update(text).digest("hex").slice(0, 16); } function uniq(items: T[]): T[] { return [...new Set(items)]; } function clipLines(lines: string[], first: number, last: number): string[] { if (lines.length <= first + last) return lines; return [ ...lines.slice(0, first), `[cmprss omitted ${lines.length - first - last} lines]`, ...lines.slice(-last), ]; } function containsError(value: unknown): boolean { return ERROR_RE.test(JSON.stringify(value)); } function formatJson(value: unknown): string { return JSON.stringify(value, null, 2); } function objectShape(value: unknown): string | undefined { return isRecord(value) ? Object.keys(value).sort().join("\0") : undefined; } function summarizeJsonArray(items: unknown[]): { values: unknown[]; kept: number; } { const shapes = new Map(); for (const item of items) { const shape = objectShape(item); if (shape) shapes.set(shape, (shapes.get(shape) ?? 0) + 1); } const selected = new Set(); for (let index = 0; index < Math.min(5, items.length); index++) selected.add(index); for (let index = Math.max(0, items.length - 5); index < items.length; index++) selected.add(index); let errors = 0; let rareShapes = 0; for (const [index, item] of items.entries()) { if (errors < 10 && containsError(item)) { selected.add(index); errors++; } const shape = objectShape(item); if (rareShapes < 10 && shape !== undefined && shapes.get(shape) === 1) { selected.add(index); rareShapes++; } } const values: unknown[] = []; let omitted = 0; for (const [index, item] of items.entries()) { if (!selected.has(index)) { omitted++; continue; } if (omitted > 0) { values.push(`[cmprss omitted ${omitted} items]`); omitted = 0; } values.push(item); } if (omitted > 0) values.push(`[cmprss omitted ${omitted} items]`); return { values, kept: selected.size }; } function compressJson(text: string): Compression | undefined { let parsed: unknown; try { parsed = JSON.parse(text); } catch { return undefined; } if (Array.isArray(parsed)) { const summary = summarizeJsonArray(parsed); return { compressor: "json", text: [ `[cmprss json array: ${parsed.length} items, kept ${summary.kept}]`, formatJson(summary.values), ].join("\n"), }; } if (isRecord(parsed)) { const out: Record = {}; for (const [key, value] of Object.entries(parsed)) { if (typeof value === "string" && value.length > 160) { out[key] = `${value.slice(0, 100)} …[cmprss ${value.length - 140} chars]… ${value.slice(-40)}`; } else if (Array.isArray(value) && value.length > 12) { out[key] = summarizeJsonArray(value).values; } else out[key] = value; } return { compressor: "json", text: `[cmprss json object]\n${formatJson(out)}`, }; } return undefined; } function parseSearchLine(line: string) { const match = SEARCH_RE.exec(line); if (!match?.groups) return undefined; return { file: match.groups.file, line: Number(match.groups.line), body: match.groups.body, raw: line, }; } function compressSearch(text: string): Compression | undefined { const lines = text.split(/\r?\n/); const matches = lines.map(parseSearchLine).filter((x) => x !== undefined); if (matches.length < 10 || matches.length < lines.length * 0.6) return undefined; const byFile = new Map(); for (const match of matches) { const group = byFile.get(match.file) ?? []; group.push(match); byFile.set(match.file, group); } const kept: string[] = []; let files = 0; for (const [file, group] of byFile) { if (files++ >= 15) break; kept.push(`[cmprss file: ${file}, ${group.length} matches]`); const selected = uniq([ ...group.slice(0, 2), ...group.filter((m) => ERROR_RE.test(m.body)).slice(0, 5), ...[...group].sort((a, b) => a.body.length - b.body.length).slice(0, 2), ...group.slice(-2), ]); for (const match of selected.slice(0, 11)) kept.push(match.raw); } return { compressor: "search", text: [ `[cmprss search: ${matches.length} matches in ${byFile.size} files]`, ...kept, ].join("\n"), }; } function compressDiff(text: string): Compression | undefined { const lines = text.split(/\r?\n/); const diffish = lines.filter((line) => /^(diff --git|@@ |--- |\+\+\+ |[+-])/.test(line), ).length; if (diffish < 20) return undefined; const kept = lines.filter( (line) => /^(diff --git|@@ |--- |\+\+\+ |[+-])/.test(line) || ERROR_RE.test(line), ); return { compressor: "diff", text: [ `[cmprss diff: ${lines.length} lines, kept ${kept.length}]`, ...clipLines(kept, 120, 80), ].join("\n"), }; } function compressStack(text: string): Compression | undefined { const lines = text.split(/\r?\n/); const stack = lines.filter((line) => STACK_RE.test(line)); if (stack.length < 4) return undefined; const kept = lines.filter( (line, index) => STACK_RE.test(line) || ERROR_RE.test(line) || index < 5 || index >= lines.length - 10, ); return { compressor: "stacktrace", text: [ `[cmprss stacktrace: ${lines.length} lines, kept ${kept.length}]`, ...clipLines(uniq(kept), 80, 80), ].join("\n"), }; } function compressLog(text: string): Compression | undefined { const lines = text.split(/\r?\n/); const signal = lines.filter( (line) => ERROR_RE.test(line) || STACK_RE.test(line), ); if (lines.length < 80 || signal.length === 0) return undefined; const kept = uniq([ ...lines.slice(0, 20), ...lines.filter((line) => ERROR_RE.test(line)).slice(0, 40), ...lines.filter((line) => STACK_RE.test(line)).slice(0, 60), ...lines.slice(-40), ]); return { compressor: "log", text: [ `[cmprss log: ${lines.length} lines, kept ${kept.length}]`, ...clipLines(kept, 90, 90), ].join("\n"), }; } function compressText(text: string): Compression { const lines = text.split(/\r?\n/); return { compressor: "text", text: [ `[cmprss text: ${lines.length} lines]`, ...clipLines(lines, 40, 80), ].join("\n"), }; } function compressContent(text: string): Compression { return ( compressJson(text) ?? compressDiff(text) ?? compressStack(text) ?? compressSearch(text) ?? compressLog(text) ?? compressText(text) ); } function normalizeConfig(raw: unknown): CmprssConfig { const cfg = isRecord(raw) ? raw : {}; return { enabled: typeof cfg.enabled === "boolean" ? cfg.enabled : DEFAULT_CONFIG.enabled, thresholdBytes: typeof cfg.thresholdBytes === "number" && Number.isFinite(cfg.thresholdBytes) && cfg.thresholdBytes >= 0 ? Math.trunc(cfg.thresholdBytes) : DEFAULT_CONFIG.thresholdBytes, maxStoredBlocks: typeof cfg.maxStoredBlocks === "number" && Number.isFinite(cfg.maxStoredBlocks) && cfg.maxStoredBlocks > 0 ? Math.trunc(cfg.maxStoredBlocks) : DEFAULT_CONFIG.maxStoredBlocks, status: typeof cfg.status === "boolean" ? cfg.status : DEFAULT_CONFIG.status, tools: Array.isArray(cfg.tools) ? cfg.tools.filter((x) => typeof x === "string") : DEFAULT_CONFIG.tools, }; } function settingsFrom(cwd = process.cwd()): CmprssConfig { const manager = SettingsManager.create(cwd); const global = manager.getGlobalSettings() as Record; const project = manager.getProjectSettings() as Record; return normalizeConfig({ ...(isRecord(global.cmprss) ? global.cmprss : {}), ...(isRecord(project.cmprss) ? project.cmprss : {}), }); } export function createRuntime( config: CmprssConfig, append?: (event: StateEvent) => void, ): Runtime { const runtime: Runtime = { config, enabled: config.enabled, blocks: new Map(), entries: [], stats: { blocks: 0, originalBytes: 0, compressedBytes: 0, retrievedBytes: 0, }, append, retrieve(hash: string) { const block = runtime.blocks.get(hash); if (!block) throw new Error("cmprss: unknown hash"); return block.originalText; }, }; return runtime; } function record(runtime: Runtime, event: StateEvent): void { applyStateEvent(runtime, event); runtime.entries.push(event); runtime.append?.(event); } function applyStateEvent(runtime: Runtime, event: StateEvent): void { if (event.op === "enabled") { runtime.enabled = event.enabled; return; } if (event.op === "clear") { runtime.blocks.clear(); runtime.stats = { blocks: 0, originalBytes: 0, compressedBytes: 0, retrievedBytes: 0, }; return; } if (event.op === "retrieve") { runtime.stats.retrievedBytes += event.contextBytes; return; } const { meta, originalText } = event; runtime.blocks.set(meta.hash, { meta, originalText }); while (runtime.blocks.size > runtime.config.maxStoredBlocks) { const first = runtime.blocks.keys().next().value; if (!first) break; runtime.blocks.delete(first); } runtime.stats.blocks = runtime.blocks.size; runtime.stats.originalBytes += meta.originalBytes; runtime.stats.compressedBytes += meta.compressedBytes; } function parseStateEvent(data: unknown): StateEvent | undefined { if ( !isRecord(data) || typeof data.op !== "string" || typeof data.at !== "number" ) return undefined; if (data.op === "enabled" && typeof data.enabled === "boolean") return { op: "enabled", enabled: data.enabled, at: data.at }; if (data.op === "clear") return { op: "clear", at: data.at }; if ( data.op === "retrieve" && typeof data.hash === "string" && typeof data.contextBytes === "number" && Number.isFinite(data.contextBytes) && data.contextBytes >= 0 ) return { op: "retrieve", hash: data.hash, contextBytes: data.contextBytes, at: data.at, }; if ( data.op === "block" && isRecord(data.meta) && typeof data.originalText === "string" ) return data as StateEvent; return undefined; } export function replayState( runtime: Runtime, entries: Array<{ type?: unknown; customType?: unknown; data?: unknown }>, ): void { applyStateEvent(runtime, { op: "clear", at: Date.now() }); for (const entry of entries) { if (entry.type !== "custom" || entry.customType !== ENTRY_TYPE) continue; const event = parseStateEvent(entry.data); if (event) applyStateEvent(runtime, event); } } function compressible(runtime: Runtime, event: ToolResultEventLike): boolean { if (!runtime.enabled || event.isError) return false; const tool = String(event.toolName ?? ""); if (["cmprss_retrieve", "edit", "write"].includes(tool)) return false; if ( tool === "read" && (event.input?.offset !== undefined || event.input?.limit !== undefined || event.input?.l !== undefined) ) return false; if ( !runtime.config.tools.includes(tool) && !runtime.config.tools.includes("custom") ) return false; return true; } export function compressToolResult( runtime: Runtime, event: ToolResultEventLike, ) { if (!compressible(runtime, event)) return undefined; const visibleText = textOf(event.content); const path = fullOutputPath(event.details); const persistedText = path ? readPersistedOutput(path) : ""; const originalText = persistedText || visibleText; const originalBytes = bytes(originalText); if (originalBytes <= runtime.config.thresholdBytes) return undefined; const compression = compressContent(originalText); const hash = hashText(originalText); 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.`; const readWarning = event.toolName === "read" ? "\nBefore editing hidden content, retrieve exact text or use read offset/limit." : ""; const text = `${marker}${readWarning}\n\n${compression.text}`; const meta: BlockMeta = { hash, compressor: compression.compressor, originalBytes, compressedBytes: bytes(text), tokensSavedEstimate: Math.max( 0, Math.floor((originalBytes - bytes(text)) / 4), ), sourceTool: String(event.toolName), createdAt: Date.now(), }; record(runtime, { op: "block", meta, originalText, at: meta.createdAt }); return { content: [{ type: "text", text }], details: { ...(isRecord(event.details) ? event.details : {}), cmprss: meta, }, isError: false, }; } export function retrieveToolResult( runtime: Runtime, hash: string, offset = 0, limit = MAX_RETRIEVE_BYTES, ): { content: [{ type: "text"; text: string }]; details: RetrieveDetails; } { if (!Number.isInteger(offset) || offset < 0) throw new Error("cmprss: offset must be a non-negative integer"); if (!Number.isInteger(limit) || limit < 1) throw new Error("cmprss: limit must be a positive integer"); if (limit > MAX_RETRIEVE_BYTES) throw new Error(`cmprss: limit must be at most ${MAX_RETRIEVE_BYTES}`); const original = Buffer.from(runtime.retrieve(hash), "utf8"); if (offset >= original.length) throw new Error( `cmprss: offset ${offset} is beyond end of block (${original.length} bytes)`, ); if (offset > 0 && isUtf8Continuation(original[offset])) throw new Error("cmprss: offset must be a UTF-8 boundary"); let nextOffset = Math.min(offset + limit, original.length); while ( nextOffset > offset && nextOffset < original.length && isUtf8Continuation(original[nextOffset]) ) nextOffset--; if (nextOffset === offset) throw new Error("cmprss: limit must include a complete UTF-8 character"); const chunk = original.subarray(offset, nextOffset).toString("utf8"); const hasMore = nextOffset < original.length; const continuation = hasMore ? `\n\n[cmprss: bytes ${offset}-${nextOffset - 1} of ${original.length}. Continue with cmprss_retrieve(hash="${hash}", offset=${nextOffset}, limit=${limit}).]` : ""; const text = `${chunk}${continuation}`; const contextBytes = bytes(text); const at = Date.now(); record(runtime, { op: "retrieve", hash, contextBytes, at }); return { content: [{ type: "text", text }], details: { hash, offset, nextOffset, limit, returnedBytes: nextOffset - offset, totalBytes: original.length, hasMore, }, }; } export function runCommand(runtime: Runtime, args: string): string { const command = args.trim() || "status"; if (command === "on") { record(runtime, { op: "enabled", enabled: true, at: Date.now() }); return "cmprss: on"; } if (command === "off") { record(runtime, { op: "enabled", enabled: false, at: Date.now() }); return "cmprss: off"; } if (command === "clear") { record(runtime, { op: "clear", at: Date.now() }); return "cmprss: cleared"; } if (command === "stats" || command === "status") { const saved = savedTokens(runtime); return `cmprss: ${runtime.enabled ? "on" : "off"}; blocks=${runtime.stats.blocks}; saved~${saved}t; threshold=${runtime.config.thresholdBytes}B`; } return "cmprss: usage: /cmprss [status|stats|on|off|clear]"; } function savedTokens(runtime: Runtime): number { return Math.max( 0, Math.floor( (runtime.stats.originalBytes - runtime.stats.compressedBytes - runtime.stats.retrievedBytes) / 4, ), ); } function formatStatusText( runtime: Runtime, usage?: Pick, ): string { const saved = savedTokens(runtime); const contextWindow = usage?.contextWindow; if ( typeof contextWindow !== "number" || !Number.isFinite(contextWindow) || contextWindow <= 0 ) return `${STATUS_ICON} ${saved}t`; const percent = Math.round((saved / contextWindow) * 100); return `${STATUS_ICON} ${percent === 0 ? "0" : `-${percent}`}%`; } function updateStatus( runtime: Runtime, ctx: { hasUI?: boolean; ui?: { setStatus?: (key: string, text: string | undefined) => void }; getContextUsage?: () => ContextUsage | undefined; }, ): void { if (!ctx.hasUI || !runtime.config.status) return; if (!runtime.enabled) { ctx.ui?.setStatus?.(STATUS_KEY, `${STATUS_ICON} off`); return; } ctx.ui?.setStatus?.( STATUS_KEY, formatStatusText(runtime, ctx.getContextUsage?.()), ); } export default function cmprssExtension(pi: ExtensionAPI) { let runtime = createRuntime(DEFAULT_CONFIG, (event) => pi.appendEntry(ENTRY_TYPE, event), ); pi.on("session_start", (_event, ctx) => { runtime = createRuntime(settingsFrom(ctx.cwd), (event) => pi.appendEntry(ENTRY_TYPE, event), ); replayState( runtime, ctx.sessionManager.getBranch() as Array<{ type?: unknown; customType?: unknown; data?: unknown; }>, ); updateStatus(runtime, ctx); }); pi.on("session_shutdown", () => { runtime.blocks.clear(); }); pi.on("tool_result", ((event: any, ctx: any) => { const result = compressToolResult(runtime, event); updateStatus(runtime, ctx); return result; }) as any); pi.on("model_select", (_event, ctx) => { updateStatus(runtime, ctx); }); pi.registerTool({ name: "cmprss_retrieve", label: "cmprss retrieve", 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.`, parameters: Type.Object({ hash: Type.String({ description: "cmprss hash from the compressed marker", }), offset: Type.Optional( Type.Integer({ description: "UTF-8 byte offset, starting at 0", minimum: 0, }), ), limit: Type.Optional( Type.Integer({ description: `Maximum bytes to return, defaults to ${MAX_RETRIEVE_BYTES}`, minimum: 1, maximum: MAX_RETRIEVE_BYTES, }), ), }), renderCall(args, theme) { const offset = args.offset ?? 0; const limit = args.limit ?? MAX_RETRIEVE_BYTES; return new Text( `${theme.fg("toolTitle", theme.bold("cmprss_retrieve"))} ${theme.fg("accent", args.hash)} ${theme.fg("dim", `offset=${offset} limit=${limit}`)}`, 0, 0, ); }, renderResult(result, { expanded }, theme, context) { const details = result.details as RetrieveDetails | undefined; const content = result.content[0]; const text = content?.type === "text" ? content.text : ""; if (!details) { return new Text( theme.fg(context.isError ? "error" : "muted", text), 0, 0, ); } const end = details.nextOffset - 1; let summary = theme.fg( "success", `✓ ${details.returnedBytes}B · ${details.offset}-${end} of ${details.totalBytes}`, ); if (!expanded) summary += ` ${theme.fg("dim", `(${keyHint("app.tools.expand", "to expand")})`)}`; else if (text) summary += `\n${theme.fg("toolOutput", text)}`; return new Text(summary, 0, 0); }, async execute(_toolCallId, params) { return retrieveToolResult( runtime, params.hash, params.offset, params.limit, ); }, }); pi.registerCommand("cmprss", { description: "Show or change cmprss state.", async handler(args, ctx) { const message = runCommand(runtime, args); updateStatus(runtime, ctx); if (ctx.hasUI) ctx.ui.notify(message, "info"); }, }); } export const __test = { DEFAULT_CONFIG, MAX_RETRIEVE_BYTES, compressToolResult, createRuntime, replayState, retrieveToolResult, runCommand, compressContent, formatStatusText, };