@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,232 @@
1
+ /**
2
+ * Word HTML 预览的字体子集服务。
3
+ *
4
+ * 前端 HTML 预览优先使用用户本机字体;本机缺失时,按当前 DOCX 的实际
5
+ * 文本内容生成 WOFF2 子集,避免下载全量中文字体。
6
+ *
7
+ * 默认使用 gateway 镜像内的开源近似字体:
8
+ * 仿宋_GB2312 -> AR PL UMing CN
9
+ * 楷体_GB2312 -> AR PL UKai CN
10
+ * 黑体 -> WenQuanYi Zen Hei
11
+ * 方正小标宋 -> AR PL UMing CN(近似)
12
+ * 宋体 -> AR PL UMing CN
13
+ *
14
+ * 如果部署方有授权字体,可通过环境变量覆盖为真实字体:
15
+ * DEEPPATH_WORD_FONT_FANGSONG / _KAITI / _HEI / _XIAOBIAOSONG / _SONG
16
+ * 以及 DEEPPATH_WORD_FONT_<KEY>_FACE 指定 TTC face。
17
+ */
18
+ import { execFile } from 'node:child_process';
19
+ import { createHash } from 'node:crypto';
20
+ import { existsSync } from 'node:fs';
21
+ import { mkdir, readFile, stat } from 'node:fs/promises';
22
+ import path from 'node:path';
23
+ import { promisify } from 'node:util';
24
+ import { listSkillRoots } from '@steerable/agent-shell/local-backend/skill-loader';
25
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
26
+ import { SAFE_CHAT_ID } from './preview.js';
27
+ import { getChatWordWorkspace, resolveWordPythonCommand, SAFE_DOCUMENT_ID, WORD_DOCX_FILENAME, WORD_PREVIEW_DIRNAME, } from './workspace.js';
28
+ const execFileAsync = promisify(execFile);
29
+ const SUBSET_TIMEOUT_MS = 120_000;
30
+ export class WordFontDependencyError extends Error {
31
+ constructor(message) {
32
+ super(message);
33
+ this.name = 'WordFontDependencyError';
34
+ }
35
+ }
36
+ const FONT_SOURCES = [
37
+ {
38
+ family: 'fangsong',
39
+ paths: [
40
+ '/usr/share/fonts/truetype/word/simfang.ttf',
41
+ '/data/deeppath-team/fonts-src/simfang.ttf',
42
+ '/usr/share/fonts/truetype/arphic/uming.ttc',
43
+ ],
44
+ defaultFace: 0,
45
+ envSuffix: 'FANGSONG',
46
+ },
47
+ {
48
+ family: 'kaiti',
49
+ paths: [
50
+ '/usr/share/fonts/truetype/word/simkai.ttf',
51
+ '/data/deeppath-team/fonts-src/simkai.ttf',
52
+ '/usr/share/fonts/truetype/arphic/ukai.ttc',
53
+ ],
54
+ defaultFace: 0,
55
+ envSuffix: 'KAITI',
56
+ },
57
+ {
58
+ family: 'hei',
59
+ paths: [
60
+ '/usr/share/fonts/truetype/word/simhei.ttf',
61
+ '/data/deeppath-team/fonts-src/simhei.ttf',
62
+ '/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc',
63
+ ],
64
+ defaultFace: 0,
65
+ envSuffix: 'HEI',
66
+ },
67
+ {
68
+ family: 'xiaobiaosong',
69
+ paths: [
70
+ '/usr/share/fonts/truetype/word/FZXiaoBiaoSong-B05S.ttf',
71
+ '/data/deeppath-team/fonts-src/FZXiaoBiaoSong.ttf',
72
+ '/usr/share/fonts/truetype/arphic/uming.ttc',
73
+ ],
74
+ defaultFace: 0,
75
+ envSuffix: 'XIAOBIAOSONG',
76
+ },
77
+ {
78
+ family: 'song',
79
+ paths: [
80
+ '/usr/share/fonts/truetype/word/simsun.ttf',
81
+ '/data/deeppath-team/fonts-src/simsun.ttf',
82
+ '/usr/share/fonts/truetype/arphic/uming.ttc',
83
+ ],
84
+ defaultFace: 0,
85
+ envSuffix: 'SONG',
86
+ },
87
+ ];
88
+ export const WORD_FONT_FAMILIES = new Set(FONT_SOURCES.map((source) => source.family));
89
+ function sourceConfig(family) {
90
+ const config = FONT_SOURCES.find((item) => item.family === family);
91
+ if (!config)
92
+ throw new Error(`unsupported word font family: ${family}`);
93
+ return config;
94
+ }
95
+ function resolveSourcePath(family) {
96
+ const config = sourceConfig(family);
97
+ const configured = process.env[`DEEPPATH_WORD_FONT_${config.envSuffix}`]?.trim();
98
+ const configuredFace = process.env[`DEEPPATH_WORD_FONT_${config.envSuffix}_FACE`]?.trim();
99
+ const face = configuredFace && Number.isFinite(Number(configuredFace))
100
+ ? Math.max(0, Math.trunc(Number(configuredFace)))
101
+ : config.defaultFace;
102
+ if (configured) {
103
+ return { source: configured, face };
104
+ }
105
+ const source = config.paths.find((candidate) => existsSync(candidate)) ?? config.paths[0];
106
+ return { source, face };
107
+ }
108
+ function resolveWordMasterSkillDir() {
109
+ const candidates = [
110
+ ...[...listSkillRoots()].reverse(),
111
+ process.env.DEEPPATH_WORD_SKILL_DIR?.trim(),
112
+ process.env.DEEPPATH_TEAM_SKILLS_DIR?.trim(),
113
+ path.resolve(getUserDataDir(), '..', '..', 'skills'),
114
+ ].filter((root) => Boolean(root));
115
+ for (const root of candidates) {
116
+ const candidate = path.join(root, 'word-master');
117
+ if (existsSync(path.join(candidate, 'scripts', 'subset_font.py'))) {
118
+ return candidate;
119
+ }
120
+ }
121
+ return null;
122
+ }
123
+ const fontLocks = new Map();
124
+ async function withFontLock(key, task) {
125
+ const previous = fontLocks.get(key) ?? Promise.resolve();
126
+ let release;
127
+ const gate = new Promise((resolve) => {
128
+ release = resolve;
129
+ });
130
+ const tail = previous.then(() => gate);
131
+ fontLocks.set(key, tail);
132
+ await previous;
133
+ try {
134
+ return await task();
135
+ }
136
+ finally {
137
+ release();
138
+ if (fontLocks.get(key) === tail)
139
+ fontLocks.delete(key);
140
+ }
141
+ }
142
+ /**
143
+ * 生成/读取指定文档的字体子集。
144
+ */
145
+ export async function readWordFontSubset(chatId, documentId, familyRaw) {
146
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
147
+ return null;
148
+ if (!SAFE_DOCUMENT_ID.test(documentId))
149
+ return null;
150
+ if (!WORD_FONT_FAMILIES.has(familyRaw))
151
+ return null;
152
+ const family = familyRaw;
153
+ const documentPath = path.join(getChatWordWorkspace(chatId), documentId);
154
+ const docxPath = path.join(documentPath, WORD_DOCX_FILENAME);
155
+ let docxStat;
156
+ try {
157
+ docxStat = await stat(docxPath);
158
+ if (!docxStat.isFile())
159
+ return null;
160
+ }
161
+ catch {
162
+ return null;
163
+ }
164
+ const { source, face } = resolveSourcePath(family);
165
+ if (!existsSync(source)) {
166
+ throw new WordFontDependencyError(`缺少字体源文件:${source}。可通过 DEEPPATH_WORD_FONT_${sourceConfig(family).envSuffix} 覆盖。`);
167
+ }
168
+ const sourceTag = createHash('sha1')
169
+ .update(`${source}\u0000${face}`)
170
+ .digest('hex')
171
+ .slice(0, 8);
172
+ const cacheDir = path.join(documentPath, WORD_PREVIEW_DIRNAME, 'fonts');
173
+ const cachePath = path.join(cacheDir, `${family}.${sourceTag}.${Math.max(0, Math.round(docxStat.mtimeMs))}.woff2`);
174
+ const loadCache = async () => {
175
+ try {
176
+ const buffer = await readFile(cachePath);
177
+ return {
178
+ family,
179
+ mime: 'font/woff2',
180
+ base64: buffer.toString('base64'),
181
+ bytes: buffer.length,
182
+ };
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ };
188
+ const cached = await loadCache();
189
+ if (cached)
190
+ return cached;
191
+ const lockKey = `${chatId}\u0000${documentId}\u0000${family}`;
192
+ return withFontLock(lockKey, async () => {
193
+ const cachedAgain = await loadCache();
194
+ if (cachedAgain)
195
+ return cachedAgain;
196
+ const skillDir = resolveWordMasterSkillDir();
197
+ if (!skillDir) {
198
+ throw new WordFontDependencyError('未找到 word-master 技能目录或 subset_font.py');
199
+ }
200
+ const scriptPath = path.join(skillDir, 'scripts', 'subset_font.py');
201
+ const python = resolveWordPythonCommand();
202
+ mkdir(cacheDir, { recursive: true });
203
+ try {
204
+ await execFileAsync(python, [
205
+ scriptPath,
206
+ '--source',
207
+ source,
208
+ '--font-number',
209
+ String(face),
210
+ '--docx',
211
+ docxPath,
212
+ '--output',
213
+ cachePath,
214
+ ], { timeout: SUBSET_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 });
215
+ }
216
+ catch (err) {
217
+ const error = err;
218
+ if (error.code === 'ENOENT') {
219
+ throw new WordFontDependencyError(`缺少字体子集依赖:找不到 ${python}。请确认 word-master venv 已安装 fonttools 和 brotli。`);
220
+ }
221
+ const detail = error.stderr ? error.stderr.toString().trim() : '';
222
+ throw new Error(detail || error.message || '字体子集生成失败');
223
+ }
224
+ const buffer = await readFile(cachePath);
225
+ return {
226
+ family,
227
+ mime: 'font/woff2',
228
+ base64: buffer.toString('base64'),
229
+ bytes: buffer.length,
230
+ };
231
+ });
232
+ }
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Word 文档预览的数据源 —— 按会话隔离,扫描 `files/<chatId>/word/`。
3
+ *
4
+ * Word 产物目录结构:
5
+ * files/<chatId>/word/<documentId>/
6
+ * ├── document.docx
7
+ * ├── content.json
8
+ * ├── meta.json
9
+ * ├── preview/manifest.json
10
+ * ├── preview/page-001.png
11
+ * └── validation/word_format_report.json
12
+ *
13
+ * 这里只负责“列出文档 / 读取页图 / 读取 DOCX / 检测 word-master 调用”。
14
+ * DOCX → PDF → PNG 的实际转换在 word-render.ts 中完成;列表接口按需调用它。
15
+ */
16
+ import { readFile, readdir, stat } from 'node:fs/promises';
17
+ import path from 'node:path';
18
+ import { SAFE_CHAT_ID } from './preview.js';
19
+ import { ensureWordPreview } from './word-render.js';
20
+ import { getChatWordWorkspace, SAFE_DOCUMENT_ID, SAFE_PAGE_FILE, WORD_DOCX_FILENAME, WORD_PREVIEW_DIRNAME, WORD_PREVIEW_MANIFEST_FILENAME, } from './workspace.js';
21
+ export { SAFE_DOCUMENT_ID, SAFE_PAGE_FILE };
22
+ function isPathInside(parent, child) {
23
+ const rel = path.relative(path.resolve(parent), path.resolve(child));
24
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
25
+ }
26
+ function asRecord(value) {
27
+ return value && typeof value === 'object' ? value : {};
28
+ }
29
+ function readString(value) {
30
+ return typeof value === 'string' && value.trim() ? value.trim() : null;
31
+ }
32
+ /** 只用于 Content-Disposition 的展示文件名,不参与磁盘路径拼接。 */
33
+ export function safeDownloadFileName(title) {
34
+ const cleaned = title.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim();
35
+ return (cleaned || 'word-document').slice(0, 120);
36
+ }
37
+ async function readJsonFile(filePath) {
38
+ try {
39
+ const text = await readFile(filePath, 'utf8');
40
+ return JSON.parse(text);
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ async function readMeta(documentPath) {
47
+ return readJsonFile(path.join(documentPath, 'meta.json'));
48
+ }
49
+ /**
50
+ * content.json 里的议案标题(中文)。模型出件时偶尔只写了 content.json 而漏写
51
+ * meta.json.title;展示名不能因为这一处遗漏就回退成 ASCII 目录名。
52
+ */
53
+ async function readContentTitle(documentPath) {
54
+ const content = await readJsonFile(path.join(documentPath, 'content.json'));
55
+ return readString(content?.title);
56
+ }
57
+ /**
58
+ * 用户可见的文档名(列表标签 + 下载文件名):
59
+ * `meta.json.title` → `content.json.title` → `documentId`。
60
+ *
61
+ * `documentId` 受 SAFE_DOCUMENT_ID 限制只能是 ASCII(目录名/磁盘路径),所以
62
+ * 中文展示名必须来自 meta.json.title 或 content.json.title,目录名只作最后兜底。
63
+ */
64
+ async function resolveDocumentTitle(documentPath, documentId, meta) {
65
+ return readString(meta?.title) ?? (await readContentTitle(documentPath)) ?? documentId;
66
+ }
67
+ async function readManifest(documentPath) {
68
+ return readJsonFile(path.join(documentPath, WORD_PREVIEW_DIRNAME, WORD_PREVIEW_MANIFEST_FILENAME));
69
+ }
70
+ function normalizePages(documentPath, manifest) {
71
+ const raw = Array.isArray(manifest?.pages) ? manifest.pages : [];
72
+ return raw
73
+ .map((page, index) => {
74
+ const record = asRecord(page);
75
+ const file = readString(record.file);
76
+ if (!file || !SAFE_PAGE_FILE.test(file))
77
+ return null;
78
+ const width = typeof record.width === 'number' ? record.width : 0;
79
+ const height = typeof record.height === 'number' ? record.height : 0;
80
+ const pageIndex = typeof record.index === 'number' && Number.isFinite(record.index) && record.index > 0
81
+ ? record.index
82
+ : index + 1;
83
+ return {
84
+ index: pageIndex,
85
+ file,
86
+ width: Math.max(0, Math.round(width)),
87
+ height: Math.max(0, Math.round(height)),
88
+ mtimeMs: 0,
89
+ };
90
+ })
91
+ .filter((page) => page !== null)
92
+ .sort((a, b) => a.index - b.index);
93
+ }
94
+ function normalizeValidation(meta) {
95
+ const validation = meta?.validation;
96
+ if (!validation || typeof validation !== 'object')
97
+ return null;
98
+ return {
99
+ ok: validation.ok === true,
100
+ checkedAt: readString(validation.checkedAt),
101
+ reportPath: readString(validation.reportPath),
102
+ };
103
+ }
104
+ /**
105
+ * 扫描当前会话的 Word 文档。
106
+ *
107
+ * @param opts.ensurePreview 是否顺便补齐/刷新预览(列表接口使用 true)。
108
+ * @param opts.force 是否强制重新渲染预览(手动刷新按钮使用)。
109
+ */
110
+ export async function listWordDocuments(chatId, opts = {}) {
111
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
112
+ return [];
113
+ let entries;
114
+ try {
115
+ entries = await readdir(getChatWordWorkspace(chatId), { withFileTypes: true });
116
+ }
117
+ catch {
118
+ return [];
119
+ }
120
+ const documents = [];
121
+ for (const entry of entries) {
122
+ if (!entry.isDirectory())
123
+ continue;
124
+ const documentId = entry.name;
125
+ if (!SAFE_DOCUMENT_ID.test(documentId))
126
+ continue;
127
+ const documentPath = path.join(getChatWordWorkspace(chatId), documentId);
128
+ const docxPath = path.join(documentPath, WORD_DOCX_FILENAME);
129
+ let docxStat;
130
+ try {
131
+ docxStat = await stat(docxPath);
132
+ if (!docxStat.isFile())
133
+ continue;
134
+ }
135
+ catch {
136
+ continue;
137
+ }
138
+ const meta = await readMeta(documentPath);
139
+ let previewError = null;
140
+ if (opts.ensurePreview) {
141
+ try {
142
+ await ensureWordPreview(chatId, documentId, { force: opts.force });
143
+ }
144
+ catch (err) {
145
+ previewError = err instanceof Error ? err.message : String(err);
146
+ }
147
+ }
148
+ const manifest = await readManifest(documentPath);
149
+ const pages = normalizePages(documentPath, manifest);
150
+ // 页图 mtime 用于前端做“同页内容是否变化”的轻量判断。
151
+ for (const page of pages) {
152
+ try {
153
+ const info = await stat(path.join(documentPath, WORD_PREVIEW_DIRNAME, page.file));
154
+ page.mtimeMs = Math.max(0, Math.round(info.mtimeMs));
155
+ }
156
+ catch {
157
+ page.mtimeMs = 0;
158
+ }
159
+ }
160
+ const updatedAtCandidates = [
161
+ docxStat.mtimeMs,
162
+ typeof meta?.updatedAt === 'string' ? Date.parse(meta.updatedAt) : Number.NaN,
163
+ pages.reduce((max, page) => Math.max(max, page.mtimeMs), 0),
164
+ ].filter((value) => Number.isFinite(value) && value > 0);
165
+ documents.push({
166
+ documentId,
167
+ documentPath,
168
+ title: await resolveDocumentTitle(documentPath, documentId, meta),
169
+ template: readString(meta?.template),
170
+ status: pages.length > 0
171
+ ? 'preview_ready'
172
+ : previewError || readString(manifest?.error)
173
+ ? 'preview_failed'
174
+ : 'preview_pending',
175
+ docxPath,
176
+ docxMtimeMs: Math.max(0, Math.round(docxStat.mtimeMs)),
177
+ updatedAt: updatedAtCandidates.length
178
+ ? Math.max(...updatedAtCandidates)
179
+ : Math.max(0, Math.round(docxStat.mtimeMs)),
180
+ pageCount: pages.length,
181
+ validation: normalizeValidation(meta),
182
+ preview: {
183
+ manifestPath: pages.length > 0
184
+ ? path.join(documentPath, WORD_PREVIEW_DIRNAME, WORD_PREVIEW_MANIFEST_FILENAME)
185
+ : null,
186
+ pages,
187
+ error: previewError ?? readString(manifest?.error),
188
+ },
189
+ });
190
+ }
191
+ documents.sort((a, b) => b.updatedAt - a.updatedAt || b.documentId.localeCompare(a.documentId, 'zh-CN'));
192
+ return documents;
193
+ }
194
+ /** 供 turn hook 做轻量变更检测:只看 documentId + DOCX mtime。 */
195
+ export function wordDocumentsSignature(documents) {
196
+ return documents
197
+ .map((doc) => `${doc.documentId}@${doc.docxMtimeMs}`)
198
+ .sort()
199
+ .join('|');
200
+ }
201
+ /** 读取单页预览 PNG;返回 base64,前端直接拼 data URI。 */
202
+ export async function readWordPreviewPage(chatId, documentId, pageFile) {
203
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
204
+ return null;
205
+ if (!SAFE_DOCUMENT_ID.test(documentId))
206
+ return null;
207
+ if (!SAFE_PAGE_FILE.test(pageFile))
208
+ return null;
209
+ const documentPath = path.join(getChatWordWorkspace(chatId), documentId);
210
+ const pagePath = path.join(documentPath, WORD_PREVIEW_DIRNAME, pageFile);
211
+ if (!isPathInside(documentPath, pagePath))
212
+ return null;
213
+ try {
214
+ const buffer = await readFile(pagePath);
215
+ const manifest = await readManifest(documentPath);
216
+ const pages = normalizePages(documentPath, manifest);
217
+ const page = pages.find((item) => item.file === pageFile)?.index ?? 1;
218
+ return {
219
+ mime: 'image/png',
220
+ base64: buffer.toString('base64'),
221
+ page,
222
+ pageCount: pages.length,
223
+ };
224
+ }
225
+ catch {
226
+ return null;
227
+ }
228
+ }
229
+ /** 读取 DOCX 文件,供前端下载。 */
230
+ export async function readWordDocument(chatId, documentId) {
231
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
232
+ return null;
233
+ if (!SAFE_DOCUMENT_ID.test(documentId))
234
+ return null;
235
+ const documentPath = path.join(getChatWordWorkspace(chatId), documentId);
236
+ const docxPath = path.join(documentPath, WORD_DOCX_FILENAME);
237
+ if (!isPathInside(documentPath, docxPath))
238
+ return null;
239
+ try {
240
+ const buffer = await readFile(docxPath);
241
+ const meta = await readMeta(documentPath);
242
+ const title = await resolveDocumentTitle(documentPath, documentId, meta);
243
+ return {
244
+ fileName: `${safeDownloadFileName(title)}.docx`,
245
+ base64: buffer.toString('base64'),
246
+ size: buffer.length,
247
+ };
248
+ }
249
+ catch {
250
+ return null;
251
+ }
252
+ }
253
+ /**
254
+ * 判断一次工具调用是否在处理逻辑里调用了 word-master。
255
+ * 与 `isPptMasterToolCall` 同款:技能工具、技能脚本命令、技能/工作区路径
256
+ * 都可能命中;宁可多广播一次,也不要漏掉 Word 预览刷新。
257
+ */
258
+ export function isWordMasterToolCall(tool, args) {
259
+ if (!args || typeof args !== 'object')
260
+ return false;
261
+ // 1) skill 工具显式加载 word-master。
262
+ if (typeof tool === 'string' && /skill/i.test(tool)) {
263
+ const candidates = [
264
+ args.name,
265
+ args.skill,
266
+ args.skillName,
267
+ args.skill_name,
268
+ args.skillId,
269
+ args.id,
270
+ ];
271
+ if (candidates.some((value) => typeof value === 'string' && /word[-_ ]?master/i.test(value))) {
272
+ return true;
273
+ }
274
+ }
275
+ // 2) shell / snippet / 文件读写参数里出现 word-master 或 files/<chatId>/word/。
276
+ const fields = [
277
+ args.command,
278
+ args.code,
279
+ args.path,
280
+ args.target,
281
+ args.file,
282
+ args.cwd,
283
+ ];
284
+ const haystack = fields
285
+ .filter((value) => typeof value === 'string')
286
+ .join('\n');
287
+ if (/word[-_ ]?master/i.test(haystack))
288
+ return true;
289
+ if (/(^|[\\/])word([\\/]|$)/i.test(haystack))
290
+ return true;
291
+ return false;
292
+ }