@bismawy/pi-arnative 0.8.1 → 0.9.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/README.md CHANGED
@@ -10,45 +10,30 @@ Refined aesthetics. Cohesive tools. Built for Pi.
10
10
 
11
11
  ## Overview
12
12
 
13
- pi-arnative replaces pi’s default terminal chrome with a unified, cohesive visual aesthetic.
13
+ pi-arnative replaces pi’s default terminal chrome with a unified visual interface.
14
14
 
15
- - Warm Themes: Cohesive, contrast-checked OKLCH color palettes generated without drift.
15
+ - Warm Themes: Contrast-checked OKLCH color palettes generated without drift (`arnative` plus 10 variants).
16
16
  - Tabbed Header: Compact box menu showing Directory, Model, Context, Skills, Extensions, and Shortcuts.
17
- - Rounded Tool Boxes: Status, spinner, and duration for every tool call with expandable outputs.
18
- - Enhanced Footer: 3-row status grid tracking branch, active duration (30s idle freeze), and token speed.
19
- - Transcript Clock: Timestamps for conversation messages with clean bubble backgrounds.
20
- - Usage Dashboard: Real-time token counts and cost tracking across all local sessions via `/usage`.
21
- - Custom Providers: any OpenAI-, Anthropic-, Gemini- or Ollama-compatible endpoint from three inputs — URL, key, name; models are probed and picked, saved to pi's own `models.json`/`auth.json`, together with the context window and output cap the probe answered and the compat flags the endpoint needs. Enter on a stored provider edits: reselect models, re-probe the endpoint, cycle per-model thinking levels (off → auto → minimal → low → medium → high → xhigh → max, auto-detected from ids), set all of them at once (`[A]` auto, `[R]` off), probe which effort levels the channel really accepts (`p`), or delete.
22
- - Model Heal: keeps `models.json` correct with no command (adopted from pi-auto-compat) — missing compat flags, the context window and output cap each channel's `/models` publishes, and the effort levels a relay really accepts. Explicit values always win.
17
+ - Rounded Tool Boxes: Status, spinner, runtime duration, and clickable `[show]` / `[hide]` output toggles.
18
+ - Task List: `todo` tool, `/todos` view, and a boxed widget above the editor that auto-hides 30s after all tasks finish.
19
+ - Enhanced Footer: 3-row status grid (`Arnative (Full)`) or single collapsible row (`Arnative (Minimal)`) tracking branch, diff, active duration, and token speed.
20
+ - Working Spinners: 18 animated presets with live picker preview and optional `[g]` gradient sweep.
21
+ - Transcript Clock: Per-message timestamps with clean bubble backgrounds.
22
+ - Usage Dashboard: Real-time token counts and cost tracking across local sessions via `/usage`.
23
+ - Custom Providers: Interactive `/providers` wizard to probe endpoints, pick models, set thinking levels, and save OpenAI-, Anthropic-, Gemini-, or Ollama-compatible channels to `models.json` and `auth.json`.
24
+ - Model Heal: Background sync (`/model-heal`) that fills missing compat flags, `/models` token limits, and accepted reasoning effort levels in `models.json`.
25
+ - Auto-compact: Automatic context compaction after a turn settles using smart window tiers or a fixed token budget.
23
26
 
24
27
  <details>
25
28
  <summary><b>Configuration & Presets</b></summary>
26
29
 
27
- ### Working Spinner Presets
28
- Configurable via `/arnative` → **Animations** (saved to `~/.pi/agent/arnative/config.json`).
29
- Features 18 presets with live animated preview in the picker (`Arnative` as default, `Pi (system)`, and alphabetical variants). Press `[g]` in the picker to toggle Google brand gradient sweep on accent presets.
30
+ Saved to `~/.pi/agent/arnative/config.json` via `/arnative`:
30
31
 
