@bismawy/pi-arnative 0.7.0 → 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,20 @@
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
+
3
18
  ## [0.7.0] - 2026-10-24
4
19
 
5
20
  ### Added
package/README.md CHANGED
@@ -18,7 +18,7 @@ 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
22
 
23
23
  <details>
24
24
  <summary><b>Configuration & Presets</b></summary>
@@ -33,6 +33,14 @@ Configurable via `/arnative` → **Footers**:
33
33
  - `Arnative (Minimal)` (single collapsible head row; click or `ctrl+alt+m` to toggle)
34
34
  - `Pi (system)` (built-in footer)
35
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
+
36
44
  </details>
37
45
 
38
46
  ## Install
@@ -59,7 +67,7 @@ npm run dev
59
67
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
60
68
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
61
69
  | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
62
- | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Providers, Usage) |
70
+ | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, Providers, Usage) |
63
71
  | Click tool / `ctrl+o` | Toggle tool output box |
64
72
  | `←` | Back — step back from submenus/dashboard to menu |
65
73
 
@@ -91,6 +99,7 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
91
99
  | `extensions/section-headers.ts` | Tabbed header and resource box (preset: `/arnative headers`) |
92
100
  | `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
93
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) |
94
103
  | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
95
104
  | `extensions/arnative.ts` | Settings menu with live preview and navigation |
96
105
  | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
@@ -121,12 +130,16 @@ npm run preview # Live preview the working tree in your own Pi (stamps a pushabl
121
130
 
122
131
  Pre-publish verification and tag validation are enforced via `scripts/release-check.mjs`.
123
132
 
124
- **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
125
134
  carries no live-preview stamp, so a fix cannot reach GitHub unseen. `npm run preview`
126
135
  launches Pi with this working tree and writes `.git/arnative-preview` for the exact commit
127
136
  that was shown; editing `extensions/`, `lib/`, `themes/`, or `package.json` afterwards
128
137
  invalidates it and the hook asks for a fresh preview. The preview must run on a clean tree
129
- — 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
+ ```
130
143
 
131
144
  </details>
132
145
 
@@ -24,6 +24,7 @@ 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";
27
28
  import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
28
29
  import { openProviders } from "../lib/provider.ts";
29
30
  import { openUsage } from "./usage.ts";
@@ -44,7 +45,7 @@ export function menuRows(menus: Pick<ArnativeMenu, "label" | "description">[]):
44
45
  /** Title of the settings menu, derived from `screenTitle` so the format lives in one place. */
45
46
  export const MENU_TITLE = screenTitle("Settings");
46
47
  /** One-line description under the menu title. */
47
- export const MENU_DESC = "Themes, headers, footers, animations, providers, usage";
48
+ export const MENU_DESC = "Themes, headers, footers, animations, auto-compact, providers, usage";
48
49
 
49
50
  const THEMES_PICKER_TEXT: ListPickerText = {
50
51
  title: screenTitle("Themes"),
@@ -241,6 +242,71 @@ const openAnimations = async (ctx: ExtensionCommandContext): Promise<boolean | v
241
242
  return goBack === true;
242
243
  };
