codexmate 0.0.32 → 0.0.33

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 (147) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -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 +551 -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 +162 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16023 -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 +126 -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 +650 -647
  54. package/web-ui/index.html +36 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +168 -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 +269 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +861 -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 +774 -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 +1012 -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 +538 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +79 -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 +3192 -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/modals-basic.html +173 -162
  105. package/web-ui/partials/index/panel-config-claude.html +166 -136
  106. package/web-ui/partials/index/panel-config-codex.html +190 -196
  107. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  108. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  109. package/web-ui/partials/index/panel-dashboard.html +186 -219
  110. package/web-ui/partials/index/panel-docs.html +114 -114
  111. package/web-ui/partials/index/panel-market.html +177 -177
  112. package/web-ui/partials/index/panel-orchestration.html +391 -391
  113. package/web-ui/partials/index/panel-plugins.html +253 -253
  114. package/web-ui/partials/index/panel-sessions.html +319 -313
  115. package/web-ui/partials/index/panel-settings.html +190 -190
  116. package/web-ui/partials/index/panel-trash.html +82 -82
  117. package/web-ui/partials/index/panel-usage.html +137 -137
  118. package/web-ui/res/json5.min.js +1 -1
  119. package/web-ui/res/vue.global.prod.js +13 -13
  120. package/web-ui/session-helpers.mjs +591 -591
  121. package/web-ui/source-bundle.cjs +233 -233
  122. package/web-ui/styles/base-theme.css +281 -281
  123. package/web-ui/styles/bridge-pool.css +197 -197
  124. package/web-ui/styles/controls-forms.css +433 -433
  125. package/web-ui/styles/dashboard.css +406 -406
  126. package/web-ui/styles/docs-panel.css +245 -245
  127. package/web-ui/styles/feedback.css +108 -108
  128. package/web-ui/styles/health-check-dialog.css +144 -144
  129. package/web-ui/styles/layout-shell.css +628 -638
  130. package/web-ui/styles/modals-core.css +499 -466
  131. package/web-ui/styles/navigation-panels.css +391 -391
  132. package/web-ui/styles/openclaw-structured.css +266 -266
  133. package/web-ui/styles/plugins-panel.css +564 -564
  134. package/web-ui/styles/responsive.css +392 -392
  135. package/web-ui/styles/sessions-list.css +683 -647
  136. package/web-ui/styles/sessions-preview.css +407 -407
  137. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  138. package/web-ui/styles/sessions-usage.css +588 -588
  139. package/web-ui/styles/settings-panel.css +349 -349
  140. package/web-ui/styles/skills-list.css +305 -305
  141. package/web-ui/styles/skills-market.css +429 -429
  142. package/web-ui/styles/task-orchestration.css +822 -822
  143. package/web-ui/styles/titles-cards.css +472 -472
  144. package/web-ui/styles/trash-panel.css +90 -90
  145. package/web-ui/styles/webhook.css +81 -81
  146. package/web-ui/styles.css +24 -24
  147. package/web-ui.html +17 -17
