@mmmbuto/nexuscrew 0.9.73 → 0.9.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,815 @@
1
+ 'use strict';
2
+ // lib/fleet/model-discovery.js — per-engine dynamic model discovery (lots 1-2).
3
+ //
4
+ // One collector per endpoint kind (OpenAI-compatible, Anthropic, Ollama,
5
+ // llama-server, LM Studio), a per-engine disk cache with TTL under the
6
+ // NexusCrew home, and a field-by-field precedence merge. Lot 2 adds the public
7
+ // catalog (models.dev) as a third, key-less source: a snapshot with its own
8
+ // TTL and fallback, an explicit provider/model mapping, and the same record
9
+ // shape joining the merge below the provider API. The engine's endpoint
10
+ // and key are resolved by the CALLER (managed.js, through the same
11
+ // credentialSources/credential path the launcher uses) and handed to this
12
+ // module in memory only: the key never reaches a file, a log, a cache entry
13
+ // or an error string.
14
+ //
15
+ // Hard constraints encoded here:
16
+ // * llama-server: ONLY `GET /v1/models` plus a single `GET /props` for the
17
+ // resident model. A router with `--models-max 1` unloads the resident
18
+ // model on any per-model request, so this collector must never issue a
19
+ // per-model request (measured on the production router, 2026-10-18).
20
+ // * discovery PROPOSES, never fills: the merged list is capped at
21
+ // DISCOVERY_PROPOSAL_CAP. The number mirrors MAX_MODELS in
22
+ // definitions.js on purpose; it is not imported from there because
23
+ // definitions.js requires managed.js, which requires this module — the
24
+ // duplication is deliberate and pinned by tests.
25
+ // * a model absent from the API listing is never dropped: it keeps its
26
+ // user/backup record and is marked `inApi: false`; a model that no layer
27
+ // carries but the PREVIOUS cached listing knew stays too, as a bare id
28
+ // (the 'known' layer) — a model that was in the APIs never silently
29
+ // disappears from the proposal. When the API could
30
+ // not be reached at all (and no last-good value exists) `inApi` stays
31
+ // ABSENT: unknown is not false.
32
+ // * fallback chain on error/timeout: last good disk value first, then the
33
+ // backup catalog supplied by the caller.
34
+
35
+ const fs = require('node:fs');
36
+ const path = require('node:path');
37
+ const crypto = require('node:crypto');
38
+
39
+ const DISCOVERY_PROPOSAL_CAP = 128; // mirrors MAX_MODELS (definitions.js)
40
+ const DEFAULT_TIMEOUT_MS = 2500;
41
+ const HOSTED_TTL_MS = 12 * 60 * 60 * 1000;
42
+ const LOCAL_TTL_MS = 60 * 1000;
43
+ const CACHE_VERSION = 1;
44
+ const MAX_SHOW_CALLS = 32; // Ollama /api/show: only listed ids the caller asked about
45
+ const ANTHROPIC_MAX_PAGES = 5; // pagination safety bound
46
+ const ANTHROPIC_VERSION = '2023-06-01';
47
+ const MODEL_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
48
+ const ENGINE_KEY_RE = /^[a-z0-9][a-z0-9._-]{0,63}$/;
49
+ const MERGE_FIELDS = Object.freeze(['contextWindow', 'maxTokens', 'tools', 'vision', 'reasoning', 'deprecated']);
50
+
51
+ const COLLECTOR_KINDS = Object.freeze(['openai-compat', 'anthropic', 'ollama', 'llama-server', 'lmstudio']);
52
+
53
+ // Local endpoints change with every pull/start; hosted listings barely move
54
+ // in a day. The TTL follows the endpoint, not the caller.
55
+ function collectorDefaultTtlMs(collector) {
56
+ return collector === 'ollama' || collector === 'llama-server' || collector === 'lmstudio'
57
+ ? LOCAL_TTL_MS : HOSTED_TTL_MS;
58
+ }
59
+
60
+ // Sanitized failure: fixed reason strings only. The raw fetch error can embed
61
+ // the request URL; the key lives in headers — neither may surface here.
62
+ class DiscoveryError extends Error {
63
+ constructor(reason) {
64
+ super(`model discovery: ${reason}`);
65
+ this.name = 'DiscoveryError';
66
+ this.reason = reason;
67
+ }
68
+ }
69
+
70
+ function trimBase(baseUrl) {
71
+ const b = String(baseUrl || '').trim().replace(/\/+$/, '');
72
+ return /^https?:\/\//i.test(b) ? b : null;
73
+ }
74
+
75
+ function openAiStyleModelsUrl(base) {
76
+ const b = trimBase(base);
77
+ if (!b) return null;
78
+ return /\/v1$/.test(b) ? `${b}/models` : `${b}/v1/models`;
79
+ }
80
+
81
+ function anthropicModelsUrl(base) {
82
+ const b = trimBase(base);
83
+ if (!b) return null;
84
+ return /\/v1$/.test(b) ? `${b}/models?limit=1000` : `${b}/v1/models?limit=1000`;
85
+ }
86
+
87
+ function ollamaApiUrl(base, suffix) {
88
+ const b = trimBase(base);
89
+ if (!b) return null;
90
+ // ollama-cloud engines declare `https://ollama.com/v1`: the native API
91
+ // (`/api/tags`, `/api/show`) lives at the root, not under `/v1`.
92
+ return `${b.replace(/\/v1$/, '')}${suffix}`;
93
+ }
94
+
95
+ function llamaPropsUrl(base) {
96
+ const b = trimBase(base);
97
+ if (!b) return null;
98
+ return `${b.replace(/\/v1$/, '')}/props`;
99
+ }
100
+
101
+ function lmstudioModelsUrl(base) {
102
+ const b = trimBase(base);
103
+ if (!b) return null;
104
+ return /\/api\/v\d+$/.test(b) ? `${b}/models` : `${b}/api/v0/models`;
105
+ }
106
+
107
+ async function httpJson(url, {
108
+ apiKey = '', authMode = 'bearer', method = 'GET', body, fetchImpl, timeoutMs = DEFAULT_TIMEOUT_MS,
109
+ } = {}) {
110
+ // The deadline covers the WHOLE read: headers AND body. The timer stays
111
+ // armed until the response is parsed — a server that answers the headers
112
+ // and then stalls inside `json()` cannot hang the request with no expiry,
113
+ // and the abort while reading is reported as the same fixed timeout reason.
114
+ const controller = new AbortController();
115
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
116
+ const isAbort = (error) => !!(error && (error.name === 'AbortError' || error.code === 'ABORT_ERR'));
117
+ try {
118
+ const headers = { accept: 'application/json' };
119
+ if (body !== undefined) headers['content-type'] = 'application/json';
120
+ if (apiKey) {
121
+ if (authMode === 'x-api-key') {
122
+ headers['x-api-key'] = apiKey;
123
+ headers['anthropic-version'] = ANTHROPIC_VERSION;
124
+ } else {
125
+ headers.authorization = `Bearer ${apiKey}`;
126
+ }
127
+ }
128
+ let response;
129
+ try {
130
+ response = await fetchImpl(url, {
131
+ method,
132
+ headers,
133
+ signal: controller.signal,
134
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
135
+ });
136
+ } catch (error) {
137
+ throw new DiscoveryError(isAbort(error) ? `timeout after ${timeoutMs}ms` : 'network error');
138
+ }
139
+ // Minimal fakes (and some SDK shims) carry `ok` without `status`: honor
140
+ // `ok === true` as 200, mirroring the previous discoverOllamaModels check.
141
+ const okFlag = !!(response && typeof response === 'object' && response.ok === true);
142
+ const status = response && typeof response.status === 'number' ? response.status : (okFlag ? 200 : 0);
143
+ if (!(status >= 200 && status < 300)) throw new DiscoveryError(`HTTP ${status}`);
144
+ let parsed;
145
+ try {
146
+ parsed = await response.json();
147
+ } catch (error) {
148
+ // The timer is still armed here: an abort while reading the body is the
149
+ // deadline expiring again, not a malformed payload.
150
+ throw new DiscoveryError(isAbort(error) ? `timeout after ${timeoutMs}ms` : 'invalid JSON response');
151
+ }
152
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
153
+ throw new DiscoveryError('unexpected response shape');
154
+ }
155
+ return parsed;
156
+ } finally {
157
+ clearTimeout(timer);
158
+ }
159
+ }
160
+
161
+ // One normalized record per model. Fields the source does not provide stay
162
+ // ABSENT — no invented defaults, no guesses.
163
+ function normalizeModelRecord(raw) {
164
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
165
+ const id = typeof raw.id === 'string' ? raw.id : '';
166
+ if (!MODEL_ID_RE.test(id)) return null;
167
+ const out = { id };
168
+ for (const key of ['contextWindow', 'maxTokens']) {
169
+ if (raw[key] === undefined) continue;
170
+ if (Number.isSafeInteger(raw[key]) && raw[key] > 0) out[key] = raw[key];
171
+ }
172
+ for (const key of ['tools', 'vision', 'reasoning', 'deprecated']) {
173
+ if (raw[key] === undefined) continue;
174
+ if (typeof raw[key] === 'boolean') out[key] = raw[key];
175
+ }
176
+ return out;
177
+ }
178
+
179
+ function collectIds(records, seen, out) {
180
+ for (const raw of records) {
181
+ const rec = normalizeModelRecord(raw);
182
+ if (!rec || seen.has(rec.id)) continue;
183
+ seen.add(rec.id);
184
+ out.push(rec);
185
+ }
186
+ return out;
187
+ }
188
+
189
+ // --- Collectors -------------------------------------------------------------
190
+ // Each collector maps an endpoint kind to a list of normalized API records
191
+ // (`{ id, contextWindow?, maxTokens?, tools?, vision?, reasoning? }`).
192
+
193
+ const collectors = {
194
+ // OpenAI-compatible `GET /v1/models`: `{ data: [{ id, ... }] }`. The listing
195
+ // carries ids; context/pricing fields are provider-specific and usually
196
+ // absent — they stay absent.
197
+ 'openai-compat': async ({ baseUrl, apiKey, fetchImpl, timeoutMs }) => {
198
+ const url = openAiStyleModelsUrl(baseUrl);
199
+ if (!url) throw new DiscoveryError('invalid base URL');
200
+ const body = await httpJson(url, { apiKey, fetchImpl, timeoutMs });
201
+ return collectIds(Array.isArray(body.data) ? body.data : [], new Set(), []);
202
+ },
203
+
204
+ // Anthropic `GET /v1/models` with x-api-key + anthropic-version and
205
+ // `after_id` pagination (limit <= 1000 per page, bounded pages).
206
+ 'anthropic': async ({ baseUrl, apiKey, fetchImpl, timeoutMs }) => {
207
+ const base = anthropicModelsUrl(baseUrl);
208
+ if (!base) throw new DiscoveryError('invalid base URL');
209
+ const out = []; const seen = new Set();
210
+ let after = '';
211
+ for (let page = 0; page < ANTHROPIC_MAX_PAGES; page += 1) {
212
+ const url = after ? `${base}&after_id=${encodeURIComponent(after)}` : base;
213
+ const body = await httpJson(url, { apiKey, authMode: 'x-api-key', fetchImpl, timeoutMs });
214
+ collectIds(Array.isArray(body.data) ? body.data : [], seen, out);
215
+ if (body.has_more !== true || typeof body.last_id !== 'string' || !body.last_id) break;
216
+ after = body.last_id;
217
+ }
218
+ return out;
219
+ },
220
+
221
+ // Ollama `GET /api/tags` (+ Bearer key on cloud). `POST /api/show` runs ONLY
222
+ // for listed ids the caller explicitly asked details for (`detailIds`) and
223
+ // only to read what the listing cannot give (context length, capabilities).
224
+ 'ollama': async ({ baseUrl, apiKey, fetchImpl, timeoutMs, detailIds }) => {
225
+ const tagsUrl = ollamaApiUrl(baseUrl, '/api/tags');
226
+ if (!tagsUrl) throw new DiscoveryError('invalid base URL');
227
+ const tags = await httpJson(tagsUrl, { apiKey, fetchImpl, timeoutMs });
228
+ const listed = collectIds(Array.isArray(tags.models) ? tags.models.map((m) => ({
229
+ id: typeof m?.name === 'string' && m.name ? m.name : m?.model,
230
+ })) : [], new Set(), []);
231
+ const wanted = new Set(Array.isArray(detailIds) ? detailIds.filter((id) => typeof id === 'string') : []);
232
+ if (!wanted.size) return listed;
233
+ const showUrl = ollamaApiUrl(baseUrl, '/api/show');
234
+ let calls = 0;
235
+ for (const rec of listed) {
236
+ if (calls >= MAX_SHOW_CALLS) break;
237
+ if (!wanted.has(rec.id)) continue;
238
+ calls += 1;
239
+ try {
240
+ const show = await httpJson(showUrl, {
241
+ method: 'POST', body: { name: rec.id }, apiKey, fetchImpl, timeoutMs,
242
+ });
243
+ for (const [key, value] of Object.entries(show.model_info || {})) {
244
+ if (/\.context_length$/.test(key) && Number.isSafeInteger(value) && value > 0) {
245
+ if (rec.contextWindow === undefined) rec.contextWindow = value;
246
+ break;
247
+ }
248
+ }
249
+ const caps = Array.isArray(show.capabilities) ? show.capabilities : [];
250
+ if (caps.includes('tools')) rec.tools = true;
251
+ if (caps.includes('vision')) rec.vision = true;
252
+ if (caps.includes('thinking') || show.thinking === true) rec.reasoning = true;
253
+ } catch (_) {
254
+ // A failed per-model detail is not a failed discovery: the id stays
255
+ // listed with the fields the listing provides.
256
+ }
257
+ }
258
+ return listed;
259
+ },
260
+
261
+ // llama-server `GET /v1/models` + ONE `GET /props` (resident model only).
262
+ // NEVER a per-model request: on a `--models-max 1` router any per-model
263
+ // request unloads the resident model. `/props` describes whichever model is
264
+ // resident; it enriches at most the matching record and its failure is
265
+ // non-fatal (an idle router still lists its presets).
266
+ 'llama-server': async ({ baseUrl, apiKey, fetchImpl, timeoutMs }) => {
267
+ const modelsUrl = openAiStyleModelsUrl(baseUrl);
268
+ if (!modelsUrl) throw new DiscoveryError('invalid base URL');
269
+ const body = await httpJson(modelsUrl, { apiKey, fetchImpl, timeoutMs });
270
+ const listed = collectIds(Array.isArray(body.data) ? body.data : [], new Set(), []);
271
+ try {
272
+ const props = await httpJson(llamaPropsUrl(baseUrl), { apiKey, fetchImpl, timeoutMs });
273
+ const alias = typeof props.model_alias === 'string' ? props.model_alias : '';
274
+ const target = alias ? listed.find((r) => r.id === alias) : null;
275
+ if (target) {
276
+ if (Number.isSafeInteger(props.n_ctx) && props.n_ctx > 0) target.contextWindow = props.n_ctx;
277
+ if (props.modalities && props.modalities.vision === true) target.vision = true;
278
+ const caps = props.chat_template_caps;
279
+ if (caps && typeof caps === 'object' && caps.tools === true) target.tools = true;
280
+ }
281
+ } catch (_) { /* no resident / props unavailable: the listing stands */ }
282
+ return listed;
283
+ },
284
+
285
+ // LM Studio `GET /api/v0/models`: `{ data: [{ id, max_context_length, ... }] }`.
286
+ 'lmstudio': async ({ baseUrl, apiKey, fetchImpl, timeoutMs }) => {
287
+ const url = lmstudioModelsUrl(baseUrl);
288
+ if (!url) throw new DiscoveryError('invalid base URL');
289
+ const body = await httpJson(url, { apiKey, fetchImpl, timeoutMs });
290
+ const items = Array.isArray(body.data) ? body.data : [];
291
+ return collectIds(items.map((m) => ({
292
+ id: m?.id, contextWindow: m?.max_context_length,
293
+ })), new Set(), []);
294
+ },
295
+ };
296
+
297
+ // --- Disk cache -------------------------------------------------------------
298
+ // <home>/.nexuscrew/model-discovery/<engine>.json, mode 600, atomic write.
299
+ // Only SUCCESSFUL API results are cached; failures never poison the file, and
300
+ // a stale-but-valid file is the "last good value" the fallback chain serves.
301
+ // The cache key is the DECLARED engine id: two engines sharing one profile
302
+ // (two custom engines of the same client) must never share a listing. The
303
+ // record also carries an endpoint FINGERPRINT — a truncated sha256 of the
304
+ // normalized base URL — so a listing fetched from another endpoint is never
305
+ // served (nor kept as last-good) after the engine's endpoint changed. The
306
+ // fingerprint covers the URL only: the API key, or anything derived from it,
307
+ // must never reach the file. Records without a fingerprint (older layout)
308
+ // are simply ignored: no error, no forced deletion.
309
+
310
+ function cacheDirFor(home) { return path.join(home, '.nexuscrew', 'model-discovery'); }
311
+
312
+ function safeEngineKey(engine) {
313
+ const e = String(engine || '');
314
+ return ENGINE_KEY_RE.test(e) ? e : crypto.createHash('sha256').update(e).digest('hex').slice(0, 16);
315
+ }
316
+
317
+ function cachePathFor(home, engine) { return path.join(cacheDirFor(home), `${safeEngineKey(engine)}.json`); }
318
+
319
+ function endpointFingerprint(baseUrl) {
320
+ const base = trimBase(baseUrl) || '';
321
+ return crypto.createHash('sha256').update(base).digest('hex').slice(0, 16);
322
+ }
323
+
324
+ function readCache(home, engine, endpoint) {
325
+ try {
326
+ const parsed = JSON.parse(fs.readFileSync(cachePathFor(home, engine), 'utf8'));
327
+ if (!parsed || typeof parsed !== 'object') return null;
328
+ if (parsed.version !== CACHE_VERSION || parsed.engine !== String(engine)) return null;
329
+ if (!Array.isArray(parsed.models) || !Number.isSafeInteger(parsed.fetchedAt)) return null;
330
+ if (parsed.endpoint !== endpoint) return null;
331
+ // A successful EMPTY listing is a valid record: a provider that dropped
332
+ // every model must not fall back to the previous one forever.
333
+ const models = collectIds(parsed.models, new Set(), []);
334
+ return { fetchedAt: parsed.fetchedAt, collector: typeof parsed.collector === 'string' ? parsed.collector : '', models };
335
+ } catch (_) { return null; }
336
+ }
337
+
338
+ function writeCache(home, engine, collector, fetchedAt, models, endpoint) {
339
+ const dir = cacheDirFor(home);
340
+ try {
341
+ const st = fs.lstatSync(dir);
342
+ if (st.isSymbolicLink() || !st.isDirectory()) throw new Error('unsafe model-discovery directory');
343
+ } catch (e) {
344
+ if (e.code === 'ENOENT') fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
345
+ else throw e;
346
+ }
347
+ fs.chmodSync(dir, 0o700);
348
+ const target = cachePathFor(home, engine);
349
+ const tmp = path.join(dir, `.${safeEngineKey(engine)}.${crypto.randomBytes(6).toString('hex')}.tmp`);
350
+ const payload = JSON.stringify({ version: CACHE_VERSION, engine: String(engine), collector, fetchedAt, models, endpoint });
351
+ try {
352
+ fs.writeFileSync(tmp, payload, { mode: 0o600 });
353
+ fs.chmodSync(tmp, 0o600);
354
+ fs.renameSync(tmp, target);
355
+ } catch (e) {
356
+ try { fs.unlinkSync(tmp); } catch (_) {}
357
+ throw e;
358
+ }
359
+ }
360
+
361
+ // --- Public catalog snapshot (lot 2: models.dev) -----------------------------
362
+ // Third source: a public, key-less catalog. NEVER mandatory: on failure the
363
+ // last good snapshot serves, then nothing — an engine keeps working on its
364
+ // user/api/backup layers either way. The snapshot is large (~6 MB), so the TTL
365
+ // is one day, the default timeout is generous, and a fresh read is memoized
366
+ // in-process so per-engine lookups do not reparse the file every time.
367
+
368
+ const PUBLIC_CATALOG_URL = 'https://models.dev/api.json';
369
+ const PUBLIC_CATALOG_TTL_MS = 24 * 60 * 60 * 1000;
370
+ const PUBLIC_CATALOG_TIMEOUT_MS = 10000;
371
+ const PUBLIC_CATALOG_CACHE_FILE = 'public-catalog.json';
372
+
373
+ // Shape: `{ "<provider>": { id, name, models: { "<model>": { … } } } }`. Model
374
+ // entries are validated leniently at LOOKUP time (absent fields stay absent);
375
+ // here only the provider level must hold.
376
+ function validateCatalogSnapshot(parsed) {
377
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
378
+ let withModels = 0;
379
+ for (const provider of Object.values(parsed)) {
380
+ if (!provider || typeof provider !== 'object' || Array.isArray(provider)) return false;
381
+ if (provider.models && typeof provider.models === 'object' && !Array.isArray(provider.models)) withModels += 1;
382
+ }
383
+ return withModels > 0;
384
+ }
385
+
386
+ function readPublicCatalogCache(home) {
387
+ try {
388
+ const parsed = JSON.parse(fs.readFileSync(path.join(cacheDirFor(home), PUBLIC_CATALOG_CACHE_FILE), 'utf8'));
389
+ if (!parsed || typeof parsed !== 'object') return null;
390
+ if (parsed.version !== CACHE_VERSION || parsed.kind !== 'public-catalog') return null;
391
+ if (!Number.isSafeInteger(parsed.fetchedAt) || !validateCatalogSnapshot(parsed.providers)) return null;
392
+ return { fetchedAt: parsed.fetchedAt, catalog: parsed.providers };
393
+ } catch (_) { return null; }
394
+ }
395
+
396
+ function writePublicCatalogCache(home, fetchedAt, catalog) {
397
+ const dir = cacheDirFor(home);
398
+ try {
399
+ const st = fs.lstatSync(dir);
400
+ if (st.isSymbolicLink() || !st.isDirectory()) throw new Error('unsafe model-discovery directory');
401
+ } catch (e) {
402
+ if (e.code === 'ENOENT') fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
403
+ else throw e;
404
+ }
405
+ fs.chmodSync(dir, 0o700);
406
+ const target = path.join(dir, PUBLIC_CATALOG_CACHE_FILE);
407
+ const tmp = path.join(dir, `.public-catalog.${crypto.randomBytes(6).toString('hex')}.tmp`);
408
+ const payload = JSON.stringify({ version: CACHE_VERSION, kind: 'public-catalog', fetchedAt, providers: catalog });
409
+ try {
410
+ fs.writeFileSync(tmp, payload, { mode: 0o600 });
411
+ fs.chmodSync(tmp, 0o600);
412
+ fs.renameSync(tmp, target);
413
+ } catch (e) {
414
+ try { fs.unlinkSync(tmp); } catch (_) {}
415
+ throw e;
416
+ }
417
+ }
418
+
419
+ // --- Public catalog mapping --------------------------------------------------
420
+ // Engine provider -> catalog provider id, as an explicit, TESTED table: no
421
+ // inference. Unlisted providers (local runtimes, login accounts, custom
422
+ // gateways on unknown hosts) get NO public layer at all — a missing mapping
423
+ // means no data, never a guess.
424
+
425
+ const PUBLIC_CATALOG_PROVIDER_IDS = Object.freeze({
426
+ zai: 'zai',
427
+ 'zai-a': 'zai',
428
+ 'zai-p': 'zai',
429
+ 'ollama-cloud': 'ollama-cloud',
430
+ 'opencode-go': 'opencode-go',
431
+ anthropic: 'anthropic',
432
+ openai: 'openai',
433
+ 'openai-api': 'openai',
434
+ 'openai-codex': 'openai',
435
+ deepseek: 'deepseek',
436
+ openrouter: 'openrouter',
437
+ nvidia: 'nvidia',
438
+ xai: 'xai',
439
+ });
440
+
441
+ // Custom engines carry no provider type: an EXACT host match is the only
442
+ // fallback. No suffix or substring matching — a lookalike host maps to nothing.
443
+ const PUBLIC_CATALOG_HOSTS = Object.freeze({
444
+ 'api.z.ai': 'zai',
445
+ 'opencode.ai': 'opencode-go',
446
+ 'ollama.com': 'ollama-cloud',
447
+ 'api.anthropic.com': 'anthropic',
448
+ 'api.openai.com': 'openai',
449
+ 'openrouter.ai': 'openrouter',
450
+ 'api.deepseek.com': 'deepseek',
451
+ 'api.x.ai': 'xai',
452
+ 'integrate.api.nvidia.com': 'nvidia',
453
+ });
454
+
455
+ function publicCatalogProviderId({ provider, baseUrl } = {}) {
456
+ const type = PUBLIC_CATALOG_PROVIDER_IDS[String(provider || '')];
457
+ if (type) return type;
458
+ const base = trimBase(baseUrl);
459
+ if (!base) return null;
460
+ let host;
461
+ try { host = new URL(base).hostname.toLowerCase(); } catch (_) { return null; }
462
+ return PUBLIC_CATALOG_HOSTS[host] || null;
463
+ }
464
+
465
+ // Candidate catalog ids for one API model id, best first: exact, case-folded,
466
+ // one "vendor/" prefix dropped, then each of those without a ":cloud"/"-cloud"
467
+ // suffix. Context-variant markers like "[1m]" are deliberately NOT stripped:
468
+ // inheriting the base model's limits would import wrong numbers.
469
+ function publicCatalogIdCandidates(apiId) {
470
+ const out = [];
471
+ const push = (v) => { if (v && !out.includes(v)) out.push(v); };
472
+ const id = String(apiId || '');
473
+ push(id);
474
+ push(id.toLowerCase());
475
+ const slash = id.indexOf('/');
476
+ if (slash > 0 && slash < id.length - 1) {
477
+ push(id.slice(slash + 1));
478
+ push(id.slice(slash + 1).toLowerCase());
479
+ }
480
+ for (const base of [...out]) {
481
+ const stripped = base.replace(/(?::cloud|-cloud)$/, '');
482
+ if (stripped !== base) { push(stripped); push(stripped.toLowerCase()); }
483
+ }
484
+ return out;
485
+ }
486
+
487
+ // One normalized record per MATCHING api id. The record keeps the API id, so
488
+ // it merges onto the engine's own listing; catalog fields map as:
489
+ // limit.context -> contextWindow, limit.output -> maxTokens, tool_call ->
490
+ // tools, modalities.input "image" -> vision, reasoning -> reasoning,
491
+ // status "deprecated" -> deprecated. Absent catalog fields stay absent.
492
+ function normalizePublicCatalogModel(id, m) {
493
+ const out = { id };
494
+ const limit = m.limit && typeof m.limit === 'object' && !Array.isArray(m.limit) ? m.limit : {};
495
+ if (Number.isSafeInteger(limit.context) && limit.context > 0) out.contextWindow = limit.context;
496
+ if (Number.isSafeInteger(limit.output) && limit.output > 0) out.maxTokens = limit.output;
497
+ if (typeof m.tool_call === 'boolean') out.tools = m.tool_call;
498
+ const input = m.modalities && Array.isArray(m.modalities.input) ? m.modalities.input : null;
499
+ if (input) out.vision = input.includes('image');
500
+ if (typeof m.reasoning === 'boolean') out.reasoning = m.reasoning;
501
+ if (m.status === 'deprecated') out.deprecated = true;
502
+ return out;
503
+ }
504
+
505
+ function publicCatalogRecords(catalog, providerId, modelIds) {
506
+ const provider = catalog && typeof catalog === 'object' && !Array.isArray(catalog) ? catalog[providerId] : null;
507
+ const models = provider && typeof provider === 'object' && !Array.isArray(provider)
508
+ && provider.models && typeof provider.models === 'object' && !Array.isArray(provider.models)
509
+ ? provider.models : null;
510
+ if (!models) return [];
511
+ const lcIndex = new Map();
512
+ for (const key of Object.keys(models)) {
513
+ const lc = key.toLowerCase();
514
+ if (!lcIndex.has(lc)) lcIndex.set(lc, key);
515
+ }
516
+ const out = [];
517
+ const seen = new Set();
518
+ for (const apiId of Array.isArray(modelIds) ? modelIds : []) {
519
+ if (typeof apiId !== 'string' || !apiId || seen.has(apiId)) continue;
520
+ seen.add(apiId);
521
+ let entry = null;
522
+ for (const cand of publicCatalogIdCandidates(apiId)) {
523
+ const hit = Object.prototype.hasOwnProperty.call(models, cand)
524
+ ? models[cand]
525
+ : (lcIndex.has(cand.toLowerCase()) ? models[lcIndex.get(cand.toLowerCase())] : null);
526
+ if (hit && typeof hit === 'object' && !Array.isArray(hit)) { entry = hit; break; }
527
+ }
528
+ // No match -> no record: the model keeps whatever the other layers say.
529
+ if (entry) out.push(normalizePublicCatalogModel(apiId, entry));
530
+ }
531
+ return out;
532
+ }
533
+
534
+ // --- Precedence merge -------------------------------------------------------
535
+ // Field-by-field, per the approved precedence order: user (fleet.json) > provider API >
536
+ // public catalog (models.dev snapshot, lot 2) > internal backup > known-gone.
537
+ // The user layer also fixes the ORDER: user-declared models come first, so the
538
+ // cap can never cut them out of the proposal. The last layer carries BARE IDS
539
+ // of models the API listed on a previous fetch and no longer lists: they carry
540
+ // no fields (nothing below the real layers may invent data), they only keep
541
+ // the row alive with `inApi: false` — a model that was there never silently
542
+ // disappears from the proposal.
543
+
544
+ function mergeModelRecords({
545
+ userModels = [], apiModels = [], publicCatalogModels = [], backupModels = [],
546
+ knownModels = [], apiKnown = true, fetchedAt = 0, cap = DISCOVERY_PROPOSAL_CAP,
547
+ } = {}) {
548
+ const layers = [
549
+ { name: 'user', models: userModels },
550
+ { name: 'api', models: apiModels },
551
+ { name: 'public', models: publicCatalogModels },
552
+ { name: 'backup', models: backupModels },
553
+ { name: 'known', models: knownModels },
554
+ ];
555
+ const merged = new Map(); // id -> { order, values, fieldSources, source }
556
+ const apiIds = new Set();
557
+ let order = 0;
558
+ for (const layer of layers) {
559
+ const records = collectIds(Array.isArray(layer.models) ? layer.models : [], new Set(), []);
560
+ if (layer.name === 'api') for (const r of records) apiIds.add(r.id);
561
+ for (const rec of records) {
562
+ let entry = merged.get(rec.id);
563
+ if (!entry) {
564
+ entry = { order: order++, values: {}, fieldSources: {}, source: layer.name };
565
+ merged.set(rec.id, entry);
566
+ }
567
+ for (const field of MERGE_FIELDS) {
568
+ if (rec[field] !== undefined && entry.values[field] === undefined) {
569
+ entry.values[field] = rec[field];
570
+ entry.fieldSources[field] = layer.name;
571
+ }
572
+ }
573
+ }
574
+ }
575
+ const effectiveCap = Number.isSafeInteger(cap) && cap > 0 ? cap : DISCOVERY_PROPOSAL_CAP;
576
+ return [...merged.entries()]
577
+ .sort((a, b) => a[1].order - b[1].order)
578
+ .slice(0, effectiveCap)
579
+ .map(([id, entry]) => ({
580
+ id,
581
+ ...entry.values,
582
+ source: entry.source,
583
+ ...(Object.keys(entry.fieldSources).length ? { fieldSources: entry.fieldSources } : {}),
584
+ ...(apiKnown ? { inApi: apiIds.has(id) } : {}),
585
+ ...(fetchedAt ? { fetchedAt } : {}),
586
+ }));
587
+ }
588
+
589
+ // --- Discovery instance -----------------------------------------------------
590
+
591
+ function createModelDiscovery({ fetchImpl: defaultFetchImpl = globalThis.fetch, now = () => Date.now() } = {}) {
592
+ // Raw API layer with cache + fallback. `noCache: true` disattiva la cache in
593
+ // ENTRAMBE le direzioni: nessuna lettura, nessuna scrittura, e su errore la
594
+ // ricaduta e' il backup (vuoto), non l'ultimo valore buono.
595
+ // Returns:
596
+ // { status: 'api', fetchedAt, apiModels, stale: false, error: '' }
597
+ // { status: 'cache', fetchedAt, apiModels, stale: true|false, error } (last good value)
598
+ // { status: 'backup', fetchedAt: 0, apiModels: [], stale: false, error } (nothing known)
599
+ async function fetchEngineModels(opts = {}) {
600
+ const {
601
+ engine, collector, baseUrl, apiKey = '', home,
602
+ noCache = false, ttlMs, timeoutMs = DEFAULT_TIMEOUT_MS, detailIds,
603
+ fetchImpl = defaultFetchImpl,
604
+ } = opts;
605
+ if (!engine) throw new DiscoveryError('engine is required');
606
+ if (!COLLECTOR_KINDS.includes(collector)) throw new DiscoveryError(`unknown collector: ${collector}`);
607
+ if (typeof fetchImpl !== 'function') throw new DiscoveryError('no fetch implementation');
608
+ const ttl = ttlMs === undefined ? collectorDefaultTtlMs(collector) : ttlMs;
609
+ const at = now();
610
+ const endpoint = endpointFingerprint(baseUrl);
611
+ // `noCache` deve voler dire UNA cosa: nessuna cache. Non solo «salta il
612
+ // valore fresco», ma nemmeno LEGGE (per ricadere sull'ultimo buono) e
613
+ // nemmeno SCRIVE. Il caso che l'ha imposto: una fixture ha scritto la cache
614
+ // nella home vera dell'operatore; e con `noCache` attivo una lettura ferma
615
+ // non e' una risposta, e' un residuo di ieri.
616
+ // L'UNICA lettura che sopravvive a noCache e' il listing PRECEDENTE, e non
617
+ // come risposta: serve solo a calcolare quali id l'API ha tolto (il delta
618
+ // «prima c'era, ora no»). La risposta non esce mai dal file e il file non
619
+ // si scrive: e' storia, non cache attiva.
620
+ const previous = home ? readCache(home, engine, endpoint) : null;
621
+ const cached = !noCache ? previous : null;
622
+ if (!noCache && cached && at - cached.fetchedAt < ttl) {
623
+ return {
624
+ status: 'cache', fetchedAt: cached.fetchedAt, stale: false, error: '',
625
+ apiModels: cached.models.map((m) => ({ ...m })),
626
+ };
627
+ }
628
+ let apiModels;
629
+ try {
630
+ apiModels = await collectors[collector]({ baseUrl, apiKey, fetchImpl, timeoutMs, detailIds });
631
+ } catch (error) {
632
+ const reason = error instanceof DiscoveryError ? error.reason : 'discovery failed';
633
+ if (cached) {
634
+ return {
635
+ status: 'cache', fetchedAt: cached.fetchedAt, stale: true, error: reason,
636
+ apiModels: cached.models.map((m) => ({ ...m })),
637
+ };
638
+ }
639
+ return { status: 'backup', fetchedAt: 0, stale: false, error: reason, apiModels: [] };
640
+ }
641
+ const fetchedAt = now();
642
+ // Il delta degli spariti si calcola SOLO su una lettura vera: la risposta
643
+ // fresca riuscita contro il listing precedente. Gli id che mancano restano
644
+ // fuori dalla cache appena scritta: il file conserva il listing come
645
+ // l'API l'ha dato, non la nostra storia.
646
+ const freshIds = new Set(apiModels.map((m) => m.id));
647
+ const disappeared = previous
648
+ ? previous.models.filter((m) => !freshIds.has(m.id)).map((m) => m.id)
649
+ : [];
650
+ // The write follows the SUCCESS, not the size: an empty listing that the
651
+ // API answered with replaces the previous one. Failures never reach here.
652
+ if (!noCache && home) {
653
+ try { writeCache(home, engine, collector, fetchedAt, apiModels, endpoint); } catch (_) { /* cache is best-effort */ }
654
+ }
655
+ return {
656
+ status: 'api', fetchedAt, stale: false, error: '',
657
+ apiModels: apiModels.map((m) => ({ ...m })),
658
+ ...(disappeared.length ? { disappeared } : {}),
659
+ };
660
+ }
661
+
662
+ // Public catalog snapshot with cache + fallback. Same contract shape as
663
+ // fetchEngineModels, minus any key — and the SAME noCache contract as the
664
+ // API layer: with `noCache` the snapshot is never served as the answer,
665
+ // never used as a ripiego on failure, and never written (disk or memo):
666
+ // { status: 'api', fetchedAt, stale: false, error: '', catalog }
667
+ // { status: 'cache', fetchedAt, stale: true|false, error, catalog } (last good)
668
+ // { status: 'none', fetchedAt: 0, stale: false, error, catalog: null }
669
+ let publicCatalogMemo = null; // { home, fetchedAt, catalog }: same-process reuse
670
+ async function fetchPublicCatalogSnapshot(opts = {}) {
671
+ const {
672
+ home, noCache = false, ttlMs = PUBLIC_CATALOG_TTL_MS,
673
+ timeoutMs = PUBLIC_CATALOG_TIMEOUT_MS, fetchImpl = defaultFetchImpl,
674
+ } = opts;
675
+ if (typeof fetchImpl !== 'function') throw new DiscoveryError('no fetch implementation');
676
+ const at = now();
677
+ const memoFresh = !noCache && publicCatalogMemo && publicCatalogMemo.home === home
678
+ && at - publicCatalogMemo.fetchedAt < ttlMs;
679
+ if (memoFresh) {
680
+ return {
681
+ status: 'cache', fetchedAt: publicCatalogMemo.fetchedAt, stale: false, error: '',
682
+ catalog: publicCatalogMemo.catalog,
683
+ };
684
+ }
685
+ const cached = home ? readPublicCatalogCache(home) : null;
686
+ if (!noCache && cached && at - cached.fetchedAt < ttlMs) {
687
+ publicCatalogMemo = { home, fetchedAt: cached.fetchedAt, catalog: cached.catalog };
688
+ return {
689
+ status: 'cache', fetchedAt: cached.fetchedAt, stale: false, error: '',
690
+ catalog: cached.catalog,
691
+ };
692
+ }
693
+ let catalog;
694
+ try {
695
+ // Public endpoint: no key, no auth header, fixed accept header only.
696
+ catalog = await httpJson(PUBLIC_CATALOG_URL, { fetchImpl, timeoutMs });
697
+ if (!validateCatalogSnapshot(catalog)) throw new DiscoveryError('unexpected response shape');
698
+ } catch (error) {
699
+ const reason = error instanceof DiscoveryError ? error.reason : 'catalog fetch failed';
700
+ if (cached && !noCache) {
701
+ publicCatalogMemo = { home, fetchedAt: cached.fetchedAt, catalog: cached.catalog };
702
+ return { status: 'cache', fetchedAt: cached.fetchedAt, stale: true, error: reason, catalog: cached.catalog };
703
+ }
704
+ return { status: 'none', fetchedAt: 0, stale: false, error: reason, catalog: null };
705
+ }
706
+ const fetchedAt = now();
707
+ // A forced read answers but leaves no trace: neither the memo nor the disk
708
+ // snapshot is written under noCache.
709
+ if (!noCache) publicCatalogMemo = { home, fetchedAt, catalog };
710
+ if (home && !noCache) {
711
+ try { writePublicCatalogCache(home, fetchedAt, catalog); } catch (_) { /* cache is best-effort */ }
712
+ }
713
+ return { status: 'api', fetchedAt, stale: false, error: '', catalog };
714
+ }
715
+
716
+ // Public layer for one engine: map the provider, snapshot the catalog (its
717
+ // own TTL, cache and fallback), then normalize records for the ids the
718
+ // engine already knows from the user/api/backup layers. The public catalog
719
+ // COMPLETES fields; it never adds models to the proposal. An unmapped
720
+ // provider skips the network entirely.
721
+ async function resolvePublicCatalogLayer(opts, apiModels, userModels, backupModels) {
722
+ const config = opts.publicCatalog && typeof opts.publicCatalog === 'object' ? opts.publicCatalog : {};
723
+ const providerId = publicCatalogProviderId(config);
724
+ if (!providerId) {
725
+ return { providerId: null, records: [], summary: { providerId: null, status: 'skipped', records: 0 } };
726
+ }
727
+ const ids = [];
728
+ const seen = new Set();
729
+ for (const list of [userModels, apiModels, backupModels]) {
730
+ for (const m of Array.isArray(list) ? list : []) {
731
+ const id = m && typeof m.id === 'string' ? m.id : null;
732
+ if (id && !seen.has(id)) { seen.add(id); ids.push(id); }
733
+ }
734
+ }
735
+ // `noCache` is ONE contract on BOTH layers: a forced refresh that skips
736
+ // the engine cache skips the public snapshot too. The engine-level flag
737
+ // reaches the snapshot unless the publicCatalog config overrides it.
738
+ const noCache = config.noCache === true || opts.noCache === true;
739
+ const snapshot = await fetchPublicCatalogSnapshot({
740
+ home: opts.home,
741
+ ...(config.fetchImpl !== undefined ? { fetchImpl: config.fetchImpl } : {}),
742
+ ...(config.timeoutMs !== undefined ? { timeoutMs: config.timeoutMs } : {}),
743
+ ...(config.ttlMs !== undefined ? { ttlMs: config.ttlMs } : {}),
744
+ ...(noCache ? { noCache: true } : {}),
745
+ });
746
+ if (!snapshot.catalog) {
747
+ return {
748
+ providerId, records: [],
749
+ summary: { providerId, status: snapshot.status, error: snapshot.error, records: 0 },
750
+ };
751
+ }
752
+ const records = publicCatalogRecords(snapshot.catalog, providerId, ids);
753
+ return {
754
+ providerId, records,
755
+ summary: {
756
+ providerId, status: snapshot.status, fetchedAt: snapshot.fetchedAt,
757
+ stale: snapshot.stale, error: snapshot.error, records: records.length,
758
+ },
759
+ };
760
+ }
761
+
762
+ // Full engine view: API layer + user/backup layers merged per field, capped,
763
+ // with `inApi` marked only when the API (or its last good value) actually
764
+ // answered. The public catalog layer joins the merge when `publicCatalog`
765
+ // describes the engine's provider (or when `publicCatalogModels` is supplied
766
+ // pre-built, e.g. by tests and later UI lots).
767
+ async function discoverEngine(opts = {}) {
768
+ const {
769
+ userModels = [], backupModels = [], publicCatalogModels, publicCatalog,
770
+ cap = DISCOVERY_PROPOSAL_CAP,
771
+ } = opts;
772
+ const layer = await fetchEngineModels(opts);
773
+ let publicModels = Array.isArray(publicCatalogModels) ? publicCatalogModels : [];
774
+ let publicLayer = null;
775
+ if (!Array.isArray(publicCatalogModels) && publicCatalog) {
776
+ publicLayer = await resolvePublicCatalogLayer(opts, layer.apiModels, userModels, backupModels);
777
+ publicModels = publicLayer.records;
778
+ }
779
+ const apiKnown = layer.status !== 'backup';
780
+ const models = mergeModelRecords({
781
+ userModels,
782
+ apiModels: layer.apiModels,
783
+ publicCatalogModels: publicModels,
784
+ backupModels,
785
+ knownModels: (layer.disappeared || []).map((id) => ({ id })),
786
+ apiKnown,
787
+ fetchedAt: layer.fetchedAt || now(),
788
+ cap,
789
+ });
790
+ return {
791
+ ...layer,
792
+ source: layer.status,
793
+ models,
794
+ ...(publicLayer ? { publicCatalog: publicLayer.summary } : {}),
795
+ };
796
+ }
797
+
798
+ return { fetchEngineModels, discoverEngine, fetchPublicCatalogSnapshot, limits: { cap: DISCOVERY_PROPOSAL_CAP } };
799
+ }
800
+
801
+ module.exports = {
802
+ COLLECTOR_KINDS,
803
+ DiscoveryError,
804
+ createModelDiscovery,
805
+ mergeModelRecords,
806
+ normalizeModelRecord,
807
+ collectorDefaultTtlMs,
808
+ PUBLIC_CATALOG_URL,
809
+ PUBLIC_CATALOG_TTL_MS,
810
+ publicCatalogProviderId,
811
+ publicCatalogIdCandidates,
812
+ publicCatalogRecords,
813
+ DISCOVERY_PROPOSAL_CAP,
814
+ DEFAULT_TIMEOUT_MS,
815
+ };