@steerable/steer 0.0.0-stage → 0.3.11

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 +131 -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,437 @@
1
+ /**
2
+ * PPT 单页修改 —— 方案 A 的后端支撑:资源上传 + 修改指令构造 + 单页历史。
3
+ *
4
+ * 数据流:
5
+ * 1. 前端把用户上传的图片/数据文件经 `savePptResources` 落进当前项目的
6
+ * `images/` 或 `data/` 目录(这些目录在 ppt 工作区内,ppt-master 与
7
+ * exec 沙箱都可读可写);
8
+ * 2. 前端提交修改要求时,router 用 `buildPptSlideEditInstruction` 拼装一条
9
+ * 带强上下文约束的「单页修改指令」,注入运行中的回合(steer)或作为
10
+ * 普通消息发送(fallback);
11
+ * 3. 每次提交修改前,router 调 `backupPptSlide` 把当前页 SVG 备份到
12
+ * `svg_output/.history/`,可随时回滚。
13
+ */
14
+ import { mkdirSync } from 'node:fs';
15
+ import { copyFile, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { sanitizeName, uniqueFileName } from '@steerable/agent-shell/attachments';
18
+ import { pptRenderScriptPath } from './render.js';
19
+ import { getChatPptWorkspace, listPptPreviews, SAFE_CHAT_ID, SAFE_PROJECT_ID, SAFE_SLIDE_NAME, } from './preview.js';
20
+ const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif']);
21
+ const DATA_EXTENSIONS = new Set(['.csv', '.tsv', '.json', '.xlsx', '.xls']);
22
+ /** 单张上传图片上限(与 image-attachment 的源文件上限对齐)。 */
23
+ export const PPT_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
24
+ /** 单个数据文件上限。 */
25
+ export const PPT_DATA_MAX_BYTES = 10 * 1024 * 1024;
26
+ /** 单页修改指令长度上限,防止撑爆上下文。 */
27
+ export const PPT_EDIT_INSTRUCTION_MAX_CHARS = 8000;
28
+ /** 每页保留的历史备份数量。 */
29
+ const PPT_SLIDE_HISTORY_LIMIT = 20;
30
+ const CHART_TYPE_TEXT = {
31
+ auto: '自动(由你根据数据选择最合适的图表类型)',
32
+ bar: '柱状图',
33
+ line: '折线图',
34
+ pie: '饼图',
35
+ };
36
+ function extOf(name) {
37
+ return path.extname(name).toLowerCase();
38
+ }
39
+ function inferKind(name, kind) {
40
+ if (kind === 'image' || kind === 'data')
41
+ return kind;
42
+ const ext = extOf(name);
43
+ if (IMAGE_EXTENSIONS.has(ext))
44
+ return 'image';
45
+ if (DATA_EXTENSIONS.has(ext))
46
+ return 'data';
47
+ return null;
48
+ }
49
+ function decodeData(data) {
50
+ const text = data.trim();
51
+ if (!text)
52
+ return null;
53
+ return Buffer.from(text, 'base64');
54
+ }
55
+ function isSafeResourceKind(kind) {
56
+ return kind === 'image' || kind === 'data';
57
+ }
58
+ /** 资源路径必须仍落在本项目目录内,防止前端传任意路径写进指令。 */
59
+ function isPathInside(parent, child) {
60
+ const rel = path.relative(path.resolve(parent), path.resolve(child));
61
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
62
+ }
63
+ /**
64
+ * 把一批资源落进当前 PPT 项目的 `images/`(图片)或 `data/`(数据)目录。
65
+ * 逐文件返回结果,单个失败不影响整批。与 attachments.save 相同的容错语义。
66
+ */
67
+ export async function savePptResources(chatId, projectId, files) {
68
+ const out = [];
69
+ if (!chatId || !SAFE_CHAT_ID.test(chatId)) {
70
+ for (const file of files) {
71
+ out.push({
72
+ name: sanitizeName(file.name || path.basename(file.path || '')),
73
+ path: '',
74
+ kind: 'image',
75
+ size: 0,
76
+ error: `invalid chatId: ${chatId}`,
77
+ });
78
+ }
79
+ return { files: out };
80
+ }
81
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId)) {
82
+ for (const file of files) {
83
+ out.push({
84
+ name: sanitizeName(file.name || path.basename(file.path || '')),
85
+ path: '',
86
+ kind: 'image',
87
+ size: 0,
88
+ error: `invalid projectId: ${projectId}`,
89
+ });
90
+ }
91
+ return { files: out };
92
+ }
93
+ // 项目必须真实存在,避免往任意目录写文件。
94
+ const previews = await listPptPreviews(chatId, { force: true });
95
+ const project = previews.find((p) => p.projectId === projectId);
96
+ if (!project) {
97
+ for (const file of files) {
98
+ out.push({
99
+ name: sanitizeName(file.name || path.basename(file.path || '')),
100
+ path: '',
101
+ kind: 'image',
102
+ size: 0,
103
+ error: 'project not found',
104
+ });
105
+ }
106
+ return { files: out };
107
+ }
108
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
109
+ for (const file of files) {
110
+ const sourcePath = typeof file.path === 'string' ? file.path.trim() : '';
111
+ const originalName = sanitizeName(file.name || path.basename(sourcePath || ''));
112
+ const kind = inferKind(originalName, file.kind);
113
+ if (!kind) {
114
+ out.push({
115
+ name: originalName,
116
+ path: '',
117
+ kind: 'image',
118
+ size: 0,
119
+ error: `unsupported file type: ${path.extname(originalName) || originalName}`,
120
+ });
121
+ continue;
122
+ }
123
+ if (!isSafeResourceKind(kind)) {
124
+ out.push({ name: originalName, path: '', kind: 'image', size: 0, error: 'invalid kind' });
125
+ continue;
126
+ }
127
+ const ext = extOf(originalName);
128
+ const extAllowed = kind === 'image' ? IMAGE_EXTENSIONS.has(ext) : DATA_EXTENSIONS.has(ext);
129
+ if (!extAllowed) {
130
+ out.push({
131
+ name: originalName,
132
+ path: '',
133
+ kind,
134
+ size: 0,
135
+ error: `unsupported ${kind} file type: ${ext || originalName}`,
136
+ });
137
+ continue;
138
+ }
139
+ const targetDir = path.join(projectRoot, kind === 'image' ? 'images' : 'data');
140
+ const maxBytes = kind === 'image' ? PPT_IMAGE_MAX_BYTES : PPT_DATA_MAX_BYTES;
141
+ try {
142
+ mkdirSync(targetDir, { recursive: true });
143
+ const data = typeof file.data === 'string' ? file.data : '';
144
+ if (data.trim()) {
145
+ const bytes = decodeData(data);
146
+ if (bytes.length > maxBytes) {
147
+ out.push({
148
+ name: originalName,
149
+ path: '',
150
+ kind,
151
+ size: 0,
152
+ error: `file too large (${bytes.length} bytes), max=${maxBytes}`,
153
+ });
154
+ continue;
155
+ }
156
+ const storedName = uniqueFileName(targetDir, originalName);
157
+ const destPath = path.join(targetDir, storedName);
158
+ await writeFile(destPath, bytes);
159
+ out.push({ name: storedName, path: destPath, kind, size: bytes.length });
160
+ continue;
161
+ }
162
+ if (sourcePath) {
163
+ const sourceStat = await stat(sourcePath);
164
+ if (!sourceStat.isFile()) {
165
+ out.push({ name: originalName, path: '', kind, size: 0, error: 'source is not a regular file' });
166
+ continue;
167
+ }
168
+ if (sourceStat.size > maxBytes) {
169
+ out.push({
170
+ name: originalName,
171
+ path: '',
172
+ kind,
173
+ size: 0,
174
+ error: `file too large (${sourceStat.size} bytes), max=${maxBytes}`,
175
+ });
176
+ continue;
177
+ }
178
+ const storedName = uniqueFileName(targetDir, originalName);
179
+ const destPath = path.join(targetDir, storedName);
180
+ await copyFile(sourcePath, destPath);
181
+ out.push({ name: storedName, path: destPath, kind, size: sourceStat.size });
182
+ continue;
183
+ }
184
+ out.push({ name: originalName, path: '', kind, size: 0, error: 'no content (missing path and data)' });
185
+ }
186
+ catch (err) {
187
+ out.push({
188
+ name: originalName,
189
+ path: '',
190
+ kind,
191
+ size: 0,
192
+ error: err instanceof Error ? err.message : String(err),
193
+ });
194
+ }
195
+ }
196
+ return { files: out };
197
+ }
198
+ /**
199
+ * 拼装单页修改指令。这是方案 A 效果好坏的核心:给 agent 目标页路径、
200
+ * 已上传资源路径与硬性约束,让「改哪一页、用什么资源、改完做什么」都
201
+ * 不需要模型再猜。
202
+ */
203
+ export function buildPptSlideEditInstruction(input) {
204
+ const slidePath = path.join(input.projectPath, 'svg_output', input.slideName);
205
+ const chartType = input.chartType === 'bar' || input.chartType === 'line' || input.chartType === 'pie'
206
+ ? input.chartType
207
+ : 'auto';
208
+ const lines = [
209
+ '【PPT 单页修改请求】',
210
+ `项目目录:${input.projectPath}`,
211
+ `目标页:${slidePath}`,
212
+ '',
213
+ `修改要求:${input.instruction}`,
214
+ ];
215
+ const resources = Array.isArray(input.resources) ? input.resources : [];
216
+ const imageResources = resources.filter((r) => r.kind === 'image');
217
+ const dataResources = resources.filter((r) => r.kind === 'data');
218
+ // 速查卡:把「这次改哪一页、要读多少」直接讲死。
219
+ // 背景:三条修改是三个独立回合(各自 chatId),实测每条都要重新 ls / cat
220
+ // README / 读 design_spec 全文,三次重复侦察各占 20~30s。这些信息宿主本来
221
+ // 就持有,直接给出即可。
222
+ lines.push('', '工作方式(宿主预置,不必自行摸索):', '- 只读目标页 SVG 就够;**不要**读 design_spec.md 全文、**不要**读技能里的 checker.py 源码。', '- 需要页面清单时用一次 `ls svg_output/` 拿到,不要逐页打开其它 SVG。', '- 页面尺寸以目标页现有 width/height/viewBox 为准(同项目各页一致)。');
223
+ if (resources.length > 0) {
224
+ lines.push('');
225
+ lines.push('已上传资源(均已落盘,可直接使用):');
226
+ for (const res of resources) {
227
+ const kindText = res.kind === 'image' ? '图片' : '数据文件';
228
+ lines.push(`- [${kindText}] ${res.path}`);
229
+ }
230
+ if (imageResources.length > 0) {
231
+ lines.push('图片资源用法:本页 SVG 中以相对路径 `../images/<文件名>` 引用;项目内文件名请用 ASCII(中文/空格名在导出链路里不稳定)。');
232
+ }
233
+ if (dataResources.length > 0) {
234
+ lines.push('数据文件用法:先用 python 读取并检查前几行,再生成图表 PNG 到 `images/`,最后在本页 SVG 中引用 `../images/<图表文件名>.png`。');
235
+ }
236
+ }
237
+ if (imageResources.length > 0) {
238
+ // 登记规则是导出门禁(缺了会被 svg_image_missing_spec 挡下),而格式极死。
239
+ // 实测 #1 为确认格式花了 15 轮 / 70s 去 grep checker.py —— 这里把契约给全,
240
+ // 并显式禁止再去看源码。
241
+ lines.push('', '新增图片必须做两处登记(导出门禁,缺了会被 `svg_image_missing_spec` 拒绝导出):', '把要用的图片先复制/改名为 `images/page_<页序号>_<用途>.png`(ASCII),然后**只追加**下面两行:', '', '1) `spec_lock.md` 的 `## images` 段(注意格式是 `- 键: 路径 | source=… | crop=…`):', ' `- page-<页序号>-<用途>: images/page_<页序号>_<用途>.png | source=user | crop=no-crop`', '2) `design_spec.md` 的 `## VIII. Image Resource List` 表(**12 列**,只追加数据行,不要重写表头):', ' `| images/page_<页序号>_<用途>.png | <宽> × <高> | <宽高比:1> | <该页用途> | Document scan | <排版说明> | no-crop | user | Existing | <来源> | none | local |`', '', '两行必须彼此一致,否则质检照样报错:', '- `spec_lock` 的 `source=` 必须等于 §VIII 的 `Acquire Via`(都填 `user`)→ 否则 `locked_image_source_mismatch`', '- `spec_lock` 的 `crop=` 必须等于 §VIII 的 `Crop Policy`(都填 `no-crop`)→ 否则 `locked_image_crop_mismatch`', '- `spec_lock` 行**不要**写 `pattern=`,否则会要求与 §VIII 的 `Image pattern` 版面兼容(`locked_image_pattern_mismatch`)', '', '★ 以上就是全部登记契约,**不要再读 checker.py 源码去确认格式**。', '★ `spec_lock.md` / `design_spec.md` 不是页面文件:追加这两行是允许且必需的,不算"改动其他页"。');
242
+ }
243
+ if (dataResources.length > 0) {
244
+ lines.push('');
245
+ lines.push(`图表要求:类型 = ${CHART_TYPE_TEXT[chartType]};`);
246
+ lines.push('用 python(matplotlib 或 ppt-master 技能自带图表脚本)读取 data/ 下的数据,输出 2x 分辨率 PNG 到 `images/`,文件名建议 `chart_<本页序号>.png`;注意中文字体缺失时用英文标签或改在 SVG 文本层标注中文。');
247
+ }
248
+ lines.push('', 'SVG 文本硬约束(横向坐标超出页面的根因):', '- SVG 的 <text> 不会自动换行,文本里的 `\\n` 只会被当成空格,不能表示换行;', '- 每个可视行必须显式写成带 x/dy 的 <tspan>(或独立 <text>);需要折行时先用 `text_measure.py wrap` 按上级 `data-pptx-bounds` 的可用宽度算出每行;', '- 任一行的估算宽度 + 起始 x 不得超过所属 slot 的 `data-pptx-bounds` 右边界;没有 slot 时不得超过根 viewBox 右边界;', '- 固定高度的标题 / slot 先按可用行数预检,放不下时改写文案或拆分,不要依赖自动换行或把长行塞进页面。');
249
+ // 视觉复核:把渲染器钉死成宿主提供的脚本。
250
+ // 背景:本机 cairosvg 会把内嵌栅格渲成空白且 CJK 变豆腐块。chromium(snap /
251
+ // playwright)都起不来。实测模型为此各花了 ~35s / 52s / 54s 反复试错。
252
+ lines.push('', '视觉复核(需要"看一眼"时):', `- 运行:\`python3 "${pptRenderScriptPath(input.projectPath)}" "${input.projectPath}" ${input.slideName} --out /tmp/${input.slideName.replace(/\.svg$/, '')}.png\``, '- 该脚本自带 resvg 渲染器(首次运行会自建 venv 装依赖),stdout 是一行 JSON。', '- **不要**用 cairosvg / chromium / headless 浏览器做渲染:本机这些路径都不可用(cairosvg 渲不出内嵌图片、CJK 变豆腐块)。', '- JSON 里的 `sources[].mean_luma` / `light_ratio` 能直接判断"原图本身是否极浅"——用户上传的影印件常常 90%+ 像素接近纯白,渲出来看着像空白是忠实还原,不是渲染损坏;这种情况直接在汇报里说明,不要去改像素。');
253
+ const constraints = [
254
+ `只允许修改 ${input.slideName} 这一页 SVG 文件,不得改动其他任何页的 SVG;`,
255
+ '新增图片/图表必须放在本项目的 `images/` 目录,并通过相对路径 `../images/xxx` 引用;',
256
+ ];
257
+ if (input.refreshQualityReport !== false) {
258
+ constraints.push('修改完成后运行 ppt-master 的 `svg_quality_checker.py` 刷新 final 质检报告(stage=final),确保后续导出不因 stale 报告失败;');
259
+ }
260
+ constraints.push('文本必须显式折行:SVG <text> 不会自动换行,`\\n` 只当空格;所有可视行写成带 x/dy 的 <tspan>,并用 `text_measure.py wrap` 复核每一行不超出所属 data-pptx-bounds / 根 viewBox 的右边界;', '保持本页 SVG 的 width/height/viewBox 与其他页一致,不要改变页面尺寸;', '若资源或信息不足以完成修改,请说明缺什么,不要臆造数据或图片。');
261
+ lines.push('');
262
+ lines.push('硬性约束:');
263
+ constraints.forEach((text, index) => {
264
+ lines.push(`${index + 1}. ${text}`);
265
+ });
266
+ let text = lines.join('\n');
267
+ if (text.length > PPT_EDIT_INSTRUCTION_MAX_CHARS) {
268
+ text = `${text.slice(0, PPT_EDIT_INSTRUCTION_MAX_CHARS)}\n…(指令过长已截断)`;
269
+ }
270
+ return text;
271
+ }
272
+ /** 当前页 SVG 路径。 */
273
+ function slideSvgPath(projectRoot, slideName) {
274
+ return path.join(projectRoot, 'svg_output', slideName);
275
+ }
276
+ /** 当前页历史备份目录。 */
277
+ function historyDir(projectRoot) {
278
+ return path.join(projectRoot, 'svg_output', '.history');
279
+ }
280
+ /** 从备份文件名里解析出它属于哪一页(`<slideName>.<timestamp>.svg`)。 */
281
+ function isBackupOf(backupName, slideName) {
282
+ return (backupName.startsWith(`${slideName}.`) &&
283
+ backupName.toLowerCase().endsWith('.svg') &&
284
+ backupName !== slideName);
285
+ }
286
+ /**
287
+ * 修改前把当前页 SVG 备份到 `svg_output/.history/`,保留最近
288
+ * PPT_SLIDE_HISTORY_LIMIT 份,用于一键回滚。
289
+ */
290
+ export async function backupPptSlide(chatId, projectId, slideName) {
291
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
292
+ return null;
293
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId))
294
+ return null;
295
+ if (!slideName || !SAFE_SLIDE_NAME.test(slideName))
296
+ return null;
297
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
298
+ const source = slideSvgPath(projectRoot, slideName);
299
+ let svg;
300
+ try {
301
+ svg = await readFile(source, 'utf8');
302
+ }
303
+ catch {
304
+ return null;
305
+ }
306
+ const dir = historyDir(projectRoot);
307
+ mkdirSync(dir, { recursive: true });
308
+ const backupName = uniqueFileName(dir, `${slideName}.${Date.now()}.svg`);
309
+ const backupPath = path.join(dir, backupName);
310
+ await writeFile(backupPath, svg, 'utf8');
311
+ // 清理旧备份:只删当前页的备份,保留最近 N 份。
312
+ try {
313
+ const entries = await readdir(dir);
314
+ const current = entries.filter((name) => isBackupOf(name, slideName));
315
+ const withMtime = [];
316
+ for (const name of current) {
317
+ try {
318
+ const info = await stat(path.join(dir, name));
319
+ withMtime.push({ name, mtimeMs: info.mtimeMs });
320
+ }
321
+ catch {
322
+ // ignore
323
+ }
324
+ }
325
+ withMtime.sort((a, b) => b.mtimeMs - a.mtimeMs);
326
+ for (const item of withMtime.slice(PPT_SLIDE_HISTORY_LIMIT)) {
327
+ await rm(path.join(dir, item.name), { force: true });
328
+ }
329
+ }
330
+ catch {
331
+ // 清理失败不影响备份。
332
+ }
333
+ return { name: backupName, path: backupPath };
334
+ }
335
+ /** 列出当前页的历史备份(新的在前)。 */
336
+ export async function listPptSlideHistory(chatId, projectId, slideName) {
337
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
338
+ return [];
339
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId))
340
+ return [];
341
+ if (!slideName || !SAFE_SLIDE_NAME.test(slideName))
342
+ return [];
343
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
344
+ const dir = historyDir(projectRoot);
345
+ let entries;
346
+ try {
347
+ entries = await readdir(dir);
348
+ }
349
+ catch {
350
+ return [];
351
+ }
352
+ const out = [];
353
+ for (const name of entries) {
354
+ if (!isBackupOf(name, slideName))
355
+ continue;
356
+ const filePath = path.join(dir, name);
357
+ try {
358
+ const info = await stat(filePath);
359
+ if (!info.isFile())
360
+ continue;
361
+ out.push({ name, path: filePath, size: info.size, mtimeMs: info.mtimeMs });
362
+ }
363
+ catch {
364
+ // ignore
365
+ }
366
+ }
367
+ out.sort((a, b) => b.mtimeMs - a.mtimeMs);
368
+ return out;
369
+ }
370
+ /**
371
+ * 用某个历史备份覆盖回当前页 SVG。备份名只接受纯文件名(白名单校验),
372
+ * 防止路径穿越。
373
+ */
374
+ export async function restorePptSlideHistory(chatId, projectId, slideName, backupName) {
375
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
376
+ return false;
377
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId))
378
+ return false;
379
+ if (!slideName || !SAFE_SLIDE_NAME.test(slideName))
380
+ return false;
381
+ if (!backupName || !/^[^/\\]+$/.test(backupName) || !backupName.toLowerCase().endsWith('.svg')) {
382
+ return false;
383
+ }
384
+ if (!isBackupOf(backupName, slideName))
385
+ return false;
386
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
387
+ const backupPath = path.join(historyDir(projectRoot), backupName);
388
+ let svg;
389
+ try {
390
+ svg = await readFile(backupPath, 'utf8');
391
+ }
392
+ catch {
393
+ return false;
394
+ }
395
+ await writeFile(slideSvgPath(projectRoot, slideName), svg, 'utf8');
396
+ return true;
397
+ }
398
+ /**
399
+ * 校验前端提交的资源引用是否仍落在本项目目录内;只把合法且存在的资源
400
+ * 写进指令,避免任意路径注入。
401
+ */
402
+ export async function filterValidPptResources(chatId, projectId, resources) {
403
+ if (!Array.isArray(resources))
404
+ return [];
405
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
406
+ const validKinds = new Set(['image', 'data']);
407
+ const out = [];
408
+ for (const item of resources) {
409
+ if (!item || typeof item !== 'object')
410
+ continue;
411
+ const name = item.name;
412
+ const resPath = item.path;
413
+ const kind = item.kind;
414
+ if (typeof name !== 'string' || typeof resPath !== 'string')
415
+ continue;
416
+ if (kind !== 'image' && kind !== 'data')
417
+ continue;
418
+ if (!validKinds.has(kind))
419
+ continue;
420
+ if (!isPathInside(projectRoot, resPath))
421
+ continue;
422
+ try {
423
+ const info = await stat(resPath);
424
+ if (!info.isFile())
425
+ continue;
426
+ out.push({ name: path.basename(resPath), path: resPath, kind, size: info.size });
427
+ }
428
+ catch {
429
+ continue;
430
+ }
431
+ }
432
+ return out;
433
+ }
434
+ /** 仅用于测试/诊断:确认一个文件是否存在于资源目录内。 */
435
+ export function isSafeResourcePath(projectRoot, resourcePath) {
436
+ return isPathInside(projectRoot, resourcePath);
437
+ }