From ebea992b10698fb5cf1f7c3f5de7fa58c4c39987 Mon Sep 17 00:00:00 2001 From: Wxw-Gu <84499436+Wxw-Gu@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:54:37 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=96=B0=E5=A2=9E=E6=8B=93=E5=B1=95?= =?UTF-8?q?=E4=B8=AD=E5=BF=83=E5=8A=9F=E8=83=BD,=20=E6=8F=90=E4=BE=9B=20?= =?UTF-8?q?=E5=85=B3=E9=94=AE=E8=AF=8D=E5=9B=9E=E5=A4=8D=20=E5=8E=BB?= =?UTF-8?q?=E6=B0=B4=E5=8D=B0=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 + docs/README.md | 2 + docs/extensions/api-reference.md | 187 +++++ docs/extensions/architecture.md | 99 +++ docs/extensions/clone-and-customize.md | 170 ++++ docs/extensions/getting-started.md | 141 ++++ docs/extensions/security.md | 86 ++ electron.vite.config.ts | 2 + eslint.config.mjs | 9 + examples/extensions/README.md | 37 + examples/extensions/douyin-sender/README.md | 143 ++++ .../douyin-sender/background/index.js | 766 ++++++++++++++++++ .../extensions/douyin-sender/lib/douyin.js | 354 ++++++++ .../extensions/douyin-sender/manifest.json | 35 + .../douyin-sender/tests/douyin.test.mjs | 412 ++++++++++ examples/extensions/douyin-sender/ui/app.js | 620 ++++++++++++++ .../extensions/douyin-sender/ui/index.html | 192 +++++ .../extensions/douyin-sender/ui/style.css | 387 +++++++++ examples/extensions/keyword-bot/README.md | 116 +++ .../keyword-bot/background/index.js | 221 +++++ .../extensions/keyword-bot/lib/matcher.js | 213 +++++ examples/extensions/keyword-bot/manifest.json | 42 + .../keyword-bot/tests/matcher.test.mjs | 279 +++++++ examples/extensions/keyword-bot/ui/app.js | 495 +++++++++++ examples/extensions/keyword-bot/ui/index.html | 71 ++ examples/extensions/keyword-bot/ui/style.css | 384 +++++++++ packages/extension-sdk/README.md | 27 + packages/extension-sdk/index.d.ts | 188 +++++ packages/extension-sdk/package.json | 9 + .../extensions/extension-action-registry.ts | 134 +++ .../extensions/extension-automation-bridge.ts | 45 + src/main/extensions/extension-entitlement.ts | 74 ++ src/main/extensions/extension-event-bus.ts | 135 +++ src/main/extensions/extension-host.ts | 677 ++++++++++++++++ src/main/extensions/extension-installer.ts | 390 +++++++++ src/main/extensions/extension-ipc.ts | 195 +++++ src/main/extensions/extension-log.ts | 125 +++ src/main/extensions/extension-manager.ts | 761 +++++++++++++++++ src/main/extensions/extension-paths.ts | 65 ++ src/main/extensions/extension-protocol.ts | 101 +++ src/main/extensions/extension-registry.ts | 155 ++++ src/main/extensions/extension-send-gateway.ts | 358 ++++++++ src/main/extensions/extension-service.ts | 128 +++ src/main/extensions/extension-storage.ts | 142 ++++ src/main/extensions/host-runtime.ts | 545 +++++++++++++ src/main/index.ts | 62 +- src/main/services/automation-action-runner.ts | 208 ++++- src/main/services/automation-service.ts | 49 +- .../services/mac-wechat-runtime-manager.ts | 35 +- src/main/services/message-listener-service.ts | 46 +- .../personal-wechat-capability-service.ts | 3 +- .../services/personal-wechat-send-service.ts | 179 +++- src/main/services/wechat-action-gateway.ts | 82 +- src/main/wcdb4-client.ts | 24 +- src/preload/index.d.ts | 36 + src/preload/index.ts | 40 + src/renderer/index.html | 2 +- src/renderer/src/App.tsx | 3 + .../components/layout/PrimaryNavigation.tsx | 9 + .../src/components/layout/navigation.ts | 2 + .../features/extensions/ExtensionPageHost.tsx | 122 +++ .../extensions/ExtensionWorkspace.tsx | 494 +++++++++++ src/renderer/src/styles/extensions.scss | 597 ++++++++++++++ src/renderer/src/styles/index.scss | 1 + src/shared/automation.ts | 62 +- src/shared/extensions/errors.ts | 98 +++ src/shared/extensions/events.ts | 123 +++ src/shared/extensions/ipc.ts | 62 ++ src/shared/extensions/manifest.ts | 419 ++++++++++ src/shared/extensions/permissions.ts | 127 +++ src/shared/extensions/rpc.ts | 219 +++++ src/shared/extensions/types.ts | 124 +++ src/shared/personal-wechat.ts | 16 + src/shared/wechat-action.ts | 3 + .../integration/extension-automation.test.ts | 272 +++++++ tests/integration/extension-lifecycle.test.ts | 328 ++++++++ tests/unit/extension-event-bus.test.ts | 177 ++++ tests/unit/extension-examples.test.ts | 46 ++ tests/unit/extension-host.test.ts | 230 ++++++ tests/unit/extension-installer.test.ts | 242 ++++++ tests/unit/extension-manifest.test.ts | 120 +++ tests/unit/extension-send-gateway.test.ts | 338 ++++++++ tests/unit/extension-state.test.ts | 111 +++ tests/unit/message-listener-service.test.ts | 11 + .../unit/personal-wechat-send-service.test.ts | 14 + 85 files changed, 14750 insertions(+), 106 deletions(-) create mode 100644 docs/extensions/api-reference.md create mode 100644 docs/extensions/architecture.md create mode 100644 docs/extensions/clone-and-customize.md create mode 100644 docs/extensions/getting-started.md create mode 100644 docs/extensions/security.md create mode 100644 examples/extensions/README.md create mode 100644 examples/extensions/douyin-sender/README.md create mode 100644 examples/extensions/douyin-sender/background/index.js create mode 100644 examples/extensions/douyin-sender/lib/douyin.js create mode 100644 examples/extensions/douyin-sender/manifest.json create mode 100644 examples/extensions/douyin-sender/tests/douyin.test.mjs create mode 100644 examples/extensions/douyin-sender/ui/app.js create mode 100644 examples/extensions/douyin-sender/ui/index.html create mode 100644 examples/extensions/douyin-sender/ui/style.css create mode 100644 examples/extensions/keyword-bot/README.md create mode 100644 examples/extensions/keyword-bot/background/index.js create mode 100644 examples/extensions/keyword-bot/lib/matcher.js create mode 100644 examples/extensions/keyword-bot/manifest.json create mode 100644 examples/extensions/keyword-bot/tests/matcher.test.mjs create mode 100644 examples/extensions/keyword-bot/ui/app.js create mode 100644 examples/extensions/keyword-bot/ui/index.html create mode 100644 examples/extensions/keyword-bot/ui/style.css create mode 100644 packages/extension-sdk/README.md create mode 100644 packages/extension-sdk/index.d.ts create mode 100644 packages/extension-sdk/package.json create mode 100644 src/main/extensions/extension-action-registry.ts create mode 100644 src/main/extensions/extension-automation-bridge.ts create mode 100644 src/main/extensions/extension-entitlement.ts create mode 100644 src/main/extensions/extension-event-bus.ts create mode 100644 src/main/extensions/extension-host.ts create mode 100644 src/main/extensions/extension-installer.ts create mode 100644 src/main/extensions/extension-ipc.ts create mode 100644 src/main/extensions/extension-log.ts create mode 100644 src/main/extensions/extension-manager.ts create mode 100644 src/main/extensions/extension-paths.ts create mode 100644 src/main/extensions/extension-protocol.ts create mode 100644 src/main/extensions/extension-registry.ts create mode 100644 src/main/extensions/extension-send-gateway.ts create mode 100644 src/main/extensions/extension-service.ts create mode 100644 src/main/extensions/extension-storage.ts create mode 100644 src/main/extensions/host-runtime.ts create mode 100644 src/renderer/src/features/extensions/ExtensionPageHost.tsx create mode 100644 src/renderer/src/features/extensions/ExtensionWorkspace.tsx create mode 100644 src/renderer/src/styles/extensions.scss create mode 100644 src/shared/extensions/errors.ts create mode 100644 src/shared/extensions/events.ts create mode 100644 src/shared/extensions/ipc.ts create mode 100644 src/shared/extensions/manifest.ts create mode 100644 src/shared/extensions/permissions.ts create mode 100644 src/shared/extensions/rpc.ts create mode 100644 src/shared/extensions/types.ts create mode 100644 tests/integration/extension-automation.test.ts create mode 100644 tests/integration/extension-lifecycle.test.ts create mode 100644 tests/unit/extension-event-bus.test.ts create mode 100644 tests/unit/extension-examples.test.ts create mode 100644 tests/unit/extension-host.test.ts create mode 100644 tests/unit/extension-installer.test.ts create mode 100644 tests/unit/extension-manifest.test.ts create mode 100644 tests/unit/extension-send-gateway.test.ts create mode 100644 tests/unit/extension-state.test.ts diff --git a/.gitignore b/.gitignore index 077e595..25fd124 100644 --- a/.gitignore +++ b/.gitignore @@ -31,3 +31,6 @@ task_plan.md *libtmlicense* debug-originals /build/mac-staging/ + +# 去水印脚本 +/examples/extensions/douyin-sender/scripts/douyin.py diff --git a/docs/README.md b/docs/README.md index 18ca6f2..c05c4ca 100644 --- a/docs/README.md +++ b/docs/README.md @@ -50,6 +50,8 @@ Agent Hub 让微信机器人调用本机 TraceMemo;Reader Skill / Local HTTP A ## 开发文档 - [开发、测试与构建](./development/overview.md) +- [克隆 TraceMemo 后开发自己的扩展](./extensions/clone-and-customize.md) +- [扩展 API 参考](./extensions/api-reference.md) - [界面开发规范:按钮与主题色](./development/ui-guidelines.md) - [微信系统消息解析与格式兼容](./development/wechat-system-message-parsing.md) - [Query Agent POC(开发测试入口)](./development/query-agent-poc.md) diff --git a/docs/extensions/api-reference.md b/docs/extensions/api-reference.md new file mode 100644 index 0000000..a76a508 --- /dev/null +++ b/docs/extensions/api-reference.md @@ -0,0 +1,187 @@ +# 扩展 API 参考(v1) + +## manifest.json + +| 字段 | 必填 | 说明 | +| --- | --- | --- | +| `manifestVersion` | 是 | 固定 `1` | +| `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 | +| `name` | 是 | 展示名,≤ 64 字 | +| `version` | 是 | `x.y.z`(可带 prerelease) | +| `apiVersion` | 是 | 必须为 `1` | +| `minAppVersion` | 否 | 低于该版本拒绝安装 | +| `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) | +| `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 | +| `entrypoints.page` | 二选一 | 页面 HTML 相对路径 | +| `entrypoints.background` | 二选一 | 后台入口相对路径 | +| `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 | +| `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` | +| `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background | + +路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名; +安装时还会用 realpath 复核入口仍在扩展目录内。 + +## 权限 + +| 权限 | 风险 | 能力 | +| --- | --- | --- | +| `messages.subscribe` | 高 | 接收 `message.received` | +| `messages.query` | 高 | `tm.messages.query` | +| `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 | +| `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` | +| `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` | +| `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video | +| `ai.chat` | 中 | `tm.ai.chat` | +| `storage` | 低 | `tm.storage.*` 与页面存储 | +| `automation.action` | 中 | `tm.automation.registerAction` | + +安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。 + +## 后台 API + +### tm.extension + +- `id: string` +- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验) +- `permissions: string[]`(当前已授予) + +### tm.events + +- `on('message.received', handler): () => void` +- `off('message.received', handler): void` + +事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId / +senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。 + +### tm.messages.query + +```ts +await tm.messages.query({ conversationId, startTime?, endTime?, limit? }) +// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] } +``` + +- 时间参数是 **epoch 毫秒**;默认最近 24 小时。 +- 单次窗口最多 7 天,`limit` 上限 200。 +- 数据库未连接时抛 `DATABASE_NOT_READY`。 + +### tm.wechat.send + +```ts +// 文本 +await tm.wechat.send({ to, text, at?, dedupeKey? }) + +// 图片 +await tm.wechat.send({ type: 'image', to, path: '/abs/path/cover.png', dedupeKey? }) + +// 视频(原生 Host 以 {toWxid, type:'video', msg:<路径>} 提交) +await tm.wechat.send({ type: 'video', to, path: '/abs/path/clip.mp4', dedupeKey? }) +// → { actionId, status: 'sent' } +``` + +按顺序检查:权限 → 参数(文本 ≤ 2000 字)→ manifest 会话范围 → 频率 +(同扩展 2 秒一条、每分钟 10 条)→ 本机发送能力 → 授权校验 → Gateway。 +任何一步不通过都抛带错误码的异常,不会「静默丢弃」。 + +媒体路径额外约束: + +- 必须是**绝对路径**的普通文件,realpath 后仍位于**扩展数据目录**或**系统临时目录**; +- 大小 1B–100MB; +- 图片扩展名:jpg/jpeg/png/gif/webp/bmp;视频扩展名:mp4/mov/m4v; +- 视频走 `type: 'video'`,不复用图片通道;发送失败不会降级成图片。 + +### tm.ai.chat + +```ts +await tm.ai.chat([{ role: 'user', content: '...' }]) +// → { text } +``` + +使用 TraceMemo 已配置的 AI Provider;扩展拿不到 API Key。 + +### tm.storage + +```ts +await tm.storage.set('config', { ... }) +await tm.storage.get('config') +await tm.storage.remove('config') +await tm.storage.list() +``` + +键:`[A-Za-z0-9._-]{1,64}`;单值 ≤ 256KB,总量 ≤ 1MB;只接受 JSON 值。 + +### tm.automation.registerAction + +```ts +tm.automation.registerAction({ id, title, description?, inputSchema?, handler }) +``` + +`id`:`[a-z0-9][a-z0-9._-]{1,63}`。`handler` 返回: + +```ts +{ success: boolean, output?: object, reply?: { type: 'text', text, at? }, error?: string } +``` + +`inputSchema` 只支持 `object` + `string|number|boolean` 属性的浅校验;必填项缺失会直接拒绝。 + +执行超时默认 15 秒(宿主可配,最大 60 秒),超时返回 `ACTION_TIMEOUT`。 + +### tm.capabilities.get + +返回只读快照:`enabled / permissions / platform / databaseReady / send{...} / ai{...}`。 + +### tm.log + +`info / warn / error`,写入扩展日志(详情页可见,最多保留 200 条,单行 ≤ 500 字)。 + +## 页面桥 + +页面 → 宿主: + +```ts +{ source: 'tracememo-extension-page', extensionId, requestId, method, params } +``` + +宿主 → 页面: + +```ts +{ source: 'tracememo-extension-host', requestId, ok: true, result } +{ source: 'tracememo-extension-host', requestId, ok: false, error: { code, message } } +``` + +页面方法白名单:`storage.get|set|remove|list`、`capabilities.get`、`contacts.listGroups`、`extension.info`。 +页面不能发送微信消息、不能查询消息、不能调用 AI。 + +## 错误码 + +| 码 | 含义 | +| --- | --- | +| `EXTENSION_NOT_FOUND` | 扩展不存在 / 已卸载 | +| `EXTENSION_DISABLED` | 扩展未启用 | +| `EXTENSION_INCOMPATIBLE` | apiVersion 或 minAppVersion 不满足 | +| `EXTENSION_INVALID_MANIFEST` | manifest 不合法 | +| `EXTENSION_INVALID_PATH` | 入口 / 资源路径越界 | +| `EXTENSION_HOST_UNAVAILABLE` | 后台进程未运行 | +| `PERMISSION_DENIED` | 未授予权限,或超出声明范围 | +| `CAPABILITY_UNAVAILABLE` | 本机能力不具备(未绑定 / 未就绪) | +| `LICENSE_REQUIRED` | 无有效授权 | +| `DATABASE_NOT_READY` | 微信数据库未连接 | +| `SEND_NOT_SUPPORTED` | 当前平台或内容类型不支持 | +| `ACTION_TIMEOUT` | 处理超时 | +| `ACTION_FAILED` | 执行失败 | +| `RATE_LIMITED` | 触发频率限制 | +| `INVALID_REQUEST` | 参数非法 | +| `STORAGE_LIMIT_EXCEEDED` | 存储超限 | + +## 自动化动作输入 + +规则里保存的静态 `input` 会与宿主注入字段合并,同名键以宿主为准: + +```json +{ + "url": "https://example.com/video", + "conversationId": "xxx@chatroom", + "isGroup": true, + "accountId": "wxid_self", + "message": { "eventId": "message:...", "text": "...", "mentionsMe": false } +} +``` diff --git a/docs/extensions/architecture.md b/docs/extensions/architecture.md new file mode 100644 index 0000000..c6689a9 --- /dev/null +++ b/docs/extensions/architecture.md @@ -0,0 +1,99 @@ +# 扩展中心架构(v1) + +## 目标 + +把用户二次开发从官方源码里剥离:扩展装在自己的目录、走稳定的 SDK、由宿主做权限与能力检查。 +官方升级只替换应用本体,不触碰扩展目录与数据目录。 + +## 分层 + +```text +TraceMemo Core(Electron 主进程 / 渲染层) + │ +ExtensionManager ─── ExtensionRegistry(启用状态 / 授权集合) + │ ExtensionInstaller(目录 / ZIP 安装,原子替换) + │ ExtensionLogStore(日志) + │ ExtensionActionRegistry(自动化动作) + │ ExtensionEventBus(消息事件分发) + │ + ExtensionHost(每个扩展一个 Node 子进程) + │ require(background/index.js),注入 tm + │ + tm.* ── 白名单 RPC ──▶ 宿主能力 + ├─ storage → extensions-data/ + ├─ messages.query→ chat-service(有界窗口) + ├─ wechat.send → ExtensionSendGateway → WechatActionGateway + ├─ ai.chat → AIProviderService + └─ capabilities → 只读快照 +``` + +关键边界: + +- **主进程从不 `require` 扩展代码**;扩展只在子进程里加载。 +- 扩展不 import 官方业务模块,只通过 JSON RPC 申请能力。 +- 发送、消息读取、AI 调用全部复用既有服务,没有第二套监听或发送实现。 + +## 目录 + +```text +/ + extensions// 代码(manifest.json / ui / background) + extensions-data// 扩展私有数据(storage.json) + extensions-state/ 宿主状态 + registry.json 启用状态与已授予权限 + logs/.jsonl 运行日志(轮转一份 .1) + extensions-staging/ 安装临时目录(成功后原子改名) +``` + +三者分离的原因: + +| 场景 | 结果 | +| --- | --- | +| 官方应用升级 | `userData` 不变,扩展与配置原样保留 | +| 扩展升级(同 id 新版本) | 只替换 `extensions/`,`extensions-data` 不动 | +| 卸载并选择保留数据 | 删除代码目录,保留 `extensions-data` | +| 卸载并清除数据 | 同时删除数据目录与日志 | + +## 生命周期 + +```text +install → 校验 manifest / 入口 → 临时目录 → 原子替换 → 登记(默认未启用) +enable → 授予 manifest 声明的权限 → 启动子进程 → activate 握手 → active +message → ExtensionEventBus 去重 → 按 subscriptions 过滤 → 投递给子进程 +action → 自动化 runner → ExtensionHost.invokeAction → 返回 reply / output +disable → 停止子进程 → 撤销高风险权限(仅保留 storage)→ inactive +upgrade → 停进程 → 替换目录 → 保留 enabled 与授权 → 重启 +``` + +崩溃处理:子进程异常退出时按 1s / 2s / 4s 退避重启,5 分钟内超过 3 次标记为 +`crashed` 并停止自动重启,等用户手动停用再启用。 + +## 消息事件 + +- 事件来源只有 `MessageListenerService` 的规范化结果,不直连数据库。 +- `eventId = message:`,同一条消息稳定不变。 +- `mentionsMe` 来自 `source.atuserlist` ∩ 当前账号 username;拿不到自身身份时为 `false`。 +- 分发前做 manifest 级过滤(消息类型 / 会话范围 / 是否 @我 / 是否包含自己)。 +- 子进程侧有令牌桶(容量 100,按 60/秒补充);超出时丢弃并记一条 warn, + 不让扩展拖慢主进程监听循环。 + +**已知降级**:旧 Native Runtime 的事件不带 `sessionId`,监听层只能回读「最近活跃会话」。 +事件总线不掩盖这一点,自动化状态与扩展能力快照都按「降级」标记。 + +## 发送链路 + +```text +tm.wechat.send + → ExtensionHost(权限检查)→ ExtensionSendGateway(权限 / 范围 / 频率 / 能力 / 授权校验) + → WechatActionGateway.executeFromExtension(origin=extension, purpose=extension_send) + → WechatSendGateway → Windows / macOS sender +``` + +自动化动作返回的 `reply` 走同一条 Gateway,但 purpose 是 `extension_action`, +幂等键由 `executionId` 派生。扩展无法传入 `origin` / `purpose` / `triggerType`。 + +## 与自动化的关系 + +- 扩展注册动作,自动化负责触发、过滤、冷却、幂等、执行日志。 +- 自动化规则里的 `extensionAction` 只保存 `extensionId + actionId + 静态 input`; + 卸载扩展后规则**保留**,执行时明确报 `EXTENSION_NOT_FOUND`,不会静默删除用户配置。 diff --git a/docs/extensions/clone-and-customize.md b/docs/extensions/clone-and-customize.md new file mode 100644 index 0000000..e5bd098 --- /dev/null +++ b/docs/extensions/clone-and-customize.md @@ -0,0 +1,170 @@ +# 克隆 TraceMemo 后开发自己的扩展 + +本指南说明如何从 TraceMemo 示例开始,编写、安装和调试自己的扩展。扩展代码与 TraceMemo 主程序分开维护;通常只需要写一个扩展目录,不必改 TraceMemo 的业务源码。 + +本文适用于包含 Extension Center v1 的 TraceMemo 版本,扩展 API 版本为 `1`。较早的源码或安装包如果还没有左侧「扩展」入口,需要先使用包含 Extension Center 的分支或版本。 + +## 1. 克隆并启动 TraceMemo + +先按项目开发文档准备 Node.js 与 pnpm,然后克隆源码、安装依赖并启动开发版: + +```bash +git clone https://github.com/Wxw-Gu/TraceMemo.git +cd TraceMemo +pnpm install +pnpm dev +``` + +`pnpm dev` 启动的是 TraceMemo 开发版。扩展安装后会复制到应用的用户数据目录;修改源码目录里的文件不会自动同步到已安装副本,每次改完都要重新安装同一扩展目录。 + +## 2. 从示例创建扩展 + +建议先复制示例,再按功能删改文件: + +```bash +cp -R examples/extensions/keyword-bot ../my-tracememo-extension +``` + +`keyword-bot` 带有规则、匹配与发送逻辑;如果只是做最小扩展,保留 `manifest.json`、`ui/` 与 `storage` 用法,删除 `lib/`、规则 UI 以及 `background` 里的匹配/发送代码即可。 + +目录通常如下: + +```text +my-tracememo-extension/ + manifest.json 扩展身份、入口和权限声明 + background/index.js 可选;后台逻辑,运行于独立 Node 子进程 + ui/ 可选;扩展页面,运行于 sandbox iframe + index.html + app.js + style.css +``` + +最小扩展只要求有一个页面或后台入口。可先从 `keyword-bot` 保留 `manifest.json`、页面桥与 `storage` 用法,再把 `manifest.json` 中的 `id`、`name`、`description`、`author` 改成自己的信息;`id` 是反向域名格式,例如 `com.example.my-helper`,必须唯一,不能使用 `com.tracememo.`、`tracememo.` 或 `tm.` 前缀。版本采用 `x.y.z` 格式。 + +示例中的页面脚本也有一个 `EXTENSION_ID` 常量,使用页面桥时要将它改成 manifest 中完全相同的 id。稳定 id 很重要:相同 id 的升级会保留该扩展的配置;换 id 则会被视为另一个扩展。 + +典型 manifest: + +```json +{ + "manifestVersion": 1, + "id": "com.example.my-helper", + "name": "我的扩展", + "version": "1.0.0", + "apiVersion": "1", + "minAppVersion": "2.6.0", + "description": "我的 TraceMemo 扩展", + "permissions": ["storage"], + "entrypoints": { + "page": "ui/index.html", + "background": "background/index.js" + }, + "contributions": { + "pages": [{ "id": "settings", "title": "设置" }] + } +} +``` + +`minAppVersion` 是最低应用版本,可按扩展实际依赖调整。入口路径必须是扩展目录内的安全相对路径;安装器会检查 manifest 和入口文件。 + +## 3. 编写后台逻辑 + +后台入口导出 `activate(tm)`。TraceMemo 会在扩展启用时启动独立 Node 子进程,并注入 `tm` API: + +```js +module.exports = function activate(tm) { + tm.log.info(`扩展已启动:${tm.extension.id}`) + + tm.events.on('message.received', async (event) => { + if (event.isSelf || !event.mentionsMe || !event.text) return + + await tm.wechat.send({ + to: event.conversationId, + text: '收到,我来处理。', + dedupeKey: event.eventId + }) + }) +} +``` + +上面这个例子需要在 manifest 中声明 `messages.subscribe`、`wechat.send.text`,并声明消息订阅范围: + +```json +{ + "permissions": ["messages.subscribe", "wechat.send.text", "storage"], + "subscriptions": { + "messageTypes": ["text"], + "conversationIds": [], + "requireMentionMe": true, + "includeSelf": false + } +} +``` + +按需申请权限,不要为了省事把所有权限都加上。高、中风险权限会在启用时要求用户确认;没有获得相应授权的 API 会返回权限错误。微信发送仍经过 TraceMemo 的权限、范围、频率、发送能力和授权校验。 + +可用 API 包括 `tm.events`、有界的 `tm.messages.query`、`tm.wechat.send`、`tm.ai.chat`、`tm.storage`、`tm.automation.registerAction`、`tm.capabilities.get` 和 `tm.log`。字段、限制与错误码见[扩展 API 参考](./api-reference.md)。仓库的 `packages/extension-sdk/index.d.ts` 只提供类型定义,不是运行时依赖;运行时的 `tm` 由 TraceMemo 注入。 + +## 4. 编写扩展页面 + +页面在 sandbox iframe 中运行,不能访问 `window.api`、Node 或 Electron。需要调用宿主白名单功能时,通过 `postMessage` 页面桥通信。可参考 `examples/extensions/keyword-bot/ui/app.js` 里的 `callHost()` 与消息处理,并更新其中的扩展 id。页面桥目前允许存储读写、能力查询、群列表查询(需 `contacts.list`)和扩展信息查询;页面不能直接读取聊天消息、调用 AI 或发送微信。 + +后台逻辑使用 `tm.storage`;页面则通过页面桥的 `storage.get` / `storage.set` 等方法访问同一扩展的私有存储。 + +## 5. 在 TraceMemo 中安装和调试 + +1. 在开发版或已支持扩展的 TraceMemo 中打开左侧「扩展」。 +2. 选择「安装目录」,指向 `my-tracememo-extension`。也可以将扩展文件打成 ZIP;`manifest.json` 必须位于 ZIP 根目录,然后选择「安装 ZIP」。 +3. 安装完成后,选中扩展并点「启用」。检查权限清单,只确认扩展功能确实需要的权限。 +4. 有页面入口时点「打开页面」;检查配置是否读写正常。后台运行日志可在扩展详情页查看。 +5. 修改源码后重新安装同一个目录,以更新已安装副本;如后台进程仍未刷新,再停用后重新启用。页面资源更新后重新打开或刷新扩展页面。 + +同一 `id` 重新安装会更新扩展代码并保留已授予权限、启用状态和扩展存储。卸载默认保留数据;需要清理时再明确选择删除数据。 + +## 6. 编写和运行测试 + +纯 JavaScript 扩展可用 Node 内置检查器与测试运行器,不需要把扩展依赖装进 TraceMemo: + +```bash +node --check ../my-tracememo-extension/background/index.js +node --test ../my-tracememo-extension/tests/*.test.mjs +``` + +若扩展放在 TraceMemo 仓库的 `examples/extensions/` 下,也可以参照示例的测试命令,例如: + +```bash +node --test examples/extensions/keyword-bot/tests/matcher.test.mjs +``` + +改动 TraceMemo 扩展宿主、SDK 契约或示例校验时,再运行对应的 TraceMemo 测试: + +```bash +pnpm exec vitest run --config vitest.unit.config.ts tests/unit/extension-manifest.test.ts tests/unit/extension-installer.test.ts tests/unit/extension-host.test.ts +pnpm typecheck +``` + +## 7. 自动化动作 + +扩展可以在 manifest 中用 `contributions.automationActions` 声明动作,并申请 `automation.action`;后台通过 `tm.automation.registerAction()` 注册实现。动作返回的 `reply` 由 TraceMemo 宿主经统一 Gateway 发送,扩展不应自行绕过 Gateway。 + +当前版本可以在扩展详情页查看动作是否已注册;自动化规则编辑器尚未提供选择扩展动作的入口,因此目前不能通过界面把这些扩展动作配置到规则中。相关执行接口已在宿主侧实现,界面入口开放后再按产品文档配置。 + +## 8. 安全与发布前检查 + +扩展后台虽然运行在独立进程,但这**不是操作系统级沙箱**。它是任意 Node.js 代码,拥有运行 TraceMemo 用户的文件与网络权限。只安装自己编写或信任来源的扩展,不要把不可信扩展当成受隔离代码。 + +发布前至少确认: + +- manifest id 唯一、版本递增、权限最小化,所有入口文件都在扩展目录内; +- 页面只使用受支持的 postMessage 白名单,不假设能访问 Electron API; +- 消息回调处理异常并使用稳定的 `dedupeKey`; +- 单元测试覆盖纯逻辑,人工验证安装、启用、停用、重装和配置保留; +- README 说明扩展行为、权限用途、外部依赖与可能发送的内容。 + +## 相关资料 + +- [扩展开发入门与 API 用法](./getting-started.md) +- [扩展 API 参考](./api-reference.md) +- [扩展中心架构](./architecture.md) +- [扩展安全模型](./security.md) +- [可安装示例](../../examples/extensions/README.md) diff --git a/docs/extensions/getting-started.md b/docs/extensions/getting-started.md new file mode 100644 index 0000000..986d51f --- /dev/null +++ b/docs/extensions/getting-started.md @@ -0,0 +1,141 @@ +# 扩展开发入门 + +从克隆源码到创建独立扩展的完整流程见[克隆 TraceMemo 后开发自己的扩展](./clone-and-customize.md)。本页保留 API 用法速查。 + +## 1. 安装示例 + +1. 打开 TraceMemo,左侧一级导航点「扩展」。 +2. 点「安装目录」,选择 `examples/extensions/keyword-bot`。 +3. 列表里出现 **关键词回复机器人**,状态为「已停用」。 +4. 点「启用」→「打开页面」;页面顶部的「启用机器人」默认关闭,打开后修改规则并保存。 +5. 完全退出并重启 TraceMemo,配置仍在。 + +`examples/extensions/douyin-sender` 用同样的方式安装;它依赖本机 `python3`、Chrome 和抖音解析脚本,先看它自己的 README。 + +## 2. 最小扩展 + +```text +my-extension/ + manifest.json + ui/index.html + background/index.js +``` + +`manifest.json`: + +```json +{ + "manifestVersion": 1, + "id": "com.example.my-extension", + "name": "我的扩展", + "version": "1.0.0", + "apiVersion": "1", + "minAppVersion": "2.6.0", + "permissions": ["storage"], + "entrypoints": { "page": "ui/index.html", "background": "background/index.js" }, + "contributions": { "pages": [{ "id": "settings", "title": "设置" }] } +} +``` + +`background/index.js`: + +```js +module.exports = function activate(tm) { + tm.log.info('我的扩展已启动') +} +``` + +`ui/index.html` 里不能直接用 `window.api`。页面通过 postMessage 与宿主通信: + +```js +const requestId = `req-${Date.now()}` +parent.postMessage( + { + source: 'tracememo-extension-page', + extensionId: 'com.example.my-extension', + requestId, + method: 'storage.get', + params: { key: 'greeting' } + }, + '*' +) +window.addEventListener('message', (event) => { + const data = event.data + if (!data || data.source !== 'tracememo-extension-host' || data.requestId !== requestId) return + console.log(data.ok ? data.result : data.error) +}) +``` + +页面可调用的方法只有:`storage.get` / `storage.set` / `storage.remove` / `storage.list` / +`capabilities.get` / `extension.info`。 + +## 3. 订阅消息 + +manifest 必须同时声明权限与订阅: + +```json +{ + "permissions": ["messages.subscribe"], + "subscriptions": { + "messageTypes": ["text"], + "conversationIds": [], + "requireMentionMe": false, + "includeSelf": false + } +} +``` + +```js +module.exports = function activate(tm) { + tm.events.on('message.received', async (event) => { + if (event.isSelf) return + if (!event.mentionsMe) return + await tm.wechat.send({ + to: event.conversationId, + text: '收到', + dedupeKey: event.eventId + }) + }) +} +``` + +`dedupeKey` 建议直接用 `event.eventId`:同一条消息重复投递时,Gateway 会按审计记录短路。 + +## 4. 注册自动化动作 + +```js +tm.automation.registerAction({ + id: 'douyin.process', + title: '抖音视频处理', + description: '处理指定视频链接', + inputSchema: { + type: 'object', + properties: { url: { type: 'string' } }, + required: ['url'] + }, + async handler(input) { + return { + success: true, + output: { url: input.url }, + reply: { type: 'text', text: '已收到链接' } + } + } +}) +``` + +扩展中心会展示动作声明与运行时注册状态。当前自动化规则编辑器尚未提供扩展动作选择入口,因此暂时不能从界面配置该动作。宿主侧执行契约与输入结构见[扩展 API 参考](./api-reference.md#自动化动作输入)。 + +扩展动作返回的 `reply` 由宿主经 Gateway 发送;扩展本身不调用发送接口也能完成回复。 + +## 5. 开发与调试 + +- TraceMemo 会把扩展复制到用户数据目录;改完源码后先在扩展中心重新安装同一目录,更新已安装的文件。需要时再「停用 → 启用」重启后台进程。 +- 页面资源更新后重新打开或刷新扩展页面。 +- 日志在扩展详情页底部,`宿主` 表示生命周期与错误,`扩展` 表示 `tm.log.*` 写入的内容。 +- 想看完整后台输出,可以在终端启动 `pnpm dev`,子进程 stderr 会进主进程日志。 + +## 6. 升级与保留 + +- 扩展升级只替换代码目录;`storage` 数据与启用状态保留。 +- 官方 TraceMemo 升级不触碰 `extensions/`、`extensions-data/`、`extensions-state/`。 +- 卸载默认保留数据(v1 界面只提供「保留数据」这一条路径;`keepData: false` 已在 IPC 中实现,界面暂未暴露)。 diff --git a/docs/extensions/security.md b/docs/extensions/security.md new file mode 100644 index 0000000..2b4677e --- /dev/null +++ b/docs/extensions/security.md @@ -0,0 +1,86 @@ +# 扩展安全模型(v1) + +## 信任分级 + +| 类型 | 说明 | 本版支持 | +| --- | --- | --- | +| 声明式 UI 扩展 | 只有页面,使用白名单存储 / 能力查询 | 是 | +| 受信任本地代码扩展 | 后台是任意 Node 代码,可读写本机文件 | 是(安装即视为信任) | + +**独立进程不等于强沙箱。** 后台子进程(`ELECTRON_RUN_AS_NODE`)拥有运行用户的全部 +Node 能力,因此扩展作者可以读写本机文件、发起网络请求。本版不声称限制了这些—— +它限制的是**TraceMemo 内部能力**: + +- 拿不到数据库句柄、数据库密钥、授权凭据、Native Runtime 句柄; +- 不能直接调用原生发送接口(dylib / 底层端口); +- 不能 `require` 官方主进程模块; +- 不能伪造宿主可信元数据(`origin` / `purpose` / `triggerType` / 幂等键)。 + +## 进程与权限 + +```text +主进程 ── fork ──▶ 扩展子进程(每扩展一个) + │ 只注入 tm + ▼ + 白名单 RPC(method + params) + │ + 宿主再次校验权限 +``` + +两侧都检查权限:子进程提前失败给出明确错误码,宿主侧才是权威判定。 +子进程崩溃 / 挂死不影响主进程:宿主有启动超时、调用超时、退避重启与熔断。 + +## 发送安全 + +```text +扩展声明「发什么」 + ↓ +宿主填 origin=extension / purpose=extension_send / recipient 类型 / 幂等键 + ↓ +ExtensionSendGateway:权限 → 会话范围 → 频率 → 本机能力 → 授权校验 + ↓ +WechatActionGateway:用途白名单 + `extension_*` 必须来自 origin=extension + ↓ +WechatSendGateway:真实发送 + Send Log +``` + +- 扩展不能在请求里指定 `purpose`,因此无法借用 `manual_*` / `api_*` 等用途绕过白名单。 +- 自动化草稿里的 `extensionAction` 只保存扩展 id、动作 id 与静态输入; + 发送内容由扩展返回,发送动作由 runner 发起,幂等键由 `executionId` 派生。 +- 授权只在主进程判定:macOS 读 Native license(要求 `authorized === true`), + Windows 探测 `/license/status` 只接受 `LICENSE_OK`。UI 上的 `ready` 不作为授权依据。 + +## 页面安全 + +- 自定义协议 `tm-extension:///`,每次请求 realpath 复核目录归属; +- iframe `sandbox="allow-scripts"`:无 same-origin、无 Node、无 preload、无 `window.api`; +- 响应头 CSP:`default-src 'self'`、`script-src 'self'`、`connect-src 'none'`、 + `object-src 'none'`、`base-uri 'none'`、`form-action 'none'`; +- 页面只能调用 `storage.*` / `capabilities.get` / `contacts.listGroups` / `extension.info`; + `contacts.listGroups` 只返回群名称与会话 id,且要求 manifest 声明 `contacts.list`。 + +## 安装安全 + +ZIP 安装校验: + +1. 包大小 ≤ 100MB、文件数 ≤ 2000、单文件 ≤ 20MB、解压总量 ≤ 50MB; +2. 条目路径规范化后判重(大小写不敏感),拒绝 `..`、绝对路径、盘符、保留名; +3. 拒绝 `SymbolicLink` 与非常规条目; +4. 先解压到 `extensions-staging`,校验 manifest 与入口存在后才原子改名; +5. 目标已存在时先改名备份,替换失败自动回滚。 + +目录安装同样拒绝符号链接与非普通文件,并遵守同样的体积 / 数量上限。 + +## 隐私 + +- 宿主日志只记录生命周期、错误摘要与数量,不写聊天正文、昵称、wxid、群名、路径; +- `message.received` 只在扩展声明 `messages.subscribe` 且用户启用后才投递; +- 扩展自己写 `tm.log.*` 的内容会落盘并展示,作者需自行遵守隐私约定; +- 扩展存储按 id 隔离,路径来自已校验的 id,不接受任意目录。 + +## 已知边界(v1 未解决) + +- 后台代码的文件 / 网络权限未做系统级限制(无 seatbelt / AppContainer); +- 页面与后台共享 `storage`,因此页面能读到后台写入的任何配置; +- 没有签名校验与来源可信度分级,安装来源完全依赖用户选择; +- 事件投递是「至多一次」:进程重启或过载时可能丢事件,扩展需要用 `eventId` 自行幂等。 diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 987c7db..9238775 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -11,6 +11,8 @@ export default defineConfig({ rollupOptions: { input: { index: resolve('src/main/index.ts'), + /* 扩展后台宿主:由 `ExtensionHost` 以子进程方式 fork,不在主进程加载。 */ + extensionHost: resolve('src/main/extensions/host-runtime.ts'), reportTemplateTest: resolve('src/main/report-template-test-entry.ts'), queryAgentPoc: resolve('src/main/query-agent-poc-entry.ts'), voiceRecognitionWorker: resolve('src/main/voice-pipeline/voice-recognition-worker.ts'), diff --git a/eslint.config.mjs b/eslint.config.mjs index 8de9b90..741f1bc 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -34,5 +34,14 @@ export default defineConfig( ...eslintPluginReactRefresh.configs.vite.rules } }, + { + // 扩展示例是给第三方作者抄的 CommonJS,不是 TS 源码: + // 返回类型/require 规则在这里没有意义,强制它们只会让示例变成反例。 + files: ['examples/**/*.{js,mjs}'], + rules: { + '@typescript-eslint/explicit-function-return-type': 'off', + '@typescript-eslint/no-require-imports': 'off' + } + }, eslintConfigPrettier ) diff --git a/examples/extensions/README.md b/examples/extensions/README.md new file mode 100644 index 0000000..a349787 --- /dev/null +++ b/examples/extensions/README.md @@ -0,0 +1,37 @@ +# 扩展示例 + +两个可直接安装的示例,用来验证扩展中心从安装到发送的完整链路。 + +| 目录 | 用途 | 申请权限 | +| --- | --- | --- | +| `keyword-bot/` | 消息事件、关键词匹配、Gateway 发送、自动化动作 | `messages.subscribe`、`contacts.list`、`wechat.send.text`、`storage`、`automation.action` | +| `douyin-sender/` | @我 发抖音链接 → 解析 → 下载 → 发回视频;配置页可测试发送 | `messages.subscribe`、`contacts.list`、`wechat.send.video`、`wechat.send.text`、`storage` | + +## 安装 + +TraceMemo → 左侧「扩展」→「安装目录」,选择对应目录即可。 + +安装后扩展默认**未启用**: + +- `keyword-bot` 的 `enabled` 为 `false`,需要在配置页手动打开才会回复; +- `douyin-sender` 依赖本机的 `python3`、Chrome 和抖音解析脚本,安装前先看它自己的 README。 + +## 测试建议 + +- 关键词机器人默认监听全部群聊 + 私聊;想只对某个群生效,在「监听范围」里搜索并多选群聊。 +- 冷却时间按「会话 + 规则」计算,避免同一句话连续刷屏。 +- 扩展的发送走 `tm.wechat.send`,最终仍由 TraceMemo Gateway 做权限、授权校验、限流与审计。 + +## 开发 + +扩展目录里只需要 `manifest.json` 与入口文件: + +```text +my-extension/ + manifest.json + ui/index.html + background/index.js +``` + +`background/index.js` 导出 `activate(tm)`(或 `module.exports = { activate }`)。页面通过 +`postMessage` 与宿主通信,协议见 `docs/extensions/api-reference.md`。 diff --git a/examples/extensions/douyin-sender/README.md b/examples/extensions/douyin-sender/README.md new file mode 100644 index 0000000..aa5e63e --- /dev/null +++ b/examples/extensions/douyin-sender/README.md @@ -0,0 +1,143 @@ +# 抖音视频搬运 + +被 @ 且消息里带抖音分享链接时,解析作品、下载视频,并发回原会话。 + +判定范围由扩展自己控制:只有**真正 @ 到当前登录账号**的文本消息才会进入流程 +(`subscriptions.requireMentionMe: true`),普通消息直接忽略。 + +## 前置条件 + +- 本机有 `python3`(3.10 及以上)。 +- 本机装了 Chrome:解析脚本用真实浏览器打开作品页、拦截页面自己发出的 `aweme/detail` 响应, + 不自造签名。 +- 解析脚本已存在于本机(默认 `scripts/douyin.py`,相对于扩展目录,也可在配置页指定自定义路径)。 +- 首次运行时脚本会在 `~/Library/Caches/douyin-video/venv`(Windows 落在 `%LOCALAPPDATA%`) + 自建 venv 并安装 `playwright` / `requests`,约 30 秒;之后复用,不再安装。 + +## 安装 + +TraceMemo → 左侧「扩展」→「安装目录」,选择本目录 `douyin-sender/`。 + +安装完成后: + +1. 打开「抖音解析设置」页面,确认 Python 路径与脚本路径; +2. 打开总开关,保存; +3. 在「测试发送」里选目标群、粘贴抖音分享文案,点「测试发送」验证; + 或在微信里 @ 自己发一条带抖音分享链接的文本消息。 + +扩展默认 `enabled: false`,安装后不会自动对外发送。 + +配置页的群列表来自本机通讯录,对应权限 `contacts.list`(只读群名与会话 id,不含聊天内容)。 + +升级同 id 的扩展会替换代码并保留配置;如果新版本**新增了权限**(例如从 image 换成 video), +升级后请「停用 → 启用」一次,让宿主按新 manifest 重新授权。 + +## 测试发送(配置页) + +配置页底部有独立的「测试发送」: + +1. 下拉选择目标群(列表来自 `contacts.listGroups`,需要 `contacts.list` 权限); +2. 粘贴抖音链接或整段分享文案(命令行脚本不需要手动截取 URL); +3. 点「测试发送」,页面会轮询进度,解析完成后把去水印视频发到该群; +4. 测试路径**不发回执**,避免测试时多一条消息; +5. 测试任务同样计入统计,进度显示在「当前任务」。 + +设置页可选使用「抖音 Cookie」面板粘贴并保存 Cookie header。宿主通过系统安全存储加密后保存在本机,页面只展示是否已配置,不会回显内容;测试发送与自动解析时在后台使用该 Cookie,未配置时也可回退读取本机 `douyin-cookie` 文件。 + +## 配置字段 + +| 字段 | 默认值 | 说明 | +| ----------------- | ------------------------ | ---------------------------------------------------------------------- | +| `enabled` | `false` | 总开关;关闭时任何消息都不处理 | +| `pythonPath` | `python3` | Python 可执行文件,支持 `~` | +| `scriptPath` | `scripts/douyin.py` | 解析脚本路径(默认相对于扩展目录,支持 `~` 与绝对路径) | +| `quality` | `720` | `''` 最高 / `1080` / `720` / `540`;其他值收敛到 `720` | +| `showUi` | `false` | 排障开关:显示浏览器窗口以观察最终页面;不保证改变平台响应 | +| 抖音 Cookie | 未配置 | 配置页输入后由 Electron `safeStorage` 加密保存 | +| `ackText` | `收到,正在解析,请稍候…`| 命中后先回复的文本;留空表示不回执 | +| `errorReply` | `true` | 失败时是否在原会话回一条简短说明 | +| `includeDirect` | `false` | 是否同时处理私聊 | +| `groups` | `[]` | 群白名单;空数组表示全部群 | +| `cooldownSeconds` | `60` | 按会话计的冷却,0–3600 | +| `maxFileMB` | `100` | 单文件上限,1–100,不能超过宿主 100 MB 硬限制 | + +保存时写入 `configVersion: 1`;后台最多 1 秒内读到新配置(配置缓存 TTL 1000 ms)。 + +## 处理流程 + +1. `message.received` → 判定顺序:总开关 → 自己发的 → 非 text → 未 @我 → 提取链接 → 会话范围 → 冷却。 +2. 命中后先回执(`ackText`,默认「收到,正在解析,请稍候…」;留空关闭),再进入解析。 +3. `python3 + + diff --git a/examples/extensions/douyin-sender/ui/style.css b/examples/extensions/douyin-sender/ui/style.css new file mode 100644 index 0000000..d93c88c --- /dev/null +++ b/examples/extensions/douyin-sender/ui/style.css @@ -0,0 +1,387 @@ +:root { + color-scheme: light dark; + --bg: #f6f8f7; + --card: #ffffff; + --text: #1c2622; + --muted: #6b7a73; + --border: #dfe6e2; + --brand: #247a63; + --danger: #b4472f; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #161c19; + --card: #1e2622; + --text: #eef4f1; + --muted: #9aaba3; + --border: #33403a; + --brand: #4bb894; + --danger: #e0735a; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', + sans-serif; +} + +.page { + max-width: 720px; + margin: 0 auto; + padding: 26px 22px 40px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.page-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; +} + +h1 { + margin: 0; + font-size: 19px; +} + +h2 { + margin: 0; + font-size: 13px; + font-weight: 700; +} + +header p { + margin: 8px 0 0; + max-width: 52ch; + color: var(--muted); + font-size: 12px; + line-height: 19px; +} + +.panel { + display: flex; + flex-direction: column; + gap: 12px; + padding: 16px 18px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--card); +} + +.panel-header { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; +} + +.field > span { + color: var(--muted); + font-size: 11px; +} + +input[type='text'], +input[type='number'], +select, +textarea { + width: 100%; + padding: 7px 9px; + border: 1px solid var(--border); + border-radius: 8px; + background: transparent; + color: var(--text); + font-family: inherit; + font-size: 12px; +} + +textarea { + resize: vertical; +} + +.grid-2 { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + gap: 12px; +} + +.row { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} + +.check, +.switch { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--muted); +} + +.switch { + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 999px; + color: var(--text); +} + +button { + padding: 6px 11px; + border: 1px solid var(--border); + border-radius: 8px; + background: transparent; + color: var(--text); + font-family: inherit; + font-size: 12px; + cursor: pointer; +} + +button.primary { + border-color: transparent; + background: var(--brand); + color: #fff; +} + +button.ghost:hover { + border-color: var(--brand); +} + +.page-footer { + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; +} + +.status { + min-height: 18px; + margin: 0; + color: var(--muted); + font-size: 12px; +} + +.status[data-kind='ok'] { + color: var(--brand); +} + +.status[data-kind='error'] { + color: var(--danger); +} + +.muted { + color: var(--muted); + font-size: 12px; +} + +.muted strong { + color: var(--text); + font-size: 13px; +} + +.stats { + width: 100%; + border-collapse: collapse; + font-size: 12px; +} + +.stats th { + padding: 6px 8px; + border-bottom: 1px solid var(--border); + color: var(--muted); + font-size: 11px; + font-weight: 600; + text-align: left; +} + +.stats td { + padding: 6px 8px; + border-bottom: 1px solid var(--border); +} + +.stats tr:last-child td { + border-bottom: 0; +} + +.stats td.empty { + color: var(--muted); + text-align: center; +} + +.stats .mono { + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; + font-size: 11px; +} + +.stats .ok { + color: var(--brand); +} + +.stats .fail { + color: var(--danger); +} + +code { + padding: 1px 4px; + border-radius: 4px; + background: var(--bg); + font-size: 11px; +} + +/* 当前任务:状态徽标 + 一行阶段 + 一行细节。 */ +.badge { + padding: 2px 8px; + border-radius: 999px; + background: var(--bg); + color: var(--muted); + font-size: 11px; + font-weight: 600; +} + +.badge[data-status='running'] { + background: color-mix(in srgb, var(--brand) 14%, transparent); + color: var(--brand); +} + +.badge[data-status='done'] { + background: color-mix(in srgb, var(--brand) 14%, transparent); + color: var(--brand); +} + +.badge[data-status='failed'] { + background: color-mix(in srgb, var(--danger) 14%, transparent); + color: var(--danger); +} + +.progress-line { + display: flex; + align-items: baseline; + gap: 8px; + margin: 0; + font-size: 13px; +} + +.progress-line .muted { + font-size: 11px; +} + +/* 群聊多选:chips + 搜索框 + 复选下拉。 */ +.group-picker { + position: relative; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--card); + padding: 6px; +} + +.group-picker:focus-within { + border-color: var(--brand); +} + +.group-chips { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 4px; +} + +.group-chip { + display: inline-flex; + align-items: center; + gap: 2px; + max-width: 100%; + padding: 2px 4px 2px 8px; + border-radius: 6px; + background: var(--bg); + font-size: 11px; +} + +.group-chip > span { + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.group-chip-remove { + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; + font-size: 14px; + line-height: 1; + padding: 0 4px; +} + +.group-chip-remove:hover { + color: var(--danger); +} + +.group-picker > input[type='text'] { + width: 100%; + border: 0; + outline: 0; + background: transparent; + color: var(--text); + padding: 4px 2px; + font: inherit; + font-size: 12px; +} + +.group-options { + position: absolute; + z-index: 30; + left: 0; + right: 0; + top: calc(100% + 4px); + max-height: 220px; + overflow: auto; + padding: 4px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--card); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12); +} + +.group-option { + display: flex; + align-items: center; + gap: 6px; + padding: 5px 6px; + border-radius: 6px; + cursor: pointer; + font-size: 12px; +} + +.group-option:hover { + background: var(--bg); +} + +.group-option input { + margin: 0; +} + +.group-option-empty { + padding: 8px 6px; + color: var(--muted); + font-size: 11px; +} diff --git a/examples/extensions/keyword-bot/README.md b/examples/extensions/keyword-bot/README.md new file mode 100644 index 0000000..f67fe5c --- /dev/null +++ b/examples/extensions/keyword-bot/README.md @@ -0,0 +1,116 @@ +# 关键词回复机器人 + +监听微信文本消息,按规则表匹配关键词,命中后经 TraceMemo Gateway 回复。 + +两条入口共用同一份配置与同一套判定(`lib/matcher.js`): + +- `message.received` 事件:扩展自己判断范围与冷却,再调用 `tm.wechat.send`; +- 自动化动作 `keyword.reply`:只返回回复文本,不发送,发送由宿主的自动化流程完成。 + +扩展本身不碰 socket、dylib 或 HTTP,所有发送都经过宿主 Gateway 的权限、授权校验、限流与审计。 + +## 目录 + +```text +keyword-bot/ + manifest.json 权限、订阅、页面与自动化动作声明 + background/index.js 事件编排、冷却表、命中统计 + lib/matcher.js 纯函数:规范化 / 匹配 / 范围 / 模板 / 决策 + ui/ 配置页(沙箱 iframe,只调用 storage.* / capabilities.get / extension.info) + tests/matcher.test.mjs +``` + +## 功能 + +- 规则支持三种匹配方式:`contains`(包含)、`exact`(完全匹配)、`prefix`(以…开头),均不区分大小写; +- 每条规则可单独启用/停用,并设置优先级与冷却; +- 监听范围可按群限定,可开关私聊,可要求真正 @ 我; +- 回复内容支持模板变量; +- 配置页展示今日命中数与最近 5 条命中结果。 + +## 配置字段 + +顶层: + +| 字段 | 类型 | 默认 | 说明 | +| ------------------------ | -------- | ------- | ----------------------------------------- | +| `configVersion` | number | `2` | 保存时写入;v1(无此字段)读取时自动迁移 | +| `enabled` | boolean | `false` | 总开关。缺省关闭,避免安装后立即对外发送 | +| `rules` | array | `[]` | 规则表,见下 | +| `scope.groups` | string[] | `[]` | 群 id(`xxx@chatroom`);空数组表示全部群 | +| `scope.includeDirect` | boolean | `true` | 是否处理私聊 | +| `scope.requireMentionMe` | boolean | `false` | 是否只处理真正 @ 登录账号的消息 | + +规则: + +| 字段 | 类型 | 默认 | 约束 | +| ----------------- | ------- | ------------- | ------------------------------------------- | +| `id` | string | `rule-<序号>` | ≤ 64 字符;冷却键的一部分,尽量稳定 | +| `keyword` | string | `''` | ≤ 120 字符;启用中为空的规则会被丢弃 | +| `mode` | string | `contains` | `contains` / `exact` / `prefix` | +| `reply` | string | `''` | ≤ 2000 字符;启用中为空的规则会被丢弃 | +| `cooldownSeconds` | number | `0` | 0–3600,取整到秒 | +| `enabled` | boolean | `true` | v1 规则迁移后为 `true`;显式 `false` 才停用 | +| `priority` | number | `0` | 0–100 整数,越大越先匹配 | + +配置页保存时只校验**启用中**的规则必须有 `keyword` 与 `reply`;停用的规则允许留空,方便先存草稿。 + +## 模板变量 + +| 变量 | 含义 | +| ----------- | -------------------------------------------------------------------------- | +| `{sender}` | 发送者昵称;为空时渲染为「你」。自动化动作路径没有发送者上下文,恒为「你」 | +| `{keyword}` | 命中的关键词(规则里的原文) | +| `{time}` | 当前本地时间 `HH:mm` | + +未知变量(例如 `{group}`)原样保留,不会被静默删除。渲染结果 trim 后截断到 2000 字符。 + +## 优先级与冷却语义 + +- 只考虑 `enabled !== false` 的规则;按 `priority` 降序排列,同优先级保持规则在数组中的顺序; +- 取**第一个**命中的规则,一条消息最多回复一次(stopOnMatch),不会叠加多条回复; +- 冷却键是 `conversationId:ruleId`,即「同一会话 + 同一条规则」各自独立计时; +- 冷却只在**发送成功后**写入:发送失败不占用冷却,下一条命中会立刻重试; +- 冷却表只存在内存里,扩展进程重启后清空——宁可多回一条,也不跨重启误拦。 + +## 统计口径与隐私边界 + +存储键 `stats`,结构: + +```json +{ + "dateKey": "2026-11-12", + "todayCount": 3, + "lastHits": [{ "at": 0, "ruleId": "rule-1", "ok": true }] +} +``` + +- 每条命中记一条,**成功和失败都记**;`todayCount` 统计的是命中的次数(含发送失败); +- `lastHits` 最多保留 20 条,配置页只展示最近 5 条;`at` 是 epoch 毫秒; +- 跨日后读取会把 `todayCount` 归零,`lastHits` 作为滚动历史保留; +- 只记录规则 id、时间与发送结果,**不记录会话 id、消息正文、发送者昵称或群名**; +- 统计写入失败只打 warn 日志,不影响回复; +- 统计只覆盖事件自动回复,不包含自动化动作 `keyword.reply` 的调用。 + +## 测试 + +零依赖,Node 内置测试运行器,不安装任何包: + +```bash +node --test examples/extensions/keyword-bot/tests/matcher.test.mjs +node --check examples/extensions/keyword-bot/lib/matcher.js +node --check examples/extensions/keyword-bot/background/index.js +node --check examples/extensions/keyword-bot/ui/app.js +``` + +用例覆盖:三种匹配方式、大小写、空关键词、禁用规则、优先级与稳定性、群范围与私聊开关、@ 要求、自己发的消息、冷却中/过期、模板替换与未知变量、超长截断、v1 迁移、非法规则丢弃、数值越界收敛、决策顺序。 + +`tests/matcher.test.mjs` 中的 fixture 全部为占位数据(`张三`、`李四`、`测试群`、`fixture-room@chatroom`、`wxid_fixture`)。 + +## 已知限制 + +- 不回复自己发送的消息(`isSelf` 直接跳过); +- 消息事件是「至多一次」投递:扩展进程重启的瞬间可能丢事件,没有补投队列; +- 不读取群名,因此没有 `{group}` 变量;需要按群定制时请拆成多条规则并配合「监听范围」; +- 配置缓存窗口为 1 秒,保存后最多 1 秒生效; +- 冷却表与配置缓存都在扩展后台进程内存中,进程重启即丢失。 diff --git a/examples/extensions/keyword-bot/background/index.js b/examples/extensions/keyword-bot/background/index.js new file mode 100644 index 0000000..5134d1d --- /dev/null +++ b/examples/extensions/keyword-bot/background/index.js @@ -0,0 +1,221 @@ +/** + * 关键词回复机器人。 + * + * 两条入口共用同一份配置与 `lib/matcher.js` 的同一套判定: + * 1. `message.received` 事件 → 自己判断范围 / 冷却 → `tm.wechat.send`; + * 2. 自动化动作 `keyword.reply` → 只返回回复内容,由宿主 Gateway 发送。 + * + * 发送**永远**经过宿主:本文件里没有任何 socket、dylib 或 HTTP 调用。 + * 匹配/规范化逻辑全部在 `lib/matcher.js`,本文件只负责编排与统计。 + */ + +const { normalizeConfig, pickRule, renderReply, shouldReply } = require('../lib/matcher.js') + +const CONFIG_KEY = 'config' +const STATS_KEY = 'stats' +/** 配置缓存窗口:配置页保存后最多 1 秒生效,避免每条消息都读一次 storage。 */ +const CONFIG_TTL_MS = 1000 +/** 最近命中记录上限;只保留规则 id、时间与结果,不保留任何会话内容。 */ +const STATS_HISTORY_LIMIT = 20 +/** 冷却表清理阈值:超过后剔除已过期项,避免长期运行无限增长。 */ +const COOLDOWN_PRUNE_SIZE = 500 + +let tm = null +let cachedConfig = null +let cachedAt = 0 +let cachedStats = null +const cooldownUntil = new Map() +/** 统计写入串行化:并发消息不互相覆盖 `stats` 快照。 */ +let statsChain = Promise.resolve() + +function loadConfig() { + if (cachedConfig && Date.now() - cachedAt < CONFIG_TTL_MS) return Promise.resolve(cachedConfig) + return Promise.resolve(tm.storage.get(CONFIG_KEY)) + .then((stored) => { + cachedConfig = normalizeConfig(stored) + cachedAt = Date.now() + return cachedConfig + }) + .catch((error) => { + tm.log.warn(`读取配置失败,本次按未启用处理:${describeError(error)}`) + // 读失败也要缓存一小段时间,避免每条消息都打一次失败日志。 + cachedConfig = normalizeConfig(null) + cachedAt = Date.now() + return cachedConfig + }) +} + +/** 本地时区的 `YYYY-MM-DD`,用于判定「今日」。 */ +function statsDateKey(timestamp) { + const date = new Date(timestamp) + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + return `${date.getFullYear()}-${month}-${day}` +} + +/** 本地时区的 `HH:mm`,模板变量 `{time}` 与统计展示共用。 */ +function formatClock(timestamp) { + const date = new Date(timestamp) + const hour = String(date.getHours()).padStart(2, '0') + const minute = String(date.getMinutes()).padStart(2, '0') + return `${hour}:${minute}` +} + +function emptyStats(timestamp) { + return { dateKey: statsDateKey(timestamp), todayCount: 0, lastHits: [] } +} + +/** + * 规范化统计快照。 + * + * 跨日后 `todayCount` 归零;`lastHits` 作为滚动历史保留(它记的是「最近命中」, + * 不是「今日命中」)。任何字段缺失或类型不对都退化为空值,统计损坏不能影响回复。 + */ +function normalizeStats(raw, timestamp) { + const base = emptyStats(timestamp) + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return base + const lastHits = Array.isArray(raw.lastHits) + ? raw.lastHits + .filter((hit) => hit && typeof hit === 'object') + .map((hit) => ({ + at: Number(hit.at), + ruleId: String(hit.ruleId == null ? '' : hit.ruleId).slice(0, 64), + ok: hit.ok === true + })) + .filter((hit) => Number.isFinite(hit.at) && hit.at > 0 && hit.ruleId) + .slice(-STATS_HISTORY_LIMIT) + : [] + const sameDay = raw.dateKey === base.dateKey + const count = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0 + return { dateKey: base.dateKey, todayCount: count, lastHits } +} + +function loadStats() { + if (cachedStats) return Promise.resolve(cachedStats) + return Promise.resolve(tm.storage.get(STATS_KEY)) + .then((stored) => { + cachedStats = normalizeStats(stored, Date.now()) + return cachedStats + }) + .catch(() => { + cachedStats = emptyStats(Date.now()) + return cachedStats + }) +} + +/** + * 追加一条命中记录并落库。 + * + * 成功与失败都记;只写 `ruleId` / `at` / `ok`,绝不写会话 id、正文或昵称。 + * 写失败只 warn:统计是旁路,不能因为 storage 异常把回复一起吞掉。 + */ +function recordHit(ruleId, ok) { + statsChain = statsChain + .then(async () => { + const stats = await loadStats() + const now = Date.now() + const dateKey = statsDateKey(now) + if (stats.dateKey !== dateKey) { + stats.dateKey = dateKey + stats.todayCount = 0 + } + stats.todayCount += 1 + stats.lastHits = stats.lastHits + .concat({ at: now, ruleId: String(ruleId || '').slice(0, 64), ok: ok === true }) + .slice(-STATS_HISTORY_LIMIT) + await tm.storage.set(STATS_KEY, stats) + }) + .catch((error) => { + tm.log.warn(`命中统计写入失败:${describeError(error)}`) + }) + return statsChain +} + +/** 冷却只在真正发送成功后写入;发送失败不占冷却,下一条可以立刻重试。 */ +function markCooldown(conversationId, rule, timestamp) { + const seconds = Number(rule.cooldownSeconds) || 0 + cooldownUntil.set(`${conversationId}:${rule.id}`, timestamp + seconds * 1000) + if (cooldownUntil.size > COOLDOWN_PRUNE_SIZE) { + for (const [key, until] of cooldownUntil) { + if (until <= timestamp) cooldownUntil.delete(key) + } + } +} + +function describeError(error) { + return error && error.message ? error.message : String(error) +} + +async function onMessage(event) { + try { + const config = await loadConfig() + const now = Date.now() + const verdict = shouldReply(event, config, cooldownUntil, now) + if (!verdict.reply || !verdict.rule) return + + const rule = verdict.rule + const text = renderReply(rule.reply, { + senderName: event.senderName, + keyword: rule.keyword, + time: formatClock(now) + }) + + try { + await tm.wechat.send({ + to: event.conversationId, + text, + // 同一条微信消息在补投/重启后 eventId 不变,交给 Gateway 幂等短路。 + dedupeKey: event.eventId + }) + } catch (error) { + await recordHit(rule.id, false) + throw error + } + + markCooldown(event.conversationId, rule, Date.now()) + await recordHit(rule.id, true) + tm.log.info(`关键词命中,已发送回复(规则 ${rule.id})`) + } catch (error) { + tm.log.error(`自动回复失败:${describeError(error)}`) + } +} + +module.exports = function activate(api) { + tm = api + tm.events.on('message.received', onMessage) + + tm.automation.registerAction({ + id: 'keyword.reply', + title: '关键词回复', + description: '按机器人配置匹配关键词并返回回复内容', + inputSchema: { + type: 'object', + properties: { text: { type: 'string' } }, + required: ['text'] + }, + async handler(input) { + const config = await loadConfig() + if (!config.enabled) { + return { success: false, error: '机器人未启用' } + } + const rule = pickRule(input.text, config) + if (!rule) { + return { success: true, output: { matched: false } } + } + return { + success: true, + output: { matched: true, ruleId: rule.id }, + // 动作路径没有发送者上下文,`{sender}` 会渲染成「你」。 + reply: { + type: 'text', + text: renderReply(rule.reply, { + keyword: rule.keyword, + time: formatClock(Date.now()) + }) + } + } + } + }) + + tm.log.info('关键词回复机器人已加载') +} diff --git a/examples/extensions/keyword-bot/lib/matcher.js b/examples/extensions/keyword-bot/lib/matcher.js new file mode 100644 index 0000000..dd3f4e2 --- /dev/null +++ b/examples/extensions/keyword-bot/lib/matcher.js @@ -0,0 +1,213 @@ +'use strict' + +/** + * 关键词回复的纯函数层:配置规范化、匹配、范围判定、模板渲染、决策。 + * + * 契约: + * - 全部函数无副作用、不读写 storage、不打印日志,便于单测与后台进程复用; + * - 输入一律容忍 `undefined` / 错误类型,坏配置退化为「不回复」而不是抛错; + * - `enabled` 在任何一层都是硬开关:配置损坏时不能自动对外发送。 + */ + +/** 当前配置结构版本。v1 没有该字段,读取时按 v1 迁移。 */ +const CONFIG_VERSION = 2 + +/** 与 UI、宿主动作输出保持一致的长度上限(字符)。 */ +const MAX_RULE_ID_LENGTH = 64 +const MAX_KEYWORD_LENGTH = 120 +const MAX_REPLY_LENGTH = 2000 +const MAX_GROUPS = 200 + +const MODES = new Set(['contains', 'exact', 'prefix']) + +/** + * 把任意来源的配置规范化为 `configVersion: 2`。 + * + * 启用中的空规则丢弃,停用的空规则保留为草稿;顶层 `enabled` 缺省 `false`, + * 配置缺失或损坏时宁可静默,也不能自动群发。 + * + * @param {unknown} raw storage 里读出的原始值 + */ +function normalizeConfig(raw) { + const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {} + const sourceRules = Array.isArray(input.rules) ? input.rules : [] + const rules = sourceRules + .filter((rule) => rule && typeof rule === 'object' && !Array.isArray(rule)) + .map((rule, index) => ({ + id: String(rule.id || `rule-${index + 1}`).slice(0, MAX_RULE_ID_LENGTH), + keyword: String(rule.keyword == null ? '' : rule.keyword).slice(0, MAX_KEYWORD_LENGTH), + mode: MODES.has(rule.mode) ? rule.mode : 'contains', + reply: String(rule.reply == null ? '' : rule.reply).slice(0, MAX_REPLY_LENGTH), + cooldownSeconds: clampNumber(rule.cooldownSeconds, 0, 3600), + // v1 规则没有该字段;只有显式 false 才算禁用。 + enabled: rule.enabled !== false, + priority: clampNumber(rule.priority, 0, 100) + })) + .filter((rule) => rule.enabled === false || (rule.keyword.trim() && rule.reply.trim())) + + const scope = input.scope && typeof input.scope === 'object' ? input.scope : {} + return { + configVersion: CONFIG_VERSION, + enabled: input.enabled === true, + rules, + scope: { + groups: Array.isArray(scope.groups) + ? scope.groups + .map((id) => String(id == null ? '' : id).trim()) + .filter(Boolean) + .slice(0, MAX_GROUPS) + : [], + includeDirect: scope.includeDirect !== false, + requireMentionMe: scope.requireMentionMe === true + } + } +} + +/** + * 单条规则是否命中文本:大小写不敏感;`exact` / `prefix` 先 trim, + * `contains` 只 trim 关键词;空关键词恒为 false。 + * + * @param {unknown} text 消息正文 + * @param {{ keyword?: unknown, mode?: unknown }} rule + * @returns {boolean} + */ +function matchRule(text, rule) { + const keyword = String((rule && rule.keyword) == null ? '' : rule.keyword) + .trim() + .toLowerCase() + if (!keyword) return false + const haystack = String(text == null ? '' : text).toLowerCase() + const mode = rule && MODES.has(rule.mode) ? rule.mode : 'contains' + if (mode === 'exact') return haystack.trim() === keyword + if (mode === 'prefix') return haystack.trim().startsWith(keyword) + return haystack.includes(keyword) +} + +/** + * 选出唯一命中的规则:`priority` 降序、同优先级保持数组顺序,取第一个命中。 + * + * 这就是 stopOnMatch 语义:一条消息最多回复一次,命中即停。 + * 禁用规则(`enabled === false`)不参与匹配。 + * + * @param {unknown} text + * @param {object} config normalizeConfig 的产物 + */ +function pickRule(text, config) { + const rules = config && Array.isArray(config.rules) ? config.rules : [] + const candidates = rules + .map((rule, index) => ({ rule, index })) + .filter((item) => item.rule && item.rule.enabled !== false) + // 显式带下标排序,避免依赖引擎排序稳定性。 + .sort((a, b) => (b.rule.priority || 0) - (a.rule.priority || 0) || a.index - b.index) + for (const item of candidates) { + if (matchRule(text, item.rule)) return item.rule + } + return null +} + +/** + * 会话是否在生效范围内。 + * + * - 群聊:`groups` 为空表示全部群;非空时必须包含 `event.conversationId`; + * - 私聊:只看 `includeDirect`。 + * + * 范围在规则匹配之前判定:范围外的会话连匹配都不做,避免误触统计。 + */ +function inScope(event, config) { + const scope = (config && config.scope) || {} + if (event && event.isGroup) { + const groups = Array.isArray(scope.groups) ? scope.groups : [] + return groups.length === 0 || groups.includes(event.conversationId) + } + return scope.includeDirect !== false +} + +/** + * 渲染回复模板。 + * + * 支持 `{sender}`(发送者昵称,空则「你」)、`{keyword}`(命中关键词)、 + * `{time}`(调用方给的本地时间字符串,缺省空串)。未知 `{xxx}` 原样保留, + * 方便用户在模板里写其它占位而不是被静默吃掉。结果 trim 后截断到 2000 字符。 + */ +function renderReply(template, ctx) { + const source = String(template == null ? '' : template) + const context = ctx && typeof ctx === 'object' ? ctx : {} + const sender = String(context.senderName == null ? '' : context.senderName).trim() || '你' + const keyword = String(context.keyword == null ? '' : context.keyword) + const time = String(context.time == null ? '' : context.time) + const rendered = source.replace(/\{(sender|keyword|time)\}/g, (match, token) => { + if (token === 'sender') return sender + if (token === 'keyword') return keyword + if (token === 'time') return time + return match + }) + return rendered.trim().slice(0, MAX_REPLY_LENGTH) +} + +/** + * 综合决策:是否回复、用哪条规则、为什么。 + * + * `reason` 取值固定,可直接用于日志/统计口径: + * `disabled` | `self` | `type` | `scope` | `mention` | `no_match` | `cooldown` | `ok`。 + * + * 判断顺序固定为:总开关 → 自己发的 → 消息类型 → 会话范围 → @ 要求 → 规则匹配 → 冷却。 + * 冷却键为 `conversationId:ruleId`,值为到期时间戳(epoch 毫秒),`now < until` 即冷却中。 + * 冷却表允许是 `Map` 或普通对象,后台进程重启后自然清空(宁可多回一条,也不跨重启误拦)。 + * + * @param {object} event 宿主的 message.received 事件 + * @param {object} config normalizeConfig 的产物 + * @param {Map|Record} [cooldownUntil] + * @param {number} [now] epoch 毫秒,缺省取当前时间 + */ +function shouldReply(event, config, cooldownUntil, now) { + if (!config || config.enabled !== true) { + return { reply: false, rule: null, reason: 'disabled' } + } + if (!event || event.isSelf === true) { + return { reply: false, rule: null, reason: 'self' } + } + if (event.type !== 'text') { + return { reply: false, rule: null, reason: 'type' } + } + if (!inScope(event, config)) { + return { reply: false, rule: null, reason: 'scope' } + } + if (config.scope && config.scope.requireMentionMe === true && event.mentionsMe !== true) { + return { reply: false, rule: null, reason: 'mention' } + } + const rule = pickRule(event.text, config) + if (!rule) { + return { reply: false, rule: null, reason: 'no_match' } + } + const currentTime = Number.isFinite(now) ? now : Date.now() + const key = `${event.conversationId}:${rule.id}` + if (currentTime < readCooldown(cooldownUntil, key)) { + return { reply: false, rule: null, reason: 'cooldown' } + } + return { reply: true, rule, reason: 'ok' } +} + +/** 冷却表读取:兼容 Map 与普通对象,缺失值按 0(永不冷却)。 */ +function readCooldown(table, key) { + if (!table) return 0 + const value = table instanceof Map ? table.get(key) : table[key] + const until = Number(value) + return Number.isFinite(until) ? until : 0 +} + +/** 收敛到 [min, max] 的整数;非数字 / NaN 一律当 0。 */ +function clampNumber(value, min, max) { + const numeric = Number(value) + if (!Number.isFinite(numeric)) return 0 + return Math.min(Math.max(Math.round(numeric), min), max) +} + +module.exports = { + CONFIG_VERSION, + normalizeConfig, + matchRule, + pickRule, + inScope, + renderReply, + shouldReply +} diff --git a/examples/extensions/keyword-bot/manifest.json b/examples/extensions/keyword-bot/manifest.json new file mode 100644 index 0000000..af423ce --- /dev/null +++ b/examples/extensions/keyword-bot/manifest.json @@ -0,0 +1,42 @@ +{ + "manifestVersion": 1, + "id": "com.example.keyword-bot", + "name": "关键词回复机器人", + "version": "1.0.0", + "apiVersion": "1", + "minAppVersion": "2.6.0", + "description": "监听微信文本消息,命中关键词后经 TraceMemo Gateway 回复。", + "author": "TraceMemo Examples", + "permissions": [ + "messages.subscribe", + "contacts.list", + "wechat.send.text", + "storage", + "automation.action" + ], + "entrypoints": { + "page": "ui/index.html", + "background": "background/index.js" + }, + "subscriptions": { + "messageTypes": ["text"], + "conversationIds": [], + "requireMentionMe": false, + "includeSelf": false + }, + "contributions": { + "pages": [ + { + "id": "settings", + "title": "机器人配置" + } + ], + "automationActions": [ + { + "id": "keyword.reply", + "title": "关键词回复", + "description": "按机器人配置匹配关键词并返回回复内容" + } + ] + } +} diff --git a/examples/extensions/keyword-bot/tests/matcher.test.mjs b/examples/extensions/keyword-bot/tests/matcher.test.mjs new file mode 100644 index 0000000..5caa532 --- /dev/null +++ b/examples/extensions/keyword-bot/tests/matcher.test.mjs @@ -0,0 +1,279 @@ +import test from 'node:test' +import assert from 'node:assert/strict' + +import matcher from '../lib/matcher.js' + +const { normalizeConfig, matchRule, pickRule, inScope, renderReply, shouldReply } = matcher + +const GROUP_ID = 'fixture-room@chatroom' +const NOW = 1_700_000_000_000 + +/** 构造一份启用状态下的最小配置,参数按需覆盖。 */ +function buildConfig(overrides = {}) { + return normalizeConfig({ + enabled: true, + rules: [{ id: 'rule-1', keyword: '关键词', mode: 'contains', reply: '默认回复' }], + scope: { groups: [], includeDirect: true, requireMentionMe: false }, + ...overrides + }) +} + +/** 构造一条群聊文本消息事件。 */ +function buildEvent(overrides = {}) { + return { + eventId: 'event-fixture-1', + accountId: 'account-fixture', + conversationId: GROUP_ID, + messageId: 'message-fixture-1', + senderId: 'wxid_fixture', + senderName: '张三', + isGroup: true, + isSelf: false, + type: 'text', + text: '你好,关键词', + mentionsMe: false, + timestamp: NOW, + ...overrides + } +} + +test('exact 模式比较 trim 后的完整文本', () => { + const rule = { keyword: '关键词', mode: 'exact' } + assert.equal(matchRule(' 关键词 ', rule), true) + assert.equal(matchRule('你好,关键词', rule), false) +}) + +test('exact 模式不匹配大小写不同的关键词之外的差异', () => { + const rule = { keyword: 'Hello', mode: 'exact' } + assert.equal(matchRule('hello', rule), true) + assert.equal(matchRule('hello world', rule), false) +}) + +test('contains 模式匹配任意位置的子串', () => { + const rule = { keyword: '关键词', mode: 'contains' } + assert.equal(matchRule('前面的关键词后面', rule), true) + assert.equal(matchRule('完全无关', rule), false) +}) + +test('prefix 模式只匹配开头', () => { + const rule = { keyword: '你好', mode: 'prefix' } + assert.equal(matchRule(' 你好世界', rule), true) + assert.equal(matchRule('世界你好', rule), false) +}) + +test('匹配对大小写不敏感', () => { + assert.equal(matchRule('Say HELLO now', { keyword: 'hello', mode: 'contains' }), true) + assert.equal(matchRule('HELLO WORLD', { keyword: 'hello', mode: 'prefix' }), true) +}) + +test('空关键词在任何模式下都不命中', () => { + for (const mode of ['contains', 'exact', 'prefix']) { + assert.equal(matchRule('任意文本', { keyword: ' ', mode }), false) + assert.equal(matchRule('', { keyword: '', mode }), false) + } +}) + +test('pickRule 跳过禁用规则', () => { + const config = buildConfig({ + rules: [ + { id: 'disabled', keyword: '关键词', reply: '不会发送', enabled: false }, + { id: 'active', keyword: '关键词', reply: '会发送' } + ] + }) + const rule = pickRule('关键词', config) + assert.equal(rule.id, 'active') +}) + +test('pickRule 按 priority 降序选择', () => { + const config = buildConfig({ + rules: [ + { id: 'low', keyword: '关键词', reply: '低', priority: 10 }, + { id: 'high', keyword: '关键词', reply: '高', priority: 90 } + ] + }) + assert.equal(pickRule('关键词', config).id, 'high') +}) + +test('同优先级保持数组顺序(先定义先命中)', () => { + const config = buildConfig({ + rules: [ + { id: 'first', keyword: '关键词', reply: '一', priority: 50 }, + { id: 'second', keyword: '关键词', reply: '二', priority: 50 } + ] + }) + assert.equal(pickRule('关键词', config).id, 'first') +}) + +test('同一条消息只返回一个规则(stopOnMatch)', () => { + const config = buildConfig({ + rules: [ + { id: 'a', keyword: '关键词', reply: '一', priority: 1 }, + { id: 'b', keyword: '关键词', reply: '二', priority: 2 } + ] + }) + const rule = pickRule('关键词 关键词', config) + assert.equal(rule.id, 'b') +}) + +test('群范围命中指定群', () => { + const config = buildConfig({ scope: { groups: [GROUP_ID] } }) + assert.equal(inScope(buildEvent(), config), true) +}) + +test('群范围排除未列出的群', () => { + const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } }) + assert.equal(inScope(buildEvent(), config), false) +}) + +test('groups 为空表示全部群聊', () => { + const config = buildConfig({ scope: { groups: [] } }) + assert.equal(inScope(buildEvent(), config), true) +}) + +test('includeDirect 为 false 时不处理私聊', () => { + const closed = buildConfig({ scope: { groups: [], includeDirect: false } }) + const open = buildConfig({ scope: { groups: [], includeDirect: true } }) + const direct = buildEvent({ isGroup: false, conversationId: 'wxid_fixture' }) + assert.equal(inScope(direct, closed), false) + assert.equal(inScope(direct, open), true) +}) + +test('requireMentionMe 只放行真正 @ 我的消息', () => { + const config = buildConfig({ scope: { groups: [], requireMentionMe: true } }) + assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'mention') + assert.equal(shouldReply(buildEvent({ mentionsMe: true }), config, new Map(), NOW).reason, 'ok') +}) + +test('自己发的消息不回复', () => { + const verdict = shouldReply(buildEvent({ isSelf: true }), buildConfig(), new Map(), NOW) + assert.deepEqual(verdict, { reply: false, rule: null, reason: 'self' }) +}) + +test('非文本消息不回复', () => { + const verdict = shouldReply(buildEvent({ type: 'image' }), buildConfig(), new Map(), NOW) + assert.equal(verdict.reason, 'type') +}) + +test('总开关关闭时不回复', () => { + const config = buildConfig({ enabled: false }) + assert.equal(shouldReply(buildEvent(), config, new Map(), NOW).reason, 'disabled') + assert.equal(shouldReply(buildEvent(), null, new Map(), NOW).reason, 'disabled') +}) + +test('没有命中规则时 reason 为 no_match', () => { + const verdict = shouldReply(buildEvent({ text: '无关内容' }), buildConfig(), new Map(), NOW) + assert.deepEqual(verdict, { reply: false, rule: null, reason: 'no_match' }) +}) + +test('冷却中不回复', () => { + const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW + 30_000]]) + const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW) + assert.deepEqual(verdict, { reply: false, rule: null, reason: 'cooldown' }) +}) + +test('冷却过期后恢复回复', () => { + const cooldown = new Map([[`${GROUP_ID}:rule-1`, NOW]]) + const verdict = shouldReply(buildEvent(), buildConfig(), cooldown, NOW) + assert.equal(verdict.reply, true) + assert.equal(verdict.reason, 'ok') + assert.equal(verdict.rule.id, 'rule-1') +}) + +test('冷却表也支持普通对象', () => { + const cooldown = { [`${GROUP_ID}:rule-1`]: NOW + 1 } + assert.equal(shouldReply(buildEvent(), buildConfig(), cooldown, NOW).reason, 'cooldown') + assert.equal(shouldReply(buildEvent(), buildConfig(), {}, NOW).reason, 'ok') +}) + +test('模板变量按上下文替换', () => { + const text = renderReply('{sender} 说了 {keyword},现在是 {time}', { + senderName: '张三', + keyword: '关键词', + time: '09:05' + }) + assert.equal(text, '张三 说了 关键词,现在是 09:05') +}) + +test('发送者昵称为空时渲染为「你」', () => { + assert.equal(renderReply('{sender}', { senderName: ' ' }), '你') + assert.equal(renderReply('{sender}', {}), '你') +}) + +test('未知变量原样保留', () => { + const text = renderReply('{sender} 和 {group}', { senderName: '李四' }) + assert.equal(text, '李四 和 {group}') +}) + +test('模板缺失的时间变量渲染为空串', () => { + assert.equal(renderReply('[{time}]', {}), '[]') +}) + +test('渲染结果 trim 后截断到 2000 字符', () => { + const input = ` ${'长'.repeat(2100)} ` + const text = renderReply(input, {}) + assert.equal(text.length, 2000) + assert.equal(text, '长'.repeat(2000)) +}) + +test('v1 配置迁移补齐 enabled / priority 与 configVersion', () => { + const config = normalizeConfig({ + enabled: true, + rules: [{ id: 'old', keyword: '关键词', mode: 'contains', reply: '旧规则' }], + scope: { groups: ['fixture-room@chatroom'] } + }) + assert.equal(config.configVersion, 2) + assert.equal(config.rules.length, 1) + assert.equal(config.rules[0].enabled, true) + assert.equal(config.rules[0].priority, 0) + assert.equal(config.scope.includeDirect, true) + assert.equal(config.scope.requireMentionMe, false) +}) + +test('keyword 或 reply 为空的启用规则被丢弃,停用草稿保留', () => { + const config = normalizeConfig({ + enabled: true, + rules: [ + { id: 'no-keyword', keyword: ' ', reply: '有回复' }, + { id: 'no-reply', keyword: '有词', reply: ' ' }, + { id: 'draft', keyword: '', reply: '', enabled: false }, + { id: 'ok', keyword: '有词', reply: '有回复' } + ] + }) + assert.deepEqual( + config.rules.map((rule) => rule.id), + ['draft', 'ok'] + ) +}) + +test('非对象与缺失字段的配置退化为未启用空配置', () => { + for (const raw of [null, undefined, 'broken', 42, []]) { + const config = normalizeConfig(raw) + assert.equal(config.configVersion, 2) + assert.equal(config.enabled, false) + assert.deepEqual(config.rules, []) + assert.deepEqual(config.scope, { groups: [], includeDirect: true, requireMentionMe: false }) + } +}) + +test('越界数值收敛到边界,非法值按 0', () => { + const config = normalizeConfig({ + rules: [ + { id: 'clamp-high', keyword: '一', reply: '一', cooldownSeconds: 99_999, priority: 999 }, + { id: 'clamp-low', keyword: '二', reply: '二', cooldownSeconds: -5, priority: -5 }, + { id: 'nan', keyword: '三', reply: '三', cooldownSeconds: 'oops', priority: 'oops' } + ] + }) + assert.equal(config.rules[0].cooldownSeconds, 3600) + assert.equal(config.rules[0].priority, 100) + assert.equal(config.rules[1].cooldownSeconds, 0) + assert.equal(config.rules[1].priority, 0) + assert.equal(config.rules[2].cooldownSeconds, 0) + assert.equal(config.rules[2].priority, 0) +}) + +test('群范围过滤先于规则匹配,范围外不产生命中', () => { + const config = buildConfig({ scope: { groups: ['other-room@chatroom'] } }) + const verdict = shouldReply(buildEvent(), config, new Map(), NOW) + assert.equal(verdict.reason, 'scope') + assert.equal(verdict.rule, null) +}) diff --git a/examples/extensions/keyword-bot/ui/app.js b/examples/extensions/keyword-bot/ui/app.js new file mode 100644 index 0000000..679fcad --- /dev/null +++ b/examples/extensions/keyword-bot/ui/app.js @@ -0,0 +1,495 @@ +const EXTENSION_ID = 'com.example.keyword-bot' +const PAGE_SOURCE = 'tracememo-extension-page' +const HOST_SOURCE = 'tracememo-extension-host' +const CONFIG_KEY = 'config' +const STATS_KEY = 'stats' +const CONFIG_VERSION = 2 +const MAX_KEYWORD_LENGTH = 120 +const MAX_REPLY_LENGTH = 2000 +const STATS_PREVIEW = 5 + +const DEFAULT_CONFIG = { + configVersion: CONFIG_VERSION, + enabled: false, + rules: [ + { + id: 'rule-1', + keyword: '你好', + mode: 'contains', + reply: '你好呀,{sender}!', + cooldownSeconds: 30, + enabled: true, + priority: 0 + } + ], + scope: { groups: [], includeDirect: true, requireMentionMe: false } +} + +const pending = new Map() +let sequence = 0 +let config = clone(DEFAULT_CONFIG) + +function clone(value) { + return JSON.parse(JSON.stringify(value)) +} + +function callHost(method, params) { + return new Promise((resolve, reject) => { + const requestId = `req-${++sequence}` + pending.set(requestId, { resolve, reject }) + window.parent.postMessage( + { source: PAGE_SOURCE, extensionId: EXTENSION_ID, requestId, method, params }, + '*' + ) + }) +} + +window.addEventListener('message', (event) => { + const data = event.data + if (!data || data.source !== HOST_SOURCE) return + const entry = pending.get(data.requestId) + if (!entry) return + pending.delete(data.requestId) + if (data.ok) entry.resolve(data.result) + else entry.reject(new Error((data.error && data.error.message) || '调用失败')) +}) + +const rulesContainer = document.getElementById('rules') +const status = document.getElementById('status') +const statsSummary = document.getElementById('stats-summary') +const statsList = document.getElementById('stats-list') +const groupPicker = document.getElementById('group-picker') +const groupChips = document.getElementById('group-chips') +const groupSearch = document.getElementById('group-search') +const groupOptions = document.getElementById('group-options') + +let allGroups = [] +let selectedGroupIds = new Set() +let groupLoadError = '' + +function groupDisplayName(group) { + if (!group) return '' + return group.name && group.name !== group.id ? `${group.name}(${group.id})` : group.id +} + +function renderGroupChips() { + groupChips.textContent = '' + groupChips.hidden = selectedGroupIds.size === 0 + for (const id of selectedGroupIds) { + const group = allGroups.find((item) => item.id === id) + const chip = document.createElement('span') + chip.className = 'group-chip' + const name = document.createElement('span') + name.textContent = group ? group.name || id : id + name.title = id + const remove = document.createElement('button') + remove.type = 'button' + remove.className = 'group-chip-remove' + remove.textContent = '×' + remove.setAttribute('aria-label', `移除 ${group ? group.name || id : id}`) + remove.addEventListener('click', (event) => { + event.stopPropagation() + selectedGroupIds.delete(id) + renderGroupChips() + renderGroupOptions() + }) + chip.append(name, remove) + groupChips.append(chip) + } +} + +function renderGroupOptions() { + if (groupOptions.hidden) return + const query = groupSearch.value.trim().toLowerCase() + groupOptions.textContent = '' + if (groupLoadError) { + groupOptions.append(emptyGroupOption(groupLoadError)) + return + } + if (!allGroups.length) { + groupOptions.append(emptyGroupOption('未读取到群列表(请先连接微信数据库)')) + return + } + const matches = allGroups.filter((group) => { + if (!query) return true + return group.id.toLowerCase().includes(query) || group.name.toLowerCase().includes(query) + }) + if (!matches.length) { + groupOptions.append(emptyGroupOption('没有匹配的群聊')) + return + } + for (const group of matches.slice(0, 200)) { + const option = document.createElement('label') + option.className = 'group-option' + const checkbox = document.createElement('input') + checkbox.type = 'checkbox' + checkbox.checked = selectedGroupIds.has(group.id) + checkbox.addEventListener('change', () => { + if (checkbox.checked) selectedGroupIds.add(group.id) + else selectedGroupIds.delete(group.id) + renderGroupChips() + }) + const text = document.createElement('span') + text.textContent = groupDisplayName(group) + option.append(checkbox, text) + groupOptions.append(option) + } +} + +function emptyGroupOption(text) { + const empty = document.createElement('div') + empty.className = 'group-option-empty' + empty.textContent = text + return empty +} + +function openGroupOptions() { + groupOptions.hidden = false + renderGroupOptions() +} + +function closeGroupOptions() { + groupOptions.hidden = true + groupSearch.value = '' +} + +groupSearch.addEventListener('focus', openGroupOptions) +groupSearch.addEventListener('input', openGroupOptions) +groupSearch.addEventListener('keydown', (event) => { + if (event.key === 'Escape') { + closeGroupOptions() + groupSearch.blur() + } +}) +document.addEventListener('click', (event) => { + if (!groupPicker.contains(event.target)) closeGroupOptions() +}) + +async function loadGroups() { + try { + const result = await callHost('contacts.listGroups', {}) + allGroups = result && Array.isArray(result.groups) ? result.groups : [] + groupLoadError = '' + } catch (error) { + allGroups = [] + groupLoadError = `群列表读取失败:${error.message}` + } + renderGroupChips() + renderGroupOptions() +} + +function setStatus(text, kind) { + status.textContent = text + status.dataset.kind = kind || '' +} + +function clampInteger(value, min, max, fallback) { + const numeric = Number(value) + if (!Number.isFinite(numeric)) return fallback + return Math.min(Math.max(Math.round(numeric), min), max) +} + +function newRuleId() { + return `rule-${Date.now().toString(36)}` +} + +/** + * 页面侧的轻量规范化:只用于展示与回写,真正的判定在后台 lib/matcher.js。 + * 缺字段一律补默认值,保证 v1 配置打开后能直接编辑。 + */ +function normalizeRule(rule, index) { + const source = rule && typeof rule === 'object' ? rule : {} + return { + id: String(source.id || `rule-${index + 1}`).slice(0, 64), + keyword: String(source.keyword == null ? '' : source.keyword).slice(0, MAX_KEYWORD_LENGTH), + mode: ['contains', 'exact', 'prefix'].includes(source.mode) ? source.mode : 'contains', + reply: String(source.reply == null ? '' : source.reply).slice(0, MAX_REPLY_LENGTH), + cooldownSeconds: clampInteger(source.cooldownSeconds, 0, 3600, 0), + enabled: source.enabled !== false, + priority: clampInteger(source.priority, 0, 100, 0) + } +} + +function normalizeStoredConfig(stored) { + if (!stored || typeof stored !== 'object') return clone(DEFAULT_CONFIG) + const scope = stored.scope && typeof stored.scope === 'object' ? stored.scope : {} + return { + configVersion: CONFIG_VERSION, + enabled: stored.enabled === true, + rules: Array.isArray(stored.rules) + ? stored.rules.map(normalizeRule) + : clone(DEFAULT_CONFIG.rules), + scope: { + groups: Array.isArray(scope.groups) + ? scope.groups.map((id) => String(id).trim()).filter(Boolean) + : [], + includeDirect: scope.includeDirect !== false, + requireMentionMe: scope.requireMentionMe === true + } + } +} + +function field(label, control) { + const wrapper = document.createElement('label') + wrapper.className = 'field' + const caption = document.createElement('span') + caption.textContent = label + wrapper.append(caption, control) + return wrapper +} + +function renderRules() { + rulesContainer.textContent = '' + config.rules.forEach((rule, index) => { + const card = document.createElement('article') + card.className = 'rule-card' + if (!rule.enabled) card.classList.add('is-disabled') + + const head = document.createElement('div') + head.className = 'rule-head' + const title = document.createElement('strong') + title.textContent = `规则 ${index + 1}` + const toggle = document.createElement('label') + toggle.className = 'check' + const enabledInput = document.createElement('input') + enabledInput.type = 'checkbox' + enabledInput.checked = rule.enabled + enabledInput.addEventListener('change', () => { + rule.enabled = enabledInput.checked + card.classList.toggle('is-disabled', !rule.enabled) + }) + const toggleText = document.createElement('span') + toggleText.textContent = '启用' + toggle.append(enabledInput, toggleText) + const remove = document.createElement('button') + remove.type = 'button' + remove.className = 'ghost danger' + remove.textContent = '删除' + remove.addEventListener('click', () => { + config.rules.splice(index, 1) + renderRules() + }) + const headActions = document.createElement('div') + headActions.className = 'rule-head-actions' + headActions.append(toggle, remove) + head.append(title, headActions) + + const keywordInput = document.createElement('input') + keywordInput.type = 'text' + keywordInput.maxLength = MAX_KEYWORD_LENGTH + keywordInput.value = rule.keyword + keywordInput.addEventListener('input', () => { + rule.keyword = keywordInput.value + }) + + const modeSelect = document.createElement('select') + ;[ + ['contains', '包含'], + ['exact', '完全匹配'], + ['prefix', '以…开头'] + ].forEach(([value, label]) => { + const option = document.createElement('option') + option.value = value + option.textContent = label + option.selected = rule.mode === value + modeSelect.append(option) + }) + modeSelect.addEventListener('change', () => { + rule.mode = modeSelect.value + }) + + const replyInput = document.createElement('textarea') + replyInput.rows = 2 + replyInput.maxLength = MAX_REPLY_LENGTH + replyInput.value = rule.reply + replyInput.addEventListener('input', () => { + rule.reply = replyInput.value + }) + const replyBlock = field('回复内容', replyInput) + const replyHint = document.createElement('p') + replyHint.className = 'hint' + replyHint.textContent = + '可用变量:{sender}(发送者)、{keyword}(命中词)、{time}(当前时间 HH:mm)' + replyBlock.append(replyHint) + + const cooldownInput = document.createElement('input') + cooldownInput.type = 'number' + cooldownInput.min = '0' + cooldownInput.max = '3600' + cooldownInput.value = String(rule.cooldownSeconds) + cooldownInput.addEventListener('change', () => { + rule.cooldownSeconds = clampInteger(cooldownInput.value, 0, 3600, 0) + cooldownInput.value = String(rule.cooldownSeconds) + }) + + const priorityInput = document.createElement('input') + priorityInput.type = 'number' + priorityInput.min = '0' + priorityInput.max = '100' + priorityInput.step = '1' + priorityInput.value = String(rule.priority) + priorityInput.addEventListener('change', () => { + rule.priority = clampInteger(priorityInput.value, 0, 100, 0) + priorityInput.value = String(rule.priority) + }) + + const numberRow = document.createElement('div') + numberRow.className = 'field-row' + const cooldownField = field('冷却时间(秒)', cooldownInput) + const priorityField = field('优先级(0–100,越大越先匹配)', priorityInput) + numberRow.append(cooldownField, priorityField) + + card.append( + head, + field('关键词', keywordInput), + field('匹配方式', modeSelect), + replyBlock, + numberRow + ) + rulesContainer.append(card) + }) +} + +function syncForm() { + document.getElementById('enabled').checked = config.enabled === true + selectedGroupIds = new Set(config.scope.groups) + renderGroupChips() + renderGroupOptions() + document.getElementById('include-direct').checked = config.scope.includeDirect !== false + document.getElementById('require-mention').checked = config.scope.requireMentionMe === true + renderRules() +} + +function readForm() { + config.enabled = document.getElementById('enabled').checked + config.scope.groups = [...selectedGroupIds].slice(0, 200) + config.scope.includeDirect = document.getElementById('include-direct').checked + config.scope.requireMentionMe = document.getElementById('require-mention').checked +} + +function localDateKey(timestamp) { + const date = new Date(timestamp) + const month = String(date.getMonth() + 1).padStart(2, '0') + const day = String(date.getDate()).padStart(2, '0') + return `${date.getFullYear()}-${month}-${day}` +} + +function formatClock(timestamp) { + const date = new Date(timestamp) + const hour = String(date.getHours()).padStart(2, '0') + const minute = String(date.getMinutes()).padStart(2, '0') + return `${hour}:${minute}` +} + +/** 统计展示:只读 storage,不参与任何写入。 */ +function renderStats(raw) { + statsList.textContent = '' + const now = Date.now() + const sameDay = raw && raw.dateKey === localDateKey(now) + const todayCount = sameDay ? Math.max(0, Math.floor(Number(raw.todayCount) || 0)) : 0 + const hits = raw && Array.isArray(raw.lastHits) ? raw.lastHits.filter((hit) => hit && hit.at) : [] + + if (!hits.length && todayCount === 0) { + statsSummary.textContent = '暂无命中记录' + return + } + statsSummary.textContent = `今日命中 ${todayCount} 次` + + hits + .slice(-STATS_PREVIEW) + .reverse() + .forEach((hit) => { + const item = document.createElement('li') + item.className = 'stats-item' + const time = document.createElement('span') + time.textContent = formatClock(Number(hit.at)) + const ruleId = document.createElement('code') + ruleId.textContent = String(hit.ruleId || '未知规则') + const result = document.createElement('span') + result.className = hit.ok === true ? 'stats-ok' : 'stats-fail' + result.textContent = hit.ok === true ? '成功' : '失败' + item.append(time, ruleId, result) + statsList.append(item) + }) +} + +async function loadStats() { + try { + const stored = await callHost('storage.get', { key: STATS_KEY }) + renderStats(stored) + } catch (error) { + renderStats(null) + setStatus(`统计读取失败:${error.message}`, 'error') + } +} + +document.getElementById('add-rule').addEventListener('click', () => { + config.rules.push({ + id: newRuleId(), + keyword: '', + mode: 'contains', + reply: '', + cooldownSeconds: 30, + enabled: true, + priority: 0 + }) + renderRules() +}) + +document.getElementById('save').addEventListener('click', async () => { + readForm() + // 只有启用中的规则必须有内容:停用的草稿允许留空,方便先存后写。 + const invalid = config.rules.find( + (rule) => rule.enabled && (!rule.keyword.trim() || !rule.reply.trim()) + ) + if (invalid) { + setStatus('启用中的规则都需要关键词和回复内容;也可以先取消启用再保存。', 'error') + return + } + const payload = { + configVersion: CONFIG_VERSION, + enabled: config.enabled === true, + rules: config.rules.map(normalizeRule), + scope: { + groups: config.scope.groups.slice(0, 200), + includeDirect: config.scope.includeDirect !== false, + requireMentionMe: config.scope.requireMentionMe === true + } + } + try { + await callHost('storage.set', { key: CONFIG_KEY, value: payload }) + // 回写规范化结果但保留原对象引用:卡片上的输入事件仍在改这些对象。 + payload.rules.forEach((rule, index) => Object.assign(config.rules[index], rule)) + config.configVersion = CONFIG_VERSION + setStatus('配置已保存。后台进程会在下一次收到消息时生效。', 'ok') + loadStats() + } catch (error) { + setStatus(`保存失败:${error.message}`, 'error') + } +}) + +document.getElementById('reset').addEventListener('click', async () => { + config = clone(DEFAULT_CONFIG) + syncForm() + try { + await callHost('storage.set', { key: CONFIG_KEY, value: config }) + setStatus('已恢复默认配置。', 'ok') + } catch (error) { + setStatus(`重置失败:${error.message}`, 'error') + } +}) + +document.getElementById('refresh-stats').addEventListener('click', () => { + loadStats() +}) + +async function boot() { + const stored = await callHost('storage.get', { key: CONFIG_KEY }) + config = normalizeStoredConfig(stored) + syncForm() + await loadGroups() + setStatus('配置已读取。默认不启用,避免安装后立即对外发送。') + loadStats() +} + +boot().catch((error) => setStatus(`加载失败:${error.message}`, 'error')) diff --git a/examples/extensions/keyword-bot/ui/index.html b/examples/extensions/keyword-bot/ui/index.html new file mode 100644 index 0000000..1c11eea --- /dev/null +++ b/examples/extensions/keyword-bot/ui/index.html @@ -0,0 +1,71 @@ + + + + + + 关键词回复机器人 + + + +
+ + +
+
+

