dsh-dot-life 0.21.1 → 0.22.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.en.md CHANGED
@@ -13,6 +13,9 @@ Between your conversations, she keeps living.
13
13
  [![node](https://img.shields.io/badge/node-%E2%89%A5%2022-339933?style=flat-square&logo=node.js&logoColor=white)](package.json)
14
14
  [![stars](https://img.shields.io/github/stars/Kevinwu901113/dsh-dot?style=flat-square&color=f59e0b)](https://github.com/Kevinwu901113/dsh-dot/stargazers)
15
15
 
16
+ [![DSH Market](https://raw.githubusercontent.com/2BingLing/dsh-market/master/assets/readme/badge-listed-en.svg)](https://dsh.market/)
17
+ [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com)
18
+
16
19
  [简体中文](README.md) · **English**
17
20
 
18
21
  [Quick start](#-quick-start) · [Features](#-features) · [Settings](#%EF%B8%8F-settings) · [Architecture](#-architecture) · [Commands](#%EF%B8%8F-commands) · [Coexistence](#-coexisting-with-other-plugins)
@@ -81,7 +84,7 @@ Every key, which ones only apply to a newly created phone / VM, and rules for ag
81
84
 
82
85
  ## 🧩 Architecture
83
86
 
84
- One plugin, six components. Each can be turned off on its own; the rest keep running.
87
+ One plugin, seven components. Each can be turned off on its own; the rest keep running.
85
88
 
86
89
  ```mermaid
87
90
  flowchart LR
@@ -116,13 +119,14 @@ flowchart LR
116
119
  | **`memory`** | Transcript + auto-recall (local multilingual-e5-small + bge-reranker-base; SiliconFlow / DashScope optional), three notes (about you / herself / not over yet), people cards, diary, handoff · [docs](docs/memory.md) | `DSH_DOT_MEMORY=off` |
117
120
  | **`dot`** | Scheduled results → IM, approval and device notices, working rules, sidebar status panel | `DSH_DOT_CONTACT=off` |
118
121
  | **`computer`** | Bundled microVM ([microsandbox](https://github.com/zerocore-ai/microsandbox)) or Docker · [docs](docs/computer.md) | `DSH_DOT_COMPUTER=off` |
122
+ | **`compat`** | Living next to other plugins: whose session is this, which tools it sees, where its commands run; knows [qq-bridge](https://github.com/Derpyu520/qq-bridge) today · [docs (zh)](docs/qq-bridge.md) | `DSH_DOT_COMPAT=off` |
119
123
 
120
124
  ## ⌨️ Commands
121
125
 
122
126
  ```text
123
127
  /phone [accept|restart|screenshot]
124
128
  /interlude [now|advance|seed|preset <code>|canon]
125
- /dot [test|check]
129
+ /dot [test|check|doctor]
126
130
  /dot memory [now|diary|handoff|recall …]
127
131
  /dot people [approve <id>|drop <id>|forget <name>]
128
132
  /qq [install|account|start|qr|backend|owner]
@@ -136,6 +140,7 @@ The **◎** button at the top of a conversation opens the dot panel: device stat
136
140
  - MCP tools are namespaced: `mcp__dot-vm__*`, `mcp__dot-phone__*`.
137
141
  - Memory coexistence (`DSH_DOT_MEMORY_COEXIST=auto`) drops to `people-only` when another memory service is found.
138
142
  - One QQ account, one responder. `bash` also passes the computer gate.
143
+ - [qq-bridge](https://github.com/Derpyu520/qq-bridge) is detected and lived with (`compat` settings, [docs/qq-bridge.md](docs/qq-bridge.md)): none of dot's tools in its sessions, its folder never shared into her VM, its bot never answered; its closed-agent owner chat gets her phone and computer.
139
144
 
140
145
  See the [Chinese README](README.md#-与其他插件共存) for injected message `source` tags (for context-compression plugins) and upgrade notes.
141
146
 
package/README.md CHANGED
@@ -13,6 +13,9 @@
13
13
  [![node](https://img.shields.io/badge/node-%E2%89%A5%2022-339933?style=flat-square&logo=node.js&logoColor=white)](package.json)
14
14
  [![stars](https://img.shields.io/github/stars/Kevinwu901113/dsh-dot?style=flat-square&color=f59e0b)](https://github.com/Kevinwu901113/dsh-dot/stargazers)
15
15
 
16
+ [![DSH Market](https://raw.githubusercontent.com/2BingLing/dsh-market/master/assets/readme/badge-listed-zh.svg)](https://dsh.market/)
17
+ [![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://awesome-dsh-plugin.com)
18
+
16
19
  **简体中文** · [English](README.en.md)
17
20
 
18
21
  [快速开始](#-快速开始) · [她能做什么](#-她能做什么) · [设置](#%EF%B8%8F-设置) · [架构](#-架构) · [命令](#%EF%B8%8F-命令与文件) · [共存](#-与其他插件共存) · [路线图](docs/ROADMAP.md)
@@ -127,6 +130,9 @@ dsh plugin --profile desktop add github:Kevinwu901113/dsh-dot # 源码
127
130
 
128
131
  </details>
129
132
 
133
+ > [!TIP]
134
+ > **已经在用 [qq-bridge](https://github.com/Derpyu520/qq-bridge),只想要她的手机和电脑?** 直接装,什么都不用配:插件会认出 qq-bridge,它的会话里不出现 dot 的工具,它的目录不进虚拟机,它的机器人号她不回。把 qq-bridge 切到 closed-agent 模式,管理员私聊就能用 `mcp__dot-phone__*` / `mcp__dot-vm__*`;dot / 记忆 / 幕间 / QQ 四个组件可以在插件页关掉。细节在 [docs/qq-bridge.md](docs/qq-bridge.md)。
135
+
130
136
  ## ⚙️ 设置
131
137
 
132
138
  所有个人设置都在**一个文件**:`~/.dsh/dsh-dot.json`(Windows:`%USERPROFILE%\.dsh\dsh-dot.json`),按组件分段,升级插件不会覆盖,改完重启 dsh。
@@ -146,7 +152,7 @@ dsh plugin --profile desktop add github:Kevinwu901113/dsh-dot # 源码
146
152
 
147
153
  ## 🧩 架构
148
154
 
149
- 一个插件,六个组件。每个都能单独关,缺了哪个其余照常跑。
155
+ 一个插件,七个组件。每个都能单独关,缺了哪个其余照常跑。
150
156
 
151
157
  ```mermaid
152
158
  flowchart LR
@@ -181,6 +187,7 @@ flowchart LR
181
187
  | **`memory`** 🧠 | 原话库 + 自动召回(本机 multilingual-e5-small + bge-reranker-base,可切 SiliconFlow / DashScope);三栏笔记(关于你 / 她自己 / 还没了的事);人物卡;日记;15 万 token 交班 · [文档](docs/memory.md) | — | `DSH_DOT_MEMORY=off` |
182
188
  | **`dot`** ◎ | 定时结果 → IM、审批与设备提醒、工作规则、右侧栏状态面板 | [dsh-im](https://github.com/xmanrui/dsh-im) | `DSH_DOT_CONTACT=off` |
183
189
  | **`computer`** 🖥️ | 自带 microVM:shell、浏览器、桌面、实时画面、审批、审计 · [文档](docs/computer.md) | [microsandbox](https://github.com/zerocore-ai/microsandbox)(自带)或 Docker | `DSH_DOT_COMPUTER=off` |
190
+ | **`compat`** 🤝 | 和别的插件共处:每个会话归谁、看得见哪些工具、命令在哪跑;今天认 [qq-bridge](https://github.com/Derpyu520/qq-bridge) · [文档](docs/qq-bridge.md) | — | `DSH_DOT_COMPAT=off` |
184
191
 
185
192
  ## 🕰️ 她的一天
186
193
 
@@ -199,7 +206,7 @@ flowchart LR
199
206
  ```text
200
207
  /phone [accept|restart|screenshot]
201
208
  /interlude [now|advance|seed|preset <code>|canon]
202
- /dot [test|check|prompts [stop]]
209
+ /dot [test|check|doctor|prompts [stop]]
203
210
  /dot memory [now|diary|handoff|recall …]
204
211
  /dot people [approve <id>|drop <id>|forget <名字>]
205
212
  /qq [install|account|start|qr|backend|owner]
@@ -240,6 +247,7 @@ flowchart LR
240
247
  - **MCP 工具名有命名空间**:`mcp__dot-vm__*`、`mcp__dot-phone__*`,前缀定义在 `src/tool-prefixes.js`。
241
248
  - **记忆共存**:`DSH_DOT_MEMORY_COEXIST` 默认 `auto`,发现 `hermesMemory` / `autoMemory` / `dshMemory` / `memoryBank` 等就切到 `people-only`,只保留人物卡、还没了的事、日记和召回,免得两个插件一起"讲记忆"。`full` / `people-only` 可强制。
242
249
  - **一个 QQ 号只能有一个应答者**:不要在她的号上再跑别的 OneBot 机器人。
250
+ - **[qq-bridge](https://github.com/Derpyu520/qq-bridge)**:自动认出并共处,见 [docs/qq-bridge.md](docs/qq-bridge.md)——它的会话里不出现 dot 的工具,它的目录不进她的虚拟机,它的机器人号她不回;它 closed-agent 模式的管理员私聊能用她的手机和电脑(`compat` 设置)。
243
251
  - **`bash` 也过电脑闸门**:别的插件再给 `bash` 加审批,同一条命令会弹两次。
244
252
  - **上下文压缩插件**:dsh-dot 注入的消息带固定 `source`,压缩时请保留、别当成用户原话:
245
253
 
package/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-dot: one plugin, five components. The character lives on her own devices.
1
+ # dsh-dot: one plugin, seven components. The character lives on her own devices.
2
2
  # phone — her phone: an Android emulator this plugin installs, boots and keeps alive;
3
3
  # tools mcp__dot-phone__* (mobile-mcp over adb). The emulator window is the live view.
4
4
  # DSH_DOT_PHONE=off turns it off.
@@ -13,6 +13,8 @@
13
13
  # live view, working rules as a prompt section. Needs dsh-im and the official
14
14
  # schedule bundle (see README). DSH_DOT_CONTACT=off turns it off.
15
15
  # memory — what she remembers (people, fragments, diary, owner/self banks). DSH_DOT_MEMORY=off.
16
+ # compat — living next to qq-bridge: per-session tool visibility, where its commands run, its bot
17
+ # accounts kept out of her QQ. DSH_DOT_COMPAT=off turns it off.
16
18
  # interlude — 幕间, after HDS-Interlude: the Canon (persona, HDSI presets by share code) as a
17
19
  # prompt section, and a life between conversations — script, continuity, intents,
18
20
  # going to look at things on her phone / in her browser (read-only), optional
@@ -37,6 +39,12 @@
37
39
  defaultPreset: !!js "process.env.DSH_DOT_COMPUTER === 'off' ? 'workspace-write' : (process.env.DSH_COMPUTER_PRESET ?? 'computer')"
38
40
 
39
41
  - insert:
42
+ # 0. Living next to other plugins (qq-bridge today): whose session is this, which of our tools it
43
+ # may see, where its commands run, which QQ accounts are not hers to answer. Always on; it only
44
+ # does something when qq-bridge is found (docs/qq-bridge.md). DSH_DOT_COMPAT=off turns it off.
45
+ - id: dot-compat
46
+ disabled: !!js "process.env.DSH_DOT_COMPAT === 'off'"
47
+ name: 'dsh-dot-life/compat'
40
48
  - id: dot-computer
41
49
  disabled: !!js "process.env.DSH_DOT_COMPUTER === 'off'"
42
50
  name: 'dsh-dot-life/computer'
package/docs/DESIGN.md CHANGED
@@ -118,7 +118,7 @@ dsh-bridge 没有公开服务,所以 `src/im.js` 包装了基类原型上的 `
118
118
 
119
119
  Kevin:"把 computer 和 dot 合并为一个插件的不同组件"。做法:
120
120
 
121
- - dsh-computer 仓库的历史用 `git merge --allow-unrelated-histories` 并进来(提交记录保留),文件移到 `src/computer/`(vm / subprocess / gate / audit / backends / ui-host),原 dsh-dot 的 core 移到 `src/dot/core.js`。
121
+ - dsh-computer 仓库的历史用 `git merge --allow-unrelated-histories` 并进来(提交记录保留),文件移到 `src/computer/`(vm / subprocess / gate / audit / backends;根组件的宿主侧现在在 `src/page/host.js`),原 dsh-dot 的 core 移到 `src/dot/core.js`。
122
122
  - `cordis.patch.yml` 合并:电脑那部分(关掉宿主 subprocess、沙箱策略、权限预设、`dot-computer` / `dot-subprocess` / `dot-gate` / `dot-mcp` / `dot-ui`)在前,`dot` 在后。组件名 `dsh-dot/computer`、`dsh-dot/subprocess`、`dsh-dot/gate`、`dsh-dot/dot`;`package.json` 的 `exports` 对应。
123
123
  - 客户端 bundle `lib/client.js` 的 `__ModuleLoader__` id 必须等于包名,改成 `dsh-dot`(CSS tag 同步);标签页内部 id 不动。`ui/` 源码的 tsdown 配置同步。
124
124
  - **对外不变**(v0.9.2 前):`mcp__vm__*` 工具(v0.9.2 起改为 `mcp__dot-vm__*`,避免和别的插件撞名)、`dshComputer` 服务名、`~/.dsh/dsh-computer*` 文件、VM 名 `dsh-computer`、`DSH_COMPUTER_*` 环境变量都保留——已经跑着的虚拟机、快照、审计日志不用迁移。
@@ -330,3 +330,14 @@ Kevin:"感觉现在很难给他长任务。他很容易直接结束然后就
330
330
  - **体检**:`/phone doctor`(不再依赖 dot 组件),虚拟化、磁盘、内存(Windows 页面文件,已在跑的不重复算)、端口占用(BlueStacks 的 5555 等)、下载源、手机网络、模拟器崩溃;能修的带一键修复(`/phone doctor fix <id>`)。首次启动和手机出错时自动跑。
331
331
  - **dot 设置页**(左侧栏「dot 设置」,设计见 `docs/DOT-PAGE.md`):开始(六步引导:体检、组件、手机、电脑、人设、QQ)、状态、设置(按 `src/settings-schema.js` 生成的表单,写 `~/.dsh/dsh-dot.json`)、体检(一键修复)、诊断(打码的诊断包下载 / 存到 `~/.dsh/diag/`,复制摘要)、危险区(重建手机、清下载缓存)。首次打开 dsh 右下角提示一次。挂在插件根组件上,只开部分组件也能用。
332
332
  - `dsh-dot.json` 格式坏了会在 `/phone` 和页面上直接显示,不再只进日志。
333
+
334
+ ## 0.22.0:和 qq-bridge 共处
335
+
336
+ 起因:很多人先装了 [qq-bridge](https://github.com/Derpyu520/qq-bridge),再想要这里的手机和虚拟机。逐组件对过两边源码(`docs/qq-bridge.md`):dot、记忆、幕间、面板本来就只认她自己的会话,没有冲突;冲突在三处——我们注册的全局工具会进它的会话(白名单拒掉,但每条消息多带几十个工具说明;它私聊模式下 `account` 能把她的 App 密码交出去)、电脑组件会把它的目录共享进虚拟机(重建一次,她的 QQ 掉线)、她和它的机器人在一个群里会互相回复。反过来,它 patch 进 dsh 的三个 MCP server 也会出现在她的会话里。
337
+
338
+ - **新组件 `compat`**(`src/compat/qq-bridge.js`,总是开着,只在找到 qq-bridge 时起作用):顺着 `~/.dsh/plugins/qq-agent-presets` 找到它的 `config.json` / `state/mode.json`;一个 `owner(session)` 回答会话归谁(`dot` / `qqb-sandbox` / `qqb-owner` / `other`),其他组件只问它。
339
+ - **工具可见性**:`agent/created` 里按归属 `tools.restrict({ deny })`(dsh 的 restrict 取交集,和它自己的叠加),`tools/change` 时重算,执行期 guard 兜底。她的工具只在她的会话;手机电脑另给 closed-agent 的管理员私聊;qq-bridge 的工具不进她的会话。工具归类在 `src/tool-prefixes.js`,测试和源码对账。
340
+ - **电脑**:qq-bridge 的目录不共享(命令在虚拟机家目录跑);管理员私聊可选 `host`。
341
+ - **QQ**:自动忽略它的机器人号(从它的 SnowLuma 配置读)+ `qq.ignore`;防互刷熔断(`loopMax` / `loopCooldownMinutes`),对任何机器人有效。
342
+ - **体检**:同号、同群、读不到机器人号。
343
+ - `dot.scope: all` 也不再把 `qqb-*` 当她的。
package/docs/ROADMAP.md CHANGED
@@ -1,4 +1,4 @@
1
- # dsh-dot 总体规划(2026-10-23;「现在在哪」更新于 2026-11-03,v0.12.0)
1
+ # dsh-dot 总体规划(2026-10-23;「现在在哪」更新于 2026-11-08,v0.22.0)
2
2
 
3
3
  ## 一句话
4
4
 
@@ -17,6 +17,7 @@ dot 是一个**在自己手机上过日子的角色**:有自己的手机、账
17
17
  | 她电脑上的 QQ(`qq`) | ✅ NapCat 或 SnowLuma(`/qq backend`),她用手机摄像头扫码登录(`/qq qr`);只认她的号 | 10-30 真机:SnowLuma 连上、`mcp__dot-qq__*` 挂载,她自己扫码登录 |
18
18
  | IM 通道 | ✅ QQ 连上时 dot 的提醒、幕间主动联系、她对你 QQ 消息的回答都走她的 QQ;没连上时退回 dsh-im 官方机器人。SnowLuma 下收发已实测(10-29,22 条进 38 条出);`qq_send` 对陌生人的审批只有单元测试,没有陌生人来过 | 真机 10-29 |
19
19
  | 自动召回(`memory` 的 RAG 层) | ✅ 0.12:每次叫醒前按叫醒她的话从 transcript 取原话注入;本机 bge-small-zh 默认(0.15.2 起换成 multilingual-e5-small;首次用时装库、走 hf-mirror 下模型),SiliconFlow / DashScope 可切,`/dot memory recall …` 一条命令切换 | 公开基准 108 题:74 → 96(0.15.2,真实代码路径,本机 e5);真机未跑 |
20
+ | 和 qq-bridge 共处(`compat`) | ✅ 0.22:认出 qq-bridge,按会话归属藏工具、不共享它的目录、不回它的机器人号、体检查同号/同群;它 closed-agent 的管理员私聊能用她的手机电脑 | 非 dot 会话实测:dot 的 7 个工具藏掉、手机电脑在(11-08);qq-bridge 真机未装 |
20
21
  | "玩"(点赞/评论/关注) | ✅ 代码在(playIntent → 正常轮次,Moltbook 守则),11-02 起默认开、内置 App 表按手机上装的收窄;发帖/私信不做 | 真机 0 次(之前默认关) |
21
22
 
22
23
  ## 架构(不再变的部分)
package/docs/SETTINGS.md CHANGED
@@ -26,7 +26,7 @@ dsh-dot 的所有个人设置都写在**一个文件**里:
26
26
  **给 agent 的规则**(dsh、Claude、Codex 等改这个文件时照做):
27
27
 
28
28
  1. 先读现有文件;不存在就新建 `{}`。只增改相关的键,**不要删别的段和键**。
29
- 2. 顶层按组件分段:`phone`、`computer`、`gate`、`qq`、`memory`、`interlude`、`dot`。键名和类型照下面的表,不要发明新键。
29
+ 2. 顶层按组件分段:`phone`、`computer`、`gate`、`qq`、`memory`、`interlude`、`dot`、`compat`。键名和类型照下面的表,不要发明新键。
30
30
  3. 写合法 JSON(不能有注释、尾逗号)。想留说明就用 `_` 开头的键,如 `"_note": "..."`,会被忽略。
31
31
  4. 下文标 **🔒 建立时** 的项只对新建的手机 / 虚拟机生效,改之前先告诉用户要重建、会丢什么,得到同意再动。
32
32
  5. 有专门命令的(`/phone size`、`/dot memory recall …`、`/qq owner` 等),优先告诉用户用命令,命令不用重启。
@@ -157,6 +157,9 @@ setx DSH_DOT_COMPUTER off
157
157
  | `typingMsPerChar` | `60` | 分条发送的打字停顿,0 一次发完 |
158
158
  | `tidy` | `true` | 去掉句号、引号、破折号等书面符号 |
159
159
  | `dropLatinLeaks` | `true` | 不发整条都是英文的气泡(思考漏出来),短英文照发 |
160
+ | `ignore` | `""` | 不回复的 QQ 号(别的机器人),逗号或空格分开;qq-bridge 的机器人号自动认出,不用填 |
161
+ | `loopMax` | `4` | 防互刷(只管群聊):一个群里和同一个号一来一回这么多轮、中间没别人说话,就暂停理它;0 关 |
162
+ | `loopCooldownMinutes` | `10` | 防互刷暂停多久 |
160
163
 
161
164
  ### `memory`
162
165
 
@@ -228,6 +231,17 @@ setx DSH_DOT_COMPUTER off
228
231
  | `approvalWaitMs` | `600000` | 她的会话里要审批时立刻告诉你(QQ 连着发 QQ,否则 IM;一轮只发第一条,后面的只计数);这么久没人点就当拒绝,再告诉你一句过期了;0 = 一直等 |
229
232
  | `imBot` / `imTarget` | `""` | dsh-im 的投递目标,空 = 第一个 |
230
233
 
234
+ ### `compat`(和 qq-bridge 共处,见 [qq-bridge.md](qq-bridge.md))
235
+
236
+ | 键 | 默认 | 作用 |
237
+ |---|---|---|
238
+ | `qqBridge` | `"auto"` | `auto` 装了 qq-bridge 就认 / `true` / `false` |
239
+ | `qqBridgeRoot` | `""` | 自动找不到时填它的目录 |
240
+ | `ownerDevices` | `true` | qq-bridge closed-agent 模式的管理员私聊能用她的手机和电脑 |
241
+ | `ownerComputer` | `"vm"` | 那个私聊里的命令:`vm` 她的电脑(不共享它的目录)/ `host` 本机 |
242
+ | `hideBridgeTools` | `true` | 她的会话里不出现 qq-bridge 的 MCP 工具 |
243
+ | `refreshMs` | `5000` | 多久重读一次它的配置 |
244
+
231
245
  ## 优先级和旧文件
232
246
 
233
247
  从弱到强:组件默认值 → 旧的单组件文件(`~/.dsh/dsh-phone.json`、`dsh-computer.json`、`dsh-qq.json`)→ 插件自带的 `cordis.patch.yml` → **`dsh-dot.json`** → 命令设的值(`/phone size`、`/phone accept`、`/phone number`、`/dot memory recall …` 写进 `dsh-phone.json` / `dsh-memory.json`)。
@@ -0,0 +1,77 @@
1
+ # 和 qq-bridge 一起用
2
+
3
+ [qq-bridge](https://github.com/Derpyu520/qq-bridge) 是把 QQ 群接进 dsh 的桥:它自己跑一个进程,用 dsh 的 web API 建会话、收发消息。很多人先装了它,再想要 dsh-dot 的**手机和虚拟机**。这一页说两边怎么共处——全部改动在 dsh-dot 这边,qq-bridge 一个字节不用动。
4
+
5
+ ## 结论先说
6
+
7
+ | 你要的 | 做法 |
8
+ |---|---|
9
+ | qq-bridge 照常跑,她的组件一个都别碰它 | 什么都不用设。装了 qq-bridge 就自动认出(`compat.qqBridge: auto`):它的会话里不会出现 dot 的任何工具,它的目录不会被共享进她的虚拟机,它的机器人号她不回 |
10
+ | **只要手机和虚拟机,给 qq-bridge 的管理员私聊用** | qq-bridge 切到 **closed-agent 模式**(它的控制台或 `state/mode.json`)。这个模式下只有管理员私聊能建会话,用的是 dsh 默认 preset、全工具面;dsh-dot 把她的手机(`mcp__dot-phone__*`)和电脑(`mcp__dot-vm__*`、`bash` 进虚拟机)给这个会话,其他的(记忆、她的 QQ、账号库)不给。dot / 记忆 / 幕间 / QQ 组件可以在 dsh 插件页关掉,只留 phone + computer |
11
+ | 她和 qq-bridge 的机器人在同一个群 | 她自动不回它(号从它的 SnowLuma 配置里读);它会不会回她看它自己的黑名单(`deny.private` / `deny.groups`)。`/dot doctor` 会列出共同的群 |
12
+
13
+ ## 它在 dsh 里长什么样
14
+
15
+ - 会话 ID `qqb-g-<群号>-<随机>`(群)/ `qqb-p-<QQ号>-<随机>`(私聊);所有会话共用一个工作目录(它的 `state/agents`,或 `sessionCwd`);黑话学习会话在 `state/slang-agent`。
16
+ - 模式 `chat` / `reserved` / `reserved2`:会话挂它自己的 `qq-chat` / `qq-chat-v2` preset——工具白名单,`bash`、`read` 等本地工具在注册期就被藏掉。**私聊也一样**,所以这些模式下给它手机也用不了(会被它自己拒绝),dsh-dot 一律当沙箱会话处理。
17
+ - 模式 `closed-agent`:只有 `ownerQQ` 的私聊能建会话,dsh 默认 preset,全工具面。
18
+ - 它往 dsh 的 profile 里 patch 了三个全局 MCP server:`snowluma`、`snowluma-host`、`web-search-safe`——这些工具本来会出现在**她的**会话里。
19
+ - `~/.dsh/plugins/qq-agent-presets` 和 `qq-mode-console` 是指向它仓库的链接:dsh-dot 顺着找到它的 `config.json` 和 `state/`。
20
+
21
+ ## dsh-dot 做了什么(`compat` 组件,`src/compat/qq-bridge.js`)
22
+
23
+ **1. 每个会话归谁。** 一个函数回答,别的组件只问它:
24
+
25
+ | 判定 | 条件 |
26
+ |---|---|
27
+ | `dot` | 她的:工作目录在 `~/dot` 下,或 dsh-im 开的会话,或她的跑腿 |
28
+ | `qqb-sandbox` | `qqb-g-*`;`qqb-p-*` 且会话 preset 是 `qq-chat*`(dsh 记在会话头里;没记的看它的 `state/mode.json`,不是 closed-agent 就算沙箱);工作目录在它 `state/` 下的其他会话 |
29
+ | `qqb-owner` | `qqb-p-*` 且 preset 不是 `qq-chat*`(或模式是 closed-agent) |
30
+ | `other` | 其他所有会话 |
31
+
32
+ `qqb-*` 会话**永远不是她的**,哪怕 `dot.scope` 设成 `all`。
33
+
34
+ **2. 工具可见性。** dsh 的 `agent/created` 事件里按归属 `tools.restrict({ deny })`,全局工具集变了(她的虚拟机起来、手机挂上)就重算;另加一个执行期 guard 兜底。dsh 的 restrict 是**取交集**,和 qq-bridge 自己的 restrict 叠加、互不覆盖。
35
+
36
+ | 会话 | 藏掉 |
37
+ |---|---|
38
+ | `dot` | qq-bridge 的 `mcp__snowluma__*`、`mcp__snowluma-host__*`、`mcp__web-search-safe__*`(`compat.hideBridgeTools`) |
39
+ | `qqb-sandbox` | dsh-dot 的全部:`memory` `recall` `account` `doings` `tell_him` `qq_send` `qq_sticker_keep` `phone_zoom`、`mcp__dot-phone__*`、`mcp__dot-vm__*`、`mcp__dot-qq__*` |
40
+ | `qqb-owner` | 她自己的:`memory` `recall` `account` `doings` `tell_him` `qq_send` `qq_sticker_keep`、`mcp__dot-qq__*`;手机和电脑给(`compat.ownerDevices`) |
41
+ | `other` | 她自己的那些(`account` 里存着她 App 的密码,不给任何第三方会话);手机电脑照旧 |
42
+
43
+ 名单在 `src/tool-prefixes.js`(`DOT_TOOLS` / `DEVICE_TOOL_PREFIXES`),测试会把它和源码里所有 `tools.register` 对账,加工具忘了归类会直接红。
44
+
45
+ **3. 电脑。** subprocess provider 只看得到命令的 cwd:
46
+
47
+ - qq-bridge 的目录**永远不共享进虚拟机**(共享要重建虚拟机,她虚拟机里的 QQ 会掉一次线;它 `state/` 下的东西也不该进去)。命令在虚拟机的家目录跑。
48
+ - closed-agent 模式下那个目录就是管理员私聊的:`compat.ownerComputer: vm`(默认)进她的电脑;`host` 走 dsh 自带的本机执行,相当于没装 dsh-dot。
49
+ - 审批不动:它自己会把 `approval/requested` 转到 QQ。
50
+
51
+ **4. QQ。** 她的 QQ 组件:
52
+
53
+ - 自动忽略 qq-bridge 的机器人号(从它 `config.json` 的 `snowluma.homeDir`(或 `SNOWLUMA_HOME`)下的 `config/onebot_<号>.json` 读;读不到体检会提示);`qq.ignore` 手动加别的号。被忽略的消息不叫醒她、不打分、不记忆。管理员(`qq.owner`)永远不忽略。
54
+ - 防互刷熔断:一个聊天里和同一个号一来一回 `qq.loopMax`(默认 4)轮、中间没别人说话,她就 `qq.loopCooldownMinutes`(默认 10)分钟不理那个号。不依赖 qq-bridge,对任何机器人有效。记 `loop-break`。
55
+ - `/qq` 状态里有一行 `not answered: …`。
56
+
57
+ **5. 体检。** `/dot doctor` / `/phone doctor` / dot 页面:找到 qq-bridge 时列出它的目录、模式、机器人号;❌ 她的号和它的机器人号相同(互相挤下线)、她的号是它的 `ownerQQ`;⚠️ 读不到它的机器人号、两边在同一个群。
58
+
59
+ ## 设置(`~/.dsh/dsh-dot.json` 的 `compat` 段)
60
+
61
+ | 键 | 默认 | 作用 |
62
+ |---|---|---|
63
+ | `qqBridge` | `"auto"` | `auto` 装了就认;`true` 没找到会提示;`false` 不管它(`DSH_DOT_COMPAT=off` 整个组件关掉) |
64
+ | `qqBridgeRoot` | `""` | 自动找不到时填它的目录(里面有 `config.json`) |
65
+ | `ownerDevices` | `true` | closed-agent 的管理员私聊能用她的手机和电脑 |
66
+ | `ownerComputer` | `"vm"` | 那个私聊里的命令在哪跑:`vm` 她的电脑(不共享它的目录)/ `host` 本机 |
67
+ | `hideBridgeTools` | `true` | 她的会话里不出现 qq-bridge 的 MCP 工具 |
68
+ | `refreshMs` | `5000` | 多久重读一次它的 `config.json` / `mode.json` |
69
+
70
+ `qq` 段新增:`ignore`(不回的号,逗号分开)、`loopMax`、`loopCooldownMinutes`(防互刷只管群聊,私聊不限)。
71
+
72
+ ## 没做的
73
+
74
+ - **SnowLuma 的部署**:qq-bridge 只连接用户自己装好的 SnowLuma;dsh-dot 的 `/qq install snowluma` 会在虚拟机里自动装(许可证问题另议)。两边各装各的互不影响,但**不要登录同一个号**。
75
+ - 不改 qq-bridge 的任何文件;要不要在它那边把她的号拉黑,由用户决定。
76
+ - 没有 `config.json` 的 qq-bridge 目录不算装了(它自己也不启动)。
77
+ - 关掉 dot 组件时,dsh-dot 只是手机和虚拟机的通道:qq 组件也应一起关掉(她的 QQ 工具只给她的会话,没有 dot 就没有她的会话)。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-dot-life",
3
- "version": "0.21.1",
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.",
3
+ "version": "0.22.1",
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, seven components; lives next to qq-bridge.",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-only",
7
7
  "keywords": [
@@ -24,7 +24,8 @@
24
24
  "hds-interlude",
25
25
  "persona",
26
26
  "microvm",
27
- "microsandbox"
27
+ "microsandbox",
28
+ "qq-bridge"
28
29
  ],
29
30
  "repository": {
30
31
  "type": "git",
@@ -32,7 +33,7 @@
32
33
  },
33
34
  "homepage": "https://github.com/Kevinwu901113/dsh-dot#readme",
34
35
  "exports": {
35
- ".": "./src/computer/ui-host.js",
36
+ ".": "./src/page/host.js",
36
37
  "./client": "./lib/client.js",
37
38
  "./computer": "./src/computer/vm.js",
38
39
  "./vm": "./src/computer/vm.js",
@@ -44,7 +45,8 @@
44
45
  "./interlude": "./src/interlude/core.js",
45
46
  "./memory": "./src/memory/memory.js",
46
47
  "./phone": "./src/phone/phone.js",
47
- "./qq": "./src/qq/qq.js"
48
+ "./qq": "./src/qq/qq.js",
49
+ "./compat": "./src/compat/qq-bridge.js"
48
50
  },
49
51
  "files": [
50
52
  "src",
@@ -0,0 +1,286 @@
1
+ // dsh-dot/compat: living next to qq-bridge (github.com/Derpyu520/qq-bridge) in the same dsh.
2
+ //
3
+ // qq-bridge is a separate process that drives dsh over its web API. From dsh's side it looks like:
4
+ // · sessions whose id is `qqb-g-<group>-<hex>` (a group) or `qqb-p-<uin>-<hex>` (a private chat),
5
+ // all in one cwd — its `sessionCwd`, else `<repo>/state/agents`; its slang learner lives in
6
+ // `<repo>/state/slang-agent` with a dsh-generated id;
7
+ // · a mode (its `state/mode.json`): chat / reserved / reserved2 run its own `qq-chat*` presets
8
+ // (a tool whitelist, no local tools: bash, read … are restricted away); `closed-agent` is the
9
+ // owner's private chat only, on the dsh default preset with the full tool surface;
10
+ // · three global MCP servers it patches into the profile: `snowluma`, `snowluma-host`,
11
+ // `web-search-safe` (so `mcp__snowluma__*` is in every session's tool list — hers included);
12
+ // · two bundles linked at `~/.dsh/plugins/qq-agent-presets` and `~/.dsh/plugins/qq-mode-console`
13
+ // — the link target is the repo, which is how this module finds its config.json and state/.
14
+ //
15
+ // What this component does, all of it on our side (qq-bridge is never modified):
16
+ // 1. `owner(session)`: whose session is this — hers ('dot'), a qq-bridge chat on a whitelist preset
17
+ // ('qqb-sandbox'), the qq-bridge owner's full private chat ('qqb-owner'), or anybody else ('other').
18
+ // Every other component asks here instead of guessing.
19
+ // 2. Tool visibility, one `agent/created` hook: dot's own tools (memory, recall, account, qq_send …)
20
+ // only in her sessions; her phone and computer tools only in hers and in qq-bridge's owner chat
21
+ // (which is what a qq-bridge user wants from this plugin); nothing of ours in a sandboxed
22
+ // qq-bridge session (its whitelist would refuse them anyway, but they cost tokens on every message
23
+ // and break its "no local capability in the schema" rule). qq-bridge's own MCP tools are hidden
24
+ // from her sessions in return. Backed by a guard so the restriction holds even for a tool
25
+ // registered after the agent was created.
26
+ // 3. The computer: a qq-bridge session's cwd (its state/ dir) is never shared into her VM (sharing
27
+ // restarts the VM: her QQ inside it would drop); its commands run in the VM's own home, or on
28
+ // the host when `computer: 'host'` is chosen.
29
+ // 4. QQ: the bridge's bot accounts are read from its SnowLuma home (config/onebot_<uin>.json) so
30
+ // she never answers them (two bots in one group would otherwise talk forever); `/dot doctor`
31
+ // checks the two are not the same account and not in the same groups.
32
+ //
33
+ // Settings (~/.dsh/dsh-dot.json, section "compat"): see `defaults`.
34
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
37
+ import { sectionOf, dshHome } from '../settings.js';
38
+ import { DOT_TOOLS, DOT_TOOL_PREFIXES, DEVICE_TOOL_PREFIXES, PHONE_ZOOM_TOOL } from '../tool-prefixes.js';
39
+
40
+ export const name = 'dsh-dot/compat';
41
+ export const inject = [];
42
+
43
+ export const defaults = {
44
+ // Looking for qq-bridge: 'auto' (on when its bundles are linked into ~/.dsh), true, false.
45
+ qqBridge: 'auto',
46
+ // Where qq-bridge is checked out, when auto-detection cannot see it (the folder with config.json).
47
+ qqBridgeRoot: '',
48
+ // qq-bridge's owner private chat (its closed-agent mode): give it her phone and computer tools?
49
+ ownerDevices: true,
50
+ // Where a qq-bridge owner-chat command runs: 'vm' (her computer, in the VM's home; nothing of
51
+ // qq-bridge's is shared in) or 'host' (dsh's own local runner, as without this plugin).
52
+ ownerComputer: 'vm',
53
+ // Hide qq-bridge's MCP tools (mcp__snowluma__*, mcp__snowluma-host__*, mcp__web-search-safe__*) from her sessions.
54
+ hideBridgeTools: true,
55
+ // Reread qq-bridge's config.json / state/mode.json at most this often (ms).
56
+ refreshMs: 5000,
57
+ };
58
+
59
+ /** qq-bridge's session ids: `qqb-g-<group>-<hex>` / `qqb-p-<uin>-<hex>` (its encodeSelfKey). */
60
+ export const BRIDGE_ID_RE = /^qqb-([gp])-(\d{1,20})(?:-[a-f0-9]{32})?$/;
61
+ /** The MCP servers qq-bridge patches into the dsh profile (its scripts/setup-dsh.mjs). */
62
+ export const BRIDGE_TOOL_PREFIXES = ['mcp__snowluma__', 'mcp__snowluma-host__', 'mcp__web-search-safe__'];
63
+ /** The bundles it links into ~/.dsh/plugins (name → link); the link target is inside its repo. */
64
+ const BRIDGE_BUNDLES = ['qq-agent-presets', 'qq-mode-console'];
65
+
66
+ const inside = (parent, p) => { if (!parent || !p) return false; const r = relative(parent, p); return r === '' || (!r.startsWith('..') && !isAbsolute(r)); };
67
+ const readJson = (file) => { try { return JSON.parse(readFileSync(file, 'utf8')); } catch { return null; } };
68
+ const mtime = (file) => { try { return statSync(file).mtimeMs; } catch { return 0; } };
69
+
70
+ /**
71
+ * Where qq-bridge is: the explicit root, else the repo behind `~/.dsh/plugins/qq-agent-presets`
72
+ * or `qq-mode-console` (links into its checkout). A checkout without `config.json` is not a running
73
+ * qq-bridge (its own loadConfig() refuses to start without one), so it does not count: ''.
74
+ */
75
+ export function findRoot({ root = '', home = dshHome() } = {}) {
76
+ const configured = (dir) => existsSync(join(dir, 'config.json'));
77
+ if (root) return configured(root) ? resolve(root) : '';
78
+ for (const bundle of BRIDGE_BUNDLES) {
79
+ let target;
80
+ try { target = realpathSync(join(home, 'plugins', bundle)); } catch { continue; }
81
+ // <repo>/plugins/<bundle> or a build dir inside the repo → walk up to the repo root.
82
+ for (let dir = target; dir !== dirname(dir); dir = dirname(dir)) {
83
+ if (existsSync(join(dir, 'src', 'bridge.js')) && existsSync(join(dir, 'package.json'))) return configured(dir) ? dir : '';
84
+ }
85
+ }
86
+ return '';
87
+ }
88
+
89
+ /** qq-bridge's bot accounts: SnowLuma's per-account files `config/onebot_<uin>.json` (its snowluma-conn.js). */
90
+ export function botUins(config, env = process.env) {
91
+ const homes = [];
92
+ const sl = config?.snowluma ?? {};
93
+ if (sl.homeDir) homes.push(String(sl.homeDir));
94
+ if (sl.launcherPath) homes.push(dirname(String(sl.launcherPath)));
95
+ if (env.SNOWLUMA_HOME) homes.push(env.SNOWLUMA_HOME);
96
+ const uins = new Set();
97
+ for (const h of homes) {
98
+ let entries = [];
99
+ try { entries = readdirSync(join(h.replace(/^~(?=$|[\\/])/, homedir()), 'config')); } catch { continue; }
100
+ for (const e of entries) { const m = /^onebot_(\d+)\.json$/i.exec(e); if (m) uins.add(m[1]); }
101
+ }
102
+ return [...uins].sort();
103
+ }
104
+
105
+ /**
106
+ * Everything of qq-bridge's this plugin looks at, read from its files (never its network):
107
+ * { root, configPath, config, stateDir, sessionCwd, slangCwd, mode, ownerQQ, groups, privates, botUins, consolePort, sandboxPresets }.
108
+ */
109
+ export function readBridge(root, env = process.env) {
110
+ const configPath = join(root, 'config.json');
111
+ const config = readJson(configPath) ?? {};
112
+ const stateDir = join(root, 'state');
113
+ const modeFile = readJson(join(stateDir, 'mode.json'));
114
+ const mode = String(modeFile?.mode ?? config.mode ?? 'reserved2').trim() || 'reserved2';
115
+ const allow = config.allow ?? {};
116
+ const list = (v) => (Array.isArray(v) ? v.map((x) => String(x)).filter(Boolean) : []);
117
+ return {
118
+ root, configPath, config, stateDir,
119
+ sessionCwd: config.sessionCwd ? resolve(String(config.sessionCwd)) : join(stateDir, 'agents'),
120
+ slangCwd: join(stateDir, 'slang-agent'),
121
+ mode: mode === 'simulation' ? 'reserved2' : mode,
122
+ ownerQQ: config.ownerQQ == null ? '' : String(config.ownerQQ),
123
+ groups: list(allow.groups ?? allow.group),
124
+ privates: list(allow.private ?? allow.privates),
125
+ botUins: botUins(config, env),
126
+ consolePort: Number(config.consolePort) || 3100,
127
+ // The whitelist presets its chat modes run on (its PRESET_NAMES: qq-chat / qq-chat-v2), as configured.
128
+ sandboxPresets: [...new Set([config.agentPreset, config.socialV2?.agentPreset, 'qq-chat', 'qq-chat-v2'].map((x) => String(x ?? '').trim()).filter(Boolean))],
129
+ stamp: `${mtime(configPath)}:${mtime(join(stateDir, 'mode.json'))}`,
130
+ };
131
+ }
132
+
133
+ /**
134
+ * Whose session is this. `hers(id, cwd)` is dot's own test (ctx.dshDot.hers) when the dot
135
+ * component is on. Returns 'dot' | 'qqb-sandbox' | 'qqb-owner' | 'other'.
136
+ * qqb-owner: qq-bridge in closed-agent mode, the id is a private chat (`qqb-p-`) — the owner's
137
+ * full-tool session (only the owner gets a session in that mode).
138
+ * qqb-sandbox: any other qq-bridge session: a group, a whitelisted private chat on a qq-chat
139
+ * preset, or its slang learner (dsh id, cwd under its state/).
140
+ */
141
+ export function classify({ id = '', cwd = '', preset } = {}, bridge, hers) {
142
+ const m = BRIDGE_ID_RE.exec(String(id));
143
+ if (!m && hers?.(id, cwd)) return 'dot';
144
+ if (m) {
145
+ if (m[1] !== 'p') return 'qqb-sandbox';
146
+ // The session's preset is the truth when dsh records it: one of the bridge's chat presets (read from
147
+ // its config; `qq-chat*` by name when the bridge is not readable) is the whitelist, anything else
148
+ // is the owner's full chat. The bridge's mode file stands in for an older dsh that records none.
149
+ if (preset !== undefined && preset !== null && preset !== '') {
150
+ const p = String(preset);
151
+ return (bridge?.sandboxPresets ?? ['qq-chat', 'qq-chat-v2']).includes(p) || /^qq-chat/.test(p) ? 'qqb-sandbox' : 'qqb-owner';
152
+ }
153
+ return bridge?.mode === 'closed-agent' ? 'qqb-owner' : 'qqb-sandbox';
154
+ }
155
+ if (!bridge) return 'other';
156
+ // By cwd alone (the subprocess provider sees nothing else): every qq-bridge session lives in one
157
+ // folder. In closed-agent mode only the owner's chat gets a session at all (groups are refused, and
158
+ // a sandbox session has no shell to run anything with), so that folder is the owner's then.
159
+ if (cwd && (inside(bridge.stateDir, cwd) || inside(bridge.sessionCwd, cwd) || inside(bridge.slangCwd, cwd))) return bridge.mode === 'closed-agent' && !inside(bridge.slangCwd, cwd) ? 'qqb-owner' : 'qqb-sandbox';
160
+ return 'other';
161
+ }
162
+
163
+ /** Is this tool one of dot's own (hers to use, nobody else's): memory, account, qq_send, her SnowLuma actions …? */
164
+ export const isDotTool = (n) => DOT_TOOLS.includes(n) || DOT_TOOL_PREFIXES.some((p) => n.startsWith(p));
165
+ /** Is this tool her phone's or her computer's (mcp__dot-phone__*, mcp__dot-vm__*, phone_zoom)? */
166
+ export const isDeviceTool = (n) => n === PHONE_ZOOM_TOOL || DEVICE_TOOL_PREFIXES.some((p) => n.startsWith(p));
167
+ /** Is this tool qq-bridge's? */
168
+ export const isBridgeTool = (n) => BRIDGE_TOOL_PREFIXES.some((p) => n.startsWith(p));
169
+
170
+ /**
171
+ * Which of `names` (the global tool list) a session of this owner must not see.
172
+ * @param owner - from classify()
173
+ * @param opts.ownerDevices - whether qq-bridge's owner chat gets the device tools
174
+ * @param opts.hideBridgeTools - whether her sessions lose qq-bridge's MCP tools
175
+ */
176
+ export function hiddenFor(owner, names, { ownerDevices = true, hideBridgeTools = true } = {}) {
177
+ const out = [];
178
+ for (const n of names) {
179
+ if (owner === 'dot') { if (hideBridgeTools && isBridgeTool(n)) out.push(n); continue; }
180
+ if (isDotTool(n)) { out.push(n); continue; }
181
+ if (isDeviceTool(n) && (owner === 'qqb-sandbox' || (owner === 'qqb-owner' && !ownerDevices))) out.push(n);
182
+ }
183
+ return out;
184
+ }
185
+
186
+ /**
187
+ * The compat service, `ctx.dshDotCompat`:
188
+ * bridge() → the qq-bridge facts (readBridge) or null when it is not here / turned off
189
+ * owner(id, cwd, preset) → 'dot' | 'qqb-sandbox' | 'qqb-owner' | 'other' (preset: session.header.agentPreset)
190
+ * ownerOf(c) → the same, for a system-prompt context `c` (c.agent.session)
191
+ * ownerOfCwd(cwd) → the same, from the cwd alone (what the subprocess provider sees)
192
+ * ignoredUins() → qq-bridge's bot accounts (strings)
193
+ * ownerComputer → 'vm' | 'host' (where a qqb-owner command runs)
194
+ * doctor() → Promise<[{ name, level, detail, fix }]> for /dot doctor
195
+ */
196
+ export function apply(ctx, config = {}) {
197
+ const logger = ctx.logger('dsh-dot/compat');
198
+ const cfg = { ...defaults, ...config, ...sectionOf('compat', (m) => logger.warn(m)) };
199
+ const hers = (id, cwd) => { try { return Boolean(ctx.get('dshDot')?.hers?.(id, cwd)); } catch { return false; } };
200
+
201
+ let cached = null, cachedAt = 0, root = '', announced = false;
202
+ const bridge = () => {
203
+ if (cfg.qqBridge === false) return null;
204
+ const now = Date.now();
205
+ if (cached !== null && now - cachedAt < cfg.refreshMs) return cached || null;
206
+ cachedAt = now;
207
+ root ||= findRoot({ root: cfg.qqBridgeRoot });
208
+ if (!root) { if (cfg.qqBridge === true && !announced) { announced = true; logger.warn('compat.qqBridge is on but qq-bridge was not found: set compat.qqBridgeRoot to its folder'); } cached = false; return null; }
209
+ const next = readBridge(root);
210
+ if (!cached || cached.stamp !== next.stamp) {
211
+ cached = next;
212
+ if (!announced) { announced = true; logger.info(`qq-bridge found at ${root}: mode ${next.mode}, bot ${next.botUins.join('/') || '(none seen)'}, owner ${next.ownerQQ || '(unset)'}, ${next.groups.length} group(s)`); }
213
+ }
214
+ return cached;
215
+ };
216
+ const owner = (id, cwd, preset) => classify({ id, cwd, preset }, bridge(), hers);
217
+ const ownerOfCwd = (cwd) => classify({ cwd }, bridge(), (i, c) => hers('', c));
218
+
219
+ /** Whose session is the one a system-prompt `text: (c) => …` is being built for. */
220
+ const ownerOf = (c) => { const s = c?.agent?.session; return owner(s?.id ?? '', s?.header?.cwd ?? '', s?.header?.agentPreset); };
221
+ const api = {
222
+ bridge, owner, ownerOf, ownerOfCwd,
223
+ ignoredUins: () => bridge()?.botUins ?? [],
224
+ get ownerComputer() { return cfg.ownerComputer === 'host' ? 'host' : 'vm'; },
225
+ hiddenFor: (o, names) => hiddenFor(o, names, cfg),
226
+ doctor: async () => {
227
+ let qq; try { qq = ctx.get('dshQq'); } catch { qq = undefined; }
228
+ let groups = null;
229
+ if (qq?.connected && qq.groups) { try { groups = (await qq.groups()).map((g) => g.gid); } catch (err) { logger.debug(`group list: ${err.message}`); } }
230
+ return doctor({ bridge: bridge(), qq, groupsOf: groups ? () => groups : undefined });
231
+ },
232
+ settings: () => ({ ...cfg }),
233
+ };
234
+ ctx.provide?.('dshDotCompat', api);
235
+
236
+ // ── tool visibility: one restriction per agent, recomputed when the global tool set changes ──
237
+ ctx.inject(['tools'], (scope) => {
238
+ const live = new Map(); // agent id → { agent, dispose, owner }
239
+ const names = () => { try { return scope.tools.schemas().map((s) => s.name); } catch { return []; } };
240
+ const applyTo = (entry) => {
241
+ const hidden = api.hiddenFor(entry.owner, names());
242
+ const key = hidden.join('\n');
243
+ if (key === entry.key) return;
244
+ try { entry.dispose?.(); } catch {}
245
+ entry.dispose = null; entry.key = key;
246
+ if (!hidden.length) return;
247
+ try { entry.dispose = entry.agent.ctx.tools.restrict({ deny: hidden }); } catch (err) { logger.warn(`restrict ${entry.agent.id}: ${err.message}`); return; }
248
+ logger.debug(`${entry.agent.id} (${entry.owner}): ${hidden.length} tool(s) hidden`);
249
+ };
250
+ scope.effect(() => scope.on('agent/created', ({ agent }) => {
251
+ const s = agent?.session;
252
+ if (!agent?.id || !agent.ctx?.tools) return;
253
+ const o = owner(agent.id, s?.header?.cwd, s?.header?.agentPreset);
254
+ const entry = { agent, owner: o, dispose: null, key: undefined };
255
+ live.set(agent.id, entry);
256
+ applyTo(entry);
257
+ // The guard outlives any restriction gap (a tool registered later, a failed restrict): a tool
258
+ // this session must not see is not run from it either.
259
+ try {
260
+ agent.ctx.tools.guard?.((exec) => (api.hiddenFor(o, [exec.name]).length ? `dsh-dot: ${exec.name} is not available in this session (${o})` : undefined));
261
+ } catch (err) { logger.warn(`guard ${agent.id}: ${err.message}`); }
262
+ }), 'dsh-dot/compat: per-session tool visibility');
263
+ scope.effect(() => scope.on('agent/disposed', ({ agent }) => { const e = live.get(agent?.id); if (e) { try { e.dispose?.(); } catch {} live.delete(agent.id); } }), 'dsh-dot/compat: forget disposed agents');
264
+ scope.effect(() => scope.on('tools/change', () => { for (const e of live.values()) applyTo(e); }), 'dsh-dot/compat: re-apply on tool changes');
265
+ });
266
+
267
+ logger.info(`compat ready — qq-bridge: ${cfg.qqBridge === false ? 'off' : bridge() ? 'found' : 'not found'}`);
268
+ return api;
269
+ }
270
+
271
+ /** The /dot doctor items about living next to qq-bridge. `qq` is ctx.dshQq (her QQ) when on. */
272
+ export function doctor({ bridge, qq, groupsOf } = {}) {
273
+ if (!bridge) return [];
274
+ const items = [];
275
+ const item = (name, level, detail, fix = '') => items.push({ name, level, detail, fix });
276
+ const hers = qq?.selfId || qq?.qq || '';
277
+ item('qq-bridge', 'ok', `在 ${bridge.root},模式 ${bridge.mode}${bridge.botUins.length ? `,机器人 ${bridge.botUins.join('/')}` : ''};它的会话里不会出现 dot 的工具${bridge.mode === 'closed-agent' ? ',主人私聊会话能用她的手机和电脑' : ''}`);
278
+ if (!bridge.botUins.length) item('qq-bridge 机器人号', 'warn', '没读到 qq-bridge 的机器人号(它的 config.json 没填 snowluma.homeDir,SNOWLUMA_HOME 也没设)', '在 qq-bridge 的 config.json 里填 snowluma.homeDir,或在 dsh-dot.json 的 qq.ignore 里手动写上它的号;不然两个机器人在同一个群里会互相回复');
279
+ if (hers && bridge.botUins.includes(String(hers))) item('QQ 账号', 'bad', `她的 QQ ${hers} 也是 qq-bridge 的机器人号:两边会互相把对方挤下线`, '给她另一个 QQ 号(/qq account <号>),qq-bridge 保留现在这个');
280
+ if (hers && bridge.ownerQQ && String(hers) === bridge.ownerQQ) item('QQ 账号', 'bad', `她的 QQ ${hers} 是 qq-bridge 的管理员号(ownerQQ)`, '她不能用你的号;/qq account 换成她自己的');
281
+ if (groupsOf && bridge.groups.length) {
282
+ const shared = groupsOf().filter((g) => bridge.groups.includes(String(g)));
283
+ if (shared.length) item('共同的群', 'warn', `她和 qq-bridge 的机器人都在:${shared.join('、')};她不回它的消息,但它会回她的`, `想让两边都安静:在 qq-bridge 那边把她的号 ${hers || ''} 拉黑(它的 config.json 有 deny.private / deny.groups 黑名单,按它的文档填),或别让两个号进同一个群`);
284
+ }
285
+ return items;
286
+ }
@@ -5,6 +5,7 @@
5
5
  import { execFile } from 'node:child_process';
6
6
  import { randomUUID } from 'node:crypto';
7
7
  import { existsSync } from 'node:fs';
8
+ import { basename, isAbsolute } from 'node:path';
8
9
  import { promisify } from 'node:util';
9
10
  import { LocalSubprocessRuntime } from '@deepseek-ai/dsh-subprocess-local';
10
11
  import { SubprocessExecutableNotFoundError } from '@deepseek-ai/dsh-subprocess';
@@ -31,16 +32,32 @@ export default class DshComputerSubprocess extends LocalSubprocessRuntime {
31
32
  this.vm = ctx.dshComputer;
32
33
  this.backend = this.vm.backend;
33
34
  this.log = ctx.logger('dsh-computer');
35
+ // Whose command is this (by its cwd): src/compat/qq-bridge.js, when that component is on.
36
+ this.compat = () => { try { return ctx.get?.('dshDotCompat'); } catch { return undefined; } };
34
37
  this.log.info(`subprocess routed into computer "${this.vm.container}" (${this.backend.kind})`);
35
38
  }
36
39
 
40
+ /**
41
+ * Where a command from this cwd goes: 'vm' (hers and everyone else's: into her computer),
42
+ * 'vm-noshare' (a qq-bridge session: into the VM, but its folder is never shared in — sharing
43
+ * re-creates the VM and her QQ inside it would drop, and nothing under qq-bridge's state/ belongs
44
+ * in there), or 'host' (a qq-bridge owner chat with compat.ownerComputer 'host': dsh's own local
45
+ * runner, as if this plugin were not installed).
46
+ */
47
+ routeFor(cwd) {
48
+ const c = this.compat();
49
+ const owner = c?.ownerOfCwd?.(cwd) ?? 'other';
50
+ if (owner === 'qqb-owner' && c.ownerComputer === 'host') return 'host';
51
+ return owner === 'qqb-owner' || owner === 'qqb-sandbox' ? 'vm-noshare' : 'vm';
52
+ }
53
+
37
54
  /**
38
55
  * Map a host cwd into the VM. A workspace that is not shared yet gets shared now (the VM is
39
56
  * re-created with the extra folder; the spawn waits on the remount lock). Folders that may not
40
- * be shared run in the VM home.
57
+ * be shared — or must not be (route 'vm-noshare') — run in the VM home.
41
58
  */
42
- vmCwd(cwd) {
43
- if (!this.vm.isShared(cwd)) this.vm.ensureShared?.(cwd);
59
+ vmCwd(cwd, route = this.routeFor(cwd)) {
60
+ if (route === 'vm' && !this.vm.isShared(cwd)) this.vm.ensureShared?.(cwd);
44
61
  return this.vm.isShared(cwd) ? this.backend.toGuestPath(cwd) : VM_HOME;
45
62
  }
46
63
 
@@ -102,6 +119,7 @@ export default class DshComputerSubprocess extends LocalSubprocessRuntime {
102
119
  }
103
120
 
104
121
  spawn(spec) {
122
+ if (this.routeFor(spec.cwd) === 'host') return this.spawnOnHost(spec);
105
123
  const id = randomUUID();
106
124
  const cwd = this.vmCwd(spec.cwd);
107
125
  this.vm.audit?.({ kind: 'exec', argv: clip(spec.argv.join(' ')), cwd });
@@ -115,9 +133,26 @@ export default class DshComputerSubprocess extends LocalSubprocessRuntime {
115
133
  return handle;
116
134
  }
117
135
 
136
+ /**
137
+ * Route 'host': dsh's own local runner. resolveExecutable() has no cwd to route by, so argv[0]
138
+ * may be the VM's answer (`/bin/bash`); one that does not exist here goes back to its bare name
139
+ * for the host's PATH.
140
+ */
141
+ hostArgv(argv) {
142
+ const [cmd, ...rest] = argv;
143
+ return isAbsolute(cmd) && !existsSync(cmd) ? [basename(cmd), ...rest] : argv;
144
+ }
145
+
146
+ spawnOnHost(spec) {
147
+ this.vm.audit?.({ kind: 'exec-host', argv: clip(spec.argv.join(' ')), cwd: spec.cwd });
148
+ return super.spawn({ ...spec, argv: this.hostArgv(spec.argv) });
149
+ }
150
+
118
151
  async spawnTerminal(spec) {
152
+ const route = this.routeFor(spec.cwd);
153
+ if (route === 'host') return super.spawnTerminal({ ...spec, argv: this.hostArgv(spec.argv) });
119
154
  this.usable();
120
- const shared = this.vm.isShared(spec.cwd) ? null : this.vm.ensureShared?.(spec.cwd);
155
+ const shared = route !== 'vm' || this.vm.isShared(spec.cwd) ? null : this.vm.ensureShared?.(spec.cwd);
121
156
  if (shared) await shared;
122
157
  const argv = this.backend.execArgv({ user: this.vm.user, cwd: this.vmCwd(spec.cwd), env: spec.env, argv: spec.argv, tty: true });
123
158
  this.vm.audit?.({ kind: 'terminal', argv: clip(spec.argv.join(' ')) });
package/src/doctor.js CHANGED
@@ -212,9 +212,12 @@ export function report(items, { onlyProblems = false } = {}) {
212
212
  * Run the doctor against whatever services exist right now (any subset of components):
213
213
  * phone/computer are the dshPhone / dshComputer services or undefined.
214
214
  */
215
- export async function doctorFor({ phone, computer, home }, deps) {
215
+ export async function doctorFor({ phone, computer, compat, home }, deps) {
216
216
  const p = phone?.doctorInfo?.() ?? null;
217
217
  if (p && phone.network && p.running) p.network = await phone.network().catch(() => null);
218
218
  const c = computer?.doctorInfo?.() ?? null;
219
- return diagnose({ phone: p, computer: c, home }, deps);
219
+ const items = await diagnose({ phone: p, computer: c, home }, deps);
220
+ // Living next to qq-bridge (dshDotCompat): its own findings, when it is here.
221
+ try { items.push(...((await compat?.doctor?.()) ?? [])); } catch (err) { items.push({ name: 'qq-bridge', level: 'warn', detail: `检查没跑完:${err.message}`, fix: '' }); }
222
+ return items;
220
223
  }
package/src/dot/core.js CHANGED
@@ -14,6 +14,7 @@
14
14
  // 3. dsh-budget blocks are announced on IM, and the `daily` block is lifted at local midnight;
15
15
  // 4. VM failures are announced on IM; /dot shows the status.
16
16
  import { PHONE_TOOL_PREFIX, PHONE_ZOOM_TOOL, VM_TOOL_PREFIX } from '../tool-prefixes.js';
17
+ import { BRIDGE_ID_RE } from '../compat/qq-bridge.js';
17
18
  import { createManuals, defaultManuals } from './manuals.js';
18
19
  import { batchLaunch, createHowto, howtoTool } from './howto.js';
19
20
  import { KNOWN_APPS, collectReply } from '../interlude/core.js';
@@ -440,7 +441,8 @@ export function apply(ctx, config = {}) {
440
441
  const setLast = (id) => { if (id === lastSession) return; lastSession = id; store.set('lastSession', id); phone()?.setPriority?.(id); };
441
442
  const wantHome = cfg.scope === 'all' || String(cfg.scope).includes('home');
442
443
  const wantIm = cfg.scope === 'all' || String(cfg.scope).includes('im');
443
- const isDotSession = (id, cwd) => cfg.scope === 'all' || (wantHome && cwd && inside(home, cwd)) || (wantIm && imSessions.has(id));
444
+ // qq-bridge's sessions (`qqb-…`, see src/compat/qq-bridge.js) are never hers, whatever the scope says.
445
+ const isDotSession = (id, cwd) => !BRIDGE_ID_RE.test(String(id ?? '')) && (cfg.scope === 'all' || (wantHome && cwd && inside(home, cwd)) || (wantIm && imSessions.has(id)));
444
446
 
445
447
  // Her errand session (see defaults.errands). Created on first use in <home>, remembered across
446
448
  // restarts, archived and replaced once it grows past errandMaxTokens.
@@ -1183,7 +1185,7 @@ export function apply(ctx, config = {}) {
1183
1185
  // something still has to be installed, and when a device fails; problems go to the log and his IM.
1184
1186
  let lastDoctor = null;
1185
1187
  const runDoctor = async () => {
1186
- const items = await doctorFor({ phone: phone(), computer: computer(), home: dshHome() });
1188
+ const items = await doctorFor({ phone: phone(), computer: computer(), compat: ctx.get('dshDotCompat'), home: dshHome() });
1187
1189
  lastDoctor = { at: Date.now(), bad: items.filter((i) => i.level === 'bad').length, warn: items.filter((i) => i.level === 'warn').length };
1188
1190
  audit('doctor', { bad: lastDoctor.bad, warn: lastDoctor.warn, problems: items.filter((i) => i.level !== 'ok').map((i) => i.name) });
1189
1191
  return items;
@@ -1312,6 +1314,8 @@ export function apply(ctx, config = {}) {
1312
1314
  say: (text) => noteToConversation('say', text, prompt('dot.interlude-say', { text: String(text).trim() })),
1313
1315
  stats,
1314
1316
  isErrand,
1317
+ /** Is this session hers (her conversation, an IM-opened one, her errand): what compat asks before letting it see her tools. */
1318
+ hers: (id, cwd) => isDotSession(id, cwd) || isErrand(id),
1315
1319
  busy: (id) => turns.has(id),
1316
1320
  /** One open turn as the watchdog sees it (turnState + who and what), or null. */
1317
1321
  turn: (id) => turnInfo(id),
package/src/page/api.js CHANGED
@@ -32,21 +32,20 @@ function writeSetup(patch) {
32
32
 
33
33
  function services(ctx) {
34
34
  const get = (n) => { try { return ctx.get(n); } catch { return undefined; } };
35
- return { phone: get('dshPhone'), computer: get('dshComputer'), qq: get('dshQq'), dot: get('dshDot'), interlude: get('dshInterlude') };
35
+ return { phone: get('dshPhone'), computer: get('dshComputer'), qq: get('dshQq'), dot: get('dshDot'), interlude: get('dshInterlude'), compat: get('dshDotCompat') };
36
36
  }
37
37
 
38
38
  /** Each component's status (null = component off). */
39
39
  export function statusOf(ctx) {
40
40
  const s = services(ctx);
41
41
  const st = (svc) => { try { return svc?.status?.() ?? (svc ? {} : null); } catch (err) { return { state: 'error', error: err.message }; } };
42
- return { phone: st(s.phone), computer: st(s.computer), qq: st(s.qq), dot: s.dot ? { state: 'on' } : null, interlude: s.interlude ? { state: 'on' } : null };
42
+ return { phone: st(s.phone), computer: st(s.computer), qq: st(s.qq), dot: s.dot ? { state: 'on' } : null, interlude: s.interlude ? { state: 'on' } : null, compat: s.compat ? { state: 'on', qqBridge: (() => { try { const b = s.compat.bridge(); return b ? { root: b.root, mode: b.mode, bots: b.botUins } : null; } catch { return null; } })() } : null };
43
43
  }
44
44
 
45
45
  const need = (svc, what) => { if (!svc) throw new Error(`${what}组件没开(在 dsh 的插件页打开)`); return svc; };
46
46
  const ACTIONS = {
47
47
  'phone-rebuild': async ({ phone }, body) => {
48
- if (body?.confirm !== 'dot') throw new Error('要确认:输入 dot');
49
- await need(phone, '手机').rebuild({ gb: body.gb ? Number(body.gb) : undefined });
48
+ await need(phone, '手机').rebuild({ gb: body?.gb ? Number(body.gb) : undefined });
50
49
  return '旧手机已删除,正在新建并开机(几分钟)';
51
50
  },
52
51
  'phone-cleanup': async ({ phone }) => { const b = need(phone, '手机').cleanup(); return `清掉了 ${Math.round(b / 1048576)} MB 下载缓存`; },
@@ -63,9 +62,9 @@ const ACTIONS = {
63
62
  const r = await need(interlude, '幕间').importPreset(String(body?.code ?? '').trim());
64
63
  return `已导入:${r.name}(${r.title},作者 @${r.author},${r.license})`;
65
64
  },
66
- 'phone-accept': async ({ phone }, body) => { if (!phone) throw new Error('手机组件没开'); if (body?.gb) phone.setStorage(String(body.gb)); phone.accept(); return '已接受许可,开始安装'; },
67
- 'phone-restart': async ({ phone }) => { if (!phone) throw new Error('手机组件没开'); await phone.restart(); return '手机重启中'; },
68
- 'phone-retry': async ({ phone }) => { if (!phone) throw new Error('手机组件没开'); await phone.restart(); return '重试中'; },
65
+ 'phone-accept': async ({ phone }, body) => { need(phone, '手机'); if (body?.gb) phone.setStorage(String(body.gb)); phone.accept(); return '已接受许可,开始安装'; },
66
+ 'phone-restart': async ({ phone }) => { await need(phone, '手机').restart(); return '手机重启中'; },
67
+ 'phone-retry': async ({ phone }) => { await need(phone, '手机').restart(); return '重试中'; },
69
68
  };
70
69
 
71
70
  /**
@@ -102,7 +101,7 @@ async function readJson(req, limit = 256 * 1024) {
102
101
 
103
102
  export function createApi(ctx, logger) {
104
103
  const json = (res, status, body) => res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(body));
105
- const doctor = () => { const s = services(ctx); return doctorFor({ phone: s.phone, computer: s.computer, home: dshHome() }); };
104
+ const doctor = () => { const s = services(ctx); return doctorFor({ phone: s.phone, computer: s.computer, compat: s.compat, home: dshHome() }); };
106
105
  const info = () => { const s = services(ctx); const st = statusOf(ctx); return versions({ pluginVersion, dshVersion, phone: s.phone ? { ...st.phone } : null, computer: s.computer ? { ...st.computer, image: s.computer.doctorInfo?.().image, backend: s.computer.doctorInfo?.().backend } : null }); };
107
106
  const dotHome = () => services(ctx).dot?.home || join(homedir(), 'dot');
108
107
 
@@ -110,7 +109,8 @@ export function createApi(ctx, logger) {
110
109
  const route = `${req.method} ${sub}`;
111
110
  try {
112
111
  if (route === 'GET /status') { const su = setupSteps(ctx); return json(res, 200, { status: statusOf(ctx), fileError: fileError() || null, setup: { done: su.done, dismissed: su.dismissed }, version: pluginVersion }); }
113
- if (route === 'GET /settings') return json(res, 200, { entries: describe(readAll()), fileError: fileError() || null, components: Object.fromEntries(Object.entries(statusOf(ctx)).map(([k, v]) => [k, v !== null])) });
112
+ // components: which sections' components are on (gate exposes no service and is never listed: the page treats an unlisted section as on)
113
+ if (route === 'GET /settings') { const s = services(ctx); return json(res, 200, { entries: describe(readAll()), fileError: fileError() || null, components: Object.fromEntries(Object.keys(s).map((k) => [k, Boolean(s[k])])) }); }
114
114
  if (route === 'PUT /settings') {
115
115
  const body = await readJson(req);
116
116
  const patch = validatePatch(body.patch);
@@ -2,7 +2,7 @@
2
2
  // sidebar tabs, the header buttons and the dot page; on the host this mounts the dot page's API
3
3
  // (/dsh-dot/api: settings, doctor, one-click fixes, diagnostics), independent of which other
4
4
  // components are on.
5
- import { mountApi } from '../page/api.js';
5
+ import { mountApi } from './api.js';
6
6
 
7
7
  export const inject = [];
8
8
 
package/src/page/page.js CHANGED
@@ -69,9 +69,8 @@ async function api(method, path, body) {
69
69
  if (!r.ok) throw new Error(j.error || ('HTTP ' + r.status));
70
70
  return j;
71
71
  }
72
- const NAMES = { phone: '手机', computer: '电脑', qq: 'QQ', dot: 'dot', interlude: '幕间' };
72
+ const NAMES = { phone: '手机', computer: '电脑', gate: '审批', qq: 'QQ', dot: 'dot', interlude: '幕间', compat: '兼容' };
73
73
  const APPLY = { live: '即时生效', 'restart-phone': '重启手机生效', 'restart-dsh': '重启 dsh 生效', create: '只对新建生效' };
74
- const SECTION_OF_GROUP = (g) => g.startsWith('手机') ? 'phone' : g === '电脑' ? 'computer' : g === 'QQ' ? 'qq' : g === 'dot' ? 'dot' : g === '审批' ? 'computer' : '';
75
74
  function level(s) { if (!s) return ''; if (/ready|on/.test(s.state)) return 'ok'; if (s.state === 'error') return 'bad'; return 'warn'; }
76
75
  function stateText(name, s) {
77
76
  if (!s) return '关';
@@ -128,7 +127,7 @@ function renderSettings() {
128
127
  for (const e of entries) (groups[e.group] ||= []).push(e);
129
128
  $('groups').className = '';
130
129
  $('groups').innerHTML = Object.entries(groups).map(([g, list]) => {
131
- const sec = SECTION_OF_GROUP(g), on = !sec || components[sec] !== false;
130
+ const sec = list[0].section, on = components[sec] !== false;
132
131
  return '<div class="card" style="margin-bottom:12px"><details class="group"' + (on ? ' open' : '') + '><summary>' + esc(g) + (on ? '' : ' <span class="mute small">(' + NAMES[sec] + '组件没开:在 dsh 的插件页打开)</span>') + '</summary>'
133
132
  + list.map((e) => '<div class="set' + (changes[id(e)] !== undefined ? ' changed' : '') + '" data-id="' + id(e) + '"><label for="in-' + id(e).replace('.', '-') + '">' + esc(e.zh)
134
133
  + '<span class="tag' + (e.apply === 'create' ? ' create' : '') + '">' + APPLY[e.apply] + '</span><br><span class="key">' + id(e) + ' · 默认 ' + esc(JSON.stringify(e.default)) + (e.value !== undefined ? ' · 已设 ' + esc(JSON.stringify(e.value)) : '') + '</span></label><div>' + control(e) + '</div></div>').join('')
@@ -232,7 +231,7 @@ $('sum').onclick = async () => {
232
231
  $('rb').onclick = async () => {
233
232
  if ($('rbConfirm').value.trim() !== 'dot') { $('rbMsg').className = 'msg err'; $('rbMsg').textContent = '先在框里输入 dot'; return; }
234
233
  if (!confirm('确定删掉现在这台手机并新建?她手机里的一切都会没有。')) return;
235
- await act('phone-rebuild', $('rbMsg'), { confirm: 'dot', gb: $('rbGb').value || undefined });
234
+ await act('phone-rebuild', $('rbMsg'), { gb: $('rbGb').value || undefined });
236
235
  };
237
236
  $('cl').onclick = () => act('phone-cleanup', $('clMsg'));
238
237
 
@@ -242,6 +241,7 @@ function renderStatus(st) {
242
241
  phone: (x) => [x.serial && '设备 ' + x.serial, x.api && 'Android API ' + x.api + (x.abi ? ' (' + x.abi + ')' : ''), x.storage && x.storage.gb && '存储 ' + x.storage.gb + ' GB'],
243
242
  computer: (x) => [x.backend && '后端 ' + x.backend, x.stage && '阶段 ' + x.stage],
244
243
  qq: (x) => [x.connected ? '已连接' : '未连接', x.qq && '她的号 ' + x.qq, x.owner && '你的号 ' + x.owner],
244
+ compat: (x) => [x.qqBridge ? 'qq-bridge:' + x.qqBridge.root + '(模式 ' + x.qqBridge.mode + (x.qqBridge.bots && x.qqBridge.bots.length ? ',机器人 ' + x.qqBridge.bots.join('/') : '') + ')' : '没发现 qq-bridge'],
245
245
  };
246
246
  $('statusCards').className = '';
247
247
  $('statusCards').innerHTML = Object.entries(st).map(([k, x]) => '<div class="card" style="margin-bottom:12px"><div class="row" style="justify-content:space-between"><h2><span class="badge ' + level(x) + '"><span class="dotc"></span>' + NAMES[k] + ':' + esc(stateText(k, x)) + '</span></h2>'
@@ -438,7 +438,7 @@ export function apply(ctx, config = {}, deps = {}) {
438
438
  phone.doctorInfo = () => ({ installed: installed(), running: Boolean(child) || phone.isReady, ramMb: cfg.ramMb, dataGb: phone.storage().gb, port, adbPort: cfg.adbPort || 5037, gpu: gpuMode(cfg.gpu), crashed: lastCrash, paths: { emulator: paths.emulator } });
439
439
  /** Android's own verdict on its network: validated | partial | none (null when it cannot be read). */
440
440
  /** The machine check (src/doctor.js) for the phone and, when it is on, the computer. */
441
- phone.doctor = () => doctorFor({ phone, computer: (() => { try { return ctx.get('dshComputer'); } catch { return undefined; } })(), home: dshHome() });
441
+ phone.doctor = () => { const svc = (n) => { try { return ctx.get(n); } catch { return undefined; } }; return doctorFor({ phone, computer: svc('dshComputer'), compat: svc('dshDotCompat'), home: dshHome() }); };
442
442
  phone.network = async () => {
443
443
  if (!phone.isReady) return null;
444
444
  const out = String((await phone.adbExec(['shell', 'dumpsys connectivity']).catch(() => ({ stdout: '' }))).stdout);
@@ -922,12 +922,21 @@ export function apply(ctx, config = {}, deps = {}) {
922
922
  }, { prepend: true });
923
923
 
924
924
  ctx.inject(['systemPrompt'], (scope) => {
925
+ // The phone section goes to every session that has the phone tools; the parts about her (wake-ups
926
+ // through dot, her sticker album, remembering) only to her own sessions (compat says whose a
927
+ // session is; without compat every session counts as hers, as before). A session compat hides
928
+ // the phone from (a qq-bridge sandbox) gets nothing.
929
+ const ownerOf = (c) => { try { return ctx.get?.('dshDotCompat')?.ownerOf?.(c) ?? 'dot'; } catch { return 'dot'; } };
925
930
  scope.effect(() => scope.systemPrompt.section({
926
931
  name: 'phone:device',
927
932
  order: 60,
928
- text: () => (phone.state === 'ready'
929
- ? deviceText(mcpDevice(), cfg.number, { dot: Boolean(ctx.get?.('dshDot')), qq: Boolean(ctx.get?.('dshQq')), memory: Boolean(ctx.get?.('dotMemory')) })
930
- : ''),
933
+ text: (c) => {
934
+ if (phone.state !== 'ready') return '';
935
+ const o = ownerOf(c);
936
+ if (o === 'qqb-sandbox') return '';
937
+ const hers = o === 'dot';
938
+ return deviceText(mcpDevice(), cfg.number, { dot: hers && Boolean(ctx.get?.('dshDot')), qq: hers && Boolean(ctx.get?.('dshQq')), memory: hers && Boolean(ctx.get?.('dotMemory')) });
939
+ },
931
940
  }), 'dsh-dot/phone: device section');
932
941
  });
933
942
 
package/src/qq/qq.js CHANGED
@@ -44,6 +44,16 @@ export const defaults = {
44
44
  scoreThreshold: 7,
45
45
  scoreModel: '',
46
46
  scoreMaxPerMinute: 6,
47
+ // Accounts she never answers (other bots: a qq-bridge bot found next to her is ignored on its own,
48
+ // see src/compat/qq-bridge.js). Their messages do not wake her, are not scored, not remembered.
49
+ // A list, or numbers separated by commas / spaces.
50
+ ignore: '',
51
+ // Two bots answering each other in a group never stop: when someone (not the owner) and she have
52
+ // gone back and forth loopMax times in one group with nobody else saying a word in between, she
53
+ // stops answering that account there for loopCooldownMinutes. Groups only: in a private chat there
54
+ // is never anybody else, a friend talking to her is not a loop. 0 = off.
55
+ loopMax: 4,
56
+ loopCooldownMinutes: 10,
47
57
  // Outgoing text is tidied to her chat voice: no 。at line ends, no quotes/dashes/colons/asterisks/
48
58
  // hashes (times and URLs keep theirs). Off = send exactly what the model wrote.
49
59
  tidy: true,
@@ -467,6 +477,43 @@ function withFileLog(logger) {
467
477
  return wrapped;
468
478
  }
469
479
 
480
+ /** The `ignore` setting as a list of QQ numbers: an array, or a string of numbers separated by , , space or newline. */
481
+ export function parseIgnore(v) {
482
+ const raw = Array.isArray(v) ? v : String(v ?? '').split(/[\s,,;;]+/);
483
+ return [...new Set(raw.map((x) => String(x ?? '').trim()).filter((x) => /^\d{5,12}$/.test(x)))];
484
+ }
485
+
486
+ /**
487
+ * Two bots in one group answering each other. Per group it counts rounds — someone's message, then
488
+ * hers (said()), then the same someone again — and trips at `max` such rounds with nobody else in
489
+ * between (any other account's message, the owner's above all, resets it). Tripped, that account
490
+ * is not answered in that group for `cooldownMs`. Only `group:` chats count: a private chat has no
491
+ * "anybody else" and is never a loop. Pure bookkeeping, no I/O.
492
+ */
493
+ export function createLoopBreaker({ max = 4, cooldownMs = 600_000, now = Date.now } = {}) {
494
+ const chats = new Map(); // chat → { with, rounds, saidSince } ; cooling: `${chat}|${uin}` → until
495
+ const cooling = new Map();
496
+ return {
497
+ /** A message from `uin` in `chat`. → '' (fine) | 'cooling' (still ignored) | 'tripped' (ignored from now on). */
498
+ heard(chat, uin, { human = false } = {}) {
499
+ if (!max || !String(chat).startsWith('group:')) return '';
500
+ const key = `${chat}|${uin}`, until = cooling.get(key);
501
+ if (until) { if (until > now()) return 'cooling'; cooling.delete(key); }
502
+ const c = chats.get(chat);
503
+ if (human || !c || c.with !== uin) { chats.set(chat, { with: uin, rounds: 0, saidSince: false }); return ''; }
504
+ if (!c.saidSince) return ''; // they said two things in a row: no round completed
505
+ c.rounds++; c.saidSince = false;
506
+ if (c.rounds < max) return '';
507
+ cooling.set(key, now() + cooldownMs); chats.delete(chat);
508
+ return 'tripped';
509
+ },
510
+ /** She sent something to `chat`. */
511
+ said(chat) { const c = chats.get(chat); if (c) c.saidSince = true; },
512
+ /** Is `uin` cooling in `chat`? */
513
+ cooling(chat, uin) { const until = cooling.get(`${chat}|${uin}`); return Boolean(until && until > now()); },
514
+ };
515
+ }
516
+
470
517
  export function apply(ctx, config = {}, deps = {}) {
471
518
  const logger = withFileLog(ctx.logger('dsh-dot/qq'));
472
519
  const settings = readSettingsFile();
@@ -482,6 +529,11 @@ export function apply(ctx, config = {}, deps = {}) {
482
529
  sanitise('githubProxy', (v) => assertSafeShellUrl(v, 'githubProxy'), '');
483
530
  sanitise('backend', (v) => { if (!BACKENDS.includes(v)) throw new Error(`unknown backend "${String(v).slice(0, 20)}" (${BACKENDS.join(' | ')})`); return v; }, defaults.backend);
484
531
  sanitise('snowlumaVersion', (v) => { if (!/^[A-Za-z0-9._-]{1,40}$/.test(String(v))) throw new Error('bad release tag'); return String(v); }, '');
532
+ cfg.ignore = parseIgnore(cfg.ignore);
533
+ const loop = createLoopBreaker({ max: Number(cfg.loopMax) || 0, cooldownMs: (Number(cfg.loopCooldownMinutes) || 10) * 60_000 });
534
+ const notAnswered = () => { let b = []; try { b = ctx.get('dshDotCompat')?.ignoredUins?.() ?? []; } catch {} const all = [...new Set([...cfg.ignore, ...b])]; return all.length ? `\nnot answered: ${all.join(', ')}${b.length ? ` (${b.join(', ')}: qq-bridge's bot)` : ''}` : ''; };
535
+ /** Accounts she does not answer: the ignore setting plus whatever compat knows (qq-bridge's bots). */
536
+ const ignored = (uin) => { if (cfg.ignore.includes(String(uin))) return 'ignore'; try { if (ctx.get('dshDotCompat')?.ignoredUins?.().includes(String(uin))) return 'qq-bridge'; } catch {} return ''; };
485
537
  if (!cfg.token) { cfg.token = randomBytes(24).toString('hex'); writeSettings({ token: cfg.token }); }
486
538
  const audit = createAudit(auditFile());
487
539
  // Her stickers also live in her phone's album (dot-stickers): re-synced whenever the saved set changes and when the phone comes up.
@@ -921,6 +973,15 @@ export function apply(ctx, config = {}, deps = {}) {
921
973
  const selfId = String(ev.self_id ?? qq.selfId);
922
974
  if (String(ev.user_id) === selfId) return;
923
975
  const isGroup = ev.message_type === 'group';
976
+ const chat = isGroup ? `group:${ev.group_id}` : `user:${ev.user_id}`;
977
+ // Another bot's words: not hers to answer (an owner message is never ignored).
978
+ if (!(qq.owner && String(ev.user_id) === String(qq.owner))) {
979
+ const why = ignored(ev.user_id);
980
+ if (why) { audit({ kind: 'ignored', why, from: String(ev.user_id), chat }); return; }
981
+ const cooling = loop.heard(chat, String(ev.user_id));
982
+ if (cooling === 'tripped') { audit({ kind: 'loop-break', chat, with: String(ev.user_id), max: cfg.loopMax, cooldownMinutes: cfg.loopCooldownMinutes }); logger.warn(`qq: ${chat} — ${cfg.loopMax} rounds back and forth with ${ev.user_id} and nobody else: not answering them there for ${cfg.loopCooldownMinutes} min`); }
983
+ if (cooling) return;
984
+ } else loop.heard(chat, String(ev.user_id), { human: true });
924
985
  const who = ev.sender?.card || ev.sender?.nickname || String(ev.user_id);
925
986
  // Every picture in it, in order, with the words that stand for it in `text` — what she may get to see (seeImages).
926
987
  const seen = [];
@@ -1147,6 +1208,7 @@ export function apply(ctx, config = {}, deps = {}) {
1147
1208
  const ids = [], failed = [];
1148
1209
  const started = Date.now();
1149
1210
  const toOwner = Boolean(qq.owner) && target.user_id === Number(qq.owner);
1211
+ loop.said(target.group_id ? `group:${target.group_id}` : `user:${target.user_id}`);
1150
1212
  let unsent = null;
1151
1213
  for (const [i, part] of parts.entries()) {
1152
1214
  if (i && cfg.typingMsPerChar > 0) await new Promise((r) => setTimeout(r, Math.min(2500, part.length * cfg.typingMsPerChar)));
@@ -1172,6 +1234,8 @@ export function apply(ctx, config = {}, deps = {}) {
1172
1234
  return { sent: n, messageIds: ids, said: parts, imagesSent: went.length, images: went, ...(failed.length ? { failed, textSent: parts.length } : {}), ...(dropped ? { dropped } : {}) };
1173
1235
  };
1174
1236
  /** Her friend list: [{ uid, nickname, remark }] (OneBot get_friend_list). */
1237
+ /** The groups she is in: [{ gid, name }] (OneBot get_group_list). */
1238
+ qq.groups = async () => ((await call('get_group_list', {})) ?? []).map((g) => ({ gid: String(g.group_id ?? ''), name: String(g.group_name ?? '') })).filter((g) => g.gid);
1175
1239
  qq.friends = async () => ((await call('get_friend_list', {})) ?? []).map((f) => ({ uid: String(f.user_id ?? ''), nickname: String(f.nickname ?? ''), remark: String(f.remark ?? '') })).filter((f) => f.uid);
1176
1240
  qq.setAccount = (n) => { cfg.qq = assertSafeQQ(n); qq.qq = cfg.qq; writeSettings({ qq: cfg.qq }); };
1177
1241
  qq.setOwner = (n) => { qq.owner = assertSafeQQ(n, 'owner QQ number'); writeSettings({ owner: qq.owner }); };
@@ -1241,10 +1305,13 @@ export function apply(ctx, config = {}, deps = {}) {
1241
1305
  });
1242
1306
 
1243
1307
  ctx.inject(['systemPrompt'], (scope) => {
1308
+ // Her QQ is hers: the section goes only to her sessions (compat says whose a session is; without
1309
+ // compat, every session, as before). Another plugin's session has no qq_send to use it with.
1310
+ const hers = (c) => { try { const o = ctx.get('dshDotCompat')?.ownerOf?.(c); return o === undefined || o === 'dot'; } catch { return true; } };
1244
1311
  scope.effect(() => scope.systemPrompt.section({
1245
1312
  name: 'qq:channel',
1246
1313
  order: 61,
1247
- text: () => (qq.connected
1314
+ text: (c) => (qq.connected && hers(c)
1248
1315
  ? channelText({ qq: qq.qq, owner: qq.owner, groupPolicy: cfg.groupPolicy, stickers: stickers.prompt() })
1249
1316
  : ''),
1250
1317
  }), 'dsh-dot/qq: channel section');
@@ -1320,7 +1387,7 @@ export function apply(ctx, config = {}, deps = {}) {
1320
1387
  }
1321
1388
  } catch (err) { extra = `\nerror: ${err.message}`; }
1322
1389
  const s = qq.status();
1323
- return { kind: 'success', text: `qq: ${s.state}${s.error ? ` — ${s.error}` : ''} · backend: ${s.backend}${sl() ? ` · mcp: ${mcpFork ? 'mounted' : 'not mounted'}` : ''}\naccount: ${s.qq || '(not set)'} · owner: ${s.owner || '(not set — /qq owner <your QQ number>)'} · connected: ${s.connected} · ws: ${s.wsPort} in the computer${extra}` };
1390
+ return { kind: 'success', text: `qq: ${s.state}${s.error ? ` — ${s.error}` : ''} · backend: ${s.backend}${sl() ? ` · mcp: ${mcpFork ? 'mounted' : 'not mounted'}` : ''}\naccount: ${s.qq || '(not set)'} · owner: ${s.owner || '(not set — /qq owner <your QQ number>)'} · connected: ${s.connected} · ws: ${s.wsPort} in the computer${notAnswered()}${extra}` };
1324
1391
  },
1325
1392
  }), 'dsh-dot/qq: /qq command');
1326
1393
  });
@@ -13,8 +13,9 @@ import { defaults as computerDefaults } from './computer/vm.js';
13
13
  import { defaults as gateDefaults } from './computer/gate.js';
14
14
  import { defaults as qqDefaults } from './qq/qq.js';
15
15
  import { defaults as dotDefaults } from './dot/core.js';
16
+ import { defaults as compatDefaults } from './compat/qq-bridge.js';
16
17
 
17
- export const COMPONENT_DEFAULTS = { phone: phoneDefaults, computer: computerDefaults, gate: gateDefaults, qq: qqDefaults, dot: dotDefaults };
18
+ export const COMPONENT_DEFAULTS = { phone: phoneDefaults, computer: computerDefaults, gate: gateDefaults, qq: qqDefaults, dot: dotDefaults, compat: compatDefaults };
18
19
 
19
20
  const choice = (...values) => ({ type: 'enum', values });
20
21
  const e = (section, key, group, type, apply, zh, extra = {}) => ({ section, key, group, apply, zh, ...(typeof type === 'string' ? { type } : type), ...extra });
@@ -61,6 +62,9 @@ export const SCHEMA = [
61
62
  e('qq', 'typingMsPerChar', 'QQ', 'int', 'live', '分条发送的打字停顿(毫秒/字,0 = 一次发完)', { min: 0, max: 500 }),
62
63
  e('qq', 'tidy', 'QQ', 'bool', 'live', '去掉句号、引号、破折号等书面符号'),
63
64
  e('qq', 'dropLatinLeaks', 'QQ', 'bool', 'live', '不发整条都是英文的气泡'),
65
+ e('qq', 'ignore', 'QQ', 'text', 'live', '不回复的 QQ 号(别的机器人;逗号分开。qq-bridge 的机器人号会自动认出,不用填)'),
66
+ e('qq', 'loopMax', 'QQ', 'int', 'live', '防互刷(只管群聊):和同一个号在一个群里一来一回几轮、中间没别人说话就停(0 = 不管)', { min: 0, max: 50 }),
67
+ e('qq', 'loopCooldownMinutes', 'QQ', 'int', 'live', '防互刷:停多少分钟', { min: 1, max: 1440 }),
64
68
  e('qq', 'token', 'QQ', 'text', 'restart-dsh', 'OneBot 令牌', { secret: true, hidden: true }),
65
69
  // dot
66
70
  e('dot', 'phoneCheckEveryMinutes', 'dot', 'int', 'restart-dsh', '隔多久拿起手机看一眼(分钟,0 = 不看)', { min: 0, max: 1440 }),
@@ -68,6 +72,12 @@ export const SCHEMA = [
68
72
  e('dot', 'manuals', 'dot', 'bool', 'restart-dsh', '手机、电脑说明书在第一次用时才给(省 token)'),
69
73
  e('dot', 'howto', 'dot', 'bool', 'restart-dsh', '记录她自己的 App 使用经验'),
70
74
  e('dot', 'approvalWaitMs', 'dot', 'int', 'restart-dsh', '没人回的审批多久算拒绝(毫秒,0 = 一直等)', { min: 0 }),
75
+ // compat (living next to qq-bridge)
76
+ e('compat', 'qqBridge', '兼容·qq-bridge', choice('auto', true, false), 'restart-dsh', '认 qq-bridge(auto = 装了就认)'),
77
+ e('compat', 'qqBridgeRoot', '兼容·qq-bridge', 'text', 'restart-dsh', 'qq-bridge 的目录(自动找不到时填;里面有 config.json)'),
78
+ e('compat', 'ownerDevices', '兼容·qq-bridge', 'bool', 'live', 'qq-bridge 管理员私聊(封闭 agent 模式)能用她的手机和电脑'),
79
+ e('compat', 'ownerComputer', '兼容·qq-bridge', choice('vm', 'host'), 'live', '管理员私聊里的命令在哪跑:vm = 她的电脑(不共享 qq-bridge 的目录)/ host = 本机'),
80
+ e('compat', 'hideBridgeTools', '兼容·qq-bridge', 'bool', 'live', '她的会话里不出现 qq-bridge 的工具(mcp__snowluma__* 等)'),
71
81
  ];
72
82
 
73
83
  /** Keys whose values never leave the machine as they are (diagnostics, logs). */
@@ -90,7 +100,11 @@ export function validate(entry, value) {
90
100
  if (entry.max !== undefined && n > entry.max) fail(`不能大于 ${entry.max}`);
91
101
  return n;
92
102
  }
93
- case 'enum': if (!entry.values.includes(value)) fail(`只能是 ${entry.values.map((v) => v || '(空)').join(' / ')}`); return value;
103
+ case 'enum': {
104
+ // A <select> hands back strings; an enum of true/false (compat.qqBridge) takes them as booleans.
105
+ const v = value === 'true' && entry.values.includes(true) ? true : value === 'false' && entry.values.includes(false) ? false : value;
106
+ if (!entry.values.includes(v)) fail(`只能是 ${entry.values.map((x) => (x === '' ? '(空)' : String(x))).join(' / ')}`); return v;
107
+ }
94
108
  case 'enum-or-text': case 'text': if (typeof value !== 'string') fail('要文字'); return value.trim();
95
109
  default: return value;
96
110
  }
package/src/settings.js CHANGED
@@ -9,7 +9,7 @@ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFil
9
9
  import { homedir } from 'node:os';
10
10
  import { dirname, join } from 'node:path';
11
11
 
12
- export const SECTIONS = ['phone', 'computer', 'gate', 'qq', 'memory', 'interlude', 'dot'];
12
+ export const SECTIONS = ['phone', 'computer', 'gate', 'qq', 'memory', 'interlude', 'dot', 'compat'];
13
13
 
14
14
  export const dshHome = () => process.env.DSH_HOME || join(homedir(), '.dsh');
15
15
  export const settingsPath = () => join(dshHome(), 'dsh-dot.json');
@@ -11,3 +11,12 @@ export const QQ_SERVER = 'dot-qq';
11
11
  export const QQ_TOOL_PREFIX = `mcp__${QQ_SERVER}__`;
12
12
  // dot's own phone tool (phone.js): a part of the screen, enlarged. Read-only, so observation turns allow it.
13
13
  export const PHONE_ZOOM_TOOL = 'phone_zoom';
14
+
15
+ // Every model-facing tool this plugin registers, by who may use it (src/compat/qq-bridge.js hides the
16
+ // rest per session; test/compat.test.js checks the list against the register() calls in src/).
17
+ // DOT_TOOLS / DOT_TOOL_PREFIXES: hers alone — her memory, her accounts, her QQ (qq_send and her
18
+ // SnowLuma actions), her day. Never in another plugin's session.
19
+ // DEVICE_TOOL_PREFIXES: her phone and her computer — hers, and a qq-bridge owner chat's.
20
+ export const DOT_TOOLS = ['memory', 'recall', 'account', 'doings', 'tell_him', 'qq_send', 'qq_sticker_keep'];
21
+ export const DOT_TOOL_PREFIXES = [QQ_TOOL_PREFIX];
22
+ export const DEVICE_TOOL_PREFIXES = [PHONE_TOOL_PREFIX, VM_TOOL_PREFIX];