codexmate 0.0.21 → 0.0.23

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 (115) hide show
  1. package/README.md +390 -284
  2. package/README.zh.md +322 -0
  3. package/cli/agents-files.js +224 -162
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +359 -359
  6. package/cli/builtin-proxy.js +1044 -580
  7. package/cli/claude-proxy.js +998 -998
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/openai-bridge.js +950 -0
  11. package/cli/openclaw-config.js +629 -629
  12. package/cli/session-usage.concurrent.js +28 -0
  13. package/cli/session-usage.js +112 -0
  14. package/cli/session-usage.models.js +176 -0
  15. package/cli/skills.js +1141 -1141
  16. package/cli/zip-commands.js +510 -510
  17. package/cli.js +13214 -13129
  18. package/lib/cli-file-utils.js +151 -151
  19. package/lib/cli-models-utils.js +419 -419
  20. package/lib/cli-network-utils.js +164 -164
  21. package/lib/cli-path-utils.js +69 -69
  22. package/lib/cli-session-utils.js +121 -121
  23. package/lib/cli-sessions.js +386 -386
  24. package/lib/cli-utils.js +155 -155
  25. package/lib/download-artifacts.js +77 -77
  26. package/lib/mcp-stdio.js +440 -440
  27. package/lib/task-orchestrator.js +869 -869
  28. package/lib/text-diff.js +303 -303
  29. package/lib/workflow-engine.js +340 -340
  30. package/package.json +74 -74
  31. package/res/json5.min.js +1 -1
  32. package/res/logo.png +0 -0
  33. package/res/vue.global.prod.js +13 -13
  34. package/web-ui/app.js +626 -530
  35. package/web-ui/index.html +34 -33
  36. package/web-ui/logic.agents-diff.mjs +386 -386
  37. package/web-ui/logic.claude.mjs +168 -168
  38. package/web-ui/logic.mjs +5 -5
  39. package/web-ui/logic.runtime.mjs +128 -124
  40. package/web-ui/logic.sessions.mjs +614 -581
  41. package/web-ui/modules/api.mjs +90 -90
  42. package/web-ui/modules/app.computed.dashboard.mjs +126 -113
  43. package/web-ui/modules/app.computed.index.mjs +17 -15
  44. package/web-ui/modules/app.computed.main-tabs.mjs +202 -195
  45. package/web-ui/modules/app.computed.session.mjs +653 -507
  46. package/web-ui/modules/app.constants.mjs +15 -15
  47. package/web-ui/modules/app.methods.agents.mjs +544 -493
  48. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  49. package/web-ui/modules/app.methods.codex-config.mjs +795 -640
  50. package/web-ui/modules/app.methods.index.mjs +92 -88
  51. package/web-ui/modules/app.methods.install.mjs +177 -149
  52. package/web-ui/modules/app.methods.navigation.mjs +662 -619
  53. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  54. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  55. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  56. package/web-ui/modules/app.methods.providers.mjs +404 -363
  57. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  58. package/web-ui/modules/app.methods.session-actions.mjs +537 -520
  59. package/web-ui/modules/app.methods.session-browser.mjs +691 -626
  60. package/web-ui/modules/app.methods.session-timeline.mjs +448 -448
  61. package/web-ui/modules/app.methods.session-trash.mjs +422 -422
  62. package/web-ui/modules/app.methods.startup-claude.mjs +417 -412
  63. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -471
  64. package/web-ui/modules/config-mode.computed.mjs +126 -126
  65. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  66. package/web-ui/modules/i18n.mjs +1823 -0
  67. package/web-ui/modules/plugins.computed.mjs +3 -0
  68. package/web-ui/modules/plugins.methods.mjs +3 -0
  69. package/web-ui/modules/plugins.storage.mjs +11 -0
  70. package/web-ui/modules/sessions-filters-url.mjs +85 -0
  71. package/web-ui/modules/skills.computed.mjs +107 -107
  72. package/web-ui/modules/skills.methods.mjs +481 -481
  73. package/web-ui/partials/index/layout-footer.html +13 -13
  74. package/web-ui/partials/index/layout-header.html +461 -402
  75. package/web-ui/partials/index/modal-config-template-agents.html +175 -125
  76. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  77. package/web-ui/partials/index/modal-health-check.html +72 -72
  78. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  79. package/web-ui/partials/index/modal-skills.html +200 -184
  80. package/web-ui/partials/index/modals-basic.html +165 -156
  81. package/web-ui/partials/index/panel-config-claude.html +159 -126
  82. package/web-ui/partials/index/panel-config-codex.html +255 -237
  83. package/web-ui/partials/index/panel-config-openclaw.html +78 -78
  84. package/web-ui/partials/index/panel-docs.html +147 -130
  85. package/web-ui/partials/index/panel-market.html +174 -174
  86. package/web-ui/partials/index/panel-orchestration.html +388 -397
  87. package/web-ui/partials/index/panel-plugins.html +273 -0
  88. package/web-ui/partials/index/panel-sessions.html +298 -292
  89. package/web-ui/partials/index/panel-settings.html +258 -190
  90. package/web-ui/partials/index/panel-usage.html +353 -213
  91. package/web-ui/session-helpers.mjs +573 -559
  92. package/web-ui/source-bundle.cjs +233 -233
  93. package/web-ui/styles/base-theme.css +264 -271
  94. package/web-ui/styles/controls-forms.css +369 -360
  95. package/web-ui/styles/docs-panel.css +247 -182
  96. package/web-ui/styles/feedback.css +108 -108
  97. package/web-ui/styles/health-check-dialog.css +144 -144
  98. package/web-ui/styles/layout-shell.css +602 -376
  99. package/web-ui/styles/modals-core.css +464 -464
  100. package/web-ui/styles/navigation-panels.css +390 -348
  101. package/web-ui/styles/openclaw-structured.css +266 -266
  102. package/web-ui/styles/plugins-panel.css +523 -0
  103. package/web-ui/styles/responsive.css +456 -450
  104. package/web-ui/styles/sessions-list.css +400 -400
  105. package/web-ui/styles/sessions-preview.css +411 -411
  106. package/web-ui/styles/sessions-toolbar-trash.css +268 -243
  107. package/web-ui/styles/sessions-usage.css +879 -628
  108. package/web-ui/styles/settings-panel.css +166 -0
  109. package/web-ui/styles/skills-list.css +303 -296
  110. package/web-ui/styles/skills-market.css +406 -335
  111. package/web-ui/styles/task-orchestration.css +822 -776
  112. package/web-ui/styles/titles-cards.css +408 -408
  113. package/web-ui/styles.css +20 -18
  114. package/web-ui.html +17 -17
  115. package/README.en.md +0 -349
