@giladbarnea/pi-custom-footer 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gilad Barnea
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,42 @@
1
+ <div align="center">
2
+
3
+ # Custom Footer
4
+
5
+ **Know how much context remains. See what each turn costs.**
6
+
7
+ [![pi extension](https://img.shields.io/badge/pi-extension-blueviolet)](https://github.com/earendil-works/pi)
8
+ [![npm](https://img.shields.io/npm/v/%40giladbarnea%2Fpi-custom-footer)](https://www.npmjs.com/package/@giladbarnea/pi-custom-footer)
9
+ [![license](https://img.shields.io/github/license/giladbarnea/custom-footer)](LICENSE)
10
+
11
+ </div>
12
+
13
+ A Pi footer that puts your session’s context, cache usage, cost, and loaded skills around the editor.
14
+
15
+ ```sh
16
+ pi install npm:@giladbarnea/pi-custom-footer
17
+ ```
18
+
19
+ Above the editor, see your model, thinking level, session name and ID. Loaded skills get their own row, with token ages.
20
+
21
+ Below the editor, see:
22
+
23
+ - **Context remaining at a glance:** a color-graded gauge and used/window tokens.
24
+ - **Cost across the conversation:** cumulative cost and average cost per assistant turn.
25
+ - **Cache behavior:** session hit rate, latest hit or estimated miss, and reused/new token totals.
26
+ - **Where you are:** Git branch, dirty marker, directory, and other extensions’ status messages.
27
+
28
+ The layout follows your Pi theme and condenses to two footer lines in narrow panes.
29
+
30
+ **Resize without rescanning the conversation.** The header and footer share cached values. Session changes refresh them, including forks and compaction.
31
+
32
+ Skill age measures context-token growth since the first response after a skill load. A cache miss compares consecutive prompt sizes with reported reuse. Costs use the model’s reported pricing, including when you use a subscription.
33
+
34
+ ## Development
35
+
36
+ ```sh
37
+ npm ci
38
+ npm test
39
+ npm run check
40
+ ```
41
+
42
+ Tests cover rendered values, skill tracking, cache reuse, session changes, and forks. They make no model calls.
package/index.ts ADDED
@@ -0,0 +1,619 @@
1
+ /** Show session context, cache usage, cost, and loaded skills around the editor. */
2
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
5
+
6
+ import { getLoadedSkills, type SkillLocation } from "./skill-tracker.ts";
7
+
8
+ // ── Layout constants ────────────────────────────────────────────────────────
9
+
10
+ const NARROW_WIDTH = 56;
11
+ const NARROW_SEPARATOR = " ";
12
+ const WIDE_SEPARATOR = " · ";
13
+ const CONTEXT_GAUGE_SYMBOLS = [" ", "▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
14
+ const CONTEXT_GAUGE_STEP_COUNT = CONTEXT_GAUGE_SYMBOLS.length;
15
+ const CONTEXT_MUTED_THRESHOLD = 40;
16
+ const CONTEXT_WARNING_THRESHOLD = 65;
17
+ const CONTEXT_ERROR_THRESHOLD = 85;
18
+ const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
19
+ const ANSI_RESET = "\x1b[0m";
20
+
21
+ const THINKING_LEVELS: Record<string, { full: string; short: string; token: string }> = {
22
+ off: { full: "off", short: "o", token: "dim" },
23
+ minimal: { full: "min", short: "mn", token: "thinkingMinimal" },
24
+ low: { full: "low", short: "l", token: "thinkingLow" },
25
+ medium: { full: "med", short: "md", token: "thinkingMedium" },
26
+ high: { full: "high", short: "h", token: "thinkingHigh" },
27
+ xhigh: { full: "xhigh", short: "x", token: "thinkingXhigh" },
28
+ max: { full: "max", short: "mx", token: "thinkingMax" },
29
+ };
30
+
31
+ // ── Generic helpers ─────────────────────────────────────────────────────────
32
+
33
+ function isNarrow(width: number): boolean {
34
+ return width <= NARROW_WIDTH;
35
+ }
36
+
37
+ function joinedLine(parts: string[], separator: string): string {
38
+ return ` ${parts.join(separator)}`;
39
+ }
40
+
41
+ function wrapJoinedLines(parts: string[], width: number, separator: string): string[] {
42
+ if (parts.length === 0) return [];
43
+ const lines: string[] = [];
44
+ const remainingParts = [...parts];
45
+ while (remainingParts.length > 0) {
46
+ const lineParts: string[] = [];
47
+ while (remainingParts.length > 0) {
48
+ const candidateLine = joinedLine([...lineParts, remainingParts[0]!], separator);
49
+ if (lineParts.length > 0 && visibleWidth(candidateLine) >= width) break;
50
+ lineParts.push(remainingParts.shift()!);
51
+ if (visibleWidth(joinedLine(lineParts, separator)) >= width) break;
52
+ }
53
+ lines.push(truncateToWidth(joinedLine(lineParts, separator), width));
54
+ }
55
+ return lines;
56
+ }
57
+
58
+ function renderExtensionStatuses(
59
+ extensionStatuses: ReadonlyMap<string, string>,
60
+ width: number,
61
+ theme: any,
62
+ ): string[] {
63
+ if (extensionStatuses.size === 0) return [];
64
+ const statusLine = [...extensionStatuses.entries()]
65
+ .sort(([firstKey], [secondKey]) => firstKey.localeCompare(secondKey))
66
+ .map(([, text]) => text.replace(/[\r\n\t]/g, " ").replace(/ +/g, " ").trim())
67
+ .join(" ");
68
+ return [truncateToWidth(statusLine, width, theme.fg("dim", "..."))];
69
+ }
70
+
71
+ function formatTokens(n: number): string {
72
+ if (n >= 1_000_000) {
73
+ const millions = n / 1_000_000;
74
+ return `${millions >= 10 ? Math.round(millions) : millions.toFixed(1)}M`;
75
+ }
76
+ if (n >= 1_000) {
77
+ const thousands = n / 1_000;
78
+ return `${thousands >= 10 ? Math.round(thousands) : thousands.toFixed(1)}k`;
79
+ }
80
+ return String(n);
81
+ }
82
+
83
+ function formatCost(value: number): string {
84
+ return value < 0.1 ? value.toFixed(3) : value.toFixed(2);
85
+ }
86
+
87
+ function currentDirectoryName(cwd: string): string {
88
+ return cwd.split("/").pop() || cwd;
89
+ }
90
+
91
+ function normalizeDisplayValue(value: string): string {
92
+ return value.toLowerCase().replace(/[/\\]/g, "").trim();
93
+ }
94
+
95
+ function trimSessionPrefix(session: string, cwd: string): string {
96
+ const firstWord = session.split(/\s+/)[0] ?? "";
97
+ return normalizeDisplayValue(firstWord) === normalizeDisplayValue(currentDirectoryName(cwd))
98
+ ? session.slice(firstWord.length).trim()
99
+ : session;
100
+ }
101
+
102
+ type DisplaySessionPart = { text: string; token: "text" | "dim" };
103
+
104
+ function getDisplaySessionParts(ctx: any, cwd: string, pi: ExtensionAPI): DisplaySessionPart[] {
105
+ const customName = pi.getSessionName?.() || null;
106
+ const sessionId = ctx.sessionManager?.getSessionId?.() || null;
107
+ if (!customName) return sessionId ? [{ text: sessionId, token: "dim" }] : [];
108
+ const displayName = trimSessionPrefix(customName, cwd);
109
+ const namePart = { text: displayName, token: "text" } as const;
110
+ const idPart = sessionId ? [{ text: sessionId, token: "dim" } as const] : [];
111
+ return [namePart, ...idPart];
112
+ }
113
+
114
+ function getSkillLocations(pi: ExtensionAPI): SkillLocation[] {
115
+ return pi.getCommands().flatMap((command) => {
116
+ if (command.source !== "skill") return [];
117
+ const name = command.name.startsWith("skill:") ? command.name.slice("skill:".length) : command.name;
118
+ return [{ name, filePath: command.sourceInfo.path }];
119
+ });
120
+ }
121
+
122
+ // ── ANSI color helpers ──────────────────────────────────────────────────────
123
+
124
+ type RgbColor = { red: number; green: number; blue: number };
125
+ type RgbTokens = { dim: RgbColor | null; muted: RgbColor | null; warning: RgbColor | null; error: RgbColor | null };
126
+
127
+ function ansi256ToRgb(index: number): RgbColor {
128
+ const basicPalette: RgbColor[] = [
129
+ { red: 0, green: 0, blue: 0 },
130
+ { red: 128, green: 0, blue: 0 },
131
+ { red: 0, green: 128, blue: 0 },
132
+ { red: 128, green: 128, blue: 0 },
133
+ { red: 0, green: 0, blue: 128 },
134
+ { red: 128, green: 0, blue: 128 },
135
+ { red: 0, green: 128, blue: 128 },
136
+ { red: 192, green: 192, blue: 192 },
137
+ { red: 128, green: 128, blue: 128 },
138
+ { red: 255, green: 0, blue: 0 },
139
+ { red: 0, green: 255, blue: 0 },
140
+ { red: 255, green: 255, blue: 0 },
141
+ { red: 0, green: 0, blue: 255 },
142
+ { red: 255, green: 0, blue: 255 },
143
+ { red: 0, green: 255, blue: 255 },
144
+ { red: 255, green: 255, blue: 255 },
145
+ ];
146
+ if (index < 16) return basicPalette[index] ?? basicPalette[7]!;
147
+ if (index >= 232) {
148
+ const value = 8 + (index - 232) * 10;
149
+ return { red: value, green: value, blue: value };
150
+ }
151
+ const cubeIndex = index - 16;
152
+ const redLevel = Math.floor(cubeIndex / 36);
153
+ const greenLevel = Math.floor((cubeIndex % 36) / 6);
154
+ const blueLevel = cubeIndex % 6;
155
+ const levelToValue = (level: number) => (level === 0 ? 0 : 55 + level * 40);
156
+ return {
157
+ red: levelToValue(redLevel),
158
+ green: levelToValue(greenLevel),
159
+ blue: levelToValue(blueLevel),
160
+ };
161
+ }
162
+
163
+ function ansiCodeToRgb(code: number): RgbColor | null {
164
+ if (code >= 30 && code <= 37) return ansi256ToRgb(code - 30);
165
+ if (code >= 90 && code <= 97) return ansi256ToRgb(code - 90 + 8);
166
+ return null;
167
+ }
168
+
169
+ function getThemeTokenRgb(theme: any, token: string): RgbColor | null {
170
+ const themed = theme.fg(token, "x");
171
+ const matches = [...themed.matchAll(/\x1b\[([0-9;]+)m/g)];
172
+ for (let i = matches.length - 1; i >= 0; i -= 1) {
173
+ const codes = matches[i]?.[1]?.split(";").map(Number) ?? [];
174
+ for (let j = 0; j < codes.length; j += 1) {
175
+ const code = codes[j];
176
+ if (code === 38 && codes[j + 1] === 2) {
177
+ return { red: codes[j + 2] ?? 255, green: codes[j + 3] ?? 255, blue: codes[j + 4] ?? 255 };
178
+ }
179
+ if (code === 38 && codes[j + 1] === 5) {
180
+ return ansi256ToRgb(codes[j + 2] ?? 7);
181
+ }
182
+ const basic = ansiCodeToRgb(code);
183
+ if (basic) return basic;
184
+ }
185
+ }
186
+ return null;
187
+ }
188
+
189
+ function blendChannel(start: number, end: number, ratio: number): number {
190
+ return Math.round(start + (end - start) * ratio);
191
+ }
192
+
193
+ function blendRgb(start: RgbColor, end: RgbColor, ratio: number): RgbColor {
194
+ return {
195
+ red: blendChannel(start.red, end.red, ratio),
196
+ green: blendChannel(start.green, end.green, ratio),
197
+ blue: blendChannel(start.blue, end.blue, ratio),
198
+ };
199
+ }
200
+
201
+ function colorizeRgb(text: string, rgb: RgbColor): string {
202
+ return `\x1b[38;2;${rgb.red};${rgb.green};${rgb.blue}m${text}${ANSI_RESET}`;
203
+ }
204
+
205
+ function renderContextUsage(
206
+ theme: any,
207
+ pct: number,
208
+ text: string,
209
+ rgbTokens: RgbTokens,
210
+ ): string {
211
+ const { dim, muted, warning, error } = rgbTokens;
212
+ if (!dim || !muted || !warning || !error) {
213
+ if (pct >= CONTEXT_ERROR_THRESHOLD) return theme.fg("error", text);
214
+ if (pct >= CONTEXT_WARNING_THRESHOLD) return theme.fg("warning", text);
215
+ if (pct >= CONTEXT_MUTED_THRESHOLD) return theme.fg("muted", text);
216
+ return theme.fg("dim", text);
217
+ }
218
+ if (pct < CONTEXT_MUTED_THRESHOLD) {
219
+ return colorizeRgb(text, blendRgb(dim, muted, pct / CONTEXT_MUTED_THRESHOLD));
220
+ }
221
+ if (pct < CONTEXT_WARNING_THRESHOLD) {
222
+ return colorizeRgb(
223
+ text,
224
+ blendRgb(muted, warning, (pct - CONTEXT_MUTED_THRESHOLD) / (CONTEXT_WARNING_THRESHOLD - CONTEXT_MUTED_THRESHOLD)),
225
+ );
226
+ }
227
+ if (pct < CONTEXT_ERROR_THRESHOLD) {
228
+ return colorizeRgb(
229
+ text,
230
+ blendRgb(warning, error, (pct - CONTEXT_WARNING_THRESHOLD) / (CONTEXT_ERROR_THRESHOLD - CONTEXT_WARNING_THRESHOLD)),
231
+ );
232
+ }
233
+ return theme.fg("error", text);
234
+ }
235
+
236
+ function ctxGauge(pct: number): string {
237
+ const stepIndex = Math.min(
238
+ Math.floor(pct / (100 / CONTEXT_GAUGE_STEP_COUNT)),
239
+ CONTEXT_GAUGE_STEP_COUNT - 1,
240
+ );
241
+ return CONTEXT_GAUGE_SYMBOLS[stepIndex]!;
242
+ }
243
+
244
+ function renderThinkingLabel(theme: any, level: string, full: boolean): string | null {
245
+ if (!level) return null;
246
+ const info = THINKING_LEVELS[level];
247
+ if (!info) return level;
248
+ const label = full ? info.full : info.short;
249
+ const text = level === "high" || level === "xhigh" ? theme.bold(label) : label;
250
+ return theme.fg(info.token, text);
251
+ }
252
+
253
+ // ── Session helpers ─────────────────────────────────────────────────────────
254
+
255
+ interface SessionStats {
256
+ totalCost: number;
257
+ totalReused: number;
258
+ totalFresh: number;
259
+ sessionCacheHitRate: number | null;
260
+ latestCacheHitRate: number | null;
261
+ latestCacheMissTokens: number | null;
262
+ averageCostPerTurn: number;
263
+ lastContextTokens: number; // input+output+cacheRead+cacheWrite of the last valid turn
264
+ }
265
+
266
+ function getSessionStats(ctx: any): SessionStats {
267
+ let turnCount = 0;
268
+ let totalCost = 0;
269
+ let totalReused = 0;
270
+ let totalFresh = 0;
271
+ let lastContextTokens = 0;
272
+ let previousPromptTokens: number | null = null;
273
+ let cacheWasReported = false;
274
+ let latestCacheHitRate: number | null = null;
275
+ let latestCacheMissTokens: number | null = null;
276
+ for (const entry of ctx.sessionManager?.getBranch?.() ?? []) {
277
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
278
+ previousPromptTokens = null;
279
+ cacheWasReported = false;
280
+ continue;
281
+ }
282
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
283
+ const message = entry.message as AssistantMessage;
284
+ if (message.stopReason === "error" || message.stopReason === "aborted") continue;
285
+ const { input, output, cacheRead, cacheWrite, cost } = message.usage;
286
+ const promptTokens = input + cacheRead + cacheWrite;
287
+ turnCount += 1;
288
+ totalCost += cost.total;
289
+ totalReused += cacheRead;
290
+ totalFresh += input + cacheWrite;
291
+ lastContextTokens = promptTokens + output;
292
+ if (promptTokens <= 0) continue;
293
+
294
+ const cacheReported = cacheRead + cacheWrite > 0;
295
+ const cacheKnowledgeAvailable = cacheReported || cacheWasReported;
296
+ latestCacheHitRate = cacheKnowledgeAvailable ? (cacheRead / promptTokens) * 100 : null;
297
+ latestCacheMissTokens = null;
298
+ if (previousPromptTokens !== null && cacheKnowledgeAvailable) {
299
+ const missedTokens = Math.min(previousPromptTokens, promptTokens) - cacheRead;
300
+ latestCacheMissTokens = missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS ? missedTokens : null;
301
+ }
302
+ previousPromptTokens = promptTokens;
303
+ cacheWasReported ||= cacheReported;
304
+ }
305
+ const totalPrompt = totalReused + totalFresh;
306
+ return {
307
+ totalCost,
308
+ totalReused,
309
+ totalFresh,
310
+ sessionCacheHitRate: totalPrompt > 0 ? (totalReused / totalPrompt) * 100 : null,
311
+ latestCacheHitRate,
312
+ latestCacheMissTokens,
313
+ averageCostPerTurn: turnCount > 0 ? totalCost / turnCount : 0,
314
+ lastContextTokens,
315
+ };
316
+ }
317
+
318
+ // Mirror pi's own context accounting (calculateContextTokens in
319
+ // dist/core/compaction/compaction.js: input+output+cacheRead+cacheWrite of the
320
+ // last valid assistant turn). getContextUsage() is authoritative when present;
321
+ // the fallback only fires before the first response or right after compaction.
322
+ function getContextPercent(
323
+ ctx: any,
324
+ lastContextTokens: number,
325
+ usage: ReturnType<ExtensionContext["getContextUsage"]>,
326
+ ): { pct: number; window: number; tokens: number } {
327
+ if (usage && usage.percent != null) {
328
+ return { pct: usage.percent, window: usage.contextWindow ?? 0, tokens: usage.tokens ?? 0 };
329
+ }
330
+ const window = ctx.model?.contextWindow ?? 200_000;
331
+ return {
332
+ pct: window > 0 ? (lastContextTokens / window) * 100 : 0,
333
+ window,
334
+ tokens: lastContextTokens,
335
+ };
336
+ }
337
+
338
+ function formatModel(model: any): string {
339
+ const rawName = model?.name || model?.id || "no-model";
340
+ const words = rawName.split(/\s+/);
341
+ return words.length === 2 && words[0]?.endsWith(":") ? words[1] : rawName;
342
+ }
343
+
344
+ interface FooterSnapshot {
345
+ manager: ExtensionContext["sessionManager"];
346
+ sessionId: string;
347
+ leafId: string | null;
348
+ model: ExtensionContext["model"];
349
+ stats: SessionStats;
350
+ context: ReturnType<typeof getContextPercent>;
351
+ sessionParts: DisplaySessionPart[];
352
+ }
353
+
354
+ // ── Extension entry point ───────────────────────────────────────────────────
355
+
356
+ export default function (pi: ExtensionAPI) {
357
+ let currentCtx: any = null;
358
+ let tuiRef: any = null;
359
+ let gitBranch: string | null = null;
360
+ let gitDirty = false;
361
+ let thinkingLevel = "off";
362
+ let loadedSkills: Array<{ name: string; tokenAge: number | null }> = [];
363
+ let skillsDirty = true;
364
+ let snapshot: FooterSnapshot | undefined;
365
+
366
+ // ── Rendering ────────────────────────────────────────────────────────
367
+
368
+ function refreshLoadedSkills(ctx: any, currentContextTokens: number | null): void {
369
+ loadedSkills = getLoadedSkills(
370
+ ctx.sessionManager.buildSessionContext().messages,
371
+ getSkillLocations(pi),
372
+ ctx.cwd,
373
+ ).map(({ name, loadedAtTokens }) => ({
374
+ name,
375
+ tokenAge:
376
+ currentContextTokens !== null && loadedAtTokens !== null && currentContextTokens >= loadedAtTokens
377
+ ? currentContextTokens - loadedAtTokens
378
+ : null,
379
+ }));
380
+ }
381
+
382
+ function getSnapshot(): FooterSnapshot {
383
+ const manager: ExtensionContext["sessionManager"] = currentCtx.sessionManager;
384
+ const sessionId = manager.getSessionId();
385
+ const leafId = manager.getLeafId();
386
+ const model: ExtensionContext["model"] = currentCtx.model;
387
+ if (snapshot && snapshot.manager === manager && snapshot.sessionId === sessionId && snapshot.leafId === leafId && snapshot.model === model) return snapshot;
388
+ const stats = getSessionStats(currentCtx);
389
+ const usage = currentCtx.getContextUsage();
390
+ if (skillsDirty) refreshLoadedSkills(currentCtx, usage?.tokens ?? null);
391
+ skillsDirty = false;
392
+ snapshot = {
393
+ manager, sessionId, leafId, model, stats,
394
+ context: getContextPercent(currentCtx, stats.lastContextTokens, usage),
395
+ sessionParts: getDisplaySessionParts(currentCtx, currentCtx.cwd || ".", pi),
396
+ };
397
+ return snapshot;
398
+ }
399
+
400
+ function renderAbove(width: number, theme: any): string[] {
401
+ if (!currentCtx) return [];
402
+ const model = formatModel(currentCtx.model);
403
+ const thinking = renderThinkingLabel(theme, thinkingLevel, true);
404
+ const sessionParts = getSnapshot().sessionParts.map((part) => theme.fg(part.token, part.text));
405
+ const skillPills = loadedSkills.map(({ name, tokenAge }) => {
406
+ const nameText = theme.fg("mdHeading", ` ${name}`);
407
+ const ageText = tokenAge === null ? "" : theme.fg("muted", ` -${formatTokens(tokenAge)}`);
408
+ return theme.bg("toolPendingBg", `${nameText}${ageText} `);
409
+ });
410
+ const parts = [theme.fg("accent", theme.bold(model))];
411
+ if (thinking) parts.push(thinking);
412
+ parts.push(...sessionParts);
413
+ const separator = theme.fg("dim", WIDE_SEPARATOR);
414
+ return [
415
+ ...wrapJoinedLines(parts, width, separator),
416
+ ...wrapJoinedLines(skillPills, width, separator),
417
+ ];
418
+ }
419
+
420
+ function renderBelow(width: number, theme: any): string[] {
421
+ if (!currentCtx) return [];
422
+ const { stats, context: { pct, window, tokens } } = getSnapshot();
423
+ const rgbTokens: RgbTokens = {
424
+ dim: getThemeTokenRgb(theme, "dim"),
425
+ muted: getThemeTokenRgb(theme, "muted"),
426
+ warning: getThemeTokenRgb(theme, "warning"),
427
+ error: getThemeTokenRgb(theme, "error"),
428
+ };
429
+ return isNarrow(width)
430
+ ? renderFooterNarrow(width, theme, stats, pct, window, rgbTokens)
431
+ : renderFooterWide(width, theme, stats, pct, window, tokens, rgbTokens);
432
+ }
433
+
434
+ function renderFooterWide(
435
+ width: number,
436
+ theme: any,
437
+ stats: SessionStats,
438
+ pct: number,
439
+ window: number,
440
+ tokens: number,
441
+ rgbTokens: RgbTokens,
442
+ ): string[] {
443
+ const separator = theme.fg("dim", WIDE_SEPARATOR);
444
+ const label = (text: string) => theme.fg("dim", text.padEnd(8));
445
+ const cwd = currentCtx.cwd || ".";
446
+
447
+ const locationParts: string[] = [];
448
+ if (gitBranch) {
449
+ const dirty = gitDirty ? theme.fg("warning", "*") : "";
450
+ locationParts.push(`${theme.fg("accent", ` ${gitBranch}`)}${dirty}`);
451
+ }
452
+ locationParts.push(theme.bg("selectedBg", theme.fg("text", ` ${currentDirectoryName(cwd)}/ `)));
453
+ const locationLine = truncateToWidth(` ${locationParts.join(separator)}`, width);
454
+
455
+ const gauge = renderContextUsage(theme, pct, `${ctxGauge(pct)} ${Math.round(pct)}%`, rgbTokens);
456
+ const contextValue = theme.fg("text", `${formatTokens(tokens)} / ${formatTokens(window)} tokens`);
457
+ const usingSubscription = currentCtx.model
458
+ ? currentCtx.modelRegistry?.isUsingOAuth?.(currentCtx.model)
459
+ : false;
460
+ const costText = theme.fg("warning", `$${formatCost(stats.totalCost)}`);
461
+ const subLabel = usingSubscription ? theme.fg("muted", " sub") : "";
462
+ const perTurn = theme.fg("dim", `$${formatCost(stats.averageCostPerTurn)}/turn`);
463
+ const contextLine = truncateToWidth(
464
+ ` ${label("context")}${gauge} ${contextValue}${separator}${costText}${subLabel} ${perTurn}`,
465
+ width,
466
+ );
467
+
468
+ const sessionHit = stats.sessionCacheHitRate;
469
+ const sessionHitToken = sessionHit != null && sessionHit >= 80 ? "success" : "muted";
470
+ const sessionHitText = sessionHit != null ? `${sessionHit.toFixed(1)}% session` : "no cache yet";
471
+ const latestHit = stats.latestCacheHitRate;
472
+ const latestText = stats.latestCacheMissTokens != null
473
+ ? theme.fg("warning", `latest miss ${formatTokens(stats.latestCacheMissTokens)} re-billed`)
474
+ : latestHit != null
475
+ ? theme.fg(latestHit >= 80 ? "success" : "muted", `latest ${latestHit.toFixed(1)}%`)
476
+ : null;
477
+ const reuseSplit = theme.fg("dim", `${formatTokens(stats.totalReused)} reused / ${formatTokens(stats.totalFresh)} new`);
478
+ const cacheParts = [theme.fg(sessionHitToken, sessionHitText), latestText, reuseSplit].filter(Boolean);
479
+ const cacheLine = truncateToWidth(` ${label("cache")}${cacheParts.join(separator)}`, width);
480
+
481
+ return [locationLine, contextLine, cacheLine];
482
+ }
483
+
484
+ function renderFooterNarrow(
485
+ width: number,
486
+ theme: any,
487
+ stats: SessionStats,
488
+ pct: number,
489
+ window: number,
490
+ rgbTokens: RgbTokens,
491
+ ): string[] {
492
+ const cwd = currentCtx.cwd || ".";
493
+ const locationParts: string[] = [];
494
+ if (gitBranch) {
495
+ const dirty = gitDirty ? theme.fg("warning", "*") : "";
496
+ locationParts.push(`${theme.fg("accent", gitBranch)}${dirty}`);
497
+ }
498
+ locationParts.push(theme.fg("text", `${currentDirectoryName(cwd)}/`));
499
+ const locationLine = truncateToWidth(` ${locationParts.join(NARROW_SEPARATOR)}`, width);
500
+
501
+ const gauge = renderContextUsage(theme, pct, `${Math.round(pct)}%/${formatTokens(window)}`, rgbTokens);
502
+ const latestHit = stats.latestCacheHitRate;
503
+ const cache = stats.latestCacheMissTokens != null
504
+ ? theme.fg("warning", `miss ${formatTokens(stats.latestCacheMissTokens)}`)
505
+ : latestHit != null
506
+ ? theme.fg("muted", `latest ${Math.round(latestHit)}%`)
507
+ : "";
508
+ const cost = theme.fg("warning", `$${formatCost(stats.totalCost)}`);
509
+ const dataLine = truncateToWidth(` ${[gauge, cache, cost].filter(Boolean).join(NARROW_SEPARATOR)}`, width);
510
+
511
+ return [locationLine, dataLine];
512
+ }
513
+
514
+ // ── Git ───────────────────────────────────────────────────────────────
515
+
516
+ async function refreshGit(): Promise<void> {
517
+ try {
518
+ const branchResult = await pi.exec("git", ["branch", "--show-current"]);
519
+ gitBranch = branchResult.stdout.trim() || null;
520
+ if (!gitBranch) {
521
+ gitDirty = false;
522
+ return;
523
+ }
524
+ const statusResult = await pi.exec("git", ["status", "--porcelain"]);
525
+ gitDirty = statusResult.stdout.trim().length > 0;
526
+ } catch {
527
+ gitBranch = null;
528
+ gitDirty = false;
529
+ }
530
+ }
531
+
532
+ function requestRender(): void {
533
+ tuiRef?.requestRender();
534
+ }
535
+
536
+ function updateCtx(ctx: any): void {
537
+ currentCtx = ctx;
538
+ snapshot = undefined;
539
+ requestRender();
540
+ }
541
+
542
+ async function refreshCtx(ctx: any): Promise<void> {
543
+ currentCtx = ctx;
544
+ snapshot = undefined;
545
+ await refreshGit();
546
+ requestRender();
547
+ }
548
+
549
+ // ── Event wiring ──────────────────────────────────────────────────────
550
+
551
+ pi.events.on("session:name-changed", () => {
552
+ snapshot = undefined;
553
+ requestRender();
554
+ });
555
+
556
+ pi.on("session_start", async (_event: any, ctx: any) => {
557
+ currentCtx = ctx;
558
+ snapshot = undefined;
559
+ skillsDirty = true;
560
+ thinkingLevel = pi.getThinkingLevel() ?? "off";
561
+ await refreshGit();
562
+
563
+ ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
564
+ tuiRef = tui;
565
+ const unsub = footerData.onBranchChange(() => {
566
+ gitBranch = footerData.getGitBranch();
567
+ void refreshGit().then(requestRender);
568
+ });
569
+ return {
570
+ dispose: unsub,
571
+ invalidate() {},
572
+ render(width: number): string[] {
573
+ return [...renderBelow(width, theme), ...renderExtensionStatuses(footerData.getExtensionStatuses(), width, theme)];
574
+ },
575
+ };
576
+ });
577
+
578
+ ctx.ui.setWidget(
579
+ "custom-footer-above",
580
+ (_tui: any, theme: any) => ({
581
+ dispose() {},
582
+ invalidate() {},
583
+ render(width: number): string[] {
584
+ return renderAbove(width, theme);
585
+ },
586
+ }),
587
+ { placement: "aboveEditor" },
588
+ );
589
+ });
590
+
591
+ pi.on("session_shutdown", async () => {
592
+ currentCtx = null;
593
+ tuiRef = null;
594
+ gitBranch = null;
595
+ gitDirty = false;
596
+ loadedSkills = [];
597
+ snapshot = undefined;
598
+ skillsDirty = true;
599
+ });
600
+
601
+ pi.on("model_select", async (_event: any, ctx: any) => updateCtx(ctx));
602
+ pi.on("thinking_level_select", async (event: any) => {
603
+ thinkingLevel = event.level;
604
+ requestRender();
605
+ });
606
+ pi.on("message_end", async (_event: any, ctx: any) => updateCtx(ctx));
607
+ pi.on("turn_end", async (_event: any, ctx: any) => {
608
+ skillsDirty = true;
609
+ await refreshCtx(ctx);
610
+ });
611
+ pi.on("session_compact", async (_event: any, ctx: any) => {
612
+ skillsDirty = true;
613
+ updateCtx(ctx);
614
+ });
615
+ pi.on("session_tree", async (_event: any, ctx: any) => {
616
+ skillsDirty = true;
617
+ updateCtx(ctx);
618
+ });
619
+ }
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "@giladbarnea/pi-custom-footer",
3
+ "version": "0.1.0",
4
+ "description": "Context, cache, cost, and loaded skills at a glance in Pi.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Gilad Barnea",
8
+ "keywords": [
9
+ "pi-package",
10
+ "pi",
11
+ "pi-coding-agent",
12
+ "footer",
13
+ "context",
14
+ "cache"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/giladbarnea/custom-footer.git"
19
+ },
20
+ "homepage": "https://github.com/giladbarnea/custom-footer",
21
+ "bugs": {
22
+ "url": "https://github.com/giladbarnea/custom-footer/issues"
23
+ },
24
+ "files": [
25
+ "index.ts",
26
+ "skill-tracker.ts",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "scripts": {
31
+ "test": "node tests/skills.mjs && node tests/cache.mjs && node tests/load.mjs",
32
+ "check": "tsc --noEmit"
33
+ },
34
+ "engines": {
35
+ "node": ">=22.19.0"
36
+ },
37
+ "peerDependencies": {
38
+ "@earendil-works/pi-ai": ">=0.84.2",
39
+ "@earendil-works/pi-coding-agent": ">=0.84.2",
40
+ "@earendil-works/pi-tui": ">=0.84.2"
41
+ },
42
+ "devDependencies": {
43
+ "@earendil-works/pi-ai": "0.85.1",
44
+ "@earendil-works/pi-coding-agent": "0.85.1",
45
+ "@earendil-works/pi-tui": "0.85.1",
46
+ "@types/node": "^22.0.0",
47
+ "jiti": "^2.7.0",
48
+ "typescript": "~5.9.3"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ },
53
+ "pi": {
54
+ "extensions": [
55
+ "./index.ts"
56
+ ]
57
+ }
58
+ }
@@ -0,0 +1,127 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+
4
+ export type SkillLocation = {
5
+ filePath: string;
6
+ name: string;
7
+ };
8
+
9
+ export type LoadedSkill = {
10
+ loadedAtTokens: number | null;
11
+ name: string;
12
+ };
13
+
14
+ type UnknownRecord = Record<string, unknown>;
15
+
16
+ const MAX_SKILL_NAME_LENGTH = 64;
17
+ const SKILL_NAME_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
18
+
19
+ function isRecord(value: unknown): value is UnknownRecord {
20
+ return typeof value === "object" && value !== null;
21
+ }
22
+
23
+ function resolvePath(cwd: string, rawPath: string): string {
24
+ const path = rawPath.startsWith("@") ? rawPath.slice(1) : rawPath;
25
+ return path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : resolve(cwd, path);
26
+ }
27
+
28
+ function textFromContent(content: unknown): string {
29
+ if (typeof content === "string") return content;
30
+ if (!Array.isArray(content)) return "";
31
+ return content.flatMap((block) =>
32
+ isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : [],
33
+ ).join("\n");
34
+ }
35
+
36
+ function isValidSkillName(name: string): boolean {
37
+ return name.length <= MAX_SKILL_NAME_LENGTH && SKILL_NAME_PATTERN.test(name);
38
+ }
39
+
40
+ function expandedSkillNames(content: unknown): string[] {
41
+ return [...textFromContent(content).matchAll(/<skill name="([^"]+)" location="[^"]+">/g)]
42
+ .map((match) => match[1]!)
43
+ .filter(isValidSkillName);
44
+ }
45
+
46
+ function readPaths(toolCall: UnknownRecord): string[] {
47
+ if (!isRecord(toolCall.arguments)) return [];
48
+ if (toolCall.name === "read" && typeof toolCall.arguments.path === "string") {
49
+ return [toolCall.arguments.path];
50
+ }
51
+ if (toolCall.name !== "read_many_files" || !Array.isArray(toolCall.arguments.paths)) return [];
52
+ return toolCall.arguments.paths.filter((path): path is string => typeof path === "string");
53
+ }
54
+
55
+ function skillNamesForReadPath(rawPath: string, skills: readonly SkillLocation[], cwd: string): string[] {
56
+ const path = resolvePath(cwd, rawPath);
57
+ return skills.flatMap((skill) => path === resolvePath(cwd, skill.filePath) ? [skill.name] : []);
58
+ }
59
+
60
+ function assistantPromptTokens(message: UnknownRecord, compactionTimestamp: number | null): number | null {
61
+ if (message.role !== "assistant" || message.stopReason === "error" || message.stopReason === "aborted") return null;
62
+ if (compactionTimestamp !== null && (typeof message.timestamp !== "number" || message.timestamp <= compactionTimestamp)) return null;
63
+ if (!isRecord(message.usage)) return null;
64
+ const { input, cacheRead, cacheWrite } = message.usage;
65
+ if (typeof input !== "number" || typeof cacheRead !== "number" || typeof cacheWrite !== "number") return null;
66
+ const promptTokens = input + cacheRead + cacheWrite;
67
+ return promptTokens > 0 ? promptTokens : null;
68
+ }
69
+
70
+ function latestCompactionTimestamp(history: readonly unknown[]): number | null {
71
+ return history.reduce<number | null>((latest, message) => {
72
+ if (!isRecord(message) || message.role !== "compactionSummary" || typeof message.timestamp !== "number") return latest;
73
+ return latest === null ? message.timestamp : Math.max(latest, message.timestamp);
74
+ }, null);
75
+ }
76
+
77
+ /**
78
+ * Return skills in the effective model history with their first valid post-load prompt size.
79
+ *
80
+ * @example
81
+ * getLoadedSkills([], [], "/workspace") // []
82
+ */
83
+ export function getLoadedSkills(
84
+ history: readonly unknown[],
85
+ skills: readonly SkillLocation[],
86
+ cwd: string,
87
+ ): LoadedSkill[] {
88
+ const compactionTimestamp = latestCompactionTimestamp(history);
89
+ const loadedSkills = new Map<string, number | null>();
90
+ const pendingBaselines = new Set<string>();
91
+ const skillNamesByToolCall = new Map<string, string[]>();
92
+
93
+ const markLoaded = (skillName: string) => {
94
+ loadedSkills.set(skillName, null);
95
+ pendingBaselines.add(skillName);
96
+ };
97
+
98
+ for (const message of history) {
99
+ if (!isRecord(message)) continue;
100
+
101
+ if (message.role === "user") {
102
+ for (const skillName of expandedSkillNames(message.content)) markLoaded(skillName);
103
+ continue;
104
+ }
105
+
106
+ if (message.role === "toolResult") {
107
+ if (message.isError !== false || typeof message.toolCallId !== "string") continue;
108
+ for (const skillName of skillNamesByToolCall.get(message.toolCallId) ?? []) markLoaded(skillName);
109
+ continue;
110
+ }
111
+
112
+ if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
113
+ const promptTokens = assistantPromptTokens(message, compactionTimestamp);
114
+ if (promptTokens !== null) {
115
+ for (const skillName of pendingBaselines) loadedSkills.set(skillName, promptTokens);
116
+ pendingBaselines.clear();
117
+ }
118
+
119
+ for (const toolCall of message.content.filter(isRecord)) {
120
+ if (toolCall.type !== "toolCall" || typeof toolCall.id !== "string") continue;
121
+ const skillNames = readPaths(toolCall).flatMap((path) => skillNamesForReadPath(path, skills, cwd));
122
+ if (skillNames.length > 0) skillNamesByToolCall.set(toolCall.id, [...new Set(skillNames)]);
123
+ }
124
+ }
125
+
126
+ return [...loadedSkills].map(([name, loadedAtTokens]) => ({ name, loadedAtTokens }));
127
+ }