@giladbarnea/pi-custom-footer 0.1.9 → 0.1.11

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.
Files changed (3) hide show
  1. package/README.md +6 -4
  2. package/index.ts +100 -20
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ---
2
- last_updated: 2026-11-07T17-30
2
+ last_updated: 2026-11-11T15-30
3
3
  ---
4
4
 
5
5
  <div align="center">
@@ -16,6 +16,8 @@ last_updated: 2026-11-07T17-30
16
16
 
17
17
  A Pi footer that puts your session’s context, cache usage, cost, and loaded skills around the editor.
18
18
 
19
+ **Mobile-friendly and optimized for multiplexers.** It works on a phone with the keyboard up, in a narrow tmux pane, and on a wide desktop. Every line drops its least important detail first, so you keep the facts that matter at any size.
20
+
19
21
  ```sh
20
22
  pi install npm:@giladbarnea/pi-custom-footer
21
23
  ```
@@ -28,16 +30,16 @@ Below the editor, see:
28
30
 
29
31
  - **Context remaining at a glance:** a color-graded gauge and used/window tokens.
30
32
  - **Cost across the conversation:** cumulative cost and average cost per assistant turn.
31
- - **Cache behavior:** session hit rate, latest hit or estimated miss, and reused/new token totals.
33
+ - **Cache behavior:** session hit rate, latest hit or miss, and reused/new token totals. Like Pi’s own notice, a miss shows what it cost and why it happened: an idle gap or a model switch.
32
34
  - **Where you are:** Git branch, dirty marker, directory, and other extensions’ status messages.
33
35
 
34
- The layout follows your Pi theme. The header and the footer each take the fewest lines they can. To fit, they first drop labels, round readings, remove whitespace, and drop the branch icon. Only then does the footer hide facts: the reused/new split, the session hit rate, the token counts, and last the cost per turn.
36
+ The layout follows your Pi theme. The header and the footer each take the fewest lines they can. To fit, they first drop labels, round readings, remove whitespace, and drop the branch icon. Only then does the footer hide facts: the reused/new split, the session hit rate, the token counts, and last the cost per turn. A cache miss drops its re-billed tokens early. It keeps its cause until every one of those facts has hidden, and keeps its cost to the end.
35
37
 
36
38
  Skills get one row for every eight terminal rows past the first six, with a minimum of one. A 21-row phone screen gets one row, a 27-row screen two, and a 34-row screen three. To fit, the row first drops token ages, then separators, then shortens long names in the middle (`caut…ctor`). Only then does it hide skills from the end, behind a `+N` count at the end of the last row.
37
39
 
38
40
  **Resize without rescanning the conversation.** The header and footer share cached values. Session changes refresh them, including forks and compaction.
39
41
 
40
- 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.
42
+ Skill age measures context-token growth since the first response after a skill load. Cache misses mirror Pi’s own miss accounting: the tokens re-billed since the last request or cache warm, their extra cost over cache reads, and the idle time. Costs use the model’s reported pricing, including when you use a subscription.
41
43
 
42
44
  ## Development
43
45
 
package/index.ts CHANGED
@@ -24,6 +24,14 @@
24
24
  * - The header omits the routed physical model and thinking level.
25
25
  * - After compaction, unknown usage falls back to the selected model's window
26
26
  * or 200k, ignoring the known physical window from getContextUsage().
27
+ *
28
+ * Known differences from Pi's cache-miss notice, reviewed November 11, 2026,
29
+ * against Pi 1.4.0 and 1.5.2:
30
+ * - The footer shows any miss above 1,024 tokens. Pi's notice hides a miss
31
+ * under 20k tokens that also costs under $0.10.
32
+ * - Errored and aborted turns are skipped, as elsewhere in the footer. Pi's
33
+ * scan includes them.
34
+ * - The footer scans the current branch. Pi scans every session entry.
27
35
  */
28
36
  import type { AssistantMessage } from "@earendil-works/pi-ai";
29
37
  import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
@@ -51,6 +59,8 @@ const BRANCH_GLYPH = "";
51
59
  const CONTEXT_GAUGE_SYMBOLS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
52
60
  const CONTEXT_GAUGE_STEP_COUNT = CONTEXT_GAUGE_SYMBOLS.length;
53
61
  const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
62
+ // Pi's prompt-cache TTL: a miss after a longer idle gap names the gap as its cause.
63
+ const CACHE_TTL_MS = 5 * 60 * 1000;
54
64
  // Match Theme.fg, which resets the foreground only. A full reset would punch a
