@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.
@@ -4,9 +4,9 @@
4
4
  * shared with the Model tab.
5
5
  */
6
6
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
7
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
8
  import { tmpdir } from "node:os";
9
- import { join } from "node:path";
9
+ import { join, relative } from "node:path";
10
10
  import { matchesKey, truncateToWidth, visibleWidth, type Component, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
11
11
  import { renderScreen, screenTitle } from "../lib/box.ts";
12
12
  import { assert, isMain } from "../lib/check.ts";
@@ -400,8 +400,9 @@ if (isMain(import.meta.url)) {
400
400
 
401
401
  // A session file that grows is parsed from the tail only (byte offset in the cache), not re-read.
402
402
  const file = join(fixture, "sessions", "proj", "a.jsonl");
403
- const cachedBefore = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, { consumed: number; size: number }>;
404
- assert(cachedBefore[file]!.consumed === cachedBefore[file]!.size, "cache records the full parsed offset");
403
+ const cachePath = join(fixture, "arnative", "usage-cache.json");
404
+ const cachedBefore = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, { c: number; s: number }>;
405
+ assert(cachedBefore[relative(join(fixture, "sessions"), file)]!.c === cachedBefore[relative(join(fixture, "sessions"), file)]!.s, "cache records the full parsed offset");
405
406
  writeFileSync(file, asst("gemini-3.8-flash", 1000) + String.fromCharCode(10), { flag: "a" });
406
407
  const grown = collectUsageSummary(true);
407
408
  assert(grown.totals.msgs === 4, "an appended record is picked up from the tail");
@@ -413,12 +414,12 @@ if (isMain(import.meta.url)) {
413
414
  // The per-file rollup is what makes a refresh cheap: folding a tail must reproduce the same
414
415
  // totals as parsing the whole file from scratch. Compare the incremental answer to a cold one.
415
416
  const incremental = JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash"));
416
- const cacheRaw = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, unknown>;
417
+ const cacheRaw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
417
418
  // Drop the cache (as a fresh machine, or a version bump, would) and rescan the whole file.
418
419
  // Writing `{}` is not enough on its own: the disk cache is memoized per process, so the
419
420
  // memo would answer and this assert would compare a value against itself, never failing.
420
421
  resetUsageCache();
421
- writeFileSync(join(fixture, "arnative-usage-cache.json"), "{}", "utf8");
422
+ writeFileSync(cachePath, "{}", "utf8");
422
423
  collectUsageSummary(true);
423
424
  assert(
424
425
  JSON.stringify(getModelAllTimeUsage("gemini-3.8-flash")) === incremental,
@@ -436,17 +437,71 @@ if (isMain(import.meta.url)) {
436
437
  // Disk cache pruning: no cache key may point at a session file that is gone.
437
438
  rmSync(join(fixture, "sessions", "proj", "a.jsonl"));
438
439
  collectUsageSummary(true);
439
- const raw = JSON.parse(readFileSync(join(fixture, "arnative-usage-cache.json"), "utf8")) as Record<string, unknown>;
440
+ const raw = JSON.parse(readFileSync(cachePath, "utf8")) as Record<string, unknown>;
440
441
  assert(Object.keys(raw).length === 0, "usage disk cache prunes deleted session files");
441
442
  rmSync(fixture, { recursive: true, force: true });
442
443
 
444
+ // A flat pre-folder cache is moved into the arnative folder on first read; the v4
445
+ // items keep working (decode feeds the summary, a grown file tail-folds forward) and
446
+ // the next save is the compact v5 shape: session-dir-relative keys, model-only rows.
447
+ const mig = mkdtempSync(join(tmpdir(), "arnative-usage-mig-"));
448
+ process.env.PI_CODING_AGENT_DIR = mig;
449
+ mkdirSync(join(mig, "sessions", "p"), { recursive: true });
450
+ const migFile = join(mig, "sessions", "p", "a.jsonl");
451
+ const migLine = asst("gemini-3.8-flash", 5) + String.fromCharCode(10);
452
+ writeFileSync(migFile, migLine, "utf8");
453
+ const migStat = statSync(migFile);
454
+ writeFileSync(
455
+ join(mig, "arnative-usage-cache.json"),
456
+ JSON.stringify({
457
+ [migFile]: {
458
+ mtimeMs: migStat.mtimeMs,
459
+ size: migStat.size,
460
+ v: 4,
461
+ consumed: migStat.size,
462
+ rollup: {
463
+ providers: {
464
+ "x\u0000m": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
465
+ "x": { sessions: 1, msgs: 3, input: 4, output: 5, cacheRead: 6, cost: 0 },
466
+ },
467
+ },
468
+ },
469
+ }),
470
+ "utf8",
471
+ );
472
+ resetUsageCache();
473
+ assert(collectUsageSummary(true).totals.msgs === 3, "a migrated v4 entry feeds the summary as-is (no reparse of an unchanged file)");
474
+ writeFileSync(migFile, asst("gemini-3.8-flash", 7) + String.fromCharCode(10), { flag: "a" });
475
+ assert(collectUsageSummary(true).totals.msgs === 4, "a grown file tail-folds on top of a migrated v4 entry");
476
+ assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the cache is saved into the arnative folder");
477
+ const migrated = JSON.parse(readFileSync(join(mig, "arnative", "usage-cache.json"), "utf8")) as Record<string, { r: Record<string, number[]> }>;
478
+ const migKey = join("p", "a.jsonl");
479
+ assert(Object.keys(migrated)[0] === migKey, "v5 keys are stored relative to the sessions dir");
480
+ assert(
481
+ Object.keys(migrated[migKey]!.r).every((k) => k.includes("\u0000")),
482
+ "v5 stores model rows only (provider rows are derived on load)",
483
+ );
484
+ // Layout "1" cleanup: the dead flat prices file and a flat cache a downgrade recreated
485
+ // beside the folder copy are removed on the next load; the folder copy survives.
486
+ writeFileSync(join(mig, "arnative-prices.json"), "{}", "utf8");
487
+ writeFileSync(join(mig, "arnative-usage-cache.json"), "{}", "utf8");
488
+ resetUsageCache();
489
+ collectUsageSummary(true);
490
+ assert(!existsSync(join(mig, "arnative-prices.json")), "the dead flat prices file is removed");
491
+ assert(!existsSync(join(mig, "arnative-usage-cache.json")), "a flat cache recreated beside the folder copy is removed");
492
+ assert(existsSync(join(mig, "arnative", "usage-cache.json")), "the folder copy survives the cleanup");
493
+ rmSync(mig, { recursive: true, force: true });
494
+ // Back to the main fixture: the UI rows below still scan it.
495
+ process.env.PI_CODING_AGENT_DIR = fixture;
496
+ resetUsageCache();
497
+
443
498
  // UI checks need rows of their own: the scratch above ends with an empty, deleted file.
444
499
  // These use a provider that reports NO cost (cost.total = 0), which is the case the estimate
445
500
  // exists for; `asst` above reports 0.02 per message and would be priced by the provider.
446
501
  mkdirSync(join(fixture, "sessions", "ui"), { recursive: true });
447
502
  const freeAsstOf = (provider: string, model: string, input: number) =>
448
503
  JSON.stringify({ message: { role: "assistant", provider, model, usage: { input, output: 5, cacheRead: 1, cost: { total: 0 } } } });
449
- const freeAsst = (model: string, input: number) => freeAsstOf("wally", model, input);
504
+ const freeAsst = (model: string, input: number) => freeAsstOf("alpha", model, input);
450
505
  writeFileSync(
451
506
  join(fixture, "sessions", "ui", "rows.jsonl"),
452
507
  [
@@ -454,50 +509,50 @@ if (isMain(import.meta.url)) {
454
509
  freeAsst("other-model", 7),
455
510
  // The shipped shape of the collision: a bare id and, on another provider, a path id
456
511
  // that merely ENDS with it. Suffix matching folded the second into the first, so a first
457
- // run under `river/…` showed wally+yarz's 29.5M/3.2M/360.5M as if it were its own.
512
+ // run under a shared alias showed two providers' usage as if it were one provider's own.
458
513
  freeAsst("deepseek-v4.1-flash", 300),
459
- freeAsstOf("9router", "river/deepseek-ai/DeepSeek-V4.1-Flash", 200),
514
+ freeAsstOf("shared", "team/deepseek-ai/DeepSeek-V4.1-Flash", 200),
460
515
  ].join(String.fromCharCode(10)),
461
516
  );
462
517
  collectUsageSummary(true);
463
518
 
464
519
  // Per-id totals: a model id reports its own tokens only, whatever it is a suffix of.
465
520
  assert(getModelAllTimeUsage("deepseek-v4.1-flash").input === 300, "a bare id does not absorb a longer id that ends with it");
466
- assert(getModelAllTimeUsage("river/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
467
- assert(getModelAllTimeUsage("RIVER/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
521
+ assert(getModelAllTimeUsage("team/deepseek-ai/DeepSeek-V4.1-Flash").input === 200, "a path id counts its own provider's tokens only");
522
+ assert(getModelAllTimeUsage("TEAM/DeepSeek-AI/deepseek-V4.1-Flash").input === 200, "case still does not split one model's history");
468
523
  assert(getModelAllTimeUsage("deepseek-v4.1-flash:free").input === 300, "a route tag folds into the model it tags");
469
524
 
470
525
  // Cost estimation: unpriced pairs use rates declared automatically in models.json.
471
526
  assert(loadPriceTable() !== null && Object.keys(loadPriceTable()).length === 0, "no models.json rates means an empty table");
472
- assert(!hasPrice("wally", "gemini-3.8-flash"), "a pair absent from models.json has no price");
473
- assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "wally") === null, "an unknown pair estimates nothing");
527
+ assert(!hasPrice("alpha", "gemini-3.8-flash"), "a pair absent from models.json has no price");
528
+ assert(estimateCost(1000, 100, 0, "gemini-3.8-flash", "alpha") === null, "an unknown pair estimates nothing");
474
529
  assert(collectUsageSummary(true).totals.estimatedCost === 0, "nothing is estimated without rates");
475
- assert(estimateCost(1000, 100, 0, "other-model", "wally") === null, "a second unpriced pair estimates nothing either");
530
+ assert(estimateCost(1000, 100, 0, "other-model", "alpha") === null, "a second unpriced pair estimates nothing either");
476
531
 
477
532
  writeFileSync(
478
533
  join(fixture, "models.json"),
479
534
  JSON.stringify({
480
535
  providers: {
481
- wally: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
482
- yarz: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
536
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 1, output: 2, cacheRead: 0.1 } }] },
537
+ beta: { models: [{ id: "gemini-3.8-flash", cost: { input: 10, output: 20 } }] },
483
538
  },
484
539
  }),
485
540
  );
486
- assert(hasPrice("wally", "gemini-3.8-flash"), "a priced provider+model is found in the table");
541
+ assert(hasPrice("alpha", "gemini-3.8-flash"), "a priced provider+model is found in the table");
487
542
  assert(!hasPrice("enclave", "gemini-3.8-flash"), "another provider with no entry is not priced");
488
- assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "wally") === 1, "1M input tokens at wally's $1/M costs $1");
543
+ assert(estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "alpha") === 1, "1M input tokens at alpha's $1/M costs $1");
489
544
  assert(
490
- estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "yarz") === 10,
491
- "the SAME model at yarz costs 10x (rates are per provider, not per model)",
545
+ estimateCost(1_000_000, 0, 0, "gemini-3.8-flash", "beta") === 10,
546
+ "the SAME model at beta costs 10x (rates are per provider, not per model)",
492
547
  );
