@bismawy/pi-arnative 0.8.0-rc.1 → 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,8 +1,9 @@
1
1
  # Changelog
2
2
 
3
- ## [0.8.0-rc.1] - 2026-10-25
3
+ ## [0.8.0] - 2026-10-26
4
4
 
5
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`).
6
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`).
7
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`.
8
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`).
package/README.md CHANGED
@@ -19,6 +19,7 @@ pi-arnative replaces pi’s default terminal chrome with a unified, cohesive vis
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
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>
@@ -41,6 +42,14 @@ When the context crosses the chosen threshold after a run settles, pi's own comp
41
42
 
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.
43
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
+
44
53
  </details>
45
54
 
46
55
  ## Install
@@ -67,7 +76,8 @@ npm run dev
67
76
  | `ctrl+alt+n` · `alt+n` | New session (`/new`) |
68
77
  | `ctrl+alt+m` · `alt+m` | Toggle Minimal footer |
69
78
  | `/usage` | Token & cost dashboard (or `/arnative` → **Usage**) |
70
- | `/arnative` | Settings menu (Themes, Headers, Footers, Animations, Auto-compact, 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**) |
71
81
  | Click tool / `ctrl+o` | Toggle tool output box |
72
82
  | `←` | Back — step back from submenus/dashboard to menu |
73
83
 
@@ -100,6 +110,8 @@ To bind `app.session.new` in `~/.pi/agent/keybindings.json`:
100
110
  | `extensions/footer.ts` | 3-row status grid footer and boxed editor (preset: `/arnative footers`) |
101
111
  | `extensions/animations.ts` | Working spinner presets and `/arnative` → Animations picker |
102
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 |
103
115
  | `lib/spinner.ts` | Spinner preset catalog: frames, cadence, and painters |
104
116
  | `extensions/arnative.ts` | Settings menu with live preview and navigation |
105
117
  | `lib/provider.ts` | Custom provider wizard: probe, model pick, edit actions, `models.json`/`auth.json` save |
@@ -25,6 +25,8 @@ import {
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
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";
28
30
  import { LIST_LEGEND_LIVE, LIST_LEGEND_MOVE, LIST_LEGEND_ROOT, ListPicker, nameRows, rowText, type ListPickerText, type ListRow } from "../lib/list-picker.ts";
29
31
  import { openProviders } from "../lib/provider.ts";
30
32
  import { openUsage } from "./usage.ts";
@@ -307,6 +309,75 @@ const openAutoCompact = async (ctx: ExtensionCommandContext): Promise<boolean |
307
309
  return goBack === true;
308
310
  };