@@ -1,814 +1,814 @@
1
- function isPlainRecord(value) {
2
- return !!(value && typeof value === 'object' && !Array.isArray(value));
3
- }
4
-
5
- function normalizeProviderId(provider) {
6
- const normalized = typeof provider === 'string' ? provider.trim().toLowerCase() : '';
7
- if (!normalized) return '';
8
- if (normalized === 'modelstudio' || normalized === 'qwencloud') {
9
- return 'qwen';
10
- }
11
- if (normalized === 'z.ai' || normalized === 'z-ai') {
12
- return 'zai';
13
- }
14
- if (normalized === 'opencode-zen') {
15
- return 'opencode';
16
- }
17
- if (normalized === 'opencode-go-auth') {
18
- return 'opencode-go';
19
- }
20
- if (normalized === 'kimi' || normalized === 'kimi-code' || normalized === 'kimi-coding') {
21
- return 'kimi';
22
- }
23
- if (normalized === 'bedrock' || normalized === 'aws-bedrock') {
24
- return 'amazon-bedrock';
25
- }
26
- if (normalized === 'bytedance' || normalized === 'doubao') {
27
- return 'volcengine';
28
- }
29
- return normalized;
30
- }
31
-
32
- function findNormalizedProviderKey(entries, provider) {
33
- if (!isPlainRecord(entries)) {
34
- return '';
35
- }
36
- const providerKey = normalizeProviderId(provider);
37
- if (!providerKey) {
38
- return '';
39
- }
40
- return Object.keys(entries).find((key) => normalizeProviderId(key) === providerKey) || '';
41
- }
42
-
43
- function collectDistinctProviderKeys(...providerMaps) {
44
- const byNormalizedKey = new Map();
45
- for (const providerMap of providerMaps) {
46
- if (!isPlainRecord(providerMap)) continue;
47
- for (const key of Object.keys(providerMap)) {
48
- const normalizedKey = normalizeProviderId(key);
49
- if (!normalizedKey || byNormalizedKey.has(normalizedKey)) continue;
50
- byNormalizedKey.set(normalizedKey, key);
51
- }
52
- }
53
- return Array.from(byNormalizedKey.values());
54
- }
55
-
56
- function isEnvTemplateString(value) {
57
- return typeof value === 'string' && /^\$\{[A-Z][A-Z0-9_]{0,127}\}$/.test(value.trim());
58
- }
59
-
60
- function isSecretRefRecord(value) {
61
- return isPlainRecord(value)
62
- && typeof value.source === 'string'
63
- && typeof value.provider === 'string'
64
- && typeof value.id === 'string';
65
- }
66
-
67
- function isLegacySecretRefRecord(value) {
68
- return isPlainRecord(value)
69
- && typeof value.source === 'string'
70
- && typeof value.id === 'string'
71
- && (value.provider === undefined || value.provider === null || value.provider === '');
72
- }
73
-
74
- function coerceSecretRefRecord(value) {
75
- if (isSecretRefRecord(value)) {
76
- return {
77
- source: value.source.trim(),
78
- provider: value.provider.trim(),
79
- id: value.id.trim()
80
- };
81
- }
82
- if (isLegacySecretRefRecord(value)) {
83
- return {
84
- source: value.source.trim(),
85
- provider: 'default',
86
- id: value.id.trim()
87
- };
88
- }
89
- return null;
90
- }
91
-
92
- const BUILTIN_PROVIDER_DEFAULTS = {
93
- openai: {
94
- baseUrl: 'https://api.openai.com/v1',
95
- apiType: 'openai-responses'
96
- },
97
- 'openai-codex': {
98
- baseUrl: 'https://chatgpt.com/backend-api',
99
- apiType: 'openai-codex-responses'
100
- }
101
- };
102
-
103
- function formatSecretRefLabel(ref) {
104
- const normalized = coerceSecretRefRecord(ref);
105
- if (!normalized) return '';
106
- return `SecretRef(${normalized.source}:${normalized.provider}:${normalized.id})`;
107
- }
108
-
109
- function readFirstProviderDisplayValue(records, keys) {
110
- for (const record of records) {
111
- if (!isPlainRecord(record)) continue;
112
- for (const key of keys) {
113
- if (typeof record[key] === 'string' && record[key].trim()) {
114
- return {
115
- value: record[key].trim(),
116
- readOnly: false,
117
- kind: isEnvTemplateString(record[key]) ? 'env-template' : 'string'
118
- };
119
- }
120
- if (coerceSecretRefRecord(record[key])) {
121
- return {
122
- value: formatSecretRefLabel(record[key]),
123
- readOnly: true,
124
- kind: 'secret-ref'
125
- };
126
- }
127
- }
128
- }
129
- return {
130
- value: '',
131
- readOnly: false,
132
- kind: 'missing'
133
- };
134
- }
135
-
136
- function readOpenclawAuthProfileDisplayValue(authProfilesByProvider, providerName) {
137
- const matchedKey = findNormalizedProviderKey(authProfilesByProvider, providerName) || providerName;
138
- const summary = isPlainRecord(authProfilesByProvider) ? authProfilesByProvider[matchedKey] : null;
139
- if (!isPlainRecord(summary)) {
140
- return {
141
- value: '',
142
- readOnly: false,
143
- kind: 'missing',
144
- sourceKind: '',
145
- sourceProfileId: '',
146
- sourceWriteField: '',
147
- sourceOriginalValue: '',
148
- sourceCredentialType: ''
149
- };
150
- }
151
- if (typeof summary.resolvedValue === 'string' && summary.resolvedValue.trim()) {
152
- return {
153
- value: summary.resolvedValue.trim(),
154
- readOnly: false,
155
- kind: 'auth-profile-value',
156
- sourceKind: 'auth-profile',
157
- sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
158
- sourceWriteField: typeof summary.resolvedField === 'string' ? summary.resolvedField.trim() : '',
159
- sourceOriginalValue: summary.resolvedValue.trim(),
160
- sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
161
- };
162
- }
163
- const resolvedField = typeof summary.resolvedField === 'string' ? summary.resolvedField.trim() : '';
164
- if (summary.editable === true && resolvedField) {
165
- return {
166
- value: '',
167
- readOnly: false,
168
- kind: 'auth-profile-value',
169
- sourceKind: 'auth-profile',
170
- sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
171
- sourceWriteField: resolvedField,
172
- sourceOriginalValue: '',
173
- sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
174
- };
175
- }
176
- if (typeof summary.display !== 'string' || !summary.display.trim()) {
177
- return {
178
- value: '',
179
- readOnly: false,
180
- kind: 'missing',
181
- sourceKind: '',
182
- sourceProfileId: '',
183
- sourceWriteField: '',
184
- sourceOriginalValue: '',
185
- sourceCredentialType: ''
186
- };
187
- }
188
- return {
189
- value: summary.display.trim(),
190
- readOnly: true,
191
- kind: 'auth-profile',
192
- sourceKind: '',
193
- sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
194
- sourceWriteField: '',
195
- sourceOriginalValue: '',
196
- sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
197
- };
198
- }
199
-
200
- function readBuiltinProviderDisplayValue(providerName, field) {
201
- const defaults = BUILTIN_PROVIDER_DEFAULTS[normalizeProviderId(providerName)];
202
- if (!defaults) {
203
- return {
204
- value: '',
205
- readOnly: false,
206
- kind: 'missing'
207
- };
208
- }
209
- const key = field === 'apiType' ? 'apiType' : 'baseUrl';
210
- const value = typeof defaults[key] === 'string' ? defaults[key].trim() : '';
211
- return {
212
- value,
213
- readOnly: false,
214
- kind: value ? 'builtin-default' : 'missing'
215
- };
216
- }
217
-
218
- function readPreferredProviderModels(records) {
219
- for (const record of records) {
220
- if (isPlainRecord(record) && Array.isArray(record.models) && record.models.length) {
221
- return record.models;
222
- }
223
- }
224
- return [];
225
- }
226
-
227
- export function createOpenclawCoreMethods() {
228
- return {
229
- getOpenclawParser() {
230
- const globalWindow = typeof window !== 'undefined' ? window : null;
231
- if (globalWindow && globalWindow.JSON5
232
- && typeof globalWindow.JSON5.parse === 'function'
233
- && typeof globalWindow.JSON5.stringify === 'function') {
234
- return {
235
- parse: globalWindow.JSON5.parse,
236
- stringify: globalWindow.JSON5.stringify
237
- };
238
- }
239
- return {
240
- parse: JSON.parse,
241
- stringify: JSON.stringify
242
- };
243
- },
244
-
245
- parseOpenclawContent(content, options = {}) {
246
- const allowEmpty = !!options.allowEmpty;
247
- const raw = typeof content === 'string' ? content.trim() : '';
248
- if (!raw) {
249
- if (allowEmpty) {
250
- return { ok: true, data: {} };
251
- }
252
- return { ok: false, error: '配置内容为空' };
253
- }
254
- try {
255
- const parser = this.getOpenclawParser();
256
- const data = parser.parse(raw);
257
- if (!data || typeof data !== 'object' || Array.isArray(data)) {
258
- return { ok: false, error: '配置格式错误(根节点必须是对象)' };
259
- }
260
- return { ok: true, data };
261
- } catch (e) {
262
- return { ok: false, error: e.message || '解析失败' };
263
- }
264
- },
265
-
266
- stringifyOpenclawConfig(data) {
267
- const parser = this.getOpenclawParser();
268
- try {
269
- return parser.stringify(data, null, 2);
270
- } catch (e) {
271
- return JSON.stringify(data, null, 2);
272
- }
273
- },
274
-
275
- resetOpenclawStructured() {
276
- this.openclawStructured = {
277
- agentPrimary: '',
278
- agentFallbacks: [''],
279
- workspace: '',
280
- timeout: '',
281
- contextTokens: '',
282
- maxConcurrent: '',
283
- envItems: [{ key: '', value: '', show: false }],
284
- toolsProfile: 'default',
285
- toolsAllow: [''],
286
- toolsDeny: ['']
287
- };
288
- this.openclawAgentsList = [];
289
- this.openclawProviders = [];
290
- this.openclawMissingProviders = [];
291
- },
292
-
293
- getOpenclawQuickDefaults() {
294
- return {
295
- providerName: '',
296
- baseUrl: '',
297
- baseUrlReadOnly: false,
298
- baseUrlDisplayKind: 'missing',
299
- apiKey: '',
300
- apiKeyReadOnly: false,
301
- apiKeyDisplayKind: 'missing',
302
- apiKeySourceKind: '',
303
- apiKeySourceProfileId: '',
304
- apiKeySourceWriteField: '',
305
- apiKeySourceOriginalValue: '',
306
- apiKeySourceCredentialType: '',
307
- apiType: 'openai-responses',
308
- modelId: '',
309
- modelName: '',
310
- contextWindow: '',
311
- maxTokens: '',
312
- setPrimary: true,
313
- overrideProvider: true,
314
- overrideModels: true,
315
- showKey: false
316
- };
317
- },
318
-
319
- resetOpenclawQuick() {
320
- this.openclawQuick = this.getOpenclawQuickDefaults();
321
- },
322
-
323
- toggleOpenclawQuickKey() {
324
- this.openclawQuick.showKey = !this.openclawQuick.showKey;
325
- },
326
-
327
- fillOpenclawQuickFromConfig(config, options = {}) {
328
- const defaults = this.getOpenclawQuickDefaults();
329
- if (!isPlainRecord(config)) {
330
- this.openclawQuick = defaults;
331
- return;
332
- }
333
- const authProfilesByProvider = isPlainRecord(options.authProfilesByProvider)
334
- ? options.authProfilesByProvider
335
- : (isPlainRecord(this.openclawAuthProfilesByProvider) ? this.openclawAuthProfilesByProvider : {});
336
-
337
- const agentDefaults = isPlainRecord(config.agents) && isPlainRecord(config.agents.defaults)
338
- ? config.agents.defaults
339
- : {};
340
- const modelConfig = agentDefaults.model;
341
- const legacyAgent = isPlainRecord(config.agent)
342
- ? config.agent
343
- : {};
344
-
345
- let primaryRef = '';
346
- if (isPlainRecord(modelConfig) && typeof modelConfig.primary === 'string') {
347
- primaryRef = modelConfig.primary;
348
- } else if (typeof modelConfig === 'string') {
349
- primaryRef = modelConfig;
350
- }
351
- if (!primaryRef) {
352
- if (typeof legacyAgent.model === 'string') {
353
- primaryRef = legacyAgent.model;
354
- } else if (isPlainRecord(legacyAgent.model) && typeof legacyAgent.model.primary === 'string') {
355
- primaryRef = legacyAgent.model.primary;
356
- }
357
- }
358
-
359
- let providerName = '';
360
- let modelId = '';
361
- if (primaryRef) {
362
- const parts = primaryRef.split('/');
363
- if (parts.length >= 2) {
364
- providerName = parts.shift().trim();
365
- modelId = parts.join('/').trim();
366
- }
367
- }
368
-
369
- const modelProviders = isPlainRecord(config.models) && isPlainRecord(config.models.providers)
370
- ? config.models.providers
371
- : null;
372
- const rootProviders = isPlainRecord(config.providers)
373
- ? config.providers
374
- : null;
375
- const providerKeys = collectDistinctProviderKeys(modelProviders, rootProviders);
376
- if (!providerName && providerKeys.length === 1) {
377
- providerName = providerKeys[0];
378
- }
379
-
380
- const normalizedConfiguredProviderName = providerName
381
- ? (findNormalizedProviderKey(modelProviders, providerName)
382
- || findNormalizedProviderKey(rootProviders, providerName)
383
- || providerName)
384
- : '';
385
- if (normalizedConfiguredProviderName) {
386
- providerName = normalizedConfiguredProviderName;
387
- }
388
-
389
- const buildProviderRecords = (name) => {
390
- if (!name) return [];
391
- const modelProviderKey = findNormalizedProviderKey(modelProviders, name) || name;
392
- const rootProviderKey = findNormalizedProviderKey(rootProviders, name) || name;
393
- return [
394
- modelProviders && modelProviders[modelProviderKey],
395
- rootProviders && rootProviders[rootProviderKey]
396
- ];
397
- };
398
- let providerRecords = buildProviderRecords(providerName);
399
- const hasProviderConfig = providerRecords.some((item) => isPlainRecord(item));
400
- if (!hasProviderConfig && providerKeys.length === 1) {
401
- providerName = providerKeys[0];
402
- providerRecords = buildProviderRecords(providerName);
403
- }
404
- const providerConfig = providerRecords.find((item) => isPlainRecord(item)) || null;
405
- const providerModels = readPreferredProviderModels(providerRecords);
406
-
407
- let modelEntry = null;
408
- if (providerModels.length) {
409
- if (modelId) {
410
- modelEntry = providerModels.find(item => item && (item.id === modelId || item.model === modelId));
411
- }
412
- if (!modelEntry && providerModels.length === 1) {
413
- modelEntry = providerModels[0];
414
- if (!modelId && modelEntry) {
415
- if (typeof modelEntry.id === 'string' && modelEntry.id.trim()) {
416
- modelId = modelEntry.id.trim();
417
- } else if (typeof modelEntry.model === 'string' && modelEntry.model.trim()) {
418
- modelId = modelEntry.model.trim();
419
- }
420
- }
421
- }
422
- }
423
-
424
- const configuredBaseUrlField = readFirstProviderDisplayValue(providerRecords, ['baseUrl', 'base_url', 'url']);
425
- const baseUrlField = configuredBaseUrlField.value
426
- ? configuredBaseUrlField
427
- : readBuiltinProviderDisplayValue(providerName, 'baseUrl');
428
- const providerApiKeyField = readFirstProviderDisplayValue(providerRecords, ['apiKey', 'api_key', 'keyRef', 'key', 'authToken', 'auth_token', 'tokenRef', 'token']);
429
- const authProfileField = providerName
430
- ? readOpenclawAuthProfileDisplayValue(authProfilesByProvider, providerName)
431
- : {
432
- value: '',
433
- readOnly: false,
434
- kind: 'missing',
435
- sourceKind: '',
436
- sourceProfileId: '',
437
- sourceWriteField: '',
438
- sourceOriginalValue: '',
439
- sourceCredentialType: ''
440
- };
441
- const apiKeyField = providerApiKeyField.value ? providerApiKeyField : authProfileField;
442
- const configuredApiTypeField = readFirstProviderDisplayValue(providerRecords, ['api', 'apiType', 'api_type']);
443
- const apiTypeField = configuredApiTypeField.value
444
- ? configuredApiTypeField
445
- : readBuiltinProviderDisplayValue(providerName, 'apiType');
446
-
447
- this.openclawQuick = {
448
- ...defaults,
449
- providerName,
450
- baseUrl: baseUrlField.value,
451
- baseUrlReadOnly: baseUrlField.readOnly,
452
- baseUrlDisplayKind: baseUrlField.kind,
453
- apiKey: apiKeyField.value,
454
- apiKeyReadOnly: apiKeyField.readOnly,
455
- apiKeyDisplayKind: apiKeyField.kind,
456
- apiKeySourceKind: apiKeyField.sourceKind || '',
457
- apiKeySourceProfileId: apiKeyField.sourceProfileId || '',
458
- apiKeySourceWriteField: apiKeyField.sourceWriteField || '',
459
- apiKeySourceOriginalValue: apiKeyField.sourceOriginalValue || '',
460
- apiKeySourceCredentialType: apiKeyField.sourceCredentialType || '',
461
- apiType: apiTypeField.value || defaults.apiType,
462
- modelId: modelId || '',
463
- modelName: modelEntry && typeof modelEntry.name === 'string'
464
- ? modelEntry.name
465
- : (modelEntry && typeof modelEntry.displayName === 'string' ? modelEntry.displayName : ''),
466
- contextWindow: modelEntry && typeof modelEntry.contextWindow === 'number'
467
- ? String(modelEntry.contextWindow)
468
- : (modelEntry && typeof modelEntry.context_window === 'number' ? String(modelEntry.context_window) : ''),
469
- maxTokens: modelEntry && typeof modelEntry.maxTokens === 'number'
470
- ? String(modelEntry.maxTokens)
471
- : (modelEntry && typeof modelEntry.max_tokens === 'number' ? String(modelEntry.max_tokens) : '')
472
- };
473
- },
474
-
475
- syncOpenclawQuickFromText(options = {}) {
476
- const silent = !!options.silent;
477
- const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
478
- if (!parsed.ok) {
479
- this.resetOpenclawQuick();
480
- if (!silent) {
481
- this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
482
- }
483
- return false;
484
- }
485
- this.fillOpenclawQuickFromConfig(parsed.data, {
486
- authProfilesByProvider: this.openclawAuthProfilesByProvider
487
- });
488
- if (!silent) {
489
- this.showMessage('已读取配置', 'success');
490
- }
491
- return true;
492
- },
493
-
494
- mergeOpenclawModelEntry(existing, incoming, overwrite = false) {
495
- if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
496
- return { ...incoming };
497
- }
498
- if (overwrite) {
499
- return { ...incoming };
500
- }
501
- const merged = { ...existing };
502
- for (const [key, value] of Object.entries(incoming || {})) {
503
- if (merged[key] === undefined || merged[key] === null || merged[key] === '') {
504
- merged[key] = value;
505
- }
506
- }
507
- return merged;
508
- },
509
-
510
- fillOpenclawStructured(config) {
511
- const defaults = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
512
- && config.agents.defaults && typeof config.agents.defaults === 'object' && !Array.isArray(config.agents.defaults)
513
- ? config.agents.defaults
514
- : {};
515
- const model = defaults.model && typeof defaults.model === 'object' && !Array.isArray(defaults.model)
516
- ? defaults.model
517
- : {};
518
- const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
519
- ? config.agent
520
- : {};
521
- const fallbackSource = Array.isArray(model.fallbacks)
522
- ? model.fallbacks
523
- : (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model) && Array.isArray(legacyAgent.model.fallbacks)
524
- ? legacyAgent.model.fallbacks
525
- : []);
526
- const fallbackList = fallbackSource
527
- .filter(item => typeof item === 'string' && item.trim())
528
- .map(item => item.trim());
529
- const env = config && config.env && typeof config.env === 'object' && !Array.isArray(config.env)
530
- ? config.env
531
- : {};
532
- const envItems = Object.entries(env).map(([key, value]) => ({
533
- key,
534
- value: value == null ? '' : String(value),
535
- show: false
536
- }));
537
- const tools = config && config.tools && typeof config.tools === 'object' && !Array.isArray(config.tools)
538
- ? config.tools
539
- : {};
540
-
541
- let primary = typeof model.primary === 'string' ? model.primary : '';
542
- if (!primary) {
543
- if (typeof legacyAgent.model === 'string') {
544
- primary = legacyAgent.model;
545
- } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && typeof legacyAgent.model.primary === 'string') {
546
- primary = legacyAgent.model.primary;
547
- }
548
- }
549
-
550
- this.openclawStructured = {
551
- agentPrimary: primary,
552
- agentFallbacks: fallbackList.length ? fallbackList : [''],
553
- workspace: typeof defaults.workspace === 'string' ? defaults.workspace : '',
554
- timeout: typeof defaults.timeout === 'number' && Number.isFinite(defaults.timeout)
555
- ? String(defaults.timeout)
556
- : '',
557
- contextTokens: typeof defaults.contextTokens === 'number' && Number.isFinite(defaults.contextTokens)
558
- ? String(defaults.contextTokens)
559
- : '',
560
- maxConcurrent: typeof defaults.maxConcurrent === 'number' && Number.isFinite(defaults.maxConcurrent)
561
- ? String(defaults.maxConcurrent)
562
- : '',
563
- envItems: envItems.length ? envItems : [{ key: '', value: '', show: false }],
564
- toolsProfile: typeof tools.profile === 'string' && tools.profile.trim() ? tools.profile : 'default',
565
- toolsAllow: Array.isArray(tools.allow) && tools.allow.length
566
- ? tools.allow.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
567
- : [''],
568
- toolsDeny: Array.isArray(tools.deny) && tools.deny.length
569
- ? tools.deny.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
570
- : ['']
571
- };
572
- },
573
-
574
- syncOpenclawStructuredFromText(options = {}) {
575
- const silent = !!options.silent;
576
- const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
577
- if (!parsed.ok) {
578
- this.resetOpenclawStructured();
579
- this.resetOpenclawQuick();
580
- if (!silent) {
581
- this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
582
- }
583
- return false;
584
- }
585
- this.fillOpenclawStructured(parsed.data);
586
- this.fillOpenclawQuickFromConfig(parsed.data, {
587
- authProfilesByProvider: this.openclawAuthProfilesByProvider
588
- });
589
- this.refreshOpenclawProviders(parsed.data);
590
- this.refreshOpenclawAgentsList(parsed.data);
591
- if (!silent) {
592
- this.showMessage('已刷新配置', 'success');
593
- }
594
- return true;
595
- },
596
-
597
- getOpenclawActiveProviders(config) {
598
- const active = new Set();
599
- const addProvider = (ref) => {
600
- if (typeof ref !== 'string') return;
601
- const text = ref.trim();
602
- if (!text) return;
603
- const parts = text.split('/');
604
- if (parts.length < 2) return;
605
- const provider = parts[0].trim();
606
- if (provider) active.add(provider);
607
- };
608
- const defaults = config && config.agents && config.agents.defaults
609
- ? config.agents.defaults
610
- : {};
611
- const model = defaults && defaults.model;
612
- if (model && typeof model === 'object' && !Array.isArray(model)) {
613
- addProvider(model.primary);
614
- if (Array.isArray(model.fallbacks)) {
615
- for (const item of model.fallbacks) {
616
- addProvider(item);
617
- }
618
- }
619
- } else if (typeof model === 'string') {
620
- addProvider(model);
621
- }
622
- const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
623
- ? config.agent
624
- : {};
625
- if (typeof legacyAgent.model === 'string') {
626
- addProvider(legacyAgent.model);
627
- } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model)) {
628
- addProvider(legacyAgent.model.primary);
629
- if (Array.isArray(legacyAgent.model.fallbacks)) {
630
- for (const item of legacyAgent.model.fallbacks) {
631
- addProvider(item);
632
- }
633
- }
634
- }
635
- const modelsDefaults = config && config.models && config.models.defaults
636
- ? config.models.defaults
637
- : {};
638
- if (modelsDefaults && typeof modelsDefaults.provider === 'string' && modelsDefaults.provider.trim()) {
639
- active.add(modelsDefaults.provider.trim());
640
- }
641
- if (modelsDefaults && typeof modelsDefaults.model === 'string') {
642
- addProvider(modelsDefaults.model);
643
- }
644
- return active;
645
- },
646
-
647
- maskProviderValue(value) {
648
- const text = value == null ? '' : String(value);
649
- if (!text) return '****';
650
- if (text.length <= 6) return '****';
651
- return `${text.slice(0, 3)}****${text.slice(-3)}`;
652
- },
653
-
654
- formatProviderValue(key, value) {
655
- if (typeof value === 'undefined' || value === null) {
656
- return '';
657
- }
658
- if (coerceSecretRefRecord(value)) {
659
- return formatSecretRefLabel(value);
660
- }
661
- let text = '';
662
- if (typeof value === 'string') {
663
- text = value;
664
- } else if (typeof value === 'number' || typeof value === 'boolean') {
665
- text = String(value);
666
- } else {
667
- try {
668
- text = JSON.stringify(value);
669
- } catch (_) {
670
- text = String(value);
671
- }
672
- }
673
- if (!text) return '';
674
- if (isEnvTemplateString(text)) {
675
- return `EnvRef(${text.trim().slice(2, -1)})`;
676
- }
677
- if (/key|token|secret|password/i.test(key)) {
678
- return this.maskProviderValue(text);
679
- }
680
- if (text.length > 160) {
681
- return `${text.slice(0, 157)}...`;
682
- }
683
- return text;
684
- },
685
-
686
- collectOpenclawProviders(source, providerMap, activeProviders, entries) {
687
- if (!providerMap || typeof providerMap !== 'object' || Array.isArray(providerMap)) {
688
- return;
689
- }
690
- const keys = Object.keys(providerMap).sort();
691
- for (const key of keys) {
692
- const value = providerMap[key];
693
- const fields = [];
694
- if (value && typeof value === 'object' && !Array.isArray(value)) {
695
- const fieldKeys = Object.keys(value).sort();
696
- for (const fieldKey of fieldKeys) {
697
- const fieldValue = this.formatProviderValue(fieldKey, value[fieldKey]);
698
- if (fieldValue === '') continue;
699
- fields.push({ key: fieldKey, value: fieldValue });
700
- }
701
- } else {
702
- const fieldValue = this.formatProviderValue('value', value);
703
- if (fieldValue !== '') {
704
- fields.push({ key: 'value', value: fieldValue });
705
- }
706
- }
707
- entries.push({
708
- key,
709
- source,
710
- fields,
711
- isActive: activeProviders.has(key)
712
- });
713
- }
714
- },
715
-
716
- refreshOpenclawProviders(config) {
717
- const activeProviders = this.getOpenclawActiveProviders(config || {});
718
- const entries = [];
719
- const modelsProviders = config && config.models ? config.models.providers : null;
720
- const rootProviders = config && config.providers ? config.providers : null;
721
- this.collectOpenclawProviders('models.providers', modelsProviders, activeProviders, entries);
722
- this.collectOpenclawProviders('providers', rootProviders, activeProviders, entries);
723
- const existing = new Set(entries.map(item => item.key));
724
- const missing = [];
725
- for (const provider of activeProviders) {
726
- if (!existing.has(provider)) {
727
- missing.push(provider);
728
- }
729
- }
730
- this.openclawProviders = entries;
731
- this.openclawMissingProviders = missing;
732
- },
733
-
734
- refreshOpenclawAgentsList(config) {
735
- const list = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
736
- ? config.agents.list
737
- : null;
738
- if (!Array.isArray(list)) {
739
- this.openclawAgentsList = [];
740
- return;
741
- }
742
- const entries = [];
743
- list.forEach((item, index) => {
744
- if (!item || typeof item !== 'object') return;
745
- const id = typeof item.id === 'string' && item.id.trim() ? item.id.trim() : `agent-${index + 1}`;
746
- const identity = item.identity && typeof item.identity === 'object' && !Array.isArray(item.identity)
747
- ? item.identity
748
- : {};
749
- const name = typeof identity.name === 'string' && identity.name.trim()
750
- ? identity.name.trim()
751
- : id;
752
- entries.push({
753
- key: `${id}-${index}`,
754
- id,
755
- name,
756
- theme: typeof identity.theme === 'string' ? identity.theme : '',
757
- emoji: typeof identity.emoji === 'string' ? identity.emoji : '',
758
- avatar: typeof identity.avatar === 'string' ? identity.avatar : ''
759
- });
760
- });
761
- this.openclawAgentsList = entries;
762
- },
763
-
764
- normalizeStringList(list) {
765
- if (!Array.isArray(list)) return [];
766
- const result = [];
767
- const seen = new Set();
768
- for (const item of list) {
769
- const value = typeof item === 'string' ? item.trim() : String(item || '').trim();
770
- if (!value) continue;
771
- const key = value;
772
- if (seen.has(key)) continue;
773
- seen.add(key);
774
- result.push(value);
775
- }
776
- return result;
777
- },
778
-
779
- normalizeEnvItems(items) {
780
- if (!Array.isArray(items)) {
781
- return { ok: true, items: {} };
782
- }
783
- const output = {};
784
- const seen = new Set();
785
- for (const item of items) {
786
- const key = item && typeof item.key === 'string' ? item.key.trim() : '';
787
- if (!key) continue;
788
- if (seen.has(key)) {
789
- return { ok: false, error: `环境变量重复: ${key}` };
790
- }
791
- seen.add(key);
792
- const value = item && typeof item.value !== 'undefined' ? String(item.value) : '';
793
- output[key] = value;
794
- }
795
- return { ok: true, items: output };
796
- },
797
-
798
- parseOptionalNumber(value, label) {
799
- const text = typeof value === 'string'
800
- ? value.trim()
801
- : typeof value === 'number'
802
- ? String(value).trim()
803
- : String(value || '').trim();
804
- if (!text) {
805
- return { ok: true, value: null };
806
- }
807
- const num = Number(text);
808
- if (!Number.isFinite(num) || num < 0) {
809
- return { ok: false, error: `${label} 请输入有效数字` };
810
- }
811
- return { ok: true, value: num };
812
- }
813
- };
814
- }
1
+ function isPlainRecord(value) {
2
+ return !!(value && typeof value === 'object' && !Array.isArray(value));
3
+ }
4
+
5
+ function normalizeProviderId(provider) {
6
+ const normalized = typeof provider === 'string' ? provider.trim().toLowerCase() : '';
7
+ if (!normalized) return '';
8
+ if (normalized === 'modelstudio' || normalized === 'qwencloud') {
9
+ return 'qwen';
10
+ }
11
+ if (normalized === 'z.ai' || normalized === 'z-ai') {
12
+ return 'zai';
13
+ }
14
+ if (normalized === 'opencode-zen') {
15
+ return 'opencode';
16
+ }
17
+ if (normalized === 'opencode-go-auth') {
18
+ return 'opencode-go';
19
+ }
20
+ if (normalized === 'kimi' || normalized === 'kimi-code' || normalized === 'kimi-coding') {
21
+ return 'kimi';
22
+ }
23
+ if (normalized === 'bedrock' || normalized === 'aws-bedrock') {
24
+ return 'amazon-bedrock';
25
+ }
26
+ if (normalized === 'bytedance' || normalized === 'doubao') {
27
+ return 'volcengine';
28
+ }
29
+ return normalized;
30
+ }
31
+
32
+ function findNormalizedProviderKey(entries, provider) {
33
+ if (!isPlainRecord(entries)) {
34
+ return '';
35
+ }
36
+ const providerKey = normalizeProviderId(provider);
37
+ if (!providerKey) {
38
+ return '';
39
+ }
40
+ return Object.keys(entries).find((key) => normalizeProviderId(key) === providerKey) || '';
41
+ }
42
+
43
+ function collectDistinctProviderKeys(...providerMaps) {
44
+ const byNormalizedKey = new Map();
45
+ for (const providerMap of providerMaps) {
46
+ if (!isPlainRecord(providerMap)) continue;
47
+ for (const key of Object.keys(providerMap)) {
48
+ const normalizedKey = normalizeProviderId(key);
49
+ if (!normalizedKey || byNormalizedKey.has(normalizedKey)) continue;
50
+ byNormalizedKey.set(normalizedKey, key);
51
+ }
52
+ }
53
+ return Array.from(byNormalizedKey.values());
54
+ }
55
+
56
+ function isEnvTemplateString(value) {
57
+ return typeof value === 'string' && /^\$\{[A-Z][A-Z0-9_]{0,127}\}$/.test(value.trim());
58
+ }
59
+
60
+ function isSecretRefRecord(value) {
61
+ return isPlainRecord(value)
62
+ && typeof value.source === 'string'
63
+ && typeof value.provider === 'string'
64
+ && typeof value.id === 'string';
65
+ }
66
+
67
+ function isLegacySecretRefRecord(value) {
68
+ return isPlainRecord(value)
69
+ && typeof value.source === 'string'
70
+ && typeof value.id === 'string'
71
+ && (value.provider === undefined || value.provider === null || value.provider === '');
72
+ }
73
+
74
+ function coerceSecretRefRecord(value) {
75
+ if (isSecretRefRecord(value)) {
76
+ return {
77
+ source: value.source.trim(),
78
+ provider: value.provider.trim(),
79
+ id: value.id.trim()
80
+ };
81
+ }
82
+ if (isLegacySecretRefRecord(value)) {
83
+ return {
84
+ source: value.source.trim(),
85
+ provider: 'default',
86
+ id: value.id.trim()
87
+ };
88
+ }
89
+ return null;
90
+ }
91
+
92
+ const BUILTIN_PROVIDER_DEFAULTS = {
93
+ openai: {
94
+ baseUrl: 'https://api.openai.com/v1',
95
+ apiType: 'openai-responses'
96
+ },
97
+ 'openai-codex': {
98
+ baseUrl: 'https://chatgpt.com/backend-api',
99
+ apiType: 'openai-codex-responses'
100
+ }
101
+ };
102
+
103
+ function formatSecretRefLabel(ref) {
104
+ const normalized = coerceSecretRefRecord(ref);
105
+ if (!normalized) return '';
106
+ return `SecretRef(${normalized.source}:${normalized.provider}:${normalized.id})`;
107
+ }
108
+
109
+ function readFirstProviderDisplayValue(records, keys) {
110
+ for (const record of records) {
111
+ if (!isPlainRecord(record)) continue;
112
+ for (const key of keys) {
113
+ if (typeof record[key] === 'string' && record[key].trim()) {
114
+ return {
115
+ value: record[key].trim(),
116
+ readOnly: false,
117
+ kind: isEnvTemplateString(record[key]) ? 'env-template' : 'string'
118
+ };
119
+ }
120
+ if (coerceSecretRefRecord(record[key])) {
121
+ return {
122
+ value: formatSecretRefLabel(record[key]),
123
+ readOnly: true,
124
+ kind: 'secret-ref'
125
+ };
126
+ }
127
+ }
128
+ }
129
+ return {
130
+ value: '',
131
+ readOnly: false,
132
+ kind: 'missing'
133
+ };
134
+ }
135
+
136
+ function readOpenclawAuthProfileDisplayValue(authProfilesByProvider, providerName) {
137
+ const matchedKey = findNormalizedProviderKey(authProfilesByProvider, providerName) || providerName;
138
+ const summary = isPlainRecord(authProfilesByProvider) ? authProfilesByProvider[matchedKey] : null;
139
+ if (!isPlainRecord(summary)) {
140
+ return {
141
+ value: '',
142
+ readOnly: false,
143
+ kind: 'missing',
144
+ sourceKind: '',
145
+ sourceProfileId: '',
146
+ sourceWriteField: '',
147
+ sourceOriginalValue: '',
148
+ sourceCredentialType: ''
149
+ };
150
+ }
151
+ if (typeof summary.resolvedValue === 'string' && summary.resolvedValue.trim()) {
152
+ return {
153
+ value: summary.resolvedValue.trim(),
154
+ readOnly: false,
155
+ kind: 'auth-profile-value',
156
+ sourceKind: 'auth-profile',
157
+ sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
158
+ sourceWriteField: typeof summary.resolvedField === 'string' ? summary.resolvedField.trim() : '',
159
+ sourceOriginalValue: summary.resolvedValue.trim(),
160
+ sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
161
+ };
162
+ }
163
+ const resolvedField = typeof summary.resolvedField === 'string' ? summary.resolvedField.trim() : '';
164
+ if (summary.editable === true && resolvedField) {
165
+ return {
166
+ value: '',
167
+ readOnly: false,
168
+ kind: 'auth-profile-value',
169
+ sourceKind: 'auth-profile',
170
+ sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
171
+ sourceWriteField: resolvedField,
172
+ sourceOriginalValue: '',
173
+ sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
174
+ };
175
+ }
176
+ if (typeof summary.display !== 'string' || !summary.display.trim()) {
177
+ return {
178
+ value: '',
179
+ readOnly: false,
180
+ kind: 'missing',
181
+ sourceKind: '',
182
+ sourceProfileId: '',
183
+ sourceWriteField: '',
184
+ sourceOriginalValue: '',
185
+ sourceCredentialType: ''
186
+ };
187
+ }
188
+ return {
189
+ value: summary.display.trim(),
190
+ readOnly: true,
191
+ kind: 'auth-profile',
192
+ sourceKind: '',
193
+ sourceProfileId: typeof summary.profileId === 'string' ? summary.profileId.trim() : '',
194
+ sourceWriteField: '',
195
+ sourceOriginalValue: '',
196
+ sourceCredentialType: typeof summary.type === 'string' ? summary.type.trim() : ''
197
+ };
198
+ }
199
+
200
+ function readBuiltinProviderDisplayValue(providerName, field) {
201
+ const defaults = BUILTIN_PROVIDER_DEFAULTS[normalizeProviderId(providerName)];
202
+ if (!defaults) {
203
+ return {
204
+ value: '',
205
+ readOnly: false,
206
+ kind: 'missing'
207
+ };
208
+ }
209
+ const key = field === 'apiType' ? 'apiType' : 'baseUrl';
210
+ const value = typeof defaults[key] === 'string' ? defaults[key].trim() : '';
211
+ return {
212
+ value,
213
+ readOnly: false,
214
+ kind: value ? 'builtin-default' : 'missing'
215
+ };
216
+ }
217
+
218
+ function readPreferredProviderModels(records) {
219
+ for (const record of records) {
220
+ if (isPlainRecord(record) && Array.isArray(record.models) && record.models.length) {
221
+ return record.models;
222
+ }
223
+ }
224
+ return [];
225
+ }
226
+
227
+ export function createOpenclawCoreMethods() {
228
+ return {
229
+ getOpenclawParser() {
230
+ const globalWindow = typeof window !== 'undefined' ? window : null;
231
+ if (globalWindow && globalWindow.JSON5
232
+ && typeof globalWindow.JSON5.parse === 'function'
233
+ && typeof globalWindow.JSON5.stringify === 'function') {
234
+ return {
235
+ parse: globalWindow.JSON5.parse,
236
+ stringify: globalWindow.JSON5.stringify
237
+ };
238
+ }
239
+ return {
240
+ parse: JSON.parse,
241
+ stringify: JSON.stringify
242
+ };
243
+ },
244
+
245
+ parseOpenclawContent(content, options = {}) {
246
+ const allowEmpty = !!options.allowEmpty;
247
+ const raw = typeof content === 'string' ? content.trim() : '';
248
+ if (!raw) {
249
+ if (allowEmpty) {
250
+ return { ok: true, data: {} };
251
+ }
252
+ return { ok: false, error: '配置内容为空' };
253
+ }
254
+ try {
255
+ const parser = this.getOpenclawParser();
256
+ const data = parser.parse(raw);
257
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
258
+ return { ok: false, error: '配置格式错误(根节点必须是对象)' };
259
+ }
260
+ return { ok: true, data };
261
+ } catch (e) {
262
+ return { ok: false, error: e.message || '解析失败' };
263
+ }
264
+ },
265
+
266
+ stringifyOpenclawConfig(data) {
267
+ const parser = this.getOpenclawParser();
268
+ try {
269
+ return parser.stringify(data, null, 2);
270
+ } catch (e) {
271
+ return JSON.stringify(data, null, 2);
272
+ }
273
+ },
274
+
275
+ resetOpenclawStructured() {
276
+ this.openclawStructured = {
277
+ agentPrimary: '',
278
+ agentFallbacks: [''],
279
+ workspace: '',
280
+ timeout: '',
281
+ contextTokens: '',
282
+ maxConcurrent: '',
283
+ envItems: [{ key: '', value: '', show: false }],
284
+ toolsProfile: 'default',
285
+ toolsAllow: [''],
286
+ toolsDeny: ['']
287
+ };
288
+ this.openclawAgentsList = [];
289
+ this.openclawProviders = [];
290
+ this.openclawMissingProviders = [];
291
+ },
292
+
293
+ getOpenclawQuickDefaults() {
294
+ return {
295
+ providerName: '',
296
+ baseUrl: '',
297
+ baseUrlReadOnly: false,
298
+ baseUrlDisplayKind: 'missing',
299
+ apiKey: '',
300
+ apiKeyReadOnly: false,
301
+ apiKeyDisplayKind: 'missing',
302
+ apiKeySourceKind: '',
303
+ apiKeySourceProfileId: '',
304
+ apiKeySourceWriteField: '',
305
+ apiKeySourceOriginalValue: '',
306
+ apiKeySourceCredentialType: '',
307
+ apiType: 'openai-responses',
308
+ modelId: '',
309
+ modelName: '',
310
+ contextWindow: '',
311
+ maxTokens: '',
312
+ setPrimary: true,
313
+ overrideProvider: true,
314
+ overrideModels: true,
315
+ showKey: false
316
+ };
317
+ },
318
+
319
+ resetOpenclawQuick() {
320
+ this.openclawQuick = this.getOpenclawQuickDefaults();
321
+ },
322
+
323
+ toggleOpenclawQuickKey() {
324
+ this.openclawQuick.showKey = !this.openclawQuick.showKey;
325
+ },
326
+
327
+ fillOpenclawQuickFromConfig(config, options = {}) {
328
+ const defaults = this.getOpenclawQuickDefaults();
329
+ if (!isPlainRecord(config)) {
330
+ this.openclawQuick = defaults;
331
+ return;
332
+ }
333
+ const authProfilesByProvider = isPlainRecord(options.authProfilesByProvider)
334
+ ? options.authProfilesByProvider
335
+ : (isPlainRecord(this.openclawAuthProfilesByProvider) ? this.openclawAuthProfilesByProvider : {});
336
+
337
+ const agentDefaults = isPlainRecord(config.agents) && isPlainRecord(config.agents.defaults)
338
+ ? config.agents.defaults
339
+ : {};
340
+ const modelConfig = agentDefaults.model;
341
+ const legacyAgent = isPlainRecord(config.agent)
342
+ ? config.agent
343
+ : {};
344
+
345
+ let primaryRef = '';
346
+ if (isPlainRecord(modelConfig) && typeof modelConfig.primary === 'string') {
347
+ primaryRef = modelConfig.primary;
348
+ } else if (typeof modelConfig === 'string') {
349
+ primaryRef = modelConfig;
350
+ }
351
+ if (!primaryRef) {
352
+ if (typeof legacyAgent.model === 'string') {
353
+ primaryRef = legacyAgent.model;
354
+ } else if (isPlainRecord(legacyAgent.model) && typeof legacyAgent.model.primary === 'string') {
355
+ primaryRef = legacyAgent.model.primary;
356
+ }
357
+ }
358
+
359
+ let providerName = '';
360
+ let modelId = '';
361
+ if (primaryRef) {
362
+ const parts = primaryRef.split('/');
363
+ if (parts.length >= 2) {
364
+ providerName = parts.shift().trim();
365
+ modelId = parts.join('/').trim();
366
+ }
367
+ }
368
+
369
+ const modelProviders = isPlainRecord(config.models) && isPlainRecord(config.models.providers)
370
+ ? config.models.providers
371
+ : null;
372
+ const rootProviders = isPlainRecord(config.providers)
373
+ ? config.providers
374
+ : null;
375
+ const providerKeys = collectDistinctProviderKeys(modelProviders, rootProviders);
376
+ if (!providerName && providerKeys.length === 1) {
377
+ providerName = providerKeys[0];
378
+ }
379
+
380
+ const normalizedConfiguredProviderName = providerName
381
+ ? (findNormalizedProviderKey(modelProviders, providerName)
382
+ || findNormalizedProviderKey(rootProviders, providerName)
383
+ || providerName)
384
+ : '';
385
+ if (normalizedConfiguredProviderName) {
386
+ providerName = normalizedConfiguredProviderName;
387
+ }
388
+
389
+ const buildProviderRecords = (name) => {
390
+ if (!name) return [];
391
+ const modelProviderKey = findNormalizedProviderKey(modelProviders, name) || name;
392
+ const rootProviderKey = findNormalizedProviderKey(rootProviders, name) || name;
393
+ return [
394
+ modelProviders && modelProviders[modelProviderKey],
395
+ rootProviders && rootProviders[rootProviderKey]
396
+ ];
397
+ };
398
+ let providerRecords = buildProviderRecords(providerName);
399
+ const hasProviderConfig = providerRecords.some((item) => isPlainRecord(item));
400
+ if (!hasProviderConfig && providerKeys.length === 1) {
401
+ providerName = providerKeys[0];
402
+ providerRecords = buildProviderRecords(providerName);
403
+ }
404
+ const providerConfig = providerRecords.find((item) => isPlainRecord(item)) || null;
405
+ const providerModels = readPreferredProviderModels(providerRecords);
406
+
407
+ let modelEntry = null;
408
+ if (providerModels.length) {
409
+ if (modelId) {
410
+ modelEntry = providerModels.find(item => item && (item.id === modelId || item.model === modelId));
411
+ }
412
+ if (!modelEntry && providerModels.length === 1) {
413
+ modelEntry = providerModels[0];
414
+ if (!modelId && modelEntry) {
415
+ if (typeof modelEntry.id === 'string' && modelEntry.id.trim()) {
416
+ modelId = modelEntry.id.trim();
417
+ } else if (typeof modelEntry.model === 'string' && modelEntry.model.trim()) {
418
+ modelId = modelEntry.model.trim();
419
+ }
420
+ }
421
+ }
422
+ }
423
+
424
+ const configuredBaseUrlField = readFirstProviderDisplayValue(providerRecords, ['baseUrl', 'base_url', 'url']);
425
+ const baseUrlField = configuredBaseUrlField.value
426
+ ? configuredBaseUrlField
427
+ : readBuiltinProviderDisplayValue(providerName, 'baseUrl');
428
+ const providerApiKeyField = readFirstProviderDisplayValue(providerRecords, ['apiKey', 'api_key', 'keyRef', 'key', 'authToken', 'auth_token', 'tokenRef', 'token']);
429
+ const authProfileField = providerName
430
+ ? readOpenclawAuthProfileDisplayValue(authProfilesByProvider, providerName)
431
+ : {
432
+ value: '',
433
+ readOnly: false,
434
+ kind: 'missing',
435
+ sourceKind: '',
436
+ sourceProfileId: '',
437
+ sourceWriteField: '',
438
+ sourceOriginalValue: '',
439
+ sourceCredentialType: ''
440
+ };
441
+ const apiKeyField = providerApiKeyField.value ? providerApiKeyField : authProfileField;
442
+ const configuredApiTypeField = readFirstProviderDisplayValue(providerRecords, ['api', 'apiType', 'api_type']);
443
+ const apiTypeField = configuredApiTypeField.value
444
+ ? configuredApiTypeField
445
+ : readBuiltinProviderDisplayValue(providerName, 'apiType');
446
+
447
+ this.openclawQuick = {
448
+ ...defaults,
449
+ providerName,
450
+ baseUrl: baseUrlField.value,
451
+ baseUrlReadOnly: baseUrlField.readOnly,
452
+ baseUrlDisplayKind: baseUrlField.kind,
453
+ apiKey: apiKeyField.value,
454
+ apiKeyReadOnly: apiKeyField.readOnly,
455
+ apiKeyDisplayKind: apiKeyField.kind,
456
+ apiKeySourceKind: apiKeyField.sourceKind || '',
457
+ apiKeySourceProfileId: apiKeyField.sourceProfileId || '',
458
+ apiKeySourceWriteField: apiKeyField.sourceWriteField || '',
459
+ apiKeySourceOriginalValue: apiKeyField.sourceOriginalValue || '',
460
+ apiKeySourceCredentialType: apiKeyField.sourceCredentialType || '',
461
+ apiType: apiTypeField.value || defaults.apiType,
462
+ modelId: modelId || '',
463
+ modelName: modelEntry && typeof modelEntry.name === 'string'
464
+ ? modelEntry.name
465
+ : (modelEntry && typeof modelEntry.displayName === 'string' ? modelEntry.displayName : ''),
466
+ contextWindow: modelEntry && typeof modelEntry.contextWindow === 'number'
467
+ ? String(modelEntry.contextWindow)
468
+ : (modelEntry && typeof modelEntry.context_window === 'number' ? String(modelEntry.context_window) : ''),
469
+ maxTokens: modelEntry && typeof modelEntry.maxTokens === 'number'
470
+ ? String(modelEntry.maxTokens)
471
+ : (modelEntry && typeof modelEntry.max_tokens === 'number' ? String(modelEntry.max_tokens) : '')
472
+ };
473
+ },
474
+
475
+ syncOpenclawQuickFromText(options = {}) {
476
+ const silent = !!options.silent;
477
+ const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
478
+ if (!parsed.ok) {
479
+ this.resetOpenclawQuick();
480
+ if (!silent) {
481
+ this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
482
+ }
483
+ return false;
484
+ }
485
+ this.fillOpenclawQuickFromConfig(parsed.data, {
486
+ authProfilesByProvider: this.openclawAuthProfilesByProvider
487
+ });
488
+ if (!silent) {
489
+ this.showMessage('已读取配置', 'success');
490
+ }
491
+ return true;
492
+ },
493
+
494
+ mergeOpenclawModelEntry(existing, incoming, overwrite = false) {
495
+ if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
496
+ return { ...incoming };
497
+ }
498
+ if (overwrite) {
499
+ return { ...incoming };
500
+ }
501
+ const merged = { ...existing };
502
+ for (const [key, value] of Object.entries(incoming || {})) {
503
+ if (merged[key] === undefined || merged[key] === null || merged[key] === '') {
504
+ merged[key] = value;
505
+ }
506
+ }
507
+ return merged;
508
+ },
509
+
510
+ fillOpenclawStructured(config) {
511
+ const defaults = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
512
+ && config.agents.defaults && typeof config.agents.defaults === 'object' && !Array.isArray(config.agents.defaults)
513
+ ? config.agents.defaults
514
+ : {};
515
+ const model = defaults.model && typeof defaults.model === 'object' && !Array.isArray(defaults.model)
516
+ ? defaults.model
517
+ : {};
518
+ const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
519
+ ? config.agent
520
+ : {};
521
+ const fallbackSource = Array.isArray(model.fallbacks)
522
+ ? model.fallbacks
523
+ : (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model) && Array.isArray(legacyAgent.model.fallbacks)
524
+ ? legacyAgent.model.fallbacks
525
+ : []);
526
+ const fallbackList = fallbackSource
527
+ .filter(item => typeof item === 'string' && item.trim())
528
+ .map(item => item.trim());
529
+ const env = config && config.env && typeof config.env === 'object' && !Array.isArray(config.env)
530
+ ? config.env
531
+ : {};
532
+ const envItems = Object.entries(env).map(([key, value]) => ({
533
+ key,
534
+ value: value == null ? '' : String(value),
535
+ show: false
536
+ }));
537
+ const tools = config && config.tools && typeof config.tools === 'object' && !Array.isArray(config.tools)
538
+ ? config.tools
539
+ : {};
540
+
541
+ let primary = typeof model.primary === 'string' ? model.primary : '';
542
+ if (!primary) {
543
+ if (typeof legacyAgent.model === 'string') {
544
+ primary = legacyAgent.model;
545
+ } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && typeof legacyAgent.model.primary === 'string') {
546
+ primary = legacyAgent.model.primary;
547
+ }
548
+ }
549
+
550
+ this.openclawStructured = {
551
+ agentPrimary: primary,
552
+ agentFallbacks: fallbackList.length ? fallbackList : [''],
553
+ workspace: typeof defaults.workspace === 'string' ? defaults.workspace : '',
554
+ timeout: typeof defaults.timeout === 'number' && Number.isFinite(defaults.timeout)
555
+ ? String(defaults.timeout)
556
+ : '',
557
+ contextTokens: typeof defaults.contextTokens === 'number' && Number.isFinite(defaults.contextTokens)
558
+ ? String(defaults.contextTokens)
559
+ : '',
560
+ maxConcurrent: typeof defaults.maxConcurrent === 'number' && Number.isFinite(defaults.maxConcurrent)
561
+ ? String(defaults.maxConcurrent)
562
+ : '',
563
+ envItems: envItems.length ? envItems : [{ key: '', value: '', show: false }],
564
+ toolsProfile: typeof tools.profile === 'string' && tools.profile.trim() ? tools.profile : 'default',
565
+ toolsAllow: Array.isArray(tools.allow) && tools.allow.length
566
+ ? tools.allow.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
567
+ : [''],
568
+ toolsDeny: Array.isArray(tools.deny) && tools.deny.length
569
+ ? tools.deny.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
570
+ : ['']
571
+ };
572
+ },
573
+
574
+ syncOpenclawStructuredFromText(options = {}) {
575
+ const silent = !!options.silent;
576
+ const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
577
+ if (!parsed.ok) {
578
+ this.resetOpenclawStructured();
579
+ this.resetOpenclawQuick();
580
+ if (!silent) {
581
+ this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
582
+ }
583
+ return false;
584
+ }
585
+ this.fillOpenclawStructured(parsed.data);
586
+ this.fillOpenclawQuickFromConfig(parsed.data, {
587
+ authProfilesByProvider: this.openclawAuthProfilesByProvider
588
+ });
589
+ this.refreshOpenclawProviders(parsed.data);
590
+ this.refreshOpenclawAgentsList(parsed.data);
591
+ if (!silent) {
592
+ this.showMessage('已刷新配置', 'success');
593
+ }
594
+ return true;
595
+ },
596
+
597
+ getOpenclawActiveProviders(config) {
598
+ const active = new Set();
599
+ const addProvider = (ref) => {
600
+ if (typeof ref !== 'string') return;
601
+ const text = ref.trim();
602
+ if (!text) return;
603
+ const parts = text.split('/');
604
+ if (parts.length < 2) return;
605
+ const provider = parts[0].trim();
606
+ if (provider) active.add(provider);
607
+ };
608
+ const defaults = config && config.agents && config.agents.defaults
609
+ ? config.agents.defaults
610
+ : {};
611
+ const model = defaults && defaults.model;
612
+ if (model && typeof model === 'object' && !Array.isArray(model)) {
613
+ addProvider(model.primary);
614
+ if (Array.isArray(model.fallbacks)) {
615
+ for (const item of model.fallbacks) {
616
+ addProvider(item);
617
+ }
618
+ }
619
+ } else if (typeof model === 'string') {
620
+ addProvider(model);
621
+ }
622
+ const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
623
+ ? config.agent
624
+ : {};
625
+ if (typeof legacyAgent.model === 'string') {
626
+ addProvider(legacyAgent.model);
627
+ } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model)) {
628
+ addProvider(legacyAgent.model.primary);
629
+ if (Array.isArray(legacyAgent.model.fallbacks)) {
630
+ for (const item of legacyAgent.model.fallbacks) {
631
+ addProvider(item);
632
+ }
633
+ }
634
+ }
635
+ const modelsDefaults = config && config.models && config.models.defaults
636
+ ? config.models.defaults
637
+ : {};
638
+ if (modelsDefaults && typeof modelsDefaults.provider === 'string' && modelsDefaults.provider.trim()) {
639
+ active.add(modelsDefaults.provider.trim());
640
+ }
641
+ if (modelsDefaults && typeof modelsDefaults.model === 'string') {
642
+ addProvider(modelsDefaults.model);
643
+ }
644
+ return active;
645
+ },
646
+
647
+ maskProviderValue(value) {
648
+ const text = value == null ? '' : String(value);
649
+ if (!text) return '****';
650
+ if (text.length <= 6) return '****';
651
+ return `${text.slice(0, 3)}****${text.slice(-3)}`;
652
+ },
653
+
654
+ formatProviderValue(key, value) {
655
+ if (typeof value === 'undefined' || value === null) {
656
+ return '';
657
+ }
658
+ if (coerceSecretRefRecord(value)) {
659
+ return formatSecretRefLabel(value);
660
+ }
661
+ let text = '';
662
+ if (typeof value === 'string') {
663
+ text = value;
664
+ } else if (typeof value === 'number' || typeof value === 'boolean') {
665
+ text = String(value);
666
+ } else {
667
+ try {
668
+ text = JSON.stringify(value);
669
+ } catch (_) {
670
+ text = String(value);
671
+ }
672
+ }
673
+ if (!text) return '';
674
+ if (isEnvTemplateString(text)) {
675
+ return `EnvRef(${text.trim().slice(2, -1)})`;
676
+ }
677
+ if (/key|token|secret|password/i.test(key)) {
678
+ return this.maskProviderValue(text);
679
+ }
680
+ if (text.length > 160) {
681
+ return `${text.slice(0, 157)}...`;
682
+ }
683
+ return text;
684
+ },
685
+
686
+ collectOpenclawProviders(source, providerMap, activeProviders, entries) {
687
+ if (!providerMap || typeof providerMap !== 'object' || Array.isArray(providerMap)) {
688
+ return;
689
+ }
690
+ const keys = Object.keys(providerMap).sort();
691
+ for (const key of keys) {
692
+ const value = providerMap[key];
693
+ const fields = [];
694
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
695
+ const fieldKeys = Object.keys(value).sort();
696
+ for (const fieldKey of fieldKeys) {
697
+ const fieldValue = this.formatProviderValue(fieldKey, value[fieldKey]);
698
+ if (fieldValue === '') continue;
699
+ fields.push({ key: fieldKey, value: fieldValue });
700
+ }
701
+ } else {
702
+ const fieldValue = this.formatProviderValue('value', value);
703
+ if (fieldValue !== '') {
704
+ fields.push({ key: 'value', value: fieldValue });
705
+ }
706
+ }
707
+ entries.push({
708
+ key,
709
+ source,
710
+ fields,
711
+ isActive: activeProviders.has(key)
712
+ });
713
+ }
714
+ },
715
+
716
+ refreshOpenclawProviders(config) {
717
+ const activeProviders = this.getOpenclawActiveProviders(config || {});
718
+ const entries = [];
719
+ const modelsProviders = config && config.models ? config.models.providers : null;
720
+ const rootProviders = config && config.providers ? config.providers : null;
721
+ this.collectOpenclawProviders('models.providers', modelsProviders, activeProviders, entries);
722
+ this.collectOpenclawProviders('providers', rootProviders, activeProviders, entries);
723
+ const existing = new Set(entries.map(item => item.key));
724
+ const missing = [];
725
+ for (const provider of activeProviders) {
726
+ if (!existing.has(provider)) {
727
+ missing.push(provider);
728
+ }
729
+ }
730
+ this.openclawProviders = entries;
731
+ this.openclawMissingProviders = missing;
732
+ },
733
+
734
+ refreshOpenclawAgentsList(config) {
735
+ const list = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
736
+ ? config.agents.list
737
+ : null;
738
+ if (!Array.isArray(list)) {
739
+ this.openclawAgentsList = [];
740
+ return;
741
+ }
742
+ const entries = [];
743
+ list.forEach((item, index) => {
744
+ if (!item || typeof item !== 'object') return;
745
+ const id = typeof item.id === 'string' && item.id.trim() ? item.id.trim() : `agent-${index + 1}`;
746
+ const identity = item.identity && typeof item.identity === 'object' && !Array.isArray(item.identity)
747
+ ? item.identity
748
+ : {};
749
+ const name = typeof identity.name === 'string' && identity.name.trim()
750
+ ? identity.name.trim()
751
+ : id;
752
+ entries.push({
753
+ key: `${id}-${index}`,
754
+ id,
755
+ name,
756
+ theme: typeof identity.theme === 'string' ? identity.theme : '',
757
+ emoji: typeof identity.emoji === 'string' ? identity.emoji : '',
758
+ avatar: typeof identity.avatar === 'string' ? identity.avatar : ''
759
+ });
760
+ });
761
+ this.openclawAgentsList = entries;
762
+ },
763
+
764
+ normalizeStringList(list) {
765
+ if (!Array.isArray(list)) return [];
766
+ const result = [];
767
+ const seen = new Set();
768
+ for (const item of list) {
769
+ const value = typeof item === 'string' ? item.trim() : String(item || '').trim();
770
+ if (!value) continue;
771
+ const key = value;
772
+ if (seen.has(key)) continue;
773
+ seen.add(key);
774
+ result.push(value);
775
+ }
776
+ return result;
777
+ },
778
+
779
+ normalizeEnvItems(items) {
780
+ if (!Array.isArray(items)) {
781
+ return { ok: true, items: {} };
782
+ }
783
+ const output = {};
784
+ const seen = new Set();
785
+ for (const item of items) {
786
+ const key = item && typeof item.key === 'string' ? item.key.trim() : '';
787
+ if (!key) continue;
788
+ if (seen.has(key)) {
789
+ return { ok: false, error: `环境变量重复: ${key}` };
790
+ }
791
+ seen.add(key);
792
+ const value = item && typeof item.value !== 'undefined' ? String(item.value) : '';
793
+ output[key] = value;
794
+ }
795
+ return { ok: true, items: output };
796
+ },
797
+
798
+ parseOptionalNumber(value, label) {
799
+ const text = typeof value === 'string'
800
+ ? value.trim()
801
+ : typeof value === 'number'
802
+ ? String(value).trim()
803
+ : String(value || '').trim();
804
+ if (!text) {
805
+ return { ok: true, value: null };
806
+ }
807
+ const num = Number(text);
808
+ if (!Number.isFinite(num) || num < 0) {
809
+ return { ok: false, error: `${label} 请输入有效数字` };
810
+ }
811
+ return { ok: true, value: num };
812
+ }
813
+ };
814
+ }