@@ -1,629 +1,629 @@
1
- const JSON5 = require('json5');
2
-
3
- function createOpenclawConfigController(deps = {}) {
4
- const {
5
- fs,
6
- path,
7
- os,
8
- ensureDir,
9
- readJsonObjectFromFile,
10
- writeJsonAtomic,
11
- backupFileIfNeededOnce,
12
- stripUtf8Bom,
13
- detectLineEnding,
14
- normalizeLineEnding,
15
- ensureUtf8Bom,
16
- isPlainObject,
17
- resolveHomePath,
18
- readAgentsFile,
19
- applyAgentsFile,
20
- OPENCLAW_CONFIG_FILE,
21
- OPENCLAW_WORKSPACE_DIR,
22
- OPENCLAW_DIR,
23
- OPENCLAW_DEFAULT_AGENT_ID,
24
- OPENCLAW_AUTH_PROFILES_FILE_NAME,
25
- OPENCLAW_AUTH_STATE_FILE_NAME,
26
- AGENTS_FILE_NAME
27
- } = deps;
28
-
29
- if (!fs) throw new Error('createOpenclawConfigController 缺少 fs');
30
- if (!path) throw new Error('createOpenclawConfigController 缺少 path');
31
- if (!os) throw new Error('createOpenclawConfigController 缺少 os');
32
- if (typeof ensureDir !== 'function') throw new Error('createOpenclawConfigController 缺少 ensureDir');
33
- if (typeof readJsonObjectFromFile !== 'function') throw new Error('createOpenclawConfigController 缺少 readJsonObjectFromFile');
34
- if (typeof writeJsonAtomic !== 'function') throw new Error('createOpenclawConfigController 缺少 writeJsonAtomic');
35
- if (typeof backupFileIfNeededOnce !== 'function') throw new Error('createOpenclawConfigController 缺少 backupFileIfNeededOnce');
36
- if (typeof stripUtf8Bom !== 'function') throw new Error('createOpenclawConfigController 缺少 stripUtf8Bom');
37
- if (typeof detectLineEnding !== 'function') throw new Error('createOpenclawConfigController 缺少 detectLineEnding');
38
- if (typeof normalizeLineEnding !== 'function') throw new Error('createOpenclawConfigController 缺少 normalizeLineEnding');
39
- if (typeof ensureUtf8Bom !== 'function') throw new Error('createOpenclawConfigController 缺少 ensureUtf8Bom');
40
- if (typeof isPlainObject !== 'function') throw new Error('createOpenclawConfigController 缺少 isPlainObject');
41
- if (typeof resolveHomePath !== 'function') throw new Error('createOpenclawConfigController 缺少 resolveHomePath');
42
- if (typeof readAgentsFile !== 'function') throw new Error('createOpenclawConfigController 缺少 readAgentsFile');
43
- if (typeof applyAgentsFile !== 'function') throw new Error('createOpenclawConfigController 缺少 applyAgentsFile');
44
- if (!OPENCLAW_CONFIG_FILE) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_CONFIG_FILE');
45
- if (!OPENCLAW_WORKSPACE_DIR) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_WORKSPACE_DIR');
46
- if (!OPENCLAW_DIR) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_DIR');
47
- if (!OPENCLAW_DEFAULT_AGENT_ID) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_DEFAULT_AGENT_ID');
48
- if (!OPENCLAW_AUTH_PROFILES_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_AUTH_PROFILES_FILE_NAME');
49
- if (!OPENCLAW_AUTH_STATE_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_AUTH_STATE_FILE_NAME');
50
- if (!AGENTS_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 AGENTS_FILE_NAME');
51
-
52
- function resolveOpenclawWorkspaceDir(config) {
53
- const workspace = config
54
- && config.agents
55
- && config.agents.defaults
56
- && typeof config.agents.defaults.workspace === 'string'
57
- ? config.agents.defaults.workspace
58
- : '';
59
- const resolved = resolveHomePath(workspace);
60
- if (!resolved) {
61
- return OPENCLAW_WORKSPACE_DIR;
62
- }
63
- if (path.isAbsolute(resolved)) {
64
- return resolved;
65
- }
66
- return path.join(OPENCLAW_DIR, resolved);
67
- }
68
-
69
- function normalizeOpenclawWorkspaceFileName(input) {
70
- const raw = typeof input === 'string' ? input.trim() : '';
71
- if (!raw) {
72
- return { error: '文件名不能为空' };
73
- }
74
- if (raw.includes('\0')) {
75
- return { error: '文件名非法' };
76
- }
77
- if (raw.includes('/') || raw.includes('\\') || raw.includes('..')) {
78
- return { error: '文件名非法' };
79
- }
80
- const baseName = path.basename(raw);
81
- if (baseName !== raw) {
82
- return { error: '文件名非法' };
83
- }
84
- if (!raw.toLowerCase().endsWith('.md')) {
85
- return { error: '仅支持 .md 文件' };
86
- }
87
- return { ok: true, name: raw };
88
- }
89
-
90
- function normalizeOpenclawProviderId(provider) {
91
- const normalized = typeof provider === 'string' ? provider.trim().toLowerCase() : '';
92
- if (!normalized) return '';
93
- if (normalized === 'modelstudio' || normalized === 'qwencloud') {
94
- return 'qwen';
95
- }
96
- if (normalized === 'z.ai' || normalized === 'z-ai') {
97
- return 'zai';
98
- }
99
- if (normalized === 'opencode-zen') {
100
- return 'opencode';
101
- }
102
- if (normalized === 'opencode-go-auth') {
103
- return 'opencode-go';
104
- }
105
- if (normalized === 'kimi' || normalized === 'kimi-code' || normalized === 'kimi-coding') {
106
- return 'kimi';
107
- }
108
- if (normalized === 'bedrock' || normalized === 'aws-bedrock') {
109
- return 'amazon-bedrock';
110
- }
111
- if (normalized === 'bytedance' || normalized === 'doubao') {
112
- return 'volcengine';
113
- }
114
- if (normalized === 'volcengine-plan') {
115
- return 'volcengine';
116
- }
117
- if (normalized === 'byteplus-plan') {
118
- return 'byteplus';
119
- }
120
- return normalized;
121
- }
122
-
123
- function findNormalizedOpenclawProviderValue(entries, provider) {
124
- if (!isPlainObject(entries)) {
125
- return undefined;
126
- }
127
- const providerKey = normalizeOpenclawProviderId(provider);
128
- if (!providerKey) {
129
- return undefined;
130
- }
131
- for (const [key, value] of Object.entries(entries)) {
132
- if (normalizeOpenclawProviderId(key) === providerKey) {
133
- return value;
134
- }
135
- }
136
- return undefined;
137
- }
138
-
139
- function resolveOpenclawStateDir() {
140
- const override = typeof process.env.OPENCLAW_STATE_DIR === 'string'
141
- ? process.env.OPENCLAW_STATE_DIR.trim()
142
- : '';
143
- return override ? resolveHomePath(override) : OPENCLAW_DIR;
144
- }
145
-
146
- function resolveOpenclawAgentDir() {
147
- const override = [process.env.OPENCLAW_AGENT_DIR, process.env.PI_CODING_AGENT_DIR]
148
- .find(value => typeof value === 'string' && value.trim());
149
- if (override) {
150
- return resolveHomePath(override.trim());
151
- }
152
- return path.join(resolveOpenclawStateDir(), 'agents', OPENCLAW_DEFAULT_AGENT_ID, 'agent');
153
- }
154
-
155
- function buildOpenclawAuthProfileDisplay(profileId, credential) {
156
- const type = typeof credential.type === 'string' && credential.type.trim()
157
- ? credential.type.trim()
158
- : 'unknown';
159
- const parts = [`AuthProfile(${type}:${profileId})`];
160
- const label = typeof credential.displayName === 'string' && credential.displayName.trim()
161
- ? credential.displayName.trim()
162
- : (typeof credential.email === 'string' && credential.email.trim() ? credential.email.trim() : '');
163
- if (label) {
164
- parts.push(label);
165
- }
166
- return parts.join(' · ');
167
- }
168
-
169
- function resolveOpenclawAuthProfileEditableValue(credential) {
170
- if (!isPlainObject(credential)) {
171
- return {
172
- resolvedValue: '',
173
- resolvedField: '',
174
- editable: false,
175
- valueKind: 'missing'
176
- };
177
- }
178
- if (credential.type === 'api_key' && typeof credential.key === 'string' && credential.key.trim()) {
179
- return {
180
- resolvedValue: credential.key.trim(),
181
- resolvedField: 'key',
182
- editable: true,
183
- valueKind: 'api_key'
184
- };
185
- }
186
- if (credential.type === 'token' && typeof credential.token === 'string' && credential.token.trim()) {
187
- return {
188
- resolvedValue: credential.token.trim(),
189
- resolvedField: 'token',
190
- editable: true,
191
- valueKind: 'token'
192
- };
193
- }
194
- if (credential.type === 'oauth' && typeof credential.access === 'string' && credential.access.trim()) {
195
- return {
196
- resolvedValue: credential.access.trim(),
197
- resolvedField: 'access',
198
- editable: true,
199
- valueKind: 'oauth-access'
200
- };
201
- }
202
- return {
203
- resolvedValue: '',
204
- resolvedField: '',
205
- editable: false,
206
- valueKind: typeof credential.type === 'string' && credential.type.trim()
207
- ? credential.type.trim()
208
- : 'missing'
209
- };
210
- }
211
-
212
- function getOpenclawAuthProfileTypeRank(credential) {
213
- const type = typeof credential.type === 'string' ? credential.type.trim().toLowerCase() : '';
214
- if (type === 'oauth') return 0;
215
- if (type === 'token') return 1;
216
- if (type === 'api_key') return 2;
217
- return 3;
218
- }
219
-
220
- function readOpenclawAuthProfilesSummary() {
221
- const agentDir = resolveOpenclawAgentDir();
222
- const authStorePath = path.join(agentDir, OPENCLAW_AUTH_PROFILES_FILE_NAME);
223
- const authStatePath = path.join(agentDir, OPENCLAW_AUTH_STATE_FILE_NAME);
224
- const storeResult = readJsonObjectFromFile(authStorePath, { profiles: {} });
225
- const stateResult = readJsonObjectFromFile(authStatePath, {});
226
- const profiles = storeResult.ok && isPlainObject(storeResult.data) && isPlainObject(storeResult.data.profiles)
227
- ? storeResult.data.profiles
228
- : {};
229
- const state = stateResult.ok && isPlainObject(stateResult.data)
230
- ? stateResult.data
231
- : {};
232
-
233
- const grouped = new Map();
234
- for (const [profileId, credential] of Object.entries(profiles)) {
235
- if (!isPlainObject(credential)) continue;
236
- const provider = typeof credential.provider === 'string' ? credential.provider.trim() : '';
237
- const normalizedProvider = normalizeOpenclawProviderId(provider);
238
- if (!normalizedProvider) continue;
239
- if (!grouped.has(normalizedProvider)) {
240
- grouped.set(normalizedProvider, []);
241
- }
242
- grouped.get(normalizedProvider).push([profileId, credential]);
243
- }
244
-
245
- const providers = {};
246
- for (const [providerKey, entries] of grouped.entries()) {
247
- const explicitOrder = findNormalizedOpenclawProviderValue(state.order, providerKey);
248
- const lastGood = findNormalizedOpenclawProviderValue(state.lastGood, providerKey);
249
- let selectedEntry = null;
250
-
251
- if (typeof explicitOrder === 'string' && explicitOrder.trim()) {
252
- selectedEntry = entries.find(([profileId]) => profileId === explicitOrder.trim()) || null;
253
- }
254
- if (!selectedEntry && typeof lastGood === 'string' && lastGood.trim()) {
255
- selectedEntry = entries.find(([profileId]) => profileId === lastGood.trim()) || null;
256
- }
257
- if (!selectedEntry) {
258
- entries.sort((a, b) => {
259
- const rankDelta = getOpenclawAuthProfileTypeRank(a[1]) - getOpenclawAuthProfileTypeRank(b[1]);
260
- if (rankDelta !== 0) return rankDelta;
261
- return a[0].localeCompare(b[0]);
262
- });
263
- selectedEntry = entries[0] || null;
264
- }
265
- if (!selectedEntry) continue;
266
- const [profileId, credential] = selectedEntry;
267
- const resolvedValueMeta = resolveOpenclawAuthProfileEditableValue(credential);
268
- providers[providerKey] = {
269
- profileId,
270
- provider: typeof credential.provider === 'string' ? credential.provider : providerKey,
271
- normalizedProvider: providerKey,
272
- type: typeof credential.type === 'string' ? credential.type : '',
273
- displayName: typeof credential.displayName === 'string' ? credential.displayName : '',
274
- display: buildOpenclawAuthProfileDisplay(profileId, credential),
275
- email: typeof credential.email === 'string' ? credential.email : '',
276
- editable: !!resolvedValueMeta.editable,
277
- resolvedValue: resolvedValueMeta.resolvedValue,
278
- resolvedField: resolvedValueMeta.resolvedField,
279
- valueKind: resolvedValueMeta.valueKind
280
- };
281
- }
282
-
283
- return {
284
- authStorePath,
285
- authStatePath,
286
- providers
287
- };
288
- }
289
-
290
- function sanitizeOpenclawAuthProfilesForClient(providers) {
291
- const sanitized = {};
292
- for (const [providerKey, summary] of Object.entries(isPlainObject(providers) ? providers : {})) {
293
- if (!isPlainObject(summary)) {
294
- continue;
295
- }
296
- const normalized = { ...summary };
297
- delete normalized.resolvedValue;
298
- sanitized[providerKey] = normalized;
299
- }
300
- return sanitized;
301
- }
302
-
303
- function normalizeOpenclawAuthProfileUpdate(entry) {
304
- if (!isPlainObject(entry)) return null;
305
- const profileId = typeof entry.profileId === 'string' ? entry.profileId.trim() : '';
306
- const provider = typeof entry.provider === 'string' ? entry.provider.trim() : '';
307
- const field = typeof entry.field === 'string' ? entry.field.trim() : '';
308
- const value = typeof entry.value === 'string' ? entry.value.trim() : '';
309
- const allowedFields = new Set(['key', 'token', 'access']);
310
- if (!profileId || !provider || !allowedFields.has(field) || !value) {
311
- return null;
312
- }
313
- return { profileId, provider, field, value };
314
- }
315
-
316
- function applyOpenclawAuthProfileUpdates(params = {}) {
317
- const updates = Array.isArray(params.updates)
318
- ? params.updates.map(normalizeOpenclawAuthProfileUpdate).filter(Boolean)
319
- : [];
320
- if (!updates.length) {
321
- return { ok: true, applied: [] };
322
- }
323
-
324
- const authSummary = readOpenclawAuthProfilesSummary();
325
- const authStorePath = authSummary.authStorePath;
326
- const storeResult = readJsonObjectFromFile(authStorePath, { version: 1, profiles: {} });
327
- if (!storeResult.ok) {
328
- return { ok: false, error: storeResult.error || '读取 OpenClaw auth profile 失败' };
329
- }
330
- const store = isPlainObject(storeResult.data) ? storeResult.data : { version: 1, profiles: {} };
331
- const profiles = isPlainObject(store.profiles) ? { ...store.profiles } : {};
332
- const applied = [];
333
-
334
- for (const update of updates) {
335
- const existing = profiles[update.profileId];
336
- if (!isPlainObject(existing)) {
337
- return { ok: false, error: `未找到 OpenClaw 认证配置: ${update.profileId}` };
338
- }
339
- const existingProvider = typeof existing.provider === 'string' ? existing.provider.trim() : '';
340
- if (normalizeOpenclawProviderId(existingProvider) !== normalizeOpenclawProviderId(update.provider)) {
341
- return { ok: false, error: `认证配置与 provider 不匹配: ${update.profileId}` };
342
- }
343
-
344
- const next = { ...existing };
345
- next[update.field] = update.value;
346
- if (update.field === 'key') {
347
- next.type = 'api_key';
348
- delete next.keyRef;
349
- } else if (update.field === 'token') {
350
- next.type = 'token';
351
- delete next.tokenRef;
352
- } else if (update.field === 'access') {
353
- next.type = 'oauth';
354
- }
355
- profiles[update.profileId] = next;
356
- applied.push({
357
- profileId: update.profileId,
358
- provider: existingProvider || update.provider,
359
- field: update.field
360
- });
361
- }
362
-
363
- try {
364
- ensureDir(path.dirname(authStorePath));
365
- const backupPath = fs.existsSync(authStorePath) ? backupFileIfNeededOnce(authStorePath) : '';
366
- writeJsonAtomic(authStorePath, {
367
- ...store,
368
- version: Number(store.version) > 0 ? Number(store.version) : 1,
369
- profiles
370
- });
371
- return {
372
- ok: true,
373
- applied,
374
- authStorePath,
375
- backupPath
376
- };
377
- } catch (e) {
378
- return {
379
- ok: false,
380
- error: e && e.message ? e.message : '写入 OpenClaw auth profile 失败'
381
- };
382
- }
383
- }
384
-
385
- function readOpenclawConfigFile() {
386
- const filePath = OPENCLAW_CONFIG_FILE;
387
- const authProfilesByProvider = sanitizeOpenclawAuthProfilesForClient(
388
- readOpenclawAuthProfilesSummary().providers
389
- );
390
- if (!fs.existsSync(filePath)) {
391
- return {
392
- exists: false,
393
- path: filePath,
394
- content: '',
395
- lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
396
- authProfilesByProvider
397
- };
398
- }
399
-
400
- try {
401
- const raw = fs.readFileSync(filePath, 'utf-8');
402
- return {
403
- exists: true,
404
- path: filePath,
405
- content: stripUtf8Bom(raw),
406
- lineEnding: detectLineEnding(raw),
407
- authProfilesByProvider
408
- };
409
- } catch (e) {
410
- return { error: `读取 OpenClaw 配置失败: ${e.message}` };
411
- }
412
- }
413
-
414
- function parseOpenclawConfigText(content) {
415
- const raw = stripUtf8Bom(typeof content === 'string' ? content : '');
416
- if (!raw.trim()) {
417
- return { ok: false, error: 'OpenClaw 配置内容不能为空' };
418
- }
419
- try {
420
- const parsed = JSON5.parse(raw);
421
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
422
- return { ok: false, error: '配置格式错误(根节点必须是对象)' };
423
- }
424
- return { ok: true, data: parsed };
425
- } catch (e) {
426
- return { ok: false, error: `配置解析失败: ${e.message}` };
427
- }
428
- }
429
-
430
- function getOpenclawWorkspaceInfo() {
431
- const readResult = readOpenclawConfigFile();
432
- let workspaceDir = OPENCLAW_WORKSPACE_DIR;
433
- let configError = readResult.error || '';
434
- if (!configError && readResult.exists && readResult.content.trim()) {
435
- const parsed = parseOpenclawConfigText(readResult.content);
436
- if (parsed.ok) {
437
- workspaceDir = resolveOpenclawWorkspaceDir(parsed.data);
438
- } else {
439
- configError = parsed.error || '';
440
- }
441
- }
442
- return {
443
- workspaceDir,
444
- configError,
445
- configPath: readResult.path || OPENCLAW_CONFIG_FILE
446
- };
447
- }
448
-
449
- function readOpenclawAgentsFile(params = {}) {
450
- const workspaceInfo = getOpenclawWorkspaceInfo();
451
- const baseDir = workspaceInfo.workspaceDir;
452
- const filePath = path.join(baseDir, AGENTS_FILE_NAME);
453
-
454
- if (!fs.existsSync(baseDir)) {
455
- return {
456
- exists: false,
457
- path: filePath,
458
- content: '',
459
- lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
460
- workspaceDir: baseDir,
461
- configError: workspaceInfo.configError,
462
- baseDirMissing: true
463
- };
464
- }
465
-
466
- const readResult = readAgentsFile({ baseDir, metaOnly: !!params.metaOnly });
467
- return {
468
- ...readResult,
469
- workspaceDir: baseDir,
470
- configError: workspaceInfo.configError
471
- };
472
- }
473
-
474
- function applyOpenclawAgentsFile(params = {}) {
475
- const workspaceInfo = getOpenclawWorkspaceInfo();
476
- const baseDir = workspaceInfo.workspaceDir;
477
- ensureDir(baseDir);
478
- const result = applyAgentsFile({
479
- ...params,
480
- baseDir
481
- });
482
- return {
483
- ...result,
484
- workspaceDir: baseDir,
485
- configError: workspaceInfo.configError
486
- };
487
- }
488
-
489
- function readOpenclawWorkspaceFile(params = {}) {
490
- const nameResult = normalizeOpenclawWorkspaceFileName(params.fileName);
491
- if (nameResult.error) {
492
- return { error: nameResult.error };
493
- }
494
- const workspaceInfo = getOpenclawWorkspaceInfo();
495
- const baseDir = workspaceInfo.workspaceDir;
496
- const filePath = path.join(baseDir, nameResult.name);
497
-
498
- if (!fs.existsSync(baseDir)) {
499
- return {
500
- exists: false,
501
- path: filePath,
502
- content: '',
503
- lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
504
- workspaceDir: baseDir,
505
- configError: workspaceInfo.configError,
506
- baseDirMissing: true
507
- };
508
- }
509
-
510
- if (!fs.existsSync(filePath)) {
511
- return {
512
- exists: false,
513
- path: filePath,
514
- content: '',
515
- lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
516
- workspaceDir: baseDir,
517
- configError: workspaceInfo.configError
518
- };
519
- }
520
-
521
- if (params.metaOnly) {
522
- return {
523
- exists: true,
524
- path: filePath,
525
- content: '',
526
- lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
527
- workspaceDir: baseDir,
528
- configError: workspaceInfo.configError
529
- };
530
- }
531
-
532
- try {
533
- const raw = fs.readFileSync(filePath, 'utf-8');
534
- return {
535
- exists: true,
536
- path: filePath,
537
- content: stripUtf8Bom(raw),
538
- lineEnding: detectLineEnding(raw),
539
- workspaceDir: baseDir,
540
- configError: workspaceInfo.configError
541
- };
542
- } catch (e) {
543
- return { error: `读取 OpenClaw 工作区文件失败: ${e.message}` };
544
- }
545
- }
546
-
547
- function applyOpenclawWorkspaceFile(params = {}) {
548
- const nameResult = normalizeOpenclawWorkspaceFileName(params.fileName);
549
- if (nameResult.error) {
550
- return { error: nameResult.error };
551
- }
552
- const workspaceInfo = getOpenclawWorkspaceInfo();
553
- const baseDir = workspaceInfo.workspaceDir;
554
- ensureDir(baseDir);
555
-
556
- const content = typeof params.content === 'string' ? params.content : '';
557
- const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
558
- const normalized = normalizeLineEnding(content, lineEnding);
559
- const finalContent = ensureUtf8Bom(normalized);
560
- const filePath = path.join(baseDir, nameResult.name);
561
-
562
- try {
563
- fs.writeFileSync(filePath, finalContent, 'utf-8');
564
- return {
565
- success: true,
566
- path: filePath,
567
- workspaceDir: baseDir,
568
- configError: workspaceInfo.configError
569
- };
570
- } catch (e) {
571
- return { error: `写入 OpenClaw 工作区文件失败: ${e.message}` };
572
- }
573
- }
574
-
575
- function applyOpenclawConfig(params = {}) {
576
- const content = typeof params.content === 'string' ? params.content : '';
577
- const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
578
- const normalized = normalizeLineEnding(content, lineEnding);
579
- const parsed = parseOpenclawConfigText(normalized);
580
- if (!parsed.ok) {
581
- return { success: false, error: parsed.error };
582
- }
583
-
584
- try {
585
- const authUpdateResult = applyOpenclawAuthProfileUpdates({ updates: params.authProfileUpdates });
586
- if (!authUpdateResult.ok) {
587
- return {
588
- success: false,
589
- error: authUpdateResult.error || '写入 OpenClaw 认证配置失败'
590
- };
591
- }
592
- ensureDir(OPENCLAW_DIR);
593
- const backupPath = backupFileIfNeededOnce(OPENCLAW_CONFIG_FILE);
594
- fs.writeFileSync(OPENCLAW_CONFIG_FILE, normalized, 'utf-8');
595
- const result = {
596
- success: true,
597
- targetPath: OPENCLAW_CONFIG_FILE
598
- };
599
- if (backupPath) {
600
- result.backupPath = backupPath;
601
- }
602
- if (authUpdateResult.authStorePath) {
603
- result.authStorePath = authUpdateResult.authStorePath;
604
- }
605
- if (Array.isArray(authUpdateResult.applied) && authUpdateResult.applied.length) {
606
- result.authProfilesUpdated = authUpdateResult.applied;
607
- }
608
- return result;
609
- } catch (e) {
610
- return {
611
- success: false,
612
- error: e.message || '写入 OpenClaw 配置失败'
613
- };
614
- }
615
- }
616
-
617
- return {
618
- readOpenclawConfigFile,
619
- applyOpenclawConfig,
620
- readOpenclawAgentsFile,
621
- applyOpenclawAgentsFile,
622
- readOpenclawWorkspaceFile,
623
- applyOpenclawWorkspaceFile
624
- };
625
- }
626
-
627
- module.exports = {
628
- createOpenclawConfigController
629
- };
1
+ const JSON5 = require('json5');
2
+
3
+ function createOpenclawConfigController(deps = {}) {
4
+ const {
5
+ fs,
6
+ path,
7
+ os,
8
+ ensureDir,
9
+ readJsonObjectFromFile,
10
+ writeJsonAtomic,
11
+ backupFileIfNeededOnce,
12
+ stripUtf8Bom,
13
+ detectLineEnding,
14
+ normalizeLineEnding,
15
+ ensureUtf8Bom,
16
+ isPlainObject,
17
+ resolveHomePath,
18
+ readAgentsFile,
19
+ applyAgentsFile,
20
+ OPENCLAW_CONFIG_FILE,
21
+ OPENCLAW_WORKSPACE_DIR,
22
+ OPENCLAW_DIR,
23
+ OPENCLAW_DEFAULT_AGENT_ID,
24
+ OPENCLAW_AUTH_PROFILES_FILE_NAME,
25
+ OPENCLAW_AUTH_STATE_FILE_NAME,
26
+ AGENTS_FILE_NAME
27
+ } = deps;
28
+
29
+ if (!fs) throw new Error('createOpenclawConfigController 缺少 fs');
30
+ if (!path) throw new Error('createOpenclawConfigController 缺少 path');
31
+ if (!os) throw new Error('createOpenclawConfigController 缺少 os');
32
+ if (typeof ensureDir !== 'function') throw new Error('createOpenclawConfigController 缺少 ensureDir');
33
+ if (typeof readJsonObjectFromFile !== 'function') throw new Error('createOpenclawConfigController 缺少 readJsonObjectFromFile');
34
+ if (typeof writeJsonAtomic !== 'function') throw new Error('createOpenclawConfigController 缺少 writeJsonAtomic');
35
+ if (typeof backupFileIfNeededOnce !== 'function') throw new Error('createOpenclawConfigController 缺少 backupFileIfNeededOnce');
36
+ if (typeof stripUtf8Bom !== 'function') throw new Error('createOpenclawConfigController 缺少 stripUtf8Bom');
37
+ if (typeof detectLineEnding !== 'function') throw new Error('createOpenclawConfigController 缺少 detectLineEnding');
38
+ if (typeof normalizeLineEnding !== 'function') throw new Error('createOpenclawConfigController 缺少 normalizeLineEnding');
39
+ if (typeof ensureUtf8Bom !== 'function') throw new Error('createOpenclawConfigController 缺少 ensureUtf8Bom');
40
+ if (typeof isPlainObject !== 'function') throw new Error('createOpenclawConfigController 缺少 isPlainObject');
41
+ if (typeof resolveHomePath !== 'function') throw new Error('createOpenclawConfigController 缺少 resolveHomePath');
42
+ if (typeof readAgentsFile !== 'function') throw new Error('createOpenclawConfigController 缺少 readAgentsFile');
43
+ if (typeof applyAgentsFile !== 'function') throw new Error('createOpenclawConfigController 缺少 applyAgentsFile');
44
+ if (!OPENCLAW_CONFIG_FILE) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_CONFIG_FILE');
45
+ if (!OPENCLAW_WORKSPACE_DIR) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_WORKSPACE_DIR');
46
+ if (!OPENCLAW_DIR) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_DIR');
47
+ if (!OPENCLAW_DEFAULT_AGENT_ID) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_DEFAULT_AGENT_ID');
48
+ if (!OPENCLAW_AUTH_PROFILES_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_AUTH_PROFILES_FILE_NAME');
49
+ if (!OPENCLAW_AUTH_STATE_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 OPENCLAW_AUTH_STATE_FILE_NAME');
50
+ if (!AGENTS_FILE_NAME) throw new Error('createOpenclawConfigController 缺少 AGENTS_FILE_NAME');
51
+
52
+ function resolveOpenclawWorkspaceDir(config) {
53
+ const workspace = config
54
+ && config.agents
55
+ && config.agents.defaults
56
+ && typeof config.agents.defaults.workspace === 'string'
57
+ ? config.agents.defaults.workspace
58
+ : '';
59
+ const resolved = resolveHomePath(workspace);
60
+ if (!resolved) {
61
+ return OPENCLAW_WORKSPACE_DIR;
62
+ }
63
+ if (path.isAbsolute(resolved)) {
64
+ return resolved;
65
+ }
66
+ return path.join(OPENCLAW_DIR, resolved);
67
+ }
68
+
69
+ function normalizeOpenclawWorkspaceFileName(input) {
70
+ const raw = typeof input === 'string' ? input.trim() : '';
71
+ if (!raw) {
72
+ return { error: '文件名不能为空' };
73
+ }
74
+ if (raw.includes('\0')) {
75
+ return { error: '文件名非法' };
76
+ }
77
+ if (raw.includes('/') || raw.includes('\\') || raw.includes('..')) {
78
+ return { error: '文件名非法' };
79
+ }
80
+ const baseName = path.basename(raw);
81
+ if (baseName !== raw) {
82
+ return { error: '文件名非法' };
83
+ }
84
+ if (!raw.toLowerCase().endsWith('.md')) {
85
+ return { error: '仅支持 .md 文件' };
86
+ }
87
+ return { ok: true, name: raw };
88
+ }
89
+
90
+ function normalizeOpenclawProviderId(provider) {
91
+ const normalized = typeof provider === 'string' ? provider.trim().toLowerCase() : '';
92
+ if (!normalized) return '';
93
+ if (normalized === 'modelstudio' || normalized === 'qwencloud') {
94
+ return 'qwen';
95
+ }
96
+ if (normalized === 'z.ai' || normalized === 'z-ai') {
97
+ return 'zai';
98
+ }
99
+ if (normalized === 'opencode-zen') {
100
+ return 'opencode';
101
+ }
102
+ if (normalized === 'opencode-go-auth') {
103
+ return 'opencode-go';
104
+ }
105
+ if (normalized === 'kimi' || normalized === 'kimi-code' || normalized === 'kimi-coding') {
106
+ return 'kimi';
107
+ }
108
+ if (normalized === 'bedrock' || normalized === 'aws-bedrock') {
109
+ return 'amazon-bedrock';
110
+ }
111
+ if (normalized === 'bytedance' || normalized === 'doubao') {
112
+ return 'volcengine';
113
+ }
114
+ if (normalized === 'volcengine-plan') {
115
+ return 'volcengine';
116
+ }
117
+ if (normalized === 'byteplus-plan') {
118
+ return 'byteplus';
119
+ }
120
+ return normalized;
121
+ }
122
+
123
+ function findNormalizedOpenclawProviderValue(entries, provider) {
124
+ if (!isPlainObject(entries)) {
125
+ return undefined;
126
+ }
127
+ const providerKey = normalizeOpenclawProviderId(provider);
128
+ if (!providerKey) {
129
+ return undefined;
130
+ }
131
+ for (const [key, value] of Object.entries(entries)) {
132
+ if (normalizeOpenclawProviderId(key) === providerKey) {
133
+ return value;
134
+ }
135
+ }
136
+ return undefined;
137
+ }
138
+
139
+ function resolveOpenclawStateDir() {
140
+ const override = typeof process.env.OPENCLAW_STATE_DIR === 'string'
141
+ ? process.env.OPENCLAW_STATE_DIR.trim()
142
+ : '';
143
+ return override ? resolveHomePath(override) : OPENCLAW_DIR;
144
+ }
145
+
146
+ function resolveOpenclawAgentDir() {
147
+ const override = [process.env.OPENCLAW_AGENT_DIR, process.env.PI_CODING_AGENT_DIR]
148
+ .find(value => typeof value === 'string' && value.trim());
149
+ if (override) {
150
+ return resolveHomePath(override.trim());
151
+ }
152
+ return path.join(resolveOpenclawStateDir(), 'agents', OPENCLAW_DEFAULT_AGENT_ID, 'agent');
153
+ }
154
+
155
+ function buildOpenclawAuthProfileDisplay(profileId, credential) {
156
+ const type = typeof credential.type === 'string' && credential.type.trim()
157
+ ? credential.type.trim()
158
+ : 'unknown';
159
+ const parts = [`AuthProfile(${type}:${profileId})`];
160
+ const label = typeof credential.displayName === 'string' && credential.displayName.trim()
161
+ ? credential.displayName.trim()
162
+ : (typeof credential.email === 'string' && credential.email.trim() ? credential.email.trim() : '');
163
+ if (label) {
164
+ parts.push(label);
165
+ }
166
+ return parts.join(' · ');
167
+ }
168
+
169
+ function resolveOpenclawAuthProfileEditableValue(credential) {
170
+ if (!isPlainObject(credential)) {
171
+ return {
172
+ resolvedValue: '',
173
+ resolvedField: '',
174
+ editable: false,
175
+ valueKind: 'missing'
176
+ };
177
+ }
178
+ if (credential.type === 'api_key' && typeof credential.key === 'string' && credential.key.trim()) {
179
+ return {
180
+ resolvedValue: credential.key.trim(),
181
+ resolvedField: 'key',
182
+ editable: true,
183
+ valueKind: 'api_key'
184
+ };
185
+ }
186
+ if (credential.type === 'token' && typeof credential.token === 'string' && credential.token.trim()) {
187
+ return {
188
+ resolvedValue: credential.token.trim(),
189
+ resolvedField: 'token',
190
+ editable: true,
191
+ valueKind: 'token'
192
+ };
193
+ }
194
+ if (credential.type === 'oauth' && typeof credential.access === 'string' && credential.access.trim()) {
195
+ return {
196
+ resolvedValue: credential.access.trim(),
197
+ resolvedField: 'access',
198
+ editable: true,
199
+ valueKind: 'oauth-access'
200
+ };
201
+ }
202
+ return {
203
+ resolvedValue: '',
204
+ resolvedField: '',
205
+ editable: false,
206
+ valueKind: typeof credential.type === 'string' && credential.type.trim()
207
+ ? credential.type.trim()
208
+ : 'missing'
209
+ };
210
+ }
211
+
212
+ function getOpenclawAuthProfileTypeRank(credential) {
213
+ const type = typeof credential.type === 'string' ? credential.type.trim().toLowerCase() : '';
214
+ if (type === 'oauth') return 0;
215
+ if (type === 'token') return 1;
216
+ if (type === 'api_key') return 2;
217
+ return 3;
218
+ }
219
+
220
+ function readOpenclawAuthProfilesSummary() {
221
+ const agentDir = resolveOpenclawAgentDir();
222
+ const authStorePath = path.join(agentDir, OPENCLAW_AUTH_PROFILES_FILE_NAME);
223
+ const authStatePath = path.join(agentDir, OPENCLAW_AUTH_STATE_FILE_NAME);
224
+ const storeResult = readJsonObjectFromFile(authStorePath, { profiles: {} });
225
+ const stateResult = readJsonObjectFromFile(authStatePath, {});
226
+ const profiles = storeResult.ok && isPlainObject(storeResult.data) && isPlainObject(storeResult.data.profiles)
227
+ ? storeResult.data.profiles
228
+ : {};
229
+ const state = stateResult.ok && isPlainObject(stateResult.data)
230
+ ? stateResult.data
231
+ : {};
232
+
233
+ const grouped = new Map();
234
+ for (const [profileId, credential] of Object.entries(profiles)) {
235
+ if (!isPlainObject(credential)) continue;
236
+ const provider = typeof credential.provider === 'string' ? credential.provider.trim() : '';
237
+ const normalizedProvider = normalizeOpenclawProviderId(provider);
238
+ if (!normalizedProvider) continue;
239
+ if (!grouped.has(normalizedProvider)) {
240
+ grouped.set(normalizedProvider, []);
241
+ }
242
+ grouped.get(normalizedProvider).push([profileId, credential]);
243
+ }
244
+
245
+ const providers = {};
246
+ for (const [providerKey, entries] of grouped.entries()) {
247
+ const explicitOrder = findNormalizedOpenclawProviderValue(state.order, providerKey);
248
+ const lastGood = findNormalizedOpenclawProviderValue(state.lastGood, providerKey);
249
+ let selectedEntry = null;
250
+
251
+ if (typeof explicitOrder === 'string' && explicitOrder.trim()) {
252
+ selectedEntry = entries.find(([profileId]) => profileId === explicitOrder.trim()) || null;
253
+ }
254
+ if (!selectedEntry && typeof lastGood === 'string' && lastGood.trim()) {
255
+ selectedEntry = entries.find(([profileId]) => profileId === lastGood.trim()) || null;
256
+ }
257
+ if (!selectedEntry) {
258
+ entries.sort((a, b) => {
259
+ const rankDelta = getOpenclawAuthProfileTypeRank(a[1]) - getOpenclawAuthProfileTypeRank(b[1]);
260
+ if (rankDelta !== 0) return rankDelta;
261
+ return a[0].localeCompare(b[0]);
262
+ });
263
+ selectedEntry = entries[0] || null;
264
+ }
265
+ if (!selectedEntry) continue;
266
+ const [profileId, credential] = selectedEntry;
267
+ const resolvedValueMeta = resolveOpenclawAuthProfileEditableValue(credential);
268
+ providers[providerKey] = {
269
+ profileId,
270
+ provider: typeof credential.provider === 'string' ? credential.provider : providerKey,
271
+ normalizedProvider: providerKey,
272
+ type: typeof credential.type === 'string' ? credential.type : '',
273
+ displayName: typeof credential.displayName === 'string' ? credential.displayName : '',
274
+ display: buildOpenclawAuthProfileDisplay(profileId, credential),
275
+ email: typeof credential.email === 'string' ? credential.email : '',
276
+ editable: !!resolvedValueMeta.editable,
277
+ resolvedValue: resolvedValueMeta.resolvedValue,
278
+ resolvedField: resolvedValueMeta.resolvedField,
279
+ valueKind: resolvedValueMeta.valueKind
280
+ };
281
+ }
282
+
283
+ return {
284
+ authStorePath,
285
+ authStatePath,
286
+ providers
287
+ };
288
+ }
289
+
290
+ function sanitizeOpenclawAuthProfilesForClient(providers) {
291
+ const sanitized = {};
292
+ for (const [providerKey, summary] of Object.entries(isPlainObject(providers) ? providers : {})) {
293
+ if (!isPlainObject(summary)) {
294
+ continue;
295
+ }
296
+ const normalized = { ...summary };
297
+ delete normalized.resolvedValue;
298
+ sanitized[providerKey] = normalized;
299
+ }
300
+ return sanitized;
301
+ }
302
+
303
+ function normalizeOpenclawAuthProfileUpdate(entry) {
304
+ if (!isPlainObject(entry)) return null;
305
+ const profileId = typeof entry.profileId === 'string' ? entry.profileId.trim() : '';
306
+ const provider = typeof entry.provider === 'string' ? entry.provider.trim() : '';
307
+ const field = typeof entry.field === 'string' ? entry.field.trim() : '';
308
+ const value = typeof entry.value === 'string' ? entry.value.trim() : '';
309
+ const allowedFields = new Set(['key', 'token', 'access']);
310
+ if (!profileId || !provider || !allowedFields.has(field) || !value) {
311
+ return null;
312
+ }
313
+ return { profileId, provider, field, value };
314
+ }
315
+
316
+ function applyOpenclawAuthProfileUpdates(params = {}) {
317
+ const updates = Array.isArray(params.updates)
318
+ ? params.updates.map(normalizeOpenclawAuthProfileUpdate).filter(Boolean)
319
+ : [];
320
+ if (!updates.length) {
321
+ return { ok: true, applied: [] };
322
+ }
323
+
324
+ const authSummary = readOpenclawAuthProfilesSummary();
325
+ const authStorePath = authSummary.authStorePath;
326
+ const storeResult = readJsonObjectFromFile(authStorePath, { version: 1, profiles: {} });
327
+ if (!storeResult.ok) {
328
+ return { ok: false, error: storeResult.error || '读取 OpenClaw auth profile 失败' };
329
+ }
330
+ const store = isPlainObject(storeResult.data) ? storeResult.data : { version: 1, profiles: {} };
331
+ const profiles = isPlainObject(store.profiles) ? { ...store.profiles } : {};
332
+ const applied = [];
333
+
334
+ for (const update of updates) {
335
+ const existing = profiles[update.profileId];
336
+ if (!isPlainObject(existing)) {
337
+ return { ok: false, error: `未找到 OpenClaw 认证配置: ${update.profileId}` };
338
+ }
339
+ const existingProvider = typeof existing.provider === 'string' ? existing.provider.trim() : '';
340
+ if (normalizeOpenclawProviderId(existingProvider) !== normalizeOpenclawProviderId(update.provider)) {
341
+ return { ok: false, error: `认证配置与 provider 不匹配: ${update.profileId}` };
342
+ }
343
+
344
+ const next = { ...existing };
345
+ next[update.field] = update.value;
346
+ if (update.field === 'key') {
347
+ next.type = 'api_key';
348
+ delete next.keyRef;
349
+ } else if (update.field === 'token') {
350
+ next.type = 'token';
351
+ delete next.tokenRef;
352
+ } else if (update.field === 'access') {
353
+ next.type = 'oauth';
354
+ }
355
+ profiles[update.profileId] = next;
356
+ applied.push({
357
+ profileId: update.profileId,
358
+ provider: existingProvider || update.provider,
359
+ field: update.field
360
+ });
361
+ }
362
+
363
+ try {
364
+ ensureDir(path.dirname(authStorePath));
365
+ const backupPath = fs.existsSync(authStorePath) ? backupFileIfNeededOnce(authStorePath) : '';
366
+ writeJsonAtomic(authStorePath, {
367
+ ...store,
368
+ version: Number(store.version) > 0 ? Number(store.version) : 1,
369
+ profiles
370
+ });
371
+ return {
372
+ ok: true,
373
+ applied,
374
+ authStorePath,
375
+ backupPath
376
+ };
377
+ } catch (e) {
378
+ return {
379
+ ok: false,
380
+ error: e && e.message ? e.message : '写入 OpenClaw auth profile 失败'
381
+ };
382
+ }
383
+ }
384
+
385
+ function readOpenclawConfigFile() {
386
+ const filePath = OPENCLAW_CONFIG_FILE;
387
+ const authProfilesByProvider = sanitizeOpenclawAuthProfilesForClient(
388
+ readOpenclawAuthProfilesSummary().providers
389
+ );
390
+ if (!fs.existsSync(filePath)) {
391
+ return {
392
+ exists: false,
393
+ path: filePath,
394
+ content: '',
395
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
396
+ authProfilesByProvider
397
+ };
398
+ }
399
+
400
+ try {
401
+ const raw = fs.readFileSync(filePath, 'utf-8');
402
+ return {
403
+ exists: true,
404
+ path: filePath,
405
+ content: stripUtf8Bom(raw),
406
+ lineEnding: detectLineEnding(raw),
407
+ authProfilesByProvider
408
+ };
409
+ } catch (e) {
410
+ return { error: `读取 OpenClaw 配置失败: ${e.message}` };
411
+ }
412
+ }
413
+
414
+ function parseOpenclawConfigText(content) {
415
+ const raw = stripUtf8Bom(typeof content === 'string' ? content : '');
416
+ if (!raw.trim()) {
417
+ return { ok: false, error: 'OpenClaw 配置内容不能为空' };
418
+ }
419
+ try {
420
+ const parsed = JSON5.parse(raw);
421
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
422
+ return { ok: false, error: '配置格式错误(根节点必须是对象)' };
423
+ }
424
+ return { ok: true, data: parsed };
425
+ } catch (e) {
426
+ return { ok: false, error: `配置解析失败: ${e.message}` };
427
+ }
428
+ }
429
+
430
+ function getOpenclawWorkspaceInfo() {
431
+ const readResult = readOpenclawConfigFile();
432
+ let workspaceDir = OPENCLAW_WORKSPACE_DIR;
433
+ let configError = readResult.error || '';
434
+ if (!configError && readResult.exists && readResult.content.trim()) {
435
+ const parsed = parseOpenclawConfigText(readResult.content);
436
+ if (parsed.ok) {
437
+ workspaceDir = resolveOpenclawWorkspaceDir(parsed.data);
438
+ } else {
439
+ configError = parsed.error || '';
440
+ }
441
+ }
442
+ return {
443
+ workspaceDir,
444
+ configError,
445
+ configPath: readResult.path || OPENCLAW_CONFIG_FILE
446
+ };
447
+ }
448
+
449
+ function readOpenclawAgentsFile(params = {}) {
450
+ const workspaceInfo = getOpenclawWorkspaceInfo();
451
+ const baseDir = workspaceInfo.workspaceDir;
452
+ const filePath = path.join(baseDir, AGENTS_FILE_NAME);
453
+
454
+ if (!fs.existsSync(baseDir)) {
455
+ return {
456
+ exists: false,
457
+ path: filePath,
458
+ content: '',
459
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
460
+ workspaceDir: baseDir,
461
+ configError: workspaceInfo.configError,
462
+ baseDirMissing: true
463
+ };
464
+ }
465
+
466
+ const readResult = readAgentsFile({ baseDir, metaOnly: !!params.metaOnly });
467
+ return {
468
+ ...readResult,
469
+ workspaceDir: baseDir,
470
+ configError: workspaceInfo.configError
471
+ };
472
+ }
473
+
474
+ function applyOpenclawAgentsFile(params = {}) {
475
+ const workspaceInfo = getOpenclawWorkspaceInfo();
476
+ const baseDir = workspaceInfo.workspaceDir;
477
+ ensureDir(baseDir);
478
+ const result = applyAgentsFile({
479
+ ...params,
480
+ baseDir
481
+ });
482
+ return {
483
+ ...result,
484
+ workspaceDir: baseDir,
485
+ configError: workspaceInfo.configError
486
+ };
487
+ }
488
+
489
+ function readOpenclawWorkspaceFile(params = {}) {
490
+ const nameResult = normalizeOpenclawWorkspaceFileName(params.fileName);
491
+ if (nameResult.error) {
492
+ return { error: nameResult.error };
493
+ }
494
+ const workspaceInfo = getOpenclawWorkspaceInfo();
495
+ const baseDir = workspaceInfo.workspaceDir;
496
+ const filePath = path.join(baseDir, nameResult.name);
497
+
498
+ if (!fs.existsSync(baseDir)) {
499
+ return {
500
+ exists: false,
501
+ path: filePath,
502
+ content: '',
503
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
504
+ workspaceDir: baseDir,
505
+ configError: workspaceInfo.configError,
506
+ baseDirMissing: true
507
+ };
508
+ }
509
+
510
+ if (!fs.existsSync(filePath)) {
511
+ return {
512
+ exists: false,
513
+ path: filePath,
514
+ content: '',
515
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
516
+ workspaceDir: baseDir,
517
+ configError: workspaceInfo.configError
518
+ };
519
+ }
520
+
521
+ if (params.metaOnly) {
522
+ return {
523
+ exists: true,
524
+ path: filePath,
525
+ content: '',
526
+ lineEnding: os.EOL === '\r\n' ? '\r\n' : '\n',
527
+ workspaceDir: baseDir,
528
+ configError: workspaceInfo.configError
529
+ };
530
+ }
531
+
532
+ try {
533
+ const raw = fs.readFileSync(filePath, 'utf-8');
534
+ return {
535
+ exists: true,
536
+ path: filePath,
537
+ content: stripUtf8Bom(raw),
538
+ lineEnding: detectLineEnding(raw),
539
+ workspaceDir: baseDir,
540
+ configError: workspaceInfo.configError
541
+ };
542
+ } catch (e) {
543
+ return { error: `读取 OpenClaw 工作区文件失败: ${e.message}` };
544
+ }
545
+ }
546
+
547
+ function applyOpenclawWorkspaceFile(params = {}) {
548
+ const nameResult = normalizeOpenclawWorkspaceFileName(params.fileName);
549
+ if (nameResult.error) {
550
+ return { error: nameResult.error };
551
+ }
552
+ const workspaceInfo = getOpenclawWorkspaceInfo();
553
+ const baseDir = workspaceInfo.workspaceDir;
554
+ ensureDir(baseDir);
555
+
556
+ const content = typeof params.content === 'string' ? params.content : '';
557
+ const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
558
+ const normalized = normalizeLineEnding(content, lineEnding);
559
+ const finalContent = ensureUtf8Bom(normalized);
560
+ const filePath = path.join(baseDir, nameResult.name);
561
+
562
+ try {
563
+ fs.writeFileSync(filePath, finalContent, 'utf-8');
564
+ return {
565
+ success: true,
566
+ path: filePath,
567
+ workspaceDir: baseDir,
568
+ configError: workspaceInfo.configError
569
+ };
570
+ } catch (e) {
571
+ return { error: `写入 OpenClaw 工作区文件失败: ${e.message}` };
572
+ }
573
+ }
574
+
575
+ function applyOpenclawConfig(params = {}) {
576
+ const content = typeof params.content === 'string' ? params.content : '';
577
+ const lineEnding = params.lineEnding === '\r\n' ? '\r\n' : '\n';
578
+ const normalized = normalizeLineEnding(content, lineEnding);
579
+ const parsed = parseOpenclawConfigText(normalized);
580
+ if (!parsed.ok) {
581
+ return { success: false, error: parsed.error };
582
+ }
583
+
584
+ try {
585
+ const authUpdateResult = applyOpenclawAuthProfileUpdates({ updates: params.authProfileUpdates });
586
+ if (!authUpdateResult.ok) {
587
+ return {
588
+ success: false,
589
+ error: authUpdateResult.error || '写入 OpenClaw 认证配置失败'
590
+ };
591
+ }
592
+ ensureDir(OPENCLAW_DIR);
593
+ const backupPath = backupFileIfNeededOnce(OPENCLAW_CONFIG_FILE);
594
+ fs.writeFileSync(OPENCLAW_CONFIG_FILE, normalized, 'utf-8');
595
+ const result = {
596
+ success: true,
597
+ targetPath: OPENCLAW_CONFIG_FILE
598
+ };
599
+ if (backupPath) {
600
+ result.backupPath = backupPath;
601
+ }
602
+ if (authUpdateResult.authStorePath) {
603
+ result.authStorePath = authUpdateResult.authStorePath;
604
+ }
605
+ if (Array.isArray(authUpdateResult.applied) && authUpdateResult.applied.length) {
606
+ result.authProfilesUpdated = authUpdateResult.applied;
607
+ }
608
+ return result;
609
+ } catch (e) {
610
+ return {
611
+ success: false,
612
+ error: e.message || '写入 OpenClaw 配置失败'
613
+ };
614
+ }
615
+ }
616
+
617
+ return {
618
+ readOpenclawConfigFile,
619
+ applyOpenclawConfig,
620
+ readOpenclawAgentsFile,
621
+ applyOpenclawAgentsFile,
622
+ readOpenclawWorkspaceFile,
623
+ applyOpenclawWorkspaceFile
624
+ };
625
+ }
626
+
627
+ module.exports = {
628
+ createOpenclawConfigController
629
+ };