codexmate 0.0.32 → 0.0.34

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 (148) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +230 -224
  4. package/cli/archive-helpers.js +453 -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 +556 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -69
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -150
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/update.js +171 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16079 -15829
  25. package/lib/automation.js +404 -404
  26. package/lib/cli-file-utils.js +151 -151
  27. package/lib/cli-models-utils.js +440 -440
  28. package/lib/cli-network-utils.js +190 -190
  29. package/lib/cli-path-utils.js +85 -85
  30. package/lib/cli-session-utils.js +121 -121
  31. package/lib/cli-sessions.js +427 -426
  32. package/lib/cli-utils.js +155 -155
  33. package/lib/cli-webhook.js +154 -126
  34. package/lib/download-artifacts.js +92 -92
  35. package/lib/mcp-stdio.js +453 -453
  36. package/lib/task-orchestrator.js +869 -869
  37. package/lib/text-diff.js +303 -303
  38. package/lib/win-tray.js +119 -0
  39. package/lib/workflow-engine.js +340 -340
  40. package/package.json +76 -76
  41. package/plugins/README.md +20 -20
  42. package/plugins/README.zh-CN.md +20 -20
  43. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  44. package/plugins/prompt-templates/computed.mjs +253 -253
  45. package/plugins/prompt-templates/index.mjs +8 -8
  46. package/plugins/prompt-templates/manifest.mjs +15 -15
  47. package/plugins/prompt-templates/methods.mjs +553 -553
  48. package/plugins/prompt-templates/overview.mjs +91 -91
  49. package/plugins/prompt-templates/ownership.mjs +19 -19
  50. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  51. package/plugins/prompt-templates/storage.mjs +64 -64
  52. package/plugins/registry.mjs +16 -16
  53. package/web-ui/app.js +654 -647
  54. package/web-ui/index.html +37 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +172 -168
  57. package/web-ui/logic.codex.mjs +69 -69
  58. package/web-ui/logic.mjs +5 -5
  59. package/web-ui/logic.runtime.mjs +128 -128
  60. package/web-ui/logic.session-convert.mjs +70 -70
  61. package/web-ui/logic.sessions.mjs +781 -781
  62. package/web-ui/modules/api.mjs +90 -90
  63. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  64. package/web-ui/modules/app.computed.index.mjs +17 -17
  65. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  66. package/web-ui/modules/app.computed.session.mjs +735 -693
  67. package/web-ui/modules/app.constants.mjs +15 -15
  68. package/web-ui/modules/app.methods.agents.mjs +651 -651
  69. package/web-ui/modules/app.methods.claude-config.mjs +306 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +869 -861
  71. package/web-ui/modules/app.methods.index.mjs +94 -94
  72. package/web-ui/modules/app.methods.install.mjs +205 -205
  73. package/web-ui/modules/app.methods.navigation.mjs +788 -774
  74. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  75. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  76. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  77. package/web-ui/modules/app.methods.providers.mjs +575 -529
  78. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  79. package/web-ui/modules/app.methods.session-actions.mjs +591 -591
  80. package/web-ui/modules/app.methods.session-browser.mjs +1011 -1012
  81. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  82. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  83. package/web-ui/modules/app.methods.startup-claude.mjs +547 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +87 -79
  86. package/web-ui/modules/config-mode.computed.mjs +124 -124
  87. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  88. package/web-ui/modules/i18n.dict.mjs +3195 -3177
  89. package/web-ui/modules/i18n.mjs +62 -62
  90. package/web-ui/modules/plugins.computed.mjs +3 -3
  91. package/web-ui/modules/plugins.methods.mjs +3 -3
  92. package/web-ui/modules/plugins.storage.mjs +11 -11
  93. package/web-ui/modules/provider-url-display.mjs +17 -17
  94. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  95. package/web-ui/modules/skills.computed.mjs +107 -107
  96. package/web-ui/modules/skills.methods.mjs +482 -482
  97. package/web-ui/partials/index/layout-footer.html +13 -13
  98. package/web-ui/partials/index/layout-header.html +499 -503
  99. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  100. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  101. package/web-ui/partials/index/modal-health-check.html +45 -45
  102. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  103. package/web-ui/partials/index/modal-skills.html +200 -200
  104. package/web-ui/partials/index/modal-webhook.html +42 -0
  105. package/web-ui/partials/index/modals-basic.html +223 -162
  106. package/web-ui/partials/index/panel-config-claude.html +155 -136
  107. package/web-ui/partials/index/panel-config-codex.html +176 -196
  108. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  109. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  110. package/web-ui/partials/index/panel-dashboard.html +186 -219
  111. package/web-ui/partials/index/panel-docs.html +114 -114
  112. package/web-ui/partials/index/panel-market.html +177 -177
  113. package/web-ui/partials/index/panel-orchestration.html +391 -391
  114. package/web-ui/partials/index/panel-plugins.html +253 -253
  115. package/web-ui/partials/index/panel-sessions.html +319 -313
  116. package/web-ui/partials/index/panel-settings.html +158 -190
  117. package/web-ui/partials/index/panel-trash.html +82 -82
  118. package/web-ui/partials/index/panel-usage.html +137 -137
  119. package/web-ui/res/json5.min.js +1 -1
  120. package/web-ui/res/vue.global.prod.js +13 -13
  121. package/web-ui/session-helpers.mjs +591 -591
  122. package/web-ui/source-bundle.cjs +233 -233
  123. package/web-ui/styles/base-theme.css +281 -281
  124. package/web-ui/styles/bridge-pool.css +266 -197
  125. package/web-ui/styles/controls-forms.css +433 -433
  126. package/web-ui/styles/dashboard.css +406 -406
  127. package/web-ui/styles/docs-panel.css +245 -245
  128. package/web-ui/styles/feedback.css +108 -108
  129. package/web-ui/styles/health-check-dialog.css +144 -144
  130. package/web-ui/styles/layout-shell.css +628 -638
  131. package/web-ui/styles/modals-core.css +499 -466
  132. package/web-ui/styles/navigation-panels.css +391 -391
  133. package/web-ui/styles/openclaw-structured.css +266 -266
  134. package/web-ui/styles/plugins-panel.css +564 -564
  135. package/web-ui/styles/responsive.css +392 -392
  136. package/web-ui/styles/sessions-list.css +683 -647
  137. package/web-ui/styles/sessions-preview.css +407 -407
  138. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  139. package/web-ui/styles/sessions-usage.css +588 -588
  140. package/web-ui/styles/settings-panel.css +415 -349
  141. package/web-ui/styles/skills-list.css +305 -305
  142. package/web-ui/styles/skills-market.css +429 -429
  143. package/web-ui/styles/task-orchestration.css +822 -822
  144. package/web-ui/styles/titles-cards.css +472 -472
  145. package/web-ui/styles/trash-panel.css +90 -90
  146. package/web-ui/styles/webhook.css +115 -81
  147. package/web-ui/styles.css +24 -24
  148. package/web-ui.html +17 -17