493
- assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "wally") === 2, "1M output tokens at $2/M costs $2");
494
- assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "wally")! - 0.1) < 1e-9, "cache reads use their own rate");
495
- assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "wally") === 1, "a vendor/my-model id matches the model rate");
548
+ assert(estimateCost(0, 1_000_000, 0, "gemini-3.8-flash", "alpha") === 2, "1M output tokens at $2/M costs $2");
549
+ assert(Math.abs(estimateCost(0, 0, 1_000_000, "gemini-3.8-flash", "alpha")! - 0.1) < 1e-9, "cache reads use their own rate");
550
+ assert(estimateCost(1_000_000, 0, 0, "vendor/gemini-3.8-flash", "alpha") === 1, "a vendor/my-model id matches the model rate");
496
551
  const withPrices = collectUsageSummary(true);
497
552
  assert(withPrices.totals.estimatedCost > 0, "models.json rates produce an estimate");
498
553
  assert(withPrices.totals.reportedCost === 0, "the reported total stays at the provider's own number");
499
554
  assert(withPrices.totals.cost === withPrices.totals.reportedCost, "the headline cost never absorbs the estimate");
500
- assert(estimateCost(1_000_000, 0, 0, "other-model", "wally") === null, "a pair with no rate stays unpriced even when others are priced");
555
+ assert(estimateCost(1_000_000, 0, 0, "other-model", "alpha") === null, "a pair with no rate stays unpriced even when others are priced");
501
556
 
