@pixelbyte-software/pixcode 1.33.10 → 1.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/api-docs.html +395 -395
  2. package/dist/assets/{index-B_dU5AHA.js → index-BvClqlMf.js} +134 -134
  3. package/dist/favicon.svg +8 -8
  4. package/dist/icons/icon-128x128.svg +9 -9
  5. package/dist/icons/icon-144x144.svg +9 -9
  6. package/dist/icons/icon-152x152.svg +9 -9
  7. package/dist/icons/icon-192x192.svg +9 -9
  8. package/dist/icons/icon-384x384.svg +9 -9
  9. package/dist/icons/icon-512x512.svg +9 -9
  10. package/dist/icons/icon-72x72.svg +9 -9
  11. package/dist/icons/icon-96x96.svg +9 -9
  12. package/dist/icons/icon-template.svg +9 -9
  13. package/dist/index.html +1 -1
  14. package/dist/logo.svg +12 -12
  15. package/dist/openapi.yaml +1311 -1311
  16. package/dist-server/server/index.js +4 -0
  17. package/dist-server/server/index.js.map +1 -1
  18. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js +47 -0
  19. package/dist-server/server/modules/orchestration/a2a/adapter-registry.js.map +1 -0
  20. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js +17 -0
  21. package/dist-server/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.js.map +1 -0
  22. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js +233 -0
  23. package/dist-server/server/modules/orchestration/a2a/adapters/claude-code.adapter.js.map +1 -0
  24. package/dist-server/server/modules/orchestration/a2a/agent-card.js +50 -0
  25. package/dist-server/server/modules/orchestration/a2a/agent-card.js.map +1 -0
  26. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js +25 -0
  27. package/dist-server/server/modules/orchestration/a2a/auth.middleware.js.map +1 -0
  28. package/dist-server/server/modules/orchestration/a2a/bus.js +34 -0
  29. package/dist-server/server/modules/orchestration/a2a/bus.js.map +1 -0
  30. package/dist-server/server/modules/orchestration/a2a/routes.js +233 -0
  31. package/dist-server/server/modules/orchestration/a2a/routes.js.map +1 -0
  32. package/dist-server/server/modules/orchestration/a2a/types.js +6 -0
  33. package/dist-server/server/modules/orchestration/a2a/types.js.map +1 -0
  34. package/dist-server/server/modules/orchestration/a2a/validator.js +85 -0
  35. package/dist-server/server/modules/orchestration/a2a/validator.js.map +1 -0
  36. package/dist-server/server/modules/orchestration/index.js +10 -0
  37. package/dist-server/server/modules/orchestration/index.js.map +1 -0
  38. package/dist-server/server/opencode-cli.js +4 -1
  39. package/dist-server/server/opencode-cli.js.map +1 -1
  40. package/package.json +178 -178
  41. package/scripts/smoke/a2a-roundtrip.mjs +98 -0
  42. package/server/database/db.js +794 -794
  43. package/server/database/json-store.js +194 -194
  44. package/server/index.js +9 -0
  45. package/server/modules/orchestration/a2a/adapter-registry.ts +58 -0
  46. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +49 -0
  47. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +283 -0
  48. package/server/modules/orchestration/a2a/agent-card.ts +55 -0
  49. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -0
  50. package/server/modules/orchestration/a2a/bus.ts +46 -0
  51. package/server/modules/orchestration/a2a/routes.ts +264 -0
  52. package/server/modules/orchestration/a2a/types.ts +111 -0
  53. package/server/modules/orchestration/a2a/validator.ts +90 -0
  54. package/server/modules/orchestration/index.ts +26 -0
  55. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  56. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  57. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  58. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  59. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  60. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  61. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  62. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  63. package/server/modules/providers/shared/provider-configs.ts +142 -142
  64. package/server/opencode-cli.js +4 -1
  65. package/server/opencode-response-handler.js +107 -107
  66. package/server/qwen-code-cli.js +395 -395
  67. package/server/qwen-response-handler.js +73 -73
  68. package/server/routes/qwen.js +27 -27
  69. package/server/services/external-access.js +171 -171
  70. package/server/services/provider-credentials.js +189 -189
  71. package/server/services/provider-models.js +381 -381
  72. package/server/services/telegram/telegram-http-client.js +130 -130
  73. package/server/services/vapid-keys.js +36 -36
  74. package/server/utils/port-access.js +209 -209
  75. package/scripts/rest-sweep.mjs +0 -93