31
- ### Footer Presets
32
- Configurable via `/arnative` → **Footers**:
33
- - `Arnative (Full)` (default 3-row grid)
34
- - `Arnative (Minimal)` (single collapsible head row; click or `ctrl+alt+m` to toggle)
35
- - `Pi (system)` (built-in footer)
36
-
37
- ### Auto-compact
38
- Configurable via `/arnative` → **Auto-compact** (saved to `~/.pi/agent/arnative/config.json`).
39
- When the context crosses the chosen threshold after a run settles, pi's own compaction fires — the same machinery and summary as `/compact`, keeping long sessions light without the manual step. Two shapes of control:
40
- - **Smart** (tiered by context window): ≥768k→20% · ≥384k→40% · ≥192k→80% · below 192k→pi core. Every tier lands the trigger near the same ~200k-token transcript ceiling — a 1M window trips at a fifth of its window, a 256k at 80%, and a 128k model defers entirely to pi's own near-full compaction (the behavior that is already safe there).
41
- - **A manual token budget** (`100k`–`400k`): one absolute number, whatever the window.
42
-
43
- Off by default. Guards: no re-trigger while a compaction runs, a growth-margin wait (5% of the threshold) after an attempt that freed too little or failed, and a full reset on session start. Pi's own `compaction.reserveTokens` threshold, including per-model overrides, is unaffected; whichever fires first wins.
44
-
45
- ### Model heal
46
- Configurable via `/arnative` → **Model heal** (saved to `~/.pi/agent/arnative/config.json`). Runs on its own on session start, model select, a change to `models.json`, and an error that names a rejected parameter:
47
- - **Full** (default): compat flags offline, plus `contextWindow`/`maxTokens` from each channel's `GET /models` (6 h TTL) and the accepted `reasoning_effort` levels written as a `thinkingLevelMap` (24 h TTL).
48
- - **Flags**: the offline compat pass only, no network.
49
- - **Off**: nothing.
50
-
51
- `/model-heal` forces every pass now, ignoring the TTLs (`/auto-compat` is an alias once pi-auto-compat is uninstalled). A value you set by hand — even `false` — is never overwritten, a corrupt `models.json` is reported and never rewritten, and the first write keeps a backup. While pi-auto-compat is still installed, pi-arnative defers to it and says so once.
32
+ - **Headers & Footers:** `Arnative (Full)` (default), `Arnative (Minimal)` (footer only; click head text or press `ctrl+alt+m` to toggle), or `Pi (system)`.
33
+ - **Animations:** 18 presets (`Arnative` default, `Pi (system)`, and alphabetical variants). Press `[g]` in the picker to toggle the Google gradient sweep.
34
+ - **Auto-compact:** Off by default. **Smart** tiers trigger near ~200k tokens (`≥768k→20%`, `≥384k→40%`, `≥192k→80%`, `<192k→pi core`), or pick a fixed budget (`100k` to `400k`).
35
+ - **Model heal:** **Full** (default: offline compat flags, `GET /models` limits with 6h TTL, reasoning effort probe with 24h TTL), **Flags** (offline only), or **Off**. Hand-edited fields are never overwritten.
36
+ - **Task list (`todo`):** Stored per session in `~/.pi/agent/arnative/todos/<session-id>.json` (uninstall `@juicesharp/rpiv-todo` first to avoid tool name conflict). Click `[click to expand]` / `[click to collapse]` or press `ctrl+alt+o` (`alt+o`) to toggle; click `↑`/`↓` counters or press `ctrl+alt+j`/`k` (`alt+j`/`k`) to scroll. Auto-hides 30s after completion (set `PI_ARNATIVE_TODO_HIDE_MS` to override, `0` for immediate hide; expanding pauses the timer).
52
37
 
53
38
  </details>
54
39
 