502
557
  const fakeTheme = {
503
558
  fg: (_c: string, t: string) => `\x1b[38;2;100;100;100m${t}\x1b[39m`,
@@ -606,7 +661,7 @@ if (isMain(import.meta.url)) {
606
661
  // The unpriced notice is gone: the `-` in Cost already says it.
607
662
  assert(!body.includes("unpriced"), "the unpriced notice line is removed");
608
663
  // Provider rows are capitalized so they read as names, not raw ids.
609
- assert(plain(lines[firstRow]!).includes("Wally") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
664
+ assert(plain(lines[firstRow]!).includes("Alpha") || plain(lines[firstRow]!).includes("Google"), "provider rows are capitalized");
610
665
 
611
666
  // Thinking level -> theme slot is unit-tested in lib/ansi.ts (one definition); here we
612
667
  // only prove the box border actually takes its color from that slot at render time.
@@ -721,20 +776,20 @@ if (isMain(import.meta.url)) {
721
776
  join(fixture, "models.json"),
722
777
  JSON.stringify({
723
778
  providers: {
724
- wally: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
725
- yarz: { models: [{ id: "gemini-3.8-flash" }] },
779
+ alpha: { models: [{ id: "gemini-3.8-flash", cost: { input: 0.28, output: 0.42, cacheRead: 0.028 } }] },
780
+ beta: { models: [{ id: "gemini-3.8-flash" }] },
726
781
  },
727
782
  }),
728
783
  );
729
784
  const fromModels = collectUsageSummary(true);
730
- const wally = fromModels.providers.find((p) => p.name === "wally")!;
785
+ const alpha = fromModels.providers.find((p) => p.name === "alpha")!;
731
786
  const expected = (100 / 1e6) * 0.28 + (5 / 1e6) * 0.42 + (1 / 1e6) * 0.028;
732
- assert(Math.abs(wally.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${wally.estimatedCost}`);
787
+ assert(Math.abs(alpha.estimatedCost - expected) < 1e-12, `models.json cost prices the provider, got ${alpha.estimatedCost}`);
733
788
  assert(
734
- Math.abs(wally.models.reduce((n, m) => n + m.estimatedCost, 0) - wally.estimatedCost) < 1e-9,
789
+ Math.abs(alpha.models.reduce((n, m) => n + m.estimatedCost, 0) - alpha.estimatedCost) < 1e-9,
735
790
  "a provider's estimate is the sum of its models' estimates",
736
791
  );
737
- assert(wally.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
792
+ assert(alpha.models.find((m) => m.name === "other-model")!.estimatedCost === 0, "a model without a declared cost stays unpriced");
738
793
  writeFileSync(join(fixture, "models.json"), "{}", "utf8");
739
794
  collectUsageSummary(true);
740
795
 
@@ -745,7 +800,7 @@ if (isMain(import.meta.url)) {
745
800
  (estModal as unknown as { summary: unknown }).summary = {
746
801
  providers: [
747
802
  {
748
- name: "wally", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
803
+ name: "alpha", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000,
749
804
  totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546,
750
805
  models: [{ name: "deepseek-v4.1-flash", sessions: 1, msgs: 2, input: 1_000_000, output: 500_000, cacheRead: 2_000_000, totalTokens: 1_500_000, cost: 0, estimatedCost: 0.546 }],
751
806
  },
@@ -757,14 +812,14 @@ if (isMain(import.meta.url)) {
757
812
  ],
758
813
  totals: { sessions: 2, msgs: 3, input: 3_200_000, output: 1_126_000, cacheRead: 2_000_000, totalTokens: 4_326_000, cost: 0.65, reportedCost: 0.65, estimatedCost: 0.546 },
759
814
  };
760
- (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["wally"]);
815
+ (estModal as unknown as { expandedProviders: Set<string> }).expandedProviders = new Set(["alpha"]);
761
816
  const estLines = estModal.render(90);
762
817
  const estBody = estLines.map(plain).join("\n");
763
818
  assert(estBody.includes("~$0.55"), "a row with a rate but no reported cost shows the estimate with `~`");
764
819
  assert(estBody.includes("$0.65") && !estBody.includes("~$0.65"), "a reported cost is shown as-is, never with `~`");
765
820
  assert(estBody.includes("estimated (models.json)"), "the estimate line names models.json");
766
821
  // Only the two table rows — the detail line also carries the estimate.
767
- const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Wally|deepseek)/.test(l));
822
+ const estRows = estLines.map(plain).filter((l) => /^\u2502 [\u25be\u25b8 ] (Alpha|deepseek)/.test(l));
768
823
  assert(estRows.length === 2 && estRows.every((l) => l.includes("~$0.55")), `the estimate shows on the provider row and its model row, got ${JSON.stringify(estRows)}`);
769
824
 
770
825
  // Cost must survive every width: a clipped `$5` is worse than a dropped column.
package/lib/box.ts CHANGED
@@ -32,7 +32,8 @@ const applyBg = (line: string, width: number, bgFn: (text: string) => string): s
32
32
  export interface ScreenText {
33
33
  title: string;
34
34
  description: string;
35
- /** Keybind legend, drawn as the last row above the bottom edge. */
35
+ /** Keybind legend, drawn as the last row above the bottom edge. Plain text is dimmed
36
+ * by the frame; a legend that already carries ANSI styling renders verbatim. */
36
37
  legend: string;
37
38
  }
38
39
 
@@ -66,7 +67,7 @@ export function renderScreen(
66
67
  row(""),
67
68
  ...body.map(row),
68
69
  row(""),
69
- row(fg("dim", text.legend)),
70
+ row(text.legend.includes("\u001b[") ? text.legend : fg("dim", text.legend)),
70
71
  boxEdge("╰", "╯", width, border),
71
72
  ].map((l) => truncateToWidth(l, width, ""));
72
73
  }
@@ -131,8 +132,12 @@ if (isMain(import.meta.url)) {
131
132
  assert(taggedScreen[2]!.includes("<muted>d"), "the description is muted");
132
133
  assert(taggedScreen[taggedScreen.length - 2]!.includes("<dim>l"), "the legend is dim");
133
134
  assert(renderScreen(null, 40, { title: "t", description: "d", legend: "l" }, ["x"]).every((l) => visibleWidth(l) === 40), "a null theme still frames the screen");
135
+ // A legend that styles itself (the models picker accents its picked count) renders
136
+ // verbatim: no dim wrap that would mute the accent and leak a reset into the tail.
137
+ const styled = renderScreen(th, 60, { title: "t", description: "d", legend: "<accent>34/44 picked</accent><dim> · keys</dim>" }, []);
138
+ assert(styled[styled.length - 2]!.includes("<accent>34/44 picked</accent>"), "a pre-styled legend renders verbatim");
134
139
  // The header copy is longer than a narrow terminal: the wall must win over the text.
135
- const longCopy = "Selection previews live — same list as /settings → Theme.";
140
+ const longCopy = "Selection previews live — arnative themes only (all themes: /settings → Theme).";
136
141
  for (const w of [40, 50, 56, 60]) {
137
142
  const narrow = renderScreen(th, w, { title: screenTitle("Themes"), description: longCopy, legend: "[Esc] Revert" }, []);
138
143
  assert(narrow.every((l) => visibleWidth(l) === w), `a long description keeps every line at width ${w}`);