55
65
  // hole in any background the caller has already opened, such as the cwd pill.
56
66
  const ANSI_FG_RESET = "\x1b[39m";
@@ -152,9 +162,13 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
152
162
  ["cwd", "short"], ["spacing", "bare"],
153
163
  // 4. Drop the branch icon.
154
164
  ["branch", "bare"],
155
- // 5. Hide whole facts. The cost per turn goes last, because seeing what
156
- // each turn costs is half of what the footer is for.
165
+ // 5. Hide whole facts. The cost per turn goes last of them, because
166
+ // seeing what each turn costs is half of what the footer is for.
157
167
  ["reuse", "hidden"], ["cacheSession", "hidden"], ["tokens", "hidden"], ["perTurn", "hidden"],
168
+ // 6. Drop the cause of a cache miss, keeping its cost. It outranks every
169
+ // hidden fact: it shows only on the turn that missed, and says what to
170
+ // do about the cost (an idle gap or a model switch).
171
+ ["latest", "bare"],
158
172
  ],
159
173
  };
160
174
 
@@ -482,39 +496,102 @@ function renderThinkingLabel(theme: any, level: string, full: boolean): string {
482
496
 
483
497
  // ── Session helpers ─────────────────────────────────────────────────────────
484
498
 
499
+ /** A cache miss in the terms of Pi's own miss notice. */
500
+ type CacheMiss = { missedTokens: number; missedCost: number; idleMs: number; modelChanged: boolean };
501
+ type PreviousRequest = { promptTokens: number; modelKey: string; timestamp: number; reportedCache: boolean };
502
+ type ModelLookup = Pick<ExtensionContext["modelRegistry"], "find">;
503
+
504
+ // Mirror pi's own miss detection (detectMiss in dist/core/cache-stats.js, which
505
+ // pi does not export), so the footer reports the numbers of pi's notice.
506
+ function detectCacheMiss(previous: PreviousRequest | undefined, message: AssistantMessage, models: ModelLookup): CacheMiss | null {
507
+ const { input, cacheRead, cacheWrite, cost } = message.usage;
508
+ const promptTokens = input + cacheRead + cacheWrite;
509
+ if (!previous || (cacheRead + cacheWrite === 0 && !previous.reportedCache)) return null;
510
+ const missedTokens = Math.min(previous.promptTokens, promptTokens) - cacheRead;
511
+ if (missedTokens <= CACHE_MISS_NOISE_FLOOR_TOKENS) return null;
512
+ const paidTokens = input + cacheWrite;
513
+ const paidPerToken = paidTokens > 0 ? (cost.input + cost.cacheWrite) / paidTokens : 0;
514
+ const readPerToken = cacheRead > 0
515
+ ? cost.cacheRead / cacheRead
516
+ : (models.find(message.provider, message.model)?.cost.cacheRead ?? 0) / 1_000_000;
517
+ return {
518
+ missedTokens,
519
+ missedCost: missedTokens * Math.max(0, paidPerToken - readPerToken),
520
+ idleMs: Math.max(0, message.timestamp - previous.timestamp),
521
+ modelChanged: `${message.provider}/${message.model}` !== previous.modelKey,
522
+ };
523
+ }
524
+
525
+ /** The latest miss in its three forms. Ranked: what it cost, then why it
526
+ * happened, then how many tokens. Without a cost, the tokens take its place.
527
+ * @example
528
+ * cacheMissForms({ missedTokens: 199_000, missedCost: 0.38, idleMs: 360_000, modelChanged: false })
529
+ * // { full: "latest miss after 6m idle: 199k re-billed $0.38", short: "miss 6m idle $0.38", bare: "miss $0.38" }
530
+ */
531
+ function cacheMissForms(miss: CacheMiss): Required<FactForms> {
532
+ // Pi's notice shows a cost from one cent, rounded to cents, and an idle gap from the TTL, in whole minutes.
533
+ const cost = miss.missedCost >= 0.01 ? `$${miss.missedCost.toFixed(2)}` : null;
534
+ const cause = miss.modelChanged ? "model switch" : miss.idleMs >= CACHE_TTL_MS ? `${Math.round(miss.idleMs / 60_000)}m idle` : null;
535
+ const tokens = formatTokens(miss.missedTokens);
536
+ const words = (...parts: (string | null)[]) => parts.filter(Boolean).join(" ");
537
+ return {
538
+ full: words("latest miss", cause && `after ${cause}:`, `${tokens} re-billed`, cost),
539
+ short: words("miss", cause, cost ?? tokens),
540
+ bare: words("miss", cost ?? tokens),
541
+ };
542
+ }
543
+
485
544
  interface SessionStats {
486
545
  totalCost: number;
487
546
  totalReused: number;
488
547
  totalFresh: number;
489
548
  sessionCacheHitRate: number | null;
490
549
  latestCacheHitRate: number | null;
491
- latestCacheMissTokens: number | null;
550
+ latestCacheMiss: CacheMiss | null;
492
551
  averageCostPerTurn: number;
493
552
  lastContextTokens: number; // input+output+cacheRead+cacheWrite of the last valid turn
494
553
  }
495
554
 
496
- function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
555
+ /** Exported for tests/miss-parity.mjs, which compares the mirrored miss detection with Pi's. */
556
+ export function getSessionStats(branch: readonly SessionEntry[], models: ModelLookup): SessionStats {
497
557
  let turnCount = 0;
498
558
  let totalCost = 0;
559
+ let turnCost = 0;
499
560
  let totalReused = 0;
500
561
  let totalFresh = 0;
501
562
  let lastContextTokens = 0;
502
- let previousPromptTokens: number | null = null;
563
+ let previousRequest: PreviousRequest | undefined;
503
564
  let cacheWasReported = false;
504
565
  let latestCacheHitRate: number | null = null;
505
- let latestCacheMissTokens: number | null = null;
566
+ let latestCacheMiss: CacheMiss | null = null;
506
567
  for (const entry of branch) {
507
568
  if (entry.type === "compaction" || entry.type === "branch_summary") {
508
- previousPromptTokens = null;
569
+ previousRequest = undefined;
509
570
  cacheWasReported = false;
510
571
  continue;
511
572
  }
573
+ // Like Pi's footer, count usage entries (cache warms) in the totals only: they are not turns.
574
+ if (entry.type === "usage") {
575
+ const { input, cacheRead, cacheWrite, cost } = entry.usage;
576
+ totalCost += cost.total;
577
+ totalReused += cacheRead;
578
+ totalFresh += input + cacheWrite;
579
+ // Like pi's miss detection, the next turn's miss and idle gap count from a cache warm.
580
+ const warmPromptTokens = input + cacheRead + cacheWrite;
581
+ if (entry.kind === "cache_warm" && warmPromptTokens > 0) {
582
+ previousRequest = {
583
+ promptTokens: warmPromptTokens, modelKey: `${entry.provider}/${entry.model}`, timestamp: Date.parse(entry.timestamp), reportedCache: true,
584
+ };
585
+ }
586
+ continue;
587
+ }
512
588
  if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
513
589
  const message = entry.message as AssistantMessage;
514
590
  if (message.stopReason === "error" || message.stopReason === "aborted") continue;
515
591
  const { input, output, cacheRead, cacheWrite, cost } = message.usage;
516
592
  const promptTokens = input + cacheRead + cacheWrite;
517
593
  turnCount += 1;
594
+ turnCost += cost.total;
518
595
  totalCost += cost.total;
519
596
  totalReused += cacheRead;
520
597
  totalFresh += input + cacheWrite;
@@ -524,12 +601,11 @@ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
524
601
  const cacheReported = cacheRead + cacheWrite > 0;
525
602
  const cacheKnowledgeAvailable = cacheReported || cacheWasReported;
526
603
  latestCacheHitRate = cacheKnowledgeAvailable ? (cacheRead / promptTokens) * 100 : null;
527
- latestCacheMissTokens = null;
528
- if (previousPromptTokens !== null && cacheKnowledgeAvailable) {
529
- const missedTokens = Math.min(previousPromptTokens, promptTokens) - cacheRead;
530
- latestCacheMissTokens = missedTokens > CACHE_MISS_NOISE_FLOOR_TOKENS ? missedTokens : null;
531
- }
532
- previousPromptTokens = promptTokens;
604
+ latestCacheMiss = detectCacheMiss(previousRequest, message, models);
605
+ previousRequest = {
606
+ promptTokens, modelKey: `${message.provider}/${message.model}`, timestamp: message.timestamp,
607
+ reportedCache: (previousRequest?.reportedCache ?? false) || cacheReported,
608
+ };
533
609
  cacheWasReported ||= cacheReported;
534
610
  }
535
611
  const totalPrompt = totalReused + totalFresh;
@@ -539,8 +615,8 @@ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
539
615
  totalFresh,
540
616
  sessionCacheHitRate: totalPrompt > 0 ? (totalReused / totalPrompt) * 100 : null,
541
617
  latestCacheHitRate,
542
- latestCacheMissTokens,
543
- averageCostPerTurn: turnCount > 0 ? totalCost / turnCount : 0,
618
+ latestCacheMiss,
619
+ averageCostPerTurn: turnCount > 0 ? turnCost / turnCount : 0,
544
620
  lastContextTokens,
545
621
  };
546
622
  }
