diff --git a/docs/agent/api.md b/docs/agent/api.md index 315c17c..e34682d 100644 --- a/docs/agent/api.md +++ b/docs/agent/api.md @@ -48,6 +48,7 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A | GET | `/api/v1/agent/status` | Agent Hub、连接器和数据库状态 | 无 | | POST | `/api/v1/agent/group-report` | 读取群聊并生成总结图片 | `{ "group": "群名或标识", "range": "today\|yesterday\|7days" }` | | POST | `/api/v1/agent/send` | 通过已连接机器人测试发送文字或本地图片 | `{ "to": "接收者", "text": "...", "media_url": "..." }` | +| POST | `/api/v1/wechat/send` | 用本机微信账号把消息发给别人 | `{ "to": "wxid 或 filehelper", "type": "text\|image\|voice", "text": "..." }` | | GET | `/api/v1/wechat-personal/send-capability` | 个人微信发送能力状态 | 无 | | GET | `/api/v1/scheduled-reports` | 定时日报任务列表 | 无 | | POST | `/api/v1/scheduled-reports` | 创建定时日报任务 | `ScheduledReportApiCreateRequest` JSON | @@ -76,6 +77,86 @@ Token 由应用生成并保存在本机,**不接受用环境变量覆盖**:A `/api/v1/query/*` 是一组结构化的 Query 端点,见下方[LLM-friendly Query Tool API](#llm-friendly-query-tool-api)。 +## 发送消息 API + +两个发送端点走**完全不同的通道**,用途也不同,不要混用。 + +| | `POST /api/v1/wechat/send` | `POST /api/v1/agent/send` | +| --- | --- | --- | +| 通道 | 本机微信(macOS native runtime / Windows hook) | Agent Hub 机器人(iLink) | +| 身份 | 你本人当前登录的微信账号 | 已扫码接入的机器人 | +| 用途 | **以你的身份把消息发给别人**(好友 / 群 / 文件传输助手) | **机器人给自己发通知**(测试连通性) | +| 前置条件 | 本机微信已启动,发送能力为 `ready` | 连接器为 `online` | +| 内容类型 | `text` / `image` / `voice`,媒体只接受本地文件 | `text` / `image`(URL 或本地路径) | +| 典型失败 | 能力未就绪 `503`、发送失败 `502` | 连接器离线 `503`、凭证过期 `401` | + +### 本地发送:`POST /api/v1/wechat/send` + +用你正在登录的微信账号发消息。**这是唯一能把消息发给别人(而不是发给机器人自己)的端点。** + +```bash +: "${TRACEMEMO_API_TOKEN:?Set TRACEMEMO_API_TOKEN from API Center}" +curl -X POST http://127.0.0.1:6131/api/v1/wechat/send \ + -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"to":"filehelper","type":"text","text":"来自 Agent 的一条消息"}' +``` + +请求体: + +| 字段 | 必填 | 说明 | +| --- | --- | --- | +| `to` | 是 | 接收者:好友 wxid、群 id(以 `@chatroom` 结尾),或 `filehelper`(文件传输助手)。**不做昵称解析**,先调 `/api/v1/resolve?q=张三` 换 wxid | +| `type` | 否 | `text`(默认)/ `image` / `voice` | +| `text` | `type=text` 时必填 | **最长 2000 字符**,超限返回 `400`,不会截断 | +| `filePath` | `type=image\|voice` 时必填 | 本机**绝对路径**,必须已存在。不接受 URL —— 需要发网络图片时先落盘 | +| `isGroup` | 否 | 通常可省略;`to` 以 `@chatroom` 结尾时自动判为群 | +| `idempotencyKey` | 否 | 幂等键。**重试时请原样带上**,避免 Agent 超时重发导致重复消息 | + +发送前会先校验当前发送能力(等价于 `GET /api/v1/wechat-personal/send-capability`):`ready=false` 时直接返回 `503`,不会进入投递;`capabilities[type]=false` 时返回 `503 SEND_NOT_READY`。 + +> **没有 3 秒节流。** 自动化规则(定时日报、退群通知)之间共享 3 秒发送间隔,但本端点属于手动发送,**不受该队列约束**:连续调用会连续投递。Agent 需要自行控制频率,不要用它循环刷消息。 + +响应: + +```json +{ + "success": true, + "status": "sent", + "actionId": "5f0c…", + "recipient": { "type": "contact", "id": "filehelper" }, + "contentType": "text", + "durationMs": 842 +} +``` + +| HTTP | `errorCode` | 含义 | +| --- | --- | --- | +| `400` | `INVALID_REQUEST` / `INVALID_RECIPIENT` | 字段缺失、`text` 超长、`filePath` 不存在 | +| `403` | `POLICY_BLOCKED` / `ACTION_NOT_ALLOWED` / `RECIPIENT_SCOPE_VIOLATION` | 发送策略拒绝 | +| `502` | `SEND_FAILED` | 已进入投递,底层发送失败(看 `error`) | +| `503` | `SEND_CAPABILITY_UNAVAILABLE` | 微信未启动 / 未绑定 / 未初始化 | +| `503` | `SEND_NOT_READY` | 能力在,但不支持该内容类型(例如语音 hook 未就绪) | +| `503` | `UNSUPPORTED_PLATFORM` | 非 macOS / Windows | +| `500` | `INTERNAL_ERROR` | 网关执行抛出未预期异常 | + +> **`status: "sent"` 只代表投递成功,不等于消息已写入本地数据库。** TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不会写入。因此不要用 `/api/v1/chatlog` 回查自己刚发的消息来判断是否发送成功 —— 查不到是正常现象;也**不要**因为本地库没有就重发,那会产生真实的重复消息。需要人工确认时,让对方用手机微信或另一个账号查看会话。 + +每一次发送都会写入 `actions/wechat-actions.json` 审计记录(`origin` 为 `http_api`),可在 Send Log 中核对。这份记录证明的是「调用过并成功投递」,**不能**证明对方已收到或本地库已落库。 + +### 机器人通知:`POST /api/v1/agent/send` + +走已扫码的 Agent Hub 连接器,给**自己**发一条测试消息,用于确认机器人链路是否通畅。它不适合「通知某人」这类场景 —— 那要用上面的 `/api/v1/wechat/send`。 + +```bash +curl -X POST http://127.0.0.1:6131/api/v1/agent/send \ + -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ + -H "Content-Type: application/json" \ + -d '{"to":"<你的 wxid>","text":"connector ok"}' +``` + +`to` 省略时回落到当前登录账号自己。`media_url` 可传 URL。连接器离线返回 `503`,凭证过期返回 `401`。 + ## Application Capabilities `GET /api/v1/capabilities` 描述 TraceMemo 应用级能力和当前运行环境;`GET /api/v1/query/capabilities` 只描述结构化 Query primitive,两者不是同一份目录。应用能力使用 `supported` 和 `available` 分开表示“代码支持”与“当前可用”;运行时原因使用稳定的简短 code,不返回 Token、数据库路径、微信密钥或 sender 诊断路径。 @@ -390,7 +471,7 @@ curl -X POST -H "$AUTH" -H 'Content-Type: application/json' "$BASE/query/voice-t Reader Skill 是随应用分发的说明文件。它被安装到 Agent 自己的 Skill 目录之后就与 TraceMemo 分离了,不再随应用升级自动变化,所以它必须能自己证明版本: -- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.3.0`); +- `SKILL.md` frontmatter 的 `version` 是**唯一真源**(形如 `1.4.0`); - `/api/v1/health` 的 `skill.version` 回报当前应用内置的版本; - 两者不一致,就说明 Agent 手里那份已经过期,接口契约可能已经变化。 @@ -405,8 +486,8 @@ curl http://127.0.0.1:6131/api/v1/health "ok": true, "ready": true, "service": "TraceMemo Reader", - "version": "2.5.0", - "skill": { "name": "tracememo-reader", "version": "1.3.0", "available": true }, + "version": "2.5.1", + "skill": { "name": "tracememo-reader", "version": "1.4.0", "available": true }, "timestamp": "2026-10-13T08:43:52.863Z" } ``` @@ -423,10 +504,10 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ ```json { "name": "tracememo-reader", - "version": "1.3.0", + "version": "1.4.0", "contentHash": "", "modifiedAt": "2026-10-13T08:37:30.000Z", - "markdown": "---\nname: tracememo-reader\nversion: 1.3.0\n…" + "markdown": "---\nname: tracememo-reader\nversion: 1.4.0\n…" } ``` diff --git a/docs/skill/tracememo-reader/SKILL.md b/docs/skill/tracememo-reader/SKILL.md index 2b0176f..47c1ff0 100644 --- a/docs/skill/tracememo-reader/SKILL.md +++ b/docs/skill/tracememo-reader/SKILL.md @@ -1,7 +1,7 @@ --- name: tracememo-reader -version: 1.3.0 -description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体,并管理定时日报任务。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。 +version: 1.4.0 +description: 通过 TraceMemo 本地 HTTP API 按需读取用户有权访问的微信聊天数据和图片媒体、管理定时日报任务,并用用户本机登录的微信账号发送消息。当用户要求查看微信消息、查找联系人或群聊、总结聊天、查看或理解图片、生成群聊总结、查询或修改定时日报、给好友或群发送微信消息、代发消息、查看发送记录时使用。此 Skill 由本机 TraceMemo 提供数据,不是 MCP Server。 --- # TraceMemo Reader @@ -76,6 +76,7 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ | POST | `/query/voice-transcribe` | 把指定语音消息转成文字(本机离线识别) | | GET | `/query/capabilities` | Query 端点能力目录 | | GET | `/wechat-personal/send-capability` | 个人微信发送能力状态(文字 / 图片 / 语音) | +| POST | `/wechat/send` | 用本机微信账号发消息给他人(文字/图片/语音) | | GET | `/scheduled-reports` | 查询全部定时日报任务 | | GET | `/scheduled-reports/:id` | 查询单个定时日报任务 | | POST | `/scheduled-reports` | 创建定时日报任务 | @@ -91,7 +92,68 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ | POST | `/agent/group-report` | 按群和 `today`/`yesterday`/`7days` 生成总结图片 | | POST | `/agent/send` | 已连接机器人发送测试(文字或本地图片) | -这个 API **不只是只读的**:`/report` 会渲染并写文件,`/agent/send` 会真的发出微信消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE` 与 `/agent/send` 尤其需要用户明确确认。 +这个 API **不只是只读的**:`/report` 会渲染并写文件,`/wechat/send` 会以用户本人的微信账号把消息真的发给别人,`/agent/send` 会通过机器人发出消息,`/scheduled-reports*` 会创建、修改、删除或立刻执行定时任务。这些调用都要先确认用户意图;`DELETE`、`/wechat/send` 与 `/agent/send` 尤其需要用户明确确认。 + +## 发送微信消息 + +两个发送端点的**身份和通道完全不同**,不要混用: + +| | `/wechat/send` | `/agent/send` | +| -------- | ------------------------------ | -------------------------------- | +| 发送身份 | 用户本机正在登录的微信账号 | 已扫码接入的 TraceMemo 机器人 | +| 收件人 | 好友 / 群 / 文件传输助手 | 一般是自己,用于测试连接器连通性 | +| 前置条件 | 本机微信已启动,发送能力 ready | Agent Hub 连接器 online | + +用户说“发消息给某人 / 某个群 / 文件传输助手”时,**只能用 `/wechat/send`**。`/agent/send` 不是用来通知别人的。 + +### 调用前必须做 + +1. 调用 `GET /wechat-personal/send-capability`,只有 `capability.ready === true` 且 `capability.capabilities[type] === true` 才继续。否则停下来说明需要先在 TraceMemo「设置 → 发送能力」里完成绑定,**不要**直接调用再解释失败。 +2. 通过 `/resolve` 把用户说的昵称换成 wxid;`to` 只接受 wxid、`xxx@chatroom` 群 id,或 `filehelper`。**不要猜 wxid,也不要把昵称直接写进 `to`。** +3. 把「发给谁 + 发什么」复述给用户并得到确认后再发。这是不可撤回的外部操作。 + +### 请求 + +```json +{ "to": "wxid_xxx", "type": "text", "text": "消息内容", "idempotencyKey": "可选" } +``` + +| 字段 | 必填 | 说明 | +| ---------------- | ------------------ | ------------------------------------------------------------------- | +| `to` | 是 | wxid / `xxx@chatroom` / `filehelper`;以 `@chatroom` 结尾自动判为群 | +| `type` | 否 | `text`(默认)/ `image` / `voice` | +| `text` | `type=text` 时必填 | **最多 2000 字符**,超限返回 `400`,不会自动截断 | +| `filePath` | `type=image/voice` | 本机**绝对路径**且文件必须存在;**不接受 URL** | +| `idempotencyKey` | 否 | 重试时原样带回,避免超时重发产生重复消息 | + +几个必须遵守的限制: + +- **超过 2000 字符不要硬发**。先告诉用户内容过长,征得同意后再拆成多条依次发送;不要静默截断。 +- **媒体只收本地文件**。用户给的是聊天里的图片时,先用 `/chatlog` 拿到 `media.url` 下载成临时文件,再把该路径传给 `filePath`;网络图片同样需要先落盘。不要试图传 URL。 +- **本端点没有节流**。automation 的 3 秒间隔对它不生效,连续调用就会连续投递。单个任务里连续发送超过 3 条前,先和用户确认节奏。 + +### 结果 + +成功返回 `success: true`、`status: "sent"`、`actionId`。失败时读 `errorCode`: + +- `400 INVALID_REQUEST` / `INVALID_RECIPIENT`:字段不合法,按 `error` 里的说明修正; +- `403 POLICY_BLOCKED`:被发送策略拒绝,如实告知用户; +- `502 SEND_FAILED`:已进入投递但微信侧失败,不要说成“已发送”; +- `503 SEND_CAPABILITY_UNAVAILABLE` / `SEND_NOT_READY`:能力未就绪,引导用户去绑定; +- `503 UNSUPPORTED_PLATFORM`:当前系统不支持。 + +只有 `status === "sent"` 才能告诉用户发送成功。不要凭 `actionId` 或 HTTP 200 之外的任何信息推断结果。 + +### 发送成功后不要用 `/chatlog` 自证 + +`status: "sent"` 只表示消息已经交给微信完成投递,**不代表它会出现在本地聊天数据库里**。TraceMemo 读的是微信本地库,自己发出的消息可能延迟落库,也可能根本不写入。 + +因此: + +- **不要**用 `/chatlog` 查自己刚发出的那条消息来确认发送成功。查不到是正常现象,不等于发送失败。 +- **不要**因为本地库没有这条消息就重发 —— 那会产生真实的重复消息。 +- 需要人工确认时,请用户用**手机微信**或**另一个微信号**查看该会话;这是唯一可靠的确认方式。 +- Send Log 与 `actions/wechat-actions.json` 记录的是 TraceMemo 自己的发送动作与结果,能证明“调用过并成功投递”,**不能**证明对方收到或本地库已落库。不要把它们混为一谈。 ## 定时日报管理 @@ -199,8 +261,8 @@ curl -H "Authorization: Bearer $TRACEMEMO_API_TOKEN" \ ## 常见错误 - `401`:Token 缺失、错误或被轮换;请用户回 API Center 复制最新 Token。 -- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。 +- `403`:浏览器 Origin 不在 loopback 允许列表;CLI/Agent 通常不带 Origin。注意 `/wechat/send` 的 `403 POLICY_BLOCKED` 是被发送策略拒绝,含义不同。 - `404`:会话查询失败时先用 `/resolve` 确认会话标识;媒体请求表示标识未登记、已过期、有歧义,或图片文件不存在(`NOT_FOUND`)。先重新读取 `/chatlog` 并使用新的 `media.url`;若仍失败,再检查本地图片文件是否存在。 - `422`:媒体标识格式错误,或消息不是可读取的图片(`NOT_IMAGE`)。 -- `503`:用户还没有完成数据库连接或对应服务未就绪。 +- `503`:用户还没有完成数据库连接或对应服务未就绪。发送端点返回 `503` 时先查 `/wechat-personal/send-capability`,不要反复重试。 - 空结果:缩小/扩大时间范围,确认账号和会话,再检查媒体或语音是否可读。 diff --git a/electron-builder.send-runtime.yml b/electron-builder.send-runtime.yml index 5162a30..21aac85 100644 --- a/electron-builder.send-runtime.yml +++ b/electron-builder.send-runtime.yml @@ -6,6 +6,10 @@ extraResources: to: resources filter: - '**/*' + - from: resources/wcdb/macos/arm64 + to: resources/wcdb/macos/arm64 + filter: + - 'tm-wcdb-config-helper' - from: docs/skill/tracememo-reader to: skill/tracememo-reader filter: diff --git a/src/main/http-server.ts b/src/main/http-server.ts index 1a55837..bcafe40 100644 --- a/src/main/http-server.ts +++ b/src/main/http-server.ts @@ -1,4 +1,5 @@ import crypto from 'crypto' +import { existsSync } from 'fs' import http, { IncomingMessage, ServerResponse, Server } from 'http' import { app } from 'electron' import { @@ -35,6 +36,9 @@ import { automationRuleStore, AutomationRulePersistenceError } from './services/ import { automationExecutionLogService } from './services/automation-execution-log-service' import { groupExitMonitorService } from './services/group-exit-monitor-service' import { LocalAgentApiError, LocalAgentApiService } from './services/local-agent-api-service' +import { wechatActionGateway } from './services/wechat-action-gateway' +import type { WechatActionRequest, WechatActionResult } from '../shared/wechat-action' +import type { PersonalWechatSendCapability } from '../shared/personal-wechat' import type { GroupStatsService } from './services/group-stats-service' import { encodeMessageRef } from '../shared/local-query-api' import type { @@ -77,6 +81,8 @@ export interface HttpServerOptions { agentApiService?: LocalAgentApiService groupStatsService?: Pick appVersionProvider?: () => string + wechatSendCapabilityProvider?: () => Promise + wechatSendExecutor?: (request: WechatActionRequest) => Promise } let configuredQueryApiService: LocalQueryApiService | undefined @@ -563,6 +569,298 @@ const routes: Record = { const SCHEDULED_REPORTS_ROUTE = '/api/v1/scheduled-reports' const WECHAT_SEND_CAPABILITY_ROUTE = '/api/v1/wechat-personal/send-capability' +const WECHAT_SEND_ROUTE = '/api/v1/wechat/send' + +/** + * 文本上限必须与 `wechat-action-gateway.ts` 的 `normalizeActionRequest` 一致, + * 否则本层放过的请求会被网关静默拒绝;在此先拦是为了返回实际长度。 + */ +const WECHAT_SEND_MAX_TEXT_LENGTH = 2_000 +const WECHAT_SEND_MAX_RECIPIENT_LENGTH = 512 +const WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH = 200 + +const WECHAT_SEND_CONTENT_TYPES = ['text', 'image', 'voice'] as const +type WechatSendContentType = (typeof WECHAT_SEND_CONTENT_TYPES)[number] + +interface WechatSendApiDependencies { + getCapability: () => Promise + execute: (request: WechatActionRequest) => Promise +} + +type ParsedWechatSend = + | { + ok: true + recipient: WechatActionRequest['recipient'] + content: WechatActionRequest['content'] + idempotencyKey?: string + } + | { ok: false; status: number; code: string; message: string } + +function readSendString(value: unknown): string { + return typeof value === 'string' ? value.trim() : '' +} + +/** + * 请求体 → Gateway 动作。 + * + * 字段在本层先校验:`WechatActionGateway` 对不合格请求只回一个 `INVALID_REQUEST`, + * 调用方拿不到具体是哪个字段的问题。 + */ +function parseWechatSendPayload(payload: unknown): ParsedWechatSend { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + return { ok: false, status: 400, code: 'INVALID_REQUEST', message: '请求体必须是 JSON 对象' } + } + const body = payload as Record + + const to = readSendString(body.to) + if (!to) { + return { + ok: false, + status: 400, + code: 'INVALID_RECIPIENT', + message: '缺少 to:接收者 wxid、群 id 或 filehelper' + } + } + if (to.length > WECHAT_SEND_MAX_RECIPIENT_LENGTH) { + return { + ok: false, + status: 400, + code: 'INVALID_RECIPIENT', + message: `to 长度 ${to.length} 超过上限 ${WECHAT_SEND_MAX_RECIPIENT_LENGTH} 字符` + } + } + if (body.isGroup !== undefined && typeof body.isGroup !== 'boolean') { + return { ok: false, status: 400, code: 'INVALID_REQUEST', message: 'isGroup 必须是布尔值' } + } + + const rawType = body.type === undefined ? 'text' : body.type + if ( + typeof rawType !== 'string' || + !WECHAT_SEND_CONTENT_TYPES.includes(rawType as WechatSendContentType) + ) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: `type 必须是 ${WECHAT_SEND_CONTENT_TYPES.join(' / ')} 之一` + } + } + const type = rawType as WechatSendContentType + + const rawKey = body.idempotencyKey + if (rawKey !== undefined && typeof rawKey !== 'string') { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: 'idempotencyKey 必须是字符串' + } + } + const idempotencyKey = readSendString(rawKey) + if (idempotencyKey.length > WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: `idempotencyKey 长度 ${idempotencyKey.length} 超过上限 ${WECHAT_SEND_MAX_IDEMPOTENCY_KEY_LENGTH} 字符` + } + } + + const recipient: WechatActionRequest['recipient'] = { + type: body.isGroup === true || to.endsWith('@chatroom') ? 'group' : 'contact', + id: to + } + + let content: WechatActionRequest['content'] + if (type === 'text') { + const text = typeof body.text === 'string' ? body.text.trim() : '' + if (!text) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: 'type=text 时 text 不能为空' + } + } + if (text.length > WECHAT_SEND_MAX_TEXT_LENGTH) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: `text 长度 ${text.length} 超过上限 ${WECHAT_SEND_MAX_TEXT_LENGTH} 字符` + } + } + content = { type: 'text', text } + } else { + const filePath = readSendString(body.filePath) + if (!filePath) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: `type=${type} 时 filePath 必填,且必须是本机绝对路径(不接受 URL)` + } + } + if (!existsSync(filePath)) { + return { + ok: false, + status: 400, + code: 'INVALID_REQUEST', + message: `filePath 指向的文件不存在:${filePath}` + } + } + content = { type, path: filePath } + } + + return { + ok: true, + recipient, + content, + ...(idempotencyKey ? { idempotencyKey } : {}) + } +} + +function wechatActionResultStatus(result: WechatActionResult): number { + if (result.status === 'sent') return 200 + switch (result.errorCode) { + case 'INVALID_REQUEST': + case 'INVALID_RECIPIENT': + return 400 + case 'ACTION_NOT_ALLOWED': + case 'POLICY_BLOCKED': + case 'RECIPIENT_SCOPE_VIOLATION': + return 403 + case 'SEND_CAPABILITY_UNAVAILABLE': + case 'SEND_NOT_READY': + return 503 + default: + return 502 + } +} + +function actionDurationMs(result: WechatActionResult): number { + const started = Date.parse(result.startedAt) + const finished = Date.parse(result.finishedAt) + if (!Number.isFinite(started) || !Number.isFinite(finished)) return 0 + return Math.max(0, finished - started) +} + +/** + * 本地个人微信发送:用本机登录的微信账号把消息发给**别人**(好友 / 群 / 文件传输助手)。 + * + * 与 `/api/v1/agent/send` 的区别是传输通道:这个端点走本机 runtime/hook, + * 不依赖 Agent Hub 连接器在线,也不消耗机器人身份。 + */ +function createWechatSendRoute( + pathname: string, + deps: WechatSendApiDependencies +): RouteHandler | undefined { + if (pathname !== WECHAT_SEND_ROUTE) return undefined + + return withMethods(['POST'], async ({ res, body }) => { + let payload: unknown + try { + payload = JSON.parse(typeof body === 'string' && body.trim() ? body : '{}') + } catch { + return sendWechatSendError(res, 400, 'INVALID_REQUEST', '请求体 JSON 解析失败') + } + + const parsed = parseWechatSendPayload(payload) + if (!parsed.ok) { + return sendWechatSendError(res, parsed.status, parsed.code, parsed.message) + } + + // 发送能力必须在真正投递前确认:否则失败只能等到 runtime 超时后才知道。 + let capability: PersonalWechatSendCapability + try { + capability = await deps.getCapability() + } catch (error) { + return sendWechatSendError( + res, + 503, + 'SEND_CAPABILITY_UNAVAILABLE', + '个人微信发送能力探测失败', + { reason: error instanceof Error ? error.message : String(error) } + ) + } + if (!capability.supported) { + return sendWechatSendError( + res, + 503, + 'UNSUPPORTED_PLATFORM', + capability.message || '当前平台不支持个人微信发送', + { capabilityStatus: capability.status } + ) + } + if (!capability.ready) { + return sendWechatSendError( + res, + 503, + 'SEND_CAPABILITY_UNAVAILABLE', + capability.message || '个人微信发送能力未就绪', + { + capabilityStatus: capability.status, + ...(capability.error ? { reason: capability.error } : {}) + } + ) + } + const contentType = parsed.content.type + if (!capability.capabilities[contentType]) { + const label = contentType === 'text' ? '文字' : contentType === 'image' ? '图片' : '语音' + return sendWechatSendError(res, 503, 'SEND_NOT_READY', `当前微信发送能力不支持发送${label}`, { + capabilityStatus: capability.status, + capabilities: capability.capabilities + }) + } + + let result: WechatActionResult + try { + result = await deps.execute({ + origin: 'http_api', + purpose: `api_${contentType}` as WechatActionRequest['purpose'], + triggerType: 'user', + recipient: parsed.recipient, + content: parsed.content, + ...(parsed.idempotencyKey ? { idempotencyKey: parsed.idempotencyKey } : {}) + }) + } catch (error) { + return sendWechatSendError(res, 500, 'INTERNAL_ERROR', '微信发送执行失败', { + reason: error instanceof Error ? error.message : String(error) + }) + } + + const status = wechatActionResultStatus(result) + sendJson(res, status, { + success: result.status === 'sent', + status: result.status, + actionId: result.actionId, + recipient: parsed.recipient, + contentType, + durationMs: actionDurationMs(result), + ...(result.errorCode ? { errorCode: result.errorCode } : {}), + ...(result.reason ? { error: result.reason } : {}) + }) + }) +} + +/** + * 发送端点的错误响应保持扁平:Agent 读 `errorCode` 就能分支, + * 不需要再往 `details` 里翻一层(`sendError` 的通用结构会多包一层)。 + */ +function sendWechatSendError( + res: ServerResponse, + status: number, + errorCode: string, + message: string, + extra?: Record +): void { + sendJson(res, status, { + success: false, + errorCode, + error: message, + ...(extra || {}) + }) +} function parseJsonBody(body: unknown): unknown { if (typeof body !== 'string' || !body.trim()) { @@ -1043,6 +1341,12 @@ export function startHttpServer( const scheduledReportApi = createScheduledReportApi(options) const queryApi = options.queryApiService || configuredQueryApiService || new LocalQueryApiService() const agentApi = createAgentApiService(options) + const wechatSendApi: WechatSendApiDependencies = { + getCapability: + options.wechatSendCapabilityProvider || + (() => personalWechatCapabilityService.getPersonalWechatSendCapability()), + execute: options.wechatSendExecutor || ((request) => wechatActionGateway.execute(request)) + } return new Promise((resolve, reject) => { const server: Server = http.createServer(async (req, res) => { const requestId = requestIdFor(req) @@ -1064,6 +1368,7 @@ export function startHttpServer( const handler = routes[url.pathname] || createAgentApiRoute(url.pathname, agentApi) || + createWechatSendRoute(url.pathname, wechatSendApi) || createScheduledReportRoute(url.pathname, scheduledReportApi) || (url.pathname.startsWith(QUERY_ROUTE_PREFIX) ? createQueryRoute(url.pathname, queryApi) diff --git a/src/shared/wechat-action.ts b/src/shared/wechat-action.ts index 5ee3d3d..709a0cc 100644 --- a/src/shared/wechat-action.ts +++ b/src/shared/wechat-action.ts @@ -16,6 +16,12 @@ export type WechatActionOrigin = * 也不进 Send Log —— 排查「消息到底发没发出去」时会缺一份证据。 */ | 'user_manual' + /** + * 外部 Agent 通过本地 HTTP API(`POST /api/v1/wechat/send`)发起的发送。 + * + * 与 `user_manual` 分开登记,审计记录才能区分人工点击与 Agent 调用。 + */ + | 'http_api' /** Automation(@我生成日报 / 退群通知)。与 `shared/automation.ts` 的 AUTOMATION_SEND_ORIGIN 一致。 */ | 'automation' | 'unknown' @@ -36,6 +42,10 @@ export type WechatActionPurpose = | 'manual_image' /** 用户手动发送文本。 */ | 'manual_text' + /** 外部 Agent 经本地 HTTP API 发送;按内容类型分开,便于审计统计。 */ + | 'api_text' + | 'api_image' + | 'api_voice' /** 用户确认后的日报图片;进入 automation 队列以复用 3 秒发送间隔。 */ | 'manual_report_image' /** 日报图片成功后的后置词;只有图片 sent 后才会创建。 */ diff --git a/tests/integration/wechat-send-api.test.ts b/tests/integration/wechat-send-api.test.ts new file mode 100644 index 0000000..4736aa6 --- /dev/null +++ b/tests/integration/wechat-send-api.test.ts @@ -0,0 +1,253 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +const root = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const fs = require('node:fs') as typeof import('node:fs') + // eslint-disable-next-line @typescript-eslint/no-require-imports + const os = require('node:os') as typeof import('node:os') + // eslint-disable-next-line @typescript-eslint/no-require-imports + const path = require('node:path') as typeof import('node:path') + return fs.mkdtempSync(path.join(os.tmpdir(), 'tracememo-wechat-send-api-')) +}) + +vi.mock('electron', () => ({ + app: { getPath: () => root, getVersion: () => 'test-version' }, + safeStorage: { + isEncryptionAvailable: () => true, + encryptString: (value: string) => Buffer.from(value, 'utf8'), + decryptString: (value: Buffer) => value.toString('utf8') + } +})) + +vi.mock('../../src/main/services/chat-service', () => ({ + isReady: () => true, + listContacts: () => [], + listContactsAsync: async () => [], + listMessages: () => [], + getGroupSnapshot: () => null, + listRecentChat: () => [], + resolveMd5: () => null +})) + +vi.mock('../../src/main/group-report-service', () => ({ exportGroupReport: vi.fn() })) +vi.mock('../../src/main/services/agent-group-report-service', () => ({ + generateAgentGroupReport: vi.fn() +})) +vi.mock('../../src/main/services/agent-hub-service', () => ({ + agentHubService: { + getStatus: () => ({ connector: 'offline' }), + testSend: vi.fn() + } +})) +vi.mock('../../src/main/services/group-exit-monitor-service', () => ({ + groupExitMonitorService: { + getState: () => ({ enabled: false, running: false, monitoredRoomIds: [] }) + } +})) +vi.mock('../../src/main/services/wechat-action-gateway', () => ({ + wechatActionGateway: { execute: vi.fn() } +})) + +import type { PersonalWechatSendCapability } from '../../src/shared/personal-wechat' +import type { WechatActionRequest, WechatActionResult } from '../../src/shared/wechat-action' +import type { LocalAgentApiService } from '../../src/main/services/local-agent-api-service' +import { startHttpServer, type HttpServerHandle } from '../../src/main/http-server' + +const TOKEN = 'T'.repeat(43) + +function capabilityOf( + overrides: Partial = {} +): PersonalWechatSendCapability { + return { + supported: true, + ready: true, + status: 'ready', + capabilities: { text: true, image: true, voice: true }, + senderStatus: {} as PersonalWechatSendCapability['senderStatus'], + message: '可以发送', + ...overrides + } +} + +function sentResult(overrides: Partial = {}): WechatActionResult { + return { + actionId: 'action-1', + status: 'sent', + decision: 'allow', + startedAt: '2026-10-20T00:00:00.000Z', + finishedAt: '2026-10-20T00:00:00.500Z', + ...overrides + } +} + +let handle: HttpServerHandle +let capability: PersonalWechatSendCapability +let executeResult: WechatActionResult +const execute = vi.fn() +const lastAction = (): WechatActionRequest => execute.mock.calls[0][0] as WechatActionRequest + +async function post(body: unknown, token: string | null = TOKEN): Promise { + return fetch(`http://${handle.host}:${handle.port}/api/v1/wechat/send`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(token ? { Authorization: `Bearer ${token}` } : {}) + }, + body: JSON.stringify(body) + }) +} + +beforeAll(async () => { + handle = await startHttpServer('127.0.0.1', 0, { + tokenProvider: () => TOKEN, + agentApiService: {} as LocalAgentApiService, + wechatSendCapabilityProvider: async () => capability, + wechatSendExecutor: execute + }) +}) + +afterAll(async () => { + await handle.close() + await fs.remove(root) +}) + +beforeEach(() => { + capability = capabilityOf() + executeResult = sentResult() + execute.mockReset() + execute.mockImplementation(async () => executeResult) +}) + +describe('POST /api/v1/wechat/send', () => { + it('未携带 Token 时返回 401', async () => { + const response = await post({ to: 'filehelper', text: 'hi' }, null) + expect(response.status).toBe(401) + expect(execute).not.toHaveBeenCalled() + }) + + it('缺少 to 时返回 400 且不进入投递', async () => { + const response = await post({ text: 'hi' }) + expect(response.status).toBe(400) + const body = await response.json() + expect(body.errorCode).toBe('INVALID_RECIPIENT') + expect(execute).not.toHaveBeenCalled() + }) + + it('text 超过 2000 字符时返回 400 并给出实际长度', async () => { + const response = await post({ to: 'filehelper', text: 'x'.repeat(2_001) }) + expect(response.status).toBe(400) + const body = await response.json() + expect(body.errorCode).toBe('INVALID_REQUEST') + expect(body.error).toContain('2001') + expect(execute).not.toHaveBeenCalled() + }) + + it('type 非法时返回 400', async () => { + const response = await post({ to: 'filehelper', type: 'video', text: 'hi' }) + expect(response.status).toBe(400) + expect((await response.json()).errorCode).toBe('INVALID_REQUEST') + }) + + it('媒体类型缺少 filePath 或文件不存在时返回 400', async () => { + const missing = await post({ to: 'filehelper', type: 'image' }) + expect(missing.status).toBe(400) + + const absent = await post({ + to: 'filehelper', + type: 'image', + filePath: path.join(root, 'no-such-image.png') + }) + expect(absent.status).toBe(400) + expect((await absent.json()).error).toContain('不存在') + expect(execute).not.toHaveBeenCalled() + }) + + it('发送能力未就绪时返回 503', async () => { + capability = capabilityOf({ + ready: false, + status: 'needs_binding', + message: '请先绑定个人微信' + }) + const response = await post({ to: 'filehelper', text: 'hi' }) + expect(response.status).toBe(503) + const body = await response.json() + expect(body.errorCode).toBe('SEND_CAPABILITY_UNAVAILABLE') + expect(body.capabilityStatus).toBe('needs_binding') + expect(execute).not.toHaveBeenCalled() + }) + + it('能力就绪但不支持该内容类型时返回 503 SEND_NOT_READY', async () => { + capability = capabilityOf({ capabilities: { text: true, image: false, voice: false } }) + const response = await post({ to: 'filehelper', type: 'voice', filePath: __filename }) + expect(response.status).toBe(503) + expect((await response.json()).errorCode).toBe('SEND_NOT_READY') + expect(execute).not.toHaveBeenCalled() + }) + + it('文本发送成功时以 http_api 来源经过 Gateway', async () => { + const response = await post({ to: 'filehelper', type: 'text', text: ' 你好 ' }) + expect(response.status).toBe(200) + const body = await response.json() + expect(body.success).toBe(true) + expect(body.actionId).toBe('action-1') + expect(body.recipient).toEqual({ type: 'contact', id: 'filehelper' }) + expect(body.durationMs).toBe(500) + + const action = lastAction() + expect(action.origin).toBe('http_api') + expect(action.purpose).toBe('api_text') + expect(action.triggerType).toBe('user') + expect(action.content).toEqual({ type: 'text', text: '你好' }) + }) + + it('type 省略时按文本发送', async () => { + await post({ to: 'wxid_friend', text: 'hi' }) + expect(lastAction().content).toEqual({ type: 'text', text: 'hi' }) + }) + + it('群 id 自动判定为 group', async () => { + await post({ to: 'room@chatroom', text: 'hi' }) + expect(lastAction().recipient).toEqual({ type: 'group', id: 'room@chatroom' }) + }) + + it('idempotencyKey 原样透传给 Gateway', async () => { + await post({ to: 'filehelper', text: 'hi', idempotencyKey: 'agent-run-42' }) + expect(lastAction().idempotencyKey).toBe('agent-run-42') + }) + + it('图片发送使用本地文件路径', async () => { + const imagePath = path.join(root, 'report.png') + await fs.writeFile(imagePath, 'png') + const response = await post({ to: 'filehelper', type: 'image', filePath: imagePath }) + expect(response.status).toBe(200) + expect(lastAction().content).toEqual({ type: 'image', path: imagePath }) + }) + + it('底层发送失败时返回 502 并带上 errorCode', async () => { + executeResult = sentResult({ + status: 'failed', + decision: 'allow', + errorCode: 'SEND_FAILED', + reason: '微信发送失败' + }) + const response = await post({ to: 'filehelper', text: 'hi' }) + expect(response.status).toBe(502) + const body = await response.json() + expect(body.success).toBe(false) + expect(body.errorCode).toBe('SEND_FAILED') + expect(body.error).toBe('微信发送失败') + }) + + it('策略拒绝时返回 403', async () => { + executeResult = sentResult({ + status: 'blocked', + decision: 'block', + errorCode: 'POLICY_BLOCKED', + reason: '该发送动作未通过策略检查' + }) + const response = await post({ to: 'filehelper', text: 'hi' }) + expect(response.status).toBe(403) + }) +}) diff --git a/tests/unit/wechat-action-gateway.test.ts b/tests/unit/wechat-action-gateway.test.ts index 37c7ac3..1701727 100644 --- a/tests/unit/wechat-action-gateway.test.ts +++ b/tests/unit/wechat-action-gateway.test.ts @@ -524,6 +524,35 @@ describe('WechatActionGateway', () => { expect(result.errorCode).toBe('INVALID_REQUEST') expect(mocks.sender.send).not.toHaveBeenCalled() }) + + it('放行 HTTP API 来源,并在审计里与人工发送区分开', async () => { + const userData = mkdtempSync(join(tmpdir(), 'tracememo-wechat-action-')) + directories.push(userData) + const gateway = new WechatActionGateway({ getUserDataPath: () => userData }) + + const result = await manualAction(gateway, { + origin: 'http_api', + purpose: 'api_text', + recipient: { type: 'contact', id: 'filehelper' }, + content: { type: 'text', text: '来自 Agent' } + }) + + expect(result).toMatchObject({ status: 'sent', decision: 'allow' }) + expect(mocks.sender.send).toHaveBeenCalledWith({ + type: 'text', + to: 'filehelper', + isGroup: false, + text: '来自 Agent' + }) + const audit = readJsonSync(join(userData, 'actions', 'wechat-actions.json')) + expect(audit[0]).toMatchObject({ + origin: 'http_api', + purpose: 'api_text', + triggerType: 'user', + recipientId: 'filehelper', + sendStatus: 'sent' + }) + }) }) describe('toPersonalWechatSendResult', () => {