@bismawy/pi-arnative 0.9.1 → 0.10.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +3 -3
  3. package/extensions/animations.ts +1 -1
  4. package/extensions/arnative.ts +23 -11
  5. package/extensions/autocompact.ts +0 -0
  6. package/extensions/footer.ts +0 -0
  7. package/extensions/model-heal.ts +93 -18
  8. package/extensions/section-headers.ts +0 -0
  9. package/extensions/timestamps.ts +0 -0
  10. package/extensions/todos.ts +43 -15
  11. package/extensions/tools.ts +128 -11
  12. package/extensions/ui-render-tweaks.ts +5 -5
  13. package/extensions/usage.ts +309 -19
  14. package/lib/ansi.ts +22 -12
  15. package/lib/box.ts +1 -1
  16. package/lib/check.ts +0 -0
  17. package/lib/compat.ts +13 -64
  18. package/lib/format.ts +0 -0
  19. package/lib/list-picker.ts +117 -22
  20. package/lib/model-heal.ts +78 -13
  21. package/lib/patch.ts +0 -0
  22. package/lib/preset-store.ts +0 -0
  23. package/lib/provider.ts +153 -66
  24. package/lib/shortcuts.ts +36 -20
  25. package/lib/spinner.ts +0 -0
  26. package/lib/status-widget.ts +14 -0
  27. package/lib/todos.ts +0 -0
  28. package/lib/usage-store.ts +227 -24
  29. package/package.json +1 -1
  30. package/themes/arnative-blossom.json +89 -0
  31. package/themes/arnative-crimson.json +89 -0
  32. package/themes/arnative-cyberpunk.json +28 -28
  33. package/themes/arnative-dracula.json +40 -39
  34. package/themes/arnative-earthy.json +89 -0
  35. package/themes/arnative-garden.json +89 -0
  36. package/themes/arnative-gruvbox.json +40 -39
  37. package/themes/arnative-lemonade.json +89 -0
  38. package/themes/{arnative-synthwave.json → arnative-magical.json} +32 -31
  39. package/themes/arnative-matrix.json +37 -36
  40. package/themes/arnative-neutral.json +89 -0
  41. package/themes/arnative-nord.json +43 -42
  42. package/themes/arnative-zinc.json +43 -42
  43. package/themes/arnative.json +32 -31
  44. package/themes/gen-themes.mjs +376 -129
  45. package/themes/arnative-emerald.json +0 -88
  46. package/themes/arnative-sun.json +0 -88
  47. package/themes/arnative-violet.json +0 -88
package/lib/compat.ts CHANGED
@@ -190,7 +190,6 @@ export function mergeMeta(prev: ModelMeta | undefined, next: ModelMeta): ModelMe
190
190
  // pi's levels in clamp order; `off` has no wire name of its own.
191
191
  export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
192
192
  const EFFORT_RANK = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
193
- const PROBED = new Set(EFFORT_RANK);
194
193
  const IDENTITY: Record<string, string> = { low: "low", medium: "medium", high: "high", xhigh: "xhigh" };
195
194
  const LEVEL_TIMEOUT_MS = 30_000;
196
195
  const PROBE_TOKENS = 16;
@@ -228,24 +227,6 @@ export function thinkingPayload(compat: Compat, enabled: boolean): Record<string
228
227
  }
229
228
  }
230
229
 
231
- /** Nearest accepted effort, up first (pi's clamp order), ties down. */
232
- export function nearestEffort(level: string, accepted: Set<string>): string | undefined {
233
- const idx = EFFORT_RANK.indexOf(level);
234
- if (idx === -1) return undefined;
235
- let best: string | undefined;
236
- let bestDistance = Number.POSITIVE_INFINITY;
237
- for (const candidate of accepted) {
238
- const cIdx = EFFORT_RANK.indexOf(candidate);
239
- if (cIdx === -1) continue;
240
- const distance = cIdx >= idx ? cIdx - idx : (idx - cIdx) * 1.01;
241
- if (distance < bestDistance) {
242
- bestDistance = distance;
243
- best = candidate;
244
- }
245
- }
246
- return best;
247
- }
248
-
249
230
  /** A map that remaps or drops a level was shaped by the user, not by a probe. */
250
231
  export function carriesRemap(map: Record<string, string | null> | undefined): boolean {
251
232
  if (!map) return false;
@@ -256,47 +237,16 @@ export function carriesRemap(map: Record<string, string | null> | undefined): bo
256
237
  return false;
257
238
  }
258
239
 
