@bismawy/pi-arnative 0.16.0 → 0.18.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.
Files changed (47) hide show
  1. package/README.md +25 -16
  2. package/extensions/index.ts +41 -0
  3. package/lib/active-clock.ts +91 -0
  4. package/lib/ansi.ts +40 -78
  5. package/lib/box.ts +49 -68
  6. package/lib/chatbox.ts +371 -0
  7. package/lib/color.ts +3 -31
  8. package/lib/compat.ts +0 -60
  9. package/lib/edit-diff.ts +199 -0
  10. package/{extensions → lib/features}/arnative.ts +96 -423
  11. package/{extensions/autocompact.ts → lib/features/auto-compact.ts} +30 -325
  12. package/{extensions → lib/features}/budget.ts +17 -242
  13. package/lib/features/footer.ts +2232 -0
  14. package/{extensions/section-headers.ts → lib/features/headers.ts} +38 -49
  15. package/{extensions → lib/features}/model-heal.ts +5 -28
  16. package/lib/features/progress-group.ts +1557 -0
  17. package/{extensions → lib/features}/render-cache.ts +130 -158
  18. package/{extensions → lib/features}/timestamps.ts +132 -131
  19. package/{extensions → lib/features}/todos.ts +44 -158
  20. package/lib/features/tools.ts +1202 -0
  21. package/lib/features/ui-render-tweaks.ts +606 -0
  22. package/lib/features/usage.ts +786 -0
  23. package/lib/format.ts +22 -4
  24. package/lib/git-status.ts +164 -0
  25. package/lib/list-picker.ts +1 -127
  26. package/lib/model-heal.ts +70 -162
  27. package/lib/patch.ts +0 -63
  28. package/lib/preset-store.ts +17 -133
  29. package/lib/provider-store.ts +573 -0
  30. package/lib/provider.ts +52 -851
  31. package/lib/runtime.ts +209 -0
  32. package/lib/shortcuts.ts +8 -58
  33. package/lib/spinner.ts +88 -162
  34. package/lib/status-widget.ts +4 -30
  35. package/lib/todos.ts +20 -143
  36. package/lib/usage-pricing.ts +143 -0
  37. package/lib/usage-store.ts +44 -378
  38. package/package.json +5 -6
  39. package/CHANGELOG.md +0 -678
  40. package/extensions/animations.ts +0 -242
  41. package/extensions/footer.ts +0 -2580
  42. package/extensions/tools.ts +0 -2231
  43. package/extensions/ui-render-tweaks.ts +0 -1005
  44. package/extensions/usage-export.ts +0 -283
  45. package/extensions/usage.ts +0 -1406
  46. package/lib/check.ts +0 -21
  47. package/themes/gen-themes.mjs +0 -715
