@steerable/steer 0.0.0-stage → 0.3.13

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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/bin/steer.js +2 -0
  4. package/dist/packages/doc-preview/src/assemble.js +183 -0
  5. package/dist/packages/doc-preview/src/edit-failure.js +116 -0
  6. package/dist/packages/doc-preview/src/edit-service.js +879 -0
  7. package/dist/packages/doc-preview/src/edit.js +437 -0
  8. package/dist/packages/doc-preview/src/export.js +540 -0
  9. package/dist/packages/doc-preview/src/index.js +5 -0
  10. package/dist/packages/doc-preview/src/migrations.js +77 -0
  11. package/dist/packages/doc-preview/src/office-converter.js +186 -0
  12. package/dist/packages/doc-preview/src/office-file-preview.js +457 -0
  13. package/dist/packages/doc-preview/src/office-media.js +80 -0
  14. package/dist/packages/doc-preview/src/office-raster.js +146 -0
  15. package/dist/packages/doc-preview/src/office-routes.js +191 -0
  16. package/dist/packages/doc-preview/src/office-runtime.js +251 -0
  17. package/dist/packages/doc-preview/src/preview.js +296 -0
  18. package/dist/packages/doc-preview/src/render.js +351 -0
  19. package/dist/packages/doc-preview/src/routes.js +376 -0
  20. package/dist/packages/doc-preview/src/settings.js +58 -0
  21. package/dist/packages/doc-preview/src/store.js +134 -0
  22. package/dist/packages/doc-preview/src/tasks.js +16 -0
  23. package/dist/packages/doc-preview/src/word-font.js +232 -0
  24. package/dist/packages/doc-preview/src/word-preview.js +292 -0
  25. package/dist/packages/doc-preview/src/word-render.js +283 -0
  26. package/dist/packages/doc-preview/src/word-routes.js +203 -0
  27. package/dist/packages/doc-preview/src/workspace.js +100 -0
  28. package/dist/products/bundled-python.js +110 -0
  29. package/dist/products/load-locale.js +38 -0
  30. package/dist/products/manifest.json +13 -0
  31. package/dist/products/node-gate.js +132 -0
  32. package/dist/products/steer/active.js +93 -0
  33. package/dist/products/steer/browser-detect.js +230 -0
  34. package/dist/products/steer/browser-protocol.js +2 -0
  35. package/dist/products/steer/browser-session.js +811 -0
  36. package/dist/products/steer/browser.js +521 -0
  37. package/dist/products/steer/cli-main.js +13 -0
  38. package/dist/products/steer/cli.js +8 -0
  39. package/dist/products/steer/computer-macos.js +126 -0
  40. package/dist/products/steer/computer-session.js +118 -0
  41. package/dist/products/steer/computer.js +186 -0
  42. package/dist/products/steer/file-preview.js +392 -0
  43. package/dist/products/steer/locales/shell.zh.json +1120 -0
  44. package/dist/products/steer/locales/zh.json +95 -0
  45. package/dist/products/steer/markdown-preview.js +139 -0
  46. package/dist/products/steer/migrate-legacy-data.js +238 -0
  47. package/dist/products/steer/permissions.js +174 -0
  48. package/dist/products/steer/product.json +85 -0
  49. package/dist/products/steer/server.js +8 -0
  50. package/dist/products/steer/skill-read.js +105 -0
  51. package/dist/products/steer/turn-changes.js +187 -0
  52. package/package.json +38 -4
