From 77ef1ec11ce67bf21d3b399cad296af005dfa1a3 Mon Sep 17 00:00:00 2001 From: kicer Date: Wed, 11 Nov 2026 20:50:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(skills):=20office=20=E6=9C=AC=E5=9C=B0?= =?UTF-8?q?=E6=94=BE=E8=A1=8C=20watch=E3=80=81x2pdf=20=E5=8A=A0=E6=B5=8F?= =?UTF-8?q?=E8=A7=88=E5=99=A8=E5=90=8E=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit office 封装层:本地直跑(AGENT_LOCAL_PICK)没有预览网关,不发 ui_card、 不 POST __pv-touch;watch/unwatch 与 mark/goto 族放行,watch 改后台拉起 + 等端口就绪后报地址退出(前台透传会卡到 terminal 超时)。 x2pdf:文本类分派改为 WeasyPrint → 无头浏览器 → LibreOffice,浏览器后端只需 装了 Chrome 系,不要求用户为转 PDF 现编 pango;CSS/base 注入到 head,无 @page 时 补 A4(浏览器默认 Letter)。吞掉 WeasyPrint 导入失败时裸 print 到 stdout 的告警。 对外文案只讲结果(排版降级/无可用排版能力),实现细节留在 AGENTS.md。 --- skills/office/SKILL.md | 3 ++ skills/office/scripts/office | 82 ++++++++++++++++++++++++---- skills/x2pdf/AGENTS.md | 27 +++++++--- skills/x2pdf/SKILL.md | 6 +-- skills/x2pdf/run.py | 102 ++++++++++++++++++++++++++++++----- 5 files changed, 186 insertions(+), 34 deletions(-) diff --git a/skills/office/SKILL.md b/skills/office/SKILL.md index 30a908f..285584b 100644 --- a/skills/office/SKILL.md +++ b/skills/office/SKILL.md @@ -31,6 +31,9 @@ office [args...] create/open 成功后,用户可自行查看该文档的实时预览(预览页上的选区、标注类交互之后都能被 get-pos 读到)。用户反馈"看第几段/选中了哪里/修改哪里"时,优先用 get-pos 读回选区再针对性改。 +本地直跑没有预览卡片时,用 `office watch ` 起自带预览页(立即返回本机地址), +`office unwatch ` 停。 + ## 注意 - 所有操作文档在任务目录里。 diff --git a/skills/office/scripts/office b/skills/office/scripts/office index 1f1baf0..46ad1f4 100755 --- a/skills/office/scripts/office +++ b/skills/office/scripts/office @@ -2,22 +2,28 @@ // office: officecli 的封装层(技能唯一入口)。 // - 二进制不进 PATH、SKILL.md 不提及:可见面 = 可调用面,模型只认识本脚本;路径可用 OFFICECLI_BIN 覆盖。 // - 命令治理移植自原 MCP 桥:隐去命令报原生风格 unrecognized;view 渲染族拦截给替代路径; -// watch 族不透传(预览由平台托管)。 +// watch 族在服务器形态不透传(预览由平台网关托管),本地直跑放行(见 LOCAL 分支)。 // - create/open 成功在 stdout 尾行发 ui_card marker(::ui_card {json}::):core 剥离后转聊天流卡片, -// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。 +// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。本地没有预览网关,不发卡片。 'use strict'; -const { spawnSync } = require('node:child_process'); +const { spawn, spawnSync } = require('node:child_process'); const path = require('node:path'); const http = require('node:http'); +const fs = require('node:fs'); +const net = require('node:net'); +const os = require('node:os'); const BIN = process.env.OFFICECLI_BIN || path.resolve(__dirname, '..', 'bin', 'officecli'); +// 本地直跑(local/start.sh 注入):没有 executor,也没有 /preview 网关, +// 预览卡片必然是死链、__pv-touch 打不通,watch 也就没有平台托管可言。 +const LOCAL = process.env.AGENT_LOCAL_PICK === '1'; // 本部署不合适的命令(自锁死 / 装配环境族):原生风格报错,help 清单同步删行(见 help 段)。 const unrecognized = (v) => "Unrecognized command or argument '" + v + "'."; const HIDDEN_TOP = /^(mcp|skills|install|plugins)(?:\s|$)/; const HIDDEN_LINE = /^ {2}(?:mcp|skills|install|plugins)\b/; // '\b' 绝不能用字符串拼 RegExp(会变退格符) const HELP_STRIP = /^ {2}(?:watch|unwatch)\b/; -const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖 +const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖(本地有真实 watch,放行) const VIEW_BLOCKED = new Set(['html', 'screenshot', 'svg', 'pdf', 'forms']); // 需无头浏览器/导出插件,本环境没有 const OFFICE_EXT_RE = /\.(?:docx|xlsx|pptx)$/i; const EDIT_RE = /^(set|add|remove|move|swap|raw-set|add-part|batch|import|merge|refresh)$/; @@ -60,8 +66,8 @@ const first = String(argv[0] || ''); // ---------- 命令面闸门 ---------- let m = HIDDEN_TOP.exec(cmd); if (m || (first === 'help' && HIDDEN_TOP.test(argv.slice(1).join(' ')))) err(unrecognized(m ? m[1] : argv[1])); -if (HIDDEN_SUBS.has(first)) err(unrecognized(first)); -if (first === 'watch' || first === 'unwatch') { +if (!LOCAL && HIDDEN_SUBS.has(first)) err(unrecognized(first)); +if (!LOCAL && (first === 'watch' || first === 'unwatch')) { err('Preview slots are managed by the platform: create/open a document, then click the preview card in the chat.'); } @@ -83,6 +89,63 @@ if (first === 'get-pos') { argv = ['get', file, 'selected', '--json']; } +// watch:原生是常驻 HTTP 预览服务,前台透传会一直阻塞到 terminal 超时。 +// 本地改成后台拉起 → 等端口就绪 → 报地址 → 立刻退出,预览页留在后台刷新(编辑通知走原生管道,同机可用)。 +function startWatch() { + const file = argv[1]; + if (!file) err('Usage: watch [--port ]'); + let port = 26315; + for (let i = 2; i < argv.length; i++) { + const a = String(argv[i]); + if (a === '--port') { port = Number(argv[i + 1]); break; } + if (a.startsWith('--port=')) { port = Number(a.slice(7)); break; } + } + if (!Number.isInteger(port) || port <= 0 || port > 65535) err('watch: --port 需要合法端口号'); + const url = 'http://127.0.0.1:' + port + '/'; + const report = () => { + process.stdout.write('预览地址:' + url + '\n停止预览:unwatch ' + file + '\n'); + process.exit(0); + }; + const probe = (cb) => { + const s = net.connect({ host: '127.0.0.1', port }); + s.setTimeout(300); + s.once('connect', () => { s.destroy(); cb(true); }); + s.once('timeout', () => { s.destroy(); cb(false); }); + s.once('error', () => cb(false)); + }; + probe((up) => { + if (up) return report(); + const logf = path.join(os.tmpdir(), 'officecli-watch-' + port + '.log'); + let fd; + try { fd = fs.openSync(logf, 'a'); } catch (e) { err('watch: 无法写日志 ' + logf + ': ' + (e && e.message || e)); } + const child = spawn(BIN, argv, { + cwd: process.cwd(), env: vendorEnv(), detached: true, stdio: ['ignore', fd, fd], + }); + try { fs.closeSync(fd); } catch (_) {} + child.on('error', (e) => { err('watch 启动失败:' + (e && e.message || e)); }); + child.unref(); + let tries = 0; + const tick = () => { + probe((ok) => { + if (ok) return report(); + if (++tries > 50) { + let tail = ''; + try { tail = fs.readFileSync(logf, 'utf8').split('\n').slice(-5).join('\n').trim(); } catch (_) {} + err('watch 未能在 5s 内就绪;日志:' + logf + (tail ? '\n' + tail : '')); + } + setTimeout(tick, 100); + }); + }; + setTimeout(tick, 100); + }); +} + +if (LOCAL && first === 'watch' && !helpCmd && !(argv[2] && HIDDEN_SUBS.has(String(argv[2])))) { + startWatch(); + // 不能落到下面的同步透传:spawnSync 会堵住事件循环,端口就绪的回调就再也跑不到 + return; +} + // ---------- 透传 ---------- let r; try { @@ -101,13 +164,14 @@ if (r.error) { let outRaw = scrub(r.stdout || ''); // help 文本对齐可调用面:隐去的命令删行(原生 cwd 已是会话目录,无扩展命令需补录) if (helpCmd && outRaw.includes('Commands:')) { - outRaw = outRaw.split('\n').filter((ln) => !HIDDEN_LINE.test(ln) && !HELP_STRIP.test(ln)).join('\n'); + outRaw = outRaw.split('\n') + .filter((ln) => !HIDDEN_LINE.test(ln) && (LOCAL || !HELP_STRIP.test(ln))).join('\n'); } if (outRaw) process.stdout.write(outRaw); if (r.stderr) process.stderr.write(scrub(r.stderr || '')); // create/open 成功尾行发预览卡片 marker(core 解析后剥离;模型面无感) -if (r.status === 0 && /^(create|open)$/.test(first)) { +if (r.status === 0 && !LOCAL && /^(create|open)$/.test(first)) { let file = null; for (const t of argv) { const s = String(t); @@ -130,7 +194,7 @@ if (r.status === 0 && /^(create|open)$/.test(first)) { // 网关命中活槽位后 POST watch /api/switch 就地重读,页面靠 vendor 自带的 doc-switched 监听自刷。 // fire-and-forget:800ms 封顶,一切失败静默——预览永远不是命令成功的前提。 const CODE = r.status === null ? 1 : r.status; -if (CODE === 0 && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) { +if (CODE === 0 && !LOCAL && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) { let done = false; const finish = () => { if (done) return; done = true; process.exit(CODE); }; try { diff --git a/skills/x2pdf/AGENTS.md b/skills/x2pdf/AGENTS.md index d10c598..68f89ce 100644 --- a/skills/x2pdf/AGENTS.md +++ b/skills/x2pdf/AGENTS.md @@ -1,16 +1,29 @@ # x2pdf -`ModuleNotFoundError`(`markdown`)或提示 WeasyPrint 不可用:把依赖装进 `$AGENT_SKILLS_DEPS` +`ModuleNotFoundError`(`markdown`):把依赖装进 `$AGENT_SKILLS_DEPS` ```sh python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/x2pdf/requirements.txt" ``` -WeasyPrint 还要系统库 pango/cairo:Linux `apt install libpango-1.0-0 libpangocairo-1.0-0 libcairo2`; -macOS `brew install pango`;Windows 装不起来就跳过——有 LibreOffice 时文本类会自动回落。 +## 后端缺哪个,代价多大 -Office 类(docx/xlsx/pptx)报「未找到 LibreOffice」:装一个 LibreOffice -(Linux `apt install libreoffice`;macOS `brew install --cask libreoffice`; -Windows `winget install TheDocumentFoundation.LibreOffice`)。 +| 后端 | 缺了的影响 | 怎么补 | +|---|---|---| +| LibreOffice | **Office 类(docx/xlsx/pptx)完全不能转**,必装 | Linux `apt install libreoffice`;macOS `brew install --cask libreoffice`;Windows `winget install TheDocumentFoundation.LibreOffice` | +| 浏览器 | 文本类落到 LibreOffice,CSS 基本失效 | 通常不用装:已有 Chrome / Chromium / Edge 就自动用 | +| WeasyPrint | 文本类没有页码、`@page` 精确排版失效 | 先装 Python 包(见上),再补系统库 pango/cairo:Linux `apt install libpango-1.0-0 libpangocairo-1.0-0 libcairo2`;macOS `brew install pango`;Windows 补 GTK 运行库,装不上就跳过 | -装了 LibreOffice 后文本类也能用(回落路径,`page` 的边距/页码与部分 CSS 不生效),此时不必装 pango。 +报「没有可用的 PDF 排版能力」时:文本类有三个后端可退,按上表从便宜到贵补,别一次全装。 +输出带着「排版降级」(无页码/边距偏差)不是失败,是后端不全,按需补。 +系统级安装(几百 MB,老系统上可能源码编译十几分钟)先跟用户说清代价,由他决定装还是接受降级。 + +## 装完必须验证 + +`pip install` 成功不代表能用,缺系统库时 import 就炸: + +```sh +python3 -c "import weasyprint; print(weasyprint.__version__)" +``` + +报 `could not import some external libraries` = 系统库(pango/cairo)还没到位,不是 Python 包的问题。 diff --git a/skills/x2pdf/SKILL.md b/skills/x2pdf/SKILL.md index b32e560..1154e51 100644 --- a/skills/x2pdf/SKILL.md +++ b/skills/x2pdf/SKILL.md @@ -37,10 +37,8 @@ output_schema: 统一 PDF 转换入口,按扩展名自动分派两条渲染路径: -- **md / txt / html → WeasyPrint**(CSS 排版,字体走 fontconfig,中文用系统文泉驿/Noto,无需字体文件); - 本机没有 WeasyPrint(缺包,或缺它依赖的 pango/cairo)时自动回落 LibreOffice—— - 能出件,但 `page`/`css` 只部分生效,不适合精确排版 -- **docx / xlsx / pptx / odt / ods / odp → LibreOffice headless**(忠于原文档版式,`page`/`css` 参数不生效) +- **md / txt / html → 渲染成 PDF**(CSS 排版,字体走系统 fontconfig,中文用系统文泉驿/Noto,无需字体文件) +- **docx / xlsx / pptx / odt / ods / odp → 按原文档版式转换**(`page`/`css` 参数不生效) ### Markdown 输入(`.md` / `.markdown`) - 标准语法之外,支持表格(管道语法)、围栏代码块(```/~~~)、脚注、定义列表、 diff --git a/skills/x2pdf/run.py b/skills/x2pdf/run.py index 1529829..c929d00 100644 --- a/skills/x2pdf/run.py +++ b/skills/x2pdf/run.py @@ -3,16 +3,19 @@ x2pdf 技能主入口:通用 PDF 转换。 分派策略(按输入文件扩展名): -- .md / .markdown / .txt / .html / .htm → WeasyPrint 渲染;本机没有 WeasyPrint - (缺包,或缺它要 dlopen 的 pango/cairo)时回落 LibreOffice,保真度略低但不缺库 +- .md / .markdown / .txt / .html / .htm → 依次尝试 WeasyPrint / 无头浏览器 / LibreOffice + 三者都是本机可能没有的渲染后端:WeasyPrint 缺包或缺 pango/cairo 时不可用, + 浏览器(Chrome/Chromium/Edge)不需要任何 Python 依赖,保真度介于两者之间 - .docx / .xlsx / .pptx / .odt / .ods / .odp → LibreOffice headless 转换 依赖不假设镜像预烘:Python 包由 requirements.txt 声明,系统库由 install.sh 就绪校验。 -LibreOffice 的定位不只看 PATH:macOS 的 app bundle 与 Windows 的安装目录都不进 PATH, -which() 找不到不等于没装(见 find_soffice)。 +LibreOffice 与浏览器的定位不只看 PATH:macOS 的 app bundle 与 Windows 的安装目录都不进 PATH, +which() 找不到不等于没装(见 find_soffice / find_browser)。 中文字体走 fontconfig(系统文泉驿/Noto),技能不携带字体文件。 """ +import contextlib import html as html_mod +import io import json import os import re @@ -50,6 +53,28 @@ def find_soffice(): return None +def find_browser(): + """定位支持 --headless --print-to-pdf 的浏览器(Chrome / Chromium / Edge)。 + 不要求用户为了转 PDF 装 Python 侧渲染栈:pango 在老系统上只能现编。 + 同 find_soffice:macOS app bundle 与 Windows 安装目录都不进 PATH。""" + for name in ('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser', + 'microsoft-edge', 'msedge'): + p = shutil.which(name) + if p: + return p + for c in ('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', + '/Applications/Chromium.app/Contents/MacOS/Chromium', + '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', + str(Path.home() / 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'), + r'C:\Program Files\Google\Chrome\Application\chrome.exe', + r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', + r'C:\Program Files\Microsoft\Edge\Application\msedge.exe', + r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'): + if Path(c).is_file(): + return c + return None + + def req_hint(): return '本机环境: %s' % (SKILL_DIR / 'AGENTS.md') @@ -200,10 +225,18 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg): output_path.parent.mkdir(parents=True, exist_ok=True) try: - from weasyprint import CSS, HTML + # 导入失败时 WeasyPrint 会往 stdout 打一大段「could not import some external libraries」 + # (text/ffi.py 里裸 print),模型会把这段当成真错。降级是预期行为,噪声吞掉, + # 由返回值那句 note 告知实际后端。 + sink = io.StringIO() + with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink): + from weasyprint import CSS, HTML except (ImportError, OSError): # 缺 Python 包是 ImportError;装了包但缺它要 dlopen 的 libpango/libgobject 时是 OSError。 - # 两种都当作「本机没有 WeasyPrint」,回落 LibreOffice(Office 分支本来也要它)。 + # 两种都当作「本机没有 WeasyPrint」:先试浏览器(只需装了 Chrome 系),再回落 LibreOffice。 + browser = find_browser() + if browser: + return convert_html_browser(browser, document, output_path, base_url, sheets, ext) return convert_html_pdf(document, output_path, ext) # 注:stylesheets 参数只接受 CSS 对象,传字符串会被当成文件路径 HTML(string=document, base_url=base_url).write_pdf( @@ -211,14 +244,56 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg): return '' +def inject_styles(document, sheets, base_url): + """把 CSS 与 base 标签塞进已有 HTML:浏览器后端只能吃单个文件。 + 注入点是 (其次 ),绝不能落到 doctype 前面——那会触发怪异模式。""" + head = '' + if base_url: + head += '\n' % Path(base_url).resolve().as_uri() + if sheets: + head += '\n' % '\n'.join(sheets) + if not head: + return document + m = re.search(r'', document, re.I) or re.search(r']*>', document, re.I) + if m: + return document[:m.start()] + head + document[m.start():] + d = re.match(r'\s*]*>', document, re.I) + if d: + return document[:d.end()] + '\n' + head + document[d.end():] + return head + document + + +def convert_html_browser(browser, document, output_path, base_url, sheets, ext): + """HTML → 无头浏览器打印:WeasyPrint 不可用时的中间档。 + 浏览器能完整解析 CSS(表格边框/底纹/分页),但页码是 WeasyPrint 的 CSS 计数器特性, + 这里不生效;@page 的 size/margin 视浏览器版本部分生效。""" + output_path.parent.mkdir(parents=True, exist_ok=True) + tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-browser-')) + try: + # 浏览器默认纸张是 Letter,WeasyPrint 默认 A4。文档自己没写 @page 时补上 A4, + # 否则同一份 html 换后端就换纸型。 + if not any('@page' in s for s in sheets) and '@page' not in document: + sheets = list(sheets) + ['@page { size: A4; }'] + src = tmp_root / 'document.html' + src.write_text(inject_styles(document, sheets, base_url), encoding='utf-8') + cmd = [browser, '--headless', '--disable-gpu', '--no-pdf-header-footer', + '--virtual-time-budget=2000', + '--print-to-pdf=%s' % str(output_path.resolve()), src.as_uri()] + proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120) + if not output_path.is_file() or output_path.stat().st_size == 0: + detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300] + raise RuntimeError('PDF 生成失败(exit=%s):%s' % (proc.returncode, detail or '无输出')) + finally: + shutil.rmtree(tmp_root, ignore_errors=True) + return '排版降级:无页码,尺寸/边距可能与预期有偏差' + + def convert_html_pdf(document, output_path, ext): - """HTML → LibreOffice:WeasyPrint 不可用时的回落路径。 + """HTML → LibreOffice:最后一道回落(浏览器也没有时)。 代价是保真度:@page 的边距/页码与大部分 CSS 在 LibreOffice 的 HTML 导入里不生效, 适合「拿到一份能看的 PDF」,不适合精确排版。""" if not find_soffice(): - raise RuntimeError('这台机器没有可用的 PDF 渲染后端:%s 需 WeasyPrint,但 WeasyPrint 不可用' - '(缺 Python 包,或缺系统库 pango/cairo);也没找到 LibreOffice。%s' - % (ext, req_hint())) + raise RuntimeError('这台机器没有可用的 PDF 排版能力,无法转换 %s;%s' % (ext, req_hint())) tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-html-')) try: src = tmp_root / 'document.html' @@ -226,7 +301,7 @@ def convert_html_pdf(document, output_path, ext): convert_office_pdf(src, output_path) finally: shutil.rmtree(tmp_root, ignore_errors=True) - return '用 LibreOffice 渲染(WeasyPrint 不可用):@page 边距/页码与部分 CSS 不生效' + return '排版降级:边距/页码与部分 CSS 不生效' def convert_office_pdf(input_path, output_path): @@ -234,8 +309,7 @@ def convert_office_pdf(input_path, output_path): 每次用独立临时 UserInstallation/HOME,避免并发实例互踩共享配置。""" soffice = find_soffice() if not soffice: - raise FileNotFoundError('未找到 LibreOffice(soffice),无法转换 Office 文档。' - '服务器镜像已预装;本机装一个 LibreOffice 即可。') + raise FileNotFoundError('这台机器没有可用于转换 Office 文档的组件;%s' % req_hint()) output_path.parent.mkdir(parents=True, exist_ok=True) tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-office-')) @@ -256,7 +330,7 @@ def convert_office_pdf(input_path, output_path): generated = pdf_dir / (input_path.stem + '.pdf') if not generated.exists(): detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300] - raise RuntimeError('LibreOffice 转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出')) + raise RuntimeError('文档转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出')) shutil.move(str(generated), str(output_path)) finally: shutil.rmtree(tmp_root, ignore_errors=True)