@@ -1,381 +1,381 @@
1
- /**
2
- * Provider model catalog — dynamic discovery + persistent cache.
3
- *
4
- * Each CLI provider offers a different way to list the models it can run:
5
- *
6
- * - Anthropic: https://api.anthropic.com/v1/models (API key required)
7
- * - OpenAI : https://api.openai.com/v1/models (or a custom baseUrl when
8
- * the user points Codex at an OpenAI-compatible proxy)
9
- * - Google : https://generativelanguage.googleapis.com/v1beta/models
10
- * - Qwen : same OpenAI-compat shape when users BYOK through
11
- * ModelStudio / ModelScope / OpenRouter etc.
12
- *
13
- * The UI still keeps a hardcoded "known good" catalog as a baseline so
14
- * brand-new installs don't show an empty dropdown; discovery merges the
15
- * server-reported list on top, dedupes, and persists to
16
- * `~/.pixcode/provider-models.json` with a 6-hour freshness window.
17
- */
18
- import { promises as fs } from 'node:fs';
19
- import os from 'node:os';
20
- import path from 'node:path';
21
-
22
- import { getProviderCredentials } from './provider-credentials.js';
23
-
24
- const CACHE_FILE = path.join(os.homedir(), '.pixcode', 'provider-models.json');
25
- const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
26
-
27
- async function readCache() {
28
- try {
29
- const raw = await fs.readFile(CACHE_FILE, 'utf8');
30
- const parsed = JSON.parse(raw);
31
- return parsed && typeof parsed === 'object' ? parsed : {};
32
- } catch {
33
- return {};
34
- }
35
- }
36
-
37
- async function writeCache(next) {
38
- await fs.mkdir(path.dirname(CACHE_FILE), { recursive: true });
39
- await fs.writeFile(CACHE_FILE, JSON.stringify(next, null, 2), { mode: 0o600 });
40
- }
41
-
42
- /**
43
- * Cache entry shape:
44
- * { models: [{ value, label, source: 'static' | 'api' }],
45
- * fetchedAt: '<iso date>',
46
- * error?: '...' }
47
- *
48
- * `source` tells the UI which entries came from the live API so a
49
- * refresh can prune stale ones without losing the hand-maintained
50
- * defaults.
51
- */
52
- async function loadCachedEntry(provider) {
53
- const cache = await readCache();
54
- return cache[provider] || null;
55
- }
56
-
57
- async function saveCacheEntry(provider, entry) {
58
- const cache = await readCache();
59
- cache[provider] = { ...entry, fetchedAt: new Date().toISOString() };
60
- await writeCache(cache);
61
- }
62
-
63
- function normalizeList(list) {
64
- if (!Array.isArray(list)) return [];
65
- const seen = new Set();
66
- const out = [];
67
- for (const item of list) {
68
- if (!item || typeof item !== 'object') continue;
69
- const value = typeof item.value === 'string' ? item.value.trim() : '';
70
- if (!value || seen.has(value)) continue;
71
- seen.add(value);
72
- const label = typeof item.label === 'string' && item.label.trim() ? item.label.trim() : value;
73
- const source = item.source === 'api' ? 'api' : 'static';
74
- const entry = { value, label, source };
75
- if (typeof item.free === 'boolean') entry.free = item.free;
76
- out.push(entry);
77
- }
78
- return out;
79
- }
80
-
81
- function mergeCatalogs(primary, secondary) {
82
- const seen = new Map();
83
- for (const item of [...primary, ...secondary]) {
84
- if (!seen.has(item.value)) seen.set(item.value, item);
85
- }
86
- return Array.from(seen.values());
87
- }
88
-
89
- // ---------------- Per-provider live discovery ----------------
90
-
91
- async function discoverAnthropic(apiKey, baseUrl) {
92
- const endpoint = (baseUrl?.replace(/\/+$/, '') || 'https://api.anthropic.com') + '/v1/models';
93
- const response = await fetch(endpoint, {
94
- headers: {
95
- 'x-api-key': apiKey,
96
- 'anthropic-version': '2023-06-01',
97
- },
98
- });
99
- if (!response.ok) throw new Error(`Anthropic /v1/models returned ${response.status}`);
100
- const data = await response.json();
101
- const rows = Array.isArray(data?.data) ? data.data : [];
102
- return rows
103
- .filter((m) => typeof m?.id === 'string')
104
- .map((m) => ({
105
- value: m.id,
106
- label: typeof m.display_name === 'string' && m.display_name.trim() ? m.display_name : m.id,
107
- source: 'api',
108
- }));
109
- }
110
-
111
- async function discoverOpenAiCompat(apiKey, baseUrl, fallbackBase) {
112
- const endpoint = (baseUrl?.replace(/\/+$/, '') || fallbackBase) + '/models';
113
- const response = await fetch(endpoint, {
114
- headers: { Authorization: `Bearer ${apiKey}` },
115
- });
116
- if (!response.ok) {
117
- // 401 specifically means our key is bad — but for codex/qwen/etc.
118
- // users often log in via OAuth (`codex login`, `qwen auth`) which
119
- // doesn't expose an OpenAI-compatible API key. Surface a clean
120
- // "no live discovery available" rather than a scary 401 trace.
121
- if (response.status === 401) {
122
- const err = new Error('OpenAI-compatible /v1/models requires an API key. The static catalog is shown instead — that\'s expected when you signed in via OAuth (e.g. `codex login`).');
123
- err.code = 'OAUTH_NO_API_KEY';
124
- throw err;
125
- }
126
- throw new Error(`${endpoint} returned ${response.status}`);
127
- }
128
- const data = await response.json();
129
- const rows = Array.isArray(data?.data) ? data.data : [];
130
- return rows
131
- .filter((m) => typeof m?.id === 'string')
132
- .map((m) => ({
133
- value: m.id,
134
- label: m.id,
135
- source: 'api',
136
- }));
137
- }
138
-
139
- /**
140
- * Detect whether the user is authenticated via the provider's OAuth flow
141
- * (codex login / qwen auth) so we can skip live model discovery silently
142
- * — those flows don't surface a usable OpenAI-compatible API key, and the
143
- * SDK calls the upstream APIs through its own internal auth path.
144
- */
145
- async function hasProviderOauthAuth(provider) {
146
- if (provider === 'codex') {
147
- try {
148
- await fs.access(path.join(os.homedir(), '.codex', 'auth.json'));
149
- return true;
150
- } catch { return false; }
151
- }
152
- if (provider === 'qwen') {
153
- try {
154
- await fs.access(path.join(os.homedir(), '.qwen', 'oauth_creds.json'));
155
- return true;
156
- } catch { return false; }
157
- }
158
- return false;
159
- }
160
-
161
- /**
162
- * OpenCode is multi-provider — its "model" picker isn't a single API list,
163
- * it's the union of every provider it can route to (Anthropic, OpenAI,
164
- * Google, xAI, OpenRouter, OpenCode Zen, Ollama, etc.). The canonical
165
- * catalog lives at https://models.dev/api.json (no auth, ~1.8 MB JSON, 115
166
- * providers as of 2026-04). We pull that, filter to providers the user
167
- * has authenticated with (read `~/.local/share/opencode/auth.json`) plus
168
- * always include the OpenCode Zen tier (works without explicit auth on
169
- * the free models), drop deprecated entries, and tag free models.
170
- */
171
- async function discoverOpencode() {
172
- const url = process.env.OPENCODE_MODELS_URL || 'https://models.dev/api.json';
173
- const response = await fetch(url, {
174
- // OpenCode itself caches this for hours; we cache for 6h via the
175
- // outer wrapper so a single 7s fetch on cold start is acceptable.
176
- signal: AbortSignal.timeout(15000),
177
- });
178
- if (!response.ok) throw new Error(`models.dev/api.json returned ${response.status}`);
179
- const data = await response.json();
180
- if (!data || typeof data !== 'object') throw new Error('models.dev returned a non-object payload');
181
-
182
- // Read OpenCode's auth.json to know which providers the user can
183
- // actually call. Missing file → only show always-free Zen.
184
- const authedProviders = new Set(['opencode']);
185
- try {
186
- const authPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'auth.json');
187
- const raw = await fs.readFile(authPath, 'utf8');
188
- const auth = JSON.parse(raw);
189
- if (auth && typeof auth === 'object') {
190
- for (const k of Object.keys(auth)) authedProviders.add(k);
191
- }
192
- } catch { /* no auth.json → only Zen free models surface */ }
193
-
194
- // Common env-var providers OpenCode picks up automatically. If the user
195
- // exported one in their shell, surface those models too even without
196
- // auth.json. Mirrors the env list in opencode-auth.provider.ts.
197
- const envProviderHints = {
198
- anthropic: ['ANTHROPIC_API_KEY'],
199
- openai: ['OPENAI_API_KEY'],
200
- google: ['GOOGLE_GENERATIVE_AI_API_KEY', 'GEMINI_API_KEY'],
201
- 'google-vertex': ['GOOGLE_APPLICATION_CREDENTIALS'],
202
- xai: ['XAI_API_KEY'],
203
- groq: ['GROQ_API_KEY'],
204
- cerebras: ['CEREBRAS_API_KEY'],
205
- openrouter: ['OPENROUTER_API_KEY'],
206
- };
207
- for (const [providerId, envVars] of Object.entries(envProviderHints)) {
208
- if (envVars.some((v) => process.env[v]?.trim())) authedProviders.add(providerId);
209
- }
210
-
211
- const out = [];
212
- for (const [providerId, providerCfg] of Object.entries(data)) {
213
- if (!authedProviders.has(providerId)) continue;
214
- if (!providerCfg || typeof providerCfg !== 'object') continue;
215
- const models = providerCfg.models;
216
- if (!models || typeof models !== 'object') continue;
217
-
218
- const providerName = typeof providerCfg.name === 'string' && providerCfg.name.trim()
219
- ? providerCfg.name
220
- : providerId;
221
-
222
- for (const [modelId, modelCfg] of Object.entries(models)) {
223
- if (!modelCfg || typeof modelCfg !== 'object') continue;
224
- // Skip deprecated entries from the default list — users can
225
- // still hand-type them if they really need to.
226
- if (modelCfg.status === 'deprecated') continue;
227
- const cost = modelCfg.cost && typeof modelCfg.cost === 'object' ? modelCfg.cost : null;
228
- const free = !cost || (Number(cost.input) === 0 && Number(cost.output) === 0);
229
- const ctx = modelCfg.limit?.context;
230
- const ctxLabel = typeof ctx === 'number' && ctx > 0
231
- ? ` · ${ctx >= 1_000_000 ? `${(ctx / 1_000_000).toFixed(1)}M` : `${Math.round(ctx / 1000)}K`}`
232
- : '';
233
- const freeLabel = free ? ' · Free' : '';
234
- const modelName = typeof modelCfg.name === 'string' && modelCfg.name.trim()
235
- ? modelCfg.name
236
- : modelId;
237
-
238
- out.push({
239
- value: `${providerId}/${modelId}`,
240
- label: `${providerName} · ${modelName}${ctxLabel}${freeLabel}`,
241
- source: 'api',
242
- free,
243
- });
244
- }
245
- }
246
-
247
- // Sort: free first (handy when the user is unauthed), then by label.
248
- out.sort((a, b) => {
249
- if (a.free !== b.free) return a.free ? -1 : 1;
250
- return a.label.localeCompare(b.label);
251
- });
252
-
253
- return out;
254
- }
255
-
256
- async function discoverGoogle(apiKey) {
257
- // Google Generative Language API — public models list, API key as query.
258
- const endpoint = `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`;
259
- const response = await fetch(endpoint);
260
- if (!response.ok) throw new Error(`Google /v1beta/models returned ${response.status}`);
261
- const data = await response.json();
262
- const rows = Array.isArray(data?.models) ? data.models : [];
263
- return rows
264
- .filter((m) => typeof m?.name === 'string' && m.name.includes('models/'))
265
- .map((m) => {
266
- const id = m.name.replace(/^models\//, '');
267
- return {
268
- value: id,
269
- label: typeof m.displayName === 'string' && m.displayName.trim() ? m.displayName : id,
270
- source: 'api',
271
- };
272
- });
273
- }
274
-
275
- /**
276
- * Returns the merged catalog for a provider.
277
- * opts.forceRefresh: ignore cache and hit the upstream API
278
- * opts.staticList: hardcoded fallback from shared/modelConstants.js
279
- */
280
- export async function getProviderModels(provider, opts = {}) {
281
- const { forceRefresh = false, staticList = [] } = opts;
282
- const staticCatalog = normalizeList(staticList.map((m) => ({ ...m, source: 'static' })));
283
-
284
- const cached = await loadCachedEntry(provider);
285
- const cacheFresh = cached?.fetchedAt
286
- ? Date.now() - Date.parse(cached.fetchedAt) < CACHE_TTL_MS
287
- : false;
288
-
289
- if (!forceRefresh && cacheFresh && Array.isArray(cached?.models)) {
290
- return {
291
- models: mergeCatalogs(normalizeList(cached.models), staticCatalog),
292
- fetchedAt: cached.fetchedAt,
293
- error: cached.error,
294
- fromCache: true,
295
- };
296
- }
297
-
298
- // OpenCode is the odd one out: its catalog is models.dev, not a per-key
299
- // API endpoint. Skip the credential plumbing and dispatch straight.
300
- let liveModels = [];
301
- let error;
302
- if (provider === 'opencode') {
303
- try {
304
- liveModels = await discoverOpencode();
305
- } catch (err) {
306
- error = err?.message || String(err);
307
- }
308
- const merged = mergeCatalogs(normalizeList(liveModels), staticCatalog);
309
- const entry = { models: merged, error };
310
- await saveCacheEntry(provider, entry).catch(() => { /* non-fatal */ });
311
- return { models: merged, fetchedAt: new Date().toISOString(), error, fromCache: false };
312
- }
313
-
314
- // Pick up credentials from Pixcode's UI store first, then fall back to
315
- // the native env vars so a user who already exported ANTHROPIC_API_KEY
316
- // (or authenticated Claude Code via OAuth — the SDK writes the key into
317
- // process.env on boot) gets live models without re-entering anything.
318
- const creds = await getProviderCredentials(provider);
319
- const envKey = {
320
- claude: process.env.ANTHROPIC_API_KEY,
321
- codex: process.env.OPENAI_API_KEY,
322
- qwen: process.env.OPENAI_API_KEY || process.env.QWEN_API_KEY,
323
- gemini: process.env.GEMINI_API_KEY,
324
- }[provider];
325
- const envBase = {
326
- claude: process.env.ANTHROPIC_BASE_URL,
327
- codex: process.env.OPENAI_BASE_URL,
328
- qwen: process.env.OPENAI_BASE_URL,
329
- gemini: undefined,
330
- }[provider];
331
- const apiKey = creds?.apiKey || envKey;
332
- const baseUrl = creds?.baseUrl || envBase || undefined;
333
-
334
- if (!apiKey) {
335
- // Codex and Qwen support OAuth (`codex login`, `qwen auth`) which
336
- // DOESN'T expose a usable API key — the SDK auths against the
337
- // upstream API directly. Skip the discovery step silently in that
338
- // case; the static catalog is the right answer.
339
- const oauthOnly = await hasProviderOauthAuth(provider);
340
- if (!oauthOnly) {
341
- // Be explicit so the UI can surface a useful hint rather than just
342
- // showing the static baseline with no reason given.
343
- error = `No ${provider} API key configured. Save one in Settings > Agents > API Key, or sign in via the CLI (e.g. \`codex login\`).`;
344
- }
345
- } else {
346
- try {
347
- if (provider === 'claude') {
348
- liveModels = await discoverAnthropic(apiKey, baseUrl);
349
- } else if (provider === 'codex') {
350
- liveModels = await discoverOpenAiCompat(apiKey, baseUrl, 'https://api.openai.com/v1');
351
- } else if (provider === 'qwen') {
352
- liveModels = await discoverOpenAiCompat(
353
- apiKey,
354
- baseUrl,
355
- 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
356
- );
357
- } else if (provider === 'gemini') {
358
- liveModels = await discoverGoogle(apiKey);
359
- }
360
- } catch (err) {
361
- // OAuth users get a clean message instead of a raw 401 stack.
362
- if (err?.code === 'OAUTH_NO_API_KEY') {
363
- error = err.message;
364
- } else {
365
- error = err?.message || String(err);
366
- }
367
- }
368
- }
369
-
370
- const merged = mergeCatalogs(normalizeList(liveModels), staticCatalog);
371
- const entry = { models: merged, error };
372
- await saveCacheEntry(provider, entry).catch(() => { /* non-fatal */ });
373
- return { models: merged, fetchedAt: new Date().toISOString(), error, fromCache: false };
374
- }
375
-
376
- export async function clearProviderModelCache(provider) {
377
- const cache = await readCache();
378
- if (provider) delete cache[provider];
379
- else Object.keys(cache).forEach((k) => delete cache[k]);
380
- await writeCache(cache);
381
- }
1
+ /**
2
+ * Provider model catalog — dynamic discovery + persistent cache.
3
+ *
4
+ * Each CLI provider offers a different way to list the models it can run:
5
+ *
6
+ * - Anthropic: https://api.anthropic.com/v1/models (API key required)
7
+ * - OpenAI : https://api.openai.com/v1/models (or a custom baseUrl when
8
+ * the user points Codex at an OpenAI-compatible proxy)
9
+ * - Google : https://generativelanguage.googleapis.com/v1beta/models
10
+ * - Qwen : same OpenAI-compat shape when users BYOK through
11
+ * ModelStudio / ModelScope / OpenRouter etc.
12
+ *
13
+ * The UI still keeps a hardcoded "known good" catalog as a baseline so
14
+ * brand-new installs don't show an empty dropdown; discovery merges the
15
+ * server-reported list on top, dedupes, and persists to
16
+ * `~/.pixcode/provider-models.json` with a 6-hour freshness window.
17
+ */
18
+ import { promises as fs } from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+
22
+ import { getProviderCredentials } from './provider-credentials.js';
23
+
24
+ const CACHE_FILE = path.join(os.homedir(), '.pixcode', 'provider-models.json');
25
+ const CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6 hours
26
+
27
+ async function readCache() {
28
+ try {
29
+ const raw = await fs.readFile(CACHE_FILE, 'utf8');
30
+ const parsed = JSON.parse(raw);
31
+ return parsed && typeof parsed === 'object' ? parsed : {};
32
+ } catch {
33
+ return {};
34
+ }
35
+ }
36
+
37
+ async function writeCache(next) {
38
+ await fs.mkdir(path.dirname(CACHE_FILE), { recursive: true });
39
+ await fs.writeFile(CACHE_FILE, JSON.stringify(next, null, 2), { mode: 0o600 });
40
+ }
41
+
42
+ /**
43
+ * Cache entry shape:
44
+ * { models: [{ value, label, source: 'static' | 'api' }],
45
+ * fetchedAt: '<iso date>',
46
+ * error?: '...' }
47
+ *
48
+ * `source` tells the UI which entries came from the live API so a
49
+ * refresh can prune stale ones without losing the hand-maintained
50
+ * defaults.
51
+ */
52
+ async function loadCachedEntry(provider) {
53
+ const cache = await readCache();
54
+ return cache[provider] || null;
55
+ }
56
+
57
+ async function saveCacheEntry(provider, entry) {
58
+ const cache = await readCache();
59
+ cache[provider] = { ...entry, fetchedAt: new Date().toISOString() };
60
+ await writeCache(cache);
61
+ }
62
+
63
+ function normalizeList(list) {
64
+ if (!Array.isArray(list)) return [];
65
+ const seen = new Set();
66
+ const out = [];
67
+ for (const item of list) {
68
+ if (!item || typeof item !== 'object') continue;
69
+ const value = typeof item.value === 'string' ? item.value.trim() : '';
70
+ if (!value || seen.has(value)) continue;
71
+ seen.add(value);
72
+ const label = typeof item.label === 'string' && item.label.trim() ? item.label.trim() : value;
73
+ const source = item.source === 'api' ? 'api' : 'static';
74
+ const entry = { value, label, source };
75
+ if (typeof item.free === 'boolean') entry.free = item.free;
76
+ out.push(entry);
77
+ }
78
+ return out;
79
+ }
80
+
81
+ function mergeCatalogs(primary, secondary) {
82
+ const seen = new Map();
83
+ for (const item of [...primary, ...secondary]) {
84
+ if (!seen.has(item.value)) seen.set(item.value, item);
85
+ }
86
+ return Array.from(seen.values());
87
+ }
88
+
89
+ // ---------------- Per-provider live discovery ----------------
90
+
91
+ async function discoverAnthropic(apiKey, baseUrl) {
92
+ const endpoint = (baseUrl?.replace(/\/+$/, '') || 'https://api.anthropic.com') + '/v1/models';
93
+ const response = await fetch(endpoint, {
94
+ headers: {
95
+ 'x-api-key': apiKey,
96
+ 'anthropic-version': '2023-06-01',
97
+ },
98
+ });
99
+ if (!response.ok) throw new Error(`Anthropic /v1/models returned ${response.status}`);
100
+ const data = await response.json();
101
+ const rows = Array.isArray(data?.data) ? data.data : [];
102
+ return rows
103
+ .filter((m) => typeof m?.id === 'string')
104
+ .map((m) => ({
105
+ value: m.id,
106
+ label: typeof m.display_name === 'string' && m.display_name.trim() ? m.display_name : m.id,
107
+ source: 'api',
108
+ }));
109
+ }
110
+
111
+ async function discoverOpenAiCompat(apiKey, baseUrl, fallbackBase) {
112
+ const endpoint = (baseUrl?.replace(/\/+$/, '') || fallbackBase) + '/models';
113
+ const response = await fetch(endpoint, {
114
+ headers: { Authorization: `Bearer ${apiKey}` },
115
+ });
116
+ if (!response.ok) {
117
+ // 401 specifically means our key is bad — but for codex/qwen/etc.
118
+ // users often log in via OAuth (`codex login`, `qwen auth`) which
119
+ // doesn't expose an OpenAI-compatible API key. Surface a clean
120
+ // "no live discovery available" rather than a scary 401 trace.
121
+ if (response.status === 401) {
122
+ const err = new Error('OpenAI-compatible /v1/models requires an API key. The static catalog is shown instead — that\'s expected when you signed in via OAuth (e.g. `codex login`).');
123
+ err.code = 'OAUTH_NO_API_KEY';
124
+ throw err;
125
+ }
126
+ throw new Error(`${endpoint} returned ${response.status}`);
127
+ }
128
+ const data = await response.json();
129
+ const rows = Array.isArray(data?.data) ? data.data : [];
130
+ return rows
131
+ .filter((m) => typeof m?.id === 'string')
132
+ .map((m) => ({
133
+ value: m.id,
134
+ label: m.id,
135
+ source: 'api',
136
+ }));
137
+ }
138
+
139
+ /**
140
+ * Detect whether the user is authenticated via the provider's OAuth flow
141
+ * (codex login / qwen auth) so we can skip live model discovery silently
142
+ * — those flows don't surface a usable OpenAI-compatible API key, and the
143
+ * SDK calls the upstream APIs through its own internal auth path.
144
+ */
145
+ async function hasProviderOauthAuth(provider) {
146
+ if (provider === 'codex') {
147
+ try {
148
+ await fs.access(path.join(os.homedir(), '.codex', 'auth.json'));
149
+ return true;
150
+ } catch { return false; }
151
+ }
152
+ if (provider === 'qwen') {
153
+ try {
154
+ await fs.access(path.join(os.homedir(), '.qwen', 'oauth_creds.json'));
155
+ return true;
156
+ } catch { return false; }
157
+ }
158
+ return false;
159
+ }
160
+
161
+ /**
162
+ * OpenCode is multi-provider — its "model" picker isn't a single API list,
163
+ * it's the union of every provider it can route to (Anthropic, OpenAI,
164
+ * Google, xAI, OpenRouter, OpenCode Zen, Ollama, etc.). The canonical
165
+ * catalog lives at https://models.dev/api.json (no auth, ~1.8 MB JSON, 115
166
+ * providers as of 2026-04). We pull that, filter to providers the user
167
+ * has authenticated with (read `~/.local/share/opencode/auth.json`) plus
168
+ * always include the OpenCode Zen tier (works without explicit auth on
169
+ * the free models), drop deprecated entries, and tag free models.
170
+ */
171
+ async function discoverOpencode() {
172
+ const url = process.env.OPENCODE_MODELS_URL || 'https://models.dev/api.json';
173
+ const response = await fetch(url, {
174
+ // OpenCode itself caches this for hours; we cache for 6h via the
175
+ // outer wrapper so a single 7s fetch on cold start is acceptable.
176
+ signal: AbortSignal.timeout(15000),
177
+ });
178
+ if (!response.ok) throw new Error(`models.dev/api.json returned ${response.status}`);
179
+ const data = await response.json();
180
+ if (!data || typeof data !== 'object') throw new Error('models.dev returned a non-object payload');
181
+
182
+ // Read OpenCode's auth.json to know which providers the user can
183
+ // actually call. Missing file → only show always-free Zen.
184
+ const authedProviders = new Set(['opencode']);
185
+ try {
186
+ const authPath = path.join(os.homedir(), '.local', 'share', 'opencode', 'auth.json');
187
+ const raw = await fs.readFile(authPath, 'utf8');
188
+ const auth = JSON.parse(raw);
189
+ if (auth && typeof auth === 'object') {
190
+ for (const k of Object.keys(auth)) authedProviders.add(k);
191
+ }
192
+ } catch { /* no auth.json → only Zen free models surface */ }
193
+
194
+ // Common env-var providers OpenCode picks up automatically. If the user
195
+ // exported one in their shell, surface those models too even without
196
+ // auth.json. Mirrors the env list in opencode-auth.provider.ts.
197
+ const envProviderHints = {
198
+ anthropic: ['ANTHROPIC_API_KEY'],
199
+ openai: ['OPENAI_API_KEY'],
200
+ google: ['GOOGLE_GENERATIVE_AI_API_KEY', 'GEMINI_API_KEY'],
201
+ 'google-vertex': ['GOOGLE_APPLICATION_CREDENTIALS'],
202
+ xai: ['XAI_API_KEY'],
203
+ groq: ['GROQ_API_KEY'],
204
+ cerebras: ['CEREBRAS_API_KEY'],
205
+ openrouter: ['OPENROUTER_API_KEY'],
206
+ };
207
+ for (const [providerId, envVars] of Object.entries(envProviderHints)) {
208
+ if (envVars.some((v) => process.env[v]?.trim())) authedProviders.add(providerId);
209
+ }
210
+
211
+ const out = [];
212
+ for (const [providerId, providerCfg] of Object.entries(data)) {
213
+ if (!authedProviders.has(providerId)) continue;
214
+ if (!providerCfg || typeof providerCfg !== 'object') continue;
215
+ const models = providerCfg.models;
216
+ if (!models || typeof models !== 'object') continue;
217
+
218
+ const providerName = typeof providerCfg.name === 'string' && providerCfg.name.trim()
219
+ ? providerCfg.name
220
+ : providerId;
221
+
222
+ for (const [modelId, modelCfg] of Object.entries(models)) {
223
+ if (!modelCfg || typeof modelCfg !== 'object') continue;
224
+ // Skip deprecated entries from the default list — users can
225
+ // still hand-type them if they really need to.
226
+ if (modelCfg.status === 'deprecated') continue;
227
+ const cost = modelCfg.cost && typeof modelCfg.cost === 'object' ? modelCfg.cost : null;
228
+ const free = !cost || (Number(cost.input) === 0 && Number(cost.output) === 0);
229
+ const ctx = modelCfg.limit?.context;
230
+ const ctxLabel = typeof ctx === 'number' && ctx > 0
231
+ ? ` · ${ctx >= 1_000_000 ? `${(ctx / 1_000_000).toFixed(1)}M` : `${Math.round(ctx / 1000)}K`}`
232
+ : '';
233
+ const freeLabel = free ? ' · Free' : '';
234
+ const modelName = typeof modelCfg.name === 'string' && modelCfg.name.trim()
235
+ ? modelCfg.name
236
+ : modelId;
237
+
238
+ out.push({
239
+ value: `${providerId}/${modelId}`,
240
+ label: `${providerName} · ${modelName}${ctxLabel}${freeLabel}`,
241
+ source: 'api',
242
+ free,
243
+ });
244
+ }
245
+ }
246
+
247
+ // Sort: free first (handy when the user is unauthed), then by label.
248
+ out.sort((a, b) => {
249
+ if (a.free !== b.free) return a.free ? -1 : 1;
250
+ return a.label.localeCompare(b.label);
251
+ });
252
+
253
+ return out;
254
+ }
255
+
256
+ async function discoverGoogle(apiKey) {
257
+ // Google Generative Language API — public models list, API key as query.
258
+ const endpoint = `https://generativelanguage.googleapis.com/v1beta/models?key=${encodeURIComponent(apiKey)}`;
259
+ const response = await fetch(endpoint);
260
+ if (!response.ok) throw new Error(`Google /v1beta/models returned ${response.status}`);
261
+ const data = await response.json();
262
+ const rows = Array.isArray(data?.models) ? data.models : [];
263
+ return rows
264
+ .filter((m) => typeof m?.name === 'string' && m.name.includes('models/'))
265
+ .map((m) => {
266
+ const id = m.name.replace(/^models\//, '');
267
+ return {
268
+ value: id,
269
+ label: typeof m.displayName === 'string' && m.displayName.trim() ? m.displayName : id,
270
+ source: 'api',
271
+ };
272
+ });
273
+ }
274
+
275
+ /**
276
+ * Returns the merged catalog for a provider.
277
+ * opts.forceRefresh: ignore cache and hit the upstream API
278
+ * opts.staticList: hardcoded fallback from shared/modelConstants.js
279
+ */
280
+ export async function getProviderModels(provider, opts = {}) {
281
+ const { forceRefresh = false, staticList = [] } = opts;
282
+ const staticCatalog = normalizeList(staticList.map((m) => ({ ...m, source: 'static' })));
283
+
284
+ const cached = await loadCachedEntry(provider);
285
+ const cacheFresh = cached?.fetchedAt
286
+ ? Date.now() - Date.parse(cached.fetchedAt) < CACHE_TTL_MS
287
+ : false;
288
+
289
+ if (!forceRefresh && cacheFresh && Array.isArray(cached?.models)) {
290
+ return {
291
+ models: mergeCatalogs(normalizeList(cached.models), staticCatalog),
292
+ fetchedAt: cached.fetchedAt,
293
+ error: cached.error,
294
+ fromCache: true,
295
+ };
296
+ }
297
+
298
+ // OpenCode is the odd one out: its catalog is models.dev, not a per-key
299
+ // API endpoint. Skip the credential plumbing and dispatch straight.
300
+ let liveModels = [];
301
+ let error;
302
+ if (provider === 'opencode') {
303
+ try {
304
+ liveModels = await discoverOpencode();
305
+ } catch (err) {
306
+ error = err?.message || String(err);
307
+ }
308
+ const merged = mergeCatalogs(normalizeList(liveModels), staticCatalog);
309
+ const entry = { models: merged, error };
310
+ await saveCacheEntry(provider, entry).catch(() => { /* non-fatal */ });
311
+ return { models: merged, fetchedAt: new Date().toISOString(), error, fromCache: false };
312
+ }
313
+
314
+ // Pick up credentials from Pixcode's UI store first, then fall back to
315
+ // the native env vars so a user who already exported ANTHROPIC_API_KEY
316
+ // (or authenticated Claude Code via OAuth — the SDK writes the key into
317
+ // process.env on boot) gets live models without re-entering anything.
318
+ const creds = await getProviderCredentials(provider);
319
+ const envKey = {
320
+ claude: process.env.ANTHROPIC_API_KEY,
321
+ codex: process.env.OPENAI_API_KEY,
322
+ qwen: process.env.OPENAI_API_KEY || process.env.QWEN_API_KEY,
323
+ gemini: process.env.GEMINI_API_KEY,
324
+ }[provider];
325
+ const envBase = {
326
+ claude: process.env.ANTHROPIC_BASE_URL,
327
+ codex: process.env.OPENAI_BASE_URL,
328
+ qwen: process.env.OPENAI_BASE_URL,
329
+ gemini: undefined,
330
+ }[provider];
331
+ const apiKey = creds?.apiKey || envKey;
332
+ const baseUrl = creds?.baseUrl || envBase || undefined;
333
+
334
+ if (!apiKey) {
335
+ // Codex and Qwen support OAuth (`codex login`, `qwen auth`) which
336
+ // DOESN'T expose a usable API key — the SDK auths against the
337
+ // upstream API directly. Skip the discovery step silently in that
338
+ // case; the static catalog is the right answer.
339
+ const oauthOnly = await hasProviderOauthAuth(provider);
340
+ if (!oauthOnly) {
341
+ // Be explicit so the UI can surface a useful hint rather than just
342
+ // showing the static baseline with no reason given.
343
+ error = `No ${provider} API key configured. Save one in Settings > Agents > API Key, or sign in via the CLI (e.g. \`codex login\`).`;
344
+ }
345
+ } else {
346
+ try {
347
+ if (provider === 'claude') {
348
+ liveModels = await discoverAnthropic(apiKey, baseUrl);
349
+ } else if (provider === 'codex') {
350
+ liveModels = await discoverOpenAiCompat(apiKey, baseUrl, 'https://api.openai.com/v1');
351
+ } else if (provider === 'qwen') {
352
+ liveModels = await discoverOpenAiCompat(
353
+ apiKey,
354
+ baseUrl,
355
+ 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
356
+ );
357
+ } else if (provider === 'gemini') {
358
+ liveModels = await discoverGoogle(apiKey);
359
+ }
360
+ } catch (err) {
361
+ // OAuth users get a clean message instead of a raw 401 stack.
362
+ if (err?.code === 'OAUTH_NO_API_KEY') {
363
+ error = err.message;
364
+ } else {
365
+ error = err?.message || String(err);
366
+ }
367
+ }
368
+ }
369
+
370
+ const merged = mergeCatalogs(normalizeList(liveModels), staticCatalog);
371
+ const entry = { models: merged, error };
372
+ await saveCacheEntry(provider, entry).catch(() => { /* non-fatal */ });
373
+ return { models: merged, fetchedAt: new Date().toISOString(), error, fromCache: false };
374
+ }
375
+
376
+ export async function clearProviderModelCache(provider) {
377
+ const cache = await readCache();
378
+ if (provider) delete cache[provider];
379
+ else Object.keys(cache).forEach((k) => delete cache[k]);
380
+ await writeCache(cache);
381
+ }