@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,296 @@
1
+ /**
2
+ * PPT 设计稿预览的数据源 —— 按会话(chatId)隔离,扫描 ppt-master 为当前
3
+ * 会话产出的 SVG 设计稿。
4
+ *
5
+ * 每个会话一个独立工作区:`<数据目录>/ppt-projects/<chatId>/`。ppt-master 在
6
+ * 该工作区下按项目分目录(`<workspace>/<项目名>/svg_output/*.svg`)。SVG 里
7
+ * 通过 `href="../images/xxx.png"` 引用同项目 `images/` 下的位图,因此在把
8
+ * SVG 文本回给渲染端之前,这里把这些本地图片内联成 data URI,让浏览器能
9
+ * 一次性渲染出完整预览。
10
+ */
11
+ import { mkdirSync } from 'node:fs';
12
+ import { readdir, readFile, stat } from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
15
+ export const SAFE_CHAT_ID = /^[0-9a-zA-Z_-]{1,64}$/;
16
+ export const SAFE_PROJECT_ID = /^[^/\\]+$/;
17
+ export const SAFE_SLIDE_NAME = /^[^/\\]+\.svg$/i;
18
+ /**
19
+ * 归一化判断一个技能名是否是 ppt-master(显式 `/ppt-master` 触发路径)。
20
+ * 兼容 `ppt-master` / `ppt_master` / `ppt master` / `pptmaster` 及大小写。
21
+ */
22
+ export function isPptSkillName(name) {
23
+ if (typeof name !== 'string')
24
+ return false;
25
+ const key = name.trim().toLowerCase().replace(/[\s_-]+/g, '');
26
+ return key === 'pptmaster';
27
+ }
28
+ /**
29
+ * 判断一次工具调用是否是「加载 ppt-master 技能」——catalog 路径下 sidecar
30
+ * 注入的 `skill` 工具按需返回技能正文。参数键不唯一(name / skill /
31
+ * skillName / skill_name …),故同时做字段探测与序列化兜底。
32
+ */
33
+ export function isPptSkillToolCall(tool, args) {
34
+ if (typeof tool !== 'string' || !/skill/i.test(tool))
35
+ return false;
36
+ if (!args || typeof args !== 'object')
37
+ return false;
38
+ const candidates = [
39
+ args.name,
40
+ args.skill,
41
+ args.skillName,
42
+ args.skill_name,
43
+ args.skillId,
44
+ args.id,
45
+ ];
46
+ if (candidates.some((c) => isPptSkillName(c)))
47
+ return true;
48
+ try {
49
+ return /ppt[-_ ]?master/i.test(JSON.stringify(args));
50
+ }
51
+ catch {
52
+ return false;
53
+ }
54
+ }
55
+ /**
56
+ * 判断一次工具调用是否「在处理逻辑里调用了 ppt-master」——不依赖用户消息,
57
+ * 只看工具调用本身。覆盖三类实际会触发 ppt-master 的情况:
58
+ * - `skill` 工具按需加载 ppt-master(catalog 路径,见 isPptSkillToolCall);
59
+ * - `local_exec_shell` / `local_run_snippet` 执行了 ppt-master 技能目录下的脚本;
60
+ * - 文件读写(`local_read_file` / `local_write_file` / `local_edit_file` /
61
+ * `local_open_path`)指向 ppt-master 技能目录内的文件。
62
+ *
63
+ * 之所以要覆盖 shell / 文件操作:续跑(「继续」)轮次里模型通常不再调用
64
+ * `skill` 工具,而是直接跑 `/skills/ppt-master/scripts/...` 里的 python
65
+ * 脚本或读写其工作流文件——这些才是「处理逻辑调用 ppt-master」的真实信号。
66
+ */
67
+ export function isPptMasterToolCall(tool, args) {
68
+ if (isPptSkillToolCall(tool, args))
69
+ return true;
70
+ if (!args || typeof args !== 'object')
71
+ return false;
72
+ const fields = [args.command, args.code, args.path, args.target, args.file];
73
+ const haystack = fields.filter((f) => typeof f === 'string').join('\n');
74
+ return /ppt[-_ ]?master/i.test(haystack);
75
+ }
76
+ /**
77
+ * 清单指纹:用于「本轮是否新增设计稿」的变更检测。slides 与 projects 在
78
+ * `listPptPreviews` 里已稳定排序,这里只做确定性拼接,避免目录扫描顺序
79
+ * 抖动造成误判。
80
+ */
81
+ export function pptPreviewsSignature(previews) {
82
+ return previews
83
+ .map((p) => `${p.projectId}:${p.slides
84
+ .map((s) => `${s.name}@${s.mtimeMs}`)
85
+ .join(',')}`)
86
+ .join('|');
87
+ }
88
+ /** 当前会话的 PPT 工作区根目录(持久化,不落 /tmp)。 */
89
+ export function getChatPptWorkspace(chatId) {
90
+ const workspace = path.join(getUserDataDir(), 'ppt-projects', chatId);
91
+ mkdirSync(workspace, { recursive: true });
92
+ return workspace;
93
+ }
94
+ /**
95
+ * 从设计稿文件名解析页码(排序 + 缩略图页码标签都吃这个值)。
96
+ *
97
+ * 约定是行首数字(`01_cover.svg`),但模板工作流也会产出带页 id 前缀的
98
+ * `P01_cover.svg`。原来只认 `^(\d+)`,于是整册都落进 `MAX_SAFE_INTEGER`
99
+ * 兜底值:排序退化成纯字典序(碰巧还对),而缩略图页码把哨兵值原样画了
100
+ * 出来——事故现场 18 页全显示 `9007199254740991`。这里容忍一个字母前缀。
101
+ *
102
+ * 真的解析不出数字(如 `cover.svg`)仍返回哨兵值,由调用方按序号降级;
103
+ * 不要把哨兵值当页码展示。
104
+ */
105
+ function parseSlideOrder(name) {
106
+ const m = name.match(/^[A-Za-z]*(\d+)/);
107
+ return m ? parseInt(m[1], 10) : Number.MAX_SAFE_INTEGER;
108
+ }
109
+ const LIST_CACHE_TTL_MS = 1500;
110
+ const LIST_CACHE_MAX_ENTRIES = 128;
111
+ /**
112
+ * 每个 chatId 的清单缓存。渲染端即使多开标签页 / 面板与自动打开逻辑同时
113
+ * 请求,也会在 TTL 内合并成一次磁盘扫描;TTL 小于渲染端轮询间隔,不会
114
+ * 牺牲“新生成一页后 2s 内可见”的时效。
115
+ */
116
+ const listCache = new Map();
117
+ /** 让某个会话的清单缓存立即失效(单页修改/回滚后调用)。 */
118
+ export function invalidatePptPreviewsCache(chatId) {
119
+ listCache.delete(chatId);
120
+ }
121
+ export async function listPptPreviews(chatId, opts = {}) {
122
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
123
+ return [];
124
+ // `force` 用于后端「变更检测」扫描:必须读真实磁盘,不能吃到渲染端轮询
125
+ // 时代遗留下来的 TTL 缓存,否则「刚写完的一页」会被 1.5s 内的旧清单挡住。
126
+ if (!opts.force) {
127
+ const cached = listCache.get(chatId);
128
+ if (cached && Date.now() - cached.at < LIST_CACHE_TTL_MS) {
129
+ return cached.previews;
130
+ }
131
+ }
132
+ const root = getChatPptWorkspace(chatId);
133
+ let entries;
134
+ try {
135
+ entries = await readdir(root, { withFileTypes: true });
136
+ }
137
+ catch {
138
+ return [];
139
+ }
140
+ const previews = [];
141
+ for (const entry of entries) {
142
+ if (!entry.isDirectory())
143
+ continue;
144
+ const projectId = entry.name;
145
+ const svgDir = path.join(root, projectId, 'svg_output');
146
+ let files;
147
+ try {
148
+ files = await readdir(svgDir);
149
+ }
150
+ catch {
151
+ continue;
152
+ }
153
+ const slideStats = [];
154
+ for (const file of files) {
155
+ if (!SAFE_SLIDE_NAME.test(file))
156
+ continue;
157
+ let mtimeMs = 0;
158
+ try {
159
+ const info = await stat(path.join(svgDir, file));
160
+ mtimeMs = Math.max(0, Math.round(info.mtimeMs));
161
+ }
162
+ catch {
163
+ // stat 失败就按 0 处理,不阻断清单。
164
+ }
165
+ slideStats.push({ name: file, order: parseSlideOrder(file), mtimeMs });
166
+ }
167
+ const slides = slideStats.sort((a, b) => a.order - b.order || a.name.localeCompare(b.name, 'zh-CN'));
168
+ if (slides.length === 0)
169
+ continue;
170
+ previews.push({ projectId, projectPath: path.join(root, projectId), slides });
171
+ }
172
+ previews.sort((a, b) => b.projectId.localeCompare(a.projectId, 'zh-CN'));
173
+ // 空结果不缓存:空目录扫描很便宜,且避免「刚生成第一批设计稿却被 TTL
174
+ // 内的空缓存挡住」;非空结果才合并短时间内的重复请求。
175
+ if (previews.length === 0) {
176
+ listCache.delete(chatId);
177
+ return previews;
178
+ }
179
+ if (listCache.size >= LIST_CACHE_MAX_ENTRIES) {
180
+ const oldest = listCache.keys().next().value;
181
+ if (oldest !== undefined)
182
+ listCache.delete(oldest);
183
+ }
184
+ listCache.set(chatId, { at: Date.now(), previews });
185
+ return previews;
186
+ }
187
+ /**
188
+ * 读取当前会话某项目的一页设计稿 SVG,并把本地图片引用内联成 data URI。
189
+ * chatId / projectId / slideName 都经过白名单校验,防止路径穿越。
190
+ */
191
+ export async function readPptSvg(chatId, projectId, slideName) {
192
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
193
+ return null;
194
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId))
195
+ return null;
196
+ if (!slideName || !SAFE_SLIDE_NAME.test(slideName))
197
+ return null;
198
+ const svgPath = path.join(getChatPptWorkspace(chatId), projectId, 'svg_output', slideName);
199
+ let svg;
200
+ try {
201
+ svg = await readFile(svgPath, 'utf8');
202
+ }
203
+ catch {
204
+ return null;
205
+ }
206
+ return inlineLocalImages(svg, path.dirname(svgPath));
207
+ }
208
+ const PPT_RESOURCE_DIRS = {
209
+ image: 'images',
210
+ data: 'data',
211
+ };
212
+ /**
213
+ * 列出当前会话某项目已上传的单页修改资源(图片 + 数据文件)。
214
+ * 目录不存在时返回空数组;文件名非法/读取失败的文件跳过。
215
+ */
216
+ export async function listPptResources(chatId, projectId) {
217
+ if (!chatId || !SAFE_CHAT_ID.test(chatId))
218
+ return [];
219
+ if (!projectId || !SAFE_PROJECT_ID.test(projectId))
220
+ return [];
221
+ const projectRoot = path.join(getChatPptWorkspace(chatId), projectId);
222
+ const out = [];
223
+ for (const kind of ['image', 'data']) {
224
+ const dir = path.join(projectRoot, PPT_RESOURCE_DIRS[kind]);
225
+ let entries;
226
+ try {
227
+ entries = await readdir(dir);
228
+ }
229
+ catch {
230
+ continue;
231
+ }
232
+ for (const name of entries) {
233
+ if (name.startsWith('.'))
234
+ continue;
235
+ const filePath = path.join(dir, name);
236
+ try {
237
+ const info = await stat(filePath);
238
+ if (!info.isFile())
239
+ continue;
240
+ out.push({ name, path: filePath, kind, size: info.size });
241
+ }
242
+ catch {
243
+ // 单个文件 stat 失败就跳过。
244
+ }
245
+ }
246
+ }
247
+ return out;
248
+ }
249
+ const EXT_MIME = {
250
+ '.png': 'image/png',
251
+ '.jpg': 'image/jpeg',
252
+ '.jpeg': 'image/jpeg',
253
+ '.webp': 'image/webp',
254
+ '.gif': 'image/gif',
255
+ };
256
+ const LOCAL_IMAGE_RE = /((?:xlink:)?href)="([^"]+\.(?:png|jpe?g|webp|gif))"/gi;
257
+ async function inlineLocalImages(svg, svgDir) {
258
+ const replacements = [];
259
+ let m;
260
+ LOCAL_IMAGE_RE.lastIndex = 0;
261
+ while ((m = LOCAL_IMAGE_RE.exec(svg)) !== null) {
262
+ const full = m[0];
263
+ const attr = m[1];
264
+ const value = m[2];
265
+ const start = m.index;
266
+ if (/^(data:|https?:|#)/i.test(value))
267
+ continue;
268
+ // 只内联项目内的相对引用(../images/xxx 之类);绝对/逃逸路径跳过。
269
+ const abs = path.resolve(svgDir, value);
270
+ const projectRoot = path.resolve(svgDir, '..');
271
+ if (abs !== projectRoot && !abs.startsWith(projectRoot + path.sep))
272
+ continue;
273
+ try {
274
+ const buf = await readFile(abs);
275
+ const mime = EXT_MIME[path.extname(abs).toLowerCase()] ?? 'application/octet-stream';
276
+ replacements.push({
277
+ start,
278
+ end: start + full.length,
279
+ text: `${attr}="data:${mime};base64,${buf.toString('base64')}"`,
280
+ });
281
+ }
282
+ catch {
283
+ // 图片读不到就保留原引用,预览降级但不报错。
284
+ }
285
+ }
286
+ if (replacements.length === 0)
287
+ return svg;
288
+ let out = '';
289
+ let pos = 0;
290
+ for (const r of replacements) {
291
+ out += svg.slice(pos, r.start) + r.text;
292
+ pos = r.end;
293
+ }
294
+ out += svg.slice(pos);
295
+ return out;
296
+ }
@@ -0,0 +1,351 @@
1
+ /**
2
+ * 单页修改的**视觉复核**支撑 —— 把「渲染一页 SVG 成 PNG」变成宿主提供的
3
+ * 一条命令,而不是让模型自己现场摸索渲染器。
4
+ *
5
+ * 为什么需要它(实测结论,2026-09):
6
+ * 本机三条常见光栅化路径全部不可用——
7
+ * - `cairosvg`:内嵌 `<image>` 渲染成纯白(红图测试取到 (255,255,255)),
8
+ * 且无字体回退链,CJK 渲成豆腐块;
9
+ * - snap `chromium`:`snap/chromium/current` 符号链接权限失败;
10
+ * - Playwright 自带 chromium:`Trace/breakpoint trap (core dumped)`。
11
+ * 而 `resvg-py`(纯 wheel,无需系统依赖)两者都正常。
12
+ *
13
+ * 技能文档 `visual-review.md` 其实已写明「Playwright, not cairosvg」,
14
+ * 但单页修改走的 `edit-single-page.md` 一个字都没提渲染器,于是模型只能
15
+ * 反复试错:实测在三次修改里为此各花了 ~35s / 52s / 54s。
16
+ *
17
+ * 设计取舍:
18
+ * - **脚本落在项目内**(`<project>/.host/render_page.py`)而不是技能目录:
19
+ * ppt-master 是用户安装的外部技能,宿主改不到它、改了也会被重装覆盖;
20
+ * 而 `.host/` 在 PPT 工作区内,随项目走、可版本控制、可被 exec 沙箱写入。
21
+ * - **脚本自举 venv**:`python3` 直跑,缺依赖就自建 `<project>/.host/.venv`
22
+ * 并装 `resvg-py`/`pillow`,再 re-exec。这样模型只需记住一条命令,
23
+ * 不必知道 snippet 运行器的 pipPackages 机制。
24
+ * - 幂等写:内容没变就不落盘,避免每次点火都改 mtime(会干扰
25
+ * `listPptPreviews` 的 mtime 变更检测)。
26
+ */
27
+ import { existsSync } from 'node:fs';
28
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
29
+ import { spawn } from 'node:child_process';
30
+ import path from 'node:path';
31
+ /** 宿主工具的落点(项目内隐藏目录;`svg_output/` 之外,不影响质检与预览)。 */
32
+ export const PPT_HOST_DIR_NAME = '.host';
33
+ /** 相对项目根渲染脚本路径。 */
34
+ export const PPT_RENDER_SCRIPT_REL_PATH = path.join(PPT_HOST_DIR_NAME, 'render_page.py');
35
+ /** 渲染脚本绝对路径。 */
36
+ export function pptRenderScriptPath(projectPath) {
37
+ return path.join(projectPath, PPT_RENDER_SCRIPT_REL_PATH);
38
+ }
39
+ /**
40
+ * 渲染脚本正文。
41
+ *
42
+ * 与模型交互的契约(写进单页修改指令,改动时两处要一起改):
43
+ * `python3 <project>/.host/render_page.py <project_path> <svg 文件名> [--out X.png] [--scale N]`
44
+ * 成功时 stdout 打印一行 JSON:`{"ok": true, "out": ..., "width": ..., ...}`。
45
+ */
46
+ export const PPT_RENDER_SCRIPT_SOURCE = `#!/usr/bin/env python3
47
+ """Render one project page (SVG) to PNG — host-provided, self-bootstrapping.
48
+
49
+ Why this exists
50
+ 本机 cairosvg 会把内嵌 <image> 渲染成空白、且 CJK 变豆腐块;chromium
51
+ (snap / playwright) 都起不来。resvg 两者都正常,所以视觉复核只用它。
52
+
53
+ Usage
54
+ python3 <project>/.host/render_page.py <project_path> <page.svg> \\
55
+ [--out /tmp/page.png] [--scale 2]
56
+
57
+ Output
58
+ stdout 是一行 JSON(失败时也打印 JSON 并以非 0 退出):
59
+ {"ok": true, "out": "...", "width": ..., "height": ...,
60
+ "raster_images": N, "ink_ratio": 0.0123,
61
+ "sources": [{"href": "../images/x.png", "path": "...", "exists": true,
62
+ "size": [w, h], "mean_luma": 247.6,
63
+ "light_ratio": 0.923, "dark_ratio": 0.012}]}
64
+
65
+ sources 里每张外部图片的亮度统计,是用来区分"渲染坏了"和"原图本身极浅"
66
+ 的:用户上传的影印件常常 90%+ 像素接近纯白,渲出来看着像空白是忠实还原。
67
+ """
68
+
69
+ import json
70
+ import os
71
+ import subprocess
72
+ import sys
73
+
74
+ VENV_DIRNAME = ".venv"
75
+ SHARED_VENV_DIRNAME = ".host-venv"
76
+ REQUIRED = ("resvg_py", "PIL")
77
+
78
+
79
+ def _fail(message, hint=""):
80
+ print(json.dumps({"ok": False, "error": message, "hint": hint}, ensure_ascii=False))
81
+ sys.exit(1)
82
+
83
+
84
+ def _venv_python(venv_dir):
85
+ if os.name == "nt":
86
+ return os.path.join(venv_dir, "Scripts", "python.exe")
87
+ return os.path.join(venv_dir, "bin", "python")
88
+
89
+
90
+ def _missing_modules():
91
+ missing = []
92
+ for name in REQUIRED:
93
+ try:
94
+ __import__(name)
95
+ except Exception:
96
+ missing.append(name)
97
+ return missing
98
+
99
+
100
+ def _venv_dir(host_dir):
101
+ """Pick the venv location: shared per workspace, else next to this script.
102
+
103
+ 脚本在 <workspace>/<project>/.host/ 下,所以 <workspace>/<project>/.host/../..
104
+ 就是 workspace 根。共享一份 venv 而不是每个项目各装一份(resvg+pillow 约
105
+ 37MB/份)。workspace 与项目同属 exec 沙箱的可写根,所以写它同样安全。
106
+ """
107
+ workspace = os.path.dirname(os.path.dirname(os.path.abspath(host_dir)))
108
+ if workspace and os.path.isdir(workspace):
109
+ return os.path.join(workspace, SHARED_VENV_DIRNAME)
110
+ return os.path.join(host_dir, VENV_DIRNAME)
111
+
112
+
113
+ def _bootstrap():
114
+ """Create a cached venv and re-exec under it."""
115
+ host_dir = os.path.dirname(os.path.abspath(__file__))
116
+ venv_dir = _venv_dir(host_dir)
117
+ venv_python = _venv_python(venv_dir)
118
+ if not os.path.exists(venv_python):
119
+ try:
120
+ subprocess.check_call([sys.executable, "-m", "venv", venv_dir])
121
+ except Exception as exc:
122
+ _fail("cannot create venv at " + venv_dir + ": " + str(exc),
123
+ "ensure python3-venv is available, or install resvg-py manually")
124
+ try:
125
+ subprocess.check_call([
126
+ venv_python, "-m", "pip", "install", "--quiet",
127
+ "--disable-pip-version-check", "resvg-py", "pillow",
128
+ ])
129
+ except Exception as exc:
130
+ _fail("pip install resvg-py pillow failed: " + str(exc),
131
+ "check network / pip mirror availability")
132
+ os.execv(venv_python, [venv_python, os.path.abspath(__file__)] + sys.argv[1:])
133
+
134
+
135
+ def _parse_args(argv):
136
+ if len(argv) < 3:
137
+ _fail("usage: render_page.py <project_path> <page.svg> [--out PNG] [--scale N]")
138
+ project_dir = os.path.abspath(argv[1])
139
+ page = argv[2]
140
+ out = None
141
+ scale = 2.0
142
+ i = 3
143
+ while i < len(argv):
144
+ token = argv[i]
145
+ if token == "--out" and i + 1 < len(argv):
146
+ out = argv[i + 1]
147
+ i += 2
148
+ elif token == "--scale" and i + 1 < len(argv):
149
+ try:
150
+ scale = float(argv[i + 1])
151
+ except ValueError:
152
+ _fail("--scale must be a number")
153
+ i += 2
154
+ else:
155
+ _fail("unknown argument: " + token)
156
+ return project_dir, page, out, scale
157
+
158
+
159
+ def _raster_sources(svg_text, svg_dir):
160
+ """每个引用文件的外部 <image>:路径 + 自身亮度统计。
161
+
162
+ 亮度统计是刻意带的:用户上传的影印件常常本身极浅(实测某页 92% 像素
163
+ 亮度 >=220、均值 247.6),渲出来"看着像空白"是**忠实还原**而非渲染损坏。
164
+ 先把数字给出来,模型就不必再用 PIL 手测一轮。
165
+ """
166
+ import re
167
+ sources = []
168
+ for chunk in re.findall(r"<image\\b[^>]*>", svg_text, flags=re.IGNORECASE):
169
+ match = re.search(r'(?:xlink:href|href)\\s*=\\s*"([^"]*)"', chunk, flags=re.IGNORECASE)
170
+ if not match:
171
+ continue
172
+ href = match.group(1).strip()
173
+ if not href or href.lower().startswith("data:"):
174
+ continue
175
+ resolved = href if os.path.isabs(href) else os.path.normpath(os.path.join(svg_dir, href))
176
+ entry = {"href": href, "path": resolved, "exists": os.path.exists(resolved)}
177
+ if entry["exists"]:
178
+ try:
179
+ from PIL import Image
180
+ import statistics
181
+ with Image.open(resolved) as handle:
182
+ grey = handle.convert("L")
183
+ entry["size"] = list(handle.size)
184
+ histogram = grey.histogram()
185
+ total = sum(histogram) or 1
186
+ entry["mean_luma"] = round(
187
+ sum(value * count for value, count in enumerate(histogram)) / total, 1
188
+ )
189
+ entry["light_ratio"] = round(
190
+ sum(count for value, count in enumerate(histogram) if value >= 220) / total, 3
191
+ )
192
+ entry["dark_ratio"] = round(
193
+ sum(count for value, count in enumerate(histogram) if value < 150) / total, 4
194
+ )
195
+ except Exception as exc:
196
+ entry["error"] = str(exc)
197
+ sources.append(entry)
198
+ return sources
199
+
200
+
201
+
202
+ def _ink_ratio(png_path):
203
+ """Fraction of pixels that are clearly not the white/light background."""
204
+ from PIL import Image
205
+ with Image.open(png_path) as im:
206
+ grey = im.convert("L")
207
+ histogram = grey.histogram()
208
+ total = sum(histogram) or 1
209
+ dark = sum(count for value, count in enumerate(histogram) if value < 200)
210
+ return round(dark / total, 4)
211
+
212
+
213
+ def main():
214
+ # --warmup:只自举依赖,不渲染。
215
+ # 宿主在点火时后台跑它,把"首次渲染要付的建 venv + pip 安装"从 agent 回合里
216
+ # 挪出去——实测冷启动 136s,落在回合内会把整段优化收益吃光。
217
+ if "--warmup" in sys.argv[1:]:
218
+ if _missing_modules():
219
+ _bootstrap()
220
+ print(json.dumps({"ok": True, "warmup": True}, ensure_ascii=False))
221
+ return
222
+
223
+ # 先校验参数再自举:参数错误不该触发建 venv / 装依赖。
224
+ project_dir, page, out, scale = _parse_args(sys.argv)
225
+
226
+ if _missing_modules():
227
+ _bootstrap()
228
+
229
+ import resvg_py
230
+ from PIL import Image # noqa: F401 (imported for the side effect of validating deps)
231
+
232
+ svg_path = page if os.path.isabs(page) else os.path.join(project_dir, "svg_output", page)
233
+ if not os.path.exists(svg_path):
234
+ _fail("svg not found: " + svg_path)
235
+
236
+ try:
237
+ with open(svg_path, "r", encoding="utf-8") as handle:
238
+ svg_text = handle.read()
239
+ except Exception as exc:
240
+ _fail("cannot read svg: " + str(exc))
241
+
242
+ if out is None:
243
+ out = os.path.join("/tmp", os.path.splitext(os.path.basename(svg_path))[0] + ".render.png")
244
+ os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
245
+
246
+ # Canvas 取自 SVG 自身的 width/height(保持与其它页一致的既有契约)。
247
+ import re
248
+ width = None
249
+ height = None
250
+ width_match = re.search(r'<svg[^>]*\\bwidth\\s*=\\s*"([0-9.]+)', svg_text)
251
+ height_match = re.search(r'<svg[^>]*\\bheight\\s*=\\s*"([0-9.]+)', svg_text)
252
+ if width_match:
253
+ width = float(width_match.group(1))
254
+ if height_match:
255
+ height = float(height_match.group(1))
256
+
257
+ render_width = int(round((width or 1280) * scale))
258
+ render_height = int(round((height or 720) * scale))
259
+
260
+ try:
261
+ payload = resvg_py.svg_to_bytes(
262
+ svg_path=svg_path, width=render_width, height=render_height
263
+ )
264
+ except Exception as exc:
265
+ _fail("resvg render failed: " + str(exc))
266
+
267
+ if not payload:
268
+ _fail("resvg returned empty output (page may be blank)")
269
+ with open(out, "wb") as handle:
270
+ handle.write(bytes(payload))
271
+
272
+ try:
273
+ ink = _ink_ratio(out)
274
+ except Exception:
275
+ ink = None
276
+
277
+ sources = _raster_sources(svg_text, os.path.dirname(os.path.abspath(svg_path)))
278
+ print(json.dumps({
279
+ "ok": True,
280
+ "out": out,
281
+ "page": os.path.basename(svg_path),
282
+ "image_size": [render_width, render_height],
283
+ "raster_images": len(sources),
284
+ "ink_ratio": ink,
285
+ "sources": sources,
286
+ }, ensure_ascii=False))
287
+
288
+
289
+ if __name__ == "__main__":
290
+ main()
291
+ `;
292
+ /**
293
+ * 幂等落盘渲染脚本。内容一致时不写(保留 mtime,避免惊动预览的变更检测)。
294
+ *
295
+ * 失败不抛:渲染脚本是「锦上添花」的复核手段,写不进去不该挡住单页修改本身。
296
+ */
297
+ export async function ensurePptRenderScript(projectPath) {
298
+ const target = pptRenderScriptPath(projectPath);
299
+ try {
300
+ const existing = await readFile(target, 'utf8').catch(() => null);
301
+ if (existing === PPT_RENDER_SCRIPT_SOURCE) {
302
+ return { path: target, wrote: false };
303
+ }
304
+ await mkdir(path.dirname(target), { recursive: true });
305
+ await writeFile(target, PPT_RENDER_SCRIPT_SOURCE, 'utf8');
306
+ return { path: target, wrote: true };
307
+ }
308
+ catch (err) {
309
+ console.warn('[ppt-render] 落盘渲染脚本失败(不阻塞修改)', err);
310
+ return { path: target, wrote: false };
311
+ }
312
+ }
313
+ /**
314
+ * 后台预热渲染依赖(建 venv + 装 resvg-py/pillow),**不阻塞**调用方。
315
+ *
316
+ * 为什么必须预热:首次渲染要付一次冷启动成本——实测 `python3 -m venv` +
317
+ * `pip install resvg-py pillow` 合计 **136s**。这段如果落在 agent 回合里
318
+ * (模型按指令去渲染时才触发),会把单页修改的墙钟整个拖长一倍:
319
+ * 实测 P08 回归 370.2s,其中 136.2s 就是这一次自举。
320
+ *
321
+ * 点火时调用它,让自举与模型前几轮(侦察 / 读页 / 排版,通常 60~120s)
322
+ * 重叠。venv 落在 workspace 根(`<workspace>/.host-venv`),同一会话的
323
+ * 后续修改直接复用,不再付这个成本。
324
+ *
325
+ * 失败静默:预热不成功只是让首次渲染慢一点,不该影响修改本身。
326
+ */
327
+ export function warmPptRenderVenv(projectPath) {
328
+ const script = pptRenderScriptPath(projectPath);
329
+ if (!existsSync(script))
330
+ return;
331
+ try {
332
+ const child = spawn(resolveRenderPython(), [script, '--warmup'], {
333
+ detached: true,
334
+ stdio: 'ignore',
335
+ });
336
+ // 解释器缺失等 exec 失败走异步 'error' 事件——fire-and-forget 不监听
337
+ // 就会变成宿主进程的未处理异常;预热失败只意味着首次渲染慢一些。
338
+ child.on('error', (err) => {
339
+ console.warn('[ppt-render] 预热渲染依赖失败(首次渲染会慢一些)', err);
340
+ });
341
+ // 让子进程脱离宿主生命周期:宿主重启不该杀掉预热(venv 是共享的)。
342
+ child.unref();
343
+ }
344
+ catch (err) {
345
+ console.warn('[ppt-render] 预热渲染依赖失败(首次渲染会慢一些)', err);
346
+ }
347
+ }
348
+ /** 跑渲染脚本用的 python(与模型在 shell 里用的一致)。 */
349
+ function resolveRenderPython() {
350
+ return process.env.DEEPPATH_RENDER_PYTHON || 'python3';
351
+ }