关键词规则

+ +
+
+
+ +
+

监听范围

+
+ 只监听这些群聊(可多选、可搜索;留空表示全部群聊) +
+ + + +
+
+
+ + +
+
+ +
+
+

运行统计

+ +
+

暂无命中记录

+
    +

    统计只记录规则编号、命中时间与发送结果,不含会话、昵称与消息正文。

    +
    + +
    +
    + + +
    +

    +
    +
    + + + diff --git a/examples/extensions/keyword-bot/ui/style.css b/examples/extensions/keyword-bot/ui/style.css new file mode 100644 index 0000000..c034646 --- /dev/null +++ b/examples/extensions/keyword-bot/ui/style.css @@ -0,0 +1,384 @@ +:root { + color-scheme: light dark; + --bg: #f6f8f7; + --card: #ffffff; + --text: #1c2622; + --muted: #6b7a73; + --border: #dfe6e2; + --brand: #247a63; + --danger: #b4472f; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #161c19; + --card: #1e2622; + --text: #eef4f1; + --muted: #9aaba3; + --border: #33403a; + --brand: #4bb894; + --danger: #e0735a; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + min-height: 100vh; + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', + sans-serif; +} + +.page { + max-width: 720px; + margin: 0 auto; + padding: 26px 22px 40px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.page-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; +} + +h1 { + margin: 0; + font-size: 19px; +} + +h2 { + margin: 0; + font-size: 13px; + font-weight: 700; +} + +header p { + margin: 8px 0 0; + max-width: 52ch; + color: var(--muted); + font-size: 12px; + line-height: 19px; +} + +.panel { + display: flex; + flex-direction: column; + gap: 12px; + padding: 16px 18px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--card); +} + +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.rules { + display: flex; + flex-direction: column; + gap: 12px; +} + +.rule-card { + display: flex; + flex-direction: column; + gap: 10px; + padding: 12px 14px; + border: 1px solid var(--border); + border-radius: 10px; +} + +.rule-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + font-size: 12px; +} + +.rule-head-actions { + display: flex; + align-items: center; + gap: 10px; +} + +.rule-card.is-disabled { + border-style: dashed; +} + +.rule-card.is-disabled .field, +.rule-card.is-disabled .field-row { + opacity: 0.55; +} + +.field-row { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; +} + +.hint { + margin: 0; + color: var(--muted); + font-size: 11px; + line-height: 16px; +} + +.stats-summary { + margin: 0; + color: var(--text); + font-size: 12px; +} + +.stats-list { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.stats-item { + display: flex; + align-items: center; + gap: 8px; + color: var(--muted); + font-size: 12px; +} + +.stats-ok { + color: var(--brand); +} + +.stats-fail { + color: var(--danger); +} + +@media (max-width: 480px) { + .field-row { + grid-template-columns: minmax(0, 1fr); + } +} + +.field > span { + color: var(--muted); + font-size: 11px; +} + +input[type='text'], +input[type='number'], +select, +textarea { + width: 100%; + padding: 7px 9px; + border: 1px solid var(--border); + border-radius: 8px; + background: transparent; + color: var(--text); + font-family: inherit; + font-size: 12px; +} + +textarea { + resize: vertical; +} + +.row { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; +} + +.check, +.switch { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--muted); +} + +.switch { + padding: 6px 10px; + border: 1px solid var(--border); + border-radius: 999px; + color: var(--text); +} + +button { + padding: 6px 11px; + border: 1px solid var(--border); + border-radius: 8px; + background: transparent; + color: var(--text); + font-family: inherit; + font-size: 12px; + cursor: pointer; +} + +button.primary { + border-color: transparent; + background: var(--brand); + color: #fff; +} + +button.ghost:hover { + border-color: var(--brand); +} + +button.danger { + color: var(--danger); +} + +.page-footer { + display: flex; + align-items: center; + gap: 16px; + flex-wrap: wrap; +} + +.status { + min-height: 18px; + margin: 0; + color: var(--muted); + font-size: 12px; +} + +.status[data-kind='ok'] { + color: var(--brand); +} + +.status[data-kind='error'] { + color: var(--danger); +} + +code { + padding: 1px 4px; + border-radius: 4px; + background: var(--bg); + font-size: 11px; +} + +/* 群聊多选:chips + 搜索框 + 复选下拉。 */ +.group-picker { + position: relative; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--card); + padding: 6px; +} + +.group-picker:focus-within { + border-color: var(--brand); +} + +.group-chips { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-bottom: 4px; +} + +.group-chip { + display: inline-flex; + align-items: center; + gap: 2px; + max-width: 100%; + padding: 2px 4px 2px 8px; + border-radius: 6px; + background: var(--bg); + font-size: 11px; +} + +.group-chip > span { + max-width: 220px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.group-chip-remove { + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; + font-size: 14px; + line-height: 1; + padding: 0 4px; +} + +.group-chip-remove:hover { + color: var(--danger); +} + +.group-picker > input[type='text'] { + width: 100%; + border: 0; + outline: 0; + background: transparent; + color: var(--text); + padding: 4px 2px; + font: inherit; + font-size: 12px; +} + +.group-options { + position: absolute; + z-index: 30; + left: 0; + right: 0; + top: calc(100% + 4px); + max-height: 220px; + overflow: auto; + padding: 4px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--card); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12); +} + +.group-option { + display: flex; + align-items: center; + gap: 6px; + padding: 5px 6px; + border-radius: 6px; + cursor: pointer; + font-size: 12px; +} + +.group-option:hover { + background: var(--bg); +} + +.group-option input { + margin: 0; +} + +.group-option-empty { + padding: 8px 6px; + color: var(--muted); + font-size: 11px; +} diff --git a/packages/extension-sdk/README.md b/packages/extension-sdk/README.md new file mode 100644 index 0000000..7634ea3 --- /dev/null +++ b/packages/extension-sdk/README.md @@ -0,0 +1,27 @@ +# @tracememo/extension-sdk + +TraceMemo 扩展 SDK v1 的**类型定义**。运行期不需要安装或打包这个包:宿主在扩展后台进程里注入全局 `tm`。 + +## 用法 + +把 `index.d.ts` 复制进扩展仓库(或作为 devDependency),然后: + +```ts +import type { TraceMemoApi } from './extension-sdk' + +module.exports = function activate(tm: TraceMemoApi): void { + tm.events.on('message.received', async (event) => { + if (event.isSelf || event.type !== 'text') return + if (!event.text?.includes('你好')) return + await tm.wechat.send({ to: event.conversationId, text: '你好呀!', dedupeKey: event.eventId }) + }) +} +``` + +## 约定 + +- 所有能力都要在 `manifest.json` 里声明权限;未声明的调用返回 `PERMISSION_DENIED`。 +- 后台是**独立 Node 子进程**,不是强沙箱:安装即表示信任该扩展代码。 +- 页面运行在 `sandbox="allow-scripts"` 的 iframe 里,只能通过 postMessage 调用 + `storage.*` / `capabilities.get` / `extension.info`,不能发送微信消息。 +- 发送永远经过宿主 Gateway:权限、授权校验、限流、审计与幂等都在宿主侧执行。 diff --git a/packages/extension-sdk/index.d.ts b/packages/extension-sdk/index.d.ts new file mode 100644 index 0000000..d2c0504 --- /dev/null +++ b/packages/extension-sdk/index.d.ts @@ -0,0 +1,188 @@ +/** + * TraceMemo 扩展 SDK v1 —— 仅类型定义。 + * + * 运行期没有这个包:宿主在后台子进程里注入全局 `tm`,扩展入口只需要 + * `module.exports = function activate(tm: TraceMemoApi) {}`。 + * 把本文件放进扩展仓库即可获得补全与类型检查。 + */ + +export type ExtensionMessageType = + | 'text' + | 'image' + | 'voice' + | 'video' + | 'sticker' + | 'file' + | 'link' + | 'system' + | 'other' + +export interface TraceMemoMessageEvent { + /** 同一条微信消息稳定不变:`message:`。 */ + eventId: string + accountId: string + conversationId: string + messageId: string + senderId?: string + senderName?: string + isGroup: boolean + isSelf: boolean + type: ExtensionMessageType + text?: string + /** 真正 @ 到当前登录账号,不是正文里的 `@昵称`。 */ + mentionsMe: boolean + /** epoch 毫秒。 */ + timestamp: number +} + +export interface TraceMemoQueriedMessage { + messageId: string + conversationId: string + senderId?: string + senderName?: string + isSelf: boolean + type: string + text?: string + /** epoch 毫秒。 */ + timestamp: number +} + +export interface TraceMemoSendTextRequest { + /** 缺省为 text。 */ + type?: 'text' + /** 群为 `xxx@chatroom`,私聊为 wxid。 */ + to: string + text: string + at?: Record + /** 相同键的重复请求会被 Gateway 审计短路。 */ + dedupeKey?: string +} + +/** + * 图片发送。 + */ +export interface TraceMemoSendImageRequest { + type: 'image' + to: string + path: string + dedupeKey?: string +} + +/** + * 视频发送。原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。 + * 路径必须位于扩展数据目录或系统临时目录。 + */ +export interface TraceMemoSendVideoRequest { + type: 'video' + to: string + path: string + dedupeKey?: string +} + +export type TraceMemoSendRequest = + | TraceMemoSendTextRequest + | TraceMemoSendImageRequest + | TraceMemoSendVideoRequest + +export interface TraceMemoAutomationActionDefinition { + id: string + title: string + description?: string + inputSchema?: { + type: 'object' + properties?: Record + required?: string[] + } + handler: (input: Record) => unknown | Promise +} + +export interface TraceMemoAutomationActionOutput { + success: boolean + output?: Record + /** 宿主经 Gateway 发回原会话;扩展自己不发消息。 */ + reply?: { type: 'text'; text: string; at?: Record } + error?: string +} + +export interface TraceMemoCapabilities { + extensionId: string + enabled: boolean + permissions: string[] + platform: string + databaseReady: boolean + send: { + supported: boolean + ready: boolean + canSendText: boolean + canSendImage: boolean + canSendVideo: boolean + licensed: boolean + message: string + } + ai: { configured: boolean; modelName: string } +} + +export interface TraceMemoApi { + extension: { + readonly id: string + /** 扩展私有数据目录;下载与生成的文件应放在这里。 */ + readonly dataDir: string + readonly permissions: string[] + } + events: { + on( + name: 'message.received', + handler: (event: TraceMemoMessageEvent) => void | Promise + ): () => void + off( + name: 'message.received', + handler: (event: TraceMemoMessageEvent) => void | Promise + ): void + } + messages: { + query(request: { + conversationId: string + /** epoch 毫秒;默认最近 24 小时。 */ + startTime?: number + /** epoch 毫秒;默认现在。 */ + endTime?: number + limit?: number + }): Promise<{ messages: TraceMemoQueriedMessage[] }> + } + wechat: { + send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }> + } + ai: { + chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }> + } + storage: { + get(key: string): Promise + set(key: string, value: unknown): Promise + remove(key: string): Promise + list(): Promise> + } + automation: { + registerAction(definition: TraceMemoAutomationActionDefinition): void + } + capabilities: { + get(): Promise + } + log: { + info(message: unknown): void + warn(message: unknown): void + error(message: unknown): void + } +} + +/** + * 后台入口签名。 + * + * ```js + * module.exports = function activate(tm) { ... } + * ``` + */ +export type TraceMemoActivate = (tm: TraceMemoApi) => void | Promise + +declare global { + var tm: TraceMemoApi +} diff --git a/packages/extension-sdk/package.json b/packages/extension-sdk/package.json new file mode 100644 index 0000000..880f56f --- /dev/null +++ b/packages/extension-sdk/package.json @@ -0,0 +1,9 @@ +{ + "name": "@tracememo/extension-sdk", + "version": "1.0.0", + "private": true, + "description": "TraceMemo 扩展 SDK 的类型定义(v1)。运行期由宿主注入 tm 对象,无需打包进扩展。", + "types": "index.d.ts", + "files": ["index.d.ts", "README.md"], + "license": "MIT" +} diff --git a/src/main/extensions/extension-action-registry.ts b/src/main/extensions/extension-action-registry.ts new file mode 100644 index 0000000..b8d6fdf --- /dev/null +++ b/src/main/extensions/extension-action-registry.ts @@ -0,0 +1,134 @@ +import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest' +import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types' + +export interface RegisteredExtensionAction { + extensionId: string + extensionName: string + actionId: string + title: string + description?: string + /** 后台进程是否真的注册了这个动作。 */ + registered: boolean + /** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */ + declared: boolean +} + +/** + * 扩展贡献的自动化动作注册表。 + * + * 两个来源刻意分开记: + * - `declared`:manifest 里写了什么 —— 用于在规则编辑器里展示「这个扩展提供了哪些动作」; + * - `registered`:后台进程运行期真正注册了什么 —— 只有它能被执行。 + * + * 二者不一致时**不猜**:动作在界面上显示为不可用,规则执行时明确报错。 + */ +export class ExtensionActionRegistry { + private readonly registered = new Map< + string, + Map + >() + private readonly declared = new Map< + string, + { name: string; actions: ExtensionAutomationActionContribution[] } + >() + private readonly names = new Map() + + setDeclared( + extensionId: string, + extensionName: string, + actions: ExtensionAutomationActionContribution[] + ): void { + this.names.set(extensionId, extensionName) + this.declared.set(extensionId, { name: extensionName, actions: [...actions] }) + } + + setRegistered( + extensionId: string, + extensionName: string, + actions: Array<{ id: string; title: string; description?: string }> + ): void { + this.names.set(extensionId, extensionName) + this.registered.set( + extensionId, + new Map( + actions.map((action) => [ + action.id, + { + title: action.title, + ...(action.description ? { description: action.description } : {}) + } + ]) + ) + ) + } + + remove(extensionId: string): void { + this.registered.delete(extensionId) + this.declared.delete(extensionId) + this.names.delete(extensionId) + } + + removeRuntime(extensionId: string): void { + this.registered.delete(extensionId) + } + + isRegistered(extensionId: string, actionId: string): boolean { + return this.registered.get(extensionId)?.has(actionId) === true + } + + get(extensionId: string, actionId: string): RegisteredExtensionAction | undefined { + const declaredAction = this.declared + .get(extensionId) + ?.actions.find((action) => action.id === actionId) + const runtime = this.registered.get(extensionId)?.get(actionId) + if (!declaredAction && !runtime) return undefined + return { + extensionId, + extensionName: this.names.get(extensionId) || extensionId, + actionId, + title: runtime?.title || declaredAction?.title || actionId, + ...(runtime?.description || declaredAction?.description + ? { description: runtime?.description || declaredAction?.description } + : {}), + registered: Boolean(runtime), + declared: Boolean(declaredAction) + } + } + + list(): RegisteredExtensionAction[] { + const result: RegisteredExtensionAction[] = [] + const extensionIds = new Set([...this.declared.keys(), ...this.registered.keys()]) + for (const extensionId of extensionIds) { + const declaredActions = this.declared.get(extensionId)?.actions ?? [] + const runtimeActions = this.registered.get(extensionId) ?? new Map() + const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()]) + for (const actionId of ids) { + const action = this.get(extensionId, actionId) + if (action) result.push(action) + } + } + return result.sort((left, right) => { + if (left.extensionName !== right.extensionName) + return left.extensionName.localeCompare(right.extensionName) + return left.title.localeCompare(right.title) + }) + } + + summariesFor(extensionId: string): ExtensionAutomationActionSummary[] { + const declaredActions = this.declared.get(extensionId)?.actions ?? [] + const runtimeActions = this.registered.get(extensionId) ?? new Map() + const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()]) + return Array.from(ids).map((actionId) => { + const declaredAction = declaredActions.find((action) => action.id === actionId) + const runtime = runtimeActions.get(actionId) + return { + id: actionId, + title: runtime?.title || declaredAction?.title || actionId, + ...(runtime?.description || declaredAction?.description + ? { description: runtime?.description || declaredAction?.description } + : {}), + registered: Boolean(runtime) + } + }) + } +} diff --git a/src/main/extensions/extension-automation-bridge.ts b/src/main/extensions/extension-automation-bridge.ts new file mode 100644 index 0000000..bb4f33b --- /dev/null +++ b/src/main/extensions/extension-automation-bridge.ts @@ -0,0 +1,45 @@ +import { ExtensionError } from '../../shared/extensions/errors' +import { hasExtensionPermission } from '../../shared/extensions/permissions' +import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc' +import type { ExtensionMessageEvent } from '../../shared/extensions/events' +import { getExtensionManager, hasExtensionManager } from './extension-service' + +export interface ExtensionActionContext { + conversationId: string + isGroup: boolean + accountId: string + message?: ExtensionMessageEvent +} + +/** + * 自动化 → 扩展动作的桥。 + * + * 输入里的 `conversationId` / `accountId` / `message` 是**宿主注入的运行时上下文**, + * 与用户在规则里配置的静态 `input` 合并;同名键以宿主值为准,扩展不能靠配置 + * 伪造一个假的会话或账号。 + */ +export async function invokeExtensionAction( + extensionId: string, + actionId: string, + input: Record, + context: ExtensionActionContext +): Promise { + if (!hasExtensionManager()) { + throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展系统尚未初始化') + } + const runtimeInput: Record = { + ...input, + conversationId: context.conversationId, + isGroup: context.isGroup, + accountId: context.accountId, + ...(context.message ? { message: context.message } : {}) + } + return getExtensionManager().invokeAutomationAction(extensionId, actionId, runtimeInput) +} + +export function canExtensionSendText(extensionId: string): boolean { + if (!hasExtensionManager()) return false + const extension = getExtensionManager().get(extensionId) + if (!extension?.enabled) return false + return hasExtensionPermission(extension.grantedPermissions, 'wechat.send.text') +} diff --git a/src/main/extensions/extension-entitlement.ts b/src/main/extensions/extension-entitlement.ts new file mode 100644 index 0000000..12b9ead --- /dev/null +++ b/src/main/extensions/extension-entitlement.ts @@ -0,0 +1,74 @@ +import { mapLicenseStatus, probeLicenseStatus } from '../services/msg-insert-capability-service' +import { macWechatRuntimeManager } from '../services/mac-wechat-runtime-manager' + +export interface ExtensionEntitlementResult { + ok: boolean + message: string + source: 'mac_license' | 'hook_license' | 'unsupported' +} + +export interface ExtensionEntitlementDependencies { + platform?: NodeJS.Platform + getMacLicense?: () => Promise<{ authorized: boolean; message?: string }> + probeLicense?: () => Promise<{ ok: boolean; status?: string }> +} + +/** + * 扩展发送的 授权校验。 + * + * 只在主进程可信边界调用,且**不接受渲染层 / 扩展传入的任何布尔值**: + * - macOS:读 Native Runtime 的 license 状态,要求 `authorized === true`; + * - Windows:探测本机 Hook 的 `/license/status`,只接受 `LICENSE_OK`。 + * + * 与「发送能力 ready」是两件事:能力 ready 只说明本机装好了 Runtime, + * 不代表授权有效。 + */ +export async function checkExtensionSendEntitlement( + dependencies: ExtensionEntitlementDependencies = {} +): Promise { + const platform = dependencies.platform ?? process.platform + if (platform === 'darwin') { + try { + const status = dependencies.getMacLicense + ? await dependencies.getMacLicense() + : await macWechatRuntimeManager.getMacLicenseStatus() + if (status.authorized) { + return { ok: true, message: '授权有效', source: 'mac_license' } + } + return { + ok: false, + message: status.message || '需要有效授权才能由扩展发送消息', + source: 'mac_license' + } + } catch (error) { + return { + ok: false, + message: error instanceof Error ? error.message : '无法确认授权状态', + source: 'mac_license' + } + } + } + if (platform === 'win32') { + try { + const probe = dependencies.probeLicense + ? await dependencies.probeLicense() + : await probeLicenseStatus() + if (!probe.ok) { + return { ok: false, message: '无法确认授权状态', source: 'hook_license' } + } + const mapped = mapLicenseStatus(probe.status) + return { + ok: mapped.entitlement === 'valid', + message: mapped.message, + source: 'hook_license' + } + } catch (error) { + return { + ok: false, + message: error instanceof Error ? error.message : '无法确认授权状态', + source: 'hook_license' + } + } + } + return { ok: false, message: '当前平台不支持微信发送', source: 'unsupported' } +} diff --git a/src/main/extensions/extension-event-bus.ts b/src/main/extensions/extension-event-bus.ts new file mode 100644 index 0000000..25810ed --- /dev/null +++ b/src/main/extensions/extension-event-bus.ts @@ -0,0 +1,135 @@ +import { createHash } from 'node:crypto' +import type { ExtensionEventEnvelope } from '../../shared/extensions/events' +import { + buildExtensionMessageEvent, + EXTENSION_EVENT_PROTOCOL_VERSION, + shouldDeliverExtensionEvent, + type ExtensionMessageEvent +} from '../../shared/extensions/events' +import type { ExtensionSubscriptions } from '../../shared/extensions/manifest' +import type { NormalizedIncomingMessage } from '../services/message-listener-service' + +const DEDUPE_TTL_MS = 10 * 60 * 1000 +const DEDUPE_MAX_ENTRIES = 5_000 + +export interface ExtensionEventSubscriber { + extensionId: string + subscriptions: ExtensionSubscriptions | undefined + deliver: (envelope: ExtensionEventEnvelope) => boolean +} + +export interface ExtensionEventBusDependencies { + listSubscribers: () => ExtensionEventSubscriber[] + getAccountId: () => string + getSelfUsernames: () => string[] + now?: () => number + onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void +} + +export interface ExtensionEventBusStats { + received: number + deduped: number + delivered: number + dropped: number +} + +/** + * 把 MessageListener 的规范化消息分发给扩展。 + * + * 去重键 `sessionId:localId`,扩展侧独立保留一层,避免进程重启后补投重复; + * 旧 Runtime 只能回读最近活跃会话,能力诊断会如实标记降级。 + */ +export class ExtensionEventBus { + private readonly seen = new Map() + private readonly now: () => number + private accountId = '' + private counters: ExtensionEventBusStats = { received: 0, deduped: 0, delivered: 0, dropped: 0 } + + constructor(private readonly dependencies: ExtensionEventBusDependencies) { + this.now = dependencies.now ?? (() => Date.now()) + } + + /** 切换账号时清空去重表:旧账号的 localId 不能在新账号下命中。 */ + setAccountId(accountId: string): void { + const next = String(accountId || '').trim() + if (next === this.accountId) return + this.accountId = next + this.seen.clear() + } + + stats(): ExtensionEventBusStats { + return { ...this.counters } + } + + /** 入口**绝不抛**:它挂在 MessageListener 的投递循环上。 */ + handleMessage(message: NormalizedIncomingMessage): void { + try { + this.counters.received += 1 + const eventId = buildEventId(message.sessionId, message.localId) + if (!this.markSeen(eventId)) { + this.counters.deduped += 1 + return + } + const selfUsernames = new Set(this.dependencies.getSelfUsernames()) + const event = buildExtensionMessageEvent({ + eventId, + accountId: this.accountId, + conversationId: message.sessionId, + messageId: message.serverId || message.localId, + ...(message.senderId ? { senderId: message.senderId } : {}), + ...(message.senderNickname ? { senderName: message.senderNickname } : {}), + isGroup: message.isGroup, + isSelf: message.isSelf, + messageType: message.messageType, + ...(message.content !== undefined ? { content: message.content } : {}), + // 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。 + mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)), + createTimeSeconds: message.createTime + }) + const envelope: ExtensionEventEnvelope = { + version: EXTENSION_EVENT_PROTOCOL_VERSION, + kind: 'message.received', + event + } + for (const subscriber of this.dependencies.listSubscribers()) { + if (!shouldDeliverExtensionEvent(subscriber.subscriptions, event)) continue + if (subscriber.deliver(envelope)) { + this.counters.delivered += 1 + this.dependencies.onDelivered?.(subscriber.extensionId, event) + } else { + this.counters.dropped += 1 + } + } + } catch (error) { + console.warn( + `[ExtensionEventBus] dispatch failed: ${error instanceof Error ? error.message : String(error)}` + ) + } + } + + private markSeen(eventId: string): boolean { + const now = this.now() + if (this.seen.has(eventId)) return false + this.seen.set(eventId, now) + if (this.seen.size > DEDUPE_MAX_ENTRIES) { + for (const [key, at] of this.seen) { + if (now - at > DEDUPE_TTL_MS) this.seen.delete(key) + } + if (this.seen.size > DEDUPE_MAX_ENTRIES) { + const overflow = this.seen.size - DEDUPE_MAX_ENTRIES + let removed = 0 + for (const key of this.seen.keys()) { + this.seen.delete(key) + removed += 1 + if (removed >= overflow) break + } + } + } + return true + } +} + +export function buildEventId(sessionId: string, localId: string): string { + const digest = createHash('sha1').update(`${sessionId}\u0001${localId}`).digest('hex') + return `message:${digest}` +} diff --git a/src/main/extensions/extension-host.ts b/src/main/extensions/extension-host.ts new file mode 100644 index 0000000..ce24c84 --- /dev/null +++ b/src/main/extensions/extension-host.ts @@ -0,0 +1,677 @@ +import { fork, type ChildProcess } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' +import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types' +import { + sortPermissionsByRisk, + type ExtensionPermission +} from '../../shared/extensions/permissions' +import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest' +import { + EXTENSION_HOST_PROTOCOL_VERSION, + type ExtensionAutomationActionOutput, + type ExtensionHostCall, + type ExtensionHostCallMethod, + type ExtensionHostInboundMessage, + type ExtensionHostOutboundMessage, + type ExtensionMessagesQueryRequest, + type ExtensionQueriedMessage, + type ExtensionSendImageRequest, + type ExtensionSendTextRequest, + type ExtensionSendTextResult, + type ExtensionSendVideoRequest +} from '../../shared/extensions/rpc' +import type { ExtensionEventEnvelope } from '../../shared/extensions/events' +import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types' +import type { ExtensionStorage } from './extension-storage' + +const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000 +const DEFAULT_ACTION_TIMEOUT_MS = 15_000 +const MAX_RESTARTS = 3 +const RESTART_WINDOW_MS = 5 * 60 * 1000 +const RESTART_BASE_DELAY_MS = 1_000 +const EVENT_BUCKET_CAPACITY = 100 +const EVENT_REFILL_PER_SECOND = 60 + +export interface ExtensionHostChild { + send(message: unknown): void + kill(): void + on(event: 'message', listener: (message: unknown) => void): void + on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void + on(event: 'error', listener: (error: Error) => void): void + once?(event: 'exit', listener: () => void): void + readonly pid?: number +} + +export interface ExtensionHostSpawnOptions { + extensionId: string + extensionDir: string +} + +export interface ExtensionHostDependencies { + extensionId: string + extensionDir: string + /** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */ + dataDir: string + permissions: ExtensionPermission[] + storage: ExtensionStorage + spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild + onLog?: (level: 'info' | 'warn' | 'error', message: string) => void + onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void + onActionsChanged?: () => void + queryMessages?: ( + extensionId: string, + request: ExtensionMessagesQueryRequest + ) => Promise + sendText?: ( + extensionId: string, + request: ExtensionSendTextRequest + ) => Promise + sendImage?: ( + extensionId: string, + request: ExtensionSendImageRequest + ) => Promise + sendVideo?: ( + extensionId: string, + request: ExtensionSendVideoRequest + ) => Promise + aiChat?: ( + extensionId: string, + messages: Array<{ role: string; content: string }> + ) => Promise<{ text: string }> + capabilities?: (extensionId: string) => Promise + now?: () => number + activateTimeoutMs?: number + actionTimeoutMs?: number +} + +interface PendingAction { + resolve: (value: ExtensionAutomationActionOutput) => void + reject: (error: Error) => void + timer: ReturnType +} + +interface RegisteredAction { + id: string + title: string + description?: string +} + +interface ActivationWaiter { + resolve: () => void + reject: (error: Error) => void + timer: ReturnType + child: ExtensionHostChild +} + +/** + * 单个扩展的后台进程。 + * + * **隔离边界**:每个扩展一个独立 Node 子进程,`require` 只发生在那里面; + * 主进程从不 `require` 扩展代码。子进程拿不到 Electron API、数据库句柄、 + * 授权凭据或原生发送通道 —— 它只能通过本类转发的白名单 RPC 申请能力。 + * + * ⚠️ 独立进程不等于强沙箱:后台仍是任意 Node 代码,安装时按「受信任本地开发者扩展」处理。 + */ +export class ExtensionHost { + private readonly dependencies: ExtensionHostDependencies + private readonly storage: ExtensionStorage + private readonly now: () => number + private child: ExtensionHostChild | null = null + private state: ExtensionRuntimeSnapshot + private stopping = false + private activation: Promise | null = null + private activationWaiter: ActivationWaiter | null = null + private restartTimer: ReturnType | null = null + private readonly pendingActions = new Map() + private readonly testHandlers = new Map< + string, + { + resolve: (value: unknown) => void + reject: (error: Error) => void + timer: ReturnType + } + >() + private readonly actions = new Map() + private eventTokens = EVENT_BUCKET_CAPACITY + private eventTokensAt: number + private droppedEvents = 0 + private mutedDropLog = false + private restartTimestamps: number[] = [] + + constructor(dependencies: ExtensionHostDependencies) { + this.dependencies = dependencies + this.storage = dependencies.storage + this.now = dependencies.now ?? (() => Date.now()) + this.eventTokensAt = this.now() + this.state = { state: 'inactive', since: this.now(), restarts: 0 } + } + + snapshot(): ExtensionRuntimeSnapshot { + return { ...this.state } + } + + registeredActions(): RegisteredAction[] { + return Array.from(this.actions.values()).map((action) => ({ ...action })) + } + + async testSend(params: Record): Promise { + return this.runTestMessage('test-send', params) + } + + private async runTestMessage( + type: 'test-send', + params: Record + ): Promise { + if (this.state.state !== 'active' || !this.child) { + throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE') + } + const requestId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.testHandlers.delete(requestId) + reject(new ExtensionError('ACTION_TIMEOUT')) + }, 450_000) + this.testHandlers.set(requestId, { resolve, reject, timer }) + try { + this.child?.send({ + type, + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId, + params + }) + } catch (error) { + clearTimeout(timer) + this.testHandlers.delete(requestId) + reject( + new ExtensionError( + 'EXTENSION_HOST_UNAVAILABLE', + error instanceof Error ? error.message : '扩展进程不可用' + ) + ) + } + }) + } + + /** 启动并等待 `activate` 握手完成。重复调用复用同一次启动。 */ + async start(): Promise { + if (this.state.state === 'active') return + if (this.activation) return this.activation + this.stopping = false + this.activation = this.doStart().finally(() => { + this.activation = null + }) + return this.activation + } + + async stop(): Promise { + this.stopping = true + if (this.restartTimer) { + clearTimeout(this.restartTimer) + this.restartTimer = null + } + const child = this.child + this.child = null + this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) + this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) + this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) + this.actions.clear() + this.setState('inactive') + if (!child) return + try { + child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION }) + } catch { + // 进程可能已经断开;kill 兜底。 + } + await new Promise((resolve) => { + const timer = setTimeout(() => { + try { + child.kill() + } catch { + // ignore + } + resolve() + }, 1_500) + child.once?.('exit', () => { + clearTimeout(timer) + resolve() + }) + }) + } + + /** + * 投递消息事件。 + * + * 令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志, + * 也不能让主进程的监听回调被拖垮。 + */ + deliverEvent(envelope: ExtensionEventEnvelope): boolean { + if (this.state.state !== 'active' || !this.child) return false + this.refillTokens() + if (this.eventTokens < 1) { + this.droppedEvents += 1 + if (!this.mutedDropLog && this.droppedEvents % 100 === 1) { + this.dependencies.onLog?.('warn', '消息事件超过扩展处理上限,部分事件已丢弃') + this.mutedDropLog = true + setTimeout(() => { + this.mutedDropLog = false + }, 10_000) + } + return false + } + this.eventTokens -= 1 + try { + this.child.send({ type: 'event', version: EXTENSION_HOST_PROTOCOL_VERSION, envelope }) + return true + } catch { + return false + } + } + + /** 调用扩展注册的自动化动作。超时由宿主强制结束,扩展无法自行取消。 */ + async invokeAction( + actionId: string, + input: Record, + timeoutMs = this.dependencies.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS + ): Promise { + if (this.state.state !== 'active' || !this.child) { + throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE') + } + if (!this.actions.has(actionId)) { + throw new ExtensionError('ACTION_FAILED', `扩展没有注册动作 ${actionId}`) + } + const requestId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => { + this.pendingActions.delete(requestId) + reject(new ExtensionError('ACTION_TIMEOUT')) + }, + Math.max(1_000, Math.min(timeoutMs, 60_000)) + ) + this.pendingActions.set(requestId, { resolve, reject, timer }) + try { + this.child?.send({ + type: 'invoke-action', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId, + actionId, + input, + timeoutMs + }) + } catch (error) { + clearTimeout(timer) + this.pendingActions.delete(requestId) + reject( + new ExtensionError( + 'EXTENSION_HOST_UNAVAILABLE', + error instanceof Error ? error.message : '扩展进程不可用' + ) + ) + } + }) + } + + private async doStart(): Promise { + this.setState('starting') + this.actions.clear() + let child: ExtensionHostChild + try { + child = this.dependencies.spawn({ + extensionId: this.dependencies.extensionId, + extensionDir: this.dependencies.extensionDir + }) + } catch (error) { + this.setState('error', error instanceof Error ? error.message : '扩展进程启动失败') + throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程启动失败') + } + this.child = child + this.wire(child) + + try { + await this.activateChild(child) + this.setState('active') + this.dependencies.onLog?.('info', '扩展后台已启动') + } catch (error) { + this.dependencies.onLog?.( + 'error', + `扩展启动失败:${error instanceof Error ? error.message : String(error)}` + ) + // 先摘掉引用再 kill:否则 exit 回调会被当成「运行期崩溃」并触发重启。 + if (this.child === child) this.child = null + try { + child.kill() + } catch { + // ignore + } + this.setState('error', error instanceof Error ? error.message : '扩展启动失败') + throw error instanceof Error + ? error + : new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展启动失败') + } + } + + /** 发 `activate` 并等待 `activated`。握手结果由 `handleMessage` 统一结算。 */ + private activateChild(child: ExtensionHostChild): Promise { + const timeoutMs = this.dependencies.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS + return new Promise((resolve, reject) => { + const timer = setTimeout( + () => { + this.settleActivation(new ExtensionError('ACTION_TIMEOUT', '扩展启动超时')) + }, + Math.max(2_000, timeoutMs) + ) + this.activationWaiter = { resolve, reject, timer, child } + try { + child.send({ + type: 'activate', + version: EXTENSION_HOST_PROTOCOL_VERSION, + extensionId: this.dependencies.extensionId, + extensionDir: this.dependencies.extensionDir, + dataDir: this.dependencies.dataDir, + apiVersion: EXTENSION_API_VERSION, + permissions: sortPermissionsByRisk(this.dependencies.permissions) + }) + } catch (error) { + this.settleActivation( + new ExtensionError( + 'EXTENSION_HOST_UNAVAILABLE', + error instanceof Error ? error.message : '无法向扩展进程发送激活指令' + ) + ) + } + }) + } + + private settleActivation(error?: Error): void { + const waiter = this.activationWaiter + if (!waiter) return + this.activationWaiter = null + clearTimeout(waiter.timer) + if (error) waiter.reject(error) + else waiter.resolve() + } + + private wire(child: ExtensionHostChild): void { + child.on('message', (message) => this.handleMessage(message)) + child.on('error', (error) => { + this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`) + }) + child.on('exit', (code) => this.handleExit(child, code)) + } + + private handleExit(child: ExtensionHostChild, code: number | null): void { + if (this.child !== child) return + this.child = null + this.actions.clear() + this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出')) + this.failPendingActions( + new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`) + ) + this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出')) + if (this.stopping) { + this.setState('inactive') + return + } + const timestamp = this.now() + this.restartTimestamps = this.restartTimestamps.filter( + (item) => timestamp - item < RESTART_WINDOW_MS + ) + if (this.restartTimestamps.length >= MAX_RESTARTS) { + this.dependencies.onLog?.('error', '扩展连续异常退出,已停止自动重启') + this.setState('crashed', '扩展连续异常退出,已停止自动重启') + return + } + this.restartTimestamps.push(timestamp) + this.setState('starting', '扩展进程异常退出,正在重启') + const delay = RESTART_BASE_DELAY_MS * 2 ** (this.restartTimestamps.length - 1) + this.restartTimer = setTimeout(() => { + this.restartTimer = null + this.state = { ...this.state, restarts: this.state.restarts + 1, since: this.now() } + void this.start().catch(() => undefined) + }, delay) + } + + private handleMessage(raw: unknown): void { + if (!raw || typeof raw !== 'object') return + const message = raw as ExtensionHostOutboundMessage & { version?: number } + if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return + switch (message.type) { + case 'activated': + this.settleActivation( + message.ok + ? undefined + : new ExtensionError('ACTION_FAILED', message.error?.message || '扩展激活失败') + ) + return + case 'call': + void this.handleCall(message) + return + case 'register-action': { + const action = message.action + if (!action || typeof action.id !== 'string') return + this.actions.set(action.id, { + id: action.id, + title: String(action.title || action.id).slice(0, 60), + ...(action.description ? { description: String(action.description).slice(0, 200) } : {}) + }) + this.dependencies.onActionsChanged?.() + return + } + case 'log': + this.dependencies.onLog?.(message.level, message.message) + return + case 'action-result': { + const pending = this.pendingActions.get(message.requestId) + if (!pending) return + clearTimeout(pending.timer) + this.pendingActions.delete(message.requestId) + if (message.ok && message.output) { + pending.resolve(message.output) + } else { + pending.reject( + new ExtensionError( + 'ACTION_FAILED', + message.error?.message || message.output?.error || '扩展动作执行失败' + ) + ) + } + return + } + case 'test-result': { + const pending = this.testHandlers.get(message.requestId) + if (!pending) return + clearTimeout(pending.timer) + this.testHandlers.delete(message.requestId) + if (message.ok) pending.resolve(message.result) + else + pending.reject( + new ExtensionError(message.error?.code || 'ACTION_FAILED', message.error?.message) + ) + return + } + } + } + + private async handleCall(message: ExtensionHostCall): Promise { + try { + const result = await this.executeCall(message.method, message.params) + this.send({ + type: 'call-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + callId: message.callId, + ok: true, + result + }) + } catch (error) { + this.send({ + type: 'call-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + callId: message.callId, + ok: false, + error: toExtensionErrorPayload(error) + }) + } + } + + private async executeCall( + method: ExtensionHostCallMethod, + params: Record + ): Promise { + const extensionId = this.dependencies.extensionId + switch (method) { + case 'storage.get': + this.requirePermission('storage') + return this.storage.get(extensionId, params.key) + case 'storage.set': + this.requirePermission('storage') + this.storage.set(extensionId, params.key, params.value) + return { ok: true } + case 'storage.remove': + this.requirePermission('storage') + return { removed: this.storage.remove(extensionId, params.key) } + case 'storage.list': + this.requirePermission('storage') + return { entries: this.storage.list(extensionId) } + case 'messages.query': { + this.requirePermission('messages.query') + if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return { + messages: await this.dependencies.queryMessages( + extensionId, + params as unknown as ExtensionMessagesQueryRequest + ) + } + } + case 'wechat.send.text': { + this.requirePermission('wechat.send.text') + if (!this.dependencies.sendText) throw new ExtensionError('SEND_NOT_SUPPORTED') + return this.dependencies.sendText( + extensionId, + params as unknown as ExtensionSendTextRequest + ) + } + case 'wechat.send.image': { + this.requirePermission('wechat.send.image') + if (!this.dependencies.sendImage) throw new ExtensionError('SEND_NOT_SUPPORTED') + return this.dependencies.sendImage( + extensionId, + params as unknown as ExtensionSendImageRequest + ) + } + case 'wechat.send.video': { + this.requirePermission('wechat.send.video') + if (!this.dependencies.sendVideo) throw new ExtensionError('SEND_NOT_SUPPORTED') + return this.dependencies.sendVideo( + extensionId, + params as unknown as ExtensionSendVideoRequest + ) + } + case 'ai.chat': { + this.requirePermission('ai.chat') + if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + const messages = Array.isArray(params.messages) ? params.messages : [] + const normalized = messages + .filter((item): item is { role: string; content: string } => + Boolean(item && typeof item === 'object') + ) + .slice(0, 40) + .map((item) => ({ + role: String((item as { role?: unknown }).role || 'user'), + content: String((item as { content?: unknown }).content || '').slice(0, 20_000) + })) + return this.dependencies.aiChat(extensionId, normalized) + } + case 'capabilities.get': + if (!this.dependencies.capabilities) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.capabilities(extensionId) + default: + throw new ExtensionError('INVALID_REQUEST', `未知方法:${String(method)}`) + } + } + + private requirePermission(permission: ExtensionPermission): void { + if (!this.dependencies.permissions.includes(permission)) { + throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`) + } + } + + private send(message: ExtensionHostInboundMessage): void { + try { + this.child?.send(message) + } catch { + // 进程已退出:pending 会由 handleExit 统一失败。 + } + } + + private failPendingActions(error: Error): void { + for (const [requestId, pending] of this.pendingActions) { + clearTimeout(pending.timer) + this.pendingActions.delete(requestId) + pending.reject(error) + } + } + + private failPendingTests(error: Error): void { + for (const [requestId, pending] of this.testHandlers) { + clearTimeout(pending.timer) + this.testHandlers.delete(requestId) + pending.reject(error) + } + } + + private refillTokens(): void { + const now = this.now() + const elapsed = Math.max(0, now - this.eventTokensAt) + if (elapsed <= 0) return + this.eventTokens = Math.min( + EVENT_BUCKET_CAPACITY, + this.eventTokens + (elapsed / 1000) * EVENT_REFILL_PER_SECOND + ) + this.eventTokensAt = now + } + + private setState(next: ExtensionRuntimeSnapshot['state'], lastError?: string): void { + this.state = { + state: next, + since: this.now(), + restarts: this.state.restarts, + ...(lastError ? { lastError } : {}) + } + this.dependencies.onStateChange?.(this.snapshot()) + } +} + +/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */ +export function forkExtensionHost( + scriptPath: string +): (options: ExtensionHostSpawnOptions) => ExtensionHostChild { + return (options) => { + const child: ChildProcess = fork(scriptPath, [], { + stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + serialization: 'advanced', + env: { + ...process.env, + ELECTRON_RUN_AS_NODE: '1', + TM_EXTENSION_ID: options.extensionId, + TM_EXTENSION_DIR: options.extensionDir + } + }) + return { + send: (message) => { + if (!child.connected) throw new Error('扩展进程未连接') + child.send(message as object) + }, + kill: () => child.kill(), + on: (event, listener) => { + if (event === 'message') child.on('message', listener as (message: unknown) => void) + else if (event === 'exit') child.on('exit', listener as (code: number | null) => void) + else child.on('error', listener as (error: Error) => void) + }, + once: (event, listener) => { + child.once(event, listener) + }, + ...(child.pid ? { pid: child.pid } : {}) + } + } +} diff --git a/src/main/extensions/extension-installer.ts b/src/main/extensions/extension-installer.ts new file mode 100644 index 0000000..b1d137d --- /dev/null +++ b/src/main/extensions/extension-installer.ts @@ -0,0 +1,390 @@ +import { promises as fs } from 'node:fs' +import path from 'node:path' +import { Open } from 'unzipper' +import { ExtensionError } from '../../shared/extensions/errors' +import { + isSafeRelativeEntryPath, + parseExtensionManifest, + type ExtensionManifest +} from '../../shared/extensions/manifest' +import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry' +import { isPathInside, type ExtensionPaths } from './extension-paths' + +const MAX_FILES = 2_000 +const MAX_TOTAL_BYTES = 50 * 1024 * 1024 +const MAX_FILE_BYTES = 20 * 1024 * 1024 +const MAX_PACKAGE_BYTES = 100 * 1024 * 1024 + +export interface InstallOptions { + /** 应用版本,用于 `minAppVersion` 兼容检查。 */ + appVersion: string + source?: 'directory' | 'package' +} + +export interface InstallOutcome { + manifest: ExtensionManifest + installPath: string + previousVersion?: string + upgraded: boolean +} + +export interface ExtensionInstallerDependencies { + paths: ExtensionPaths + registry: ExtensionRegistry + now?: () => number +} + +interface TreeEntry { + relativePath: string + type: 'file' | 'directory' + size: number +} + +/** + * 扩展安装 / 升级 / 卸载。 + * + * 写入顺序固定为「临时目录 → 校验 → 原子改名」:任何一步失败都不会留下 + * 半装目录;升级失败时旧版本仍在原位。 + */ +export class ExtensionInstaller { + private readonly paths: ExtensionPaths + private readonly registry: ExtensionRegistry + private readonly now: () => number + + constructor(dependencies: ExtensionInstallerDependencies) { + this.paths = dependencies.paths + this.registry = dependencies.registry + this.now = dependencies.now ?? (() => Date.now()) + } + + async installFromDirectory(sourceDir: string, options: InstallOptions): Promise { + const root = path.resolve(sourceDir) + const stat = await fs.stat(root).catch(() => null) + if (!stat || !stat.isDirectory()) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的路径不是目录') + } + const manifest = await this.readManifest(root, options.appVersion) + const entries = await this.collectTree(root) + this.assertEntrypointsPresent(entries, manifest) + + const staging = this.paths.stagingPath('dir') + await fs.mkdir(staging, { recursive: true }) + try { + await copyTree(root, staging, entries) + return await this.finalize(staging, manifest, options.source ?? 'directory') + } finally { + await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined) + } + } + + async installFromPackage(packagePath: string, options: InstallOptions): Promise { + const stat = await fs.stat(packagePath).catch(() => null) + if (!stat || !stat.isFile()) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的扩展包不存在') + } + if (stat.size > MAX_PACKAGE_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包超过大小限制') + } + + const archive = await Open.file(packagePath) + if (!archive.files.length || archive.files.length > MAX_FILES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包文件数量不合法') + } + + const seen = new Set() + let declaredTotal = 0 + const entries: Array<{ + relativePath: string + directory: boolean + size: number + entry: (typeof archive.files)[number] + }> = [] + for (const entry of archive.files) { + const normalized = normalizeZipPath(entry.path) + const collisionKey = normalized.toLowerCase() + if (seen.has(collisionKey)) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内路径重复:${normalized}`) + } + seen.add(collisionKey) + if (entry.type !== 'File' && entry.type !== 'Directory') { + throw new ExtensionError( + 'EXTENSION_INSTALL_FAILED', + `扩展包条目类型不受支持:${normalized}` + ) + } + const directory = entry.type === 'Directory' + const size = Number(entry.uncompressedSize || 0) + if (!directory && size > MAX_FILE_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内文件过大:${normalized}`) + } + declaredTotal += size + if (declaredTotal > MAX_TOTAL_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包解压后体积超过限制') + } + entries.push({ relativePath: normalized, directory, size, entry }) + } + + const manifestFile = entries.find( + (item) => item.relativePath === 'manifest.json' && !item.directory + ) + if (!manifestFile) + throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展包缺少 manifest.json') + const manifest = this.parseManifestText( + (await manifestFile.entry.buffer()).toString('utf8'), + options.appVersion + ) + this.assertEntrypointsPresent( + entries.map((item) => ({ + relativePath: item.relativePath, + type: item.directory ? 'directory' : 'file', + size: item.size + })), + manifest + ) + + const staging = this.paths.stagingPath('zip') + await fs.mkdir(staging, { recursive: true }) + try { + let actualTotal = 0 + for (const item of entries) { + const destination = path.resolve(staging, item.relativePath) + if (!isPathInside(staging, destination)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包条目越界:${item.relativePath}`) + } + if (item.directory) { + await fs.mkdir(destination, { recursive: true }) + continue + } + await fs.mkdir(path.dirname(destination), { recursive: true }) + const chunks: Buffer[] = [] + for await (const chunk of item.entry.stream()) { + const buffer = Buffer.from(chunk as Uint8Array) + actualTotal += buffer.length + if (actualTotal > MAX_TOTAL_BYTES || buffer.length > MAX_FILE_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包实际解压体积超过限制') + } + chunks.push(buffer) + } + await fs.writeFile(destination, Buffer.concat(chunks)) + const fileStat = await fs.lstat(destination) + if (!fileStat.isFile()) { + throw new ExtensionError( + 'EXTENSION_INVALID_PATH', + `扩展包条目不是普通文件:${item.relativePath}` + ) + } + } + return await this.finalize(staging, manifest, 'package') + } finally { + await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined) + } + } + + /** + * 卸载扩展。 + * + * `keepData` 为 true 时**只**删除代码目录,用户配置保留在 + * `extensions-data/`,同名扩展重新安装后能读回。 + */ + async uninstall(extensionId: string, options: { keepData: boolean }): Promise { + const target = this.paths.installDir(extensionId) + if (!isPathInside(this.paths.extensionsDir, target)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界') + } + const trash = `${target}.removed-${this.now()}` + const exists = await fs + .stat(target) + .then(() => true) + .catch(() => false) + if (exists) { + await fs.rename(target, trash) + await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined) + } + if (!options.keepData) { + await fs + .rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true }) + .catch(() => undefined) + } + this.registry.remove(extensionId) + } + + private async readManifest(root: string, appVersion: string): Promise { + const manifestPath = path.join(root, 'manifest.json') + const text = await fs.readFile(manifestPath, 'utf8').catch(() => '') + if (!text) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展目录缺少 manifest.json') + return this.parseManifestText(text, appVersion) + } + + private parseManifestText(text: string, appVersion: string): ExtensionManifest { + const result = parseExtensionManifestJsonWithDetail(text, appVersion) + if (!result.ok || !result.manifest) { + throw new ExtensionError( + result.code === 'EXTENSION_INCOMPATIBLE' + ? 'EXTENSION_INCOMPATIBLE' + : 'EXTENSION_INVALID_MANIFEST', + result.message || '扩展 manifest 不合法' + ) + } + return result.manifest + } + + private assertEntrypointsPresent(entries: TreeEntry[], manifest: ExtensionManifest): void { + const files = new Set( + entries.filter((entry) => entry.type === 'file').map((entry) => entry.relativePath) + ) + for (const [key, value] of Object.entries(manifest.entrypoints)) { + if (!value) continue + if (!files.has(value)) { + throw new ExtensionError( + 'EXTENSION_INVALID_MANIFEST', + `entrypoints.${key} 指向的文件不存在:${value}` + ) + } + } + for (const page of manifest.contributions.pages) { + const entry = page.entry || manifest.entrypoints.page + if (!entry || !files.has(entry)) { + throw new ExtensionError('EXTENSION_INVALID_MANIFEST', `页面 ${page.id} 的入口文件不存在`) + } + } + } + + private async collectTree(root: string): Promise { + const entries: TreeEntry[] = [] + let total = 0 + const walk = async (directory: string, prefix: string): Promise => { + const items = await fs.readdir(directory, { withFileTypes: true }) + for (const item of items) { + const relativePath = prefix ? `${prefix}/${item.name}` : item.name + if (!isSafeRelativeEntryPath(relativePath)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`) + } + const absolute = path.join(directory, item.name) + const stat = await fs.lstat(absolute) + if (stat.isSymbolicLink()) { + throw new ExtensionError( + 'EXTENSION_INVALID_PATH', + `扩展目录不能包含符号链接:${relativePath}` + ) + } + if (stat.isDirectory()) { + entries.push({ relativePath, type: 'directory', size: 0 }) + await walk(absolute, relativePath) + continue + } + if (!stat.isFile()) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `不支持的文件类型:${relativePath}`) + } + if (stat.size > MAX_FILE_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', `文件过大:${relativePath}`) + } + total += stat.size + if (total > MAX_TOTAL_BYTES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展体积超过限制') + } + entries.push({ relativePath, type: 'file', size: stat.size }) + if (entries.length > MAX_FILES) { + throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展文件数量超过限制') + } + } + } + await walk(root, '') + return entries + } + + /** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */ + private async finalize( + staging: string, + manifest: ExtensionManifest, + source: 'directory' | 'package' + ): Promise { + const target = this.paths.installDir(manifest.id) + if (!isPathInside(this.paths.extensionsDir, target)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界') + } + await fs.mkdir(this.paths.extensionsDir, { recursive: true }) + + const existingRecord = this.registry.get(manifest.id) + const backup = `${target}.backup-${this.now()}` + const targetExists = await fs + .stat(target) + .then(() => true) + .catch(() => false) + + if (targetExists) await fs.rename(target, backup) + try { + await fs.rename(staging, target) + } catch (error) { + if (targetExists) await fs.rename(backup, target).catch(() => undefined) + throw new ExtensionError( + 'EXTENSION_INSTALL_FAILED', + error instanceof Error ? error.message : '安装目录替换失败' + ) + } + if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined) + + const timestamp = this.now() + const record: ExtensionRegistryRecord = { + id: manifest.id, + version: manifest.version, + apiVersion: manifest.apiVersion, + // 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。 + enabled: existingRecord?.enabled ?? false, + grantedPermissions: existingRecord?.grantedPermissions ?? [], + installedAt: existingRecord?.installedAt ?? timestamp, + updatedAt: timestamp, + source + } + this.registry.upsert(record) + + return { + manifest, + installPath: target, + ...(existingRecord ? { previousVersion: existingRecord.version } : {}), + upgraded: Boolean(existingRecord) + } + } +} + +function normalizeZipPath(value: string): string { + const normalized = String(value || '') + .replace(/\\/g, '/') + .replace(/\/+$/, '') + if (!isSafeRelativeEntryPath(normalized)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包内路径不合法:${value}`) + } + return normalized +} + +async function copyTree(root: string, destination: string, entries: TreeEntry[]): Promise { + for (const entry of entries) { + const from = path.join(root, entry.relativePath) + const to = path.resolve(destination, entry.relativePath) + if (!isPathInside(destination, to)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', `复制路径越界:${entry.relativePath}`) + } + if (entry.type === 'directory') { + await fs.mkdir(to, { recursive: true }) + continue + } + await fs.mkdir(path.dirname(to), { recursive: true }) + await fs.copyFile(from, to) + } +} + +/** + * 与 shared 的 `parseExtensionManifestJson` 同构,但把「兼容性」与「格式」区分开, + * 好让安装界面给出可操作的提示(升级 TraceMemo vs 修 manifest)。 + */ +function parseExtensionManifestJsonWithDetail( + text: string, + appVersion: string +): ReturnType { + let value: unknown + try { + value = JSON.parse(text) + } catch { + return { ok: false, code: 'EXTENSION_INVALID_MANIFEST', message: 'manifest.json 不是合法 JSON' } + } + return parseExtensionManifest(value, { appVersion }) +} diff --git a/src/main/extensions/extension-ipc.ts b/src/main/extensions/extension-ipc.ts new file mode 100644 index 0000000..b97a3be --- /dev/null +++ b/src/main/extensions/extension-ipc.ts @@ -0,0 +1,195 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { BrowserWindow, dialog, ipcMain, shell } from 'electron' +import { EXTENSION_IPC } from '../../shared/extensions/ipc' +import type { + ExtensionInstallResult, + ExtensionLogEntry, + ExtensionOperationResult, + ExtensionPageDescriptor, + ExtensionPageRequest, + ExtensionPageResponse, + InstalledExtension +} from '../../shared/extensions/types' +import type { ExtensionManager } from './extension-manager' +import type { ExtensionPaths } from './extension-paths' + +export interface ExtensionIpcOptions { + /** 懒取:扩展系统在窗口创建之后才完成初始化。 */ + getManager: () => ExtensionManager + paths: ExtensionPaths + /** 扩展页面 IPC 的调用方必须是主窗口;其它 webContents 一律拒绝。 */ + isTrustedSender: (senderId: number) => boolean +} + +/** + * 注册扩展中心的 IPC。 + * + * 所有入参都在这一层收敛类型与长度:渲染层与扩展页面都是「不可信输入」, + * 不能把未校验的对象直接交给 manager。 + */ +export function registerExtensionIpc(options: ExtensionIpcOptions): void { + const { paths } = options + const manager = (): ExtensionManager => options.getManager() + const guard = ( + handler: (...args: Args) => Promise | Result + ): (( + event: Electron.IpcMainInvokeEvent, + ...args: Args + ) => Promise) => { + return async (event, ...args) => { + if (!options.isTrustedSender(event.sender.id)) { + return { success: false, error: { code: 'PERMISSION_DENIED', message: '不受信任的调用方' } } + } + try { + return await handler(...args) + } catch (error) { + return { + success: false, + error: { + code: 'ACTION_FAILED', + message: error instanceof Error ? error.message : '扩展操作失败' + } + } + } + } + } + + ipcMain.handle( + EXTENSION_IPC.list, + guard((): InstalledExtension[] => manager().list()) + ) + + ipcMain.handle( + EXTENSION_IPC.detail, + guard((extensionId: unknown): InstalledExtension | null => + manager().get(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.pickDirectory, + guard(async (): Promise => { + const window = BrowserWindow.getFocusedWindow() + const result = window + ? await dialog.showOpenDialog(window, { properties: ['openDirectory'] }) + : await dialog.showOpenDialog({ properties: ['openDirectory'] }) + return result.canceled || !result.filePaths.length ? null : result.filePaths[0] + }) + ) + + ipcMain.handle( + EXTENSION_IPC.pickPackage, + guard(async (): Promise => { + const window = BrowserWindow.getFocusedWindow() + const options: Electron.OpenDialogOptions = { + properties: ['openFile'], + filters: [ + { name: 'TraceMemo 扩展包', extensions: ['zip', 'tmext'] }, + { name: '全部文件', extensions: ['*'] } + ] + } + const result = window + ? await dialog.showOpenDialog(window, options) + : await dialog.showOpenDialog(options) + return result.canceled || !result.filePaths.length ? null : result.filePaths[0] + }) + ) + + ipcMain.handle( + EXTENSION_IPC.installDirectory, + guard( + (directory: unknown): Promise => + manager().installFromDirectory(requirePath(directory)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.installPackage, + guard( + (packagePath: unknown): Promise => + manager().installFromPackage(requirePath(packagePath)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.setEnabled, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; enabled?: unknown } + return manager().setEnabled(requireId(input.id), input.enabled === true) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.uninstall, + guard((payload: unknown): Promise => { + const input = (payload ?? {}) as { id?: unknown; keepData?: unknown } + return manager().uninstall(requireId(input.id), input.keepData !== false) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.logs, + guard((payload: unknown): ExtensionLogEntry[] => { + const input = (payload ?? {}) as { id?: unknown; limit?: unknown } + const limit = Number(input.limit) + return manager().getLogs(requireId(input.id), Number.isFinite(limit) ? limit : 100) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.clearLogs, + guard((extensionId: unknown): { success: true } => { + manager().clearLogs(requireId(extensionId)) + return { success: true } + }) + ) + + ipcMain.handle( + EXTENSION_IPC.pageUrl, + guard((payload: unknown): ExtensionPageDescriptor => { + const input = (payload ?? {}) as { id?: unknown; pageId?: unknown } + const pageId = + typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined + return manager().pageUrl(requireId(input.id), pageId) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.pageRequest, + guard((payload: unknown): Promise => { + const request = (payload ?? {}) as Partial + const extensionId = requireId(request.extensionId) + const method = String(request.method || '') + const params = + request.params && typeof request.params === 'object' && !Array.isArray(request.params) + ? (request.params as Record) + : {} + return manager().pageRequest(extensionId, method, params) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.openDataDir, + guard(async (extensionId: unknown): Promise<{ success: boolean; error?: string }> => { + const id = requireId(extensionId) + const directory = paths.extensionDataDir(id) + fs.ensureDirSync(directory) + const error = await shell.openPath(directory) + return error ? { success: false, error } : { success: true } + }) + ) +} + +function requireId(value: unknown): string { + const id = String(value || '').trim() + if (!/^[a-z0-9.-]{3,128}$/.test(id)) throw new Error('扩展 id 不合法') + return id +} + +function requirePath(value: unknown): string { + const target = String(value || '').trim() + if (!target || target.length > 4_096) throw new Error('路径不合法') + if (!path.isAbsolute(target)) throw new Error('必须使用绝对路径') + return target +} diff --git a/src/main/extensions/extension-log.ts b/src/main/extensions/extension-log.ts new file mode 100644 index 0000000..b56b610 --- /dev/null +++ b/src/main/extensions/extension-log.ts @@ -0,0 +1,125 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { randomUUID } from 'node:crypto' +import type { ExtensionLogEntry } from '../../shared/extensions/types' + +const MAX_ENTRIES_PER_EXTENSION = 200 +const MAX_MESSAGE_LENGTH = 500 +const MAX_FILE_BYTES = 256 * 1024 + +/** + * 扩展日志:内存环形缓冲 + 磁盘 JSONL(超过上限时轮转一份 `.1`)。 + * + * 隐私边界:宿主只记录**生命周期与错误摘要**,不写聊天正文。 + * 扩展主动写入的内容会原样落盘并展示给用户,作者必须自己遵守隐私约定。 + */ +export class ExtensionLogStore { + private readonly logsDir: string + private readonly memory = new Map() + private readonly loaded = new Set() + + constructor(logsDir: string) { + this.logsDir = logsDir + } + + append( + extensionId: string, + level: ExtensionLogEntry['level'], + source: ExtensionLogEntry['source'], + message: string + ): ExtensionLogEntry { + this.ensureLoaded(extensionId) + const entry: ExtensionLogEntry = { + id: randomUUID(), + at: Date.now(), + level, + source, + message: sanitizeMessage(message) + } + const list = this.memory.get(extensionId) ?? [] + list.push(entry) + if (list.length > MAX_ENTRIES_PER_EXTENSION) + list.splice(0, list.length - MAX_ENTRIES_PER_EXTENSION) + this.memory.set(extensionId, list) + this.appendToDisk(extensionId, entry) + return entry + } + + list(extensionId: string, limit = MAX_ENTRIES_PER_EXTENSION): ExtensionLogEntry[] { + this.ensureLoaded(extensionId) + const list = this.memory.get(extensionId) ?? [] + return list.slice(-Math.max(1, Math.min(limit, MAX_ENTRIES_PER_EXTENSION))).reverse() + } + + clear(extensionId: string): void { + this.memory.set(extensionId, []) + this.loaded.add(extensionId) + fs.removeSync(this.filePath(extensionId)) + fs.removeSync(`${this.filePath(extensionId)}.1`) + } + + remove(extensionId: string): void { + this.memory.delete(extensionId) + this.loaded.delete(extensionId) + fs.removeSync(this.filePath(extensionId)) + fs.removeSync(`${this.filePath(extensionId)}.1`) + } + + private filePath(extensionId: string): string { + return path.join(this.logsDir, `${extensionId}.jsonl`) + } + + private ensureLoaded(extensionId: string): void { + if (this.loaded.has(extensionId)) return + this.loaded.add(extensionId) + try { + const text = fs.readFileSync(this.filePath(extensionId), 'utf8') + const lines = text.split('\n').filter(Boolean).slice(-MAX_ENTRIES_PER_EXTENSION) + const entries: ExtensionLogEntry[] = [] + for (const line of lines) { + try { + const raw = JSON.parse(line) as Partial + if (!raw || typeof raw !== 'object') continue + if (typeof raw.message !== 'string') continue + entries.push({ + id: String(raw.id || randomUUID()), + at: Number(raw.at) || 0, + level: raw.level === 'warn' || raw.level === 'error' ? raw.level : 'info', + source: raw.source === 'extension' ? 'extension' : 'core', + message: sanitizeMessage(raw.message) + }) + } catch { + // 单行损坏不影响其余日志。 + } + } + this.memory.set(extensionId, entries) + } catch { + this.memory.set(extensionId, []) + } + } + + private appendToDisk(extensionId: string, entry: ExtensionLogEntry): void { + try { + const filePath = this.filePath(extensionId) + fs.ensureDirSync(path.dirname(filePath)) + const size = fs.statSync(filePath, { throwIfNoEntry: false })?.size ?? 0 + if (size > MAX_FILE_BYTES) fs.moveSync(filePath, `${filePath}.1`, { overwrite: true }) + fs.appendFileSync(filePath, `${JSON.stringify(entry)}\n`, 'utf8') + } catch { + // 日志写不进去不能影响扩展运行。 + } + } +} + +// eslint-disable-next-line no-control-regex -- 终端 ANSI 序列与控制字符要在落盘前剥掉 +const ANSI_PATTERN = /\u001b\[[0-9;]*m/g +// eslint-disable-next-line no-control-regex -- 同上:日志里不允许出现不可见控制字符 +const CONTROL_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g + +function sanitizeMessage(value: unknown): string { + const text = String(value ?? '') + .replace(ANSI_PATTERN, '') + .replace(CONTROL_PATTERN, '') + .trim() + return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text +} diff --git a/src/main/extensions/extension-manager.ts b/src/main/extensions/extension-manager.ts new file mode 100644 index 0000000..c878b6a --- /dev/null +++ b/src/main/extensions/extension-manager.ts @@ -0,0 +1,761 @@ +import fs from 'fs-extra' +import os from 'node:os' +import path from 'node:path' +import { safeStorage } from 'electron' +import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' +import { + autoGrantedPermissions, + hasExtensionPermission, + type ExtensionPermission +} from '../../shared/extensions/permissions' +import { + checkExtensionCompatibility, + parseExtensionManifest, + type ExtensionManifest +} from '../../shared/extensions/manifest' +import type { + ExtensionCapabilitySnapshot, + ExtensionInstallResult, + ExtensionLogEntry, + ExtensionOperationResult, + ExtensionPageDescriptor, + ExtensionPageMethod, + ExtensionPageResponse, + InstalledExtension +} from '../../shared/extensions/types' +import type { + ExtensionAutomationActionOutput, + ExtensionMessagesQueryRequest, + ExtensionQueriedMessage, + ExtensionSendImageRequest, + ExtensionSendTextRequest, + ExtensionSendTextResult, + ExtensionSendVideoRequest +} from '../../shared/extensions/rpc' +import type { PersonalWechatSendCapability } from '../../shared/personal-wechat' +import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action' +import type { NormalizedIncomingMessage } from '../services/message-listener-service' +import { ExtensionActionRegistry } from './extension-action-registry' +import { ExtensionEventBus } from './extension-event-bus' +import type { ExtensionEntitlementResult } from './extension-entitlement' +import { + ExtensionHost, + forkExtensionHost, + type ExtensionHostChild, + type ExtensionHostSpawnOptions +} from './extension-host' +import { ExtensionInstaller } from './extension-installer' +import { ExtensionLogStore } from './extension-log' +import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry' +import { ExtensionSendGateway } from './extension-send-gateway' +import { ExtensionStorage } from './extension-storage' +import type { ExtensionPaths } from './extension-paths' + +export interface ExtensionManagerDependencies { + paths: ExtensionPaths + appVersion: string + platform?: NodeJS.Platform + spawn?: (options: ExtensionHostSpawnOptions) => ExtensionHostChild + getCapability: () => Promise + checkEntitlement: () => Promise + executeAction: (request: WechatActionRequest) => Promise + queryMessages: (request: ExtensionMessagesQueryRequest) => Promise + /** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */ + listGroups: () => Promise> + aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }> + getAccountId: () => string + getSelfUsernames: () => string[] + isDatabaseReady: () => boolean + now?: () => number + onChange?: ( + extensionId: string, + reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions' + ) => void +} + +const PAGE_METHODS: ExtensionPageMethod[] = [ + 'storage.get', + 'storage.set', + 'storage.remove', + 'storage.list', + 'capabilities.get', + 'contacts.listGroups', + 'test.send', + 'douyin.cookie.get', + 'douyin.cookie.set', + 'douyin.cookie.clear', + 'extension.info' +] + +/** + * 扩展系统的编排层。 + * + * 职责边界: + * - **只做编排**:清单读取、安装、启停、进程托管、事件分发、能力转发; + * - 不实现消息监听(复用 `MessageListenerService`)、不实现发送(复用 + * `WechatActionGateway`)、不实现自动化规则存储(复用 `AutomationRuleStore`)。 + * + * 所有扩展代码都在 `ExtensionHost` 的子进程里运行;本类不 `require` 任何扩展文件。 + */ +export class ExtensionManager { + private readonly dependencies: ExtensionManagerDependencies + private readonly paths: ExtensionPaths + private readonly registry: ExtensionRegistry + private readonly installer: ExtensionInstaller + private readonly storage: ExtensionStorage + private readonly logs: ExtensionLogStore + private readonly actions = new ExtensionActionRegistry() + private readonly sendGateway: ExtensionSendGateway + private readonly hosts = new Map() + private readonly manifests = new Map() + private readonly eventBus: ExtensionEventBus + private readonly now: () => number + private initialized = false + + constructor(dependencies: ExtensionManagerDependencies) { + this.dependencies = dependencies + this.paths = dependencies.paths + this.now = dependencies.now ?? (() => Date.now()) + this.registry = new ExtensionRegistry({ registryFile: this.paths.registryFile, now: this.now }) + this.installer = new ExtensionInstaller({ + paths: this.paths, + registry: this.registry, + now: this.now + }) + this.storage = new ExtensionStorage({ dataRoot: this.paths.dataDir }) + this.logs = new ExtensionLogStore(this.paths.logsDir) + this.sendGateway = new ExtensionSendGateway({ + getCapability: dependencies.getCapability, + checkEntitlement: dependencies.checkEntitlement, + executeAction: dependencies.executeAction, + getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId), + now: this.now + }) + this.eventBus = new ExtensionEventBus({ + listSubscribers: () => this.listEventSubscribers(), + getAccountId: dependencies.getAccountId, + getSelfUsernames: dependencies.getSelfUsernames, + now: this.now + }) + } + + /** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */ + async initialize(): Promise { + if (this.initialized) return + this.initialized = true + for (const directory of [ + this.paths.extensionsDir, + this.paths.dataDir, + this.paths.stateDir, + this.paths.logsDir, + this.paths.stagingDir + ]) { + fs.ensureDirSync(directory) + } + this.eventBus.setAccountId(this.dependencies.getAccountId()) + for (const record of this.registry.list()) { + const manifest = this.readManifest(record.id) + if (!manifest) { + this.logs.append(record.id, 'error', 'core', '扩展文件缺失或 manifest 无法读取') + continue + } + this.syncDeclared(record.id, manifest) + if (!record.enabled) continue + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) + if (!compatibility.compatible) { + this.logs.append(record.id, 'error', 'core', compatibility.reason || '扩展不兼容') + continue + } + try { + await this.startHost(record.id, manifest) + } catch (error) { + this.logs.append( + record.id, + 'error', + 'core', + `扩展启动失败:${error instanceof Error ? error.message : String(error)}` + ) + } + } + } + + list(): InstalledExtension[] { + return this.registry + .list() + .map((record) => this.toInstalled(record)) + .sort((left, right) => left.name.localeCompare(right.name)) + } + + get(extensionId: string): InstalledExtension | null { + const record = this.registry.get(extensionId) + if (!record) return null + return this.toInstalled(record) + } + + getLogs(extensionId: string, limit = 100): ExtensionLogEntry[] { + return this.logs.list(extensionId, limit) + } + + clearLogs(extensionId: string): void { + this.logs.clear(extensionId) + } + + async installFromDirectory(directory: string): Promise { + return this.install(() => + this.installer.installFromDirectory(directory, { appVersion: this.dependencies.appVersion }) + ) + } + + async installFromPackage(packagePath: string): Promise { + return this.install(() => + this.installer.installFromPackage(packagePath, { + appVersion: this.dependencies.appVersion, + source: 'package' + }) + ) + } + + async setEnabled(extensionId: string, enabled: boolean): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + const manifest = this.readManifest(extensionId) + if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')) + + if (!enabled) { + await this.stopHost(extensionId) + this.registry.setEnabled(extensionId, false) + this.registry.setGrantedPermissions(extensionId, autoGrantedPermissions(manifest.permissions)) + this.dependencies.onChange?.(extensionId, 'disabled') + return { success: true } + } + + const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion) + if (!compatibility.compatible) { + return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', compatibility.reason)) + } + this.registry.setEnabled(extensionId, true) + this.registry.setGrantedPermissions(extensionId, manifest.permissions) + this.syncDeclared(extensionId, manifest) + if (manifest.entrypoints.background) { + try { + await this.startHost(extensionId, manifest) + } catch { + // 启用状态保留:运行状态会显示为「错误」,用户可以查看日志后重新启用。 + } + } + this.dependencies.onChange?.(extensionId, 'enabled') + return { success: true } + } + + async uninstall(extensionId: string, keepData: boolean): Promise { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + await this.stopHost(extensionId) + this.actions.remove(extensionId) + this.manifests.delete(extensionId) + try { + await this.installer.uninstall(extensionId, { keepData }) + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + if (!keepData) this.logs.remove(extensionId) + this.dependencies.onChange?.(extensionId, 'uninstalled') + return { success: true } + } + + /** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */ + pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor { + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + const manifest = this.readManifest(extensionId) + if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失') + const page = pageId + ? manifest.contributions.pages.find((item) => item.id === pageId) + : manifest.contributions.pages[0] + const entry = page?.entry || manifest.entrypoints.page + if (!entry) throw new ExtensionError('EXTENSION_NOT_FOUND', '扩展没有可打开的页面') + return { + extensionId, + pageId: page?.id || 'main', + title: page?.title || manifest.name, + url: `tm-extension://${extensionId}/${entry}` + } + } + + /** + * 扩展页面可调用的能力。 + * + * 页面**没有**发送 / 查询 / AI 权限:那些能力只从后台进程按权限申请。 + * 页面与后台共享同一个 `storage` 命名空间,所以配置页保存的内容后台能直接读到。 + */ + async pageRequest( + extensionId: string, + method: string, + params: Record = {} + ): Promise { + try { + if (!PAGE_METHODS.includes(method as ExtensionPageMethod)) { + throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`) + } + if (method.startsWith('douyin.cookie.') && extensionId !== 'com.example.douyin-sender') { + throw new ExtensionError('PERMISSION_DENIED', 'Cookie 能力不适用于此扩展') + } + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + const manifest = this.readManifest(extensionId) + if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失') + if (!manifest.permissions.includes('storage') && method.startsWith('storage.')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 storage 权限') + } + if (method === 'contacts.listGroups' && !manifest.permissions.includes('contacts.list')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 contacts.list 权限') + } + switch (method as ExtensionPageMethod) { + case 'storage.get': + return { ok: true, result: this.storage.get(extensionId, params.key) } + case 'storage.set': + this.storage.set(extensionId, params.key, params.value) + return { ok: true, result: { ok: true } } + case 'storage.remove': + return { ok: true, result: { removed: this.storage.remove(extensionId, params.key) } } + case 'storage.list': + return { ok: true, result: { entries: this.storage.list(extensionId) } } + case 'capabilities.get': + return { ok: true, result: await this.buildCapabilitySnapshot(extensionId) } + case 'contacts.listGroups': { + const groups = await this.dependencies.listGroups() + return { + ok: true, + result: { + groups: groups + .filter((group) => group && group.id) + .map((group) => ({ id: group.id, name: group.name || group.id })) + .slice(0, 2_000) + } + } + } + case 'test.send': { + if (extensionId !== 'com.example.douyin-sender') { + throw new ExtensionError('PERMISSION_DENIED', '测试能力不适用于此扩展') + } + const host = this.hosts.get(extensionId) + if (!host) throw new ExtensionError('EXTENSION_DISABLED') + const cookieHeader = String(params.cookieHeader || '') || this.readDouyinCookie() + try { + return { ok: true, result: await host.testSend({ ...params, cookieHeader }) } + } finally { + params.cookieHeader = '' + } + } + case 'douyin.cookie.get': + return { ok: true, result: { configured: Boolean(this.readDouyinCookie()) } } + case 'douyin.cookie.set': { + const value = String(params.cookieHeader || '').trim() + if (!value) throw new ExtensionError('INVALID_REQUEST', 'Cookie 不能为空') + if (!safeStorage.isEncryptionAvailable()) + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '系统安全存储不可用') + fs.writeFileSync( + path.join(this.paths.userData, 'douyin-cookie.bin'), + safeStorage.encryptString(value), + { mode: 0o600 } + ) + fs.chmodSync(path.join(this.paths.userData, 'douyin-cookie.bin'), 0o600) + this.syncDouyinCookieToExtensionData(value) + return { ok: true, result: { configured: true } } + } + case 'douyin.cookie.clear': + this.clearDouyinCookie() + return { ok: true, result: { configured: false } } + case 'extension.info': + return { + ok: true, + result: { + id: manifest.id, + name: manifest.name, + version: manifest.version, + enabled: record.enabled + } + } + default: + throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`) + } + } catch (error) { + return { ok: false, error: toExtensionErrorPayload(error) } + } + } + + handleMessage(message: NormalizedIncomingMessage): void { + this.eventBus.setAccountId(this.dependencies.getAccountId()) + this.eventBus.handleMessage(message) + } + + private syncDouyinCookieToExtensionData(value: string): void { + try { + const dataDir = this.paths.extensionDataDir('com.example.douyin-sender') + fs.ensureDirSync(dataDir) + const target = path.join(dataDir, 'douyin-cookie.txt') + fs.writeFileSync(target, value, { mode: 0o600 }) + fs.chmodSync(target, 0o600) + } catch { + // 扩展数据目录同步失败不影响加密主存储。 + } + } + + private readDouyinCookie(): string { + const file = path.join(this.paths.userData, 'douyin-cookie.bin') + if (fs.existsSync(file) && safeStorage.isEncryptionAvailable()) { + try { + const decrypted = safeStorage.decryptString(fs.readFileSync(file)).trim() + if (decrypted) { + this.syncDouyinCookieToExtensionData(decrypted) + return decrypted + } + } catch { + // 加密文件损坏或不可解密时继续尝试桌面 Cookie 文件。 + } + } + const desktopCookie = path.join(os.homedir(), 'Desktop', 'douyin-cookie') + if (fs.existsSync(desktopCookie)) { + try { + return fs.readFileSync(desktopCookie, 'utf8').trim() + } catch { + return '' + } + } + return '' + } + + private clearDouyinCookie(): void { + try { + fs.removeSync(path.join(this.paths.userData, 'douyin-cookie.bin')) + fs.removeSync( + path.join(this.paths.extensionDataDir('com.example.douyin-sender'), 'douyin-cookie.txt') + ) + } catch { + throw new ExtensionError('INVALID_REQUEST', '无法清除抖音 Cookie') + } + } + + setAccountId(accountId: string): void { + this.eventBus.setAccountId(accountId) + } + + /** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */ + async invokeAutomationAction( + extensionId: string, + actionId: string, + input: Record, + timeoutMs?: number + ): Promise { + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 automation.action 权限') + } + const host = this.hosts.get(extensionId) + if (!host) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE') + if (!this.actions.isRegistered(extensionId, actionId)) { + throw new ExtensionError('ACTION_FAILED', '扩展没有注册该动作') + } + return host.invokeAction(actionId, input, timeoutMs) + } + + getActions(): ReturnType { + return this.actions.list() + } + + async dispose(): Promise { + const ids = Array.from(this.hosts.keys()) + await Promise.all(ids.map((id) => this.stopHost(id))) + } + + private async install( + run: () => Promise<{ manifest: ExtensionManifest; upgraded: boolean; previousVersion?: string }> + ): Promise { + let outcome: Awaited> + try { + outcome = await run() + } catch (error) { + return { success: false, error: toExtensionErrorPayload(error) } + } + const { manifest } = outcome + const wasEnabled = this.registry.get(manifest.id)?.enabled === true + if (wasEnabled) await this.stopHost(manifest.id) + this.manifests.delete(manifest.id) + this.manifests.set(manifest.id, manifest) + this.syncDeclared(manifest.id, manifest) + // 新安装只自动授予低风险权限;升级保留用户已经授予的集合。 + if (!outcome.upgraded) { + this.registry.setGrantedPermissions(manifest.id, autoGrantedPermissions(manifest.permissions)) + } + this.logs.append( + manifest.id, + 'info', + 'core', + outcome.upgraded + ? `扩展已更新:${outcome.previousVersion ?? '?'} → ${manifest.version}` + : `扩展已安装:${manifest.version}` + ) + this.dependencies.onChange?.(manifest.id, 'installed') + if (wasEnabled && manifest.entrypoints.background) { + await this.startHost(manifest.id, manifest).catch(() => undefined) + } + const installed = this.get(manifest.id) + return { success: true, ...(installed ? { extension: installed } : {}) } + } + + private async startHost(extensionId: string, manifest: ExtensionManifest): Promise { + if (!manifest.entrypoints.background) return + await this.stopHost(extensionId) + const host = new ExtensionHost({ + extensionId, + extensionDir: this.paths.installDir(extensionId), + dataDir: this.paths.extensionDataDir(extensionId), + permissions: this.registry.get(extensionId)?.grantedPermissions ?? [], + storage: this.storage, + spawn: this.dependencies.spawn ?? this.defaultSpawn(), + onLog: (level, message) => { + this.logs.append(extensionId, level, 'core', message) + if (level === 'error') this.dependencies.onChange?.(extensionId, 'runtime') + }, + onStateChange: () => this.dependencies.onChange?.(extensionId, 'runtime'), + onActionsChanged: () => { + this.syncRegisteredActions(extensionId, manifest.name) + this.dependencies.onChange?.(extensionId, 'actions') + }, + queryMessages: (id, request) => this.queryMessages(id, request), + sendText: (id, request) => this.sendText(id, request), + sendImage: (id, request) => this.sendImage(id, request), + sendVideo: (id, request) => this.sendVideo(id, request), + aiChat: (_id, messages) => this.dependencies.aiChat(messages), + capabilities: (id) => this.buildCapabilitySnapshot(id) + }) + this.hosts.set(extensionId, host) + await host.start() + } + + private async stopHost(extensionId: string): Promise { + const host = this.hosts.get(extensionId) + if (!host) return + this.hosts.delete(extensionId) + await host.stop() + this.actions.removeRuntime(extensionId) + } + + private defaultSpawn(): (options: ExtensionHostSpawnOptions) => ExtensionHostChild { + // electron-vite 把主进程入口输出到 out/main,扩展宿主脚本与它同级。 + return forkExtensionHost(path.join(__dirname, 'extensionHost.js')) + } + + private syncDeclared(extensionId: string, manifest: ExtensionManifest): void { + this.actions.setDeclared(extensionId, manifest.name, manifest.contributions.automationActions) + } + + private syncRegisteredActions(extensionId: string, extensionName: string): void { + const host = this.hosts.get(extensionId) + this.actions.setRegistered(extensionId, extensionName, host?.registeredActions() ?? []) + } + + private listEventSubscribers(): Array<{ + extensionId: string + subscriptions: ExtensionManifest['subscriptions'] + deliver: ( + envelope: Parameters[0] extends never + ? never + : import('../../shared/extensions/events').ExtensionEventEnvelope + ) => boolean + }> { + const subscribers: Array<{ + extensionId: string + subscriptions: ExtensionManifest['subscriptions'] + deliver: ( + envelope: import('../../shared/extensions/events').ExtensionEventEnvelope + ) => boolean + }> = [] + for (const [extensionId, host] of this.hosts) { + const record = this.registry.get(extensionId) + const manifest = this.manifests.get(extensionId) + if (!record?.enabled || !manifest) continue + if (!hasExtensionPermission(record.grantedPermissions, 'messages.subscribe')) continue + if (host.snapshot().state !== 'active') continue + subscribers.push({ + extensionId, + subscriptions: manifest.subscriptions, + deliver: (envelope) => host.deliverEvent(envelope) + }) + } + return subscribers + } + + private async queryMessages( + extensionId: string, + request: ExtensionMessagesQueryRequest + ): Promise { + if (!this.dependencies.isDatabaseReady()) { + throw new ExtensionError('DATABASE_NOT_READY') + } + const conversationId = String(request?.conversationId || '').trim() + if (!conversationId || conversationId.length > 128) { + throw new ExtensionError('INVALID_REQUEST', '会话 id 不合法') + } + const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 200)) + const startTime = Number.isFinite(Number(request?.startTime)) + ? Number(request.startTime) + : Date.now() - 24 * 60 * 60 * 1000 + const endTime = Number.isFinite(Number(request?.endTime)) ? Number(request.endTime) : Date.now() + if (endTime <= startTime) throw new ExtensionError('INVALID_REQUEST', '时间范围不合法') + if (endTime - startTime > 7 * 24 * 60 * 60 * 1000) { + throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 7 天') + } + const record = this.registry.get(extensionId) + if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED') + return this.dependencies.queryMessages({ + conversationId, + startTime, + endTime, + limit + }) + } + + private async sendText( + extensionId: string, + request: ExtensionSendTextRequest + ): Promise { + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + const manifest = this.manifests.get(extensionId) + return this.sendGateway.sendText( + { + extensionId, + permissions: record.grantedPermissions, + conversationScope: manifest?.subscriptions?.conversationIds ?? [] + }, + request + ) + } + + private async sendImage( + extensionId: string, + request: ExtensionSendImageRequest + ): Promise { + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + const manifest = this.manifests.get(extensionId) + return this.sendGateway.sendImage( + { + extensionId, + permissions: record.grantedPermissions, + conversationScope: manifest?.subscriptions?.conversationIds ?? [] + }, + request + ) + } + + private async sendVideo( + extensionId: string, + request: ExtensionSendVideoRequest + ): Promise { + const record = this.registry.get(extensionId) + if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND') + if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED') + const manifest = this.manifests.get(extensionId) + return this.sendGateway.sendVideo( + { + extensionId, + permissions: record.grantedPermissions, + conversationScope: manifest?.subscriptions?.conversationIds ?? [] + }, + request + ) + } + + private async buildCapabilitySnapshot(extensionId: string): Promise { + const record = this.registry.get(extensionId) + const granted = record?.grantedPermissions ?? [] + const capability = await this.dependencies.getCapability().catch(() => null) + let licensed = false + if (hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text')) { + const entitlement = await this.dependencies.checkEntitlement().catch(() => null) + licensed = entitlement?.ok === true + } + return { + extensionId, + enabled: record?.enabled === true, + permissions: [...granted], + platform: this.dependencies.platform ?? process.platform, + databaseReady: this.dependencies.isDatabaseReady(), + send: { + supported: Boolean(capability?.supported), + ready: Boolean(capability?.ready), + canSendText: Boolean(capability?.capabilities?.text), + canSendImage: Boolean(capability?.capabilities?.image), + canSendVideo: Boolean(capability?.capabilities?.video), + licensed, + message: capability?.message || '暂时无法获知微信发送能力' + }, + ai: { + configured: false, + modelName: '' + } + } + } + + private toInstalled(record: ExtensionRegistryRecord): InstalledExtension { + const manifest = this.readManifest(record.id) + const compatibility = manifest + ? checkExtensionCompatibility(manifest, this.dependencies.appVersion) + : { compatible: false, code: 'manifest' as const, reason: '扩展文件缺失或 manifest 无法读取' } + const host = this.hosts.get(record.id) + const runtime = host + ? host.snapshot() + : { + state: record.enabled ? ('active' as const) : ('inactive' as const), + since: record.updatedAt, + restarts: 0 + } + return { + id: record.id, + name: manifest?.name || record.id, + version: manifest?.version || record.version, + apiVersion: manifest?.apiVersion || record.apiVersion, + ...(manifest?.minAppVersion ? { minAppVersion: manifest.minAppVersion } : {}), + ...(manifest?.description ? { description: manifest.description } : {}), + ...(manifest?.author ? { author: manifest.author } : {}), + enabled: record.enabled, + installedAt: record.installedAt, + updatedAt: record.updatedAt, + compatibility, + permissions: manifest?.permissions ?? [], + grantedPermissions: record.grantedPermissions, + runtime, + pages: (manifest?.contributions.pages ?? []).map((page) => ({ + id: page.id, + title: page.title + })), + automationActions: this.actions.summariesFor(record.id), + filesPresent: Boolean(manifest) + } + } + + private readManifest(extensionId: string): ExtensionManifest | null { + if (this.manifests.has(extensionId)) return this.manifests.get(extensionId) ?? null + const file = path.join(this.paths.installDir(extensionId), 'manifest.json') + let manifest: ExtensionManifest | null = null + try { + const parsed = parseExtensionManifest(fs.readJsonSync(file) as unknown) + manifest = parsed.ok ? (parsed.manifest ?? null) : null + } catch { + manifest = null + } + this.manifests.set(extensionId, manifest) + return manifest + } +} + +function failure(error: unknown): ExtensionOperationResult { + const payload = toExtensionErrorPayload(error) + return { success: false, error: payload } +} diff --git a/src/main/extensions/extension-paths.ts b/src/main/extensions/extension-paths.ts new file mode 100644 index 0000000..99a4259 --- /dev/null +++ b/src/main/extensions/extension-paths.ts @@ -0,0 +1,65 @@ +import path from 'node:path' +import { app } from 'electron' + +/** + * 扩展相关目录的唯一解析器。 + * + * **所有扩展文件都在 `userData` 下**,与安装目录 / `app.asar` / 源码树完全分离: + * 官方升级只替换应用本体,不会碰这三个目录。Windows 与 macOS 的差异由 + * `app.getPath('userData')` 吸收,调用方不假设任何绝对路径。 + * + * ```text + * /extensions// 扩展代码(manifest + ui + background) + * /extensions-data// 扩展私有数据(配置、缓存) + * /extensions-state/ 宿主状态(registry、日志) + * /extensions-staging/ 安装临时目录(成功后原子改名,不留半装状态) + * ``` + */ +export interface ExtensionPaths { + userData: string + extensionsDir: string + dataDir: string + stateDir: string + stagingDir: string + registryFile: string + logsDir: string + installDir: (extensionId: string) => string + extensionDataDir: (extensionId: string) => string + logFile: (extensionId: string) => string + stagingPath: (prefix: string) => string +} + +export function createExtensionPaths(userData: string): ExtensionPaths { + const extensionsDir = path.join(userData, 'extensions') + const dataDir = path.join(userData, 'extensions-data') + const stateDir = path.join(userData, 'extensions-state') + const stagingDir = path.join(userData, 'extensions-staging') + const logsDir = path.join(stateDir, 'logs') + return { + userData, + extensionsDir, + dataDir, + stateDir, + stagingDir, + registryFile: path.join(stateDir, 'registry.json'), + logsDir, + installDir: (extensionId) => path.join(extensionsDir, extensionId), + extensionDataDir: (extensionId) => path.join(dataDir, extensionId), + logFile: (extensionId) => path.join(logsDir, `${extensionId}.jsonl`), + stagingPath: (prefix) => path.join(stagingDir, `${prefix}-${Date.now().toString(36)}`) + } +} + +let cached: ExtensionPaths | null = null + +/** 懒解析:`app.getPath` 必须在 app ready 之后才可靠。 */ +export function getExtensionPaths(): ExtensionPaths { + if (!cached) cached = createExtensionPaths(app.getPath('userData')) + return cached +} + +/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */ +export function isPathInside(parent: string, child: string): boolean { + const relative = path.relative(path.resolve(parent), path.resolve(child)) + return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative)) +} diff --git a/src/main/extensions/extension-protocol.ts b/src/main/extensions/extension-protocol.ts new file mode 100644 index 0000000..b5025e7 --- /dev/null +++ b/src/main/extensions/extension-protocol.ts @@ -0,0 +1,101 @@ +import { promises as fs } from 'node:fs' +import path from 'node:path' +import { protocol } from 'electron' +import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest' +import { isPathInside, type ExtensionPaths } from './extension-paths' + +export const EXTENSION_SCHEME = 'tm-extension' + +const MIME_TYPES: Record = { + '.html': 'text/html; charset=utf-8', + '.htm': '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', + '.txt': 'text/plain; charset=utf-8', + '.svg': 'image/svg+xml', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.woff': 'font/woff', + '.woff2': 'font/woff2', + '.wasm': 'application/wasm' +} + +/** + * 扩展页面协议:只接受 `tm-extension:///`,realpath 必须仍在 + * 扩展目录内;响应带严格 CSP(无外链、无内联脚本、无网络)。 + * + * `registerSchemesAsPrivileged` 必须在 app ready 前调用。 + */ +export function registerExtensionScheme(): void { + protocol.registerSchemesAsPrivileged([ + { + scheme: EXTENSION_SCHEME, + privileges: { + standard: true, + secure: true, + supportFetchAPI: true, + corsEnabled: false, + stream: true + } + } + ]) +} + +export function installExtensionProtocolHandler(paths: ExtensionPaths): void { + protocol.handle(EXTENSION_SCHEME, async (request) => { + try { + const url = new URL(request.url) + const extensionId = url.hostname.toLowerCase() + if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return notFound() + const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') + if (!isSafeRelativeEntryPath(relative)) return notFound() + + const root = paths.installDir(extensionId) + const resolved = path.resolve(root, relative) + if (!isPathInside(root, resolved)) return notFound() + const realRoot = await fs.realpath(root).catch(() => null) + const realFile = await fs.realpath(resolved).catch(() => null) + if (!realRoot || !realFile) return notFound() + if (!isPathInside(realRoot, realFile)) return notFound() + + const stat = await fs.stat(realFile) + if (!stat.isFile() || stat.size > 20 * 1024 * 1024) return notFound() + const body = await fs.readFile(realFile) + const contentType = + MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream' + return new Response(body, { + status: 200, + headers: { + 'Content-Type': contentType, + 'Content-Security-Policy': [ + "default-src 'self'", + "script-src 'self'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data:", + "font-src 'self' data:", + "connect-src 'none'", + "object-src 'none'", + "base-uri 'none'", + "form-action 'none'" + ].join('; '), + 'X-Content-Type-Options': 'nosniff', + 'Cache-Control': 'no-store' + } + }) + } catch { + return notFound() + } + }) +} + +function notFound(): Response { + return new Response('Not found', { + status: 404, + headers: { 'Content-Type': 'text/plain; charset=utf-8' } + }) +} diff --git a/src/main/extensions/extension-registry.ts b/src/main/extensions/extension-registry.ts new file mode 100644 index 0000000..4a6bb99 --- /dev/null +++ b/src/main/extensions/extension-registry.ts @@ -0,0 +1,155 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { + normalizeExtensionPermissions, + type ExtensionPermission +} from '../../shared/extensions/permissions' +import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest' + +/** + * 宿主侧的扩展安装状态。 + * + * **manifest 不是状态的一部分**:它以扩展目录里的 `manifest.json` 为准, + * 升级扩展只替换目录、不动这里的启用状态与权限授予。 + */ +export interface ExtensionRegistryRecord { + id: string + version: string + apiVersion: string + enabled: boolean + grantedPermissions: ExtensionPermission[] + installedAt: number + updatedAt: number + source: 'directory' | 'package' +} + +interface RegistryFile { + version: number + extensions: ExtensionRegistryRecord[] +} + +const REGISTRY_VERSION = 1 + +function normalizeRecord(value: unknown): ExtensionRegistryRecord | null { + if (!value || typeof value !== 'object') return null + const raw = value as Partial + const id = String(raw.id || '').trim() + if (!id) return null + const installedAt = Number(raw.installedAt) || 0 + return { + id, + version: String(raw.version || '0.0.0'), + apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION), + // 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。 + enabled: raw.enabled === true, + grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions), + installedAt, + updatedAt: Number(raw.updatedAt) || installedAt, + source: raw.source === 'package' ? 'package' : 'directory' + } +} + +export interface ExtensionRegistryDependencies { + registryFile: string + now?: () => number +} + +export class ExtensionRegistry { + private readonly registryFile: string + private readonly now: () => number + private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] } + private loaded = false + + constructor(dependencies: ExtensionRegistryDependencies) { + this.registryFile = dependencies.registryFile + this.now = dependencies.now ?? (() => Date.now()) + } + + list(): ExtensionRegistryRecord[] { + this.ensureLoaded() + return this.state.extensions.map((record) => ({ + ...record, + grantedPermissions: [...record.grantedPermissions] + })) + } + + get(id: string): ExtensionRegistryRecord | undefined { + const key = String(id || '').trim() + if (!key) return undefined + return this.list().find((record) => record.id === key) + } + + upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord { + this.ensureLoaded() + const exists = this.state.extensions.some((item) => item.id === record.id) + const next = exists + ? this.state.extensions.map((item) => (item.id === record.id ? record : item)) + : [...this.state.extensions, record] + this.commit(next) + return { ...record, grantedPermissions: [...record.grantedPermissions] } + } + + remove(id: string): boolean { + this.ensureLoaded() + const next = this.state.extensions.filter((item) => item.id !== id) + if (next.length === this.state.extensions.length) return false + this.commit(next) + return true + } + + setEnabled(id: string, enabled: boolean): ExtensionRegistryRecord | undefined { + const current = this.get(id) + if (!current) return undefined + return this.upsert({ ...current, enabled, updatedAt: this.now() }) + } + + setGrantedPermissions( + id: string, + permissions: ExtensionPermission[] + ): ExtensionRegistryRecord | undefined { + const current = this.get(id) + if (!current) return undefined + return this.upsert({ + ...current, + grantedPermissions: normalizeExtensionPermissions(permissions), + updatedAt: this.now() + }) + } + + private ensureLoaded(): void { + if (this.loaded) return + this.loaded = true + try { + const raw = fs.readJsonSync(this.registryFile) as unknown + if (!raw || typeof raw !== 'object') return + const list = (raw as { extensions?: unknown }).extensions + if (!Array.isArray(list)) return + this.state = { + version: REGISTRY_VERSION, + extensions: list + .map((item) => normalizeRecord(item)) + .filter((item): item is ExtensionRegistryRecord => item !== null) + } + } catch { + // 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。 + } + } + + private commit(extensions: ExtensionRegistryRecord[]): void { + const previous = this.state + this.state = { version: REGISTRY_VERSION, extensions } + try { + this.persist() + } catch (error) { + this.state = previous + throw error + } + } + + private persist(): void { + fs.ensureDirSync(path.dirname(this.registryFile)) + const temporary = `${this.registryFile}.tmp` + fs.writeJsonSync(temporary, this.state, { spaces: 2 }) + fs.moveSync(temporary, this.registryFile, { overwrite: true }) + } +} diff --git a/src/main/extensions/extension-send-gateway.ts b/src/main/extensions/extension-send-gateway.ts new file mode 100644 index 0000000..90317ab --- /dev/null +++ b/src/main/extensions/extension-send-gateway.ts @@ -0,0 +1,358 @@ +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { ExtensionError } from '../../shared/extensions/errors' +import { + hasExtensionPermission, + type ExtensionPermission +} from '../../shared/extensions/permissions' +import type { + ExtensionSendImageRequest, + ExtensionSendTextRequest, + ExtensionSendTextResult, + ExtensionSendVideoRequest +} from '../../shared/extensions/rpc' +import type { PersonalWechatSendCapability } from '../../shared/personal-wechat' +import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action' +import type { ExtensionEntitlementResult } from './extension-entitlement' +import { isPathInside } from './extension-paths' + +const MAX_TEXT_LENGTH = 2_000 +const MAX_RECIPIENT_LENGTH = 128 +const MAX_MEDIA_BYTES = 100 * 1024 * 1024 +const SEND_INTERVAL_MS = 2_000 +const SEND_WINDOW_MS = 60_000 +const SEND_WINDOW_LIMIT = 10 +/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */ +const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp']) +const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v']) + +export interface ExtensionSendContext { + extensionId: string + permissions: ExtensionPermission[] + /** manifest 声明的会话范围;空数组表示不限制。 */ + conversationScope: string[] +} + +export interface ExtensionSendGatewayDependencies { + getCapability: () => Promise + checkEntitlement: () => Promise + executeAction: (request: WechatActionRequest) => Promise + /** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */ + getExtensionDataRoot?: (extensionId: string) => string + now?: () => number +} + +/** + * 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。 + * + * origin、purpose、triggerType、幂等键全部由宿主填写,扩展只描述 + * 「发给谁、发什么」。 + */ +export class ExtensionSendGateway { + private readonly getCapability: () => Promise + private readonly checkEntitlement: () => Promise + private readonly executeAction: (request: WechatActionRequest) => Promise + private readonly getExtensionDataRoot: (extensionId: string) => string + private readonly now: () => number + private readonly sendHistory = new Map() + + constructor(dependencies: ExtensionSendGatewayDependencies) { + this.getCapability = dependencies.getCapability + this.checkEntitlement = dependencies.checkEntitlement + this.executeAction = dependencies.executeAction + this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '') + this.now = dependencies.now ?? (() => Date.now()) + } + + async sendText( + context: ExtensionSendContext, + request: ExtensionSendTextRequest + ): Promise { + if (!hasExtensionPermission(context.permissions, 'wechat.send.text')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.text 权限') + } + const to = String(request?.to || '').trim() + const text = String(request?.text || '').trim() + if (!to || to.length > MAX_RECIPIENT_LENGTH) { + throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法') + } + if (!text || text.length > MAX_TEXT_LENGTH) { + throw new ExtensionError('INVALID_REQUEST', '发送内容不能为空且不能超过 2000 字') + } + if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) { + throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围') + } + const at = normalizeAt(request?.at, to) + this.assertRateLimit(context.extensionId) + + const capability = await this.getCapability().catch(() => null) + if (!capability || !capability.supported) { + throw new ExtensionError( + 'SEND_NOT_SUPPORTED', + capability?.message || '当前环境不支持微信发送' + ) + } + if (!capability.ready || !capability.capabilities?.text) { + throw new ExtensionError( + 'CAPABILITY_UNAVAILABLE', + capability.message || '个人微信发送能力尚未就绪' + ) + } + + const entitlement = await this.checkEntitlement() + if (!entitlement.ok) { + throw new ExtensionError('LICENSE_REQUIRED', entitlement.message) + } + + const result = await this.executeAction({ + ...(request.dedupeKey + ? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) } + : {}), + origin: 'extension', + purpose: 'extension_send', + triggerType: 'automation', + recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to }, + content: { type: 'text', text, ...(at ? { at } : {}) }, + metadata: { extensionId: context.extensionId } + }) + + if (result.status === 'sent') { + return { actionId: result.actionId, status: 'sent' } + } + throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败') + } + + /** + * 发送图片。 + * + * 文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件, + * 否则扩展就能借 TraceMemo 把本机任意文件发出去。 + */ + async sendImage( + context: ExtensionSendContext, + request: ExtensionSendImageRequest + ): Promise { + if (!hasExtensionPermission(context.permissions, 'wechat.send.image')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.image 权限') + } + const to = String(request?.to || '').trim() + if (!to || to.length > MAX_RECIPIENT_LENGTH) { + throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法') + } + if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) { + throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围') + } + const mediaPath = assertSendableMediaPath( + request?.path, + this.getExtensionDataRoot(context.extensionId), + IMAGE_EXTENSIONS + ) + this.assertRateLimit(context.extensionId) + + const capability = await this.getCapability().catch(() => null) + if (!capability || !capability.supported) { + throw new ExtensionError( + 'SEND_NOT_SUPPORTED', + capability?.message || '当前环境不支持微信发送' + ) + } + if (!capability.ready || !capability.capabilities?.image) { + throw new ExtensionError( + 'CAPABILITY_UNAVAILABLE', + capability.message || '个人微信发送能力尚未就绪' + ) + } + + const entitlement = await this.checkEntitlement() + if (!entitlement.ok) { + throw new ExtensionError('LICENSE_REQUIRED', entitlement.message) + } + + const result = await this.executeAction({ + ...(request.dedupeKey + ? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) } + : {}), + origin: 'extension', + purpose: 'extension_send', + triggerType: 'automation', + recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to }, + content: { type: 'image', path: mediaPath }, + metadata: { extensionId: context.extensionId } + }) + + if (result.status === 'sent') { + return { actionId: result.actionId, status: 'sent' } + } + throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败') + } + + /** + * 发送视频。 + * + * 与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。 + * 文件边界与图片相同(扩展数据目录 / 临时目录、普通文件、≤ 100MB)。 + */ + async sendVideo( + context: ExtensionSendContext, + request: ExtensionSendVideoRequest + ): Promise { + if (!hasExtensionPermission(context.permissions, 'wechat.send.video')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.video 权限') + } + const to = String(request?.to || '').trim() + if (!to || to.length > MAX_RECIPIENT_LENGTH) { + throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法') + } + if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) { + throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围') + } + const mediaPath = assertSendableMediaPath( + request?.path, + this.getExtensionDataRoot(context.extensionId), + VIDEO_EXTENSIONS + ) + this.assertRateLimit(context.extensionId) + + const capability = await this.getCapability().catch(() => null) + if (!capability || !capability.supported) { + throw new ExtensionError( + 'SEND_NOT_SUPPORTED', + capability?.message || '当前环境不支持微信发送' + ) + } + if (!capability.ready || !capability.capabilities?.video) { + throw new ExtensionError( + 'CAPABILITY_UNAVAILABLE', + capability.message || '当前微信发送能力不支持视频' + ) + } + + const entitlement = await this.checkEntitlement() + if (!entitlement.ok) { + throw new ExtensionError('LICENSE_REQUIRED', entitlement.message) + } + + const result = await this.executeAction({ + ...(request.dedupeKey + ? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) } + : {}), + origin: 'extension', + purpose: 'extension_send', + triggerType: 'automation', + recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to }, + content: { type: 'video', path: mediaPath }, + metadata: { extensionId: context.extensionId } + }) + + if (result.status === 'sent') { + return { actionId: result.actionId, status: 'sent' } + } + throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败') + } + + /** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */ + private assertRateLimit(extensionId: string): void { + const now = this.now() + const history = (this.sendHistory.get(extensionId) ?? []).filter( + (timestamp) => now - timestamp < SEND_WINDOW_MS + ) + const last = history[history.length - 1] + if (last !== undefined && now - last < SEND_INTERVAL_MS) { + throw new ExtensionError('RATE_LIMITED', '发送过于频繁,请稍后再试') + } + if (history.length >= SEND_WINDOW_LIMIT) { + throw new ExtensionError('RATE_LIMITED', '已达到每分钟发送上限') + } + history.push(now) + this.sendHistory.set(extensionId, history) + } +} + +/** + * 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件。 + * + * 用 realpath 复核,符号链接跳到目录外同样会被拒绝;这一层不能省, + * 否则 `wechat.send.image` 就等价于「读取并外发任意本机文件」。 + */ +function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set): string { + const raw = String(value ?? '').trim() + if (!raw || raw.length > 4_096) { + throw new ExtensionError('INVALID_REQUEST', '媒体路径不合法') + } + if (!path.isAbsolute(raw)) { + throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是绝对路径') + } + let realPath: string + try { + realPath = fs.realpathSync(raw) + } catch { + throw new ExtensionError('INVALID_REQUEST', '媒体文件不存在') + } + const stat = fs.statSync(realPath) + if (!stat.isFile()) { + throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是普通文件') + } + if (stat.size <= 0 || stat.size > MAX_MEDIA_BYTES) { + throw new ExtensionError('INVALID_REQUEST', '媒体文件为空或超过 100MB') + } + const extension = path.extname(realPath).toLowerCase() + if (!allowed.has(extension)) { + throw new ExtensionError('SEND_NOT_SUPPORTED', `不支持发送 ${extension || '无扩展名'} 文件`) + } + const roots = [dataRoot, os.tmpdir()] + .filter(Boolean) + .map((root) => { + try { + return fs.realpathSync(root) + } catch { + return '' + } + }) + .filter(Boolean) + if (!roots.some((root) => isPathInside(root, realPath))) { + throw new ExtensionError('PERMISSION_DENIED', '只能发送扩展数据目录或临时目录中的文件') + } + return realPath +} + +function normalizeAt(value: unknown, recipientId: string): Record | undefined { + if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined + if (!recipientId.endsWith('@chatroom')) return undefined + const entries = Object.entries(value as Record) + if (!entries.length || entries.length > 50) return undefined + const result: Record = {} + for (const [wxid, name] of entries) { + const key = String(wxid).trim() + if (!key || typeof name !== 'string' || !name.trim()) continue + result[key] = name.trim() + } + return Object.keys(result).length ? result : undefined +} + +/** 扩展提供的去重键只作为后缀,前缀固定,避免与官方自动化幂等键串台。 */ +export function extensionIdempotencyKey(extensionId: string, dedupeKey: string): string { + const digest = createHash('sha1') + .update(`${extensionId}\u0001${String(dedupeKey).trim()}`) + .digest('hex') + return `extension:${extensionId}:${digest}` +} + +function mapGatewayError( + code: string | undefined +): 'CAPABILITY_UNAVAILABLE' | 'PERMISSION_DENIED' | 'ACTION_FAILED' | 'INVALID_REQUEST' { + switch (code) { + case 'SEND_CAPABILITY_UNAVAILABLE': + case 'SEND_NOT_READY': + return 'CAPABILITY_UNAVAILABLE' + case 'ACTION_NOT_ALLOWED': + case 'RECIPIENT_SCOPE_VIOLATION': + return 'PERMISSION_DENIED' + case 'INVALID_REQUEST': + case 'INVALID_RECIPIENT': + return 'INVALID_REQUEST' + default: + return 'ACTION_FAILED' + } +} diff --git a/src/main/extensions/extension-service.ts b/src/main/extensions/extension-service.ts new file mode 100644 index 0000000..67b48ae --- /dev/null +++ b/src/main/extensions/extension-service.ts @@ -0,0 +1,128 @@ +import { AIProviderService } from '../services/ai-provider-service' +import { + getChatDb, + getSelfAccountInfo, + isReady, + listContacts, + listMessagesAsync, + resolveMd5 +} from '../services/chat-service' +import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service' +import { wechatActionGateway } from '../services/wechat-action-gateway' +import { ExtensionError } from '../../shared/extensions/errors' +import type { + ExtensionMessagesQueryRequest, + ExtensionQueriedMessage +} from '../../shared/extensions/rpc' +import { checkExtensionSendEntitlement } from './extension-entitlement' +import { ExtensionManager } from './extension-manager' +import { getExtensionPaths } from './extension-paths' + +let manager: ExtensionManager | null = null + +export interface ExtensionSystemOptions { + appVersion: string + onChange: (extensionId: string, reason: string) => void +} + +/** + * 扩展系统的主进程接线。 + * + * 这里只做依赖注入:所有能力都来自既有服务,扩展系统自己不实现第二套 + * 消息监听、发送通道或 AI Provider。 + */ +export async function initExtensionSystem(options: ExtensionSystemOptions): Promise { + if (manager) return + manager = new ExtensionManager({ + paths: getExtensionPaths(), + appVersion: options.appVersion, + getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(), + checkEntitlement: () => checkExtensionSendEntitlement(), + executeAction: (request) => wechatActionGateway.execute(request), + queryMessages: queryConversationMessages, + listGroups: async () => { + try { + return listContacts() + .filter((contact) => contact.type === 'group') + .map((contact) => ({ + id: contact.m_nsUsrName, + name: contact.m_nsNickName || contact.m_nsUsrName + })) + } catch { + return [] + } + }, + aiChat: chatWithConfiguredProvider, + getAccountId: () => String(getSelfAccountInfo()?.wxid || ''), + getSelfUsernames: () => { + try { + return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean) + } catch { + return [] + } + }, + isDatabaseReady: () => { + try { + return isReady() + } catch { + return false + } + }, + onChange: (extensionId, reason) => options.onChange(extensionId, reason) + }) + await manager.initialize() +} + +export function getExtensionManager(): ExtensionManager { + if (!manager) throw new Error('扩展系统尚未初始化') + return manager +} + +export function hasExtensionManager(): boolean { + return manager !== null +} + +export async function disposeExtensionSystem(): Promise { + const current = manager + manager = null + if (current) await current.dispose() +} + +async function queryConversationMessages( + request: ExtensionMessagesQueryRequest +): Promise { + const contact = resolveMd5(request.conversationId) + if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接') + const messages = await listMessagesAsync( + contact.md5, + Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000), + Math.floor((request.endTime ?? Date.now()) / 1000), + { limit: request.limit ?? 50 }, + '', + 'unknown' + ) + return messages.map((message) => ({ + messageId: message.serverId || String(message.localId ?? message.id), + conversationId: request.conversationId, + ...(message.senderId ? { senderId: message.senderId } : {}), + ...(message.name ? { senderName: message.name } : {}), + isSelf: message.isSender === true, + type: message.type, + ...(message.type === 'text' ? { text: message.content } : {}), + timestamp: Math.round((message.createTime ?? 0) * 1000) + })) +} + +async function chatWithConfiguredProvider( + messages: Array<{ role: string; content: string }> +): Promise<{ text: string }> { + const result = await new AIProviderService().chat(messages) + if (!result.success) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 调用失败') + } + return { text: result.data || '' } +} + +export function extensionManagerForTests(value: ExtensionManager | null): void { + manager = value +} diff --git a/src/main/extensions/extension-storage.ts b/src/main/extensions/extension-storage.ts new file mode 100644 index 0000000..1919073 --- /dev/null +++ b/src/main/extensions/extension-storage.ts @@ -0,0 +1,142 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { ExtensionError } from '../../shared/extensions/errors' + +const STORAGE_FILE = 'storage.json' +const STORAGE_VERSION = 1 +const MAX_KEY_LENGTH = 64 +const MAX_VALUE_BYTES = 256 * 1024 +const MAX_TOTAL_BYTES = 1024 * 1024 +const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/ + +interface StorageFile { + version: number + values: Record +} + +export interface ExtensionStorageDependencies { + /** 通常是 `/extensions-data`。 */ + dataRoot: string + maxTotalBytes?: number + maxValueBytes?: number +} + +/** + * 扩展私有的键值存储。 + * + * 边界: + * - 每个扩展一个独立目录,键空间互不可见; + * - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**; + * - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。 + */ +export class ExtensionStorage { + private readonly dataRoot: string + private readonly maxTotalBytes: number + private readonly maxValueBytes: number + + constructor(dependencies: ExtensionStorageDependencies) { + this.dataRoot = dependencies.dataRoot + this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES + this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES + } + + filePath(extensionId: string): string { + return path.join(this.dataRoot, extensionId, STORAGE_FILE) + } + + directory(extensionId: string): string { + return path.join(this.dataRoot, extensionId) + } + + get(extensionId: string, key: unknown): unknown { + const name = assertKey(key) + const values = this.read(extensionId).values + return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined + } + + set(extensionId: string, key: unknown, value: unknown): void { + const name = assertKey(key) + const serialized = serializeValue(value) + if (Buffer.byteLength(serialized, 'utf8') > this.maxValueBytes) { + throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限') + } + const file = this.read(extensionId) + file.values[name] = JSON.parse(serialized) + this.assertTotalSize(file) + this.write(extensionId, file) + } + + remove(extensionId: string, key: unknown): boolean { + const name = assertKey(key) + const file = this.read(extensionId) + if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false + delete file.values[name] + this.write(extensionId, file) + return true + } + + list(extensionId: string): Array<{ key: string; value: unknown }> { + const values = this.read(extensionId).values + return Object.keys(values).map((key) => ({ key, value: clone(values[key]) })) + } + + clear(extensionId: string): void { + this.write(extensionId, { version: STORAGE_VERSION, values: {} }) + } + + private read(extensionId: string): StorageFile { + const filePath = this.filePath(extensionId) + try { + const raw = fs.readJsonSync(filePath) as unknown + if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} } + const values = (raw as { values?: unknown }).values + if (!values || typeof values !== 'object' || Array.isArray(values)) { + return { version: STORAGE_VERSION, values: {} } + } + return { version: STORAGE_VERSION, values: values as Record } + } catch { + return { version: STORAGE_VERSION, values: {} } + } + } + + private write(extensionId: string, file: StorageFile): void { + const filePath = this.filePath(extensionId) + fs.ensureDirSync(path.dirname(filePath)) + const temporary = `${filePath}.tmp` + fs.writeJsonSync(temporary, file, { spaces: 2 }) + fs.moveSync(temporary, filePath, { overwrite: true }) + } + + private assertTotalSize(file: StorageFile): void { + const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8') + if (bytes > this.maxTotalBytes) { + throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '扩展存储总量超出上限') + } + } +} + +function assertKey(value: unknown): string { + if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '存储键必须是字符串') + const key = value.trim() + if (!KEY_PATTERN.test(key)) { + throw new ExtensionError('INVALID_REQUEST', '存储键只能包含字母、数字、点、下划线与短横线') + } + if (key.length > MAX_KEY_LENGTH) throw new ExtensionError('INVALID_REQUEST', '存储键过长') + return key +} + +function serializeValue(value: unknown): string { + if (value === undefined) throw new ExtensionError('INVALID_REQUEST', '不能存储 undefined') + try { + const serialized = JSON.stringify(value) + if (serialized === undefined) throw new Error('unsupported') + return serialized + } catch { + throw new ExtensionError('INVALID_REQUEST', '存储值必须可序列化为 JSON') + } +} + +function clone(value: T): T { + if (value === null || typeof value !== 'object') return value + return JSON.parse(JSON.stringify(value)) as T +} diff --git a/src/main/extensions/host-runtime.ts b/src/main/extensions/host-runtime.ts new file mode 100644 index 0000000..f3e2b4d --- /dev/null +++ b/src/main/extensions/host-runtime.ts @@ -0,0 +1,545 @@ +/** + * 扩展后台进程入口。 + * + * 这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、 + * 把请求转成白名单 RPC。任何 `require` 都只发生在这里,主进程永远不会加载 + * 第三方扩展代码。 + * + * 与主进程的协议见 `src/shared/extensions/rpc.ts`。 + */ +import fs from 'node:fs' +import path from 'node:path' +import { randomUUID } from 'node:crypto' +import { + EXTENSION_HOST_PROTOCOL_VERSION, + type ExtensionAutomationActionOutput, + type ExtensionHostActivate, + type ExtensionHostCall, + type ExtensionHostCallResult, + type ExtensionHostEvent, + type ExtensionHostInboundMessage, + type ExtensionHostInvokeAction, + type ExtensionHostTestSend, + type ExtensionHostOutboundMessage, + type ExtensionHostRegisterAction +} from '../../shared/extensions/rpc' +import type { ExtensionMessageEvent } from '../../shared/extensions/events' + +type MessageHandler = (event: ExtensionMessageEvent) => void | Promise + +interface RegisteredActionDefinition { + id: string + title: string + description?: string + inputSchema?: Record + handler: (input: Record) => unknown +} + +interface PendingCall { + resolve: (value: unknown) => void + reject: (error: Error) => void + timer: ReturnType +} + +const pendingCalls = new Map() +const eventHandlers = new Set() +const actions = new Map() +let permissions: string[] = [] +let activated = false +let extensionDir = '' +let extensionDataDir = '' +let extensionId = process.env.TM_EXTENSION_ID || '' + +function post(message: ExtensionHostOutboundMessage): void { + if (typeof process.send !== 'function') return + try { + process.send(message) + } catch { + // 父进程已断开;子进程会在 shutdown 或退出时结束。 + } +} + +function sendLog(level: 'info' | 'warn' | 'error', message: string): void { + post({ type: 'log', version: EXTENSION_HOST_PROTOCOL_VERSION, level, message }) +} + +function requirePermission(permission: string): void { + if (!permissions.includes(permission)) { + const error = new Error(`扩展没有 ${permission} 权限`) + ;(error as Error & { code?: string }).code = 'PERMISSION_DENIED' + throw error + } +} + +/** 白名单 RPC:扩展只能申请这些能力,且每次都要过权限检查。 */ +function callHost( + method: ExtensionHostCall['method'], + params: Record, + timeoutMs = 8_000 +): Promise { + if (!activated) return Promise.reject(new Error('扩展尚未激活')) + const callId = randomUUID() + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pendingCalls.delete(callId) + reject(Object.assign(new Error('宿主调用超时'), { code: 'ACTION_TIMEOUT' })) + }, timeoutMs) + pendingCalls.set(callId, { resolve, reject, timer }) + post({ type: 'call', version: EXTENSION_HOST_PROTOCOL_VERSION, callId, method, params }) + }) +} + +const tm = { + extension: { + get id(): string { + return extensionId + }, + /** 扩展私有数据目录;下载/生成的媒体应放在这里。 */ + get dataDir(): string { + return extensionDataDir + }, + get permissions(): string[] { + return [...permissions] + } + }, + events: { + on(name: 'message.received', handler: MessageHandler): () => void { + if (name !== 'message.received' || typeof handler !== 'function') return () => undefined + eventHandlers.add(handler) + return () => eventHandlers.delete(handler) + }, + off(name: 'message.received', handler: MessageHandler): void { + if (name !== 'message.received') return + eventHandlers.delete(handler) + } + }, + messages: { + async query(request: { + conversationId: string + startTime?: number + endTime?: number + limit?: number + }): Promise<{ messages: unknown[] }> { + requirePermission('messages.query') + const result = (await callHost('messages.query', { ...request })) as { messages: unknown[] } + return result + } + }, + wechat: { + /** + * 发送文本、图片或视频。 + * + * 兼容旧调用:不传 `type` 视为 `text`。视频走独立的 video 通道, + * 原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。 + */ + async send(request: { + type?: 'text' | 'image' | 'video' + to: string + text?: string + path?: string + at?: Record + dedupeKey?: string + }) { + const type = + request && (request.type === 'image' || request.type === 'video') ? request.type : 'text' + if (type === 'image' || type === 'video') { + requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image') + return (await callHost( + type === 'video' ? 'wechat.send.video' : 'wechat.send.image', + { + to: request.to, + path: request.path, + ...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {}) + }, + 180_000 + )) as { + actionId: string + status: 'sent' + } + } + requirePermission('wechat.send.text') + return (await callHost( + 'wechat.send.text', + { + to: request.to, + text: request.text, + ...(request.at ? { at: request.at } : {}), + ...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {}) + }, + 20_000 + )) as { + actionId: string + status: 'sent' + } + } + }, + ai: { + async chat(messages: Array<{ role: string; content: string }>) { + requirePermission('ai.chat') + return (await callHost('ai.chat', { messages }, 60_000)) as { text: string } + } + }, + storage: { + async get(key: string): Promise { + requirePermission('storage') + return callHost('storage.get', { key }) + }, + async set(key: string, value: unknown): Promise { + requirePermission('storage') + await callHost('storage.set', { key, value }) + }, + async remove(key: string): Promise { + requirePermission('storage') + const result = (await callHost('storage.remove', { key })) as { removed?: boolean } + return result.removed === true + }, + async list(): Promise> { + requirePermission('storage') + const result = (await callHost('storage.list', {})) as { + entries?: Array<{ key: string; value: unknown }> + } + return result.entries ?? [] + } + }, + automation: { + registerAction(definition: { + id: string + title: string + description?: string + inputSchema?: Record + handler: (input: Record) => unknown + }): void { + requirePermission('automation.action') + const id = String(definition?.id || '').trim() + if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(id)) throw new Error('动作 id 不合法') + if (typeof definition.handler !== 'function') throw new Error('动作必须提供 handler') + const title = String(definition.title || id) + .trim() + .slice(0, 60) + if (!title) throw new Error('动作 title 不能为空') + actions.set(id, { + id, + title, + ...(definition.description + ? { description: String(definition.description).slice(0, 200) } + : {}), + ...(definition.inputSchema ? { inputSchema: definition.inputSchema } : {}), + handler: definition.handler + }) + const message: ExtensionHostRegisterAction = { + type: 'register-action', + version: EXTENSION_HOST_PROTOCOL_VERSION, + action: { + id, + title, + ...(definition.description + ? { description: String(definition.description).slice(0, 200) } + : {}), + hasInputSchema: Boolean(definition.inputSchema) + } + } + post(message) + } + }, + capabilities: { + async get(): Promise { + return callHost('capabilities.get', {}) + } + }, + log: { + info(message: unknown): void { + sendLog('info', String(message ?? '')) + }, + warn(message: unknown): void { + sendLog('warn', String(message ?? '')) + }, + error(message: unknown): void { + sendLog('error', String(message ?? '')) + } + } +} + +/** 入口文件必须真实位于扩展目录内;符号链接与越界路径都会被拒绝。 */ +function resolveBackgroundEntry(dir: string): string | null { + const manifestPath = path.join(dir, 'manifest.json') + let manifest: { entrypoints?: { background?: unknown } } + try { + manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as typeof manifest + } catch { + return null + } + const relative = String(manifest.entrypoints?.background || '') + if (!relative) return null + const resolved = path.resolve(dir, relative) + try { + const realDir = fs.realpathSync(dir) + const realEntry = fs.realpathSync(resolved) + const inside = path.relative(realDir, realEntry) + if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) return null + return realEntry + } catch { + return null + } +} + +function pickExportedActivator(loaded: unknown): ((api: typeof tm) => unknown) | null { + if (typeof loaded === 'function') return loaded as (api: typeof tm) => unknown + if (loaded && typeof loaded === 'object') { + const candidate = (loaded as { activate?: unknown }).activate + if (typeof candidate === 'function') return candidate as (api: typeof tm) => unknown + } + return null +} + +async function activate(message: ExtensionHostActivate): Promise { + extensionId = message.extensionId + extensionDir = message.extensionDir + extensionDataDir = message.dataDir + permissions = Array.isArray(message.permissions) ? message.permissions : [] + const entry = resolveBackgroundEntry(extensionDir) + if (!entry) { + post({ + type: 'activated', + version: EXTENSION_HOST_PROTOCOL_VERSION, + ok: false, + error: { code: 'EXTENSION_INVALID_PATH', message: '后台入口文件不合法或不存在' } + }) + return + } + try { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const loaded = require(entry) as unknown + const activator = pickExportedActivator(loaded) + if (activator) await activator(tm) + activated = true + post({ type: 'activated', version: EXTENSION_HOST_PROTOCOL_VERSION, ok: true }) + } catch (error) { + activated = false + post({ + type: 'activated', + version: EXTENSION_HOST_PROTOCOL_VERSION, + ok: false, + error: { + code: 'ACTION_FAILED', + message: error instanceof Error ? error.message.slice(0, 300) : '扩展激活失败' + } + }) + } +} + +async function dispatchEvent(message: ExtensionHostEvent): Promise { + if (!activated) return + for (const handler of eventHandlers) { + try { + await withTimeout(Promise.resolve(handler(message.envelope.event)), 10_000) + } catch (error) { + sendLog('error', `消息处理失败:${error instanceof Error ? error.message : String(error)}`) + } + } +} + +function validateActionInput( + schema: Record | undefined, + input: Record +): void { + if (!schema) return + const required = Array.isArray(schema.required) ? schema.required : [] + for (const key of required) { + if (typeof key === 'string' && !(key in input)) { + throw new Error(`缺少必填参数:${key}`) + } + } + const properties = schema.properties + if (!properties || typeof properties !== 'object') return + for (const [key, definition] of Object.entries(properties as Record)) { + if (!(key in input)) continue + const type = (definition as { type?: unknown })?.type + const value = input[key] + if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`) + if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`) + if (type === 'boolean' && typeof value !== 'boolean') + throw new Error(`参数 ${key} 必须是布尔值`) + } +} + +async function invokeAction(message: ExtensionHostInvokeAction): Promise { + const definition = actions.get(message.actionId) + if (!definition) { + post({ + type: 'action-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { code: 'ACTION_FAILED', message: `动作不存在:${message.actionId}` } + }) + return + } + try { + validateActionInput(definition.inputSchema, message.input) + const raw = await withTimeout( + Promise.resolve(definition.handler(message.input)), + Math.max(1_000, Math.min(message.timeoutMs - 500, 60_000)) + ) + const output = normalizeActionOutput(raw) + post({ + type: 'action-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: output.success, + output, + ...(output.success + ? {} + : { + error: { code: 'ACTION_FAILED' as const, message: output.error || '扩展动作返回失败' } + }) + }) + } catch (error) { + post({ + type: 'action-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { + code: + error instanceof Error && /超时/.test(error.message) ? 'ACTION_TIMEOUT' : 'ACTION_FAILED', + message: error instanceof Error ? error.message.slice(0, 300) : '扩展动作执行失败' + } + }) + } +} + +function normalizeActionOutput(raw: unknown): ExtensionAutomationActionOutput { + if (!raw || typeof raw !== 'object') { + return { success: false, error: '动作必须返回对象' } + } + const value = raw as Partial + const reply = value.reply + const hasReply = + reply && reply.type === 'text' && typeof reply.text === 'string' && reply.text.trim().length > 0 + return { + success: value.success !== false, + ...(value.output && typeof value.output === 'object' ? { output: value.output } : {}), + ...(hasReply + ? { + reply: { + type: 'text' as const, + text: reply!.text.trim().slice(0, 2_000), + ...(reply!.at && typeof reply!.at === 'object' ? { at: reply!.at } : {}) + } + } + : {}), + ...(typeof value.error === 'string' && value.error.trim() + ? { error: value.error.trim().slice(0, 300) } + : {}) + } +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('扩展处理超时')), timeoutMs) + promise.then( + (value) => { + clearTimeout(timer) + resolve(value) + }, + (error) => { + clearTimeout(timer) + reject(error) + } + ) + }) +} + +process.on('message', (raw: unknown) => { + if (!raw || typeof raw !== 'object') return + const message = raw as ExtensionHostInboundMessage + if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return + switch (message.type) { + case 'activate': + void activate(message) + return + case 'event': + void dispatchEvent(message) + return + case 'invoke-action': + void invokeAction(message) + return + case 'test-send': + if (extensionId !== 'com.example.douyin-sender') return + void dispatchTestSend(message) + return + case 'call-result': { + const result = message as ExtensionHostCallResult + const pending = pendingCalls.get(result.callId) + if (!pending) return + clearTimeout(pending.timer) + pendingCalls.delete(result.callId) + if (result.ok) { + pending.resolve(result.result) + } else { + pending.reject( + Object.assign(new Error(result.error?.message || '宿主调用失败'), { + code: result.error?.code || 'ACTION_FAILED' + }) + ) + } + return + } + case 'shutdown': + process.exit(0) + } +}) + +async function dispatchTestSend(message: ExtensionHostTestSend): Promise { + const handler = ( + globalThis as typeof globalThis & { + __tmTestSend?: (params: Record) => Promise + } + ).__tmTestSend + if (!handler) { + post({ + type: 'test-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { code: 'ACTION_FAILED', message: '测试处理器不可用' } + }) + return + } + try { + const result = await handler(message.params) + post({ + type: 'test-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: true, + result + }) + } catch (error) { + post({ + type: 'test-result', + version: EXTENSION_HOST_PROTOCOL_VERSION, + requestId: message.requestId, + ok: false, + error: { + code: 'ACTION_FAILED', + message: error instanceof Error ? error.message : '测试任务失败' + } + }) + } +} + +process.on('uncaughtException', (error) => { + sendLog('error', `未捕获异常:${error.message}`) + process.exit(1) +}) + +process.on('unhandledRejection', (reason) => { + sendLog( + 'warn', + `未处理的 Promise 拒绝:${reason instanceof Error ? reason.message : String(reason)}` + ) +}) + +// 让宿主知道进程已就绪,可以发 activate。必须在监听器之后发送。 +post({ type: 'ready', version: EXTENSION_HOST_PROTOCOL_VERSION }) diff --git a/src/main/index.ts b/src/main/index.ts index 3896143..6a911c9 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -141,6 +141,16 @@ import { leaveNotificationContactDisplayName } from './services/leave-notification-target' import { MessageListenerService } from './services/message-listener-service' +import { EXTENSION_IPC } from '../shared/extensions/ipc' +import { installExtensionProtocolHandler, registerExtensionScheme } from './extensions/extension-protocol' +import { registerExtensionIpc } from './extensions/extension-ipc' +import { getExtensionPaths } from './extensions/extension-paths' +import { + disposeExtensionSystem, + getExtensionManager, + hasExtensionManager, + initExtensionSystem +} from './extensions/extension-service' import { automationRuleStore } from './services/automation-rule-store' import { automationExecutionLogService } from './services/automation-execution-log-service' import { initAutomationService, getAutomationService } from './services/automation-service' @@ -1079,8 +1089,10 @@ function createWindow(): void { // Electron 初始化完成并准备创建浏览器窗口后,将调用此方法 // 某些 API 只能在此事件发生后使用 -app.whenReady().then(async () => { - if (isLegacyMigrationHelper) { +/* 扩展页面走自定义协议;scheme 必须在 app ready 之前登记为特权协议。 */ +registerExtensionScheme() + +app.whenReady().then(async () => { if (isLegacyMigrationHelper) { try { runLegacySafeStorageHelper() app.exit(0) @@ -1442,7 +1454,24 @@ app.whenReady().then(async () => { // Create the renderer before native WCDB bootstrap so startup progress is visible immediately. await reportTemplateService.recover() registerReportTemplateIpc() + installExtensionProtocolHandler(getExtensionPaths()) + registerExtensionIpc({ + getManager: getExtensionManager, + paths: getExtensionPaths(), + isTrustedSender: (senderId) => + BrowserWindow.getAllWindows().some((window) => window.webContents.id === senderId) + }) createWindow() + void initExtensionSystem({ + appVersion: app.getVersion(), + onChange: (extensionId, reason) => { + for (const window of BrowserWindow.getAllWindows()) { + if (!window.isDestroyed()) { + window.webContents.send(EXTENSION_IPC.changed, { extensionId, reason }) + } + } + } + }) wcdbBootstrapPromise = bootstrapWcdbNativeAsync().then(() => { console.log('[WCDB4] async bootstrap complete') }) @@ -1706,6 +1735,21 @@ app.whenReady().then(async () => { }` ) } + /* + * 扩展事件分发:与 Automation 并行、互不影响。 + * 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。 + */ + if (hasExtensionManager()) { + try { + getExtensionManager().handleMessage(message) + } catch (error) { + console.warn( + `[Extension] handleMessage failed: ${ + error instanceof Error ? error.message : String(error) + }` + ) + } + } }) const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false }) configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled) @@ -1884,7 +1928,7 @@ app.whenReady().then(async () => { // 排查「消息到底发没发出去」时恰好缺的就是那份证据。 // 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成 // 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。 - if (request.type === 'text' || request.type === 'image') { + if (request.type === 'text' || request.type === 'image' || request.type === 'video') { const to = String(request.to || '').trim() const recipient = { type: @@ -1912,7 +1956,12 @@ app.whenReady().then(async () => { } const action = await wechatActionGateway.execute({ origin: 'user_manual', - purpose: request.type === 'text' ? 'manual_text' : 'manual_image', + purpose: + request.type === 'text' + ? 'manual_text' + : request.type === 'video' + ? 'manual_video' + : 'manual_image', triggerType: 'user', recipient, content: @@ -1922,7 +1971,9 @@ app.whenReady().then(async () => { text: String(request.text || ''), ...(request.at ? { at: request.at } : {}) } - : { type: 'image', path: String(request.filePath || '') } + : request.type === 'video' + ? { type: 'video', path: String(request.filePath || '') } + : { type: 'image', path: String(request.filePath || '') } }) // 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。 return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus()) @@ -3674,6 +3725,7 @@ app.on('before-quit', (event) => { agentHubService.stop() scheduledReportService.stop() groupExitMonitorService.stop() + await disposeExtensionSystem().catch(() => undefined) flushBootstrapCacheWritesSync() const [, nativeCallsDrained] = await Promise.all([ apiServer.stop().catch(() => undefined), diff --git a/src/main/services/automation-action-runner.ts b/src/main/services/automation-action-runner.ts index d570bc0..912a36c 100644 --- a/src/main/services/automation-action-runner.ts +++ b/src/main/services/automation-action-runner.ts @@ -19,8 +19,21 @@ import { renderLeaveNotificationText, type GroupMemberExitedEvent } from '../../shared/group-exit-event' -import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action' -import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history' +import type { + WechatActionContent, + WechatActionRequest, + WechatActionResult +} from '../../shared/wechat-action' +import type { ExtensionMessageEvent } from '../../shared/extensions/events' +import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc' +import { + canExtensionSendText, + invokeExtensionAction +} from '../extensions/extension-automation-bridge' +import type { + SaveGeneratedReportRequest, + SaveGeneratedReportResult +} from '../../shared/report-history' import { generateAgentGroupReport, type AgentGroupReportRequest, @@ -45,6 +58,21 @@ import type { AutomationTargetResolution } from './automation-wechat-target' /** 一步执行完毕后,后续步骤的处置方式。 */ const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send'] +/** + * 配了扩展动作时的步骤顺序。 + * + * 只有规则真的配了扩展动作才把这一步加进来:给每条日报都渲染一条 + * 「执行扩展动作 已跳过」是纯噪声,用户会以为规则配错了。 + */ +const EXTENSION_STEP_ORDER: AutomationStepKey[] = [ + 'received', + 'matched', + 'extension_action', + 'reply', + 'report', + 'send' +] + /** 退群通知的步骤顺序(与消息型规则**不共用**)。 */ const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [ 'exit_received', @@ -74,6 +102,7 @@ const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [ */ const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。' const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。' +const SKIPPED_AFTER_EXTENSION_FAILURE = '前置步骤失败(扩展动作未成功),本次不再继续。' /** * 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。 @@ -102,6 +131,8 @@ export interface AutomationRunInput { sourceDisplayName: string /** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */ triggerSender?: { wxid: string; displayName: string } + /** 触发本次执行的消息(扩展动作的运行时上下文)。 */ + message?: ExtensionMessageEvent } export interface AutomationRunResult { @@ -185,6 +216,22 @@ export interface ScheduledReportRunResult { export interface AutomationActionRunnerDependencies { generateReport?: (request: AgentGroupReportRequest) => Promise executeAction?: (request: WechatActionRequest) => Promise + /** + * 扩展动作调用。默认走 `ExtensionManager`;单测注入假实现即可绕开子进程。 + */ + invokeExtensionAction?: ( + extensionId: string, + actionId: string, + input: Record, + context: { + conversationId: string + isGroup: boolean + accountId: string + message?: ExtensionMessageEvent + } + ) => Promise + /** 扩展是否具备发送文本的权限。默认读扩展中心授予集合。 */ + canExtensionSendText?: (extensionId: string) => boolean now?: () => number /** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */ delay?: (ms: number) => Promise @@ -246,7 +293,9 @@ function actionErrorMessage(code: string | undefined, fallback: string | undefin } export class AutomationActionRunner { - private readonly generateReport: (request: AgentGroupReportRequest) => Promise + private readonly generateReport: ( + request: AgentGroupReportRequest + ) => Promise private readonly executeAction: (request: WechatActionRequest) => Promise private readonly now: () => number private readonly delay: (ms: number) => Promise @@ -257,21 +306,31 @@ export class AutomationActionRunner { AutomationActionRunnerDependencies['resolveReportContact'] > private readonly getContactAvatars: (usernames: string[]) => Promise> + private readonly invokeExtensionAction: NonNullable< + AutomationActionRunnerDependencies['invokeExtensionAction'] + > + private readonly canExtensionSendText: (extensionId: string) => boolean constructor(dependencies: AutomationActionRunnerDependencies = {}) { this.generateReport = dependencies.generateReport ?? generateAgentGroupReport - this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request)) + this.executeAction = + dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request)) this.now = dependencies.now ?? (() => Date.now()) this.delay = - dependencies.delay ?? - ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) + dependencies.delay ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw)) this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids)) + this.invokeExtensionAction = + dependencies.invokeExtensionAction ?? + ((id, actionId, input, context) => invokeExtensionAction(id, actionId, input, context)) + this.canExtensionSendText = dependencies.canExtensionSendText ?? canExtensionSendText } async run(input: AutomationRunInput): Promise { - const steps = STEP_ORDER.map((key) => createStep(key)) + const extensionAction = findAction(input.rule, 'extensionAction') + const order = extensionAction ? EXTENSION_STEP_ORDER : STEP_ORDER + const steps = order.map((key) => createStep(key)) const stepAt = (key: AutomationStepKey): AutomationStep => steps.find((step) => step.key === key) as AutomationStep @@ -282,25 +341,77 @@ export class AutomationActionRunner { const reportAction = findAction(input.rule, 'generateReport') const sendAction = findAction(input.rule, 'sendReportImage') - // ---- 步骤 3:回复确认 ---- + // ---- 步骤 3:扩展动作 ---- // - // 回复等待:规则一命中就秒回,看起来就是个机器人(消息刚到、回复就到)。 - // 等待时长是**规则自己的一项执行参数**(`rule.replyDelaySeconds`,在 - // 「编辑自动化 → 3 · 触发后执行」里配),所以不同规则可以不一样。 - // - // 等待刻意放在 `reply` 步骤计时**之外** —— `reply.durationMs` 只应该反映发送本身, - // 否则用户看到「回复确认 2000ms」会误以为是发送慢。 - // 已经命中就不再回头重判规则:等待窗口里规则被停用/删掉也不中断本次执行, - // 与 cooldown、同消息幂等的口径一致(都是「命中那一刻」的快照)。 - if (replyAction) { + // 扩展动作先跑,它产出的 `reply` 会成为下一步「回复确认」的内容。 + // 扩展本身**不发送**:内容交回宿主,由宿主在权限与授权都通过后经 Gateway 发出。 + let extensionOutput: ExtensionAutomationActionOutput | undefined + if (extensionAction) { + const extensionStep = stepAt('extension_action') + extensionStep.status = 'running' + extensionStep.startedAt = this.now() + try { + extensionOutput = await this.invokeExtensionAction( + String(extensionAction.extensionId || ''), + String(extensionAction.actionId || ''), + extensionAction.input ?? {}, + { + conversationId: input.conversationId, + isGroup: input.isGroup, + accountId: input.message?.accountId ?? '', + ...(input.message ? { message: input.message } : {}) + } + ) + } catch (error) { + markFailed( + extensionStep, + this.now(), + error instanceof Error ? error.message : '扩展动作执行失败' + ) + markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE) + return { steps, status: 'failed', errorSummary: extensionStep.error } + } + if (!extensionOutput || extensionOutput.success === false) { + markFailed(extensionStep, this.now(), extensionOutput?.error || '扩展动作返回失败') + markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE) + return { steps, status: 'failed', errorSummary: extensionStep.error } + } + if (extensionOutput.reply) extensionStep.detail = '已生成回复内容' + markSuccess(extensionStep, this.now()) + } + + const extensionReply = extensionOutput?.reply + + // 步骤 4:回复确认。 + // 命中即视为快照:等待窗口内规则被停用/删除也不中断本次执行。 + // 等待时长来自 rule.replyDelaySeconds,且不计入 reply.durationMs。 + const willReply = Boolean(extensionReply) || Boolean(replyAction) + if (willReply) { // 用共享的归一化函数,而不是 `Number(...) || 0`:旧版 rules.json 里没有这个字段, // 那应该按**默认 2 秒**处理(否则「默认 2 秒」要等用户手动进编辑页才会生效)。 const replyDelayMs = normalizeReplyDelaySeconds(input.rule.replyDelaySeconds) * 1_000 if (replyDelayMs > 0) await this.delay(replyDelayMs) } - if (!replyAction) { + if (!willReply) { markSkipped(stepAt('reply')) + } else if (extensionReply) { + const replyStep = stepAt('reply') + const extensionId = String(extensionAction?.extensionId || '') + if (!this.canExtensionSendText(extensionId)) { + markFailed(replyStep, this.now(), '扩展没有 wechat.send.text 权限,回复未发送') + markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE) + return { steps, status: 'failed', errorSummary: replyStep.error } + } + replyStep.status = 'running' + replyStep.startedAt = this.now() + const sent = await this.sendExtensionReply(input, extensionId, extensionReply) + if (!sent.ok) { + markFailed(replyStep, this.now(), sent.error || '回复确认失败') + markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE) + return { steps, status: 'failed', errorSummary: replyStep.error } + } + markSuccess(replyStep, this.now()) } else { const replyStep = stepAt('reply') replyStep.status = 'running' @@ -316,12 +427,12 @@ export class AutomationActionRunner { : undefined const sent = await this.sendThroughGateway(input, 'reply', { type: 'text', - text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT, + text: replyAction?.text?.trim() || DEFAULT_REPLY_TEXT, ...(confirmationAt ? { at: confirmationAt } : {}) }) if (!sent.ok) { markFailed(replyStep, this.now(), sent.error || '回复确认失败') - markRemainingSkipped(steps, 'reply', SKIPPED_AFTER_REPLY_FAILURE) + markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE) return { steps, status: 'failed', errorSummary: replyStep.error } } markSuccess(replyStep, this.now()) @@ -346,7 +457,7 @@ export class AutomationActionRunner { } if (!result.success || !result.pngPath) { markFailed(reportStep, this.now(), result.error || '日报生成失败') - markRemainingSkipped(steps, 'report', SKIPPED_AFTER_REPORT_FAILURE) + markRemainingSkipped(steps, order, 'report', SKIPPED_AFTER_REPORT_FAILURE) return { steps, status: 'failed', errorSummary: reportStep.error } } pngPath = result.pngPath @@ -395,6 +506,43 @@ export class AutomationActionRunner { return { steps, status: 'success', pngPath } } + /** + * 发送扩展产出的回复。 + * + * 内容来自扩展,**发送动作来自宿主**:`origin` / `purpose` / 幂等键都在这里填, + * 扩展返回的只是「想说什么」。所以扩展无法借这条链路绕过发送策略。 + */ + private async sendExtensionReply( + input: AutomationRunInput, + extensionId: string, + reply: NonNullable + ): Promise<{ ok: boolean; error?: string }> { + try { + const result = await this.executeAction({ + idempotencyKey: `extension_action:${input.executionId}`, + origin: 'extension', + purpose: 'extension_action', + triggerType: 'automation', + executionId: input.executionId, + recipient: { + type: input.isGroup ? 'group' : 'contact', + id: input.conversationId, + name: input.sourceDisplayName + }, + content: { + type: 'text', + text: reply.text, + ...(reply.at ? { at: reply.at } : {}) + }, + metadata: { extensionId } + }) + if (result.status === 'sent') return { ok: true } + return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) } + } catch (error) { + return { ok: false, error: error instanceof Error ? error.message : String(error) } + } + } + /** * 把「@我生成日报」产出的日报写进**日报历史**。 * @@ -522,7 +670,9 @@ export class AutomationActionRunner { generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊', contactAvatar, source: 'scheduled', - dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range), + dateRange: + generated.reportMetadata?.dateRange || + scheduledReportRangeLabel(input.config.report.range), reportDate: generated.reportMetadata?.reportDate, messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0, generatedAt: new Date(this.now()).toISOString(), @@ -674,7 +824,9 @@ export class AutomationActionRunner { * 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown * (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。 */ - async runLeaveNotification(input: LeaveNotificationRunInput): Promise { + async runLeaveNotification( + input: LeaveNotificationRunInput + ): Promise { const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key)) const stepAt = (key: AutomationStepKey): AutomationStep => steps.find((step) => step.key === key) as AutomationStep @@ -792,18 +944,22 @@ export class AutomationActionRunner { } } -function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined { +function findAction( + rule: AutomationRule, + type: AutomationAction['type'] +): AutomationAction | undefined { return rule.actions.find((action) => action.type === type && action.enabled) } /** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */ function markRemainingSkipped( steps: AutomationStep[], + order: AutomationStepKey[], after: AutomationStepKey, skipReason?: string ): void { - const from = STEP_ORDER.indexOf(after) + 1 - for (const key of STEP_ORDER.slice(from)) { + const from = order.indexOf(after) + 1 + for (const key of order.slice(from)) { const step = steps.find((item) => item.key === key) if (step) markSkipped(step, skipReason) } diff --git a/src/main/services/automation-service.ts b/src/main/services/automation-service.ts index 4c14ab7..2e5e6fa 100644 --- a/src/main/services/automation-service.ts +++ b/src/main/services/automation-service.ts @@ -1,8 +1,5 @@ import { createHash, randomUUID } from 'node:crypto' -import { - matchAutomationRule, - type AutomationMatchInput -} from '../../shared/automation-matcher' +import { matchAutomationRule, type AutomationMatchInput } from '../../shared/automation-matcher' import { AUTOMATION_SEND_PURPOSE, BUILTIN_LEAVE_NOTIFICATION_RULE_ID, @@ -14,6 +11,8 @@ import { type ScheduledRuleRunOutcome } from '../../shared/automation' import type { GroupMemberExitedEvent } from '../../shared/group-exit-event' +import { buildExtensionMessageEvent } from '../../shared/extensions/events' +import { buildEventId } from '../extensions/extension-event-bus' import type { PersonalWechatSendCapability } from '../../shared/personal-wechat' import type { Wcdb4Client } from '../wcdb4-client' import type { NormalizedIncomingMessage } from './message-listener-service' @@ -28,18 +27,12 @@ import { scheduledReportSourceDisplayName } from './scheduled-report-target' import type { AutomationTargetContact } from './automation-wechat-target' -import { - automationRuleStore, - type AutomationRuleStore -} from './automation-rule-store' +import { automationRuleStore, type AutomationRuleStore } from './automation-rule-store' import { automationExecutionLogService, type AutomationExecutionLogService } from './automation-execution-log-service' -import { - automationActionRunner, - type AutomationActionRunner -} from './automation-action-runner' +import { automationActionRunner, type AutomationActionRunner } from './automation-action-runner' /** * AutomationService —— Automation v1 的编排层。 * @@ -137,9 +130,7 @@ export function leaveNotificationIdempotencyKey(eventId: string): string { * 「立即执行」会因为幂等而被静默吞掉。 */ export function scheduledReportExecutionId(ruleId: string, slot: string): string { - return createHash('sha1') - .update(`scheduled_report\u0001${ruleId}\u0001${slot}`) - .digest('hex') + return createHash('sha1').update(`scheduled_report\u0001${ruleId}\u0001${slot}`).digest('hex') } /** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */ @@ -291,7 +282,7 @@ export class AutomationService { const sourceDisplayName = this.resolveDisplayName(message) try { - await this.execute(rule, message, sourceDisplayName) + await this.execute(rule, message, sourceDisplayName, selfUsernames) } finally { // 无论 success / failed / 抛异常都要解除 in-flight。 // 漏掉这一步会让这条规则在这个会话里**永久锁死**。 @@ -660,7 +651,10 @@ export class AutomationService { return true } - /** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> { + /** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ + id: string + name: string + }> { try { return listContacts() .filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom')) @@ -683,7 +677,8 @@ export class AutomationService { private async execute( rule: AutomationRule, message: NormalizedIncomingMessage, - sourceDisplayName: string + sourceDisplayName: string, + selfUsernames: string[] ): Promise { const executionId = randomUUID() const startedAt = this.now() @@ -727,6 +722,24 @@ export class AutomationService { displayName: message.senderNickname } } + : {}), + ...(rule.actions.some((action) => action.type === 'extensionAction' && action.enabled) + ? { + message: buildExtensionMessageEvent({ + eventId: buildEventId(message.sessionId, message.localId), + accountId: String(getSelfAccountInfo()?.wxid || ''), + conversationId: message.sessionId, + messageId: message.serverId || message.localId, + ...(message.senderId ? { senderId: message.senderId } : {}), + ...(message.senderNickname ? { senderName: message.senderNickname } : {}), + isGroup: message.isGroup, + isSelf: message.isSelf, + messageType: message.messageType, + ...(message.content !== undefined ? { content: message.content } : {}), + mentionsMe: message.mentionTargets.some((target) => selfUsernames.includes(target)), + createTimeSeconds: message.createTime + }) + } : {}) }) } catch (error) { diff --git a/src/main/services/mac-wechat-runtime-manager.ts b/src/main/services/mac-wechat-runtime-manager.ts index a976428..ccb7f71 100644 --- a/src/main/services/mac-wechat-runtime-manager.ts +++ b/src/main/services/mac-wechat-runtime-manager.ts @@ -112,9 +112,7 @@ export function formatMacWechatHostStartupFailure(code: number | null, diagnosti const lines = diagnostic.trim().split('\n').filter(Boolean) const detail = lines[lines.length - 1] if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}` - return code === null - ? '发送运行时在启动过程中退出' - : `发送运行时启动失败(进程退出码 ${code})` + return code === null ? '发送运行时在启动过程中退出' : `发送运行时启动失败(进程退出码 ${code})` } export function resolveMacWechatSendMechanism( @@ -201,6 +199,12 @@ export function deriveMacWechatSenderStatus({ const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true + /* + * 视频复用图片的媒体通道(Host 的 `/SendMsg` type=video)。 + * Runtime manifest 不单独声明 video 能力,因此以图片通道是否可用作为判据; + * 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。 + */ + const canSendVideo = bindingReady && binding?.canSendImage === true const sessionAttached = identityMatches && (binding?.sessionAttached ?? false) const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false) @@ -224,10 +228,11 @@ export function deriveMacWechatSenderStatus({ imageHookInstalled: identityMatches && (binding?.canSendImage ?? false), imageHookReady: identityMatches && (binding?.canSendImage ?? false), messageListenerReady: scriptLoaded, - canSend: canSendText || canSendImage || canSendVoice, + canSend: canSendText || canSendImage || canSendVoice || canSendVideo, canSendText, canSendImage, canSendVoice, + canSendVideo, message, error: state === 'error' ? message : undefined } @@ -349,9 +354,7 @@ export class MacWechatRuntimeManager { * comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime * online" and "WeChat bound" stay two independent states. */ - ensureStarted( - options: { allowManualRestart?: boolean } = {} - ): Promise { + ensureStarted(options: { allowManualRestart?: boolean } = {}): Promise { if (this.startInFlight) return this.startInFlight const startPromise = this.ensureStartedOnce(options) @@ -367,9 +370,9 @@ export class MacWechatRuntimeManager { return startPromise } - protected async ensureStartedOnce( - options: { allowManualRestart?: boolean } - ): Promise { + protected async ensureStartedOnce(options: { + allowManualRestart?: boolean + }): Promise { if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot() if (options.allowManualRestart) this.manuallyStopped = false if (isMacNativeRuntimeUnavailable()) { @@ -481,19 +484,13 @@ export class MacWechatRuntimeManager { } try { if (!app.isPackaged) { - execFileSync('/usr/bin/codesign', [ - '--force', - '--sign', - '-', - '--timestamp=none', - hostPath - ]) + execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', '--timestamp=none', hostPath]) } execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath]) } catch (error) { this.lifecycle = 'stopped' - this.lastError = '无法验证发送 Host 签名:' + - (error instanceof Error ? error.message : String(error)) + this.lastError = + '无法验证发送 Host 签名:' + (error instanceof Error ? error.message : String(error)) appLogger.write({ level: 'error', scope: 'mac-wechat-runtime', diff --git a/src/main/services/message-listener-service.ts b/src/main/services/message-listener-service.ts index 007b196..d67b019 100644 --- a/src/main/services/message-listener-service.ts +++ b/src/main/services/message-listener-service.ts @@ -137,14 +137,39 @@ export function extractMentionTargets(source: string | undefined): string[] { if (!match) return [] const inner = match[1].trim() const unwrapped = inner.replace(/^$/, '').trim() - return unwrapped ? [unwrapped] : [] + if (!unwrapped) return [] + return unwrapped + .split(',') + .map((item) => item.trim()) + .filter(Boolean) } -/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */ +/** 把 WCDB 的 `source` 列(明文 XML 字符串或 zstd 压缩的 Buffer)还原成 XML 文本。 */ export function decodeSourcePayload(value: unknown): string | undefined { + if (typeof value === 'string') { + const trimmed = value.trim() + if (!trimmed) return undefined + if ( + trimmed.length >= 8 && + trimmed.length % 2 === 0 && + /^28b52ffd[0-9a-f]+$/i.test(trimmed) + ) { + try { + return Buffer.from(zstdDecompress(Buffer.from(trimmed, 'hex'))).toString('utf8') + } catch { + return undefined + } + } + return trimmed + } + let buffer: Buffer | null = null if (Buffer.isBuffer(value)) { buffer = value + } else if (value instanceof Uint8Array) { + buffer = Buffer.from(value) + } else if (Array.isArray(value)) { + buffer = Buffer.from(value) } else { const candidate = value as { type?: string; data?: unknown } | null if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) { @@ -193,6 +218,7 @@ export class MessageListenerService { private readonly pendingSessions = new Set() private coalesceTimer: ReturnType | null = null private readbackInFlight = false + private pendingReadback = false private disposed = false private readonly coalesceMs: number @@ -282,8 +308,13 @@ export class MessageListenerService { * - **legacy(protocol v1,旧 runtime)**:只能退回「最近活跃会话」`getSessions()[0]`。 */ private async readback(): Promise { - if (this.disposed || this.readbackInFlight) return + if (this.disposed) return + if (this.readbackInFlight) { + this.pendingReadback = true + return + } this.readbackInFlight = true + this.pendingReadback = false const startedAt = Date.now() const preciseSessions = Array.from(this.pendingSessions) @@ -321,6 +352,15 @@ export class MessageListenerService { ) } finally { this.readbackInFlight = false + if (!this.disposed && (this.pendingReadback || this.pendingSessions.size > 0)) { + this.pendingReadback = false + if (!this.coalesceTimer) { + this.coalesceTimer = setTimeout(() => { + this.coalesceTimer = null + void this.readback() + }, this.coalesceMs) + } + } } } diff --git a/src/main/services/personal-wechat-capability-service.ts b/src/main/services/personal-wechat-capability-service.ts index 16ff966..883cb70 100644 --- a/src/main/services/personal-wechat-capability-service.ts +++ b/src/main/services/personal-wechat-capability-service.ts @@ -37,7 +37,8 @@ export class PersonalWechatCapabilityService { const capabilities = { text: Boolean(senderStatus.canSendText), image: Boolean(senderStatus.canSendImage), - voice: Boolean(senderStatus.canSendVoice) + voice: Boolean(senderStatus.canSendVoice), + video: Boolean(senderStatus.canSendVideo) } const status = this.mapState(senderStatus) const ready = status === 'ready' diff --git a/src/main/services/personal-wechat-send-service.ts b/src/main/services/personal-wechat-send-service.ts index 33e32fc..c6fa91a 100644 --- a/src/main/services/personal-wechat-send-service.ts +++ b/src/main/services/personal-wechat-send-service.ts @@ -23,7 +23,10 @@ import type { import { loadSettings } from './settings-store' import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder' import { appLogger } from '../app-logger' -import { accountDirectoryBelongsToIdentity, readLocalAccountIdentity } from './local-account-identity' +import { + accountDirectoryBelongsToIdentity, + readLocalAccountIdentity +} from './local-account-identity' import { macWechatRuntimeManager } from './mac-wechat-runtime-manager' const execFileAsync = promisify(execFile) @@ -31,6 +34,8 @@ const WINDOWS_LOOPBACK_HOST = '127.0.0.1' const REQUEST_TIMEOUT_MS = 20_000 const MAX_IMAGE_BYTES = 20 * 1024 * 1024 const MAX_VOICE_BYTES = 20 * 1024 * 1024 +/** 视频与扩展发送通道的上限保持一致。 */ +const MAX_VIDEO_BYTES = 100 * 1024 * 1024 // 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。 const VOICE_ENCODER_NAME = 'silk' const VOICE_ENCODER_VERSION = 'tm-wechat-native' @@ -327,6 +332,73 @@ function stageMacWechatImageForMessageSourceSend( return stagedPath } +const MAC_VIDEO_STAGE_PREFIX = 'tm-video-' +const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000 + +/** + * macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib` + * 只能读取 `~/Library/Containers/com.tencent.xinWeChat/Data/...` 容器内路径, + * 直接传 `~/Library/Application Support/TraceMemo/...` 会触发 `VIDEO_PREPARATION_FAILED:0`。 + * 因此发送前需将容器外视频暂存到微信容器的 `Documents` 目录。 + */ +export function stageMacWechatVideoForSend( + filePath: string, + wechatFilesRoot = WECHAT_FILES_ROOT +): { stagedPath: string; cleanup: () => void } { + const normalized = String(filePath || '').trim() + const containerDataRoot = dirname(dirname(wechatFilesRoot)) + if ( + containerDataRoot.includes('com.tencent.xinWeChat') && + normalized.startsWith(`${containerDataRoot}${sep}`) + ) { + return { stagedPath: normalized, cleanup: () => {} } + } + + const documentsDir = dirname(wechatFilesRoot) + const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot + mkdirSync(stageDir, { recursive: true }) + + // 顺手清理超过 10 分钟的历史暂存视频,防止异常退出残留。 + const now = Date.now() + try { + for (const entry of readdirSync(stageDir)) { + if (!entry.startsWith(MAC_VIDEO_STAGE_PREFIX)) continue + const candidate = join(stageDir, entry) + try { + if (now - statSync(candidate).mtimeMs > MAC_VIDEO_STAGE_RETENTION_MS) { + unlinkSync(candidate) + } + } catch { + // Best-effort stale file cleanup. + } + } + } catch { + // Ignore directory listing errors. + } + + const extension = extname(normalized).toLowerCase() + const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.mp4' + const stagedPath = join( + stageDir, + `${MAC_VIDEO_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}` + ) + copyFileSync(normalized, stagedPath) + + return { + stagedPath, + cleanup: () => { + const timer = setTimeout(() => { + try { + unlinkSync(stagedPath) + } catch { + // Best-effort delayed cleanup after WeChat finishes asynchronous video upload. + } + }, 120_000) + timer.unref?.() + } + } +} + /** Locate the current account's temporary image directory consumed by the image send path. */ export function findWechatImagePath( root = WECHAT_FILES_ROOT, @@ -443,6 +515,12 @@ export function buildWindowsWechatRequest( body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() } } } + if (request.type === 'video') { + return { + endpoint: '/SendMsg', + body: { toWxid: target, type: 'video', msg: String(request.filePath || '').trim() } + } + } const fromId = String(request.fromId || '').trim() const filePath = String(options.filePath || request.filePath || '').trim() @@ -609,6 +687,7 @@ export class PersonalWechatSendService { if (request.type === 'text') return this.sendMacText(request) if (request.type === 'image') return this.sendMacImage(request) if (request.type === 'voice') return this.sendMacVoice(request) + if (request.type === 'video') return this.sendMacVideo(request) } return { success: false, @@ -772,11 +851,78 @@ export class PersonalWechatSendService { signal: AbortSignal.timeout(timeoutMs) }).catch(() => null) if (response === null || !response.ok) return null - return (await response.json().catch(() => null)) as { - code: number - ok: boolean - message: string - } | null + const payload = (await response.json().catch(() => null)) as Record | null + if (!payload) return null + /* + * 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`, + * `/SendMsg` 兼容层可能返回 `{status:true}` 或 Windows 风格的 `{ret:0}`。 + * 这里统一收敛,避免「实际已发送、界面报失败」。 + */ + const explicitFailure = payload.ok === false || payload.status === false + const ok = + !explicitFailure && + (payload.ok === true || payload.status === true || payload.ret === 0 || payload.code === 0) + return { + code: Number(payload.code ?? payload.ret ?? (ok ? 0 : 1)), + ok, + message: String(payload.message ?? payload.msg ?? '') + } + } + + /** + * macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。 + * + * 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行, + * 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。 + * 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。 + */ + private async sendMacVideo( + request: Extract + ): Promise { + await macWechatRuntimeManager.ensureStarted() + const status = await macWechatRuntimeManager.buildSenderStatus() + if (!status.canSendVideo) { + return { + success: false, + status, + error: status.message || '当前微信发送组件不支持视频,请升级后重试' + } + } + const filePath = String(request.filePath || '').trim() + if (!filePath || !existsSync(filePath)) { + return { success: false, status, error: '请选择有效的视频文件' } + } + const size = statSync(filePath).size + if (size <= 0 || size > MAX_VIDEO_BYTES) { + return { success: false, status, error: '视频必须小于 100 MB' } + } + + let staged: { stagedPath: string; cleanup: () => void } | null = null + try { + staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot) + } catch (error) { + const latest = await macWechatRuntimeManager.buildSenderStatus() + return { + success: false, + status: latest, + error: error instanceof Error ? error.message : '无法将视频暂存到微信沙盒目录' + } + } + + try { + const result = await this.postMacHost( + '/SendMsg', + { toWxid: request.to, type: 'video', msg: staged.stagedPath }, + 180_000 + ) + const latest = await macWechatRuntimeManager.buildSenderStatus() + if (!result?.ok) { + return { success: false, status: latest, error: result?.message || '视频发送失败' } + } + return { success: true, status: latest } + } finally { + staged.cleanup() + } } private async sendMacImage( @@ -974,21 +1120,24 @@ export class PersonalWechatSendService { request = { ...request, to, text } } else { const filePath = String(request.filePath || '').trim() + const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片' + const limit = + request.type === 'voice' + ? MAX_VOICE_BYTES + : request.type === 'video' + ? MAX_VIDEO_BYTES + : MAX_IMAGE_BYTES if (!filePath || !existsSync(filePath)) { const status = await this.getWindowsStatus() - return { - success: false, - status, - error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件` - } + return { success: false, status, error: `请选择有效的${label}文件` } } const size = statSync(filePath).size - if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) { + if (size <= 0 || size > limit) { const status = await this.getWindowsStatus() return { success: false, status, - error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB` + error: `${label}必须小于 ${Math.round(limit / (1024 * 1024))} MB` } } request = { ...request, to, filePath } @@ -1019,6 +1168,10 @@ export class PersonalWechatSendService { filePath: preparedImage.filePath }) await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000) + } else if (request.type === 'video') { + // 视频不复制到临时目录:原生 Host 直接按绝对路径读取。 + const windowsRequest = buildWindowsWechatRequest(request) + await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000) } else if (request.type === 'voice') { const fromId = String(request.fromId || '').trim() if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音') diff --git a/src/main/services/wechat-action-gateway.ts b/src/main/services/wechat-action-gateway.ts index 57aa724..01f7446 100644 --- a/src/main/services/wechat-action-gateway.ts +++ b/src/main/services/wechat-action-gateway.ts @@ -39,7 +39,15 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([ // purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。 'automation_scheduled_report_postfix', 'manual_report_image', - 'manual_report_postfix' + 'manual_report_postfix', + /* + * 扩展来源的两个用途。 + * + * 扩展不能自己决定 purpose:`ExtensionSendGateway` 与自动化 runner 分别填这两个值, + * 且 `evaluateWechatActionPolicy` 要求 `origin === 'extension'`,两边同时成立才放行。 + */ + 'extension_send', + 'extension_action' ]) export interface ReportImageSequenceRequest { @@ -137,6 +145,46 @@ export class WechatActionGateway { return this.loadAuditState().records.map((record) => ({ ...record })) } + /** + * 扩展来源的发送入口。 + * + * 与 `execute()` 的区别只有一个:`origin` / `purpose` / `metadata.extensionId` + * 由这里按宿主规则填,扩展侧传不进来。其余检查(能力、审计、幂等、 + * 自动化发送节流)与普通发送完全一致。 + */ + async executeFromExtension(input: { + extensionId: string + purpose: 'extension_send' | 'extension_action' + recipient: WechatActionRequest['recipient'] + content: WechatActionContent + idempotencyKey?: string + executionId?: string + }): Promise { + const extensionId = String(input.extensionId || '').trim() + const startedAt = this.deps.now().toISOString() + if (!extensionId) { + return { + actionId: randomUUID(), + status: 'blocked', + decision: 'block', + errorCode: 'INVALID_REQUEST', + reason: '扩展发送缺少扩展标识', + startedAt, + finishedAt: startedAt + } + } + return this.execute({ + ...(input.idempotencyKey ? { idempotencyKey: String(input.idempotencyKey) } : {}), + ...(input.executionId ? { executionId: String(input.executionId) } : {}), + origin: 'extension', + purpose: input.purpose, + triggerType: 'automation', + recipient: input.recipient, + content: input.content, + metadata: { extensionId } + }) + } + async execute(request: WechatActionRequest): Promise { const normalized = normalizeActionRequest(request) const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined @@ -256,9 +304,10 @@ export class WechatActionGateway { const queued = this.automationSendTail.then(async () => { const now = this.deps.now().getTime() - const remaining = this.lastAutomationSendStartedAt !== undefined - ? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt)) - : 0 + const remaining = + this.lastAutomationSendStartedAt !== undefined + ? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt)) + : 0 if (remaining > 0) await this.deps.wait(remaining) this.lastAutomationSendStartedAt = this.deps.now().getTime() return this.deps.send(sendRequest) @@ -393,14 +442,20 @@ export class WechatActionGateway { !request.content || (request.content.type !== 'text' && request.content.type !== 'image' && + request.content.type !== 'video' && request.content.type !== 'voice') ) { return } const state = this.loadAuditState() + const extensionId = + request.metadata && typeof request.metadata.extensionId === 'string' + ? request.metadata.extensionId.trim().slice(0, 128) + : '' const record: WechatActionAuditRecord = { actionId: result.actionId, ...(idempotencyKey ? { idempotencyKey } : {}), + ...(extensionId ? { extensionId } : {}), origin: request.origin, purpose: request.purpose, triggerType: request.triggerType, @@ -465,6 +520,18 @@ export function evaluateWechatActionPolicy(request: WechatActionRequest): Policy reason: `自动化动作不允许执行 purpose=${request.purpose}` } } + /* + * 扩展用途必须来自扩展来源。少了这一条,任何能构造 `WechatActionRequest` 的 + * 内部调用都可以用 `extension_send` 绕过自动化用途白名单。 + */ + if (String(request.purpose).startsWith('extension_') && request.origin !== 'extension') { + return { + decision: 'block', + source: 'deterministic', + reasonCode: 'ACTION_NOT_ALLOWED', + reason: '扩展发送用途只能用于扩展来源的请求' + } + } return { decision: 'allow', source: 'deterministic' } } @@ -526,7 +593,7 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu content: { type: 'text', text, ...(at ? { at } : {}) } } as WechatActionRequest } - if (contentType !== 'image' && contentType !== 'voice') return null + if (contentType !== 'image' && contentType !== 'video' && contentType !== 'voice') return null const filePath = String((content as { path?: unknown }).path || '').trim() if (!filePath) return null return { @@ -585,6 +652,9 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech if (request.content.type === 'image') { return { ...base, type: 'image', filePath: request.content.path } } + if (request.content.type === 'video') { + return { ...base, type: 'video', filePath: request.content.path } + } const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {} const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : '' const durationMs = @@ -638,7 +708,7 @@ function contentAudit( } function contentTypeLabel(type: WechatActionContent['type']): string { - return type === 'text' ? '文字' : type === 'image' ? '图片' : '语音' + return type === 'text' ? '文字' : type === 'image' ? '图片' : type === 'video' ? '视频' : '语音' } function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] { diff --git a/src/main/wcdb4-client.ts b/src/main/wcdb4-client.ts index c371723..25599b5 100644 --- a/src/main/wcdb4-client.ts +++ b/src/main/wcdb4-client.ts @@ -1442,8 +1442,16 @@ export class Wcdb4Client { // cannot silently stop at a shard boundary. let tableMessages: Wcdb4Message[] = [] const cursorSatisfiesLimit = maxRows !== undefined && cursorMessages.length >= maxRows + const cursorMissingSource = + cursorMessages.length > 0 && + cursorMessages.some( + (msg) => !msg.raw || !Object.prototype.hasOwnProperty.call(msg.raw, 'source') + ) let tableScanExecuted = false - if (!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) { + if ( + (!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) || + (Boolean(endTime) && cursorMissingSource) + ) { tableScanExecuted = true tableMessages = await this.getMessagesByTableScanAsync( username, @@ -2411,7 +2419,19 @@ export class Wcdb4Client { ? `local:${message.mesLocalID}:${message.msgCreateTime || 0}` : `${message.msgCreateTime}:${message.msgContent}` const key = recoveredRow ? `recovered:${identity}` : identity - merged.set(key, message) + const existing = merged.get(key) + if (existing?.raw && message.raw) { + merged.set(key, { + ...existing, + ...message, + raw: { + ...existing.raw, + ...message.raw + } + }) + } else { + merged.set(key, message) + } } const messages = Array.from(merged.values()).sort( (left, right) => diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index f1dd223..984161f 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -1,5 +1,17 @@ import { ElectronAPI } from '@electron-toolkit/preload' import { Contact, Message, MessagesAroundResult } from '../shared/types' +import type { + ExtensionChangedEvent, + ExtensionPageRequest +} from '../shared/extensions/ipc' +import type { + ExtensionInstallResult, + ExtensionLogEntry, + ExtensionOperationResult, + ExtensionPageDescriptor, + ExtensionPageResponse, + InstalledExtension +} from '../shared/extensions/types' import { GroupReportExportRequest, GroupReportExportResult, @@ -817,6 +829,30 @@ declare global { onAgentHubConversationsCleared: (callback: () => void) => () => void onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => () => void onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => () => void + /* 扩展中心 */ + listExtensions: () => Promise + getExtension: (extensionId: string) => Promise + pickExtensionDirectory: () => Promise + pickExtensionPackage: () => Promise + installExtensionFromDirectory: (directory: string) => Promise + installExtensionFromPackage: (packagePath: string) => Promise + setExtensionEnabled: ( + extensionId: string, + enabled: boolean + ) => Promise + uninstallExtension: ( + extensionId: string, + keepData?: boolean + ) => Promise + getExtensionLogs: (extensionId: string, limit?: number) => Promise + clearExtensionLogs: (extensionId: string) => Promise<{ success: true }> + getExtensionPageUrl: ( + extensionId: string, + pageId?: string + ) => Promise + extensionPageRequest: (request: ExtensionPageRequest) => Promise + openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }> + onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void } } } diff --git a/src/preload/index.ts b/src/preload/index.ts index 06deec7..553c6c4 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -131,6 +131,16 @@ import type { SaveTextToSpeechSettingsRequest, SynthesizeTextToSpeechRequest } from '../shared/text-to-speech' +import type { ExtensionChangedEvent } from '../shared/extensions/ipc' +import type { + ExtensionInstallResult, + ExtensionLogEntry, + ExtensionOperationResult, + ExtensionPageDescriptor, + ExtensionPageRequest, + ExtensionPageResponse, + InstalledExtension +} from '../shared/extensions/types' // 渲染器的自定义 API const api = { @@ -265,6 +275,36 @@ const api = { enabled: boolean ): Promise => ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }), + listExtensions: (): Promise => ipcRenderer.invoke('extension:list'), + getExtension: (extensionId: string): Promise => + ipcRenderer.invoke('extension:get', extensionId), + pickExtensionDirectory: (): Promise => + ipcRenderer.invoke('extension:pickDirectory'), + pickExtensionPackage: (): Promise => ipcRenderer.invoke('extension:pickPackage'), + installExtensionFromDirectory: (directory: string): Promise => + ipcRenderer.invoke('extension:installDirectory', directory), + installExtensionFromPackage: (packagePath: string): Promise => + ipcRenderer.invoke('extension:installPackage', packagePath), + setExtensionEnabled: (extensionId: string, enabled: boolean): Promise => + ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }), + uninstallExtension: (extensionId: string, keepData = true): Promise => + ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }), + getExtensionLogs: (extensionId: string, limit?: number): Promise => + ipcRenderer.invoke('extension:getLogs', { id: extensionId, limit }), + clearExtensionLogs: (extensionId: string): Promise<{ success: true }> => + ipcRenderer.invoke('extension:clearLogs', extensionId), + getExtensionPageUrl: (extensionId: string, pageId?: string): Promise => + ipcRenderer.invoke('extension:getPageUrl', { id: extensionId, pageId }), + extensionPageRequest: (request: ExtensionPageRequest): Promise => + ipcRenderer.invoke('extension:pageRequest', request), + openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> => + ipcRenderer.invoke('extension:openDataDir', extensionId), + onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => { + const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void => + callback(payload) + ipcRenderer.on('extension:changed', listener) + return () => ipcRenderer.removeListener('extension:changed', listener) + }, onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => { const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void => callback(state) diff --git a/src/renderer/index.html b/src/renderer/index.html index a06792c..d474c47 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -7,7 +7,7 @@ diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index af54c29..d0c52f3 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -46,6 +46,7 @@ import { Button, useToast } from './components/ui' import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt' import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace' import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace' +import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace' import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar' import { buildContactSearchIndex, @@ -2139,6 +2140,8 @@ function App(): React.ReactElement { ) case 'agent-hub': return + case 'extensions': + return case 'api': return ( ) + case 'extensions': + // 拼图:扩展是「往现有能力上加一块」,与自动化的闪电区分开。 + return ( + + ) case 'export': return (
    +
    + +
    + {descriptor.title} + {descriptor.extensionId} +
    + +
    +
    + {!loaded && ( +
    +

    {slow ? '页面尚未响应。扩展页面必须通过 tm.* 与宿主通信。' : '正在加载扩展页面…'}

    +
    + )} +