codexmate 0.0.31 → 0.0.32

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