@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/CHANGELOG.md CHANGED
@@ -1,5 +1,43 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.0-rc.1] - 2026-10-25
4
+
5
+ ### Added
6
+ - **Auto-compact keeps long sessions light.** `/arnative` → **Auto-compact** picks **Smart** — a tier table 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) — or a **manual token budget** (`100k`–`400k`, one absolute number for any window). When a run settles with the context at or above the threshold, pi's own compaction fires through `ctx.compact()` — the same machinery and summary as `/compact`, never mid-run. Small windows defer entirely: a 128k model keeps pi's near-full `reserveTokens` compaction untouched. The saved choice is marked with a green ✓ at the end of its picker row. 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 (usage oscillating at the threshold cannot re-summarize every turn), and a full reset on session start (`extensions/autocompact.ts`).
7
+ - **The push gate hook now ships with the repo.** `.githooks/pre-push` is the pre-push gate the README describes (it used to live only in a machine-local setup): it rejects a branch push whose tip tree does not match the `.git/arnative-preview` stamp that `npm run preview` writes, so a fix cannot reach GitHub without a live preview. Tags and branch deletions pass; activate per clone with `git config core.hooksPath .githooks`.
8
+ - **Providers now write the limits and compat flags the endpoint implies.** The wizard already read the `/models` answer to list ids and threw the rest away; the same answer now also supplies each model's `contextWindow`/`maxTokens` (kept through later edits that never mention them) and a `compat` block the rules imply — developer-role off for reasoning models on a third-party OpenAI-compatible channel, session-affinity headers, Anthropic cache control on Claude-style relays, deepseek thinking format, adaptive thinking on Opus/Sonnet ≥ 4.6 and Fable ≥ 5 — while any value already in `models.json` still wins (`lib/compat.ts`, `suggestCompat`; `lib/provider.ts`, `wireModels`).
9
+ - **Thinking screen: `p` asks the channel which effort levels it accepts.** A 7-request probe per model sends `none`…`max`, records what answers, and stores the result as that model's `thinkingLevelMap` — a rejected level is remapped to the nearest accepted one, so `/think` offers only real levels instead of discovering them one 400 at a time. The result is the map itself, so it stays until the level is changed by hand; a channel that answers nothing writes nothing (`lib/compat.ts`, `probeEffort`/`buildEffortMap`; `lib/provider.ts`, `thinkingFlow`). The screen also gains two bulk keys: `[A]` sets every model to `auto` and `[R]` sets every model to `off`, in memory only, so Esc still discards and Enter saves.
10
+
11
+ ### Changed
12
+ - **Thinking now starts at `auto` for every model.** The provider wizard's id heuristic used to fall back to `off`, so a relay catalog with no effort suffix in its ids saved every model as chat and the Thinking screen showed almost nothing to do. The fallback is now `auto` (`reasoning: true`, no `thinkingLevelMap`), so `/think` passes the level straight to the endpoint for all of them; an explicit `-high`/`-xhigh`/`-max`/`-medium`/`-low`/`-minimal` suffix still pins that level, and Space in the Thinking screen still sets a model to `off` by hand (`lib/provider.ts`, `detectLevel`).
13
+
14
+ ### Fixed
15
+ - **The preview gate launches pi again on Windows.** `scripts/preview.mjs` spawned `pi` directly, which Node cannot do on Windows — the npm launcher is a sh script (ENOENT) or a `.cmd` (needs a shell) — so `npm run preview` crashed before pi ever opened and no push could ever be stamped. It now resolves the real entry (`where pi` → the global npm dir → `dist/bundle/cli.js`) and runs it with Node directly, args unquoted and intact; POSIX behavior is unchanged (`pi` still spawns directly when that works).
16
+ - **Large-session render cost: the per-frame patches are bounded now.** Both render patches scaled with the whole transcript on every frame, which made long sessions (a 1M-context model past ~20%) feel heavy in the terminal. The reload-box scan ran inside every `Container.render` — measured at 0.76 ms against pi's own 0.59 ms layout pass at 12.6k lines — and now refuses containers larger than 64 lines before scanning, because the reload box is a fixed ~9-line container (`extensions/ui-render-tweaks.ts`, `shouldHideReloadBox`). The user-bubble bg repair rebuilt every styled line on every frame and is now memoized per source line — pi's Markdown cache returns the same string references frame after frame — reset on a theme change and capped at 8192 entries (`extensions/timestamps.ts`, `repairBubbleBg`).
17
+
18
+ ## [0.7.0] - 2026-10-24
19
+
20
+ ### Added
21
+ - **Providers: a custom endpoint from three inputs.** `/arnative` → **Providers** asks for the endpoint URL, API key, and name, then probes the endpoint once (Ollama `/api/tags`, Gemini `/v1beta/models`, OpenAI/Anthropic `/models` lists), lists the models it answered with, and saves on Space-picked selection — the key into `auth.json` (the file `/login` writes), the declaration into `models.json`. `[a]` switches the API flavor when a relay answers in an ambiguous shape; no answer falls back to manual ids. Opening `/model` picks up the saved provider (`extensions/provider.ts`).
22
+ - **Provider actions: edit and delete on Enter.** Enter on a stored provider opens an action menu — Select models, Probe models (re-reads the endpoint, vanished models stay listed), Thinking, Delete. Every action writes through to `models.json` immediately (delete also removes the `auth.json` key); sibling provider fields like `compat` survive every edit.
23
+ - **Reasoning auto-detection.** Model ids decide the thinking flag on save: a `thinking`/`reasoner` token, an effort suffix (`-high`/`-medium`/`-low`), or an o1/o3/o4/r1-style generation marks reasoning models — `ag/claude-opus-4-6-thinking` and `ag/gemini-4-argon-high` on, `wally/glm-5.3-flash` off. The Thinking screen lists the flags with the detected values and Space overrides them.
24
+ - **Thinking levels on pi's full scale.** The Thinking screen no longer toggles a boolean: Space cycles each model through `off → auto → minimal → low → medium → high → xhigh → max`, detected from the id (an explicit `-high`/`-xhigh`/`-max`… suffix pins that level; a `thinking`/`reasoner`/o1/r1 token means `auto`). Levels write pi's own wire shape — `reasoning: true` plus a `thinkingLevelMap` that pins exactly the supported level — so `/think` offers the model's real levels and clamps to them (`xhigh`/`max` only appear when mapped, exactly as pi's schema defines).
25
+ - **Scrolling model lists.** The shared picker gains a 10-row viewport: long relay catalogs scroll a window centered on the cursor, with `↑ N more` / `↓ N more` rows announcing what is hidden, so the box keeps one height (`lib/list-picker.ts`).
26
+ - **Picked count in the models legend.** The models picker footer reads `34/44 picked · [↑↓] Move …` with the count in the accent color, next to the keys it describes (`lib/box.ts` renders a pre-styled legend verbatim).
27
+ - **Back where it belongs.** `←` works in submenus only: the provider list steps back to the `/arnative` menu, the provider actions step back to the list, and every settings screen keeps its `[←] Back` legend. The root menu hides the key entirely (`back: false`) — it has nothing behind it, so Esc and `q` stay the only closes and its legend reads `[↑↓] Move [Enter] Open [Esc] Close`. Fill screens (model pick, thinking levels) hide it too, so a stray `←` cannot throw away a half-picked list.
28
+ - **The provider list reflects its own edits.** After adding, editing or deleting a provider, the Providers screen re-reads `models.json` instead of showing the copy it opened with — a new provider appears immediately, no `/arnative` round-trip.
29
+ - **Wizard prompts in the arnative box.** Every text field the provider wizard asks for (endpoint, key, name, manual ids, headless fallbacks) renders as an arnative screen: rounded thinking-colored border, `Provider - Arnative⠙` title, the field as the description, a `> ` prompt with the pi-tui editor underneath (arrows, word motions, paste, undo all work), a dim example while empty, and the `[Enter] Save [Esc] Cancel` legend — replacing pi's full-width native input dialog (`lib/list-picker.ts`, `InputPicker`).
30
+ - **Probe status above the chat input.** While the wizard probes an endpoint (add flow and the Probe models action), a one-line dim `probing endpoint…` appears directly above the chat input (pi's `setWidget` aboveEditor slot) and disappears the moment the probe settles — no longer a status row in the bottom footer (`lib/provider.ts`, `probingStatus`).
31
+ - **All pi-arnative files in one folder, cache 55% smaller.** Everything the package writes now lives under `~/.pi/agent/arnative/` — `config.json` (preset choices) and `usage-cache.json` (the `/usage` scan cache) — instead of three flat `arnative-*.json` files in `~/.pi/agent/`; existing files are migrated in automatically on first read. The cache gained a compact disk shape: keys are session-dir-relative paths, rollups store one row per provider+model (provider rows are derived on load), and one-letter field names — 90 KB shrank to 40 KB on a real machine with identical answers. The legacy `arnative-prices.json` is deleted from the disk on first load (nothing has read it since pricing moved into `cost` fields in pi's `models.json`, which the provider wizard fills in), and a flat file a downgrade recreated beside the folder copy is removed the same way; `config.json` stamps a `layoutVersion` so the next layout change has one hook to migrate from. Preset choices and the cache are never deleted — only moved (`lib/preset-store.ts`, `lib/usage-store.ts`).
32
+ - **Footer diff stat now tracks edits as they land.** The git refresh ran only at session and turn start, so a session that edits or commits inside a turn (the normal pattern when each step is committed) kept showing the pre-turn snapshot — often clean — and the `+X -Y` working-tree diff never appeared. The footer now re-reads git state whenever a tool call finishes (edit, write, or a commit through bash); concurrent refreshes still coalesce into at most two `git` runs per burst (`extensions/footer.ts`).
33
+
34
+ ### Changed
35
+ - **`/arnative` → Themes lists this package's themes only.** The picker shows the `arnative` family (`arnative` and its variants) and nothing else — pi's own `system`/`dark`/`light` and a theme of your own (e.g. `omarchy-system`) stay in `/settings` → Theme, which keeps the full list. Esc still reverts to whatever theme was active when the picker opened, arnative or not, and the empty-list message now points at a reinstall instead of the themes folder (`extensions/arnative.ts`).
36
+
37
+ ### Fixed
38
+ - **Esc cancels the add-provider flow at every prompt.** The flow asked for endpoint, API key and provider name, but only Esc at the first prompt aborted: Esc at the key prompt continued keyless (and could save a provider with a dummy key that never authenticates), Esc at the name prompt silently accepted the suggested name. Both prompts now honor the `[Esc] Cancel` their legend promises — Enter on an empty key field still means keyless, and an empty name still accepts the suggestion (`lib/provider.ts`).
39
+ - **Provider config writes are atomic.** `writeJson` wrote `models.json` and `auth.json` with a direct `writeFileSync`, so a crash or power loss mid-write could truncate them — a truncated `auth.json` breaks the stored credentials of every provider, and the wizard then refuses to save until the file is repaired by hand. It now writes a temp file and renames it over the target, the same pattern `preset-store.ts` and `usage-store.ts` already use, and the self-check proves an interrupted save leaves the previous config intact (`lib/provider.ts`).
40
+
3
41
  ## [0.6.2] - 2026-10-20
4
42
 
5
43
  ### Fixed
package/README.md CHANGED
@@ -18,12 +18,13 @@ pi-arnative replaces pi’s default terminal chrome with a unified, cohesive vis
18
18
  - Enhanced Footer: 3-row status grid tracking branch, active duration (30s idle freeze), and token speed.
19
19
  - Transcript Clock: Timestamps for conversation messages with clean bubble backgrounds.
20
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.
21
22
 
22
23
  <details>
23
24
  <summary><b>Configuration & Presets</b></summary>
24
25
 
25
26
  ### Working Spinner Presets
26
- Configurable via `/arnative` → **Animations** (saved to `arnative-config.json`).
27
+ Configurable via `/arnative` → **Animations** (saved to `~/.pi/agent/arnative/config.json`).
27
28
  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.
28
29
 
29
30
  ### Footer Presets
@@ -32,6 +33,14 @@ Configurable via `/arnative` → **Footers**:
32
33
  - `Arnative (Minimal)` (single collapsible head row; click or `ctrl+alt+m` to toggle)
33
34
  - `Pi (system)` (built-in footer)
34
35
 
36
+ ### Auto-compact
37
+ Configurable via `/arnative` → **Auto-compact** (saved to `~/.pi/agent/arnative/config.json`).
38
+ 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:
39
+ - **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).
40
+ - **A manual token budget** (`100k`–`400k`): one absolute number, whatever the window.
41
+
42
+ 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.
43
+
35
44
  </details>
36
45
 
37
46
  ## Install
@@ -58,7 +67,7 @@ npm run dev
58
67
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
59
68
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
60
69
  | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
61
- | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Usage) |
70
+ | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Providers, Usage) |
62
71
  | Click tool / `ctrl+o` | Toggle tool output box |
