@pixelbyte-software/pixcode 1.35.1 → 1.35.2

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