@@ -619,7 +695,7 @@ export default function (pi: ExtensionAPI) {
619
695
  const model: ExtensionContext["model"] = currentCtx.model;
620
696
  if (snapshot && snapshot.manager === manager && snapshot.sessionId === sessionId && snapshot.leafId === leafId && snapshot.model === model) return snapshot;
621
697
  const branch = manager.getBranch();
622
- const stats = getSessionStats(branch);
698
+ const stats = getSessionStats(branch, currentCtx.modelRegistry);
623
699
  const usage = currentCtx.getContextUsage();
624
700
  // Boundary edits commit after turn_end, which may already have rendered the old projection.
625
701
  const contextChangeId = branch.reduce<string | undefined>((latest, entry) =>
@@ -700,7 +776,7 @@ export default function (pi: ExtensionAPI) {
700
776
  ? paint.ramp(CACHE_STOPS, sessionHit, `${sessionHit.toFixed(1)}% session`)
701
777
  : theme.fg("dim", "no cache yet");
702
778
  const latestHit = stats.latestCacheHitRate;
703
- const missedTokens = stats.latestCacheMissTokens;
779
+ const missForms = stats.latestCacheMiss && cacheMissForms(stats.latestCacheMiss);
704
780
  const footerFacts: Partial<Record<FooterFact, FactForms>> = {
705
781
  branch: gitBranch
706
782
  ? { full: `${paint.token(PLACE_TOKEN, `${BRANCH_GLYPH} ${gitBranch}`)}${dirty}`, bare: `${paint.token(PLACE_TOKEN, gitBranch)}${dirty}` }
@@ -714,10 +790,14 @@ export default function (pi: ExtensionAPI) {
714
790
  cost: { full: cost(formatCost(stats.totalCost)), short: cost(stats.totalCost.toFixed(1)), bare: cost(stats.totalCost.toFixed(0)) },
715
791
  perTurn: { full: paint.quiet(SPEND_TOKEN, `$${formatCost(stats.averageCostPerTurn)}/turn`) },
716
792
  cacheSession: { full: `${label("cache")}${sessionHitText}`, bare: sessionHitText },
717
- latest: missedTokens != null
718
- ? { full: theme.fg("error", `latest miss ${formatTokens(missedTokens)} re-billed`), short: theme.fg("error", `miss ${formatTokens(missedTokens)}`) }
793
+ latest: missForms
794
+ ? { full: theme.fg("error", missForms.full), short: theme.fg("error", missForms.short), bare: theme.fg("error", missForms.bare) }
719
795
  : latestHit != null
720
- ? { full: paint.ramp(CACHE_STOPS, latestHit, `latest ${latestHit.toFixed(1)}%`), short: paint.ramp(CACHE_STOPS, latestHit, `latest ${Math.round(latestHit)}%`) }
796
+ ? {
797
+ full: paint.ramp(CACHE_STOPS, latestHit, `latest ${latestHit.toFixed(1)}%`),
798
+ short: paint.ramp(CACHE_STOPS, latestHit, `latest ${Math.round(latestHit)}%`),
799
+ bare: paint.ramp(CACHE_STOPS, latestHit, `latest ${Math.round(latestHit)}%`),
800
+ }
721
801
  : undefined,
722
802
  reuse: {
723
803
  full: paint.ramp(CACHE_STOPS, sessionHit ?? 0, formatTokens(stats.totalReused)) +
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-custom-footer",
3
- "version": "0.1.9",
3
+ "version": "0.1.11",
4
4
  "description": "Context, cache, cost, and loaded skills at a glance in Pi.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,7 +28,7 @@
28
28
  "LICENSE"
29
29
  ],
30
30
  "scripts": {
31
- "test": "node tests/skills.mjs && node tests/cache.mjs && node tests/layout.mjs && node tests/load.mjs && node --test tests/context.mjs",
31
+ "test": "node tests/skills.mjs && node tests/cache.mjs && node tests/layout.mjs && node tests/load.mjs && node tests/miss-parity.mjs && node --test tests/context.mjs",
32
32
  "check": "tsc --noEmit"
33
33
  },
34
34
  "engines": {