codexmate 0.0.32 → 0.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +551 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -69
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -150
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/update.js +162 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16023 -15829
  25. package/lib/automation.js +404 -404
  26. package/lib/cli-file-utils.js +151 -151
  27. package/lib/cli-models-utils.js +440 -440
  28. package/lib/cli-network-utils.js +190 -190
  29. package/lib/cli-path-utils.js +85 -85
  30. package/lib/cli-session-utils.js +121 -121
  31. package/lib/cli-sessions.js +427 -426
  32. package/lib/cli-utils.js +155 -155
  33. package/lib/cli-webhook.js +126 -126
  34. package/lib/download-artifacts.js +92 -92
  35. package/lib/mcp-stdio.js +453 -453
  36. package/lib/task-orchestrator.js +869 -869
  37. package/lib/text-diff.js +303 -303
  38. package/lib/win-tray.js +119 -0
  39. package/lib/workflow-engine.js +340 -340
  40. package/package.json +76 -76
  41. package/plugins/README.md +20 -20
  42. package/plugins/README.zh-CN.md +20 -20
  43. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  44. package/plugins/prompt-templates/computed.mjs +253 -253
  45. package/plugins/prompt-templates/index.mjs +8 -8
  46. package/plugins/prompt-templates/manifest.mjs +15 -15
  47. package/plugins/prompt-templates/methods.mjs +553 -553
  48. package/plugins/prompt-templates/overview.mjs +91 -91
  49. package/plugins/prompt-templates/ownership.mjs +19 -19
  50. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  51. package/plugins/prompt-templates/storage.mjs +64 -64
  52. package/plugins/registry.mjs +16 -16
  53. package/web-ui/app.js +650 -647
  54. package/web-ui/index.html +36 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +168 -168
  57. package/web-ui/logic.codex.mjs +69 -69
  58. package/web-ui/logic.mjs +5 -5
  59. package/web-ui/logic.runtime.mjs +128 -128
  60. package/web-ui/logic.session-convert.mjs +70 -70
  61. package/web-ui/logic.sessions.mjs +781 -781
  62. package/web-ui/modules/api.mjs +90 -90
  63. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  64. package/web-ui/modules/app.computed.index.mjs +17 -17
  65. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  66. package/web-ui/modules/app.computed.session.mjs +735 -693
  67. package/web-ui/modules/app.constants.mjs +15 -15
  68. package/web-ui/modules/app.methods.agents.mjs +651 -651
  69. package/web-ui/modules/app.methods.claude-config.mjs +269 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +861 -861
  71. package/web-ui/modules/app.methods.index.mjs +94 -94
  72. package/web-ui/modules/app.methods.install.mjs +205 -205
  73. package/web-ui/modules/app.methods.navigation.mjs +774 -774
  74. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  75. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  76. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  77. package/web-ui/modules/app.methods.providers.mjs +575 -529
  78. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  79. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  80. package/web-ui/modules/app.methods.session-browser.mjs +1012 -1012
  81. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  82. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  83. package/web-ui/modules/app.methods.startup-claude.mjs +538 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  86. package/web-ui/modules/config-mode.computed.mjs +124 -124
  87. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  88. package/web-ui/modules/i18n.dict.mjs +3192 -3177
  89. package/web-ui/modules/i18n.mjs +62 -62
  90. package/web-ui/modules/plugins.computed.mjs +3 -3
  91. package/web-ui/modules/plugins.methods.mjs +3 -3
  92. package/web-ui/modules/plugins.storage.mjs +11 -11
  93. package/web-ui/modules/provider-url-display.mjs +17 -17
  94. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  95. package/web-ui/modules/skills.computed.mjs +107 -107
  96. package/web-ui/modules/skills.methods.mjs +482 -482
  97. package/web-ui/partials/index/layout-footer.html +13 -13
  98. package/web-ui/partials/index/layout-header.html +499 -503
  99. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  100. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  101. package/web-ui/partials/index/modal-health-check.html +45 -45
  102. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  103. package/web-ui/partials/index/modal-skills.html +200 -200
  104. package/web-ui/partials/index/modals-basic.html +173 -162
  105. package/web-ui/partials/index/panel-config-claude.html +166 -136
  106. package/web-ui/partials/index/panel-config-codex.html +190 -196
  107. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  108. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  109. package/web-ui/partials/index/panel-dashboard.html +186 -219
  110. package/web-ui/partials/index/panel-docs.html +114 -114
  111. package/web-ui/partials/index/panel-market.html +177 -177
  112. package/web-ui/partials/index/panel-orchestration.html +391 -391
  113. package/web-ui/partials/index/panel-plugins.html +253 -253
  114. package/web-ui/partials/index/panel-sessions.html +319 -313
  115. package/web-ui/partials/index/panel-settings.html +190 -190
  116. package/web-ui/partials/index/panel-trash.html +82 -82
  117. package/web-ui/partials/index/panel-usage.html +137 -137
  118. package/web-ui/res/json5.min.js +1 -1
  119. package/web-ui/res/vue.global.prod.js +13 -13
  120. package/web-ui/session-helpers.mjs +591 -591
  121. package/web-ui/source-bundle.cjs +233 -233
  122. package/web-ui/styles/base-theme.css +281 -281
  123. package/web-ui/styles/bridge-pool.css +197 -197
  124. package/web-ui/styles/controls-forms.css +433 -433
  125. package/web-ui/styles/dashboard.css +406 -406
  126. package/web-ui/styles/docs-panel.css +245 -245
  127. package/web-ui/styles/feedback.css +108 -108
  128. package/web-ui/styles/health-check-dialog.css +144 -144
  129. package/web-ui/styles/layout-shell.css +628 -638
  130. package/web-ui/styles/modals-core.css +499 -466
  131. package/web-ui/styles/navigation-panels.css +391 -391
  132. package/web-ui/styles/openclaw-structured.css +266 -266
  133. package/web-ui/styles/plugins-panel.css +564 -564
  134. package/web-ui/styles/responsive.css +392 -392
  135. package/web-ui/styles/sessions-list.css +683 -647
  136. package/web-ui/styles/sessions-preview.css +407 -407
  137. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  138. package/web-ui/styles/sessions-usage.css +588 -588
  139. package/web-ui/styles/settings-panel.css +349 -349
  140. package/web-ui/styles/skills-list.css +305 -305
  141. package/web-ui/styles/skills-market.css +429 -429
  142. package/web-ui/styles/task-orchestration.css +822 -822
  143. package/web-ui/styles/titles-cards.css +472 -472
  144. package/web-ui/styles/trash-panel.css +90 -90
  145. package/web-ui/styles/webhook.css +81 -81
  146. package/web-ui/styles.css +24 -24
  147. package/web-ui.html +17 -17
@@ -1,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
+ };