@luxass/pi-cost-explorer 0.0.0-stage → 0.1.0

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/src/format.ts ADDED
@@ -0,0 +1,131 @@
1
+ import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
+
3
+ export function money(value: number): string {
4
+ if (value === 0) return "$0";
5
+ const abs = Math.abs(value);
6
+ if (abs < 0.0001) return "<$0.0001";
7
+ if (abs < 0.01) return `$${value.toFixed(4)}`;
8
+ if (abs < 1) return `$${value.toFixed(3)}`;
9
+ if (abs < 1000) return `$${value.toFixed(2)}`;
10
+ return `$${Math.round(value).toLocaleString("en-US")}`;
11
+ }
12
+
13
+ export function tokens(value: number): string {
14
+ if (value < 1000) return String(value);
15
+ if (value < 1_000_000) return `${trimZero((value / 1000).toFixed(1))}k`;
16
+ return `${trimZero((value / 1_000_000).toFixed(2))}M`;
17
+ }
18
+
19
+ function trimZero(text: string): string {
20
+ return text.replace(/\.0+$/, "").replace(/(\.\d*?)0+$/, "$1");
21
+ }
22
+
23
+ export function percent(fraction: number | undefined): string {
24
+ if (fraction === undefined || !Number.isFinite(fraction)) return "–";
25
+ const value = fraction * 100;
26
+ if (value > 0 && value < 10) return `${value.toFixed(1)}%`;
27
+ return `${Math.round(value)}%`;
28
+ }
29
+
30
+ export function duration(ms: number): string {
31
+ const seconds = Math.round(ms / 1000);
32
+ if (seconds < 60) return `${seconds}s`;
33
+ const minutes = Math.floor(seconds / 60);
34
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
35
+ const hours = Math.floor(minutes / 60);
36
+ if (hours < 24) return `${hours}h ${minutes % 60}m`;
37
+ return `${Math.floor(hours / 24)}d ${hours % 24}h`;
38
+ }
39
+
40
+ function pad(value: number): string {
41
+ return String(value).padStart(2, "0");
42
+ }
43
+
44
+ export function clock(timestamp: number): string {
45
+ if (!timestamp) return "--:--";
46
+ const date = new Date(timestamp);
47
+ return `${pad(date.getHours())}:${pad(date.getMinutes())}`;
48
+ }
49
+
50
+ const EIGHTHS = ["", "▏", "▎", "▍", "▌", "▋", "▊", "▉"];
51
+
52
+ /** A horizontal bar with eighth-cell precision. */
53
+ export function bar(fraction: number, width: number): string {
54
+ if (width <= 0) return "";
55
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0));
56
+ const eighths = Math.round(clamped * width * 8);
57
+ const full = Math.floor(eighths / 8);
58
+ const partial = EIGHTHS[eighths % 8] ?? "";
59
+ return "█".repeat(full) + partial;
60
+ }
61
+
62
+ const SPARKS = ["▁", "▂", "▃", "▄", "▅", "▆", "▇", "█"];
63
+
64
+ /** Groups values into at most `width` buckets and draws their sums. */
65
+ export function sparkline(values: readonly number[], width: number): string {
66
+ if (values.length === 0 || width <= 0) return "";
67
+ const buckets = Math.min(width, values.length);
68
+ const sums = Array.from({ length: buckets }, () => 0);
69
+ values.forEach((value, index) => {
70
+ const bucket = Math.min(buckets - 1, Math.floor((index * buckets) / values.length));
71
+ sums[bucket]! += value;
72
+ });
73
+ const peak = Math.max(...sums);
74
+ if (peak <= 0) return SPARKS[0]!.repeat(buckets);
75
+ return sums
76
+ .map((sum) => SPARKS[Math.min(SPARKS.length - 1, Math.floor((sum / peak) * SPARKS.length))]!)
77
+ .join("");
78
+ }
79
+
80
+ /** Truncates or pads text to exactly `width` visible columns. */
81
+ export function fit(text: string, width: number, align: "left" | "right" = "left"): string {
82
+ if (width <= 0) return "";
83
+ const clipped = truncateToWidth(text, width, "…");
84
+ const padding = " ".repeat(Math.max(0, width - visibleWidth(clipped)));
85
+ return align === "right" ? padding + clipped : clipped + padding;
86
+ }
87
+
88
+ export function plural(count: number, word: string): string {
89
+ return `${count} ${word}${count === 1 ? "" : "s"}`;
90
+ }
91
+
92
+ export interface Column<Row> {
93
+ header: string;
94
+ /** Omit for the one flexible column that takes the remaining width. */
95
+ width?: number;
96
+ align?: "left" | "right";
97
+ /** Optional columns are removed, last first, until the table fits. */
98
+ optional?: boolean;
99
+ cell: (row: Row) => string;
100
+ }
101
+
102
+ const GAP = " ";
103
+
104
+ /** Lays out rows as aligned columns that fit `width`. */
105
+ export function table<Row>(
106
+ columns: readonly Column<Row>[],
107
+ rows: readonly Row[],
108
+ width: number,
109
+ ): { header: string; lines: string[] } {
110
+ const shown = [...columns];
111
+ const fixedWidth = (flexWidth: number) =>
112
+ shown.reduce((sum, column) => sum + (column.width ?? flexWidth) + GAP.length, -GAP.length);
113
+
114
+ while (fixedWidth(12) > width) {
115
+ const index = shown.findLastIndex((column) => column.optional);
116
+ if (index === -1) break;
117
+ shown.splice(index, 1);
118
+ }
119
+
120
+ const flexWidth = Math.max(1, width - fixedWidth(0));
121
+ const line = (text: (column: Column<Row>) => string) =>
122
+ fit(
123
+ shown.map((column) => fit(text(column), column.width ?? flexWidth, column.align)).join(GAP),
124
+ width,
125
+ );
126
+
127
+ return {
128
+ header: line((column) => column.header),
129
+ lines: rows.map((row) => line((column) => column.cell(row))),
130
+ };
131
+ }
package/src/index.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import { analyze } from "./analysis";
4
+ import { CostDialog } from "./dialog";
5
+
6
+ export default function (pi: ExtensionAPI) {
7
+ pi.registerCommand("cost", {
8
+ description: "Explore this session's cost by model, prompt, tool, and request",
9
+ handler: async (_args, ctx) => {
10
+ if (ctx.mode !== "tui") {
11
+ ctx.ui.notify("/cost needs Pi's terminal interface.", "error");
12
+ return;
13
+ }
14
+
15
+ // These listeners belong to this dialog. They are removed when it closes.
16
+ const unsubscribe: Array<() => void> = [];
17
+
18
+ try {
19
+ await ctx.ui.custom<void>(
20
+ (tui, theme, keybindings, done) => {
21
+ const dialog = new CostDialog({
22
+ tui,
23
+ theme,
24
+ keybindings,
25
+ load: (onlyCurrentBranch) => {
26
+ const branch = ctx.sessionManager.getBranch();
27
+ const branchIds = new Set(branch.map((entry) => entry.id));
28
+ const entries = onlyCurrentBranch ? branch : ctx.sessionManager.getEntries();
29
+ return analyze(entries, branchIds);
30
+ },
31
+ done,
32
+ });
33
+
34
+ // Saved entries are complete by the time a turn ends.
35
+ unsubscribe.push(
36
+ pi.on("turn_end", () => dialog.refresh()),
37
+ pi.on("agent_end", () => dialog.refresh()),
38
+ pi.on("session_shutdown", () => dialog.close()),
39
+ );
40
+
41
+ return dialog;
42
+ },
43
+ {
44
+ overlay: true,
45
+ overlayOptions: {
46
+ anchor: "center",
47
+ width: 110,
48
+ minWidth: 50,
49
+ maxHeight: "85%",
50
+ margin: 2,
51
+ },
52
+ },
53
+ );
54
+ } finally {
55
+ for (const stop of unsubscribe) stop();
56
+ }
57
+ },
58
+ });
59
+ }