dsh-dot-life 0.12.2 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,194 @@
1
+ # 设置:`~/.dsh/dsh-dot.json`
2
+
3
+ dsh-dot 的所有个人设置都写在**一个文件**里:
4
+
5
+ | 系统 | 路径 |
6
+ |---|---|
7
+ | macOS / Linux | `~/.dsh/dsh-dot.json` |
8
+ | Windows | `%USERPROFILE%\.dsh\dsh-dot.json` |
9
+ | 设了 `DSH_HOME` 时 | `$DSH_HOME/dsh-dot.json` |
10
+
11
+ - 文件不存在就是全用默认值,需要时自己建。
12
+ - 它在插件包外面,**升级插件不会覆盖**;桌面版拿不到终端环境变量,也能用它配置。
13
+ - **改完重启 dsh 才生效**(退出桌面版再打开)。
14
+ - 文件写坏了(不是合法 JSON)会被整个忽略,日志里有一行 `dsh-dot.json ignored`。
15
+
16
+ ## 让 dsh(或别的 agent)帮你改
17
+
18
+ 把下面这段连同你的需求发给 dsh 即可:
19
+
20
+ ```text
21
+ 帮我改 dsh-dot 的设置:<你的需求,例如"手机存储改成 32 GB,晚上 1 点前都算她的活跃时间">。
22
+ 设置文件是 ~/.dsh/dsh-dot.json,说明在 https://github.com/Kevinwu901113/dsh-dot/blob/main/docs/SETTINGS.md 。
23
+ 先读这份说明,再读现有的设置文件,只改需要的键,保留其他内容,改完告诉我要不要重启、有没有只在新建时生效的项。
24
+ ```
25
+
26
+ **给 agent 的规则**(dsh、Claude、Codex 等改这个文件时照做):
27
+
28
+ 1. 先读现有文件;不存在就新建 `{}`。只增改相关的键,**不要删别的段和键**。
29
+ 2. 顶层按组件分段:`phone`、`computer`、`gate`、`qq`、`memory`、`interlude`、`dot`。键名和类型照下面的表,不要发明新键。
30
+ 3. 写合法 JSON(不能有注释、尾逗号)。想留说明就用 `_` 开头的键,如 `"_note": "..."`,会被忽略。
31
+ 4. 下文标 **🔒 建立时** 的项只对新建的手机 / 虚拟机生效,改之前先告诉用户要重建、会丢什么,得到同意再动。
32
+ 5. 有专门命令的(`/phone size`、`/dot memory recall …`、`/qq owner` 等),优先告诉用户用命令,命令不用重启。
33
+ 6. 改完提醒用户重启 dsh。
34
+
35
+ ## 示例
36
+
37
+ ```json
38
+ {
39
+ "phone": { "dataGb": 32, "ramMb": 4096 },
40
+ "computer": { "rootDisk": "32G", "memory": "6G", "cpus": 4 },
41
+ "qq": { "githubProxy": "https://ghfast.top/", "groupPolicy": "score" },
42
+ "memory": { "dailyAt": "01:30" },
43
+ "interlude": { "activeHours": "09:00-01:00", "speak": true },
44
+ "dot": { "phoneCheckEveryMinutes": 60 }
45
+ }
46
+ ```
47
+
48
+ ## 常见需求
49
+
50
+ | 我想… | 改什么 | 注意 |
51
+ |---|---|---|
52
+ | **手机存储大一点** | 建手机前:`/phone size 32`,或 `/phone accept 32`,或 `phone.dataGb`(8–256) | 🔒 建立时。手机建好后**扩不了**(改 AVD 的 `config.ini` 实测无效)。已经满了:卸 App、清 App 数据;或者删掉 `~/.dsh/phone/avd/dot.avd/` 和 `dot.ini` 重建(手机里的 App 和登录全丢),重建前先 `/phone size <GB>` |
53
+ | 手机内存 / 机型 / 语言 / 时区 | `phone.ramMb`、`phone.device`、`phone.locale`、`phone.timezone` | `ramMb`、`device` 🔒 建立时(同上,删 AVD 重建) |
54
+ | 不显示模拟器窗口 | `phone.window: false` | 画面仍可在 dsh 的手机标签页看 |
55
+ | **电脑磁盘大一点** | `computer.rootDisk`,如 `"32G"` | 🔒 建立时。已有虚拟机扩不了,要重建:`msb rm -f dsh-computer` 并删 `~/.microsandbox/snapshots/dsh-computer/`(见 [computer.md](computer.md#六维护)),装过的东西和 QQ 登录会丢。0.11.3 之前建的虚拟机只有约 4 GB |
56
+ | 电脑内存 / CPU | `computer.memory`(如 `"6G"`)、`computer.cpus` | 重启 dsh 生效 |
57
+ | 电脑里 QQ 报 `no space left` / `ENOSPC` | 先 `/qq clean`(清缓存和残留),还不够 `/qq clean napcat`(用 SnowLuma 时删掉 NapCat) | 根治是加大 `computer.rootDisk` 重建 |
58
+ | 共享文件夹给电脑 | `computer.mounts: ["/Users/你/Projects/a"]` | |
59
+ | 国内网络下载慢 | QQ 安装:`qq.githubProxy`;召回模型:`/dot memory recall mirror <url>`(默认已走 hf-mirror);虚拟机镜像:`computer.image` 换镜像源 | |
60
+ | 召回换云端 / 关掉 | `/dot memory recall backend siliconflow`,再 `/dot memory recall key siliconflow <key>` | 命令即时生效,不用重启,也不用改这个文件 |
61
+ | **她的作息** | `interlude.activeHours`(如 `"09:00-01:00"`,可跨午夜)、`interlude.advanceEveryMinutes`(自己过日子的间隔,0 关)、`interlude.maxRoundsPerDay` | 活跃时段外不跑幕间、不主动找你 |
62
+ | 日记时间 | `memory.dailyAt`(默认 `"23:30"`) | |
63
+ | **让她主动找你** | `interlude.speak: true`,`interlude.maxContactsPerDay`、`interlude.willingnessThreshold`(0–1,越低越爱找你) | 默认关 |
64
+ | 拿手机看的频率 | `dot.phoneCheckEveryMinutes`(默认 30,0 关) | |
65
+ | 夜里通知不叫醒她 | `dot.notifyHours: "08:00-23:00"`(只有这个时段内通知才叫醒) | 默认空 = 任何时候都叫醒 |
66
+ | 某个 App 的通知别叫醒她 | `/phone notify mute <包名>` | 命令即时生效 |
67
+ | 群聊里插话的规则 | `qq.groupPolicy`:`mention`(被 @ 才回,默认)/ `score`(按价值评分,配 `qq.scoreThreshold` 0–10)/ `all` / `none` | |
68
+ | 回复不拆条、不模拟打字 | `qq.typingMsPerChar: 0` | |
69
+ | 发 QQ 的审批松紧 | `qq.sendPolicy`:`reply`(默认)/ `always` / `off` | |
70
+ | 她逛 / 玩的 App | `interlude.phoneApps`(站点 → 包名)、`interlude.playApps`(名字 → 包名)、`interlude.play: false` 关掉「玩」 | 只对她自己装了的 App 生效 |
71
+ | 省 token | `interlude.maxRoundsPerDay`、`interlude.browseDailyCap`、`memory.handoffTokens`(交班阈值,默认 150000)、`dot.phoneCheckEveryMinutes` 调大 | 每轮用量在 `~/dot/interlude/calls.jsonl`、`~/dot/memory/calls.jsonl` |
72
+ | 和别的记忆插件一起用 | `memory.coexist`:`auto`(默认)/ `people-only` / `full` | |
73
+ | 电脑审批多 / 少 | `gate.mode`:`risky`(默认)/ `browser`(每个浏览器动作都问)/ `off` | |
74
+ | 换她的家目录 | `dot.home`、`memory.home`、`interlude.home` **三处写同一个路径** | 默认 `~/dot` |
75
+ | **没有硬件虚拟化 / 不要手机** | `phone.enabled: false` | |
76
+ | 关掉某个组件 | `qq.enabled`、`memory.enabled`、`interlude.enabled`、`dot.enabled` 设 `false` | 其余组件照常 |
77
+ | **不要电脑** | 只能用环境变量 `DSH_DOT_COMPUTER=off`(见下) | 电脑组件会改 dsh 的全局沙箱设置,必须在插件加载前决定,设置文件来不及 |
78
+
79
+ ### 设置环境变量(只有关电脑等少数项需要)
80
+
81
+ ```bash
82
+ # macOS 桌面版:设完退出并重开 dsh
83
+ launchctl setenv DSH_DOT_COMPUTER off
84
+ ```
85
+
86
+ ```powershell
87
+ # Windows:设完重开 dsh
88
+ setx DSH_DOT_COMPUTER off
89
+ ```
90
+
91
+ ## 全部键
92
+
93
+ 只列常改的;完整列表和含义见各组件文档:[phone](phone.md)、[computer](computer.md)、[qq](qq.md)、[memory](memory.md)、[interlude](interlude.md)。源码里每个组件的 `defaults` 就是全集。
94
+
95
+ ### `phone`
96
+
97
+ | 键 | 默认 | 作用 |
98
+ |---|---|---|
99
+ | `enabled` | `true` | `false` 关掉手机 |
100
+ | `dataGb` | `16` | 存储(GB,8–256)🔒 建立时 |
101
+ | `ramMb` | `3072` | 内存 🔒 建立时 |
102
+ | `device` | `"pixel_6"` | 机型 🔒 建立时 |
103
+ | `api` / `abi` | `35` / 跟随 CPU | 系统镜像 🔒 建立时 |
104
+ | `locale` / `timezone` | `"zh-CN"` / `"Asia/Shanghai"` | 语言、时区 |
105
+ | `window` | `true` | 显示模拟器窗口 |
106
+ | `gpu` | `"auto"` | 模拟器 GPU 模式 |
107
+ | `notifyMuted` | `[]` | 不叫醒她的包名(也可用 `/phone notify mute`) |
108
+ | `keepAppsAlive` | `true` | 不让后台 App 被冻结(聊天 App 收消息靠它) |
109
+ | `publicUrl` | `""` | 你对外暴露的 dsh 地址,用于实时画面链接 |
110
+
111
+ ### `computer`
112
+
113
+ | 键 | 默认 | 作用 |
114
+ |---|---|---|
115
+ | `rootDisk` | `"16G"` | 磁盘 🔒 建立时 |
116
+ | `memory` / `cpus` | `"4G"` / `2` | 资源上限 |
117
+ | `mounts` | `[]` | 共享文件夹 |
118
+ | `backend` | `"auto"` | `microsandbox` / `docker` |
119
+ | `image` | `ghcr.io/agent-infra/sandbox:latest` | 镜像 |
120
+ | `publicUrl` | `""` | 你对外暴露的 dsh 地址 |
121
+
122
+ 网关端口只能用环境变量 `DSH_COMPUTER_PORT` 改。
123
+
124
+ ### `gate`
125
+
126
+ | 键 | 默认 | 作用 |
127
+ |---|---|---|
128
+ | `mode` | `"risky"` | `off` / `risky` / `browser` |
129
+
130
+ 分类表(`readOnlyTools`、`alwaysAskTools`、`protectedPaths`、`shellPatterns` 等)也可以在这里覆盖,见 [computer.md](computer.md)。
131
+
132
+ ### `qq`
133
+
134
+ | 键 | 默认 | 作用 |
135
+ |---|---|---|
136
+ | `enabled` | `true` | `false` 关掉 |
137
+ | `backend` | `"napcat"` | `snowluma`(也可 `/qq backend`) |
138
+ | `qq` / `owner` | `""` | 她的号 / 你的号(建议用 `/qq account`、`/qq owner`) |
139
+ | `githubProxy` | `""` | GitHub 下载镜像前缀,如 `https://ghfast.top/` |
140
+ | `groupPolicy` | `"mention"` | `mention` / `score` / `all` / `none` |
141
+ | `scoreThreshold` | `7` | `score` 模式的插话门槛(0–10) |
142
+ | `sendPolicy` | `"reply"` | `reply` / `always` / `off` |
143
+ | `replyWindowMinutes` | `30` | `reply` 模式下多久内算"对方找过她" |
144
+ | `typingMsPerChar` | `60` | 分条发送的打字停顿,0 一次发完 |
145
+ | `tidy` | `true` | 去掉句号、引号、破折号等书面符号 |
146
+
147
+ ### `memory`
148
+
149
+ | 键 | 默认 | 作用 |
150
+ |---|---|---|
151
+ | `enabled` | `true` | `false` 关掉 |
152
+ | `home` | `~/dot` | 和 `dot.home`、`interlude.home` 保持一致 |
153
+ | `handoffTokens` | `150000` | 对话多长换新会话 |
154
+ | `dailyAt` | `"23:30"` | 每天整理 + 写日记的时间 |
155
+ | `coexist` | `"auto"` | `auto` / `people-only` / `full` |
156
+ | `recallBackend` | `"local"` | `local` / `siliconflow` / `dashscope` / `off`(建议用 `/dot memory recall backend`,命令设的值优先) |
157
+ | `recallTopK` / `recallMaxTokens` / `recallMinScore` | `8` / `1500` / `0.45` | 每次叫醒注入多少旧对话 |
158
+ | `recallMirror` | `""` | 本机模型下载镜像,默认 hf-mirror |
159
+
160
+ ### `interlude`
161
+
162
+ | 键 | 默认 | 作用 |
163
+ |---|---|---|
164
+ | `enabled` | `true` | `false` 关掉 |
165
+ | `home` | `~/dot` | 和另外两处保持一致 |
166
+ | `activeHours` | `"08:00-23:00"` | 活跃时段 |
167
+ | `idleMinutes` | `10` | 聊天安静多久后跑一轮 |
168
+ | `advanceEveryMinutes` | `180` | 自己过日子的间隔,0 关 |
169
+ | `maxRoundsPerDay` | `12` | 每天最多几轮 |
170
+ | `browseDailyCap` / `vmDailyCap` | `6` / `2` | 每天「去看」上限 |
171
+ | `vmSites` | `[]` | 用电脑浏览器看的网站(她登录过的) |
172
+ | `phoneApps` / `playApps` | 内置表 | 逛 / 玩的 App |
173
+ | `play` | `true` | 「玩」(点赞、评论、关注) |
174
+ | `speak` | `false` | 主动找你 |
175
+ | `maxContactsPerDay` / `willingnessThreshold` | `2` / `0.6` | 主动联系的上限和门槛 |
176
+ | `presetHub` | `https://typ0.space` | HDSI 预设站 |
177
+
178
+ ### `dot`
179
+
180
+ | 键 | 默认 | 作用 |
181
+ |---|---|---|
182
+ | `enabled` | `true` | `false` 关掉联系人层 |
183
+ | `home` | `~/dot` | 和另外两处保持一致 |
184
+ | `phoneCheckEveryMinutes` | `30` | 隔多久拿起手机看一眼,0 关 |
185
+ | `notifyHours` | `""` | 只在这个时段内通知叫醒她;空 = 一直 |
186
+ | `notifyBatchMs` | `1000` | 多少毫秒内的通知合并成一次叫醒 |
187
+ | `errandMaxTokens` | `60000` | 跑腿会话多长换新 |
188
+ | `imBot` / `imTarget` | `""` | dsh-im 的投递目标,空 = 第一个 |
189
+
190
+ ## 优先级和旧文件
191
+
192
+ 从弱到强:组件默认值 → 旧的单组件文件(`~/.dsh/dsh-phone.json`、`dsh-computer.json`、`dsh-qq.json`)→ 插件自带的 `cordis.patch.yml` → **`dsh-dot.json`** → 命令设的值(`/phone size`、`/phone accept`、`/dot memory recall …` 写进 `dsh-phone.json` / `dsh-memory.json`)。
193
+
194
+ 旧文件继续有效,不用迁移;新设置写进 `dsh-dot.json` 就行。不要去改 `node_modules` 里插件自带的 `cordis.patch.yml`,升级会被覆盖。
package/docs/phone.md CHANGED
@@ -70,3 +70,7 @@ An Android phone the plugin installs and runs for the character, exposed to the
70
70
  - mobile-mcp 的工具每次调用都要带 `device`,模型偶尔会忘;提示段里给了设备号。
71
71
  - 多台手机未做。
72
72
  - 数据分区建好后不能扩大(改 `config.ini` 的 `disk.dataPartition.size` 不生效,实测);满了只能清 App 数据、卸 App,或清空重建。
73
+
74
+ ## 模拟器挂了
75
+
76
+ 接管的模拟器(上次 dsh 留下的)不是我们的子进程,QEMU 卡死崩溃(11-03:所有 QEMU 线程 15 秒无响应后 crash)时没有退出事件。所以就绪后每 `aliveEveryMs`(15 s)问一次 `adb get-state`,连续 3 次没回应就记 `emulator-gone`、状态转 error、停通知监听,`restartDelayMs` 后像退出一样重开。
package/docs/qq.md CHANGED
@@ -49,7 +49,7 @@ QQ 的电脑登录码**不接受相册导入,只认摄像头**。她手机的
49
49
  | 她发图 | `images` 里每一项直接作为**图片**发出(不是链接):网址(NapCat 下载)、`phone:screen`(手机此刻截图)、`phone:latest`(手机里最新的照片/截图/下载)、`/sdcard/…`(手机上的文件)、电脑上的绝对路径;≤10 MB |
50
50
  | 图片网址规则 | 只接受公网 `http`/`https`、端口 80/443、不带账号密码;回环、私网、链路本地(含 169.254.169.254)、组播、`localhost`/`*.local`/`*.internal`/单段主机名一律拒绝并报错(NapCat 在 VM 里下载,防止她让它访问 VM 内部服务)。公网域名解析到内网(DNS rebinding)这里拦不住 |
51
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 的「玩」) |
52
+ | 表情包 | 别人发的表情包(QQ 标 `sub_type: 1`;QQ 自带的大表情 mface 的 summary 是 `[?]`、`[doge]` 这种短方括号,也算)进文本是 `[表情包 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 的「玩」) |
53
53
  | dot 的提醒、幕间的主动联系 | 连上后优先走她的 QQ(发给 `owner`),dsh-im 的官方机器人退为后备 |
54
54
  | 手机上 QQ 的通知 | 连上后自动忽略(否则同一条叫两次);手机 QQ 照常可以看空间、看群、发图 |
55
55
  | 她能做什么 | 发文字和图片。加好友、进群、撤回、发文件都没有工具 |
package/lib/client.js CHANGED
@@ -425,7 +425,7 @@ window.__ModuleLoader__.load({
425
425
  phoneOffline: "手机还没有就绪(第一次要先在对话里发 /phone accept,下载约 2 GB;默认给手机 16 GB 存储,想要别的大小发 /phone accept 32 这样,建好后不能再改)。",
426
426
  dotTitle: "dot",
427
427
  dotOpen: "dot",
428
- dotDescription: "她现在在干什么、今天做了什么、记得什么",
428
+ dotDescription: "她现在在干什么、最近几场做了什么、记得什么",
429
429
  dotToggle: "dot 面板",
430
430
  dotChecking: "正在连接 dot…",
431
431
  dotOffline: "dot 还没有加载(dsh-dot/dot 组件未启用,或 dsh 还在启动)。",
@@ -451,7 +451,7 @@ window.__ModuleLoader__.load({
451
451
  phoneOffline: "The phone is not ready yet (first time: send /phone accept in a chat; it downloads about 2 GB. The phone gets 16 GB of storage; for another size send e.g. /phone accept 32 — it cannot be changed later).",
452
452
  dotTitle: "dot",
453
453
  dotOpen: "dot",
454
- dotDescription: "What she is doing now, today, and what she remembers",
454
+ dotDescription: "What she is doing now, her last scenes, and what she remembers",
455
455
  dotToggle: "dot panel",
456
456
  dotChecking: "Connecting to dot…",
457
457
  dotOffline: "dot is not loaded (the dsh-dot/dot component is off, or dsh is still starting).",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-dot-life",
3
- "version": "0.12.2",
3
+ "version": "0.13.0",
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",
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { VM_TOOL_PREFIX } from '../tool-prefixes.js';
12
12
  import { clip } from './audit.js';
13
+ import { sectionOf } from '../settings.js';
13
14
 
14
15
  export const name = 'dot-gate';
15
16
  export const inject = ['tools', 'dshComputer'];
@@ -84,7 +85,7 @@ export function decide(call, cfg, compiled = compile(cfg)) {
84
85
  }
85
86
 
86
87
  export function apply(ctx, config = {}) {
87
- const cfg = { ...defaults, ...config };
88
+ const cfg = { ...defaults, ...config, ...sectionOf('gate', (m) => ctx.logger?.('dsh-dot/gate')?.warn?.(m)) };
88
89
  const vm = ctx.dshComputer;
89
90
  const audit = (entry) => vm.audit?.(entry);
90
91
  const sessionOf = (exec) => exec.agent?.session?.id;
@@ -13,6 +13,7 @@ import { createAudit } from './audit.js';
13
13
  import { computerApiKey, keyHeaders, KEY_HEADER } from './key.js';
14
14
  import { mountComputerView, LIVE_VIEW_PAGE } from './live-view.js';
15
15
  import { localUrl, publicUrlOf } from '../web-auth.js';
16
+ import { sectionOf, setValues } from '../settings.js';
16
17
 
17
18
  export const name = 'dot-computer';
18
19
 
@@ -203,8 +204,10 @@ export async function ensureServices(config, computer, logger) {
203
204
  }
204
205
 
205
206
  export function apply(ctx, config = {}) {
206
- const cfg = { ...defaults, ...readSettingsFile(), ...Object.fromEntries(Object.entries(config).filter(([, v]) => v !== undefined && v !== '' && !(Array.isArray(v) && !v.length))) };
207
207
  const logger = withFileLog(ctx.logger('dsh-computer'));
208
+ // The gateway port is fixed by the patch (DSH_COMPUTER_PORT): the UI relay and the gate read the same value.
209
+ const { port: _port, ...user } = sectionOf('computer', (m) => logger.warn(m));
210
+ const cfg = { ...defaults, ...readSettingsFile(), ...setValues(config, { dropEmptyArrays: true }), ...user };
208
211
  const apiKey = computerApiKey(cfg.apiKey);
209
212
  const backend = pickBackend({ ...cfg, apiKey }, logger);
210
213
  const base = `http://127.0.0.1:${cfg.port}`;
@@ -0,0 +1,247 @@
1
+ // dsh-dot/dot activity: the panel's "last N scenes" — one row per time something woke her (his
2
+ // message, a QQ message, a phone notification, picking up her phone, a 幕间 round, a scheduled task,
3
+ // a play) until that turn ended, with what she did in it, in her own words, and what it cost.
4
+ //
5
+ // Nothing new is written for this: every scene is read back from records that already exist —
6
+ // $DSH_HOME/dsh-computer-audit.jsonl, dsh-phone-audit.jsonl kind dot / interlude / memory / tool / approval-asked
7
+ // $DSH_HOME/dsh-qq-audit.jsonl message / sent / sticker-kept / approval-asked
8
+ // <home>/memory/transcript.jsonl his words, scheduled tasks, notes her errands left, her replies
9
+ // <home>/memory/calls.jsonl + diary.md the daily consolidation and the diary it wrote
10
+ // <home>/interlude/calls.jsonl + script.md each 幕间 round: tokens, and the passage it wrote
11
+ // Only the tail of each file is read (the last few days, a bounded number of bytes), and a file is
12
+ // parsed again only when its size or mtime changed, so the panel's 3-second poll stays cheap.
13
+ import { closeSync, openSync, readSync, statSync } from 'node:fs';
14
+ import { join } from 'node:path';
15
+
16
+ export const DEFAULT_SCENES = 30;
17
+ const DAY = 86400000;
18
+ const WINDOW = 10 * 60000; // an event belongs to a scene that saw something this recently
19
+ const MERGE = 20000; // two records of one wake (audit line + transcript line) are this close
20
+ const CLIP = 80;
21
+
22
+ const clip = (s, n = CLIP) => { const t = String(s ?? '').replace(/\s+/g, ' ').trim(); return t.length > n ? `${t.slice(0, n)}…` : t; };
23
+ const timeOf = (v) => (typeof v === 'number' ? v : Date.parse(v ?? '')) || 0;
24
+
25
+ /** The last `maxBytes` of a file as lines (a partial first line dropped); `.1` (rotated audit) fills up what is left. */
26
+ export function tailLines(file, maxBytes = 1 << 20) {
27
+ const read = (f, budget) => {
28
+ let fd;
29
+ try {
30
+ const size = statSync(f).size;
31
+ if (!size || budget <= 0) return { lines: [], size };
32
+ const len = Math.min(size, budget);
33
+ const buf = Buffer.alloc(len);
34
+ fd = openSync(f, 'r');
35
+ readSync(fd, buf, 0, len, size - len);
36
+ let text = buf.toString('utf8');
37
+ if (len < size) text = text.slice(text.indexOf('\n') + 1);
38
+ return { lines: text.split('\n').filter(Boolean), size };
39
+ } catch (error) { void error; return { lines: [], size: 0 }; } finally { if (fd !== undefined) try { closeSync(fd); } catch (error) { void error; } }
40
+ };
41
+ const cur = read(file, maxBytes);
42
+ if (cur.size >= maxBytes || !file.endsWith('.jsonl')) return cur.lines;
43
+ return [...read(`${file}.1`, maxBytes - cur.size).lines, ...cur.lines];
44
+ }
45
+
46
+ const parseJsonl = (lines) => lines.map((l) => { try { return JSON.parse(l); } catch (error) { void error; return null; } }).filter(Boolean);
47
+
48
+ /** "## <head>\n<body>" sections (script.md, diary.md). */
49
+ export function sections(text) {
50
+ return String(text ?? '').split(/^## /m).filter((x) => x.trim()).map((x) => { const [head, ...body] = x.split('\n'); return { head: head.trim(), text: body.join('\n').trim() }; });
51
+ }
52
+ /** "2026-11-03 14:05 星期二 下午 · advance" → local ms (to the minute). */
53
+ const headTime = (head) => { const m = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})/.exec(head); return m ? new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5]).getTime() : 0; };
54
+ /** First sentence of a passage. */
55
+ export const firstSentence = (text) => { const line = String(text ?? '').trim().split('\n')[0]; return clip(/^.*?[。!?!?…]+[”」』]?/.exec(line)?.[0] ?? line); };
56
+ const localDay = (ms) => { const d = new Date(ms); return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; };
57
+
58
+ const APP = { qq: 'QQ', 'com.tencent.mobileqq': 'QQ', 'com.tencent.mm': '微信', 'com.max.xiaoheihe': '小黑盒', 'tv.danmaku.bili': 'B站', 'com.sina.weibo': '微博', 'com.xingin.xhs': '小红书', 'com.zhihu.android': '知乎', 'com.ss.android.ugc.aweme': '抖音', 'com.coolapk.market': '酷安', 'com.baidu.tieba': '贴吧', 'com.douban.frodo': '豆瓣', 'com.taobao.taobao': '淘宝', 'com.eg.android.AlipayGphone': '支付宝', 'org.telegram.messenger': 'Telegram', 'com.android.chrome': 'Chrome' };
59
+ const appName = (pkg) => APP[pkg] ?? String(pkg ?? '').split('.').pop() ?? '';
60
+ const PLAY_KEY = { like: 'like', comment: 'comment', follow: 'follow', collect: 'sticker' };
61
+ const PHASE = { advance: 'advance', 'follow-up': 'follow-up', intent: 'intent', seed: 'seed' };
62
+
63
+ /**
64
+ * Turn the records into scenes, newest first.
65
+ * @param {object} src - parsed records: audit (computer+phone audit), qq, transcript, interludeCalls, script, memoryCalls, diary.
66
+ * @param {object} opts - now, limit, days, busy(session) → bool, isErrand(session) → bool.
67
+ * Each scene: { at, end, session, source: { kind, name? }, status: 'running'|'done'|'failed', trigger?,
68
+ * actions: [{ k, text, via? }], stats: { tools, model, in, out } }. Action and source kinds are keys;
69
+ * the page words them (zh/en).
70
+ */
71
+ export function buildScenes(src, { now = Date.now(), limit = DEFAULT_SCENES, days = 3, busy = () => false, isErrand = () => false } = {}) {
72
+ const since = now - days * DAY;
73
+ const ev = [];
74
+ const push = (t, type, e) => { if (t >= since && t <= now + 60000) ev.push({ t, type, e }); };
75
+ for (const e of src.audit ?? []) push(timeOf(e.ts), e.kind === 'dot' || e.kind === 'interlude' || e.kind === 'memory' ? `${e.kind}:${e.event}` : e.kind, e);
76
+ for (const e of src.qq ?? []) push(timeOf(e.ts), `qq:${e.kind}`, e);
77
+ for (const e of src.transcript ?? []) push(timeOf(e.at), `tr:${e.who}`, e);
78
+ for (const e of src.interludeCalls ?? []) push(timeOf(e.ts), String(e.phase ?? '').endsWith(':refresh') ? 'ic:refresh' : 'ic:round', e);
79
+ for (const e of src.memoryCalls ?? []) if (/daily|diary/.test(String(e.reason ?? ''))) push(timeOf(e.at), 'mc:diary', e);
80
+ ev.sort((a, b) => a.t - b.t);
81
+ const qqAudited = (src.qq ?? []).length > 0;
82
+ // qq.js audits a message as { kind: 'message', ...msg }: msg.kind wins, so the line's kind is private / group.
83
+ const qqMessages = ev.filter((x) => ['qq:private', 'qq:group', 'qq:message'].includes(x.type));
84
+ const phoneNotes = ev.filter((x) => x.type === 'notification');
85
+ const scripts = (src.script ?? []).map((s) => ({ t: headTime(s.head), text: s.text, phase: s.head.split('·').pop().trim() }));
86
+ const diary = new Map((src.diary ?? []).map((d) => [d.head.slice(0, 10), d.text]));
87
+
88
+ const scenes = [];
89
+ const open = (t, session, source, extra = {}) => {
90
+ const s = { at: t, end: t, session: session || '', source, status: 'done', trigger: '', actions: [], stats: { tools: 0, model: 0, in: 0, out: 0 }, ...extra };
91
+ scenes.push(s); return s;
92
+ };
93
+ const recent = (t, pred = () => true, win = WINDOW) => { for (let i = scenes.length - 1; i >= 0; i--) { const s = scenes[i]; if (s.at <= t + 3000 && t - s.end <= win && pred(s)) return s; if (t - s.end > DAY) break; } return null; };
94
+ const sameWake = (t, session, kinds) => recent(t, (s) => s.session === session && kinds.includes(s.source.kind) && Math.abs(t - s.at) <= MERGE, MERGE);
95
+ const act = (s, k, text, extra = {}) => {
96
+ if (!s) return;
97
+ const body = clip(text);
98
+ const key = body.replace(/[\s/·,。,.!?!?]/g, '').slice(0, 24);
99
+ if (key && s.actions.some((a) => a.key === key)) return; // one thing seen in two records (QQ relay + transcript)
100
+ s.actions.push({ k, text: body, key, ...extra });
101
+ };
102
+ const touch = (s, t) => { if (s && t > s.end) s.end = t; };
103
+ const nearBefore = (list, t, pred, win = 120000) => { for (let i = list.length - 1; i >= 0; i--) { const x = list[i]; if (x.t > t + 2000) continue; if (t - x.t > win) return null; if (pred(x.e)) return x.e; } return null; };
104
+ const qqSource = (m) => (m.kind === 'group' ? { kind: 'qq', name: `群 ${m.groupId} · ${m.who}` } : { kind: 'qq', name: m.who || m.userId });
105
+
106
+ for (const { t, type, e } of ev) {
107
+ switch (type) {
108
+ // ── wakes ──
109
+ case 'tr:owner': case 'dot:owner-message': {
110
+ const s = sameWake(t, e.session, ['owner']) ?? open(t, e.session, { kind: 'owner' });
111
+ if (type === 'tr:owner') s.trigger ||= clip(e.text);
112
+ else { const m = nearBefore(qqMessages, t, (x) => x.fromOwner); if (m) { s.viaQq = true; s.trigger ||= clip(m.text); } }
113
+ touch(s, t); break;
114
+ }
115
+ case 'dot:notification-woke': {
116
+ const pkgs = [].concat(e.pkgs ?? []);
117
+ let s = sameWake(t, e.session, ['notify']);
118
+ if (!s) {
119
+ const qqMsg = pkgs.includes('qq') ? nearBefore(qqMessages, t, (x) => !x.fromOwner) : null;
120
+ const note = !qqMsg ? nearBefore(phoneNotes, t, (x) => pkgs.includes(x.pkg)) : null;
121
+ s = open(t, e.session, qqMsg ? qqSource(qqMsg) : { kind: 'phone', name: appName(pkgs[0]) });
122
+ s.source.kind = qqMsg ? 'qq' : 'phone';
123
+ s.wakeKind = 'notify';
124
+ if (qqMsg) { s.trigger = clip(qqMsg.text); s.viaQq = true; } else if (note) s.trigger = clip(`${note.title ? `${note.title}:` : ''}${note.text ?? ''}`);
125
+ if (e.count > 1) s.count = e.count;
126
+ }
127
+ touch(s, t); break;
128
+ }
129
+ case 'tr:phone': {
130
+ // The notification as her conversation read it; joins the wake it belongs to.
131
+ const s = recent(t, (x) => x.session === e.session && x.wakeKind === 'notify' && Math.abs(t - x.at) <= MERGE, MERGE);
132
+ const text = String(e.text ?? '').replace(/^\[手机通知\]\s*/, '');
133
+ if (s) { s.trigger ||= clip(text); touch(s, t); break; }
134
+ const m = /^(\S+?)\s*·\s*([^::]+)[::]/.exec(text);
135
+ const n = open(t, e.session, m?.[1] === 'QQ' ? { kind: 'qq', name: m[2].trim() } : { kind: 'phone', name: m?.[1] ?? '' }, { wakeKind: 'notify' });
136
+ n.trigger = clip(m ? text.slice(m[0].length) : text); break;
137
+ }
138
+ case 'dot:phone-check': open(t, e.session, { kind: 'check' }); break;
139
+ case 'tr:schedule': { const s = open(t, e.session, { kind: 'schedule' }); s.trigger = clip(e.text); break; }
140
+ case 'ic:round': {
141
+ const sc = scripts.find((x) => Math.abs(x.t - Math.floor(t / 60000) * 60000) < 60000 && (!x.phase || x.phase === e.phase)) ?? scripts.find((x) => Math.abs(x.t - t) < 120000);
142
+ const s = open(t, 'interlude', { kind: 'interlude', name: PHASE[e.phase] ?? e.phase ?? '' }, { round: true, roundOpen: true });
143
+ s.stats.model = 1; s.stats.in = (e.usage?.in ?? 0) + (e.usage?.cached ?? 0); s.stats.out = e.usage?.out ?? 0;
144
+ if (sc) act(s, 'interlude', firstSentence(sc.text));
145
+ break;
146
+ }
147
+ case 'interlude:play': {
148
+ const s = open(t, e.session, { kind: 'play', name: e.app ?? '' });
149
+ s.trigger = clip(e.why ?? '');
150
+ act(s, PLAY_KEY[e.action] ?? 'play', `${e.app ?? ''} · ${e.target ?? ''}`);
151
+ break;
152
+ }
153
+ case 'mc:diary': {
154
+ const text = diary.get(localDay(t));
155
+ if (!text) break;
156
+ const s = open(t, 'memory', { kind: 'schedule', name: 'diary' });
157
+ s.stats.model = 1; s.stats.in = e.usage?.in ?? 0; s.stats.out = e.usage?.out ?? 0;
158
+ act(s, 'diary', text);
159
+ break;
160
+ }
161
+ // ── what she did ──
162
+ case 'ic:refresh': { const s = recent(t, (x) => x.round, 30 * 60000); if (s) { s.stats.model++; s.stats.in += (e.usage?.in ?? 0) + (e.usage?.cached ?? 0); s.stats.out += e.usage?.out ?? 0; } break; }
163
+ case 'interlude:round': { const s = recent(t, (x) => x.roundOpen, 30 * 60000); if (s) { s.roundOpen = false; touch(s, t); } break; }
164
+ case 'interlude:round-failed': { const s = recent(t, (x) => x.roundOpen, 30 * 60000); if (s) { s.roundOpen = false; s.status = 'failed'; touch(s, t); } break; }
165
+ case 'interlude:browse': {
166
+ const s = recent(t, (x) => x.round, 30 * 60000) ?? recent(t);
167
+ act(s, 'look', e.query ?? '', { via: e.via === 'web' ? 'web' : e.via === 'phone' ? 'phone' : 'computer' }); touch(s, t); break;
168
+ }
169
+ case 'qq:sent': {
170
+ const s = recent(t, (x) => x.roundOpen, 30 * 60000) ?? recent(t, (x) => !x.round && !isErrand(x.session)) ?? open(t, '', { kind: 'qq', name: e.to?.group_id ? `群 ${e.to.group_id}` : String(e.to?.user_id ?? '') });
171
+ const images = [].concat(e.images ?? []);
172
+ if (e.text) act(s, s.round ? 'contact' : 'qq', e.text);
173
+ if (images.length) act(s, 'image', images.join(' '));
174
+ touch(s, t); break;
175
+ }
176
+ case 'qq:sticker-kept': {
177
+ const s = recent(t, (x) => !x.round) ?? open(t, '', { kind: 'qq', name: e.from === 'self' ? '' : e.from });
178
+ act(s, 'sticker', e.from === 'self' ? (e.note || e.id) : `${e.from} · ${e.id}`); touch(s, t); break;
179
+ }
180
+ case 'tr:note': {
181
+ // What an errand found, left in her conversation: belongs to the errand scene that just ended.
182
+ const s = recent(t, (x) => (isErrand(x.session) || ['check', 'play'].includes(x.source.kind) || (x.wakeKind === 'notify' && x.session !== e.session)) && x.session !== e.session, 15 * 60000)
183
+ ?? recent(t, (x) => x.session === e.session);
184
+ act(s, 'saw', String(e.text ?? '').replace(/^\[[^\]]*\]\s*/, '')); touch(s, t); break;
185
+ }
186
+ case 'tr:her': {
187
+ if (e.to && qqAudited) break; // her qq_send: the QQ audit has it
188
+ const s = recent(t, (x) => x.session === e.session);
189
+ act(s, s?.viaQq || e.to ? 'qq' : 'reply', e.text); touch(s, t); break;
190
+ }
191
+ case 'tool': { const s = recent(t, (x) => x.session === e.session); if (s) { s.stats.tools++; touch(s, t); } break; }
192
+ case 'approval-asked': case 'qq:approval-asked': {
193
+ const s = recent(t, (x) => x.session === e.session) ?? recent(t);
194
+ const tool = String(e.tool ?? '');
195
+ if (/install_app/.test(tool)) act(s, 'install', tool.replace(/^.*__/, ''));
196
+ else act(s, 'approval', `${tool.replace(/^.*__/, '')}${e.reason ? ` · ${String(e.reason).split('\n')[0]}` : ''}`);
197
+ touch(s, t); break;
198
+ }
199
+ case 'dot:silent': { const s = recent(t, (x) => x.session === e.session); if (s) { s.quiet = true; touch(s, t); } break; }
200
+ default:
201
+ }
202
+ }
203
+ // Status: a scene is running while its session is in a turn and it is that session's latest, or while its round has not closed.
204
+ const latest = new Map();
205
+ for (const s of scenes) latest.set(s.session, s);
206
+ for (const s of scenes) {
207
+ if (s.status === 'failed') continue;
208
+ if (s.round ? s.roundOpen && now - s.at < 15 * 60000 : s.session && latest.get(s.session) === s && busy(s.session)) s.status = 'running';
209
+ }
210
+ return scenes.slice(-limit).reverse().map(({ at, end, session, source, status, trigger, actions, stats, quiet, count }) => ({
211
+ at, end, session, source, status, ...(trigger ? { trigger } : {}), ...(quiet && !actions.length ? { quiet: true } : {}), ...(count ? { count } : {}),
212
+ actions: actions.slice(0, 20).map(({ key, ...a }) => { void key; return a; }), stats,
213
+ }));
214
+ }
215
+
216
+ /** Reads the records (tails, cached by size+mtime) and builds the scenes. */
217
+ export function createActivity({ dshHome, home, maxBytes = 1 << 20, days = 3 }) {
218
+ const cache = new Map();
219
+ const load = (file, parse, bytes = maxBytes) => {
220
+ let st;
221
+ try { st = statSync(file); } catch (error) { void error; cache.delete(file); return parse([]); }
222
+ let rot = 0;
223
+ try { rot = statSync(`${file}.1`).mtimeMs; } catch (error) { void error; }
224
+ const sig = `${st.size}:${st.mtimeMs}:${rot}`;
225
+ const hit = cache.get(file);
226
+ if (hit?.sig === sig) return hit.value;
227
+ const value = parse(tailLines(file, bytes));
228
+ cache.set(file, { sig, value });
229
+ return value;
230
+ };
231
+ const dsh = (n) => join(dshHome, n);
232
+ const md = (lines) => sections(lines.join('\n'));
233
+ return {
234
+ read() {
235
+ return {
236
+ audit: [...load(dsh('dsh-computer-audit.jsonl'), parseJsonl), ...load(dsh('dsh-phone-audit.jsonl'), parseJsonl)],
237
+ qq: load(dsh('dsh-qq-audit.jsonl'), parseJsonl),
238
+ transcript: load(join(home, 'memory', 'transcript.jsonl'), parseJsonl),
239
+ memoryCalls: load(join(home, 'memory', 'calls.jsonl'), parseJsonl, maxBytes / 4),
240
+ diary: load(join(home, 'memory', 'diary.md'), md, 64 << 10),
241
+ interludeCalls: load(join(home, 'interlude', 'calls.jsonl'), parseJsonl),
242
+ script: load(join(home, 'interlude', 'script.md'), md, 256 << 10),
243
+ };
244
+ },
245
+ scenes(opts = {}) { return buildScenes(this.read(), { days, ...opts }); },
246
+ };
247
+ }
package/src/dot/core.js CHANGED
@@ -18,6 +18,7 @@ import { homedir } from 'node:os';
18
18
  import { join, relative, isAbsolute } from 'node:path';