63
72
  | `←` | Back — step back from submenus/dashboard to menu |
64
73
 
@@ -90,8 +99,11 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
90
99
  | `extensions/section-headers.ts` | Tabbed header and resource box (preset: `/arnative headers`) |
91
100
  | `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
92
101
  | `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
102
+ | `extensions/autocompact.ts` | Auto-compact: Smart tiers by window or a fixed token budget (`/arnative` → Auto-compact) |
93
103
  | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
94
104
  | `extensions/arnative.ts` | Settings menu with live preview and navigation |
105
+ | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
106
+ | `lib/list-picker.ts` | The live-preview/multi-select picker every arnative screen shares |
95
107
  | `extensions/timestamps.ts` | Message timestamps and bubble backgrounds |
96
108
  | `extensions/ui-render-tweaks.ts` | Contrast tweaks, selection style, and UI polish |
97
109
  | `extensions/usage.ts` | Token and cost dashboard (`/usage`) |
@@ -118,12 +130,16 @@ npm run preview # Live preview the working tree in your own Pi (stamps a pushabl
118
130
 
119
131
  Pre-publish verification and tag validation are enforced via `scripts/release-check.mjs`.
120
132
 
121
- **Local-first push gate:** the global pre-push hook rejects any branch push whose commit
133
+ **Local-first push gate:** the pre-push hook (`.githooks/pre-push`) rejects any branch push whose commit
122
134
  carries no live-preview stamp, so a fix cannot reach GitHub unseen. `npm run preview`
