codexmate 0.0.25 → 0.0.26

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 (135) hide show
  1. package/README.md +416 -413
  2. package/README.zh.md +349 -346
  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 +1079 -1079
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +997 -997
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -0
  15. package/cli/session-convert-io.js +82 -0
  16. package/cli/session-convert.js +43 -0
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15218 -14736
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +379 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -92
  32. package/lib/mcp-stdio.js +453 -453
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +74 -74
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +619 -619
  44. package/plugins/prompt-templates/overview.mjs +90 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +625 -612
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.mjs +5 -5
  54. package/web-ui/logic.runtime.mjs +128 -128
  55. package/web-ui/logic.session-convert.mjs +70 -0
  56. package/web-ui/logic.sessions.mjs +709 -614
  57. package/web-ui/modules/api.mjs +90 -90
  58. package/web-ui/modules/app.computed.dashboard.mjs +171 -128
  59. package/web-ui/modules/app.computed.index.mjs +17 -17
  60. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  61. package/web-ui/modules/app.computed.session.mjs +946 -670
  62. package/web-ui/modules/app.constants.mjs +15 -15
  63. package/web-ui/modules/app.methods.agents.mjs +632 -632
  64. package/web-ui/modules/app.methods.claude-config.mjs +179 -174
  65. package/web-ui/modules/app.methods.codex-config.mjs +860 -784
  66. package/web-ui/modules/app.methods.index.mjs +92 -92
  67. package/web-ui/modules/app.methods.install.mjs +205 -205
  68. package/web-ui/modules/app.methods.navigation.mjs +743 -695
  69. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  70. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  71. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  72. package/web-ui/modules/app.methods.providers.mjs +404 -404
  73. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  74. package/web-ui/modules/app.methods.session-actions.mjs +596 -544
  75. package/web-ui/modules/app.methods.session-browser.mjs +985 -722
  76. package/web-ui/modules/app.methods.session-timeline.mjs +479 -448
  77. package/web-ui/modules/app.methods.session-trash.mjs +424 -424
  78. package/web-ui/modules/app.methods.startup-claude.mjs +522 -417
  79. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  80. package/web-ui/modules/config-mode.computed.mjs +124 -124
  81. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  82. package/web-ui/modules/i18n.dict.mjs +2113 -2055
  83. package/web-ui/modules/i18n.mjs +56 -56
  84. package/web-ui/modules/plugins.computed.mjs +3 -3
  85. package/web-ui/modules/plugins.methods.mjs +3 -3
  86. package/web-ui/modules/plugins.storage.mjs +11 -11
  87. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  88. package/web-ui/modules/skills.computed.mjs +107 -107
  89. package/web-ui/modules/skills.methods.mjs +481 -481
  90. package/web-ui/partials/index/layout-footer.html +13 -13
  91. package/web-ui/partials/index/layout-header.html +475 -475
  92. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  93. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  94. package/web-ui/partials/index/modal-health-check.html +45 -45
  95. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  96. package/web-ui/partials/index/modal-skills.html +200 -200
  97. package/web-ui/partials/index/modals-basic.html +165 -165
  98. package/web-ui/partials/index/panel-config-claude.html +184 -179
  99. package/web-ui/partials/index/panel-config-codex.html +283 -283
  100. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  101. package/web-ui/partials/index/panel-dashboard.html +186 -186
  102. package/web-ui/partials/index/panel-docs.html +147 -147
  103. package/web-ui/partials/index/panel-market.html +177 -177
  104. package/web-ui/partials/index/panel-orchestration.html +391 -391
  105. package/web-ui/partials/index/panel-plugins.html +279 -279
  106. package/web-ui/partials/index/panel-sessions.html +326 -303
  107. package/web-ui/partials/index/panel-settings.html +258 -258
  108. package/web-ui/partials/index/panel-usage.html +342 -361
  109. package/web-ui/res/json5.min.js +1 -1
  110. package/web-ui/res/vue.global.prod.js +13 -13
  111. package/web-ui/session-helpers.mjs +576 -573
  112. package/web-ui/source-bundle.cjs +233 -233
  113. package/web-ui/styles/base-theme.css +268 -264
  114. package/web-ui/styles/controls-forms.css +423 -423
  115. package/web-ui/styles/dashboard.css +274 -274
  116. package/web-ui/styles/docs-panel.css +247 -247
  117. package/web-ui/styles/feedback.css +108 -108
  118. package/web-ui/styles/health-check-dialog.css +144 -144
  119. package/web-ui/styles/layout-shell.css +603 -603
  120. package/web-ui/styles/modals-core.css +464 -464
  121. package/web-ui/styles/navigation-panels.css +390 -390
  122. package/web-ui/styles/openclaw-structured.css +266 -266
  123. package/web-ui/styles/plugins-panel.css +523 -523
  124. package/web-ui/styles/responsive.css +454 -454
  125. package/web-ui/styles/sessions-list.css +415 -398
  126. package/web-ui/styles/sessions-preview.css +411 -411
  127. package/web-ui/styles/sessions-toolbar-trash.css +330 -268
  128. package/web-ui/styles/sessions-usage.css +945 -912
  129. package/web-ui/styles/settings-panel.css +166 -166
  130. package/web-ui/styles/skills-list.css +303 -303
  131. package/web-ui/styles/skills-market.css +406 -406
  132. package/web-ui/styles/task-orchestration.css +822 -822
  133. package/web-ui/styles/titles-cards.css +408 -408
  134. package/web-ui/styles.css +21 -21
  135. package/web-ui.html +17 -17
@@ -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
+ };