@@ -58,11 +43,9 @@ Configurable via `/arnative` → **Model heal** (saved to `~/.pi/agent/arnative/
58
43
  pi install npm:@bismawy/pi-arnative
59
44
  ```
60
45
 
61
- Apply a theme via `/settings` → **Theme** → `arnative` (or variant). Requires a [Nerd Font](https://www.nerdfonts.com/font-downloads).
62
- On a fresh install the `arnative` theme is applied automatically when pi has no theme of its
63
- own; a theme you already chose is never overridden.
46
+ Requires a [Nerd Font](https://www.nerdfonts.com/font-downloads). On a fresh install, `arnative` is applied automatically if no theme is set; switch anytime via `/arnative themes` or `/settings` → **Theme**.
64
47
 
65
- To test locally:
48
+ Local development:
66
49
  ```bash
67
50
  npm run dev
68
51
  ```
@@ -75,27 +58,30 @@ npm run dev
75
58
  | `ctrl+alt+r` · `alt+r` | Quick reload (`/reload`) |
76
59
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
77
60
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
78
- | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
61
+ | `ctrl+alt+o` · `alt+o` | Expand or collapse task list |
62
+ | `ctrl+alt+j` · `alt+j` | Scroll task list down |
63
+ | `ctrl+alt+k` · `alt+k` | Scroll task list up |
64
+ | Click `[show]` / `[hide]` · `ctrl+o` | Toggle tool output box |
65
+ | `←` / `Esc` | Step back to parent menu / close active screen |
79
66
  | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Model heal, Providers, Usage) |
80
- | `/providers` | Provider screen (or `/arnative` → **Providers**) |
81
- | `/model-heal` | Heal `models.json` now (or `/arnative` → **Model heal**) |
82
- | Click tool / `ctrl+o` | Toggle tool output box |
83
- | `←` | Back — step back from submenus/dashboard to menu |
67
+ | `/usage` | Token & cost dashboard |
68
+ | `/todos` | Full task list recap |
69
+ | `/providers` | Custom provider manager |
70
+ | `/model-heal` | Run `models.json` heal passes now |
84
71
 
85
72
  <details>
86
73
  <summary><b>Keybindings & Platform Notes</b></summary>
87
74
 
88
- To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
75
+ Bind `app.session.new` in `~/.pi/agent/keybindings.json`:
89
76
  ```json
90
77
  {
91
78
  "app.session.new": ["ctrl+alt+n", "alt+n"]
92
79
  }
93
80
  ```
94
81
 
95
- - **Windows / WSL:** Windows Terminal aliases `Ctrl+Alt` to AltGr; use `alt+…` (or disable `altGrAliasing` in WT profile).
96
- - **macOS:** Uses `ctrl+option+…`.
97
- - **tmux / Herdr:** If Esc has delay, set `PI_TUI_ESC_TIMEOUT=100` in your environment.
98
- - **Navigation:** `←` navigates back to parent menus; `Esc` cancels or closes the active screen.
82
+ - **Windows / WSL:** Windows Terminal maps `Ctrl+Alt` to AltGr; use `alt+…` or disable `altGrAliasing`.
83
+ - **macOS:** Use `ctrl+option+…`.
84
+ - **tmux / Herdr:** Set `PI_TUI_ESC_TIMEOUT=100` if `Esc` has a delay.
99
85
 
100
86
  </details>
101
87
 
@@ -106,52 +92,35 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
106
92
 
107
93
  | File | Role |
108
94
  | --- | --- |
109
- | `extensions/tools.ts` | Rounded tool boxes, spinners, and duration |
110
- | `extensions/section-headers.ts` | Tabbed header and resource box (preset: `/arnative headers`) |
111
- | `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
112
- | `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
113
- | `extensions/autocompact.ts` | Auto-compact: Smart tiers by window or a fixed token budget (`/arnative` → Auto-compact) |
114
- | `extensions/model-heal.ts` | Model heal triggers: session start, model select, `models.json` watcher, rejected-parameter errors, `/model-heal` |
115
- | `lib/model-heal.ts` | Model heal passes: compat flags, `/models` limits sync, effort probe |
116
- | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
117
- | `extensions/arnative.ts` | Settings menu with live preview and navigation |
118
- | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
119
- | `lib/list-picker.ts` | The live-preview/multi-select picker every arnative screen shares |
95
+ | `extensions/arnative.ts` | `/arnative` settings menu and live preview pickers |
96
+ | `extensions/section-headers.ts` | Tabbed header and resource box |
97
+ | `extensions/footer.ts` | 3-row status grid, Minimal footer, and boxed editor |
98
+ | `extensions/tools.ts` | Rounded tool boxes, spinners, duration, and `[show]` / `[hide]` toggles |
99
+ | `extensions/todos.ts` | `todo` tool, boxed widget above editor, and `/todos` screen |
100
+ | `extensions/animations.ts` | Spinner preset picker and live preview |
101
+ | `extensions/autocompact.ts` | Smart and fixed-budget context compaction |
102
+ | `extensions/model-heal.ts` | Automatic `models.json` heal triggers and `/model-heal` |
120
103
  | `extensions/timestamps.ts` | Message timestamps and bubble backgrounds |
121
- | `extensions/ui-render-tweaks.ts` | Contrast tweaks, selection style, and UI polish |
104
+ | `extensions/ui-render-tweaks.ts` | Contrast tweaks, selection styling, and UI polish |
122
105
  | `extensions/usage.ts` | Token and cost dashboard (`/usage`) |
106
+ | `lib/todos.ts` | Task state, window layout, box rows, and session store |
107
+ | `lib/spinner.ts` | Spinner preset catalog, frames, and gradient painters |
108
+ | `lib/provider.ts` | Custom provider probe, model picker, and config writer |
109
+ | `lib/model-heal.ts` | Compat flags, `/models` limit sync, and reasoning effort probe |
110
+ | `lib/list-picker.ts` | Shared live-preview and multi-select picker component |
123
111
 
124
112
  </details>
125
113
 
126
114
  <details>
127
- <summary><b>Theme Variants</b></summary>
128
-
129
- Theme definitions are generated via `themes/gen-themes.mjs` using OKLCH color math (`lib/color.ts`).
130
-
131
- **Variants:** `sun` · `zinc` · `violet` · `emerald` · `matrix` · `cyberpunk` · `synthwave` · `gruvbox` · `nord` · `dracula`
132
-
133
- </details>
134
-
135
- <details>
136
- <summary><b>Development & Verification</b></summary>
137
-
138
- ```bash
139
- npm test # Run unit tests and self-checks
140
- npm run themes # Rebuild all theme variants
141
- npm run preview # Live preview the working tree in your own Pi (stamps a pushable commit)
142
- ```
143
-
144
- Pre-publish verification and tag validation are enforced via `scripts/release-check.mjs`.
115
+ <summary><b>Theme Variants & Development</b></summary>
145
116
 
146
- **Local-first push gate:** the pre-push hook (`.githooks/pre-push`) rejects any branch push whose commit
147
- carries no live-preview stamp, so a fix cannot reach GitHub unseen. `npm run preview`
148
- launches Pi with this working tree and writes `.git/arnative-preview` for the exact commit
149
- that was shown; editing `extensions/`, `lib/`, `themes/`, or `package.json` afterwards
150
- invalidates it and the hook asks for a fresh preview. The preview must run on a clean tree
151
- — commit or stash first. Git does not auto-install hooks; activate per clone:
117
+ **Themes (`themes/gen-themes.mjs` + `lib/color.ts`):** `arnative` · `sun` · `zinc` · `violet` · `emerald` · `matrix` · `cyberpunk` · `synthwave` · `gruvbox` · `nord` · `dracula`
152
118
 
153
119
  ```bash
154
- git config core.hooksPath .githooks
120
+ npm test # Run self-checks and unit tests
121
+ npm run themes # Regenerate theme JSON files
122
+ npm run preview # Live preview in Pi and stamp .git/arnative-preview
123
+ git config core.hooksPath .githooks # Enable pre-push preview verification hook
155
124
  ```
156
125
 
157
126
  </details>
@@ -11,7 +11,7 @@ import { stripAnsi } from "../lib/ansi.ts";
11
11
  import { screenTitle } from "../lib/box.ts";
12
12
  import { assert, isMain } from "../lib/check.ts";
13
13
  import { markedLabels, ROW_DIVIDER } from "../lib/format.ts";
14
- import { SPINNER_PRESETS, type SpinnerPreset } from "../lib/spinner.ts";
14
+ import { SPINNER_GRADIENT_KEY, SPINNER_PRESET_KEY, SPINNER_PRESETS, type SpinnerPreset } from "../lib/spinner.ts";
15
15
  import {
16
16
  activeSpinnerGradient,
17
17
  animationsPickerText,
@@ -22,11 +22,18 @@ import {
22
22
  setSpinnerGradient,
23
23
  setSpinnerPreset,
24
24
  } from "./animations.ts";
25
+ import { FOOTER_PRESET_KEY, HEADER_PRESET_KEY, ensureChoices } from "../lib/preset-store.ts";
25
26
  import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
26
27
  import { HEADER_PRESETS, activeHeaderPreset, setHeaderPreset, type HeaderPreset } from "./section-headers.ts";
27
- import { AUTO_COMPACT_CHOICES, activeAutoCompact, setAutoCompact, type AutoCompactChoice } from "./autocompact.ts";
28
+ import {
29
+ AUTO_COMPACT_CHOICES,
30
+ AUTO_COMPACT_KEY,
31
+ activeAutoCompact,
32
+ setAutoCompact,
33
+ type AutoCompactChoice,
34
+ } from "./autocompact.ts";
28
35
  import { healNow } from "./model-heal.ts";
29
- import { MODEL_HEAL_CHOICES, activeModelHeal, setModelHeal, type ModelHealChoice } from "../lib/model-heal.ts";
36
+ import { MODEL_HEAL_CHOICES, MODEL_HEAL_KEY, activeModelHeal, setModelHeal, type ModelHealChoice } from "../lib/model-heal.ts";
30
37
  import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
31
38
  import { openProviders } from "../lib/provider.ts";
32
39
  import { openUsage } from "./usage.ts";
@@ -518,7 +525,7 @@ export function shouldApplyDefaultTheme(
518
525
  * set without starting a session. */
519
526
  export function registerCommands(pi: Pick<ExtensionAPI, "registerCommand">): void {
520
527
  pi.registerCommand("arnative", {
521
- description: "Arnative settings menu: themes, headers, footers, providers, usage",
528
+ description: "Arnative settings menu: themes, headers, footers, animations, auto-compact, model heal, providers, usage",
522
529
  getArgumentCompletions: arnativeCompletions,
523
530
  handler: arnativeHandler,
524
531
  });
@@ -530,8 +537,24 @@ export function registerCommands(pi: Pick<ExtensionAPI, "registerCommand">): voi
530
537
  });
531
538
  }
532
539
 
540
+ /** Record the choices in use in `config.json`, defaults included, so the file reads as the
541
+ * profile instead of a diff against it. Idempotent: only keys that differ get written. */
542
+ export function recordProfile(): void {
543
+ ensureChoices({
544
+ [HEADER_PRESET_KEY]: activeHeaderPreset(),
545
+ [FOOTER_PRESET_KEY]: activeFooterPreset(),
546
+ [SPINNER_PRESET_KEY]: activeSpinnerPreset(),
547
+ [SPINNER_GRADIENT_KEY]: activeSpinnerGradient() ? "on" : "off",
548
+ [AUTO_COMPACT_KEY]: activeAutoCompact(),
549
+ [MODEL_HEAL_KEY]: activeModelHeal(),
550
+ });
551
+ }
552
+
533
553
  export default function (pi: ExtensionAPI) {
534
554
  pi.on("session_start", async (_event, ctx) => {
555
+ // Before the theme branch below returns: the profile is recorded once per install, so
556
+ // `config.json` lists every choice even when it never left its default.
557
+ recordProfile();
535
558
  // `setTheme` writes the choice into pi's settings, so this runs once per install and the
536
559
  // second session already sees an explicit setting.
537
560
  if (!shouldApplyDefaultTheme(pi.getSettings()?.theme, ctx.ui.getAllThemes())) return;
@@ -30,7 +30,7 @@ import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts
30
30
  export const AUTO_COMPACT_CHOICES = ["Off", "Smart", "100k", "150k", "200k", "300k", "400k"] as const;
31
31
  export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
32
32
  export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
33
- const AUTO_COMPACT_KEY = "autoCompact";
33
+ export const AUTO_COMPACT_KEY = "autoCompact";
34
34
 
35
35
  /** Smart's tier table, first match wins. `null` defers the window to pi's own
36
36
  * compaction — the "100%" tier, where the current behavior is already safe. */
@@ -16,6 +16,7 @@ import { softOf, softSecondaryOf, stripAnsi } from "../lib/ansi.ts";
16
16
  import { assert, isMain } from "../lib/check.ts";
17
17
  import { capitalize, markedLabels, modelDisplayParts } from "../lib/format.ts";
18
18
  import { IS_WINDOWS_LIKE, SHORTCUT_RELOAD, SHORTCUT_TOGGLE_FOOTER } from "../lib/shortcuts.ts";
19
+ import { markPatched, originalOf } from "../lib/patch.ts";
19
20
  import { formatTokens } from "../lib/usage-store.ts";
20
21
  import { FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY, loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
21
22
  import { EDITOR_KEY, activeSpinnerGradient, activeSpinnerPreset } from "./animations.ts";
@@ -73,17 +74,17 @@ export function setFooterPreset(name: FooterPreset, ctx: ExtensionContext): void
73
74
  applyFooterPreset(ctx);
74
75
  }
75
76
 
76
- // Intercept the built-in FooterComponent to force a pure 2-line footer
77
- const PATCHED_KEY = Symbol.for("pi-arnative.footer2LinesPatched");
78
- if (FooterComponent?.prototype?.render && !(globalThis as Record<symbol, boolean>)[PATCHED_KEY]) {
79
- (globalThis as Record<symbol, boolean>)[PATCHED_KEY] = true;
80
- const origRender = FooterComponent.prototype.render;
81
- FooterComponent.prototype.render = function (width: number): string[] {
77
+ // Intercept the built-in FooterComponent to force a pure 2-line footer.
78
+ // Reinstalled on every load (lib/patch.ts): `/reload` must pick up a footer change.
79
+ if (FooterComponent?.prototype?.render) {
80
+ const proto = FooterComponent.prototype as any;
81
+ const origRender = originalOf<(this: any, width: number) => string[]>(proto, "render");
82
+ proto.render = markPatched(function (this: any, width: number): string[] {
82
83
  // "Pi (system)" preset = pi's own footer, so keep its stock line count.
83
84
  if (activeFooterPreset() === "Pi (system)") return origRender.call(this, width);
84
85
  const lines = origRender.call(this, width);
85
86
  return lines.length > 2 ? lines.slice(0, 2) : lines;
86
- };
87
+ });
87
88
  }
88
89
 
89
90
  let activeThemeProxy: { fg(color: string, text: string): string; bg?(color: string, text: string): string } | null = null;
@@ -1379,9 +1380,12 @@ if (isMain(import.meta.url)) {
1379
1380
  writeFileSync(join(repo, ".git", "HEAD"), "ref: refs/heads/arnative-tests\n");
1380
1381
  git = null;
1381
1382
  const noGit = mkdtempSync(join(tmpdir(), "pi-arnative-nogit-"));
1382
- void refreshGit(noGit); // in flight (deterministic: sync up to the first await), resolves git = null
1383
+ // `noGit` is not always repo-free: a temp dir under a versioned home finds the home
1384
+ // repo, so this first refresh really is in flight and can publish the home branch
1385
+ // before the queued one lands. Wait for the queued result, not for "not null".
1386
+ void refreshGit(noGit);
1383
1387
  await refreshGit(repo); // queued behind it with the newest cwd
1384
- for (let i = 0; i < 100 && git === null; i++) await new Promise((r) => setTimeout(r, 20));
1388
+ for (let i = 0; i < 250 && git?.branch !== "arnative-tests"; i++) await new Promise((r) => setTimeout(r, 20));
1385
1389
  assert(git !== null && git.branch === "arnative-tests", "queued git refresh re-ran on the newest cwd (not dropped)");
1386
1390
  rmSync(noGit, { recursive: true, force: true });
1387
1391
  rmSync(repo, { recursive: true, force: true });
@@ -1489,7 +1493,7 @@ if (isMain(import.meta.url)) {
1489
1493
  // Self-check: the ponytail glyph. \uef51 carries no outline in the Windows Nerd Font
1490
1494
  // build and renders blank there, so the status silently loses its icon (this is what
1491
1495
  // a past commit did). Pin the codepoint so a swap back to an invisible one fails here.
1492
- const ponyLine = ponytailStatusLine("⚡ ponytail: FULL", (s) => s, (s) => s, (s) => s);
1496
+ const ponyLine = ponytailStatusLine("ponytail: FULL", (s) => s, (s) => s, (s) => s);
1493
1497
  assert(ponyLine.includes("\uef04"), "the ponytail status renders the \\uef04 horse, not the blank \\uef51");
1494
1498
  assert(!ponyLine.includes("\uef51"), "the blank \\uef51 glyph must never come back");
1495
1499
  assert(ponytailStatusLine("ponytail: LITE", (s) => s, (s) => s, (s) => s).includes("LITE"), "the ponytail mode is read from the status text");
@@ -12,11 +12,12 @@
12
12
  * - Box divider '├────┤'. Active tab content is left-aligned, wrapped, soft.
13
13
  * - Hides pi's built-in stacked list in loadedResourcesContainer.
14
14
  */
15
- import { readFileSync, readdirSync } from "node:fs";
15
+ import { readFileSync } from "node:fs";
16
16
  import { fileURLToPath } from "node:url";
17
- import { userInfo } from "node:os";
17
+ import { homedir, userInfo } from "node:os";
18
18
  import { join } from "node:path";
19
19
  import {
20
+ CONFIG_DIR_NAME,
20
21
  UserMessageComponent,
21
22
  getAgentDir,
22
23
  VERSION,
@@ -39,6 +40,7 @@ import { SHORTCUT_NEW_SESSION, SHORTCUT_NEXT_TAB, SHORTCUT_RELOAD } from "../lib
39
40
  import { HEADER_PRESET_KEY as HEADER_PRESET_CONFIG_KEY, loadChoice, saveChoice } from "../lib/preset-store.ts";
40
41
  import { formatTokens, getModelAllTimeUsage } from "../lib/usage-store.ts";
41
42
 
43
+ import { patchOnce } from "../lib/patch.ts";
42
44
  export type TabKey = "Model" | "Directory" | "Context" | "Skills" | "Extensions" | "Shortcut";
43
45
 
44
46
  // Tab order for the next-tab shortcut and for the menu line.
@@ -139,14 +141,6 @@ export function sectionNameOf(text: string): "Context" | "Skills" | "Extensions"
139
141
  return null;
140
142
  }
141
143
 
142
- export function packageNameOf(label: string): string | null {
143
- const base = label.split(":")[0].trim();
144
- if (base === "") return null;
145
- const at = base.lastIndexOf("@");
146
- if (at > 0 && /^\d/.test(base.slice(at + 1))) return null;
147
- return /^[\w.@/-]+$/.test(base) ? base : null;
148
- }
149
-
150
144
  /**
151
145
  * OS account name of whoever is running pi, for the header greeting. Falls back to the
152
146
  * usual env vars, then to a neutral word so the line is never empty.
@@ -162,8 +156,6 @@ export function deviceUser(): string {
162
156
  return u || "there";
163
157
  }
164
158
 
165
- const versionCache = new Map<string, string | null>();
166
-
167
159
  export function readVersion(dir: string): string | null {
168
160
  try {
169
161
  const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as { version?: unknown };
@@ -173,27 +165,123 @@ export function readVersion(dir: string): string | null {
173
165
  }
174
166
  }
175
167
 
176
- export function installedVersion(
177
- label: string,
178
- root = join(getAgentDir(), "npm", "node_modules"),
179
- gitRoot = join(getAgentDir(), "git"),
180
- ): string | null {
181
- const name = packageNameOf(label);
182
- if (!name) return null;
183
- if (versionCache.has(name)) return versionCache.get(name) ?? null;
184
- let version = readVersion(join(root, name));
185
- if (!version && name.includes("/")) {
168
+ // ---------------------------------------------------------------------------
169
+ // Extensions tab = the `pi list` rows, then the loose extension files.
170
+ // pi's own listing names one loaded module per row, so a package shows up as
171
+ // eleven file names and the package itself never appears.
172
+ // ---------------------------------------------------------------------------
173
+
174
+ export interface InstalledPackage {
175
+ /** Row text: the configured source without its `npm:` prefix, plus the installed version
176
+ * when the source names none. */
177
+ label: string;
178
+ /** Absolute dir for a local-path source (null for npm and git packages). */
179
+ localPath: string | null;
180
+ }
181
+
182
+ /** Installed version per `agentDir` and package name; one read per package per process. */
183
+ const versionCache = new Map<string, string | null>();
184
+
185
+ /** `name@1.2.3` -> `{ name: "name", version: "1.2.3" }`; a scope's `@` is not a version. */
186
+ function splitVersion(label: string): { name: string; version: string | null } {
187
+ const at = label.lastIndexOf("@");
188
+ if (at > 0 && /\d/.test(label.slice(at + 1))) return { name: label.slice(0, at), version: label.slice(at + 1) };
189
+ return { name: label, version: null };
190
+ }
191
+
192
+ /** The row text of an npm package: the source as configured, or with the installed version.
193
+ * The version lives in the package's own `package.json`, the same place `pi list` resolves it. */
194
+ function npmRow(source: string, agentDir: string): string {
195
+ const label = source.slice("npm:".length);
196
+ const { name, version } = splitVersion(label);
197
+ if (version !== null) return label; // pinned in settings: show what was asked for
198
+ const key = `${agentDir}\0${name}`;
199
+ if (!versionCache.has(key)) versionCache.set(key, readVersion(join(agentDir, "npm", "node_modules", name)));
200
+ const installed = versionCache.get(key) ?? null;
201
+ return installed ? `${label}@${installed}` : label;
202
+ }
203
+
204
+ /** Slashes forward, `~` expanded, lower case: comparable against a listing path. */
205
+ function comparablePath(path: string): string {
206
+ const home = homedir().replace(/\\/g, "/");
207
+ const expanded = path.startsWith("~") ? home + path.slice(1) : path;
208
+ return expanded.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
209
+ }
210
+
211
+ /**
212
+ * Packages configured in settings, in `pi list` order: user scope first, then project.
213
+ * Read straight from the two settings files; the header runs on every render, so it
214
+ * must not build a package manager for this.
215
+ */
216
+ export function installedPackages(agentDir: string, cwd: string): InstalledPackage[] {
217
+ const sourcesOf = (file: string): string[] => {
186
218
  try {
187
- for (const host of readdirSync(gitRoot)) {
188
- version = readVersion(join(gitRoot, host, name));
189
- if (version) break;
190
- }
219
+ const settings = JSON.parse(readFileSync(file, "utf8")) as {
220
+ packages?: Array<string | { source?: unknown }>;
221
+ };
222
+ return (settings.packages ?? [])
223
+ .map((pkg) => (typeof pkg === "string" ? pkg : typeof pkg.source === "string" ? pkg.source : ""))
224
+ .filter((source) => source !== "");
191
225
  } catch {
192
- version = null;
226
+ return []; // no settings file (or unreadable JSON): the tab shows no package, not an error
193
227
  }
228
+ };
229
+ const scopes = [
230
+ { sources: sourcesOf(join(agentDir, "settings.json")), baseDir: agentDir },
231
+ { sources: sourcesOf(join(cwd, CONFIG_DIR_NAME, "settings.json")), baseDir: join(cwd, CONFIG_DIR_NAME) },
232
+ ];
233
+ return scopes.flatMap(({ sources, baseDir }) =>
234
+ sources.map((source) => {
235
+ const packaged = /^(npm|git):/.test(source);
236
+ // Relative local sources resolve against their own scope dir, the way pi installs them.
237
+ const absolute = /^([A-Za-z]:)?[\\/]/.test(source) || source.startsWith("~") ? source : join(baseDir, source);
238
+ const label = source.startsWith("npm:") ? npmRow(source, agentDir) : source;
239
+ return { label, localPath: packaged ? null : comparablePath(absolute) };
240
+ }),
241
+ );
242
+ }
243
+
244
+ /** Loose extension files from pi's expanded `[Extensions]` listing (never package modules). */
245
+ export function listingLocalPaths(expanded: string): string[] {
246
+ const paths: string[] = [];
247
+ for (const line of stripAnsi(expanded).split("\n")) {
248
+ if (line.trim() === "") continue;
249
+ // pi indents the groups by 2, a loose path or a package source by 4, a package module by 6.
250
+ if (line.length - line.trimStart().length !== 4) continue;
251
+ const text = line.trim();
252
+ if (!/^(npm|git):/.test(text)) paths.push(text);
253
+ }
254
+ return paths;
255
+ }
256
+
257
+ /** Last segment of a path; an `index.ts` file names its folder instead. */
258
+ function fileLabel(path: string): string {
259
+ const segments = path.split("/").filter(Boolean);
260
+ const last = segments[segments.length - 1] ?? path;
261
+ if ((last === "index.ts" || last === "index.js") && segments.length > 1) {
262
+ return segments[segments.length - 2]!;
194
263
  }
195
- versionCache.set(name, version);
196
- return version;
264
+ return last;
265
+ }
266
+
267
+ /** Tab rows: one per installed package, then the loose extension files, sorted. */
268
+ export function extensionTabItems(expanded: string, agentDir: string, cwd: string): string[] {
269
+ const packages = installedPackages(agentDir, cwd);
270
+ const localRoots = packages.map((pkg) => pkg.localPath).filter((root): root is string => root !== null);
271
+ const items = packages.map((pkg) => pkg.label);
272
+ const seen = new Set(items);
273
+ const locals: string[] = [];
274
+ for (const path of listingLocalPaths(expanded)) {
275
+ const comparable = comparablePath(path);
276
+ // Modules of a local-path package are rows of that package, not files of their own.
277
+ if (localRoots.some((root) => comparable === root || comparable.startsWith(`${root}/`))) continue;
278
+ const label = fileLabel(path.replace(/\\/g, "/"));
279
+ if (seen.has(label)) continue;
280
+ seen.add(label);
281
+ locals.push(label);
282
+ }
283
+ locals.sort((a, b) => a.localeCompare(b));
284
+ return [...items, ...locals];
197
285
  }
198
286
 
199
287
  // Arnative build actually running: package.json one level above this extension file.
@@ -201,7 +289,7 @@ export function installedVersion(
201
289
  // behind whenever the local clone (or a hand-copied extensions/) is what pi loaded.
202
290
  const ARNATIVE_VERSION = readVersion(fileURLToPath(new URL("..", import.meta.url)));
203
291
 
204
- export function extractItemsFromBody(body: string, isExtensions = false): string[] {
292
+ export function extractItemsFromBody(body: string): string[] {
205
293
  const plain = stripAnsi(body).trim();
206
294
  if (!plain) return [];
207
295
  const lines = plain.split("\n").map((l) => l.trim()).filter(Boolean);
@@ -213,17 +301,7 @@ export function extractItemsFromBody(body: string, isExtensions = false): string
213
301
  items.push(line);
214
302
  }
215
303
  }
216
- if (!isExtensions) return items;
217
- // One row per package (like `pi list`): drop the `:subpath` of every module inside a
218
- // package and repeat nothing. Local single-file extensions (`hark.ts`) stay as they are.
219
- const labels = new Set<string>();
220
- for (const item of items) {
221
- const colon = item.indexOf(":");
222
- const base = (colon === -1 ? item : item.slice(0, colon)).trim();
223
- const ver = installedVersion(base);
224
- labels.add(ver ? `${base}@${ver}` : base);
225
- }
226
- return [...labels];
304
+ return items;
227
305
  }
228
306
 
229
307
  // Cheatsheet for the Shortcut tab. Mirrors README "Shortcuts" plus the bindings the
@@ -706,16 +784,14 @@ export function extensionIssuesLines(th: BoxTheme | null, width: number, rows: s
706
784
  // Hooks the shared `app.tools.expand` key: `ctrl+o to expand` -> `[ctrl+o to expand]`.
707
785
  const wrapHint = (key: string): string => `[${key} to expand]`;
708
786
 
709
- // Intercept loadedResourcesContainer: capture data for the tabs and hide pi's own display
710
- const SECTION_HEADER_KEY = Symbol.for("pi-arnative.sectionHeadersRewritten");
711
- if (UserMessageComponent?.prototype && !(globalThis as Record<symbol, boolean>)[SECTION_HEADER_KEY]) {
712
- (globalThis as Record<symbol, boolean>)[SECTION_HEADER_KEY] = true;
787
+ // Intercept loadedResourcesContainer: capture data for the tabs and hide pi's own display.
788
+ // Reinstalled on every load (lib/patch.ts), otherwise `/reload` keeps the first closure.
789
+ if (UserMessageComponent?.prototype) {
713
790
  const containerProto = Object.getPrototypeOf(UserMessageComponent.prototype) as {
714
791
  addChild?: (child: unknown) => unknown;
715
792
  };
716
793
  if (typeof containerProto?.addChild === "function") {
717
- const origAddChild = containerProto.addChild;
718
- containerProto.addChild = function (child: any): unknown {
794
+ patchOnce(containerProto, "addChild", (origAddChild) => function (this: any, child: any): unknown {
719
795
  // "Pi (system)" preset = pi's own header, so leave pi's startup list untouched.
720
796
  if (activeHeaderPreset() === "Pi (system)") return origAddChild.call(this, child);
721
797
  try {
@@ -732,9 +808,14 @@ if (UserMessageComponent?.prototype && !(globalThis as Record<symbol, boolean>)[
732
808
  (this as Record<string, unknown>)._isLoadedResourcesContainer = true;
733
809
 
734
810
  countsKnown = true;
735
- const rawBody = body.split("\n").slice(1).join("\n");
736
- const items = extractItemsFromBody(rawBody, sectionName === "Extensions");
737
- tabStore.set(sectionName, items);
811
+ if (sectionName === "Extensions") {
812
+ // The expanded listing carries the loose files; the packages come from settings.
813
+ const expanded = typeof child.getExpandedText === "function" ? String(child.getExpandedText()) : "";
814
+ tabStore.set("Extensions", extensionTabItems(expanded, getAgentDir(), getCwd() || process.cwd()));
815
+ } else {
816
+ const rawBody = body.split("\n").slice(1).join("\n");
817
+ tabStore.set(sectionName, extractItemsFromBody(rawBody));
818
+ }
738
819
 
739
820
  // Hide this child from the built-in display so it does not stack under the header
740
821
  child.render = () => [];
@@ -765,7 +846,7 @@ if (UserMessageComponent?.prototype && !(globalThis as Record<symbol, boolean>)[
765
846
  // fail-safe
766
847
  }
767
848
  return origAddChild.call(this, child);
768
- };
849
+ });
769
850
  }
770
851
  }
771
852