12 +import { readdir, readFile }
from "node:fs/promises";
13 +import { dirname, join }
from "node:path";
15 + ExtensionCommandContext,
17 +}
from "@earendil-works/pi-coding-agent";
18 +import { DynamicBorder }
from "@earendil-works/pi-coding-agent";
27 +}
from "@earendil-works/pi-tui";
31 +interface TokenStats {
38 +interface BaseStats {
43 +interface ModelStats extends BaseStats {
44 + sessions
: Set<
string>;
46 +interface ProviderStats extends BaseStats {
47 + sessions
: Set<
string>;
48 + models
: Map<
string,
ModelStats>;
50 +interface TotalStats extends BaseStats {
58 +interface PeriodInsights {
59 + insights
: Insight[];
61 +interface RawMessage {
70 +interface ParsedMessage {
81 +interface ParsedSession {
83 + messages
: ParsedMessage[];
85 +interface PeriodRawData {
86 + messages
: RawMessage[];
87 + sessionCosts
: Map<
string,
number>;
89 +interface GlobalSessionSpan {
93 +interface TimeFilteredStats {
94 + providers
: Map<
string,
ProviderStats>;
96 + insights
: PeriodInsights;
98 +interface UsageData {
99 + today
: TimeFilteredStats;
100 + thisWeek
: TimeFilteredStats;
101 + lastWeek
: TimeFilteredStats;
102 + allTime
: TimeFilteredStats;
104 +type TabName = "today" | "thisWeek" | "lastWeek" | "allTime";
105 +type ViewMode = "table" | "insights";
109 +interface DataColumn {
113 + getValue: (stats
: BaseStats & { sessions
: Set<
string>
| number })
=> string;
116 +const SESSIONS_COL
: DataColumn = {
120 + formatNumber(
typeof s.sessions
=== "number" ? s.sessions
: s.sessions.
size),
122 +const MSGS_COL
: DataColumn = {
125 + getValue: (s)
=> formatNumber(s.messages),
127 +const COST_COL
: DataColumn = {
130 + getValue: (s)
=> formatCost(s.cost),
132 +const TOKENS_COL
: DataColumn = {
135 + getValue: (s)
=> formatTokens(s.tokens.total),
137 +const INPUT_COL
: DataColumn = {
141 + getValue: (s)
=> formatTokens(s.tokens.
input + s.tokens.cacheWrite),
143 +const OUTPUT_COL
: DataColumn = {
147 + getValue: (s)
=> formatTokens(s.tokens.output),
149 +const CACHE_COL
: DataColumn = {
153 + getValue: (s)
=> formatTokens(s.tokens.cacheRead
+ s.tokens.cacheWrite),
156 +const FULL_COLS
: DataColumn[]
= [
166 +interface TableLayout {
167 + columns
: DataColumn[];
169 + tableWidth
: number;
172 +const MAX_NAME_WIDTH
= 26;
174 +function getTableLayout(width
: number)
: TableLayout {
175 + const layouts
: Array<{
176 + columns
: DataColumn[];
180 + { columns: FULL_COLS, minName: MAX_NAME_WIDTH },
182 + columns: [SESSIONS_COL, MSGS_COL, COST_COL, TOKENS_COL],
187 + columns: [SESSIONS_COL, COST_COL, TOKENS_COL],
191 + { columns: [COST_COL, TOKENS_COL], minName:
10, compact:
true },
192 + { columns: [COST_COL], minName:
8, compact:
true },
194 + for (
const c
of layouts) {
195 + const colsWidth
= c.columns.
reduce((s, col)
=> s
+ col.
width,
0);
196 + const nameWidth
= Math.
min(MAX_NAME_WIDTH,
Math.
max(width
- colsWidth,
0));
197 + if (nameWidth
>= c.minName)
199 + columns: c.columns,
201 + tableWidth: nameWidth
+ colsWidth,
202 + compact:
!!c.
compact,
205 + const fallback
= layouts.
at(
-1);
206 + if (
!fallback)
throw new Error(
"usage layouts must not be empty");
207 + const fw
= fallback.columns.
reduce((s, col)
=> s
+ col.
width,
0);
209 + columns: fallback.columns,
210 + nameWidth:
Math.
min(MAX_NAME_WIDTH,
Math.
max(width
- fw,
0)),
218 +async function collectSessionFiles(
221 + signal
?: AbortSignal,
224 + const entries
= await readdir(dir, { withFileTypes:
true });
225 + for (
const entry
of entries) {
226 + if (signal?.aborted)
return;
227 + const p
= join(dir, entry.
name);
228 + if (entry.
isDirectory())
await collectSessionFiles(p, files, signal);
229 + else if (entry.
isFile()
&& entry.
name.
endsWith(
".jsonl")) files.
push(p);
236 +const YIELD_EVERY_N_LINES
= 500;
238 +async function parseSessionFile(
240 + seenHashes
: Set<
string>,
241 + signal
?: AbortSignal,
242 +)
: Promise<
ParsedSession | null> {
244 + const content
= await readFile(filePath,
"utf8");
245 + if (signal?.aborted)
return null;
247 + const lines
= content.
trim().
split(
"\n");
248 + const messages
: ParsedMessage[]
= [];
249 + let sessionId
= "";
251 + for (
let i
= 0; i
< lines.
length; i
++) {
252 + if (signal?.aborted)
return null;
253 + if (i
% YIELD_EVERY_N_LINES
=== 0)
254 + await new Promise<
void>((r)
=> setImmediate(r));
256 + const line
= lines[i];
257 + if (
!line?.
trim())
continue;
259 + const entry
= parseJsonLine(line);
260 + if (
!entry)
continue;
262 + if (entry.
type === "session") {
263 + sessionId
= entry.
id as string;
265 + entry.
type === "message" && 266 + (entry.message
as any)?.role
=== "assistant" 268 + const msg
= extractUsageMessage(
269 + entry.message
as Record<
string,
unknown>,
271 + if (
!msg)
continue;
272 + const hash
= `${msg.timestamp}:${msg.input + msg.output + msg.cacheRead + msg.cacheWrite}`;
273 + if (seenHashes.
has(hash))
continue;
274 + seenHashes.
add(hash);
275 + messages.
push(msg);
278 + return sessionId
? { sessionId, messages }
: null;
284 +function parseJsonLine(line
: string)
: Record<
string,
unknown>
| null {
286 + return JSON.
parse(line);
292 +function extractUsageMessage(
293 + msg
: Record<
string,
unknown>,
294 +)
: ParsedMessage | null {
295 + const usage
= msg.usage
as Record<
string,
number | undefined>
| undefined;
296 + if (
!usage
|| !msg.provider
|| !msg.model)
return null;
298 + const input
= usage.
input ?? 0;
299 + const output
= usage.output
?? 0;
300 + const cacheRead
= usage.cacheRead
?? 0;
301 + const cacheWrite
= usage.cacheWrite
?? 0;
302 + const cost
= (usage.cost
as Record<
string,
number>
| undefined)?.total
?? 0;
304 + const fallbackTs
= msg.timestamp
305 + ? new Date(msg.timestamp
as string).
getTime()
308 + (msg.timestamp
as number)
|| (
Number.
isNaN(fallbackTs)
? 0 : fallbackTs);
311 + provider: msg.provider
as string,
312 + model: msg.model
as string,
322 +function accumulateStats(
323 + target
: BaseStats & { sessions
: Set<
string>
| number },
326 + tokens
: TokenStats,
328 + if (target.sessions
instanceof Set) target.sessions.
add(sessionId);
330 + target.cost
+= cost;
331 + target.tokens.total
+= tokens.total;
332 + target.tokens.
input += tokens.
input;
333 + target.tokens.output
+= tokens.output;
334 + target.tokens.cacheRead
+= tokens.cacheRead;
335 + target.tokens.cacheWrite
+= tokens.cacheWrite;
338 +function emptyTokens()
: TokenStats {
339 + return { total:
0, input:
0, output:
0, cacheRead:
0, cacheWrite:
0 };
341 +function emptyTimeFiltered()
: TimeFilteredStats {
343 + providers:
new Map(),
344 + totals: { sessions:
0, messages:
0, cost:
0, tokens:
emptyTokens() },
345 + insights: { insights: [] },
348 +function emptyUsage()
: UsageData {
350 + today:
emptyTimeFiltered(),
351 + thisWeek:
emptyTimeFiltered(),
352 + lastWeek:
emptyTimeFiltered(),
353 + allTime:
emptyTimeFiltered(),
357 +const TAB_ORDER
: TabName[]
= [
"today",
"thisWeek",
"lastWeek",
"allTime"];
359 +function getPeriods(
363 + lastWeekMs
: number,
365 + const periods
: TabName[]
= [
"allTime"];
366 + if (ts
>= todayMs) periods.
push(
"today");
367 + if (ts
>= weekMs) periods.
push(
"thisWeek");
368 + else if (ts
>= lastWeekMs) periods.
push(
"lastWeek");
372 +async function collectUsageData(
373 + sessionDir
: string,
374 + signal
?: AbortSignal,
375 +)
: Promise<
UsageData | null> {
376 + const startOfToday
= new Date();
377 + startOfToday.
setHours(
0,
0,
0,
0);
378 + const todayMs
= startOfToday.
getTime();
379 + const startOfWeek
= new Date();
380 + const dow
= startOfWeek.
getDay();
381 + startOfWeek.
setDate(startOfWeek.
getDate()
- (dow
=== 0 ? 6 : dow
- 1));
382 + startOfWeek.
setHours(
0,
0,
0,
0);
383 + const weekMs
= startOfWeek.
getTime();
384 + const startOfLastWeek
= new Date(startOfWeek);
385 + startOfLastWeek.
setDate(startOfLastWeek.
getDate()
- 7);
386 + const lastWeekMs
= startOfLastWeek.
getTime();
388 + const data
= emptyUsage();
389 + const rawByPeriod
: Record<
TabName,
PeriodRawData>
= {
390 + today: { messages: [], sessionCosts:
new Map() },
391 + thisWeek: { messages: [], sessionCosts:
new Map() },
392 + lastWeek: { messages: [], sessionCosts:
new Map() },
393 + allTime: { messages: [], sessionCosts:
new Map() },
395 + const globalSessionSpans
= new Map<
string,
GlobalSessionSpan>();
397 + const files
: string[]
= [];
400 + await collectSessionFiles(
dirname(sessionDir), files, signal);
401 + if (signal?.aborted)
return null;
402 + const seenHashes
= new Set<
string>();
404 + for (
const filePath
of files) {
405 + if (signal?.aborted)
return null;
406 + const parsed
= await parseSessionFile(filePath, seenHashes, signal);
407 + if (
!parsed)
continue;
409 + for (
const msg
of parsed.messages) {
410 + if (msg.timestamp
> 0) {
411 + const span
= globalSessionSpans.
get(parsed.sessionId);
413 + globalSessionSpans.
set(parsed.sessionId, {
414 + startMs: msg.timestamp,
415 + endMs: msg.timestamp,
418 + if (msg.timestamp
< span.startMs) span.startMs
= msg.timestamp;
419 + if (msg.timestamp
> span.endMs) span.endMs
= msg.timestamp;
423 + const periods
= getPeriods(msg.timestamp, todayMs, weekMs, lastWeekMs);
425 + total: msg.
input + msg.output
+ msg.cacheWrite,
427 + output: msg.output,
428 + cacheRead: msg.cacheRead,
429 + cacheWrite: msg.cacheWrite,
432 + for (
const period
of periods) {
433 + const stats
= data[period];
434 + let providerStats
= stats.providers.
get(msg.provider);
435 + if (
!providerStats) {
437 + sessions:
new Set(),
440 + tokens:
emptyTokens(),
443 + stats.providers.
set(msg.provider, providerStats);
445 + let modelStats
= providerStats.models.
get(msg.model);
448 + sessions:
new Set(),
451 + tokens:
emptyTokens(),
453 + providerStats.models.
set(msg.model, modelStats);
456 + modelStats.sessions.
add(parsed.sessionId);
457 + accumulateStats(modelStats, parsed.sessionId, msg.cost, tokens);
458 + accumulateStats(providerStats, parsed.sessionId, msg.cost, tokens);
459 + accumulateStats(stats.totals, parsed.sessionId, msg.cost, tokens);
460 + rawByPeriod[period].messages.
push({
461 + sessionId: parsed.sessionId,
462 + timestamp: msg.timestamp,
465 + cacheRead: msg.cacheRead,
466 + cacheWrite: msg.cacheWrite,
468 + rawByPeriod[period].sessionCosts.
set(
470 + (rawByPeriod[period].sessionCosts.
get(parsed.sessionId)
?? 0)
+ 475 + await new Promise<
void>((r)
=> setImmediate(r));
479 + const longSessionIds
= new Set<
string>();
480 + for (
const [id, span]
of globalSessionSpans) {
481 + if (span.endMs
- span.startMs
>= LONG_SESSION_MS) longSessionIds.
add(id);
483 + for (
const period
of TAB_ORDER)
484 + data[period].insights
= computeInsights(
485 + rawByPeriod[period],
494 +const PARALLEL_WINDOW_MS
= 2 * 60_000;
495 +const PARALLEL_THRESHOLD
= 4;
496 +const LARGE_CONTEXT
= 150_000;
497 +const LARGE_UNCACHED
= 100_000;
498 +const LONG_SESSION_MS
= 8 * 60 * 60 * 1000;
500 +const MIN_MSG_PARALLEL
= 10;
502 +function computeInsights(
503 + raw
: PeriodRawData,
504 + longSessionIds
: Set<
string>,
506 + if (
!raw.messages.
length)
return { insights: [] };
507 + const total
= raw.messages.
reduce((s, m)
=> s
+ m.cost,
0);
508 + if (total
<= 0)
return { insights: [] };
510 + const candidates
: Insight[]
= [];
513 + const timed
= raw.messages.
filter((m)
=> m.timestamp
> 0);
515 + timed.
length >= MIN_MSG_PARALLEL
&& 516 + new Set(timed.
map((m)
=> m.sessionId)).
size >= PARALLEL_THRESHOLD
518 + const sorted
= timed.
slice().
sort((a, b)
=> a.timestamp
- b.timestamp);
519 + const sidCount
= new Map<
string,
number>();
524 + for (
const cur
of sorted) {
526 + right
< sorted.
length && 527 + sorted[right]?.timestamp
<= cur.timestamp
+ PARALLEL_WINDOW_MS
529 + const sid
= sorted[right]?.sessionId;
530 + const n
= (sidCount.
get(sid)
?? 0)
+ 1;
531 + sidCount.
set(sid, n);
532 + if (n
=== 1) unique
++;
537 + sorted[left]?.timestamp
< cur.timestamp
- PARALLEL_WINDOW_MS
539 + const sid
= sorted[left]?.sessionId;
540 + const n
= (sidCount.
get(sid)
?? 0)
- 1;
542 + sidCount.
delete(sid);
544 + }
else sidCount.
set(sid, n);
547 + if (unique
>= PARALLEL_THRESHOLD) parallelCost
+= cur.cost;
549 + if (parallelCost
> 0)
551 + percent: (parallelCost
/ total)
* 100,
552 + headline:
`of cost was while ${PARALLEL_THRESHOLD}+ sessions ran in parallel`,
553 + advice:
"Queueing sessions uses capacity more evenly.",
558 + const largeCtxW
= raw.messages
559 + .
filter((m)
=> m.
input + m.cacheRead
+ m.cacheWrite
> LARGE_CONTEXT)
560 + .
reduce((s, m)
=> s
+ m.cost,
0);
563 + percent: (largeCtxW
/ total)
* 100,
564 + headline:
`of cost was at >${Math.round(LARGE_CONTEXT / 1000)}k context`,
565 + advice:
"/compact mid-task, /clear when switching tasks.",
569 + const uncachedW
= raw.messages
570 + .
filter((m)
=> m.
input + m.cacheWrite
> LARGE_UNCACHED)
571 + .
reduce((s, m)
=> s
+ m.cost,
0);
574 + percent: (uncachedW
/ total)
* 100,
575 + headline:
`of cost came from >${Math.round(LARGE_UNCACHED / 1000)}k-token uncached prompts`,
576 + advice:
"/compact before stepping away keeps the cold-start small.",
580 + const longW
= raw.messages
581 + .
filter((m)
=> longSessionIds.
has(m.sessionId))
582 + .
reduce((s, m)
=> s
+ m.cost,
0);
585 + percent: (longW
/ total)
* 100,
586 + headline:
`of cost came from ${Math.round(LONG_SESSION_MS / 3600_000)}h+ sessions`,
587 + advice:
"Continuous usage can add up quickly.",
591 + if (raw.sessionCosts.
size > TOP_N) {
592 + const sorted
= Array.
from(raw.sessionCosts.
values()).
sort((a, b)
=> b
- a);
593 + const topW
= sorted.
slice(
0, TOP_N).
reduce((s, c)
=> s
+ c,
0);
595 + percent: (topW
/ total)
* 100,
596 + headline:
`of cost from top ${TOP_N} sessions`,
597 + advice:
"A small number of sessions drives most spend.",
602 + insights: candidates
603 + .
filter((i)
=> i.percent
>= 1)
604 + .
sort((a, b)
=> b.percent
- a.percent),
610 +function formatCost(c
: number)
: string {
611 + if (c
=== 0)
return "-";
612 + if (c
< 0.01)
return `$${c.toFixed(4)}`;
613 + if (c
< 10)
return `$${c.toFixed(2)}`;
614 + if (c
< 100)
return `$${c.toFixed(1)}`;
615 + return `$${Math.round(c)}`;
618 +function formatTokens(n
: number)
: string {
619 + if (n
=== 0)
return "-";
620 + if (n
< 1_000)
return n.
toString();
621 + if (n
< 10_000)
return `${(n / 1_000).toFixed(1)}k`;
622 + if (n
< 1_000_000)
return `${Math.round(n / 1_000)}k`;
623 + if (n
< 10_000_000)
return `${(n / 1_000_000).toFixed(1)}M`;
624 + return `${Math.round(n / 1_000_000)}M`;
627 +function formatNumber(n
: number)
: string {
628 + return n
=== 0 ? "-" : n.
toLocaleString();
631 +function padLeft(s
: string, len
: number)
: string {
632 + const v
= visibleWidth(s);
633 + return v
>= len
? s
: " ".
repeat(len
- v)
+ s;
636 +function padRight(s
: string, len
: number)
: string {
637 + const v
= visibleWidth(s);
638 + return v
>= len
? s
: s
+ " ".
repeat(len
- v);
644 + align
: "left" | "right" = "left",
646 + return align
=== "right" 647 + ? padLeft(
truncateToWidth(s, len), len)
648 + : padRight(
truncateToWidth(s, len), len);
651 +function pickFitting(w
: number, variants
: string[])
: string {
652 + for (
const v
of variants)
if (
visibleWidth(v)
<= w)
return v;
653 + return variants[variants.
length - 1]
|| "";
656 +function formatPct(p
: number)
: string {
657 + return p
>= 10 ? `${Math.round(p)}%` : `${Math.round(p * 10) / 10}%`;
662 +const TAB_LABELS
: Record<
TabName,
string>
= {
664 + thisWeek:
"This Week",
665 + lastWeek:
"Last Week",
666 + allTime:
"All Time",
669 +class UsageComponent {
670 + private activeTab
: TabName = "allTime";
671 + private viewMode
: ViewMode = "table";
672 + private data
: UsageData;
673 + private selectedIndex
= 0;
674 + private expanded
= new Set<
string>();
675 + private providerOrder
: string[]
= [];
676 + private theme
: Theme;
677 + private requestRender: ()
=> void;
678 + private done: ()
=> void;
683 + requestRender: ()
=> void,
686 + this.theme
= theme;
688 + this.requestRender
= requestRender;
690 + this.
updateProviderOrder();
693 + private updateProviderOrder() {
694 + const stats
= this.
data[this.activeTab];
695 + this.providerOrder
= Array.
from(stats.providers.
entries())
696 + .
sort((a, b)
=> b[
1].cost
- a[
1].cost)
698 + this.
selectedIndex = Math.
min(
699 + this.
selectedIndex,
700 + Math.
max(
0, this.providerOrder.
length - 1),
704 + handleInput(data
: string)
: void {
705 + if (
matchesKey(data,
"escape")
|| matchesKey(data,
"q")) {
709 + if (
matchesKey(data,
"v")) {
710 + this.viewMode
= this.viewMode
=== "table" ? "insights" : "table";
711 + this.
requestRender();
714 + if (
matchesKey(data,
"tab")
|| matchesKey(data,
"right")) {
715 + const idx
= TAB_ORDER.
indexOf(this.activeTab);
717 + TAB_ORDER[(idx
+ 1)
% TAB_ORDER.
length]
?? this.activeTab;
718 + this.
updateProviderOrder();
719 + this.
requestRender();
720 + }
else if (
matchesKey(data,
"shift+tab")
|| matchesKey(data,
"left")) {
721 + const idx
= TAB_ORDER.
indexOf(this.activeTab);
723 + TAB_ORDER[(idx
- 1 + TAB_ORDER.
length)
% TAB_ORDER.
length]
?? 725 + this.
updateProviderOrder();
726 + this.
requestRender();
727 + }
else if (this.viewMode
=== "table" && matchesKey(data,
"up")) {
728 + if (this.
selectedIndex > 0) {
729 + this.
selectedIndex--;
730 + this.
requestRender();
732 + }
else if (this.viewMode
=== "table" && matchesKey(data,
"down")) {
733 + if (this.
selectedIndex < this.providerOrder.
length - 1) {
734 + this.
selectedIndex++;
735 + this.
requestRender();
738 + this.viewMode
=== "table" && 739 + (
matchesKey(data,
"enter")
|| matchesKey(data,
"space"))
741 + const p
= this.providerOrder[this.
selectedIndex];
743 + this.expanded.
has(p)
? this.expanded.
delete(p)
: this.expanded.
add(p);
744 + this.
requestRender();
749 + render(width
: number)
: string[] {
750 + return this.viewMode
=== "insights" 751 + ? this.
renderInsightsView(width)
752 + : this.
renderTableView(width);
755 + private renderInsightsView(width
: number)
: string[] {
756 + const th
= this.theme;
757 + const stats
= this.
data[this.activeTab];
758 + const lines
: string[]
= [];
759 + lines.
push(th.
fg(
"accent", th.
bold(
"Usage Insights")),
"");
763 + `What's contributing to your cost? ${TAB_LABELS[this.activeTab]} · weighted by USD`,
767 + if (
!stats.totals.messages) {
768 + lines.
push(th.
fg(
"dim",
" No usage for this period."),
"");
769 + }
else if (
!stats.totals.cost) {
770 + lines.
push(th.
fg(
"dim",
" No cost data."),
"");
771 + }
else if (
!stats.insights.insights.
length) {
772 + lines.
push(th.
fg(
"dim",
" No insights above 1%."),
"");
774 + for (
const insight
of stats.insights.insights) {
776 + `${th.fg("accent", th.bold(formatPct(insight.percent)))} ${insight.headline}`,
778 + for (
const w
of wrapTextWithAnsi(
780 + Math.
max(width
- 5,
30),
782 + lines.
push(
` ${th.fg("dim", w)}`);
789 + pickFitting(width, [
790 + "[Tab/←→] period [v] table [q] close",
795 + return lines.
map((l)
=> truncateToWidth(l, width));
798 + private renderTableView(width
: number)
: string[] {
799 + const th
= this.theme;
800 + const stats
= this.
data[this.activeTab];
801 + const layout
= getTableLayout(width);
802 + const lines
: string[]
= [];
805 + const tabs
= TAB_ORDER.
map((t)
=> 806 + t
=== this.activeTab
807 + ? th.
fg(
"accent",
`[${TAB_LABELS[t]}]`)
808 + : th.
fg(
"dim",
` ${TAB_LABELS[t]} `),
811 + pickFitting(width, [
813 + th.
fg(
"accent",
`[${TAB_LABELS[this.activeTab]}]`),
816 + if (layout.
compact)
818 + ...wrapTextWithAnsi(
819 + th.
fg(
"dim",
"Compact view. Widen terminal for more columns."),
820 + Math.
max(width,
1),
826 + let headerLine
= fitCell(
"Provider / Model", layout.nameWidth);
827 + for (
const col
of layout.columns)
828 + headerLine
+= col.dimmed
829 + ? th.
fg(
"dim",
fitCell(col.
label, col.
width,
"right"))
830 + : fitCell(col.
label, col.
width,
"right");
831 + lines.
push(th.
fg(
"muted", headerLine));
832 + lines.
push(th.
fg(
"border",
"─".
repeat(layout.tableWidth)));
835 + if (
!this.providerOrder.
length) {
836 + lines.
push(th.
fg(
"dim",
" No usage data"));
838 + for (
let i
= 0; i
< this.providerOrder.
length; i
++) {
839 + const name
= this.providerOrder[i];
840 + if (
!name)
continue;
841 + const prov
= stats.providers.
get(name);
842 + if (
!prov)
continue;
843 + const sel
= i
=== this.
selectedIndex;
844 + const exp
= this.expanded.
has(name);
846 + ? th.
fg(
"accent",
`${exp ? "▾" : "▸"} `)
847 + : th.
fg(
"dim",
`${exp ? "▾" : "▸"} `);
849 + this.
row(name, prov, layout, { prefix: arrow, selected: sel }),
852 + for (
const [mn, ms]
of Array.
from(prov.models.
entries()).
sort(
853 + (a, b)
=> b[
1].cost
- a[
1].cost,
855 + lines.
push(this.
row(mn, ms, layout, { indent:
4, dimAll:
true }));
861 + lines.
push(th.
fg(
"border",
"─".
repeat(layout.tableWidth)));
862 + let totalRow
= fitCell(th.
bold(
"Total"), layout.nameWidth);
863 + for (
const col
of layout.columns)
864 + totalRow
+= col.dimmed
865 + ? th.
fg(
"dim",
fitCell(col.
getValue(stats.totals), col.
width,
"right"))
866 + : fitCell(col.
getValue(stats.totals), col.
width,
"right");
867 + lines.
push(totalRow);
873 + pickFitting(width, [
874 + "Tokens = In + Out + CacheWrite · ↑In = In + CacheWrite (v0.2.0+)",
875 + "Incl. CacheWrite (v0.2.0+)",
882 + pickFitting(width, [
883 + "[Tab/←→] period [↑↓] select [Enter] expand [v] insights [q] close",
884 + "[↑↓] select [v] insights [q] close",
889 + return lines.
map((l)
=> truncateToWidth(l, width));
894 + stats
: BaseStats & { sessions
: Set<
string>
| number },
895 + layout
: TableLayout,
899 + selected
?: boolean;
903 + const th
= this.theme;
904 + const { indent
= 0, selected
= false, dimAll
= false }
= opts;
905 + const rawPrefix
= opts.
prefix ?? " ".
repeat(indent);
906 + const prefixW
= visibleWidth(
truncateToWidth(rawPrefix, layout.nameWidth));
907 + const innerW
= Math.
max(layout.nameWidth
- prefixW,
0);
908 + const truncName
= innerW
> 0 ? truncateToWidth(name, innerW)
: "";
909 + const styledName
= selected
910 + ? th.
fg(
"accent", truncName)
912 + ? th.
fg(
"dim", truncName)
914 + let row
= rawPrefix
+ (innerW
> 0 ? padRight(styledName, innerW)
: "");
915 + for (
const col
of layout.columns) {
916 + const v
= fitCell(col.
getValue(stats), col.
width,
"right");
917 + row
+= col.dimmed
|| dimAll
? th.
fg(
"dim", v)
: v;
922 + invalidate()
: void {}
926 +export async function showUsage(
928 + ctx
: ExtensionCommandContext,
930 + if (
!ctx.hasUI)
return;
932 + const data
= await ctx.ui.
custom<
UsageData | null>(
933 + (tui, theme, _kb, done)
=> {
934 + const loader
= new CancellableLoader(
936 + (s)
=> theme.
fg(
"accent", s),
937 + (s)
=> theme.
fg(
"muted", s),
938 + "Loading Usage...",
940 + let finished
= false;
941 + const finish = (v
: UsageData | null)
=> {
942 + if (finished)
return;
947 + loader.
onAbort = ()
=> finish(
null);
948 + collectUsageData(ctx.sessionManager.
getSessionDir(), loader.signal)
950 + .
catch(()
=> finish(
null));
957 + await ctx.ui.
custom<
void>((tui, theme, _kb, done)
=> {
958 + const container
= new Container();
959 + container.
addChild(
new Spacer(
1));
960 + container.
addChild(
new DynamicBorder((s
: string)
=> theme.
fg(
"border", s)));
961 + container.
addChild(
new Spacer(
1));
962 + const usage
= new UsageComponent(
965 + ()
=> tui.
requestRender(),
969 + render: (w
: number)
=> {
970 + const border
= container.
render(w).
map((l)
=> truncateToWidth(l, w));
973 + ...usage.
render(w),
975 + theme.
fg(
"border",
"─".
repeat(w)),
976 + ].
map((l)
=> truncateToWidth(l, w));
978 + invalidate: ()
=> container.
invalidate(),
979 + handleInput: (input
: string)
=> usage.
handleInput(input),