codexmate 0.0.20 → 0.0.21

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 (102) hide show
  1. package/README.en.md +349 -259
  2. package/README.md +284 -252
  3. package/cli/agents-files.js +162 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +580 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/config-health.js +338 -338
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/skills.js +1141 -0
  12. package/cli/zip-commands.js +510 -0
  13. package/cli.js +13101 -13497
  14. package/lib/cli-file-utils.js +151 -151
  15. package/lib/cli-models-utils.js +419 -311
  16. package/lib/cli-network-utils.js +164 -164
  17. package/lib/cli-path-utils.js +69 -0
  18. package/lib/cli-session-utils.js +121 -121
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/cli-utils.js +155 -155
  21. package/lib/download-artifacts.js +77 -0
  22. package/lib/mcp-stdio.js +440 -440
  23. package/lib/task-orchestrator.js +869 -0
  24. package/lib/text-diff.js +303 -303
  25. package/lib/workflow-engine.js +340 -340
  26. package/package.json +74 -70
  27. package/res/json5.min.js +1 -1
  28. package/res/vue.global.prod.js +13 -0
  29. package/web-ui/app.js +530 -397
  30. package/web-ui/index.html +33 -30
  31. package/web-ui/logic.agents-diff.mjs +386 -386
  32. package/web-ui/logic.claude.mjs +168 -108
  33. package/web-ui/logic.mjs +5 -5
  34. package/web-ui/logic.runtime.mjs +124 -124
  35. package/web-ui/logic.sessions.mjs +581 -263
  36. package/web-ui/modules/api.mjs +90 -69
  37. package/web-ui/modules/app.computed.dashboard.mjs +113 -113
  38. package/web-ui/modules/app.computed.index.mjs +15 -13
  39. package/web-ui/modules/app.computed.main-tabs.mjs +195 -0
  40. package/web-ui/modules/app.computed.session.mjs +507 -141
  41. package/web-ui/modules/app.constants.mjs +15 -15
  42. package/web-ui/modules/app.methods.agents.mjs +493 -493
  43. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  44. package/web-ui/modules/app.methods.codex-config.mjs +640 -640
  45. package/web-ui/modules/app.methods.index.mjs +88 -86
  46. package/web-ui/modules/app.methods.install.mjs +149 -157
  47. package/web-ui/modules/app.methods.navigation.mjs +619 -478
  48. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -514
  49. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -337
  50. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -251
  51. package/web-ui/modules/app.methods.providers.mjs +363 -265
  52. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  53. package/web-ui/modules/app.methods.session-actions.mjs +520 -457
  54. package/web-ui/modules/app.methods.session-browser.mjs +626 -435
  55. package/web-ui/modules/app.methods.session-timeline.mjs +448 -441
  56. package/web-ui/modules/app.methods.session-trash.mjs +422 -419
  57. package/web-ui/modules/app.methods.startup-claude.mjs +412 -406
  58. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  59. package/web-ui/modules/config-mode.computed.mjs +126 -124
  60. package/web-ui/modules/skills.computed.mjs +107 -107
  61. package/web-ui/modules/skills.methods.mjs +481 -481
  62. package/web-ui/partials/index/layout-footer.html +13 -69
  63. package/web-ui/partials/index/layout-header.html +402 -337
  64. package/web-ui/partials/index/modal-config-template-agents.html +125 -125
  65. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  66. package/web-ui/partials/index/modal-health-check.html +72 -72
  67. package/web-ui/partials/index/modal-openclaw-config.html +280 -275
  68. package/web-ui/partials/index/modal-skills.html +184 -184
  69. package/web-ui/partials/index/modals-basic.html +156 -196
  70. package/web-ui/partials/index/panel-config-claude.html +126 -100
  71. package/web-ui/partials/index/panel-config-codex.html +237 -237
  72. package/web-ui/partials/index/panel-config-openclaw.html +78 -84
  73. package/web-ui/partials/index/panel-docs.html +130 -0
  74. package/web-ui/partials/index/panel-market.html +174 -174
  75. package/web-ui/partials/index/panel-orchestration.html +397 -0
  76. package/web-ui/partials/index/panel-sessions.html +292 -387
  77. package/web-ui/partials/index/panel-settings.html +190 -166
  78. package/web-ui/partials/index/panel-usage.html +213 -0
  79. package/web-ui/session-helpers.mjs +559 -362
  80. package/web-ui/source-bundle.cjs +233 -233
  81. package/web-ui/styles/base-theme.css +271 -373
  82. package/web-ui/styles/controls-forms.css +360 -354
  83. package/web-ui/styles/docs-panel.css +182 -0
  84. package/web-ui/styles/feedback.css +108 -108
  85. package/web-ui/styles/health-check-dialog.css +144 -144
  86. package/web-ui/styles/layout-shell.css +376 -330
  87. package/web-ui/styles/modals-core.css +464 -449
  88. package/web-ui/styles/navigation-panels.css +348 -381
  89. package/web-ui/styles/openclaw-structured.css +266 -266
  90. package/web-ui/styles/responsive.css +450 -416
  91. package/web-ui/styles/sessions-list.css +400 -414
  92. package/web-ui/styles/sessions-preview.css +411 -405
  93. package/web-ui/styles/sessions-toolbar-trash.css +243 -243
  94. package/web-ui/styles/sessions-usage.css +628 -276
  95. package/web-ui/styles/skills-list.css +296 -298
  96. package/web-ui/styles/skills-market.css +335 -335
  97. package/web-ui/styles/task-orchestration.css +776 -0
  98. package/web-ui/styles/titles-cards.css +408 -407
  99. package/web-ui/styles.css +18 -16
  100. package/web-ui.html +17 -17
  101. package/res/screenshot.png +0 -0
  102. package/res/vue.global.js +0 -18552
