@giladbarnea/pi-custom-footer 0.1.12 → 0.1.14
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/README.md +5 -4
- package/index.ts +180 -39
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
---
|
|
2
|
-
last_updated: 2026-11-
|
|
2
|
+
last_updated: 2026-11-14T15-30
|
|
3
3
|
---
|
|
4
4
|
|
|
5
5
|
<div align="center">
|
|
@@ -30,17 +30,18 @@ Below the editor, see:
|
|
|
30
30
|
|
|
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
|
-
- **Cache behavior:** session hit rate,
|
|
33
|
+
- **Cache behavior:** session hit rate, the last message as `hit 100%` or `miss 45%`, and reused/new token totals. A hit means more than 90% of the prompt was read from the cache. Like Pi’s own notice, a miss that re-billed cached tokens 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
|
|
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`). A hit or miss drops its percentage. Only then does the footer hide facts: the `sub` mark of a subscription, a stale reading's age, the burn rate with its reset time, the reused/new split, the last message's plain `hit` or `miss`, the token counts, the session hit rate, 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
|
|
|
41
42
|
**Resize without rescanning the conversation.** The header and footer share cached values. Session changes refresh them, including forks and compaction.
|
|
42
43
|
|
|
43
|
-
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.
|
|
44
|
+
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. Numbers show two decimal places below 10, one from 10, and none from 100.
|
|
44
45
|
|
|
45
46
|
The pace comes from `~/.cache/quota/provider-usage.json` (or under `XDG_CACHE_HOME`), which the author’s `quota` tool writes. That tool is not public yet, and without the file the footer shows no pace. The reading is for the pool of the session’s model: Claude, Fable or Codex. The footer only reads that file. It never runs `quota` and never fetches. Burn and target each take a color from `quota`’s heat map: green near 1.0×, cool where allowance goes unused, amber then red where it runs out early. A Fable session shows Fable’s target capped by the room left in the shared Claude week.
|
|
46
47
|
|
package/index.ts
CHANGED
|
@@ -27,8 +27,9 @@
|
|
|
27
27
|
*
|
|
28
28
|
* Known differences from Pi's cache-miss notice, reviewed November 11, 2026,
|
|
29
29
|
* against Pi 1.4.0 and 1.5.2:
|
|
30
|
-
* - The footer shows
|
|
31
|
-
*
|
|
30
|
+
* - The footer shows a miss above 1,024 tokens when at most 90% of the
|
|
31
|
+
* prompt was read from the cache. Pi's notice hides a miss under 20k tokens
|
|
32
|
+
* that also costs under $0.10.
|
|
32
33
|
* - Errored and aborted turns are skipped, as elsewhere in the footer. Pi's
|
|
33
34
|
* scan includes them.
|
|
34
35
|
* - The footer scans the current branch. Pi scans every session entry.
|
|
@@ -37,8 +38,9 @@ import { readFileSync } from "node:fs";
|
|
|
37
38
|
import { homedir } from "node:os";
|
|
38
39
|
import { join } from "node:path";
|
|
39
40
|
|
|
40
|
-
import
|
|
41
|
-
import type {
|
|
41
|
+
import * as piAi from "@earendil-works/pi-ai";
|
|
42
|
+
import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
|
|
43
|
+
import { SettingsManager, type ExtensionAPI, type ExtensionContext, type SessionEntry, type Theme } from "@earendil-works/pi-coding-agent";
|
|
42
44
|
import { truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui";
|
|
43
45
|
|
|
44
46
|
import {
|
|
@@ -63,6 +65,8 @@ const BRANCH_GLYPH = "";
|
|
|
63
65
|
const CONTEXT_GAUGE_SYMBOLS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
|
|
64
66
|
const CONTEXT_GAUGE_STEP_COUNT = CONTEXT_GAUGE_SYMBOLS.length;
|
|
65
67
|
const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
68
|
+
// The last message counts as a cache hit when more than this share of its prompt was read from the cache.
|
|
69
|
+
const CACHE_HIT_ABOVE_PERCENT = 90;
|
|
66
70
|
// Pi's prompt-cache TTL: a miss after a longer idle gap names the gap as its cause.
|
|
67
71
|
const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
68
72
|
// Match Theme.fg, which resets the foreground only. A full reset would punch a
|
|
@@ -70,6 +74,10 @@ const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
|
70
74
|
const ANSI_FG_RESET = "\x1b[39m";
|
|
71
75
|
const QUIET_BLEND = 0.38;
|
|
72
76
|
const PACE_BAR_CELLS = 9;
|
|
77
|
+
const MINUTE_MS = 60_000;
|
|
78
|
+
// pi-keep-cache-warm's session entries and tool, read only while that extension is loaded.
|
|
79
|
+
const KEEP_CACHE_WARM_ENTRY = "keep-cache-warm";
|
|
80
|
+
const KEEP_CACHE_WARM_TOOL = "keep_cache_warm";
|
|
73
81
|
// The quota tool refreshes its cache every 5 minutes while in use. A reading older than half an hour has gone stale.
|
|
74
82
|
const PACE_STALE_AFTER_MS = 30 * 60 * 1000;
|
|
75
83
|
// 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 +154,7 @@ type Ladder<Key extends string> = {
|
|
|
146
154
|
steps: readonly (readonly [Key | "spacing", Form])[];
|
|
147
155
|
};
|
|
148
156
|
type HeaderFact = "model" | "thinking" | "sessionName" | "sessionId";
|
|
149
|
-
type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "reuse" | "pace";
|
|
157
|
+
type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "expiry" | "reuse" | "pace";
|
|
150
158
|
|
|
151
159
|
const SPACING = {
|
|
152
160
|
full: { separator: WIDE_SEPARATOR, joiner: " " },
|
|
@@ -170,34 +178,46 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
|
|
|
170
178
|
rows: [
|
|
171
179
|
[["branch"], ["cwd"]],
|
|
172
180
|
[["context", "tokens"], ["cost", "perTurn"]],
|
|
173
|
-
[["cacheSession"], ["latest"], ["reuse"]],
|
|
181
|
+
[["cacheSession"], ["latest"], ["expiry"], ["reuse"]],
|
|
174
182
|
[["pace"]],
|
|
175
183
|
],
|
|
176
184
|
steps: [
|
|
177
185
|
// 1. Drop what the values already imply. First the pace bar and the words
|
|
178
186
|
// "resets in": the bar draws what the two rates say. Then the labels.
|
|
179
187
|
["pace", "short"],
|
|
180
|
-
["tokens", "short"], ["context", "bare"], ["cacheSession", "bare"],
|
|
181
|
-
// 2. Shorten the readings: the
|
|
188
|
+
["tokens", "short"], ["context", "bare"], ["cacheSession", "bare"], ["expiry", "short"],
|
|
189
|
+
// 2. Shorten the readings: the last message's cache share (for a
|
|
190
|
+
// detected miss, its re-billed tokens), then the cost, rounded twice.
|
|
182
191
|
["latest", "short"], ["cost", "short"], ["cost", "bare"],
|
|
183
192
|
// 3. Remove whitespace: the padding inside the cwd pill, then the separators.
|
|
184
193
|
["cwd", "short"], ["spacing", "bare"],
|
|
185
194
|
// 4. Drop the branch icon.
|
|
186
195
|
["branch", "bare"],
|
|
187
|
-
// 5. Hide whole facts. First
|
|
188
|
-
//
|
|
189
|
-
//
|
|
190
|
-
//
|
|
191
|
-
//
|
|
196
|
+
// 5. Hide whole facts. First the "sub" mark: that a model runs on your
|
|
197
|
+
// subscription is rarely news, so it is the least important fact, but
|
|
198
|
+
// it is still data and outlasts all the formatting above. Then a stale
|
|
199
|
+
// quota reading's age: it outlasts the bar, the labels and the
|
|
200
|
+
// whitespace, so a laptop still sees that the rates are old, and it
|
|
201
|
+
// goes before every other part of the pace left. Then the burn rate
|
|
202
|
+
// and the reset time: the sign keeps the verdict, and the target is
|
|
203
|
+
// the number to act on. The last message's "hit" or "miss" hides
|
|
204
|
+
// before the session hit rate: the session rate is the cost signal,
|
|
205
|
+
// and the last message only hints at it. The session rate also
|
|
206
|
+
// outlasts the token counts, which the context gauge already sums
|
|
207
|
+
// up, so a phone keeps one cache fact. The word
|
|
192
208
|
// "target" outlasts the cache and token facts, because it names that
|
|
193
|
-
// number once the burn rate is gone. The
|
|
194
|
-
//
|
|
195
|
-
//
|
|
209
|
+
// number once the burn rate is gone. The time left on the cache
|
|
210
|
+
// outlasts it: it says whether to hurry back before a cold restart.
|
|
211
|
+
// The cost per turn goes last of them, because seeing what each turn
|
|
212
|
+
// costs is half of what the footer is for. The target rate hides only
|
|
213
|
+
// at the very end, in step 7.
|
|
214
|
+
["cost", "least"],
|
|
196
215
|
["pace", "brief"], ["pace", "bare"],
|
|
197
|
-
["reuse", "hidden"], ["
|
|
198
|
-
// 6. Drop the cause of a cache miss, keeping its cost.
|
|
199
|
-
//
|
|
200
|
-
//
|
|
216
|
+
["reuse", "hidden"], ["latest", "brief"], ["tokens", "hidden"], ["cacheSession", "hidden"], ["pace", "least"], ["expiry", "hidden"], ["perTurn", "hidden"],
|
|
217
|
+
// 6. Drop the cause of a detected cache miss, keeping its cost.
|
|
218
|
+
// Unlike a plain "hit" or "miss", it outranks every hidden fact: it
|
|
219
|
+
// shows only on the turn that missed, and says what to do about the
|
|
220
|
+
// cost (an idle gap or a model switch).
|
|
201
221
|
["latest", "bare"],
|
|
202
222
|
// 7. Last, hide the target rate. Because the footer takes the fullest
|
|
203
223
|
// state with the fewest lines, this fires only where the target alone
|
|
@@ -330,8 +350,14 @@ function formatTokens(n: number): string {
|
|
|
330
350
|
return String(n);
|
|
331
351
|
}
|
|
332
352
|
|
|
333
|
-
|
|
334
|
-
|
|
353
|
+
/** A number with as many decimal places as its size earns: two below 10, one below 100, none from 100, and never more than maxPlaces.
|
|
354
|
+
* @example
|
|
355
|
+
* [formatDecimal(0.099), formatDecimal(9.996), formatDecimal(12.34), formatDecimal(99.96), formatDecimal(123.4), formatDecimal(5.25, 1)]
|
|
356
|
+
* // ["0.10", "10.0", "12.3", "100", "123", "5.3"]
|
|
357
|
+
*/
|
|
358
|
+
function formatDecimal(value: number, maxPlaces = 2): string {
|
|
359
|
+
const places = [2, 1].find((candidate) => candidate <= maxPlaces && Number(value.toFixed(candidate)) < 10 ** (3 - candidate)) ?? 0;
|
|
360
|
+
return value.toFixed(places);
|
|
335
361
|
}
|
|
336
362
|
|
|
337
363
|
function currentDirectoryName(cwd: string): string {
|
|
@@ -556,20 +582,20 @@ function detectCacheMiss(previous: PreviousRequest | undefined, message: Assista
|
|
|
556
582
|
};
|
|
557
583
|
}
|
|
558
584
|
|
|
559
|
-
/** The
|
|
585
|
+
/** The last message's miss in its three forms. Ranked: what it cost, then why it
|
|
560
586
|
* happened, then how many tokens. Without a cost, the tokens take its place.
|
|
561
587
|
* @example
|
|
562
588
|
* cacheMissForms({ missedTokens: 199_000, missedCost: 0.38, idleMs: 360_000, modelChanged: false })
|
|
563
|
-
* // { full: "
|
|
589
|
+
* // { full: "miss after 6m idle: 199k re-billed $0.38", short: "miss 6m idle $0.38", bare: "miss $0.38" }
|
|
564
590
|
*/
|
|
565
591
|
function cacheMissForms(miss: CacheMiss): Record<"full" | "short" | "bare", string> {
|
|
566
592
|
// Pi's notice shows a cost from one cent, rounded to cents, and an idle gap from the TTL, in whole minutes.
|
|
567
|
-
const cost = miss.missedCost >= 0.01 ? `$${miss.missedCost
|
|
593
|
+
const cost = miss.missedCost >= 0.01 ? `$${formatDecimal(miss.missedCost)}` : null;
|
|
568
594
|
const cause = miss.modelChanged ? "model switch" : miss.idleMs >= CACHE_TTL_MS ? `${Math.round(miss.idleMs / 60_000)}m idle` : null;
|
|
569
595
|
const tokens = formatTokens(miss.missedTokens);
|
|
570
596
|
const words = (...parts: (string | null)[]) => parts.filter(Boolean).join(" ");
|
|
571
597
|
return {
|
|
572
|
-
full: words("
|
|
598
|
+
full: words("miss", cause && `after ${cause}:`, `${tokens} re-billed`, cost),
|
|
573
599
|
short: words("miss", cause, cost ?? tokens),
|
|
574
600
|
bare: words("miss", cost ?? tokens),
|
|
575
601
|
};
|
|
@@ -682,6 +708,91 @@ function formatRemaining(milliseconds: number): string {
|
|
|
682
708
|
return `${Math.floor(milliseconds / 60_000)}m`;
|
|
683
709
|
}
|
|
684
710
|
|
|
711
|
+
// ── Cache expiry ────────────────────────────────────────────────────────────
|
|
712
|
+
// When the prompt cache is really gone: the latest of three times. The last
|
|
713
|
+
// touch plus the model's cache lifetime. Pi's own idle-warming horizon, when Pi
|
|
714
|
+
// will refresh this context. And an armed pi-keep-cache-warm deadline, when
|
|
715
|
+
// that extension runs in this Pi process. Pi's warming policy comes from pi-ai,
|
|
716
|
+
// which exports it since Pi 1.5.1. Without it, or without idle warming (the
|
|
717
|
+
// default since Pi 1.5.1), the time is last touch plus lifetime.
|
|
718
|
+
|
|
719
|
+
/** Pi's idle cache-warming policy, exported by pi-ai since Pi 1.5.1. */
|
|
720
|
+
type PiWarmingPolicy = {
|
|
721
|
+
evaluateCacheWarming(model: Model<Api>, promptTokens: number, phase: "idle"): { action: "warm" | "stop" };
|
|
722
|
+
getCacheWarmingDelayMs(ttlMs: number): number | undefined;
|
|
723
|
+
getPromptCacheTtlMs(model: Model<Api>): number | undefined;
|
|
724
|
+
CACHE_WARMING_MAX_IDLE_AGE_MS: number;
|
|
725
|
+
};
|
|
726
|
+
const piWarming = piAi as unknown as Partial<PiWarmingPolicy>;
|
|
727
|
+
/** Pi's own lifetime lookup where pi-ai exports it, else the same lookup on the model's `promptCache`. */
|
|
728
|
+
const promptCacheTtlMs = piWarming.getPromptCacheTtlMs ?? ((model: Model<Api>): number | undefined => {
|
|
729
|
+
const seconds = model.promptCache?.[process.env.PI_CACHE_RETENTION === "long" ? "long" : "short"];
|
|
730
|
+
return seconds === undefined ? undefined : seconds * 1000;
|
|
731
|
+
});
|
|
732
|
+
|
|
733
|
+
type KeepCacheWarmData = { kind: "arm"; deadline: string } | { kind: "warm"; provider: string; model: string } | { kind: "stop" };
|
|
734
|
+
type CacheExpiryInputs = {
|
|
735
|
+
model: Model<Api>;
|
|
736
|
+
/** Pi's effective `cacheWarming` mode. */
|
|
737
|
+
warmingMode: string;
|
|
738
|
+
/** When this process loaded pi-keep-cache-warm's tool; null when it is not loaded. Older entries are ignored. */
|
|
739
|
+
keepCacheWarmSince: number | null;
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
/** When the session's prompt cache is really gone, or null when Pi knows no cache lifetime for the model or nothing cached yet.
|
|
743
|
+
* A compaction or branch summary starts over: the next request misses anyway.
|
|
744
|
+
*/
|
|
745
|
+
function cacheExpiresAt(branch: readonly SessionEntry[], { model, warmingMode, keepCacheWarmSince }: CacheExpiryInputs): number | null {
|
|
746
|
+
const lifetimeMs = promptCacheTtlMs(model);
|
|
747
|
+
if (lifetimeMs === undefined) return null;
|
|
748
|
+
const isCurrentModel = (provider: string, id: string) => provider === model.provider && id === model.id;
|
|
749
|
+
let lastTouch: number | undefined;
|
|
750
|
+
let lastRequest: { at: number; promptTokens: number } | undefined;
|
|
751
|
+
let keepWarmDeadline: number | undefined;
|
|
752
|
+
for (const entry of branch) {
|
|
753
|
+
if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
754
|
+
lastTouch = lastRequest = keepWarmDeadline = undefined;
|
|
755
|
+
} else if (entry.type === "message" && entry.message.role === "assistant") {
|
|
756
|
+
const message = entry.message as AssistantMessage;
|
|
757
|
+
if (message.stopReason === "error" || message.stopReason === "aborted") continue;
|
|
758
|
+
const { input, cacheRead, cacheWrite } = message.usage;
|
|
759
|
+
// Pi warms only the last request, and only for the selected model.
|
|
760
|
+
lastRequest = isCurrentModel(message.provider, message.model) ? { at: message.timestamp, promptTokens: input + cacheRead + cacheWrite } : undefined;
|
|
761
|
+
if (lastRequest) lastTouch = message.timestamp;
|
|
762
|
+
} else if (entry.type === "usage" && entry.kind === "cache_warm" && isCurrentModel(entry.provider, entry.model)) {
|
|
763
|
+
lastTouch = Date.parse(entry.timestamp);
|
|
764
|
+
} else if (entry.type === "custom" && entry.customType === KEEP_CACHE_WARM_ENTRY && keepCacheWarmSince !== null && Date.parse(entry.timestamp) >= keepCacheWarmSince) {
|
|
765
|
+
const data = entry.data as KeepCacheWarmData;
|
|
766
|
+
if (data.kind === "arm") keepWarmDeadline = Date.parse(data.deadline);
|
|
767
|
+
if (data.kind === "stop") keepWarmDeadline = undefined;
|
|
768
|
+
if (data.kind === "warm" && isCurrentModel(data.provider, data.model)) lastTouch = Date.parse(entry.timestamp);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
if (lastTouch === undefined) return null;
|
|
772
|
+
return Math.max(lastTouch + lifetimeMs, keepWarmDeadline ?? 0, piIdleHorizon(model, warmingMode, lifetimeMs, lastRequest) ?? 0);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** 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.
|
|
776
|
+
* Null when Pi will not refresh this context: no exported policy, a mode other than "idle", or Pi's cost rule says stop.
|
|
777
|
+
*/
|
|
778
|
+
function piIdleHorizon(model: Model<Api>, warmingMode: string, lifetimeMs: number, lastRequest: { at: number; promptTokens: number } | undefined): number | null {
|
|
779
|
+
const { evaluateCacheWarming, getCacheWarmingDelayMs, CACHE_WARMING_MAX_IDLE_AGE_MS } = piWarming;
|
|
780
|
+
if (!lastRequest || warmingMode !== "idle" || !evaluateCacheWarming || !getCacheWarmingDelayMs || CACHE_WARMING_MAX_IDLE_AGE_MS === undefined) return null;
|
|
781
|
+
const delayMs = getCacheWarmingDelayMs(lifetimeMs);
|
|
782
|
+
if (delayMs === undefined || evaluateCacheWarming(model, lastRequest.promptTokens, "idle").action !== "warm") return null;
|
|
783
|
+
return lastRequest.at + Math.floor(CACHE_WARMING_MAX_IDLE_AGE_MS / delayMs) * delayMs + lifetimeMs;
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** Time left, in the shortest clear form, rounded up so a live cache never reads 0m.
|
|
787
|
+
* @example
|
|
788
|
+
* [formatTimeLeft(26 * 60_000), formatTimeLeft(30_000), formatTimeLeft(65 * 60_000), formatTimeLeft(120 * 60_000)] // ["26m", "1m", "1h5m", "2h"]
|
|
789
|
+
*/
|
|
790
|
+
function formatTimeLeft(milliseconds: number): string {
|
|
791
|
+
const minutes = Math.ceil(milliseconds / MINUTE_MS);
|
|
792
|
+
if (minutes < 60) return `${minutes}m`;
|
|
793
|
+
return `${Math.floor(minutes / 60)}h${minutes % 60 ? `${minutes % 60}m` : ""}`;
|
|
794
|
+
}
|
|
795
|
+
|
|
685
796
|
interface SessionStats {
|
|
686
797
|
totalCost: number;
|
|
687
798
|
totalReused: number;
|
|
@@ -797,11 +908,15 @@ interface FooterSnapshot {
|
|
|
797
908
|
context: ReturnType<typeof getContextPercent>;
|
|
798
909
|
session: DisplaySession;
|
|
799
910
|
pace: Pace | null;
|
|
911
|
+
cacheExpiresAt: number | null;
|
|
800
912
|
}
|
|
801
913
|
|
|
802
914
|
// ── Extension entry point ───────────────────────────────────────────────────
|
|
803
915
|
|
|
804
916
|
export default function (pi: ExtensionAPI) {
|
|
917
|
+
const loadedAt = Date.now();
|
|
918
|
+
// Redraws the footer once a minute, so the cache's time left stays live without session events.
|
|
919
|
+
let minuteTimer: ReturnType<typeof setInterval> | undefined;
|
|
805
920
|
let currentCtx: any = null;
|
|
806
921
|
let tuiRef: any = null;
|
|
807
922
|
let gitBranch: string | null = null;
|
|
@@ -850,6 +965,13 @@ export default function (pi: ExtensionAPI) {
|
|
|
850
965
|
context: getContextPercent(currentCtx, stats.lastContextTokens, usage),
|
|
851
966
|
session: getDisplaySession(currentCtx, currentCtx.cwd || ".", pi),
|
|
852
967
|
pace: readPace(model, Date.now()),
|
|
968
|
+
// Read Pi's settings and tools only for a model with a known cache lifetime.
|
|
969
|
+
cacheExpiresAt: model && promptCacheTtlMs(model) !== undefined ? cacheExpiresAt(branch, {
|
|
970
|
+
model,
|
|
971
|
+
// Pi's own default for the setting, which changed to "idle" in Pi 1.5.1.
|
|
972
|
+
warmingMode: SettingsManager.inMemory(pi.getSettings()).getCacheWarmingMode(),
|
|
973
|
+
keepCacheWarmSince: pi.getAllTools().some((tool) => tool.name === KEEP_CACHE_WARM_TOOL) ? loadedAt : null,
|
|
974
|
+
}) : null,
|
|
853
975
|
};
|
|
854
976
|
return snapshot;
|
|
855
977
|
}
|
|
@@ -896,7 +1018,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
896
1018
|
|
|
897
1019
|
function renderBelow(width: number, theme: any): string[] {
|
|
898
1020
|
if (!currentCtx) return [];
|
|
899
|
-
const { stats, context: { pct, window, tokens }, pace } = getSnapshot();
|
|
1021
|
+
const { stats, context: { pct, window, tokens }, pace, cacheExpiresAt: expiresAt } = getSnapshot();
|
|
900
1022
|
const paint = makePainter(theme);
|
|
901
1023
|
const label = (text: string) => theme.fg("dim", `${text} `);
|
|
902
1024
|
const pill = (text: string) => theme.bg("selectedBg", paint.token(PLACE_TOKEN, theme.bold(text)));
|
|
@@ -904,27 +1026,31 @@ export default function (pi: ExtensionAPI) {
|
|
|
904
1026
|
// A dirty worktree is a property of the place, not a cost, so it stays in
|
|
905
1027
|
// the place family and leaves `warning` meaning spend alone.
|
|
906
1028
|
const dirty = gitDirty ? paint.token(PLACE_TOKEN, "*") : "";
|
|
907
|
-
const gauge = paint.ramp(CONTEXT_STOPS, pct, `${ctxGauge(pct)}
|
|
1029
|
+
const gauge = paint.ramp(CONTEXT_STOPS, pct, `${ctxGauge(pct)}${Math.round(pct)}%`);
|
|
908
1030
|
// Colour the figure that moves and leave its reference quiet, so the eye
|
|
909
1031
|
// lands on the reading rather than on the window size beside it.
|
|
910
1032
|
const usedTokens = paint.ramp(CONTEXT_STOPS, pct, formatTokens(tokens));
|
|
911
1033
|
const usingSubscription = currentCtx.model
|
|
912
1034
|
? currentCtx.modelRegistry?.isUsingOAuth?.(currentCtx.model)
|
|
913
1035
|
: false;
|
|
914
|
-
const cost = (
|
|
1036
|
+
const cost = (maxPlaces: number) => paint.token(SPEND_TOKEN, `$${formatDecimal(stats.totalCost, maxPlaces)}`);
|
|
1037
|
+
const sub = usingSubscription ? theme.fg("muted", " sub") : "";
|
|
915
1038
|
// A hit rate is a measurement, so it rides the ramp. The old cliff at 80%
|
|
916
1039
|
// made 79% and 20% look identical and threw the reading away.
|
|
917
1040
|
const sessionHit = stats.sessionCacheHitRate;
|
|
918
1041
|
const sessionHitText = sessionHit != null
|
|
919
|
-
? paint.ramp(CACHE_STOPS, sessionHit, `${sessionHit
|
|
1042
|
+
? paint.ramp(CACHE_STOPS, sessionHit, `${formatDecimal(sessionHit, 1)}% session`)
|
|
920
1043
|
: theme.fg("dim", "no cache yet");
|
|
1044
|
+
// The last message is a hit or a miss by its cache share alone. A miss that pi's accounting
|
|
1045
|
+
// also detects shows its cost and cause instead of the share.
|
|
921
1046
|
const latestHit = stats.latestCacheHitRate;
|
|
922
|
-
const
|
|
1047
|
+
const isHit = latestHit != null && latestHit > CACHE_HIT_ABOVE_PERCENT;
|
|
1048
|
+
const missForms = !isHit && stats.latestCacheMiss ? cacheMissForms(stats.latestCacheMiss) : null;
|
|
923
1049
|
const paceForms = (reading: Pace): FactForms => {
|
|
924
1050
|
const dim = (text: string) => theme.fg("dim", text);
|
|
925
1051
|
const burnHeat = (text: string) => paint.ramp(PACE_STOPS, pacePosition(reading.burn, false), text);
|
|
926
|
-
const burn = burnHeat(`${reading.burn
|
|
927
|
-
const target = paint.ramp(PACE_STOPS, pacePosition(reading.target, true), `${reading.target
|
|
1052
|
+
const burn = burnHeat(`${formatDecimal(reading.burn)}×`);
|
|
1053
|
+
const target = paint.ramp(PACE_STOPS, pacePosition(reading.target, true), `${formatDecimal(reading.target)}×`);
|
|
928
1054
|
// The sign carries the verdict, and colour repeats it.
|
|
929
1055
|
const sign = reading.burn > reading.target ? theme.fg("error", ">") : dim("≤");
|
|
930
1056
|
const resets = formatRemaining(reading.resetsInMs);
|
|
@@ -948,22 +1074,32 @@ export default function (pi: ExtensionAPI) {
|
|
|
948
1074
|
full: `${usedTokens}${theme.fg("dim", ` / ${formatTokens(window)} tokens`)}`,
|
|
949
1075
|
short: `${usedTokens}${theme.fg("dim", ` / ${formatTokens(window)}`)}`,
|
|
950
1076
|
},
|
|
951
|
-
cost: { full: cost(
|
|
952
|
-
perTurn: { full: paint.quiet(SPEND_TOKEN, `$${
|
|
1077
|
+
cost: { full: `${cost(2)}${sub}`, short: `${cost(1)}${sub}`, bare: `${cost(0)}${sub}`, least: cost(0) },
|
|
1078
|
+
perTurn: { full: paint.quiet(SPEND_TOKEN, `$${formatDecimal(stats.averageCostPerTurn)}/turn`) },
|
|
953
1079
|
cacheSession: { full: `${label("cache")}${sessionHitText}`, bare: sessionHitText },
|
|
1080
|
+
// "brief" is the step where a plain hit or miss hides; a detected miss stays to the end.
|
|
954
1081
|
latest: missForms
|
|
955
|
-
? { full: theme.fg("error", missForms.full), short: theme.fg("error", missForms.short), bare: theme.fg("error", missForms.bare) }
|
|
1082
|
+
? { full: theme.fg("error", missForms.full), short: theme.fg("error", missForms.short), brief: theme.fg("error", missForms.short), bare: theme.fg("error", missForms.bare) }
|
|
956
1083
|
: latestHit != null
|
|
957
1084
|
? {
|
|
958
|
-
full: paint.ramp(CACHE_STOPS, latestHit,
|
|
959
|
-
short: paint.ramp(CACHE_STOPS, latestHit,
|
|
960
|
-
|
|
1085
|
+
full: paint.ramp(CACHE_STOPS, latestHit, `${isHit ? "hit" : "miss"} ${Math.round(latestHit)}%`),
|
|
1086
|
+
short: paint.ramp(CACHE_STOPS, latestHit, isHit ? "hit" : "miss"),
|
|
1087
|
+
brief: "",
|
|
1088
|
+
bare: "",
|
|
961
1089
|
}
|
|
962
1090
|
: undefined,
|
|
963
1091
|
reuse: {
|
|
964
1092
|
full: paint.ramp(CACHE_STOPS, sessionHit ?? 0, formatTokens(stats.totalReused)) +
|
|
965
1093
|
theme.fg("dim", ` reused / ${formatTokens(stats.totalFresh)} new`),
|
|
966
1094
|
},
|
|
1095
|
+
// Once the time has passed the fact hides: there is nothing left to hurry back for,
|
|
1096
|
+
// and the next request's miss shows what it cost.
|
|
1097
|
+
expiry: expiresAt !== null && expiresAt > Date.now()
|
|
1098
|
+
? {
|
|
1099
|
+
full: `${label("warm for")}${theme.fg("muted", formatTimeLeft(expiresAt - Date.now()))}`,
|
|
1100
|
+
short: theme.fg("muted", formatTimeLeft(expiresAt - Date.now())),
|
|
1101
|
+
}
|
|
1102
|
+
: undefined,
|
|
967
1103
|
pace: pace ? paceForms(pace) : undefined,
|
|
968
1104
|
};
|
|
969
1105
|
return fitFacts(footerFacts, FOOTER_LADDER, width, theme);
|
|
@@ -1016,6 +1152,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1016
1152
|
snapshot = undefined;
|
|
1017
1153
|
skillsDirty = true;
|
|
1018
1154
|
thinkingLevel = pi.getThinkingLevel() ?? "off";
|
|
1155
|
+
clearInterval(minuteTimer);
|
|
1156
|
+
minuteTimer = setInterval(requestRender, MINUTE_MS);
|
|
1157
|
+
minuteTimer.unref();
|
|
1019
1158
|
await refreshGit();
|
|
1020
1159
|
|
|
1021
1160
|
ctx.ui.setFooter((tui: any, theme: any, footerData: any) => {
|
|
@@ -1047,6 +1186,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1047
1186
|
});
|
|
1048
1187
|
|
|
1049
1188
|
pi.on("session_shutdown", async () => {
|
|
1189
|
+
clearInterval(minuteTimer);
|
|
1190
|
+
minuteTimer = undefined;
|
|
1050
1191
|
currentCtx = null;
|
|
1051
1192
|
tuiRef = null;
|
|
1052
1193
|
gitBranch = null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@giladbarnea/pi-custom-footer",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.14",
|
|
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": {
|