codexmate 0.0.41 → 0.0.43

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 (155) hide show
  1. package/README.md +168 -168
  2. package/README.zh.md +168 -168
  3. package/cli/agents-files.js +230 -230
  4. package/cli/analytics-export-args.js +68 -68
  5. package/cli/archive-helpers.js +453 -453
  6. package/cli/auth-profiles.js +375 -375
  7. package/cli/builtin-proxy.js +2144 -2144
  8. package/cli/claude-proxy.js +1022 -1022
  9. package/cli/config-bootstrap.js +407 -407
  10. package/cli/config-health.js +454 -454
  11. package/cli/doctor-core.js +903 -903
  12. package/cli/import-skills-url.js +356 -356
  13. package/cli/local-bridge.js +556 -556
  14. package/cli/openai-bridge.js +1984 -1984
  15. package/cli/openclaw-config.js +629 -629
  16. package/cli/session-convert-args.js +69 -69
  17. package/cli/session-convert-io.js +82 -82
  18. package/cli/session-convert.js +150 -150
  19. package/cli/session-usage.concurrent.js +28 -28
  20. package/cli/session-usage.js +304 -304
  21. package/cli/session-usage.models.js +176 -176
  22. package/cli/skills.js +1141 -1141
  23. package/cli/update.js +171 -171
  24. package/cli/zip-commands.js +510 -510
  25. package/cli.js +16495 -16458
  26. package/lib/automation.js +404 -404
  27. package/lib/cli-file-utils.js +151 -151
  28. package/lib/cli-models-utils.js +440 -440
  29. package/lib/cli-network-utils.js +190 -190
  30. package/lib/cli-path-utils.js +85 -85
  31. package/lib/cli-session-utils.js +121 -121
  32. package/lib/cli-sessions.js +427 -427
  33. package/lib/cli-utils.js +155 -155
  34. package/lib/cli-webhook.js +154 -154
  35. package/lib/download-artifacts.js +92 -92
  36. package/lib/mcp-stdio.js +453 -453
  37. package/lib/task-orchestrator.js +869 -869
  38. package/lib/text-diff.js +303 -303
  39. package/lib/win-tray.js +119 -119
  40. package/lib/workflow-engine.js +340 -340
  41. package/package.json +77 -77
  42. package/plugins/README.md +20 -20
  43. package/plugins/README.zh-CN.md +20 -20
  44. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  45. package/plugins/prompt-templates/computed.mjs +311 -311
  46. package/plugins/prompt-templates/index.mjs +8 -8
  47. package/plugins/prompt-templates/manifest.mjs +18 -18
  48. package/plugins/prompt-templates/methods.mjs +553 -553
  49. package/plugins/prompt-templates/overview.mjs +91 -91
  50. package/plugins/prompt-templates/ownership.mjs +19 -19
  51. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  52. package/plugins/prompt-templates/storage.mjs +64 -64
  53. package/plugins/registry.mjs +16 -16
  54. package/web-ui/app.js +705 -695
  55. package/web-ui/index.html +37 -37
  56. package/web-ui/logic.agents-diff.mjs +386 -386
  57. package/web-ui/logic.claude.mjs +172 -172
  58. package/web-ui/logic.codex.mjs +69 -69
  59. package/web-ui/logic.mjs +5 -5
  60. package/web-ui/logic.runtime.mjs +128 -128
  61. package/web-ui/logic.session-convert.mjs +70 -70
  62. package/web-ui/logic.sessions.mjs +782 -782
  63. package/web-ui/modules/api.mjs +90 -90
  64. package/web-ui/modules/app.computed.dashboard.mjs +252 -252
  65. package/web-ui/modules/app.computed.index.mjs +17 -17
  66. package/web-ui/modules/app.computed.main-tabs.mjs +214 -214
  67. package/web-ui/modules/app.computed.session.mjs +876 -876
  68. package/web-ui/modules/app.constants.mjs +15 -15
  69. package/web-ui/modules/app.methods.agents.mjs +651 -651
  70. package/web-ui/modules/app.methods.claude-config.mjs +412 -412
  71. package/web-ui/modules/app.methods.codex-config.mjs +869 -869
  72. package/web-ui/modules/app.methods.index.mjs +96 -96
  73. package/web-ui/modules/app.methods.install.mjs +205 -205
  74. package/web-ui/modules/app.methods.navigation.mjs +804 -804
  75. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  76. package/web-ui/modules/app.methods.openclaw-editing.mjs +420 -420
  77. package/web-ui/modules/app.methods.openclaw-persist.mjs +375 -375
  78. package/web-ui/modules/app.methods.providers.mjs +602 -601
  79. package/web-ui/modules/app.methods.runtime.mjs +426 -420
  80. package/web-ui/modules/app.methods.session-actions.mjs +617 -591
  81. package/web-ui/modules/app.methods.session-browser.mjs +1018 -1018
  82. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  83. package/web-ui/modules/app.methods.session-trash.mjs +468 -468
  84. package/web-ui/modules/app.methods.startup-claude.mjs +557 -554
  85. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  86. package/web-ui/modules/app.methods.tool-config-permissions.mjs +90 -87
  87. package/web-ui/modules/app.methods.webhook.mjs +87 -87
  88. package/web-ui/modules/config-mode.computed.mjs +124 -124
  89. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  90. package/web-ui/modules/i18n/locales/en.mjs +1187 -1140
  91. package/web-ui/modules/i18n/locales/ja.mjs +1178 -1130
  92. package/web-ui/modules/i18n/locales/vi.mjs +294 -239
  93. package/web-ui/modules/i18n/locales/zh.mjs +1190 -1143
  94. package/web-ui/modules/i18n.dict.mjs +14 -14
  95. package/web-ui/modules/i18n.mjs +111 -111
  96. package/web-ui/modules/plugins.computed.mjs +3 -3
  97. package/web-ui/modules/plugins.methods.mjs +3 -3
  98. package/web-ui/modules/plugins.storage.mjs +11 -11
  99. package/web-ui/modules/provider-url-display.mjs +17 -17
  100. package/web-ui/modules/sessions-filters-url.mjs +138 -138
  101. package/web-ui/modules/skills.computed.mjs +107 -107
  102. package/web-ui/modules/skills.methods.mjs +513 -513
  103. package/web-ui/partials/index/layout-footer.html +13 -13
  104. package/web-ui/partials/index/layout-header.html +478 -478
  105. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  106. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  107. package/web-ui/partials/index/modal-health-check.html +45 -45
  108. package/web-ui/partials/index/modal-openclaw-config.html +344 -344
  109. package/web-ui/partials/index/modal-skills.html +200 -200
  110. package/web-ui/partials/index/modal-webhook.html +42 -42
  111. package/web-ui/partials/index/modals-basic.html +263 -263
  112. package/web-ui/partials/index/panel-config-claude.html +187 -187
  113. package/web-ui/partials/index/panel-config-codex.html +205 -205
  114. package/web-ui/partials/index/panel-config-openclaw.html +89 -89
  115. package/web-ui/partials/index/panel-dashboard.html +171 -171
  116. package/web-ui/partials/index/panel-docs.html +114 -114
  117. package/web-ui/partials/index/panel-market.html +104 -104
  118. package/web-ui/partials/index/panel-orchestration.html +391 -391
  119. package/web-ui/partials/index/panel-plugins.html +253 -253
  120. package/web-ui/partials/index/panel-sessions.html +325 -319
  121. package/web-ui/partials/index/panel-settings.html +181 -181
  122. package/web-ui/partials/index/panel-trash.html +82 -82
  123. package/web-ui/partials/index/panel-usage.html +181 -181
  124. package/web-ui/res/json5.min.js +1 -1
  125. package/web-ui/res/vue.global.prod.js +13 -13
  126. package/web-ui/res/vue.runtime.global.prod.js +7 -7
  127. package/web-ui/res/web-ui-render.precompiled.js +7671 -7666
  128. package/web-ui/session-helpers.mjs +602 -602
  129. package/web-ui/source-bundle.cjs +305 -305
  130. package/web-ui/styles/base-theme.css +291 -291
  131. package/web-ui/styles/bridge-pool.css +266 -266
  132. package/web-ui/styles/controls-forms.css +532 -532
  133. package/web-ui/styles/dashboard.css +438 -438
  134. package/web-ui/styles/docs-panel.css +245 -245
  135. package/web-ui/styles/feedback.css +108 -108
  136. package/web-ui/styles/health-check-dialog.css +144 -144
  137. package/web-ui/styles/layout-shell.css +711 -711
  138. package/web-ui/styles/modals-core.css +499 -499
  139. package/web-ui/styles/navigation-panels.css +399 -399
  140. package/web-ui/styles/openclaw-structured.css +616 -616
  141. package/web-ui/styles/plugins-panel.css +564 -564
  142. package/web-ui/styles/responsive.css +501 -501
  143. package/web-ui/styles/sessions-list.css +683 -683
  144. package/web-ui/styles/sessions-preview.css +407 -407
  145. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  146. package/web-ui/styles/sessions-usage.css +849 -849
  147. package/web-ui/styles/settings-panel.css +419 -419
  148. package/web-ui/styles/skills-list.css +305 -305
  149. package/web-ui/styles/skills-market.css +723 -723
  150. package/web-ui/styles/task-orchestration.css +822 -822
  151. package/web-ui/styles/titles-cards.css +492 -486
  152. package/web-ui/styles/trash-panel.css +90 -90
  153. package/web-ui/styles/webhook.css +115 -115
  154. package/web-ui/styles.css +24 -24
  155. package/web-ui.html +17 -17
