Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(docs): cindy_docs 内置文档工具面——任意任务直接产出 PDF/Word/PPT/Excel (#3049)

Chris Zhang62c62dd8d001
diff --git a/apps/desktop/forge.config.ts b/apps/desktop/forge.config.ts
index f012002a82..bc118c28e8 100644
--- a/apps/desktop/forge.config.ts
+++ b/apps/desktop/forge.config.ts
@@ -21,6 +21,8 @@ import {
} from '@cindy/maker-shared/brand-identity';
import { stageMacIOSSimulatorHelper } from './forge-ios-simulator-helper';
import { stagePackagedThirdPartyNotices } from './forge-third-party-notices';
+import { READ_SHEET_RUNTIME_PACKAGES } from '../../packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps';
+import { reviewPdfRuntimePackages } from './src/main/reviewer/reviewPdfRuntimeDeps';
const _require = createRequire(__filename);
const DESKTOP_PACKAGE_VERSION = (_require('./package.json') as { version: string }).version;
@@ -253,8 +255,12 @@ function resolveOptions(fromDirs?: string[]): { paths: string[] } | undefined {
}
function copyDiscordRuntimeDeps(destModules: string): void {
+ copyRuntimeDependencyTrees(DISCORD_RUNTIME_DEPS, destModules);
+}
+
+function copyRuntimeDependencyTrees(deps: readonly string[], destModules: string): void {
const seen = new Set<string>();
- for (const dep of DISCORD_RUNTIME_DEPS) {
+ for (const dep of deps) {
copyDependencyTree(dep, destModules, undefined, seen);
}
}
@@ -324,6 +330,9 @@ function bundleNativeDeps(buildPath: string, targetPlatform: string, targetArch:
...NATIVE_RUNTIME_DEPS,
parcelWatcherPlatformPkg(targetPlatform, targetArch),
...sharpPlatformPkgs(targetPlatform, targetArch),
+ // Reviewer PDF utility 的 canvas wrapper 由 Vite externalize;正式包必须
+ // 同时带 wrapper 与目标平台的预编译 binding,不能依赖 workspace hoist。
+ ...reviewPdfRuntimePackages(targetPlatform, targetArch),
// loudness 只在 Windows 用 (录音时静音)。它的 Win 后端是个捆绑的 .exe,
// 必须运行时按 __dirname 找 — 所以走 NATIVE_RUNTIME_DEPS 这条路, 不让 vite
// bundle。Mac/Linux 完全不带, 避免拖入 execa 这条无用依赖链。
@@ -345,6 +354,7 @@ function bundleNativeDeps(buildPath: string, targetPlatform: string, targetArch:
console.log(`[forge:afterCopy] bundled native dep: ${dep} <- ${src}`);
}
copyDiscordRuntimeDeps(destModules);
+ copyRuntimeDependencyTrees(READ_SHEET_RUNTIME_PACKAGES, destModules);
}
// 针对 packaged buildPath 的 node_modules 强制重建 better-sqlite3 —— force:true 确保
@@ -1562,6 +1572,13 @@ const config: ForgeConfig = {
// 超时直接 kill,不阻塞 Electron main。
target: 'preload',
},
+ {
+ entry: 'src/main/doc-tools/docsOutputWriterUtilityProcess.ts',
+ config: 'vite.preload.config.ts',
+ // 最终文档落盘绑定到已验证父目录的 cwd capability,避免 main 侧
+ // realpath 与 write/rename 之间被 symlink 替换。
+ target: 'preload',
+ },
{
entry: 'src/main/watcher-host/watcherHostProcess.ts',
config: 'vite.watcher-host.config.ts',
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 3679a144ab..7fc337eea1 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -51,9 +51,33 @@
"license": "Apache-2.0",
"dependencies": {
"@babel/parser": "^7.29.7",
+ "@cindy/anthropic-compat-proxy": "workspace:*",
+ "@cindy/anthropic-responses-bridge": "workspace:*",
"@cindy/auth-client": "workspace:*",
+ "@cindy/browser-control-runtime": "workspace:*",
+ "@cindy/device-link": "workspace:*",
+ "@cindy/embedding-client": "workspace:*",
+ "@cindy/file-browser-core": "workspace:*",
+ "@cindy/github-client": "workspace:*",
+ "@cindy/heartbeat-client": "workspace:*",
+ "@cindy/im": "workspace:*",
+ "@cindy/ios-simulator-runtime": "workspace:*",
+ "@cindy/maker-cc-manager": "workspace:*",
+ "@cindy/maker-core": "workspace:*",
+ "@cindy/maker-pi-manager": "workspace:*",
+ "@cindy/maker-remote-ssh": "workspace:*",
+ "@cindy/maker-scheduler": "workspace:*",
+ "@cindy/maker-shared": "workspace:*",
+ "@cindy/mcps": "workspace:*",
+ "@cindy/model-providers": "workspace:*",
+ "@cindy/orca-workflow": "workspace:*",
"@cindy/plugin-protocol": "workspace:*",
+ "@cindy/remote-file-service": "workspace:*",
+ "@cindy/responses-anthropic-bridge": "workspace:*",
+ "@cindy/responses-chat-bridge": "workspace:*",
"@cindy/slack-hook-protocol": "workspace:*",
+ "@cindy/voice-input-core": "workspace:*",
+ "@cindy/wechat-ilink": "workspace:*",
"@codemirror/commands": "^6.10.3",
"@codemirror/lang-cpp": "^6.0.3",
"@codemirror/lang-css": "^6.3.1",
@@ -74,38 +98,18 @@
"@codemirror/search": "^6.7.0",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.41.1",
- "@cindy/orca-workflow": "workspace:*",
"@floating-ui/react-dom": "^2.1.9",
"@fontsource-variable/inter": "^5.2.8",
"@fontsource-variable/jetbrains-mono": "^5.2.8",
"@google/model-viewer": "^4.0.0",
"@lezer/highlight": "^1.2.3",
- "@cindy/anthropic-compat-proxy": "workspace:*",
- "@cindy/anthropic-responses-bridge": "workspace:*",
- "@cindy/responses-anthropic-bridge": "workspace:*",
- "@cindy/responses-chat-bridge": "workspace:*",
- "@cindy/browser-control-runtime": "workspace:*",
- "@cindy/device-link": "workspace:*",
- "@cindy/embedding-client": "workspace:*",
- "@cindy/file-browser-core": "workspace:*",
- "@cindy/github-client": "workspace:*",
- "@cindy/heartbeat-client": "workspace:*",
- "@cindy/ios-simulator-runtime": "workspace:*",
- "@cindy/maker-cc-manager": "workspace:*",
- "@cindy/maker-core": "workspace:*",
- "@cindy/maker-pi-manager": "workspace:*",
- "@cindy/maker-remote-ssh": "workspace:*",
- "@cindy/maker-scheduler": "workspace:*",
- "@cindy/maker-shared": "workspace:*",
- "@cindy/model-providers": "workspace:*",
- "@cindy/remote-file-service": "workspace:*",
- "@cindy/voice-input-core": "workspace:*",
"@modelcontextprotocol/sdk": "^1.29.0",
+ "@napi-rs/canvas": "^0.1.100",
"@paralleldrive/cuid2": "^2.3.1",
"@parcel/watcher": "^2.5.6",
"@radix-ui/react-alert-dialog": "^1.1.15",
- "@radix-ui/react-dismissable-layer": "^1.1.15",
"@radix-ui/react-dialog": "^1.1.15",
+ "@radix-ui/react-dismissable-layer": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-focus-guards": "^1.1.4",
"@radix-ui/react-focus-scope": "^1.1.12",
@@ -133,10 +137,12 @@
"cindy-tools": "workspace:*",
"clsx": "^2.1.1",
"diff": "^8.0.4",
+ "docx": "^9.7.1",
"drizzle-orm": "^0.45.2",
"electron-squirrel-startup": "^1.0.1",
"electron-store": "^7.0.3",
"electron-window-state": "^5.0.3",
+ "exceljs": "^4.4.0",
"fix-path": "^5.0.0",
"gray-matter": "^4.0.3",
"harmonyos-sans-sc-webfont-splitted": "1.1.0",
@@ -146,16 +152,15 @@
"js-yaml": "^4.1.0",
"jszip": "^3.10.1",
"katex": "^0.16.45",
- "@cindy/im": "workspace:*",
- "@cindy/wechat-ilink": "workspace:*",
- "@cindy/mcps": "workspace:*",
"loudness": "^0.4.2",
"lucide-react": "^0.468.0",
+ "marked": "^16.4.2",
"mermaid": "^11.14.0",
"node-machine-id": "^1.1.12",
"node-pty": "^1.0.0",
"pdfjs-dist": "^5.7.284",
"picomatch": "^4.0.5",
+ "pptxgenjs": "^4.0.1",
"qrcode": "^1.5.4",
"react": "^19.0.0",
"react-dom": "^19.0.0",
@@ -168,8 +173,8 @@
"remark-cjk-friendly": "^2.3.1",
"remark-gfm": "^4.0.1",
"remark-math": "^6.0.0",
- "sharp": "^0.35.0",
"semver": "^7.8.5",
+ "sharp": "^0.35.0",
"silk-wasm": "^3.7.1",
"smol-toml": "^1.6.1",
"sortablejs": "^1.15.6",
diff --git a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
index d9faaba378..5790301942 100644
--- a/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
+++ b/apps/desktop/src/main/__tests__/mainWindowBackgroundThrottling.test.ts
@@ -187,6 +187,14 @@ describe('窗口可见性广播(装饰动画闸门的兜底信号)', () => {
// 将来这两个视图若引入常驻动画,删掉本豁免即可。
'权限引导窗与 backdrop 视图无常驻装饰动画',
],
+ [
+ 'doc-tools/htmlPdfRenderer.ts',
+ // render_pdf 的离屏排版窗:从不 show()、没有 Cindy 自己的 Renderer、不加载
+ // index.html,装的是任务给的任意 HTML —— 闸门根本不在这条链上,广播无处可送。
+ // 关节流是因为它全程隐藏:Chromium 会把隐藏窗口的定时器/rAF 降频,页面在打印前
+ // 需要跑的布局与字体加载会被拖慢甚至卡到超时。窗口即用即毁,节流关闭不会常驻耗电。
+ '离屏 PDF 排版窗从不显示、不加载 Cindy Renderer,装饰动画闸门不适用',
+ ],
]);
it('关闭了 backgroundThrottling 的窗口要么装广播,要么显式登记豁免', () => {
diff --git a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts
new file mode 100644
index 0000000000..db0178c74e
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterPackaging.test.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const desktopRoot = path.resolve(__dirname, '../../../..');
+
+describe('docs output writer packaging', () => {
+ it('ships the cwd-bound utility entry and forks that packaged file', () => {
+ const forge = readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');
+ const controller = readFileSync(
+ path.join(desktopRoot, 'src/main/doc-tools/docsOutputWriter.ts'),
+ 'utf8',
+ );
+ expect(forge).toContain("entry: 'src/main/doc-tools/docsOutputWriterUtilityProcess.ts'");
+ expect(controller).toContain("path.join(__dirname, 'docsOutputWriterUtilityProcess.js')");
+ expect(controller).toContain('cwd: rootDir');
+ });
+});
diff --git a/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts
new file mode 100644
index 0000000000..7ff571dc3c
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/__tests__/docsOutputWriterUtilityProcess.test.ts
@@ -0,0 +1,313 @@
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ relativeOutputParentPath,
+ type DocsOutputWriteRequest,
+} from '../docsOutputWriterProtocol.js';
+import {
+ relativePathSegments,
+ runDocsOutputWriteForTest,
+ sameRelativePath,
+} from '../docsOutputWriterUtilityProcess.js';
+
+let root: string;
+const cleanup: string[] = [];
+const utilityModuleUrl = pathToFileURL(
+ path.resolve(process.cwd(), 'src/main/doc-tools/docsOutputWriterUtilityProcess.ts'),
+).href;
+const tsxLoader = createRequire(import.meta.url).resolve('tsx');
+
+beforeEach(async () => {
+ root = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-writer-'));
+ cleanup.push(root);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ while (cleanup.length > 0) {
+ await fs.promises.rm(cleanup.pop()!, { recursive: true, force: true });
+ }
+});
+
+async function request(
+ targetName: string,
+ data: string,
+ overwrite: boolean,
+ parent = root,
+): Promise<DocsOutputWriteRequest> {
+ const stat = await fs.promises.lstat(parent, { bigint: true });
+ const rootStat = await fs.promises.lstat(root, { bigint: true });
+ const rootRealPath = await fs.promises.realpath(root);
+ const parentRealPath = await fs.promises.realpath(parent);
+ return {
+ expectedRoot: {
+ realPath: rootRealPath,
+ dev: rootStat.dev,
+ ino: rootStat.ino,
+ },
+ expectedParent: {
+ realPath: parentRealPath,
+ dev: stat.dev,
+ ino: stat.ino,
+ },
+ parentRelativePath: path.relative(rootRealPath, parentRealPath),
+ targetName,
+ data: Buffer.from(data),
+ overwrite,
+ };
+}
+
+async function missingParentRequest(
+ targetName: string,
+ data: string,
+): Promise<DocsOutputWriteRequest> {
+ const rootStat = await fs.promises.lstat(root, { bigint: true });
+ const rootRealPath = await fs.promises.realpath(root);
+ return {
+ expectedRoot: { realPath: rootRealPath, dev: rootStat.dev, ino: rootStat.ino },
+ expectedParent: null,
+ parentRelativePath: 'nested/reports',
+ targetName,
+ data: Buffer.from(data),
+ overwrite: false,
+ };
+}
+
+describe('docs output cwd-bound writer', () => {
+ it('derives output parents from the lexical session root before realpath canonicalization', () => {
+ const lexicalRoot = path.join(root, 'session-root-alias');
+ expect(relativeOutputParentPath(lexicalRoot, path.join(lexicalRoot, 'documents'))).toBe(
+ 'documents',
+ );
+ expect(relativeOutputParentPath(lexicalRoot, path.join(root, 'outside'))).toBeNull();
+ });
+
+ it('uses Windows case-insensitive semantics for relative parent paths', () => {
+ expect(sameRelativePath('Documents/Reports', 'documents\\reports', 'win32')).toBe(true);
+ expect(sameRelativePath('Documents/Reports', 'documents\\reports', 'darwin')).toBe(false);
+ });
+
+ it('normalizes only the current platform separators when walking output parents', () => {
+ expect(relativePathSegments('nested/reports', 'win32')).toEqual(['nested', 'reports']);
+ expect(relativePathSegments('nested\\reports', 'win32')).toEqual(['nested', 'reports']);
+ expect(relativePathSegments('reports\\2026', 'darwin')).toEqual(['reports\\2026']);
+ });
+
+ it.runIf(process.platform !== 'win32')(
+ 'keeps backslashes as literal output-directory characters on POSIX',
+ async () => {
+ const rootStat = await fs.promises.lstat(root, { bigint: true });
+ const rootRealPath = await fs.promises.realpath(root);
+ const pending: DocsOutputWriteRequest = {
+ expectedRoot: { realPath: rootRealPath, dev: rootStat.dev, ino: rootStat.ino },
+ expectedParent: null,
+ parentRelativePath: 'reports\\2026',
+ targetName: 'report.bin',
+ data: Buffer.from('literal-backslash'),
+ overwrite: false,
+ };
+
+ await runDocsOutputWriteForTest(pending, root);
+ expect(
+ await fs.promises.readFile(path.join(root, 'reports\\2026', 'report.bin'), 'utf8'),
+ ).toBe('literal-backslash');
+ await expect(fs.promises.stat(path.join(root, 'reports'))).rejects.toThrow();
+ },
+ );
+
+ it('creates exclusively and never truncates an existing file by default', async () => {
+ const first = await request('report.bin', 'one', false);
+ await runDocsOutputWriteForTest(first, root);
+ await expect(
+ runDocsOutputWriteForTest(await request('report.bin', 'two', false), root),
+ ).rejects.toMatchObject({ code: 'FILE_EXISTS' });
+ expect(await fs.promises.readFile(path.join(root, 'report.bin'), 'utf8')).toBe('one');
+ expect((await fs.promises.readdir(root)).some((name) => name.includes('.cindy-docs-'))).toBe(
+ false,
+ );
+ });
+
+ it('does not expose a partial target when the first write fails', async () => {
+ const originalOpen = fs.promises.open.bind(fs.promises);
+ vi.spyOn(fs.promises, 'open').mockImplementationOnce(async (file, flags, mode) => {
+ const handle = await originalOpen(file, flags, mode);
+ vi.spyOn(handle, 'writeFile').mockImplementationOnce(async (data) => {
+ await handle.write(Buffer.from(data as Uint8Array).subarray(0, 3));
+ throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ });
+ return handle;
+ });
+
+ await expect(
+ runDocsOutputWriteForTest(await request('report.bin', 'partial-data', false), root),
+ ).rejects.toMatchObject({ code: 'ENOSPC' });
+ await expect(fs.promises.stat(path.join(root, 'report.bin'))).rejects.toThrow();
+ expect((await fs.promises.readdir(root)).some((name) => name.includes('.cindy-docs-'))).toBe(
+ false,
+ );
+ });
+
+ it.each(['ENOTSUP', 'EPERM'])(
+ 'fails closed without exposing a target when hard-link publication returns %s',
+ async (code) => {
+ vi.spyOn(fs.promises, 'link').mockRejectedValueOnce(
+ Object.assign(new Error('hard links unsupported'), { code }),
+ );
+
+ await expect(
+ runDocsOutputWriteForTest(await request('report.bin', 'not-published', false), root),
+ ).rejects.toMatchObject({ code: 'ATOMIC_PUBLISH_UNSUPPORTED' });
+ await expect(fs.promises.stat(path.join(root, 'report.bin'))).rejects.toThrow();
+ expect((await fs.promises.readdir(root)).some((name) => name.includes('.cindy-docs-'))).toBe(
+ false,
+ );
+ },
+ );
+
+ it('creates missing parents inside the anchored session root', async () => {
+ await runDocsOutputWriteForTest(await missingParentRequest('report.bin', 'nested'), root);
+ expect(await fs.promises.readFile(path.join(root, 'nested/reports/report.bin'), 'utf8')).toBe(
+ 'nested',
+ );
+ });
+
+ it('atomically replaces an existing regular file', async () => {
+ await fs.promises.writeFile(path.join(root, 'report.bin'), 'old');
+ await runDocsOutputWriteForTest(await request('report.bin', 'new', true), root);
+ expect(await fs.promises.readFile(path.join(root, 'report.bin'), 'utf8')).toBe('new');
+ expect((await fs.promises.readdir(root)).some((name) => name.includes('.cindy-docs-'))).toBe(
+ false,
+ );
+ });
+
+ it.each(['EEXIST', 'EPERM'])(
+ 'fails closed without moving the original target when atomic replace returns %s',
+ async (code) => {
+ await fs.promises.writeFile(path.join(root, 'report.bin'), 'old');
+ vi.spyOn(fs.promises, 'rename').mockRejectedValueOnce(
+ Object.assign(new Error('replace denied'), { code }),
+ );
+
+ await expect(
+ runDocsOutputWriteForTest(await request('report.bin', 'new', true), root),
+ ).rejects.toMatchObject({ code: 'ATOMIC_PUBLISH_UNSUPPORTED' });
+ expect(await fs.promises.readFile(path.join(root, 'report.bin'), 'utf8')).toBe('old');
+ expect((await fs.promises.readdir(root)).some((name) => name.includes('.cindy-docs-'))).toBe(
+ false,
+ );
+ },
+ );
+
+ it('rejects a parent path rebound to an outside symlink before the final operation', async () => {
+ const safe = path.join(root, 'safe');
+ const moved = path.join(root, 'safe-original');
+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));
+ cleanup.push(outside);
+ await fs.promises.mkdir(safe);
+ const pending = await request('report.bin', 'blocked', false, safe);
+ await fs.promises.rename(safe, moved);
+ await fs.promises.symlink(outside, safe, process.platform === 'win32' ? 'junction' : 'dir');
+
+ await expect(runDocsOutputWriteForTest(pending, root)).rejects.toMatchObject({
+ code: 'PATH_NOT_ALLOWED',
+ });
+ await expect(fs.promises.stat(path.join(outside, 'report.bin'))).rejects.toThrow();
+ });
+
+ it.runIf(process.platform !== 'win32')(
+ 'binds create and overwrite operations to the verified parent inode in the utility process',
+ async () => {
+ for (const overwrite of [false, true]) {
+ const safe = path.join(root, overwrite ? 'overwrite-safe' : 'create-safe');
+ const moved = `${safe}-original`;
+ const outside = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));
+ cleanup.push(outside);
+ await fs.promises.mkdir(safe);
+ if (overwrite) await fs.promises.writeFile(path.join(safe, 'report.bin'), 'old');
+
+ const probe = spawnSync(
+ process.execPath,
+ [
+ '--import',
+ tsxLoader,
+ '-e',
+ `
+const fs = (await import('node:fs')).default;
+const path = (await import('node:path')).default;
+const { runDocsOutputWrite } = await import(process.env.CINDY_WRITER_MODULE);
+const root = process.env.CINDY_WRITER_ROOT;
+const safe = process.env.CINDY_WRITER_SAFE;
+const moved = process.env.CINDY_WRITER_MOVED;
+const outside = process.env.CINDY_WRITER_OUTSIDE;
+const overwrite = process.env.CINDY_WRITER_OVERWRITE === 'true';
+const rootStat = await fs.promises.lstat(root, { bigint: true });
+const parentStat = await fs.promises.lstat(safe, { bigint: true });
+const request = {
+ expectedRoot: { realPath: await fs.promises.realpath(root), dev: rootStat.dev, ino: rootStat.ino },
+ expectedParent: { realPath: await fs.promises.realpath(safe), dev: parentStat.dev, ino: parentStat.ino },
+ parentRelativePath: path.relative(root, safe),
+ targetName: 'report.bin',
+ data: Buffer.from(overwrite ? 'new' : 'bound'),
+ overwrite,
+};
+const originalOpen = fs.promises.open.bind(fs.promises);
+fs.promises.open = async (...args) => {
+ fs.promises.open = originalOpen;
+ await fs.promises.rename(safe, moved);
+ await fs.promises.symlink(outside, safe, 'dir');
+ return originalOpen(...args);
+};
+process.chdir(root);
+let code = 'NO_ERROR';
+try { await runDocsOutputWrite(request); } catch (error) { code = error?.code || String(error); }
+const outsideExists = fs.existsSync(path.join(outside, 'report.bin'));
+const movedValue = fs.existsSync(path.join(moved, 'report.bin'))
+ ? await fs.promises.readFile(path.join(moved, 'report.bin'), 'utf8')
+ : null;
+process.stdout.write(JSON.stringify({ code, outsideExists, movedValue }));
+`,
+ ],
+ {
+ cwd: root,
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ CINDY_WRITER_MODULE: utilityModuleUrl,
+ CINDY_WRITER_ROOT: root,
+ CINDY_WRITER_SAFE: safe,
+ CINDY_WRITER_MOVED: moved,
+ CINDY_WRITER_OUTSIDE: outside,
+ CINDY_WRITER_OVERWRITE: String(overwrite),
+ },
+ },
+ );
+ expect(probe.status, probe.stderr || String(probe.error ?? '')).toBe(0);
+ expect(JSON.parse(probe.stdout)).toEqual({
+ code: 'PATH_NOT_ALLOWED',
+ outsideExists: false,
+ movedValue: overwrite ? 'old' : null,
+ });
+ }
+ },
+ );
+
+ it('anchors the final write at the session root when the parent inode moves away', async () => {
+ const safe = path.join(root, 'safe');
+ const moved = path.join(root, 'safe-original');
+ await fs.promises.mkdir(safe);
+ const pending = await request('report.bin', 'blocked', false, safe);
+ await fs.promises.rename(safe, moved);
+
+ await expect(runDocsOutputWriteForTest(pending, root)).rejects.toMatchObject({
+ code: 'PATH_NOT_ALLOWED',
+ });
+ await expect(fs.promises.stat(path.join(moved, 'report.bin'))).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts b/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts
new file mode 100644
index 0000000000..ddd68dcf65
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/__tests__/htmlPdfRenderer.test.ts
@@ -0,0 +1,519 @@
+/**
+ * htmlPdfRenderer 测试:用可控的 electron 桩驱动隐藏渲染窗。
+ *
+ * 覆盖 electron-security §3 / §3.1 里对这扇窗真正适用的那几条:
+ * - 安全字段全部显式写死、无 preload、不 show;
+ * - 导航与弹窗 fail closed;
+ * - 即用即毁(成功、失败、超时三条路径都销毁窗口);
+ * - 同刻并发 1、其余排队;
+ * - 30s 超时;
+ * - 加载失败 / 渲染进程崩溃只让这次渲染失败,不升级、不自动重建。
+ */
+
+import { EventEmitter } from 'node:events';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+interface FakeWindowOptions {
+ webPreferences?: Record<string, unknown>;
+ show?: boolean;
+ [k: string]: unknown;
+}
+
+class FakeSession extends EventEmitter {
+ permissionRequestHandler: ((...args: any[]) => void) | undefined;
+ permissionCheckHandler: ((...args: any[]) => boolean) | undefined;
+ beforeRequestHandler:
+ | ((
+ details: { url: string; resourceType?: string },
+ callback: (response: { cancel: boolean }) => void,
+ ) => void)
+ | undefined;
+ webRequest = {
+ onBeforeRequest: vi.fn(
+ (
+ handler: (
+ details: { url: string; resourceType?: string },
+ callback: (response: { cancel: boolean }) => void,
+ ) => void,
+ ) => {
+ this.beforeRequestHandler = handler;
+ },
+ ),
+ };
+
+ constructor() {
+ super();
+ }
+
+ setPermissionRequestHandler(handler: (...args: any[]) => void): void {
+ this.permissionRequestHandler = handler;
+ }
+
+ setPermissionCheckHandler(handler: (...args: any[]) => boolean): void {
+ this.permissionCheckHandler = handler;
+ }
+}
+
+class FakeWebContents extends EventEmitter {
+ windowOpenHandler: ((details: unknown) => unknown) | undefined;
+ readonly session = new FakeSession();
+
+ printToPDF = vi.fn(async (_opts: unknown) => {
+ FakeBrowserWindow.calls.push('printToPDF');
+ return FakeBrowserWindow.pdfResult();
+ });
+
+ executeJavaScript = vi.fn(async (script: string) => {
+ FakeBrowserWindow.calls.push(`executeJavaScript:${script}`);
+ return FakeBrowserWindow.fontsBehavior();
+ });
+
+ setWindowOpenHandler(handler: (details: unknown) => unknown): void {
+ this.windowOpenHandler = handler;
+ }
+}
+
+class FakeBrowserWindow extends EventEmitter {
+ static instances: FakeBrowserWindow[] = [];
+ /** 调用顺序流水,用来断言「加载 → 等字体 → 打印」这条硬顺序。 */
+ static calls: string[] = [];
+ static pdfResult: () => Promise<Buffer> | Buffer = () => Buffer.from('%PDF-ok');
+ static fontsBehavior: () => Promise<unknown> | unknown = () => true;
+ static loadBehavior: (win: FakeBrowserWindow, file: string) => Promise<void> = async () => {};
+
+ readonly webContents = new FakeWebContents();
+ readonly options: FakeWindowOptions;
+ destroyed = false;
+ shown = false;
+ loadedFile: string | undefined;
+
+ constructor(options: FakeWindowOptions) {
+ super();
+ this.options = options;
+ FakeBrowserWindow.instances.push(this);
+ }
+
+ async loadFile(file: string): Promise<void> {
+ this.loadedFile = file;
+ FakeBrowserWindow.calls.push('loadFile');
+ await FakeBrowserWindow.loadBehavior(this, file);
+ }
+
+ show(): void {
+ this.shown = true;
+ }
+
+ destroy(): void {
+ this.destroyed = true;
+ }
+
+ isDestroyed(): boolean {
+ return this.destroyed;
+ }
+}
+
+let tempRoot: string;
+
+vi.mock('electron', () => ({
+ BrowserWindow: FakeBrowserWindow,
+ app: { getPath: () => tempRoot },
+ nativeTheme: { shouldUseDarkColors: false },
+}));
+
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+const { renderHtmlToPdf, __getActiveRenderCount } = await import('../htmlPdfRenderer.js');
+
+const BASE_INPUT = {
+ pageSize: 'A4' as const,
+ landscape: false,
+ printBackground: true,
+ margins: { top: 0.4, bottom: 0.4, left: 0.4, right: 0.4 },
+ timeoutMs: 30_000,
+ fontTimeoutMs: 5_000,
+};
+
+beforeEach(async () => {
+ tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-renderer-'));
+ FakeBrowserWindow.instances = [];
+ FakeBrowserWindow.calls = [];
+ FakeBrowserWindow.pdfResult = () => Buffer.from('%PDF-ok');
+ FakeBrowserWindow.fontsBehavior = () => true;
+ FakeBrowserWindow.loadBehavior = async () => {};
+});
+
+afterEach(async () => {
+ await fs.rm(tempRoot, { recursive: true, force: true }).catch(() => undefined);
+});
+
+describe('渲染窗的安全配置', () => {
+ it('§3 的安全字段全部显式写死,且没有 preload、不 show', async () => {
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ const win = FakeBrowserWindow.instances[0]!;
+ const prefs = win.options.webPreferences!;
+
+ expect(win.options.show).toBe(false);
+ expect(prefs).toMatchObject({
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ webviewTag: false,
+ });
+ expect(prefs.preload).toBeUndefined();
+ expect(prefs.enableBlinkFeatures).toBeUndefined();
+ expect(prefs.partition).toMatch(/^temp:cindy-docs-/);
+ expect(win.webContents.session.webRequest.onBeforeRequest).toHaveBeenCalledTimes(1);
+ expect(win.webContents.session.permissionRequestHandler).toBeDefined();
+ expect(win.webContents.session.permissionCheckHandler).toBeDefined();
+ const permissionCallback = vi.fn();
+ win.webContents.session.permissionRequestHandler!({}, 'geolocation', permissionCallback);
+ expect(permissionCallback).toHaveBeenCalledWith(false);
+ expect(win.webContents.session.permissionCheckHandler!()).toBe(false);
+ const downloadEvent = { preventDefault: vi.fn() };
+ win.webContents.session.emit('will-download', downloadEvent, {});
+ expect(downloadEvent.preventDefault).toHaveBeenCalledTimes(1);
+ expect(win.shown).toBe(false);
+ });
+
+ it('本地资源路径含 symlink 时 fail closed,不把 file URL 交给 Chromium', async () => {
+ const sourceDir = path.join(tempRoot, 'source');
+ const outsideDir = path.join(tempRoot, 'outside');
+ await Promise.all([fs.mkdir(sourceDir), fs.mkdir(outsideDir)]);
+ await fs.writeFile(path.join(sourceDir, 'src.html'), '<p>x</p>');
+ await fs.writeFile(path.join(outsideDir, 'secret.png'), 'secret');
+ const link = path.join(sourceDir, 'secret.png');
+ await fs.symlink(
+ path.join(outsideDir, 'secret.png'),
+ link,
+ process.platform === 'win32' ? 'file' : undefined,
+ );
+ await renderHtmlToPdf({
+ ...BASE_INPUT,
+ htmlBytes: await fs.readFile(path.join(sourceDir, 'src.html')),
+ }).catch(() => undefined);
+ const handler = FakeBrowserWindow.instances[0]!.webContents.session.beforeRequestHandler!;
+ const response = await new Promise<{ cancel: boolean }>((resolve) =>
+ handler({ url: pathToFileURL(link).href }, resolve),
+ );
+ expect(response.cancel).toBe(true);
+ });
+
+ it('请求级 URL 策略只放行内联 URL,阻断本地 file URL 与网络', async () => {
+ const localAsset = path.join(tempRoot, 'asset.txt');
+ await fs.writeFile(localAsset, 'asset', 'utf8');
+ await fs.writeFile(path.join(tempRoot, 'src.html'), '<p>x</p>');
+ await renderHtmlToPdf({
+ ...BASE_INPUT,
+ htmlBytes: await fs.readFile(path.join(tempRoot, 'src.html')),
+ }).catch(() => undefined);
+ const win = FakeBrowserWindow.instances[0]!;
+ const handler = win.webContents.session.beforeRequestHandler!;
+ const decide = async (url: string): Promise<boolean> => {
+ const response = await new Promise<{ cancel: boolean }>((resolve) =>
+ handler({ url }, resolve),
+ );
+ return !response.cancel;
+ };
+ expect(await decide(`file://${localAsset}`)).toBe(false);
+ expect(await decide('data:text/plain,ok')).toBe(true);
+ expect(await decide('https://example.com/font.woff2')).toBe(false);
+ expect(await decide('http://127.0.0.1:8080/secret')).toBe(false);
+ expect(await decide('file:///etc/passwd')).toBe(false);
+ });
+
+ it('只放行已准备好的主文档入口,不放行其它 file 子资源', async () => {
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ const win = FakeBrowserWindow.instances[0]!;
+ const handler = win.webContents.session.beforeRequestHandler!;
+ const entry = pathToFileURL(win.loadedFile!).href;
+ const mainFrame = await new Promise<{ cancel: boolean }>((resolve) =>
+ handler({ url: entry, resourceType: 'mainFrame' }, resolve),
+ );
+ const subresource = await new Promise<{ cancel: boolean }>((resolve) =>
+ handler({ url: entry, resourceType: 'image' }, resolve),
+ );
+ expect(mainFrame.cancel).toBe(false);
+ expect(subresource.cancel).toBe(true);
+ });
+
+ it('弹窗与 Renderer 发起的导航一律 deny', async () => {
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ const win = FakeBrowserWindow.instances[0]!;
+ expect(win.webContents.windowOpenHandler!({ url: 'https://evil.example' })).toEqual({
+ action: 'deny',
+ });
+
+ // will-navigate 只对 Renderer 发起的导航触发,首帧 loadFile 不经过它,
+ // 所以这里全拒 —— 包括页面想重新加载自己。
+ for (const url of ['https://evil.example', `file://${win.loadedFile}`, 'about:blank']) {
+ const event = { preventDefault: vi.fn() };
+ win.webContents.emit('will-navigate', event, url);
+ expect(event.preventDefault, `${url} should be blocked`).toHaveBeenCalled();
+ }
+ });
+});
+
+describe('渲染主流程', () => {
+ it('内联 HTML 落到临时文件被加载,渲染完临时目录被清理', async () => {
+ let loadedContent = '';
+ FakeBrowserWindow.loadBehavior = async (_win, file) => {
+ loadedContent = await fs.readFile(file, 'utf-8');
+ };
+ const { buffer } = await renderHtmlToPdf({ ...BASE_INPUT, html: '<h1>hello</h1>' });
+ expect(buffer.toString()).toBe('%PDF-ok');
+ expect(loadedContent).toBe('<h1>hello</h1>');
+
+ const tempFile = FakeBrowserWindow.instances[0]!.loadedFile!;
+ await expect(fs.stat(path.dirname(tempFile))).rejects.toThrow();
+ });
+
+ it('只加载传入的 HTML 快照,不按调用方路径重新打开源文件', async () => {
+ const source = path.join(tempRoot, 'src.html');
+ await fs.writeFile(source, '<p>x</p>', 'utf-8');
+ await renderHtmlToPdf({ ...BASE_INPUT, htmlBytes: await fs.readFile(source) });
+ expect(FakeBrowserWindow.instances[0]!.loadedFile).not.toBe(source);
+ await expect(fs.stat(source)).resolves.toBeTruthy();
+ });
+
+ it('主文档快照完成后源路径被换成外部链接也不会改变待打印内容', async () => {
+ const source = path.join(tempRoot, 'src.html');
+ const outside = path.join(tempRoot, 'outside.html');
+ const moved = path.join(tempRoot, 'src-original.html');
+ await fs.writeFile(source, '<p>safe</p>', 'utf-8');
+ await fs.writeFile(outside, '<p>outside</p>', 'utf-8');
+ const snapshot = await fs.readFile(source);
+ await fs.rename(source, moved);
+ await fs.symlink(outside, source, process.platform === 'win32' ? 'file' : undefined);
+ let loadedContent = '';
+ FakeBrowserWindow.loadBehavior = async (_win, file) => {
+ loadedContent = await fs.readFile(file, 'utf-8');
+ };
+
+ await renderHtmlToPdf({ ...BASE_INPUT, htmlBytes: snapshot });
+
+ expect(loadedContent).toBe('<p>safe</p>');
+ });
+
+ it('排版参数原样交给 printToPDF(margins 用 custom)', async () => {
+ await renderHtmlToPdf({
+ ...BASE_INPUT,
+ html: '<p/>',
+ pageSize: 'Letter',
+ landscape: true,
+ printBackground: false,
+ margins: { top: 1, bottom: 0.2, left: 0.3, right: 0.4 },
+ });
+ expect(FakeBrowserWindow.instances[0]!.webContents.printToPDF).toHaveBeenCalledWith({
+ pageSize: 'Letter',
+ landscape: true,
+ printBackground: false,
+ margins: { marginType: 'custom', top: 1, bottom: 0.2, left: 0.3, right: 0.4 },
+ });
+ });
+
+ it('成功后窗口即刻销毁(不隐藏复用)', async () => {
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>' });
+ expect(FakeBrowserWindow.instances[0]!.destroyed).toBe(true);
+ });
+
+ it('每次渲染都是全新窗口,不跨任务复用 webContents', async () => {
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>1</p>' });
+ await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>2</p>' });
+ expect(FakeBrowserWindow.instances).toHaveLength(2);
+ expect(FakeBrowserWindow.instances[0]).not.toBe(FakeBrowserWindow.instances[1]);
+ });
+});
+
+// Chromium 不会自己等 @font-face —— 字体没加载完就打印会被静默换成系统字体,
+// 而且不报任何错。这组用例把「加载 → 等字体 → 打印」的顺序和超时降级钉死。
+describe('字体就绪等待', () => {
+ it('顺序硬约束:加载完成 → 等 document.fonts.ready → 才打印', async () => {
+ const { fontsReady } = await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ expect(fontsReady).toBe(true);
+ expect(FakeBrowserWindow.calls).toEqual([
+ 'loadFile',
+ 'executeJavaScript:document.fonts.ready.then(() => true)',
+ 'printToPDF',
+ ]);
+ });
+
+ it('等字体超时时照常出片,但把 fontsReady=false 带回去', async () => {
+ FakeBrowserWindow.fontsBehavior = () =>
+ new Promise(() => {
+ /* 永不 resolve:字体一直加载不完 */
+ });
+ const started = Date.now();
+ const { buffer, fontsReady } = await renderHtmlToPdf({
+ ...BASE_INPUT,
+ html: '<p>x</p>',
+ fontTimeoutMs: 60,
+ });
+ // 关键:字体等不到不能拖满总超时,也不能让整次渲染失败。
+ expect(Date.now() - started).toBeLessThan(5_000);
+ expect(buffer.toString()).toBe('%PDF-ok');
+ expect(fontsReady).toBe(false);
+ expect(FakeBrowserWindow.calls).toContain('printToPDF');
+ });
+
+ it('页面没有 document.fonts(求值抛错)时降级为 fontsReady=false,不影响出片', async () => {
+ FakeBrowserWindow.fontsBehavior = () =>
+ Promise.reject(new Error('document.fonts is undefined'));
+ const { buffer, fontsReady } = await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ expect(buffer.toString()).toBe('%PDF-ok');
+ expect(fontsReady).toBe(false);
+ });
+
+ it('字体探测返回非 true 也按未就绪处理(不猜)', async () => {
+ FakeBrowserWindow.fontsBehavior = () => undefined;
+ const { fontsReady } = await renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' });
+ expect(fontsReady).toBe(false);
+ });
+
+ it('等字体期间页面崩溃仍然判这次渲染失败,不会打印出半成品', async () => {
+ FakeBrowserWindow.fontsBehavior = () => new Promise(() => {});
+ FakeBrowserWindow.loadBehavior = async (win) => {
+ setTimeout(() => {
+ win.webContents.emit('render-process-gone', {}, { reason: 'crashed' });
+ }, 10);
+ };
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p>x</p>' })).rejects.toThrow(
+ /渲染进程异常退出/,
+ );
+ expect(FakeBrowserWindow.calls).not.toContain('printToPDF');
+ expect(FakeBrowserWindow.instances[0]!.destroyed).toBe(true);
+ });
+});
+
+describe('故障隔离', () => {
+ it('加载失败让这次渲染失败,窗口销毁,且不去调 printToPDF', async () => {
+ FakeBrowserWindow.loadBehavior = async (win) => {
+ win.webContents.emit('did-fail-load', {}, -6, 'ERR_FILE_NOT_FOUND', 'file:///missing', true);
+ await new Promise(() => {
+ /* 永不 resolve —— 真实 loadFile 在失败时也不会正常完成 */
+ });
+ };
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>' })).rejects.toThrow(/HTML 加载失败/);
+ const win = FakeBrowserWindow.instances[0]!;
+ expect(win.destroyed).toBe(true);
+ expect(win.webContents.printToPDF).not.toHaveBeenCalled();
+ });
+
+ it('子 frame 加载失败不阻断已成功的顶层文档', async () => {
+ FakeBrowserWindow.loadBehavior = async (win) => {
+ win.webContents.emit(
+ 'did-fail-load',
+ {},
+ -3,
+ 'ERR_ABORTED',
+ 'https://blocked.example/frame',
+ false,
+ );
+ };
+ const { buffer } = await renderHtmlToPdf({
+ ...BASE_INPUT,
+ html: '<iframe src="https://blocked.example/frame"></iframe><p>ok</p>',
+ });
+ expect(buffer.toString()).toBe('%PDF-ok');
+ expect(FakeBrowserWindow.instances[0]!.webContents.printToPDF).toHaveBeenCalledTimes(1);
+ });
+
+ it('渲染进程崩溃被翻成失败,不升级成别的东西', async () => {
+ FakeBrowserWindow.loadBehavior = async (win) => {
+ win.webContents.emit('render-process-gone', {}, { reason: 'crashed' });
+ await new Promise(() => {});
+ };
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>' })).rejects.toThrow(
+ /渲染进程异常退出\(crashed\)/,
+ );
+ expect(FakeBrowserWindow.instances[0]!.destroyed).toBe(true);
+ });
+
+ it('printToPDF 抛错时窗口照样销毁,不泄漏', async () => {
+ FakeBrowserWindow.pdfResult = () => Promise.reject(new Error('printToPDF boom'));
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>' })).rejects.toThrow(
+ 'printToPDF boom',
+ );
+ expect(FakeBrowserWindow.instances[0]!.destroyed).toBe(true);
+ });
+
+ it('失败不自动重试:一次调用只建一扇窗', async () => {
+ FakeBrowserWindow.pdfResult = () => Promise.reject(new Error('boom'));
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>' })).rejects.toThrow();
+ expect(FakeBrowserWindow.instances).toHaveLength(1);
+ });
+
+ it('前一次失败不影响排在后面的那次', async () => {
+ // 按调用顺序取行为:两次渲染是排队串行的,不能靠"改一次全局变量"来区分。
+ const behaviors: Array<() => Promise<Buffer>> = [
+ () => Promise.reject(new Error('boom')),
+ () => Promise.resolve(Buffer.from('%PDF-second')),
+ ];
+ FakeBrowserWindow.pdfResult = () => behaviors.shift()!();
+
+ const failing = renderHtmlToPdf({ ...BASE_INPUT, html: '<p>1</p>' });
+ const following = renderHtmlToPdf({ ...BASE_INPUT, html: '<p>2</p>' });
+
+ await expect(failing).rejects.toThrow('boom');
+ expect((await following).buffer.toString()).toBe('%PDF-second');
+ });
+});
+
+describe('超时与并发', () => {
+ it('超过 timeoutMs 直接判超时并销毁窗口', async () => {
+ // 用真实计时器 + 很短的超时:假计时器会让「渲染排队链」这条真实异步链
+ // 卡在半路,测出来的就不是生产行为了。
+ FakeBrowserWindow.loadBehavior = async () => {
+ await new Promise(() => {
+ /* 卡住不返回,模拟加载不出来的外部资源 */
+ });
+ };
+ await expect(renderHtmlToPdf({ ...BASE_INPUT, html: '<p/>', timeoutMs: 50 })).rejects.toThrow(
+ /渲染超时\(50ms timeout\)/,
+ );
+ expect(FakeBrowserWindow.instances[0]!.destroyed).toBe(true);
+ });
+
+ it('同刻只跑一个渲染,其余排队', async () => {
+ const gates: Array<() => void> = [];
+ FakeBrowserWindow.loadBehavior = async () =>
+ new Promise<void>((resolve) => {
+ gates.push(resolve);
+ });
+
+ const first = renderHtmlToPdf({ ...BASE_INPUT, html: '<p>1</p>' });
+ const second = renderHtmlToPdf({ ...BASE_INPUT, html: '<p>2</p>' });
+
+ // 让第一个走到 loadFile
+ await vi.waitFor(() => expect(gates).toHaveLength(1));
+ expect(FakeBrowserWindow.instances).toHaveLength(1);
+ expect(__getActiveRenderCount()).toBe(1);
+
+ gates[0]!();
+ await first;
+ await vi.waitFor(() => expect(gates).toHaveLength(2));
+ expect(FakeBrowserWindow.instances).toHaveLength(2);
+ gates[1]!();
+ await second;
+ expect(__getActiveRenderCount()).toBe(0);
+ });
+});
diff --git a/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts b/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts
new file mode 100644
index 0000000000..bbc665a277
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/__tests__/readSheetProcessPackaging.test.ts
@@ -0,0 +1,98 @@
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { READ_SHEET_RUNTIME_PACKAGES } from '../../../../../../packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps';
+
+const desktopRoot = path.resolve(process.cwd());
+const workspaceRequire = createRequire(import.meta.url);
+
+function packageDirectory(name: string, fromDirs?: string[]): string {
+ const options = fromDirs ? { paths: fromDirs } : { paths: [desktopRoot] };
+ try {
+ return path.dirname(workspaceRequire.resolve(`${name}/package.json`, options));
+ } catch {
+ let current = path.dirname(workspaceRequire.resolve(name, options));
+ while (current !== path.dirname(current)) {
+ const packageJson = path.join(current, 'package.json');
+ if (fs.existsSync(packageJson)) {
+ const manifest = JSON.parse(fs.readFileSync(packageJson, 'utf8')) as { name?: string };
+ if (manifest.name === name) return current;
+ }
+ current = path.dirname(current);
+ }
+ throw new Error(`cannot resolve package directory: ${name}`);
+ }
+}
+
+function stageDependencyTree(
+ name: string,
+ destinationModules: string,
+ fromDirs?: string[],
+ seen = new Set<string>(),
+): void {
+ const source = packageDirectory(name, fromDirs);
+ const destination = path.join(destinationModules, name);
+ const key = `${destination}\0${source}`;
+ if (seen.has(key)) return;
+ seen.add(key);
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.cpSync(source, destination, {
+ recursive: true,
+ dereference: true,
+ filter: (sourcePath) => path.basename(sourcePath) !== 'node_modules',
+ });
+ const manifest = JSON.parse(fs.readFileSync(path.join(source, 'package.json'), 'utf8')) as {
+ dependencies?: Record<string, string>;
+ };
+ for (const dependency of Object.keys(manifest.dependencies ?? {}).sort()) {
+ stageDependencyTree(dependency, path.join(destination, 'node_modules'), [source], seen);
+ }
+}
+
+describe('read_sheet XLSX worker packaging contract', () => {
+ it('copies the worker runtime dependency closures into packaged node_modules', () => {
+ const forge = fs.readFileSync(path.join(desktopRoot, 'forge.config.ts'), 'utf8');
+ expect(READ_SHEET_RUNTIME_PACKAGES).toEqual(['jszip', 'exceljs']);
+ expect(forge).toContain('copyRuntimeDependencyTrees(READ_SHEET_RUNTIME_PACKAGES, destModules)');
+ expect(forge).toContain('copyDependencyTree(childDep, childDestModules, [src], seen)');
+ });
+
+ it('loads ExcelJS and JSZip from an isolated staged dependency tree', () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-read-sheet-package-'));
+ try {
+ const stagedModules = path.join(temp, 'node_modules');
+ const seen = new Set<string>();
+ for (const runtimePackage of READ_SHEET_RUNTIME_PACKAGES) {
+ stageDependencyTree(runtimePackage, stagedModules, undefined, seen);
+ }
+ const probeRequirePath = path.join(temp, 'probe.cjs');
+ const probe = spawnSync(
+ process.execPath,
+ [
+ '-e',
+ `const { createRequire } = require('node:module');
+const stagedRequire = createRequire(${JSON.stringify(probeRequirePath)});
+const ExcelJS = stagedRequire('exceljs');
+const JSZip = stagedRequire('jszip');
+(async () => {
+ const workbook = new ExcelJS.Workbook();
+ workbook.addWorksheet('Sheet1').addRow(['ok']);
+ const bytes = await workbook.xlsx.writeBuffer();
+ const zip = await JSZip.loadAsync(bytes);
+ process.stdout.write(zip.file('xl/workbook.xml') ? 'ok' : 'missing');
+})().catch((error) => { console.error(error); process.exitCode = 1; });`,
+ ],
+ { cwd: temp, encoding: 'utf8' },
+ );
+ expect(probe.status, probe.stderr || String(probe.error ?? '')).toBe(0);
+ expect(probe.stdout).toBe('ok');
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/apps/desktop/src/main/doc-tools/docsOutputWriter.ts b/apps/desktop/src/main/doc-tools/docsOutputWriter.ts
new file mode 100644
index 0000000000..beff2fc610
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/docsOutputWriter.ts
@@ -0,0 +1,209 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+// eslint-disable-next-line no-restricted-imports -- final writes need a one-shot cwd-bound process, not a database worker.
+import { utilityProcess } from 'electron';
+
+import { DocsPathError, type WriteDocsOutputFn } from '@cindy/mcps';
+
+import {
+ relativeOutputParentPath,
+ type DocsOutputWriteRequest,
+ type DocsOutputWriteResult,
+} from './docsOutputWriterProtocol.js';
+
+interface DocsOutputWriterChildLike {
+ postMessage(message: unknown): void;
+ on(event: 'message', listener: (message: unknown) => void): void;
+ on(event: 'exit', listener: (code: number) => void): void;
+ on(event: 'error', listener: (error: unknown) => void): void;
+ kill(): boolean;
+ stderr?: NodeJS.ReadableStream | null;
+}
+
+function isInside(parent: string, candidate: string): boolean {
+ if (parent === candidate) return true;
+ const relative = path.relative(parent, candidate);
+ return relative.length > 0 && !relative.startsWith('..') && !path.isAbsolute(relative);
+}
+
+function forkDocsOutputWriter(rootDir: string): DocsOutputWriterChildLike {
+ const env: NodeJS.ProcessEnv = {};
+ for (const key of [
+ 'PATH',
+ 'SystemRoot',
+ 'WINDIR',
+ 'TEMP',
+ 'TMP',
+ 'TMPDIR',
+ 'LANG',
+ 'LC_ALL',
+ ] as const) {
+ if (process.env[key] !== undefined) env[key] = process.env[key];
+ }
+ return utilityProcess.fork(path.join(__dirname, 'docsOutputWriterUtilityProcess.js'), [], {
+ cwd: rootDir,
+ env,
+ stdio: ['ignore', 'ignore', 'pipe'],
+ serviceName: 'cindy-docs-output-writer',
+ });
+}
+
+function parseResult(value: unknown): DocsOutputWriteResult | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const result = value as Partial<DocsOutputWriteResult>;
+ if (result.ok === true) return { ok: true };
+ if (
+ result.ok === false &&
+ (result.errorCode === 'FILE_EXISTS' ||
+ result.errorCode === 'PATH_NOT_ALLOWED' ||
+ result.errorCode === 'ATOMIC_PUBLISH_UNSUPPORTED' ||
+ result.errorCode === 'INTERNAL') &&
+ typeof result.message === 'string'
+ ) {
+ return result as DocsOutputWriteResult;
+ }
+ return null;
+}
+
+function throwResultError(
+ result: Exclude<DocsOutputWriteResult, { ok: true }>,
+ abs: string,
+): never {
+ if (result.errorCode === 'FILE_EXISTS') {
+ throw new DocsPathError(
+ 'FILE_EXISTS',
+ result.message,
+ '同名文件已存在。确认要覆盖就再调一次并传 overwrite: true,否则换一个文件名。',
+ );
+ }
+ if (result.errorCode === 'PATH_NOT_ALLOWED') {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ result.message,
+ `输出路径 "${abs}" 在最终落盘时不再属于本任务工作目录,已停止写入。请检查目录后重试。`,
+ );
+ }
+ if (result.errorCode === 'ATOMIC_PUBLISH_UNSUPPORTED') {
+ throw new DocsPathError(
+ 'ATOMIC_PUBLISH_UNSUPPORTED',
+ result.message,
+ '请换到支持硬链接的本地工作目录;如确认允许覆盖同名文件,可显式传 overwrite:true 后重试。',
+ );
+ }
+ throw new Error(result.message);
+}
+
+export const writeDocsOutput: WriteDocsOutputFn = async (input) => {
+ const parentDir = path.dirname(input.path);
+ const realRoot = await fs.realpath(input.root);
+ const lexicalParent = path.resolve(parentDir);
+ const parentRelativePath = relativeOutputParentPath(input.root, lexicalParent);
+ if (parentRelativePath === null) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输出目录不在任务工作目录内: ${lexicalParent}`,
+ '请改用任务工作目录内的输出路径。',
+ );
+ }
+ const rootStat = await fs.lstat(realRoot, { bigint: true });
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `任务工作目录不是可用的真实目录: ${realRoot}`,
+ '请改用任务工作目录内的输出路径。',
+ );
+ }
+ let expectedParent: DocsOutputWriteRequest['expectedParent'] = null;
+ try {
+ const realParent = await fs.realpath(parentDir);
+ if (!isInside(realRoot, realParent)) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输出目录不在任务工作目录内: ${realParent}`,
+ '请改用任务工作目录内的输出路径。',
+ );
+ }
+ const parentStat = await fs.lstat(realParent, { bigint: true });
+ if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输出目录不是可用的真实目录: ${realParent}`,
+ '请改用任务工作目录内的普通目录。',
+ );
+ }
+ expectedParent = { realPath: realParent, dev: parentStat.dev, ino: parentStat.ino };
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') throw error;
+ // Missing parents are created by the root-anchored utility process.
+ }
+
+ const request: DocsOutputWriteRequest = {
+ expectedRoot: {
+ realPath: realRoot,
+ dev: rootStat.dev,
+ ino: rootStat.ino,
+ },
+ expectedParent,
+ parentRelativePath,
+ targetName: path.basename(input.path),
+ data: new Uint8Array(input.data),
+ overwrite: input.overwrite,
+ };
+ // Anchor the utility process at the session root, not at the output parent.
+ // If a parent directory is moved out of the session after validation, the
+ // same relative path from this cwd no longer resolves to that outside inode.
+ const child = forkDocsOutputWriter(realRoot);
+
+ await new Promise<void>((resolve, reject) => {
+ let settled = false;
+ let ready = false;
+ let stderr = '';
+ child.stderr?.on('data', (chunk: Buffer | string) => {
+ if (stderr.length < 8_000) stderr += String(chunk).slice(0, 8_000 - stderr.length);
+ });
+ const finish = (error?: unknown): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ try {
+ child.kill();
+ } catch {
+ // One-shot process may already have exited after sending its result.
+ }
+ if (error) reject(error);
+ else resolve();
+ };
+ const timer = setTimeout(() => finish(new Error('文档落盘隔离进程超时')), 60_000);
+ timer.unref?.();
+
+ child.on('message', (message) => {
+ if (
+ !ready &&
+ message &&
+ typeof message === 'object' &&
+ (message as { type?: unknown }).type === 'ready'
+ ) {
+ ready = true;
+ child.postMessage({ type: 'write', request });
+ return;
+ }
+ const result = parseResult(message);
+ if (!result) return;
+ if (result.ok) finish();
+ else {
+ try {
+ throwResultError(result, input.path);
+ } catch (error) {
+ finish(error);
+ }
+ }
+ });
+ child.on('error', (error) => finish(error));
+ child.on('exit', (code) => {
+ if (!settled) {
+ finish(new Error(stderr.trim() || `文档落盘隔离进程异常退出(${String(code)})`));
+ }
+ });
+ });
+};
diff --git a/apps/desktop/src/main/doc-tools/docsOutputWriterProtocol.ts b/apps/desktop/src/main/doc-tools/docsOutputWriterProtocol.ts
new file mode 100644
index 0000000000..3d7b29c82d
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/docsOutputWriterProtocol.ts
@@ -0,0 +1,47 @@
+import path from 'node:path';
+
+/**
+ * Keep the caller's lexical root and output path in the same namespace when
+ * deriving the relative parent. `realpath(root)` may change `/var` into
+ * `/private/var` or replace a session-root symlink, while the already checked
+ * output path deliberately retains the caller-visible spelling.
+ */
+export function relativeOutputParentPath(rootDir: string, parentDir: string): string | null {
+ const lexicalRoot = path.resolve(rootDir);
+ const lexicalParent = path.resolve(parentDir);
+ const relative = path.relative(lexicalRoot, lexicalParent);
+ if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
+ return null;
+ }
+ return relative;
+}
+
+export interface DocsOutputParentIdentity {
+ realPath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+export interface DocsOutputRootIdentity {
+ realPath: string;
+ dev: bigint;
+ ino: bigint;
+}
+
+export interface DocsOutputWriteRequest {
+ expectedRoot: DocsOutputRootIdentity;
+ /** Existing parent identity, or null when the utility must create it safely. */
+ expectedParent: DocsOutputParentIdentity | null;
+ parentRelativePath: string;
+ targetName: string;
+ data: Uint8Array;
+ overwrite: boolean;
+}
+
+export type DocsOutputWriteResult =
+ | { ok: true }
+ | {
+ ok: false;
+ errorCode: 'FILE_EXISTS' | 'PATH_NOT_ALLOWED' | 'ATOMIC_PUBLISH_UNSUPPORTED' | 'INTERNAL';
+ message: string;
+ };
diff --git a/apps/desktop/src/main/doc-tools/docsOutputWriterUtilityProcess.ts b/apps/desktop/src/main/doc-tools/docsOutputWriterUtilityProcess.ts
new file mode 100644
index 0000000000..c8e0f07b76
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/docsOutputWriterUtilityProcess.ts
@@ -0,0 +1,318 @@
+import { randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import type { DocsOutputWriteRequest, DocsOutputWriteResult } from './docsOutputWriterProtocol.js';
+
+interface ParentPortLike {
+ postMessage(message: unknown): void;
+ on(event: 'message', listener: (event: { data: unknown }) => void): void;
+}
+
+class OutputWriteError extends Error {
+ constructor(
+ readonly code: 'FILE_EXISTS' | 'PATH_NOT_ALLOWED' | 'ATOMIC_PUBLISH_UNSUPPORTED' | 'INTERNAL',
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;
+const hasCode = (error: unknown, code: string): boolean =>
+ Boolean(error && typeof error === 'object' && (error as NodeJS.ErrnoException).code === code);
+const HARD_LINK_UNSUPPORTED_CODES = new Set([
+ 'EACCES',
+ 'EMLINK',
+ 'ENOSYS',
+ 'ENOTSUP',
+ 'EOPNOTSUPP',
+ 'EPERM',
+ 'EXDEV',
+]);
+
+function samePath(left: string, right: string): boolean {
+ const normalize = (value: string) => {
+ const resolved = path.resolve(value);
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
+ };
+ return normalize(left) === normalize(right);
+}
+
+export function sameRelativePath(
+ left: string,
+ right: string,
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ const pathApi = platform === 'win32' ? path.win32 : path.posix;
+ const normalize = (value: string) => pathApi.normalize(value);
+ const normalizedLeft = normalize(left);
+ const normalizedRight = normalize(right);
+ return platform === 'win32'
+ ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
+ : normalizedLeft === normalizedRight;
+}
+
+export function relativePathSegments(
+ relative: string,
+ platform: NodeJS.Platform = process.platform,
+): string[] {
+ const pathApi = platform === 'win32' ? path.win32 : path.posix;
+ return pathApi.normalize(relative).split(pathApi.sep).filter(Boolean);
+}
+
+async function verifyParent(request: DocsOutputWriteRequest, workingDir: string): Promise<void> {
+ try {
+ const rootStat = await fs.promises.lstat(request.expectedRoot.realPath, { bigint: true });
+ if (
+ !rootStat.isDirectory() ||
+ rootStat.isSymbolicLink() ||
+ rootStat.dev !== request.expectedRoot.dev ||
+ rootStat.ino !== request.expectedRoot.ino
+ ) {
+ throw new OutputWriteError('PATH_NOT_ALLOWED', '任务工作目录身份在最终落盘前发生变化');
+ }
+ const stat = await fs.promises.lstat(workingDir, { bigint: true });
+ const realParent = await fs.promises.realpath(workingDir);
+ const relative = path.relative(request.expectedRoot.realPath, realParent);
+ if (
+ !stat.isDirectory() ||
+ stat.isSymbolicLink() ||
+ (request.expectedParent !== null &&
+ (stat.dev !== request.expectedParent.dev ||
+ stat.ino !== request.expectedParent.ino ||
+ !samePath(realParent, request.expectedParent.realPath))) ||
+ !sameRelativePath(relative, request.parentRelativePath) ||
+ relative.startsWith('..') ||
+ path.isAbsolute(relative)
+ ) {
+ throw new OutputWriteError(
+ 'PATH_NOT_ALLOWED',
+ '输出目录与任务工作目录的从属关系在最终落盘前发生变化',
+ );
+ }
+ } catch (error) {
+ if (error instanceof OutputWriteError) throw error;
+ throw new OutputWriteError('PATH_NOT_ALLOWED', '任务工作目录或输出目录在最终落盘前不可用');
+ }
+}
+
+/**
+ * Create an output parent one path component at a time while the utility
+ * process is anchored at the session root. The main process deliberately
+ * never calls recursive mkdir on a user-controlled path: all directory
+ * creation and identity checks happen in this root-bound process.
+ */
+async function ensureParent(request: DocsOutputWriteRequest, workingDir: string): Promise<void> {
+ const relative = request.parentRelativePath;
+ if (relative === '' || relative === '.') {
+ await verifyParent(request, workingDir);
+ return;
+ }
+ // Normalize separators with the current platform before walking each
+ // component. Windows accepts both slash forms, while POSIX keeps a
+ // backslash as a literal filename character.
+ const segments = relativePathSegments(relative);
+ if (segments.some((segment) => segment === '.' || segment === '..' || segment.includes('\0'))) {
+ throw new OutputWriteError('PATH_NOT_ALLOWED', '输出目录相对路径不合法');
+ }
+ let current = request.expectedRoot.realPath;
+ for (const segment of segments) {
+ current = path.join(current, segment);
+ try {
+ const stat = await fs.promises.lstat(current, { bigint: true });
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
+ throw new OutputWriteError('PATH_NOT_ALLOWED', '输出目录包含符号链接或非目录成员');
+ }
+ } catch (error) {
+ if (!hasCode(error, 'ENOENT')) throw error;
+ await fs.promises.mkdir(current);
+ const created = await fs.promises.lstat(current, { bigint: true });
+ if (!created.isDirectory() || created.isSymbolicLink()) {
+ throw new OutputWriteError('PATH_NOT_ALLOWED', '输出目录创建后不是普通目录');
+ }
+ }
+ }
+ await verifyParent(request, workingDir);
+}
+
+async function writeExclusive(target: string, data: Uint8Array): Promise<void> {
+ const flags =
+ fs.constants.O_WRONLY |
+ fs.constants.O_CREAT |
+ fs.constants.O_EXCL |
+ (fs.constants.O_NOFOLLOW ?? 0);
+ let handle: fs.promises.FileHandle | undefined;
+ try {
+ handle = await fs.promises.open(target, flags, 0o600);
+ await handle.writeFile(data);
+ await handle.sync();
+ } catch (error) {
+ if (hasCode(error, 'EEXIST')) {
+ throw new OutputWriteError('FILE_EXISTS', `目标文件已存在: ${target}`);
+ }
+ throw error;
+ } finally {
+ await handle?.close().catch(() => undefined);
+ }
+}
+
+async function publishExclusive(staging: string, target: string): Promise<void> {
+ try {
+ // A same-directory hard link publishes the fully synced staging inode in
+ // one step and never replaces an existing destination. If the utility is
+ // terminated while writing, only the hidden staging name can be partial.
+ await fs.promises.link(staging, target);
+ } catch (error) {
+ if (hasCode(error, 'EEXIST')) {
+ throw new OutputWriteError('FILE_EXISTS', `目标文件已存在: ${target}`);
+ }
+ const code = (error as NodeJS.ErrnoException)?.code;
+ if (code && HARD_LINK_UNSUPPORTED_CODES.has(code)) {
+ throw new OutputWriteError(
+ 'ATOMIC_PUBLISH_UNSUPPORTED',
+ '当前输出位置不支持安全的原子防覆盖发布,目标文件未创建',
+ );
+ }
+ throw error;
+ }
+}
+
+async function assertReplaceableTarget(target: string): Promise<void> {
+ try {
+ const stat = await fs.promises.lstat(target);
+ if (!stat.isFile() || stat.isSymbolicLink()) {
+ throw new OutputWriteError('PATH_NOT_ALLOWED', `覆盖目标不是普通文件: ${target}`);
+ }
+ } catch (error) {
+ if (hasCode(error, 'ENOENT')) return;
+ throw error;
+ }
+}
+
+async function replaceFile(
+ request: DocsOutputWriteRequest,
+ workingDir: string,
+ staging: string,
+ target: string,
+): Promise<void> {
+ await verifyParent(request, workingDir);
+ await assertReplaceableTarget(target);
+ try {
+ await fs.promises.rename(staging, target);
+ return;
+ } catch (error) {
+ if (!hasCode(error, 'EEXIST') && !hasCode(error, 'EPERM')) throw error;
+ }
+ // Some Windows, exFAT, and network filesystems reject rename-over-existing.
+ // Moving the old target aside before publishing creates an interruptible
+ // window where a killed utility process makes the user's file disappear.
+ // Fail closed instead: the synced staging file is cleaned by the caller and
+ // the original target remains at its stable name.
+ throw new OutputWriteError(
+ 'ATOMIC_PUBLISH_UNSUPPORTED',
+ '当前输出位置不支持安全的原子覆盖,原文件未移动',
+ );
+}
+
+async function writeWithinVerifiedParent(
+ request: DocsOutputWriteRequest,
+ workingDir: string,
+ outputPath: (name: string) => string,
+): Promise<void> {
+ const target = outputPath(request.targetName);
+ const staging = outputPath(`.cindy-docs-staging-${randomUUID()}-${request.targetName}`);
+ try {
+ await writeExclusive(staging, request.data);
+ await verifyParent(request, workingDir);
+ if (request.overwrite) {
+ await replaceFile(request, workingDir, staging, target);
+ } else {
+ await publishExclusive(staging, target);
+ }
+ await verifyParent(request, workingDir);
+ } finally {
+ try {
+ const stat = await fs.promises.lstat(staging);
+ if (stat.isFile() && !stat.isSymbolicLink()) {
+ await fs.promises.rm(staging, { force: true });
+ }
+ } catch {
+ // Unknown/replaced staging paths are deliberately left untouched.
+ }
+ }
+}
+
+function assertValidRequest(request: DocsOutputWriteRequest): void {
+ if (
+ !request ||
+ typeof request.targetName !== 'string' ||
+ request.targetName !== path.basename(request.targetName) ||
+ request.targetName === '.' ||
+ request.targetName === '..' ||
+ request.targetName.includes('\0') ||
+ !(request.data instanceof Uint8Array) ||
+ typeof request.overwrite !== 'boolean'
+ ) {
+ throw new OutputWriteError('INTERNAL', '文档落盘请求不合法');
+ }
+}
+
+/** Direct-unit-test entry: Vitest runs in worker threads where chdir is unavailable. */
+export async function runDocsOutputWriteForTest(
+ request: DocsOutputWriteRequest,
+ rootDir: string,
+): Promise<void> {
+ assertValidRequest(request);
+ const workingDir = path.join(rootDir, request.parentRelativePath);
+ await ensureParent(request, workingDir);
+ await writeWithinVerifiedParent(request, workingDir, (name) => path.join(workingDir, name));
+}
+
+export async function runDocsOutputWrite(request: DocsOutputWriteRequest): Promise<void> {
+ assertValidRequest(request);
+ // Production starts with `.` bound to the session root. Resolve and verify
+ // the parent from that capability, then chdir into the verified directory so
+ // final file operations no longer re-resolve its mutable lexical path.
+ const anchoredWorkingDir = path.join('.', request.parentRelativePath);
+ await ensureParent(request, anchoredWorkingDir);
+ const previousCwd = process.cwd();
+ try {
+ // chdir binds subsequent relative path operations to the directory inode
+ // selected above. If the lexical parent is rebound before chdir, the
+ // immediate identity check rejects it before any bytes are written; if it
+ // is rebound afterwards, open/rename continue through the verified inode
+ // instead of following the replacement symlink.
+ process.chdir(anchoredWorkingDir);
+ await verifyParent(request, '.');
+ await writeWithinVerifiedParent(request, '.', (name) => name);
+ } finally {
+ try {
+ process.chdir(previousCwd);
+ } catch {
+ // The production utility handles one request and never reuses cwd. A
+ // vanished caller cwd must not turn a safely completed write into an
+ // unrelated failure.
+ }
+ }
+}
+
+if (parentPort) {
+ let handled = false;
+ parentPort.postMessage({ type: 'ready' });
+ parentPort.on('message', (event) => {
+ const message = event.data as { type?: unknown; request?: DocsOutputWriteRequest };
+ if (handled || message?.type !== 'write' || !message.request) return;
+ handled = true;
+ void runDocsOutputWrite(message.request)
+ .then<DocsOutputWriteResult, DocsOutputWriteResult>(
+ () => ({ ok: true }),
+ (error) => ({
+ ok: false,
+ errorCode: error instanceof OutputWriteError ? error.code : 'INTERNAL',
+ message: (error instanceof Error ? error.message : String(error)).slice(0, 8_000),
+ }),
+ )
+ .then((result) => parentPort.postMessage(result));
+ });
+}
diff --git a/apps/desktop/src/main/doc-tools/htmlPdfRenderer.ts b/apps/desktop/src/main/doc-tools/htmlPdfRenderer.ts
new file mode 100644
index 0000000000..70975a5bae
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/htmlPdfRenderer.ts
@@ -0,0 +1,332 @@
+/**
+ * doc-tools/htmlPdfRenderer.ts —— cindy_docs `render_pdf` 的宿主实现。
+ *
+ * 在一个**不可见、即用即毁**的 BrowserWindow 里加载目标 HTML,再用
+ * `webContents.printToPDF` 出字节。`@cindy/mcps` 不 import electron(既有铁律),
+ * 所以这个函数由 mcp-integrations/mcp-providers.ts 闭包注入给 MCP server。
+ *
+ * ── 与 electron-security-and-process-boundaries §3 的对账 ──────────────────
+ * webPreferences 的全部安全字段显式写死,不依赖 Electron 默认值:sandbox、
+ * contextIsolation、nodeIntegration(含 SubFrames / Worker)、webSecurity、
+ * allowRunningInsecureContent、experimentalFeatures、plugins、navigateOnDragDrop、
+ * webviewTag,并且**不挂任何 preload** —— 这个窗口只排版内容,不需要任何 bridge,
+ * 页面里的脚本因此拿不到 Cindy 的任何 IPC 面。导航与弹窗按 §6 fail closed:
+ * `setWindowOpenHandler` 一律 deny,`will-navigate` 只放行首帧那一个地址。
+ *
+ * ── 与 §3.1「独立辅助窗口统一生命周期基线」的关系 ──────────────────────────
+ * §3.1 约束的是「从界面打开、用户会反复打开、要展示给人看」的辅助窗口,权威基线是
+ * resource-usage-window 那套预热 + 隐藏复用 + 双阶段就绪握手的控制器。
+ * **本渲染窗不属于那一类,也刻意不复用那套控制器**,冲突点写在这里:
+ *
+ * 1. 它永远不 show()。没有「打开路径」,也就没有要移出点击路径的准备成本,
+ * 预热与 ready-to-show/内容就绪握手在这里没有对应语义。
+ * 2. 它加载的是**任务提供的任意 HTML**。隐藏复用意味着同一个 webContents 先后
+ * 承载不同任务的内容,残留的 JS 计时器、Service Worker、内存里的上一份文档
+ * 都会跨任务泄漏 —— 这是安全退步,不是性能优化。所以是即用即毁:每次渲染
+ * 一个全新窗口,`finally` 里必 destroy。
+ * 3. 它没有 Renderer 入口、没有 preload、没有主题表面 —— §3.1 第 4/5/6 条
+ * (交互态重置、轻量入口、首帧底色)在这里无对象。
+ *
+ * §3.1 里仍然适用、且这里确实做到的是:安全字段(第 6 条)与故障隔离 + 有界恢复
+ * (第 7 条)。有界恢复在这里体现为:30 秒硬超时、同刻只允许一个渲染窗(其余排队)、
+ * 加载失败 / Renderer 崩溃都只让这一次渲染失败并销毁窗口,绝不升级成整应用退出,
+ * 也不会形成无限重建循环(本模块从不自动重试,重试与否由模型决定)。
+ */
+
+import { promises as fs } from 'node:fs';
+import { randomUUID } from 'node:crypto';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { BrowserWindow, app } from 'electron';
+
+import type { DocsPdfRenderInput, DocsPdfRenderOutput, RenderHtmlToPdfFn } from '@cindy/mcps';
+
+import { createLogger } from '../logger.js';
+
+const log = createLogger('doc-tools/html-pdf');
+
+/**
+ * 渲染窗视口。只影响 CSS 视口宽度(媒体查询、百分比布局),不影响最终纸张尺寸
+ * —— 纸张由 printToPDF 的 pageSize 决定。给一个接近 A4 96dpi 的宽度,让没写
+ * 打印样式的普通网页也能排出正常的行长。
+ */
+const RENDER_VIEWPORT = { width: 1024, height: 1440 };
+
+/**
+ * 同刻并发上限 1。printToPDF 走的是完整 Chromium 排版 + 光栅化,并发开多个隐藏
+ * 窗口在低配机器上会把主进程拖到卡顿;文档生成本来就不是高频操作,排队即可。
+ */
+let renderChain: Promise<unknown> = Promise.resolve();
+
+/** 供测试断言排队行为:当前是否有渲染在跑。 */
+let activeRenders = 0;
+
+export function __getActiveRenderCount(): number {
+ return activeRenders;
+}
+
+function tempRoot(): string {
+ // app.getPath('temp') 在 Electron 里就是系统临时目录;非 Electron 环境(单测)
+ // 回落 os.tmpdir()。可丢弃临时数据放这里,符合 credentials-and-local-storage 的口径。
+ try {
+ return app.getPath('temp');
+ } catch {
+ return os.tmpdir();
+ }
+}
+
+interface PreparedSource {
+ fileUrlPath: string;
+ /** 需要清理的临时目录(仅内联 HTML 走这条路)。 */
+ cleanupDir?: string;
+}
+
+async function prepareSource(input: DocsPdfRenderInput): Promise<PreparedSource> {
+ const dir = await fs.mkdtemp(path.join(tempRoot(), 'cindy-docs-html-'));
+ const file = path.join(dir, 'source.html');
+ const sourceHtml = input.htmlBytes
+ ? Buffer.from(input.htmlBytes).toString('utf8')
+ : (input.html ?? '');
+ await fs.writeFile(file, sourceHtml, 'utf-8');
+ return {
+ fileUrlPath: file,
+ cleanupDir: dir,
+ };
+}
+
+function createRenderWindow(partition: string): BrowserWindow {
+ return new BrowserWindow({
+ show: false,
+ width: RENDER_VIEWPORT.width,
+ height: RENDER_VIEWPORT.height,
+ // 永不进入用户视野:不上任务栏、不抢焦点、不参与窗口切换。
+ skipTaskbar: true,
+ paintWhenInitiallyHidden: true,
+ webPreferences: {
+ // 每次渲染独占一个非持久 partition,不与主窗口/OAuth 页面共享 Cookie、缓存、
+ // localStorage 或既有权限状态。temp: partition 在窗口销毁后不落盘。
+ partition,
+ // ── electron-security §3:全部安全字段显式写死 ──
+ sandbox: true,
+ contextIsolation: true,
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ nodeIntegrationInWorker: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ experimentalFeatures: false,
+ plugins: false,
+ navigateOnDragDrop: false,
+ webviewTag: false,
+ spellcheck: false,
+ // 有意不设 preload:排版窗不需要任何 bridge,页面脚本拿不到 IPC 面。
+ // 有意不设 enableBlinkFeatures。
+ backgroundThrottling: false,
+ },
+ });
+}
+
+/**
+ * PDF 排版窗只允许读取 data/blob URL 与 about:blank;本地 file:// 子资源也拒绝。
+ * 外部网络请求一律取消:即便不读取响应,图片/字体/iframe 也能借用户网络身份探测
+ * localhost/内网或触发第三方跟踪副作用。需要远程资源时由模型先转成 data URI。
+ */
+async function isAllowedResourceUrl(
+ requestUrl: string,
+ entryUrl: string,
+ resourceType?: string,
+): Promise<boolean> {
+ let parsed: URL;
+ try {
+ parsed = new URL(requestUrl);
+ } catch {
+ return false;
+ }
+ if (parsed.protocol === 'data:' || parsed.protocol === 'blob:' || parsed.protocol === 'about:') {
+ return true;
+ }
+ // loadFile() itself is a trusted top-level entry prepared by this renderer.
+ // Only that exact main-frame URL is exempted; page-initiated file: subresources
+ // remain blocked and cannot reopen a path after the security check.
+ if (resourceType === 'mainFrame' && requestUrl === entryUrl) return true;
+ // Never let Chromium reopen a user-controlled file path after this check.
+ // Task-directory resources are converted to data: snapshots by the MCP tool
+ // before this host receives the HTML bytes.
+ if (parsed.protocol === 'file:') return false;
+ return false;
+}
+
+function lockRequests(win: BrowserWindow, entryUrl: string): void {
+ const session = win.webContents.session;
+ session.setPermissionRequestHandler((_webContents, _permission, callback) => callback(false));
+ session.setPermissionCheckHandler(() => false);
+ session.on('will-download', (event) => event.preventDefault());
+ session.webRequest.onBeforeRequest((details, callback) => {
+ void isAllowedResourceUrl(details.url, entryUrl, details.resourceType)
+ .then((allowed) => callback({ cancel: !allowed }))
+ .catch(() => callback({ cancel: true }));
+ });
+}
+
+/**
+ * 弹窗与导航一律 fail closed(electron-security §6)。
+ *
+ * 这里是「全部拒绝」而不是「放行首帧那个地址」:`will-navigate` 只对 Renderer 发起的
+ * 导航触发,Main 侧 `loadFile` 那一次首帧加载根本不经过它。所以能到这个回调的,
+ * 只可能是页面自己想跳走(meta refresh / location.href / 表单自动提交 / 链接点击)
+ * —— 一个只用来排版的离屏文档没有任何理由跳转。顺带避开了「拼 file:// URL 再比字符串」
+ * 在 Windows 上(`C:\a` vs `file:///C:/a`)必然对不上的坑。
+ */
+function lockNavigation(win: BrowserWindow): void {
+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ win.webContents.on('will-navigate', (event: { preventDefault: () => void }) => {
+ event.preventDefault();
+ });
+}
+
+/**
+ * 等页面的 webfont 全部就绪。
+ *
+ * 为什么必须显式等:Chromium **不会**在打印前自己等 `@font-face` 下载完 —— 字体还没
+ * 到位就排版,会静默回退到系统默认字体。这是「我指定的字体在 PDF 里没生效」最常见的
+ * 原因,而且它不报任何错,只能靠等。
+ *
+ * `document.fonts.ready` 是标准 FontFaceSet API,在没有 preload 的 sandbox 窗口里
+ * 同样可用:`executeJavaScript` 由主进程发起、在页面主世界求值,不依赖任何页面桥。
+ *
+ * 单独给一个小超时(而不是拖满总超时):字体等不到只是"排版可能不是你要的",
+ * 不是"渲染失败" —— 该出片还得出片,只是把 fontsReady=false 带回去让上层告警。
+ */
+async function waitForFonts(win: BrowserWindow, timeoutMs: number): Promise<boolean> {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ const ready = win.webContents.executeJavaScript('document.fonts.ready.then(() => true)');
+ const timeout = new Promise<false>((resolve) => {
+ timer = setTimeout(() => resolve(false), timeoutMs);
+ });
+ return (await Promise.race([ready, timeout])) === true;
+ } catch (err) {
+ // 页面没有 document.fonts(极老的内容)或求值被拒:按"没等到"处理,继续渲染。
+ log.warn('font readiness probe failed', err);
+ return false;
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+}
+
+interface RenderAttemptResult {
+ buffer: Buffer;
+ fontsReady: boolean;
+}
+
+async function renderOnce(input: DocsPdfRenderInput): Promise<RenderAttemptResult> {
+ const source = await prepareSource(input);
+ let win: BrowserWindow | null = null;
+ let timer: NodeJS.Timeout | undefined;
+
+ try {
+ win = createRenderWindow(`temp:cindy-docs-${randomUUID()}`);
+ const target = win;
+ lockNavigation(target);
+ lockRequests(target, pathToFileURL(source.fileUrlPath).href);
+
+ const work = (async (): Promise<RenderAttemptResult> => {
+ // 加载失败与 Renderer 崩溃都要把这次渲染判死,否则 printToPDF 会在一个空白
+ // 或已死的 webContents 上返回一份「合法但全白」的 PDF —— 那正是最坏的结果:
+ // 用户拿到一个看着像成功的坏文件。
+ const failure = new Promise<never>((_resolve, reject) => {
+ target.webContents.once(
+ 'did-fail-load',
+ (
+ _event: unknown,
+ errorCode: number,
+ errorDescription: string,
+ _validatedUrl: string,
+ isMainFrame: boolean,
+ ) => {
+ if (!isMainFrame) return;
+ reject(new Error(`HTML 加载失败(${errorCode} ${errorDescription})`));
+ },
+ );
+ target.webContents.once(
+ 'render-process-gone',
+ (_event: unknown, details: { reason?: string }) => {
+ reject(new Error(`渲染进程异常退出(${details?.reason ?? 'unknown'})`));
+ },
+ );
+ });
+
+ await Promise.race([target.loadFile(source.fileUrlPath), failure]);
+ // 顺序是硬要求:加载完成 → 等字体就绪 → 才允许 printToPDF。
+ // 提前打印会拿到字体回退后的排版,而且不会有任何报错。
+ const fontsReady = await Promise.race([waitForFonts(target, input.fontTimeoutMs), failure]);
+ const pdf = await Promise.race([
+ target.webContents.printToPDF({
+ landscape: input.landscape,
+ printBackground: input.printBackground,
+ pageSize: input.pageSize,
+ margins: {
+ marginType: 'custom',
+ top: input.margins.top,
+ bottom: input.margins.bottom,
+ left: input.margins.left,
+ right: input.margins.right,
+ },
+ }),
+ failure,
+ ]);
+ return {
+ buffer: Buffer.isBuffer(pdf) ? pdf : Buffer.from(pdf as Uint8Array),
+ fontsReady,
+ };
+ })();
+
+ const timeout = new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error(`HTML 渲染超时(${input.timeoutMs}ms timeout)`));
+ }, input.timeoutMs);
+ });
+
+ return await Promise.race([work, timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ // 即用即毁。超时路径下 work 那条 promise 可能还挂在加载上,destroy 会把它一起
+ // 掐掉;window 销毁后残留的 rejection 由下面的 catch 兜住,不会变成
+ // unhandledRejection 把主进程带走。
+ if (win && !win.isDestroyed()) {
+ try {
+ win.destroy();
+ } catch (err) {
+ log.warn('destroy render window failed', err);
+ }
+ }
+ if (source.cleanupDir) {
+ await fs.rm(source.cleanupDir, { recursive: true, force: true }).catch(() => {
+ /* 临时目录清理尽力而为 */
+ });
+ }
+ }
+}
+
+/**
+ * HTML → PDF。串行执行(同刻 1 个渲染窗),失败抛错由 MCP 工具层翻成
+ * RENDER_TIMEOUT / RENDER_FAILED。
+ */
+export const renderHtmlToPdf: RenderHtmlToPdfFn = (input) => {
+ const start = async (): Promise<DocsPdfRenderOutput> => {
+ activeRenders += 1;
+ try {
+ return await renderOnce(input);
+ } finally {
+ activeRenders -= 1;
+ }
+ };
+ // 成功与失败都接同一个 start:前一次渲染失败不该拖垮排在它后面的这次。
+ const run = renderChain.then(start, start);
+ // 链上只保留「已结束」这一个信号,错误由各自的调用方 await 拿到 —— 不 catch 的话
+ // 这条内部链会变成一个没人处理的 rejection。
+ renderChain = run.catch(() => undefined);
+ return run;
+};
diff --git a/apps/desktop/src/main/doc-tools/pdfInspector.ts b/apps/desktop/src/main/doc-tools/pdfInspector.ts
new file mode 100644
index 0000000000..f2f6d15ae4
--- /dev/null
+++ b/apps/desktop/src/main/doc-tools/pdfInspector.ts
@@ -0,0 +1,39 @@
+/**
+ * doc-tools/pdfInspector.ts —— cindy_docs `inspect_pdf` 的宿主实现。
+ *
+ * 只是一层薄适配:把 MCP 侧的入参转成 reviewer 那条**已经打包好的**一次性 PDF
+ * utility process 请求。
+ *
+ * 为什么复用 reviewer 的进程而不是在 main 里直接 import pdfjs:
+ * 1. 打包体积 —— pdfjs 打进 main bundle 是 +1.62 MB(minified),而它已经作为
+ * 独立 forge entry 随包发出去了一份,再来一份纯属重复;
+ * 2. 安全与稳定 —— 正式包关闭 RunAsNode,解析「模型刚生成/用户给的」PDF 属于
+ * 处理不可信输入,不该在 Electron main 进程里做;那个 utility process 有
+ * 128MB 堆上限、中性 cwd、最小 env,超时直接 kill;
+ * 3. 零打包改动 —— forge entry 与 vite 配置都已存在且被 packaging 契约测试守着。
+ *
+ * 代价是 doc-tools 依赖了 reviewer 目录下的模块。那个模块本质是「有界 PDF 读取
+ * 设施」而非 reviewer 业务逻辑,协议里已按 kind 分成 extract / inspect 两种作业。
+ */
+
+import type { InspectPdfFn } from '@cindy/mcps';
+
+import { inspectPdfPagesInChild } from '../reviewer/reviewPdfProcess.js';
+
+/** 与 MCP 工具侧的 MAX_INPUT_BYTES 对齐;子进程侧还会再校验一次。 */
+const MAX_INPUT_BYTES = 64 * 1024 * 1024;
+
+export const inspectPdf: InspectPdfFn = async (input) => {
+ const result = await inspectPdfPagesInChild(input.data, {
+ timeoutMs: input.timeoutMs,
+ maxPages: input.maxPages,
+ maxInputBytes: MAX_INPUT_BYTES,
+ previewChars: input.previewChars,
+ pages: input.pages,
+ });
+ return {
+ numPages: result.numPages,
+ pagesInspected: result.pagesInspected,
+ pages: result.pages,
+ };
+};
diff --git a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
index 706d141089..16ef943886 100644
--- a/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/mcpToolApprovalPolicy.test.ts
@@ -59,6 +59,8 @@ describe('desktop Claude read-only allowlist', () => {
'mcp__cindy_scheduler__list_tools',
'mcp__cindy_ssh__list_tools',
'mcp__cindy_helper__list_tools',
+ 'mcp__cindy_docs__read_sheet',
+ 'mcp__cindy_docs__inspect_pdf',
'mcp__cindy_memory__list_tools',
'mcp__cindy_contacts__list_tools',
'mcp__cindy_slack__slack_status',
@@ -106,6 +108,40 @@ describe('desktop MCP approval policy', () => {
);
});
+ // cindy_docs 是渐进披露 server:对外只有 list_tools / call_tool。read_sheet 与
+ // inspect_pdf 只读会话工作目录内的文件(路径由 @cindy/mcps 确定性钳制),免审批;
+ // 四个落盘工具必须继续走常规审批链 —— 一次"同意 call_tool"不能变成写盘的通行证。
+ it('auto-approves only the two read-only docs tools', () => {
+ // cindy_docs 六个工具自 2026-08-21 起顶层暴露(此前藏在 call_tool 二级分派后,
+ // 模型看不见、从没调用过)。审批因此改按 `<server>::<tool>` 精确匹配。
+ for (const tool of ['read_sheet', 'inspect_pdf']) {
+ expect(
+ getDesktopMcpToolApprovalPolicy({
+ serverName: 'cindy_docs',
+ toolName: tool,
+ toolParams: { path: 'a.pdf' },
+ }),
+ `${tool} should be auto-approved`,
+ ).toBe('auto-approve');
+ }
+
+ // 四个落盘工具继续逐次确认。
+ for (const tool of ['make_docx', 'make_pptx', 'make_xlsx', 'render_pdf']) {
+ expect(
+ getDesktopMcpToolApprovalPolicy({
+ serverName: 'cindy_docs',
+ toolName: tool,
+ toolParams: { outPath: 'a.docx' },
+ }),
+ `${tool} must not be auto-approved`,
+ ).toBe('prompt');
+ }
+
+ // 工具名读不出来时 fail closed;cindy_docs 也不在 TRUSTED_MCP_SERVERS 里,
+ // 不按 server 整体静默。
+ expect(getDesktopMcpToolApprovalPolicy({ serverName: 'cindy_docs' })).toBe('prompt');
+ });
+
it('auto-approves only explicitly reviewed builtin servers', () => {
for (const serverName of [
'cindy_android',
diff --git a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
index e7e04a7810..a946bdfd29 100644
--- a/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
+++ b/apps/desktop/src/main/maker-host/mcp-tool-approval-policy.ts
@@ -59,6 +59,12 @@ const READ_ONLY_MCP_TOOLS: ReadonlySet<string> = new Set([
'cindy_scheduler::list_tools',
'cindy_ssh::list_tools',
'cindy_helper::list_tools',
+ // cindy_docs 六个工具顶层暴露(2026-08-21)。两个只读工具免审批:路径由
+ // cindy-docs/_paths.ts 钳制在会话 workingDir 内,不写盘、不出境。inspect_pdf
+ // 尤其要免审批 —— 它是「出完 PDF 回读自检」闭环的一步,卡审批模型就会跳过自检
+ // 直接交付。四个落盘工具(make_docx/make_pptx/make_xlsx/render_pdf)不在此表。
+ 'cindy_docs::read_sheet',
+ 'cindy_docs::inspect_pdf',
'cindy_memory::list_tools',
'cindy_contacts::list_tools',
'cindy_slack::slack_status',
diff --git a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
index bb72b32022..5614a6bc82 100644
--- a/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
+++ b/apps/desktop/src/main/maker-host/plugins/__tests__/plugin-registry.test.ts
@@ -70,6 +70,7 @@ function realBuiltinProviderNames(): KnownProviderName[] {
ssh: {} as never,
memory: {} as never,
contacts: {} as never,
+ docs: {} as never,
xdtHelper: {} as never,
orca: {} as never,
lsp: {} as never,
@@ -395,6 +396,22 @@ describe('PluginRegistry — scoped priority', () => {
}
});
+ // 文档工坊(cindy_docs)的归置裁决:不是基础设施(不做文档的用户应该能关掉,
+ // 省下两个入口工具的上下文),也没有专属设置页,所以它必须出现在通用「内置工具」
+ // 列表里、默认开启、可由用户在项目或用户默认作用域里关掉。
+ it('exposes the document toolkit as a user-toggleable builtin, enabled by default', async () => {
+ expect(ESSENTIAL_PLUGIN_IDS.has('docs')).toBe(false);
+ expect(HOSTED_ELSEWHERE_PLUGIN_IDS.has('docs')).toBe(false);
+ expect(registry.isEnabled('docs', workingDir)).toBe(true);
+
+ const list = await registry.listPlugins(workingDir);
+ expect(list.map((item) => item.id)).toContain('docs');
+
+ writeProjectSettings(workingDir, { docs: false });
+ registry = createRegistry();
+ expect(registry.isEnabled('docs', workingDir)).toBe(false);
+ });
+
it('listPlugins exposes browser in the user-default scope', async () => {
const list = await registry.listPlugins();
diff --git a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
index 2e4963abac..dd08bc6708 100644
--- a/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
+++ b/apps/desktop/src/main/maker-host/plugins/builtin-plugins.ts
@@ -7,7 +7,7 @@
*
* 所有 ID 都使用短且一致的名字,不带 `cindy_` 前缀:
* android | ios-simulator | browser | computer | feishu_bot | wechat |
- * scheduler | ssh | memory | contacts | xdt_helper | collab(→ cindy_orca) | lsp
+ * scheduler | ssh | memory | contacts | docs | xdt_helper | collab(→ cindy_orca) | lsp
*
* @cindy/mcps/providers.ts 里的现役 MCP provider `name` 使用 `cindy_` 前缀;
* 用户配置仍使用稳定的短 plugin id。映射关系由 PROVIDER_NAME_TO_PLUGIN_ID 定义,
@@ -40,6 +40,7 @@ const BUILTIN_META: BuiltinPluginMeta[] = [
{ id: 'ssh', name: 'SSH Remote', description: 'Run commands on configured SSH hosts via the built-in connection pool (aliases, ssh-agent/keys) — nothing installed remotely' },
{ id: 'memory', name: 'Maker Memory', description: 'Cross-agent long-term memory for persistent context across sessions' },
{ id: 'contacts', name: 'Smart Contacts', description: 'Agent-native contacts — cross-platform identity resolution, relationship context, and timeline events' },
+ { id: 'docs', name: 'Document Toolkit', description: 'Turn content into real files — PDF, Word, Excel, and PowerPoint — and read them back to verify the result. No extra software to install.' },
{ id: 'xdt_helper', name: 'Cindy Helper', description: 'Host capability disclosure — tells agents what tools and models are available' },
{ id: 'collab', name: 'Collab Mode', description: 'Multi-worker collaboration (Orca team) — start_team / create_worker / send_to_worker etc.' },
{ id: 'lsp', name: 'LSP', description: 'TypeScript LSP queries (Beta — gated by Settings → Experimental → LSP Mode)' },
@@ -80,6 +81,7 @@ export type KnownProviderName =
| 'cindy_ssh'
| 'cindy_memory'
| 'cindy_contacts'
+ | 'cindy_docs'
| 'cindy_helper'
| 'cindy_orca'
| 'cindy_lsp';
@@ -110,6 +112,7 @@ export const PROVIDER_NAME_TO_PLUGIN_ID: Record<KnownProviderName, PluginId> = {
cindy_ssh: 'ssh',
cindy_memory: 'memory',
cindy_contacts: 'contacts',
+ cindy_docs: 'docs',
cindy_helper: 'xdt_helper',
cindy_orca: 'collab',
cindy_lsp: 'lsp',
@@ -167,6 +170,7 @@ const PLUGIN_ID_TO_MCP_ID: Record<PluginId, LiziMcpId | undefined> = {
ssh: 'cindy_ssh',
memory: 'cindy_memory',
contacts: 'cindy_contacts',
+ docs: 'cindy_docs',
xdt_helper: 'cindy_helper',
collab: 'cindy_orca',
lsp: 'cindy_lsp',
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index fdfe50ce1a..b4814eb998 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -17,6 +17,9 @@ import {
type ToolResultImageDescription,
} from './ghost.js';
import { createGroupHistoryMcpServer } from './groupHistoryMcpServer.js';
+import { renderHtmlToPdf } from '../doc-tools/htmlPdfRenderer.js';
+import { writeDocsOutput } from '../doc-tools/docsOutputWriter.js';
+import { inspectPdf } from '../doc-tools/pdfInspector.js';
import { getAndroidMcpDeps } from './android.js';
import { getIOSSimulatorMcpDeps } from './ios-simulator.js';
import { getBrowserMcpDeps } from './browser.js';
@@ -301,6 +304,17 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
logger: createLogger('mcp/cindy_lsp'),
isUserEnabled: () => readLspModeSettings().enabled,
},
+ // cindy_docs(文档工坊): docx / pptx / xlsx / csv 全在 @cindy/mcps 内用纯 JS 库实现,
+ // 这里只补上包里做不到的三件事 —— 都需要 electron:
+ // writeDocsOutput: 最终落盘靠 cwd 绑定的单次 utility process;
+ // renderHtmlToPdf: HTML → PDF 靠 Chromium printToPDF(隐藏窗即用即毁);
+ // inspectPdf: 回读 PDF 结构靠一次性 utility process 里的 pdfjs。
+ docs: {
+ logger: createLogger('mcp/cindy_docs'),
+ writeDocsOutput,
+ renderHtmlToPdf,
+ inspectPdf,
+ },
// xdt-helper: 自省 + history + send_to_session (essential 常开)。
// send_to_session 是 skill(issue-bot 等)的会话路由原语, 放 essential 常开不断。
// tryGetOrcaCollabService() 是延迟查找:createDesktopMcpProviders 在 app
diff --git a/apps/desktop/src/main/reviewer/__tests__/pdfInspect.test.ts b/apps/desktop/src/main/reviewer/__tests__/pdfInspect.test.ts
new file mode 100644
index 0000000000..a58ebbc821
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/__tests__/pdfInspect.test.ts
@@ -0,0 +1,156 @@
+/**
+ * inspectPdfPages 的真文件测试:手搓最小 PDF → 真 pdfjs 解析 → 断言结构判定。
+ *
+ * 用手写 PDF 而不是二进制 fixture,是为了让「这份 PDF 里到底有什么」在测试里
+ * 一眼可读 —— 第 2 页确实一个绘制指令都没有,所以它必须被判成 blank。
+ * 这条判定是 cindy_docs 产出自检的地基:整页空白的 PDF 字节数完全正常,
+ * 除了回读结构没有别的办法发现。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ inspectPdfPages,
+ pageVisibilityUnverified,
+ selectPdfPageNumbers,
+} from '../reviewPdfUtilityProcess.js';
+
+/**
+ * 生成一份合法的最小 PDF。
+ * pageSpecs 里每项要么是一段文字(该页画这段文字),要么 null(完全空白页)。
+ */
+function buildPdf(
+ pageSpecs: Array<string | null | { raw: string }>,
+ mediaBox = '[0 0 595.28 841.89]',
+): Uint8Array {
+ const objs: string[] = [];
+ const push = (body: string): number => {
+ objs.push(body);
+ return objs.length; // 1-based object number
+ };
+
+ const pageNums: number[] = [];
+
+ // 先占掉 1(Catalog)与 2(Pages),内容最后回填 —— 它们要引用后面对象的编号。
+ push('');
+ push('');
+ const font = push('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>');
+
+ for (const spec of pageSpecs) {
+ if (spec === null) {
+ pageNums.push(
+ push(`<< /Type /Page /Parent 2 0 R /MediaBox ${mediaBox} /Resources << >> >>`),
+ );
+ continue;
+ }
+ const stream = typeof spec === 'string' ? `BT /F1 24 Tf 72 760 Td (${spec}) Tj ET` : spec.raw;
+ const contentNum = push(
+ `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`,
+ );
+ pageNums.push(
+ push(
+ `<< /Type /Page /Parent 2 0 R /MediaBox ${mediaBox} ` +
+ `/Resources << /Font << /F1 ${font} 0 R >> >> /Contents ${contentNum} 0 R >>`,
+ ),
+ );
+ }
+
+ objs[0] = '<< /Type /Catalog /Pages 2 0 R >>';
+ objs[1] =
+ `<< /Type /Pages /Kids [${pageNums.map((n) => `${n} 0 R`).join(' ')}] ` +
+ `/Count ${pageNums.length} >>`;
+
+ let out = '%PDF-1.4\n';
+ const offsets: number[] = [];
+ objs.forEach((body, index) => {
+ offsets[index] = out.length;
+ out += `${index + 1} 0 obj\n${body}\nendobj\n`;
+ });
+ const xref = out.length;
+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n`;
+ for (const offset of offsets) {
+ out += `${String(offset).padStart(10, '0')} 00000 n \n`;
+ }
+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
+ return new Uint8Array(Buffer.from(out, 'latin1'));
+}
+
+describe('inspectPdfPages', () => {
+ it('声明极大页数时只构造 maxPages 个默认页码', () => {
+ expect(selectPdfPageNumbers(Number.MAX_SAFE_INTEGER, [], 3)).toEqual([1, 2, 3]);
+ expect(selectPdfPageNumbers(100, [99, 2, 2, 101, 1], 2)).toEqual([1, 2]);
+ });
+
+ it('读出页数、尺寸、文本量,并把真正空白的页判成 blank', async () => {
+ const pdf = buildPdf(['Hello Cindy Docs', null]);
+ const result = await inspectPdfPages(pdf, [], 10, 400);
+
+ expect(result.numPages).toBe(2);
+ expect(result.pagesInspected).toBe(2);
+
+ const [first, second] = result.pages;
+ expect(first!.page).toBe(1);
+ expect(Math.round(first!.width)).toBe(595);
+ expect(Math.round(first!.height)).toBe(842);
+ expect(first!.rotation).toBe(0);
+ expect(first!.textChars).toBe('Hello Cindy Docs'.length);
+ expect(first!.textPreview).toContain('Hello Cindy Docs');
+ expect(first!.blank).toBe(false);
+
+ // 第 2 页没有 Contents,任何绘制指令都没有 —— 这就是「打开是白的」那种页。
+ expect(second!.textChars).toBe(0);
+ expect(second!.drawOps).toBe(0);
+ expect(second!.imageOps).toBe(0);
+ expect(second!.blank).toBe(true);
+ });
+
+ it('按页码挑页,越界页码被丢掉而不是报错', async () => {
+ const pdf = buildPdf(['one', 'two', 'three']);
+ const result = await inspectPdfPages(pdf, [3, 1, 99], 10, 400);
+ expect(result.numPages).toBe(3);
+ // 去重 + 升序,越界的 99 被丢弃
+ expect(result.pages.map((p) => p.page)).toEqual([1, 3]);
+ expect(result.pages[1]!.textPreview).toContain('three');
+ });
+
+ it('只含图形状态与变换控制算子的页面仍判为空白', async () => {
+ const pdf = buildPdf([{ raw: 'q 1 0 0 1 0 0 cm Q' }]);
+ const result = await inspectPdfPages(pdf, [], 10, 100);
+ expect(result.pages[0]).toMatchObject({ textChars: 0, drawOps: 0, imageOps: 0, blank: true });
+ });
+
+ it('算子表解析失败时把空文本页标记为未验证', () => {
+ expect(pageVisibilityUnverified(0, null, null)).toBe(true);
+ expect(pageVisibilityUnverified(0, 0, 0)).toBe(false);
+ expect(pageVisibilityUnverified(12, 3, 0)).toBe(false);
+ });
+
+ it('maxPages 卡住检查页数,不会把整份文档读完', async () => {
+ const pdf = buildPdf(['a', 'b', 'c', 'd', 'e']);
+ const result = await inspectPdfPages(pdf, [], 2, 400);
+ expect(result.numPages).toBe(5);
+ expect(result.pagesInspected).toBe(2);
+ expect(result.pages.map((p) => p.page)).toEqual([1, 2]);
+ });
+
+ it('previewChars 截断文本预览', async () => {
+ const pdf = buildPdf(['abcdefghijklmnop']);
+ const result = await inspectPdfPages(pdf, [], 10, 5);
+ expect(result.pages[0]!.textPreview).toHaveLength(5);
+ // 截断的是预览,字符总数仍然是真实值
+ expect(result.pages[0]!.textChars).toBe(16);
+ });
+
+ it('非 A4 尺寸如实报出来(供上层判断 pageSize 是不是传错了)', async () => {
+ const pdf = buildPdf(['x'], '[0 0 612 792]');
+ const result = await inspectPdfPages(pdf, [], 10, 100);
+ expect(Math.round(result.pages[0]!.width)).toBe(612);
+ expect(Math.round(result.pages[0]!.height)).toBe(792);
+ });
+
+ it('损坏的 PDF 抛错而不是返回一份"看起来正常"的空结果', async () => {
+ await expect(
+ inspectPdfPages(new Uint8Array(Buffer.from('not a pdf at all')), [], 10, 100),
+ ).rejects.toThrow();
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
index e0e63dc3b2..bd2e355059 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewArtifactContent.test.ts
@@ -20,7 +20,12 @@ const tempDirs: string[] = [];
class InProcessPdfUtility extends EventEmitter implements ReviewPdfUtilityChildLike {
postMessage(message: unknown): void {
+ // 这个假子进程只服务 reviewer 的正文抽取;协议后来加了 'inspect'(cindy_docs
+ // 的产出自检),两者共用同一条链路,所以这里要先按 kind 收窄再取 maxChars。
const request = message as ReviewPdfUtilityRequest;
+ if (request.kind !== 'extract') {
+ throw new Error(`unexpected PDF utility request kind: ${request.kind}`);
+ }
void extractReviewPdfText(request.data, request.maxChars, request.maxPages)
.then<ReviewPdfUtilityResponse, ReviewPdfUtilityResponse>(
(result) => ({ kind: 'result', id: request.id, ok: true, result }),
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcess.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcess.test.ts
index 63e47096f3..3b1a975e29 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcess.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcess.test.ts
@@ -4,9 +4,13 @@ import { describe, expect, it, vi } from 'vitest';
import {
extractReviewPdfTextInChild,
+ inspectPdfPagesInChild,
type ReviewPdfUtilityChildLike,
} from '../reviewPdfProcess.js';
-import type { ReviewPdfUtilityRequest } from '../reviewPdfProcessProtocol.js';
+import type {
+ ReviewPdfInspectUtilityRequest,
+ ReviewPdfUtilityRequest,
+} from '../reviewPdfProcessProtocol.js';
class FakePdfUtility extends EventEmitter implements ReviewPdfUtilityChildLike {
readonly postMessage = vi.fn((message: unknown) => void message);
@@ -60,3 +64,109 @@ describe('isolated Review PDF extraction', () => {
expect(child.kill).toHaveBeenCalledTimes(1);
});
});
+
+// inspect 与 extract 共用同一个一次性进程(同一个 forge entry,pdfjs 只打包一份),
+// 所以超时/崩溃/kill 的语义必须完全一致 —— 这组用例守住这一点。
+describe('isolated PDF structure inspection', () => {
+ it('把页码与上限透传给子进程,并接收结构结果', async () => {
+ const child = new FakePdfUtility();
+ let sent: ReviewPdfInspectUtilityRequest | undefined;
+ child.postMessage.mockImplementationOnce((message) => {
+ sent = message as ReviewPdfInspectUtilityRequest;
+ queueMicrotask(() => {
+ child.emit('message', {
+ kind: 'result',
+ id: sent!.id,
+ ok: true,
+ result: {
+ numPages: 3,
+ pagesInspected: 1,
+ pages: [
+ {
+ page: 2,
+ width: 595.28,
+ height: 841.89,
+ rotation: 0,
+ textChars: 0,
+ textPreview: '',
+ drawOps: 0,
+ imageOps: 0,
+ blank: true,
+ visibilityUnverified: false,
+ },
+ ],
+ },
+ });
+ });
+ });
+
+ await expect(
+ inspectPdfPagesInChild(Buffer.from('%PDF-1.4'), {
+ timeoutMs: 1_000,
+ maxPages: 5,
+ maxInputBytes: 1_024,
+ previewChars: 100,
+ pages: [2],
+ fork: () => child,
+ }),
+ ).resolves.toMatchObject({ numPages: 3, pagesInspected: 1 });
+
+ expect(sent).toMatchObject({ kind: 'inspect', pages: [2], maxPages: 5, previewChars: 100 });
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ });
+
+ it('形状不合法的结果按失败处理,不把脏数据交上去', async () => {
+ const child = new FakePdfUtility();
+ child.postMessage.mockImplementationOnce((message) => {
+ const request = message as ReviewPdfUtilityRequest;
+ queueMicrotask(() => {
+ child.emit('message', {
+ kind: 'result',
+ id: request.id,
+ ok: true,
+ // pagesInspected 与 pages.length 对不上 —— 校验必须拦下来。
+ result: { numPages: 2, pagesInspected: 2, pages: [] },
+ });
+ });
+ });
+
+ await expect(
+ inspectPdfPagesInChild(Buffer.from('%PDF-1.4'), {
+ timeoutMs: 1_000,
+ maxPages: 5,
+ maxInputBytes: 1_024,
+ previewChars: 100,
+ fork: () => child,
+ }),
+ ).rejects.toThrow('invalid result');
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ });
+
+ it('无响应的子进程照样被超时 kill', async () => {
+ const child = new FakePdfUtility();
+ await expect(
+ inspectPdfPagesInChild(Buffer.from('%PDF-1.4'), {
+ timeoutMs: 120,
+ maxPages: 5,
+ maxInputBytes: 1_024,
+ previewChars: 100,
+ fork: () => child,
+ }),
+ ).rejects.toThrow('timed out');
+ expect(child.kill).toHaveBeenCalledTimes(1);
+ });
+
+ it('超出字节上限在 fork 之前就被拒', async () => {
+ const fork = vi.fn(() => new FakePdfUtility());
+ await expect(
+ inspectPdfPagesInChild(Buffer.alloc(2_048), {
+ timeoutMs: 1_000,
+ maxPages: 5,
+ maxInputBytes: 1_024,
+ previewChars: 100,
+ fork,
+ }),
+ ).rejects.toThrow('invalid PDF extractor configuration');
+ expect(fork).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts b/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts
index a374d18fdf..ca561289a4 100644
--- a/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts
+++ b/apps/desktop/src/main/reviewer/__tests__/reviewPdfProcessPackaging.test.ts
@@ -1,9 +1,15 @@
+import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
+import { createRequire } from 'node:module';
+import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
+import { reviewPdfRuntimePackages } from '../reviewPdfRuntimeDeps';
+
const desktopRoot = path.resolve(process.cwd());
+const workspaceRequire = createRequire(import.meta.url);
describe('Review PDF utility process packaging contract', () => {
it('packages a dedicated utility-process entry without reopening RunAsNode', () => {
@@ -16,6 +22,10 @@ describe('Review PDF utility process packaging contract', () => {
path.join(desktopRoot, 'src/main/reviewer/reviewPdfUtilityProcess.ts'),
'utf8',
);
+ const polyfills = fs.readFileSync(
+ path.join(desktopRoot, 'src/main/reviewer/pdfNodeDomPolyfills.ts'),
+ 'utf8',
+ );
const viteConfig = fs.readFileSync(
path.join(desktopRoot, 'vite.review-pdf-process.config.ts'),
'utf8',
@@ -28,9 +38,73 @@ describe('Review PDF utility process packaging contract', () => {
expect(controller).toContain('utilityProcess.fork');
expect(controller).not.toContain('ELECTRON_RUN_AS_NODE');
expect(controller).not.toContain('process.execPath');
+ expect(worker.indexOf("import './pdfNodeDomPolyfills.js'")).toBeLessThan(
+ worker.indexOf("import 'pdfjs-dist/legacy/build/pdf.worker.mjs'"),
+ );
expect(worker).toContain("import 'pdfjs-dist/legacy/build/pdf.worker.mjs'");
expect(worker).toContain("from 'pdfjs-dist/legacy/build/pdf.mjs'");
+ expect(polyfills).toContain("from '@napi-rs/canvas'");
+ expect(polyfills).toContain("typeof globalThis.DOMMatrix === 'undefined'");
+ expect(viteConfig).toContain("external: ['@napi-rs/canvas']");
expect(viteConfig).toContain('inlineDynamicImports: true');
+ expect(forge).toContain('...reviewPdfRuntimePackages(targetPlatform, targetArch)');
+ });
+
+ it('staged canvas wrapper and current-platform binding load without workspace node_modules', () => {
+ const runtimePackages = reviewPdfRuntimePackages(process.platform, process.arch);
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-review-pdf-package-'));
+ try {
+ const stagedModules = path.join(temp, 'node_modules');
+ const stagePackage = (name: string): void => {
+ const packageJson = workspaceRequire.resolve(`${name}/package.json`, {
+ paths: [desktopRoot],
+ });
+ const destination = path.join(stagedModules, name);
+ fs.mkdirSync(path.dirname(destination), { recursive: true });
+ fs.cpSync(path.dirname(packageJson), destination, { recursive: true, dereference: true });
+ };
+ for (const runtimePackage of runtimePackages) stagePackage(runtimePackage);
+
+ const probeRequirePath = path.join(temp, 'probe.cjs');
+ const probe = spawnSync(
+ process.execPath,
+ [
+ '-e',
+ `const { createRequire } = require('node:module');
+const stagedRequire = createRequire(${JSON.stringify(probeRequirePath)});
+const canvas = stagedRequire('@napi-rs/canvas');
+process.stdout.write(canvas.createCanvas(1, 1).toBuffer('image/png').subarray(1, 4).toString('ascii'));`,
+ ],
+ { cwd: temp, encoding: 'utf8' },
+ );
+ expect(probe.status, probe.stderr || String(probe.error ?? '')).toBe(0);
+ expect(probe.stdout).toBe('PNG');
+ } finally {
+ fs.rmSync(temp, { recursive: true, force: true });
+ }
+ });
+
+ it('maps every packaged Desktop target to its canvas binding', () => {
+ expect(reviewPdfRuntimePackages('darwin', 'arm64')).toEqual([
+ '@napi-rs/canvas',
+ '@napi-rs/canvas-darwin-arm64',
+ ]);
+ expect(reviewPdfRuntimePackages('darwin', 'x64')).toEqual([
+ '@napi-rs/canvas',
+ '@napi-rs/canvas-darwin-x64',
+ ]);
+ expect(reviewPdfRuntimePackages('win32', 'x64')).toEqual([
+ '@napi-rs/canvas',
+ '@napi-rs/canvas-win32-x64-msvc',
+ ]);
+ expect(reviewPdfRuntimePackages('linux', 'arm64')).toEqual([
+ '@napi-rs/canvas',
+ '@napi-rs/canvas-linux-arm64-gnu',
+ ]);
+ expect(reviewPdfRuntimePackages('linux', 'x64')).toEqual([
+ '@napi-rs/canvas',
+ '@napi-rs/canvas-linux-x64-gnu',
+ ]);
});
it('passes only system locale/temp variables and a neutral cwd to the helper', () => {
diff --git a/apps/desktop/src/main/reviewer/pdfNodeDomPolyfills.ts b/apps/desktop/src/main/reviewer/pdfNodeDomPolyfills.ts
new file mode 100644
index 0000000000..5d18600303
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/pdfNodeDomPolyfills.ts
@@ -0,0 +1,22 @@
+/**
+ * PDF.js detects Electron utility processes as a non-Node environment because
+ * `process.type` is `utility`. Its built-in Node bootstrap therefore skips the
+ * DOM geometry polyfills even though the worker bundle constructs a DOMMatrix
+ * during module evaluation. Install the same canvas implementation PDF.js uses
+ * in ordinary Node before either PDF.js bundle is evaluated.
+ */
+import {
+ DOMMatrix as CanvasDOMMatrix,
+ ImageData as CanvasImageData,
+ Path2D as CanvasPath2D,
+} from '@napi-rs/canvas';
+
+if (typeof globalThis.DOMMatrix === 'undefined') {
+ globalThis.DOMMatrix = CanvasDOMMatrix as unknown as typeof globalThis.DOMMatrix;
+}
+if (typeof globalThis.ImageData === 'undefined') {
+ globalThis.ImageData = CanvasImageData as unknown as typeof globalThis.ImageData;
+}
+if (typeof globalThis.Path2D === 'undefined') {
+ globalThis.Path2D = CanvasPath2D as unknown as typeof globalThis.Path2D;
+}
diff --git a/apps/desktop/src/main/reviewer/reviewPdfProcess.ts b/apps/desktop/src/main/reviewer/reviewPdfProcess.ts
index 91a4799466..11d278f04e 100644
--- a/apps/desktop/src/main/reviewer/reviewPdfProcess.ts
+++ b/apps/desktop/src/main/reviewer/reviewPdfProcess.ts
@@ -4,12 +4,18 @@ import path from 'node:path';
import { utilityProcess } from 'electron';
import type {
+ ReviewPdfInspectProcessResult,
+ ReviewPdfPageInspection,
ReviewPdfTextProcessResult,
ReviewPdfUtilityRequest,
ReviewPdfUtilityResponse,
} from './reviewPdfProcessProtocol.js';
-export type { ReviewPdfTextProcessResult } from './reviewPdfProcessProtocol.js';
+export type {
+ ReviewPdfInspectProcessResult,
+ ReviewPdfPageInspection,
+ ReviewPdfTextProcessResult,
+} from './reviewPdfProcessProtocol.js';
export interface ReviewPdfUtilityChildLike {
postMessage(message: unknown): void;
@@ -84,28 +90,21 @@ function parseResponse(value: unknown, expectedId: string): ReviewPdfUtilityResp
: null;
}
-export async function extractReviewPdfTextInChild(
- data: Uint8Array,
- maxChars: number,
- options: ReviewPdfTextProcessOptions,
-): Promise<ReviewPdfTextProcessResult> {
- if (
- !Number.isSafeInteger(maxChars) ||
- maxChars <= 0 ||
- !Number.isSafeInteger(options.timeoutMs) ||
- options.timeoutMs <= 0 ||
- !Number.isSafeInteger(options.maxPages) ||
- options.maxPages <= 0 ||
- !Number.isSafeInteger(options.maxInputBytes) ||
- options.maxInputBytes <= 0 ||
- data.byteLength > options.maxInputBytes
- ) {
- throw new Error('invalid PDF extractor configuration');
- }
-
+/**
+ * 一次性子进程作业的公共骨架:fork → 发一条请求 → 收一条匹配响应 → 无论成败都 kill。
+ * extract 与 inspect 共用它,超时/崩溃/退出的处理只此一份,不会两边走样。
+ */
+function runPdfUtilityJob<T>(
+ buildRequest: (id: string) => ReviewPdfUtilityRequest,
+ // 这里刻意用 boolean 而不是类型谓词:两种作业的响应是一个联合类型,谓词只会把它
+ // 交叉成 `Union & T`,反而推不回调用方要的 T。真正的保证在运行期 —— validate 不
+ // 通过就 reject,下面那次断言只在校验成功之后发生。
+ validate: (result: unknown) => boolean,
+ options: { timeoutMs: number; fork?: () => ReviewPdfUtilityChildLike },
+): Promise<T> {
const child = (options.fork ?? forkReviewPdfUtilityProcess)();
const id = randomUUID();
- return new Promise<ReviewPdfTextProcessResult>((resolve, reject) => {
+ return new Promise<T>((resolve, reject) => {
let settled = false;
const timer = setTimeout(() => {
finish(() => reject(new Error('PDF extraction timed out in the isolated process')));
@@ -132,11 +131,11 @@ export async function extractReviewPdfTextInChild(
finish(() => reject(new Error(response.error.slice(0, 8_000))));
return;
}
- if (!isReviewPdfTextProcessResult(response.result, maxChars, options.maxPages)) {
+ if (!validate(response.result)) {
finish(() => reject(new Error('PDF extractor returned an invalid result')));
return;
}
- finish(() => resolve(response.result));
+ finish(() => resolve(response.result as T));
});
child.on('error', (type, location) => {
finish(() =>
@@ -147,18 +146,138 @@ export async function extractReviewPdfTextInChild(
finish(() => reject(new Error(`PDF extractor exited with code ${String(code)}`)));
});
- const request: ReviewPdfUtilityRequest = {
+ try {
+ child.postMessage(buildRequest(id));
+ } catch (error) {
+ finish(() => reject(error));
+ }
+ });
+}
+
+export async function extractReviewPdfTextInChild(
+ data: Uint8Array,
+ maxChars: number,
+ options: ReviewPdfTextProcessOptions,
+): Promise<ReviewPdfTextProcessResult> {
+ if (
+ !Number.isSafeInteger(maxChars) ||
+ maxChars <= 0 ||
+ !Number.isSafeInteger(options.timeoutMs) ||
+ options.timeoutMs <= 0 ||
+ !Number.isSafeInteger(options.maxPages) ||
+ options.maxPages <= 0 ||
+ !Number.isSafeInteger(options.maxInputBytes) ||
+ options.maxInputBytes <= 0 ||
+ data.byteLength > options.maxInputBytes
+ ) {
+ throw new Error('invalid PDF extractor configuration');
+ }
+
+ return runPdfUtilityJob<ReviewPdfTextProcessResult>(
+ (id) => ({
kind: 'extract',
id,
data: new Uint8Array(data),
maxInputBytes: options.maxInputBytes,
maxChars,
maxPages: options.maxPages,
- };
- try {
- child.postMessage(request);
- } catch (error) {
- finish(() => reject(error));
- }
- });
+ }),
+ (result) => isReviewPdfTextProcessResult(result, maxChars, options.maxPages),
+ options,
+ );
+}
+
+export interface ReviewPdfInspectProcessOptions {
+ timeoutMs: number;
+ maxPages: number;
+ maxInputBytes: number;
+ previewChars: number;
+ /** 要检查的页码(1 起);空数组 = 从头顺序取 maxPages 页。 */
+ pages?: readonly number[];
+ /** Test seam; production always forks the packaged Electron utility entry. */
+ fork?: () => ReviewPdfUtilityChildLike;
+}
+
+function isReviewPdfPageInspection(value: unknown, maxPages: number): boolean {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const page = value as Record<string, unknown>;
+ const nullableCount = (v: unknown): boolean =>
+ v === null || (Number.isSafeInteger(v) && Number(v) >= 0);
+ return (
+ Number.isSafeInteger(page.page) &&
+ Number(page.page) >= 1 &&
+ typeof page.width === 'number' &&
+ Number.isFinite(page.width) &&
+ typeof page.height === 'number' &&
+ Number.isFinite(page.height) &&
+ Number.isSafeInteger(page.rotation) &&
+ Number.isSafeInteger(page.textChars) &&
+ Number(page.textChars) >= 0 &&
+ typeof page.textPreview === 'string' &&
+ nullableCount(page.drawOps) &&
+ nullableCount(page.imageOps) &&
+ typeof page.blank === 'boolean' &&
+ typeof page.visibilityUnverified === 'boolean' &&
+ maxPages > 0
+ );
+}
+
+function isReviewPdfInspectResult(
+ value: unknown,
+ maxPages: number,
+): value is ReviewPdfInspectProcessResult {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const record = value as Record<string, unknown>;
+ return (
+ Number.isSafeInteger(record.numPages) &&
+ Number(record.numPages) >= 0 &&
+ Number.isSafeInteger(record.pagesInspected) &&
+ Number(record.pagesInspected) >= 0 &&
+ Number(record.pagesInspected) <= maxPages &&
+ Array.isArray(record.pages) &&
+ record.pages.length === Number(record.pagesInspected) &&
+ record.pages.every((page) => isReviewPdfPageInspection(page, maxPages))
+ );
+}
+
+/**
+ * 读一份 PDF 的结构快照(页数/尺寸/文本量/空白判定),供 cindy_docs 的 inspect_pdf
+ * 做产出自检。与文本抽取共用同一个一次性 utility process。
+ */
+export async function inspectPdfPagesInChild(
+ data: Uint8Array,
+ options: ReviewPdfInspectProcessOptions,
+): Promise<ReviewPdfInspectProcessResult> {
+ if (
+ !Number.isSafeInteger(options.timeoutMs) ||
+ options.timeoutMs <= 0 ||
+ !Number.isSafeInteger(options.maxPages) ||
+ options.maxPages <= 0 ||
+ !Number.isSafeInteger(options.maxInputBytes) ||
+ options.maxInputBytes <= 0 ||
+ !Number.isSafeInteger(options.previewChars) ||
+ options.previewChars < 0 ||
+ data.byteLength > options.maxInputBytes
+ ) {
+ throw new Error('invalid PDF extractor configuration');
+ }
+
+ const pages = [...(options.pages ?? [])];
+ if (!pages.every((page) => Number.isSafeInteger(page) && page >= 1)) {
+ throw new Error('invalid PDF extractor configuration');
+ }
+
+ return runPdfUtilityJob<ReviewPdfInspectProcessResult>(
+ (id) => ({
+ kind: 'inspect',
+ id,
+ data: new Uint8Array(data),
+ maxInputBytes: options.maxInputBytes,
+ pages,
+ maxPages: options.maxPages,
+ previewChars: options.previewChars,
+ }),
+ (result) => isReviewPdfInspectResult(result, options.maxPages),
+ options,
+ );
}
diff --git a/apps/desktop/src/main/reviewer/reviewPdfProcessProtocol.ts b/apps/desktop/src/main/reviewer/reviewPdfProcessProtocol.ts
index 2df8e16e92..80331fb7fd 100644
--- a/apps/desktop/src/main/reviewer/reviewPdfProcessProtocol.ts
+++ b/apps/desktop/src/main/reviewer/reviewPdfProcessProtocol.ts
@@ -1,3 +1,11 @@
+/**
+ * 一次性 PDF utility process 的请求/响应协议。
+ *
+ * 两个消费方共用同一条进程链路(同一个 forge entry,pdfjs 只打包一份):
+ * - 'extract' : Reviewer 读 PDF 交付物的正文(有字符上限)。
+ * - 'inspect' : cindy_docs 的 inspect_pdf —— 出完 PDF 后回读结构做产出自检。
+ */
+
export interface ReviewPdfTextProcessResult {
sections: string[];
pagesInspected: number;
@@ -5,7 +13,36 @@ export interface ReviewPdfTextProcessResult {
clipped: boolean;
}
-export interface ReviewPdfUtilityRequest {
+/** 单页结构快照。宽高单位是 PDF point(1/72 英寸)。 */
+export interface ReviewPdfPageInspection {
+ page: number;
+ width: number;
+ height: number;
+ rotation: number;
+ /** 该页可提取文本的字符数。 */
+ textChars: number;
+ /** 文本开头片段,供模型判断"这页装的是不是它以为的内容"。 */
+ textPreview: string;
+ /**
+ * 绘图算子数量。null = 该页算子表读取失败(文件损坏 / 超内存预算),此时不参与
+ * 空白判定 —— 读不出来不等于「这页是空的」。
+ */
+ drawOps: number | null;
+ /** 图像绘制算子数量。null 含义同 drawOps。 */
+ imageOps: number | null;
+ /** 无文本且无任何绘图/图像算子。算子读不出来时恒为 false(不猜)。 */
+ blank: boolean;
+ /** true = 算子读取不完整,结构检查未完成;false = 算子已成功读取。 */
+ visibilityUnverified: boolean;
+}
+
+export interface ReviewPdfInspectProcessResult {
+ numPages: number;
+ pagesInspected: number;
+ pages: ReviewPdfPageInspection[];
+}
+
+export interface ReviewPdfExtractUtilityRequest {
kind: 'extract';
id: string;
data: Uint8Array;
@@ -14,6 +51,27 @@ export interface ReviewPdfUtilityRequest {
maxPages: number;
}
+export interface ReviewPdfInspectUtilityRequest {
+ kind: 'inspect';
+ id: string;
+ data: Uint8Array;
+ maxInputBytes: number;
+ /** 要检查的页码(1 起)。空数组 = 从第 1 页顺序取 maxPages 页。 */
+ pages: number[];
+ maxPages: number;
+ /** 每页 textPreview 的字符上限。 */
+ previewChars: number;
+}
+
+export type ReviewPdfUtilityRequest =
+ | ReviewPdfExtractUtilityRequest
+ | ReviewPdfInspectUtilityRequest;
+
export type ReviewPdfUtilityResponse =
- | { kind: 'result'; id: string; ok: true; result: ReviewPdfTextProcessResult }
+ | {
+ kind: 'result';
+ id: string;
+ ok: true;
+ result: ReviewPdfTextProcessResult | ReviewPdfInspectProcessResult;
+ }
| { kind: 'result'; id: string; ok: false; error: string };
diff --git a/apps/desktop/src/main/reviewer/reviewPdfRuntimeDeps.ts b/apps/desktop/src/main/reviewer/reviewPdfRuntimeDeps.ts
new file mode 100644
index 0000000000..6120ac2c59
--- /dev/null
+++ b/apps/desktop/src/main/reviewer/reviewPdfRuntimeDeps.ts
@@ -0,0 +1,17 @@
+/** Runtime packages needed by the externalized Reviewer PDF canvas polyfill. */
+export function reviewPdfRuntimePackages(platform: string, arch: string): string[] {
+ let binding: string | undefined;
+ if (platform === 'darwin' && (arch === 'x64' || arch === 'arm64')) {
+ binding = `@napi-rs/canvas-darwin-${arch}`;
+ } else if (platform === 'win32' && (arch === 'x64' || arch === 'arm64')) {
+ binding = `@napi-rs/canvas-win32-${arch}-msvc`;
+ } else if (platform === 'linux') {
+ if (arch === 'arm' || arch === 'armv7l') {
+ binding = '@napi-rs/canvas-linux-arm-gnueabihf';
+ } else if (arch === 'x64' || arch === 'arm64') {
+ binding = `@napi-rs/canvas-linux-${arch}-gnu`;
+ }
+ }
+ if (!binding) throw new Error(`Unsupported @napi-rs/canvas target: ${platform}-${arch}`);
+ return ['@napi-rs/canvas', binding];
+}
diff --git a/apps/desktop/src/main/reviewer/reviewPdfUtilityProcess.ts b/apps/desktop/src/main/reviewer/reviewPdfUtilityProcess.ts
index 272cc791d0..7656af8c75 100644
--- a/apps/desktop/src/main/reviewer/reviewPdfUtilityProcess.ts
+++ b/apps/desktop/src/main/reviewer/reviewPdfUtilityProcess.ts
@@ -1,4 +1,15 @@
-/** One-shot packaged Electron utility process for bounded PDF text extraction. */
+/**
+ * One-shot packaged Electron utility process for bounded PDF reading.
+ *
+ * 两种作业共用这一条链路(同一个 forge entry —— pdfjs 只打包一份,也只在这里跑):
+ * - 'extract' : Reviewer 读 PDF 交付物正文。
+ * - 'inspect' : cindy_docs 的 inspect_pdf,回读刚生成的 PDF 做产出自检。
+ * 正式包关闭 RunAsNode,PDF.js 一律在这个一次性进程里跑,超时直接 kill。
+ */
+
+// Electron utility processes have `process.type="utility"`, so PDF.js does not
+// run its own Node bootstrap. This import must stay before both PDF.js bundles.
+import './pdfNodeDomPolyfills.js';
// PDF.js uses a fake worker under Node and otherwise loads `./pdf.worker.mjs`
// with a variable dynamic import. Forge/Vite cannot discover or copy that
@@ -9,6 +20,8 @@ import 'pdfjs-dist/legacy/build/pdf.worker.mjs';
import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.mjs';
import type {
+ ReviewPdfInspectProcessResult,
+ ReviewPdfPageInspection,
ReviewPdfTextProcessResult,
ReviewPdfUtilityRequest,
ReviewPdfUtilityResponse,
@@ -21,25 +34,46 @@ interface ParentPortLike {
const parentPort = (process as unknown as { parentPort?: ParentPortLike }).parentPort;
+/** 两种请求共有的字节与页数护栏。 */
+function hasValidEnvelope(request: Partial<ReviewPdfUtilityRequest>): boolean {
+ return (
+ typeof request.id === 'string' &&
+ request.id.length > 0 &&
+ request.data instanceof Uint8Array &&
+ Number.isSafeInteger(request.maxInputBytes) &&
+ Number(request.maxInputBytes) > 0 &&
+ request.data.byteLength <= Number(request.maxInputBytes) &&
+ Number.isSafeInteger(request.maxPages) &&
+ Number(request.maxPages) > 0
+ );
+}
+
function parseRequest(value: unknown): ReviewPdfUtilityRequest | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const request = value as Partial<ReviewPdfUtilityRequest>;
- if (
- request.kind !== 'extract' ||
- typeof request.id !== 'string' ||
- request.id.length === 0 ||
- !(request.data instanceof Uint8Array) ||
- !Number.isSafeInteger(request.maxInputBytes) ||
- Number(request.maxInputBytes) <= 0 ||
- request.data.byteLength > Number(request.maxInputBytes) ||
- !Number.isSafeInteger(request.maxChars) ||
- Number(request.maxChars) <= 0 ||
- !Number.isSafeInteger(request.maxPages) ||
- Number(request.maxPages) <= 0
- ) {
- return null;
+ if (!hasValidEnvelope(request)) return null;
+
+ if (request.kind === 'extract') {
+ const maxChars = (request as { maxChars?: unknown }).maxChars;
+ if (!Number.isSafeInteger(maxChars) || Number(maxChars) <= 0) return null;
+ return request as ReviewPdfUtilityRequest;
+ }
+
+ if (request.kind === 'inspect') {
+ const inspect = request as { pages?: unknown; previewChars?: unknown };
+ if (!Number.isSafeInteger(inspect.previewChars) || Number(inspect.previewChars) < 0) {
+ return null;
+ }
+ if (
+ !Array.isArray(inspect.pages) ||
+ !inspect.pages.every((page) => Number.isSafeInteger(page) && Number(page) >= 1)
+ ) {
+ return null;
+ }
+ return request as ReviewPdfUtilityRequest;
}
- return request as ReviewPdfUtilityRequest;
+
+ return null;
}
export async function extractReviewPdfText(
@@ -104,6 +138,163 @@ export async function extractReviewPdfText(
}
}
+/** pdfjs 里代表"画了一张图"的算子。用于区分「这页有图」和「这页什么都没有」。 */
+const IMAGE_OPS: readonly number[] = [
+ pdfjs.OPS.paintImageXObject,
+ pdfjs.OPS.paintInlineImageXObject,
+ pdfjs.OPS.paintImageMaskXObject,
+ pdfjs.OPS.paintImageMaskXObjectGroup,
+ pdfjs.OPS.paintInlineImageXObjectGroup,
+ pdfjs.OPS.paintImageXObjectRepeat,
+ pdfjs.OPS.paintImageMaskXObjectRepeat,
+ pdfjs.OPS.paintSolidColorImageMask,
+].filter((op): op is number => typeof op === 'number');
+
+/**
+ * 真正会留下可见像素的算子。save/restore、transform、clip、构造但未描边的
+ * path 等控制算子不能算“画过”,否则合法的 `q Q` 空白页会被误报为非空。
+ */
+const VISIBLE_PAINT_OPS: readonly number[] = [
+ pdfjs.OPS.stroke,
+ pdfjs.OPS.closeStroke,
+ pdfjs.OPS.fill,
+ pdfjs.OPS.eoFill,
+ pdfjs.OPS.fillStroke,
+ pdfjs.OPS.eoFillStroke,
+ pdfjs.OPS.closeFillStroke,
+ pdfjs.OPS.closeEOFillStroke,
+ pdfjs.OPS.shadingFill,
+ pdfjs.OPS.showText,
+ pdfjs.OPS.showSpacedText,
+ pdfjs.OPS.nextLineShowText,
+ pdfjs.OPS.nextLineSetSpacingShowText,
+ ...IMAGE_OPS,
+].filter((op): op is number => typeof op === 'number');
+
+export function pageVisibilityUnverified(
+ textChars: number,
+ drawOps: number | null,
+ imageOps: number | null,
+): boolean {
+ // This flag denotes an incomplete structural read, not every page that
+ // legitimately contains content. A successful operator parse must still
+ // allow the normal structural verdict to be `ok`.
+ void textChars;
+ return drawOps === null || imageOps === null;
+}
+
+export function selectPdfPageNumbers(
+ numPages: number,
+ requestedPages: readonly number[],
+ maxPages: number,
+): number[] {
+ if (requestedPages.length > 0) {
+ return [...new Set(requestedPages)]
+ .filter((page) => page >= 1 && page <= numPages)
+ .sort((left, right) => left - right)
+ .slice(0, maxPages);
+ }
+
+ const count = Math.max(0, Math.min(numPages, maxPages));
+ return Array.from({ length: count }, (_, index) => index + 1);
+}
+
+/**
+ * 读 PDF 的结构快照:页数、每页尺寸/旋转、文本量与开头片段、绘图与图像算子数,
+ * 并据此判定结构上空白页。这里不做位图渲染,但算子读取成功的页面仍可
+ * 正常给出结构 verdict;只有算子解析失败/未完成才标记 visibilityUnverified。
+ *
+ * 这是 cindy_docs 产出自检的数据来源 —— 生成 PDF 最常见也最难自查的翻车是
+ * 「文件生成了、打开是白的」,它在字节数上完全正常。这里给的是确定性证据:
+ * 某页 textChars=0 且 drawOps=0 且 imageOps=0,那它在结构上就是白的;反之
+ * 仅能证明存在结构内容,不能证明最终像素肉眼可见;这不把每一页都降级成 warning。
+ *
+ * 算子表单独 try/catch:损坏页或超预算时降级成 null 而不是让整次检查失败 ——
+ * 半份结构信息也比"检查工具自己挂了"有用。null 时 blank 恒为 false,并标记
+ * visibilityUnverified,不把未完成的结构检查当成通过。
+ */
+export async function inspectPdfPages(
+ data: Uint8Array,
+ requestedPages: readonly number[],
+ maxPages: number,
+ previewChars: number,
+): Promise<ReviewPdfInspectProcessResult> {
+ const loadingTask = pdfjs.getDocument({
+ data,
+ useWorkerFetch: false,
+ useWasm: false,
+ stopAtErrors: true,
+ // 与 extract 不同:这里要数图像算子,不能把 maxImageSize 卡到 1(那会让含图页
+ // 直接报错)。仍然不解码到位图 —— 只读算子表,内存占用与页面复杂度成正比。
+ isOffscreenCanvasSupported: false,
+ isImageDecoderSupported: false,
+ disableFontFace: true,
+ enableXfa: false,
+ disableRange: true,
+ disableStream: true,
+ disableAutoFetch: true,
+ verbosity: 0,
+ });
+ let document: Awaited<typeof loadingTask.promise> | null = null;
+ try {
+ document = await loadingTask.promise;
+ const numPages = document.numPages;
+
+ // 去重 + 升序 + 丢掉越界页码;不传则从第 1 页顺序取。
+ const selected = selectPdfPageNumbers(numPages, requestedPages, maxPages);
+
+ const pages: ReviewPdfPageInspection[] = [];
+ for (const pageNumber of selected) {
+ const page = await document.getPage(pageNumber);
+ const viewport = page.getViewport({ scale: 1 });
+
+ const textContent = await page.getTextContent();
+ const parts: string[] = [];
+ for (const item of textContent.items) {
+ if (!item || typeof item !== 'object' || !('str' in item)) continue;
+ if (typeof item.str !== 'string') continue;
+ parts.push(item.str, item.hasEOL ? '\n' : ' ');
+ }
+ const text = parts.join('').replace(/\s+/g, ' ').trim();
+
+ let drawOps: number | null = null;
+ let imageOps: number | null = null;
+ try {
+ const operatorList = await page.getOperatorList();
+ const fnArray = operatorList.fnArray;
+ let images = 0;
+ let visiblePaints = 0;
+ for (const fn of fnArray) {
+ if (IMAGE_OPS.includes(fn)) images += 1;
+ if (VISIBLE_PAINT_OPS.includes(fn)) visiblePaints += 1;
+ }
+ drawOps = visiblePaints;
+ imageOps = images;
+ } catch {
+ drawOps = null;
+ imageOps = null;
+ }
+
+ pages.push({
+ page: pageNumber,
+ width: Math.round(viewport.width * 100) / 100,
+ height: Math.round(viewport.height * 100) / 100,
+ rotation: viewport.rotation,
+ textChars: text.length,
+ textPreview: previewChars > 0 ? text.slice(0, previewChars) : '',
+ drawOps,
+ imageOps,
+ blank: text.length === 0 && drawOps === 0 && imageOps === 0,
+ visibilityUnverified: pageVisibilityUnverified(text.length, drawOps, imageOps),
+ });
+ }
+ return { numPages, pagesInspected: pages.length, pages };
+ } finally {
+ if (document) await document.destroy().catch(() => undefined);
+ else await loadingTask.destroy().catch(() => undefined);
+ }
+}
+
if (parentPort) {
let started = false;
parentPort.on('message', (event) => {
@@ -111,7 +302,16 @@ if (parentPort) {
const request = parseRequest(event.data);
if (!request) return;
started = true;
- void extractReviewPdfText(request.data, request.maxChars, request.maxPages)
+ const job =
+ request.kind === 'extract'
+ ? extractReviewPdfText(request.data, request.maxChars, request.maxPages)
+ : inspectPdfPages(
+ request.data,
+ request.pages,
+ request.maxPages,
+ request.previewChars,
+ );
+ void job
.then<ReviewPdfUtilityResponse, ReviewPdfUtilityResponse>(
(result) => ({ kind: 'result', id: request.id, ok: true, result }),
(error) => ({
diff --git a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
index 4e2cfb8e73..90a130fbe7 100644
--- a/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
+++ b/apps/desktop/src/renderer/__tests__/agentActionRowRendering.test.ts
@@ -45,7 +45,7 @@ vi.mock('@/components/chat/useFileChipContextMenu', () => ({
vi.mock('@/lib/filePreview', () => ({ shouldOpenTextLightbox: async () => false }));
vi.mock('@/lib/localPathResolver', () => ({ toLocalFileUrl: (p: string) => `xdt-file://${p}` }));
-import { AgentActionRow } from '@/components/chat/AgentActionRow';
+import { AgentActionRow, humanizeDocumentToolResult } from '@/components/chat/AgentActionRow';
import { AgentActionsBlock } from '@/components/chat/AgentActionsBlock';
import { __test_internals as expandMemory } from '@/hooks/useExpandedBlockMemory';
import type { ChatMessage } from '@/lib/makerChatStore';
@@ -64,6 +64,39 @@ const mkTool = (id: string, toolName: string, toolInput: unknown): ChatMessage =
toolInput,
});
+describe('document tool result presentation', () => {
+ it('shows a human hint instead of the raw JSON error payload', () => {
+ expect(
+ humanizeDocumentToolResult(
+ 'mcp__cindy_docs__make_docx',
+ JSON.stringify({
+ ok: false,
+ errorCode: 'FILE_EXISTS',
+ data: { hint: '目标文件已存在,请换一个文件名。' },
+ }),
+ ),
+ ).toBe('目标文件已存在,请换一个文件名。');
+ });
+
+ it('shows a human hint for read-only document tool failures too', () => {
+ const error = JSON.stringify({
+ ok: false,
+ errorCode: 'FILE_TOO_LARGE',
+ data: { hint: '文件超过检查上限,请先压缩或拆分。' },
+ });
+ expect(humanizeDocumentToolResult('mcp__cindy_docs__read_sheet', error)).toBe(
+ '文件超过检查上限,请先压缩或拆分。',
+ );
+ expect(humanizeDocumentToolResult('mcp:cindy_docs:inspect_pdf', error)).toBe(
+ '文件超过检查上限,请先压缩或拆分。',
+ );
+ });
+
+ it('does not rewrite non-document tool results', () => {
+ expect(humanizeDocumentToolResult('Bash', '{"ok":false}')).toBeNull();
+ });
+});
+
describe('AgentActionRow — 行主文案', () => {
it('Bash 有 description:显示描述、隐藏动词、hover title 为命令原文', () => {
render(
@@ -137,7 +170,12 @@ describe('AgentActionRow — 行主文案', () => {
message: mkTool('t1', 'exec', {
command: 'rg -n useMemo src/renderer | head -40',
commandActions: [
- { type: 'search', command: 'rg -n useMemo src/renderer', query: 'useMemo', path: 'src/renderer' },
+ {
+ type: 'search',
+ command: 'rg -n useMemo src/renderer',
+ query: 'useMemo',
+ path: 'src/renderer',
+ },
],
}),
}),
@@ -208,11 +246,13 @@ describe('AgentActionRow — 行主文案', () => {
render(
createElement(AgentActionRow, {
message: mkTool('t1', 'file_change', {
- changes: [{
- path: '/repo/src/old.ts',
- kind: { type: 'update', move_path: '/repo/src/new.ts' },
- diff: '',
- }],
+ changes: [
+ {
+ path: '/repo/src/old.ts',
+ kind: { type: 'update', move_path: '/repo/src/new.ts' },
+ diff: '',
+ },
+ ],
}),
}),
);
diff --git a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
index b4c25f607e..fef0891dd5 100644
--- a/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
+++ b/apps/desktop/src/renderer/__tests__/generatedFiles.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { collectGeneratedFiles, extractCommandOutputPathCandidates } from '../lib/generatedFiles';
+import {
+ collectGeneratedFiles,
+ extractCommandOutputPathCandidates,
+ extractDocumentArtifactMetadata,
+} from '../lib/generatedFiles';
const WORKDIR = '/work';
@@ -9,6 +13,131 @@ function toolUse(toolName: string, toolInput: unknown) {
}
describe('collectGeneratedFiles', () => {
+ it('turns a top-level cindy docs tool result into artifact metadata', () => {
+ const files = collectGeneratedFiles(
+ [
+ {
+ role: 'tool_use',
+ toolName: 'mcp__cindy_docs__make_pptx',
+ toolUseId: 'ppt-1',
+ toolInput: {
+ outPath: 'documents/roadmap.pptx',
+ title: '产品路线图',
+ theme: 'navy',
+ slides: [{ title: '封面', layout: 'cover' }],
+ },
+ },
+ {
+ role: 'tool_result',
+ toolUseId: 'ppt-1',
+ content: JSON.stringify({
+ ok: true,
+ artifact: {
+ format: 'pptx',
+ title: '产品路线图',
+ theme: 'navy',
+ summary: { kind: 'slides', value: 5 },
+ },
+ }),
+ },
+ ],
+ WORKDIR,
+ );
+ expect(files).toHaveLength(1);
+ expect(files[0].artifactConfirmed).toBe(true);
+ expect(files[0].artifact).toEqual({
+ format: 'pptx',
+ title: '产品路线图',
+ theme: 'navy',
+ summary: { kind: 'slides', value: 5 },
+ preview: { kind: 'slide', title: '封面' },
+ });
+ });
+
+ it('builds the spreadsheet thumbnail only from real tool input cells', () => {
+ expect(
+ extractDocumentArtifactMetadata('make_xlsx', {
+ outPath: 'documents/progress.xlsx',
+ sheets: [
+ {
+ name: '交付进度表',
+ header: ['项目', '状态', '完成率'],
+ rows: [
+ ['文档工坊', '进行中', 0.82],
+ ['作品卡', '已完成', { formula: '1', result: '100%' }],
+ ],
+ },
+ ],
+ }),
+ ).toMatchObject({
+ format: 'xlsx',
+ title: '交付进度表',
+ preview: {
+ kind: 'sheet',
+ hasHeader: true,
+ rows: [
+ ['项目', '状态', '完成率'],
+ ['文档工坊', '进行中', '0.82'],
+ ['作品卡', '已完成', '100%'],
+ ],
+ },
+ });
+ });
+
+ it('recognizes document metadata without a result for replayed tool calls', () => {
+ expect(
+ extractDocumentArtifactMetadata('mcp:cindy_docs:make_docx', {
+ outPath: 'documents/report.docx',
+ title: '季度报告',
+ subtitle: '内部版',
+ theme: 'light',
+ }),
+ ).toMatchObject({
+ format: 'docx',
+ title: '季度报告',
+ subtitle: '内部版',
+ theme: 'light',
+ });
+ });
+
+ it('uses generated byte size as a readable PDF/Word artifact summary', () => {
+ expect(
+ extractDocumentArtifactMetadata(
+ 'render_pdf',
+ { outPath: 'documents/report.pdf', html: '<h1>报告</h1>' },
+ JSON.stringify({ ok: true, bytes: 1536 }),
+ ),
+ ).toMatchObject({ format: 'pdf', summary: { kind: 'bytes', value: 1536 } });
+ expect(
+ extractDocumentArtifactMetadata(
+ 'make_docx',
+ { outPath: 'documents/report.docx', markdown: '# 报告' },
+ JSON.stringify({
+ ok: true,
+ artifact: { format: 'docx', summary: { kind: 'bytes', value: 2048 } },
+ }),
+ ),
+ ).toMatchObject({ format: 'docx', summary: { kind: 'bytes', value: 2048 } });
+ });
+
+ it('does not attach artwork metadata to an explicit failed or malformed tool result', () => {
+ const input = {
+ outPath: 'documents/report.docx',
+ title: '季度报告',
+ theme: 'light',
+ };
+ expect(
+ extractDocumentArtifactMetadata(
+ 'make_docx',
+ input,
+ JSON.stringify({ ok: false, errorCode: 'FILE_EXISTS' }),
+ ),
+ ).toBeUndefined();
+ expect(extractDocumentArtifactMetadata('make_docx', input, 'not-json')).toBeUndefined();
+ // 历史消息没有保存 tool_result 时仍保留兼容重建。
+ expect(extractDocumentArtifactMetadata('make_docx', input)).toBeDefined();
+ });
+
it('collects Write (claude) and write (pi) created files', () => {
const files = collectGeneratedFiles(
[
diff --git a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
index 874bfea9dd..84a3903381 100644
--- a/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/generatedFilesCard.test.ts
@@ -1,7 +1,14 @@
+import { createElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
import { describe, expect, it } from 'vitest';
-import { isLocalGeneratedFileInTurn } from '../components/chat/GeneratedFilesCard';
-import type { GeneratedFileRef } from '../lib/generatedFiles';
+import {
+ ArtifactPreview,
+ getDocumentCoverThemeStyle,
+ isConfirmedRemoteGeneratedFile,
+ isLocalGeneratedFileInTurn,
+} from '../components/chat/GeneratedFilesCard';
+import type { DocumentArtifactMetadata, GeneratedFileRef } from '../lib/generatedFiles';
const START = Date.parse('2026-08-05T10:00:00.000Z');
const END = Date.parse('2026-08-05T10:01:00.000Z');
@@ -12,6 +19,12 @@ const toolFile: GeneratedFileRef = {
source: 'tool',
};
const commandFile: GeneratedFileRef = { ...toolFile, source: 'command' };
+const confirmedDocumentFile: GeneratedFileRef = {
+ ...toolFile,
+ name: 'report.docx',
+ artifact: { format: 'docx' },
+ artifactConfirmed: true,
+};
describe('isLocalGeneratedFileInTurn', () => {
it('accepts a tool-created file whose birthtime falls in the turn', () => {
@@ -36,6 +49,28 @@ describe('isLocalGeneratedFileInTurn', () => {
).toBe(false);
});
+ it('accepts a successfully overwritten document by its current mtime', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ confirmedDocumentFile,
+ { kind: 'file', birthtimeMs: START - 60_000, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(true);
+ });
+
+ it('does not grant the mtime path to unconfirmed replay metadata', () => {
+ expect(
+ isLocalGeneratedFileInTurn(
+ { ...confirmedDocumentFile, artifactConfirmed: undefined },
+ { kind: 'file', birthtimeMs: START - 60_000, mtimeMs: START + 5_000 },
+ START,
+ END,
+ ),
+ ).toBe(false);
+ });
+
it('rejects a failed tool path that only appears in a later turn', () => {
expect(
isLocalGeneratedFileInTurn(
@@ -69,3 +104,48 @@ describe('isLocalGeneratedFileInTurn', () => {
).toBe(true);
});
});
+
+describe('remote generated-file visibility', () => {
+ it('shows a card only after remote stat definitively confirms a file', () => {
+ expect(isConfirmedRemoteGeneratedFile('file')).toBe(true);
+ expect(isConfirmedRemoteGeneratedFile('directory')).toBe(false);
+ expect(isConfirmedRemoteGeneratedFile('nonfile')).toBe(false);
+ expect(isConfirmedRemoteGeneratedFile('unknown')).toBe(false);
+ });
+});
+
+describe('document cover theme tokens', () => {
+ it('maps each artifact theme to semantic preview tokens', () => {
+ const light = getDocumentCoverThemeStyle('light');
+ const dark = getDocumentCoverThemeStyle('dark');
+ const navy = getDocumentCoverThemeStyle('navy');
+ expect(light['--doc-cover-surface']).not.toBe(dark['--doc-cover-surface']);
+ expect(navy['--doc-cover-accent']).not.toBe(light['--doc-cover-accent']);
+ expect(light['--doc-cover-tint']).not.toBe(dark['--doc-cover-tint']);
+ expect(navy['--doc-cover-tint']).not.toBe(light['--doc-cover-tint']);
+ expect(light['--doc-cover-ink']).toContain('var(--text-primary)');
+ });
+
+ it('applies artifact themes to PPT and Excel previews', () => {
+ const artifacts: DocumentArtifactMetadata[] = [
+ {
+ format: 'pptx',
+ theme: 'dark',
+ preview: { kind: 'slide', title: 'Quarterly review' },
+ },
+ {
+ format: 'xlsx',
+ theme: 'navy',
+ preview: { kind: 'sheet', rows: [['Metric'], ['42']], hasHeader: true },
+ },
+ ];
+
+ const [slide, sheet] = artifacts.map((artifact) =>
+ renderToStaticMarkup(createElement(ArtifactPreview, { artifact, title: 'Document' })),
+ );
+ expect(slide).toContain('data-document-theme="dark"');
+ expect(slide).toContain('--doc-cover-surface:var(--surface)');
+ expect(sheet).toContain('data-document-theme="navy"');
+ expect(sheet).toContain('--doc-cover-tint:color-mix');
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
index 4728e40e62..3ddae39711 100644
--- a/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
+++ b/apps/desktop/src/renderer/components/chat/AgentActionRow.tsx
@@ -53,7 +53,11 @@ import {
import { cn, basename } from '@/lib/utils';
import { Spinner } from '@/components/ui/spinner';
import type { ChatMessage } from '@/lib/makerChatStore';
-import { verbForTool, verbLabelKeyForIntent, verbLabelKeyForRow } from '@/lib/agent-actions/verbAggregator';
+import {
+ verbForTool,
+ verbLabelKeyForIntent,
+ verbLabelKeyForRow,
+} from '@/lib/agent-actions/verbAggregator';
import { statsForToolCall } from '@/lib/agent-actions/diffStats';
import { extractDisplayParam } from '@/lib/agent-actions/actionPresentation';
import { SUPPORTED_IMAGE_EXTS, extractExt } from '@/lib/fileTypes';
@@ -230,8 +234,7 @@ function parseAudioTracks(raw: unknown): ToolAudioTrack[] {
: undefined;
// kind 字段是新增 — 老版本 server / 历史 message 没带,默认按 'music' 渲染保
// 持兼容(那条路径自带 cover placeholder,不会因 missing kind 走崩)。
- const kind: 'music' | 'sound_effect' =
- obj.kind === 'sound_effect' ? 'sound_effect' : 'music';
+ const kind: 'music' | 'sound_effect' = obj.kind === 'sound_effect' ? 'sound_effect' : 'music';
out.push({
kind,
audioUrl,
@@ -345,10 +348,7 @@ export function extractToolResultMedia(toolResult: string): ToolMediaItem[] {
// 提取层只打标不裁决,压不压基座由 MessageStream 验证锚卡真含对应图片
// 后决定(验证不过照常渲染,图片永不消失)。手机端提取器不认该令牌。
const imagesInCard = parsed.xdt_images_in_card === true;
- if (
- typeof parsed.xdt_image_url === 'string' &&
- isToolImageUrl(parsed.xdt_image_url)
- ) {
+ if (typeof parsed.xdt_image_url === 'string' && isToolImageUrl(parsed.xdt_image_url)) {
const modelFile = nextModelFile();
items.push({
kind: 'image',
@@ -372,10 +372,7 @@ export function extractToolResultMedia(toolResult: string): ToolMediaItem[] {
}
// 协议白名单与图卡同款双世界:老 xdt-video://(遗产只读)+ 新
// cindy-media://(意识 gen_video 等新链路产物)。
- if (
- typeof parsed.xdt_video_url === 'string' &&
- isToolVideoUrl(parsed.xdt_video_url)
- ) {
+ if (typeof parsed.xdt_video_url === 'string' && isToolVideoUrl(parsed.xdt_video_url)) {
items.push({
kind: 'video',
url: parsed.xdt_video_url,
@@ -455,16 +452,38 @@ export function extractToolResultImageUrls(toolResult: string): string[] {
.map((m) => m.url);
}
+/** 文档工具失败时优先展示可执行的 hint,避免把内部 JSON 直接甩给普通用户。 */
+export function humanizeDocumentToolResult(toolName: string, toolResult: string): string | null {
+ const normalized = toolName.replace(/^mcp__/, 'mcp:').replace(/__/g, ':');
+ const documentTool = normalized.split(':').at(-1) ?? normalized;
+ if (!/^(make_docx|make_pptx|make_xlsx|render_pdf|read_sheet|inspect_pdf)$/.test(documentTool)) {
+ return null;
+ }
+ try {
+ const parsed = JSON.parse(toolResult) as {
+ ok?: unknown;
+ data?: { hint?: unknown; message?: unknown };
+ };
+ if (parsed.ok !== false) return null;
+ if (typeof parsed.data?.hint === 'string' && parsed.data.hint.trim()) {
+ return parsed.data.hint.trim();
+ }
+ if (typeof parsed.data?.message === 'string' && parsed.data.message.trim()) {
+ return parsed.data.message.trim();
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
function commandDisplayText(inp: Record<string, unknown>): string {
if (typeof inp.displayCommand === 'string') return inp.displayCommand;
if (typeof inp.command !== 'string') return '';
return normalizeDisplayCommand(inp.command) ?? inp.command;
}
-function formatInlineInput(
- toolName: string,
- inp: Record<string, unknown> | null,
-): string {
+function formatInlineInput(toolName: string, inp: Record<string, unknown> | null): string {
if (!inp) return '';
switch (toolName) {
case 'Bash':
@@ -700,7 +719,10 @@ export function AgentActionRow({
? descriptor.intent?.action
: undefined;
const isRawCommandFallback =
- descriptor.kind === 'command' && !descriptor.description && !descriptor.intent && showRawCommand;
+ descriptor.kind === 'command' &&
+ !descriptor.description &&
+ !descriptor.intent &&
+ showRawCommand;
const verbLabel = t(
intentAction
? verbLabelKeyForIntent(intentAction)
@@ -716,9 +738,10 @@ export function AgentActionRow({
() => extractDisplayParam(descriptor, { hideRawCommandFallback: showRawCommand }),
[descriptor, showRawCommand],
);
- const fileChangeCountText = isFileChange && descriptor.changes.length > 1
- ? t('chat.agentActionRow.fileChange.files', { count: descriptor.changes.length })
- : null;
+ const fileChangeCountText =
+ isFileChange && descriptor.changes.length > 1
+ ? t('chat.agentActionRow.fileChange.files', { count: descriptor.changes.length })
+ : null;
const rawCommand =
showRawCommand &&
descriptor.kind === 'command' &&
@@ -727,10 +750,10 @@ export function AgentActionRow({
descriptor.command
? descriptor.command
: null;
- const stats = useMemo(
- () => statsForToolCall(toolName, inp),
- [toolName, inp],
- );
+ const userFacingToolResult = toolResult
+ ? (humanizeDocumentToolResult(toolName, toolResult) ?? toolResult)
+ : null;
+ const stats = useMemo(() => statsForToolCall(toolName, inp), [toolName, inp]);
const isFilePathTool = FILE_PATH_TOOLS.has(toolName);
const filePath = descriptor.kind === 'file' ? descriptor.filePath : '';
const singleFileChange =
@@ -894,7 +917,7 @@ export function AgentActionRow({
? `${rowVerbLabel} ${ghostInfo.name} ${ghostInfo.tool}`
: displayParam || fileChangeCountText
? hideVerb
- ? displayParam?.text ?? fileChangeCountText ?? ''
+ ? (displayParam?.text ?? fileChangeCountText ?? '')
: `${rowVerbLabel} ${displayParam?.text ?? fileChangeCountText ?? ''}`
: rowVerbLabel
}
@@ -921,11 +944,7 @@ export function AgentActionRow({
}
className="inline-flex h-[18px] w-4 items-center justify-center shrink-0 text-[var(--msg-tool-card-chevron)]"
>
- {status === 'running' ? (
- <Spinner size={13} />
- ) : (
- <Check size={13} />
- )}
+ {status === 'running' ? <Spinner size={13} /> : <Check size={13} />}
</span>
{!hideVerb && (
<span className="text-14 text-[var(--msg-tool-card-chevron)] shrink-0">
@@ -943,11 +962,7 @@ export function AgentActionRow({
{/* v9: 移除 chevron 上的"查看详情" Tooltip。整行 button 已经是
统一激活目标,末尾 chevron 只保留视觉提示。 */}
<span aria-hidden="true" className={ACTIVITY_ROW_CHEVRON_SLOT_CLASS}>
- {isInlineExpand && expanded ? (
- <ChevronDown size={13} />
- ) : (
- <ChevronRight size={13} />
- )}
+ {isInlineExpand && expanded ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
</span>
</button>
{rawCommand && !expanded && (
@@ -981,22 +996,22 @@ export function AgentActionRow({
)}
>
{inlineInputText && (
- <pre className="whitespace-pre-wrap break-words m-0">
- {inlineInputText}
- </pre>
+ <pre className="whitespace-pre-wrap break-words m-0">{inlineInputText}</pre>
)}
- {toolResult && (
+ {userFacingToolResult && (
<>
{inlineInputText && (
<div className="my-2 h-px bg-[var(--msg-tool-card-chevron)]/20" />
)}
<pre className="whitespace-pre-wrap break-words m-0 text-[var(--msg-tool-card-chevron)]">
- {toolResult}
+ {userFacingToolResult}
</pre>
</>
)}
- {!inlineInputText && !toolResult && (
- <span className="text-[var(--msg-tool-card-chevron)]">{t('chat.agentActionRow.noContent')}</span>
+ {!inlineInputText && !userFacingToolResult && (
+ <span className="text-[var(--msg-tool-card-chevron)]">
+ {t('chat.agentActionRow.noContent')}
+ </span>
)}
</div>
)}
@@ -1017,9 +1032,7 @@ export function AgentActionRow({
onClose={closeLightbox}
/>
)}
- {lightbox.kind === 'image' && (
- <ImageLightbox src={lightbox.src} onClose={closeLightbox} />
- )}
+ {lightbox.kind === 'image' && <ImageLightbox src={lightbox.src} onClose={closeLightbox} />}
{lightbox.kind === 'payload' && (
<ToolPayloadLightbox
payload={lightbox.payload}
diff --git a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
index 7e39e55449..b22b9688ab 100644
--- a/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx
@@ -15,8 +15,8 @@
*
* 存在性门槛(DESIGN.md §14.5「可点必存在」):本地会话渲染前 stat 过滤,不存在
* 的文件不出 chip,整卡为空则不渲染。远程会话经 verifyRemotePathCached 远端 stat
- * 复核:先按 tool_use 记录乐观呈现,verdict 回来后 nonfile/directory 摘掉;
- * unknown(断链 / 限流)保持乐观——与正文 chip 的远程点亮不变量同策。
+ * 复核:仅在远端明确确认是普通文件后呈现;检查中、断链或限流都不先展示一张
+ * 可能无法打开的完成卡。
*
* 本地文件统一要求时间戳落在本轮 `[turnStartMs, turnEndMs)` 窗口内。tool 来源
* (Write / file-change add)也不能只凭存在性:Write 可能覆盖既有文件,失败路径也可能
@@ -30,12 +30,13 @@ import { ChevronDown, ChevronUp, FileText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
-import type { GeneratedFileRef } from '@/lib/generatedFiles';
+import type { DocumentArtifactMetadata, GeneratedFileRef } from '@/lib/generatedFiles';
import { classifyMarkdownHref, toLocalFileUrl } from '@/lib/localPathResolver';
import { isRemoteFileOrigin, toRemoteMediaOrigin } from '@/lib/sessionFileOrigin';
import {
fetchChatFileWithToasts,
revealRemoteChatFile,
+ type RemotePathVerdict,
verifyRemotePathCached,
} from '@/lib/remoteFileOpen';
import { shouldOpenTextLightboxForOrigin } from '@/lib/filePreview';
@@ -46,7 +47,182 @@ import { ImageLightbox } from './ImageLightbox';
import { TextLightbox } from './TextLightbox';
import { ModelLightbox } from './ModelLightbox';
+function formatArtifactSummaryValue(summary: DocumentArtifactMetadata['summary']): number | string {
+ if (!summary || summary.kind !== 'bytes') return summary?.value ?? '';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ let value = summary.value;
+ let unitIndex = 0;
+ while (value >= 1024 && unitIndex < units.length - 1) {
+ value /= 1024;
+ unitIndex += 1;
+ }
+ const precision = value >= 100 ? 0 : value >= 10 ? 1 : 2;
+ return `${value.toFixed(precision)} ${units[unitIndex]}`;
+}
+
+const DOCUMENT_COVER_THEME_TOKENS = {
+ light: {
+ '--doc-cover-surface': 'var(--surface-elevated)',
+ '--doc-cover-tint': 'var(--surface-hover)',
+ '--doc-cover-accent': 'var(--accent-cta-bg)',
+ '--doc-cover-ink': 'var(--text-primary)',
+ '--doc-cover-muted': 'var(--text-tertiary)',
+ },
+ dark: {
+ '--doc-cover-surface': 'var(--surface)',
+ '--doc-cover-tint': 'color-mix(in srgb, var(--surface) 88%, var(--text-primary))',
+ '--doc-cover-accent': 'var(--text-primary)',
+ '--doc-cover-ink': 'var(--text-primary)',
+ '--doc-cover-muted': 'var(--text-secondary)',
+ },
+ navy: {
+ '--doc-cover-surface': 'color-mix(in srgb, var(--surface-elevated) 88%, var(--focus-ring))',
+ '--doc-cover-tint': 'color-mix(in srgb, var(--surface-elevated) 76%, var(--focus-ring))',
+ '--doc-cover-accent': 'var(--focus-ring)',
+ '--doc-cover-ink': 'var(--text-primary)',
+ '--doc-cover-muted': 'var(--text-secondary)',
+ },
+} as const;
+
+export function getDocumentCoverThemeStyle(
+ theme: DocumentArtifactMetadata['theme'] = 'light',
+): Record<string, string> {
+ return DOCUMENT_COVER_THEME_TOKENS[theme] ?? DOCUMENT_COVER_THEME_TOKENS.light;
+}
+
+export function isConfirmedRemoteGeneratedFile(verdict: RemotePathVerdict): boolean {
+ return verdict === 'file';
+}
+
+function DocumentCoverPreview({
+ artifact,
+ title,
+}: {
+ artifact: DocumentArtifactMetadata;
+ title: string;
+}) {
+ const { t } = useTranslation();
+ const formatLabel = t(`chat.generatedFiles.formats.${artifact.format}`);
+
+ return (
+ <span
+ className="flex h-[142px] border-b border-[var(--border-default)] bg-[var(--surface)] p-3"
+ style={getDocumentCoverThemeStyle(artifact.theme)}
+ data-document-theme={artifact.theme ?? 'light'}
+ >
+ <span className="flex h-full w-full flex-col rounded-lg border border-[var(--border-default)] bg-[var(--doc-cover-surface)] px-4 py-3.5">
+ <span className="flex items-center justify-between text-11 font-medium uppercase tracking-[0.1em] text-[var(--doc-cover-muted)]">
+ <span>{formatLabel}</span>
+ {artifact.summary && (
+ <span className="normal-case tracking-normal">
+ {t(`chat.generatedFiles.summary.${artifact.summary.kind}`, {
+ count: formatArtifactSummaryValue(artifact.summary),
+ })}
+ </span>
+ )}
+ </span>
+ <span className="mt-5 block h-1 w-9 rounded-[9999px] bg-[var(--doc-cover-accent)]" />
+ <span className="mt-3 line-clamp-2 text-15 font-semibold leading-5 text-[var(--doc-cover-ink)]">
+ {title}
+ </span>
+ {artifact.subtitle && (
+ <span className="mt-1 line-clamp-1 text-11 text-[var(--doc-cover-muted)]">
+ {artifact.subtitle}
+ </span>
+ )}
+ </span>
+ </span>
+ );
+}
+
+function SlidePreview({ artifact, title }: { artifact: DocumentArtifactMetadata; title: string }) {
+ const { t } = useTranslation();
+ const preview = artifact.preview?.kind === 'slide' ? artifact.preview : undefined;
+ const previewTitle = preview?.title || title;
+ const previewSubtitle = preview?.subtitle || artifact.subtitle;
+
+ return (
+ <span
+ className="relative flex aspect-[16/9] items-center justify-center border-b border-[var(--border-default)] bg-[var(--doc-cover-surface)] px-8 text-center"
+ style={getDocumentCoverThemeStyle(artifact.theme)}
+ data-document-theme={artifact.theme ?? 'light'}
+ >
+ <span className="min-w-0">
+ <span className="mx-auto mb-3 block h-1 w-9 rounded-[9999px] bg-[var(--doc-cover-accent)]" />
+ <span className="block line-clamp-2 text-15 font-semibold leading-5 text-[var(--doc-cover-ink)]">
+ {previewTitle}
+ </span>
+ {previewSubtitle && (
+ <span className="mt-1 block line-clamp-1 text-11 text-[var(--doc-cover-muted)]">
+ {previewSubtitle}
+ </span>
+ )}
+ </span>
+ {artifact.summary && (
+ <span className="absolute bottom-2 right-2 rounded-[9999px] border border-[var(--border-default)] px-2 py-0.5 text-11 text-[var(--doc-cover-muted)]">
+ {t(`chat.generatedFiles.summary.${artifact.summary.kind}`, {
+ count: formatArtifactSummaryValue(artifact.summary),
+ })}
+ </span>
+ )}
+ </span>
+ );
+}
+
+function SheetPreview({ artifact, title }: { artifact: DocumentArtifactMetadata; title: string }) {
+ const preview = artifact.preview?.kind === 'sheet' ? artifact.preview : undefined;
+ if (!preview?.rows.length) return <DocumentCoverPreview artifact={artifact} title={title} />;
+
+ const columnCount = Math.max(1, ...preview.rows.map((row) => row.length));
+ const gridTemplateColumns =
+ columnCount === 3 ? '1fr 1.6fr 1fr' : `repeat(${columnCount}, minmax(0, 1fr))`;
+
+ return (
+ <span
+ className="block border-b border-[var(--border-default)] bg-[var(--doc-cover-surface)]"
+ style={getDocumentCoverThemeStyle(artifact.theme)}
+ data-document-theme={artifact.theme ?? 'light'}
+ >
+ {preview.rows.map((row, rowIndex) => (
+ <span
+ key={rowIndex}
+ className={cn(
+ 'grid min-h-8 border-b border-[var(--border-default)] last:border-b-0',
+ rowIndex === 0 && preview.hasHeader && 'bg-[var(--doc-cover-tint)]',
+ )}
+ style={{ gridTemplateColumns }}
+ >
+ {Array.from({ length: columnCount }, (_, columnIndex) => (
+ <span
+ key={columnIndex}
+ className={cn(
+ 'min-w-0 truncate border-r border-[var(--border-default)] px-2.5 py-1.5 text-12 leading-5 text-[var(--doc-cover-ink)] last:border-r-0',
+ rowIndex === 0 && preview.hasHeader && 'text-11 text-[var(--doc-cover-muted)]',
+ )}
+ >
+ {row[columnIndex] || '\u00a0'}
+ </span>
+ ))}
+ </span>
+ ))}
+ </span>
+ );
+}
+
+export function ArtifactPreview({
+ artifact,
+ title,
+}: {
+ artifact: DocumentArtifactMetadata;
+ title: string;
+}) {
+ if (artifact.format === 'xlsx') return <SheetPreview artifact={artifact} title={title} />;
+ if (artifact.format === 'pptx') return <SlidePreview artifact={artifact} title={title} />;
+ return <DocumentCoverPreview artifact={artifact} title={title} />;
+}
+
function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {
+ const { t } = useTranslation();
const fileCtx = useChatSessionFile();
const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
const ctxMenu = useFileChipContextMenu({
@@ -101,6 +277,16 @@ function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {
setTextLightboxOpen(true);
};
+ const artifact = file.artifact;
+ const format = artifact?.format;
+ const formatLabel = format ? t(`chat.generatedFiles.formats.${format}`) : null;
+ const artifactTitle = artifact?.title || file.name;
+ const summaryLabel = artifact?.summary
+ ? t(`chat.generatedFiles.summary.${artifact.summary.kind}`, {
+ count: formatArtifactSummaryValue(artifact.summary),
+ })
+ : null;
+
return (
<>
<button
@@ -109,17 +295,42 @@ function GeneratedFileChip({ file }: { file: GeneratedFileRef }) {
onClick={() => void open()}
onContextMenu={ctxMenu.onContextMenu}
className={cn(
- 'inline-flex items-center gap-1.5',
- 'h-7 px-2.5 py-1.5 max-w-[280px]',
- 'rounded-[9999px]',
- 'bg-[var(--msg-md-inline-code-bg)]',
- 'text-13 font-medium text-[var(--msg-assistant-text)]',
- 'hover:bg-[var(--cmd-palette-item-hover)]',
- 'transition-colors cursor-pointer',
+ artifact
+ ? 'group block w-full max-w-[420px] cursor-pointer overflow-hidden rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] text-left transition-colors hover:border-[var(--text-tertiary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]'
+ : 'inline-flex h-7 max-w-[280px] items-center gap-1.5 rounded-[9999px] bg-[var(--msg-md-inline-code-bg)] px-2.5 py-1.5 text-13 font-medium text-[var(--msg-assistant-text)] transition-colors hover:bg-[var(--cmd-palette-item-hover)]',
)}
>
- <FileText size={14} className="shrink-0 opacity-70" />
- <span className="truncate">{file.name}</span>
+ {artifact ? (
+ <>
+ <ArtifactPreview artifact={artifact} title={artifactTitle} />
+ <span className="flex min-w-0 items-center gap-3 px-3 py-2.5">
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-13 font-medium leading-5 text-[var(--text-primary)]">
+ {artifactTitle}
+ </span>
+ <span className="mt-0.5 flex min-w-0 items-center gap-1.5 text-11 text-[var(--text-tertiary)]">
+ <span className="shrink-0">{formatLabel}</span>
+ {summaryLabel && (
+ <>
+ <span aria-hidden="true">·</span>
+ <span className="shrink-0">{summaryLabel}</span>
+ </>
+ )}
+ <span aria-hidden="true">·</span>
+ <span className="truncate">{file.name}</span>
+ </span>
+ </span>
+ <span className="shrink-0 text-[var(--text-tertiary)] transition-colors group-hover:text-[var(--text-secondary)]">
+ <FileText size={15} aria-hidden="true" />
+ </span>
+ </span>
+ </>
+ ) : (
+ <>
+ <FileText size={14} className="shrink-0 opacity-70" />
+ <span className="truncate">{file.name}</span>
+ </>
+ )}
</button>
{ctxMenu.menu}
{lightboxSrc && <ImageLightbox src={lightboxSrc} onClose={() => setLightboxSrc(null)} />}
@@ -150,10 +361,10 @@ interface GeneratedFileStat {
}
/**
- * 本地文件是否有足够证据归属于该 turn。tool 来源必须有真实创建时间:
- * Write 也可能覆盖既有文件,仅凭成功/mtime 不能把它当成“新建”;birthtime
- * 不可用时宁可不出。command 来源为兼容不提供 birthtime 的 Linux FS,维持
- * mtime 回退,但仍受完整 turn 时间窗约束。
+ * 本地文件是否有足够证据归属于该 turn。普通文件工具必须有真实创建时间;
+ * 只有文档工具的结构化 ok:true 结果能证明 overwrite 是本轮成功交付,此时
+ * 改用 mtime。command 来源为兼容不提供 birthtime 的 Linux FS,维持 mtime
+ * 回退,但仍受完整 turn 时间窗约束。
*/
export function isLocalGeneratedFileInTurn(
file: GeneratedFileRef,
@@ -164,16 +375,16 @@ export function isLocalGeneratedFileInTurn(
if (stat.kind !== 'file' || turnStartMs === null) return false;
const birthtimeMs =
typeof stat.birthtimeMs === 'number' && stat.birthtimeMs > 0 ? stat.birthtimeMs : null;
- const ts = file.source === 'tool' ? birthtimeMs : (birthtimeMs ?? stat.mtimeMs);
- // tool 来源的 birthtime 是同机 FS 事实,不放宽下界:放 2 分钟 slack 会把本轮
- // 覆盖的旧文件误当新建。command 来源保留消息落库/执行时序抖动余量。
- const lowerBound =
- file.source === 'tool' ? turnStartMs : turnStartMs - TURN_START_SLACK_MS;
- return (
- typeof ts === 'number' &&
- ts >= lowerBound &&
- (turnEndMs === null || ts < turnEndMs)
- );
+ const confirmedArtifactOverwrite = file.artifactConfirmed === true;
+ const ts = confirmedArtifactOverwrite
+ ? stat.mtimeMs
+ : file.source === 'tool'
+ ? birthtimeMs
+ : (birthtimeMs ?? stat.mtimeMs);
+ // tool 来源的 birthtime 或显式成功交付的 mtime 都是同机 FS 事实,不放宽
+ // 下界;command 来源保留消息落库/执行时序抖动余量。
+ const lowerBound = file.source === 'tool' ? turnStartMs : turnStartMs - TURN_START_SLACK_MS;
+ return typeof ts === 'number' && ts >= lowerBound && (turnEndMs === null || ts < turnEndMs);
}
/** 折叠阈值:约两行 chip。超过则收起为「前 N 个 + 再显示 M 个文件」。 */
@@ -191,26 +402,21 @@ export function GeneratedFilesCard({
const { t } = useTranslation();
const fileCtx = useChatSessionFile();
const remoteOrigin = isRemoteFileOrigin(fileCtx.origin) ? fileCtx.origin : null;
- // 本地会话:stat 过滤到真实存在的文件(null = 尚未算完,不渲染,避免闪现后
- // 又被过滤掉);远程:tool 来源先乐观呈现、远端 stat 复核,command 候选无法
- // 验证 mtime 一律不出(见文件头注释)。
- const [existing, setExisting] = useState<GeneratedFileRef[] | null>(
- remoteOrigin ? files.filter((f) => f.source === 'tool') : null,
- );
+ // 本地与远程都先保持 null,等存在性检查完成后再展示,避免完成卡闪现后消失。
+ // 远程 command 候选无法验证 mtime,一律不出(见文件头注释)。
+ const [existing, setExisting] = useState<GeneratedFileRef[] | null>(null);
const [expanded, setExpanded] = useState(false);
useEffect(() => {
let cancelled = false;
+ setExisting(null);
if (remoteOrigin) {
const toolFiles = files.filter((f) => f.source === 'tool');
- setExisting(toolFiles);
void (async () => {
const checks = await Promise.all(
toolFiles.map(async (f) => {
const verdict = await verifyRemotePathCached(remoteOrigin, fileCtx.workingDir, f.path);
- // nonfile(不存在 / 非普通文件)/ directory 是远端确定结论 → 摘掉;
- // unknown(断链 / 限流)保持乐观。
- return verdict !== 'nonfile' && verdict !== 'directory';
+ return isConfirmedRemoteGeneratedFile(verdict);
}),
);
if (!cancelled) setExisting(toolFiles.filter((_, idx) => checks[idx]));
@@ -244,12 +450,17 @@ export function GeneratedFilesCard({
const visible = expanded ? existing : existing.slice(0, MAX_VISIBLE_FILES);
const hiddenCount = existing.length - visible.length;
+ const hasArtifacts = existing.some((file) => file.artifact);
+ const hasOnlyArtifacts = existing.every((file) => file.artifact);
+
return (
- <div className="my-1 flex flex-col gap-1.5">
- <span className="text-12 text-[var(--text-secondary)]">
- {t('chat.generatedFiles.title')}
- </span>
- <div className="flex flex-wrap gap-1.5">
+ <div className="my-1 flex flex-col gap-2">
+ {!hasOnlyArtifacts && (
+ <span className="text-12 font-medium text-[var(--text-secondary)]">
+ {t('chat.generatedFiles.title')}
+ </span>
+ )}
+ <div className={cn('flex flex-wrap gap-2', hasArtifacts && 'flex-col')}>
{visible.map((f) => (
<GeneratedFileChip key={f.path} file={f} />
))}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 8d1e08756f..674ee205d7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -3140,6 +3140,10 @@
"name": "Cindy Memory",
"description": "Cross-agent long-term memory for persistent context across sessions"
},
+ "docs": {
+ "name": "Document Toolkit",
+ "description": "Turn content into real files — PDF, Word, Excel, and PowerPoint — and read them back to verify the result. No extra software to install."
+ },
"xdt_helper": {
"name": "Cindy Helper",
"description": "Host capability disclosure — tells agents what tools and models are available"
@@ -7882,7 +7886,10 @@
"generatedFiles": {
"title": "Files created this message",
"showMore": "Show {{count}} more",
- "showLess": "Show less"
+ "showLess": "Show less",
+ "artifactLabel": "Artifact",
+ "formats": { "pdf": "PDF", "docx": "Word", "pptx": "PPT", "xlsx": "Excel" },
+ "summary": { "pages": "{{count}} pages", "slides": "{{count}} slides", "sheets": "{{count}} sheets", "rows": "{{count}} rows", "bytes": "{{count}}" }
},
"turnChanges": {
"title": "Changed {{count}} files",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 103633dbd1..e8c1713fd8 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -3139,6 +3139,10 @@
"name": "Cindy メモリ",
"description": "セッションをまたいでコンテキストを保持する Agent 横断の長期メモリ"
},
+ "docs": {
+ "name": "ドキュメント工房",
+ "description": "内容を実ファイルに — PDF / Word / Excel / PowerPoint を生成し、読み返して仕上がりを確認。追加ソフトのインストールは不要。"
+ },
"xdt_helper": {
"name": "Cindy Helper",
"description": "ホスト機能の開示 — 利用可能なツールとモデルを Agent に伝える"
@@ -7879,7 +7883,10 @@
"generatedFiles": {
"title": "このメッセージで作成されたファイル",
"showMore": "さらに {{count}} 件表示",
- "showLess": "折りたたむ"
+ "showLess": "折りたたむ",
+ "artifactLabel": "成果物",
+ "formats": { "pdf": "PDF", "docx": "Word", "pptx": "PPT", "xlsx": "Excel" },
+ "summary": { "pages": "{{count}} ページ", "slides": "{{count}} 枚のスライド", "sheets": "{{count}} シート", "rows": "{{count}} 行", "bytes": "{{count}}" }
},
"turnChanges": {
"title": "{{count}} ファイルを変更",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 88a557db34..10d836e20a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -3139,6 +3139,10 @@
"name": "Cindy 메모리",
"description": "세션 간 컨텍스트를 유지하는 Agent 공통 장기 메모리"
},
+ "docs": {
+ "name": "문서 공방",
+ "description": "내용을 실제 파일로 — PDF·Word·Excel·PowerPoint 생성과 결과 확인용 읽기. 추가 소프트웨어 설치가 필요 없습니다."
+ },
"xdt_helper": {
"name": "Cindy Helper",
"description": "호스트 기능 공개 — 사용 가능한 도구와 모델을 Agent에 알림"
@@ -7879,7 +7883,10 @@
"generatedFiles": {
"title": "이 메시지에서 생성된 파일",
"showMore": "{{count}}개 더 보기",
- "showLess": "간략히 보기"
+ "showLess": "간략히 보기",
+ "artifactLabel": "산출물",
+ "formats": { "pdf": "PDF", "docx": "Word", "pptx": "PPT", "xlsx": "Excel" },
+ "summary": { "pages": "{{count}}페이지", "slides": "{{count}}개 슬라이드", "sheets": "{{count}}개 시트", "rows": "{{count}}행", "bytes": "{{count}}" }
},
"turnChanges": {
"title": "파일 {{count}}개 변경",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index ac3d304984..78b42685e5 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -3131,6 +3131,10 @@
"name": "Cindy 记忆",
"description": "跨 Agent 的长期记忆,让上下文在任务之间持续"
},
+ "docs": {
+ "name": "文档工坊",
+ "description": "把内容做成真文件 —— PDF、Word、Excel、PPT,并能回读核对产出。不需要另装任何软件。"
+ },
"xdt_helper": {
"name": "Cindy Helper",
"description": "宿主能力自省 —— 告诉 Agent 当前可用的工具与模型"
@@ -7871,7 +7875,10 @@
"generatedFiles": {
"title": "本条消息生成的文件",
"showMore": "显示另外 {{count}} 个",
- "showLess": "收起"
+ "showLess": "收起",
+ "artifactLabel": "成品",
+ "formats": { "pdf": "PDF", "docx": "Word", "pptx": "PPT", "xlsx": "Excel" },
+ "summary": { "pages": "{{count}} 页", "slides": "{{count}} 张幻灯片", "sheets": "{{count}} 个工作表", "rows": "{{count}} 行", "bytes": "{{count}}" }
},
"turnChanges": {
"title": "已更改 {{count}} 个文件",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 9f79074892..7226aa1642 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -3131,6 +3131,10 @@
"name": "Cindy 記憶",
"description": "跨 Agent 的長期記憶,讓上下文在任務之間持續"
},
+ "docs": {
+ "name": "文件工坊",
+ "description": "把內容做成真檔案 —— PDF、Word、Excel、PPT,並能回讀核對產出。不需要另裝任何軟體。"
+ },
"xdt_helper": {
"name": "Cindy Helper",
"description": "宿主能力自省 —— 告訴 Agent 當前可用的工具與模型"
@@ -7870,7 +7874,10 @@
"generatedFiles": {
"title": "本條訊息生成的檔案",
"showMore": "顯示另外 {{count}} 個",
- "showLess": "收起"
+ "showLess": "收起",
+ "artifactLabel": "成品",
+ "formats": { "pdf": "PDF", "docx": "Word", "pptx": "PPT", "xlsx": "Excel" },
+ "summary": { "pages": "{{count}} 頁", "slides": "{{count}} 張投影片", "sheets": "{{count}} 個工作表", "rows": "{{count}} 列", "bytes": "{{count}}" }
},
"turnChanges": {
"title": "已更改 {{count}} 個檔案",
diff --git a/apps/desktop/src/renderer/lib/generatedFiles.ts b/apps/desktop/src/renderer/lib/generatedFiles.ts
index 8d40b83831..7386d31eb8 100644
--- a/apps/desktop/src/renderer/lib/generatedFiles.ts
+++ b/apps/desktop/src/renderer/lib/generatedFiles.ts
@@ -34,12 +34,202 @@ export interface GeneratedFileRef {
* 'command' = 命令文本启发式候选,渲染前还需 mtime 时间窗校验。
*/
source: 'tool' | 'command';
+ /** 文档工具返回的轻量交付信息;普通源码文件没有此字段。 */
+ artifact?: DocumentArtifactMetadata;
+ /** true 仅表示同一 tool_use 有结构化 ok:true 结果,可用本轮 mtime 证明成功覆盖。 */
+ artifactConfirmed?: boolean;
+}
+
+export type DocumentArtifactFormat = 'pdf' | 'docx' | 'pptx' | 'xlsx';
+export type DocumentArtifactSummary = {
+ kind: 'pages' | 'slides' | 'sheets' | 'rows' | 'bytes';
+ value: number;
+};
+
+export type DocumentArtifactPreview =
+ | {
+ kind: 'sheet';
+ /** 只取工具输入中真实存在的前几行、前几列。 */
+ rows: string[][];
+ hasHeader: boolean;
+ }
+ | {
+ kind: 'slide';
+ /** 封面文字来自第一张幻灯片,不构造示例内容。 */
+ title?: string;
+ subtitle?: string;
+ };
+
+export interface DocumentArtifactMetadata {
+ format: DocumentArtifactFormat;
+ title?: string;
+ subtitle?: string;
+ theme?: 'light' | 'dark' | 'navy';
+ cover?: boolean;
+ summary?: DocumentArtifactSummary;
+ preview?: DocumentArtifactPreview;
}
interface ToolUseLike {
role: string;
toolName?: string;
toolInput?: unknown;
+ toolUseId?: string;
+ content?: string;
+}
+
+function documentToolName(toolName: string): string | null {
+ const normalized = toolName.replace(/^mcp__/, 'mcp:').replace(/__/g, ':');
+ const name = normalized.split(':').at(-1) ?? normalized;
+ return /^(make_docx|make_pptx|make_xlsx|render_pdf)$/.test(name) ? name : null;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? (value as Record<string, unknown>)
+ : null;
+}
+
+function parseToolResult(content: string | undefined): Record<string, unknown> | null {
+ if (!content) return null;
+ try {
+ const parsed = JSON.parse(content) as unknown;
+ return asRecord(parsed);
+ } catch {
+ return null;
+ }
+}
+
+function stringField(record: Record<string, unknown> | null, key: string): string | undefined {
+ const value = record?.[key];
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
+}
+
+function previewCellText(value: unknown): string {
+ if (value === null || value === undefined) return '';
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return String(value).slice(0, 48);
+ }
+ const record = asRecord(value);
+ if (record && 'result' in record) return previewCellText(record.result);
+ if (record && 'text' in record) return previewCellText(record.text);
+ return '';
+}
+
+function sheetPreview(input: Record<string, unknown> | null): DocumentArtifactPreview | undefined {
+ const firstSheet = asRecord(Array.isArray(input?.sheets) ? input.sheets[0] : null);
+ if (!firstSheet) return undefined;
+ const header = Array.isArray(firstSheet.header)
+ ? firstSheet.header.slice(0, 3).map(previewCellText)
+ : [];
+ const bodyRows = Array.isArray(firstSheet.rows)
+ ? firstSheet.rows
+ .slice(0, header.length > 0 ? 3 : 4)
+ .filter(Array.isArray)
+ .map((row) => row.slice(0, 3).map(previewCellText))
+ : [];
+ const rows = header.length > 0 ? [header, ...bodyRows] : bodyRows;
+ return rows.length > 0 ? { kind: 'sheet', rows, hasHeader: header.length > 0 } : undefined;
+}
+
+export function extractDocumentArtifactMetadata(
+ toolName: string,
+ input: unknown,
+ resultContent?: string,
+): DocumentArtifactMetadata | undefined {
+ const name = documentToolName(toolName);
+ if (!name) return undefined;
+ const inputRecord = asRecord(input);
+ const result = parseToolResult(resultContent);
+ // 旧消息可能没有保存 tool_result,仍允许只按输入重建轻量卡片;但只要当前
+ // 消息明确带了结果,就必须由 ok:true 证明生成成功。解析失败和 ok:false 都
+ // 不能把同轮预先存在的同名文件冒充成这次成功交付的作品。
+ if (resultContent !== undefined && result?.ok !== true) return undefined;
+ const resultArtifact = asRecord(result?.artifact);
+ const format =
+ name === 'make_docx'
+ ? 'docx'
+ : name === 'make_pptx'
+ ? 'pptx'
+ : name === 'make_xlsx'
+ ? 'xlsx'
+ : 'pdf';
+ const theme =
+ stringField(resultArtifact, 'theme') ??
+ stringField(result, 'theme') ??
+ stringField(inputRecord, 'theme');
+ const validTheme = theme === 'light' || theme === 'dark' || theme === 'navy' ? theme : undefined;
+ const title =
+ stringField(resultArtifact, 'title') ??
+ stringField(result, 'title') ??
+ stringField(inputRecord, 'title') ??
+ (name === 'make_pptx'
+ ? stringField(
+ asRecord(Array.isArray(inputRecord?.slides) ? inputRecord.slides[0] : null),
+ 'title',
+ )
+ : name === 'make_xlsx'
+ ? stringField(
+ asRecord(Array.isArray(inputRecord?.sheets) ? inputRecord.sheets[0] : null),
+ 'name',
+ )
+ : undefined);
+ const subtitle =
+ stringField(resultArtifact, 'subtitle') ??
+ stringField(result, 'subtitle') ??
+ stringField(inputRecord, 'subtitle');
+ const rawSummary = asRecord(resultArtifact?.summary) ?? asRecord(result?.summary);
+ const summaryKind = rawSummary?.kind;
+ const summaryValue = rawSummary?.value;
+ const summary =
+ (summaryKind === 'pages' ||
+ summaryKind === 'slides' ||
+ summaryKind === 'sheets' ||
+ summaryKind === 'rows' ||
+ summaryKind === 'bytes') &&
+ typeof summaryValue === 'number' &&
+ Number.isFinite(summaryValue)
+ ? { kind: summaryKind, value: summaryValue }
+ : name === 'make_pptx' && Array.isArray(inputRecord?.slides)
+ ? { kind: 'slides' as const, value: inputRecord.slides.length }
+ : name === 'make_xlsx' && Array.isArray(inputRecord?.sheets)
+ ? { kind: 'sheets' as const, value: inputRecord.sheets.length }
+ : (name === 'make_docx' || name === 'render_pdf') &&
+ typeof result?.bytes === 'number' &&
+ Number.isFinite(result.bytes)
+ ? { kind: 'bytes' as const, value: result.bytes }
+ : undefined;
+ const firstSlide =
+ name === 'make_pptx'
+ ? asRecord(Array.isArray(inputRecord?.slides) ? inputRecord.slides[0] : null)
+ : null;
+ const preview =
+ name === 'make_xlsx'
+ ? sheetPreview(inputRecord)
+ : name === 'make_pptx'
+ ? {
+ kind: 'slide' as const,
+ ...(stringField(firstSlide, 'title')
+ ? { title: stringField(firstSlide, 'title') }
+ : {}),
+ ...(stringField(firstSlide, 'subtitle')
+ ? { subtitle: stringField(firstSlide, 'subtitle') }
+ : {}),
+ }
+ : undefined;
+ return {
+ format,
+ ...(title ? { title } : {}),
+ ...(subtitle ? { subtitle } : {}),
+ ...(validTheme ? { theme: validTheme } : {}),
+ ...(typeof resultArtifact?.cover === 'boolean'
+ ? { cover: resultArtifact.cover }
+ : typeof inputRecord?.cover === 'boolean'
+ ? { cover: inputRecord.cover }
+ : {}),
+ ...(summary ? { summary: summary as DocumentArtifactSummary } : {}),
+ ...(preview ? { preview } : {}),
+ };
}
/**
@@ -504,6 +694,16 @@ export function collectGeneratedFiles(
messages: readonly ToolUseLike[],
workingDir: string,
): GeneratedFileRef[] {
+ const resultByToolUseId = new Map<string, string>();
+ for (const message of messages) {
+ if (
+ message.role === 'tool_result' &&
+ message.toolUseId &&
+ typeof message.content === 'string'
+ ) {
+ resultByToolUseId.set(message.toolUseId, message.content);
+ }
+ }
// 第一遍:收「本轮被文件工具**修改**过」的路径。它们是编辑不是新建,命令文本
// 里再出现也不算产物候选——否则跑测试 / 构建命令引用刚编辑过的源码文件
// (`vitest run src/x.test.ts`)会被 mtime 窗口放行,把编码会话的改动文件全
@@ -544,6 +744,32 @@ export function collectGeneratedFiles(
for (const rawPath of createdPathsFromToolUse(toolName, msg.toolInput)) {
addPath(rawPath, 'tool');
}
+ const resultContent = msg.toolUseId ? resultByToolUseId.get(msg.toolUseId) : undefined;
+ const artifact = extractDocumentArtifactMetadata(toolName, msg.toolInput, resultContent);
+ if (artifact) {
+ const outputPath =
+ typeof asRecord(msg.toolInput)?.outPath === 'string'
+ ? (asRecord(msg.toolInput)!.outPath as string)
+ : undefined;
+ if (outputPath) {
+ const abs = canonicalizeWindowsShape(resolveToolFilePath(outputPath, workingDir));
+ const key = dedupeKeyForPath(abs);
+ const existing = byKey.get(key);
+ const artifactConfirmed = parseToolResult(resultContent)?.ok === true;
+ if (existing) {
+ existing.artifact = artifact;
+ if (artifactConfirmed) existing.artifactConfirmed = true;
+ } else {
+ byKey.set(key, {
+ path: abs,
+ name: basename(abs),
+ source: 'tool',
+ artifact,
+ ...(artifactConfirmed ? { artifactConfirmed: true } : {}),
+ });
+ }
+ }
+ }
const descriptor = describeToolUse(toolName, msg.toolInput);
if (descriptor.kind === 'command' && descriptor.command) {
for (const rawPath of extractCommandOutputPathCandidates(descriptor.command)) {
diff --git a/apps/desktop/vite.review-pdf-process.config.ts b/apps/desktop/vite.review-pdf-process.config.ts
index 1b6cccc9d6..f237f7f1a7 100644
--- a/apps/desktop/vite.review-pdf-process.config.ts
+++ b/apps/desktop/vite.review-pdf-process.config.ts
@@ -7,6 +7,9 @@ export default defineConfig({
},
build: {
rollupOptions: {
+ // Keep the native canvas binding as a packaged runtime dependency. Trying
+ // to CommonJS-transform it makes Forge silently omit this utility entry.
+ external: ['@napi-rs/canvas'],
output: {
inlineDynamicImports: true,
},
diff --git a/docs/product-rules/README.md b/docs/product-rules/README.md
index 3676903e2f..8e22792241 100644
--- a/docs/product-rules/README.md
+++ b/docs/product-rules/README.md
@@ -19,5 +19,7 @@
身份命名与默认值方向、区域相关 UI 标注与对外口径。
- [`task-and-conversation-naming.md`](task-and-conversation-naming.md):`session` 的中文
叫「任务」,任务 / 对话 / 消息的分层定义与判定规则,以及「任务」与 `task` 的歧义处理。
+- [`document-workshop-quality.md`](document-workshop-quality.md):无插件文档基础能力的
+ HTML-first 工序、四格式统一视觉语言、Session 作品卡和插件增强层边界。
- [`session-runtime-control.md`](session-runtime-control.md):Agent 调整任务模型、来源、
推理强度与 Fast 的统一控制面,baseline/effective/pending 状态和自动降级边界。
diff --git a/docs/product-rules/document-workshop-quality.md b/docs/product-rules/document-workshop-quality.md
new file mode 100644
index 0000000000..768bbe6940
--- /dev/null
+++ b/docs/product-rules/document-workshop-quality.md
@@ -0,0 +1,50 @@
+# 文档工坊基础能力质量契约
+
+> 这份规则约束 Cindy 内置的 PDF、Word、PPT、Excel 文档能力。它描述的是基础产品应该稳定做到的事,不要求用户安装插件,也不把排版责任推回给用户。
+
+## 1. 基础工序:HTML-first,但不把 HTML 当成最终交付
+
+当用户要一份正式文档时,Agent 默认先在脑中或临时内容里形成一份**自包含 HTML 初稿**:样式内联,图片使用 data URI、可访问的公网地址或任务目录内的本地资源,页面有明确的封面、层级、留白和内容标题。HTML 是排版草图和跨格式的共同视觉参考,不是要求用户看懂的中间产物。
+
+随后按交付格式选择顶层工具:`render_pdf`、`make_docx`、`make_pptx`、`make_xlsx`。工具描述中的版式工序优先于任何外部 skill;六个文档工具直接暴露,不能再教 Agent 通过已下线的 `list_tools` / `call_tool` 二级入口分派。
+
+落地后必须做结构自检:PDF 用 `inspect_pdf`;Word、PPT、Excel 至少检查文件存在、尺寸/数量和关键内容是否落盘。发现失败时先回看原始 XML 或结构数据,再判断是否真的缺失,不能把目检台的折叠、域、编号递推或资源限制误判成生成失败。
+
+## 2. 四种格式的统一视觉语言
+
+四种格式共享三套受控主题(`light`、`dark`、`navy`),共享以下设计骨架:
+
+- 封面:主题色强调带或色块、清晰主标题、可选副标题/来源/日期;不把标题挤在页顶,也不让封面只剩一片空白。
+- 内容页:标题层级稳定,正文有足够行距和留白,强调色只承担导航和重点,不用满屏彩色装饰。
+- 内容标题:封面标题、章节标题、表头/页眉和作品卡标题使用同一套语义角色;格式可以不同,但不能各自发明一套视觉身份。
+- 交付元数据:格式、主题、标题/副标题和数量(页/幻灯片/工作表/行列)可被上层 UI 消费。它们只描述生成结果,不代表视觉复核或用户验收。
+
+格式差异是语义差异,不是随意差异:PDF 重视打印尺寸和分页,Word 重视可编辑层级和表格,PPT 重视单页信息密度和演讲节奏,Excel 重视扫描、筛选、冻结和汇总识别。
+
+## 3. Session 作品卡
+
+作品卡是 Cindy 内置能力,不是插件专属能力。它不是普通文件 chip 的放大版,而是交付结果的轻量封面:
+
+- 左侧使用类型化封面(PDF / Word / PPT / Excel 各有稳定字标和主题色);
+- 中间显示标题,标题缺失时回退到文件名;副标题显示格式或主题,避免把内部路径当主信息;
+- 下方显示页数、幻灯片数、工作表/行数或文件大小等可读摘要;
+- 作品卡只显示真实的文件与生成摘要;工具返回的 warning 仍留在工具结果中,不转换成“待视觉复核”“已检查”或其它验收状态;
+- 点击仍沿用文件正文的打开策略,右键仍保留复制、定位和打开方式;
+- Light 与 Dark 都必须使用语义 token,不写仅适配一个模式的固定颜色;
+- 多个产物使用统一卡片骨架,不能因为格式不同而退化成四套互不相干的组件。
+
+作品卡只展示真实存在且属于当前 turn 的文件。无法确认归属或远端 stat 失败时宁可不展示,不显示一个用户点不开的“完成品”。
+
+## 4. 内置能力与插件边界
+
+内置能力负责“任何会话都能完成”:顶层工具、受控主题、HTML-first 排版契约、格式落地、结构自检和 Session 作品卡。它不能依赖插件是否安装。
+
+插件未来负责“更快、更傻瓜、更有选择”:模板库、报表/简历/周报等场景卡、模板选择面板、成品记录和跨格式编排引导。插件可以调用内置工具,但不能复制一份与工具描述或本规则冲突的排版说明,也不能成为基础文档能力的唯一入口。
+
+文件生成成功、结构检查通过、视觉复核通过、用户接受交付是四个不同事件。本期没有用户接受、拒绝、批注或侧栏审阅状态,也不会在作品卡中模拟这些状态。`inspect_pdf` 的 `verdict` 只属于该工具的一次结构检查,不会自动回写作品卡。
+
+## 5. 失败与质量门槛
+
+工具失败返回稳定的错误码和人话 hint:说明发生了什么、最可能的原因、下一步应该改哪个输入。原始 `message` 只作为诊断字段保留给日志/审计,不作为默认用户文案直接倾倒到对话里。
+
+提交前必须覆盖相关单测、涉及 package 的 typecheck、i18n 与 glossary 门禁;不能启动 Electron、dev server、CDP,也不能用 LibreOffice、pandoc 或外部 Office 工具假装完成目检。PDF 若无法在当前环境实机视觉验证,交付说明必须明确“结构已测、视觉未实机验证”。
diff --git a/packages/lizi-mcps/package.json b/packages/lizi-mcps/package.json
index 505d81eee4..6539ff75fa 100644
--- a/packages/lizi-mcps/package.json
+++ b/packages/lizi-mcps/package.json
@@ -19,20 +19,26 @@
},
"license": "Apache-2.0",
"dependencies": {
- "@googleapis/calendar": "^15.0.0",
- "@googleapis/drive": "^20.2.0",
- "@googleapis/gmail": "^17.0.0",
- "@googleapis/sheets": "^13.0.1",
"@cindy/browser-control-runtime": "workspace:*",
"@cindy/github-client": "workspace:*",
"@cindy/gitlab-client": "workspace:*",
+ "@cindy/ios-simulator-runtime": "workspace:*",
"@cindy/maker-core": "workspace:*",
"@cindy/maker-scheduler": "workspace:*",
"@cindy/maker-shared": "workspace:*",
- "@cindy/ios-simulator-runtime": "workspace:*",
+ "@googleapis/calendar": "^15.0.0",
+ "@googleapis/drive": "^20.2.0",
+ "@googleapis/gmail": "^17.0.0",
+ "@googleapis/sheets": "^13.0.1",
"@modelcontextprotocol/sdk": "^1.29.0",
+ "docx": "^9.7.1",
+ "entities": "^6.0.1",
"eventsource-parser": "^3.0.6",
+ "exceljs": "^4.4.0",
"google-auth-library": "^10.6.2",
+ "jszip": "^3.10.1",
+ "marked": "^16.4.2",
+ "pptxgenjs": "^4.0.1",
"sharp": "^0.35.0",
"zod": "^4.0.0"
},
diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsCsv.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsCsv.test.ts
new file mode 100644
index 0000000000..934c0b4f12
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/cindyDocsCsv.test.ts
@@ -0,0 +1,119 @@
+/**
+ * cindy-docs/csv.ts 的 RFC 4180 口径测试。
+ *
+ * 这些用例就是解析口径本身:改了实现就必须来这里说明改的是哪一条,
+ * 而不是把断言改成新行为。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ delimiterForExtension,
+ parseDelimited,
+ parseDelimitedWindow,
+} from '../cindy-docs/csv.js';
+
+const csv = (text: string) => parseDelimited(text, { delimiter: ',' });
+
+describe('parseDelimited', () => {
+ it('切出基本的行列', () => {
+ expect(csv('a,b,c\n1,2,3')).toEqual([
+ ['a', 'b', 'c'],
+ ['1', '2', '3'],
+ ]);
+ });
+
+ it('引号字段里的分隔符不切分', () => {
+ expect(csv('a,"b,c",d')).toEqual([['a', 'b,c', 'd']]);
+ });
+
+ it('两个连续引号转义成一个引号', () => {
+ expect(csv('"say ""hi""",x')).toEqual([['say "hi"', 'x']]);
+ });
+
+ it('引号字段里可以跨行', () => {
+ expect(csv('a,"line1\nline2",c')).toEqual([['a', 'line1\nline2', 'c']]);
+ });
+
+ it('CRLF / LF / 裸 CR 都算一次换行', () => {
+ expect(csv('a\r\nb\nc\rd')).toEqual([['a'], ['b'], ['c'], ['d']]);
+ });
+
+ it('剥掉 UTF-8 BOM,避免污染第一列表头', () => {
+ expect(csv('区域,收入')).toEqual([['区域', '收入']]);
+ });
+
+ it('结尾换行不产生额外空行', () => {
+ expect(csv('a,b\n1,2\n')).toEqual([
+ ['a', 'b'],
+ ['1', '2'],
+ ]);
+ });
+
+ it('保留换行终止的显式空记录,但不把单个结尾换行算成数据', () => {
+ expect(csv('a\n\n')).toEqual([['a'], ['']]);
+ expect(csv('a\n')).toEqual([['a']]);
+ });
+
+ it('空文本返回零行', () => {
+ expect(csv('')).toEqual([]);
+ });
+
+ it('字段中间的引号按普通字符处理(与 Excel 一致)', () => {
+ expect(csv('a"b,c')).toEqual([['a"b', 'c']]);
+ });
+
+ it('未闭合引号按读到文件尾收尾,不抛错', () => {
+ expect(csv('a,"unterminated')).toEqual([['a', 'unterminated']]);
+ });
+
+ it('保留空字段', () => {
+ expect(csv('a,,c')).toEqual([['a', '', 'c']]);
+ });
+
+ it('保留文件末尾没有换行的显式空记录', () => {
+ expect(csv('""')).toEqual([['']]);
+ expect(csv('header\n""')).toEqual([['header'], ['']]);
+ });
+
+ it('tsv 用制表符切分', () => {
+ expect(parseDelimited('a\tb\n1\t2', { delimiter: '\t' })).toEqual([
+ ['a', 'b'],
+ ['1', '2'],
+ ]);
+ });
+});
+
+describe('parseDelimitedWindow', () => {
+ it('只保留请求窗口,但仍返回准确总行数', () => {
+ const text = Array.from({ length: 10_000 }, (_, i) => `${i},value-${i}`).join('\n');
+ expect(
+ parseDelimitedWindow(text, { delimiter: ',', startRow: 5_001, maxRows: 2 }),
+ ).toEqual({
+ rows: [
+ ['5000', 'value-5000'],
+ ['5001', 'value-5001'],
+ ],
+ totalRows: 10_000,
+ });
+ });
+
+ it('分页时仍把引号内换行视为同一逻辑行', () => {
+ expect(
+ parseDelimitedWindow('head,note\nfirst,"line1\nline2"\nlast,done\n', {
+ delimiter: ',',
+ startRow: 2,
+ maxRows: 1,
+ }),
+ ).toEqual({ rows: [['first', 'line1\nline2']], totalRows: 3 });
+ });
+});
+
+describe('delimiterForExtension', () => {
+ it('tsv / tab 用制表符,其余用逗号', () => {
+ expect(delimiterForExtension('.tsv')).toBe('\t');
+ expect(delimiterForExtension('.TAB')).toBe('\t');
+ expect(delimiterForExtension('.csv')).toBe(',');
+ expect(delimiterForExtension('.txt')).toBe(',');
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsDefaults.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsDefaults.test.ts
new file mode 100644
index 0000000000..3b141f7c24
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/cindyDocsDefaults.test.ts
@@ -0,0 +1,743 @@
+/**
+ * cindy_docs 美观默认值:PPT 母版版式、Word 封面/标题层级/表格、Excel 色带/
+ * 斑马纹/数字格式、PDF 无样式 HTML 套模板。真文件往返,不起 Electron。
+ */
+
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import ExcelJS from 'exceljs';
+import JSZip from 'jszip';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { createCindyDocsMcpServer } from '../cindy_docsMcpServer.js';
+import { columnPercents } from '../cindy-docs/docxStyles.js';
+import {
+ assertXlsxAggregateBounds,
+ inferNumberFormat,
+ isSummaryRow,
+} from '../cindy-docs/make_xlsx.js';
+import {
+ PPTX_LAYOUT_IDS,
+ PPTX_MAX_IMAGE_BYTES,
+ PPTX_MAX_TOTAL_IMAGE_BYTES,
+ PPTX_THEMES,
+} from '../cindy-docs/make_pptx.js';
+import { layoutSlots, SLIDE_H, SLIDE_W } from '../cindy-docs/pptxMasters.js';
+import { applyReportTemplate, extractHtmlTitle, htmlLooksUnstyled } from '../cindy-docs/pdfTemplate.js';
+import { DOCS_THEMES, formatDocsDate, themeToArgb } from '../cindy-docs/themes.js';
+import type {
+ DocsMcpDeps,
+ DocsMcpSessionCtx,
+ DocsPdfRenderInput,
+ WriteDocsOutputFn,
+} from '../cindy-docs/types.js';
+
+let workdir: string;
+const created: string[] = [];
+
+beforeEach(async () => {
+ workdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-defaults-'));
+ created.push(workdir);
+});
+
+afterEach(async () => {
+ while (created.length > 0) {
+ const dir = created.pop()!;
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
+ }
+});
+
+function sessionCtx(overrides: Partial<DocsMcpSessionCtx> = {}): DocsMcpSessionCtx {
+ return {
+ agentKind: 'claude-code',
+ workingDir: workdir,
+ sessionId: 'sess-defaults',
+ ...overrides,
+ };
+}
+
+async function connect(deps: DocsMcpDeps = {}, ctx = sessionCtx()) {
+ const server = createCindyDocsMcpServer({ writeDocsOutput: testWriter, ...deps }, ctx);
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'docs-defaults-client', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ return client;
+}
+
+const testWriter: WriteDocsOutputFn = async ({ path: outputPath, data, overwrite }) => {
+ await fs.writeFile(outputPath, data, { flag: overwrite ? 'w' : 'wx' });
+};
+
+function payload(result: unknown): Record<string, unknown> {
+ const content = (result as { content: Array<{ text: string }> }).content;
+ return JSON.parse(content[0]!.text) as Record<string, unknown>;
+}
+
+async function callTool(
+ client: Client,
+ name: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ // 六个文档工具是顶层直接注册的,不再经 call_tool 二级分派(2026-08-21 改)。
+ return payload(await client.callTool({ name, arguments: args }));
+}
+
+async function unzip(file: string, entry: string): Promise<string> {
+ const zip = await JSZip.loadAsync(await fs.readFile(file));
+ const found = zip.file(entry);
+ if (!found) throw new Error(`missing ${entry}; have ${Object.keys(zip.files).join(',')}`);
+ return found.async('string');
+}
+
+async function unzipAll(file: string, predicate: (name: string) => boolean): Promise<string> {
+ const zip = await JSZip.loadAsync(await fs.readFile(file));
+ const parts: string[] = [];
+ for (const name of Object.keys(zip.files)) {
+ if (!predicate(name)) continue;
+ const found = zip.file(name);
+ if (found) parts.push(await found.async('string'));
+ }
+ return parts.join('\n');
+}
+
+describe('PPT 母版版式', () => {
+ it('layoutSlots 封面/分节/内容页几何互不相同,有图时正文收窄', () => {
+ const cover = layoutSlots('cover', { hasImage: false, hasSubtitle: true });
+ const section = layoutSlots('section', {
+ hasImage: false,
+ hasSubtitle: false,
+ });
+ const content = layoutSlots('content', {
+ hasImage: false,
+ hasSubtitle: false,
+ });
+ const split = layoutSlots('content', {
+ hasImage: true,
+ hasSubtitle: false,
+ });
+
+ expect(cover.title.fontSize).toBeGreaterThan(section.title.fontSize);
+ expect(section.title.fontSize).toBeGreaterThan(content.title.fontSize);
+ expect(content.accentLine).toBeDefined();
+ // 封面也有强调短线了(2026-08-22):原来封面除了一根细竖条什么都没有,
+ // 目检下来就是「白底加几行字」。
+ expect(cover.accentLine).toBeDefined();
+ expect(split.body.w).toBeLessThan(content.body.w);
+ expect(split.image).toBeDefined();
+ });
+
+ it('六套版式写入母版,结构化对比/指标/大图页写进真文件', async () => {
+ await fs.writeFile(
+ path.join(workdir, 'chart.png'),
+ Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ 'base64',
+ ),
+ );
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ title: 'Q3 经营回顾',
+ theme: 'navy',
+ slides: [
+ {
+ title: 'Q3 经营回顾',
+ layout: 'cover',
+ subtitle: '华东区 · 内部汇报',
+ },
+ { title: '增长从哪里来', layout: 'section' },
+ {
+ title: '结论先行',
+ layout: 'content',
+ bullets: ['续约拉动', '新品尚未放量'],
+ },
+ {
+ title: '两条路径各有取舍',
+ layout: 'comparison',
+ columns: [
+ { title: '无插件基础版', bullets: ['随时可用', '结构稳定'] },
+ { title: '模板增强版', bullets: ['场景更细', '选择更简单'] },
+ ],
+ },
+ {
+ title: '关键目标一眼读完',
+ layout: 'metrics',
+ metrics: [
+ { value: '98%', label: '生成成功率', detail: '标准输入口径' },
+ { value: 4, label: '核心格式' },
+ ],
+ },
+ {
+ title: '让图承担主体',
+ layout: 'image',
+ imagePath: 'chart.png',
+ body: '示意图 · 数据口径见备注',
+ },
+ ],
+ outPath: 'deck.pptx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.theme).toBe('navy');
+ expect(result.layouts).toEqual([
+ 'cover',
+ 'section',
+ 'content',
+ 'comparison',
+ 'metrics',
+ 'image',
+ ]);
+ expect(result.footer).toBe(true);
+
+ const layouts = await unzipAll(
+ result.path as string,
+ (name) => name.startsWith('ppt/slideLayouts/') && name.endsWith('.xml'),
+ );
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.cover);
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.section);
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.content);
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.comparison);
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.metrics);
+ expect(layouts).toContain(PPTX_LAYOUT_IDS.image);
+
+ const slide1 = await unzip(result.path as string, 'ppt/slides/slide1.xml');
+ expect(slide1).toContain('Q3 经营回顾');
+ expect(slide1).toContain('华东区');
+ expect(slide1).toContain(PPTX_THEMES.navy.background);
+ // 封面标题字号 44pt = DrawingML 4400(2026-08-22 从 40pt 放大:封面通栏只有
+ // 一行字,40pt 在实机目检里显得又小又散)。
+ expect(slide1).toContain('4400');
+
+ expect(layouts).toContain(PPTX_THEMES.navy.accent);
+ expect(layouts).toContain('Q3 经营回顾');
+ // pptxgenjs 把页码写成 type="slidenum" 字段;母版上的 hf sldNum="0" 只是关闭位,不算。
+ expect(layouts).toMatch(/type="slidenum"/);
+
+ const comparison = await unzip(result.path as string, 'ppt/slides/slide4.xml');
+ expect(comparison).toContain('无插件基础版');
+ expect(comparison).toContain('模板增强版');
+ const metrics = await unzip(result.path as string, 'ppt/slides/slide5.xml');
+ expect(metrics).toContain('98%');
+ expect(metrics).toContain('生成成功率');
+ const image = await unzip(result.path as string, 'ppt/slides/slide6.xml');
+ expect(image).toContain('示意图');
+ expect(image).toContain('r:embed');
+ });
+
+ it('footer:false 时母版不登记页码', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ footer: false,
+ slides: [{ title: '只有内容', layout: 'content', bullets: ['一条'] }],
+ outPath: 'no-footer.pptx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.footer).toBe(false);
+ const layouts = await unzipAll(
+ result.path as string,
+ (name) => name.startsWith('ppt/slideLayouts/') && name.endsWith('.xml'),
+ );
+ expect(layouts).not.toMatch(/type="slidenum"/);
+ });
+
+ it('图片在交给 pptxgenjs 前受单文件和累计字节上限约束', async () => {
+ const client = await connect();
+ const tooLarge = path.join(workdir, 'too-large.png');
+ const handle = await fs.open(tooLarge, 'w');
+ await handle.truncate(PPTX_MAX_IMAGE_BYTES + 1);
+ await handle.close();
+
+ const single = await callTool(client, 'make_pptx', {
+ slides: [{ title: '超大图片', imagePath: 'too-large.png' }],
+ outPath: 'single-limit.pptx',
+ });
+ expect(single.errorCode).toBe('FILE_TOO_LARGE');
+ await expect(fs.stat(path.join(workdir, 'single-limit.pptx'))).rejects.toThrow();
+
+ const repeated = path.join(workdir, 'repeated.png');
+ const repeatedBytes = Math.floor(PPTX_MAX_TOTAL_IMAGE_BYTES / 3) + 1;
+ const repeatedHandle = await fs.open(repeated, 'w');
+ const validPng = Buffer.from(
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ 'base64',
+ );
+ await repeatedHandle.write(validPng, 0, validPng.length, 0);
+ await repeatedHandle.truncate(repeatedBytes);
+ await repeatedHandle.close();
+ const aggregate = await callTool(client, 'make_pptx', {
+ slides: [1, 2, 3, 4].map((n) => ({
+ title: `重复 ${n}`,
+ imagePath: 'repeated.png',
+ })),
+ outPath: 'aggregate-limit.pptx',
+ });
+ expect(aggregate.errorCode).toBe('FILE_TOO_LARGE');
+ await expect(fs.stat(path.join(workdir, 'aggregate-limit.pptx'))).rejects.toThrow();
+ });
+});
+
+describe('Word 封面 / 标题层级 / 表格', () => {
+ it('给了 title 就出独立封面,标题层级和表格色带写进 styles / 表格 XML', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ title: '季度经营回顾',
+ subtitle: '内部稿',
+ theme: 'navy',
+ markdown: [
+ '# 摘要',
+ '',
+ '正文一段。',
+ '',
+ '## 明细',
+ '',
+ '| 区域 | 收入 |',
+ '|---|--:|',
+ '| 华东 | 1200 |',
+ '| 华南 | 860 |',
+ ].join('\n'),
+ outPath: 'report.docx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.cover).toBe(true);
+ expect(result.theme).toBe('navy');
+
+ const documentXml = await unzip(result.path as string, 'word/document.xml');
+ expect(documentXml).toContain('季度经营回顾');
+ expect(documentXml).toContain('内部稿');
+ expect(documentXml).toContain('摘要');
+ // 封面是独立节,后面正文另起一节
+ expect(documentXml.match(/<w:sectPr[\s>]/g)?.length ?? 0).toBeGreaterThanOrEqual(2);
+
+ /*
+ 日期在**封面页脚**里,不在正文流里。原来它跟在标题下面,靠段间距悬在半空,
+ 标题一长就跟着往下挪、位置永远不稳;现在沉到页脚才真的贴着页底。
+ 这里断言的是位置,不只是「出现过」—— 只查 document.xml 含不含日期,
+ 恰恰是搬回正文流也能通过的那种弱断言。
+ */
+ expect(documentXml).not.toContain(formatDocsDate());
+ const coverFooter = await unzip(result.path as string, 'word/footer1.xml');
+ expect(coverFooter).toContain(formatDocsDate());
+
+ // 封面顶部那条实心强调带:用段落底纹画,不是边框 —— 边框只有线,填不出面积。
+ expect(documentXml).toContain(`<w:shd w:fill="${DOCS_THEMES.navy.accent}"`);
+
+ const stylesXml = await unzip(result.path as string, 'word/styles.xml');
+ expect(stylesXml).toContain('Heading1');
+ expect(stylesXml).toContain('Heading2');
+ expect(stylesXml).toContain(DOCS_THEMES.navy.title);
+ expect(stylesXml).toContain(DOCS_THEMES.navy.accent);
+
+ // 表头色带用强调色,斑马纹落在第二行数据
+ expect(documentXml).toContain(DOCS_THEMES.navy.accent);
+ expect(documentXml).toContain(DOCS_THEMES.navy.zebra);
+ });
+
+ it('cover:false 时 title 仍作正文标题段,不另起封面节', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ title: '无封面',
+ cover: false,
+ markdown: '只有一段。',
+ outPath: 'plain.docx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.cover).toBe(false);
+ const documentXml = await unzip(result.path as string, 'word/document.xml');
+ expect(documentXml).toContain('无封面');
+ expect(documentXml.match(/<w:sectPr[\s>]/g)?.length ?? 0).toBe(1);
+ });
+
+ it('dark 主题把页面底色写进 Word 文档,与浅色正文配套', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ theme: 'dark',
+ title: '深色报告',
+ markdown: '# 结论\n\n正文。',
+ outPath: 'dark.docx',
+ });
+ expect(result.ok).toBe(true);
+ const documentXml = await unzip(result.path as string, 'word/document.xml');
+ expect(documentXml).toContain(`<w:background w:color="${DOCS_THEMES.dark.background}"`);
+ const stylesXml = await unzip(result.path as string, 'word/styles.xml');
+ expect(stylesXml).toContain(DOCS_THEMES.dark.body);
+ expect(stylesXml).toContain(DOCS_THEMES.dark.title);
+ });
+});
+
+describe('Excel 表头色带 / 斑马纹 / 数字格式', () => {
+ it('在 ExcelJS 前限制工作簿总单元格和总文本量', () => {
+ const wideRow = Array.from({ length: 256 }, () => null);
+ expect(() =>
+ assertXlsxAggregateBounds([
+ { name: 'Too many cells', rows: Array.from({ length: 391 }, () => wideRow) },
+ ]),
+ ).toThrow(/100000 个单元格/);
+
+ const longText = 'x'.repeat(32_767);
+ expect(() =>
+ assertXlsxAggregateBounds([
+ { name: 'Too much text', rows: Array.from({ length: 257 }, () => [longText]) },
+ ]),
+ ).toThrow(/文本合计超过 8 MB/);
+ });
+
+ it('表头用强调色、奇数数据行打斑马纹、整数列带千分位', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ theme: 'navy',
+ sheets: [
+ {
+ name: '明细',
+ header: ['区域', '收入', '占比'],
+ rows: [
+ ['华东', 1200, 0.18],
+ ['华南', 860, 0.12],
+ ['华北', 2040, 0.3],
+ ],
+ },
+ ],
+ outPath: 'pretty.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.theme).toBe('navy');
+
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ const ws = wb.getWorksheet('明细')!;
+ const headerFill = ws.getRow(1).getCell(1).fill as {
+ fgColor?: { argb?: string };
+ };
+ expect(headerFill.fgColor?.argb).toBe(themeToArgb(DOCS_THEMES.navy.accent));
+ expect(ws.getRow(1).font?.color?.argb).toBe(themeToArgb(DOCS_THEMES.navy.accentOn));
+
+ const zebra = ws.getRow(3).getCell(1).fill as {
+ fgColor?: { argb?: string };
+ };
+ expect(zebra.fgColor?.argb).toBe(themeToArgb(DOCS_THEMES.navy.zebra));
+ const even = ws.getRow(2).getCell(1).fill as { fgColor?: { argb?: string } } | undefined;
+ expect(even?.fgColor?.argb ?? '').not.toBe(themeToArgb(DOCS_THEMES.navy.zebra));
+
+ expect(ws.getColumn(2).numFmt).toBe('#,##0');
+ expect(ws.getColumn(3).numFmt).toMatch(/%/);
+ });
+
+ it('zebra:false 时不打斑马纹', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ zebra: false,
+ sheets: [{ name: 'S', header: ['a'], rows: [[1], [2]] }],
+ outPath: 'plain.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ const fill = wb.getWorksheet('S')!.getRow(3).getCell(1).fill as
+ { fgColor?: { argb?: string } } | undefined;
+ expect(fill?.fgColor?.argb ?? '').not.toBe(themeToArgb(DOCS_THEMES.light.zebra));
+ });
+
+ it('dark 主题为全部正文格设置深色底与浅色字,斑马行只覆盖底色', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ theme: 'dark',
+ sheets: [
+ {
+ name: 'Dark',
+ header: ['项目', '值', '备注'],
+ rows: [['A', 1], ['B']],
+ },
+ ],
+ outPath: 'dark.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ const ws = wb.getWorksheet('Dark')!;
+ const row2 = ws.getCell('A2');
+ const row3 = ws.getCell('A3');
+ expect((row2.fill as { fgColor?: { argb?: string } }).fgColor?.argb).toBe(
+ themeToArgb(DOCS_THEMES.dark.background),
+ );
+ expect((row3.fill as { fgColor?: { argb?: string } }).fgColor?.argb).toBe(
+ themeToArgb(DOCS_THEMES.dark.zebra),
+ );
+ expect(row2.font.color?.argb).toBe(themeToArgb(DOCS_THEMES.dark.body));
+ expect(row3.font.color?.argb).toBe(themeToArgb(DOCS_THEMES.dark.body));
+ const row2Tail = ws.getCell('C2');
+ const row3Tail = ws.getCell('C3');
+ expect((row2Tail.fill as { fgColor?: { argb?: string } }).fgColor?.argb).toBe(
+ themeToArgb(DOCS_THEMES.dark.background),
+ );
+ expect((row3Tail.fill as { fgColor?: { argb?: string } }).fgColor?.argb).toBe(
+ themeToArgb(DOCS_THEMES.dark.zebra),
+ );
+ expect(row2Tail.font.color?.argb).toBe(themeToArgb(DOCS_THEMES.dark.body));
+ expect(row3Tail.font.color?.argb).toBe(themeToArgb(DOCS_THEMES.dark.body));
+ });
+});
+
+describe('PDF 无样式 HTML 套报告模板', () => {
+ it('没有非空标题时让作品卡回退到文件名', () => {
+ expect(extractHtmlTitle('<p>正文</p>')).toBeUndefined();
+ expect(extractHtmlTitle('<title> </title><h1>\n</h1>')).toBeUndefined();
+ expect(extractHtmlTitle('<title>季度回顾</title>')).toBe('季度回顾');
+ expect(extractHtmlTitle('<h1>季度回顾</h1>')).toBe('季度回顾');
+ expect(extractHtmlTitle('<title>R&amp;D &#x62a5;&#x544a;</title>')).toBe('R&D 报告');
+ expect(extractHtmlTitle('<title>Acme &copy; 2026</title>')).toBe('Acme © 2026');
+ expect(extractHtmlTitle('<title>C++ <vector> 指南</title>')).toBe('C++ <vector> 指南');
+ expect(
+ extractHtmlTitle(
+ `<!-- <title>Draft</title> --><script>const sample = '<title>Script</title>';</script><title>Final</title>`,
+ ),
+ ).toBe('Final');
+ expect(
+ extractHtmlTitle(
+ `<script>const sample = '<h1>Draft</h1>';</script><!-- <h1>Comment</h1> --><h1>Final heading</h1>`,
+ ),
+ ).toBe('Final heading');
+ });
+
+ it('htmlLooksUnstyled 只在没有 stylesheet 时为真', () => {
+ expect(htmlLooksUnstyled('<h1>hi</h1>')).toBe(true);
+ expect(htmlLooksUnstyled('<style>h1{color:red}</style><h1>hi</h1>')).toBe(false);
+ expect(htmlLooksUnstyled('<link rel="stylesheet" href="a.css"><h1>hi</h1>')).toBe(false);
+ expect(htmlLooksUnstyled('<link rel="alternate StyleSheet" href="a.css"><h1>hi</h1>')).toBe(false);
+ expect(htmlLooksUnstyled('<!-- <style>old rules</style> --><h1>hi</h1>')).toBe(true);
+ expect(
+ htmlLooksUnstyled(
+ `<script>const sample = '<style>old rules</style>';</script><template><link rel="stylesheet" href="old.css"></template><h1>hi</h1>`,
+ ),
+ ).toBe(true);
+ const wrapped = applyReportTemplate('<h1>hi</h1>', DOCS_THEMES.light);
+ expect(wrapped.applied).toBe(true);
+ expect(wrapped.html).toContain('data-cindy-docs-template="report"');
+ expect(applyReportTemplate(wrapped.html, DOCS_THEMES.light).applied).toBe(false);
+ });
+
+ it('套模板时不把 script 或注释里的伪 body 结束标签当成正文边界', () => {
+ const wrapped = applyReportTemplate(
+ `<html><body><script>const demo = '</body>';</script><!-- </body> --><h1>完整报告</h1></body></html>`,
+ DOCS_THEMES.light,
+ );
+ expect(wrapped.applied).toBe(true);
+ expect(wrapped.html).toContain("const demo = '</body>';");
+ expect(wrapped.html).toContain('<!-- </body> -->');
+ expect(wrapped.html).toContain('<h1>完整报告</h1>');
+ });
+
+ it('省略 body 时只移除真实 head,不把脚本或注释里的伪结束标签留进正文', () => {
+ const wrapped = applyReportTemplate(
+ `<html><head><script>const sample = '</head><h1>脚本标题</h1>';</script><!-- </head> --><title>报告</title></head><h1>真实正文</h1></html>`,
+ DOCS_THEMES.light,
+ );
+ expect(wrapped.applied).toBe(true);
+ expect(wrapped.html).toContain('<h1>真实正文</h1>');
+ expect(wrapped.html).not.toContain('脚本标题');
+ expect(wrapped.html).not.toContain('const sample =');
+ });
+
+ it('省略 head 结束标签与 body 时在正文元素前隐式结束 head', () => {
+ const wrapped = applyReportTemplate(
+ '<!doctype html><head><title>报告</title><h1>正文</h1>',
+ DOCS_THEMES.light,
+ );
+ expect(wrapped.applied).toBe(true);
+ expect(wrapped.html).toContain('<h1>正文</h1>');
+ expect(wrapped.html).not.toContain('<p></p>');
+ });
+
+ it('省略 body 时不改写 raw-text 中的 html 包装标签形状文本', () => {
+ const wrapped = applyReportTemplate(
+ `<!doctype html><html><script>const marker = '<html>'; const closing = '</html>';</script><h1>真实正文</h1></html>`,
+ DOCS_THEMES.light,
+ );
+ expect(wrapped.applied).toBe(true);
+ expect(wrapped.html).toContain("const marker = '<html>';");
+ expect(wrapped.html).toContain("const closing = '</html>';");
+ expect(wrapped.html).toContain('<h1>真实正文</h1>');
+ });
+
+ it('render_pdf 对无样式 HTML 自动套模板,已有 style 的原样透传', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const pdfBytes = Buffer.from(`%PDF-1.7\n${'x'.repeat(4096)}\n%%EOF`);
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const auto = await callTool(client, 'render_pdf', {
+ html: '<h1>季度回顾</h1><p>正文</p>',
+ outPath: 'auto.pdf',
+ });
+ expect(auto.ok).toBe(true);
+ expect(auto.templateApplied).toBe(true);
+ expect(seen[0]!.html).toContain('data-cindy-docs-template="report"');
+ expect(seen[0]!.html).toContain('季度回顾');
+ // 套模板后由 CSS @page 管边距,Electron 边距归零避免双边距
+ expect(seen[0]!.margins).toEqual({ top: 0, bottom: 0, left: 0, right: 0 });
+
+ const styled = await callTool(client, 'render_pdf', {
+ html: '<style>h1{color:red}</style><h1>已有样式</h1>',
+ outPath: 'styled.pdf',
+ });
+ expect(styled.ok).toBe(true);
+ expect(styled.templateApplied).toBe(false);
+ expect(seen[1]!.html).toBe('<style>h1{color:red}</style><h1>已有样式</h1>');
+ expect(seen[1]!.margins).toEqual({
+ top: 0.4,
+ bottom: 0.4,
+ left: 0.4,
+ right: 0.4,
+ });
+
+ const sourceDir = path.join(workdir, 'report-assets');
+ await fs.mkdir(sourceDir);
+ await fs.writeFile(
+ path.join(sourceDir, 'report.html'),
+ '<h1>相对资源</h1><img src="./chart.png">',
+ 'utf8',
+ );
+ await fs.writeFile(path.join(sourceDir, 'chart.png'), 'png-bytes', 'utf8');
+ const relative = await callTool(client, 'render_pdf', {
+ htmlPath: 'report-assets/report.html',
+ outPath: 'relative.pdf',
+ });
+ expect(relative.ok).toBe(true);
+ expect(Buffer.from(seen[2]!.htmlBytes!).toString('utf8')).toContain('data:image/png;base64,');
+ expect(Object.prototype.hasOwnProperty.call(seen[2], 'htmlBaseDir')).toBe(false);
+ expect(relative.warning).toBeUndefined();
+ });
+
+ it('template:none 跳过套模板;用户显式 margins 优先生效', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const pdfBytes = Buffer.from(`%PDF-1.7\n${'x'.repeat(4096)}\n%%EOF`);
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const skipped = await callTool(client, 'render_pdf', {
+ html: '<h1>hi</h1>',
+ outPath: 'none.pdf',
+ template: 'none',
+ });
+ expect(skipped.templateApplied).toBe(false);
+ expect(seen[0]!.html).toBe('<h1>hi</h1>');
+
+ const custom = await callTool(client, 'render_pdf', {
+ html: '<h1>hi</h1>',
+ outPath: 'margins.pdf',
+ margins: { top: 1, bottom: 1, left: 0.5, right: 0.5 },
+ });
+ expect(custom.templateApplied).toBe(true);
+ expect(seen[1]!.margins).toEqual({
+ top: 1,
+ bottom: 1,
+ left: 0.5,
+ right: 0.5,
+ });
+ });
+});
+
+/**
+ * 版面尺寸必须与 pptxMasters 的几何常量一致。
+ *
+ * 曾经不一致:layout 用了 pptxgenjs 的 'LAYOUT_16x9'(10" × 5.625"),几何却按
+ * 13.333" × 7.5" 写 —— 页脚和页码定位在 y=7.02,整个落在页面外,**从来没显示过**,
+ * 正文框也伸出页底。这条只比对数字,不依赖任何人肉目检。
+ */
+describe('页面尺寸与几何常量对齐', () => {
+ const EMU = 914400;
+
+ it('生成的 pptx 页面尺寸就是 SLIDE_W × SLIDE_H', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: '页面尺寸', layout: 'content', bullets: ['一条'] }],
+ outPath: 'size.pptx',
+ });
+ const xml = await unzip(result.path as string, 'ppt/presentation.xml');
+ const size = xml.match(/<p:sldSz[^>]*>/)![0];
+ expect(Number(size.match(/cx="(\d+)"/)![1]) / EMU).toBeCloseTo(SLIDE_W, 2);
+ expect(Number(size.match(/cy="(\d+)"/)![1]) / EMU).toBeCloseTo(SLIDE_H, 2);
+ });
+
+ it('母版上的每个形状都落在页面之内(页脚页码不许跑到页外)', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ title: '页脚检查',
+ slides: [{ title: '页脚', layout: 'content', bullets: ['一条'] }],
+ outPath: 'footer.pptx',
+ });
+ const layouts = await unzipAll(
+ result.path as string,
+ (name) => name.startsWith('ppt/slideLayouts/') && name.endsWith('.xml'),
+ );
+ for (const m of layouts.matchAll(
+ /<a:off x="(-?\d+)" y="(-?\d+)"\/><a:ext cx="(\d+)" cy="(\d+)"\/>/g,
+ )) {
+ const y = Number(m[2]) / EMU;
+ const h = Number(m[4]) / EMU;
+ if (h === 0) continue; // pptxgenjs 写的空组占位
+ expect(y + h).toBeLessThanOrEqual(SLIDE_H + 0.01);
+ }
+ });
+});
+
+/*
+ * 下面三组只比数字,不靠人眼 —— 每一条都对应一个目检真看出来、而「XML 里有这个
+ * 字符串」那种自检永远看不出来的毛病。
+ */
+describe('表格与版式的数值不变量', () => {
+ it('单字「率」也要认成百分比列 —— 工具描述承诺过', () => {
+ // 这条就是目检里那一列显示 0.03 而不是 3.3% 的直接原因:老正则写的是「比率」,
+ // 于是「退款率」「转化率」「完成率」这些最常见的百分比表头一个都匹配不上。
+ for (const header of ['退款率', '转化率', '完成率', '占比', '毛利率 %', 'Refund rate']) {
+ expect(inferNumberFormat(header, [0.0325, 0.064])).toBe('0.0%');
+ }
+ // 大于 1 的「率」不套百分号:汇率、频率这类不是占比。
+ expect(inferNumberFormat('汇率', [7.12, 7.3])).toBe('#,##0.00');
+ // 没有语义信号的整数列照旧走千分位。
+ expect(inferNumberFormat('订单数', [1284, 3921])).toBe('#,##0');
+ });
+
+ it('汇总行按结构判定 —— 公式占多数,不查「合计 / Total」词表', () => {
+ const f = (formula: string) => ({ formula, result: 1 });
+ expect(isSummaryRow(['合计', '', f('SUM(A1:A9)'), f('SUM(B1:B9)')])).toBe(true);
+ // 换任何语言都成立:判据是「这一行的数是算出来的」,不是它叫什么。
+ expect(isSummaryRow(['Gesamt', f('SUM(A1:A9)'), f('SUM(B1:B9)')])).toBe(true);
+ // 普通数据行不算,哪怕里面夹了一个计算列。
+ expect(isSummaryRow(['7月', '直营门店', 1284, 986400, f('D2-E2')])).toBe(false);
+ expect(isSummaryRow([])).toBe(false);
+ });
+
+ it('表格列宽按内容分,且总和仍是 100%', () => {
+ // 「严重度」放两个字,「建议」放一整句 —— 等分会让一边空一片、一边挤三行。
+ const pcts = columnPercents([8, 12, 6, 24]);
+ expect(pcts.length).toBe(4);
+ expect(Math.round(pcts.reduce((a, b) => a + b, 0))).toBe(100);
+ // 内容多的列必须比内容少的列宽。
+ expect(pcts[3]).toBeGreaterThan(pcts[2]!);
+ expect(pcts[1]).toBeGreaterThan(pcts[2]!);
+ // 极端值不许把某一列压到没法看。
+ const extreme = columnPercents([1, 1, 400]);
+ expect(Math.min(...extreme)).toBeGreaterThanOrEqual(7.9);
+ expect(Math.round(extreme.reduce((a, b) => a + b, 0))).toBe(100);
+ });
+
+ it('斑马纹必须和底色拉开肉眼可辨的差', () => {
+ // 原来 light/navy 的斑马纹与白底只差 2%,整张表看不出隔行 —— 打了等于没打。
+ const lum = (hex: string) =>
+ parseInt(hex.slice(0, 2), 16) * 0.299 +
+ parseInt(hex.slice(2, 4), 16) * 0.587 +
+ parseInt(hex.slice(4, 6), 16) * 0.114;
+ for (const name of ['light', 'dark', 'navy'] as const) {
+ const t = DOCS_THEMES[name];
+ expect(Math.abs(lum(t.background) - lum(t.zebra))).toBeGreaterThan(6);
+ }
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
new file mode 100644
index 0000000000..5bbe070991
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/cindyDocsMcpServer.test.ts
@@ -0,0 +1,2732 @@
+/**
+ * cindy_docs MCP server 测试:真 McpServer + InMemoryTransport,真文件往返。
+ *
+ * 覆盖:
+ * - 六个工具顶层暴露(防回退:曾藏在二级分派后导致模型从不调用)
+ * - render_pdf / inspect_pdf 的注册门(host 没注入对应回调时工具不出现)
+ * - office_to_pdf 已彻底下线(裁决:不保留任何依赖系统级 LibreOffice 的路径)
+ * - make_docx / make_pptx / make_xlsx 的真文件产出(解包断言 XML / exceljs 读回)
+ * - make_xlsx 的公式纪律:公式文本 + 缓存值一起落盘,回读拿到算好的值而不是 null
+ * - read_sheet 的 xlsx / csv / tsv 与截断标注
+ * - inspect_pdf 的判读结论(纸张名 / 空白页 / verdict)与失败归类
+ * - 路径边界:.. 穿越、绝对路径越界、symlink 逃逸
+ * - overwrite 语义
+ * - 无 workingDir 时 fail closed
+ * - render_pdf 的空产物 / 超时归类 / fontsReady 透传
+ */
+
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import ExcelJS from 'exceljs';
+import JSZip from 'jszip';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCindyDocsMcpServer } from '../cindy_docsMcpServer.js';
+import {
+ DOCX_MAX_MARKDOWN_BYTES,
+ DOCX_MAX_SUBTITLE_BYTES,
+ DOCX_MAX_TITLE_BYTES,
+} from '../cindy-docs/make_docx.js';
+import {
+ detectPptxImageMime,
+ isSupportedPptxImage,
+ PPTX_MAX_BULLETS_PER_SLIDE,
+ PPTX_MAX_SLIDES,
+ PPTX_MAX_TOTAL_TEXT_BYTES,
+ PPTX_THEMES,
+ resolvePptxGenConstructor,
+ validateDecodablePptxImage,
+} from '../cindy-docs/make_pptx.js';
+import { DocsPathError, readInputFileWithinLimit } from '../cindy-docs/_paths.js';
+import { RENDER_PDF_MAX_HTML_BYTES } from '../cindy-docs/render_pdf.js';
+import { MAX_XLSX_ZIP_ENTRIES } from '../cindy-docs/read_sheet.js';
+import type {
+ DocsMcpDeps,
+ DocsMcpSessionCtx,
+ DocsPdfInspection,
+ DocsPdfPageInspection,
+ DocsPdfRenderInput,
+ WriteDocsOutputFn,
+} from '../cindy-docs/types.js';
+
+let workdir: string;
+const created: string[] = [];
+
+beforeEach(async () => {
+ workdir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-test-'));
+ created.push(workdir);
+});
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ while (created.length > 0) {
+ const dir = created.pop()!;
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
+ }
+});
+
+function sessionCtx(overrides: Partial<DocsMcpSessionCtx> = {}): DocsMcpSessionCtx {
+ return {
+ agentKind: 'claude-code',
+ workingDir: workdir,
+ sessionId: 'sess-1',
+ ...overrides,
+ };
+}
+
+async function connect(deps: DocsMcpDeps = {}, ctx = sessionCtx()) {
+ const server = createCindyDocsMcpServer({ writeDocsOutput: testWriter, ...deps }, ctx);
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'docs-test-client', version: '0.0.0' });
+ await Promise.all([server.connect(serverTx), client.connect(clientTx)]);
+ return client;
+}
+
+const testWriter: WriteDocsOutputFn = async ({ path: outputPath, data, overwrite }) => {
+ try {
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
+ await fs.writeFile(outputPath, data, { flag: overwrite ? 'w' : 'wx' });
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
+ throw new DocsPathError('FILE_EXISTS', `目标文件已存在: ${outputPath}`, 'overwrite');
+ }
+ throw error;
+ }
+};
+
+function payload(result: unknown): Record<string, unknown> {
+ const content = (result as { content: Array<{ text: string }> }).content;
+ return JSON.parse(content[0]!.text) as Record<string, unknown>;
+}
+
+/** 六个工具顶层直接调用(2026-08-21 起不再经 call_tool 二级分派)。 */
+async function callTool(
+ client: Client,
+ name: string,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ return payload(await client.callTool({ name, arguments: args }));
+}
+
+async function unzip(file: string, entry: string): Promise<string> {
+ const zip = await JSZip.loadAsync(await fs.readFile(file));
+ const found = zip.file(entry);
+ if (!found) throw new Error(`missing ${entry}; have ${Object.keys(zip.files).join(',')}`);
+ return found.async('string');
+}
+
+describe('cindy_docs 入口工具', () => {
+ // 防回退:六个工具必须顶层可见。曾经它们藏在 list_tools/call_tool 二级分派
+ // 后面,真机上模型因此从未调用过任何一个(make_pptx 调用数 0),回了句「做不了」。
+ it('六个工具全部顶层暴露,没有二级分派入口', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.from('%PDF-'),
+ fontsReady: true,
+ }),
+ inspectPdf: async () => ({ numPages: 1, pagesInspected: 0, pages: [] }),
+ });
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name).sort()).toEqual([
+ 'inspect_pdf',
+ 'make_docx',
+ 'make_pptx',
+ 'make_xlsx',
+ 'read_sheet',
+ 'render_pdf',
+ ]);
+ expect(tools.map((t) => t.name)).not.toContain('list_tools');
+ expect(tools.map((t) => t.name)).not.toContain('call_tool');
+ });
+
+ it('顶层描述自解释:说清什么时候用,并带上路径与错误码约束', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.from('%PDF-'),
+ fontsReady: true,
+ }),
+ inspectPdf: async () => ({ numPages: 1, pagesInspected: 0, pages: [] }),
+ });
+ const { tools } = await client.listTools();
+ const byName = new Map(tools.map((t) => [t.name, t.description ?? '']));
+ // 顶层描述是模型唯一的选型依据 —— 触发词必须写在里面。
+ expect(byName.get('make_pptx')).toContain('PPT');
+ expect(byName.get('make_docx')).toContain('Word');
+ expect(byName.get('make_xlsx')).toContain('Excel');
+ expect(byName.get('render_pdf')).toContain('PDF');
+ expect(byName.get('inspect_pdf')).toContain('自检');
+ for (const description of byName.values()) {
+ expect(description).toContain('PATH_NOT_ALLOWED');
+ }
+ });
+
+ it('office_to_pdf 已彻底下线,连工具名都不存在', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.from('%PDF-'),
+ fontsReady: true,
+ }),
+ inspectPdf: async () => ({ numPages: 1, pagesInspected: 0, pages: [] }),
+ });
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name)).not.toContain('office_to_pdf');
+ // 顶层化后不存在的工具由 MCP 协议层直接拒绝(不再有 call_tool 的
+ // UNKNOWN_TOOL payload) —— 断言"调用会失败"即可。
+ const called = await client.callTool({
+ name: 'office_to_pdf',
+ arguments: { path: 'a.docx', outPath: 'a.pdf' },
+ });
+ expect((called as { isError?: boolean }).isError).toBe(true);
+ });
+
+ it('host 没注入渲染回调时 render_pdf / inspect_pdf 不注册', async () => {
+ const client = await connect({});
+ const { tools } = await client.listTools();
+ const names = tools.map((t) => t.name);
+ expect(names).not.toContain('render_pdf');
+ expect(names).not.toContain('inspect_pdf');
+ // 三个 author 工具与 read_sheet 不依赖 host 回调,恒在。
+ expect(names.sort()).toEqual(['make_docx', 'make_pptx', 'make_xlsx', 'read_sheet']);
+ });
+
+ it('缺必填参数被 schema 拦下,错误里带得出哪个字段', async () => {
+ const client = await connect();
+ // outPath 必填。顶层工具的入参校验由 MCP SDK 用同一份 zod shape 执行,
+ // 失败信息里含字段名,模型据此自纠。
+ const called = await client.callTool({
+ name: 'make_docx',
+ arguments: { markdown: 'x' },
+ });
+ expect((called as { isError?: boolean }).isError).toBe(true);
+ expect(JSON.stringify(called)).toContain('outPath');
+ });
+
+ it('未知字段不被静默忽略', async () => {
+ const client = await connect();
+ const called = await client.callTool({
+ name: 'make_docx',
+ arguments: { markdown: 'x', outPath: 'a.docx', tittle: '拼错的字段' },
+ });
+ // 拼错的字段不被静默剥掉:SDK 用同一份 zod shape 严格校验,直接判失败。
+ expect((called as { isError?: boolean }).isError).toBe(true);
+ expect(JSON.stringify(called)).toContain('tittle');
+ });
+});
+
+describe('make_docx', () => {
+ it('在解析 Markdown 前限制正文、标题和副题规模', async () => {
+ const client = await connect();
+ const cases = [
+ {
+ markdown: 'x'.repeat(DOCX_MAX_MARKDOWN_BYTES + 1),
+ outPath: 'too-large-markdown.docx',
+ },
+ {
+ markdown: 'ok',
+ title: 'x'.repeat(DOCX_MAX_TITLE_BYTES + 1),
+ outPath: 'too-large-title.docx',
+ },
+ {
+ markdown: 'ok',
+ subtitle: 'x'.repeat(DOCX_MAX_SUBTITLE_BYTES + 1),
+ outPath: 'too-large-subtitle.docx',
+ },
+ ];
+ for (const args of cases) {
+ const result = await client.callTool({ name: 'make_docx', arguments: args });
+ expect((result as { isError?: boolean }).isError).toBe(true);
+ await expect(fs.stat(path.join(workdir, args.outPath))).rejects.toThrow();
+ }
+ });
+
+ it('生成真 Word 文件,标题/粗体/列表/表格/代码块/分页符都落到 XML', async () => {
+ const client = await connect();
+ const markdown = [
+ '# 一级标题',
+ '',
+ '正文 **加粗** 与 *斜体* 与 `code`。',
+ '',
+ '- 无序一',
+ '- 无序二',
+ '',
+ '1. 有序一',
+ '2. 有序二',
+ '',
+ '> 引用一句',
+ '',
+ '| 列A | 列B |',
+ '|---|---|',
+ '| 1 | 2 |',
+ '',
+ '```js',
+ 'const x = 1;',
+ '```',
+ '',
+ '<!-- pagebreak -->',
+ '',
+ '尾页正文。',
+ ].join('\n');
+
+ const result = await callTool(client, 'make_docx', {
+ markdown,
+ outPath: 'documents/报告.docx',
+ title: '测试报告',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.format).toBe('docx');
+ expect(result.relativePath).toBe(path.join('documents', '报告.docx'));
+ expect(result.bytes as number).toBeGreaterThan(3000);
+
+ const file = result.path as string;
+ const xml = await unzip(file, 'word/document.xml');
+ expect(xml).toContain('Heading1');
+ expect(xml).toContain('一级标题');
+ expect(xml).toContain('<w:b/>');
+ expect(xml).toContain('<w:i/>');
+ expect(xml).toContain('Courier New');
+ expect(xml).toContain('<w:numPr>');
+ expect(xml).toContain('<w:tbl>');
+ expect(xml).toContain('引用一句');
+ expect(xml).toContain('const x = 1;');
+ expect(xml).toContain('w:type="page"');
+ // title 同时写进 core properties
+ expect(await unzip(file, 'docProps/core.xml')).toContain('测试报告');
+ // 有序列表用 decimal 编号定义
+ expect(await unzip(file, 'word/numbering.xml')).toContain('decimal');
+ });
+
+ it('引用块内外的有序列表不共用编号引用', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: ['> 1. 引用里的一', '> 2. 引用里的二', '', '1. 块外的一', '2. 块外的二'].join('\n'),
+ outPath: 'lists.docx',
+ });
+ expect(result.ok).toBe(true);
+ const xml = await unzip(result.path as string, 'word/document.xml');
+ const instances = [...xml.matchAll(/<w:numId w:val="(\d+)"\/>/g)].map((m) => m[1]);
+ // 两个列表各自一个 numId,不能是同一个 —— 否则块外列表会从 3 开始编号。
+ expect(new Set(instances).size).toBe(2);
+ });
+
+ it('保留有序列表显式起始编号', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: ['5. 第五步', '6. 第六步'].join('\n'),
+ outPath: 'ordered-start.docx',
+ });
+ expect(result.ok).toBe(true);
+ const numbering = await unzip(result.path as string, 'word/numbering.xml');
+ expect(numbering).toContain('<w:start w:val="5"/>');
+ });
+
+ it('保留从零开始的有序列表编号', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: ['0. 前置步骤', '1. 第一步'].join('\n'),
+ outPath: 'ordered-zero-start.docx',
+ });
+ expect(result.ok).toBe(true);
+ const numbering = await unzip(result.path as string, 'word/numbering.xml');
+ expect(numbering).toContain('<w:start w:val="0"/>');
+ });
+
+ it('列表项的正文与嵌套列表保持原始块顺序,只有首段带编号', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: ['1. 第一段', '', ' - 子项', '', ' 结论段'].join('\n'),
+ outPath: 'ordered-block-order.docx',
+ });
+ expect(result.ok).toBe(true);
+ const xml = await unzip(result.path as string, 'word/document.xml');
+ expect(xml.indexOf('第一段')).toBeLessThan(xml.indexOf('子项'));
+ expect(xml.indexOf('子项')).toBeLessThan(xml.indexOf('结论段'));
+ const paragraphs = xml.match(/<w:p\b[\s\S]*?<\/w:p>/g) ?? [];
+ expect(paragraphs.find((paragraph) => paragraph.includes('第一段'))).toContain('<w:numPr>');
+ expect(paragraphs.find((paragraph) => paragraph.includes('结论段'))).not.toContain('<w:numPr>');
+ });
+
+ it('输出目录不存在时自动创建', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# hi',
+ outPath: 'a/b/c/deep.docx',
+ });
+ expect(result.ok).toBe(true);
+ await expect(fs.stat(path.join(workdir, 'a/b/c/deep.docx'))).resolves.toBeTruthy();
+ });
+});
+
+describe('make_xlsx', () => {
+ it('在进入 ExcelJS 前限制工作表、行、列和单元格文本规模', async () => {
+ const client = await connect();
+ const invalidSheets = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: Array.from({ length: 33 }, (_, index) => ({ name: `S${index}`, rows: [] })),
+ outPath: 'too-many-sheets.xlsx',
+ },
+ });
+ expect((invalidSheets as { isError?: boolean }).isError).toBe(true);
+
+ const invalidRows = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: [{ name: 'S', rows: Array.from({ length: 5001 }, () => []) }],
+ outPath: 'too-many-rows.xlsx',
+ },
+ });
+ expect((invalidRows as { isError?: boolean }).isError).toBe(true);
+
+ const invalidColumns = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: [{ name: 'S', rows: [Array.from({ length: 257 }, () => null)] }],
+ outPath: 'too-many-columns.xlsx',
+ },
+ });
+ expect((invalidColumns as { isError?: boolean }).isError).toBe(true);
+
+ const invalidText = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: [{ name: 'S', rows: [['x'.repeat(32_768)]] }],
+ outPath: 'cell-text-too-long.xlsx',
+ },
+ });
+ expect((invalidText as { isError?: boolean }).isError).toBe(true);
+ });
+
+ it('写出的表能被 exceljs 读回,表头加粗 + 冻结首行 + 类型保真', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ sheets: [
+ {
+ name: '明细',
+ header: ['区域', '收入', '达标'],
+ rows: [
+ ['华东', 1200, true],
+ ['华南', 860, false],
+ ['西北', null, false],
+ ],
+ },
+ { name: '备注', rows: [['只有数据没有表头']] },
+ ],
+ outPath: 'data/report.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.sheets).toEqual([
+ { name: '明细', rows: 3 },
+ { name: '备注', rows: 1 },
+ ]);
+
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ const ws = wb.getWorksheet('明细')!;
+ expect(ws.getRow(1).font?.bold).toBe(true);
+ // exceljs 的 views 是 normal / frozen / split 的联合类型,ySplit 只存在于
+ // frozen 分支 —— 断言前先窄化,别用 any 把类型信息丢掉。
+ const view = ws.views?.[0];
+ expect(view?.state).toBe('frozen');
+ expect(view?.state === 'frozen' ? view.ySplit : undefined).toBe(1);
+ expect(ws.getRow(2).getCell(1).value).toBe('华东');
+ expect(ws.getRow(2).getCell(2).value).toBe(1200);
+ expect(ws.getRow(2).getCell(3).value).toBe(true);
+ // 列宽按内容自适应,且不小于下限
+ expect(ws.getColumn(1).width!).toBeGreaterThanOrEqual(8);
+ // 无表头的表不冻结
+ expect(wb.getWorksheet('备注')!.views?.[0]?.state ?? 'normal').not.toBe('frozen');
+ });
+
+ it('非法工作表名被消毒,重名自动去重', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ sheets: [
+ { name: 'a/b:c', rows: [['1']] },
+ { name: 'a/b:c', rows: [['2']] },
+ ],
+ outPath: 'x.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ expect(wb.worksheets.map((w) => w.name)).toEqual(['a_b_c', 'a_b_c_2']);
+ });
+
+ it('工作表名按 Excel 的大小写不敏感语义去重,保留展示名称', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ sheets: [
+ { name: 'Data', rows: [['one']] },
+ { name: 'data', rows: [['two']] },
+ ],
+ outPath: 'case-insensitive.xlsx',
+ });
+ expect(result.ok).toBe(true);
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ expect(wb.worksheets.map((w) => w.name)).toEqual(['Data', 'data_2']);
+ });
+
+ // 公式纪律:xlsx 只存公式文本,不存值。缓存值(result)必须一起写进去,否则
+ // Excel 重算之前那格是空的,而 read_sheet / 预览 / Numbers 直接读到 null。
+ // 这是「不引入 LibreOffice 重算」这条裁决的零依赖等价物,必须被测试钉死。
+ it('公式单元格连同缓存值一起落盘,回读拿到的是算好的值而不是空', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_xlsx', {
+ sheets: [
+ {
+ name: '汇总',
+ header: ['区域', '收入'],
+ rows: [
+ ['华东', 1200],
+ ['华南', 860],
+ ['合计', { formula: 'SUM(B2:B3)', result: 2060 }],
+ // 模型经常带上等号,两种写法都要能落对。
+ ['均值', { formula: '=AVERAGE(B2:B3)', result: 1030 }],
+ ['备注', { formula: 'IF(B4>2000,"达标","未达标")', result: '达标' }],
+ ],
+ },
+ ],
+ outPath: 'formula.xlsx',
+ });
+ expect(result.ok).toBe(true);
+
+ const wb = new ExcelJS.Workbook();
+ await wb.xlsx.readFile(result.path as string);
+ const ws = wb.getWorksheet('汇总')!;
+
+ const sum = ws.getRow(4).getCell(2).value as {
+ formula: string;
+ result: number;
+ };
+ expect(sum.formula).toBe('SUM(B2:B3)');
+ expect(sum.result).toBe(2060);
+
+ // 前导等号被剥掉:xlsx 里存的公式本来就不带 '='。
+ const avg = ws.getRow(5).getCell(2).value as {
+ formula: string;
+ result: number;
+ };
+ expect(avg.formula).toBe('AVERAGE(B2:B3)');
+ expect(avg.result).toBe(1030);
+
+ const text = ws.getRow(6).getCell(2).value as {
+ formula: string;
+ result: string;
+ };
+ expect(text.result).toBe('达标');
+
+ // 而且 read_sheet 回读时看到的是缓存值,不是公式文本、更不是 null ——
+ // 这正是「不靠 LibreOffice 重算」要保住的那个性质。
+ const readBack = await callTool(client, 'read_sheet', {
+ path: 'formula.xlsx',
+ });
+ const rows = readBack.rows as unknown[][];
+ expect(rows[3]![1]).toBe(2060);
+ expect(rows[4]![1]).toBe(1030);
+ expect(rows[5]![1]).toBe('达标');
+ });
+
+ it('公式缺 result 直接判参数错,不给"打开才发现是空格"的机会', async () => {
+ const client = await connect();
+ const called = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: [{ name: 'S', rows: [[{ formula: 'SUM(A1:A2)' }]] }],
+ outPath: 'bad.xlsx',
+ },
+ });
+ expect((called as { isError?: boolean }).isError).toBe(true);
+ expect(JSON.stringify(called)).toContain('result');
+ });
+
+ it('公式 result:null 直接判参数错,空字符串才表示空缓存值', async () => {
+ const client = await connect();
+ const called = await client.callTool({
+ name: 'make_xlsx',
+ arguments: {
+ sheets: [{ name: 'S', rows: [[{ formula: 'SUM(A1:A2)', result: null }]] }],
+ outPath: 'null-result.xlsx',
+ },
+ });
+ expect((called as { isError?: boolean }).isError).toBe(true);
+ expect(JSON.stringify(called)).toContain('result');
+ });
+});
+
+describe('make_pptx', () => {
+ it('在进入 PptxGenJS 前限制页数、要点数和整份文字量', async () => {
+ const client = await connect();
+ const tooManySlides = await client.callTool({
+ name: 'make_pptx',
+ arguments: {
+ slides: Array.from({ length: PPTX_MAX_SLIDES + 1 }, (_, index) => ({
+ title: `第 ${index + 1} 页`,
+ })),
+ outPath: 'too-many-slides.pptx',
+ },
+ });
+ expect((tooManySlides as { isError?: boolean }).isError).toBe(true);
+
+ const tooManyBullets = await client.callTool({
+ name: 'make_pptx',
+ arguments: {
+ slides: [
+ {
+ title: '要点过多',
+ bullets: Array.from({ length: PPTX_MAX_BULLETS_PER_SLIDE + 1 }, () => 'x'),
+ },
+ ],
+ outPath: 'too-many-bullets.pptx',
+ },
+ });
+ expect((tooManyBullets as { isError?: boolean }).isError).toBe(true);
+
+ const textPerSlide = 64_000 + 32_000;
+ const slideCount = Math.floor(PPTX_MAX_TOTAL_TEXT_BYTES / textPerSlide) + 1;
+ const tooMuchText = await client.callTool({
+ name: 'make_pptx',
+ arguments: {
+ slides: Array.from({ length: slideCount }, (_, index) => ({
+ title: `第 ${index + 1} 页`,
+ notes: 'n'.repeat(64_000),
+ body: 'b'.repeat(32_000),
+ })),
+ outPath: 'too-much-text.pptx',
+ },
+ });
+ expect((tooMuchText as { isError?: boolean }).isError).toBe(true);
+ for (const file of ['too-many-slides.pptx', 'too-many-bullets.pptx', 'too-much-text.pptx']) {
+ await expect(fs.stat(path.join(workdir, file))).rejects.toThrow();
+ }
+ });
+
+ it('accepts direct and wrapped pptxgenjs constructors', () => {
+ class FakePptx {}
+ expect(resolvePptxGenConstructor(FakePptx)).toBe(FakePptx);
+ expect(resolvePptxGenConstructor({ default: FakePptx })).toBe(FakePptx);
+ expect(resolvePptxGenConstructor({ default: { default: FakePptx } })).toBe(FakePptx);
+ expect(() => resolvePptxGenConstructor({ default: {} })).toThrow(
+ 'pptxgenjs did not expose a constructor',
+ );
+ });
+
+ it('生成真 pptx,标题/要点/备注都在,深浅主题背景不同', async () => {
+ const client = await connect();
+ const light = await callTool(client, 'make_pptx', {
+ slides: [
+ {
+ title: '结论先行',
+ bullets: ['要点一', '要点二'],
+ notes: '这里是备注',
+ body: '补充说明',
+ },
+ { title: '第二页' },
+ ],
+ outPath: 'deck-light.pptx',
+ theme: 'light',
+ title: '汇报',
+ });
+ expect(light.ok).toBe(true);
+ expect(light.slides).toBe(2);
+ expect(light.theme).toBe('light');
+
+ const slide1 = await unzip(light.path as string, 'ppt/slides/slide1.xml');
+ expect(slide1).toContain('结论先行');
+ expect(slide1).toContain('要点一');
+ expect(slide1).toContain('补充说明');
+ expect(slide1).toContain(PPTX_THEMES.light.background);
+ const notes = await unzip(light.path as string, 'ppt/notesSlides/notesSlide1.xml');
+ expect(notes).toContain('这里是备注');
+
+ const dark = await callTool(client, 'make_pptx', {
+ slides: [{ title: '深色' }],
+ outPath: 'deck-dark.pptx',
+ theme: 'dark',
+ });
+ const darkSlide = await unzip(dark.path as string, 'ppt/slides/slide1.xml');
+ expect(darkSlide).toContain(PPTX_THEMES.dark.background);
+ expect(PPTX_THEMES.dark.background).not.toBe(PPTX_THEMES.light.background);
+ });
+
+ it('最大合法标题启用文本框缩放,不静默裁切', async () => {
+ const client = await connect();
+ const longTitle = '长'.repeat(1_000);
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: longTitle }],
+ outPath: 'long-title.pptx',
+ });
+
+ expect(result.ok).toBe(true);
+ const slide = await unzip(result.path as string, 'ppt/slides/slide1.xml');
+ expect(slide).toContain(longTitle);
+ expect(slide).toContain('<a:normAutofit');
+ });
+
+ it('最大合法正文启用文本框缩放,不静默裁切', async () => {
+ const client = await connect();
+ const longBody = '正'.repeat(32_000);
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: '长正文', layout: 'content', body: longBody }],
+ outPath: 'long-body.pptx',
+ });
+
+ expect(result.ok).toBe(true);
+ const slide = await unzip(result.path as string, 'ppt/slides/slide1.xml');
+ expect(slide).toContain(longBody);
+ expect(slide.match(/<a:normAutofit/g)).toHaveLength(2);
+ });
+
+ it('最大合法普通要点启用文本框缩放,不静默裁切', async () => {
+ const client = await connect();
+ const longBullet = '点'.repeat(4_000);
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: '长要点', layout: 'content', bullets: [longBullet] }],
+ outPath: 'long-bullet.pptx',
+ });
+
+ expect(result.ok).toBe(true);
+ const slide = await unzip(result.path as string, 'ppt/slides/slide1.xml');
+ expect(slide).toContain(longBullet);
+ expect(slide.match(/<a:normAutofit/g)).toHaveLength(2);
+ });
+
+ it('最大合法指标值和标签启用文本框缩放,不静默裁切', async () => {
+ const client = await connect();
+ const longValue = '9'.repeat(1_000);
+ const longLabel = '标'.repeat(1_000);
+ const result = await callTool(client, 'make_pptx', {
+ slides: [
+ {
+ title: '指标页',
+ layout: 'metrics',
+ metrics: [
+ { value: longValue, label: longLabel },
+ { value: '2', label: '对照指标' },
+ ],
+ },
+ ],
+ outPath: 'long-metric.pptx',
+ });
+
+ expect(result.ok).toBe(true);
+ const slide = await unzip(result.path as string, 'ppt/slides/slide1.xml');
+ expect(slide).toContain(longValue);
+ expect(slide).toContain(longLabel);
+ expect(slide.match(/<a:normAutofit/g)).toHaveLength(5);
+ });
+
+ it('拒绝会静默丢弃 imagePath 的版式组合', async () => {
+ const client = await connect();
+ const layouts = [
+ { layout: 'cover' },
+ { layout: 'section' },
+ { layout: 'comparison', columns: [{ title: '甲' }, { title: '乙' }] },
+ {
+ layout: 'metrics',
+ metrics: [
+ { value: '1', label: '甲' },
+ { value: '2', label: '乙' },
+ ],
+ },
+ ];
+
+ for (const [index, slide] of layouts.entries()) {
+ const result = await client.callTool({
+ name: 'make_pptx',
+ arguments: {
+ slides: [{ title: '带图页面', imagePath: '../../../etc/hosts', ...slide }],
+ outPath: `discarded-image-${index}.pptx`,
+ },
+ });
+ expect((result as { isError?: boolean }).isError).toBe(true);
+ await expect(
+ fs.stat(path.join(workdir, `discarded-image-${index}.pptx`)),
+ ).rejects.toThrow();
+ }
+ });
+
+ it('拒绝会静默丢弃字段的版式组合', async () => {
+ const client = await connect();
+ const cases = [
+ {
+ name: 'metrics-body',
+ slide: {
+ title: '指标页',
+ layout: 'metrics',
+ body: '这段正文不会被 metrics 版式消费',
+ metrics: [
+ { value: '1', label: '甲' },
+ { value: '2', label: '乙' },
+ ],
+ },
+ },
+ {
+ name: 'metrics-bullets',
+ slide: {
+ title: '指标页',
+ layout: 'metrics',
+ bullets: ['这条要点不会被 metrics 版式消费'],
+ metrics: [
+ { value: '1', label: '甲' },
+ { value: '2', label: '乙' },
+ ],
+ },
+ },
+ {
+ name: 'content-columns',
+ slide: {
+ title: '内容页',
+ layout: 'content',
+ columns: [{ title: '甲' }, { title: '乙' }],
+ },
+ },
+ {
+ name: 'content-metrics',
+ slide: {
+ title: '内容页',
+ layout: 'content',
+ metrics: [
+ { value: '1', label: '甲' },
+ { value: '2', label: '乙' },
+ ],
+ },
+ },
+ ];
+
+ for (const testCase of cases) {
+ const result = await client.callTool({
+ name: 'make_pptx',
+ arguments: {
+ slides: [testCase.slide],
+ outPath: `${testCase.name}.pptx`,
+ },
+ });
+ expect((result as { isError?: boolean }).isError).toBe(true);
+ await expect(fs.stat(path.join(workdir, `${testCase.name}.pptx`))).rejects.toThrow();
+ }
+ });
+
+ it('图片路径越界时整个生成不发生,不留半成品', async () => {
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: '第一页' }, { title: '带图', imagePath: '../../../etc/hosts' }],
+ outPath: 'deck.pptx',
+ });
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ await expect(fs.stat(path.join(workdir, 'deck.pptx'))).rejects.toThrow();
+ });
+
+ it('不支持的图片格式先被拦下,不生成打不开的坏包', async () => {
+ await fs.writeFile(path.join(workdir, 'pic.webp'), 'not-really-webp');
+ const client = await connect();
+ const result = await callTool(client, 'make_pptx', {
+ slides: [{ title: '带图', imagePath: 'pic.webp' }],
+ outPath: 'deck.pptx',
+ });
+ expect(result.errorCode).toBe('UNSUPPORTED_IMAGE');
+ expect((result.data as Record<string, string>).hint).toContain('.png');
+ await expect(fs.stat(path.join(workdir, 'deck.pptx'))).rejects.toThrow();
+
+ // 支持的扩展名照常放行
+ expect(isSupportedPptxImage('/a/b.PNG')).toBe(true);
+ expect(isSupportedPptxImage('/a/b.svg')).toBe(false);
+ });
+
+ it('支持的图片后缀也必须有真实图片字节,MIME 按内容而不是后缀决定', async () => {
+ await fs.writeFile(path.join(workdir, 'fake.png'), 'plain text');
+ const client = await connect();
+ const invalid = await callTool(client, 'make_pptx', {
+ slides: [{ title: '伪图片', imagePath: 'fake.png' }],
+ outPath: 'fake-image.pptx',
+ });
+ expect(invalid.errorCode).toBe('INVALID_IMAGE');
+ await expect(fs.stat(path.join(workdir, 'fake-image.pptx'))).rejects.toThrow();
+
+ const jpegNamedPng = Buffer.from([
+ 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x01, 0x00, 0x01, 0x03, 0x01, 0x11, 0x00,
+ 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xff, 0xd9,
+ ]);
+ expect(detectPptxImageMime(jpegNamedPng)).toBeNull();
+
+ const completeJpeg = Buffer.from([
+ 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x01, 0x00, 0x01, 0x03, 0x01, 0x11, 0x00,
+ 0x02, 0x11, 0x00, 0x03, 0x11, 0x00, 0xff, 0xda, 0x00, 0x0c, 0x03, 0x01, 0x00, 0x02, 0x11,
+ 0x03, 0x11, 0x00, 0x00, 0x3f, 0x00, 0x01, 0xff, 0xd9,
+ ]);
+ expect(detectPptxImageMime(completeJpeg)).toBe('image/jpeg');
+
+ const progressiveJpeg = Buffer.from([
+ 0xff, 0xd8, 0xff, 0xc2, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00,
+ 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0xff, 0xc4, 0x00, 0x02,
+ 0xff, 0xda, 0x00, 0x08, 0x01, 0x01, 0x01, 0x3f, 0x00, 0x02, 0x02, 0xff, 0xd9,
+ ]);
+ expect(detectPptxImageMime(progressiveJpeg)).toBe('image/jpeg');
+
+ const invalidPng = Buffer.from([
+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44,
+ 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x44, 0x41, 0x54, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
+ ]);
+ expect(detectPptxImageMime(invalidPng)).toBe('image/png');
+ await expect(validateDecodablePptxImage(invalidPng)).resolves.toBe(false);
+ });
+});
+
+describe('read_sheet', () => {
+ it('读回自己刚生成的 xlsx,支持按名与按序号选表', async () => {
+ const client = await connect();
+ await callTool(client, 'make_xlsx', {
+ sheets: [
+ { name: 'S1', header: ['a', 'b'], rows: [[1, 2]] },
+ { name: 'S2', header: ['c'], rows: [['x']] },
+ ],
+ outPath: 'r.xlsx',
+ });
+
+ const first = await callTool(client, 'read_sheet', { path: 'r.xlsx' });
+ expect(first.ok).toBe(true);
+ expect(first.sheet).toBe('S1');
+ expect(first.sheetNames).toEqual(['S1', 'S2']);
+ expect(first.rows).toEqual([
+ ['a', 'b'],
+ [1, 2],
+ ]);
+ expect(first.truncated).toBe(false);
+
+ expect((await callTool(client, 'read_sheet', { path: 'r.xlsx', sheet: 'S2' })).rows).toEqual([
+ ['c'],
+ ['x'],
+ ]);
+ expect((await callTool(client, 'read_sheet', { path: 'r.xlsx', sheet: 2 })).sheet).toBe('S2');
+
+ const missing = await callTool(client, 'read_sheet', {
+ path: 'r.xlsx',
+ sheet: '不存在',
+ });
+ expect(missing.errorCode).toBe('SHEET_NOT_FOUND');
+ expect((missing.data as Record<string, string>).hint).toContain('S1');
+ expect((await callTool(client, 'read_sheet', { path: 'r.xlsx', sheet: 9 })).errorCode).toBe(
+ 'SHEET_NOT_FOUND',
+ );
+ });
+
+ it('读 csv / tsv,引号与跨行字段保真', async () => {
+ const client = await connect();
+ await fs.writeFile(
+ path.join(workdir, 'a.csv'),
+ 'name,note\r\n甲,"含,逗号"\r\n乙,"跨\n行"\r\n',
+ 'utf-8',
+ );
+ const csv = await callTool(client, 'read_sheet', { path: 'a.csv' });
+ expect(csv.format).toBe('csv');
+ expect(csv.rows).toEqual([
+ ['name', 'note'],
+ ['甲', '含,逗号'],
+ ['乙', '跨\n行'],
+ ]);
+
+ await fs.writeFile(path.join(workdir, 'a.tsv'), 'x\ty\n1\t2\n', 'utf-8');
+ expect((await callTool(client, 'read_sheet', { path: 'a.tsv' })).rows).toEqual([
+ ['x', 'y'],
+ ['1', '2'],
+ ]);
+ });
+
+ it('按 BOM 解码 UTF-16LE CSV 与 UTF-16BE TSV', async () => {
+ const client = await connect();
+ const csvText = 'name,note\r\n甲,季度报告\r\n';
+ await fs.writeFile(
+ path.join(workdir, 'utf16le.csv'),
+ Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(csvText, 'utf16le')]),
+ );
+ expect((await callTool(client, 'read_sheet', { path: 'utf16le.csv' })).rows).toEqual([
+ ['name', 'note'],
+ ['甲', '季度报告'],
+ ]);
+
+ const tsvText = '项目\t数值\n乙\t42\n';
+ const utf16Le = Buffer.from(tsvText, 'utf16le');
+ const utf16Be = Buffer.allocUnsafe(utf16Le.length);
+ for (let index = 0; index < utf16Le.length; index += 2) {
+ utf16Be[index] = utf16Le[index + 1]!;
+ utf16Be[index + 1] = utf16Le[index]!;
+ }
+ await fs.writeFile(
+ path.join(workdir, 'utf16be.tsv'),
+ Buffer.concat([Buffer.from([0xfe, 0xff]), utf16Be]),
+ );
+ expect((await callTool(client, 'read_sheet', { path: 'utf16be.tsv' })).rows).toEqual([
+ ['项目', '数值'],
+ ['乙', '42'],
+ ]);
+ });
+
+ it('超过 maxRows 时明确标注截断,不假装这就是全表', async () => {
+ const client = await connect();
+ const lines = Array.from({ length: 50 }, (_, i) => `${i},v${i}`).join('\n');
+ await fs.writeFile(path.join(workdir, 'big.csv'), lines, 'utf-8');
+ const result = await callTool(client, 'read_sheet', {
+ path: 'big.csv',
+ maxRows: 10,
+ });
+ expect(result.returnedRows).toBe(10);
+ expect(result.totalRows).toBe(50);
+ expect(result.truncated).toBe(true);
+ expect(result.startRow).toBe(1);
+ expect(result.endRow).toBe(10);
+ expect(result.nextStartRow).toBe(11);
+ expect(result.truncationNote).toContain('50');
+
+ const middle = await callTool(client, 'read_sheet', {
+ path: 'big.csv',
+ startRow: 21,
+ maxRows: 10,
+ });
+ expect(middle.rows).toEqual(
+ Array.from({ length: 10 }, (_, i) => [String(i + 20), `v${i + 20}`]),
+ );
+ expect(middle.startRow).toBe(21);
+ expect(middle.endRow).toBe(30);
+ expect(middle.nextStartRow).toBe(31);
+
+ const last = await callTool(client, 'read_sheet', {
+ path: 'big.csv',
+ startRow: 41,
+ maxRows: 10,
+ });
+ expect(last.returnedRows).toBe(10);
+ expect(last.truncated).toBe(false);
+ expect(last.nextStartRow).toBeUndefined();
+ });
+
+ it('CSV 列分页元数据按全文件最宽行统计,不随当前行页缩小', async () => {
+ const client = await connect();
+ const wideRow = Array.from({ length: 100 }, (_, i) => `v${i}`).join(',');
+ await fs.writeFile(path.join(workdir, 'wide.csv'), `a,b\n${wideRow}\n`, 'utf8');
+ const first = await callTool(client, 'read_sheet', {
+ path: 'wide.csv',
+ maxRows: 1,
+ maxColumns: 8,
+ });
+ expect(first.totalColumns).toBe(100);
+ expect(first.nextStartColumn).toBe(9);
+ });
+
+ it('按 worksheet.rowCount 保留物理行号,稀疏尾行会正确标记截断', async () => {
+ const workbook = new ExcelJS.Workbook();
+ const sheet = workbook.addWorksheet('Sparse');
+ sheet.getCell('A1000').value = 'tail';
+ await fs.writeFile(
+ path.join(workdir, 'sparse.xlsx'),
+ Buffer.from((await workbook.xlsx.writeBuffer()) as ArrayBuffer),
+ );
+ const client = await connect();
+ const first = await callTool(client, 'read_sheet', {
+ path: 'sparse.xlsx',
+ maxRows: 200,
+ });
+ expect(first.totalRows).toBe(1000);
+ expect(first.returnedRows).toBe(200);
+ expect(first.truncated).toBe(true);
+
+ const full = await callTool(client, 'read_sheet', {
+ path: 'sparse.xlsx',
+ maxRows: 1000,
+ });
+ expect(full.totalRows).toBe(1000);
+ expect(full.truncated).toBe(false);
+ expect((full.rows as unknown[][])[999]![0]).toBe('tail');
+
+ const tail = await callTool(client, 'read_sheet', {
+ path: 'sparse.xlsx',
+ startRow: 999,
+ maxRows: 2,
+ });
+ expect(tail.rows).toEqual([[null], ['tail']]);
+ expect(tail.startRow).toBe(999);
+ expect(tail.endRow).toBe(1000);
+ expect(tail.truncated).toBe(false);
+ });
+
+ it('宽表按列窗口读取,不会物化 XFD 右侧的大量空格', async () => {
+ const workbook = new ExcelJS.Workbook();
+ const sheet = workbook.addWorksheet('Wide');
+ sheet.getCell('XFD1').value = 'tail-column';
+ await fs.writeFile(
+ path.join(workdir, 'wide.xlsx'),
+ Buffer.from((await workbook.xlsx.writeBuffer()) as ArrayBuffer),
+ );
+ const client = await connect();
+ const first = await callTool(client, 'read_sheet', {
+ path: 'wide.xlsx',
+ maxRows: 1,
+ maxColumns: 8,
+ });
+ expect(first.totalColumns).toBe(16384);
+ expect(first.returnedRows).toBe(1);
+ expect((first.rows as unknown[][])[0]).toHaveLength(8);
+ expect(first.nextStartColumn).toBe(9);
+
+ const tail = await callTool(client, 'read_sheet', {
+ path: 'wide.xlsx',
+ maxRows: 1,
+ startColumn: 16384,
+ maxColumns: 1,
+ });
+ expect(tail.rows).toEqual([['tail-column']]);
+ expect(tail.truncated).toBe(false);
+ expect(tail.nextStartColumn).toBeUndefined();
+ });
+
+ it('xlsx 输入先过文件大小与 ZIP 解压比上限,不把异常压缩包交给 ExcelJS', async () => {
+ const client = await connect();
+ await fs.writeFile(path.join(workdir, 'huge.xlsx'), Buffer.alloc(32 * 1024 * 1024 + 1, 0));
+ expect((await callTool(client, 'read_sheet', { path: 'huge.xlsx' })).errorCode).toBe(
+ 'FILE_TOO_LARGE',
+ );
+
+ const zip = new JSZip();
+ zip.file(
+ 'xl/worksheets/sheet1.xml',
+ '<sheetData>' + 'x'.repeat(2 * 1024 * 1024) + '</sheetData>',
+ );
+ await fs.writeFile(
+ path.join(workdir, 'bomb.xlsx'),
+ await zip.generateAsync({
+ type: 'nodebuffer',
+ compression: 'DEFLATE',
+ compressionOptions: { level: 9 },
+ }),
+ );
+ const bomb = await callTool(client, 'read_sheet', { path: 'bomb.xlsx' });
+ expect(bomb.errorCode).toBe('FILE_TOO_LARGE');
+ expect((bomb.data as Record<string, string>).hint).toContain('压缩');
+
+ const manyEntries = new JSZip();
+ for (let i = 0; i <= MAX_XLSX_ZIP_ENTRIES; i += 1) {
+ manyEntries.file(`xl/comments/empty-${i}.xml`, '');
+ }
+ await fs.writeFile(
+ path.join(workdir, 'many-entries.xlsx'),
+ await manyEntries.generateAsync({
+ type: 'nodebuffer',
+ compression: 'STORE',
+ }),
+ );
+ const entries = await callTool(client, 'read_sheet', {
+ path: 'many-entries.xlsx',
+ });
+ expect(entries.errorCode).toBe('FILE_TOO_LARGE');
+ expect((entries.data as Record<string, string>).hint).toContain('ZIP 条目');
+ });
+
+ it('.xls 与未知扩展名给出可执行的降级指引', async () => {
+ const client = await connect();
+ await fs.writeFile(path.join(workdir, 'old.xls'), 'x', 'utf-8');
+ const xls = await callTool(client, 'read_sheet', { path: 'old.xls' });
+ expect(xls.errorCode).toBe('UNSUPPORTED_FORMAT');
+ expect((xls.data as Record<string, string>).hint).toContain('.xlsx');
+
+ await fs.writeFile(path.join(workdir, 'a.pdf'), 'x', 'utf-8');
+ expect((await callTool(client, 'read_sheet', { path: 'a.pdf' })).errorCode).toBe(
+ 'UNSUPPORTED_FORMAT',
+ );
+ });
+
+ it('文件不存在返回 NOT_A_FILE', async () => {
+ const client = await connect();
+ expect((await callTool(client, 'read_sheet', { path: 'ghost.csv' })).errorCode).toBe(
+ 'NOT_A_FILE',
+ );
+ });
+});
+
+describe('路径边界与覆盖语义', () => {
+ it('四种生成工具拒绝缺失或错误的输出扩展名', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.from('%PDF-1.7'),
+ fontsReady: true,
+ }),
+ });
+ const cases: Array<[string, Record<string, unknown>]> = [
+ ['make_docx', { markdown: '# x', outPath: 'wrong.pdf' }],
+ ['make_pptx', { slides: [{ title: 'x' }], outPath: 'wrong.docx' }],
+ ['make_xlsx', { sheets: [{ name: 'S', rows: [[1]] }], outPath: 'wrong' }],
+ ['render_pdf', { html: '<p>x</p>', outPath: 'wrong.pptx' }],
+ ];
+ for (const [tool, args] of cases) {
+ expect((await callTool(client, tool, args)).errorCode).toBe('INVALID_EXTENSION');
+ }
+ });
+
+ it('.. 穿越与工作目录外的绝对路径都被拒', async () => {
+ const client = await connect();
+ for (const outPath of [
+ '../escape.docx',
+ path.join(os.tmpdir(), 'escape.docx'),
+ '/etc/x.docx',
+ ]) {
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# x',
+ outPath,
+ });
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect((result.data as Record<string, string>).hint).toContain('工作目录');
+ }
+ });
+
+ it('经 symlink 指向工作目录外也被拒', async () => {
+ const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));
+ created.push(outside);
+ await fs.symlink(outside, path.join(workdir, 'link'), 'dir');
+ const client = await connect();
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# x',
+ outPath: 'link/escaped.docx',
+ });
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ await expect(fs.stat(path.join(outside, 'escaped.docx'))).rejects.toThrow();
+ });
+
+ it('同名文件默认不覆盖,overwrite:true 才覆盖', async () => {
+ const client = await connect();
+ const first = await callTool(client, 'make_docx', {
+ markdown: '# 第一版',
+ outPath: 'a.docx',
+ });
+ expect(first.ok).toBe(true);
+ const firstBytes = first.bytes as number;
+
+ const blocked = await callTool(client, 'make_docx', {
+ markdown: '# 第二版',
+ outPath: 'a.docx',
+ });
+ expect(blocked.errorCode).toBe('FILE_EXISTS');
+ expect((blocked.data as Record<string, string>).hint).toContain('overwrite');
+ // 被拒时原文件必须原封不动
+ expect((await fs.stat(path.join(workdir, 'a.docx'))).size).toBe(firstBytes);
+
+ const forced = await callTool(client, 'make_docx', {
+ markdown: '# 第二版内容更长一些用来改变体积',
+ outPath: 'a.docx',
+ overwrite: true,
+ });
+ expect(forced.ok).toBe(true);
+ expect(await unzip(forced.path as string, 'word/document.xml')).toContain('第二版');
+ });
+
+ it('输入读取只接受与边界校验相同的已打开文件身份', async () => {
+ const inside = path.join(workdir, 'inside.txt');
+ const outsideDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-docs-outside-'));
+ created.push(outsideDir);
+ const outside = path.join(outsideDir, 'outside.txt');
+ await fs.writeFile(inside, 'inside');
+ await fs.writeFile(outside, 'outside');
+
+ const originalOpen = fs.open.bind(fs);
+ vi.spyOn(fs, 'open').mockImplementationOnce(async () => originalOpen(outside, 'r'));
+ await expect(
+ readInputFileWithinLimit(
+ workdir,
+ inside,
+ 1024,
+ (bytes) => new DocsPathError('FILE_TOO_LARGE', String(bytes), 'too large'),
+ ),
+ ).rejects.toMatchObject({ code: 'PATH_NOT_ALLOWED' });
+ });
+
+ it('无 workingDir 时 fail closed', async () => {
+ const client = await connect({}, sessionCtx({ workingDir: '' }));
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# x',
+ outPath: 'a.docx',
+ });
+ expect(result.errorCode).toBe('NO_SESSION_CONTEXT');
+ });
+
+ it('远程(SSH)会话拒绝生成本地文件', async () => {
+ const client = await connect({}, sessionCtx({ remoteHostId: 'box-1' }));
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# x',
+ outPath: 'a.docx',
+ });
+ expect(result.errorCode).toBe('REMOTE_SESSION_UNSUPPORTED');
+ });
+
+ it('归属解析不出来时不借用构建期 ctx', async () => {
+ // getSessionContext 是权威来源:返回 undefined 表示本次调用无法确认归属,
+ // 此时必须 fail closed,而不是回落到闭包里那个 workdir。
+ const ctx = sessionCtx({ getSessionContext: () => undefined });
+ const client = await connect({}, ctx);
+ const result = await callTool(client, 'make_docx', {
+ markdown: '# x',
+ outPath: 'a.docx',
+ });
+ expect(result.errorCode).toBe('NO_SESSION_CONTEXT');
+ });
+});
+
+describe('render_pdf', () => {
+ const pdfBytes = Buffer.from(`%PDF-1.7\n${'x'.repeat(4096)}\n%%EOF`);
+
+ it('把 host 返回的字节落盘,并透传排版参数', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ html: '<h1>hi</h1>',
+ outPath: 'out/a.pdf',
+ pageSize: 'Letter',
+ landscape: true,
+ template: 'none',
+ margins: { top: 1, bottom: 1, left: 0.5, right: 0.5 },
+ });
+ expect(result.ok).toBe(true);
+ expect(result.format).toBe('pdf');
+ expect(result.bytes).toBe(pdfBytes.length);
+ expect(await fs.readFile(path.join(workdir, 'out/a.pdf'))).toEqual(pdfBytes);
+ expect(seen[0]).toMatchObject({
+ html: '<h1>hi</h1>',
+ pageSize: 'Letter',
+ landscape: true,
+ printBackground: true,
+ margins: { top: 1, bottom: 1, left: 0.5, right: 0.5 },
+ timeoutMs: 30_000,
+ fontTimeoutMs: 5_000,
+ });
+ });
+
+ it('htmlPath 走边界校验后把已验证字节交给 host,不再传可变路径', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'src.html'), '<p>x</p>', 'utf-8');
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'src.html',
+ outPath: 'a.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ expect(seen[0]!.html).toBeUndefined();
+ expect(seen[0]!.htmlBytes).toBeDefined();
+ expect(Buffer.from(seen[0]!.htmlBytes!).toString('utf8')).toBe('<p>x</p>');
+ });
+
+ it('htmlPath 按 BOM 解码 UTF-16 后再交给资源扫描与渲染', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const source = '<html><head><title>季度报告</title></head><body><p>正文内容</p></body></html>';
+ await fs.writeFile(
+ path.join(workdir, 'utf16.html'),
+ Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(source, 'utf16le')]),
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'utf16.html',
+ outPath: 'utf16.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ expect((result.artifact as Record<string, unknown>).title).toBe('季度报告');
+ expect(Buffer.from(seen[0]!.htmlBytes!).toString('utf8')).toBe(source);
+ });
+
+ it('htmlPath 不是受支持的有效 Unicode 编码时明确拒绝', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({ buffer: pdfBytes, fontsReady: true }));
+ await fs.writeFile(
+ path.join(workdir, 'invalid-encoding.html'),
+ Buffer.from([0x3c, 0x70, 0x3e, 0x80, 0x3c, 0x2f, 0x70, 0x3e]),
+ );
+ const client = await connect({ renderHtmlToPdf });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'invalid-encoding.html',
+ outPath: 'invalid-encoding.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('UNSUPPORTED_ENCODING');
+ expect((result.data as Record<string, string>).hint).toContain('UTF-8');
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('htmlPath 的任务目录图片与样式表先快照成 data URI', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'style.css'),
+ '.hero { background-image: url("./chart.png"); }',
+ 'utf8',
+ );
+ await fs.writeFile(path.join(workdir, 'theme.css'), 'body { color: #123456; }', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'src.html'),
+ '<html><head><link rel="stylesheet" href="./style.css"><style>@import "./theme.css";</style></head><body><img src="./chart.png" srcset="./chart.png 1x,./chart.png 2x"></body></html>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'src.html',
+ outPath: 'snapshotted.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('data:image/png;base64,');
+ expect(rendered).toContain('data:text/css;base64,');
+ expect(rendered).not.toContain('./chart.png');
+ expect(rendered).not.toContain('./theme.css');
+ expect(Object.prototype.hasOwnProperty.call(seen[0], 'htmlBaseDir')).toBe(false);
+ });
+
+ it('按 BOM 或 @charset 解码本地 CSS 并移除旧编码声明', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, '图.png'), 'utf16-image', 'utf8');
+ await fs.writeFile(path.join(workdir, 'café.png'), 'legacy-image', 'utf8');
+ const utf16Css = '@charset "utf-16le"; .标题 { background: url("./图.png"); }';
+ await fs.writeFile(
+ path.join(workdir, 'utf16.css'),
+ Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(utf16Css, 'utf16le')]),
+ );
+ await fs.writeFile(
+ path.join(workdir, 'legacy.css'),
+ Buffer.from('@charset "windows-1252"; .café { background: url("./café.png"); }', 'latin1'),
+ );
+ await fs.writeFile(
+ path.join(workdir, 'encoded-css.html'),
+ '<link rel="stylesheet" href="./utf16.css"><link rel="stylesheet" href="./legacy.css">',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'encoded-css.html',
+ outPath: 'encoded-css.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ const stylesheets = [...rendered.matchAll(/data:text\/css;base64,([^"'&>\s]+)/g)].map(
+ (match) => Buffer.from(match[1]!, 'base64').toString('utf8'),
+ );
+ expect(stylesheets).toHaveLength(2);
+ expect(stylesheets.join('\n')).toContain('.标题');
+ expect(stylesheets.join('\n')).toContain('.café');
+ expect(stylesheets.join('\n')).not.toContain('@charset');
+ expect(stylesheets.join('\n')).toContain(
+ `data:image/png;base64,${Buffer.from('utf16-image').toString('base64')}`,
+ );
+ expect(stylesheets.join('\n')).toContain(
+ `data:image/png;base64,${Buffer.from('legacy-image').toString('base64')}`,
+ );
+ });
+
+ it('按 srcset 语法分割无空格候选并保留 data URL 内部逗号', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'small.png'), 'small-image', 'utf8');
+ await fs.writeFile(path.join(workdir, 'large.png'), 'large-image', 'utf8');
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ html:
+ '<img srcset="./small.png,./large.png 2x"><source srcset="data:image/png;base64,AAAA 1x,./large.png 2x">',
+ outPath: 'compact-srcset.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = seen[0]!.html!;
+ expect(rendered).toContain(
+ `data:image/png;base64,${Buffer.from('small-image').toString('base64')}`,
+ );
+ expect(rendered.match(new RegExp(Buffer.from('large-image').toString('base64'), 'g'))).toHaveLength(
+ 2,
+ );
+ expect(rendered).toContain('data:image/png;base64,AAAA 1x');
+ });
+
+ it('内联 html 的任务目录图片与样式表同样先快照成 data URI', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(path.join(workdir, 'style.css'), '.hero { color: red; }', 'utf8');
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ html: '<link rel="stylesheet" href="./style.css"><img src="./chart.png">',
+ outPath: 'inline-snapshotted.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ expect(seen[0]!.htmlBytes).toBeUndefined();
+ expect(seen[0]!.html).toContain('data:image/png;base64,');
+ expect(seen[0]!.html).toContain('data:text/css;base64,');
+ expect(seen[0]!.html).not.toContain('./chart.png');
+ expect(seen[0]!.html).not.toContain('./style.css');
+ });
+
+ it('渲染前拒绝 HTML、CSS 与 base 中的显式 file URL', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({ buffer: pdfBytes, fontsReady: true }));
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(path.join(workdir, 'style.css'), '.hero { color: red; }', 'utf8');
+ const imageUrl = pathToFileURL(path.join(workdir, 'chart.png')).href;
+ const styleUrl = pathToFileURL(path.join(workdir, 'style.css')).href;
+ const baseUrl = pathToFileURL(`${workdir}${path.sep}`).href;
+ const cases = [
+ `<img src="${imageUrl}">`,
+ `<style>.hero { background: url("${imageUrl}"); }</style>`,
+ `<link rel="stylesheet" href="${styleUrl}">`,
+ `<base href="${baseUrl}"><img src="./chart.png">`,
+ ];
+ const client = await connect({ renderHtmlToPdf });
+
+ for (const [index, html] of cases.entries()) {
+ const result = await callTool(client, 'render_pdf', {
+ html,
+ outPath: `explicit-file-${index}.pdf`,
+ template: 'none',
+ });
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ await expect(fs.stat(path.join(workdir, `explicit-file-${index}.pdf`))).rejects.toThrow();
+ }
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('渲染前拒绝会被宿主阻断的公网资源', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({ buffer: pdfBytes, fontsReady: true }));
+ const cases = [
+ '<img src="https://cdn.example/chart.png">',
+ '<img src="//cdn.example/chart.png">',
+ '<link rel="stylesheet" href="https://cdn.example/theme.css">',
+ '<style>.hero { background: url("https://cdn.example/chart.png"); }</style>',
+ '<base href="https://cdn.example/"><img src="./chart.png">',
+ ];
+ const client = await connect({ renderHtmlToPdf });
+
+ for (const [index, html] of cases.entries()) {
+ const result = await callTool(client, 'render_pdf', {
+ html,
+ outPath: `blocked-remote-${index}.pdf`,
+ template: 'none',
+ });
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ expect((result.data as Record<string, string>).hint).toContain('阻断');
+ await expect(fs.stat(path.join(workdir, `blocked-remote-${index}.pdf`))).rejects.toThrow();
+ }
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('HTML 读取后源目录被重绑时拒绝混合目录版本的资源', async () => {
+ const sourceDir = path.join(workdir, 'source');
+ const movedDir = path.join(workdir, 'source-original');
+ await fs.mkdir(sourceDir);
+ await fs.writeFile(path.join(sourceDir, 'chart.png'), 'original-chart', 'utf8');
+ await fs.writeFile(path.join(sourceDir, 'src.html'), '<img src="./chart.png">', 'utf8');
+ const originalStat = fs.stat.bind(fs);
+ let swapped = false;
+ vi.spyOn(fs, 'stat').mockImplementation(async (target, options) => {
+ if (!swapped && String(target).endsWith(`${path.sep}chart.png`)) {
+ swapped = true;
+ await fs.rename(sourceDir, movedDir);
+ await fs.mkdir(sourceDir);
+ await fs.writeFile(path.join(sourceDir, 'chart.png'), 'replacement-chart', 'utf8');
+ await fs.writeFile(path.join(sourceDir, 'src.html'), '<img src="./chart.png">', 'utf8');
+ }
+ return originalStat(target, options as never);
+ });
+ const client = await connect({
+ renderHtmlToPdf: async () => ({ buffer: pdfBytes, fontsReady: true }),
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'source/src.html',
+ outPath: 'rebound.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ });
+
+ it('HTML 属性值含 > 时仍完整快照资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'quoted-tag.html'),
+ '<img alt="1 > 0" src="./chart.png">',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'quoted-tag.html',
+ outPath: 'quoted-tag.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('data:image/png;base64,');
+ expect(rendered).not.toContain('./chart.png');
+ });
+
+ it('CSS 注释与字符串里的 url 不被误当成本地资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(
+ path.join(workdir, 'css-safe.html'),
+ '<style>/* background: url(./missing.png) */ body::before { content: "url(./missing.png)"; }</style>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'css-safe.html',
+ outPath: 'css-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ expect(Buffer.from(seen[0]!.htmlBytes!).toString('utf8')).toContain('./missing.png');
+ });
+
+ it('按 CSS token 跳过 url 函数名后的注释', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'commented-url-image', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'css-url-comment.html'),
+ '<style>.hero { background: url/* asset */("./chart.png"); }</style>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'css-url-comment.html',
+ outPath: 'css-url-comment.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain(
+ `data:image/png;base64,${Buffer.from('commented-url-image').toString('base64')}`,
+ );
+ expect(rendered).not.toContain('./chart.png');
+ });
+
+ it('只在 CSS 标识符边界识别 url 函数', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'css-url-boundary.html'),
+ '<style>:root { --example: myurl("./missing.png"); } .escaped { background: u\\72l("./chart.png"); } .real { background: url("./chart.png"); }</style>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'css-url-boundary.html',
+ outPath: 'css-url-boundary.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('myurl("./missing.png")');
+ expect(rendered.match(/data:image\/png;base64,/g)).toHaveLength(2);
+ expect(rendered).not.toContain('u\\72l("./chart.png")');
+ });
+
+ it('按 CSS token 语义解码本地资源 URL 的转义', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'my image.png'), 'escaped-space', 'utf8');
+ await fs.writeFile(path.join(workdir, 'hex name.png'), 'hex-space', 'utf8');
+ await fs.writeFile(path.join(workdir, 'linewrap.png'), 'continued-line', 'utf8');
+ const css = [
+ '.space { background: url("./my\\ image.png"); }',
+ '.hex { background: url("./hex\\20 name.png"); }',
+ '.continued { background: url("./line\\' + '\n' + 'wrap.png"); }',
+ ].join('\n');
+ await fs.writeFile(path.join(workdir, 'css-escapes.html'), `<style>${css}</style>`, 'utf8');
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'css-escapes.html',
+ outPath: 'css-escapes.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ for (const contents of ['escaped-space', 'hex-space', 'continued-line']) {
+ expect(rendered).toContain(
+ `data:image/png;base64,${Buffer.from(contents).toString('base64')}`,
+ );
+ }
+ });
+
+ it('只在真实 HTML 开始标签内重写 style 属性', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(
+ path.join(workdir, 'style-safe.html'),
+ `<script>const sample = ' style="background:url(./missing.png)"';</script><p>ok</p>`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'style-safe.html',
+ outPath: 'style-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('<p>ok</p>');
+ expect(rendered).toContain('./missing.png');
+ });
+
+ it('不把 script 内 tag-shaped 字符串当成真实资源标签', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(
+ path.join(workdir, 'raw-text-safe.html'),
+ `<script>const sample = '<img src="./missing.png">';</script><p>ok</p>`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'raw-text-safe.html',
+ outPath: 'raw-text-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('<img src="./missing.png">');
+ });
+
+ it('启用脚本时不快照 noscript 内的图片与样式资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(
+ path.join(workdir, 'noscript-safe.html'),
+ `<noscript><img src="./missing.png"><style>.fallback{background:url(./missing-bg.png)}</style></noscript><p>ok</p>`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'noscript-safe.html',
+ outPath: 'noscript-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('<img src="./missing.png">');
+ expect(rendered).toContain('url(./missing-bg.png)');
+ expect(rendered).toContain('<p>ok</p>');
+ });
+
+ it('不快照其它 HTML raw-text 元素里的资源形状文本', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const rawText = ['iframe', 'noembed', 'noframes', 'xmp']
+ .map(
+ (tag) =>
+ `<${tag}><img src="./missing-${tag}.png"><style>.x{background:url(./missing-${tag}-bg.png)}</style></${tag}>`,
+ )
+ .join('');
+ await fs.writeFile(
+ path.join(workdir, 'other-raw-text-safe.html'),
+ `${rawText}<p>ok</p>`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'other-raw-text-safe.html',
+ outPath: 'other-raw-text-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('./missing-iframe.png');
+ expect(rendered).toContain('url(./missing-xmp-bg.png)');
+ expect(rendered).toContain('<p>ok</p>');
+ });
+
+ it('不快照未实例化 template 子树内的图片与样式资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'template-safe.html'),
+ `<template><script>const sample = '<template><img src="./fake.png"></template>';</script><img src="./missing.png"><style>.unused{background:url(./missing-bg.png)}</style><template><img src="./nested-missing.png"></template></template><p>ok</p><img src="./chart.png">`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'template-safe.html',
+ outPath: 'template-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('./missing.png');
+ expect(rendered).toContain('url(./missing-bg.png)');
+ expect(rendered).toContain('./nested-missing.png');
+ expect(rendered).toContain('<p>ok</p>');
+ expect(rendered).toContain('data:image/png;base64,');
+ });
+
+ it('只处理真实 style 元素,不处理脚本与注释中的 style 形状文本', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'style-raw-text-safe.html'),
+ `<script>const sample = '<style>.x{background:url(./missing.png)}</style>';</script><!-- <style>.x{background:url(./missing.png)}</style> --><style>.real{background:url(./chart.png)}</style>`,
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'style-raw-text-safe.html',
+ outPath: 'style-raw-text-safe.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('./missing.png');
+ expect(rendered).toContain('data:image/png;base64,');
+ });
+
+ it('按 HTML base href 解析相对资源而不是固定使用 HTML 同目录', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.mkdir(path.join(workdir, 'assets'));
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'root-chart', 'utf8');
+ await fs.writeFile(path.join(workdir, 'assets/chart.png'), 'assets-chart', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'base.html'),
+ '<base href="assets/"><img src="chart.png">',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'base.html',
+ outPath: 'base.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain(
+ `data:image/png;base64,${Buffer.from('assets-chart').toString('base64')}`,
+ );
+ expect(rendered).not.toContain(Buffer.from('root-chart').toString('base64'));
+ });
+
+ it('按 HTML 属性语义解码命名与数字实体后快照本地资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ const assets = path.join(workdir, 'R&D');
+ await fs.mkdir(assets);
+ await fs.writeFile(path.join(assets, 'theme.css'), 'body{color:red}', 'utf8');
+ await fs.writeFile(path.join(assets, '©.png'), 'named-image', 'utf8');
+ await fs.writeFile(path.join(assets, 'chart.png'), 'numeric-image', 'utf8');
+ await fs.writeFile(path.join(assets, 'chart&copy.png'), 'style-image', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'attribute-entities.html'),
+ '<base href="./R&amp;D/"><link rel=stylesheet href=theme&#46;css><img src="&copy;.png" srcset="chart&#x2e;png 1x"><div style="background:url(chart&amp;copy.png)"></div>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'attribute-entities.html',
+ outPath: 'attribute-entities.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain(
+ `data:text/css;base64,${Buffer.from('body{color:red}').toString('base64')}`,
+ );
+ for (const contents of ['named-image', 'numeric-image', 'style-image']) {
+ expect(rendered).toContain(
+ `data:image/png;base64,${Buffer.from(contents).toString('base64')}`,
+ );
+ }
+ });
+
+ it('解码 stylesheet rel 实体并以内联 CSS MIME 快照无扩展名样式表', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'theme'), 'body{color:purple}', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'encoded-rel.html'),
+ '<link rel="style&#115;heet" href="./theme"><p>ok</p>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'encoded-rel.html',
+ outPath: 'encoded-rel.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain(
+ `data:text/css;base64,${Buffer.from('body{color:purple}').toString('base64')}`,
+ );
+ });
+
+ it('重写内联 style 后按原引号重新转义 HTML 属性值', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'style-entities.html'),
+ '<div style="font-family:&quot;Arial&quot;;background:url(&quot;./chart.png&quot;)">ok</div>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'style-entities.html',
+ outPath: 'style-entities.pdf',
+ template: 'none',
+ });
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('font-family:&quot;Arial&quot;');
+ expect(rendered).toContain('background:url(&quot;data:image/png;base64,');
+ expect(rendered).not.toContain('style="font-family:"Arial""');
+ });
+
+ it('在首个资源快照前替换 base 子目录时拒绝混合目录版本', async () => {
+ const assetsDir = path.join(workdir, 'assets');
+ const movedDir = path.join(workdir, 'assets-original');
+ await fs.mkdir(assetsDir);
+ await fs.writeFile(path.join(assetsDir, 'chart.png'), 'original-chart', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'base-rebound.html'),
+ '<base href="assets/"><img src="chart.png">',
+ 'utf8',
+ );
+
+ const originalStat = fs.stat.bind(fs);
+ let swapped = false;
+ vi.spyOn(fs, 'stat').mockImplementation(async (target, options) => {
+ if (!swapped && String(target).endsWith(`${path.sep}assets${path.sep}chart.png`)) {
+ swapped = true;
+ await fs.rename(assetsDir, movedDir);
+ await fs.mkdir(assetsDir);
+ await fs.writeFile(path.join(assetsDir, 'chart.png'), 'replacement-chart', 'utf8');
+ }
+ return originalStat(target, options as never);
+ });
+
+ const client = await connect({
+ renderHtmlToPdf: async () => ({ buffer: pdfBytes, fontsReady: true }),
+ });
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'base-rebound.html',
+ outPath: 'base-rebound.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('PATH_NOT_ALLOWED');
+ });
+
+ it('快照 SVG image 的 href 与 xlink:href 本地资源', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'svg.html'),
+ '<svg><image href="./chart.png"/><image xlink:href=./chart.png /></svg>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'svg.html',
+ outPath: 'svg.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered.match(/data:image\/png;base64,/g)).toHaveLength(2);
+ expect(rendered).not.toContain('./chart.png');
+ });
+
+ it('快照 SVG use 的 href 与 xlink:href 并保留片段', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(
+ path.join(workdir, 'icons.svg'),
+ '<svg><symbol id="check"><path d="M0 0h1v1z"/></symbol></svg>',
+ 'utf8',
+ );
+ await fs.writeFile(
+ path.join(workdir, 'svg-use.html'),
+ '<svg><use href="./icons.svg#check"/><use xlink:href=./icons.svg#check /></svg>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'svg-use.html',
+ outPath: 'svg-use.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered.match(/data:image\/svg\+xml;base64,[^\s"']+#check/g)).toHaveLength(2);
+ expect(rendered).not.toContain('./icons.svg');
+ });
+
+ it('快照未加引号的本地资源属性', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'chart.png'), 'png-bytes', 'utf8');
+ await fs.writeFile(path.join(workdir, 'style.css'), 'body { color: red; }', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'unquoted.html'),
+ '<html><head><link rel=stylesheet href=./style.css></head><body><img src=./chart.png poster=./chart.png data=./chart.png srcset=./chart.png><source srcset=./chart.png></body></html>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'unquoted.html',
+ outPath: 'unquoted.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ expect(rendered).toContain('data:image/png;base64,');
+ expect(rendered).toContain('data:text/css;base64,');
+ expect(rendered).not.toContain('./chart.png');
+ expect(rendered).not.toContain('./style.css');
+ });
+
+ it('限制重复本地资源展开后的 HTML 快照大小', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({
+ buffer: pdfBytes,
+ fontsReady: true,
+ }));
+ await fs.writeFile(path.join(workdir, 'repeat.png'), Buffer.alloc(512 * 1024, 0x61));
+ const repeatedImages = Array.from({ length: 100 }, () => '<img src="./repeat.png">').join('');
+ await fs.writeFile(
+ path.join(workdir, 'repeated.html'),
+ `<html><body>${repeatedImages}</body></html>`,
+ 'utf8',
+ );
+ const client = await connect({ renderHtmlToPdf });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'repeated.html',
+ outPath: 'repeated.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('FILE_TOO_LARGE');
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('限制本地资源引用次数并缓存重复引用', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({
+ buffer: pdfBytes,
+ fontsReady: true,
+ }));
+ await fs.writeFile(path.join(workdir, 'tiny.png'), 'x', 'utf8');
+ const repeatedImages = Array.from({ length: 4_097 }, () => '<img src="./tiny.png">').join('');
+ const client = await connect({ renderHtmlToPdf });
+
+ const result = await callTool(client, 'render_pdf', {
+ html: repeatedImages,
+ outPath: 'too-many-resource-references.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('FILE_TOO_LARGE');
+ expect((result.data as Record<string, string>).hint).toContain('4096');
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('递归快照 CSS 的本地 @import 并将 URL 形式标记为 text/css', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'theme.css'), 'body { color: #123456; }', 'utf8');
+ await fs.writeFile(path.join(workdir, 'theme'), '.hero { color: #654321; }', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'style.css'),
+ '@import "./theme.css"; @import url("./theme"); .hero { color: red; }',
+ 'utf8',
+ );
+ await fs.writeFile(
+ path.join(workdir, 'import.html'),
+ '<html><head><link rel="stylesheet" href="./style.css"></head><body>ok</body></html>',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ htmlPath: 'import.html',
+ outPath: 'import.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = Buffer.from(seen[0]!.htmlBytes!).toString('utf8');
+ const quotedTheme = `data:text/css;base64,${Buffer.from(
+ 'body { color: #123456; }',
+ ).toString('base64')}`;
+ const urlTheme = `data:text/css;base64,${Buffer.from(
+ '.hero { color: #654321; }',
+ ).toString('base64')}`;
+ const rewrittenCss = `@import url("${quotedTheme}"); @import url("${urlTheme}"); .hero { color: red; }`;
+ expect(rendered).toContain(
+ `data:text/css;base64,${Buffer.from(rewrittenCss).toString('base64')}`,
+ );
+ });
+
+ it('按 CSS token 跳过 @import 后的注释', async () => {
+ const seen: DocsPdfRenderInput[] = [];
+ await fs.writeFile(path.join(workdir, 'theme.css'), '.hero { color: #654321; }', 'utf8');
+ await fs.writeFile(
+ path.join(workdir, 'style-with-comment.css'),
+ '@import /* theme */ "./theme.css"; .hero { color: red; }',
+ 'utf8',
+ );
+ const client = await connect({
+ renderHtmlToPdf: async (input) => {
+ seen.push(input);
+ return { buffer: pdfBytes, fontsReady: true };
+ },
+ });
+
+ const result = await callTool(client, 'render_pdf', {
+ html: '<link rel="stylesheet" href="./style-with-comment.css">',
+ outPath: 'import-comment.pdf',
+ template: 'none',
+ });
+
+ expect(result.ok).toBe(true);
+ const rendered = seen[0]!.html!;
+ const stylesheet = rendered.match(/data:text\/css;base64,([^"'&>\s]+)/)?.[1];
+ expect(stylesheet).toBeDefined();
+ const decodedStylesheet = Buffer.from(stylesheet!, 'base64').toString('utf8');
+ expect(decodedStylesheet).toContain(
+ `data:text/css;base64,${Buffer.from('.hero { color: #654321; }').toString('base64')}`,
+ );
+ expect(decodedStylesheet).not.toContain('./theme.css');
+ });
+
+ it('htmlPath 与 html 必须二选一', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => ({ buffer: pdfBytes, fontsReady: true }),
+ });
+ expect((await callTool(client, 'render_pdf', { outPath: 'a.pdf' })).errorCode).toBe(
+ 'INVALID_ARGS',
+ );
+ expect(
+ (
+ await callTool(client, 'render_pdf', {
+ outPath: 'a.pdf',
+ html: '<p/>',
+ htmlPath: 'x.html',
+ })
+ ).errorCode,
+ ).toBe('INVALID_ARGS');
+ });
+
+ it('htmlPath 与内联 html 都在主进程读取前执行同一大小上限', async () => {
+ const renderHtmlToPdf = vi.fn(async () => ({
+ buffer: pdfBytes,
+ fontsReady: true,
+ }));
+ const client = await connect({ renderHtmlToPdf });
+
+ const hugePath = path.join(workdir, 'huge.html');
+ const handle = await fs.open(hugePath, 'w');
+ await handle.truncate(RENDER_PDF_MAX_HTML_BYTES + 1);
+ await handle.close();
+
+ expect(
+ (
+ await callTool(client, 'render_pdf', {
+ htmlPath: 'huge.html',
+ outPath: 'path.pdf',
+ })
+ ).errorCode,
+ ).toBe('FILE_TOO_LARGE');
+ expect(
+ (
+ await callTool(client, 'render_pdf', {
+ html: 'x'.repeat(RENDER_PDF_MAX_HTML_BYTES + 1),
+ outPath: 'inline.pdf',
+ })
+ ).errorCode,
+ ).toBe('FILE_TOO_LARGE');
+ expect(renderHtmlToPdf).not.toHaveBeenCalled();
+ });
+
+ it('空产物报 RENDER_EMPTY,超小产物带回验告警', async () => {
+ const empty = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.alloc(0),
+ fontsReady: true,
+ }),
+ });
+ expect(
+ (await callTool(empty, 'render_pdf', { html: '<p/>', outPath: 'a.pdf' })).errorCode,
+ ).toBe('RENDER_EMPTY');
+
+ const tiny = await connect({
+ renderHtmlToPdf: async () => ({
+ buffer: Buffer.from('%PDF-1.7'),
+ fontsReady: true,
+ }),
+ });
+ const result = await callTool(tiny, 'render_pdf', {
+ html: '<p/>',
+ outPath: 'b.pdf',
+ });
+ expect(result.ok).toBe(true);
+ expect(result.warning).toContain('白页');
+ });
+
+ it('超时被归成 RENDER_TIMEOUT,其余失败归 RENDER_FAILED', async () => {
+ const timeout = await connect({
+ renderHtmlToPdf: async () => {
+ throw new Error('HTML 渲染超时(30000ms timeout)');
+ },
+ });
+ const timedOut = await callTool(timeout, 'render_pdf', {
+ html: '<p/>',
+ outPath: 'a.pdf',
+ });
+ expect(timedOut.errorCode).toBe('RENDER_TIMEOUT');
+
+ const failed = await connect({
+ renderHtmlToPdf: async () => {
+ throw new Error('render process gone');
+ },
+ });
+ expect(
+ (await callTool(failed, 'render_pdf', { html: '<p/>', outPath: 'a.pdf' })).errorCode,
+ ).toBe('RENDER_FAILED');
+ });
+
+ it('渲染失败时不留下空文件', async () => {
+ const client = await connect({
+ renderHtmlToPdf: async () => {
+ throw new Error('boom');
+ },
+ });
+ await callTool(client, 'render_pdf', { html: '<p/>', outPath: 'a.pdf' });
+ await expect(fs.stat(path.join(workdir, 'a.pdf'))).rejects.toThrow();
+ });
+});
+
+describe('inspect_pdf', () => {
+ const page = (over: Partial<DocsPdfPageInspection> = {}): DocsPdfPageInspection => ({
+ page: 1,
+ width: 595.28,
+ height: 841.89,
+ rotation: 0,
+ textChars: 120,
+ textPreview: '季度经营回顾',
+ drawOps: 42,
+ imageOps: 1,
+ blank: false,
+ visibilityUnverified: false,
+ ...over,
+ });
+
+ async function withPdf(
+ inspection: DocsPdfInspection,
+ bytes = Buffer.from(`%PDF-1.7\n${'x'.repeat(5000)}`),
+ ) {
+ const client = await connect({ inspectPdf: async () => inspection });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), bytes);
+ return client;
+ }
+
+ it('把结构翻译成可判读的结论:纸张名 + 空白页 + verdict', async () => {
+ const client = await withPdf({
+ numPages: 2,
+ pagesInspected: 2,
+ pages: [page(), page({ page: 2, textChars: 0, drawOps: 0, imageOps: 0, blank: true })],
+ });
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.ok).toBe(true);
+ expect(result.numPages).toBe(2);
+ expect(result.blankPages).toEqual([2]);
+ expect(result.verdict).toBe('partial-blank');
+ expect(result.warning).toContain('第 2 页');
+ const pages = result.pages as Array<Record<string, unknown>>;
+ expect(pages[0]!.paper).toBe('A4');
+ });
+
+ it('整份全空白给出"不能交付"的结论', async () => {
+ const client = await withPdf({
+ numPages: 1,
+ pagesInspected: 1,
+ pages: [page({ textChars: 0, drawOps: 0, imageOps: 0, blank: true })],
+ });
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.verdict).toBe('blank');
+ expect(result.warning).toContain('不能交付');
+ });
+
+ it('全部正常时 verdict=ok 且没有告警', async () => {
+ const client = await withPdf({
+ numPages: 1,
+ pagesInspected: 1,
+ pages: [page()],
+ });
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.verdict).toBe('ok');
+ expect(result.warning).toBeUndefined();
+ expect(result.blankPages).toEqual([]);
+ });
+
+ it('只检查部分页时返回 incomplete 并给出下一批页码', async () => {
+ const client = await withPdf({
+ numPages: 12,
+ pagesInspected: 10,
+ pages: Array.from({ length: 10 }, (_, index) => page({ page: index + 1 })),
+ });
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.verdict).toBe('incomplete');
+ expect(result.inspectedThrough).toBe(10);
+ expect(result.nextPages).toEqual([11, 12]);
+ expect(result.warning).toContain('11、12');
+ expect(result.verdict).not.toBe('ok');
+ });
+
+ it('连续检查多批 PDF 页面时 nextPages 沿游标前进', async () => {
+ const client = await connect({
+ inspectPdf: async ({ pages }) => {
+ const selected =
+ pages.length > 0 ? pages : Array.from({ length: 10 }, (_, index) => index + 1);
+ return {
+ numPages: 30,
+ pagesInspected: selected.length,
+ pages: selected.map((pageNumber) => page({ page: pageNumber })),
+ };
+ },
+ });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from(`%PDF-1.7\n${'x'.repeat(5000)}`));
+
+ const first = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(first.inspectedThrough).toBe(10);
+ expect(first.nextPages).toEqual([11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
+ const missingPreviousVerdict = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: first.nextPages,
+ inspectedThrough: first.inspectedThrough,
+ });
+ expect(missingPreviousVerdict.ok).toBe(false);
+ expect(missingPreviousVerdict.errorCode).toBe('INVALID_ARGS');
+ const second = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: first.nextPages,
+ inspectedThrough: first.inspectedThrough,
+ previousVerdict: first.verdict,
+ previousPdfSha256: first.pdfSha256,
+ });
+ expect(second.inspectedThrough).toBe(20);
+ expect(second.nextPages).toEqual([21, 22, 23, 24, 25, 26, 27, 28, 29, 30]);
+ const third = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: second.nextPages,
+ inspectedThrough: second.inspectedThrough,
+ previousVerdict: second.verdict,
+ previousPdfSha256: second.pdfSha256,
+ });
+ expect(third.inspectedThrough).toBe(30);
+ expect(third.nextPages).toBeUndefined();
+ expect(third.verdict).toBe('ok');
+ });
+
+ it('最后一批正常时仍保留此前批次发现的空白页与未验证结论', async () => {
+ const scenarios = [
+ {
+ verdict: 'partial-blank',
+ warning: '此前批次已发现空白页',
+ problemPage: page({ page: 5, textChars: 0, drawOps: 0, imageOps: 0, blank: true }),
+ },
+ {
+ verdict: 'warning',
+ warning: '此前批次存在结构算子解析未完成的页面',
+ problemPage: page({
+ page: 5,
+ textChars: 0,
+ drawOps: null,
+ imageOps: null,
+ blank: false,
+ visibilityUnverified: true,
+ }),
+ },
+ ] as const;
+
+ for (const scenario of scenarios) {
+ const client = await connect({
+ inspectPdf: async ({ pages }) => {
+ const selected =
+ pages.length > 0 ? pages : Array.from({ length: 10 }, (_, index) => index + 1);
+ return {
+ numPages: 30,
+ pagesInspected: selected.length,
+ pages: selected.map((pageNumber) =>
+ pageNumber === 5 ? scenario.problemPage : page({ page: pageNumber }),
+ ),
+ };
+ },
+ });
+ await fs.writeFile(
+ path.join(workdir, 'out.pdf'),
+ Buffer.from(`%PDF-1.7\n${'x'.repeat(5000)}`),
+ );
+
+ const first = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(first.verdict).toBe(scenario.verdict);
+ const second = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: first.nextPages,
+ inspectedThrough: first.inspectedThrough,
+ previousVerdict: first.verdict,
+ previousPdfSha256: first.pdfSha256,
+ });
+ const third = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: second.nextPages,
+ inspectedThrough: second.inspectedThrough,
+ previousVerdict: second.verdict,
+ previousPdfSha256: second.pdfSha256,
+ });
+
+ expect(third.inspectedThrough).toBe(30);
+ expect(third.verdict).toBe(scenario.verdict);
+ expect(third.warning).toContain(scenario.warning);
+ expect(third.verdict).not.toBe('ok');
+ }
+ });
+
+ it('算子表未能解析时 verdict 不得误报 ok', async () => {
+ const client = await withPdf({
+ numPages: 1,
+ pagesInspected: 1,
+ pages: [
+ page({
+ textChars: 0,
+ drawOps: null,
+ imageOps: null,
+ blank: false,
+ visibilityUnverified: true,
+ }),
+ ],
+ });
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.verdict).toBe('warning');
+ expect(result.warning).toContain('未做位图级可见性确认');
+ expect(result.verdict).not.toBe('ok');
+ });
+
+ it('横向与非标准纸张都翻译成人能对照的说法', async () => {
+ const client = await withPdf({
+ numPages: 2,
+ pagesInspected: 2,
+ pages: [page({ width: 841.89, height: 595.28 }), page({ page: 2, width: 300, height: 300 })],
+ });
+ const pages = (await callTool(client, 'inspect_pdf', { path: 'out.pdf' })).pages as Array<
+ Record<string, unknown>
+ >;
+ expect(pages[0]!.paper).toBe('A4 landscape');
+ expect(pages[1]!.paper).toBe('4.17×4.17 in');
+ });
+
+ it('页码与上限原样透传给 host', async () => {
+ const seen: unknown[] = [];
+ const client = await connect({
+ inspectPdf: async (input) => {
+ seen.push(input);
+ return { numPages: 9, pagesInspected: 0, pages: [] };
+ },
+ });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from('%PDF-1.7 body'));
+ await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: [1, 5],
+ maxPages: 3,
+ });
+ expect(seen[0]).toMatchObject({
+ pages: [1, 5],
+ maxPages: 3,
+ timeoutMs: 15_000,
+ });
+ });
+
+ it('在 schema 阶段拒绝超过单批上限的页码数组', async () => {
+ const inspectPdf = vi.fn(async () => ({ numPages: 1, pagesInspected: 1, pages: [page()] }));
+ const client = await connect({ inspectPdf });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from('%PDF-1.7 body'));
+
+ const result = await client.callTool({
+ name: 'inspect_pdf',
+ arguments: {
+ path: 'out.pdf',
+ pages: Array.from({ length: 51 }, (_, index) => index + 1),
+ },
+ });
+
+ expect((result as { content: Array<{ text: string }> }).content[0]!.text).toContain(
+ 'MCP error -32602',
+ );
+ expect(inspectPdf).not.toHaveBeenCalled();
+ });
+
+ it('PDF 在分批检查期间变化时拒绝累计旧文件结果', async () => {
+ const inspectPdf = vi.fn(async ({ pages }: { pages: number[] }) => {
+ const selected =
+ pages.length > 0 ? pages : Array.from({ length: 10 }, (_, index) => index + 1);
+ return {
+ numPages: 20,
+ pagesInspected: selected.length,
+ pages: selected.map((pageNumber) => page({ page: pageNumber })),
+ };
+ });
+ const client = await connect({ inspectPdf });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from(`%PDF-1.7\nold-${'x'.repeat(5000)}`));
+
+ const first = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from(`%PDF-1.7\nnew-${'x'.repeat(5000)}`));
+ const second = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: first.nextPages,
+ inspectedThrough: first.inspectedThrough,
+ previousVerdict: first.verdict,
+ previousPdfSha256: first.pdfSha256,
+ });
+
+ expect(second.ok).toBe(false);
+ expect(second.errorCode).toBe('PDF_CHANGED');
+ expect((second.data as Record<string, string>).hint).toContain('从第 1 页重新检查');
+ expect(inspectPdf).toHaveBeenCalledTimes(1);
+ });
+
+ it('指定页码全部越界时不把零页检查误报为 ok', async () => {
+ const client = await withPdf({ numPages: 3, pagesInspected: 0, pages: [] });
+ const result = await callTool(client, 'inspect_pdf', {
+ path: 'out.pdf',
+ pages: [99],
+ });
+
+ expect(result.ok).toBe(false);
+ expect(result.errorCode).toBe('NO_PAGES_INSPECTED');
+ expect((result.data as Record<string, unknown>).numPages).toBe(3);
+ });
+
+ it('0 字节的 PDF 直接判定生成失败', async () => {
+ const client = await withPdf({ numPages: 0, pagesInspected: 0, pages: [] }, Buffer.alloc(0));
+ const result = await callTool(client, 'inspect_pdf', { path: 'out.pdf' });
+ expect(result.errorCode).toBe('EMPTY_FILE');
+ });
+
+ it('超限 PDF 在交给解析进程前按 stat 拒绝', async () => {
+ const inspectPdf = vi.fn(async () => ({
+ numPages: 0,
+ pagesInspected: 0,
+ pages: [],
+ }));
+ const client = await connect({ inspectPdf });
+ const hugePath = path.join(workdir, 'huge.pdf');
+ const handle = await fs.open(hugePath, 'w');
+ await handle.truncate(64 * 1024 * 1024 + 1);
+ await handle.close();
+
+ const result = await callTool(client, 'inspect_pdf', { path: 'huge.pdf' });
+ expect(result.errorCode).toBe('FILE_TOO_LARGE');
+ expect(inspectPdf).not.toHaveBeenCalled();
+ });
+
+ it('非 pdf 扩展名与越界路径都被拒', async () => {
+ const client = await connect({
+ inspectPdf: async () => ({ numPages: 0, pagesInspected: 0, pages: [] }),
+ });
+ await fs.writeFile(path.join(workdir, 'a.txt'), 'x');
+ expect((await callTool(client, 'inspect_pdf', { path: 'a.txt' })).errorCode).toBe(
+ 'UNSUPPORTED_FORMAT',
+ );
+ expect((await callTool(client, 'inspect_pdf', { path: '../x.pdf' })).errorCode).toBe(
+ 'PATH_NOT_ALLOWED',
+ );
+ });
+
+ it('解析超时与解析失败分开归类', async () => {
+ await fs.writeFile(path.join(workdir, 'out.pdf'), Buffer.from('%PDF-1.7 body'));
+ const timeout = await connect({
+ inspectPdf: async () => {
+ throw new Error('PDF extraction timed out in the isolated process');
+ },
+ });
+ expect((await callTool(timeout, 'inspect_pdf', { path: 'out.pdf' })).errorCode).toBe(
+ 'INSPECT_TIMEOUT',
+ );
+
+ const broken = await connect({
+ inspectPdf: async () => {
+ throw new Error('InvalidPDFException');
+ },
+ });
+ const failed = await callTool(broken, 'inspect_pdf', { path: 'out.pdf' });
+ expect(failed.errorCode).toBe('INSPECT_FAILED');
+ expect((failed.data as Record<string, string>).hint).toContain('重做');
+ });
+});
+
+describe('工具错误遥测', () => {
+ it('errorCode 会被交给注入的 logger', async () => {
+ const warn = vi.fn();
+ const client = await connect({
+ logger: {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn,
+ error: vi.fn(),
+ },
+ });
+ await callTool(client, 'read_sheet', { path: 'ghost.csv' });
+ expect(warn).toHaveBeenCalled();
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/providersDocs.test.ts b/packages/lizi-mcps/src/__tests__/providersDocs.test.ts
new file mode 100644
index 0000000000..84223264f0
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/providersDocs.test.ts
@@ -0,0 +1,135 @@
+/**
+ * cindy_docs 的 provider 装配测试。
+ *
+ * 钉住三件事:
+ * 1. 只有 host 传了 docs deps 才出现这个 provider(与其它 server 同规矩);
+ * 2. `enabled` 白名单能筛掉它(desktop 侧按 plugin 开关传 BUILTIN_LIZI_MCP_IDS);
+ * 3. toClaudeSdkConfig 把 ctx 的 workingDir / sessionId / getSessionContext
+ * 真的绑进 server —— 路径边界完全建立在这上面,绑错等于边界失效。
+ */
+
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLiziMcpProviders } from '../providers.js';
+import type { LiziMcpSessionContext } from '../types.js';
+
+const ctx: LiziMcpSessionContext = {
+ agentKind: 'claude-code',
+ workingDir: '/tmp/does-not-matter',
+ sessionId: 'sess-42',
+};
+
+describe('createLiziMcpProviders — cindy_docs', () => {
+ it('没传 docs deps 时不注册', () => {
+ const names = createLiziMcpProviders({}).map((p) => p.name);
+ expect(names).not.toContain('cindy_docs');
+ });
+
+ it('传了 docs deps(即使是空对象)就注册', () => {
+ const names = createLiziMcpProviders({ docs: {} }).map((p) => p.name);
+ expect(names).toContain('cindy_docs');
+ });
+
+ it('enabled 白名单不含 cindy_docs 时被筛掉', () => {
+ const names = createLiziMcpProviders({ docs: {}, enabled: ['cindy_helper'] }).map(
+ (p) => p.name,
+ );
+ expect(names).not.toContain('cindy_docs');
+ });
+
+ it('provider 没有自带 isEnabled 门控(启停由 host 的 plugin registry 包一层)', () => {
+ const provider = createLiziMcpProviders({
+ docs: { writeDocsOutput: async () => undefined },
+ }).find((p) => p.name === 'cindy_docs')!;
+ expect(provider.isEnabled).toBeUndefined();
+ });
+
+ it('toClaudeSdkConfig 产出可实例化的 sdk server,并绑定会话 ctx', async () => {
+ const provider = createLiziMcpProviders({
+ docs: { writeDocsOutput: async () => undefined },
+ }).find((p) => p.name === 'cindy_docs')!;
+ const config = provider.toClaudeSdkConfig(ctx) as {
+ type: string;
+ name: string;
+ instance: { connect: (t: unknown) => Promise<void> };
+ };
+ expect(config.type).toBe('sdk');
+ expect(config.name).toBe('cindy_docs');
+
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'docs-provider-test', version: '0.0.0' });
+ await Promise.all([config.instance.connect(serverTx), client.connect(clientTx)]);
+ // 六个工具顶层直接注册,不再是 call_tool / list_tools 两个入口(2026-08-21 改:
+ // 藏在二级分派后面时模型根本没把「做个 PPT」和它联系起来)。这里 host 没注入
+ // 渲染 / 回读回调,所以 render_pdf 与 inspect_pdf 不登记。
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name).sort()).toEqual([
+ 'make_docx',
+ 'make_pptx',
+ 'make_xlsx',
+ 'read_sheet',
+ ]);
+ // 顶层描述必须自解释 —— 模型只能靠它选型。
+ const pptx = tools.find((t) => t.name === 'make_pptx');
+ expect(pptx?.description ?? '').toContain('PPT');
+ });
+
+ it('ctx 的 getSessionContext 被透传:归属由每次调用现解析,而不是建 server 时冻结', async () => {
+ const getSessionContext = vi.fn(() => undefined);
+ const provider = createLiziMcpProviders({ docs: {} }).find((p) => p.name === 'cindy_docs')!;
+ const config = provider.toClaudeSdkConfig({ ...ctx, getSessionContext }) as {
+ instance: { connect: (t: unknown) => Promise<void> };
+ };
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'docs-ctx-test', version: '0.0.0' });
+ await Promise.all([config.instance.connect(serverTx), client.connect(clientTx)]);
+
+ const result = await client.callTool({
+ name: 'read_sheet',
+ arguments: { path: 'a.csv' },
+ });
+ const body = JSON.parse(
+ (result as { content: Array<{ text: string }> }).content[0]!.text,
+ ) as Record<string, unknown>;
+ // accessor 返回 undefined = 无法确认归属 → fail closed
+ expect(body.errorCode).toBe('NO_SESSION_CONTEXT');
+ expect(getSessionContext).toHaveBeenCalled();
+ });
+
+ it('render_pdf / inspect_pdf 的注册取决于 host 是否注入了对应回调', async () => {
+ // 顶层暴露之后没有 list_tools 类目可查了,直接读 MCP 工具清单,再挑出这两个
+ // 受 host 注入门控的工具 —— 断言的仍是同一件事:host 没给能力就不该登记。
+ const HOST_GATED = ['render_pdf', 'inspect_pdf'] as const;
+ async function gatedToolNames(deps: Parameters<typeof createLiziMcpProviders>[0]['docs']) {
+ const provider = createLiziMcpProviders({ docs: deps }).find(
+ (p) => p.name === 'cindy_docs',
+ )!;
+ const config = provider.toClaudeSdkConfig(ctx) as {
+ instance: { connect: (t: unknown) => Promise<void> };
+ };
+ const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'docs-render-gate', version: '0.0.0' });
+ await Promise.all([config.instance.connect(serverTx), client.connect(clientTx)]);
+ const { tools } = await client.listTools();
+ return tools
+ .map((t) => t.name)
+ .filter((name): name is (typeof HOST_GATED)[number] =>
+ (HOST_GATED as readonly string[]).includes(name),
+ )
+ .sort();
+ }
+
+ expect(await gatedToolNames({})).toEqual([]);
+ expect(
+ await gatedToolNames({
+ writeDocsOutput: async () => undefined,
+ renderHtmlToPdf: async () => ({ buffer: Buffer.alloc(0), fontsReady: true }),
+ }),
+ ).toEqual(['render_pdf']);
+ expect(
+ await gatedToolNames({ inspectPdf: async () => ({ numPages: 0, pagesInspected: 0, pages: [] }) }),
+ ).toEqual(['inspect_pdf']);
+ });
+});
diff --git a/packages/lizi-mcps/src/cindy-docs/_paths.ts b/packages/lizi-mcps/src/cindy-docs/_paths.ts
new file mode 100644
index 0000000000..d7ff7fe724
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/_paths.ts
@@ -0,0 +1,274 @@
+/**
+ * cindy-docs/_paths.ts —— 文档工具的路径边界与输出落盘前置。
+ *
+ * 归属判据与 cindy_slack 的 out_file 泄洪同款:**当前 tool-call 的 session ctx
+ * 才是权威**(resolveLiziMcpSessionContext:Claude 走闭包、Codex/Pi 走
+ * AsyncLocalStorage;解析不出归属时它会把 workingDir 抹成空串)。所有
+ * 模型给的路径先经 resolvePathInsideRoot 做「.. 穿越 + symlink 逃逸 + 绝对路径
+ * 越界」三重钳制,再决定能不能写。
+ *
+ * 为什么写类工具默认不覆盖:文档产出常常是用户手里唯一的一份(改了三轮的报告),
+ * 模型重跑一次就静默盖掉是不可接受的。覆盖必须由模型显式 overwrite:true 表态。
+ */
+
+import { constants as fsConstants, promises as fs, type BigIntStats } from 'node:fs';
+import path from 'node:path';
+
+import { resolveLiziMcpSessionContext } from '../session-context.js';
+import { PathBoundaryError, resolvePathInsideRoot } from '../shared/assertInsidePath.js';
+import type { DocsMcpSessionCtx } from './types.js';
+
+/** 工具层可识别的路径类失败。code 直接进 payload 的 errorCode。 */
+export class DocsPathError extends Error {
+ constructor(
+ readonly code:
+ | 'NO_SESSION_CONTEXT'
+ | 'REMOTE_SESSION_UNSUPPORTED'
+ | 'PATH_NOT_ALLOWED'
+ | 'FILE_EXISTS'
+ | 'ATOMIC_PUBLISH_UNSUPPORTED'
+ | 'INVALID_EXTENSION'
+ | 'NOT_A_FILE'
+ | 'SHEET_NOT_FOUND'
+ | 'FILE_TOO_LARGE'
+ | 'UNSUPPORTED_ENCODING'
+ | 'READ_TIMEOUT',
+ message: string,
+ readonly hint: string,
+ ) {
+ super(message);
+ this.name = 'DocsPathError';
+ }
+}
+
+/**
+ * 解析当前 tool-call 的会话根目录。空 workingDir(未绑定会话 / 归属无法确认)
+ * 与 SSH 远程会话都 fail closed —— 后者的 workingDir 是远端机器上的路径字符串,
+ * 拿它当本机根会与同名本地目录互串。
+ */
+export function resolveSessionRoot(sessionCtx: DocsMcpSessionCtx): string {
+ const ctx = resolveLiziMcpSessionContext(sessionCtx);
+ if (ctx.remoteHostId) {
+ throw new DocsPathError(
+ 'REMOTE_SESSION_UNSUPPORTED',
+ `远程会话(${ctx.remoteHostId})的工作目录不在本机`,
+ '文档工具只能在本机会话里生成文件。请在本地会话中重试,或让用户把内容带回本机后再生成。',
+ );
+ }
+ const root = typeof ctx.workingDir === 'string' ? ctx.workingDir.trim() : '';
+ if (root.length === 0) {
+ throw new DocsPathError(
+ 'NO_SESSION_CONTEXT',
+ '当前调用无法确认所属会话的工作目录',
+ '本次调用没有绑定会话工作目录,无法确定文件该落在哪里。请在一个已打开工作目录的任务里重试。',
+ );
+ }
+ return root;
+}
+
+/** 把 PathBoundaryError 统一翻成工具层的 PATH_NOT_ALLOWED。 */
+function toPathError(err: unknown, inputPath: string): never {
+ if (err instanceof PathBoundaryError) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ err.message,
+ `路径 "${inputPath}" 不在本任务的工作目录内。请改用工作目录内的相对路径(例如 documents/report.pdf)。`,
+ );
+ }
+ throw err;
+}
+
+/**
+ * 校验并准备一个输出路径:边界钳制 → 覆盖判定。
+ * 返回可直接写入的绝对路径。
+ */
+export async function prepareOutputPath(
+ root: string,
+ outPath: string,
+ overwrite: boolean,
+): Promise<string> {
+ let abs: string;
+ try {
+ abs = await resolvePathInsideRoot(root, outPath);
+ } catch (err) {
+ toPathError(err, outPath);
+ }
+
+ let exists = true;
+ try {
+ await fs.stat(abs);
+ } catch {
+ exists = false;
+ }
+ if (exists && !overwrite) {
+ throw new DocsPathError(
+ 'FILE_EXISTS',
+ `目标文件已存在: ${abs}`,
+ '同名文件已存在。确认要覆盖就再调一次并传 overwrite: true,否则换一个文件名(建议加日期或版本后缀)。',
+ );
+ }
+
+ return abs;
+}
+
+/** 生成器只允许与实际字节格式一致的后缀,避免产出“内容是 Word、名字却是 PDF”的文件。 */
+export function assertOutputExtension(outPath: string, expectedExtension: string): void {
+ const expected = expectedExtension.toLowerCase();
+ const actual = path.extname(outPath).toLowerCase();
+ if (actual === expected) return;
+ throw new DocsPathError(
+ 'INVALID_EXTENSION',
+ `输出文件必须使用 ${expected} 扩展名,当前是 "${actual || '(无扩展名)'}"`,
+ `请把 outPath 改成以 ${expected} 结尾的文件名。`,
+ );
+}
+
+/** 校验一个读取路径:边界钳制 + 必须是普通文件。 */
+export async function prepareInputPath(root: string, inPath: string): Promise<string> {
+ let abs: string;
+ try {
+ abs = await resolvePathInsideRoot(root, inPath);
+ } catch (err) {
+ toPathError(err, inPath);
+ }
+ let isFile = false;
+ try {
+ const st = await fs.stat(abs);
+ isFile = st.isFile();
+ } catch {
+ isFile = false;
+ }
+ if (!isFile) {
+ throw new DocsPathError(
+ 'NOT_A_FILE',
+ `文件不存在或不是普通文件: ${abs}`,
+ `找不到文件 "${inPath}"。先确认它在本任务的工作目录里,并检查文件名与扩展名。`,
+ );
+ }
+ return abs;
+}
+
+/**
+ * 在分配输入缓冲区前先从已打开的文件句柄读取大小,并且最多只读取该次 stat
+ * 看到的字节数。这样即使文件很大,或在 stat 后继续增长,也不会让 readFile
+ * 在主进程里无上限分配内存。
+ */
+function sameFileIdentity(a: BigIntStats, b: BigIntStats): boolean {
+ return (
+ a.dev !== 0n &&
+ a.ino !== 0n &&
+ b.dev !== 0n &&
+ b.ino !== 0n &&
+ a.dev === b.dev &&
+ a.ino === b.ino
+ );
+}
+
+function sameFileVersion(a: BigIntStats, b: BigIntStats): boolean {
+ return (
+ sameFileIdentity(a, b) &&
+ a.mode === b.mode &&
+ a.size === b.size &&
+ a.mtimeNs === b.mtimeNs &&
+ a.ctimeNs === b.ctimeNs
+ );
+}
+
+function changedInputPath(abs: string): DocsPathError {
+ return new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输入文件在校验与读取之间发生变化: ${abs}`,
+ '文件路径在读取时发生了变化,已为安全起见停止。请确认文件仍在本任务工作目录内后重试。',
+ );
+}
+
+function isInsideRealRoot(realRoot: string, candidate: string): boolean {
+ if (realRoot === candidate) return true;
+ const relative = path.relative(realRoot, candidate);
+ return relative.length > 0 && !relative.startsWith('..') && !path.isAbsolute(relative);
+}
+
+async function verifyOpenedInputStillInsideRoot(
+ realRoot: string,
+ canonicalPath: string,
+ openedStat: BigIntStats,
+): Promise<void> {
+ try {
+ const rebound = await fs.realpath(canonicalPath);
+ if (!isInsideRealRoot(realRoot, rebound)) throw changedInputPath(canonicalPath);
+ const reboundStat = await fs.stat(rebound, { bigint: true });
+ if (!sameFileIdentity(openedStat, reboundStat)) throw changedInputPath(canonicalPath);
+ } catch (err) {
+ if (err instanceof DocsPathError) throw err;
+ if (err instanceof PathBoundaryError) toPathError(err, canonicalPath);
+ throw changedInputPath(canonicalPath);
+ }
+}
+
+export async function readInputFileWithinLimit(
+ root: string,
+ abs: string,
+ maxBytes: number,
+ tooLarge: (bytes: number) => DocsPathError,
+): Promise<Buffer> {
+ // 校验与读取绑定到同一个已打开文件身份,封住路径检查后父目录被换成根外
+ // symlink 的窗口;身份不可用的网络盘 fail closed,不拿 0 === 0 放行。
+ let canonicalPath: string;
+ let realRoot: string;
+ try {
+ [canonicalPath, realRoot] = await Promise.all([fs.realpath(abs), fs.realpath(root)]);
+ if (!isInsideRealRoot(realRoot, canonicalPath)) throw changedInputPath(abs);
+ } catch (err) {
+ if (err instanceof DocsPathError) throw err;
+ if (err instanceof PathBoundaryError) toPathError(err, abs);
+ throw changedInputPath(abs);
+ }
+ const expectedStat = await fs.stat(canonicalPath, { bigint: true });
+ const handle = await fs.open(
+ canonicalPath,
+ fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0),
+ );
+ try {
+ const stat = await handle.stat({ bigint: true });
+ if (!stat.isFile() || !sameFileIdentity(expectedStat, stat)) {
+ throw changedInputPath(canonicalPath);
+ }
+ await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, stat);
+ if (stat.size > BigInt(maxBytes)) throw tooLarge(Number(stat.size));
+ const size = Number(stat.size);
+
+ const data = Buffer.allocUnsafeSlow(size);
+ let offset = 0;
+ while (offset < data.length) {
+ const { bytesRead } = await handle.read(data, offset, data.length - offset, offset);
+ if (bytesRead === 0) break;
+ offset += bytesRead;
+ }
+
+ const probe = Buffer.allocUnsafe(1);
+ const { bytesRead: extraBytes } = await handle.read(probe, 0, 1, offset);
+ if (extraBytes > 0) throw tooLarge(Math.max(size + extraBytes, maxBytes + 1));
+ const after = await handle.stat({ bigint: true });
+ if (offset !== data.length || !sameFileVersion(stat, after)) {
+ throw changedInputPath(canonicalPath);
+ }
+ await verifyOpenedInputStillInsideRoot(realRoot, canonicalPath, after);
+ return data;
+ } finally {
+ await handle.close();
+ }
+}
+
+/** 落盘后统一的成功信息:相对路径更适合读给用户听,绝对路径供后续工具串联。 */
+export function describeOutput(
+ root: string,
+ abs: string,
+ bytes: number,
+): { path: string; relativePath: string; bytes: number } {
+ const rel = path.relative(path.resolve(root), abs);
+ return {
+ path: abs,
+ relativePath: rel.length > 0 ? rel : path.basename(abs),
+ bytes,
+ };
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/_payload.ts b/packages/lizi-mcps/src/cindy-docs/_payload.ts
new file mode 100644
index 0000000000..7263f25069
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/_payload.ts
@@ -0,0 +1,61 @@
+/**
+ * cindy-docs/_payload.ts —— cindy_docs 工具族共享的 MCP tool result payload helper。
+ *
+ * 与 xdt-helper/_payload.ts 同口径(每个 server 家族各自持有一份,不跨家族 import):
+ * - 成功: { ok: true, ...data }
+ * - 失败: { ok: false, errorCode, data: { ...data, hint } }, isError: true
+ *
+ * hint 必须写成「模型能照着自纠」或「能照着转告用户」的人话,不是内部术语。
+ */
+
+export interface DocsPayloadContentBlock {
+ type: 'text';
+ text: string;
+}
+
+export interface DocsPayloadResult {
+ content: DocsPayloadContentBlock[];
+ isError?: boolean;
+ [k: string]: unknown;
+}
+
+/** 生成工具交给上层作品卡的稳定元数据。字段刻意保持小而语义化,避免把排版旋钮泄漏到 UI。 */
+export type DocsArtifactFormat = 'pdf' | 'docx' | 'pptx' | 'xlsx';
+
+export interface DocsArtifactMetadata {
+ format: DocsArtifactFormat;
+ title?: string;
+ subtitle?: string;
+ theme?: 'light' | 'dark' | 'navy';
+ cover?: boolean;
+ summary?: {
+ kind: 'pages' | 'slides' | 'sheets' | 'rows' | 'bytes';
+ value: number;
+ };
+}
+
+export function artifactMetadata(metadata: DocsArtifactMetadata): DocsArtifactMetadata {
+ return metadata;
+}
+
+export function okPayload(data: Record<string, unknown>): DocsPayloadResult {
+ return {
+ content: [{ type: 'text', text: JSON.stringify({ ok: true, ...data }) }],
+ };
+}
+
+export function errorPayload(
+ errorCode: string,
+ hint: string,
+ data: Record<string, unknown> = {},
+): DocsPayloadResult {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: JSON.stringify({ ok: false, errorCode, data: { ...data, hint } }),
+ },
+ ],
+ isError: true,
+ };
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/_textEncoding.ts b/packages/lizi-mcps/src/cindy-docs/_textEncoding.ts
new file mode 100644
index 0000000000..1fe0d50307
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/_textEncoding.ts
@@ -0,0 +1,60 @@
+import { DocsPathError } from './_paths.js';
+
+type UnicodeTextKind = 'HTML' | '文本表格' | '本地样式表';
+
+const CSS_CHARSET_PREFIX = /^@charset\s+["']([^"']+)["']\s*;/i;
+
+function encodingError(kind: string, encoding: string, hint?: string): DocsPathError {
+ return new DocsPathError(
+ 'UNSUPPORTED_ENCODING',
+ `${kind}不是有效的 ${encoding.toUpperCase()} 文本`,
+ hint ??
+ `请把${kind}保存为 UTF-8、带 BOM 的 UTF-16LE 或带 BOM 的 UTF-16BE 后重试,避免内容乱码。`,
+ );
+}
+
+/** Decode UTF-8 or BOM-marked UTF-16 without silently replacing malformed input. */
+export function decodeUnicodeText(bytes: Buffer, kind: UnicodeTextKind): string {
+ let encoding: 'utf-8' | 'utf-16le' | 'utf-16be' = 'utf-8';
+ let offset = 0;
+ if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
+ offset = 3;
+ } else if (bytes[0] === 0xff && bytes[1] === 0xfe) {
+ encoding = 'utf-16le';
+ offset = 2;
+ } else if (bytes[0] === 0xfe && bytes[1] === 0xff) {
+ encoding = 'utf-16be';
+ offset = 2;
+ }
+
+ try {
+ return new TextDecoder(encoding, { fatal: true }).decode(bytes.subarray(offset));
+ } catch {
+ throw encodingError(kind, encoding);
+ }
+}
+
+/** Decode a local stylesheet before rewriting it as UTF-8 and drop stale @charset metadata. */
+export function decodeCssText(bytes: Buffer): string {
+ const hasUnicodeBom =
+ (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) ||
+ (bytes[0] === 0xff && bytes[1] === 0xfe) ||
+ (bytes[0] === 0xfe && bytes[1] === 0xff);
+ let decoded: string;
+ if (hasUnicodeBom) {
+ decoded = decodeUnicodeText(bytes, '本地样式表');
+ } else {
+ const declared = bytes.subarray(0, 256).toString('latin1').match(CSS_CHARSET_PREFIX)?.[1];
+ const encoding = declared ?? 'utf-8';
+ try {
+ decoded = new TextDecoder(encoding, { fatal: true }).decode(bytes);
+ } catch {
+ throw encodingError(
+ '本地样式表',
+ encoding,
+ '请把本地样式表保存为 UTF-8、带 BOM 的 UTF-16LE / UTF-16BE,或使用受支持的 @charset 编码声明后重试。',
+ );
+ }
+ }
+ return decoded.replace(CSS_CHARSET_PREFIX, '');
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/csv.ts b/packages/lizi-mcps/src/cindy-docs/csv.ts
new file mode 100644
index 0000000000..3e56b60e88
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/csv.ts
@@ -0,0 +1,141 @@
+/**
+ * cindy-docs/csv.ts —— RFC 4180 分隔符文本解析(csv / tsv 共用)。
+ *
+ * 为什么手写而不是拉一个库:read_sheet 只需要「把一份本地文本切成二维数组」,
+ * 规则本身就是 RFC 4180 那几条,自己实现比引一个新依赖更可控,也方便把口径
+ * 钉在测试里。
+ *
+ * 覆盖的口径:
+ * - 引号字段内可含分隔符、换行与转义引号("" → ");
+ * - CRLF / LF / CR 三种行尾都当换行,输出统一不带行尾符;
+ * - 前导 BOM 剥掉(Excel 导出的 UTF-8 CSV 常带 BOM,不剥会污染第一列表头);
+ * - 最后一行没有行尾符也算一行;整份文本为空则返回零行;
+ * - 引号只有在字段的第一个字符时才进入引号态,`a"b` 原样保留(与 Excel 一致)。
+ */
+
+export interface ParseDelimitedOptions {
+ /** 单字符分隔符。csv → ','; tsv → '\t'。 */
+ delimiter: string;
+}
+
+export interface ParseDelimitedWindowOptions extends ParseDelimitedOptions {
+ /** 1 起的逻辑行号。 */
+ startRow: number;
+ /** 最多保留多少行;解析器仍会计数到文件尾,以便返回准确总行数。 */
+ maxRows: number;
+ /** Also return the widest logical row seen while scanning the whole input. */
+ includeTotalColumns?: boolean;
+}
+
+export interface ParseDelimitedWindowResult {
+ rows: string[][];
+ totalRows: number;
+ totalColumns?: number;
+}
+
+/** 把分隔符文本解析成二维字符串数组。永不 throw。 */
+export function parseDelimited(text: string, opts: ParseDelimitedOptions): string[][] {
+ return parseDelimitedWindow(text, {
+ ...opts,
+ startRow: 1,
+ maxRows: Number.MAX_SAFE_INTEGER,
+ }).rows;
+}
+
+/** 单次扫描完整文本,但只保留请求的行窗口,避免把整份文件展开成二维数组。 */
+export function parseDelimitedWindow(
+ text: string,
+ opts: ParseDelimitedWindowOptions,
+): ParseDelimitedWindowResult {
+ const delimiter = opts.delimiter.length > 0 ? opts.delimiter[0]! : ',';
+ const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
+
+ const rows: string[][] = [];
+ const firstRow = Math.max(1, Math.trunc(opts.startRow));
+ const maxRows = Math.max(0, Math.trunc(opts.maxRows));
+ const lastRow = Math.min(Number.MAX_SAFE_INTEGER, firstRow + maxRows - 1);
+ let totalRows = 0;
+ let totalColumns = 0;
+ let row: string[] = [];
+ let field = '';
+ let inQuotes = false;
+ let recordStarted = false;
+ // 字段是否还停在「第一个字符」上 —— 决定引号算引号态还是普通字符。
+ let atFieldStart = true;
+
+ const endField = (): void => {
+ row.push(field);
+ field = '';
+ atFieldStart = true;
+ };
+ const endRow = (): void => {
+ endField();
+ totalColumns = Math.max(totalColumns, row.length);
+ totalRows += 1;
+ if (totalRows >= firstRow && totalRows <= lastRow) rows.push(row);
+ row = [];
+ recordStarted = false;
+ };
+
+ for (let i = 0; i < src.length; i += 1) {
+ const ch = src[i]!;
+
+ if (inQuotes) {
+ if (ch === '"') {
+ if (src[i + 1] === '"') {
+ field += '"';
+ i += 1;
+ } else {
+ inQuotes = false;
+ }
+ } else {
+ field += ch;
+ }
+ continue;
+ }
+
+ if (ch === '"' && atFieldStart) {
+ inQuotes = true;
+ atFieldStart = false;
+ recordStarted = true;
+ continue;
+ }
+ if (ch === delimiter) {
+ recordStarted = true;
+ endField();
+ continue;
+ }
+ if (ch === '\r') {
+ // CRLF 与裸 CR 都作一次换行。
+ if (src[i + 1] === '\n') i += 1;
+ endRow();
+ continue;
+ }
+ if (ch === '\n') {
+ endRow();
+ continue;
+ }
+ field += ch;
+ atFieldStart = false;
+ recordStarted = true;
+ }
+
+ // 未闭合的引号:按「读到文件尾即字段结束」收尾,不报错 —— 半截文件也应该
+ // 尽量给出可用内容,让模型自己判断要不要重取。
+ if (inQuotes || field.length > 0 || row.length > 0 || recordStarted) {
+ endRow();
+ }
+
+ return {
+ rows,
+ totalRows,
+ ...(opts.includeTotalColumns ? { totalColumns } : {}),
+ };
+}
+
+/** 按扩展名推断分隔符;未知扩展名按逗号处理。 */
+export function delimiterForExtension(ext: string): string {
+ const normalized = ext.toLowerCase();
+ if (normalized === '.tsv' || normalized === '.tab') return '\t';
+ return ',';
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/docxStyles.ts b/packages/lizi-mcps/src/cindy-docs/docxStyles.ts
new file mode 100644
index 0000000000..b27909d9cc
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/docxStyles.ts
@@ -0,0 +1,266 @@
+/**
+ * cindy-docs/docxStyles.ts —— Word 的体面默认值:标题层级、封面、表格色带。
+ *
+ * 不嵌字体:OOXML 正文是 Unicode,中文字形由用户打开时的 Word / WPS / Pages 决定。
+ * 这里只定字号、粗细、颜色、间距和表格铬件。
+ */
+
+import {
+ AlignmentType,
+ BorderStyle,
+ Footer,
+ HeadingLevel,
+ PageNumber,
+ Paragraph,
+ Table,
+ TableCell,
+ TableRow,
+ ShadingType,
+ TextRun,
+ VerticalAlign,
+ WidthType,
+ type IParagraphStyleOptions,
+ type ISectionOptions,
+ type IStylesOptions,
+ type ITableBordersOptions,
+ type ParagraphChild,
+} from 'docx';
+
+import { formatDocsDate, type DocsTheme } from './themes.js';
+
+const PAGE_TWIPS = { top: 1134, right: 1134, bottom: 1134, left: 1134 } as const;
+/*
+ 封面上边距收回到 1 英寸 —— 顶部那条强调带要贴着版心上沿,压住整页;边距留 2 英寸
+ 的话带子悬在半空,压不住任何东西。标题块改由 COVER_TITLE_DROP_TWIPS 单独下压。
+*/
+const COVER_PAGE_TWIPS = { top: 1440, right: 1440, bottom: 1440, left: 1440 } as const;
+/**
+ * 标题块相对强调带再往下推多少(twips,1440 = 1 英寸)。
+ *
+ * A4 高 16838 twips。上边距 1 英寸 + 这里 2.3 英寸,标题落在离纸顶约 3.4 英寸处,
+ * 即页面上三分之一 —— 视线的自然落点。落在纸的最上沿只会显得像一张便签。
+ */
+const COVER_TITLE_DROP_TWIPS = 3300;
+
+function thinBorder(theme: DocsTheme): ITableBordersOptions {
+ const edge = { style: BorderStyle.SINGLE, size: 4, color: theme.line, space: 0 };
+ return {
+ top: edge,
+ bottom: edge,
+ left: edge,
+ right: edge,
+ insideHorizontal: edge,
+ insideVertical: edge,
+ };
+}
+
+function headingStyle(
+ id: string,
+ name: string,
+ size: number,
+ color: string,
+ before: number,
+ after: number,
+ outlineLevel: number,
+): IParagraphStyleOptions {
+ return {
+ id,
+ name,
+ basedOn: 'Normal',
+ next: 'Normal',
+ quickFormat: true,
+ paragraph: { spacing: { before, after }, outlineLevel },
+ run: { size, bold: true, color, font: 'Calibri' },
+ };
+}
+
+export function docxDocumentStyles(theme: DocsTheme): IStylesOptions {
+ return {
+ default: {
+ document: {
+ run: { font: 'Calibri', size: 22, color: theme.body },
+ paragraph: { spacing: { after: 160, line: 276 } },
+ },
+ title: {
+ run: { size: 56, bold: true, color: theme.title, font: 'Calibri' },
+ paragraph: { spacing: { after: 240 } },
+ },
+ },
+ paragraphStyles: [
+ headingStyle('Heading1', 'Heading 1', 32, theme.title, 360, 160, 0),
+ headingStyle('Heading2', 'Heading 2', 26, theme.accent, 280, 120, 1),
+ headingStyle('Heading3', 'Heading 3', 24, theme.title, 240, 100, 2),
+ headingStyle('Heading4', 'Heading 4', 22, theme.body, 200, 80, 3),
+ headingStyle('Heading5', 'Heading 5', 22, theme.muted, 180, 80, 4),
+ headingStyle('Heading6', 'Heading 6', 20, theme.muted, 160, 80, 5),
+ ],
+ };
+}
+
+/**
+ * 封面。
+ *
+ * 上一版是三段文字堆在页面顶端:小标题、大标题、日期,全落在上方 15%,底下 2/3
+ * 是纯空白 —— 和 PPT 封面之前那个「白底加几行字」是同一个毛病,只有结构没有构图。
+ * 目检一眼就能看出来,而「XML 里有 Title 样式」这种自检永远看不出来。
+ *
+ * 现在的构图:顶部一条实心强调带压住版面 → 标题块下压到上三分之一(读者视线的
+ * 落点,不是纸的边缘)→ 日期沉到页脚。三样东西各就各位,页面才有重心。
+ */
+export function docxCoverSection(
+ theme: DocsTheme,
+ options: { title: string; subtitle?: string; date?: string },
+): ISectionOptions {
+ const date = options.date ?? formatDocsDate();
+ const subtitle = options.subtitle?.trim() ?? '';
+ return {
+ properties: {
+ page: { margin: COVER_PAGE_TWIPS },
+ },
+ // 日期沉到页脚才是真的在页底。原来它跟在标题下面,靠段间距悬在半空 ——
+ // 标题一长就跟着往下挪,位置永远不稳。
+ footers: {
+ default: new Footer({
+ children: [
+ new Paragraph({
+ children: [new TextRun({ text: date, color: theme.muted, size: 18 })],
+ }),
+ ],
+ }),
+ },
+ children: [
+ // 顶部实心强调带。用段落底纹画,不用边框 —— 边框只有线,填不出面积,
+ // 而封面缺的正是面积(PPT 封面那次的结论一样)。
+ new Paragraph({
+ shading: { type: ShadingType.SOLID, fill: theme.accent, color: theme.accent },
+ spacing: { after: 0, line: 240 },
+ children: [new TextRun({ text: ' ', size: 16, color: theme.accent })],
+ }),
+ // 把标题块推到上三分之一。空段落 + 段前距,不用手数换行。
+ new Paragraph({
+ spacing: { before: COVER_TITLE_DROP_TWIPS, after: 0 },
+ children: [],
+ }),
+ new Paragraph({
+ border: {
+ bottom: { style: BorderStyle.SINGLE, size: 16, space: 8, color: theme.accent },
+ },
+ spacing: { after: 280 },
+ children: [
+ new TextRun({
+ text: subtitle.length > 0 ? subtitle : ' ',
+ color: theme.muted,
+ size: 20,
+ }),
+ ],
+ }),
+ new Paragraph({
+ heading: HeadingLevel.TITLE,
+ children: [new TextRun({ text: options.title, color: theme.title })],
+ spacing: { before: 200, after: 200 },
+ }),
+ ],
+ };
+}
+
+export function docxBodySectionProperties(): ISectionOptions['properties'] {
+ return {
+ page: { margin: PAGE_TWIPS },
+ };
+}
+
+export function docxBodyFooter(theme: DocsTheme): Footer {
+ return new Footer({
+ children: [
+ new Paragraph({
+ alignment: AlignmentType.RIGHT,
+ children: [
+ new TextRun({
+ children: [PageNumber.CURRENT],
+ color: theme.muted,
+ size: 16,
+ }),
+ ],
+ }),
+ ],
+ });
+}
+
+/**
+ * 一列有多宽,按这一列真正要放的字数分。
+ *
+ * 不给列宽时 docx 生成的 `tblGrid` 每列都是 `w=100`,Word 只能按等分排 ——
+ * 于是「严重度」这种只放「中 / 高」两个字的列,和「建议」那种要放一整句的列
+ * 一样宽:一边空一大片,一边挤成三行。这是「表格很破」最常见的一种。
+ *
+ * 上下限是为了不让极端值毁掉版面:一列最少占 8%(再窄中文标题都竖排了),
+ * 最多占 40%(再宽其余列就没法看了)。
+ */
+const MIN_COL_PCT = 8;
+const MAX_COL_PCT = 40;
+
+export function columnPercents(columnTextWidths: readonly number[]): number[] {
+ const n = columnTextWidths.length;
+ if (n === 0) return [];
+ const floor = Math.min(MIN_COL_PCT, 100 / n);
+ const ceil = Math.max(MAX_COL_PCT, 100 / n);
+ const safe = columnTextWidths.map((w) => Math.max(1, w));
+ const total = safe.reduce((a, b) => a + b, 0);
+ const raw = safe.map((w) => Math.min(ceil, Math.max(floor, (w / total) * 100)));
+ // 钳到上下限之后总和会偏离 100,按比例拉回去,免得表格宽度对不上。
+ const sum = raw.reduce((a, b) => a + b, 0);
+ return raw.map((v) => Math.round((v / sum) * 1000) / 10);
+}
+
+export function styledDocxTable(
+ theme: DocsTheme,
+ rows: TableRow[],
+ columnPercentages?: readonly number[],
+): Table {
+ return new Table({
+ width: { size: 100, type: WidthType.PERCENTAGE },
+ borders: thinBorder(theme),
+ ...(columnPercentages && columnPercentages.length > 0
+ ? // docx 的 columnWidths 走 dxa;A4 正文宽约 9638 twips(11906 - 2×1134)。
+ { columnWidths: columnPercentages.map((pct) => Math.round((pct / 100) * 9638)) }
+ : {}),
+ rows,
+ });
+}
+
+export function styledDocxHeaderCell(
+ theme: DocsTheme,
+ children: ParagraphChild[],
+ alignment?: (typeof AlignmentType)[keyof typeof AlignmentType],
+): TableCell {
+ return new TableCell({
+ shading: { fill: theme.accent },
+ verticalAlign: VerticalAlign.CENTER,
+ margins: { top: 60, bottom: 60, left: 80, right: 80 },
+ children: [
+ new Paragraph({
+ children,
+ ...(alignment ? { alignment } : {}),
+ }),
+ ],
+ });
+}
+
+export function styledDocxBodyCell(
+ theme: DocsTheme,
+ zebra: boolean,
+ children: ParagraphChild[],
+ alignment?: (typeof AlignmentType)[keyof typeof AlignmentType],
+): TableCell {
+ return new TableCell({
+ shading: { fill: zebra ? theme.zebra : theme.background },
+ verticalAlign: VerticalAlign.CENTER,
+ margins: { top: 50, bottom: 50, left: 80, right: 80 },
+ children: [
+ new Paragraph({
+ children,
+ ...(alignment ? { alignment } : {}),
+ }),
+ ],
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/index.ts b/packages/lizi-mcps/src/cindy-docs/index.ts
new file mode 100644
index 0000000000..66ec6c7d0f
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/index.ts
@@ -0,0 +1,65 @@
+/**
+ * cindy-docs/index.ts
+ *
+ * cindy_docs 工具族的聚合导出。cindy_docsMcpServer.ts 从这里一次性 import 并注册
+ * (与 xdt-helper/index.ts、scheduler/index.ts 同模式)。
+ */
+
+export { registerMakeDocxTool } from './make_docx.js';
+export {
+ registerMakePptxTool,
+ PPTX_THEMES,
+ PPTX_LAYOUT_IDS,
+ PPTX_LAYOUT_NAMES,
+ DEFAULT_PPTX_LAYOUT,
+ isSupportedPptxImage,
+} from './make_pptx.js';
+export { DOCS_THEMES, resolveDocsTheme, formatDocsDate } from './themes.js';
+export { registerMakeXlsxTool } from './make_xlsx.js';
+export { registerReadSheetTool } from './read_sheet.js';
+export {
+ registerRenderPdfTool,
+ RENDER_PDF_TIMEOUT_MS,
+ RENDER_PDF_FONT_TIMEOUT_MS,
+ RENDER_PDF_MAX_HTML_BYTES,
+} from './render_pdf.js';
+export { registerInspectPdfTool, INSPECT_PDF_TIMEOUT_MS } from './inspect_pdf.js';
+
+export { markdownToDocxBuffer, type MarkdownToDocxOptions } from './markdownToDocx.js';
+export {
+ applyReportTemplate,
+ htmlLooksUnstyled,
+ htmlHasRelativeResources,
+} from './pdfTemplate.js';
+export { inferNumberFormat } from './make_xlsx.js';
+export {
+ parseDelimited,
+ parseDelimitedWindow,
+ delimiterForExtension,
+ type ParseDelimitedOptions,
+ type ParseDelimitedWindowOptions,
+ type ParseDelimitedWindowResult,
+} from './csv.js';
+export {
+ DocsPathError,
+ describeOutput,
+ prepareInputPath,
+ prepareOutputPath,
+ readInputFileWithinLimit,
+ resolveSessionRoot,
+} from './_paths.js';
+export { okPayload, errorPayload, type DocsPayloadResult } from './_payload.js';
+
+export type {
+ DocsMcpDeps,
+ DocsMcpSessionCtx,
+ DocsPdfInspection,
+ DocsPdfMargins,
+ DocsPdfPageInspection,
+ DocsPdfPageSize,
+ DocsPdfRenderInput,
+ DocsPdfRenderOutput,
+ InspectPdfFn,
+ RenderHtmlToPdfFn,
+ WriteDocsOutputFn,
+} from './types.js';
diff --git a/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts b/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts
new file mode 100644
index 0000000000..1f009b7c81
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/inspect_pdf.ts
@@ -0,0 +1,298 @@
+/**
+ * cindy-docs/inspect_pdf.ts —— 回读一份 PDF 的结构,做产出自检。
+ *
+ * 为什么需要它:生成 PDF 最常见、也最难自查的翻车是「文件生成了,打开是白的」——
+ * 字节数完全正常(PDF 结构、字体、元数据都在),光看 bytes 判断不出来。模型不回读
+ * 就交付,用户打开才发现,这是最坏的顺序。
+ *
+ * 本工具给的是**确定性证据**而不是猜测:某页 textChars=0 且 drawOps=0 且
+ * imageOps=0,那它就是白的;12 页而不是预期的 2 页,说明分页样式没生效;
+ * 页面尺寸不是 A4,说明 pageSize 传错了。
+ *
+ * 【不产出图片】本工具返回结构与文本,不做位图渲染 —— 见 README/PR 说明:
+ * 把 PDF 栅格成 PNG 在 Node 侧需要引入原生 canvas 绑定(打包链路改造 + 每平台
+ * 二进制),代价与收益不匹配。空白/串页/尺寸错这几类真实翻车,结构证据已经能定死。
+ */
+
+import { createHash } from 'node:crypto';
+import path from 'node:path';
+
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ DocsPathError,
+ prepareInputPath,
+ readInputFileWithinLimit,
+ resolveSessionRoot,
+} from './_paths.js';
+import { errorPayload, okPayload } from './_payload.js';
+import type { DocsMcpSessionCtx, InspectPdfFn } from './types.js';
+
+/** 解析超时。结构读取比渲染轻得多,15 秒足够;卡住通常意味着文件损坏。 */
+export const INSPECT_PDF_TIMEOUT_MS = 15_000;
+/** 单次最多检查多少页 —— 页数越多算子表解析越贵,而自检并不需要通读全文。 */
+const DEFAULT_MAX_PAGES = 10;
+const HARD_MAX_PAGES = 50;
+/** 每页文本预览字符数。够判断"这页装的是不是我以为的内容",又不撑爆上下文。 */
+const PREVIEW_CHARS = 400;
+/** 输入上限:超大 PDF 解析会顶满 utility process 的内存预算。 */
+const MAX_INPUT_BYTES = 64 * 1024 * 1024;
+
+/** 常见纸张(pt),用于把裸数字翻译成人能对照的名字。允许 2pt 误差。 */
+const PAPER_SIZES: ReadonlyArray<{ name: string; w: number; h: number }> = [
+ { name: 'A3', w: 841.89, h: 1190.55 },
+ { name: 'A4', w: 595.28, h: 841.89 },
+ { name: 'A5', w: 419.53, h: 595.28 },
+ { name: 'Letter', w: 612, h: 792 },
+ { name: 'Legal', w: 612, h: 1008 },
+ { name: 'Tabloid', w: 792, h: 1224 },
+];
+
+function describePaper(width: number, height: number): string {
+ const near = (a: number, b: number): boolean => Math.abs(a - b) <= 2;
+ for (const paper of PAPER_SIZES) {
+ if (near(width, paper.w) && near(height, paper.h)) return paper.name;
+ if (near(width, paper.h) && near(height, paper.w)) return `${paper.name} landscape`;
+ }
+ // 非标准尺寸直接报英寸,比报 pt 更容易被人对照。
+ return `${(width / 72).toFixed(2)}×${(height / 72).toFixed(2)} in`;
+}
+
+const DESCRIPTION = [
+ '回读一份 PDF 的结构,用来检查自己刚生成的 PDF 到底对不对。',
+ '',
+ '【务必在交付 PDF 前调一次】render_pdf 返回成功只代表"文件写出来了",',
+ '不代表内容是对的。最常见的翻车是整页空白 —— 字节数看着完全正常。',
+ '',
+ '【能查出什么】每页的:文字字符数与开头片段、绘图/图像算子数、是否空白、',
+ '页面尺寸(会翻译成 A4 / Letter 这类名字)与旋转角。文档级还给总页数与空白页清单。',
+ '',
+ '【怎么判读】',
+ '- blankPages 非空 → 那几页是结构上确定为空的,大概率 CSS 把内容藏了或外部资源没加载上,重做;',
+ '- visibilityUnverified=true → 某页算子解析未完成,未做位图级可见性确认,结构检查证据不完整;请重试或人工打开确认,不要把 verdict 当作视觉验收;',
+ '- numPages 远超预期 → 分页样式没生效(检查 page-break / break-inside);',
+ '- paper 不是你要的尺寸 → render_pdf 的 pageSize 传错了;',
+ '- textPreview 和你写的内容对不上 → 装错了内容或页序错乱。',
+ '',
+ '【不产出图片】本工具返回结构与文本,不做位图预览。空白、串页、尺寸错这几类',
+ '真实翻车靠上面的字段已经能定死;需要肉眼确认版式细节时,请把文件路径给用户去打开。',
+ '',
+ '【参数】pages 可指定要看的页码(1 起,如 [1,2,5]);不传就从第 1 页顺序取 maxPages 页。',
+ '分批连续检查时,把上一批响应的 inspectedThrough、verdict 和 pdfSha256 分别作为 inspectedThrough、previousVerdict 与 previousPdfSha256 原样传回,工具才会确认文件未变化并累计覆盖和已发现的异常。',
+].join('\n');
+
+export function registerInspectPdfTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+ inspectPdf: InspectPdfFn,
+): void {
+ registry.register({
+ name: 'inspect_pdf',
+ category: 'read',
+ description: DESCRIPTION,
+ inputShape: {
+ path: z.string().min(1).describe('PDF 路径,工作目录内的相对路径或绝对路径。'),
+ pages: z
+ .array(z.number().int().min(1))
+ .max(HARD_MAX_PAGES)
+ .optional()
+ .describe(
+ `要检查的页码(1 起),最多 ${HARD_MAX_PAGES} 项。不传 = 从第 1 页顺序取 maxPages 页。`,
+ ),
+ inspectedThrough: z
+ .number()
+ .int()
+ .min(0)
+ .default(0)
+ .describe('此前已连续检查到的页码。分批检查时传上一批响应的同名字段,默认 0。'),
+ previousVerdict: z
+ .enum(['ok', 'blank', 'partial-blank', 'warning', 'incomplete'])
+ .optional()
+ .describe(
+ '上一批响应的 verdict。inspectedThrough > 0 时必须原样传回,避免后续正常页覆盖已发现的异常。',
+ ),
+ previousPdfSha256: z
+ .string()
+ .regex(/^[a-f0-9]{64}$/)
+ .optional()
+ .describe(
+ '上一批响应的 pdfSha256。inspectedThrough > 0 时必须原样传回,文件变化时会要求从第 1 页重新检查。',
+ ),
+ maxPages: z
+ .number()
+ .int()
+ .min(1)
+ .max(HARD_MAX_PAGES)
+ .default(DEFAULT_MAX_PAGES)
+ .describe(`最多检查多少页,默认 ${DEFAULT_MAX_PAGES},上限 ${HARD_MAX_PAGES}。`),
+ },
+ handler: async ({
+ path: inputPath,
+ pages,
+ inspectedThrough,
+ previousVerdict,
+ previousPdfSha256,
+ maxPages,
+ }) => {
+ try {
+ if (
+ inspectedThrough > 0 &&
+ (previousVerdict === undefined || previousPdfSha256 === undefined)
+ ) {
+ return errorPayload(
+ 'INVALID_ARGS',
+ '分批检查已带 inspectedThrough,但缺少上一批的 previousVerdict 或 previousPdfSha256。请把上一批响应的 verdict 和 pdfSha256 原样传回,避免跨文件累计或丢失已发现的异常。',
+ { inspectedThrough },
+ );
+ }
+ const carriedVerdict = previousVerdict ?? 'incomplete';
+ const root = resolveSessionRoot(sessionCtx);
+ const abs = await prepareInputPath(root, inputPath);
+ if (path.extname(abs).toLowerCase() !== '.pdf') {
+ return errorPayload(
+ 'UNSUPPORTED_FORMAT',
+ `只能检查 .pdf 文件,给的是 "${path.extname(abs) || '(无扩展名)'}"。`,
+ { path: abs },
+ );
+ }
+
+ const data = await readInputFileWithinLimit(
+ root,
+ abs,
+ MAX_INPUT_BYTES,
+ (bytes) =>
+ new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `PDF 过大: ${bytes} 字节`,
+ `PDF 有 ${(bytes / 1024 / 1024).toFixed(1)} MB,超出检查上限(64 MB)。请先压缩或拆分 PDF。`,
+ ),
+ );
+ if (data.byteLength === 0) {
+ return errorPayload(
+ 'EMPTY_FILE',
+ '这个 PDF 是 0 字节 —— 上一步的生成其实没成功。请重新生成,不要交付。',
+ { path: abs },
+ );
+ }
+ const pdfSha256 = createHash('sha256').update(data).digest('hex');
+ if (inspectedThrough > 0 && previousPdfSha256 !== pdfSha256) {
+ return errorPayload(
+ 'PDF_CHANGED',
+ '分批检查期间 PDF 内容已经变化,不能把不同文件版本的检查结果合并。请去掉 pages、inspectedThrough、previousVerdict 和 previousPdfSha256,从第 1 页重新检查当前文件。',
+ {
+ path: abs,
+ previousPdfSha256,
+ pdfSha256,
+ },
+ );
+ }
+ const inspection = await inspectPdf({
+ data: new Uint8Array(data),
+ pages: pages ?? [],
+ maxPages,
+ previewChars: PREVIEW_CHARS,
+ timeoutMs: INSPECT_PDF_TIMEOUT_MS,
+ });
+
+ const decorated = inspection.pages.map((page) => ({
+ ...page,
+ paper: describePaper(page.width, page.height),
+ }));
+ if (inspection.pagesInspected === 0 || decorated.length === 0) {
+ return errorPayload(
+ 'NO_PAGES_INSPECTED',
+ inspection.numPages > 0
+ ? '没有检查到任何页面。指定页码可能全部超出 PDF 的实际页数,请改用 1 到总页数之间的页码后重试。'
+ : '这份 PDF 没有可检查的页面,不能把它当作检查通过的成品。请重新生成后再检查。',
+ {
+ path: abs,
+ numPages: inspection.numPages,
+ requestedPages: pages ?? [],
+ },
+ );
+ }
+ const blankPages = decorated.filter((p) => p.blank).map((p) => p.page);
+ const allInspectedBlank = decorated.length > 0 && blankPages.length === decorated.length;
+ const visibilityUnverifiedPages = decorated
+ .filter((p) => p.visibilityUnverified)
+ .map((p) => p.page);
+ const inspectedPageNumbers = new Set(decorated.map((page) => page.page));
+ let accumulatedThrough = Math.min(inspectedThrough, inspection.numPages);
+ while (inspectedPageNumbers.has(accumulatedThrough + 1)) accumulatedThrough += 1;
+ const partial = accumulatedThrough < inspection.numPages;
+ const nextPages: number[] = [];
+ if (partial) {
+ // numPages is untrusted PDF metadata. Never allocate an array sized by
+ // that declaration. Advance only through pages proven contiguous with
+ // the caller's previous cursor, then generate one bounded next batch.
+ for (
+ let page = accumulatedThrough + 1;
+ page <= inspection.numPages && nextPages.length < maxPages;
+ page += 1
+ ) {
+ nextPages.push(page);
+ }
+ }
+ const coverageWarning = partial
+ ? `当前已连续覆盖 ${accumulatedThrough}/${inspection.numPages} 页,下一批页码为 ${nextPages.join('、')}。请用 pages: [${nextPages.join(', ')}],并传 inspectedThrough: ${accumulatedThrough},再把本次响应的 verdict 和 pdfSha256 原样作为 previousVerdict 与 previousPdfSha256 继续检查。`
+ : undefined;
+
+ const previousFoundBlank = carriedVerdict === 'blank' || carriedVerdict === 'partial-blank';
+ const previousAllBlank = carriedVerdict === 'blank';
+ const previousVisibilityUnverified = carriedVerdict === 'warning';
+ const accumulatedAllBlank =
+ allInspectedBlank && (inspectedThrough === 0 || previousAllBlank);
+ const accumulatedFoundBlank = previousFoundBlank || blankPages.length > 0;
+ const accumulatedVisibilityUnverified =
+ previousVisibilityUnverified || visibilityUnverifiedPages.length > 0;
+
+ const verdictAndWarning = accumulatedAllBlank
+ ? {
+ verdict: 'blank',
+ warning: `连续检查到的每一页都是空白 —— 这份 PDF 不能交付。回去检查 HTML 是否真有可见内容、外部图片/字体是否加载失败,修好后重新生成再查一次。${coverageWarning ? ` ${coverageWarning}` : ''}`,
+ }
+ : accumulatedFoundBlank
+ ? {
+ verdict: 'partial-blank',
+ warning: `${blankPages.length > 0 ? `第 ${blankPages.join('、')} 页是空白的。` : '此前批次已发现空白页。'}通常是分页把内容挤走了(检查 page-break / break-inside),修好后重新生成。${coverageWarning ? ` ${coverageWarning}` : ''}`,
+ }
+ : accumulatedVisibilityUnverified
+ ? {
+ verdict: 'warning',
+ warning: `${visibilityUnverifiedPages.length > 0 ? `第 ${visibilityUnverifiedPages.join('、')} 页的结构算子解析未完成` : '此前批次存在结构算子解析未完成的页面'},未做位图级可见性确认,检查证据不完整。请重试并在必要时打开 PDF 确认。${coverageWarning ? ` ${coverageWarning}` : ''}`,
+ }
+ : partial
+ ? { verdict: 'incomplete', warning: coverageWarning! }
+ : { verdict: 'ok' };
+
+ return okPayload({
+ path: abs,
+ bytes: data.byteLength,
+ pdfSha256,
+ numPages: inspection.numPages,
+ pagesInspected: inspection.pagesInspected,
+ inspectedThrough: accumulatedThrough,
+ pages: decorated,
+ blankPages,
+ visibilityUnverifiedPages,
+ ...(partial ? { nextPages } : {}),
+ ...verdictAndWarning,
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ const timedOut = /timed out|timeout|超时/i.test(message);
+ return errorPayload(
+ timedOut ? 'INSPECT_TIMEOUT' : 'INSPECT_FAILED',
+ timedOut
+ ? `解析超过 ${INSPECT_PDF_TIMEOUT_MS / 1000} 秒被中止,文件可能损坏或过于复杂。`
+ : `读取 PDF 失败:${message}。如果这是刚生成的文件,说明生成环节就出了问题,请重做而不是交付。`,
+ { message },
+ );
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/make_docx.ts b/packages/lizi-mcps/src/cindy-docs/make_docx.ts
new file mode 100644
index 0000000000..d216f91b48
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/make_docx.ts
@@ -0,0 +1,128 @@
+/**
+ * cindy-docs/make_docx.ts —— Markdown → Word(.docx)。
+ *
+ * 结构化生成(marked lexer → docx 对象树),不是「打印成 PDF 再改名」:出来的
+ * 是真 Word 文档,标题进导航窗格、表格能选中、列表能续编号,用户可以接着改。
+ */
+
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ assertOutputExtension,
+ describeOutput,
+ DocsPathError,
+ prepareOutputPath,
+ resolveSessionRoot,
+} from './_paths.js';
+import { artifactMetadata, errorPayload, okPayload } from './_payload.js';
+import { markdownToDocxBuffer } from './markdownToDocx.js';
+import type { DocsMcpSessionCtx, WriteDocsOutputFn } from './types.js';
+
+export const DOCX_MAX_MARKDOWN_BYTES = 4 * 1024 * 1024;
+export const DOCX_MAX_TITLE_BYTES = 4 * 1024;
+export const DOCX_MAX_SUBTITLE_BYTES = 16 * 1024;
+
+function utf8BoundedString(maxBytes: number, label: string): z.ZodString {
+ return z.string().refine((value) => Buffer.byteLength(value, 'utf8') <= maxBytes, {
+ message: `${label}超过 ${(maxBytes / 1024).toFixed(0)} KiB 上限`,
+ });
+}
+
+const DESCRIPTION = [
+ '把 Markdown 正文生成为真正的 Word 文档(.docx)。',
+ '',
+ '【何时用】用户要 Word / doc / 「可编辑的文档」/ 需要交给别人接着改的正式文稿。',
+ '只要产物要给人二次编辑,就用本工具,不要生成 PDF 再让用户想办法转回去。',
+ '',
+ '【支持的 Markdown】标题 #~######、段落、**粗体**、*斜体*、~~删除线~~、`行内代码`、',
+ '```代码块```、有序/无序列表(含嵌套)、表格(支持列对齐)、> 引用、--- 分隔线、链接。',
+ '图片不内嵌,会降级成 "[图片: 说明]" 文本。',
+ '',
+ '【分页】需要强制分页时,在 Markdown 里单独写一行 `<!-- pagebreak -->`。',
+ '',
+ '【版式】给了 title 默认出独立封面(可用 cover:false 关掉);subtitle 写在封面强调线上方。',
+ 'theme: "light"(默认) / "dark" / "navy"。标题层级、表格色带/斑马纹、正文页脚页码都已内置,',
+ '不需要为了好看去写 HTML。',
+ '',
+ '【输出】outPath 必须在本任务的工作目录内(建议 documents/ 子目录,文件名带日期)。',
+ '目录不存在会自动创建;同名文件默认不覆盖,确要覆盖再传 overwrite: true。',
+ 'Markdown 正文最大 4 MB;超限时请拆成多份文档。',
+].join('\n');
+
+export function registerMakeDocxTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+ writeDocsOutput: WriteDocsOutputFn,
+): void {
+ registry.register({
+ name: 'make_docx',
+ category: 'author',
+ description: DESCRIPTION,
+ inputShape: {
+ markdown: utf8BoundedString(DOCX_MAX_MARKDOWN_BYTES, 'Markdown 正文')
+ .min(1)
+ .describe('文档正文(Markdown),UTF-8 最大 4 MB。'),
+ outPath: z
+ .string()
+ .min(1)
+ .describe(
+ '输出 .docx 路径,工作目录内的相对路径或绝对路径,如 documents/报告-2026-08-19.docx。',
+ ),
+ title: utf8BoundedString(DOCX_MAX_TITLE_BYTES, '文档标题')
+ .optional()
+ .describe('可选文档标题:写进 Word 文档属性;默认再生成一页封面。'),
+ subtitle: utf8BoundedString(DOCX_MAX_SUBTITLE_BYTES, '文档副题')
+ .optional()
+ .describe('封面副题 / 密级 / 来源一行。没给 title 时无效。'),
+ cover: z
+ .boolean()
+ .optional()
+ .describe('是否生成独立封面页。给了 title 时默认 true;没给 title 时无效。'),
+ theme: z
+ .enum(['light', 'dark', 'navy'])
+ .default('light')
+ .describe('配色主题:light / dark / navy。影响标题色、表头色带和斑马纹。'),
+ overwrite: z
+ .boolean()
+ .default(false)
+ .describe('目标文件已存在时是否覆盖。默认 false(存在即报 FILE_EXISTS)。'),
+ },
+ handler: async ({ markdown, outPath, title, subtitle, cover, theme, overwrite }) => {
+ try {
+ const root = resolveSessionRoot(sessionCtx);
+ assertOutputExtension(outPath, '.docx');
+ const abs = await prepareOutputPath(root, outPath, overwrite);
+ const trimmedTitle = title?.trim() ?? '';
+ const useCover = trimmedTitle.length > 0 && (cover ?? true);
+ const buffer = await markdownToDocxBuffer(markdown, {
+ theme,
+ cover: useCover,
+ ...(trimmedTitle.length > 0 ? { title: trimmedTitle } : {}),
+ ...(subtitle ? { subtitle } : {}),
+ });
+ await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+ return okPayload({
+ ...describeOutput(root, abs, buffer.byteLength),
+ format: 'docx',
+ theme,
+ cover: useCover,
+ artifact: artifactMetadata({
+ format: 'docx',
+ ...(trimmedTitle ? { title: trimmedTitle } : {}),
+ ...(subtitle?.trim() ? { subtitle: subtitle.trim() } : {}),
+ theme,
+ cover: useCover,
+ summary: { kind: 'bytes', value: buffer.byteLength },
+ }),
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return errorPayload('DOCX_BUILD_FAILED', `生成 Word 文档失败:${message}`, { message });
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/make_pptx.ts b/packages/lizi-mcps/src/cindy-docs/make_pptx.ts
new file mode 100644
index 0000000000..c2a5d830a9
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/make_pptx.ts
@@ -0,0 +1,881 @@
+/**
+ * cindy-docs/make_pptx.ts —— 结构化幻灯片 → PowerPoint(.pptx)。
+ *
+ * 版式走 pptxgenjs 母版(封面 / 分节 / 内容 / 对比 / 指标 / 大图),色板走 themes.ts。
+ * 模型只选命名主题和结构化版式,不喂色号、不喂自由坐标、不捆图片字体。页脚页码
+ * 登记在母版上,由 PowerPoint 自己递增。
+ */
+
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+
+import * as pptxgenModule from 'pptxgenjs';
+import type pptxgen from 'pptxgenjs';
+import sharp from 'sharp';
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ assertOutputExtension,
+ describeOutput,
+ DocsPathError,
+ prepareInputPath,
+ prepareOutputPath,
+ readInputFileWithinLimit,
+ resolveSessionRoot,
+} from './_paths.js';
+import { artifactMetadata, errorPayload, okPayload } from './_payload.js';
+import {
+ bodyFontSize,
+ DEFAULT_PPTX_LAYOUT,
+ defineCindyPptxMasters,
+ layoutSlots,
+ PPTX_LAYOUT_IDS,
+ PPTX_LAYOUT_NAMES,
+ type PptxLayoutName,
+} from './pptxMasters.js';
+import { DOCS_THEMES, resolveDocsTheme, type DocsThemeName } from './themes.js';
+import type { DocsMcpSessionCtx, WriteDocsOutputFn } from './types.js';
+
+/** 主题色板对外可见,让测试断言真实取值而不是硬编码色号(实现漂移能被测出来)。 */
+export const PPTX_THEMES = DOCS_THEMES;
+
+export {
+ DEFAULT_PPTX_LAYOUT,
+ PPTX_LAYOUT_IDS,
+ PPTX_LAYOUT_NAMES,
+} from './pptxMasters.js';
+
+/**
+ * pptxgenjs 按扩展名决定内嵌资源的 content-type,不认的格式会生成一个 PowerPoint
+ * 打不开的坏包。支持面在这里登记一次,工具描述与运行期校验共用。
+ */
+export const PPTX_SUPPORTED_IMAGE_EXT: ReadonlySet<string> = new Set([
+ '.png',
+ '.jpg',
+ '.jpeg',
+ '.gif',
+]);
+
+/**
+ * 图片会被 base64 编码并写进 zip;原始字节的单文件与整份 deck 上限同时约束
+ * main 进程峰值。总量按「每次使用」累计,重复引用同一张大图也不能绕过。
+ */
+export const PPTX_MAX_IMAGE_BYTES = 12 * 1024 * 1024;
+export const PPTX_MAX_TOTAL_IMAGE_BYTES = 32 * 1024 * 1024;
+/** Keep decode work bounded before handing bytes to pptxgenjs. */
+export const PPTX_MAX_IMAGE_PIXELS = 12_000_000;
+export const PPTX_MAX_SLIDES = 100;
+export const PPTX_MAX_BULLETS_PER_SLIDE = 20;
+export const PPTX_MAX_TOTAL_TEXT_BYTES = 4 * 1024 * 1024;
+const PPTX_MAX_TITLE_CHARS = 1_000;
+const PPTX_MAX_BODY_CHARS = 32_000;
+const PPTX_MAX_NOTES_CHARS = 64_000;
+const PPTX_MAX_BULLET_CHARS = 4_000;
+
+export function isSupportedPptxImage(filePath: string): boolean {
+ return PPTX_SUPPORTED_IMAGE_EXT.has(path.extname(filePath).toLowerCase());
+}
+
+export type PptxImageMime = 'image/png' | 'image/jpeg' | 'image/gif';
+
+/** 按真实字节识别并做结构校验,不能相信模型给的扩展名。 */
+export function detectPptxImageMime(bytes: Buffer): PptxImageMime | null {
+ if (
+ bytes.length >= 45 &&
+ bytes.subarray(0, 8).equals(
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ ) &&
+ bytes.subarray(12, 16).toString('ascii') === 'IHDR'
+ ) {
+ let offset = 8;
+ let sawHeader = false;
+ let sawImageData = false;
+ while (offset + 12 <= bytes.length) {
+ const chunkLength = bytes.readUInt32BE(offset);
+ const type = bytes.subarray(offset + 4, offset + 8).toString('ascii');
+ const chunkEnd = offset + 12 + chunkLength;
+ if (chunkEnd > bytes.length) break;
+ if (type === 'IHDR') {
+ if (
+ sawHeader ||
+ chunkLength !== 13 ||
+ bytes.readUInt32BE(offset + 8) === 0 ||
+ bytes.readUInt32BE(offset + 12) === 0
+ ) return null;
+ sawHeader = true;
+ } else if (type === 'IDAT') {
+ sawImageData = true;
+ } else if (type === 'IEND') {
+ return sawHeader && sawImageData && chunkLength === 0 ? 'image/png' : null;
+ }
+ offset = chunkEnd;
+ }
+ return null;
+ }
+
+ if (
+ bytes.length >= 14 &&
+ (bytes.subarray(0, 6).toString('ascii') === 'GIF87a' ||
+ bytes.subarray(0, 6).toString('ascii') === 'GIF89a') &&
+ bytes.readUInt16LE(6) > 0 &&
+ bytes.readUInt16LE(8) > 0
+ ) {
+ let offset = 13;
+ const logicalPacked = bytes[10]!;
+ if ((logicalPacked & 0x80) !== 0) offset += 3 * 2 ** ((logicalPacked & 0x07) + 1);
+ let sawImage = false;
+ const skipSubBlocks = (): boolean => {
+ while (offset < bytes.length) {
+ const size = bytes[offset++]!;
+ if (size === 0) return true;
+ if (offset + size > bytes.length) return false;
+ offset += size;
+ }
+ return false;
+ };
+ while (offset < bytes.length) {
+ const block = bytes[offset++]!;
+ if (block === 0x3b) return sawImage && offset === bytes.length ? 'image/gif' : null;
+ if (block === 0x21) {
+ if (offset >= bytes.length) return null;
+ offset += 1; // extension label
+ if (!skipSubBlocks()) return null;
+ continue;
+ }
+ if (block !== 0x2c || offset + 9 > bytes.length) return null;
+ const imageWidth = bytes.readUInt16LE(offset + 4);
+ const imageHeight = bytes.readUInt16LE(offset + 6);
+ const imagePacked = bytes[offset + 8]!;
+ offset += 9;
+ if (imageWidth === 0 || imageHeight === 0) return null;
+ if ((imagePacked & 0x80) !== 0) offset += 3 * 2 ** ((imagePacked & 0x07) + 1);
+ if (offset >= bytes.length) return null;
+ offset += 1; // LZW minimum code size
+ if (!skipSubBlocks()) return null;
+ sawImage = true;
+ }
+ return null;
+ }
+
+ if (
+ bytes.length >= 11 &&
+ bytes[0] === 0xff &&
+ bytes[1] === 0xd8 &&
+ bytes[bytes.length - 2] === 0xff &&
+ bytes[bytes.length - 1] === 0xd9
+ ) {
+ let offset = 2;
+ let sawFrame = false;
+ let sawScan = false;
+ while (offset + 1 < bytes.length) {
+ while (offset < bytes.length && bytes[offset] === 0xff) offset += 1;
+ if (offset >= bytes.length) break;
+ const marker = bytes[offset]!;
+ offset += 1;
+ if (marker === 0xd9) return sawFrame && sawScan && offset === bytes.length ? 'image/jpeg' : null;
+ if (marker === 0xda) {
+ if (offset + 2 > bytes.length) return null;
+ const segmentLength = bytes.readUInt16BE(offset);
+ if (!sawFrame || segmentLength < 8 || offset + segmentLength > bytes.length) return null;
+ const componentCount = bytes[offset + 2]!;
+ if (componentCount === 0 || segmentLength !== 6 + componentCount * 2) return null;
+ offset += segmentLength;
+
+ // Scan data may contain stuffed 0xFF bytes, restart markers, and
+ // another marker segment before the next SOS in progressive JPEGs.
+ let scanBytes = 0;
+ let scanEnded = false;
+ while (offset < bytes.length) {
+ if (bytes[offset] !== 0xff) {
+ scanBytes += 1;
+ offset += 1;
+ continue;
+ }
+ let markerOffset = offset + 1;
+ while (markerOffset < bytes.length && bytes[markerOffset] === 0xff) markerOffset += 1;
+ if (markerOffset >= bytes.length) return null;
+ const scanMarker = bytes[markerOffset]!;
+ if (scanMarker === 0x00) {
+ scanBytes += 1;
+ offset = markerOffset + 1;
+ continue;
+ }
+ if (scanMarker >= 0xd0 && scanMarker <= 0xd7) {
+ offset = markerOffset + 1;
+ continue;
+ }
+ if (scanBytes === 0) return null;
+ sawScan = true;
+ offset = markerOffset - 1;
+ scanEnded = true;
+ break;
+ }
+ if (!scanEnded) return null;
+ continue;
+ }
+ if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) continue;
+ if (offset + 2 > bytes.length) break;
+ const segmentLength = bytes.readUInt16BE(offset);
+ if (segmentLength < 2 || offset + segmentLength > bytes.length) break;
+ const isStartOfFrame =
+ (marker >= 0xc0 && marker <= 0xc3) ||
+ (marker >= 0xc5 && marker <= 0xc7) ||
+ (marker >= 0xc9 && marker <= 0xcb) ||
+ (marker >= 0xcd && marker <= 0xcf);
+ if (isStartOfFrame) {
+ if (segmentLength < 8) return null;
+ const componentCount = bytes[offset + 7]!;
+ if (
+ componentCount === 0 ||
+ segmentLength !== 8 + componentCount * 3 ||
+ bytes.readUInt16BE(offset + 3) === 0 ||
+ bytes.readUInt16BE(offset + 5) === 0
+ ) {
+ return null;
+ }
+ sawFrame = true;
+ }
+ offset += segmentLength;
+ }
+ }
+ return null;
+}
+
+/** Decode the payload before handing it to pptxgenjs; signatures alone accept corrupt PNGs.
+ * The encoded output is intentionally discarded: returning a raw RGBA buffer here would
+ * let a compressed image expand to hundreds of MB in the Electron main process.
+ */
+export async function validateDecodablePptxImage(bytes: Buffer): Promise<boolean> {
+ try {
+ const decoded = await sharp(bytes, { limitInputPixels: PPTX_MAX_IMAGE_PIXELS })
+ .ensureAlpha()
+ .png()
+ .toBuffer({ resolveWithObject: true });
+ return decoded.info.width > 0 && decoded.info.height > 0 && decoded.data.byteLength > 0;
+ } catch {
+ return false;
+ }
+}
+
+function pptxImageDataUri(mime: PptxImageMime, bytes: Buffer): string {
+ return `data:${mime};base64,${bytes.toString('base64')}`;
+}
+
+type PptxGenConstructor = new () => pptxgen;
+
+/**
+ * pptxgenjs 是 CommonJS 包:Vitest / 打包后 ESM 会直接给构造器,tsx 按源码
+ * 运行时可能给一层或两层 default wrapper。只写 default import 会让
+ * 单测通过、真实工具运行却在 `new` 处失败。这里做有界的 CJS/ESM 归一。
+ */
+export function resolvePptxGenConstructor(moduleValue: unknown): PptxGenConstructor {
+ let candidate = moduleValue;
+ for (let depth = 0; depth < 4; depth += 1) {
+ if (!candidate || typeof candidate !== 'object' || !('default' in candidate)) break;
+ candidate = (candidate as { default: unknown }).default;
+ }
+ if (typeof candidate !== 'function') {
+ throw new TypeError('pptxgenjs did not expose a constructor');
+ }
+ return candidate as PptxGenConstructor;
+}
+
+const DESCRIPTION = [
+ '把结构化的幻灯片内容生成为 PowerPoint 演示文稿(.pptx)。',
+ '',
+ '【何时用】用户要 PPT / 演示文稿 / 汇报材料 / 「几页讲清楚」。',
+ '',
+ '【每页可给】title(标题,必填)、layout(cover 封面 / section 分节 / content 内容 / comparison 双栏对比 / metrics 数据强调 / image 大图,默认 content)、',
+ 'subtitle(封面副题或分节导语)、bullets(要点数组)、body(整段正文)、',
+ 'notes(演讲者备注,只在演讲者视图可见)、imagePath(content / image 版式可用,工作目录内的 png / jpg / gif)。',
+ '单张图片最大 12 MB,整份演示文稿按每次使用累计最多 32 MB;超限时先压缩图片或减少重复大图。',
+ '整份最多 100 页、每页最多 20 条普通要点、全部文字合计最大 4 MB;超限时请拆分演示文稿。',
+ 'comparison 必须给 columns(恰好两栏,每栏含 title + bullets/body);metrics 必须给 metrics(2–4 个 value + label + 可选 detail);image 必须给 imagePath,图片会自动裁切铺满主体区,body 可作题注。',
+ '',
+ '【主题】theme: "light"(浅色,默认,适合打印和明亮会议室)、"dark"(深色,适合投影)、',
+ '"navy"(商务蓝,适合正式汇报)。三套都是克制色板,不要指望自定义配色。',
+ '',
+ '【版式】封面、分节和普通内容页用于叙事骨架;真正的左右比较用 comparison;关键数字用 metrics;一张图承担主体时用 image。',
+ 'footer 默认 true,会在分节页和除封面外的内容类页面显示页脚标签(用 title)和页码;封面始终不显示页码。',
+ '',
+ '【写作建议】每页只表达一个结论;标题写结论而不是名词短语。首页用 cover,章节切换用 section,不要把“左右对比”或“核心数据”硬塞成普通要点。',
+ '',
+ '【输出】outPath 必须在本任务的工作目录内。同名文件默认不覆盖,确要覆盖再传 overwrite: true。',
+].join('\n');
+
+const ComparisonColumnSchema = z.object({
+ title: z.string().min(1).max(PPTX_MAX_TITLE_CHARS).describe('这一栏的短标题。'),
+ bullets: z
+ .array(z.string().min(1).max(PPTX_MAX_BULLET_CHARS))
+ .max(5)
+ .optional()
+ .describe('这一栏的 1–5 条要点。'),
+ body: z.string().max(PPTX_MAX_BODY_CHARS).optional().describe('这一栏的补充正文。'),
+});
+
+const MetricSchema = z.object({
+ value: z
+ .union([z.string().max(PPTX_MAX_TITLE_CHARS), z.number()])
+ .describe('醒目的指标值,如 98% 或 4。'),
+ label: z.string().min(1).max(PPTX_MAX_TITLE_CHARS).describe('指标名称。'),
+ detail: z.string().max(PPTX_MAX_BODY_CHARS).optional().describe('一句口径或解释。'),
+});
+
+const SlideSchema = z
+ .object({
+ title: z.string().min(1).max(PPTX_MAX_TITLE_CHARS).describe('本页标题。'),
+ layout: z
+ .enum(PPTX_LAYOUT_NAMES)
+ .default(DEFAULT_PPTX_LAYOUT)
+ .describe(
+ '版式:cover 封面 / section 分节 / content 内容 / comparison 双栏对比 / metrics 数据强调 / image 大图。默认 content。',
+ ),
+ subtitle: z
+ .string()
+ .max(PPTX_MAX_BODY_CHARS)
+ .optional()
+ .describe('封面副题、分节导语或内容页标题下的一行说明。'),
+ bullets: z
+ .array(z.string().max(PPTX_MAX_BULLET_CHARS))
+ .max(PPTX_MAX_BULLETS_PER_SLIDE)
+ .optional()
+ .describe('要点数组,建议 3-5 条。'),
+ body: z
+ .string()
+ .max(PPTX_MAX_BODY_CHARS)
+ .optional()
+ .describe('整段正文。与 bullets 可并存(正文排在要点之后)。'),
+ notes: z.string().max(PPTX_MAX_NOTES_CHARS).optional().describe('演讲者备注。'),
+ imagePath: z.string().optional().describe('工作目录内的图片路径(png/jpg/gif)。content 放右半区,image 放通栏主体。'),
+ columns: z
+ .array(ComparisonColumnSchema)
+ .length(2)
+ .optional()
+ .describe('comparison 专用的两栏内容。固定两栏,不接收坐标。'),
+ metrics: z.array(MetricSchema).min(2).max(4).optional().describe('metrics 专用的 2–4 个指标卡。'),
+ })
+ .superRefine((slide, ctx) => {
+ if (slide.layout === 'comparison' && !slide.columns) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['columns'],
+ message: 'comparison 版式需要恰好两栏 columns。',
+ });
+ }
+ if (slide.layout === 'metrics' && !slide.metrics) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['metrics'],
+ message: 'metrics 版式需要 2–4 个 metrics。',
+ });
+ }
+ if (slide.layout === 'image' && !slide.imagePath) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['imagePath'],
+ message: 'image 版式需要 imagePath。',
+ });
+ }
+ if (slide.imagePath && slide.layout !== 'content' && slide.layout !== 'image') {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ['imagePath'],
+ message: 'imagePath 只允许用于 content 或 image 版式。',
+ });
+ }
+
+ const rejectUnused = (field: string, message: string): void => {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [field],
+ message,
+ });
+ };
+ if (slide.layout === 'content') {
+ if (slide.columns) rejectUnused('columns', 'content 版式不接收 columns,请改用 comparison。');
+ if (slide.metrics) rejectUnused('metrics', 'content 版式不接收 metrics,请改用 metrics。');
+ } else if (slide.layout === 'comparison') {
+ if (slide.bullets) rejectUnused('bullets', 'comparison 版式不接收顶层 bullets,请放进 columns。');
+ if (slide.body) rejectUnused('body', 'comparison 版式不接收顶层 body,请放进 columns。');
+ if (slide.metrics) rejectUnused('metrics', 'comparison 版式不接收 metrics,请改用 metrics。');
+ } else if (slide.layout === 'metrics') {
+ if (slide.bullets) rejectUnused('bullets', 'metrics 版式不接收 bullets,请把内容放进 metrics.detail。');
+ if (slide.body) rejectUnused('body', 'metrics 版式不接收 body,请把内容放进 metrics.detail。');
+ if (slide.columns) rejectUnused('columns', 'metrics 版式不接收 columns,请改用 comparison。');
+ } else if (slide.layout === 'image') {
+ if (slide.bullets) rejectUnused('bullets', 'image 版式不接收 bullets,请改用 content。');
+ if (slide.columns) rejectUnused('columns', 'image 版式不接收 columns,请改用 comparison。');
+ if (slide.metrics) rejectUnused('metrics', 'image 版式不接收 metrics,请改用 metrics。');
+ } else {
+ if (slide.columns) rejectUnused('columns', `${slide.layout} 版式不接收 columns,请改用 comparison。`);
+ if (slide.metrics) rejectUnused('metrics', `${slide.layout} 版式不接收 metrics,请改用 metrics。`);
+ }
+ });
+
+function slideTextBytes(slide: z.infer<typeof SlideSchema>): number {
+ const parts: string[] = [slide.title];
+ if (slide.subtitle) parts.push(slide.subtitle);
+ if (slide.body) parts.push(slide.body);
+ if (slide.notes) parts.push(slide.notes);
+ parts.push(...(slide.bullets ?? []));
+ for (const column of slide.columns ?? []) {
+ parts.push(column.title, ...(column.bullets ?? []));
+ if (column.body) parts.push(column.body);
+ }
+ for (const metric of slide.metrics ?? []) {
+ parts.push(String(metric.value), metric.label);
+ if (metric.detail) parts.push(metric.detail);
+ }
+ return parts.reduce((total, part) => total + Buffer.byteLength(part, 'utf8'), 0);
+}
+
+const SlidesSchema = z
+ .array(SlideSchema)
+ .min(1)
+ .max(PPTX_MAX_SLIDES)
+ .superRefine((slides, ctx) => {
+ let totalBytes = 0;
+ for (const slide of slides) {
+ totalBytes += slideTextBytes(slide);
+ if (totalBytes > PPTX_MAX_TOTAL_TEXT_BYTES) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: '演示文稿全部文字超过 4 MB 上限,请拆分后再生成。',
+ });
+ return;
+ }
+ }
+ });
+
+export function registerMakePptxTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+ writeDocsOutput: WriteDocsOutputFn,
+): void {
+ registry.register({
+ name: 'make_pptx',
+ category: 'author',
+ description: DESCRIPTION,
+ inputShape: {
+ slides: SlidesSchema.describe('幻灯片列表,至少一页、最多 100 页。'),
+ outPath: z
+ .string()
+ .min(1)
+ .describe('输出 .pptx 路径,工作目录内的相对路径或绝对路径。'),
+ title: z
+ .string()
+ .max(PPTX_MAX_TITLE_CHARS)
+ .optional()
+ .describe('可选演示文稿标题,写进文件属性,并作为页脚标签。'),
+ theme: z
+ .enum(['light', 'dark', 'navy'])
+ .default('light')
+ .describe('配色主题:light / dark / navy。'),
+ footer: z
+ .boolean()
+ .default(true)
+ .describe('分节页和除封面外的内容类页面是否显示页脚与页码。封面始终不显示页码。默认 true。'),
+ overwrite: z
+ .boolean()
+ .default(false)
+ .describe('目标文件已存在时是否覆盖。默认 false。'),
+ },
+ handler: async ({ slides, outPath, title, theme, footer, overwrite }) => {
+ try {
+ const root = resolveSessionRoot(sessionCtx);
+ assertOutputExtension(outPath, '.pptx');
+ const abs = await prepareOutputPath(root, outPath, overwrite);
+ const palette = resolveDocsTheme(theme as DocsThemeName);
+
+ // 图片先全部过边界闸和字节上限、再转成内存 data URI。后续 pptxgenjs 不再
+ // 按路径二次读取,既封住 stat/read 的竞态,也让 main 的图片峰值有硬上界。
+ const imageDataByIndex = new Map<number, string>();
+ const loadedImages = new Map<string, { bytes: number; data: string }>();
+ let totalImageBytes = 0;
+ for (const [index, slide] of slides.entries()) {
+ if (!slide.imagePath) continue;
+ const imageAbs = await prepareInputPath(root, slide.imagePath);
+ // pptxgenjs 只按扩展名决定内嵌的 content-type,喂个 .webp 进去会生成一个
+ // PowerPoint 打不开的坏包 —— 那正是「看着成功、其实交了坏文件」,必须先拦。
+ if (!isSupportedPptxImage(imageAbs)) {
+ return errorPayload(
+ 'UNSUPPORTED_IMAGE',
+ `第 ${index + 1} 页的图片格式不支持。演示文稿只能内嵌 ${[...PPTX_SUPPORTED_IMAGE_EXT].join(' / ')};请先把它转成 PNG 或 JPG。`,
+ { slide: index + 1, imagePath: imageAbs },
+ );
+ }
+ let loaded = loadedImages.get(imageAbs);
+ if (!loaded) {
+ const bytes = await readInputFileWithinLimit(
+ root,
+ imageAbs,
+ PPTX_MAX_IMAGE_BYTES,
+ (size) =>
+ new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `第 ${index + 1} 页的图片过大: ${size} 字节`,
+ `图片 "${slide.imagePath}" 有 ${(size / 1024 / 1024).toFixed(1)} MB,超过单张图片上限(12 MB)。请先压缩或缩小图片。`,
+ ),
+ );
+ const mime = detectPptxImageMime(bytes);
+ if (!mime || !(await validateDecodablePptxImage(bytes))) {
+ return errorPayload(
+ 'INVALID_IMAGE',
+ `第 ${index + 1} 页的图片内容不是有效的 PNG / JPEG / GIF。请重新导出或更换图片。`,
+ { slide: index + 1, imagePath: imageAbs },
+ );
+ }
+ loaded = { bytes: bytes.byteLength, data: pptxImageDataUri(mime, bytes) };
+ loadedImages.set(imageAbs, loaded);
+ }
+ totalImageBytes += loaded.bytes;
+ if (totalImageBytes > PPTX_MAX_TOTAL_IMAGE_BYTES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `演示文稿图片累计过大: ${totalImageBytes} 字节`,
+ `这份演示文稿引用的图片累计 ${(totalImageBytes / 1024 / 1024).toFixed(1)} MB,超过 32 MB 上限(重复引用也累计)。请压缩图片或减少重复大图。`,
+ );
+ }
+ imageDataByIndex.set(index, loaded.data);
+ }
+
+ const PptxGen = resolvePptxGenConstructor(pptxgenModule);
+ const pptx = new PptxGen();
+ // **不是 LAYOUT_16x9**:那个在 pptxgenjs 里是 10" × 5.625",而 pptxMasters 的
+ // 几何常量按 13.333" × 7.5" 写(现代 PowerPoint 的宽屏默认)。两边对不上的
+ // 后果不是「小一点」——页脚与页码定位在 y=7.02,整个落在页面外,**从来没
+ // 显示过**;正文框也伸出页底,长内容会被裁掉。LAYOUT_WIDE 才是 13.33 × 7.5。
+ pptx.layout = 'LAYOUT_WIDE';
+ if (title) pptx.title = title;
+ pptx.author = 'Cindy';
+
+ defineCindyPptxMasters(pptx, {
+ theme: palette,
+ footer,
+ ...(title ? { footerLabel: title } : {}),
+ });
+
+ const usedLayouts: PptxLayoutName[] = [];
+ for (const [index, slide] of slides.entries()) {
+ const layout: PptxLayoutName = slide.layout ?? DEFAULT_PPTX_LAYOUT;
+ usedLayouts.push(layout);
+ const page = pptx.addSlide({ masterName: PPTX_LAYOUT_IDS[layout] });
+ // 幻灯片自己再刷一次底色:母版底色在 slideLayout 里,测试和解压器读 slide XML
+ // 时也能直接看到主题色,两边不一致就说明登记错了。
+ page.background = { color: palette.background };
+
+ const imageData = imageDataByIndex.get(index);
+ const subtitle = slide.subtitle?.trim() ?? '';
+ const slots = layoutSlots(layout, {
+ hasImage: Boolean(imageData),
+ hasSubtitle: subtitle.length > 0,
+ });
+
+ page.addText(slide.title, {
+ x: slots.title.x,
+ y: slots.title.y,
+ w: slots.title.w,
+ h: slots.title.h,
+ // 标题框高度属于版式契约,不能让长标题静默裁切。交给 PowerPoint
+ // 在固定框内缩小字号,既保留完整文本,也不开放模型自由改坐标/框高。
+ fit: 'shrink',
+ fontSize: slots.title.fontSize,
+ bold: true,
+ color: palette.title,
+ valign: layout === 'cover' || layout === 'section' ? 'top' : 'middle',
+ margin: 0,
+ });
+
+ if (slots.subtitle && subtitle.length > 0) {
+ page.addText(subtitle, {
+ x: slots.subtitle.x,
+ y: slots.subtitle.y,
+ w: slots.subtitle.w,
+ h: slots.subtitle.h,
+ fit: 'shrink',
+ fontSize: slots.subtitle.fontSize,
+ color: palette.muted,
+ valign: 'top',
+ margin: 0,
+ });
+ }
+
+ if (slots.accentLine) {
+ page.addShape('rect', {
+ x: slots.accentLine.x,
+ y: slots.accentLine.y,
+ w: slots.accentLine.w,
+ h: slots.accentLine.h,
+ fill: { color: palette.accent },
+ line: { color: palette.accent, width: 0 },
+ });
+ }
+
+ if (layout === 'comparison') {
+ const columns = slide.columns ?? [];
+ const gap = 0.36;
+ const cardW = (slots.body.w - gap) / 2;
+ for (const [columnIndex, column] of columns.entries()) {
+ const x = slots.body.x + columnIndex * (cardW + gap);
+ page.addShape('rect', {
+ x,
+ y: slots.body.y,
+ w: cardW,
+ h: slots.body.h,
+ fill: { color: palette.surface },
+ line: { color: palette.line, width: 1 },
+ });
+ page.addShape('rect', {
+ x,
+ y: slots.body.y,
+ w: cardW,
+ h: 0.08,
+ fill: { color: palette.accent },
+ line: { color: palette.accent, width: 0 },
+ });
+ page.addText(column.title, {
+ x: x + 0.34,
+ y: slots.body.y + 0.34,
+ w: cardW - 0.68,
+ h: 0.5,
+ fit: 'shrink',
+ fontSize: 20,
+ bold: true,
+ color: palette.title,
+ margin: 0,
+ });
+ const columnBullets = column.bullets ?? [];
+ if (columnBullets.length > 0) {
+ page.addText(
+ columnBullets.map((text) => ({
+ text,
+ options: { bullet: true, breakLine: true },
+ })),
+ {
+ x: x + 0.34,
+ y: slots.body.y + 1.05,
+ w: cardW - 0.68,
+ h: column.body ? slots.body.h - 2.15 : slots.body.h - 1.4,
+ fit: 'shrink',
+ fontSize: bodyFontSize(16, columnBullets.length),
+ color: palette.body,
+ lineSpacingMultiple: 1.35,
+ valign: 'top',
+ margin: 0,
+ },
+ );
+ }
+ if (column.body?.trim()) {
+ page.addText(column.body.trim(), {
+ x: x + 0.34,
+ y: slots.body.y + slots.body.h - 0.92,
+ w: cardW - 0.68,
+ h: 0.58,
+ fit: 'shrink',
+ fontSize: 13,
+ color: palette.muted,
+ margin: 0,
+ valign: 'bottom',
+ });
+ }
+ }
+ } else if (layout === 'metrics') {
+ const metrics = slide.metrics ?? [];
+ const columns = metrics.length <= 3 ? metrics.length : 2;
+ const rows = Math.ceil(metrics.length / columns);
+ const gapX = 0.3;
+ const gapY = 0.28;
+ const cardW = (slots.body.w - gapX * (columns - 1)) / columns;
+ const cardH = (slots.body.h - gapY * (rows - 1)) / rows;
+ for (const [metricIndex, metric] of metrics.entries()) {
+ const column = metricIndex % columns;
+ const row = Math.floor(metricIndex / columns);
+ const x = slots.body.x + column * (cardW + gapX);
+ const y = slots.body.y + row * (cardH + gapY);
+ page.addShape('rect', {
+ x,
+ y,
+ w: cardW,
+ h: cardH,
+ fill: { color: palette.surface },
+ line: { color: palette.line, width: 1 },
+ });
+ page.addText(String(metric.value), {
+ x: x + 0.3,
+ y: y + 0.36,
+ w: cardW - 0.6,
+ h: Math.min(0.95, cardH * 0.4),
+ fit: 'shrink',
+ fontSize: metrics.length <= 3 ? 32 : 27,
+ bold: true,
+ color: palette.accent,
+ margin: 0,
+ });
+ page.addText(metric.label, {
+ x: x + 0.3,
+ y: y + Math.min(1.36, cardH * 0.48),
+ w: cardW - 0.6,
+ h: 0.42,
+ fit: 'shrink',
+ fontSize: 16,
+ bold: true,
+ color: palette.title,
+ margin: 0,
+ });
+ if (metric.detail?.trim()) {
+ page.addText(metric.detail.trim(), {
+ x: x + 0.3,
+ y: y + Math.min(1.92, cardH * 0.7),
+ w: cardW - 0.6,
+ h: Math.max(0.36, cardH * 0.22),
+ fit: 'shrink',
+ fontSize: 12,
+ color: palette.muted,
+ margin: 0,
+ valign: 'top',
+ });
+ }
+ }
+ } else if (layout === 'image') {
+ if (imageData && slots.image) {
+ page.addShape('rect', {
+ x: slots.image.x,
+ y: slots.image.y,
+ w: slots.image.w,
+ h: slots.image.h,
+ fill: { color: palette.surface },
+ line: { color: palette.line, width: 1 },
+ });
+ page.addImage({
+ data: imageData,
+ x: slots.image.x,
+ y: slots.image.y,
+ w: slots.image.w,
+ h: slots.image.h,
+ sizing: { type: 'cover', w: slots.image.w, h: slots.image.h },
+ });
+ }
+ if (slide.body?.trim()) {
+ page.addText(slide.body.trim(), {
+ x: slots.body.x,
+ y: slots.body.y,
+ w: slots.body.w,
+ h: slots.body.h,
+ fit: 'shrink',
+ fontSize: slots.body.fontSize,
+ color: palette.muted,
+ align: 'right',
+ margin: 0,
+ });
+ }
+ } else {
+ const hasBullets = Boolean(slide.bullets && slide.bullets.length > 0);
+ const hasBody = Boolean(slide.body && slide.body.trim().length > 0);
+ if (hasBullets || hasBody) {
+ const bulletBlockH = hasBullets
+ ? Math.min(
+ slots.body.h * 0.72,
+ 0.42 * (slide.bullets?.length ?? 0) + 0.25,
+ )
+ : 0;
+ if (hasBullets) {
+ page.addText(
+ slide.bullets!.map((text) => ({
+ text,
+ options: { bullet: true, breakLine: true },
+ })),
+ {
+ x: slots.body.x,
+ y: slots.body.y,
+ w: slots.body.w,
+ h: hasBody ? bulletBlockH : slots.body.h,
+ fit: 'shrink',
+ // 要点少就放大字号占住版面(见 bodyFontSize)。正文一律顶着标题排 ——
+ // 试过垂直居中,目检下来标题与正文之间裂开一条空白,更糟。
+ fontSize: hasBody
+ ? slots.body.fontSize
+ : bodyFontSize(
+ slots.body.fontSize,
+ slide.bullets?.length ?? 0,
+ ),
+ color: palette.body,
+ // 行距放到 1.5:1.3 在实机目检里几行要点糊成一坨,读起来很挤。
+ lineSpacingMultiple: 1.5,
+ valign: 'top',
+ margin: 0,
+ },
+ );
+ }
+ if (hasBody) {
+ const bodyY = hasBullets
+ ? slots.body.y + bulletBlockH + 0.12
+ : slots.body.y;
+ page.addText(slide.body!.trim(), {
+ x: slots.body.x,
+ y: bodyY,
+ w: slots.body.w,
+ h: Math.max(0.6, slots.body.y + slots.body.h - bodyY),
+ fit: 'shrink',
+ fontSize: Math.max(13, slots.body.fontSize - 3),
+ color: palette.muted,
+ lineSpacingMultiple: 1.35,
+ valign: 'top',
+ margin: 0,
+ });
+ }
+ }
+ }
+
+ if (layout !== 'image' && imageData && slots.image) {
+ page.addImage({
+ data: imageData,
+ x: slots.image.x,
+ y: slots.image.y,
+ w: slots.image.w,
+ h: slots.image.h,
+ sizing: { type: 'contain', w: slots.image.w, h: slots.image.h },
+ });
+ }
+ if (slide.notes && slide.notes.length > 0) page.addNotes(slide.notes);
+ }
+
+ const buffer = (await pptx.write({
+ outputType: 'nodebuffer',
+ })) as Buffer;
+ await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+ return okPayload({
+ ...describeOutput(root, abs, buffer.byteLength),
+ format: 'pptx',
+ theme,
+ footer,
+ slides: slides.length,
+ layouts: usedLayouts,
+ artifact: artifactMetadata({
+ format: 'pptx',
+ ...(title?.trim()
+ ? { title: title.trim() }
+ : slides[0]?.title
+ ? { title: slides[0].title }
+ : {}),
+ theme,
+ cover: slides.some(
+ (slide) => (slide.layout ?? DEFAULT_PPTX_LAYOUT) === 'cover',
+ ),
+ summary: { kind: 'slides', value: slides.length },
+ }),
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return errorPayload(
+ 'PPTX_BUILD_FAILED',
+ `生成演示文稿失败:${message}`,
+ { message },
+ );
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts b/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts
new file mode 100644
index 0000000000..cf8ef8d055
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/make_xlsx.ts
@@ -0,0 +1,487 @@
+/**
+ * cindy-docs/make_xlsx.ts —— 结构化数据 → Excel 工作簿(.xlsx)。
+ *
+ * 表头处理是刻意的:加粗 + 浅底 + 冻结首行 + 按内容估宽。用户拿到的第一屏就
+ * 应该是能直接看的表,而不是一片等宽未冻结的裸数据。
+ */
+
+import ExcelJS from 'exceljs';
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ assertOutputExtension,
+ describeOutput,
+ DocsPathError,
+ prepareOutputPath,
+ resolveSessionRoot,
+} from './_paths.js';
+import { artifactMetadata, errorPayload, okPayload } from './_payload.js';
+import {
+ DEFAULT_DOCS_THEME,
+ resolveDocsTheme,
+ themeToArgb,
+ type DocsTheme,
+ type DocsThemeName,
+} from './themes.js';
+import type { DocsMcpSessionCtx, WriteDocsOutputFn } from './types.js';
+
+/** 列宽估算上下限:太窄看不全,太宽一屏放不下几列。 */
+const MIN_COL_WIDTH = 8;
+const MAX_COL_WIDTH = 60;
+/** 只用前若干行估宽 —— 万行表逐格量宽既慢又没必要。 */
+const WIDTH_SAMPLE_ROWS = 200;
+const BORDER_ROW_CAP = 2000;
+/** ExcelJS 会在当前进程中构建整棵工作簿对象树,输入必须先过硬边界。 */
+const MAX_XLSX_SHEETS = 32;
+const MAX_XLSX_ROWS_PER_SHEET = 5000;
+const MAX_XLSX_COLUMNS = 256;
+const MAX_XLSX_CELL_TEXT_CHARS = 32_767;
+const MAX_XLSX_FORMULA_CHARS = 8192;
+const MAX_XLSX_TOTAL_CELLS = 100_000;
+const MAX_XLSX_TOTAL_TEXT_BYTES = 8 * 1024 * 1024;
+
+const DESCRIPTION = [
+ '把结构化数据生成为 Excel 工作簿(.xlsx),支持多个工作表。',
+ '',
+ '【何时用】用户要 Excel / 表格文件 / 对账表 / 可以自己排序筛选的数据。',
+ '数据本身要是二维的(行 × 列);一段叙述性文字应该用 make_docx 而不是本工具。',
+ '',
+ '【格式】每张表的 header 会加粗 + 主题强调色带 + 冻结首行,列宽按内容自适应。',
+ '数据行默认斑马纹;整数列自动千分位,0–1 的占比列(表头含 % / 率 / 占比)自动百分号。',
+ 'theme: "light"(默认) / "dark" / "navy";zebra 默认 true。',
+ 'rows 里的每个单元格可以是字符串、数字、布尔或 null(留空)。',
+ '数字请传数字类型而不是字符串,否则 Excel 里不能参与求和。',
+ `单份工作簿最多 ${MAX_XLSX_SHEETS} 张表、每表 ${MAX_XLSX_ROWS_PER_SHEET} 行 × ${MAX_XLSX_COLUMNS} 列、合计 ${MAX_XLSX_TOTAL_CELLS} 个单元格。`,
+ '',
+ '【公式】要写公式就传 { formula, result },例如',
+ '{ "formula": "SUM(B2:B4)", "result": 3060 }。',
+ '**result(算好的值)必填**:xlsx 文件本身不存公式的计算结果,少了它,用户在',
+ 'Excel 里点开重算之前那一格是空的,预览、Numbers 和各种解析库也全读到空值。',
+ '你既然写得出这个公式,就把结果一并算出来填上。',
+ '',
+ '【输出】outPath 必须在本任务的工作目录内。目录不存在会自动创建;',
+ '同名文件默认不覆盖,确要覆盖再传 overwrite: true。',
+].join('\n');
+
+/**
+ * 公式单元格。**result 是刻意必填的**:xlsx 只存公式文本,不存值 —— 缓存值要写文件
+ * 的人自己填。少了它,Excel/WPS 打开重算前那一格是空的,而 Numbers、预览、大多数
+ * 解析库(含本工具的 read_sheet)直接读到 null。业界绕这个坑的常见做法是「写完再拿
+ * LibreOffice 重算一遍」,那等于给文档功能绑一个系统级依赖 —— 我们不走那条路,
+ * 改成让调用方把算好的值一起给过来。模型本来就知道这个数,写下来是零成本的。
+ */
+const CellTextSchema = z.string().max(MAX_XLSX_CELL_TEXT_CHARS);
+
+const FormulaCellSchema = z.object({
+ formula: z
+ .string()
+ .min(1)
+ .max(MAX_XLSX_FORMULA_CHARS)
+ .describe('Excel 公式,不带开头的等号,如 "SUM(B2:B10)"。'),
+ result: z
+ .union([CellTextSchema, z.number(), z.boolean()])
+ .describe('公式的计算结果(缓存值)。必填 —— 没有它,打开文件重算前这格是空的。'),
+});
+
+const CellSchema = z.union([
+ CellTextSchema,
+ z.number(),
+ z.boolean(),
+ z.null(),
+ FormulaCellSchema,
+]);
+
+const SheetSchema = z.object({
+ name: z
+ .string()
+ .min(1)
+ .max(31)
+ .describe('工作表名。Excel 限 31 字符,且不能含 : \\ / ? * [ ]。'),
+ header: z
+ .array(CellTextSchema)
+ .max(MAX_XLSX_COLUMNS)
+ .optional()
+ .describe('可选表头行。给了就会加粗 + 主题色带 + 冻结首行。'),
+ rows: z
+ .array(z.array(CellSchema).max(MAX_XLSX_COLUMNS))
+ .max(MAX_XLSX_ROWS_PER_SHEET)
+ .describe('数据行,每行是一个单元格数组。数字请用数字类型。'),
+});
+
+const SheetsSchema = z.array(SheetSchema).min(1).max(MAX_XLSX_SHEETS);
+
+type XlsxSheetInput = z.infer<typeof SheetSchema>;
+
+/** 聚合边界需在 ExcelJS 构造 Workbook 之前执行,避免先实体化再报错。 */
+export function assertXlsxAggregateBounds(sheets: readonly XlsxSheetInput[]): void {
+ let totalCells = 0;
+ let totalTextBytes = 0;
+ const addText = (value: unknown): void => {
+ if (typeof value === 'string') totalTextBytes += Buffer.byteLength(value, 'utf8');
+ };
+ for (const sheet of sheets) {
+ totalCells += sheet.header?.length ?? 0;
+ for (const header of sheet.header ?? []) addText(header);
+ for (const row of sheet.rows) {
+ totalCells += row.length;
+ for (const cell of row) {
+ if (isFormulaCell(cell)) {
+ addText(cell.formula);
+ addText(cell.result);
+ } else {
+ addText(cell);
+ }
+ }
+ }
+ if (totalCells > MAX_XLSX_TOTAL_CELLS) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `工作簿合计超过 ${MAX_XLSX_TOTAL_CELLS} 个单元格`,
+ `请把工作簿拆分到不超过 ${MAX_XLSX_TOTAL_CELLS} 个单元格后重试。`,
+ );
+ }
+ if (totalTextBytes > MAX_XLSX_TOTAL_TEXT_BYTES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ '工作簿文本合计超过 8 MB',
+ '请缩短单元格文本或拆分工作簿后重试。',
+ );
+ }
+ }
+}
+
+type FormulaCell = z.infer<typeof FormulaCellSchema>;
+
+function isFormulaCell(value: unknown): value is FormulaCell {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ !Array.isArray(value) &&
+ typeof (value as { formula?: unknown }).formula === 'string'
+ );
+}
+
+/** 公式文本允许带或不带前导 '='(模型两种都会写),统一剥掉再交给 exceljs。 */
+function normalizeFormula(formula: string): string {
+ return formula.startsWith('=') ? formula.slice(1) : formula;
+}
+
+/** 落到 exceljs 的实际单元格值。公式格走 { formula, result } 形态(原生支持缓存值)。 */
+function toExcelValue(cell: unknown): unknown {
+ if (isFormulaCell(cell)) {
+ return {
+ formula: normalizeFormula(cell.formula),
+ result: cell.result,
+ };
+ }
+ return cell === null ? null : cell;
+}
+
+function cellText(value: unknown): string {
+ if (value === null || value === undefined) return '';
+ // 列宽按「用户会看到的东西」估:公式格显示的是结果,不是公式文本。
+ if (isFormulaCell(value)) return value.result === null ? '' : String(value.result);
+ return String(value);
+}
+
+function numericSamples(values: unknown[]): number[] {
+ const out: number[] = [];
+ for (const value of values) {
+ if (typeof value === 'number' && Number.isFinite(value)) {
+ out.push(value);
+ continue;
+ }
+ if (isFormulaCell(value) && typeof value.result === 'number' && Number.isFinite(value.result)) {
+ out.push(value.result);
+ }
+ }
+ return out;
+}
+
+/** 按表头语义 + 列里的数推断一种对人友好的默认数字格式。 */
+export function inferNumberFormat(
+ header: string | undefined,
+ values: unknown[],
+): string | undefined {
+ const nums = numericSamples(values);
+ if (nums.length === 0) return undefined;
+ const label = header ?? '';
+ /*
+ 单字「率」必须在里面。原来写的是「比率」,于是「退款率」「转化率」「完成率」
+ 这些最常见的百分比列一个都匹配不上 —— 而工具描述明明白白承诺了「表头含
+ % / 率 / 占比 自动百分号」。目检一眼看穿:那一列显示的是 0.03,不是 3.3%。
+
+ 放宽到单字不会误伤:下面那道 0–1 区间闸把「汇率」「频率」这类大于 1 的挡在
+ 外面,匹配上了也不会套百分号。
+ */
+ const looksPercent = /[%%]|率|占比|比例|百分|percent|rate|ratio|share/i.test(label);
+ if (looksPercent && nums.every((n) => n >= 0 && n <= 1)) return '0.0%';
+ if (nums.every((n) => Number.isInteger(n))) return '#,##0';
+ return '#,##0.00';
+}
+
+/**
+ * 列宽要按**用户看到的字符数**算,不是按原始值。
+ *
+ * 原来量的是 `String(986400)`(6 字),而单元格实际显示 `986,400`(7 字);百分比列
+ * 更离谱:量 `0.0325`(6 字),显示 `3.3%`(4 字)。前者让金额列偏窄 —— Excel 放不下
+ * 就显示一整格 `#####`,这是「表格很破」最直接的一种。
+ *
+ * 只做宽度估算用,不追求和 Excel 的渲染逐像素一致。
+ */
+export function formattedWidthSample(text: string, numFmt: string | undefined): string {
+ if (!numFmt) return text;
+ const n = Number(text);
+ if (!Number.isFinite(n) || text.trim() === '') return text;
+ if (numFmt.includes('%')) return `${(n * 100).toFixed(1)}%`;
+ const digits = numFmt.includes('.00') ? 2 : 0;
+ return n.toLocaleString('en-US', {
+ minimumFractionDigits: digits,
+ maximumFractionDigits: digits,
+ });
+}
+
+/**
+ * 汇总行判定 —— **按结构判,不按字眼判**。
+ *
+ * 「最后一行的非空格里公式格占多数」就是汇总行:它的数是**算出来的**,不是录入的。
+ * 这条规则不需要维护一张「合计 / 总计 / 小计 / Total / 合計 / 합계…」的词表,
+ * 换任何语言都成立,也不会因为某张表把汇总行叫「本季累计」就漏判。
+ *
+ * 只看最后一行:整表都是公式的场景(比如一张纯计算表)不该每行都被强调。
+ */
+export function isSummaryRow(row: readonly unknown[]): boolean {
+ const filled = row.filter((cell) => cell !== null && cell !== undefined && cell !== '');
+ if (filled.length === 0) return false;
+ const formulas = filled.filter((cell) => isFormulaCell(cell)).length;
+ return formulas * 2 > filled.length;
+}
+
+function paintRow(
+ row: ExcelJS.Row,
+ fillArgb: string,
+ font?: Partial<ExcelJS.Font>,
+ columnCount?: number,
+): void {
+ const paint = (cell: ExcelJS.Cell): void => {
+ cell.fill = {
+ type: 'pattern',
+ pattern: 'solid',
+ fgColor: { argb: fillArgb },
+ };
+ if (font) cell.font = { ...(cell.font ?? {}), ...font };
+ };
+ if (columnCount !== undefined) {
+ for (let column = 1; column <= columnCount; column += 1) paint(row.getCell(column));
+ return;
+ }
+ row.eachCell({ includeEmpty: true }, paint);
+}
+
+function applyThinBorder(
+ ws: ExcelJS.Worksheet,
+ theme: DocsTheme,
+ rows: number,
+ cols: number,
+): void {
+ if (rows === 0 || cols === 0 || rows * cols > BORDER_ROW_CAP * 8) return;
+ const border = {
+ style: 'thin' as const,
+ color: { argb: themeToArgb(theme.line) },
+ };
+ const box = { top: border, bottom: border, left: border, right: border };
+ const limit = Math.min(rows, BORDER_ROW_CAP);
+ for (let r = 1; r <= limit; r += 1) {
+ for (let c = 1; c <= cols; c += 1) {
+ ws.getCell(r, c).border = box;
+ }
+ }
+}
+
+/** 估算显示宽度:CJK 与全角字符占两格,其余占一格。 */
+function displayWidth(text: string): number {
+ let width = 0;
+ for (const ch of text) {
+ const code = ch.codePointAt(0) ?? 0;
+ const wide =
+ (code >= 0x1100 && code <= 0x115f) ||
+ (code >= 0x2e80 && code <= 0xa4cf) ||
+ (code >= 0xac00 && code <= 0xd7a3) ||
+ (code >= 0xf900 && code <= 0xfaff) ||
+ (code >= 0xfe30 && code <= 0xfe6f) ||
+ (code >= 0xff00 && code <= 0xff60) ||
+ (code >= 0xffe0 && code <= 0xffe6);
+ width += wide ? 2 : 1;
+ }
+ return width;
+}
+
+export function registerMakeXlsxTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+ writeDocsOutput: WriteDocsOutputFn,
+): void {
+ registry.register({
+ name: 'make_xlsx',
+ category: 'author',
+ description: DESCRIPTION,
+ inputShape: {
+ sheets: SheetsSchema.describe('工作表列表,至少一张。'),
+ outPath: z.string().min(1).describe('输出 .xlsx 路径,工作目录内的相对路径或绝对路径。'),
+ theme: z
+ .enum(['light', 'dark', 'navy'])
+ .default('light')
+ .describe('配色主题:light / dark / navy。影响表头色带和斑马纹。'),
+ zebra: z.boolean().default(true).describe('数据行是否打斑马纹。默认 true。'),
+ overwrite: z.boolean().default(false).describe('目标文件已存在时是否覆盖。默认 false。'),
+ },
+ handler: async ({ sheets, outPath, theme, zebra, overwrite }) => {
+ try {
+ assertXlsxAggregateBounds(sheets);
+ const root = resolveSessionRoot(sessionCtx);
+ assertOutputExtension(outPath, '.xlsx');
+ const abs = await prepareOutputPath(root, outPath, overwrite);
+ const palette = resolveDocsTheme((theme ?? DEFAULT_DOCS_THEME) as DocsThemeName);
+
+ const workbook = new ExcelJS.Workbook();
+ workbook.creator = 'Cindy';
+ workbook.created = new Date();
+
+ // Excel 的工作表名比较大小写不敏感,但展示名仍保留用户原始大小写。
+ const usedNames = new Set<string>();
+ const writtenSheets: Array<{ name: string; rows: number }> = [];
+ for (const sheet of sheets) {
+ // Excel 的非法工作表字符会让文件直接打不开,静默换成下划线比报错更有用。
+ let name = sheet.name.replace(/[:\\/?*[\]]/g, '_').slice(0, 31);
+ if (name.trim().length === 0) name = 'Sheet';
+ let unique = name;
+ let n = 2;
+ while (usedNames.has(unique.toLowerCase())) {
+ const suffix = `_${n}`;
+ unique = `${name.slice(0, 31 - suffix.length)}${suffix}`;
+ n += 1;
+ }
+ usedNames.add(unique.toLowerCase());
+
+ const ws = workbook.addWorksheet(unique);
+ writtenSheets.push({ name: unique, rows: sheet.rows.length });
+ const columnCount = Math.max(
+ sheet.header?.length ?? 0,
+ ...sheet.rows.map((row) => row.length),
+ 1,
+ );
+ if (sheet.header && sheet.header.length > 0) {
+ const headerRow = ws.addRow(sheet.header);
+ headerRow.font = {
+ bold: true,
+ color: { argb: themeToArgb(palette.accentOn) },
+ };
+ paintRow(
+ headerRow,
+ themeToArgb(palette.accent),
+ { bold: true, color: { argb: themeToArgb(palette.accentOn) } },
+ columnCount,
+ );
+ headerRow.alignment = { vertical: 'middle' };
+ ws.views = [{ state: 'frozen', ySplit: 1 }];
+ }
+ // 最后一行是不是汇总行,决定它不打斑马纹、而是单独强调(见 isSummaryRow)。
+ const lastIndex = sheet.rows.length - 1;
+ const summaryIndex =
+ lastIndex >= 0 && isSummaryRow(sheet.rows[lastIndex]!) ? lastIndex : -1;
+
+ for (const [rowIndex, row] of sheet.rows.entries()) {
+ const excelRow = ws.addRow(row.map(toExcelValue));
+ // 先给每个正文格落完整主题底色和前景色,再叠斑马/汇总样式。
+ // 不能只给 dark 的斑马行涂深底:那会形成白底黑字/深底黑字交替。
+ paintRow(
+ excelRow,
+ themeToArgb(palette.background),
+ { color: { argb: themeToArgb(palette.body) } },
+ columnCount,
+ );
+ if (rowIndex === summaryIndex) {
+ /*
+ 汇总行必须一眼能和数据行分开。原来它混在斑马纹里,和普通一行长得
+ 一模一样 —— 一张表最重要的那一行反而最不显眼。给的是加粗 + 一条
+ 上边框(会计里表示「以上求和」的那条线)+ 一层浅底,不换字色,
+ 免得在三套主题下有一套对比度翻车。
+ */
+ paintRow(excelRow, themeToArgb(palette.surface), { bold: true }, columnCount);
+ excelRow.eachCell({ includeEmpty: true }, (cell) => {
+ cell.border = {
+ ...(cell.border ?? {}),
+ top: {
+ style: 'thin',
+ color: { argb: themeToArgb(palette.accent) },
+ },
+ };
+ });
+ } else if (zebra && rowIndex % 2 === 1) {
+ paintRow(excelRow, themeToArgb(palette.zebra), undefined, columnCount);
+ }
+ }
+ for (let col = 0; col < columnCount; col += 1) {
+ // 先定数字格式,再按**格式化后的样子**量宽 —— 反过来会让千分位金额列
+ // 偏窄,用户打开看到一整格 `#####`(见 formattedWidthSample)。
+ const numFmt = inferNumberFormat(
+ sheet.header?.[col],
+ sheet.rows.map((row) => row[col]),
+ );
+ let width = displayWidth(cellText(sheet.header?.[col]));
+ const sampled = sheet.rows.slice(0, WIDTH_SAMPLE_ROWS);
+ for (const row of sampled) {
+ width = Math.max(
+ width,
+ displayWidth(formattedWidthSample(cellText(row[col]), numFmt)),
+ );
+ }
+ const column = ws.getColumn(col + 1);
+ column.width = Math.min(MAX_COL_WIDTH, Math.max(MIN_COL_WIDTH, width + 2));
+ if (numFmt) {
+ column.numFmt = numFmt;
+ column.alignment = { horizontal: 'right' };
+ }
+ }
+ if (sheet.header && sheet.header.length > 0) {
+ ws.autoFilter = {
+ from: { row: 1, column: 1 },
+ to: { row: ws.rowCount, column: columnCount },
+ };
+ }
+ applyThinBorder(ws, palette, ws.rowCount, columnCount);
+ }
+
+ const arrayBuffer = await workbook.xlsx.writeBuffer();
+ await writeDocsOutput({
+ root,
+ path: abs,
+ data: Buffer.from(arrayBuffer as ArrayBuffer),
+ overwrite,
+ });
+ return okPayload({
+ ...describeOutput(root, abs, arrayBuffer.byteLength),
+ format: 'xlsx',
+ theme,
+ zebra,
+ sheets: writtenSheets,
+ artifact: artifactMetadata({
+ format: 'xlsx',
+ ...(sheets[0]?.name ? { title: sheets[0].name } : {}),
+ theme,
+ summary: { kind: 'sheets', value: sheets.length },
+ }),
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return errorPayload('XLSX_BUILD_FAILED', `生成 Excel 失败:${message}`, {
+ message,
+ });
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/markdownToDocx.ts b/packages/lizi-mcps/src/cindy-docs/markdownToDocx.ts
new file mode 100644
index 0000000000..33b0bb3eab
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/markdownToDocx.ts
@@ -0,0 +1,491 @@
+/**
+ * cindy-docs/markdownToDocx.ts —— Markdown → docx 文档树。
+ *
+ * 链路:marked 只做词法解析(lexer,不生成 HTML),我们自己把 token 映射成 docx
+ * 的段落/表格对象。不走「markdown → HTML → docx」是因为中间那层 HTML 会把
+ * 结构信息压扁成样式,再还原回 Word 的语义样式(标题级别、列表编号、表格)就只能靠猜。
+ *
+ * 覆盖:标题(h1-h6)、段落、粗体/斜体/删除线、行内代码、链接、代码块、
+ * 有序/无序列表(含嵌套)、表格、引用、分隔线,以及显式分页符约定
+ * `<!-- pagebreak -->`(独占一行)。
+ *
+ * 未覆盖(有意):图片、脚注、HTML 内联。这些要么需要外部资源解析(与路径边界
+ * 冲突),要么在 Word 里没有对应的语义结构;遇到时降级成纯文本,不静默丢内容。
+ */
+
+import {
+ AlignmentType,
+ BorderStyle,
+ Document,
+ HeadingLevel,
+ LevelFormat,
+ Packer,
+ PageBreak,
+ Paragraph,
+ Table,
+ TableRow,
+ TextRun,
+ ExternalHyperlink,
+ type IParagraphOptions,
+ type ParagraphChild,
+} from 'docx';
+import { marked, type Token, type Tokens } from 'marked';
+
+import {
+ docxBodyFooter,
+ docxBodySectionProperties,
+ docxCoverSection,
+ docxDocumentStyles,
+ styledDocxBodyCell,
+ styledDocxHeaderCell,
+ styledDocxTable,
+ columnPercents,
+} from './docxStyles.js';
+import {
+ DEFAULT_DOCS_THEME,
+ resolveDocsTheme,
+ type DocsTheme,
+ type DocsThemeName,
+} from './themes.js';
+
+/** 有序列表 numbering reference 的前缀;每个列表独立配置起始数字并重新编号。 */
+const ORDERED_REF_PREFIX = 'cindy-docs-ordered';
+const MONO_FONT = 'Courier New';
+
+const HEADING_BY_DEPTH = [
+ HeadingLevel.HEADING_1,
+ HeadingLevel.HEADING_2,
+ HeadingLevel.HEADING_3,
+ HeadingLevel.HEADING_4,
+ HeadingLevel.HEADING_5,
+ HeadingLevel.HEADING_6,
+] as const;
+
+/** 独占一行的分页符约定。大小写不敏感,允许注释内前后空格。 */
+const PAGE_BREAK_RE = /^<!--\s*pagebreak\s*-->$/i;
+
+interface InlineStyle {
+ bold?: boolean;
+ italics?: boolean;
+ strike?: boolean;
+ color?: string;
+}
+
+/** 把 marked 的 inline token 递归摊成 docx run。未知类型降级为纯文本,不丢内容。 */
+function inlineRuns(
+ tokens: Token[] | undefined,
+ theme: DocsTheme,
+ style: InlineStyle = {},
+): ParagraphChild[] {
+ if (!tokens || tokens.length === 0) return [];
+ const out: ParagraphChild[] = [];
+ for (const token of tokens) {
+ switch (token.type) {
+ case 'strong':
+ out.push(
+ ...inlineRuns((token as Tokens.Strong).tokens, theme, {
+ ...style,
+ bold: true,
+ }),
+ );
+ break;
+ case 'em':
+ out.push(
+ ...inlineRuns((token as Tokens.Em).tokens, theme, {
+ ...style,
+ italics: true,
+ }),
+ );
+ break;
+ case 'del':
+ out.push(
+ ...inlineRuns((token as Tokens.Del).tokens, theme, {
+ ...style,
+ strike: true,
+ }),
+ );
+ break;
+ case 'codespan':
+ out.push(
+ new TextRun({
+ text: (token as Tokens.Codespan).text,
+ font: MONO_FONT,
+ shading: { fill: theme.surface },
+ ...style,
+ }),
+ );
+ break;
+ case 'link': {
+ const link = token as Tokens.Link;
+ const children = inlineRuns(link.tokens, theme, style);
+ out.push(
+ new ExternalHyperlink({
+ link: link.href,
+ children:
+ children.length > 0
+ ? children
+ : [new TextRun({ text: link.text ?? link.href, ...style })],
+ }),
+ );
+ break;
+ }
+ case 'br':
+ out.push(new TextRun({ text: '', break: 1 }));
+ break;
+ case 'image': {
+ // 图片不内嵌(要读外部字节,与路径边界冲突),降级成「alt (url)」文本,
+ // 让用户至少知道这里原本有张图、图在哪。
+ const image = token as Tokens.Image;
+ const label = image.text && image.text.length > 0 ? image.text : image.href;
+ out.push(new TextRun({ text: `[图片: ${label}]`, italics: true, ...style }));
+ break;
+ }
+ default: {
+ const nested = (token as { tokens?: Token[] }).tokens;
+ if (nested && nested.length > 0) {
+ out.push(...inlineRuns(nested, theme, style));
+ break;
+ }
+ const text =
+ (token as { text?: string; raw?: string }).text ?? (token as { raw?: string }).raw ?? '';
+ if (text.length > 0) out.push(new TextRun({ text, ...style }));
+ break;
+ }
+ }
+ }
+ return out;
+}
+
+/** 跨整篇文档共享的编号配置状态;每个有序列表保留自己的起始数字与编号引用。 */
+interface BlockContext {
+ theme: DocsTheme;
+ nextOrderedListId: number;
+ orderedLists: Array<{ reference: string; level: number; start: number }>;
+}
+
+function quoteParagraphStyle(theme: DocsTheme) {
+ return {
+ indent: { left: 360 },
+ border: {
+ left: {
+ style: BorderStyle.SINGLE,
+ size: 12,
+ space: 8,
+ color: theme.muted,
+ },
+ },
+ } as const;
+}
+
+function listParagraphs(
+ list: Tokens.List,
+ depth: number,
+ ctx: BlockContext,
+): Array<Paragraph | Table> {
+ const out: Array<Paragraph | Table> = [];
+ const level = Math.min(depth, 3);
+ const orderedReference = list.ordered
+ ? `${ORDERED_REF_PREFIX}-${ctx.nextOrderedListId++}`
+ : undefined;
+ if (orderedReference) {
+ const start =
+ Number.isInteger(list.start) && (list.start as number) >= 0 ? (list.start as number) : 1;
+ ctx.orderedLists.push({ reference: orderedReference, level, start });
+ }
+ for (const item of list.items) {
+ const numbering: IParagraphOptions['numbering'] = orderedReference
+ ? { reference: orderedReference, level, instance: 0 }
+ : undefined;
+ const marker = numbering ? { numbering } : { bullet: { level } };
+ let markerWritten = false;
+ const writeMarker = (children: ParagraphChild[]): void => {
+ out.push(new Paragraph({ children, ...marker, spacing: { after: 60 } }));
+ markerWritten = true;
+ };
+
+ for (const child of item.tokens ?? []) {
+ if (child.type === 'space') continue;
+ if (child.type === 'list') {
+ // 极端输入可以让列表项直接从子列表开始;仍需保留父级项目符号。
+ if (!markerWritten) writeMarker([]);
+ out.push(...listParagraphs(child as Tokens.List, depth + 1, ctx));
+ continue;
+ }
+ if (!markerWritten && (child.type === 'paragraph' || child.type === 'text')) {
+ const paragraph = child as Tokens.Paragraph;
+ const children = inlineRuns(paragraph.tokens, ctx.theme);
+ writeMarker(
+ children.length > 0
+ ? children
+ : [new TextRun({ text: (child as { text?: string }).text ?? '' })],
+ );
+ continue;
+ }
+ if (!markerWritten) writeMarker([]);
+ // 后续正文块各自保持独立段落,并留在嵌套列表前后的原始位置。
+ out.push(...blocksFromTokens([child], ctx));
+ }
+ if (!markerWritten) writeMarker([]);
+ }
+ return out;
+}
+
+function codeParagraphs(code: Tokens.Code, theme: DocsTheme): Paragraph[] {
+ const lines = code.text.split('\n');
+ return lines.map(
+ (line, index) =>
+ new Paragraph({
+ children: [
+ new TextRun({
+ // Word 会把空段落压成零高,补一个空格让代码块的空行仍然可见。
+ text: line.length > 0 ? line : ' ',
+ font: MONO_FONT,
+ size: 20,
+ }),
+ ],
+ shading: { fill: theme.surface },
+ spacing: {
+ before: index === 0 ? 120 : 0,
+ after: index === lines.length - 1 ? 120 : 0,
+ },
+ }),
+ );
+}
+
+function alignmentFor(
+ align: 'center' | 'left' | 'right' | null,
+): (typeof AlignmentType)[keyof typeof AlignmentType] | undefined {
+ if (align === 'center') return AlignmentType.CENTER;
+ if (align === 'right') return AlignmentType.RIGHT;
+ if (align === 'left') return AlignmentType.LEFT;
+ return undefined;
+}
+
+/** 估算一格占多宽:CJK 与全角记两格,其余一格。与 make_xlsx 的口径一致。 */
+function cellDisplayWidth(text: string): number {
+ let width = 0;
+ for (const ch of text) {
+ const code = ch.codePointAt(0) ?? 0;
+ const wide =
+ (code >= 0x1100 && code <= 0x115f) ||
+ (code >= 0x2e80 && code <= 0xa4cf) ||
+ (code >= 0xac00 && code <= 0xd7a3) ||
+ (code >= 0xf900 && code <= 0xfaff) ||
+ (code >= 0xfe30 && code <= 0xfe6f) ||
+ (code >= 0xff00 && code <= 0xff60) ||
+ (code >= 0xffe0 && code <= 0xffe6);
+ width += wide ? 2 : 1;
+ }
+ return width;
+}
+
+function tableBlock(table: Tokens.Table, theme: DocsTheme): Table {
+ const headerRow = new TableRow({
+ tableHeader: true,
+ children: table.header.map((cell, col) =>
+ styledDocxHeaderCell(
+ theme,
+ inlineRuns(cell.tokens, theme, { bold: true, color: theme.accentOn }),
+ alignmentFor(table.align?.[col] ?? null),
+ ),
+ ),
+ });
+ const bodyRows = table.rows.map(
+ (row, rowIndex) =>
+ new TableRow({
+ children: row.map((cell, col) =>
+ styledDocxBodyCell(
+ theme,
+ rowIndex % 2 === 1,
+ inlineRuns(cell.tokens, theme),
+ alignmentFor(table.align?.[col] ?? null),
+ ),
+ ),
+ }),
+ );
+ /*
+ 列宽按这一列真正要放的字数分。量的是**纯文本**长度(CJK 记两格),不含加粗、
+ 链接这些不影响占位的修饰;表头也算进去,免得一个长表头被自己那列挤成两行。
+ */
+ const columnTextWidths = table.header.map((cell, col) => {
+ const widths = [cellDisplayWidth(cell.text)];
+ for (const row of table.rows) widths.push(cellDisplayWidth(row[col]?.text ?? ''));
+ return Math.max(...widths);
+ });
+ return styledDocxTable(theme, [headerRow, ...bodyRows], columnPercents(columnTextWidths));
+}
+
+/** inQuote 单独传参而不是塞进 ctx:它是随递归深度变化的位置信息,不是文档级状态。 */
+function blocksFromTokens(
+ tokens: Token[],
+ ctx: BlockContext,
+ inQuote = false,
+): Array<Paragraph | Table> {
+ const quoteStyle = inQuote ? quoteParagraphStyle(ctx.theme) : {};
+ const out: Array<Paragraph | Table> = [];
+ for (const token of tokens) {
+ switch (token.type) {
+ case 'heading': {
+ const heading = token as Tokens.Heading;
+ const level = HEADING_BY_DEPTH[Math.min(Math.max(heading.depth, 1), 6) - 1]!;
+ out.push(
+ new Paragraph({
+ heading: level,
+ children: inlineRuns(heading.tokens, ctx.theme),
+ spacing: { before: 240, after: 120 },
+ ...quoteStyle,
+ }),
+ );
+ break;
+ }
+ case 'paragraph':
+ case 'text': {
+ // blockquote 内的单行会被 marked 归成 'text' 而不是 'paragraph',
+ // 两者同构处理,否则引用块只剩空段。
+ const paragraph = token as Tokens.Paragraph;
+ const children = inlineRuns(paragraph.tokens, ctx.theme);
+ out.push(
+ new Paragraph({
+ children:
+ children.length > 0
+ ? children
+ : [
+ new TextRun({
+ text: (token as { text?: string }).text ?? '',
+ }),
+ ],
+ spacing: { after: 120 },
+ ...quoteStyle,
+ }),
+ );
+ break;
+ }
+ case 'list': {
+ out.push(...listParagraphs(token as Tokens.List, 0, ctx));
+ break;
+ }
+ case 'code':
+ out.push(...codeParagraphs(token as Tokens.Code, ctx.theme));
+ break;
+ case 'table':
+ out.push(tableBlock(token as Tokens.Table, ctx.theme));
+ // Word 里表格紧跟正文会粘在一起,补一个空段落当间距。
+ out.push(new Paragraph({ children: [], spacing: { after: 120 } }));
+ break;
+ case 'blockquote':
+ out.push(...blocksFromTokens((token as Tokens.Blockquote).tokens ?? [], ctx, true));
+ break;
+ case 'hr':
+ out.push(
+ new Paragraph({
+ children: [],
+ border: {
+ bottom: {
+ style: BorderStyle.SINGLE,
+ size: 6,
+ space: 1,
+ color: ctx.theme.line,
+ },
+ },
+ spacing: { before: 120, after: 120 },
+ }),
+ );
+ break;
+ case 'html': {
+ const raw = ((token as Tokens.HTML).raw ?? '').trim();
+ if (PAGE_BREAK_RE.test(raw)) {
+ out.push(new Paragraph({ children: [new PageBreak()] }));
+ } else if (raw.length > 0) {
+ // 其它 HTML 不解释,原样落成文本,避免静默吞掉用户写的内容。
+ out.push(new Paragraph({ children: [new TextRun({ text: raw })] }));
+ }
+ break;
+ }
+ case 'space':
+ break;
+ default: {
+ const text = (token as { text?: string }).text ?? '';
+ if (text.trim().length > 0) {
+ out.push(new Paragraph({ children: [new TextRun({ text })], ...quoteStyle }));
+ }
+ break;
+ }
+ }
+ }
+ return out;
+}
+
+export interface MarkdownToDocxOptions {
+ /** 文档标题:写进 core properties;cover=true 时做独立封面,否则插在正文最前。 */
+ title?: string;
+ /** 封面副题 / 密级 / 来源一行。 */
+ subtitle?: string;
+ /** 是否生成独立封面页。给了 title 时默认 true。 */
+ cover?: boolean;
+ theme?: DocsThemeName;
+}
+
+/** 把 Markdown 编成 .docx 字节。纯函数,不碰文件系统。 */
+export async function markdownToDocxBuffer(
+ markdown: string,
+ options: MarkdownToDocxOptions = {},
+): Promise<Buffer> {
+ const theme = resolveDocsTheme(options.theme ?? DEFAULT_DOCS_THEME);
+ const title = options.title?.trim() ?? '';
+ const useCover = Boolean(title) && (options.cover ?? true);
+ const tokens = marked.lexer(markdown ?? '');
+ const ctx: BlockContext = { theme, nextOrderedListId: 0, orderedLists: [] };
+ const body = blocksFromTokens(tokens, ctx);
+
+ const children: Array<Paragraph | Table> = [];
+ if (title.length > 0 && !useCover) {
+ children.push(
+ new Paragraph({
+ heading: HeadingLevel.TITLE,
+ children: [new TextRun({ text: title, color: theme.title })],
+ spacing: { after: 240 },
+ }),
+ );
+ }
+ children.push(...body);
+ if (children.length === 0) {
+ children.push(new Paragraph({ children: [] }));
+ }
+
+ const bodySection = {
+ properties: docxBodySectionProperties(),
+ footers: { default: docxBodyFooter(theme) },
+ children,
+ };
+
+ const doc = new Document({
+ ...(title.length > 0 ? { title } : {}),
+ background: { color: theme.background },
+ styles: docxDocumentStyles(theme),
+ numbering: {
+ config: ctx.orderedLists.map(({ reference, level: startLevel, start }) => ({
+ reference,
+ levels: [0, 1, 2, 3].map((level) => ({
+ level,
+ format: LevelFormat.DECIMAL,
+ text: `%${level + 1}.`,
+ alignment: AlignmentType.START,
+ ...(level === startLevel ? { start } : {}),
+ style: {
+ paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } },
+ },
+ })),
+ })),
+ },
+ sections: useCover
+ ? [
+ docxCoverSection(theme, {
+ title,
+ ...(options.subtitle ? { subtitle: options.subtitle } : {}),
+ }),
+ bodySection,
+ ]
+ : [bodySection],
+ });
+ return Packer.toBuffer(doc);
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/pdfTemplate.ts b/packages/lizi-mcps/src/cindy-docs/pdfTemplate.ts
new file mode 100644
index 0000000000..126a542023
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/pdfTemplate.ts
@@ -0,0 +1,477 @@
+/**
+ * cindy-docs/pdfTemplate.ts —— 无样式 HTML 的内置报告模板。
+ *
+ * render_pdf 的目标是「不装插件也体面」:模型如果只丢过来一段裸 <h1>/<p>/<table>,
+ * 没有 <style> 也没有外链 CSS,就自动套这套打印样式。已经自己写了样式的 HTML
+ * 原样透传,绝不覆盖。
+ *
+ * 纯配置:色板来自 themes.ts,字体只声明系统字体族,不捆 webfont、不捆图片。
+ */
+
+import { decodeHTML } from 'entities';
+
+import { themeToCssHex, type DocsTheme } from './themes.js';
+
+export const PDF_TEMPLATE_MARK = 'data-cindy-docs-template="report"';
+
+const RELATIVE_RESOURCE_RE =
+ /\b(?:src|href)\s*=\s*["'](?!https?:|data:|#|\/\/|file:)[^"']+/i;
+const HTML_RAW_TEXT_TAGS = new Set([
+ 'iframe',
+ 'noembed',
+ 'noframes',
+ 'noscript',
+ 'script',
+ 'style',
+ 'textarea',
+ 'title',
+ 'xmp',
+]);
+const HTML_HEAD_CONTENT_TAGS = new Set([
+ 'base',
+ 'basefont',
+ 'bgsound',
+ 'head',
+ 'html',
+ 'link',
+ 'meta',
+ 'noframes',
+ 'noscript',
+ 'script',
+ 'style',
+ 'template',
+ 'title',
+]);
+const HTML_ATTRIBUTE_PATTERN =
+ /(\s+)([A-Za-z_:][\w:.-]*)(\s*=\s*)(?:(['"])([\s\S]*?)\4|([^\s"'=<>`]+))/gi;
+
+export function htmlLooksUnstyled(html: string): boolean {
+ if (html.includes(PDF_TEMPLATE_MARK)) return false;
+ return !htmlHasStylesheetElement(html);
+}
+
+export function htmlHasRelativeResources(html: string): boolean {
+ return RELATIVE_RESOURCE_RE.test(html);
+}
+
+function stripTags(raw: string): string {
+ return raw.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
+}
+
+export function extractHtmlTitle(html: string): string | undefined {
+ const title = findHtmlElementRange(html, 'title');
+ if (title) {
+ const value = decodeHTML(html.slice(title.contentStart, title.contentEnd))
+ .replace(/\s+/g, ' ')
+ .trim();
+ if (value.length > 0) return value;
+ }
+ const heading = findHtmlElementRange(html, 'h1');
+ if (heading) {
+ const value = decodeHTML(
+ stripTags(html.slice(heading.contentStart, heading.contentEnd)),
+ );
+ if (value.length > 0) return value;
+ }
+ return undefined;
+}
+
+function findHtmlTagEnd(html: string, start: number): number {
+ let quote: '"' | "'" | undefined;
+ for (let index = start + 1; index < html.length; index += 1) {
+ const current = html[index]!;
+ if (quote) {
+ if (current === quote) quote = undefined;
+ continue;
+ }
+ if (current === '"' || current === "'") quote = current;
+ else if (current === '>') return index;
+ }
+ return -1;
+}
+
+function readHtmlAttribute(tag: string, attributeName: string): string | undefined {
+ const wanted = attributeName.toLowerCase();
+ for (const match of tag.matchAll(HTML_ATTRIBUTE_PATTERN)) {
+ if (match[2]!.toLowerCase() === wanted) return match[4] ? match[5] : match[6];
+ }
+ return undefined;
+}
+
+interface HtmlElementRange {
+ start: number;
+ contentStart: number;
+ contentEnd: number;
+ end: number;
+}
+
+function findRawTextClosing(
+ html: string,
+ name: string,
+ contentStart: number,
+): { start: number; end: number } | undefined {
+ const closing = new RegExp(`<\\/\\s*${name}\\s*>`, 'ig');
+ closing.lastIndex = contentStart;
+ const match = closing.exec(html);
+ return match ? { start: match.index, end: match.index + match[0].length } : undefined;
+}
+
+/** Find one real HTML element while ignoring comments, raw-text contents and template subtrees. */
+function findHtmlElementRange(html: string, wantedName: string): HtmlElementRange | undefined {
+ const wanted = wantedName.toLowerCase();
+ let opening: { start: number; contentStart: number } | undefined;
+ let templateDepth = 0;
+ let index = 0;
+ while (index < html.length) {
+ const tagStart = html.indexOf('<', index);
+ if (tagStart < 0) {
+ if (wanted === 'head' && opening && templateDepth === 0) {
+ const trailingText = html.slice(index).search(/[^\t\n\f\r ]/);
+ if (trailingText >= 0) {
+ const implicitEnd = index + trailingText;
+ return {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: implicitEnd,
+ end: implicitEnd,
+ };
+ }
+ }
+ break;
+ }
+ if (wanted === 'head' && opening && templateDepth === 0) {
+ const textBeforeTag = html.slice(index, tagStart).search(/[^\t\n\f\r ]/);
+ if (textBeforeTag >= 0) {
+ const implicitEnd = index + textBeforeTag;
+ return {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: implicitEnd,
+ end: implicitEnd,
+ };
+ }
+ }
+ if (html.startsWith('<!--', tagStart)) {
+ const commentEnd = html.indexOf('-->', tagStart + 4);
+ index = commentEnd < 0 ? html.length : commentEnd + 3;
+ continue;
+ }
+ const tagEnd = findHtmlTagEnd(html, tagStart);
+ if (tagEnd < 0) break;
+ const tag = html.slice(tagStart, tagEnd + 1);
+ const closingName = tag.match(/^<\s*\/\s*([A-Za-z][\w:-]*)\s*>/)?.[1]?.toLowerCase();
+ if (closingName === 'template' && templateDepth > 0) {
+ templateDepth -= 1;
+ index = tagEnd + 1;
+ continue;
+ }
+ if (closingName === wanted && opening && templateDepth === 0) {
+ return {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: tagStart,
+ end: tagEnd + 1,
+ };
+ }
+ if (
+ wanted === 'head' &&
+ opening &&
+ templateDepth === 0 &&
+ closingName &&
+ (closingName === 'body' || closingName === 'html' || closingName === 'br')
+ ) {
+ return {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: tagStart,
+ end: tagStart,
+ };
+ }
+ const name = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/)?.[1]?.toLowerCase();
+ if (!name) {
+ index = tagEnd + 1;
+ continue;
+ }
+ if (wanted === 'head' && opening && templateDepth === 0 && !HTML_HEAD_CONTENT_TAGS.has(name)) {
+ return {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: tagStart,
+ end: tagStart,
+ };
+ }
+ if (name === 'template' && !/\/\s*>$/.test(tag)) {
+ templateDepth += 1;
+ index = tagEnd + 1;
+ continue;
+ }
+ if (templateDepth === 0 && name === wanted && !opening) {
+ if (HTML_RAW_TEXT_TAGS.has(name)) {
+ const rawClosing = findRawTextClosing(html, name, tagEnd + 1);
+ return rawClosing
+ ? {
+ start: tagStart,
+ contentStart: tagEnd + 1,
+ contentEnd: rawClosing.start,
+ end: rawClosing.end,
+ }
+ : {
+ start: tagStart,
+ contentStart: tagEnd + 1,
+ contentEnd: html.length,
+ end: html.length,
+ };
+ }
+ opening = { start: tagStart, contentStart: tagEnd + 1 };
+ }
+ if (HTML_RAW_TEXT_TAGS.has(name)) {
+ const rawClosing = findRawTextClosing(html, name, tagEnd + 1);
+ index = rawClosing?.end ?? html.length;
+ continue;
+ }
+ index = tagEnd + 1;
+ }
+ return opening
+ ? {
+ start: opening.start,
+ contentStart: opening.contentStart,
+ contentEnd: html.length,
+ end: html.length,
+ }
+ : undefined;
+}
+
+function htmlHasStylesheetElement(html: string): boolean {
+ let templateDepth = 0;
+ let index = 0;
+ while (index < html.length) {
+ const tagStart = html.indexOf('<', index);
+ if (tagStart < 0) break;
+ if (html.startsWith('<!--', tagStart)) {
+ const commentEnd = html.indexOf('-->', tagStart + 4);
+ index = commentEnd < 0 ? html.length : commentEnd + 3;
+ continue;
+ }
+ const tagEnd = findHtmlTagEnd(html, tagStart);
+ if (tagEnd < 0) break;
+ const tag = html.slice(tagStart, tagEnd + 1);
+ const closing = tag.match(/^<\s*\/\s*([A-Za-z][\w:-]*)\s*>/);
+ if (closing?.[1]?.toLowerCase() === 'template' && templateDepth > 0) {
+ templateDepth -= 1;
+ index = tagEnd + 1;
+ continue;
+ }
+ const opening = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/);
+ const name = opening?.[1]?.toLowerCase();
+ if (!name) {
+ index = tagEnd + 1;
+ continue;
+ }
+ if (name === 'template' && !/\/\s*>$/.test(tag)) {
+ templateDepth += 1;
+ index = tagEnd + 1;
+ continue;
+ }
+ if (templateDepth === 0) {
+ if (name === 'style') return true;
+ if (name === 'link') {
+ const rel = readHtmlAttribute(tag, 'rel');
+ if (
+ rel &&
+ decodeHTML(rel)
+ .split(/\s+/)
+ .some((token) => token.toLowerCase() === 'stylesheet')
+ ) {
+ return true;
+ }
+ }
+ }
+ if (HTML_RAW_TEXT_TAGS.has(name)) {
+ const rawTextEnd = new RegExp(`<\\/\\s*${name}\\s*>`, 'ig');
+ rawTextEnd.lastIndex = tagEnd + 1;
+ const closingMatch = rawTextEnd.exec(html);
+ index = closingMatch ? closingMatch.index + closingMatch[0].length : html.length;
+ continue;
+ }
+ index = tagEnd + 1;
+ }
+ return false;
+}
+
+/**
+ * Locate the real body element without treating tag-shaped text in comments or
+ * HTML raw-text elements as markup. A lightweight scanner is enough here: the
+ * template only needs the byte range, while Chromium remains the HTML parser.
+ */
+function findHtmlBodyRange(html: string): { start: number; end: number } | undefined {
+ const body = findHtmlElementRange(html, 'body');
+ return body ? { start: body.contentStart, end: body.contentEnd } : undefined;
+}
+
+/** 只剥扫描器确认的文档包装节点;raw-text 中的标签形状字符串必须原样保留。 */
+function stripHtmlDocumentWrappers(html: string): string {
+ let output = '';
+ let cursor = 0;
+ let index = 0;
+ let templateDepth = 0;
+
+ while (index < html.length) {
+ const tagStart = html.indexOf('<', index);
+ if (tagStart < 0) break;
+ if (html.startsWith('<!--', tagStart)) {
+ const commentEnd = html.indexOf('-->', tagStart + 4);
+ index = commentEnd < 0 ? html.length : commentEnd + 3;
+ continue;
+ }
+ const tagEnd = findHtmlTagEnd(html, tagStart);
+ if (tagEnd < 0) break;
+ const tag = html.slice(tagStart, tagEnd + 1);
+ const closingName = tag.match(/^<\s*\/\s*([A-Za-z][\w:-]*)\s*>/)?.[1]?.toLowerCase();
+ const openingName = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/)?.[1]?.toLowerCase();
+
+ if (closingName === 'template' && templateDepth > 0) {
+ templateDepth -= 1;
+ } else if (openingName === 'template' && !/\/\s*>$/.test(tag)) {
+ templateDepth += 1;
+ }
+
+ const isDoctype = templateDepth === 0 && /^<!doctype\b/i.test(tag);
+ const isHtmlWrapper = templateDepth === 0 && (openingName === 'html' || closingName === 'html');
+ if (isDoctype || isHtmlWrapper) {
+ output += html.slice(cursor, tagStart);
+ cursor = tagEnd + 1;
+ }
+
+ if (openingName && HTML_RAW_TEXT_TAGS.has(openingName)) {
+ const rawClosing = findRawTextClosing(html, openingName, tagEnd + 1);
+ index = rawClosing?.end ?? html.length;
+ continue;
+ }
+ index = tagEnd + 1;
+ }
+
+ return `${output}${html.slice(cursor)}`;
+}
+
+export function extractHtmlBody(html: string): string {
+ const body = findHtmlBodyRange(html);
+ if (body) return html.slice(body.start, body.end).trim();
+ const head = findHtmlElementRange(html, 'head');
+ const withoutHead = head ? `${html.slice(0, head.start)}${html.slice(head.end)}` : html;
+ return stripHtmlDocumentWrappers(withoutHead).trim();
+}
+
+export function reportTemplateCss(theme: DocsTheme): string {
+ const ink = themeToCssHex(theme.title);
+ const body = themeToCssHex(theme.body);
+ const muted = themeToCssHex(theme.muted);
+ const line = themeToCssHex(theme.line);
+ const accent = themeToCssHex(theme.accent);
+ const wash = themeToCssHex(theme.surface);
+ const paper = themeToCssHex(theme.background);
+ const zebra = themeToCssHex(theme.zebra);
+ return `
+@page { size: A4; margin: 18mm 16mm; }
+:root {
+ --ink: ${ink}; --body: ${body}; --muted: ${muted}; --line: ${line};
+ --accent: ${accent}; --wash: ${wash}; --paper: ${paper}; --zebra: ${zebra};
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; padding: 0; }
+body {
+ color: var(--body); background: var(--paper);
+ font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",
+ -apple-system, "Helvetica Neue", Arial, sans-serif;
+ font-size: 11pt; line-height: 1.7;
+ -webkit-print-color-adjust: exact; print-color-adjust: exact;
+}
+h1, h2, h3, h4, h5, h6 {
+ color: var(--ink); break-after: avoid; page-break-after: avoid;
+}
+h1 { font-size: 22pt; line-height: 1.3; margin: 0 0 10pt; }
+h2 {
+ font-size: 15pt; margin: 18pt 0 7pt; padding-left: 8pt;
+ border-left: 3px solid var(--accent);
+}
+h3 { font-size: 12.5pt; margin: 13pt 0 5pt; }
+h4, h5, h6 { font-size: 11pt; margin: 10pt 0 4pt; }
+p { margin: 0 0 8pt; }
+ul, ol { margin: 0 0 8pt 1.4em; }
+li { margin: 0 0 3pt; }
+blockquote {
+ margin: 10pt 0; padding: 6pt 12pt; color: var(--muted);
+ border-left: 3px solid var(--line); background: var(--wash);
+}
+code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: 9.5pt; }
+code { padding: 0 2pt; background: var(--wash); border-radius: 3pt; }
+pre {
+ padding: 8pt 10pt; background: var(--wash); border: 1px solid var(--line);
+ border-radius: 4pt; overflow-wrap: anywhere;
+}
+pre code { background: none; padding: 0; }
+table { width: 100%; border-collapse: collapse; margin: 10pt 0; font-size: 10pt; }
+th, td { border: 1px solid var(--line); padding: 5pt 7pt; text-align: left; vertical-align: top; }
+thead th { background: var(--wash); font-weight: 600; color: var(--ink); }
+tbody tr:nth-child(even) td { background: var(--zebra); }
+table, figure, pre, blockquote { break-inside: avoid; page-break-inside: avoid; }
+thead { display: table-header-group; }
+img { max-width: 100%; height: auto; }
+figcaption { font-size: 9pt; color: var(--muted); margin-top: 3pt; }
+header.cover { border-bottom: 2px solid var(--accent); padding-bottom: 10pt; margin-bottom: 18pt; }
+header.cover h1 { font-size: 20pt; margin: 0 0 6pt; }
+header.cover .meta { font-size: 9.5pt; color: var(--muted); }
+.page-break { break-before: page; page-break-before: always; }
+footer, footer.note {
+ margin-top: 20pt; padding-top: 8pt; border-top: 1px solid var(--line);
+ font-size: 9pt; color: var(--muted);
+}
+`.trim();
+}
+
+export function wrapInReportTemplate(html: string, theme: DocsTheme): string {
+ const title = extractHtmlTitle(html);
+ const body = extractHtmlBody(html) || '<p></p>';
+ return [
+ '<!doctype html>',
+ '<html lang="zh-CN">',
+ '<head>',
+ '<meta charset="utf-8" />',
+ `<title>${title ? escapeHtml(title) : ''}</title>`,
+ `<style ${PDF_TEMPLATE_MARK}>`,
+ reportTemplateCss(theme),
+ '</style>',
+ '</head>',
+ '<body>',
+ body,
+ '</body>',
+ '</html>',
+ ].join('\n');
+}
+
+function escapeHtml(text: string): string {
+ return text
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+export interface ApplyReportTemplateResult {
+ html: string;
+ applied: boolean;
+}
+
+export function applyReportTemplate(
+ html: string,
+ theme: DocsTheme,
+ mode: 'auto' | 'report' | 'none' = 'auto',
+): ApplyReportTemplateResult {
+ if (mode === 'none') return { html, applied: false };
+ if (mode === 'auto' && !htmlLooksUnstyled(html)) return { html, applied: false };
+ if (mode === 'report' && html.includes(PDF_TEMPLATE_MARK)) return { html, applied: false };
+ if (mode === 'report' && !htmlLooksUnstyled(html)) {
+ // 已经有自己的样式:只标记「未覆盖」,不二次包裹。
+ return { html, applied: false };
+ }
+ return { html: wrapInReportTemplate(html, theme), applied: true };
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/pptxMasters.ts b/packages/lizi-mcps/src/cindy-docs/pptxMasters.ts
new file mode 100644
index 0000000000..8b9aab97d7
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/pptxMasters.ts
@@ -0,0 +1,277 @@
+/**
+ * cindy-docs/pptxMasters.ts —— pptxgenjs 母版版式(纯几何 + 色板,不捆图不捆字体)。
+ *
+ * 六套版式:
+ * - cover 封面:左侧强调条、大标题、无页码
+ * - section 分节:左侧强调条、居中偏上标题、页脚页码
+ * - content 内容:标题区 + 正文区 + 页脚页码;有图时文字收窄到左半
+ * - comparison 双栏对比:两个结构化信息卡并排
+ * - metrics 数据强调:2–4 个指标卡
+ * - image 大图:标题区 + 通栏图片 + 可选题注
+ *
+ * 母版只放「每一页都一样」的铬件(底色、强调条、页脚线、页码)。标题和正文仍由
+ * 调用方按本文件给出的槽位往 slide 上写 —— 占位符在 pptxgenjs 里不好测,也容易
+ * 让文字落到母版层导致解包断言扑空。
+ */
+
+import type pptxgen from 'pptxgenjs';
+
+import type { DocsTheme } from './themes.js';
+
+export const SLIDE_W = 13.333;
+export const SLIDE_H = 7.5;
+
+/** 封面左侧强调色块的宽度(英寸)。约占页宽 1/3,是封面唯一的构图元素。 */
+export const COVER_PANEL_W = 4.4;
+
+/** 分节页顶部强调带的高度(英寸)。 */
+export const SECTION_BAND_H = 0.62;
+
+export const PPTX_LAYOUT_NAMES = [
+ 'cover',
+ 'section',
+ 'content',
+ 'comparison',
+ 'metrics',
+ 'image',
+] as const;
+export type PptxLayoutName = (typeof PPTX_LAYOUT_NAMES)[number];
+export const DEFAULT_PPTX_LAYOUT: PptxLayoutName = 'content';
+
+export const PPTX_LAYOUT_IDS = {
+ cover: 'CINDY_COVER',
+ section: 'CINDY_SECTION',
+ content: 'CINDY_CONTENT',
+ comparison: 'CINDY_COMPARISON',
+ metrics: 'CINDY_METRICS',
+ image: 'CINDY_IMAGE',
+} as const;
+
+export interface PptxBox {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+ fontSize: number;
+}
+
+export interface PptxLayoutSlots {
+ title: PptxBox;
+ subtitle?: PptxBox;
+ body: PptxBox;
+ image?: Omit<PptxBox, 'fontSize'>;
+ /** 内容页标题下的强调短线;封面/分节没有。 */
+ accentLine?: Omit<PptxBox, 'fontSize'>;
+}
+
+export interface DefineCindyPptxMastersOptions {
+ theme: DocsTheme;
+ footer: boolean;
+ footerLabel?: string;
+}
+
+function footerLabelText(label: string | undefined): string {
+ const trimmed = (label ?? '').trim();
+ if (trimmed.length === 0) return '';
+ return trimmed.length > 42 ? `${trimmed.slice(0, 41)}…` : trimmed;
+}
+
+/**
+ * 给一份演示文稿登记六套母版。同一份 deck 只应调一次;主题在登记时固化。
+ */
+export function defineCindyPptxMasters(
+ pptx: pptxgen,
+ options: DefineCindyPptxMastersOptions,
+): void {
+ const { theme, footer } = options;
+ const label = footer ? footerLabelText(options.footerLabel) : '';
+ const pageNumber = footer
+ ? { x: 12.15, y: 7.12, w: 0.55, h: 0.28, fontSize: 10, color: theme.muted, align: 'right' as const }
+ : undefined;
+
+ const footerChrome = footer
+ ? [
+ {
+ rect: {
+ x: 0.7,
+ y: 7.02,
+ w: 11.93,
+ h: 0.012,
+ fill: { color: theme.line },
+ },
+ },
+ ...(label.length > 0
+ ? [
+ {
+ text: {
+ text: label,
+ options: {
+ x: 0.7,
+ y: 7.12,
+ w: 11.2,
+ h: 0.28,
+ fontSize: 10,
+ color: theme.muted,
+ margin: 0,
+ },
+ },
+ },
+ ]
+ : []),
+ ]
+ : [];
+
+ // 封面:左侧整幅强调色块 + 右侧留白。原来只有一根 0.16" 的竖条,在实机目检里
+ // 几乎看不见 —— 整页就是「白底加几行字」。色块给足面积才撑得起一页封面。
+ pptx.defineSlideMaster({
+ title: PPTX_LAYOUT_IDS.cover,
+ background: { color: theme.background },
+ objects: [
+ { rect: { x: 0, y: 0, w: COVER_PANEL_W, h: SLIDE_H, fill: { color: theme.accent } } },
+ // 色块右缘一道浅色窄条,让色块与白底之间有个交代,不是硬切。
+ {
+ rect: {
+ x: COVER_PANEL_W,
+ y: 0,
+ w: 0.06,
+ h: SLIDE_H,
+ fill: { color: theme.surface },
+ },
+ },
+ ],
+ });
+
+ // 分节:顶部一条粗强调带 + 底部细线。整页只有一个标题,靠这两条横向元素定住
+ // 视觉重心,否则标题浮在中间、上下大片空白(实机目检里就是这样)。
+ pptx.defineSlideMaster({
+ title: PPTX_LAYOUT_IDS.section,
+ background: { color: theme.background },
+ ...(pageNumber ? { slideNumber: pageNumber } : {}),
+ objects: [
+ { rect: { x: 0, y: 0, w: SLIDE_W, h: SECTION_BAND_H, fill: { color: theme.accent } } },
+ ...footerChrome,
+ ],
+ });
+
+ const contentChrome = [
+ // 顶部一条细强调线贯穿:内容页原来只有孤零零的标题和一小段短线,页面没有
+ // 任何边界感。这条线成本极低,但让每一页都「有个头」。
+ {
+ rect: { x: 0, y: 0, w: SLIDE_W, h: 0.075, fill: { color: theme.accent } },
+ },
+ ...footerChrome,
+ ];
+ for (const layout of ['content', 'comparison', 'metrics', 'image'] as const) {
+ pptx.defineSlideMaster({
+ title: PPTX_LAYOUT_IDS[layout],
+ background: { color: theme.background },
+ ...(pageNumber ? { slideNumber: pageNumber } : {}),
+ objects: contentChrome,
+ });
+ }
+}
+
+/** 按版式 + 是否有图算出这一页内容该落在哪。几何是唯一真相,make_pptx 不要再手写坐标。 */
+export function layoutSlots(
+ layout: PptxLayoutName,
+ opts: { hasImage: boolean; hasSubtitle: boolean },
+): PptxLayoutSlots {
+ const { hasImage, hasSubtitle } = opts;
+
+ if (layout === 'cover') {
+ // 文字整体落在色块右侧的留白区,与色块之间留一个身位。标题放大到 44pt ——
+ // 封面就这一行字,原来的 40pt 配 11.5" 宽通栏显得又小又散。
+ const x = COVER_PANEL_W + 0.85;
+ const w = SLIDE_W - x - 0.9;
+ return {
+ title: { x, y: hasSubtitle ? 2.35 : 2.75, w, h: 1.9, fontSize: 44 },
+ ...(hasSubtitle ? { subtitle: { x, y: 4.45, w, h: 0.75, fontSize: 18 } } : {}),
+ body: { x, y: hasSubtitle ? 5.3 : 4.75, w, h: 1.5, fontSize: 15 },
+ // 标题与副题之间的短粗线,给封面一个可读的分隔。
+ accentLine: { x, y: hasSubtitle ? 4.06 : 4.46, w: 1.9, h: 0.07 },
+ };
+ }
+
+ if (layout === 'section') {
+ // 分节页整体下压到视觉中线偏上,顶部让给强调带;标题左对齐不居中 ——
+ // 居中标题配大片空白正是实机目检里最空的一页。
+ return {
+ title: { x: 0.95, y: hasSubtitle ? 2.75 : 3.05, w: 11.5, h: 1.25, fontSize: 34 },
+ ...(hasSubtitle ? { subtitle: { x: 0.95, y: 4.5, w: 11.5, h: 0.55, fontSize: 16 } } : {}),
+ body: { x: 0.95, y: hasSubtitle ? 5.15 : 4.55, w: 11.5, h: 1.7, fontSize: 16 },
+ accentLine: { x: 0.95, y: hasSubtitle ? 4.14 : 4.44, w: 1.6, h: 0.06 },
+ };
+ }
+
+ if (layout === 'image') {
+ const titleY = 0.52;
+ const titleH = hasSubtitle ? 0.6 : 0.78;
+ const accentY = titleY + titleH + (hasSubtitle ? 0.44 : 0.1);
+ const imageY = accentY + 0.3;
+ return {
+ title: { x: 0.7, y: titleY, w: 11.93, h: titleH, fontSize: 28 },
+ ...(hasSubtitle
+ ? {
+ subtitle: {
+ x: 0.7,
+ y: titleY + titleH + 0.08,
+ w: 11.93,
+ h: 0.38,
+ fontSize: 15,
+ },
+ }
+ : {}),
+ accentLine: { x: 0.7, y: accentY, w: 2.2, h: 0.06 },
+ body: { x: 0.7, y: 6.35, w: 11.93, h: 0.38, fontSize: 12 },
+ image: { x: 0.7, y: imageY, w: 11.93, h: 6.15 - imageY },
+ };
+ }
+
+ const textW = layout === 'content' && hasImage ? SLIDE_W / 2 - 0.7 : 11.93;
+ const titleH = hasSubtitle ? 0.6 : 0.78;
+ // 标题下压一点,给顶部那条强调线让位。
+ const titleY = 0.52;
+ const accentY = titleY + titleH + (hasSubtitle ? 0.44 : 0.1);
+ const bodyY = accentY + 0.3;
+ return {
+ title: { x: 0.7, y: titleY, w: 11.93, h: titleH, fontSize: 28 },
+ ...(hasSubtitle
+ ? { subtitle: { x: 0.7, y: titleY + titleH + 0.08, w: textW, h: 0.38, fontSize: 15 } }
+ : {}),
+ // 强调线加粗到 0.06":原来 0.045" 在实机目检里几乎看不见,等于没有。
+ accentLine: { x: 0.7, y: accentY, w: 2.2, h: 0.06 },
+ body: {
+ x: 0.7,
+ y: bodyY,
+ w: textW,
+ h: SLIDE_H - bodyY - 0.75,
+ fontSize: 18,
+ },
+ ...(layout === 'content' && hasImage
+ ? {
+ image: {
+ x: SLIDE_W / 2 + 0.15,
+ y: bodyY,
+ w: SLIDE_W / 2 - 0.85,
+ h: SLIDE_H - bodyY - 0.85,
+ },
+ }
+ : {}),
+ };
+}
+
+/**
+ * 要点少时把字号放大去占住版面,而不是把文字推到页面中间。
+ *
+ * 先试过「要点 ≤5 条就垂直居中」——目检一看更糟:标题、强调线,然后**裂开一大条
+ * 空白**才是正文,两块彻底断开。正确做法是让内容自己长大:三四条要点用 22pt,
+ * 页面自然充实;条目多了退回 18pt 保证放得下。
+ *
+ * 返回的是字号,不是对齐 —— 正文一律顶着标题排。
+ */
+export function bodyFontSize(base: number, lineCount: number): number {
+ if (lineCount <= 0) return base;
+ if (lineCount <= 3) return base + 4;
+ if (lineCount <= 5) return base + 2;
+ return base;
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps.ts b/packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps.ts
new file mode 100644
index 0000000000..9ead399b3e
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/readSheetRuntimeDeps.ts
@@ -0,0 +1,6 @@
+/**
+ * read_sheet 的 XLSX worker 通过 createRequire() 在运行期加载这两个包。
+ * Vite 不会把 worker 字符串里的 require 依赖收进 main bundle,因此 Desktop
+ * 正式包必须显式携带它们以及各自的完整 dependencies 闭包。
+ */
+export const READ_SHEET_RUNTIME_PACKAGES = ['jszip', 'exceljs'] as const;
diff --git a/packages/lizi-mcps/src/cindy-docs/read_sheet.ts b/packages/lizi-mcps/src/cindy-docs/read_sheet.ts
new file mode 100644
index 0000000000..8f0e191f84
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/read_sheet.ts
@@ -0,0 +1,478 @@
+/**
+ * cindy-docs/read_sheet.ts —— 读取本地表格文件(xlsx / csv / tsv)成结构化行。
+ *
+ * 只读工具,进 READ_ONLY_MCP_TOOLS 免审批 —— 路径已被钳制在会话工作目录内,
+ * 不外发内容、无副作用。
+ *
+ * 截断口径:超出 maxRows 时**明确标注** truncated / totalRows,不静默截断。
+ * 模型据此决定是分批再读还是换个思路(例如让 Excel 自己算而不是把全表读进上下文)。
+ */
+
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { Worker } from 'node:worker_threads';
+
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ DocsPathError,
+ prepareInputPath,
+ readInputFileWithinLimit,
+ resolveSessionRoot,
+} from './_paths.js';
+import { errorPayload, okPayload } from './_payload.js';
+import { decodeUnicodeText } from './_textEncoding.js';
+import { delimiterForExtension, parseDelimitedWindow } from './csv.js';
+import { READ_SHEET_RUNTIME_PACKAGES } from './readSheetRuntimeDeps.js';
+import type { DocsMcpSessionCtx } from './types.js';
+
+const DEFAULT_MAX_ROWS = 200;
+const HARD_MAX_ROWS = 5000;
+const DEFAULT_MAX_COLUMNS = 64;
+const HARD_MAX_COLUMNS = 256;
+/** 文本表格的读入上限(字节)。超过就拒读,避免把几百 MB 日志当 csv 塞进内存。 */
+const MAX_TEXT_BYTES = 32 * 1024 * 1024;
+/** xlsx 在 ExcelJS 中会展开 ZIP,压缩包与展开后都设硬上限。 */
+const MAX_XLSX_BYTES = 32 * 1024 * 1024;
+export const MAX_XLSX_ZIP_ENTRIES = 4096;
+const XLSX_READ_TIMEOUT_MS = 15_000;
+
+const DESCRIPTION = [
+ '读取工作目录内的表格文件(.xlsx / .csv / .tsv),返回结构化的二维数据。',
+ '',
+ '【何时用】用户让你分析、汇总、核对一份表格;或者你刚用 make_xlsx 生成了文件,',
+ '要回读确认内容真的写进去了(产出自检)。',
+ '',
+ '【参数】sheet 只对 xlsx 有效,可传工作表名或 1 起的序号;不传取第一张。',
+ 'startRow 是 1 起的起始行,默认 1;maxRows 默认 200,最大 5000。',
+ `startColumn 是 1 起的起始列,默认 1;maxColumns 默认 ${DEFAULT_MAX_COLUMNS},最大 ${HARD_MAX_COLUMNS}。`,
+ '返回里 truncated=true 表示后面还有更多行,nextStartRow 可直接用于下一次读取;',
+ 'totalRows 是实际总行数 —— 别把截断当成「表就这么大」。',
+ '',
+ '【返回】rows 是二维数组(每格为字符串、数字、布尔或 null);',
+ 'xlsx 的公式格返回其缓存的计算结果,日期返回 ISO 字符串。',
+ 'csv / tsv 支持 UTF-8,以及带 BOM 的 UTF-16LE / UTF-16BE 导出文件。',
+ 'xlsx 会先检查文件大小与 ZIP 解压比,再在受限 worker 中解析(15 秒超时);超限会返回 FILE_TOO_LARGE/READ_TIMEOUT。',
+ '',
+ '【读不到时】文件不在工作目录内会返回 PATH_NOT_ALLOWED,不存在返回 NOT_A_FILE。',
+ '.xls(老二进制格式)不支持,先让用户另存为 .xlsx。',
+].join('\n');
+
+type SheetCell = string | number | boolean | null;
+
+interface SheetRead {
+ rows: SheetCell[][];
+ totalRows: number;
+ totalColumns: number;
+ startColumn: number;
+ endColumn: number;
+ sheetName?: string;
+ sheetNames?: string[];
+}
+
+function xlsxTooLarge(bytes: number): DocsPathError {
+ return new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `工作簿过大: ${bytes} 字节`,
+ `这个 .xlsx 文件有 ${(bytes / 1024 / 1024).toFixed(1)} MB,超出单次读取上限(32 MB)。请先拆分工作簿,或改用命令行工具处理。`,
+ );
+}
+
+const XLSX_WORKER_SOURCE = String.raw`
+const { parentPort, workerData } = require('node:worker_threads');
+const JSZip = require(workerData.jszipPath);
+const ExcelJS = require(workerData.exceljsPath);
+
+const MAX_XLSX_UNCOMPRESSED_BYTES = 128 * 1024 * 1024;
+const MAX_XLSX_COMPRESSION_RATIO = 100;
+const MAX_XLSX_ZIP_ENTRIES = 4096;
+
+function findSignature(bytes, signature, start, end) {
+ for (let i = end - 4; i >= start; i -= 1) {
+ if (
+ bytes[i] === (signature & 0xff) &&
+ bytes[i + 1] === ((signature >>> 8) & 0xff) &&
+ bytes[i + 2] === ((signature >>> 16) & 0xff) &&
+ bytes[i + 3] === ((signature >>> 24) & 0xff)
+ ) return i;
+ }
+ return -1;
+}
+
+function centralDirectoryEntryCount(archive) {
+ const bytes = new Uint8Array(archive.buffer, archive.byteOffset, archive.byteLength);
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const eocd = findSignature(bytes, 0x06054b50, Math.max(0, bytes.length - 0xffff - 22), bytes.length);
+ if (eocd < 0) return null;
+ const declared = view.getUint16(eocd + 10, true);
+ const directorySize = view.getUint32(eocd + 12, true);
+ const directoryOffset = view.getUint32(eocd + 16, true);
+ if (declared === 0xffff || directorySize === 0xffffffff || directoryOffset === 0xffffffff) {
+ return MAX_XLSX_ZIP_ENTRIES + 1;
+ }
+ if (declared > MAX_XLSX_ZIP_ENTRIES) return declared;
+ const end = directoryOffset + directorySize;
+ if (!Number.isSafeInteger(end) || end > bytes.length) return null;
+ let offset = directoryOffset;
+ let count = 0;
+ while (offset < end) {
+ if (offset + 46 > end || view.getUint32(offset, true) !== 0x02014b50) return null;
+ const nameLength = view.getUint16(offset + 28, true);
+ const extraLength = view.getUint16(offset + 30, true);
+ const commentLength = view.getUint16(offset + 32, true);
+ offset += 46 + nameLength + extraLength + commentLength;
+ count += 1;
+ if (count > MAX_XLSX_ZIP_ENTRIES) return count;
+ }
+ return offset === end ? count : null;
+}
+
+async function assertSafeXlsxArchive(archive) {
+ const entryCount = centralDirectoryEntryCount(archive);
+ if (entryCount !== null && entryCount > MAX_XLSX_ZIP_ENTRIES) {
+ const error = new Error('工作簿 ZIP 条目过多');
+ error.code = 'FILE_TOO_LARGE';
+ error.hint = '这个工作簿包含过多 ZIP 条目,为保护 Cindy 已拒绝读取。请拆分工作簿或重新保存为普通 .xlsx。';
+ throw error;
+ }
+ let zip;
+ try {
+ zip = await JSZip.loadAsync(archive, { createFolders: false });
+ } catch {
+ // 让 ExcelJS 给出原本的格式错误信息,这里仅负责资源边界。
+ return;
+ }
+ let compressed = 0;
+ let uncompressed = 0;
+ for (const entry of Object.values(zip.files)) {
+ const data = entry._data;
+ if (!data) continue;
+ compressed += data.compressedSize || 0;
+ uncompressed += data.uncompressedSize || 0;
+ if (uncompressed > MAX_XLSX_UNCOMPRESSED_BYTES) {
+ const error = new Error('工作簿解压后过大');
+ error.code = 'FILE_TOO_LARGE';
+ error.hint = '这个工作簿的解压体积超过 128 MB,为保护 Cindy 已拒绝读取。请先拆分或重新保存文件。';
+ throw error;
+ }
+ }
+ const ratio = compressed > 0 ? uncompressed / compressed : Number.POSITIVE_INFINITY;
+ if (ratio > MAX_XLSX_COMPRESSION_RATIO) {
+ const error = new Error('工作簿压缩比异常');
+ error.code = 'FILE_TOO_LARGE';
+ error.hint = '这个工作簿疑似是异常压缩包,为保护 Cindy 已拒绝读取。请用 Excel/WPS 重新另存为 .xlsx 后再试。';
+ throw error;
+ }
+}
+
+function normalizeCell(value) {
+ if (value === null || value === undefined) return null;
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
+ if (value instanceof Date) return value.toISOString();
+ if (typeof value === 'object') {
+ if ('result' in value) return normalizeCell(value.result);
+ if ('formula' in value) return '=' + String(value.formula);
+ if ('text' in value && typeof value.text === 'string') return value.text;
+ if ('hyperlink' in value && typeof value.hyperlink === 'string') return value.hyperlink;
+ if ('richText' in value && Array.isArray(value.richText)) return value.richText.map((part) => part.text || '').join('');
+ if ('error' in value) return String(value.error);
+ }
+ return String(value);
+}
+
+(async () => {
+ await assertSafeXlsxArchive(workerData.archive);
+ const workbook = new ExcelJS.Workbook();
+ // 主线程通过受限文件句柄只读取一次;worker 解析同一份已经过大小与 ZIP
+ // 边界校验的字节,不能再按路径重开一个可能已被替换的文件。
+ await workbook.xlsx.load(Buffer.from(workerData.archive));
+ const sheetNames = workbook.worksheets.map((ws) => ws.name);
+ if (sheetNames.length === 0) {
+ return parentPort.postMessage({
+ rows: [],
+ totalRows: 0,
+ totalColumns: 0,
+ startColumn: workerData.startColumn,
+ endColumn: workerData.startColumn - 1,
+ sheetNames,
+ });
+ }
+ let worksheet = workbook.worksheets[0];
+ if (typeof workerData.sheetSelector === 'number') worksheet = workbook.worksheets[workerData.sheetSelector - 1];
+ else if (typeof workerData.sheetSelector === 'string' && workerData.sheetSelector.length > 0) {
+ worksheet = workbook.worksheets.find((ws) => ws.name === workerData.sheetSelector);
+ }
+ if (!worksheet) {
+ const error = new Error('SHEET_NOT_FOUND');
+ error.code = 'SHEET_NOT_FOUND';
+ error.available = sheetNames;
+ throw error;
+ }
+ const totalRows = Math.max(worksheet.rowCount || 0, worksheet.actualRowCount || 0);
+ const totalColumns = Math.max(worksheet.columnCount || 0, worksheet.actualColumnCount || 0);
+ const rows = [];
+ const firstRow = workerData.startRow;
+ const lastRow = Math.min(totalRows, firstRow + workerData.maxRows - 1);
+ const firstColumn = workerData.startColumn;
+ const lastColumn = Math.min(totalColumns, firstColumn + workerData.maxColumns - 1);
+ for (let r = firstRow; r <= lastRow; r += 1) {
+ const row = worksheet.getRow(r);
+ const cells = [];
+ for (let c = firstColumn; c <= lastColumn; c += 1) cells.push(normalizeCell(row.getCell(c).value));
+ rows.push(cells);
+ }
+ parentPort.postMessage({
+ rows,
+ totalRows,
+ totalColumns,
+ startColumn: firstColumn,
+ endColumn: Math.max(firstColumn - 1, lastColumn),
+ sheetName: worksheet.name,
+ sheetNames,
+ });
+})().catch((error) => parentPort.postMessage({ error: {
+ code: error.code,
+ message: String(error.message || error),
+ hint: error.hint,
+ available: error.available,
+} }));
+`;
+
+function readXlsxInWorker(
+ archive: Buffer,
+ sheetSelector: string | number | undefined,
+ startRow: number,
+ maxRows: number,
+ startColumn: number,
+ maxColumns: number,
+): Promise<SheetRead> {
+ return new Promise((resolve, reject) => {
+ // readInputFileWithinLimit 使用独占 ArrayBuffer;转移所有权可避免在主进程
+ // 与 worker 间再复制一份最多 32 MB 的工作簿。
+ const archiveBuffer = archive.buffer as ArrayBuffer;
+ const archiveView = new Uint8Array(
+ archiveBuffer,
+ archive.byteOffset,
+ archive.byteLength,
+ );
+ const worker = new Worker(XLSX_WORKER_SOURCE, {
+ eval: true,
+ workerData: {
+ archive: archiveView,
+ sheetSelector,
+ startRow,
+ maxRows,
+ startColumn,
+ maxColumns,
+ jszipPath: createRequire(import.meta.url).resolve(READ_SHEET_RUNTIME_PACKAGES[0]),
+ exceljsPath: createRequire(import.meta.url).resolve(READ_SHEET_RUNTIME_PACKAGES[1]),
+ },
+ transferList: [archiveBuffer],
+ resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 16 },
+ });
+ let settled = false;
+ let timer: NodeJS.Timeout | undefined;
+ const finish = (fn: () => void): void => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ fn();
+ void worker.terminate();
+ };
+ timer = setTimeout(() => {
+ finish(() => reject(new DocsPathError(
+ 'READ_TIMEOUT',
+ `读取工作簿超时(${XLSX_READ_TIMEOUT_MS}ms)`,
+ '这个工作簿解析时间过长,为保护 Cindy 已终止读取。请先拆分或重新保存文件。',
+ )));
+ }, XLSX_READ_TIMEOUT_MS);
+ worker.once('message', (message: { error?: { code?: string; message?: string; hint?: string; available?: string[] } } & SheetRead) => {
+ if (message.error) {
+ if (message.error.code === 'SHEET_NOT_FOUND') {
+ finish(() => reject(new DocsPathError(
+ 'SHEET_NOT_FOUND',
+ `找不到工作表: ${String(sheetSelector)}`,
+ `这个文件里的工作表是:${message.error?.available?.join(' / ') || '未知'}。请换一个名称或序号。`,
+ )));
+ } else if (message.error.code === 'FILE_TOO_LARGE') {
+ finish(() => reject(new DocsPathError(
+ 'FILE_TOO_LARGE',
+ message.error?.message || '工作簿资源边界超限',
+ message.error?.hint || '这个工作簿触发了安全边界,请拆分或重新保存为普通 .xlsx 后再试。',
+ )));
+ } else {
+ finish(() => reject(Object.assign(new Error(message.error?.message || '读取工作簿失败'), { code: message.error?.code })));
+ }
+ return;
+ }
+ finish(() => resolve(message));
+ });
+ worker.once('error', (error) => finish(() => reject(error)));
+ worker.once('exit', (code) => {
+ if (code !== 0) finish(() => reject(new Error(`工作簿解析进程退出(${code})`)));
+ });
+ });
+}
+
+async function readXlsx(
+ root: string,
+ absPath: string,
+ sheetSelector: string | number | undefined,
+ startRow: number,
+ maxRows: number,
+ startColumn: number,
+ maxColumns: number,
+): Promise<SheetRead> {
+ const archive = await readInputFileWithinLimit(root, absPath, MAX_XLSX_BYTES, xlsxTooLarge);
+ return readXlsxInWorker(archive, sheetSelector, startRow, maxRows, startColumn, maxColumns);
+}
+
+async function readTextTable(
+ root: string,
+ absPath: string,
+ ext: string,
+ startRow: number,
+ maxRows: number,
+ startColumn: number,
+ maxColumns: number,
+): Promise<SheetRead> {
+ const bytes = await readInputFileWithinLimit(
+ root,
+ absPath,
+ MAX_TEXT_BYTES,
+ (size) =>
+ new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `文本表格过大: ${size} 字节`,
+ `这个文件有 ${(size / 1024 / 1024).toFixed(1)} MB,超出单次读取上限(32 MB)。请先让用户拆分文件,或改用命令行工具处理。`,
+ ),
+ );
+ const text = decodeUnicodeText(bytes, '文本表格');
+ const parsed = parseDelimitedWindow(text, {
+ delimiter: delimiterForExtension(ext),
+ startRow,
+ maxRows,
+ includeTotalColumns: true,
+ });
+ const totalColumns = parsed.totalColumns ?? 0;
+ const endColumn = Math.min(totalColumns, startColumn + maxColumns - 1);
+ return {
+ rows: parsed.rows.map((row) => row.slice(startColumn - 1, endColumn)),
+ totalRows: parsed.totalRows,
+ totalColumns,
+ startColumn,
+ endColumn: Math.max(startColumn - 1, endColumn),
+ };
+}
+
+export function registerReadSheetTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+): void {
+ registry.register({
+ name: 'read_sheet',
+ category: 'read',
+ description: DESCRIPTION,
+ inputShape: {
+ path: z
+ .string()
+ .min(1)
+ .describe('表格文件路径,工作目录内的相对路径或绝对路径。'),
+ sheet: z
+ .union([z.string(), z.number().int().min(1)])
+ .optional()
+ .describe('仅 xlsx 有效:工作表名,或 1 起的序号。不传取第一张。'),
+ startRow: z
+ .number()
+ .int()
+ .min(1)
+ .max(Number.MAX_SAFE_INTEGER - HARD_MAX_ROWS)
+ .default(1)
+ .describe('从第几行开始返回,1 起。默认 1;配合 nextStartRow 分批继续读取。'),
+ maxRows: z
+ .number()
+ .int()
+ .min(1)
+ .max(HARD_MAX_ROWS)
+ .default(DEFAULT_MAX_ROWS)
+ .describe(`最多返回多少行,默认 ${DEFAULT_MAX_ROWS},上限 ${HARD_MAX_ROWS}。`),
+ startColumn: z
+ .number()
+ .int()
+ .min(1)
+ .max(Number.MAX_SAFE_INTEGER - HARD_MAX_COLUMNS)
+ .default(1)
+ .describe('从第几列开始返回,1 起。默认 1;配合 nextStartColumn 分批读取宽表。'),
+ maxColumns: z
+ .number()
+ .int()
+ .min(1)
+ .max(HARD_MAX_COLUMNS)
+ .default(DEFAULT_MAX_COLUMNS)
+ .describe(`最多返回多少列,默认 ${DEFAULT_MAX_COLUMNS},上限 ${HARD_MAX_COLUMNS}。`),
+ },
+ handler: async ({ path: inputPath, sheet, startRow, maxRows, startColumn, maxColumns }) => {
+ try {
+ const root = resolveSessionRoot(sessionCtx);
+ const abs = await prepareInputPath(root, inputPath);
+ const ext = path.extname(abs).toLowerCase();
+
+ let result: SheetRead;
+ if (ext === '.xlsx' || ext === '.xlsm') {
+ result = await readXlsx(root, abs, sheet, startRow, maxRows, startColumn, maxColumns);
+ } else if (ext === '.csv' || ext === '.tsv' || ext === '.tab' || ext === '.txt') {
+ result = await readTextTable(root, abs, ext, startRow, maxRows, startColumn, maxColumns);
+ } else if (ext === '.xls') {
+ return errorPayload(
+ 'UNSUPPORTED_FORMAT',
+ '这是老的 .xls 二进制格式,读不了。请让用户在 Excel / WPS 里「另存为」.xlsx 后再试。',
+ { path: abs, extension: ext },
+ );
+ } else {
+ return errorPayload(
+ 'UNSUPPORTED_FORMAT',
+ `不支持的表格格式 "${ext}"。支持的是 .xlsx / .xlsm / .csv / .tsv。`,
+ { path: abs, extension: ext },
+ );
+ }
+
+ const endRow = result.rows.length > 0 ? startRow + result.rows.length - 1 : startRow - 1;
+ const truncated = endRow < result.totalRows;
+ return okPayload({
+ path: abs,
+ format: ext.replace('.', ''),
+ ...(result.sheetName !== undefined ? { sheet: result.sheetName } : {}),
+ ...(result.sheetNames !== undefined ? { sheetNames: result.sheetNames } : {}),
+ rows: result.rows,
+ startRow,
+ endRow,
+ returnedRows: result.rows.length,
+ totalRows: result.totalRows,
+ startColumn: result.startColumn,
+ endColumn: result.endColumn,
+ totalColumns: result.totalColumns,
+ truncated,
+ ...(truncated
+ ? {
+ nextStartRow: endRow + 1,
+ truncationNote: `返回了第 ${startRow}–${endRow} 行,总共 ${result.totalRows} 行。需要更多请用 startRow=${endRow + 1} 继续读取(单次上限 ${HARD_MAX_ROWS}),不要把这一页当作全表。`,
+ }
+ : {}),
+ ...(result.endColumn < result.totalColumns
+ ? {
+ nextStartColumn: result.endColumn + 1,
+ columnTruncationNote: `返回了第 ${result.startColumn}–${result.endColumn} 列,总共 ${result.totalColumns} 列。需要更多请用 startColumn=${result.endColumn + 1} 继续读取(单次上限 ${HARD_MAX_COLUMNS})。`,
+ }
+ : {}),
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ return errorPayload('SHEET_READ_FAILED', `读取表格失败:${message}`, { message });
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/render_pdf.ts b/packages/lizi-mcps/src/cindy-docs/render_pdf.ts
new file mode 100644
index 0000000000..8a68ddec25
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/render_pdf.ts
@@ -0,0 +1,1224 @@
+/**
+ * cindy-docs/render_pdf.ts —— HTML → PDF。
+ *
+ * 渲染本身在 desktop main 的隐藏 BrowserWindow 里跑(Chromium printToPDF),
+ * 由 deps.renderHtmlToPdf 注入 —— 本包不 import electron。工具层只负责:
+ * 参数校验、路径边界、把返回的字节落盘、把失败翻成人话。
+ *
+ * host 没注入渲染能力(纯 Node 宿主复用本包)时本工具整个不注册,不做「注册了
+ * 再运行期报不可用」——模型看不到的工具不会被误选。
+ */
+
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+import { decodeHTMLAttribute } from 'entities';
+import { z } from 'zod';
+
+import type { DocsToolRegistry } from '../cindy_docsToolRegistry.js';
+import {
+ assertOutputExtension,
+ describeOutput,
+ DocsPathError,
+ prepareInputPath,
+ prepareOutputPath,
+ readInputFileWithinLimit,
+ resolveSessionRoot,
+} from './_paths.js';
+import { artifactMetadata, errorPayload, okPayload } from './_payload.js';
+import { decodeCssText, decodeUnicodeText } from './_textEncoding.js';
+import { applyReportTemplate, extractHtmlTitle } from './pdfTemplate.js';
+import { DEFAULT_DOCS_THEME, resolveDocsTheme, type DocsThemeName } from './themes.js';
+import type {
+ DocsMcpSessionCtx,
+ DocsPdfPageSize,
+ RenderHtmlToPdfFn,
+ WriteDocsOutputFn,
+} from './types.js';
+
+/** 与设计一致的渲染硬超时。加载卡死的页面不能拖着任务不放。 */
+export const RENDER_PDF_TIMEOUT_MS = 30_000;
+/**
+ * 等 webfont 就绪的子超时。Chromium 不会自己等 @font-face,字体没加载完就打印会被
+ * 静默替换成系统字体。这里单独给一小段时间等 document.fonts.ready;等不到就照常
+ * 出片并告警,不占满总超时(字体只是"可能不对",而不是"渲染失败")。
+ */
+export const RENDER_PDF_FONT_TIMEOUT_MS = 5_000;
+/** 自包含 HTML 允许内联图片/字体,但仍需限制主进程读取和模板复制的内存上界。 */
+export const RENDER_PDF_MAX_HTML_BYTES = 16 * 1024 * 1024;
+/** 空/超小 PDF 的告警阈值:低于这个字节数几乎必然是白页,值得让模型自查。 */
+const SUSPICIOUS_PDF_BYTES = 2_048;
+/** 单个任务目录资源的上限,避免 HTML 引用一个超大本地文件拖垮 main。 */
+const MAX_LOCAL_RESOURCE_BYTES = 8 * 1024 * 1024;
+/** 一个 HTML 快照允许带入的本地资源总量。 */
+const MAX_LOCAL_RESOURCE_TOTAL_BYTES = 32 * 1024 * 1024;
+/** 资源展开成 data URI 后的 HTML 硬上限,防止重复引用放大主进程字符串。 */
+const MAX_SNAPSHOT_HTML_BYTES = 64 * 1024 * 1024;
+/** 单次 HTML 快照允许处理的本地资源引用次数,防止重复 token 拖垮主进程。 */
+const MAX_LOCAL_RESOURCE_REFERENCES = 4_096;
+
+const DEFAULT_MARGIN_INCHES = 0.4;
+
+const LOCAL_RESOURCE_MIME_TYPES: Record<string, string> = {
+ '.avif': 'image/avif',
+ '.css': 'text/css',
+ '.gif': 'image/gif',
+ '.jpeg': 'image/jpeg',
+ '.jpg': 'image/jpeg',
+ '.otf': 'font/otf',
+ '.png': 'image/png',
+ '.svg': 'image/svg+xml',
+ '.ttf': 'font/ttf',
+ '.wasm': 'application/wasm',
+ '.webp': 'image/webp',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+};
+
+interface ResourceSnapshotContext {
+ root: string;
+ totalBytes: number;
+ resourceReferences: number;
+ cache: Map<string, string>;
+ lexicalCache: Map<string, string>;
+ cssStack: Set<string>;
+ directorySnapshots: Map<string, DirectorySnapshot>;
+}
+
+interface DirectorySnapshot {
+ path: string;
+ realPath: string;
+ dev: bigint;
+ ino: bigint;
+ mtimeNs: bigint;
+ ctimeNs: bigint;
+}
+
+function resourceDirectoryChanged(directory: string): DocsPathError {
+ return new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `HTML 快照期间资源目录发生变化: ${directory}`,
+ 'HTML 与相对资源不再来自同一份任务目录快照,请确认资源目录未被并发修改后重试。',
+ );
+}
+
+async function captureDirectorySnapshot(directory: string): Promise<DirectorySnapshot> {
+ try {
+ const [realPath, stat] = await Promise.all([
+ fs.realpath(directory),
+ fs.stat(directory, { bigint: true }),
+ ]);
+ if (!stat.isDirectory()) throw resourceDirectoryChanged(directory);
+ return {
+ path: directory,
+ realPath,
+ dev: stat.dev,
+ ino: stat.ino,
+ mtimeNs: stat.mtimeNs,
+ ctimeNs: stat.ctimeNs,
+ };
+ } catch (error) {
+ if (error instanceof DocsPathError) throw error;
+ throw resourceDirectoryChanged(directory);
+ }
+}
+
+function sameDirectorySnapshot(left: DirectorySnapshot, right: DirectorySnapshot): boolean {
+ return (
+ left.dev === right.dev &&
+ left.ino === right.ino &&
+ left.realPath === right.realPath &&
+ left.mtimeNs === right.mtimeNs &&
+ left.ctimeNs === right.ctimeNs
+ );
+}
+
+async function recordDirectorySnapshot(
+ context: ResourceSnapshotContext,
+ directory: string,
+ expected?: DirectorySnapshot,
+): Promise<void> {
+ const key = path.resolve(directory);
+ const current = await captureDirectorySnapshot(directory);
+ if (expected && !sameDirectorySnapshot(expected, current)) {
+ throw resourceDirectoryChanged(directory);
+ }
+ const previous = context.directorySnapshots.get(key);
+ if (previous && !sameDirectorySnapshot(previous, current)) {
+ throw resourceDirectoryChanged(directory);
+ }
+ context.directorySnapshots.set(key, current);
+}
+
+async function verifyDirectorySnapshots(context: ResourceSnapshotContext): Promise<void> {
+ for (const snapshot of context.directorySnapshots.values()) {
+ const current = await captureDirectorySnapshot(snapshot.path);
+ if (!sameDirectorySnapshot(snapshot, current)) {
+ throw resourceDirectoryChanged(snapshot.path);
+ }
+ }
+}
+
+function dataUri(mime: string, bytes: Uint8Array): string {
+ return `data:${mime};base64,${Buffer.from(bytes).toString('base64')}`;
+}
+
+function isLocalResourceReference(reference: string): boolean {
+ const value = reference.trim();
+ if (!value || value.startsWith('#') || value.startsWith('//')) return false;
+ try {
+ return new URL(value).protocol === '';
+ } catch {
+ return !/^[a-z][a-z\d+.-]*:/i.test(value);
+ }
+}
+
+function assertNotExplicitFileUrl(reference: string): void {
+ const value = reference.trim();
+ if (!value) return;
+ try {
+ if (new URL(value).protocol !== 'file:') return;
+ } catch {
+ return;
+ }
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `HTML 不允许显式 file: URL: ${reference}`,
+ '请改用任务工作目录内的相对路径或 data URI。',
+ );
+}
+
+function assertNotBlockedRemoteUrl(reference: string): void {
+ const value = reference.trim();
+ if (!value) return;
+ if (value.startsWith('//')) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `HTML 不允许公网资源 URL: ${reference}`,
+ '渲染器会阻断 http(s) 请求。请先把图片、字体或样式表放进任务工作目录,或改成 data URI。',
+ );
+ }
+ let protocol = '';
+ try {
+ protocol = new URL(value).protocol;
+ } catch {
+ return;
+ }
+ if (protocol !== 'http:' && protocol !== 'https:') return;
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `HTML 不允许公网资源 URL: ${reference}`,
+ '渲染器会阻断 http(s) 请求。请先把图片、字体或样式表放进任务工作目录,或改成 data URI。',
+ );
+}
+
+function resolveLocalResourcePath(baseUrl: URL, reference: string): string | undefined {
+ let resolved: URL;
+ try {
+ resolved = new URL(reference.trim(), baseUrl);
+ } catch {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `本地资源 URL 无法解码: ${reference}`,
+ '请把图片、字体或样式表改成有效的相对路径或 data URI。',
+ );
+ }
+ if (resolved.protocol !== 'file:') return undefined;
+ resolved.hash = '';
+ resolved.search = '';
+ try {
+ return fileURLToPath(resolved);
+ } catch {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `本地资源 URL 无法解析: ${reference}`,
+ '请把图片、字体或样式表改成有效的相对路径或 data URI。',
+ );
+ }
+}
+
+function resourceMime(absPath: string): string {
+ return (
+ LOCAL_RESOURCE_MIME_TYPES[path.extname(absPath).toLowerCase()] ?? 'application/octet-stream'
+ );
+}
+
+function assertSnapshotHtmlSize(bytes: number): void {
+ if (bytes > MAX_SNAPSHOT_HTML_BYTES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ 'HTML 引用的本地资源展开后过大',
+ '这份 HTML 的本地资源在转换成 data URI 后超过 64 MB。请减少重复引用、压缩资源或拆分文档后重试。',
+ );
+ }
+}
+
+async function replaceAsync(
+ input: string,
+ pattern: RegExp,
+ replacer: (match: string, ...groups: string[]) => Promise<string>,
+): Promise<string> {
+ const matches = Array.from(input.matchAll(pattern));
+ if (matches.length === 0) return input;
+ const parts: string[] = [];
+ let outputBytes = 0;
+ const pushPart = (part: string): void => {
+ outputBytes += Buffer.byteLength(part, 'utf8');
+ assertSnapshotHtmlSize(outputBytes);
+ parts.push(part);
+ };
+ let cursor = 0;
+ for (const match of matches) {
+ const index = match.index ?? 0;
+ pushPart(input.slice(cursor, index));
+ pushPart(await replacer(match[0]!, ...match.slice(1).map((group) => group ?? '')));
+ cursor = index + match[0]!.length;
+ }
+ pushPart(input.slice(cursor));
+ return parts.join('');
+}
+
+function findHtmlTagEnd(input: string, start: number): number {
+ let quote: string | undefined;
+ for (let end = start + 1; end < input.length; end += 1) {
+ const ch = input[end]!;
+ if (quote) {
+ if (ch === quote) quote = undefined;
+ continue;
+ }
+ if (ch === '"' || ch === "'") quote = ch;
+ else if (ch === '>') return end;
+ }
+ return -1;
+}
+
+const HTML_RAW_TEXT_TAGS = new Set([
+ 'iframe',
+ 'noembed',
+ 'noframes',
+ 'noscript',
+ 'script',
+ 'style',
+ 'textarea',
+ 'title',
+ 'xmp',
+]);
+
+function findTemplateSubtreeEnd(input: string, contentStart: number): number {
+ let depth = 1;
+ let index = contentStart;
+ while (index < input.length) {
+ const start = input.indexOf('<', index);
+ if (start < 0) return input.length;
+ if (input.startsWith('<!--', start)) {
+ const endComment = input.indexOf('-->', start + 4);
+ index = endComment < 0 ? input.length : endComment + 3;
+ continue;
+ }
+ const end = findHtmlTagEnd(input, start);
+ if (end < 0) return input.length;
+ const tag = input.slice(start, end + 1);
+ const rawText = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/i);
+ if (rawText && HTML_RAW_TEXT_TAGS.has(rawText[1]!.toLowerCase())) {
+ const closing = new RegExp(`<\\/\\s*${rawText[1]}\\s*>`, 'ig');
+ closing.lastIndex = end + 1;
+ const closingMatch = closing.exec(input);
+ index = closingMatch ? closingMatch.index + closingMatch[0].length : input.length;
+ continue;
+ }
+ if (/^<\s*template\b/i.test(tag) && !/\/\s*>$/.test(tag)) depth += 1;
+ else if (/^<\s*\/\s*template\s*>/i.test(tag)) {
+ depth -= 1;
+ if (depth === 0) return end + 1;
+ }
+ index = end + 1;
+ }
+ return input.length;
+}
+
+/** HTML tag scanner that does not terminate on `>` inside a quoted attribute. */
+async function replaceHtmlTagsAsync(
+ input: string,
+ predicate: (tag: string) => boolean,
+ replacer: (tag: string) => Promise<string>,
+): Promise<string> {
+ const parts: string[] = [];
+ let outputBytes = 0;
+ const pushPart = (part: string): void => {
+ outputBytes += Buffer.byteLength(part, 'utf8');
+ assertSnapshotHtmlSize(outputBytes);
+ parts.push(part);
+ };
+ let cursor = 0;
+ let index = 0;
+ while (index < input.length) {
+ const start = input.indexOf('<', index);
+ if (start < 0) break;
+ if (input.startsWith('<!--', start)) {
+ const endComment = input.indexOf('-->', start + 4);
+ index = endComment < 0 ? input.length : endComment + 3;
+ continue;
+ }
+ const end = findHtmlTagEnd(input, start);
+ if (end < 0) break;
+ const tag = input.slice(start, end + 1);
+ if (/^<\s*template\b/i.test(tag) && !/\/\s*>$/.test(tag)) {
+ index = findTemplateSubtreeEnd(input, end + 1);
+ continue;
+ }
+ const rawTextMatch = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/i);
+ if (rawTextMatch && HTML_RAW_TEXT_TAGS.has(rawTextMatch[1]!.toLowerCase())) {
+ if (predicate(tag)) {
+ pushPart(input.slice(cursor, start));
+ pushPart(await replacer(tag));
+ cursor = end + 1;
+ }
+ const name = rawTextMatch[1]!;
+ const closing = new RegExp(`<\\/\\s*${name}\\s*>`, 'ig');
+ closing.lastIndex = end + 1;
+ const closingMatch = closing.exec(input);
+ index = closingMatch ? closingMatch.index + closingMatch[0].length : input.length;
+ continue;
+ }
+ if (predicate(tag)) {
+ pushPart(input.slice(cursor, start));
+ pushPart(await replacer(tag));
+ cursor = end + 1;
+ }
+ index = end + 1;
+ }
+ pushPart(input.slice(cursor));
+ return parts.join('');
+}
+
+async function inlineCssImports(
+ css: string,
+ baseUrl: URL,
+ context: ResourceSnapshotContext,
+): Promise<string> {
+ return rewriteCssResources(css, baseUrl, context);
+}
+
+async function inlineCssUrls(
+ css: string,
+ baseUrl: URL,
+ context: ResourceSnapshotContext,
+ decodeReference: (reference: string) => string = (reference) => reference,
+): Promise<string> {
+ return rewriteCssResources(css, baseUrl, context, decodeReference);
+}
+
+function isCssHexDigit(value: string | undefined): boolean {
+ return value !== undefined && /^[\da-f]$/i.test(value);
+}
+
+function isCssWhitespace(value: string | undefined): boolean {
+ return value === ' ' || value === '\t' || value === '\r' || value === '\n' || value === '\f';
+}
+
+function skipCssWhitespaceAndComments(css: string, start: number): number {
+ let cursor = start;
+ while (cursor < css.length) {
+ while (isCssWhitespace(css[cursor])) cursor += 1;
+ if (!css.startsWith('/*', cursor)) break;
+ const end = css.indexOf('*/', cursor + 2);
+ cursor = end < 0 ? css.length : end + 2;
+ }
+ return cursor;
+}
+
+function isCssIdentifierContinuation(value: string | undefined): boolean {
+ if (value === undefined) return false;
+ const codePoint = value.codePointAt(0)!;
+ return (
+ value === '-' ||
+ value === '_' ||
+ value === '\\' ||
+ /^[a-z\d]$/i.test(value) ||
+ codePoint >= 0x80
+ );
+}
+
+function cssEscapeEnd(value: string, start: number): number {
+ const next = value[start + 1];
+ if (next === undefined) return start + 1;
+ if (next === '\r' && value[start + 2] === '\n') return start + 3;
+ if (next === '\r' || next === '\n' || next === '\f') return start + 2;
+ if (!isCssHexDigit(next)) return start + 2;
+ let end = start + 1;
+ let digits = 0;
+ while (digits < 6 && isCssHexDigit(value[end])) {
+ end += 1;
+ digits += 1;
+ }
+ if (value[end] === '\r' && value[end + 1] === '\n') return end + 2;
+ if (isCssWhitespace(value[end])) return end + 1;
+ return end;
+}
+
+/** Decode CSS escapes after the containing HTML attribute has been decoded. */
+function decodeCssResourceReference(value: string): string {
+ let decoded = '';
+ let index = 0;
+ while (index < value.length) {
+ if (value[index] !== '\\') {
+ decoded += value[index]!;
+ index += 1;
+ continue;
+ }
+ const escapeEnd = cssEscapeEnd(value, index);
+ const escaped = value.slice(index + 1, escapeEnd);
+ if (escaped === '\n' || escaped === '\r' || escaped === '\f' || escaped === '\r\n') {
+ index = escapeEnd;
+ continue;
+ }
+ const hex = escaped.match(/^[\da-f]{1,6}/i)?.[0];
+ if (hex) {
+ const codePoint = Number.parseInt(hex, 16);
+ decoded +=
+ codePoint === 0 || codePoint > 0x10ffff || (codePoint >= 0xd800 && codePoint <= 0xdfff)
+ ? '\ufffd'
+ : String.fromCodePoint(codePoint);
+ } else if (escaped.length > 0) {
+ decoded += escaped[0]!;
+ } else {
+ decoded += '\ufffd';
+ }
+ index = escapeEnd;
+ }
+ return decoded;
+}
+
+function parseCssIdentifier(css: string, index: number): { value: string; end: number } | null {
+ let value = '';
+ let cursor = index;
+ while (isCssIdentifierContinuation(css[cursor])) {
+ if (css[cursor] === '\\') {
+ const end = cssEscapeEnd(css, cursor);
+ value += decodeCssResourceReference(css.slice(cursor, end));
+ cursor = end;
+ } else {
+ value += css[cursor]!;
+ cursor += 1;
+ }
+ }
+ return cursor > index ? { value, end: cursor } : null;
+}
+
+function parseCssUrlToken(
+ css: string,
+ index: number,
+): { reference: string; end: number } | null {
+ if (isCssIdentifierContinuation(css[index - 1])) return null;
+ const identifier = parseCssIdentifier(css, index);
+ if (identifier?.value.toLowerCase() !== 'url') return null;
+ const open = skipCssWhitespaceAndComments(css, identifier.end);
+ if (css[open] !== '(') return null;
+ let cursor = open + 1;
+ cursor = skipCssWhitespaceAndComments(css, cursor);
+ let reference = '';
+ if (css[cursor] === '"' || css[cursor] === "'") {
+ const quote = css[cursor]!;
+ cursor += 1;
+ const start = cursor;
+ while (cursor < css.length && css[cursor] !== quote) {
+ if (css[cursor] === '\\') cursor = cssEscapeEnd(css, cursor);
+ else cursor += 1;
+ }
+ reference = css.slice(start, cursor);
+ cursor += 1;
+ } else {
+ const start = cursor;
+ while (cursor < css.length && css[cursor] !== ')') {
+ if (css[cursor] === '\\') cursor = cssEscapeEnd(css, cursor);
+ else cursor += 1;
+ }
+ reference = css.slice(start, cursor).trim();
+ }
+ while (isCssWhitespace(css[cursor])) cursor += 1;
+ return css[cursor] === ')' ? { reference, end: cursor + 1 } : null;
+}
+
+async function rewriteCssResources(
+ css: string,
+ baseUrl: URL,
+ context: ResourceSnapshotContext,
+ decodeReference: (reference: string) => string = (reference) => reference,
+): Promise<string> {
+ const out: string[] = [];
+ let index = 0;
+ while (index < css.length) {
+ if (css.startsWith('/*', index)) {
+ const end = css.indexOf('*/', index + 2);
+ const stop = end < 0 ? css.length : end + 2;
+ out.push(css.slice(index, stop));
+ index = stop;
+ continue;
+ }
+ const current = css[index]!;
+ if (current === '"' || current === "'") {
+ const quote = current;
+ let end = index + 1;
+ while (end < css.length) {
+ if (css[end] === '\\') end = cssEscapeEnd(css, end);
+ else if (css[end] === quote) {
+ end += 1;
+ break;
+ } else end += 1;
+ }
+ out.push(css.slice(index, end));
+ index = end;
+ continue;
+ }
+ const importMatch = css.slice(index).match(/^@import\b/i);
+ if (importMatch) {
+ let cursor = index + importMatch[0].length;
+ cursor = skipCssWhitespaceAndComments(css, cursor);
+ if (css[cursor] === '"' || css[cursor] === "'") {
+ const quote = css[cursor]!;
+ const start = cursor;
+ cursor += 1;
+ while (cursor < css.length && css[cursor] !== quote) {
+ if (css[cursor] === '\\') cursor = cssEscapeEnd(css, cursor);
+ else cursor += 1;
+ }
+ const reference = css.slice(start + 1, cursor);
+ const snapshot = await snapshotLocalResource(
+ context,
+ baseUrl,
+ decodeCssResourceReference(decodeReference(reference.trim())),
+ 'text/css',
+ );
+ out.push(css.slice(index, start));
+ out.push(snapshot ? `url("${snapshot}")` : css.slice(start, cursor + 1));
+ index = Math.min(css.length, cursor + 1);
+ continue;
+ }
+ const importUrl = parseCssUrlToken(css, cursor);
+ if (importUrl) {
+ const snapshot = await snapshotLocalResource(
+ context,
+ baseUrl,
+ decodeCssResourceReference(decodeReference(importUrl.reference)),
+ 'text/css',
+ );
+ out.push(css.slice(index, cursor));
+ out.push(snapshot ? `url("${snapshot}")` : css.slice(cursor, importUrl.end));
+ index = importUrl.end;
+ continue;
+ }
+ }
+ const urlToken = parseCssUrlToken(css, index);
+ if (urlToken) {
+ const original = css.slice(index, urlToken.end);
+ const snapshot = await snapshotLocalResource(
+ context,
+ baseUrl,
+ decodeCssResourceReference(decodeReference(urlToken.reference)),
+ );
+ out.push(snapshot ? `url("${snapshot}")` : original);
+ index = urlToken.end;
+ continue;
+ }
+ out.push(current);
+ index += 1;
+ }
+ const rewritten = out.join('');
+ assertSnapshotHtmlSize(Buffer.byteLength(rewritten, 'utf8'));
+ return rewritten;
+}
+
+function splitSrcset(value: string): string[] {
+ const candidates: string[] = [];
+ let start = 0;
+ for (let index = 0; index < value.length - 1; index += 1) {
+ if (value[index] !== ',') continue;
+ const segment = value.slice(start, index).trimStart();
+ const insideDataUrl = /^data:/i.test(segment) && !/\s/.test(segment);
+ if (insideDataUrl) continue;
+ candidates.push(value.slice(start, index));
+ start = index + 1;
+ }
+ candidates.push(value.slice(start));
+ return candidates.map((candidate) => candidate.trim()).filter(Boolean);
+}
+
+/**
+ * Read the small subset of HTML attributes whose values may point at local
+ * task resources. HTML permits these values to be either quoted or
+ * unquoted; keeping one parser for both forms prevents the resource policy
+ * from silently dropping valid markup such as `<img src=./chart.png>`.
+ */
+const HTML_ATTRIBUTE_PATTERN =
+ /(\s+)([A-Za-z_:][\w:.-]*)(\s*=\s*)(?:(['"])([\s\S]*?)\4|([^\s"'=<>\x60]+))/gi;
+
+function readHtmlAttribute(tag: string, attributeName: string): string | undefined {
+ const wanted = attributeName.toLowerCase();
+ for (const match of tag.matchAll(HTML_ATTRIBUTE_PATTERN)) {
+ if (match[2]!.toLowerCase() !== wanted) continue;
+ return match[4] ? match[5] : match[6];
+ }
+ return undefined;
+}
+
+async function rewriteHtmlAttributes(
+ tag: string,
+ attributeNames: readonly string[],
+ replacer: (value: string, attributeName: string) => Promise<string>,
+): Promise<string> {
+ const wanted = new Set(attributeNames.map((name) => name.toLowerCase()));
+ return replaceAsync(
+ tag,
+ HTML_ATTRIBUTE_PATTERN,
+ async (match, leading, attributeName, equals, quote, quoted, bare) => {
+ const normalizedName = attributeName.toLowerCase();
+ if (!wanted.has(normalizedName)) return match;
+ const value = quote ? quoted : bare;
+ const rewritten = await replacer(value, normalizedName);
+ if (rewritten === value) return match;
+ if (quote) {
+ const escaped = rewritten
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(quote === '"' ? /"/g : /'/g, quote === '"' ? '&quot;' : '&#39;');
+ return `${leading}${attributeName}${equals}${quote}${escaped}${quote}`;
+ }
+ if (/^[^\s"'=<>\x60]+$/.test(rewritten)) {
+ return `${leading}${attributeName}${equals}${rewritten}`;
+ }
+ const escaped = rewritten
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/"/g, '&quot;');
+ return `${leading}${attributeName}${equals}"${escaped}"`;
+ },
+ );
+}
+
+async function inlineSrcset(
+ value: string,
+ baseUrl: URL,
+ context: ResourceSnapshotContext,
+): Promise<string> {
+ const candidates = splitSrcset(value);
+ const rewritten = await Promise.all(
+ candidates.map(async (candidate) => {
+ const match = candidate.match(/^(\S+)(?:\s+(.+))?$/);
+ if (!match) return candidate;
+ const snapshot = await snapshotLocalResource(
+ context,
+ baseUrl,
+ decodeHTMLAttribute(match[1]!),
+ );
+ return `${snapshot ?? match[1]}${match[2] ? ` ${match[2]}` : ''}`;
+ }),
+ );
+ return rewritten.join(', ');
+}
+
+async function rewriteHtmlStyleElementsAsync(
+ input: string,
+ baseUrl: URL,
+ context: ResourceSnapshotContext,
+): Promise<string> {
+ const parts: string[] = [];
+ let cursor = 0;
+ let index = 0;
+ let outputBytes = 0;
+ const push = (part: string): void => {
+ outputBytes += Buffer.byteLength(part, 'utf8');
+ assertSnapshotHtmlSize(outputBytes);
+ parts.push(part);
+ };
+ while (index < input.length) {
+ const start = input.indexOf('<', index);
+ if (start < 0) break;
+ if (input.startsWith('<!--', start)) {
+ const endComment = input.indexOf('-->', start + 4);
+ index = endComment < 0 ? input.length : endComment + 3;
+ continue;
+ }
+ const end = findHtmlTagEnd(input, start);
+ if (end < 0) break;
+ const tag = input.slice(start, end + 1);
+ if (/^<\s*template\b/i.test(tag) && !/\/\s*>$/.test(tag)) {
+ index = findTemplateSubtreeEnd(input, end + 1);
+ continue;
+ }
+ const opening = /^<\s*style\b/i.test(tag) && !/^<\s*\/style\b/i.test(tag);
+ if (!opening) {
+ const raw = tag.match(/^<\s*([A-Za-z][\w:-]*)\b/i);
+ if (raw && HTML_RAW_TEXT_TAGS.has(raw[1]!.toLowerCase())) {
+ const closing = new RegExp(`<\\/\\s*${raw[1]}\\s*>`, 'ig');
+ closing.lastIndex = end + 1;
+ const closingMatch = closing.exec(input);
+ index = closingMatch ? closingMatch.index + closingMatch[0].length : input.length;
+ continue;
+ }
+ index = end + 1;
+ continue;
+ }
+ const closing = /<\/\s*style\s*>/gi;
+ closing.lastIndex = end + 1;
+ const closingMatch = closing.exec(input);
+ if (!closingMatch) break;
+ push(input.slice(cursor, start));
+ push(tag);
+ const css = input.slice(end + 1, closingMatch.index);
+ const imported = await inlineCssImports(css, baseUrl, context);
+ push(await inlineCssUrls(imported, baseUrl, context));
+ push(closingMatch[0]);
+ cursor = closingMatch.index + closingMatch[0].length;
+ index = cursor;
+ }
+ push(input.slice(cursor));
+ return parts.join('');
+}
+
+async function snapshotLocalResource(
+ context: ResourceSnapshotContext,
+ baseUrl: URL,
+ reference: string,
+ mimeOverride?: string,
+): Promise<string | undefined> {
+ assertNotExplicitFileUrl(reference);
+ assertNotBlockedRemoteUrl(reference);
+ if (!isLocalResourceReference(reference)) return undefined;
+ let fragment = '';
+ try {
+ fragment = new URL(reference.trim(), baseUrl).hash;
+ } catch {
+ // resolveLocalResourcePath below returns the user-facing validation error.
+ }
+ const absPath = resolveLocalResourcePath(baseUrl, reference);
+ if (!absPath) return undefined;
+ context.resourceReferences += 1;
+ if (context.resourceReferences > MAX_LOCAL_RESOURCE_REFERENCES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ 'HTML 引用的本地资源次数过多',
+ `这份 HTML 的本地图片、字体和样式表引用超过 ${MAX_LOCAL_RESOURCE_REFERENCES} 次。请减少重复引用或改用 data URI。`,
+ );
+ }
+ const lexicalCacheKey = `${path.resolve(absPath)}\0${mimeOverride ?? ''}`;
+ const lexicalCached = context.lexicalCache.get(lexicalCacheKey);
+ if (lexicalCached) return `${lexicalCached}${fragment}`;
+ const preparedPath = await prepareInputPath(context.root, absPath);
+ const cacheKey = `${path.resolve(preparedPath)}\0${mimeOverride ?? ''}`;
+ const cached = context.cache.get(cacheKey);
+ if (cached) return `${cached}${fragment}`;
+
+ const resourceDirectory = path.dirname(preparedPath);
+ const beforeDirectory = await captureDirectorySnapshot(resourceDirectory);
+ await recordDirectorySnapshot(context, resourceDirectory, beforeDirectory);
+
+ const bytes = await readInputFileWithinLimit(
+ context.root,
+ preparedPath,
+ MAX_LOCAL_RESOURCE_BYTES,
+ (size) =>
+ new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `本地资源过大: ${preparedPath}`,
+ `这份本地资源有 ${(size / 1024 / 1024).toFixed(1)} MB,超过单个资源上限(8 MB)。请压缩或改成更小的 data URI。`,
+ ),
+ );
+ const afterDirectory = await captureDirectorySnapshot(resourceDirectory);
+ if (!sameDirectorySnapshot(beforeDirectory, afterDirectory)) {
+ throw resourceDirectoryChanged(resourceDirectory);
+ }
+ context.totalBytes += bytes.byteLength;
+ if (context.totalBytes > MAX_LOCAL_RESOURCE_TOTAL_BYTES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ 'HTML 引用的本地资源总量过大',
+ '这份 HTML 引用的本地图片、字体和样式表总量超过 32 MB。请压缩资源或拆分文档后重试。',
+ );
+ }
+
+ const mime = mimeOverride ?? resourceMime(preparedPath);
+ let snapshotBytes = bytes;
+ if (mime === 'text/css') {
+ const decodedCss = decodeCssText(bytes);
+ if (context.cssStack.has(cacheKey)) {
+ return dataUri(mime, Buffer.from(decodedCss, 'utf8'));
+ }
+ context.cssStack.add(cacheKey);
+ try {
+ const imported = await inlineCssImports(decodedCss, pathToFileURL(preparedPath), context);
+ const rewritten = await inlineCssUrls(imported, pathToFileURL(preparedPath), context);
+ snapshotBytes = Buffer.from(rewritten, 'utf8');
+ } finally {
+ context.cssStack.delete(cacheKey);
+ }
+ }
+ const snapshot = dataUri(mime, snapshotBytes);
+ context.cache.set(cacheKey, snapshot);
+ context.lexicalCache.set(lexicalCacheKey, snapshot);
+ return `${snapshot}${fragment}`;
+}
+
+async function inlineLocalResources(
+ root: string,
+ sourcePath: string,
+ html: string,
+ expectedSourceDirectory?: DirectorySnapshot,
+ initialDirectorySnapshots?: Map<string, DirectorySnapshot>,
+): Promise<string> {
+ const context: ResourceSnapshotContext = {
+ root,
+ totalBytes: 0,
+ resourceReferences: 0,
+ cache: new Map(),
+ lexicalCache: new Map(),
+ cssStack: new Set(),
+ directorySnapshots: new Map(initialDirectorySnapshots),
+ };
+ await recordDirectorySnapshot(
+ context,
+ path.dirname(sourcePath),
+ expectedSourceDirectory
+ ? { ...expectedSourceDirectory, path: path.dirname(sourcePath) }
+ : undefined,
+ );
+ const documentUrl = pathToFileURL(sourcePath);
+ let baseUrl = documentUrl;
+ let baseTag: string | undefined;
+ await replaceHtmlTagsAsync(
+ html,
+ (tag) => /^<base\b/i.test(tag),
+ async (tag) => {
+ baseTag ??= tag;
+ return tag;
+ },
+ );
+ const rawBaseHref = baseTag ? readHtmlAttribute(baseTag, 'href') : undefined;
+ const baseHref = rawBaseHref ? decodeHTMLAttribute(rawBaseHref) : undefined;
+ if (baseHref) {
+ assertNotExplicitFileUrl(baseHref);
+ assertNotBlockedRemoteUrl(baseHref);
+ try {
+ baseUrl = new URL(baseHref, documentUrl);
+ } catch {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `HTML 的 base href 无法解析: ${baseHref}`,
+ '请把 <base href> 改成有效的本地相对路径。',
+ );
+ }
+ }
+ let rewritten = await replaceHtmlTagsAsync(
+ html,
+ (tag) => /^<link\b/i.test(tag),
+ async (tag) => {
+ const href = readHtmlAttribute(tag, 'href');
+ if (!href) return tag;
+ assertNotBlockedRemoteUrl(decodeHTMLAttribute(href));
+ const rel = decodeHTMLAttribute(readHtmlAttribute(tag, 'rel') ?? '');
+ const isStylesheet = rel
+ .split(/\s+/)
+ .some((token) => token.toLowerCase() === 'stylesheet');
+ if (!isStylesheet && !/\.css(?:[?#]|$)/i.test(href)) return tag;
+ return rewriteHtmlAttributes(tag, ['href'], async (reference) => {
+ return (
+ (await snapshotLocalResource(
+ context,
+ baseUrl,
+ decodeHTMLAttribute(reference),
+ 'text/css',
+ )) ?? reference
+ );
+ });
+ },
+ );
+ rewritten = await replaceHtmlTagsAsync(
+ rewritten,
+ (tag) => /^<(?:img|source|audio|video|track|object|input|image|use)\b/i.test(tag),
+ async (tag) => {
+ const withSources = await rewriteHtmlAttributes(
+ tag,
+ ['src', 'poster', 'data', 'href', 'xlink:href'],
+ async (reference) =>
+ (await snapshotLocalResource(context, baseUrl, decodeHTMLAttribute(reference))) ??
+ reference,
+ );
+ return rewriteHtmlAttributes(withSources, ['srcset'], async (value) =>
+ inlineSrcset(value, baseUrl, context),
+ );
+ },
+ );
+ rewritten = await rewriteHtmlStyleElementsAsync(rewritten, baseUrl, context);
+ const result = await replaceHtmlTagsAsync(
+ rewritten,
+ (tag) => tag[1] !== '/' && /\bstyle\s*=/i.test(tag),
+ (tag) =>
+ rewriteHtmlAttributes(tag, ['style'], async (css) => {
+ const rewrittenCss = await inlineCssUrls(decodeHTMLAttribute(css), baseUrl, context);
+ return rewrittenCss;
+ }),
+ );
+ await verifyDirectorySnapshots(context);
+ return result;
+}
+
+const DESCRIPTION = [
+ '把 HTML 渲染成 PDF(用 Cindy 内置的 Chromium 排版,不需要用户装任何东西)。',
+ '',
+ '【何时用】需要精确版式的正式文档:报告、简历、发票、带图表的材料。',
+ '推荐做法是先写一份自包含的 HTML(样式内联,不依赖外部 CSS 文件),再用本工具出 PDF。',
+ '如果产物要给人二次编辑,请改用 make_docx —— PDF 不好改。',
+ '',
+ '【输入】htmlPath(工作目录内的 .html 文件)与 html(内联源码)二选一,必须给且只给一个。',
+ 'HTML 源码上限 16 MB;文件路径与内联源码使用同一上限。',
+ '为防止不可信 HTML 借用户网络身份探测内网或触发跟踪,渲染窗会阻断外部网络请求。',
+ '图片/字体/样式可直接引用任务目录内的相对路径;工具会先把已验证的本地资源快照成 data URI,再交给渲染器。外部网络请求仍会阻断。',
+ '',
+ '【模板】template 默认 auto:没有 <style> / 外链 CSS 的裸 HTML 会自动套内置报告模板',
+ '(系统字体、标题层级、表格斑马纹、打印页边距)。已经自己写了样式的原样透传。',
+ 'template:"none" 关闭;theme: light / dark / navy 只影响自动套上的模板。',
+ '',
+ '【排版】pageSize 默认 A4;margins 单位是英寸,默认四边 0.4。',
+ '自动套模板且未显式传 margins 时,Electron 边距归零,改由 CSS @page 管边距,避免双边距。',
+ 'printBackground 默认 true(否则深色底、色块全部不打印)。',
+ '分页控制在 HTML 里用 CSS: page-break-after / break-inside: avoid。',
+ '',
+ '【字体】渲染前会等 @font-face 加载完(最多 5 秒)。等不到会照常出片,但返回里',
+ 'fontsReady=false —— 那说明 PDF 里的字体很可能被换成了系统默认字体。要么把字体',
+ '改成 base64 内联进 HTML,要么接受回退,别不看这个字段就交付。',
+ '',
+ '【自检】出片后**务必再调 inspect_pdf 回读一次**:整页空白的 PDF 字节数看着完全',
+ '正常,只看 bytes 判断不出来。inspect_pdf 会直接告诉你哪几页是白的、总共几页、',
+ '纸张对不对。返回里的 bytes 只能筛掉最极端的情况。',
+ '',
+ '【输出】outPath 必须在本任务的工作目录内。同名文件默认不覆盖,确要覆盖再传 overwrite: true。',
+].join('\n');
+
+const PAGE_SIZES: readonly DocsPdfPageSize[] = ['A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'];
+
+export function registerRenderPdfTool(
+ registry: DocsToolRegistry,
+ sessionCtx: DocsMcpSessionCtx,
+ renderHtmlToPdf: RenderHtmlToPdfFn,
+ writeDocsOutput: WriteDocsOutputFn,
+): void {
+ registry.register({
+ name: 'render_pdf',
+ category: 'convert',
+ description: DESCRIPTION,
+ inputShape: {
+ htmlPath: z.string().optional().describe('工作目录内的 .html 文件路径。与 html 二选一。'),
+ html: z
+ .string()
+ .optional()
+ .describe(
+ '内联 HTML 源码。与 htmlPath 二选一。相对图片/字体/样式以任务工作目录为基准快照;file:// 与工作目录外路径会被拒绝。',
+ ),
+ outPath: z.string().min(1).describe('输出 .pdf 路径,工作目录内的相对路径或绝对路径。'),
+ pageSize: z
+ .enum(PAGE_SIZES as unknown as [DocsPdfPageSize, ...DocsPdfPageSize[]])
+ .default('A4')
+ .describe('纸张尺寸,默认 A4。'),
+ landscape: z.boolean().default(false).describe('是否横向。默认纵向。'),
+ printBackground: z.boolean().default(true).describe('是否打印背景色与背景图。默认 true。'),
+ margins: z
+ .object({
+ top: z.number().min(0).max(5).default(DEFAULT_MARGIN_INCHES),
+ bottom: z.number().min(0).max(5).default(DEFAULT_MARGIN_INCHES),
+ left: z.number().min(0).max(5).default(DEFAULT_MARGIN_INCHES),
+ right: z.number().min(0).max(5).default(DEFAULT_MARGIN_INCHES),
+ })
+ .optional()
+ .describe('页边距(英寸)。不传时四边都是 0.4。'),
+ template: z
+ .enum(['auto', 'report', 'none'])
+ .default('auto')
+ .describe('auto=无样式时套内置报告模板;report=同样只套无样式 HTML;none=不套。'),
+ theme: z
+ .enum(['light', 'dark', 'navy'])
+ .default('light')
+ .describe('自动套模板时使用的色板。已有样式的 HTML 不受影响。'),
+ overwrite: z.boolean().default(false).describe('目标文件已存在时是否覆盖。默认 false。'),
+ },
+ handler: async ({
+ htmlPath,
+ html,
+ outPath,
+ pageSize,
+ landscape,
+ printBackground,
+ margins,
+ template,
+ theme,
+ overwrite,
+ }) => {
+ const hasPath = typeof htmlPath === 'string' && htmlPath.length > 0;
+ const hasInline = typeof html === 'string' && html.length > 0;
+ if (hasPath === hasInline) {
+ return errorPayload(
+ 'INVALID_ARGS',
+ hasPath
+ ? 'htmlPath 和 html 只能给一个:要么指一个已有的 HTML 文件,要么直接给源码。'
+ : '必须给 htmlPath(已有的 HTML 文件)或 html(内联源码)之一。',
+ { gotHtmlPath: hasPath, gotHtml: hasInline },
+ );
+ }
+
+ try {
+ const root = resolveSessionRoot(sessionCtx);
+ assertOutputExtension(outPath, '.pdf');
+ const abs = await prepareOutputPath(root, outPath, overwrite);
+ const sourcePath = hasPath ? await prepareInputPath(root, htmlPath!) : undefined;
+ const sourceDirectory = sourcePath
+ ? await captureDirectorySnapshot(path.dirname(sourcePath))
+ : undefined;
+ const initialDirectorySnapshots = sourceDirectory
+ ? new Map([[path.resolve(path.dirname(sourcePath!)), sourceDirectory]])
+ : undefined;
+ // Capture the source's canonical relative location before reading. Keep the
+ // lexical root prefix (macOS commonly exposes /var as /private/var through
+ // realpath) so later resource boundary checks use the same root spelling.
+ // The bounded reader below verifies the source identity and root again; using
+ // this stable relative location prevents a parent-path rebind from changing
+ // the resource base between the HTML snapshot and inlining.
+ const sourceSnapshotPath = sourcePath
+ ? await (async () => {
+ const [realRoot, realSource] = await Promise.all([
+ fs.realpath(root),
+ fs.realpath(sourcePath),
+ ]);
+ const relative = path.relative(realRoot, realSource);
+ if (relative.startsWith('..') || path.isAbsolute(relative)) {
+ throw new DocsPathError(
+ 'PATH_NOT_ALLOWED',
+ `输入文件不在任务工作目录内: ${sourcePath}`,
+ '请把 HTML 文件放在当前任务工作目录内后重试。',
+ );
+ }
+ return path.join(root, relative);
+ })()
+ : undefined;
+ const sourceBytes = sourcePath
+ ? await readInputFileWithinLimit(
+ root,
+ sourcePath,
+ RENDER_PDF_MAX_HTML_BYTES,
+ (bytes) =>
+ new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `HTML 过大: ${bytes} 字节`,
+ `这份 HTML 有 ${(bytes / 1024 / 1024).toFixed(1)} MB,超出 PDF 渲染上限(16 MB)。请压缩内联图片/字体或拆分文档后重试。`,
+ ),
+ )
+ : undefined;
+ const sourceHtml = sourceBytes ? decodeUnicodeText(sourceBytes, 'HTML') : html!;
+ if (!sourcePath) {
+ const inlineBytes = Buffer.byteLength(sourceHtml, 'utf8');
+ if (inlineBytes > RENDER_PDF_MAX_HTML_BYTES) {
+ throw new DocsPathError(
+ 'FILE_TOO_LARGE',
+ `HTML 过大: ${inlineBytes} 字节`,
+ `这份 HTML 有 ${(inlineBytes / 1024 / 1024).toFixed(1)} MB,超出 PDF 渲染上限(16 MB)。请压缩内联图片/字体或拆分文档后重试。`,
+ );
+ }
+ }
+ const snapshotHtml = await inlineLocalResources(
+ root,
+ sourceSnapshotPath ?? sourcePath ?? path.join(root, '__cindy_inline__.html'),
+ sourceHtml,
+ sourceDirectory,
+ initialDirectorySnapshots,
+ );
+ const palette = resolveDocsTheme((theme ?? DEFAULT_DOCS_THEME) as DocsThemeName);
+ const wrapped = applyReportTemplate(snapshotHtml, palette, template);
+ const userSetMargins = margins !== undefined;
+ const effectiveMargins = userSetMargins
+ ? {
+ top: margins.top ?? DEFAULT_MARGIN_INCHES,
+ bottom: margins.bottom ?? DEFAULT_MARGIN_INCHES,
+ left: margins.left ?? DEFAULT_MARGIN_INCHES,
+ right: margins.right ?? DEFAULT_MARGIN_INCHES,
+ }
+ : wrapped.applied
+ ? { top: 0, bottom: 0, left: 0, right: 0 }
+ : {
+ top: DEFAULT_MARGIN_INCHES,
+ bottom: DEFAULT_MARGIN_INCHES,
+ left: DEFAULT_MARGIN_INCHES,
+ right: DEFAULT_MARGIN_INCHES,
+ };
+
+ const renderInput = sourcePath
+ ? {
+ // The host must consume the exact bytes already checked above.
+ // Local task resources have already been converted to data:
+ // snapshots, so the host never needs to reopen the caller's directory.
+ htmlBytes: Buffer.from(wrapped.html, 'utf8'),
+ }
+ : { html: wrapped.html };
+ const { buffer, fontsReady } = await renderHtmlToPdf({
+ ...renderInput,
+ pageSize,
+ landscape,
+ printBackground,
+ margins: effectiveMargins,
+ timeoutMs: RENDER_PDF_TIMEOUT_MS,
+ fontTimeoutMs: RENDER_PDF_FONT_TIMEOUT_MS,
+ });
+
+ if (!buffer || buffer.length === 0) {
+ return errorPayload(
+ 'RENDER_EMPTY',
+ '渲染出来是空的 PDF。请检查 HTML 里是否真有可见内容(常见原因:整页被 CSS 隐藏、外部样式没加载到)。',
+ {},
+ );
+ }
+ await writeDocsOutput({ root, path: abs, data: buffer, overwrite });
+
+ const described = describeOutput(root, abs, buffer.byteLength);
+ const warnings: string[] = [];
+ if (described.bytes < SUSPICIOUS_PDF_BYTES) {
+ warnings.push(
+ 'PDF 字节数异常小,很可能渲染成了白页。用 inspect_pdf 回读确认,必要时检查 HTML 与外部资源后重做,不要直接交付。',
+ );
+ }
+ if (!fontsReady) {
+ warnings.push(
+ '等字体加载超时,PDF 里的字体可能已被换成系统默认字体。若排版对字体有要求,请把字体 base64 内联进 HTML 后重做。',
+ );
+ }
+ return okPayload({
+ ...described,
+ format: 'pdf',
+ pageSize,
+ landscape,
+ fontsReady,
+ template,
+ theme,
+ templateApplied: wrapped.applied,
+ nextStep: '用 inspect_pdf 回读这份 PDF,确认页数、纸张与是否有空白页,再交付。',
+ artifact: artifactMetadata({
+ format: 'pdf',
+ title: extractHtmlTitle(snapshotHtml),
+ theme,
+ summary: { kind: 'bytes', value: buffer.byteLength },
+ }),
+ ...(warnings.length > 0 ? { warning: warnings.join(' ') } : {}),
+ });
+ } catch (err) {
+ if (err instanceof DocsPathError) {
+ return errorPayload(err.code, err.hint, { message: err.message });
+ }
+ const message = err instanceof Error ? err.message : String(err);
+ const timedOut = /timeout|超时/i.test(message);
+ return errorPayload(
+ timedOut ? 'RENDER_TIMEOUT' : 'RENDER_FAILED',
+ timedOut
+ ? `渲染超过 ${RENDER_PDF_TIMEOUT_MS / 1000} 秒被中止。常见原因是 HTML 在等一个加载不出来的外部资源;把外部图片/字体改成内联或本地文件后重试。`
+ : `渲染 PDF 失败:${message}`,
+ { message },
+ );
+ }
+ },
+ });
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/themes.ts b/packages/lizi-mcps/src/cindy-docs/themes.ts
new file mode 100644
index 0000000000..73ce4262df
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/themes.ts
@@ -0,0 +1,100 @@
+/**
+ * cindy-docs/themes.ts —— 文档工具共用的克制色板。
+ *
+ * 主题是纯配置(色号 + 语义角色),不捆图片、不捆字体。模型只能从命名色板里选,
+ * 不能自由喂色号 —— 自由配色几乎必然对比度翻车。三个命名色板覆盖浅底打印、
+ * 深色投影、正式商务汇报;再加色板只加数据,不要改调用方。
+ */
+
+export const DOCS_THEME_NAMES = ['light', 'dark', 'navy'] as const;
+export type DocsThemeName = (typeof DOCS_THEME_NAMES)[number];
+export const DEFAULT_DOCS_THEME: DocsThemeName = 'light';
+
+/** 色板字段一律 6 位十六进制、不带 #,三套出口(pptx / docx / xlsx / pdf CSS)自己加前缀。 */
+export interface DocsTheme {
+ /** 页/幻灯片底色。 */
+ background: string;
+ /** 卡片、表头浅底、引用底。 */
+ surface: string;
+ /**
+ * 斑马纹底色。
+ *
+ * 必须和 `background` 拉开肉眼可辨的差(约 4–6%)。原来只差 2%,实机目检下来
+ * 整张表看不出隔行 —— 打了跟没打一样,而它存在的唯一目的就是让眼睛横着扫
+ * 一行不串到下一行。
+ */
+ zebra: string;
+ /** 主标题、H1。 */
+ title: string;
+ /** 正文。 */
+ body: string;
+ /** 唯一强调色:分隔线、表头色带、封面竖条。 */
+ accent: string;
+ /** 强调色上的字(表头文字)。 */
+ accentOn: string;
+ /** 次要文字、页脚、题注。 */
+ muted: string;
+ /** 浅线、表格描边。 */
+ line: string;
+}
+
+export const DOCS_THEMES: Record<DocsThemeName, DocsTheme> = {
+ light: {
+ background: 'FFFFFF',
+ surface: 'F2F3F5',
+ zebra: 'F0F2F6',
+ title: '1B1F24',
+ body: '2E3440',
+ accent: '2F6FEB',
+ accentOn: 'FFFFFF',
+ muted: '6B7280',
+ line: 'D8DCE2',
+ },
+ dark: {
+ background: '14181D',
+ surface: '1E242C',
+ zebra: '1D242D',
+ title: 'F5F7FA',
+ body: 'D6DBE3',
+ accent: '6AA6FF',
+ accentOn: '0B1220',
+ muted: '9AA3B0',
+ line: '2C3440',
+ },
+ navy: {
+ background: 'FFFFFF',
+ surface: 'EEF2F7',
+ zebra: 'EDF2F8',
+ title: '0F2744',
+ body: '243040',
+ accent: '1F4E79',
+ accentOn: 'FFFFFF',
+ muted: '5C6470',
+ line: 'D8DCE2',
+ },
+};
+
+export function resolveDocsTheme(name: DocsThemeName | undefined): DocsTheme {
+ return DOCS_THEMES[name ?? DEFAULT_DOCS_THEME];
+}
+
+/** exceljs 要 ARGB;入参可以是 6 位或已经带 alpha 的 8 位。 */
+export function themeToArgb(hex: string): string {
+ const clean = hex.replace('#', '').toUpperCase();
+ if (clean.length === 8) return clean;
+ return `FF${clean}`;
+}
+
+/** CSS / HTML 要 #RRGGBB。 */
+export function themeToCssHex(hex: string): string {
+ const clean = hex.replace('#', '');
+ return `#${clean}`;
+}
+
+/** 本地日历日,不用 toISOString(UTC 会在东八区深夜错一天)。 */
+export function formatDocsDate(date: Date = new Date()): string {
+ const y = date.getFullYear();
+ const m = String(date.getMonth() + 1).padStart(2, '0');
+ const d = String(date.getDate()).padStart(2, '0');
+ return `${y}-${m}-${d}`;
+}
diff --git a/packages/lizi-mcps/src/cindy-docs/types.ts b/packages/lizi-mcps/src/cindy-docs/types.ts
new file mode 100644
index 0000000000..71527ed551
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy-docs/types.ts
@@ -0,0 +1,139 @@
+/**
+ * cindy-docs/types.ts —— cindy_docs 的 host 依赖契约。
+ *
+ * 分层理由(写清以免后人误改):
+ * - docx / pptxgenjs / exceljs / marked 都是纯 JS,没有原生绑定、不碰 Electron,
+ * 与本包已有的 sharp / googleapis / ssh 客户端同级,直接在 @cindy/mcps 内实现,
+ * 不需要绕一层 host 注入。
+ * - host 注入两类 Electron 边界能力:HTML → PDF 靠 Chromium `printToPDF`;
+ * 最终落盘靠绑定到已验证目录身份的一次性 utility process。本包铁律是不
+ * import electron(否则 package 无法在非 Electron 宿主复用,也会污染依赖方向),
+ * 所以这两个函数都由 desktop main 在 mcp-providers.ts 闭包注入。
+ */
+
+import type { LiziMcpLogger, LiziMcpSessionContext } from '../types.js';
+
+/** render_pdf 支持的纸张。与 Electron printToPDF 的 pageSize 取值对齐。 */
+export type DocsPdfPageSize = 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid';
+
+/** 页边距,单位英寸(Electron printToPDF 的 margins 就用英寸)。 */
+export interface DocsPdfMargins {
+ top: number;
+ bottom: number;
+ left: number;
+ right: number;
+}
+
+/**
+ * host 渲染回调的入参。工具层把已验证的 HTML 内容以 `htmlBytes` 或 `html` 传入:
+ * - htmlBytes 来自工作目录内已打开句柄的受限读取,host 不得按原路径重新打开;
+ * - html 是内联源码,由 host 落到自己的临时目录再加载(临时文件生命周期归 host,
+ * 见 docs/dev-rules/credentials-and-local-storage.md:可丢弃临时数据放
+ * app.getPath('temp') / os.tmpdir() 下的任务专属目录)。
+ */
+export interface DocsPdfRenderInput {
+ htmlBytes?: Uint8Array;
+ html?: string;
+ pageSize: DocsPdfPageSize;
+ landscape: boolean;
+ printBackground: boolean;
+ margins: DocsPdfMargins;
+ /** 单次渲染的硬超时(含建窗、加载、字体等待与 printToPDF)。 */
+ timeoutMs: number;
+ /**
+ * 等 webfont 就绪的子超时。Chromium **不会**自己等 @font-face 加载完再打印,
+ * 字体没就位就静默回退到系统字体 —— 这是「我指定的字体没生效」的头号成因。
+ * 超过这个时间就照常渲染,并在结果里把 fontsReady 置 false 告警,不拖满总超时。
+ */
+ fontTimeoutMs: number;
+}
+
+/** 渲染结果:PDF 字节 + 字体是否在打印前真的就绪。 */
+export interface DocsPdfRenderOutput {
+ buffer: Buffer;
+ /**
+ * false = 等 document.fonts.ready 超时或探测失败,这份 PDF 里的字体可能被
+ * Chromium 换成了系统默认字体。工具层据此给出可执行的告警。
+ */
+ fontsReady: boolean;
+}
+
+/**
+ * HTML → PDF 渲染回调。失败必须 throw(工具层统一翻成 RENDER_FAILED /
+ * RENDER_TIMEOUT)。host 侧实现见
+ * apps/desktop/src/main/doc-tools/htmlPdfRenderer.ts。
+ */
+export type RenderHtmlToPdfFn = (input: DocsPdfRenderInput) => Promise<DocsPdfRenderOutput>;
+
+/**
+ * Host-owned output commit. Desktop binds the final file operation to a
+ * previously verified parent-directory identity in a one-shot utility process.
+ */
+export type WriteDocsOutputFn = (input: {
+ root: string;
+ path: string;
+ data: Uint8Array;
+ overwrite: boolean;
+}) => Promise<void>;
+
+/** 单页结构快照。宽高单位是 PDF point(1/72 英寸)。 */
+export interface DocsPdfPageInspection {
+ page: number;
+ width: number;
+ height: number;
+ rotation: number;
+ textChars: number;
+ textPreview: string;
+ /** null = 算子表读取失败,不参与空白判定。 */
+ drawOps: number | null;
+ imageOps: number | null;
+ blank: boolean;
+ /** 结构存在但未做位图级可见性验证。 */
+ visibilityUnverified: boolean;
+}
+
+export interface DocsPdfInspection {
+ numPages: number;
+ pagesInspected: number;
+ pages: DocsPdfPageInspection[];
+}
+
+/**
+ * 读 PDF 结构的 host 回调。与 renderHtmlToPdf 同理由外置:桌面宿主把 pdfjs 放在
+ * 一次性 utility process 里跑(正式包关闭 RunAsNode,且解析不可信 PDF 不该在
+ * Electron main 里进行),那条链路依赖 electron.utilityProcess,本包不能碰。
+ */
+export type InspectPdfFn = (input: {
+ data: Uint8Array;
+ /** 1 起的页码;空数组 = 从头顺序取 maxPages 页。 */
+ pages: number[];
+ maxPages: number;
+ previewChars: number;
+ timeoutMs: number;
+}) => Promise<DocsPdfInspection>;
+
+/**
+ * cindy_docs MCP server 工厂参数。
+ *
+ * writeDocsOutput / renderHtmlToPdf / inspectPdf 缺省 = host 没接对应能力→
+ * 对应工具不注册,与 memory 的 session_search / contacts 的系统通讯录同模式:
+ * 能力不具备就不注册该顶层工具,而不是注册了再运行期报错。
+ */
+export interface DocsMcpDeps {
+ /** Required for authoring tools; hosts must provide an identity-bound writer. */
+ writeDocsOutput?: WriteDocsOutputFn;
+ renderHtmlToPdf?: RenderHtmlToPdfFn;
+ inspectPdf?: InspectPdfFn;
+ logger?: LiziMcpLogger;
+}
+
+/**
+ * Per-session ctx 绑定参数。与 XdtHelperMcpSessionCtx 同构:Claude in-process
+ * 路径在 toClaudeSdkConfig(ctx) 时闭包绑定;Codex / Pi 的 HTTP bridge 在
+ * tool-call 阶段由 getSessionContext 恢复。所有文件路径都以解析出来的
+ * workingDir 为根,解析不出来就 fail closed(见 _paths.ts)。
+ */
+export interface DocsMcpSessionCtx extends LiziMcpSessionContext {
+ agentKind: 'claude-code' | 'codex' | 'pi';
+ workingDir: string;
+}
diff --git a/packages/lizi-mcps/src/cindy_docsMcpServer.ts b/packages/lizi-mcps/src/cindy_docsMcpServer.ts
new file mode 100644
index 0000000000..69a2292fa7
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy_docsMcpServer.ts
@@ -0,0 +1,216 @@
+/**
+ * cindy_docsMcpServer.ts
+ * ---------------------------------------------------------------------------
+ * In-process MCP server:文档工坊(cindy_docs)。把「说人话要一份 PDF/Word/Excel/PPT」
+ * 变成真文件的一组格式原语。
+ *
+ * 设计:
+ * - server name = `cindy_docs`,对应 Cindy 内部可开关的 built-in provider id 'docs'。
+ * 这里的 id 只是宿主能力开关,不是需要用户安装的外置 `.cindy` 文档插件;不做文档的
+ * 用户仍可关闭它,省下入口工具的那点上下文。
+ * - **六个工具全部顶层直接注册**,不做渐进式发现(2026-08-21 真机实证后改回):
+ * 伙伴会话里 cindy_docs 挂载成功、日志 instance_resolved,但 make_pptx 与
+ * list_tools 的调用次数都是 0 —— 模型看见的只是一个泛泛的 `list_tools` 入口,
+ * 没有把「做个 PPT」和它联系起来,转头去找 python 库、没找到、回了句做不了。
+ * 渐进披露适合 cindy_helper 那种几十个工具的大工具面;六个名字自解释的文档
+ * 工具藏在二级分派后面,省下的上下文远不抵「能力等于不存在」的代价。
+ * - 三个类目(仍保留在 registry 里,供工具描述与测试分组用):
+ * - 'author' : make_docx / make_pptx / make_xlsx —— 从结构化内容直接出 Office 文件
+ * - 'convert' : render_pdf —— 出 PDF
+ * - 'read' : read_sheet / inspect_pdf —— 读已有表格 / 回读 PDF 做产出自检
+ *
+ * 边界:
+ * - 本包不 import electron(既有铁律)。render_pdf 靠 Chromium printToPDF,渲染函数
+ * 由 desktop main 经 deps.renderHtmlToPdf 注入;host 没注入就不注册该工具。
+ * - 生成/读取工具依赖的 docx / pptxgenjs / exceljs / marked 都是纯 JS,与本包已有的
+ * sharp / googleapis 同级,直接在包内实现,不再绕一层注入。
+ * - inspect_pdf 同样走 host 注入:桌面宿主把 pdfjs 放在一次性 utility process 里跑
+ * (正式包关闭 RunAsNode,解析不可信 PDF 也不该在 Electron main 内进行)。
+ * - **零系统依赖**:全部能力都不要求用户预先安装 LibreOffice / Office 或任何外部程序。
+ * - 所有文件路径钳制在当前 tool-call 解析出来的会话 workingDir 内(见 cindy-docs/_paths.ts)。
+ */
+
+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
+import { z } from 'zod';
+
+import { DocsToolRegistry } from './cindy_docsToolRegistry.js';
+import {
+ registerInspectPdfTool,
+ registerMakeDocxTool,
+ registerMakePptxTool,
+ registerMakeXlsxTool,
+ registerReadSheetTool,
+ registerRenderPdfTool,
+} from './cindy-docs/index.js';
+import type { DocsMcpDeps, DocsMcpSessionCtx } from './cindy-docs/types.js';
+import { resolveLiziMcpSessionContext } from './session-context.js';
+import { logToolResultErrorCode } from './tool-error-telemetry.js';
+import type { LiziMcpLogger } from './types.js';
+
+/**
+ * 每个工具描述末尾都带的共同约束。顶层暴露后没有 call_tool 那段总说明可挂,
+ * 这些错误码与纪律必须跟着每个工具走 —— 模型不会为了看约束去调另一个工具。
+ */
+const D_COMMON_TAIL =
+ ' 全部能力零系统依赖,不需要用户预先装 LibreOffice / Office 或任何外部程序。' +
+ '所有输入输出路径必须在当前任务的工作目录内(建议放 documents/,文件名用「日期-主题」)。' +
+ '错误码:`PATH_NOT_ALLOWED` 路径越界;`FILE_EXISTS` 目标已存在(确认覆盖再加 overwrite:true);' +
+ '`ATOMIC_PUBLISH_UNSUPPORTED` 当前输出位置无法安全地原子防覆盖发布;' +
+ '`NOT_A_FILE` 输入找不到;`NO_SESSION_CONTEXT` 本次调用没绑定工作目录。';
+
+/**
+ * 「先定版式再产出」——所有格式共用的那句总纲。
+ *
+ * 挂在**工具描述**上而不是只写进某类会话的提示词:模型选工具时一定会读到它,
+ * 伙伴会话、普通会话、三种 harness 全覆盖,不依赖任何 skill 是否安装。实测确认
+ * 描述原文会一字不差进模型上下文。
+ *
+ * 定完版式之后怎么落地,**取决于目标格式能接住多少设计**,所以下面分三种:
+ * - `make_pptx` → 走 HTML 设计稿:逐页版式选择与内容切分能整块迁移过去;
+ * - `render_pdf` → HTML 就是版式本身,一次写到位;
+ * - `make_docx` → 不走设计稿:它只收 markdown + 三选一主题,版式全由内置样式排,
+ * 设计稿没有落点(见 D_DESIGN_DOCX 的说明);
+ * - `make_xlsx` → 不适用:表格好不好看取决于列宽、表头、数字格式。
+ */
+const D_DESIGN_CORE =
+ ' 【动手前先定版式】选定一套字号层级、一组配色、统一的留白与对齐,把真实内容填进去' +
+ '看层级立不立得住,再开始产出。跳过这一步就是「纯白一片只有字」的来源。';
+
+/** PPT / Word:HTML 只是自己的设计草稿,成品必须由结构化工具还原。 */
+const D_DESIGN_VIA_HTML =
+ D_DESIGN_CORE +
+ '**调本工具之前必须先做这一步,不是可选项**:在 `tmp/` 写一份自包含 HTML 设计稿' +
+ '(样式内联)把版式落定,把真实内容填进去逐屏/逐页看一遍,再对着它还原成本工具的' +
+ '结构化参数 —— 每一页/每一节用哪种版式、标题与正文的层级关系、表格怎么分栏、' +
+ '哪里该留白,都在设计稿里定完再动手。' +
+ '**这是你自己的工序,用户看不到也不该看到** —— 不要把设计稿发给他、不要问他' +
+ '「要不要先看草稿」、不要把 `tmp/` 路径念给他听,他只收 `documents/` 里的成品。' +
+ '设计稿只用来定版式,不要试图把 HTML 整份转成目标格式。';
+
+/** PDF:HTML 本身就是版式,不需要额外的草稿环节。 */
+const D_DESIGN_PDF =
+ D_DESIGN_CORE + 'PDF 的 HTML 就是版式本身,按目标纸张(A4 / Letter)一次写到位再渲染。';
+
+/**
+ * Word:**不走 HTML 设计稿**,因为没有可迁移的落点。
+ *
+ * 这不是偷懒省事,是实测确认的事实:`make_docx` 只收 markdown / title /
+ * subtitle / cover / theme,版式全由工具内部样式决定 —— 字号层级、留白、对齐
+ * 一个都传不进来。硬要求先写 HTML 只会白烧一轮 token,模型也会当场指出这条
+ * 要求与工具接口矛盾然后跳过(2026-08-21 真机复现,它把理由讲得很清楚)。
+ *
+ * 所以这里给的是**对得上它真实旋钮**的设计要求:结构、层级、表格、主题、封面。
+ */
+const D_DESIGN_DOCX =
+ D_DESIGN_CORE +
+ 'Word 的版式由本工具的内置样式排,不需要另写 HTML 设计稿 —— 设计功夫花在能传进来的地方:' +
+ 'markdown 的标题层级要真的分出主次(不要通篇二级标题)、长段落切分、该用表格的地方用表格而不是罗列、' +
+ '按内容气质选 theme(正式选 navy、日常选 light)、正式文档给 title + subtitle 出封面。';
+
+/**
+ * 顶层工具的对外描述。registry 里那份 description 讲的是参数细节,这里讲的是
+ * **什么时候该调它** —— 顶层描述是模型唯一的选型依据,必须自解释。
+ */
+const TOP_LEVEL_DESCRIPTIONS: Record<string, string> = {
+ make_pptx:
+ '做 PPT 演示文稿(.pptx)。用户说「做个 PPT / 幻灯片 / 汇报稿 / slides / deck」时用这个,' +
+ '传 slides 数组直接出真文件,自带封面/分节/内容三套版式与配色主题。' +
+ '不要去找 python-pptx 之类的外部库,也不要只给文字大纲。' +
+ D_DESIGN_VIA_HTML,
+ make_docx:
+ '做 Word 文档(.docx)。用户说「做个 Word / 文档 / 报告 / 说明书」且需要对方可编辑时用这个,' +
+ '内容整理成 Markdown 传进来,标题层级、表格、封面会自动排好。' +
+ D_DESIGN_DOCX,
+ make_xlsx:
+ '做 Excel 表格(.xlsx)。用户说「做个表 / 表格 / Excel / 统计表」时用这个,传 sheets + rows,' +
+ '表头加粗冻结与数字格式自动处理;写公式要连缓存值一起给,否则很多阅读器打开是空白。',
+ render_pdf:
+ '出 PDF。用户要「PDF / 正式文档 / 可打印的东西」时用这个:先写一份自包含 HTML(内联样式)' +
+ '把版式定下来,再用它渲染成 PDF。宿主用内置 Chromium 排版,不需要任何外部工具。' +
+ D_DESIGN_PDF,
+ read_sheet:
+ '读已有表格(xlsx / csv / tsv)。用户丢来一个表要你分析、汇总、回答其中数据时用这个,' +
+ '别让用户手工把内容贴进对话。也用于生成表格后回读核对。',
+ inspect_pdf:
+ '回读 PDF 做产出自检:页数、纸型、旋转、每页文字量与是否空白。' +
+ '**出完 PDF 交付前一定要调它一次** —— 整页空白的 PDF 字节数看着完全正常,' +
+ '只看文件大小判断不出来,blankPages / verdict 才是确定性证据。',
+};
+
+/**
+ * 把 registry 里的工具逐个注册成顶层 MCP 工具。参数 schema 直接复用 registry
+ * 的 inputShape(单一事实源),执行仍走 registry.call 以保留 strict 校验、
+ * 统一错误码与 telemetry。
+ */
+function registerTopLevelTools(
+ server: McpServer,
+ registry: DocsToolRegistry,
+ telemetry: { logger?: LiziMcpLogger; getSessionId: () => string | undefined },
+): void {
+ for (const summary of registry.list()) {
+ const def = registry.get(summary.name);
+ if (!def) continue;
+ const description = `${TOP_LEVEL_DESCRIPTIONS[def.name] ?? def.description}${D_COMMON_TAIL}`;
+ server.registerTool(
+ def.name,
+ {
+ description,
+ // **strict()**:拼错的字段必须报错,不能被静默剥掉。用 server.tool(rawShape)
+ // 时 SDK 会按非严格对象解析,`tittle` 这种笔误会被悄悄丢掉、生成一份没有
+ // 标题的文档 —— 用户要打开才发现。registerTool 收完整 schema,所以这里
+ // 显式收严,与 registry.call 内部的 strict 口径保持一致。
+ inputSchema: z.object(def.inputShape).strict(),
+ },
+ async (args: Record<string, unknown>) => {
+ const result = await registry.call(def.name, args);
+ logToolResultErrorCode({
+ logger: telemetry.logger,
+ server: 'cindy_docs',
+ tool: def.name,
+ result,
+ sessionId: telemetry.getSessionId(),
+ });
+ return result;
+ },
+ );
+ }
+}
+
+export function createCindyDocsMcpServer(
+ deps: DocsMcpDeps,
+ sessionCtx: DocsMcpSessionCtx,
+): McpServer {
+ const server = new McpServer({ name: 'cindy_docs', version: '1.0.0' });
+ const registry = new DocsToolRegistry();
+
+ if (deps.writeDocsOutput) {
+ registerMakeDocxTool(registry, sessionCtx, deps.writeDocsOutput);
+ registerMakePptxTool(registry, sessionCtx, deps.writeDocsOutput);
+ registerMakeXlsxTool(registry, sessionCtx, deps.writeDocsOutput);
+ }
+ registerReadSheetTool(registry, sessionCtx);
+ // 生成工具、render_pdf / inspect_pdf 只在 host 提供对应边界回调时注册 ——
+ // 没有能力的宿主里让模型看不到它们,好过看见了调用再拿到一个「不可用」。
+ if (deps.renderHtmlToPdf && deps.writeDocsOutput) {
+ registerRenderPdfTool(
+ registry,
+ sessionCtx,
+ deps.renderHtmlToPdf,
+ deps.writeDocsOutput,
+ );
+ }
+ if (deps.inspectPdf) {
+ registerInspectPdfTool(registry, sessionCtx, deps.inspectPdf);
+ }
+
+ registerTopLevelTools(server, registry, {
+ ...(deps.logger ? { logger: deps.logger } : {}),
+ // per-call 解析:Codex / Pi 的 HTTP bridge 在 server factory 阶段 ctx 是空的,
+ // tool-call 阶段才由 AsyncLocalStorage 恢复。
+ getSessionId: () => resolveLiziMcpSessionContext(sessionCtx).sessionId,
+ });
+
+ return server;
+}
+
+export type { DocsMcpDeps, DocsMcpSessionCtx } from './cindy-docs/types.js';
diff --git a/packages/lizi-mcps/src/cindy_docsToolRegistry.ts b/packages/lizi-mcps/src/cindy_docsToolRegistry.ts
new file mode 100644
index 0000000000..82ae5e526e
--- /dev/null
+++ b/packages/lizi-mcps/src/cindy_docsToolRegistry.ts
@@ -0,0 +1,142 @@
+/**
+ * cindy_docsToolRegistry.ts
+ * ---------------------------------------------------------------------------
+ * 与 XdtHelperToolRegistry / SchedulerToolRegistry 同构:cindy_docs 的细粒度工具
+ * 注册在这里,而不是直接挂到 McpServer 上。MCP server 会把注册结果投影成六个
+ * 顶层文档工具;registry 只负责统一 schema 校验、错误格式和 handler 分派。
+ *
+ * Category 分三类:
+ * - 'author' : 从结构化输入直接生成 Office 文件 (make_docx / make_pptx / make_xlsx)
+ * - 'convert' : 把已有内容转成 PDF (render_pdf)
+ * - 'read' : 只读解析已有表格文件 (read_sheet)
+ *
+ * 拆成三类而不是一锅端,是因为模型的意图天然分这三种:「我有内容要出文件」、
+ * 「我有文件要转格式」、「我要读表格里的数」。工具描述直接进入模型上下文,
+ * 因此每个工具的 description 必须把选型与排版工序说完整。
+ */
+
+import { z } from 'zod';
+
+export type DocsToolCategory = 'author' | 'convert' | 'read';
+
+export type DocsToolContentBlock = { type: 'text'; text: string };
+
+export interface DocsToolResult {
+ content: DocsToolContentBlock[];
+ isError?: boolean;
+ [k: string]: unknown;
+}
+
+export type DocsToolHandler<T = Record<string, unknown>> = (
+ args: T,
+) => Promise<DocsToolResult>;
+
+export interface DocsToolDef {
+ name: string;
+ category: DocsToolCategory;
+ description: string;
+ inputShape: z.ZodRawShape;
+ handler: DocsToolHandler;
+}
+
+export interface DocsToolSummary {
+ name: string;
+ category: DocsToolCategory;
+ description: string;
+}
+
+export class DocsToolRegistry {
+ private readonly tools = new Map<string, DocsToolDef>();
+
+ register<T extends z.ZodRawShape>(def: {
+ name: string;
+ category: DocsToolCategory;
+ description: string;
+ inputShape: T;
+ handler: DocsToolHandler<{ [K in keyof T]: z.infer<T[K]> }>;
+ }): void {
+ if (this.tools.has(def.name)) {
+ throw new Error(`[cindyDocsToolRegistry] duplicate tool name: ${def.name}`);
+ }
+ this.tools.set(def.name, def as unknown as DocsToolDef);
+ }
+
+ has(name: string): boolean {
+ return this.tools.has(name);
+ }
+
+ get(name: string): DocsToolDef | undefined {
+ return this.tools.get(name);
+ }
+
+ list(category?: DocsToolCategory): DocsToolSummary[] {
+ const all: DocsToolSummary[] = [];
+ for (const t of this.tools.values()) {
+ if (category && t.category !== category) continue;
+ all.push({ name: t.name, category: t.category, description: t.description });
+ }
+ return all;
+ }
+
+ listCategories(): DocsToolCategory[] {
+ const set = new Set<DocsToolCategory>();
+ for (const t of this.tools.values()) set.add(t.category);
+ return Array.from(set);
+ }
+
+ async call(name: string, rawArgs: unknown): Promise<DocsToolResult> {
+ const def = this.tools.get(name);
+ if (!def) {
+ return {
+ content: [
+ {
+ type: 'text',
+ text: JSON.stringify({
+ ok: false,
+ errorCode: 'UNKNOWN_TOOL',
+ data: {
+ requested: name,
+ available: Array.from(this.tools.keys()),
+ hint: '请确认工具名称和参数 schema 后重试',
+ },
+ }),
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ // strict:未知字段直接判失败(而非默默剥掉)。与 xdt-helper registry 同口径——
+ // 拼错字段若被静默忽略,模型会以为参数生效了,实际出来的文件跟它想的不一样。
+ const objSchema = z.strictObject(def.inputShape);
+ const parsed = objSchema.safeParse(rawArgs ?? {});
+ if (!parsed.success) {
+ let jsonSchema: unknown;
+ try {
+ jsonSchema = z.toJSONSchema(objSchema);
+ } catch {
+ jsonSchema = '<schema serialization failed>';
+ }
+ return {
+ content: [
+ {
+ type: 'text',
+ text: JSON.stringify({
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ data: {
+ tool: name,
+ validation_errors: parsed.error.issues,
+ schema: jsonSchema,
+ hint: '请按 schema 修正参数后重试',
+ },
+ }),
+ },
+ ],
+ isError: true,
+ };
+ }
+
+ return def.handler(parsed.data as Record<string, unknown>);
+ }
+}
diff --git a/packages/lizi-mcps/src/index.ts b/packages/lizi-mcps/src/index.ts
index e5d5e4ee70..9aa2074142 100644
--- a/packages/lizi-mcps/src/index.ts
+++ b/packages/lizi-mcps/src/index.ts
@@ -32,6 +32,10 @@ export * from './lizi_xdtHelperMcpServer.js';
export * from './lizi_xdtHelperToolRegistry.js';
export * from './xdt-helper/index.js';
+export { createCindyDocsMcpServer } from './cindy_docsMcpServer.js';
+export * from './cindy_docsToolRegistry.js';
+export * from './cindy-docs/index.js';
+
export * from './orca/index.js';
export * from './session-context.js';
diff --git a/packages/lizi-mcps/src/providers.ts b/packages/lizi-mcps/src/providers.ts
index e07a38d760..10d42877f6 100644
--- a/packages/lizi-mcps/src/providers.ts
+++ b/packages/lizi-mcps/src/providers.ts
@@ -23,6 +23,8 @@ import { createSshMcpServer } from './cindy_sshMcpServer.js';
import { createCindyMemoryMcpServer } from './cindy_memoryMcpServer.js';
import { createCindyContactsMcpServer } from './cindy_contactsMcpServer.js';
import { createXdtHelperMcpServer, type XdtHelperMcpDeps } from './lizi_xdtHelperMcpServer.js';
+import { createCindyDocsMcpServer } from './cindy_docsMcpServer.js';
+import type { DocsMcpDeps } from './cindy-docs/types.js';
import { createOrcaMcpServer, type OrcaMcpDeps } from './orca/index.js';
import { createCindyLspMcpServer, detectTypeScriptProject } from './lsp/index.js';
import { createBrowserMcpServer } from './browser/index.js';
@@ -88,6 +90,14 @@ export interface CreateLiziMcpProvidersOptions {
* 对应"协同模式"可关插件。deps 注入即激活 9 个 team 工具。
*/
orca?: OrcaMcpDeps;
+ /**
+ * cindy_docs(文档工坊): PDF / Word / Excel / PPT 的格式转换原语。
+ * 与 xdtHelper 同款 —— 无外部账号依赖,host 仍需显式传(即使 {})才启用。
+ * writeDocsOutput 缺省时生成工具不注册;renderHtmlToPdf 缺省时 render_pdf
+ * 不注册(本包不 import electron,这些边界能力由 desktop main 闭包注入)。
+ * 对应宿主内置能力开关 id 'docs'(不是需要安装的外置 .cindy 插件)。
+ */
+ docs?: DocsMcpDeps;
}
function selected(
@@ -380,6 +390,28 @@ export function createLiziMcpProviders(
});
}
+ if (opts.docs && selected(enabled, 'cindy_docs')) {
+ providers.push({
+ name: 'cindy_docs',
+ // 无 isEnabled 门控:plugin 系统已在 host 层(mcp-providers.ts wrap)按
+ // 宿主内置能力开关 id 'docs' 已包了 isEnabled 检查,这里再加就是双重门(同 cindy_ssh / cindy_orca)。
+ // ctx 闭包绑定 workingDir/sessionId —— 所有文件路径都以它为根做边界钳制;
+ // Codex / Pi 的 HTTP bridge 在 tool-call 阶段由 AsyncLocalStorage 恢复真实 ctx,
+ // 恢复不出来时 _paths.resolveSessionRoot 会 fail closed 返 NO_SESSION_CONTEXT。
+ toClaudeSdkConfig: (ctx) => ({
+ type: 'sdk',
+ name: 'cindy_docs',
+ instance: createCindyDocsMcpServer(opts.docs!, {
+ agentKind: ctx.agentKind === 'codex' ? 'codex' : ctx.agentKind === 'pi' ? 'pi' : 'claude-code',
+ workingDir: ctx.workingDir,
+ ...(ctx.getSessionContext ? { getSessionContext: ctx.getSessionContext } : {}),
+ sessionId: ctx.sessionId,
+ vendorOptions: ctx.vendorOptions,
+ }),
+ }),
+ });
+ }
+
if (opts.orca && selected(enabled, 'cindy_orca')) {
providers.push({
name: 'cindy_orca',
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 24b85aa9a1..22abfe6243 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -450,6 +450,9 @@ export type SessionSearchFn = (
// 'cindy_slack'(与老 lizi_slack_bot 无关)2026-07-19 上线: Slack 网关工具,
// 经 hook 通道由 slack-hook-server 以托管 user token 调 Slack 官方 MCP,
// 接替退役的 cindy-slack 意识。
+// 'cindy_docs'(文档工坊)2026-08-19 上线: PDF / Word / Excel / PPT 的生成与
+// 检查原语。**零系统依赖**——不走任何需要用户先装 LibreOffice / Office 的路径,
+// 对应宿主内置能力开关 id 'docs'(不是需要安装的外置 .cindy 插件)。
export type LiziMcpId =
| 'android'
| 'ios_simulator'
@@ -464,6 +467,7 @@ export type LiziMcpId =
| 'cindy_contacts'
| 'cindy_helper'
| 'cindy_orca'
+ | 'cindy_docs'
| 'cindy_lsp';
// ── Host-callback Result pattern ────────────────────────────────────────────
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 60b82e8b85..ccd78fb5c2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -211,6 +211,9 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.29.0
version: 1.29.0([email protected])
+ '@napi-rs/canvas':
+ specifier: ^0.1.100
+ version: 0.1.100
'@paralleldrive/cuid2':
specifier: ^2.3.1
version: 2.3.1
@@ -307,6 +310,9 @@ importers:
diff:
specifier: ^8.0.4
version: 8.0.4
+ docx:
+ specifier: ^9.7.1
+ version: 9.7.1
drizzle-orm:
specifier: ^0.45.2
version: 0.45.2(@types/[email protected])([email protected])
@@ -319,6 +325,9 @@ importers:
electron-window-state:
specifier: ^5.0.3
version: 5.0.3
+ exceljs:
+ specifier: ^4.4.0
+ version: 4.4.0
fix-path:
specifier: ^5.0.0
version: 5.0.0
@@ -352,6 +361,9 @@ importers:
lucide-react:
specifier: ^0.468.0
version: 0.468.0([email protected])
+ marked:
+ specifier: ^16.4.2
+ version: 16.4.2
mermaid:
specifier: ^11.14.0
version: 11.16.0
@@ -367,6 +379,9 @@ importers:
picomatch:
specifier: ^4.0.5
version: 4.0.5
+ pptxgenjs:
+ specifier: ^4.0.1
+ version: 4.0.1
qrcode:
specifier: ^1.5.4
version: 1.5.4
@@ -1035,12 +1050,30 @@ importers:
'@modelcontextprotocol/sdk':
specifier: ^1.29.0
version: 1.29.0([email protected])
+ docx:
+ specifier: ^9.7.1
+ version: 9.7.1
+ entities:
+ specifier: ^6.0.1
+ version: 6.0.1
eventsource-parser:
specifier: ^3.0.6
version: 3.1.0
+ exceljs:
+ specifier: ^4.4.0
+ version: 4.4.0
google-auth-library:
specifier: ^10.6.2
version: 10.9.0
+ jszip:
+ specifier: ^3.10.1
+ version: 3.10.1
+ marked:
+ specifier: ^16.4.2
+ version: 16.4.2
+ pptxgenjs:
+ specifier: ^4.0.1
+ version: 4.0.1
sharp:
specifier: ^0.35.0
version: 0.35.3(@types/[email protected])
@@ -2733,6 +2766,12 @@ packages:
resolution: {integrity: sha512-4aQzz9vgxcNXFfo/iyNgDDYfsU5XGKKxWxZopw0cVotHiW+U8IJbIxMaxsINs6bHhtkG3StKNPcOrn3eBuxKPw==}
hasBin: true
+ '@fast-csv/[email protected]':
+ resolution: {integrity: sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==}
+
+ '@fast-csv/[email protected]':
+ resolution: {integrity: sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==}
+
'@felixrieseberg/[email protected]':
resolution: {integrity: sha512-Dko6I4SuaEB/QLfkS8K//XJZez3Sdt1ldV0Z1VE3IqYw1YMov5W6KQZugYiUnC6jmYa9Yz0LibWdZuKRrOtqnA==}
engines: {node: '>=12.0.0'}
@@ -4593,6 +4632,9 @@ packages:
resolution: {integrity: sha512-CPM9nzrCPPJHQNA9keH9CVkVI+WR5kMa+7XEs5jcGQ0VoAGnLv242w8lIVgwAEfmE4oufJRaTc9PNLQl0ioAow==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==}
+
resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==}
@@ -5177,6 +5219,9 @@ packages:
resolution: {integrity: sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==}
+
resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==}
@@ -5186,6 +5231,9 @@ packages:
resolution: {integrity: sha512-7B1Rtx82hjnSD4PGLAjVWeYH3tHAcVUmChh85a3lltKQm6FresXh9ErQo6oAv6CqxttczC3/kEg8SY5NluPuUw==}
+ resolution: {integrity: sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==}
+
resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}
@@ -5249,9 +5297,17 @@ packages:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ resolution: {integrity: sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==}
+ engines: {node: '>=0.10'}
+
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
+ resolution: {integrity: sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==}
+ engines: {node: '>=0.2.0'}
+
resolution: {integrity: sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA==}
engines: {node: '>=10.0.0'}
@@ -5324,6 +5380,9 @@ packages:
resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==}
+
resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==}
engines: {node: '>=4'}
@@ -5989,6 +6048,10 @@ packages:
resolution: {integrity: sha512-Ndrrf6BMPalkQPd/zubL+4YghH2J9NspapQ09uDXwYbvOPkP0oaqf5CkcwJ0b50kS2O3ul6yVu+jz+RY62Cejg==}
+ resolution: {integrity: sha512-ilXFf9Moz47ABjFpDiA5s1w9lpb4EFSp7+5iiJSbfyYDM+bpZdAgLlSr7fW4aXhVe/E+F6QCv0EvRVFEd5CsWg==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==}
@@ -6122,6 +6185,9 @@ packages:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}
+
resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==}
@@ -6387,6 +6453,10 @@ packages:
resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==}
engines: {node: '>=18.0.0'}
+ resolution: {integrity: sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==}
+ engines: {node: '>=8.3.0'}
+
resolution: {integrity: sha512-adbxcyWV46qiHyvSp50TKt05tB4tK3HcmF7/nxfAdhnox83seTDbwnaqKO4sXRy7roHAIFqJP/Rw/AuEbX61LA==}
engines: {node: '>=6'}
@@ -6745,6 +6815,10 @@ packages:
resolution: {integrity: sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA==}
engines: {'0': node >=0.6.0}
+ resolution: {integrity: sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==}
+ engines: {node: '>=10.0.0'}
+
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
@@ -6942,6 +7016,11 @@ packages:
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
+ resolution: {integrity: sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==}
+ engines: {node: '>=0.6'}
+ deprecated: This package is no longer supported.
+
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
@@ -7126,6 +7205,9 @@ packages:
resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==}
+
resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}
engines: {node: '>= 0.4'}
@@ -7236,6 +7318,9 @@ packages:
resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}
engines: {node: '>= 14'}
+ resolution: {integrity: sha512-4EC57ddXrkaF0x83Oj8sM6SLQHAWXw90Skqu2M4AEWENZ3F02dFJE/GARA8igO79tcgYqGrD7ae4f5L3um2lgg==}
+
resolution: {integrity: sha512-SEQu7vl8KjNL2eoGBLF3+wAjpsNfA9XMlXAYj/3EdaNfAlxKthD1xjEQfGOUhllCGGJVNY34bRr6lPINhNjyZw==}
engines: {node: '>=8.12.0'}
@@ -7753,6 +7838,9 @@ packages:
resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==}
+ resolution: {integrity: sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==}
+
resolution: {integrity: sha512-rJysbR9GKIalhTbVL2tYbF2hVyDnrf7pFUZBwjPaMIdadYHmeT+EVi/Bu3qd7ETQPahTotg2WRCatXwRBW554g==}
engines: {node: '>=16.0.0'}
@@ -7802,6 +7890,9 @@ packages:
resolution: {integrity: sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==}
+ resolution: {integrity: sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==}
+
resolution: {integrity: sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==}
@@ -7809,12 +7900,31 @@ packages:
resolution: {integrity: sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==}
deprecated: This package is deprecated. Use the optional chaining (?.) operator instead.
+ resolution: {integrity: sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==}
+
resolution: {integrity: sha512-AupTIzdLQxJS5wIYUQlgGyk2XRTfGXA+MCghDHqZk0pzUNYvd3EESS6dkChNauNYVIutcb0dfHw1ri9Q1yPV8Q==}
+ resolution: {integrity: sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==}
+
+ resolution: {integrity: sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==}
+ deprecated: This package is deprecated. Use require('node:util').isDeepStrictEqual instead.
+
+ resolution: {integrity: sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==}
+
+ resolution: {integrity: sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==}
+
resolution: {integrity: sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==}
+ resolution: {integrity: sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==}
+
resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==}
@@ -7830,6 +7940,9 @@ packages:
resolution: {integrity: sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==}
+ resolution: {integrity: sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==}
+
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
@@ -8254,6 +8367,9 @@ packages:
resolution: {integrity: sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==}
+
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
@@ -8363,6 +8479,11 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
+ resolution: {integrity: sha512-kVrnsrJqMR8+oLJnGEmSWw9BivK5mt7H3FZatVRjrc5wGqFYuBxX1yG7+A7Gi5AefkX6t/oCkizcQgpu0cY1dQ==}
+ engines: {node: ^18 || >=20}
+ hasBin: true
+
resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==}
@@ -8818,6 +8939,9 @@ packages:
engines: {node: '>=14.0.0'}
hasBin: true
+ resolution: {integrity: sha512-TeJISr8wouAuXw4C1F/mC33xbZs/FuEG6nH9FG1Zj+nuPcGMP5YRHl6X+j3HSUnS1f3at6k75ZZXPMZlA5Lj9A==}
+
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@@ -9386,6 +9510,10 @@ packages:
resolution: {integrity: sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==}
engines: {node: '>=11.0.0'}
+ resolution: {integrity: sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
engines: {node: '>=v12.22.7'}
@@ -9908,6 +10036,9 @@ packages:
resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ==}
+
resolution: {integrity: sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg==}
@@ -10102,6 +10233,9 @@ packages:
resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==}
engines: {node: '>= 0.8'}
+ resolution: {integrity: sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==}
+
resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==}
hasBin: true
@@ -10180,6 +10314,11 @@ packages:
deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
hasBin: true
+ resolution: {integrity: sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==}
+ deprecated: uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).
+ hasBin: true
+
resolution: {integrity: sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==}
@@ -10455,6 +10594,10 @@ packages:
expo: '*'
expo-modules-core: '*'
+ resolution: {integrity: sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==}
+ hasBin: true
+
resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
engines: {node: '>=18'}
@@ -10467,6 +10610,9 @@ packages:
resolution: {integrity: sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==}
engines: {node: '>=4.0.0'}
+ resolution: {integrity: sha512-huCv9IH9Tcf95zuYCsQraZtWnJvBtLVE0QHMOs8bWyZAFZNDcYjsPq1nEx8jKA9y+Beo9v+7OBPRisQTjinQMw==}
+
resolution: {integrity: sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==}
engines: {node: '>=4.0'}
@@ -12399,6 +12545,25 @@ snapshots:
chalk: 4.1.2
js-yaml: 4.3.0
+ '@fast-csv/[email protected]':
+ dependencies:
+ '@types/node': 14.18.63
+ lodash.escaperegexp: 4.1.2
+ lodash.isboolean: 3.0.3
+ lodash.isequal: 4.5.0
+ lodash.isfunction: 3.0.9
+ lodash.isnil: 4.0.0
+
+ '@fast-csv/[email protected]':
+ dependencies:
+ '@types/node': 14.18.63
+ lodash.escaperegexp: 4.1.2
+ lodash.groupby: 4.6.0
+ lodash.isfunction: 3.0.9
+ lodash.isnil: 4.0.0
+ lodash.isundefined: 3.0.1
+ lodash.uniq: 4.5.0
+
dependencies:
'@electron-forge/maker-base': 7.11.2
@@ -13038,7 +13203,6 @@ snapshots:
'@napi-rs/canvas-linux-x64-musl': 0.1.100
'@napi-rs/canvas-win32-arm64-msvc': 0.1.100
'@napi-rs/canvas-win32-x64-msvc': 0.1.100
- optional: true
dependencies:
@@ -14329,6 +14493,8 @@ snapshots:
dependencies:
'@types/node': 25.9.5
+ '@types/[email protected]': {}
+
dependencies:
undici-types: 5.26.5
@@ -15144,6 +15310,11 @@ snapshots:
+ dependencies:
+ buffers: 0.1.1
+ chainsaw: 0.1.0
+
dependencies:
file-uri-to-path: 1.0.0
@@ -15158,6 +15329,8 @@ snapshots:
dependencies:
bluebird: 3.7.2
+
@@ -15230,11 +15403,15 @@ snapshots:
+
dependencies:
base64-js: 1.5.1
ieee754: 1.2.1
+
optional: true
@@ -15318,6 +15495,10 @@ snapshots:
loupe: 3.2.1
pathval: 2.0.1
+ dependencies:
+ traverse: 0.3.9
+
dependencies:
ansi-styles: 3.2.1
@@ -16038,6 +16219,15 @@ snapshots:
+ dependencies:
+ '@types/node': 25.9.5
+ hash.js: 1.1.7
+ jszip: 3.10.1
+ nanoid: 5.1.16
+ xml: 1.0.1
+ xml-js: 1.6.11
+
@@ -16090,6 +16280,10 @@ snapshots:
es-errors: 1.3.0
gopd: 1.2.0
+ dependencies:
+ readable-stream: 2.3.8
+
@@ -16478,6 +16672,18 @@ snapshots:
dependencies:
eventsource-parser: 3.1.0
+ dependencies:
+ archiver: 5.3.2
+ dayjs: 1.11.21
+ fast-csv: 4.3.6
+ jszip: 3.10.1
+ readable-stream: 3.6.2
+ saxes: 5.0.1
+ tmp: 0.2.7
+ unzipper: 0.10.14
+ uuid: 8.3.2
+
dependencies:
cross-spawn: 6.0.6
@@ -16957,6 +17163,11 @@ snapshots:
optional: true
+ dependencies:
+ '@fast-csv/format': 4.3.5
+ '@fast-csv/parse': 4.3.6
+
@@ -17177,6 +17388,13 @@ snapshots:
optional: true
+ dependencies:
+ graceful-fs: 4.2.11
+ inherits: 2.0.4
+ mkdirp: 0.5.6
+ rimraf: 2.6.3
+
@@ -17432,6 +17650,11 @@ snapshots:
dependencies:
has-symbols: 1.1.0
+ dependencies:
+ inherits: 2.0.4
+ minimalistic-assert: 1.0.1
+
dependencies:
function-bind: 1.1.2
@@ -17603,6 +17826,8 @@ snapshots:
transitivePeerDependencies:
- supports-color
+
@@ -18043,6 +18268,8 @@ snapshots:
+
dependencies:
cli-truncate: 3.1.0
@@ -18103,14 +18330,28 @@ snapshots:
+
+
+
+
+
+
+
@@ -18121,6 +18362,8 @@ snapshots:
+
@@ -18877,6 +19120,8 @@ snapshots:
+
dependencies:
brace-expansion: 5.0.8
@@ -18941,6 +19186,8 @@ snapshots:
+
@@ -19339,6 +19586,13 @@ snapshots:
dependencies:
commander: 9.5.0
+ dependencies:
+ '@types/node': 22.20.1
+ https: 1.0.0
+ image-size: 1.2.1
+ jszip: 3.10.1
+
dependencies:
detect-libc: 2.1.2
@@ -20027,7 +20281,6 @@ snapshots:
dependencies:
glob: 7.2.3
- optional: true
dependencies:
@@ -20115,6 +20368,10 @@ snapshots:
+ dependencies:
+ xmlchars: 2.2.0
+
dependencies:
xmlchars: 2.2.0
@@ -20704,6 +20961,8 @@ snapshots:
dependencies:
punycode: 2.3.1
+
@@ -20881,6 +21140,19 @@ snapshots:
+ dependencies:
+ big-integer: 1.6.52
+ binary: 0.3.0
+ bluebird: 3.4.7
+ buffer-indexof-polyfill: 1.0.2
+ duplexer2: 0.1.4
+ fstream: 1.0.12
+ graceful-fs: 4.2.11
+ listenercount: 1.0.1
+ readable-stream: 2.3.8
+ setimmediate: 1.0.5
+
dependencies:
browserslist: 4.28.6
@@ -20954,6 +21226,8 @@ snapshots:
+
dependencies:
spdx-correct: 3.2.0
@@ -21322,6 +21596,10 @@ snapshots:
expo: 56.0.16(bedb3dfb85b4bb5081482612eab0a2c6)
expo-modules-core: 56.0.21([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected]))([email protected](patch_hash=9442031604caa9cd185e0b2be6867055459fc3a6d2781296027989db098f972d)(@babel/[email protected])(@react-native/[email protected](@babel/[email protected]))(@types/[email protected])([email protected]))([email protected])
+ dependencies:
+ sax: 1.6.0
+
@@ -21334,6 +21612,8 @@ snapshots:
sax: 1.6.0
xmlbuilder: 11.0.1
+