@bismawy/pi-arnative 0.6.2 → 0.8.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -0
- package/README.md +20 -4
- package/extensions/arnative.ts +185 -195
- package/extensions/autocompact.ts +294 -0
- package/extensions/footer.ts +8 -3
- package/extensions/timestamps.ts +30 -1
- package/extensions/tools.ts +3 -3
- package/extensions/ui-render-tweaks.ts +12 -1
- package/extensions/usage.ts +90 -35
- package/lib/box.ts +8 -3
- package/lib/compat.ts +415 -0
- package/lib/list-picker.ts +409 -0
- package/lib/preset-store.ts +67 -9
- package/lib/provider.ts +1190 -0
- package/lib/shortcuts.ts +7 -4
- package/lib/usage-store.ts +90 -20
- package/package.json +3 -3
package/lib/provider.ts
ADDED
|
@@ -0,0 +1,1190 @@
|
|
|
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.
|
|
8
|
+
*/
|
|
9
|
+
import { matchesKey, visibleWidth } from "@earendil-works/pi-tui";
|
|
10
|
+
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, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
13
|
+
import { tmpdir } from "node:os";
|
|
14
|
+
import { dirname, join } from "node:path";
|
|
15
|
+
import { assert, isMain } from "../lib/check.ts";
|
|
16
|
+
import { buildEffortMap, isEffortProbeable, mergeMeta, parseModelMeta, probeEffort, suggestCompat, type Compat, type ModelMeta } from "./compat.ts";
|
|
17
|
+
import { screenTitle, type ScreenText } from "../lib/box.ts";
|
|
18
|
+
import { stripAnsi } from "../lib/ansi.ts";
|
|
19
|
+
import { INPUT_LEGEND, InputPicker, LIST_LEGEND_MOVE, ListPicker, rowText, type ListRow } from "./list-picker.ts";
|
|
20
|
+
|
|
21
|
+
// ---------------------------------------------------------------- flavors
|
|
22
|
+
|
|
23
|
+
/** The wire protocols pi implements. A provider entry names one; the probe guesses it. */
|
|
24
|
+
export const API_FLAVORS = ["openai-completions", "openai-responses", "anthropic-messages", "google-generative-ai"] as const;
|
|
25
|
+
export type ApiFlavor = (typeof API_FLAVORS)[number];
|
|
26
|
+
|
|
27
|
+
export const FLAVOR_LABELS: Record<ApiFlavor, string> = {
|
|
28
|
+
"openai-completions": "OpenAI Chat Completions",
|
|
29
|
+
"openai-responses": "OpenAI Responses",
|
|
30
|
+
"anthropic-messages": "Anthropic Messages",
|
|
31
|
+
"google-generative-ai": "Gemini (Generative Language)",
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Chat base for a flavor: the OpenAI implementations append to `/v1`, the Anthropic and
|
|
35
|
+
* Gemini ones carry their version in the path, so a `/v1` suffix there is a lie. */
|
|
36
|
+
export function chatBaseUrl(flavor: ApiFlavor, base: string): string {
|
|
37
|
+
const stripped = base.replace(/\/(v1|v1beta)\/?$/i, "");
|
|
38
|
+
if (flavor === "anthropic-messages" || flavor === "google-generative-ai") return stripped;
|
|
39
|
+
return /\/v\d+\w*$/.test(base) ? base.replace(/\/$/, "") : `${stripped}/v1`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `https://api.deepseek.com/v1` → `deepseek`; the offered default for the name input. */
|
|
43
|
+
export function guessProviderName(base: string): string {
|
|
44
|
+
try {
|
|
45
|
+
const host = new URL(base).hostname;
|
|
46
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host) || host === "localhost") return host;
|
|
47
|
+
const labels = host.split(".");
|
|
48
|
+
const generic = new Set(["api", "llm", "gateway", "proxy", "relay", "open", "cloud"]);
|
|
49
|
+
const named = labels.filter((l, i) => !(i === 0 && generic.has(l)));
|
|
50
|
+
const tld = new Set(["com", "ai", "org", "net", "io", "dev", "app", "cn", "id", "co"]);
|
|
51
|
+
const body = named.length > 1 && tld.has(named[named.length - 1]!) ? named.slice(0, -1) : named;
|
|
52
|
+
return body.join("-").toLowerCase().replace(/[^a-z0-9-]/g, "") || host;
|
|
53
|
+
} catch {
|
|
54
|
+
return "custom";
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Trim, default the scheme to `http://` for bare hosts (Ollama), drop trailing slashes. */
|
|
59
|
+
export function normalizeBase(input: string): string {
|
|
60
|
+
const trimmed = input.trim().replace(/\/+$/, "");
|
|
61
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)) return trimmed;
|
|
62
|
+
return `http://${trimmed}`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------- probe
|
|
66
|
+
|
|
67
|
+
export type ProbeShape = "openai" | "ollama" | "gemini";
|
|
68
|
+
|
|
69
|
+
export interface ProbeCandidate {
|
|
70
|
+
/** Full URL to GET. */
|
|
71
|
+
url: string;
|
|
72
|
+
/** Flavor a list at this URL implies. */
|
|
73
|
+
flavor: ApiFlavor;
|
|
74
|
+
/** Body shape this path serves; the parse is strict to it. */
|
|
75
|
+
shape: ProbeShape;
|
|
76
|
+
/** The endpoint works without a key (Ollama); the saved entry then carries a dummy key. */
|
|
77
|
+
keyless: boolean;
|
|
78
|
+
/** Extra headers for this probe only (the Gemini key header, the OpenAI/Anthropic set). */
|
|
79
|
+
headers?: Record<string, string>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** GETs whose answer decides flavor and model list, in priority order. */
|
|
83
|
+
export function buildCandidates(base: string, key: string): ProbeCandidate[] {
|
|
84
|
+
const keyless = !key;
|
|
85
|
+
const auth: Record<string, string> = key
|
|
86
|
+
? {
|
|
87
|
+
// Every header style at once: a strict server ignores the others.
|
|
88
|
+
authorization: `Bearer ${key}`,
|
|
89
|
+
"x-api-key": key,
|
|
90
|
+
"anthropic-version": "2023-06-01",
|
|
91
|
+
}
|
|
92
|
+
: {};
|
|
93
|
+
const candidates: ProbeCandidate[] = [
|
|
94
|
+
{ url: `${base}/api/tags`, flavor: "openai-completions", shape: "ollama", keyless: true },
|
|
95
|
+
{
|
|
96
|
+
url: `${base}/v1beta/models`,
|
|
97
|
+
flavor: "google-generative-ai",
|
|
98
|
+
shape: "gemini",
|
|
99
|
+
keyless: false,
|
|
100
|
+
headers: key ? { "x-goog-api-key": key } : undefined,
|
|
101
|
+
},
|
|
102
|
+
];
|
|
103
|
+
// A base already ending in `/v1` serves the list at `/models`; anything else tries the
|
|
104
|
+
// common layouts. Both answer `{data: [{id}]}` — openai-completions wins the tie, the
|
|
105
|
+
// model picker's `[a]` is the override for an Anthropic-shaped relay.
|
|
106
|
+
const listPaths = /\/v1$/.test(base) ? ["/models"] : ["/v1/models", "/models"];
|
|
107
|
+
for (const path of listPaths) {
|
|
108
|
+
candidates.push({ url: `${base}${path}`, flavor: "openai-completions", shape: "openai", keyless, headers: auth });
|
|
109
|
+
}
|
|
110
|
+
return candidates;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Model ids from a probed list body, or undefined when the body does not match the
|
|
114
|
+
* shape the path serves — a strict parse keeps a relay's answer on its own path. */
|
|
115
|
+
export function parseModelList(candidate: ProbeCandidate, body: unknown): string[] | undefined {
|
|
116
|
+
if (typeof body !== "object" || body === null) return undefined;
|
|
117
|
+
const record = body as Record<string, unknown>;
|
|
118
|
+
if (candidate.shape === "openai") {
|
|
119
|
+
if (!Array.isArray(record.data)) return undefined;
|
|
120
|
+
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");
|
|
121
|
+
}
|
|
122
|
+
if (!Array.isArray(record.models)) return undefined;
|
|
123
|
+
return record.models
|
|
124
|
+
.map((m) => (typeof m === "object" && m !== null ? (m as Record<string, unknown>).name : undefined))
|
|
125
|
+
.filter((n): n is string => typeof n === "string")
|
|
126
|
+
.map((n) => (candidate.shape === "gemini" ? n.replace(/^models\//, "") : n));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface ProbeResult {
|
|
130
|
+
flavor: ApiFlavor;
|
|
131
|
+
/** Chat base for the flavor (`chatBaseUrl`). */
|
|
132
|
+
baseUrl: string;
|
|
133
|
+
models: string[];
|
|
134
|
+
/** `contextWindow`/`maxTokens` from the same answer — no second request. */
|
|
135
|
+
meta: Map<string, ModelMeta>;
|
|
136
|
+
/** Path that answered, for the notify line. */
|
|
137
|
+
via: string;
|
|
138
|
+
keyless: boolean;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export type FetchLike = (url: string, init?: { headers?: Record<string, string>; signal?: AbortSignal }) => Promise<{
|
|
142
|
+
ok: boolean;
|
|
143
|
+
status?: number;
|
|
144
|
+
json(): Promise<unknown>;
|
|
145
|
+
}>;
|
|
146
|
+
|
|
147
|
+
/** Probe once: every candidate GET runs in parallel, the first candidate in priority
|
|
148
|
+
* order that answers with a recognized model list wins. Undefined when none does. */
|
|
149
|
+
export async function probeEndpoint(base: string, key: string, fetchImpl: FetchLike = fetch, timeoutMs = 10_000): Promise<ProbeResult | undefined> {
|
|
150
|
+
const candidates = buildCandidates(base, key);
|
|
151
|
+
const settled = await Promise.allSettled(
|
|
152
|
+
candidates.map(async (candidate) => {
|
|
153
|
+
const response = await fetchImpl(candidate.url, {
|
|
154
|
+
headers: candidate.headers,
|
|
155
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
156
|
+
});
|
|
157
|
+
if (!response.ok) throw new Error(`HTTP ${response.status ?? "error"}`);
|
|
158
|
+
const body = await response.json();
|
|
159
|
+
const models = parseModelList(candidate, body);
|
|
160
|
+
if (!models || models.length === 0) throw new Error("no models");
|
|
161
|
+
return { candidate, models, meta: parseModelMeta(body) };
|
|
162
|
+
}),
|
|
163
|
+
);
|
|
164
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
165
|
+
const result = settled[i];
|
|
166
|
+
if (result?.status !== "fulfilled") continue;
|
|
167
|
+
const { candidate, models, meta } = result.value;
|
|
168
|
+
return {
|
|
169
|
+
flavor: candidate.flavor,
|
|
170
|
+
baseUrl: chatBaseUrl(candidate.flavor, base),
|
|
171
|
+
models: [...new Set(models)],
|
|
172
|
+
meta,
|
|
173
|
+
via: new URL(candidate.url).pathname,
|
|
174
|
+
keyless: candidate.keyless,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
return undefined;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------- stores
|
|
181
|
+
|
|
182
|
+
/** pi's thinking scale, in order — `/think` clamps a request to the nearest level a model
|
|
183
|
+
* supports, and `xhigh`/`max` only exist when the map names them. */
|
|
184
|
+
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
185
|
+
/** `auto` is not a pi level: it means `reasoning: true` with no map, so every `/think`
|
|
186
|
+
* level travels to the endpoint unchanged — for models that take an effort parameter. */
|
|
187
|
+
export type ThinkingSetting = ThinkingLevel | "auto";
|
|
188
|
+
export const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
189
|
+
export const THINKING_SETTINGS: ThinkingSetting[] = ["off", "auto", ...THINKING_LEVELS.slice(1)];
|
|
190
|
+
|
|
191
|
+
export interface ProviderModel {
|
|
192
|
+
id: string;
|
|
193
|
+
/** Thinking level; undefined means chat (no `reasoning` flag). */
|
|
194
|
+
level?: ThinkingSetting;
|
|
195
|
+
/** An effort map a probe produced; it wins over the level's own single pin. */
|
|
196
|
+
map?: Record<string, string | null>;
|
|
197
|
+
/** Stopped in the stored entry, so a reselect never loses it. */
|
|
198
|
+
meta?: ModelMeta;
|
|
199
|
+
compat?: Compat;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export interface ProviderEntry {
|
|
203
|
+
name?: string;
|
|
204
|
+
baseUrl: string;
|
|
205
|
+
api: ApiFlavor;
|
|
206
|
+
/** Set only when the endpoint needs no credential; a real key goes to auth.json. */
|
|
207
|
+
apiKey?: string;
|
|
208
|
+
models: ProviderModel[];
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Level heuristic over a relay catalog id: the catalogs expose only ids, so an explicit
|
|
212
|
+
* level suffix (`-high`, `-xhigh`, `-max`…) pins that level, and everything else starts at
|
|
213
|
+
* `auto` — the endpoint decides. A chat-only model is switched to `off` by hand in the
|
|
214
|
+
* Thinking screen; pi passes an unmapped level through, so an endpoint that rejects
|
|
215
|
+
* reasoning parameters only breaks when `/think` is above `off`. */
|
|
216
|
+
export function detectLevel(id: string): ThinkingSetting {
|
|
217
|
+
const s = id.toLowerCase();
|
|
218
|
+
if (/-x-?high$/.test(s)) return "xhigh";
|
|
219
|
+
if (/-max(imum)?$/.test(s)) return "max";
|
|
220
|
+
if (/-high$/.test(s)) return "high";
|
|
221
|
+
if (/-med(ium)?$/.test(s)) return "medium";
|
|
222
|
+
if (/-low$/.test(s)) return "low";
|
|
223
|
+
if (/-min(imal)?$/.test(s)) return "minimal";
|
|
224
|
+
return "auto";
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const isObj = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null;
|
|
228
|
+
|
|
229
|
+
/** Pure merge: one provider added or replaced, every other key preserved. */
|
|
230
|
+
export function withProvider(config: unknown, name: string, entry: ProviderEntry): Record<string, unknown> {
|
|
231
|
+
const root = isObj(config) ? { ...config } : {};
|
|
232
|
+
const providers = isObj(root.providers) ? { ...root.providers } : {};
|
|
233
|
+
// The same wire serialization every edit uses, so a first save and a later edit of the
|
|
234
|
+
// same provider produce the same models.json shape.
|
|
235
|
+
providers[name] = { ...entry, models: wireModels(name, entry, entry.models, []) };
|
|
236
|
+
root.providers = providers;
|
|
237
|
+
return root;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function withoutProvider(config: unknown, name: string): Record<string, unknown> {
|
|
241
|
+
const root = isObj(config) ? { ...config } : {};
|
|
242
|
+
const providers = isObj(root.providers) ? { ...root.providers } : {};
|
|
243
|
+
delete providers[name];
|
|
244
|
+
root.providers = providers;
|
|
245
|
+
return root;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function providerNames(config: unknown): string[] {
|
|
249
|
+
return isObj(config) && isObj(config.providers) ? Object.keys(config.providers) : [];
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export interface ProviderSummary {
|
|
253
|
+
name: string;
|
|
254
|
+
api?: string;
|
|
255
|
+
modelCount: number;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function summarizeProviders(config: unknown): ProviderSummary[] {
|
|
259
|
+
if (!isObj(config) || !isObj(config.providers)) return [];
|
|
260
|
+
return Object.entries(config.providers).map(([name, value]) => {
|
|
261
|
+
const entry = isObj(value) ? value : {};
|
|
262
|
+
const models = Array.isArray(entry.models) ? entry.models.length : 0;
|
|
263
|
+
return { name, api: typeof entry.api === "string" ? entry.api : undefined, modelCount: models };
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Pure merge: the auth.json credential `/login` writes, keyed by provider id. */
|
|
268
|
+
export function withAuth(auth: unknown, name: string, key: string): Record<string, unknown> {
|
|
269
|
+
const root = isObj(auth) ? { ...auth } : {};
|
|
270
|
+
root[name] = { type: "api_key", key };
|
|
271
|
+
return root;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function withoutAuth(auth: unknown, name: string): Record<string, unknown> {
|
|
275
|
+
const root = isObj(auth) ? { ...auth } : {};
|
|
276
|
+
delete root[name];
|
|
277
|
+
return root;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Rewrites one provider's model list and nothing else — compat, headers, name, every
|
|
281
|
+
* sibling field survives an edit exactly as it was stored. Levels serialize to pi's
|
|
282
|
+
* wire shape: `reasoning` for anything thinking, plus a `thinkingLevelMap` that pins
|
|
283
|
+
* exactly one supported level for a detected variant. */
|
|
284
|
+
export function levelToWire(level: ThinkingSetting | undefined): { reasoning?: true; thinkingLevelMap?: Record<string, string | null> } {
|
|
285
|
+
if (level === undefined || level === "off") return {};
|
|
286
|
+
if (level === "auto") return { reasoning: true };
|
|
287
|
+
const thinkingLevelMap: Record<string, string | null> = {};
|
|
288
|
+
for (const l of THINKING_LEVELS) thinkingLevelMap[l] = l === level ? level : null;
|
|
289
|
+
return { reasoning: true, thinkingLevelMap };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Reads pi's wire shape back into a level: a single non-off mapped level is that level;
|
|
293
|
+
* `reasoning: true` without a pin is `auto`. */
|
|
294
|
+
export function wireToLevel(reasoning: unknown, map: unknown): ThinkingSetting {
|
|
295
|
+
if (map !== null && typeof map === "object") {
|
|
296
|
+
const pinned = THINKING_LEVELS.filter((l) => l !== "off" && typeof (map as Record<string, unknown>)[l] === "string");
|
|
297
|
+
if (pinned.length === 1) return pinned[0]!;
|
|
298
|
+
}
|
|
299
|
+
return reasoning === true ? "auto" : "off";
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function withProviderModels(config: unknown, name: string, models: ProviderModel[]): Record<string, unknown> {
|
|
303
|
+
const root = isObj(config) ? { ...config } : {};
|
|
304
|
+
const providers = isObj(root.providers) ? { ...root.providers } : {};
|
|
305
|
+
const base = isObj(providers[name]) ? providers[name] : {};
|
|
306
|
+
const stated: Record<string, unknown>[] = Array.isArray(base.models) ? base.models.filter(isObj) : [];
|
|
307
|
+
providers[name] = { ...base, models: wireModels(name, base, models, stated) };
|
|
308
|
+
root.providers = providers;
|
|
309
|
+
return root;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** One model in pi's wire shape: the level (or a probed map), the compat flags the rules
|
|
313
|
+
* imply, and the limits the probe found. Every other key of the stored entry survives —
|
|
314
|
+
* only `reasoning` and `thinkingLevelMap` are rewritten, because the level owns them. */
|
|
315
|
+
function wireModels(name: string, provider: { api?: unknown; baseUrl?: unknown }, models: ProviderModel[], stated: Record<string, unknown>[]): Record<string, unknown>[] {
|
|
316
|
+
const api = typeof provider.api === "string" ? provider.api : undefined;
|
|
317
|
+
const baseUrl = typeof provider.baseUrl === "string" ? provider.baseUrl : "";
|
|
318
|
+
return models.map((m) => {
|
|
319
|
+
const prev = stated.find((s) => s.id === m.id);
|
|
320
|
+
const next: Record<string, unknown> = { ...(prev ?? {}) };
|
|
321
|
+
next.id = m.id;
|
|
322
|
+
delete next.reasoning;
|
|
323
|
+
delete next.thinkingLevelMap;
|
|
324
|
+
Object.assign(next, m.map ? { reasoning: true, thinkingLevelMap: m.map } : levelToWire(m.level));
|
|
325
|
+
const stored = isObj(next.compat) ? next.compat : {};
|
|
326
|
+
const compat = { ...stored, ...suggestCompat({ provider: name, id: m.id, api, baseUrl, reasoning: next.reasoning === true, compat: stored }), ...(m.compat ?? {}) };
|
|
327
|
+
if (Object.keys(compat).length > 0) next.compat = compat;
|
|
328
|
+
const meta = m.meta ?? (prev && typeof prev === "object" ? { contextWindow: prev.contextWindow as number | undefined, maxTokens: prev.maxTokens as number | undefined } : undefined);
|
|
329
|
+
if (meta?.contextWindow !== undefined) next.contextWindow = meta.contextWindow;
|
|
330
|
+
if (meta?.maxTokens !== undefined) next.maxTokens = meta.maxTokens;
|
|
331
|
+
return next;
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** A stored selection keeps its level; a new id gets the detected one. A probed limit is
|
|
336
|
+
* merged into the stored one, so a reselect never loses what an earlier probe learned. */
|
|
337
|
+
export function mergeLevels(entry: ProviderEntry, ids: string[], meta?: Map<string, ModelMeta>): ProviderModel[] {
|
|
338
|
+
return ids.map((id) => {
|
|
339
|
+
const existing = entry.models.find((m) => m.id === id);
|
|
340
|
+
const found = meta?.get(id);
|
|
341
|
+
return { id, level: existing?.level ?? detectLevel(id), meta: found ? mergeMeta(existing?.meta, found) : existing?.meta };
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
const modelsPath = (): string => join(getAgentDir(), "models.json");
|
|
346
|
+
const authPath = (): string => join(getAgentDir(), "auth.json");
|
|
347
|
+
|
|
348
|
+
/** pi's own models.json tolerance, replicated exactly: `//` comments and trailing
|
|
349
|
+
* commas are dropped outside string literals, so the wizard accepts every file pi's
|
|
350
|
+
* ModelConfig accepts — a hand-edited file never blocks the menu. */
|
|
351
|
+
export function looseJsonParse(content: string): unknown {
|
|
352
|
+
const stripped = content
|
|
353
|
+
.replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (m) => (m[0] === '"' ? m : ""))
|
|
354
|
+
.replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (m, tail?: string) => tail ?? (m[0] === '"' ? m : ""));
|
|
355
|
+
return JSON.parse(stripped) as unknown;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Missing file → undefined. Corrupt JSON is thrown, never overwritten: the caller aborts
|
|
359
|
+
* and reports, so a broken models.json cannot be clobbered by a save. Reads with pi's
|
|
360
|
+
* tolerance: BOM stripped, comments and trailing commas dropped before JSON.parse. */
|
|
361
|
+
function readJson(path: string): unknown {
|
|
362
|
+
let content: string;
|
|
363
|
+
try {
|
|
364
|
+
content = readFileSync(path, "utf8");
|
|
365
|
+
} catch {
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
if (content.trim() === "") return undefined;
|
|
369
|
+
return looseJsonParse(content.replace(/^\uFEFF/, ""));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function writeJson(path: string, value: unknown): void {
|
|
373
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
374
|
+
// Temp + rename, the package's own standard (preset-store.ts, usage-store.ts): a crash
|
|
375
|
+
// mid-write must never truncate models.json or auth.json — a corrupted auth.json breaks
|
|
376
|
+
// the stored credentials of every provider, and the wizard refuses to save until it is
|
|
377
|
+
// repaired by hand.
|
|
378
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
379
|
+
writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
|
|
380
|
+
renameSync(tmp, path);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export function loadModelsConfig(): unknown {
|
|
384
|
+
return readJson(modelsPath());
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
export function saveProvider(name: string, entry: ProviderEntry, key: string | undefined): void {
|
|
388
|
+
writeJson(modelsPath(), withProvider(readJson(modelsPath()), name, entry));
|
|
389
|
+
if (key) writeJson(authPath(), withAuth(readJson(authPath()), name, key));
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
export function deleteProviderNamed(name: string): boolean {
|
|
393
|
+
const config = readJson(modelsPath());
|
|
394
|
+
if (!providerNames(config).includes(name)) return false;
|
|
395
|
+
writeJson(modelsPath(), withoutProvider(config, name));
|
|
396
|
+
writeJson(authPath(), withoutAuth(readJson(authPath()), name));
|
|
397
|
+
return true;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** The stored credential for a provider, from the same auth.json /login writes. */
|
|
401
|
+
export function readAuthKey(name: string): string | undefined {
|
|
402
|
+
const auth = readJson(authPath());
|
|
403
|
+
if (!isObj(auth) || !isObj(auth[name])) return undefined;
|
|
404
|
+
const entry = auth[name] as Record<string, unknown>;
|
|
405
|
+
if (entry.type === "api_key" && typeof entry.key === "string") return entry.key;
|
|
406
|
+
return undefined;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** The stored entry with its models typed; extra fields stay in the raw config (edits go
|
|
410
|
+
* through {@link withProviderModels}, which never drops them). */
|
|
411
|
+
export function loadProviderEntry(config: unknown, name: string): ProviderEntry | undefined {
|
|
412
|
+
if (!isObj(config) || !isObj(config.providers)) return undefined;
|
|
413
|
+
const value = (config.providers as Record<string, unknown>)[name];
|
|
414
|
+
if (!isObj(value)) return undefined;
|
|
415
|
+
const models: ProviderModel[] = Array.isArray(value.models)
|
|
416
|
+
? (value.models as unknown[]).flatMap((m): ProviderModel[] => {
|
|
417
|
+
if (!isObj(m) || typeof m.id !== "string") return [];
|
|
418
|
+
const level = wireToLevel(m.reasoning, m.thinkingLevelMap);
|
|
419
|
+
const contextWindow = typeof m.contextWindow === "number" ? m.contextWindow : undefined;
|
|
420
|
+
const maxTokens = typeof m.maxTokens === "number" ? m.maxTokens : undefined;
|
|
421
|
+
const meta = contextWindow === undefined && maxTokens === undefined ? undefined : { contextWindow, maxTokens };
|
|
422
|
+
return [{ id: m.id, ...(level === "off" ? {} : { level }), ...(meta ? { meta } : {}), ...(isObj(m.compat) ? { compat: m.compat } : {}) }];
|
|
423
|
+
})
|
|
424
|
+
: [];
|
|
425
|
+
return {
|
|
426
|
+
name: typeof value.name === "string" ? value.name : name,
|
|
427
|
+
baseUrl: typeof value.baseUrl === "string" ? value.baseUrl : "",
|
|
428
|
+
api: (typeof value.api === "string" ? value.api : "openai-completions") as ApiFlavor,
|
|
429
|
+
apiKey: typeof value.apiKey === "string" ? value.apiKey : undefined,
|
|
430
|
+
models,
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// ---------------------------------------------------------------- wizard
|
|
435
|
+
|
|
436
|
+
const PROVIDERS_TEXT: ScreenText = {
|
|
437
|
+
title: screenTitle("Providers"),
|
|
438
|
+
description: "Custom endpoints: add with one probe, delete with a confirm.",
|
|
439
|
+
legend: LIST_LEGEND_MOVE,
|
|
440
|
+
};
|
|
441
|
+
|
|
442
|
+
const ADD_ROW = "+ Add provider";
|
|
443
|
+
|
|
444
|
+
const MODEL_LEGEND = "[↑↓] Move [Space] Toggle [a] API [Enter] Save [Esc] Cancel";
|
|
445
|
+
const MODEL_LEGEND_LOCKED = "[↑↓] Move [Space] Toggle [Enter] Save [Esc] Cancel";
|
|
446
|
+
/** Rows visible before the model list scrolls (a relay catalog can exceed the screen). */
|
|
447
|
+
const MODEL_VIEWPORT = 10;
|
|
448
|
+
|
|
449
|
+
/** One model-selection screen: Space checks rows, `a` cycles the API flavor (unless the
|
|
450
|
+
* stored api is final), Enter saves. Esc leaves without writing anything. */
|
|
451
|
+
const pickModels = async (
|
|
452
|
+
ctx: ExtensionCommandContext,
|
|
453
|
+
models: string[],
|
|
454
|
+
opts: { flavor: ApiFlavor; via?: string; checked?: Set<string>; lockFlavor?: boolean },
|
|
455
|
+
): Promise<{ picked: string[]; flavor: ApiFlavor } | undefined> => {
|
|
456
|
+
const checked = new Set(opts.checked ?? models);
|
|
457
|
+
let flavor = opts.flavor;
|
|
458
|
+
const rows: ListRow[] = models.map((id) => ({ label: id }));
|
|
459
|
+
const picked = await ctx.ui.custom<string[] | null>((tui, theme, _kb, done) => {
|
|
460
|
+
const picker = new ListPicker(
|
|
461
|
+
theme,
|
|
462
|
+
rows,
|
|
463
|
+
undefined,
|
|
464
|
+
{
|
|
465
|
+
preview: () => {},
|
|
466
|
+
revert: () => {},
|
|
467
|
+
done: () => done([...checked]),
|
|
468
|
+
cancel: () => done(null),
|
|
469
|
+
// A fill screen: `←` is hidden — it must not throw away a half-picked list.
|
|
470
|
+
back: false,
|
|
471
|
+
requestRender: () => tui.requestRender(),
|
|
472
|
+
toggle: () => {
|
|
473
|
+
const label = rows[picker.index]?.label;
|
|
474
|
+
if (!label) return;
|
|
475
|
+
if (checked.has(label)) checked.delete(label);
|
|
476
|
+
else checked.add(label);
|
|
477
|
+
},
|
|
478
|
+
marked: (label) => checked.has(label),
|
|
479
|
+
press: (keyData) => {
|
|
480
|
+
if (opts.lockFlavor || !matchesKey(keyData, "a")) return;
|
|
481
|
+
flavor = API_FLAVORS[(API_FLAVORS.indexOf(flavor) + 1) % API_FLAVORS.length]!;
|
|
482
|
+
},
|
|
483
|
+
description: () => `${FLAVOR_LABELS[flavor]}${opts.via ? ` · ${opts.via}` : ""}`,
|
|
484
|
+
// The picked count lives in the legend, accented, next to the keys it refers to.
|
|
485
|
+
legend: () =>
|
|
486
|
+
`${theme.fg("accent", `${checked.size}/${models.length} picked`)}${theme.fg("dim", ` · ${opts.lockFlavor ? MODEL_LEGEND_LOCKED : MODEL_LEGEND}`)}`,
|
|
487
|
+
},
|
|
488
|
+
{ title: screenTitle("Models"), description: FLAVOR_LABELS[flavor], legend: opts.lockFlavor ? MODEL_LEGEND_LOCKED : MODEL_LEGEND },
|
|
489
|
+
false,
|
|
490
|
+
ctx.thinkingLevel,
|
|
491
|
+
MODEL_VIEWPORT,
|
|
492
|
+
);
|
|
493
|
+
return picker;
|
|
494
|
+
});
|
|
495
|
+
if (!picked) return undefined;
|
|
496
|
+
return { picked, flavor };
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
const readInput = async (
|
|
500
|
+
ctx: ExtensionCommandContext,
|
|
501
|
+
/** The arnative screen name — the box title becomes `<screen> - Arnative⠙`. */
|
|
502
|
+
screen: string,
|
|
503
|
+
/** What the field is, shown as the description under the title. */
|
|
504
|
+
field: string,
|
|
505
|
+
placeholder: string,
|
|
506
|
+
initial = "",
|
|
507
|
+
): Promise<string | undefined> => {
|
|
508
|
+
if (ctx.mode === "tui") {
|
|
509
|
+
const value = await ctx.ui.custom<string | null>((tui, theme, _kb, done) =>
|
|
510
|
+
new InputPicker(
|
|
511
|
+
theme,
|
|
512
|
+
{ title: screenTitle(screen), description: field, legend: INPUT_LEGEND },
|
|
513
|
+
initial,
|
|
514
|
+
{
|
|
515
|
+
done: (v) => done(v),
|
|
516
|
+
cancel: () => done(null),
|
|
517
|
+
requestRender: () => tui.requestRender(),
|
|
518
|
+
},
|
|
519
|
+
placeholder,
|
|
520
|
+
ctx.thinkingLevel,
|
|
521
|
+
),
|
|
522
|
+
);
|
|
523
|
+
return value === null ? undefined : value.trim();
|
|
524
|
+
}
|
|
525
|
+
// No custom screens (RPC/headless): the native prompt.
|
|
526
|
+
const value = await ctx.ui.input(`${screen} · ${field}`, initial || placeholder);
|
|
527
|
+
return value === undefined ? undefined : value.trim();
|
|
528
|
+
};
|
|
529
|
+
|
|
530
|
+
/** Manual fallback when the probe found nothing: ids one at a time, a flavor question. */
|
|
531
|
+
const manualModels = async (ctx: ExtensionCommandContext): Promise<{ picked: string[]; flavor: ApiFlavor } | undefined> => {
|
|
532
|
+
const picked: string[] = [];
|
|
533
|
+
for (;;) {
|
|
534
|
+
const id = await readInput(ctx, "Models", `Model id ${picked.length + 1} — empty to finish`, "paste an id");
|
|
535
|
+
if (id === undefined) return undefined;
|
|
536
|
+
if (id === "") break;
|
|
537
|
+
picked.push(id);
|
|
538
|
+
}
|
|
539
|
+
if (picked.length === 0) return undefined;
|
|
540
|
+
const label = await ctx.ui.select("API flavor", API_FLAVORS.map((f) => FLAVOR_LABELS[f]));
|
|
541
|
+
if (label === undefined) return undefined;
|
|
542
|
+
return { picked, flavor: API_FLAVORS[API_FLAVORS.map((f) => FLAVOR_LABELS[f]).indexOf(label)]! };
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
/** Transient probe status, pinned above the chat column (pi's aboveEditor widget
|
|
546
|
+
* slot) for exactly as long as the request is in flight — a one-line dim "probing
|
|
547
|
+
* endpoint…" right where the user is about to type, instead of a status row in the
|
|
548
|
+
* bottom footer. Removed the moment the probe settles. */
|
|
549
|
+
const PROBE_WIDGET_KEY = "arnative-probe";
|
|
550
|
+
function probingStatus(ctx: ExtensionCommandContext, text: string | undefined): void {
|
|
551
|
+
if (!text) {
|
|
552
|
+
ctx.ui.setWidget?.(PROBE_WIDGET_KEY, undefined);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
ctx.ui.setWidget?.(
|
|
556
|
+
PROBE_WIDGET_KEY,
|
|
557
|
+
(_tui: TUI, theme: Theme) => ({
|
|
558
|
+
dispose() { /* no listeners, no timers — nothing to clean up */ },
|
|
559
|
+
invalidate() { /* a static line, recomputed on every render anyway */ },
|
|
560
|
+
render(_width: number): string[] {
|
|
561
|
+
return [theme.fg("dim", text)];
|
|
562
|
+
},
|
|
563
|
+
}),
|
|
564
|
+
{ placement: "aboveEditor" },
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
const addProviderFlow = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
569
|
+
const endpointRaw = await readInput(ctx, "Provider", "Endpoint API — the base URL", "https://api.example.com/v1");
|
|
570
|
+
if (!endpointRaw) return;
|
|
571
|
+
const endpoint = normalizeBase(endpointRaw);
|
|
572
|
+
|
|
573
|
+
const key = await readInput(ctx, "Provider", "API key — empty for local or keyless endpoints", "sk-…");
|
|
574
|
+
// Esc cancels the flow, Enter on an empty field means keyless: readInput keeps the two
|
|
575
|
+
// apart (undefined vs ""), and the field's own legend promises [Esc] Cancel.
|
|
576
|
+
if (key === undefined) return;
|
|
577
|
+
|
|
578
|
+
const suggested = guessProviderName(endpoint);
|
|
579
|
+
const nameInput = await readInput(ctx, "Provider", "a provider id (letters, digits, - and _)", suggested, suggested);
|
|
580
|
+
if (nameInput === undefined) return; // Esc cancels; an empty Enter accepts the suggestion.
|
|
581
|
+
const name = nameInput || suggested;
|
|
582
|
+
if (!/^[A-Za-z0-9_-]+$/.test(name)) {
|
|
583
|
+
ctx.ui.notify(`[arnative] "${name}" is not a usable provider id (letters, digits, - and _ only).`, "warning");
|
|
584
|
+
return;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
probingStatus(ctx, "probing endpoint…");
|
|
588
|
+
let result: ProbeResult | undefined;
|
|
589
|
+
try {
|
|
590
|
+
result = await probeEndpoint(endpoint, key ?? "");
|
|
591
|
+
} finally {
|
|
592
|
+
probingStatus(ctx, undefined);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
let picked: string[];
|
|
596
|
+
let flavor: ApiFlavor;
|
|
597
|
+
if (result) {
|
|
598
|
+
ctx.ui.notify(`[arnative] ${FLAVOR_LABELS[result.flavor]} · ${result.via} · ${result.models.length} models.`, "info");
|
|
599
|
+
if (ctx.mode === "tui") {
|
|
600
|
+
const chosen = await pickModels(ctx, result.models, { flavor: result.flavor, via: result.via });
|
|
601
|
+
if (!chosen) return;
|
|
602
|
+
({ picked, flavor } = chosen);
|
|
603
|
+
} else {
|
|
604
|
+
// No custom screens (RPC/headless): the ids as one editable list, empty = all.
|
|
605
|
+
const answer = await readInput(ctx, "Models", "ids comma/space separated — empty = all", "", result.models.join(", "));
|
|
606
|
+
if (answer === undefined) return;
|
|
607
|
+
picked = answer === "" ? result.models : answer.split(/[\s,]+/).filter(Boolean);
|
|
608
|
+
flavor = result.flavor;
|
|
609
|
+
}
|
|
610
|
+
} else {
|
|
611
|
+
ctx.ui.notify("[arnative] No model list answered. Enter ids by hand.", "warning");
|
|
612
|
+
const manual = await manualModels(ctx);
|
|
613
|
+
if (!manual) return;
|
|
614
|
+
({ picked, flavor } = manual);
|
|
615
|
+
}
|
|
616
|
+
if (picked.length === 0) {
|
|
617
|
+
ctx.ui.notify("[arnative] No models picked — nothing saved.", "warning");
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const entry: ProviderEntry = {
|
|
622
|
+
name,
|
|
623
|
+
baseUrl: chatBaseUrl(flavor, endpoint),
|
|
624
|
+
api: flavor,
|
|
625
|
+
models: mergeLevels({ name, baseUrl: chatBaseUrl(flavor, endpoint), api: flavor, models: [] }, picked, result?.meta),
|
|
626
|
+
};
|
|
627
|
+
// A keyless endpoint still needs a resolvable credential for pi to list the models.
|
|
628
|
+
if (!key) entry.apiKey = result?.keyless ? "ollama" : "dummy";
|
|
629
|
+
try {
|
|
630
|
+
saveProvider(name, entry, key || undefined);
|
|
631
|
+
} catch (error) {
|
|
632
|
+
ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}. Fix the JSON by hand first.`, "error");
|
|
633
|
+
return;
|
|
634
|
+
}
|
|
635
|
+
ctx.ui.notify(`[arnative] Provider saved: ${name} (${FLAVOR_LABELS[flavor]}, ${picked.length} models, ${levelsSummary(entry.models)}). Open /model to pick one.`, "info");
|
|
636
|
+
};
|
|
637
|
+
|
|
638
|
+
const deleteProviderFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
|
|
639
|
+
if (!(await ctx.ui.confirm("Delete provider", `${name}? The stored key goes with it.`))) return;
|
|
640
|
+
try {
|
|
641
|
+
ctx.ui.notify(deleteProviderNamed(name) ? `[arnative] Deleted ${name}.` : `[arnative] ${name} was already gone.`, "info");
|
|
642
|
+
} catch (error) {
|
|
643
|
+
ctx.ui.notify(`[arnative] Not deleted: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
644
|
+
}
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
/** "3 thinking (auto, high, xhigh)" — the levels a save registered, for the notify. */
|
|
648
|
+
const levelsSummary = (models: ProviderModel[]): string => {
|
|
649
|
+
const on = models.filter((m) => m.level && m.level !== "off");
|
|
650
|
+
const distinct = [...new Set(on.map((m) => m.level!))];
|
|
651
|
+
return on.length === 0 ? "0 thinking" : `${on.length} thinking (${distinct.join(", ")})`;
|
|
652
|
+
};
|
|
653
|
+
|
|
654
|
+
/** Writes one provider's model list through to models.json (auth.json is untouched — the
|
|
655
|
+
* key only changes through add or delete). */
|
|
656
|
+
const saveModelsNamed = (ctx: ExtensionCommandContext, name: string, models: ProviderModel[]): void => {
|
|
657
|
+
try {
|
|
658
|
+
writeJson(modelsPath(), withProviderModels(readJson(modelsPath()), name, models));
|
|
659
|
+
} catch (error) {
|
|
660
|
+
ctx.ui.notify(`[arnative] Not saved: ${error instanceof Error ? error.message : "config file unreadable"}.`, "error");
|
|
661
|
+
return;
|
|
662
|
+
}
|
|
663
|
+
ctx.ui.notify(`[arnative] ${name}: ${models.length} models, ${levelsSummary(models)} — models.json updated. Open /model to refresh.`, "info");
|
|
664
|
+
};
|
|
665
|
+
|
|
666
|
+
const selectModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
667
|
+
const ids = entry.models.map((m) => m.id);
|
|
668
|
+
let picked: string[] | undefined;
|
|
669
|
+
if (ctx.mode === "tui") {
|
|
670
|
+
const chosen = await pickModels(ctx, ids, { flavor: entry.api, checked: new Set(ids), lockFlavor: true });
|
|
671
|
+
if (!chosen) return;
|
|
672
|
+
picked = chosen.picked;
|
|
673
|
+
} else {
|
|
674
|
+
const answer = await readInput(ctx, "Models", "ids comma/space — empty = keep", "", ids.join(", "));
|
|
675
|
+
if (answer === undefined || answer === "") return;
|
|
676
|
+
picked = answer.split(/[\s,]+/).filter(Boolean);
|
|
677
|
+
}
|
|
678
|
+
saveModelsNamed(ctx, name, mergeLevels(entry, picked));
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
const probeModelsFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
682
|
+
// The real key lives in auth.json; an inline dummy never authenticates a probe.
|
|
683
|
+
const stored = readAuthKey(name);
|
|
684
|
+
const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : "";
|
|
685
|
+
const key = stored ?? inline;
|
|
686
|
+
probingStatus(ctx, "probing endpoint…");
|
|
687
|
+
let result: ProbeResult | undefined;
|
|
688
|
+
try {
|
|
689
|
+
result = await probeEndpoint(entry.baseUrl, key ?? "");
|
|
690
|
+
} finally {
|
|
691
|
+
probingStatus(ctx, undefined);
|
|
692
|
+
}
|
|
693
|
+
if (!result) {
|
|
694
|
+
ctx.ui.notify("[arnative] The endpoint did not answer a model list (key or URL wrong?).", "warning");
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
ctx.ui.notify(`[arnative] ${FLAVOR_LABELS[result.flavor]} · ${result.via} · ${result.models.length} models.`, "info");
|
|
698
|
+
// Vanished models stay listed (still checked) so a relay hiccup cannot shrink the set.
|
|
699
|
+
const union = [...new Set([...result.models, ...entry.models.map((m) => m.id)])];
|
|
700
|
+
let picked: string[] | undefined;
|
|
701
|
+
if (ctx.mode === "tui") {
|
|
702
|
+
const chosen = await pickModels(ctx, union, { flavor: entry.api, via: result.via, checked: new Set(entry.models.map((m) => m.id)), lockFlavor: true });
|
|
703
|
+
if (!chosen) return;
|
|
704
|
+
picked = chosen.picked;
|
|
705
|
+
} else {
|
|
706
|
+
const answer = await readInput(ctx, "Models", "ids comma/space — empty = keep", "", union.join(", "));
|
|
707
|
+
if (answer === undefined || answer === "") return;
|
|
708
|
+
picked = answer.split(/[\s,]+/).filter(Boolean);
|
|
709
|
+
}
|
|
710
|
+
saveModelsNamed(ctx, name, mergeLevels(entry, picked, result.meta));
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
const THINKING_LEGEND = "[↑↓] Move [Space] Cycle [A] All auto [R] All off [p] Probe [Enter] Save [Esc] Cancel";
|
|
714
|
+
|
|
715
|
+
/** Space cycles one model through off → auto → minimal → … → max. `auto` means
|
|
716
|
+
* `reasoning: true` with no map (every `/think` level passes through unchanged); an
|
|
717
|
+
* explicit level pins `thinkingLevelMap` to that single value. `p` asks the channel which
|
|
718
|
+
* effort names it really accepts and stores the answer as the model's map. */
|
|
719
|
+
const thinkingFlow = async (ctx: ExtensionCommandContext, name: string, entry: ProviderEntry): Promise<void> => {
|
|
720
|
+
const levels = new Map(entry.models.map((m) => [m.id, m.level ?? detectLevel(m.id)] as const));
|
|
721
|
+
const probed = new Map<string, Record<string, string | null>>();
|
|
722
|
+
const cycle = (label: string): void => {
|
|
723
|
+
const current = levels.get(label) ?? "off";
|
|
724
|
+
const next = THINKING_SETTINGS[(THINKING_SETTINGS.indexOf(current) + 1) % THINKING_SETTINGS.length]!;
|
|
725
|
+
levels.set(label, next);
|
|
726
|
+
// A probed map belongs to `auto` only: a pinned level states its own answer.
|
|
727
|
+
if (next !== "auto") probed.delete(label);
|
|
728
|
+
};
|
|
729
|
+
const rows: ListRow[] = entry.models.map((m) => ({ label: m.id }));
|
|
730
|
+
/** "medium→high, max off" — what a probed map actually changed. */
|
|
731
|
+
const summary = (map: Record<string, string | null>): string => {
|
|
732
|
+
const parts = Object.entries(map)
|
|
733
|
+
.filter(([level, value]) => value !== level && !(value === null && level === "off"))
|
|
734
|
+
.map(([level, value]) => (value === null ? `${level} off` : `${level}→${value}`));
|
|
735
|
+
return parts.length === 0 ? "all levels accepted" : parts.join(", ");
|
|
736
|
+
};
|
|
737
|
+
let busy: string | undefined;
|
|
738
|
+
let progress: string | undefined;
|
|
739
|
+
let warn: string | undefined;
|
|
740
|
+
let refresh: () => void = () => {};
|
|
741
|
+
let closed = false;
|
|
742
|
+
const probe = async (label: string): Promise<void> => {
|
|
743
|
+
const model = entry.models.find((m) => m.id === label);
|
|
744
|
+
const compat = model?.compat ?? {};
|
|
745
|
+
if (!isEffortProbeable({ provider: name, id: label, api: entry.api, baseUrl: entry.baseUrl, reasoning: true, compat }, compat)) {
|
|
746
|
+
warn = `${label}: this channel does not take a probing request (not an OpenAI-compatible reasoning model).`;
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
busy = label;
|
|
750
|
+
progress = "starting…";
|
|
751
|
+
refresh();
|
|
752
|
+
const inline = entry.apiKey && entry.apiKey !== "dummy" && entry.apiKey !== "ollama" ? entry.apiKey : undefined;
|
|
753
|
+
try {
|
|
754
|
+
const supported = await probeEffort(
|
|
755
|
+
{ provider: name, id: label, api: entry.api, baseUrl: entry.baseUrl, reasoning: true, compat },
|
|
756
|
+
{
|
|
757
|
+
baseUrl: entry.baseUrl,
|
|
758
|
+
key: readAuthKey(name) ?? inline,
|
|
759
|
+
onLevel: (level, _accepted, index) => {
|
|
760
|
+
progress = `${level} · ${index + 1}/7`;
|
|
761
|
+
refresh();
|
|
762
|
+
},
|
|
763
|
+
},
|
|
764
|
+
);
|
|
765
|
+
if (supported.length === 0) {
|
|
766
|
+
warn = `${label}: no effort level answered — the map is unchanged.`;
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
const current = probed.get(label) ?? levelToWire(levels.get(label))?.thinkingLevelMap;
|
|
770
|
+
const next = buildEffortMap(current, supported);
|
|
771
|
+
if (next) probed.set(label, next);
|
|
772
|
+
levels.set(label, "auto");
|
|
773
|
+
warn = `${label}: ${next ? summary(next) : "every level is accepted as-is"}.`;
|
|
774
|
+
} finally {
|
|
775
|
+
busy = undefined;
|
|
776
|
+
progress = undefined;
|
|
777
|
+
refresh();
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
let saved: boolean;
|
|
781
|
+
if (ctx.mode === "tui") {
|
|
782
|
+
const outcome = await ctx.ui.custom<boolean | null>((tui, theme, _kb, done) => {
|
|
783
|
+
refresh = () => {
|
|
784
|
+
if (!closed) tui.requestRender();
|
|
785
|
+
};
|
|
786
|
+
const close = (value: boolean | null) => {
|
|
787
|
+
closed = true;
|
|
788
|
+
done(value);
|
|
789
|
+
};
|
|
790
|
+
const picker = new ListPicker(
|
|
791
|
+
theme,
|
|
792
|
+
rows,
|
|
793
|
+
undefined,
|
|
794
|
+
{
|
|
795
|
+
preview: () => {},
|
|
796
|
+
revert: () => {},
|
|
797
|
+
// A probe is a round trip, but it never owns the screen: leaving mid-probe just
|
|
798
|
+
// discards the answer, because the save reads `probed` before it lands.
|
|
799
|
+
done: () => close(true),
|
|
800
|
+
cancel: () => close(null),
|
|
801
|
+
// A fill screen: `←` is hidden — it must not throw away half-set levels.
|
|
802
|
+
back: false,
|
|
803
|
+
requestRender: () => refresh(),
|
|
804
|
+
toggle: () => {
|
|
805
|
+
const label = rows[picker.index]?.label;
|
|
806
|
+
if (label && !busy) cycle(label);
|
|
807
|
+
},
|
|
808
|
+
press: (keyData) => {
|
|
809
|
+
if (busy) return;
|
|
810
|
+
// Plain letters only: Ctrl/Alt/F-keys are swallowed or remapped by some
|
|
811
|
+
// terminals, so the two bulk keys stay on the same key everywhere. Shift keeps
|
|
812
|
+
// them deliberate — pi-tui lowercases a key id, so "A" would mean plain `a`.
|
|
813
|
+
if (matchesKey(keyData, "shift+a")) {
|
|
814
|
+
for (const id of levels.keys()) levels.set(id, "auto");
|
|
815
|
+
probed.clear();
|
|
816
|
+
refresh();
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
if (matchesKey(keyData, "shift+r")) {
|
|
820
|
+
for (const id of levels.keys()) levels.set(id, "off");
|
|
821
|
+
probed.clear();
|
|
822
|
+
refresh();
|
|
823
|
+
return;
|
|
824
|
+
}
|
|
825
|
+
const label = rows[picker.index]?.label;
|
|
826
|
+
if (!label || !matchesKey(keyData, "p")) return;
|
|
827
|
+
void probe(label);
|
|
828
|
+
},
|
|
829
|
+
note: (label) => {
|
|
830
|
+
if (busy === label) return `probing ${progress ?? ""}`.trim();
|
|
831
|
+
const map = probed.get(label);
|
|
832
|
+
return `${levels.get(label) ?? "off"}${map ? ` · ${summary(map)}` : ""}`;
|
|
833
|
+
},
|
|
834
|
+
description: () => `cycle: ${THINKING_SETTINGS.join(" → ")}`,
|
|
835
|
+
legend: () =>
|
|
836
|
+
`${theme.fg("accent", `${[...levels.values()].filter((l) => l !== "off").length}/${rows.length} thinking`)}${theme.fg("dim", ` · ${THINKING_LEGEND}`)}`,
|
|
837
|
+
},
|
|
838
|
+
{ title: screenTitle("Thinking"), description: "level per model — auto-detected from the id", legend: THINKING_LEGEND },
|
|
839
|
+
false,
|
|
840
|
+
ctx.thinkingLevel,
|
|
841
|
+
MODEL_VIEWPORT,
|
|
842
|
+
);
|
|
843
|
+
return picker;
|
|
844
|
+
});
|
|
845
|
+
saved = outcome === true;
|
|
846
|
+
} else {
|
|
847
|
+
// No custom screens (RPC/headless): `id:level` pairs, e.g. `o1-mini:low`.
|
|
848
|
+
const answer = await readInput(ctx, "Thinking", "levels as id:level pairs — empty = cancel", "", [...levels].map(([id, l]) => `${id}:${l}`).join(", "));
|
|
849
|
+
if (answer === undefined || answer === "") return;
|
|
850
|
+
for (const pair of answer.split(/[\s,]+/).filter(Boolean)) {
|
|
851
|
+
const [id, level] = pair.split(":");
|
|
852
|
+
if (id && level && THINKING_SETTINGS.includes(level as ThinkingSetting)) levels.set(id, level as ThinkingSetting);
|
|
853
|
+
}
|
|
854
|
+
saved = true;
|
|
855
|
+
}
|
|
856
|
+
if (!saved) return;
|
|
857
|
+
saveModelsNamed(
|
|
858
|
+
ctx,
|
|
859
|
+
name,
|
|
860
|
+
entry.models.map((m) => {
|
|
861
|
+
const level = levels.get(m.id);
|
|
862
|
+
const map = level === "off" ? undefined : probed.get(m.id);
|
|
863
|
+
return { id: m.id, level, ...(map ? { map } : {}) };
|
|
864
|
+
}),
|
|
865
|
+
);
|
|
866
|
+
if (warn) ctx.ui.notify(`[arnative] ${warn}`, "info");
|
|
867
|
+
};
|
|
868
|
+
|
|
869
|
+
const ACTION_SELECT = "Select models";
|
|
870
|
+
const ACTION_PROBE = "Probe models";
|
|
871
|
+
const ACTION_THINKING = "Thinking";
|
|
872
|
+
const ACTION_DELETE = "Delete";
|
|
873
|
+
|
|
874
|
+
const ACTIONS_TEXT: ScreenText = {
|
|
875
|
+
title: screenTitle("Provider"),
|
|
876
|
+
description: "Edit the models, re-probe, toggle thinking, or delete.",
|
|
877
|
+
legend: LIST_LEGEND_MOVE,
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
/** Enter on an existing provider: an action menu instead of a straight delete. Every
|
|
881
|
+
* action writes through to models.json (and auth.json for delete) before returning. */
|
|
882
|
+
const providerActionFlow = async (ctx: ExtensionCommandContext, name: string): Promise<void> => {
|
|
883
|
+
for (;;) {
|
|
884
|
+
const entry = loadProviderEntry(loadModelsConfig(), name);
|
|
885
|
+
if (!entry) {
|
|
886
|
+
ctx.ui.notify(`[arnative] ${name} is gone — the list will refresh.`, "warning");
|
|
887
|
+
return;
|
|
888
|
+
}
|
|
889
|
+
const rows: ListRow[] = [
|
|
890
|
+
{ label: ACTION_SELECT, note: "tick the models this provider exposes" },
|
|
891
|
+
{ label: ACTION_PROBE, note: "re-read the model list from the endpoint" },
|
|
892
|
+
{ label: ACTION_THINKING, note: "toggle reasoning per model (auto-detected)" },
|
|
893
|
+
{ label: ACTION_DELETE, note: "remove the provider and its stored key" },
|
|
894
|
+
];
|
|
895
|
+
let action: string | null | undefined;
|
|
896
|
+
if (ctx.mode === "tui") {
|
|
897
|
+
action = await ctx.ui.custom<string | null>((tui, theme, _kb, done) => {
|
|
898
|
+
const picker = new ListPicker(
|
|
899
|
+
theme,
|
|
900
|
+
rows,
|
|
901
|
+
undefined,
|
|
902
|
+
{
|
|
903
|
+
preview: () => {},
|
|
904
|
+
revert: () => {},
|
|
905
|
+
done: () => done(rows[picker.index]?.label),
|
|
906
|
+
cancel: () => done(null),
|
|
907
|
+
// `←` leaves the actions for the provider list; Esc closes the whole menu.
|
|
908
|
+
back: () => done(null),
|
|
909
|
+
requestRender: () => tui.requestRender(),
|
|
910
|
+
},
|
|
911
|
+
{ ...ACTIONS_TEXT, title: screenTitle(`Provider · ${name}`) },
|
|
912
|
+
false,
|
|
913
|
+
ctx.thinkingLevel,
|
|
914
|
+
);
|
|
915
|
+
return picker;
|
|
916
|
+
});
|
|
917
|
+
} else {
|
|
918
|
+
const picked = await ctx.ui.select(`${name} — edit or delete`, rows.map(rowText));
|
|
919
|
+
action = picked === undefined ? undefined : rows.find((r) => picked.startsWith(r.label))?.label;
|
|
920
|
+
}
|
|
921
|
+
if (!action) return;
|
|
922
|
+
if (action === ACTION_DELETE) {
|
|
923
|
+
await deleteProviderFlow(ctx, name);
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
if (action === ACTION_SELECT) await selectModelsFlow(ctx, name, entry);
|
|
927
|
+
else if (action === ACTION_PROBE) await probeModelsFlow(ctx, name, entry);
|
|
928
|
+
else if (action === ACTION_THINKING) await thinkingFlow(ctx, name, entry);
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
|
|
932
|
+
/** The Providers screen: existing entries as rows, add as the last row. `←` reopens the
|
|
933
|
+
* settings menu, like every screen; after an add or a delete the list reopens. */
|
|
934
|
+
export const openProviders = async (ctx: ExtensionCommandContext): Promise<boolean | void> => {
|
|
935
|
+
/** Provider rows re-read from models.json; empty means the file turned unreadable. */
|
|
936
|
+
const refresh = (): ListRow[] => {
|
|
937
|
+
let summaries: ProviderSummary[];
|
|
938
|
+
try {
|
|
939
|
+
summaries = summarizeProviders(loadModelsConfig());
|
|
940
|
+
} catch {
|
|
941
|
+
ctx.ui.notify("[arnative] models.json is not valid JSON — fix it by hand first.", "error");
|
|
942
|
+
return [];
|
|
943
|
+
}
|
|
944
|
+
const rows: ListRow[] = summaries.map((s) => ({
|
|
945
|
+
label: s.name,
|
|
946
|
+
note: `${s.api ?? "unknown api"} · ${s.modelCount} model${s.modelCount === 1 ? "" : "s"}`,
|
|
947
|
+
}));
|
|
948
|
+
rows.push({ label: ADD_ROW, note: "endpoint, key, name — the rest is automatic" });
|
|
949
|
+
return rows;
|
|
950
|
+
};
|
|
951
|
+
|
|
952
|
+
const rows = refresh();
|
|
953
|
+
if (rows.length === 0) return;
|
|
954
|
+
|
|
955
|
+
const choose = async (label: string | undefined): Promise<void> => {
|
|
956
|
+
if (label === ADD_ROW) await addProviderFlow(ctx);
|
|
957
|
+
else if (label) await providerActionFlow(ctx, label);
|
|
958
|
+
};
|
|
959
|
+
|
|
960
|
+
if (ctx.mode !== "tui") {
|
|
961
|
+
// No custom screens (RPC/headless): the blocking picker, `rowText` as the flat label.
|
|
962
|
+
const picked = await ctx.ui.select(PROVIDERS_TEXT.title, rows.map(rowText));
|
|
963
|
+
if (picked === undefined) return;
|
|
964
|
+
// Provider ids are [A-Za-z0-9_-], so a `startsWith` on the flat row is unambiguous.
|
|
965
|
+
const label = rows.find((r) => picked.startsWith(r.label))?.label;
|
|
966
|
+
await choose(label);
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
for (;;) {
|
|
971
|
+
const index = await ctx.ui.custom<number | null>((tui, theme, _kb, done) => {
|
|
972
|
+
const picker = new ListPicker(theme, rows, undefined, {
|
|
973
|
+
preview: () => {},
|
|
974
|
+
revert: () => {},
|
|
975
|
+
done: () => done(picker.index),
|
|
976
|
+
cancel: () => done(null),
|
|
977
|
+
// `←` steps back to the settings menu; Esc closes for good.
|
|
978
|
+
back: () => done(-1),
|
|
979
|
+
requestRender: () => tui.requestRender(),
|
|
980
|
+
}, PROVIDERS_TEXT, false, ctx.thinkingLevel);
|
|
981
|
+
return picker;
|
|
982
|
+
});
|
|
983
|
+
if (index === null || index === undefined) return;
|
|
984
|
+
if (index === -1) return true;
|
|
985
|
+
await choose(rows[index]?.label);
|
|
986
|
+
// A provider may have been added, edited or deleted: re-read the list instead of
|
|
987
|
+
// showing the copy the screen opened with. An unreadable models.json keeps the old
|
|
988
|
+
// rows up rather than blanking the screen.
|
|
989
|
+
const fresh = refresh();
|
|
990
|
+
if (fresh.length > 0) {
|
|
991
|
+
rows.length = 0;
|
|
992
|
+
rows.push(...fresh);
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
|
|
997
|
+
// Self-check: `node lib/provider.ts`
|
|
998
|
+
if (isMain(import.meta.url)) {
|
|
999
|
+
// Flavors and bases.
|
|
1000
|
+
assert(chatBaseUrl("openai-completions", "https://api.x.com/v1") === "https://api.x.com/v1", "openai keeps an explicit /v1");
|
|
1001
|
+
assert(chatBaseUrl("openai-completions", "https://api.x.com") === "https://api.x.com/v1", "openai appends /v1");
|
|
1002
|
+
assert(chatBaseUrl("openai-completions", "https://api.x.com/v1beta/") === "https://api.x.com/v1", "openai rewrites /v1beta to /v1");
|
|
1003
|
+
assert(chatBaseUrl("anthropic-messages", "https://relay.x.com/v1") === "https://relay.x.com", "anthropic strips /v1");
|
|
1004
|
+
assert(chatBaseUrl("google-generative-ai", "https://relay.x.com/v1beta") === "https://relay.x.com", "gemini strips /v1beta");
|
|
1005
|
+
assert(normalizeBase("localhost:11434") === "http://localhost:11434", "bare host defaults to http");
|
|
1006
|
+
assert(normalizeBase(" https://x.com/ ") === "https://x.com", "trailing slashes trimmed");
|
|
1007
|
+
assert(guessProviderName("https://api.deepseek.com/v1") === "deepseek", "api prefix and tld dropped");
|
|
1008
|
+
assert(guessProviderName("https://openrouter.ai/api/v1") === "openrouter", "openrouter keeps its name");
|
|
1009
|
+
assert(guessProviderName("http://localhost:11434") === "localhost", "localhost stays localhost");
|
|
1010
|
+
assert(guessProviderName("http://192.168.1.10:11434") === "192.168.1.10", "an IP is kept verbatim");
|
|
1011
|
+
|
|
1012
|
+
// Probe parsing.
|
|
1013
|
+
const listPath = buildCandidates("https://x.com/v1", "k").find((c) => c.url === "https://x.com/v1/models")!;
|
|
1014
|
+
assert(listPath.url === "https://x.com/v1/models", "a /v1 base probes /models");
|
|
1015
|
+
const paths = buildCandidates("https://x.com", "").map((c) => c.url);
|
|
1016
|
+
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");
|
|
1017
|
+
const authed = buildCandidates("https://x.com", "sk-1")[0]!;
|
|
1018
|
+
assert(authed.url === "https://x.com/api/tags", "the ollama probe comes first");
|
|
1019
|
+
const openaiShape = { data: [{ id: "m1", context_length: 262_144, max_output_tokens: 32_000 }, { id: "m2" }] };
|
|
1020
|
+
const geminiShape = { models: [{ name: "models/gemini-x" }] };
|
|
1021
|
+
const ollamaShape = { models: [{ name: "qwen:7b" }] };
|
|
1022
|
+
assert(parseModelList(listPath, openaiShape)!.join() === "m1,m2", "data[].id parses");
|
|
1023
|
+
assert(parseModelList(listPath, geminiShape) === undefined, "a models[] shape is not a list answer for openai paths");
|
|
1024
|
+
const geminiCandidate = buildCandidates("https://x.com", "k").find((c) => c.url.endsWith("/v1beta/models"))!;
|
|
1025
|
+
assert(parseModelList(geminiCandidate, geminiShape)![0] === "gemini-x", "gemini strips the models/ prefix");
|
|
1026
|
+
const ollamaCandidate = buildCandidates("https://x.com", "k").find((c) => c.url.endsWith("/api/tags"))!;
|
|
1027
|
+
assert(parseModelList(ollamaCandidate, ollamaShape)![0] === "qwen:7b", "ollama keeps the tag verbatim");
|
|
1028
|
+
assert(parseModelList(listPath, { data: "no" }) === undefined, "a non-array data is no list");
|
|
1029
|
+
assert(parseModelList(listPath, "nope") === undefined, "a scalar body is no list");
|
|
1030
|
+
|
|
1031
|
+
// Probe priority with a fake fetch routed by path — the same layout every real server
|
|
1032
|
+
// has: each endpoint answers only its own shape, the rest 404.
|
|
1033
|
+
const route = (map: Record<string, unknown>) => async (url: string) => {
|
|
1034
|
+
const body = map[new URL(url).pathname];
|
|
1035
|
+
if (body === undefined) return { ok: false, status: 404, json: async () => ({}) };
|
|
1036
|
+
return { ok: true, status: 200, json: async () => body };
|
|
1037
|
+
};
|
|
1038
|
+
const probeOllama = await probeEndpoint("http://localhost:11434", "", route({ "/api/tags": ollamaShape }));
|
|
1039
|
+
assert(probeOllama?.flavor === "openai-completions" && probeOllama.via === "/api/tags" && probeOllama.keyless, "an ollama answer wins and is keyless");
|
|
1040
|
+
assert(probeOllama?.baseUrl === "http://localhost:11434/v1", "the ollama chat base gets /v1");
|
|
1041
|
+
const probeGemini = await probeEndpoint("https://relay.x.com", "k", route({ "/v1beta/models": geminiShape }));
|
|
1042
|
+
assert(probeGemini?.flavor === "google-generative-ai" && probeGemini.models[0] === "gemini-x", "a gemini answer is detected");
|
|
1043
|
+
const probeOpenai = await probeEndpoint("https://api.x.com/v1", "k", route({ "/v1/models": openaiShape }));
|
|
1044
|
+
assert(probeOpenai?.flavor === "openai-completions" && probeOpenai.baseUrl === "https://api.x.com/v1", "an openai answer is detected");
|
|
1045
|
+
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");
|
|
1046
|
+
const none = await probeEndpoint("https://api.x.com", "", route({}));
|
|
1047
|
+
assert(none === undefined, "no answer → undefined, the caller falls back to manual entry");
|
|
1048
|
+
const empty = await probeEndpoint("https://api.x.com/v1", "", route({ "/v1/models": { data: [] } }));
|
|
1049
|
+
assert(empty === undefined, "an empty list is no answer");
|
|
1050
|
+
|
|
1051
|
+
// Store merges: one provider in, one out, everything else preserved.
|
|
1052
|
+
const config = { providers: { a: { baseUrl: "x", api: "openai-completions", models: [] } }, other: 1 };
|
|
1053
|
+
const added = withProvider(config, "b", { baseUrl: "y", api: "anthropic-messages", models: [{ id: "m" }] });
|
|
1054
|
+
assert((added.providers as Record<string, unknown>).a !== undefined && added.other === 1, "withProvider preserves other keys and providers");
|
|
1055
|
+
assert((config.providers as Record<string, unknown>).b === undefined, "withProvider does not mutate its input");
|
|
1056
|
+
assert(providerNames(withoutProvider(added, "a")).join() === "b", "withoutProvider removes one");
|
|
1057
|
+
assert(summarizeProviders(added)[1]!.modelCount === 1, "summarize counts models");
|
|
1058
|
+
assert(summarizeProviders(undefined).length === 0, "summarize survives a missing file body");
|
|
1059
|
+
assert(summarizeProviders({ providers: { a: {} } })[0]!.modelCount === 0, "summarize survives a provider without models");
|
|
1060
|
+
const auth = withAuth({ a: { type: "api_key", key: "1" } }, "b", "2");
|
|
1061
|
+
assert((auth.b as { key: string }).key === "2" && auth.a !== undefined, "withAuth adds one credential");
|
|
1062
|
+
assert(withoutAuth(auth, "a").a === undefined, "withoutAuth removes one");
|
|
1063
|
+
|
|
1064
|
+
// The model picker screen: checks toggle, `a` cycles, Esc leaves, Enter returns the ids.
|
|
1065
|
+
const fakeTheme = { fg: (_c: string, t: string) => t, bold: (t: string) => t };
|
|
1066
|
+
const renderModels = (checked: Set<string>, rows: ListRow[]) =>
|
|
1067
|
+
new ListPicker(fakeTheme, rows, undefined, {
|
|
1068
|
+
preview: () => {},
|
|
1069
|
+
revert: () => {},
|
|
1070
|
+
done: () => {},
|
|
1071
|
+
requestRender: () => {},
|
|
1072
|
+
marked: (label) => checked.has(label),
|
|
1073
|
+
}, { title: screenTitle("Models"), description: "d", legend: MODEL_LEGEND }, false).render(60).map(stripAnsi);
|
|
1074
|
+
const picked0 = renderModels(new Set(["m1"]), [{ label: "m1" }, { label: "m2" }]);
|
|
1075
|
+
assert(picked0.some((l) => l.includes("[x] m1")) && picked0.some((l) => l.includes("[ ] m2")), "checked and unchecked rows render");
|
|
1076
|
+
assert(picked0.some((l) => l.includes("[a] API")), "the model legend advertises the flavor switch");
|
|
1077
|
+
|
|
1078
|
+
// The store reads with pi's own tolerance: a hand-edited models.json (comments, trailing
|
|
1079
|
+
// commas) is exactly what pi itself accepts, and strings containing `//` or `,]` survive.
|
|
1080
|
+
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");
|
|
1081
|
+
const kept = looseJsonParse('{"u":"http://x//y","v":"a,b]"}') as Record<string, string>;
|
|
1082
|
+
assert(kept.u === "http://x//y" && kept.v === "a,b]", "string literals survive the strip");
|
|
1083
|
+
assert((looseJsonParse("{\"a\": 1,}") as { a: number }).a === 1, "a trailing comma before the closing brace parses");
|
|
1084
|
+
let threw = false;
|
|
1085
|
+
try {
|
|
1086
|
+
looseJsonParse("{nope");
|
|
1087
|
+
} catch {
|
|
1088
|
+
threw = true;
|
|
1089
|
+
}
|
|
1090
|
+
assert(threw, "genuinely broken JSON still throws, so the caller can report it");
|
|
1091
|
+
|
|
1092
|
+
// Thinking levels auto-detect from ids (relay catalogs expose only ids).
|
|
1093
|
+
assert(detectLevel("ag/claude-opus-4-6-thinking") === "auto", "a thinking token means flexible thinking");
|
|
1094
|
+
assert(detectLevel("ag/gemini-4-argon-high") === "high", "a -high suffix pins high");
|
|
1095
|
+
assert(detectLevel("ag/gemini-4-argon-xhigh") === "xhigh", "an -xhigh suffix pins xhigh");
|
|
1096
|
+
assert(detectLevel("ag/gemini-4-argon-x-high") === "xhigh", "-x-high also pins xhigh");
|
|
1097
|
+
assert(detectLevel("foo/bar-max") === "max", "a -max suffix pins max");
|
|
1098
|
+
assert(detectLevel("foo/bar-medium") === "medium", "a -medium suffix pins medium");
|
|
1099
|
+
assert(detectLevel("foo/bar-low") === "low", "a -low suffix pins low");
|
|
1100
|
+
assert(detectLevel("foo/bar-minimal") === "minimal", "a -minimal suffix pins minimal");
|
|
1101
|
+
assert(detectLevel("deepseek-reasoner") === "auto", "reasoner means flexible thinking");
|
|
1102
|
+
assert(detectLevel("o1-mini") === "auto", "an o-generation id means flexible thinking");
|
|
1103
|
+
assert(detectLevel("deepseek-r1") === "auto", "r1 means flexible thinking");
|
|
1104
|
+
assert(detectLevel("ocz/mimo-v2.6-flash-free") === "auto", "a plain flash id starts at auto");
|
|
1105
|
+
assert(detectLevel("oc/big-pickle") === "auto", "an unrelated id starts at auto");
|
|
1106
|
+
|
|
1107
|
+
// Levels serialize to pi's wire shape and read back unchanged.
|
|
1108
|
+
const wireHigh = levelToWire("high") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
|
|
1109
|
+
assert(wireHigh.reasoning === true, "a pinned level sets reasoning");
|
|
1110
|
+
assert(wireHigh.thinkingLevelMap?.high === "high", "the pinned level maps to itself");
|
|
1111
|
+
assert(THINKING_LEVELS.filter((l) => wireHigh.thinkingLevelMap![l] === null).length === 6, "every other level is null");
|
|
1112
|
+
assert(levelToWire("xhigh")!.thinkingLevelMap!.xhigh === "xhigh", "xhigh needs its explicit map entry");
|
|
1113
|
+
const wireAuto = levelToWire("auto") as { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> };
|
|
1114
|
+
assert(wireAuto.reasoning === true && wireAuto.thinkingLevelMap === undefined, "auto is reasoning without a map");
|
|
1115
|
+
assert(Object.keys(levelToWire("off")).length === 0, "off writes no flags");
|
|
1116
|
+
assert(wireToLevel(true, undefined) === "auto" && wireToLevel(false, undefined) === "off", "wire round-trips auto and off");
|
|
1117
|
+
assert(wireToLevel(true, levelToWire("medium").thinkingLevelMap) === "medium", "wire round-trips a pinned level");
|
|
1118
|
+
|
|
1119
|
+
// Edit flows rewrite only `models` and keep every other provider field.
|
|
1120
|
+
const rich = { providers: { r: { name: "R", baseUrl: "b", api: "openai-completions", compat: { supportsLongCacheRetention: false }, models: [{ id: "m1", reasoning: true }] } } };
|
|
1121
|
+
const edited = withProviderModels(rich, "r", [{ id: "m2", level: "high" }]);
|
|
1122
|
+
const savedProvider = (edited.providers as Record<string, Record<string, unknown>>).r!;
|
|
1123
|
+
assert(savedProvider.compat !== undefined && savedProvider.name === "R", "withProviderModels keeps sibling fields");
|
|
1124
|
+
const savedModels = savedProvider.models as { id: string; reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> }[];
|
|
1125
|
+
assert(savedModels[0]!.id === "m2" && savedModels[0]!.reasoning === true && savedModels[0]!.thinkingLevelMap?.high === "high", "withProviderModels serializes the level");
|
|
1126
|
+
const savedCompat = (savedModels[0] as { compat?: Record<string, unknown> }).compat;
|
|
1127
|
+
assert(savedCompat?.supportsLongCacheRetention === false && savedCompat?.sendSessionAffinityHeaders === true, "a save writes the compat flags a relay needs");
|
|
1128
|
+
|
|
1129
|
+
// A probe's limits land in the entry and survive a later edit that does not mention them.
|
|
1130
|
+
const withMeta = withProviderModels(rich, "r", [{ id: "m1", level: "auto", meta: { contextWindow: 1_000_000, maxTokens: 64_000 } }]);
|
|
1131
|
+
const metaModels = (withMeta.providers as Record<string, { models: { id: string; contextWindow?: number; maxTokens?: number }[] }>).r!.models;
|
|
1132
|
+
assert(metaModels[0]!.contextWindow === 1_000_000 && metaModels[0]!.maxTokens === 64_000, "a probed window and cap are written");
|
|
1133
|
+
const keptMeta = withProviderModels(withMeta, "r", [{ id: "m1", level: "high" }]);
|
|
1134
|
+
const keptModel = (keptMeta.providers as Record<string, { models: { contextWindow?: number; maxTokens?: number }[] }>).r!.models[0]!;
|
|
1135
|
+
assert(keptModel.contextWindow === 1_000_000 && keptModel.maxTokens === 64_000, "an edit that says nothing about limits keeps them");
|
|
1136
|
+
assert((loadProviderEntry(withMeta, "r")?.models[0]!.meta?.contextWindow ?? 0) === 1_000_000, "the limits load back as meta");
|
|
1137
|
+
const probedMap = withProviderModels(rich, "r", [{ id: "m1", level: "auto", map: { medium: "high", xhigh: null } }]);
|
|
1138
|
+
const probedModel = (probedMap.providers as Record<string, { models: { reasoning?: boolean; thinkingLevelMap?: Record<string, string | null> }[] }>).r!.models[0]!;
|
|
1139
|
+
assert(probedModel.reasoning === true && probedModel.thinkingLevelMap?.medium === "high", "a probed map wins over the level's own pin");
|
|
1140
|
+
const levelAfterProbe = withProviderModels(probedMap, "r", [{ id: "m1", level: "high" }]);
|
|
1141
|
+
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");
|
|
1142
|
+
const merged = mergeLevels({ name: "n", baseUrl: "b", api: "openai-completions", models: [{ id: "m1", level: "auto" }, { id: "m2", level: "off" }] }, ["m2", "x-thinking"]);
|
|
1143
|
+
assert(merged[0]!.id === "m2" && merged[0]!.level === "off", "a stored chat model stays chat");
|
|
1144
|
+
assert(merged[1]!.level === "auto", "a new id defaults to auto");
|
|
1145
|
+
const keptFlag = mergeLevels({ name: "n", baseUrl: "b", api: "openai-completions", models: [{ id: "m1", level: "low" }] }, ["m1"]);
|
|
1146
|
+
assert(keptFlag[0]!.level === "low", "a stored level survives a reselect");
|
|
1147
|
+
const entryLoaded = loadProviderEntry(rich, "r");
|
|
1148
|
+
assert(entryLoaded?.models[0]!.id === "m1" && entryLoaded.api === "openai-completions", "loadProviderEntry reads models and api");
|
|
1149
|
+
assert(loadProviderEntry(rich, "missing") === undefined, "loadProviderEntry misses cleanly");
|
|
1150
|
+
const roundTrip = loadProviderEntry(withProviderModels(rich, "r", [{ id: "m9", level: "xhigh" }]), "r");
|
|
1151
|
+
assert(roundTrip?.models[0]!.level === "xhigh", "a saved level loads back as itself");
|
|
1152
|
+
assert(levelsSummary([{ id: "a" }, { id: "b", level: "high" }, { id: "c", level: "auto" }]) === "2 thinking (high, auto)", "the save notify names the registered levels");
|
|
1153
|
+
assert(levelsSummary([{ id: "a" }]) === "0 thinking", "an all-chat save says so plainly");
|
|
1154
|
+
// The Thinking screen's bulk keys are Shift+letter: pi-tui lowercases a key id, so this
|
|
1155
|
+
// pins that they stay distinct from the plain letters navigation already uses.
|
|
1156
|
+
assert(matchesKey("A", "shift+a") && !matchesKey("a", "shift+a"), "Shift+A is its own key, not plain a");
|
|
1157
|
+
assert(matchesKey("R", "shift+r") && !matchesKey("r", "shift+r"), "Shift+R is its own key, not plain r");
|
|
1158
|
+
|
|
1159
|
+
// The stored key is read back from auth.json in an isolated agent dir (never the user's).
|
|
1160
|
+
const tmp = mkdtempSync(join(tmpdir(), "arnative-providers-"));
|
|
1161
|
+
process.env.PI_CODING_AGENT_DIR = tmp;
|
|
1162
|
+
saveProvider("t1", { name: "t1", baseUrl: "https://x.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-x");
|
|
1163
|
+
assert(readAuthKey("t1") === "sk-x", "readAuthKey returns the stored key");
|
|
1164
|
+
assert(readAuthKey("missing") === undefined, "readAuthKey misses cleanly");
|
|
1165
|
+
// Atomicity: a save interrupted at the temp write (a directory sits where the temp file
|
|
1166
|
+
// should go) must leave the previous config intact — the direct-write code it replaces
|
|
1167
|
+
// truncated models.json on any mid-write failure.
|
|
1168
|
+
const blockedTmp = join(tmp, `models.json.${process.pid}.tmp`);
|
|
1169
|
+
mkdirSync(blockedTmp);
|
|
1170
|
+
let interrupted = false;
|
|
1171
|
+
try {
|
|
1172
|
+
saveProvider("t2", { name: "t2", baseUrl: "https://y.com/v1", api: "openai-completions", models: [{ id: "m" }] }, "sk-y");
|
|
1173
|
+
} catch {
|
|
1174
|
+
interrupted = true;
|
|
1175
|
+
}
|
|
1176
|
+
assert(interrupted, "a blocked temp write surfaces the error instead of passing silently");
|
|
1177
|
+
assert(providerNames(loadModelsConfig()).join() === "t1", "the previous config survives the interrupted save");
|
|
1178
|
+
assert(readAuthKey("t2") === undefined, "the interrupted save never reached auth.json");
|
|
1179
|
+
rmSync(blockedTmp, { recursive: true, force: true });
|
|
1180
|
+
assert(readdirSync(tmp).every((f) => !f.endsWith(".tmp")), "a completed save leaves no temp files behind");
|
|
1181
|
+
delete process.env.PI_CODING_AGENT_DIR;
|
|
1182
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
1183
|
+
|
|
1184
|
+
// The providers screen copy stays factual and pinned.
|
|
1185
|
+
assert(PROVIDERS_TEXT.title === "Providers - Arnative\u2819", `providers title pinned, got ${PROVIDERS_TEXT.title}`);
|
|
1186
|
+
assert(ADD_ROW === "+ Add provider", "the add row label is pinned");
|
|
1187
|
+
assert(visibleWidth(PROVIDERS_TEXT.legend) > 0, "the screen carries a legend");
|
|
1188
|
+
|
|
1189
|
+
console.log("provider.ts self-check OK");
|
|
1190
|
+
}
|