@bismawy/pi-arnative 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }