@bismawy/pi-arnative 0.16.1 → 0.18.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.
- package/README.md +25 -16
- package/extensions/index.ts +41 -0
- package/lib/active-clock.ts +91 -0
- package/lib/ansi.ts +40 -78
- package/lib/box.ts +49 -68
- package/lib/chatbox.ts +371 -0
- package/lib/color.ts +3 -31
- package/lib/compat.ts +0 -60
- package/lib/edit-diff.ts +199 -0
- package/{extensions → lib/features}/arnative.ts +96 -423
- package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -327
- package/{extensions → lib/features}/budget.ts +17 -242
- package/lib/features/footer.ts +2232 -0
- package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
- package/{extensions → lib/features}/model-heal.ts +5 -28
- package/lib/features/progress-group.ts +1691 -0
- package/{extensions → lib/features}/render-cache.ts +391 -218
- package/{extensions → lib/features}/timestamps.ts +18 -94
- package/{extensions → lib/features}/todos.ts +44 -158
- package/lib/features/tools.ts +1202 -0
- package/lib/features/ui-render-tweaks.ts +606 -0
- package/lib/features/usage.ts +786 -0
- package/lib/format.ts +22 -4
- package/lib/git-status.ts +164 -0
- package/lib/list-picker.ts +1 -127
- package/lib/model-heal.ts +70 -162
- package/lib/patch.ts +0 -63
- package/lib/preset-store.ts +17 -133
- package/lib/provider-store.ts +573 -0
- package/lib/provider.ts +52 -851
- package/lib/runtime.ts +209 -0
- package/lib/shortcuts.ts +8 -58
- package/lib/spinner.ts +88 -162
- package/lib/status-widget.ts +4 -30
- package/lib/todos.ts +20 -143
- package/lib/usage-pricing.ts +143 -0
- package/lib/usage-store.ts +44 -378
- package/package.json +48 -49
- package/themes/arnative-blossom.json +0 -0
- package/themes/arnative-crimson.json +0 -0
- package/themes/arnative-cyberpunk.json +0 -0
- package/themes/arnative-dracula.json +0 -0
- package/themes/arnative-earthy.json +0 -0
- package/themes/arnative-garden.json +0 -0
- package/themes/arnative-gruvbox.json +0 -0
- package/themes/arnative-lemonade.json +0 -0
- package/themes/arnative-magical.json +0 -0
- package/themes/arnative-matrix.json +0 -0
- package/themes/arnative-neutral.json +0 -0
- package/themes/arnative-nord.json +0 -0
- package/themes/arnative-zinc.json +0 -0
- package/themes/arnative.json +0 -0
- package/CHANGELOG.md +0 -683
- package/extensions/animations.ts +0 -242
- package/extensions/footer.ts +0 -2617
- package/extensions/tools.ts +0 -2231
- package/extensions/ui-render-tweaks.ts +0 -1005
- package/extensions/usage-export.ts +0 -283
- package/extensions/usage.ts +0 -1406
- package/lib/check.ts +0 -21
- package/themes/gen-themes.mjs +0 -715
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Arnative Usage Dashboard (/usage): table UI + the /usage command.
|
|
3
|
+
* Data layer (session scan + cache + aggregation) lives in lib/usage-store.ts —
|
|
4
|
+
* shared with the Model tab.
|
|
5
|
+
*/
|
|
6
|
+
import { getAgentDir, type ExtensionAPI, type ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
+
import { renameSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { matchesKey, truncateToWidth, visibleWidth, type Component, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
|
|
10
|
+
import { renderScreen, screenTitle } from "../box.ts";
|
|
11
|
+
import { capitalize } from "../format.ts";
|
|
12
|
+
import { thinkingColorOf, softOf, softSecondaryOf } from "../ansi.ts";
|
|
13
|
+
import { writeAtomicSync } from "../preset-store.ts";
|
|
14
|
+
import { legendUsage, matchesBack, RESET_USAGE, UNDO_USAGE } from "../shortcuts.ts";
|
|
15
|
+
import { collectUsageSummary, formatTokens, hasPrice, loadPriceTable, markUsageDirty, resetUsageStats, restoreUsageStats, USAGE_RANGES, type UsageRange, type UsageSummary } from "../usage-store.ts";
|
|
16
|
+
|
|
17
|
+
export function formatCost(n: number): string {
|
|
18
|
+
if (!n || n <= 0) return "-";
|
|
19
|
+
if (n < 0.01) return "<$0.01";
|
|
20
|
+
if (n < 1000) {
|
|
21
|
+
// Rounding at the boundary used to print "$1000.00" instead of "$1.0k".
|
|
22
|
+
const s = n.toFixed(2);
|
|
23
|
+
return s === "1000.00" ? "$1.0k" : `$${s}`;
|
|
24
|
+
}
|
|
25
|
+
return `$${(n / 1000).toFixed(1)}k`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatCount(n: number): string {
|
|
29
|
+
return n > 0 ? n.toLocaleString("en-US") : "-";
|
|
30
|
+
}
|
|
31
|
+
// =============================================================================
|
|
32
|
+
// /usage TUI component
|
|
33
|
+
// =============================================================================
|
|
34
|
+
|
|
35
|
+
interface RowItem {
|
|
36
|
+
type: "project" | "provider" | "model" | "price";
|
|
37
|
+
/** Set on project rows, and on the provider rows nested under one in Project view. */
|
|
38
|
+
projectName?: string;
|
|
39
|
+
providerName: string;
|
|
40
|
+
modelName?: string;
|
|
41
|
+
label: string;
|
|
42
|
+
sessions: number;
|
|
43
|
+
msgs: number;
|
|
44
|
+
tokens: number;
|
|
45
|
+
input: number;
|
|
46
|
+
output: number;
|
|
47
|
+
cacheRead: number;
|
|
48
|
+
/** Billed cost only; the estimate stays in `estimatedCost`. */
|
|
49
|
+
cost: number;
|
|
50
|
+
/** Catalog totals plus the price-table reconstruction when `cost` is 0 — shown with a `~`. */
|
|
51
|
+
estimatedCost: number;
|
|
52
|
+
expanded?: boolean;
|
|
53
|
+
/** Prices view only: the $/1M rates declared in models.json. */
|
|
54
|
+
rates?: { in: number; out: number; cacheRead: number; cacheWrite: number };
|
|
55
|
+
/** Prices view only: a model used in the sessions but absent from the price table. */
|
|
56
|
+
unpriced?: boolean;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The stat columns every row shares; each view only adds its type, label and nesting. */
|
|
60
|
+
const statsOf = (
|
|
61
|
+
s: { sessions: number; msgs: number; totalTokens: number; input: number; output: number; cacheRead: number; cost: number; estimatedCost: number },
|
|
62
|
+
): Pick<RowItem, "sessions" | "msgs" | "tokens" | "input" | "output" | "cacheRead" | "cost" | "estimatedCost"> => ({
|
|
63
|
+
sessions: s.sessions,
|
|
64
|
+
msgs: s.msgs,
|
|
65
|
+
tokens: s.totalTokens,
|
|
66
|
+
input: s.input,
|
|
67
|
+
output: s.output,
|
|
68
|
+
cacheRead: s.cacheRead,
|
|
69
|
+
cost: s.cost,
|
|
70
|
+
estimatedCost: s.estimatedCost,
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
/** The dashboard views, cycled by `v`: Provider → Project → Prices. */
|
|
74
|
+
type UsageView = "provider" | "project" | "prices";
|
|
75
|
+
|
|
76
|
+
/** Labels on the range bar, in tab order. */
|
|
77
|
+
const RANGE_LABELS: Record<UsageRange, string> = { all: "All", today: "Today", "7d": "7 day", "30d": "30 day" };
|
|
78
|
+
/** The three views `v` cycles, in that order, and the view a press would show next. */
|
|
79
|
+
const VIEW_LABELS: Record<UsageView, string> = { provider: "Provider", project: "Project", prices: "Prices" };
|
|
80
|
+
const NEXT_VIEW: Record<UsageView, UsageView> = { provider: "project", project: "prices", prices: "provider" };
|
|
81
|
+
/** Data rows on screen at once: five reads as a table, sixteen pushed the Total row off. */
|
|
82
|
+
const USAGE_VIEWPORT = 5;
|
|
83
|
+
|
|
84
|
+
export class UsageModalComponent implements Component {
|
|
85
|
+
private expandedProviders = new Set<string>();
|
|
86
|
+
private expandedProjects = new Set<string>();
|
|
87
|
+
private view: UsageView = "provider";
|
|
88
|
+
private selectedIndex = 0;
|
|
89
|
+
private summary: UsageSummary;
|
|
90
|
+
/** Which window the numbers cover. `all` keeps the old dashboard's meaning. */
|
|
91
|
+
private range: UsageRange = "all";
|
|
92
|
+
/** Tab hitboxes of the last render: column span of each range on the bar line. */
|
|
93
|
+
private tabHitboxes: { line: number; start: number; end: number; range: UsageRange }[] = [];
|
|
94
|
+
|
|
95
|
+
private theme: { fg(c: string, t: string): string; bold?(t: string): string };
|
|
96
|
+
private onDone: (back: boolean) => void;
|
|
97
|
+
private requestRender: () => void;
|
|
98
|
+
/** Painter for the box border's thinking slot, probed once so a theme without
|
|
99
|
+
* `thinking*` falls back to dim. */
|
|
100
|
+
private edgeOf: (s: string) => string;
|
|
101
|
+
/** Row layout of the last render: which table row sits on which screen line. */
|
|
102
|
+
private rowHitboxes: { line: number; index: number }[] = [];
|
|
103
|
+
/** A destructive step waits here until the user answers it. Nothing is touched before. */
|
|
104
|
+
private confirmStep: "reset" | "undo" | null = null;
|
|
105
|
+
/** One line under the table, stating what the last reset changed. */
|
|
106
|
+
private notice: string | null = null;
|
|
107
|
+
/** A wrapper keeps the first reset undoable when no previous baseline existed. */
|
|
108
|
+
private undoBaseline: { previous: string | null } | null = null;
|
|
109
|
+
|
|
110
|
+
constructor(
|
|
111
|
+
theme: { fg(c: string, t: string): string; bold?(t: string): string },
|
|
112
|
+
/** Leave the dashboard. `true` when the user asked to go back (`←`), false for a plain close. */
|
|
113
|
+
onDone: (back: boolean) => void,
|
|
114
|
+
requestRender: () => void,
|
|
115
|
+
thinkingLevel?: string,
|
|
116
|
+
) {
|
|
117
|
+
this.theme = theme;
|
|
118
|
+
this.onDone = onDone;
|
|
119
|
+
this.requestRender = requestRender;
|
|
120
|
+
this.edgeOf = thinkingColorOf(theme, thinkingLevel);
|
|
121
|
+
this.summary = collectUsageSummary(true, this.range);
|
|
122
|
+
// Default: expand the first provider when there is one
|
|
123
|
+
if (this.summary.providers.length > 0) {
|
|
124
|
+
this.expandedProviders.add(this.summary.providers[0]!.name);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
invalidate(): void {}
|
|
129
|
+
|
|
130
|
+
dispose(): void {}
|
|
131
|
+
|
|
132
|
+
private buildFlatRows(): RowItem[] {
|
|
133
|
+
const rows: RowItem[] = [];
|
|
134
|
+
if (this.view === "prices") {
|
|
135
|
+
// Every models.json pair, grouped under its provider like the Provider view: a tree
|
|
136
|
+
// opened one provider at a time. Inside a group the cheapest input rate comes first,
|
|
137
|
+
// and a used model the table does not price ends its group marked `unpriced`.
|
|
138
|
+
const table = loadPriceTable();
|
|
139
|
+
const groups = new Map<string, RowItem[]>();
|
|
140
|
+
const addTo = (provider: string, row: RowItem): void => {
|
|
141
|
+
const list = groups.get(provider) ?? [];
|
|
142
|
+
list.push(row);
|
|
143
|
+
groups.set(provider, list);
|
|
144
|
+
};
|
|
145
|
+
for (const [provider, models] of Object.entries(table)) {
|
|
146
|
+
for (const [model, r] of Object.entries(models)) {
|
|
147
|
+
addTo(provider, {
|
|
148
|
+
type: "price",
|
|
149
|
+
providerName: provider,
|
|
150
|
+
modelName: model,
|
|
151
|
+
label: model,
|
|
152
|
+
sessions: 0,
|
|
153
|
+
msgs: 0,
|
|
154
|
+
tokens: 0,
|
|
155
|
+
input: 0,
|
|
156
|
+
output: 0,
|
|
157
|
+
cacheRead: 0,
|
|
158
|
+
cost: 0,
|
|
159
|
+
estimatedCost: 0,
|
|
160
|
+
rates: { in: r.input ?? 0, out: r.output ?? 0, cacheRead: r.cacheRead ?? 0, cacheWrite: r.cacheWrite ?? 0 },
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
for (const p of this.summary.providers) {
|
|
165
|
+
for (const m of p.models) {
|
|
166
|
+
// `models.json` holds the user's custom rates only: a built-in model has no entry
|
|
167
|
+
// yet still reports a cost, so it is priced, not unpriced. Only a model that
|
|
168
|
+
// shows `-` in the table (no rate, no cost) belongs here.
|
|
169
|
+
if (hasPrice(p.name, m.name, table) || m.cost > 0 || m.estimatedCost > 0) continue;
|
|
170
|
+
addTo(p.name, {
|
|
171
|
+
type: "price",
|
|
172
|
+
providerName: p.name,
|
|
173
|
+
modelName: m.name,
|
|
174
|
+
label: m.name,
|
|
175
|
+
...statsOf(m),
|
|
176
|
+
unpriced: true,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const cheapest = (list: RowItem[]): number => Math.min(...list.map((r) => r.rates?.in ?? Number.POSITIVE_INFINITY));
|
|
181
|
+
const ordered = [...groups.entries()].sort((a, b) => cheapest(a[1]) - cheapest(b[1]) || a[0].localeCompare(b[0]));
|
|
182
|
+
for (const [provider, models] of ordered) {
|
|
183
|
+
const isExpanded = this.expandedProviders.has(provider);
|
|
184
|
+
rows.push({
|
|
185
|
+
type: "provider",
|
|
186
|
+
providerName: provider,
|
|
187
|
+
label: capitalize(provider),
|
|
188
|
+
sessions: 0,
|
|
189
|
+
msgs: 0,
|
|
190
|
+
tokens: 0,
|
|
191
|
+
input: 0,
|
|
192
|
+
output: 0,
|
|
193
|
+
cacheRead: 0,
|
|
194
|
+
cost: 0,
|
|
195
|
+
estimatedCost: 0,
|
|
196
|
+
expanded: isExpanded,
|
|
197
|
+
});
|
|
198
|
+
if (!isExpanded) continue;
|
|
199
|
+
models.sort((a, b) => (a.rates?.in ?? Number.POSITIVE_INFINITY) - (b.rates?.in ?? Number.POSITIVE_INFINITY) || a.label.localeCompare(b.label));
|
|
200
|
+
for (const row of models) rows.push(row);
|
|
201
|
+
}
|
|
202
|
+
return rows;
|
|
203
|
+
}
|
|
204
|
+
if (this.view === "project") {
|
|
205
|
+
// Same grid and columns as the Provider view, one level up: Project → Provider.
|
|
206
|
+
for (const proj of this.summary.projects) {
|
|
207
|
+
const isExpanded = this.expandedProjects.has(proj.name);
|
|
208
|
+
rows.push({
|
|
209
|
+
type: "project",
|
|
210
|
+
projectName: proj.name,
|
|
211
|
+
providerName: proj.name,
|
|
212
|
+
label: proj.name,
|
|
213
|
+
...statsOf(proj),
|
|
214
|
+
expanded: isExpanded,
|
|
215
|
+
});
|
|
216
|
+
if (!isExpanded) continue;
|
|
217
|
+
for (const p of proj.providers) {
|
|
218
|
+
rows.push({
|
|
219
|
+
type: "provider",
|
|
220
|
+
projectName: proj.name,
|
|
221
|
+
providerName: p.name,
|
|
222
|
+
label: capitalize(p.name),
|
|
223
|
+
...statsOf(p),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return rows;
|
|
228
|
+
}
|
|
229
|
+
for (const p of this.summary.providers) {
|
|
230
|
+
const isExpanded = this.expandedProviders.has(p.name);
|
|
231
|
+
rows.push({
|
|
232
|
+
type: "provider",
|
|
233
|
+
providerName: p.name,
|
|
234
|
+
// No marker in the label: the row gutter draws the expand arrow, so a selected
|
|
235
|
+
// provider does not end up with two arrows on one line. Capitalized to match the
|
|
236
|
+
// detail line and the model rows beneath it.
|
|
237
|
+
label: capitalize(p.name),
|
|
238
|
+
...statsOf(p),
|
|
239
|
+
expanded: isExpanded,
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
if (isExpanded) {
|
|
243
|
+
for (const m of p.models) {
|
|
244
|
+
rows.push({
|
|
245
|
+
type: "model",
|
|
246
|
+
providerName: p.name,
|
|
247
|
+
modelName: m.name,
|
|
248
|
+
label: m.name,
|
|
249
|
+
...statsOf(m),
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return rows;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private toggleRow(row: RowItem | undefined): boolean {
|
|
258
|
+
if (!row) return false;
|
|
259
|
+
if (row.type === "project") {
|
|
260
|
+
if (this.expandedProjects.has(row.projectName!)) this.expandedProjects.delete(row.projectName!);
|
|
261
|
+
else this.expandedProjects.add(row.projectName!);
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
if (row.type !== "provider") return false;
|
|
265
|
+
if (this.expandedProviders.has(row.providerName)) this.expandedProviders.delete(row.providerName);
|
|
266
|
+
else this.expandedProviders.add(row.providerName);
|
|
267
|
+
return true;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Cycle the view: Provider → Project → Prices → Provider. One key, one grid, one legend. */
|
|
271
|
+
private cycleView(): void {
|
|
272
|
+
this.view = this.view === "provider" ? "project" : this.view === "project" ? "prices" : "provider";
|
|
273
|
+
if (this.view === "project" && this.expandedProjects.size === 0 && this.summary.projects.length > 0) {
|
|
274
|
+
this.expandedProjects.add(this.summary.projects[0]!.name);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Refresh every row after a baseline change; the selected provider may disappear. */
|
|
279
|
+
private runConfirm(step: "reset" | "undo"): void {
|
|
280
|
+
if (step === "reset") {
|
|
281
|
+
this.undoBaseline = { previous: resetUsageStats() };
|
|
282
|
+
this.notice = "Usage statistics reset. Sessions kept.";
|
|
283
|
+
} else if (this.undoBaseline) {
|
|
284
|
+
restoreUsageStats(this.undoBaseline.previous);
|
|
285
|
+
this.notice = "Previous statistics restored. Sessions kept.";
|
|
286
|
+
this.undoBaseline = null;
|
|
287
|
+
}
|
|
288
|
+
this.summary = collectUsageSummary(true, this.range);
|
|
289
|
+
this.selectedIndex = 0;
|
|
290
|
+
this.expandedProviders.clear();
|
|
291
|
+
const first = this.summary.providers[0];
|
|
292
|
+
if (first) this.expandedProviders.add(first.name);
|
|
293
|
+
this.requestRender();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Switch the window and re-read the numbers for it. Selection returns to the first row:
|
|
297
|
+
* a provider that carried the last 3 months can be absent from today. */
|
|
298
|
+
private setRange(range: UsageRange): void {
|
|
299
|
+
if (range === this.range) return;
|
|
300
|
+
this.range = range;
|
|
301
|
+
this.summary = collectUsageSummary(true, range);
|
|
302
|
+
this.selectedIndex = 0;
|
|
303
|
+
this.expandedProviders.clear();
|
|
304
|
+
const first = this.summary.providers[0];
|
|
305
|
+
if (first) this.expandedProviders.add(first.name);
|
|
306
|
+
this.requestRender();
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
handleInput(keyData: string): void {
|
|
310
|
+
const rows = this.buildFlatRows();
|
|
311
|
+
// A pending question owns the keyboard: any key but y answers no, so a stray press
|
|
312
|
+
// can neither delete anything nor navigate.
|
|
313
|
+
if (this.confirmStep) {
|
|
314
|
+
const yes = matchesKey(keyData, "y") || matchesKey(keyData, "Y");
|
|
315
|
+
const step = this.confirmStep;
|
|
316
|
+
this.confirmStep = null;
|
|
317
|
+
if (yes) this.runConfirm(step);
|
|
318
|
+
else this.requestRender();
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
// Esc and ← both step out one level: the dashboard reports it upward so the /arnative
|
|
322
|
+
// menu reopens. q closes outright, for a dashboard opened by /usage on its own.
|
|
323
|
+
if (matchesBack(keyData) || matchesKey(keyData, "escape")) {
|
|
324
|
+
this.onDone(true);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
if (matchesKey(keyData, "q") || matchesKey(keyData, "shift+q")) {
|
|
328
|
+
this.onDone(false);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (RESET_USAGE.matches(keyData)) {
|
|
332
|
+
this.confirmStep = "reset";
|
|
333
|
+
this.notice = null;
|
|
334
|
+
this.requestRender();
|
|
335
|
+
return;
|
|
336
|
+
}
|
|
337
|
+
if (UNDO_USAGE.matches(keyData) && this.undoBaseline) {
|
|
338
|
+
this.confirmStep = "undo";
|
|
339
|
+
this.requestRender();
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (matchesKey(keyData, "tab") || matchesKey(keyData, "shift+tab")) {
|
|
343
|
+
const at = USAGE_RANGES.indexOf(this.range);
|
|
344
|
+
const step = matchesKey(keyData, "shift+tab") ? -1 : 1;
|
|
345
|
+
this.setRange(USAGE_RANGES[(at + step + USAGE_RANGES.length) % USAGE_RANGES.length]!);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
|
|
349
|
+
// Up
|
|
350
|
+
if (this.selectedIndex > 0) {
|
|
351
|
+
this.selectedIndex--;
|
|
352
|
+
this.requestRender();
|
|
353
|
+
}
|
|
354
|
+
return;
|
|
355
|
+
}
|
|
356
|
+
if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
|
|
357
|
+
// Down
|
|
358
|
+
if (this.selectedIndex < rows.length - 1) {
|
|
359
|
+
this.selectedIndex++;
|
|
360
|
+
this.requestRender();
|
|
361
|
+
}
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (matchesKey(keyData, "enter") || matchesKey(keyData, "space")) {
|
|
365
|
+
if (this.toggleRow(rows[this.selectedIndex])) this.requestRender();
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (matchesKey(keyData, "v")) {
|
|
369
|
+
this.cycleView();
|
|
370
|
+
this.requestRender();
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
/** A click on a provider row toggles it, using the hitboxes of the last render so a
|
|
375
|
+
* scrolled-out row is not clickable. Hover is not tracked: nothing reads it. */
|
|
376
|
+
handleMouse(event: TuiMouseEvent): { handled: boolean; render?: boolean } | undefined {
|
|
377
|
+
if (event.type === "wheel" || event.type === "move" || event.type === "drag" || event.type === "release") {
|
|
378
|
+
return undefined;
|
|
379
|
+
}
|
|
380
|
+
// A click on the range bar picks that window, so the bar is a control, not a label.
|
|
381
|
+
const tab = this.tabHitboxes.find((h) => h.line === event.y && event.x >= h.start && event.x <= h.end);
|
|
382
|
+
if (tab) {
|
|
383
|
+
if (event.type === "click") this.setRange(tab.range);
|
|
384
|
+
return { handled: true, render: event.type === "click" };
|
|
385
|
+
}
|
|
386
|
+
const hit = this.rowHitboxes.find((h) => h.line === event.y);
|
|
387
|
+
if (!hit) {
|
|
388
|
+
// A click outside the table is not ours to consume: let it fall through (text
|
|
389
|
+
// selection, scrollback).
|
|
390
|
+
return undefined;
|
|
391
|
+
}
|
|
392
|
+
if (event.type === "click") {
|
|
393
|
+
this.selectedIndex = hit.index;
|
|
394
|
+
this.toggleRow(this.buildFlatRows()[hit.index]);
|
|
395
|
+
return { handled: true, render: true };
|
|
396
|
+
}
|
|
397
|
+
// Press: claim the row so the terminal tracks it for the follow-up click.
|
|
398
|
+
return { handled: true, render: false };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
render(width: number): string[] {
|
|
402
|
+
const th = this.theme;
|
|
403
|
+
const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
|
|
404
|
+
// The box accent follows the session's thinking level (theme `thinking*` slot), so the
|
|
405
|
+
// dashboard reads as belonging to the model that produced the usage.
|
|
406
|
+
const edge = (t: string) => this.edgeOf(t);
|
|
407
|
+
const boxW = width;
|
|
408
|
+
// `secondarySoft` is a vars-only token on Pi 1.2+; softSecondaryOf resolves the soft
|
|
409
|
+
// label tier (the border-accent hue) and falls back to the accent tier.
|
|
410
|
+
const soft = softSecondaryOf(th);
|
|
411
|
+
const acc = (s: string) => th.fg("accent", s);
|
|
412
|
+
// Selection follows the menu style: a chosen row takes the soft accent, not the accent
|
|
413
|
+
// that marks the provider level itself. `softOf` resolves the token on Pi <=1.1.0 and
|
|
414
|
+
// derives it from the resolved accent on 1.2+, where `fg("accentSoft")` throws.
|
|
415
|
+
const accSoft = softOf(th);
|
|
416
|
+
const dim = (s: string) => th.fg("dim", s);
|
|
417
|
+
|
|
418
|
+
const rows = this.buildFlatRows();
|
|
419
|
+
if (this.selectedIndex >= rows.length) {
|
|
420
|
+
this.selectedIndex = Math.max(0, rows.length - 1);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Columns: full header words. `colW.name` is the header's own name column; a data row
|
|
424
|
+
// spends the first two cells on the expand arrow, so its name field is that much
|
|
425
|
+
// shorter and the numeric columns still start on the header's grid.
|
|
426
|
+
const gutter = 2;
|
|
427
|
+
const contentW = boxW - 4;
|
|
428
|
+
const colW = { name: 30, session: 10, messages: 11, tokens: 10, cost: 11 };
|
|
429
|
+
const allNumeric = colW.session + colW.messages + colW.tokens + colW.cost;
|
|
430
|
+
// A very narrow terminal drops Session/Messages rather than truncating Tokens or Cost.
|
|
431
|
+
const narrow = contentW - allNumeric < 18;
|
|
432
|
+
const numericW = narrow ? colW.tokens + colW.cost : allNumeric;
|
|
433
|
+
colW.name = Math.max(8, Math.min(colW.name, contentW - numericW));
|
|
434
|
+
const rowNameW = Math.max(4, colW.name - gutter);
|
|
435
|
+
|
|
436
|
+
const formatCol = (text: string, w: number, alignRight = true) => {
|
|
437
|
+
const str = truncateToWidth(text, w);
|
|
438
|
+
const diff = Math.max(0, w - visibleWidth(str));
|
|
439
|
+
return alignRight ? " ".repeat(diff) + str : str + " ".repeat(diff);
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
const sessionW = narrow ? 0 : colW.session;
|
|
443
|
+
const messagesW = narrow ? 0 : colW.messages;
|
|
444
|
+
// No leading gutter: the header is content, so it starts on the same left edge as the
|
|
445
|
+
// box title, the detail line and the Total row. The rows' numeric columns are measured
|
|
446
|
+
// to land on this grid despite their arrow. The header names the tree's two levels;
|
|
447
|
+
// the grid under it never moves between views. The Prices view reuses the same four
|
|
448
|
+
// numeric columns for the $/1M rates.
|
|
449
|
+
const nameHeader = this.view === "project" ? "Project / Provider" : "Provider / Model";
|
|
450
|
+
const [hSess, hMsgs, hToks, hCost] =
|
|
451
|
+
this.view === "prices" ? ["In $/M", "Out $/M", "Read $/M", "Write $/M"] : ["Session", "Messages", "Tokens", "Cost"];
|
|
452
|
+
const headerText =
|
|
453
|
+
formatCol(th.fg("dim", nameHeader), colW.name, false) +
|
|
454
|
+
formatCol(th.fg("dim", hSess), sessionW) +
|
|
455
|
+
formatCol(th.fg("dim", hMsgs), messagesW) +
|
|
456
|
+
formatCol(th.fg("dim", hToks), colW.tokens) +
|
|
457
|
+
formatCol(th.fg("dim", hCost), colW.cost);
|
|
458
|
+
|
|
459
|
+
// Body rows only — the frame comes from `renderScreen`, so this dashboard and the
|
|
460
|
+
// /arnative menus cannot drift. No inner `├─┤` rule (skill arnative-pi rule 7).
|
|
461
|
+
const body: string[] = [];
|
|
462
|
+
/** Rows the chrome draws above the body: top edge, title, description, blank. */
|
|
463
|
+
const CHROME_ROWS = 4;
|
|
464
|
+
this.rowHitboxes = [];
|
|
465
|
+
this.tabHitboxes = [];
|
|
466
|
+
|
|
467
|
+
// Row 1: the window bar. The active range is the only accented word, so the numbers
|
|
468
|
+
// below are read with the window they cover; the counter on the same line says how many
|
|
469
|
+
// rows exist beyond the viewport.
|
|
470
|
+
const bar: string[] = [];
|
|
471
|
+
let barCol = 0;
|
|
472
|
+
const barRow = CHROME_ROWS + body.length;
|
|
473
|
+
for (const r of USAGE_RANGES) {
|
|
474
|
+
if (bar.length > 0) {
|
|
475
|
+
bar.push(dim(" · "));
|
|
476
|
+
barCol += 3;
|
|
477
|
+
}
|
|
478
|
+
const label = RANGE_LABELS[r];
|
|
479
|
+
const text = r === this.range ? acc(bold(label)) : th.fg("muted", label);
|
|
480
|
+
this.tabHitboxes.push({ line: barRow, start: barCol + 2, end: barCol + label.length + 1, range: r });
|
|
481
|
+
bar.push(text);
|
|
482
|
+
barCol += label.length;
|
|
483
|
+
}
|
|
484
|
+
const counter = `${Math.min(rows.length, USAGE_VIEWPORT)}/${rows.length}`;
|
|
485
|
+
const barLine = bar.join("");
|
|
486
|
+
const counterFits = contentW - barCol - counter.length - 1 >= 0;
|
|
487
|
+
// Blank rows separate the range bar from the description above (via renderScreen) and the
|
|
488
|
+
// table header below — no inner horizontal rules.
|
|
489
|
+
body.push(counterFits ? barLine + " ".repeat(contentW - barCol - counter.length) + dim(counter) : barLine);
|
|
490
|
+
body.push("");
|
|
491
|
+
body.push(headerText);
|
|
492
|
+
|
|
493
|
+
// Row 2 onward: the table, windowed so the box keeps one height however long the list
|
|
494
|
+
// of providers and models grows. The line above and below say what is out of sight.
|
|
495
|
+
const maxVisibleRows = USAGE_VIEWPORT;
|
|
496
|
+
let startIdx = 0;
|
|
497
|
+
if (rows.length > maxVisibleRows) {
|
|
498
|
+
startIdx = Math.max(0, Math.min(this.selectedIndex - Math.floor(maxVisibleRows / 2), rows.length - maxVisibleRows));
|
|
499
|
+
}
|
|
500
|
+
const visibleRows = rows.slice(startIdx, startIdx + maxVisibleRows);
|
|
501
|
+
if (startIdx > 0) body.push(dim(`↑ ${startIdx} more`));
|
|
502
|
+
|
|
503
|
+
for (let i = 0; i < visibleRows.length; i++) {
|
|
504
|
+
const item = visibleRows[i]!;
|
|
505
|
+
const actualIdx = startIdx + i;
|
|
506
|
+
const isSelected = actualIdx === this.selectedIndex;
|
|
507
|
+
|
|
508
|
+
// Provider and project group rows sit on the plain text color, and the rows beneath
|
|
509
|
+
// them are dim — including the providers nested under a project. The cursor paints
|
|
510
|
+
// any row the soft accent, and the expand arrow alone carries the accent so the eye
|
|
511
|
+
// can find the tree.
|
|
512
|
+
const plain = (s: string) => th.fg("text", s);
|
|
513
|
+
const nested =
|
|
514
|
+
item.type === "model" || item.type === "price" || (this.view === "project" && item.type === "provider");
|
|
515
|
+
const resting = nested ? dim : plain;
|
|
516
|
+
const paintName = isSelected ? accSoft : resting;
|
|
517
|
+
const paintVal = isSelected ? accSoft : resting;
|
|
518
|
+
const isPrice = item.type === "price";
|
|
519
|
+
// A Prices group row names the provider; its rate columns stay blank, so the tree
|
|
520
|
+
// reads as a heading instead of a provider with $0.00 rates.
|
|
521
|
+
const isPriceGroup = this.view === "prices" && item.type === "provider";
|
|
522
|
+
const blank = (w: number) => " ".repeat(w);
|
|
523
|
+
|
|
524
|
+
// One indent for the rows under a group (model, price, or the provider under a
|
|
525
|
+
// project): it eats name width so the figures keep their columns.
|
|
526
|
+
const groupType: RowItem["type"] = this.view === "project" ? "project" : "provider";
|
|
527
|
+
const indent = item.type === groupType ? "" : " ";
|
|
528
|
+
const cName = formatCol(paintName(isSelected ? bold(item.label) : item.label), Math.max(10, rowNameW - indent.length), false);
|
|
529
|
+
const cSess = isPriceGroup ? blank(sessionW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.in ?? 0) : formatCount(item.sessions)), sessionW);
|
|
530
|
+
const cMsgs = isPriceGroup ? blank(messagesW) : formatCol(paintVal(isPrice ? formatCost(item.rates?.out ?? 0) : formatCount(item.msgs)), messagesW);
|
|
531
|
+
const cToks = isPriceGroup ? blank(colW.tokens) : formatCol(paintVal(isPrice ? formatCost(item.rates?.cacheRead ?? 0) : formatTokens(item.tokens)), colW.tokens);
|
|
532
|
+
// A row with no billed cost but a rate shows `~$x` in place of `-`, so the guess is
|
|
533
|
+
// visible exactly where it is one; the report line still keeps it out of the headline.
|
|
534
|
+
// The Prices view puts the cache-write rate here, or `unpriced` for a used model the
|
|
535
|
+
// table does not price.
|
|
536
|
+
const costCell = isPrice
|
|
537
|
+
? item.unpriced
|
|
538
|
+
? "unpriced"
|
|
539
|
+
: formatCost(item.rates?.cacheWrite ?? 0)
|
|
540
|
+
: item.cost > 0
|
|
541
|
+
? formatCost(item.cost)
|
|
542
|
+
: item.estimatedCost > 0
|
|
543
|
+
? `~${formatCost(item.estimatedCost)}`
|
|
544
|
+
: "-";
|
|
545
|
+
const cCost = isPriceGroup ? blank(colW.cost) : formatCol(paintVal(costCell), colW.cost);
|
|
546
|
+
|
|
547
|
+
// Gutter: the expand arrow carries the accent, blank indent for the rows beneath it.
|
|
548
|
+
const gutterText = item.type === groupType ? acc(item.expanded ? "▾" : "▸") : " ";
|
|
549
|
+
const line = indent + gutterText + " " + cName + cSess + cMsgs + cToks + cCost;
|
|
550
|
+
this.rowHitboxes.push({ line: CHROME_ROWS + body.length, index: actualIdx });
|
|
551
|
+
body.push(line);
|
|
552
|
+
}
|
|
553
|
+
const hiddenBelow = rows.length - (startIdx + visibleRows.length);
|
|
554
|
+
if (hiddenBelow > 0) body.push(dim(`↓ ${hiddenBelow} more`));
|
|
555
|
+
|
|
556
|
+
// Blank row separates the table rows from the Total band (no inner rules).
|
|
557
|
+
body.push("");
|
|
558
|
+
|
|
559
|
+
if (this.view === "prices") {
|
|
560
|
+
// No Total band for rates: a count of what the table prices, and of the used models
|
|
561
|
+
// it does not, is the honest summary of this view.
|
|
562
|
+
const unpriced = rows.filter((r) => r.unpriced).length;
|
|
563
|
+
const priced = rows.filter((r) => r.type === "price" && !r.unpriced).length;
|
|
564
|
+
body.push(dim(`${priced} priced · ${unpriced} unpriced (models.json)`));
|
|
565
|
+
} else {
|
|
566
|
+
// Total row. Its cost column is the billed total only.
|
|
567
|
+
const t = this.summary.totals;
|
|
568
|
+
const totalName = formatCol(soft(bold("Total")), colW.name, false);
|
|
569
|
+
const totalSess = formatCol(soft(bold(formatCount(t.sessions))), sessionW);
|
|
570
|
+
const totalMsgs = formatCol(soft(bold(formatCount(t.msgs))), messagesW);
|
|
571
|
+
const totalToks = formatCol(soft(bold(formatTokens(t.totalTokens))), colW.tokens);
|
|
572
|
+
// Billed when a provider reported one; otherwise the catalog estimate, marked `~` so
|
|
573
|
+
// the Total row never claims a billed number it does not have.
|
|
574
|
+
const totalValue = t.cost > 0 ? formatCost(t.cost) : t.estimatedCost > 0 ? `~${formatCost(t.estimatedCost)}` : "-";
|
|
575
|
+
const totalCost = formatCol(soft(bold(totalValue)), colW.cost);
|
|
576
|
+
|
|
577
|
+
// Same left edge as the header: one table, three bands, one column grid.
|
|
578
|
+
body.push(totalName + totalSess + totalMsgs + totalToks + totalCost);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// The selected row's detail sits below Total, separated by a blank row.
|
|
582
|
+
body.push("");
|
|
583
|
+
body.push(this.selectedDetail(rows[this.selectedIndex], acc, soft));
|
|
584
|
+
if (this.notice) body.push(th.fg("muted", this.notice));
|
|
585
|
+
|
|
586
|
+
const viewName = VIEW_LABELS[this.view];
|
|
587
|
+
return renderScreen(
|
|
588
|
+
th,
|
|
589
|
+
width,
|
|
590
|
+
{
|
|
591
|
+
title: screenTitle("Usage"),
|
|
592
|
+
description: `${viewName} · ${
|
|
593
|
+
this.view === "prices"
|
|
594
|
+
? width >= 70
|
|
595
|
+
? "Rates per 1M tokens from models.json; `unpriced` marks a used model with no rate."
|
|
596
|
+
: "Rates per 1M tokens (models.json)."
|
|
597
|
+
: width >= 70
|
|
598
|
+
? "Token, message & cache usage across all local Pi sessions."
|
|
599
|
+
: "Usage across all local sessions."
|
|
600
|
+
}`,
|
|
601
|
+
legend: this.footer(width, th),
|
|
602
|
+
},
|
|
603
|
+
body,
|
|
604
|
+
edge,
|
|
605
|
+
);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
/** The last row of the box: a pending question, or the keys that are live right now. */
|
|
609
|
+
private footer(width: number, th: { fg(c: string, t: string): string }): string {
|
|
610
|
+
if (this.confirmStep === "reset") {
|
|
611
|
+
return th.fg("accent", "Reset all usage statistics?") + " " + th.fg("muted", "sessions stay") + " " + th.fg("text", "[y] Yes [Esc] Cancel");
|
|
612
|
+
}
|
|
613
|
+
if (this.confirmStep === "undo") {
|
|
614
|
+
return (
|
|
615
|
+
th.fg("accent", "Undo the statistics reset?") +
|
|
616
|
+
" " +
|
|
617
|
+
th.fg("muted", "sessions stay") +
|
|
618
|
+
" " +
|
|
619
|
+
th.fg("text", "[y] Yes [Esc] Cancel")
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
return legendUsage(width, { reset: true, undo: this.undoBaseline !== null, next: VIEW_LABELS[NEXT_VIEW[this.view]] });
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/** Detail for the selected row: icon in `accent`, text and `·` dividers in `accentSoft`. */
|
|
626
|
+
private selectedDetail(
|
|
627
|
+
row: RowItem | undefined,
|
|
628
|
+
accent: (t: string) => string,
|
|
629
|
+
soft: (t: string) => string,
|
|
630
|
+
): string {
|
|
631
|
+
if (!row) return soft("No usage recorded yet.");
|
|
632
|
+
const icon = `${accent("\uf4bc")} `;
|
|
633
|
+
if (row.type === "price") {
|
|
634
|
+
const title = `${row.providerName} · ${row.modelName}`;
|
|
635
|
+
const parts = row.unpriced
|
|
636
|
+
? ["unpriced", `↑${formatTokens(row.input)}`, `↓${formatTokens(row.output)}`]
|
|
637
|
+
: [
|
|
638
|
+
`in ${formatCost(row.rates!.in)}`,
|
|
639
|
+
`out ${formatCost(row.rates!.out)}`,
|
|
640
|
+
`cache read ${formatCost(row.rates!.cacheRead)}`,
|
|
641
|
+
`cache write ${formatCost(row.rates!.cacheWrite)}`,
|
|
642
|
+
];
|
|
643
|
+
if (row.unpriced && row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
|
|
644
|
+
const divider = soft(" · ");
|
|
645
|
+
return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
|
|
646
|
+
}
|
|
647
|
+
const title =
|
|
648
|
+
row.type === "model" ? `${row.providerName} · ${row.modelName}` : row.type === "project" ? row.projectName! : row.providerName;
|
|
649
|
+
const parts = [
|
|
650
|
+
`↑${formatTokens(row.input)}`,
|
|
651
|
+
`↓${formatTokens(row.output)}`,
|
|
652
|
+
`cache ${formatTokens(row.cacheRead)}`,
|
|
653
|
+
];
|
|
654
|
+
if (row.estimatedCost > 0) parts.push(`${formatCost(row.estimatedCost)} est.`);
|
|
655
|
+
const divider = soft(" · ");
|
|
656
|
+
return `${icon}${soft(capitalize(title))}${divider}${soft(parts.join(" · "))}`;
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
/** Open the dashboard. Shared by `/usage` and `/arnative` → Usage, so the two cannot drift. */
|
|
661
|
+
export async function openUsage(ctx: ExtensionCommandContext): Promise<boolean> {
|
|
662
|
+
if (!ctx.hasUI) return false;
|
|
663
|
+
// The thinking level colors the box, so read it when the dashboard opens.
|
|
664
|
+
const thinkingLevel = ctx.thinkingLevel;
|
|
665
|
+
const back = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
|
|
666
|
+
return new UsageModalComponent(
|
|
667
|
+
theme,
|
|
668
|
+
(wantsBack) => done(wantsBack),
|
|
669
|
+
() => tui.requestRender(),
|
|
670
|
+
thinkingLevel,
|
|
671
|
+
);
|
|
672
|
+
});
|
|
673
|
+
return back === true;
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
/** At most one Prometheus textfile write per minute, whatever the turn rate. */
|
|
677
|
+
const EXPORT_THROTTLE_MS = 60_000;
|
|
678
|
+
/** `PI_ARNATIVE_EXPORT=0` disables the export (a local file with no network, so it ships on). */
|
|
679
|
+
export const EXPORT_ENV = "PI_ARNATIVE_EXPORT";
|
|
680
|
+
|
|
681
|
+
/** The textfile a collector scrapes: `<agent dir>/arnative/usage.prom`. */
|
|
682
|
+
export function promFilePath(): string {
|
|
683
|
+
return join(getAgentDir(), "arnative", "usage.prom");
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const escapePromLabel = (v: string): string => v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n");
|
|
687
|
+
|
|
688
|
+
/** Render Prometheus exposition text for one summary (pure and deterministic). */
|
|
689
|
+
export function renderProm(summary: UsageSummary, now: number): string {
|
|
690
|
+
const lines: string[] = [];
|
|
691
|
+
const sample = (name: string, labels: [string, string][], value: number): string =>
|
|
692
|
+
`${name}${labels.length > 0 ? `{${labels.map(([k, v]) => `${k}="${escapePromLabel(v)}"`).join(",")}}` : ""} ${value}`;
|
|
693
|
+
const gauge = (name: string, help: string, value: number): void => {
|
|
694
|
+
lines.push(`# HELP ${name} ${help}`, `# TYPE ${name} gauge`, sample(name, [], value));
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
const t = summary.totals;
|
|
698
|
+
gauge("arnative_cost_billed_total", "Provider-billed cost in USD across all sessions (totalFromProvider; estimates never mixed in).", t.cost);
|
|
699
|
+
gauge("arnative_cost_estimated_total", "Catalog-estimated cost in USD from models.json rates; never billed.", t.estimatedCost);
|
|
700
|
+
gauge("arnative_cost_today", "Provider-billed cost in USD in the current UTC day (the day buckets).", t.today?.cost ?? 0);
|
|
701
|
+
gauge("arnative_cost_30d", "Provider-billed cost in USD over the last 30 UTC days (the day buckets).", t.last30d?.cost ?? 0);
|
|
702
|
+
lines.push("# HELP arnative_tokens_total Token usage by provider, model and kind.", "# TYPE arnative_tokens_total gauge");
|
|
703
|
+
for (const p of summary.providers) {
|
|
704
|
+
for (const m of p.models) {
|
|
705
|
+
for (const [kind, value] of [["input", m.input], ["output", m.output], ["cache_read", m.cacheRead], ["cache_write", m.cacheWrite]] as const) {
|
|
706
|
+
const labels: [string, string][] = [
|
|
707
|
+
["provider", p.name],
|
|
708
|
+
["model", m.name],
|
|
709
|
+
["kind", kind],
|
|
710
|
+
];
|
|
711
|
+
lines.push(sample("arnative_tokens_total", labels, value));
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
gauge("arnative_sessions_total", "Distinct Pi session files scanned.", t.sessions);
|
|
716
|
+
gauge("arnative_usage_last_change_timestamp_seconds", "Unix time this process last saw the usage data change (not the last scrape).", now / 1000);
|
|
717
|
+
return `${lines.join("\n")}\n`;
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/** Write the exposition atomically with Windows lock fallback. */
|
|
721
|
+
export function writePromFile(text: string, path: string, rename: (from: string, to: string) => void = renameSync): void {
|
|
722
|
+
writeAtomicSync(path, text, rename);
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
let lastExportMs = 0;
|
|
726
|
+
let lastExportText = "";
|
|
727
|
+
let lastSummaryJson = "";
|
|
728
|
+
let lastScanAt = 0;
|
|
729
|
+
|
|
730
|
+
/** One throttled, diff-skipped, non-throwing Prometheus textfile export attempt. */
|
|
731
|
+
export function exportProm(now: number, path: string = promFilePath()): boolean {
|
|
732
|
+
try {
|
|
733
|
+
if (process.env[EXPORT_ENV] === "0") return false;
|
|
734
|
+
if (now - lastExportMs < EXPORT_THROTTLE_MS) return false;
|
|
735
|
+
lastExportMs = now;
|
|
736
|
+
const summary = collectUsageSummary(true);
|
|
737
|
+
const key = JSON.stringify(summary);
|
|
738
|
+
if (key !== lastSummaryJson) {
|
|
739
|
+
lastSummaryJson = key;
|
|
740
|
+
lastScanAt = now;
|
|
741
|
+
}
|
|
742
|
+
const text = renderProm(summary, lastScanAt);
|
|
743
|
+
if (text === lastExportText) return false;
|
|
744
|
+
writePromFile(text, path);
|
|
745
|
+
lastExportText = text;
|
|
746
|
+
return true;
|
|
747
|
+
} catch {
|
|
748
|
+
return false;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
export default function (pi: ExtensionAPI) {
|
|
753
|
+
let exportTimer: ReturnType<typeof setTimeout> | null = null;
|
|
754
|
+
const cancelDeferredExport = (): void => {
|
|
755
|
+
if (exportTimer) {
|
|
756
|
+
clearTimeout(exportTimer);
|
|
757
|
+
exportTimer = null;
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
pi.registerCommand("usage", {
|
|
761
|
+
description: "Arnative token & model usage dashboard",
|
|
762
|
+
handler: async (_args: string, ctx: ExtensionCommandContext) => {
|
|
763
|
+
await openUsage(ctx);
|
|
764
|
+
},
|
|
765
|
+
});
|
|
766
|
+
pi.on("turn_end", () => {
|
|
767
|
+
markUsageDirty();
|
|
768
|
+
// Defer synchronous disk scan + atomic writes off the turn_end hot path.
|
|
769
|
+
if (!exportTimer) {
|
|
770
|
+
exportTimer = setTimeout(() => {
|
|
771
|
+
exportTimer = null;
|
|
772
|
+
exportProm(Date.now());
|
|
773
|
+
}, 0);
|
|
774
|
+
exportTimer.unref?.();
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
pi.on("session_shutdown", () => {
|
|
778
|
+
cancelDeferredExport();
|
|
779
|
+
lastExportMs = 0;
|
|
780
|
+
exportProm(Date.now());
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
export const __test = {
|
|
785
|
+
RANGE_LABELS,
|
|
786
|
+
};
|