@@ -1,446 +1,453 @@
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
+ execFileSync,
8
+ zipLib,
9
+ yauzl,
10
+ ensureDir,
11
+ isPathInside,
12
+ commandExists,
13
+ MAX_UPLOAD_SIZE,
14
+ MAX_SKILLS_ZIP_UPLOAD_SIZE,
15
+ MAX_SKILLS_ZIP_ENTRY_COUNT,
16
+ MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES
17
+ } = deps;
18
+
19
+ if (!fs) throw new Error('createArchiveHelperController 缺少 fs');
20
+ if (!path) throw new Error('createArchiveHelperController 缺少 path');
21
+ if (!os) throw new Error('createArchiveHelperController 缺少 os');
22
+ if (typeof execSync !== 'function') throw new Error('createArchiveHelperController 缺少 execSync');
23
+ if (!zipLib) throw new Error('createArchiveHelperController 缺少 zipLib');
24
+ if (!yauzl) throw new Error('createArchiveHelperController 缺少 yauzl');
25
+ if (typeof ensureDir !== 'function') throw new Error('createArchiveHelperController 缺少 ensureDir');
26
+ if (typeof isPathInside !== 'function') throw new Error('createArchiveHelperController 缺少 isPathInside');
27
+ if (typeof commandExists !== 'function') throw new Error('createArchiveHelperController 缺少 commandExists');
28
+
29
+ const ZIP_PATHS = ['zip'];
30
+
31
+ function findZipExecutable() {
32
+ for (const candidate of ZIP_PATHS) {
33
+ try {
34
+ if (candidate === 'zip') {
35
+ if (commandExists('zip', '--help')) {
36
+ return 'zip';
37
+ }
38
+ } else if (fs.existsSync(candidate)) {
39
+ return candidate;
40
+ }
41
+ } catch (_) {}
42
+ }
43
+ return null;
44
+ }
45
+
46
+ function resolveZipTool() {
47
+ const zipExe = findZipExecutable();
48
+ if (zipExe) {
49
+ return { type: 'zip', cmd: zipExe };
50
+ }
51
+ return { type: 'lib', cmd: 'zip-lib' };
52
+ }
53
+
54
+ function resolveUnzipTool() {
55
+ return { type: 'lib', cmd: 'zip-lib' };
56
+ }
57
+
58
+ async function zipWithLibrary(absPath, outputPath) {
59
+ const stat = fs.lstatSync(absPath);
60
+ if (stat.isDirectory()) {
61
+ await zipLib.archiveFolder(absPath, outputPath);
62
+ return;
63
+ }
64
+ await zipLib.archiveFile(absPath, outputPath);
65
+ }
66
+
67
+ async function unzipWithLibrary(zipPath, outputDir) {
68
+ await zipLib.extract(zipPath, outputDir);
69
+ }
70
+
71
+ function copyDirRecursive(srcDir, destDir, options = {}) {
72
+ const dereferenceSymlinks = !!(options && options.dereferenceSymlinks);
73
+ const allowedRootRealPath = (options && typeof options.allowedRootRealPath === 'string')
74
+ ? options.allowedRootRealPath
75
+ : '';
76
+ const visitedRealPaths = options && options.visitedRealPaths instanceof Set
77
+ ? options.visitedRealPaths
78
+ : new Set();
79
+ const childOptions = {
80
+ ...options,
81
+ dereferenceSymlinks,
82
+ allowedRootRealPath,
83
+ visitedRealPaths
84
+ };
85
+ ensureDir(destDir);
86
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
87
+ for (const entry of entries) {
88
+ const srcPath = path.join(srcDir, entry.name);
89
+ const destPath = path.join(destDir, entry.name);
90
+ if (entry.isDirectory()) {
91
+ if (!dereferenceSymlinks) {
92
+ copyDirRecursive(srcPath, destPath, childOptions);
93
+ continue;
94
+ }
95
+ const realPath = fs.realpathSync(srcPath);
96
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
97
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
98
+ }
99
+ if (visitedRealPaths.has(realPath)) {
100
+ continue;
101
+ }
102
+ visitedRealPaths.add(realPath);
103
+ try {
104
+ copyDirRecursive(srcPath, destPath, childOptions);
105
+ } finally {
106
+ visitedRealPaths.delete(realPath);
107
+ }
108
+ } else if (entry.isSymbolicLink()) {
109
+ if (dereferenceSymlinks) {
110
+ const realPath = fs.realpathSync(srcPath);
111
+ if (allowedRootRealPath && !isPathInside(realPath, allowedRootRealPath)) {
112
+ throw new Error(`symlink escapes skill root: ${srcPath}`);
113
+ }
114
+ const realStat = fs.statSync(realPath);
115
+ if (realStat.isDirectory()) {
116
+ if (visitedRealPaths.has(realPath)) {
117
+ continue;
118
+ }
119
+ visitedRealPaths.add(realPath);
120
+ try {
121
+ copyDirRecursive(realPath, destPath, childOptions);
122
+ } finally {
123
+ visitedRealPaths.delete(realPath);
124
+ }
125
+ } else {
126
+ fs.copyFileSync(realPath, destPath);
127
+ }
128
+ } else {
129
+ const target = fs.readlinkSync(srcPath);
130
+ fs.symlinkSync(target, destPath);
131
+ }
132
+ } else {
133
+ fs.copyFileSync(srcPath, destPath);
134
+ }
135
+ }
136
+ }
137
+
138
+ function inspectZipArchiveLimits(zipPath, options = {}) {
139
+ const maxEntryCount = Number.isFinite(options.maxEntryCount) && options.maxEntryCount > 0
140
+ ? Math.floor(options.maxEntryCount)
141
+ : MAX_SKILLS_ZIP_ENTRY_COUNT;
142
+ const maxUncompressedBytes = Number.isFinite(options.maxUncompressedBytes) && options.maxUncompressedBytes > 0
143
+ ? Math.floor(options.maxUncompressedBytes)
144
+ : MAX_SKILLS_ZIP_UNCOMPRESSED_BYTES;
145
+
146
+ return new Promise((resolve, reject) => {
147
+ yauzl.open(zipPath, { lazyEntries: true, autoClose: true }, (openErr, zipFile) => {
148
+ if (openErr) {
149
+ reject(openErr);
150
+ return;
151
+ }
152
+ if (!zipFile) {
153
+ reject(new Error('无法读取 ZIP 文件'));
154
+ return;
155
+ }
156
+ let entryCount = 0;
157
+ let totalUncompressedBytes = 0;
158
+ let settled = false;
159
+ const finish = (err, data) => {
160
+ if (settled) return;
161
+ settled = true;
162
+ try {
163
+ zipFile.close();
164
+ } catch (_) {}
165
+ if (err) {
166
+ reject(err);
167
+ } else {
168
+ resolve(data);
169
+ }
170
+ };
171
+
172
+ zipFile.on('entry', (entry) => {
173
+ if (settled) return;
174
+ entryCount += 1;
175
+ const entrySize = Number.isFinite(entry.uncompressedSize) ? entry.uncompressedSize : 0;
176
+ totalUncompressedBytes += entrySize;
177
+ if (entryCount > maxEntryCount) {
178
+ finish(new Error(`压缩包条目过多(>${maxEntryCount})`));
179
+ return;
180
+ }
181
+ if (totalUncompressedBytes > maxUncompressedBytes) {
182
+ finish(new Error(`压缩包解压总大小超限(>${Math.floor(maxUncompressedBytes / 1024 / 1024)}MB)`));
183
+ return;
184
+ }
185
+ zipFile.readEntry();
186
+ });
187
+
188
+ zipFile.on('end', () => {
189
+ finish(null, { entryCount, totalUncompressedBytes });
190
+ });
191
+
192
+ zipFile.on('error', (zipErr) => {
193
+ finish(zipErr);
194
+ });
195
+
196
+ zipFile.readEntry();
197
+ });
198
+ });
199
+ }
200
+
201
+ function writeUploadZipStream(req, prefix, originalName = '', maxSize = MAX_SKILLS_ZIP_UPLOAD_SIZE) {
202
+ return new Promise((resolve, reject) => {
203
+ const lengthHeader = parseInt(req.headers['content-length'] || '0', 10);
204
+ if (Number.isFinite(lengthHeader) && lengthHeader > maxSize) {
205
+ reject(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
206
+ return;
207
+ }
208
+
209
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
210
+ const rawName = originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`;
211
+ const fileName = path.basename(rawName);
212
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
213
+ const stream = fs.createWriteStream(zipPath);
214
+ let bytesWritten = 0;
215
+ let settled = false;
216
+ let hasContent = false;
217
+
218
+ const fail = (err) => {
219
+ if (settled) return;
220
+ settled = true;
221
+ try {
222
+ stream.destroy();
223
+ } catch (_) {}
224
+ try {
225
+ fs.rmSync(tempDir, { recursive: true, force: true });
226
+ } catch (_) {}
227
+ reject(err);
228
+ };
229
+
230
+ const done = () => {
231
+ if (settled) return;
232
+ settled = true;
233
+ if (!hasContent || bytesWritten <= 0) {
234
+ try {
235
+ fs.rmSync(tempDir, { recursive: true, force: true });
236
+ } catch (_) {}
237
+ reject(new Error('备份文件为空'));
238
+ return;
239
+ }
240
+ resolve({ tempDir, zipPath });
241
+ };
242
+
243
+ req.on('error', (err) => fail(err));
244
+ req.on('aborted', () => fail(new Error('上传已中断')));
245
+ req.on('close', () => {
246
+ if (!settled && !req.complete) {
247
+ fail(new Error('上传已中断'));
248
+ }
249
+ });
250
+ stream.on('error', (err) => fail(err));
251
+ req.on('data', (chunk) => {
252
+ if (settled) return;
253
+ hasContent = true;
254
+ bytesWritten += chunk.length;
255
+ if (bytesWritten > maxSize) {
256
+ fail(new Error(`备份文件过大(>${Math.floor(maxSize / 1024 / 1024)}MB)`));
257
+ try {
258
+ req.destroy();
259
+ } catch (_) {}
260
+ return;
261
+ }
262
+ stream.write(chunk);
263
+ });
264
+ req.on('end', () => {
265
+ if (settled) return;
266
+ stream.end(() => done());
267
+ });
268
+ });
269
+ }
270
+
271
+ function writeUploadZip(base64, prefix, originalName = '') {
272
+ let buffer;
273
+ try {
274
+ buffer = Buffer.from(base64 || '', 'base64');
275
+ } catch (_) {
276
+ return { error: '备份文件内容不是有效的 base64 编码' };
277
+ }
278
+
279
+ if (!buffer || buffer.length === 0) {
280
+ return { error: '备份文件为空' };
281
+ }
282
+
283
+ if (buffer.length > MAX_UPLOAD_SIZE) {
284
+ return { error: `备份文件过大(>${Math.floor(MAX_UPLOAD_SIZE / 1024 / 1024)}MB)` };
285
+ }
286
+
287
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`));
288
+ const fileName = path.basename(originalName && typeof originalName === 'string' ? originalName : `${prefix}.zip`);
289
+ const zipPath = path.join(tempDir, fileName.toLowerCase().endsWith('.zip') ? fileName : `${fileName}.zip`);
290
+ fs.writeFileSync(zipPath, buffer);
291
+ return { tempDir, zipPath };
292
+ }
293
+
294
+ async function extractUploadZip(zipPath, extractDir) {
295
+ resolveUnzipTool();
296
+ ensureDir(extractDir);
297
+ await unzipWithLibrary(zipPath, extractDir);
298
+ }
299
+
300
+ function findConfigSourceDir(extractedDir, markerDirName, requiredFileName) {
301
+ const markerPath = path.join(extractedDir, markerDirName);
302
+ if (fs.existsSync(markerPath) && fs.statSync(markerPath).isDirectory()) {
303
+ return markerPath;
304
+ }
305
+
306
+ const entries = fs.readdirSync(extractedDir, { withFileTypes: true }).filter((item) => item.isDirectory());
307
+ if (entries.length === 1) {
308
+ const onlyDir = path.join(extractedDir, entries[0].name);
309
+ const nestedMarker = path.join(onlyDir, markerDirName);
310
+ if (fs.existsSync(nestedMarker) && fs.statSync(nestedMarker).isDirectory()) {
311
+ return nestedMarker;
312
+ }
313
+ if (fs.existsSync(path.join(onlyDir, requiredFileName))) {
314
+ return onlyDir;
315
+ }
316
+ }
317
+
318
+ if (fs.existsSync(path.join(extractedDir, requiredFileName))) {
319
+ return extractedDir;
320
+ }
321
+
322
+ return extractedDir;
323
+ }
324
+
325
+ async function prepareDirectoryDownload(dirPath, options = {}) {
326
+ const missingMessage = typeof options.missingMessage === 'string' && options.missingMessage.trim()
327
+ ? options.missingMessage.trim()
328
+ : '目录不存在';
329
+ const fileNamePrefix = typeof options.fileNamePrefix === 'string' && options.fileNamePrefix.trim()
330
+ ? options.fileNamePrefix.trim()
331
+ : 'archive';
332
+
333
+ try {
334
+ if (!fs.existsSync(dirPath)) {
335
+ return { error: missingMessage, path: dirPath };
336
+ }
337
+
338
+ const tempDir = os.tmpdir();
339
+ const timestamp = Date.now();
340
+ const zipFileName = `${fileNamePrefix}-${timestamp}.zip`;
341
+ const zipFilePath = path.join(tempDir, zipFileName);
342
+
343
+ const zipTool = resolveZipTool();
344
+ if (zipTool.type === 'zip') {
345
+ if (typeof execFileSync === 'function') {
346
+ execFileSync(zipTool.cmd, ['-0', '-q', '-r', zipFilePath, dirPath], { stdio: 'ignore' });
347
+ } else {
348
+ execSync(`"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`, { stdio: 'ignore' });
349
+ }
350
+ } else {
351
+ await zipWithLibrary(dirPath, zipFilePath);
352
+ }
353
+
354
+ return {
355
+ success: true,
356
+ downloadPath: zipFilePath,
357
+ fileName: zipFileName,
358
+ sourcePath: dirPath
359
+ };
360
+ } catch (e) {
361
+ return { error: `打包失败:${e.message}` };
362
+ }
363
+ }
364
+
365
+ async function backupDirectoryIfExists(dirPath, prefix) {
366
+ if (!fs.existsSync(dirPath)) {
367
+ return { backupPath: '' };
368
+ }
369
+
370
+ const tempDir = os.tmpdir();
371
+ const timestamp = Date.now();
372
+ const zipFileName = `${prefix}-${timestamp}.zip`;
373
+ const zipFilePath = path.join(tempDir, zipFileName);
374
+ const zipTool = resolveZipTool();
375
+
376
+ try {
377
+ if (zipTool.type === 'zip') {
378
+ if (typeof execFileSync === 'function') {
379
+ execFileSync(zipTool.cmd, ['-0', '-q', '-r', zipFilePath, dirPath], { stdio: 'ignore' });
380
+ } else {
381
+ execSync(`"${zipTool.cmd}" -0 -q -r "${zipFilePath}" "${dirPath}"`, { stdio: 'ignore' });
382
+ }
383
+ } else {
384
+ await zipWithLibrary(dirPath, zipFilePath);
385
+ }
386
+ return { backupPath: zipFilePath, fileName: zipFileName };
387
+ } catch (e) {
388
+ return { backupPath: '', warning: `备份失败: ${e.message}` };
389
+ }
390
+ }
391
+
392
+ async function restoreConfigDirectoryFromUpload(payload, options) {
393
+ const { targetDir, requiredFileName, markerDirName, tempPrefix, backupPrefix } = options;
394
+ if (!payload || typeof payload.fileBase64 !== 'string' || !payload.fileBase64.trim()) {
395
+ return { error: '缺少备份文件内容' };
396
+ }
397
+
398
+ const upload = writeUploadZip(payload.fileBase64, tempPrefix, payload.fileName);
399
+ if (upload.error) {
400
+ return { error: upload.error };
401
+ }
402
+
403
+ const tempDir = upload.tempDir;
404
+ const extractDir = path.join(tempDir, 'extract');
405
+ let backupPath = '';
406
+ try {
407
+ await extractUploadZip(upload.zipPath, extractDir);
408
+ const sourceDir = findConfigSourceDir(extractDir, markerDirName, requiredFileName);
409
+ const requiredPath = path.join(sourceDir, requiredFileName);
410
+ if (!fs.existsSync(requiredPath)) {
411
+ return { error: `无效备份,缺少 ${requiredFileName}` };
412
+ }
413
+
414
+ const backupResult = await backupDirectoryIfExists(targetDir, backupPrefix);
415
+ backupPath = backupResult.backupPath || '';
416
+
417
+ fs.rmSync(targetDir, { recursive: true, force: true });
418
+ copyDirRecursive(sourceDir, targetDir);
419
+
420
+ return {
421
+ success: true,
422
+ targetDir,
423
+ appliedFrom: payload.fileName || '',
424
+ backupPath,
425
+ backupWarning: backupResult.warning || ''
426
+ };
427
+ } catch (e) {
428
+ return { error: `导入失败:${e.message}` };
429
+ } finally {
430
+ fs.rmSync(tempDir, { recursive: true, force: true });
431
+ }
432
+ }
433
+
434
+ return {
435
+ resolveZipTool,
436
+ resolveUnzipTool,
437
+ zipWithLibrary,
438
+ unzipWithLibrary,
439
+ copyDirRecursive,
440
+ inspectZipArchiveLimits,
441
+ writeUploadZipStream,
442
+ writeUploadZip,
443
+ extractUploadZip,
444
+ findConfigSourceDir,
445
+ prepareDirectoryDownload,
446
+ backupDirectoryIfExists,
447
+ restoreConfigDirectoryFromUpload
448
+ };
449
+ }
450
+
451
+ module.exports = {
452
+ createArchiveHelperController
453
+ };