@bismawy/pi-arnative 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 {
@@ -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
 
@@ -25,9 +25,10 @@ import {
25
25
  CHATBOX_PROMPT_KEY as CHATBOX_PROMPT_CONFIG_KEY,
26
26
  FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY,
27
27
  FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY,
28
+ choiceSetting,
29
+ flagSetting,
28
30
  loadChoice,
29
31
  resetPresetCache,
30
- saveChoice,
31
32
  } from "../lib/preset-store.ts";
32
33
  import { formatCost } from "./usage.ts";
33
34
  import { isByteLimitedModel, wireBytesSnapshot } from "./autocompact.ts";
@@ -47,41 +48,34 @@ import { spinnerPainter } from "../lib/spinner.ts";
47
48
  export const CHATBOX_PRESETS = ["Pi (system)", "Arnative"] as const;
48
49
  export type ChatboxPreset = (typeof CHATBOX_PRESETS)[number];
49
50
  export const DEFAULT_CHATBOX_PRESET: ChatboxPreset = "Arnative";
50
- const CHATBOX_PRESET_KEY = Symbol.for("pi-arnative.chatboxPreset");
51
+ const chatboxPreset = choiceSetting(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS, DEFAULT_CHATBOX_PRESET);
52
+ const CHATBOX_PRESET_KEY = chatboxPreset.slot;
51
53
 
52
54
  export const CHATBOX_PROMPTS = ["❯", ">", "›", "▸", "→", "\uf44f", "\udb82\udf79", "\uf51b", "\udb80\udf7d", "\uf120", "\uf489", "\udb80\udd7a"] as const;
53
55
  export type ChatboxPrompt = (typeof CHATBOX_PROMPTS)[number];
54
56
  export const DEFAULT_CHATBOX_PROMPT: ChatboxPrompt = "❯";
55
- const CHATBOX_PROMPT_KEY = Symbol.for("pi-arnative.chatboxPrompt");
57
+ const chatboxPrompt = choiceSetting(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS, DEFAULT_CHATBOX_PROMPT);
58
+ const CHATBOX_PROMPT_KEY = chatboxPrompt.slot;
56
59
 
57
60
  export const CHATBOX_DIALOGS = ["Left", "Center", "Right", "Inside", "Outside"] as const;
58
61
  export type ChatboxDialog = (typeof CHATBOX_DIALOGS)[number];
59
62
  export const DEFAULT_CHATBOX_DIALOG: ChatboxDialog = "Left";
60
- const CHATBOX_DIALOG_KEY = Symbol.for("pi-arnative.chatboxDialog");
63
+ const chatboxDialog = choiceSetting(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS, DEFAULT_CHATBOX_DIALOG);
64
+ const CHATBOX_DIALOG_KEY = chatboxDialog.slot;
61
65
 
62
66
  export const PROMPT_IDLE_MS = 3_000;
63
67
  const PROMPT_TYPED_AT_KEY = Symbol.for("pi-arnative.promptTypedAt");
64
68
  const PROMPT_IDLE_TIMER_KEY = Symbol.for("pi-arnative.promptIdleTimer");
65
69
 
66
- export function activeChatboxPreset(): ChatboxPreset {
67
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] ?? loadChoice(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS);
68
- return CHATBOX_PRESETS.includes(stored as ChatboxPreset) ? (stored as ChatboxPreset) : DEFAULT_CHATBOX_PRESET;
69
- }
70
-
70
+ export const activeChatboxPreset = (): ChatboxPreset => chatboxPreset.get();
71
71
  export function setChatboxPreset(name: ChatboxPreset): void {
72
- (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] = name;
73
- saveChoice(CHATBOX_PRESET_CONFIG_KEY, name);
72
+ chatboxPreset.set(name);
74
73
  poke();
75
74
  }
76
75
 
77
- export function activeChatboxPrompt(): ChatboxPrompt {
78
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] ?? loadChoice(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS);
79
- return CHATBOX_PROMPTS.includes(stored as ChatboxPrompt) ? (stored as ChatboxPrompt) : DEFAULT_CHATBOX_PROMPT;
80
- }
81
-
76
+ export const activeChatboxPrompt = (): ChatboxPrompt => chatboxPrompt.get();
82
77
  export function setChatboxPrompt(prompt: ChatboxPrompt): void {
83
- (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] = prompt;
84
- saveChoice(CHATBOX_PROMPT_CONFIG_KEY, prompt);
78
+ chatboxPrompt.set(prompt);
85
79
  poke();
86
80
  }
87
81
 
@@ -90,14 +84,9 @@ export function nextChatboxPrompt(current: ChatboxPrompt = activeChatboxPrompt()
90
84
  return CHATBOX_PROMPTS[(idx + 1) % CHATBOX_PROMPTS.length]!;
91
85
  }
92
86
 