@@ -0,0 +1,573 @@
1
+ /**
2
+ * Provider endpoint probing, model metadata merging, and models.json / auth.json store operations.
3
+ */
4
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import { buildCatalogIndex, findMetaForId, mergeMeta, parseModelMeta, suggestCompat, type CatalogIndex, type Compat, type ModelMeta } from "./compat.ts";
8
+ import { writeJsonAtomicSync } from "./preset-store.ts";
9
+
10
+ // ---------------------------------------------------------------- flavors
11
+
12
+ /** The wire protocols pi implements. A provider entry names one; the probe guesses it. */
13
+ export const API_FLAVORS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"] as const;
14
+ export type ApiFlavor = (typeof API_FLAVORS)[number];
15
+
16
+ export const FLAVOR_LABELS: Record<ApiFlavor, string> = {
17
+ "openai-completions": "OpenAI Chat Completions",
18
+ "openai-responses": "OpenAI Responses",
19
+ "anthropic-messages": "Anthropic Messages",
20
+ "google-generative-ai": "Gemini (Generative Language)",
21
+ };
22
+
23
+ /** Chat base for a flavor: the OpenAI implementations append to `/v1`, the Anthropic and
24
+ * Gemini ones carry their version in the path, so a `/v1` suffix there is a lie. */
25
+ export function chatBaseUrl(flavor: ApiFlavor, base: string): string {
26
+ const stripped = base.replace(/\/(v1|v1beta)\/?$/i, "");
27
+ if (flavor === "anthropic-messages" || flavor === "google-generative-ai") return stripped;
28
+ return /\/v\d+\w*$/.test(base) ? base.replace(/\/$/, "") : `${stripped}/v1`;
29
+ }
30
+
31
+ /** `https://api.deepseek.com/v1` → `deepseek`; the offered default for the name input. */
32
+ export function guessProviderName(base: string): string {
33
+ try {
34
+ const host = new URL(base).hostname;
35
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host) || host === "localhost") return host;
36
+ const labels = host.split(".");
37
+ const generic = new Set(["api", "llm", "gateway", "proxy", "relay", "open", "cloud"]);
38
+ const named = labels.filter((l, i) => !(i === 0 && generic.has(l)));
39
+ const tld = new Set(["com", "ai", "org", "net", "io", "dev", "app", "cn", "id", "co"]);
40
+ const body = named.length > 1 && tld.has(named[named.length - 1]!) ? named.slice(0, -1) : named;
41
+ return body.join("-").toLowerCase().replace(/[^a-z0-9-]/g, "") || host;
42
+ } catch {
43
+ return "custom";
44
+ }
45
+ }
46
+
47
+ /** Trim, default the scheme to `http://` for bare hosts (Ollama), drop trailing slashes. */
48
+ export function normalizeBase(input: string): string {
49
+ const trimmed = input.trim().replace(/\/+$/, "");
50
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return trimmed;
51
+ return `http://${trimmed}`;
52
+ }
53
+
54
+ // ---------------------------------------------------------------- probe
55
+
56
+ export type ProbeShape = "openai" | "ollama" | "gemini";
57
+
58
+ export interface ProbeCandidate {
59
+ /** Full URL to GET. */
60
+ url: string;
61
+ /** Flavor a list at this URL implies. */
62
+ flavor: ApiFlavor;
63
+ /** Body shape this path serves; the parse is strict to it. */
64
+ shape: ProbeShape;
65
+ /** The endpoint works without a key (Ollama); the saved entry then carries a dummy key. */
66
+ keyless: boolean;
67
+ /** Extra headers for this probe only (the Gemini key header, the OpenAI/Anthropic set). */
68
+ headers?: Record<string, string>;
69
+ }
70
+
71
+ /** GETs whose answer decides flavor and model list, in priority order. */
72
+ export function buildCandidates(base: string, key: string): ProbeCandidate[] {
73
+ const keyless = !key;
74
+ const auth: Record<string, string> = key
75
+ ? {
76
+ // Every header style at once: a strict server ignores the others.
77
+ authorization: `Bearer ${key}`,
78
+ "x-api-key": key,
79
+ "anthropic-version": "2023-06-01",
80
+ }
81
+ : {};
82
+ const candidates: ProbeCandidate[] = [
83
+ { url: `${base}/api/tags`, flavor: "openai-completions", shape: "ollama", keyless: true },
84
+ {
85
+ url: `${base}/v1beta/models`,
86
+ flavor: "google-generative-ai",
87
+ shape: "gemini",
88
+ keyless: false,
89
+ headers: key ? { "x-goog-api-key": key } : undefined,
90
+ },
91
+ ];
92
+ // A base already ending in `/v1` serves the list at `/models`; anything else tries the
93
+ // common layouts. Both answer `{data: [{id}]}` — openai-completions wins the tie, the
94
+ // model picker's `[a]` is the override for an Anthropic-shaped relay.
95
+ const listPaths = /\/v1$/.test(base) ? ["/models"] : ["/v1/models", "/models"];
96
+ for (const path of listPaths) {
97
+ candidates.push({ url: `${base}${path}`, flavor: "openai-completions", shape: "openai", keyless, headers: auth });
98
+ }
99
+ return candidates;
100
+ }
101
+
102
+ /** Model ids from a probed list body, or undefined when the body does not match the
103
+ * shape the path serves — a strict parse keeps a relay's answer on its own path. */
104
+ export function parseModelList(candidate: ProbeCandidate, body: unknown): string[] | undefined {
105
+ if (typeof body !== "object" || body === null) return undefined;
106
+ const record = body as Record<string, unknown>;
107
+ if (candidate.shape === "openai") {
108
+ if (!Array.isArray(record.data)) return undefined;
109
+ return record.data.map((m) => (typeof m === "object" && m !== null ? (m as Record<string, unknown>).id : undefined)).filter((id): id is string => typeof id === "string");
110
+ }
111
+ if (!Array.isArray(record.models)) return undefined;
112
+ return record.models
113
+ .map((m) => (typeof m === "object" && m !== null ? (m as Record<string, unknown>).name : undefined))
114
+ .filter((n): n is string => typeof n === "string")
115
+ .map((n) => (candidate.shape === "gemini" ? n.replace(/^models\//, "") : n));
116
+ }
117
+
118
+ export interface ProbeResult {
119
+ flavor: ApiFlavor;
120
+ /** Chat base for the flavor (`chatBaseUrl`). */
121
+ baseUrl: string;
122
+ models: string[];
123
+ /** `contextWindow`/`maxTokens` from the same answer — no second request. */
124
+ meta: Map<string, ModelMeta>;
125
+ /** Path that answered, for the notify line. */
126
+ via: string;
127
+ keyless: boolean;
128
+ }
129
+
130
+ export type FetchLike = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{
131
+ ok: boolean;
132
+ status?: number;
133
+ json(): Promise<unknown>;
134
+ }>;
135
+
136
+ /** Probe once: every candidate GET runs in parallel, the first candidate in priority
137
+ * order that answers with a recognized model list wins. Undefined when none does. */
138
+ export async function probeEndpoint(base: string, key: string, fetchImpl: FetchLike = fetch, timeoutMs = 10_000): Promise<ProbeResult | undefined> {
139
+ const candidates = buildCandidates(base, key);
140
+ const settled = await Promise.allSettled(
141
+ candidates.map(async (candidate) => {
142
+ const response = await fetchImpl(candidate.url, {
143
+ headers: candidate.headers,
144
+ signal: AbortSignal.timeout(timeoutMs),
145
+ });
146
+ if (!response.ok) throw new Error(`HTTP ${response.status ?? "error"}`);
147
+ const body = await response.json();
148
+ const models = parseModelList(candidate, body);
149
+ if (!models || models.length === 0) throw new Error("no models");
150
+ return { candidate, models, meta: parseModelMeta(body) };
151
+ }),
152
+ );
153
+ for (let i = 0; i < candidates.length; i++) {
154
+ const result = settled[i];
155
+ if (result?.status !== "fulfilled") continue;
156
+ const { candidate, models, meta } = result.value;
157
+ return {
158
+ flavor: candidate.flavor,
159
+ baseUrl: chatBaseUrl(candidate.flavor, base),
160
+ models: [...new Set(models)],
161
+ meta,
162
+ via: new URL(candidate.url).pathname,
163
+ keyless: candidate.keyless,
164
+ };
165
+ }
166
+ return undefined;
167
+ }
168
+
169
+ // ---------------------------------------------------------------- stores
170
+
171
+ /** pi's thinking scale, in order — `/think` clamps a request to the nearest level a model
172
+ * supports, and `xhigh`/`max` only exist when the map names them. */
173
+ export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
174
+ /** `auto` is not a pi level: it means `reasoning: true` with no map, so every `/think`
175
+ * level travels to the endpoint unchanged — for models that take an effort parameter. */
176
+ export type ThinkingSetting = ThinkingLevel | "auto";
177
+ export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
178
+
179
+ export interface ProviderModel {
180
+ id: string;
181
+ /** Thinking level; undefined means chat (no `reasoning` flag). */
182
+ level?: ThinkingSetting;
183
+ /** An effort map a probe produced; it wins over the level's own single pin. */
184
+ map?: Record<string, string | null>;
185
+ /** Stopped in the stored entry, so a reselect never loses it. */
186
+ meta?: ModelMeta;
187
+ compat?: Compat;
188
+ }
189
+
190
+ export interface ProviderEntry {
191
+ name?: string;
192
+ baseUrl: string;
193
+ api: ApiFlavor;
194
+ /** Set only when the endpoint needs no credential; a real key goes to auth.json. */
195
+ apiKey?: string;
196
+ models: ProviderModel[];
197
+ }
198
+
199
+ /** Level heuristic over a relay catalog id: the catalogs expose only ids, so an explicit
200
+ * level suffix (`-high`, `-xhigh`, `-max`…) pins that level, and everything else starts at
201
+ * `auto` — the endpoint decides. A chat-only model is switched to `off` by hand in the
202
+ * Thinking screen; pi passes an unmapped level through, so an endpoint that rejects
203
+ * reasoning parameters only breaks when `/think` is above `off`. */
204
+ export function detectLevel(id: string): ThinkingSetting {
205
+ const s = id.toLowerCase();
206
+ if (/-x-?high$/.test(s)) return "xhigh";
207
+ if (/-max(imum)?$/.test(s)) return "max";
208
+ if (/-high$/.test(s)) return "high";
209
+ if (/-med(ium)?$/.test(s)) return "medium";
210
+ if (/-low$/.test(s)) return "low";
211
+ if (/-min(imal)?$/.test(s)) return "minimal";
212
+ return "auto";
213
+ }
214
+
215
+ export const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
216
+
217
+ /** Pure merge: one provider added or replaced, every other key preserved. */
218
+ export function withProvider(config: unknown, name: string, entry: ProviderEntry): Record<string, unknown> {
219
+ const root = isObj(config) ? { ...config } : {};
220
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
221
+ // The same wire serialization every edit uses, so a first save and a later edit of the
222
+ // same provider produce the same models.json shape.
223
+ providers[name] = { ...entry, models: wireModels(name, entry, entry.models, []) };
224
+ root.providers = providers;
225
+ return root;
226
+ }
227
+
228
+ export function withoutProvider(config: unknown, name: string): Record<string, unknown> {
229
+ const root = isObj(config) ? { ...config } : {};
230
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
231
+ delete providers[name];
232
+ root.providers = providers;
233
+ return root;
234
+ }
235
+
236
+ export function providerNames(config: unknown): string[] {
237
+ return isObj(config) && isObj(config.providers) ? Object.keys(config.providers) : [];
238
+ }
239
+
240
+ /** Pure patch of one provider's scalar fields (endpoint, id, display name, inline key).
241
+ * `undefined` drops the field; models, compat, headers and every sibling survive — the
242
+ * same contract as {@link withProviderModels}. */
243
+ export function withProviderFields(config: unknown, name: string, patch: Record<string, string | undefined>): Record<string, unknown> {
244
+ const root = isObj(config) ? { ...config } : {};
245
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
246
+ const next: Record<string, unknown> = { ...(isObj(providers[name]) ? providers[name] : {}), ...patch };
247
+ for (const [key, value] of Object.entries(next)) if (value === undefined) delete next[key];
248
+ providers[name] = next;
249
+ root.providers = providers;
250
+ return root;
251
+ }
252
+
253
+ /** Pure rename: the provider keeps its position in the list, and a `name` that only
254
+ * repeated the old id follows it (a hand-written display name stays as written). */
255
+ export function renameProvider(config: unknown, from: string, to: string): Record<string, unknown> {
256
+ const root = isObj(config) ? { ...config } : {};
257
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
258
+ if (!(from in providers)) return root;
259
+ root.providers = Object.fromEntries(
260
+ Object.entries(providers).map(([key, value]): [string, unknown] => {
261
+ if (key !== from) return [key, value];
262
+ const entry: Record<string, unknown> = isObj(value) ? { ...value } : {};
263
+ if (entry.name === from) entry.name = to;
264
+ return [to, entry];
265
+ }),
266
+ );
267
+ return root;
268
+ }
269
+
270
+ /** The credential follows its provider in auth.json; a provider with no entry stays without one. */
271
+ export function renameAuth(auth: unknown, from: string, to: string): Record<string, unknown> {
272
+ const root = isObj(auth) ? { ...auth } : {};
273
+ if (!(from in root)) return root;
274
+ return Object.fromEntries(Object.entries(root).map(([key, value]): [string, unknown] => [key === from ? to : key, value]));
275
+ }
276
+
277
+ export interface ProviderSummary {
278
+ name: string;
279
+ api?: string;
280
+ modelCount: number;
281
+ }
282
+
283
+ export function summarizeProviders(config: unknown): ProviderSummary[] {
284
+ if (!isObj(config) || !isObj(config.providers)) return [];
285
+ return Object.entries(config.providers).map(([name, value]) => {
286
+ const entry = isObj(value) ? value : {};
287
+ const models = Array.isArray(entry.models) ? entry.models.length : 0;
288
+ return { name, api: typeof entry.api === "string" ? entry.api : undefined, modelCount: models };
289
+ });
290
+ }
291
+
292
+ /** Pure merge: the auth.json credential `/login` writes, keyed by provider id. */
293
+ export function withAuth(auth: unknown, name: string, key: string): Record<string, unknown> {
294
+ const root = isObj(auth) ? { ...auth } : {};
295
+ root[name] = { type: "api_key", key };
296
+ return root;
297
+ }
298
+
299
+ export function withoutAuth(auth: unknown, name: string): Record<string, unknown> {
300
+ const root = isObj(auth) ? { ...auth } : {};
301
+ delete root[name];
302
+ return root;
303
+ }
304
+
305
+ /** Rewrites one provider's model list and nothing else — compat, headers, name, every
306
+ * sibling field survives an edit exactly as it was stored. Levels serialize to pi's
307
+ * wire shape: `reasoning` for anything thinking, plus a `thinkingLevelMap` whose pinned
308
+ * level is a ceiling: every effort up to it maps to itself, every level above it is null,
309
+ * and `off` stays unmapped. pi reads null as unsupported, so the old map that nulled every
310
+ * level but one left the user stuck on that level, unable to lower it or turn thinking off. */
311
+ export function levelToWire(level: ThinkingSetting | undefined): { reasoning?: true; thinkingLevelMap?: Record<string, string | null> } {
312
+ if (level === undefined || level === "off") return {};
313
+ if (level === "auto") return { reasoning: true };
314
+ const ceiling = THINKING_LEVELS.indexOf(level);
315
+ const thinkingLevelMap: Record<string, string | null> = {};
316
+ THINKING_LEVELS.forEach((l, i) => {
317
+ if (l !== "off") thinkingLevelMap[l] = i <= ceiling ? l : null;
318
+ });
319
+ return { reasoning: true, thinkingLevelMap };
320
+ }
321
+
322
+ /** Reads pi's wire shape back into a level: the highest level mapped to itself is that level
323
+ * when every level above it is null (a ceiling, or the old single-pin shape). Any other map
324
+ * (heal's default, a probed remap) and `reasoning: true` alone are `auto`. */
325
+ export function wireToLevel(reasoning: unknown, map: unknown): ThinkingSetting {
326
+ if (isObj(map)) {
327
+ const levels = THINKING_LEVELS.filter((l) => l !== "off");
328
+ const top = levels.findLastIndex((l) => map[l] === l);
329
+ if (top !== -1 && levels.slice(top + 1).every((l) => map[l] === null)) {
330
+ // A ceiling maps every level below it to itself; the old single pin nulls them all.
331
+ // Anything else (an exact probed map with gaps) is a map, not a pin.
332
+ const below = levels.slice(0, top);
333
+ if (below.every((l) => map[l] === l) || below.every((l) => map[l] === null)) return levels[top]!;
334
+ }
335
+ }
336
+ return reasoning === true ? "auto" : "off";
337
+ }
338
+
339
+ export function withProviderModels(config: unknown, name: string, models: ProviderModel[]): Record<string, unknown> {
340
+ const root = isObj(config) ? { ...config } : {};
341
+ const providers = isObj(root.providers) ? { ...root.providers } : {};
342
+ const base = isObj(providers[name]) ? providers[name] : {};
343
+ const stated: Record<string, unknown>[] = Array.isArray(base.models) ? base.models.filter(isObj) : [];
344
+ providers[name] = { ...base, models: wireModels(name, base, models, stated) };
345
+ root.providers = providers;
346
+ return root;
347
+ }
348
+
349
+ /** One model in pi's wire shape: the level (or a probed map), the compat flags the rules
350
+ * imply, and the limits the probe found. Every other key of the stored entry survives —
351
+ * only `reasoning` and `thinkingLevelMap` are rewritten, because the level owns them. */
352
+ function wireModels(name: string, provider: { api?: unknown; baseUrl?: unknown }, models: ProviderModel[], stated: Record<string, unknown>[]): Record<string, unknown>[] {
353
+ const api = typeof provider.api === "string" ? provider.api : undefined;
354
+ const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl : "";
355
+ return models.map((m) => {
356
+ const prev = stated.find((s) => s.id === m.id);
357
+ const next: Record<string, unknown> = { ...(prev ?? {}) };
358
+ next.id = m.id;
359
+ delete next.reasoning;
360
+ delete next.thinkingLevelMap;
361
+ Object.assign(next, m.map ? { reasoning: true, thinkingLevelMap: m.map } : levelToWire(m.level));
362
+ const stored = isObj(next.compat) ? next.compat : {};
363
+ const compat = { ...stored, ...suggestCompat({ provider: name, id: m.id, api, baseUrl, reasoning: next.reasoning === true, compat: stored }), ...(m.compat ?? {}) };
364
+ if (Object.keys(compat).length > 0) next.compat = compat;
365
+ const meta = m.meta ?? (prev && typeof prev === "object" ? { contextWindow: prev.contextWindow as number | undefined, maxTokens: prev.maxTokens as number | undefined } : undefined);
366
+ if (meta?.contextWindow !== undefined) next.contextWindow = meta.contextWindow;
367
+ if (meta?.maxTokens !== undefined) next.maxTokens = meta.maxTokens;
368
+ return next;
369
+ });
370
+ }
371
+
372
+ /** A stored selection keeps its level; a new id gets the detected one. A probed limit is
373
+ * merged into the stored one, and a probed effort map travels with the level, so a reselect
374
+ * never loses what an earlier probe learned (an `auto` level serializes without a map). */
375
+ const PUBLIC_CATALOG_URL = "https://openrouter.ai/api/v1/models";
376
+ const PUBLIC_CATALOG_TTL_MS = 60 * 60 * 1000;
377
+ let publicCatalogCache: { index: CatalogIndex; at: number } | undefined;
378
+
379
+ type RegistryLike = { getAll?: () => readonly { id?: unknown; contextWindow?: unknown; maxTokens?: unknown }[] };
380
+
381
+ async function fetchPublicCatalog(fetchImpl: FetchLike, timeoutMs = 5_000): Promise<CatalogIndex | undefined> {
382
+ if (fetchImpl === fetch && publicCatalogCache && Date.now() - publicCatalogCache.at < PUBLIC_CATALOG_TTL_MS) {
383
+ return publicCatalogCache.index;
384
+ }
385
+ try {
386
+ const res = await fetchImpl(PUBLIC_CATALOG_URL, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
387
+ if (!res.ok) return undefined;
388
+ const parsed = parseModelMeta(await res.json());
389
+ const index = buildCatalogIndex(parsed);
390
+ if (fetchImpl === fetch) publicCatalogCache = { index, at: Date.now() };
391
+ return index;
392
+ } catch {
393
+ return undefined;
394
+ }
395
+ }
396
+
397
+ /** Fill missing `contextWindow` (and `maxTokens`) for picked models from pi's local
398
+ * model registry first, then from OpenRouter's public catalog if any still lack one. */
399
+ export async function resolveMissingMeta(
400
+ ids: readonly string[],
401
+ baseMeta: Map<string, ModelMeta> | undefined,
402
+ ctx: { modelRegistry?: RegistryLike } | undefined,
403
+ fetchImpl: FetchLike = fetch,
404
+ ): Promise<Map<string, ModelMeta>> {
405
+ const out = new Map<string, ModelMeta>(baseMeta ?? []);
406
+ let missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
407
+ if (missing.length === 0) return out;
408
+
409
+ // Tier 1: pi's built-in catalog and already-configured providers (instant, offline).
410
+ try {
411
+ const all = ctx?.modelRegistry?.getAll?.() ?? [];
412
+ const entries: [string, ModelMeta][] = [];
413
+ for (const m of all) {
414
+ if (typeof m?.id !== "string" || typeof m.contextWindow !== "number" || m.contextWindow <= 0) continue;
415
+ entries.push([m.id, { contextWindow: m.contextWindow, ...(typeof m.maxTokens === "number" && m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {}) }]);
416
+ }
417
+ if (entries.length > 0) {
418
+ const localIdx = buildCatalogIndex(entries);
419
+ for (const id of missing) {
420
+ const found = findMetaForId(id, localIdx);
421
+ if (found) out.set(id, mergeMeta(out.get(id), found));
422
+ }
423
+ }
424
+ } catch {
425
+ // Stale or partial registry must never block saving a provider.
426
+ }
427
+
428
+ missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
429
+ if (missing.length === 0) return out;
430
+
431
+ // Tier 2: public model catalog for open/commercial models not yet in local registry.
432
+ const publicIdx = await fetchPublicCatalog(fetchImpl);
433
+ if (publicIdx) {
434
+ for (const id of missing) {
435
+ const found = findMetaForId(id, publicIdx);
436
+ if (found) out.set(id, mergeMeta(out.get(id), found));
437
+ }
438
+ }
439
+ return out;
440
+ }
441
+
442
+ export const seedMeta = (entry: ProviderEntry, extra?: Map<string, ModelMeta>): Map<string, ModelMeta> => {
443
+ const out = new Map<string, ModelMeta>();
444
+ for (const m of entry.models) if (m.meta) out.set(m.id, m.meta);
445
+ if (extra) for (const [id, meta] of extra) out.set(id, mergeMeta(out.get(id), meta));
446
+ return out;
447
+ };
448
+
449
+ export function mergeLevels(entry: ProviderEntry, ids: string[], meta?: Map<string, ModelMeta>): ProviderModel[] {
450
+ return ids.map((id) => {
451
+ const existing = entry.models.find((m) => m.id === id);
452
+ const found = meta?.get(id);
453
+ return { id, level: existing?.level ?? detectLevel(id), map: existing?.map, meta: found ? mergeMeta(existing?.meta, found) : existing?.meta };
454
+ });
455
+ }
456
+
457
+ export const modelsPath = (): string => join(getAgentDir(), "models.json");
458
+ export const authPath = (): string => join(getAgentDir(), "auth.json");
459
+
460
+ /** pi's own models.json tolerance, replicated exactly: `//` comments and trailing
461
+ * commas are dropped outside string literals, so the wizard accepts every file pi's
462
+ * ModelConfig accepts — a hand-edited file never blocks the menu. */
463
+ export function looseJsonParse(content: string): unknown {
464
+ const stripped = content
465
+ .replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : ""))
466
+ .replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m, tail?: string) => tail ?? (m[0] === '"' ? m : ""));
467
+ return JSON.parse(stripped) as unknown;
468
+ }
469
+
470
+ /** Missing file → undefined. Corrupt JSON is thrown, never overwritten: the caller aborts
471
+ * and reports, so a broken models.json cannot be clobbered by a save. Reads with pi's
472
+ * tolerance: BOM stripped, comments and trailing commas dropped before JSON.parse. */
473
+ export function readJson(path: string): unknown {
474
+ let content: string;
475
+ try {
476
+ content = readFileSync(path, "utf8");
477
+ } catch {
478
+ return undefined;
479
+ }
480
+ if (content.trim() === "") return undefined;
481
+ return looseJsonParse(content.replace(/^\uFEFF/, ""));
482
+ }
483
+
484
+ export function writeJson(path: string, value: unknown): void {
485
+ writeJsonAtomicSync(path, value);
486
+ }
487
+
488
+ export function loadModelsConfig(): unknown {
489
+ return readJson(modelsPath());
490
+ }
491
+
492
+ /** Replace models.json whole, atomically (Model Heal writes a config it read and edited). */
493
+ export function saveModelsConfig(value: unknown): void {
494
+ writeJson(modelsPath(), value);
495
+ }
496
+
497
+ export function saveProvider(name: string, entry: ProviderEntry, key: string | undefined): void {
498
+ writeJson(modelsPath(), withProvider(readJson(modelsPath()), name, entry));
499
+ if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
500
+ }
501
+
502
+ /** Writes one provider's key: a real key lands in auth.json (the file /login writes, and the
503
+ * credential pi prefers over an inline models.json apiKey), `undefined` removes it. A
504
+ * literal inline key is dropped from models.json so the secret lives in one place; an
505
+ * env-var or shell reference is configuration, not a secret, and stays put. */
506
+ export function saveProviderKey(name: string, key: string | undefined): void {
507
+ const auth = readJson(authPath());
508
+ // Nothing stored and nothing to store: leave a missing auth.json missing.
509
+ if (key || (isObj(auth) && name in auth)) writeJson(authPath(), key ? withAuth(auth, name, key) : withoutAuth(auth, name));
510
+ const config = readJson(modelsPath());
511
+ const entry = isObj(config) && isObj(config.providers) && isObj(config.providers[name]) ? (config.providers[name] as Record<string, unknown>) : undefined;
512
+ if (!entry || typeof entry.apiKey !== "string" || /^[$!]/.test(entry.apiKey)) return;
513
+ writeJson(modelsPath(), withProviderFields(config, name, { apiKey: undefined }));
514
+ }
515
+
516
+ /** `dummy`/`ollama` are placeholders a keyless entry carries so pi can list its models;
517
+ * `$VAR`, `${VAR}` and `!command` are references, not secrets. Neither is a stored key. */
518
+ const PLACEHOLDER_KEYS = new Set(["dummy", "ollama"]);
519
+ export function inlineKey(entry: ProviderEntry): string | undefined {
520
+ const value = entry.apiKey;
521
+ if (!value || PLACEHOLDER_KEYS.has(value) || /^[$!]/.test(value)) return undefined;
522
+ return value;
523
+ }
524
+
525
+ /** One secret as it may be shown on screen: its last four characters, never the whole key. */
526
+ export function keyHint(key: string): string {
527
+ return key.length > 8 ? `••••${key.slice(-4)}` : "••••";
528
+ }
529
+
530
+ export function deleteProviderNamed(name: string): boolean {
531
+ const config = readJson(modelsPath());
532
+ if (!providerNames(config).includes(name)) return false;
533
+ writeJson(modelsPath(), withoutProvider(config, name));
534
+ writeJson(authPath(), withoutAuth(readJson(authPath()), name));
535
+ return true;
536
+ }
537
+
538
+ /** The stored credential for a provider, from the same auth.json /login writes. */
539
+ export function readAuthKey(name: string): string | undefined {
540
+ const auth = readJson(authPath());
541
+ if (!isObj(auth) || !isObj(auth[name])) return undefined;
542
+ const entry = auth[name] as Record<string, unknown>;
543
+ if (entry.type === "api_key" && typeof entry.key === "string") return entry.key;
544
+ return undefined;
545
+ }
546
+
547
+ /** The stored entry with its models typed; extra fields stay in the raw config (edits go
548
+ * through {@link withProviderModels}, which never drops them). */
549
+ export function loadProviderEntry(config: unknown, name: string): ProviderEntry | undefined {
550
+ if (!isObj(config) || !isObj(config.providers)) return undefined;
551
+ const value = (config.providers as Record<string, unknown>)[name];
552
+ if (!isObj(value)) return undefined;
553
+ const models: ProviderModel[] = Array.isArray(value.models)
554
+ ? (value.models as unknown[]).flatMap((m): ProviderModel[] => {
555
+ if (!isObj(m) || typeof m.id !== "string") return [];
556
+ const level = wireToLevel(m.reasoning, m.thinkingLevelMap);
557
+ const contextWindow = typeof m.contextWindow === "number" ? m.contextWindow : undefined;
558
+ const maxTokens = typeof m.maxTokens === "number" ? m.maxTokens : undefined;
559
+ const meta = contextWindow === undefined && maxTokens === undefined ? undefined : { contextWindow, maxTokens };
560
+ // An `auto` model keeps its stored map, so a later save never wipes what a probe learned.
561
+ const map = level === "auto" && isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined;
562
+ return [{ id: m.id, ...(level === "off" ? {} : { level }), ...(map ? { map } : {}), ...(meta ? { meta } : {}), ...(isObj(m.compat) ? { compat: m.compat } : {}) }];
563
+ })
564
+ : [];
565
+ return {
566
+ name: typeof value.name === "string" ? value.name : name,
567
+ baseUrl: typeof value.baseUrl === "string" ? value.baseUrl : "",
568
+ api: (typeof value.api === "string" ? value.api : "openai-completions") as ApiFlavor,
569
+ apiKey: typeof value.apiKey === "string" ? value.apiKey : undefined,
570
+ models,
571
+ };
572
+ }
573
+