@bismawy/pi-arnative 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/shortcuts.ts CHANGED
@@ -37,12 +37,14 @@ export const SHORTCUT_RELOAD = build("r");
37
37
  export const SHORTCUT_TOGGLE_FOOTER = build("m");
38
38
  /** Expand/collapse the task list widget. Same platform split: Alt+o on Windows/WSL. */
39
39
  export const SHORTCUT_TOGGLE_TODOS = build("o");
40
+ /** Open the /arnative settings menu. Alt+a on Windows/WSL, Ctrl+alt+a elsewhere. */
41
+ export const SHORTCUT_OPEN_ARNATIVE = build("a");
40
42
  /** Scroll the expanded task list: `j` down, `k` up, one task per press. */
41
43
  export const SHORTCUT_SCROLL_TODOS_DOWN = build("j");
42
44
  export const SHORTCUT_SCROLL_TODOS_UP = build("k");
43
45
 
44
- /** The one "go back" key: `←` leaves a screen for its parent, while Esc closes or reverts
45
- * it. Defined here so no screen can advertise a key another screen does not handle. */
46
+ /** The `←` byte matcher. Esc is the advertised way out of a screen (Back, or Close at the
47
+ * root); `←` stays as an alias so muscle memory keeps working, but no footer names it. */
46
48
  export const BACK_KEY_LABEL = "←";
47
49
  export function matchesBack(data: string): boolean {
48
50
  return matchesKey(data, "left");
@@ -65,23 +67,34 @@ const MOVE = keySet("↑↓", "up", "down");
65
67
  const CHOOSE = keySet("Enter", "enter");
66
68
  const BACK = keySet(BACK_KEY_LABEL, "left");
67
69
  const CANCEL = keySet("Esc", "escape");
68
- const QUIT = keySet("q/Esc", "q", "escape");
70
+ /** The usage dashboard window switch: Tab forward, Shift+Tab back. */
71
+ const RANGE = keySet("Tab", "tab");
72
+ /** Upper case on purpose: the lower case keys already navigate, so a plain r cannot
73
+ * start a destructive flow by accident. Both footers name the capital letter. */
74
+ export const RESET_USAGE = keySet("R", "shift+r");
75
+ /** The undo of a reset, offered only while a reset is the last thing that happened. */
76
+ export const UNDO_USAGE = keySet("U", "shift+u");
69
77
 
70
78
  const legend = (...pairs: [string, string][]): string => pairs.map(([key, action]) => `[${key}] ${action}`).join(" ");
71
79
 
72
- /** Root `/arnative` menu: nothing behind it, so `←` is not advertised — Esc closes. */
80
+ /** Root `/arnative` menu: nothing behind it, so Esc closes. */
73
81
  export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Close"]);
74
- /** Move-and-open list inside a submenu (the provider list, the provider actions):
75
- * `←` steps back to the screen above. */
76
- export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [BACK.label, "Back"], [CANCEL.label, "Close"]);
77
- /** Live-preview list: moving applies, Enter keeps, `←` steps out, Esc reverts. */
78
- export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [BACK.label, "Back"], [CANCEL.label, "Revert"]);
82
+ /** Move-and-open list inside a submenu (the provider list, the provider actions): Esc steps
83
+ * back to the screen above, exactly like ←. */
84
+ export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Back"]);
85
+ /** Live-preview list: moving applies, Enter keeps, Esc drops the preview and steps out. */
86
+ export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [CANCEL.label, "Back"]);
79
87
  /** A list you only read (the `/todos` recap): moving changes nothing, so there is no Open. */
80
88
  export const LEGEND_READ_ONLY = legend([MOVE.label, "Move"], [CANCEL.label, "Close"]);
