@evandu/super-pi 0.1.273 → 0.1.275

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 (97) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-documents/index.ts +16 -1
  3. package/agents/super-pi-task/core.ts +8 -8
  4. package/bin/completion.js +19 -5
  5. package/bin/render-presentation.ps1 +35 -0
  6. package/bin/super-pi.js +3 -0
  7. package/desktop/main.cjs +16 -9
  8. package/desktop/notifications.cjs +2 -1
  9. package/desktop/relaunch.cjs +5 -2
  10. package/desktop/restart-handoff.cjs +35 -0
  11. package/desktop/runtime.cjs +28 -4
  12. package/dist/client/.super-pi-client-sources.json +34 -19
  13. package/dist/client/assets/CodeMirrorEditor-DJgZdigq.js +2 -0
  14. package/dist/client/assets/{GitDiffEditor-CpoDDQrA.css → GitDiffEditor-DIRyUxnb.css} +1 -1
  15. package/dist/client/assets/GitDiffEditor-lOnvlR42.js +29 -0
  16. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  17. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  18. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  19. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  20. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  21. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  22. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  23. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  24. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  25. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  26. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  27. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  28. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  29. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  30. package/dist/client/assets/dist-DeD9copn.js +1 -0
  31. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  32. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  33. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  34. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  35. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  36. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  37. package/dist/client/assets/index-BWm699nV.js +350 -0
  38. package/dist/client/assets/index-CnNljc5p.css +1 -0
  39. package/dist/client/index.html +2 -2
  40. package/dist/server/agents.d.ts +1 -1
  41. package/dist/server/agents.js +10 -3
  42. package/dist/server/application/conversation-service.d.ts +1 -1
  43. package/dist/server/application/conversation-service.js +3 -2
  44. package/dist/server/application/document-service.d.ts +134 -0
  45. package/dist/server/application/document-service.js +9 -0
  46. package/dist/server/application/group-chat-service.d.ts +17 -0
  47. package/dist/server/application/group-chat-service.js +168 -3
  48. package/dist/server/application/group-rsi.d.ts +13 -0
  49. package/dist/server/application/group-rsi.js +69 -0
  50. package/dist/server/application/worktree-service.js +6 -2
  51. package/dist/server/http-server.js +54 -3
  52. package/dist/server/index.js +15 -2
  53. package/dist/server/managed-http.js +2 -1
  54. package/dist/server/managed-model-adapter.d.ts +4 -0
  55. package/dist/server/managed-model-relay.d.ts +1 -1
  56. package/dist/server/managed-model-relay.js +18 -15
  57. package/dist/server/managed-servers.d.ts +10 -1
  58. package/dist/server/managed-servers.js +63 -4
  59. package/dist/server/presentations/brief.d.ts +49 -0
  60. package/dist/server/presentations/brief.js +132 -0
  61. package/dist/server/presentations/inspect.d.ts +15 -0
  62. package/dist/server/presentations/inspect.js +30 -0
  63. package/dist/server/presentations/native.d.ts +8 -0
  64. package/dist/server/presentations/native.js +33 -0
  65. package/dist/server/presentations/render.d.ts +16 -0
  66. package/dist/server/presentations/render.js +152 -0
  67. package/dist/server/presentations/service.d.ts +176 -0
  68. package/dist/server/presentations/service.js +155 -0
  69. package/dist/server/remote-bootstrap.d.ts +11 -0
  70. package/dist/server/remote-bootstrap.js +105 -29
  71. package/dist/server/runtime.js +3 -2
  72. package/dist/shared/group-chat.d.ts +40 -0
  73. package/dist/shared/message-source-link.d.ts +1 -0
  74. package/dist/shared/message-source-link.js +4 -0
  75. package/dist/shared/workspace-file-preview.d.ts +1 -1
  76. package/dist/shared/workspace-file-preview.js +2 -0
  77. package/package.json +5 -1
  78. package/skills/presentation/SKILL.md +23 -1
  79. package/skills/presentation/references/spec.md +15 -0
  80. package/dist/client/assets/CodeMirrorEditor-D8MjtASz.js +0 -2
  81. package/dist/client/assets/GitDiffEditor-DFJmhUHc.js +0 -29
  82. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  83. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  84. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  85. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  86. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  87. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  88. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  89. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  90. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  91. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  92. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  93. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  94. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  95. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  96. package/dist/client/assets/index-Bqutm6qV.js +0 -350
  97. package/dist/client/assets/index-DV3qc1Hh.css +0 -1
