@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,283 @@
1
+ /**
2
+ * Word 预览渲染 —— 把 word-master 生成的 DOCX 转成逐页 PNG。
3
+ *
4
+ * 方案:
5
+ * DOCX --(LibreOffice headless)--> PDF --(pdftoppm,macOS 没有 poppler 时用 PDFKit)--> preview/page-001.png
6
+ *
7
+ * 产物写入:
8
+ * files/<chatId>/word/<documentId>/preview/
9
+ * ├── manifest.json
10
+ * ├── page-001.png
11
+ * └── ...
12
+ *
13
+ * 转换全部在宿主进程完成;模型只需要生成 DOCX,不需要自己调用 LibreOffice。
14
+ * 这样也能保证预览与最终 DOCX 的 mtime 对齐,避免 stale 预览。
15
+ */
16
+ import { execFile } from 'node:child_process';
17
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
18
+ import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { promisify } from 'node:util';
22
+ import { rasterizePdfDocument, resolveSofficeCommand } from './office-raster.js';
23
+ import { getChatWordWorkspace, SAFE_DOCUMENT_ID, WORD_DOCX_FILENAME, WORD_PREVIEW_DIRNAME, WORD_PREVIEW_MANIFEST_FILENAME, } from './workspace.js';
24
+ const execFileAsync = promisify(execFile);
25
+ const SOFFICE_TIMEOUT_MS = 180_000;
26
+ const PREVIEW_DPI = 110;
27
+ export class WordRenderDependencyError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = 'WordRenderDependencyError';
31
+ }
32
+ }
33
+ async function runExec(file, args, options) {
34
+ try {
35
+ await execFileAsync(file, args, {
36
+ timeout: options.timeoutMs,
37
+ maxBuffer: 32 * 1024 * 1024,
38
+ env: options.env,
39
+ });
40
+ }
41
+ catch (err) {
42
+ const error = err;
43
+ if (error.code === 'ENOENT') {
44
+ throw new WordRenderDependencyError(`缺少 Word 预览依赖:找不到 ${file}。请在 gateway 运行镜像中安装 libreoffice-writer / poppler-utils。`);
45
+ }
46
+ const detail = [error.stderr, error.stdout]
47
+ .map((value) => (value ? value.toString().trim() : ''))
48
+ .filter(Boolean)
49
+ .join('\n');
50
+ const tail = detail ? detail.split('\n').slice(-8).join('\n') : '';
51
+ throw new Error(tail || error.message || `${file} 执行失败`);
52
+ }
53
+ }
54
+ function parsePngSize(filePath) {
55
+ try {
56
+ const buffer = readFileSync(filePath);
57
+ if (buffer.length < 24)
58
+ return null;
59
+ // PNG signature + IHDR: width/height 位于 offset 16/20,big-endian。
60
+ const signature = buffer.subarray(0, 8).toString('hex');
61
+ if (signature !== '89504e470d0a1a0a')
62
+ return null;
63
+ const width = buffer.readUInt32BE(16);
64
+ const height = buffer.readUInt32BE(20);
65
+ return { width, height };
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
71
+ function listRasterPages(previewDir) {
72
+ const entries = readdirSync(previewDir);
73
+ return entries
74
+ .map((name) => {
75
+ const match = name.match(/^page-(\d+)\.png$/i);
76
+ if (!match)
77
+ return null;
78
+ return { source: name, page: Number.parseInt(match[1], 10) };
79
+ })
80
+ .filter((item) => item !== null)
81
+ .sort((a, b) => a.page - b.page);
82
+ }
83
+ function normalizePageFileName(index) {
84
+ return `page-${String(index).padStart(3, '0')}.png`;
85
+ }
86
+ async function readManifest(documentPath) {
87
+ try {
88
+ const text = await readFile(path.join(documentPath, WORD_PREVIEW_DIRNAME, WORD_PREVIEW_MANIFEST_FILENAME), 'utf8');
89
+ return JSON.parse(text);
90
+ }
91
+ catch {
92
+ return null;
93
+ }
94
+ }
95
+ async function previewIsCurrent(documentPath, docxMtimeMs) {
96
+ const manifest = await readManifest(documentPath);
97
+ if (!manifest || manifest.docxMtimeMs !== docxMtimeMs)
98
+ return false;
99
+ if (!Array.isArray(manifest.pages) || manifest.pages.length === 0)
100
+ return false;
101
+ for (const page of manifest.pages) {
102
+ if (!existsSync(path.join(documentPath, WORD_PREVIEW_DIRNAME, page.file))) {
103
+ return false;
104
+ }
105
+ }
106
+ return true;
107
+ }
108
+ /**
109
+ * 每个文档一把串行锁;同一文档的重复刷新请求合并到第一次转换之后。
110
+ */
111
+ const renderLocks = new Map();
112
+ async function withDocumentLock(key, task) {
113
+ const previous = renderLocks.get(key) ?? Promise.resolve();
114
+ let release;
115
+ const gate = new Promise((resolve) => {
116
+ release = resolve;
117
+ });
118
+ const tail = previous.then(() => gate);
119
+ renderLocks.set(key, tail);
120
+ await previous;
121
+ try {
122
+ return await task();
123
+ }
124
+ finally {
125
+ release();
126
+ if (renderLocks.get(key) === tail) {
127
+ renderLocks.delete(key);
128
+ }
129
+ }
130
+ }
131
+ /**
132
+ * 确保某个 Word 文档有最新预览。`force = true` 时跳过 mtime 判断强制重转。
133
+ */
134
+ export async function ensureWordPreview(chatId, documentId, opts = {}) {
135
+ if (!SAFE_DOCUMENT_ID.test(documentId)) {
136
+ throw new Error(`invalid documentId: ${documentId}`);
137
+ }
138
+ const documentPath = path.join(getChatWordWorkspace(chatId), documentId);
139
+ const docxPath = path.join(documentPath, WORD_DOCX_FILENAME);
140
+ const docxStat = await stat(docxPath);
141
+ if (!docxStat.isFile()) {
142
+ throw new Error('document.docx not found');
143
+ }
144
+ const docxMtimeMs = Math.max(0, Math.round(docxStat.mtimeMs));
145
+ if (!opts.force && (await previewIsCurrent(documentPath, docxMtimeMs))) {
146
+ const manifest = await readManifest(documentPath);
147
+ if (manifest)
148
+ return manifest;
149
+ }
150
+ const key = `${chatId}\u0000${documentId}`;
151
+ return withDocumentLock(key, async () => {
152
+ // 拿锁后再检查一次,避免并发请求重复转换。
153
+ if (!opts.force && (await previewIsCurrent(documentPath, docxMtimeMs))) {
154
+ const manifest = await readManifest(documentPath);
155
+ if (manifest)
156
+ return manifest;
157
+ }
158
+ const previewDir = path.join(documentPath, WORD_PREVIEW_DIRNAME);
159
+ mkdirSync(previewDir, { recursive: true });
160
+ const tmpDir = await mkdtemp(path.join(os.tmpdir(), 'word-preview-'));
161
+ const profileDir = path.join(tmpDir, 'lo-profile');
162
+ mkdirSync(profileDir, { recursive: true });
163
+ try {
164
+ const soffice = resolveSofficeCommand();
165
+ await runExec(soffice, [
166
+ `-env:UserInstallation=file://${profileDir}`,
167
+ '--headless',
168
+ '--norestore',
169
+ '--convert-to',
170
+ 'pdf',
171
+ '--outdir',
172
+ tmpDir,
173
+ docxPath,
174
+ ], {
175
+ timeoutMs: SOFFICE_TIMEOUT_MS,
176
+ env: {
177
+ ...process.env,
178
+ HOME: tmpDir,
179
+ XDG_CACHE_HOME: path.join(tmpDir, 'cache'),
180
+ XDG_CONFIG_HOME: path.join(tmpDir, 'config'),
181
+ },
182
+ });
183
+ const pdfPath = path.join(tmpDir, `${path.basename(docxPath, path.extname(docxPath))}.pdf`);
184
+ if (!existsSync(pdfPath)) {
185
+ throw new Error('LibreOffice 未生成 PDF,请检查 DOCX 是否合法');
186
+ }
187
+ // 清掉旧页图,避免上一次多出来的页残留。
188
+ for (const name of readdirSync(previewDir)) {
189
+ if (/^page-\d+\.png$/i.test(name)) {
190
+ rmSync(path.join(previewDir, name), { force: true });
191
+ }
192
+ }
193
+ await rasterizePdfDocument({
194
+ pdfPath,
195
+ previewDir,
196
+ dpi: PREVIEW_DPI,
197
+ });
198
+ // pdftoppm 默认生成 page-1.png / page-01.png;统一重命名为 page-001.png。
199
+ const rasterPages = listRasterPages(previewDir);
200
+ const pages = [];
201
+ for (let i = 0; i < rasterPages.length; i += 1) {
202
+ const sourcePath = path.join(previewDir, rasterPages[i].source);
203
+ const targetName = normalizePageFileName(i + 1);
204
+ const targetPath = path.join(previewDir, targetName);
205
+ if (sourcePath !== targetPath) {
206
+ renameSync(sourcePath, targetPath);
207
+ }
208
+ const size = parsePngSize(targetPath);
209
+ pages.push({
210
+ index: i + 1,
211
+ file: targetName,
212
+ width: size?.width ?? 0,
213
+ height: size?.height ?? 0,
214
+ });
215
+ }
216
+ if (pages.length === 0) {
217
+ throw new Error('未生成任何预览页,请检查 LibreOffice / poppler 是否可用');
218
+ }
219
+ const manifest = {
220
+ documentId,
221
+ docxMtimeMs,
222
+ dpi: PREVIEW_DPI,
223
+ pages,
224
+ generatedAt: new Date().toISOString(),
225
+ };
226
+ writeFileSync(path.join(previewDir, WORD_PREVIEW_MANIFEST_FILENAME), JSON.stringify(manifest, null, 2), 'utf8');
227
+ // meta.json 是可选增强:写入预览状态,便于列表页直接展示。
228
+ try {
229
+ const metaPath = path.join(documentPath, 'meta.json');
230
+ let meta = {};
231
+ if (existsSync(metaPath)) {
232
+ try {
233
+ meta = JSON.parse(readFileSync(metaPath, 'utf8'));
234
+ }
235
+ catch {
236
+ meta = {};
237
+ }
238
+ }
239
+ meta.preview = {
240
+ status: 'ready',
241
+ pageCount: pages.length,
242
+ updatedAt: new Date().toISOString(),
243
+ docxMtimeMs,
244
+ };
245
+ writeFileSync(metaPath, JSON.stringify(meta, null, 2), 'utf8');
246
+ }
247
+ catch {
248
+ // meta 写入失败不影响预览本身。
249
+ }
250
+ return manifest;
251
+ }
252
+ finally {
253
+ await rm(tmpDir, { recursive: true, force: true });
254
+ }
255
+ });
256
+ }
257
+ /** 刷新一个会话下所有 Word 文档的预览。返回成功/失败计数。 */
258
+ export async function refreshWordPreviews(chatId) {
259
+ const root = getChatWordWorkspace(chatId);
260
+ let entries;
261
+ try {
262
+ entries = await readdir(root, { withFileTypes: true });
263
+ }
264
+ catch {
265
+ return { refreshed: 0, failed: 0, errors: [] };
266
+ }
267
+ let refreshed = 0;
268
+ let failed = 0;
269
+ const errors = [];
270
+ for (const entry of entries) {
271
+ if (!entry.isDirectory() || !SAFE_DOCUMENT_ID.test(entry.name))
272
+ continue;
273
+ try {
274
+ await ensureWordPreview(chatId, entry.name, { force: true });
275
+ refreshed += 1;
276
+ }
277
+ catch (err) {
278
+ failed += 1;
279
+ errors.push(`${entry.name}: ${err instanceof Error ? err.message : String(err)}`);
280
+ }
281
+ }
282
+ return { refreshed, failed, errors };
283
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * etown 包 Word 预览相关 local-backend 路由。
3
+ *
4
+ * 前缀:`/api/v2/word-preview`
5
+ *
6
+ * 职责:
7
+ * - 列出当前会话 Word 文档;
8
+ * - 读取单页 PNG;
9
+ * - 下载 DOCX;
10
+ * - 手动刷新预览;
11
+ * - MVP 修改入口:返回一段可发回主聊天的修改指令。
12
+ */
13
+ import { readWordFontSubset } from './word-font.js';
14
+ import { listWordDocuments, readWordDocument, readWordPreviewPage, } from './word-preview.js';
15
+ import { ensureWordPreview } from './word-render.js';
16
+ import { SAFE_DOCUMENT_ID } from './workspace.js';
17
+ function asRecord(body) {
18
+ if (!body || typeof body !== 'object')
19
+ return {};
20
+ return body;
21
+ }
22
+ function errorMessage(err) {
23
+ return err instanceof Error ? err.message : String(err);
24
+ }
25
+ export function buildWordEditInstruction(input) {
26
+ const lines = [
27
+ '【Word 文档修改请求】',
28
+ `文档目录:${input.documentPath}`,
29
+ `文档文件:${input.docxPath}`,
30
+ ];
31
+ if (input.pageIndex !== undefined) {
32
+ lines.push(`目标页:第 ${input.pageIndex} 页${input.pageFile ? `(预览文件 ${input.pageFile})` : ''}`, `修改范围:只修改第 ${input.pageIndex} 页对应的正文内容,其它页必须保持原样,不得改动。`);
33
+ }
34
+ lines.push('', `修改要求:${input.instruction}`, '', '请按以下要求处理:', '1. 读取并更新同目录下的 content.json,保持模板格式约定不变;', input.pageIndex !== undefined
35
+ ? `2. 仅改动与第 ${input.pageIndex} 页对应的内容,其余页原样保留;`
36
+ : '2. 按修改要求更新对应内容;', '3. 使用 word-master 重新生成 document.docx;', '4. 运行 verify_format.py 校验通过;', '5. 刷新 Word 预览,完成后告诉用户预览已更新。');
37
+ return lines.join('\n');
38
+ }
39
+ export function createEtownWordRoutes() {
40
+ return [
41
+ // 列出当前会话的 Word 文档(按需补齐/刷新预览)。
42
+ {
43
+ method: 'GET',
44
+ path: '/api/v2/word-preview',
45
+ handler: async ({ query }) => {
46
+ const chatId = query.get('chatId') ?? '';
47
+ if (!chatId) {
48
+ return { status: 400, data: { detail: 'chatId is required' } };
49
+ }
50
+ try {
51
+ const documents = await listWordDocuments(chatId, { ensurePreview: true });
52
+ return { status: 200, data: { documents } };
53
+ }
54
+ catch (err) {
55
+ return { status: 500, data: { detail: errorMessage(err) } };
56
+ }
57
+ },
58
+ },
59
+ // 单页预览图。
60
+ {
61
+ method: 'GET',
62
+ path: '/api/v2/word-preview/page',
63
+ handler: async ({ query }) => {
64
+ const chatId = query.get('chatId') ?? '';
65
+ const documentId = query.get('document') ?? '';
66
+ const pageFile = query.get('page') ?? '';
67
+ if (!chatId || !documentId || !pageFile) {
68
+ return { status: 400, data: { detail: 'chatId / document / page are required' } };
69
+ }
70
+ const page = await readWordPreviewPage(chatId, documentId, pageFile);
71
+ if (!page) {
72
+ return { status: 404, data: { detail: 'word preview page not found' } };
73
+ }
74
+ return { status: 200, data: page };
75
+ },
76
+ },
77
+ // HTML 预览的字体子集(本机缺失字体时兜底)。
78
+ {
79
+ method: 'GET',
80
+ path: '/api/v2/word-preview/font',
81
+ handler: async ({ query }) => {
82
+ const chatId = query.get('chatId') ?? '';
83
+ const documentId = query.get('document') ?? '';
84
+ const family = query.get('family') ?? '';
85
+ if (!chatId || !documentId || !family) {
86
+ return {
87
+ status: 400,
88
+ data: { detail: 'chatId / document / family are required' },
89
+ };
90
+ }
91
+ try {
92
+ const font = await readWordFontSubset(chatId, documentId, family);
93
+ if (!font) {
94
+ return { status: 404, data: { detail: 'word font subset not found' } };
95
+ }
96
+ return { status: 200, data: font };
97
+ }
98
+ catch (err) {
99
+ return { status: 500, data: { detail: errorMessage(err) } };
100
+ }
101
+ },
102
+ },
103
+ // 下载 DOCX。
104
+ {
105
+ method: 'GET',
106
+ path: '/api/v2/word-preview/docx',
107
+ handler: async ({ query }) => {
108
+ const chatId = query.get('chatId') ?? '';
109
+ const documentId = query.get('document') ?? '';
110
+ if (!chatId || !documentId) {
111
+ return { status: 400, data: { detail: 'chatId / document are required' } };
112
+ }
113
+ const docx = await readWordDocument(chatId, documentId);
114
+ if (!docx) {
115
+ return { status: 404, data: { detail: 'word document not found' } };
116
+ }
117
+ return { status: 200, data: docx };
118
+ },
119
+ },
120
+ // 手动刷新预览。
121
+ {
122
+ method: 'POST',
123
+ path: '/api/v2/word-preview/refresh',
124
+ handler: async ({ body }) => {
125
+ const payload = asRecord(body);
126
+ const chatId = String(payload.chatId ?? '');
127
+ const documentId = String(payload.documentId ?? '');
128
+ if (!chatId || !documentId || !SAFE_DOCUMENT_ID.test(documentId)) {
129
+ return { status: 400, data: { detail: 'chatId / documentId are required' } };
130
+ }
131
+ try {
132
+ const manifest = await ensureWordPreview(chatId, documentId, { force: true });
133
+ return {
134
+ status: 200,
135
+ data: {
136
+ success: true,
137
+ documentId,
138
+ pageCount: manifest.pages.length,
139
+ },
140
+ };
141
+ }
142
+ catch (err) {
143
+ return { status: 500, data: { detail: errorMessage(err) } };
144
+ }
145
+ },
146
+ },
147
+ // MVP 修改入口:不建独立队列,返回可发回主聊天的指令。
148
+ {
149
+ method: 'POST',
150
+ path: '/api/v2/word-preview/edit',
151
+ handler: async ({ body }) => {
152
+ const payload = asRecord(body);
153
+ const chatId = String(payload.chatId ?? '');
154
+ const documentId = String(payload.documentId ?? '');
155
+ const instruction = String(payload.instruction ?? '').trim();
156
+ if (!chatId || !documentId || !SAFE_DOCUMENT_ID.test(documentId)) {
157
+ return { status: 400, data: { detail: 'chatId / documentId are required' } };
158
+ }
159
+ if (!instruction) {
160
+ return { status: 400, data: { detail: 'instruction is required' } };
161
+ }
162
+ if (instruction.length > 4000) {
163
+ return { status: 400, data: { detail: 'instruction too long (max 4000 chars)' } };
164
+ }
165
+ const pageIndexRaw = payload.pageIndex;
166
+ let pageIndex;
167
+ if (pageIndexRaw !== undefined && pageIndexRaw !== null && pageIndexRaw !== '') {
168
+ const parsed = Number(pageIndexRaw);
169
+ if (!Number.isInteger(parsed) || parsed < 1) {
170
+ return { status: 400, data: { detail: 'pageIndex must be a positive integer' } };
171
+ }
172
+ pageIndex = parsed;
173
+ }
174
+ const documents = await listWordDocuments(chatId, { ensurePreview: false });
175
+ const document = documents.find((item) => item.documentId === documentId);
176
+ if (!document) {
177
+ return { status: 404, data: { detail: 'word document not found' } };
178
+ }
179
+ const page = pageIndex === undefined
180
+ ? undefined
181
+ : document.preview.pages.find((item) => item.index === pageIndex);
182
+ if (pageIndex !== undefined && !page) {
183
+ return { status: 400, data: { detail: `第 ${pageIndex} 页不存在` } };
184
+ }
185
+ return {
186
+ status: 200,
187
+ data: {
188
+ accepted: false,
189
+ mode: 'chat',
190
+ pageIndex,
191
+ instruction: buildWordEditInstruction({
192
+ documentPath: document.documentPath,
193
+ docxPath: document.docxPath,
194
+ instruction,
195
+ pageIndex,
196
+ pageFile: page?.file,
197
+ }),
198
+ },
199
+ };
200
+ },
201
+ },
202
+ ];
203
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * etown 场景的通用生成文件工作区。
3
+ *
4
+ * 现有 PPT 链路继续使用 `<userDataDir>/ppt-projects/<chatId>/`;Word 等
5
+ * 其它工具统一使用本文件提供的 `<userDataDir>/files/<chatId>/`,避免把
6
+ * Word 产物继续塞进 ppt-projects,同时为后续其它工具留出扩展位。
7
+ */
8
+ import { existsSync, mkdirSync } from 'node:fs';
9
+ import path from 'node:path';
10
+ import { listSkillRoots } from '@steerable/agent-shell/local-backend/skill-loader';
11
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
12
+ /** 与 SAFE_CHAT_ID 保持同一口径;workspace 自身只做防御性校验。 */
13
+ export const SAFE_WORKSPACE_ID = /^[0-9a-zA-Z_-]{1,64}$/;
14
+ /** Word 文档 ID / 预览页文件白名单。 */
15
+ export const SAFE_DOCUMENT_ID = /^[0-9a-zA-Z_-]{1,128}$/;
16
+ export const SAFE_PAGE_FILE = /^page-\d{3,}\.png$/i;
17
+ /** Word 单文档目录内固定使用的 DOCX 文件名(展示名走 meta.json)。 */
18
+ export const WORD_DOCX_FILENAME = 'document.docx';
19
+ /** Word 预览页目录与清单文件名。 */
20
+ export const WORD_PREVIEW_DIRNAME = 'preview';
21
+ export const WORD_PREVIEW_MANIFEST_FILENAME = 'manifest.json';
22
+ function safeChatId(chatId) {
23
+ return SAFE_WORKSPACE_ID.test(chatId);
24
+ }
25
+ /** 当前会话的通用生成文件根目录(持久化,不落 /tmp)。 */
26
+ export function getChatFilesWorkspace(chatId) {
27
+ if (!safeChatId(chatId)) {
28
+ throw new Error(`invalid chatId: ${chatId}`);
29
+ }
30
+ const workspace = path.join(getUserDataDir(), 'files', chatId);
31
+ mkdirSync(workspace, { recursive: true });
32
+ return workspace;
33
+ }
34
+ /** 当前会话的 Word 工作区根目录。 */
35
+ export function getChatWordWorkspace(chatId) {
36
+ const workspace = path.join(getChatFilesWorkspace(chatId), 'word');
37
+ mkdirSync(workspace, { recursive: true });
38
+ return workspace;
39
+ }
40
+ /**
41
+ * 当前会话的脱敏工作区根目录(mask-master 用)。
42
+ *
43
+ * 与 Word 同理落在 {@link getChatFilesWorkspace} 下:既持久化,又落在 office
44
+ * 预览白名单(`files/<chatId>`)里,脱敏后的 docx/pptx 能直接在右侧预览。
45
+ */
46
+ export function getChatMaskWorkspace(chatId) {
47
+ const workspace = path.join(getChatFilesWorkspace(chatId), 'mask');
48
+ mkdirSync(workspace, { recursive: true });
49
+ return workspace;
50
+ }
51
+ /**
52
+ * 解析 mask-master 技能应使用的 Python 解释器。
53
+ *
54
+ * 优先级与 ppt/word 一致:环境变量 DEEPPATH_MASK_PYTHON → 技能自带 .venv →
55
+ * 宿主裸 python3。该技能需要 python-docx / openpyxl / python-pptx 三者齐备。
56
+ */
57
+ export function resolveMaskPythonCommand() {
58
+ const configured = process.env.DEEPPATH_MASK_PYTHON?.trim();
59
+ if (configured)
60
+ return configured;
61
+ for (const root of [...listSkillRoots()].reverse()) {
62
+ const candidates = process.platform === 'win32'
63
+ ? [path.join(root, 'mask-master', '.venv', 'Scripts', 'python.exe')]
64
+ : [
65
+ path.join(root, 'mask-master', '.venv', 'bin', 'python3'),
66
+ path.join(root, 'mask-master', '.venv', 'bin', 'python'),
67
+ ];
68
+ for (const candidate of candidates) {
69
+ if (existsSync(candidate))
70
+ return candidate;
71
+ }
72
+ }
73
+ return process.platform === 'win32' ? 'python' : 'python3';
74
+ }
75
+ /**
76
+ * 解析 word-master 技能应使用的 Python 解释器。
77
+ *
78
+ * 与 ppt-master 的 resolvePptPythonCommand 保持同样的优先级:
79
+ * 1. 环境变量 DEEPPATH_WORD_PYTHON;
80
+ * 2. 技能自带 .venv;
81
+ * 3. 宿主裸 python3(最后兜底)。
82
+ */
83
+ export function resolveWordPythonCommand() {
84
+ const configured = process.env.DEEPPATH_WORD_PYTHON?.trim();
85
+ if (configured)
86
+ return configured;
87
+ for (const root of [...listSkillRoots()].reverse()) {
88
+ const candidates = process.platform === 'win32'
89
+ ? [path.join(root, 'word-master', '.venv', 'Scripts', 'python.exe')]
90
+ : [
91
+ path.join(root, 'word-master', '.venv', 'bin', 'python3'),
92
+ path.join(root, 'word-master', '.venv', 'bin', 'python'),
93
+ ];
94
+ for (const candidate of candidates) {
95
+ if (existsSync(candidate))
96
+ return candidate;
97
+ }
98
+ }
99
+ return process.platform === 'win32' ? 'python' : 'python3';
100
+ }