123
135
  launches Pi with this working tree and writes `.git/arnative-preview` for the exact commit
124
136
  that was shown; editing `extensions/`, `lib/`, `themes/`, or `package.json` afterwards
125
137
  invalidates it and the hook asks for a fresh preview. The preview must run on a clean tree
126
- — commit or stash first.
138
+ — commit or stash first. Git does not auto-install hooks; activate per clone:
139
+
140
+ ```bash
141
+ git config core.hooksPath .githooks
142
+ ```
127
143
 
128
144
  </details>
129
145
 
@@ -6,12 +6,11 @@
6
6
  * the session's thinking slot (`lib/ansi.ts`), so it belongs to the active model.
7
7
  */
8
8
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
9
- import { matchesKey, truncateToWidth, visibleWidth, type AutocompleteItem, type Component } from "@earendil-works/pi-tui";
10
- import { softSecondaryOf, stripAnsi, thinkingColorOf } from "../lib/ansi.ts";
11
- import { renderScreen, screenTitle, type ScreenText } from "../lib/box.ts";
9
+ import { visibleWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
10
+ import { stripAnsi } from "../lib/ansi.ts";
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 { LEGEND_LIVE, LEGEND_MOVE, matchesBack } from "../lib/shortcuts.ts";
15
14
  import { SPINNER_PRESETS, type SpinnerPreset } from "../lib/spinner.ts";
16
15
  import {
17
16
  activeSpinnerGradient,
@@ -25,6 +24,9 @@ import {
25
24
  } from "./animations.ts";
26
25
  import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
27
26
  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 { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
29
+ import { openProviders } from "../lib/provider.ts";
28
30
  import { openUsage } from "./usage.ts";
29
31
 
30
32
  export interface ArnativeMenu {
@@ -35,199 +37,30 @@ export interface ArnativeMenu {
35
37
  open: (ctx: ExtensionCommandContext) => Promise<boolean | void>;
36
38
  }
37
39
 
38
- /** One picker row: `Label · Note`. `note` is absent on the preset lists (themes, headers,
39
- * footers), which are bare names. */
40
- export interface ListRow {
41
- label: string;
42
- note?: string;
43
- }
44
-
45
40
  /** Menu rows: `Label · description` (same rhythm as /jev-eye's menu). */
46
41
  export function menuRows(menus: Pick<ArnativeMenu, "label" | "description">[]): ListRow[] {
47
42
  return menus.map((m) => ({ label: m.label, note: m.description }));
48
43
  }
49
44
 
50
- // Legends come from the `KeySet`s the handlers match, so a key cannot be advertised on a
51
- // screen that does not handle it; the root menu has nothing behind it and omits `←`.
52
- export const LIST_LEGEND_MOVE = LEGEND_MOVE;
53
- export const LIST_LEGEND_LIVE = LEGEND_LIVE;
54
-
55
- /** One row as a flat string — the headless/RPC `ctx.ui.select` fallback, which has no columns. */
56
- export function rowText(row: ListRow): string {
57
- return row.note ? `${row.label} · ${row.note}` : row.label;
58
- }
59
-
60
- /** Bare names (preset lists) as rows; the cursor's `→` marks the live value. */
61
- const nameRows = (names: readonly string[]): ListRow[] => names.map((label) => ({ label }));
62
-
63
45
  /** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
64
46
  export const MENU_TITLE = screenTitle("Settings");
65
47
  /** One-line description under the menu title. */
66
- export const MENU_DESC = "Themes, headers, footers, animations, usage";
67
-
68
- interface ListPickerHooks {
69
- /** Apply a value on every selection move (live preview). */
70
- preview: (name: string) => void;
71
- /** Restore the value the picker opened with (Esc). */
72
- revert: () => void;
73
- done: () => void;
74
- requestRender: () => void;
75
- /** Esc, when it must be told apart from Enter (a menu selects, it does not revert). */
76
- cancel?: () => void;
77
- /** `←`: leave this screen for its parent (the menu, or the chat when there is none).
78
- * Distinct from `cancel`/Esc, which closes or reverts the screen it is on. */
79
- back?: () => void;
80
- /** `g`: toggle a screen-level switch (Animations → gradient). Only a screen that passes
81
- * this hook reacts to the key, so `g` stays a plain letter everywhere else. */
82
- toggleGradient?: () => void;
83
- /** Note re-read on every render, so a row can animate (Animations → a moving frame).
84
- * Returning undefined keeps the row's static note. */
85
- note?: (label: string) => string | undefined;
86
- /** Repaint cadence for an animated note. The frame itself is read from the clock, so a
87
- * missed repaint costs one frame and never desynchronises the animation. */
88
- tickMs?: number;
89
- /** Legend re-read on every render, for a key row that states live state
90
- * (`[g] Gradient on`). A constant legend would keep advertising the value it opened with. */
91
- legend?: () => string;
92
- }
93
-
94
- /** Box copy, so one picker serves every menu ("Themes - Arnative⠙", "Headers - Arnative⠙", …).
95
- * The same shape every arnative screen uses — see {@link renderScreen}. */
96
- export type ListPickerText = ScreenText;
97
-
98
- /** Live-preview picker: ↑↓ previews instantly, Enter keeps, Esc reverts. A caller whose
99
- * preview does nothing (`livePreview: false`) gets a plain menu: no revert on Esc, and
100
- * Esc is reported through `cancel` so "chose nothing" stays distinguishable from Enter. */
101
- export class ListPicker implements Component {
102
- private theme: { fg(c: string, t: string): string; bold?(t: string): string };
103
- private rows: ListRow[];
104
- private hooks: ListPickerHooks;
105
- private text: ListPickerText;
106
- private selected: number;
107
- private applied: string | undefined;
108
- private readonly livePreview: boolean;
109
- private readonly opened: string | undefined;
110
- private readonly tick: ReturnType<typeof setInterval> | undefined;
111
- /** Border painter, from the session's thinking level — the box follows the model. */
112
- private readonly edge: (s: string) => string;
113
-
114
- constructor(
115
- theme: { fg(c: string, t: string): string; bold?(t: string): string },
116
- rows: ListRow[],
117
- current: string | undefined,
118
- hooks: ListPickerHooks,
119
- text: ListPickerText,
120
- /** False for a menu: the selection is applied only on Enter, never while moving. */
121
- livePreview = true,
122
- /** The session's thinking level; colors the box border (theme `thinking*` slot). */
123
- thinkingLevel?: string,
124
- ) {
125
- this.theme = theme;
126
- this.rows = rows;
127
- this.hooks = hooks;
128
- this.text = text;
129
- this.livePreview = livePreview;
130
- this.opened = current;
131
- this.applied = current;
132
- this.selected = Math.max(0, rows.findIndex((r) => r.label === current));
133
- this.edge = thinkingColorOf(theme, thinkingLevel);
134
- this.tick = hooks.tickMs ? setInterval(() => hooks.requestRender(), hooks.tickMs) : undefined;
135
- }
136
-
137
- invalidate(): void {}
138
- dispose(): void {
139
- if (this.tick) clearInterval(this.tick);
140
- }
141
-
142
- /** Selected row, for callers that need the choice after `done()` resolves. */
143
- get index(): number {
144
- return this.selected;
145
- }
146
-
147
- private move(delta: number): void {
148
- const next = Math.min(this.rows.length - 1, Math.max(0, this.selected + delta));
149
- if (next === this.selected) return;
150
- this.selected = next;
151
- if (!this.livePreview) {
152
- this.hooks.requestRender();
153
- return;
154
- }
155
- this.applied = this.rows[next]!.label;
156
- this.hooks.preview(this.applied);
157
- this.hooks.requestRender();
158
- }
159
-
160
- handleInput(keyData: string): void {
161
- if (matchesBack(keyData)) {
162
- // Leave for the parent without touching the preview: `back` owns the revert of an
163
- // uncommitted preview, because "cancel" here means "close", not "undo".
164
- if (this.hooks.back) {
165
- this.hooks.back();
166
- return;
167
- }
168
- // No parent (the root menu): ← behaves like Esc — close, reverting a live preview.
169
- if (this.applied !== this.opened) this.hooks.revert();
170
- (this.hooks.cancel ?? this.hooks.done)();
171
- return;
172
- }
173
- if (matchesKey(keyData, "q") || matchesKey(keyData, "Q") || matchesKey(keyData, "escape")) {
174
- if (this.applied !== this.opened) this.hooks.revert();
175
- (this.hooks.cancel ?? this.hooks.done)();
176
- return;
177
- }
178
- if (matchesKey(keyData, "up") || matchesKey(keyData, "k")) {
179
- this.move(-1);
180
- return;
181
- }
182
- if (matchesKey(keyData, "down") || matchesKey(keyData, "j")) {
183
- this.move(1);
184
- return;
185
- }
186
- if (matchesKey(keyData, "enter")) {
187
- this.hooks.done();
188
- return;
189
- }
190
- if (this.hooks.toggleGradient && matchesKey(keyData, "g")) this.hooks.toggleGradient();
191
- }
192
-
193
- render(width: number): string[] {
194
- const th = this.theme;
195
- const bold = th.bold ?? ((t: string) => `\x1b[1m${t}\x1b[22m`);
196
- const soft = softSecondaryOf(th);
197
- const edge = (text: string) => this.edge(text);
198
- const column = Math.max(0, ...this.rows.map((r) => visibleWidth(r.label)));
199
- const body: string[] = [];
200
- for (let i = 0; i < this.rows.length; i++) {
201
- const item = this.rows[i]!;
202
- const isSelected = i === this.selected;
203
- const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg(item.note ? "text" : "muted", s);
204
- const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
205
- const noteText = this.hooks.note?.(item.label) ?? item.note;
206
- const note = noteText ? `${th.fg("dim", ROW_DIVIDER)}${th.fg("dim", noteText)}` : "";
207
- // Extract parenthetical suffix to render softly
208
- const suffix = /(\(.*\))$/.exec(item.label)?.[1] ?? "";
209
- const head = suffix ? item.label.slice(0, item.label.length - suffix.length) : item.label;
210
- const tail = suffix ? th.fg("dim", suffix) : "";
211
- const content = `${isSelected ? th.fg("accent", "→ ") : " "}${paint(head)}${tail}${pad}${note}`;
212
- body.push(truncateToWidth(content, width - 4, ""));
213
- }
214
- return renderScreen(th, width, this.hooks.legend ? { ...this.text, legend: this.hooks.legend() } : this.text, body, edge);
215
- }
216
- }
48
+ export const MENU_DESC = "Themes, headers, footers, animations, auto-compact, providers, usage";
217
49
 
218
50
  const THEMES_PICKER_TEXT: ListPickerText = {
219
51
  title: screenTitle("Themes"),
220
- description: "Selection previews live — same list as /settings → Theme.",
52
+ description: "Selection previews live — arnative themes only (all themes: /settings → Theme).",
221
53
  legend: LIST_LEGEND_LIVE,
222
54
  };
223
55
 
224
56
  const openThemes = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
225
- const themes = ctx.ui.getAllThemes();
226
- if (themes.length === 0) {
227
- ctx.ui.notify("[arnative] No themes found. Add files to ~/.pi/agent/themes/ and run /reload.", "warning");
57
+ // Only this package's family (`arnative`, `arnative-<variant>`): the picker brands itself
58
+ // arnative, so pi's own themes and the user's belong in /settings → Theme, not here.
59
+ const names = ctx.ui.getAllThemes().map((t) => t.name).filter(isArnativeThemeName);
60
+ if (names.length === 0) {
61
+ ctx.ui.notify("[arnative] No arnative themes found. Reinstall pi-arnative, or pick any theme in /settings → Theme.", "warning");
228
62
  return;
229
63
  }
230
- const names = themes.map((t) => t.name);
231
64
  const current = ctx.ui.theme.name;
232
65
 
233
66
  if (ctx.mode !== "tui") {
@@ -409,11 +242,76 @@ const openAnimations = async (ctx: ExtensionCommandContext): Promise<boolean | v
409
242
  return goBack === true;
410
243
  };
411
244
 
245
+ const AUTOCOMPACT_PICKER_TEXT: ListPickerText = {
246
+ title: screenTitle("Auto-compact"),
247
+ description: "Smart tiers the trigger by context window; manual budgets fire at one absolute size.",
248
+ legend: LIST_LEGEND_MOVE,
249
+ };
250
+
251
+ /** One note per row: Smart states its tier table, a manual budget its window-independence. */
252
+ const AUTO_COMPACT_NOTES: Record<AutoCompactChoice, string> = {
253
+ Off: "never — pi's own compaction stays in charge",
254
+ Smart: "by window: 1M→20% · 512k→40% · 256k→80% · <192k→pi core",
255
+ "100k": "always above 100k tokens, any window",
256
+ "150k": "always above 150k tokens, any window",
257
+ "200k": "always above 200k tokens, any window",
258
+ "300k": "always above 300k tokens, any window",
259
+ "400k": "always above 400k tokens, any window",
260
+ };
261
+
262
+ /** Rows for the Auto-compact picker: the saved choice ends its row with a green ✓. */
263
+ export function autoCompactRows(opened: AutoCompactChoice): ListRow[] {
264
+ return AUTO_COMPACT_CHOICES.map((c) => ({ label: c, note: AUTO_COMPACT_NOTES[c], chosen: c === opened }));
265
+ }
266
+
267
+ /** A plain (non-live) picker: the choice is committed by Enter, nothing previews. The
268
+ * trigger itself lives in `extensions/autocompact.ts` and fires on the next settle. */
269
+ const openAutoCompact = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
270
+ const opened = activeAutoCompact();
271
+
272
+ if (ctx.mode !== "tui") {
273
+ // No custom components (RPC/headless): fall back to the blocking picker.
274
+ const labels = AUTO_COMPACT_CHOICES.map((c) => (c === opened ? `${c} ✓` : c));
275
+ const pick = await ctx.ui.select(AUTOCOMPACT_PICKER_TEXT.title, labels);
276
+ if (pick === undefined) return;
277
+ setAutoCompact(AUTO_COMPACT_CHOICES[labels.indexOf(pick)]!);
278
+ ctx.ui.notify(
279
+ `[arnative] Auto-compact: ${pick === "Off" ? "off" : pick === "Smart" ? "smart (tiered by context window)" : `above ${pick} tokens of context`}`,
280
+ "info",
281
+ );
282
+ return;
283
+ }
284
+
285
+ const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
286
+ const picker = new ListPicker(
287
+ theme,
288
+ autoCompactRows(opened),
289
+ opened,
290
+ {
291
+ preview: () => {},
292
+ revert: () => {},
293
+ done: () => {
294
+ setAutoCompact(AUTO_COMPACT_CHOICES[picker.index]!);
295
+ done(false);
296
+ },
297
+ cancel: () => done(false),
298
+ back: () => done(true),
299
+ requestRender: () => tui.requestRender(),
300
+ },
301
+ AUTOCOMPACT_PICKER_TEXT,
302
+ false,
303
+ ctx.thinkingLevel,
304
+ );
305
+ return picker;
306
+ });
307
+ return goBack === true;
308
+ };
309
+
412
310
  export const MENUS: ArnativeMenu[] = [
413
311
  {
414
312
  value: "themes",
415
313
  label: "Themes",
416
- description: "list & apply themes (the /settings → Theme list)",
314
+ description: "arnative themes only (all themes: /settings → Theme)",
417
315
  open: openThemes,
418
316
  },
419
317
  {
@@ -434,6 +332,18 @@ export const MENUS: ArnativeMenu[] = [
434
332
  description: "choose the working spinner",
435
333
  open: openAnimations,
436
334
  },
335
+ {
336
+ value: "compact",
337
+ label: "Auto-compact",
338
+ description: "smart by window or a fixed token budget (off by default)",
339
+ open: openAutoCompact,
340
+ },
341
+ {
342
+ value: "providers",
343
+ label: "Providers",
344
+ description: "custom endpoints: endpoint, key, name — the rest is automatic",
345
+ open: openProviders,
346
+ },
437
347
  {
438
348
  value: "usage",
439
349
  label: "Usage",
@@ -465,8 +375,11 @@ async function openMainMenu(ctx: ExtensionCommandContext, startLabel?: string):
465
375
  revert: () => {},
466
376
  done: () => done(picker.index),
467
377
  cancel: () => done(null),
378
+ // Nothing is behind the root menu: `←` is not a close shortcut here, so the key
379
+ // is hidden — Esc (and `q`) close, and the legend says so.
380
+ back: false,
468
381
  requestRender: () => tui.requestRender(),
469
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false, ctx.thinkingLevel);
382
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false, ctx.thinkingLevel);
470
383
  return picker;
471
384
  });
472
385
  if (index === null || index === undefined) return;
@@ -508,6 +421,13 @@ export function arnativeCompletions(prefix: string): AutocompleteItem[] | null {
508
421
  * fresh install lands on Arnative without ever overriding a choice someone made. */
509
422
  export const DEFAULT_THEME = "arnative";
510
423
 
424
+ /** A theme of this package's family: `arnative` itself or an `arnative-<variant>`. The
425
+ * generator (`themes/gen-themes.mjs`) ships only such names, so the name is the identity —
426
+ * pi may load them from the package dir or a user copy, and both answer to it. */
427
+ export function isArnativeThemeName(name: string): boolean {
428
+ return name === DEFAULT_THEME || name.startsWith(`${DEFAULT_THEME}-`);
429
+ }
430
+
511
431
  /** Should the shipped theme be installed? Only when no theme is set at all (pi would fall back
512
432
  * to `system`) and the theme actually loaded, which a headless or filtered load may not do. */
513
433
  export function shouldApplyDefaultTheme(
@@ -525,7 +445,7 @@ export default function (pi: ExtensionAPI) {
525
445
  ctx.ui.setTheme(DEFAULT_THEME);
526
446
  });
527
447
  pi.registerCommand("arnative", {
528
- description: "Arnative settings menu: themes, headers, footers, usage",
448
+ description: "Arnative settings menu: themes, headers, footers, providers, usage",
529
449
  getArgumentCompletions: arnativeCompletions,
530
450
  handler: arnativeHandler,
531
451
  });
@@ -538,14 +458,14 @@ if (isMain(import.meta.url)) {
538
458
  assert(markedLabels(["a"], undefined)[0] === " a", "markedLabels handles no active theme");
539
459
  const labels = menuRows(MENUS);
540
460
  assert(labels.length === MENUS.length, "menuRows one row per menu");
541
- assert(rowText(labels[0]!) === "Themes · list & apply themes (the /settings → Theme list)", "menu row text format");
542
- assert(labels[0]!.label === "Themes" && labels[0]!.note === "list & apply themes (the /settings → Theme list)", "menu row keeps label and note apart");
461
+ assert(rowText(labels[0]!) === "Themes · arnative themes only (all themes: /settings → Theme)", "menu row text format");
462
+ assert(labels[0]!.label === "Themes" && labels[0]!.note === "arnative themes only (all themes: /settings → Theme)", "menu row keeps label and note apart");
543
463
  assert(MENU_TITLE === "Settings - Arnative\u2819", `the menu title is the pinned string, got ${MENU_TITLE}`);
544
- assert(MENU_DESC === "Themes, headers, footers, animations, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
464
+ assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
545
465
  // Every menu row is reachable and the description names them all, so a new screen cannot
546
466
  // be added to MENUS and forgotten in the copy a user reads first.
547
- assert(MENUS.length === 5, "five settings screens");
548
- for (const label of ["Themes", "Headers", "Footers", "Animations", "Usage"]) {
467
+ assert(MENUS.length === 7, "seven settings screens");
468
+ for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
549
469
  assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
550
470
  }
551
471
  assert(/^Settings - Arnative/.test(MENU_TITLE), "title follows `<setting> - <extension>`");
@@ -558,11 +478,29 @@ if (isMain(import.meta.url)) {
558
478
  assert(arnativeCompletions("he")![0]!.value === "headers", "headers menu has completions");
559
479
  assert(arnativeCompletions("fo")![0]!.value === "footers", "footers menu has completions");
560
480
  assert(MENUS.some((m) => m.value === "footers"), "footers menu registered");
481
+ assert(arnativeCompletions("co")![0]!.value === "compact", "compact menu has completions");
482
+ assert(MENUS.some((m) => m.value === "compact"), "compact menu registered");
483
+
484
+ // The Auto-compact picker marks the saved choice with a green ✓ at the row's end.
485
+ const acRows = autoCompactRows("Smart");
486
+ assert(acRows[0]!.label === "Off" && acRows[1]!.label === "Smart", "labels stay clean — the marker is not part of the label");
487
+ assert(acRows[1]!.chosen === true && acRows[0]!.chosen !== true, "the ✓ follows the saved choice");
488
+ assert(acRows.every((r) => r.note!.length > 0), "every Auto-compact row carries its note");
489
+ assert(autoCompactRows("Off")[0]!.chosen === true, "the marker moves when the saved choice changes");
490
+ assert(arnativeCompletions("pr")![0]!.value === "providers", "providers menu has completions");
491
+ assert(MENUS.some((m) => m.value === "providers"), "providers menu registered");
561
492
  // Usage is reachable from /arnative even though it is a dashboard, not a setting.
562
493
  assert(MENUS.some((m) => m.value === "usage"), "usage menu registered");
563
494
  assert(arnativeCompletions("us")![0]!.value === "usage", "usage menu has completions");
564
495
  assert(typeof MENUS.find((m) => m.value === "usage")!.open === "function", "the usage row opens the dashboard");
565
496
 
497
+ // The /arnative picker lists the package's family only; everything else (system, dark,
498
+ // light, a theme of the user's own) stays in /settings → Theme.
499
+ assert(isArnativeThemeName("arnative"), "the default theme is family");
500
+ assert(isArnativeThemeName("arnative-sun"), "a variant is family");
501
+ for (const outsider of ["system", "dark", "light", "omarchy-system", "arnativeX", ""])
502
+ assert(!isArnativeThemeName(outsider), `${JSON.stringify(outsider)} is not family`);
503
+
566
504
  // The shipped theme is applied only when pi has no theme setting of its own.
567
505
  assert(shouldApplyDefaultTheme(undefined, [{ name: "arnative" }]), "an unset theme installs Arnative");
568
506
  assert(!shouldApplyDefaultTheme("arnative", [{ name: "arnative" }]), "an explicit Arnative setting is left alone");
@@ -599,8 +537,8 @@ if (isMain(import.meta.url)) {
599
537
 
600
538
  // `←` reports upward instead of closing on a screen with a parent, reverting the live
601
539
  // preview first; the root menu has nothing behind it and omits the key.
602
- assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Close", "menu legend pinned, and free of a dead back key");
603
- assert(!LIST_LEGEND_MOVE.includes("←"), "the root menu does not advertise ←");
540
+ assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "the root menu legend omits ←");
541
+ assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", "submenu legend advertises ← Back");
604
542
  assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [←] Back [Esc] Revert", "live legend pinned");
605
543
  let backs = 0;
606
544
  let backReverts = 0;
@@ -635,12 +573,15 @@ if (isMain(import.meta.url)) {
635
573
  done: () => {},
636
574
  cancel: () => { menuCancelled = true; },
637
575
  requestRender: () => {},
638
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false);
639
- const menuLines = mainPicker.render(60);
576
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
577
+ // 80 columns: the description names all seven screens (a tripwire — a screen added
578
+ // to MENUS must be added to the copy too), and that one-liner no longer fits 60.
579
+ const menuLines = mainPicker.render(80);
640
580
  assert(menuLines.some((l) => l.includes(MENU_TITLE)), "the main menu renders its title");
581
+ assert(menuLines.some((l) => l.includes("[Esc] Close") && !l.includes("←")), "the root menu legend renders without a back key");
641
582
  assert(menuLines.some((l) => l.includes(MENU_DESC)), "the main menu renders the description under the title");
642
583
  assert(menuLines.findIndex((l) => l.includes(MENU_TITLE)) < menuLines.findIndex((l) => l.includes(MENU_DESC)), "description sits below the title");
643
- assert(menuLines.every((l) => visibleWidth(l) === 60), "main menu lines fit the width");
584
+ assert(menuLines.every((l) => visibleWidth(l) === 80), "main menu lines fit the width");
644
585
  // The pinned /arnative layout: `→ Themes · note`, every `·` in one column (skill rule 10).
645
586
  const plainMenu = menuLines.map(stripAnsi);
646
587
  const row0 = menuLines.map(stripAnsi).find((l) => l.includes("→ Themes"))!;
@@ -648,7 +589,7 @@ if (isMain(import.meta.url)) {
648
589
  // not a literal run of spaces, so adding a wider screen cannot break the layout test.
649
590
  const widest = Math.max(...MENUS.map((m) => m.label.length));
650
591
  assert(
651
- row0.startsWith(`│ → ${"Themes".padEnd(widest)}${ROW_DIVIDER}list & apply themes`),
592
+ row0.startsWith(`│ → ${"Themes".padEnd(widest)}${ROW_DIVIDER}arnative themes only`),
652
593
  `menu row layout, got ${JSON.stringify(row0)}`,
653
594
  );
654
595
  assert(plainMenu.filter((l) => l.includes(ROW_DIVIDER)).every((l) => l.indexOf(ROW_DIVIDER) === row0.indexOf(ROW_DIVIDER)), "every divider sits in one column");
@@ -665,7 +606,7 @@ if (isMain(import.meta.url)) {
665
606
  revert: () => {},
666
607
  done: () => {},
667
608
  requestRender: () => {},
668
- }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_MOVE }, false);
609
+ }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
669
610
  const resumedRows = resumed.render(60).map(stripAnsi);
670
611
  assert(resumedRows.some((l) => l.startsWith("│ → Usage")), "the menu reopens on the row it was left on");
671
612
  assert(!resumedRows.some((l) => l.startsWith("│ → Themes")), "and not on the first row");
@@ -769,5 +710,54 @@ if (isMain(import.meta.url)) {
769
710
  mainPicker.handleInput("g");
770
711
  assert(gradientOn, "a screen without the hook ignores g");
771
712
 
713
+ // Multi-select (Providers → model list): Space toggles, `[x]` marks, the cursor still moves.
714
+ const picked: string[] = [];
715
+ const chosen = new Set<string>(["a"]);
716
+ const multiRows = nameRows(["a", "b", "c"]);
717
+ const multiPicker = new ListPicker(fakeTheme, multiRows, "a", {
718
+ preview: quiet,
719
+ revert: quiet,
720
+ done: quiet,
721
+ requestRender: quiet,
722
+ toggle: () => {
723
+ const label = multiRows[multiPicker.index]!.label;
724
+ if (chosen.has(label)) chosen.delete(label);
725
+ else chosen.add(label);
726
+ picked.push(label);
727
+ },
728
+ marked: (label) => chosen.has(label),
729
+ }, { title: screenTitle("Providers"), description: "pick models", legend: "[Space] Toggle" }, false);
730
+ const multiLines = multiPicker.render(50).map(stripAnsi);
731
+ assert(multiLines.some((l) => l.includes("→ [x] a")), "a checked row shows [x] behind the cursor");
732
+ assert(multiLines.some((l) => l.includes("[ ] b")), "unchecked rows show [ ]");
733
+ multiPicker.handleInput(" ");
734
+ assert(picked[0] === "a" && !chosen.has("a"), "Space toggles the row under the cursor");
735
+ multiPicker.handleInput("\x1b[B");
736
+ multiPicker.handleInput(" ");
737
+ assert(chosen.has("b"), "Space toggles the row the cursor moved to");
738
+ assert(multiPicker.render(50).map(stripAnsi).some((l) => l.includes("→ [x] b")), "the check follows the cursor");
739
+ mainPicker.handleInput(" ");
740
+ assert(chosen.has("b") && picked.length === 2, "a screen without the toggle hook ignores Space");
741
+
742
+ // Unhandled keys reach the screen's own switch (`press`), and no hook means no route.
743
+ let pressed: string[] = [];
744
+ const pressPicker = new ListPicker(fakeTheme, nameRows(["a", "b", "c"]), "a", {
745
+ preview: quiet,
746
+ revert: quiet,
747
+ done: quiet,
748
+ requestRender: quiet,
749
+ press: (keyData) => pressed.push(keyData),
750
+ }, { title: screenTitle("Providers"), description: "pick models", legend: "[a] API" }, false);
751
+ pressPicker.handleInput("a");
752
+ assert(pressed.length === 1 && pressed[0] === "a", "an unhandled key reaches the screen via press");
753
+ const routed = new ListPicker(fakeTheme, nameRows(["a"]), undefined, {
754
+ preview: quiet,
755
+ revert: quiet,
756
+ done: quiet,
757
+ requestRender: quiet,
758
+ });
759
+ routed.handleInput("a");
760
+ assert(pressed.length === 1, "a screen without press ignores stray letters");
761
+
772
762
  console.log("arnative.ts self-check OK");
773
763
  }