@erichll/pi-statusline 0.9.0 → 0.11.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/CHANGELOG.md +19 -0
- package/README.md +4 -3
- package/examples/statusline.json +4 -0
- package/package.json +4 -4
- package/src/config.ts +3 -2
- package/src/index.ts +2 -2
- package/src/render.ts +14 -5
- package/src/runtime.ts +8 -2
- package/src/session.ts +21 -1
- package/src/types.ts +11 -1
- package/src/usage.ts +35 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.11.0 - 2026-11-20
|
|
4
|
+
|
|
5
|
+
- Add a `speed` segment, enabled by default, that shows the `service_tier` of
|
|
6
|
+
the latest provider request (`fast` for `priority`, `Ultra Fast` for
|
|
7
|
+
`ultrafast`, `flex`). It is read from the outgoing payload, so it shows what
|
|
8
|
+
was actually requested; it works with CLIProxyAPI's `/fast` and `/ultrafast`
|
|
9
|
+
modes, which the replaced built-in footer could no longer label. It is hidden
|
|
10
|
+
until a request carries a tier, and cleared on a model switch. Existing
|
|
11
|
+
segment lists gain it before `context` unless they list it explicitly.
|
|
12
|
+
|
|
13
|
+
## 0.10.0 - 2026-11-03
|
|
14
|
+
|
|
15
|
+
- Mark the cost segment when the summed USD total is a catalog estimate or
|
|
16
|
+
mixes an estimate with a provider-reported bill (`0.012~`). Totals Pi
|
|
17
|
+
reports as billed, and totals recorded before `totalFromProvider` existed,
|
|
18
|
+
stay unmarked.
|
|
19
|
+
- Verify the type check and the full statusline test suite against Pi 1.5.0.
|
|
20
|
+
The peer floor stays `>=1.4.0`.
|
|
21
|
+
|
|
3
22
|
## 0.9.0 - 2026-10-28
|
|
4
23
|
|
|
5
24
|
- Raise the development and peer baseline to Pi 1.4.0. Older Pi peer versions
|
package/README.md
CHANGED
|
@@ -81,6 +81,7 @@ Available segments:
|
|
|
81
81
|
| ID | Data | Default |
|
|
82
82
|
| --- | --- | --- |
|
|
83
83
|
| `model`, `thinking` | Model and colored `(level)` suffix | On |
|
|
84
|
+
| `speed` | Service tier of the latest provider request: `fast` (`priority`), `Ultra Fast` (`ultrafast`) or `flex`; hidden when the request carried none or before the first request after a model switch | On |
|
|
84
85
|
| `context` | Current context usage | On |
|
|
85
86
|
| `quota` | Subscription Usage and reset countdowns; hidden without data | On |
|
|
86
87
|
| `directory` | Current directory | On |
|
|
@@ -88,14 +89,14 @@ Available segments:
|
|
|
88
89
|
| `session` | Time since the session was created, on the bottom row | On |
|
|
89
90
|
| `toolTotal` | Tool calls recorded in the whole session (` 128`), on the bottom row; hidden at zero | On |
|
|
90
91
|
| `tokens` | Cumulative session tokens, on the bottom row | On |
|
|
91
|
-
| `cost` | Pi-recorded cumulative USD cost | Off |
|
|
92
|
+
| `cost` | Pi-recorded cumulative USD cost. A trailing `~` means the total is a catalog estimate, or mixes an estimate with a provider-reported bill | Off |
|
|
92
93
|
| `input`, `output`, `cacheRead`, `cacheWrite` | Individual session token counters | Off |
|
|
93
94
|
| `statuses` | Other extensions' text, at the end of the bottom row | On |
|
|
94
95
|
|
|
95
96
|
`segments` is an ordered array of
|
|
96
97
|
`{ id, enabled, icon?, color?, iconColor?, background? }`. Omitted segments are
|
|
97
|
-
disabled, **except `quota`, `session` and `toolTotal`**: old configurations automatically
|
|
98
|
-
gain `quota` after `context`, and `session` and `toolTotal` before `tokens` (or at the end when
|
|
98
|
+
disabled, **except `quota`, `speed`, `session` and `toolTotal`**: old configurations automatically
|
|
99
|
+
gain `quota` after `context`, `speed` before `context`, and `session` and `toolTotal` before `tokens` (or at the end when
|
|
99
100
|
the anchor is absent). To keep one off, include it with `"enabled": false`.
|
|
100
101
|
|
|
101
102
|
Colors accept `#RRGGBB` or supported Pi theme tokens such as `accent`, `muted`,
|
package/examples/statusline.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@erichll/pi-statusline",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "Configurable Pi statusline with live preview, Git and session usage",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
"@earendil-works/pi-tui": ">=1.4.0"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"@earendil-works/pi-ai": "^1.
|
|
26
|
-
"@earendil-works/pi-coding-agent": "^1.
|
|
27
|
-
"@earendil-works/pi-tui": "^1.
|
|
25
|
+
"@earendil-works/pi-ai": "^1.5.0",
|
|
26
|
+
"@earendil-works/pi-coding-agent": "^1.5.0",
|
|
27
|
+
"@earendil-works/pi-tui": "^1.5.0",
|
|
28
28
|
"@types/node": "^26.6.5",
|
|
29
29
|
"typescript": "^7.0.2"
|
|
30
30
|
}
|
package/src/config.ts
CHANGED
|
@@ -10,7 +10,7 @@ export function validColor(value: unknown): value is ColorValue {
|
|
|
10
10
|
return typeof value === "string" && (/^#[\da-f]{6}$/i.test(value) || (COLORS as readonly string[]).includes(value));
|
|
11
11
|
}
|
|
12
12
|
export function presetConfig(): StatuslineConfig {
|
|
13
|
-
const enabled = new Set<string>(["model", "thinking", "directory", "git", "context", "quota", "session", "toolTotal", "tokens", "statuses"]);
|
|
13
|
+
const enabled = new Set<string>(["model", "thinking", "speed", "directory", "git", "context", "quota", "session", "toolTotal", "tokens", "statuses"]);
|
|
14
14
|
return {
|
|
15
15
|
version: 1, enabled: true, preset: "powerline", icons: "nerd",
|
|
16
16
|
separator: "powerline", pathMode: "basename", modelDisplay: "name", contextDisplay: "bar", spacing: 1,
|
|
@@ -80,13 +80,14 @@ export function parseConfig(raw: unknown): StatuslineConfig {
|
|
|
80
80
|
return result;
|
|
81
81
|
});
|
|
82
82
|
// Upgrade older lists once with segments added later; an explicit entry (including disabled) wins.
|
|
83
|
-
const insert = (id: "quota" | "session" | "toolTotal", index: number) => {
|
|
83
|
+
const insert = (id: "quota" | "speed" | "session" | "toolTotal", index: number) => {
|
|
84
84
|
if (seen.has(id)) return;
|
|
85
85
|
config.segments.splice(index < 0 ? config.segments.length : index, 0, { id, enabled: true });
|
|
86
86
|
seen.add(id);
|
|
87
87
|
};
|
|
88
88
|
const contextIndex = config.segments.findIndex((segment) => segment.id === "context");
|
|
89
89
|
insert("quota", contextIndex < 0 ? -1 : contextIndex + 1);
|
|
90
|
+
insert("speed", config.segments.findIndex((segment) => segment.id === "context"));
|
|
90
91
|
insert("session", config.segments.findIndex((segment) => segment.id === "tokens"));
|
|
91
92
|
insert("toolTotal", config.segments.findIndex((segment) => segment.id === "tokens"));
|
|
92
93
|
// All other omissions remain editable but disabled.
|
package/src/index.ts
CHANGED
|
@@ -25,7 +25,7 @@ export default function statusline(pi: ExtensionAPI): void {
|
|
|
25
25
|
session.install();
|
|
26
26
|
});
|
|
27
27
|
pi.on("session_shutdown", () => { generation++; session?.dispose(); session = undefined; });
|
|
28
|
-
pi.on("before_provider_request", (
|
|
28
|
+
pi.on("before_provider_request", (event, ctx) => { session?.setContext(ctx); session?.beginProviderRequest(event.payload); });
|
|
29
29
|
pi.on("after_provider_response", (event, ctx) => { session?.setContext(ctx); session?.observeProviderResponse(event.headers); });
|
|
30
30
|
pi.on("provider_stream_event", (event, ctx) => {
|
|
31
31
|
if (!session?.active) return;
|
|
@@ -61,7 +61,7 @@ export default function statusline(pi: ExtensionAPI): void {
|
|
|
61
61
|
const resetLive = (event: unknown, ctx: ExtensionContext) => { session?.setLive(undefined); refresh(event, ctx); };
|
|
62
62
|
pi.on("agent_end", resetLive);
|
|
63
63
|
pi.on("turn_end", (event, ctx) => { if (event.message.role === "assistant") session?.runtime.message(event.message, true); session?.runtime.turnEnd(); refresh(event, ctx); });
|
|
64
|
-
pi.on("model_select", (event, ctx) => { session?.quota.clear(); refresh(event, ctx); });
|
|
64
|
+
pi.on("model_select", (event, ctx) => { session?.quota.clear(); session?.clearServiceTier(); refresh(event, ctx); });
|
|
65
65
|
pi.on("thinking_level_select", refresh);
|
|
66
66
|
pi.on("session_compact", (event, ctx) => {
|
|
67
67
|
session?.compaction.finish("success", event.compactionEntry.id); session?.runtime.compaction(false); resetLive(event, ctx);
|
package/src/render.ts
CHANGED
|
@@ -13,11 +13,11 @@ export type RenderTheme = Pick<Theme, "style" | "colors" | "appearance">;
|
|
|
13
13
|
// Keep rainbow hues independent of semantic theme colors, which can repeat.
|
|
14
14
|
const THINKING_RAINBOW = ["#c084fc", "#f472b6", "#fb923c", "#facc15", "#4ade80", "#22d3ee", "#60a5fa"].map((value) => parseColor(value));
|
|
15
15
|
const ICONS: Record<StatuslineConfig["icons"], Partial<Record<SegmentId, string>>> = {
|
|
16
|
-
unicode: { model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", session: "◷", toolTotal: "⚒", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
|
|
17
|
-
nerd: { model: "", directory: "", git: "", context: "", quota: "", cost: "$", input: "↑", output: "↓", session: "", toolTotal: "", tokens: "", cacheRead: "R", cacheWrite: "W" },
|
|
18
|
-
ascii: { model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", session: "ses:", toolTotal: "tool:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
|
|
16
|
+
unicode: { speed: "⚡", model: "", directory: "▸", git: "⑂", context: "◉", cost: "$", input: "↑", output: "↓", session: "◷", toolTotal: "⚒", tokens: "Σ", cacheRead: "R", cacheWrite: "W" },
|
|
17
|
+
nerd: { speed: "\uf0e7", model: "", directory: "", git: "", context: "", quota: "", cost: "$", input: "↑", output: "↓", session: "", toolTotal: "", tokens: "", cacheRead: "R", cacheWrite: "W" },
|
|
18
|
+
ascii: { speed: "", model: "", directory: "", git: "git:", context: "ctx:", cost: "$", input: "in:", output: "out:", session: "ses:", toolTotal: "tool:", tokens: "tok:", cacheRead: "R:", cacheWrite: "W:" },
|
|
19
19
|
};
|
|
20
|
-
const DROP_ORDER: SegmentId[] = ["cost", "cacheWrite", "cacheRead", "output", "input", "thinking", "git", "directory"];
|
|
20
|
+
const DROP_ORDER: SegmentId[] = ["cost", "speed", "cacheWrite", "cacheRead", "output", "input", "thinking", "git", "directory"];
|
|
21
21
|
export function formatTokens(value: number): string {
|
|
22
22
|
if (value < 1000) return String(Math.round(value));
|
|
23
23
|
const divisor = value >= 1e6 ? 1e6 : 1000;
|
|
@@ -64,11 +64,16 @@ function gitText(data: StatuslineSnapshot, ascii: boolean): string | undefined {
|
|
|
64
64
|
if (git.behind) bits.push(`${ascii ? "v" : "↓"}${git.behind}`);
|
|
65
65
|
return bits.join(" ");
|
|
66
66
|
}
|
|
67
|
+
/** Service tiers worth showing; `default`, `auto` and unknown values stay hidden. */
|
|
68
|
+
function speedLabel(tier: string | undefined): string | undefined {
|
|
69
|
+
return tier === "priority" ? "fast" : tier === "ultrafast" ? "Ultra Fast" : tier === "flex" ? "flex" : undefined;
|
|
70
|
+
}
|
|
67
71
|
function segmentText(id: SegmentId, data: StatuslineSnapshot, config: StatuslineConfig): string | undefined {
|
|
68
72
|
const usage = data.usage;
|
|
69
73
|
switch (id) {
|
|
70
74
|
case "model": return (config.modelDisplay === "last" ? data.modelId.split("/").filter(Boolean).at(-1) : undefined) || data.model || "No model";
|
|
71
75
|
case "thinking": return undefined; // Its settings now control the model's suffix.
|
|
76
|
+
case "speed": return speedLabel(data.serviceTier);
|
|
72
77
|
case "directory": return displayPath(data, config.pathMode);
|
|
73
78
|
case "git": return gitText(data, config.icons === "ascii");
|
|
74
79
|
case "context": {
|
|
@@ -80,7 +85,10 @@ function segmentText(id: SegmentId, data: StatuslineSnapshot, config: Statusline
|
|
|
80
85
|
case "quota": return renderQuota(data.quota, config.icons === "ascii");
|
|
81
86
|
case "session": return data.sessionMinutes === null ? undefined : formatSessionAge(data.sessionMinutes);
|
|
82
87
|
case "toolTotal": return data.toolCalls > 0 ? String(data.toolCalls) : undefined;
|
|
83
|
-
case "cost":
|
|
88
|
+
case "cost": {
|
|
89
|
+
const amount = usage.cost.toFixed(3);
|
|
90
|
+
return usage.costProvenance === "estimated" || usage.costProvenance === "mixed" ? `${amount}~` : amount;
|
|
91
|
+
}
|
|
84
92
|
case "input": return formatTokens(usage.input);
|
|
85
93
|
case "output": return formatTokens(usage.output);
|
|
86
94
|
case "tokens": return formatTokens(usage.input + usage.output + usage.cacheRead + usage.cacheWrite);
|
|
@@ -107,6 +115,7 @@ function defaultColor(id: SegmentId, data: StatuslineSnapshot): ColorValue {
|
|
|
107
115
|
const colors: Record<string, ColorValue> = { off: "thinkingOff", minimal: "thinkingMinimal", low: "thinkingLow", medium: "thinkingMedium", high: "thinkingHigh", xhigh: "thinkingXhigh", max: "thinkingMax" };
|
|
108
116
|
return colors[data.thinking] ?? "muted";
|
|
109
117
|
}
|
|
118
|
+
if (id === "speed") return "warning";
|
|
110
119
|
if (id === "model") return "accent";
|
|
111
120
|
if (id === "directory") return "success";
|
|
112
121
|
if (id === "context") return "#c678dd";
|
package/src/runtime.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { AssistantMessage, AssistantMessageEvent } from "@earendil-works/pi
|
|
|
3
3
|
import type { AgentActivityOutcome } from "@earendil-works/pi-coding-agent";
|
|
4
4
|
import { cleanText } from "./text.ts";
|
|
5
5
|
import { toolTarget } from "./tools.ts";
|
|
6
|
-
import { emptyUsage, readUsage } from "./usage.ts";
|
|
6
|
+
import { emptyUsage, mergeCostProvenance, readUsage } from "./usage.ts";
|
|
7
7
|
import type { UsageTotals } from "./types.ts";
|
|
8
8
|
|
|
9
9
|
export type Clock = () => number;
|
|
@@ -131,7 +131,13 @@ export class RuntimeState {
|
|
|
131
131
|
const hidden = !retainSummary && !this.running;
|
|
132
132
|
const elapsedMs = hidden || !this.runId ? 0 : Math.max(0, (this.running ? now : this.endMs) - this.startMs);
|
|
133
133
|
const usage = !hidden && this.messages.size ? emptyUsage() : null;
|
|
134
|
-
if (usage)
|
|
134
|
+
if (usage) {
|
|
135
|
+
for (const contribution of this.messages.values()) {
|
|
136
|
+
usage.input += contribution.input; usage.output += contribution.output;
|
|
137
|
+
usage.cacheRead += contribution.cacheRead; usage.cacheWrite += contribution.cacheWrite; usage.cost += contribution.cost;
|
|
138
|
+
usage.costProvenance = mergeCostProvenance(usage.costProvenance, contribution.costProvenance);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
135
141
|
const denominator = usage ? usage.input + usage.cacheRead + usage.cacheWrite : 0;
|
|
136
142
|
return {
|
|
137
143
|
runId: hidden ? null : this.runId, status: hidden ? "Idle" : this.state, elapsedMs,
|
package/src/session.ts
CHANGED
|
@@ -17,6 +17,13 @@ export function sessionStart(timestamp: string | undefined, now = Date.now()): n
|
|
|
17
17
|
return Number.isFinite(ms) && ms <= now + 60000 ? ms : null;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
/** The request's `service_tier`, when it is a short plain token. */
|
|
21
|
+
export function serviceTierOf(payload: unknown): string | undefined {
|
|
22
|
+
if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return undefined;
|
|
23
|
+
const tier = (payload as { service_tier?: unknown }).service_tier;
|
|
24
|
+
return typeof tier === "string" && /^[\w.-]{1,32}$/.test(tier) ? tier.toLowerCase() : undefined;
|
|
25
|
+
}
|
|
26
|
+
|
|
20
27
|
export class FooterSession {
|
|
21
28
|
readonly runtime = new RuntimeState();
|
|
22
29
|
readonly compaction = new CompactionState();
|
|
@@ -39,6 +46,7 @@ export class FooterSession {
|
|
|
39
46
|
private sessionStartMs: number | null = null;
|
|
40
47
|
private toolCalls = 0;
|
|
41
48
|
private skills: string[] = [];
|
|
49
|
+
private serviceTier: string | undefined;
|
|
42
50
|
private readonly gitReader: GitReader | undefined;
|
|
43
51
|
private readonly commands: () => readonly SlashCommandInfo[];
|
|
44
52
|
private signal: AbortSignal | undefined;
|
|
@@ -49,7 +57,18 @@ export class FooterSession {
|
|
|
49
57
|
}
|
|
50
58
|
get active(): boolean { return this.ownsFooter && !this.closed; }
|
|
51
59
|
setContext(ctx: ExtensionContext): void { this.ctx = ctx; this.quota.select(ctx.model); this.watchSignal(); }
|
|
52
|
-
beginProviderRequest(): void {
|
|
60
|
+
beginProviderRequest(payload?: unknown): void {
|
|
61
|
+
if (!this.active) return;
|
|
62
|
+
this.quota.beginRequest(this.ctx.model);
|
|
63
|
+
// The tier is read from the outgoing payload, so it reflects what was actually requested.
|
|
64
|
+
this.setServiceTier(serviceTierOf(payload));
|
|
65
|
+
}
|
|
66
|
+
/** Forget the observed tier, e.g. after a model switch, until the next request reports it. */
|
|
67
|
+
clearServiceTier(): void { this.setServiceTier(undefined); }
|
|
68
|
+
private setServiceTier(tier: string | undefined): void {
|
|
69
|
+
if (tier === this.serviceTier) return;
|
|
70
|
+
this.serviceTier = tier; this.schedule(true);
|
|
71
|
+
}
|
|
53
72
|
observeProviderResponse(headers: Record<string, string>): void {
|
|
54
73
|
if (!this.active) return;
|
|
55
74
|
this.quota.response(headers, this.ctx.model); this.schedule(true);
|
|
@@ -156,6 +175,7 @@ export class FooterSession {
|
|
|
156
175
|
thinking: this.ctx.thinkingLevel ?? "off", cwd: this.ctx.cwd, home: homedir(),
|
|
157
176
|
context: this.context, usage: this.usage.snapshot(), quota: this.quota.snapshot(this.ctx.model), git: this.git,
|
|
158
177
|
statuses: this.provider?.getExtensionStatuses() ?? new Map(),
|
|
178
|
+
...(this.serviceTier ? { serviceTier: this.serviceTier } : {}),
|
|
159
179
|
// Minute resolution keeps an idle footer from repainting every second.
|
|
160
180
|
sessionMinutes: this.sessionStartMs === null ? null : Math.floor(Math.max(0, Date.now() - this.sessionStartMs) / 60000),
|
|
161
181
|
toolCalls: this.toolCalls, skills: this.skills,
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { ThemeColor } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
|
|
3
|
-
export const SEGMENT_IDS = ["model", "thinking", "context", "quota", "directory", "git", "cost", "input", "output", "session", "toolTotal", "tokens", "cacheRead", "cacheWrite", "statuses"] as const;
|
|
3
|
+
export const SEGMENT_IDS = ["model", "thinking", "speed", "context", "quota", "directory", "git", "cost", "input", "output", "session", "toolTotal", "tokens", "cacheRead", "cacheWrite", "statuses"] as const;
|
|
4
4
|
export type SegmentId = typeof SEGMENT_IDS[number];
|
|
5
5
|
export type ColorValue = ThemeColor | `#${string}`;
|
|
6
6
|
export type Preset = "powerline";
|
|
@@ -44,12 +44,20 @@ export interface StatuslineConfig {
|
|
|
44
44
|
segments: SegmentConfig[];
|
|
45
45
|
runtime: RuntimeConfig;
|
|
46
46
|
}
|
|
47
|
+
/** Where a summed USD total came from. `unknown` is Pi before 1.5, or a cost with no flag. */
|
|
48
|
+
export type CostProvenance = "provider" | "estimated" | "mixed" | "unknown";
|
|
47
49
|
export interface UsageTotals {
|
|
48
50
|
input: number;
|
|
49
51
|
output: number;
|
|
50
52
|
cacheRead: number;
|
|
51
53
|
cacheWrite: number;
|
|
52
54
|
cost: number;
|
|
55
|
+
/**
|
|
56
|
+
* `unknown` keeps the historical unmarked display. It does not combine with
|
|
57
|
+
* a later flag: only a real estimate, or both an estimate and a provider bill,
|
|
58
|
+
* mark the total.
|
|
59
|
+
*/
|
|
60
|
+
costProvenance: CostProvenance;
|
|
53
61
|
}
|
|
54
62
|
export interface GitState {
|
|
55
63
|
kind: "repository" | "none" | "unknown";
|
|
@@ -74,6 +82,8 @@ export interface StatuslineSnapshot {
|
|
|
74
82
|
quota?: import("./quota.ts").QuotaSnapshot;
|
|
75
83
|
git: GitState;
|
|
76
84
|
statuses: ReadonlyMap<string, string>;
|
|
85
|
+
/** `service_tier` of the latest provider request (`priority`, `ultrafast`, ...); undefined when it carried none. */
|
|
86
|
+
serviceTier?: string;
|
|
77
87
|
/** Whole minutes since the session file was created; null when unknown. */
|
|
78
88
|
sessionMinutes: number | null;
|
|
79
89
|
/** Completed tool calls recorded in the session file, across all runs. */
|
package/src/usage.ts
CHANGED
|
@@ -1,14 +1,33 @@
|
|
|
1
1
|
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
2
|
import type { SessionEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
-
import type { UsageTotals } from "./types.ts";
|
|
3
|
+
import type { CostProvenance, UsageTotals } from "./types.ts";
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
const NUMERIC_KEYS = ["input", "output", "cacheRead", "cacheWrite", "cost"] as const;
|
|
6
|
+
export function emptyUsage(): UsageTotals {
|
|
7
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, costProvenance: "unknown" };
|
|
8
|
+
}
|
|
6
9
|
const finite = (value: unknown): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
10
|
+
function costProvenance(cost: unknown): CostProvenance {
|
|
11
|
+
if (!cost || typeof cost !== "object") return "unknown";
|
|
12
|
+
const flag = (cost as Record<string, unknown>).totalFromProvider;
|
|
13
|
+
if (flag === true) return "provider";
|
|
14
|
+
if (flag === false) return "estimated";
|
|
15
|
+
return "unknown";
|
|
16
|
+
}
|
|
17
|
+
/** `unknown` is the identity, so missing flags do not mark an otherwise uniform total. */
|
|
18
|
+
export function mergeCostProvenance(current: CostProvenance, next: CostProvenance): CostProvenance {
|
|
19
|
+
if (next === "unknown" || current === next) return current;
|
|
20
|
+
if (current === "unknown") return next;
|
|
21
|
+
return "mixed";
|
|
22
|
+
}
|
|
7
23
|
export function readUsage(value: unknown): UsageTotals {
|
|
8
24
|
if (!value || typeof value !== "object") return emptyUsage();
|
|
9
25
|
const usage = value as Record<string, unknown>;
|
|
10
26
|
const cost = usage.cost && typeof usage.cost === "object" ? (usage.cost as Record<string, unknown>).total : 0;
|
|
11
|
-
return {
|
|
27
|
+
return {
|
|
28
|
+
input: finite(usage.input), output: finite(usage.output), cacheRead: finite(usage.cacheRead), cacheWrite: finite(usage.cacheWrite),
|
|
29
|
+
cost: finite(cost), costProvenance: costProvenance(usage.cost),
|
|
30
|
+
};
|
|
12
31
|
}
|
|
13
32
|
export function entryUsage(entry: SessionEntry): UsageTotals {
|
|
14
33
|
if (entry.type === "usage" || entry.type === "compaction" || entry.type === "branch_summary") return readUsage(entry.usage);
|
|
@@ -16,7 +35,12 @@ export function entryUsage(entry: SessionEntry): UsageTotals {
|
|
|
16
35
|
return emptyUsage();
|
|
17
36
|
}
|
|
18
37
|
function add(target: UsageTotals, value: UsageTotals, sign = 1): void {
|
|
19
|
-
for (const key of
|
|
38
|
+
for (const key of NUMERIC_KEYS) target[key] += sign * value[key];
|
|
39
|
+
}
|
|
40
|
+
function provenanceOf(parts: Iterable<UsageTotals>): CostProvenance {
|
|
41
|
+
let result: CostProvenance = "unknown";
|
|
42
|
+
for (const part of parts) result = mergeCostProvenance(result, part.costProvenance);
|
|
43
|
+
return result;
|
|
20
44
|
}
|
|
21
45
|
function messageKey(message: AssistantMessage): string { return `${message.provider}/${message.model}/${message.timestamp}`; }
|
|
22
46
|
|
|
@@ -46,7 +70,13 @@ export class UsageCache {
|
|
|
46
70
|
setLive(message: AssistantMessage | undefined): void { this.live = message; }
|
|
47
71
|
snapshot(): UsageTotals {
|
|
48
72
|
const total = { ...this.totals };
|
|
49
|
-
|
|
73
|
+
const parts = [...this.contributions.values()];
|
|
74
|
+
if (this.live && !this.persistedMessages.has(messageKey(this.live))) {
|
|
75
|
+
const live = readUsage(this.live.usage);
|
|
76
|
+
add(total, live);
|
|
77
|
+
parts.push(live);
|
|
78
|
+
}
|
|
79
|
+
total.costProvenance = provenanceOf(parts);
|
|
50
80
|
return total;
|
|
51
81
|
}
|
|
52
82
|
}
|