codexmate 0.0.32 → 0.0.34

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