81
- /** The read-only usage dashboard. The full legend needs the room, so a narrow box degrades. */
82
- export function legendUsage(width: number): string {
83
- const full = legend([MOVE.label, "Move"], ["Click", "Open/close"], [BACK.label, "Back"], [QUIT.label, "Exit"]);
84
- return width >= visibleWidth(full) ? full : legend([QUIT.label, "Exit"]);
89
+ /** The usage dashboard. `reset` adds the key that deletes history, so a screen without
90
+ * that key never advertises it; `undo` appears only while a reset can be undone. */
91
+ export function legendUsage(width: number, opts: { reset?: boolean; undo?: boolean } = {}): string {
92
+ const pairs: [string, string][] = [[MOVE.label, "Move"], [RANGE.label, "Range"], ["Click", "Open/close"]];
93
+ if (opts.reset) pairs.push([CANCEL.label, "Back"], [RESET_USAGE.label, "Reset"]);
94
+ if (opts.undo) pairs.push([UNDO_USAGE.label, "Undo"]);
95
+ if (!opts.reset) pairs.push([CANCEL.label, "Back"]);
96
+ const full = legend(...pairs);
97
+ return width >= visibleWidth(full) ? full : legend([CANCEL.label, "Back"]);
85
98
  }
86
99
 
87
100
  if (isMain(import.meta.url)) {
@@ -117,20 +130,23 @@ if (isMain(import.meta.url)) {
117
130
  assert(!matchesBack("h"), "a bare letter is not the back key");
118
131
  // The legends are built from the same keys the handlers match, so a key cannot be
119
132
  // advertised on one screen and handled on none.
120
- assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", `root menu legend pinned, got ${LEGEND_MOVE}`);
121
- assert(LEGEND_MOVE.includes("[←] Back"), "the root menu advertises ← Back");
133
+ assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Back", `submenu legend pinned, got ${LEGEND_MOVE}`);
122
134
  assert(LEGEND_READ_ONLY === "[↑↓] Move [Esc] Close", `read-only legend pinned, got ${LEGEND_READ_ONLY}`);
123
135
  assert(
124
- LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${BACK_KEY_LABEL}] Back [Esc] Revert`,
136
+ LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${CANCEL.label}] Back`,
125
137
  `live legend pinned, got ${LEGEND_LIVE}`,
126
138
  );
127
139
  assert(MOVE.matches("\x1b[A") && MOVE.matches("\x1b[B"), "the ↑↓ key matches both arrows");
128
140
  assert(CHOOSE.matches("\r"), "[Enter] matches carriage return");
129
- assert(BACK.matches("\x1b[D"), "[←] in the legend is the same key matchesBack accepts");
141
+ assert(BACK.matches("\x1b[D"), "← is still the back key, even when the footer names only Esc");
130
142
  assert(CANCEL.matches("\x1b"), "[Esc] matches escape");
131
- assert(!CANCEL.matches("\x1b[D"), "[Esc] is not the back key");
132
- assert(legendUsage(120).includes(`[${BACK_KEY_LABEL}] Back`), "a wide usage legend advertises back");
143
+ assert(!CANCEL.matches("\x1b[D"), "[Esc] is not the ← byte sequence");
144
+ assert(legendUsage(120).includes("[Esc] Back"), "a wide usage legend advertises Esc Back");
133
145
  assert(legendUsage(120).includes("[Click] Open/close"), "a wide usage legend advertises the mouse");
134
- assert(legendUsage(20) === "[q/Esc] Exit", "a narrow usage legend degrades to the one key that still fits");
146
+ assert(legendUsage(20) === "[Esc] Back", "a narrow usage legend degrades to the one key that still fits");
147
+ assert(legendUsage(160, { reset: true }).includes("[R] Reset"), "a reset-capable dashboard advertises R Reset");
148
+ assert(!legendUsage(160).includes("Reset"), "the read-only dashboard does not advertise a key it lacks");
149
+ assert(RESET_USAGE.matches("R") && !RESET_USAGE.matches("r"), "a capital R is shift+r, not r");
150
+ assert(UNDO_USAGE.matches("U") && !UNDO_USAGE.matches("u"), "a capital U is shift+u, not u");
135
151
  console.log("shortcuts.ts self-check OK");
136
152
  }
@@ -21,6 +21,15 @@ export const STATUS_ICON = "\ueb1b";
21
21
  /** pi's own cap on a string-array widget (`InteractiveMode.MAX_WIDGET_LINES`). */
22
22
  export const MAX_STATUS_ROWS = 10;
23
23
 
24
+ // A row that opens with its own Nerd Font glyph (a private-use code point) and a space keeps
25
+ // that glyph as its mark in place of STATUS_ICON, such as model-heal's U+F06DE.
26
+ function ownMark(row: string): boolean {
27
+ const cp = row.codePointAt(0);
28
+ if (cp === undefined) return false;
29
+ const pua = (cp >= 0xe000 && cp <= 0xf8ff) || (cp >= 0xf0000 && cp <= 0xffffd);
30
+ return pua && row[cp > 0xffff ? 2 : 1] === " ";
31
+ }
32
+
24
33
  type FgTheme = { fg?(color: string, text: string): string } | null;
25
34
 
26
35
  /** `dim(text)`, or the plain text when the theme is absent or rejects the token. */
@@ -38,6 +47,7 @@ export function statusRows(th: FgTheme, rows: string[], width = Number.POSITIVE_
38
47
  const lines = rows
39
48
  .slice(0, MAX_STATUS_ROWS)
40
49
  .map((row, i) => {
50
+ if (i === 0 && ownMark(row)) return row.includes("\x1b") ? dim(th, " ") + row : dim(th, " " + row);
41
51
  const prefix = i === 0 ? ` ${STATUS_ICON} ` : " ";
42
52
  return row.includes("\x1b") ? dim(th, prefix) + row : dim(th, prefix + row);
43
53
  });
@@ -52,6 +62,10 @@ if (isMain(import.meta.url)) {
52
62
  "one space before the mark, one after, one dim span for the whole row",
53
63
  );
54
64
  assert(JSON.stringify(statusRows(null, ["plain"])) === JSON.stringify([" \ueb1b plain"]), "no theme renders the plain line");
65
+ assert(
66
+ JSON.stringify(statusRows(null, ["\u{f06de} model-heal: x", "y"])) === JSON.stringify([" \u{f06de} model-heal: x", " y"]),
67
+ "a row that opens with its own glyph keeps it as the mark",
68
+ );
55
69
  assert(
56
70
  JSON.stringify(statusRows({ fg: () => { throw new Error("unknown token"); } }, ["safe"])) === JSON.stringify([" \ueb1b safe"]),
57
71
  "a theme that rejects the token does not crash the render",
@@ -6,7 +6,7 @@
6
6
  * - No double counting: the active session is already in its own file, so it is
7
7
  * NOT re-added from sessionManager (that inflated the ↑↓ totals).
8
8
  */
9
- import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
9
+ import { closeSync, copyFileSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
10
10
  import { join, relative } from "node:path";
11
11
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
12
 
@@ -17,6 +17,33 @@ interface UsageEntry {
17
17
  output: number;
18
18
  cacheRead: number;
19
19
  cost: number;
20
+ /** Local day (YYYY-MM-DD) the message was written, so a range view can skip it. */
21
+ day: string;
22
+ }
23
+
24
+ /** A time window the dashboard can show. `all` is the whole history. */
25
+ export type UsageRange = "all" | "today" | "7d" | "30d" | "3m";
26
+
27
+ /** Tab order of the range bar. */
28
+ export const USAGE_RANGES: readonly UsageRange[] = ["all", "today", "7d", "30d", "3m"];
29
+
30
+ /** Local calendar day of a timestamp, the unit day buckets and ranges are compared in. */
31
+ export function dayKey(ms: number): string {
32
+ const d = new Date(ms);
33
+ const pad = (n: number): string => String(n).padStart(2, "0");
34
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
35
+ }
36
+
37
+ /** Local midnight where `range` starts: today, 7 or 30 calendar days back, 3 months back.
38
+ * `undefined` for `all`, which has no floor. */
39
+ export function rangeStart(range: UsageRange, now = Date.now()): number | undefined {
40
+ if (range === "all") return undefined;
41
+ const d = new Date(now);
42
+ d.setHours(0, 0, 0, 0);
43
+ if (range === "today") return d.getTime();
44
+ if (range === "3m") d.setMonth(d.getMonth() - 3);
45
+ else d.setDate(d.getDate() - (range === "7d" ? 6 : 29));
46
+ return d.getTime();
20
47
  }
21
48
 
22
49
  interface FileCacheItem {
@@ -36,8 +63,14 @@ interface FileCacheItem {
36
63
  /** Usage totals for one session file, per provider and per provider+model. */
37
64
  interface FileRollup {
38
65
  providers: Record<string, Rollup>;
66
+ /** provider\0model key -> day -> totals. Absent on an item cached before ranges
67
+ * existed; that item is re-parsed once so a range view never reads a wrong number. */
68
+ days?: Record<string, Record<string, Buckets>>;
39
69
  }
40
70
 
71
+ /** One day's totals for one provider\0model key. */
72
+ type Buckets = { msgs: number; input: number; output: number; cacheRead: number; cost: number };
73
+
41
74
  interface Rollup {
42
75
  sessions: number;
43
76
  msgs: number;
@@ -57,15 +90,26 @@ function addToRollup(r: Rollup, e: UsageEntry): void {
57
90
  r.cost += e.cost;
58
91
  }
59
92
 
93
+ const emptyBuckets = (): Buckets => ({ msgs: 0, input: 0, output: 0, cacheRead: 0, cost: 0 });
94
+
60
95
  /** Fold entries into an existing file rollup, updating provider and provider+model keys together. */
61
96
  function foldInto(rollup: FileRollup, entries: UsageEntry[]): void {
62
97
  if (entries.length === 0) return;
63
98
  for (const e of entries) {
64
99
  const key = `${e.provider}\u0000${e.model}`;
65
- (rollup.providers[e.provider] ??= emptyRollup());
66
- addToRollup(rollup.providers[e.provider]!, e);
67
- (rollup.providers[key] ??= emptyRollup());
68
- addToRollup(rollup.providers[key]!, e);
100
+ for (const k of [e.provider, key]) {
101
+ (rollup.providers[k] ??= emptyRollup());
102
+ addToRollup(rollup.providers[k]!, e);
103
+ }
104
+ // Day buckets are stored on the model key only: the provider row is their sum, so a
105
+ // long history is not written twice to disk.
106
+ const perDay = ((rollup.days ??= {})[key] ??= {});
107
+ const day = (perDay[e.day] ??= emptyBuckets());
108
+ day.msgs++;
109
+ day.input += e.input;
110
+ day.output += e.output;
111
+ day.cacheRead += e.cacheRead;
112
+ day.cost += e.cost;
69
113
  }
70
114
  // `sessions` counts the file, not the messages, so it is 1 once the file has any use.
71
115
  for (const key of Object.keys(rollup.providers)) rollup.providers[key]!.sessions = 1;
@@ -85,6 +129,7 @@ interface UsageModelStats {
85
129
  input: number;
86
130
  output: number;
87
131
  cacheRead: number;
132
+ /** Prompt + completion + cache reads: the same total a vendor dashboard reports. */
88
133
  totalTokens: number;
89
134
  cost: number;
90
135
  /** Cost reconstructed from the price table, only when `cost` is 0. Never folded into `cost`. */
@@ -220,7 +265,15 @@ const CACHE_VERSION = 4; // v4: per-file rollup (was raw entries in v3)
220
265
  /** The v5 disk shape: one-char keys, and only provider\0model rows — provider-level
221
266
  * rollups are derived on load, so every number is stored once. Keys on disk are
222
267
  * paths relative to the sessions dir (the absolute path dominated the old size). */
223
- type DiskItem = { m: number; s: number; c?: number; r: Record<string, [number, number, number, number, number]> };
268
+ type DiskItem = {
269
+ m: number;
270
+ s: number;
271
+ c?: number;
272
+ r: Record<string, [number, number, number, number, number]>;
273
+ /** provider\0model -> day -> the same five numbers. Optional: an item cached before
274
+ * ranges existed has none, and is re-parsed whole when a range is first asked for. */
275
+ d?: Record<string, Record<string, [number, number, number, number, number]>>;
276
+ };
224
277
 
225
278
  /** Decode one disk item (v5 compact or v4 full) into the in-memory shape. */
226
279
  function decodeDiskItem(raw: unknown): FileCacheItem | null {
@@ -244,7 +297,22 @@ function decodeDiskItem(raw: unknown): FileCacheItem | null {
244
297
  p.cacheRead += cacheRead;
245
298
  p.cost += cost;
246
299
  }
247
- return { mtimeMs: d.m, size: d.s, v: CACHE_VERSION, consumed: typeof d.c === "number" ? d.c : d.s, rollup };
300
+ return { mtimeMs: d.m, size: d.s, v: CACHE_VERSION, consumed: typeof d.c === "number" ? d.c : d.s, rollup: { providers: rollup.providers, ...(decodeDays(d.d) ?? {}) } };
301
+ }
302
+
303
+ /** Decode the optional day map; a missing or malformed one stays absent on purpose. */
304
+ function decodeDays(raw: unknown): { days: NonNullable<FileRollup["days"]> } | null {
305
+ if (!raw || typeof raw !== "object") return null;
306
+ const days: NonNullable<FileRollup["days"]> = {};
307
+ for (const [pm, perDay] of Object.entries(raw as Record<string, unknown>)) {
308
+ if (!perDay || typeof perDay !== "object") continue;
309
+ for (const [day, a] of Object.entries(perDay as Record<string, unknown>)) {
310
+ if (!Array.isArray(a) || a.length < 5) continue;
311
+ const [msgs, input, output, cacheRead, cost] = a as [number, number, number, number, number];
312
+ (days[pm] ??= {})[day] = { msgs, input, output, cacheRead, cost };
313
+ }
314
+ }
315
+ return Object.keys(days).length > 0 ? { days } : null;
248
316
  }
249
317
 
250
318
  /** Encode an in-memory item as v5: model rows only (see DiskItem). */
@@ -253,7 +321,13 @@ function encodeDiskItem(item: FileCacheItem): DiskItem {
253
321
  for (const [pm, roll] of Object.entries(item.rollup.providers)) {
254
322
  if (pm.includes("\u0000")) r[pm] = [roll.msgs, roll.input, roll.output, roll.cacheRead, roll.cost];
255
323
  }
256
- return { m: item.mtimeMs, s: item.size, c: item.consumed ?? item.size, r };
324
+ const d: NonNullable<DiskItem["d"]> = {};
325
+ for (const [pm, perDay] of Object.entries(item.rollup.days ?? {})) {
326
+ const out: Record<string, [number, number, number, number, number]> = {};
327
+ for (const [day, b] of Object.entries(perDay)) out[day] = [b.msgs, b.input, b.output, b.cacheRead, b.cost];
328
+ if (Object.keys(out).length > 0) d[pm] = out;
329
+ }
330
+ return { m: item.mtimeMs, s: item.size, c: item.consumed ?? item.size, r, ...(Object.keys(d).length > 0 ? { d } : {}) };
257
331
  }
258
332
 
259
333
  // Disk cache is memoized; save writes memory + disk together.
@@ -339,15 +413,18 @@ function scanSessionFiles(dir: string): string[] {
339
413
  return files;
340
414
  }
341
415
 
342
- /** Extract a usage entry from one line, or null when it is not an assistant message. */
343
- function entryOfLine(line: string): UsageEntry | null {
416
+ /** Extract a usage entry from one line, or null when it is not an assistant message.
417
+ * `fallbackDay` dates a line that carries no timestamp of its own (older records). */
418
+ function entryOfLine(line: string, fallbackDay: string): UsageEntry | null {
344
419
  // Loose prefilter (fast path only): exact key would break on JSON formatting changes
345
420
  // and silently drop usage. The role is re-checked on the parsed object below.
346
421
  if (!line || !line.includes('"role"')) return null;
347
422
  try {
348
- const m = JSON.parse(line)?.message;
423
+ const rec = JSON.parse(line) as { timestamp?: unknown; message?: { role?: string; provider?: string; model?: string; usage?: Record<string, unknown> } };
424
+ const m = rec?.message;
349
425
  if (m?.role !== "assistant") return null;
350
- const u = m.usage || {};
426
+ const u = (m.usage ?? {}) as { input?: unknown; output?: unknown; cacheRead?: unknown; cost?: { total?: unknown } };
427
+ const written = typeof rec.timestamp === "string" ? Date.parse(rec.timestamp) : Number.NaN;
351
428
  return {
352
429
  provider: String(m.provider || "unknown"),
353
430
  model: String(m.model || "unknown"),
@@ -355,6 +432,7 @@ function entryOfLine(line: string): UsageEntry | null {
355
432
  output: Number(u.output) || 0,
356
433
  cacheRead: Number(u.cacheRead) || 0,
357
434
  cost: Number(u.cost?.total) || 0,
435
+ day: Number.isFinite(written) ? dayKey(written) : fallbackDay,
358
436
  };
359
437
  } catch {
360
438
  return null;
@@ -366,21 +444,21 @@ function entryOfLine(line: string): UsageEntry | null {
366
444
  * be fed back to `readSync`; a trailing segment without a newline counts only when it parses, so
367
445
  * a write caught mid-flight is left for the next scan rather than dropped.
368
446
  */
369
- function parseBuffer(buf: Buffer): { entries: UsageEntry[]; consumed: number } {
447
+ function parseBuffer(buf: Buffer, fallbackDay: string): { entries: UsageEntry[]; consumed: number } {
370
448
  const entries: UsageEntry[] = [];
371
449
  let start = 0;
372
450
  let consumed = 0;
373
451
  for (;;) {
374
452
  const nl = buf.indexOf(10, start);
375
453
  if (nl === -1) break;
376
- const entry = entryOfLine(buf.toString("utf8", start, nl));
454
+ const entry = entryOfLine(buf.toString("utf8", start, nl), fallbackDay);
377
455
  if (entry) entries.push(entry);
378
456
  start = nl + 1;
379
457
  consumed = start;
380
458
  }
381
459
  if (start < buf.length) {
382
460
  const tail = buf.toString("utf8", start);
383
- const entry = entryOfLine(tail);
461
+ const entry = entryOfLine(tail, fallbackDay);
384
462
  if (entry) {
385
463
  entries.push(entry);
386
464
  consumed = buf.length;
@@ -423,6 +501,7 @@ function readTail(filePath: string, fromByte: number): Buffer | null {
423
501
  }
424
502
 
425
503
  let cachedSummary: UsageSummary | null = null;
504
+ let cachedRange: UsageRange | null = null;
426
505
  let lastScanMs = 0;
427
506
 
428
507
  /** Drop every in-memory memo so the next scan reads the cache file and the session files
@@ -432,15 +511,136 @@ let lastScanMs = 0;
432
511
  export function resetUsageCache(): void {
433
512
  diskMemo = null;
434
513
  cachedSummary = null;
514
+ cachedRange = null;
435
515
  lastScanMs = 0;
436
516
  }
437
517
 
438
- export function collectUsageSummary(forceScan = false): UsageSummary {
518
+ // =============================================================================
519
+ // Reset: move the history aside, never destroy it
520
+ // =============================================================================
521
+ //
522
+ // The numbers on the dashboard are not a counter we own: they are a fold over Pi's
523
+ // session files. Deleting the cache changes nothing, so a real reset has to move those
524
+ // files. They go to `arnative/usage-trash/<stamp>/` with their folder structure intact,
525
+ // which is what makes the reset undoable; Pi simply stops seeing them, and `/resume`
526
+ // forgets those sessions until they are moved back.
527
+
528
+ /** Where a reset parks the history: one folder per reset, so two resets never collide. */
529
+ export function usageTrashRoot(): string {
530
+ return join(cacheDir(), "usage-trash");
531
+ }
532
+
533
+ /** What a reset would move: used by the confirmation line, before anything is touched. */
534
+ export function usageHistorySize(keep: readonly string[] = []): { files: number; bytes: number } {
535
+ const sessionsDir = join(getAgentDir(), "sessions");
536
+ const kept = new Set(keep.map((p) => p.toLowerCase()));
537
+ let files = 0;
538
+ let bytes = 0;
539
+ for (const file of scanSessionFiles(sessionsDir)) {
540
+ if (kept.has(file.toLowerCase())) continue;
541
+ try {
542
+ bytes += statSync(file).size;
543
+ files++;
544
+ } catch {
545
+ // Vanished between the scan and the stat: it is gone, so it is not part of the total.
546
+ }
547
+ }
548
+ return { files, bytes };
549
+ }
550
+
551
+ /** Move every session file except `keep` (the one in use) into the trash, and drop the
552
+ * cache. Returns the folder to pass to {@link restoreUsageHistory}. */
553
+ export function resetUsageHistory(keep: readonly string[] = []): { moved: number; bytes: number; dir: string } {
554
+ const sessionsDir = join(getAgentDir(), "sessions");
555
+ const kept = new Set(keep.map((p) => p.toLowerCase()));
556
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
557
+ const dir = join(usageTrashRoot(), stamp);
558
+ let moved = 0;
559
+ let bytes = 0;
560
+ for (const file of scanSessionFiles(sessionsDir)) {
561
+ if (kept.has(file.toLowerCase())) continue;
562
+ const rel = relative(sessionsDir, file);
563
+ const dest = join(dir, rel);
564
+ try {
565
+ bytes += statSync(file).size;
566
+ mkdirSync(join(dest, ".."), { recursive: true });
567
+ try {
568
+ renameSync(file, dest);
569
+ } catch {
570
+ // Different volume: copy, then drop the original.
571
+ copyFileSync(file, dest);
572
+ unlinkSync(file);
573
+ }
574
+ moved++;
575
+ } catch {
576
+ // A locked file (Windows, session still open elsewhere) stays where it is: the reset
577
+ // moved what it could, and the confirmation line reports the count it actually moved.
578
+ }
579
+ }
580
+ resetUsageCache();
581
+ return { moved, bytes, dir };
582
+ }
583
+
584
+ /** The undo of {@link resetUsageHistory}: move the parked files back into place. */
585
+ export function restoreUsageHistory(dir: string): { restored: number } {
586
+ const sessionsDir = join(getAgentDir(), "sessions");
587
+ let restored = 0;
588
+ for (const file of scanSessionFiles(dir)) {
589
+ const dest = join(sessionsDir, relative(dir, file));
590
+ try {
591
+ mkdirSync(join(dest, ".."), { recursive: true });
592
+ if (existsSync(dest)) continue; // A new session took that name: keep both.
593
+ try {
594
+ renameSync(file, dest);
595
+ } catch {
596
+ copyFileSync(file, dest);
597
+ unlinkSync(file);
598
+ }
599
+ restored++;
600
+ } catch {
601
+ // Locked: leave it in the trash, the rest still comes back.
602
+ }
603
+ }
604
+ resetUsageCache();
605
+ return { restored };
606
+ }
607
+
608
+ /** One file's rollup, narrowed to the days a range covers. Same shape the `all` path reads
609
+ * straight from `providers`, so the aggregation below runs once for both. */
610
+ function rollupSince(rollup: FileRollup, sinceDay: string): Record<string, Rollup> {
611
+ const out: Record<string, Rollup> = {};
612
+ for (const [pm, perDay] of Object.entries(rollup.days ?? {})) {
613
+ const sep = pm.indexOf("\u0000");
614
+ if (sep === -1) continue;
615
+ const pname = pm.slice(0, sep);
616
+ for (const [day, b] of Object.entries(perDay)) {
617
+ if (day < sinceDay) continue;
618
+ for (const key of [pm, pname]) {
619
+ const r = (out[key] ??= emptyRollup());
620
+ r.msgs += b.msgs;
621
+ r.input += b.input;
622
+ r.output += b.output;
623
+ r.cacheRead += b.cacheRead;
624
+ r.cost += b.cost;
625
+ }
626
+ }
627
+ }
628
+ for (const r of Object.values(out)) r.sessions = 1;
629
+ return out;
630
+ }
631
+
632
+ export function collectUsageSummary(forceScan = false, range: UsageRange = "all"): UsageSummary {
439
633
  const now = Date.now();
440
- if (!forceScan && cachedSummary && now - lastScanMs < 5000) {
634
+ if (!forceScan && cachedSummary && cachedRange === range && now - lastScanMs < 5000) {
441
635
  return cachedSummary;
442
636
  }
443
637
 
638
+ // A range reads day buckets, so a file cached before they existed is parsed once more.
639
+ // `all` never needs them, which keeps the first open of the dashboard as cheap as before.
640
+ const start = rangeStart(range, now);
641
+ const sinceDay = start === undefined ? "" : dayKey(start);
642
+ const needDays = start !== undefined;
643
+
444
644
  const sessionsDir = join(getAgentDir(), "sessions");
445
645
  const files = scanSessionFiles(sessionsDir);
446
646
  const diskCache = loadDiskCache();
@@ -469,6 +669,8 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
469
669
 
470
670
  let cached = diskCache.get(file);
471
671
  if (!(cached && cached.v === CACHE_VERSION && cached.rollup)) cached = undefined;
672
+ if (cached && needDays && !cached.rollup.days) cached = undefined;
673
+ const fallbackDay = dayKey(stat.mtimeMs);
472
674
 
473
675
  if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
474
676
  // Unchanged since the last scan: its rollup already holds everything.
@@ -477,7 +679,7 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
477
679
  // the existing rollup. (A shrunk file, or one whose size is below the offset,
478
680
  // re-parses whole — see the final branch.)
479
681
  const tail = readTail(file, cached.consumed!);
480
- const parsed = tail ? parseBuffer(tail) : null;
682
+ const parsed = tail ? parseBuffer(tail, fallbackDay) : null;
481
683
  if (parsed) {
482
684
  foldInto(cached.rollup, parsed.entries);
483
685
  cached.consumed = cached.consumed! + parsed.consumed;
@@ -485,19 +687,19 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
485
687
  cached.size = stat.size;
486
688
  } else {
487
689
  // Unreadable: fall back to whole-file.
488
- const full = parseBuffer(readFileSync(file));
690
+ const full = parseBuffer(readFileSync(file), fallbackDay);
489
691
  cached = { mtimeMs: stat.mtimeMs, size: stat.size, v: CACHE_VERSION, consumed: full.consumed, rollup: rollupOfFile(full.entries) };
490
692
  diskCache.set(file, cached);
491
693
  }
492
694
  cacheDirty = true;
493
695
  } else {
494
- const full = parseBuffer(readFileSync(file));
696
+ const full = parseBuffer(readFileSync(file), fallbackDay);
495
697
  cached = { mtimeMs: stat.mtimeMs, size: stat.size, v: CACHE_VERSION, consumed: full.consumed, rollup: rollupOfFile(full.entries) };
496
698
  diskCache.set(file, cached);
497
699
  cacheDirty = true;
498
700
  }
499
701
 
500
- for (const [key, r] of Object.entries(cached.rollup.providers)) {
702
+ for (const [key, r] of Object.entries(needDays ? rollupSince(cached.rollup, sinceDay) : cached.rollup.providers)) {
501
703
  const sep = key.indexOf("\u0000");
502
704
  const pname = sep === -1 ? key : key.slice(0, sep);
503
705
  if (!providerMap.has(pname)) {
@@ -570,7 +772,7 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
570
772
  input: mData.input,
571
773
  output: mData.output,
572
774
  cacheRead: mData.cacheRead,
573
- totalTokens: mData.input + mData.output,
775
+ totalTokens: mData.input + mData.output + mData.cacheRead,
574
776
  cost: mData.cost,
575
777
  });
576
778
  }
@@ -583,7 +785,7 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
583
785
  input: pData.input,
584
786
  output: pData.output,
585
787
  cacheRead: pData.cacheRead,
586
- totalTokens: pData.input + pData.output,
788
+ totalTokens: pData.input + pData.output + pData.cacheRead,
587
789
  cost: pData.cost,
588
790
  models,
589
791
  });
@@ -613,13 +815,14 @@ export function collectUsageSummary(forceScan = false): UsageSummary {
613
815
  input: totalInp,
614
816
  output: totalOut,
615
817
  cacheRead: totalCache,
616
- totalTokens: totalInp + totalOut,
818
+ totalTokens: totalInp + totalOut + totalCache,
617
819
  cost: totalCost,
618
820
  reportedCost: totalCost,
619
821
  estimatedCost,
620
822
  },
621
823
  };
622
824
  lastScanMs = now;
825
+ cachedRange = range;
623
826
  return cachedSummary;
624
827
  }
625
828
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bismawy/pi-arnative",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -43,6 +43,7 @@
43
43
  "dev": "pi --extension ./extensions/tools.ts --extension ./extensions/section-headers.ts --extension ./extensions/footer.ts --extension ./extensions/timestamps.ts --extension ./extensions/ui-render-tweaks.ts --extension ./extensions/usage.ts --extension ./extensions/animations.ts --extension ./extensions/autocompact.ts --extension ./extensions/model-heal.ts --extension ./extensions/todos.ts --extension ./extensions/arnative.ts",
44
44
  "test": "node lib/box.ts && node lib/patch.ts && node lib/ansi.ts && node lib/color.ts && node lib/shortcuts.ts && node lib/status-widget.ts && node lib/preset-store.ts && node lib/spinner.ts && node lib/todos.ts && node themes/gen-themes.mjs --check && node extensions/tools.ts && node lib/list-picker.ts && node lib/compat.ts && node lib/provider.ts && node lib/model-heal.ts && node extensions/footer.ts && node extensions/timestamps.ts && node extensions/ui-render-tweaks.ts && node extensions/usage.ts && node extensions/animations.ts && node extensions/autocompact.ts && node extensions/model-heal.ts && node extensions/todos.ts && node extensions/arnative.ts && node scripts/reporter.mjs --self-check && node --test --test-reporter=./scripts/reporter.mjs",
45
45
  "preview": "node scripts/preview.mjs",
46
+ "overlay": "node scripts/overlay.mjs",
46
47
  "themes": "node themes/gen-themes.mjs",
47
48
  "release:check": "node scripts/release-check.mjs pre-tag",
48
49
  "prepublishOnly": "npm test && node scripts/release-check.mjs pre-publish"
@@ -0,0 +1,89 @@
1
+ {
2
+ "$schema": "https://pi.dev/schemas/theme.schema.json",
3
+ "name": "arnative-blossom",
4
+ "appearance": "dark",
5
+ "vars": {
6
+ "fg": "oklch(88% 0.015 6)",
7
+ "fgMuted": "oklch(72% 0.015 6)",
8
+ "fgDim": "oklch(61% 0.015 6)",
9
+ "fgFaint": "oklch(49% 0.015 6)",
10
+ "primary": "oklch(69.9% 0.17 6)",
11
+ "secondary": "oklch(87.3% 0.072 2)",
12
+ "secondarySoft": "oklch(90% 0.0252 2)",
13
+ "accent": "oklch(78% 0.129 18)",
14
+ "accentSoft": "oklch(90% 0.04515 18)",
15
+ "accentBorder": "oklch(82% 0.101 18)",
16
+ "success": "oklch(78% 0.15 145)",
17
+ "error": "oklch(76% 0.143 25)",
18
+ "warning": "oklch(86% 0.14 85)",
19
+ "tone": "oklch(84% 0.10 350)",
20
+ "surfaceMsg": "oklch(19% 0.05 6)"
21
+ },
22
+ "colors": {
23
+ "accent": "accent",
24
+ "border": "oklch(55% 0.063 2)",
25
+ "borderAccent": "accentSoft",
26
+ "borderMuted": "fgFaint",
27
+ "success": "success",
28
+ "error": "error",
29
+ "warning": "warning",
30
+ "muted": "fgMuted",
31
+ "dim": "fgDim",
32
+ "text": "fg",
33
+
34
+ "thinkingText": "fgMuted",
35
+ "selectedBg": "oklch(31% 0.045 2)",
36
+ "scrollbarTrack": "fgFaint",
37
+ "scrollbarThumb": "accentSoft",
38
+ "searchMatchBg": "oklch(38% 0.081 18)",
39
+ "searchMatchText": "fg",
40
+ "userMessageBg": "surfaceMsg",
41
+ "userMessageText": "fg",
42
+ "customMessageBg": "oklch(25% 0.05 6)",
43
+ "customMessageText": "fg",
44
+ "customMessageLabel": "oklch(78% 0.126 6)",
45
+ "toolPendingBg": "oklch(22% 0.05 18)",
46
+ "toolSuccessBg": "oklch(21% 0.06 145)",
47
+ "toolErrorBg": "oklch(21% 0.06 25)",
48
+ "toolTitle": "fg",
49
+
50
+ "toolOutput": "fgMuted",
51
+ "mdHeading": "primary",
52
+ "mdLink": "tone",
53
+ "mdLinkUrl": "fgDim",
54
+ "mdCode": "tone",
55
+ "mdCodeBlock": "success",
56
+ "mdCodeBlockBorder": "fgMuted",
57
+ "mdQuote": "fgMuted",
58
+ "mdQuoteBorder": "fgMuted",
59
+ "mdHr": "fgFaint",
60
+
61
+ "mdListBullet": "accent",
62
+ "toolDiffAdded": "success",
63
+ "toolDiffRemoved": "error",
64
+ "toolDiffContext": "fgMuted",
65
+ "syntaxComment": "fgDim",
66
+ "syntaxKeyword": "oklch(80% 0.115 18)",
67
+ "syntaxFunction": "oklch(86% 0.079 6)",
68
+ "syntaxVariable": "oklch(84% 0.088 18)",
69
+ "syntaxString": "oklch(82% 0.126 140)",
70
+ "syntaxNumber": "oklch(80% 0.123 2)",
71
+ "syntaxType": "oklch(80% 0.137 350)",
72
+ "syntaxOperator": "fg",
73
+
74
+ "syntaxPunctuation": "fgMuted",
75
+ "thinkingOff": "oklch(40% 0.015 6)",
76
+ "thinkingMinimal": "oklch(47% 0.045 18)",
77
+ "thinkingLow": "oklch(55% 0.072 18)",
78
+ "thinkingMedium": "oklch(63% 0.108 18)",
79
+ "thinkingHigh": "oklch(71% 0.144 18)",
80
+ "thinkingXhigh": "oklch(79% 0.122 18)",
81
+ "thinkingMax": "accent",
82
+ "bashMode": "success"
83
+ },
84
+ "export": {
85
+ "pageBg": "oklch(18% 0.015 6)",
86
+ "cardBg": "oklch(21% 0.015 6)",
87
+ "infoBg": "oklch(29% 0.045 18)"
88
+ }
89
+ }