@@ -0,0 +1,33 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ let queue = Promise.resolve();
7
+ /** Native rendering is optional and serialized; a failed engine never masquerades as verified. */
8
+ export async function nativePreview(path, count) {
9
+ if (process.env.SUPER_PI_PRESENTATION_NATIVE === "0" || process.platform !== "win32")
10
+ return { reason: "此服务端未启用原生办公引擎,提供 PNG 布局预览。" };
11
+ const task = queue.catch(() => { }).then(async () => {
12
+ const directory = await mkdtemp(join(tmpdir(), "super-pi-native-ppt-"));
13
+ try {
14
+ await new Promise((resolve, reject) => execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", fileURLToPath(new URL("../../../bin/render-presentation.ps1", import.meta.url)), "-InputFile", path, "-OutputDirectory", directory], { windowsHide: true, timeout: 60_000, maxBuffer: 64 * 1024 }, (error, _stdout, stderr) => error ? reject(new Error(stderr.trim().slice(0, 1000) || error.message)) : resolve()));
15
+ const pages = [];
16
+ for (let index = 1; index <= count; index++) {
17
+ const bytes = await readFile(join(directory, `slide-${index}.png`));
18
+ if (bytes.length < 100 || bytes.subarray(1, 4).toString() !== "PNG")
19
+ throw new Error("原生引擎未导出完整 PNG");
20
+ pages.push(bytes);
21
+ }
22
+ return { pages, engine: "Microsoft PowerPoint" };
23
+ }
24
+ catch (error) {
25
+ return { reason: `原生渲染未完成,保留布局预览:${String(error instanceof Error ? error.message : error).slice(0, 1200)}` };
26
+ }
27
+ finally {
28
+ await rm(directory, { recursive: true, force: true, maxRetries: 4 });
29
+ }
30
+ });
31
+ queue = task;
32
+ return task;
33
+ }
@@ -0,0 +1,16 @@
1
+ import type { PresentationSpec, PresentationSlide } from "./schema.js";
2
+ export type LayoutWarning = {
3
+ slideId: string;
4
+ elementId: string;
5
+ message: string;
6
+ };
7
+ export declare function rasterPreviews(spec: PresentationSpec, previews: string[]): Promise<{
8
+ pages: Buffer<ArrayBufferLike>[];
9
+ sheets: Buffer<ArrayBufferLike>[];
10
+ }>;
11
+ export declare function writePptx(spec: PresentationSpec): Promise<Buffer>;
12
+ /** SVG is a layout preview, never evidence that an office engine rendered the PPTX. */
13
+ export declare function layoutPreview(spec: PresentationSpec, page: PresentationSlide): {
14
+ svg: string;
15
+ warnings: LayoutWarning[];
16
+ };
@@ -0,0 +1,152 @@
1
+ import { fileURLToPath } from "node:url";
2
+ export async function rasterPreviews(spec, previews) {
3
+ const { Resvg } = await import("@resvg/resvg-js").catch(() => { throw new Error("缺少 PNG 预览组件 @resvg/resvg-js,请修复 Super Pi 安装。"); });
4
+ const font = { fontFiles: ["NotoSansSC-Regular.otf", "NotoSansSC-Bold.otf"].map(name => fileURLToPath(new URL(`../../../assets/fonts/${name}`, import.meta.url))), loadSystemFonts: false, defaultFontFamily: "Noto Sans SC" };
5
+ const render = (svg, width) => new Resvg(svg, { fitTo: { mode: "width", value: width }, font }).render().asPng();
6
+ const width = 640, height = width * spec.canvas.height / spec.canvas.width;
7
+ const sheets = [];
8
+ // Bounded contact sheets allow one visual review per ten slides instead of one tool per slide.
9
+ for (let offset = 0; offset < previews.length; offset += 10) {
10
+ const pages = previews.slice(offset, offset + 10);
11
+ const body = pages.map((svg, i) => svg.replace("<svg ", `<svg x="${(i % 2) * width}" y="${Math.floor(i / 2) * height}" `).replace(/width="[^"]+" height="[^"]+"/, `width="${width}" height="${height}"`)).join("");
12
+ sheets.push(render(`<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="${Math.ceil(pages.length / 2) * height}"><rect width="1280" height="100%" fill="#F8FAFD"/>${body}</svg>`, 1280));
13
+ }
14
+ return { pages: previews.map(svg => render(svg, 1280)), sheets };
15
+ }
16
+ const xml = (value) => String(value ?? "").replace(/[<>&"']/g, c => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c]);
17
+ const color = (value, fallback = "233047") => {
18
+ const clean = value?.replace(/^#/, "") ?? fallback;
19
+ if (!/^[\da-f]{6}$/i.test(clean))
20
+ throw new Error(`颜色必须为六位 RGB:${value}`);
21
+ return clean;
22
+ };
23
+ const palette = ["245BA8", "14927C", "C67921", "8554AC", "C54565", "52627A"];
24
+ export async function writePptx(spec) {
25
+ const { default: PptxGenJS } = await import("pptxgenjs").catch(() => { throw new Error("缺少演示文稿依赖 pptxgenjs,请修复 Super Pi 安装。"); });
26
+ const Constructor = PptxGenJS;
27
+ const pptx = new Constructor();
28
+ pptx.defineLayout({ name: "SUPER_PI", width: spec.canvas.width, height: spec.canvas.height });
29
+ pptx.layout = "SUPER_PI";
30
+ pptx.author = spec.metadata?.author ?? "Super Pi";
31
+ pptx.subject = spec.metadata?.subject ?? "";
32
+ pptx.title = spec.metadata?.title ?? "Presentation";
33
+ for (const page of spec.slides) {
34
+ const slide = pptx.addSlide();
35
+ slide.background = { color: color(page.background, "FFFFFF") };
36
+ if (page.notes)
37
+ slide.addNotes(page.notes);
38
+ for (const element of page.elements) {
39
+ if (element.hidden)
40
+ continue;
41
+ const frame = { x: element.x, y: element.y, w: element.width, h: element.height, rotate: element.rotation ?? 0, altText: element.altText, objectName: element.name ?? element.id };
42
+ if (element.type === "text")
43
+ slide.addText(element.text, { ...frame, fontFace: element.fontFamily ?? "Noto Sans SC", fontSize: element.fontSize ?? 22, color: color(element.color), bold: element.bold, italic: element.italic, align: element.align ?? "left", valign: element.verticalAlign === "middle" ? "middle" : element.verticalAlign === "bottom" ? "bottom" : "top", margin: 0, breakLine: false });
44
+ else if (element.type === "table") {
45
+ if (!element.rows.length || element.rows.some(row => !Array.isArray(row) || row.length !== element.rows[0].length || row.some(cell => cell !== null && !["string", "number", "boolean"].includes(typeof cell))))
46
+ throw new Error(`表格 ${element.id} 必须为非空矩形标量数组`);
47
+ slide.addTable(element.rows.map((row, index) => row.map(cell => ({ text: String(cell ?? ""), options: { fill: { color: index < (element.headerRows ?? 1) ? "245BA8" : index % 2 ? "EDF2F8" : "FFFFFF" }, color: index < (element.headerRows ?? 1) ? "FFFFFF" : "233047", bold: index < (element.headerRows ?? 1) } }))), { ...frame, fontFace: "Noto Sans SC", fontSize: Math.max(12, Math.min(20, 200 / element.rows.length)), margin: .12, border: { type: "solid", color: "D9E1EC", pt: .5 }, rowH: element.height / element.rows.length, autoPage: false });
48
+ }
49
+ else if (element.type === "chart") {
50
+ validateChart(element);
51
+ const chartType = element.chart === "column" ? "bar" : element.chart;
52
+ slide.addChart(chartType, element.series.map(series => ({ name: series.name, labels: element.categories, values: series.values })), { ...frame, barDir: element.chart === "bar" ? "bar" : "col", showLegend: element.showLegend ?? element.series.length > 1, legendPos: "b", showValue: element.showValues ?? true, chartColors: palette, showTitle: false, catAxisLabelFontSize: 12, valAxisLabelFontSize: 12, dataLabelFormatCode: "0.##", showLabel: element.chart === "pie" || element.chart === "doughnut" });
53
+ }
54
+ else if (element.type === "shape") {
55
+ const shape = { rectangle: "rect", roundRectangle: "roundRect", ellipse: "ellipse", triangle: "triangle", chevron: "chevron" }[element.shape];
56
+ if (!shape)
57
+ throw new Error(`不支持形状:${element.shape}`);
58
+ slide.addShape(shape, { ...frame, fill: { color: color(element.fill, "EDF2F8") }, line: { color: color(element.stroke, "D9E1EC"), width: element.strokeWidth ?? 0 } });
59
+ }
60
+ else if (element.type === "line")
61
+ slide.addShape("line", { ...frame, line: { color: color(element.stroke), width: element.strokeWidth ?? 1 } });
62
+ else
63
+ throw new Error("当前制作器暂不支持图片元素;请使用文本、原生图表和表格,不能静默遗漏图片。");
64
+ }
65
+ }
66
+ return Buffer.from(await pptx.write({ outputType: "nodebuffer" }));
67
+ }
68
+ function validateChart(chart) {
69
+ if (!["bar", "column", "line", "area", "pie", "doughnut"].includes(chart.chart))
70
+ throw new Error(`暂不支持图表类型:${chart.chart}`);
71
+ if (!chart.categories?.length || chart.categories.some(item => typeof item !== "string") || chart.series.some(series => series.values.length !== chart.categories.length || series.values.some(v => typeof v !== "number" || !Number.isFinite(v))))
72
+ throw new Error(`图表 ${chart.id} 的分类与数值必须完整对应,且为有限数字`);
73
+ if (["pie", "doughnut"].includes(chart.chart) && (chart.series.length !== 1 || chart.series[0].values.some(v => v < 0) || !chart.series[0].values.some(v => v > 0)))
74
+ throw new Error("饼图和环图需要一个非负且总和大于零的数值系列");
75
+ }
76
+ /** SVG is a layout preview, never evidence that an office engine rendered the PPTX. */
77
+ export function layoutPreview(spec, page) {
78
+ const scale = 96;
79
+ const warnings = [];
80
+ const rect = (x, y, w, h, fill) => `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="#${color(fill)}"/>`;
81
+ const label = (text, x, y, size, fill = "233047", bold = false) => `<text x="${x}" y="${y}" font-size="${size}" fill="#${color(fill)}"${bold ? ' font-weight="700"' : ""}>${xml(text)}</text>`;
82
+ const draw = (e) => {
83
+ if (e.hidden)
84
+ return "";
85
+ const x = e.x * scale, y = e.y * scale, w = e.width * scale, h = e.height * scale;
86
+ if (e.type === "text") {
87
+ const size = (e.fontSize ?? 22) * scale / 72, lines = [];
88
+ const capacity = Math.max(1, Math.floor(w / size));
89
+ for (const paragraph of e.text.split("\n")) {
90
+ let line = "", units = 0;
91
+ for (const ch of paragraph) {
92
+ const width = /[\u0000-\u00ff]/.test(ch) ? .55 : 1;
93
+ if (units + width > capacity) {
94
+ lines.push(line);
95
+ line = "";
96
+ units = 0;
97
+ }
98
+ line += ch;
99
+ units += width;
100
+ }
101
+ lines.push(line);
102
+ }
103
+ if (lines.length * size * 1.25 > h)
104
+ warnings.push({ slideId: page.id, elementId: e.id, message: "文字可能超出文本框(估算);请缩短文字或调整布局。" });
105
+ return `<g font-family="${xml(e.fontFamily ?? "Noto Sans SC, sans-serif")}">${lines.map((line, i) => label(line, e.align === "center" ? x + (w - line.length * size * .65) / 2 : x, y + size + i * size * 1.25, size, e.color, e.bold)).join("")}</g>`;
106
+ }
107
+ if (e.type === "shape")
108
+ return e.shape === "ellipse" ? `<ellipse cx="${x + w / 2}" cy="${y + h / 2}" rx="${w / 2}" ry="${h / 2}" fill="#${color(e.fill, "EDF2F8")}"/>` : rect(x, y, w, h, e.fill ?? "EDF2F8");
109
+ if (e.type === "line")
110
+ return `<path d="M${x} ${y}L${x + w} ${y + h}" stroke="#${color(e.stroke)}"/>`;
111
+ if (e.type === "table")
112
+ return e.rows.map((row, i) => row.map((cell, j) => rect(x + j * w / row.length, y + i * h / e.rows.length, w / row.length, h / e.rows.length, i === 0 ? "245BA8" : i % 2 ? "EDF2F8" : "FFFFFF") + label(String(cell ?? ""), x + j * w / row.length + 8, y + (i + .55) * h / e.rows.length, 16, i === 0 ? "FFFFFF" : "233047")).join("")).join("");
113
+ if (e.type !== "chart")
114
+ return "";
115
+ validateChart(e);
116
+ const categories = e.categories, all = e.series.flatMap(s => s.values), max = Math.max(0, ...all), min = Math.min(0, ...all), span = max - min || 1;
117
+ const px = x + 100, py = y + 20, pw = w - 125, ph = h - 65;
118
+ let svg = "";
119
+ if (e.chart === "pie" || e.chart === "doughnut") {
120
+ const total = all.reduce((a, b) => a + b, 0);
121
+ let angle = -Math.PI / 2;
122
+ const cx = x + w * .4, cy = y + h * .48, r = Math.min(w * .3, h * .4);
123
+ all.forEach((v, i) => { const end = angle + 2 * Math.PI * v / (total || 1); const dx = cx + r * Math.cos(angle), dy = cy + r * Math.sin(angle), ex = cx + r * Math.cos(end), ey = cy + r * Math.sin(end); svg += v === total ? `<circle cx="${cx}" cy="${cy}" r="${r}" fill="#${palette[i % 6]}"/>` : `<path d="M${cx} ${cy}L${dx} ${dy}A${r} ${r} 0 ${end - angle > Math.PI ? 1 : 0} 1 ${ex} ${ey}Z" fill="#${palette[i % 6]}"/>`; svg += label(`${categories[i]}: ${v}`, x + w * .75, y + 30 + i * 26, 14); angle = end; });
124
+ if (e.chart === "doughnut")
125
+ svg += `<circle cx="${cx}" cy="${cy}" r="${r * .55}" fill="#${color(page.background, "FFFFFF")}"/>`;
126
+ }
127
+ else {
128
+ const horizontal = e.chart === "bar", n = categories.length, count = e.series.length;
129
+ categories.forEach((cat, i) => { svg += label(cat, horizontal ? x : px + (i + .3) * pw / n, horizontal ? py + (i + .5) * ph / n : py + ph + 22, 13); });
130
+ e.series.forEach((s, j) => {
131
+ const points = [];
132
+ s.values.forEach((v, i) => {
133
+ const value = v, normalized = (value - min) / span, zero = (0 - min) / span;
134
+ if (e.chart === "line" || e.chart === "area")
135
+ points.push(`${px + (i + .5) * pw / n},${py + ph - normalized * ph}`);
136
+ else if (horizontal)
137
+ svg += rect(px + Math.min(zero, normalized) * pw, py + (i + j / count) * ph / n, Math.abs(value) / span * pw, ph / n / count * .7, palette[j % 6]);
138
+ else
139
+ svg += rect(px + (i + j / count) * pw / n, py + ph - Math.max(normalized, zero) * ph, pw / n / count * .7, Math.abs(value) / span * ph, palette[j % 6]);
140
+ if (e.showValues !== false)
141
+ svg += label(String(value), horizontal ? px + normalized * pw + 4 : px + (i + j / count) * pw / n, horizontal ? py + (i + (j + .6) / count) * ph / n : py + ph - normalized * ph - 4, 12);
142
+ });
143
+ if (points.length)
144
+ svg += `<polyline points="${points.join(" ")}" fill="none" stroke="#${palette[j % 6]}" stroke-width="3"/>`;
145
+ if (e.showLegend !== false)
146
+ svg += label(s.name, px + j * 160, y + h, 13, palette[j % 6]);
147
+ });
148
+ }
149
+ return svg;
150
+ };
151
+ return { svg: `<svg xmlns="http://www.w3.org/2000/svg" width="${spec.canvas.width * scale}" height="${spec.canvas.height * scale}" viewBox="0 0 ${spec.canvas.width * scale} ${spec.canvas.height * scale}" role="img" aria-label="${xml(page.title)}"><title>${xml(page.title)}</title>${rect(0, 0, spec.canvas.width * scale, spec.canvas.height * scale, page.background ?? "FFFFFF")}${page.elements.map(draw).join("")}</svg>`, warnings };
152
+ }
@@ -0,0 +1,176 @@
1
+ import { type PresentationSource } from "./brief.js";
2
+ import { inspectPptx } from "./inspect.js";
3
+ export declare const PRESENTATION_TOOL_NAMES: string[];
4
+ export declare function readPresentation(root: string, path: string, slideId?: string): Promise<{
5
+ version: 1;
6
+ etag: string;
7
+ operation: string;
8
+ sourceHash: string;
9
+ title: string;
10
+ verification: "layout-only" | "native-office";
11
+ renderer: string;
12
+ nativeReason?: string;
13
+ inspection: Awaited<ReturnType<typeof inspectPptx>>;
14
+ contactSheets: {
15
+ asset: string;
16
+ hash: string;
17
+ }[];
18
+ warnings: {
19
+ slideId: string;
20
+ elementId: string;
21
+ message: string;
22
+ }[];
23
+ baseline?: {
24
+ path: string;
25
+ etag: string;
26
+ };
27
+ slides: {
28
+ id: string;
29
+ title: string;
30
+ notes: string;
31
+ asset: string;
32
+ hash: string;
33
+ }[];
34
+ source: PresentationSource;
35
+ path: string;
36
+ contactSheetPaths: string[];
37
+ link: string;
38
+ }>;
39
+ export declare function presentationAsset(root: string, path: string, asset: string): Promise<{
40
+ bytes: Buffer<ArrayBuffer>;
41
+ type: string;
42
+ }>;
43
+ export declare function presentationTool(root: string, body: Record<string, unknown>): Promise<{
44
+ version: 1;
45
+ etag: string;
46
+ operation: string;
47
+ sourceHash: string;
48
+ title: string;
49
+ verification: "layout-only" | "native-office";
50
+ renderer: string;
51
+ nativeReason?: string;
52
+ inspection: Awaited<ReturnType<typeof inspectPptx>>;
53
+ contactSheets: {
54
+ asset: string;
55
+ hash: string;
56
+ }[];
57
+ warnings: {
58
+ slideId: string;
59
+ elementId: string;
60
+ message: string;
61
+ }[];
62
+ baseline?: {
63
+ path: string;
64
+ etag: string;
65
+ };
66
+ slides: {
67
+ id: string;
68
+ title: string;
69
+ notes: string;
70
+ asset: string;
71
+ hash: string;
72
+ }[];
73
+ source: PresentationSource;
74
+ path: string;
75
+ contactSheetPaths: string[];
76
+ link: string;
77
+ } | {
78
+ version: 1;
79
+ etag: string;
80
+ operation: string;
81
+ sourceHash: string;
82
+ title: string;
83
+ verification: "layout-only" | "native-office";
84
+ renderer: string;
85
+ nativeReason?: string;
86
+ inspection: Awaited<ReturnType<typeof inspectPptx>>;
87
+ contactSheets: {
88
+ asset: string;
89
+ hash: string;
90
+ }[];
91
+ slides: {
92
+ id: string;
93
+ title: string;
94
+ notes: string;
95
+ asset: string;
96
+ hash: string;
97
+ }[];
98
+ warnings: {
99
+ slideId: string;
100
+ elementId: string;
101
+ message: string;
102
+ }[];
103
+ baseline?: {
104
+ path: string;
105
+ etag: string;
106
+ };
107
+ path: string;
108
+ contactSheetPaths: string[];
109
+ reused: boolean;
110
+ link: string;
111
+ } | {
112
+ version: 1;
113
+ etag: string;
114
+ operation: string;
115
+ sourceHash: string;
116
+ title: string;
117
+ verification: "layout-only" | "native-office";
118
+ renderer: string;
119
+ nativeReason?: string;
120
+ inspection: Awaited<ReturnType<typeof inspectPptx>>;
121
+ contactSheets: {
122
+ asset: string;
123
+ hash: string;
124
+ }[];
125
+ slides: {
126
+ id: string;
127
+ title: string;
128
+ notes: string;
129
+ asset: string;
130
+ hash: string;
131
+ }[];
132
+ warnings: {
133
+ slideId: string;
134
+ elementId: string;
135
+ message: string;
136
+ }[];
137
+ baseline?: {
138
+ path: string;
139
+ etag: string;
140
+ };
141
+ path: string;
142
+ bytes: number;
143
+ contactSheetPaths: string[];
144
+ link: string;
145
+ } | {
146
+ path: string;
147
+ etag: string;
148
+ verification: "layout-only" | "native-office";
149
+ renderer: string;
150
+ nativeReason: string | undefined;
151
+ inspection: {
152
+ slides: number;
153
+ notes: number;
154
+ nativeCharts: number;
155
+ nativeTables: number;
156
+ editableTextShapes: number;
157
+ embeddedWorkbooks: number;
158
+ canvasInches: {
159
+ width: number;
160
+ height: number;
161
+ } | undefined;
162
+ relationships: string;
163
+ verification: string;
164
+ };
165
+ warnings: {
166
+ slideId: string;
167
+ elementId: string;
168
+ message: string;
169
+ }[];
170
+ sheet: number;
171
+ totalSheets: number;
172
+ images: {
173
+ mimeType: string;
174
+ data: string;
175
+ }[];
176
+ }>;
@@ -0,0 +1,155 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants } from "node:fs";
3
+ import { copyFile, mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
4
+ import { dirname, extname } from "node:path";
5
+ import { resolveInsideRoot } from "../files.js";
6
+ import { compile, patchSource, safeJson } from "./brief.js";
7
+ import { layoutPreview, rasterPreviews, writePptx } from "./render.js";
8
+ import { nativePreview } from "./native.js";
9
+ import { inspectPptx } from "./inspect.js";
10
+ export const PRESENTATION_TOOL_NAMES = ["presentation_create", "presentation_read", "presentation_edit", "presentation_render"];
11
+ const hash = (value) => createHash("sha256").update(value).digest("hex");
12
+ const pending = new Map();
13
+ async function boundedJson(path) {
14
+ if ((await stat(path)).size > 8 * 1024 * 1024)
15
+ throw new Error("制作源超过 8 MiB");
16
+ return safeJson(await readFile(path, "utf8"));
17
+ }
18
+ async function deckBytes(path) {
19
+ if ((await stat(path)).size > 100 * 1024 * 1024)
20
+ throw new Error("演示稿超过 100 MiB,不能读取制作记录");
21
+ return readFile(path);
22
+ }
23
+ async function managed(root, path) {
24
+ const absolute = await resolveInsideRoot(root, path);
25
+ const manifest = await boundedJson(await resolveInsideRoot(root, `${path}.superpi/manifest.json`));
26
+ const etag = hash(await deckBytes(absolute));
27
+ if (manifest.version !== 1 || manifest.etag !== etag || !Array.isArray(manifest.slides))
28
+ throw new Error("PPTX 已被外部修改或制作记录失效;保留文件,请勿使用过期源稿继续修改。");
29
+ const source = await boundedJson(await resolveInsideRoot(root, `${path}.superpi/source.json`));
30
+ if (hash(JSON.stringify(source)) !== manifest.sourceHash)
31
+ throw new Error("制作源已被外部修改,请另存后重新创建,不能假定与 PPTX 一致。");
32
+ return { absolute, manifest, source };
33
+ }
34
+ export async function readPresentation(root, path, slideId) {
35
+ const { manifest, source } = await managed(root, path);
36
+ if (slideId) {
37
+ const deck = source.kind === "brief" ? source.brief : source.spec;
38
+ if (!deck.slides.some(slide => slide.id === slideId))
39
+ throw new Error(`页面不存在:${slideId}`);
40
+ deck.slides = deck.slides.filter(slide => slide.id === slideId);
41
+ }
42
+ return { ...manifest, slides: slideId ? manifest.slides.filter(slide => slide.id === slideId) : manifest.slides, source, path, contactSheetPaths: manifest.contactSheets.map(sheet => `${path}.superpi/${sheet.asset}`), link: `[打开演示稿](${path.replaceAll(" ", "%20")})` };
43
+ }
44
+ export async function presentationAsset(root, path, asset) {
45
+ const { manifest } = await managed(root, path);
46
+ if (asset === "source.json")
47
+ return { bytes: Buffer.from(JSON.stringify((await managed(root, path)).source, null, 2)), type: "application/json; charset=utf-8" };
48
+ const slide = [...manifest.slides, ...manifest.contactSheets].find(item => item.asset === asset);
49
+ if (!slide)
50
+ throw new Error("预览不存在");
51
+ const bytes = await readFile(await resolveInsideRoot(root, `${path}.superpi/${asset}`));
52
+ if (hash(bytes) !== slide.hash)
53
+ throw new Error("预览已被外部修改,请重新制作");
54
+ return { bytes, type: "image/png" };
55
+ }
56
+ async function publish(root, path, source, baseline) {
57
+ if (extname(path).toLowerCase() !== ".pptx")
58
+ throw new Error("目标必须是 .pptx");
59
+ const absolute = await resolveInsideRoot(root, path);
60
+ const previous = pending.get(absolute) ?? Promise.resolve();
61
+ const task = previous.catch(() => { }).then(async () => {
62
+ const operation = hash(JSON.stringify({ source, baseline }));
63
+ if (await stat(absolute).catch(() => null)) {
64
+ const existing = await managed(root, path).catch(() => null);
65
+ if (existing?.manifest.operation === operation)
66
+ return { ...existing.manifest, path, contactSheetPaths: existing.manifest.contactSheets.map(sheet => `${path}.superpi/${sheet.asset}`), reused: true, link: `[打开演示稿](${path.replaceAll(" ", "%20")})` };
67
+ throw new Error(`文件已存在,拒绝覆盖:${path}。请选择新版本路径。`);
68
+ }
69
+ const spec = compile(source);
70
+ const previews = spec.slides.map(slide => layoutPreview(spec, slide));
71
+ let raster = await rasterPreviews(spec, previews.map(item => item.svg));
72
+ const bytes = await writePptx(spec);
73
+ const inspection = await inspectPptx(bytes);
74
+ if (baseline && hash(await readFile(await resolveInsideRoot(root, baseline.path))) !== baseline.etag)
75
+ throw new Error("原稿在制作期间发生变化,未发布新版本");
76
+ await mkdir(dirname(absolute), { recursive: true });
77
+ // Exclusive directory reservation prevents concurrent writers and partial retry corruption.
78
+ const directory = await resolveInsideRoot(root, `${path}.superpi`);
79
+ await mkdir(directory);
80
+ let published = false;
81
+ try {
82
+ await writeFile(`${directory}/artifact.pptx`, bytes, { flag: "wx" });
83
+ const native = await nativePreview(`${directory}/artifact.pptx`, spec.slides.length);
84
+ if ("pages" in native) {
85
+ const images = native.pages.map(png => `<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="${1280 * spec.canvas.height / spec.canvas.width}" viewBox="0 0 1280 ${1280 * spec.canvas.height / spec.canvas.width}"><image width="1280" height="${1280 * spec.canvas.height / spec.canvas.width}" href="data:image/png;base64,${png.toString("base64")}"/></svg>`);
86
+ raster = { pages: native.pages, sheets: (await rasterPreviews(spec, images)).sheets };
87
+ }
88
+ const manifest = { version: 1, operation, etag: hash(bytes), sourceHash: hash(JSON.stringify(source)), title: spec.metadata?.title ?? "Presentation", verification: "pages" in native ? "native-office" : "layout-only", renderer: "pages" in native ? native.engine : "Super Pi SVG + resvg", nativeReason: "reason" in native ? native.reason : undefined, inspection, baseline, contactSheets: raster.sheets.map((png, index) => ({ asset: `overview-${index + 1}.png`, hash: hash(png) })), slides: spec.slides.map((slide, index) => ({ id: slide.id, title: slide.title ?? slide.id, notes: slide.notes ?? "", asset: `slide-${index + 1}.png`, hash: hash(raster.pages[index]) })), warnings: previews.flatMap(item => item.warnings) };
89
+ await writeFile(`${directory}/source.json`, JSON.stringify(source, null, 2), { flag: "wx" });
90
+ for (const [index, preview] of raster.pages.entries())
91
+ await writeFile(`${directory}/${manifest.slides[index].asset}`, preview, { flag: "wx" });
92
+ for (const [index, preview] of raster.sheets.entries())
93
+ await writeFile(`${directory}/${manifest.contactSheets[index].asset}`, preview, { flag: "wx" });
94
+ await writeFile(`${directory}/manifest.json`, JSON.stringify(manifest, null, 2), { flag: "wx" });
95
+ if (baseline && hash(await deckBytes(await resolveInsideRoot(root, baseline.path))) !== baseline.etag) {
96
+ throw new Error("原稿在预览生成期间发生变化,未发布新版本");
97
+ }
98
+ await copyFile(`${directory}/artifact.pptx`, absolute, constants.COPYFILE_EXCL);
99
+ published = true;
100
+ return { ...manifest, path, bytes: bytes.length, contactSheetPaths: manifest.contactSheets.map(sheet => `${path}.superpi/${sheet.asset}`), link: `[打开演示稿](${path.replaceAll(" ", "%20")})` };
101
+ }
102
+ finally {
103
+ // Only remove this call's exclusive reservation on failure; never touch an existing deck.
104
+ if (!published)
105
+ await rm(directory, { recursive: true, force: true });
106
+ }
107
+ });
108
+ pending.set(absolute, task);
109
+ try {
110
+ return await task;
111
+ }
112
+ finally {
113
+ if (pending.get(absolute) === task)
114
+ pending.delete(absolute);
115
+ }
116
+ }
117
+ export async function presentationTool(root, body) {
118
+ const path = String(body.path ?? "");
119
+ if (!path)
120
+ throw new Error("缺少 path");
121
+ if (body.action === "presentation_read")
122
+ return readPresentation(root, path, typeof body.slideId === "string" ? body.slideId : undefined);
123
+ if (body.action === "presentation_render") {
124
+ const { manifest } = await managed(root, path);
125
+ const sheet = body.sheet === undefined ? 0 : Number(body.sheet);
126
+ if (!Number.isInteger(sheet) || sheet < 0 || !manifest.contactSheets[sheet])
127
+ throw new Error("拼版编号无效(从 0 开始,每张至多十页)");
128
+ const image = await presentationAsset(root, path, manifest.contactSheets[sheet].asset);
129
+ return { path, etag: manifest.etag, verification: manifest.verification, renderer: manifest.renderer, nativeReason: manifest.nativeReason, inspection: manifest.inspection, warnings: manifest.warnings, sheet, totalSheets: manifest.contactSheets.length, images: [{ mimeType: "image/png", data: image.bytes.toString("base64") }] };
130
+ }
131
+ const input = async (inline, sourcePath) => {
132
+ if (typeof inline === "string" && typeof sourcePath === "string")
133
+ throw new Error("JSON 与 JSON 路径只能提供一个");
134
+ if (typeof inline === "string")
135
+ return safeJson(inline);
136
+ if (typeof sourcePath === "string")
137
+ return boundedJson(await resolveInsideRoot(root, sourcePath));
138
+ throw new Error("需要 JSON 字符串或工作区内 JSON 路径");
139
+ };
140
+ if (body.action === "presentation_create") {
141
+ const json = await input(body.brief, body.briefPath);
142
+ const source = json.version === 1 && json.canvas ? { kind: "spec", spec: json } : { kind: "brief", brief: json };
143
+ return publish(root, path, source);
144
+ }
145
+ if (body.action === "presentation_edit") {
146
+ const original = await managed(root, path);
147
+ if (body.baseEtag !== original.manifest.etag)
148
+ throw new Error("原稿版本不匹配,请先 presentation_read 获取 etag");
149
+ const outputPath = String(body.outputPath ?? "");
150
+ if (!outputPath || await resolveInsideRoot(root, outputPath) === original.absolute)
151
+ throw new Error("修改必须提供不同的 outputPath;原稿不可覆盖");
152
+ return publish(root, outputPath, patchSource(original.source, await input(body.patch, body.patchPath)), { path, etag: original.manifest.etag });
153
+ }
154
+ throw new Error("不支持的演示文稿操作");
155
+ }
@@ -5,8 +5,18 @@ export interface RemoteInstallation {
5
5
  packageRoot: string;
6
6
  node: string;
7
7
  piCommand: string;
8
+ archiveHash?: string;
8
9
  }
9
10
  export declare function uploadFile(client: Client, local: string, remote: string): Promise<void>;
11
+ interface NodeDownloadOptions {
12
+ fetch?: typeof fetch;
13
+ fallbackDelayMs?: number;
14
+ progress?: (step: string) => void;
15
+ }
16
+ export declare const NODE_RUNTIME_VERSION = "v22.20.0";
17
+ export declare const NODE_RUNTIME_CHECKSUMS: Readonly<Record<string, string>>;
18
+ export declare function nodeArchive(platform: string, arch: string, directory: string, options?: NodeDownloadOptions): Promise<string>;
19
+ export declare function downloadVerifiedNodeArchive(filename: string, expected: string, directory: string, options?: NodeDownloadOptions): Promise<string>;
10
20
  export declare function installRemote(options: {
11
21
  client: Client;
12
22
  id: string;
@@ -17,3 +27,4 @@ export declare function installRemote(options: {
17
27
  }): Promise<RemoteInstallation>;
18
28
  export declare function remoteStartScript(installation: RemoteInstallation, port: number, host?: ServiceListenHost): string;
19
29
  export declare function startRemote(client: Client, installation: RemoteInstallation, port: number, host?: ServiceListenHost): Promise<void>;
30
+ export {};