@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
package/lib/provider.ts CHANGED
@@ -1,588 +1,55 @@
1
1
  /**
2
- * Providers menu (/arnative → Providers): a custom provider from three inputs — endpoint
3
- * URL, API key, name. The endpoint is probed once (Ollama, Gemini, OpenAI, Anthropic list
4
- * shapes), the models it answers with are picked over with Space (`[a]` switches the API
5
- * flavor when a relay answers in an ambiguous shape), and the result lands in pi's own
6
- * stores: the key in auth.json (the file /login writes), the declaration in models.json.
7
- * Opening /model reloads both files. Nothing is hand-edited by the user.
2
+ * Providers menu (/arnative → Providers): interactive TUI wizard for adding, probing,
3
+ * editing, and removing custom endpoints backed by lib/provider-store.ts.
8
4
  */
9
- import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
5
+ import { matchesKey } from "@earendil-works/pi-tui";
10
6
  import type { ExtensionCommandContext, Theme, TUI } from "@earendil-works/pi-coding-agent";
11
- import { getAgentDir } from "@earendil-works/pi-coding-agent";
12
- import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
13
- import { tmpdir } from "node:os";
14
- import { join } from "node:path";
15
- import { assert, isMain } from "./check.ts";
16
- import { buildCatalogIndex, buildEffortMap, findMetaForId, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type CatalogIndex, type Compat, type ModelMeta } from "./compat.ts";
7
+ import { buildEffortMap, isEffortProbeable, probeEffort, type ModelMeta } from "./compat.ts";
17
8
  import { screenTitle, type ScreenText } from "./box.ts";
18
- import { stripAnsi } from "./ansi.ts";
19
- import { writeAtomicSync } from "./preset-store.ts";
20
9
  import { announce, statusRows } from "./status-widget.ts";
21
10
  import { INPUT_LEGEND, InputPicker, LIST_LEGEND_MOVE, ListPicker, rowText, type ListRow } from "./list-picker.ts";
