@bismawy/pi-arnative 0.15.0 → 0.16.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +52 -67
  3. package/extensions/animations.ts +11 -26
  4. package/extensions/arnative.ts +253 -380
  5. package/extensions/autocompact.ts +17 -22
  6. package/extensions/budget.ts +87 -136
  7. package/extensions/footer.ts +79 -60
  8. package/extensions/model-heal.ts +0 -0
  9. package/extensions/render-cache.ts +29 -15
  10. package/extensions/section-headers.ts +4 -8
  11. package/extensions/timestamps.ts +118 -41
  12. package/extensions/todos.ts +83 -33
  13. package/extensions/tools.ts +13 -30
  14. package/extensions/ui-render-tweaks.ts +0 -0
  15. package/extensions/usage-export.ts +3 -12
  16. package/extensions/usage.ts +0 -0
  17. package/lib/ansi.ts +0 -0
  18. package/lib/box.ts +0 -0
  19. package/lib/check.ts +0 -0
  20. package/lib/color.ts +0 -0
  21. package/lib/compat.ts +117 -17
  22. package/lib/format.ts +0 -0
  23. package/lib/list-picker.ts +5 -5
  24. package/lib/model-heal.ts +4 -8
  25. package/lib/patch.ts +0 -0
  26. package/lib/preset-store.ts +63 -16
  27. package/lib/provider.ts +131 -17
  28. package/lib/shortcuts.ts +0 -0
  29. package/lib/spinner.ts +1 -1
  30. package/lib/status-widget.ts +0 -0
  31. package/lib/todos.ts +0 -0
  32. package/lib/usage-store.ts +11 -20
  33. package/package.json +1 -1
  34. package/themes/arnative-blossom.json +0 -0
  35. package/themes/arnative-crimson.json +0 -0
  36. package/themes/arnative-cyberpunk.json +0 -0
  37. package/themes/arnative-dracula.json +0 -0
  38. package/themes/arnative-earthy.json +0 -0
  39. package/themes/arnative-garden.json +0 -0
  40. package/themes/arnative-gruvbox.json +0 -0
  41. package/themes/arnative-lemonade.json +0 -0
  42. package/themes/arnative-magical.json +0 -0
  43. package/themes/arnative-matrix.json +0 -0
  44. package/themes/arnative-neutral.json +0 -0
  45. package/themes/arnative-nord.json +0 -0
  46. package/themes/arnative-zinc.json +0 -0
  47. package/themes/arnative.json +0 -0
  48. package/themes/gen-themes.mjs +0 -0
@@ -21,7 +21,7 @@ import { mkdtempSync, rmSync } from "node:fs";
21
21
  import { tmpdir } from "node:os";
22
22
  import { join } from "node:path";
23
23
  import { assert, isMain } from "../lib/check.ts";
