@chen_hu_hu/pi-qq 1.0.0 → 1.0.1
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/README.md +71 -104
- package/doc/features.md +28 -43
- package/doc/plan.md +16 -16
- package/index.ts +99 -107
- package/package.json +1 -1
- package/src/bot.ts +7 -7
- package/src/budget-status.ts +9 -9
- package/src/config.ts +23 -78
- package/src/files.ts +3 -3
- package/src/inbound.ts +5 -12
- package/src/login.ts +19 -20
package/README.md
CHANGED
|
@@ -1,135 +1,102 @@
|
|
|
1
1
|
# pi-qq
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
> 手机 QQ 上发消息(文字/图片/文件)→ pi 在机器上干活 → 完整回复(Markdown → 纯文本)+ 用量摘要回传到 QQ。
|
|
3
|
+
Connect [pi](https://github.com/earendil-works/pi) to a QQ private chat. Send text, images, or files from mobile QQ; pi works on your machine and sends the result back to QQ.
|
|
5
4
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
## 功能特性
|
|
9
|
-
|
|
10
|
-
- **扫码登录 / 配置直连**:`/qq-login` 扫码即用(自动换取凭据并绑定单人),或在配置文件写入 `AppID`/`AppSecret` 免扫码直连
|
|
11
|
-
- **单人聊天**:绑定用户私聊消息直接进入 pi 会话(含图片/文件),白名单外的消息完全隔离
|
|
12
|
-
- **完整回复**:assistant 消息实时回传(流式追加 / 降级分块),Markdown 转手机可读纯文本
|
|
13
|
-
- **长任务反馈**:"正在输入"保鲜 + 每 10s 汇总工具调用 + 节流心跳(`⏱ 已运行 25 分钟 · [86] 🔧 bash · [12] 🔧 read`),数十分钟级任务不再黑盒等待
|
|
14
|
-
- **用量摘要**:每次 QQ 任务后回传本次 run 的输入(含缓存命中率)、输出与上下文占比,严格三行
|
|
15
|
-
- **发送图片/文件**:QQ 端发图自动注入 pi;QQ 端发文件保存到当前工作空间 `.pi/pi-qq/`,并把路径写入提示词(图片默认 10MB、文件默认 50MB)
|
|
16
|
-
- **诊断命令**:`/qq-md`、`/qq-stream-test`、`/qq-budget` 快速验证平台能力与额度
|
|
17
|
-
|
|
18
|
-
架构与决策记录见 [doc/features.md](./doc/features.md),实施计划与验收见 [doc/plan.md](./doc/plan.md)。
|
|
19
|
-
|
|
20
|
-
## 快速开始
|
|
21
|
-
|
|
22
|
-
### 从 npm / Pi 市场安装(推荐)
|
|
5
|
+
## Install
|
|
23
6
|
|
|
24
7
|
```bash
|
|
25
8
|
pi install npm:@chen_hu_hu/pi-qq
|
|
26
9
|
```
|
|
27
10
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
### 本地开发
|
|
31
|
-
|
|
32
|
-
#### 1. 安装依赖
|
|
11
|
+
For local development:
|
|
33
12
|
|
|
34
13
|
```bash
|
|
35
|
-
|
|
14
|
+
pi --extension /path/to/pi-qq
|
|
36
15
|
```
|
|
37
16
|
|
|
38
|
-
|
|
17
|
+
## Login
|
|
39
18
|
|
|
40
|
-
|
|
19
|
+
1. Start pi.
|
|
20
|
+
2. Run `/qq-login`.
|
|
21
|
+
3. Scan the QR code with mobile QQ.
|
|
41
22
|
|
|
42
|
-
|
|
43
|
-
{
|
|
44
|
-
"AppID": "你的 AppID",
|
|
45
|
-
"AppSecret": "你的 AppSecret"
|
|
46
|
-
}
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
**方式 B:扫码登录** — pi 中执行 `/qq-login`,用手机 QQ 扫码,凭据自动写回同一文件,
|
|
50
|
-
扫码人的 openid 自动绑定为"单人"白名单。
|
|
23
|
+
Credentials are kept in process memory only. Restarting pi requires scanning again. `/qq-logout` clears the in-memory credentials immediately.
|
|
51
24
|
|
|
52
|
-
|
|
25
|
+
## Usage
|
|
53
26
|
|
|
54
|
-
|
|
55
|
-
pi --extension /path/to/pi-qq
|
|
56
|
-
# 或放入用户扩展目录,所有会话自动加载:
|
|
57
|
-
ln -s /path/to/pi-qq ~/.pi/agent/extensions/pi-qq
|
|
58
|
-
```
|
|
27
|
+
Send a QQ private message to the bot to start a task.
|
|
59
28
|
|
|
60
|
-
|
|
29
|
+
- **Text**: normal chat message.
|
|
30
|
+
- **Images**: sent to pi as vision input.
|
|
31
|
+
- **Files**: saved under the current workspace at `.pi/pi-qq/YYYY-MM-DD/<msgId>/`; the saved path, size, and original filename are added to the prompt.
|
|
61
32
|
|
|
62
|
-
|
|
33
|
+
Example file prompt seen by pi:
|
|
63
34
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
| `allowedOpenid` | 扫码自动写入 | 单人绑定的 openid;手动配置时缺省则首个私聊用户自动绑定 |
|
|
68
|
-
| `streamAssistant` | `true` | assistant 流式回传开关(关闭则整条回复完成后一次性发送) |
|
|
69
|
-
| `markdownSupport` | `false` | 机器人是否有 markdown 权限;`true` 时回传透传原始 Markdown |
|
|
70
|
-
| `usageRelay` | `true` | 本次 run 的输入/缓存命中率/输出/上下文摘要开关 |
|
|
71
|
-
| `deliverAs` | `"steer"` | agent 忙碌时新消息的处理方式:`steer` 并入当前任务 / `followUp` 排队 |
|
|
72
|
-
| `imageMaxSize` | `10485760` | QQ 图片下载上限(字节,默认 10MB) |
|
|
73
|
-
| `fileMaxSize` | `52428800` | QQ 文件下载上限(字节,默认 50MB) |
|
|
74
|
-
| `heartbeatMinutes` | `10` | 长任务心跳间隔(分钟),`0` 关闭 |
|
|
75
|
-
| `heartbeatMaxMessages` | `3` | 每 run 消息心跳上限(流式心跳不受限) |
|
|
76
|
-
| `streamRelay` | `true` | 流式载体(append 追加语义);关闭则心跳与结果全走普通消息 |
|
|
77
|
-
| `streamFlushMs` | `10000` | 流式汇总帧间隔(毫秒,最小 300;默认每 10s 汇总工具调用) |
|
|
78
|
-
| `debug` | `false` | 诊断模式:SDK 日志 + 流式限流重试/超时日志 + 文本帧时间戳 |
|
|
79
|
-
|
|
80
|
-
## 命令
|
|
81
|
-
|
|
82
|
-
| 位置 | 命令 | 行为 |
|
|
83
|
-
| --- | --- | --- |
|
|
84
|
-
| pi 侧 | `/qq-login` | 扫码登录/换绑 |
|
|
85
|
-
| pi 侧 | `/qq-status` | 登录态、连接状态、绑定用户 |
|
|
86
|
-
| pi 侧 | `/qq-budget` | 诊断:被动额度、流式气泡数、最近 msgId 新鲜度 |
|
|
87
|
-
| pi 侧 | `/qq-logout` | 清除凭据并断开 |
|
|
88
|
-
| pi 侧 | `/qq-md [text]` | 诊断:验证 C2C markdown 渲染能力 |
|
|
89
|
-
| pi 侧 | `/qq-stream-test` | 诊断:追加模式流式全链路验证 |
|
|
90
|
-
| QQ 侧 | `/new` `/stop` `/compact` `/status` `/help` | 会话控制(`/new` 会通过扩展命令重置会话) |
|
|
35
|
+
```text
|
|
36
|
+
User sent the following file via QQ (saved locally; use read/bash or other tools to access it):
|
|
37
|
+
- /home/chen/project/myproj/.pi/pi-qq/2026-10-29/xxx/report.pdf (1.4MB, original name: report.pdf)
|
|
91
38
|
|
|
92
|
-
|
|
39
|
+
User message:
|
|
40
|
+
Summarize this file.
|
|
41
|
+
```
|
|
93
42
|
|
|
94
|
-
|
|
43
|
+
## Commands
|
|
95
44
|
|
|
96
|
-
|
|
97
|
-
[活动气泡:💭思考/[n]🔧工具计数] ← streamRelay 开启时,每 10s 汇总
|
|
98
|
-
[文本气泡:assistant 消息原文] ← 每条文本消息独立成泡
|
|
99
|
-
[活动气泡:后续工具汇总]
|
|
100
|
-
[文本气泡:最终回复原文]
|
|
101
|
-
📊 用量摘要
|
|
102
|
-
• 输入:4.1k (99.9%)
|
|
103
|
-
• 输出:2.3k
|
|
104
|
-
• 上下文:0.4%
|
|
105
|
-
```
|
|
45
|
+
Run these in the pi terminal:
|
|
106
46
|
|
|
107
|
-
|
|
47
|
+
| Command | Description |
|
|
48
|
+
| --- | --- |
|
|
49
|
+
| `/qq-login` | Log in with a QR code and bind the scanning QQ user |
|
|
50
|
+
| `/qq-status` | Show login, connection, model, context, and bound user |
|
|
51
|
+
| `/qq-logout` | Log out and clear in-memory credentials |
|
|
52
|
+
| `/qq-budget` | Show passive-reply budget and stream-bubble diagnostics |
|
|
53
|
+
| `/qq-md [text]` | Send a Markdown test message |
|
|
54
|
+
| `/qq-stream-test` | Run a streamed timeline diagnostic |
|
|
55
|
+
| `/qq-new` | Reset the current session (used by QQ `/new`) |
|
|
108
56
|
|
|
109
|
-
|
|
110
|
-
npm install # 安装依赖(prettier / vitest 为 devDependencies)
|
|
111
|
-
npm run typecheck # 类型检查
|
|
112
|
-
npm test # vitest(8 个测试文件 / 81 个测试)
|
|
113
|
-
npm run format # Prettier 格式化
|
|
114
|
-
npm run format:check # Prettier 校验
|
|
115
|
-
```
|
|
57
|
+
QQ-side commands:
|
|
116
58
|
|
|
117
|
-
|
|
59
|
+
| Command | Description |
|
|
60
|
+
| --- | --- |
|
|
61
|
+
| `/new` | Start a new pi session |
|
|
62
|
+
| `/stop` | Abort the current run |
|
|
63
|
+
| `/compact` | Compact the current context |
|
|
64
|
+
| `/status` | Show session and usage status |
|
|
65
|
+
| `/help` | Show command help |
|
|
118
66
|
|
|
119
|
-
|
|
120
|
-
`config`(配置读写)/ `login`(扫码)/ `bot`(生命周期)/ `inbound`(QQ→pi)/
|
|
121
|
-
`outbound`(pi→QQ 文本)/ `reply-budget`(被动回复额度)/ `budget-status`(`/qq-budget` 格式化)/ `run-feedback`(长任务反馈)/
|
|
122
|
-
`append-stream`(追加模式流式发送器)/ `usage`(token 累计与用量摘要)/ `images`(QQ 图片下载与校验)/
|
|
123
|
-
`files`(QQ 文件落盘与提示词路径)/ `download`(附件限流下载)/ `format`(字节格式化)。
|
|
67
|
+
## Settings
|
|
124
68
|
|
|
125
|
-
|
|
69
|
+
Create `~/.pi/agent/pi-qq.json` to override defaults. This file contains settings only; credentials are never written to it.
|
|
126
70
|
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
71
|
+
```json
|
|
72
|
+
{
|
|
73
|
+
"markdownSupport": false,
|
|
74
|
+
"streamFlushMs": 10000,
|
|
75
|
+
"debug": false
|
|
76
|
+
}
|
|
77
|
+
```
|
|
132
78
|
|
|
133
|
-
|
|
79
|
+
| Key | Default | Description |
|
|
80
|
+
| --- | --- | --- |
|
|
81
|
+
| `streamAssistant` | `true` | Stream assistant replies |
|
|
82
|
+
| `markdownSupport` | `false` | Bot has QQ Markdown permission; pass Markdown through |
|
|
83
|
+
| `usageRelay` | `true` | Send the per-run usage summary |
|
|
84
|
+
| `deliverAs` | `"steer"` | Queue new messages while busy: `steer` or `followUp` |
|
|
85
|
+
| `imageMaxSize` | `10485760` | QQ image download limit in bytes (10MB) |
|
|
86
|
+
| `fileMaxSize` | `52428800` | QQ file download limit in bytes (50MB) |
|
|
87
|
+
| `heartbeatMinutes` | `10` | Long-task heartbeat interval; `0` disables |
|
|
88
|
+
| `heartbeatMaxMessages` | `3` | Per-run message heartbeat limit |
|
|
89
|
+
| `streamRelay` | `true` | Use append-mode stream bubbles |
|
|
90
|
+
| `streamFlushMs` | `10000` | Stream summary frame interval in ms (minimum 300) |
|
|
91
|
+
| `debug` | `false` | SDK and stream retry/timeout diagnostics |
|
|
92
|
+
|
|
93
|
+
## Notes
|
|
94
|
+
|
|
95
|
+
- Only C2C (QQ private chat) is supported.
|
|
96
|
+
- Incoming images are passed to the model as vision input; the current model must support image input.
|
|
97
|
+
- Saved files are workspace-local under `.pi/`; add `.pi/` to your own project `.gitignore` if needed.
|
|
98
|
+
- QQ limits passive replies per inbound message. Use `/qq-budget` to inspect the local budget.
|
|
99
|
+
|
|
100
|
+
## License
|
|
134
101
|
|
|
135
102
|
MIT
|
package/doc/features.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
| 依赖 | 用途 |
|
|
9
9
|
| --- | --- |
|
|
10
10
|
| `@tencent-connect/qqbot-nodejs` | QQ 开放平台协议层:WebSocket Gateway、C2C 消息收发、媒体上传、流式消息 |
|
|
11
|
-
| `@tencent-connect/qqbot-connector` |
|
|
11
|
+
| `@tencent-connect/qqbot-connector` | 扫码登录:展示二维码,扫码后换取 `appId / appSecret / userOpenid`(仅内存) |
|
|
12
12
|
| `@earendil-works/pi-coding-agent`(ExtensionAPI) | pi 扩展宿主:事件订阅、命令注册、消息注入、上下文用量 |
|
|
13
13
|
|
|
14
14
|
---
|
|
@@ -35,41 +35,28 @@ pi-qq 扩展 ── pi.sendUserMessage(text+images) ─┴─ pi 事件:
|
|
|
35
35
|
|
|
36
36
|
## 2. 核心功能
|
|
37
37
|
|
|
38
|
-
### F1
|
|
38
|
+
### F1 扫码登录(仅扫码)
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
**目标**:唯一登录方式是 `/qq-login` 扫码;凭据只保存在进程内存,绝不落盘。pi 进程退出后必须重新扫码。
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
用户预先在 `~/.pi/agent/pi-qq.json` 写入:
|
|
45
|
-
|
|
46
|
-
```json
|
|
47
|
-
{
|
|
48
|
-
"AppID": "...",
|
|
49
|
-
"AppSecret": "..."
|
|
50
|
-
}
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
- 规则(已确认):配置文件中存在有效凭据 → 启动时直接构造 `QQBot` 接入,**无需扫码**;否则进入扫码流程。
|
|
54
|
-
- 读取时兼容小写 `appId` / `appSecret`;文件中其余配置项(§4)可共存。
|
|
55
|
-
- 手动配置时若未填 `allowedOpenid`:第一个发来 C2C 私聊的用户自动绑定为单人用户(写入配置并在 pi 侧提示),也可手动预先填写。
|
|
56
|
-
|
|
57
|
-
**方式 B:扫码登录**
|
|
42
|
+
**行为**
|
|
58
43
|
|
|
59
44
|
1. 用户在 pi 中执行 `/qq-login`。
|
|
60
|
-
2.
|
|
61
|
-
- `onQrDisplayed(url)`:TUI
|
|
62
|
-
- `onQrExpired()
|
|
63
|
-
- `onSuccess([{ appId, appSecret, userOpenid }])
|
|
64
|
-
3.
|
|
65
|
-
4. 立即构造 `QQBot`
|
|
45
|
+
2. 扩展停止现有连接,调用 `startQrConnect({ displayQrCodeToConsole: false, signal })`:
|
|
46
|
+
- `onQrDisplayed(url)`:TUI 用 `qrcode-terminal` 把 URL 画成 ASCII 二维码;非 TUI 输出 URL。
|
|
47
|
+
- `onQrExpired()`:提示二维码过期并自动刷新。
|
|
48
|
+
- `onSuccess([{ appId, appSecret, userOpenid }])`:获取凭据与扫码人 openid。
|
|
49
|
+
3. 凭据写入进程内存(`globalThis` 登录状态),不写 `~/.pi/agent/pi-qq.json`。`userOpenid` 作为唯一绑定的 QQ 用户白名单。
|
|
50
|
+
4. 立即构造 `QQBot` 并启动;未完成扫码前可取消(Esc / AbortSignal)。
|
|
51
|
+
5. 同一 pi 进程内的 session reload / `/new` 会复用内存登录;pi 进程退出后内存清空,下次启动必须重新 `/qq-login`。
|
|
52
|
+
6. `/qq-logout` 立即清除内存凭据并断开连接;之后可重新扫码。
|
|
66
53
|
|
|
67
54
|
**通用**
|
|
68
55
|
|
|
69
|
-
- `/qq-status
|
|
70
|
-
- `/qq-
|
|
71
|
-
-
|
|
72
|
-
-
|
|
56
|
+
- `/qq-status`、`/qq-login`、`/qq-logout`、`/qq-budget`、`/qq-md`、`/qq-stream-test`、`/qq-new` 的命令说明与 pi 终端输出均为英文。
|
|
57
|
+
- `/qq-status` 显示登录状态(in memory)、连接状态、模型、上下文与绑定用户;AppID 仅显示前 4 位 + `****`。
|
|
58
|
+
- 配置文件 `~/.pi/agent/pi-qq.json` 只保存非敏感设置;旧的 `AppID` / `AppSecret` / `allowedOpenid` 键会被忽略,不再用于登录。
|
|
59
|
+
- 白名单只接受扫码绑定的 openid;未登录时入站消息直接忽略。
|
|
73
60
|
|
|
74
61
|
### F2 单人聊天
|
|
75
62
|
|
|
@@ -77,7 +64,7 @@ pi-qq 扩展 ── pi.sendUserMessage(text+images) ─┴─ pi 事件:
|
|
|
77
64
|
|
|
78
65
|
**行为**
|
|
79
66
|
|
|
80
|
-
- 仅接受 `kind === "c2c"` 的入站消息;发送者 openid
|
|
67
|
+
- 仅接受 `kind === "c2c"` 的入站消息;发送者 openid 必须等于本次扫码绑定的内存白名单(复用 SDK `accessPolicy`,其他用户静默忽略)。入站消息的 `senderId` 即发送者的 openid。
|
|
81
68
|
- 普通文本 → `pi.sendUserMessage(text)`,触发正常 agent run。
|
|
82
69
|
- 图片消息的处理见 F3(QQ → pi)。
|
|
83
70
|
- agent 忙碌时收到新消息 → 按 `deliverAs`(默认 `steer`,可配置 `followUp`)排队。
|
|
@@ -108,10 +95,10 @@ pi-qq 扩展 ── pi.sendUserMessage(text+images) ─┴─ pi 事件:
|
|
|
108
95
|
- 一条消息多个文件按原顺序保存;部分失败时成功的文件仍保留并给出失败清单。
|
|
109
96
|
- 提示词中追加文件块,例如:
|
|
110
97
|
```text
|
|
111
|
-
|
|
112
|
-
- /home/chen/project/myproj/.pi/pi-qq/2026-10-29/xxx/report.pdf
|
|
98
|
+
User sent the following file(s) via QQ (saved locally; use read/bash or other tools to access):
|
|
99
|
+
- /home/chen/project/myproj/.pi/pi-qq/2026-10-29/xxx/report.pdf (1.4MB, original name: report.pdf)
|
|
113
100
|
|
|
114
|
-
|
|
101
|
+
User message:
|
|
115
102
|
帮我总结这个文件
|
|
116
103
|
```
|
|
117
104
|
- 纯文件消息(无文字)也会触发 run,提示词只含文件块;文件内容不直接注入 LLM,由 pi 用工具按需读取。
|
|
@@ -213,12 +200,10 @@ QQ 开放平台的发送限制直接决定回传策略,必须统一管理:
|
|
|
213
200
|
|
|
214
201
|
## 4. 配置
|
|
215
202
|
|
|
216
|
-
`~/.pi/agent/pi-qq.json
|
|
203
|
+
`~/.pi/agent/pi-qq.json`(只保存设置;不含凭据、不写入登录信息):
|
|
217
204
|
|
|
218
205
|
| 字段 | 默认 | 说明 |
|
|
219
206
|
| --- | --- | --- |
|
|
220
|
-
| `AppID` / `AppSecret` | 手动填写或扫码写入 | 机器人凭据(`0600` 保护);存在即免扫码直连(兼容小写 `appId` / `appSecret`) |
|
|
221
|
-
| `allowedOpenid` | 扫码自动写入;手动配置时可选(缺省首个私聊用户绑定) | 单人绑定的 openid |
|
|
222
207
|
| `streamAssistant` | `true` | assistant 流式回传开关 |
|
|
223
208
|
| `markdownSupport` | `false` | 机器人是否有 markdown 权限;`true` 时回传透传 Markdown |
|
|
224
209
|
| `usageRelay` | `true` | 本次 run 的 token/缓存命中率/上下文占比摘要开关 |
|
|
@@ -235,21 +220,21 @@ QQ 开放平台的发送限制直接决定回传策略,必须统一管理:
|
|
|
235
220
|
|
|
236
221
|
| 位置 | 命令 | 行为 |
|
|
237
222
|
| --- | --- | --- |
|
|
238
|
-
| pi 侧 | `/qq-login` |
|
|
223
|
+
| pi 侧 | `/qq-login` | 扫码登录并绑定(QR only) |
|
|
239
224
|
| pi 侧 | `/qq-status` | 登录态、连接状态、绑定用户 |
|
|
240
225
|
| pi 侧 | `/qq-budget` | 诊断:被动额度、流式气泡数、最近 msgId 新鲜度 |
|
|
241
|
-
| pi 侧 | `/qq-logout` |
|
|
242
|
-
| pi 侧 | `/qq-
|
|
226
|
+
| pi 侧 | `/qq-logout` | 清除内存凭据并断开 |
|
|
227
|
+
| pi 侧 | `/qq-new` | 重置当前会话(QQ `/new` 调用) |
|
|
243
228
|
| pi 侧 | `/qq-md [text]` | 诊断:发送 Markdown 消息,验证 C2C markdown 渲染能力 |
|
|
244
229
|
| pi 侧 | `/qq-stream-test` | 诊断:开流→三帧→complete,验证流式帧是否渲染 |
|
|
245
230
|
| QQ 侧 | `/new` `/stop` `/compact` `/status` `/help` | 会话控制(见 F2) |
|
|
246
231
|
|
|
247
232
|
## 6. 可靠性与安全
|
|
248
233
|
|
|
249
|
-
- **生命周期**:`session_start`
|
|
234
|
+
- **生命周期**:`session_start` 仅在进程内存有登录态时启动;`session_shutdown` 幂等关闭。SDK 默认无限重连(退避 1s→60s),4914/4915 致命关闭码上报为不可恢复,提示重新 `/qq-login`。
|
|
250
235
|
- **回声与去重**:启用 SDK `messageFilter`(跳过 bot 回声)与 `concurrencyGuard`(同用户串行),避免流式与回复互相踩踏。
|
|
251
236
|
- **安全**:
|
|
252
|
-
-
|
|
237
|
+
- 凭据仅保存在进程内存、不落盘;日志与 `/qq-status` 脱敏;扩展以 pi 同等权限运行,白名单外的消息不进入 pi(不产生任何工具执行)。
|
|
253
238
|
- QQ 侧无 shell 类命令;一切工具执行都经由 pi 自身权限体系。
|
|
254
239
|
|
|
255
240
|
## 7. 决策记录
|
|
@@ -262,7 +247,7 @@ QQ 开放平台的发送限制直接决定回传策略,必须统一管理:
|
|
|
262
247
|
| 4 | 图片方向 | F3 为 QQ → pi(用户发图给 pi);pi 不向 QQ 发图片(LLM 仅输出纯文本) |
|
|
263
248
|
| 5 | 成本展示 | 不在 QQ 摘要中展示成本;摘要严格三行(输入/缓存命中率、输出、上下文) |
|
|
264
249
|
| 6 | 回复格式 | 回复通常为 Markdown 格式的总结/提问文本(不在回复中写代码);默认轻量转纯文本,有 markdown 权限可透传 |
|
|
265
|
-
| 7 | 登录方式 |
|
|
250
|
+
| 7 | 登录方式 | 仅 `/qq-login` 扫码;凭据只存进程内存、不落盘;pi 进程退出后必须重新扫码 |
|
|
266
251
|
| 8 | 长任务反馈 | typing 保鲜 + 每 10s 汇总工具调用 + 节流心跳(默认 10 分钟/条,流式载体优先,每 run ≤3 条消息心跳保险丝)+ 机会性流式(平台拒绝即降级);不发送开始确认 |
|
|
267
252
|
| 9 | 流式可用性(实测三轮) | ① C2C markdown(msg_type=2,`sendMarkdown`)渲染正常;② SDK 内置流式 `input_mode="replace"` 被平台拒绝("已经提交的消息内容不可修改"),首帧可渲染、后续帧报错;③ 自实现 `AppendStream`(input_mode="append",增量追加 + DONE)实测通过;补齐节流合帧(500ms)与限流退避重试后**默认开启**,失败自动降级消息路径 |
|
|
268
253
|
|
|
@@ -270,7 +255,7 @@ QQ 开放平台的发送限制直接决定回传策略,必须统一管理:
|
|
|
270
255
|
|
|
271
256
|
| 阶段 | 内容 | 验收 |
|
|
272
257
|
| --- | --- | --- |
|
|
273
|
-
| M1 | F1
|
|
258
|
+
| M1 | F1 扫码登录 + 内存凭据 + 连接启动 | 扫码后 `/qq-status` 在线;重启 pi 需重新扫码 |
|
|
274
259
|
| M2 | F2 单人聊天 + F4 assistant 回传(先非流式) | QQ 发消息得到 pi 回复 |
|
|
275
260
|
| M3 | F5/F6 用量摘要(本次 run 输入/缓存命中率/输出/上下文) | 严格三行摘要正确呈现 |
|
|
276
261
|
| M4 | F3 QQ 图片/文件消息 + markdownSupport + 打磨 | 图片可进入 pi 会话;文件保存并关联到提示词 |
|
package/doc/plan.md
CHANGED
|
@@ -15,7 +15,7 @@ npm i @tencent-connect/qqbot-nodejs @tencent-connect/qqbot-connector qrcode-term
|
|
|
15
15
|
| 包 | 版本锚点 | 用途 |
|
|
16
16
|
| --- | --- | --- |
|
|
17
17
|
| `@tencent-connect/qqbot-nodejs` | ^1.0.5 | QQ 协议层(本地另有源码 `/home/chen/project/qqbot-nodejs` 可查阅) |
|
|
18
|
-
| `@tencent-connect/qqbot-connector` | ^1.2.0 |
|
|
18
|
+
| `@tencent-connect/qqbot-connector` | ^1.2.0 | 扫码登录(唯一登录方式) |
|
|
19
19
|
| `qrcode-terminal` | ^0.12 | 二维码 ASCII 渲染(零依赖) |
|
|
20
20
|
|
|
21
21
|
开发加载方式:`pi --extension /home/chen/project/pi-qq`(jiti 直接跑 TS,无需构建)。
|
|
@@ -28,8 +28,8 @@ pi-qq/
|
|
|
28
28
|
├── tsconfig.json # 仅编辑器/typecheck 用,无构建
|
|
29
29
|
├── index.ts # 扩展入口:registerCommand + pi.on 订阅 + 生命周期
|
|
30
30
|
└── src/
|
|
31
|
-
├── config.ts # ~/.pi/agent/pi-qq.json
|
|
32
|
-
├── login.ts # F1
|
|
31
|
+
├── config.ts # ~/.pi/agent/pi-qq.json 只读设置(不含凭据)
|
|
32
|
+
├── login.ts # F1:仅扫码登录(connector + TUI 二维码弹窗;凭据只返回内存)
|
|
33
33
|
├── bot.ts # QQBot 实例生命周期:start/stop、中间件装配、重连/致命关闭码上报
|
|
34
34
|
├── inbound.ts # F2/F3:白名单 → QQ 命令拦截 → 图片/文件附件 → sendUserMessage
|
|
35
35
|
├── images.ts # F3:图片类型/大小校验、15s 超时下载、ImageContent 组装
|
|
@@ -52,21 +52,21 @@ pi-qq/
|
|
|
52
52
|
| pi → QQ | `message_update`(assistant) | 流式:`openStream().update(转换后全文)`,节流 ≥300ms |
|
|
53
53
|
| pi → QQ | `message_end`(assistant) | `stream.complete()`;无流上下文时 `sendText`;`stopReason==="error"` 回错误摘要 |
|
|
54
54
|
| pi → QQ | `agent_end` | 用量摘要一条(F5 本次 run token/缓存命中率 + F6 上下文占比) |
|
|
55
|
-
| 状态 | `session_start` / `session_shutdown` |
|
|
55
|
+
| 状态 | `session_start` / `session_shutdown` | 有内存登录态则启动 bot / 幂等停止 |
|
|
56
56
|
| 汇总 | `agent_end` | 从 `event.messages` 汇总本次 run 的 assistant/toolResult usage |
|
|
57
57
|
|
|
58
58
|
## 3. 里程碑
|
|
59
59
|
|
|
60
60
|
### M1 — 登录接入与连接(F1 + bot.ts + config.ts)
|
|
61
61
|
|
|
62
|
-
1. `package.json`、`tsconfig.json`、目录骨架;`config.ts
|
|
63
|
-
2. `bot.ts`:`
|
|
62
|
+
1. `package.json`、`tsconfig.json`、目录骨架;`config.ts`:只读 `~/.pi/agent/pi-qq.json` 设置,不读写凭据。
|
|
63
|
+
2. `bot.ts`:`start/stop`、装配 `messageFilter`(回声过滤)+ `accessPolicy`(白名单)+ `concurrencyGuard`;`ready/disconnected/error` 上报到 `ctx.ui`。
|
|
64
64
|
3. `login.ts` + `index.ts`:
|
|
65
|
-
- `session_start
|
|
66
|
-
- `/qq-login`:`startQrConnect`(`displayQrCodeToConsole: false`),`onQrDisplayed` 在 TUI 弹窗画二维码(`qrcode-terminal`),`onSuccess`
|
|
67
|
-
- `/qq-status
|
|
65
|
+
- `session_start`:进程内存有登录态则启动;否则提示 `/qq-login`。
|
|
66
|
+
- `/qq-login`:`startQrConnect`(`displayQrCodeToConsole: false`),`onQrDisplayed` 在 TUI 弹窗画二维码(`qrcode-terminal`),`onSuccess` 把凭据与 openid 存入内存并启动。
|
|
67
|
+
- `/qq-status`(内存登录/连接/绑定用户)、`/qq-logout`(清内存凭据)。
|
|
68
68
|
|
|
69
|
-
|
|
69
|
+
**验收**:扫码后 `/qq-status` 在线;pi 进程重启后需重新扫码;`4914/4915` 致命关闭码给出明确提示。
|
|
70
70
|
|
|
71
71
|
### M2 — 单人聊天与完整回复(F2 文本 + F4 非流式 + reply-budget.ts)
|
|
72
72
|
|
|
@@ -118,7 +118,7 @@ pi-qq/
|
|
|
118
118
|
| 流式消息对非 C2C/过期 `msgId` 抛错 | 流式路径崩溃 | `openStream` 前置校验,失败即降级 `sendText`(M4 已含) |
|
|
119
119
|
| 被动额度耗尽(长 run 多回复) | 消息发不出去 | reply-budget 统一发牌,超限降级主动+提示;摘要固定合并 |
|
|
120
120
|
| markdown 转换漏判 | QQ 端残留记号 | 转换函数单测覆盖常见结构;允许透传开关兜底 |
|
|
121
|
-
| connector 混淆代码异常 / 扫码接口变更 |
|
|
121
|
+
| connector 混淆代码异常 / 扫码接口变更 | 无法登录 | 重试扫码;升级 connector;保留日志排查 |
|
|
122
122
|
| pi 事件在非 TUI 模式无 UI | 扩展报错 | 所有 `ctx.ui` 调用前判 `ctx.hasUI`/`ctx.mode` |
|
|
123
123
|
|
|
124
124
|
## 6. Todo-List(随进度勾选)
|
|
@@ -127,16 +127,16 @@ pi-qq/
|
|
|
127
127
|
|
|
128
128
|
- [x] 依赖安装:`@tencent-connect/qqbot-nodejs` + `@tencent-connect/qqbot-connector` + `qrcode-terminal`(用户已执行)
|
|
129
129
|
- [x] pi / SDK / connector API 签名核对(types.d.ts + 本地源码)
|
|
130
|
-
- [x] `package.json` 完善(`type: module`、private
|
|
130
|
+
- [x] `package.json` 完善(`type: module`、description;发布时移除 private)
|
|
131
131
|
- [x] `tsconfig.json`(`moduleResolution: bundler`;`paths` 借用 pi 发行目录类型 + `typeRoots` 借用其 @types/node,typecheck 走 `npx typescript`,无需安装 devDeps)
|
|
132
132
|
|
|
133
133
|
### M1 — 登录接入与连接
|
|
134
134
|
|
|
135
|
-
- [x] `src/config.ts`:`~/.pi/agent/pi-qq.json`
|
|
135
|
+
- [x] `src/config.ts`:`~/.pi/agent/pi-qq.json` 只读设置(不含凭据)
|
|
136
136
|
- [x] `src/bot.ts`:`createBot/start/stop`、中间件装配(messageFilter/accessPolicy/concurrencyGuard)、连接状态跟踪、致命关闭码上报
|
|
137
|
-
- [x] `src/login.ts
|
|
138
|
-
- [x] `index.ts`:`/qq-login` `/qq-status` `/qq-logout` 命令 + `session_start`
|
|
139
|
-
- [x]
|
|
137
|
+
- [x] `src/login.ts`:仅扫码 `startQrConnect`(含二维码展示与取消;凭据返回内存)
|
|
138
|
+
- [x] `index.ts`:`/qq-login` `/qq-status` `/qq-logout` 命令 + 内存登录态 + `session_start` 接入 + `session_shutdown` 幂等停止
|
|
139
|
+
- [x] 验收:扫码在线 / pi 重启后重新扫码 / `4914` `4915` 明确提示(扫码路径已实测;`4914/4915` 如未触发可在后续观察)
|
|
140
140
|
|
|
141
141
|
### M2 — 单人聊天与完整回复(非流式)
|
|
142
142
|
|
package/index.ts
CHANGED
|
@@ -1,13 +1,5 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
-
import {
|
|
3
|
-
clearCredentials,
|
|
4
|
-
getCredentials,
|
|
5
|
-
getSettings,
|
|
6
|
-
readConfig,
|
|
7
|
-
saveCredentials,
|
|
8
|
-
type Credentials,
|
|
9
|
-
type PiQQConfig,
|
|
10
|
-
} from "./src/config";
|
|
2
|
+
import { getSettings, readConfig, type Credentials } from "./src/config";
|
|
11
3
|
import { startBot, type BotState, type RunningBot } from "./src/bot";
|
|
12
4
|
import { runQrLogin } from "./src/login";
|
|
13
5
|
import { createInboundHandler } from "./src/inbound";
|
|
@@ -19,12 +11,30 @@ import { formatTokenCount, formatUsageSummary, sumUsageMessages, type UsageTotal
|
|
|
19
11
|
import { formatBudgetStatus } from "./src/budget-status";
|
|
20
12
|
|
|
21
13
|
/**
|
|
22
|
-
* pi-qq
|
|
23
|
-
*
|
|
24
|
-
* - M2:QQ 单人聊天注入 pi(inbound)+ assistant 消息非流式回传(message_end)
|
|
14
|
+
* pi-qq extension entry.
|
|
15
|
+
* QR login only; credentials live in process memory and are never persisted.
|
|
25
16
|
*/
|
|
26
17
|
|
|
27
|
-
/**
|
|
18
|
+
/** In-memory login state; survives extension reload/session replacement in one process. */
|
|
19
|
+
interface LoginState {
|
|
20
|
+
credentials: Credentials;
|
|
21
|
+
allowedOpenid: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const LOGIN_STATE_KEY = "__piQQLoginState";
|
|
25
|
+
type GlobalWithLogin = typeof globalThis & { [LOGIN_STATE_KEY]?: LoginState };
|
|
26
|
+
|
|
27
|
+
function getLoginState(): LoginState | undefined {
|
|
28
|
+
return (globalThis as GlobalWithLogin)[LOGIN_STATE_KEY];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function setLoginState(state: LoginState | undefined): void {
|
|
32
|
+
const store = globalThis as GlobalWithLogin;
|
|
33
|
+
if (state) store[LOGIN_STATE_KEY] = state;
|
|
34
|
+
else delete store[LOGIN_STATE_KEY];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Session-level runtime state; rebuilt by a new runtime after reload/session switch. */
|
|
28
38
|
let running: RunningBot | undefined;
|
|
29
39
|
let lastState: BotState = "stopped";
|
|
30
40
|
let stateDetail: string | undefined;
|
|
@@ -33,7 +43,7 @@ const budget = new ReplyBudget();
|
|
|
33
43
|
const runFeedback = new RunFeedback({
|
|
34
44
|
bot: () => running?.bot,
|
|
35
45
|
budget,
|
|
36
|
-
boundOpenid: () =>
|
|
46
|
+
boundOpenid: () => getLoginState()?.allowedOpenid,
|
|
37
47
|
getHeartbeatMinutes: () => getSettings(readConfig().config).heartbeatMinutes,
|
|
38
48
|
getHeartbeatMaxMessages: () => getSettings(readConfig().config).heartbeatMaxMessages,
|
|
39
49
|
getStreamRelay: () => getSettings(readConfig().config).streamRelay,
|
|
@@ -41,20 +51,20 @@ const runFeedback = new RunFeedback({
|
|
|
41
51
|
getDebug: () => getSettings(readConfig().config).debug,
|
|
42
52
|
makeChannel: () => ({
|
|
43
53
|
budget,
|
|
44
|
-
boundOpenid:
|
|
54
|
+
boundOpenid: getLoginState()?.allowedOpenid ?? "",
|
|
45
55
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
46
56
|
}),
|
|
47
57
|
onWarn: (msg) => sessionCtx?.ui.notify(`pi-qq ${msg}`, "warning"),
|
|
48
58
|
});
|
|
49
59
|
|
|
50
|
-
const fmtTokens = (n: number | null): string => (n === null ? "
|
|
60
|
+
const fmtTokens = (n: number | null): string => (n === null ? "unknown" : formatTokenCount(n));
|
|
51
61
|
|
|
52
62
|
export default function (pi: ExtensionAPI) {
|
|
53
63
|
const maskAppId = (appId: string) => `${appId.slice(0, 4)}****`;
|
|
54
64
|
|
|
55
65
|
// —— 实时配置读取器(绑定/设置变更即时生效)——
|
|
56
66
|
|
|
57
|
-
const getAllowedOpenid = () =>
|
|
67
|
+
const getAllowedOpenid = () => getLoginState()?.allowedOpenid;
|
|
58
68
|
const getBoundOpenid = getAllowedOpenid;
|
|
59
69
|
const getDeliverAs = () => getSettings(readConfig().config).deliverAs;
|
|
60
70
|
|
|
@@ -66,7 +76,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
66
76
|
const settings = getSettings(config);
|
|
67
77
|
if (!settings.usageRelay) return null;
|
|
68
78
|
|
|
69
|
-
const bound =
|
|
79
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
70
80
|
const bot = running?.bot;
|
|
71
81
|
const hasUsage = usage.input + usage.output + usage.cacheRead + usage.cacheWrite > 0;
|
|
72
82
|
if (!bound || !bot || !hasUsage) return null;
|
|
@@ -87,31 +97,34 @@ export default function (pi: ExtensionAPI) {
|
|
|
87
97
|
};
|
|
88
98
|
|
|
89
99
|
const getStatusLines = (): string[] => {
|
|
90
|
-
const
|
|
100
|
+
const login = getLoginState();
|
|
91
101
|
const usage = sessionCtx?.getContextUsage();
|
|
92
102
|
const model = sessionCtx?.model;
|
|
93
103
|
return [
|
|
94
|
-
"pi-qq
|
|
95
|
-
|
|
96
|
-
|
|
104
|
+
"pi-qq status",
|
|
105
|
+
`Login: ${login ? `QR login, in memory (AppID ${maskAppId(login.credentials.appId)})` : "not logged in"}`,
|
|
106
|
+
`Connection: ${lastState}${stateDetail ? ` (${stateDetail})` : ""}`,
|
|
107
|
+
`Model: ${model?.name ?? "none"}`,
|
|
97
108
|
usage
|
|
98
|
-
?
|
|
99
|
-
: "
|
|
100
|
-
|
|
109
|
+
? `Context: ${fmtTokens(usage.tokens)}/${fmtTokens(usage.contextWindow)} (${usage.percent?.toFixed(1) ?? "?"}%)`
|
|
110
|
+
: "Context: unknown",
|
|
111
|
+
`Bound user: ${login?.allowedOpenid ?? "none"}`,
|
|
112
|
+
`Settings: ~/.pi/agent/pi-qq.json`,
|
|
101
113
|
];
|
|
102
114
|
};
|
|
103
115
|
|
|
104
|
-
// ——
|
|
116
|
+
// —— Login and connection ——
|
|
105
117
|
|
|
106
|
-
const startWithCredentials = (ctx: ExtensionContext, creds: Credentials,
|
|
118
|
+
const startWithCredentials = (ctx: ExtensionContext, creds: Credentials, allowedOpenid: string) => {
|
|
119
|
+
const settings = getSettings(readConfig().config);
|
|
107
120
|
running?.stop();
|
|
108
121
|
stateDetail = undefined;
|
|
109
122
|
sessionCtx = ctx;
|
|
110
123
|
running = startBot({
|
|
111
124
|
credentials: creds,
|
|
112
|
-
allowedOpenid
|
|
113
|
-
markdownSupport:
|
|
114
|
-
debug:
|
|
125
|
+
allowedOpenid,
|
|
126
|
+
markdownSupport: settings.markdownSupport,
|
|
127
|
+
debug: settings.debug,
|
|
115
128
|
onMessage: createInboundHandler({
|
|
116
129
|
pi,
|
|
117
130
|
ctx,
|
|
@@ -128,13 +141,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
128
141
|
onStateChange: (state, detail) => {
|
|
129
142
|
lastState = state;
|
|
130
143
|
stateDetail = detail;
|
|
131
|
-
|
|
132
|
-
if (state === "
|
|
133
|
-
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "连接被致命关闭"}`, "error");
|
|
144
|
+
if (state === "connected") ctx.ui.notify("pi-qq connected", "info");
|
|
145
|
+
else if (state === "blocked") ctx.ui.notify(`pi-qq ${detail ?? "connection blocked"}`, "error");
|
|
134
146
|
else if (state === "stopped" && detail) ctx.ui.notify(`pi-qq ${detail}`, "warning");
|
|
135
147
|
},
|
|
136
148
|
onRecoverableError: () => {
|
|
137
|
-
//
|
|
149
|
+
// Recoverable errors are handled by the SDK reconnect loop.
|
|
138
150
|
},
|
|
139
151
|
});
|
|
140
152
|
};
|
|
@@ -143,24 +155,20 @@ export default function (pi: ExtensionAPI) {
|
|
|
143
155
|
running?.stop();
|
|
144
156
|
running = undefined;
|
|
145
157
|
lastState = "stopped";
|
|
158
|
+
stateDetail = undefined;
|
|
146
159
|
};
|
|
147
160
|
|
|
148
|
-
// ——
|
|
161
|
+
// —— Lifecycle ——
|
|
149
162
|
|
|
150
163
|
pi.on("session_start", (_event, ctx) => {
|
|
151
|
-
const {
|
|
152
|
-
if (error) {
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (creds) {
|
|
158
|
-
startWithCredentials(ctx, creds, config, "配置直连");
|
|
164
|
+
const { error } = readConfig();
|
|
165
|
+
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
166
|
+
|
|
167
|
+
const login = getLoginState();
|
|
168
|
+
if (login) {
|
|
169
|
+
startWithCredentials(ctx, login.credentials, login.allowedOpenid);
|
|
159
170
|
} else if (ctx.hasUI) {
|
|
160
|
-
ctx.ui.notify(
|
|
161
|
-
"pi-qq 未配置机器人凭据:执行 /qq-login 扫码登录,或在 ~/.pi/agent/pi-qq.json 写入 { AppID, AppSecret } 后重启会话",
|
|
162
|
-
"warning",
|
|
163
|
-
);
|
|
171
|
+
ctx.ui.notify("pi-qq: run /qq-login to scan a QR code.", "warning");
|
|
164
172
|
}
|
|
165
173
|
});
|
|
166
174
|
|
|
@@ -248,9 +256,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
248
256
|
|
|
249
257
|
const payload = settings.markdownSupport ? text : markdownToPlain(text);
|
|
250
258
|
|
|
251
|
-
const bound =
|
|
259
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
252
260
|
if (!bound) {
|
|
253
|
-
ctx.ui.notify("pi-qq
|
|
261
|
+
ctx.ui.notify("pi-qq: no bound QQ user; skipping reply.", "warning");
|
|
254
262
|
return;
|
|
255
263
|
}
|
|
256
264
|
|
|
@@ -261,142 +269,126 @@ export default function (pi: ExtensionAPI) {
|
|
|
261
269
|
});
|
|
262
270
|
});
|
|
263
271
|
|
|
264
|
-
// ——
|
|
272
|
+
// —— Commands ——
|
|
265
273
|
|
|
266
274
|
pi.registerCommand("qq-login", {
|
|
267
|
-
description: "pi-qq
|
|
275
|
+
description: "pi-qq: log in with a QR code and bind the scanning QQ user",
|
|
268
276
|
handler: async (_args, ctx) => {
|
|
269
|
-
const {
|
|
270
|
-
if (error) {
|
|
271
|
-
|
|
277
|
+
const { error } = readConfig();
|
|
278
|
+
if (error) ctx.ui.notify(`pi-qq ${error}`, "error");
|
|
279
|
+
|
|
280
|
+
stopIfRunning();
|
|
281
|
+
setLoginState(undefined);
|
|
282
|
+
const result = await runQrLogin(ctx);
|
|
283
|
+
if (!result) return;
|
|
284
|
+
if (!result.userOpenid) {
|
|
285
|
+
ctx.ui.notify("pi-qq: QR login did not return a user openid; cannot bind.", "error");
|
|
272
286
|
return;
|
|
273
287
|
}
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
const creds = await runQrLogin(ctx);
|
|
279
|
-
if (!creds) return; // 取消或失败,原因已提示
|
|
280
|
-
saveCredentials(creds, { userOpenid: creds.userOpenid });
|
|
281
|
-
startWithCredentials(
|
|
282
|
-
ctx,
|
|
283
|
-
creds,
|
|
284
|
-
{ ...config, allowedOpenid: creds.userOpenid ?? config.allowedOpenid },
|
|
285
|
-
"扫码登录",
|
|
286
|
-
);
|
|
288
|
+
|
|
289
|
+
const credentials: Credentials = { appId: result.appId, appSecret: result.appSecret };
|
|
290
|
+
setLoginState({ credentials, allowedOpenid: result.userOpenid });
|
|
291
|
+
startWithCredentials(ctx, credentials, result.userOpenid);
|
|
287
292
|
},
|
|
288
293
|
});
|
|
289
294
|
|
|
290
295
|
pi.registerCommand("qq-status", {
|
|
291
|
-
description: "pi-qq
|
|
296
|
+
description: "pi-qq: show login, connection, and bound QQ user",
|
|
292
297
|
handler: async (_args, ctx) => {
|
|
293
|
-
|
|
294
|
-
const creds = error ? null : getCredentials(config);
|
|
295
|
-
const source = creds ? (config.AppID ? "配置文件(AppID)" : "扫码写入") : "未配置";
|
|
296
|
-
const lines = [
|
|
297
|
-
"pi-qq 状态",
|
|
298
|
-
`连接:${lastState}${stateDetail ? `(${stateDetail})` : ""}`,
|
|
299
|
-
creds ? `凭据:${maskAppId(creds.appId)}(来源:${source})` : "凭据:未配置",
|
|
300
|
-
`绑定用户:${config.allowedOpenid ?? "未绑定"}`,
|
|
301
|
-
"配置文件:~/.pi/agent/pi-qq.json",
|
|
302
|
-
];
|
|
303
|
-
ctx.ui.notify(lines.join("\n"), error ? "warning" : "info");
|
|
298
|
+
ctx.ui.notify(getStatusLines().join("\n"), "info");
|
|
304
299
|
},
|
|
305
300
|
});
|
|
306
301
|
|
|
307
302
|
pi.registerCommand("qq-budget", {
|
|
308
|
-
description: "pi-qq
|
|
303
|
+
description: "pi-qq: show passive reply budget, stream bubbles, and last inbound target",
|
|
309
304
|
handler: async (_args, ctx) => {
|
|
310
305
|
ctx.ui.notify(formatBudgetStatus(budget.snapshot(), budget.lastTarget).join("\n"), "info");
|
|
311
306
|
},
|
|
312
307
|
});
|
|
313
308
|
|
|
314
309
|
pi.registerCommand("qq-logout", {
|
|
315
|
-
description: "pi-qq
|
|
310
|
+
description: "pi-qq: log out and clear in-memory credentials",
|
|
316
311
|
handler: async (_args, ctx) => {
|
|
317
312
|
stopIfRunning();
|
|
318
|
-
|
|
319
|
-
ctx.ui.notify("pi-qq
|
|
313
|
+
setLoginState(undefined);
|
|
314
|
+
ctx.ui.notify("pi-qq logged out. Credentials cleared from memory; run /qq-login to scan again.", "info");
|
|
320
315
|
},
|
|
321
316
|
});
|
|
322
317
|
|
|
323
318
|
pi.registerCommand("qq-new", {
|
|
324
|
-
description: "pi-qq
|
|
319
|
+
description: "pi-qq: reset the current session (used by QQ /new)",
|
|
325
320
|
handler: async (_args, ctx) => {
|
|
326
321
|
if (!ctx.isIdle()) {
|
|
327
|
-
ctx.ui.notify("
|
|
322
|
+
ctx.ui.notify("pi-qq: the agent is busy; run /stop before resetting the session.", "warning");
|
|
328
323
|
return;
|
|
329
324
|
}
|
|
330
325
|
const { cancelled } = await ctx.newSession();
|
|
331
|
-
if (cancelled) ctx.ui.notify("
|
|
326
|
+
if (cancelled) ctx.ui.notify("pi-qq: session reset cancelled.", "warning");
|
|
332
327
|
},
|
|
333
328
|
});
|
|
334
329
|
|
|
335
|
-
// ——
|
|
330
|
+
// —— Diagnostic commands ——
|
|
336
331
|
|
|
337
332
|
const diagTarget = () => {
|
|
338
333
|
const last = budget.lastTarget;
|
|
339
334
|
if (last) return { scope: "c2c" as const, targetId: last.openid, msgId: last.msgId };
|
|
340
|
-
const bound =
|
|
335
|
+
const bound = getLoginState()?.allowedOpenid;
|
|
341
336
|
return bound ? { scope: "c2c" as const, targetId: bound } : undefined;
|
|
342
337
|
};
|
|
343
338
|
|
|
344
339
|
pi.registerCommand("qq-md", {
|
|
345
|
-
description: "pi-qq
|
|
340
|
+
description: "pi-qq: send a Markdown message to verify QQ C2C Markdown rendering",
|
|
346
341
|
handler: async (args, ctx) => {
|
|
347
342
|
if (!running) {
|
|
348
|
-
ctx.ui.notify("pi-qq
|
|
343
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
349
344
|
return;
|
|
350
345
|
}
|
|
351
346
|
const target = diagTarget();
|
|
352
347
|
if (!target) {
|
|
353
|
-
ctx.ui.notify("pi-qq
|
|
348
|
+
ctx.ui.notify("pi-qq: no send target. Send a QQ message first.", "warning");
|
|
354
349
|
return;
|
|
355
350
|
}
|
|
356
|
-
const content = args?.trim() || "**Markdown
|
|
351
|
+
const content = args?.trim() || "**Markdown test**\n# Heading\n- Item one\n- Item two\n[Link](https://qq.com)";
|
|
357
352
|
try {
|
|
358
353
|
await running.bot.sendMarkdown(target, content);
|
|
359
|
-
ctx.ui.notify(
|
|
360
|
-
"已发送 Markdown 测试消息:若 QQ 中渲染为富文本 → C2C markdown 可用;若显示原文/报错 → 记录现象",
|
|
361
|
-
"info",
|
|
362
|
-
);
|
|
354
|
+
ctx.ui.notify("Markdown test sent. Check whether QQ renders it as rich text.", "info");
|
|
363
355
|
} catch (err) {
|
|
364
|
-
ctx.ui.notify(`Markdown
|
|
356
|
+
ctx.ui.notify(`Markdown send failed: ${(err as Error).message}`, "error");
|
|
365
357
|
}
|
|
366
358
|
},
|
|
367
359
|
});
|
|
368
360
|
|
|
369
361
|
pi.registerCommand("qq-stream-test", {
|
|
370
|
-
description: "pi-qq
|
|
362
|
+
description: "pi-qq: run a streamed timeline diagnostic (thinking/tools/text)",
|
|
371
363
|
handler: async (_args, ctx) => {
|
|
372
364
|
if (!running) {
|
|
373
|
-
ctx.ui.notify("pi-qq
|
|
365
|
+
ctx.ui.notify("pi-qq is not connected.", "warning");
|
|
374
366
|
return;
|
|
375
367
|
}
|
|
376
368
|
const last = budget.lastTarget;
|
|
377
369
|
if (!last) {
|
|
378
|
-
ctx.ui.notify("pi-qq
|
|
370
|
+
ctx.ui.notify("pi-qq: send a QQ message first (streaming needs a msgId).", "warning");
|
|
379
371
|
return;
|
|
380
372
|
}
|
|
381
373
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
382
374
|
try {
|
|
383
375
|
const stream = new AppendStream(running.bot.messageApi, running.bot.getCredentials(), last.openid, last.msgId);
|
|
384
|
-
await stream.append("
|
|
376
|
+
await stream.append("Thinking...\n[3] 🔧 bash\n[2] 🔧 read\n");
|
|
385
377
|
await sleep(1200);
|
|
386
|
-
await stream.append("\n
|
|
378
|
+
await stream.append("\n**Intermediate message**: first-turn reply.\n");
|
|
387
379
|
await sleep(1200);
|
|
388
380
|
await stream.append("[1] 🔧 edit\n");
|
|
389
381
|
await sleep(800);
|
|
390
|
-
await stream.append("\n
|
|
391
|
-
let doneNote = "DONE
|
|
382
|
+
await stream.append("\n**Final reply** (streamed append)");
|
|
383
|
+
let doneNote = "DONE succeeded";
|
|
392
384
|
try {
|
|
393
385
|
await stream.done();
|
|
394
386
|
} catch (doneErr) {
|
|
395
|
-
doneNote = `DONE
|
|
387
|
+
doneNote = `DONE rejected: ${(doneErr as Error).message}`;
|
|
396
388
|
}
|
|
397
|
-
ctx.ui.notify(
|
|
389
|
+
ctx.ui.notify(`Stream timeline test: frames sent, ${doneNote}. Check the QQ activity timeline.`, "info");
|
|
398
390
|
} catch (err) {
|
|
399
|
-
ctx.ui.notify(
|
|
391
|
+
ctx.ui.notify(`Stream timeline test failed: ${(err as Error).message}`, "error");
|
|
400
392
|
}
|
|
401
393
|
},
|
|
402
394
|
});
|
package/package.json
CHANGED
package/src/bot.ts
CHANGED
|
@@ -24,7 +24,7 @@ export type BotState =
|
|
|
24
24
|
|
|
25
25
|
export interface StartBotOptions {
|
|
26
26
|
credentials: Credentials;
|
|
27
|
-
/** F2
|
|
27
|
+
/** F2: QR-bound single user; production always provides it */
|
|
28
28
|
allowedOpenid?: string;
|
|
29
29
|
markdownSupport?: boolean;
|
|
30
30
|
/** 诊断模式:SDK 内部日志(超时/限流/重连等)打到终端 */
|
|
@@ -54,7 +54,7 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
54
54
|
bot.use(messageFilter({ skipSelfEcho: true }));
|
|
55
55
|
// 清洗 @marker / face tags 等协议标记,只留纯文本
|
|
56
56
|
bot.use(contentSanitizer({ stripBotMention: true }));
|
|
57
|
-
//
|
|
57
|
+
// Single-user allowlist for C2C; inbound also rejects when no QR login is active.
|
|
58
58
|
bot.use(accessPolicy(opts.allowedOpenid ? { c2c: { mode: "allowlist", allow: [opts.allowedOpenid] } } : {}));
|
|
59
59
|
// 同用户串行处理,避免流式与回复互相踩踏
|
|
60
60
|
bot.use(concurrencyGuard());
|
|
@@ -72,19 +72,19 @@ export function startBot(opts: StartBotOptions): RunningBot {
|
|
|
72
72
|
let stopped = false;
|
|
73
73
|
report("starting");
|
|
74
74
|
void bot.start().catch((err: unknown) => {
|
|
75
|
-
if (stopped) return; //
|
|
75
|
+
if (stopped) return; // Normal return from an explicit stop().
|
|
76
76
|
const code = (err as { code?: string }).code;
|
|
77
77
|
if (code === GatewayErrorCode.FATAL_CLOSE) {
|
|
78
78
|
const closeCode = (err as { closeCode?: number }).closeCode;
|
|
79
79
|
report(
|
|
80
80
|
"blocked",
|
|
81
|
-
|
|
82
|
-
|
|
81
|
+
`Connection closed by the server (${closeCode ?? "unknown"}, 4914=offline/sandbox, 4915=banned). ` +
|
|
82
|
+
`Check the bot status on the QQ Open Platform, or run /qq-login again.`,
|
|
83
83
|
);
|
|
84
84
|
} else if (code === GatewayErrorCode.RETRY_EXHAUSTED) {
|
|
85
|
-
report("stopped",
|
|
85
|
+
report("stopped", `Reconnect budget exhausted: ${(err as Error).message}; run /qq-login to retry.`);
|
|
86
86
|
} else {
|
|
87
|
-
report("stopped",
|
|
87
|
+
report("stopped", `Startup failed: ${(err as Error).message}; check credentials and network.`);
|
|
88
88
|
}
|
|
89
89
|
});
|
|
90
90
|
|
package/src/budget-status.ts
CHANGED
|
@@ -10,7 +10,7 @@ function mask(value: string): string {
|
|
|
10
10
|
return `${value.slice(0, 8)}…`;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
/**
|
|
13
|
+
/** Render `/qq-budget` output lines; pure function for tests. */
|
|
14
14
|
export function formatBudgetStatus(
|
|
15
15
|
snapshot: BudgetSnapshot,
|
|
16
16
|
last: BudgetTarget | undefined,
|
|
@@ -20,13 +20,13 @@ export function formatBudgetStatus(
|
|
|
20
20
|
const estimated = snapshot.hasTarget ? Math.max(0, snapshot.remaining - snapshot.streamBubbles) : null;
|
|
21
21
|
|
|
22
22
|
return [
|
|
23
|
-
"pi-qq
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
`msgId
|
|
30
|
-
|
|
23
|
+
"pi-qq passive reply budget",
|
|
24
|
+
`Limit: ${snapshot.limit}/msg (${snapshot.ttlHours}h)`,
|
|
25
|
+
`Last inbound: ${last ? `${mask(last.openid)} / ${mask(last.msgId)}, ${ageSec}s ago` : "none"}`,
|
|
26
|
+
`Passive remaining: ${snapshot.hasTarget ? snapshot.remaining : "—"}`,
|
|
27
|
+
`Stream bubbles: ${snapshot.streamBubbles} (current msgId)`,
|
|
28
|
+
`Estimated remaining: ${estimated ?? "—"} (diagnostic only)`,
|
|
29
|
+
`msgId window: ${snapshot.hasTarget ? (snapshot.fresh ? "valid" : "expired") : "—"}`,
|
|
30
|
+
`Recorded: passive ${snapshot.totalReplies} / stream ${snapshot.streamBubblesTotal} / ${snapshot.trackedMessages} msgId(s)`,
|
|
31
31
|
];
|
|
32
32
|
}
|
package/src/config.ts
CHANGED
|
@@ -1,52 +1,44 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import {
|
|
3
|
+
import { join } from "node:path";
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
* ~/.pi/agent/pi-qq.json
|
|
6
|
+
* ~/.pi/agent/pi-qq.json contains non-secret settings only.
|
|
7
7
|
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
8
|
+
* QQ credentials are intentionally never written to disk: QR login keeps them in
|
|
9
|
+
* process memory, so restarting pi requires scanning a new QR code.
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
/**
|
|
12
|
+
/** Runtime settings (features.md §4). */
|
|
13
13
|
export interface PiQQSettings {
|
|
14
|
-
/** F4
|
|
14
|
+
/** F4: stream assistant replies */
|
|
15
15
|
streamAssistant?: boolean;
|
|
16
|
-
/** F4
|
|
16
|
+
/** F4: bot has QQ markdown permission; pass Markdown through when true */
|
|
17
17
|
markdownSupport?: boolean;
|
|
18
|
-
/** F5/F6
|
|
18
|
+
/** F5/F6: usage summary switch */
|
|
19
19
|
usageRelay?: boolean;
|
|
20
|
-
/** F2
|
|
20
|
+
/** F2: how a busy agent handles new messages */
|
|
21
21
|
deliverAs?: "steer" | "followUp";
|
|
22
|
-
/** F3
|
|
22
|
+
/** F3: QQ image download limit (bytes) */
|
|
23
23
|
imageMaxSize?: number;
|
|
24
|
-
/** F3
|
|
24
|
+
/** F3: QQ file download limit (bytes), default 50MB */
|
|
25
25
|
fileMaxSize?: number;
|
|
26
|
-
/** F7
|
|
26
|
+
/** F7: heartbeat interval in minutes, 0 disables */
|
|
27
27
|
heartbeatMinutes?: number;
|
|
28
|
-
/** F7
|
|
28
|
+
/** F7: per-run message heartbeat limit */
|
|
29
29
|
heartbeatMaxMessages?: number;
|
|
30
|
-
/** F7
|
|
30
|
+
/** F7: stream summary frame interval (ms, minimum 300) */
|
|
31
31
|
streamFlushMs?: number;
|
|
32
|
-
/**
|
|
32
|
+
/** Diagnostic mode: SDK logs + stream retry/timeout logs */
|
|
33
33
|
debug?: boolean;
|
|
34
|
-
/** F7
|
|
35
|
-
* 无 markdown 权限的机器人必须保持 false(实测:气泡停在 "..." 且结果被流接管丢失) */
|
|
34
|
+
/** F7: append-mode stream relay switch */
|
|
36
35
|
streamRelay?: boolean;
|
|
37
36
|
}
|
|
38
37
|
|
|
39
|
-
/**
|
|
40
|
-
export
|
|
41
|
-
AppID?: string;
|
|
42
|
-
AppSecret?: string;
|
|
43
|
-
/** 兼容小写写法(仅读取) */
|
|
44
|
-
appId?: string;
|
|
45
|
-
appSecret?: string;
|
|
46
|
-
/** F2:单人绑定的 openid 白名单 */
|
|
47
|
-
allowedOpenid?: string;
|
|
48
|
-
}
|
|
38
|
+
/** Settings file schema (legacy credential keys are ignored). */
|
|
39
|
+
export type PiQQConfig = PiQQSettings;
|
|
49
40
|
|
|
41
|
+
/** QR login result; kept in memory only. */
|
|
50
42
|
export interface Credentials {
|
|
51
43
|
appId: string;
|
|
52
44
|
appSecret: string;
|
|
@@ -54,7 +46,7 @@ export interface Credentials {
|
|
|
54
46
|
|
|
55
47
|
export const CONFIG_PATH = join(homedir(), ".pi", "agent", "pi-qq.json");
|
|
56
48
|
|
|
57
|
-
/**
|
|
49
|
+
/** Read settings; missing file yields empty settings, malformed JSON returns an error. */
|
|
58
50
|
export function readConfig(): { config: PiQQConfig; error?: string } {
|
|
59
51
|
let raw: string;
|
|
60
52
|
try {
|
|
@@ -65,59 +57,13 @@ export function readConfig(): { config: PiQQConfig; error?: string } {
|
|
|
65
57
|
try {
|
|
66
58
|
return { config: JSON.parse(raw) as PiQQConfig };
|
|
67
59
|
} catch (e) {
|
|
68
|
-
return { config: {}, error:
|
|
60
|
+
return { config: {}, error: `Failed to parse config file (${CONFIG_PATH}): ${(e as Error).message}` };
|
|
69
61
|
}
|
|
70
62
|
}
|
|
71
63
|
|
|
72
|
-
/** 从配置提取机器人凭据(大写/小写键均可),不完整返回 null。 */
|
|
73
|
-
export function getCredentials(config: PiQQConfig): Credentials | null {
|
|
74
|
-
const appId = config.AppID ?? config.appId;
|
|
75
|
-
const appSecret = config.AppSecret ?? config.appSecret;
|
|
76
|
-
if (appId && appSecret) return { appId, appSecret };
|
|
77
|
-
return null;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function writeConfig(config: PiQQConfig): void {
|
|
81
|
-
mkdirSync(dirname(CONFIG_PATH), { recursive: true });
|
|
82
|
-
// mode 只在新建文件时生效,已存在文件需显式 chmod 回 0600
|
|
83
|
-
writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 });
|
|
84
|
-
chmodSync(CONFIG_PATH, 0o600);
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** 写入凭据(归一化为大写键名,清除兼容小写键);userOpenid 提供时覆盖单人绑定。 */
|
|
88
|
-
export function saveCredentials(creds: Credentials, opts?: { userOpenid?: string }): void {
|
|
89
|
-
const { config, error } = readConfig();
|
|
90
|
-
if (error) throw new Error(`拒绝写入:${error}`);
|
|
91
|
-
delete config.appId;
|
|
92
|
-
delete config.appSecret;
|
|
93
|
-
config.AppID = creds.appId;
|
|
94
|
-
config.AppSecret = creds.appSecret;
|
|
95
|
-
if (opts?.userOpenid) config.allowedOpenid = opts.userOpenid;
|
|
96
|
-
writeConfig(config);
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
/** /qq-logout:清除凭据,保留 allowedOpenid 与其余设置(下次登录同一用户无需重配)。 */
|
|
100
|
-
export function clearCredentials(): void {
|
|
101
|
-
const { config, error } = readConfig();
|
|
102
|
-
if (error) return;
|
|
103
|
-
delete config.AppID;
|
|
104
|
-
delete config.AppSecret;
|
|
105
|
-
delete config.appId;
|
|
106
|
-
delete config.appSecret;
|
|
107
|
-
writeConfig(config);
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/** F2 的"首个私聊用户自动绑定"(M2 接线使用)。 */
|
|
111
|
-
export function setAllowedOpenid(openid: string): void {
|
|
112
|
-
const { config, error } = readConfig();
|
|
113
|
-
if (error) return;
|
|
114
|
-
config.allowedOpenid = openid;
|
|
115
|
-
writeConfig(config);
|
|
116
|
-
}
|
|
117
|
-
|
|
118
64
|
export interface ResolvedSettings extends Required<PiQQSettings> {}
|
|
119
65
|
|
|
120
|
-
/**
|
|
66
|
+
/** Settings with defaults applied (features.md §4). */
|
|
121
67
|
export function getSettings(config: PiQQConfig): ResolvedSettings {
|
|
122
68
|
return {
|
|
123
69
|
streamAssistant: config.streamAssistant ?? true,
|
|
@@ -130,7 +76,6 @@ export function getSettings(config: PiQQConfig): ResolvedSettings {
|
|
|
130
76
|
heartbeatMaxMessages: config.heartbeatMaxMessages ?? 3,
|
|
131
77
|
streamFlushMs: config.streamFlushMs ?? 10_000,
|
|
132
78
|
debug: config.debug ?? false,
|
|
133
|
-
// append 语义已实测可用(含节流与限流退避);失败自动降级消息路径,默认开启
|
|
134
79
|
streamRelay: config.streamRelay ?? true,
|
|
135
80
|
};
|
|
136
81
|
}
|
package/src/files.ts
CHANGED
|
@@ -129,10 +129,10 @@ export function formatFilePrompt(files: readonly SavedFile[], userText: string):
|
|
|
129
129
|
if (files.length === 0) return userText;
|
|
130
130
|
|
|
131
131
|
const lines = [
|
|
132
|
-
"
|
|
133
|
-
...files.map((file) => `- ${file.path}
|
|
132
|
+
"User sent the following file(s) via QQ (saved locally; use read/bash or other tools to access):",
|
|
133
|
+
...files.map((file) => `- ${file.path} (${formatBytes(file.size)}, original name: ${file.originalName})`),
|
|
134
134
|
];
|
|
135
135
|
const text = userText.trim();
|
|
136
|
-
if (text) lines.push("", "
|
|
136
|
+
if (text) lines.push("", "User message:", text);
|
|
137
137
|
return lines.join("\n");
|
|
138
138
|
}
|
package/src/inbound.ts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import type { QQBot, QQBotInboundMessage } from "@tencent-connect/qqbot-nodejs";
|
|
4
|
-
import { setAllowedOpenid } from "./config";
|
|
5
4
|
import { sendReply, type ReplyChannel } from "./outbound";
|
|
6
5
|
import type { ReplyBudget } from "./reply-budget";
|
|
7
6
|
import {
|
|
@@ -14,9 +13,9 @@ import {
|
|
|
14
13
|
import { formatFilePrompt, saveInboundFiles, type SavedFile } from "./files";
|
|
15
14
|
|
|
16
15
|
/**
|
|
17
|
-
* F2
|
|
18
|
-
*
|
|
19
|
-
*
|
|
16
|
+
* F2: QQ → pi inbound handling.
|
|
17
|
+
* Chain: C2C filter → QR-bound user whitelist → QQ commands → text/image/file injection.
|
|
18
|
+
* Use pi.sendUserMessage (ExtensionContext has no such API).
|
|
20
19
|
*/
|
|
21
20
|
|
|
22
21
|
export interface InboundDeps {
|
|
@@ -43,15 +42,9 @@ export function createInboundHandler(deps: InboundDeps) {
|
|
|
43
42
|
if (msg.kind !== "c2c") return;
|
|
44
43
|
|
|
45
44
|
const allowed = deps.getAllowedOpenid();
|
|
46
|
-
if (allowed
|
|
45
|
+
if (!allowed || msg.senderId !== allowed) return;
|
|
47
46
|
|
|
48
|
-
//
|
|
49
|
-
if (!allowed) {
|
|
50
|
-
setAllowedOpenid(msg.senderId);
|
|
51
|
-
deps.ctx.ui.notify(`pi-qq:已自动绑定首个私聊用户(${msg.senderId.slice(0, 8)}…)`, "info");
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// 记录被动回复目标与新鲜度起点(供 outbound 发牌)
|
|
47
|
+
// Record passive reply target/freshness for outbound budget.
|
|
55
48
|
deps.budget.observeInbound(msg.senderId, msg.messageId);
|
|
56
49
|
|
|
57
50
|
const channel: ReplyChannel = {
|
package/src/login.ts
CHANGED
|
@@ -4,23 +4,22 @@ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
|
4
4
|
import type { Credentials } from "./config";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* F1
|
|
8
|
-
* - TUI
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* connector 负责登录协议(生成绑定任务/轮询/解密),本模块只做展示与编排。
|
|
7
|
+
* F1: QR-code login only.
|
|
8
|
+
* - TUI: show an ASCII QR code in ctx.ui.custom; Esc cancels.
|
|
9
|
+
* - Non-TUI: print the QR URL and poll until the scan completes.
|
|
10
|
+
* Credentials are returned to the caller and kept in memory only.
|
|
12
11
|
*/
|
|
13
12
|
|
|
14
13
|
export interface QrLoginResult extends Credentials {
|
|
15
|
-
/**
|
|
14
|
+
/** openid of the scanning user, used as the single bound QQ user */
|
|
16
15
|
userOpenid?: string;
|
|
17
16
|
}
|
|
18
17
|
|
|
19
18
|
export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult | undefined> {
|
|
20
19
|
const ac = new AbortController();
|
|
21
20
|
|
|
22
|
-
//
|
|
23
|
-
const qr = { lines: [] as string[], hint: "
|
|
21
|
+
// Shared QR state so polling callbacks and the TUI component stay decoupled.
|
|
22
|
+
const qr = { lines: [] as string[], hint: "Fetching QR code…" };
|
|
24
23
|
let requestRender: (() => void) | undefined;
|
|
25
24
|
let closeOverlay: (() => void) | undefined;
|
|
26
25
|
|
|
@@ -35,28 +34,28 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
|
|
|
35
34
|
|
|
36
35
|
const stopPolling = startQrConnect(
|
|
37
36
|
{
|
|
38
|
-
//
|
|
37
|
+
// The connector currently returns one entry; iterate for future compatibility.
|
|
39
38
|
onSuccess: ([first]) => {
|
|
40
39
|
finish(first ? { appId: first.appId, appSecret: first.appSecret, userOpenid: first.userOpenid } : undefined);
|
|
41
40
|
closeOverlay?.();
|
|
42
41
|
},
|
|
43
42
|
onFailure: (err) => {
|
|
44
|
-
if (settled) return; //
|
|
45
|
-
ctx.ui.notify(
|
|
43
|
+
if (settled) return; // User cancelled (abort); no error toast.
|
|
44
|
+
ctx.ui.notify(`QR login failed: ${err.message}`, "error");
|
|
46
45
|
finish();
|
|
47
46
|
closeOverlay?.();
|
|
48
47
|
},
|
|
49
48
|
onQrDisplayed: (url) => {
|
|
50
|
-
qr.hint = "
|
|
49
|
+
qr.hint = "Scan with mobile QQ";
|
|
51
50
|
generate(url, { small: true }, (ascii) => {
|
|
52
51
|
qr.lines = ascii.split("\n").filter((line) => line.trim().length > 0);
|
|
53
52
|
});
|
|
54
53
|
requestRender?.();
|
|
55
|
-
//
|
|
56
|
-
if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq
|
|
54
|
+
// Non-TUI mode has no overlay; show the URL.
|
|
55
|
+
if (ctx.mode !== "tui") ctx.ui.notify(`pi-qq QR URL: ${url}`, "info");
|
|
57
56
|
},
|
|
58
57
|
onQrExpired: () => {
|
|
59
|
-
qr.hint = "
|
|
58
|
+
qr.hint = "QR code expired; refreshing…";
|
|
60
59
|
requestRender?.();
|
|
61
60
|
},
|
|
62
61
|
},
|
|
@@ -64,8 +63,8 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
|
|
|
64
63
|
);
|
|
65
64
|
|
|
66
65
|
if (ctx.mode !== "tui") {
|
|
67
|
-
//
|
|
68
|
-
ctx.ui.notify("pi-qq
|
|
66
|
+
// Non-TUI: no overlay or cancel affordance; wait for the scan.
|
|
67
|
+
ctx.ui.notify("pi-qq: waiting for mobile QQ scan…", "info");
|
|
69
68
|
return;
|
|
70
69
|
}
|
|
71
70
|
|
|
@@ -75,8 +74,8 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
|
|
|
75
74
|
requestRender = () => tui.requestRender();
|
|
76
75
|
return {
|
|
77
76
|
render(width: number): string[] {
|
|
78
|
-
const lines = qr.lines.length > 0 ? qr.lines : ["
|
|
79
|
-
return [...lines, "", qr.hint, theme.fg("dim", "Esc
|
|
77
|
+
const lines = qr.lines.length > 0 ? qr.lines : ["(fetching QR code…)"];
|
|
78
|
+
return [...lines, "", qr.hint, theme.fg("dim", "Esc to cancel")].map((line) =>
|
|
80
79
|
line.length > width ? line.slice(0, width) : line,
|
|
81
80
|
);
|
|
82
81
|
},
|
|
@@ -90,7 +89,7 @@ export async function runQrLogin(ctx: ExtensionContext): Promise<QrLoginResult |
|
|
|
90
89
|
};
|
|
91
90
|
})
|
|
92
91
|
.then(() => {
|
|
93
|
-
//
|
|
92
|
+
// Overlay closed by user; success/failure paths already called finish().
|
|
94
93
|
if (!settled) finish();
|
|
95
94
|
});
|
|
96
95
|
});
|