309
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
+
310
381
  export const MENUS: ArnativeMenu[] = [
311
382
  {
312
383
  value: "themes",
@@ -338,6 +409,12 @@ export const MENUS: ArnativeMenu[] = [
338
409
  description: "smart by window or a fixed token budget (off by default)",
339
410
  open: openAutoCompact,
340
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
+ },
341
418
  {
342
419
  value: "providers",
343
420
  label: "Providers",
@@ -464,7 +541,14 @@ if (isMain(import.meta.url)) {
464
541
  assert(MENU_DESC === "Themes, headers, footers, animations, auto-compact, providers, usage", `the menu description is the pinned string, got ${MENU_DESC}`);
465
542
  // Every menu row is reachable and the description names them all, so a new screen cannot
466
543
  // be added to MENUS and forgotten in the copy a user reads first.
467
- assert(MENUS.length === 7, "seven settings screens");
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
+ }
468
552
  for (const label of ["Themes", "Headers", "Footers", "Animations", "Auto-compact", "Providers", "Usage"]) {
469
553
  assert(MENUS.some((m) => m.label === label), `MENUS carries the ${label} screen`);
470
554
  }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Model heal trigger: runs the passes in lib/model-heal.ts with no command.
3
+
4
+ * Triggers: session_start, model_select, a change to models.json (debounced watcher), and an
5
+ * assistant error that names a rejected parameter (pi's auto-retry would otherwise burn its
6
+ * attempts on the same bad effort level). /model-heal forces every pass now, ignoring TTLs.
7
+
8
+ * Mode (/arnative -> Model heal): Full = flags + network passes, Flags = offline flags
9
+ * only, Off = nothing. While pi-auto-compat is installed this module defers to it and says so
10
+ * once, so two healers never write models.json at the same time.
11
+ */
12
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
13
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
14
+ import { type FSWatcher, watch } from "node:fs";
15
+ import { join } from "node:path";
16
+ import { assert, isMain } from "../lib/check.ts";
17
+ import { REJECTION_RE } from "../lib/compat.ts";
18
+ import { activeModelHeal, autoCompatInstalled, healEffort, healFlags, healMeta, type HealDeps, type HealResult, type ModelHealChoice, type RtModel } from "../lib/model-heal.ts";
19
+
20
+ interface RegistryLike {
21
+ getAll?: () => unknown[];
22
+ refresh?: (options?: { allowNetwork?: boolean }) => Promise<unknown>;
23
+ getRegisteredProviderConfig?: (provider: string) => unknown;
24
+ }
25
+
26
+ interface AssistantMessage {
27
+ role?: string;
28
+ provider?: string;
29
+ model?: string;
30
+ errorMessage?: string;
31
+ }
32
+
33
+ const DEBOUNCE_MS = 800;
34
+ const WIDGET_MS = 10_000;
35
+
36
+ const registryOf = (ctx: unknown): RegistryLike | undefined => (ctx as { modelRegistry?: RegistryLike } | undefined)?.modelRegistry;
37
+
38
+ /** The session's view of the registry, in the shape the passes take. An extension that
39
+ * supplies its own model list owns it: only modelOverrides reaches the merged model. */
40
+ export function depsFor(ctx: unknown): HealDeps {
41
+ const registry = registryOf(ctx);
42
+ return {
43
+ models: () => (registry?.getAll?.() ?? []).filter((m): m is RtModel => !!m && typeof m === "object"),
44
+ ownsModels: (provider) => {
45
+ try {
46
+ const cfg = registry?.getRegisteredProviderConfig?.(provider) as { models?: unknown; refreshModels?: unknown } | undefined;
47
+ return !!cfg && typeof cfg === "object" && (Array.isArray(cfg.models) || typeof cfg.refreshModels === "function");
48
+ } catch {
49
+ return false;
50
+ }
51
+ },
52
+ };
53
+ }
54
+
55
+ /** Only a parameter rejection says the level on the wire is wrong; auth, quota and
56
+ * transport errors cost no probe. */
57
+ export function isRejectedParam(message: AssistantMessage | undefined): boolean {
58
+ if (!message || message.role !== "assistant" || !message.provider || !message.model) return false;
59
+ return REJECTION_RE.test(message.errorMessage ?? "");
60
+ }
61
+
62
+ /** Whether a pass may run: Off runs nothing, Flags runs only the offline flags pass, Full runs
63
+ * everything, and an installed pi-auto-compat owns models.json in every mode. */
64
+ export function healAllowed(need: "Flags" | "Full", mode: ModelHealChoice, autoCompat: boolean): boolean {
65
+ if (autoCompat || mode === "Off") return false;
66
+ return need === "Flags" || mode === "Full";
67
+ }
68
+
69
+ /** The one-time hand-over notice: only when heal is wanted and pi-auto-compat holds the file. */
70
+ export const deferNotice = (mode: ModelHealChoice, autoCompat: boolean): boolean => mode !== "Off" && autoCompat;
71
+
72
+ export default function registerModelHeal(pi: ExtensionAPI): void {
73
+ let watcher: FSWatcher | undefined;
74
+ let timer: ReturnType<typeof setTimeout> | undefined;
75
+ let widgetTimer: ReturnType<typeof setTimeout> | undefined;
76
+ let deferNoticeShown = false;
77
+
78
+ // ctx getters throw once the session was replaced or reloaded, and deferred callbacks
79
+ // (timer, watcher, network passes) can outlive it: capture ui while live, guard dismissal.
80
+ function notify(ctx: ExtensionContext, lines: string[]): void {
81
+ let ui: ExtensionContext["ui"] | undefined;
82
+ try {
83
+ ui = ctx.ui;
84
+ ui?.setWidget?.("model-heal", lines.map((line) => "model-heal: " + line));
85
+ } catch {
86
+ return;
87
+ }
88
+ if (widgetTimer) clearTimeout(widgetTimer);
89
+ widgetTimer = setTimeout(() => {
90
+ widgetTimer = undefined;
91
+ try {
92
+ ui?.setWidget?.("model-heal", undefined);
93
+ } catch {
94
+ // session replaced while the widget was up
95
+ }
96
+ }, WIDGET_MS);
97
+ }
98
+
99
+ async function apply(ctx: ExtensionContext, label: string, result: HealResult): Promise<void> {
100
+ if (!result.changed) return;
101
+ let refreshed = true;
102
+ try {
103
+ await registryOf(ctx)?.refresh?.({ allowNetwork: false });
104
+ } catch {
105
+ refreshed = false;
106
+ }
107
+ notify(ctx, [label + " (" + result.detail.length + " change(s))" + (refreshed ? "" : " - run /reload to load it")]);
108
+ }
109
+
110
+ const enabled = (need: "Flags" | "Full"): boolean => healAllowed(need, activeModelHeal(), autoCompatInstalled());
111
+
112
+ function runFlags(ctx: ExtensionContext, only?: RtModel[]): void {
113
+ if (!enabled("Flags")) return;
114
+ try {
115
+ const result = healFlags(depsFor(ctx), only, ctx.model as RtModel | undefined);
116
+ void apply(ctx, "flags healed", result).catch(() => undefined);
117
+ } catch {
118
+ // stale ctx: the next session_start runs the pass again
119
+ }
120
+ }
121
+
122
+ function runNetwork(ctx: ExtensionContext, force: boolean): void {
123
+ if (!enabled("Full")) return;
124
+ let deps: HealDeps;
125
+ try {
126
+ deps = depsFor(ctx);
127
+ } catch {
128
+ return;
129
+ }
130
+ void healMeta(deps, force).then((r) => apply(ctx, "limits synced", r)).catch(() => undefined);
131
+ void healEffort(deps, force).then((r) => apply(ctx, "thinking levels probed", r)).catch(() => undefined);
132
+ }
133
+
134
+ function stopWatcher(): void {
135
+ if (timer) clearTimeout(timer);
136
+ timer = undefined;
137
+ try {
138
+ watcher?.close();
139
+ } catch {
140
+ // already closed
141
+ }
142
+ watcher = undefined;
143
+ }
144
+
145
+ function startWatcher(ctx: ExtensionContext): void {
146
+ stopWatcher();
147
+ try {
148
+ // A pass's own write fires this too; the re-run finds nothing to change.
149
+ watcher = watch(join(getAgentDir(), "models.json"), { persistent: false }, () => {
150
+ if (timer) clearTimeout(timer);
151
+ timer = setTimeout(() => {
152
+ timer = undefined;
153
+ runFlags(ctx);
154
+ }, DEBOUNCE_MS);
155
+ });
156
+ } catch {
157
+ // models.json missing or not watchable
158
+ }
159
+ }
160
+
161
+ pi.on("session_start", (_event, ctx) => {
162
+ stopWatcher();
163
+ if (deferNotice(activeModelHeal(), autoCompatInstalled())) {
164
+ if (!deferNoticeShown) notify(ctx, ["pi-auto-compat is installed, so it heals models.json. Uninstall it to hand over to pi-arnative."]);
165
+ deferNoticeShown = true;
166
+ return;
167
+ }
168
+ runFlags(ctx);
169
+ if (enabled("Flags")) startWatcher(ctx);
170
+ runNetwork(ctx, false);
171
+ });
172
+
173
+ pi.on("model_select", (event, ctx) => {
174
+ const model = (event as { model?: RtModel } | undefined)?.model;
175
+ runFlags(ctx, model ? [model] : undefined);
176
+ runNetwork(ctx, false); // TTL-gated: network only when a channel is stale
177
+ });
178
+
179
+ pi.on("message_end", (event, ctx) => {
180
+ const message = (event as { message?: AssistantMessage } | undefined)?.message;
181
+ if (!isRejectedParam(message) || !enabled("Full")) return;
182
+ try {
183
+ const deps = depsFor(ctx);
184
+ const target = deps.models().find((m) => m.provider.toLowerCase() === message!.provider!.toLowerCase() && m.id === message!.model);
185
+ if (!target) return;
186
+ void healEffort(deps, true, [target]).then((r) => apply(ctx, "thinking levels re-probed", r)).catch(() => undefined);
187
+ } catch {
188
+ // stale ctx
189
+ }
190
+ });
191
+
192
+ pi.on("session_shutdown", () => {
193
+ stopWatcher();
194
+ if (widgetTimer) clearTimeout(widgetTimer);
195
+ widgetTimer = undefined;
196
+ });
197
+
198
+ registerCommands(pi, (_args, ctx) => healNow(ctx));
199
+ }
200
+
201
+ /** Every pass now, ignoring TTLs: the /model-heal command and the /arnative Run now row. */
202
+ export async function healNow(ctx: ExtensionContext): Promise<void> {
203
+ if (autoCompatInstalled()) {
204
+ ctx.ui.notify("[arnative] pi-auto-compat is installed and heals models.json. Run /auto-compat, or uninstall it to use model heal.", "warning");
205
+ return;
206
+ }
207
+ const deps = depsFor(ctx);
208
+ const flags = healFlags(deps, undefined, ctx.model as RtModel | undefined);
209
+ const meta = await healMeta(deps, true);
210
+ const effort = await healEffort(deps, true);
211
+ const detail = [...flags.detail, ...meta.detail, ...effort.detail];
212
+ const errors = [...flags.errors, ...meta.errors, ...effort.errors];
213
+ if (detail.length > 0) {
214
+ await registryOf(ctx)?.refresh?.({ allowNetwork: false }).catch(() => undefined);
215
+ ctx.ui.notify("[arnative] Model heal fixed:\n - " + detail.join("\n - "), "info");
216
+ return;
217
+ }
218
+ ctx.ui.notify(
219
+ errors.length ? "[arnative] Model heal: nothing to fix; " + errors.length + " endpoint(s) unreachable: " + errors.join("; ") : "[arnative] Model heal: nothing to fix.",
220
+ errors.length ? "warning" : "info",
221
+ );
222
+ }
223
+
224
+ function registerCommands(pi: ExtensionAPI, runNow: (args: string, ctx: ExtensionContext) => Promise<void>): void {
225
+ const description = "Heal models.json now: compat flags, contextWindow/maxTokens from each /models, accepted thinking efforts";
226
+ pi.registerCommand("model-heal", { description, handler: runNow });
227
+ // Migration alias: keeps the old habit working once pi-auto-compat is uninstalled.
228
+ if (!autoCompatInstalled()) pi.registerCommand("auto-compat", { description: description + " (alias of /model-heal)", handler: runNow });
229
+ }
230
+
231
+ if (isMain(import.meta.url)) {
232
+ assert(isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "400 invalid reasoning_effort" }), "a rejected effort triggers a re-probe");
233
+ assert(!isRejectedParam({ role: "assistant", provider: "r", model: "m", errorMessage: "401 unauthorized" }), "an auth failure costs no probe");
234
+ assert(!isRejectedParam({ role: "user", provider: "r", model: "m", errorMessage: "bad request" }), "only assistant messages count");
235
+ assert(!isRejectedParam(undefined), "no message, no probe");
236
+ assert(healAllowed("Flags", "Full", false) && healAllowed("Full", "Full", false), "Full runs every pass");
237
+ assert(healAllowed("Flags", "Flags", false) && !healAllowed("Full", "Flags", false), "Flags runs only the offline pass");
238
+ assert(!healAllowed("Flags", "Off", false) && !healAllowed("Full", "Off", false), "Off runs nothing");
239
+ assert(!healAllowed("Flags", "Full", true) && !healAllowed("Flags", "Flags", true), "an installed pi-auto-compat owns the file");
240
+ assert(deferNotice("Full", true) && deferNotice("Flags", true), "the hand-over notice shows while heal is wanted");
241
+ assert(!deferNotice("Off", true) && !deferNotice("Full", false), "and stays quiet when Off or nothing to defer to");
242
+ const owned = depsFor({ modelRegistry: { getAll: () => [{ provider: "x", id: "a" }, null], getRegisteredProviderConfig: (p: string) => (p === "ext" ? { refreshModels: () => [] } : undefined) } });
243
+ assert(owned.models().length === 1, "non-object registry entries are dropped");
244
+ assert(owned.ownsModels("ext") && !owned.ownsModels("x"), "an extension list with refreshModels owns its models");
245
+ const throwing = depsFor({ modelRegistry: { getRegisteredProviderConfig: () => { throw new Error("stale"); } } });
246
+ assert(!throwing.ownsModels("x") && throwing.models().length === 0, "a stale registry reads as empty");
247
+ console.log("model-heal extension self-check OK");
248
+ }
package/lib/compat.ts CHANGED
@@ -197,7 +197,7 @@ const PROBE_TOKENS = 16;
197
197
  const RETRY_PAUSE_MS = 1000;
198
198
  // Only a parameter rejection indicts the level. Auth, quota and transport errors say
199
199
  // nothing, and marking a level accepted without an answer would be a lie.
200
- const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
200
+ export const REJECTION_RE = /provider.?error|invalid.?request|http 400|400[.:]|reasoning.?effort|thinking|unsupported|not supported|invalid (?:value|option|parameter|enum)|bad request/i;
201
201
 
202
202
  /** A reasoning model on a relay that expects `reasoning_effort` and does not publish its
203
203
  * own level support — the only case a probe can fix. */
@@ -0,0 +1,640 @@
1
+ /**
2
+ * Model heal: keep models.json correct without a command. Adopted from pi-auto-compat and
3
+ * built on the rules in compat.ts (the same rules the provider wizard writes).
4
+ *
5
+ * Three passes, each a single synchronous read-modify-write of models.json so two passes
6
+ * can never interleave:
7
+ * flags - compat flags + a default thinkingLevelMap (offline, cheap, every trigger)
8
+ * meta - contextWindow / maxTokens from each channel's GET /models (TTL-gated)
9
+ * effort - the reasoning_effort levels a relay accepts -> thinkingLevelMap (TTL-gated)
10
+ *
11
+ * A pass writes only a value that differs from what is stored, so a repeated trigger is a
12
+ * no-op and an explicit user value (even `false`) is never overwritten: suggestCompat only
13
+ * returns keys the merged model leaves undefined, and a network value the user has since
14
+ * edited is remembered as manual and left alone.
15
+ */
16
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
17
+ import { execSync } from "node:child_process";
18
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { dirname, join } from "node:path";
21
+ import { assert, isMain } from "./check.ts";
22
+ import {
23
+ buildEffortMap,
24
+ carriesRemap,
25
+ contextWindowAccepted,
26
+ isEffortProbeable,
27
+ parseModelMeta,
28
+ probeEffort,
29
+ suggestCompat,
30
+ type Compat,
31
+ type CompatModel,
32
+ type ModelMeta,
33
+ } from "./compat.ts";
34
+ import { loadChoice, saveChoice } from "./preset-store.ts";
35
+ import { loadModelsConfig, looseJsonParse, readAuthKey, saveModelsConfig } from "./provider.ts";
36
+
37
+ // ------------------------------------------------------------- setting
38
+
39
+ export const MODEL_HEAL_CHOICES = ["Full", "Flags", "Off"] as const;
40
+ export type ModelHealChoice = (typeof MODEL_HEAL_CHOICES)[number];
41
+ export const MODEL_HEAL_KEY = "modelHeal";
42
+ export const DEFAULT_MODEL_HEAL: ModelHealChoice = "Full";
43
+
44
+ export const activeModelHeal = (): ModelHealChoice => loadChoice(MODEL_HEAL_KEY, MODEL_HEAL_CHOICES) ?? DEFAULT_MODEL_HEAL;
45
+ export const setModelHeal = (choice: ModelHealChoice): void => saveChoice(MODEL_HEAL_KEY, choice);
46
+
47
+ /** pi-auto-compat writes the same file; two healers would double every backup and probe. */
48
+ export function autoCompatInstalled(): boolean {
49
+ try {
50
+ const settings = looseJsonParse(readFileSync(join(getAgentDir(), "settings.json"), "utf8")) as { packages?: unknown };
51
+ if (!Array.isArray(settings?.packages)) return false;
52
+ return settings.packages.some((p) => String(typeof p === "string" ? p : ((p as { source?: unknown })?.source ?? "")).includes("pi-auto-compat"));
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ // --------------------------------------------------------------- types
59
+
60
+ export type RtModel = CompatModel & { provider: string; id: string; thinkingLevelMap?: unknown };
61
+ type Obj = Record<string, unknown>;
62
+
63
+ /** What a pass needs from the running session; injected so the self-check runs offline. */
64
+ export interface HealDeps {
65
+ /** Merged registry models (models.json + built-ins + extension providers). */
66
+ models: () => RtModel[];
67
+ /** True when an extension supplies the provider's model list: pi applies that list after
68
+ * models.json, so only `modelOverrides` reaches the merged model. */
69
+ ownsModels: (provider: string) => boolean;
70
+ fetchImpl?: typeof fetch;
71
+ }
72
+
73
+ export interface HealResult {
74
+ changed: boolean;
75
+ detail: string[];
76
+ errors: string[];
77
+ }
78
+
79
+ const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v);
80
+ const lower = (v: unknown): string => String(v ?? "").toLowerCase();
81
+ const modelKey = (provider: string, id: string): string => `${lower(provider)}\0${id}`;
82
+ const none = (): HealResult => ({ changed: false, detail: [], errors: [] });
83
+ const errText = (error: unknown): string => (error instanceof Error ? error.message : String(error));
84
+
85
+ /** The map a reasoning model gets when it declares none: pi's four named efforts as-is. */
86
+ export const DEFAULT_THINKING_MAP = { low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
87
+
88
+ const HOUR_MS = 60 * 60 * 1000;
89
+ const META_TTL_MS = 6 * HOUR_MS;
90
+ const META_TIMEOUT_MS = 8000;
91
+ const META_MAX_BYTES = 2 * 1024 * 1024;
92
+ const EFFORT_TTL_MS = 24 * HOUR_MS;
93
+ const EFFORT_FAILURE_TTL_MS = HOUR_MS;
94
+ const EFFORT_BUDGET_MS = 2 * 60 * 1000;
95
+
96
+ function groupByProvider(models: RtModel[]): Map<string, RtModel[]> {
97
+ const out = new Map<string, RtModel[]>();
98
+ for (const m of models) {
99
+ if (!m?.provider || !m.id) continue;
100
+ const list = out.get(lower(m.provider)) ?? [];
101
+ list.push(m);
102
+ out.set(lower(m.provider), list);
103
+ }
104
+ return out;
105
+ }
106
+
107
+ // ------------------------------------------------------------ models.json
108
+
109
+ let backedUp = false;
110
+
111
+ /** Read, mutate, write once. A corrupt models.json throws in the read and is never
112
+ * rewritten; the first write keeps one backup of the original file, never replaced later. */
113
+ function edit(mutate: (cfg: Obj) => string[]): HealResult {
114
+ let cfg: unknown;
115
+ try {
116
+ cfg = loadModelsConfig();
117
+ } catch (error) {
118
+ return { changed: false, detail: [], errors: [`models.json unreadable, not touched: ${errText(error)}`] };
119
+ }
120
+ if (!isObj(cfg)) return none();
121
+ if (!isObj(cfg.providers)) cfg.providers = {};
122
+ const detail = mutate(cfg);
123
+ if (detail.length === 0) return none();
124
+ try {
125
+ const path = join(getAgentDir(), "models.json");
126
+ if (!backedUp && existsSync(path)) {
127
+ if (!existsSync(`${path}.bak-model-heal`)) copyFileSync(path, `${path}.bak-model-heal`);
128
+ backedUp = true;
129
+ }
130
+ saveModelsConfig(cfg);
131
+ } catch (error) {
132
+ return { changed: false, detail: [], errors: [`write failed: ${errText(error)}`] };
133
+ }
134
+ return { changed: true, detail, errors: [] };
135
+ }
136
+
137
+ const providersOf = (cfg: Obj): Record<string, Obj> => cfg.providers as Record<string, Obj>;
138
+
139
+ function providerEntry(cfg: Obj, provider: string): Obj {
140
+ const providers = providersOf(cfg);
141
+ if (!isObj(providers[provider])) providers[provider] = {};
142
+ return providers[provider]!;
143
+ }
144
+
145
+ const modelEntryOf = (entry: Obj, id: string): Obj | undefined =>
146
+ Array.isArray(entry.models) ? (entry.models as unknown[]).find((m): m is Obj => isObj(m) && String(m.id) === id) : undefined;
147
+
148
+ /** The layer a per-model value lands in: the stated models[] entry, else modelOverrides. */
149
+ function modelSlot(entry: Obj, id: string, owned: boolean): { slot: Obj; label: string } {
150
+ const stated = owned ? undefined : modelEntryOf(entry, id);
151
+ if (stated) return { slot: stated, label: `models[${id}]` };
152
+ if (!isObj(entry.modelOverrides)) entry.modelOverrides = {};
153
+ const overrides = entry.modelOverrides as Record<string, Obj>;
154
+ if (!isObj(overrides[id])) overrides[id] = {};
155
+ return { slot: overrides[id]!, label: `modelOverrides[${id}]` };
156
+ }
157
+
158
+ /** Assign the keys that differ; returns the ones written. */
159
+ function assignCompat(holder: Obj, values: Compat): string[] {
160
+ const compat = isObj(holder.compat) ? holder.compat : {};
161
+ const written = Object.keys(values).filter((k) => compat[k] !== values[k]);
162
+ if (written.length === 0) return written;
163
+ for (const k of written) compat[k] = values[k];
164
+ holder.compat = compat;
165
+ return written;
166
+ }
167
+
168
+ // ---------------------------------------------------------- pass: flags
169
+
170
+ /** The models a flags pass looks at: every model of a provider the user declared (or an
171
+ * extension owns), plus the active one - never an entry for each unused built-in. */
172
+ function flagTargets(deps: HealDeps, cfg: Obj, active?: RtModel): RtModel[] {
173
+ const declared = new Set(Object.keys(providersOf(cfg)).map(lower));
174
+ const seen = new Set<string>();
175
+ const out: RtModel[] = [];
176
+ for (const m of [...deps.models(), ...(active ? [active] : [])]) {
177
+ if (!m?.provider || !m.id || seen.has(modelKey(m.provider, m.id))) continue;
178
+ if (m !== active && !declared.has(lower(m.provider)) && !deps.ownsModels(m.provider)) continue;
179
+ seen.add(modelKey(m.provider, m.id));
180
+ out.push(m);
181
+ }
182
+ return out;
183
+ }
184
+
185
+ /**
186
+ * Compat flags + default thinking maps. A flag goes to provider level only when every
187
+ * sibling would get the identical value (or already has it) and no model layer states the
188
+ * key, so a mixed provider (Claude next to GPT on one relay) keeps per-model flags with no
189
+ * per-key rule list to maintain.
190
+ */
191
+ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): HealResult {
192
+ return edit((cfg) => {
193
+ const detail: string[] = [];
194
+ for (const [provider, entry] of Object.entries(providersOf(cfg))) {
195
+ if (!isObj(entry) || !Array.isArray(entry.models)) continue;
196
+ for (const m of entry.models) {
197
+ if (!isObj(m) || m.reasoning !== true) continue;
198
+ if (isObj(m.thinkingLevelMap) && Object.keys(m.thinkingLevelMap).length > 0) continue;
199
+ m.thinkingLevelMap = { ...DEFAULT_THINKING_MAP };
200
+ detail.push(`${provider} models[${String(m.id)}]: thinkingLevelMap`);
201
+ }
202
+ }
203
+
204
+ const siblingsOf = groupByProvider(deps.models());
205
+ for (const m of only ?? flagTargets(deps, cfg, active)) {
206
+ const suggestion = suggestCompat(m);
207
+ if (Object.keys(suggestion).length === 0) continue;
208
+ const owned = deps.ownsModels(m.provider);
209
+ const entry = providerEntry(cfg, m.provider);
210
+ const stated = owned ? undefined : modelEntryOf(entry, m.id);
211
+ const override = isObj(entry.modelOverrides) ? (entry.modelOverrides as Obj)[m.id] : undefined;
212
+ const modelLayer = { ...(isObj(override) && isObj(override.compat) ? override.compat : {}), ...(stated && isObj(stated.compat) ? stated.compat : {}) };
213
+ const siblings = siblingsOf.get(lower(m.provider)) ?? [m];
214
+
215
+ const shared: Compat = {};
216
+ const own: Compat = {};
217
+ for (const [k, v] of Object.entries(suggestion)) {
218
+ const fitsAll = siblings.every((s) => s.id === m.id || suggestCompat(s)[k] === v || s.compat?.[k] === v);
219
+ if (!owned && !(k in modelLayer) && fitsAll) shared[k] = v;
220
+ else own[k] = v;
221
+ }
222
+ const atProvider = assignCompat(entry, shared);
223
+ if (atProvider.length) detail.push(`${m.provider}: compat += ${atProvider.join(", ")}`);
224
+ if (Object.keys(own).length) {
225
+ const { slot, label } = modelSlot(entry, m.id, owned);
226
+ const atModel = assignCompat(slot, own);
227
+ if (atModel.length) detail.push(`${m.provider} ${label}: compat += ${atModel.join(", ")}`);
228
+ }
229
+ }
230
+ return detail;
231
+ });
232
+ }
233
+
234
+ // ---------------------------------------------------------------- state
235
+
236
+ interface HealState {
237
+ schema: 1;
238
+ providers: Record<string, { signature: string; fetchedAt: number }>;
239
+ sources: Record<string, { contextWindow?: number; maxTokens?: number; at: number }>;
240
+ efforts: Record<string, { at: number; map: Record<string, string | null>; failed?: boolean }>;
241
+ }
242
+
243
+ const statePath = (): string => join(getAgentDir(), "arnative", "model-heal.json");
244
+ // pi-auto-compat's state has the same schema; seeding from it keeps its provenance, so a
245
+ // value the user edited by hand under the old package stays manual after the switch.
246
+ const legacyStatePath = (): string => join(getAgentDir(), "pi-auto-compat-sync.json");
247
+
248
+ function loadState(): HealState {
249
+ for (const path of [statePath(), legacyStatePath()]) {
250
+ try {
251
+ const raw = JSON.parse(readFileSync(path, "utf8")) as Partial<HealState>;
252
+ if (raw?.schema === 1) return { schema: 1, providers: raw.providers ?? {}, sources: raw.sources ?? {}, efforts: raw.efforts ?? {} };
253
+ } catch {
254
+ // absent or unreadable: try the next, then start clean
255
+ }
256
+ }
257
+ return { schema: 1, providers: {}, sources: {}, efforts: {} };
258
+ }
259
+
260
+ /** Writes only the sections a pass owns, merged onto a fresh read: meta and effort run
261
+ * concurrently, and a whole-object save from one would drop the other's stamps. */
262
+ function saveState(part: Partial<Omit<HealState, "schema">>): void {
263
+ try {
264
+ const state = { ...loadState(), ...part };
265
+ const path = statePath();
266
+ mkdirSync(dirname(path), { recursive: true });
267
+ const tmp = `${path}.${process.pid}.tmp`;
268
+ writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, "utf8");
269
+ renameSync(tmp, path);
270
+ } catch {
271
+ // best effort: a lost stamp only costs one extra request next run
272
+ }
273
+ }
274
+
275
+ // ------------------------------------------------------------- channels
276
+
277
+ /** A models.json apiKey: "$VAR" env, "!cmd" shell output, else the literal. */
278
+ function resolveSecret(value: unknown): string | undefined {
279
+ if (typeof value !== "string" || !value) return undefined;
280
+ if (value.startsWith("$")) return process.env[value.slice(1)]?.trim() || undefined;
281
+ if (value.startsWith("!")) {
282
+ try {
283
+ // A hanging or prompting command must not freeze pi: give up after 5 s.
284
+ return execSync(value.slice(1), { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5_000 }).trim() || undefined;
285
+ } catch {
286
+ return undefined;
287
+ }
288
+ }
289
+ return value;
290
+ }
291
+
292
+ interface Channel {
293
+ provider: string;
294
+ baseUrl: string;
295
+ api: string;
296
+ // Resolved on first use, so a !cmd key never runs for a channel the TTL skips.
297
+ key: () => string | undefined;
298
+ headers: Record<string, string>;
299
+ compat: Compat;
300
+ ids: string[];
301
+ }
302
+
303
+ /** Every declared provider with a baseUrl. The key comes from auth.json (what /login and
304
+ * the wizard write) before models.json's apiKey. */
305
+ function channelsOf(cfg: Obj, deps: HealDeps): Channel[] {
306
+ const byProvider = groupByProvider(deps.models());
307
+ const out: Channel[] = [];
308
+ for (const [provider, entry] of Object.entries(providersOf(cfg))) {
309
+ if (!isObj(entry)) continue;
310
+ const merged = byProvider.get(lower(provider)) ?? [];
311
+ const baseUrl = typeof entry.baseUrl === "string" && entry.baseUrl ? entry.baseUrl : merged.find((m) => typeof m.baseUrl === "string" && m.baseUrl)?.baseUrl;
312
+ if (typeof baseUrl !== "string" || !baseUrl) continue;
313
+ const headers: Record<string, string> = {};
314
+ if (isObj(entry.headers)) for (const [k, v] of Object.entries(entry.headers)) if (typeof v === "string") headers[k] = v;
315
+ let key: { value: string | undefined } | undefined;
316
+ const stated = Array.isArray(entry.models) ? (entry.models as unknown[]).flatMap((m) => (isObj(m) && m.id ? [String(m.id)] : [])) : [];
317
+ out.push({
318
+ provider,
319
+ baseUrl,
320
+ api: lower(entry.api ?? merged[0]?.api),
321
+ key: () => (key ??= { value: readAuthKey(provider) ?? resolveSecret(entry.apiKey) }).value,
322
+ headers,
323
+ compat: { ...(isObj(entry.compat) ? entry.compat : {}), ...(merged[0]?.compat ?? {}) },
324
+ ids: [...new Set([...stated, ...merged.map((m) => m.id)])].sort(),
325
+ });
326
+ }
327
+ return out;
328
+ }
329
+
330
+ async function fetchMeta(channel: Channel, fetchImpl: typeof fetch): Promise<Map<string, ModelMeta>> {
331
+ const headers: Record<string, string> = { accept: "application/json", "accept-encoding": "identity", ...channel.headers };
332
+ const key = channel.key();
333
+ if (key) headers.authorization = `Bearer ${key}`;
334
+ const response = await fetchImpl(`${channel.baseUrl.replace(/\/+$/, "")}/models`, { headers, signal: AbortSignal.timeout(META_TIMEOUT_MS) });
335
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
336
+ const text = await response.text();
337
+ if (text.length > META_MAX_BYTES) throw new Error("response too large");
338
+ const body = JSON.parse(text) as unknown;
339
+ return parseModelMeta(Array.isArray(body) ? { data: body } : body);
340
+ }
341
+
342
+ /** Read models.json for a network pass; a corrupt file is the flags pass's to report. */
343
+ function readForPass(): Obj | undefined {
344
+ try {
345
+ const cfg = loadModelsConfig();
346
+ return isObj(cfg) && isObj(cfg.providers) ? cfg : undefined;
347
+ } catch {
348
+ return undefined;
349
+ }
350
+ }
351
+
352
+ // ----------------------------------------------------------- pass: meta
353
+
354
+ let metaInFlight = false;
355
+
356
+ /** contextWindow / maxTokens from each channel's catalog. A non-forced run skips a channel
357
+ * fetched within the TTL whose baseUrl and model ids are unchanged. */
358
+ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResult> {
359
+ if (metaInFlight) return none();
360
+ metaInFlight = true;
361
+ try {
362
+ const cfg = readForPass();
363
+ if (!cfg) return none();
364
+ const state = loadState();
365
+ const now = Date.now();
366
+ const errors: string[] = [];
367
+ const fetched = new Map<string, { meta: Map<string, ModelMeta>; signature: string }>();
368
+ for (const channel of channelsOf(cfg, deps)) {
369
+ const signature = JSON.stringify({ baseUrl: channel.baseUrl, ids: channel.ids });
370
+ const prev = state.providers[channel.provider];
371
+ if (!force && prev?.signature === signature && now - prev.fetchedAt < META_TTL_MS) continue;
372
+ try {
373
+ fetched.set(channel.provider, { meta: await fetchMeta(channel, deps.fetchImpl ?? fetch), signature });
374
+ } catch (error) {
375
+ errors.push(`${channel.provider}: ${errText(error)}`);
376
+ }
377
+ }
378
+ if (fetched.size === 0) return { changed: false, detail: [], errors };
379
+
380
+ const byProvider = groupByProvider(deps.models());
381
+ const result = edit((fresh) => {
382
+ const detail: string[] = [];
383
+ for (const [provider, { meta, signature }] of fetched) {
384
+ const entry = providerEntry(fresh, provider);
385
+ const owned = deps.ownsModels(provider);
386
+ const loaded = new Set((byProvider.get(lower(provider)) ?? []).map((m) => m.id));
387
+ for (const [id, fields] of meta) {
388
+ // A catalog id pi never loaded is not a model the user runs: no entry for it.
389
+ if (!loaded.has(id) && !modelEntryOf(entry, id)) continue;
390
+ const { slot, label } = modelSlot(entry, id, owned);
391
+ const key = modelKey(provider, id);
392
+ const prev = state.sources[key];
393
+ const curCtx = typeof slot.contextWindow === "number" ? slot.contextWindow : undefined;
394
+ const curMax = typeof slot.maxTokens === "number" ? slot.maxTokens : undefined;
395
+ // A value this pass wrote that no longer matches was edited by hand: manual from now on.
396
+ const manualCtx = prev?.contextWindow !== undefined && curCtx !== prev.contextWindow;
397
+ const manualMax = prev?.maxTokens !== undefined && curMax !== prev.maxTokens;
398
+ const next = { at: Date.now(), contextWindow: prev?.contextWindow, maxTokens: prev?.maxTokens };
399
+
400
+ if (fields.contextWindow !== undefined && !manualCtx && contextWindowAccepted(fields.contextWindow, curCtx)) {
401
+ if (curCtx !== fields.contextWindow) {
402
+ slot.contextWindow = fields.contextWindow;
403
+ detail.push(`${provider} ${label}: contextWindow ${curCtx ?? "unset"} -> ${fields.contextWindow}`);
404
+ }
405
+ next.contextWindow = fields.contextWindow;
406
+ }
407
+ const window = typeof slot.contextWindow === "number" ? slot.contextWindow : undefined;
408
+ if (fields.maxTokens !== undefined && !manualMax) {
409
+ const cap = window !== undefined && fields.maxTokens > window ? window : fields.maxTokens;
410
+ if (curMax === undefined || cap > curMax) {
411
+ slot.maxTokens = cap;
412
+ next.maxTokens = cap;
413
+ detail.push(`${provider} ${label}: maxTokens ${curMax ?? "unset"} -> ${cap}`);
414
+ }
415
+ }
416
+ // An override this pass created and left empty must not stay behind.
417
+ if (Object.keys(slot).length === 0 && isObj(entry.modelOverrides)) delete (entry.modelOverrides as Obj)[id];
418
+ if (next.contextWindow !== undefined || next.maxTokens !== undefined) state.sources[key] = next;
419
+ }
420
+ if (isObj(entry.modelOverrides) && Object.keys(entry.modelOverrides).length === 0) delete entry.modelOverrides;
421
+ state.providers[provider] = { signature, fetchedAt: Date.now() };
422
+ }
423
+ return detail;
424
+ });
425
+ // fetchedAt is kept even when nothing changed, so the TTL holds. A failed write keeps no
426
+ // stamp: a stamped value missing from models.json would read as a hand edit forever.
427
+ if (result.errors.length === 0) saveState({ providers: state.providers, sources: state.sources });
428
+ return { ...result, errors: [...errors, ...result.errors] };
429
+ } finally {
430
+ metaInFlight = false;
431
+ }
432
+ }
433
+
434
+ // --------------------------------------------------------- pass: effort
435
+
436
+ let effortInFlight = false;
437
+
438
+ const mapOf = (m: RtModel): Record<string, string | null> | undefined => (isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined);
439
+
440
+ /** Probe the reasoning efforts each relay accepts and remap rejected levels. A map the user
441
+ * shaped (a remap or a null) is theirs and never probed, not even when forced. */
442
+ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[]): Promise<HealResult> {
443
+ if (effortInFlight) return none();
444
+ effortInFlight = true;
445
+ try {
446
+ const cfg = readForPass();
447
+ if (!cfg) return none();
448
+ const channels = new Map(
449
+ channelsOf(cfg, deps)
450
+ .filter((c) => c.api === "openai-completions" || c.api === "openai-responses")
451
+ .map((c) => [lower(c.provider), c] as const),
452
+ );
453
+ if (channels.size === 0) return none();
454
+
455
+ const state = loadState();
456
+ const now = Date.now();
457
+ const pending = (only ?? deps.models()).filter((m) => {
458
+ const channel = m?.provider ? channels.get(lower(m.provider)) : undefined;
459
+ if (!channel || !isEffortProbeable(m, channel.compat) || carriesRemap(mapOf(m))) return false;
460
+ if (force) return true;
461
+ const prev = state.efforts[modelKey(m.provider, m.id)];
462
+ if (!prev) return true;
463
+ if (now - prev.at >= (prev.failed ? EFFORT_FAILURE_TTL_MS : EFFORT_TTL_MS)) return true;
464
+ return JSON.stringify(mapOf(m) ?? {}) !== JSON.stringify(prev.map); // edited since: respect it
465
+ });
466
+ if (pending.length === 0) return none();
467
+
468
+ const errors: string[] = [];
469
+ const answered: { model: RtModel; supported: string[] }[] = [];
470
+ const deadline = now + EFFORT_BUDGET_MS;
471
+ for (const model of pending) {
472
+ if (Date.now() >= deadline) {
473
+ errors.push(`${model.provider}: probe budget exhausted`);
474
+ break;
475
+ }
476
+ const channel = channels.get(lower(model.provider))!;
477
+ const supported = await probeEffort(
478
+ { ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
479
+ { baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl },
480
+ );
481
+ if (supported.length === 0) {
482
+ // Stamped as failed so the next run waits the short TTL instead of re-sending.
483
+ errors.push(`${model.provider}/${model.id}: no level answered (not patched)`);
484
+ state.efforts[modelKey(model.provider, model.id)] = { at: now, map: mapOf(model) ?? {}, failed: true };
485
+ continue;
486
+ }
487
+ answered.push({ model, supported });
488
+ }
489
+
490
+ const result = edit((fresh) => {
491
+ const detail: string[] = [];
492
+ for (const { model, supported } of answered) {
493
+ const current = mapOf(model);
494
+ const next = buildEffortMap(current, supported);
495
+ state.efforts[modelKey(model.provider, model.id)] = { at: Date.now(), map: next ?? current ?? {} };
496
+ if (!next) continue;
497
+ const { slot, label } = modelSlot(providerEntry(fresh, model.provider), model.id, deps.ownsModels(model.provider));
498
+ slot.thinkingLevelMap = next;
499
+ const parts = Object.entries(next).flatMap(([level, value]) => (value === null ? [`${level}=unsupported`] : value === level ? [] : [`${level}->${value}`]));
500
+ detail.push(`${model.provider} ${label}: thinkingLevelMap ${parts.join(", ")}`);
501
+ }
502
+ return detail;
503
+ });
504
+ saveState({ efforts: state.efforts });
505
+ return { ...result, errors: [...errors, ...result.errors] };
506
+ } finally {
507
+ effortInFlight = false;
508
+ }
509
+ }
510
+
511
+ // ----------------------------------------------------------- self-check
512
+
513
+ if (isMain(import.meta.url)) {
514
+ const dir = mkdtempSync(join(tmpdir(), "arnative-heal-"));
515
+ const previous = process.env.PI_CODING_AGENT_DIR;
516
+ process.env.PI_CODING_AGENT_DIR = dir;
517
+ try {
518
+ assert(getAgentDir() === dir, "the fixture redirects the agent dir");
519
+ const file = join(dir, "models.json");
520
+ const read = (): Record<string, Obj> => (JSON.parse(readFileSync(file, "utf8")) as Obj).providers as Record<string, Obj>;
521
+ const modelIn = (provider: string, id: string): Obj => (read()[provider]!.models as Obj[]).find((m) => m.id === id)!;
522
+ const relay = { api: "openai-completions", baseUrl: "https:\/\/relay.example/v1" };
523
+ writeFileSync(
524
+ file,
525
+ JSON.stringify({
526
+ providers: {
527
+ relay: { ...relay, apiKey: "k", models: [{ id: "gpt-x" }, { id: "claude-sonnet-4-5" }, { id: "r1", reasoning: true }] },
528
+ owned: { ...relay },
529
+ },
530
+ }),
531
+ );
532
+ const registry: RtModel[] = [
533
+ { provider: "relay", id: "gpt-x", ...relay },
534
+ { provider: "relay", id: "claude-sonnet-4-5", ...relay },
535
+ { provider: "relay", id: "r1", reasoning: true, ...relay },
536
+ { provider: "owned", id: "o1", ...relay },
537
+ ];
538
+ const deps: HealDeps = { models: () => registry, ownsModels: (p) => p === "owned" };
539
+
540
+ const first = healFlags(deps);
541
+ assert(first.changed && first.errors.length === 0, "the first flags pass writes");
542
+ const relayCompat = read().relay!.compat as Obj;
543
+ assert(relayCompat.supportsLongCacheRetention === false && relayCompat.sendSessionAffinityHeaders === true, "a channel-wide flag lands at provider level");
544
+ assert(relayCompat.cacheControlFormat === undefined, "a flag only one sibling needs stays off the provider");
545
+ assert((modelIn("relay", "claude-sonnet-4-5").compat as Obj).cacheControlFormat === "anthropic", "and lands on that model");
546
+ const r1 = modelIn("relay", "r1");
547
+ assert(isObj(r1.thinkingLevelMap) && (r1.compat as Obj).supportsDeveloperRole === false, "a reasoning model gets a map and the developer-role opt-out");
548
+ assert(read().owned!.compat === undefined && isObj((read().owned!.modelOverrides as Obj).o1), "an extension-owned provider is fixed through modelOverrides");
549
+ assert(existsSync(`${file}.bak-model-heal`), "the first write keeps a backup");
550
+
551
+ // The registry stays stale until refresh; a repeat must find nothing left to write.
552
+ assert(!healFlags(deps).changed, "a repeated pass is a no-op");
553
+
554
+ // An explicit value, even false, produces no suggestion, so nothing overwrites it.
555
+ const explicit: RtModel = { provider: "relay", id: "gpt-x", ...relay, compat: { supportsLongCacheRetention: true, sendSessionAffinityHeaders: false } };
556
+ assert(Object.keys(suggestCompat(explicit)).length === 0, "stated flags produce no suggestion");
557
+
558
+ // Meta: a synced window and cap, an unloaded catalog id, the TTL, a later hand edit.
559
+ const catalog = { data: [{ id: "gpt-x", context_length: 400_000, max_output_tokens: 32_000 }, { id: "unloaded", context_length: 9 }] };
560
+ let calls = 0;
561
+ const metaFetch = (async () => {
562
+ calls++;
563
+ return { ok: true, status: 200, text: async () => JSON.stringify(catalog) };
564
+ }) as unknown as typeof fetch;
565
+ const metaDeps: HealDeps = { ...deps, fetchImpl: metaFetch };
566
+ const meta = await healMeta(metaDeps, false);
567
+ assert(meta.changed && modelIn("relay", "gpt-x").contextWindow === 400_000 && modelIn("relay", "gpt-x").maxTokens === 32_000, "a catalog window and cap are synced");
568
+ assert(!readFileSync(file, "utf8").includes("unloaded"), "a catalog id pi never loaded gets no entry");
569
+ const callsAfterFirst = calls;
570
+ await healMeta(metaDeps, false);
571
+ assert(calls === callsAfterFirst, "a fresh signature inside the TTL costs no request");
572
+
573
+ const edited = JSON.parse(readFileSync(file, "utf8")) as Obj;
574
+ (((edited.providers as Record<string, Obj>).relay!.models as Obj[]).find((m) => m.id === "gpt-x")!).contextWindow = 200_000;
575
+ writeFileSync(file, JSON.stringify(edited));
576
+ await healMeta(metaDeps, true);
577
+ assert(modelIn("relay", "gpt-x").contextWindow === 200_000, "a hand-edited window stays manual");
578
+
579
+ // A write that fails must not stamp the state: the next run would read the unchanged
580
+ // value as a hand edit and never sync it again. A directory at the temp path fails
581
+ // the atomic write on every OS (EISDIR).
582
+ const locked = JSON.parse(readFileSync(file, "utf8")) as Obj;
583
+ (locked.providers as Record<string, Obj>).lock = { ...relay, models: [{ id: "m", contextWindow: 128_000 }] };
584
+ writeFileSync(file, JSON.stringify(locked));
585
+ const lockDeps: HealDeps = {
586
+ models: () => [{ provider: "lock", id: "m", ...relay }],
587
+ ownsModels: () => false,
588
+ fetchImpl: (async () => ({ ok: true, status: 200, text: async () => JSON.stringify({ data: [{ id: "m", context_length: 400_000 }] }) })) as unknown as typeof fetch,
589
+ };
590
+ const blocker = file + "." + process.pid + ".tmp";
591
+ mkdirSync(blocker);
592
+ const failed = await healMeta(lockDeps, true);
593
+ rmSync(blocker, { recursive: true, force: true });
594
+ assert(!failed.changed && failed.errors.some((e) => e.startsWith("write failed")), "a failed write is reported");
595
+ await healMeta(lockDeps, true);
596
+ assert(modelIn("lock", "m").contextWindow === 400_000, "a failed write leaves no stamp, so the next run still syncs");
597
+
598
+ // Effort: a relay that 400s medium remaps it upward; a shaped map is left alone.
599
+ const effortFetch = (async (_url: string, init?: { body?: string }) => {
600
+ const level = JSON.parse(init?.body ?? "{}").reasoning_effort as string;
601
+ const ok = ["none", "minimal", "low", "high"].includes(level);
602
+ return { status: ok ? 200 : 400, text: async () => (ok ? "" : "invalid reasoning_effort") };
603
+ }) as unknown as typeof fetch;
604
+ const r1Model: RtModel = { provider: "relay", id: "r1", reasoning: true, ...relay, thinkingLevelMap: { ...DEFAULT_THINKING_MAP } };
605
+ const effort = await healEffort({ ...deps, fetchImpl: effortFetch }, true, [r1Model]);
606
+ assert(effort.changed && (modelIn("relay", "r1").thinkingLevelMap as Obj).medium === "high", "a rejected effort is remapped to the nearest accepted one");
607
+ const shaped = await healEffort({ ...deps, fetchImpl: effortFetch }, true, [{ ...r1Model, thinkingLevelMap: { medium: "high" } }]);
608
+ assert(!shaped.changed, "a user-shaped map is never probed");
609
+ assert(existsSync(join(dir, "arnative", "model-heal.json")), "state lives in the arnative folder");
610
+ // The trigger runs meta and effort at once; neither save may drop the other's stamps.
611
+ await Promise.all([healMeta(metaDeps, true), healEffort({ ...deps, fetchImpl: effortFetch }, true, [r1Model])]);
612
+ const both = JSON.parse(readFileSync(join(dir, "arnative", "model-heal.json"), "utf8")) as HealState;
613
+ assert(Object.keys(both.providers).length > 0 && Object.keys(both.efforts).length > 0, "concurrent passes keep both state sections");
614
+
615
+ // A corrupt models.json is reported and left byte-for-byte as it was.
616
+ writeFileSync(file, "{ broken");
617
+ const corrupt = healFlags(deps);
618
+ assert(!corrupt.changed && corrupt.errors.length === 1 && readFileSync(file, "utf8") === "{ broken", "a corrupt file is never rewritten");
619
+
620
+ // Coexistence: pi-auto-compat in settings is detected in both package shapes.
621
+ writeFileSync(join(dir, "settings.json"), JSON.stringify({ packages: ["npm:@bismawy/pi-arnative", { source: "npm:@bismawy/pi-auto-compat" }] }));
622
+ assert(autoCompatInstalled(), "an installed pi-auto-compat is detected");
623
+ writeFileSync(join(dir, "settings.json"), JSON.stringify({ packages: ["npm:@bismawy/pi-arnative"] }));
624
+ assert(!autoCompatInstalled(), "and its removal too");
625
+
626
+ // Mode: Full until chosen, every choice round-trips, and a junk value falls back to Full.
627
+ assert(activeModelHeal() === "Full", "Full is the default mode");
628
+ for (const choice of MODEL_HEAL_CHOICES) {
629
+ setModelHeal(choice);
630
+ assert(activeModelHeal() === choice, "the " + choice + " mode is saved");
631
+ }
632
+ saveChoice(MODEL_HEAL_KEY, "Sometimes");
633
+ assert(activeModelHeal() === "Full", "an unknown saved mode reads as Full");
634
+ } finally {
635
+ if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR;
636
+ else process.env.PI_CODING_AGENT_DIR = previous;
637
+ rmSync(dir, { recursive: true, force: true });
638
+ }
639
+ console.log("model-heal.ts self-check OK");
640
+ }
package/lib/provider.ts CHANGED
@@ -384,6 +384,11 @@ export function loadModelsConfig(): unknown {
384
384
  return readJson(modelsPath());
385
385
  }
386
386
 
387
+ /** Replace models.json whole, atomically (Model Heal writes a config it read and edited). */
388
+ export function saveModelsConfig(value: unknown): void {
389
+ writeJson(modelsPath(), value);
390
+ }
391
+
387
392
  export function saveProvider(name: string, entry: ProviderEntry, key: string | undefined): void {
388
393
  writeJson(modelsPath(), withProvider(readJson(modelsPath()), name, entry));
389
394
  if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bismawy/pi-arnative",
3
- "version": "0.8.0-rc.1",
3
+ "version": "0.8.0",
4
4
  "description": "Refined aesthetics. Cohesive tools. Built for Pi. Warm themes, rounded tool boxes, tabbed header, compact footer and a /usage dashboard.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -40,8 +40,8 @@
40
40
  "@earendil-works/pi-tui": "*"
41
41
  },
42
42
  "scripts": {
43
- "dev": "pi --extension ./extensions/tools.ts --extension ./extensions/section-headers.ts --extension ./extensions/footer.ts --extension ./extensions/timestamps.ts --extension ./extensions/ui-render-tweaks.ts --extension ./extensions/usage.ts --extension ./extensions/animations.ts --extension ./extensions/autocompact.ts --extension ./extensions/arnative.ts",
44
- "test": "node lib/box.ts && node lib/ansi.ts && node lib/color.ts && node lib/shortcuts.ts && node lib/preset-store.ts && node lib/spinner.ts && node themes/gen-themes.mjs --check && node extensions/tools.ts && node lib/list-picker.ts && node lib/compat.ts && node lib/provider.ts && node extensions/footer.ts && node extensions/timestamps.ts && node extensions/ui-render-tweaks.ts && node extensions/usage.ts && node extensions/animations.ts && node extensions/autocompact.ts && node extensions/arnative.ts && node --test",
43
+ "dev": "pi --extension ./extensions/tools.ts --extension ./extensions/section-headers.ts --extension ./extensions/footer.ts --extension ./extensions/timestamps.ts --extension ./extensions/ui-render-tweaks.ts --extension ./extensions/usage.ts --extension ./extensions/animations.ts --extension ./extensions/autocompact.ts --extension ./extensions/model-heal.ts --extension ./extensions/arnative.ts",
44
+ "test": "node lib/box.ts && node lib/ansi.ts && node lib/color.ts && node lib/shortcuts.ts && node lib/preset-store.ts && node lib/spinner.ts && node themes/gen-themes.mjs --check && node extensions/tools.ts && node lib/list-picker.ts && node lib/compat.ts && node lib/provider.ts && node lib/model-heal.ts && node extensions/footer.ts && node extensions/timestamps.ts && node extensions/ui-render-tweaks.ts && node extensions/usage.ts && node extensions/animations.ts && node extensions/autocompact.ts && node extensions/model-heal.ts && node extensions/arnative.ts && node --test",
45
45
  "preview": "node scripts/preview.mjs",
46
46
  "themes": "node themes/gen-themes.mjs",
47
47
  "release:check": "node scripts/release-check.mjs pre-tag",