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,446 +1,446 @@
1
- function createArchiveHelperController(deps = {}) {
2
- const {
3
- fs,
4
- path,
5
- os,
6
- execSync,
7
- zipLib,
8
- yauzl,
9
- ensureDir,
10
- isPathInside,
11
- commandExists,
12
- MAX_UPLOAD_SIZE,
13
- MAX_SKILLS_ZIP_UPLOAD_SIZE,
14
- MAX_SKILLS_ZIP_ENTRY_COUNT,
15
- MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES
16
- } = deps;
17
-
18
- if (!fs) throw new Error('createArchiveHelperController 缺少 fs');
19
- if (!path) throw new Error('createArchiveHelperController 缺少 path');
20
- if (!os) throw new Error('createArchiveHelperController 缺少 os');
21
- if (typeof execSync !== 'function') throw new Error('createArchiveHelperController 缺少 execSync');
22
- if (!zipLib) throw new Error('createArchiveHelperController 缺少 zipLib');
23
- if (!yauzl) throw new Error('createArchiveHelperController 缺少 yauzl');
24
- if (typeof ensureDir !== 'function') throw new Error('createArchiveHelperController 缺少 ensureDir');
25
- if (typeof isPathInside !== 'function') throw new Error('createArchiveHelperController 缺少 isPathInside');
26
- if (typeof commandExists !== 'function') throw new Error('createArchiveHelperController 缺少 commandExists');
27
-
28
- const ZIP_PATHS = ['zip'];
29
-
30
- function findZipExecutable() {
31
- for (const candidate of ZIP_PATHS) {
32
- try {
33
- if (candidate === 'zip') {
34
- if (commandExists('zip', '--help')) {
35
- return 'zip';
36
- }
37
- } else if (fs.existsSync(candidate)) {
38
- return candidate;
39
- }
40
- } catch (_) {}
41
- }
42
- return null;
43
- }
44
-
45
- function resolveZipTool() {
46
- const zipExe = findZipExecutable();
47
- if (zipExe) {
48
- return { type: 'zip', cmd: zipExe };
49
- }
50
- return { type: 'lib', cmd: 'zip-lib' };
51
- }
52
-
53
- function resolveUnzipTool() {
54
- return { type: 'lib', cmd: 'zip-lib' };
55
- }
56
-
57
- async function zipWithLibrary(absPath, outputPath) {
58
- const stat = fs.lstatSync(absPath);
59
- if (stat.isDirectory()) {
60
- await zipLib.archiveFolder(absPath, outputPath);
61
- return;
62
- }
63
- await zipLib.archiveFile(absPath, outputPath);
64
- }
65
-
66
- async function unzipWithLibrary(zipPath, outputDir) {
67
- await zipLib.extract(zipPath, outputDir);
68
- }
69
-
70
- function copyDirRecursive(srcDir, destDir, options = {}) {
71
- const dereferenceSymlinks = !!(options && options.dereferenceSymlinks);
72
- const allowedRootRealPath = (options && typeof options.allowedRootRealPath === 'string')
73
- ? options.allowedRootRealPath
74
- : '';
75
- const visitedRealPaths = options && options.visitedRealPaths instanceof Set
76
- ? options.visitedRealPaths
77
- : new Set();
78
- const childOptions = {
79
- ...options,
80
- dereferenceSymlinks,
81
- allowedRootRealPath,
82
- visitedRealPaths
83
- };
84
- ensureDir(destDir);
85
- const entries = fs.readdirSync(srcDir, { withFileTypes: true });
86
- for (const entry of entries) {
87
- const srcPath = path.join(srcDir, entry.name);
88
- const destPath = path.join(destDir, entry.name);
89
- if (entry.isDirectory()) {
90
- if (!dereferenceSymlinks) {
91
- copyDirRecursive(srcPath, destPath, childOptions);
92
- continue;
93
- }
94
- const realPath = fs.realpathSync(srcPath);
95
- if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
96
- throw new Error(`symlink escapes skill root: ${srcPath}`);
97
- }
98
- if (visitedRealPaths.has(realPath)) {
99
- continue;
100
- }
101
- visitedRealPaths.add(realPath);
102
- try {
103
- copyDirRecursive(srcPath, destPath, childOptions);
104
- } finally {
105
- visitedRealPaths.delete(realPath);
106
- }
107
- } else if (entry.isSymbolicLink()) {
108
- if (dereferenceSymlinks) {
109
- const realPath = fs.realpathSync(srcPath);
110
- if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
111
- throw new Error(`symlink escapes skill root: ${srcPath}`);
112
- }
113
- const realStat = fs.statSync(realPath);
114
- if (realStat.isDirectory()) {
115
- if (visitedRealPaths.has(realPath)) {
116
- continue;
117
- }
118
- visitedRealPaths.add(realPath);
119
- try {
120
- copyDirRecursive(realPath, destPath, childOptions);
121
- } finally {
122
- visitedRealPaths.delete(realPath);
123
- }
124
- } else {
125
- fs.copyFileSync(realPath, destPath);
126
- }
127
- } else {
128
- const target = fs.readlinkSync(srcPath);
129
- fs.symlinkSync(target, destPath);
130
- }
131
- } else {
132
- fs.copyFileSync(srcPath, destPath);
133
- }
134
- }
135
- }
136
-
137
- function inspectZipArchiveLimits(zipPath, options = {}) {
138
- const maxEntryCount = Number.isFinite(options.maxEntryCount) && options.maxEntryCount > 0
139
- ? Math.floor(options.maxEntryCount)
140
- : MAX_SKILLS_ZIP_ENTRY_COUNT;
141
- const maxUncompressedBytes = Number.isFinite(options.maxUncompressedBytes) && options.maxUncompressedBytes > 0
142
- ? Math.floor(options.maxUncompressedBytes)
143
- : MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES;
144
-
145
- return new Promise((resolve, reject) => {
146
- yauzl.open(zipPath, { lazyEntries: true, autoClose: true }, (openErr, zipFile) => {
147
- if (openErr) {
148
- reject(openErr);
149
- return;
150
- }
151
- if (!zipFile) {
152
- reject(new Error('无法读取 ZIP 文件'));
153
- return;
154
- }
155
- let entryCount = 0;
156
- let totalUncompressedBytes = 0;
157
- let settled = false;
158
- const finish = (err, data) => {
159
- if (settled) return;
160
- settled = true;
161
- try {
162
- zipFile.close();
163
- } catch (_) {}
164
- if (err) {
165
- reject(err);
166
- } else {
167
- resolve(data);
168
- }
169
- };
170
-
171
- zipFile.on('entry', (entry) => {
172
- if (settled) return;
173
- entryCount += 1;
174
- const entrySize = Number.isFinite(entry.uncompressedSize) ? entry.uncompressedSize : 0;
175
- totalUncompressedBytes += entrySize;
176
- if (entryCount > maxEntryCount) {
177
- finish(new Error(`压缩包条目过多(>${maxEntryCount})`));
178
- return;
179
- }
180
- if (totalUncompressedBytes > maxUncompressedBytes) {
181
- finish(new Error(`压缩包解压总大小超限(>${Math.floor(maxUncompressedBytes / 1024 / 1024)}MB)`));
182
- return;
183
- }
184
- zipFile.readEntry();
185
- });
186
-
187
- zipFile.on('end', () => {
188
- finish(null, { entryCount, totalUncompressedBytes });
189
- });
190
-
191
- zipFile.on('error', (zipErr) => {
192
- finish(zipErr);
193
- });
194
-
195
- zipFile.readEntry();
196
- });
197
- });
198
- }
199
-
200
- function writeUploadZipStream(req, prefix, originalName = '', maxSize = MAX_SKILLS_ZIP_UPLOAD_SIZE) {
201
- return new Promise((resolve, reject) => {
202
- const lengthHeader = parseInt(req.headers['content-length'] || '0', 10);
203
- if (Number.isFinite(lengthHeader) && lengthHeader > maxSize) {
204
- reject(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
205
- return;
206
- }
207
-
208
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
209
- const rawName = originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`;
210
- const fileName = path.basename(rawName);
211
- const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
212
- const stream = fs.createWriteStream(zipPath);
213
- let bytesWritten = 0;
214
- let settled = false;
215
- let hasContent = false;
216
-
217
- const fail = (err) => {
218
- if (settled) return;
219
- settled = true;
220
- try {
221
- stream.destroy();
222
- } catch (_) {}
223
- try {
224
- fs.rmSync(tempDir, { recursive: true, force: true });
225
- } catch (_) {}
226
- reject(err);
227
- };
228
-
229
- const done = () => {
230
- if (settled) return;
231
- settled = true;
232
- if (!hasContent || bytesWritten <= 0) {
233
- try {
234
- fs.rmSync(tempDir, { recursive: true, force: true });
235
- } catch (_) {}
236
- reject(new Error('备份文件为空'));
237
- return;
238
- }
239
- resolve({ tempDir, zipPath });
240
- };
241
-
242
- req.on('error', (err) => fail(err));
243
- req.on('aborted', () => fail(new Error('上传已中断')));
244
- req.on('close', () => {
245
- if (!settled && !req.complete) {
246
- fail(new Error('上传已中断'));
247
- }
248
- });
249
- stream.on('error', (err) => fail(err));
250
- req.on('data', (chunk) => {
251
- if (settled) return;
252
- hasContent = true;
253
- bytesWritten += chunk.length;
254
- if (bytesWritten > maxSize) {
255
- fail(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
256
- try {
257
- req.destroy();
258
- } catch (_) {}
259
- return;
260
- }
261
- stream.write(chunk);
262
- });
263
- req.on('end', () => {
264
- if (settled) return;
265
- stream.end(() => done());
266
- });
267
- });
268
- }
269
-
270
- function writeUploadZip(base64, prefix, originalName = '') {
271
- let buffer;
272
- try {
273
- buffer = Buffer.from(base64 || '', 'base64');
274
- } catch (_) {
275
- return { error: '备份文件内容不是有效的 base64 编码' };
276
- }
277
-
278
- if (!buffer || buffer.length === 0) {
279
- return { error: '备份文件为空' };
280
- }
281
-
282
- if (buffer.length > MAX_UPLOAD_SIZE) {
283
- return { error: `备份文件过大(>${Math.floor(MAX_UPLOAD_SIZE / 1024 / 1024)}MB)` };
284
- }
285
-
286
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
287
- const fileName = path.basename(originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`);
288
- const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
289
- fs.writeFileSync(zipPath, buffer);
290
- return { tempDir, zipPath };
291
- }
292
-
293
- async function extractUploadZip(zipPath, extractDir) {
294
- resolveUnzipTool();
295
- ensureDir(extractDir);
296
- await unzipWithLibrary(zipPath, extractDir);
297
- }
298
-
299
- function findConfigSourceDir(extractedDir, markerDirName, requiredFileName) {
300
- const markerPath = path.join(extractedDir, markerDirName);
301
- if (fs.existsSync(markerPath) && fs.statSync(markerPath).isDirectory()) {
302
- return markerPath;
303
- }
304
-
305
- const entries = fs.readdirSync(extractedDir, { withFileTypes: true }).filter((item) => item.isDirectory());
306
- if (entries.length === 1) {
307
- const onlyDir = path.join(extractedDir, entries[0].name);
308
- const nestedMarker = path.join(onlyDir, markerDirName);
309
- if (fs.existsSync(nestedMarker) && fs.statSync(nestedMarker).isDirectory()) {
310
- return nestedMarker;
311
- }
312
- if (fs.existsSync(path.join(onlyDir, requiredFileName))) {
313
- return onlyDir;
314
- }
315
- }
316
-
317
- if (fs.existsSync(path.join(extractedDir, requiredFileName))) {
318
- return extractedDir;
319
- }
320
-
321
- return extractedDir;
322
- }
323
-
324
- async function prepareDirectoryDownload(dirPath, options = {}) {
325
- const missingMessage = typeof options.missingMessage === 'string' && options.missingMessage.trim()
326
- ? options.missingMessage.trim()
327
- : '目录不存在';
328
- const fileNamePrefix = typeof options.fileNamePrefix === 'string' && options.fileNamePrefix.trim()
329
- ? options.fileNamePrefix.trim()
330
- : 'archive';
331
-
332
- try {
333
- if (!fs.existsSync(dirPath)) {
334
- return { error: missingMessage, path: dirPath };
335
- }
336
-
337
- const tempDir = os.tmpdir();
338
- const timestamp = Date.now();
339
- const zipFileName = `${fileNamePrefix}-${timestamp}.zip`;
340
- const zipFilePath = path.join(tempDir, zipFileName);
341
-
342
- const zipTool = resolveZipTool();
343
- if (zipTool.type === 'zip') {
344
- const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
345
- execSync(cmd, { stdio: 'ignore' });
346
- } else {
347
- await zipWithLibrary(dirPath, zipFilePath);
348
- }
349
-
350
- return {
351
- success: true,
352
- downloadPath: zipFilePath,
353
- fileName: zipFileName,
354
- sourcePath: dirPath
355
- };
356
- } catch (e) {
357
- return { error: `打包失败:${e.message}` };
358
- }
359
- }
360
-
361
- async function backupDirectoryIfExists(dirPath, prefix) {
362
- if (!fs.existsSync(dirPath)) {
363
- return { backupPath: '' };
364
- }
365
-
366
- const tempDir = os.tmpdir();
367
- const timestamp = Date.now();
368
- const zipFileName = `${prefix}-${timestamp}.zip`;
369
- const zipFilePath = path.join(tempDir, zipFileName);
370
- const zipTool = resolveZipTool();
371
-
372
- try {
373
- if (zipTool.type === 'zip') {
374
- const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
375
- execSync(cmd, { stdio: 'ignore' });
376
- } else {
377
- await zipWithLibrary(dirPath, zipFilePath);
378
- }
379
- return { backupPath: zipFilePath, fileName: zipFileName };
380
- } catch (e) {
381
- return { backupPath: '', warning: `备份失败: ${e.message}` };
382
- }
383
- }
384
-
385
- async function restoreConfigDirectoryFromUpload(payload, options) {
386
- const { targetDir, requiredFileName, markerDirName, tempPrefix, backupPrefix } = options;
387
- if (!payload || typeof payload.fileBase64 !== 'string' || !payload.fileBase64.trim()) {
388
- return { error: '缺少备份文件内容' };
389
- }
390
-
391
- const upload = writeUploadZip(payload.fileBase64, tempPrefix, payload.fileName);
392
- if (upload.error) {
393
- return { error: upload.error };
394
- }
395
-
396
- const tempDir = upload.tempDir;
397
- const extractDir = path.join(tempDir, 'extract');
398
- let backupPath = '';
399
- try {
400
- await extractUploadZip(upload.zipPath, extractDir);
401
- const sourceDir = findConfigSourceDir(extractDir, markerDirName, requiredFileName);
402
- const requiredPath = path.join(sourceDir, requiredFileName);
403
- if (!fs.existsSync(requiredPath)) {
404
- return { error: `无效备份,缺少 ${requiredFileName}` };
405
- }
406
-
407
- const backupResult = await backupDirectoryIfExists(targetDir, backupPrefix);
408
- backupPath = backupResult.backupPath || '';
409
-
410
- fs.rmSync(targetDir, { recursive: true, force: true });
411
- copyDirRecursive(sourceDir, targetDir);
412
-
413
- return {
414
- success: true,
415
- targetDir,
416
- appliedFrom: payload.fileName || '',
417
- backupPath,
418
- backupWarning: backupResult.warning || ''
419
- };
420
- } catch (e) {
421
- return { error: `导入失败:${e.message}` };
422
- } finally {
423
- fs.rmSync(tempDir, { recursive: true, force: true });
424
- }
425
- }
426
-
427
- return {
428
- resolveZipTool,
429
- resolveUnzipTool,
430
- zipWithLibrary,
431
- unzipWithLibrary,
432
- copyDirRecursive,
433
- inspectZipArchiveLimits,
434
- writeUploadZipStream,
435
- writeUploadZip,
436
- extractUploadZip,
437
- findConfigSourceDir,
438
- prepareDirectoryDownload,
439
- backupDirectoryIfExists,
440
- restoreConfigDirectoryFromUpload
441
- };
442
- }
443
-
444
- module.exports = {
445
- createArchiveHelperController
446
- };
1
+ function createArchiveHelperController(deps = {}) {
2
+ const {
3
+ fs,
4
+ path,
5
+ os,
6
+ execSync,
7
+ zipLib,
8
+ yauzl,
9
+ ensureDir,
10
+ isPathInside,
11
+ commandExists,
12
+ MAX_UPLOAD_SIZE,
13
+ MAX_SKILLS_ZIP_UPLOAD_SIZE,
14
+ MAX_SKILLS_ZIP_ENTRY_COUNT,
15
+ MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES
16
+ } = deps;
17
+
18
+ if (!fs) throw new Error('createArchiveHelperController 缺少 fs');
19
+ if (!path) throw new Error('createArchiveHelperController 缺少 path');
20
+ if (!os) throw new Error('createArchiveHelperController 缺少 os');
21
+ if (typeof execSync !== 'function') throw new Error('createArchiveHelperController 缺少 execSync');
22
+ if (!zipLib) throw new Error('createArchiveHelperController 缺少 zipLib');
23
+ if (!yauzl) throw new Error('createArchiveHelperController 缺少 yauzl');
24
+ if (typeof ensureDir !== 'function') throw new Error('createArchiveHelperController 缺少 ensureDir');
25
+ if (typeof isPathInside !== 'function') throw new Error('createArchiveHelperController 缺少 isPathInside');
26
+ if (typeof commandExists !== 'function') throw new Error('createArchiveHelperController 缺少 commandExists');
27
+
28
+ const ZIP_PATHS = ['zip'];
29
+
30
+ function findZipExecutable() {
31
+ for (const candidate of ZIP_PATHS) {
32
+ try {
33
+ if (candidate === 'zip') {
34
+ if (commandExists('zip', '--help')) {
35
+ return 'zip';
36
+ }
37
+ } else if (fs.existsSync(candidate)) {
38
+ return candidate;
39
+ }
40
+ } catch (_) {}
41
+ }
42
+ return null;
43
+ }
44
+
45
+ function resolveZipTool() {
46
+ const zipExe = findZipExecutable();
47
+ if (zipExe) {
48
+ return { type: 'zip', cmd: zipExe };
49
+ }
50
+ return { type: 'lib', cmd: 'zip-lib' };
51
+ }
52
+
53
+ function resolveUnzipTool() {
54
+ return { type: 'lib', cmd: 'zip-lib' };
55
+ }
56
+
57
+ async function zipWithLibrary(absPath, outputPath) {
58
+ const stat = fs.lstatSync(absPath);
59
+ if (stat.isDirectory()) {
60
+ await zipLib.archiveFolder(absPath, outputPath);
61
+ return;
62
+ }
63
+ await zipLib.archiveFile(absPath, outputPath);
64
+ }
65
+
66
+ async function unzipWithLibrary(zipPath, outputDir) {
67
+ await zipLib.extract(zipPath, outputDir);
68
+ }
69
+
70
+ function copyDirRecursive(srcDir, destDir, options = {}) {
71
+ const dereferenceSymlinks = !!(options && options.dereferenceSymlinks);
72
+ const allowedRootRealPath = (options && typeof options.allowedRootRealPath === 'string')
73
+ ? options.allowedRootRealPath
74
+ : '';
75
+ const visitedRealPaths = options && options.visitedRealPaths instanceof Set
76
+ ? options.visitedRealPaths
77
+ : new Set();
78
+ const childOptions = {
79
+ ...options,
80
+ dereferenceSymlinks,
81
+ allowedRootRealPath,
82
+ visitedRealPaths
83
+ };
84
+ ensureDir(destDir);
85
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
86
+ for (const entry of entries) {
87
+ const srcPath = path.join(srcDir, entry.name);
88
+ const destPath = path.join(destDir, entry.name);
89
+ if (entry.isDirectory()) {
90
+ if (!dereferenceSymlinks) {
91
+ copyDirRecursive(srcPath, destPath, childOptions);
92
+ continue;
93
+ }
94
+ const realPath = fs.realpathSync(srcPath);
95
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
96
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
97
+ }
98
+ if (visitedRealPaths.has(realPath)) {
99
+ continue;
100
+ }
101
+ visitedRealPaths.add(realPath);
102
+ try {
103
+ copyDirRecursive(srcPath, destPath, childOptions);
104
+ } finally {
105
+ visitedRealPaths.delete(realPath);
106
+ }
107
+ } else if (entry.isSymbolicLink()) {
108
+ if (dereferenceSymlinks) {
109
+ const realPath = fs.realpathSync(srcPath);
110
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
111
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
112
+ }
113
+ const realStat = fs.statSync(realPath);
114
+ if (realStat.isDirectory()) {
115
+ if (visitedRealPaths.has(realPath)) {
116
+ continue;
117
+ }
118
+ visitedRealPaths.add(realPath);
119
+ try {
120
+ copyDirRecursive(realPath, destPath, childOptions);
121
+ } finally {
122
+ visitedRealPaths.delete(realPath);
123
+ }
124
+ } else {
125
+ fs.copyFileSync(realPath, destPath);
126
+ }
127
+ } else {
128
+ const target = fs.readlinkSync(srcPath);
129
+ fs.symlinkSync(target, destPath);
130
+ }
131
+ } else {
132
+ fs.copyFileSync(srcPath, destPath);
133
+ }
134
+ }
135
+ }
136
+
137
+ function inspectZipArchiveLimits(zipPath, options = {}) {
138
+ const maxEntryCount = Number.isFinite(options.maxEntryCount) && options.maxEntryCount > 0
139
+ ? Math.floor(options.maxEntryCount)
140
+ : MAX_SKILLS_ZIP_ENTRY_COUNT;
141
+ const maxUncompressedBytes = Number.isFinite(options.maxUncompressedBytes) && options.maxUncompressedBytes > 0
142
+ ? Math.floor(options.maxUncompressedBytes)
143
+ : MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES;
144
+
145
+ return new Promise((resolve, reject) => {
146
+ yauzl.open(zipPath, { lazyEntries: true, autoClose: true }, (openErr, zipFile) => {
147
+ if (openErr) {
148
+ reject(openErr);
149
+ return;
150
+ }
151
+ if (!zipFile) {
152
+ reject(new Error('无法读取 ZIP 文件'));
153
+ return;
154
+ }
155
+ let entryCount = 0;
156
+ let totalUncompressedBytes = 0;
157
+ let settled = false;
158
+ const finish = (err, data) => {
159
+ if (settled) return;
160
+ settled = true;
161
+ try {
162
+ zipFile.close();
163
+ } catch (_) {}
164
+ if (err) {
165
+ reject(err);
166
+ } else {
167
+ resolve(data);
168
+ }
169
+ };
170
+
171
+ zipFile.on('entry', (entry) => {
172
+ if (settled) return;
173
+ entryCount += 1;
174
+ const entrySize = Number.isFinite(entry.uncompressedSize) ? entry.uncompressedSize : 0;
175
+ totalUncompressedBytes += entrySize;
176
+ if (entryCount > maxEntryCount) {
177
+ finish(new Error(`压缩包条目过多(>${maxEntryCount})`));
178
+ return;
179
+ }
180
+ if (totalUncompressedBytes > maxUncompressedBytes) {
181
+ finish(new Error(`压缩包解压总大小超限(>${Math.floor(maxUncompressedBytes / 1024 / 1024)}MB)`));
182
+ return;
183
+ }
184
+ zipFile.readEntry();
185
+ });
186
+
187
+ zipFile.on('end', () => {
188
+ finish(null, { entryCount, totalUncompressedBytes });
189
+ });
190
+
191
+ zipFile.on('error', (zipErr) => {
192
+ finish(zipErr);
193
+ });
194
+
195
+ zipFile.readEntry();
196
+ });
197
+ });
198
+ }
199
+
200
+ function writeUploadZipStream(req, prefix, originalName = '', maxSize = MAX_SKILLS_ZIP_UPLOAD_SIZE) {
201
+ return new Promise((resolve, reject) => {
202
+ const lengthHeader = parseInt(req.headers['content-length'] || '0', 10);
203
+ if (Number.isFinite(lengthHeader) && lengthHeader > maxSize) {
204
+ reject(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
205
+ return;
206
+ }
207
+
208
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
209
+ const rawName = originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`;
210
+ const fileName = path.basename(rawName);
211
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
212
+ const stream = fs.createWriteStream(zipPath);
213
+ let bytesWritten = 0;
214
+ let settled = false;
215
+ let hasContent = false;
216
+
217
+ const fail = (err) => {
218
+ if (settled) return;
219
+ settled = true;
220
+ try {
221
+ stream.destroy();
222
+ } catch (_) {}
223
+ try {
224
+ fs.rmSync(tempDir, { recursive: true, force: true });
225
+ } catch (_) {}
226
+ reject(err);
227
+ };
228
+
229
+ const done = () => {
230
+ if (settled) return;
231
+ settled = true;
232
+ if (!hasContent || bytesWritten <= 0) {
233
+ try {
234
+ fs.rmSync(tempDir, { recursive: true, force: true });
235
+ } catch (_) {}
236
+ reject(new Error('备份文件为空'));
237
+ return;
238
+ }
239
+ resolve({ tempDir, zipPath });
240
+ };
241
+
242
+ req.on('error', (err) => fail(err));
243
+ req.on('aborted', () => fail(new Error('上传已中断')));
244
+ req.on('close', () => {
245
+ if (!settled && !req.complete) {
246
+ fail(new Error('上传已中断'));
247
+ }
248
+ });
249
+ stream.on('error', (err) => fail(err));
250
+ req.on('data', (chunk) => {
251
+ if (settled) return;
252
+ hasContent = true;
253
+ bytesWritten += chunk.length;
254
+ if (bytesWritten > maxSize) {
255
+ fail(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
256
+ try {
257
+ req.destroy();
258
+ } catch (_) {}
259
+ return;
260
+ }
261
+ stream.write(chunk);
262
+ });
263
+ req.on('end', () => {
264
+ if (settled) return;
265
+ stream.end(() => done());
266
+ });
267
+ });
268
+ }
269
+
270
+ function writeUploadZip(base64, prefix, originalName = '') {
271
+ let buffer;
272
+ try {
273
+ buffer = Buffer.from(base64 || '', 'base64');
274
+ } catch (_) {
275
+ return { error: '备份文件内容不是有效的 base64 编码' };
276
+ }
277
+
278
+ if (!buffer || buffer.length === 0) {
279
+ return { error: '备份文件为空' };
280
+ }
281
+
282
+ if (buffer.length > MAX_UPLOAD_SIZE) {
283
+ return { error: `备份文件过大(>${Math.floor(MAX_UPLOAD_SIZE / 1024 / 1024)}MB)` };
284
+ }
285
+
286
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
287
+ const fileName = path.basename(originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`);
288
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
289
+ fs.writeFileSync(zipPath, buffer);
290
+ return { tempDir, zipPath };
291
+ }
292
+
293
+ async function extractUploadZip(zipPath, extractDir) {
294
+ resolveUnzipTool();
295
+ ensureDir(extractDir);
296
+ await unzipWithLibrary(zipPath, extractDir);
297
+ }
298
+
299
+ function findConfigSourceDir(extractedDir, markerDirName, requiredFileName) {
300
+ const markerPath = path.join(extractedDir, markerDirName);
301
+ if (fs.existsSync(markerPath) && fs.statSync(markerPath).isDirectory()) {
302
+ return markerPath;
303
+ }
304
+
305
+ const entries = fs.readdirSync(extractedDir, { withFileTypes: true }).filter((item) => item.isDirectory());
306
+ if (entries.length === 1) {
307
+ const onlyDir = path.join(extractedDir, entries[0].name);
308
+ const nestedMarker = path.join(onlyDir, markerDirName);
309
+ if (fs.existsSync(nestedMarker) && fs.statSync(nestedMarker).isDirectory()) {
310
+ return nestedMarker;
311
+ }
312
+ if (fs.existsSync(path.join(onlyDir, requiredFileName))) {
313
+ return onlyDir;
314
+ }
315
+ }
316
+
317
+ if (fs.existsSync(path.join(extractedDir, requiredFileName))) {
318
+ return extractedDir;
319
+ }
320
+
321
+ return extractedDir;
322
+ }
323
+
324
+ async function prepareDirectoryDownload(dirPath, options = {}) {
325
+ const missingMessage = typeof options.missingMessage === 'string' && options.missingMessage.trim()
326
+ ? options.missingMessage.trim()
327
+ : '目录不存在';
328
+ const fileNamePrefix = typeof options.fileNamePrefix === 'string' && options.fileNamePrefix.trim()
329
+ ? options.fileNamePrefix.trim()
330
+ : 'archive';
331
+
332
+ try {
333
+ if (!fs.existsSync(dirPath)) {
334
+ return { error: missingMessage, path: dirPath };
335
+ }
336
+
337
+ const tempDir = os.tmpdir();
338
+ const timestamp = Date.now();
339
+ const zipFileName = `${fileNamePrefix}-${timestamp}.zip`;
340
+ const zipFilePath = path.join(tempDir, zipFileName);
341
+
342
+ const zipTool = resolveZipTool();
343
+ if (zipTool.type === 'zip') {
344
+ const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
345
+ execSync(cmd, { stdio: 'ignore' });
346
+ } else {
347
+ await zipWithLibrary(dirPath, zipFilePath);
348
+ }
349
+
350
+ return {
351
+ success: true,
352
+ downloadPath: zipFilePath,
353
+ fileName: zipFileName,
354
+ sourcePath: dirPath
355
+ };
356
+ } catch (e) {
357
+ return { error: `打包失败:${e.message}` };
358
+ }
359
+ }
360
+
361
+ async function backupDirectoryIfExists(dirPath, prefix) {
362
+ if (!fs.existsSync(dirPath)) {
363
+ return { backupPath: '' };
364
+ }
365
+
366
+ const tempDir = os.tmpdir();
367
+ const timestamp = Date.now();
368
+ const zipFileName = `${prefix}-${timestamp}.zip`;
369
+ const zipFilePath = path.join(tempDir, zipFileName);
370
+ const zipTool = resolveZipTool();
371
+
372
+ try {
373
+ if (zipTool.type === 'zip') {
374
+ const cmd = `"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`;
375
+ execSync(cmd, { stdio: 'ignore' });
376
+ } else {
377
+ await zipWithLibrary(dirPath, zipFilePath);
378
+ }
379
+ return { backupPath: zipFilePath, fileName: zipFileName };
380
+ } catch (e) {
381
+ return { backupPath: '', warning: `备份失败: ${e.message}` };
382
+ }
383
+ }
384
+
385
+ async function restoreConfigDirectoryFromUpload(payload, options) {
386
+ const { targetDir, requiredFileName, markerDirName, tempPrefix, backupPrefix } = options;
387
+ if (!payload || typeof payload.fileBase64 !== 'string' || !payload.fileBase64.trim()) {
388
+ return { error: '缺少备份文件内容' };
389
+ }
390
+
391
+ const upload = writeUploadZip(payload.fileBase64, tempPrefix, payload.fileName);
392
+ if (upload.error) {
393
+ return { error: upload.error };
394
+ }
395
+
396
+ const tempDir = upload.tempDir;
397
+ const extractDir = path.join(tempDir, 'extract');
398
+ let backupPath = '';
399
+ try {
400
+ await extractUploadZip(upload.zipPath, extractDir);
401
+ const sourceDir = findConfigSourceDir(extractDir, markerDirName, requiredFileName);
402
+ const requiredPath = path.join(sourceDir, requiredFileName);
403
+ if (!fs.existsSync(requiredPath)) {
404
+ return { error: `无效备份,缺少 ${requiredFileName}` };
405
+ }
406
+
407
+ const backupResult = await backupDirectoryIfExists(targetDir, backupPrefix);
408
+ backupPath = backupResult.backupPath || '';
409
+
410
+ fs.rmSync(targetDir, { recursive: true, force: true });
411
+ copyDirRecursive(sourceDir, targetDir);
412
+
413
+ return {
414
+ success: true,
415
+ targetDir,
416
+ appliedFrom: payload.fileName || '',
417
+ backupPath,
418
+ backupWarning: backupResult.warning || ''
419
+ };
420
+ } catch (e) {
421
+ return { error: `导入失败:${e.message}` };
422
+ } finally {
423
+ fs.rmSync(tempDir, { recursive: true, force: true });
424
+ }
425
+ }
426
+
427
+ return {
428
+ resolveZipTool,
429
+ resolveUnzipTool,
430
+ zipWithLibrary,
431
+ unzipWithLibrary,
432
+ copyDirRecursive,
433
+ inspectZipArchiveLimits,
434
+ writeUploadZipStream,
435
+ writeUploadZip,
436
+ extractUploadZip,
437
+ findConfigSourceDir,
438
+ prepareDirectoryDownload,
439
+ backupDirectoryIfExists,
440
+ restoreConfigDirectoryFromUpload
441
+ };
442
+ }
443
+
444
+ module.exports = {
445
+ createArchiveHelperController
446
+ };