22
-
23
- // ---------------------------------------------------------------- flavors
24
-
25
- /** The wire protocols pi implements. A provider entry names one; the probe guesses it. */
26
- export const API_FLAVORS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"] as const;
27
- export type ApiFlavor = (typeof API_FLAVORS)[number];
28
-
29
- export const FLAVOR_LABELS: Record<ApiFlavor, string> = {
30
- "openai-completions": "OpenAI Chat Completions",
31
- "openai-responses": "OpenAI Responses",
32
- "anthropic-messages": "Anthropic Messages",
33
- "google-generative-ai": "Gemini (Generative Language)",
34
- };
35
-
36
- /** Chat base for a flavor: the OpenAI implementations append to `/v1`, the Anthropic and
37
- * Gemini ones carry their version in the path, so a `/v1` suffix there is a lie. */
38
- export function chatBaseUrl(flavor: ApiFlavor, base: string): string {
39
- const stripped = base.replace(/\/(v1|v1beta)\/?$/i, "");
40
- if (flavor === "anthropic-messages" || flavor === "google-generative-ai") return stripped;
41
- return /\/v\d+\w*$/.test(base) ? base.replace(/\/$/, "") : `${stripped}/v1`;
42
- }
43
-
44
- /** `https://api.deepseek.com/v1` → `deepseek`; the offered default for the name input. */
45
- export function guessProviderName(base: string): string {
46
- try {
47
- const host = new URL(base).hostname;
48
- if (/^\d+\.\d+\.\d+\.\d+$/.test(host) || host === "localhost") return host;
49
- const labels = host.split(".");
50
- const generic = new Set(["api", "llm", "gateway", "proxy", "relay", "open", "cloud"]);
51
- const named = labels.filter((l, i) => !(i === 0 && generic.has(l)));
52
- const tld = new Set(["com", "ai", "org", "net", "io", "dev", "app", "cn", "id", "co"]);
53
- const body = named.length > 1 && tld.has(named[named.length - 1]!) ? named.slice(0, -1) : named;
54
- return body.join("-").toLowerCase().replace(/[^a-z0-9-]/g, "") || host;
55
- } catch {
56
- return "custom";
57
- }
58
- }
59
-
60
- /** Trim, default the scheme to `http://` for bare hosts (Ollama), drop trailing slashes. */
61
- export function normalizeBase(input: string): string {
62
- const trimmed = input.trim().replace(/\/+$/, "");
63
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return trimmed;
64
- return `http://${trimmed}`;
65
- }
66
-
67
- // ---------------------------------------------------------------- probe
68
-
69
- export type ProbeShape = "openai" | "ollama" | "gemini";
70
-
71
- export interface ProbeCandidate {
72
- /** Full URL to GET. */
73
- url: string;
74
- /** Flavor a list at this URL implies. */
75
- flavor: ApiFlavor;
76
- /** Body shape this path serves; the parse is strict to it. */
77
- shape: ProbeShape;
78
- /** The endpoint works without a key (Ollama); the saved entry then carries a dummy key. */
79
- keyless: boolean;
80
- /** Extra headers for this probe only (the Gemini key header, the OpenAI/Anthropic set). */
81
- headers?: Record<string, string>;
82
- }
83
-
84
- /** GETs whose answer decides flavor and model list, in priority order. */
85
- export function buildCandidates(base: string, key: string): ProbeCandidate[] {
86
- const keyless = !key;
87
- const auth: Record<string, string> = key
88
- ? {
89
- // Every header style at once: a strict server ignores the others.
90
- authorization: `Bearer ${key}`,
91
- "x-api-key": key,
92
- "anthropic-version": "2023-06-01",
93
- }
94
- : {};
95
- const candidates: ProbeCandidate[] = [
96
- { url: `${base}/api/tags`, flavor: "openai-completions", shape: "ollama", keyless: true },
97
- {
98
- url: `${base}/v1beta/models`,
99
- flavor: "google-generative-ai",
100
- shape: "gemini",
101
- keyless: false,
102
- headers: key ? { "x-goog-api-key": key } : undefined,
103
- },
104
- ];
105
- // A base already ending in `/v1` serves the list at `/models`; anything else tries the
106
- // common layouts. Both answer `{data: [{id}]}` — openai-completions wins the tie, the
107
- // model picker's `[a]` is the override for an Anthropic-shaped relay.
108
- const listPaths = /\/v1$/.test(base) ? ["/models"] : ["/v1/models", "/models"];
109
- for (const path of listPaths) {
110
- candidates.push({ url: `${base}${path}`, flavor: "openai-completions", shape: "openai", keyless, headers: auth });
111
- }
112
- return candidates;
113
- }
114
-
115
- /** Model ids from a probed list body, or undefined when the body does not match the
116
- * shape the path serves — a strict parse keeps a relay's answer on its own path. */
117
- export function parseModelList(candidate: ProbeCandidate, body: unknown): string[] | undefined {
118
- if (typeof body !== "object" || body === null) return undefined;
119
- const record = body as Record<string, unknown>;
120
- if (candidate.shape === "openai") {
121
- if (!Array.isArray(record.data)) return undefined;
122
- 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");
123
- }
124
- if (!Array.isArray(record.models)) return undefined;
125
- return record.models
126
- .map((m) => (typeof m === "object" && m !== null ? (m as Record<string, unknown>).name : undefined))
127
- .filter((n): n is string => typeof n === "string")
128
- .map((n) => (candidate.shape === "gemini" ? n.replace(/^models\//, "") : n));
129
- }
130
-
131
- export interface ProbeResult {
132
- flavor: ApiFlavor;
133
- /** Chat base for the flavor (`chatBaseUrl`). */
134
- baseUrl: string;
135
- models: string[];
136
- /** `contextWindow`/`maxTokens` from the same answer — no second request. */
137
- meta: Map<string, ModelMeta>;
138
- /** Path that answered, for the notify line. */
139
- via: string;
140
- keyless: boolean;
141
- }
142
-
143
- export type FetchLike = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{
144
- ok: boolean;
145
- status?: number;
146
- json(): Promise<unknown>;
147
- }>;
148
-
149
- /** Probe once: every candidate GET runs in parallel, the first candidate in priority
150
- * order that answers with a recognized model list wins. Undefined when none does. */
151
- export async function probeEndpoint(base: string, key: string, fetchImpl: FetchLike = fetch, timeoutMs = 10_000): Promise<ProbeResult | undefined> {
152
- const candidates = buildCandidates(base, key);
153
- const settled = await Promise.allSettled(
154
- candidates.map(async (candidate) => {
155
- const response = await fetchImpl(candidate.url, {
156
- headers: candidate.headers,
157
- signal: AbortSignal.timeout(timeoutMs),
158
- });
159
- if (!response.ok) throw new Error(`HTTP ${response.status ?? "error"}`);
160
- const body = await response.json();
161
- const models = parseModelList(candidate, body);
162
- if (!models || models.length === 0) throw new Error("no models");
163
- return { candidate, models, meta: parseModelMeta(body) };
164
- }),
165
- );
166
- for (let i = 0; i < candidates.length; i++) {
167
- const result = settled[i];
168
- if (result?.status !== "fulfilled") continue;
169
- const { candidate, models, meta } = result.value;
170
- return {
171
- flavor: candidate.flavor,
172
- baseUrl: chatBaseUrl(candidate.flavor, base),
173
- models: [...new Set(models)],
174
- meta,
175
- via: new URL(candidate.url).pathname,
176
- keyless: candidate.keyless,
177
- };
178
- }
179
- return undefined;
180
- }
181
-
182
- // ---------------------------------------------------------------- stores
183
-
184
- /** pi's thinking scale, in order — `/think` clamps a request to the nearest level a model
185
- * supports, and `xhigh`/`max` only exist when the map names them. */
186
- export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
187
- /** `auto` is not a pi level: it means `reasoning: true` with no map, so every `/think`
188
- * level travels to the endpoint unchanged — for models that take an effort parameter. */
189
- export type ThinkingSetting = ThinkingLevel | "auto";
190
- export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
191
-
192
- export interface ProviderModel {
193
- id: string;
194
- /** Thinking level; undefined means chat (no `reasoning` flag). */
195
- level?: ThinkingSetting;
196
- /** An effort map a probe produced; it wins over the level's own single pin. */
197
- map?: Record<string, string | null>;
198
- /** Stopped in the stored entry, so a reselect never loses it. */
199
- meta?: ModelMeta;
200
- compat?: Compat;
201
- }
202
-
203
- export interface ProviderEntry {
204
- name?: string;
205
- baseUrl: string;
206
- api: ApiFlavor;
207
- /** Set only when the endpoint needs no credential; a real key goes to auth.json. */
208
- apiKey?: string;
209
- models: ProviderModel[];
210
- }
211
-
212
- /** Level heuristic over a relay catalog id: the catalogs expose only ids, so an explicit
213
- * level suffix (`-high`, `-xhigh`, `-max`…) pins that level, and everything else starts at
214
- * `auto` — the endpoint decides. A chat-only model is switched to `off` by hand in the
215
- * Thinking screen; pi passes an unmapped level through, so an endpoint that rejects
216
- * reasoning parameters only breaks when `/think` is above `off`. */
217
- export function detectLevel(id: string): ThinkingSetting {
218
- const s = id.toLowerCase();
219
- if (/-x-?high$/.test(s)) return "xhigh";
220
- if (/-max(imum)?$/.test(s)) return "max";
221
- if (/-high$/.test(s)) return "high";
222
- if (/-med(ium)?$/.test(s)) return "medium";
223
- if (/-low$/.test(s)) return "low";
224
- if (/-min(imal)?$/.test(s)) return "minimal";
225
- return "auto";
226
- }
227
-
228
- const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
229
-
230
- /** Pure merge: one provider added or replaced, every other key preserved. */
231
- export function withProvider(config: unknown, name: string, entry: ProviderEntry): Record<string, unknown> {
232
- const root = isObj(config) ? { ...config } : {};
233
- const providers = isObj(root.providers) ? { ...root.providers } : {};
234
- // The same wire serialization every edit uses, so a first save and a later edit of the
235
- // same provider produce the same models.json shape.
236
- providers[name] = { ...entry, models: wireModels(name, entry, entry.models, []) };
237
- root.providers = providers;
238
- return root;
239
- }
240
-
241
- export function withoutProvider(config: unknown, name: string): Record<string, unknown> {
242
- const root = isObj(config) ? { ...config } : {};
243
- const providers = isObj(root.providers) ? { ...root.providers } : {};
244
- delete providers[name];
245
- root.providers = providers;
246
- return root;
247
- }
248
-
249
- export function providerNames(config: unknown): string[] {
250
- return isObj(config) && isObj(config.providers) ? Object.keys(config.providers) : [];
251
- }
252
-
253
- /** Pure patch of one provider's scalar fields (endpoint, id, display name, inline key).
254
- * `undefined` drops the field; models, compat, headers and every sibling survive — the
255
- * same contract as {@link withProviderModels}. */
256
- export function withProviderFields(config: unknown, name: string, patch: Record<string, string | undefined>): Record<string, unknown> {
257
- const root = isObj(config) ? { ...config } : {};
258
- const providers = isObj(root.providers) ? { ...root.providers } : {};
259
- const next: Record<string, unknown> = { ...(isObj(providers[name]) ? providers[name] : {}), ...patch };
260
- for (const [key, value] of Object.entries(next)) if (value === undefined) delete next[key];
261
- providers[name] = next;
262
- root.providers = providers;
263
- return root;
264
- }
265
-
266
- /** Pure rename: the provider keeps its position in the list, and a `name` that only
267
- * repeated the old id follows it (a hand-written display name stays as written). */
268
- export function renameProvider(config: unknown, from: string, to: string): Record<string, unknown> {
269
- const root = isObj(config) ? { ...config } : {};
270
- const providers = isObj(root.providers) ? { ...root.providers } : {};
271
- if (!(from in providers)) return root;
272
- root.providers = Object.fromEntries(
273
- Object.entries(providers).map(([key, value]): [string, unknown] => {
274
- if (key !== from) return [key, value];
275
- const entry: Record<string, unknown> = isObj(value) ? { ...value } : {};
276
- if (entry.name === from) entry.name = to;
277
- return [to, entry];
278
- }),
279
- );
280
- return root;
281
- }
282
-
283
- /** The credential follows its provider in auth.json; a provider with no entry stays without one. */
284
- export function renameAuth(auth: unknown, from: string, to: string): Record<string, unknown> {
285
- const root = isObj(auth) ? { ...auth } : {};
286
- if (!(from in root)) return root;
287
- return Object.fromEntries(Object.entries(root).map(([key, value]): [string, unknown] => [key === from ? to : key, value]));
288
- }
289
-
290
- export interface ProviderSummary {
291
- name: string;
292
- api?: string;
293
- modelCount: number;
294
- }
295
-
296
- export function summarizeProviders(config: unknown): ProviderSummary[] {
297
- if (!isObj(config) || !isObj(config.providers)) return [];
298
- return Object.entries(config.providers).map(([name, value]) => {
299
- const entry = isObj(value) ? value : {};
300
- const models = Array.isArray(entry.models) ? entry.models.length : 0;
301
- return { name, api: typeof entry.api === "string" ? entry.api : undefined, modelCount: models };
302
- });
303
- }
304
-
305
- /** Pure merge: the auth.json credential `/login` writes, keyed by provider id. */
306
- export function withAuth(auth: unknown, name: string, key: string): Record<string, unknown> {
307
- const root = isObj(auth) ? { ...auth } : {};
308
- root[name] = { type: "api_key", key };
309
- return root;
310
- }
311
-
312
- export function withoutAuth(auth: unknown, name: string): Record<string, unknown> {
313
- const root = isObj(auth) ? { ...auth } : {};
314
- delete root[name];
315
- return root;
316
- }
317
-
318
- /** Rewrites one provider's model list and nothing else — compat, headers, name, every
319
- * sibling field survives an edit exactly as it was stored. Levels serialize to pi's
320
- * wire shape: `reasoning` for anything thinking, plus a `thinkingLevelMap` whose pinned
321
- * level is a ceiling: every effort up to it maps to itself, every level above it is null,
322
- * and `off` stays unmapped. pi reads null as unsupported, so the old map that nulled every
323
- * level but one left the user stuck on that level, unable to lower it or turn thinking off. */
324
- export function levelToWire(level: ThinkingSetting | undefined): { reasoning?: true; thinkingLevelMap?: Record<string, string | null> } {
325
- if (level === undefined || level === "off") return {};
326
- if (level === "auto") return { reasoning: true };
327
- const ceiling = THINKING_LEVELS.indexOf(level);
328
- const thinkingLevelMap: Record<string, string | null> = {};
329
- THINKING_LEVELS.forEach((l, i) => {
330
- if (l !== "off") thinkingLevelMap[l] = i <= ceiling ? l : null;
331
- });
332
- return { reasoning: true, thinkingLevelMap };
333
- }
334
-
335
- /** Reads pi's wire shape back into a level: the highest level mapped to itself is that level
336
- * when every level above it is null (a ceiling, or the old single-pin shape). Any other map
337
- * (heal's default, a probed remap) and `reasoning: true` alone are `auto`. */
338
- export function wireToLevel(reasoning: unknown, map: unknown): ThinkingSetting {
339
- if (isObj(map)) {
340
- const levels = THINKING_LEVELS.filter((l) => l !== "off");
341
- const top = levels.findLastIndex((l) => map[l] === l);
342
- if (top !== -1 && levels.slice(top + 1).every((l) => map[l] === null)) {
343
- // A ceiling maps every level below it to itself; the old single pin nulls them all.
344
- // Anything else (an exact probed map with gaps) is a map, not a pin.
345
- const below = levels.slice(0, top);
346
- if (below.every((l) => map[l] === l) || below.every((l) => map[l] === null)) return levels[top]!;
347
- }
348
- }
349
- return reasoning === true ? "auto" : "off";
350
- }
351
-
352
- export function withProviderModels(config: unknown, name: string, models: ProviderModel[]): Record<string, unknown> {
353
- const root = isObj(config) ? { ...config } : {};
354
- const providers = isObj(root.providers) ? { ...root.providers } : {};
355
- const base = isObj(providers[name]) ? providers[name] : {};
356
- const stated: Record<string, unknown>[] = Array.isArray(base.models) ? base.models.filter(isObj) : [];
357
- providers[name] = { ...base, models: wireModels(name, base, models, stated) };
358
- root.providers = providers;
359
- return root;
360
- }
361
-
362
- /** One model in pi's wire shape: the level (or a probed map), the compat flags the rules
363
- * imply, and the limits the probe found. Every other key of the stored entry survives —
364
- * only `reasoning` and `thinkingLevelMap` are rewritten, because the level owns them. */
365
- function wireModels(name: string, provider: { api?: unknown; baseUrl?: unknown }, models: ProviderModel[], stated: Record<string, unknown>[]): Record<string, unknown>[] {
366
- const api = typeof provider.api === "string" ? provider.api : undefined;
367
- const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl : "";
368
- return models.map((m) => {
369
- const prev = stated.find((s) => s.id === m.id);
370
- const next: Record<string, unknown> = { ...(prev ?? {}) };
371
- next.id = m.id;
372
- delete next.reasoning;
373
- delete next.thinkingLevelMap;
374
- Object.assign(next, m.map ? { reasoning: true, thinkingLevelMap: m.map } : levelToWire(m.level));
375
- const stored = isObj(next.compat) ? next.compat : {};
376
- const compat = { ...stored, ...suggestCompat({ provider: name, id: m.id, api, baseUrl, reasoning: next.reasoning === true, compat: stored }), ...(m.compat ?? {}) };
377
- if (Object.keys(compat).length > 0) next.compat = compat;
378
- const meta = m.meta ?? (prev && typeof prev === "object" ? { contextWindow: prev.contextWindow as number | undefined, maxTokens: prev.maxTokens as number | undefined } : undefined);
379
- if (meta?.contextWindow !== undefined) next.contextWindow = meta.contextWindow;
380
- if (meta?.maxTokens !== undefined) next.maxTokens = meta.maxTokens;
381
- return next;
382
- });
383
- }
384
-
385
- /** A stored selection keeps its level; a new id gets the detected one. A probed limit is
386
- * merged into the stored one, and a probed effort map travels with the level, so a reselect
387
- * never loses what an earlier probe learned (an `auto` level serializes without a map). */
388
- const PUBLIC_CATALOG_URL = "https://openrouter.ai/api/v1/models";
389
- const PUBLIC_CATALOG_TTL_MS = 60 * 60 * 1000;
390
- let publicCatalogCache: { index: CatalogIndex; at: number } | undefined;
391
-
392
- type RegistryLike = { getAll?: () => readonly { id?: unknown; contextWindow?: unknown; maxTokens?: unknown }[] };
393
-
394
- async function fetchPublicCatalog(fetchImpl: FetchLike, timeoutMs = 5_000): Promise<CatalogIndex | undefined> {
395
- if (fetchImpl === fetch && publicCatalogCache && Date.now() - publicCatalogCache.at < PUBLIC_CATALOG_TTL_MS) {
396
- return publicCatalogCache.index;
397
- }
398
- try {
399
- const res = await fetchImpl(PUBLIC_CATALOG_URL, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(timeoutMs) });
400
- if (!res.ok) return undefined;
401
- const parsed = parseModelMeta(await res.json());
402
- const index = buildCatalogIndex(parsed);
403
- if (fetchImpl === fetch) publicCatalogCache = { index, at: Date.now() };
404
- return index;
405
- } catch {
406
- return undefined;
407
- }
408
- }
409
-
410
- /** Fill missing `contextWindow` (and `maxTokens`) for picked models from pi's local
411
- * model registry first, then from OpenRouter's public catalog if any still lack one. */
412
- export async function resolveMissingMeta(
413
- ids: readonly string[],
414
- baseMeta: Map<string, ModelMeta> | undefined,
415
- ctx: { modelRegistry?: RegistryLike } | undefined,
416
- fetchImpl: FetchLike = fetch,
417
- ): Promise<Map<string, ModelMeta>> {
418
- const out = new Map<string, ModelMeta>(baseMeta ?? []);
419
- let missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
420
- if (missing.length === 0) return out;
421
-
422
- // Tier 1: pi's built-in catalog and already-configured providers (instant, offline).
423
- try {
424
- const all = ctx?.modelRegistry?.getAll?.() ?? [];
425
- const entries: [string, ModelMeta][] = [];
426
- for (const m of all) {
427
- if (typeof m?.id !== "string" || typeof m.contextWindow !== "number" || m.contextWindow <= 0) continue;
428
- entries.push([m.id, { contextWindow: m.contextWindow, ...(typeof m.maxTokens === "number" && m.maxTokens > 0 ? { maxTokens: m.maxTokens } : {}) }]);
429
- }
430
- if (entries.length > 0) {
431
- const localIdx = buildCatalogIndex(entries);
432
- for (const id of missing) {
433
- const found = findMetaForId(id, localIdx);
434
- if (found) out.set(id, mergeMeta(out.get(id), found));
435
- }
436
- }
437
- } catch {
438
- // Stale or partial registry must never block saving a provider.
439
- }
440
-
441
- missing = ids.filter((id) => out.get(id)?.contextWindow === undefined);
442
- if (missing.length === 0) return out;
443
-
444
- // Tier 2: public model catalog for open/commercial models not yet in local registry.
445
- const publicIdx = await fetchPublicCatalog(fetchImpl);
446
- if (publicIdx) {
447
- for (const id of missing) {
448
- const found = findMetaForId(id, publicIdx);
449
- if (found) out.set(id, mergeMeta(out.get(id), found));
450
- }
451
- }
452
- return out;
453
- }
454
-
455
- const seedMeta = (entry: ProviderEntry, extra?: Map<string, ModelMeta>): Map<string, ModelMeta> => {
456
- const out = new Map<string, ModelMeta>();
457
- for (const m of entry.models) if (m.meta) out.set(m.id, m.meta);
458
- if (extra) for (const [id, meta] of extra) out.set(id, mergeMeta(out.get(id), meta));
459
- return out;
460
- };
461
-
462
- export function mergeLevels(entry: ProviderEntry, ids: string[], meta?: Map<string, ModelMeta>): ProviderModel[] {
463
- return ids.map((id) => {
464
- const existing = entry.models.find((m) => m.id === id);
465
- const found = meta?.get(id);
466
- return { id, level: existing?.level ?? detectLevel(id), map: existing?.map, meta: found ? mergeMeta(existing?.meta, found) : existing?.meta };
467
- });
468
- }
469
-
470
- const modelsPath = (): string => join(getAgentDir(), "models.json");
471
- const authPath = (): string => join(getAgentDir(), "auth.json");
472
-
473
- /** pi's own models.json tolerance, replicated exactly: `//` comments and trailing
474
- * commas are dropped outside string literals, so the wizard accepts every file pi's
475
- * ModelConfig accepts — a hand-edited file never blocks the menu. */
476
- export function looseJsonParse(content: string): unknown {
477
- const stripped = content
478
- .replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : ""))
479
- .replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m, tail?: string) => tail ?? (m[0] === '"' ? m : ""));
480
- return JSON.parse(stripped) as unknown;
481
- }
482
-
483
- /** Missing file → undefined. Corrupt JSON is thrown, never overwritten: the caller aborts
484
- * and reports, so a broken models.json cannot be clobbered by a save. Reads with pi's
485
- * tolerance: BOM stripped, comments and trailing commas dropped before JSON.parse. */
486
- function readJson(path: string): unknown {
487
- let content: string;
488
- try {
489
- content = readFileSync(path, "utf8");
490
- } catch {
491
- return undefined;
492
- }
493
- if (content.trim() === "") return undefined;
494
- return looseJsonParse(content.replace(/^\uFEFF/, ""));
495
- }
496
-
497
- function writeJson(path: string, value: unknown): void {
498
- writeAtomicSync(path, `${JSON.stringify(value, null, 2)}\n`);
499
- }
500
-
501
- export function loadModelsConfig(): unknown {
502
- return readJson(modelsPath());
503
- }
504
-
505
- /** Replace models.json whole, atomically (Model Heal writes a config it read and edited). */
506
- export function saveModelsConfig(value: unknown): void {
507
- writeJson(modelsPath(), value);
508
- }
509
-
510
- export function saveProvider(name: string, entry: ProviderEntry, key: string | undefined): void {
511
- writeJson(modelsPath(), withProvider(readJson(modelsPath()), name, entry));
512
- if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
513
- }
514
-
515
- /** Writes one provider's key: a real key lands in auth.json (the file /login writes, and the
516
- * credential pi prefers over an inline models.json apiKey), `undefined` removes it. A
517
- * literal inline key is dropped from models.json so the secret lives in one place; an
518
- * env-var or shell reference is configuration, not a secret, and stays put. */
519
- export function saveProviderKey(name: string, key: string | undefined): void {
520
- const auth = readJson(authPath());
521
- // Nothing stored and nothing to store: leave a missing auth.json missing.
522
- if (key || (isObj(auth) && name in auth)) writeJson(authPath(), key ? withAuth(auth, name, key) : withoutAuth(auth, name));
523
- const config = readJson(modelsPath());
524
- const entry = isObj(config) && isObj(config.providers) && isObj(config.providers[name]) ? (config.providers[name] as Record<string, unknown>) : undefined;
525
- if (!entry || typeof entry.apiKey !== "string" || /^[$!]/.test(entry.apiKey)) return;
526
- writeJson(modelsPath(), withProviderFields(config, name, { apiKey: undefined }));
527
- }
528
-
529
- /** `dummy`/`ollama` are placeholders a keyless entry carries so pi can list its models;
530
- * `$VAR`, `${VAR}` and `!command` are references, not secrets. Neither is a stored key. */
531
- const PLACEHOLDER_KEYS = new Set(["dummy", "ollama"]);
532
- export function inlineKey(entry: ProviderEntry): string | undefined {
533
- const value = entry.apiKey;
534
- if (!value || PLACEHOLDER_KEYS.has(value) || /^[$!]/.test(value)) return undefined;
535
- return value;
536
- }
537
-
538
- /** One secret as it may be shown on screen: its last four characters, never the whole key. */
539
- export function keyHint(key: string): string {
540
- return key.length > 8 ? `••••${key.slice(-4)}` : "••••";
541
- }
542
-
543
- export function deleteProviderNamed(name: string): boolean {
544
- const config = readJson(modelsPath());
545
- if (!providerNames(config).includes(name)) return false;
546
- writeJson(modelsPath(), withoutProvider(config, name));
547
- writeJson(authPath(), withoutAuth(readJson(authPath()), name));
548
- return true;
549
- }
550
-
551
- /** The stored credential for a provider, from the same auth.json /login writes. */
552
- export function readAuthKey(name: string): string | undefined {
553
- const auth = readJson(authPath());
554
- if (!isObj(auth) || !isObj(auth[name])) return undefined;
555
- const entry = auth[name] as Record<string, unknown>;
556
- if (entry.type === "api_key" && typeof entry.key === "string") return entry.key;
557
- return undefined;
558
- }
559
-
560
- /** The stored entry with its models typed; extra fields stay in the raw config (edits go
561
- * through {@link withProviderModels}, which never drops them). */
562
- export function loadProviderEntry(config: unknown, name: string): ProviderEntry | undefined {
563
- if (!isObj(config) || !isObj(config.providers)) return undefined;
564
- const value = (config.providers as Record<string, unknown>)[name];
565
- if (!isObj(value)) return undefined;
566
- const models: ProviderModel[] = Array.isArray(value.models)
567
- ? (value.models as unknown[]).flatMap((m): ProviderModel[] => {
568
- if (!isObj(m) || typeof m.id !== "string") return [];
569
- const level = wireToLevel(m.reasoning, m.thinkingLevelMap);
570
- const contextWindow = typeof m.contextWindow === "number" ? m.contextWindow : undefined;
571
- const maxTokens = typeof m.maxTokens === "number" ? m.maxTokens : undefined;
572
- const meta = contextWindow === undefined && maxTokens === undefined ? undefined : { contextWindow, maxTokens };
573
- // An `auto` model keeps its stored map, so a later save never wipes what a probe learned.
574
- const map = level === "auto" && isObj(m.thinkingLevelMap) ? (m.thinkingLevelMap as Record<string, string | null>) : undefined;
575
- return [{ id: m.id, ...(level === "off" ? {} : { level }), ...(map ? { map } : {}), ...(meta ? { meta } : {}), ...(isObj(m.compat) ? { compat: m.compat } : {}) }];
576
- })
577
- : [];
578
- return {
579
- name: typeof value.name === "string" ? value.name : name,
580
- baseUrl: typeof value.baseUrl === "string" ? value.baseUrl : "",
581
- api: (typeof value.api === "string" ? value.api : "openai-completions") as ApiFlavor,
582
- apiKey: typeof value.apiKey === "string" ? value.apiKey : undefined,
583
- models,
584
- };
585
- }
11
+ import {
12
+ API_FLAVORS,
13
+ FLAVOR_LABELS,
14
+ THINKING_LEVELS,
15
+ authPath,
16
+ chatBaseUrl,
17
+ deleteProviderNamed,
18
+ detectLevel,
19
+ guessProviderName,
20
+ inlineKey,
21
+ isObj,
22
+ keyHint,
23
+ levelToWire,
24
+ loadModelsConfig,
25
+ loadProviderEntry,
26
+ mergeLevels,
27
+ modelsPath,
28
+ normalizeBase,
29
+ probeEndpoint,
30
+ providerNames,
31
+ readAuthKey,
32
+ readJson,
33
+ renameAuth,
34
+ renameProvider,
35
+ resolveMissingMeta,
36
+ saveProvider,
37
+ saveProviderKey,
38
+ seedMeta,
39
+ summarizeProviders,
40
+ withProviderFields,
41
+ withProviderModels,
42
+ writeJson,
43
+ type ApiFlavor,
44
+ type ProbeResult,
45
+ type ProviderEntry,
46
+ type ProviderModel,
47
+ type ProviderSummary,
48
+ type ThinkingLevel,
49
+ type ThinkingSetting,
50
+ } from "./provider-store.ts";
51
+
52
+ export * from "./provider-store.ts";
586
53
 