@@ -1,514 +1,814 @@
1
- export function createOpenclawCoreMethods() {
2
- return {
3
- getOpenclawParser() {
4
- const globalWindow = typeof window !== 'undefined' ? window : null;
5
- if (globalWindow && globalWindow.JSON5
6
- && typeof globalWindow.JSON5.parse === 'function'
7
- && typeof globalWindow.JSON5.stringify === 'function') {
8
- return {
9
- parse: globalWindow.JSON5.parse,
10
- stringify: globalWindow.JSON5.stringify
11
- };
12
- }
13
- return {
14
- parse: JSON.parse,
15
- stringify: JSON.stringify
16
- };
17
- },
18
-
19
- parseOpenclawContent(content, options = {}) {
20
- const allowEmpty = !!options.allowEmpty;
21
- const raw = typeof content === 'string' ? content.trim() : '';
22
- if (!raw) {
23
- if (allowEmpty) {
24
- return { ok: true, data: {} };
25
- }
26
- return { ok: false, error: '配置内容为空' };
27
- }
28
- try {
29
- const parser = this.getOpenclawParser();
30
- const data = parser.parse(raw);
31
- if (!data || typeof data !== 'object' || Array.isArray(data)) {
32
- return { ok: false, error: '配置格式错误(根节点必须是对象)' };
33
- }
34
- return { ok: true, data };
35
- } catch (e) {
36
- return { ok: false, error: e.message || '解析失败' };
37
- }
38
- },
39
-
40
- stringifyOpenclawConfig(data) {
41
- const parser = this.getOpenclawParser();
42
- try {
43
- return parser.stringify(data, null, 2);
44
- } catch (e) {
45
- return JSON.stringify(data, null, 2);
46
- }
47
- },
48
-
49
- resetOpenclawStructured() {
50
- this.openclawStructured = {
51
- agentPrimary: '',
52
- agentFallbacks: [''],
53
- workspace: '',
54
- timeout: '',
55
- contextTokens: '',
56
- maxConcurrent: '',
57
- envItems: [{ key: '', value: '', show: false }],
58
- toolsProfile: 'default',
59
- toolsAllow: [''],
60
- toolsDeny: ['']
61
- };
62
- this.openclawAgentsList = [];
63
- this.openclawProviders = [];
64
- this.openclawMissingProviders = [];
65
- },
66
-
67
- getOpenclawQuickDefaults() {
68
- return {
69
- providerName: '',
70
- baseUrl: '',
71
- apiKey: '',
72
- apiType: 'openai-responses',
73
- modelId: '',
74
- modelName: '',
75
- contextWindow: '',
76
- maxTokens: '',
77
- setPrimary: true,
78
- overrideProvider: true,
79
- overrideModels: true,
80
- showKey: false
81
- };
82
- },
83
-
84
- resetOpenclawQuick() {
85
- this.openclawQuick = this.getOpenclawQuickDefaults();
86
- },
87
-
88
- toggleOpenclawQuickKey() {
89
- this.openclawQuick.showKey = !this.openclawQuick.showKey;
90
- },
91
-
92
- fillOpenclawQuickFromConfig(config) {
93
- const defaults = this.getOpenclawQuickDefaults();
94
- if (!config || typeof config !== 'object' || Array.isArray(config)) {
95
- this.openclawQuick = defaults;
96
- return;
97
- }
98
-
99
- const agentDefaults = config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
100
- && config.agents.defaults && typeof config.agents.defaults === 'object' && !Array.isArray(config.agents.defaults)
101
- ? config.agents.defaults
102
- : {};
103
- const modelConfig = agentDefaults.model;
104
- const legacyAgent = config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
105
- ? config.agent
106
- : {};
107
-
108
- let primaryRef = '';
109
- if (modelConfig && typeof modelConfig === 'object' && !Array.isArray(modelConfig) && typeof modelConfig.primary === 'string') {
110
- primaryRef = modelConfig.primary;
111
- } else if (typeof modelConfig === 'string') {
112
- primaryRef = modelConfig;
113
- }
114
- if (!primaryRef) {
115
- if (typeof legacyAgent.model === 'string') {
116
- primaryRef = legacyAgent.model;
117
- } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && typeof legacyAgent.model.primary === 'string') {
118
- primaryRef = legacyAgent.model.primary;
119
- }
120
- }
121
-
122
- let providerName = '';
123
- let modelId = '';
124
- if (primaryRef) {
125
- const parts = primaryRef.split('/');
126
- if (parts.length >= 2) {
127
- providerName = parts.shift().trim();
128
- modelId = parts.join('/').trim();
129
- }
130
- }
131
-
132
- const providers = config.models && typeof config.models === 'object' && !Array.isArray(config.models)
133
- && config.models.providers && typeof config.models.providers === 'object' && !Array.isArray(config.models.providers)
134
- ? config.models.providers
135
- : null;
136
- let providerConfig = providerName && providers ? providers[providerName] : null;
137
- if (!providerName && providers) {
138
- const providerKeys = Object.keys(providers);
139
- if (providerKeys.length === 1) {
140
- providerName = providerKeys[0];
141
- providerConfig = providers[providerName];
142
- }
143
- }
144
-
145
- let modelEntry = null;
146
- if (providerConfig && typeof providerConfig === 'object' && Array.isArray(providerConfig.models)) {
147
- if (modelId) {
148
- modelEntry = providerConfig.models.find(item => item && item.id === modelId);
149
- }
150
- if (!modelEntry && providerConfig.models.length === 1) {
151
- modelEntry = providerConfig.models[0];
152
- if (!modelId && modelEntry && typeof modelEntry.id === 'string') {
153
- modelId = modelEntry.id;
154
- }
155
- }
156
- }
157
-
158
- const baseUrl = providerConfig && typeof providerConfig === 'object' && typeof providerConfig.baseUrl === 'string'
159
- ? providerConfig.baseUrl
160
- : '';
161
- const apiKey = providerConfig && typeof providerConfig === 'object' && typeof providerConfig.apiKey === 'string'
162
- ? providerConfig.apiKey
163
- : '';
164
- const apiType = providerConfig && typeof providerConfig === 'object' && typeof providerConfig.api === 'string'
165
- ? providerConfig.api
166
- : defaults.apiType;
167
-
168
- this.openclawQuick = {
169
- ...defaults,
170
- providerName,
171
- baseUrl,
172
- apiKey,
173
- apiType,
174
- modelId: modelId || '',
175
- modelName: modelEntry && typeof modelEntry.name === 'string' ? modelEntry.name : '',
176
- contextWindow: modelEntry && typeof modelEntry.contextWindow === 'number'
177
- ? String(modelEntry.contextWindow)
178
- : '',
179
- maxTokens: modelEntry && typeof modelEntry.maxTokens === 'number'
180
- ? String(modelEntry.maxTokens)
181
- : ''
182
- };
183
- },
184
-
185
- syncOpenclawQuickFromText(options = {}) {
186
- const silent = !!options.silent;
187
- const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
188
- if (!parsed.ok) {
189
- this.resetOpenclawQuick();
190
- if (!silent) {
191
- this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
192
- }
193
- return false;
194
- }
195
- this.fillOpenclawQuickFromConfig(parsed.data);
196
- if (!silent) {
197
- this.showMessage('已读取配置', 'success');
198
- }
199
- return true;
200
- },
201
-
202
- mergeOpenclawModelEntry(existing, incoming, overwrite = false) {
203
- if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
204
- return { ...incoming };
205
- }
206
- if (overwrite) {
207
- return { ...incoming };
208
- }
209
- const merged = { ...existing };
210
- for (const [key, value] of Object.entries(incoming || {})) {
211
- if (merged[key] === undefined || merged[key] === null || merged[key] === '') {
212
- merged[key] = value;
213
- }
214
- }
215
- return merged;
216
- },
217
-
218
- fillOpenclawStructured(config) {
219
- const defaults = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
220
- && config.agents.defaults && typeof config.agents.defaults === 'object' && !Array.isArray(config.agents.defaults)
221
- ? config.agents.defaults
222
- : {};
223
- const model = defaults.model && typeof defaults.model === 'object' && !Array.isArray(defaults.model)
224
- ? defaults.model
225
- : {};
226
- const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
227
- ? config.agent
228
- : {};
229
- const fallbackSource = Array.isArray(model.fallbacks)
230
- ? model.fallbacks
231
- : (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model) && Array.isArray(legacyAgent.model.fallbacks)
232
- ? legacyAgent.model.fallbacks
233
- : []);
234
- const fallbackList = fallbackSource
235
- .filter(item => typeof item === 'string' && item.trim())
236
- .map(item => item.trim());
237
- const env = config && config.env && typeof config.env === 'object' && !Array.isArray(config.env)
238
- ? config.env
239
- : {};
240
- const envItems = Object.entries(env).map(([key, value]) => ({
241
- key,
242
- value: value == null ? '' : String(value),
243
- show: false
244
- }));
245
- const tools = config && config.tools && typeof config.tools === 'object' && !Array.isArray(config.tools)
246
- ? config.tools
247
- : {};
248
-
249
- let primary = typeof model.primary === 'string' ? model.primary : '';
250
- if (!primary) {
251
- if (typeof legacyAgent.model === 'string') {
252
- primary = legacyAgent.model;
253
- } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && typeof legacyAgent.model.primary === 'string') {
254
- primary = legacyAgent.model.primary;
255
- }
256
- }
257
-
258
- this.openclawStructured = {
259
- agentPrimary: primary,
260
- agentFallbacks: fallbackList.length ? fallbackList : [''],
261
- workspace: typeof defaults.workspace === 'string' ? defaults.workspace : '',
262
- timeout: typeof defaults.timeout === 'number' && Number.isFinite(defaults.timeout)
263
- ? String(defaults.timeout)
264
- : '',
265
- contextTokens: typeof defaults.contextTokens === 'number' && Number.isFinite(defaults.contextTokens)
266
- ? String(defaults.contextTokens)
267
- : '',
268
- maxConcurrent: typeof defaults.maxConcurrent === 'number' && Number.isFinite(defaults.maxConcurrent)
269
- ? String(defaults.maxConcurrent)
270
- : '',
271
- envItems: envItems.length ? envItems : [{ key: '', value: '', show: false }],
272
- toolsProfile: typeof tools.profile === 'string' && tools.profile.trim() ? tools.profile : 'default',
273
- toolsAllow: Array.isArray(tools.allow) && tools.allow.length
274
- ? tools.allow.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
275
- : [''],
276
- toolsDeny: Array.isArray(tools.deny) && tools.deny.length
277
- ? tools.deny.filter(item => typeof item === 'string' && item.trim()).map(item => item.trim())
278
- : ['']
279
- };
280
- },
281
-
282
- syncOpenclawStructuredFromText(options = {}) {
283
- const silent = !!options.silent;
284
- const parsed = this.parseOpenclawContent(this.openclawEditing.content, { allowEmpty: true });
285
- if (!parsed.ok) {
286
- this.resetOpenclawStructured();
287
- this.resetOpenclawQuick();
288
- if (!silent) {
289
- this.showMessage('解析 OpenClaw 配置失败: ' + parsed.error, 'error');
290
- }
291
- return false;
292
- }
293
- this.fillOpenclawStructured(parsed.data);
294
- this.fillOpenclawQuickFromConfig(parsed.data);
295
- this.refreshOpenclawProviders(parsed.data);
296
- this.refreshOpenclawAgentsList(parsed.data);
297
- if (!silent) {
298
- this.showMessage('已刷新配置', 'success');
299
- }
300
- return true;
301
- },
302
-
303
- getOpenclawActiveProviders(config) {
304
- const active = new Set();
305
- const addProvider = (ref) => {
306
- if (typeof ref !== 'string') return;
307
- const text = ref.trim();
308
- if (!text) return;
309
- const parts = text.split('/');
310
- if (parts.length < 2) return;
311
- const provider = parts[0].trim();
312
- if (provider) active.add(provider);
313
- };
314
- const defaults = config && config.agents && config.agents.defaults
315
- ? config.agents.defaults
316
- : {};
317
- const model = defaults && defaults.model;
318
- if (model && typeof model === 'object' && !Array.isArray(model)) {
319
- addProvider(model.primary);
320
- if (Array.isArray(model.fallbacks)) {
321
- for (const item of model.fallbacks) {
322
- addProvider(item);
323
- }
324
- }
325
- } else if (typeof model === 'string') {
326
- addProvider(model);
327
- }
328
- const legacyAgent = config && config.agent && typeof config.agent === 'object' && !Array.isArray(config.agent)
329
- ? config.agent
330
- : {};
331
- if (typeof legacyAgent.model === 'string') {
332
- addProvider(legacyAgent.model);
333
- } else if (legacyAgent.model && typeof legacyAgent.model === 'object' && !Array.isArray(legacyAgent.model)) {
334
- addProvider(legacyAgent.model.primary);
335
- if (Array.isArray(legacyAgent.model.fallbacks)) {
336
- for (const item of legacyAgent.model.fallbacks) {
337
- addProvider(item);
338
- }
339
- }
340
- }
341
- const modelsDefaults = config && config.models && config.models.defaults
342
- ? config.models.defaults
343
- : {};
344
- if (modelsDefaults && typeof modelsDefaults.provider === 'string' && modelsDefaults.provider.trim()) {
345
- active.add(modelsDefaults.provider.trim());
346
- }
347
- if (modelsDefaults && typeof modelsDefaults.model === 'string') {
348
- addProvider(modelsDefaults.model);
349
- }
350
- return active;
351
- },
352
-
353
- maskProviderValue(value) {
354
- const text = value == null ? '' : String(value);
355
- if (!text) return '****';
356
- if (text.length <= 6) return '****';
357
- return `${text.slice(0, 3)}****${text.slice(-3)}`;
358
- },
359
-
360
- formatProviderValue(key, value) {
361
- if (typeof value === 'undefined' || value === null) {
362
- return '';
363
- }
364
- let text = '';
365
- if (typeof value === 'string') {
366
- text = value;
367
- } else if (typeof value === 'number' || typeof value === 'boolean') {
368
- text = String(value);
369
- } else {
370
- try {
371
- text = JSON.stringify(value);
372
- } catch (_) {
373
- text = String(value);
374
- }
375
- }
376
- if (!text) return '';
377
- if (/key|token|secret|password/i.test(key)) {
378
- return this.maskProviderValue(text);
379
- }
380
- if (text.length > 160) {
381
- return `${text.slice(0, 157)}...`;
382
- }
383
- return text;
384
- },
385
-
386
- collectOpenclawProviders(source, providerMap, activeProviders, entries) {
387
- if (!providerMap || typeof providerMap !== 'object' || Array.isArray(providerMap)) {
388
- return;
389
- }
390
- const keys = Object.keys(providerMap).sort();
391
- for (const key of keys) {
392
- const value = providerMap[key];
393
- const fields = [];
394
- if (value && typeof value === 'object' && !Array.isArray(value)) {
395
- const fieldKeys = Object.keys(value).sort();
396
- for (const fieldKey of fieldKeys) {
397
- const fieldValue = this.formatProviderValue(fieldKey, value[fieldKey]);
398
- if (fieldValue === '') continue;
399
- fields.push({ key: fieldKey, value: fieldValue });
400
- }
401
- } else {
402
- const fieldValue = this.formatProviderValue('value', value);
403
- if (fieldValue !== '') {
404
- fields.push({ key: 'value', value: fieldValue });
405
- }
406
- }
407
- entries.push({
408
- key,
409
- source,
410
- fields,
411
- isActive: activeProviders.has(key)
412
- });
413
- }
414
- },
415
-
416
- refreshOpenclawProviders(config) {
417
- const activeProviders = this.getOpenclawActiveProviders(config || {});
418
- const entries = [];
419
- const modelsProviders = config && config.models ? config.models.providers : null;
420
- const rootProviders = config && config.providers ? config.providers : null;
421
- this.collectOpenclawProviders('models.providers', modelsProviders, activeProviders, entries);
422
- this.collectOpenclawProviders('providers', rootProviders, activeProviders, entries);
423
- const existing = new Set(entries.map(item => item.key));
424
- const missing = [];
425
- for (const provider of activeProviders) {
426
- if (!existing.has(provider)) {
427
- missing.push(provider);
428
- }
429
- }
430
- this.openclawProviders = entries;
431
- this.openclawMissingProviders = missing;
432
- },
433
-
434
- refreshOpenclawAgentsList(config) {
435
- const list = config && config.agents && typeof config.agents === 'object' && !Array.isArray(config.agents)
436
- ? config.agents.list
437
- : null;
438
- if (!Array.isArray(list)) {
439
- this.openclawAgentsList = [];
440
- return;
441
- }
442
- const entries = [];
443
- list.forEach((item, index) => {
444
- if (!item || typeof item !== 'object') return;
445
- const id = typeof item.id === 'string' && item.id.trim() ? item.id.trim() : `agent-${index + 1}`;
446
- const identity = item.identity && typeof item.identity === 'object' && !Array.isArray(item.identity)
447
- ? item.identity
448
- : {};
449
- const name = typeof identity.name === 'string' && identity.name.trim()
450
- ? identity.name.trim()
451
- : id;
452
- entries.push({
453
- key: `${id}-${index}`,
454
- id,
455
- name,
456
- theme: typeof identity.theme === 'string' ? identity.theme : '',
457
- emoji: typeof identity.emoji === 'string' ? identity.emoji : '',
458
- avatar: typeof identity.avatar === 'string' ? identity.avatar : ''
459
- });
460
- });
461
- this.openclawAgentsList = entries;
462
- },
463
-
464
- normalizeStringList(list) {
465
- if (!Array.isArray(list)) return [];
466
- const result = [];
467
- const seen = new Set();
468
- for (const item of list) {
469
- const value = typeof item === 'string' ? item.trim() : String(item || '').trim();
470
- if (!value) continue;
471
- const key = value;
472
- if (seen.has(key)) continue;
473
- seen.add(key);
474
- result.push(value);
475
- }
476
- return result;
477
- },
478
-
479
- normalizeEnvItems(items) {
480
- if (!Array.isArray(items)) {
481
- return { ok: true, items: {} };
482
- }
483
- const output = {};
484
- const seen = new Set();
485
- for (const item of items) {
486
- const key = item && typeof item.key === 'string' ? item.key.trim() : '';
487
- if (!key) continue;
488
- if (seen.has(key)) {
489
- return { ok: false, error: `环境变量重复: ${key}` };
490
- }
491
- seen.add(key);
492
- const value = item && typeof item.value !== 'undefined' ? String(item.value) : '';
493
- output[key] = value;
494
- }
495
- return { ok: true, items: output };
496
- },
497
-
498
- parseOptionalNumber(value, label) {
499
- const text = typeof value === 'string'
500
- ? value.trim()
501
- : typeof value === 'number'
502
- ? String(value).trim()
503
- : String(value || '').trim();
504
- if (!text) {
505
- return { ok: true, value: null };
506
- }
507
- const num = Number(text);
508
- if (!Number.isFinite(num) || num < 0) {
509
- return { ok: false, error: `${label} 请输入有效数字` };
510
- }
511
- return { ok: true, value: num };
512
- }
513
- };
514
- }
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
+ }