243
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
+
244
310
  export const MENUS: ArnativeMenu[] = [
245
311
  {
246
312
  value: "themes",
@@ -266,6 +332,12 @@ export const MENUS: ArnativeMenu[] = [
266
332
  description: "choose the working spinner",
267
333
  open: openAnimations,
268
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
+ },
269
341
  {
270
342
  value: "providers",
271
343
  label: "Providers",
@@ -389,11 +461,11 @@ if (isMain(import.meta.url)) {
389
461
  assert(rowText(labels[0]!) === "Themes · arnative themes only (all themes: /settings → Theme)", "menu row text format");
390
462
  assert(labels[0]!.label === "Themes" && labels[0]!.note === "arnative themes only (all themes: /settings → Theme)", "menu row keeps label and note apart");
391
463
  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}`);
464
+ assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
393
465
  // Every menu row is reachable and the description names them all, so a new screen cannot
394
466
  // 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"]) {
467
+ assert(MENUS.length === 7, "seven settings screens");
468
+ for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
397
469
  assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
398
470
  }
399
471
  assert(/^Settings - Arnative/.test(MENU_TITLE), "title follows `<setting> - <extension>`");
@@ -406,6 +478,15 @@ if (isMain(import.meta.url)) {
406
478
  assert(arnativeCompletions("he")![0]!.value === "headers", "headers menu has completions");
407
479
  assert(arnativeCompletions("fo")![0]!.value === "footers", "footers menu has completions");
408
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");
409
490
  assert(arnativeCompletions("pr")![0]!.value === "providers", "providers menu has completions");
410
491
  assert(MENUS.some((m) => m.value === "providers"), "providers menu registered");
411
492
  // Usage is reachable from /arnative even though it is a dashboard, not a setting.
@@ -493,12 +574,14 @@ if (isMain(import.meta.url)) {
493
574
  cancel: () => { menuCancelled = true; },
494
575
  requestRender: () => {},
495
576
  }, { title: MENU_TITLE, description: MENU_DESC, legend: LIST_LEGEND_ROOT }, false);
496
- const menuLines = mainPicker.render(60);
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);
497
580
  assert(menuLines.some((l) => l.includes(MENU_TITLE)), "the main menu renders its title");
498
581
  assert(menuLines.some((l) => l.includes("[Esc] Close") && !l.includes("←")), "the root menu legend renders without a back key");
499
582
  assert(menuLines.some((l) => l.includes(MENU_DESC)), "the main menu renders the description under the title");
500
583
  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");
584
+ assert(menuLines.every((l) => visibleWidth(l) === 80), "main menu lines fit the width");
502
585
  // The pinned /arnative layout: `→ Themes · note`, every `·` in one column (skill rule 10).
503
586
  const plainMenu = menuLines.map(stripAnsi);
504
587
  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");
@@ -78,10 +78,31 @@ export function formatTimeBadge(timeStr: string, th: { fg(color: string, text: s
78
78
  // \x1b[0m (full reset), so padding AFTER the reset loses the bubble bg and renders
79
79
  // dark for the rest of the line. Re-apply the bubble bg after every reset and close
80
80
  // it at end of line so it cannot leak. Same pattern as InputBgEditor below.
81
+ //
82
+ // The repair is pure per (line, bgOpen) pair, and pi's Markdown cache hands the render
83
+ // patch the SAME string references frame after frame — so a Map keyed by the source
84
+ // line turns every frame after the first into lookups instead of split/join rebuilds.
85
+ // Only the patched render closure calls this, so module-local state is correct even
86
+ // across /reload (the closure keeps this module instance alive). Reset when the bg
87
+ // code changes (theme switch); past the cap the whole map is dropped, because a
88
+ // session's user lines are far below it and correctness never depends on a hit.
89
+ const BUBBLE_BG_CACHE_MAX = 8192;
90
+ let bubbleBgOpen = "";
91
+ let bubbleBgCache = new Map<string, string>();
92
+
81
93
  export function repairBubbleBg(line: string, bgOpen: string): string {
82
94
  if (!bgOpen || (!line.includes("\x1b[0m") && !line.includes("\x1b[49m"))) return line;
95
+ if (bgOpen !== bubbleBgOpen) {
96
+ bubbleBgOpen = bgOpen;
97
+ bubbleBgCache = new Map();
98
+ }
99
+ const hit = bubbleBgCache.get(line);
100
+ if (hit !== undefined) return hit;
83
101
  const patched = line.split("\x1b[0m").join(`\x1b[0m${bgOpen}`).split("\x1b[49m").join(`\x1b[49m${bgOpen}`);
84
- return patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
102
+ const result = patched.endsWith(bgOpen) ? `${patched}\x1b[49m` : patched;
103
+ if (bubbleBgCache.size >= BUBBLE_BG_CACHE_MAX) bubbleBgCache.clear();
104
+ bubbleBgCache.set(line, result);
105
+ return result;
85
106
  }
86
107
 
87
108
  /**
@@ -249,6 +270,14 @@ if (isMain(import.meta.url)) {
249
270
  assert(clean.includes(`\x1b[0m${bg}`), "bg re-applied after the reset");
250
271
  assert(clean.endsWith("\x1b[49m"), "bubble bg closed at end of line");
251
272
  assert(repairBubbleBg("plain", "") === "plain", "no bgOpen: unchanged");
273
+
274
+ // memoized repair: a different bg code resets the cache, so nothing repairs
275
+ // against a stale bubble background after a theme switch
276
+ const dirty2 = `${bg}Second\x1b[0m pad \x1b[49m`;
277
+ const otherBg = "\x1b[48;2;1;2;3m";
278
+ assert(repairBubbleBg(dirty2, otherBg).includes(`\x1b[0m${otherBg}`), "a new bg code repairs against that bg");
279
+ assert(repairBubbleBg(dirty2, bg).includes(`\x1b[0m${bg}`), "and back to the previous bg after another reset");
280
+ assert(repairBubbleBg(dirty2, bg) === repairBubbleBg(dirty2, bg), "repeat repair stays stable");
252
281
  assert(ansiBgOpen(null, "userMessageBg") === "", "no theme: empty bgOpen");
253
282
  assert(
254
283
  ansiBgOpen({ bg: (_c, t) => `\x1b[48;2;52;53;61m${t}\x1b[49m` }, "userMessageBg") === "\x1b[48;2;52;53;61m",
@@ -1042,7 +1042,7 @@ if (isMain(import.meta.url)) {
1042
1042
  );
1043
1043
 
1044
1044
  // pi-fff override mode: find/grep re-registered with own renderers, no renderShell
1045
- const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in D:/Pi/x\x1b[39m"] };
1045
+ const fffCall = { render: () => ["\x1b[1mfind \x1b[22m\x1b[36m*.ts in /tmp/work\x1b[39m"] };
1046
1046
  const fffRes = { render: () => ["src/a.ts \x1b[2m... (6 more lines)\x1b[22m"] };
1047
1047
  const fffFind = { toolName: "find", toolDefinition: { renderCall: () => fffCall, renderResult: () => fffRes } };
1048
1048
  assert(
@@ -1053,10 +1053,10 @@ if (isMain(import.meta.url)) {
1053
1053
  { content: [{ type: "text", text: "src/a.ts\nsrc/b.ts" }] },
1054
1054
  { expanded: false, isPartial: false },
1055
1055
  th,
1056
- { args: { pattern: "*.ts", path: "D:/Pi/x" }, state: {} },
1056
+ { args: { pattern: "*.ts", path: "/tmp/work" }, state: {} },
1057
1057
  ).render(60);
1058
1058
  assert(fffOut[0].startsWith("╭") && fffOut[fffOut.length - 1].startsWith("╰"), "pi-fff find: result wrapped in a box");
1059
- assert(fffOut.some((l: string) => l.includes("*.ts in D:/Pi/x")), "pi-fff find: renderCall title goes in the box");
1059
+ assert(fffOut.some((l: string) => l.includes("*.ts in /tmp/work")), "pi-fff find: renderCall title goes in the box");
1060
1060
  assert(fffOut.some((l: string) => l.includes("6 more lines")), "pi-fff find: renderResult summary goes in the box");
1061
1061
 
1062
1062
  // pi-fff default mode (`ffgrep`/`fffind`): same renderer shape, different names.