587
54
  // ---------------------------------------------------------------- wizard
588
55
 
@@ -1367,275 +834,9 @@ export const openProviders = async (ctx: ExtensionCommandContext): Promise<boole
1367
834
  }
1368
835
  };
1369
836
 
1370
- // Self-check: `node lib/provider.ts`
1371
- if (isMain(import.meta.url)) {
1372
- // Flavors and bases.
1373
- assert(chatBaseUrl("openai-completions", "https://api.x.com/v1") === "https://api.x.com/v1", "openai keeps an explicit /v1");
1374
- assert(chatBaseUrl("openai-completions", "https://api.x.com") === "https://api.x.com/v1", "openai appends /v1");
1375
- assert(chatBaseUrl("openai-completions", "https://api.x.com/v1beta/") === "https://api.x.com/v1", "openai rewrites /v1beta to /v1");
1376
- assert(chatBaseUrl("anthropic-messages", "https://relay.x.com/v1") === "https://relay.x.com", "anthropic strips /v1");
1377
- assert(chatBaseUrl("google-generative-ai", "https://relay.x.com/v1beta") === "https://relay.x.com", "gemini strips /v1beta");
1378
- assert(normalizeBase("localhost:11434") === "http://localhost:11434", "bare host defaults to http");
1379
- assert(normalizeBase(" https://x.com/ ") === "https://x.com", "trailing slashes trimmed");
1380
- assert(guessProviderName("https://api.deepseek.com/v1") === "deepseek", "api prefix and tld dropped");
1381
- assert(guessProviderName("https://openrouter.ai/api/v1") === "openrouter", "openrouter keeps its name");
1382
- assert(guessProviderName("http://localhost:11434") === "localhost", "localhost stays localhost");
1383
- assert(guessProviderName("http://192.168.1.10:11434") === "192.168.1.10", "an IP is kept verbatim");
1384
-
1385
- // Probe parsing.
1386
- const listPath = buildCandidates("https://x.com/v1", "k").find((c) => c.url === "https://x.com/v1/models")!;
1387
- assert(listPath.url === "https://x.com/v1/models", "a /v1 base probes /models");
1388
- const paths = buildCandidates("https://x.com", "").map((c) => c.url);
1389
- assert(paths.includes("https://x.com/v1/models") && paths.includes("https://x.com/api/tags") && paths.includes("https://x.com/v1beta/models"), "a bare base probes the common layouts");
1390
- const authed = buildCandidates("https://x.com", "sk-1")[0]!;
1391
- assert(authed.url === "https://x.com/api/tags", "the ollama probe comes first");
1392
- const openaiShape = { data: [{ id: "m1", context_length: 262_144, max_output_tokens: 32_000 }, { id: "m2" }] };
1393
- const geminiShape = { models: [{ name: "models/gemini-x" }] };
1394
- const ollamaShape = { models: [{ name: "qwen:7b" }] };
1395
- assert(parseModelList(listPath, openaiShape)!.join() === "m1,m2", "data[].id parses");
1396
- assert(parseModelList(listPath, geminiShape) === undefined, "a models[] shape is not a list answer for openai paths");
1397
- const geminiCandidate = buildCandidates("https://x.com", "k").find((c) => c.url.endsWith("/v1beta/models"))!;
1398
- assert(parseModelList(geminiCandidate, geminiShape)![0] === "gemini-x", "gemini strips the models/ prefix");
1399
- const ollamaCandidate = buildCandidates("https://x.com", "k").find((c) => c.url.endsWith("/api/tags"))!;
1400
- assert(parseModelList(ollamaCandidate, ollamaShape)![0] === "qwen:7b", "ollama keeps the tag verbatim");
1401
- assert(parseModelList(listPath, { data: "no" }) === undefined, "a non-array data is no list");
1402
- assert(parseModelList(listPath, "nope") === undefined, "a scalar body is no list");
1403
-
1404
- // Probe priority with a fake fetch routed by path — the same layout every real server
1405
- // has: each endpoint answers only its own shape, the rest 404.
1406
- const route = (map: Record<string, unknown>) => async (url: string) => {
1407
- const body = map[new URL(url).pathname];
1408
- if (body === undefined) return { ok: false, status: 404, json: async () => ({}) };
1409
- return { ok: true, status: 200, json: async () => body };
1410
- };
1411
- const probeOllama = await probeEndpoint("http://localhost:11434", "", route({ "/api/tags": ollamaShape }));
1412
- assert(probeOllama?.flavor === "openai-completions" && probeOllama.via === "/api/tags" && probeOllama.keyless, "an ollama answer wins and is keyless");
1413
- assert(probeOllama?.baseUrl === "http://localhost:11434/v1", "the ollama chat base gets /v1");
1414
- const probeGemini = await probeEndpoint("https://relay.x.com", "k", route({ "/v1beta/models": geminiShape }));
1415
- assert(probeGemini?.flavor === "google-generative-ai" && probeGemini.models[0] === "gemini-x", "a gemini answer is detected");
1416
- const probeOpenai = await probeEndpoint("https://api.x.com/v1", "k", route({ "/v1/models": openaiShape }));
1417
- assert(probeOpenai?.flavor === "openai-completions" && probeOpenai.baseUrl === "https://api.x.com/v1", "an openai answer is detected");
1418
- assert(probeOpenai?.meta.get("m1")?.contextWindow === 262_144 && probeOpenai.meta.get("m1")?.maxTokens === 32_000, "the same answer carries the limits, so no second request is needed");
1419
- const none = await probeEndpoint("https://api.x.com", "", route({}));
1420
- assert(none === undefined, "no answer → undefined, the caller falls back to manual entry");
1421
- const empty = await probeEndpoint("https://api.x.com/v1", "", route({ "/v1/models": { data: [] } }));
1422
- assert(empty === undefined, "an empty list is no answer");
1423
-
1424
- // Store merges: one provider in, one out, everything else preserved.
1425
- const config = { providers: { a: { baseUrl: "x", api: "openai-completions", models: [] } }, other: 1 };
1426
- const added = withProvider(config, "b", { baseUrl: "y", api: "anthropic-messages", models: [{ id: "m" }] });
1427
- assert((added.providers as Record<string, unknown>).a !== undefined && added.other === 1, "withProvider preserves other keys and providers");
1428
- assert((config.providers as Record<string, unknown>).b === undefined, "withProvider does not mutate its input");
1429
- assert(providerNames(withoutProvider(added, "a")).join() === "b", "withoutProvider removes one");
1430
- assert(summarizeProviders(added)[1]!.modelCount === 1, "summarize counts models");
1431
- assert(summarizeProviders(undefined).length === 0, "summarize survives a missing file body");
1432
- assert(summarizeProviders({ providers: { a: {} } })[0]!.modelCount === 0, "summarize survives a provider without models");
1433
- const auth = withAuth({ a: { type: "api_key", key: "1" } }, "b", "2");
1434
- assert((auth.b as { key: string }).key === "2" && auth.a !== undefined, "withAuth adds one credential");
1435
- assert(withoutAuth(auth, "a").a === undefined, "withoutAuth removes one");
1436
-
1437
- // Secrets: the hint never shows more than the tail, and only a literal inline key counts.
1438
- assert(keyHint("sk-abcdefgh1234") === "••••1234", "the hint keeps the last four characters");
1439
- assert(keyHint("short") === "••••", "a short secret shows nothing at all");
1440
- assert(!keyHint("sk-abcdefgh1234").includes("abcdefgh"), "the body of the key never reaches the screen");
1441
- assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "dummy", models: [] }) === undefined, "a placeholder is not a key");
1442
- assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "ollama", models: [] }) === undefined, "the keyless placeholder is not a key");
1443
- assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "$OPENAI_KEY", models: [] }) === undefined, "an env reference is not a key");
1444
- assert(inlineKey({ baseUrl: "b", api: "openai-completions", apiKey: "sk-1", models: [] }) === "sk-1", "a literal key is read back");
1445
-
1446
- // The Edit screen's patches: one field lands, the models and every sibling survive, and
1447
- // a rename keeps the provider's place in the list with its credential following it.
1448
- const fieldEntry = { providers: { r: { name: "r", baseUrl: "old", api: "openai-completions", apiKey: "sk-1", compat: { x: 1 }, models: [{ id: "m1" }] } } };
1449
- const patched = withProviderFields(fieldEntry, "r", { baseUrl: "https://new.example/v1" });
1450
- const patchedEntry = (patched.providers as Record<string, Record<string, unknown>>).r!;
1451
- assert(patchedEntry.baseUrl === "https://new.example/v1" && patchedEntry.apiKey === "sk-1", "withProviderFields rewrites the named field only");
1452
- assert((patchedEntry.models as unknown[]).length === 1 && patchedEntry.compat !== undefined, "an endpoint edit keeps models and compat");
1453
- assert(((fieldEntry.providers as Record<string, Record<string, unknown>>).r!).baseUrl === "old", "withProviderFields does not mutate its input");
1454
- assert((withProviderFields(fieldEntry, "r", { apiKey: undefined }).providers as Record<string, Record<string, unknown>>).r!.apiKey === undefined, "an undefined patch drops the field");
1455
- const renamed = renameProvider({ providers: { a: { name: "a", models: [{ id: "m" }] }, b: { name: "" } } }, "a", "c");
1456
- assert(providerNames(renamed).join() === "c,b", "renameProvider keeps the position and changes the id");
1457
- assert((renamed.providers as Record<string, { name?: string; models?: unknown[] }>).c!.name === "c", "a name that repeated the old id follows it");
1458
- assert(((renamed.providers as Record<string, { models?: unknown[] }>).c!.models ?? []).length === 1, "a rename keeps the models");
1459
- assert((renameProvider({ providers: { a: { name: "Keep" } } }, "a", "c").providers as Record<string, { name?: string }>).c!.name === "Keep", "a hand-written display name is untouched");
1460
- assert((renameProvider({ providers: { a: {} } }, "missing", "c").providers as Record<string, unknown>).a !== undefined, "renaming a missing provider writes nothing");
1461
- const movedAuth = renameAuth({ a: { type: "api_key", key: "1" }, b: { type: "api_key", key: "2" } }, "a", "c");
1462
- assert((movedAuth.c as { key: string }).key === "1" && movedAuth.a === undefined && (movedAuth.b as { key: string }).key === "2", "renameAuth moves one credential");
1463
- assert(renameAuth({}, "a", "c").a === undefined, "an absent credential is not invented");
1464
-
1465
- // The model picker screen: checks toggle, `a` cycles, Esc leaves, Enter returns the ids.
1466
- const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
1467
- const renderModels = (checked: Set<string>, rows: ListRow[]) =>
1468
- new ListPicker(fakeTheme, rows, undefined, {
1469
- preview: () => {},
1470
- revert: () => {},
1471
- done: () => {},
1472
- requestRender: () => {},
1473
- marked: (label) => checked.has(label),
1474
- }, { title: screenTitle("Models"), description: "d", legend: MODEL_LEGEND }, false).render(60).map(stripAnsi);
1475
- const picked0 = renderModels(new Set(["m1"]), [{ label: "m1" }, { label: "m2" }]);
1476
- assert(picked0.some((l) => l.includes("[x] m1")) && picked0.some((l) => l.includes("[ ] m2")), "checked and unchecked rows render");
1477
- assert(picked0.some((l) => l.includes("[a] API")), "the model legend advertises the flavor switch");
1478
- // Models and Probe models share this screen, so the filter is checked once here.
1479
- const searchable = new ListPicker(fakeTheme, [{ label: "river/flash" }, { label: "river/glm" }, { label: "other/kimi" }], undefined, { preview: () => {}, revert: () => {}, done: () => {}, requestRender: () => {}, search: "models" }, { title: screenTitle("Models"), description: "d", legend: MODEL_LEGEND }, false);
1480
- assert(searchable.render(70).map(stripAnsi).some((l) => l.includes("> Type to filter models...")), "the idle model filter names the key-less placeholder");
1481
- searchable.handleInput("/");
1482
- for (const ch of "river glm") searchable.handleInput(ch);
1483
- const narrowed = searchable.render(70).map(stripAnsi);
1484
- assert(narrowed.filter((l) => /river\/(flash|glm)|other\/kimi/.test(l)).length === 1 && narrowed.some((l) => l.includes("river/glm")), "typing narrows the model list to the fuzzy match");
1485
- assert(searchable.index === 1, "the selection follows the filtered row back to its model");
1486
-
1487
- // The store reads with pi's own tolerance: a hand-edited models.json (comments, trailing
1488
- // commas) is exactly what pi itself accepts, and strings containing `//` or `,]` survive.
1489
- assert((looseJsonParse('{\n// c\n"a": 1, // x\n"b": [1, 2,],\n}') as { a: number; b: number[] }).b.join() === "1,2", "trailing commas and // comments are dropped");
1490
- const kept = looseJsonParse('{"u":"http://x//y","v":"a,b]"}') as Record<string, string>;
1491
- assert(kept.u === "http://x//y" && kept.v === "a,b]", "string literals survive the strip");
1492
- assert((looseJsonParse("{\"a\": 1,}") as { a: number }).a === 1, "a trailing comma before the closing brace parses");
1493
- let threw = false;
1494
- try {
1495
- looseJsonParse("{nope");
1496
- } catch {
1497
- threw = true;
1498
- }
1499
- assert(threw, "genuinely broken JSON still throws, so the caller can report it");
1500
-
1501
- // Thinking levels auto-detect from ids (relay catalogs expose only ids).
1502
- assert(detectLevel("ag/claude-opus-4-6-thinking") === "auto", "a thinking token means flexible thinking");
1503
- assert(detectLevel("ag/gemini-4-argon-high") === "high", "a -high suffix pins high");
1504
- assert(detectLevel("ag/gemini-4-argon-xhigh") === "xhigh", "an -xhigh suffix pins xhigh");
1505
- assert(detectLevel("ag/gemini-4-argon-x-high") === "xhigh", "-x-high also pins xhigh");
1506
- assert(detectLevel("foo/bar-max") === "max", "a -max suffix pins max");
1507
- assert(detectLevel("foo/bar-medium") === "medium", "a -medium suffix pins medium");
1508
- assert(detectLevel("foo/bar-low") === "low", "a -low suffix pins low");
1509
- assert(detectLevel("foo/bar-minimal") === "minimal", "a -minimal suffix pins minimal");
1510
- assert(detectLevel("deepseek-reasoner") === "auto", "reasoner means flexible thinking");
1511
- assert(detectLevel("o1-mini") === "auto", "an o-generation id means flexible thinking");
1512
- assert(detectLevel("deepseek-r1") === "auto", "r1 means flexible thinking");
1513
- assert(detectLevel("ocz/mimo-v2.6-flash-free") === "auto", "a plain flash id starts at auto");
1514
- assert(detectLevel("oc/big-pickle") === "auto", "an unrelated id starts at auto");
1515
-
1516
- // Levels serialize to pi's wire shape and read back unchanged.
1517
- const wireHigh = levelToWire("high") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
1518
- assert(wireHigh.reasoning === true, "a pinned level sets reasoning");
1519
- assert(wireHigh.thinkingLevelMap?.high === "high", "the pinned level maps to itself");
1520
- assert(wireHigh.thinkingLevelMap?.medium === "medium" && wireHigh.thinkingLevelMap?.minimal === "minimal", "levels below the ceiling stay available");
1521
- assert(wireHigh.thinkingLevelMap?.xhigh === null && wireHigh.thinkingLevelMap?.max === null, "levels above the ceiling are null");
1522
- assert(!("off" in wireHigh.thinkingLevelMap!), "off stays unmapped, so thinking can still be turned off");
1523
- assert(wireToLevel(true, { off: null, minimal: null, low: null, medium: null, high: null, xhigh: "xhigh", max: null }) === "xhigh", "the old single-pin shape still reads as its level");
1524
- assert(wireToLevel(true, { low: "low", medium: "medium", high: "high", xhigh: "xhigh" }) === "auto", "heal's default map is auto, not an xhigh pin");
1525
- assert(wireToLevel(true, { medium: "high" }) === "auto", "a probed remap is auto");
1526
- assert(wireToLevel(true, { minimal: null, low: "low", medium: null, high: "high", xhigh: null, max: "max" }) === "auto", "an exact probed map with gaps is auto, not a max ceiling");
1527
- assert(loadProviderEntry({ providers: { p: { models: [{ id: "m", reasoning: true, thinkingLevelMap: { medium: null } }] } } }, "p")?.models[0]?.map?.medium === null, "a probed map survives a reload");
1528
- for (const l of ["minimal", "low", "medium", "high", "xhigh", "max"] as const) assert(wireToLevel(true, levelToWire(l).thinkingLevelMap) === l, `wire round-trips ${l}`);
1529
- assert(levelToWire("xhigh")!.thinkingLevelMap!.xhigh === "xhigh", "xhigh needs its explicit map entry");
1530
- const wireAuto = levelToWire("auto") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
1531
- assert(wireAuto.reasoning === true && wireAuto.thinkingLevelMap === undefined, "auto is reasoning without a map");
1532
- assert(Object.keys(levelToWire("off")).length === 0, "off writes no flags");
1533
- assert(wireToLevel(true, undefined) === "auto" && wireToLevel(false, undefined) === "off", "wire round-trips auto and off");
1534
- assert(wireToLevel(true, levelToWire("medium").thinkingLevelMap) === "medium", "wire round-trips a pinned level");
1535
-
1536
- // Edit flows rewrite only `models` and keep every other provider field.
1537
- const rich = { providers: { r: { name: "R", baseUrl: "b", api: "openai-completions", compat: { supportsLongCacheRetention: false }, models: [{ id: "m1", reasoning: true }] } } };
1538
- const edited = withProviderModels(rich, "r", [{ id: "m2", level: "high" }]);
1539
- const savedProvider = (edited.providers as Record<string, Record<string, unknown>>).r!;
1540
- assert(savedProvider.compat !== undefined && savedProvider.name === "R", "withProviderModels keeps sibling fields");
1541
- const savedModels = savedProvider.models as { id: string; reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> }[];
1542
- assert(savedModels[0]!.id === "m2" && savedModels[0]!.reasoning === true && savedModels[0]!.thinkingLevelMap?.high === "high", "withProviderModels serializes the level");
1543
- const savedCompat = (savedModels[0] as { compat?: Record<string, unknown> }).compat;
1544
- assert(savedCompat?.supportsLongCacheRetention === false && savedCompat?.sendSessionAffinityHeaders === true, "a save writes the compat flags a relay needs");
1545
-
1546
- // A probe's limits land in the entry and survive a later edit that does not mention them.
1547
- const withMeta = withProviderModels(rich, "r", [{ id: "m1", level: "auto", meta: { contextWindow: 1_000_000, maxTokens: 64_000 } }]);
1548
- const metaModels = (withMeta.providers as Record<string, { models: { id: string; contextWindow?: number; maxTokens?: number }[] }>).r!.models;
1549
- assert(metaModels[0]!.contextWindow === 1_000_000 && metaModels[0]!.maxTokens === 64_000, "a probed window and cap are written");
1550
- const keptMeta = withProviderModels(withMeta, "r", [{ id: "m1", level: "high" }]);
1551
- const keptModel = (keptMeta.providers as Record<string, { models: { contextWindow?: number; maxTokens?: number }[] }>).r!.models[0]!;
1552
- assert(keptModel.contextWindow === 1_000_000 && keptModel.maxTokens === 64_000, "an edit that says nothing about limits keeps them");
1553
- assert((loadProviderEntry(withMeta, "r")?.models[0]!.meta?.contextWindow ?? 0) === 1_000_000, "the limits load back as meta");
1554
- const probedMap = withProviderModels(rich, "r", [{ id: "m1", level: "auto", map: { medium: "high", xhigh: null } }]);
1555
- const probedModel = (probedMap.providers as Record<string, { models: { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> }[] }>).r!.models[0]!;
1556
- assert(probedModel.reasoning === true && probedModel.thinkingLevelMap?.medium === "high", "a probed map wins over the level's own pin");
1557
- const levelAfterProbe = withProviderModels(probedMap, "r", [{ id: "m1", level: "high" }]);
1558
- assert((levelAfterProbe.providers as Record<string, { models: { thinkingLevelMap?: Record<string, string | null> }[] }>).r!.models[0]!.thinkingLevelMap?.high === "high", "changing the level replaces the probed map");
1559
- const merged = mergeLevels({ name: "n", baseUrl: "b", api: "openai-completions", models: [{ id: "m1", level: "auto" }, { id: "m2", level: "off" }] }, ["m2", "x-thinking"]);
1560
- assert(merged[0]!.id === "m2" && merged[0]!.level === "off", "a stored chat model stays chat");
1561
- assert(merged[1]!.level === "auto", "a new id defaults to auto");
1562
- const keptFlag = mergeLevels({ name: "n", baseUrl: "b", api: "openai-completions", models: [{ id: "m1", level: "low" }] }, ["m1"]);
1563
- assert(keptFlag[0]!.level === "low", "a stored level survives a reselect");
1564
- // A reselect used to reserialize `auto` without its map, wiping every probed level.
1565
- const reselected = withProviderModels(probedMap, "r", mergeLevels(loadProviderEntry(probedMap, "r")!, ["m1"]));
1566
- const reselectedMap = (reselected.providers as Record<string, { models: { thinkingLevelMap?: Record<string, string | null> }[] }>).r!.models[0]!.thinkingLevelMap;
1567
- assert(reselectedMap?.medium === "high" && reselectedMap?.xhigh === null, "a reselect keeps the probed map");
1568
- const entryLoaded = loadProviderEntry(rich, "r");
1569
- assert(entryLoaded?.models[0]!.id === "m1" && entryLoaded.api === "openai-completions", "loadProviderEntry reads models and api");
1570
- assert(loadProviderEntry(rich, "missing") === undefined, "loadProviderEntry misses cleanly");
1571
- const roundTrip = loadProviderEntry(withProviderModels(rich, "r", [{ id: "m9", level: "xhigh" }]), "r");
1572
- assert(roundTrip?.models[0]!.level === "xhigh", "a saved level loads back as itself");
1573
- assert(levelsSummary([{ id: "a" }, { id: "b", level: "high" }, { id: "c", level: "auto" }]) === "2 thinking (high, auto)", "the save notify names the registered levels");
1574
- assert(levelsSummary([{ id: "a" }]) === "0 thinking", "an all-chat save says so plainly");
1575
- // The Thinking screen's bulk keys are Shift+letter: pi-tui lowercases a key id, so this
1576
- // pins that they stay distinct from the plain letters navigation already uses.
1577
- assert(matchesKey("R", "shift+r") && !matchesKey("r", "shift+r"), "Shift+R is its own key, not plain r");
1578
-
1579
- // The stored key is read back from auth.json in an isolated agent dir (never the user's).
1580
- const tmp = mkdtempSync(join(tmpdir(), "arnative-providers-"));
1581
- process.env.PI_CODING_AGENT_DIR = tmp;
1582
- saveProvider("t1", { name: "t1", baseUrl: "https://x.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-x");
1583
- assert(readAuthKey("t1") === "sk-x", "readAuthKey returns the stored key");
1584
- assert(readAuthKey("missing") === undefined, "readAuthKey misses cleanly");
1585
- // Atomicity: a save interrupted at the temp write (a directory sits where the temp file
1586
- // should go) must leave the previous config intact — the direct-write code it replaces
1587
- // truncated models.json on any mid-write failure.
1588
- const blockedTmp = join(tmp, `models.json.${process.pid}.tmp`);
1589
- mkdirSync(blockedTmp);
1590
- let interrupted = false;
1591
- try {
1592
- saveProvider("t2", { name: "t2", baseUrl: "https://y.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-y");
1593
- } catch {
1594
- interrupted = true;
1595
- }
1596
- assert(interrupted, "a blocked temp write surfaces the error instead of passing silently");
1597
- assert(providerNames(loadModelsConfig()).join() === "t1", "the previous config survives the interrupted save");
1598
- assert(readAuthKey("t2") === undefined, "the interrupted save never reached auth.json");
1599
- rmSync(blockedTmp, { recursive: true, force: true });
1600
-
1601
- // Automatic contextWindow fallback: probed > local modelRegistry > public catalog.
1602
- const resolved = await resolveMissingMeta(
1603
- ["probed-m", "zai-org/GLM-5.3-Flash", "public/only-model", "unknown-model"],
1604
- new Map([["probed-m", { contextWindow: 64_000 }]]),
1605
- { modelRegistry: { getAll: () => [{ id: "remote/river/zai-org/GLM-5.3-Flash", contextWindow: 1_000_000, maxTokens: 131_072 }] } },
1606
- route({ "/api/v1/models": { data: [{ id: "public/only-model", context_length: 200_000, top_provider: { max_completion_tokens: 16_384 } }] } }),
1607
- );
1608
- assert(resolved.get("probed-m")?.contextWindow === 64_000, "a probed contextWindow stays untouched");
1609
- assert(resolved.get("zai-org/GLM-5.3-Flash")?.contextWindow === 1_000_000, "missing window falls back to local modelRegistry");
1610
- assert(resolved.get("public/only-model")?.contextWindow === 200_000 && resolved.get("public/only-model")?.maxTokens === 16_384, "still-missing window falls back to public catalog");
1611
- assert(resolved.get("unknown-model") === undefined, "unknown models stay undefined without throwing");
1612
- const offline = await resolveMissingMeta(["x"], undefined, undefined, (async () => { throw new Error("offline"); }) as unknown as typeof fetch);
1613
- assert(offline.size === 0, "an offline public catalog failure degrades cleanly");
1614
- assert(readdirSync(tmp).every((f) => !f.endsWith(".tmp")), "a completed save leaves no temp files behind");
1615
- // Edit writes: the key moves to auth.json and leaves models.json, so the secret lives in
1616
- // one place; an env reference is configuration and stays put.
1617
- saveProvider("t3", { name: "t3", baseUrl: "https://z.com/v1", api: "openai-completions", apiKey: "sk-inline", models: [{ id: "m" }] }, undefined);
1618
- saveProviderKey("t3", "sk-edited");
1619
- assert(readAuthKey("t3") === "sk-edited", "an edited key lands in auth.json");
1620
- const t3 = (loadModelsConfig().providers as Record<string, Record<string, unknown>>).t3!;
1621
- assert(t3.apiKey === undefined, "the inline copy is dropped, so the secret lives in one place");
1622
- assert(t3.baseUrl === "https://z.com/v1" && (t3.models as unknown[]).length === 1, "the key edit leaves the rest of the entry alone");
1623
- saveProviderKey("t3", undefined);
1624
- assert(readAuthKey("t3") === undefined, "an empty key removes the credential");
1625
- saveProvider("t4", { name: "t4", baseUrl: "https://w.com/v1", api: "openai-completions", apiKey: "$W_KEY", models: [] }, undefined);
1626
- saveProviderKey("t4", "sk-y");
1627
- assert((loadModelsConfig().providers as Record<string, Record<string, unknown>>).t4!.apiKey === "$W_KEY", "an env reference survives an edit");
1628
- saveProvider("t5", { name: "t5", baseUrl: "https://v.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-t5");
1629
- saveModelsConfig(renameProvider(loadModelsConfig(), "t5", "t6"));
1630
- assert(providerNames(loadModelsConfig()).includes("t6") && !providerNames(loadModelsConfig()).includes("t5"), "a rename reaches models.json");
1631
- assert(loadProviderEntry(loadModelsConfig(), "t6")?.models[0]!.id === "m", "the renamed provider keeps its models");
1632
- delete process.env.PI_CODING_AGENT_DIR;
1633
- rmSync(tmp, { recursive: true, force: true });
1634
-
1635
- // The providers screen copy stays factual and pinned.
1636
- assert(PROVIDERS_TEXT.title === "Providers - Arnative\u2819", `providers title pinned, got ${PROVIDERS_TEXT.title}`);
1637
- assert(ADD_ROW === "+ Add provider", "the add row label is pinned");
1638
- assert(visibleWidth(PROVIDERS_TEXT.legend) > 0, "the screen carries a legend");
1639
-
1640
- console.log("provider.ts self-check OK");
1641
- }
837
+ export const __test = {
838
+ PROVIDERS_TEXT,
839
+ ADD_ROW,
840
+ MODEL_LEGEND,
841
+ levelsSummary,
842
+ };