@bismawy/pi-arnative 0.10.1 → 0.11.1

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.
@@ -17,8 +17,16 @@ import { assert, isMain } from "../lib/check.ts";
17
17
  import { capitalize, markedLabels, modelDisplayParts } from "../lib/format.ts";
18
18
  import { IS_WINDOWS_LIKE, SHORTCUT_RELOAD, SHORTCUT_TOGGLE_FOOTER } from "../lib/shortcuts.ts";
19
19
  import { markPatched, originalOf } from "../lib/patch.ts";
20
- import { formatTokens } from "../lib/usage-store.ts";
21
- import { FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
20
+ import { estimateCost, formatTokens, loadPriceTable, TOOL_PROVIDER, type PriceTable } from "../lib/usage-store.ts";
21
+ import {
22
+ FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY,
23
+ FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY,
24
+ loadChoice,
25
+ resetPresetCache,
26
+ saveChoice,
27
+ } from "../lib/preset-store.ts";
28
+ import { formatCost } from "./usage.ts";
29
+ import { budgetLevelNow } from "./budget.ts";
22
30
  import { EDITOR_KEY, activeSpinnerGradient, activeSpinnerPreset } from "./animations.ts";
23
31
  import { spinnerPainter } from "../lib/spinner.ts";
24
32
 
@@ -48,6 +56,22 @@ export function minimalExpanded(): { left: boolean; right: boolean } {
48
56
  }
49
57
  const FOOTER_PRESET_KEY = Symbol.for("pi-arnative.footerPreset");
50
58
  const FOOTER_REGISTRAR_KEY = Symbol.for("pi-arnative.footerRegistrar");
59
+ const FOOTER_COST_KEY = Symbol.for("pi-arnative.footerCost");
60
+
61
+ /** Is the session cost cell on? Stored as `"on"`/`"off"` so an absent key reads as off
62
+ * through the same allow-list path every other choice uses. */
63
+ export function activeFooterCost(): boolean {
64
+ const stored = (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] ?? loadChoice(FOOTER_COST_CONFIG_KEY, ["on", "off"] as const);
65
+ return stored === "on";
66
+ }
67
+
68
+ /** Flip the cost cell, persist it, and repaint the footer at once — the choice is a command
69
+ * the user asked for, so it is not part of the picker's preview/revert dance. */
70
+ export function setFooterCost(on: boolean): void {
71
+ (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] = on ? "on" : "off";
72
+ saveChoice(FOOTER_COST_CONFIG_KEY, on ? "on" : "off");
73
+ poke();
74
+ }
51
75
 
52
76
  export function activeFooterPreset(): FooterPreset {
53
77
  const stored = (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] ?? loadChoice(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS);
@@ -601,65 +625,252 @@ function parseOptimizer(raw: string | undefined): string | null {
601
625
 
602
626
  // Pi's own per-message usage: shown when pi-cache-optimizer has no adapter for the
603
627
  // provider (a custom one like mytool.ts publishes no pi-cache-stats status).
628
+ // The denominator (`input + cacheRead`) includes tool-result (child) tokens, because the ↑
629
+ // cell above is total spend — the hit rate is measured against the same total, so do not
630
+ // "fix" the denominator back to assistant messages only.
604
631
  let usageTotals = { inp: 0, read: 0 };
605
632
  export function piCacheHit(): string | null {
606
633
  const total = usageTotals.inp + usageTotals.read;
607
634
  return total > 0 ? "pi " + ((usageTotals.read / total) * 100).toFixed(1) + "%" : null;
608
635
  }
609
636
 
637
+ // The cache cell's COLOUR comes from a recent window, not the session-wide rate above: the
638
+ // last CACHE_WINDOW_MSGS assistant messages, with the session's first two always skipped
639
+ // (turn 1 is a cold cache, so colouring it would cry wolf on every session). The `pi …%`
640
+ // text stays session-wide; only the colour is windowed.
641
+ export const CACHE_WINDOW_MSGS = 10;
642
+ /** Windowed (input, cacheRead) sums of the last scan — read by the render for the colour. */
643
+ let usageWindow = { inp: 0, read: 0 };
644
+
645
+ export type CacheHitBand = "soft" | "warning" | "error";
646
+ /** Colour band of a windowed cache-hit rate: ≥70% keeps the current soft tier, 40–70% is
647
+ * amber (the theme's `warning` slot), below 40% is red (`error`). No rate yet (fewer than
648
+ * 3 assistant messages, so an empty window) stays soft. */
649
+ export function cacheHitBand(winInp: number, winRead: number): CacheHitBand {
650
+ const total = winInp + winRead;
651
+ if (total <= 0) return "soft";
652
+ const rate = winRead / total;
653
+ if (rate >= 0.7) return "soft";
654
+ if (rate >= 0.4) return "warning";
655
+ return "error";
656
+ }
657
+
610
658
  let usageScanAt = 0;
611
659
  let usageScanLen = -1;
612
- let usageScanNums = { inp: 0, out: 0, read: 0 };
613
- // Usage of the branch's last entry at scan time: a stream tick mutates that message
614
- // in place (branch length unchanged), so the delta is applied on top of the cached
615
- // sums — O(1) per frame, numbers always fresh, still no O(N) rescan per frame.
616
- let usageScanLast = { inp: 0, out: 0, read: 0 };
660
+ interface UsageTotals {
661
+ inp: number;
662
+ out: number;
663
+ read: number;
664
+ /** Sum of `cost.total` over the messages the provider billed (`totalFromProvider`). */
665
+ costBilled: number;
666
+ /** Everything else: catalog totals, plus a price-table reconstruction for messages that
667
+ * carried no cost at all. Never blended into `costBilled`. */
668
+ costEstimated: number;
669
+ /** Only set on the branch-last snapshot (`lastUsageOf`): that entry is an assistant message. */
670
+ assistant?: boolean;
671
+ }
617
672
 
618
- const lastUsageOf = (branch: readonly unknown[]): { inp: number; out: number; read: number } => {
673
+ let usageScanManager: object | undefined;
674
+ let usageScanLeaf: unknown;
675
+ // A stream mutates the same leaf, so its delta updates the cached prefix. A different
676
+ // manager or leaf must rescan: equal-length /tree branches can have different usage.
677
+
678
+ let usageScanNums: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
679
+ // Usage of the branch's last entry at scan time (assistant or tool result): a stream tick
680
+ // mutates that entry in place (branch length unchanged), so the delta is applied on top of
681
+ // the cached sums — O(1) per frame, numbers always fresh, still no O(N) rescan per frame.
682
+ let usageScanLast: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
683
+ // Windowed sums at scan time, plus the window contribution of the branch's last entry
684
+ // (`null` when that entry is not an assistant message inside the window): the in-place
685
+ // delta of a stream tick lands in the window exactly when the last entry is one.
686
+ let usageScanWin = { inp: 0, read: 0 };
687
+ let usageScanWinLast: { inp: number; read: number } | null = null;
688
+
689
+ type MessageUsage = {
690
+ input?: number;
691
+ output?: number;
692
+ cacheRead?: number;
693
+ cacheWrite?: number;
694
+ cost?: { total?: number; totalFromProvider?: boolean };
695
+ /** Only set by a tool that names what produced its own usage; absent on the main LLM calls. */
696
+ provider?: string;
697
+ model?: string;
698
+ };
699
+
700
+ /** True when a usage object carries any countable field: a tool result without usage (or with
701
+ * an all-zero one) adds nothing to the sums. */
702
+ const hasUsage = (u: MessageUsage | undefined): u is MessageUsage =>
703
+ !!u && !!((u.input || 0) || (u.output || 0) || (u.cacheRead || 0) || (u.cacheWrite || 0) || (u.cost?.total || 0));
704
+
705
+ /** Attribution of one branch message's usage: a tool result's usage names no provider/model,
706
+ * so it is attributed to the tool itself (`tool` · toolName), never to the parent's model. */
707
+ /** A tool result names no provider/model: it is attributed to the tool itself, never to the
708
+ * parent's model. pi-subagents does not set `totalFromProvider` on that usage, so child spend
709
+ * always lands in the estimated part of the cell (`~`) even when the children were billed. */
710
+ const attributionOf = (
711
+ m: { role: string; provider?: string; model?: string; toolName?: string },
712
+ u: MessageUsage,
713
+ ): { provider: string | undefined; model: string | undefined } =>
714
+ m.role === "toolResult"
715
+ ? { provider: u.provider ?? TOOL_PROVIDER, model: u.model ?? m.toolName ?? TOOL_PROVIDER }
716
+ : { provider: m.provider, model: m.model };
717
+
718
+ /** Billed vs estimated split of one message's usage: a provider-billed total goes to
719
+ * `costBilled`, a catalog total (pi's own estimate) to `costEstimated`, and a message that
720
+ * carried no cost at all is recomputed from the price table, cache writes included. */
721
+ const costSplitOf = (
722
+ u: MessageUsage,
723
+ provider: string | undefined,
724
+ model: string | undefined,
725
+ table: PriceTable,
726
+ ): { costBilled: number; costEstimated: number } => {
727
+ const total = u.cost?.total || 0;
728
+ if (u.cost?.totalFromProvider === true) return { costBilled: total, costEstimated: 0 };
729
+ if (total > 0) return { costBilled: 0, costEstimated: total };
730
+ const est = provider && model ? estimateCost(u.input || 0, u.output || 0, u.cacheRead || 0, u.cacheWrite || 0, model, provider, table) : null;
731
+ return { costBilled: 0, costEstimated: est ?? 0 };
732
+ };
733
+
734
+ const lastUsageOf = (branch: readonly unknown[], table: PriceTable): UsageTotals => {
735
+ const zeros: UsageTotals = { inp: 0, out: 0, read: 0, costBilled: 0, costEstimated: 0 };
619
736
  const last = branch[branch.length - 1] as
620
- | { type?: string; message?: { role?: string; usage?: { input?: number; output?: number; cacheRead?: number } } }
737
+ | {
738
+ type?: string;
739
+ message?: { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage };
740
+ }
621
741
  | undefined;
622
- const u = last?.type === "message" && last.message?.role === "assistant" ? last.message.usage : undefined;
623
- return u ? { inp: u.input || 0, out: u.output || 0, read: u.cacheRead || 0 } : { inp: 0, out: 0, read: 0 };
742
+ const m = last?.type === "message" ? last.message : undefined;
743
+ const role = m?.role;
744
+ const assistant = role === "assistant";
745
+ const u = role === "assistant" || role === "toolResult" ? m!.usage : undefined;
746
+ if (!hasUsage(u)) {
747
+ zeros.assistant = assistant;
748
+ return zeros;
749
+ }
750
+ const { provider, model } = attributionOf(m!, u);
751
+ const { costBilled, costEstimated } = costSplitOf(u, provider, model, table);
752
+ return { inp: u.input || 0, out: u.output || 0, read: u.cacheRead || 0, costBilled, costEstimated, assistant };
624
753
  };
625
754
 
755
+ /** No burn rate below five minutes of active time: dividing a two-minute clock prints nonsense. */
756
+ export const RATE_MIN_ACTIVE_MS = 5 * 60_000;
757
+ /** Terminals narrower than this drop the rate — the cost alone still fits. */
758
+ export const RATE_MIN_WIDTH = 80;
759
+
760
+ /** The session cost cell, with the burn rate appended in parentheses (one cell, not two): `$0.42 ($1.80/h)`.
761
+ * Billed and estimated never blend: `$0.42` when only the provider billed, `~$0.42` when only
762
+ * an estimate exists, `$0.30 + ~$0.12` when the branch has both, and no cell at all when there
763
+ * is no cost — the same promise `/usage` makes. The rate is cost per ACTIVE hour — the clock
764
+ * counts active time (idle pauses excluded), not wall-clock — so it is labelled `$/h`; it
765
+ * carries the `~` whenever estimated cost feeds it, like the estimated part of the cell, and
766
+ * is hidden below RATE_MIN_ACTIVE_MS of active time and below RATE_MIN_WIDTH columns.
767
+ * `bandPaint` paints the whole cell (icon and text) when a budget cap is near or over —
768
+ * amber at `warn`, red at `over` (see `budgetLevelNow`); without it the icon keeps `acc` and
769
+ * the text `soft`. */
770
+ export function costCell(
771
+ costBilled: number,
772
+ costEstimated: number,
773
+ acc: (t: string) => string,
774
+ soft: (t: string) => string,
775
+ width: number = RATE_MIN_WIDTH,
776
+ bandPaint?: (t: string) => string,
777
+ ): string {
778
+ if (!(costBilled > 0) && !(costEstimated > 0)) return "";
779
+ const parts: string[] = [];
780
+ if (costBilled > 0) parts.push(formatCost(costBilled));
781
+ if (costEstimated > 0) parts.push(`~${formatCost(costEstimated)}`);
782
+ let text = parts.join(" + ");
783
+ const activeMs = clock.total();
784
+ if (activeMs >= RATE_MIN_ACTIVE_MS && width >= RATE_MIN_WIDTH) {
785
+ const rate = (costBilled + costEstimated) / (activeMs / 3_600_000);
786
+ text += ` (${costEstimated > 0 ? "~" : ""}${formatCost(rate)}/h)`;
787
+ }
788
+ return `${(bandPaint ?? acc)("\uf155")} ${(bandPaint ?? soft)(text)}`;
789
+ }
790
+
626
791
  // 2s cache + branch length: the footer renders on every poke/stream tick, so
627
792
  // without this every frame rescans the whole branch (O(N) per frame).
628
793
  export function getUsage(
629
794
  ctx: { sessionManager: { getBranch(): readonly unknown[] }; getContextUsage(): { tokens: number | null; contextWindow: number; percent: number | null } | undefined },
630
795
  acc: (t: string) => string,
631
796
  soft: (t: string) => string,
797
+ /** Off by default: the cost cell is opt-in (`/arnative` → Footers → `[c]`). */
798
+ showCost: boolean = activeFooterCost(),
799
+ /** Terminal width: the burn rate is dropped below RATE_MIN_WIDTH columns. */
800
+ width: number = RATE_MIN_WIDTH,
801
+ /** Budget band painter for the cost cell (amber at `warn`, red at `over`); absent keeps acc/soft. */
802
+ bandPaint?: (t: string) => string,
803
+ /** Painter for the divider that opens the cost group; the caller passes the footer `dim`. */
804
+ dim: (t: string) => string = soft,
632
805
  ): string {
633
806
  const branch = ctx.sessionManager.getBranch();
634
- const last = lastUsageOf(branch);
807
+ // Memoized on models.json's stat, so this is one statSync per frame, not a read.
808
+ const priceTable = loadPriceTable();
809
+ const leaf = branch[branch.length - 1];
810
+ const last = lastUsageOf(branch, priceTable);
635
811
  let inp = 0;
636
812
  let out = 0;
637
813
  let read = 0;
638
- if (Date.now() - usageScanAt < 2000 && branch.length === usageScanLen) {
814
+ let costBilled = 0;
815
+ let costEstimated = 0;
816
+ let winInp = 0;
817
+ let winRead = 0;
818
+ if (Date.now() - usageScanAt < 2000 && branch.length === usageScanLen && ctx.sessionManager === usageScanManager && leaf === usageScanLeaf) {
639
819
  // Cached sums + the streaming delta of the last message (mutated in place).
640
820
  inp = usageScanNums.inp + last.inp - usageScanLast.inp;
641
821
  out = usageScanNums.out + last.out - usageScanLast.out;
642
822
  read = usageScanNums.read + last.read - usageScanLast.read;
823
+ costBilled = usageScanNums.costBilled + last.costBilled - usageScanLast.costBilled;
824
+ costEstimated = usageScanNums.costEstimated + last.costEstimated - usageScanLast.costEstimated;
825
+ // The window covers assistant messages only, so the in-place delta of the last
826
+ // entry lands in it exactly when that entry is an assistant message in the window.
827
+ winInp = usageScanWin.inp + (usageScanWinLast ? last.inp - usageScanWinLast.inp : 0);
828
+ winRead = usageScanWin.read + (usageScanWinLast ? last.read - usageScanWinLast.read : 0);
643
829
  } else {
830
+ // (input, cacheRead) of the trailing assistant messages, capped so the window below
831
+ // is the last CACHE_WINDOW_MSGS of them once the first two are skipped.
832
+ const assist: [number, number][] = [];
644
833
  for (const e of branch) {
645
- if (e && typeof e === "object" && "type" in e && e.type === "message") {
646
- const m = (e as { message?: unknown }).message;
647
- if (m && typeof m === "object" && "role" in m && m.role === "assistant" && "usage" in m) {
648
- const u = (m as AssistantMessage).usage;
649
- if (u) {
650
- inp += u.input || 0;
651
- out += u.output || 0;
652
- read += u.cacheRead || 0;
653
- }
654
- }
834
+ if (!e || typeof e !== "object" || !("type" in e) || e.type !== "message") continue;
835
+ const m = (e as { message?: unknown }).message as
836
+ | { role?: string; provider?: string; model?: string; toolName?: string; usage?: MessageUsage }
837
+ | undefined;
838
+ // Assistant messages carry their own call's usage; a tool result carries the child
839
+ // (subagent / nested tool) spend — pi puts that nowhere else, so summing both roles
840
+ // counts every token once, never twice.
841
+ if (!m || (m.role !== "assistant" && m.role !== "toolResult")) continue;
842
+ const u = m.usage;
843
+ if (m.role === "assistant") {
844
+ assist.push([u?.input || 0, u?.cacheRead || 0]);
845
+ if (assist.length > CACHE_WINDOW_MSGS + 2) assist.shift();
655
846
  }
847
+ if (!hasUsage(u)) continue;
848
+ inp += u.input || 0;
849
+ out += u.output || 0;
850
+ read += u.cacheRead || 0;
851
+ const { provider, model } = attributionOf(m, u);
852
+ const split = costSplitOf(u, provider, model, priceTable);
853
+ costBilled += split.costBilled;
854
+ costEstimated += split.costEstimated;
656
855
  }
657
- usageScanNums = { inp, out, read };
856
+ usageScanNums = { inp, out, read, costBilled, costEstimated };
658
857
  usageScanLast = last;
659
858
  usageScanAt = Date.now();
660
859
  usageScanLen = branch.length;
860
+ // Windowed cache rate, computed in this same pass: the last CACHE_WINDOW_MSGS
861
+ // assistant messages, the session's first two skipped (turn 1 is always cold).
862
+ const win = assist.slice(Math.max(2, assist.length - CACHE_WINDOW_MSGS));
863
+ for (const [wi, wr] of win) {
864
+ winInp += wi;
865
+ winRead += wr;
866
+ }
867
+ usageScanWin = { inp: winInp, read: winRead };
868
+ usageScanWinLast = last.assistant === true && assist.length > 2 ? { inp: last.inp, read: last.read } : null;
869
+ usageScanManager = ctx.sessionManager;
870
+ usageScanLeaf = leaf;
661
871
  }
662
872
  usageTotals = { inp, read };
873
+ usageWindow = { inp: winInp, read: winRead };
663
874
  const parts: string[] = [];
664
875
  if (inp > 0) parts.push(`${acc("↑")}${soft(formatTokens(inp))}`);
665
876
  if (out > 0) parts.push(`${acc("↓")}${soft(formatTokens(out))}`);
@@ -668,6 +879,12 @@ export function getUsage(
668
879
  if (u && u.percent !== null && u.tokens !== null) {
669
880
  parts.push(`${acc("\udb81\udfaf")} ${soft(`${u.percent.toFixed(1)}%/${formatTokens(u.contextWindow)}`)}`);
670
881
  }
882
+ if (showCost) {
883
+ const cell = costCell(costBilled, costEstimated, acc, soft, width, bandPaint);
884
+ // The dollar icon opens a new group, so it takes the same divider the footer uses
885
+ // between cells; the token and context parts stay a space apart.
886
+ if (cell) parts.push(parts.length > 0 ? `${dim("·")} ${cell}` : cell);
887
+ }
671
888
  return parts.join(" ");
672
889
  }
673
890
 
@@ -912,6 +1129,8 @@ export default function (pi: ExtensionAPI) {
912
1129
  // previous session's sums whenever the fresh branch happens to be the same length.
913
1130
  usageScanAt = 0;
914
1131
  usageScanLen = -1;
1132
+ usageScanManager = undefined;
1133
+ usageScanLeaf = undefined;
915
1134
  } else {
916
1135
  currentModel = (globalThis as Record<symbol, any>)[MODEL_KEY] ?? ctx.model;
917
1136
  currentThinkingLevel = (globalThis as Record<symbol, any>)[THINKING_KEY] ?? ctx.thinkingLevel;
@@ -1027,13 +1246,30 @@ export default function (pi: ExtensionAPI) {
1027
1246
 
1028
1247
  let usageStr = "";
1029
1248
  try {
1030
- usageStr = getUsage(ctx, acc, secondarySoft);
1249
+ // The cost cell's colour follows the budget band — amber at ≥80% of a
1250
+ // cap, red at ≥100% — read from the memoized usage summary, so the
1251
+ // render path scans at most once per 5s memo expiry, never per frame.
1252
+ // Nothing is read at all while the cell is off.
1253
+ const band = activeFooterCost() ? budgetLevelNow() : "ok";
1254
+ const bandPaint = band === "warn" ? colorOr("warning", acc) : band === "over" ? colorOr("error", acc) : undefined;
1255
+ usageStr = getUsage(ctx, acc, secondarySoft, activeFooterCost(), width, bandPaint, dim);
1031
1256
  } catch {
1032
1257
  // fallback
1033
1258
  }
1034
1259
  const opt = parseOptimizer(rawCache) ?? piCacheHit();
1035
1260
  const speedStr = latestSpeed !== null && latestSpeed > 0 ? `${acc("\udb81\udcc5")} ${secondarySoft(`${latestSpeed.toFixed(1)} tok/s`)}` : "";
1036
- const metricCells = [speedStr, opt ? `${acc("\udb80\udf5b")} ${secondarySoft(opt)}` : "", usageStr].filter(Boolean);
1261
+ // The cache cell's colour follows the recent window (the last 10 assistant
1262
+ // messages, the first two skipped): soft ≥70%, amber 40–70% (`warning`
1263
+ // slot, accent when the theme has none), red below 40% (`error`). A passive
1264
+ // colour only — never a notify. The `pi …%` text itself stays as is.
1265
+ // Only pi's own number may be coloured by pi's window: a cache-stats plugin
1266
+ // publishes its own rate (often per request, not per token), and painting it
1267
+ // with our band would contradict the number printed next to it.
1268
+ const fromPi = !parseOptimizer(rawCache);
1269
+ const band = fromPi ? cacheHitBand(usageWindow.inp, usageWindow.read) : null;
1270
+ const bandPaint = band === "warning" ? colorOr("warning", acc) : band === "error" ? colorOr("error", acc) : null;
1271
+ const cacheCell = opt ? `${(bandPaint ?? acc)("\udb80\udf5b")} ${(bandPaint ?? secondarySoft)(opt)}` : "";
1272
+ const metricCells = [speedStr, cacheCell, usageStr].filter(Boolean);
1037
1273
 
1038
1274
  // Fixed 3-row grid: head (cwd/model), then statuses and metrics each
1039
1275
  // wrapped inside their half of the width. Arnative (Minimal) starts collapsed
@@ -1243,6 +1479,8 @@ export default function (pi: ExtensionAPI) {
1243
1479
  });
1244
1480
 
1245
1481
  pi.on("session_shutdown", async (_event, ctx) => {
1482
+ usageScanManager = undefined;
1483
+ usageScanLeaf = undefined;
1246
1484
  stopWorkingClock();
1247
1485
  stopIdleProbe();
1248
1486
  stopClockTick();
@@ -1371,6 +1609,151 @@ if (isMain(import.meta.url)) {
1371
1609
  // No pi-cache-stats status (provider without an optimizer adapter): the cache cell
1372
1610
  // falls back to Pi's own usage, cacheRead / (input + cacheRead) = 10 / 1110.
1373
1611
  assert(piCacheHit() === "pi 0.9%", "cache fallback reads Pi's built-in usage: " + piCacheHit());
1612
+ // Cost cell: opt-in, and the branch scan splits billed from estimated cost.
1613
+ assert(costCell(0, 0, id, id) === "", "no cost at all: no cell");
1614
+ assert(costCell(0.42, 0, id, id).endsWith("$0.42") && !costCell(0.42, 0, id, id).includes("~"), "billed only: $0.42 without ~");
1615
+ assert(costCell(0, 0.42, id, id).includes("~$0.42") && !costCell(0, 0.42, id, id).includes("+"), "estimated only: ~$0.42");
1616
+ assert(costCell(0.3, 0.12, id, id).includes("$0.30 + ~$0.12"), "both: $0.30 + ~$0.12, never blended");
1617
+ // The budget band paints the cost cell — amber at `warn`, red at `over`; no band keeps acc/soft.
1618
+ const warnPaint = (t: string) => `<warn>${t}</warn>`;
1619
+ const overPaint = (t: string) => `<error>${t}</error>`;
1620
+ assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH, warnPaint) === `<warn>\uf155</warn> <warn>$0.42</warn>`, "the warn band paints icon and text: " + costCell(0.42, 0, id, id, RATE_MIN_WIDTH, warnPaint));
1621
+ assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH, overPaint) === `<error>\uf155</error> <error>$0.42</error>`, "the over band paints icon and text: " + costCell(0.42, 0, id, id, RATE_MIN_WIDTH, overPaint));
1622
+ assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH) === "\uf155 $0.42", "no band: acc icon, soft text, as before");
1623
+
1624
+ // Self-check: the burn rate appended to the cost cell — cost / ACTIVE hours of the clock
1625
+ // (idle pauses excluded, not wall-clock), hidden below 5 active minutes, when the cost
1626
+ // is 0, and below 80 columns. Freeze the clock's live part so total() is exactly `active`.
1627
+ const clockBackup = { active: clock.active, runStarted: clock.runStarted, lastSeen: clock.lastSeen };
1628
+ const freezeClock = (activeMs: number) => {
1629
+ clock.active = activeMs;
1630
+ clock.runStarted = Date.now();
1631
+ clock.lastSeen = clock.runStarted - clock.pauseMs - 1;
1632
+ };
1633
+ freezeClock(14 * 60_000); // $0.42 over 14 active minutes = $1.80/h
1634
+ assert(costCell(0.42, 0, id, id).includes("$0.42 ($1.80/h)"), "the rate is cost / active hours: $0.42 over 14 active minutes is $1.80/h: " + costCell(0.42, 0, id, id));
1635
+ assert(!costCell(0.42, 0, id, id).includes("~"), "a billed-only rate carries no ~");
1636
+ assert(costCell(0, 0.42, id, id).includes("~$1.80/h"), "an estimate-based rate is prefixed ~, like the estimated part of the cell");
1637
+ freezeClock(RATE_MIN_ACTIVE_MS - 1);
1638
+ assert(!costCell(0.42, 0, id, id).includes("/h"), "no rate below 5 minutes of active time (a two-minute clock would print nonsense)");
1639
+ freezeClock(RATE_MIN_ACTIVE_MS);
1640
+ assert(costCell(0.42, 0, id, id).includes("/h"), "the rate appears at exactly 5 active minutes");
1641
+ assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH - 1).endsWith("$0.42"), "below 80 columns the rate is dropped, the cost stays");
1642
+ assert(costCell(0.42, 0, id, id, RATE_MIN_WIDTH).includes("/h"), "at 80 columns the rate is kept");
1643
+ assert(costCell(0, 0, id, id) === "", "zero cost: no cell at all, so no rate either");
1644
+ clock.active = clockBackup.active;
1645
+ clock.runStarted = clockBackup.runStarted;
1646
+ clock.lastSeen = clockBackup.lastSeen;
1647
+
1648
+ // Self-check: the cache cell's colour bands (the `pi …%` text itself stays session-wide).
1649
+ assert(cacheHitBand(300, 700) === "soft" && cacheHitBand(200, 800) === "soft", "a windowed rate ≥70% keeps the soft tier");
1650
+ assert(cacheHitBand(600, 400) === "warning" && cacheHitBand(550, 450) === "warning", "40–70% is the amber (warning) band");
1651
+ assert(cacheHitBand(700, 300) === "error" && cacheHitBand(601, 399) === "error", "below 40% is the red (error) band");
1652
+ assert(cacheHitBand(0, 0) === "soft", "an empty window (fewer than 3 assistant messages) stays soft");
1653
+ // The windowed rate itself, through the scan pass: the first two assistant messages are
1654
+ // ignored, the window is capped at the last CACHE_WINDOW_MSGS, and a stream tick moves
1655
+ // it through the in-place delta without a rescan.
1656
+ const asstMsg = (inp: number, read: number) => ({ type: "message", message: { role: "assistant", usage: { input: inp, output: 5, cacheRead: read } } });
1657
+ const winBranch = [asstMsg(1000, 0), asstMsg(1000, 0), asstMsg(1000, 1000), asstMsg(1000, 1000)];
1658
+ const winCtx = { sessionManager: { getBranch: () => winBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1659
+ usageScanAt = 0;
1660
+ usageScanLen = -1;
1661
+ getUsage(winCtx, id, id, false);
1662
+ assert(usageWindow.inp === 2000 && usageWindow.read === 2000, "the windowed rate ignores the first two assistant messages: " + JSON.stringify(usageWindow));
1663
+ assert(piCacheHit() === "pi 33.3%", "the pi …% text stays session-wide while the colour is windowed: " + piCacheHit());
1664
+ const scanAtWin = usageScanAt;
1665
+ // A stream tick mutates the last entry in place; replacing it would be a new leaf, and the
1666
+ // i7 identity check would (correctly) rescan instead of taking the delta.
1667
+ (winBranch[3] as { message: { usage: { cacheRead: number } } }).message.usage.cacheRead = 0;
1668
+ getUsage(winCtx, id, id, false);
1669
+ assert(usageWindow.inp === 2000 && usageWindow.read === 1000, "a stream tick moves the window through the delta: " + JSON.stringify(usageWindow));
1670
+ assert(usageScanAt === scanAtWin, "the windowed delta took the cached path, not a rescan");
1671
+ assert(cacheHitBand(usageWindow.inp, usageWindow.read) === "error", "a collapsed recent window is red even though the session rate is still 33.3%");
1672
+ usageScanAt = 0;
1673
+ usageScanLen = -1;
1674
+ const capBranch = [asstMsg(1000, 0), asstMsg(1000, 0), asstMsg(1000, 0), ...Array.from({ length: CACHE_WINDOW_MSGS }, () => asstMsg(600, 400))];
1675
+ const capCtx = { sessionManager: { getBranch: () => capBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1676
+ getUsage(capCtx, id, id, false);
1677
+ assert(usageWindow.inp === 6_000 && usageWindow.read === 4_000, "the window is capped at the last " + CACHE_WINDOW_MSGS + " assistant messages: " + JSON.stringify(usageWindow));
1678
+ assert(cacheHitBand(usageWindow.inp, usageWindow.read) === "warning", "a 40% windowed rate is the amber band");
1679
+ const costBranch: Array<{
1680
+ type: string;
1681
+ message: { role: string; usage?: { input?: number; output?: number; cacheRead?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
1682
+ }> = [{ type: "message", message: { role: "assistant", usage: { input: 10, output: 5, cacheRead: 0, cost: { total: 0.42, totalFromProvider: true } } } }];
1683
+ const costCtx = { sessionManager: { getBranch: () => costBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1684
+ assert(!getUsage(costCtx, id, id, false).includes("$0.42"), "cost cell is off unless the switch is on");
1685
+ assert(getUsage(costCtx, id, id, true).includes("$0.42"), "cost cell sums the branch's billed cost when on");
1686
+ assert(
1687
+ getUsage(costCtx, id, id, true).includes("·  $0.42"),
1688
+ "the cost cell opens with the footer divider, so the dollar icon reads as its own group",
1689
+ );
1690
+ assert(getUsage(costCtx, id, id, true, RATE_MIN_WIDTH, warnPaint).includes("<warn>$0.42</warn>"), "the warn band reaches the cost cell through getUsage");
1691
+ assert(getUsage(costCtx, id, id, true, RATE_MIN_WIDTH, overPaint).includes("<error>$0.42</error>"), "the over band reaches the cost cell through getUsage");
1692
+
1693
+ // Child spend from a tool result: one assistant message + one tool result carrying usage —
1694
+ // the sums are the sum of both, once each — and a tool result mutated in place (a finished
1695
+ // child call updates its usage, branch length unchanged) still applies the delta on the
1696
+ // cached sums, no rescan.
1697
+ const childBranch: Array<{
1698
+ type: string;
1699
+ message: { role: string; toolName?: string; usage?: { input?: number; output?: number; cacheRead?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
1700
+ }> = [
1701
+ { type: "message", message: { role: "assistant", usage: { input: 100, output: 50, cacheRead: 10 } } },
1702
+ {
1703
+ type: "message",
1704
+ message: { role: "toolResult", toolName: "subagent", usage: { input: 400, output: 60, cacheRead: 20, cost: { total: 0.05, totalFromProvider: true } } },
1705
+ },
1706
+ ];
1707
+ const childCtx = { sessionManager: { getBranch: () => childBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1708
+ usageScanAt = 0;
1709
+ usageScanLen = -1;
1710
+ const child1 = getUsage(childCtx, id, id, true);
1711
+ assert(child1.includes("↑500") && child1.includes("↓110"), "a tool result's usage is summed with the assistant message's, once each: " + child1);
1712
+ assert(child1.includes("$0.05"), "the tool result's billed cost is summed too: " + child1);
1713
+ childBranch[1]!.message.usage = { input: 700, output: 60, cacheRead: 20, cost: { total: 0.05, totalFromProvider: true } }; // child finished, same branch length
1714
+ const scanAtBefore = usageScanAt;
1715
+ const child2 = getUsage(childCtx, id, id, true);
1716
+ assert(child2.includes("↑800") && !child2.includes("↑500"), "a tool result mutated in place: the delta is applied without a rescan (length unchanged): " + child2);
1717
+ assert(usageScanAt === scanAtBefore, "the tool-result tick took the in-place delta path, not a rescan");
1718
+ childBranch[1]!.message.usage = undefined; // a tool result without usage adds nothing
1719
+ usageScanAt = 0;
1720
+ usageScanLen = -1;
1721
+ const child3 = getUsage(childCtx, id, id, true);
1722
+ assert(child3.includes("↑100") && child3.includes("↓50") && !child3.includes("$0.05"), "a tool result without usage adds nothing: " + child3);
1723
+
1724
+ // Billed vs estimated in getUsage: a costless message is recomputed from models.json
1725
+ // (cache writes included) and shown next to the billed total, not folded into it.
1726
+ const costFixture = mkdtempSync(join(tmpdir(), "pi-arnative-cost-"));
1727
+ const prevCostDir = process.env.PI_CODING_AGENT_DIR;
1728
+ process.env.PI_CODING_AGENT_DIR = costFixture;
1729
+ writeFileSync(
1730
+ join(costFixture, "models.json"),
1731
+ JSON.stringify({ providers: { google: { models: [{ id: "m", cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 3 } }] } } }),
1732
+ );
1733
+ usageScanAt = 0;
1734
+ usageScanLen = -1;
1735
+ const mixedBranch: Array<{
1736
+ type: string;
1737
+ message: { role: string; provider?: string; model?: string; usage?: { input?: number; output?: number; cacheRead?: number; cacheWrite?: number; cost?: { total?: number; totalFromProvider?: boolean } } };
1738
+ }> = [
1739
+ { type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.3, totalFromProvider: true } } } },
1740
+ // No cost at all: 1M input at $1/M + 500k cache writes at $3/M = ~$2.50.
1741
+ { type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 1_000_000, output: 0, cacheRead: 0, cacheWrite: 500_000 } } },
1742
+ ];
1743
+ const mixedCtx = { sessionManager: { getBranch: () => mixedBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1744
+ const mixedCell = getUsage(mixedCtx, id, id, true);
1745
+ assert(mixedCell.includes("$0.30 + ~$2.50"), "a mixed branch shows the billed and estimated parts apart: " + mixedCell);
1746
+ usageScanAt = 0;
1747
+ usageScanLen = -1;
1748
+ const catalogBranch: typeof mixedBranch = [
1749
+ { type: "message", message: { role: "assistant", provider: "google", model: "m", usage: { input: 10, output: 5, cacheRead: 0, cacheWrite: 0, cost: { total: 0.12 } } } },
1750
+ ];
1751
+ const catalogCtx = { sessionManager: { getBranch: () => catalogBranch }, getContextUsage: () => undefined } as Parameters<typeof getUsage>[0];
1752
+ const catalogCell = getUsage(catalogCtx, id, id, true);
1753
+ assert(catalogCell.includes("~$0.12") && !catalogCell.includes("+"), "a catalog total (no totalFromProvider) is an estimate, marked ~: " + catalogCell);
1754
+ if (prevCostDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
1755
+ else process.env.PI_CODING_AGENT_DIR = prevCostDir;
1756
+ rmSync(costFixture, { recursive: true, force: true });
1374
1757
 
1375
1758
  // regression: a refresh arriving while one is in flight is re-run with the newest
1376
1759
  // cwd, not dropped (the footer's git state no longer stays stale until the next trigger).