@bismawy/pi-arnative 0.6.2 → 0.8.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/shortcuts.ts CHANGED
@@ -64,8 +64,11 @@ const QUIT = keySet("q/Esc", "q", "escape");
64
64
 
65
65
  const legend = (...pairs: [string, string][]): string => pairs.map(([key, action]) => `[${key}] ${action}`).join(" ");
66
66
 
67
- /** Root menu: move and open. No `[←]` — the menu has no screen behind it. */
68
- export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Close"]);
67
+ /** Root `/arnative` menu: nothing behind it, so `←` is not advertised — Esc closes. */
68
+ export const LEGEND_ROOT = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [CANCEL.label, "Close"]);
69
+ /** Move-and-open list inside a submenu (the provider list, the provider actions):
70
+ * `←` steps back to the screen above. */
71
+ export const LEGEND_MOVE = legend([MOVE.label, "Move"], [CHOOSE.label, "Open"], [BACK.label, "Back"], [CANCEL.label, "Close"]);
69
72
  /** Live-preview list: moving applies, Enter keeps, `←` steps out, Esc reverts. */
70
73
  export const LEGEND_LIVE = legend([MOVE.label, "Preview"], [CHOOSE.label, "Select"], [BACK.label, "Back"], [CANCEL.label, "Revert"]);
71
74
  /** The read-only usage dashboard. The full legend needs the room, so a narrow box degrades. */
