@pixelbyte-software/pixcode 1.35.2 → 1.35.3

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 (173) hide show
  1. package/LICENSE +718 -718
  2. package/README.de.md +248 -248
  3. package/README.ja.md +240 -240
  4. package/README.ko.md +240 -240
  5. package/README.md +303 -303
  6. package/README.ru.md +248 -248
  7. package/README.tr.md +250 -250
  8. package/README.zh-CN.md +240 -240
  9. package/dist/api-docs.html +548 -548
  10. package/dist/assets/{index-D1-AIL_5.js → index-D8z78r_D.js} +57 -57
  11. package/dist/assets/{index-B8w57E1r.css → index-DmchzORZ.css} +1 -1
  12. package/dist/clear-cache.html +85 -85
  13. package/dist/convert-icons.md +52 -52
  14. package/dist/favicon.svg +8 -8
  15. package/dist/generate-icons.js +48 -48
  16. package/dist/icons/codex-white.svg +3 -3
  17. package/dist/icons/codex.svg +3 -3
  18. package/dist/icons/cursor-white.svg +11 -11
  19. package/dist/icons/icon-128x128.svg +9 -9
  20. package/dist/icons/icon-144x144.svg +9 -9
  21. package/dist/icons/icon-152x152.svg +9 -9
  22. package/dist/icons/icon-192x192.svg +9 -9
  23. package/dist/icons/icon-384x384.svg +9 -9
  24. package/dist/icons/icon-512x512.svg +9 -9
  25. package/dist/icons/icon-72x72.svg +9 -9
  26. package/dist/icons/icon-96x96.svg +9 -9
  27. package/dist/icons/icon-template.svg +9 -9
  28. package/dist/icons/qwen-logo.svg +14 -14
  29. package/dist/index.html +59 -59
  30. package/dist/logo.svg +12 -12
  31. package/dist/manifest.json +60 -60
  32. package/dist/openapi.yaml +1693 -1693
  33. package/dist/sw.js +124 -124
  34. package/dist-server/server/cli.js +96 -96
  35. package/dist-server/server/daemon/manager.js +33 -33
  36. package/dist-server/server/daemon-manager.js +64 -64
  37. package/dist-server/server/routes/commands.js +25 -25
  38. package/dist-server/server/routes/git.js +17 -17
  39. package/dist-server/server/routes/taskmaster.js +419 -419
  40. package/package.json +180 -180
  41. package/scripts/fix-node-pty.js +67 -67
  42. package/scripts/smoke/a2a-roundtrip.mjs +167 -167
  43. package/scripts/smoke/orchestration-api.mjs +172 -172
  44. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  45. package/server/claude-sdk.js +898 -898
  46. package/server/cli.js +935 -935
  47. package/server/constants/config.js +4 -4
  48. package/server/cursor-cli.js +342 -342
  49. package/server/daemon/manager.js +564 -564
  50. package/server/daemon-manager.js +959 -959
  51. package/server/database/db.js +794 -794
  52. package/server/database/json-store.js +197 -197
  53. package/server/gemini-cli.js +535 -535
  54. package/server/gemini-response-handler.js +79 -79
  55. package/server/index.js +3135 -3135
  56. package/server/load-env.js +34 -34
  57. package/server/middleware/auth.js +173 -173
  58. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  59. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +55 -55
  60. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +284 -284
  61. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  62. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  63. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  64. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  65. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  66. package/server/modules/orchestration/a2a/routes.ts +577 -577
  67. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  68. package/server/modules/orchestration/a2a/types.ts +125 -125
  69. package/server/modules/orchestration/a2a/validator.ts +113 -113
  70. package/server/modules/orchestration/index.ts +66 -66
  71. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  72. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  73. package/server/modules/orchestration/preview/types.ts +19 -19
  74. package/server/modules/orchestration/tasks/orchestration-task-store.ts +45 -45
  75. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +73 -73
  76. package/server/modules/orchestration/tasks/orchestration-task.service.ts +145 -145
  77. package/server/modules/orchestration/tasks/orchestration-task.types.ts +29 -29
  78. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  79. package/server/modules/orchestration/workflows/workflow-runner.ts +1206 -1206
  80. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  81. package/server/modules/orchestration/workflows/workflow.routes.ts +169 -169
  82. package/server/modules/orchestration/workflows/workflow.types.ts +70 -70
  83. package/server/modules/orchestration/workflows/workspace-target.ts +120 -120
  84. package/server/modules/orchestration/workspace/docker-workspace.ts +135 -135
  85. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  86. package/server/modules/orchestration/workspace/types.ts +52 -52
  87. package/server/modules/orchestration/workspace/workspace-manager.ts +97 -97
  88. package/server/modules/orchestration/workspace/worktree-workspace.ts +125 -125
  89. package/server/modules/providers/index.ts +2 -2
  90. package/server/modules/providers/list/claude/claude-auth.provider.ts +145 -145
  91. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  92. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  93. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  94. package/server/modules/providers/list/codex/codex-auth.provider.ts +115 -115
  95. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  96. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  97. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  98. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +143 -143
  99. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  100. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  101. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  102. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +163 -163
  103. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  104. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  105. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  106. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +130 -130
  107. package/server/modules/providers/list/opencode/opencode-mcp.provider.ts +126 -126
  108. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +232 -232
  109. package/server/modules/providers/list/opencode/opencode.provider.ts +29 -29
  110. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +145 -145
  111. package/server/modules/providers/list/qwen/qwen-mcp.provider.ts +114 -114
  112. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  113. package/server/modules/providers/list/qwen/qwen.provider.ts +21 -21
  114. package/server/modules/providers/provider.registry.ts +40 -40
  115. package/server/modules/providers/provider.routes.ts +819 -819
  116. package/server/modules/providers/services/mcp.service.ts +86 -86
  117. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  118. package/server/modules/providers/services/sessions.service.ts +45 -45
  119. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  120. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  121. package/server/modules/providers/shared/provider-configs.ts +142 -142
  122. package/server/modules/providers/tests/mcp.test.ts +293 -293
  123. package/server/openai-codex.js +462 -462
  124. package/server/opencode-cli.js +459 -459
  125. package/server/opencode-response-handler.js +107 -107
  126. package/server/projects.js +3105 -3105
  127. package/server/qwen-code-cli.js +395 -395
  128. package/server/qwen-response-handler.js +73 -73
  129. package/server/routes/agent.js +1365 -1365
  130. package/server/routes/auth.js +138 -138
  131. package/server/routes/codex.js +19 -19
  132. package/server/routes/commands.js +554 -554
  133. package/server/routes/cursor.js +52 -52
  134. package/server/routes/gemini.js +24 -24
  135. package/server/routes/git.js +1488 -1488
  136. package/server/routes/mcp-utils.js +31 -31
  137. package/server/routes/messages.js +61 -61
  138. package/server/routes/network.js +120 -120
  139. package/server/routes/plugins.js +318 -318
  140. package/server/routes/projects.js +915 -915
  141. package/server/routes/qwen.js +27 -27
  142. package/server/routes/settings.js +286 -286
  143. package/server/routes/taskmaster.js +1496 -1496
  144. package/server/routes/telegram.js +125 -125
  145. package/server/routes/user.js +123 -123
  146. package/server/services/external-access.js +171 -171
  147. package/server/services/install-jobs.js +571 -571
  148. package/server/services/notification-orchestrator.js +242 -242
  149. package/server/services/provider-credentials.js +189 -189
  150. package/server/services/provider-models.js +381 -381
  151. package/server/services/telegram/bot.js +279 -279
  152. package/server/services/telegram/telegram-http-client.js +130 -130
  153. package/server/services/telegram/translations.js +170 -170
  154. package/server/services/vapid-keys.js +36 -36
  155. package/server/sessionManager.js +225 -225
  156. package/server/shared/interfaces.ts +54 -54
  157. package/server/shared/types.ts +172 -172
  158. package/server/shared/utils.ts +193 -193
  159. package/server/tsconfig.json +36 -36
  160. package/server/utils/colors.js +21 -21
  161. package/server/utils/commandParser.js +303 -303
  162. package/server/utils/frontmatter.js +18 -18
  163. package/server/utils/gitConfig.js +34 -34
  164. package/server/utils/mcp-detector.js +147 -147
  165. package/server/utils/plugin-loader.js +457 -457
  166. package/server/utils/plugin-process-manager.js +184 -184
  167. package/server/utils/port-access.js +209 -209
  168. package/server/utils/runtime-paths.js +37 -37
  169. package/server/utils/taskmaster-websocket.js +128 -128
  170. package/server/utils/url-detection.js +71 -71
  171. package/server/vite-daemon.js +78 -78
  172. package/shared/modelConstants.js +162 -162
  173. package/shared/networkHosts.js +22 -22
@@ -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
+ }