repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/cmprss/index.ts
RawFile outline
- ENTRY_TYPE line 9
- STATUS_KEY line 10
- ERROR_RE line 12
- SEARCH_RE line 14
- STACK_RE line 16
- TextContent line 19
- ToolResultEventLike line 20
- CmprssConfig line 27
- Compressor line 34
- BlockMeta line 35
- StateEvent line 44
- Runtime line 48
- Compression line 58
- DEFAULT_CONFIG line 63
- isRecord line 71
- fullOutputPath line 75
- textOf line 81
- bytes line 92
- readPersistedOutput line 96
- hashText line 104
- uniq line 108
- clipLines line 112
- containsError line 121
- formatJson line 125
- compressJson line 129
- parseSearchLine line 171
- compressSearch line 182
- compressDiff line 214
- compressStack line 233
- compressLog line 253
- compressText line 274
- compressContent line 285
- normalizeConfig line 296
- settingsFrom line 321
- settingsManager line 324
- createRuntime line 332
- retrieve line 343
- record line 352
- applyStateEvent line 358
- parseStateEvent line 380
- replayState line 399
- compressible line 411
- compressToolResult line 430
- runCommand line 472
- savedTokens line 493
- formatStatusText line 502
- updateStatus line 518
- cmprssExtension line 537
- type line 549
- customType line 550
- data line 551
- execute line 580
- handler line 591
- __test line 599
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import type {
ContextUsage,
ExtensionAPI,
} from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
const ENTRY_TYPE = "cmprss-state";
const STATUS_KEY = "cmprss";
const ERROR_RE =
/\b(error|fail|fatal|warn|exception|denied|timeout|missing|deprecated|critical|traceback|panic)\b/i;
const SEARCH_RE =
/^(?<file>.+?)(?<sep>[:-])(?<line>\d+)(?<sep2>[:-])(?<body>.*)$/;
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<string, unknown>;
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 };
type Runtime = {
config: CmprssConfig;
enabled: boolean;
blocks: Map<string, { meta: BlockMeta; originalText: string }>;
entries: StateEvent[];
stats: { blocks: number; originalBytes: number; compressedBytes: number };
append?: (event: StateEvent) => void;
retrieve(hash: string): string;
};
type Compression = {
compressor: Compressor;
text: string;
};
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<string, unknown> {
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 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<T>(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 compressJson(text: string): Compression | undefined {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return undefined;
}
if (Array.isArray(parsed)) {
const first = parsed.slice(0, 5);
const last = parsed.slice(-5);
const errors = parsed.filter(containsError).slice(0, 10);
const kept = uniq([...first, ...errors, ...last]);
return {
compressor: "json",
text: [
`[cmprss json array: ${parsed.length} items, kept ${kept.length}]`,
formatJson(kept),
].join("\n"),
};
}
if (isRecord(parsed)) {
const out: Record<string, unknown> = {};
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] = [
...value.slice(0, 5),
`[cmprss omitted ${value.length - 10} items]`,
...value.slice(-5),
];
} 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<string, typeof matches>();
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.slice(-2),
]);
for (const match of selected.slice(0, 5)) 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(pi: unknown): CmprssConfig {
const raw = (
pi as {
settingsManager?: {
getSettings?: () => Record<string, unknown> | undefined;
};
}
).settingsManager?.getSettings?.();
return normalizeConfig(isRecord(raw?.cmprss) ? raw.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 },
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 };
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 === "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 (["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 exact original text.`;
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 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) / 4,
),
);
}
function formatStatusText(
runtime: Runtime,
usage?: Pick<ContextUsage, "contextWindow">,
): string {
const saved = savedTokens(runtime);
const contextWindow = usage?.contextWindow;
if (
typeof contextWindow !== "number" ||
!Number.isFinite(contextWindow) ||
contextWindow <= 0
)
return `cmprss: ${saved}t`;
const percent = Math.round((saved / contextWindow) * 100);
return `cmprss: ${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, "cmprss: off");
return;
}
ctx.ui?.setStatus?.(
STATUS_KEY,
formatStatusText(runtime, ctx.getContextUsage?.()),
);
}
export default function cmprssExtension(pi: ExtensionAPI) {
let runtime = createRuntime(settingsFrom(pi), (event) =>
pi.appendEntry(ENTRY_TYPE, event),
);
pi.on("session_start", (_event, ctx) => {
runtime = createRuntime(settingsFrom(pi), (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 exact original text for a cmprss hash.",
parameters: Type.Object({
hash: Type.String({
description: "cmprss hash from the compressed marker",
}),
}),
async execute(_toolCallId, params) {
const text = runtime.retrieve(params.hash);
return {
content: [{ type: "text", text }],
details: { hash: params.hash, cmprssRetrieve: true },
};
},
});
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,
compressToolResult,
createRuntime,
replayState,
runCommand,
compressContent,
formatStatusText,
};