@bismawy/pi-arnative 0.16.0 → 0.18.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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
@@ -21,24 +21,11 @@
21
21
  */
22
22
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
23
23
  import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
24
- import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
25
- import { tmpdir } from "node:os";
26
- import { join } from "node:path";
27
- import { screenTitle } from "../lib/box.ts";
28
- import { assert, isMain } from "../lib/check.ts";
29
- import { announce } from "../lib/status-widget.ts";
30
- import { ListPicker, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
31
- import {
32
- BUDGET_DAY_KEY,
33
- BUDGET_ENFORCE_KEY,
34
- BUDGET_MONTH_KEY,
35
- flagSetting,
36
- loadChoice,
37
- loadNumber,
38
- resetPresetCache,
39
- saveChoice,
40
- } from "../lib/preset-store.ts";
41
- import { collectUsageSummary, resetUsageCache } from "../lib/usage-store.ts";
24
+ import { screenTitle } from "../box.ts";
25
+ import { announce } from "../status-widget.ts";
26
+ import { ListPicker, rowText, type ListPickerText, type ListRow } from "../list-picker.ts";
27
+ import { BUDGET_DAY_KEY, BUDGET_ENFORCE_KEY, BUDGET_MONTH_KEY, flagSetting, loadNumber, saveChoice } from "../preset-store.ts";
28
+ import { collectUsageSummary, markUsageDirty } from "../usage-store.ts";
42
29
  import { formatCost } from "./usage.ts";
43
30
 
44
31
  // ---------------------------------------------------------------- settings
@@ -114,7 +101,7 @@ export interface BudgetVerdict {
114
101
  }
115
102
 
116
103
  /** `warn` starts at this fraction of a cap. */
117
- export const WARN_PCT = 0.8;
104
+ const WARN_PCT = 0.8;
118
105
 
119
106
  /**
120
107
  * Pure decision — no I/O, the unit under test. `warn` at ≥80% of any set cap, `over` at ≥100%.
@@ -218,7 +205,7 @@ function changeBudgetRow(index: number): void {
218
205
  // ---------------------------------------------------------------- the Budget screen (TUI)
219
206
 
220
207
  /** Width of the spend-vs-cap bar, in cells. */
221
- export const BUDGET_BAR_WIDTH = 20;
208
+ const BUDGET_BAR_WIDTH = 20;
222
209
 
223
210
  /** Total estimated spend across the displayed windows: rolling 30d already includes today. */
224
211
  export function estimatedWindowTotal(spend: BudgetSpend | null): number {
@@ -391,6 +378,7 @@ let overNotified = false;
391
378
  export default function registerBudget(pi: ExtensionAPI): void {
392
379
  pi.on("session_start", () => {
393
380
  overNotified = false;
381
+ markUsageDirty();
394
382
  });
395
383
 
396
384
  pi.on("input", async (event, ctx) => {
@@ -399,7 +387,7 @@ export default function registerBudget(pi: ExtensionAPI): void {
399
387
  if (event.source === "extension") return { action: "continue" };
400
388
  const caps = { day: activeBudgetDay(), month: activeBudgetMonth() };
401
389
  if (caps.day === undefined && caps.month === undefined) return { action: "continue" };
402
- const spend = spendNow(true);
390
+ const spend = spendNow(false);
403
391
  // Unknown spend (no day buckets): never block.
404
392
  if (spend === null) return { action: "continue" };
405
393
  const enforce = activeBudgetEnforce();
@@ -421,224 +409,11 @@ export default function registerBudget(pi: ExtensionAPI): void {
421
409
  });
422
410
  }
423
411
 
424
- // Self-check: `node extensions/budget.ts`
425
- if (isMain(import.meta.url)) {
426
- // The real agent dir must not decide pass/fail, and the check must not touch it.
427
- const fixture = mkdtempSync(join(tmpdir(), "arnative-budget-"));
428
- const prevDir = process.env.PI_CODING_AGENT_DIR;
429
- process.env.PI_CODING_AGENT_DIR = fixture;
430
- const clearSlots = () => {
431
- delete (globalThis as Record<symbol, unknown>)[BUDGET_DAY_SLOT];
432
- delete (globalThis as Record<symbol, unknown>)[BUDGET_MONTH_SLOT];
433
- delete (globalThis as Record<symbol, unknown>)[BUDGET_ENFORCE_SLOT];
434
- };
435
- clearSlots();
436
- resetPresetCache();
437
-
438
- // The decision function: percentages of a $100 day cap.
439
- for (const [spend, level] of [[0, "ok"], [79, "ok"], [80, "warn"], [99, "warn"], [100, "over"], [120, "over"]] as const) {
440
- assert(budgetState({ today: spend, month: 0 }, { day: 100 }, true).level === level, `${spend}% of the cap is ${level}`);
441
- }
442
- assert(budgetState({ today: 999, month: 999 }, {}, true).level === "ok", "no caps set → ok");
443
- assert(budgetState({ today: 999, month: 999 }, {}, true).reason === undefined, "ok carries no reason");
444
- assert(budgetState({ today: 50, month: 0 }, { day: 0 }, true).level === "ok", "a zero cap is not a cap");
445
- assert(budgetState({ today: 85, month: 120 }, { day: 100, month: 100 }, true).level === "over", "the month cap is checked and over wins");
446
- assert(budgetState({ today: 85, month: 50 }, { day: 100, month: 100 }, true).level === "warn", "80% of either cap warns");
447
- // Rule 4: estimate-only spend never reaches over.
448
- assert(budgetState({ today: 0, month: 0, estimatedToday: 120 }, { day: 100 }, true).level === "warn", "estimate-only spend is capped at warn, never over");
449
- assert(budgetState({ today: 0, month: 0, estimatedToday: 120 }, { day: 100 }, false).level === "warn", "estimate-only spend is warn with enforce off too");
450
- assert(budgetState({ today: 120, month: 0, estimatedToday: 30 }, { day: 100 }, true).level === "over", "a billed crossing is over even with estimates in the mix");
451
- // Billed 90 of a 100 cap already warns on its own: the estimate did not push it there, so the
452
- // reason must not claim the over-cap is estimate-only.
453
- const mixed = budgetState({ today: 90, month: 0, estimatedToday: 40 }, { day: 100 }, true);
454
- assert(mixed.level === "warn" && !(mixed.reason ?? "").includes("never blocked"), "a mixed warn does not claim estimate-only: " + mixed.reason);
455
- // Pinned reason strings.
456
- assert(
457
- budgetState({ today: 6, month: 0 }, { day: 5 }, true).reason === "day cap $5.00 at 120% ($6.00 billed) — turn blocked",
458
- "over + enforce reason pinned: " + budgetState({ today: 6, month: 0 }, { day: 5 }, true).reason,
459
- );
460
- assert(
461
- budgetState({ today: 6, month: 0 }, { day: 5 }, false).reason === "day cap $5.00 at 120% ($6.00 billed) — enforcement off",
462
- "over + enforce off reason pinned",
463
- );
464
- assert(budgetState({ today: 4, month: 0 }, { day: 5 }, true).reason === "day cap $5.00 at 80% ($4.00 spent)", "warn reason pinned");
465
- assert(
466
- budgetState({ today: 0, month: 0, estimatedToday: 6 }, { day: 5 }, true).reason === "day cap $5.00 at 120% ($6.00 spent) — estimate only, never blocked",
467
- "estimate-capped reason pinned",
468
- );
469
-
470
- // The fixed cap choices and their labels.
471
- assert(nextCap(undefined) === 1 && nextCap(0) === 1 && nextCap(5) === 10 && nextCap(7.5) === 10 && nextCap(500) === 0, "nextCap cycles the choices, past the largest wraps to off");
472
- assert(capLabel(undefined) === "off" && capLabel(0) === "off" && capLabel(5) === "$5.00", "capLabel pinned");
473
-
474
- // Settings: absent reads as unset / off; a set value persists through the fixture config.
475
- assert(activeBudgetDay() === undefined && activeBudgetMonth() === undefined && activeBudgetEnforce() === false, "no caps, enforce off by default");
476
- setBudgetDay(5);
477
- setBudgetEnforce(true);
478
- assert(activeBudgetDay() === 5 && loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE) === 5, "a day cap is stored and reads back");
479
- assert(activeBudgetEnforce() === true && loadChoice(BUDGET_ENFORCE_KEY, ["on", "off"] as const) === "on", "enforce is stored as on/off");
480
- setBudgetDay(undefined);
481
- assert(activeBudgetDay() === undefined && loadNumber(BUDGET_DAY_KEY, BUDGET_AMOUNT_RANGE) === undefined, "clearing the cap stores the empty string (unset)");
482
-
483
- // The spend comes from the day buckets: one billed $6 entry today → today and 30d both $6.
484
- mkdirSync(join(fixture, "sessions", "p"), { recursive: true });
485
- const asst = (cost: number) =>
486
- JSON.stringify({
487
- message: { role: "assistant", provider: "google", model: "m", timestamp: Date.now(), usage: { input: 10, output: 5, cost: { total: cost, totalFromProvider: true } } },
488
- });
489
- writeFileSync(join(fixture, "sessions", "p", "s.jsonl"), asst(6) + "\n");
490
- resetUsageCache();
491
- const spend = spendNow();
492
- assert(spend !== null && spend.today === 6 && spend.month === 6 && spend.estimatedToday === 0, "spend reads the day buckets (today / 30d): " + JSON.stringify(spend));
493
-
494
- // The level right now, through the same memoized summary.
495
- assert(budgetLevelNow() === "ok", "no caps → ok");
496
- setBudgetDay(5);
497
- assert(budgetLevelNow() === "over", "$6 of a $5 day cap is over");
498
- setBudgetDay(7.5);
499
- assert(budgetLevelNow() === "warn", "$6 of $7.50 is exactly 80% → warn");
500
- setBudgetDay(undefined);
501
-
502
- // The gate, driven through a fake pi.
503
- const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
504
- registerBudget({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
505
- const notes: { msg: string; level: string }[] = [];
506
- const ctxOf = (): unknown => ({ ui: { notify: (msg: string, level: string) => void notes.push({ msg, level }) } });
507
- const ev = (source: string) => ({ type: "input", text: "hi", source });
508
- const input = async (source: string, ctx: unknown) => (await handlers.input!(ev(source), ctx)) as { action: string };
509
-
510
- setBudgetDay(5); // $6 spent → 120% of the day cap
511
- setBudgetEnforce(false);
512
- assert((await input("interactive", ctxOf())).action === "continue", "over + enforce off lets the turn through");
513
- assert(notes.length === 1 && notes[0]!.level === "warning", "over + enforce off notifies once, as a warning");
514
- assert(notes[0]!.msg === "day cap $5.00 at 120% ($6.00 billed) — enforcement off", "the notify carries the pinned reason: " + notes[0]!.msg);
515
- assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 1, "the second over-input does not notify again (once per session)");
516
- assert((await input("extension", ctxOf())).action === "continue" && notes.length === 1, "an extension-injected input is never swallowed and never notifies");
517
- await handlers.session_start!({}, undefined);
518
- setBudgetEnforce(true);
519
- assert((await input("interactive", ctxOf())).action === "handled", "over + enforce on blocks the next turn");
520
- assert(notes.length === 2 && notes[1]!.level === "error" && notes[1]!.msg === "day cap $5.00 at 120% ($6.00 billed) — turn blocked", "over + enforce on notifies an error with the pinned reason");
521
- assert(
522
- (await input("interactive", { get ui(): unknown { throw new Error("boom"); } })).action === "continue",
523
- "a throwing handler path fails open: continue, never block",
524
- );
525
- assert(notes.length === 2, "the failed notify was not recorded");
526
- setBudgetDay(7.5); // 80% → warn: no notify, the turn goes through
527
- assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "warn does not notify and does not block");
528
-
529
- // Unknown spend (no day buckets) never blocks, even with enforce on and a cap set.
530
- const empty = mkdtempSync(join(tmpdir(), "arnative-budget-empty-"));
531
- process.env.PI_CODING_AGENT_DIR = empty;
532
- clearSlots();
533
- resetPresetCache();
534
- resetUsageCache();
535
- setBudgetDay(5);
536
- setBudgetEnforce(true);
537
- assert(spendNow() === null, "no day buckets → the spend is unknown");
538
- assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "unknown spend never blocks");
539
-
540
- // No caps set → the gate is a no-op.
541
- process.env.PI_CODING_AGENT_DIR = fixture;
542
- clearSlots();
543
- resetPresetCache();
544
- resetUsageCache();
545
- setBudgetEnforce(true);
546
- setBudgetDay(undefined);
547
- assert((await input("interactive", ctxOf())).action === "continue" && notes.length === 2, "no caps → continue, no notify");
548
-
549
- // The Budget screen rows carry the live values and the pinned copy.
550
- setBudgetDay(5);
551
- const rows = budgetRows();
552
- assert(rows.map((r) => r.label).join(",") === "Day cap,30d cap,Enforce", "the Budget rows: " + rows.map((r) => r.label).join(","));
553
- assert(rows[0]!.note === "$5.00" && rows[1]!.note === "off", "the cap rows show the stored caps");
554
- assert(rows[2]!.note === ENFORCE_ON_NOTE && ENFORCE_ON_NOTE === "on — blocks the next turn over a cap", "the enforce row is pinned: " + rows[2]!.note);
555
- assert(BUDGET_PICKER_TEXT.title === "Budget - Arnative\u2819", "the Budget screen title is pinned: " + BUDGET_PICKER_TEXT.title);
556
- assert(
557
- BUDGET_PICKER_TEXT.description === "Warn-only caps on the UTC day and the rolling 30d — enforce on blocks the next turn.",
558
- "the Budget screen description is pinned",
559
- );
560
- assert(BUDGET_PICKER_TEXT.legend === "[↑↓] Move [Space] Change [R] Reset [Esc] Back", "the Budget legend is pinned");
561
- assert(rowText(rows[0]!) === "Day cap · $5.00", "the headless row text is pinned: " + rowText(rows[0]!));
562
-
563
- // The dashboard: the two spend-vs-cap windows, pure and pinned.
564
- const windows = budgetWindows(spendNow(), { day: activeBudgetDay(), month: activeBudgetMonth() }, activeBudgetEnforce());
565
- assert(windows.length === 2 && windows[0]!.label === "Today" && windows[1]!.label === "30d", "two status windows: " + windows.map((w) => w.label).join(","));
566
- assert(windows[0]!.pct === 120 && windows[0]!.level === "over" && windows[0]!.frac === 1, "today $6 of a $5 cap is 120% over, bar full: " + JSON.stringify(windows[0]));
567
- assert(windows[1]!.cap === undefined && windows[1]!.level === "ok" && windows[1]!.frac === 0 && windows[1]!.pct === undefined, "no month cap → no bar, no percent, ok");
568
- assert(budgetWindows(null, { day: 5 }, true).every((w) => w.unknown), "unknown spend (no day buckets) flags both windows");
569
- assert(budgetWindows({ today: 0, month: 0, estimatedToday: 6 }, { day: 5 }, true)[0]!.level === "warn", "estimate-only today spend warns, never over");
570
-
571
- // The modal render: status bars above the editable rows, through the shared screen frame.
572
- const modalTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
573
- const changed: number[] = [];
574
- let resets = 0;
575
- const modal = createBudgetPicker(
576
- modalTheme as never,
577
- budgetRows(),
578
- { change: (i) => void changed.push(i), reset: () => void resets++, done: () => {}, requestRender: () => {} },
579
- BUDGET_PICKER_TEXT as never,
580
- );
581
- const rendered = modal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
582
- assert(rendered.some((l) => l.includes("Budget - Arnative")), "the modal keeps the shared screen title");
583
- assert(rendered[0]!.includes("╭") && rendered[rendered.length - 1]!.includes("╰"), "the modal keeps the shared screen frame");
584
- assert(rendered.some((l) => l.includes("Today") && l.includes("█") && l.includes("120%") && l.includes("OVER")), "the Today row shows spend, bar, percent and level");
585
- assert(rendered.some((l) => l.includes("30d") && l.includes("no cap")), "the uncapped window says no cap");
586
- assert(rendered.some((l) => l.includes("Day cap") && l.includes("$5.00")), "the editable rows render with their notes");
587
- modal.handleInput("\x1b[B"); // down
588
- modal.handleInput(" "); // space
589
- assert(changed.length === 1 && changed[0] === 1, "down+space changes the second row (30d cap), not the first");
590
- modal.handleInput("R");
591
- modal.handleInput("r");
592
- assert(resets === 2, "R/r triggers budget reset");
593
- assert(modal.render(40).length > 0, "the modal renders on a narrow terminal");
594
-
595
- // Both windows capped: the bars share one column however long the spend-of-cap text is.
596
- setBudgetMonth(10);
597
- const aligned = modal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
598
- const todayBar = aligned.find((l) => l.includes("Today") && l.includes("█"))!;
599
- const monthBar = aligned.find((l) => l.includes("30d") && l.includes("█"))!;
600
- assert(todayBar.includes("█") && monthBar.includes("█"), "both capped windows draw a bar");
601
- assert(todayBar.indexOf("█") === monthBar.indexOf("█"), "both bars start on the same column: " + JSON.stringify([todayBar, monthBar]));
602
-
603
- // The level colors come from the active theme's semantic slots: OK accent, WARN warning,
604
- // OVER error. The theme records (slot, text) pairs: literal tags would count as width and
605
- // truncate the render.
606
- const calls: { slot: string; text: string }[] = [];
607
- const slotTheme = { fg: (c: string, t: string) => (calls.push({ slot: c, text: t }), t), bold: (t: string) => t };
608
- const slotModal = createBudgetPicker(slotTheme as never, budgetRows(), { change: () => {}, reset: () => {}, done: () => {}, requestRender: () => {} }, BUDGET_PICKER_TEXT as never);
609
- slotModal.render(80); // today OVER (120% of $5), 30d OK (60% of $10)
610
- assert(calls.find((c) => c.text === "Today")?.slot === "dim", "Today label uses dim");
611
- assert(calls.find((c) => c.text === "30d ")?.slot === "dim", "30d label uses dim");
612
- assert(calls.find((c) => c.text === "OVER")?.slot === "error", "OVER paints with the theme's error slot");
613
- assert(calls.find((c) => c.text === "OK")?.slot === "accent", "OK paints with the theme's accent slot");
614
- setBudgetMonth(7); // 30d $6 of $7 = 85% → WARN
615
- slotModal.render(80);
616
- assert(calls.filter((c) => c.text === "WARN").pop()?.slot === "warning", "WARN paints with the theme's warning slot");
617
- setBudgetEnforce(true);
618
- resetBudget();
619
- assert(activeBudgetDay() === undefined && activeBudgetMonth() === undefined && activeBudgetEnforce() === false, "resetBudget clears caps and enforce");
620
-
621
- // An estimated-cost entry adds the `Total · $X est.` line under the windows.
622
- writeFileSync(
623
- join(fixture, "sessions", "p", "e.jsonl"),
624
- JSON.stringify({ message: { role: "assistant", provider: "google", model: "m", timestamp: Date.now(), usage: { input: 1, output: 1, cost: { total: 2 } } } }) + "\n",
625
- );
626
- resetUsageCache();
627
- calls.length = 0;
628
- const estRendered = slotModal.render(80).map((l) => l.replace(/\x1b\[[0-9;]*m/g, ""));
629
- assert(estRendered.some((l) => l.includes("Total · $2.00 est.")), "the estimated total line renders: " + estRendered.filter((l) => l.includes("Total")).join(" | "));
630
- assert(calls.find((c) => c.text === "Total")?.slot === "dim", "Total label uses dim");
631
- assert(calls.find((c) => c.text === "$2.00 est.")?.slot === "text", "Total value beside label uses default text color");
632
- rmSync(join(fixture, "sessions", "p", "e.jsonl"));
633
- resetUsageCache();
634
-
635
- // Restore: the next module load starts from the real agent dir and the stored defaults.
636
- rmSync(fixture, { recursive: true, force: true });
637
- rmSync(empty, { recursive: true, force: true });
638
- if (prevDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
639
- else process.env.PI_CODING_AGENT_DIR = prevDir;
640
- clearSlots();
641
- resetPresetCache();
642
- resetUsageCache();
643
- console.log("budget.ts self-check OK");
644
- }
412
+ export const __test = {
413
+ BUDGET_DAY_SLOT,
414
+ BUDGET_MONTH_SLOT,
415
+ BUDGET_ENFORCE_SLOT,
416
+ BUDGET_PICKER_TEXT,
417
+ ENFORCE_ON_NOTE,
418
+ createBudgetPicker,
419
+ };