A local-first multi-agent app development platform, built on PenguinHarness
feat(plugins): 让 Adelie 能读改你正在看的 WPS 文档
lmlihenga89e9525285b
diff --git a/README.md b/README.mdindex d6e75ebd..58ab3726 100644--- a/README.md+++ b/README.md@@ -96,7 +96,7 @@ optimise its own Skills:| Category | Plugins || --- | --- |-| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |+| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `use-wps-office`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` || Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram` || AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` || Agent Company | `agent-company` |diff --git a/README.zh.md b/README.zh.mdindex 50cdbb07..90d5aa60 100644--- a/README.zh.md+++ b/README.zh.md@@ -82,7 +82,7 @@ Adelie 运行在你的电脑或服务器上,自动串联 Agent 应用的创建| 分类 | 插件 || ----------- | ------------------------------------------------------------------------------- |-| 办公效率 | `data-analysis`、`use-firecrawl`、`browser-automation`、`use-bento-slides`、`humanizer`、`goal`、`continual-learning`、`csu-mail`、`lesson-video`、`requirements-box` |+| 办公效率 | `data-analysis`、`use-firecrawl`、`browser-automation`、`use-bento-slides`、`use-wps-office`、`humanizer`、`goal`、`continual-learning`、`csu-mail`、`lesson-video`、`requirements-box` || 软件开发 | `software-development`、`use-claude-code`、`wechat-miniprogram` || AI 应用开发 | `agent-development`、`model-development`、`skill-porting`、`agent-tuning` || Agent 公司 | `agent-company` |diff --git a/changelog/unreleased/2026-10-15-wps-office.md b/changelog/unreleased/2026-10-15-wps-office.mdnew file mode 100644index 00000000..87bf128f--- /dev/null+++ b/changelog/unreleased/2026-10-15-wps-office.md@@ -0,0 +1,38 @@+# Adelie can now read and edit the WPS document you are looking at++- **Date:** 2026-10-15+- **Type:** feat+- **Scope:** `plugins`++[中文版](2026-10-15-wps-office.zh.md)++New plugin: **WPS** (`@lmliheng/use-wps-office`). It puts an Adelie conversation inside WPS Writer —+a side panel opened from a button in the ribbon — and puts the document that is open on your screen+under the agent's hands: nine operations (summary, read, search, replace, insert, delete, insert a+break, create, reveal) are exposed to a Session as `mcp__wps__*` tools.++The runtime is one dependency-free Node file (`kit/serve.mjs`), and it stays on the machine: the+bridge binds `127.0.0.1`, Adelie is reached over loopback, and no port is opened to the network. The+bridge plays four parts and nothing else — it hosts the add-on's page, sends document commands to the+panel that executes them, talks to Adelie on the panel's behalf, and registers the add-on with WPS+through WPS's own local publish service (`127.0.0.1:58890`). A bridge is needed at all because the+panel runs in WPS's embedded browser on a different origin, and Adelie deliberately enables no CORS.++Editing goes through the person: panel Sessions start `read-only`, so reads run freely while every+write is an approval the person answers in the panel. `replace_paragraph` and `delete_paragraph`+take an optional `expect` — the paragraph's current text — and refuse when it no longer matches+("the paragraph changed, read it again"), because the numbers a model read can go stale.++Commands are one at a time, in order: two writers on one document would make both unreadable. A+command the panel never answers fails with a readable message instead of hanging the turn.++`install.mjs` writes the settings, registers the add-on with WPS, registers the bridge as one MCP+server in the agent's config and self-checks the connection, leaves a launcher in the Windows login+Startup folder, and starts the bridge. Every step is idempotent, so running it again is also the+repair; `uninstall.mjs` is its mirror. Settings, state and `bridge.log` live under+`<data root>/wps-bridge/`, never in the plugin directory, which is replaced wholesale on update.++**Not verified:** the WPS side itself. The panel and the bridge are tested here (bridge, install+and add-on hosting under `node --test`; fourteen browser tests driving the real panel against a+stub WPS), but the ribbon button, the task pane and the document API only exist on a machine with+WPS installed — that first run has to happen on Windows, with WPS open.diff --git a/changelog/unreleased/2026-10-15-wps-office.zh.md b/changelog/unreleased/2026-10-15-wps-office.zh.mdnew file mode 100644index 00000000..9832f05a--- /dev/null+++ b/changelog/unreleased/2026-10-15-wps-office.zh.md@@ -0,0 +1,32 @@+# 能让 Adelie 读改你正在看的 WPS 文档了++- **Date:** 2026-10-15+- **Type:** feat+- **Scope:** `plugins`++[English](2026-10-15-wps-office.md)++新插件:**WPS**(`@lmliheng/use-wps-office`)。它把 Adelie 的对话搬进 WPS 文字——功能区点一下开侧栏,+再把你屏幕上那份打开的文档交到 Agent 手里:九个操作(读概况、读正文、搜索、替换、插入、删除、插分隔符、+新建、定位)以 `mcp__wps__*` 工具的形式交给会话。++运行时就是一个零依赖的 Node 文件(`kit/serve.mjs`),全程不出这台机器:桥只绑 `127.0.0.1`,Adelie 走+回环地址访问,不对网络开任何端口。桥只做四件事——托管加载项那页、把文档指令下发给真正执行它的面板、+替面板跟 Adelie 说话、通过 WPS 自己的本机上架服务(`127.0.0.1:58890`)登记加载项。之所以要有这个桥,+是因为面板跑在 WPS 的内嵌浏览器里、与 Adelie 不同源,而 Adelie 明确不开 CORS。++改文档要用户点头:面板建的会话是**只读**的,读随便读,每一处改动都是一次用户要在侧栏里回答的审批。+替换与删除都能带一个 `expect`(那一段现在的原文),对不上就拒绝执行并回「段落已变,先重新读取」——+模型读到的段号是会过期的。++指令一次只跑一条、按顺序,因为同一份文档上两个写者会让两边都读不懂;面板始终不回话时,那一轮会报一句+看得懂的错,而不是一直卡着。++安装脚本 `install.mjs` 会写设置、把加载项交给 WPS、把桥登记成 Agent 的一个 MCP 服务器并自己连一次核对、+在 Windows 的启动文件夹放一个开机自启项、然后把桥拉起来。每一步都可以重复跑,所以**重跑就是修复**;+`uninstall.mjs` 是它的反面。设置、状态和 `bridge.log` 都在 `<数据根>/wps-bridge/` 下,**不放插件目录**+(插件更新会整体替换)。++**没有验证到的:WPS 那一侧本身。** 面板和桥这边都测过(桥、安装脚本、加载项托管走 `node --test`;+十四条浏览器测试让真面板跑在假 WPS 上),但功能区的按钮、任务窗格、文档接口只在装了 WPS 的机器上存在,+第一次必须发生在 Windows 上、并且当着 WPS 的面。diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex a9553784..63d6c2d3 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -40,6 +40,7 @@"@lmliheng/software-development": "workspace:*","@lmliheng/use-bento-slides": "workspace:*","@lmliheng/use-firecrawl": "workspace:*",+ "@lmliheng/use-wps-office": "workspace:*","@lmliheng/use-claude-code": "workspace:*","@lmliheng/wechat-miniprogram": "workspace:*","@prismshadow/agenthub": "^0.4.15",diff --git a/packages/core/package.json b/packages/core/package.jsonindex 6efad1e4..138729f1 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -73,6 +73,7 @@"@lmliheng/software-development": "workspace:*","@lmliheng/use-bento-slides": "workspace:*","@lmliheng/use-firecrawl": "workspace:*",+ "@lmliheng/use-wps-office": "workspace:*","@lmliheng/use-claude-code": "workspace:*","@lmliheng/wechat-miniprogram": "workspace:*","@prismshadow/agenthub": "^0.4.15",diff --git a/packages/core/test/plugins.test.ts b/packages/core/test/plugins.test.tsindex 4cfb94cf..362f4077 100644--- a/packages/core/test/plugins.test.ts+++ b/packages/core/test/plugins.test.ts@@ -65,7 +65,7 @@ describe("loadLibraryPlugins", () => {it("loads every plugin directory sorted by name, each with a date-sequence version and a category", () => {const plugins = loadLibraryPlugins();expect(plugins.map((p) => p.name)).toEqual([...plugins.map((p) => p.name)].sort());- expect(plugins.length).toBe(18);+ expect(plugins.length).toBe(19);for (const plugin of plugins) {expect(plugin.version, plugin.name).toMatch(PLUGIN_VERSION_PATTERN);expect(@@ -216,6 +216,7 @@ describe("groupPlugins / loadPluginGroups", () => {"requirements-box","use-bento-slides","use-firecrawl",+ "use-wps-office",]);expect(names("ai-app-development")).toEqual(["agent-development",diff --git a/packages/desktop/package.json b/packages/desktop/package.jsonindex b3814ec9..8285e560 100644--- a/packages/desktop/package.json+++ b/packages/desktop/package.json@@ -32,6 +32,7 @@"@lmliheng/software-development": "workspace:*","@lmliheng/use-bento-slides": "workspace:*","@lmliheng/use-firecrawl": "workspace:*",+ "@lmliheng/use-wps-office": "workspace:*","@lmliheng/use-claude-code": "workspace:*","@lmliheng/wechat-miniprogram": "workspace:*"},diff --git a/packages/docs/content/skills.en.md b/packages/docs/content/skills.en.mdindex feb281fa..ba64bcf5 100644--- a/packages/docs/content/skills.en.md+++ b/packages/docs/content/skills.en.md@@ -217,6 +217,7 @@ The built-in plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plu| --- | --- | --- || Office Productivity | `data-analysis` | Complete data-analysis tasks with bounded evidence inspection, explicit answer-changing decisions, native artifact handling and final output verification || | `use-firecrawl` | Web search and page scraping into clean markdown via the Firecrawl API |+| | `use-wps-office` | An Adelie side panel inside WPS Writer: read, search, replace, insert into and delete from the open document, with the same nine document operations exposed to the Agent as MCP tools (not preinstalled; needs WPS on Windows) || | `browser-automation` | Drive the desktop app's [Built-in Browser](/builtin-browser) with `penguin browser`: read pages as simplified HTML or text, act with JavaScript and trusted clicks and typing, and extract data such as Amazon orders, signed in with accounts imported from the system browser || | `use-bento-slides` | Author and edit Bento presentations: single-file `.bento.html` decks whose document is JSON, mapping material to charts, morph transitions and state slides || | `humanizer` | Strip AI-writing tells from prose in any language and rewrite it into the register of books, newspapers and encyclopedias (not preinstalled: install from the library when needed) |diff --git a/packages/docs/content/skills.zh.md b/packages/docs/content/skills.zh.mdindex cc69c26e..119784bd 100644--- a/packages/docs/content/skills.zh.md+++ b/packages/docs/content/skills.zh.md@@ -217,6 +217,7 @@ Agent 可以在 Task 中重写自己的 `SKILL.md`。结合 Benchmark 评估和| --- | --- | --- || 办公效率 | `data-analysis` | 完成数据分析任务:有限度地检查证据,明确决定是否修改答案,原生处理产出文件,并核验最终输出 || | `use-firecrawl` | 通过 Firecrawl API 搜索网页、抓取页面,输出干净的 markdown |+| | `use-wps-office` | 在 WPS 文字里开一个 Adelie 侧栏:读、搜、替换、插入、删除当前这篇文档,九个文档操作也作为 MCP 工具交给 Agent(不预装,需要 Windows 上的 WPS) || | `browser-automation` | 用 `penguin browser` 驱动桌面应用的[内置浏览器](/builtin-browser):以简化 HTML 或纯文本读取页面,用 JavaScript 以及可信的点击和输入操作页面,提取亚马逊订单这样的数据,登录状态可从系统浏览器导入 || | `use-bento-slides` | 创建和编辑 Bento 演示文稿:单文件 `.bento.html` 幻灯片,文件内容为 JSON,支持素材到图表的映射、morph 过渡和状态幻灯片 || | `humanizer` | 去除任何语言文字中的 AI 写作痕迹,改写成书籍、报纸和百科全书的语体(不预装:需要时从插件库安装) |diff --git a/plugins/README.md b/plugins/README.mdindex 5cfa42d4..9ac6b30c 100644--- a/plugins/README.md+++ b/plugins/README.md@@ -8,7 +8,7 @@ Included plugins, by category (`PLUGIN_CATEGORIES` in `packages/core/src/plugins| Category | Plugins || --- | --- |-| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` |+| Office Productivity | `data-analysis`, `use-firecrawl`, `browser-automation`, `use-bento-slides`, `use-wps-office`, `humanizer`, `goal`, `continual-learning`, `csu-mail`, `lesson-video`, `requirements-box` || Software Development | `software-development`, `use-claude-code`, `wechat-miniprogram` || AI App Development | `agent-development`, `model-development`, `skill-porting`, `agent-tuning` || Agent Company | `agent-company` |diff --git a/plugins/use-wps-office/LICENSE b/plugins/use-wps-office/LICENSEnew file mode 100644index 00000000..261eeb9e--- /dev/null+++ b/plugins/use-wps-office/LICENSE@@ -0,0 +1,201 @@+ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/plugins/use-wps-office/README.md b/plugins/use-wps-office/README.mdnew file mode 100644index 00000000..0304e29b--- /dev/null+++ b/plugins/use-wps-office/README.md@@ -0,0 +1,61 @@+# WPS(`@lmliheng/use-wps-office`)++把 Adelie 的对话搬进 **WPS 文字**:功能区多一个「Adelie」按钮,点开是侧栏——问它、让它读、让它改+当前这篇文档;同一套文档操作也作为 MCP 工具交给 Agent(`mcp__wps__*`)。++运行时就是一个**零依赖的 Node 文件**(`skills/wps-office/kit/serve.mjs`)。它同时是四样东西:++| 身份 | 接口 | 干什么 |+| --- | --- | --- |+| 面板的宿主 | `GET /addin/*` | 发加载项那一页(WPS 以「在线加载项」加载这个目录) |+| Agent 的手 | `GET /addin/commands`(SSE)+ `POST /addin/result`,以及 `POST /mcp` | 把文档操作下发给面板执行,一次只跑一条;同一个操作也作为 MCP 工具给 Adelie |+| Adelie 的客户端 | `GET /panel/state|history|events`,`POST /panel/session|ask|approve|abort` | 面板的对话;把 Adelie 的流归一成面板认识的几种事件 |+| WPS 的安装按钮 | `GET /publish`、`POST /publish/enable|disable` | 通过 WPS 自己的本机上架服务(`127.0.0.1:58890`)登记加载项 |++**为什么要中间这个桥**:面板跑在 WPS 的内嵌浏览器里,与 Adelie 不同源,而 Adelie 明确不开 CORS+(仅限同源)。桥就是那个「另一个源」——面板只跟它说话,它再跟 Adelie 说话。全程只走 `127.0.0.1`。++## 装++```bash+node skills/wps-office/kit/install.mjs+```++它写设置、把加载项交给 WPS(这一步 WPS 要开着)、把桥登记成 Agent 的一个 MCP 服务器并自检、+在 Windows 上放一个开机自启的 `.cmd`、然后把桥拉起来。**每一步都可以重复跑,重跑就是修复。**++诊断页:`http://127.0.0.1:3891/status`;安装按钮那一页:`/publish`。文件都在数据根的+`wps-bridge/`(设置、状态、`bridge.log`)——**不放插件目录**,因为插件更新会整体替换。++卸载:`node skills/wps-office/kit/uninstall.mjs`(加 `--purge` 连日志一起删)。++## 文件++| 路径 | 是什么 |+| --- | --- |+| `skills/wps-office/kit/serve.mjs` | 桥,也是这个插件的全部运行时 |+| `skills/wps-office/kit/adelie.mjs` | 找 Adelie、带令牌调它的 HTTP 客户端(`install.mjs` 也用) |+| `skills/wps-office/kit/wps.mjs` | WPS 本机上架服务(58890)的客户端 |+| `skills/wps-office/kit/install.mjs` / `uninstall.mjs` | 装与卸 |+| `skills/wps-office/kit/addin/` | 加载项本身:`manifest.xml`、`ribbon.xml`、面板页与文档操作层 |+| `skills/wps-office/SKILL.md` | Agent 读的说明书 |+| `test/` | 桥、安装脚本、加载项托管、面板冒烟四组测试 |++## 测试++```bash+node --test plugins/use-wps-office/test/ # 桥、安装脚本、加载项托管(不需要浏览器)+cd packages/web && npx playwright test -c ../../plugins/use-wps-office/test/playwright.config.mjs+ # 面板在 Chromium 里真的跑一遍(14 条)+```++面板那组跑的时候 `stub-wps.js` 会顶掉 WPS:假文档、假 Range、假任务窗格接口,所以没有 WPS 的+机器也能验。**真机上没验过的**:ribbon 按钮图标呈现、`CreateTaskPane`/`PluginStorage`/`app.Enum`+的真实行为、`app.Selection` 的字符偏移、`Documents.Add` 四参数的老版本兼容、IME 回车。这些只能+在 Windows + WPS 上跑第一次。++## 来源++加载项的清单形状、ribbon 回调写法、`InsertBreak` 的位置取法(段落标记之前一格)参考了 Apache-2.0+的文策 AI(`visresearch/WordAgent`,`frontend/wps_word_plugin/`)与其发布页+(`backend/gui/resources/publish.html`,58890 那套接口的出处);代码按本项目的契约重写,没有整段搬运。diff --git a/plugins/use-wps-office/icon.svg b/plugins/use-wps-office/icon.svgnew file mode 100644index 00000000..4b26abb8--- /dev/null+++ b/plugins/use-wps-office/icon.svg@@ -0,0 +1,10 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Adelie">+ <title>Adelie</title>+ <!-- Adelie 的插件图标。纯文本 SVG、无脚本、无外链:Adelie 的插件加载器把技能目录里的文件当+ 文本读进内存再安装到 Agent,二进制会被破坏。蓝色取 web-design 规范的 brand-500 #4285f4。 -->+ <rect x="0" y="0" width="64" height="64" rx="14" ry="14" fill="#4285f4" />+ <!-- 白色 A:两腿一笔画完,再加一根横杠 -->+ <path d="M14.5 51.5 32 12.5 49.5 51.5" fill="none" stroke="#ffffff" stroke-width="6.8"+ stroke-linecap="round" stroke-linejoin="round" />+ <path d="M19.6 40.2 44.4 40.2" fill="none" stroke="#ffffff" stroke-width="7.4" />+</svg>diff --git a/plugins/use-wps-office/package.json b/plugins/use-wps-office/package.jsonnew file mode 100644index 00000000..4076011a--- /dev/null+++ b/plugins/use-wps-office/package.json@@ -0,0 +1,33 @@+{+ "name": "@lmliheng/use-wps-office",+ "version": "0.3.8",+ "description": "Adelie inside WPS Writer: a dependency-free bridge that hosts a WPS add-on panel, lets the Agent read and edit the open document through MCP tools, and registers the add-on with WPS's own local publish service — loopback only.",+ "license": "Apache-2.0",+ "scripts": {+ "test": "node --test \"test/*.test.mjs\""+ },+ "repository": {+ "type": "git",+ "url": "git+https://github.com/lmliheng/Adelie.git",+ "directory": "plugins/use-wps-office"+ },+ "keywords": [+ "adelie-plugin",+ "penguin-harness",+ "wps",+ "office",+ "docx",+ "mcp",+ "addon"+ ],+ "files": [+ "plugin.json",+ "icon.svg",+ "README.md",+ "skills",+ "LICENSE"+ ],+ "publishConfig": {+ "access": "public"+ }+}diff --git a/plugins/use-wps-office/plugin.json b/plugins/use-wps-office/plugin.jsonnew file mode 100644index 00000000..13e1c8a4--- /dev/null+++ b/plugins/use-wps-office/plugin.json@@ -0,0 +1,9 @@+{+ "description": "Put an Adelie conversation inside WPS Writer. One dependency-free Node file is the whole runtime: it hosts the WPS add-on's panel, drives the open document through a local command channel that the panel executes, exposes nine document operations (read, search, replace, insert, delete, insert break, create, reveal) to the Agent as MCP tools, and registers the add-on with WPS through WPS's own local publish service. Everything stays on this machine — loopback only, no port opened to the network.",+ "description_zh": "把 Adelie 的对话搬进 WPS 文字。运行时就是一个零依赖的 Node 文件:它托管 WPS 加载项的面板页,用一条本机命令通道让面板去改那份打开的文档,把这九个文档操作(读、搜、替换、插入、删除、插分隔符、新建、定位)当作 MCP 工具交给 Agent,并通过 WPS 自己的本机上架服务登记加载项。全程不出这台机器,只走回环地址,不对网络开端口。",+ "short_description": "Adelie inside WPS Writer: a side panel that reads and edits the open document.",+ "short_description_zh": "在 WPS 文字里开一个 Adelie 侧栏,能读能改当前这篇文档。",+ "version": "2026.10.15.1",+ "category": "office-productivity",+ "preinstall": false+}diff --git a/plugins/use-wps-office/skills/wps-office/SKILL.md b/plugins/use-wps-office/skills/wps-office/SKILL.mdnew file mode 100644index 00000000..600dab58--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/SKILL.md@@ -0,0 +1,116 @@+---+name: wps-office+description: Put an Adelie conversation inside WPS Writer — a side panel in WPS that talks to an Adelie session, and nine document operations (summary, read, search, replace, insert, delete, break, create, reveal) exposed to the Agent as MCP tools so it can work on the document that is open on the person's screen. One dependency-free Node file is the whole runtime, and everything stays on the machine. Use when the user wants to install, run or repair the WPS panel, asks Adelie to read or edit a WPS document, wants the agent's answer written into the open .docx, or asks why the WPS panel is not showing up.+---++# WPS:在 WPS 文字里开一个 Adelie 侧栏++一套东西,两个身份:++- 对**用户**:WPS 功能区多一个「Adelie」按钮,点开是侧栏,能像聊天一样让它读、改当前这篇文档。+- 对**你(Agent)**:同一件事变成九个 `mcp__wps__*` 工具,你直接调就能改那份打开的文档。++桥(`kit/serve.mjs`,零依赖 Node)同时干四件事:托管加载项那页、下发文档指令给面板执行、+替面板跟 Adelie 说话、把加载项登记进 WPS。**它只绑 127.0.0.1,不对网络开端口。**++## Before you start++消息只是点名这个技能(比如「装 WPS 插件」)而没有具体的事,先问清楚三样:**哪台机器**(桥必须和+WPS 同机,因为 WPS 只往本机地址取加载项)、**端口**(默认 3891,撞了才换)、**要不要开机自启**。++还有一件必须先讲明白:**这套东西的加载项只能在 WPS 上跑,当前没有 Windows + WPS 的真机就没法+验收**。你可以把桥跑起来、把加载项登记进去、让 Agent 侧全部验通,但「WPS 里那个按钮长什么样、+点开有没有侧栏」只有用户在 WPS 里亲眼看到才算数。装之前把这句话说清楚,别让用户以为你已经替他看过。++## 结论先行++| 你要的 | 哪一步 | 产物 |+| --- | --- | --- |+| 跑起来 | `node <技能目录>/kit/install.mjs` | 写设置、登记加载项、装 MCP、起桥、留开机自启 |+| 用户能用 | 打开 WPS,点功能区「Adelie」 | 侧栏(面板页由桥托管) |+| 你改文档 | 调 `mcp__wps__*` 工具 | 直接改那份打开的文档 |+| 出问题 | `http://127.0.0.1:3891/status` 与 `wps-bridge/bridge.log` | 桥 / WPS / 面板各自的状态 |+| 不要了 | `node <技能目录>/kit/uninstall.mjs` | 摘掉加载项与 MCP 条目,日志默认留着 |++## 一、装++```bash+node <技能目录>/kit/install.mjs # 装(或重装 = 修复)+node <技能目录>/kit/serve.mjs --status # 只看状态,什么都不改+```++install 做五件事,**每一步都可以重复跑**(重跑就是修复):写 `config.json`、把加载项交给 WPS+(通过 WPS 自己的本机上架服务 58890,所以**这时 WPS 得开着**)、把桥登记成 Agent 的一个 MCP+服务器并自己连一次自检、在 Windows 的启动文件夹里放一个开机自启的 `.cmd`、把桥拉起来。++参数:`--port`(默认 3891)、`--root`(Adelie 数据根,默认按 `ADELIE_HOME`/`~/.adelie/data` 找)、+`--adelie`(Adelie 的地址,默认自动发现)、`--project` / `--agent`(哪个项目、哪个 Agent 拥有这个+对话,默认第一个项目 + `default_agent`)、`--no-mcp` / `--no-wps` / `--no-autostart` / `--no-start`+(跳过对应的那一步)。++WPS 没开着时第 2 步会跳过并告诉用户怎么办:先打开 WPS,再重跑,或者打开+`http://127.0.0.1:3891/publish` 点一下「安装 / 修复」。++## 二、装完之后,用户看到什么++- WPS 功能区出现「Adelie」组,点一下开/收侧栏。+- 侧栏顶部写着当前文档名与段数;下面是对话,输入框在底下。+- 面板**按文档认会话**:同一份文档打开的是同一个 Adelie 会话,换一份文档就是一个新会话。+- 面板建的会话是 **`read-only` 模式**:读随便读,**改动会弹审批**——用户点「允许」才动文档。+- 回复气泡下面有一粒「写进文档」,把这一轮的回答按段落插到当前光标处。++## 三、你(Agent)怎么改文档++九个工具,段落号**从 1 开始**,指的是最近一次读取时那份文档的段落:++| 工具 | 干什么 | 只读? |+| --- | --- | --- |+| `mcp__wps__document_summary` | 文档名、路径、段数、当前选区 | 是 |+| `mcp__wps__read_document` | 按段落读正文(`from`/`to`,缺省全文,一次最多 400 段) | 是 |+| `mcp__wps__search_document` | 按文本找段落(大小写不敏感的子串) | 是 |+| `mcp__wps__replace_paragraph` | 替换某一段正文,保留段落样式 | 否 |+| `mcp__wps__insert_paragraph_after` | 在某段之后插一段 | 否 |+| `mcp__wps__delete_paragraph` | 删某一段 | 否 |+| `mcp__wps__insert_break` | 在某段之后插分隔符(`line`/`page`/`section`) | 否 |+| `mcp__wps__create_document` | 新建一篇空白 docx 并切过去 | 否 |+| `mcp__wps__reveal_paragraph` | 把视图滚到某段并选中它 | 是 |++规矩(写进工具描述里了,这里也说一遍):++1. **动手前先读**:`document_summary` 确认是哪份文档,`read_document` / `search_document` 拿到段号。+2. **改的时候带上 `expect`**:写入当前那段的原文,对不上就拒绝执行并回「段落已变,先重新读取」。+ 这是防呆——用户的段号可能已经因为别处的编辑变了。收到了就重新读一遍再改。+3. **改完再读一次确认**,别把「工具没报错」当成「文档改对了」。+4. 写工具都是 `rw`:在 `read-only` 会话里会自动升级成需要用户批准。用户拒绝时不要绕道去改,+ 问他要不要换个做法。+5. 段落里不能有换行——`replace_paragraph` 一次只写一段;要写多段就一段一段插。++## 四、出问题按这个顺序看++1. `http://127.0.0.1:3891/status`(人看的页)或 `/status.json`(机器看的):桥在不在、Adelie 连没连上、+ WPS 上架服务通不通、加载项登记了没、面板连没连。+2. `<数据根>/wps-bridge/bridge.log`:桥每次请求都记一行,包括面板报上来的错误。+3. `node <技能目录>/kit/serve.mjs --status`:命令行版的同一份诊断(不用起服务)。+4. 常见几种:**WPS 里没有 Adelie 那一栏** → 加载项没登记(重跑 install,WPS 要开着)。+ **侧栏说「未连接」** → 桥没跑(重跑 install 的起桥那步)。**说「还没连上 Adelie」** → Adelie+ 本体没开。**点发送没反应、工具都报「WPS 里没有打开 Adelie 侧栏」** → WPS 里那个面板页没开。++## 五、卸载++```bash+node <技能目录>/kit/uninstall.mjs # 摘掉加载项与 MCP 条目,保留设置和日志+node <技能目录>/kit/uninstall.mjs --purge # 连 <数据根>/wps-bridge/ 一起删+```++它会停用加载项、从 Agent 配置里移除 `wps` 这个 MCP 服务器、删掉开机自启的 `.cmd`。+**正在跑的桥进程不在它的职责里**——那是托管面板页的进程,告诉用户关掉那个最小化的窗口即可。++## 六、红线++- 桥只绑 `127.0.0.1`。**不要**为了让别的机器连上来改成 `0.0.0.0` 或做端口转发——这等于把+ 「改用户文档」的能力放到网络上。+- 面板那句「允许」就是用户对自己文档的授权。**不要**替用户批准,也不要把 `approvalMode`+ 改成 `allow-all` 图省事。+- 用户的文档不是你的草稿纸:不确定要改哪一段就问,不要靠猜段号去试。+- 这是**用户机器的**安装:装完把 `install.mjs` 打印的那几行(端口、加载项地址、诊断地址)+ 原样告诉用户,别只说「装好了」。diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/README.md b/plugins/use-wps-office/skills/wps-office/kit/addin/README.mdnew file mode 100644index 00000000..acd90fc8--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/README.md@@ -0,0 +1,54 @@+# WPS 加载项(面板侧)++这一份是真正传进 WPS 的「在线加载项」:WPS 打开 `http://127.0.0.1:<端口>/addin/index.html`,+页面与桥同源,所以普通的 `fetch` / `EventSource` 就能说话。面板零依赖 —— 原生 ES 模块 + 原生 DOM,+没有框架、没有 CDN、没有外链资源,在 WPS 的任务窗格(Chromium 内核)和普通浏览器里都能跑。++两侧的来源:**桥**是 `kit/serve.mjs`(同一个插件包的另一个目录,负责静态文件、`/addin/*` 指令通道、+`/panel/*` Adelie 代理、`/mcp` 文档工具);**这一侧**按 `ADDIN-PROTOCOL.md` 写。ribbon 回调的形状、+段落范围取法(`max(Start, End - 1)`)、`Range.Delete()` 之后再写入新文本、`InsertBreak` 的枚举值,+参考了 Apache-2.0 许可的文策 AI(WenCe)WPS 加载项的 `frontend/wps_word_plugin/`(`manifest.xml`、+`public/ribbon.xml`、`src/components/ribbon.js`、`src/components/js/docxJsonConverter.js`);+代码是按本契约重写的,没有整段搬运,涉及的文件头都写了出处。++## 文件++| 文件 | 做什么 |+| --- | --- |+| `manifest.xml` | WPS JsPlugin 清单:`Name` 为 `Adelie`、`Url` 留空、`IconUrl` 指向 `images/icon.svg`,`Application Name="wps"` 挂 `ribbon.xml` 与一个 420px 的任务窗格 |+| `ribbon.xml` | `customUI`:一个 `btnAdeliePanel` 按钮,回调 `ribbon.OnAddinLoad / OnAction / GetImage` |+| `index.html` | 面板本体(任务窗格那一页,也能在浏览器里独立打开)。所有资源都是相对路径 |+| `panel.js` | `window.ribbon`(WPS 宿主调用)+ 上下文本地报送、命令通道、聊天流、写回文档 |+| `panel.css` | 面板样式,按 `web-design` 规范:单一蓝色强调、浅色/纯黑两套、发丝边框,宽度 380–420px |+| `wps-api.js` | 契约 §3 的九个 `doc.*` 操作,只用白名单里的 WPS API,每个调用 try/catch |+| `stub-wps.js` | 没有 WPS 时假装一个(只给测试和本地调试用),`window.wps` / `window.Application` 都在这里 |+| `images/icon.svg` | 加载项图标:ADELIE 蓝底 + 白色 A。用文本 SVG 而不是 PNG —— 加载项目录会被当文本读进内存,二进制会被 UTF-8 解码破坏 |++## 本地怎么跑、怎么调++```sh+# 1. 用假桥把这一页和它的接口一起发出来(假桥在同一个包的另一处:test/fake-bridge.mjs)+node test/fake-bridge.mjs # 默认 127.0.0.1:3891++# 2. 浏览器打开(页面里没有 WPS,会自动 import stub-wps.js)+open http://127.0.0.1:3891/addin/index.html+open 'http://127.0.0.1:3891/addin/index.html?stub=1' # 就算宿主有 wps 也强制用假实现++# 3. 浏览器冒烟测试(14 条,覆盖 ribbon、命令通道、聊天流、九个文档操作、深浅色)+cd packages/web+npx playwright test -c ../../plugins/wps-office/test/playwright.config.mjs+PANEL_BASE_URL=http://127.0.0.1:3892/ … # 换端口(同时给 config 和 spec)+```++## 在 WPS 真机上没验证到的地方++- ribbon 的实际呈现:按钮图标(`getImage` 返回相对路径 `images/icon.svg`)、`size="large"` 的排版,+ 以及 `CreateTaskPane` / `PluginStorage` / `app.Enum` 在真机上的行为,只能由 Windows + WPS 上跑第一次。+- `app.Selection`:契约 §2.1 要报选区,但 §3 的白名单里没有它,这里按 Word 兼容的+ `app.Selection.Range.Start/End/Text` 读取,读不到就把 `selection` 报成 `null`(不报错)。真机上要确认+ 这两个字段是否就是段落定位用的字符偏移。+- `para.Range.End` 是否总是「段落标记之后一格」(替换时按 `End - 1` 留出段落标记):Word 语义如此,+ 文策 AI 的实现也这么用,但 WPS 各版本可能有出入。+- `range.InsertBreak()` 的枚举:优先取 `app.Enum` / `wps.Enum`,取不到就用 `wdLineBreak = 6`、+ `wdPageBreak = 7`、`wdSectionBreakNextPage = 2`。+- `doc.create` 里 `Documents.Add('', false, 0, true)` 的四个参数(老版本会退化到无参数调用)。diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/images/icon.svg b/plugins/use-wps-office/skills/wps-office/kit/addin/images/icon.svgnew file mode 100644index 00000000..114d9284--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/images/icon.svg@@ -0,0 +1,9 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Adelie">+ <title>Adelie</title>+ <!-- 加载项功能区按钮与清单里的图标,与插件根目录那份同一张图。+ 纯文本 SVG:这个目录会被 Adelie 的插件加载器当文本读进内存,二进制会被破坏。 -->+ <rect x="0" y="0" width="64" height="64" rx="14" ry="14" fill="#4285f4" />+ <path d="M14.5 51.5 32 12.5 49.5 51.5" fill="none" stroke="#ffffff" stroke-width="6.8"+ stroke-linecap="round" stroke-linejoin="round" />+ <path d="M19.6 40.2 44.4 40.2" fill="none" stroke="#ffffff" stroke-width="7.4" />+</svg>diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/index.html b/plugins/use-wps-office/skills/wps-office/kit/addin/index.htmlnew file mode 100644index 00000000..fe15eeda--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/index.html@@ -0,0 +1,119 @@+<!doctype html>+<html lang="zh-CN">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>Adelie · WPS 助手</title>+ <link rel="stylesheet" href="panel.css" />+ </head>+ <body>+ <div class="app" id="app">+ <header class="topbar">+ <span class="brand">+ <img class="brand-mark" src="images/icon.svg" alt="" width="24" height="24" />+ <span class="brand-name">Adelie</span>+ </span>+ <span class="spacer"></span>+ <span class="conn" id="conn">+ <span class="dot" id="conn-dot" aria-hidden="true"></span>+ <span class="conn-text" id="conn-text">连接中…</span>+ </span>+ <button+ class="icon-btn"+ id="thinking-toggle"+ type="button"+ aria-pressed="true"+ aria-label="显示或隐藏思考过程"+ >+ <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false">+ <path+ d="M8 1.5a4.5 4.5 0 0 1 2.6 8.2c-.5.4-.8 1-.8 1.6v.2H6.2v-.2c0-.6-.3-1.2-.8-1.6A4.5 4.5 0 0 1 8 1.5Z"+ fill="none"+ stroke="currentColor"+ stroke-width="1.3"+ stroke-linejoin="round"+ />+ <path+ d="M6.4 13.2h3.2"+ fill="none"+ stroke="currentColor"+ stroke-width="1.3"+ stroke-linecap="round"+ />+ </svg>+ </button>+ <button class="icon-btn" id="theme" type="button" aria-label="切换到深色">+ <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false">+ <path+ d="M8 3.2a4.8 4.8 0 1 0 4.8 4.8A4.8 4.8 0 0 0 8 3.2Zm0 -2.2v1.6M8 13v1.6M1.4 8H3M13 8h1.6M3.4 3.4l1.1 1.1M11.5 11.5l1.1 1.1M12.6 3.4l-1.1 1.1M4.5 11.5l-1.1 1.1"+ fill="none"+ stroke="currentColor"+ stroke-width="1.3"+ stroke-linecap="round"+ />+ </svg>+ </button>+ </header>++ <p class="doc-line" id="doc-line">正在读取文档…</p>+ <p class="session-line caption" id="session-line"></p>++ <section class="contexts" id="contexts" role="group" aria-label="提问时带上的上下文">+ <button class="chip" type="button" data-context="selection" aria-pressed="true">+ 选中内容+ </button>+ <button class="chip" type="button" data-context="document" aria-pressed="false">+ 整篇文档+ </button>+ <button class="chip" type="button" data-context="none" aria-pressed="false">+ 不带上下文+ </button>+ </section>++ <main+ class="messages"+ id="messages"+ role="log"+ aria-live="polite"+ aria-label="与 Adelie 的对话"+ tabindex="-1"+ >+ <div class="empty" id="empty">+ <p class="eyebrow">WPS 助手</p>+ <h1 class="empty-title">让 Adelie 直接改这篇文档</h1>+ <p class="empty-sub">说清要改哪里,它读完选中的段落再动手;改动会落在文档里。</p>+ <div class="examples">+ <button class="chip example" type="button" data-example="把第 2 段的标题改得更简洁一些">+ 把第 2 段的标题改得更简洁+ </button>+ <button+ class="chip example"+ type="button"+ data-example="通读全文,指出前后不一致的地方"+ >+ 通读全文,指出前后不一致的地方+ </button>+ <button class="chip example" type="button" data-example="在结尾加一段三点式总结">+ 在结尾加一段三点式总结+ </button>+ </div>+ </div>+ </main>++ <form class="composer" id="composer">+ <label class="sr-only" for="input">对 Adelie 说</label>+ <textarea id="input" rows="1" placeholder="让 Adelie 改这篇文档…"></textarea>+ <div class="composer-foot">+ <span class="hint">Enter 发送 · Shift+Enter 换行</span>+ <span class="spacer"></span>+ <button class="btn secondary" id="abort" type="button" hidden>停止</button>+ <button class="btn primary" id="send" type="submit">发送</button>+ </div>+ </form>++ <p class="disclaimer">改动由 Adelie 在你自己的电脑上写入这篇文档;写入前请先看清内容。</p>+ </div>+ <div class="toasts" id="toasts" aria-live="polite"></div>+ <script type="module" src="panel.js"></script>+ </body>+</html>diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/manifest.xml b/plugins/use-wps-office/skills/wps-office/kit/addin/manifest.xmlnew file mode 100644index 00000000..0435b488--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/manifest.xml@@ -0,0 +1,27 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ Adelie 的 WPS 加载项清单(契约 §0、§6)。+ 形状照 Apache-2.0 的文策 AI(WenCe)WPS 加载项 frontend/wps_word_plugin/manifest.xml 的结构写:+ <Applications><Application Name="wps"> + RibbonXml + TaskPanes。Url 按要求留空,+ 图标指向本目录里的 images/icon.svg(文本 SVG,不用二进制)。+-->+<JsPlugin>+ <ApiVersion>1.0.0</ApiVersion>+ <Name>Adelie</Name>+ <Version>1.0.0</Version>+ <Description>Adelie 文档助手:在 WPS 文字里读、搜、改这篇文档</Description>+ <Author>Adelie</Author>+ <Url></Url>+ <HelpUrl></HelpUrl>+ <IconUrl>images/icon.svg</IconUrl>++ <!-- WPS 文字(wps)支持 -->+ <Applications>+ <Application Name="wps">+ <RibbonXml>ribbon.xml</RibbonXml>+ <TaskPanes>+ <TaskPane Label="Adelie" Url="index.html" Width="420" Visible="false" />+ </TaskPanes>+ </Application>+ </Applications>+</JsPlugin>diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/panel.css b/plugins/use-wps-office/skills/wps-office/kit/addin/panel.cssnew file mode 100644index 00000000..e48cc4a9--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/panel.css@@ -0,0 +1,619 @@+/*+ * Adelie WPS 面板的样式 —— 按 web-design 规范:GitHub 风的简洁、单一蓝色强调、+ * 浅色与纯黑两套、用发丝边框而不是阴影。面板按 380–420px 宽设计。+ */++:root {+ color-scheme: light;+ --brand-50: #e8f0fe;+ --brand-100: #d2e3fc;+ --brand-300: #8ab4f8;+ --brand-500: #4285f4;+ --brand-600: #1a73e8;+ --brand-700: #0b57d0;++ --gray-50: #f9fafb;+ --gray-100: #f3f4f6;+ --gray-200: #e5e7eb;+ --gray-300: #d1d5db;+ --gray-400: #9ca3af;+ --gray-500: #6b7280;+ --gray-600: #4b5563;+ --gray-900: #111827;++ --bg: #ffffff;+ --surface: #ffffff;+ --border: var(--gray-200);+ --control-border: var(--gray-300);+ --fg: var(--gray-900);+ --fg-muted: var(--gray-600);+ --fg-faint: var(--gray-500);+ --accent-bg: #111827;+ --accent-fg: #ffffff;+ --ok: #15803d;+ --warn: #b45309;+ --danger: #b91c1c;+ --danger-bg: #fef2f2;+ --bubble-bg: var(--gray-100);++ --radius-control: 6px;+ --radius-card: 12px;+ --radius-pill: 9999px;+ --ease: cubic-bezier(0.2, 0.7, 0.3, 1);+}++.dark {+ color-scheme: dark;+ --bg: #000000;+ --surface: #0d0d0d;+ --border: #1f1f1f;+ --control-border: #303030;+ --fg: #f3f4f6;+ --fg-muted: #9ca3af;+ --fg-faint: #6b7280;+ --accent-bg: #f3f4f6;+ --accent-fg: #111827;+ --brand-600: #8ab4f8;+ --brand-700: #8ab4f8;+ --ok: #4ade80;+ --warn: #fbbf24;+ --danger: #f87171;+ --danger-bg: #450a0a;+ --bubble-bg: #1f1f1f;+}++* {+ box-sizing: border-box;+}++[hidden] {+ display: none !important;+}++html,+body {+ height: 100%;+}++body {+ margin: 0;+ background: var(--bg);+ color: var(--fg);+ font-family:+ ui-sans-serif,+ system-ui,+ -apple-system,+ "Segoe UI",+ Roboto,+ "PingFang SC",+ "Microsoft YaHei",+ sans-serif;+ font-size: 14px;+ line-height: 1.5;+ -webkit-font-smoothing: antialiased;+ display: flex;+ justify-content: center;+}++code,+kbd {+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ font-size: 12px;+}++.caption {+ font-size: 12px;+ color: var(--fg-faint);+}++.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++.spacer {+ flex: 1;+}++:focus-visible {+ outline: 3px solid rgb(107 114 128 / 0.4);+ outline-offset: 2px;+}++/* ---------- 骨架 ---------- */++.app {+ display: flex;+ flex-direction: column;+ width: 100%;+ max-width: 420px;+ height: 100dvh;+ min-height: 0;+ border-left: 1px solid var(--border);+ border-right: 1px solid var(--border);+ background: var(--bg);+}++.topbar {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 12px;+ border-bottom: 1px solid var(--border);+}++.brand {+ display: inline-flex;+ align-items: center;+ gap: 8px;+}++.brand-mark {+ width: 24px;+ height: 24px;+ border-radius: 6px;+ display: block;+}++.brand-name {+ font-size: 15px;+ font-weight: 600;+ letter-spacing: -0.025em;+}++.conn {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 12px;+ color: var(--fg-muted);+ cursor: default;+}++.dot {+ width: 7px;+ height: 7px;+ border-radius: var(--radius-pill);+ background: var(--gray-400);+}++.dot.on {+ background: var(--ok);+}++.icon-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 32px;+ height: 32px;+ padding: 0;+ border: 1px solid transparent;+ border-radius: var(--radius-control);+ background: transparent;+ color: var(--fg-muted);+ cursor: pointer;+ transition:+ color 150ms var(--ease),+ background-color 150ms var(--ease),+ border-color 150ms var(--ease);+}++.icon-btn:hover {+ background: var(--gray-100);+ color: var(--fg);+}++.dark .icon-btn:hover {+ background: #1f1f1f;+}++.icon-btn[aria-pressed="false"] {+ color: var(--fg-faint);+}++.doc-line {+ margin: 0;+ padding: 8px 12px 0;+ font-size: 12px;+ color: var(--fg-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.session-line {+ margin: 0;+ padding: 2px 12px 0;+ min-height: 0;+}++.contexts {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ padding: 8px 12px 10px;+ border-bottom: 1px solid var(--border);+}++.chip {+ border: 1px solid var(--border);+ border-radius: var(--radius-pill);+ background: transparent;+ color: var(--fg-muted);+ padding: 4px 10px;+ min-height: 28px;+ font-size: 12px;+ font-family: inherit;+ cursor: pointer;+ transition:+ color 150ms var(--ease),+ background-color 150ms var(--ease),+ border-color 150ms var(--ease);+}++.chip:hover {+ background: var(--gray-50);+}++.dark .chip:hover {+ background: #141414;+}++.chip[aria-pressed="true"] {+ background: var(--brand-50);+ border-color: var(--brand-100);+ color: var(--brand-700);+}++.dark .chip[aria-pressed="true"] {+ background: #10203a;+ border-color: #1b3a63;+ color: var(--brand-300);+}++/* ---------- 对话区 ---------- */++.messages {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 12px;+ display: flex;+ flex-direction: column;+ gap: 10px;+ scrollbar-width: thin;+ scrollbar-color: var(--control-border) transparent;+}++.messages:focus {+ outline: none;+}++.empty {+ margin: auto 0;+ text-align: center;+ padding: 12px 4px;+ background-image: radial-gradient(rgb(26 115 232 / 0.14) 1px, transparent 1px);+ background-size: 22px 22px;+ background-position: center;+}++.eyebrow {+ margin: 0 0 6px;+ font-size: 11px;+ font-weight: 600;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--brand-700);+}++.empty-title {+ margin: 0 0 6px;+ font-size: 18px;+ font-weight: 600;+ letter-spacing: -0.025em;+}++.empty-sub {+ margin: 0 0 12px;+ font-size: 13px;+ color: var(--fg-muted);+}++.examples {+ display: grid;+ gap: 6px;+}++.chip.example {+ text-align: left;+ border-radius: var(--radius-control);+ padding: 8px 10px;+}++.msg.user {+ align-self: flex-end;+ max-width: 85%;+ background: var(--bubble-bg);+ border-radius: 12px;+ padding: 8px 14px;+ white-space: pre-wrap;+ word-break: break-word;+}++.msg.assistant {+ align-self: stretch;+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.turn-text {+ white-space: pre-wrap;+ word-break: break-word;+}++.turn-text > .caption {+ color: var(--fg-faint);+}++.turn-tools {+ display: flex;+ flex-direction: column;+ gap: 2px;+}++.turn-tools:empty {+ display: none;+}++.tool-line {+ margin: 0;+ font-size: 12px;+ color: var(--fg-faint);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.tool-name {+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ color: var(--fg-muted);+}++.tool-summary {+ margin-left: 6px;+}++.tool-line[data-state="running"] .tool-name::before {+ content: "● ";+ color: var(--warn);+}++.tool-line[data-state="done"] .tool-name::before {+ content: "✓ ";+ color: var(--ok);+}++.tool-line[data-state="failed"] .tool-name::before {+ content: "✕ ";+ color: var(--danger);+}++.thinking {+ border-left: 2px solid var(--border);+ padding-left: 10px;+ font-size: 13px;+ color: var(--fg-muted);+}++.thinking > summary {+ cursor: pointer;+ font-size: 12px;+ color: var(--fg-faint);+}++.thinking-body {+ white-space: pre-wrap;+ word-break: break-word;+ margin-top: 4px;+}++.hide-thinking .thinking {+ display: none;+}++.turn-actions:empty {+ display: none;+}++.turn-actions {+ display: flex;+ gap: 6px;+}++.approval {+ border: 1px solid var(--border);+ border-radius: var(--radius-card);+ padding: 10px 12px;+ background: var(--surface);+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.approval-title {+ margin: 0;+ font-size: 13px;+ font-weight: 600;+}++.approval-summary {+ margin: 0;+ font-size: 12px;+ color: var(--fg-muted);+ white-space: pre-wrap;+ word-break: break-word;+ max-height: 12rem;+ overflow-y: auto;+ scrollbar-width: thin;+}++.approval.answered {+ border-style: dashed;+}++.approval-actions {+ display: flex;+ gap: 6px;+}++.error-line {+ margin: 0;+ padding: 8px 10px;+ border-radius: var(--radius-control);+ background: var(--danger-bg);+ color: var(--danger);+ font-size: 13px;+ white-space: pre-wrap;+ word-break: break-word;+}++/* ---------- 输入区 ---------- */++.composer {+ margin: 0 12px;+ border: 1px solid var(--control-border);+ border-radius: var(--radius-card);+ background: var(--surface);+ padding: 8px 10px 6px;+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.composer:focus-within {+ border-color: var(--gray-400);+ box-shadow: 0 0 0 2px rgb(156 163 175 / 0.3);+}++.composer textarea {+ border: 0;+ resize: none;+ padding: 0;+ font: inherit;+ color: inherit;+ background: transparent;+ min-height: 22px;+ max-height: 160px;+ outline: none;+}++.composer-foot {+ display: flex;+ align-items: center;+ gap: 6px;+}++.hint {+ font-size: 11px;+ color: var(--fg-faint);+}++.btn {+ border-radius: var(--radius-control);+ padding: 6px 12px;+ min-height: 32px;+ font-size: 13px;+ font-weight: 500;+ font-family: inherit;+ cursor: pointer;+ transition:+ color 150ms var(--ease),+ background-color 150ms var(--ease),+ border-color 150ms var(--ease),+ opacity 150ms var(--ease);+}++.btn.primary {+ background: var(--accent-bg);+ color: var(--accent-fg);+ border: 1px solid var(--accent-bg);+}++.btn.primary:hover {+ opacity: 0.9;+}++.btn.secondary {+ background: var(--surface);+ color: var(--fg);+ border: 1px solid var(--control-border);+}++.btn.secondary:hover {+ background: var(--gray-100);+}++.dark .btn.secondary:hover {+ background: #1f1f1f;+}++.btn:disabled {+ opacity: 0.5;+ cursor: default;+}++.disclaimer {+ margin: 8px 12px 10px;+ font-size: 11px;+ line-height: 1.45;+ color: var(--fg-faint);+}++/* ---------- 提示条 ---------- */++.toasts {+ position: fixed;+ right: 12px;+ bottom: 12px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ pointer-events: none;+}++.toast {+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 10px 14px;+ font-size: 13px;+ animation: toast-in 280ms var(--ease);+}++@keyframes toast-in {+ from {+ opacity: 0;+ transform: translateY(10px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++@media (prefers-reduced-motion: reduce) {+ * {+ animation: none !important;+ transition: none !important;+ }+}diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/panel.js b/plugins/use-wps-office/skills/wps-office/kit/addin/panel.jsnew file mode 100644index 00000000..c681fbef--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/panel.js@@ -0,0 +1,828 @@+/**+ * Adelie WPS 面板 —— 任务窗格里的那一页(契约 §1 ribbon、§2 桥接口)+ *+ * 零依赖:原生 ES 模块 + 原生 DOM,没有框架、没有 CDN、没有外链资源。它同时要在+ * WPS 的任务窗格(Chromium 内核)和普通浏览器里跑:前者由 WPS 注入 window.wps,+ * 后者由 stub-wps.js 顶上(契约 §0、§4)。+ *+ * 三件事:+ * 1. window.ribbon —— WPS 宿主直接调,负责开关这个任务窗格(契约 §1)。+ * 2. 上下文本地报送 + 命令通道 —— 文档概况报给桥,桥推来的 doc.* 命令由 wps-api.js 执行(§2.1–2.3)。+ * 3. 聊天 —— 建会话、发问、流式回显、审批、把回复写进文档(§2.4)。+ */+import { runOperation } from "./wps-api.js";++const PANEL_VERSION = "1.0.0";+const TASKPANE_KEY = "adelie_taskpane_id";+const TASKPANE_WIDTH = 420; // 面板按 380–420px 宽设计(契约 §6)+const DOC_WATCH_INTERVAL = 1500; // 检查文档/选区变化的间隔+const HELLO_DEBOUNCE = 500; // 变化后 500ms 防抖再上报(契约 §2.1)+const EVENT_NAMES = ["status", "delta", "thinking", "tool", "approval", "done", "error"];+const THEME_KEY = "adelie.wps.theme";+const THINKING_KEY = "adelie.wps.thinking";+const CONTEXT_KEY = "adelie.wps.context";++/* ------------------------------------------------------------------ *+ * 普通浏览器里没有 WPS:装上假实现(契约 §4)+ * ------------------------------------------------------------------ */+const forcedStub = new URLSearchParams(location.search).has("stub");+if (forcedStub || (!window.wps && !window.Application)) {+ await import("./stub-wps.js");+}++/* ------------------------------------------------------------------ *+ * ribbon(契约 §1)—— WPS 宿主调用 window.ribbon+ * ------------------------------------------------------------------ */++function ribbonOnAddinLoad(ribbonUI) {+ try {+ window.Application.ribbonUI = ribbonUI;+ if (!window.Application.Enum || typeof window.Application.Enum !== "object") {+ // 老版本 WPS 不提供 app.Enum,补上任务窗格停靠需要的两个值。+ window.Application.Enum = { msoCTPDockPositionLeft: 0, msoCTPDockPositionRight: 2 };+ }+ log("info", "Adelie 加载项已就绪");+ return true;+ } catch (error) {+ console.error("[adelie] ribbon OnAddinLoad 失败:", error);+ log("error", "Adelie 加载项初始化失败", { message: String(error?.message ?? error) });+ return false;+ }+}++function ribbonOnAction(control) {+ const id = control?.Id ?? control?.id;+ if (id !== "btnAdeliePanel") return true;+ try {+ const app = window.Application;+ const paneId = app.PluginStorage.getItem(TASKPANE_KEY);+ if (!paneId) {+ const pane = app.CreateTaskPane(location.origin + "/addin/index.html", "Adelie");+ app.PluginStorage.setItem(TASKPANE_KEY, pane.ID);+ pane.DockPosition = app.Enum?.msoCTPDockPositionRight ?? 2;+ // 先把窗格显示出来再改宽度(WPS 已知的顺序坑,契约 §1)+ pane.Visible = true;+ pane.Width = window.devicePixelRatio * TASKPANE_WIDTH;+ } else {+ const pane = app.GetTaskPane(paneId);+ pane.Visible = !pane.Visible;+ pane.Width = window.devicePixelRatio * TASKPANE_WIDTH;+ }+ return true;+ } catch (error) {+ console.error("[adelie] 打开面板失败:", error);+ log("error", "打开 Adelie 面板失败", { message: String(error?.message ?? error) });+ return true;+ }+}++function ribbonGetImage() {+ // 图标就在加载项目录里,面板与桥同源,相对路径即可(契约 §1)。+ // 用 SVG 而不是 PNG:这个加载项目录会被插件加载器当文本读进内存,二进制会被 UTF-8 解码破坏。+ return "images/icon.svg";+}++window.ribbon = {+ OnAddinLoad: ribbonOnAddinLoad,+ OnAction: ribbonOnAction,+ GetImage: ribbonGetImage,+};++/* ------------------------------------------------------------------ *+ * 与桥说话(契约 §2)+ * ------------------------------------------------------------------ */++const BRIDGE = {+ async request(path, { method = "GET", body } = {}) {+ const init = { method, headers: {} };+ if (body !== undefined) {+ init.headers["content-type"] = "application/json";+ init.body = JSON.stringify(body);+ }+ let response;+ try {+ response = await fetch(path, init);+ } catch (error) {+ throw new Error(`连不上 Adelie 桥(${path}):${error?.message ?? error}`);+ }+ const raw = await response.text();+ let payload = null;+ if (raw) {+ try {+ payload = JSON.parse(raw);+ } catch (error) {+ payload = null;+ }+ }+ if (!response.ok) {+ throw new Error(payload?.error ? String(payload.error) : `桥返回 HTTP ${response.status}`);+ }+ if (payload && payload.ok === false) {+ throw new Error(payload.error ? String(payload.error) : "桥没有说清失败原因");+ }+ return payload ?? { ok: true };+ },+};++/** 诊断日志(契约 §2.3);日志本身失败不再上报,免得套娃。 */+function log(level, message, data) {+ try {+ void fetch("/addin/log", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ level, message, data: data ?? {} }),+ }).catch(() => {});+ } catch (error) {+ // 桥不在也没关系。+ }+ const sink = level === "error" ? console.error : level === "warn" ? console.warn : console.log;+ sink(`[adelie] ${message}`, data ?? "");+}++/* ------------------------------------------------------------------ *+ * 面板状态+ * ------------------------------------------------------------------ */++const state = {+ doc: null, // 最近一次 doc.summary 的结果+ adelie: null, // 桥报上来的 Adelie 连接信息+ session: null, // { sessionId, projectId, model, running }+ connected: false,+ commandsConnected: false,+ eventsConnected: false,+ running: false, // 桥说它在忙(status 事件)+ sending: false, // 刚才那条 /panel/ask 还在飞+ context: "selection", // selection | document | none+ tail: 120,+ showThinking: true,+ fingerprint: "",+ debounce: null,+ turn: null, // 当前这一轮回复的 DOM 片段+ approvals: [], // 还没答的审批卡片+};++const dom = {};++function initDom() {+ dom.root = document.getElementById("app");+ dom.docLine = document.getElementById("doc-line");+ dom.sessionLine = document.getElementById("session-line");+ dom.connDot = document.getElementById("conn-dot");+ dom.connText = document.getElementById("conn-text");+ dom.theme = document.getElementById("theme");+ dom.contexts = document.getElementById("contexts");+ dom.messages = document.getElementById("messages");+ dom.empty = document.getElementById("empty");+ dom.form = document.getElementById("composer");+ dom.input = document.getElementById("input");+ dom.send = document.getElementById("send");+ dom.abort = document.getElementById("abort");+ dom.toasts = document.getElementById("toasts");+ dom.thinkingToggle = document.getElementById("thinking-toggle");+}++function el(tag, props = {}, children = []) {+ const node = document.createElement(tag);+ for (const [key, value] of Object.entries(props)) {+ if (value === undefined || value === null) continue;+ if (key === "class") node.className = value;+ else if (key === "text") node.textContent = value;+ else if (key === "html") node.innerHTML = value;+ else if (key.startsWith("on") && typeof value === "function") {+ node.addEventListener(key.slice(2).toLowerCase(), value);+ } else if (key === "dataset") {+ for (const [dataKey, dataValue] of Object.entries(value)) node.dataset[dataKey] = dataValue;+ } else {+ node.setAttribute(key, value);+ }+ }+ for (const child of [].concat(children)) {+ if (child === null || child === undefined || child === false) continue;+ node.append(typeof child === "string" ? document.createTextNode(child) : child);+ }+ return node;+}++function toast(message) {+ const node = el("div", { class: "toast", role: "status", text: message });+ dom.toasts.append(node);+ setTimeout(() => node.remove(), 3600);+}++/* ------------------------------------------------------------------ *+ * 文档上下文本地报送(契约 §2.1)+ * ------------------------------------------------------------------ */++async function collectDocument() {+ try {+ return await runOperation("doc.summary", {});+ } catch (error) {+ log("warn", "读取文档概况失败", { message: String(error?.message ?? error) });+ return null;+ }+}++function fingerprintOf(doc) {+ if (!doc) return "none";+ const selection = doc.selection ? `${doc.selection.from}-${doc.selection.to}` : "-";+ return [doc.name, doc.path, doc.paragraphs, selection].join("|");+}++async function sendHello(reason) {+ state.doc = await collectDocument();+ renderDocLine();+ try {+ const response = await BRIDGE.request("/addin/hello", {+ method: "POST",+ body: {+ doc: state.doc,+ panel: { version: PANEL_VERSION, ua: navigator.userAgent },+ },+ });+ state.adelie = response?.adelie ?? null;+ setConnected(true);+ } catch (error) {+ setConnected(false, String(error?.message ?? error));+ log("warn", "上报文档概况失败", { reason, message: String(error?.message ?? error) });+ }+ state.fingerprint = fingerprintOf(state.doc);+}++function startDocumentWatch() {+ setInterval(() => {+ void (async () => {+ const doc = await collectDocument();+ const fingerprint = fingerprintOf(doc);+ state.doc = doc;+ renderDocLine();+ if (fingerprint === state.fingerprint) return;+ // 选区或文档变了:500ms 防抖后再上报(契约 §2.1)+ state.fingerprint = fingerprint;+ clearTimeout(state.debounce);+ state.debounce = setTimeout(() => void sendHello("change"), HELLO_DEBOUNCE);+ })();+ }, DOC_WATCH_INTERVAL);+}++/* ------------------------------------------------------------------ *+ * 命令通道(契约 §2.2)+ * ------------------------------------------------------------------ */++function startCommandChannel() {+ const source = new EventSource("/addin/commands");+ const answered = new Set();+ const queue = [];+ let busy = false;++ const pump = () => {+ if (busy) return;+ const command = queue.shift();+ if (!command) return;+ busy = true;+ void (async () => {+ let payload;+ try {+ const result = await runOperation(command.op, command.args ?? {});+ payload = { id: command.id, ok: true, result };+ } catch (error) {+ // 失败也要回答(契约 §2.2)+ payload = { id: command.id, ok: false, error: String(error?.message ?? error) };+ }+ try {+ await BRIDGE.request("/addin/result", { method: "POST", body: payload });+ } catch (error) {+ log("error", "回答命令失败", { id: command.id, message: String(error?.message ?? error) });+ showErrorLine(`回答文档命令失败:${error?.message ?? error}`);+ }+ log(payload.ok ? "info" : "warn", `文档命令 ${command.op} ${payload.ok ? "完成" : "失败"}`, {+ id: command.id,+ ...(payload.ok ? { result: payload.result } : { error: payload.error }),+ });+ if (payload.ok && command.op !== "doc.summary") scheduleHello();+ busy = false;+ pump();+ })();+ };++ source.onmessage = (event) => {+ let command = null;+ try {+ command = JSON.parse(event.data);+ } catch (error) {+ log("warn", "收到看不懂的命令", { raw: String(event.data).slice(0, 200) });+ return;+ }+ if (!command || command.id === undefined || command.id === null) {+ log("warn", "命令没有 id,没法回答", { raw: String(event.data).slice(0, 200) });+ return;+ }+ if (answered.has(command.id)) return; // 同一个 id 只能回答一次+ answered.add(command.id);+ queue.push(command);+ pump();+ };+ source.onopen = () => {+ state.commandsConnected = true;+ renderConnection();+ };+ source.onerror = () => {+ // EventSource 会自己重连,这里只更新界面上的状态。+ state.commandsConnected = false;+ renderConnection();+ };+ return source;+}++/** 文档被命令改过之后,把新的概况补报一次(桥靠它校验改动)。 */+function scheduleHello() {+ clearTimeout(state.debounce);+ state.debounce = setTimeout(() => void sendHello("command"), HELLO_DEBOUNCE);+}++/* ------------------------------------------------------------------ *+ * 聊天(契约 §2.4)+ * ------------------------------------------------------------------ */++function startEventStream() {+ const source = new EventSource("/panel/events");+ const handle = (name, event) => {+ let data = {};+ try {+ data = event.data ? JSON.parse(event.data) : {};+ } catch (error) {+ log("warn", "收到看不懂的流事件", { name, raw: String(event.data).slice(0, 200) });+ return;+ }+ applyEvent(name, data);+ };+ for (const name of EVENT_NAMES) source.addEventListener(name, (event) => handle(name, event));+ // 桥若用默认事件名并把类型放在载荷里,也认。+ source.onmessage = (event) => {+ let data = {};+ try {+ data = event.data ? JSON.parse(event.data) : {};+ } catch (error) {+ return;+ }+ const name =+ typeof data?.type === "string"+ ? data.type+ : typeof data?.event === "string"+ ? data.event+ : "";+ if (EVENT_NAMES.includes(name)) applyEvent(name, data);+ };+ source.onopen = () => {+ state.eventsConnected = true;+ renderConnection();+ };+ source.onerror = () => {+ state.eventsConnected = false;+ renderConnection();+ };+ return source;+}++function applyEvent(name, data) {+ switch (name) {+ case "status":+ setRunning(Boolean(data?.running));+ break;+ case "delta":+ appendDelta(typeof data?.text === "string" ? data.text : "");+ break;+ case "thinking":+ appendThinking(typeof data?.text === "string" ? data.text : "");+ break;+ case "tool":+ appendToolLine(data ?? {});+ break;+ case "approval":+ showApproval(data ?? {});+ break;+ case "done":+ finishTurn(typeof data?.text === "string" ? data.text : "");+ break;+ case "error":+ showErrorLine(String(data?.message ?? "Adelie 报了一个没有说明的错误"));+ setRunning(false);+ break;+ default:+ break;+ }+}++function ensureTurn() {+ if (state.turn) return state.turn;+ dom.empty?.setAttribute("hidden", "hidden");+ const text = el("div", { class: "turn-text" });+ const tools = el("div", { class: "turn-tools" });+ const thinkingBody = el("div", { class: "thinking-body" });+ const thinkingWrap = el("details", { class: "thinking" }, [+ el("summary", {}, [el("span", { text: "思考过程" })]),+ thinkingBody,+ ]);+ thinkingWrap.hidden = true;+ const actions = el("div", { class: "turn-actions" });+ const bubble = el("article", { class: "msg assistant", role: "article" }, [+ thinkingWrap,+ tools,+ text,+ actions,+ ]);+ dom.messages.append(bubble);+ state.turn = {+ bubble,+ textEl: text,+ text: "",+ toolsEl: tools,+ thinkingWrap,+ thinkingBody,+ thinkingText: "",+ actions,+ };+ scrollToBottom();+ return state.turn;+}++function appendDelta(chunk) {+ if (!chunk && state.turn) return;+ const turn = ensureTurn();+ turn.text += chunk;+ turn.textEl.textContent = turn.text;+ if (chunk && turn.thinkingWrap && !turn.thinkingWrap.hidden) turn.thinkingWrap.open = false;+ scrollToBottom();+}++function appendThinking(chunk) {+ if (!state.showThinking) return;+ const turn = ensureTurn();+ turn.thinkingText += chunk;+ turn.thinkingWrap.hidden = false;+ turn.thinkingBody.textContent = turn.thinkingText;+ scrollToBottom();+}++function appendToolLine(data) {+ const turn = ensureTurn();+ const name = String(data?.name ?? "工具");+ const summary = data?.summary ? String(data.summary) : "";+ const stateName = ["running", "done", "failed"].includes(data?.state) ? data.state : "running";+ let line = turn.toolsEl.querySelector(`[data-tool-id="${data?.id ?? name}"]`);+ if (!line) {+ line = el("p", { class: "tool-line", dataset: { toolId: data?.id ?? name } }, [+ el("span", { class: "tool-name", text: name }),+ el("span", { class: "tool-summary", text: summary }),+ ]);+ turn.toolsEl.append(line);+ } else {+ line.querySelector(".tool-summary").textContent = summary;+ }+ line.dataset.state = stateName;+ scrollToBottom();+}++function finishTurn(finalText) {+ const turn = ensureTurn();+ if (finalText) turn.text = finalText;+ turn.textEl.textContent = turn.text;+ setRunning(false);+ if (turn.thinkingWrap && turn.thinkingText) turn.thinkingWrap.open = false;+ if (!turn.actions.querySelector(".write-btn")) {+ const write = el("button", {+ class: "btn secondary write-btn",+ type: "button",+ text: "写进文档",+ onclick: () => void writeTurnIntoDocument(turn),+ });+ turn.actions.append(write);+ }+ if (!turn.text.trim())+ turn.textEl.append(el("span", { class: "caption", text: "(这一轮没有文字回复)" }));+ scrollToBottom();+}++function showApproval(data) {+ const toolCallId = data?.toolCallId ? String(data.toolCallId) : "";+ const name = String(data?.name ?? "工具");+ const summary = data?.summary ? String(data.summary) : "";+ const actions = el("div", { class: "approval-actions" });+ const card = el(+ "div",+ { class: "approval", role: "alertdialog", "aria-label": `需要允许:${name}` },+ [+ el("p", { class: "approval-title", text: `${name} 需要你的允许` }),+ el("p", { class: "approval-summary", text: summary }),+ actions,+ ],+ );+ const approve = el("button", { class: "btn primary", type: "button", text: "允许" });+ const deny = el("button", { class: "btn secondary", type: "button", text: "拒绝" });+ const answer = async (decision) => {+ approve.disabled = true;+ deny.disabled = true;+ try {+ await BRIDGE.request("/panel/approve", { method: "POST", body: { toolCallId, decision } });+ card.replaceChildren(+ el("p", {+ class: "caption",+ text: decision === "allow" ? `已允许 ${name}` : `已拒绝 ${name}`,+ }),+ );+ card.classList.add("answered");+ } catch (error) {+ showErrorLine(`回答审批失败:${error?.message ?? error}`);+ approve.disabled = false;+ deny.disabled = false;+ }+ state.approvals = state.approvals.filter((item) => item.card !== card);+ };+ approve.addEventListener("click", () => void answer("allow"));+ deny.addEventListener("click", () => void answer("deny"));+ actions.append(approve, deny);+ dom.messages.append(card);+ state.approvals.push({ card, deny: () => void answer("deny") });+ scrollToBottom();+ approve.focus();+}++function showErrorLine(message) {+ const line = el("p", { class: "error-line", role: "alert", text: message });+ dom.messages.append(line);+ scrollToBottom();+}++async function sendMessage() {+ const text = dom.input.value.trim();+ if (!text || state.running || state.sending) return;+ appendUserMessage(text);+ dom.input.value = "";+ autoGrow();+ state.turn = null;+ // 只在这条请求飞出去之前锁一下,防连点;之后是「忙」还是「闲」由桥的 status 事件说了算(契约 §2.4)+ setSending(true);+ try {+ await BRIDGE.request("/panel/ask", {+ method: "POST",+ body: { text, context: state.context, tail: state.tail },+ });+ } catch (error) {+ showErrorLine(`发送失败:${error?.message ?? error}`);+ } finally {+ setSending(false);+ }+}++function appendUserMessage(text) {+ dom.empty?.setAttribute("hidden", "hidden");+ dom.messages.append(el("article", { class: "msg user", role: "article" }, [el("div", { text })]));+ scrollToBottom();+}++function appendHistoryMessage(message) {+ const role = message?.role === "user" ? "user" : "assistant";+ const text = String(message?.text ?? "");+ if (!text) return;+ dom.empty?.setAttribute("hidden", "hidden");+ if (role === "user") appendUserMessage(text);+ else+ dom.messages.append(+ el("article", { class: "msg assistant" }, [el("div", { class: "turn-text", text })]),+ );+}++let historyLoaded = false;++/** 面板打开时把这篇文档已经聊过的内容补上,用户才看得到上下文。 */+async function loadHistory() {+ if (historyLoaded) return;+ historyLoaded = true;+ try {+ const response = await BRIDGE.request("/panel/history?limit=50");+ for (const message of response?.messages ?? []) appendHistoryMessage(message);+ scrollToBottom();+ } catch (error) {+ log("warn", "读取历史失败", { message: String(error?.message ?? error) });+ }+}++async function abortTurn() {+ try {+ await BRIDGE.request("/panel/abort", { method: "POST" });+ setRunning(false);+ toast("已请求停止");+ } catch (error) {+ showErrorLine(`停止失败:${error?.message ?? error}`);+ }+}++async function writeTurnIntoDocument(turn) {+ const text = turn.text.trim();+ if (!text) {+ toast("这一轮没有可写入的文字");+ return;+ }+ const doc = state.doc ?? (await collectDocument());+ let index = doc?.selection?.to ?? doc?.paragraphs ?? 1;+ const lines = text+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ try {+ for (const line of lines) {+ const result = await runOperation("doc.insertAfter", { index, text: line });+ index = result.index;+ }+ await runOperation("doc.reveal", { index: Math.max(1, index - lines.length + 1) });+ toast(`已写入 ${lines.length} 段`);+ scheduleHello();+ } catch (error) {+ showErrorLine(`写入文档失败:${error?.message ?? error}`);+ }+}++async function ensureSession() {+ try {+ const current = await BRIDGE.request("/panel/state");+ state.adelie = current?.adelie ?? state.adelie;+ state.session = current?.session ?? null;+ } catch (error) {+ log("warn", "读取面板状态失败", { message: String(error?.message ?? error) });+ }+ if (!state.session) {+ try {+ const created = await BRIDGE.request("/panel/session", { method: "POST" });+ state.session = {+ sessionId: created?.sessionId ?? "",+ projectId: created?.projectId ?? "",+ model: created?.model ?? "",+ running: false,+ };+ } catch (error) {+ log("warn", "建立会话失败", { message: String(error?.message ?? error) });+ showErrorLine(`还没连上 Adelie:${error?.message ?? error}`);+ }+ }+ renderSessionLine();+ void loadHistory();+}++/* ------------------------------------------------------------------ *+ * 界面+ * ------------------------------------------------------------------ */++function setConnected(connected, message) {+ state.connected = connected;+ renderConnection(message);+ renderDocLine();+}++function renderConnection(message) {+ dom.connDot?.classList.toggle("on", state.connected);+ if (!dom.connText) return;+ dom.connText.textContent = state.connected ? "已连接 Adelie" : "未连接";+ dom.connText.title = state.connected+ ? `桥:${state.adelie?.origin ?? location.origin}`+ : (message ?? "没有连上 Adelie 桥,文档命令收不到");+}++function renderDocLine() {+ if (!dom.docLine) return;+ const doc = state.doc;+ if (!doc) {+ dom.docLine.textContent = "没读到文档(先在 WPS 里打开一篇)";+ return;+ }+ const name = doc.name || "未命名文档";+ const selection = doc.selection ? ` · 选中第 ${doc.selection.from}–${doc.selection.to} 段` : "";+ dom.docLine.textContent = `${name} · ${doc.paragraphs} 段${selection}`;+ dom.docLine.title = doc.path || name;+}++function renderSessionLine() {+ if (!dom.sessionLine) return;+ dom.sessionLine.textContent = state.session?.model ? `模型 ${state.session.model}` : "";+}++function setRunning(running) {+ state.running = running;+ renderSendState();+}++/** 发送请求在飞的这一小段时间:防连点,但不改变「桥说它还在忙」这个状态。 */+function setSending(sending) {+ state.sending = sending;+ renderSendState();+}++function renderSendState() {+ const busy = state.running || state.sending;+ if (dom.send) dom.send.disabled = busy;+ if (dom.abort) dom.abort.hidden = !state.running;+ if (dom.input) dom.input.placeholder = busy ? "Adelie 正在处理…" : "让 Adelie 改这篇文档…";+}++function scrollToBottom() {+ if (dom.messages) dom.messages.scrollTop = dom.messages.scrollHeight;+}++function autoGrow() {+ if (!dom.input) return;+ dom.input.style.height = "auto";+ dom.input.style.height = `${Math.min(dom.input.scrollHeight, 160)}px`;+}++function setContext(context) {+ state.context = context;+ localStorage.setItem(CONTEXT_KEY, context);+ for (const chip of dom.contexts.querySelectorAll(".chip")) {+ chip.setAttribute("aria-pressed", String(chip.dataset.context === context));+ }+}++function setThinking(show) {+ state.showThinking = show;+ localStorage.setItem(THINKING_KEY, show ? "1" : "0");+ if (dom.thinkingToggle) dom.thinkingToggle.setAttribute("aria-pressed", String(show));+ if (dom.messages) dom.messages.classList.toggle("hide-thinking", !show);+}++function initTheme() {+ const stored = localStorage.getItem(THEME_KEY);+ const preferred = window.matchMedia?.("(prefers-color-scheme: dark)").matches ? "dark" : "light";+ applyTheme(stored || preferred);+}++function applyTheme(theme) {+ document.documentElement.classList.toggle("dark", theme === "dark");+ localStorage.setItem(THEME_KEY, theme);+ if (dom.theme)+ dom.theme.setAttribute("aria-label", theme === "dark" ? "切换到浅色" : "切换到深色");+}++function bindUi() {+ dom.form.addEventListener("submit", (event) => {+ event.preventDefault();+ void sendMessage();+ });+ dom.input.addEventListener("input", autoGrow);+ dom.input.addEventListener("keydown", (event) => {+ if (event.key !== "Enter" || event.shiftKey) return;+ // 中文输入法组字时的回车只是上屏,不能当发送(IME 安全,见 web-design 规范)+ if (event.isComposing || event.keyCode === 229) return;+ event.preventDefault();+ void sendMessage();+ });+ dom.abort.addEventListener("click", () => void abortTurn());+ dom.theme.addEventListener("click", () => {+ applyTheme(document.documentElement.classList.contains("dark") ? "light" : "dark");+ });+ dom.contexts.addEventListener("click", (event) => {+ const chip = event.target.closest(".chip");+ if (chip?.dataset.context) setContext(chip.dataset.context);+ });+ dom.thinkingToggle.addEventListener("click", () => setThinking(!state.showThinking));+ for (const button of document.querySelectorAll("[data-example]")) {+ button.addEventListener("click", () => {+ dom.input.value = button.dataset.example;+ autoGrow();+ dom.input.focus();+ });+ }+ document.addEventListener("keydown", (event) => {+ if (event.key !== "Escape" || !state.approvals.length) return;+ // Esc 关掉最上面那张审批卡片(等同拒绝),焦点回到对话区+ const pending = state.approvals.pop();+ pending.deny();+ dom.messages.focus();+ });+}++/* ------------------------------------------------------------------ *+ * 启动+ * ------------------------------------------------------------------ */++function boot() {+ initDom();+ bindUi();+ initTheme();+ setContext(localStorage.getItem(CONTEXT_KEY) || "selection");+ setThinking(localStorage.getItem(THINKING_KEY) !== "0");+ setRunning(false);+ renderDocLine();++ startDocumentWatch();+ startCommandChannel();+ startEventStream();+ // 先报文档再建会话:桥按文档认会话,反过来的话第一次开面板会撞上「还没有打开文档」。+ void (async () => {+ await sendHello("boot");+ await ensureSession();+ })();+}++if (document.readyState === "loading") {+ document.addEventListener("DOMContentLoaded", boot);+} else {+ boot();+}diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/ribbon.xml b/plugins/use-wps-office/skills/wps-office/kit/addin/ribbon.xmlnew file mode 100644index 00000000..92be0047--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/ribbon.xml@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="UTF-8"?>+<!--+ Adelie 的 ribbon:一个「Adelie」按钮,点一下开/收侧栏面板(契约 §1)。+ 回调都挂在 window.ribbon 上(panel.js 里赋值),写法与 Apache-2.0 的文策 AI(WenCe)+ WPS 加载项 public/ribbon.xml + src/components/ribbon.js 一致。+-->+<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" onLoad="ribbon.OnAddinLoad">+ <ribbon startFromScratch="false">+ <tabs>+ <tab id="adelieTab" label="Adelie">+ <group id="adelieGroup" label="Adelie">+ <button+ id="btnAdeliePanel"+ label="Adelie"+ size="large"+ onAction="ribbon.OnAction"+ getImage="ribbon.GetImage"+ enabled="true"+ visible="true"+ />+ </group>+ </tab>+ </tabs>+ </ribbon>+</customUI>diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/stub-wps.js b/plugins/use-wps-office/skills/wps-office/kit/addin/stub-wps.jsnew file mode 100644index 00000000..6e507ea8--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/stub-wps.js@@ -0,0 +1,367 @@+/**+ * 浏览器里假装 WPS —— 只给 Playwright 冒烟测试和本地调试用(契约 §4)。+ *+ * 面板在真 WPS 里拿 `window.wps` / `window.Application` 干活;在没有 WPS 的普通浏览器里,+ * panel.js 会动态 import 这个文件,于是同一份面板代码能跑通全部 op。假实现忠实执行契约 §3+ * 的语义(`expect` 不匹配必须报错、写操作改的是同一段、段落号 1 起),因为测试靠它判定+ * 面板是不是真的按契约改了「文档」。+ *+ * 模型:每篇文档是一串段落 `[{ text, style }]`,每一段在字符缓冲里占 `text + "\r"`,+ * 与 Word/WPS 的 Range 位置一致(第 1 段从 0 开始)。范围位置在文档被改动后不跟随,+ * 而 WPS 那边每次都会重新取,面板也是,够用。+ *+ * 顺带把 ribbon 用到的几个宿主接口也做出来(CreateTaskPane / GetTaskPane / PluginStorage /+ * Enum),这样在没有 WPS 的浏览器里点「Adelie」按钮的判断逻辑也能被测到。+ */++const PARAGRAPH_MARK = "\r";+const DEFAULT_STYLE = "正文";++const ENUM = {+ msoCTPDockPositionLeft: 0,+ msoCTPDockPositionRight: 2,+ wdLineBreak: 6,+ wdPageBreak: 7,+ wdSectionBreakNextPage: 2,+};++function clamp(value, min, max) {+ return Math.min(Math.max(value, min), max);+}++function sampleParagraphs() {+ return [+ { text: "季度报告草稿", style: "标题 1" },+ { text: "一、本季度概况", style: "标题 2" },+ { text: "本季度共交付三个版本,用户反馈集中在加载速度上。", style: "正文" },+ { text: "二、下一步计划", style: "标题 2" },+ { text: "十一月完成性能专项,十二月发布年度总结。", style: "正文" },+ ];+}++class FakeDoc {+ constructor({ name = "未命名.docx", path = "", paragraphs = [] } = {}) {+ this.name = name;+ this.path = path;+ this.paragraphs = paragraphs.length+ ? paragraphs.map((item) => ({+ text: String(item.text ?? ""),+ style: String(item.style ?? DEFAULT_STYLE),+ }))+ : [{ text: "", style: DEFAULT_STYLE }];+ this.selection = { start: 0, end: 0 };+ }++ /** 整篇文档的字符缓冲:每段是 `text + "\r"`。 */+ get buffer() {+ return this.paragraphs.map((item) => item.text + PARAGRAPH_MARK).join("");+ }++ /** 第 index 段(1 起)的起始字符位置。 */+ paraStart(index) {+ let start = 0;+ for (let i = 1; i < index; i += 1) start += this.paragraphs[i - 1].text.length + 1;+ return start;+ }++ /** 某个字符位置落在第几段(1 起)。 */+ paragraphIndexAt(position) {+ let start = 0;+ for (let i = 0; i < this.paragraphs.length; i += 1) {+ const end = start + this.paragraphs[i].text.length + 1;+ if (position < end) return i + 1;+ start = end;+ }+ return this.paragraphs.length;+ }++ clampSelection() {+ // 范围右端可以正好落在文档末尾(Range.End == 内容长度),所以按长度而不是长度 - 1 收边。+ const last = this.buffer.length;+ this.selection = {+ start: clamp(this.selection.start, 0, last),+ end: clamp(this.selection.end, 0, last),+ };+ if (this.selection.end < this.selection.start) this.selection.end = this.selection.start;+ }++ setSelection(start, end) {+ this.selection = {+ start: clamp(start, 0, this.buffer.length),+ end: clamp(end, 0, this.buffer.length),+ };+ this.clampSelection();+ }++ /** 把 [from, to) 换成 text —— `.Text` 写入与 `.Delete()` 都走这里。 */+ splice(from, to, text) {+ const buffer = this.buffer;+ const a = clamp(from, 0, buffer.length);+ const b = clamp(to, a, buffer.length);+ const oldParagraphs = this.paragraphs.map((item) => ({ ...item }));+ const oldStarts = oldParagraphs.map((_, index) => this.paraStart(index + 1));++ const next = buffer.slice(0, a) + text + buffer.slice(b);+ const tailStart = a + text.length; // 插入文本之后那些旧内容的新起点+ const shift = text.length - (b - a);++ const parts = next.split(PARAGRAPH_MARK);+ if (parts.length > 1 && parts[parts.length - 1] === "") parts.pop(); // 末尾那个标记不额外算一段++ const rebuilt = [];+ let position = 0;+ for (const part of parts) {+ // 段落样式按「这一段在旧缓冲里来自哪一段」来定:改动之前的位置原样、之后的位置补位移、+ // 插入文本自身沿用插入点所在的段落。删掉段落标记时,后一段因此接管前一段的样式(与 Word 一致)。+ const oldPosition = position < a ? position : position >= tailStart ? position - shift : a;+ rebuilt.push({ text: part, style: styleAt(oldParagraphs, oldStarts, oldPosition) });+ position += part.length + 1;+ }+ this.paragraphs = rebuilt.length ? rebuilt : [{ text: "", style: oldParagraphs[0].style }];+ this.clampSelection();+ }++ /** range.InsertParagraphAfter():在 position 处切开该段,后半段沿用样式。 */+ insertParagraphAfter(position) {+ const index = this.paragraphIndexAt(position);+ const paragraph = this.paragraphs[index - 1];+ const offset = clamp(position - this.paraStart(index), 0, paragraph.text.length);+ this.paragraphs.splice(+ index - 1,+ 1,+ { text: paragraph.text.slice(0, offset), style: paragraph.style },+ { text: paragraph.text.slice(offset), style: paragraph.style },+ );+ this.clampSelection();+ }++ /** range.InsertBreak(type):文本里留下的字符与 Word 一样 —— 分页 \f、分节 \n、换行 \v。 */+ insertBreak(position, type) {+ const character = type === 7 ? "\f" : [2, 3, 4, 5].includes(type) ? "\n" : "\v";+ this.splice(position, position, character);+ }+}++function styleAt(oldParagraphs, oldStarts, position) {+ let index = 0;+ for (let i = 0; i < oldStarts.length; i += 1) {+ if (oldStarts[i] <= position) index = i;+ }+ return oldParagraphs[Math.min(index, oldParagraphs.length - 1)].style;+}++class FakeRange {+ constructor(doc, start, end) {+ this.doc = doc;+ this.start = start;+ this.end = end;+ }++ get Start() {+ return this.start;+ }++ get End() {+ return this.end;+ }++ get Text() {+ return this.doc.buffer.slice(this.start, this.end);+ }++ set Text(value) {+ const text = String(value ?? "");+ this.doc.splice(this.start, this.end, text);+ this.end = this.start + text.length;+ }++ Delete() {+ this.doc.splice(this.start, this.end, "");+ this.end = this.start;+ }++ InsertParagraphAfter() {+ this.doc.insertParagraphAfter(this.end);+ }++ InsertBreak(type) {+ this.doc.insertBreak(this.end, type);+ }++ Select() {+ this.doc.setSelection(this.start, this.end);+ }+}++function paragraphObject(doc, index) {+ if (!Number.isInteger(index) || index < 1 || index > doc.paragraphs.length) {+ throw new Error(`段落 ${index} 不存在`);+ }+ return {+ get Range() {+ const start = doc.paraStart(index);+ return new FakeRange(doc, start, start + doc.paragraphs[index - 1].text.length + 1);+ },+ get Style() {+ const name = doc.paragraphs[index - 1].style;+ return { NameLocal: name, Name: name };+ },+ set Style(value) {+ const name = typeof value === "string" ? value : (value?.NameLocal ?? value?.Name);+ if (name) doc.paragraphs[index - 1].style = String(name);+ },+ };+}++function documentObject(doc) {+ return {+ get Name() {+ return doc.name;+ },+ get FullName() {+ return doc.path;+ },+ get DocID() {+ return doc.name;+ },+ Paragraphs: {+ get Count() {+ return doc.paragraphs.length;+ },+ Item: (index) => paragraphObject(doc, index),+ },+ Range: (start, end) => new FakeRange(doc, start, end),+ Activate() {},+ };+}++function selectionObject(doc) {+ return {+ get Start() {+ return doc.selection.start;+ },+ get End() {+ return doc.selection.end;+ },+ get Text() {+ return doc.buffer.slice(doc.selection.start, doc.selection.end);+ },+ get Range() {+ return new FakeRange(doc, doc.selection.start, doc.selection.end);+ },+ };+}++/** 装上假 WPS:返回内部状态与几个给测试用的小工具。 */+export function installStubWps(win = window) {+ const state = {+ documents: [+ new FakeDoc({+ name: "季度报告.docx",+ path: "C:\\Users\\Me\\Documents\\季度报告.docx",+ paragraphs: sampleParagraphs(),+ }),+ ],+ active: 0,+ pluginStorage: new Map(),+ taskPanes: new Map(),+ nextTaskPaneId: 1,+ };++ function activeDoc() {+ return state.documents[state.active] ?? null;+ }++ const app = {+ get ActiveDocument() {+ const doc = activeDoc();+ return doc ? documentObject(doc) : null;+ },+ Documents: {+ get Count() {+ return state.documents.length;+ },+ Item(index) {+ const doc = state.documents[Number(index) - 1];+ if (!doc) throw new Error(`文档 ${index} 不存在`);+ return documentObject(doc);+ },+ Add(name) {+ const doc = new FakeDoc({ name: name || `文档${state.documents.length + 1}.docx` });+ state.documents.push(doc);+ state.active = state.documents.length - 1;+ return documentObject(doc);+ },+ },+ get Selection() {+ const doc = activeDoc();+ return doc ? selectionObject(doc) : null;+ },+ get Enum() {+ return ENUM;+ },+ CreateTaskPane(url, title) {+ const id = `fake-pane-${state.nextTaskPaneId}`;+ state.nextTaskPaneId += 1;+ const pane = { ID: id, Url: url, Caption: title, Visible: false, Width: 0, DockPosition: -1 };+ state.taskPanes.set(id, pane);+ return pane;+ },+ GetTaskPane(id) {+ const pane = state.taskPanes.get(id);+ if (!pane) throw new Error(`任务窗格 ${id} 不存在`);+ return pane;+ },+ PluginStorage: {+ getItem: (key) => (state.pluginStorage.has(key) ? state.pluginStorage.get(key) : null),+ setItem: (key, value) => {+ state.pluginStorage.set(key, value);+ },+ removeItem: (key) => {+ state.pluginStorage.delete(key);+ },+ },+ };++ win.wps = { WpsApplication: () => app, Enum: ENUM };+ win.Application = app;++ const helpers = {+ app,+ state,+ activeDocument() {+ const doc = activeDoc();+ return {+ name: doc.name,+ path: doc.path,+ paragraphs: doc.paragraphs.map((item) => ({ ...item })),+ selection: { ...doc.selection },+ };+ },+ paragraphTexts() {+ return activeDoc().paragraphs.map((item) => item.text);+ },+ setParagraphs(paragraphs) {+ const doc = activeDoc();+ doc.paragraphs = paragraphs.map((item) => ({+ text: String(item.text ?? ""),+ style: String(item.style ?? DEFAULT_STYLE),+ }));+ doc.selection = { start: 0, end: 0 };+ },+ selectParagraphs(from, to = from) {+ const doc = activeDoc();+ const start = doc.paraStart(from);+ const end = doc.paraStart(to) + doc.paragraphs[to - 1].text.length;+ doc.setSelection(start, end);+ },+ selectText(start, end) {+ activeDoc().setSelection(start, end);+ },+ };++ win.__fakeWps = helpers;+ return helpers;+}++installStubWps();diff --git a/plugins/use-wps-office/skills/wps-office/kit/addin/wps-api.js b/plugins/use-wps-office/skills/wps-office/kit/addin/wps-api.jsnew file mode 100644index 00000000..bfbdf1dd--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/addin/wps-api.js@@ -0,0 +1,546 @@+/**+ * Adelie WPS 加载项 —— 文档操作层(契约 §3 的每个 op 都在这里)+ *+ * 这一层只碰契约 §3「允许使用的 WPS API」白名单里的属性与方法;每个调用都包在+ * try/catch 里,属性缺失时抛出一句能读懂的错,绝不静默返回成功。段落号一律 1 起+ * (doc.Paragraphs.Item(i) 的 i)。所有写操作返回改完之后的**同一段落**信息。+ *+ * 出处:分段取 Range、Range.Delete() 之后再写入新文本、以及 InsertBreak 的位置取法+ * (取段落标记之前一格:max(Start, End - 1)),参考了 Apache-2.0 许可的文策 AI(WenCe)+ * WPS 加载项的 frontend/wps_word_plugin/src/components/js/docxJsonConverter.js+ * (editDocxParagraph / insertBreakAfterParagraph / deleteDocxPara)。代码为按本契约重写,+ * 未整段搬运。+ */++/** 一次读取最多返回的段落数(契约 §3 doc.read)。 */+const MAX_READ_PARAGRAPHS = 400;+/** selection.text 的截断长度(契约 §2.1)。 */+const SELECTION_TEXT_LIMIT = 4000;++/** 段落标记字符;para.Range.Text 的末尾就是它。 */+const PARAGRAPH_MARK = "\r";++/** 分隔符枚举(Word/WPS 通用值),app.Enum 里读不到时用它们兜底。 */+const BREAK_VALUES = { line: 6, page: 7, section: 2 };+const BREAK_ENUM_NAMES = {+ line: "wdLineBreak",+ page: "wdPageBreak",+ section: "wdSectionBreakNextPage",+};+const BREAK_LABELS = { line: "换行符", page: "分页符", section: "分节符" };++/** 本层自己的错误类型,调用方可以据此区分「契约里的业务错」与意外异常。 */+export class WpsApiError extends Error {+ constructor(message) {+ super(message);+ this.name = "WpsApiError";+ }+}++function fail(message) {+ throw new WpsApiError(message);+}++function reasonOf(error) {+ if (!error) return "未知错误";+ return error.message ? String(error.message) : String(error);+}++/** 去掉行尾空白(含段落标记、表格单元格标记)——`expect` 比较与对外返回的正文都用它。 */+export function normalizeParagraphText(text) {+ return String(text).replace(/[\s\u0007]+$/u, "");+}++function toInteger(value, name) {+ const num = Number(value);+ if (!Number.isInteger(num)) fail(`${name} 必须是整数,收到 ${JSON.stringify(value)}`);+ return num;+}++/* ------------------------------------------------------------------ *+ * 宿主与应用对象+ * ------------------------------------------------------------------ */++/** 契约 §3:`wps.WpsApplication()`,退化到 `window.Application`。 */+export function getApplication() {+ let app = null;+ try {+ if (window.wps && typeof window.wps.WpsApplication === "function")+ app = window.wps.WpsApplication();+ } catch (error) {+ console.warn(+ "[adelie] wps.WpsApplication() 调用失败,改用 window.Application:",+ reasonOf(error),+ );+ }+ if (!app) app = window.Application ?? null;+ if (!app) {+ fail("没有找到 WPS 应用对象:wps.WpsApplication() 与 window.Application 都不可用");+ }+ return app;+}++function activeDocument(app) {+ let doc = null;+ try {+ doc = app.ActiveDocument;+ } catch (error) {+ fail(`读取 app.ActiveDocument 失败:${reasonOf(error)}`);+ }+ if (!doc) fail("当前没有打开的文档,请先在 WPS 里打开或新建一篇文档");+ return doc;+}++function documentName(doc) {+ try {+ return doc.Name ? String(doc.Name) : "";+ } catch (error) {+ return "";+ }+}++function documentPath(doc) {+ try {+ return doc.FullName ? String(doc.FullName) : "";+ } catch (error) {+ return "";+ }+}++/* ------------------------------------------------------------------ *+ * 段落+ * ------------------------------------------------------------------ */++function paragraphCount(doc) {+ let raw;+ try {+ raw = doc.Paragraphs ? doc.Paragraphs.Count : undefined;+ } catch (error) {+ fail(`读取段落数失败:${reasonOf(error)}`);+ }+ const count = Number(raw);+ if (!Number.isInteger(count) || count < 0) {+ fail(`WPS 没有给出有效的段落数(doc.Paragraphs.Count = ${JSON.stringify(raw)})`);+ }+ return count;+}++function paragraphAt(doc, index) {+ const index2 = toInteger(index, "index");+ if (index2 < 1) fail(`段落号从 1 开始,收到 ${index2}`);+ const count = paragraphCount(doc);+ if (count === 0) fail("文档里一段都没有,先用 doc.create 新建一篇文档");+ if (index2 > count) fail(`段落 ${index2} 不存在(文档共 ${count} 段)`);+ let para = null;+ try {+ para = doc.Paragraphs.Item(index2);+ } catch (error) {+ fail(`取第 ${index2} 段失败:${reasonOf(error)}`);+ }+ if (!para) fail(`第 ${index2} 段不存在`);+ return para;+}++/** 取段落的字符范围;Start/End 是必读的两个数,缺了就没法改。 */+function paragraphRange(para, index) {+ let range = null;+ try {+ range = para.Range;+ } catch (error) {+ fail(`第 ${index} 段没有 Range:${reasonOf(error)}`);+ }+ if (!range) fail(`第 ${index} 段没有 Range`);+ const start = Number(range.Start);+ const end = Number(range.End);+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start) {+ fail(`第 ${index} 段的 Range 不可用(Start=${range.Start}, End=${range.End})`);+ }+ return { range, start, end };+}++/** 段落正文(原样,带段落标记)。 */+function paragraphRawText(para, index) {+ let text;+ try {+ text = para.Range ? para.Range.Text : undefined;+ } catch (error) {+ fail(`读取第 ${index} 段正文失败:${reasonOf(error)}`);+ }+ if (typeof text !== "string") fail(`第 ${index} 段读不到正文(para.Range.Text 不是字符串)`);+ return text;+}++function paragraphStyleName(para) {+ try {+ const style = para.Style;+ if (!style) return "";+ return String(style.NameLocal || style.Name || "");+ } catch (error) {+ // 样式只是附带信息,读不到不算失败。+ return "";+ }+}++/** 写操作返回的「同一段落」信息:段号 + 改完之后的正文。 */+function paragraphInfo(doc, index) {+ const para = paragraphAt(doc, index);+ return { index, text: normalizeParagraphText(paragraphRawText(para, index)) };+}++function docRange(doc, start, end) {+ let range = null;+ try {+ range = doc.Range(start, end);+ } catch (error) {+ fail(`取文档范围 [${start}, ${end}) 失败:${reasonOf(error)}`);+ }+ if (!range) fail(`取文档范围 [${start}, ${end}) 没有返回范围对象`);+ return range;+}++/** `expect` 校验:只比较「去掉行尾空白之后的当前正文」。 */+function assertExpect(args, currentText) {+ if (args.expect === undefined || args.expect === null) return;+ const expect = typeof args.expect === "string" ? args.expect : String(args.expect);+ if (currentText !== expect) fail("段落已变,先重新读取");+}++/** 读选区:from/to 是 1 起的段落号,没有选区(或宿主不给选区)时返回 null。 */+function selectionInfo(app, doc) {+ let start;+ let end;+ let text;+ try {+ const selection = app.Selection;+ if (!selection) return null;+ const range = selection.Range ?? selection;+ start = Number(range.Start);+ end = Number(range.End);+ text = typeof range.Text === "string" ? range.Text : "";+ } catch (error) {+ return null;+ }+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return null;+ return {+ from: paragraphIndexAtChar(doc, start),+ to: paragraphIndexAtChar(doc, end - 1), // 右端是开区间,减 1 才是最后一个被选中的字符+ text: text.slice(0, SELECTION_TEXT_LIMIT),+ };+}++/** 某个字符偏移落在第几段(1 起)。段落的 Range 自带位置,按它比较最贴近真实文档。 */+function paragraphIndexAtChar(doc, offset) {+ const count = paragraphCount(doc);+ for (let i = 1; i <= count; i++) {+ const para = paragraphAt(doc, i);+ const { start, end } = paragraphRange(para, i);+ if (offset <= Math.max(start, end - 1)) return i;+ }+ return count;+}++/* ------------------------------------------------------------------ *+ * op 实现(契约 §3)+ * ------------------------------------------------------------------ */++async function opSummary() {+ const app = getApplication();+ const doc = activeDocument(app);+ return {+ name: documentName(doc),+ path: documentPath(doc),+ paragraphs: paragraphCount(doc),+ selection: selectionInfo(app, doc),+ };+}++async function opRead(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const count = paragraphCount(doc);+ if (count === 0) return { paragraphs: [], truncated: false };++ const from = args.from === undefined || args.from === null ? 1 : toInteger(args.from, "from");+ const to = args.to === undefined || args.to === null ? count : toInteger(args.to, "to");+ if (from < 1) fail(`from 从 1 开始,收到 ${from}`);+ if (to < from) fail(`结束段号 ${to} 小于起始段号 ${from}`);++ const wantedEnd = Math.min(to, count);+ const limitedEnd = Math.min(wantedEnd, from + MAX_READ_PARAGRAPHS - 1);+ const paragraphs = [];+ for (let i = from; i <= limitedEnd; i++) {+ const para = paragraphAt(doc, i);+ paragraphs.push({+ index: i,+ text: normalizeParagraphText(paragraphRawText(para, i)),+ style: paragraphStyleName(para),+ });+ }+ return { paragraphs, truncated: wantedEnd > limitedEnd || to > count };+}++async function opSearch(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const query = typeof args.query === "string" ? args.query : "";+ if (!query.trim()) fail("搜索词不能为空(query)");+ const limit =+ args.limit === undefined || args.limit === null ? 20 : toInteger(args.limit, "limit");+ if (limit < 1) fail(`limit 至少是 1,收到 ${limit}`);++ const needle = query.toLowerCase();+ const count = paragraphCount(doc);+ const matches = [];+ for (let i = 1; i <= count && matches.length < limit; i++) {+ const para = paragraphAt(doc, i);+ const text = normalizeParagraphText(paragraphRawText(para, i));+ if (!text) continue; // 跳过空段+ if (text.toLowerCase().includes(needle)) matches.push({ index: i, text });+ }+ return { matches };+}++async function opReplace(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const index = toInteger(args.index, "index");+ if (typeof args.text !== "string") fail("text 必须是字符串");+ const text = args.text;+ if (/[\r\n\u000b\u000c]/u.test(text)) {+ fail("替换文本里不能有换行;要写多段请用 doc.insertAfter 一段一段插");+ }++ const para = paragraphAt(doc, index);+ const current = normalizeParagraphText(paragraphRawText(para, index));+ assertExpect(args, current);++ const { start, end } = paragraphRange(para, index);+ const contentEnd = Math.max(start, end - 1); // 留出末尾的段落标记,段落样式因此不变+ if (contentEnd > start) {+ const content = docRange(doc, start, contentEnd);+ if (typeof content.Delete !== "function")+ fail("这个 WPS 版本不支持 range.Delete(),无法替换段落正文");+ try {+ content.Delete();+ } catch (error) {+ fail(`清空第 ${index} 段正文失败:${reasonOf(error)}`);+ }+ }+ if (text) {+ const target = docRange(doc, start, start);+ try {+ target.Text = text;+ } catch (error) {+ fail(`写入第 ${index} 段正文失败:${reasonOf(error)}`);+ }+ }+ return paragraphInfo(doc, index);+}++async function opInsertAfter(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const index = toInteger(args.index, "index");+ if (typeof args.text !== "string") fail("text 必须是字符串");+ const text = args.text;++ const para = paragraphAt(doc, index);+ const { start, end } = paragraphRange(para, index);+ const previousStyle = paragraphStyleName(para);+ const position = Math.max(start, end - 1);++ const mark = docRange(doc, position, position);+ if (typeof mark.InsertParagraphAfter !== "function") {+ fail("这个 WPS 版本不支持 range.InsertParagraphAfter(),无法在其后插入段落");+ }+ try {+ mark.InsertParagraphAfter();+ } catch (error) {+ fail(`在第 ${index} 段之后插入段落失败:${reasonOf(error)}`);+ }++ const newIndex = index + 1;+ const created = paragraphAt(doc, newIndex);+ if (previousStyle) {+ try {+ created.Style = previousStyle;+ } catch (error) {+ // 新段落本来就继承前一段的样式,这里只是显式再写一遍;写不进去不是失败。+ console.warn(`[adelie] 第 ${newIndex} 段设置样式 ${previousStyle} 失败:`, reasonOf(error));+ }+ }++ if (text) {+ const target = paragraphAt(doc, newIndex);+ const range = paragraphRange(target, newIndex);+ const writeAt = range.start;+ const contentEnd = Math.max(writeAt, range.end - 1);+ if (contentEnd > writeAt) {+ const content = docRange(doc, writeAt, contentEnd);+ if (typeof content.Delete === "function") content.Delete();+ }+ const writeRange = docRange(doc, writeAt, writeAt);+ try {+ writeRange.Text = text;+ } catch (error) {+ fail(`写入新段落正文失败:${reasonOf(error)}`);+ }+ }+ return paragraphInfo(doc, newIndex);+}++async function opDelete(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const index = toInteger(args.index, "index");++ const count = paragraphCount(doc);+ const para = paragraphAt(doc, index);+ const current = normalizeParagraphText(paragraphRawText(para, index));+ assertExpect(args, current);+ if (count <= 1) {+ fail("这是文档里最后一段,删掉就没有段落可用了;请先执行 doc.create 新建一篇空白文档");+ }++ const { start, end } = paragraphRange(para, index);+ let from;+ let to;+ if (index < count) {+ // 连本段的段落标记一起删,下一段上提。+ from = start;+ to = end;+ } else {+ // 末段:删「前一段的段落标记 + 本段正文」,上一段因此成为最后一段。+ const previous = paragraphAt(doc, index - 1);+ const previousRange = paragraphRange(previous, index - 1);+ from = Math.max(0, previousRange.end - 1);+ to = Math.max(start, end - 1);+ }++ const target = docRange(doc, from, to);+ if (typeof target.Delete !== "function") fail("这个 WPS 版本不支持 range.Delete(),无法删除段落");+ try {+ target.Delete();+ } catch (error) {+ fail(`删除第 ${index} 段失败:${reasonOf(error)}`);+ }+ return { index };+}++async function opBreak(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const index = toInteger(args.index, "index");+ const kind = args.kind;+ if (!Object.prototype.hasOwnProperty.call(BREAK_VALUES, kind)) {+ fail(`kind 只能是 line、page 或 section,收到 ${JSON.stringify(kind)}`);+ }++ const para = paragraphAt(doc, index);+ const { start, end } = paragraphRange(para, index);+ const position = Math.max(start, end - 1);+ const target = docRange(doc, position, position);+ if (typeof target.InsertBreak !== "function") {+ fail("这个 WPS 版本不支持 range.InsertBreak(),无法插入分隔符");+ }+ try {+ target.InsertBreak(breakValue(app, kind));+ } catch (error) {+ fail(`在第 ${index} 段之后插入${BREAK_LABELS[kind]}失败:${reasonOf(error)}`);+ }+ return { index };+}++/** 枚举值优先取宿主给的,取不到用 Word 通用值兜底(契约 §3 要求「写清楚并容错」)。 */+function breakValue(app, kind) {+ const name = BREAK_ENUM_NAMES[kind];+ try {+ const fromApp = app.Enum ? Number(app.Enum[name]) : NaN;+ if (Number.isFinite(fromApp)) return fromApp;+ } catch (error) {+ // 宿主没有 app.Enum 就一直往下走。+ }+ try {+ const fromWps = window.wps && window.wps.Enum ? Number(window.wps.Enum[name]) : NaN;+ if (Number.isFinite(fromWps)) return fromWps;+ } catch (error) {+ // 同上:读不到就用字面值。+ }+ return BREAK_VALUES[kind];+}++async function opCreate() {+ const app = getApplication();+ const documents = app.Documents;+ if (!documents || typeof documents.Add !== "function")+ fail("WPS 没有提供 app.Documents.Add,无法新建文档");++ let doc = null;+ try {+ // WdNewBlankDocument = 0;第 4 个参数为 true 表示窗口可见(契约 §3)。+ doc = documents.Add("", false, 0, true);+ } catch (error) {+ try {+ doc = documents.Add(); // 老版本不接受这四个参数+ } catch (error2) {+ fail(`新建文档失败:${reasonOf(error2)}`);+ }+ }+ if (!doc) fail("WPS 新建文档后没有返回文档对象");+ try {+ if (typeof doc.Activate === "function") doc.Activate();+ } catch (error) {+ // 新文档一般已经是活动文档,Activate 失败不影响结果。+ }+ const active = app.ActiveDocument ?? doc;+ return { name: documentName(active) };+}++async function opReveal(args = {}) {+ const app = getApplication();+ const doc = activeDocument(app);+ const index = toInteger(args.index, "index");+ const para = paragraphAt(doc, index);+ const { range } = paragraphRange(para, index);+ if (typeof range.Select !== "function")+ fail("这个 WPS 版本不支持 range.Select(),无法定位到该段");+ try {+ range.Select();+ } catch (error) {+ fail(`定位到第 ${index} 段失败:${reasonOf(error)}`);+ }+ return { index };+}++/* ------------------------------------------------------------------ *+ * 对外入口+ * ------------------------------------------------------------------ */++export const OPERATIONS = {+ "doc.summary": opSummary,+ "doc.read": opRead,+ "doc.search": opSearch,+ "doc.replace": opReplace,+ "doc.insertAfter": opInsertAfter,+ "doc.delete": opDelete,+ "doc.break": opBreak,+ "doc.create": opCreate,+ "doc.reveal": opReveal,+};++export const OPERATION_NAMES = Object.keys(OPERATIONS);++/**+ * 跑一个 op:认不出名字、参数不对、WPS 报错都抛 WpsApiError,绝不静默成功。+ * 桥那边把 message 原样带给调用者,所以这里的文案要让用户看得懂。+ */+export async function runOperation(op, args) {+ const handler = OPERATIONS[op];+ if (!handler) fail(`不认识的文档操作:${op}`);+ try {+ return await handler(args ?? {});+ } catch (error) {+ if (error instanceof WpsApiError) throw error;+ fail(`${op} 失败:${reasonOf(error)}`);+ }+}diff --git a/plugins/use-wps-office/skills/wps-office/kit/adelie.mjs b/plugins/use-wps-office/skills/wps-office/kit/adelie.mjsnew file mode 100644index 00000000..9a11f993--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/adelie.mjs@@ -0,0 +1,286 @@+/**+ * The Adelie side of the kit, in one place: where Adelie keeps its data, where the bridge+ * keeps its own files, and a small HTTP client that finds a running Adelie and talks to it.+ *+ * It lives apart from `serve.mjs` because two callers need it — the long-running bridge, and+ * the one-shot `install.mjs` / `uninstall.mjs` that write the agent's config — and a second+ * copy of the discovery ladder would be a second thing to get wrong.+ *+ * Everything is local: the origin is this machine's Adelie, the token is the one Adelie writes+ * into its data root, and no request leaves the loopback interface.+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++/** Adelie's data root: the same precedence the CLI and the desktop shell use. */+export function resolveDataRoot(env = process.env) {+ return env.ADELIE_HOME ?? env.PENGUIN_HOME ?? path.join(os.homedir(), ".adelie", "data");+}++/** Where the bridge keeps its config and state — under Adelie's root, never inside the plugin. */+export function bridgeDir(root) {+ return path.join(root, "wps-bridge");+}++/**+ * The bridge's settings, and the file they are read from (`<root>/wps-bridge/config.json`).+ * They live here rather than in `serve.mjs` so the installer can resolve the same effective+ * port and MCP URL the bridge will use, without a second copy of the numbers to drift.+ */+export const DEFAULT_CONFIG = {+ /** The bridge's own port. Fixed by default so the WPS add-on's URL stays valid. */+ port: 3891,+ host: "127.0.0.1",+ /** Adelie's origin; null = discover it (desktop port file, then the usual dev ports). */+ adelieUrl: null,+ /** Session target: the first Project unless set; the Agent that owns the WPS conversation. */+ projectId: null,+ agentId: "default_agent",+ /** Panel sessions start here: reads run freely, document writes ask the person (rw -> approval). */+ approvalMode: "read-only",+ /** Register the MCP tools in the Agent's config during install. */+ installMcp: true,+ /** How long a document command may stay unanswered before the agent's turn gets an error. */+ commandTimeoutMs: 30_000,+};++/** The name the bridge's tools get in Adelie: `mcp__wps__read_document`. */+export const MCP_SERVER_NAME = "wps";++export function readJsonFile(file, fallback) {+ try {+ return { ...fallback, ...JSON.parse(fs.readFileSync(file, "utf8")) };+ } catch {+ return { ...fallback };+ }+}++export function writeJsonFile(file, value) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);+}++/* ------------------------------------------------------------------------- Adelie ------- */++/** Where the desktop shell announces the port of the server it started. */+function portFileCandidates() {+ const names = ["Adelie", "Adelie-Dev", "adelie"];+ const bases = [];+ if (process.platform === "win32") {+ const appData = process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming");+ for (const n of names) bases.push(path.join(appData, n));+ } else if (process.platform === "darwin") {+ for (const n of names) bases.push(path.join(os.homedir(), "Library", "Application Support", n));+ } else {+ const configHome = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config");+ for (const n of names) bases.push(path.join(configHome, n));+ }+ return bases.map((b) => path.join(b, "server-port"));+}++function readPortFile(file) {+ try {+ const m = /^(\d{1,5})\s*/.exec(fs.readFileSync(file, "utf8"));+ return m ? Number(m[1]) : null;+ } catch {+ return null;+ }+}++/** Whether something at this origin answers Adelie's public install probe. */+async function isAdelie(origin) {+ try {+ const res = await fetch(`${origin}/api/install`, { signal: AbortSignal.timeout(2000) });+ if (!res.ok) return false;+ const body = await res.json();+ return typeof body?.installId === "string";+ } catch {+ return false;+ }+}++/**+ * Find Adelie: an explicit setting first, then the desktop shell's port announcement, then+ * the ports a CLI-run server uses. Nothing here is cached beyond the call — a restarted+ * Adelie picks a new port, and the bridge must follow it.+ */+export async function discoverAdelie(config) {+ if (config.adelieUrl !== null && config.adelieUrl !== undefined) {+ const origin = String(config.adelieUrl).replace(/\/$/, "");+ if (await isAdelie(origin)) return { origin, source: "config" };+ }+ for (const file of portFileCandidates()) {+ const port = readPortFile(file);+ if (port === null) continue;+ const origin = `http://localhost:${port}`;+ if (await isAdelie(origin)) return { origin, source: `port-file:${file}` };+ }+ for (const port of [7364, 4000, 7370]) {+ const origin = `http://localhost:${port}`;+ if (await isAdelie(origin)) return { origin, source: `probe:${port}` };+ }+ return { origin: null, source: "not-found" };+}++/** The local API token Adelie writes on every start — re-read per request, it rotates. */+export function readToken(root) {+ try {+ return fs.readFileSync(path.join(root, "api-token"), "utf8").trim();+ } catch {+ return null;+ }+}++/**+ * Adelie's HTTP client: origin discovery, the rotating local token as a Bearer header, one+ * retry after re-reading the token (the token changes on every Adelie restart, and a bridge+ * outlives those).+ */+export class Adelie {+ constructor(root, config, log = () => {}) {+ this.root = root;+ this.config = config;+ this.log = log;+ this.origin = null;+ }++ async ensure() {+ const { origin, source } = await discoverAdelie(this.config);+ if (origin !== null) this.origin = origin;+ return { origin: this.origin, source };+ }++ async fetch(pathname, init = {}) {+ if (this.origin === null) await this.ensure();+ if (this.origin === null) {+ throw new Error(+ "找不到正在运行的 Adelie。请先打开 Adelie 桌面应用(或启动服务端),再重试。",+ );+ }+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const token = readToken(this.root);+ const headers = {+ ...(init.headers ?? {}),+ ...(token !== null ? { authorization: `Bearer ${token}` } : {}),+ ...(init.body !== undefined ? { "content-type": "application/json" } : {}),+ };+ const res = await fetch(`${this.origin}${pathname}`, {+ ...init,+ headers,+ signal: init.signal ?? AbortSignal.timeout(120_000),+ });+ if (res.status === 401 && attempt === 0) continue;+ return res;+ }+ throw new Error("Adelie 拒绝了这个请求(401):本机 API 令牌读不到或已失效。");+ }++ async json(pathname, init) {+ const res = await this.fetch(pathname, init);+ const text = await res.text();+ let body = null;+ try {+ body = text === "" ? null : JSON.parse(text);+ } catch {+ body = text;+ }+ if (!res.ok) {+ // A 401 has one cause worth naming: the local token is missing or rotated. Adelie's own+ // wording ("Not signed in or the sign-in has expired") sends the person looking for a+ // sign-in that does not exist on a loopback API.+ if (res.status === 401) {+ throw new Error(+ "Adelie 不认这个请求的本机令牌(401)。令牌每次启动 Adelie 都会重发,读不到就说明数据根不对或 Adelie 刚重启过;重新跑一次安装脚本即可。",+ );+ }+ const message =+ (body !== null && typeof body === "object" && body.error?.message) ||+ (typeof body === "string" && body.slice(0, 300)) ||+ `HTTP ${res.status}`;+ throw new Error(message);+ }+ return body;+ }++ /** The Project this kit works in: the configured one, else the first Adelie lists. */+ async projectId() {+ if (this.config.projectId !== null && this.config.projectId !== undefined) {+ return this.config.projectId;+ }+ const body = await this.json("/api/projects");+ const first = body?.projects?.[0]?.projectId;+ if (typeof first !== "string") throw new Error("Adelie 里还没有 Project。");+ return first;+ }++ async createSession({ workspace } = {}) {+ const projectId = await this.projectId();+ const agentId = this.config.agentId;+ const body = await this.json(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions`,+ {+ method: "POST",+ body: JSON.stringify({+ approvalMode: this.config.approvalMode,+ ...(workspace !== undefined && fs.existsSync(workspace) ? { workspace } : {}),+ }),+ },+ );+ const sessionId = body?.session?.sessionId;+ if (typeof sessionId !== "string") throw new Error("Adelie 没有返回 sessionId。");+ return { sessionId, projectId, agentId };+ }++ messages(sessionId, limit) {+ const qs = limit === undefined ? "" : `?tailLimit=${limit}`;+ return this.json(`/api/sessions/${encodeURIComponent(sessionId)}/messages${qs}`);+ }++ task(sessionId, text) {+ return this.json(`/api/sessions/${encodeURIComponent(sessionId)}/tasks`, {+ method: "POST",+ body: JSON.stringify({ input: [{ type: "text", text }], queueIfBusy: true }),+ });+ }++ approve(sessionId, toolCallId, decision) {+ return this.json(+ `/api/sessions/${encodeURIComponent(sessionId)}/approvals/${encodeURIComponent(toolCallId)}`,+ { method: "POST", body: JSON.stringify({ decision }) },+ );+ }++ abort(sessionId) {+ return this.json(`/api/sessions/${encodeURIComponent(sessionId)}/abort`, { method: "POST" });+ }++ /* --- the agent's own configuration: the bridge's tools are registered here ----------------- */++ /** The agent's config view (`{ config, agentsMd, … }`). */+ agentConfig() {+ return this.projectId().then((projectId) =>+ this.json(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(this.config.agentId)}/config`,+ ),+ );+ }++ /** Write the agent's config. The server merges per key, so sending `tools` alone is safe. */+ async updateAgentConfig(config) {+ const projectId = await this.projectId();+ return this.json(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(this.config.agentId)}/config`,+ { method: "PUT", body: JSON.stringify({ config }) },+ );+ }++ /** Ask Adelie to connect to one MCP entry and list its tools — the install's own check. */+ async mcpTest(name, config) {+ const projectId = await this.projectId();+ return this.json(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(this.config.agentId)}/config/mcp-test`,+ { method: "POST", body: JSON.stringify({ name, config }) },+ );+ }+}diff --git a/plugins/use-wps-office/skills/wps-office/kit/install.mjs b/plugins/use-wps-office/skills/wps-office/kit/install.mjsnew file mode 100644index 00000000..a6159a56--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/install.mjs@@ -0,0 +1,259 @@+#!/usr/bin/env node+/**+ * Install Adelie's WPS panel. One run does four things, each idempotent — running it again is+ * also the repair:+ *+ * 1. writes the bridge's settings (`<Adelie 数据根>/wps-bridge/config.json`);+ * 2. tells WPS to load the panel (`http://127.0.0.1:<port>/addin/index.html`) through WPS's+ * own local relay — this is the step that needs WPS running;+ * 3. registers the bridge's document tools in the agent's config as one MCP server, then+ * asks Adelie itself to connect to it (`config/mcp-test`) so a broken setup says so here+ * instead of mid-conversation;+ * 4. starts the bridge now, and on Windows leaves a launcher in the login Startup folder so+ * it is there again after a reboot.+ *+ * Nothing here needs the network: loopback only, and every port is on this machine.+ *+ * node install.mjs [--port 3891] [--root <数据根>] [--adelie <origin>] [--project <id>]+ * [--agent <id>] [--no-mcp] [--no-wps] [--no-autostart] [--no-start]+ */+import { spawn } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import {+ Adelie,+ DEFAULT_CONFIG,+ MCP_SERVER_NAME,+ bridgeDir,+ readJsonFile,+ resolveDataRoot,+ writeJsonFile,+} from "./adelie.mjs";+import { addonInstalled, ensureRelay, setAddon } from "./wps.mjs";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const SERVE = path.join(HERE, "serve.mjs");++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(`--${name}`);+const option = (name) => {+ const at = argv.indexOf(`--${name}`);+ return at >= 0 ? argv[at + 1] : undefined;+};++const lines = [];+const say = (text = "") => {+ lines.push(text);+ process.stdout.write(`${text}\n`);+};+const step = (n, text) => say(`\n${n}. ${text}`);++async function main() {+ const root = option("root") ?? resolveDataRoot();+ const configFile = path.join(bridgeDir(root), "config.json");+ const config = readJsonFile(configFile, DEFAULT_CONFIG);++ // Flags win over the stored settings; everything else stays as it was.+ if (option("port") !== undefined) config.port = Number(option("port"));+ if (option("adelie") !== undefined) config.adelieUrl = option("adelie");+ if (option("project") !== undefined) config.projectId = option("project");+ if (option("agent") !== undefined) config.agentId = option("agent");+ if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) {+ throw new Error(`端口不合法:${config.port}`);+ }++ // WPS's add-on record holds the add-on *directory*: it fetches manifest.xml, the ribbon and+ // the page from under it. Handing it the page URL instead leaves an add-on that never loads.+ const addinUrl = `http://127.0.0.1:${config.port}/addin/`;+ const panelUrl = `${addinUrl}index.html`;+ const mcpUrl = `http://127.0.0.1:${config.port}/mcp`;++ say("Adelie 的 WPS 面板 · 安装");+ say(` 数据根:${root}`);+ say(` 桥端口:${config.port}`);+ say(` 加载项目录:${addinUrl}`);++ step(1, "写入设置");+ writeJsonFile(configFile, config);+ say(` ${configFile}`);++ let adelie = null;+ step(2, "连接 Adelie");+ adelie = new Adelie(root, config, () => {});+ const { origin, source } = await adelie.ensure();+ if (origin === null) {+ say(" ✗ 没有找到正在运行的 Adelie。先打开 Adelie 桌面应用,再重跑本脚本。");+ } else {+ say(` ✓ ${origin}(发现方式:${source})`);+ }++ let mcpOk = null;+ if (config.installMcp !== false && !flag("no-mcp")) {+ step(3, `把文档工具登记成 MCP 服务器「${MCP_SERVER_NAME}」`);+ if (origin === null) {+ say(" – 跳过:Adelie 没在运行。");+ } else {+ mcpOk = await registerMcp(adelie, mcpUrl);+ }+ }++ if (!flag("no-wps")) {+ step(4, "让 WPS 加载面板");+ const relay = await ensureRelay({ timeoutMs: 15_000 });+ if (relay === null) {+ say(" – 跳过:WPS 的本机上架服务没起来。");+ say(" 先把 WPS 打开并保持运行,然后重跑本脚本(或打开下面这个页面点一下「启用」)。");+ say(` http://127.0.0.1:${config.port}/publish`);+ } else {+ await setAddon({ cmd: "enable", url: addinUrl });+ const installed = await addonInstalled().catch(() => false);+ say(` ✓ 已交给 WPS(上架服务版本 ${relay}),当前状态:${installed ? "已启用" : "已提交"}`);+ }+ }++ if (!flag("no-autostart")) {+ step(5, "让它开机就在");+ const placed = installAutostart(root);+ say(placed === null ? " – 只在 Windows 上做这件事,本机不需要。" : ` ✓ ${placed}`);+ }++ if (!flag("no-start")) {+ step(6, "把桥跑起来");+ const running = await isBridgeUp(config.port);+ if (running) {+ say(` ✓ 已经在跑(${config.port})。`);+ } else {+ startBridge(root);+ const up = await waitForBridge(config.port);+ say(+ up ? ` ✓ 已启动(${config.port})。` : ` ✗ 没起来,看看 ${bridgeDir(root)}/bridge.log`,+ );+ }+ }++ say("\n接下来:");+ say(" 1. 打开 WPS —— 功能区里应当出现「Adelie」那一组,点开就是侧栏。");+ say(" 2. 在侧栏里提问;需要改文档时,该批准的地方会弹出来问你要不要允许。");+ say(` 3. 想先看看面板长什么样,浏览器里打开 ${panelUrl} 。`);+ say(+ ` 4. 出问题先看 http://127.0.0.1:${config.port}/status ,那里写着桥、WPS、面板各是什么状态。`,+ );+ say(`\n诊断:node ${path.relative(process.cwd(), SERVE)} --status`);+ if (mcpOk === false) {+ say(+ "\n注意:Adelie 没能连上桥的 MCP 服务(上面有原因)。面板本身照常能用,只是 Agent 摸不到文档。",+ );+ }+}++/** Register (or refresh) the bridge as one MCP server in the agent's config, then test it. */+async function registerMcp(adelie, url) {+ const entry = { name: MCP_SERVER_NAME, config: { transport: "http", url } };+ let view;+ try {+ view = await adelie.agentConfig();+ } catch (err) {+ say(` ✗ 读不到 Agent 配置:${err.message}`);+ return false;+ }+ const servers = Array.isArray(view?.config?.tools?.mcpServers)+ ? view.config.tools.mcpServers+ : [];+ const others = servers.filter((s) => s?.name !== MCP_SERVER_NAME);+ const existing = servers.find((s) => s?.name === MCP_SERVER_NAME);+ const same =+ existing !== undefined && JSON.stringify(existing.config) === JSON.stringify(entry.config);+ if (!same) {+ try {+ await adelie.updateAgentConfig({ tools: { mcpServers: [...others, entry] } });+ say(+ ` ✓ 已写入 Agent「${adelie.config.agentId}」的配置(原有 ${others.length} 个 MCP 服务器不动)`,+ );+ } catch (err) {+ say(` ✗ 写配置失败:${err.message}`);+ return false;+ }+ } else {+ say(" ✓ 配置里已经是这一条,不用改。");+ }++ try {+ const probe = await adelie.mcpTest(entry.name, entry.config);+ if (probe?.ok === true) {+ say(` ✓ Adelie 连上了:${(probe.tools ?? []).length} 个工具,${probe.latencyMs} ms`);+ say(+ ` ${(probe.tools ?? []).slice(0, 3).join("、")}${probe.tools?.length > 3 ? " …" : ""}`,+ );+ return true;+ }+ say(` ✗ Adelie 连不上这个 MCP 服务器:${probe?.error ?? "未知原因"}`);+ return false;+ } catch (err) {+ say(` ✗ 自检失败:${err.message}`);+ return false;+ }+}++/**+ * Windows: a launcher in the login Startup folder, so the bridge is running before WPS is+ * opened. It uses the very Node that ran this install — the machine's own interpreter, which+ * is the one thing here we can be sure of.+ */+function installAutostart(root) {+ if (process.platform !== "win32") return null;+ const startup = path.join(+ process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"),+ "Microsoft",+ "Windows",+ "Start Menu",+ "Programs",+ "Startup",+ );+ if (!fs.existsSync(startup)) return null;+ const file = path.join(startup, "adelie-wps-bridge.cmd");+ const body = [+ "@echo off",+ `rem Adelie 的 WPS 桥:由「Adelie WPS 面板」安装脚本生成,删掉这一行即可取消开机自启。`,+ `start "adelie-wps-bridge" /min "${process.execPath}" "${SERVE}" --root "${root}"`,+ "",+ ].join("\r\n");+ fs.writeFileSync(file, body, "utf8");+ return file;+}++async function isBridgeUp(port) {+ try {+ const res = await fetch(`http://127.0.0.1:${port}/status.json`, {+ signal: AbortSignal.timeout(2000),+ });+ return res.ok;+ } catch {+ return false;+ }+}++async function waitForBridge(port, timeoutMs = 8000) {+ const until = Date.now() + timeoutMs;+ while (Date.now() < until) {+ if (await isBridgeUp(port)) return true;+ await new Promise((r) => setTimeout(r, 200));+ }+ return false;+}++/** Start the bridge detached: it must outlive this install command. */+function startBridge(root) {+ const child = spawn(process.execPath, [SERVE, "--root", root], {+ detached: true,+ stdio: "ignore",+ windowsHide: true,+ });+ child.unref();+}++await main().catch((err) => {+ process.stderr.write(`\n安装没有做完:${err?.message ?? err}\n`);+ process.exitCode = 1;+});diff --git a/plugins/use-wps-office/skills/wps-office/kit/serve.mjs b/plugins/use-wps-office/skills/wps-office/kit/serve.mjsnew file mode 100644index 00000000..e10c11c7--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/serve.mjs@@ -0,0 +1,1057 @@+#!/usr/bin/env node+/**+ * Adelie's WPS bridge: one dependency-free Node process that puts an Adelie conversation+ * inside WPS.+ *+ * Why a bridge at all, when Adelie's own server could serve the panel: the panel lives in+ * WPS's embedded browser, and Adelie deliberately enables no CORS (`仅限同源`), so a page on+ * another origin cannot call its API. The bridge is that other origin — and the panel talks+ * only to it, while it talks to Adelie. Everything stays on this machine: the bridge binds+ * 127.0.0.1, Adelie lands on localhost, and no port is exposed to the network.+ *+ * It plays four parts, and nothing else:+ *+ * 1. the panel's host `GET /addin/*` — the WPS add-on's page and assets, served from+ * `kit/addin/`; WPS loads `http://127.0.0.1:<port>/addin/index.html`+ * as an online add-on, so one panel serves every document.+ * 2. the agent's hands `GET /addin/commands` (SSE, bridge -> panel) + `POST /addin/result`+ * — document reads and edits executed inside WPS by the panel,+ * serialized one at a time, because two writers on one document is a+ * bug waiting to happen. `POST /mcp` exposes those same operations as+ * MCP tools, so an Adelie session drives the open document; reads+ * advertise `readOnlyHint` (permission `r`) and every write does not+ * (permission `rw`), which is what puts edits behind Adelie's approval.+ * 3. Adelie's client `GET /panel/state|history|events`, `POST /panel/session|ask|approve|abort`+ * — the conversation for the current document. The panel gets a+ * normalized event set (status/delta/thinking/tool/approval/done/error)+ * so it never has to understand Adelie's own message protocol, and an+ * Adelie protocol change lands here, not in the panel.+ * 4. WPS's install button `GET /publish` + `POST /publish/enable|disable|refresh` — the add-on+ * record, written through WPS's local relay (see wps.mjs).+ *+ * Configuration and state live beside Adelie's data root (`<root>/wps-bridge/`), never in this+ * directory: the plugin's files are replaced wholesale on update.+ */+import http from "node:http";+import fs from "node:fs";+import fsp from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import {+ Adelie,+ DEFAULT_CONFIG,+ bridgeDir,+ readJsonFile,+ readToken,+ resolveDataRoot,+ writeJsonFile,+} from "./adelie.mjs";+import {+ ADDON_NAME,+ addonInstalled,+ ensureRelay,+ listAddons,+ relayReachable,+ setAddon,+} from "./wps.mjs";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const ADDIN_DIR = path.join(HERE, "addin");+const KIT_VERSION = "1.0.0";++/* ------------------------------------------------------------------ paths & config ------ */++/* ------------------------------------------------------------------------- logging ------ */++let logStream = null;++function logTo(root, level, message, data) {+ const line = `${new Date().toISOString()} ${level.padEnd(5)} ${message}${+ data !== undefined ? ` ${typeof data === "string" ? data : JSON.stringify(data)}` : ""+ }`;+ process.stderr.write(`${line}\n`);+ if (root === null) return;+ try {+ const file = path.join(bridgeDir(root), "bridge.log");+ if (logStream === null) {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const size = fs.existsSync(file) ? fs.statSync(file).size : 0;+ if (size > 2 * 1024 * 1024) fs.renameSync(file, `${file}.1`);+ logStream = fs.createWriteStream(file, { flags: "a" });+ }+ logStream.write(`${line}\n`);+ } catch {+ // A log that cannot be written must never take the bridge down.+ }+}++/* ------------------------------------------------------------- panel command channel ---- */++/**+ * The document-operations channel. The panel is the only executor — it is the one holding+ * WPS's own API — so every call is one command out over SSE and one result back, serialized:+ * document edits must be observed in order, and a second writer interleaving with the first+ * would make both unreadable.+ */+class PanelChannel {+ constructor(log) {+ this.log = log;+ this.clients = new Set();+ this.pending = new Map();+ this.queue = Promise.resolve();+ this.seq = 0;+ this.hello = null;+ }++ get connected() {+ return this.clients.size > 0;+ }++ addClient(res) {+ this.clients.add(res);+ res.on("close", () => this.clients.delete(res));+ }++ /** A panel call that never arrives must fail loudly rather than hang the agent's turn. */+ send(op, args, { timeoutMs = 30_000 } = {}) {+ if (!this.connected) {+ return Promise.reject(+ new Error("WPS 里没有打开 Adelie 侧栏。请在 WPS 中打开 Adelie 面板后重试。"),+ );+ }+ const run = () =>+ new Promise((resolve, reject) => {+ const id = `c${++this.seq}`;+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`WPS 面板没有回应「${op}」(等待 ${timeoutMs / 1000} 秒超时)。`));+ }, timeoutMs);+ this.pending.set(id, { resolve, reject, timer });+ this.push({ id, op, args });+ });+ this.queue = this.queue.then(run, run);+ return this.queue;+ }++ /** Frames go out as plain SSE data lines; the panel answers with `/addin/result`. */+ push(frame) {+ const payload = `data: ${JSON.stringify(frame)}\n\n`;+ for (const res of this.clients) {+ try {+ res.write(payload);+ } catch {+ this.clients.delete(res);+ }+ }+ }++ settle(id, ok, payload) {+ const entry = this.pending.get(id);+ if (entry === undefined) return;+ this.pending.delete(id);+ clearTimeout(entry.timer);+ if (ok) entry.resolve(payload ?? {});+ else entry.reject(new Error(typeof payload === "string" ? payload : "WPS 面板报告了错误"));+ }+}++/* ------------------------------------------------- Adelie stream -> panel events -------- */++/**+ * One turn's translator: Adelie speaks in `OmniMessage`s and `ServerEvent`s, the panel in a+ * handful of shapes it can draw. Keeping the translation here (and not in the panel) means a+ * change to Adelie's protocol is one file's problem, and the panel's UI stays about the+ * document.+ */+class TurnTranslator {+ constructor(emit) {+ this.emit = emit;+ this.text = "";+ this.running = false;+ }++ /** One SSE frame from Adelie's session stream. */+ accept(frame) {+ if (typeof frame !== "object" || frame === null) return;+ const type = frame.type;+ if (type === "task_state") {+ const running = frame.state !== "idle";+ this.emit({ type: "status", running, queued: frame.queued ?? 0 });+ if (running) {+ this.text = "";+ this.running = true;+ } else if (this.running) {+ this.running = false;+ this.emit({ type: "done", text: this.text });+ }+ return;+ }+ if (type === "approval_request") {+ const call = frame.toolCall?.payload ?? {};+ this.emit({+ type: "approval",+ toolCallId: call.tool_call_id,+ name: call.name,+ summary: summarizeArguments(call.arguments),+ });+ return;+ }+ if (type === "resync_required") {+ this.emit({ type: "error", message: "连接中断过,正在重新同步对话。" });+ return;+ }+ if (frame.type !== "model_msg" && frame.type !== "event_msg") return;+ const payload = frame.payload ?? {};+ switch (payload.type) {+ case "partial_text":+ if (payload.event_type === "delta" && payload.text !== "") {+ this.text += payload.text;+ this.emit({ type: "delta", text: payload.text });+ }+ return;+ case "text":+ // The complete message is authoritative — partials can be dropped on reconnect.+ if (payload.role === "assistant" && typeof payload.text === "string") {+ this.text = payload.text;+ }+ return;+ case "partial_thinking":+ if (payload.event_type === "delta" && payload.thinking !== "") {+ this.emit({ type: "thinking", text: payload.thinking });+ }+ return;+ case "partial_tool_call":+ if (payload.event_type === "start") {+ this.emit({+ type: "tool",+ id: payload.tool_call_id,+ name: payload.name,+ summary: "",+ state: "running",+ });+ }+ return;+ case "tool_call":+ this.emit({+ type: "tool",+ id: payload.tool_call_id,+ name: payload.name,+ summary: summarizeArguments(payload.arguments),+ state: "running",+ });+ return;+ case "tool_call_output":+ this.emit({+ type: "tool",+ id: payload.tool_call_id,+ name: "",+ summary: firstLine(payload.output),+ state: payload.stop_reason === "completed" ? "done" : "failed",+ });+ return;+ case "abort":+ this.emit({ type: "error", message: payload.error_message ?? "任务被中断。" });+ return;+ case "approval_decision":+ this.emit({+ type: "tool",+ id: payload.tool_call_id,+ name: "",+ summary: payload.decision === "allow" ? "已允许" : "已拒绝",+ state: "done",+ });+ return;+ case "request_end":+ if (payload.stop_reason === "fatal" || payload.stop_reason === "retryable") {+ this.emit({ type: "error", message: payload.error_message ?? "模型调用失败。" });+ }+ return;+ default:+ return;+ }+ }+}++/** Tool arguments are a JSON string; a human-readable one-liner is what the panel draws. */+function summarizeArguments(args) {+ if (typeof args !== "string" || args.trim() === "") return "";+ try {+ const parsed = JSON.parse(args);+ const parts = [];+ for (const [k, v] of Object.entries(parsed)) {+ const value = typeof v === "string" ? v : JSON.stringify(v);+ parts.push(`${k}=${value.length > 60 ? `${value.slice(0, 60)}…` : value}`);+ }+ return parts.join(" ");+ } catch {+ return args.length > 80 ? `${args.slice(0, 80)}…` : args;+ }+}++function firstLine(text) {+ if (typeof text !== "string") return "";+ const line = text.split("\n").find((l) => l.trim() !== "") ?? "";+ return line.length > 120 ? `${line.slice(0, 120)}…` : line;+}++/* ------------------------------------------------------------------------------ MCP ----- */++/** The document tools an Adelie session can call; each maps onto one panel command. */+const MCP_TOOLS = [+ {+ name: "document_summary",+ op: "doc.summary",+ readOnly: true,+ description:+ "当前在 WPS 里打开的文档的概况:文档名、路径、段落总数、以及选区(若有一段被选中)。改文档前先调它确认目标文档。",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ args: () => ({}),+ },+ {+ name: "read_document",+ op: "doc.read",+ readOnly: true,+ description:+ "按段落读取文档正文(段落号从 1 开始,闭区间)。缺省读全文,最多 400 段。返回每段的段落号、正文与段落样式名。",+ inputSchema: {+ type: "object",+ properties: {+ from: { type: "integer", description: "起始段落号(含),1 起" },+ to: { type: "integer", description: "结束段落号(含)" },+ },+ additionalProperties: false,+ },+ args: (a) => ({ from: a.from, to: a.to }),+ },+ {+ name: "search_document",+ op: "doc.search",+ readOnly: true,+ description: "在当前文档里按文本查找段落(大小写不敏感的子串匹配),返回命中的段落号与正文。",+ inputSchema: {+ type: "object",+ properties: {+ query: { type: "string", description: "要找的文字" },+ limit: { type: "integer", description: "最多返回几条,默认 20" },+ },+ required: ["query"],+ additionalProperties: false,+ },+ args: (a) => ({ query: a.query, limit: a.limit }),+ },+ {+ name: "replace_paragraph",+ op: "doc.replace",+ readOnly: false,+ description:+ "替换某一段的正文,保留该段原有的段落样式。传 expect 时,只有该段当前正文与 expect 完全一致才会替换(防止改错行);不一致时先重新读取。text 里不能有换行,多段请用 insert_paragraph_after 逐段插入。",+ inputSchema: {+ type: "object",+ properties: {+ index: { type: "integer", description: "段落号,1 起" },+ text: { type: "string", description: "新的正文(单段)" },+ expect: { type: "string", description: "替换前该段应有的正文,用于校验" },+ },+ required: ["index", "text"],+ additionalProperties: false,+ },+ args: (a) => ({ index: a.index, text: a.text, expect: a.expect }),+ },+ {+ name: "insert_paragraph_after",+ op: "doc.insertAfter",+ readOnly: false,+ description: "在某一段之后插入一个新段落(沿用前一段的样式),返回新段落的段落号。",+ inputSchema: {+ type: "object",+ properties: {+ index: { type: "integer", description: "参照段落的段落号,1 起" },+ text: { type: "string", description: "新段落的正文" },+ },+ required: ["index", "text"],+ additionalProperties: false,+ },+ args: (a) => ({ index: a.index, text: a.text }),+ },+ {+ name: "delete_paragraph",+ op: "doc.delete",+ readOnly: false,+ description: "删除某一段。传 expect 时先校验该段正文,不一致则拒绝删除。",+ inputSchema: {+ type: "object",+ properties: {+ index: { type: "integer", description: "段落号,1 起" },+ expect: { type: "string", description: "删除前该段应有的正文" },+ },+ required: ["index"],+ additionalProperties: false,+ },+ args: (a) => ({ index: a.index, expect: a.expect }),+ },+ {+ name: "insert_break",+ op: "doc.break",+ readOnly: false,+ description: "在某一段之后插入分隔符:分页 / 分节 / 换行。",+ inputSchema: {+ type: "object",+ properties: {+ index: { type: "integer", description: "段落号,1 起" },+ kind: { type: "string", enum: ["line", "page", "section"], description: "分隔符种类" },+ },+ required: ["index", "kind"],+ additionalProperties: false,+ },+ args: (a) => ({ index: a.index, kind: a.kind }),+ },+ {+ name: "create_document",+ op: "doc.create",+ readOnly: false,+ description: "新建并打开一个空白 docx 文档;之后所有读写都针对这个新文档。",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ args: () => ({}),+ },+ {+ name: "reveal_paragraph",+ op: "doc.reveal",+ readOnly: true,+ description: "把视图滚到某一段并选中它,让用户看见改动落在了哪里。",+ inputSchema: {+ type: "object",+ properties: { index: { type: "integer", description: "段落号,1 起" } },+ required: ["index"],+ additionalProperties: false,+ },+ args: (a) => ({ index: a.index }),+ },+];++/* ---------------------------------------------------------------------------- server ---- */++const MIME = {+ ".html": "text/html; charset=utf-8",+ ".js": "text/javascript; charset=utf-8",+ ".mjs": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8",+ ".json": "application/json; charset=utf-8",+ ".png": "image/png",+ ".svg": "image/svg+xml",+ ".xml": "application/xml; charset=utf-8",+ ".ico": "image/x-icon",+ ".woff2": "font/woff2",+};++function sendJson(res, status, body) {+ const text = JSON.stringify(body);+ res.writeHead(status, {+ "content-type": "application/json; charset=utf-8",+ "cache-control": "no-store",+ "content-length": Buffer.byteLength(text),+ });+ res.end(text);+}++function sendText(res, status, text, contentType = "text/plain; charset=utf-8") {+ res.writeHead(status, {+ "content-type": contentType,+ "cache-control": "no-store",+ "content-length": Buffer.byteLength(text),+ });+ res.end(text);+}++async function readBody(req, capBytes = 512 * 1024) {+ const chunks = [];+ let total = 0;+ for await (const chunk of req) {+ total += chunk.length;+ if (total > capBytes) throw new Error("请求体过大");+ chunks.push(chunk);+ }+ if (chunks.length === 0) return {};+ const text = Buffer.concat(chunks).toString("utf8");+ try {+ return JSON.parse(text);+ } catch {+ throw new Error("请求体不是合法 JSON");+ }+}++function startEventStream(res) {+ res.writeHead(200, {+ "content-type": "text/event-stream; charset=utf-8",+ "cache-control": "no-store",+ connection: "keep-alive",+ "x-accel-buffering": "no",+ });+ res.write(": adelie-wps bridge\n\n");+ return res;+}++async function main() {+ const argv = process.argv.slice(2);+ const flag = (name) => argv.includes(`--${name}`);+ const option = (name) => {+ const at = argv.indexOf(`--${name}`);+ return at >= 0 ? argv[at + 1] : undefined;+ };++ const root = option("root") ?? resolveDataRoot();+ const configFile = path.join(bridgeDir(root), "config.json");+ const stateFile = path.join(bridgeDir(root), "state.json");+ const config = readJsonFile(configFile, DEFAULT_CONFIG);+ if (option("port") !== undefined) config.port = Number(option("port"));+ if (option("adelie") !== undefined) config.adelieUrl = option("adelie");+ if (option("project") !== undefined) config.projectId = option("project");++ const adelie = new Adelie(root, config, (m, d) => logTo(root, "info", m, d));+ const panel = new PanelChannel((m, d) => logTo(root, "info", m, d));+ const state = readJsonFile(stateFile, { sessions: {} });+ const panelEventClients = new Set();+ const translator = new TurnTranslator((event) => {+ for (const res of panelEventClients) {+ try {+ res.write(`data: ${JSON.stringify(event)}\n\n`);+ } catch {+ panelEventClients.delete(res);+ }+ }+ });++ /**+ * What WPS is told to load, and what a person can open in a browser. WPS's add-on record+ * holds a *directory* — it fetches `manifest.xml`, the ribbon and the page from under it —+ * which is how WPS's own publish page registers an online add-on (`…/jsplugindir/`).+ */+ const addinBase = `http://127.0.0.1:${config.port}/addin/`;+ /** The panel page itself: what the ribbon opens as a task pane, and what you open to look. */+ const addinUrl = `${addinBase}index.html`;++ const sessionFor = (docKey) => state.sessions?.[docKey] ?? null;+ const rememberSession = (docKey, value) => {+ state.sessions = { ...(state.sessions ?? {}), [docKey]: { ...value, atMs: Date.now() } };+ writeJsonFile(stateFile, state);+ };++ /* ------------------------------------------------------------------ Adelie stream ---- */++ let streamAbort = null;+ let streamSessionId = null;++ /** One long-lived subscription per session, reconnecting; events fan out to the panel. */+ function subscribe(sessionId) {+ if (streamSessionId === sessionId && streamAbort !== null) return;+ streamAbort?.abort();+ streamSessionId = sessionId;+ const controller = new AbortController();+ streamAbort = controller;+ void (async () => {+ let backoff = 1000;+ while (!controller.signal.aborted) {+ try {+ const res = await adelie.fetch(`/api/sessions/${encodeURIComponent(sessionId)}/stream`, {+ headers: { accept: "text/event-stream" },+ signal: controller.signal,+ });+ if (!res.ok || res.body === null) throw new Error(`HTTP ${res.status}`);+ backoff = 1000;+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let at;+ while ((at = buffer.indexOf("\n\n")) >= 0) {+ const frame = buffer.slice(0, at);+ buffer = buffer.slice(at + 2);+ const data = frame+ .split("\n")+ .filter((l) => l.startsWith("data:"))+ .map((l) => l.slice(5).trimStart())+ .join("\n");+ if (data === "" || data === "{}") continue;+ try {+ translator.accept(JSON.parse(data));+ } catch {+ // An unreadable frame is not worth dropping the subscription for.+ }+ }+ }+ } catch (err) {+ if (controller.signal.aborted) return;+ logTo(root, "warn", "adelie stream dropped", String(err));+ }+ if (controller.signal.aborted) return;+ await new Promise((r) => setTimeout(r, backoff));+ backoff = Math.min(backoff * 2, 10_000);+ }+ })();+ }++ /* ------------------------------------------------------------------- HTTP routes ----- */++ const server = http.createServer((req, res) => {+ void handle(req, res).catch((err) => {+ logTo(root, "error", `${req.method} ${req.url} failed`, String(err?.message ?? err));+ if (!res.headersSent) sendJson(res, 500, { ok: false, error: String(err?.message ?? err) });+ else res.end();+ });+ });++ async function handle(req, res) {+ const url = new URL(req.url ?? "/", `http://127.0.0.1:${config.port}`);+ const route = `${req.method} ${url.pathname}`;++ /* --- the panel's command channel ---------------------------------------------------- */+ if (route === "POST /addin/hello") {+ const body = await readBody(req);+ panel.hello = { ...body, atMs: Date.now() };+ const { origin } = await adelie.ensure();+ logTo(root, "info", "panel connected", { doc: body?.doc?.name ?? null, adelie: origin });+ return sendJson(res, 200, {+ ok: true,+ adelie: { connected: origin !== null, origin },+ panel: { document: body?.doc ?? null },+ });+ }+ if (route === "GET /addin/commands") {+ const stream = startEventStream(res);+ panel.addClient(stream);+ const timer = setInterval(() => {+ try {+ stream.write("event: ping\ndata: {}\n\n");+ } catch {+ clearInterval(timer);+ }+ }, 20_000);+ req.on("close", () => clearInterval(timer));+ return;+ }+ if (route === "POST /addin/result") {+ const body = await readBody(req);+ panel.settle(body.id, body.ok === true, body.ok === true ? body.result : body.error);+ return sendJson(res, 200, { ok: true });+ }+ if (route === "POST /addin/log") {+ const body = await readBody(req);+ logTo(+ root,+ body.level === "error" ? "error" : body.level === "warn" ? "warn" : "info",+ `panel: ${body.message ?? ""}`,+ body.data,+ );+ return sendJson(res, 200, { ok: true });+ }++ /* --- the add-on's own files --------------------------------------------------------- */+ // Everything under /addin/ that is not one of the endpoints above is a file of the panel+ // itself. This block comes after them on purpose: as a prefix match it would otherwise+ // swallow /addin/commands and answer 404 for a page the panel needs.+ if (req.method === "GET" && url.pathname.startsWith("/addin/")) {+ const rel = url.pathname.slice("/addin/".length) || "index.html";+ const file = path.join(ADDIN_DIR, rel);+ if (!file.startsWith(ADDIN_DIR)) return sendText(res, 403, "forbidden");+ try {+ const body = await fsp.readFile(file);+ res.writeHead(200, {+ "content-type": MIME[path.extname(file)] ?? "application/octet-stream",+ "cache-control": "no-store",+ "content-length": body.length,+ });+ return res.end(body);+ } catch {+ return sendText(res, 404, `no such add-in file: ${rel}`);+ }+ }++ /* --- the panel's conversation ------------------------------------------------------- */+ if (route === "GET /panel/state") {+ const { origin } = await adelie.ensure();+ const doc = panel.hello?.doc ?? null;+ const key = docKeyOf(doc);+ const known = key === null ? null : sessionFor(key);+ return sendJson(res, 200, {+ ok: true,+ adelie: { connected: origin !== null, origin: adelie.origin },+ panel: { connected: panel.connected, document: doc },+ session: known,+ bridge: { version: KIT_VERSION, port: config.port },+ });+ }+ if (route === "POST /panel/session") {+ const doc = panel.hello?.doc ?? null;+ const key = docKeyOf(doc);+ if (key === null) return sendJson(res, 400, { ok: false, error: "还没有打开文档。" });+ const existing = sessionFor(key);+ if (existing !== null) {+ subscribe(existing.sessionId);+ return sendJson(res, 200, { ok: true, ...existing });+ }+ const workspace = doc?.path ? path.dirname(doc.path) : undefined;+ const created = await adelie.createSession({ workspace });+ const value = { ...created, document: doc?.path ?? doc?.name ?? "未命名" };+ rememberSession(key, value);+ subscribe(value.sessionId);+ return sendJson(res, 200, { ok: true, ...value });+ }+ if (route === "GET /panel/history") {+ const doc = panel.hello?.doc ?? null;+ const key = docKeyOf(doc);+ const known = key === null ? null : sessionFor(key);+ if (known === null) return sendJson(res, 200, { ok: true, messages: [] });+ const limit = Number(url.searchParams.get("limit") ?? 60);+ const body = await adelie.messages(known.sessionId, limit);+ const messages = [];+ for (const message of body?.messages ?? []) {+ const payload = message?.payload ?? {};+ if (message?.type !== "model_msg" || payload.type !== "text") continue;+ if (payload.role !== "user" && payload.role !== "assistant") continue;+ if (payload.sender !== undefined) continue;+ const text = String(payload.text ?? "").trim();+ if (text === "") continue;+ messages.push({ role: payload.role, text });+ }+ return sendJson(res, 200, { ok: true, messages });+ }+ if (route === "POST /panel/ask") {+ const body = await readBody(req);+ const text = String(body.text ?? "").trim();+ if (text === "") return sendJson(res, 400, { ok: false, error: "消息是空的。" });+ const doc = panel.hello?.doc ?? null;+ const key = docKeyOf(doc);+ if (key === null) return sendJson(res, 400, { ok: false, error: "还没有打开文档。" });+ let known = sessionFor(key);+ if (known === null) {+ const created = await adelie.createSession({+ workspace: doc?.path ? path.dirname(doc.path) : undefined,+ });+ known = { ...created, document: doc?.path ?? doc?.name ?? "未命名" };+ rememberSession(key, known);+ }+ subscribe(known.sessionId);+ const prompt = withDocumentContext(text, doc, body);+ try {+ const sent = await adelie.task(known.sessionId, prompt);+ return sendJson(res, 200, { ok: true, queued: sent?.queued === true });+ } catch (err) {+ return sendJson(res, 200, { ok: false, error: String(err?.message ?? err) });+ }+ }+ if (route === "POST /panel/approve") {+ const body = await readBody(req);+ const doc = panel.hello?.doc ?? null;+ const known = docKeyOf(doc) === null ? null : sessionFor(docKeyOf(doc));+ if (known === null) return sendJson(res, 400, { ok: false, error: "没有会话。" });+ await adelie.approve(+ known.sessionId,+ String(body.toolCallId ?? ""),+ body.decision === "deny" ? "deny" : "allow",+ );+ return sendJson(res, 200, { ok: true });+ }+ if (route === "POST /panel/abort") {+ const doc = panel.hello?.doc ?? null;+ const known = docKeyOf(doc) === null ? null : sessionFor(docKeyOf(doc));+ if (known === null) return sendJson(res, 400, { ok: false, error: "没有会话。" });+ await adelie.abort(known.sessionId);+ return sendJson(res, 200, { ok: true });+ }+ if (route === "GET /panel/events") {+ const stream = startEventStream(res);+ panelEventClients.add(stream);+ const timer = setInterval(() => {+ try {+ stream.write("event: ping\ndata: {}\n\n");+ } catch {+ clearInterval(timer);+ }+ }, 20_000);+ req.on("close", () => {+ clearInterval(timer);+ panelEventClients.delete(stream);+ });+ return;+ }++ /* --- the agent's document tools (MCP) ----------------------------------------------- */+ if (url.pathname === "/mcp") {+ if (req.method === "GET") {+ res.writeHead(405, { allow: "POST", "content-type": "application/json" });+ return res.end("{}");+ }+ if (req.method === "DELETE") {+ res.writeHead(204);+ return res.end();+ }+ if (req.method !== "POST") return sendText(res, 405, "method not allowed");+ const body = await readBody(req);+ const reply = await mcpReply(body);+ if (reply === null) {+ res.writeHead(202, { "content-type": "application/json" });+ return res.end();+ }+ return sendJson(res, 200, reply);+ }++ /* --- installing the add-on into WPS -------------------------------------------------- */+ if (route === "GET /publish") {+ return sendText(+ res,+ 200,+ publishPage(config, addinBase, addinUrl),+ "text/html; charset=utf-8",+ );+ }+ if (route === "GET /publish/state") {+ const reachable = await relayReachable();+ let addons = [];+ let error = null;+ if (reachable) {+ try {+ addons = await listAddons();+ } catch (err) {+ error = String(err?.message ?? err);+ }+ }+ return sendJson(res, 200, {+ ok: true,+ relay: reachable,+ installed: await addonInstalled().catch(() => false),+ addons,+ error,+ addinUrl: addinBase,+ panelUrl: addinUrl,+ });+ }+ if (route === "POST /publish/enable" || route === "POST /publish/disable") {+ const enable = url.pathname.endsWith("enable");+ const version = await ensureRelay({ timeoutMs: 20_000 });+ if (version === null) {+ return sendJson(res, 200, {+ ok: false,+ error: "WPS 的本机上架服务没起来。请先打开 WPS(并保持它运行),再点一次。",+ });+ }+ try {+ await setAddon({ cmd: enable ? "enable" : "disable", url: enable ? addinBase : "" });+ logTo(root, "info", `add-on ${enable ? "enabled" : "disabled"} via WPS relay`, addinBase);+ return sendJson(res, 200, { ok: true, installed: await addonInstalled() });+ } catch (err) {+ return sendJson(res, 200, { ok: false, error: String(err?.message ?? err) });+ }+ }++ /* --- diagnostics --------------------------------------------------------------------- */+ if (route === "GET /status" || route === "GET /status.json") {+ const { origin, source } = await adelie.ensure();+ const report = {+ bridge: { version: KIT_VERSION, port: config.port, root, dataRoot: root },+ adelie: {+ origin,+ source,+ token: readToken(root) !== null,+ },+ wps: {+ relay: await relayReachable(),+ addonInstalled: await addonInstalled().catch(() => false),+ addonUrl: addinBase,+ },+ panel: { connected: panel.connected, document: panel.hello?.doc ?? null },+ mcp: { tools: MCP_TOOLS.map((t) => t.name), url: `http://127.0.0.1:${config.port}/mcp` },+ state: state.sessions ?? {},+ };+ if (url.pathname.endsWith(".json")) return sendJson(res, 200, { ok: true, ...report });+ return sendText(res, 200, statusPage(report), "text/html; charset=utf-8");+ }+ if (route === "GET /") {+ res.writeHead(302, { location: "/status" });+ return res.end();+ }+ return sendJson(res, 404, { ok: false, error: `no route: ${route}` });+ }++ /** One MCP request in, one JSON-RPC response out — or null for a notification. */+ async function mcpReply(body) {+ const id = body?.id ?? null;+ const method = body?.method;+ const ok = (result) => ({ jsonrpc: "2.0", id, result });+ const fail = (code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });+ if (method === undefined) return fail(-32600, "invalid request");+ if (method.startsWith("notifications/")) return null;+ if (method === "initialize") {+ return ok({+ protocolVersion: body.params?.protocolVersion ?? "2025-06-18",+ capabilities: { tools: { listChanged: false } },+ serverInfo: { name: "adelie-wps", version: KIT_VERSION },+ instructions:+ "这些工具操作 WPS 里当前打开的文档。段落号从 1 开始,来自最近一次读取;改动前先读取或搜索定位,改完再读一次确认。",+ });+ }+ if (method === "ping") return ok({});+ if (method === "tools/list") {+ return ok({+ tools: MCP_TOOLS.map((tool) => ({+ name: tool.name,+ description: tool.description,+ inputSchema: tool.inputSchema,+ annotations: { readOnlyHint: tool.readOnly, openWorldHint: false },+ })),+ });+ }+ if (method === "tools/call") {+ const name = body.params?.name;+ const tool = MCP_TOOLS.find((t) => t.name === name);+ if (tool === undefined) return fail(-32602, `unknown tool: ${String(name)}`);+ const args = body.params?.arguments ?? {};+ try {+ const result = await panel.send(tool.op, tool.args(args), {+ timeoutMs: config.commandTimeoutMs,+ });+ return ok({ content: [{ type: "text", text: JSON.stringify(result, null, 2) }] });+ } catch (err) {+ return ok({+ content: [{ type: "text", text: String(err?.message ?? err) }],+ isError: true,+ });+ }+ }+ return fail(-32601, `unsupported method: ${method}`);+ }++ /* --- diagnostics from the command line, for install / repair / the skill --------------- */+ if (flag("status")) {+ const { origin, source } = await adelie.ensure();+ const report = {+ port: config.port,+ addinUrl: addinBase,+ panelUrl: addinUrl,+ dataRoot: root,+ adelie: { origin, source, token: readToken(root) !== null },+ wps: { relay: await relayReachable(), installed: await addonInstalled().catch(() => false) },+ mcpUrl: `http://127.0.0.1:${config.port}/mcp`,+ };+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);+ return;+ }+ if (flag("print-url")) {+ process.stdout.write(`${addinBase}\n`);+ return;+ }++ await new Promise((resolve, reject) => {+ server.once("error", (err) => {+ if (err.code === "EADDRINUSE") {+ reject(+ new Error(+ `端口 ${config.port} 已被占用。若 Adelie 的 WPS 桥已在运行,这没关系;否则请用 --port 换一个端口并重新安装加载项。`,+ ),+ );+ } else {+ reject(err);+ }+ });+ server.listen(config.port, config.host, () => {+ logTo(root, "info", `adelie wps bridge listening on http://${config.host}:${config.port}`);+ logTo(root, "info", `add-on directory: ${addinBase} (page: ${addinUrl})`);+ logTo(root, "info", `mcp endpoint: http://127.0.0.1:${config.port}/mcp`);+ resolve();+ });+ });++ const shutdown = () => {+ logTo(root, "info", "bridge stopping");+ streamAbort?.abort();+ server.close(() => process.exit(0));+ setTimeout(() => process.exit(0), 2000).unref();+ };+ process.on("SIGINT", shutdown);+ process.on("SIGTERM", shutdown);+}++/** A document's identity for session reuse: its full path, or its name when unsaved. */+function docKeyOf(doc) {+ if (doc === null || doc === undefined) return null;+ const key =+ doc.path && String(doc.path).trim() !== "" ? String(doc.path) : `untitled:${doc.name ?? ""}`;+ return key.trim() === "" || key === "untitled:" ? null : key;+}++/**+ * What the agent is told about the document, ahead of the person's question. The panel sends+ * the context choice (selection / whole document / none); the text itself is read through the+ * same command channel, so the agent gets what the person can actually see right now.+ */+function withDocumentContext(text, doc, body) {+ const context = body.context ?? "selection";+ if (context === "none") return text;+ // The document is always named: an agent that answers about "this document" without knowing+ // which one it is will guess, and the person cannot see the guess.+ const name = doc?.name ?? "未命名";+ const where = doc?.path ? `${name}(${doc.path})` : name;+ const lines = [`[WPS 文档:${where}]`];+ if (context === "selection" && doc?.selection?.text) {+ lines.push("[当前选中的内容]", String(doc.selection.text), "[/当前选中的内容]");+ }+ lines.push("", text);+ return lines.join("\n");+}++/* ------------------------------------------------------------------------ static pages --- */++function publishPage(config, addinBase, addinUrl) {+ return `<!doctype html>+<html lang="zh-CN"><head><meta charset="utf-8"><title>Adelie · WPS 加载项</title>+<style>+ body{font:14px/1.6 system-ui,-apple-system,"Microsoft YaHei",sans-serif;margin:0;padding:28px;color:#1f2328}+ h1{font-size:18px;margin:0 0 4px} p{margin:6px 0;color:#57606a}+ code{background:#f6f8fa;border-radius:6px;padding:2px 6px}+ button{font:inherit;padding:6px 14px;margin-right:8px;border:1px solid #d0d7de;border-radius:6px;background:#f6f8fa;cursor:pointer}+ button.primary{background:#0969da;border-color:#0969da;color:#fff}+ #state{margin-top:16px;padding:12px;border:1px solid #d0d7de;border-radius:8px;background:#f6f8fa;white-space:pre-wrap}+</style></head><body>+<h1>把 Adelie 面板装进 WPS</h1>+<p>WPS 里登记的加载项目录:<code>${addinBase}</code> · 桥端口:<code>${config.port}</code></p>+<p>面板页面(想先看看长什么样就点开):<code>${addinUrl}</code></p>+<p>点「安装 / 修复」会通过 WPS 自己的本机上架服务登记这个加载项(WPS 需要正在运行)。</p>+<p><button class="primary" onclick="act('enable')">安装 / 修复</button>+ <button onclick="act('disable')">停用</button>+ <button onclick="refresh()">刷新状态</button></p>+<div id="state">正在读取…</div>+<script>+ async function act(what){+ const r = await (await fetch('/publish/' + what, {method:'POST'})).json();+ document.getElementById('state').textContent = r.ok ? '已提交,正在核对…' : ('失败:' + r.error);+ setTimeout(refresh, 800);+ }+ async function refresh(){+ const r = await (await fetch('/publish/state')).json();+ document.getElementById('state').textContent =+ 'WPS 上架服务:' + (r.relay ? '在运行' : '未启动(请先打开 WPS)') + '\\n' ++ 'Adelie 加载项:' + (r.installed ? '已登记' : '未登记') + '\\n' ++ '当前加载项列表:' + JSON.stringify(r.addons);+ }+ refresh();+</script></body></html>`;+}++function statusPage(report) {+ return `<!doctype html>+<html lang="zh-CN"><head><meta charset="utf-8"><title>Adelie WPS 桥</title>+<style>+ body{font:13px/1.6 ui-monospace,Menlo,Consolas,monospace;margin:0;padding:24px;color:#1f2328}+ h1{font-size:16px} pre{background:#f6f8fa;border:1px solid #d0d7de;border-radius:8px;padding:14px;overflow:auto}+</style></head><body>+<h1>Adelie WPS 桥 · v${KIT_VERSION}</h1>+<pre>${JSON.stringify(report, null, 2).replace(/[&<]/g, (c) => (c === "&" ? "&" : "<"))}</pre>+</body></html>`;+}++main().catch((err) => {+ process.stderr.write(`adelie-wps bridge failed: ${err?.stack ?? err}\n`);+ process.exit(1);+});diff --git a/plugins/use-wps-office/skills/wps-office/kit/uninstall.mjs b/plugins/use-wps-office/skills/wps-office/kit/uninstall.mjsnew file mode 100644index 00000000..7c9bd3eb--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/uninstall.mjs@@ -0,0 +1,125 @@+#!/usr/bin/env node+/**+ * Undo `install.mjs`: take the panel back out of WPS, drop the bridge's MCP entry from the+ * agent's config, and remove the login launcher. Idempotent, and deliberately narrow — it+ * touches only what the installer created:+ *+ * - the WPS add-on record named `adelie_wps_panel` (disabled, not deleted — WPS keeps its+ * own list, and disabling is the reversible half of what the installer did);+ * - the `wps` entry in the agent's `tools.mcpServers`;+ * - `…\Startup\adelie-wps-bridge.cmd`.+ *+ * Files that hold your settings and history (`<数据根>/wps-bridge/`) are kept: pass `--purge`+ * to delete that directory too. Nothing else on disk is touched.+ *+ * node uninstall.mjs [--root <数据根>] [--agent <id>] [--no-wps] [--purge]+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import {+ Adelie,+ DEFAULT_CONFIG,+ MCP_SERVER_NAME,+ bridgeDir,+ readJsonFile,+ resolveDataRoot,+} from "./adelie.mjs";+import { ensureRelay, setAddon } from "./wps.mjs";++const argv = process.argv.slice(2);+const flag = (name) => argv.includes(`--${name}`);+const option = (name) => {+ const at = argv.indexOf(`--${name}`);+ return at >= 0 ? argv[at + 1] : undefined;+};++const say = (text = "") => process.stdout.write(`${text}\n`);++async function main() {+ const root = option("root") ?? resolveDataRoot();+ const configFile = path.join(bridgeDir(root), "config.json");+ const config = readJsonFile(configFile, DEFAULT_CONFIG);+ if (option("agent") !== undefined) config.agentId = option("agent");++ say("Adelie 的 WPS 面板 · 卸载");+ say(` 数据根:${root}`);++ if (!flag("no-wps")) {+ say("\n1. 从 WPS 撤下加载项");+ const relay = await ensureRelay({ timeoutMs: 10_000 });+ if (relay === null) {+ say(" – 跳过:WPS 没在运行。关掉就够用了;等下次开着 WPS 时再跑一次本脚本,");+ say(" 可以把它从 WPS 的加载项列表里也停掉。");+ } else {+ try {+ await setAddon({ cmd: "disable", url: "" });+ say(" ✓ 已停用(下次启动 WPS 时不再加载这个面板)。");+ } catch (err) {+ say(` ✗ WPS 拒绝了停用:${err.message}`);+ }+ }+ }++ say("\n2. 从 Agent 配置里拿掉桥的工具");+ const adelie = new Adelie(root, config, () => {});+ const { origin } = await adelie.ensure();+ if (origin === null) {+ say(" – 跳过:Adelie 没在运行。想现在做,就先打开 Adelie 再跑一次。");+ } else {+ try {+ const view = await adelie.agentConfig();+ const servers = Array.isArray(view?.config?.tools?.mcpServers)+ ? view.config.tools.mcpServers+ : [];+ const kept = servers.filter((s) => s?.name !== MCP_SERVER_NAME);+ if (kept.length === servers.length) {+ say(` ✓ 配置里本来就没有「${MCP_SERVER_NAME}」。`);+ } else {+ await adelie.updateAgentConfig({ tools: { mcpServers: kept } });+ say(` ✓ 已移除(其余 ${kept.length} 个 MCP 服务器不动)。`);+ }+ } catch (err) {+ say(` ✗ 没能改 Agent 配置:${err.message}`);+ }+ }++ say("\n3. 取消开机自启");+ const launcher = path.join(+ process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"),+ "Microsoft",+ "Windows",+ "Start Menu",+ "Programs",+ "Startup",+ "adelie-wps-bridge.cmd",+ );+ if (fs.existsSync(launcher)) {+ fs.rmSync(launcher);+ say(` ✓ 已删除 ${launcher}`);+ } else {+ say(" – 没有这个文件(非 Windows,或本来就没建)。");+ }++ say("\n4. 桥自己的日志、设置与文档会话对照表");+ if (flag("purge")) {+ const dir = bridgeDir(root);+ if (fs.existsSync(dir)) {+ fs.rmSync(dir, { recursive: true, force: true });+ say(` ✓ 已删除 ${dir}`);+ } else {+ say(" – 本来就没有。");+ }+ } else {+ say(` – 保留 ${bridgeDir(root)} (设置、日志,以及哪份文档对应哪个会话)。`);+ say(" 要一并删掉就加 --purge。");+ }++ say("\n还在跑的桥进程不会自己退出:它是加载项页面的托管方。");+ say("卸载完可以直接关掉那个最小化的窗口(或在任务管理器里结束那个 node 进程)。");+}++await main().catch((err) => {+ process.stderr.write(`\n卸载没有做完:${err?.message ?? err}\n`);+ process.exitCode = 1;+});diff --git a/plugins/use-wps-office/skills/wps-office/kit/wps.mjs b/plugins/use-wps-office/skills/wps-office/kit/wps.mjsnew file mode 100644index 00000000..a210070e--- /dev/null+++ b/plugins/use-wps-office/skills/wps-office/kit/wps.mjs@@ -0,0 +1,148 @@+/**+ * The WPS side's local relay, spoken from Node — the client half of WPS's own+ * "publish an add-on" service.+ *+ * Installing our panel into WPS is not a file copy. WPS runs a local relay HTTP+ * service (`http://127.0.0.1:58890`, started by the `ksoWPSCloudSvr://start=RelayHttpServer`+ * protocol) and owns an add-on list: the official WPS publish page installs and disables+ * add-ons by POSTing to it. So do we — from Node, which sidesteps the page's cross-origin+ * limits and needs no browser at all.+ *+ * The shapes below were read off that official page (`wpsjs publish`), which the Apache-2.0+ * project visresearch/WordAgent vendors as `backend/gui/resources/publish.html`:+ *+ * - `POST /version` body `{}` (or the serverId envelope) -> a version string+ * - `POST /deployaddons/runParams` body = an add-on record + `cmd`+ * - `POST /publishlist` body `{}` -> the currently published add-ons, as JSON+ *+ * Every body is one JSON document, base64'd; on relay versions that support it, the document+ * is wrapped as `{ serverId, data }` (multi-user mode). We send the bare form first — that is+ * what the official page does whenever it has no serverId — and retry wrapped when the bare+ * form is refused, so one implementation covers both generations.+ */+import { spawn } from "node:child_process";++/** Where WPS's local add-on relay answers. Fixed by WPS, not configurable. */+export const RELAY_ORIGIN = "http://127.0.0.1:58890";++/** The add-on name registered with WPS. Stable: a re-install updates this entry, never adds a second. */+export const ADDON_NAME = "adelie_wps_panel";++/** The relay's answer is either the literal `OK` or an empty 200 body (see the official page). */+function relayOk(text) {+ const trimmed = text.trim();+ return trimmed === "OK" || trimmed === "";+}++/** One relay call: base64 body, the wrapped retry, and the collected answer. */+async function call(endpoint, payload, { serverId } = {}) {+ const bare = Buffer.from(JSON.stringify(payload), "utf8").toString("base64");+ const send = async (body) => {+ const res = await fetch(`${RELAY_ORIGIN}${endpoint}`, {+ method: "POST",+ headers: { "content-type": "text/plain;charset=UTF-8" },+ body,+ signal: AbortSignal.timeout(15_000),+ });+ return { status: res.status, text: await res.text() };+ };+ const first = await send(bare);+ if (first.status < 300 && relayOk(first.text)) return first;+ // Relay generations that speak the envelope refuse the bare form; retry wrapped once.+ const wrapped = Buffer.from(+ JSON.stringify({ serverId: serverId ?? "00000000-0000-4000-8000-000000000000", data: bare }),+ "utf8",+ ).toString("base64");+ const second = await send(wrapped);+ return second;+}++/** The relay's version string, or null when nothing is listening (WPS not running). */+export async function relayVersion() {+ try {+ const res = await call("/version", {});+ return res.status < 300 ? res.text.trim() : null;+ } catch {+ return null;+ }+}++/** Whether the relay is up — i.e. whether WPS is running and has started its service. */+export async function relayReachable() {+ return (await relayVersion()) !== null;+}++/** The add-ons WPS currently has published, as the relay reports them. */+export async function listAddons() {+ const res = await call("/publishlist", {});+ if (res.status >= 300)+ throw new Error(`WPS 上架服务返回 ${res.status}:${res.text.slice(0, 200)}`);+ try {+ return JSON.parse(res.text);+ } catch {+ return [];+ }+}++/**+ * Install or disable one add-on. `cmd` is `enable` / `disable`; `url` is the panel page the+ * WPS host loads — an `online` add-on is fetched from that URL on every launch, which is+ * exactly how one panel serves every document.+ */+export async function setAddon({ cmd, name = ADDON_NAME, url, version = "1.0.0" }) {+ const payload = {+ cmd,+ name,+ url: url ?? "",+ addonType: "wps",+ online: "true",+ multiUser: "false",+ version,+ customDomain: "",+ };+ const res = await call("/deployaddons/runParams", payload);+ if (res.status >= 300 || !relayOk(res.text)) {+ throw new Error(+ `WPS 上架服务拒绝了 ${cmd}(${res.status}):${res.text.slice(0, 200) || "空响应"}`,+ );+ }+ return true;+}++/**+ * Ask the WPS host to start its relay service, by opening WPS's own custom protocol. Only+ * meaningful on Windows, where that protocol is registered; elsewhere (and when WPS is+ * closed) the caller's retry ladder ends in a clear "open WPS first" message.+ */+export function startRelay() {+ if (process.platform !== "win32") return false;+ const child = spawn("cmd", ["/c", "start", "", "ksoWPSCloudSvr://start=RelayHttpServer"], {+ detached: true,+ stdio: "ignore",+ windowsHide: true,+ });+ child.unref();+ return true;+}++/** Wait until the relay answers, nudging it once on Windows; null when it never came up. */+export async function ensureRelay({ timeoutMs = 20_000 } = {}) {+ if (await relayReachable()) return await relayVersion();+ startRelay();+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 1000));+ if (await relayReachable()) return await relayVersion();+ }+ return null;+}++/** Whether our add-on is currently published to WPS. */+export async function addonInstalled() {+ try {+ const list = await listAddons();+ return Array.isArray(list) && list.some((a) => a?.name === ADDON_NAME && a?.enable !== "false");+ } catch {+ return false;+ }+}diff --git a/plugins/use-wps-office/test/addin.test.mjs b/plugins/use-wps-office/test/addin.test.mjsnew file mode 100644index 00000000..8d393048--- /dev/null+++ b/plugins/use-wps-office/test/addin.test.mjs@@ -0,0 +1,139 @@+/**+ * What WPS fetches from the bridge when it loads the add-on. WPS is handed a *directory*+ * (`http://127.0.0.1:<port>/addin/`) and pulls `manifest.xml`, the ribbon and the page out of+ * it, so these tests drive the real `kit/serve.mjs` over HTTP and check exactly that: every+ * file the manifest and the page name is really served, under the right content type, from+ * that directory URL — and nothing outside it can be fetched.+ *+ * No browser and no WPS needed; the add-on directory is the plugin's own.+ *+ * node --test plugins/wps-office/test/addin.test.mjs+ */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import fs from "node:fs";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { after, before, test } from "node:test";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const ADDIN = path.join(HERE, "..", "skills", "wps-office", "kit", "addin");+const SERVE = path.join(HERE, "..", "skills", "wps-office", "kit", "serve.mjs");++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function freePort() {+ return new Promise((resolve, reject) => {+ const probe = net.createServer();+ probe.once("error", reject);+ probe.listen(0, "127.0.0.1", () => {+ const { port } = probe.address();+ probe.close(() => resolve(port));+ });+ });+}++let root = null;+let bridge = null;+let base = null;++before(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), "wps-addin-test-"));+ const port = await freePort();+ bridge = spawn(process.execPath, [SERVE, "--root", root, "--port", String(port)], {+ stdio: ["ignore", "pipe", "pipe"],+ });+ base = `http://127.0.0.1:${port}/addin/`;+ for (let i = 0; i < 80; i += 1) {+ try {+ if ((await fetch(`http://127.0.0.1:${port}/status.json`)).ok) return;+ } catch {+ // not listening yet+ }+ await sleep(50);+ }+ throw new Error("桥没起来");+});++after(async () => {+ bridge?.kill("SIGTERM");+ await sleep(150);+ fs.rmSync(root, { recursive: true, force: true });+});++test("加载项目录:WPS 拿到的那个地址能直接列出这页", async () => {+ const res = await fetch(base);+ assert.equal(res.status, 200);+ assert.match(res.headers.get("content-type") ?? "", /text\/html/);+ assert.equal(await res.text(), fs.readFileSync(path.join(ADDIN, "index.html"), "utf8"));+});++test("清单与功能区都在目录里,是 XML 而不是二进制流", async () => {+ const manifest = await fetch(`${base}manifest.xml`);+ assert.equal(manifest.status, 200);+ assert.match(manifest.headers.get("content-type") ?? "", /xml/);+ const text = await manifest.text();+ assert.match(text, /<Name>Adelie<\/Name>/);+ assert.match(text, /<Application Name="wps">/);+ assert.match(text, /<RibbonXml>ribbon\.xml<\/RibbonXml>/);+ assert.match(text, /<TaskPane [^>]*Url="index\.html"/);++ const ribbon = await fetch(`${base}ribbon.xml`);+ assert.equal(ribbon.status, 200);+ const ribbonText = await ribbon.text();+ assert.match(ribbonText, /onLoad="ribbon\.OnAddinLoad"/);+ assert.match(ribbonText, /onAction="ribbon\.OnAction"/);+ assert.match(ribbonText, /getImage="ribbon\.GetImage"/);+});++test("页面要的每个文件都取得到,类型也对", async () => {+ const wanted = [+ ["panel.js", /javascript/],+ ["panel.css", /text\/css/],+ ["wps-api.js", /javascript/],+ ["stub-wps.js", /javascript/],+ ["images/icon.svg", /svg/],+ ];+ for (const [rel, type] of wanted) {+ const res = await fetch(`${base}${rel}`);+ assert.equal(res.status, 200, `${rel} 应当取得到`);+ assert.match(res.headers.get("content-type") ?? "", type, `${rel} 的类型`);+ assert.ok((await res.text()).length > 0, `${rel} 不该是空的`);+ }+});++test("页面只引相对路径(加载项目录可能被当成根来解析)", async () => {+ const html = await (await fetch(`${base}index.html`)).text();+ const refs = [...html.matchAll(/(?:src|href)="([^"]+)"/g)].map((m) => m[1]);+ assert.ok(refs.length > 0, "页面总得引用点什么");+ for (const ref of refs) {+ assert.ok(!ref.startsWith("/"), `${ref} 不该是绝对路径`);+ assert.ok(!/^https?:/i.test(ref), `${ref} 不该指向外部`);+ }+});++test("ribbon 回调在页面里真的存在", async () => {+ const [ribbon, panel] = await Promise.all([+ (await fetch(`${base}ribbon.xml`)).text(),+ (await fetch(`${base}panel.js`)).text(),+ ]);+ for (const handler of [...ribbon.matchAll(/="ribbon\.(\w+)"/g)].map((m) => m[1])) {+ assert.ok(panel.includes(`${handler}:`), `panel.js 里没有 window.ribbon.${handler}`);+ }+});++test("目录之外的文件拿不到", async () => {+ for (const attempt of ["..%2f..%2fpackage.json", "..%2fserve.mjs", "%2e%2e%2fsuite.js"]) {+ const res = await fetch(`${base}${attempt}`, { redirect: "manual" });+ assert.notEqual(res.status, 200, `${attempt} 不该被发出去`);+ const body = await res.text();+ assert.ok(!body.includes('"name"'), `${attempt} 不该泄露插件自己的文件`);+ }+});++test("没有这个文件就说没有", async () => {+ const res = await fetch(`${base}nope.js`);+ assert.equal(res.status, 404);+});diff --git a/plugins/use-wps-office/test/bridge.test.mjs b/plugins/use-wps-office/test/bridge.test.mjsnew file mode 100644index 00000000..bb1117d2--- /dev/null+++ b/plugins/use-wps-office/test/bridge.test.mjs@@ -0,0 +1,519 @@+/**+ * The bridge's own tests. They run the real `kit/serve.mjs` as a child process and talk to it+ * over HTTP, with a fake Adelie on one side and a fake WPS panel on the other — which is the+ * only way to check the two things that matter here: a document command actually round-trips+ * through the panel in order, and Adelie's message stream really arrives as the handful of+ * event shapes the panel draws.+ *+ * Nothing here touches the live Adelie (the bridge is pointed at the fake by `--adelie`), and+ * every port is picked free at run time.+ *+ * node --test plugins/wps-office/test/bridge.test.mjs+ */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import fs from "node:fs";+import http from "node:http";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { after, before, test } from "node:test";+import { Adelie } from "../skills/wps-office/kit/adelie.mjs";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const SERVE = path.join(HERE, "..", "skills", "wps-office", "kit", "serve.mjs");+/** Short enough that the timeout path is testable, long enough that it is never hit by accident. */+const COMMAND_TIMEOUT_MS = 3000;++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function freePort() {+ return new Promise((resolve, reject) => {+ const probe = net.createServer();+ probe.once("error", reject);+ probe.listen(0, "127.0.0.1", () => {+ const { port } = probe.address();+ probe.close(() => resolve(port));+ });+ });+}++async function waitFor(what, check, timeoutMs = 8000) {+ const until = Date.now() + timeoutMs;+ for (;;) {+ const value = await check();+ if (value) return value;+ if (Date.now() > until) throw new Error(`等待超时:${what}`);+ await sleep(25);+ }+}++function readJson(req) {+ return new Promise((resolve) => {+ let body = "";+ req.on("data", (chunk) => {+ body += chunk;+ });+ req.on("end", () => {+ try {+ resolve(body === "" ? {} : JSON.parse(body));+ } catch {+ resolve({});+ }+ });+ });+}++/** A stand-in for Adelie's HTTP surface: only the routes the bridge actually calls. */+function fakeAdelie() {+ const streams = new Set();+ const seen = {+ sessions: [],+ tasks: [],+ approvals: [],+ aborts: [],+ rejected: [],+ token: undefined,+ };+ const server = http.createServer((req, res) => {+ void (async () => {+ const url = new URL(req.url, "http://127.0.0.1");+ const json = (body, status = 200) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+ };+ if (url.pathname === "/api/install") return json({ installId: "test-install" });+ if (req.method === "GET" && url.pathname !== "/api/install") {+ // Once armed, everything else wants the token Adelie rotates on every restart.+ if (seen.token !== undefined && req.headers.authorization !== `Bearer ${seen.token}`) {+ seen.rejected.push(req.headers.authorization ?? null);+ return json({ error: { message: "Not signed in or the sign-in has expired." } }, 401);+ }+ }+ if (url.pathname === "/api/projects") return json({ projects: [{ projectId: "p1" }] });+ if (req.method === "POST" && /\/sessions$/.test(url.pathname)) {+ const body = await readJson(req);+ seen.sessions.push({ path: url.pathname, body });+ return json({ session: { sessionId: "s1" } });+ }+ if (url.pathname === "/api/sessions/s1/stream") {+ res.writeHead(200, {+ "content-type": "text/event-stream",+ "cache-control": "no-cache",+ connection: "keep-alive",+ });+ res.write(": connected\n\n");+ streams.add(res);+ req.on("close", () => streams.delete(res));+ return;+ }+ if (url.pathname === "/api/sessions/s1/messages") {+ return json({+ messages: [+ { type: "model_msg", payload: { type: "text", role: "user", text: "你好" } },+ { type: "model_msg", payload: { type: "text", role: "assistant", text: "在的" } },+ { type: "event_msg", payload: { type: "request_end" } },+ ],+ });+ }+ if (req.method === "POST" && url.pathname === "/api/sessions/s1/tasks") {+ const body = await readJson(req);+ seen.tasks.push(body);+ return json({ queued: false });+ }+ if (req.method === "POST" && url.pathname.startsWith("/api/sessions/s1/approvals/")) {+ const body = await readJson(req);+ seen.approvals.push({ id: url.pathname.split("/").pop(), ...body });+ return json({ ok: true });+ }+ if (req.method === "POST" && url.pathname === "/api/sessions/s1/abort") {+ seen.aborts.push(true);+ return json({ ok: true });+ }+ return json({ error: { message: `no fake route: ${req.method} ${url.pathname}` } }, 404);+ })();+ });+ return {+ server,+ seen,+ /** Push one frame down the session stream, exactly as Adelie's SSE would. */+ emit(frame) {+ const payload = `data: ${JSON.stringify(frame)}\n\n`;+ for (const res of streams) res.write(payload);+ },+ connectedStreams: () => streams.size,+ };+}++/** An SSE reader that keeps frames and lets a test wait for a matching one. */+async function sseClient(url) {+ const res = await fetch(url, { headers: { accept: "text/event-stream" } });+ assert.equal(res.status, 200, `${url} 应返回 200`);+ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ const frames = [];+ const waiters = new Set();+ let cursor = 0;+ void (async () => {+ let buffer = "";+ for (;;) {+ const { value, done } = await reader.read();+ if (done) break;+ buffer += decoder.decode(value, { stream: true });+ let at;+ while ((at = buffer.indexOf("\n\n")) >= 0) {+ const raw = buffer.slice(0, at);+ buffer = buffer.slice(at + 2);+ // `event:` lines are advisory; only the data payload is read.+ const data = raw+ .split("\n")+ .filter((l) => l.startsWith("data:"))+ .map((l) => l.slice(5).trimStart())+ .join("\n");+ if (data === "") continue;+ try {+ frames.push(JSON.parse(data));+ } catch {+ // keep-alive and comments are not frames+ }+ }+ for (const waiter of [...waiters]) waiter();+ }+ })();+ return {+ frames,+ next(predicate, timeoutMs = 8000) {+ return new Promise((resolve, reject) => {+ const attempt = () => {+ for (let i = cursor; i < frames.length; i += 1) {+ if (predicate(frames[i])) {+ cursor = i + 1;+ clearTimeout(timer);+ waiters.delete(attempt);+ resolve(frames[i]);+ return;+ }+ }+ };+ const timer = setTimeout(() => {+ waiters.delete(attempt);+ reject(new Error(`没有等到期望的帧,已有:${JSON.stringify(frames)}`));+ }, timeoutMs);+ waiters.add(attempt);+ attempt();+ });+ },+ close: () => reader.cancel().catch(() => {}),+ };+}++function mcp(toolName, args = {}) {+ return { name: toolName, args };+}++let bang = null; // bridge client handle+let panel = null; // the fake WPS panel's command stream+let api = null; // fake Adelie+let root = null;+let bridge = null;+let adelieOrigin = null;++/** Call an MCP tool through the bridge and return the JSON-RPC result. */+async function callTool(name, args = {}) {+ const res = await fetch(`${bang.url}/mcp`, {+ method: "POST",+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream" },+ body: JSON.stringify({+ jsonrpc: "2.0",+ id: 7,+ method: "tools/call",+ params: { name, arguments: args },+ }),+ });+ return (await res.json()).result;+}++/** The text the bridge packed into an MCP tool result. */+const textOf = (result) => result.content.map((c) => c.text).join("\n");++before(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), "wps-bridge-test-"));+ const adeliePort = await freePort();+ const bridgePort = await freePort();++ api = fakeAdelie();+ await new Promise((resolve) => api.server.listen(adeliePort, "127.0.0.1", resolve));+ adelieOrigin = `http://127.0.0.1:${adeliePort}`;++ fs.mkdirSync(path.join(root, "wps-bridge"), { recursive: true });+ fs.writeFileSync(+ path.join(root, "wps-bridge", "config.json"),+ JSON.stringify(+ {+ port: bridgePort,+ adelieUrl: `http://127.0.0.1:${adeliePort}`,+ agentId: "default_agent",+ approvalMode: "read-only",+ commandTimeoutMs: COMMAND_TIMEOUT_MS,+ },+ null,+ 2,+ ),+ );++ bridge = spawn(process.execPath, [SERVE, "--root", root], { stdio: ["ignore", "pipe", "pipe"] });+ const log = [];+ bridge.stdout.on("data", (d) => log.push(String(d)));+ bridge.stderr.on("data", (d) => log.push(String(d)));+ bang = { url: `http://127.0.0.1:${bridgePort}` };+ await waitFor("桥开始监听", async () => {+ try {+ const res = await fetch(`${bang.url}/status.json`);+ return res.ok;+ } catch {+ return false;+ }+ });++ panel = await sseClient(`${bang.url}/addin/commands`);+ const hello = await fetch(`${bang.url}/addin/hello`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ doc: { name: "月报.docx", path: "/tmp/月报.docx", paragraphs: 12 },+ version: "test",+ }),+ });+ assert.equal(hello.status, 200);+});++after(async () => {+ await panel?.close();+ bridge?.kill("SIGTERM");+ await new Promise((resolve) => api?.server.close(resolve));+ await sleep(150);+ fs.rmSync(root, { recursive: true, force: true });+});++test("桥把文档操作暴露成 MCP 工具,读工具是只读", async () => {+ const status = await (await fetch(`${bang.url}/status.json`)).json();+ assert.equal(status.ok, true);+ assert.equal(status.mcp.url, `${bang.url}/mcp`);+ assert.ok(status.mcp.tools.includes("read_document"));++ const res = await fetch(`${bang.url}/mcp`, {+ method: "POST",+ headers: { "content-type": "application/json", accept: "application/json" },+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }),+ });+ const { result } = await res.json();+ const byName = new Map(result.tools.map((t) => [t.name, t]));+ assert.equal(byName.get("read_document").annotations.readOnlyHint, true);+ assert.equal(byName.get("search_document").annotations.readOnlyHint, true);+ assert.equal(byName.get("replace_paragraph").annotations.readOnlyHint, false);+ assert.equal(byName.get("delete_paragraph").annotations.readOnlyHint, false);+});++test("面板连上后,读取命令走到面板再带着结果回到 Adelie", async () => {+ const pending = callTool("read_document", { from: 2, to: 3 });+ const command = await panel.next((f) => f.op === "doc.read");+ assert.deepEqual(command.args, { from: 2, to: 3 });++ const paragraphs = [+ { index: 2, text: "第一段正文", style: "正文" },+ { index: 3, text: "第二段正文", style: "正文" },+ ];+ const ack = await fetch(`${bang.url}/addin/result`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id: command.id, ok: true, result: { paragraphs } }),+ });+ assert.equal(ack.status, 200);++ const result = await pending;+ assert.ok(!result.isError, textOf(result));+ assert.deepEqual(JSON.parse(textOf(result)), { paragraphs });+});++test("改文档的命令按顺序一条条下发,前一条没回下一条不下", async () => {+ const first = callTool("replace_paragraph", {+ index: 3,+ text: "改后的正文",+ expect: "第二段正文",+ });+ const second = callTool("delete_paragraph", { index: 4, expect: "第三段正文" });++ const a = await panel.next((f) => f.op === "doc.replace");+ await sleep(300);+ // The second command must not have been pushed while the first is unanswered.+ assert.equal(+ panel.frames.filter((f) => f.op === "doc.delete").length,+ 0,+ "第一条命令未回应时不该下发第二条",+ );++ await fetch(`${bang.url}/addin/result`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id: a.id, ok: true, result: { index: 3, text: "改后的正文" } }),+ });++ const b = await panel.next((f) => f.op === "doc.delete");+ assert.deepEqual(b.args, { index: 4, expect: "第三段正文" });+ await fetch(`${bang.url}/addin/result`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id: b.id, ok: true, result: { deleted: 4 } }),+ });++ assert.deepEqual(JSON.parse(textOf(await first)), { index: 3, text: "改后的正文" });+ assert.deepEqual(JSON.parse(textOf(await second)), { deleted: 4 });+});++test("面板报错时,工具结果是错误,而不是假装的成功", async () => {+ const pending = callTool("replace_paragraph", { index: 3, text: "新", expect: "已经过期" });+ const command = await panel.next((f) => f.op === "doc.replace");+ await fetch(`${bang.url}/addin/result`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ id: command.id,+ ok: false,+ error: "第 3 段和 expect 不一致,先重新读取。",+ }),+ });++ const result = await pending;+ assert.equal(result.isError, true);+ assert.match(textOf(result), /expect/);+});++test("面板不回应时,命令会超时而不是把这一轮卡死", async () => {+ const started = Date.now();+ const result = await callTool("document_summary", {});+ assert.equal(result.isError, true);+ assert.match(textOf(result), /超时/);+ assert.ok(Date.now() - started < COMMAND_TIMEOUT_MS + 2000, "超时应当及时返回");+ await panel.next((f) => f.op === "doc.summary");+});++test("WPS 里没开面板时,工具直接说明原因", async () => {+ await panel.close();+ const result = await callTool("document_summary", {});+ assert.equal(result.isError, true);+ assert.match(textOf(result), /面板/);+ panel = await sseClient(`${bang.url}/addin/commands`);+});++test("对话:文档对应的 Adelie 会话按只读方式建,提问发得出去", async () => {+ const res = await fetch(`${bang.url}/panel/session`, { method: "POST" });+ const body = await res.json();+ assert.equal(body.ok, true);+ assert.equal(body.sessionId, "s1");+ const created = api.seen.sessions.at(-1);+ assert.match(created.path, /\/agents\/default_agent\/sessions$/);+ assert.equal(created.body.approvalMode, "read-only");++ const asked = await fetch(`${bang.url}/panel/ask`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ text: "把第二段改成新标题" }),+ });+ assert.equal((await asked.json()).ok, true);+ const task = api.seen.tasks.at(-1);+ assert.equal(task.queueIfBusy, true);+ assert.match(task.input[0].text, /把第二段改成新标题/);+ assert.match(task.input[0].text, /月报\.docx/, "提问要带上当前文档是哪一份");+});++test("Adelie 的流被归一化成面板要的几种事件", async () => {+ const events = await sseClient(`${bang.url}/panel/events`);+ await waitFor("桥订阅上 Adelie 的会话流", () => api.connectedStreams() > 0);++ api.emit({ type: "task_state", state: "running", queued: 0 });+ assert.deepEqual(await events.next((e) => e.type === "status"), {+ type: "status",+ running: true,+ queued: 0,+ });++ api.emit({+ type: "model_msg",+ payload: { type: "partial_text", event_type: "delta", text: "好的," },+ });+ assert.equal((await events.next((e) => e.type === "delta")).text, "好的,");++ api.emit({+ type: "approval_request",+ toolCall: {+ payload: {+ tool_call_id: "t1",+ name: "mcp__wps__replace_paragraph",+ arguments: '{"index":2,"text":"新标题"}',+ },+ },+ });+ const approval = await events.next((e) => e.type === "approval");+ assert.equal(approval.toolCallId, "t1");+ assert.match(approval.summary, /index=2/);++ // The complete message wins over the partials, and idle ends the turn with it.+ api.emit({+ type: "model_msg",+ payload: { type: "text", role: "assistant", text: "好的,已改好第二段。" },+ });+ api.emit({ type: "task_state", state: "idle" });+ const done = await events.next((e) => e.type === "done");+ assert.equal(done.text, "好的,已改好第二段。");++ // A tool that failed surfaces as a failed tool, not as silence.+ api.emit({+ type: "model_msg",+ payload: {+ type: "tool_call_output",+ tool_call_id: "t2",+ output: "第 3 段和 expect 不一致",+ stop_reason: "error",+ },+ });+ const failed = await events.next((e) => e.type === "tool" && e.state === "failed");+ assert.match(failed.summary, /不一致/);++ await events.close();+});++test("面板的历史只保留对话正文", async () => {+ const body = await (await fetch(`${bang.url}/panel/history`)).json();+ assert.equal(body.ok, true);+ assert.deepEqual(body.messages, [+ { role: "user", text: "你好" },+ { role: "assistant", text: "在的" },+ ]);+});++test("Adelie 换了令牌:桥会重读令牌、再试一次,失败也说人话", async () => {+ // Adelie writes a fresh token on every start; the bridge must pick up the new one without+ // being restarted, and must not relay Adelie's sign-in wording for a loopback API.+ const client = new Adelie(root, { adelieUrl: adelieOrigin, projectId: null }, () => {});+ api.seen.token = "tok-2";+ const before = api.seen.rejected.length;+ await assert.rejects(() => client.projectId(), /令牌/);+ assert.equal(api.seen.rejected.length - before, 2, "401 之后应当再试一次");++ fs.writeFileSync(path.join(root, "api-token"), "tok-2\n");+ assert.equal(await client.projectId(), "p1", "读到新令牌后应当直接通");++ fs.rmSync(path.join(root, "api-token"));+ api.seen.token = undefined;+});++test("审批决定能回传给 Adelie", async () => {+ const res = await fetch(`${bang.url}/panel/approve`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ toolCallId: "t1", decision: "allow" }),+ });+ assert.equal((await res.json()).ok, true);+ assert.deepEqual(api.seen.approvals.at(-1), { id: "t1", decision: "allow" });+});diff --git a/plugins/use-wps-office/test/fake-bridge.mjs b/plugins/use-wps-office/test/fake-bridge.mjsnew file mode 100644index 00000000..3c4acb12--- /dev/null+++ b/plugins/use-wps-office/test/fake-bridge.mjs@@ -0,0 +1,385 @@+#!/usr/bin/env node+/**+ * 测试用的假桥(契约 §5)—— 只实现面板用到的那几个接口,够 Playwright 冒烟跑通:+ * 静态文件(把 addin 目录当加载项目录发出去)、`/addin/hello|commands|result|log`、+ * `/panel/state|session|ask|approve|abort|history|events`。+ *+ * 它跟 `kit/serve.mjs`(真桥)无关:真桥由主 agent 写,之后会拿这份 spec 跑对照测试。+ * 另外多出几个 `/__test/*` 口子,用于测试把「桥推命令」「桥推流事件」这两件事做出来,+ * 以及读走面板报上来的东西。+ *+ * 用法:`node fake-bridge.mjs`(默认 127.0.0.1:3891)或作为模块+ * `const bridge = await startFakeBridge({ port: 3891 })`。+ */+import { createServer } from "node:http";+import { readFile } from "node:fs/promises";+import { dirname, extname, join, normalize } from "node:path";+import { fileURLToPath } from "node:url";++const HERE = dirname(fileURLToPath(import.meta.url));+const ADDIN_DIR = join(HERE, "..", "skills", "wps-office", "kit", "addin");++const CONTENT_TYPES = {+ ".html": "text/html; charset=utf-8",+ ".js": "text/javascript; charset=utf-8",+ ".mjs": "text/javascript; charset=utf-8",+ ".css": "text/css; charset=utf-8",+ ".xml": "application/xml; charset=utf-8",+ ".json": "application/json; charset=utf-8",+ ".md": "text/markdown; charset=utf-8",+ ".svg": "image/svg+xml",+ ".png": "image/png",+};++const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++function initialState() {+ return {+ hellos: [], // 面板报上来的文档概况+ logs: [], // 面板的诊断日志+ results: [], // 面板对命令的回答+ asks: [], // 面板发来的提问+ approvals: [], // 面板对审批的回答+ aborts: 0,+ sessionRequests: 0,+ history: [], // GET /panel/history 给面板的内容+ doc: null, // 最近一次 hello 里的文档概况+ session: null, // GET /panel/state 里的会话+ commandsSent: [], // 桥推给面板的命令+ askResponse: { ok: true, queued: false },+ };+}++export async function startFakeBridge({ port = 3891, host = "127.0.0.1" } = {}) {+ const state = initialState();+ /** 推命令用的 SSE 连接(面板的 /addin/commands)。 */+ const commandClients = new Set();+ /** 推流事件用的 SSE 连接(面板的 /panel/events)。 */+ const eventClients = new Set();+ /** 等面板回答某条命令:id -> {resolve, timer}。 */+ const waiters = new Map();+ let nextId = 1;++ function writeJson(res, status, payload) {+ const body = JSON.stringify(payload);+ res.writeHead(status, {+ "content-type": "application/json; charset=utf-8",+ "cache-control": "no-store",+ "content-length": Buffer.byteLength(body),+ });+ res.end(body);+ }++ function noContent(res) {+ res.writeHead(204, { "cache-control": "no-store" });+ res.end();+ }++ function readBody(req) {+ return new Promise((resolve) => {+ const chunks = [];+ req.on("data", (chunk) => chunks.push(chunk));+ req.on("end", () => {+ const raw = Buffer.concat(chunks).toString("utf8");+ if (!raw) {+ resolve({});+ return;+ }+ try {+ resolve(JSON.parse(raw));+ } catch (error) {+ resolve({});+ }+ });+ });+ }++ function openSse(res) {+ res.writeHead(200, {+ "content-type": "text/event-stream; charset=utf-8",+ "cache-control": "no-store",+ connection: "keep-alive",+ });+ res.write(": adelie fake bridge\n\n");+ }++ function writeSse(res, event, data) {+ const lines = [];+ if (event) lines.push(`event: ${event}`);+ lines.push(`data: ${JSON.stringify(data)}`);+ res.write(`${lines.join("\n")}\n\n`);+ }++ async function serveAddinFile(res, relative) {+ const clean = normalize(relative || "index.html").replace(/^(\.\.[/\\])+/, "");+ const file = join(ADDIN_DIR, clean);+ if (!file.startsWith(ADDIN_DIR)) {+ writeJson(res, 403, { ok: false, error: "越界了" });+ return;+ }+ try {+ const data = await readFile(file);+ res.writeHead(200, {+ "content-type": CONTENT_TYPES[extname(file)] ?? "application/octet-stream",+ "cache-control": "no-store",+ "content-length": data.length,+ });+ res.end(data);+ } catch (error) {+ writeJson(res, 404, { ok: false, error: `找不到 ${relative}` });+ }+ }++ const server = createServer((req, res) => {+ void handle(req, res).catch((error) => {+ writeJson(res, 500, { ok: false, error: String(error?.message ?? error) });+ });+ });++ async function handle(req, res) {+ const url = new URL(req.url ?? "/", `http://${host}:${port}`);+ const pathname = url.pathname;+ const method = req.method ?? "GET";++ /* ---------- 测试用的口子 ---------- */+ if (pathname === "/__test/state") {+ writeJson(res, 200, state);+ return;+ }+ if (pathname === "/__test/set" && method === "POST") {+ Object.assign(state, await readBody(req));+ writeJson(res, 200, { ok: true });+ return;+ }+ if (pathname === "/__test/command" && method === "POST") {+ const body = await readBody(req);+ try {+ const result = await runCommand(body);+ writeJson(res, 200, result);+ } catch (error) {+ writeJson(res, 200, {+ id: body.id ?? null,+ ok: false,+ error: String(error?.message ?? error),+ });+ }+ return;+ }+ if (pathname === "/__test/push" && method === "POST") {+ pushCommand(await readBody(req));+ writeJson(res, 202, { ok: true });+ return;+ }+ if (pathname === "/__test/event" && method === "POST") {+ const body = await readBody(req);+ pushEvent(body.event ?? null, body.data ?? {});+ writeJson(res, 200, { ok: true, clients: eventClients.size });+ return;+ }++ /* ---------- 面板页与它的资源 ---------- */+ if (pathname === "/favicon.ico") {+ await serveAddinFile(res, "images/icon.svg");+ return;+ }++ /* ---------- 桥的接口(契约 §2) ---------- */+ if (pathname === "/addin/hello" && method === "POST") {+ const body = await readBody(req);+ state.hellos.push(body);+ state.doc = body.doc ?? null;+ writeJson(res, 200, {+ ok: true,+ adelie: { connected: true, origin: `http://${host}:${port}` },+ });+ return;+ }+ if (pathname === "/addin/log" && method === "POST") {+ state.logs.push(await readBody(req));+ noContent(res);+ return;+ }+ if (pathname === "/addin/commands" && method === "GET") {+ openSse(res);+ commandClients.add(res);+ req.on("close", () => commandClients.delete(res));+ return;+ }+ if (pathname === "/addin/result" && method === "POST") {+ const body = await readBody(req);+ state.results.push(body);+ const waiter = waiters.get(body.id);+ if (waiter) {+ clearTimeout(waiter.timer);+ waiters.delete(body.id);+ waiter.resolve(body);+ }+ noContent(res);+ return;+ }++ // 其余的 /addin/* 是加载项自己的文件(index.html、panel.js、images/icon.svg……)+ if (pathname.startsWith("/addin/") && method === "GET") {+ await serveAddinFile(res, pathname.slice("/addin/".length));+ return;+ }++ if (pathname === "/panel/state" && method === "GET") {+ writeJson(res, 200, {+ ok: true,+ adelie: { connected: true, origin: `http://${host}:${port}` },+ session: state.session,+ doc: state.doc,+ });+ return;+ }+ if (pathname === "/panel/session" && method === "POST") {+ state.sessionRequests += 1;+ state.session = {+ sessionId: "session-fake-1",+ projectId: "project-fake-1",+ running: false,+ model: "deepseek-flash",+ };+ writeJson(res, 200, {+ ok: true,+ sessionId: state.session.sessionId,+ projectId: state.session.projectId,+ model: state.session.model,+ });+ return;+ }+ if (pathname === "/panel/ask" && method === "POST") {+ state.asks.push(await readBody(req));+ writeJson(res, 200, state.askResponse);+ return;+ }+ if (pathname === "/panel/approve" && method === "POST") {+ state.approvals.push(await readBody(req));+ writeJson(res, 200, { ok: true });+ return;+ }+ if (pathname === "/panel/abort" && method === "POST") {+ state.aborts += 1;+ writeJson(res, 200, { ok: true });+ return;+ }+ if (pathname === "/panel/history" && method === "GET") {+ writeJson(res, 200, { ok: true, messages: state.history });+ return;+ }+ if (pathname === "/panel/events" && method === "GET") {+ openSse(res);+ eventClients.add(res);+ req.on("close", () => eventClients.delete(res));+ return;+ }++ writeJson(res, 404, { ok: false, error: `假桥没有这个接口:${method} ${pathname}` });+ }++ /* ---------- 测试用的小工具 ---------- */++ function pushCommand(command) {+ const payload = {+ id: command.id ?? `cmd-${nextId++}`,+ op: command.op,+ args: command.args ?? {},+ };+ for (const client of commandClients) writeSse(client, null, payload);+ state.commandsSent.push(payload);+ return payload.id;+ }++ function pushEvent(event, data) {+ for (const client of eventClients) writeSse(client, event, data);+ }++ function awaitResult(id, timeout = 15_000) {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ waiters.delete(id);+ reject(new Error(`命令 ${id} 在 ${timeout}ms 内没有收到面板的回答`));+ }, timeout);+ waiters.set(id, { resolve, timer });+ });+ }++ async function waitForCommandClient(timeout = 10_000) {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ if (commandClients.size > 0) return;+ await sleep(50);+ }+ throw new Error("面板一直没连上命令通道(/addin/commands)");+ }++ async function runCommand({ op, args = {}, id }, timeout = 15_000) {+ await waitForCommandClient();+ const commandId = pushCommand({ id, op, args });+ return await awaitResult(commandId, timeout);+ }++ async function waitFor(predicate, { timeout = 10_000, interval = 50 } = {}) {+ const deadline = Date.now() + timeout;+ while (Date.now() < deadline) {+ if (predicate(state)) return state;+ await sleep(interval);+ }+ throw new Error(`等了 ${timeout}ms,条件依然不成立`);+ }++ function reset() {+ Object.assign(state, initialState());+ }++ async function close() {+ for (const client of [...commandClients, ...eventClients]) {+ try {+ client.end();+ } catch (error) {+ // 连接已经断了就算了。+ }+ }+ commandClients.clear();+ eventClients.clear();+ for (const waiter of waiters.values()) clearTimeout(waiter.timer);+ waiters.clear();+ await new Promise((resolve) => server.close(resolve));+ }++ await new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(port, host, () => {+ server.off("error", reject);+ resolve();+ });+ });++ return {+ url: `http://${host}:${port}`,+ port,+ state,+ stateSnapshot: () => JSON.parse(JSON.stringify(state)),+ reset,+ set: (patch) => {+ Object.assign(state, patch);+ return state;+ },+ waitFor,+ waitForCommandClient,+ runCommand,+ pushCommand,+ pushEvent,+ awaitResult,+ close,+ server,+ };+}++const isMain = process.argv[1] && fileURLToPath(import.meta.url) === normalize(process.argv[1]);+if (isMain) {+ const port = Number(process.env.PANEL_PORT ?? 3891);+ const bridge = await startFakeBridge({ port });+ console.log(`假桥在 ${bridge.url}(Ctrl-C 停)`);+}diff --git a/plugins/use-wps-office/test/install.test.mjs b/plugins/use-wps-office/test/install.test.mjsnew file mode 100644index 00000000..00284ca3--- /dev/null+++ b/plugins/use-wps-office/test/install.test.mjs@@ -0,0 +1,228 @@+/**+ * Install / uninstall tests: what the installer actually does to the agent's config, to the+ * bridge's settings file, and to the running bridge — checked against a fake Adelie that+ * records every write, so no real Adelie and no real agent is touched.+ *+ * `--no-wps` keeps WPS out of it (the relay only exists on a machine with WPS running); the+ * relay path is covered by the bridge's own `/publish` state test.+ *+ * node --test plugins/wps-office/test/install.test.mjs+ */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import fs from "node:fs";+import http from "node:http";+import net from "node:net";+import os from "node:os";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { after, before, test } from "node:test";++const HERE = path.dirname(fileURLToPath(import.meta.url));+const KIT = path.join(HERE, "..", "skills", "wps-office", "kit");+const INSTALL = path.join(KIT, "install.mjs");+const UNINSTALL = path.join(KIT, "uninstall.mjs");++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++async function freePort() {+ return new Promise((resolve, reject) => {+ const probe = net.createServer();+ probe.once("error", reject);+ probe.listen(0, "127.0.0.1", () => {+ const { port } = probe.address();+ probe.close(() => resolve(port));+ });+ });+}++function readJson(req) {+ return new Promise((resolve) => {+ let body = "";+ req.on("data", (c) => {+ body += c;+ });+ req.on("end", () => {+ try {+ resolve(body === "" ? {} : JSON.parse(body));+ } catch {+ resolve({});+ }+ });+ });+}++/** A fake Adelie that keeps the agent config in memory and records every write. */+function fakeAdelie() {+ const state = {+ config: {+ tools: { builtin: ["read_file"], mcpServers: [{ name: "other", config: { url: "x" } }] },+ },+ writes: [],+ probes: [],+ };+ const server = http.createServer((req, res) => {+ void (async () => {+ const url = new URL(req.url, "http://127.0.0.1");+ const json = (body, status = 200) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+ };+ if (url.pathname === "/api/install") return json({ installId: "test" });+ if (url.pathname === "/api/projects") return json({ projects: [{ projectId: "p1" }] });+ if (url.pathname === "/api/projects/p1/agents/default_agent/config") {+ if (req.method === "GET") return json({ config: state.config, agentsMd: "# agent" });+ if (req.method === "PUT") {+ const body = await readJson(req);+ state.writes.push(body);+ state.config = {+ ...state.config,+ ...body.config,+ tools: { ...state.config.tools, ...(body.config?.tools ?? {}) },+ };+ return json({ config: state.config });+ }+ }+ if (url.pathname.endsWith("/config/mcp-test")) {+ const body = await readJson(req);+ state.probes.push(body);+ return json({ ok: true, tools: ["mcp__wps__read_document"], latencyMs: 3 });+ }+ return json({ error: { message: `no fake route: ${req.method} ${url.pathname}` } }, 404);+ })();+ });+ return { server, state };+}++/** Run one of the kit's CLI scripts to completion. */+function run(script, args) {+ return new Promise((resolve) => {+ const child = spawn(process.execPath, [script, ...args], { stdio: ["ignore", "pipe", "pipe"] });+ let out = "";+ child.stdout.on("data", (d) => (out += d));+ child.stderr.on("data", (d) => (out += d));+ child.on("close", (code) => resolve({ code, out }));+ });+}++/** Kill the bridge this test started — matched by the unique temp root in its command line. */+function killBridgesFor(root) {+ // Linux-only: elsewhere nothing is killed, and the temp root goes away with the test anyway.+ let entries = [];+ try {+ entries = fs.readdirSync("/proc");+ } catch {+ return;+ }+ for (const entry of entries) {+ if (!/^\d+$/.test(entry)) continue;+ try {+ const cmdline = fs.readFileSync(`/proc/${entry}/cmdline`, "utf8");+ if (cmdline.includes(root) && cmdline.includes("serve.mjs"))+ process.kill(Number(entry), "SIGTERM");+ } catch {+ // process gone, or not ours to read+ }+ }+}++let root = null;+let api = null;+let bridgePort = null;+let adelieUrl = null;++before(async () => {+ root = fs.mkdtempSync(path.join(os.tmpdir(), "wps-install-test-"));+ api = fakeAdelie();+ const adeliePort = await freePort();+ await new Promise((resolve) => api.server.listen(adeliePort, "127.0.0.1", resolve));+ adelieUrl = `http://127.0.0.1:${adeliePort}`;+ bridgePort = await freePort();+});++after(async () => {+ killBridgesFor(root);+ await sleep(200);+ await new Promise((resolve) => api.server.close(resolve));+ fs.rmSync(root, { recursive: true, force: true });+});++test("安装:把桥登记成一个 MCP 服务器,别的不动,并真的连一次", async () => {+ const { code, out } = await run(INSTALL, [+ "--root",+ root,+ "--port",+ String(bridgePort),+ "--adelie",+ adelieUrl,+ "--no-wps",+ "--no-autostart",+ ]);+ assert.equal(code, 0, out);+ assert.match(out, /已写入 Agent/);+ assert.match(out, /Adelie 连上了/);++ const servers = api.state.config.tools.mcpServers;+ assert.deepEqual(+ servers.map((s) => s.name).sort(),+ ["other", "wps"],+ "原有的 MCP 服务器必须留着",+ );+ const wps = servers.find((s) => s.name === "wps");+ assert.equal(wps.config.transport, "http");+ assert.equal(wps.config.url, `http://127.0.0.1:${bridgePort}/mcp`);+ assert.deepEqual(api.state.probes.at(-1), { name: "wps", config: wps.config });++ const config = JSON.parse(fs.readFileSync(path.join(root, "wps-bridge", "config.json"), "utf8"));+ assert.equal(config.port, bridgePort);+ assert.equal(config.adelieUrl, adelieUrl);+});++test("安装:桥被真的拉起来了,现在就能应答", async () => {+ const res = await fetch(`http://127.0.0.1:${bridgePort}/status.json`);+ assert.equal(res.status, 200);+ const status = await res.json();+ assert.equal(status.mcp.url, `http://127.0.0.1:${bridgePort}/mcp`);+});++test("再装一次:不重复写、不重复登记", async () => {+ const before = api.state.writes.length;+ const { code, out } = await run(INSTALL, [+ "--root",+ root,+ "--port",+ String(bridgePort),+ "--adelie",+ adelieUrl,+ "--no-wps",+ "--no-autostart",+ ]);+ assert.equal(code, 0, out);+ assert.match(out, /已经是这一条/);+ assert.match(out, /已经在跑/);+ assert.equal(api.state.writes.length, before, "第二次安装不该再写配置");+ assert.equal(api.state.config.tools.mcpServers.length, 2);+});++test("卸载:摘掉桥的工具,其余保留", async () => {+ const { code, out } = await run(UNINSTALL, ["--root", root, "--adelie", adelieUrl, "--no-wps"]);+ assert.equal(code, 0, out);+ assert.deepEqual(+ api.state.config.tools.mcpServers.map((s) => s.name),+ ["other"],+ );+ assert.ok(fs.existsSync(path.join(root, "wps-bridge", "config.json")), "默认要留着设置和日志");+});++test("卸载 --purge:连设置和日志一起清掉", async () => {+ const { code, out } = await run(UNINSTALL, [+ "--root",+ root,+ "--adelie",+ adelieUrl,+ "--no-wps",+ "--purge",+ ]);+ assert.equal(code, 0, out);+ assert.ok(!fs.existsSync(path.join(root, "wps-bridge")), "--purge 之后不该再留着目录");+});diff --git a/plugins/use-wps-office/test/panel.spec.mjs b/plugins/use-wps-office/test/panel.spec.mjsnew file mode 100644index 00000000..155e96d8--- /dev/null+++ b/plugins/use-wps-office/test/panel.spec.mjs@@ -0,0 +1,491 @@+/**+ * WPS 面板的浏览器冒烟测试(契约 §5)—— 用 Playwright/Chromium 打开假桥提供的+ * `/addin/index.html`,页面里 stub-wps.js 生效,于是整个面板(ribbon、命令通道、聊天流、+ * 文档操作)能在没有 WPS 的机器上真的跑一遍。+ *+ * 跑法(仓库的 @playwright/test 装在 packages/web 下):+ * cd /root/adelie-fork/packages/web+ * npx playwright test -c /root/adelie-fork/plugins/wps-office/test/playwright.config.mjs+ * 换端口:PANEL_BASE_URL=http://127.0.0.1:3892/ 同时给 config 与这份 spec 用。+ */+import { existsSync } from "node:fs";+import { createRequire } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { startFakeBridge } from "./fake-bridge.mjs";++/**+ * @playwright/test 是仓库 packages/web 的依赖(插件本身不带依赖),从那里解析;+ * 与 playwright.config.mjs 里的同一段逻辑,两个文件各自独立可用。+ */+function loadPlaywright() {+ let directory = dirname(fileURLToPath(import.meta.url));+ for (let depth = 0; depth < 6; depth += 1) {+ const manifest = join(directory, "packages", "web", "package.json");+ if (existsSync(manifest)) return createRequire(manifest)("@playwright/test");+ directory = dirname(directory);+ }+ return createRequire(import.meta.url)("@playwright/test");+}++const { test: base, expect } = loadPlaywright();++const BASE_URL = process.env.PANEL_BASE_URL || "http://127.0.0.1:3891";+const PORT = Number(new URL(BASE_URL).port || 3891);++let bridge;++/** 每个用例一份控制台/页面错误清单;资源类的无关噪声(favicon、连接中断)不算。 */+const test = base.extend({+ errors: async ({ page }, use) => {+ const errors = [];+ page.on("pageerror", (error) => errors.push(`pageerror: ${error.message}`));+ page.on("console", (message) => {+ if (message.type() !== "error") return;+ const text = message.text();+ if (text.includes("favicon") || text.includes("ERR_ABORTED")) return;+ errors.push(`console: ${text}`);+ });+ await use(errors);+ },+});++test.beforeAll(async () => {+ bridge = await startFakeBridge({ port: PORT });+});++test.afterAll(async () => {+ await bridge.close();+});++test.beforeEach(() => {+ bridge.reset();+});++/** 打开面板并等它就绪(连上桥、发送按钮可用)。 */+async function openPanel(page) {+ await page.goto("/addin/index.html");+ await expect(page.locator("#send")).toBeVisible();+ await expect(page.locator("#conn-text")).toHaveText("已连接 Adelie");+ await expect(page.locator("#doc-line")).toContainText("季度报告.docx");+}++test("面板渲染出来,并把文档概况报给桥(契约 §2.1)", async ({ page, errors }) => {+ await openPanel(page);++ await expect(page.getByRole("heading", { name: "让 Adelie 直接改这篇文档" })).toBeVisible();+ await expect(page.locator("#doc-line")).toContainText("5 段");++ const state = await bridge.waitFor((snapshot) => snapshot.hellos.length > 0);+ const hello = state.hellos.at(-1);+ expect(hello.doc.name).toBe("季度报告.docx");+ expect(hello.doc.path).toContain("季度报告.docx");+ expect(hello.doc.paragraphs).toBe(5);+ expect(hello.doc.selection).toBeNull(); // 没有选区时是 null+ expect(hello.panel.version).toBe("1.0.0");+ expect(hello.panel.ua).toContain("Chrome");++ expect(errors).toEqual([]);+});++test("ribbon:加载时存 ribbonUI,点按钮开关任务窗格(契约 §1)", async ({ page, errors }) => {+ await openPanel(page);++ const ribbon = await page.evaluate(() => {+ const loaded = window.ribbon.OnAddinLoad({ id: "ribbon-ui" });+ const stored = window.Application.ribbonUI;+ window.ribbon.OnAction({ Id: "btnAdeliePanel" });+ const panes = [...window.__fakeWps.state.taskPanes.values()];+ const opened = {+ key: window.Application.PluginStorage.getItem("adelie_taskpane_id"),+ pane: { ...panes[0] },+ };+ window.ribbon.OnAction({ Id: "btnAdeliePanel" });+ return {+ loaded,+ stored: stored?.id,+ image: window.ribbon.GetImage(),+ opened,+ toggled: panes[0].Visible,+ };+ });++ expect(ribbon.loaded).toBe(true);+ expect(ribbon.stored).toBe("ribbon-ui");+ expect(ribbon.opened.key).toBe("fake-pane-1");+ expect(ribbon.opened.pane.Url).toBe(`${BASE_URL}/addin/index.html`);+ expect(ribbon.opened.pane.Caption).toBe("Adelie");+ expect(ribbon.opened.pane.Visible).toBe(true);+ expect(ribbon.opened.pane.DockPosition).toBe(2); // msoCTPDockPositionRight+ expect(ribbon.opened.pane.Width).toBeGreaterThan(0);+ expect(ribbon.toggled).toBe(false); // 再点一次是收起+ expect(ribbon.image).toBe("images/icon.svg");++ expect(errors).toEqual([]);+});++test("发送问题会把文字与上下文交给桥(契约 §2.4)", async ({ page, errors }) => {+ await openPanel(page);++ await page.fill("#input", "把第 2 段的标题改简洁");+ await page.press("#input", "Enter"); // Enter 发送(IME 安全的那条路径)++ const state = await bridge.waitFor((snapshot) => snapshot.asks.length > 0);+ expect(state.asks.at(-1)).toEqual({+ text: "把第 2 段的标题改简洁",+ context: "selection",+ tail: 120,+ });+ await expect(page.locator(".msg.user")).toHaveText("把第 2 段的标题改简洁");+ await expect(page.locator("#input")).toHaveValue("");++ // 切到「整篇文档」再发一条,带上的上下文跟着变+ await page.click('button[data-context="document"]');+ await expect(page.locator('button[data-context="document"]')).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ await page.fill("#input", "通读全文");+ await page.click("#send");+ await expect.poll(async () => bridge.state.asks.length).toBe(2);+ expect(bridge.state.asks.at(-1).context).toBe("document");++ expect(errors).toEqual([]);+});++test("流式 delta 收尾成回复气泡,并给出「写进文档」(契约 §2.4)", async ({ page, errors }) => {+ await openPanel(page);++ await bridge.pushEvent("status", { running: true });+ await expect(page.locator("#send")).toBeDisabled();++ await bridge.pushEvent("delta", { text: "好的," });+ await bridge.pushEvent("delta", { text: "我把第 2 段改短。" });+ await expect(page.locator(".msg.assistant .turn-text")).toHaveText("好的,我把第 2 段改短。");++ await bridge.pushEvent("done", { text: "好的,我把第 2 段改短。" });+ await expect(page.locator("#send")).toBeEnabled();+ await expect(page.getByRole("button", { name: "写进文档" })).toBeVisible();++ expect(errors).toEqual([]);+});++test("思考过程、工具行、错误行都按契约显示(契约 §2.4)", async ({ page, errors }) => {+ await openPanel(page);++ await bridge.pushEvent("thinking", { text: "先看看第 2 段有多长。" });+ await expect(page.locator(".thinking-body")).toHaveText("先看看第 2 段有多长。");++ await bridge.pushEvent("tool", {+ id: "t1",+ name: "exec_command",+ summary: "读取文档",+ state: "running",+ });+ await expect(page.locator(".tool-line .tool-name")).toContainText("exec_command");+ await expect(page.locator(".tool-line")).toHaveAttribute("data-state", "running");+ await bridge.pushEvent("tool", {+ id: "t1",+ name: "exec_command",+ summary: "改完第 2 段",+ state: "done",+ });+ await expect(page.locator(".tool-line")).toHaveAttribute("data-state", "done");+ await expect(page.locator(".tool-line .tool-summary")).toHaveText("改完第 2 段");++ await bridge.pushEvent("error", { message: "模型连接失败" });+ await expect(page.locator(".error-line")).toHaveText("模型连接失败");++ expect(errors).toEqual([]);+});++test("审批卡片:允许会回桥,Esc 等于拒绝(契约 §2.4)", async ({ page, errors }) => {+ await openPanel(page);++ await bridge.pushEvent("approval", {+ toolCallId: "call-1",+ name: "exec_command",+ summary: "要改第 3 段",+ });+ await expect(page.locator(".approval")).toContainText("exec_command 需要你的允许");+ await page.getByRole("button", { name: "允许" }).click();+ await expect.poll(async () => bridge.state.approvals.length).toBe(1);+ expect(bridge.state.approvals.at(-1)).toEqual({ toolCallId: "call-1", decision: "allow" });+ await expect(page.locator(".approval")).toContainText("已允许 exec_command");++ await bridge.pushEvent("approval", {+ toolCallId: "call-2",+ name: "write_file",+ summary: "要写文件",+ });+ await page.keyboard.press("Escape");+ await expect.poll(async () => bridge.state.approvals.length).toBe(2);+ expect(bridge.state.approvals.at(-1)).toEqual({ toolCallId: "call-2", decision: "deny" });++ expect(errors).toEqual([]);+});++test("桥推 doc.replace:假文档真的改了,面板回了 result(契约 §2.2、§3、§5)", async ({+ page,+ errors,+}) => {+ await openPanel(page);++ const before = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ expect(before[2]).toBe("本季度共交付三个版本,用户反馈集中在加载速度上。");++ const response = await bridge.runCommand({+ op: "doc.replace",+ args: {+ index: 3,+ text: "本季度交付三个版本,反馈集中在加载速度。",+ expect: "本季度共交付三个版本,用户反馈集中在加载速度上。",+ },+ });++ expect(response.ok).toBe(true);+ expect(response.result).toEqual({ index: 3, text: "本季度交付三个版本,反馈集中在加载速度。" });++ const after = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ expect(after[2]).toBe("本季度交付三个版本,反馈集中在加载速度。");+ expect(after.length).toBe(5);+ // 段落样式没被动过(替换只动正文)+ const styles = await page.evaluate(() =>+ window.__fakeWps.activeDocument().paragraphs.map((item) => item.style),+ );+ expect(styles[2]).toBe("正文");++ expect(errors).toEqual([]);+});++test("expect 不匹配必须报「段落已变,先重新读取」,而且一个字都不改(契约 §3)", async ({+ page,+ errors,+}) => {+ await openPanel(page);++ const before = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ const response = await bridge.runCommand({+ op: "doc.replace",+ args: { index: 3, text: "不该写进去", expect: "其实不是这一段" },+ });++ expect(response.ok).toBe(false);+ expect(response.error).toBe("段落已变,先重新读取");++ const after = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ expect(after).toEqual(before);++ expect(errors).toEqual([]);+});++test("同一个 id 只回答一次(契约 §2.2)", async ({ page, errors }) => {+ await openPanel(page);+ await bridge.waitForCommandClient();++ bridge.pushCommand({ id: "dup-1", op: "doc.read", args: { from: 1, to: 1 } });+ bridge.pushCommand({ id: "dup-1", op: "doc.read", args: { from: 1, to: 1 } });++ await expect+ .poll(async () => bridge.state.results.filter((item) => item.id === "dup-1").length)+ .toBe(1);+ await page.waitForTimeout(300);+ expect(bridge.state.results.filter((item) => item.id === "dup-1").length).toBe(1);+ const answers = bridge.state.results.filter((item) => item.id === "dup-1");+ expect(answers[0].ok).toBe(true);+ expect(answers[0].result.paragraphs[0].text).toBe("季度报告草稿");++ expect(errors).toEqual([]);+});++test("其余 op:read 截断、search、insertAfter、delete、break、reveal、create(契约 §3)", async ({+ page,+ errors,+}) => {+ await openPanel(page);++ // doc.read:1 起闭区间,带样式+ const read = await bridge.runCommand({ op: "doc.read", args: { from: 2, to: 3 } });+ expect(read.ok).toBe(true);+ expect(read.result.paragraphs).toEqual([+ { index: 2, text: "一、本季度概况", style: "标题 2" },+ { index: 3, text: "本季度共交付三个版本,用户反馈集中在加载速度上。", style: "正文" },+ ]);+ expect(read.result.truncated).toBe(false);++ // doc.read:超过 400 段要截断+ await page.evaluate(() => {+ const many = [];+ for (let i = 1; i <= 450; i += 1) many.push({ text: `第 ${i} 段`, style: "正文" });+ window.__fakeWps.setParagraphs(many);+ });+ const capped = await bridge.runCommand({ op: "doc.read", args: {} });+ expect(capped.result.paragraphs.length).toBe(400);+ expect(capped.result.paragraphs.at(-1).index).toBe(400);+ expect(capped.result.truncated).toBe(true);++ // doc.search:大小写不敏感、跳过空段+ await page.evaluate(() =>+ window.__fakeWps.setParagraphs([+ { text: "Alpha 计划", style: "正文" },+ { text: "", style: "正文" },+ { text: "alpha beta", style: "正文" },+ ]),+ );+ const empty = await bridge.runCommand({ op: "doc.search", args: { query: " " } });+ expect(empty.ok).toBe(false);+ expect(empty.error).toContain("搜索词不能为空");+ const search = await bridge.runCommand({ op: "doc.search", args: { query: "ALPHA" } });+ expect(search.result.matches).toEqual([+ { index: 1, text: "Alpha 计划" },+ { index: 3, text: "alpha beta" },+ ]);++ // doc.insertAfter:新段落沿用前一段样式,返回新段号+ await page.evaluate(() =>+ window.__fakeWps.setParagraphs([+ { text: "标题", style: "标题 1" },+ { text: "正文一", style: "正文" },+ ]),+ );+ const inserted = await bridge.runCommand({+ op: "doc.insertAfter",+ args: { index: 1, text: "新的一段" },+ });+ expect(inserted.result).toEqual({ index: 2, text: "新的一段" });+ const afterInsert = await page.evaluate(() => window.__fakeWps.activeDocument().paragraphs);+ expect(afterInsert.map((item) => item.text)).toEqual(["标题", "新的一段", "正文一"]);+ expect(afterInsert[1].style).toBe("标题 1");++ // doc.break:分页符插在该段之后(段落标记之前)+ const broken = await bridge.runCommand({ op: "doc.break", args: { index: 1, kind: "page" } });+ expect(broken.ok).toBe(true);+ expect(broken.result).toEqual({ index: 1 });+ const pageBreak = await page.evaluate(() => window.__fakeWps.paragraphTexts()[0]);+ expect(pageBreak).toBe("标题\f");+ const badKind = await bridge.runCommand({+ op: "doc.break",+ args: { index: 1, kind: "pagebreak" },+ });+ expect(badKind.ok).toBe(false);+ expect(badKind.error).toContain("kind 只能是");++ // doc.reveal:把选区挪到这一段上+ const revealed = await bridge.runCommand({ op: "doc.reveal", args: { index: 3 } });+ expect(revealed.result).toEqual({ index: 3 });+ const selection = await page.evaluate(() => {+ const doc = window.__fakeWps.state.documents[window.__fakeWps.state.active];+ return {+ selection: { ...doc.selection },+ expected: {+ start: doc.paraStart(3),+ end: doc.paraStart(3) + doc.paragraphs[2].text.length + 1,+ },+ };+ });+ expect(selection.selection).toEqual(selection.expected);++ // doc.delete:删掉中间一段+ const deleted = await bridge.runCommand({+ op: "doc.delete",+ args: { index: 2, expect: "新的一段" },+ });+ expect(deleted.result).toEqual({ index: 2 });+ const afterDelete = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ expect(afterDelete).toEqual(["标题\f", "正文一"]);++ // doc.delete:最后一段要拦住并提示 doc.create+ await page.evaluate(() =>+ window.__fakeWps.setParagraphs([{ text: "只剩这一段", style: "正文" }]),+ );+ const last = await bridge.runCommand({ op: "doc.delete", args: { index: 1 } });+ expect(last.ok).toBe(false);+ expect(last.error).toContain("doc.create");++ // doc.create:新建空白文档并切过去+ const created = await bridge.runCommand({ op: "doc.create", args: {} });+ expect(created.ok).toBe(true);+ const newDoc = await page.evaluate(() => window.__fakeWps.activeDocument());+ expect(newDoc.paragraphs.length).toBe(1);+ expect(newDoc.paragraphs[0].text).toBe("");+ const summary = await bridge.runCommand({ op: "doc.summary", args: {} });+ expect(summary.result.paragraphs).toBe(1);+ expect(summary.result.name).toBe(created.result.name);++ // 不认识的 op 也要回答(失败也算回答)+ const unknown = await bridge.runCommand({ op: "doc.nope", args: {} });+ expect(unknown.ok).toBe(false);+ expect(unknown.error).toContain("不认识的文档操作");++ expect(errors).toEqual([]);+});++test("选区变了以后防抖上报,带上 1 起的段号(契约 §2.1)", async ({ page, errors }) => {+ await openPanel(page);+ await bridge.waitFor((snapshot) => snapshot.hellos.length > 0);++ await page.evaluate(() => window.__fakeWps.selectParagraphs(2, 3));++ await expect+ .poll(async () => bridge.state.hellos.filter((hello) => hello.doc?.selection).length, {+ timeout: 15_000,+ })+ .toBeGreaterThan(0);++ const hello = bridge.state.hellos.filter((item) => item.doc?.selection).at(-1);+ expect(hello.doc.selection.from).toBe(2);+ expect(hello.doc.selection.to).toBe(3);+ expect(hello.doc.selection.text).toContain("本季度共交付三个版本");+ await expect(page.locator("#doc-line")).toContainText("选中第 2–3 段");++ expect(errors).toEqual([]);+});++test("「写进文档」把回复按段落插进文档(契约 §2.4)", async ({ page, errors }) => {+ await openPanel(page);++ await bridge.pushEvent("done", { text: "第一段回复\n第二段回复" });+ await page.getByRole("button", { name: "写进文档" }).click();++ await expect+ .poll(async () => (await page.evaluate(() => window.__fakeWps.paragraphTexts())).length)+ .toBe(7);+ const texts = await page.evaluate(() => window.__fakeWps.paragraphTexts());+ expect(texts.slice(-2)).toEqual(["第一段回复", "第二段回复"]);+ await expect(page.locator(".toast")).toContainText("已写入 2 段");++ expect(errors).toEqual([]);+});++test("打开面板会回放这篇文档聊过的历史(契约 §2.4)", async ({ page, errors }) => {+ await bridge.reset();+ await bridge.set({+ history: [+ { role: "user", text: "之前的问题" },+ { role: "assistant", text: "之前的回答" },+ ],+ });+ await openPanel(page);++ await expect(page.locator(".msg.user")).toHaveText("之前的问题");+ await expect(page.locator(".msg.assistant .turn-text")).toHaveText("之前的回答");++ expect(errors).toEqual([]);+});++test("深浅色切换会记住(web-design)", async ({ page, errors }) => {+ await openPanel(page);++ const before = await page.evaluate(() => document.documentElement.classList.contains("dark"));+ await page.click("#theme");+ const after = await page.evaluate(() => document.documentElement.classList.contains("dark"));+ expect(after).toBe(!before);++ await page.reload();+ await expect(page.locator("#send")).toBeVisible();+ const reloaded = await page.evaluate(() => document.documentElement.classList.contains("dark"));+ expect(reloaded).toBe(after);++ expect(errors).toEqual([]);+});diff --git a/plugins/use-wps-office/test/playwright.config.mjs b/plugins/use-wps-office/test/playwright.config.mjsnew file mode 100644index 00000000..ff2a57d3--- /dev/null+++ b/plugins/use-wps-office/test/playwright.config.mjs@@ -0,0 +1,49 @@+import { existsSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++/**+ * @playwright/test 是仓库 packages/web 的依赖(插件本身不带依赖),所以从那里解析:+ * 从本文件往上找到 <仓库>/packages/web/package.json,用它的解析器 require。找不到就退回+ * 普通解析(万一以后装在别处)。+ */+function loadPlaywright() {+ let directory = dirname(fileURLToPath(import.meta.url));+ for (let depth = 0; depth < 6; depth += 1) {+ const manifest = join(directory, "packages", "web", "package.json");+ if (existsSync(manifest)) return createRequire(manifest)("@playwright/test");+ directory = dirname(directory);+ }+ return createRequire(import.meta.url)("@playwright/test");+}++const { defineConfig } = loadPlaywright();++/**+ * WPS 面板的浏览器冒烟测试(契约 §5)。+ *+ * baseURL 走环境变量:默认打到假桥(fake-bridge.mjs)在 127.0.0.1:3891 起的地址;+ * 主 agent 拿真桥(kit/serve.mjs)跑对照测试时,用 PANEL_BASE_URL 指过去即可。+ * 跑法(仓库的 @playwright/test 装在 packages/web 下):+ * cd packages/web && npx playwright test -c ../../plugins/wps-office/test/playwright.config.mjs+ */+export default defineConfig({+ testDir: ".",+ // 这个目录里还躺着桥和安装脚本的 node:test 文件;Playwright 会 import 一切 test 文件,+ // 那不是我们要跑的东西,所以只认面板这份 spec。+ testMatch: /panel\.spec\.mjs$/,+ // 失败截图之类的产物不放仓库里(默认会落在仓库根目录,污染 git status),丢进系统临时目录。+ outputDir: join(tmpdir(), "adelie-wps-panel-playwright"),+ timeout: 60_000,+ expect: { timeout: 10_000 },+ fullyParallel: false,+ workers: 1,+ reporter: [["list"]],+ use: {+ baseURL: process.env.PANEL_BASE_URL || "http://127.0.0.1:3891",+ headless: true,+ locale: "zh-CN",+ },+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d929aa9b..a2d7746a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -105,6 +105,9 @@ importers:'@lmliheng/use-firecrawl':specifier: workspace:*version: link:../../plugins/use-firecrawl+ '@lmliheng/use-wps-office':+ specifier: workspace:*+ version: link:../../plugins/use-wps-office'@lmliheng/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -196,6 +199,9 @@ importers:'@lmliheng/use-firecrawl':specifier: workspace:*version: link:../../plugins/use-firecrawl+ '@lmliheng/use-wps-office':+ specifier: workspace:*+ version: link:../../plugins/use-wps-office'@lmliheng/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -293,6 +299,9 @@ importers:'@lmliheng/use-firecrawl':specifier: workspace:*version: link:../../plugins/use-firecrawl+ '@lmliheng/use-wps-office':+ specifier: workspace:*+ version: link:../../plugins/use-wps-office'@lmliheng/wechat-miniprogram':specifier: workspace:*version: link:../../plugins/wechat-miniprogram@@ -771,6 +780,8 @@ importers:plugins/use-firecrawl: {}+ plugins/use-wps-office: {}+plugins/wechat-miniprogram: {}packages:@@ -1531,6 +1542,9 @@ packages:'@lmliheng/use-firecrawl@file:plugins/use-firecrawl':resolution: {directory: plugins/use-firecrawl, type: directory}+ '@lmliheng/use-wps-office@file:plugins/use-wps-office':+ resolution: {directory: plugins/use-wps-office, type: directory}+'@lmliheng/wechat-miniprogram@file:plugins/wechat-miniprogram':resolution: {directory: plugins/wechat-miniprogram, type: directory}@@ -5599,6 +5613,7 @@ snapshots:'@lmliheng/use-bento-slides': file:plugins/use-bento-slides'@lmliheng/use-claude-code': file:plugins/use-claude-code'@lmliheng/use-firecrawl': file:plugins/use-firecrawl+ '@lmliheng/use-wps-office': file:plugins/use-wps-office'@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.15([email protected])([email protected])@@ -5634,6 +5649,7 @@ snapshots:'@lmliheng/use-bento-slides': file:plugins/use-bento-slides'@lmliheng/use-claude-code': file:plugins/use-claude-code'@lmliheng/use-firecrawl': file:plugins/use-firecrawl+ '@lmliheng/use-wps-office': file:plugins/use-wps-office'@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0'@prismshadow/agenthub': 0.4.15([email protected])([email protected])@@ -5667,6 +5683,7 @@ snapshots:'@lmliheng/use-bento-slides': file:plugins/use-bento-slides'@lmliheng/use-claude-code': file:plugins/use-claude-code'@lmliheng/use-firecrawl': file:plugins/use-firecrawl+ '@lmliheng/use-wps-office': file:plugins/use-wps-office'@lmliheng/wechat-miniprogram': file:plugins/wechat-miniprogram'@modelcontextprotocol/client': 2.0.0@@ -5758,6 +5775,8 @@ snapshots:'@lmliheng/use-firecrawl@file:plugins/use-firecrawl': {}+ '@lmliheng/use-wps-office@file:plugins/use-wps-office': {}+'@lmliheng/wechat-miniprogram@file:plugins/wechat-miniprogram': {}'@malept/[email protected]':