@giladbarnea/pi-custom-footer 0.1.12 → 0.1.13

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 +3 -2
  2. package/index.ts +126 -10
  3. package/package.json +2 -2
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  ---
2
- last_updated: 2026-11-11T22-45
2
+ last_updated: 2026-11-12T09-30
3
3
  ---
4
4
 
5
5
  <div align="center">
@@ -31,10 +31,11 @@ Below the editor, see:
31
31
  - **Context remaining at a glance:** a color-graded gauge and used/window tokens.
32
32
  - **Cost across the conversation:** cumulative cost and average cost per assistant turn.
33
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.
34
+ - **How long the cache stays warm:** `warm for 26m`, live: the footer redraws once a minute. It counts down to the latest of three times: the last request or cache warm plus the model’s cache lifetime; the end of Pi’s own idle warming, when Pi will refresh this context; and a deadline set with pi-keep-cache-warm in this Pi session. Once that time has passed, the fact hides. Pi’s idle warming counts on Pi 1.5.1 and later; earlier versions show last touch plus lifetime. Models without a declared cache lifetime, such as OpenAI and Codex, show nothing.
34
35
  - **Where you are:** Git branch, dirty marker, directory, and other extensions’ status messages.
35
36
  - **Subscription pace:** this week’s burn rate against the target rate, as `burn ━━━━●┊─── 1.07× ≤ target 1.18× · resets in 12h`. The sign turns to `>` when you are over budget, and the dot passes the time marker. A reading more than 30 minutes old adds its age, such as `· 2h old`. The age outlasts the pace bar and goes before the rest of the pace. Optional: shown only when a `quota` cache file exists.
36
37
 
37
- The layout follows your Pi theme. The header and the footer each take the fewest lines they can. To fit, they first drop the pace bar and labels, round readings, remove whitespace, and drop the branch icon. Only then does the footer hide facts: a stale reading's age, the burn rate with its reset time, the reused/new split, the session hit rate, the token counts, the word `target`, and last the cost per turn. The target rate stays down to `≤ 1.18×`. 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. Last, the target rate hides only where it alone would add a line.
38
+ The layout follows your Pi theme. The header and the footer each take the fewest lines they can. To fit, they first drop the pace bar and labels, round readings, remove whitespace, and drop the branch icon. The cache time drops its label (`26m`). Only then does the footer hide facts: a stale reading's age, the burn rate with its reset time, the reused/new split, the session hit rate, the token counts, the word `target`, the cache time, and last the cost per turn. The target rate stays down to `≤ 1.18×`. 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. Last, the target rate hides only where it alone would add a line.
38
39
 
39
40
  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.
40
41
 
package/index.ts CHANGED
@@ -37,8 +37,9 @@ import { readFileSync } from "node:fs";
37
37
  import { homedir } from "node:os";
38
38
  import { join } from "node:path";
39
39
 