259
- /** Probe results → `thinkingLevelMap`. A rejected level maps to the nearest accepted one;
260
- * a level that works stays unmapped, so nothing is pinned that need not be. Undefined when
261
- * nothing answered or nothing changed. */
262
- export function buildEffortMap(current: Record<string, string | null> | undefined, supported: string[]): Record<string, string | null> | undefined {
240
+ /** Probe results -> an exact `thinkingLevelMap`: each accepted effort maps to itself and
241
+ * every rejected one is null, so pi offers only the levels the channel really runs and
242
+ * never sends one it drops. `off` stays pi's call (it disables thinking; it is not an
243
+ * effort). Undefined when nothing answered. */
244
+ export function buildEffortMap(supported: string[]): Record<string, string | null> | undefined {
263
245
  const accepted = new Set(supported);
264
246
  if (accepted.size === 0) return undefined;
265
247
  const out: Record<string, string | null> = {};
266
- let changed = false;
267
- for (const level of THINKING_LEVELS) {
268
- const existing = current?.[level];
269
- const optIn = level === "off" || level === "xhigh" || level === "max";
270
- if (optIn) {
271
- if (existing === undefined) continue; // not offered → not the probe's call
272
- if (existing === null || !PROBED.has(existing)) {
273
- out[level] = existing;
274
- continue;
275
- }
276
- const from = level === "off" ? "minimal" : level;
277
- const value = accepted.has(existing) ? existing : level === "off" && accepted.has("none") ? "none" : nearestEffort(from, accepted);
278
- if (!value) {
279
- out[level] = null;
280
- changed = true;
281
- continue;
282
- }
283
- if (value !== existing) changed = true;
284
- out[level] = value;
285
- continue;
286
- }
287
- if (existing !== undefined && existing !== level) {
288
- out[level] = existing; // offered under another name: deliberate
289
- continue;
290
- }
291
- if (existing === null) {
292
- out[level] = null;
293
- continue;
294
- }
295
- if (accepted.has(level)) continue;
296
- out[level] = nearestEffort(level, accepted) ?? null;
297
- changed = true;
298
- }
299
- return changed ? out : undefined;
248
+ for (const level of THINKING_LEVELS) if (level !== "off") out[level] = accepted.has(level) ? level : null;
249
+ return out;
300
250
  }
301
251
 
302
252
  export interface EffortProbeOptions {
@@ -387,12 +337,11 @@ if (isMain(import.meta.url)) {
387
337
  assert(mergeMeta({ maxTokens: 4096 }, { maxTokens: 8192 }).maxTokens === 8192, "an output cap only grows");
388
338
  assert(mergeMeta({ contextWindow: 1024 }, { maxTokens: 8192 }).maxTokens === 1024, "a cap above the window clamps to the window");
389
339
 
390
- assert(nearestEffort("medium", new Set(["low", "high"])) === "high", "a rejected level moves up first");
391
- assert(nearestEffort("high", new Set(["low", "medium"])) === "medium", "with no level above it moves down");
392
- assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.medium === "high", "a rejected level is remapped");
393
- assert(buildEffortMap(undefined, ["minimal", "low", "high"])?.xhigh === undefined, "an opt-in level is not invented");
394
- assert(buildEffortMap({ medium: null, high: "high" }, ["high"])?.medium === null, "a deliberate null survives");
395
- assert(buildEffortMap({ medium: "high" }, ["high"])?.medium === "high", "a deliberate remap is preserved");
340
+ assert(buildEffortMap([]) === undefined, "nothing answered writes nothing");
341
+ const exact = buildEffortMap(["none", "low", "high", "max"])!;
342
+ assert(exact.low === "low" && exact.high === "high" && exact.max === "max", "an accepted effort maps to itself");
343
+ assert(exact.minimal === null && exact.medium === null && exact.xhigh === null, "a rejected effort is unsupported, never remapped");
344
+ assert(exact.off === undefined, "off stays pi's call");
396
345
  assert(carriesRemap({ medium: "high" }) && carriesRemap({ low: null }) && !carriesRemap({ low: "low" }), "only a shaped map counts as deliberate");
397
346
  assert(thinkingPayload({ thinkingFormat: "zai" }, true)?.thinking !== undefined, "a channel that needs a thinking block gets one");
398
347
  assert(isEffortProbeable({ ...base, reasoning: true }), "a reasoning model on a relay is probeable");
@@ -407,7 +356,7 @@ if (isMain(import.meta.url)) {
407
356
  }) as unknown as typeof fetch;
408
357
  const supported = await probeEffort({ ...base, id: "relay-model", reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: fakeFetch });
409
358
  assert(supported.join() === "none,minimal,low,high", "the probe reports exactly the accepted levels");
410
- assert(buildEffortMap(undefined, supported)?.medium === "high", "a rejected level is remapped to the nearest accepted one");
359
+ assert(buildEffortMap(supported)?.medium === null, "a rejected level is not offered");
411
360
  const deadFetch = (async () => ({ status: 401, text: async () => "unauthorized" })) as unknown as typeof fetch;
412
361
  assert((await probeEffort({ ...base, reasoning: true }, { baseUrl: base.baseUrl, fetchImpl: deadFetch })).length === 0, "a credential failure answers nothing, so nothing is written");
413
362
 
package/lib/format.ts CHANGED
File without changes
@@ -17,7 +17,7 @@ export const LIST_LEGEND_ROOT = LEGEND_ROOT;
17
17
  export const LIST_LEGEND_MOVE = LEGEND_MOVE;
18
18
  export const LIST_LEGEND_LIVE = LEGEND_LIVE;
19
19
  /** A text field: Enter keeps the value, Esc leaves it untouched. */
20
- export const INPUT_LEGEND = "[Enter] Save [Esc] Cancel";
20
+ export const INPUT_LEGEND = "[Enter] Save [Esc] Back";
21
21
 
22
22
  /** One picker row: `Label · Note`. `note` is absent on the preset lists (themes, headers,
23
23
  * footers), which are bare names. */
@@ -74,6 +74,9 @@ interface ListPickerHooks {
74
74
  /** Description re-read on every render, so the line under the title can follow screen
75
75
  * state (the model list shows the API flavor `a` switched to). */
76
76
  description?: () => string;
77
+ // What the rows are ("models"): shows a filter line under the description, the way
78
+ // vision-watcher filters its model list. Slash focuses it, Enter keeps it, Esc clears it.
79
+ search?: string;
77
80
  }
78
81
 
79
82
  /** Box copy, so one picker serves every menu ("Themes - Arnative⠙", "Headers - Arnative⠙", …).
@@ -97,6 +100,11 @@ export class ListPicker implements Component {
97
100
  private readonly edge: (s: string) => string;
98
101
  /** Rows shown before the list scrolls (a relay catalog can be far longer than the screen). */
99
102
  private readonly maxRows: number | undefined;
103
+ private readonly field: Input | undefined;
104
+ private typing = false;
105
+ private get placeholder(): string {
106
+ return "Type to filter " + (this.hooks?.search ?? "") + "...";
107
+ }
100
108
 
101
109
  constructor(
102
110
  theme: { fg(c: string, t: string): string; bold?(t: string): string },
@@ -121,6 +129,8 @@ export class ListPicker implements Component {
121
129
  this.selected = Math.max(0, rows.findIndex((r) => r.label === current));
122
130
  this.edge = thinkingColorOf(theme, thinkingLevel);
123
131
  this.maxRows = maxRows;
132
+ // The live field: accent prompt and a cursor, shown only while typing (render draws the idle line).
133
+ this.field = hooks.search ? new Input({ prompt: theme.fg("accent", "> "), placeholder: this.placeholder, placeholderStyle: (t) => theme.fg("muted", t) }) : undefined;
124
134
  this.tick = hooks.tickMs ? setInterval(() => hooks.requestRender(), hooks.tickMs) : undefined;
125
135
  }
126
136
 
@@ -134,37 +144,93 @@ export class ListPicker implements Component {
134
144
 
135
145
  /** Selected row, for callers that need the choice after `done()` resolves. */
136
146
  get index(): number {
137
- return this.selected;
147
+ return this.shown[this.selected] ?? -1;
148
+ }
149
+
150
+ // Rows the search query matches, as indexes into rows. The match is fuzzy (the query's
151
+ // characters in order, gaps allowed, spaces ignored), so "river flash" and "riverflash"
152
+ // both find river/.../DeepSeek-V4.1-Flash.
153
+ private get shown(): number[] {
154
+ const q = this.query.toLowerCase().replace(/\s+/g, "");
155
+ const fits = (label: string): boolean => {
156
+ let at = 0;
157
+ for (const ch of label.toLowerCase()) if (ch === q[at]) at++;
158
+ return at === q.length;
159
+ };
160
+ return this.rows.flatMap((r, i) => (fits(r.label) ? [i] : []));
161
+ }
162
+
163
+ private get query(): string {
164
+ return this.field?.getValue() ?? "";
165
+ }
166
+
167
+ private setQuery(query: string): void {
168
+ this.field?.setValue(query);
169
+ this.selected = 0;
170
+ this.hooks.requestRender();
171
+ }
172
+
173
+ // True when the key belongs to the search field. Slash switches typing on and off. While
174
+ // typing every key is text (Space and digits too) and the arrows edit the field, so
175
+ // Enter, slash or Esc ends typing and keeps the filter; every command then acts on the
176
+ // matching rows. Esc one more time is the screen's Back.
177
+ private searchKey(keyData: string): boolean {
178
+ const field = this.field;
179
+ if (!field) return false;
180
+ const setTyping = (on: boolean): true => {
181
+ this.typing = on;
182
+ field.focused = on;
183
+ this.hooks.requestRender();
184
+ return true;
185
+ };
186
+ if (!this.typing) return keyData === "/" && setTyping(true);
187
+ if (keyData === "/" || matchesKey(keyData, "enter") || matchesKey(keyData, "escape")) return setTyping(false);
188
+ if (matchesKey(keyData, "up") || matchesKey(keyData, "down")) return false;
189
+ const before = this.query;
190
+ field.handleInput(keyData);
191
+ if (this.query !== before) this.selected = 0;
192
+ this.hooks.requestRender();
193
+ return true;
194
+ }
195
+
196
+ /** Esc/←: `back` owns an uncommitted preview's revert, so it is not duplicated here. */
197
+ private leave(): void {
198
+ if (this.hooks.back) {
199
+ this.hooks.back();
200
+ return;
201
+ }
202
+ if (this.applied !== this.opened) this.hooks.revert();
203
+ (this.hooks.cancel ?? this.hooks.done)();
138
204
  }
139
205
 
140
206
  private move(delta: number): void {
141
- const next = Math.min(this.rows.length - 1, Math.max(0, this.selected + delta));
142
- if (next === this.selected) return;
207
+ const shown = this.shown;
208
+ const next = Math.min(shown.length - 1, Math.max(0, this.selected + delta));
209
+ if (next === this.selected || next < 0) return;
143
210
  this.selected = next;
144
211
  if (!this.livePreview) {
145
212
  this.hooks.requestRender();
146
213
  return;
147
214
  }
148
- this.applied = this.rows[next]!.label;
215
+ this.applied = this.rows[shown[next]!]!.label;
149
216
  this.hooks.preview(this.applied);
150
217
  this.hooks.requestRender();
151
218
  }
152
219
 
153
220
  handleInput(keyData: string): void {
221
+ if (this.searchKey(keyData)) return;
222
+ // Esc steps out one level: a screen with a parent reopens it, and the root closes.
223
+ // ← is the same key for muscle memory, but a fill screen (`back: false`) hides it.
224
+ if (matchesKey(keyData, "escape")) {
225
+ this.leave();
226
+ return;
227
+ }
154
228
  if (matchesBack(keyData)) {
155
- // Leave for the parent without touching the preview: `back` owns the revert of an
156
- // uncommitted preview, because "cancel" here means "close", not "undo".
157
229
  if (this.hooks.back === false) return;
158
- if (this.hooks.back) {
159
- this.hooks.back();
160
- return;
161
- }
162
- // No parent (the root menu): ← behaves like Esc — close, reverting a live preview.
163
- if (this.applied !== this.opened) this.hooks.revert();
164
- (this.hooks.cancel ?? this.hooks.done)();
230
+ this.leave();
165
231
  return;
166
232
  }
167
- if (keyData === "Q" || matchesKey(keyData, "q") || matchesKey(keyData, "escape")) {
233
+ if (keyData === "Q" || matchesKey(keyData, "q")) {
168
234
  if (this.applied !== this.opened) this.hooks.revert();
169
235
  (this.hooks.cancel ?? this.hooks.done)();
170
236
  return;
@@ -194,11 +260,12 @@ export class ListPicker implements Component {
194
260
  const column = Math.max(0, ...this.rows.map((r) => visibleWidth(r.label)));
195
261
  const body: string[] = [];
196
262
  // A long list scrolls a window centered on the cursor, so the box keeps one height.
197
- const max = this.maxRows ?? this.rows.length;
198
- const windowStart = this.rows.length <= max ? 0 : Math.min(Math.max(0, this.selected - Math.floor(max / 2)), this.rows.length - max);
199
- const windowEnd = Math.min(this.rows.length, windowStart + max);
263
+ const shown = this.shown;
264
+ const max = this.maxRows ?? shown.length;
265
+ const windowStart = shown.length <= max ? 0 : Math.min(Math.max(0, this.selected - Math.floor(max / 2)), shown.length - max);
266
+ const windowEnd = Math.min(shown.length, windowStart + max);
200
267
  for (let i = windowStart; i < windowEnd; i++) {
201
- const item = this.rows[i]!;
268
+ const item = this.rows[shown[i]!]!;
202
269
  const isSelected = i === this.selected;
203
270
  const paint = isSelected ? (s: string) => soft(bold(s)) : (s: string) => th.fg(item.note ? "text" : "muted", s);
204
271
  const pad = " ".repeat(Math.max(0, column - visibleWidth(item.label)));
@@ -220,7 +287,14 @@ export class ListPicker implements Component {
220
287
  }
221
288
  // Hidden rows are announced, never silently cut (an empty line is still a row).
222
289
  if (windowStart > 0) body.unshift(truncateToWidth(th.fg("dim", `↑ ${windowStart} more`), width - 4, ""));
223
- if (windowEnd < this.rows.length) body.push(truncateToWidth(th.fg("dim", `↓ ${this.rows.length - windowEnd} more`), width - 4, ""));
290
+ if (windowEnd < shown.length) body.push(truncateToWidth(th.fg("dim", `↓ ${shown.length - windowEnd} more`), width - 4, ""));
291
+ if (this.field) {
292
+ // Idle, pi-tui's Input would still paint its fake cursor, so the off state is drawn here:
293
+ // a disabled prompt (the editor's idle border colour) over the kept query or the placeholder.
294
+ const idle = th.fg("borderMuted", "> ") + (this.query ? th.fg("text", this.query) : th.fg("dim", this.placeholder));
295
+ const line = this.typing ? this.field.render(Math.max(1, width - 4)) : [truncateToWidth(idle, width - 4, "")];
296
+ body.unshift(...line, "");
297
+ }
224
298
  return renderScreen(
225
299
  th,
226
300
  width,
@@ -313,8 +387,8 @@ export class InputPicker implements Component, Focusable {
313
387
  // Self-check: `node lib/list-picker.ts`
314
388
  if (isMain(import.meta.url)) {
315
389
  assert(LIST_LEGEND_ROOT === "[↑↓] Move [Enter] Open [Esc] Close", "root legend pinned, no ← behind the root menu");
316
- assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [←] Back [Esc] Close", "move legend pinned, ← advertised where a back target exists");
317
- assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [←] Back [Esc] Revert", "live legend pinned");
390
+ assert(LIST_LEGEND_MOVE === "[↑↓] Move [Enter] Open [Esc] Back", "move legend pinned: Esc is Back where a parent exists");
391
+ assert(LIST_LEGEND_LIVE === "[↑↓] Preview [Enter] Select [Esc] Back", "live legend pinned: Esc drops the preview and steps out");
318
392
  const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
319
393
  const quiet = (): void => undefined;
320
394
  const picker = new ListPicker(fakeTheme, nameRows(["a", "b"]), "a", { preview: quiet, revert: quiet, done: quiet, requestRender: quiet }, { title: screenTitle("Test"), description: "d", legend: "l" }, false);
@@ -402,5 +476,26 @@ if (isMain(import.meta.url)) {
402
476
  assert(!inputCancelled, "Enter is not a cancel");
403
477
  field.handleInput("\x1b");
404
478
  assert(inputCancelled, "Esc cancels the field");
479
+ // The Thinking flow: / starts typing, every key is text, Enter keeps the filter, then commands act on it.
480
+ const hits: string[] = [];
481
+ const filtered = new ListPicker(fakeTheme, [{ label: "river/ds-v4" }, { label: "auto/glm" }], undefined, { preview: () => {}, revert: () => {}, done: () => hits.push("done"), requestRender: () => {}, toggle: () => hits.push("toggle"), press: (k) => { if (/^[0-9]$/.test(k)) hits.push("press " + k); }, search: "models" }, { title: "T", description: "d", legend: "l" }, false);
482
+ filtered.handleInput("r");
483
+ assert(filtered.index === 0, "a letter outside typing does not filter");
484
+ filtered.handleInput("/");
485
+ for (const ch of "River 7") filtered.handleInput(ch);
486
+ assert(hits.join() === "" && filtered.index === -1, "while typing, Space and digits are text");
487
+ filtered.handleInput("\x7f");
488
+ for (const ch of "ds4") filtered.handleInput(ch);
489
+ assert(filtered.index === 0 && hits.join() === "", "the filter is fuzzy and ignores spaces: river ds4 finds river/ds-v4");
490
+ filtered.handleInput("\r");
491
+ filtered.handleInput("0");
492
+ filtered.handleInput(" ");
493
+ assert(hits.join() === "press 0,toggle" && filtered.index === 0, "Enter ends typing without saving, then keys are commands on the match");
494
+ filtered.handleInput("/");
495
+ filtered.handleInput("\x1b");
496
+ assert(hits.join() === "press 0,toggle", "Esc while typing ends typing and keeps the filter, so the screen stays open");
497
+ filtered.handleInput("\x1b");
498
+ assert(hits.join().endsWith("done"), "a second Esc, outside typing, leaves the screen");
499
+
405
500
  console.log("list-picker.ts self-check OK");
406
501
  }
package/lib/model-heal.ts CHANGED
@@ -27,12 +27,13 @@ import {
27
27
  parseModelMeta,
28
28
  probeEffort,
29
29
  suggestCompat,
30
+ THINKING_LEVELS,
30
31
  type Compat,
31
32
  type CompatModel,
32
33
  type ModelMeta,
33
34
  } from "./compat.ts";
34
35
  import { loadChoice, saveChoice } from "./preset-store.ts";
35
- import { loadModelsConfig, looseJsonParse, readAuthKey, saveModelsConfig } from "./provider.ts";
36
+ import { levelToWire, loadModelsConfig, looseJsonParse, readAuthKey, saveModelsConfig, wireToLevel } from "./provider.ts";
36
37
 
37
38
  // ------------------------------------------------------------- setting
38
39
 
@@ -68,6 +69,7 @@ export interface HealDeps {
68
69
  * models.json, so only `modelOverrides` reaches the merged model. */
69
70
  ownsModels: (provider: string) => boolean;
70
71
  fetchImpl?: typeof fetch;
72
+ signal?: AbortSignal;
71
73
  }
72
74
 
73
75
  export interface HealResult {
@@ -87,6 +89,7 @@ export const DEFAULT_THINKING_MAP = { low: "low", medium: "medium", high: "high"
87
89
 
88
90
  const HOUR_MS = 60 * 60 * 1000;
89
91
  const META_TTL_MS = 6 * HOUR_MS;
92
+ const META_FAILURE_TTL_MS = HOUR_MS;
90
93
  const META_TIMEOUT_MS = 8000;
91
94
  const META_MAX_BYTES = 2 * 1024 * 1024;
92
95
  const EFFORT_TTL_MS = 24 * HOUR_MS;
@@ -134,6 +137,16 @@ function edit(mutate: (cfg: Obj) => string[]): HealResult {
134
137
  return { changed: true, detail, errors: [] };
135
138
  }
136
139
 
140
+ /** The pre-0.9.2 wizard pin: all seven levels present, one non-off level mapped to itself,
141
+ * the other six null. */
142
+ const isSinglePin = (map: unknown): boolean => {
143
+ if (!isObj(map)) return false;
144
+ const values = THINKING_LEVELS.map((l) => map[l]);
145
+ if (values.some((v) => v === undefined)) return false;
146
+ const live = THINKING_LEVELS.filter((l) => map[l] !== null);
147
+ return live.length === 1 && live[0] !== "off" && map[live[0]!] === live[0];
148
+ };
149
+
137
150
  const providersOf = (cfg: Obj): Record<string, Obj> => cfg.providers as Record<string, Obj>;
138
151
 
139
152
  function providerEntry(cfg: Obj, provider: string): Obj {
@@ -195,6 +208,14 @@ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): H
195
208
  if (!isObj(entry) || !Array.isArray(entry.models)) continue;
196
209
  for (const m of entry.models) {
197
210
  if (!isObj(m) || m.reasoning !== true) continue;
211
+ // Before 0.9.2 the wizard pinned a level by nulling all six others, which pi reads as
212
+ // unsupported: the model was stuck on that one level. Rewrite that exact shape as the
213
+ // ceiling map the wizard writes now; any other map is the user's and stays.
214
+ if (isSinglePin(m.thinkingLevelMap)) {
215
+ m.thinkingLevelMap = levelToWire(wireToLevel(true, m.thinkingLevelMap)).thinkingLevelMap;
216
+ detail.push(`${provider} models[${String(m.id)}]: thinkingLevelMap ceiling`);
217
+ continue;
218
+ }
198
219
  if (isObj(m.thinkingLevelMap) && Object.keys(m.thinkingLevelMap).length > 0) continue;
199
220
  m.thinkingLevelMap = { ...DEFAULT_THINKING_MAP };
200
221
  detail.push(`${provider} models[${String(m.id)}]: thinkingLevelMap`);
@@ -235,9 +256,9 @@ export function healFlags(deps: HealDeps, only?: RtModel[], active?: RtModel): H
235
256
 
236
257
  interface HealState {
237
258
  schema: 1;
238
- providers: Record<string, { signature: string; fetchedAt: number }>;
259
+ providers: Record<string, { signature: string; fetchedAt: number; failed?: boolean }>;
239
260
  sources: Record<string, { contextWindow?: number; maxTokens?: number; at: number }>;
240
- efforts: Record<string, { at: number; map: Record<string, string | null>; failed?: boolean }>;
261
+ efforts: Record<string, { at: number; map: Record<string, string | null>; failed?: boolean; exact?: boolean }>;
241
262
  }
242
263
 
243
264
  const statePath = (): string => join(getAgentDir(), "arnative", "model-heal.json");
@@ -366,15 +387,22 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
366
387
  const errors: string[] = [];
367
388
  const fetched = new Map<string, { meta: Map<string, ModelMeta>; signature: string }>();
368
389
  for (const channel of channelsOf(cfg, deps)) {
390
+ deps.signal?.throwIfAborted();
369
391
  const signature = JSON.stringify({ baseUrl: channel.baseUrl, ids: channel.ids });
370
392
  const prev = state.providers[channel.provider];
371
- if (!force && prev?.signature === signature && now - prev.fetchedAt < META_TTL_MS) continue;
393
+ if (!force && prev?.signature === signature && now - prev.fetchedAt < (prev.failed ? META_FAILURE_TTL_MS : META_TTL_MS)) continue;
372
394
  try {
373
- fetched.set(channel.provider, { meta: await fetchMeta(channel, deps.fetchImpl ?? fetch), signature });
395
+ const meta = await fetchMeta(channel, deps.fetchImpl ?? fetch);
396
+ deps.signal?.throwIfAborted();
397
+ fetched.set(channel.provider, { meta, signature });
374
398
  } catch (error) {
399
+ deps.signal?.throwIfAborted();
375
400
  errors.push(`${channel.provider}: ${errText(error)}`);
401
+ state.providers[channel.provider] = { signature, fetchedAt: Date.now(), failed: true };
376
402
  }
377
403
  }
404
+ // A failed endpoint needs a cooldown even when no catalog answered.
405
+ if (errors.length > 0) saveState({ providers: state.providers });
378
406
  if (fetched.size === 0) return { changed: false, detail: [], errors };
379
407
 
380
408
  const byProvider = groupByProvider(deps.models());
@@ -435,6 +463,9 @@ export async function healMeta(deps: HealDeps, force: boolean): Promise<HealResu
435
463
 
436
464
  let effortInFlight = false;
437
465
 
466
+ const sameMap = (a: Record<string, string | null> | undefined, b: Record<string, string | null> | undefined): boolean =>
467
+ THINKING_LEVELS.every((l) => a?.[l] === b?.[l]);
468
+
438
469
  const mapOf = (m: RtModel): Record<string, string | null> | undefined => (isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined);
439
470
 
440
471
  /** Probe the reasoning efforts each relay accepts and remap rejected levels. A map the user
@@ -456,12 +487,15 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
456
487
  const now = Date.now();
457
488
  const pending = (only ?? deps.models()).filter((m) => {
458
489
  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;
490
+ if (!channel || !isEffortProbeable(m, channel.compat)) return false;
461
491
  const prev = state.efforts[modelKey(m.provider, m.id)];
462
- if (!prev) return true;
492
+ // A shaped map (a null or a remap) is the user's unless the probe wrote it. A map an
493
+ // older probe wrote (nearest-effort remaps) is redone now, not after the TTL.
494
+ const probeWrote = prev !== undefined && sameMap(mapOf(m), prev.map);
495
+ if (carriesRemap(mapOf(m)) && !probeWrote) return false;
496
+ if (force || !prev || (probeWrote && !prev.failed && prev.exact !== true)) return true;
463
497
  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
498
+ return !sameMap(mapOf(m), prev.map);
465
499
  });
466
500
  if (pending.length === 0) return none();
467
501
 
@@ -469,6 +503,7 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
469
503
  const answered: { model: RtModel; supported: string[] }[] = [];
470
504
  const deadline = now + EFFORT_BUDGET_MS;
471
505
  for (const model of pending) {
506
+ deps.signal?.throwIfAborted();
472
507
  if (Date.now() >= deadline) {
473
508
  errors.push(`${model.provider}: probe budget exhausted`);
474
509
  break;
@@ -478,6 +513,7 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
478
513
  { ...model, compat: { ...channel.compat, ...(model.compat ?? {}) } },
479
514
  { baseUrl: channel.baseUrl, key: channel.key(), headers: channel.headers, fetchImpl: deps.fetchImpl },
480
515
  );
516
+ deps.signal?.throwIfAborted();
481
517
  if (supported.length === 0) {
482
518
  // Stamped as failed so the next run waits the short TTL instead of re-sending.
483
519
  errors.push(`${model.provider}/${model.id}: no level answered (not patched)`);
@@ -491,8 +527,9 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
491
527
  const detail: string[] = [];
492
528
  for (const { model, supported } of answered) {
493
529
  const current = mapOf(model);
494
- const next = buildEffortMap(current, supported);
495
- state.efforts[modelKey(model.provider, model.id)] = { at: Date.now(), map: next ?? current ?? {} };
530
+ const exact = buildEffortMap(supported)!;
531
+ const next = sameMap(current, exact) ? undefined : exact;
532
+ state.efforts[modelKey(model.provider, model.id)] = { at: Date.now(), map: exact, exact: true };
496
533
  if (!next) continue;
497
534
  const { slot, label } = modelSlot(providerEntry(fresh, model.provider), model.id, deps.ownsModels(model.provider));
498
535
  slot.thinkingLevelMap = next;
@@ -508,6 +545,26 @@ export async function healEffort(deps: HealDeps, force: boolean, only?: RtModel[
508
545
  }
509
546
  }
510
547
 
548
+ /** A turn the relay rejected for its effort: that one level becomes null in the model's map,
549
+ * so pi stops offering it and the other levels stay. The map is stamped as probe-written, so
550
+ * the shaped-map guard does not lock it as the user's and a later rejection can drop more. */
551
+ export function markRejectedLevel(deps: HealDeps, model: RtModel, level: string): HealResult {
552
+ if (level === "off" || !(THINKING_LEVELS as readonly string[]).includes(level)) return none();
553
+ const state = loadState();
554
+ const result = edit((fresh) => {
555
+ const { slot, label } = modelSlot(providerEntry(fresh, model.provider), model.id, deps.ownsModels(model.provider));
556
+ const stored = isObj(slot.thinkingLevelMap) ? (slot.thinkingLevelMap as Record<string, string | null>) : mapOf(model);
557
+ const base: Record<string, string | null> = { ...(stored ?? DEFAULT_THINKING_MAP) };
558
+ if (base[level] === null) return [];
559
+ const next = { ...base, [level]: null };
560
+ slot.thinkingLevelMap = next;
561
+ state.efforts[modelKey(model.provider, model.id)] = { at: Date.now(), map: next, exact: true };
562
+ return [model.provider + " " + label + ": thinkingLevelMap " + level + "=unsupported (rejected by the relay)"];
563
+ });
564
+ if (result.changed) saveState({ efforts: state.efforts });
565
+ return result;
566
+ }
567
+
511
568
  // ----------------------------------------------------------- self-check
512
569
 
513
570
  if (isMain(import.meta.url)) {
@@ -524,7 +581,7 @@ if (isMain(import.meta.url)) {
524
581
  file,
525
582
  JSON.stringify({
526
583
  providers: {
527
- relay: { ...relay, apiKey: "k", models: [{ id: "gpt-x" }, { id: "claude-sonnet-4-5" }, { id: "r1", reasoning: true }] },
584
+ relay: { ...relay, apiKey: "k", models: [{ id: "gpt-x" }, { id: "claude-sonnet-4-5" }, { id: "r1", reasoning: true }, { id: "pinned", reasoning: true, thinkingLevelMap: { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null } }] },
528
585
  owned: { ...relay },
529
586
  },
530
587
  }),
@@ -547,6 +604,8 @@ if (isMain(import.meta.url)) {
547
604
  assert(isObj(r1.thinkingLevelMap) && (r1.compat as Obj).supportsDeveloperRole === false, "a reasoning model gets a map and the developer-role opt-out");
548
605
  assert(read().owned!.compat === undefined && isObj((read().owned!.modelOverrides as Obj).o1), "an extension-owned provider is fixed through modelOverrides");
549
606
  assert(existsSync(`${file}.bak-model-heal`), "the first write keeps a backup");
607
+ const pinned = modelIn("relay", "pinned").thinkingLevelMap as Obj;
608
+ assert(pinned.minimal === "minimal" && pinned.medium === "medium" && pinned.xhigh === "xhigh" && pinned.max === null && !("off" in pinned), "an old single-pin map becomes a ceiling map");
550
609
 
551
610
  // The registry stays stale until refresh; a repeat must find nothing left to write.
552
611
  assert(!healFlags(deps).changed, "a repeated pass is a no-op");
@@ -603,9 +662,15 @@ if (isMain(import.meta.url)) {
603
662
  }) as unknown as typeof fetch;
604
663
  const r1Model: RtModel = { provider: "relay", id: "r1", reasoning: true, ...relay, thinkingLevelMap: { ...DEFAULT_THINKING_MAP } };
605
664
  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");
665
+ assert(effort.changed && (modelIn("relay", "r1").thinkingLevelMap as Obj).medium === null, "a rejected effort is marked unsupported, not remapped");
607
666
  const shaped = await healEffort({ ...deps, fetchImpl: effortFetch }, true, [{ ...r1Model, thinkingLevelMap: { medium: "high" } }]);
608
667
  assert(!shaped.changed, "a user-shaped map is never probed");
668
+ const runtime = markRejectedLevel(deps, r1Model, "low");
669
+ const afterRuntime = modelIn("relay", "r1").thinkingLevelMap as Obj;
670
+ assert(runtime.changed && afterRuntime.low === null && afterRuntime.medium === null && afterRuntime.high === "high", "a level rejected at runtime is dropped and the rest stay");
671
+ assert(!markRejectedLevel(deps, r1Model, "low").changed, "a level already dropped is a no-op");
672
+ assert(!markRejectedLevel(deps, r1Model, "off").changed, "off is never dropped");
673
+ assert((await healEffort({ ...deps, fetchImpl: effortFetch }, false, [{ ...r1Model, thinkingLevelMap: afterRuntime as Record<string, string | null> }])).errors.length === 0, "a runtime-dropped map stays probe-owned");
609
674
  assert(existsSync(join(dir, "arnative", "model-heal.json")), "state lives in the arnative folder");
610
675
  // The trigger runs meta and effort at once; neither save may drop the other's stamps.
611
676
  await Promise.all([healMeta(metaDeps, true), healEffort({ ...deps, fetchImpl: effortFetch }, true, [r1Model])]);
package/lib/patch.ts CHANGED
File without changes
File without changes