@@ -1,554 +1,557 @@
1
- import {
2
- findDuplicateClaudeConfigName,
3
- getClaudeModelCatalogForBaseUrl,
4
- matchClaudeConfigFromSettings,
5
- normalizeClaudeConfig,
6
- normalizeClaudeSettingsEnv,
7
- normalizeClaudeValue
8
- } from '../logic.mjs';
9
-
10
- export function createStartupClaudeMethods(options = {}) {
11
- const {
12
- api,
13
- defaultModelContextWindow = 190000,
14
- defaultModelAutoCompactTokenLimit = 185000
15
- } = options;
16
-
17
- return {
18
- async loadAll(options = {}) {
19
- if (this._loadAllPromise) {
20
- this._loadAllPendingOptions = options;
21
- return this._loadAllPromise;
22
- }
23
- const preserveLoading = !!options.preserveLoading;
24
- const run = async () => {
25
- const configLoadTimeoutMs = 6000;
26
- const withTimeout = async (promise, ms) => {
27
- const timeoutMs = Number.isFinite(Number(ms)) ? Math.max(0, Number(ms)) : 0;
28
- if (!timeoutMs) {
29
- return promise;
30
- }
31
- let timer = null;
32
- try {
33
- return await Promise.race([
34
- promise,
35
- new Promise((_, reject) => {
36
- timer = setTimeout(() => reject(new Error('timeout')), timeoutMs);
37
- })
38
- ]);
39
- } finally {
40
- if (timer) {
41
- clearTimeout(timer);
42
- }
43
- }
44
- };
45
- if (!preserveLoading) {
46
- this.loading = true;
47
- }
48
- this.initError = '';
49
- const startedAt = Date.now();
50
- const timeLeftMs = () => configLoadTimeoutMs - (Date.now() - startedAt);
51
- try {
52
- const statusRes = await withTimeout(api('status'), timeLeftMs());
53
- if (statusRes && statusRes.error) {
54
- this.initError = statusRes.error;
55
- return false;
56
- }
57
- const listRes = await withTimeout(api('list'), timeLeftMs());
58
- if (listRes && listRes.error) {
59
- this.initError = listRes.error;
60
- return false;
61
- }
62
- this.currentProvider = statusRes.provider;
63
- if (statusRes.version) {
64
- this.appVersion = statusRes.version;
65
- }
66
- this.currentModels = statusRes.currentModels && typeof statusRes.currentModels === 'object'
67
- ? { ...statusRes.currentModels }
68
- : {};
69
- const dictModelForCurrent = this.currentProvider
70
- && typeof this.currentModels[this.currentProvider] === 'string'
71
- ? this.currentModels[this.currentProvider].trim()
72
- : '';
73
- this.currentModel = dictModelForCurrent || statusRes.model;
74
- try {
75
- const installRes = await withTimeout(api('install-status'), Math.max(0, Math.min(1200, timeLeftMs())));
76
- if (installRes && !installRes.error) {
77
- const targets = Array.isArray(installRes.targets) ? installRes.targets : null;
78
- if (targets) {
79
- this.installStatusTargets = targets;
80
- }
81
- if (typeof installRes.packageManager === 'string' && typeof this.normalizeInstallPackageManager === 'function') {
82
- this.installPackageManager = this.normalizeInstallPackageManager(installRes.packageManager);
83
- }
84
- }
85
- } catch (_) {}
86
- {
87
- const tier = typeof statusRes.serviceTier === 'string'
88
- ? statusRes.serviceTier.trim().toLowerCase()
89
- : '';
90
- this.serviceTier = tier === 'fast' ? 'fast' : (tier ? 'standard' : 'fast');
91
- }
92
- {
93
- const effort = typeof statusRes.modelReasoningEffort === 'string'
94
- ? statusRes.modelReasoningEffort.trim().toLowerCase()
95
- : '';
96
- const allowedReasoningEfforts = new Set(['low', 'medium', 'high', 'xhigh']);
97
- this.modelReasoningEffort = allowedReasoningEfforts.has(effort) ? effort : 'medium';
98
- }
99
- {
100
- const contextWindow = this.normalizePositiveIntegerInput(
101
- statusRes.modelContextWindow,
102
- 'model_context_window',
103
- defaultModelContextWindow
104
- );
105
- if (this.editingCodexBudgetField !== 'modelContextWindowInput') {
106
- this.modelContextWindowInput = contextWindow.ok && contextWindow.text
107
- ? contextWindow.text
108
- : String(defaultModelContextWindow);
109
- }
110
- }
111
- {
112
- const autoCompactTokenLimit = this.normalizePositiveIntegerInput(
113
- statusRes.modelAutoCompactTokenLimit,
114
- 'model_auto_compact_token_limit',
115
- defaultModelAutoCompactTokenLimit
116
- );
117
- if (this.editingCodexBudgetField !== 'modelAutoCompactTokenLimitInput') {
118
- this.modelAutoCompactTokenLimitInput = autoCompactTokenLimit.ok && autoCompactTokenLimit.text
119
- ? autoCompactTokenLimit.text
120
- : String(defaultModelAutoCompactTokenLimit);
121
- }
122
- }
123
- if (statusRes.toolConfigPermissions && typeof statusRes.toolConfigPermissions === 'object') {
124
- this.toolConfigPermissions = {
125
- codex: statusRes.toolConfigPermissions.codex === true,
126
- claude: statusRes.toolConfigPermissions.claude === true
127
- };
128
- }
129
- this.providersList = listRes.providers;
130
- if (typeof this.loadLocalBridgeExcluded === 'function') { this.loadLocalBridgeExcluded(); }
131
- if (typeof this.loadClaudeLocalBridgeStatus === 'function') { this.loadClaudeLocalBridgeStatus(); }
132
- if (statusRes.configReady === false) {
133
- this.showMessage('配置已加载', 'info');
134
- }
135
- if (statusRes.initNotice) {
136
- this.showMessage('配置就绪', 'info');
137
- }
138
- this.maybeShowStarPrompt();
139
- return true;
140
- } catch (e) {
141
- this.initError = e && e.message === 'timeout'
142
- ? '读取配置超时'
143
- : '连接失败: ' + (e && e.message ? e.message : '');
144
- return false;
145
- } finally {
146
- if (!preserveLoading) {
147
- this.loading = false;
148
- }
149
- }
150
- };
151
-
152
- this._loadAllPromise = run()
153
- .finally(() => {
154
- this._loadAllPromise = null;
155
- });
156
-
157
- const result = await this._loadAllPromise;
158
- if (result) {
159
- Promise.resolve(this.loadModelsForProvider(this.currentProvider)).catch(() => {});
160
- Promise.resolve(this.loadCodexAuthProfiles()).catch(() => {});
161
- }
162
- const pending = this._loadAllPendingOptions;
163
- this._loadAllPendingOptions = null;
164
- if (pending) {
165
- return this.loadAll(pending);
166
- }
167
- return result;
168
- },
169
-
170
- async loadModelsForProvider(providerName, options = {}) {
171
- const targetProvider = typeof providerName === 'string' ? providerName.trim() : '';
172
- const requestSeq = (Number(this.codexModelsRequestSeq) || 0) + 1;
173
- this.codexModelsRequestSeq = requestSeq;
174
- this.codexModelsLoading = true;
175
- if (!targetProvider) {
176
- this.models = [];
177
- this.modelsSource = 'unlimited';
178
- this.modelsHasCurrent = true;
179
- this.codexModelsLoading = false;
180
- return;
181
- }
182
- const isLatestRequest = () => {
183
- const currentProvider = typeof this.currentProvider === 'string' ? this.currentProvider.trim() : '';
184
- return requestSeq === Number(this.codexModelsRequestSeq || 0)
185
- && (!currentProvider || currentProvider === targetProvider);
186
- };
187
- try {
188
- const res = await api('models', { provider: targetProvider });
189
- if (!isLatestRequest()) {
190
- return;
191
- }
192
- if (res.unlimited) {
193
- this.models = [];
194
- this.modelsSource = 'unlimited';
195
- this.modelsHasCurrent = true;
196
- return;
197
- }
198
- if (res.error) {
199
- this.models = [];
200
- this.modelsSource = 'error';
201
- this.modelsHasCurrent = true;
202
- return;
203
- }
204
- const list = Array.isArray(res.models) ? res.models : [];
205
- this.models = list;
206
- this.modelsSource = res.source || 'remote';
207
- this.modelsHasCurrent = !!this.currentModel && list.includes(this.currentModel);
208
- } catch (_) {
209
- if (!isLatestRequest()) {
210
- return;
211
- }
212
- this.models = [];
213
- this.modelsSource = 'error';
214
- this.modelsHasCurrent = true;
215
- } finally {
216
- if (requestSeq === Number(this.codexModelsRequestSeq || 0)) {
217
- this.codexModelsLoading = false;
218
- }
219
- }
220
- },
221
-
222
- getCurrentClaudeConfig() {
223
- if (!this.currentClaudeConfig) return null;
224
- return this.claudeConfigs[this.currentClaudeConfig] || null;
225
- },
226
-
227
- normalizeClaudeValue,
228
-
229
- normalizeClaudeConfig(config) {
230
- return normalizeClaudeConfig(config);
231
- },
232
-
233
- normalizeClaudeSettingsEnv(env) {
234
- return normalizeClaudeSettingsEnv(env);
235
- },
236
-
237
- matchClaudeConfigFromSettings(env) {
238
- return matchClaudeConfigFromSettings(this.claudeConfigs, env);
239
- },
240
-
241
- findDuplicateClaudeConfigName(config) {
242
- return findDuplicateClaudeConfigName(this.claudeConfigs, config);
243
- },
244
-
245
- mergeClaudeConfig(existing = {}, updates = {}) {
246
- const previous = this.normalizeClaudeConfig(existing);
247
- const next = this.normalizeClaudeConfig({ ...existing, ...updates });
248
- const externalCredentialType = next.apiKey
249
- ? ''
250
- : (next.externalCredentialType || previous.externalCredentialType || '');
251
- return {
252
- apiKey: next.apiKey,
253
- baseUrl: next.baseUrl,
254
- model: next.model || previous.model || 'glm-4.7',
255
- hasKey: !!(next.apiKey || externalCredentialType),
256
- externalCredentialType
257
- };
258
- },
259
-
260
- buildClaudeImportedConfigName(baseUrl) {
261
- const normalizedUrl = typeof baseUrl === 'string' ? baseUrl.trim() : '';
262
- if (!normalizedUrl) return '导入配置';
263
- try {
264
- const parsed = new URL(normalizedUrl);
265
- const host = typeof parsed.host === 'string' ? parsed.host.trim() : '';
266
- if (host) return `导入-${host}`;
267
- } catch (_) {}
268
- return '导入配置';
269
- },
270
-
271
- ensureClaudeConfigFromSettings(env = {}) {
272
- const normalized = this.normalizeClaudeSettingsEnv(env);
273
- const hasCredential = !!(normalized.apiKey || normalized.authToken || normalized.useKey);
274
- if (!normalized.baseUrl || !hasCredential) return '';
275
-
276
- const duplicateName = this.findDuplicateClaudeConfigName(normalized);
277
- if (duplicateName) return duplicateName;
278
-
279
- const preferredName = this.buildClaudeImportedConfigName(normalized.baseUrl);
280
- let candidateName = preferredName;
281
- let suffix = 2;
282
- const maxAttempts = 1000;
283
- while (this.claudeConfigs[candidateName] && suffix <= maxAttempts) {
284
- candidateName = `${preferredName}-${suffix}`;
285
- suffix += 1;
286
- }
287
- if (this.claudeConfigs[candidateName]) {
288
- return '';
289
- }
290
-
291
- this.claudeConfigs[candidateName] = this.mergeClaudeConfig({}, normalized);
292
- this.saveClaudeConfigs();
293
- return candidateName;
294
- },
295
-
296
- async refreshClaudeSelectionFromSettings(options = {}) {
297
- if (this._refreshClaudeSelectionPromise) {
298
- this._refreshClaudeSelectionPendingOptions = options;
299
- return this._refreshClaudeSelectionPromise;
300
- }
301
- const silent = !!options.silent;
302
- const silentModelError = !!options.silentModelError || silent;
303
- const run = async () => {
304
- const configLoadTimeoutMs = 6000;
305
- const withTimeout = async (promise, ms) => {
306
- const timeoutMs = Number.isFinite(Number(ms)) ? Math.max(0, Number(ms)) : 0;
307
- if (!timeoutMs) {
308
- return promise;
309
- }
310
- let timer = null;
311
- try {
312
- return await Promise.race([
313
- promise,
314
- new Promise((_, reject) => {
315
- timer = setTimeout(() => reject(new Error('timeout')), timeoutMs);
316
- })
317
- ]);
318
- } finally {
319
- if (timer) {
320
- clearTimeout(timer);
321
- }
322
- }
323
- };
324
- try {
325
- const res = await withTimeout(api('get-claude-settings'), configLoadTimeoutMs);
326
- if (res && res.error) {
327
- if (!silent) {
328
- this.showMessage('读取配置失败', 'error');
329
- }
330
- return;
331
- }
332
- const matchName = this.matchClaudeConfigFromSettings((res && res.env) || {});
333
- if (matchName) {
334
- if (this.currentClaudeConfig !== matchName) {
335
- this.currentClaudeConfig = matchName;
336
- try { localStorage.setItem('currentClaudeConfig', matchName); } catch (_) {}
337
- }
338
- this.refreshClaudeModelContext({ silentError: silentModelError });
339
- return;
340
- }
341
- const importedName = this.ensureClaudeConfigFromSettings((res && res.env) || {});
342
- if (importedName) {
343
- if (this.currentClaudeConfig !== importedName) {
344
- this.currentClaudeConfig = importedName;
345
- try { localStorage.setItem('currentClaudeConfig', importedName); } catch (_) {}
346
- }
347
- this.refreshClaudeModelContext({ silentError: silentModelError });
348
- if (!silent) {
349
- this.showMessage(`检测到外部 Claude 配置,已自动导入:${importedName}`, 'success');
350
- }
351
- return;
352
- }
353
- {
354
- const configNames = Object.keys(this.claudeConfigs || {});
355
- const current = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
356
- const fallback = current && this.claudeConfigs && this.claudeConfigs[current]
357
- ? current
358
- : (configNames[0] || '');
359
- if (!fallback) {
360
- this.currentClaudeConfig = '';
361
- try { localStorage.setItem('currentClaudeConfig', ''); } catch (_) {}
362
- this.currentClaudeModel = '';
363
- this.resetClaudeModelsState();
364
- return;
365
- }
366
- if (this.currentClaudeConfig !== fallback) {
367
- this.currentClaudeConfig = fallback;
368
- try { localStorage.setItem('currentClaudeConfig', fallback); } catch (_) {}
369
- }
370
- this.refreshClaudeModelContext({ silentError: silentModelError });
371
- }
372
- } catch (e) {
373
- if (!silent) {
374
- this.showMessage(e && e.message === 'timeout' ? '读取配置超时' : '读取配置失败', 'error');
375
- }
376
- }
377
- };
378
-
379
- this._refreshClaudeSelectionPromise = Promise.resolve(run())
380
- .finally(() => {
381
- this._refreshClaudeSelectionPromise = null;
382
- });
383
- await this._refreshClaudeSelectionPromise;
384
- const pending = this._refreshClaudeSelectionPendingOptions;
385
- this._refreshClaudeSelectionPendingOptions = null;
386
- if (pending) {
387
- return this.refreshClaudeSelectionFromSettings(pending);
388
- }
389
- },
390
-
391
- syncClaudeModelFromConfig() {
392
- if (this.currentClaudeConfig === 'claude-local') {
393
- const candidates = this.claudeLocalBridgeCandidateProviders
394
- ? this.claudeLocalBridgeCandidateProviders()
395
- : [];
396
- const active = candidates.find(cp => !this.isClaudeLocalBridgeExcluded(cp.name));
397
- this.currentClaudeModel = active && active.model ? active.model : '';
398
- this.claudeCustomModelDraft = this.currentClaudeModel;
399
- return;
400
- }
401
- const config = this.getCurrentClaudeConfig();
402
- this.currentClaudeModel = config && config.model ? config.model : '';
403
- this.claudeCustomModelDraft = this.currentClaudeModel;
404
- },
405
-
406
- refreshClaudeModelContext(options = {}) {
407
- this.syncClaudeModelFromConfig();
408
- return this.loadClaudeModels(options);
409
- },
410
-
411
- resetClaudeModelsState() {
412
- this.claudeModels = [];
413
- this.claudeModelsSource = 'idle';
414
- this.claudeModelsHasCurrent = true;
415
- this.claudeModelsLoading = false;
416
- },
417
-
418
- updateClaudeModelsCurrent() {
419
- const currentModel = (this.currentClaudeModel || '').trim();
420
- this.claudeModelsHasCurrent = !!currentModel && this.claudeModels.includes(currentModel);
421
- },
422
-
423
- async loadClaudeModels(options = {}) {
424
- const config = this.getCurrentClaudeConfig();
425
- const requestSeq = (Number(this.claudeModelsRequestSeq) || 0) + 1;
426
- this.claudeModelsRequestSeq = requestSeq;
427
- if (!config) {
428
- this.resetClaudeModelsState();
429
- return;
430
- }
431
- const currentConfigName = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
432
- const baseUrl = (config.baseUrl || '').trim();
433
- const apiKey = (config.apiKey || '').trim();
434
- const externalCredentialType = typeof config.externalCredentialType === 'string'
435
- ? config.externalCredentialType.trim()
436
- : '';
437
-
438
- if (!baseUrl) {
439
- this.resetClaudeModelsState();
440
- return;
441
- }
442
- const localCatalog = getClaudeModelCatalogForBaseUrl(baseUrl);
443
- if (!apiKey && externalCredentialType) {
444
- this.claudeModels = localCatalog;
445
- this.claudeModelsSource = localCatalog.length ? 'catalog' : 'unlimited';
446
- if (localCatalog.length) {
447
- this.updateClaudeModelsCurrent();
448
- } else {
449
- this.claudeModelsHasCurrent = true;
450
- }
451
- this.claudeModelsLoading = false;
452
- return;
453
- }
454
-
455
- const cache = typeof globalThis !== 'undefined'
456
- ? (globalThis.__codexmateClaudeModelsCache || (globalThis.__codexmateClaudeModelsCache = new Map()))
457
- : new Map();
458
- const cacheKey = baseUrl;
459
- const ttlMs = 2 * 60 * 1000;
460
- const now = Date.now();
461
- const cached = cache.get(cacheKey);
462
- const cachedOk = cached
463
- && Number.isFinite(cached.ts)
464
- && now - cached.ts < ttlMs
465
- && Array.isArray(cached.models);
466
- if (cachedOk) {
467
- this.claudeModels = cached.models;
468
- this.claudeModelsSource = cached.source || 'remote';
469
- if (this.claudeModels.length) {
470
- this.updateClaudeModelsCurrent();
471
- } else {
472
- this.claudeModelsHasCurrent = true;
473
- }
474
- this.claudeModelsLoading = false;
475
- } else if (localCatalog.length) {
476
- this.claudeModels = localCatalog;
477
- this.claudeModelsSource = 'catalog';
478
- this.updateClaudeModelsCurrent();
479
- this.claudeModelsLoading = false;
480
- }
481
- const isLatestRequest = () => {
482
- if (requestSeq !== Number(this.claudeModelsRequestSeq || 0)) {
483
- return false;
484
- }
485
- const liveConfigName = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
486
- if (currentConfigName && liveConfigName && liveConfigName !== currentConfigName) {
487
- return false;
488
- }
489
- const latestConfig = this.getCurrentClaudeConfig();
490
- if (!latestConfig) {
491
- return false;
492
- }
493
- return (latestConfig.baseUrl || '').trim() === baseUrl
494
- && (latestConfig.apiKey || '').trim() === apiKey
495
- && (typeof latestConfig.externalCredentialType === 'string' ? latestConfig.externalCredentialType.trim() : '') === externalCredentialType;
496
- };
497
- if (cachedOk) {
498
- return;
499
- }
500
- try {
501
- const res = await api('models-by-url', { baseUrl, apiKey });
502
- if (!isLatestRequest()) {
503
- return;
504
- }
505
- if (res.unlimited) {
506
- this.claudeModels = [];
507
- this.claudeModelsSource = 'unlimited';
508
- this.claudeModelsHasCurrent = true;
509
- cache.set(cacheKey, { ts: Date.now(), models: [], source: 'unlimited' });
510
- return;
511
- }
512
- if (res.error) {
513
- this.claudeModels = [];
514
- this.claudeModelsSource = 'error';
515
- this.claudeModelsHasCurrent = true;
516
- return;
517
- }
518
- const list = Array.isArray(res.models) ? res.models : [];
519
- this.claudeModels = list;
520
- this.claudeModelsSource = res.source || 'remote';
521
- this.updateClaudeModelsCurrent();
522
- cache.set(cacheKey, { ts: Date.now(), models: list, source: this.claudeModelsSource });
523
- } catch (_) {
524
- if (!isLatestRequest()) {
525
- return;
526
- }
527
- this.claudeModels = [];
528
- this.claudeModelsSource = 'error';
529
- this.claudeModelsHasCurrent = true;
530
- } finally {
531
- if (requestSeq === Number(this.claudeModelsRequestSeq || 0)) {
532
- this.claudeModelsLoading = false;
533
- }
534
- }
535
- },
536
-
537
- openClaudeConfigModal() {
538
- this.showAddClaudeConfigKey = false;
539
- this.showClaudeConfigModal = true;
540
- },
541
-
542
- maybeShowStarPrompt() {
543
- const storageKey = 'codexmateStarPrompted';
544
- try {
545
- if (!localStorage.getItem(storageKey)) {
546
- localStorage.setItem(storageKey, '1');
547
- }
548
- } catch (_) {
549
- // Ignore storage failures silently. The startup UI should not show
550
- // promotional prompts or block normal configuration work.
551
- }
552
- }
553
- };
554
- }
1
+ import {
2
+ findDuplicateClaudeConfigName,
3
+ getClaudeModelCatalogForBaseUrl,
4
+ matchClaudeConfigFromSettings,
5
+ normalizeClaudeConfig,
6
+ normalizeClaudeSettingsEnv,
7
+ normalizeClaudeValue
8
+ } from '../logic.mjs';
9
+
10
+ export function createStartupClaudeMethods(options = {}) {
11
+ const {
12
+ api,
13
+ defaultModelContextWindow = 190000,
14
+ defaultModelAutoCompactTokenLimit = 185000
15
+ } = options;
16
+
17
+ return {
18
+ async loadAll(options = {}) {
19
+ if (this._loadAllPromise) {
20
+ this._loadAllPendingOptions = options;
21
+ return this._loadAllPromise;
22
+ }
23
+ const preserveLoading = !!options.preserveLoading;
24
+ const run = async () => {
25
+ const configLoadTimeoutMs = 6000;
26
+ const withTimeout = async (promise, ms) => {
27
+ const timeoutMs = Number.isFinite(Number(ms)) ? Math.max(0, Number(ms)) : 0;
28
+ if (!timeoutMs) {
29
+ return promise;
30
+ }
31
+ let timer = null;
32
+ try {
33
+ return await Promise.race([
34
+ promise,
35
+ new Promise((_, reject) => {
36
+ timer = setTimeout(() => reject(new Error('timeout')), timeoutMs);
37
+ })
38
+ ]);
39
+ } finally {
40
+ if (timer) {
41
+ clearTimeout(timer);
42
+ }
43
+ }
44
+ };
45
+ if (!preserveLoading) {
46
+ this.loading = true;
47
+ }
48
+ this.initError = '';
49
+ const startedAt = Date.now();
50
+ const timeLeftMs = () => configLoadTimeoutMs - (Date.now() - startedAt);
51
+ try {
52
+ const statusRes = await withTimeout(api('status'), timeLeftMs());
53
+ if (statusRes && statusRes.error) {
54
+ this.initError = statusRes.error;
55
+ return false;
56
+ }
57
+ const listRes = await withTimeout(api('list'), timeLeftMs());
58
+ if (listRes && listRes.error) {
59
+ this.initError = listRes.error;
60
+ return false;
61
+ }
62
+ this.currentProvider = statusRes.provider;
63
+ if (statusRes.version) {
64
+ this.appVersion = statusRes.version;
65
+ }
66
+ this.currentModels = statusRes.currentModels && typeof statusRes.currentModels === 'object'
67
+ ? { ...statusRes.currentModels }
68
+ : {};
69
+ const dictModelForCurrent = this.currentProvider
70
+ && typeof this.currentModels[this.currentProvider] === 'string'
71
+ ? this.currentModels[this.currentProvider].trim()
72
+ : '';
73
+ this.currentModel = dictModelForCurrent || statusRes.model;
74
+ try {
75
+ const installRes = await withTimeout(api('install-status'), Math.max(0, Math.min(1200, timeLeftMs())));
76
+ if (installRes && !installRes.error) {
77
+ const targets = Array.isArray(installRes.targets) ? installRes.targets : null;
78
+ if (targets) {
79
+ this.installStatusTargets = targets;
80
+ }
81
+ if (typeof installRes.packageManager === 'string' && typeof this.normalizeInstallPackageManager === 'function') {
82
+ this.installPackageManager = this.normalizeInstallPackageManager(installRes.packageManager);
83
+ }
84
+ }
85
+ } catch (_) {}
86
+ {
87
+ const tier = typeof statusRes.serviceTier === 'string'
88
+ ? statusRes.serviceTier.trim().toLowerCase()
89
+ : '';
90
+ this.serviceTier = tier === 'fast' ? 'fast' : (tier ? 'standard' : 'fast');
91
+ }
92
+ {
93
+ const effort = typeof statusRes.modelReasoningEffort === 'string'
94
+ ? statusRes.modelReasoningEffort.trim().toLowerCase()
95
+ : '';
96
+ const allowedReasoningEfforts = new Set(['low', 'medium', 'high', 'xhigh']);
97
+ this.modelReasoningEffort = allowedReasoningEfforts.has(effort) ? effort : 'medium';
98
+ }
99
+ {
100
+ const contextWindow = this.normalizePositiveIntegerInput(
101
+ statusRes.modelContextWindow,
102
+ 'model_context_window',
103
+ defaultModelContextWindow
104
+ );
105
+ if (this.editingCodexBudgetField !== 'modelContextWindowInput') {
106
+ this.modelContextWindowInput = contextWindow.ok && contextWindow.text
107
+ ? contextWindow.text
108
+ : String(defaultModelContextWindow);
109
+ }
110
+ }
111
+ {
112
+ const autoCompactTokenLimit = this.normalizePositiveIntegerInput(
113
+ statusRes.modelAutoCompactTokenLimit,
114
+ 'model_auto_compact_token_limit',
115
+ defaultModelAutoCompactTokenLimit
116
+ );
117
+ if (this.editingCodexBudgetField !== 'modelAutoCompactTokenLimitInput') {
118
+ this.modelAutoCompactTokenLimitInput = autoCompactTokenLimit.ok && autoCompactTokenLimit.text
119
+ ? autoCompactTokenLimit.text
120
+ : String(defaultModelAutoCompactTokenLimit);
121
+ }
122
+ }
123
+ if (statusRes.toolConfigPermissions && typeof statusRes.toolConfigPermissions === 'object') {
124
+ this.toolConfigPermissions = {
125
+ codex: statusRes.toolConfigPermissions.codex === true,
126
+ claude: statusRes.toolConfigPermissions.claude === true
127
+ };
128
+ try {
129
+ localStorage.setItem('toolConfigPermissions', JSON.stringify(this.toolConfigPermissions));
130
+ } catch (_) {}
131
+ }
132
+ this.providersList = listRes.providers;
133
+ if (typeof this.loadLocalBridgeExcluded === 'function') { this.loadLocalBridgeExcluded(); }
134
+ if (typeof this.loadClaudeLocalBridgeStatus === 'function') { this.loadClaudeLocalBridgeStatus(); }
135
+ if (statusRes.configReady === false) {
136
+ this.showMessage('配置已加载', 'info');
137
+ }
138
+ if (statusRes.initNotice) {
139
+ this.showMessage('配置就绪', 'info');
140
+ }
141
+ this.maybeShowStarPrompt();
142
+ return true;
143
+ } catch (e) {
144
+ this.initError = e && e.message === 'timeout'
145
+ ? '读取配置超时'
146
+ : '连接失败: ' + (e && e.message ? e.message : '');
147
+ return false;
148
+ } finally {
149
+ if (!preserveLoading) {
150
+ this.loading = false;
151
+ }
152
+ }
153
+ };
154
+
155
+ this._loadAllPromise = run()
156
+ .finally(() => {
157
+ this._loadAllPromise = null;
158
+ });
159
+
160
+ const result = await this._loadAllPromise;
161
+ if (result) {
162
+ Promise.resolve(this.loadModelsForProvider(this.currentProvider)).catch(() => {});
163
+ Promise.resolve(this.loadCodexAuthProfiles()).catch(() => {});
164
+ }
165
+ const pending = this._loadAllPendingOptions;
166
+ this._loadAllPendingOptions = null;
167
+ if (pending) {
168
+ return this.loadAll(pending);
169
+ }
170
+ return result;
171
+ },
172
+
173
+ async loadModelsForProvider(providerName, options = {}) {
174
+ const targetProvider = typeof providerName === 'string' ? providerName.trim() : '';
175
+ const requestSeq = (Number(this.codexModelsRequestSeq) || 0) + 1;
176
+ this.codexModelsRequestSeq = requestSeq;
177
+ this.codexModelsLoading = true;
178
+ if (!targetProvider) {
179
+ this.models = [];
180
+ this.modelsSource = 'unlimited';
181
+ this.modelsHasCurrent = true;
182
+ this.codexModelsLoading = false;
183
+ return;
184
+ }
185
+ const isLatestRequest = () => {
186
+ const currentProvider = typeof this.currentProvider === 'string' ? this.currentProvider.trim() : '';
187
+ return requestSeq === Number(this.codexModelsRequestSeq || 0)
188
+ && (!currentProvider || currentProvider === targetProvider);
189
+ };
190
+ try {
191
+ const res = await api('models', { provider: targetProvider });
192
+ if (!isLatestRequest()) {
193
+ return;
194
+ }
195
+ if (res.unlimited) {
196
+ this.models = [];
197
+ this.modelsSource = 'unlimited';
198
+ this.modelsHasCurrent = true;
199
+ return;
200
+ }
201
+ if (res.error) {
202
+ this.models = [];
203
+ this.modelsSource = 'error';
204
+ this.modelsHasCurrent = true;
205
+ return;
206
+ }
207
+ const list = Array.isArray(res.models) ? res.models : [];
208
+ this.models = list;
209
+ this.modelsSource = res.source || 'remote';
210
+ this.modelsHasCurrent = !!this.currentModel && list.includes(this.currentModel);
211
+ } catch (_) {
212
+ if (!isLatestRequest()) {
213
+ return;
214
+ }
215
+ this.models = [];
216
+ this.modelsSource = 'error';
217
+ this.modelsHasCurrent = true;
218
+ } finally {
219
+ if (requestSeq === Number(this.codexModelsRequestSeq || 0)) {
220
+ this.codexModelsLoading = false;
221
+ }
222
+ }
223
+ },
224
+
225
+ getCurrentClaudeConfig() {
226
+ if (!this.currentClaudeConfig) return null;
227
+ return this.claudeConfigs[this.currentClaudeConfig] || null;
228
+ },
229
+
230
+ normalizeClaudeValue,
231
+
232
+ normalizeClaudeConfig(config) {
233
+ return normalizeClaudeConfig(config);
234
+ },
235
+
236
+ normalizeClaudeSettingsEnv(env) {
237
+ return normalizeClaudeSettingsEnv(env);
238
+ },
239
+
240
+ matchClaudeConfigFromSettings(env) {
241
+ return matchClaudeConfigFromSettings(this.claudeConfigs, env);
242
+ },
243
+
244
+ findDuplicateClaudeConfigName(config) {
245
+ return findDuplicateClaudeConfigName(this.claudeConfigs, config);
246
+ },
247
+
248
+ mergeClaudeConfig(existing = {}, updates = {}) {
249
+ const previous = this.normalizeClaudeConfig(existing);
250
+ const next = this.normalizeClaudeConfig({ ...existing, ...updates });
251
+ const externalCredentialType = next.apiKey
252
+ ? ''
253
+ : (next.externalCredentialType || previous.externalCredentialType || '');
254
+ return {
255
+ apiKey: next.apiKey,
256
+ baseUrl: next.baseUrl,
257
+ model: next.model || previous.model || 'glm-4.7',
258
+ hasKey: !!(next.apiKey || externalCredentialType),
259
+ externalCredentialType
260
+ };
261
+ },
262
+
263
+ buildClaudeImportedConfigName(baseUrl) {
264
+ const normalizedUrl = typeof baseUrl === 'string' ? baseUrl.trim() : '';
265
+ if (!normalizedUrl) return '导入配置';
266
+ try {
267
+ const parsed = new URL(normalizedUrl);
268
+ const host = typeof parsed.host === 'string' ? parsed.host.trim() : '';
269
+ if (host) return `导入-${host}`;
270
+ } catch (_) {}
271
+ return '导入配置';
272
+ },
273
+
274
+ ensureClaudeConfigFromSettings(env = {}) {
275
+ const normalized = this.normalizeClaudeSettingsEnv(env);
276
+ const hasCredential = !!(normalized.apiKey || normalized.authToken || normalized.useKey);
277
+ if (!normalized.baseUrl || !hasCredential) return '';
278
+
279
+ const duplicateName = this.findDuplicateClaudeConfigName(normalized);
280
+ if (duplicateName) return duplicateName;
281
+
282
+ const preferredName = this.buildClaudeImportedConfigName(normalized.baseUrl);
283
+ let candidateName = preferredName;
284
+ let suffix = 2;
285
+ const maxAttempts = 1000;
286
+ while (this.claudeConfigs[candidateName] && suffix <= maxAttempts) {
287
+ candidateName = `${preferredName}-${suffix}`;
288
+ suffix += 1;
289
+ }
290
+ if (this.claudeConfigs[candidateName]) {
291
+ return '';
292
+ }
293
+
294
+ this.claudeConfigs[candidateName] = this.mergeClaudeConfig({}, normalized);
295
+ this.saveClaudeConfigs();
296
+ return candidateName;
297
+ },
298
+
299
+ async refreshClaudeSelectionFromSettings(options = {}) {
300
+ if (this._refreshClaudeSelectionPromise) {
301
+ this._refreshClaudeSelectionPendingOptions = options;
302
+ return this._refreshClaudeSelectionPromise;
303
+ }
304
+ const silent = !!options.silent;
305
+ const silentModelError = !!options.silentModelError || silent;
306
+ const run = async () => {
307
+ const configLoadTimeoutMs = 6000;
308
+ const withTimeout = async (promise, ms) => {
309
+ const timeoutMs = Number.isFinite(Number(ms)) ? Math.max(0, Number(ms)) : 0;
310
+ if (!timeoutMs) {
311
+ return promise;
312
+ }
313
+ let timer = null;
314
+ try {
315
+ return await Promise.race([
316
+ promise,
317
+ new Promise((_, reject) => {
318
+ timer = setTimeout(() => reject(new Error('timeout')), timeoutMs);
319
+ })
320
+ ]);
321
+ } finally {
322
+ if (timer) {
323
+ clearTimeout(timer);
324
+ }
325
+ }
326
+ };
327
+ try {
328
+ const res = await withTimeout(api('get-claude-settings'), configLoadTimeoutMs);
329
+ if (res && res.error) {
330
+ if (!silent) {
331
+ this.showMessage('读取配置失败', 'error');
332
+ }
333
+ return;
334
+ }
335
+ const matchName = this.matchClaudeConfigFromSettings((res && res.env) || {});
336
+ if (matchName) {
337
+ if (this.currentClaudeConfig !== matchName) {
338
+ this.currentClaudeConfig = matchName;
339
+ try { localStorage.setItem('currentClaudeConfig', matchName); } catch (_) {}
340
+ }
341
+ this.refreshClaudeModelContext({ silentError: silentModelError });
342
+ return;
343
+ }
344
+ const importedName = this.ensureClaudeConfigFromSettings((res && res.env) || {});
345
+ if (importedName) {
346
+ if (this.currentClaudeConfig !== importedName) {
347
+ this.currentClaudeConfig = importedName;
348
+ try { localStorage.setItem('currentClaudeConfig', importedName); } catch (_) {}
349
+ }
350
+ this.refreshClaudeModelContext({ silentError: silentModelError });
351
+ if (!silent) {
352
+ this.showMessage(`检测到外部 Claude 配置,已自动导入:${importedName}`, 'success');
353
+ }
354
+ return;
355
+ }
356
+ {
357
+ const configNames = Object.keys(this.claudeConfigs || {});
358
+ const current = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
359
+ const fallback = current && this.claudeConfigs && this.claudeConfigs[current]
360
+ ? current
361
+ : (configNames[0] || '');
362
+ if (!fallback) {
363
+ this.currentClaudeConfig = '';
364
+ try { localStorage.setItem('currentClaudeConfig', ''); } catch (_) {}
365
+ this.currentClaudeModel = '';
366
+ this.resetClaudeModelsState();
367
+ return;
368
+ }
369
+ if (this.currentClaudeConfig !== fallback) {
370
+ this.currentClaudeConfig = fallback;
371
+ try { localStorage.setItem('currentClaudeConfig', fallback); } catch (_) {}
372
+ }
373
+ this.refreshClaudeModelContext({ silentError: silentModelError });
374
+ }
375
+ } catch (e) {
376
+ if (!silent) {
377
+ this.showMessage(e && e.message === 'timeout' ? '读取配置超时' : '读取配置失败', 'error');
378
+ }
379
+ }
380
+ };
381
+
382
+ this._refreshClaudeSelectionPromise = Promise.resolve(run())
383
+ .finally(() => {
384
+ this._refreshClaudeSelectionPromise = null;
385
+ });
386
+ await this._refreshClaudeSelectionPromise;
387
+ const pending = this._refreshClaudeSelectionPendingOptions;
388
+ this._refreshClaudeSelectionPendingOptions = null;
389
+ if (pending) {
390
+ return this.refreshClaudeSelectionFromSettings(pending);
391
+ }
392
+ },
393
+
394
+ syncClaudeModelFromConfig() {
395
+ if (this.currentClaudeConfig === 'claude-local') {
396
+ const candidates = this.claudeLocalBridgeCandidateProviders
397
+ ? this.claudeLocalBridgeCandidateProviders()
398
+ : [];
399
+ const active = candidates.find(cp => !this.isClaudeLocalBridgeExcluded(cp.name));
400
+ this.currentClaudeModel = active && active.model ? active.model : '';
401
+ this.claudeCustomModelDraft = this.currentClaudeModel;
402
+ return;
403
+ }
404
+ const config = this.getCurrentClaudeConfig();
405
+ this.currentClaudeModel = config && config.model ? config.model : '';
406
+ this.claudeCustomModelDraft = this.currentClaudeModel;
407
+ },
408
+
409
+ refreshClaudeModelContext(options = {}) {
410
+ this.syncClaudeModelFromConfig();
411
+ return this.loadClaudeModels(options);
412
+ },
413
+
414
+ resetClaudeModelsState() {
415
+ this.claudeModels = [];
416
+ this.claudeModelsSource = 'idle';
417
+ this.claudeModelsHasCurrent = true;
418
+ this.claudeModelsLoading = false;
419
+ },
420
+
421
+ updateClaudeModelsCurrent() {
422
+ const currentModel = (this.currentClaudeModel || '').trim();
423
+ this.claudeModelsHasCurrent = !!currentModel && this.claudeModels.includes(currentModel);
424
+ },
425
+
426
+ async loadClaudeModels(options = {}) {
427
+ const config = this.getCurrentClaudeConfig();
428
+ const requestSeq = (Number(this.claudeModelsRequestSeq) || 0) + 1;
429
+ this.claudeModelsRequestSeq = requestSeq;
430
+ if (!config) {
431
+ this.resetClaudeModelsState();
432
+ return;
433
+ }
434
+ const currentConfigName = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
435
+ const baseUrl = (config.baseUrl || '').trim();
436
+ const apiKey = (config.apiKey || '').trim();
437
+ const externalCredentialType = typeof config.externalCredentialType === 'string'
438
+ ? config.externalCredentialType.trim()
439
+ : '';
440
+
441
+ if (!baseUrl) {
442
+ this.resetClaudeModelsState();
443
+ return;
444
+ }
445
+ const localCatalog = getClaudeModelCatalogForBaseUrl(baseUrl);
446
+ if (!apiKey && externalCredentialType) {
447
+ this.claudeModels = localCatalog;
448
+ this.claudeModelsSource = localCatalog.length ? 'catalog' : 'unlimited';
449
+ if (localCatalog.length) {
450
+ this.updateClaudeModelsCurrent();
451
+ } else {
452
+ this.claudeModelsHasCurrent = true;
453
+ }
454
+ this.claudeModelsLoading = false;
455
+ return;
456
+ }
457
+
458
+ const cache = typeof globalThis !== 'undefined'
459
+ ? (globalThis.__codexmateClaudeModelsCache || (globalThis.__codexmateClaudeModelsCache = new Map()))
460
+ : new Map();
461
+ const cacheKey = baseUrl;
462
+ const ttlMs = 2 * 60 * 1000;
463
+ const now = Date.now();
464
+ const cached = cache.get(cacheKey);
465
+ const cachedOk = cached
466
+ && Number.isFinite(cached.ts)
467
+ && now - cached.ts < ttlMs
468
+ && Array.isArray(cached.models);
469
+ if (cachedOk) {
470
+ this.claudeModels = cached.models;
471
+ this.claudeModelsSource = cached.source || 'remote';
472
+ if (this.claudeModels.length) {
473
+ this.updateClaudeModelsCurrent();
474
+ } else {
475
+ this.claudeModelsHasCurrent = true;
476
+ }
477
+ this.claudeModelsLoading = false;
478
+ } else if (localCatalog.length) {
479
+ this.claudeModels = localCatalog;
480
+ this.claudeModelsSource = 'catalog';
481
+ this.updateClaudeModelsCurrent();
482
+ this.claudeModelsLoading = false;
483
+ }
484
+ const isLatestRequest = () => {
485
+ if (requestSeq !== Number(this.claudeModelsRequestSeq || 0)) {
486
+ return false;
487
+ }
488
+ const liveConfigName = typeof this.currentClaudeConfig === 'string' ? this.currentClaudeConfig.trim() : '';
489
+ if (currentConfigName && liveConfigName && liveConfigName !== currentConfigName) {
490
+ return false;
491
+ }
492
+ const latestConfig = this.getCurrentClaudeConfig();
493
+ if (!latestConfig) {
494
+ return false;
495
+ }
496
+ return (latestConfig.baseUrl || '').trim() === baseUrl
497
+ && (latestConfig.apiKey || '').trim() === apiKey
498
+ && (typeof latestConfig.externalCredentialType === 'string' ? latestConfig.externalCredentialType.trim() : '') === externalCredentialType;
499
+ };
500
+ if (cachedOk) {
501
+ return;
502
+ }
503
+ try {
504
+ const res = await api('models-by-url', { baseUrl, apiKey });
505
+ if (!isLatestRequest()) {
506
+ return;
507
+ }
508
+ if (res.unlimited) {
509
+ this.claudeModels = [];
510
+ this.claudeModelsSource = 'unlimited';
511
+ this.claudeModelsHasCurrent = true;
512
+ cache.set(cacheKey, { ts: Date.now(), models: [], source: 'unlimited' });
513
+ return;
514
+ }
515
+ if (res.error) {
516
+ this.claudeModels = [];
517
+ this.claudeModelsSource = 'error';
518
+ this.claudeModelsHasCurrent = true;
519
+ return;
520
+ }
521
+ const list = Array.isArray(res.models) ? res.models : [];
522
+ this.claudeModels = list;
523
+ this.claudeModelsSource = res.source || 'remote';
524
+ this.updateClaudeModelsCurrent();
525
+ cache.set(cacheKey, { ts: Date.now(), models: list, source: this.claudeModelsSource });
526
+ } catch (_) {
527
+ if (!isLatestRequest()) {
528
+ return;
529
+ }
530
+ this.claudeModels = [];
531
+ this.claudeModelsSource = 'error';
532
+ this.claudeModelsHasCurrent = true;
533
+ } finally {
534
+ if (requestSeq === Number(this.claudeModelsRequestSeq || 0)) {
535
+ this.claudeModelsLoading = false;
536
+ }
537
+ }
538
+ },
539
+
540
+ openClaudeConfigModal() {
541
+ this.showAddClaudeConfigKey = false;
542
+ this.showClaudeConfigModal = true;
543
+ },
544
+
545
+ maybeShowStarPrompt() {
546
+ const storageKey = 'codexmateStarPrompted';
547
+ try {
548
+ if (!localStorage.getItem(storageKey)) {
549
+ localStorage.setItem(storageKey, '1');
550
+ }
551
+ } catch (_) {
552
+ // Ignore storage failures silently. The startup UI should not show
553
+ // promotional prompts or block normal configuration work.
554
+ }
555
+ }
556
+ };
557
+ }