@bismawy/pi-arnative 0.7.0 → 0.8.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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.0] - 2026-10-26
4
+
5
+ ### Added
6
+ - **Model heal keeps `models.json` correct with no command (adopted from pi-auto-compat).** On `session_start`, `model_select`, a change to `models.json` (debounced watcher) and an assistant error that names a rejected parameter, three passes run on the rules the provider wizard already uses: flags (missing compat flags and a default `thinkingLevelMap`, offline), meta (`contextWindow`/`maxTokens` from each channel's `GET /models`, 6 h TTL, unit anomalies rejected, caps clamped to the window) and effort (the `reasoning_effort` levels a relay accepts, remapped to the nearest accepted one, 24 h TTL). Each pass is one read-modify-write that writes only real differences: an explicit value (even `false`) is never overwritten, a hand-edited network value stays manual, a user-shaped map is never probed, a corrupt file is reported and never rewritten, and the first write keeps a backup. Channel-wide flags land at provider level; extension-owned providers are fixed through `modelOverrides`. `/arnative` → **Model heal** picks `Full` (default), `Flags` (offline only) or `Off`; `/model-heal` forces every pass now, and `/auto-compat` stays as an alias once pi-auto-compat is uninstalled. While pi-auto-compat is still installed, pi-arnative defers to it and says so once, so two healers never write the same file. State lives in `<agent>/arnative/model-heal.json` (`lib/model-heal.ts`, `extensions/model-heal.ts`).
7
+ - **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`).
8
+ - **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`.
9
+ - **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`).
10
+ - **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.
11
+
12
+ ### Changed
13
+ - **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`).
14
+
15
+ ### Fixed
16
+ - **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).
17
+ - **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`).
18
+
3
19
  ## [0.7.0] - 2026-10-24
4
20
 
5
21
  ### Added
package/README.md CHANGED
@@ -18,7 +18,8 @@ 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`. 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), or delete.
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.
22
23
 
23
24
  <details>
24
25
  <summary><b>Configuration & Presets</b></summary>
@@ -33,6 +34,22 @@ Configurable via `/arnative` → **Footers**:
33
34
  - `Arnative (Minimal)` (single collapsible head row; click or `ctrl+alt+m` to toggle)
34
35
  - `Pi (system)` (built-in footer)
35
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.
52
+
36
53
  </details>
37
54
 
38
55
  ## Install
@@ -59,7 +76,8 @@ npm run dev
59
76
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
60
77
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
61
78
  | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
62
- | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Providers, Usage) |
79
+ | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Model heal, Providers, Usage) |
80
+ | `/model-heal` | Heal `models.json` now (or `/arnative` → **Model heal**) |
63
81
  | Click tool / `ctrl+o` | Toggle tool output box |
64
82
  | `←` | Back — step back from submenus/dashboard to menu |
65
83
 
@@ -91,6 +109,9 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
91
109
  | `extensions/section-headers.ts` | Tabbed header and resource box (preset: `/arnative headers`) |
92
110
  | `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
93
111
  | `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
112
+ | `extensions/autocompact.ts` | Auto-compact: Smart tiers by window or a fixed token budget (`/arnative` → Auto-compact) |
113
+ | `extensions/model-heal.ts` | Model heal triggers: session start, model select, `models.json` watcher, rejected-parameter errors, `/model-heal` |
114
+ | `lib/model-heal.ts` | Model heal passes: compat flags, `/models` limits sync, effort probe |
94
115
  | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
95
116
  | `extensions/arnative.ts` | Settings menu with live preview and navigation |
96
117
  | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
@@ -121,12 +142,16 @@ npm run preview # Live preview the working tree in your own Pi (stamps a pushabl
121
142
 
122
143
  Pre-publish verification and tag validation are enforced via `scripts/release-check.mjs`.
123
144
 
124
- **Local-first push gate:** the global pre-push hook rejects any branch push whose commit
145
+ **Local-first push gate:** the pre-push hook (`.githooks/pre-push`) rejects any branch push whose commit
125
146
  carries no live-preview stamp, so a fix cannot reach GitHub unseen. `npm run preview`
126
147
  launches Pi with this working tree and writes `.git/arnative-preview` for the exact commit
127
148
  that was shown; editing `extensions/`, `lib/`, `themes/`, or `package.json` afterwards
128
149
  invalidates it and the hook asks for a fresh preview. The preview must run on a clean tree
129
- — commit or stash first.
150
+ — commit or stash first. Git does not auto-install hooks; activate per clone:
151
+
152
+ ```bash
153
+ git config core.hooksPath .githooks
154
+ ```
130
155
 
131
156
  </details>
132
157
 
@@ -24,6 +24,9 @@ import {
24
24
  } from "./animations.ts";