@@ -0,0 +1,80 @@
1
+ /**
2
+ * 转换前把 OOXML 里内嵌的音视频条目换成空文件。
3
+ *
4
+ * LibreOffice 导出 PDF 时会把内嵌的 mp4 原样写进 PDF 附件,一份 23 页、
5
+ * 版面只有 3 MiB 的演示稿因此转出 84 MiB 的 PDF。预览只需要版面,媒体
6
+ * 与页面图形无关,所以先剥掉。保留空条目而不是删掉条目:幻灯片的关系
7
+ * 文件仍然指向它,缺条目会让关系悬空。
8
+ */
9
+ import { readFileSync, writeFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { unzipSync, zipSync } from 'fflate';
12
+ const ZIP_SIGNATURE = Buffer.from([0x50, 0x4b, 0x03, 0x04]);
13
+ /** 内嵌媒体所在的目录,`ppt/media/` 等。 */
14
+ const MEDIA_DIRECTORIES = ['ppt/media/', 'word/media/', 'xl/media/'];
15
+ /** 只有音视频会被原样搬进 PDF;图片由导出器按目标分辨率重新编码。 */
16
+ const MEDIA_EXTENSIONS = [
17
+ '.mp4',
18
+ '.m4v',
19
+ '.mov',
20
+ '.avi',
21
+ '.wmv',
22
+ '.mkv',
23
+ '.webm',
24
+ '.mp3',
25
+ '.m4a',
26
+ '.aac',
27
+ '.wav',
28
+ '.ogg',
29
+ '.flac',
30
+ '.wma',
31
+ ];
32
+ /**
33
+ * 生成一份不含内嵌音视频的副本。
34
+ *
35
+ * 非 zip(`.doc` / `.ppt` 是 OLE 复合文档)、没有媒体、或写入失败时返回
36
+ * null,调用方继续用原文件转换。
37
+ *
38
+ * @param inputPath 原始 Office 文件
39
+ * @param outDir 临时副本落盘的目录
40
+ * @param fileName 副本文件名
41
+ */
42
+ export function stripOfficeMedia(inputPath, outDir, fileName) {
43
+ const buffer = readFileSync(inputPath);
44
+ if (buffer.length < 4 || !buffer.subarray(0, 4).equals(ZIP_SIGNATURE))
45
+ return null;
46
+ if (!mentionsEmbeddedMedia(buffer))
47
+ return null;
48
+ const stripped = [];
49
+ let removedBytes = 0;
50
+ const entries = unzipSync(buffer, {
51
+ filter: (file) => {
52
+ const name = file.name.toLowerCase();
53
+ const isMedia = MEDIA_DIRECTORIES.some((directory) => name.startsWith(directory));
54
+ if (!isMedia || !MEDIA_EXTENSIONS.some((extension) => name.endsWith(extension))) {
55
+ return true;
56
+ }
57
+ stripped.push(file.name);
58
+ removedBytes += file.originalSize;
59
+ return false;
60
+ },
61
+ });
62
+ if (stripped.length === 0)
63
+ return null;
64
+ for (const name of stripped)
65
+ entries[name] = new Uint8Array(0);
66
+ const filePath = path.join(outDir, fileName);
67
+ // level 0:剩下的条目多是已压缩的图片,重新压缩只花时间不缩体积,而这份
68
+ // 副本只喂给转换器,不落进缓存。
69
+ writeFileSync(filePath, zipSync(entries, { level: 0 }));
70
+ return { filePath, strippedEntries: stripped.length, removedBytes };
71
+ }
72
+ /**
73
+ * 先在原始字节里找媒体目录与扩展名,避免为没有媒体的文件解压整个 zip。
74
+ * 命中也不保证真有媒体,剥完为空时调用方会退回原文件。
75
+ */
76
+ function mentionsEmbeddedMedia(buffer) {
77
+ if (!MEDIA_DIRECTORIES.some((directory) => buffer.includes(directory)))
78
+ return false;
79
+ return MEDIA_EXTENSIONS.some((extension) => buffer.includes(extension));
80
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 把 LibreOffice 导出的 PDF 画成逐页 PNG。
3
+ *
4
+ * 优先用 pdftoppm。macOS 上没有 poppler 时,用系统 PDFKit 编一个小工具再复用。
5
+ */
6
+ import { execFile } from 'node:child_process';
7
+ import { createHash } from 'node:crypto';
8
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { promisify } from 'node:util';
11
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
12
+ const execFileAsync = promisify(execFile);
13
+ const MAC_SOFFICE = '/Applications/LibreOffice.app/Contents/MacOS/soffice';
14
+ const RASTER_TIMEOUT_MS = 180_000;
15
+ const COMPILE_TIMEOUT_MS = 120_000;
16
+ const PDFKIT_SWIFT = `import Foundation
17
+ import PDFKit
18
+ import AppKit
19
+
20
+ let pdfPath = CommandLine.arguments[1]
21
+ let outDir = CommandLine.arguments[2]
22
+ let dpi = CGFloat(Double(CommandLine.arguments[3]) ?? 110)
23
+ let maxPages = Int(CommandLine.arguments[4]) ?? 40
24
+ guard let doc = PDFDocument(url: URL(fileURLWithPath: pdfPath)) else {
25
+ fputs("pdfkit: cannot open pdf\\n", stderr)
26
+ exit(1)
27
+ }
28
+ let scale = dpi / 72.0
29
+ let count = min(doc.pageCount, maxPages)
30
+ for i in 0..<count {
31
+ guard let page = doc.page(at: i) else { continue }
32
+ let bounds = page.bounds(for: .mediaBox)
33
+ let width = max(1, Int((bounds.width * scale).rounded()))
34
+ let height = max(1, Int((bounds.height * scale).rounded()))
35
+ guard let rep = NSBitmapImageRep(
36
+ bitmapDataPlanes: nil,
37
+ pixelsWide: width,
38
+ pixelsHigh: height,
39
+ bitsPerSample: 8,
40
+ samplesPerPixel: 4,
41
+ hasAlpha: true,
42
+ isPlanar: false,
43
+ colorSpaceName: .deviceRGB,
44
+ bytesPerRow: 0,
45
+ bitsPerPixel: 0
46
+ ) else {
47
+ fputs("pdfkit: bitmap failed\\n", stderr)
48
+ exit(2)
49
+ }
50
+ NSGraphicsContext.saveGraphicsState()
51
+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: rep)
52
+ if let ctx = NSGraphicsContext.current?.cgContext {
53
+ ctx.setFillColor(NSColor.white.cgColor)
54
+ ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))
55
+ ctx.saveGState()
56
+ ctx.scaleBy(x: scale, y: scale)
57
+ page.draw(with: .mediaBox, to: ctx)
58
+ ctx.restoreGState()
59
+ }
60
+ NSGraphicsContext.restoreGraphicsState()
61
+ guard let png = rep.representation(using: .png, properties: [:]) else {
62
+ fputs("pdfkit: png failed\\n", stderr)
63
+ exit(3)
64
+ }
65
+ let name = String(format: "page-%03d.png", i + 1)
66
+ try png.write(to: URL(fileURLWithPath: outDir).appendingPathComponent(name))
67
+ }
68
+ `;
69
+ let compileTask = null;
70
+ /** `DEEPPATH_SOFFICE`,否则 macOS 上的 LibreOffice.app,最后才是 PATH 里的 soffice。 */
71
+ export function resolveSofficeCommand() {
72
+ const fromEnv = process.env.DEEPPATH_SOFFICE?.trim();
73
+ if (fromEnv)
74
+ return fromEnv;
75
+ if (process.platform === 'darwin' && existsSync(MAC_SOFFICE))
76
+ return MAC_SOFFICE;
77
+ return 'soffice';
78
+ }
79
+ /** `DEEPPATH_PDFTOPPM`,否则命令名 pdftoppm。 */
80
+ export function resolvePdftoppmCommand() {
81
+ return process.env.DEEPPATH_PDFTOPPM?.trim() || 'pdftoppm';
82
+ }
83
+ function commandOnPath(command) {
84
+ if (command.includes(path.sep))
85
+ return existsSync(command);
86
+ const dirs = (process.env.PATH ?? '').split(path.delimiter);
87
+ return dirs.some((dir) => dir.length > 0 && existsSync(path.join(dir, command)));
88
+ }
89
+ async function ensurePdfKitRaster() {
90
+ if (compileTask)
91
+ return compileTask;
92
+ compileTask = compilePdfKitRaster().catch((err) => {
93
+ compileTask = null;
94
+ throw err;
95
+ });
96
+ return compileTask;
97
+ }
98
+ async function compilePdfKitRaster() {
99
+ const digest = createHash('sha256').update(PDFKIT_SWIFT).digest('hex').slice(0, 12);
100
+ const dir = path.join(getUserDataDir(), 'office-previews', 'tools');
101
+ const bin = path.join(dir, `pdfkit-raster-${digest}`);
102
+ if (existsSync(bin))
103
+ return bin;
104
+ mkdirSync(dir, { recursive: true });
105
+ const source = path.join(dir, `pdfkit-raster-${digest}.swift`);
106
+ writeFileSync(source, PDFKIT_SWIFT, 'utf8');
107
+ try {
108
+ await execFileAsync('swiftc', ['-O', '-o', bin, source], { timeout: COMPILE_TIMEOUT_MS });
109
+ }
110
+ catch (err) {
111
+ const error = err;
112
+ if (error.code === 'ENOENT') {
113
+ throw new Error('找不到 pdftoppm,也没有 swiftc,无法生成预览。请安装 poppler。');
114
+ }
115
+ throw new Error(error.message || '编译 PDF 预览工具失败');
116
+ }
117
+ return bin;
118
+ }
119
+ /**
120
+ * 把 PDF 画进 previewDir,文件名是 page-1.png(pdftoppm)或 page-001.png(PDFKit)。
121
+ *
122
+ * @param maxPages 只画前几页。缺省时 pdftoppm 不限制页数,PDFKit 最多 40 页。
123
+ */
124
+ export async function rasterizePdfDocument(options) {
125
+ const pdftoppm = resolvePdftoppmCommand();
126
+ if (commandOnPath(pdftoppm)) {
127
+ const args = ['-png', '-r', String(options.dpi)];
128
+ if (options.maxPages)
129
+ args.push('-f', '1', '-l', String(options.maxPages));
130
+ args.push(options.pdfPath, path.join(options.previewDir, 'page'));
131
+ await execFileAsync(pdftoppm, args, {
132
+ timeout: RASTER_TIMEOUT_MS,
133
+ maxBuffer: 32 * 1024 * 1024,
134
+ });
135
+ return;
136
+ }
137
+ if (process.platform !== 'darwin') {
138
+ throw new Error('找不到 pdftoppm,无法生成预览。请安装 poppler-utils。');
139
+ }
140
+ const bin = await ensurePdfKitRaster();
141
+ const maxPages = options.maxPages ?? 40;
142
+ await execFileAsync(bin, [options.pdfPath, options.previewDir, String(options.dpi), String(maxPages)], {
143
+ timeout: RASTER_TIMEOUT_MS,
144
+ maxBuffer: 32 * 1024 * 1024,
145
+ });
146
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * 会话里的 PPT / Word 交付文件预览。
3
+ *
4
+ * 前缀:`/api/v2/office-preview`
5
+ */
6
+ import path from 'node:path';
7
+ import { getScopedStore, LOCAL_SCOPE } from '@steerable/agent-shell/storage/driver';
8
+ import { MAX_FILE_BYTES, MAX_PDF_SOURCE_BYTES, OfficePreviewError, ensureOfficeFilePreview, ensureOfficePdfPreview, officeMimeForPath, officePreviewKind, readOfficeFileDownload, readOfficeFilePreviewPage, resolveAllowedOfficeFile, } from './office-file-preview.js';
9
+ import { downloadOfficeRuntime, getOfficeRuntimeSnapshot } from './office-runtime.js';
10
+ function asMessages(messages) {
11
+ return messages.map((message) => ({
12
+ messageMetadata: typeof message.messageMetadata === 'string' ? message.messageMetadata : null,
13
+ }));
14
+ }
15
+ function errorResponse(err) {
16
+ if (err instanceof OfficePreviewError) {
17
+ return {
18
+ status: err.status,
19
+ data: {
20
+ detail: err.message,
21
+ ...(err.code ? { code: err.code } : {}),
22
+ },
23
+ };
24
+ }
25
+ const detail = err instanceof Error ? err.message : String(err);
26
+ return { status: 500, data: { detail } };
27
+ }
28
+ export async function handleOfficePreviewList(query, deps) {
29
+ try {
30
+ const messages = asMessages(await deps.listMessages(query.get('chatId') ?? ''));
31
+ const target = await resolveAllowedOfficeFile({
32
+ chatId: query.get('chatId') ?? '',
33
+ filePath: query.get('path') ?? '',
34
+ messages,
35
+ });
36
+ return { status: 200, data: await ensureOfficeFilePreview(target) };
37
+ }
38
+ catch (err) {
39
+ return errorResponse(err);
40
+ }
41
+ }
42
+ export async function handleOfficePreviewPage(query, deps) {
43
+ try {
44
+ const messages = asMessages(await deps.listMessages(query.get('chatId') ?? ''));
45
+ const target = await resolveAllowedOfficeFile({
46
+ chatId: query.get('chatId') ?? '',
47
+ filePath: query.get('path') ?? '',
48
+ messages,
49
+ });
50
+ const page = Number(query.get('page') ?? '1');
51
+ return { status: 200, data: await readOfficeFilePreviewPage(target, page) };
52
+ }
53
+ catch (err) {
54
+ return errorResponse(err);
55
+ }
56
+ }
57
+ export async function handleOfficePreviewDownload(query, deps) {
58
+ try {
59
+ const messages = asMessages(await deps.listMessages(query.get('chatId') ?? ''));
60
+ const target = await resolveAllowedOfficeFile({
61
+ chatId: query.get('chatId') ?? '',
62
+ filePath: query.get('path') ?? '',
63
+ messages,
64
+ });
65
+ return { status: 200, data: await readOfficeFileDownload(target) };
66
+ }
67
+ catch (err) {
68
+ return errorResponse(err);
69
+ }
70
+ }
71
+ export async function handleOfficePreviewPdfMeta(query, deps) {
72
+ try {
73
+ const chatId = query.get('chatId') ?? '';
74
+ const messages = asMessages(await deps.listMessages(chatId));
75
+ const target = await resolveAllowedOfficeFile({
76
+ chatId,
77
+ filePath: query.get('path') ?? '',
78
+ messages,
79
+ maxBytes: MAX_PDF_SOURCE_BYTES,
80
+ });
81
+ const result = await ensureOfficePdfPreview(target, deps.converter);
82
+ const params = new URLSearchParams({ chatId: target.chatId, path: target.realPath });
83
+ return {
84
+ status: 200,
85
+ data: {
86
+ fileName: result.fileName,
87
+ kind: result.kind,
88
+ path: result.path,
89
+ size: result.size,
90
+ pdfUrl: `/api/v2/office-preview/pdf?${params.toString()}`,
91
+ },
92
+ };
93
+ }
94
+ catch (err) {
95
+ return errorResponse(err);
96
+ }
97
+ }
98
+ export async function handleOfficePreviewPdf(query, deps) {
99
+ try {
100
+ const messages = asMessages(await deps.listMessages(query.get('chatId') ?? ''));
101
+ const target = await resolveAllowedOfficeFile({
102
+ chatId: query.get('chatId') ?? '',
103
+ filePath: query.get('path') ?? '',
104
+ messages,
105
+ maxBytes: MAX_PDF_SOURCE_BYTES,
106
+ });
107
+ const result = await ensureOfficePdfPreview(target, deps.converter);
108
+ const baseName = path.basename(target.fileName, path.extname(target.fileName));
109
+ return {
110
+ status: 200,
111
+ kind: 'file',
112
+ filePath: result.pdfFilePath,
113
+ contentType: 'application/pdf',
114
+ fileName: `${baseName}.pdf`,
115
+ };
116
+ }
117
+ catch (err) {
118
+ return errorResponse(err);
119
+ }
120
+ }
121
+ export async function handleOfficePreviewRaw(query, deps) {
122
+ try {
123
+ const messages = asMessages(await deps.listMessages(query.get('chatId') ?? ''));
124
+ const kind = officePreviewKind(query.get('path') ?? '');
125
+ // 原文件下载与 docx 快速预览都走这条。docx 由 WebView 整份解析,跟逐页
126
+ // PNG 路径共用 80 MiB;PPT / doc 只做下载,上限跟着 PDF 通道。
127
+ const target = await resolveAllowedOfficeFile({
128
+ chatId: query.get('chatId') ?? '',
129
+ filePath: query.get('path') ?? '',
130
+ messages,
131
+ maxBytes: kind === 'word' ? MAX_FILE_BYTES : MAX_PDF_SOURCE_BYTES,
132
+ });
133
+ return {
134
+ status: 200,
135
+ kind: 'file',
136
+ filePath: target.realPath,
137
+ contentType: officeMimeForPath(target.realPath),
138
+ fileName: target.fileName,
139
+ };
140
+ }
141
+ catch (err) {
142
+ return errorResponse(err);
143
+ }
144
+ }
145
+ export function createOfficePreviewRoutes() {
146
+ const deps = {
147
+ listMessages: (chatId) => getScopedStore(LOCAL_SCOPE).listMessages(chatId, 200),
148
+ };
149
+ return [
150
+ {
151
+ method: 'GET',
152
+ path: '/api/v2/office-preview',
153
+ handler: ({ query }) => handleOfficePreviewList(query, deps),
154
+ },
155
+ {
156
+ method: 'GET',
157
+ path: '/api/v2/office-preview/page',
158
+ handler: ({ query }) => handleOfficePreviewPage(query, deps),
159
+ },
160
+ {
161
+ method: 'GET',
162
+ path: '/api/v2/office-preview/download',
163
+ handler: ({ query }) => handleOfficePreviewDownload(query, deps),
164
+ },
165
+ {
166
+ method: 'GET',
167
+ path: '/api/v2/office-preview/pdf-meta',
168
+ handler: ({ query }) => handleOfficePreviewPdfMeta(query, deps),
169
+ },
170
+ {
171
+ method: 'GET',
172
+ path: '/api/v2/office-preview/pdf',
173
+ handler: ({ query }) => handleOfficePreviewPdf(query, deps),
174
+ },
175
+ {
176
+ method: 'GET',
177
+ path: '/api/v2/office-preview/raw',
178
+ handler: ({ query }) => handleOfficePreviewRaw(query, deps),
179
+ },
180
+ {
181
+ method: 'GET',
182
+ path: '/api/v2/office-preview/runtime',
183
+ handler: async () => ({ status: 200, data: getOfficeRuntimeSnapshot() }),
184
+ },
185
+ {
186
+ method: 'POST',
187
+ path: '/api/v2/office-preview/runtime/download',
188
+ handler: async () => ({ status: 200, data: await downloadOfficeRuntime() }),
189
+ },
190
+ ];
191
+ }
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Office 转换引擎发现与按需下载管理。
3
+ *
4
+ * 解析顺序:
5
+ * 1. 环境变量 DEEPPATH_SOFFICE
6
+ * 2. 托管引擎目录 <userDataDir>/office-runtime/current(需带 .complete 标记)
7
+ * 3. 系统默认安装(macOS LibreOffice.app / Windows Program Files / PATH soffice)
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { createHash } from 'node:crypto';
11
+ import { chmodSync, createWriteStream, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { pipeline } from 'node:stream/promises';
14
+ import { Readable } from 'node:stream';
15
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
16
+ const MAC_SOFFICE = '/Applications/LibreOffice.app/Contents/MacOS/soffice';
17
+ const WIN_SOFFICE_CANDIDATES = [
18
+ 'C:\\Program Files\\LibreOffice\\program\\soffice.exe',
19
+ 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe',
20
+ ];
21
+ const COMPLETE_MARKER = '.complete';
22
+ const DEFAULT_MANIFEST_URL = 'https://dl.deeppath.cc/aroli/office-runtime/manifest.json';
23
+ function runtimeRootDir() {
24
+ return path.join(getUserDataDir(), 'office-runtime');
25
+ }
26
+ export function managedRuntimeDir() {
27
+ return path.join(runtimeRootDir(), 'current');
28
+ }
29
+ function commandOnPath(command) {
30
+ if (command.includes(path.sep) || (process.platform === 'win32' && command.includes('/'))) {
31
+ return existsSync(command) ? command : null;
32
+ }
33
+ const exts = process.platform === 'win32' ? ['.exe', '.cmd', '.bat', ''] : [''];
34
+ const dirs = (process.env.PATH ?? '').split(path.delimiter);
35
+ for (const dir of dirs) {
36
+ if (!dir)
37
+ continue;
38
+ for (const ext of exts) {
39
+ const candidate = path.join(dir, `${command}${ext}`);
40
+ if (existsSync(candidate))
41
+ return candidate;
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+ function resolveManagedEngine() {
47
+ const dir = managedRuntimeDir();
48
+ const markerPath = path.join(dir, COMPLETE_MARKER);
49
+ if (!existsSync(markerPath))
50
+ return null;
51
+ try {
52
+ const marker = JSON.parse(readFileSync(markerPath, 'utf8'));
53
+ if (typeof marker.relativeBinary !== 'string' || !marker.relativeBinary)
54
+ return null;
55
+ const bin = path.resolve(dir, marker.relativeBinary);
56
+ if (!bin.startsWith(path.resolve(dir) + path.sep) && bin !== path.resolve(dir))
57
+ return null;
58
+ return existsSync(bin) ? bin : null;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ /**
65
+ * 解析当前可用的 soffice 引擎;全部找不到时返回 null(不抛错)。
66
+ */
67
+ export function resolveOfficeEngine() {
68
+ const fromEnv = process.env.DEEPPATH_SOFFICE?.trim();
69
+ if (fromEnv) {
70
+ const resolved = commandOnPath(fromEnv);
71
+ if (resolved)
72
+ return { source: 'env', sofficePath: resolved };
73
+ }
74
+ const managed = resolveManagedEngine();
75
+ if (managed)
76
+ return { source: 'managed', sofficePath: managed };
77
+ if (process.platform === 'darwin' && existsSync(MAC_SOFFICE)) {
78
+ return { source: 'system', sofficePath: MAC_SOFFICE };
79
+ }
80
+ if (process.platform === 'win32') {
81
+ for (const candidate of WIN_SOFFICE_CANDIDATES) {
82
+ if (existsSync(candidate))
83
+ return { source: 'system', sofficePath: candidate };
84
+ }
85
+ }
86
+ const onPath = commandOnPath('soffice');
87
+ if (onPath)
88
+ return { source: 'system', sofficePath: onPath };
89
+ return null;
90
+ }
91
+ export function currentPlatformKey() {
92
+ if (process.platform === 'darwin') {
93
+ return process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
94
+ }
95
+ if (process.platform === 'win32')
96
+ return 'win32-x64';
97
+ return 'linux-x64';
98
+ }
99
+ let activeDownload = null;
100
+ let lastDownloadState = null;
101
+ export function getOfficeRuntimeSnapshot() {
102
+ const existing = resolveOfficeEngine();
103
+ if (existing) {
104
+ return {
105
+ status: 'ready',
106
+ source: existing.source,
107
+ sofficePath: existing.sofficePath,
108
+ };
109
+ }
110
+ if (lastDownloadState?.status === 'downloading') {
111
+ return { status: 'downloading', progress: lastDownloadState.progress ?? 0 };
112
+ }
113
+ if (lastDownloadState?.status === 'error') {
114
+ return { status: 'error', error: lastDownloadState.error };
115
+ }
116
+ return { status: 'missing' };
117
+ }
118
+ async function defaultExtractArchive(archivePath, targetDir) {
119
+ await new Promise((resolve, reject) => {
120
+ const args = archivePath.endsWith('.zip')
121
+ ? process.platform === 'win32'
122
+ ? ['-xf', archivePath, '-C', targetDir]
123
+ : ['-q', archivePath, '-d', targetDir]
124
+ : ['-xzf', archivePath, '-C', targetDir];
125
+ const cmd = archivePath.endsWith('.zip') && process.platform !== 'win32' ? 'unzip' : 'tar';
126
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
127
+ let stderr = '';
128
+ child.stderr.on('data', (chunk) => {
129
+ stderr += chunk.toString('utf8');
130
+ });
131
+ child.once('error', reject);
132
+ child.once('close', (code) => {
133
+ if (code === 0)
134
+ resolve();
135
+ else
136
+ reject(new Error(stderr.trim() || `${cmd} 退出码 ${code}`));
137
+ });
138
+ });
139
+ }
140
+ async function sha256File(filePath) {
141
+ const hash = createHash('sha256');
142
+ const bytes = readFileSync(filePath);
143
+ hash.update(bytes);
144
+ return hash.digest('hex');
145
+ }
146
+ /**
147
+ * 按需下载并校验托管 Office 转换引擎,原子落盘到 <userDataDir>/office-runtime/current。
148
+ */
149
+ export async function downloadOfficeRuntime(deps = {}) {
150
+ const ready = (deps.resolveEngine ?? resolveOfficeEngine)();
151
+ if (ready) {
152
+ lastDownloadState = null;
153
+ return { status: 'ready', source: ready.source, sofficePath: ready.sofficePath };
154
+ }
155
+ if (activeDownload)
156
+ return activeDownload;
157
+ const task = (async () => {
158
+ lastDownloadState = { status: 'downloading', progress: 0 };
159
+ const fetchFn = deps.fetchImpl ?? fetch;
160
+ const manifestUrl = deps.manifestUrl?.trim() ||
161
+ process.env.DEEPPATH_OFFICE_RUNTIME_MANIFEST_URL?.trim() ||
162
+ DEFAULT_MANIFEST_URL;
163
+ const root = runtimeRootDir();
164
+ mkdirSync(root, { recursive: true });
165
+ const stageDir = mkdtempSync(path.join(root, 'stage-'));
166
+ try {
167
+ const manifestRes = await fetchFn(manifestUrl);
168
+ if (!manifestRes.ok) {
169
+ throw new Error(`无法获取引擎清单 (${manifestRes.status}),请使用系统默认应用打开或手动安装 LibreOffice。`);
170
+ }
171
+ const manifest = (await manifestRes.json());
172
+ const platform = deps.platformKey ?? currentPlatformKey();
173
+ const target = manifest.targets?.[platform];
174
+ if (!target?.url || !target?.sha256 || !target?.relativeBinary) {
175
+ throw new Error(`当前平台 (${platform}) 暂未配置托管引擎包,请安装 LibreOffice 或用默认应用打开。`);
176
+ }
177
+ const archiveExt = target.url.endsWith('.zip') ? '.zip' : '.tar.gz';
178
+ const archivePath = path.join(stageDir, `runtime${archiveExt}`);
179
+ const res = await fetchFn(target.url);
180
+ if (!res.ok || !res.body) {
181
+ throw new Error(`下载引擎失败 (${res.status})`);
182
+ }
183
+ const total = Number(res.headers.get('content-length') ?? target.sizeBytes ?? 0);
184
+ let received = 0;
185
+ const nodeStream = Readable.fromWeb(res.body);
186
+ nodeStream.on('data', (chunk) => {
187
+ received += chunk.byteLength;
188
+ if (total > 0) {
189
+ lastDownloadState = {
190
+ status: 'downloading',
191
+ progress: Math.min(95, Math.round((received / total) * 95)),
192
+ };
193
+ }
194
+ });
195
+ await pipeline(nodeStream, createWriteStream(archivePath));
196
+ const digest = await sha256File(archivePath);
197
+ if (digest.toLowerCase() !== target.sha256.toLowerCase()) {
198
+ throw new Error('引擎安装包 SHA-256 校验失败,已拒绝安装');
199
+ }
200
+ const extractDir = path.join(stageDir, 'unpacked');
201
+ mkdirSync(extractDir, { recursive: true });
202
+ await (deps.extractArchive ?? defaultExtractArchive)(archivePath, extractDir);
203
+ const binaryPath = path.resolve(extractDir, target.relativeBinary);
204
+ if (!existsSync(binaryPath)) {
205
+ throw new Error('引擎解压完成但缺少可执行入口');
206
+ }
207
+ if (process.platform !== 'win32') {
208
+ chmodSync(binaryPath, 0o755);
209
+ }
210
+ writeFileSync(path.join(extractDir, COMPLETE_MARKER), JSON.stringify({ version: manifest.version, relativeBinary: target.relativeBinary }), 'utf8');
211
+ const currentDir = managedRuntimeDir();
212
+ const backupDir = path.join(root, `prev-${process.pid}-${Date.now()}`);
213
+ if (existsSync(currentDir)) {
214
+ renameSync(currentDir, backupDir);
215
+ }
216
+ try {
217
+ renameSync(extractDir, currentDir);
218
+ rmSync(backupDir, { recursive: true, force: true });
219
+ }
220
+ catch (swapErr) {
221
+ if (existsSync(backupDir) && !existsSync(currentDir)) {
222
+ renameSync(backupDir, currentDir);
223
+ }
224
+ throw swapErr;
225
+ }
226
+ lastDownloadState = null;
227
+ const resolved = resolveOfficeEngine();
228
+ if (!resolved) {
229
+ throw new Error('引擎已安装但无法解析可执行路径');
230
+ }
231
+ return { status: 'ready', source: resolved.source, sofficePath: resolved.sofficePath };
232
+ }
233
+ catch (err) {
234
+ const message = err instanceof Error ? err.message : String(err);
235
+ lastDownloadState = { status: 'error', error: message };
236
+ return { status: 'error', error: message };
237
+ }
238
+ finally {
239
+ rmSync(stageDir, { recursive: true, force: true });
240
+ }
241
+ })().finally(() => {
242
+ if (activeDownload === task)
243
+ activeDownload = null;
244
+ });
245
+ activeDownload = task;
246
+ return task;
247
+ }
248
+ export function resetOfficeRuntimeStateForTests() {
249
+ activeDownload = null;
250
+ lastDownloadState = null;
251
+ }