pi-wechat-gateway 0.3.2 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +29 -0
- package/README.md +79 -16
- package/bin/pi-wechat-gateway.mjs +25 -0
- package/bin/ts-strip-loader.mjs +11 -0
- package/docs/demo.png +0 -0
- package/package.json +11 -6
- package/src/config.ts +7 -0
- package/src/deliver.ts +147 -0
- package/src/gateway.ts +8 -20
- package/src/main.ts +22 -48
- package/src/mcp.ts +247 -0
- package/src/status.ts +66 -0
- package/systemd/pi-wechat-gateway.service +2 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.4.0 — 2026-12-06
|
|
4
|
+
|
|
5
|
+
- **投递适配器(解耦 pi-mailbox)**:新增 `src/deliver.ts`,入站落点由 `PI_WECHAT_DELIVER` 决定。
|
|
6
|
+
`mailbox`(默认,线上 systemd 服务不变:在线进 `inbox/<pid>/`、离线落 `pending/`);
|
|
7
|
+
`queue` 落 `<stateDir>/inbox-queue/<slug>/<到达毫秒>-<seq>.json`(`slug`/`text`/`sentAt`/`arrivedAt`),
|
|
8
|
+
**不读 presence**,消费方拉走 = 原子 rename 到 `inbox-queue-read/<slug>/`。认不出的值一律当 `mailbox`。
|
|
9
|
+
- `status` 增加 `delivery: { mode, queue: { depth, slugs[] } }`;`status` 载荷抽到 `src/status.ts`,
|
|
10
|
+
CLI 与 MCP 共用同一份,不再各说一套。
|
|
11
|
+
- **stdio MCP server**:`pi-wechat-gateway mcp`,工具 `wechat_send` / `wechat_pull` / `wechat_status`。
|
|
12
|
+
协议照 `@earendil-works/pi-mcp@1.8.0` 客户端实现:换行分隔 JSON-RPC 2.0、`initialize` 回客户端
|
|
13
|
+
`SUPPORTED_PROTOCOL_VERSIONS` 里的版本、`tools/list` 带 `inputSchema`、`tools/call` 回 `{content:[...]}`、
|
|
14
|
+
`ping` 回 `{}`;零新增依赖。与 daemon 只通过 `stateDir` 里的文件协作(发送落 outbox,拉取 rename 队列)。
|
|
15
|
+
- **独立 CLI 包 / 打包可安装性**:`bin` 从 `src/main.ts` 改为 `bin/pi-wechat-gateway.mjs`(薄包装器:
|
|
16
|
+
`register()` + `stripTypeScriptTypes()` 擦类型后 import 源码)。原因实测:Node 拒绝剥离 node_modules 下的
|
|
17
|
+
`.ts`(`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`),原 bin 在 `npm i -g` 后必崩;仓库内
|
|
18
|
+
`node src/main.ts run`(systemd unit)与 `~/.local/bin` 软链路径不受影响。包装器 shebang 用
|
|
19
|
+
`--disable-warning=ExperimentalWarning` 定向压掉那一条警告(不用全局屏蔽)。`files` 补 `bin`/`docs`,
|
|
20
|
+
`keywords` 补 `mcp`/`cli`;`check` 脚本加包装器语法检查。
|
|
21
|
+
- **运行环境要求**:包装器依赖 `node:module` 的 `stripTypeScriptTypes`,需要带 TypeScript 支持的 Node 构建
|
|
22
|
+
(官方二进制 / fnm / pi 自带都行;实测 Debian/Ubuntu 发行版 `/usr/bin/node` 22.22.1 报 `ERR_NO_TYPESCRIPT`)。
|
|
23
|
+
遇到这种 Node 时包装器直接打出可执行文件与版本并 `exit 78`,不再抛无头异常。systemd unit 增加
|
|
24
|
+
`PI_WECHAT_DELIVER=queue`(入站进队列,由 `wechat_pull` 拉取)。
|
|
25
|
+
- README:npm 安装(含入口说明)、命令/退出码、`PI_WECHAT_DELIVER` 两种模式对照、MCP 工具表与
|
|
26
|
+
`mcp.json` 接线片段。
|
|
27
|
+
- 测试 53 → 73 条:新增 `test/deliver.test.mjs`(7)、`test/mcp.test.mjs`(10,含用 pi 客户端自己的
|
|
28
|
+
`McpClient` + `StdioTransport` 打通握手)、`test/npm-install.test.mjs`(2:真实
|
|
29
|
+
`npm pack → npm install → .bin/… status`+MCP 握手;以及「systemd unit 仍指 src/main.ts」的零变更门禁),
|
|
30
|
+
`config`/`ops` 各补默认模式与 status 的断言。
|
|
31
|
+
|
|
3
32
|
## 0.3.2 — 2026-12-06
|
|
4
33
|
|
|
5
34
|
- **发送返回体形状校验**:`realDeps.sendText` 调完第三方 `sendMessageWeixin` 后要求返回
|
package/README.md
CHANGED
|
@@ -1,7 +1,77 @@
|
|
|
1
1
|
# pi-wechat-gateway
|
|
2
2
|
|
|
3
|
-
**一条微信通道,多个 Pi
|
|
4
|
-
`
|
|
3
|
+
**一条微信通道,多个 Pi 会话**,一个**独立 CLI 包**(没有 pi 扩展面:装它不需要 Pi,也不需要 pi-mailbox)。
|
|
4
|
+
出站:任何程序往 `outbox/` 落一个 JSON,网关是唯一发送者;入站:网关按引用/前缀路由到某个 slug,再交给
|
|
5
|
+
**投递适配器**——默认写 `pi-mailbox` 信箱(装了 pi-mailbox 的会话直接进上下文),也可以切成纯文件队列
|
|
6
|
+
(`PI_WECHAT_DELIVER=queue`,任何进程/agent 自己来拉)。
|
|
7
|
+
|
|
8
|
+
## 安装
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm i -g pi-wechat-gateway # Node >= 22.19;无构建步骤(源码就是 .ts,Node 运行时擦类型)
|
|
12
|
+
pi-wechat-gateway login # 扫码配对(第一次必须做)
|
|
13
|
+
pi-wechat-gateway install # 写 systemd user 单元 + ~/.local/bin 符号链接并 enable
|
|
14
|
+
pi-wechat-gateway start
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
不装 systemd 也行:`pi-wechat-gateway run` 前台跑(一个账号只能有一个长轮询)。
|
|
18
|
+
|
|
19
|
+
**关于入口**:包里的 `bin` 是 `bin/pi-wechat-gateway.mjs`(薄包装器),它注册一个「擦类型」loader 再
|
|
20
|
+
`import ../src/main.ts`。之所以不能直接 `bin: src/main.ts`:Node 的类型剥离拒绝 node_modules 下的 `.ts`
|
|
21
|
+
(`ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING`),`npm i -g` 后 CLI 会直接崩(`test/npm-install.test.mjs`
|
|
22
|
+
把 `npm pack → npm install → status` 做成了门禁)。`node src/main.ts run`(systemd 单元走的就是它)不受影响。
|
|
23
|
+
pi-mailbox **不是**依赖:`mailbox` 模式下它存在就投进信箱,不存在就用 `queue` 模式。
|
|
24
|
+
|
|
25
|
+
## 命令
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pi-wechat-gateway status # 服务/心跳/凭据/投递模式+队列深度/outbox/pending(JSON)
|
|
29
|
+
pi-wechat-gateway send <slug> <text…> [--priority=digest|now|urgent] [--reply]
|
|
30
|
+
pi-wechat-gateway drain-once # 只跑一轮发送(排查发送失败用)
|
|
31
|
+
pi-wechat-gateway mcp # stdio MCP server(见下)
|
|
32
|
+
pi-wechat-gateway start|stop|restart [--wait=20]
|
|
33
|
+
pi-wechat-gateway login [--no-wait] | logout [--yes]
|
|
34
|
+
pi-wechat-gateway login-status | login-code <数字>
|
|
35
|
+
pi-wechat-gateway install | uninstall | run | help
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
**退出码**:`0` 成功 / `1` 操作失败 / `2` 用法错误或需要 `--yes` / `3` 无凭据 / `4` systemd 单元不可用或
|
|
39
|
+
第三方微信 SDK 接口不匹配(`run` 拒绝启动)。
|
|
40
|
+
|
|
41
|
+
## 入站投递:`PI_WECHAT_DELIVER`
|
|
42
|
+
|
|
43
|
+
| 值 | 行为 | 依赖 |
|
|
44
|
+
|---|---|---|
|
|
45
|
+
| `mailbox`(默认) | 路由后进 `pi-mailbox` 的 `inbox/<pid>/`;目标会话离线则落 `pending/`,上线后补投(积压消息自报年龄) | 需要 pi-mailbox 的 `presence/<pid>.json` 才能知道投给谁 |
|
|
46
|
+
| `queue` | 落 `<stateDir>/inbox-queue/<slug>/<到达毫秒>-<seq>.json`,含 `slug`/`text`/`sentAt`/`arrivedAt`;**不读 presence** | 无。消费方自己拉(MCP `wechat_pull`,或任何读文件的程序);拉走 = 原子 rename 到 `inbox-queue-read/<slug>/` |
|
|
47
|
+
|
|
48
|
+
认不出来的值一律当 `mailbox`(拼错不许静默改线上行为)。`status` 的 `delivery.mode` / `delivery.queue.depth`
|
|
49
|
+
就是当前模式与积压深度。
|
|
50
|
+
|
|
51
|
+
## MCP server(stdio)
|
|
52
|
+
|
|
53
|
+
`pi-wechat-gateway mcp` 起一个 stdio MCP server(协议照 `@earendil-works/pi-mcp` 客户端实现,零新增依赖):
|
|
54
|
+
stdout 只有换行分隔的 JSON-RPC 2.0,诊断一律进 stderr。它与 daemon 是**同一 `stateDir` 的两个进程,只通过文件协作**
|
|
55
|
+
(发送 = 落 outbox;拉取 = rename 队列文件),互不 import 运行时状态。
|
|
56
|
+
|
|
57
|
+
| 工具 | 参数 | 作用 |
|
|
58
|
+
|---|---|---|
|
|
59
|
+
| `wechat_send` | `slug` 或 `pid`(二选一)+ `text`,可选 `priority`/`reply` | 往 outbox 落一条,由 daemon 发出(`[slug]` 前缀) |
|
|
60
|
+
| `wechat_pull` | 可选 `slug`/`limit`(默认 20) | 拉 `inbox-queue` 里的入站消息并标记已读;前缀(含积压年龄)按拉取时刻算 |
|
|
61
|
+
| `wechat_status` | — | 与 CLI `status` 同一份 JSON 载荷 |
|
|
62
|
+
|
|
63
|
+
接进 pi 的配置片段(写进 `~/.pi/agent/mcp.json` 的 `mcpServers`,由 L0 接线):
|
|
64
|
+
|
|
65
|
+
```json
|
|
66
|
+
"wechat": {
|
|
67
|
+
"command": "pi-wechat-gateway",
|
|
68
|
+
"args": ["mcp"],
|
|
69
|
+
"env": { "PI_WECHAT_STATE": "/home/<you>/.pi/wechat", "PI_WECHAT_DELIVER": "queue" },
|
|
70
|
+
"description": "微信网关:wechat_send / wechat_pull / wechat_status"
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
注意:`wechat_pull` 只读 `queue` 模式的队列;`mailbox` 模式下入站直接进 pi-mailbox,队列为空。
|
|
5
75
|
|
|
6
76
|

|
|
7
77
|
|
|
@@ -27,10 +97,11 @@
|
|
|
27
97
|
路由:引用文本里的 [slug] > @slug > 最近一条 requiresReply > hub
|
|
28
98
|
│
|
|
29
99
|
▼
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
100
|
+
PI_WECHAT_DELIVER=mailbox(默认)
|
|
101
|
+
~/.pi/agent/mailbox/inbox/<pid>/*.json → pi-mailbox 扩展 → 该会话上下文
|
|
102
|
+
(目标会话离线)~/.pi/wechat/pending/<ts>-<seq>-<rand>.json → 上线后补投
|
|
103
|
+
PI_WECHAT_DELIVER=queue
|
|
104
|
+
~/.pi/wechat/inbox-queue/<slug>/<ts>-<seq>.json → wechat_pull / 任何读文件的程序
|
|
34
105
|
```
|
|
35
106
|
|
|
36
107
|
## 入站消息在会话里长什么样
|
|
@@ -50,7 +121,7 @@
|
|
|
50
121
|
- 落在信箱里的消息带 `expiresAt`(默认 12h):进程被杀后残留的旧消息不会被 pid 复用的新会话当「刚收到」,
|
|
51
122
|
pi-mailbox 见过期就扣下并写 `~/.pi/agent/mailbox/logs/expired.log`。
|
|
52
123
|
|
|
53
|
-
环境变量:`PI_WECHAT_STALE_AFTER_MS`(积压判定阈值,默认 600000)、
|
|
124
|
+
环境变量:`PI_WECHAT_DELIVER`(`mailbox`|`queue`,默认 `mailbox`)、`PI_WECHAT_STALE_AFTER_MS`(积压判定阈值,默认 600000)、
|
|
54
125
|
`PI_WECHAT_INBOX_TTL_MS`(信箱有效期,默认 12h,`0` = 不过期)、
|
|
55
126
|
`PI_WECHAT_THROTTLE_MS`(出站间隔,默认 1500)、`PI_WECHAT_POLL_TIMEOUT_MS`(长轮询超时,默认 35000)、
|
|
56
127
|
`PI_WECHAT_REPLY_TTL_MS`(「最近提问」路由有效期,默认 30min)。
|
|
@@ -68,15 +139,7 @@
|
|
|
68
139
|
- `requiresReply=true` 会把该会话记为「最近提问」:用户不引用、不带前缀直接回,也回到它(TTL 30 min);
|
|
69
140
|
- 发送失败重试 3 次后落 `failed/`,不丢证据。
|
|
70
141
|
|
|
71
|
-
##
|
|
72
|
-
|
|
73
|
-
装一次就够(写好 `~/.local/bin/pi-wechat-gateway` 符号链接 + systemd 单元并 enable):
|
|
74
|
-
|
|
75
|
-
```bash
|
|
76
|
-
pi-wechat-gateway install
|
|
77
|
-
```
|
|
78
|
-
|
|
79
|
-
日常:
|
|
142
|
+
## 日常运维(装好之后)
|
|
80
143
|
|
|
81
144
|
```bash
|
|
82
145
|
pi-wechat-gateway status # 服务/心跳/队列/凭据/在线会话/待投递(JSON)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env -S node --disable-warning=ExperimentalWarning
|
|
2
|
+
// npm 包的 bin 入口。它只做两件事:注册「擦类型」loader,然后 import 真正的 CLI(src/main.ts)。
|
|
3
|
+
//
|
|
4
|
+
// 为什么需要这一层:本包源码是 TypeScript,靠 Node 内置的类型剥离直接跑(没有构建步骤)。但 Node 对
|
|
5
|
+
// node_modules 下的 .ts 明确拒绝剥离(ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING),于是
|
|
6
|
+
// `bin: src/main.ts` 在 `npm i -g` 之后必崩(2026-12-06 实测,见 test/npm-install.test.mjs)。
|
|
7
|
+
// shebang 里的 --disable-warning 只压掉我们自己这次 stripTypeScriptTypes 的 ExperimentalWarning。
|
|
8
|
+
import { register } from "node:module";
|
|
9
|
+
|
|
10
|
+
try {
|
|
11
|
+
register("./ts-strip-loader.mjs", import.meta.url);
|
|
12
|
+
} catch (error) {
|
|
13
|
+
// 有的发行版 Node 编译时关掉了 TypeScript 支持(实测 Debian/Ubuntu 的 /usr/bin/node 22.22.1 报
|
|
14
|
+
// ERR_NO_TYPESCRIPT),官方二进制与 fnm/pi 自带 Node 都有。这里只把原因说清楚,不吞掉退出码。
|
|
15
|
+
if (error?.code === "ERR_NO_TYPESCRIPT" || /TypeScript support/.test(String(error?.message))) {
|
|
16
|
+
console.error(
|
|
17
|
+
"pi-wechat-gateway: 当前 Node 没有内置 TypeScript 支持(ERR_NO_TYPESCRIPT)。\n" +
|
|
18
|
+
"请用官方 Node 构建(nodejs.org / fnm / pi 自带)运行,或在 mcp.json/unit 里把 command 指到那样的 node。\n" +
|
|
19
|
+
`当前可执行文件:${process.execPath}(${process.version})`,
|
|
20
|
+
);
|
|
21
|
+
process.exit(78);
|
|
22
|
+
}
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
25
|
+
await import("../src/main.ts");
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// 让「装在 node_modules 里的 .ts」也能跑:Node 内置的类型剥离明确拒绝 node_modules 下的文件
|
|
2
|
+
// (ERR_UNSUPPORTED_NODE_MODULES_TYPE_STRIPPING),而本包的入口就是 src/main.ts(单一源码,没有构建步骤)。
|
|
3
|
+
// 这里用官方 API node:module 的 stripTypeScriptTypes 自己擦掉类型,Node 就不再走那条内部路径。
|
|
4
|
+
import { readFile } from "node:fs/promises";
|
|
5
|
+
import { stripTypeScriptTypes } from "node:module";
|
|
6
|
+
|
|
7
|
+
export async function load(url, context, nextLoad) {
|
|
8
|
+
if (!url.endsWith(".ts")) return nextLoad(url, context);
|
|
9
|
+
const source = await readFile(new URL(url), "utf8");
|
|
10
|
+
return { format: "module", source: stripTypeScriptTypes(source), shortCircuit: true };
|
|
11
|
+
}
|
package/docs/demo.png
ADDED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-wechat-gateway",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Standalone WeChat (iLink) CLI gateway: one WeChat channel for many Pi sessions — fans notifications in, routes replies back by quote/prefix, and exposes send/pull/status as an MCP stdio server. pi-mailbox is optional.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
7
7
|
"wechat",
|
|
8
8
|
"ilink",
|
|
9
9
|
"gateway",
|
|
10
|
-
"notifications"
|
|
10
|
+
"notifications",
|
|
11
|
+
"cli",
|
|
12
|
+
"mcp",
|
|
13
|
+
"model-context-protocol"
|
|
11
14
|
],
|
|
12
15
|
"type": "module",
|
|
13
16
|
"license": "MIT",
|
|
@@ -16,20 +19,22 @@
|
|
|
16
19
|
"node": ">=22.19.0"
|
|
17
20
|
},
|
|
18
21
|
"bin": {
|
|
19
|
-
"pi-wechat-gateway": "
|
|
22
|
+
"pi-wechat-gateway": "bin/pi-wechat-gateway.mjs"
|
|
20
23
|
},
|
|
21
24
|
"files": [
|
|
25
|
+
"bin",
|
|
22
26
|
"src",
|
|
23
27
|
"systemd",
|
|
28
|
+
"docs",
|
|
24
29
|
"README.md",
|
|
25
30
|
"CHANGELOG.md",
|
|
26
31
|
"LICENSE"
|
|
27
32
|
],
|
|
28
33
|
"scripts": {
|
|
29
34
|
"test": "node --test 'test/*.test.mjs'",
|
|
30
|
-
"check": "node --check
|
|
35
|
+
"check": "node --check bin/pi-wechat-gateway.mjs && node --input-type=module -e \"await import('./src/router.ts'); await import('./src/queue.ts'); console.log('check ok')\"",
|
|
31
36
|
"validate": "npm run test && npm run check && npm run smoke",
|
|
32
|
-
"smoke": "node --input-type=module -e \"const p = await import('./src/vendor-probe.ts'); if (typeof p.probeVendor !== 'function') throw new Error('vendor-probe: 未导出 probeVendor'); await import('./src/gateway.ts'); await import('./src/main.ts'); console.log('import smoke ok')\""
|
|
37
|
+
"smoke": "node --input-type=module -e \"const p = await import('./src/vendor-probe.ts'); if (typeof p.probeVendor !== 'function') throw new Error('vendor-probe: 未导出 probeVendor'); await import('./src/gateway.ts'); await import('./src/mcp.ts'); await import('./src/status.ts'); await import('./src/main.ts'); console.log('import smoke ok')\""
|
|
33
38
|
},
|
|
34
39
|
"dependencies": {
|
|
35
40
|
"@tencent-weixin/openclaw-weixin": "2.4.10",
|
package/src/config.ts
CHANGED
|
@@ -2,6 +2,8 @@ import fs from "node:fs";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
|
|
5
|
+
import { deliveryModeOf, type DeliveryMode } from "./deliver.ts";
|
|
6
|
+
|
|
5
7
|
export type GatewayConfig = {
|
|
6
8
|
baseUrl: string;
|
|
7
9
|
token: string;
|
|
@@ -10,6 +12,8 @@ export type GatewayConfig = {
|
|
|
10
12
|
stateDir: string;
|
|
11
13
|
credentialsFile: string;
|
|
12
14
|
credentialCleared: boolean;
|
|
15
|
+
/** 入站落点:mailbox = pi-mailbox 信箱(默认,线上在用);queue = 只写 stateDir/inbox-queue(不依赖 pi-mailbox)。 */
|
|
16
|
+
delivery: DeliveryMode;
|
|
13
17
|
mailboxDir: string;
|
|
14
18
|
presenceDir: string;
|
|
15
19
|
quietFrom: number; // 分钟数(0-1439)
|
|
@@ -104,6 +108,7 @@ export function loadConfig(): GatewayConfig {
|
|
|
104
108
|
stateDir,
|
|
105
109
|
credentialsFile,
|
|
106
110
|
credentialCleared: cleared,
|
|
111
|
+
delivery: deliveryModeOf(process.env.PI_WECHAT_DELIVER),
|
|
107
112
|
mailboxDir,
|
|
108
113
|
presenceDir: path.join(mailboxDir, "presence"),
|
|
109
114
|
quietFrom: parseClock(envStr("PI_WECHAT_QUIET_FROM", "23:40"), 23 * 60 + 40),
|
|
@@ -124,6 +129,8 @@ export function gwPaths(stateDir: string) {
|
|
|
124
129
|
sent: path.join(stateDir, "sent"),
|
|
125
130
|
failed: path.join(stateDir, "failed"),
|
|
126
131
|
pending: path.join(stateDir, "pending"),
|
|
132
|
+
inboxQueue: path.join(stateDir, "inbox-queue"),
|
|
133
|
+
inboxQueueRead: path.join(stateDir, "inbox-queue-read"),
|
|
127
134
|
sync: path.join(stateDir, "sync.json"),
|
|
128
135
|
context: path.join(stateDir, "context-tokens.json"),
|
|
129
136
|
heartbeat: path.join(stateDir, "heartbeat.json"),
|
package/src/deliver.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 入站投递适配器:网关只负责把消息路由到 slug,落点由 `PI_WECHAT_DELIVER` 决定。
|
|
3
|
+
*
|
|
4
|
+
* mailbox(默认)pi-mailbox 文件信箱:会话在线进 `inbox/<pid>/`,离线落 `pending/`。
|
|
5
|
+
* 线上 systemd 服务正在跑的就是这条,不能改默认值。
|
|
6
|
+
* queue `stateDir/inbox-queue/<slug>/<到达毫秒>-<seq>-<rand>.json`:**不读 presence**,
|
|
7
|
+
* 消费方(MCP `wechat_pull` 或任何读文件的程序)自己拉走;拉走 = 原子 rename 到
|
|
8
|
+
* `inbox-queue-read/`,两个消费者抢同一条也只会有一个人拿到。
|
|
9
|
+
*
|
|
10
|
+
* 两种模式都只写自己那份文件,进程之间没有共享内存:daemon 与 MCP server 只通过文件协作。
|
|
11
|
+
*/
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
import type { GatewayConfig } from "./config.ts";
|
|
16
|
+
import { drainPending, findPidForSlug, deliverInbox, writePending } from "./mailbox.ts";
|
|
17
|
+
import { formatInbound } from "./router.ts";
|
|
18
|
+
|
|
19
|
+
export type DeliveryMode = "mailbox" | "queue";
|
|
20
|
+
|
|
21
|
+
/** 认不出来的值一律回 mailbox:默认值错了会直接改掉线上行为。 */
|
|
22
|
+
export function deliveryModeOf(value: unknown): DeliveryMode {
|
|
23
|
+
return String(value ?? "").trim().toLowerCase() === "queue" ? "queue" : "mailbox";
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type DeliveryOutcome = { file: string; via: "inbox" | "pending" | "queue" };
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 投递一条已路由的入站消息。`text` 是**原始正文**(不带前缀):
|
|
30
|
+
* mailbox 直接投时按此刻年龄加前缀;离线和 queue 都存原文,由消费方在投递那一刻重算(积压标记才不会说谎)。
|
|
31
|
+
*/
|
|
32
|
+
export function deliverInbound(
|
|
33
|
+
cfg: Pick<GatewayConfig, "delivery" | "stateDir" | "presenceDir" | "mailboxDir" | "inboxTtlMs" | "staleAfterMs">,
|
|
34
|
+
msg: { slug: string; text: string; now: Date; sentAt: Date },
|
|
35
|
+
): DeliveryOutcome {
|
|
36
|
+
if (cfg.delivery === "queue") {
|
|
37
|
+
const file = writeQueuedInbound(path.join(cfg.stateDir, "inbox-queue"), {
|
|
38
|
+
slug: msg.slug,
|
|
39
|
+
text: msg.text,
|
|
40
|
+
sentAt: msg.sentAt.toISOString(),
|
|
41
|
+
arrivedAt: msg.now.toISOString(),
|
|
42
|
+
});
|
|
43
|
+
return { file, via: "queue" };
|
|
44
|
+
}
|
|
45
|
+
const pid = findPidForSlug(cfg.presenceDir, msg.slug);
|
|
46
|
+
if (pid) {
|
|
47
|
+
const body = formatInbound(msg.text, { now: msg.now, sentAt: msg.sentAt, staleAfterMs: cfg.staleAfterMs });
|
|
48
|
+
return { file: deliverInbox(cfg.mailboxDir, pid, body, `wechat:${msg.slug}`, { now: msg.now, ttlMs: cfg.inboxTtlMs }), via: "inbox" };
|
|
49
|
+
}
|
|
50
|
+
return { file: writePending(path.join(cfg.stateDir, "pending"), { slug: msg.slug, text: msg.text, at: msg.now.toISOString(), sentAt: msg.sentAt.toISOString() }), via: "pending" };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** mailbox 模式的补投(会话上线后把 pending 送进信箱);queue 模式没有 pending 概念。 */
|
|
54
|
+
export function drainDelivered(cfg: GatewayConfig, now: Date): string[] {
|
|
55
|
+
if (cfg.delivery !== "mailbox") return [];
|
|
56
|
+
return drainPending(path.join(cfg.stateDir, "pending"), cfg.presenceDir, cfg.mailboxDir, {
|
|
57
|
+
now,
|
|
58
|
+
staleAfterMs: cfg.staleAfterMs,
|
|
59
|
+
inboxTtlMs: cfg.inboxTtlMs,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// ---------------------------------------------------------------- queue 落盘
|
|
64
|
+
|
|
65
|
+
/** `text` 是原始正文;`sentAt` 是微信里的发送时刻,`arrivedAt` 是网关收到/落盘时刻。 */
|
|
66
|
+
export type QueuedInbound = { slug: string; text: string; sentAt: string; arrivedAt: string };
|
|
67
|
+
|
|
68
|
+
export type QueuedEntry = { file: string; slug: string; item: QueuedInbound };
|
|
69
|
+
|
|
70
|
+
// 同一毫秒落多条时靠自增序号定顺序(文件名以到达毫秒开头,重启后仍然可比)
|
|
71
|
+
let queueSeq = 0;
|
|
72
|
+
const nextSeq = (): string => String(queueSeq++).padStart(6, "0");
|
|
73
|
+
|
|
74
|
+
export function writeQueuedInbound(queueDir: string, item: QueuedInbound): string {
|
|
75
|
+
const dir = path.join(queueDir, item.slug);
|
|
76
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
77
|
+
const name = `${Date.parse(item.arrivedAt) || Date.now()}-${nextSeq()}-${Math.random().toString(36).slice(2, 6)}.json`;
|
|
78
|
+
const file = path.join(dir, name);
|
|
79
|
+
const tmp = `${file}.tmp`;
|
|
80
|
+
fs.writeFileSync(tmp, `${JSON.stringify(item, null, 2)}\n`);
|
|
81
|
+
fs.renameSync(tmp, file);
|
|
82
|
+
return file;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** 队列里的消息,按到达时间升序(跨 slug 也按到达时间排)。坏文件跳过,不阻塞其它消息。 */
|
|
86
|
+
export function listQueuedInbound(queueDir: string): QueuedEntry[] {
|
|
87
|
+
let dirs: fs.Dirent[];
|
|
88
|
+
try {
|
|
89
|
+
dirs = fs.readdirSync(queueDir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.name.startsWith("."));
|
|
90
|
+
} catch {
|
|
91
|
+
return [];
|
|
92
|
+
}
|
|
93
|
+
const out: QueuedEntry[] = [];
|
|
94
|
+
for (const dir of dirs) {
|
|
95
|
+
let files: string[];
|
|
96
|
+
try {
|
|
97
|
+
files = fs.readdirSync(path.join(queueDir, dir.name)).filter((f) => f.endsWith(".json"));
|
|
98
|
+
} catch {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
for (const f of files) {
|
|
102
|
+
const file = path.join(queueDir, dir.name, f);
|
|
103
|
+
try {
|
|
104
|
+
const item = JSON.parse(fs.readFileSync(file, "utf8")) as QueuedInbound;
|
|
105
|
+
if (!item?.slug || typeof item.text !== "string") continue;
|
|
106
|
+
out.push({ file, slug: item.slug, item });
|
|
107
|
+
} catch {
|
|
108
|
+
/* 坏文件跳过:一条垃圾不该挡住整个队列 */
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
out.sort((a, b) => (Date.parse(a.item.arrivedAt) || 0) - (Date.parse(b.item.arrivedAt) || 0) || a.file.localeCompare(b.file));
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** 拉走一条:rename 进 `readDir/<slug>/`。并发下只有一个调用者能成功(rename 是原子的)。 */
|
|
117
|
+
export function claimQueuedInbound(entry: QueuedEntry, readDir: string): string | null {
|
|
118
|
+
const dir = path.join(readDir, entry.slug);
|
|
119
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
120
|
+
const target = path.join(dir, path.basename(entry.file));
|
|
121
|
+
try {
|
|
122
|
+
fs.renameSync(entry.file, target);
|
|
123
|
+
return target;
|
|
124
|
+
} catch {
|
|
125
|
+
return null; // 别人先拉走了
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export type QueueDepth = { depth: number; slugs: Array<{ slug: string; count: number; oldestAgeSec: number | null }> };
|
|
130
|
+
|
|
131
|
+
/** status 用:队列深度 + 每个 slug 最新一条等了多久(压着没人拉的消息要看得出来)。 */
|
|
132
|
+
export function queueDepth(queueDir: string, now: number = Date.now()): QueueDepth {
|
|
133
|
+
const byslug = new Map<string, { count: number; oldest: number | null }>();
|
|
134
|
+
for (const entry of listQueuedInbound(queueDir)) {
|
|
135
|
+
const at = Date.parse(entry.item.arrivedAt);
|
|
136
|
+
const cur = byslug.get(entry.slug) ?? { count: 0, oldest: null };
|
|
137
|
+
cur.count += 1;
|
|
138
|
+
if (Number.isFinite(at) && (cur.oldest === null || at < cur.oldest)) cur.oldest = at;
|
|
139
|
+
byslug.set(entry.slug, cur);
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
depth: [...byslug.values()].reduce((n, v) => n + v.count, 0),
|
|
143
|
+
slugs: [...byslug.entries()]
|
|
144
|
+
.sort((a, b) => a[0].localeCompare(b[0]))
|
|
145
|
+
.map(([slug, v]) => ({ slug, count: v.count, oldestAgeSec: v.oldest === null ? null : Math.max(0, Math.round((now - v.oldest) / 1000)) })),
|
|
146
|
+
};
|
|
147
|
+
}
|
package/src/gateway.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* 网关主循环:**唯一**持有 iLink 长轮询的进程。
|
|
3
3
|
*
|
|
4
|
-
* 微信 → 路由(引用/前缀/最近提问/hub)→
|
|
4
|
+
* 微信 → 路由(引用/前缀/最近提问/hub)→ 投递适配器(mailbox | queue,见 src/deliver.ts)
|
|
5
5
|
* 会话 → outbox 文件 → 网关发送(节流、免打扰、失败重试)
|
|
6
6
|
*
|
|
7
7
|
* 协议原语来自腾讯官方 `@tencent-weixin/openclaw-weixin`(MIT)的纯协议模块;
|
|
@@ -12,10 +12,10 @@ import path from "node:path";
|
|
|
12
12
|
|
|
13
13
|
import type { GatewayConfig } from "./config.ts";
|
|
14
14
|
import { gwPaths } from "./config.ts";
|
|
15
|
+
import { drainDelivered, deliverInbound } from "./deliver.ts";
|
|
15
16
|
import { ensureDirs, listOutbox, claim, finish, readItem, type OutboxItem } from "./queue.ts";
|
|
16
17
|
import { cursorBelongsToBot, importContextTokens, importCursor, type LegacyCursor, type LegacyTokens } from "./migrate.ts";
|
|
17
|
-
import {
|
|
18
|
-
import { formatInbound, formatOutbound, mergeDigest, priorityOf, routeInbound, shouldSend, trustedSentAt, type Priority } from "./router.ts";
|
|
18
|
+
import { formatOutbound, mergeDigest, priorityOf, routeInbound, shouldSend, trustedSentAt, type Priority } from "./router.ts";
|
|
19
19
|
|
|
20
20
|
const MAX_ATTEMPTS = 3;
|
|
21
21
|
|
|
@@ -190,26 +190,17 @@ export function handleInbound(cfg: GatewayConfig, msg: WeixinMsg, state: Gateway
|
|
|
190
190
|
// 发送时刻优先用消息自带的 create_time_ms(网关停机后补回的历史消息靠它认年龄),不可信才用收到时刻
|
|
191
191
|
const sentAtMs = sentAtOf(msg, now);
|
|
192
192
|
const sentAt = new Date(sentAtMs ?? now.getTime());
|
|
193
|
-
const
|
|
194
|
-
const p = gwPaths(cfg.stateDir);
|
|
195
|
-
const pid = findPidForSlug(cfg.presenceDir, route.slug);
|
|
196
|
-
let file: string;
|
|
197
|
-
if (pid) {
|
|
198
|
-
file = deliverInbox(cfg.mailboxDir, pid, body, `wechat:${route.slug}`, { now, ttlMs: cfg.inboxTtlMs });
|
|
199
|
-
} else {
|
|
200
|
-
// 存原始正文 + 发送时刻:投递时按当时年龄重算前缀(不会把压了一晚的消息当刚发的)
|
|
201
|
-
file = writePending(p.pending, { slug: route.slug, text: route.body, at: now.toISOString(), sentAt: sentAt.toISOString() });
|
|
202
|
-
}
|
|
193
|
+
const delivered = deliverInbound(cfg, { slug: route.slug, text: route.body, now, sentAt });
|
|
203
194
|
// 定向回复(引用/前缀)消费掉「最近提问」;落到 hub 则保持
|
|
204
195
|
if (route.reason === "quote" || route.reason === "prefix") state.pending = undefined;
|
|
205
196
|
deps.log("inbound", {
|
|
206
197
|
slug: route.slug,
|
|
207
198
|
reason: route.reason,
|
|
208
|
-
|
|
199
|
+
via: delivered.via,
|
|
209
200
|
chars: route.body.length,
|
|
210
201
|
ageMs: Math.max(0, now.getTime() - sentAt.getTime()),
|
|
211
202
|
});
|
|
212
|
-
return { slug: route.slug, file };
|
|
203
|
+
return { slug: route.slug, file: delivered.file };
|
|
213
204
|
}
|
|
214
205
|
|
|
215
206
|
// ---------------------------------------------------------------- 出站
|
|
@@ -387,16 +378,13 @@ export async function runGateway(cfg: GatewayConfig, deps: GatewayDeps, signal?:
|
|
|
387
378
|
|
|
388
379
|
const sent = await drainOutbox(cfg, state, deps);
|
|
389
380
|
saveState(p, state);
|
|
390
|
-
const delivered =
|
|
391
|
-
now: deps.now(),
|
|
392
|
-
staleAfterMs: cfg.staleAfterMs,
|
|
393
|
-
inboxTtlMs: cfg.inboxTtlMs,
|
|
394
|
-
});
|
|
381
|
+
const delivered = drainDelivered(cfg, deps.now());
|
|
395
382
|
saveJson(p.heartbeat, {
|
|
396
383
|
at: new Date().toISOString(),
|
|
397
384
|
pid: process.pid,
|
|
398
385
|
pollOkAt: lastPollOk ? new Date(lastPollOk).toISOString() : null,
|
|
399
386
|
sent,
|
|
387
|
+
delivery: cfg.delivery,
|
|
400
388
|
pendingDelivered: delivered,
|
|
401
389
|
pendingOutbox: listOutbox(p.outbox).length,
|
|
402
390
|
pendingReply: state.pending ?? null,
|
package/src/main.ts
CHANGED
|
@@ -21,17 +21,17 @@ import path from "node:path";
|
|
|
21
21
|
import { fileURLToPath } from "node:url";
|
|
22
22
|
|
|
23
23
|
import { gwPaths, loadConfig } from "./config.ts";
|
|
24
|
-
import { ensureDirs,
|
|
25
|
-
import { listPresence } from "./mailbox.ts";
|
|
24
|
+
import { ensureDirs, writeOutbox } from "./queue.ts";
|
|
26
25
|
import { readLogin, sendVerifyCode, startLogin } from "./login.ts";
|
|
27
26
|
import { drainOutbox, realDeps, runGateway, type GatewayDeps } from "./gateway.ts";
|
|
28
27
|
import { priorityOf } from "./router.ts";
|
|
29
28
|
import { renderQr } from "./qr.ts";
|
|
29
|
+
import { serveMcp } from "./mcp.ts";
|
|
30
|
+
import { buildStatus } from "./status.ts";
|
|
30
31
|
import { reportVendorProbe } from "./vendor-probe.ts";
|
|
31
32
|
import {
|
|
32
33
|
UNIT,
|
|
33
34
|
clearCredentials,
|
|
34
|
-
heartbeatFresh,
|
|
35
35
|
readClearedMarker,
|
|
36
36
|
removeClearedMarker,
|
|
37
37
|
systemctl,
|
|
@@ -290,46 +290,7 @@ async function main(): Promise<number> {
|
|
|
290
290
|
const p = gwPaths(cfg.stateDir);
|
|
291
291
|
|
|
292
292
|
if (cmd === "status") {
|
|
293
|
-
|
|
294
|
-
const hb = heartbeatFresh(p.heartbeat);
|
|
295
|
-
const out = {
|
|
296
|
-
service: { unit: UNIT, installed, active: installed && unitActive() },
|
|
297
|
-
heartbeat: readJson(p.heartbeat),
|
|
298
|
-
heartbeatFresh: hb.fresh,
|
|
299
|
-
heartbeatAgeSec: hb.ageMs === null ? null : Math.round(hb.ageMs / 1000),
|
|
300
|
-
credentials: {
|
|
301
|
-
file: cfg.credentialsFile,
|
|
302
|
-
user: cfg.userId,
|
|
303
|
-
baseUrl: cfg.baseUrl,
|
|
304
|
-
cleared: readClearedMarker(cfg.stateDir),
|
|
305
|
-
ok: Boolean(cfg.token),
|
|
306
|
-
},
|
|
307
|
-
login: readLogin(cfg.stateDir),
|
|
308
|
-
outbox: listOutbox(p.outbox).length,
|
|
309
|
-
// 收不到消息时先看这里:路由命中了但目标会话不在名册(pi-mailbox presence)就会停在这
|
|
310
|
-
// 每条带 slug 与等了多久:压在 pending 里一夜的消息会被当「积压」补投
|
|
311
|
-
pending: (() => {
|
|
312
|
-
try {
|
|
313
|
-
return fs
|
|
314
|
-
.readdirSync(p.pending)
|
|
315
|
-
.filter((f) => f.endsWith(".json"))
|
|
316
|
-
.map((f) => {
|
|
317
|
-
try {
|
|
318
|
-
const item = JSON.parse(fs.readFileSync(path.join(p.pending, f), "utf8")) as { slug?: string; at?: string; sentAt?: string };
|
|
319
|
-
const at = Date.parse(String(item.sentAt ?? item.at ?? "")) || 0;
|
|
320
|
-
return { slug: item.slug ?? f.replace(/\.json$/, ""), ageSec: at ? Math.round((Date.now() - at) / 1000) : null };
|
|
321
|
-
} catch {
|
|
322
|
-
return { file: f };
|
|
323
|
-
}
|
|
324
|
-
});
|
|
325
|
-
} catch {
|
|
326
|
-
return [];
|
|
327
|
-
}
|
|
328
|
-
})(),
|
|
329
|
-
online: listPresence(cfg.presenceDir).map((x) => ({ pid: x.pid, cwd: x.cwd })),
|
|
330
|
-
quiet: `${String(Math.floor(cfg.quietFrom / 60)).padStart(2, "0")}:${String(cfg.quietFrom % 60).padStart(2, "0")}–${String(Math.floor(cfg.quietTo / 60)).padStart(2, "0")}:${String(cfg.quietTo % 60).padStart(2, "0")}`,
|
|
331
|
-
};
|
|
332
|
-
console.log(JSON.stringify(out, null, 2));
|
|
293
|
+
console.log(JSON.stringify(buildStatus(cfg), null, 2));
|
|
333
294
|
return 0;
|
|
334
295
|
}
|
|
335
296
|
|
|
@@ -372,6 +333,12 @@ async function main(): Promise<number> {
|
|
|
372
333
|
return 0;
|
|
373
334
|
}
|
|
374
335
|
|
|
336
|
+
if (cmd === "mcp") {
|
|
337
|
+
// stdio MCP server:stdout 只走 JSON-RPC,日志/诊断一律进 stderr(否则客户端解析器会把日志当协议帧)
|
|
338
|
+
await serveMcp();
|
|
339
|
+
return 0;
|
|
340
|
+
}
|
|
341
|
+
|
|
375
342
|
if (cmd === "login-status") {
|
|
376
343
|
console.log(JSON.stringify(readLogin(cfg.stateDir), null, 2));
|
|
377
344
|
return 0;
|
|
@@ -423,14 +390,21 @@ async function main(): Promise<number> {
|
|
|
423
390
|
|
|
424
391
|
// 只有被直接执行时才跑:`import('./src/main.ts')`(单测/自检)绝不能顺手拉起真网关。
|
|
425
392
|
// 命令行走 ~/.local/bin 的符号链接进来:必须 realpath,否则「被直接执行」判不出来(会静默什么都不做)。
|
|
393
|
+
// 第二条入口是 npm 包的 bin(`bin/pi-wechat-gateway.mjs`):它 import 本文件,argv[1] 指向包装器而不是
|
|
394
|
+
// 本文件,但那仍然是「人跑这个 CLI」,与 import 自检要区分开。
|
|
426
395
|
const selfPath = fileURLToPath(import.meta.url);
|
|
396
|
+
const binPath = fileURLToPath(new URL("../bin/pi-wechat-gateway.mjs", import.meta.url));
|
|
427
397
|
const invokedDirectly = (() => {
|
|
428
398
|
if (!process.argv[1]) return false;
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
399
|
+
const resolveReal = (p: string): string => {
|
|
400
|
+
try {
|
|
401
|
+
return fs.realpathSync(path.resolve(p));
|
|
402
|
+
} catch {
|
|
403
|
+
return path.resolve(p);
|
|
404
|
+
}
|
|
405
|
+
};
|
|
406
|
+
const argv1 = resolveReal(process.argv[1]);
|
|
407
|
+
return argv1 === selfPath || argv1 === binPath;
|
|
434
408
|
})();
|
|
435
409
|
if (invokedDirectly) {
|
|
436
410
|
main()
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* stdio MCP server(子命令 `pi-wechat-gateway mcp`):把网关的两条文件通道暴露成 MCP 工具。
|
|
3
|
+
*
|
|
4
|
+
* 协议按 pi 客户端(`@earendil-works/pi-mcp@1.8.0`)的实现对齐,零新增依赖:
|
|
5
|
+
* - stdio 分帧 = **换行分隔的 JSON-RPC 2.0**(`dist/transports/lines.js`:按 `\n` 切、容忍 `\r`),
|
|
6
|
+
* 不是 LSP 的 `Content-Length` 头;
|
|
7
|
+
* - 握手是 `initialize` → 结果必须是 `{ protocolVersion, capabilities, serverInfo{name,version} }`,
|
|
8
|
+
* 且 `protocolVersion` 必须落在客户端的 `SUPPORTED_PROTOCOL_VERSIONS` 里
|
|
9
|
+
* (`dist/protocol/types.js`:2025-11-25 / 2025-06-18 / 2025-03-26 / 2024-11-05),随后客户端发
|
|
10
|
+
* `notifications/initialized`;
|
|
11
|
+
* - `tools/list` 每项 `{ name, description, inputSchema }`;`tools/call` 结果 `{ content: [{type:"text",text}] }`
|
|
12
|
+
* (`content` 缺失/非数组会被客户端判为 Invalid MCP tools/call result);
|
|
13
|
+
* - 客户端的 `ping` 要答 `{}`。
|
|
14
|
+
*
|
|
15
|
+
* 与 daemon 的协作**只通过文件**:发送 = 往 `<stateDir>/outbox` 落一个 JSON(daemon 是唯一发送者);
|
|
16
|
+
* 拉取 = 把 `<stateDir>/inbox-queue/<slug>/*.json` 原子 rename 进 `inbox-queue-read/`。
|
|
17
|
+
* 本文件不 import 网关的运行时状态(无长轮询、无内存态),两个进程可以各自重启。
|
|
18
|
+
*/
|
|
19
|
+
import fs from "node:fs";
|
|
20
|
+
import { StringDecoder } from "node:string_decoder";
|
|
21
|
+
|
|
22
|
+
import { gwPaths, loadConfig, type GatewayConfig } from "./config.ts";
|
|
23
|
+
import { claimQueuedInbound, listQueuedInbound } from "./deliver.ts";
|
|
24
|
+
import { listPresence } from "./mailbox.ts";
|
|
25
|
+
import { writeOutbox } from "./queue.ts";
|
|
26
|
+
import { formatInbound, priorityOf } from "./router.ts";
|
|
27
|
+
import { slugFor } from "./slug.ts";
|
|
28
|
+
import { buildStatus } from "./status.ts";
|
|
29
|
+
|
|
30
|
+
/** 客户端 `SUPPORTED_PROTOCOL_VERSIONS` 的原样副本:答一个它不认的版本会让握手直接失败。 */
|
|
31
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] as const;
|
|
32
|
+
export const LATEST_PROTOCOL_VERSION = SUPPORTED_PROTOCOL_VERSIONS[0];
|
|
33
|
+
|
|
34
|
+
const SERVER_NAME = "pi-wechat-gateway";
|
|
35
|
+
const SERVER_INSTRUCTIONS =
|
|
36
|
+
"微信网关:wechat_send 把消息发到用户微信,wechat_pull 拉取入站队列(拉走即标记已读),wechat_status 看服务/队列/凭据状态。";
|
|
37
|
+
|
|
38
|
+
const JSON_RPC_PARSE_ERROR = -32700;
|
|
39
|
+
const JSON_RPC_INVALID_REQUEST = -32600;
|
|
40
|
+
const JSON_RPC_METHOD_NOT_FOUND = -32601;
|
|
41
|
+
const JSON_RPC_INVALID_PARAMS = -32602;
|
|
42
|
+
|
|
43
|
+
export type JsonRpcId = string | number | null;
|
|
44
|
+
export type McpRequest = { jsonrpc?: string; id?: JsonRpcId; method?: string; params?: Record<string, unknown> };
|
|
45
|
+
export type McpResponse = { jsonrpc: "2.0"; id: JsonRpcId; result?: unknown; error?: { code: number; message: string } };
|
|
46
|
+
export type McpContext = { cfg: GatewayConfig; now: () => Date };
|
|
47
|
+
|
|
48
|
+
const pkgVersion = (): string => {
|
|
49
|
+
try {
|
|
50
|
+
return String((JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: string }).version ?? "0.0.0");
|
|
51
|
+
} catch {
|
|
52
|
+
return "0.0.0";
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const textResult = (text: string, structuredContent?: Record<string, unknown>, isError = false): Record<string, unknown> => ({
|
|
57
|
+
content: [{ type: "text", text }],
|
|
58
|
+
...(structuredContent ? { structuredContent } : {}),
|
|
59
|
+
...(isError ? { isError: true } : {}),
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const SLUG = /^[A-Za-z0-9_.@-]{1,64}$/;
|
|
63
|
+
|
|
64
|
+
export const MCP_TOOLS = [
|
|
65
|
+
{
|
|
66
|
+
name: "wechat_send",
|
|
67
|
+
description: "把一条消息发到用户微信(经网关 outbox,网关负责节流/免打扰/重试)。给 slug 或 pid 之一,再给 text。",
|
|
68
|
+
inputSchema: {
|
|
69
|
+
type: "object",
|
|
70
|
+
properties: {
|
|
71
|
+
slug: { type: "string", description: "会话 slug(如 proj-a);与 pid 二选一" },
|
|
72
|
+
pid: { type: "integer", description: "在线会话的进程号(pi-mailbox presence);与 slug 二选一" },
|
|
73
|
+
text: { type: "string", description: "消息正文;出站会加 [slug] 前缀(引用回复靠它路由)" },
|
|
74
|
+
priority: { type: "string", enum: ["digest", "now", "urgent"], description: "默认 digest:免打扰窗口内排队,urgent 永远发" },
|
|
75
|
+
reply: { type: "boolean", description: "true = 把该会话记为「最近提问」,用户不带前缀直接回也回到它" },
|
|
76
|
+
},
|
|
77
|
+
required: ["text"],
|
|
78
|
+
anyOf: [{ required: ["slug"] }, { required: ["pid"] }],
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: "wechat_status",
|
|
83
|
+
description: "网关状态:systemd 单元/心跳/凭据/入站投递模式与队列深度/outbox/pending/在线会话(JSON)。",
|
|
84
|
+
inputSchema: { type: "object", properties: {} },
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
name: "wechat_pull",
|
|
88
|
+
description: "拉取入站队列(PI_WECHAT_DELIVER=queue 模式下的消息)。拉走的条目移进 inbox-queue-read/,不会重复投递。",
|
|
89
|
+
inputSchema: {
|
|
90
|
+
type: "object",
|
|
91
|
+
properties: {
|
|
92
|
+
slug: { type: "string", description: "只拉这个 slug 的消息" },
|
|
93
|
+
limit: { type: "integer", description: "最多拉几条,默认 20" },
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
] as const;
|
|
98
|
+
|
|
99
|
+
function resolveSlug(args: Record<string, unknown>, cfg: GatewayConfig): string {
|
|
100
|
+
const slug = typeof args.slug === "string" ? args.slug.trim() : "";
|
|
101
|
+
if (slug) {
|
|
102
|
+
if (!SLUG.test(slug)) throw new Error(`slug 不合法:${slug}(只允许 [A-Za-z0-9_.@-],≤64)`);
|
|
103
|
+
return slug;
|
|
104
|
+
}
|
|
105
|
+
const pid = Number(args.pid);
|
|
106
|
+
if (!Number.isInteger(pid) || pid <= 0) throw new Error("需要 slug 或 pid(正整数)之一");
|
|
107
|
+
const hit = listPresence(cfg.presenceDir).find((p) => p.pid === pid);
|
|
108
|
+
// 只有 mailbox 模式才有人写 presence;queue 模式下 pid 无从映射,直接说清楚而不是猜
|
|
109
|
+
if (!hit) throw new Error(`没有 pid=${pid} 的在线会话(presence 由 pi-mailbox 写;queue 模式请直接用 slug)`);
|
|
110
|
+
return slugFor(hit.cwd);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function toolSend(ctx: McpContext, args: Record<string, unknown>): Record<string, unknown> {
|
|
114
|
+
const text = typeof args.text === "string" ? args.text.trim() : "";
|
|
115
|
+
if (!text) throw new Error("text 不能为空");
|
|
116
|
+
const slug = resolveSlug(args, ctx.cfg);
|
|
117
|
+
const priority = priorityOf(args.priority);
|
|
118
|
+
const item = {
|
|
119
|
+
id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
|
|
120
|
+
slug,
|
|
121
|
+
text,
|
|
122
|
+
priority,
|
|
123
|
+
requiresReply: args.reply === true || priority === "urgent",
|
|
124
|
+
createdAt: ctx.now().toISOString(),
|
|
125
|
+
};
|
|
126
|
+
const file = writeOutbox(gwPaths(ctx.cfg.stateDir).outbox, item);
|
|
127
|
+
return textResult(`已入队(slug=${slug}, priority=${priority}):${file}`, { file, slug, priority });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function toolPull(ctx: McpContext, args: Record<string, unknown>): Record<string, unknown> {
|
|
131
|
+
const p = gwPaths(ctx.cfg.stateDir);
|
|
132
|
+
const now = ctx.now();
|
|
133
|
+
const rawLimit = Number(args.limit);
|
|
134
|
+
const limit = Number.isInteger(rawLimit) && rawLimit > 0 ? Math.min(rawLimit, 200) : 20;
|
|
135
|
+
const only = typeof args.slug === "string" && args.slug.trim() ? args.slug.trim() : null;
|
|
136
|
+
const queued = listQueuedInbound(p.inboxQueue).filter((e) => only === null || e.slug === only);
|
|
137
|
+
const messages: Array<{ slug: string; text: string; sentAt: string; arrivedAt: string; file: string }> = [];
|
|
138
|
+
for (const entry of queued.slice(0, limit)) {
|
|
139
|
+
const claimed = claimQueuedInbound(entry, p.inboxQueueRead);
|
|
140
|
+
if (!claimed) continue; // 另一个消费者先拉走了
|
|
141
|
+
messages.push({
|
|
142
|
+
slug: entry.slug,
|
|
143
|
+
// 积压前缀在**拉取这一刻**算:网关停机/消费方没起来时,等待时长不会被藏掉
|
|
144
|
+
text: formatInbound(entry.item.text, { now, sentAt: entry.item.sentAt, staleAfterMs: ctx.cfg.staleAfterMs }),
|
|
145
|
+
sentAt: entry.item.sentAt,
|
|
146
|
+
arrivedAt: entry.item.arrivedAt,
|
|
147
|
+
file: claimed,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
const remaining = Math.max(0, queued.length - messages.length);
|
|
151
|
+
const hint = ctx.cfg.delivery === "queue" ? "" : `(当前投递模式是 ${ctx.cfg.delivery},队列里通常没有东西)`;
|
|
152
|
+
const body = messages.length
|
|
153
|
+
? `${messages.map((m) => `[${m.slug}] ${m.text}`).join("\n")}\n---\n拉了 ${messages.length} 条,剩 ${remaining} 条${hint}`
|
|
154
|
+
: `0 条${hint}`;
|
|
155
|
+
return textResult(body, { pulled: messages.length, remaining, messages });
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function toolStatus(ctx: McpContext): Record<string, unknown> {
|
|
159
|
+
const status = buildStatus(ctx.cfg);
|
|
160
|
+
return textResult(JSON.stringify(status, null, 2), status);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function callTool(name: string, args: Record<string, unknown>, ctx: McpContext): Record<string, unknown> {
|
|
164
|
+
try {
|
|
165
|
+
if (name === "wechat_send") return toolSend(ctx, args);
|
|
166
|
+
if (name === "wechat_pull") return toolPull(ctx, args);
|
|
167
|
+
if (name === "wechat_status") return toolStatus(ctx);
|
|
168
|
+
return textResult(`未知工具:${name}(有 ${MCP_TOOLS.map((t) => t.name).join(" / ")})`, undefined, true);
|
|
169
|
+
} catch (error) {
|
|
170
|
+
// 工具层失败按 MCP 约定放在 isError 里,不走 JSON-RPC error(否则客户端会当协议故障重连)
|
|
171
|
+
return textResult(String(error instanceof Error ? error.message : error), undefined, true);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** 一条 JSON-RPC 消息 → 一条响应(通知返回 null)。纯函数,测试直接调。 */
|
|
176
|
+
export function handleRequest(msg: McpRequest, ctx: McpContext): McpResponse | null {
|
|
177
|
+
const id = msg.id ?? null;
|
|
178
|
+
const method = String(msg.method ?? "");
|
|
179
|
+
const params = msg.params ?? {};
|
|
180
|
+
const reply = (result: unknown): McpResponse => ({ jsonrpc: "2.0", id, result });
|
|
181
|
+
const fail = (code: number, message: string): McpResponse => ({ jsonrpc: "2.0", id, error: { code, message } });
|
|
182
|
+
|
|
183
|
+
if (!method) return id === null ? null : fail(JSON_RPC_INVALID_REQUEST, "缺少 method");
|
|
184
|
+
|
|
185
|
+
if (method === "initialize") {
|
|
186
|
+
const asked = String(params.protocolVersion ?? "");
|
|
187
|
+
return reply({
|
|
188
|
+
protocolVersion: (SUPPORTED_PROTOCOL_VERSIONS as readonly string[]).includes(asked) ? asked : LATEST_PROTOCOL_VERSION,
|
|
189
|
+
capabilities: { tools: {} },
|
|
190
|
+
serverInfo: { name: SERVER_NAME, version: pkgVersion() },
|
|
191
|
+
instructions: SERVER_INSTRUCTIONS,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
if (method === "ping") return reply({});
|
|
195
|
+
if (method === "tools/list") return reply({ tools: MCP_TOOLS });
|
|
196
|
+
if (method === "tools/call") {
|
|
197
|
+
const name = String(params.name ?? "");
|
|
198
|
+
if (!name) return fail(JSON_RPC_INVALID_PARAMS, "tools/call 缺少 name");
|
|
199
|
+
const args = (params.arguments ?? {}) as Record<string, unknown>;
|
|
200
|
+
return reply(callTool(name, args, ctx));
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// 通知(无 id):initialized / cancelled 之类,不需要回包
|
|
204
|
+
if (id === null) return null;
|
|
205
|
+
return fail(JSON_RPC_METHOD_NOT_FOUND, `不支持的方法:${method}`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** stdio 主循环:按换行读 stdin、按换行写 stdout。stdout 上除了 JSON-RPC 一个字都不能有。 */
|
|
209
|
+
export async function serveMcp(opts: { cfg?: GatewayConfig; input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream } = {}): Promise<void> {
|
|
210
|
+
const cfg = opts.cfg ?? loadConfig();
|
|
211
|
+
const input = opts.input ?? process.stdin;
|
|
212
|
+
const output = opts.output ?? process.stdout;
|
|
213
|
+
const ctx: McpContext = { cfg, now: () => new Date() };
|
|
214
|
+
process.stderr.write(`pi-wechat-gateway mcp: state=${cfg.stateDir} delivery=${cfg.delivery}\n`);
|
|
215
|
+
|
|
216
|
+
let buffer = "";
|
|
217
|
+
// decoder 而不是 String(chunk):一个汉字可能被切成两个 chunk,直接 toString 会得到两个替换符
|
|
218
|
+
const decoder = new StringDecoder("utf8");
|
|
219
|
+
const handleLine = (line: string): void => {
|
|
220
|
+
if (!line.trim()) return;
|
|
221
|
+
let parsed: unknown;
|
|
222
|
+
try {
|
|
223
|
+
parsed = JSON.parse(line);
|
|
224
|
+
} catch (error) {
|
|
225
|
+
output.write(`${JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: JSON_RPC_PARSE_ERROR, message: `JSON 解析失败:${String(error)}` } })}\n`);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
if (Array.isArray(parsed) || typeof parsed !== "object" || parsed === null) {
|
|
229
|
+
output.write(`${JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: JSON_RPC_INVALID_REQUEST, message: "只接受单条 JSON-RPC 对象" } })}\n`);
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const response = handleRequest(parsed as McpRequest, ctx);
|
|
233
|
+
if (response) output.write(`${JSON.stringify(response)}\n`);
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
for await (const chunk of input) {
|
|
237
|
+
buffer += decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
|
238
|
+
for (let at = buffer.indexOf("\n"); at >= 0; at = buffer.indexOf("\n")) {
|
|
239
|
+
const line = buffer.slice(0, at).replace(/\r$/, "");
|
|
240
|
+
buffer = buffer.slice(at + 1);
|
|
241
|
+
handleLine(line);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
buffer += decoder.end();
|
|
245
|
+
// 关闭时残留的半条消息按解析失败处理:静默丢弃会让客户端一直等
|
|
246
|
+
if (buffer.trim()) handleLine(buffer);
|
|
247
|
+
}
|
package/src/status.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `status` 的载荷:CLI(`pi-wechat-gateway status`)与 MCP(`wechat_status`)共用同一份,
|
|
3
|
+
* 免得两个入口对「当前模式 / 队列深度」各有一套说法。
|
|
4
|
+
*/
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
import { gwPaths, type GatewayConfig } from "./config.ts";
|
|
9
|
+
import { queueDepth } from "./deliver.ts";
|
|
10
|
+
import { readLogin } from "./login.ts";
|
|
11
|
+
import { listPresence } from "./mailbox.ts";
|
|
12
|
+
import { heartbeatFresh, readClearedMarker, unitActive, unitInstalled, UNIT } from "./ops.ts";
|
|
13
|
+
import { listOutbox } from "./queue.ts";
|
|
14
|
+
|
|
15
|
+
const readJson = (file: string): unknown => {
|
|
16
|
+
try {
|
|
17
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function buildStatus(cfg: GatewayConfig): Record<string, unknown> {
|
|
24
|
+
const p = gwPaths(cfg.stateDir);
|
|
25
|
+
const installed = unitInstalled();
|
|
26
|
+
const hb = heartbeatFresh(p.heartbeat);
|
|
27
|
+
return {
|
|
28
|
+
service: { unit: UNIT, installed, active: installed && unitActive() },
|
|
29
|
+
heartbeat: readJson(p.heartbeat),
|
|
30
|
+
heartbeatFresh: hb.fresh,
|
|
31
|
+
heartbeatAgeSec: hb.ageMs === null ? null : Math.round(hb.ageMs / 1000),
|
|
32
|
+
credentials: {
|
|
33
|
+
file: cfg.credentialsFile,
|
|
34
|
+
user: cfg.userId,
|
|
35
|
+
baseUrl: cfg.baseUrl,
|
|
36
|
+
cleared: readClearedMarker(cfg.stateDir),
|
|
37
|
+
ok: Boolean(cfg.token),
|
|
38
|
+
},
|
|
39
|
+
login: readLogin(cfg.stateDir),
|
|
40
|
+
// 入站落点:mailbox 要 pi-mailbox 的 presence 才知道投给谁;queue 只看队列深度(不需要 presence)
|
|
41
|
+
delivery: { mode: cfg.delivery, queue: queueDepth(p.inboxQueue) },
|
|
42
|
+
outbox: listOutbox(p.outbox).length,
|
|
43
|
+
// 收不到消息时先看这里:路由命中了但目标会话不在名册(pi-mailbox presence)就会停在这
|
|
44
|
+
// 每条带 slug 与等了多久:压在 pending 里一夜的消息会被当「积压」补投
|
|
45
|
+
pending: (() => {
|
|
46
|
+
try {
|
|
47
|
+
return fs
|
|
48
|
+
.readdirSync(p.pending)
|
|
49
|
+
.filter((f) => f.endsWith(".json"))
|
|
50
|
+
.map((f) => {
|
|
51
|
+
try {
|
|
52
|
+
const item = JSON.parse(fs.readFileSync(path.join(p.pending, f), "utf8")) as { slug?: string; at?: string; sentAt?: string };
|
|
53
|
+
const at = Date.parse(String(item.sentAt ?? item.at ?? "")) || 0;
|
|
54
|
+
return { slug: item.slug ?? f.replace(/\.json$/, ""), ageSec: at ? Math.round((Date.now() - at) / 1000) : null };
|
|
55
|
+
} catch {
|
|
56
|
+
return { file: f };
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
} catch {
|
|
60
|
+
return [];
|
|
61
|
+
}
|
|
62
|
+
})(),
|
|
63
|
+
online: listPresence(cfg.presenceDir).map((x) => ({ pid: x.pid, cwd: x.cwd })),
|
|
64
|
+
quiet: `${String(Math.floor(cfg.quietFrom / 60)).padStart(2, "0")}:${String(cfg.quietFrom % 60).padStart(2, "0")}–${String(Math.floor(cfg.quietTo / 60)).padStart(2, "0")}:${String(cfg.quietTo % 60).padStart(2, "0")}`,
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -11,6 +11,8 @@ Type=simple
|
|
|
11
11
|
WorkingDirectory=%h/pi-plugins/pi-wechat-gateway
|
|
12
12
|
ExecStart=%h/.local/share/pi-node/current/bin/node %h/pi-plugins/pi-wechat-gateway/src/main.ts run
|
|
13
13
|
Environment=PI_WECHAT_STATE=%h/.pi/wechat
|
|
14
|
+
# 只保留 CLI/MCP 通道:入站落 inbox-queue,由 wechat_pull 拉取(不再注入 pi-mailbox)
|
|
15
|
+
Environment=PI_WECHAT_DELIVER=queue
|
|
14
16
|
Environment=NODE_ENV=production
|
|
15
17
|
# 境外 443 直连是黑洞(硬规则 1);微信 iLink 是国内域名,走 no_proxy 直连
|
|
16
18
|
Environment=http_proxy=http://127.0.0.1:7890
|