25
25
  import { FOOTER_PRESETS, activeFooterPreset, setFooterPreset, type FooterPreset } from "./footer.ts";
26
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 { healNow } from "./model-heal.ts";
29
+ import { MODEL_HEAL_CHOICES, activeModelHeal, setModelHeal, type ModelHealChoice } from "../lib/model-heal.ts";
27
30
  import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
28
31
  import { openProviders } from "../lib/provider.ts";
29
32
  import { openUsage } from "./usage.ts";
@@ -44,7 +47,7 @@ export function menuRows(menus: Pick<ArnativeMenu, "label" | "description">[]):
44
47
  /** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
45
48
  export const MENU_TITLE = screenTitle("Settings");
46
49
  /** One-line description under the menu title. */
47
- export const MENU_DESC = "Themes, headers, footers, animations, providers, usage";
50
+ export const MENU_DESC = "Themes, headers, footers, animations, auto-compact, providers, usage";
48
51
 
49
52
  const THEMES_PICKER_TEXT: ListPickerText = {
50
53
  title: screenTitle("Themes"),
@@ -241,6 +244,140 @@ const openAnimations = async (ctx: ExtensionCommandContext): Promise<boolean | v
241
244
  return goBack === true;
242
245
  };
243
246
 
247
+ const AUTOCOMPACT_PICKER_TEXT: ListPickerText = {
248
+ title: screenTitle("Auto-compact"),
249
+ description: "Smart tiers the trigger by context window; manual budgets fire at one absolute size.",
250
+ legend: LIST_LEGEND_MOVE,
251
+ };
252
+
253
+ /** One note per row: Smart states its tier table, a manual budget its window-independence. */
254
+ const AUTO_COMPACT_NOTES: Record<AutoCompactChoice, string> = {
255
+ Off: "never — pi's own compaction stays in charge",
256
+ Smart: "by window: 1M→20% · 512k→40% · 256k→80% · <192k→pi core",
257
+ "100k": "always above 100k tokens, any window",
258
+ "150k": "always above 150k tokens, any window",
259
+ "200k": "always above 200k tokens, any window",
260
+ "300k": "always above 300k tokens, any window",
261
+ "400k": "always above 400k tokens, any window",
262
+ };
263
+
264
+ /** Rows for the Auto-compact picker: the saved choice ends its row with a green ✓. */
265
+ export function autoCompactRows(opened: AutoCompactChoice): ListRow[] {
266
+ return AUTO_COMPACT_CHOICES.map((c) => ({ label: c, note: AUTO_COMPACT_NOTES[c], chosen: c === opened }));
267
+ }
268
+
269
+ /** A plain (non-live) picker: the choice is committed by Enter, nothing previews. The
270
+ * trigger itself lives in `extensions/autocompact.ts` and fires on the next settle. */
271
+ const openAutoCompact = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
272
+ const opened = activeAutoCompact();
273
+
274
+ if (ctx.mode !== "tui") {
275
+ // No custom components (RPC/headless): fall back to the blocking picker.
276
+ const labels = AUTO_COMPACT_CHOICES.map((c) => (c === opened ? `${c} ✓` : c));
277
+ const pick = await ctx.ui.select(AUTOCOMPACT_PICKER_TEXT.title, labels);
278
+ if (pick === undefined) return;
279
+ setAutoCompact(AUTO_COMPACT_CHOICES[labels.indexOf(pick)]!);
280
+ ctx.ui.notify(
281
+ `[arnative] Auto-compact: ${pick === "Off" ? "off" : pick === "Smart" ? "smart (tiered by context window)" : `above ${pick} tokens of context`}`,
282
+ "info",
283
+ );
284
+ return;
285
+ }
286
+
287
+ const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
288
+ const picker = new ListPicker(
289
+ theme,
290
+ autoCompactRows(opened),
291
+ opened,
292
+ {
293
+ preview: () => {},
294
+ revert: () => {},
295
+ done: () => {
296
+ setAutoCompact(AUTO_COMPACT_CHOICES[picker.index]!);
297
+ done(false);
298
+ },
299
+ cancel: () => done(false),
300
+ back: () => done(true),
301
+ requestRender: () => tui.requestRender(),
302
+ },
303
+ AUTOCOMPACT_PICKER_TEXT,
304
+ false,
305
+ ctx.thinkingLevel,
306
+ );
307
+ return picker;
308
+ });
309
+ return goBack === true;
310
+ };
311
+
312
+ const MODEL_HEAL_PICKER_TEXT: ListPickerText = {
313
+ title: screenTitle("Model heal"),
314
+ description: "Keeps models.json correct on its own: session start, model switch, file change, rejected parameter.",
315
+ legend: LIST_LEGEND_MOVE,
316
+ };
317
+
318
+ const MODEL_HEAL_RUN_NOW = "Run now";
319
+
320
+ const MODEL_HEAL_NOTES: Record<ModelHealChoice, string> = {
321
+ Full: "flags + limits from /models + probed thinking levels",
322
+ Flags: "offline compat flags only, no network",
323
+ Off: "never touch models.json",
324
+ };
325
+
326
+ /** Rows for the Model heal picker: the saved mode ends its row with a green check; the
327
+ * last row is an action, never a saved choice. */
328
+ export function modelHealRows(opened: ModelHealChoice): ListRow[] {
329
+ return [
330
+ ...MODEL_HEAL_CHOICES.map((c) => ({ label: c, note: MODEL_HEAL_NOTES[c], chosen: c === opened })),
331
+ { label: MODEL_HEAL_RUN_NOW, note: "heal every channel now, ignoring the 6h/24h TTLs" },
332
+ ];
333
+ }
334
+
335
+ const openModelHeal = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
336
+ const opened = activeModelHeal();
337
+
338
+ if (ctx.mode !== "tui") {
339
+ const labels = [...MODEL_HEAL_CHOICES, MODEL_HEAL_RUN_NOW].map((c) => (c === opened ? c + " ✓" : c));
340
+ const pick = await ctx.ui.select(MODEL_HEAL_PICKER_TEXT.title, labels);
341
+ if (pick === undefined) return;
342
+ const index = labels.indexOf(pick);
343
+ if (index === MODEL_HEAL_CHOICES.length) {
344
+ await healNow(ctx);
345
+ return;
346
+ }
347
+ setModelHeal(MODEL_HEAL_CHOICES[index]!);
348
+ ctx.ui.notify("[arnative] Model heal: " + MODEL_HEAL_CHOICES[index]!, "info");
349
+ return;
350
+ }
351
+
352
+ let runNow = false;
353
+ const goBack = await ctx.ui.custom<boolean>((tui, theme, _kb, done) => {
354
+ const picker = new ListPicker(
355
+ theme,
356
+ modelHealRows(opened),
357
+ opened,
358
+ {
359
+ preview: () => {},
360
+ revert: () => {},
361
+ done: () => {
362
+ if (picker.index === MODEL_HEAL_CHOICES.length) runNow = true;
363
+ else setModelHeal(MODEL_HEAL_CHOICES[picker.index]!);
364
+ done(false);
365
+ },
366
+ cancel: () => done(false),
367
+ back: () => done(true),
368
+ requestRender: () => tui.requestRender(),
369
+ },
370
+ MODEL_HEAL_PICKER_TEXT,
371
+ false,
372
+ ctx.thinkingLevel,
373
+ );
374
+ return picker;
375
+ });
376
+ // After the picker closed: the run notifies, and a notice under an open overlay is lost.
377
+ if (runNow) await healNow(ctx);
378
+ return goBack === true;
379
+ };
380
+
244
381
  export const MENUS: ArnativeMenu[] = [
245
382
  {
246
383
  value: "themes",
@@ -266,6 +403,18 @@ export const MENUS: ArnativeMenu[] = [
266
403
  description: "choose the working spinner",
267
404
  open: openAnimations,
268
405
  },
406
+ {
407
+ value: "compact",
408
+ label: "Auto-compact",
409
+ description: "smart by window or a fixed token budget (off by default)",
410
+ open: openAutoCompact,
411
+ },
412
+ {
413
+ value: "heal",
414
+ label: "Model heal",
415
+ description: "auto-fix models.json: compat flags, limits, thinking levels (on by default)",
416
+ open: openModelHeal,
417
+ },
269
418
  {
270
419
  value: "providers",
271
420
  label: "Providers",
@@ -389,11 +538,18 @@ if (isMain(import.meta.url)) {
389
538
  assert(rowText(labels[0]!) === "Themes · arnative themes only (all themes: /settings → Theme)", "menu row text format");
390
539
  assert(labels[0]!.label === "Themes" && labels[0]!.note === "arnative themes only (all themes: /settings → Theme)", "menu row keeps label and note apart");
391
540
  assert(MENU_TITLE === "Settings - Arnative\u2819", `the menu title is the pinned string, got ${MENU_TITLE}`);
392
- assert(MENU_DESC === "Themes, headers, footers, animations, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
541
+ assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
393
542
  // Every menu row is reachable and the description names them all, so a new screen cannot
394
543
  // be added to MENUS and forgotten in the copy a user reads first.
395
- assert(MENUS.length === 6, "six settings screens");
396
- for (const label of ["Themes", "Headers", "Footers", "Animations", "Providers", "Usage"]) {
544
+ assert(MENUS.length === 8, "eight settings screens");
545
+ {
546
+ const values = MENUS.map((m) => m.value);
547
+ assert(values.indexOf("heal") === values.indexOf("compact") + 1, "Model heal row sits right after Auto-compact");
548
+ const heal = modelHealRows("Flags");
549
+ assert(heal.map((r) => r.label).join(",") === "Full,Flags,Off,Run now", "Model heal rows: three modes then Run now");
550
+ assert(heal.filter((r) => r.chosen).map((r) => r.label).join(",") === "Flags", "Model heal marks only the saved mode");
551
+ }
552
+ for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
397
553
  assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
398
554
  }
399
555
  assert(/^Settings - Arnative/.test(MENU_TITLE), "title follows `<setting> - <extension>`");
@@ -406,6 +562,15 @@ if (isMain(import.meta.url)) {
406
562
  assert(arnativeCompletions("he")![0]!.value === "headers", "headers menu has completions");
407
563
  assert(arnativeCompletions("fo")![0]!.value === "footers", "footers menu has completions");
408
564
  assert(MENUS.some((m) => m.value === "footers"), "footers menu registered");
565
+ assert(arnativeCompletions("co")![0]!.value === "compact", "compact menu has completions");
566
+ assert(MENUS.some((m) => m.value === "compact"), "compact menu registered");
567
+
568
+ // The Auto-compact picker marks the saved choice with a green ✓ at the row's end.
569
+ const acRows = autoCompactRows("Smart");
570
+ assert(acRows[0]!.label === "Off" && acRows[1]!.label === "Smart", "labels stay clean — the marker is not part of the label");
571
+ assert(acRows[1]!.chosen === true && acRows[0]!.chosen !== true, "the ✓ follows the saved choice");
572
+ assert(acRows.every((r) => r.note!.length > 0), "every Auto-compact row carries its note");
573
+ assert(autoCompactRows("Off")[0]!.chosen === true, "the marker moves when the saved choice changes");
409
574
  assert(arnativeCompletions("pr")![0]!.value === "providers", "providers menu has completions");
410
575
  assert(MENUS.some((m) => m.value === "providers"), "providers menu registered");
411
576
  // Usage is reachable from /arnative even though it is a dashboard, not a setting.
@@ -493,12 +658,14 @@ if (isMain(import.meta.url)) {
493
658
  cancel: () => { menuCancelled = true; },
494
659
  requestRender: () => {},
495
660
  }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
496
- const menuLines = mainPicker.render(60);
661
+ // 80 columns: the description names all seven screens (a tripwire — a screen added
662
+ // to MENUS must be added to the copy too), and that one-liner no longer fits 60.
663
+ const menuLines = mainPicker.render(80);
497
664
  assert(menuLines.some((l) => l.includes(MENU_TITLE)), "the main menu renders its title");
498
665
  assert(menuLines.some((l) => l.includes("[Esc] Close") && !l.includes("←")), "the root menu legend renders without a back key");
499
666
  assert(menuLines.some((l) => l.includes(MENU_DESC)), "the main menu renders the description under the title");
500
667
  assert(menuLines.findIndex((l) => l.includes(MENU_TITLE)) < menuLines.findIndex((l) => l.includes(MENU_DESC)), "description sits below the title");
501
- assert(menuLines.every((l) => visibleWidth(l) === 60), "main menu lines fit the width");
668
+ assert(menuLines.every((l) => visibleWidth(l) === 80), "main menu lines fit the width");
502
669
  // The pinned /arnative layout: `→ Themes · note`, every `·` in one column (skill rule 10).
503
670
  const plainMenu = menuLines.map(stripAnsi);
504
671
  const row0 = menuLines.map(stripAnsi).find((l) => l.includes("→ Themes"))!;
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Auto-compact — keep long sessions light without the manual /compact.
3
+ *
4
+ * Why: pi renders the whole transcript on every frame, so the drag a user feels tracks
5
+ * the ABSOLUTE size of the session, not how full the window is. A 1M-window model gets
6
+ * heavy around 200k tokens (a fifth of its window), while a 128k model can run to
7
+ * nearly 100% and let pi's own threshold compaction handle it safely.
8
+ *
9
+ * Two shapes of control, both off until picked in `/arnative` → Auto-compact:
10
+ * - **Smart** maps the context window through a tier table (≥768k→20%, ≥384k→40%,
11
+ * ≥192k→80%, smaller→defer to pi core). Every tier lands the trigger near the same
12
+ * ~200k-token transcript ceiling, and small windows never fire at all — pi's own
13
+ * `compaction.reserveTokens` compaction stays their safety net.
14
+ * - **A manual token budget** (100k–400k) fires at the same absolute size whatever the
15
+ * window, for users who want one number.
16
+ *
17
+ * The trigger is `agent_before_settle` (idle, nothing queued) and fires pi's compaction
18
+ * through `ctx.compact()` — the same machinery and summary as /compact, never mid-run.
19
+ * Pi's own `compaction.reserveTokens` threshold, including per-model overrides, is
20
+ * unaffected; whichever fires first wins.
21
+ */
22
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
23
+ import { mkdtempSync, rmSync } from "node:fs";
24
+ import { tmpdir } from "node:os";
25
+ import { join } from "node:path";
26
+ import { assert, isMain } from "../lib/check.ts";
27
+ import { loadChoice, resetPresetCache, saveChoice } from "../lib/preset-store.ts";
28
+
29
+ /** Stored exactly as the picker shows them; `Off` disables the trigger entirely. */
30
+ export const AUTO_COMPACT_CHOICES = ["Off", "Smart", "100k", "150k", "200k", "300k", "400k"] as const;
31
+ export type AutoCompactChoice = (typeof AUTO_COMPACT_CHOICES)[number];
32
+ export const DEFAULT_AUTO_COMPACT: AutoCompactChoice = "Off";
33
+ const AUTO_COMPACT_KEY = "autoCompact";
34
+
35
+ /** Smart's tier table, first match wins. `null` defers the window to pi's own
36
+ * compaction — the "100%" tier, where the current behavior is already safe. */
37
+ const SMART_TIERS: ReadonlyArray<{ minWindow: number; percent: number | null }> = [
38
+ { minWindow: 786432, percent: 20 }, // ≥768k: a 1M window triggers at ~200k tokens
39
+ { minWindow: 393216, percent: 40 }, // 384k–768k: a 512k window triggers at ~205k
40
+ { minWindow: 196608, percent: 80 }, // 192k–384k: a 256k window triggers at ~205k
41
+ { minWindow: 0, percent: null }, // below 192k (128k models): pi core stays in charge
42
+ ];
43
+
44
+ /** The Smart percent for a context window, or null when the window defers to pi core. */
45
+ export function smartPercent(contextWindow: number): number | null {
46
+ const tier = SMART_TIERS.find((t) => contextWindow >= t.minWindow);
47
+ return tier?.percent ?? null;
48
+ }
49
+
50
+ // Active choice on globalThis so the `/arnative` picker (a second module instance, see
51
+ // animations.ts) and this module's event handlers agree without sharing memo caches.
52
+ const AUTO_COMPACT_CONFIG_KEY = Symbol.for("pi-arnative.autoCompact");
53
+
54
+ export function activeAutoCompact(): AutoCompactChoice {
55
+ const stored =
56
+ (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] ??
57
+ loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES);
58
+ return AUTO_COMPACT_CHOICES.includes(stored as AutoCompactChoice) ? (stored as AutoCompactChoice) : DEFAULT_AUTO_COMPACT;
59
+ }
60
+
61
+ /** The trigger threshold in context tokens for the given window, or null when the
62
+ * choice is off or Smart defers this window to pi's own compaction. */
63
+ export function activeAutoCompactThreshold(contextWindow: number): number | null {
64
+ const choice = activeAutoCompact();
65
+ if (choice === "Off") return null;
66
+ if (choice === "Smart") {
67
+ const percent = smartPercent(contextWindow);
68
+ return percent === null ? null : Math.round((contextWindow * percent) / 100);
69
+ }
70
+ return Number.parseInt(choice, 10) * 1000;
71
+ }
72
+
73
+ /** Pick a choice and persist it (the `/arnative` → Auto-compact rows call this). */
74
+ export function setAutoCompact(choice: AutoCompactChoice): void {
75
+ (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY] = choice;
76
+ saveChoice(AUTO_COMPACT_KEY, choice);
77
+ }
78
+
79
+ /** Session-scoped trigger state. Module-local: only this module's registrar mutates it. */
80
+ export interface AutoCompactState {
81
+ /** A compaction this module triggered has not finished yet. */
82
+ inFlight: boolean;
83
+ /** Context tokens at the last trigger; null once usage really dropped under the threshold. */
84
+ lastAttemptTokens: number | null;
85
+ /** The last triggered compaction finished, so its effect on usage is visible. */
86
+ attemptSettled: boolean;
87
+ /** Do not trigger while usage stays below this (failure backoff, anti-flap). */
88
+ blockedUntilTokens: number;
89
+ }
90
+
91
+ export function freshAutoCompactState(): AutoCompactState {
92
+ return { inFlight: false, lastAttemptTokens: null, attemptSettled: false, blockedUntilTokens: 0 };
93
+ }
94
+
95
+ /** How much usage must outgrow a previous attempt before it counts as real growth
96
+ * (5% of the threshold, at least 5k tokens). */
97
+ export function growthMargin(thresholdTokens: number): number {
98
+ return Math.max(5000, Math.round(thresholdTokens * 0.05));
99
+ }
100
+
101
+ /** Pure decision for the settle handler: fire pi's compaction now, or wait. */
102
+ export function autoCompactDecision(
103
+ state: AutoCompactState,
104
+ tokens: number | null,
105
+ thresholdTokens: number,
106
+ ): "compact" | "wait" {
107
+ if (tokens === null || tokens < thresholdTokens) return "wait";
108
+ if (state.inFlight) return "wait";
109
+ if (tokens < state.blockedUntilTokens) return "wait";
110
+ // A finished compaction that still left usage at or above the threshold freed too
111
+ // little: wait for real growth instead of re-summarizing every settle.
112
+ if (state.attemptSettled && state.lastAttemptTokens !== null && tokens < state.lastAttemptTokens + growthMargin(thresholdTokens)) {
113
+ return "wait";
114
+ }
115
+ return "compact";
116
+ }
117
+
118
+ /** Usage dropped back under the threshold (the handler's below-threshold branch).
119
+ * A shallow dip — still within the growth margin of the last attempt — keeps the
120
+ * attempt memory, so usage oscillating right at the threshold cannot re-summarize
121
+ * every turn. A real drop forgets the attempt and re-arms the trigger fully. */
122
+ export function rearmAfterDip(state: AutoCompactState, tokens: number, thresholdTokens: number): void {
123
+ if (state.lastAttemptTokens === null || tokens < state.lastAttemptTokens - growthMargin(thresholdTokens)) {
124
+ state.lastAttemptTokens = null;
125
+ state.attemptSettled = false;
126
+ state.blockedUntilTokens = 0;
127
+ }
128
+ }
129
+
130
+ export default function registerAutoCompact(pi: ExtensionAPI): void {
131
+ const state = freshAutoCompactState();
132
+
133
+ pi.on("session_start", async () => {
134
+ // Fresh session (or /reload): backoff and attempt state belonged to the previous branch.
135
+ Object.assign(state, freshAutoCompactState());
136
+ });
137
+
138
+ pi.on("agent_before_settle", async (_event, ctx) => {
139
+ const usage = typeof ctx.getContextUsage === "function" ? ctx.getContextUsage() : undefined;
140
+ const window = usage?.contextWindow;
141
+ if (typeof window !== "number" || window <= 0) return;
142
+ const threshold = activeAutoCompactThreshold(window);
143
+ if (threshold === null) return;
144
+ const tokens = usage.tokens ?? null;
145
+ if (tokens === null) return;
146
+ if (tokens < threshold) {
147
+ rearmAfterDip(state, tokens, threshold);
148
+ return;
149
+ }
150
+ if (autoCompactDecision(state, tokens, threshold) !== "compact") return;
151
+ if (typeof ctx.compact !== "function") return; // older host without the API
152
+ state.inFlight = true;
153
+ state.attemptSettled = false;
154
+ state.lastAttemptTokens = tokens;
155
+ state.blockedUntilTokens = tokens + 1; // anti-flap: re-fire only past this attempt
156
+ ctx.compact();
157
+ });
158
+
159
+ pi.on("session_compact", async () => {
160
+ // Also fires for pi's own compactions; harmless — the flags only matter after a trigger.
161
+ state.inFlight = false;
162
+ state.attemptSettled = true;
163
+ });
164
+
165
+ pi.on("session_compact_failed", async () => {
166
+ if (!state.inFlight) return;
167
+ // A failed (or user-aborted) compaction must not retry-loop at the same usage:
168
+ // wait until usage outgrows the attempt by the growth margin.
169
+ state.inFlight = false;
170
+ state.attemptSettled = true;
171
+ state.blockedUntilTokens = (state.lastAttemptTokens ?? 0) + growthMargin(state.lastAttemptTokens ?? 200000);
172
+ });
173
+ }
174
+
175
+ // Self-check: `node extensions/autocompact.ts`
176
+ if (isMain(import.meta.url)) {
177
+ // The real agent dir must not decide pass/fail, and the test must not touch it.
178
+ const fixture = mkdtempSync(join(tmpdir(), "arnative-autocompact-"));
179
+ process.env.PI_CODING_AGENT_DIR = fixture;
180
+ delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
181
+
182
+ // Choice parsing and persistence.
183
+ assert(activeAutoCompact() === "Off", "the default is off");
184
+ assert(activeAutoCompactThreshold(1_048_576) === null, "off reads as no threshold");
185
+ setAutoCompact("200k");
186
+ assert(activeAutoCompactThreshold(131072) === 200000, "a manual budget ignores the window");
187
+ assert(loadChoice(AUTO_COMPACT_KEY, AUTO_COMPACT_CHOICES) === "200k", "the choice survives a restart (read from disk)");
188
+
189
+ // Smart's tier table: the field examples land where they were asked to.
190
+ assert(smartPercent(131072) === null, "128k defers to pi core (the 100% tier)");
191
+ assert(smartPercent(196607) === null, "just under the 192k tier edge still defers");
192
+ assert(smartPercent(196608) === 80, "the 192k tier edge takes 80%");
193
+ assert(smartPercent(262144) === 80, "256k takes 80%");
194
+ assert(smartPercent(524288) === 40, "512k takes 40%");
195
+ assert(smartPercent(1048576) === 20, "1M takes 20%");
196
+ setAutoCompact("Smart");
197
+ assert(activeAutoCompactThreshold(1048576) === 209715, "Smart on 1M triggers at ~200k tokens");
198
+ assert(activeAutoCompactThreshold(262144) === 209715, "Smart on 256k triggers at ~205k tokens");
199
+ assert(activeAutoCompactThreshold(131072) === null, "Smart on 128k defers to pi core");
200
+ setAutoCompact("Off");
201
+ assert(activeAutoCompactThreshold(1048576) === null, "switching back to off disables the trigger");
202
+
203
+ // Decision table.
204
+ const s = freshAutoCompactState();
205
+ assert(autoCompactDecision(s, null, 200000) === "wait", "no usage estimate: wait");
206
+ assert(autoCompactDecision(s, 199999, 200000) === "wait", "below the threshold: wait");
207
+ assert(autoCompactDecision(s, 200000, 200000) === "compact", "at the threshold with fresh state: compact");
208
+ s.inFlight = true;
209
+ assert(autoCompactDecision(s, 250000, 200000) === "wait", "a compaction is still running: wait");
210
+ s.inFlight = false;
211
+ s.blockedUntilTokens = 260000;
212
+ assert(autoCompactDecision(s, 250000, 200000) === "wait", "below the failure backoff: wait");
213
+ s.blockedUntilTokens = 0;
214
+ s.attemptSettled = true;
215
+ s.lastAttemptTokens = 240000;
216
+ assert(autoCompactDecision(s, 245000, 200000) === "wait", "a settled attempt that freed too little waits for the growth margin");
217
+ assert(autoCompactDecision(s, 250500, 200000) === "compact", "usage outgrew the settled attempt: compact again");
218
+
219
+ // Rearm after a dip: shallow keeps the attempt memory, deep forgets it.
220
+ const r = freshAutoCompactState();
221
+ r.lastAttemptTokens = 200000;
222
+ r.attemptSettled = true;
223
+ r.blockedUntilTokens = 200001;
224
+ rearmAfterDip(r, 195000, 200000);
225
+ assert(r.lastAttemptTokens === 200000, "a shallow dip keeps the attempt memory");
226
+ rearmAfterDip(r, 189000, 200000);
227
+ assert(r.lastAttemptTokens === null && r.attemptSettled === false && r.blockedUntilTokens === 0, "a real drop forgets the attempt and re-arms");
228
+
229
+ // Registered handlers against a fake pi, driven like a Smart session on a 1M model.
230
+ setAutoCompact("Smart");
231
+ const handlers: Record<string, (event: unknown, ctx: unknown) => unknown> = {};
232
+ registerAutoCompact({ on: (name: string, fn: (event: unknown, ctx: unknown) => unknown) => void (handlers[name] = fn) } as never);
233
+ const compactCalls: number[] = [];
234
+ const ctxOf = (tokens: number | null, contextWindow = 1_048_576) => ({
235
+ getContextUsage: () => ({ tokens, contextWindow, percent: tokens === null ? null : (tokens / contextWindow) * 100 }),
236
+ compact: () => compactCalls.push(tokens ?? -1),
237
+ });
238
+
239
+ await handlers.session_start!({}, undefined);
240
+ await handlers.agent_before_settle!({}, ctxOf(210000));
241
+ assert(compactCalls.length === 1 && compactCalls[0] === 210000, "usage at/above the threshold triggers pi's compaction");
242
+ await handlers.agent_before_settle!({}, ctxOf(215000));
243
+ assert(compactCalls.length === 1, "the anti-flap guard blocks an immediate re-trigger");
244
+ await handlers.session_compact!({}, undefined);
245
+ await handlers.agent_before_settle!({}, ctxOf(215000));
246
+ assert(compactCalls.length === 1, "a settled attempt that still sits above the threshold waits for growth");
247
+ await handlers.agent_before_settle!({}, ctxOf(222000));
248
+ assert(compactCalls.length === 2 && compactCalls[1] === 222000, "usage outgrowing the attempt compacts again");
249
+ await handlers.session_compact!({}, undefined); // the compaction that made usage drop
250
+ await handlers.agent_before_settle!({}, ctxOf(60000));
251
+ assert(compactCalls.length === 2, "below the threshold nothing fires");
252
+ await handlers.agent_before_settle!({}, ctxOf(210500));
253
+ assert(compactCalls.length === 3 && compactCalls[2] === 210500, "the next crossing starts a fresh cycle");
254
+
255
+ // Oscillation at the threshold: one compaction per growth margin, not every turn.
256
+ await handlers.session_compact!({}, undefined);
257
+ await handlers.agent_before_settle!({}, ctxOf(208000)); // shallow dip under the threshold
258
+ await handlers.agent_before_settle!({}, ctxOf(211000));
259
+ assert(compactCalls.length === 3, "an oscillation at the threshold does not re-summarize every turn");
260
+ await handlers.agent_before_settle!({}, ctxOf(222000));
261
+ assert(compactCalls.length === 4 && compactCalls[3] === 222000, "real growth past the attempt compacts again");
262
+
263
+ // A failed compaction backs off; session_start clears the backoff for a fresh session.
264
+ await handlers.session_compact_failed!({}, undefined);
265
+ await handlers.agent_before_settle!({}, ctxOf(225000));
266
+ assert(compactCalls.length === 4, "after a failure the backoff holds below attempt + margin");
267
+ await handlers.agent_before_settle!({}, ctxOf(234000));
268
+ assert(compactCalls.length === 5, "and gives way once usage outgrows the failed attempt");
269
+ await handlers.session_compact_failed!({}, undefined);
270
+ await handlers.session_start!({}, undefined);
271
+ await handlers.agent_before_settle!({}, ctxOf(210500));
272
+ assert(compactCalls.length === 6, "a fresh session clears the backoff");
273
+
274
+ // The 128k case from the field: Smart defers the whole window to pi's own
275
+ // compaction — no percent, however close to full, ever fires ours.
276
+ await handlers.session_start!({}, undefined);
277
+ await handlers.agent_before_settle!({}, ctxOf(130000, 131072));
278
+ assert(compactCalls.length === 6, "a 128k window under Smart never triggers: pi core stays in charge");
279
+
280
+ // Older hosts: missing ctx APIs must degrade to a no-op, not throw.
281
+ await handlers.agent_before_settle!({}, { getContextUsage: () => undefined });
282
+ assert(compactCalls.length === 6, "no usage estimate: no trigger");
283
+ // Reset inFlight first, so the missing compact() — not a pending compaction — is what stops it.
284
+ await handlers.session_start!({}, undefined);
285
+ await handlers.agent_before_settle!({}, { getContextUsage: () => ({ tokens: 400000, contextWindow: 1_048_576, percent: 40 }) });
286
+ assert(compactCalls.length === 6, "no ctx.compact on the host: no trigger");
287
+
288
+ // Restore: the next module load starts from the real agent dir and the stored default.
289
+ rmSync(fixture, { recursive: true, force: true });
290
+ delete process.env.PI_CODING_AGENT_DIR;
291
+ delete (globalThis as Record<symbol, unknown>)[AUTO_COMPACT_CONFIG_KEY];
292
+ resetPresetCache();
293
+ console.log("autocompact.ts self-check OK");
294
+ }
@@ -599,7 +599,7 @@ function parseOptimizer(raw: string | undefined): string | null {
599
599
  }
600
600
 
601
601
  // Pi's own per-message usage: shown when pi-cache-optimizer has no adapter for the
602
- // provider (a custom one like hark.ts publishes no pi-cache-stats status).
602
+ // provider (a custom one like mytool.ts publishes no pi-cache-stats status).
603
603
  let usageTotals = { inp: 0, read: 0 };
604
604
  export function piCacheHit(): string | null {
605
605
  const total = usageTotals.inp + usageTotals.read;
@@ -1265,8 +1265,8 @@ export default function (pi: ExtensionAPI) {
1265
1265
 
1266
1266
  // Self-check: `node extensions/footer.ts`
1267
1267
  if (isMain(import.meta.url)) {
1268
- assert(shortenCwd("/run/media/bisma/DATA/Pi/pi-arnative") === "\u2026/Pi/pi-arnative", "cwd inside -> last 2 segments");
1269
- assert(shortenCwd("/home/bisma") === "/home/bisma", "shallow cwd left unchanged");
1268
+ assert(shortenCwd("/run/media/dev/DATA/work/app") === "\u2026/work/app", "cwd inside -> last 2 segments");
1269
+ assert(shortenCwd("/home/dev") === "/home/dev", "shallow cwd left unchanged");
1270
1270
  assert(shortenCwd("D:\\Pi\\a\\pi-arnative") === "D:/\u2026/a/pi-arnative", "long Windows path: drive kept");
1271
1271
  assert(shortenCwd("D:\\Pi\\pi-arnative") === "D:\\Pi\\pi-arnative", "shallow Windows path left unchanged");
1272
1272
  assert(shortenCwd("/a/x/y/z") === "\u2026/y/z", "long path -> tail");