@giladbarnea/pi-custom-footer 0.1.10 → 0.1.12
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 +9 -4
- package/index.ts +258 -26
- 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-11T22-45
|
|
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,19 @@ 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
|
|
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.
|
|
35
|
+
- **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.
|
|
33
36
|
|
|
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.
|
|
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.
|
|
35
38
|
|
|
36
39
|
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
40
|
|
|
38
41
|
**Resize without rescanning the conversation.** The header and footer share cached values. Session changes refresh them, including forks and compaction.
|
|
39
42
|
|
|
40
|
-
Skill age measures context-token growth since the first response after a skill load.
|
|
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
|
+
|
|
45
|
+
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.
|
|
41
46
|
|
|
42
47
|
## Development
|
|
43
48
|
|
package/index.ts
CHANGED
|
@@ -24,7 +24,19 @@
|
|
|
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
|
*/
|
|
36
|
+
import { readFileSync } from "node:fs";
|
|
37
|
+
import { homedir } from "node:os";
|
|
38
|
+
import { join } from "node:path";
|
|
39
|
+
|
|
28
40
|
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
29
41
|
import type { ExtensionAPI, ExtensionContext, SessionEntry, Theme } from "@earendil-works/pi-coding-agent";
|
|
30
42
|
import { truncateToWidth, visibleWidth, type TUI } from "@earendil-works/pi-tui";
|
|
@@ -51,10 +63,17 @@ const BRANCH_GLYPH = "";
|
|
|
51
63
|
const CONTEXT_GAUGE_SYMBOLS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
|
|
52
64
|
const CONTEXT_GAUGE_STEP_COUNT = CONTEXT_GAUGE_SYMBOLS.length;
|
|
53
65
|
const CACHE_MISS_NOISE_FLOOR_TOKENS = 1_024;
|
|
66
|
+
// Pi's prompt-cache TTL: a miss after a longer idle gap names the gap as its cause.
|
|
67
|
+
const CACHE_TTL_MS = 5 * 60 * 1000;
|
|
54
68
|
// Match Theme.fg, which resets the foreground only. A full reset would punch a
|
|
55
69
|
// hole in any background the caller has already opened, such as the cwd pill.
|
|
56
70
|
const ANSI_FG_RESET = "\x1b[39m";
|
|
57
71
|
const QUIET_BLEND = 0.38;
|
|
72
|
+
const PACE_BAR_CELLS = 9;
|
|
73
|
+
// The quota tool refreshes its cache every 5 minutes while in use. A reading older than half an hour has gone stale.
|
|
74
|
+
const PACE_STALE_AFTER_MS = 30 * 60 * 1000;
|
|
75
|
+
// 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.
|
|
76
|
+
const FABLE_SHARE_OF_WEEKLY = 0.5;
|
|
58
77
|
|
|
59
78
|
// ── Colour rules ────────────────────────────────────────────────────────────
|
|
60
79
|
// Hue means one of two things here and nothing else.
|
|
@@ -62,7 +81,9 @@ const QUIET_BLEND = 0.38;
|
|
|
62
81
|
// 1. A RAMP is a measurement. Its colour moves with the value, and it is loud
|
|
63
82
|
// only where there is something to act on. CONTEXT_STOPS runs quiet to loud
|
|
64
83
|
// as the window fills. CACHE_STOPS is that same scale mirrored, because a
|
|
65
|
-
// full cache is the good end and an empty one is the problem.
|
|
84
|
+
// full cache is the good end and an empty one is the problem. PACE_STOPS is
|
|
85
|
+
// the quota tool's heat map: green at the ideal 1.0×, cool where allowance
|
|
86
|
+
// goes unused, amber then red where it runs out early.
|
|
66
87
|
// 2. A FAMILY is a category. One token per kind of fact, held everywhere it
|
|
67
88
|
// appears, so the shape of the footer becomes learnable:
|
|
68
89
|
// accent place cwd, branch, dirty marker
|
|
@@ -85,6 +106,14 @@ const CONTEXT_STOPS: readonly Stop[] = [
|
|
|
85
106
|
/** The context ramp mirrored, so a full cache is quiet and an empty one is loud. */
|
|
86
107
|
const CACHE_STOPS: readonly Stop[] = CONTEXT_STOPS.map((stop) => ({ ...stop, at: 100 - stop.at })).reverse();
|
|
87
108
|
|
|
109
|
+
/** The quota tool's pace heat map (DashboardPalette.pace) on theme tokens, over pacePosition's scale. `mdLink` is the theme's cool blue. */
|
|
110
|
+
const PACE_STOPS: readonly Stop[] = [
|
|
111
|
+
{ at: -1, token: "mdLink" },
|
|
112
|
+
{ at: 0, token: "success" },
|
|
113
|
+
{ at: 0.5, token: "warning" },
|
|
114
|
+
{ at: 1, token: "error" },
|
|
115
|
+
];
|
|
116
|
+
|
|
88
117
|
const PLACE_TOKEN = "accent";
|
|
89
118
|
const SPEND_TOKEN = "warning";
|
|
90
119
|
const MACHINE_TOKEN = "syntaxKeyword";
|
|
@@ -107,9 +136,9 @@ const THINKING_LEVELS: Record<string, { full: string; short: string; token: stri
|
|
|
107
136
|
// up a kind of detail that matters more than the phase before it, and within a
|
|
108
137
|
// phase the least needed fact goes first.
|
|
109
138
|
|
|
110
|
-
type Form = "full" | "short" | "bare" | "hidden";
|
|
139
|
+
type Form = "full" | "short" | "brief" | "bare" | "least" | "hidden";
|
|
111
140
|
/** A fact's text in each form it has. A step names only forms its fact has. */
|
|
112
|
-
type FactForms = { full: string } & Partial<Record<"short" | "bare", string>>;
|
|
141
|
+
type FactForms = { full: string } & Partial<Record<"short" | "brief" | "bare" | "least", string>>;
|
|
113
142
|
/** One row of facts. Each inner list is one group, joined by the narrow joiner. */
|
|
114
143
|
type Row<Key extends string> = readonly (readonly Key[])[];
|
|
115
144
|
type Ladder<Key extends string> = {
|
|
@@ -117,7 +146,7 @@ type Ladder<Key extends string> = {
|
|
|
117
146
|
steps: readonly (readonly [Key | "spacing", Form])[];
|
|
118
147
|
};
|
|
119
148
|
type HeaderFact = "model" | "thinking" | "sessionName" | "sessionId";
|
|
120
|
-
type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "reuse";
|
|
149
|
+
type FooterFact = "branch" | "cwd" | "context" | "tokens" | "cost" | "perTurn" | "cacheSession" | "latest" | "reuse" | "pace";
|
|
121
150
|
|
|
122
151
|
const SPACING = {
|
|
123
152
|
full: { separator: WIDE_SEPARATOR, joiner: " " },
|
|
@@ -142,9 +171,12 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
|
|
|
142
171
|
[["branch"], ["cwd"]],
|
|
143
172
|
[["context", "tokens"], ["cost", "perTurn"]],
|
|
144
173
|
[["cacheSession"], ["latest"], ["reuse"]],
|
|
174
|
+
[["pace"]],
|
|
145
175
|
],
|
|
146
176
|
steps: [
|
|
147
|
-
// 1. Drop
|
|
177
|
+
// 1. Drop what the values already imply. First the pace bar and the words
|
|
178
|
+
// "resets in": the bar draws what the two rates say. Then the labels.
|
|
179
|
+
["pace", "short"],
|
|
148
180
|
["tokens", "short"], ["context", "bare"], ["cacheSession", "bare"],
|
|
149
181
|
// 2. Shorten the readings: the latest cache figure, then the cost, rounded twice.
|
|
150
182
|
["latest", "short"], ["cost", "short"], ["cost", "bare"],
|
|
@@ -152,9 +184,25 @@ const FOOTER_LADDER: Ladder<FooterFact> = {
|
|
|
152
184
|
["cwd", "short"], ["spacing", "bare"],
|
|
153
185
|
// 4. Drop the branch icon.
|
|
154
186
|
["branch", "bare"],
|
|
155
|
-
// 5. Hide whole facts.
|
|
156
|
-
//
|
|
157
|
-
|
|
187
|
+
// 5. Hide whole facts. First a stale quota reading's age: it outlasts the
|
|
188
|
+
// bar, the labels and the whitespace, so a laptop still sees that the
|
|
189
|
+
// rates are old, and it goes before every other part of the pace left.
|
|
190
|
+
// Then the burn rate and the reset time: the sign keeps the verdict,
|
|
191
|
+
// and the target is the number to act on. The word
|
|
192
|
+
// "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.
|
|
196
|
+
["pace", "brief"], ["pace", "bare"],
|
|
197
|
+
["reuse", "hidden"], ["cacheSession", "hidden"], ["tokens", "hidden"], ["pace", "least"], ["perTurn", "hidden"],
|
|
198
|
+
// 6. Drop the cause of a cache miss, keeping its cost. It outranks every
|
|
199
|
+
// hidden fact: it shows only on the turn that missed, and says what to
|
|
200
|
+
// do about the cost (an idle gap or a model switch).
|
|
201
|
+
["latest", "bare"],
|
|
202
|
+
// 7. Last, hide the target rate. Because the footer takes the fullest
|
|
203
|
+
// state with the fewest lines, this fires only where the target alone
|
|
204
|
+
// would add a line, as on a phone with the keyboard up.
|
|
205
|
+
["pace", "hidden"],
|
|
158
206
|
],
|
|
159
207
|
};
|
|
160
208
|
|
|
@@ -482,31 +530,184 @@ function renderThinkingLabel(theme: any, level: string, full: boolean): string {
|
|
|
482
530
|
|
|
483
531
|
// ── Session helpers ─────────────────────────────────────────────────────────
|
|
484
532
|
|
|
533
|
+
/** A cache miss in the terms of Pi's own miss notice. */
|
|
534
|
+
type CacheMiss = { missedTokens: number; missedCost: number; idleMs: number; modelChanged: boolean };
|
|
535
|
+
type PreviousRequest = { promptTokens: number; modelKey: string; timestamp: number; reportedCache: boolean };
|
|
536
|
+
type ModelLookup = Pick<ExtensionContext["modelRegistry"], "find">;
|
|
537
|
+
|
|
538
|
+
// Mirror pi's own miss detection (detectMiss in dist/core/cache-stats.js, which
|
|
539
|
+
// pi does not export), so the footer reports the numbers of pi's notice.
|
|
540
|
+
function detectCacheMiss(previous: PreviousRequest | undefined, message: AssistantMessage, models: ModelLookup): CacheMiss | null {
|
|
541
|
+
const { input, cacheRead, cacheWrite, cost } = message.usage;
|
|
542
|
+
const promptTokens = input + cacheRead + cacheWrite;
|
|
543
|
+
if (!previous || (cacheRead + cacheWrite === 0 && !previous.reportedCache)) return null;
|
|
544
|
+
const missedTokens = Math.min(previous.promptTokens, promptTokens) - cacheRead;
|
|
545
|
+
if (missedTokens <= CACHE_MISS_NOISE_FLOOR_TOKENS) return null;
|
|
546
|
+
const paidTokens = input + cacheWrite;
|
|
547
|
+
const paidPerToken = paidTokens > 0 ? (cost.input + cost.cacheWrite) / paidTokens : 0;
|
|
548
|
+
const readPerToken = cacheRead > 0
|
|
549
|
+
? cost.cacheRead / cacheRead
|
|
550
|
+
: (models.find(message.provider, message.model)?.cost.cacheRead ?? 0) / 1_000_000;
|
|
551
|
+
return {
|
|
552
|
+
missedTokens,
|
|
553
|
+
missedCost: missedTokens * Math.max(0, paidPerToken - readPerToken),
|
|
554
|
+
idleMs: Math.max(0, message.timestamp - previous.timestamp),
|
|
555
|
+
modelChanged: `${message.provider}/${message.model}` !== previous.modelKey,
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** The latest miss in its three forms. Ranked: what it cost, then why it
|
|
560
|
+
* happened, then how many tokens. Without a cost, the tokens take its place.
|
|
561
|
+
* @example
|
|
562
|
+
* cacheMissForms({ missedTokens: 199_000, missedCost: 0.38, idleMs: 360_000, modelChanged: false })
|
|
563
|
+
* // { full: "latest miss after 6m idle: 199k re-billed $0.38", short: "miss 6m idle $0.38", bare: "miss $0.38" }
|
|
564
|
+
*/
|
|
565
|
+
function cacheMissForms(miss: CacheMiss): Record<"full" | "short" | "bare", string> {
|
|
566
|
+
// 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.toFixed(2)}` : null;
|
|
568
|
+
const cause = miss.modelChanged ? "model switch" : miss.idleMs >= CACHE_TTL_MS ? `${Math.round(miss.idleMs / 60_000)}m idle` : null;
|
|
569
|
+
const tokens = formatTokens(miss.missedTokens);
|
|
570
|
+
const words = (...parts: (string | null)[]) => parts.filter(Boolean).join(" ");
|
|
571
|
+
return {
|
|
572
|
+
full: words("latest miss", cause && `after ${cause}:`, `${tokens} re-billed`, cost),
|
|
573
|
+
short: words("miss", cause, cost ?? tokens),
|
|
574
|
+
bare: words("miss", cost ?? tokens),
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// ── Quota pace ──────────────────────────────────────────────────────────────
|
|
579
|
+
// Read from the cache file the author's `quota` tool writes. The footer never
|
|
580
|
+
// runs the tool and never fetches: it shows the last reading any quota run
|
|
581
|
+
// left there, and adds the reading's age once it is stale. It reads the file
|
|
582
|
+
// once per snapshot, not per redraw.
|
|
583
|
+
|
|
584
|
+
type QuotaPool = "CLAUDE" | "FABLE" | "CODEX";
|
|
585
|
+
type WeeklyWindow = { used_pct: number; window_start: string; window_duration_seconds: number };
|
|
586
|
+
type QuotaCache = Record<string, { written_at?: string; usages?: { name: string; weekly: WeeklyWindow }[] }>;
|
|
587
|
+
/** One weekly limit's pace. `used` and `elapsed` are shares of the window, 0 to 1. `ageMs` is how old the reading is. */
|
|
588
|
+
type Pace = { burn: number; target: number; used: number; elapsed: number; resetsInMs: number; ageMs: number };
|
|
589
|
+
|
|
590
|
+
function quotaCacheFile(): string {
|
|
591
|
+
return join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "quota", "provider-usage.json");
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
/** The weekly pool a model spends from.
|
|
595
|
+
* @example
|
|
596
|
+
* quotaPool({ provider: "anthropic", id: "claude-fable-5-2" }) // "FABLE"
|
|
597
|
+
*/
|
|
598
|
+
function quotaPool(model: ExtensionContext["model"]): QuotaPool | null {
|
|
599
|
+
if (model?.provider === "openai-codex") return "CODEX";
|
|
600
|
+
if (model?.provider !== "anthropic") return null;
|
|
601
|
+
return model.id.includes("fable") ? "FABLE" : "CLAUDE";
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Burn and target rate of one weekly window, as the quota tool computes them. Null outside the window.
|
|
605
|
+
* @example
|
|
606
|
+
* windowPace({ used_pct: 15, window_start: "2026-01-01T00:00:00Z", window_duration_seconds: 1000 }, Date.parse("2026-01-01T00:01:40Z"))
|
|
607
|
+
* // { burn: 1.5, target: 0.944…, used: 0.15, elapsed: 0.1, resetsInMs: 900_000 }
|
|
608
|
+
* The age is the caller's: it comes from the provider entry, not the window.
|
|
609
|
+
*/
|
|
610
|
+
function windowPace(weekly: WeeklyWindow, now: number): Omit<Pace, "ageMs"> | null {
|
|
611
|
+
const durationMs = weekly.window_duration_seconds * 1000;
|
|
612
|
+
const elapsedMs = now - Date.parse(weekly.window_start);
|
|
613
|
+
if (elapsedMs <= 0 || elapsedMs >= durationMs) return null;
|
|
614
|
+
const used = weekly.used_pct / 100;
|
|
615
|
+
const elapsed = elapsedMs / durationMs;
|
|
616
|
+
return { burn: used / elapsed, target: Math.max(0, 1 - used) / (1 - elapsed), used, elapsed, resetsInMs: durationMs - elapsedMs };
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/** The pace of the model's pool, from the quota cache. Fable's target is the quota tool's pick score:
|
|
620
|
+
* its own target rate, capped by the room left in the shared Claude week. The age is that of the
|
|
621
|
+
* provider entry holding the pool, which Claude and Fable share.
|
|
622
|
+
*/
|
|
623
|
+
function readPace(model: ExtensionContext["model"], now: number): Pace | null {
|
|
624
|
+
const pool = quotaPool(model);
|
|
625
|
+
if (!pool) return null;
|
|
626
|
+
// The file belongs to another tool. A missing file, another shape or a missing pool all mean no reading.
|
|
627
|
+
try {
|
|
628
|
+
const cache: QuotaCache = JSON.parse(readFileSync(quotaCacheFile(), "utf8"));
|
|
629
|
+
const providerOf = (name: QuotaPool) => Object.values(cache).find((provider) => provider.usages?.some((usage) => usage.name === name))!;
|
|
630
|
+
const paceOf = (name: QuotaPool): Omit<Pace, "ageMs"> | null => windowPace(providerOf(name).usages!.find((usage) => usage.name === name)!.weekly, now);
|
|
631
|
+
const ageMs = Math.max(0, now - Date.parse(providerOf(pool).written_at!));
|
|
632
|
+
const pace = paceOf(pool);
|
|
633
|
+
if (!pace || Number.isNaN(ageMs)) return null;
|
|
634
|
+
if (pool !== "FABLE") return { ...pace, ageMs };
|
|
635
|
+
const claude = paceOf("CLAUDE");
|
|
636
|
+
return claude && { ...pace, target: Math.min(pace.target, claude.target / FABLE_SHARE_OF_WEEKLY), ageMs };
|
|
637
|
+
} catch {
|
|
638
|
+
return null;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** Where a rate sits on PACE_STOPS, by its distance from the ideal 1.0×. Mirrors the quota tool's
|
|
643
|
+
* DashboardPalette.pace: a burn rate heats above 1.0× (amber at 1.25×, red at 2×) and cools below it;
|
|
644
|
+
* a target rate runs the other way. Both are ideal within 5% of 1.0×.
|
|
645
|
+
* @example
|
|
646
|
+
* [pacePosition(1, false), pacePosition(1.25, false), pacePosition(2, false), pacePosition(0.25, false)] // [0, 0.5, 1, -1]
|
|
647
|
+
* [pacePosition(0.8, true), pacePosition(4, true)] // [0.5, -1]
|
|
648
|
+
*/
|
|
649
|
+
function pacePosition(rate: number, isTarget: boolean): number {
|
|
650
|
+
const pressure = (isTarget ? -1 : 1) * Math.log2(rate);
|
|
651
|
+
const idealBand = Math.log2(1.05);
|
|
652
|
+
const amberPoint = Math.log2(1.25);
|
|
653
|
+
if (pressure < -idealBand) return -Math.min(1, (-pressure - idealBand) / (2 - idealBand));
|
|
654
|
+
if (pressure <= idealBand) return 0;
|
|
655
|
+
if (pressure <= amberPoint) return 0.5 * (pressure - idealBand) / (amberPoint - idealBand);
|
|
656
|
+
return 0.5 + 0.5 * Math.min(1, (pressure - amberPoint) / (1 - amberPoint));
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** The used share (●) against the elapsed share (┊) of the window. The dot passes the marker when use is ahead of time.
|
|
660
|
+
* @example
|
|
661
|
+
* paceBar(0.55, 0.6, String, String) // "━━━━●┊───"
|
|
662
|
+
* paceBar(0.9, 0.85, String, String) // "━━━━━━┊●─"
|
|
663
|
+
*/
|
|
664
|
+
function paceBar(used: number, elapsed: number, heat: (text: string) => string, quiet: (text: string) => string): string {
|
|
665
|
+
const first = Math.round(Math.min(used, elapsed) * (PACE_BAR_CELLS - 2));
|
|
666
|
+
const second = Math.max(first + 1, Math.round(Math.min(1, Math.max(used, elapsed)) * (PACE_BAR_CELLS - 1)));
|
|
667
|
+
const between = second - first - 1;
|
|
668
|
+
const after = "─".repeat(PACE_BAR_CELLS - 1 - second);
|
|
669
|
+
return used > elapsed
|
|
670
|
+
? `${heat("━".repeat(first))}${quiet("┊")}${heat(`${"━".repeat(between)}●`)}${quiet(after)}`
|
|
671
|
+
: `${heat(`${"━".repeat(first)}●`)}${quiet(`${"─".repeat(between)}┊${after}`)}`;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/** A duration in the quota tool's own format: time left, or a reading's age.
|
|
675
|
+
* @example
|
|
676
|
+
* [formatRemaining(45_000_000), formatRemaining(110_000_000), formatRemaining(1_800_000)] // ["12h", "1d 6h", "30m"]
|
|
677
|
+
*/
|
|
678
|
+
function formatRemaining(milliseconds: number): string {
|
|
679
|
+
const hours = Math.floor(milliseconds / 3_600_000);
|
|
680
|
+
if (hours >= 24) return `${Math.floor(hours / 24)}d ${hours % 24}h`;
|
|
681
|
+
if (hours > 0) return `${hours}h`;
|
|
682
|
+
return `${Math.floor(milliseconds / 60_000)}m`;
|
|
683
|
+
}
|
|
684
|
+
|
|
485
685
|
interface SessionStats {
|
|
486
686
|
totalCost: number;
|
|
487
687
|
totalReused: number;
|
|
488
688
|
totalFresh: number;
|
|
489
689
|
sessionCacheHitRate: number | null;
|
|
490
690
|
latestCacheHitRate: number | null;
|
|
491
|
-
|
|
691
|
+
latestCacheMiss: CacheMiss | null;
|
|
492
692
|
averageCostPerTurn: number;
|
|
493
693
|
lastContextTokens: number; // input+output+cacheRead+cacheWrite of the last valid turn
|
|
494
694
|
}
|
|
495
695
|
|
|
496
|
-
|
|
696
|
+
/** Exported for tests/miss-parity.mjs, which compares the mirrored miss detection with Pi's. */
|
|
697
|
+
export function getSessionStats(branch: readonly SessionEntry[], models: ModelLookup): SessionStats {
|
|
497
698
|
let turnCount = 0;
|
|
498
699
|
let totalCost = 0;
|
|
499
700
|
let turnCost = 0;
|
|
500
701
|
let totalReused = 0;
|
|
501
702
|
let totalFresh = 0;
|
|
502
703
|
let lastContextTokens = 0;
|
|
503
|
-
let
|
|
704
|
+
let previousRequest: PreviousRequest | undefined;
|
|
504
705
|
let cacheWasReported = false;
|
|
505
706
|
let latestCacheHitRate: number | null = null;
|
|
506
|
-
let
|
|
707
|
+
let latestCacheMiss: CacheMiss | null = null;
|
|
507
708
|
for (const entry of branch) {
|
|
508
709
|
if (entry.type === "compaction" || entry.type === "branch_summary") {
|
|
509
|
-
|
|
710
|
+
previousRequest = undefined;
|
|
510
711
|
cacheWasReported = false;
|
|
511
712
|
continue;
|
|
512
713
|
}
|
|
@@ -516,6 +717,13 @@ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
|
|
|
516
717
|
totalCost += cost.total;
|
|
517
718
|
totalReused += cacheRead;
|
|
518
719
|
totalFresh += input + cacheWrite;
|
|
720
|
+
// Like pi's miss detection, the next turn's miss and idle gap count from a cache warm.
|
|
721
|
+
const warmPromptTokens = input + cacheRead + cacheWrite;
|
|
722
|
+
if (entry.kind === "cache_warm" && warmPromptTokens > 0) {
|
|
723
|
+
previousRequest = {
|
|
724
|
+
promptTokens: warmPromptTokens, modelKey: `${entry.provider}/${entry.model}`, timestamp: Date.parse(entry.timestamp), reportedCache: true,
|
|
725
|
+
};
|
|
726
|
+
}
|
|
519
727
|
continue;
|
|
520
728
|
}
|
|
521
729
|
if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
|
|
@@ -534,12 +742,11 @@ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
|
|
|
534
742
|
const cacheReported = cacheRead + cacheWrite > 0;
|
|
535
743
|
const cacheKnowledgeAvailable = cacheReported || cacheWasReported;
|
|
536
744
|
latestCacheHitRate = cacheKnowledgeAvailable ? (cacheRead / promptTokens) * 100 : null;
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
}
|
|
542
|
-
previousPromptTokens = promptTokens;
|
|
745
|
+
latestCacheMiss = detectCacheMiss(previousRequest, message, models);
|
|
746
|
+
previousRequest = {
|
|
747
|
+
promptTokens, modelKey: `${message.provider}/${message.model}`, timestamp: message.timestamp,
|
|
748
|
+
reportedCache: (previousRequest?.reportedCache ?? false) || cacheReported,
|
|
749
|
+
};
|
|
543
750
|
cacheWasReported ||= cacheReported;
|
|
544
751
|
}
|
|
545
752
|
const totalPrompt = totalReused + totalFresh;
|
|
@@ -549,7 +756,7 @@ function getSessionStats(branch: readonly SessionEntry[]): SessionStats {
|
|
|
549
756
|
totalFresh,
|
|
550
757
|
sessionCacheHitRate: totalPrompt > 0 ? (totalReused / totalPrompt) * 100 : null,
|
|
551
758
|
latestCacheHitRate,
|
|
552
|
-
|
|
759
|
+
latestCacheMiss,
|
|
553
760
|
averageCostPerTurn: turnCount > 0 ? turnCost / turnCount : 0,
|
|
554
761
|
lastContextTokens,
|
|
555
762
|
};
|
|
@@ -589,6 +796,7 @@ interface FooterSnapshot {
|
|
|
589
796
|
stats: SessionStats;
|
|
590
797
|
context: ReturnType<typeof getContextPercent>;
|
|
591
798
|
session: DisplaySession;
|
|
799
|
+
pace: Pace | null;
|
|
592
800
|
}
|
|
593
801
|
|
|
594
802
|
// ── Extension entry point ───────────────────────────────────────────────────
|
|
@@ -629,7 +837,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
629
837
|
const model: ExtensionContext["model"] = currentCtx.model;
|
|
630
838
|
if (snapshot && snapshot.manager === manager && snapshot.sessionId === sessionId && snapshot.leafId === leafId && snapshot.model === model) return snapshot;
|
|
631
839
|
const branch = manager.getBranch();
|
|
632
|
-
const stats = getSessionStats(branch);
|
|
840
|
+
const stats = getSessionStats(branch, currentCtx.modelRegistry);
|
|
633
841
|
const usage = currentCtx.getContextUsage();
|
|
634
842
|
// Boundary edits commit after turn_end, which may already have rendered the old projection.
|
|
635
843
|
const contextChangeId = branch.reduce<string | undefined>((latest, entry) =>
|
|
@@ -641,6 +849,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
641
849
|
manager, sessionId, leafId, model, stats,
|
|
642
850
|
context: getContextPercent(currentCtx, stats.lastContextTokens, usage),
|
|
643
851
|
session: getDisplaySession(currentCtx, currentCtx.cwd || ".", pi),
|
|
852
|
+
pace: readPace(model, Date.now()),
|
|
644
853
|
};
|
|
645
854
|
return snapshot;
|
|
646
855
|
}
|
|
@@ -687,7 +896,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
687
896
|
|
|
688
897
|
function renderBelow(width: number, theme: any): string[] {
|
|
689
898
|
if (!currentCtx) return [];
|
|
690
|
-
const { stats, context: { pct, window, tokens } } = getSnapshot();
|
|
899
|
+
const { stats, context: { pct, window, tokens }, pace } = getSnapshot();
|
|
691
900
|
const paint = makePainter(theme);
|
|
692
901
|
const label = (text: string) => theme.fg("dim", `${text} `);
|
|
693
902
|
const pill = (text: string) => theme.bg("selectedBg", paint.token(PLACE_TOKEN, theme.bold(text)));
|
|
@@ -710,7 +919,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
710
919
|
? paint.ramp(CACHE_STOPS, sessionHit, `${sessionHit.toFixed(1)}% session`)
|
|
711
920
|
: theme.fg("dim", "no cache yet");
|
|
712
921
|
const latestHit = stats.latestCacheHitRate;
|
|
713
|
-
const
|
|
922
|
+
const missForms = stats.latestCacheMiss && cacheMissForms(stats.latestCacheMiss);
|
|
923
|
+
const paceForms = (reading: Pace): FactForms => {
|
|
924
|
+
const dim = (text: string) => theme.fg("dim", text);
|
|
925
|
+
const burnHeat = (text: string) => paint.ramp(PACE_STOPS, pacePosition(reading.burn, false), text);
|
|
926
|
+
const burn = burnHeat(`${reading.burn.toFixed(2)}×`);
|
|
927
|
+
const target = paint.ramp(PACE_STOPS, pacePosition(reading.target, true), `${reading.target.toFixed(2)}×`);
|
|
928
|
+
// The sign carries the verdict, and colour repeats it.
|
|
929
|
+
const sign = reading.burn > reading.target ? theme.fg("error", ">") : dim("≤");
|
|
930
|
+
const resets = formatRemaining(reading.resetsInMs);
|
|
931
|
+
// A stale reading keeps showing, with its age until "brief", the form without it.
|
|
932
|
+
const age = reading.ageMs > PACE_STALE_AFTER_MS ? dim(` · ${formatRemaining(reading.ageMs)} old`) : "";
|
|
933
|
+
return {
|
|
934
|
+
full: `${label("burn")}${paceBar(reading.used, reading.elapsed, burnHeat, dim)} ${burn} ${sign} ${label("target")}${target}${dim(` · resets in ${resets}`)}${age}`,
|
|
935
|
+
short: `${label("burn")}${burn} ${sign} ${label("target")}${target}${dim(` · ${resets}`)}${age}`,
|
|
936
|
+
brief: `${label("burn")}${burn} ${sign} ${label("target")}${target}${dim(` · ${resets}`)}`,
|
|
937
|
+
bare: `${sign} ${label("target")}${target}`,
|
|
938
|
+
least: `${sign} ${target}`,
|
|
939
|
+
};
|
|
940
|
+
};
|
|
714
941
|
const footerFacts: Partial<Record<FooterFact, FactForms>> = {
|
|
715
942
|
branch: gitBranch
|
|
716
943
|
? { full: `${paint.token(PLACE_TOKEN, `${BRANCH_GLYPH} ${gitBranch}`)}${dirty}`, bare: `${paint.token(PLACE_TOKEN, gitBranch)}${dirty}` }
|
|
@@ -724,15 +951,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
724
951
|
cost: { full: cost(formatCost(stats.totalCost)), short: cost(stats.totalCost.toFixed(1)), bare: cost(stats.totalCost.toFixed(0)) },
|
|
725
952
|
perTurn: { full: paint.quiet(SPEND_TOKEN, `$${formatCost(stats.averageCostPerTurn)}/turn`) },
|
|
726
953
|
cacheSession: { full: `${label("cache")}${sessionHitText}`, bare: sessionHitText },
|
|
727
|
-
latest:
|
|
728
|
-
? { full: theme.fg("error",
|
|
954
|
+
latest: missForms
|
|
955
|
+
? { full: theme.fg("error", missForms.full), short: theme.fg("error", missForms.short), bare: theme.fg("error", missForms.bare) }
|
|
729
956
|
: latestHit != null
|
|
730
|
-
? {
|
|
957
|
+
? {
|
|
958
|
+
full: paint.ramp(CACHE_STOPS, latestHit, `latest ${latestHit.toFixed(1)}%`),
|
|
959
|
+
short: paint.ramp(CACHE_STOPS, latestHit, `latest ${Math.round(latestHit)}%`),
|
|
960
|
+
bare: paint.ramp(CACHE_STOPS, latestHit, `latest ${Math.round(latestHit)}%`),
|
|
961
|
+
}
|
|
731
962
|
: undefined,
|
|
732
963
|
reuse: {
|
|
733
964
|
full: paint.ramp(CACHE_STOPS, sessionHit ?? 0, formatTokens(stats.totalReused)) +
|
|
734
965
|
theme.fg("dim", ` reused / ${formatTokens(stats.totalFresh)} new`),
|
|
735
966
|
},
|
|
967
|
+
pace: pace ? paceForms(pace) : undefined,
|
|
736
968
|
};
|
|
737
969
|
return fitFacts(footerFacts, FOOTER_LADDER, width, theme);
|
|
738
970
|
}
|
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.12",
|
|
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": {
|