@bismawy/pi-arnative 0.10.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +6 -1
- package/extensions/arnative.ts +76 -23
- package/extensions/budget.ts +665 -0
- package/extensions/footer.ts +409 -26
- package/extensions/usage-export.ts +292 -0
- package/extensions/usage.ts +424 -147
- package/lib/compat.ts +36 -10
- package/lib/list-picker.ts +2 -2
- package/lib/model-heal.ts +12 -4
- package/lib/preset-store.ts +49 -5
- package/lib/provider.ts +36 -5
- package/lib/shortcuts.ts +12 -7
- package/lib/status-widget.ts +20 -0
- package/lib/usage-store.ts +913 -312
- package/package.json +3 -3
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget guardrail — the only arnative feature that can *stop* spend, and it stops the next
|
|
3
|
+
* turn, not a tool call: blocking a `tool_call` does not stop the spend (the assistant message
|
|
4
|
+
* that issued the call is already billed and the model spends another paid turn reacting to the
|
|
5
|
+
* error result), so the gate is `pi.on("input")` returning `{ action: "handled" }`, which stops
|
|
6
|
+
* the turn before any token is bought.
|
|
7
|
+
*
|
|
8
|
+
* Warn-only by default: `budgetEnforce` ships `"off"`. Over a cap with enforce off the gate
|
|
9
|
+
* notifies once per session and lets the turn through; with enforce on it notifies and returns
|
|
10
|
+
* `handled`. The spend comes from the usage cache's day buckets (`totals.today` / `last30d`,
|
|
11
|
+
* billed plus its catalog-estimated part); the footer band reads it through the 5s memo, the
|
|
12
|
+
* gate forces its own scan so it never decides on a total up to 5s old. Three fail-open rules: an
|
|
13
|
+
* `event.source === "extension"` input is never swallowed, an unknown spend (no day buckets)
|
|
14
|
+
* never blocks, and the whole handler is wrapped in a try/catch that returns `continue` — a
|
|
15
|
+
* throwing `input` handler is worse than no budget. Estimate-only spend (no provider-billed
|
|
16
|
+
* total) can reach `warn` but never `over` in {@link budgetState}: a cap on an unpriced model
|
|
17
|
+
* would enforce $0.
|
|
18
|
+
*
|
|
19
|
+
* The settings live in `config.json` (`budgetDay` / `budgetMonth` amount strings, `""` = unset,
|
|
20
|
+
* `budgetEnforce` `"on"`/`"off"`) and are edited from `/arnative` → **Budget** ({@link openBudget}).
|
|
21
|
+
*/
|
|
22
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import { matchesKey, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
|
|
24
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { tmpdir } from "node:os";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { thinkingColorOf } from "../lib/ansi.ts";
|
|
28
|
+
import { renderScreen, screenTitle } from "../lib/box.ts";
|
|
29
|
+
import { assert, isMain } from "../lib/check.ts";
|
|
30
|
+
import { announce } from "../lib/status-widget.ts";
|
|
31
|
+
import { rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
|
|
32
|
+
import { matchesBack } from "../lib/shortcuts.ts";
|
|
33
|
+
import {
|
|
34
|
+
BUDGET_DAY_KEY,
|
|
35
|
+
BUDGET_ENFORCE_KEY,
|
|
36
|
+
BUDGET_MONTH_KEY,
|
|
37
|
+
loadChoice,
|
|
38
|
+
loadNumber,
|
|
39
|
+
resetPresetCache,
|
|
40
|
+
saveChoice,
|
|
41
|
+
} from "../lib/preset-store.ts";
|
|
42
|
+
import { collectUsageSummary, resetUsageCache } from "../lib/usage-store.ts";
|
|
43
|
+
import { formatCost } from "./usage.ts";
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------- settings
|
|
46
|
+
|
|
47
|
+
/** Accepted cap amounts in dollars; a cap is a positive number in this range. */
|
|
48
|
+
export const BUDGET_AMOUNT_RANGE = { min: 0.01, max: 1_000_000 } as const;
|
|
49
|
+
/** The fixed cap choices the Budget screen cycles through; `0` is "off" (stored as `""`). */
|
|
50
|
+
export const BUDGET_CAPS = [0, 1, 2, 5, 10, 25, 50, 100, 250, 500] as const;
|
|
51
|
+
|
|
52
|
+
// Active values on globalThis so the `/arnative` picker and this module's event handlers agree
|
|
53
|
+
// without sharing memo caches (the same pattern as the footer cost switch).
|
|
54
|
+
const BUDGET_DAY_SLOT = Symbol.for("pi-arnative.budgetDay");
|
|
55
|
+
const BUDGET_MONTH_SLOT = Symbol.for("pi-arnative.budgetMonth");
|
|
56
|
+
const BUDGET_ENFORCE_SLOT = Symbol.for("pi-arnative.budgetEnforce");
|
|
57
|
+
|
|
58
|
+
export function activeBudgetDay(): number | undefined {
|
|
59
|
+
const stored = (globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT] ?? loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE);
|
|
60
|
+
return typeof stored === "number" && stored > 0 ? stored : undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function activeBudgetMonth(): number | undefined {
|
|
64
|
+
const stored = (globalThis as Record<symbol, unknown>)[BUDGET_MONTH_SLOT] ?? loadNumber(BUDGET_MONTH_KEY, BUDGET_AMOUNT_RANGE);
|
|
65
|
+
return typeof stored === "number" && stored > 0 ? stored : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Enforce off by default: the guardrail warns unless the user explicitly turned it on. */
|
|
69
|
+
export function activeBudgetEnforce(): boolean {
|
|
70
|
+
const stored = (globalThis as Record<symbol, unknown>)[BUDGET_ENFORCE_SLOT] ?? loadChoice(BUDGET_ENFORCE_KEY, ["on", "off"] as const);
|
|
71
|
+
return stored === "on";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function setBudgetDay(n: number | undefined): void {
|
|
75
|
+
(globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT] = n !== undefined && n > 0 ? n : undefined;
|
|
76
|
+
saveChoice(BUDGET_DAY_KEY, n !== undefined && n > 0 ? String(n) : "");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function setBudgetMonth(n: number | undefined): void {
|
|
80
|
+
(globalThis as Record<symbol, unknown>)[BUDGET_MONTH_SLOT] = n !== undefined && n > 0 ? n : undefined;
|
|
81
|
+
saveChoice(BUDGET_MONTH_KEY, n !== undefined && n > 0 ? String(n) : "");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function setBudgetEnforce(on: boolean): void {
|
|
85
|
+
(globalThis as Record<symbol, unknown>)[BUDGET_ENFORCE_SLOT] = on ? "on" : "off";
|
|
86
|
+
saveChoice(BUDGET_ENFORCE_KEY, on ? "on" : "off");
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The next cap choice after `current` (unset reads as 0); past the largest choice it wraps to off. */
|
|
90
|
+
export function nextCap(current: number | undefined): number {
|
|
91
|
+
const cur = current ?? 0;
|
|
92
|
+
return BUDGET_CAPS.find((c) => c > cur) ?? 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Row label of a cap: the amount, or `off` when unset. */
|
|
96
|
+
export const capLabel = (n: number | undefined): string => (n !== undefined && n > 0 ? formatCost(n) : "off");
|
|
97
|
+
|
|
98
|
+
// ---------------------------------------------------------------- decision
|
|
99
|
+
|
|
100
|
+
export type BudgetLevel = "ok" | "warn" | "over";
|
|
101
|
+
|
|
102
|
+
export interface BudgetSpend {
|
|
103
|
+
/** Billed spend in the current UTC day / the last 30 days (the cache's day buckets). */
|
|
104
|
+
today: number;
|
|
105
|
+
month: number;
|
|
106
|
+
/** Catalog-estimated spend in the same windows: it warns, it never blocks. */
|
|
107
|
+
estimatedToday?: number;
|
|
108
|
+
estimatedMonth?: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface BudgetVerdict {
|
|
112
|
+
level: BudgetLevel;
|
|
113
|
+
reason?: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** `warn` starts at this fraction of a cap. */
|
|
117
|
+
export const WARN_PCT = 0.8;
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Pure decision — no I/O, the unit under test. `warn` at ≥80% of any set cap, `over` at ≥100%.
|
|
121
|
+
* Rule 4: only **billed** spend can cross a cap, because a cap computed from a catalog estimate
|
|
122
|
+
* would enforce $0 on an unpriced model. An estimate still counts towards the warning, so a
|
|
123
|
+
* provider that reports no billed total is not silently ignored. `enforce` only words the
|
|
124
|
+
* reason: an `over` that will be blocked says so, one that only warns does not.
|
|
125
|
+
*/
|
|
126
|
+
export function budgetState(spend: BudgetSpend, caps: { day?: number; month?: number }, enforce: boolean): BudgetVerdict {
|
|
127
|
+
let level: BudgetLevel = "ok";
|
|
128
|
+
let reason: string | undefined;
|
|
129
|
+
const consider = (billed: number, estimated: number, cap: number | undefined, label: string): void => {
|
|
130
|
+
if (cap === undefined || !(cap > 0)) return;
|
|
131
|
+
const total = billed + estimated;
|
|
132
|
+
if (!(total > 0)) return;
|
|
133
|
+
// `floor`, not `round`: 99.6 % of a cap must not read as "at 100 %". Multiply before
|
|
134
|
+
// dividing: `(115 / 100) * 100` is 114.99999999999999, `(115 * 100) / 100` is 115.
|
|
135
|
+
const pct = Math.floor((total * 100) / cap);
|
|
136
|
+
if (billed >= cap) {
|
|
137
|
+
if (level !== "over") {
|
|
138
|
+
level = "over";
|
|
139
|
+
// The block is decided on billed spend, so the reason states billed spend too.
|
|
140
|
+
reason = `${label} cap ${formatCost(cap)} at ${Math.floor((billed * 100) / cap)}% (${formatCost(billed)} billed)`;
|
|
141
|
+
}
|
|
142
|
+
} else if (total / cap >= WARN_PCT && level === "ok") {
|
|
143
|
+
level = "warn";
|
|
144
|
+
// The note is only true when the estimate is what pushed the window into warn: billed
|
|
145
|
+
// spend below the warning threshold on its own. Otherwise the next billed dollar blocks.
|
|
146
|
+
const note = estimated > 0 && billed / cap < WARN_PCT ? " — estimate only, never blocked" : "";
|
|
147
|
+
reason = `${label} cap ${formatCost(cap)} at ${pct}% (${formatCost(total)} spent)${note}`;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
consider(spend.today, spend.estimatedToday ?? 0, caps.day, "day");
|
|
151
|
+
consider(spend.month, spend.estimatedMonth ?? 0, caps.month, "month");
|
|
152
|
+
if (level === "ok") return { level };
|
|
153
|
+
if (level === "over") return { level, reason: `${reason}${enforce ? " — turn blocked" : " — enforcement off"}` };
|
|
154
|
+
return { level, reason };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The current spend from the memoized summary's day buckets, or null when they are absent
|
|
158
|
+
* (a cache with no buckets — the spend is then unknown, never a fabricated $0). `force`
|
|
159
|
+
* re-scans: the gate must not read a total up to 5s old, the footer render must not scan. */
|
|
160
|
+
export function spendNow(force = false): BudgetSpend | null {
|
|
161
|
+
const s = collectUsageSummary(force);
|
|
162
|
+
if (!s.totals.today || !s.totals.last30d) return null;
|
|
163
|
+
return {
|
|
164
|
+
today: s.totals.today.cost,
|
|
165
|
+
month: s.totals.last30d.cost,
|
|
166
|
+
estimatedToday: s.totals.today.estimated,
|
|
167
|
+
estimatedMonth: s.totals.last30d.estimated,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** The budget level right now — read by the footer render, so it rides the same 5s memo: at
|
|
172
|
+
* most one scan per 5s on the render path, never one per frame. Any error reads as `ok`
|
|
173
|
+
* (never a false alarm). */
|
|
174
|
+
export function budgetLevelNow(): BudgetLevel {
|
|
175
|
+
try {
|
|
176
|
+
const caps = { day: activeBudgetDay(), month: activeBudgetMonth() };
|
|
177
|
+
if (caps.day === undefined && caps.month === undefined) return "ok";
|
|
178
|
+
const spend = spendNow();
|
|
179
|
+
if (spend === null) return "ok";
|
|
180
|
+
return budgetState(spend, caps, activeBudgetEnforce()).level;
|
|
181
|
+
} catch {
|
|
182
|
+
return "ok";
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ---------------------------------------------------------------- the Budget screen
|
|
187
|
+
|
|
188
|
+
const BUDGET_PICKER_TEXT: ListPickerText = {
|
|
189
|
+
title: screenTitle("Budget"),
|
|
190
|
+
description: "Warn-only caps on the UTC day and the rolling 30d — enforce on blocks the next turn.",
|
|
191
|
+
legend: "[↑↓] Move [Space] Change [Esc] Back",
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const ENFORCE_ON_NOTE = "on — blocks the next turn over a cap";
|
|
195
|
+
const ENFORCE_OFF_NOTE = "off — warns only";
|
|
196
|
+
|
|
197
|
+
/** The live note of one Budget row, re-read on every render so a change shows at once. */
|
|
198
|
+
function budgetRowNote(label: string): string | undefined {
|
|
199
|
+
if (label === "Day cap") return capLabel(activeBudgetDay());
|
|
200
|
+
if (label === "30d cap") return capLabel(activeBudgetMonth());
|
|
201
|
+
if (label === "Enforce") return activeBudgetEnforce() ? ENFORCE_ON_NOTE : ENFORCE_OFF_NOTE;
|
|
202
|
+
return undefined;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The Budget screen's editable rows: day cap, month cap, enforce. The spend itself is the
|
|
206
|
+
* status section above the rows, not a row. */
|
|
207
|
+
export function budgetRows(): ListRow[] {
|
|
208
|
+
return ["Day cap", "30d cap", "Enforce"].map((label) => ({ label, note: budgetRowNote(label) }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Enter on a row changes that row's value (the screen stays open, the note re-reads). */
|
|
212
|
+
function changeBudgetRow(index: number): void {
|
|
213
|
+
if (index === 0) setBudgetDay(nextCap(activeBudgetDay()));
|
|
214
|
+
else if (index === 1) setBudgetMonth(nextCap(activeBudgetMonth()));
|
|
215
|
+
else if (index === 2) setBudgetEnforce(!activeBudgetEnforce());
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// ---------------------------------------------------------------- the Budget screen (TUI)
|
|
219
|
+
|
|
220
|
+
/** Width of the spend-vs-cap bar, in cells. */
|
|
221
|
+
export const BUDGET_BAR_WIDTH = 20;
|
|
222
|
+
|
|
223
|
+
export interface BudgetWindow {
|
|
224
|
+
label: string;
|
|
225
|
+
/** Billed spend in the window. */
|
|
226
|
+
billed: number;
|
|
227
|
+
/** Catalog-estimated spend in the window: it warns, it never blocks. */
|
|
228
|
+
estimated: number;
|
|
229
|
+
/** Billed + estimated — the number the bar and the percentage are drawn from. */
|
|
230
|
+
total: number;
|
|
231
|
+
/** The cap, when one is set. */
|
|
232
|
+
cap?: number;
|
|
233
|
+
/** Bar fill fraction 0..1 (0 without a cap or without spend). */
|
|
234
|
+
frac: number;
|
|
235
|
+
/** Whole percent of the cap, uncapped (120 stays 120); undefined without a cap. */
|
|
236
|
+
pct?: number;
|
|
237
|
+
level: BudgetLevel;
|
|
238
|
+
/** True when the day buckets are absent: the spend is unknown, never a fabricated $0. */
|
|
239
|
+
unknown: boolean;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** The two status rows of the Budget screen, pure so the self-check pins them without a theme. */
|
|
243
|
+
export function budgetWindows(spend: BudgetSpend | null, caps: { day?: number; month?: number }, enforce: boolean): BudgetWindow[] {
|
|
244
|
+
const win = (label: string, billed: number, estimated: number, cap: number | undefined): BudgetWindow => {
|
|
245
|
+
const total = billed + estimated;
|
|
246
|
+
const base = { label, billed, estimated, total, cap, frac: 0, level: "ok" as BudgetLevel, unknown: false };
|
|
247
|
+
if (spend === null) return { ...base, unknown: true };
|
|
248
|
+
if (cap === undefined || !(cap > 0)) return base;
|
|
249
|
+
// The window's own level: only its cap and its spend decide it, through the same
|
|
250
|
+
// decision function the gate uses — estimate-only spend still caps at warn.
|
|
251
|
+
const level = budgetState(
|
|
252
|
+
label === "Today"
|
|
253
|
+
? { today: billed, month: 0, estimatedToday: estimated, estimatedMonth: 0 }
|
|
254
|
+
: { today: 0, month: billed, estimatedToday: 0, estimatedMonth: estimated },
|
|
255
|
+
label === "Today" ? { day: cap } : { month: cap },
|
|
256
|
+
enforce,
|
|
257
|
+
).level;
|
|
258
|
+
return { ...base, level, frac: total > 0 ? Math.min(1, total / cap) : 0, pct: Math.floor((total * 100) / cap) };
|
|
259
|
+
};
|
|
260
|
+
if (spend === null) {
|
|
261
|
+
return [
|
|
262
|
+
{ label: "Today", billed: 0, estimated: 0, total: 0, cap: caps.day, frac: 0, level: "ok", unknown: true },
|
|
263
|
+
{ label: "30d", billed: 0, estimated: 0, total: 0, cap: caps.month, frac: 0, level: "ok", unknown: true },
|
|
264
|
+
];
|
|
265
|
+
}
|
|
266
|
+
return [
|
|
267
|
+
win("Today", spend.today, spend.estimatedToday ?? 0, caps.day),
|
|
268
|
+
win("30d", spend.month, spend.estimatedMonth ?? 0, caps.month),
|
|
269
|
+
];
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The Budget dashboard: a spend-vs-cap status section over the editable cap rows. The frame
|
|
273
|
+
* comes from `renderScreen` like every other arnative screen; the level colors reuse the
|
|
274
|
+
* theme's warning/error slots (ok stays the accent, matching the footer band painter). */
|
|
275
|
+
class BudgetModalComponent implements Component {
|
|
276
|
+
private readonly theme: { fg(c: string, t: string): string; bold?(t: string): string };
|
|
277
|
+
private readonly rows: ListRow[];
|
|
278
|
+
private readonly hooks: { change(index: number): void; done(back: boolean): void; requestRender(): void };
|
|
279
|
+
private readonly text: ListPickerText;
|
|
280
|
+
private readonly edge: (s: string) => string;
|
|
281
|
+
private selected = 0;
|
|
282
|
+
|
|
283
|
+
constructor(
|
|
284
|
+
theme: { fg(c: string, t: string): string; bold?(t: string): string },
|
|
285
|
+
rows: ListRow[],
|
|
286
|
+
hooks: { change(index: number): void; done(back: boolean): void; requestRender(): void },
|
|
287
|
+
text: ListPickerText,
|
|
288
|
+
thinkingLevel?: string,
|
|
289
|
+
) {
|
|
290
|
+
this.theme = theme;
|
|
291
|
+
this.rows = rows;
|
|
292
|
+
this.hooks = hooks;
|
|
293
|
+
this.text = text;
|
|
294
|
+
this.edge = thinkingColorOf(theme, thinkingLevel);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
invalidate(): void {
|
|
298
|
+
/* renders are computed per call */
|
|
299
|
+
}
|
|
300
|
+
dispose(): void {
|
|
301
|
+
/* no timer to clear */
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
handleInput(keyData: string): void {
|
|
305
|
+
// Esc/← step back to /arnative, Q closes the screen — the same contract as ListPicker.
|
|
306
|
+
if (matchesKey(keyData, "escape") || matchesBack(keyData)) {
|
|
307
|
+
this.hooks.done(true);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (keyData === "Q" || matchesKey(keyData, "q")) {
|
|
311
|
+
this.hooks.done(false);
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
|
|
315
|
+
this.selected = Math.max(0, this.selected - 1);
|
|
316
|
+
this.hooks.requestRender();
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
|
|
320
|
+
this.selected = Math.min(this.rows.length - 1, this.selected + 1);
|
|
321
|
+
this.hooks.requestRender();
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (matchesKey(keyData, "space")) {
|
|
325
|
+
this.hooks.change(this.selected);
|
|
326
|
+
this.hooks.requestRender();
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
render(width: number): string[] {
|
|
331
|
+
const th = this.theme;
|
|
332
|
+
const bold = th.bold ?? ((t: string) => t);
|
|
333
|
+
const dim = (s: string) => th.fg("dim", s);
|
|
334
|
+
const acc = (s: string) => th.fg("accent", s);
|
|
335
|
+
// Levels ride the active theme's semantic slots: OK accent, WARN warning, OVER error.
|
|
336
|
+
const levelPaint = (level: BudgetLevel) =>
|
|
337
|
+
level === "ok" ? acc : level === "warn" ? (s: string) => th.fg("warning", s) : (s: string) => th.fg("error", s);
|
|
338
|
+
const contentW = Math.max(20, width - 4);
|
|
339
|
+
const body: string[] = [];
|
|
340
|
+
|
|
341
|
+
// Status: one line per window — `label · spend of cap bar pct% · LEVEL` — then the
|
|
342
|
+
// estimated total. The bars share one column: the spend-of-cap text is padded to the
|
|
343
|
+
// widest window, so a longer cap never shifts its neighbour's bar.
|
|
344
|
+
const spend = spendNow();
|
|
345
|
+
const windows = budgetWindows(spend, { day: activeBudgetDay(), month: activeBudgetMonth() }, activeBudgetEnforce());
|
|
346
|
+
const capText = (w: BudgetWindow): string => (w.cap !== undefined && w.cap > 0 ? `${formatCost(w.total)} of ${formatCost(w.cap)}` : "");
|
|
347
|
+
const partW = Math.max(0, ...windows.map((w) => visibleWidth(capText(w))));
|
|
348
|
+
for (const w of windows) {
|
|
349
|
+
const label = th.fg("text", w.label.padEnd(5));
|
|
350
|
+
if (w.unknown) {
|
|
351
|
+
body.push(`${label} · ${dim("unknown — no day buckets yet")}`);
|
|
352
|
+
continue;
|
|
353
|
+
}
|
|
354
|
+
if (w.cap === undefined || !(w.cap > 0)) {
|
|
355
|
+
body.push(`${label} · ${th.fg("text", formatCost(w.total))} ${dim("no cap")}`);
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const paint = levelPaint(w.level);
|
|
359
|
+
const filled = Math.round(w.frac * BUDGET_BAR_WIDTH);
|
|
360
|
+
const bar = paint("█".repeat(filled)) + dim("░".repeat(BUDGET_BAR_WIDTH - filled));
|
|
361
|
+
const pct = `${w.pct}%`.padEnd(4);
|
|
362
|
+
body.push(`${label} · ${th.fg("text", capText(w).padEnd(partW))} ${bar} ${paint(pct)} · ${paint(w.level.toUpperCase())}`);
|
|
363
|
+
}
|
|
364
|
+
// The estimated part of both windows, once: an estimate-only provider shows $0 billed
|
|
365
|
+
// per window, so the total is the only place the guess is summed.
|
|
366
|
+
const estimated = (spend?.estimatedToday ?? 0) + (spend?.estimatedMonth ?? 0);
|
|
367
|
+
if (estimated > 0) body.push(`${dim(`Total · ${formatCost(estimated)} est.`)}`);
|
|
368
|
+
body.push("");
|
|
369
|
+
|
|
370
|
+
// Editable rows — the same rows the headless picker offers.
|
|
371
|
+
for (let i = 0; i < this.rows.length; i++) {
|
|
372
|
+
const row = this.rows[i]!;
|
|
373
|
+
const isSelected = i === this.selected;
|
|
374
|
+
const paint = isSelected ? (s: string) => acc(bold(s)) : (s: string) => th.fg(row.note ? "text" : "muted", s);
|
|
375
|
+
const note = budgetRowNote(row.label);
|
|
376
|
+
const noteText = note ? ` ${dim("·")} ${dim(note)}` : "";
|
|
377
|
+
body.push(`${isSelected ? acc("→ ") : " "}${paint(row.label)}${noteText}`);
|
|
378
|
+
}
|
|
379
|
+
return renderScreen(th, width, this.text, body.map((l) => truncateToWidth(l, contentW, "")), this.edge);
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** `/arnative` → **Budget**: a dashboard of spend vs caps over the editable cap rows. */
|
|
384
|
+
export async function openBudget(ctx: ExtensionCommandContext): Promise<boolean | void> {
|
|
385
|
+
if (ctx.mode !== "tui") {
|
|
386
|
+
// No custom components (RPC/headless): fall back to the blocking picker.
|
|
387
|
+
const rows = budgetRows();
|
|
388
|
+
const labels = rows.map(rowText);
|
|
389
|
+
const pick = await ctx.ui.select(BUDGET_PICKER_TEXT.title, labels);
|
|
390
|
+
if (pick === undefined) return;
|
|
391
|
+
const index = labels.indexOf(pick);
|
|
392
|
+
changeBudgetRow(index);
|
|
393
|
+
ctx.ui.notify(`[arnative] Budget: ${rowText(budgetRows()[index]!)}`, "info");
|
|
394
|
+
announce(ctx.ui, `Budget: ${rowText(budgetRows()[index]!)}.`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
|
|
399
|
+
return new BudgetModalComponent(
|
|
400
|
+
theme,
|
|
401
|
+
budgetRows(),
|
|
402
|
+
{
|
|
403
|
+
change: (index) => {
|
|
404
|
+
changeBudgetRow(index);
|
|
405
|
+
announce(ctx.ui, `Budget: ${rowText(budgetRows()[index]!)}.`);
|
|
406
|
+
tui.requestRender();
|
|
407
|
+
},
|
|
408
|
+
done: (back) => done(back),
|
|
409
|
+
requestRender: () => tui.requestRender(),
|
|
410
|
+
},
|
|
411
|
+
BUDGET_PICKER_TEXT,
|
|
412
|
+
ctx.thinkingLevel,
|
|
413
|
+
);
|
|
414
|
+
});
|
|
415
|
+
return goBack === true;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ---------------------------------------------------------------- the gate
|
|
419
|
+
|
|
420
|
+
/** Notified once per session while over a cap with enforce off. */
|
|
421
|
+
let overNotified = false;
|
|
422
|
+
|
|
423
|
+
export default function registerBudget(pi: ExtensionAPI): void {
|
|
424
|
+
pi.on("session_start", () => {
|
|
425
|
+
overNotified = false;
|
|
426
|
+
});
|
|
427
|
+
|
|
428
|
+
pi.on("input", async (event, ctx) => {
|
|
429
|
+
try {
|
|
430
|
+
// An extension-injected message must never be swallowed by the budget gate.
|
|
431
|
+
if (event.source === "extension") return { action: "continue" };
|
|
432
|
+
const caps = { day: activeBudgetDay(), month: activeBudgetMonth() };
|
|
433
|
+
if (caps.day === undefined && caps.month === undefined) return { action: "continue" };
|
|
434
|
+
const spend = spendNow(true);
|
|
435
|
+
// Unknown spend (no day buckets): never block.
|
|
436
|
+
if (spend === null) return { action: "continue" };
|
|
437
|
+
const enforce = activeBudgetEnforce();
|
|
438
|
+
const verdict = budgetState(spend, caps, enforce);
|
|
439
|
+
if (verdict.level !== "over") return { action: "continue" };
|
|
440
|
+
if (enforce) {
|
|
441
|
+
ctx.ui.notify(verdict.reason ?? "over the budget cap", "error");
|
|
442
|
+
return { action: "handled" };
|
|
443
|
+
}
|
|
444
|
+
if (!overNotified) {
|
|
445
|
+
overNotified = true;
|
|
446
|
+
ctx.ui.notify(verdict.reason ?? "over the budget cap", "warning");
|
|
447
|
+
}
|
|
448
|
+
return { action: "continue" };
|
|
449
|
+
} catch {
|
|
450
|
+
// Fail open, always: a throwing input handler is worse than no budget.
|
|
451
|
+
return { action: "continue" };
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
// Self-check: `node extensions/budget.ts`
|
|
457
|
+
if (isMain(import.meta.url)) {
|
|
458
|
+
// The real agent dir must not decide pass/fail, and the check must not touch it.
|
|
459
|
+
const fixture = mkdtempSync(join(tmpdir(), "arnative-budget-"));
|
|
460
|
+
const prevDir = process.env.PI_CODING_AGENT_DIR;
|
|
461
|
+
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
462
|
+
const clearSlots = () => {
|
|
463
|
+
delete (globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT];
|
|
464
|
+
delete (globalThis as Record<symbol, unknown>)[BUDGET_MONTH_SLOT];
|
|
465
|
+
delete (globalThis as Record<symbol, unknown>)[BUDGET_ENFORCE_SLOT];
|
|
466
|
+
};
|
|
467
|
+
clearSlots();
|
|
468
|
+
resetPresetCache();
|
|
469
|
+
|
|
470
|
+
// The decision function: percentages of a $100 day cap.
|
|
471
|
+
for (const [spend, level] of [[0, "ok"], [79, "ok"], [80, "warn"], [99, "warn"], [100, "over"], [120, "over"]] as const) {
|
|
472
|
+
assert(budgetState({ today: spend, month: 0 }, { day: 100 }, true).level === level, `${spend}% of the cap is ${level}`);
|
|
473
|
+
}
|
|
474
|
+
assert(budgetState({ today: 999, month: 999 }, {}, true).level === "ok", "no caps set → ok");
|
|
475
|
+
assert(budgetState({ today: 999, month: 999 }, {}, true).reason === undefined, "ok carries no reason");
|
|
476
|
+
assert(budgetState({ today: 50, month: 0 }, { day: 0 }, true).level === "ok", "a zero cap is not a cap");
|
|
477
|
+
assert(budgetState({ today: 85, month: 120 }, { day: 100, month: 100 }, true).level === "over", "the month cap is checked and over wins");
|
|
478
|
+
assert(budgetState({ today: 85, month: 50 }, { day: 100, month: 100 }, true).level === "warn", "80% of either cap warns");
|
|
479
|
+
// Rule 4: estimate-only spend never reaches over.
|
|
480
|
+
assert(budgetState({ today: 0, month: 0, estimatedToday: 120 }, { day: 100 }, true).level === "warn", "estimate-only spend is capped at warn, never over");
|
|
481
|
+
assert(budgetState({ today: 0, month: 0, estimatedToday: 120 }, { day: 100 }, false).level === "warn", "estimate-only spend is warn with enforce off too");
|
|
482
|
+
assert(budgetState({ today: 120, month: 0, estimatedToday: 30 }, { day: 100 }, true).level === "over", "a billed crossing is over even with estimates in the mix");
|
|
483
|
+
// Billed 90 of a 100 cap already warns on its own: the estimate did not push it there, so the
|
|
484
|
+
// reason must not claim the over-cap is estimate-only.
|
|
485
|
+
const mixed = budgetState({ today: 90, month: 0, estimatedToday: 40 }, { day: 100 }, true);
|
|
486
|
+
assert(mixed.level === "warn" && !(mixed.reason ?? "").includes("never blocked"), "a mixed warn does not claim estimate-only: " + mixed.reason);
|
|
487
|
+
// Pinned reason strings.
|
|
488
|
+
assert(
|
|
489
|
+
budgetState({ today: 6, month: 0 }, { day: 5 }, true).reason === "day cap $5.00 at 120% ($6.00 billed) — turn blocked",
|
|
490
|
+
"over + enforce reason pinned: " + budgetState({ today: 6, month: 0 }, { day: 5 }, true).reason,
|
|
491
|
+
);
|
|
492
|
+
assert(
|
|
493
|
+
budgetState({ today: 6, month: 0 }, { day: 5 }, false).reason === "day cap $5.00 at 120% ($6.00 billed) — enforcement off",
|
|
494
|
+
"over + enforce off reason pinned",
|
|
495
|
+
);
|
|
496
|
+
assert(budgetState({ today: 4, month: 0 }, { day: 5 }, true).reason === "day cap $5.00 at 80% ($4.00 spent)", "warn reason pinned");
|
|
497
|
+
assert(
|
|
498
|
+
budgetState({ today: 0, month: 0, estimatedToday: 6 }, { day: 5 }, true).reason === "day cap $5.00 at 120% ($6.00 spent) — estimate only, never blocked",
|
|
499
|
+
"estimate-capped reason pinned",
|
|
500
|
+
);
|
|
501
|
+
|
|
502
|
+
// The fixed cap choices and their labels.
|
|
503
|
+
assert(nextCap(undefined) === 1 && nextCap(0) === 1 && nextCap(5) === 10 && nextCap(7.5) === 10 && nextCap(500) === 0, "nextCap cycles the choices, past the largest wraps to off");
|
|
504
|
+
assert(capLabel(undefined) === "off" && capLabel(0) === "off" && capLabel(5) === "$5.00", "capLabel pinned");
|
|
505
|
+
|
|
506
|
+
// Settings: absent reads as unset / off; a set value persists through the fixture config.
|
|
507
|
+
assert(activeBudgetDay() === undefined && activeBudgetMonth() === undefined && activeBudgetEnforce() === false, "no caps, enforce off by default");
|
|
508
|
+
setBudgetDay(5);
|
|
509
|
+
setBudgetEnforce(true);
|
|
510
|
+
assert(activeBudgetDay() === 5 && loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE) === 5, "a day cap is stored and reads back");
|
|
511
|
+
assert(activeBudgetEnforce() === true && loadChoice(BUDGET_ENFORCE_KEY, ["on", "off"] as const) === "on", "enforce is stored as on/off");
|
|
512
|
+
setBudgetDay(undefined);
|
|
513
|
+
assert(activeBudgetDay() === undefined && loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE) === undefined, "clearing the cap stores the empty string (unset)");
|
|
514
|
+
|
|
515
|
+
// The spend comes from the day buckets: one billed $6 entry today → today and 30d both $6.
|
|
516
|
+
mkdirSync(join(fixture, "sessions", "p"), { recursive: true });
|
|
517
|
+
const asst = (cost: number) =>
|
|
518
|
+
JSON.stringify({
|
|
519
|
+
message: { role: "assistant", provider: "google", model: "m", timestamp: Date.now(), usage: { input: 10, output: 5, cost: { total: cost, totalFromProvider: true } } },
|
|
520
|
+
});
|
|
521
|
+
writeFileSync(join(fixture, "sessions", "p", "s.jsonl"), asst(6) + "\n");
|
|
522
|
+
resetUsageCache();
|
|
523
|
+
const spend = spendNow();
|
|
524
|
+
assert(spend !== null && spend.today === 6 && spend.month === 6 && spend.estimatedToday === 0, "spend reads the day buckets (today / 30d): " + JSON.stringify(spend));
|
|
525
|
+
|
|
526
|
+
// The level right now, through the same memoized summary.
|
|
527
|
+
assert(budgetLevelNow() === "ok", "no caps → ok");
|
|
528
|
+
setBudgetDay(5);
|
|
529
|
+
assert(budgetLevelNow() === "over", "$6 of a $5 day cap is over");
|
|
530
|
+
setBudgetDay(7.5);
|
|
531
|
+
assert(budgetLevelNow() === "warn", "$6 of $7.50 is exactly 80% → warn");
|
|
532
|
+
setBudgetDay(undefined);
|
|
533
|
+
|
|
534
|
+
// The gate, driven through a fake pi.
|
|
535
|
+
const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
|
|
536
|
+
registerBudget({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
|
|
537
|
+
const notes: { msg: string; level: string }[] = [];
|
|
538
|
+
const ctxOf = (): unknown => ({ ui: { notify: (msg: string, level: string) => void notes.push({ msg, level }) } });
|
|
539
|
+
const ev = (source: string) => ({ type: "input", text: "hi", source });
|
|
540
|
+
const input = async (source: string, ctx: unknown) => (await handlers.input!(ev(source), ctx)) as { action: string };
|
|
541
|
+
|
|
542
|
+
setBudgetDay(5); // $6 spent → 120% of the day cap
|
|
543
|
+
setBudgetEnforce(false);
|
|
544
|
+
assert((await input("interactive", ctxOf())).action === "continue", "over + enforce off lets the turn through");
|
|
545
|
+
assert(notes.length === 1 && notes[0]!.level === "warning", "over + enforce off notifies once, as a warning");
|
|
546
|
+
assert(notes[0]!.msg === "day cap $5.00 at 120% ($6.00 billed) — enforcement off", "the notify carries the pinned reason: " + notes[0]!.msg);
|
|
547
|
+
assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 1, "the second over-input does not notify again (once per session)");
|
|
548
|
+
assert((await input("extension", ctxOf())).action === "continue" && notes.length === 1, "an extension-injected input is never swallowed and never notifies");
|
|
549
|
+
await handlers.session_start!({}, undefined);
|
|
550
|
+
setBudgetEnforce(true);
|
|
551
|
+
assert((await input("interactive", ctxOf())).action === "handled", "over + enforce on blocks the next turn");
|
|
552
|
+
assert(notes.length === 2 && notes[1]!.level === "error" && notes[1]!.msg === "day cap $5.00 at 120% ($6.00 billed) — turn blocked", "over + enforce on notifies an error with the pinned reason");
|
|
553
|
+
assert(
|
|
554
|
+
(await input("interactive", { get ui(): unknown { throw new Error("boom"); } })).action === "continue",
|
|
555
|
+
"a throwing handler path fails open: continue, never block",
|
|
556
|
+
);
|
|
557
|
+
assert(notes.length === 2, "the failed notify was not recorded");
|
|
558
|
+
setBudgetDay(7.5); // 80% → warn: no notify, the turn goes through
|
|
559
|
+
assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "warn does not notify and does not block");
|
|
560
|
+
|
|
561
|
+
// Unknown spend (no day buckets) never blocks, even with enforce on and a cap set.
|
|
562
|
+
const empty = mkdtempSync(join(tmpdir(), "arnative-budget-empty-"));
|
|
563
|
+
process.env.PI_CODING_AGENT_DIR = empty;
|
|
564
|
+
clearSlots();
|
|
565
|
+
resetPresetCache();
|
|
566
|
+
resetUsageCache();
|
|
567
|
+
setBudgetDay(5);
|
|
568
|
+
setBudgetEnforce(true);
|
|
569
|
+
assert(spendNow() === null, "no day buckets → the spend is unknown");
|
|
570
|
+
assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "unknown spend never blocks");
|
|
571
|
+
|
|
572
|
+
// No caps set → the gate is a no-op.
|
|
573
|
+
process.env.PI_CODING_AGENT_DIR = fixture;
|
|
574
|
+
clearSlots();
|
|
575
|
+
resetPresetCache();
|
|
576
|
+
resetUsageCache();
|
|
577
|
+
setBudgetEnforce(true);
|
|
578
|
+
setBudgetDay(undefined);
|
|
579
|
+
assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "no caps → continue, no notify");
|
|
580
|
+
|
|
581
|
+
// The Budget screen rows carry the live values and the pinned copy.
|
|
582
|
+
setBudgetDay(5);
|
|
583
|
+
const rows = budgetRows();
|
|
584
|
+
assert(rows.map((r) => r.label).join(",") === "Day cap,30d cap,Enforce", "the Budget rows: " + rows.map((r) => r.label).join(","));
|
|
585
|
+
assert(rows[0]!.note === "$5.00" && rows[1]!.note === "off", "the cap rows show the stored caps");
|
|
586
|
+
assert(rows[2]!.note === ENFORCE_ON_NOTE && ENFORCE_ON_NOTE === "on — blocks the next turn over a cap", "the enforce row is pinned: " + rows[2]!.note);
|
|
587
|
+
assert(BUDGET_PICKER_TEXT.title === "Budget - Arnative\u2819", "the Budget screen title is pinned: " + BUDGET_PICKER_TEXT.title);
|
|
588
|
+
assert(
|
|
589
|
+
BUDGET_PICKER_TEXT.description === "Warn-only caps on the UTC day and the rolling 30d — enforce on blocks the next turn.",
|
|
590
|
+
"the Budget screen description is pinned",
|
|
591
|
+
);
|
|
592
|
+
assert(BUDGET_PICKER_TEXT.legend === "[↑↓] Move [Space] Change [Esc] Back", "the Budget legend is pinned");
|
|
593
|
+
assert(rowText(rows[0]!) === "Day cap · $5.00", "the headless row text is pinned: " + rowText(rows[0]!));
|
|
594
|
+
|
|
595
|
+
// The dashboard: the two spend-vs-cap windows, pure and pinned.
|
|
596
|
+
const windows = budgetWindows(spendNow(), { day: activeBudgetDay(), month: activeBudgetMonth() }, activeBudgetEnforce());
|
|
597
|
+
assert(windows.length === 2 && windows[0]!.label === "Today" && windows[1]!.label === "30d", "two status windows: " + windows.map((w) => w.label).join(","));
|
|
598
|
+
assert(windows[0]!.pct === 120 && windows[0]!.level === "over" && windows[0]!.frac === 1, "today $6 of a $5 cap is 120% over, bar full: " + JSON.stringify(windows[0]));
|
|
599
|
+
assert(windows[1]!.cap === undefined && windows[1]!.level === "ok" && windows[1]!.frac === 0 && windows[1]!.pct === undefined, "no month cap → no bar, no percent, ok");
|
|
600
|
+
assert(budgetWindows(null, { day: 5 }, true).every((w) => w.unknown), "unknown spend (no day buckets) flags both windows");
|
|
601
|
+
assert(budgetWindows({ today: 0, month: 0, estimatedToday: 6 }, { day: 5 }, true)[0]!.level === "warn", "estimate-only today spend warns, never over");
|
|
602
|
+
|
|
603
|
+
// The modal render: status bars above the editable rows, through the shared screen frame.
|
|
604
|
+
const modalTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
|
|
605
|
+
const changed: number[] = [];
|
|
606
|
+
const modal = new BudgetModalComponent(
|
|
607
|
+
modalTheme as never,
|
|
608
|
+
budgetRows(),
|
|
609
|
+
{ change: (i) => void changed.push(i), done: () => {}, requestRender: () => {} },
|
|
610
|
+
BUDGET_PICKER_TEXT as never,
|
|
611
|
+
);
|
|
612
|
+
const rendered = modal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
|
|
613
|
+
assert(rendered.some((l) => l.includes("Budget - Arnative")), "the modal keeps the shared screen title");
|
|
614
|
+
assert(rendered[0]!.includes("╭") && rendered[rendered.length - 1]!.includes("╰"), "the modal keeps the shared screen frame");
|
|
615
|
+
assert(rendered.some((l) => l.includes("Today") && l.includes("█") && l.includes("120%") && l.includes("OVER")), "the Today row shows spend, bar, percent and level");
|
|
616
|
+
assert(rendered.some((l) => l.includes("30d") && l.includes("no cap")), "the uncapped window says no cap");
|
|
617
|
+
assert(rendered.some((l) => l.includes("Day cap") && l.includes("$5.00")), "the editable rows render with their notes");
|
|
618
|
+
modal.handleInput("\x1b[B"); // down
|
|
619
|
+
modal.handleInput(" "); // space
|
|
620
|
+
assert(changed.length === 1 && changed[0] === 1, "down+space changes the second row (30d cap), not the first");
|
|
621
|
+
assert(modal.render(40).length > 0, "the modal renders on a narrow terminal");
|
|
622
|
+
|
|
623
|
+
// Both windows capped: the bars share one column however long the spend-of-cap text is.
|
|
624
|
+
setBudgetMonth(10);
|
|
625
|
+
const aligned = modal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
|
|
626
|
+
const todayBar = aligned.find((l) => l.includes("Today") && l.includes("█"))!;
|
|
627
|
+
const monthBar = aligned.find((l) => l.includes("30d") && l.includes("█"))!;
|
|
628
|
+
assert(todayBar.includes("█") && monthBar.includes("█"), "both capped windows draw a bar");
|
|
629
|
+
assert(todayBar.indexOf("█") === monthBar.indexOf("█"), "both bars start on the same column: " + JSON.stringify([todayBar, monthBar]));
|
|
630
|
+
|
|
631
|
+
// The level colors come from the active theme's semantic slots: OK accent, WARN warning,
|
|
632
|
+
// OVER error. The theme records (slot, text) pairs: literal tags would count as width and
|
|
633
|
+
// truncate the render.
|
|
634
|
+
const calls: { slot: string; text: string }[] = [];
|
|
635
|
+
const slotTheme = { fg: (c: string, t: string) => (calls.push({ slot: c, text: t }), t), bold: (t: string) => t };
|
|
636
|
+
const slotModal = new BudgetModalComponent(slotTheme as never, budgetRows(), { change: () => {}, done: () => {}, requestRender: () => {} }, BUDGET_PICKER_TEXT as never);
|
|
637
|
+
slotModal.render(80); // today OVER (120% of $5), 30d OK (60% of $10)
|
|
638
|
+
assert(calls.find((c) => c.text === "OVER")?.slot === "error", "OVER paints with the theme's error slot");
|
|
639
|
+
assert(calls.find((c) => c.text === "OK")?.slot === "accent", "OK paints with the theme's accent slot");
|
|
640
|
+
setBudgetMonth(7); // 30d $6 of $7 = 85% → WARN
|
|
641
|
+
slotModal.render(80);
|
|
642
|
+
assert(calls.filter((c) => c.text === "WARN").pop()?.slot === "warning", "WARN paints with the theme's warning slot");
|
|
643
|
+
setBudgetMonth(undefined);
|
|
644
|
+
|
|
645
|
+
// An estimated-cost entry adds the `Total · $X est.` line under the windows.
|
|
646
|
+
writeFileSync(
|
|
647
|
+
join(fixture, "sessions", "p", "e.jsonl"),
|
|
648
|
+
JSON.stringify({ message: { role: "assistant", provider: "google", model: "m", timestamp: Date.now(), usage: { input: 1, output: 1, cost: { total: 2 } } } }) + "\n",
|
|
649
|
+
);
|
|
650
|
+
resetUsageCache();
|
|
651
|
+
const estRendered = modal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
|
|
652
|
+
assert(estRendered.some((l) => l.includes("Total · $4.00 est.")), "the estimated total line renders: " + estRendered.filter((l) => l.includes("Total")).join(" | "));
|
|
653
|
+
rmSync(join(fixture, "sessions", "p", "e.jsonl"));
|
|
654
|
+
resetUsageCache();
|
|
655
|
+
|
|
656
|
+
// Restore: the next module load starts from the real agent dir and the stored defaults.
|
|
657
|
+
rmSync(fixture, { recursive: true, force: true });
|
|
658
|
+
rmSync(empty, { recursive: true, force: true });
|
|
659
|
+
if (prevDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
|
|
660
|
+
else process.env.PI_CODING_AGENT_DIR = prevDir;
|
|
661
|
+
clearSlots();
|
|
662
|
+
resetPresetCache();
|
|
663
|
+
resetUsageCache();
|
|
664
|
+
console.log("budget.ts self-check OK");
|
|
665
|
+
}
|