@@ -107,8 +110,8 @@ if (isMain(import.meta.url)) {
107
110
  assert(!matchesBack("h"), "a bare letter is not the back key");
108
111
  // The legends are built from the same keys the handlers match, so a key cannot be
109
112
  // advertised on one screen and handled on none.
110
- assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Close", `root menu legend pinned, got ${LEGEND_MOVE}`);
111
- assert(!LEGEND_MOVE.includes(BACK_KEY_LABEL), "the root menu does not advertise ←");
113
+ assert(LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", `root menu legend pinned, got ${LEGEND_MOVE}`);
114
+ assert(LEGEND_MOVE.includes("[←] Back"), "the root menu advertises ← Back");
112
115
  assert(
113
116
  LEGEND_LIVE === `[↑↓] Preview [Enter] Select [${BACK_KEY_LABEL}] Back [Esc] Revert`,
114
117
  `live legend pinned, got ${LEGEND_LIVE}`,
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * Token usage data layer — the single source for /usage and the Model tab.
3
3
  * - Scans local Pi session history (~/.pi/agent/sessions/*.jsonl).
4
- * - mtime+size keyed cache in ~/.pi/agent/arnative-usage-cache.json, read into
4
+ * - mtime+size keyed cache in ~/.pi/agent/arnative/usage-cache.json, read into
5
5
  * memory once (parsing 4MB per header frame cost ~50ms and lagged long chats).
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, statSync, writeFileSync } from "node:fs";
10
- import { dirname, join } from "node:path";
9
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
10
+ import { join, relative } from "node:path";
11
11
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
12
 
13
13
  interface UsageEntry {
@@ -207,9 +207,55 @@ export function formatTokens(n: number): string {
207
207
  }
208
208
 
209
209
  // Resolved per call, not at import: the self-check points getAgentDir() at a fixture dir.
210
- const cacheFilePath = (): string => join(getAgentDir(), "arnative-usage-cache.json");
210
+ // Everything pi-arnative writes lives in one folder (agent dir/arnative); the cache moved
211
+ // there from a flat arnative-usage-cache.json, which is migrated in on first read.
212
+ const cacheDir = (): string => join(getAgentDir(), "arnative");
213
+ const cacheFilePath = (): string => join(cacheDir(), "usage-cache.json");
214
+ const legacyCachePath = (): string => join(getAgentDir(), "arnative-usage-cache.json");
215
+ /** Dead since pricing moved into `cost` fields in models.json: nothing reads it, so the
216
+ * first load after the update removes it (layout "1" — see lib/preset-store.ts). */
217
+ const legacyPricesPath = (): string => join(getAgentDir(), "arnative-prices.json");
211
218
  const CACHE_VERSION = 4; // v4: per-file rollup (was raw entries in v3)
212
219
 
220
+ /** The v5 disk shape: one-char keys, and only provider\0model rows — provider-level
221
+ * rollups are derived on load, so every number is stored once. Keys on disk are
222
+ * 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]> };
224
+
225
+ /** Decode one disk item (v5 compact or v4 full) into the in-memory shape. */
226
+ function decodeDiskItem(raw: unknown): FileCacheItem | null {
227
+ if (!raw || typeof raw !== "object") return null;
228
+ if ("rollup" in raw) {
229
+ const v4 = raw as FileCacheItem;
230
+ return v4.rollup ? { ...v4, v: CACHE_VERSION } : null;
231
+ }
232
+ const d = raw as Partial<DiskItem>;
233
+ if (typeof d.m !== "number" || typeof d.s !== "number" || !d.r) return null;
234
+ const rollup: FileRollup = { providers: {} };
235
+ for (const [pm, a] of Object.entries(d.r)) {
236
+ if (!Array.isArray(a) || a.length < 5) continue;
237
+ const [msgs, input, output, cacheRead, cost] = a as [number, number, number, number, number];
238
+ Object.assign((rollup.providers[pm] ??= emptyRollup()), { sessions: 1, msgs, input, output, cacheRead, cost });
239
+ const p = (rollup.providers[pm.split("\u0000")[0]!] ??= emptyRollup());
240
+ p.sessions = 1;
241
+ p.msgs += msgs;
242
+ p.input += input;
243
+ p.output += output;
244
+ p.cacheRead += cacheRead;
245
+ p.cost += cost;
246
+ }
247
+ return { mtimeMs: d.m, size: d.s, v: CACHE_VERSION, consumed: typeof d.c === "number" ? d.c : d.s, rollup };
248
+ }
249
+
250
+ /** Encode an in-memory item as v5: model rows only (see DiskItem). */
251
+ function encodeDiskItem(item: FileCacheItem): DiskItem {
252
+ const r: DiskItem["r"] = {};
253
+ for (const [pm, roll] of Object.entries(item.rollup.providers)) {
254
+ if (pm.includes("\u0000")) r[pm] = [roll.msgs, roll.input, roll.output, roll.cacheRead, roll.cost];
255
+ }
256
+ return { m: item.mtimeMs, s: item.size, c: item.consumed ?? item.size, r };
257
+ }
258
+
213
259
  // Disk cache is memoized; save writes memory + disk together.
214
260
  let diskMemo: Map<string, FileCacheItem> | null = null;
215
261
 
@@ -217,33 +263,57 @@ function loadDiskCache(): Map<string, FileCacheItem> {
217
263
  if (diskMemo) return diskMemo;
218
264
  diskMemo = new Map<string, FileCacheItem>();
219
265
  try {
220
- if (existsSync(cacheFilePath())) {
221
- const raw = JSON.parse(readFileSync(cacheFilePath(), "utf8")) as Record<string, FileCacheItem>;
222
- for (const [k, v] of Object.entries(raw)) {
223
- diskMemo.set(k, v);
224
- }
266
+ // One-time move into the arnative folder (was a flat file next to it).
267
+ if (!existsSync(cacheFilePath()) && existsSync(legacyCachePath())) {
268
+ mkdirSync(cacheDir(), { recursive: true });
269
+ renameSync(legacyCachePath(), cacheFilePath());
270
+ } else if (existsSync(legacyCachePath())) {
271
+ // Both exist — a downgrade recreated the flat file next to the folder copy. The
272
+ // folder copy belongs to the newer layout, so the flat one is dead.
273
+ rmSync(legacyCachePath());
225
274
  }
275
+ if (existsSync(legacyPricesPath())) rmSync(legacyPricesPath());
226
276
  } catch {
227
- // ignore
277
+ // a concurrent session may have moved it already: read whichever path exists
228
278
  }
279
+ readDiskFileInto(cacheFilePath(), diskMemo);
280
+ if (diskMemo.size === 0) readDiskFileInto(legacyCachePath(), diskMemo);
229
281
  return diskMemo;
230
282
  }
231
283
 
284
+ /** Read one cache file into `map`. v4 items keep their absolute-path keys verbatim;
285
+ * v5 keys are session-dir-relative and resolved back to absolute here. */
286
+ function readDiskFileInto(path: string, map: Map<string, FileCacheItem>): void {
287
+ try {
288
+ if (!existsSync(path)) return;
289
+ const sessionsDir = join(getAgentDir(), "sessions");
290
+ const raw = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
291
+ for (const [k, v] of Object.entries(raw)) {
292
+ const item = decodeDiskItem(v);
293
+ if (!item) continue;
294
+ map.set(v && typeof v === "object" && "rollup" in v ? k : join(sessionsDir, k), item);
295
+ }
296
+ } catch {
297
+ // ignore
298
+ }
299
+ }
300
+
232
301
  function saveDiskCache(map: Map<string, FileCacheItem>): void {
233
302
  try {
234
- // Temp file + rename: a concurrent pi session never reads a half-written cache.
235
303
  const path = cacheFilePath();
304
+ const sessionsDir = join(getAgentDir(), "sessions");
236
305
  // Re-read: another pi session may have cached its own files since this one loaded.
237
306
  // Skip keys whose session file is gone, so a prune done by this scan stays pruned.
238
- try {
239
- const disk = JSON.parse(readFileSync(path, "utf8")) as Record<string, FileCacheItem>;
240
- for (const [k, v] of Object.entries(disk)) if (!map.has(k) && existsSync(k)) map.set(k, v);
241
- } catch {
242
- // absent or corrupt: write this session's entries alone
243
- }
307
+ const disk = new Map<string, FileCacheItem>();
308
+ readDiskFileInto(path, disk);
309
+ if (disk.size === 0) readDiskFileInto(legacyCachePath(), disk);
310
+ for (const [k, v] of disk) if (!map.has(k) && existsSync(k)) map.set(k, v);
311
+ const out: Record<string, DiskItem> = {};
312
+ for (const [k, v] of map.entries()) out[relative(sessionsDir, k)] = encodeDiskItem(v);
313
+ // Temp file + rename: a concurrent pi session never reads a half-written cache.
244
314
  const tmp = `${path}.${process.pid}.tmp`;
245
- mkdirSync(dirname(path), { recursive: true });
246
- writeFileSync(tmp, JSON.stringify(Object.fromEntries(map)), "utf8");
315
+ mkdirSync(cacheDir(), { recursive: true });
316
+ writeFileSync(tmp, JSON.stringify(out), "utf8");
247
317
  renameSync(tmp, path);
248
318
  } catch {
249
319
  // ignore
@@ -564,7 +634,7 @@ const canonicalModel = (id: string): string => {
564
634
  *
565
635
  * The rule used to also match a bare tail (`target.endsWith("/" + name)`), so the first run
566
636
  * under a new provider inherited the history of every other provider whose id ended the same
567
- * way: `river/deepseek-ai/DeepSeek-V4.1-Flash` reported wally+yarz's deepseek totals
637
+ * way: `team/deepseek-ai/DeepSeek-V4.1-Flash` reported two other providers' deepseek totals
568
638
  * (29.5M in / 3.2M out / 360.5M cache) as its own (2026-10-17). Two ids that differ are two
569
639
  * routes — billed, rate-limited and counted apart — and only the vendor knows whether a short
570
640
  * id and a path id are the same model, so the tab shows the tokens of the id it names. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bismawy/pi-arnative",
3
- "version": "0.6.2",
3
+ "version": "0.8.0-rc.1",
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",
@@ -40,8 +40,8 @@
40
40
  "@earendil-works/pi-tui": "*"
41
41
  },
42
42
  "scripts": {
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/arnative.ts",
44
- "test": "node lib/box.ts && node lib/ansi.ts && node lib/color.ts && node lib/shortcuts.ts && node lib/preset-store.ts && node lib/spinner.ts && node themes/gen-themes.mjs --check && node extensions/tools.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/arnative.ts && node --test",
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/arnative.ts",
44
+ "test": "node lib/box.ts && node lib/ansi.ts && node lib/color.ts && node lib/shortcuts.ts && node lib/preset-store.ts && node lib/spinner.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 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/arnative.ts && node --test",
45
45
  "preview": "node scripts/preview.mjs",
46
46
  "themes": "node themes/gen-themes.mjs",
47
47
  "release:check": "node scripts/release-check.mjs pre-tag",