codexmate 0.0.20 → 0.0.22

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 (96) hide show
  1. package/README.md +289 -152
  2. package/README.zh.md +321 -0
  3. package/cli/agents-files.js +224 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +1044 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/openai-bridge.js +950 -0
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/session-usage.concurrent.js +28 -0
  12. package/cli/session-usage.js +112 -0
  13. package/cli/session-usage.models.js +176 -0
  14. package/cli/skills.js +1141 -0
  15. package/cli/zip-commands.js +510 -0
  16. package/cli.js +9408 -9719
  17. package/lib/cli-models-utils.js +109 -1
  18. package/lib/cli-path-utils.js +69 -0
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/download-artifacts.js +77 -0
  21. package/lib/task-orchestrator.js +869 -0
  22. package/package.json +14 -10
  23. package/res/logo.png +0 -0
  24. package/res/vue.global.prod.js +13 -0
  25. package/web-ui/app.js +193 -15
  26. package/web-ui/index.html +5 -1
  27. package/web-ui/logic.agents-diff.mjs +1 -1
  28. package/web-ui/logic.claude.mjs +60 -0
  29. package/web-ui/logic.runtime.mjs +11 -7
  30. package/web-ui/logic.sessions.mjs +372 -21
  31. package/web-ui/modules/api.mjs +22 -1
  32. package/web-ui/modules/app.computed.dashboard.mjs +23 -10
  33. package/web-ui/modules/app.computed.index.mjs +4 -0
  34. package/web-ui/modules/app.computed.main-tabs.mjs +198 -0
  35. package/web-ui/modules/app.computed.session.mjs +521 -9
  36. package/web-ui/modules/app.methods.agents.mjs +62 -11
  37. package/web-ui/modules/app.methods.codex-config.mjs +189 -34
  38. package/web-ui/modules/app.methods.index.mjs +7 -1
  39. package/web-ui/modules/app.methods.install.mjs +24 -20
  40. package/web-ui/modules/app.methods.navigation.mjs +142 -1
  41. package/web-ui/modules/app.methods.openclaw-core.mjs +339 -39
  42. package/web-ui/modules/app.methods.openclaw-editing.mjs +39 -4
  43. package/web-ui/modules/app.methods.openclaw-persist.mjs +122 -4
  44. package/web-ui/modules/app.methods.providers.mjs +192 -53
  45. package/web-ui/modules/app.methods.session-actions.mjs +99 -19
  46. package/web-ui/modules/app.methods.session-browser.mjs +196 -5
  47. package/web-ui/modules/app.methods.session-timeline.mjs +22 -15
  48. package/web-ui/modules/app.methods.session-trash.mjs +3 -0
  49. package/web-ui/modules/app.methods.startup-claude.mjs +70 -71
  50. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  51. package/web-ui/modules/config-mode.computed.mjs +2 -0
  52. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  53. package/web-ui/modules/i18n.mjs +1609 -0
  54. package/web-ui/modules/plugins.computed.mjs +220 -0
  55. package/web-ui/modules/plugins.methods.mjs +620 -0
  56. package/web-ui/modules/plugins.storage.mjs +37 -0
  57. package/web-ui/partials/index/layout-footer.html +1 -57
  58. package/web-ui/partials/index/layout-header.html +299 -175
  59. package/web-ui/partials/index/modal-config-template-agents.html +79 -29
  60. package/web-ui/partials/index/modal-confirm-toast.html +1 -1
  61. package/web-ui/partials/index/modal-health-check.html +14 -14
  62. package/web-ui/partials/index/modal-openclaw-config.html +47 -42
  63. package/web-ui/partials/index/modal-skills.html +130 -114
  64. package/web-ui/partials/index/modals-basic.html +71 -102
  65. package/web-ui/partials/index/panel-config-claude.html +50 -12
  66. package/web-ui/partials/index/panel-config-codex.html +34 -37
  67. package/web-ui/partials/index/panel-config-openclaw.html +10 -16
  68. package/web-ui/partials/index/panel-docs.html +147 -0
  69. package/web-ui/partials/index/panel-market.html +38 -38
  70. package/web-ui/partials/index/panel-orchestration.html +397 -0
  71. package/web-ui/partials/index/panel-plugins.html +243 -0
  72. package/web-ui/partials/index/panel-sessions.html +51 -146
  73. package/web-ui/partials/index/panel-settings.html +188 -96
  74. package/web-ui/partials/index/panel-usage.html +353 -0
  75. package/web-ui/session-helpers.mjs +221 -10
  76. package/web-ui/styles/base-theme.css +120 -229
  77. package/web-ui/styles/controls-forms.css +59 -51
  78. package/web-ui/styles/docs-panel.css +247 -0
  79. package/web-ui/styles/layout-shell.css +394 -128
  80. package/web-ui/styles/modals-core.css +18 -3
  81. package/web-ui/styles/navigation-panels.css +184 -183
  82. package/web-ui/styles/plugins-panel.css +518 -0
  83. package/web-ui/styles/responsive.css +102 -62
  84. package/web-ui/styles/sessions-list.css +13 -27
  85. package/web-ui/styles/sessions-preview.css +13 -7
  86. package/web-ui/styles/sessions-toolbar-trash.css +25 -0
  87. package/web-ui/styles/sessions-usage.css +581 -6
  88. package/web-ui/styles/settings-panel.css +166 -0
  89. package/web-ui/styles/skills-list.css +16 -11
  90. package/web-ui/styles/skills-market.css +63 -2
  91. package/web-ui/styles/task-orchestration.css +776 -0
  92. package/web-ui/styles/titles-cards.css +67 -66
  93. package/web-ui/styles.css +4 -0
  94. package/README.en.md +0 -259
  95. package/res/screenshot.png +0 -0
  96. package/res/vue.global.js +0 -18552
@@ -0,0 +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
+ };
@@ -0,0 +1,28 @@
1
+ function createConcurrencyLimiter(maxConcurrency) {
2
+ const max = Number.isFinite(Number(maxConcurrency))
3
+ ? Math.max(1, Math.floor(Number(maxConcurrency)))
4
+ : 8;
5
+ let active = 0;
6
+ const queue = [];
7
+ const next = () => {
8
+ const resolve = queue.shift();
9
+ if (resolve) resolve();
10
+ };
11
+ return async (task) => {
12
+ if (active >= max) {
13
+ await new Promise((resolve) => queue.push(resolve));
14
+ }
15
+ active += 1;
16
+ try {
17
+ return await task();
18
+ } finally {
19
+ active -= 1;
20
+ next();
21
+ }
22
+ };
23
+ }
24
+
25
+ module.exports = {
26
+ createConcurrencyLimiter
27
+ };
28
+