24
- import { PAYLOAD_LIMIT_KEY, loadChoice, loadSetting, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
24
+ import { PAYLOAD_LIMIT_KEY, choiceSetting, loadChoice, loadSetting, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
25
25
  import { activeRenderCache, setRenderCache } from "./render-cache.ts";
26
26
 
27
27
  /** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
@@ -170,14 +170,10 @@ export function smartPercent(contextWindow: number, renderCacheOn = activeRender
170
170
 
171
171
  // Active choice on globalThis so the `/arnative` picker (a second module instance, see
172
172
  // animations.ts) and this module's event handlers agree without sharing memo caches.
173
- const AUTO_COMPACT_CONFIG_KEY = Symbol.for("pi-arnative.autoCompact");
173
+ const autoCompactSetting = choiceSetting(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES, DEFAULT_AUTO_COMPACT);
174
+ const AUTO_COMPACT_CONFIG_KEY = autoCompactSetting.slot;
174
175
 
175
- export function activeAutoCompact(): AutoCompactChoice {
176
- const stored =
177
- (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] ??
178
- loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES);
179
- return AUTO_COMPACT_CHOICES.includes(stored as AutoCompactChoice) ? (stored as AutoCompactChoice) : DEFAULT_AUTO_COMPACT;
180
- }
176
+ export const activeAutoCompact = (): AutoCompactChoice => autoCompactSetting.get();
181
177
 
182
178
  /** The trigger threshold in context tokens for the given window, or null when the
183
179
  * choice is off or Smart defers this window to pi's own compaction. */
@@ -192,10 +188,7 @@ export function activeAutoCompactThreshold(contextWindow: number): number | null
192
188
  }
193
189
 
194
190
  /** Pick a choice and persist it (the `/arnative` → Auto-compact rows call this). */
195
- export function setAutoCompact(choice: AutoCompactChoice): void {
196
- (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] = choice;
197
- saveChoice(AUTO_COMPACT_KEY, choice);
198
- }
191
+ export const setAutoCompact = (choice: AutoCompactChoice): void => autoCompactSetting.set(choice);
199
192
 
200
193
  /** Session-scoped trigger state. Module-local: only this module's registrar mutates it. */
201
194
  export interface AutoCompactState {
@@ -698,6 +691,7 @@ if (isMain(import.meta.url)) {
698
691
  process.env.PI_CODING_AGENT_DIR = fixture;
699
692
  delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
700
693
  delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
694
+ resetPresetCache();
701
695
 
702
696
  // Payload limit parsing, persistence, and Off mode.
703
697
  assert(parsePayloadLimit("off") === "Off", "parses off case-insensitively");
@@ -713,6 +707,7 @@ if (isMain(import.meta.url)) {
713
707
  delete (globalThis as Record<symbol, unknown>)[PAYLOAD_LIMIT_CONFIG_KEY];
714
708
  saveChoice(PAYLOAD_LIMIT_KEY, "1 MB");
715
709
  resetPresetCache();
710
+ const liveCeilings = activeByteCeilings()!;
716
711
 
717
712
  // Choice parsing and persistence.
718
713
  assert(activeAutoCompact() === "Off", "the default is off");
@@ -825,7 +820,7 @@ if (isMain(import.meta.url)) {
825
820
  // Emergency tail trim: a single massive toolResult in the newest turn still sheds below target.
826
821
  const tailOnlyHuge: MessageLike[] = [
827
822
  { role: "user", content: [{ type: "text", text: "run tool" }] },
828
- { role: "toolResult", content: [{ type: "text", text: "y".repeat(SHED_TRIGGER_BYTES + 20_000) }] },
823
+ { role: "toolResult", content: [{ type: "text", text: "y".repeat(liveCeilings.shedTriggerBytes + 20_000) }] },
829
824
  ];
830
825
  const tailShed = shedMessagesForByteLimit(tailOnlyHuge, 100_000);
831
826
  assert(tailShed.changed && tailShed.bytes <= 100_000, "emergency tail trim bounds even a single giant newest message");
@@ -886,17 +881,17 @@ if (isMain(import.meta.url)) {
886
881
  const hugeRunMsgs: MessageLike[] = [
887
882
  { role: "user", content: [{ type: "text", text: "start" }] },
888
883
  { role: "assistant", content: [{ type: "toolCall", arguments: { path: "x" } }] },
889
- { role: "toolResult", content: [{ type: "text", text: "z".repeat(SHED_TRIGGER_BYTES + 10_000) }] },
884
+ { role: "toolResult", content: [{ type: "text", text: "z".repeat(liveCeilings.shedTriggerBytes + 10_000) }] },
890
885
  { role: "user", content: [{ type: "text", text: "continue" }] },
891
886
  { role: "assistant", content: [{ type: "text", text: "ok" }] },
892
887
  ];
893
888
  const ctxResult = (await handlers.context!({ messages: hugeRunMsgs }, remoteCtx)) as { messages?: MessageLike[] } | undefined;
894
889
  assert(
895
890
  Array.isArray(ctxResult?.messages) &&
896
- jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= SHED_TARGET_BYTES,
891
+ jsonByteLength(ctxResult.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetBytes,
897
892
  "context hook sheds payload with hysteresis down to the target ceiling",
898
893
  );
899
- await handlers.before_provider_request!({ payload: { blob: "p".repeat(SHED_TRIGGER_BYTES + 20_000) } }, remoteCtx);
894
+ await handlers.before_provider_request!({ payload: { blob: "p".repeat(liveCeilings.shedTriggerBytes + 20_000) } }, remoteCtx);
900
895
  await handlers.agent_before_settle!({}, remoteCtx);
901
896
  assert(compactCalls.length === 6, "remote byte shedding does not force premature compaction at 49k tokens");
902
897
 
@@ -909,10 +904,10 @@ if (isMain(import.meta.url)) {
909
904
 
910
905
  // Compaction input trimming shrinks split-turn prefixes cleanly without triggering follow-ups.
911
906
  const splitTurnPrefix: MessageLike[] = [
912
- { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(COMPACT_INPUT_BYTES) } }] },
907
+ { role: "assistant", content: [{ type: "toolCall", arguments: { content: "q".repeat(liveCeilings.compactInputBytes) } }] },
913
908
  ];
914
909
  await handlers.session_before_compact!({ preparation: { turnPrefixMessages: splitTurnPrefix } }, remoteCtx);
915
- assert(jsonByteLength(splitTurnPrefix) < COMPACT_INPUT_BYTES, "session_before_compact trims split-turn prefix messages too");
910
+ assert(jsonByteLength(splitTurnPrefix) < liveCeilings.compactInputBytes, "session_before_compact trims split-turn prefix messages too");
916
911
 
917
912
  // Remote byte silent shedding stays active even when Auto-compact is Off, and never triggers ctx.compact().
918
913
  setAutoCompact("Off");
@@ -931,11 +926,11 @@ if (isMain(import.meta.url)) {
931
926
  // A fixture sized for the 1 MB default says nothing once the wall scales: at 16 MB
932
927
  // the same array is far under the trigger and the hook rightly stays quiet.
933
928
  // Size it against the ceiling in force, or skip when scaling makes that impractical.
934
- const overTrigger = jsonByteLength(manyMsgs) > SHED_TRIGGER_BYTES;
929
+ const overTrigger = jsonByteLength(manyMsgs) > liveCeilings.shedTriggerBytes;
935
930
  if (overTrigger) {
936
931
  assert(
937
932
  Array.isArray(shedMany?.messages) &&
938
- jsonByteLength(shedMany.messages) <= SHED_TARGET_BYTES &&
933
+ jsonByteLength(shedMany.messages) <= liveCeilings.shedTargetBytes &&
939
934
  shedMany.messages[0]?.role === "user",
940
935
  "many-message session sheds below the ceiling even with Auto-compact Off",
941
936
  );
@@ -945,7 +940,7 @@ if (isMain(import.meta.url)) {
945
940
  const compactMany = manyMsgs.slice();
946
941
  await handlers.session_before_compact!({ preparation: { messagesToSummarize: compactMany } }, remoteCtx);
947
942
  assert(
948
- jsonByteLength(compactMany) <= COMPACT_INPUT_BYTES && compactMany[0]?.role !== "toolResult",
943
+ jsonByteLength(compactMany) <= liveCeilings.compactInputBytes && compactMany[0]?.role !== "toolResult",
949
944
  "many-message compaction input trims below 720 KB without orphaned toolResult",
950
945
  );
951
946
  await handlers.agent_before_settle!({}, ctxOf(950000, 1_048_576, { id: "remote/agy-cli/gemini-4-hydrogen" }));
@@ -957,7 +952,7 @@ if (isMain(import.meta.url)) {
957
952
  const after413 = (await handlers.context!({ messages: hugeRunMsgs }, nonRemoteCtx)) as { messages?: MessageLike[] } | undefined;
958
953
  assert(
959
954
  Array.isArray(after413?.messages) &&
960
- jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= INITIAL_CEILINGS.shedTargetAfter413Bytes,
955
+ jsonByteLength(after413.messages) + DEFAULT_OVERHEAD_BYTES <= liveCeilings.shedTargetAfter413Bytes,
961
956
  "saw413 activates tighter silent shedding on any model",
962
957
  );
963
958
  // Payload limit Off skips shedding and clears wireBytesSnapshot even for remote models.
@@ -20,20 +20,19 @@
20
20
  * `budgetEnforce` `"on"`/`"off"`) and are edited from `/arnative` → **Budget** ({@link openBudget}).
21
21
  */
22
22
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
23
- import { matchesKey, truncateToWidth, visibleWidth, type Component } from "@earendil-works/pi-tui";
23
+ import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
24
24
  import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
25
25
  import { tmpdir } from "node:os";
26
26
  import { join } from "node:path";
27
- import { softOf, thinkingColorOf } from "../lib/ansi.ts";
28
- import { renderScreen, screenTitle } from "../lib/box.ts";
27
+ import { screenTitle } from "../lib/box.ts";
29
28
  import { assert, isMain } from "../lib/check.ts";
30
29
  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";
30
+ import { ListPicker, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
33
31
  import {
34
32
  BUDGET_DAY_KEY,
35
33
  BUDGET_ENFORCE_KEY,
36
34
  BUDGET_MONTH_KEY,
35
+ flagSetting,
37
36
  loadChoice,
38
37
  loadNumber,
39
38
  resetPresetCache,
@@ -53,7 +52,8 @@ export const BUDGET_CAPS = [0, 1, 2, 5, 10, 25, 50, 100, 250, 500] as const;
53
52
  // without sharing memo caches (the same pattern as the footer cost switch).
54
53
  const BUDGET_DAY_SLOT = Symbol.for("pi-arnative.budgetDay");
55
54
  const BUDGET_MONTH_SLOT = Symbol.for("pi-arnative.budgetMonth");
56
- const BUDGET_ENFORCE_SLOT = Symbol.for("pi-arnative.budgetEnforce");
55
+ const budgetEnforce = flagSetting(BUDGET_ENFORCE_KEY);
56
+ const BUDGET_ENFORCE_SLOT = budgetEnforce.slot;
57
57
 
58
58
  export function activeBudgetDay(): number | undefined {
59
59
  const stored = (globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT] ?? loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE);
@@ -66,10 +66,7 @@ export function activeBudgetMonth(): number | undefined {
66
66
  }
67
67
 
68
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
- }
69
+ export const activeBudgetEnforce = (): boolean => budgetEnforce.get();
73
70
 
74
71
  export function setBudgetDay(n: number | undefined): void {
75
72
  (globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT] = n !== undefined && n > 0 ? n : undefined;
@@ -81,10 +78,7 @@ export function setBudgetMonth(n: number | undefined): void {
81
78
  saveChoice(BUDGET_MONTH_KEY, n !== undefined && n > 0 ? String(n) : "");
82
79
  }
83
80
 
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
- }
81
+ export const setBudgetEnforce = (on: boolean): void => budgetEnforce.set(on);
88
82
 
89
83
  export function resetBudget(): void {
90
84
  setBudgetDay(undefined);
@@ -226,6 +220,12 @@ function changeBudgetRow(index: number): void {
226
220
  /** Width of the spend-vs-cap bar, in cells. */
227
221
  export const BUDGET_BAR_WIDTH = 20;
228
222
 
223
+ /** Total estimated spend across the displayed windows: rolling 30d already includes today. */
224
+ export function estimatedWindowTotal(spend: BudgetSpend | null): number {
225
+ if (!spend) return 0;
226
+ return Math.max(spend.estimatedMonth ?? 0, spend.estimatedToday ?? 0);
227
+ }
228
+
229
229
  export interface BudgetWindow {
230
230
  label: string;
231
231
  /** Billed spend in the window. */
@@ -250,7 +250,6 @@ export function budgetWindows(spend: BudgetSpend | null, caps: { day?: number; m
250
250
  const win = (label: string, billed: number, estimated: number, cap: number | undefined): BudgetWindow => {
251
251
  const total = billed + estimated;
252
252
  const base = { label, billed, estimated, total, cap, frac: 0, level: "ok" as BudgetLevel, unknown: false };
253
- if (spend === null) return { ...base, unknown: true };
254
253
  if (cap === undefined || !(cap > 0)) return base;
255
254
  // The window's own level: only its cap and its spend decide it, through the same
256
255
  // decision function the gate uses — estimate-only spend still caps at warn.
@@ -275,121 +274,75 @@ export function budgetWindows(spend: BudgetSpend | null, caps: { day?: number; m
275
274
  ];
276
275
  }
277
276
 
278
- /** The Budget dashboard: a spend-vs-cap status section over the editable cap rows. The frame
279
- * comes from `renderScreen` like every other arnative screen; the level colors reuse the
280
- * theme's warning/error slots (ok stays the accent, matching the footer band painter). */
281
- class BudgetModalComponent implements Component {
282
- private readonly theme: { fg(c: string, t: string): string; bold?(t: string): string };
283
- private readonly rows: ListRow[];
284
- private readonly hooks: { change(index: number): void; reset(): void; done(back: boolean): void; requestRender(): void };
285
- private readonly text: ListPickerText;
286
- private readonly edge: (s: string) => string;
287
- private selected = 0;
288
-
289
- constructor(
290
- theme: { fg(c: string, t: string): string; bold?(t: string): string },
291
- rows: ListRow[],
292
- hooks: { change(index: number): void; reset(): void; done(back: boolean): void; requestRender(): void },
293
- text: ListPickerText,
294
- thinkingLevel?: string,
295
- ) {
296
- this.theme = theme;
297
- this.rows = rows;
298
- this.hooks = hooks;
299
- this.text = text;
300
- this.edge = thinkingColorOf(theme, thinkingLevel);
301
- }
302
-
303
- invalidate(): void {
304
- /* renders are computed per call */
305
- }
306
- dispose(): void {
307
- /* no timer to clear */
308
- }
309
-
310
- handleInput(keyData: string): void {
311
- // Esc/← step back to /arnative, Q closes the screen — the same contract as ListPicker.
312
- if (matchesKey(keyData, "escape") || matchesBack(keyData)) {
313
- this.hooks.done(true);
314
- return;
315
- }
316
- if (keyData === "Q" || matchesKey(keyData, "q")) {
317
- this.hooks.done(false);
318
- return;
319
- }
320
- if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
321
- this.selected = Math.max(0, this.selected - 1);
322
- this.hooks.requestRender();
323
- return;
324
- }
325
- if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
326
- this.selected = Math.min(this.rows.length - 1, this.selected + 1);
327
- this.hooks.requestRender();
328
- return;
329
- }
330
- if (matchesKey(keyData, "space")) {
331
- this.hooks.change(this.selected);
332
- this.hooks.requestRender();
333
- return;
277
+ /** Spend-vs-cap status rows shown above the Budget editable rows inside `ListPicker`. */
278
+ function budgetSummaryLines(th: { fg(c: string, t: string): string }): string[] {
279
+ const dim = (s: string) => th.fg("dim", s);
280
+ const acc = (s: string) => th.fg("accent", s);
281
+ const levelPaint = (level: BudgetLevel) =>
282
+ level === "ok" ? acc : level === "warn" ? (s: string) => th.fg("warning", s) : (s: string) => th.fg("error", s);
283
+ const spend = spendNow();
284
+ const windows = budgetWindows(spend, { day: activeBudgetDay(), month: activeBudgetMonth() }, activeBudgetEnforce());
285
+ const capText = (w: BudgetWindow): string => (w.cap !== undefined && w.cap > 0 ? `${formatCost(w.total)} of ${formatCost(w.cap)}` : "");
286
+ const partW = Math.max(0, ...windows.map((w) => visibleWidth(capText(w))));
287
+ const body: string[] = [];
288
+ for (const w of windows) {
289
+ const label = dim(w.label.padEnd(5));
290
+ if (w.unknown) {
291
+ body.push(`${label} · ${dim("unknown — no day buckets yet")}`);
292
+ continue;
334
293
  }
335
- if (keyData === "R" || matchesKey(keyData, "r")) {
336
- this.hooks.reset();
337
- this.hooks.requestRender();
294
+ if (w.cap === undefined || !(w.cap > 0)) {
295
+ body.push(`${label} · ${th.fg("text", formatCost(w.total))} ${dim("no cap")}`);
296
+ continue;
338
297
  }
298
+ const paint = levelPaint(w.level);
299
+ const filled = Math.round(w.frac * BUDGET_BAR_WIDTH);
300
+ const bar = paint("█".repeat(filled)) + dim("░".repeat(BUDGET_BAR_WIDTH - filled));
301
+ const pct = `${w.pct}%`.padEnd(4);
302
+ body.push(`${label} · ${th.fg("text", capText(w).padEnd(partW))} ${bar} ${paint(pct)} · ${paint(w.level.toUpperCase())}`);
339
303
  }
304
+ // Rolling 30d already includes today, so use the 30d estimate without adding today twice.
305
+ const estimated = estimatedWindowTotal(spend);
306
+ if (estimated > 0) body.push(`${dim("Total")} · ${th.fg("text", `${formatCost(estimated)} est.`)}`);
307
+ return body;
308
+ }
340
309
 
341
- render(width: number): string[] {
342
- const th = this.theme;
343
- const bold = th.bold ?? ((t: string) => t);
344
- const dim = (s: string) => th.fg("dim", s);
345
- const acc = (s: string) => th.fg("accent", s);
346
- const soft = softOf(th);
347
- // Levels ride the active theme's semantic slots: OK accent, WARN warning, OVER error.
348
- const levelPaint = (level: BudgetLevel) =>
349
- level === "ok" ? acc : level === "warn" ? (s: string) => th.fg("warning", s) : (s: string) => th.fg("error", s);
350
- const contentW = Math.max(20, width - 4);
351
- const body: string[] = [];
352
-
353
- // Status: one line per window — `label · spend of cap bar pct% · LEVEL` — then the
354
- // estimated total. The bars share one column: the spend-of-cap text is padded to the
355
- // widest window, so a longer cap never shifts its neighbour's bar.
356
- const spend = spendNow();
357
- const windows = budgetWindows(spend, { day: activeBudgetDay(), month: activeBudgetMonth() }, activeBudgetEnforce());
358
- const capText = (w: BudgetWindow): string => (w.cap !== undefined && w.cap > 0 ? `${formatCost(w.total)} of ${formatCost(w.cap)}` : "");
359
- const partW = Math.max(0, ...windows.map((w) => visibleWidth(capText(w))));
360
- for (const w of windows) {
361
- const label = dim(w.label.padEnd(5));
362
- if (w.unknown) {
363
- body.push(`${label} · ${dim("unknown — no day buckets yet")}`);
364
- continue;
365
- }
366
- if (w.cap === undefined || !(w.cap > 0)) {
367
- body.push(`${label} · ${th.fg("text", formatCost(w.total))} ${dim("no cap")}`);
368
- continue;
369
- }
370
- const paint = levelPaint(w.level);
371
- const filled = Math.round(w.frac * BUDGET_BAR_WIDTH);
372
- const bar = paint("█".repeat(filled)) + dim("░".repeat(BUDGET_BAR_WIDTH - filled));
373
- const pct = `${w.pct}%`.padEnd(4);
374
- body.push(`${label} · ${th.fg("text", capText(w).padEnd(partW))} ${bar} ${paint(pct)} · ${paint(w.level.toUpperCase())}`);
375
- }
376
- // The estimated part of both windows, once: an estimate-only provider shows $0 billed
377
- // per window, so the total is the only place the guess is summed.
378
- const estimated = (spend?.estimatedToday ?? 0) + (spend?.estimatedMonth ?? 0);
379
- if (estimated > 0) body.push(`${dim("Total")} · ${th.fg("text", `${formatCost(estimated)} est.`)}`);
380
- body.push("");
381
-
382
- // Editable rows — the same rows the headless picker offers.
383
- for (let i = 0; i < this.rows.length; i++) {
384
- const row = this.rows[i]!;
385
- const isSelected = i === this.selected;
386
- const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg("text", s);
387
- const note = budgetRowNote(row.label);
388
- const noteText = note ? ` ${dim("·")} ${dim(note)}` : "";
389
- body.push(`${isSelected ? acc("❯ ") : " "}${paint(row.label)}${noteText}`);
390
- }
391
- return renderScreen(th, width, this.text, body.map((l) => truncateToWidth(l, contentW, "")), this.edge);
392
- }
310
+ /** The Budget dashboard built on the shared `ListPicker` chrome. */
311
+ function createBudgetPicker(
312
+ theme: { fg(c: string, t: string): string; bold?(t: string): string },
313
+ rows: ListRow[],
314
+ hooks: { change(index: number): void; reset(): void; done(back: boolean): void; requestRender(): void },
315
+ text: ListPickerText,
316
+ thinkingLevel?: string,
317
+ ): ListPicker {
318
+ const picker = new ListPicker(
319
+ theme,
320
+ rows,
321
+ undefined,
322
+ {
323
+ preview: () => {},
324
+ revert: () => {},
325
+ done: () => {},
326
+ back: () => hooks.done(true),
327
+ cancel: () => hooks.done(false),
328
+ toggle: () => {
329
+ hooks.change(picker.index);
330
+ hooks.requestRender();
331
+ },
332
+ press: (keyData) => {
333
+ if (keyData !== "R" && !matchesKey(keyData, "r")) return;
334
+ hooks.reset();
335
+ hooks.requestRender();
336
+ },
337
+ note: budgetRowNote,
338
+ summary: () => budgetSummaryLines(theme),
339
+ requestRender: hooks.requestRender,
340
+ },
341
+ text,
342
+ false,
343
+ thinkingLevel,
344
+ );
345
+ return picker;
393
346
  }
394
347
 
395
348
  /** `/arnative` → **Budget**: a dashboard of spend vs caps over the editable cap rows. */
@@ -407,28 +360,26 @@ export async function openBudget(ctx: ExtensionCommandContext): Promise<boolean
407
360
  return;
408
361
  }
409
362
 
410
- const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
411
- return new BudgetModalComponent(
363
+ const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) =>
364
+ createBudgetPicker(
412
365
  theme,
413
366
  budgetRows(),
414
367
  {
415
368
  change: (index) => {
416
369
  changeBudgetRow(index);
417
370
  announce(ctx.ui, `Budget: ${rowText(budgetRows()[index]!)}.`);
418
- tui.requestRender();
419
371
  },
420
372
  reset: () => {
421
373
  resetBudget();
422
374
  announce(ctx.ui, "Budget reset to defaults.");
423
- tui.requestRender();
424
375
  },
425
376
  done: (back) => done(back),
426
377
  requestRender: () => tui.requestRender(),
427
378
  },
428
379
  BUDGET_PICKER_TEXT,
429
380
  ctx.thinkingLevel,
430
- );
431
- });
381
+ ),
382
+ );
432
383
  return goBack === true;
433
384
  }
434
385
 
@@ -621,7 +572,7 @@ if (isMain(import.meta.url)) {
621
572
  const modalTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
622
573
  const changed: number[] = [];
623
574
  let resets = 0;
624
- const modal = new BudgetModalComponent(
575
+ const modal = createBudgetPicker(
625
576
  modalTheme as never,
626
577
  budgetRows(),
627
578
  { change: (i) => void changed.push(i), reset: () => void resets++, done: () => {}, requestRender: () => {} },
@@ -654,7 +605,7 @@ if (isMain(import.meta.url)) {
654
605
  // truncate the render.
655
606
  const calls: { slot: string; text: string }[] = [];
656
607
  const slotTheme = { fg: (c: string, t: string) => (calls.push({ slot: c, text: t }), t), bold: (t: string) => t };
657
- const slotModal = new BudgetModalComponent(slotTheme as never, budgetRows(), { change: () => {}, reset: () => {}, done: () => {}, requestRender: () => {} }, BUDGET_PICKER_TEXT as never);
608
+ const slotModal = createBudgetPicker(slotTheme as never, budgetRows(), { change: () => {}, reset: () => {}, done: () => {}, requestRender: () => {} }, BUDGET_PICKER_TEXT as never);
658
609
  slotModal.render(80); // today OVER (120% of $5), 30d OK (60% of $10)
659
610
  assert(calls.find((c) => c.text === "Today")?.slot === "dim", "Today label uses dim");
660
611
  assert(calls.find((c) => c.text === "30d ")?.slot === "dim", "30d label uses dim");
@@ -675,9 +626,9 @@ if (isMain(import.meta.url)) {
675
626
  resetUsageCache();
676
627
  calls.length = 0;
677
628
  const estRendered = slotModal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
678
- assert(estRendered.some((l) => l.includes("Total · $4.00 est.")), "the estimated total line renders: " + estRendered.filter((l) => l.includes("Total")).join(" | "));
629
+ assert(estRendered.some((l) => l.includes("Total · $2.00 est.")), "the estimated total line renders: " + estRendered.filter((l) => l.includes("Total")).join(" | "));
679
630
  assert(calls.find((c) => c.text === "Total")?.slot === "dim", "Total label uses dim");
680
- assert(calls.find((c) => c.text === "$4.00 est.")?.slot === "text", "Total value beside label uses default text color");
631
+ assert(calls.find((c) => c.text === "$2.00 est.")?.slot === "text", "Total value beside label uses default text color");
681
632
  rmSync(join(fixture, "sessions", "p", "e.jsonl"));
682
633
  resetUsageCache();
683
634