@casualjim/pi-headroom 0.1.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.
@@ -0,0 +1,761 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ContextEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { Box, Text } from "@earendil-works/pi-tui";
4
+ import {
5
+ applyCompressionResult,
6
+ buildCompressionPayload,
7
+ convertMessage,
8
+ extractOpenAIText,
9
+ } from "./bridge.js";
10
+ import { HeadroomHttpClient } from "./client.js";
11
+ import { Type } from "typebox";
12
+ import { detectHeadroomHost, isRemoteBlocked, loadHeadroomConfig, resolveHeadroomSettingsFile, saveHeadroomSettings } from "./config.js";
13
+ import type { AgentMessage, CompressResult, CompressionPayload, HeadroomConfig, HeadroomMode, HeadroomStats } from "./types.js";
14
+
15
+ const STATUS_KEY = "headroom";
16
+ const SUBCOMMANDS = ["status", "on", "off", "health", "stats", "mode"] as const;
17
+ const MODES = ["normal", "quiet", "silent"] as const;
18
+ const NOTRACE_TELEMETRY_CHANNEL = "notrace.telemetry.extension";
19
+ // Bounded FIFO, not config: this is a safety valve for duplicate-compression loops.
20
+ // 512 hashes covers roughly 256 compressed candidates because we store original + compressed text hashes.
21
+ // That is far beyond the reread-loop case while keeping memory bounded for long sessions.
22
+ const MAX_SEEN_CANDIDATE_CONTENT_FINGERPRINTS = 512;
23
+
24
+ type Subcommand = (typeof SUBCOMMANDS)[number];
25
+
26
+ interface HeadroomRuntimeState {
27
+ enabled: boolean;
28
+ proxyOnline: boolean | null;
29
+ remoteWarningShown: boolean;
30
+ offlineWarningShown: boolean;
31
+ processing: boolean;
32
+ lastInputFingerprint: string | null;
33
+ lastOutputFingerprint: string | null;
34
+ lastGuardSkipCandidateFingerprint: string | null;
35
+ seenCandidateContentFingerprints?: Set<string>;
36
+ seenCandidateContentOrder?: string[];
37
+ lastCompressionTime: number;
38
+ stats: HeadroomStats;
39
+ }
40
+
41
+ interface HeadroomRuntime {
42
+ pi: ExtensionAPI;
43
+ config: HeadroomConfig;
44
+ client: HeadroomHttpClient;
45
+ state: HeadroomRuntimeState;
46
+ /** Resolved settings file for this host (pi or omp). */
47
+ settingsFile: string;
48
+ refreshStatus(ctx: ExtensionContext): void;
49
+ updateHealth(ctx: ExtensionContext): Promise<boolean>;
50
+ ensureProxy(ctx: ExtensionContext): Promise<boolean>;
51
+ }
52
+
53
+ const COMPRESSION_ENTRY_TYPE = "noheadroom.compression";
54
+
55
+ interface CompressionEntryDetails {
56
+ tokensBefore: number;
57
+ tokensAfter: number;
58
+ tokensSaved: number;
59
+ compressionRatio: number;
60
+ appliedMessages: number;
61
+ transformsApplied: string[];
62
+ timestamp: number;
63
+ }
64
+
65
+ export default function headroomExtension(pi: ExtensionAPI) {
66
+ registerCompressionRenderer(pi);
67
+ const runtime = createRuntime(pi);
68
+
69
+ pi.on("session_start", (_event, ctx) => {
70
+ if (isRemoteBlocked(runtime.config)) {
71
+ runtime.refreshStatus(ctx);
72
+ emitNotraceTelemetry(runtime);
73
+ ctx.ui.notify(
74
+ `Headroom remote URL is blocked by default: ${runtime.config.baseUrl}\nSet PI_HEADROOM_ALLOW_REMOTE=1 only if you trust that proxy with full context.`,
75
+ "warning",
76
+ );
77
+ return;
78
+ }
79
+ runtime.refreshStatus(ctx);
80
+ emitNotraceTelemetry(runtime);
81
+ if (!runtime.state.enabled) return;
82
+ void ensureProxyInBackground(runtime, ctx);
83
+ });
84
+
85
+ pi.on("context", (event, ctx) => handleContextCompression(runtime, event, ctx));
86
+
87
+ pi.registerCommand("headroom", {
88
+ description: "Headroom token compression. Usage: /headroom [on|off|status|health|stats|mode <normal|quiet|silent>]",
89
+ getArgumentCompletions(argumentPrefix) {
90
+ const parts = argumentPrefix.trim().toLowerCase().split(/\s+/);
91
+ if (parts[0] === "mode") {
92
+ const modePfx = parts[1] ?? "";
93
+ return MODES.filter((m) => m.startsWith(modePfx)).map((m) => ({
94
+ value: `mode ${m}`,
95
+ label: `mode ${m}`,
96
+ }));
97
+ }
98
+ const prefix = parts[0] ?? "";
99
+ return SUBCOMMANDS.filter((command) => command.startsWith(prefix)).map((command) => ({
100
+ value: command,
101
+ label: command,
102
+ }));
103
+ },
104
+ handler: async (args, ctx) => {
105
+ const parts = args.trim().split(/\s+/);
106
+ const first = (parts[0] ?? "").toLowerCase();
107
+ if (first === "mode") {
108
+ return handleModeChange(runtime, parts[1]?.toLowerCase() ?? "", ctx);
109
+ }
110
+ return handleCommand(runtime, parseSubcommand(first), ctx);
111
+ },
112
+ });
113
+
114
+ pi.registerCommand("headroom-health", {
115
+ description: "Check Headroom proxy health",
116
+ handler: async (_args, ctx) => {
117
+ await handleCommand(runtime, "health", ctx);
118
+ },
119
+ });
120
+
121
+ const retrieveTool = {
122
+ name: "headroom_retrieve",
123
+ label: "Headroom Retrieve",
124
+ description:
125
+ "Retrieve the full original content that Headroom compressed. Use the exact hash from a compression marker " +
126
+ "(e.g. `Retrieve more: hash=...`, `Retrieve original: hash=...`) or from a `<<ccr:hash ...>>` machine marker in a tool result.",
127
+ parameters: Type.Object({
128
+ hash: Type.String({ description: "The exact hash from the compression marker (12-24 hex characters)" }),
129
+ }),
130
+ // omp defaults extension tools to loadMode "discoverable" and approval "exec";
131
+ // a marker-redeeming tool must stay top-level and read-only. pi ignores both fields.
132
+ loadMode: "essential" as const,
133
+ approval: "read" as const,
134
+ async execute(_toolCallId: string, params: { hash?: unknown }, signal: AbortSignal | undefined) {
135
+ const hash = String(params.hash ?? "").trim().toLowerCase();
136
+ if (!/^[a-f0-9]{12,24}$/.test(hash)) {
137
+ return {
138
+ content: [
139
+ {
140
+ type: "text" as const,
141
+ text: JSON.stringify({ error: "Invalid hash format. Expected 12-24 hex characters." }),
142
+ },
143
+ ],
144
+ details: { hash, ok: false },
145
+ };
146
+ }
147
+ const result = await runtime.client.retrieve(hash, signal);
148
+ return {
149
+ content: [
150
+ {
151
+ type: "text" as const,
152
+ text: result.ok ? result.content : JSON.stringify({ error: result.error, hash }),
153
+ },
154
+ ],
155
+ details: { hash, ok: result.ok },
156
+ };
157
+ },
158
+ };
159
+ pi.registerTool(retrieveTool);
160
+ }
161
+
162
+ function createRuntime(pi: ExtensionAPI): HeadroomRuntime {
163
+ const host = detectHeadroomHost(pi);
164
+ const settingsFile = resolveHeadroomSettingsFile(host);
165
+ const config = loadHeadroomConfig(process.env, undefined, host);
166
+ const client = new HeadroomHttpClient({ baseUrl: config.baseUrl, timeoutMs: config.timeoutMs });
167
+ const state: HeadroomRuntimeState = {
168
+ enabled: config.enabled,
169
+ proxyOnline: null,
170
+ remoteWarningShown: false,
171
+ offlineWarningShown: false,
172
+ processing: false,
173
+ lastInputFingerprint: null,
174
+ lastOutputFingerprint: null,
175
+ lastGuardSkipCandidateFingerprint: null,
176
+ seenCandidateContentFingerprints: new Set(),
177
+ seenCandidateContentOrder: [],
178
+ lastCompressionTime: 0,
179
+ stats: { attempts: 0, applied: 0, guardSkips: 0, tokensSaved: 0 },
180
+ };
181
+
182
+ const runtime: HeadroomRuntime = {
183
+ pi,
184
+ config,
185
+ client,
186
+ state,
187
+ settingsFile,
188
+ refreshStatus(ctx) {
189
+ refreshStatus(ctx, runtime.config, runtime.state);
190
+ },
191
+ async updateHealth(ctx) {
192
+ const online = await updateHealthState(runtime, ctx.signal);
193
+ runtime.refreshStatus(ctx);
194
+ return online;
195
+ },
196
+ async ensureProxy(ctx) {
197
+ return ensureProxy(runtime, ctx);
198
+ },
199
+ };
200
+ return runtime;
201
+ }
202
+
203
+ async function updateHealthState(runtime: HeadroomRuntime, signal?: AbortSignal): Promise<boolean> {
204
+ if (isRemoteBlocked(runtime.config)) return false;
205
+ if (await runtime.client.health(signal)) {
206
+ runtime.state.proxyOnline = true;
207
+ } else {
208
+ runtime.state.proxyOnline = await runtime.client.probe(signal);
209
+ }
210
+ return runtime.state.proxyOnline;
211
+ }
212
+
213
+ async function ensureProxy(runtime: HeadroomRuntime, ctx: ExtensionContext): Promise<boolean> {
214
+ return runtime.updateHealth(ctx);
215
+ }
216
+
217
+ async function ensureProxyInBackground(runtime: HeadroomRuntime, ctx?: ExtensionContext): Promise<void> {
218
+ try {
219
+ await updateHealthState(runtime);
220
+ } catch (error) {
221
+ runtime.state.proxyOnline = false;
222
+ runtime.state.stats.lastError = error instanceof Error ? error.message : String(error);
223
+ }
224
+ safeRefreshStatus(runtime, ctx);
225
+ }
226
+
227
+ function safeRefreshStatus(runtime: HeadroomRuntime, ctx: ExtensionContext | undefined): void {
228
+ if (!ctx) return;
229
+ try {
230
+ runtime.refreshStatus(ctx);
231
+ } catch {
232
+ // The session may have been reloaded/replaced while background health was in flight.
233
+ }
234
+ }
235
+
236
+ function registerCompressionRenderer(pi: ExtensionAPI): void {
237
+ pi.registerMessageRenderer(COMPRESSION_ENTRY_TYPE, (message, { expanded }, theme) => {
238
+ const details = message.details as (CompressionEntryDetails & { summary?: string }) | undefined;
239
+ const content = details?.summary ?? (typeof message.content === "string" ? message.content : "headroom compression applied");
240
+ const box = new Box(1, 1, (text) => theme.bg("customMessageBg", text));
241
+ let text = `${theme.fg("success", "🗜 headroom")} ${content}`;
242
+ if (expanded && details) {
243
+ text += `\n${theme.fg("dim", ` before: ${details.tokensBefore.toLocaleString()} tokens`)}`;
244
+ text += `\n${theme.fg("dim", ` after: ${details.tokensAfter.toLocaleString()} tokens`)}`;
245
+ text += `\n${theme.fg("dim", ` saved: ${details.tokensSaved.toLocaleString()} tokens`)}`;
246
+ text += `\n${theme.fg("dim", ` messages: ${details.appliedMessages}`)}`;
247
+ text += `\n${theme.fg("dim", ` transforms: ${details.transformsApplied.join(", ") || "none"}`)}`;
248
+ }
249
+ box.addChild(new Text(text, 0, 0));
250
+ return box;
251
+ });
252
+ }
253
+
254
+ async function handleContextCompression(
255
+ runtime: HeadroomRuntime,
256
+ event: ContextEvent,
257
+ ctx: ExtensionContext,
258
+ ): Promise<{ messages?: AgentMessage[] } | undefined> {
259
+ if (runtime.state.processing) return undefined;
260
+
261
+ const bypassUncompressed = () => {
262
+ if (runtime.state.stats.last) {
263
+ runtime.state.stats.last = undefined;
264
+ runtime.refreshStatus(ctx);
265
+ }
266
+ return undefined;
267
+ };
268
+
269
+ // Throttle: max 1 compression attempt per 3 seconds to kill infinite loops
270
+ const now = Date.now();
271
+ if (now - runtime.state.lastCompressionTime < 3000) {
272
+ return bypassUncompressed();
273
+ }
274
+
275
+ // Content-based guards to prevent infinite recursion
276
+ const inputFingerprint = generateFingerprint(event.messages);
277
+
278
+ // 1. If this input matches our previous output, we already compressed it. Stop.
279
+ if (runtime.state.lastOutputFingerprint === inputFingerprint) {
280
+ return undefined;
281
+ }
282
+
283
+ // 2. If this input matches our previous input, it didn't change. Stop.
284
+ if (runtime.state.lastInputFingerprint === inputFingerprint) {
285
+ return bypassUncompressed();
286
+ }
287
+
288
+ if (shouldSkipBeforePayload(runtime, ctx)) return bypassUncompressed();
289
+ const payload = buildCompressionPayload(event.messages, runtime.config.minMessageChars, {
290
+ renameToolCalls: runtime.config.renameToolCalls,
291
+ });
292
+ if (payload.candidateCount === 0) return bypassUncompressed();
293
+
294
+ // 3. If eligible candidates haven't changed since the last skip/no-savings result,
295
+ // don't spend another proxy call just because surrounding conversation changed.
296
+ const candidateFingerprint = generateCandidateFingerprint(event.messages, payload);
297
+ if (runtime.state.lastGuardSkipCandidateFingerprint === candidateFingerprint) {
298
+ return bypassUncompressed();
299
+ }
300
+ if (allCandidateContentSeen(runtime.state, payload)) {
301
+ return bypassUncompressed();
302
+ }
303
+ ignoreSeenCandidateContent(runtime.state, payload);
304
+ if (runtime.state.proxyOnline !== true) {
305
+ void ensureProxyInBackground(runtime, ctx);
306
+ return bypassUncompressed();
307
+ }
308
+
309
+ runtime.state.processing = true;
310
+ runtime.state.lastCompressionTime = now;
311
+ runtime.state.stats.attempts++;
312
+ try {
313
+ const result = await runtime.client.compress(payload.messages, ctx.model?.id, ctx.signal);
314
+ runtime.state.proxyOnline = true;
315
+ if (!result.compressed || result.tokensSaved <= 0) {
316
+ // Even if no tokens saved, record fingerprints so we don't keep trying
317
+ // until the actual compressible candidate material changes.
318
+ runtime.state.lastInputFingerprint = inputFingerprint;
319
+ runtime.state.lastGuardSkipCandidateFingerprint = candidateFingerprint;
320
+ return bypassUncompressed();
321
+ }
322
+
323
+ const applied = applyCompressionResult(event.messages, payload.mappings, result.messages, {
324
+ minMessageChars: runtime.config.minMessageChars,
325
+ });
326
+ if (!applied.ok) {
327
+ // Record the input even on guard skips to prevent looping retries for this context
328
+ runtime.state.lastInputFingerprint = inputFingerprint;
329
+ runtime.state.lastOutputFingerprint = null;
330
+ runtime.state.lastGuardSkipCandidateFingerprint = candidateFingerprint;
331
+
332
+ recordGuardSkip(runtime.state.stats, applied.reason);
333
+ emitNotraceTelemetry(runtime);
334
+ announceGuardSkip(ctx, applied.reason, result, runtime.config.mode);
335
+ return bypassUncompressed();
336
+ }
337
+
338
+ // Store fingerprints to break the feedback loop
339
+ runtime.state.lastInputFingerprint = inputFingerprint;
340
+ runtime.state.lastOutputFingerprint = generateFingerprint(applied.messages);
341
+ runtime.state.lastGuardSkipCandidateFingerprint = null;
342
+ recordSeenCandidateContent(runtime.state, payload, applied.messages);
343
+ const appliedResult = {
344
+ ...result,
345
+ tokensBefore: applied.appliedTokensBefore,
346
+ tokensAfter: applied.appliedTokensAfter,
347
+ tokensSaved: applied.appliedTokensSaved,
348
+ compressionRatio: applied.appliedCompressionRatio,
349
+ };
350
+
351
+ recordAppliedCompression(runtime.state.stats, appliedResult, applied.appliedMessages);
352
+ emitNotraceTelemetry(runtime);
353
+ announceAppliedCompression(ctx, appliedResult, applied.appliedMessages, runtime.config.mode);
354
+ runtime.refreshStatus(ctx);
355
+ return { messages: applied.messages };
356
+ } catch (error) {
357
+ recordCompressionError(runtime, ctx, error);
358
+ return bypassUncompressed();
359
+ } finally {
360
+ runtime.state.processing = false;
361
+ }
362
+ }
363
+
364
+ function allCandidateContentSeen(state: HeadroomRuntimeState, payload: CompressionPayload): boolean {
365
+ const seen = state.seenCandidateContentFingerprints;
366
+ if (!seen?.size) return false;
367
+ const hashes = payload.mappings.filter((mapping) => mapping.applyTo).map((mapping) => stableHash(mapping.originalText));
368
+ return hashes.length > 0 && hashes.every((hash) => seen.has(hash));
369
+ }
370
+
371
+ function ignoreSeenCandidateContent(state: HeadroomRuntimeState, payload: CompressionPayload): void {
372
+ const seen = state.seenCandidateContentFingerprints;
373
+ if (!seen?.size) return;
374
+ for (const mapping of payload.mappings) {
375
+ if (mapping.applyTo && seen.has(stableHash(mapping.originalText))) mapping.applyTo = null;
376
+ }
377
+ }
378
+
379
+ function recordSeenCandidateContent(
380
+ state: HeadroomRuntimeState,
381
+ payload: CompressionPayload,
382
+ appliedMessages: AgentMessage[],
383
+ ): void {
384
+ state.seenCandidateContentFingerprints ??= new Set();
385
+ state.seenCandidateContentOrder ??= [];
386
+ payload.mappings.forEach((mapping) => {
387
+ if (!mapping.applyTo) return;
388
+ addSeenCandidateHash(state, stableHash(mapping.originalText));
389
+ const applied = convertMessage(appliedMessages[mapping.sourceIndex]);
390
+ if (applied) addSeenCandidateHash(state, stableHash(extractOpenAIText(applied)));
391
+ });
392
+ }
393
+
394
+ function addSeenCandidateHash(state: HeadroomRuntimeState, hash: string): void {
395
+ state.seenCandidateContentFingerprints ??= new Set();
396
+ state.seenCandidateContentOrder ??= [];
397
+ if (state.seenCandidateContentFingerprints.has(hash)) return;
398
+ state.seenCandidateContentFingerprints.add(hash);
399
+ state.seenCandidateContentOrder.push(hash);
400
+ while (state.seenCandidateContentOrder.length > MAX_SEEN_CANDIDATE_CONTENT_FINGERPRINTS) {
401
+ const oldest = state.seenCandidateContentOrder.shift();
402
+ if (oldest) state.seenCandidateContentFingerprints.delete(oldest);
403
+ }
404
+ }
405
+
406
+ function generateCandidateFingerprint(messages: AgentMessage[], payload: CompressionPayload): string {
407
+ const units = payload.mappings
408
+ .filter((mapping) => mapping.applyTo)
409
+ .map((mapping) => {
410
+ const source = messages[mapping.sourceIndex] as AgentMessage & {
411
+ content?: unknown;
412
+ toolCallId?: unknown;
413
+ toolName?: unknown;
414
+ };
415
+ return {
416
+ applyTo: mapping.applyTo,
417
+ sourceIndex: mapping.sourceIndex,
418
+ role: source.role,
419
+ toolCallId: typeof source.toolCallId === "string" ? source.toolCallId : null,
420
+ toolName: typeof source.toolName === "string" ? source.toolName : null,
421
+ contentShape: describeContentShape(source.content),
422
+ textLength: mapping.originalText.length,
423
+ textHash: stableHash(mapping.originalText),
424
+ };
425
+ });
426
+ return stableHash(JSON.stringify(units));
427
+ }
428
+
429
+ function describeContentShape(content: unknown): string {
430
+ if (Array.isArray(content)) {
431
+ return content
432
+ .map((part) => {
433
+ if (!part || typeof part !== "object" || !("type" in part)) return "unknown";
434
+ return String((part as { type?: unknown }).type ?? "unknown");
435
+ })
436
+ .join(",");
437
+ }
438
+ return typeof content;
439
+ }
440
+
441
+ function stableHash(value: string): string {
442
+ return createHash("sha256").update(value).digest("hex");
443
+ }
444
+
445
+ function generateFingerprint(messages: AgentMessage[]): string {
446
+ return messages
447
+ .map((m) => {
448
+ const converted = convertMessage(m);
449
+ const text = converted ? extractOpenAIText(converted) : "";
450
+ return `${m.role}:${text.length}:${stableHash(text)}`;
451
+ })
452
+ .join(",");
453
+ }
454
+
455
+ function shouldSkipBeforePayload(runtime: HeadroomRuntime, ctx: ExtensionContext): boolean {
456
+ if (!runtime.state.enabled) return true;
457
+ if (isRemoteBlocked(runtime.config)) {
458
+ if (!runtime.state.remoteWarningShown) {
459
+ runtime.state.remoteWarningShown = true;
460
+ ctx.ui.notify("Headroom compression skipped because remote proxy is blocked.", "warning");
461
+ }
462
+ runtime.refreshStatus(ctx);
463
+ return true;
464
+ }
465
+ const usage = ctx.getContextUsage();
466
+ return usage?.tokens !== null && usage?.tokens !== undefined && usage.tokens < runtime.config.minContextTokens;
467
+ }
468
+
469
+ function recordGuardSkip(stats: HeadroomStats, reason: string): void {
470
+ stats.guardSkips++;
471
+ stats.lastSkipReason = reason;
472
+ }
473
+
474
+ function recordAppliedCompression(stats: HeadroomStats, result: CompressResult, appliedMessages: number): void {
475
+ stats.applied++;
476
+ stats.tokensSaved += result.tokensSaved;
477
+ stats.lastError = undefined;
478
+ stats.lastSkipReason = undefined;
479
+ stats.last = { ...result, appliedMessages };
480
+ }
481
+
482
+ function summarizeTelemetry(state: HeadroomRuntimeState): string | null {
483
+ if (state.stats.last) {
484
+ const pct = Math.round((1 - state.stats.last.compressionRatio) * 100);
485
+ return `last compression estimated about ${state.stats.last.tokensSaved.toLocaleString()} tokens saved (-${pct}%) across ${state.stats.last.appliedMessages} tool results; local session estimate about ${state.stats.tokensSaved.toLocaleString()} tokens saved`;
486
+ }
487
+ if (!state.enabled) return "headroom loaded but disabled for this session";
488
+ if (state.stats.lastSkipReason) return `compression not applied; last guard skip: ${state.stats.lastSkipReason}`;
489
+ if (state.stats.lastError) return `compression unavailable; last error: ${state.stats.lastError}`;
490
+ if (state.proxyOnline === false) return "proxy unavailable";
491
+ return "headroom loaded; no compression applied yet";
492
+ }
493
+
494
+ function emitNotraceTelemetry(runtime: HeadroomRuntime): void {
495
+ const state = runtime.state;
496
+ const status = !state.enabled
497
+ ? "loaded-disabled"
498
+ : state.stats.last
499
+ ? "active"
500
+ : "loaded-inactive";
501
+ const details: Record<string, unknown> = {
502
+ attempts: state.stats.attempts,
503
+ applied: state.stats.applied,
504
+ guardSkips: state.stats.guardSkips,
505
+ tokensSaved: state.stats.tokensSaved,
506
+ proxyOnline: state.proxyOnline,
507
+ lastSkipReason: state.stats.lastSkipReason,
508
+ lastError: state.stats.lastError,
509
+ };
510
+ if (state.stats.last) details.last = { ...state.stats.last };
511
+ try {
512
+ runtime.pi.events.emit(NOTRACE_TELEMETRY_CHANNEL, {
513
+ extension: "noheadroom",
514
+ loaded: true,
515
+ enabled: state.enabled,
516
+ active: Boolean(state.stats.last),
517
+ status,
518
+ summary: summarizeTelemetry(state),
519
+ details,
520
+ });
521
+ } catch {
522
+ // Telemetry should never break compression behavior.
523
+ }
524
+ }
525
+
526
+ function announceAppliedCompression(
527
+ ctx: ExtensionContext,
528
+ result: CompressResult,
529
+ appliedMessages: number,
530
+ mode: HeadroomMode = "normal",
531
+ ): void {
532
+ if (mode === "quiet" || mode === "silent") return;
533
+ const pct = Math.round((1 - result.compressionRatio) * 100);
534
+ const summary = `compressed ${appliedMessages} tool results; estimated ~${result.tokensSaved.toLocaleString()} tokens saved (-${pct}%)`;
535
+ const line = `headroom: ${summary}`;
536
+ ctx.ui.notify(line, "info");
537
+ // Note: we no longer use pi.appendEntry or pi.sendMessage here because
538
+ // modifying the session history inside the context event triggers an infinite loop.
539
+ // Non-interactive `pi -p` does not always show footer/status UI, so print an explicit proof line.
540
+ // In interactive Pi TUI, writing to stderr during the context hook can leave a stale "Working..." row.
541
+ if (!ctx.hasUI) process.stderr.write(`🗜 ${line}\n`);
542
+ }
543
+
544
+ function announceGuardSkip(ctx: ExtensionContext, reason: string, result: CompressResult, mode: HeadroomMode = "normal"): void {
545
+ if (mode === "silent") return;
546
+ const line = `headroom: compression skipped by guard (${reason}); Headroom reported ${result.tokensSaved.toLocaleString()} tokens saved but Pi context was left unchanged`;
547
+ ctx.ui.notify(line, "warning");
548
+ // In interactive Pi TUI, writing to stderr during the context hook can leave a stale "Working..." row.
549
+ if (!ctx.hasUI) process.stderr.write(`⚠ ${line}\n`);
550
+ }
551
+
552
+ function recordCompressionError(runtime: HeadroomRuntime, ctx: ExtensionContext, error: unknown): void {
553
+ runtime.state.stats.lastError = getErrorMessage(error);
554
+ if (isAbortOrTimeoutError(error)) {
555
+ emitNotraceTelemetry(runtime);
556
+ runtime.refreshStatus(ctx);
557
+ return;
558
+ }
559
+
560
+ runtime.state.proxyOnline = false;
561
+ if (!runtime.state.offlineWarningShown) {
562
+ runtime.state.offlineWarningShown = true;
563
+ ctx.ui.notify(
564
+ `Headroom proxy unavailable. Compression disabled until /headroom health succeeds.\n${runtime.state.stats.lastError}`,
565
+ "warning",
566
+ );
567
+ }
568
+ emitNotraceTelemetry(runtime);
569
+ runtime.refreshStatus(ctx);
570
+ }
571
+
572
+ function getErrorMessage(error: unknown): string {
573
+ return error instanceof Error ? error.message : String(error);
574
+ }
575
+
576
+ function isAbortOrTimeoutError(error: unknown): boolean {
577
+ if (!error || typeof error !== "object") return false;
578
+ const candidate = error as { cause?: unknown; message?: unknown; name?: unknown };
579
+ if (candidate.name === "TimeoutError" || candidate.name === "AbortError") return true;
580
+ if (
581
+ typeof candidate.message === "string" &&
582
+ /aborted due to timeout|operation was aborted/i.test(candidate.message)
583
+ ) {
584
+ return true;
585
+ }
586
+ return candidate.cause !== undefined && candidate.cause !== error && isAbortOrTimeoutError(candidate.cause);
587
+ }
588
+
589
+ async function handleCommand(runtime: HeadroomRuntime, command: Subcommand, ctx: ExtensionContext): Promise<void> {
590
+ if (command === "on") {
591
+ runtime.state.enabled = true;
592
+ runtime.state.offlineWarningShown = false;
593
+ const healthy = await runtime.ensureProxy(ctx);
594
+ emitNotraceTelemetry(runtime);
595
+ ctx.ui.notify(
596
+ healthy ? "Headroom compression enabled." : proxyStartHint(runtime.config),
597
+ healthy ? "info" : "warning",
598
+ );
599
+ return;
600
+ }
601
+ if (command === "off") {
602
+ runtime.state.enabled = false;
603
+ emitNotraceTelemetry(runtime);
604
+ runtime.refreshStatus(ctx);
605
+ ctx.ui.notify("Headroom compression disabled for this Pi session.", "info");
606
+ return;
607
+ }
608
+ if (command === "health") {
609
+ const healthy = await runtime.ensureProxy(ctx);
610
+ emitNotraceTelemetry(runtime);
611
+ ctx.ui.notify(
612
+ healthy ? `Headroom proxy online: ${runtime.config.baseUrl}` : proxyStartHint(runtime.config),
613
+ healthy ? "info" : "warning",
614
+ );
615
+ return;
616
+ }
617
+ if (command === "stats") {
618
+ await showProxyStats(ctx, runtime.client, runtime.config);
619
+ return;
620
+ }
621
+ ctx.ui.notify(renderStatus(runtime.config, runtime.state), "info");
622
+ }
623
+
624
+ async function handleModeChange(runtime: HeadroomRuntime, rawMode: string, ctx: ExtensionContext): Promise<void> {
625
+ const VALID_MODES: HeadroomMode[] = ["normal", "quiet", "silent"];
626
+ if (!VALID_MODES.includes(rawMode as HeadroomMode)) {
627
+ ctx.ui.notify(
628
+ `Unknown mode "${rawMode}". Valid modes: ${VALID_MODES.join(", ")}\nUsage: /headroom mode <normal|quiet|silent>`,
629
+ "warning",
630
+ );
631
+ return;
632
+ }
633
+ const mode = rawMode as HeadroomMode;
634
+ runtime.config.mode = mode;
635
+ saveHeadroomSettings({ mode }, runtime.settingsFile);
636
+ emitNotraceTelemetry(runtime);
637
+ ctx.ui.notify(`Headroom output mode set to "${mode}" and saved to settings.`, "info");
638
+ }
639
+
640
+ function refreshStatus(ctx: ExtensionContext, config: HeadroomConfig, state: HeadroomRuntimeState): void {
641
+ if (!ctx.hasUI) return;
642
+ ctx.ui.setStatus(STATUS_KEY, renderFooterStatus(ctx, config, state));
643
+ }
644
+
645
+ type HeadroomStatusColor = "dim" | "warning" | "success";
646
+
647
+ type HeadroomStatusTheme = {
648
+ fg(color: HeadroomStatusColor, text: string): string;
649
+ };
650
+
651
+ function isHeadroomStatusTheme(theme: unknown): theme is HeadroomStatusTheme {
652
+ return typeof (theme as { fg?: unknown } | null)?.fg === "function";
653
+ }
654
+
655
+ function createStatusPainter(theme: unknown): (color: HeadroomStatusColor, text: string) => string {
656
+ if (isHeadroomStatusTheme(theme)) return (color, text) => theme.fg(color, text);
657
+ return (_color, text) => text;
658
+ }
659
+
660
+ function renderFooterStatus(ctx: ExtensionContext, config: HeadroomConfig, state: HeadroomRuntimeState): string {
661
+ const paint = createStatusPainter(ctx.ui.theme);
662
+ if (!state.enabled) return paint("dim", "○ Headroom off");
663
+ if (isRemoteBlocked(config)) return paint("warning", "⚠") + paint("dim", " Headroom remote blocked");
664
+ if (state.proxyOnline === false) return paint("dim", "○ Headroom not running");
665
+ if (state.proxyOnline === null && !state.stats.last) return paint("dim", "○ Headroom idle");
666
+ return paint("success", "✓") + paint("dim", " Headroom active");
667
+ }
668
+
669
+ async function showProxyStats(
670
+ ctx: ExtensionContext,
671
+ client: HeadroomHttpClient,
672
+ config: HeadroomConfig,
673
+ ): Promise<void> {
674
+ if (isRemoteBlocked(config)) {
675
+ ctx.ui.notify(renderRemoteBlocked(config), "warning");
676
+ return;
677
+ }
678
+ try {
679
+ const stats = await client.stats(ctx.signal);
680
+ ctx.ui.notify(
681
+ `Headroom proxy stats (${config.baseUrl}):\n${JSON.stringify(stats, null, 2).slice(0, 4000)}`,
682
+ "info",
683
+ );
684
+ } catch (error) {
685
+ const message = error instanceof Error ? error.message : String(error);
686
+ ctx.ui.notify(`Could not read Headroom stats: ${message}`, "warning");
687
+ }
688
+ }
689
+
690
+ function renderStatus(config: HeadroomConfig, state: HeadroomRuntimeState): string {
691
+ const stats = state.stats;
692
+ const lines = [
693
+ "Headroom token compression",
694
+ ` Enabled: ${state.enabled ? "yes" : "no"}`,
695
+ ` Proxy: ${config.baseUrl} (${state.proxyOnline === true ? "online" : state.proxyOnline === false ? "not running" : "unknown"})`,
696
+ ` Remote: ${isRemoteBlocked(config) ? "blocked" : config.allowRemote ? "allowed" : "local-only"}`,
697
+ ` Mode: ${config.mode}`,
698
+ ` Thresholds: context >= ${config.minContextTokens.toLocaleString()} tokens, toolResult >= ${config.minMessageChars.toLocaleString()} chars`,
699
+ "",
700
+ "Session stats:",
701
+ ` Attempts: ${stats.attempts}`,
702
+ ` Applied: ${stats.applied}`,
703
+ ` Guard skips: ${stats.guardSkips}`,
704
+ ` Estimated tokens saved: ~${stats.tokensSaved.toLocaleString()}`,
705
+ ` Note: local estimate; proxy /stats does not track Pi extension /v1/compress calls.`,
706
+ ];
707
+ if (stats.last) {
708
+ const pct = Math.round((1 - stats.last.compressionRatio) * 100);
709
+ lines.push(
710
+ "",
711
+ "Last applied compression:",
712
+ ` ${stats.last.tokensBefore.toLocaleString()} → ${stats.last.tokensAfter.toLocaleString()} tokens (-${pct}%)`,
713
+ ` Applied messages: ${stats.last.appliedMessages}`,
714
+ ` Transforms: ${stats.last.transformsApplied.join(", ") || "none"}`,
715
+ ` CCR hashes: ${stats.last.ccrHashes.length}`,
716
+ );
717
+ }
718
+ if (stats.lastSkipReason) lines.push("", `Last guard skip: ${stats.lastSkipReason}`);
719
+ if (stats.lastError) lines.push("", `Last error: ${stats.lastError}`);
720
+ return lines.join("\n");
721
+ }
722
+
723
+ function proxyStartHint(config: HeadroomConfig): string {
724
+ if (isRemoteBlocked(config)) return renderRemoteBlocked(config);
725
+ return [
726
+ `Headroom proxy is not reachable: ${config.baseUrl}`,
727
+ "This extension never starts the proxy; run it yourself:",
728
+ ` ${renderManualProxyCommand(config)}`,
729
+ ].join("\n");
730
+ }
731
+
732
+ function renderManualProxyCommand(config: HeadroomConfig): string {
733
+ try {
734
+ const url = new URL(config.baseUrl);
735
+ const host = url.hostname === "localhost" ? "127.0.0.1" : url.hostname.replace(/^\[(.*)]$/, "$1");
736
+ const port = url.port || "8787";
737
+ return `headroom proxy --host ${host} --port ${port} --mode token --no-cache`;
738
+ } catch {
739
+ return "headroom proxy --mode token --no-cache";
740
+ }
741
+ }
742
+
743
+ function renderRemoteBlocked(config: HeadroomConfig): string {
744
+ return [
745
+ `Headroom remote URL is blocked: ${config.baseUrl}`,
746
+ "Compression sends conversation context to the proxy.",
747
+ "Set PI_HEADROOM_ALLOW_REMOTE=1 only for a trusted proxy.",
748
+ ].join("\n");
749
+ }
750
+
751
+ function parseSubcommand(args: string): Subcommand {
752
+ const normalized = args.trim().toLowerCase();
753
+ return SUBCOMMANDS.includes(normalized as Subcommand) ? (normalized as Subcommand) : "status";
754
+ }
755
+
756
+ export const __test__ = {
757
+ isAbortOrTimeoutError,
758
+ renderFooterStatus,
759
+ generateFingerprint,
760
+ handleContextCompression,
761
+ };