93
- export function activeChatboxDialog(): ChatboxDialog {
94
- const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] ?? loadChoice(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS);
95
- return CHATBOX_DIALOGS.includes(stored as ChatboxDialog) ? (stored as ChatboxDialog) : DEFAULT_CHATBOX_DIALOG;
96
- }
97
-
87
+ export const activeChatboxDialog = (): ChatboxDialog => chatboxDialog.get();
98
88
  export function setChatboxDialog(dialog: ChatboxDialog): void {
99
- (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] = dialog;
100
- saveChoice(CHATBOX_DIALOG_CONFIG_KEY, dialog);
89
+ chatboxDialog.set(dialog);
101
90
  poke();
102
91
  }
103
92
 
@@ -206,29 +195,21 @@ export function minimalExpanded(): { left: boolean; right: boolean } {
206
195
  (globalThis as Record<symbol, { left: boolean; right: boolean }>)[MINIMAL_EXPAND_KEY] = fresh;
207
196
  return fresh;
208
197
  }
209
- const FOOTER_PRESET_KEY = Symbol.for("pi-arnative.footerPreset");
198
+ const footerPreset = choiceSetting(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS, DEFAULT_FOOTER_PRESET);
199
+ const FOOTER_PRESET_KEY = footerPreset.slot;
210
200
  const FOOTER_REGISTRAR_KEY = Symbol.for("pi-arnative.footerRegistrar");
211
- const FOOTER_COST_KEY = Symbol.for("pi-arnative.footerCost");
201
+ const footerCost = flagSetting(FOOTER_COST_CONFIG_KEY);
212
202
 
213
- /** Is the session cost cell on? Stored as `"on"`/`"off"` so an absent key reads as off
214
- * through the same allow-list path every other choice uses. */
215
- export function activeFooterCost(): boolean {
216
- const stored = (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] ?? loadChoice(FOOTER_COST_CONFIG_KEY, ["on", "off"] as const);
217
- return stored === "on";
218
- }
203
+ /** Is the session cost cell on? */
204
+ export const activeFooterCost = (): boolean => footerCost.get();
219
205
 
220
- /** Flip the cost cell, persist it, and repaint the footer at once — the choice is a command
221
- * the user asked for, so it is not part of the picker's preview/revert dance. */
206
+ /** Flip the cost cell, persist it, and repaint the footer at once. */
222
207
  export function setFooterCost(on: boolean): void {
223
- (globalThis as Record<symbol, unknown>)[FOOTER_COST_KEY] = on ? "on" : "off";
224
- saveChoice(FOOTER_COST_CONFIG_KEY, on ? "on" : "off");
208
+ footerCost.set(on);
225
209
  poke();
226
210
  }
227
211
 
228
- export function activeFooterPreset(): FooterPreset {
229
- const stored = (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] ?? loadChoice(FOOTER_PRESET_CONFIG_KEY, FOOTER_PRESETS);
230
- return FOOTER_PRESETS.includes(stored as FooterPreset) ? (stored as FooterPreset) : DEFAULT_FOOTER_PRESET;
231
- }
212
+ export const activeFooterPreset = (): FooterPreset => footerPreset.get();
232
213
 
233
214
  /**
234
215
  * Hand the footer slot to the active preset: arnative's grid, or pi's built-in footer.
@@ -245,8 +226,7 @@ export function applyFooterPreset(ctx: ExtensionContext): void {
245
226
  }
246
227
  /** Select a preset and apply it immediately (the footer swaps on the spot). */
247
228
  export function setFooterPreset(name: FooterPreset, ctx: ExtensionContext): void {
248
- (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY] = name;
249
- saveChoice(FOOTER_PRESET_CONFIG_KEY, name);
229
+ footerPreset.set(name);
250
230
  applyFooterPreset(ctx);
251
231
  }
252
232
 
@@ -1343,8 +1323,10 @@ export function wrapInputListener(tui: unknown): () => void {
1343
1323
  };
1344
1324
  const target = tui as { handleTerminalInput?: (data: string) => void };
1345
1325
  if (!target || typeof target.handleTerminalInput !== "function") return () => {};
