dsh-dot-life 0.10.18 → 0.11.2
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 +1 -1
- package/cordis.patch.yml +3 -2
- package/docs/DESIGN.md +22 -2
- package/docs/ROADMAP.md +13 -12
- package/docs/interlude.md +5 -5
- package/docs/phone.md +8 -4
- package/docs/qq.md +50 -16
- package/package.json +1 -1
- package/src/interlude/core.js +30 -11
- package/src/phone/phone.js +2 -2
- package/src/qq/qq.js +81 -31
- package/src/qq/stickers.js +77 -0
package/README.md
CHANGED
|
@@ -68,7 +68,7 @@ Web 版:`dsh plugin --profile web add dsh-dot-life`。从源码装:把包名
|
|
|
68
68
|
1. **手机**:在 dsh 里发 `/phone accept`(默认给手机 16 GB 存储;要别的大小发 `/phone accept 32` 这样,手机建好后不能再改)——接受 [Android SDK 许可](https://developer.android.com/studio/terms)后插件开始下载(约 2 GB,进度在 `~/.dsh/dsh-phone.log`),装完自动开机,桌面上出现一个手机窗口。`/phone` 看状态。
|
|
69
69
|
2. **装 App、登录**:在手机窗口里像用真手机一样操作:从官网下 APK 用 `adb install`(`~/.dsh/phone/platform-tools/adb`),或者让她自己装(`mobile_install_app` 会弹审批)。登录、验证码、人脸都由你在窗口里亲手过——她遇到会停下来叫你。**用小号。** 各平台的条款都不允许自动化,封了就封了。
|
|
70
70
|
3. **人设**:`/interlude preset <分享码>` 从 [typ0.space](https://typ0.space) 导入一份 HDSI 预设,或者把 `examples/canon.minase-style.json` 放到 `~/dot/interlude/canon.json`。
|
|
71
|
-
4.
|
|
71
|
+
4. **她在手机上看什么、玩什么**:不用配。常见社区 App(小黑盒、B 站、微博、小红书、知乎、抖音、酷安、贴吧、豆瓣)的站 → 包名表是内置的,只对她**自己装了**的 App 生效:有 App 的站她用手机去看(只读、无审批、每天有上限),幕间里想点赞 / 评论 / 关注就在那些 App 里做。别的 App 在 profile 的 `cordis.patch.yml` 里给 `dot-interlude` 加 `phoneApps` / `playApps`。
|
|
72
72
|
5. **她的 QQ**:`/qq install` → `/qq account <小号>` → `/qq start` → `/qq qr`,在「手机」标签页里用她手机上的 QQ 扫一扫(码会出现在她的摄像头画面里)确认电脑登录(详见 [docs/qq.md](docs/qq.md))。之后你在 QQ 里给她发消息,1–2 秒叫醒她,她用 `qq_send` 回。不想用协议端的,按 dsh-im 的说明接一个官方机器人也行。
|
|
73
73
|
6. **电脑(可选)**:默认装上并启动;不想要就在环境里设 `DSH_DOT_COMPUTER=off`。要公网实时画面按 [docs/computer.md](docs/computer.md) 用 `tailscale serve`。
|
|
74
74
|
|
package/cordis.patch.yml
CHANGED
|
@@ -5,8 +5,9 @@
|
|
|
5
5
|
# computer — optional: a microVM (microsandbox, bundled; Docker as fallback) with shell, browser,
|
|
6
6
|
# desktop, live view, approval gates, audit log. The VM is the isolation boundary.
|
|
7
7
|
# DSH_DOT_COMPUTER=off turns it off (the host subprocess/sandbox settings stay stock).
|
|
8
|
-
# qq — her QQ on her computer: NapCat (OneBot 11) inside the VM,
|
|
9
|
-
#
|
|
8
|
+
# qq — her QQ on her computer: NapCat or SnowLuma (OneBot 11, /qq backend) inside the VM,
|
|
9
|
+
# same account as the phone app; logged in by her phone scanning the code (/qq qr).
|
|
10
|
+
# Messages wake her instantly; she answers with qq_send. Needs the computer.
|
|
10
11
|
# DSH_DOT_QQ=off turns it off.
|
|
11
12
|
# dot — the always-on glue: scheduled runs → IM, silence protocol, approval cards with the
|
|
12
13
|
# live view, working rules as a prompt section. Needs dsh-im and the official
|
package/docs/DESIGN.md
CHANGED
|
@@ -172,8 +172,8 @@ Kevin:"0123 全做。"
|
|
|
172
172
|
|
|
173
173
|
## v0.6(续):P3 `dsh-dot/qq`
|
|
174
174
|
|
|
175
|
-
- **部署在她的电脑里,不开新端口**:AIO sandbox 的 nginx 有一条按 `Host: <port>-x` 转发到 VM loopback 端口的规则(`nginx-server-port-proxy.conf.template`),支持 WebSocket upgrade。在云端容器里验证过:`curl -H "Host: 3001-dot" http://127.0.0.1:18080/` 打到 VM 内 3001。所以 OneBot WS 走已有的 18080
|
|
176
|
-
- **登录流程**:NapCat 的二维码存成 PNG → `adb push` 进她手机相册 → 她手机上的 QQ 扫一扫选相册 → 手机确认电脑登录。这就是 QQ
|
|
175
|
+
- **部署在她的电脑里,不开新端口**:AIO sandbox 的 nginx 有一条按 `Host: <port>-x` 转发到 VM loopback 端口的规则(`nginx-server-port-proxy.conf.template`),支持 WebSocket upgrade。在云端容器里验证过:`curl -H "Host: 3001-dot" http://127.0.0.1:18080/` 打到 VM 内 3001。所以 OneBot WS 走已有的 18080,外面没有新面。**(v0.8.4 起作废:这条转发不验网关密钥,已被封成 404;现在走网关验过密钥后的 `location /dsh-dot/napcat/`,见文末。)**
|
|
176
|
+
- **登录流程**:NapCat 的二维码存成 PNG → `adb push` 进她手机相册 → 她手机上的 QQ 扫一扫选相册 → 手机确认电脑登录。这就是 QQ 自己的多端登录,她的手机给她的电脑授权。**(实测不行:QQ 的电脑登录码不接受相册导入,只认摄像头。v0.8.x 起改为放到她手机虚拟摄像头前,见文末。)**
|
|
177
177
|
- **一条路**:QQ 消息和手机通知走同一条 wake 管道(合并、忙时攒、分组、静音),只是 `pkg: 'qq'`、提示换成"用 qq_send 回"。连上后手机的 QQ 通知自动忽略,避免双叫。
|
|
178
178
|
- **能力边界**:只有 `qq_send` 发文字。加好友、进群、撤回、发文件、改资料没有工具。
|
|
179
179
|
- dsh-im 官方机器人降为后备:dot 的通知器和幕间的主动联系先看 `dshQq.connected && owner`。
|
|
@@ -189,3 +189,23 @@ Kevin:"感觉现在很难给他长任务。他很容易直接结束然后就
|
|
|
189
189
|
- **B**:dot 的工作规则加一条长任务规则,措辞照 dsh 的 `create_goal` 描述("即使他没说'目标'"):先回收到、分段汇报、确认做完才标记完成、一轮能做完的不建。
|
|
190
190
|
- **C**:目标进行中,dot 的"拿起手机"、幕间的"去看""去玩"都不插进来(`goals.get(agent).phase === 'active'`);你的新消息照常在两轮之间送到。
|
|
191
191
|
- **D**(换 pro)不做:goal 每轮的提示要求"标记完成前收集证据确认整个目标达成",先看 flash 在这个约束下的表现。
|
|
192
|
+
|
|
193
|
+
## v0.8.4–v0.10.18(2026-10-28 — 10-30):安全加固、SnowLuma、摄像头扫码
|
|
194
|
+
|
|
195
|
+
**安全**(起因:插件市场的审核意见,之后按同一思路自查)
|
|
196
|
+
- 电脑网关(AIO sandbox 8080 → 本机 18080)启动 VM 时带 `SANDBOX_API_KEY`,密钥存 `$DSH_HOME/dsh-computer.key`(0600),所有进程内调用带 `X-AIO-API-Key`。网关的 `Host: <port>-x` 端口转发不验密钥,启动时改成 404;网关没加上密钥或转发没封住时电脑状态是 `unsafe`,不报告就绪,QQ 不连(`blocked`)。
|
|
197
|
+
- 实时画面挂在 dsh 自己的 web server 上(`/dsh-dot/computer/`),先过 dsh 的身份校验;noVNC 的 WebSocket 用 120 秒、一次性、绑定来源 IP 的票据(桌面版 App 走桥接没有 TCP 对端时不绑定)。
|
|
198
|
+
- 电脑工具的审批按工具分类(只读 / shell / 文件 / 浏览器动作 / 总是问),没见过的工具按动作处理并记审计;受保护路径(密钥、浏览器配置、凭据)出现在任何参数里都问。
|
|
199
|
+
- QQ:图片网址只收公网 http(s)(防 SSRF);拼进 VM root shell 的账号、端口、token、网址先校验;群消息打分的提示词把消息隔离;手机通知里"昵称像你"不等于你(标未验证);连上的不是她的号就断开(`wrong-account`)。
|
|
200
|
+
|
|
201
|
+
**SnowLuma 后端**(Kevin:"我想搭配 snowluma")
|
|
202
|
+
- 用 ptrace 钩住 Linux QQ 图形界面。装一个钉版本、校验 sha256 的干净 linuxqq(不用 NapCat 改过启动器的那份),SnowLuma 用自己的 Node 24(SQLite 存储要求,镜像自带 22),WS/HTTP 都只在 VM 回环、经网关认证路径进来;HTTP 给 SnowLuma 官方 MCP(`mcp__dot-qq__*`,219 个 action,`qqToolGate` 分级审批)。
|
|
203
|
+
- 真机踩到并修掉的:启动脚本里 `pkill -f` 匹配到自己的命令行而自杀;按 `/tmp/.X11-unix` 第一个 socket 选显示,选到 NapCat 留下的死 Xvfb;Xvnc 的显示写作 `:99.0`;GitHub API 限流拿不到 tag。
|
|
204
|
+
|
|
205
|
+
**摄像头扫码**(QQ 电脑登录码只认摄像头)
|
|
206
|
+
- AVD 后置摄像头设为 `virtualscene`。模拟器只在开机时读场景文件、海报图片每个进程只认第一次设置,实测得出的做法:开机前把 `wall` 海报挪到镜头正前方;换图时先回桌面(摄像头开着换不了)、清空海报、再设一个新文件名(`adb emu virtualscene-image`)。
|
|
207
|
+
- QQ 的码是圆点风格,zbar/OpenCV 读不出,用 zxing-cpp 读出内容,qrencode 重画成方块码,放在方形画布右侧(QQ 扫一扫的取景比相机近、偏左)。只在码读不出(过期)时点「刷新」——点有效的码会让 QQ 换码,作废她镜头里那张。
|
|
208
|
+
- 10-30 真机:她用手机 QQ 摄像头扫码,确认登录,SnowLuma `connected`。这几轮里关键的观察多是她自己说出来的("格子动都没动""左边半张在画面外""那个框压住半个码")。
|
|
209
|
+
|
|
210
|
+
**手机存储**:她 8 GB 数据分区满了;改 `disk.dataPartition.size` 不会扩大已有分区(实测)。新手机默认 16 GB,建之前可选(`/phone accept <GB>`、`/phone size <GB>`)。
|
|
211
|
+
|
package/docs/ROADMAP.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# dsh-dot 总体规划(2026-10-23)
|
|
1
|
+
# dsh-dot 总体规划(2026-10-23;「现在在哪」更新于 2026-11-02,v0.11.0)
|
|
2
2
|
|
|
3
3
|
## 一句话
|
|
4
4
|
|
|
@@ -8,14 +8,15 @@ dot 是一个**在自己手机上过日子的角色**:有自己的手机、账
|
|
|
8
8
|
|
|
9
9
|
| 层 | 状态 | 证据 |
|
|
10
10
|
|---|---|---|
|
|
11
|
-
| 手机(`phone`) | ✅ 开箱即用:自动下载/建 AVD
|
|
11
|
+
| 手机(`phone`) | ✅ 开箱即用:自动下载/建 AVD/开机/接管(只接管自己的 AVD),live view 标签页,`mcp__dot-phone__*`;摄像头是虚拟场景,能往镜头前放图;存储建手机前可选(默认 16 GB) | 真机:装好 → 她自己装了 QQ、登录、回了消息;10-30 她的 8 GB 用满,扩容不生效,清理后剩 ~2 GB |
|
|
12
12
|
| 通知 → 叫醒 | ✅ 事件 + 快照模型,任何 App,按 App 静音,后台不冻结 | 真机:发出 → 叫醒 2–4 s(原 3.5 min) |
|
|
13
|
-
| 她回消息 |
|
|
13
|
+
| 她回消息 | ✅ 一条 ~78 s;忙时来的消息攒到那轮结束一起给她(10-29 真机:`owner-message whileBusy:true`);回复按行拆成多条、按字数停顿;能发表情包(存别人发的)和小黄脸 | 真机 10-29 |
|
|
14
14
|
| 幕间(`interlude`) | ✅ HDSI 移植:Canon、剧本、连续性、打算、web/vm/phone 三路"去看"(只读无审批) | 真机跑了 14 轮;0 次 browserIntent(剧情没给理由) |
|
|
15
15
|
| 联系人层(`dot`) | ✅ 定时结果→IM、审批/设备提醒、工作规则、通知唤醒 | 真机 |
|
|
16
|
-
| 电脑(`computer`) | ✅
|
|
17
|
-
|
|
|
18
|
-
|
|
|
16
|
+
| 电脑(`computer`) | ✅ 可选;网关加密钥、端口转发封死、实时画面一次性票据、按操作类型审批、审计 | `DSH_DOT_COMPUTER=off` |
|
|
17
|
+
| 她电脑上的 QQ(`qq`) | ✅ NapCat 或 SnowLuma(`/qq backend`),她用手机摄像头扫码登录(`/qq qr`);只认她的号 | 10-30 真机:SnowLuma 连上、`mcp__dot-qq__*` 挂载,她自己扫码登录 |
|
|
18
|
+
| IM 通道 | ✅ QQ 连上时 dot 的提醒、幕间主动联系、她对你 QQ 消息的回答都走她的 QQ;没连上时退回 dsh-im 官方机器人。SnowLuma 下收发已实测(10-29,22 条进 38 条出);`qq_send` 对陌生人的审批只有单元测试,没有陌生人来过 | 真机 10-29 |
|
|
19
|
+
| "玩"(点赞/评论/关注) | ✅ 代码在(playIntent → 正常轮次,Moltbook 守则),11-02 起默认开、内置 App 表按手机上装的收窄;发帖/私信不做 | 真机 0 次(之前默认关) |
|
|
19
20
|
|
|
20
21
|
## 架构(不再变的部分)
|
|
21
22
|
|
|
@@ -35,10 +36,10 @@ dot (联系人层) ──┼─ computer ─ microVM(可选)── mcp__dot-
|
|
|
35
36
|
|
|
36
37
|
目标:你在 QQ 里和她聊一天,不漏、不串、不重复。
|
|
37
38
|
|
|
38
|
-
1.
|
|
39
|
+
1. ~~**忙时攒消息**~~:已做(`held`/`releaseHeld`,`groupNotifications`),10-29 真机验证。
|
|
39
40
|
2. ~~夜间静音~~:撤回。`notifyHours` 默认不设,任何时候来通知都叫醒她(10-25,Kevin 没要过这个)。
|
|
40
41
|
3. **回消息的速度**:先接受 ~1 min(人也不秒回);记录每次回复的耗时和工具调用数,一周后看数据再决定要不要快路。
|
|
41
|
-
4. **观察一周**:`calls.jsonl`、`web-context.jsonl
|
|
42
|
+
4. **观察一周**:`calls.jsonl`、`web-context.jsonl`、两份审计日志。不加功能。已看到的:10-27/28 余额不足时幕间一天失败 133 次——现在失败后退避 5/10/20…60 分钟。
|
|
42
43
|
|
|
43
44
|
完成标准:连发 5 条她一次回齐;夜里不叫;一周内 0 条漏回(审计可查)。
|
|
44
45
|
|
|
@@ -47,14 +48,14 @@ dot (联系人层) ──┼─ computer ─ microVM(可选)── mcp__dot-
|
|
|
47
48
|
目标:幕间不再只是躺床上;她会拿手机、会去看、会有话题。
|
|
48
49
|
|
|
49
50
|
1. **定时拿起手机**(`phoneCheckEveryMinutes`,活跃时段内,默认 30):正常轮次,"看看手机有没有新消息/新动态,有事处理,没事 `DOT_SILENT`"。这是通知之外的兜底,也是她"刷手机"的来源。
|
|
50
|
-
2.
|
|
51
|
+
2. ~~**`phoneApps` 填上**~~:内置常见 App 表,按她手机上装了什么生效(11-02);`vmSites` 给电脑。
|
|
51
52
|
3. **她关注什么**:由你给(账号/话题),原样写进 Canon 的 `world`;或者等她在对话里自己长出来。我不编。
|
|
52
53
|
4. **intent 空转**:`intent` 轮只结算不新建(现在每天 7 轮 intent 滚自己)。
|
|
53
54
|
5. **幕间观察结果回流**:`webContext` 已进下一轮;检查剧本里有没有真的用上。
|
|
54
55
|
|
|
55
|
-
完成标准:一周内剧本里出现 ≥3 次"她在手机上看到的东西";幕间 intent 轮 ≤ 2
|
|
56
|
+
完成标准:一周内剧本里出现 ≥3 次"她在手机上看到的东西";幕间 intent 轮 ≤ 2/天。→ 11-02 核对 ~/dot/interlude:phone-check 186 次;观察 phone 6 / web 4;剧本里小黑盒评论、番茄、手机存储都是真事;intents 已清空。达标。
|
|
56
57
|
|
|
57
|
-
### P2 · "玩"
|
|
58
|
+
### P2 · "玩":轻动作(已做,待真机观察)
|
|
58
59
|
|
|
59
60
|
目标:点赞、评论、发帖、关注——在她的账号上,按她的人设,低频。
|
|
60
61
|
|
|
@@ -67,7 +68,7 @@ dot (联系人层) ──┼─ computer ─ microVM(可选)── mcp__dot-
|
|
|
67
68
|
|
|
68
69
|
### P3 · 通道与第二设备(按需,不排期)
|
|
69
70
|
|
|
70
|
-
-
|
|
71
|
+
- ~~**NapCat 当她的"电脑端 QQ"**~~:已做(`dsh-dot/qq`,v0.6 起;v0.10 加 SnowLuma 后端),见 [qq.md](qq.md)。
|
|
71
72
|
- **dsh-im 官方机器人通道**:降级为可选(给想用的人),她的 IM 身份以真 QQ 为准。
|
|
72
73
|
- **真机 / PVE 24 小时**:`serial` 配置项接真安卓机(去模拟器检测、Mac 睡眠也在线);或手机搬到 PVE 的 Redroid。等有需要。
|
|
73
74
|
- **NotificationListenerService APK**:只在 dumpsys 快照被证明会漏时做。
|
package/docs/interlude.md
CHANGED
|
@@ -51,7 +51,7 @@ dsh 这边不需要重做一个对话系统——对话由 dsh 自己跑,IM
|
|
|
51
51
|
- **web**:dsh 的 `web` 服务。匿名、只读、便宜、看不见。适合好奇心:搜个新闻、看个公开页。
|
|
52
52
|
- **vm**:她自己的电脑(dsh-computer 的虚拟机浏览器)。带着她的登录态和标签页,实时画面里看得见。适合"她的站"——微博、B 站、小红书、X 这些登录后才像样的地方。实现上是往她最近一个会话里追加一条 `[幕间观察]` 消息,让她用 `mcp__dot-vm__browser_*` 自己去看,最后那段回复就是观察结果;这一轮**不算幕**(不进剧本),也**没有审批**:只读工具(打开、滚动、读文字、截图、标签页)直接放行,其他任何工具——点击、输入、下载、shell——直接拒绝,不弹审批卡。她只能看,不能动。
|
|
53
53
|
- `browser: auto`(默认):先走 web;URL 的主机在 `vmSites` 里就直接走 vm(她的站从不匿名看);web 结果太薄或被挡(JS 墙、验证码、登录墙)也升级到 vm,一天最多 `vmDailyCap` 次。
|
|
54
|
-
6.
|
|
54
|
+
6. **玩**:幕间里她可以写一个 `playIntent`——此刻真想在手机上做的一件小事:给哪篇点个赞、评论一句、关注谁(`playActions`,发帖 / 私信 / 花钱不在其中,也写不进去)。这一轮写完后变成她会话里的一条 `[想玩会儿手机] …` 消息,她用手机去做(正常轮次,手机闸门的审批照常),做完只回 `DOT_SILENT`。门控和主动联系一样:活跃时段、意愿 ≥ 阈值、每天 ≤ `maxPlaysPerDay`(默认不限)、App 在 `playApps` 里**且装在她手机上**(没装一个就等于关)。行为准则不是我们写的,是 [Moltbook](https://www.moltbook.com/heartbeat.md) 给住在社交网络上的 agent 定的守则(节译):先回别人的回复,再慷慨点赞,再用心评论,再关注,最后才发新内容——而且只在真有话说时;参与 > 创造;真诚,不为凑数。
|
|
55
55
|
7. **主动联系(Agency,默认关)**:`speak: true` 时,模型给出的 `contact` 过四道闸——在活跃时段、意愿 ≥ `willingnessThreshold`、当天未超 `maxContactsPerDay`、dsh-im 有投递目标——才通过 `dshIm.send()` 发出去。被拦下的会记在审计日志里。
|
|
56
56
|
|
|
57
57
|
### 三、和 HDSI 的对照
|
|
@@ -89,7 +89,7 @@ dsh 这边不需要重做一个对话系统——对话由 dsh 自己跑,IM
|
|
|
89
89
|
| `home` / `DSH_INTERLUDE_HOME` | `~/dot`(跟随 `DSH_DOT_HOME`) | 幕间文件所在目录 |
|
|
90
90
|
| `browser` | `auto` | HDSI 的「网页观察」怎么看:`auto`(web 优先,`vmSites` 或 web 被挡时用 vm)、`web`、`vm`、`disabled` |
|
|
91
91
|
| `browseDailyCap` | `6` | 每天最多观察几次(两种方式合计) |
|
|
92
|
-
| `phoneApps` |
|
|
92
|
+
| `phoneApps` | 内置常见社区 App(`KNOWN_APPS.sites`) | 用她手机上的 App 看的站,`{ host: 包名 }`;需要 `dsh-dot/phone` 就绪。规则同 `vmSites`:从不匿名看、只读、无审批 |
|
|
93
93
|
| `phonePreferred` | `true` | web 被挡要升级时,手机和电脑都在就先用手机 |
|
|
94
94
|
| `phoneObservationTools` | 看、滑、点、开 App、返回 | 观察轮放行的手机工具;输入、装卸 App 一律拒绝 |
|
|
95
95
|
| `vmSites` | `[]` | 只在虚拟机里看的站(主机后缀匹配,如 `bilibili.com`);虚拟机今天没额度就等,不会匿名去看 |
|
|
@@ -110,9 +110,9 @@ dsh 这边不需要重做一个对话系统——对话由 dsh 自己跑,IM
|
|
|
110
110
|
| `maxRoundsPerDay` | `12` | 每天幕间上限 |
|
|
111
111
|
| `maxTokens` | `16384` | 每轮输出上限 |
|
|
112
112
|
| `scriptEntriesInPrompt` | `2` | 下一幕能看到几段剧本 |
|
|
113
|
-
| `play` | `
|
|
114
|
-
| `playApps` |
|
|
115
|
-
| `playActions` | `like, comment, follow` | 允许的动作;`post` / `dm` 永远不执行 |
|
|
113
|
+
| `play` | `true` | 允许她在手机 App 上做小动作(点赞 / 评论 / 关注);只在她装了的 App 里 |
|
|
114
|
+
| `playApps` | 内置常见社区 App(`KNOWN_APPS.labels`) | 可以玩的 App:`{ 小黑盒: com.max.xiaoheihe }`(标签 → 包名),再按手机上装了什么收窄 |
|
|
115
|
+
| `playActions` | `like, comment, follow, collect` | 允许的动作;`collect` = 去 App 逛逛攒表情包(`qq_sticker_keep`),表情包少于 5 张时幕间会被提醒;`post` / `dm` 永远不执行 |
|
|
116
116
|
| `maxPlaysPerDay` | `3` | 每天最多几次 |
|
|
117
117
|
| `speak` | `false` | 允许主动联系 |
|
|
118
118
|
| `maxContactsPerDay` | `2` | 每天最多主动几次 |
|
package/docs/phone.md
CHANGED
|
@@ -6,12 +6,15 @@ An Android phone the plugin installs and runs for the character, exposed to the
|
|
|
6
6
|
|
|
7
7
|
1. **安装**(第一次):接受 [Android SDK 许可](https://developer.android.com/studio/terms)后(`/phone accept`,或配置 `acceptLicense: true`,或 `~/.dsh/dsh-phone.json` 里 `{"acceptLicense": true}`),从 `dl.google.com/android/repository` 读索引,下载 stable 通道的 emulator、platform-tools 和 `system-images;android-<api>;google_apis;<abi>`(约 1.7 GB),解压到 `~/.dsh/phone/`。`google_apis` 镜像没有 Play 商店——检测面最小,App 用 APK 装。
|
|
8
8
|
2. **AVD**:`~/.dsh/phone/avd/dot.avd/config.ini` 由插件写(Pixel 6 尺寸、1080×2400、3 GB 内存、数据分区默认 16 GB、不带 Play)。数据分区大小在手机建好之前选:`/phone accept <GB>` 或 `/phone size <GB>`(8–256);建好后模拟器不会扩大已有分区,`/phone size` 只显示当前大小。想改尺寸或内存,改配置后删掉这个目录重建(手机里的数据会没)。
|
|
9
|
-
3. **开机**:`emulator -avd dot -port
|
|
10
|
-
4. **MCP**:开机后以 stdio 挂一个 mobile-mcp(随插件一起安装,`ANDROID_HOME` 指向 `~/.dsh/phone`,`ANDROID_SERIAL
|
|
9
|
+
3. **开机**:`emulator -avd dot -port <端口> -no-boot-anim -gpu auto`,等 `sys.boot_completed`,然后常亮屏幕、关动画、解锁。上一次 dsh 留下的还在跑的模拟器会被直接接管,不会开两个——但只接管控制台报告 AVD 名是 `dot` 的那台(`adb emu avd name`):MuMu、雷电、BlueStacks 等也会以 `emulator-5554` 出现在 adb 里,占着端口不等于是她的手机。端口从 `port`(5554)起找第一个 adb 没列出的(到 5584 为止)。模拟器自己退出会在 `restartDelayMs` 后重开。手机在 dsh 退出后继续运行。
|
|
10
|
+
4. **MCP**:开机后以 stdio 挂一个 mobile-mcp(随插件一起安装,`ANDROID_HOME` 指向 `~/.dsh/phone`,`ANDROID_SERIAL` 是上一步占到的 `emulator-<端口>`),工具名 `mcp__dot-phone__mobile_*`:列设备、截图、列屏幕元素(带坐标)、点、滑、长按、输入、按键、打开/关闭 App、装卸 App、开 URL。
|
|
11
11
|
5. **提示**:手机就绪后系统提示里多一段 `phone:device`,告诉模型设备号和用法(先看元素再点;验证码、人脸停下来叫用户)。
|
|
12
|
-
6. **闸门**:`mobile_install_app` / `mobile_uninstall_app`
|
|
12
|
+
6. **闸门**:`mobile_install_app` / `mobile_uninstall_app` 弹审批(目前审批框只显示工具名,不显示是哪个 App);`mobile_type_keys` 的内容像密码 / 支付 / 验证码时弹审批(`sensitivePatterns`)。幕间的观察轮只放行只读工具(看、滑、点进去、开 App、返回),其余直接拒绝、不审批。
|
|
13
13
|
7. **通知叫醒她**:插件盯着系统的事件日志(`adb logcat -b events notification_enqueue`),每有 App 发通知就立刻读一次通知栏(`dumpsys notification`),另外每 `notifyPollMs` 兜底轮询一次——QQ 这类 App 在聊天窗口开着时会立刻撤回通知,光靠轮询会漏,新出现的通知(启动时已经在栏里的不算;系统包不算;`notifyApps` 可以只挑几个 App)交给 dot,dot 往她最近的会话里追加一条 `[手机通知] QQ · 宽:……`,她自己决定去 App 里回还是只回 `DOT_SILENT`。这条回复不会转发到任何 IM。所以她不需要定闹钟去看 QQ——有人找她,手机会响。**任何 App 都算**,包括她以后自己装的:新 App 默认叫醒;像手机自己的通知设置一样可以按 App 静音——`/phone notify mute <包名>` / `wake <包名>`(持久化在 `dsh-phone.json`),`/phone notify` 看每个 App 发过多少条和当前策略。她在 Android 设置里关掉某个 App 的通知也一样生效(通知栏里没有就不会叫)。几秒内连来的多条合成一次叫醒(dot 的 `notifyBatchMs`);dot 的 `notifyHours` 可以设一个静音时段(默认不设)。`/phone notifications` 看最近 20 条。
|
|
14
14
|
8. **实时画面**:两种。一是模拟器窗口本身(`window: true`);二是插件的网页,挂在 **dsh 自己的 web server** 上:`<dsh 地址>/dsh-dot/phone/`——dsh 右侧栏的「手机」标签页就是它:屏幕每秒刷新几次(PNG 流),能直接点、滑、按返回/主页、输入文字,登录 App 就在这里做。**它不单独监听端口**:页面、画面流和每一次点击都先过 dsh 的 `connection` 服务(dsh 自己的登录态 + Host/Origin 围栏,转发头一概不认),只有登录了这个 dsh 的人能看能点。想在别的设备上看,把 dsh 本身暴露出去(如 `tailscale serve` dsh 的端口,或 dsh 的远程访问),再把那个地址写进 `publicUrl`,审批提醒里的链接就是 `<publicUrl>/dsh-dot/phone/`。无头跑(服务器)时 `window: false` 只用网页。网页里的文字输入走 `adb shell input text`,只支持 ASCII(账号、验证码够用);中文由她自己的工具输。
|
|
15
|
+
9. **摄像头**:后置摄像头是模拟器的虚拟场景(`hw.camera.back=virtualscene`,前置没有)——一个有电视和书架的 3D 房间。场景里的 `wall` 海报每次开机前被挪到镜头正前方 1.5 米、1 米见方(插件改写模拟器的 `resources/Toren1BD.posters`,原文件存成 `.orig`,`table` 海报不动),所以往海报上放一张图,她打开相机或扫一扫看到的就是它。`dshPhone.showToCamera(png)` 负责放:先按 HOME 回桌面(有 App 开着摄像头时换图不生效),`adb emu virtualscene-image wall` 清空海报,再设成新写的 `resources/dsh-dot-poster-<毫秒>.png`(同一路径或不先清空,模拟器会一直显示这个进程里放的第一张),旧文件删掉。QQ 扫码登录电脑端就靠它(见 [qq.md](qq.md))。0.10.8 之前开起来的手机要 `/phone restart` 一次海报才会挪过去;更早建的、没有摄像头的 AVD 会被自动补上 `virtualscene`,同样下次开机生效。
|
|
16
|
+
|
|
17
|
+
`/phone` 看状态(含存储大小),子命令:`accept [GB]`、`size <GB>`、`retry`、`restart`、`screenshot`、`notifications`、`notify [mute|wake <包名>]`。
|
|
15
18
|
|
|
16
19
|
## 配置
|
|
17
20
|
|
|
@@ -21,7 +24,7 @@ An Android phone the plugin installs and runs for the character, exposed to the
|
|
|
21
24
|
| `api` / `tag` / `abi` | `35` / `google_apis` / 跟随宿主 CPU | 系统镜像;Apple silicon 用 `arm64-v8a`,x86 用 `x86_64` |
|
|
22
25
|
| `avd` / `device` | `dot` / `pixel_6` | AVD 名和机型 |
|
|
23
26
|
| `ramMb` / `dataGb` | `3072` / `16` | 内存、数据分区(`dataGb` 也可用 `/phone accept <GB>` / `/phone size <GB>` 在建手机前设) |
|
|
24
|
-
| `port` | `5554` |
|
|
27
|
+
| `port` | `5554` | 控制台端口的起点:被别的模拟器占着就往后找(+2,到 5584);adb 序列号 `emulator-<端口>` |
|
|
25
28
|
| `window` / `DSH_DOT_PHONE_WINDOW=off` | `true` | 显示模拟器窗口 |
|
|
26
29
|
| `liveView` | `true` | 在 dsh 的 web server 上挂实时画面页(`/dsh-dot/phone/`);`false` 关闭 |
|
|
27
30
|
| `publicUrl` | 无 | 这个 dsh 对外的地址(你自己的暴露方式);实时画面链接 = `<publicUrl>/dsh-dot/phone/`,写进审批提醒 |
|
|
@@ -66,3 +69,4 @@ An Android phone the plugin installs and runs for the character, exposed to the
|
|
|
66
69
|
- 模拟器检测:部分 App 会限制功能或拒绝登录。退路是一台真安卓机接 adb——`ANDROID_SERIAL` 换成真机序列号即可,组件其余不变(待做:`serial` 配置项)。
|
|
67
70
|
- mobile-mcp 的工具每次调用都要带 `device`,模型偶尔会忘;提示段里给了设备号。
|
|
68
71
|
- 多台手机未做。
|
|
72
|
+
- 数据分区建好后不能扩大(改 `config.ini` 的 `disk.dataPartition.size` 不生效,实测);满了只能清 App 数据、卸 App,或清空重建。
|
package/docs/qq.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# dsh-dot/qq · 她电脑上的 QQ
|
|
2
2
|
|
|
3
|
-
Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ)
|
|
3
|
+
Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) (a headless QQNT client) or [SnowLuma](https://github.com/SnowLuma/SnowLuma) (hooks the Linux QQ GUI) — both speak OneBot 11 — runs inside the computer VM, logged into **the same account as the QQ app on her phone** (QQ allows a phone and a computer at once). Messages arrive as events the moment they are sent, and she answers in a second with `qq_send`. The phone app stays for everything else.
|
|
4
4
|
|
|
5
5
|
## 为什么
|
|
6
6
|
|
|
@@ -8,9 +8,12 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
8
8
|
|
|
9
9
|
## 怎么接
|
|
10
10
|
|
|
11
|
-
- NapCat 装在**她的电脑**(dsh-dot/computer 的 VM)里,以 root 身份 rootless 安装到 `/root/Napcat`,`xvfb-run -a qq --no-sandbox -q <账号>` 后台运行。
|
|
12
|
-
- dsh 连它的 OneBot WebSocket
|
|
13
|
-
-
|
|
11
|
+
- NapCat 装在**她的电脑**(dsh-dot/computer 的 VM)里,以 root 身份 rootless 安装到 `/root/Napcat`,`xvfb-run -a /root/Napcat/opt/QQ/qq --no-sandbox -q <账号>` 后台运行。SnowLuma 的装法见下文。
|
|
12
|
+
- dsh 连它的 OneBot WebSocket **不开新端口,也不走网关的端口转发**(`Host: <端口>-xxx` 那条转发不验密钥,电脑组件启动时就把它改成 404 了)。插件往 VM 里写 `/opt/gem/nginx/dsh-dot-napcat.conf`,在网关**验过密钥之后**的那层 nginx 里加一个 `location /dsh-dot/napcat/` → VM 内 `127.0.0.1:<wsPort>`(WebSocket 也转)。dsh 连 `ws://127.0.0.1:<网关端口>/dsh-dot/napcat/`,带两样东西:`X-AIO-API-Key: <网关密钥>` 过网关,`Authorization: Bearer <OneBot token>` 给 NapCat。网关不认这种组合时(401)自动改成把 token 放进查询串 `?access_token=`。
|
|
13
|
+
- 只在电脑组件报告 `ready`(网关已加密钥、端口转发已关)之后才连;电脑报告 `unsafe` 时 QQ 不连,状态 `blocked`。
|
|
14
|
+
- 连续连不上(每 6 次)会查一下 QQ 进程还在不在,不在就重新 `/qq start`。
|
|
15
|
+
- OneBot token 第一次生成后存在 `~/.dsh/dsh-qq.json`(只有你能读,0600)。
|
|
16
|
+
- **只认她的号**:连上后每个事件都带登录的 QQ 号(`self_id`)。不是 `account` 设的号——尤其是 `owner`(你)的号——立刻断开、卸掉 QQ 工具、不处理任何消息,状态 `wrong-account`。没设 `account` 时也不会接受你的号。
|
|
14
17
|
|
|
15
18
|
## 第一次
|
|
16
19
|
|
|
@@ -18,12 +21,23 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
18
21
|
/qq install # 在她的电脑里装 NapCat(apt 依赖 + linuxqq + NapCat.Shell,几分钟;日志在 VM 的 /root/napcat-install.log)
|
|
19
22
|
/qq account 123456789 # 她的小号
|
|
20
23
|
/qq start # 写 OneBot 配置、启动 NapCat、开始连
|
|
21
|
-
/qq qr #
|
|
24
|
+
/qq qr # 把登录二维码放到她手机的摄像头前,也存到 ~/.dsh/phone/ 和她手机的相册(见下节)
|
|
22
25
|
```
|
|
23
26
|
|
|
24
|
-
|
|
27
|
+
然后她(或你在「手机」标签页里)打开 QQ → 右上角 + → 扫一扫 → 在手机上确认"电脑登录"。这就是真实的 QQ 多端登录流程——她的手机授权她的电脑。登录态保存在 VM 里,以后 `/qq start` 用账号快速登录,不用再扫。
|
|
25
28
|
|
|
26
|
-
`/qq` 看状态,`/qq log`
|
|
29
|
+
`/qq` 看状态,`/qq log` 看日志(NapCat 或 SnowLuma 的日志和进程;SnowLuma 下还有监听端口和 WebUI 密码;安装中就是安装日志),`/qq stop` 停,`/qq owner <号>` 指定"你"——必须手动指定,不会从谁先私聊自动学。全部子命令:`install [snowluma]`、`backend <napcat|snowluma>`、`account <号>`、`start`、`stop`、`qr`、`log`、`owner <号>`、`group <mention|all|none|score>`。
|
|
30
|
+
|
|
31
|
+
## 扫码登录(`/qq qr`)
|
|
32
|
+
|
|
33
|
+
QQ 的电脑登录码**不接受相册导入,只认摄像头**。她手机的后置摄像头是模拟器的虚拟场景(`hw.camera.back=virtualscene`:一个带电视和书架的房间),`/qq qr` 把码放进这个房间,QQ 的扫一扫看到的就是它。
|
|
34
|
+
|
|
35
|
+
1. **拿到码**
|
|
36
|
+
- NapCat:用 NapCat 自己写出的二维码文件;文件超过 45 秒或日志里有登录失败/过期,就重启 NapCat 等新码。
|
|
37
|
+
- SnowLuma:截 VM 屏幕上名为 `QQ` 的窗口(找不到就截整屏)。QQ 的码是圆点风格,zbar 和 OpenCV 读不出,用 **zxing-cpp** 读出内容(第一次用时在 VM 里 `pip install zxing-cpp pillow`,先清华镜像再 PyPI;旧版 pip 不带 `--break-system-packages`;zbar 兜底)。读不出时视为已过期:窗口是 680×440 的登录窗就用 `xdotool` 点码中间的「刷新」再截一次——**只在读不出时点**,点一张有效的码会让 QQ 换码、作废已经在她镜头里的那张。读出后用 `qrencode` 重画成标准方块码,贴在两倍大的白色方形画布上、往右偏四分之一码宽(QQ 扫一扫的取景比系统相机更近、也偏,码放正中会被切掉左边的定位块)。实在读不出就用窗口截图本身,`/qq qr` 的输出会写明原因。
|
|
38
|
+
2. **存起来**:`~/.dsh/phone/qq-login-<时刻>.png`,并推到她手机相册 `/sdcard/Pictures/`(旧的 `qq-login*` 先删)。
|
|
39
|
+
3. **放到摄像头前**:手机组件先按 HOME 回桌面(**摄像头开着时换图不生效**),把场景里的 `wall` 海报清空,再设成新文件 `resources/dsh-dot-poster-<毫秒>.png`(`adb emu virtualscene-image wall <文件>`;同一路径、或不先清空,模拟器都会继续显示第一张)。这块海报在每次开机前已被挪到镜头正前方 1.5 米(改写模拟器的 `resources/Toren1BD.posters`,原文件存为 `.orig`)。手机是 0.10.8 之前开起来的,要 `/phone restart` 一次海报才会挪过去。
|
|
40
|
+
4. **保持新鲜**(SnowLuma):之后 4 分钟里每 40 秒看一次,码过期换了新的才重新放上去;QQ 连上或 `/qq stop` 就停。码约一分钟过期——过期后关掉扫一扫、等几秒再打开,看到的就是新码。
|
|
27
41
|
|
|
28
42
|
## 之后发生什么
|
|
29
43
|
|
|
@@ -31,10 +45,11 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
31
45
|
|---|---|
|
|
32
46
|
| **你**(owner)私聊她 | 你打的字原样进她的会话,以"人说的话"的身份(和 dsh-im 转发 IM 一样,`kind: user`)——所以你能在 QQ 上给她派长任务,她可以建目标(`create_goal`)一轮轮做下去。夜间静音对你不生效。**她这一轮的回答会送回你的 QQ**:她自己用 `qq_send(to: owner)` 发了就不重复,没发的话 dot 把她在对话里的最后一段回复转过去(`DOT_SILENT` 除外)。**只有电脑端 QQ 按 QQ 号认出的你才算**:手机通知只有昵称,谁都能改成和你一样,所以电脑端掉线时你从手机 QQ/微信发来的话会标成「未验证身份」,当普通消息看、不当指令 |
|
|
33
47
|
| 别人私聊她 / 群里 @ 她 | `[手机通知] QQ · 路人(123):在吗` 叫醒她,和手机通知一条路(1 秒合并、忙时攒着、按对话分组、夜间静音);这些不算人的直接输入,建不了目标 |
|
|
34
|
-
| 她回 | `qq_send(to: "owner" \| "user:<号>" \| "group:<号>", text, images)
|
|
48
|
+
| 她回 | `qq_send(to: "owner" \| "user:<号>" \| "group:<号>", text, images)`,**text 每一行一条**(`<sep/>` 也行),条与条之间按字数停一下(`typingMsPerChar`,默认 60 ms/字,最多 2.5 s)。dot 转发她在对话里的回答时同样按行拆。**审批**(`sendPolicy: reply`):发给你永远不问;回最近 30 分钟内给她发过消息的人或群(文字、网图)不问;发给没找过她的人、沉默的群,或者发她手机/电脑上的文件(`phone:*`、`/sdcard/…`、电脑路径)——先弹审批 |
|
|
35
49
|
| 她发图 | `images` 里每一项直接作为**图片**发出(不是链接):网址(NapCat 下载)、`phone:screen`(手机此刻截图)、`phone:latest`(手机里最新的照片/截图/下载)、`/sdcard/…`(手机上的文件)、电脑上的绝对路径;≤10 MB |
|
|
36
50
|
| 图片网址规则 | 只接受公网 `http`/`https`、端口 80/443、不带账号密码;回环、私网、链路本地(含 169.254.169.254)、组播、`localhost`/`*.local`/`*.internal`/单段主机名一律拒绝并报错(NapCat 在 VM 里下载,防止她让它访问 VM 内部服务)。公网域名解析到内网(DNS rebinding)这里拦不住 |
|
|
37
51
|
| 别人发图给她 | 叫醒文本里是 `[图片 <网址>]`,她想看就打开 |
|
|
52
|
+
| 表情包 | 别人发的表情包(QQ 标 `sub_type: 1`)进文本是 `[表情包 sticker:<id>]`,同时下载到 `~/.dsh/stickers/`,列表在 `~/.dsh/dsh-qq-stickers.json`(最多 300 张,先进先出);她自己也能存:手机 App 里长按保存图片后 `qq_sticker_keep(image: "phone:latest", note: "无语")`(或手机路径、网图)。发:`images: ["sticker:<id>"]`(以 base64 发出,标 sticker),`face:<编号>` 发 QQ 小黄脸;提示词里列最近 12 张;这两种不走审批。**冷启动**:她的表情包少于 5 张时,幕间知道这件事,可以写一个 `collect` 的 playIntent——去某个 App 逛逛顺手攒几张(见 interlude.md 的「玩」) |
|
|
38
53
|
| dot 的提醒、幕间的主动联系 | 连上后优先走她的 QQ(发给 `owner`),dsh-im 的官方机器人退为后备 |
|
|
39
54
|
| 手机上 QQ 的通知 | 连上后自动忽略(否则同一条叫两次);手机 QQ 照常可以看空间、看群、发图 |
|
|
40
55
|
| 她能做什么 | 发文字和图片。加好友、进群、撤回、发文件都没有工具 |
|
|
@@ -44,17 +59,34 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
44
59
|
[SnowLuma](https://github.com/SnowLuma/SnowLuma) 是另一种 OneBot 11 实现:不自己当 QQ,而是用 ptrace 把钩子注入一个**正在运行的 Linux QQ 图形界面进程**,对外提供 OneBot 11(219 个 action)。dsh 这边(WebSocket、`qq_send`、审批、群打分、转发给你)对两个后端完全一样。
|
|
45
60
|
|
|
46
61
|
```
|
|
47
|
-
/qq install # 先装 NapCat:它顺带装好 Linux QQ,SnowLuma 用的就是这个 QQ
|
|
48
|
-
/qq install snowluma # 下载 SnowLuma lite 版(按 VM 的 arm64/x64,tag 取 latest,可用 snowlumaVersion 固定),解到 /root/snowluma,写配置,屏蔽 QQ 热更新(/etc/hosts 加 qqpatch.gtimg.cn)
|
|
49
62
|
/qq backend snowluma # 切后端,写进 dsh-qq.json
|
|
50
|
-
/qq
|
|
51
|
-
/qq
|
|
63
|
+
/qq install snowluma # 在后台装(几分钟,日志 VM 的 /root/snowluma-install.log),不需要先装 NapCat
|
|
64
|
+
/qq start # 停掉 NapCat 和别的 QQ,在 VM 桌面上开 QQ 图形界面,再启动 SnowLuma
|
|
65
|
+
/qq qr # 码在 QQ 窗口里:读出来重画后放到她手机摄像头前和相册(见上节);也可以直接打开「虚拟机」标签页扫
|
|
52
66
|
```
|
|
53
67
|
|
|
68
|
+
`/qq install snowluma` 装这些:
|
|
69
|
+
- **干净的系统版 Linux QQ** 到 `/opt/QQ`:钉在 SnowLuma 官方安装脚本同一版本 3.2.32_260812,sha256 校验不过就不装。不复用 NapCat 解压的那份(它的启动器被改成加载 NapCat,两个客户端会挤进同一个 QQ)。
|
|
70
|
+
- apt 依赖:QQ 图形界面要的库、中文字体、`imagemagick`(截图)、`xz-utils`、`zbar-tools` 和 `qrencode`(扫码登录)。
|
|
71
|
+
- **SnowLuma 自己的 Node 24** 到 `/root/snowluma-node`:它的 SQLite 存储要求 Node ≥ 24,而 VM 镜像自带 22。系统 Node 够新就链接过去;否则下载 `latest-v24.x`(先 npmmirror 再 nodejs.org),对 `SHASUMS256.txt` 校验后解压。
|
|
72
|
+
- SnowLuma lite 版(按 VM 的 arm64/x64)到 `/root/snowluma`:tag 先从 GitHub release 页的跳转拿(不受 API 限流影响),再试 API 和镜像;`snowlumaVersion` 可以固定。
|
|
73
|
+
- 写配置;在 `/etc/hosts` 屏蔽 QQ 热更新(`qqpatch.gtimg.cn`),免得 QQ 一升级钩子就失效。
|
|
74
|
+
|
|
75
|
+
`installed` 要求三样都在:`/opt/QQ/qq`、`/root/snowluma/index.mjs`、`/root/snowluma-node/bin/node`;少一样就提示再 `/qq install snowluma`。
|
|
76
|
+
|
|
77
|
+
`/qq start` 做这些(停进程放在单独一次 shell 调用里——`pkill -f` 按整条命令行匹配,和启动写在一起会把启动脚本自己杀掉):
|
|
78
|
+
1. 停掉 SnowLuma、任何 `opt/QQ/qq` 进程,以及 NapCat 的 `xvfb-run` 留下的 Xvfb。
|
|
79
|
+
2. `kernel.yama.ptrace_scope` 为 3 就报错退出。
|
|
80
|
+
3. 选桌面显示:VNC 服务(Xvnc / Xtigervnc / x11vnc)用的那个(`:99.0` 记作 `:99`),否则任一不带 `-auth` 的 X 服务器,否则 `:99`。不能按 `/tmp/.X11-unix` 里第一个 socket 选:NapCat 的 `xvfb-run` 会留下已经死掉的 socket,QQ 连上去就退出。
|
|
81
|
+
4. 在这个显示上开 QQ 图形界面(日志 `/root/snowluma-qq.log`),5 秒后用 `/root/snowluma-node/bin/node` 启动 SnowLuma(日志 `/root/snowluma.log`)。
|
|
82
|
+
5. 启动这一步的 shell 偶尔会被报告失败,但两个进程其实都起来了;这时以进程为准,照常继续。
|
|
83
|
+
|
|
84
|
+
注意:QQ 图形界面会记住登录过的账号(勾了「记住密码」时连密码一起),登录窗出现的可能是**快捷登录**某个旧账号。不要在她电脑的 QQ 上登录你自己的号;万一登上了,上面的「只认她的号」会断开。
|
|
85
|
+
|
|
54
86
|
- **一个账号一个电脑端**:NapCat 和 SnowLuma 都是这个号的"电脑登录",不能同时跑。`/qq start` 总会先停掉另一个。
|
|
55
87
|
- **需要 ptrace**:`kernel.yama.ptrace_scope` 为 3 时 SnowLuma 注入不了,`/qq start` 会直接报错,请换回 `napcat`。
|
|
56
88
|
- **配置**:`config/runtime.json`(WebUI 5099、自动加载钩子)和 `config/onebot.json`(回环 WS 服务器用 `wsPort` + 同一个 OneBot token;回环 HTTP 服务器 3000 给 MCP 用)。文档没说清配置目录是工作目录下的 `config/` 还是 `data/config/`,所以两处都写;`/qq start` 每次都重写,token/端口改动会生效。
|
|
57
|
-
- **WebUI**:端口 5099,只在 VM
|
|
89
|
+
- **WebUI**:端口 5099,只在 VM 回环、网关不转发它。每次启动打印的一次性管理员密码在 `/qq log` 里(没改密码时每次重新生成)。
|
|
58
90
|
- **早期软件**:SnowLuma 很新,QQ 版本一变钩子可能就失效(所以屏蔽了热更新)。出问题先 `/qq log`,不行就 `/qq backend napcat`。
|
|
59
91
|
|
|
60
92
|
### 219 个 action(MCP)
|
|
@@ -71,7 +103,7 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
71
103
|
| `send_packet`、`get_cookies`、`get_csrf_token`、`get_rkey`、改资料/头像、删好友、踢人/禁言/设管理/退群、`set_restart`、QQ 空间发/删 | 永远问 |
|
|
72
104
|
| 其他所有 action、读不出 action 名的调用 | 问,理由里写 action 名 |
|
|
73
105
|
|
|
74
|
-
|
|
106
|
+
**前提**:SnowLuma 从工作目录读 `config/`,我们在 `/root/snowluma` 里启动它。它的 MCP(`@snowluma/mcp`)在**宿主机**(你的电脑,不是 VM)上用 `npx -y` 跑,SnowLuma 的说明要求宿主有 `npx` 且 Node ≥ 24.22;不满足时插件不会单独报错,只是 `mcp__dot-qq__*` 不出现,收发消息照常(`/qq` 里看 `mcp: mounted / not mounted`)。
|
|
75
107
|
|
|
76
108
|
## 配置
|
|
77
109
|
|
|
@@ -95,11 +127,13 @@ Her QQ on her computer: [NapCat](https://github.com/NapNeko/NapCatQQ) — a head
|
|
|
95
127
|
## 风险
|
|
96
128
|
|
|
97
129
|
- 协议端个人号有被腾讯风控的可能(随机验证、封号)。**用小号**,低频。
|
|
98
|
-
- NapCat 2025-09 那次事故是公网弱口令被扫。这里 WebUI 和 OneBot 都只在 VM 的 loopback,token
|
|
130
|
+
- NapCat 2025-09 那次事故是公网弱口令被扫。这里 WebUI 和 OneBot 都只在 VM 的 loopback,token 随机,外面没有端口;dsh 进来要过网关密钥。
|
|
131
|
+
- 她电脑上的 QQ(SnowLuma 用的图形界面)会记住登录过的账号和密码。别在那里登你自己的号。
|
|
99
132
|
- 这是她的"电脑端 QQ",和手机同号同时在线;手机那边不要退出登录。
|
|
100
133
|
|
|
101
134
|
## 已知限制
|
|
102
135
|
|
|
103
136
|
- 收发文字和图片;语音、视频进来显示为 `[语音]` `[视频]`。
|
|
104
137
|
- 第一次安装要 VM 能访问 GitHub 和腾讯的下载地址;GitHub 不通时配 `githubProxy`。
|
|
105
|
-
- VM 重建(换镜像)会丢 NapCat 和登录态,`/qq install
|
|
138
|
+
- VM 重建(换镜像)会丢 NapCat / SnowLuma 和登录态,`/qq install`(或 `/qq install snowluma`)重来。
|
|
139
|
+
- 扫码登录要她的手机(摄像头);手机组件没开或没就绪时,`/qq qr` 只把图存到 `~/.dsh/phone/`。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-dot-life",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.2",
|
|
4
4
|
"description": "dot — a character who lives on her own phone, for DeepSeek Harness (dsh): an Android phone the plugin installs and runs, her own QQ, memory and a diary from real events, a life between conversations (幕间, after HDS-Interlude), an optional microVM computer with approval gates. One plugin, six components.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
package/src/interlude/core.js
CHANGED
|
@@ -24,6 +24,12 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm';
|
|
|
24
24
|
export const name = 'dot-interlude';
|
|
25
25
|
export const inject = ['llm', 'agentDefaultModel'];
|
|
26
26
|
|
|
27
|
+
/** Social apps she might install, by site and by name — nothing is installed for her; only what is on her phone counts. */
|
|
28
|
+
export const KNOWN_APPS = {
|
|
29
|
+
sites: { 'xiaoheihe.cn': 'com.max.xiaoheihe', 'bilibili.com': 'tv.danmaku.bili', 'weibo.com': 'com.sina.weibo', 'weibo.cn': 'com.sina.weibo', 'xiaohongshu.com': 'com.xingin.xhs', 'zhihu.com': 'com.zhihu.android', 'douyin.com': 'com.ss.android.ugc.aweme', 'coolapk.com': 'com.coolapk.market', 'tieba.baidu.com': 'com.baidu.tieba', 'douban.com': 'com.douban.frodo', 'qzone.qq.com': 'com.tencent.mobileqq' },
|
|
30
|
+
labels: { 小黑盒: 'com.max.xiaoheihe', B站: 'tv.danmaku.bili', 微博: 'com.sina.weibo', 小红书: 'com.xingin.xhs', 知乎: 'com.zhihu.android', 抖音: 'com.ss.android.ugc.aweme', 酷安: 'com.coolapk.market', 贴吧: 'com.baidu.tieba', 豆瓣: 'com.douban.frodo', QQ空间: 'com.tencent.mobileqq' },
|
|
31
|
+
};
|
|
32
|
+
|
|
27
33
|
export const defaults = {
|
|
28
34
|
home: '', // default ~/dot; the interlude files live in <home>/interlude
|
|
29
35
|
scope: 'home+im', // which sessions are acts: 'home' (cwd inside home), 'im' (opened from an IM bot), 'home+im', 'all'
|
|
@@ -48,7 +54,7 @@ export const defaults = {
|
|
|
48
54
|
// Her phone (dsh-dot/phone): hosts whose app she opens instead of the website, as { host: package }.
|
|
49
55
|
// e.g. { 'xiaoheihe.cn': 'com.max.xiaoheihe', 'bilibili.com': 'tv.danmaku.bili' }. Same rules as
|
|
50
56
|
// vmSites: never read anonymously, read-only, no approvals; phone and VM share `vmDailyCap`.
|
|
51
|
-
phoneApps:
|
|
57
|
+
phoneApps: KNOWN_APPS.sites,
|
|
52
58
|
phonePreferred: true, // when both phone and VM could take a thin/blocked web result, the phone goes first
|
|
53
59
|
vmTimeoutMinutes: 5, // give up waiting for an observation turn after this long
|
|
54
60
|
vmSession: '', // session id to observe in; default: the character's most recent act
|
|
@@ -67,11 +73,12 @@ export const defaults = {
|
|
|
67
73
|
// 玩: small social actions on her own accounts, on her phone — like, comment, follow (post/DM/pay
|
|
68
74
|
// never, by construction). Off by default. Executed as a normal turn (approvals apply), gated like
|
|
69
75
|
// contact: active hours, willingness, daily cap. The behaviour rules are Moltbook's agent-social
|
|
70
|
-
// rulebook (heartbeat.md / rules.md), translated — not written here.
|
|
71
|
-
|
|
72
|
-
|
|
76
|
+
// rulebook (heartbeat.md / rules.md), translated — not written here. On by default: only in apps
|
|
77
|
+
// she installed herself (playApps is narrowed to what is on her phone), and only these actions.
|
|
78
|
+
play: true,
|
|
79
|
+
playActions: ['like', 'comment', 'follow', 'collect'], // collect = save stickers she likes (qq_sticker_keep)
|
|
73
80
|
maxPlaysPerDay: 0, // 0 = no cap: how often she plays is her own habit (her self notes); a round yields at most one play, so ≤ maxRoundsPerDay
|
|
74
|
-
playApps:
|
|
81
|
+
playApps: KNOWN_APPS.labels, // app label → package she may act in; {} = none
|
|
75
82
|
speak: false, // allow proactive contact over dsh-im
|
|
76
83
|
maxContactsPerDay: 2,
|
|
77
84
|
willingnessThreshold: 0.6,
|
|
@@ -110,6 +117,12 @@ export const PLAY_SOURCE = Object.freeze({ kind: 'dsh-interlude', form: 'play' }
|
|
|
110
117
|
|
|
111
118
|
/** The message that asks her to go and do the small thing she wanted to do on her phone. */
|
|
112
119
|
export function playPrompt(p, pkg) {
|
|
120
|
+
if (p.action === 'collect') return [
|
|
121
|
+
`[想玩会儿手机] 你刚才想:去${p.app}${pkg ? `(${pkg})` : ''}逛逛${p.target && p.target !== '表情包' ? `「${p.target}」` : ''},攒几张表情包。${p.why ? `因为${p.why}。` : ''}`,
|
|
122
|
+
`去吧,用你的手机(${PHONE_TOOL_PREFIX}*)。评论区、帖子里看到合你口味的表情包就长按保存到手机,然后 qq_sticker_keep(image: "phone:latest",note 写一两个词)存成你的。挑你真会用的,三五张就够,不要见一张存一张;不发帖、不私信、不花钱。`,
|
|
123
|
+
PLAY_RULES,
|
|
124
|
+
'做完把手机放回桌面(HOME),只回一句你存了什么,或者 DOT_SILENT。',
|
|
125
|
+
].join('\n');
|
|
113
126
|
const verb = { like: '点个赞', comment: '评论一句', follow: '关注' }[p.action] ?? p.action;
|
|
114
127
|
return [
|
|
115
128
|
`[想玩会儿手机] 你刚才想:在${p.app}${pkg ? `(${pkg})` : ''}给「${p.target}」${verb}${p.text ? `,想说的是:「${p.text}」` : ''}。${p.why ? `因为${p.why}。` : ''}`,
|
|
@@ -259,7 +272,7 @@ export function lengthBlockFor(model = '') {
|
|
|
259
272
|
}
|
|
260
273
|
|
|
261
274
|
/** The round's prompt: HDSI's lite-tier assembly. `entries` are recentScript items with owner labels. */
|
|
262
|
-
export function buildPrompt({ phase, identity, state, script, digest, cursor, now, intent, speak, model = '', style = '', entries = [], browser = 'disabled', webContext = [], play = false, playApps = [], playActions = [], memories = [], herLife = [] }) {
|
|
275
|
+
export function buildPrompt({ phase, identity, state, script, digest, cursor, now, intent, speak, model = '', style = '', entries = [], browser = 'disabled', webContext = [], play = false, playApps = [], playActions = [], stickers = -1, memories = [], herLife = [] }) {
|
|
263
276
|
const isDeepseek = /deepseek/i.test(String(model));
|
|
264
277
|
const isGlm = /glm/i.test(String(model));
|
|
265
278
|
const phaseText = phase === 'follow-up' ? HDSI.PHASE_FOLLOW_UP : phase === 'intent' ? HDSI.PHASE_INTENT_DUE : HDSI.PHASE_ADVANCE;
|
|
@@ -279,7 +292,7 @@ export function buildPrompt({ phase, identity, state, script, digest, cursor, no
|
|
|
279
292
|
browser === 'disabled' ? HDSI.BROWSING_DISABLED : HDSI.BROWSING_DEFERRED,
|
|
280
293
|
HDSI.WEB_CONTEXT,
|
|
281
294
|
speak && phase !== 'follow-up' ? HDSI.AGENCY_SEPARATION : '',
|
|
282
|
-
play && playApps.length ? `${PLAY_RULES}\n她手机上有这些 App 可以玩:${playApps.join('、')}。一个 playIntent 是她此刻真想做的一件小事,不是任务。玩多少、什么时候玩,按她自己的习惯来(herLife
|
|
295
|
+
play && playApps.length ? `${PLAY_RULES}\n她手机上有这些 App 可以玩:${playApps.join('、')}。一个 playIntent 是她此刻真想做的一件小事,不是任务。玩多少、什么时候玩,按她自己的习惯来(herLife 里她自己记下的);没有习惯就是还没养成,随她。${playActions.includes('collect') && stickers >= 0 && stickers < 5 ? `她的 QQ 表情包只有 ${stickers} 张,聊天时没得发;action "collect" 是去某个 App 逛逛顺手攒几张(target 写 "表情包")。` : ''}` : '',
|
|
283
296
|
isGlm ? HDSI.EXTRA_GLM : '',
|
|
284
297
|
'MAIN NARRATIVE PROMPT (user-configurable):',
|
|
285
298
|
HDSI.MAIN_PROMPT_DEFAULT,
|
|
@@ -686,9 +699,11 @@ export function apply(ctx, config = {}) {
|
|
|
686
699
|
const text = items.map((i) => `[${i.ts.slice(5, 16).replace('T', ' ')}${i.origin === 'schedule' ? ' 定时任务' : ' 用户'}]${i.approvals ? `(有 ${i.approvals} 次审批)` : ''}\n用户/任务:${i.user || '(无)'}\n我:${i.assistant || '(无回复)'}`).join('\n\n');
|
|
687
700
|
return { items, text: text.length > cfg.digestChars ? `…${text.slice(-cfg.digestChars)}` : text };
|
|
688
701
|
}
|
|
689
|
-
let busy = false;
|
|
702
|
+
let busy = false, fails = 0, pausedUntil = 0;
|
|
690
703
|
async function round(phase, intent = null) {
|
|
691
704
|
if (busy) return { skipped: 'busy' };
|
|
705
|
+
// After a failed round (model down, balance empty) the next one waits 5, 10, 20 … up to 60 minutes.
|
|
706
|
+
if (Date.now() < pausedUntil) return { skipped: 'paused after failures' };
|
|
692
707
|
rollDay();
|
|
693
708
|
if (meta.dayRounds >= cfg.maxRoundsPerDay) return { skipped: 'daily cap' };
|
|
694
709
|
const { items, text } = digest();
|
|
@@ -707,12 +722,12 @@ export function apply(ctx, config = {}) {
|
|
|
707
722
|
const mem = ctx.get('dotMemory');
|
|
708
723
|
// She plays only in apps she has installed herself: playApps narrowed to what is on her phone.
|
|
709
724
|
const onPhone = await (ctx.get('dshPhone')?.apps?.() ?? []);
|
|
710
|
-
const playApps = Object.keys(cfg.playApps).filter((label) =>
|
|
725
|
+
const playApps = Object.keys(cfg.playApps).filter((label) => onPhone.includes(cfg.playApps[label]));
|
|
711
726
|
const { system, user, tools } = buildPrompt({
|
|
712
727
|
phase, identity: clip(identity, 6000), state, script: readScript(files.script, cfg.scriptEntriesInPrompt).join('\n'),
|
|
713
728
|
digest: text, cursor: meta.cursor, now, intent, speak: cfg.speak, model: sel.model, style: canon?.storyDefaults?.style ?? '', entries,
|
|
714
729
|
browser: browsingOpen() ? 'deferred' : 'disabled', webContext: readWebContext(),
|
|
715
|
-
play: cfg.play && Boolean(ctx.get('dshPhone')?.isReady), playApps, playActions: cfg.playActions,
|
|
730
|
+
play: cfg.play && Boolean(ctx.get('dshPhone')?.isReady), playApps, playActions: cfg.playActions, stickers: ctx.get('dshQq')?.connected ? ctx.get('dshQq').stickerCount?.() ?? -1 : -1,
|
|
716
731
|
memories: mem?.forInterlude?.() ?? [], herLife: mem?.herLife?.() ?? [],
|
|
717
732
|
});
|
|
718
733
|
const options = { provider: sel.provider, model: sel.model, ...(sel.reasoningEffort ? { reasoningEffort: sel.reasoningEffort } : {}), system, tools, maxTokens: cfg.maxTokens,
|
|
@@ -784,8 +799,10 @@ export function apply(ctx, config = {}) {
|
|
|
784
799
|
for (const p of parsed?.playIntents ?? []) await playOut(p, phase);
|
|
785
800
|
audit('round', { phase, acts: items.length, intents: intents.length, browsed: (parsed?.browserIntents ?? []).length, played: (parsed?.playIntents ?? []).length, contact: Boolean(parsed?.contact), said });
|
|
786
801
|
logger.info(`interlude #${meta.count} (${phase}): ${items.length} act(s)${said ? ' + contact' : ''}`);
|
|
802
|
+
fails = 0;
|
|
787
803
|
return { ok: true, script, contact: parsed?.contact ?? null, said };
|
|
788
804
|
} catch (error) {
|
|
805
|
+
pausedUntil = Date.now() + Math.min(60, 5 * 2 ** fails++) * 60_000;
|
|
789
806
|
logger.warn(`interlude ${phase} failed: ${error.message}`);
|
|
790
807
|
audit('round-failed', { phase, error: clip(error.message, 200) });
|
|
791
808
|
return { error: error.message };
|
|
@@ -804,7 +821,9 @@ export function apply(ctx, config = {}) {
|
|
|
804
821
|
if (p.willingness < cfg.willingnessThreshold) return held('willingness');
|
|
805
822
|
rollDay();
|
|
806
823
|
if (cfg.maxPlaysPerDay > 0 && meta.dayPlays >= cfg.maxPlaysPerDay) return held('daily cap');
|
|
807
|
-
|
|
824
|
+
const phone = ctx.get('dshPhone');
|
|
825
|
+
if (!phone?.isReady) return held('phone not ready');
|
|
826
|
+
if (!(await phone.apps?.().catch(() => []) ?? []).includes(pkg)) return held(`${p.app} is not on her phone`);
|
|
808
827
|
// Looking and playing run in her errand session when dsh-dot has one: never in the middle of a conversation.
|
|
809
828
|
const sessionId = cfg.vmSession || (await errandSession()) || lastActSession;
|
|
810
829
|
const controller = ctx.get('sessionController');
|
package/src/phone/phone.js
CHANGED
|
@@ -377,8 +377,8 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
377
377
|
}
|
|
378
378
|
|
|
379
379
|
/** The poster file of the virtual-scene camera (read when an app opens the camera) and the PNG it shows. */
|
|
380
|
-
/** The emulator's scene poster list (resources/Toren1BD.posters, read at launch) and the
|
|
381
|
-
const posterFiles = () => { const dir = join(dirname(paths.emulator), 'resources'); return { dir, posters: join(dir, 'Toren1BD.posters')
|
|
380
|
+
/** The emulator's scene poster list (resources/Toren1BD.posters, read at launch) and the folder her camera images go in. */
|
|
381
|
+
const posterFiles = () => { const dir = join(dirname(paths.emulator), 'resources'); return { dir, posters: join(dir, 'Toren1BD.posters') }; };
|
|
382
382
|
/** Before launch: the stock "wall" poster (behind the camera's start pose) moves in front of it; "table" stays. The original is kept as .orig. */
|
|
383
383
|
function ensureCameraScene() {
|
|
384
384
|
try {
|
package/src/qq/qq.js
CHANGED
|
@@ -17,6 +17,7 @@ import { homedir } from 'node:os';
|
|
|
17
17
|
import { join, dirname } from 'node:path';
|
|
18
18
|
import { createAudit } from '../computer/audit.js';
|
|
19
19
|
import { QQ_SERVER, QQ_TOOL_PREFIX } from '../tool-prefixes.js';
|
|
20
|
+
import { createStickers, isSticker, STICKER_MAX_BYTES } from './stickers.js';
|
|
20
21
|
|
|
21
22
|
export const name = 'dot-qq';
|
|
22
23
|
export const inject = [];
|
|
@@ -43,6 +44,9 @@ export const defaults = {
|
|
|
43
44
|
// Outgoing text is tidied to her chat voice: no 。at line ends, no quotes/dashes/colons/asterisks/
|
|
44
45
|
// hashes (times and URLs keep theirs). Off = send exactly what the model wrote.
|
|
45
46
|
tidy: true,
|
|
47
|
+
// Each line of qq_send's text is its own bubble, sent after a pause that grows with its length
|
|
48
|
+
// (ms per character, capped at 2.5 s) — the way a person types. 0 = all at once.
|
|
49
|
+
typingMsPerChar: 60,
|
|
46
50
|
// qq_send approval: 'reply' (default) lets her write to the owner, and answer with text or web
|
|
47
51
|
// images whoever wrote to her within replyWindowMinutes (a conversation, group or private); anything
|
|
48
52
|
// else asks — a new contact, a group nobody spoke in, or files from her phone or computer (those
|
|
@@ -128,16 +132,19 @@ export function segmentsToText(message, selfId = '') {
|
|
|
128
132
|
/**
|
|
129
133
|
* Where an image she wants to send lives, as a OneBot image segment `file`:
|
|
130
134
|
* http(s)://… → the URL (NapCat downloads it)
|
|
135
|
+
* sticker:<id> → a sticker from her collection (stickers.js); face:<n> → a QQ system face
|
|
131
136
|
* phone:screen → a screenshot of her phone right now
|
|
132
137
|
* phone:latest → the newest photo/screenshot/download on her phone
|
|
133
138
|
* /sdcard/… or phone:/… → that file on her phone
|
|
134
139
|
* any other absolute path → that file on her computer (NapCat runs there)
|
|
135
|
-
* @returns {{kind: 'url'|'phone-screen'|'phone-latest'|'phone'|'computer', ref: string}|null}
|
|
140
|
+
* @returns {{kind: 'url'|'sticker'|'face'|'phone-screen'|'phone-latest'|'phone'|'computer', ref: string}|null}
|
|
136
141
|
*/
|
|
137
142
|
export function imageSource(ref) {
|
|
138
143
|
const s = String(ref ?? '').trim();
|
|
139
144
|
if (/^https?:\/\//i.test(s)) return { kind: 'url', ref: s }; // imageSegment still checks publicHttpUrl
|
|
140
145
|
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(s)) return null; // file://, ftp://, gopher:// … never handed on
|
|
146
|
+
const own = /^(sticker|face):\s*([0-9a-z]{1,10})$/i.exec(s);
|
|
147
|
+
if (own) return { kind: own[1].toLowerCase(), ref: own[2].toLowerCase() };
|
|
141
148
|
if (/^phone:screen(shot)?$/i.test(s)) return { kind: 'phone-screen', ref: s };
|
|
142
149
|
if (/^phone:latest$/i.test(s)) return { kind: 'phone-latest', ref: s };
|
|
143
150
|
const phonePath = /^phone:(\/.+)$/i.exec(s)?.[1] ?? (/^\/(sdcard|storage)\//.test(s) ? s : '');
|
|
@@ -210,7 +217,7 @@ export function sendGate({ to, text = '', images = [] }, { owner, policy = 'repl
|
|
|
210
217
|
const target = parseTarget(to, owner);
|
|
211
218
|
if (!target) return null; // qq.send rejects it with a clear error
|
|
212
219
|
if (owner && target.user_id === Number(owner)) return null;
|
|
213
|
-
const local = [].concat(images ?? []).filter((r) => r && !/^https
|
|
220
|
+
const local = [].concat(images ?? []).filter((r) => r && !/^(https?:\/\/|sticker:|face:)/i.test(String(r)));
|
|
214
221
|
const who = target.group_id ? `group:${target.group_id}` : `user:${target.user_id}`;
|
|
215
222
|
if (local.length) return `dsh-dot/qq: sending ${local.length} file(s) from her devices to ${who} (${local.map((r) => String(r).slice(0, 40)).join(', ')})`;
|
|
216
223
|
if (policy === 'always') return `dsh-dot/qq: message to ${who}: ${String(text).slice(0, 80)}`;
|
|
@@ -382,6 +389,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
382
389
|
sanitise('snowlumaVersion', (v) => { if (!/^[A-Za-z0-9._-]{1,40}$/.test(String(v))) throw new Error('bad release tag'); return String(v); }, '');
|
|
383
390
|
if (!cfg.token) { cfg.token = randomBytes(24).toString('hex'); writeSettings({ token: cfg.token }); }
|
|
384
391
|
const audit = createAudit(auditFile());
|
|
392
|
+
const stickers = createStickers(join(dshHome(), 'dsh-qq-stickers.json'), { fetch: deps.fetch ?? globalThis.fetch });
|
|
385
393
|
const computer = () => ctx.get('dshComputer');
|
|
386
394
|
let WebSocketImpl = deps.WebSocket; // the `ws` package, loaded on first connect (tests inject a fake)
|
|
387
395
|
|
|
@@ -516,7 +524,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
516
524
|
`echo "$tag" > ${SL_DIR}/.dot-version; echo 0 > ${SL_INSTALL_DONE}`,
|
|
517
525
|
].join('\n');
|
|
518
526
|
}
|
|
519
|
-
/** Install a backend: 'napcat' (NapCat + linuxqq) or 'snowluma' (
|
|
527
|
+
/** Install a backend: 'napcat' (NapCat + its patched linuxqq) or 'snowluma' (its own pinned linuxqq, Node 24, SnowLuma). */
|
|
520
528
|
qq.install = (which = 'napcat') => (installing ??= (async () => {
|
|
521
529
|
const snow = which === 'snowluma';
|
|
522
530
|
setState('installing');
|
|
@@ -571,7 +579,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
571
579
|
'sleep 1; echo "started on $D"',
|
|
572
580
|
].join('\n');
|
|
573
581
|
qq.start = async () => {
|
|
574
|
-
if (!(await qq.installed())) { setState('not-installed', sl() ? 'SnowLuma is not installed in the computer
|
|
582
|
+
if (!(await qq.installed())) { setState('not-installed', sl() ? 'SnowLuma is not installed in the computer (it needs /opt/QQ, /root/snowluma and its Node 24) — /qq install snowluma' : 'NapCat is not installed in the computer — /qq install'); return false; }
|
|
575
583
|
if (!sl() && !cfg.qq) { setState('needs-account', 'set the QQ number: /qq account <number>'); return false; }
|
|
576
584
|
await qq.configure();
|
|
577
585
|
await qq.ensureRoute().catch((err) => logger.warn(`OneBot route: ${err.message}`));
|
|
@@ -599,7 +607,6 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
599
607
|
return true;
|
|
600
608
|
};
|
|
601
609
|
qq.stop = async () => { if (qrFreshTimer) { clearInterval(qrFreshTimer); qrFreshTimer = null; } closeWs(); unmountMcp(); try { await vmShell(KILL_ALL); } catch {} setState('stopped'); audit({ kind: `${cfg.backend}-stopped` }); };
|
|
602
|
-
/** SnowLuma's login QR is drawn by the QQ GUI: a picture of the VM screen, with whichever tool exists. */
|
|
603
610
|
/** SnowLuma: keep a live code in front of her camera while she scans (QQ's codes last about a minute). */
|
|
604
611
|
let qrFreshTimer = null;
|
|
605
612
|
function keepCameraFresh(phone, firstCode) {
|
|
@@ -741,9 +748,9 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
741
748
|
closed = false;
|
|
742
749
|
if (ws) return;
|
|
743
750
|
// NapCat never came up, or went down with the VM's services: every few failed attempts, look and restart it.
|
|
744
|
-
if (failedConnects && failedConnects % 6 === 0 && cfg.qq && !(await qq.running().catch(() => true))) {
|
|
745
|
-
logger.warn(
|
|
746
|
-
audit({ kind:
|
|
751
|
+
if (failedConnects && failedConnects % 6 === 0 && (sl() || cfg.qq) && !(await qq.running().catch(() => true))) {
|
|
752
|
+
logger.warn(`${cfg.backend} is not running in the computer; starting it again`);
|
|
753
|
+
audit({ kind: `${cfg.backend}-restart`, after: failedConnects });
|
|
747
754
|
try { await qq.start(); return; } catch (err) { logger.warn(`restart failed: ${err.message}`); }
|
|
748
755
|
}
|
|
749
756
|
let opened = false;
|
|
@@ -755,7 +762,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
755
762
|
const headers = { ...(c.authHeaders?.() ?? {}), ...(authMode === 'header' ? { Authorization: `Bearer ${cfg.token}` } : authMode === 'query' ? { Authorization: `Bearer ${key}` } : {}) };
|
|
756
763
|
const socket = new WebSocketImpl(url, { headers });
|
|
757
764
|
ws = socket;
|
|
758
|
-
socket.on('open', () => { opened = true; failedConnects = 0; logger.info(`OneBot connected (
|
|
765
|
+
socket.on('open', () => { opened = true; failedConnects = 0; logger.info(`OneBot connected (${cfg.backend} in the computer, via the gateway${authMode === 'query' ? ', token in query' : ''})`); });
|
|
759
766
|
socket.on('unexpected-response', (_req, res) => {
|
|
760
767
|
// nginx's 401 page (not NapCat's JSON 1403 over an open socket): the gateway wants the key in Authorization.
|
|
761
768
|
if (res?.statusCode === 401 && authMode === 'header') { authMode = 'query'; logger.info('gateway rejected the header combination; switching the OneBot token to the query string'); }
|
|
@@ -793,10 +800,10 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
793
800
|
if (ev.post_type !== 'message') return;
|
|
794
801
|
const selfId = String(ev.self_id ?? qq.selfId);
|
|
795
802
|
if (String(ev.user_id) === selfId) return;
|
|
796
|
-
const text = segmentsToText(ev.message, selfId);
|
|
797
|
-
if (!text) return;
|
|
798
803
|
const isGroup = ev.message_type === 'group';
|
|
799
804
|
const who = ev.sender?.card || ev.sender?.nickname || String(ev.user_id);
|
|
805
|
+
const text = segmentsToText(Array.isArray(ev.message) ? ev.message.map((s) => (s?.type === 'image' && isSticker(s.data) ? keepSticker(s.data, who) : s)) : ev.message, selfId);
|
|
806
|
+
if (!text) return;
|
|
800
807
|
const wanted = isGroup ? groupWanted(ev, cfg.groupPolicy, selfId) : true;
|
|
801
808
|
if (isGroup) {
|
|
802
809
|
// The last lines of each group, for the scorer's context (kept whether or not she is woken).
|
|
@@ -811,6 +818,13 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
811
818
|
if (wanted === 'score') { void scoreAndDeliver(msg); return; }
|
|
812
819
|
deliver(msg);
|
|
813
820
|
}
|
|
821
|
+
/** A sticker someone sent: into her collection (downloaded once, in the background) and named in the text she reads. */
|
|
822
|
+
function keepSticker(d, who) {
|
|
823
|
+
const got = urlRefusal(d.url) ? null : stickers.note({ file: d.file, url: d.url, from: who });
|
|
824
|
+
if (!got) return { type: 'text', data: { text: '[表情包]' } };
|
|
825
|
+
if (got.isNew) stickers.fetch(got.id).then((ok) => { if (ok) audit({ kind: 'sticker-kept', id: got.id, from: who }); }, (err) => logger.debug(`sticker ${got.id}: ${err.message}`));
|
|
826
|
+
return { type: 'text', data: { text: `[表情包 sticker:${got.id}]` } };
|
|
827
|
+
}
|
|
814
828
|
function deliver(msg) {
|
|
815
829
|
audit({ kind: 'message', ...msg, text: msg.text.slice(0, 200) });
|
|
816
830
|
for (const fn of listeners) { try { fn(msg); } catch (err) { logger.warn(`qq listener: ${err.message}`); } }
|
|
@@ -852,40 +866,68 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
852
866
|
}
|
|
853
867
|
/** Send text to "user:123" | "group:456" | "owner" | a number. Several bubbles: split on <sep/>. */
|
|
854
868
|
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
869
|
+
/** The bytes of an image on her phone (phone:screen | phone:latest | a path there). */
|
|
870
|
+
async function phoneBytes(src) {
|
|
871
|
+
const phone = ctx.get('dshPhone');
|
|
872
|
+
if (!phone?.isReady) throw new Error('her phone is not ready');
|
|
873
|
+
if (src.kind === 'phone-screen') return phone.screenshot();
|
|
874
|
+
let path = src.ref;
|
|
875
|
+
if (src.kind === 'phone-latest') {
|
|
876
|
+
path = (await phone.shell('ls -t /sdcard/DCIM/Camera/* /sdcard/Pictures/Screenshots/* /sdcard/DCIM/Screenshots/* /sdcard/Pictures/* /sdcard/Download/* 2>/dev/null | grep -iE "\\.(jpe?g|png|webp|gif|heic)$" | head -1')).trim();
|
|
877
|
+
if (!path) throw new Error('no photos on her phone yet');
|
|
878
|
+
}
|
|
879
|
+
const buf = Buffer.from((await phone.adbExec(['exec-out', 'cat', path], { encoding: 'buffer', maxBuffer: MAX_IMAGE_BYTES * 2 })).stdout);
|
|
880
|
+
if (!buf.length) throw new Error(`empty or missing on the phone: ${path}`);
|
|
881
|
+
if (buf.length > MAX_IMAGE_BYTES) throw new Error(`image too large (${Math.round(buf.length / 1048576)} MB > 10 MB)`);
|
|
882
|
+
return buf;
|
|
883
|
+
}
|
|
855
884
|
/** One OneBot image segment for an image she refers to (see imageSource). */
|
|
856
885
|
async function imageSegment(ref) {
|
|
857
886
|
const src = imageSource(ref);
|
|
858
|
-
if (!src) throw new Error(`can't find image "${ref}" (http(s) URL | phone:screen | phone:latest | /sdcard/… | a path on your computer)`);
|
|
887
|
+
if (!src) throw new Error(`can't find image "${ref}" (sticker:<id> | face:<n> | http(s) URL | phone:screen | phone:latest | /sdcard/… | a path on your computer)`);
|
|
859
888
|
if (src.kind === 'url') {
|
|
860
889
|
const why = urlRefusal(src.ref);
|
|
861
890
|
if (why) throw new Error(`refusing image URL "${src.ref.slice(0, 80)}": ${why} — only public http/https addresses on ports 80/443`);
|
|
862
891
|
return { type: 'image', data: { file: publicHttpUrl(src.ref) } };
|
|
863
892
|
}
|
|
864
893
|
if (src.kind === 'computer') return { type: 'image', data: { file: `file://${src.ref}` } };
|
|
865
|
-
|
|
866
|
-
if (
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
let path = src.ref;
|
|
871
|
-
if (src.kind === 'phone-latest') {
|
|
872
|
-
path = (await phone.shell('ls -t /sdcard/DCIM/Camera/* /sdcard/Pictures/Screenshots/* /sdcard/DCIM/Screenshots/* /sdcard/Pictures/* /sdcard/Download/* 2>/dev/null | grep -iE "\\.(jpe?g|png|webp|gif|heic)$" | head -1')).trim();
|
|
873
|
-
if (!path) throw new Error('no photos on her phone yet');
|
|
874
|
-
}
|
|
875
|
-
buf = Buffer.from((await phone.adbExec(['exec-out', 'cat', path], { encoding: 'buffer', maxBuffer: MAX_IMAGE_BYTES * 2 })).stdout);
|
|
876
|
-
if (!buf.length) throw new Error(`empty or missing on the phone: ${path}`);
|
|
894
|
+
if (src.kind === 'face') return { type: 'face', data: { id: src.ref } };
|
|
895
|
+
if (src.kind === 'sticker') {
|
|
896
|
+
const buf = stickers.read(src.ref);
|
|
897
|
+
if (!buf) throw new Error(`no sticker ${src.ref} in her collection (ids come from [表情包 sticker:…] in messages, or qq_sticker_keep)`);
|
|
898
|
+
return { type: 'image', data: { file: `base64://${buf.toString('base64')}`, sub_type: 1 } };
|
|
877
899
|
}
|
|
878
|
-
|
|
879
|
-
return { type: 'image', data: { file: `base64://${buf.toString('base64')}` } };
|
|
900
|
+
return { type: 'image', data: { file: `base64://${(await phoneBytes(src)).toString('base64')}` } };
|
|
880
901
|
}
|
|
881
|
-
/**
|
|
902
|
+
/** Keep an image as one of her stickers: from her phone (phone:latest | /sdcard/…) or a public web image. */
|
|
903
|
+
qq.keepSticker = async (ref, note = '') => {
|
|
904
|
+
const src = imageSource(ref);
|
|
905
|
+
let buf;
|
|
906
|
+
if (src?.kind === 'url') {
|
|
907
|
+
const why = urlRefusal(src.ref);
|
|
908
|
+
if (why) throw new Error(`refusing image URL: ${why}`);
|
|
909
|
+
const res = await (deps.fetch ?? globalThis.fetch)(publicHttpUrl(src.ref), { signal: AbortSignal.timeout(30_000) });
|
|
910
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
911
|
+
buf = Buffer.from(await res.arrayBuffer());
|
|
912
|
+
} else if (src && ['phone-latest', 'phone'].includes(src.kind)) buf = await phoneBytes(src);
|
|
913
|
+
else throw new Error(`keep a sticker from "phone:latest", a path on your phone (/sdcard/…) or a web image URL — not "${ref}"`);
|
|
914
|
+
if (buf.length > STICKER_MAX_BYTES) throw new Error(`too big for a sticker (${Math.round(buf.length / 1048576)} MB > ${STICKER_MAX_BYTES / 1048576} MB)`);
|
|
915
|
+
const got = stickers.keep(buf, { from: '自己存的', note });
|
|
916
|
+
audit({ kind: 'sticker-kept', id: got.id, from: 'self', note: String(note).slice(0, 40), isNew: got.isNew });
|
|
917
|
+
return got;
|
|
918
|
+
};
|
|
919
|
+
qq.stickerCount = () => stickers.count();
|
|
920
|
+
/** Send to "user:123" | "group:456" | "owner" | a number: text (one bubble per line or <sep/>, paced) and/or images, in that order. */
|
|
882
921
|
qq.send = async (to, text = '', images = []) => {
|
|
883
922
|
const target = parseTarget(to, qq.owner);
|
|
884
923
|
if (!target) throw new Error(`bad target "${to}" (user:<number> | group:<number> | owner)`);
|
|
885
924
|
const action = target.group_id ? 'send_group_msg' : 'send_private_msg';
|
|
886
|
-
const parts = String(text ?? '').split(/<sep\s
|
|
925
|
+
const parts = String(text ?? '').split(/<sep\s*\/>|\n/i).map((t) => (cfg.tidy ? tidyVoice(t) : t.trim())).filter(Boolean);
|
|
887
926
|
const ids = [];
|
|
888
|
-
for (const part of parts
|
|
927
|
+
for (const [i, part] of parts.entries()) {
|
|
928
|
+
if (i && cfg.typingMsPerChar > 0) await new Promise((r) => setTimeout(r, Math.min(2500, part.length * cfg.typingMsPerChar)));
|
|
929
|
+
ids.push((await call(action, { ...target, message: [{ type: 'text', data: { text: part } }] }))?.message_id);
|
|
930
|
+
}
|
|
889
931
|
for (const ref of [].concat(images ?? []).filter(Boolean)) ids.push((await call(action, { ...target, message: [await imageSegment(ref)] }))?.message_id);
|
|
890
932
|
const n = ids.length;
|
|
891
933
|
if (!n) throw new Error('nothing to send (text and images both empty)');
|
|
@@ -943,7 +985,7 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
943
985
|
ctx.inject(['tools'], (scope) => {
|
|
944
986
|
scope.effect(() => scope.tools.register({
|
|
945
987
|
name: 'qq_send',
|
|
946
|
-
description: '用你的 QQ(电脑端在线)发消息:文字和/或图片。to: "user:<QQ号>"、"group:<群号>" 或 "owner"
|
|
988
|
+
description: '用你的 QQ(电脑端在线)发消息:文字和/或图片。to: "user:<QQ号>"、"group:<群号>" 或 "owner"(和你说话的人)。text 里每一行是单独一条消息,像人打字那样一句一句发。images 是要发的图片,每张直接作为图片发出去(不是链接):"sticker:<id>"(你存的表情包,id 见收到的 [表情包 sticker:…]);"face:<编号>"(QQ 小黄脸);图片网址;"phone:screen"(你手机此刻的屏幕截图);"phone:latest"(你手机里最新的照片/截图/下载);手机上的路径 "/sdcard/...";或你电脑上的绝对路径。只在你确实想回或想说时用。',
|
|
947
989
|
parameters: { type: 'object', properties: { to: { type: 'string' }, text: { type: 'string' }, images: { type: 'array', items: { type: 'string' } } }, required: ['to'], additionalProperties: false },
|
|
948
990
|
output: { schema: { type: 'object', properties: { sent: { type: 'number' } }, required: ['sent'], additionalProperties: true }, render: (_a, v) => [{ type: 'text', text: `sent ${v?.sent ?? 0} message(s)` }] },
|
|
949
991
|
async execute(args) {
|
|
@@ -951,6 +993,13 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
951
993
|
return { sent: r.sent };
|
|
952
994
|
},
|
|
953
995
|
}), 'dsh-dot/qq: qq_send tool');
|
|
996
|
+
scope.effect(() => scope.tools.register({
|
|
997
|
+
name: 'qq_sticker_keep',
|
|
998
|
+
description: '把一张图存成你自己的表情包,以后用 qq_send 的 images: ["sticker:<id>"] 发。image:"phone:latest"(你手机里刚保存的图,在 App 里长按图片保存后用这个)、手机上的路径 "/sdcard/...",或图片网址。note 是你给它起的一两个词(比如 "无语"、"偷笑"),方便以后挑。',
|
|
999
|
+
parameters: { type: 'object', properties: { image: { type: 'string' }, note: { type: 'string' } }, required: ['image'], additionalProperties: false },
|
|
1000
|
+
output: { schema: { type: 'object', properties: { id: { type: 'string' }, isNew: { type: 'boolean' } }, required: ['id'], additionalProperties: true }, render: (_a, v) => [{ type: 'text', text: `sticker:${v?.id}${v?.isNew ? '' : ' (already kept)'}` }] },
|
|
1001
|
+
async execute(args) { return qq.keepSticker(args.image, args.note ?? ''); },
|
|
1002
|
+
}), 'dsh-dot/qq: qq_sticker_keep tool');
|
|
954
1003
|
});
|
|
955
1004
|
|
|
956
1005
|
ctx.inject(['systemPrompt'], (scope) => {
|
|
@@ -958,7 +1007,8 @@ export function apply(ctx, config = {}, deps = {}) {
|
|
|
958
1007
|
name: 'qq:channel',
|
|
959
1008
|
order: 61,
|
|
960
1009
|
text: () => (qq.connected
|
|
961
|
-
? `你的 QQ(${qq.qq})在你电脑上也登着。${qq.owner ? `QQ ${qq.owner} 是你的人:他私聊你的话会原样出现在对话里,就是他本人对你说的,回他用 qq_send(to: "owner")。` : ''}其他人发来的消息会以「[QQ] 谁:内容」叫醒你,回复用 qq_send(立刻送达,to 用 user:<QQ号> 或 owner)。${cfg.groupPolicy === 'score' ? '群消息先过了一道筛,叫醒你的都是和你相关或你明显有话说的;插话就只聊天,一两句,回 to 用 group:<群号>,没话说就不回。' : ''}要给人看图就用 qq_send 的 images 直接发图片——网上的图给网址,手机屏幕给 "phone:screen",手机里刚存的给 "phone:latest"——别发链接让人自己点。别人发来的图片会带一个网址,想看就打开。手机上的 QQ
|
|
1010
|
+
? `你的 QQ(${qq.qq})在你电脑上也登着。${qq.owner ? `QQ ${qq.owner} 是你的人:他私聊你的话会原样出现在对话里,就是他本人对你说的,回他用 qq_send(to: "owner")。` : ''}其他人发来的消息会以「[QQ] 谁:内容」叫醒你,回复用 qq_send(立刻送达,to 用 user:<QQ号> 或 owner)。${cfg.groupPolicy === 'score' ? '群消息先过了一道筛,叫醒你的都是和你相关或你明显有话说的;插话就只聊天,一两句,回 to 用 group:<群号>,没话说就不回。' : ''}要给人看图就用 qq_send 的 images 直接发图片——网上的图给网址,手机屏幕给 "phone:screen",手机里刚存的给 "phone:latest"——别发链接让人自己点。别人发来的图片会带一个网址,想看就打开。手机上的 QQ 照常可以看空间、看群。
|
|
1011
|
+
聊天的样子:一句话一行,每行就是一条消息,短的几条比一大段好;想用表情就在 images 里发:${stickers.prompt() || '你还没有表情包;别人发给你的会自动存下来,手机 App 里看到喜欢的长按保存再 qq_sticker_keep 也能存'};QQ 小黄脸 face:<编号>,常用的 14 微笑 4 得意 5 流泪 13 呲牙 20 偷笑 32 疑问 34 晕 66 爱心 97 擦汗 101 坏笑 105 委屈 111 可怜 174 无奈 178 斜眼笑 179 doge 182 笑哭 212 托腮 277 汪汪 285 摸鱼 299 牛啊 319 比心 326 生气。可以只发一个表情不说话。`
|
|
962
1012
|
: ''),
|
|
963
1013
|
}), 'dsh-dot/qq: channel section');
|
|
964
1014
|
});
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Her sticker collection: images people send her that QQ marks as stickers (image sub_type 1), and
|
|
2
|
+
// ones she keeps herself (qq_sticker_keep: saved on her phone, or a web image). Files live in
|
|
3
|
+
// $DSH_HOME/stickers/<id>.img (QQ's URLs expire), the list in $DSH_HOME/dsh-qq-stickers.json.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
|
|
8
|
+
const MAX = 300;
|
|
9
|
+
export const STICKER_MAX_BYTES = 4 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
/** An image segment's data → is it a sticker? (NapCat and SnowLuma both set sub_type 1 on 表情包.) */
|
|
12
|
+
export const isSticker = (d) => String(d?.sub_type ?? '') === '1' || /表情/.test(String(d?.summary ?? ''));
|
|
13
|
+
|
|
14
|
+
export function createStickers(file, { fetch = globalThis.fetch } = {}) {
|
|
15
|
+
const dir = join(dirname(file), 'stickers');
|
|
16
|
+
let list = [];
|
|
17
|
+
try { list = JSON.parse(readFileSync(file, 'utf8')); } catch {}
|
|
18
|
+
const save = () => { try { mkdirSync(dir, { recursive: true }); writeFileSync(file, JSON.stringify(list)); } catch {} };
|
|
19
|
+
const path = (id) => join(dir, `${id}.img`);
|
|
20
|
+
const add = (entry) => {
|
|
21
|
+
list.push(entry);
|
|
22
|
+
while (list.length > MAX) { const old = list.shift(); try { rmSync(path(old.id), { force: true }); } catch {} }
|
|
23
|
+
save();
|
|
24
|
+
};
|
|
25
|
+
const stickers = {
|
|
26
|
+
list: () => list,
|
|
27
|
+
count: () => list.filter((s) => s.saved).length,
|
|
28
|
+
get: (id) => list.find((s) => s.id === id),
|
|
29
|
+
path,
|
|
30
|
+
/** Bytes of a kept sticker, or null. */
|
|
31
|
+
read: (id) => { const s = stickers.get(id); if (!s?.saved) return null; try { return readFileSync(path(id)); } catch { return null; } },
|
|
32
|
+
/**
|
|
33
|
+
* A sticker seen in a message: noted by its QQ file name (one entry per picture), downloaded
|
|
34
|
+
* once in the background. Returns { id, isNew }.
|
|
35
|
+
*/
|
|
36
|
+
note({ file: name, url, from }) {
|
|
37
|
+
const key = String(name || url || '').replace(/[?#].*$/, '');
|
|
38
|
+
if (!key || !url) return null;
|
|
39
|
+
const id = createHash('sha1').update(key).digest('hex').slice(0, 10);
|
|
40
|
+
let s = stickers.get(id);
|
|
41
|
+
if (s) { s.seen = (s.seen ?? 1) + 1; if (!s.saved) s.url = url; save(); return { id, isNew: false }; }
|
|
42
|
+
s = { id, url, from: String(from ?? ''), at: new Date().toISOString().slice(0, 10), seen: 1, saved: false };
|
|
43
|
+
add(s);
|
|
44
|
+
return { id, isNew: true };
|
|
45
|
+
},
|
|
46
|
+
/** Download a noted sticker (its QQ URL) into the collection; true when it is there. */
|
|
47
|
+
async fetch(id) {
|
|
48
|
+
const s = stickers.get(id);
|
|
49
|
+
if (!s) return false;
|
|
50
|
+
if (s.saved && existsSync(path(id))) return true;
|
|
51
|
+
if (!s.url) return false;
|
|
52
|
+
const res = await fetch(s.url, { signal: AbortSignal.timeout(30_000) });
|
|
53
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
54
|
+
const buf = Buffer.from(await res.arrayBuffer());
|
|
55
|
+
if (!buf.length || buf.length > STICKER_MAX_BYTES) throw new Error(`${buf.length} bytes`);
|
|
56
|
+
mkdirSync(dir, { recursive: true }); writeFileSync(path(id), buf);
|
|
57
|
+
s.saved = true; delete s.url; save();
|
|
58
|
+
return true;
|
|
59
|
+
},
|
|
60
|
+
/** Keep an image she chose herself (bytes): one entry per picture (by content). Returns { id, isNew }. */
|
|
61
|
+
keep(buf, { from = '自己存的', note = '' } = {}) {
|
|
62
|
+
if (!buf?.length || buf.length > STICKER_MAX_BYTES) throw new Error(`sticker must be 1 byte – ${STICKER_MAX_BYTES / 1048576} MB`);
|
|
63
|
+
const id = createHash('sha1').update(buf).digest('hex').slice(0, 10);
|
|
64
|
+
const s = stickers.get(id);
|
|
65
|
+
if (s) { if (note) s.note = String(note).slice(0, 40); save(); return { id, isNew: false }; }
|
|
66
|
+
mkdirSync(dir, { recursive: true }); writeFileSync(path(id), buf);
|
|
67
|
+
add({ id, from: String(from), note: String(note).slice(0, 40), at: new Date().toISOString().slice(0, 10), seen: 1, saved: true });
|
|
68
|
+
return { id, isNew: true };
|
|
69
|
+
},
|
|
70
|
+
/** One line for her prompt: the newest ones, newest last. */
|
|
71
|
+
prompt(n = 12) {
|
|
72
|
+
const got = list.filter((s) => s.saved).slice(-n);
|
|
73
|
+
return got.length ? `你存的表情包(images 里写 sticker:<id> 就能发):${got.map((s) => `${s.id}(${s.note || `${s.from} 发的`}${s.seen > 1 ? ` ×${s.seen}` : ''})`).join('、')}` : '';
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
return stickers;
|
|
77
|
+
}
|