40
- import type { AssistantMessage } from "@earendil-works/pi-ai";
41
- import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
40
+ import * as piAi from "@earendil-works/pi-ai";
41
+ import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
42
+ import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type Theme } from "@earendil-works/pi-coding-agent";
42
43
  import { truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui";
43
44
 
44
45
  import {
@@ -70,6 +71,10 @@ const CACHE_TTL_MS = 5 * 60 * 1000;
70
71
  const ANSI_FG_RESET = "\x1b[39m";
71
72
  const QUIET_BLEND = 0.38;
72
73
  const PACE_BAR_CELLS = 9;
74
+ const MINUTE_MS = 60_000;
75
+ // pi-keep-cache-warm's session entries and tool, read only while that extension is loaded.
76
+ const KEEP_CACHE_WARM_ENTRY = "keep-cache-warm";
77
+ const KEEP_CACHE_WARM_TOOL = "keep_cache_warm";
73
78
  // The quota tool refreshes its cache every 5 minutes while in use. A reading older than half an hour has gone stale.
74
79
  const PACE_STALE_AFTER_MS = 30 * 60 * 1000;
75
80
  // The quota tool's own rule (FABLE_SHARE_OF_WEEKLY in its pick.py): Fable use counts at half weight against the shared Claude week.
@@ -146,7 +151,7 @@ type Ladder<Key extends string> = {
146
151
  steps: readonly (readonly [Key | "spacing", Form])[];
147
152
  };
148
153
  type HeaderFact = "model" | "thinking" | "sessionName" | "sessionId";
149
- type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "reuse" | "pace";
154
+ type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "expiry" | "reuse" | "pace";
150
155
 
151
156
  const SPACING = {
152
157
  full: { separator: WIDE_SEPARATOR, joiner: " " },
@@ -170,14 +175,14 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
170
175
  rows: [
171
176
  [["branch"], ["cwd"]],
172
177
  [["context", "tokens"], ["cost", "perTurn"]],
173
- [["cacheSession"], ["latest"], ["reuse"]],
178
+ [["cacheSession"], ["latest"], ["expiry"], ["reuse"]],
174
179
  [["pace"]],
175
180
  ],
176
181
  steps: [
177
182
  // 1. Drop what the values already imply. First the pace bar and the words
178
183
  // "resets in": the bar draws what the two rates say. Then the labels.
179
184
  ["pace", "short"],
180
- ["tokens", "short"], ["context", "bare"], ["cacheSession", "bare"],
185
+ ["tokens", "short"], ["context", "bare"], ["cacheSession", "bare"], ["expiry", "short"],
181
186
  // 2. Shorten the readings: the latest cache figure, then the cost, rounded twice.
182
187
  ["latest", "short"], ["cost", "short"], ["cost", "bare"],
183
188
  // 3. Remove whitespace: the padding inside the cwd pill, then the separators.
@@ -190,11 +195,13 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
190
195
  // Then the burn rate and the reset time: the sign keeps the verdict,
191
196
  // and the target is the number to act on. The word
192
197
  // "target" outlasts the cache and token facts, because it names that
193
- // number once the burn rate is gone. The cost per turn goes last of
194
- // them, because seeing what each turn costs is half of what the footer
195
- // is for. The target rate hides only at the very end, in step 7.
198
+ // number once the burn rate is gone. The time left on the cache
199
+ // outlasts it: it says whether to hurry back before a cold restart.
200
+ // The cost per turn goes last of them, because seeing what each turn
201
+ // costs is half of what the footer is for. The target rate hides only
202
+ // at the very end, in step 7.
196
203
  ["pace", "brief"], ["pace", "bare"],
197
- ["reuse", "hidden"], ["cacheSession", "hidden"], ["tokens", "hidden"], ["pace", "least"], ["perTurn", "hidden"],
204
+ ["reuse", "hidden"], ["cacheSession", "hidden"], ["tokens", "hidden"], ["pace", "least"], ["expiry", "hidden"], ["perTurn", "hidden"],
198
205
  // 6. Drop the cause of a cache miss, keeping its cost. It outranks every
199
206
  // hidden fact: it shows only on the turn that missed, and says what to
200
207
  // do about the cost (an idle gap or a model switch).
@@ -682,6 +689,91 @@ function formatRemaining(milliseconds: number): string {
682
689
  return `${Math.floor(milliseconds / 60_000)}m`;
683
690
  }
684
691
 
692
+ // ── Cache expiry ────────────────────────────────────────────────────────────
693
+ // When the prompt cache is really gone: the latest of three times. The last
694
+ // touch plus the model's cache lifetime. Pi's own idle-warming horizon, when Pi
695
+ // will refresh this context. And an armed pi-keep-cache-warm deadline, when
696
+ // that extension runs in this Pi process. Pi's warming policy comes from pi-ai,
697
+ // which exports it since Pi 1.5.1. Without it, or without idle warming (the
698
+ // default since Pi 1.5.1), the time is last touch plus lifetime.
699
+
700
+ /** Pi's idle cache-warming policy, exported by pi-ai since Pi 1.5.1. */
701
+ type PiWarmingPolicy = {
702
+ evaluateCacheWarming(model: Model<Api>, promptTokens: number, phase: "idle"): { action: "warm" | "stop" };
703
+ getCacheWarmingDelayMs(ttlMs: number): number | undefined;
704
+ getPromptCacheTtlMs(model: Model<Api>): number | undefined;
705
+ CACHE_WARMING_MAX_IDLE_AGE_MS: number;
706
+ };
707
+ const piWarming = piAi as unknown as Partial<PiWarmingPolicy>;
708
+ /** Pi's own lifetime lookup where pi-ai exports it, else the same lookup on the model's `promptCache`. */
709
+ const promptCacheTtlMs = piWarming.getPromptCacheTtlMs ?? ((model: Model<Api>): number | undefined => {
710
+ const seconds = model.promptCache?.[process.env.PI_CACHE_RETENTION === "long" ? "long" : "short"];
711
+ return seconds === undefined ? undefined : seconds * 1000;
712
+ });
713
+
714
+ type KeepCacheWarmData = { kind: "arm"; deadline: string } | { kind: "warm"; provider: string; model: string } | { kind: "stop" };
715
+ type CacheExpiryInputs = {
716
+ model: Model<Api>;
717
+ /** Pi's effective `cacheWarming` mode. */
718
+ warmingMode: string;
719
+ /** When this process loaded pi-keep-cache-warm's tool; null when it is not loaded. Older entries are ignored. */
720
+ keepCacheWarmSince: number | null;
721
+ };
722
+
723
+ /** When the session's prompt cache is really gone, or null when Pi knows no cache lifetime for the model or nothing cached yet.
724
+ * A compaction or branch summary starts over: the next request misses anyway.
725
+ */
726
+ function cacheExpiresAt(branch: readonly SessionEntry[], { model, warmingMode, keepCacheWarmSince }: CacheExpiryInputs): number | null {
727
+ const lifetimeMs = promptCacheTtlMs(model);
728
+ if (lifetimeMs === undefined) return null;
729
+ const isCurrentModel = (provider: string, id: string) => provider === model.provider && id === model.id;
730
+ let lastTouch: number | undefined;
731
+ let lastRequest: { at: number; promptTokens: number } | undefined;
732
+ let keepWarmDeadline: number | undefined;
733
+ for (const entry of branch) {
734
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
735
+ lastTouch = lastRequest = keepWarmDeadline = undefined;
736
+ } else if (entry.type === "message" && entry.message.role === "assistant") {
737
+ const message = entry.message as AssistantMessage;
738
+ if (message.stopReason === "error" || message.stopReason === "aborted") continue;
739
+ const { input, cacheRead, cacheWrite } = message.usage;
740
+ // Pi warms only the last request, and only for the selected model.
741
+ lastRequest = isCurrentModel(message.provider, message.model) ? { at: message.timestamp, promptTokens: input + cacheRead + cacheWrite } : undefined;
742
+ if (lastRequest) lastTouch = message.timestamp;
743
+ } else if (entry.type === "usage" && entry.kind === "cache_warm" && isCurrentModel(entry.provider, entry.model)) {
744
+ lastTouch = Date.parse(entry.timestamp);
745
+ } else if (entry.type === "custom" && entry.customType === KEEP_CACHE_WARM_ENTRY && keepCacheWarmSince !== null && Date.parse(entry.timestamp) >= keepCacheWarmSince) {
746
+ const data = entry.data as KeepCacheWarmData;
747
+ if (data.kind === "arm") keepWarmDeadline = Date.parse(data.deadline);
748
+ if (data.kind === "stop") keepWarmDeadline = undefined;
749
+ if (data.kind === "warm" && isCurrentModel(data.provider, data.model)) lastTouch = Date.parse(entry.timestamp);
750
+ }
751
+ }
752
+ if (lastTouch === undefined) return null;
753
+ return Math.max(lastTouch + lifetimeMs, keepWarmDeadline ?? 0, piIdleHorizon(model, warmingMode, lifetimeMs, lastRequest) ?? 0);
754
+ }
755
+
756
+ /** When Pi's own idle warming lets the cache go: the last refresh inside Pi's idle limit after the last request, plus the lifetime.
757
+ * Null when Pi will not refresh this context: no exported policy, a mode other than "idle", or Pi's cost rule says stop.
758
+ */
759
+ function piIdleHorizon(model: Model<Api>, warmingMode: string, lifetimeMs: number, lastRequest: { at: number; promptTokens: number } | undefined): number | null {
760
+ const { evaluateCacheWarming, getCacheWarmingDelayMs, CACHE_WARMING_MAX_IDLE_AGE_MS } = piWarming;
761
+ if (!lastRequest || warmingMode !== "idle" || !evaluateCacheWarming || !getCacheWarmingDelayMs || CACHE_WARMING_MAX_IDLE_AGE_MS === undefined) return null;
762
+ const delayMs = getCacheWarmingDelayMs(lifetimeMs);
763
+ if (delayMs === undefined || evaluateCacheWarming(model, lastRequest.promptTokens, "idle").action !== "warm") return null;
764
+ return lastRequest.at + Math.floor(CACHE_WARMING_MAX_IDLE_AGE_MS / delayMs) * delayMs + lifetimeMs;
765
+ }
766
+
767
+ /** Time left, in the shortest clear form, rounded up so a live cache never reads 0m.
768
+ * @example
769
+ * [formatTimeLeft(26 * 60_000), formatTimeLeft(30_000), formatTimeLeft(65 * 60_000), formatTimeLeft(120 * 60_000)] // ["26m", "1m", "1h5m", "2h"]
770
+ */
771
+ function formatTimeLeft(milliseconds: number): string {
772
+ const minutes = Math.ceil(milliseconds / MINUTE_MS);
773
+ if (minutes < 60) return `${minutes}m`;
774
+ return `${Math.floor(minutes / 60)}h${minutes % 60 ? `${minutes % 60}m` : ""}`;
775
+ }
776
+
685
777
  interface SessionStats {
686
778
  totalCost: number;
687
779
  totalReused: number;
@@ -797,11 +889,15 @@ interface FooterSnapshot {
797
889
  context: ReturnType<typeof getContextPercent>;
798
890
  session: DisplaySession;
799
891
  pace: Pace | null;
892
+ cacheExpiresAt: number | null;
800
893
  }
801
894
 
802
895
  // ── Extension entry point ───────────────────────────────────────────────────
803
896
 
804
897
  export default function (pi: ExtensionAPI) {
898
+ const loadedAt = Date.now();
899
+ // Redraws the footer once a minute, so the cache's time left stays live without session events.
900
+ let minuteTimer: ReturnType<typeof setInterval> | undefined;
805
901
  let currentCtx: any = null;
806
902
  let tuiRef: any = null;
807
903
  let gitBranch: string | null = null;
@@ -850,6 +946,13 @@ export default function (pi: ExtensionAPI) {
850
946
  context: getContextPercent(currentCtx, stats.lastContextTokens, usage),
851
947
  session: getDisplaySession(currentCtx, currentCtx.cwd || ".", pi),
852
948
  pace: readPace(model, Date.now()),
949
+ // Read Pi's settings and tools only for a model with a known cache lifetime.
950
+ cacheExpiresAt: model && promptCacheTtlMs(model) !== undefined ? cacheExpiresAt(branch, {
951
+ model,
952
+ // Pi's own default for the setting, which changed to "idle" in Pi 1.5.1.
953
+ warmingMode: SettingsManager.inMemory(pi.getSettings()).getCacheWarmingMode(),
954
+ keepCacheWarmSince: pi.getAllTools().some((tool) => tool.name === KEEP_CACHE_WARM_TOOL) ? loadedAt : null,
955
+ }) : null,
853
956
  };
854
957
  return snapshot;
855
958
  }
@@ -896,7 +999,7 @@ export default function (pi: ExtensionAPI) {
896
999
 
897
1000
  function renderBelow(width: number, theme: any): string[] {
898
1001
  if (!currentCtx) return [];
899
- const { stats, context: { pct, window, tokens }, pace } = getSnapshot();
1002
+ const { stats, context: { pct, window, tokens }, pace, cacheExpiresAt: expiresAt } = getSnapshot();
900
1003
  const paint = makePainter(theme);
901
1004
  const label = (text: string) => theme.fg("dim", `${text} `);
902
1005
  const pill = (text: string) => theme.bg("selectedBg", paint.token(PLACE_TOKEN, theme.bold(text)));
@@ -964,6 +1067,14 @@ export default function (pi: ExtensionAPI) {
964
1067
  full: paint.ramp(CACHE_STOPS, sessionHit ?? 0, formatTokens(stats.totalReused)) +
965
1068
  theme.fg("dim", ` reused / ${formatTokens(stats.totalFresh)} new`),
966
1069
  },
1070
+ // Once the time has passed the fact hides: there is nothing left to hurry back for,
1071
+ // and the next request's miss shows what it cost.
1072
+ expiry: expiresAt !== null && expiresAt > Date.now()
1073
+ ? {
1074
+ full: `${label("warm for")}${theme.fg("muted", formatTimeLeft(expiresAt - Date.now()))}`,
1075
+ short: theme.fg("muted", formatTimeLeft(expiresAt - Date.now())),
1076
+ }
1077
+ : undefined,
967
1078
  pace: pace ? paceForms(pace) : undefined,
968
1079
  };
969
1080
  return fitFacts(footerFacts, FOOTER_LADDER, width, theme);
@@ -1016,6 +1127,9 @@ export default function (pi: ExtensionAPI) {
1016
1127
  snapshot = undefined;
1017
1128
  skillsDirty = true;
1018
1129
  thinkingLevel = pi.getThinkingLevel() ?? "off";
1130
+ clearInterval(minuteTimer);
1131
+ minuteTimer = setInterval(requestRender, MINUTE_MS);
1132
+ minuteTimer.unref();
1019
1133
  await refreshGit();
1020
1134
 
1021
1135
  ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
@@ -1047,6 +1161,8 @@ export default function (pi: ExtensionAPI) {
1047
1161
  });
1048
1162
 
1049
1163
  pi.on("session_shutdown", async () => {
1164
+ clearInterval(minuteTimer);
1165
+ minuteTimer = undefined;
1050
1166
  currentCtx = null;
1051
1167
  tuiRef = null;
1052
1168
  gitBranch = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@giladbarnea/pi-custom-footer",
3
- "version": "0.1.12",
3
+ "version": "0.1.13",
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 tests/miss-parity.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 tests/expiry.mjs && node --test tests/context.mjs",
32
32
  "check": "tsc --noEmit"
33
33
  },
34
34
  "engines": {