1346
- if (!(globalThis as Record<symbol, boolean>)[WRAPPED_TUI_KEY]) {
1347
- (globalThis as Record<symbol, boolean>)[WRAPPED_TUI_KEY] = true;
1326
+ const g = globalThis as Record<symbol, unknown>;
1327
+ const wrapped = g[WRAPPED_TUI_KEY] instanceof WeakSet ? (g[WRAPPED_TUI_KEY] as WeakSet<object>) : (g[WRAPPED_TUI_KEY] = new WeakSet<object>());
1328
+ if (!wrapped.has(target)) {
1329
+ wrapped.add(target);
1348
1330
  const original = target.handleTerminalInput;
1349
1331
  target.handleTerminalInput = function (this: unknown, data: string): void {
1350
1332
  // One keystroke, one activity. The wrapper runs before `original`, and `pi-tui`
@@ -37,7 +37,7 @@ import { tmpdir } from "node:os";
37
37
  import { join } from "node:path";
38
38
  import { assert, isMain } from "../lib/check.ts";
39
39
  import { patchOnce } from "../lib/patch.ts";
40
- import { RENDER_CACHE_KEY, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
40
+ import { RENDER_CACHE_KEY, choiceSetting, loadChoice, resetPresetCache } from "../lib/preset-store.ts";
41
41
 
42
42
  /** Stored exactly as the picker shows them; `"On"` is the default. */
43
43
  export const RENDER_CACHE_CHOICES = ["On", "Off"] as const;
@@ -122,20 +122,14 @@ function getCacheState(): RenderCacheState {
122
122
  return g[RENDER_CACHE_STATE_KEY] as RenderCacheState;
123
123
  }
124
124
 
125
+ const renderCacheSetting = choiceSetting(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES, DEFAULT_RENDER_CACHE);
126
+
125
127
  /** Current Render cache mode (`"On"` by default). */
126
- export function activeRenderCache(): RenderCacheChoice {
127
- const stored =
128
- (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] ??
129
- loadChoice(RENDER_CACHE_KEY, RENDER_CACHE_CHOICES);
130
- return RENDER_CACHE_CHOICES.includes(stored as RenderCacheChoice)
131
- ? (stored as RenderCacheChoice)
132
- : DEFAULT_RENDER_CACHE;
133
- }
128
+ export const activeRenderCache = (): RenderCacheChoice => renderCacheSetting.get();
134
129
 
135
130
  /** Update the Render cache choice and drop stale cached frames. */
136
131
  export function setRenderCache(choice: RenderCacheChoice): void {
137
- (globalThis as Record<symbol, unknown>)[RENDER_CACHE_CONFIG_KEY] = choice;
138
- saveChoice(RENDER_CACHE_KEY, choice);
132
+ renderCacheSetting.set(choice);
139
133
  clearRenderCache();
140
134
  }
141
135
 
@@ -37,7 +37,7 @@ import { BRAND, renderBoxLines } from "../lib/box.ts";
37
37
  import { getActiveTheme, setActiveTheme, softOf, softSecondaryOf, stripAnsi, themeOf } from "../lib/ansi.ts";
38
38
  import { capitalize, expandKeyName, modelDisplayParts } from "../lib/format.ts";
39
39
  import { SHORTCUT_NEW_SESSION, SHORTCUT_NEXT_TAB, SHORTCUT_RELOAD } from "../lib/shortcuts.ts";
40
- import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, loadChoice, saveChoice } from "../lib/preset-store.ts";
40
+ import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, choiceSetting } from "../lib/preset-store.ts";
41
41
  import { formatTokens, getModelAllTimeUsage } from "../lib/usage-store.ts";
42
42
 
43
43
  import { patchOnce } from "../lib/patch.ts";
@@ -417,12 +417,9 @@ export const tabStore: Map<TabKey, string[]> =
417
417
  export const HEADER_PRESETS = ["Pi (system)", "Arnative (Full)"] as const;
418
418
  export type HeaderPreset = (typeof HEADER_PRESETS)[number];
419
419
  export const DEFAULT_HEADER_PRESET: HeaderPreset = "Arnative (Full)";
420
- const HEADER_PRESET_KEY = Symbol.for("pi-arnative.headerPreset");
420
+ const headerPreset = choiceSetting(HEADER_PRESET_CONFIG_KEY, HEADER_PRESETS, DEFAULT_HEADER_PRESET);
421
421
 
422
- export function activeHeaderPreset(): HeaderPreset {
423
- const stored = (globalThis as Record<symbol, unknown>)[HEADER_PRESET_KEY] ?? loadChoice(HEADER_PRESET_CONFIG_KEY, HEADER_PRESETS);
424
- return HEADER_PRESETS.includes(stored as HeaderPreset) ? (stored as HeaderPreset) : DEFAULT_HEADER_PRESET;
425
- }
422
+ export const activeHeaderPreset = (): HeaderPreset => headerPreset.get();
426
423
 
427
424
  /** Hand the header slot to the active preset: arnative's box, or pi's built-in ("Pi (system)"). */
428
425
  export function applyHeaderPreset(ctx: ExtensionContext): void {
@@ -435,8 +432,7 @@ export function applyHeaderPreset(ctx: ExtensionContext): void {
435
432
 
436
433
  /** Select a preset and apply it immediately (real-time: the header swaps on the spot). */
437
434
  export function setHeaderPreset(name: HeaderPreset, ctx: ExtensionContext): void {
438
- (globalThis as Record<symbol, unknown>)[HEADER_PRESET_KEY] = name;
439
- saveChoice(HEADER_PRESET_CONFIG_KEY, name);
435
+ headerPreset.set(name);
440
436
  applyHeaderPreset(ctx);
441
437
  }
442
438