19
19
  import { createUserMessage } from '@deepseek-ai/dsh-llm';
20
20
  import { mountPanel } from './panel.js';
21
+ import { sectionOf, setValues } from '../settings.js';
21
22
 
22
23
  export const name = 'dsh-dot';
23
24
  // Devices are optional components: the computer (dshComputer) and the phone (dshPhone). dot works
@@ -207,8 +208,9 @@ export function createNotifier(getIm, cfg, logger, getQq = () => undefined) {
207
208
 
208
209
  export function apply(ctx, config = {}) {
209
210
  // An empty string means "not set", except for notifyHours, where '' is documented as "always".
210
- const cfg = { ...defaults, ...Object.fromEntries(Object.entries(config).filter(([k, v]) => v !== undefined && (v !== '' || k === 'notifyHours'))) };
211
211
  const logger = ctx.logger('dsh-dot');
212
+ const cfg = { ...defaults, ...setValues(config, { keepEmpty: ['notifyHours'] }), ...sectionOf('dot', (m) => logger.warn(m)) };
213
+ if (cfg.enabled === false) { logger.info('off (dsh-dot.json: dot.enabled = false)'); return; }
212
214
  const computer = () => ctx.get('dshComputer');
213
215
  const phone = () => ctx.get('dshPhone');
214
216
  const audit = (event, data = {}) => (computer()?.audit ?? phone()?.audit)?.({ kind: 'dot', event, ...data });
@@ -239,7 +241,26 @@ export function apply(ctx, config = {}) {
239
241
  // "latest session" (his QQ message then goes into an archived errand and he never gets an answer).
240
242
  const pastErrands = new Set(store.get('pastErrands') ?? []);
241
243
  const isErrand = (id) => Boolean(id) && (id === errandId || pastErrands.has(id));
242
- if (isErrand(lastSession)) { lastSession = ''; store.set('lastSession', ''); }
244
+ // Startup self-check: the remembered pointer must be a live conversation of hers. An old state file
245
+ // can point at an errand or at a session archived since (11-03: his QQ messages went into an
246
+ // archived errand and nobody answered). What dsh cannot tell us (no registry yet, no title) is skipped.
247
+ const staleWhy = (id) => {
248
+ if (!id) return '';
249
+ if (isErrand(id)) return 'errand';
250
+ try { if (/跑腿/.test(String(ctx.get('agents')?.get?.(id)?.session?.header?.title ?? ''))) return 'errand title'; } catch (error) { void error; }
251
+ try { const ids = ctx.get('workspaceRegistry')?.archivedSessionIds; if ((Array.isArray(ids) || ids instanceof Set) && [...ids].includes(id)) return 'archived'; } catch (error) { void error; }
252
+ return '';
253
+ };
254
+ const selfCheck = () => {
255
+ const why = staleWhy(lastSession);
256
+ if (!why) return;
257
+ audit('last-session-cleared', { session: lastSession, why });
258
+ logger.warn(`her remembered conversation ${lastSession} is ${why === 'archived' ? 'archived' : 'an errand'}: cleared (the next message to her picks a new one)`);
259
+ lastSession = ''; store.set('lastSession', '');
260
+ };
261
+ selfCheck();
262
+ // The registry can come up after dot: look again once it is there.
263
+ ctx.inject?.(['workspaceRegistry'], (c) => c.effect(() => { selfCheck(); return () => {}; }, 'dsh-dot: startup self-check'));
243
264
  async function ensureErrand() {
244
265
  if (!cfg.errands) return '';
245
266
  if (errandId) return errandId;