dsh-dot-life 0.12.1 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -93,7 +93,7 @@ Web 版:`dsh plugin --profile web add dsh-dot-life`。从源码装:把包名
93
93
  | `~/.dsh/phone/` | 模拟器、platform-tools、系统镜像、AVD(`avd/dot.avd/`);`~/.dsh/dsh-phone.log` 日志、`dsh-phone-audit.jsonl` 审计、`dsh-phone.json` 设置 |
94
94
  | `~/.dsh/dsh-computer*` | 电脑的日志、审计、状态 |
95
95
  | `/phone [accept\|restart\|screenshot]` · `/interlude [now\|advance\|seed\|preset <code>\|canon]` · `/dot [test\|check]` · `/dot memory [now\|diary\|handoff\|recall …]` · `/dot people [approve <id>\|drop <id>\|forget <名字>]` | 各组件的状态和操作 |
96
- | 右侧栏 **dot** 标签页(会话顶部 ◎ 按钮) | 一页看全:手机 / 电脑 QQ / 电脑 状态、她的对话交班进度、她此刻在做什么和打算、今天的轮数 / 玩 / 去看 / 叫醒 / token、记忆用量、日记、最近两段剧本。只读,3 秒刷新;页面由 `dsh-dot/dot` 挂在 dsh 自己的 web server 上(`/dsh-dot/panel/`),不开新端口 |
96
+ | 右侧栏 **dot** 标签页(会话顶部 ◎ 按钮) | 一页看全:手机 / 电脑 QQ / 电脑 状态、她的对话交班进度、她此刻在做什么和打算、今天的轮数 / 玩 / 去看 / 叫醒 / token、**最近 30 场**(每次被叫醒到那轮结束是一场:时间 · 进行中/完成 · 来源〔你 / QQ 某人 / 手机·某 App / 拿手机 / 幕间 / 定时 / 玩〕,展开是这一场做的事——回 QQ、发图、存表情、看了、点赞、写日记、去看、主动联系、审批……每条带她的原话,底部是工具 / 模型次数和 token;全部从已有的审计、记录尾部读出,不另写文件)、记忆用量、日记、最近两段剧本。只读,3 秒刷新;页面由 `dsh-dot/dot` 挂在 dsh 自己的 web server 上(`/dsh-dot/panel/`),不开新端口 |
97
97
  | 安全边界 | 手机实时画面与控制(`/dsh-dot/phone/`)和 dot 面板都挂在 dsh 的 web server 上,每个请求先过 dsh 的 `connection` 服务(dsh 登录态 + Host/Origin 围栏,不信任任何转发头)——插件不自带鉴权、不开自己的端口。电脑的实时桌面同样挂在 dsh 的 web server 上(`/dsh-dot/computer/`,含 VNC 的 WebSocket),由插件带密钥中继给虚拟机网关;网关端口(`127.0.0.1:18080`)只绑本机回环且要求密钥(`SANDBOX_API_KEY`,每台机器自动生成在 `~/.dsh/dsh-computer.key`),只有插件内部持有。若要从外面看,请暴露 dsh 本身而不是这个端口 |
98
98
 
99
99
  dot 的通知相关:`notifyBatchMs`(1 秒内的通知合成一次叫醒)、`notifyHours`(可选的静音时段,默认不设:任何时候来通知都叫醒她);她正在跑一轮时来的通知会攒到那轮结束,同一个对话的多条按顺序列出,一次叫醒。每个组件的配置项见各自的文档:[phone](docs/phone.md)、[interlude](docs/interlude.md)、[computer](docs/computer.md);dot 自己只有 `home`、`scope`、`imBot` / `imTarget`、`autoUnblockDaily`。
package/docs/DESIGN.md CHANGED
@@ -209,3 +209,9 @@ Kevin:"感觉现在很难给他长任务。他很容易直接结束然后就
209
209
 
210
210
  **手机存储**:她 8 GB 数据分区满了;改 `disk.dataPartition.size` 不会扩大已有分区(实测)。新手机默认 16 GB,建之前可选(`/phone accept <GB>`、`/phone size <GB>`)。
211
211
 
212
+
213
+ ## v0.12.3(2026-11-03):面板「最近 30 场」、启动自检、mface 表情
214
+
215
+ - **最近 N 场**(`src/dot/activity.js`,参照别家养鱼面板的"按场列表"):一场 = 一次叫醒到那轮结束(他的话、QQ / 手机通知、拿手机、幕间一轮、定时任务、玩、每天的日记),按会话 + 时间窗把已有记录拼起来——dot / interlude / memory 审计、QQ 审计(`private`/`group`、`sent`、`sticker-kept`)、memory 的 transcript / calls / diary、幕间的 calls / script。不新增任何写入;每个文件只读尾部(最近 3 天、至多 1 MB,审计含 `.1`),按 size+mtime 缓存,面板 3 秒一轮也只做几次 `stat`。每场:时间 · 进行中/完成/出错 · 来源,展开是动作(短标签 + 她的原话,截 80 字)和工具 / 模型次数 / token(只有幕间和日记的 token 有记录)。
216
+ - **启动自检**:`lastSession` 指向跑腿(在 pastErrands、或标题含"跑腿")或已归档(`workspaceRegistry.archivedSessionIds`)就清空并记 `last-session-cleared`;查不到的跳过。起因:11-03 旧状态文件指向已归档的跑腿,他的 QQ 消息投进去没人回。
217
+ - **mface**:QQ 自带大表情的 summary 是 `[?]`、`[doge]`,没有"表情"二字,原来没被当表情包存;短方括号(1–8 字,`[图片]` 除外)也算。
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.1",
3
+ "version": "0.12.3",
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",
@@ -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
@@ -239,7 +239,26 @@ export function apply(ctx, config = {}) {
239
239
  // "latest session" (his QQ message then goes into an archived errand and he never gets an answer).
240
240
  const pastErrands = new Set(store.get('pastErrands') ?? []);
241
241
  const isErrand = (id) => Boolean(id) && (id === errandId || pastErrands.has(id));
242
- if (isErrand(lastSession)) { lastSession = ''; store.set('lastSession', ''); }
242
+ // Startup self-check: the remembered pointer must be a live conversation of hers. An old state file
243
+ // can point at an errand or at a session archived since (11-03: his QQ messages went into an
244
+ // archived errand and nobody answered). What dsh cannot tell us (no registry yet, no title) is skipped.
245
+ const staleWhy = (id) => {
246
+ if (!id) return '';
247
+ if (isErrand(id)) return 'errand';
248
+ try { if (/跑腿/.test(String(ctx.get('agents')?.get?.(id)?.session?.header?.title ?? ''))) return 'errand title'; } catch (error) { void error; }
249
+ try { const ids = ctx.get('workspaceRegistry')?.archivedSessionIds; if ((Array.isArray(ids) || ids instanceof Set) && [...ids].includes(id)) return 'archived'; } catch (error) { void error; }
250
+ return '';
251
+ };
252
+ const selfCheck = () => {
253
+ const why = staleWhy(lastSession);
254
+ if (!why) return;
255
+ audit('last-session-cleared', { session: lastSession, why });
256
+ logger.warn(`her remembered conversation ${lastSession} is ${why === 'archived' ? 'archived' : 'an errand'}: cleared (the next message to her picks a new one)`);
257
+ lastSession = ''; store.set('lastSession', '');
258
+ };
259
+ selfCheck();
260
+ // The registry can come up after dot: look again once it is there.
261
+ ctx.inject?.(['workspaceRegistry'], (c) => c.effect(() => { selfCheck(); return () => {}; }, 'dsh-dot: startup self-check'));
243
262
  async function ensureErrand() {
244
263
  if (!cfg.errands) return '';
245
264
  if (errandId) return errandId;
package/src/dot/panel.js CHANGED
@@ -1,17 +1,35 @@
1
1
  // dsh-dot/dot panel: one read-only page about her — devices, where her life stands, today's
2
- // numbers, what she remembers, her diary, the last two passages of her script — served on dsh's
2
+ // numbers, the last N scenes of her life (activity.js), what she remembers, her diary, the last two
3
+ // passages of her script — served on dsh's
3
4
  // own web server (`/dsh-dot/panel/`), so the "dot" sidebar tab is an iframe of the same origin and
4
5
  // nothing new listens on a port. The page is one file with no dependencies, like the phone's live
5
6
  // view; it polls `/dsh-dot/panel/api/state` every 3 s while visible. The layout follows what the
6
7
  // companion consoles around dsh show (NimuQDock's overview row, qq-bridge's number tiles,
7
8
  // companion-core's diary list); nothing here can change her — actions stay in /dot, /interlude.
8
9
 
10
+ import { homedir } from 'node:os';
11
+ import { join } from 'node:path';
9
12
  import { rejectUnlessOwner } from '../web-auth.js';
13
+ import { createActivity, DEFAULT_SCENES } from './activity.js';
10
14
 
11
15
  export const PANEL_PATH = '/dsh-dot/panel'; // the phone's live view is /dsh-dot/phone; prefixes must not nest
12
16
 
13
- /** Everything the page shows, gathered from the services that exist right now. */
14
- export async function collectState(ctx) {
17
+ // One reader per (DSH_HOME, home): it caches each file's parsed tail until the file changes.
18
+ const readers = new Map();
19
+ function activityOf(dot, opts = {}) {
20
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh');
21
+ const home = dot?.home || join(homedir(), 'dot');
22
+ const key = `${dshHome}\0${home}`;
23
+ if (!readers.has(key)) readers.set(key, createActivity({ dshHome, home }));
24
+ return readers.get(key).scenes({
25
+ limit: Math.max(1, Math.min(100, Number(opts.scenes) || DEFAULT_SCENES)),
26
+ busy: (id) => Boolean(dot?.busy?.(id)),
27
+ isErrand: (id) => Boolean(dot?.isErrand?.(id)),
28
+ });
29
+ }
30
+
31
+ /** Everything the page shows, gathered from the services that exist right now. `opts.scenes`: how many scenes (default 30). */
32
+ export async function collectState(ctx, opts = {}) {
15
33
  const get = (n) => { try { return ctx.get(n); } catch (error) { void error; return undefined; } };
16
34
  const dot = get('dshDot');
17
35
  const phone = get('dshPhone');
@@ -30,6 +48,8 @@ export async function collectState(ctx) {
30
48
  dot: dot ? { session: dot.session?.() || '', errand: dot.errandId?.() || '', today: dot.stats?.() ?? null } : null,
31
49
  interlude: interlude ? await safe(() => interlude.status()) : null,
32
50
  memory: memory ? await safe(() => memory.panel()) : null,
51
+ // The last N scenes (one wake until its turn ended), read back from the records that exist.
52
+ activity: await safe(() => ({ scenes: activityOf(dot, opts) })),
33
53
  };
34
54
  }
35
55
 
@@ -55,10 +75,23 @@ h2{font-size:12px;font-weight:600;color:var(--mute);margin:0 0 6px;letter-spacin
55
75
  ul{margin:4px 0;padding-left:18px}li{margin:2px 0}
56
76
  details summary{cursor:pointer;color:var(--mute)}
57
77
  #err{color:var(--bad)}
78
+ .scenes{display:grid;gap:4px}
79
+ .scene{border-top:1px solid var(--line);padding-top:4px}.scene:first-child{border-top:0;padding-top:0}
80
+ .scene>summary{list-style:none;display:grid;grid-template-columns:minmax(96px,34%) 1fr;gap:8px;align-items:baseline;color:var(--fg)}
81
+ .scene>summary::-webkit-details-marker{display:none}
82
+ .smeta{display:flex;flex-wrap:wrap;gap:4px;align-items:baseline;min-width:0}.smeta b{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:100%}
83
+ .sprev{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
84
+ .st{font-size:11px;padding:0 6px;border-radius:999px;border:1px solid var(--line);color:var(--mute)}.st.run{color:var(--ok);border-color:var(--ok)}.st.fail{color:var(--bad);border-color:var(--bad)}
85
+ .tag{display:inline-block;font-size:11px;padding:0 5px;margin-right:4px;border-radius:4px;background:var(--line);color:var(--fg);white-space:nowrap}
86
+ .sbody{margin:4px 0 6px;padding-left:8px;border-left:2px solid var(--line)}
87
+ .acts{list-style:none;padding:0;margin:2px 0}.acts li{margin:3px 0;word-break:break-word}
88
+ .sfoot{font-size:11px;color:var(--mute)}
89
+ h2 select{float:right;font:inherit;font-size:11px;background:var(--card);color:var(--mute);border:1px solid var(--line);border-radius:4px}
58
90
  </style></head><body><main>
59
91
  <div class="row" id="badges"></div>
60
92
  <div class="card"><h2>她现在</h2><div id="now"></div></div>
61
93
  <div class="card"><h2>今天</h2><div class="tiles" id="today"></div></div>
94
+ <div class="card"><h2><span id="actTitle">最近 30 场</span><select id="actN" aria-label="scenes"><option>10</option><option selected>30</option><option>60</option><option>100</option></select></h2><div class="scenes" id="activity"></div></div>
62
95
  <div class="card"><h2>记忆</h2><div id="memory"></div></div>
63
96
  <div class="card"><h2>日记</h2><div id="diary"></div></div>
64
97
  <div class="card"><h2>剧本</h2><div id="script"></div></div>
@@ -73,6 +106,44 @@ const at=(ms)=>ms?new Date(ms).toLocaleString('zh-CN',{month:'numeric',day:'nume
73
106
  const badge=(cls,label,text)=>'<span class="badge '+cls+'"><i class="dotc"></i>'+esc(label)+(text?' <span class="mute">'+esc(text)+'</span>':'')+'</span>';
74
107
  const tile=(n,label)=>'<div class="tile"><b>'+esc(n)+'</b><span>'+esc(label)+'</span></div>';
75
108
  const bar=(v,max)=>'<div class="bar"><i style="width:'+Math.min(100,Math.round(100*(v||0)/(max||1)))+'%"></i></div>';
109
+ const ZH=/^zh/i.test(navigator.language||'zh');
110
+ const T=ZH?{title:(n)=>'最近 '+n+' 场',none:'还没有记录(她被叫醒、幕间、玩过之后这里会出现)',run:'进行中',done:'完成',fail:'出错',quiet:'没出声',tools:'工具',model:'模型',times:' 次',tin:'token 入',tout:'出',
111
+ src:{owner:'你',qq:'QQ',phone:'手机',check:'拿手机',interlude:'幕间',schedule:'定时',play:'玩'},
112
+ phase:{advance:'推进','follow-up':'跟进',intent:'打算到点',seed:'开场',diary:'日记'},
113
+ act:{qq:'回 QQ',reply:'回你',image:'发图',sticker:'存表情',saw:'看了',like:'点赞',comment:'评论',follow:'关注',play:'玩',install:'装 App',diary:'写日记',interlude:'幕间',contact:'主动联系',approval:'审批',look:'去看'},
114
+ via:{web:'web',phone:'手机',computer:'电脑'}}
115
+ :{title:(n)=>'Last '+n+' scenes',none:'Nothing yet (scenes appear once she is woken, has an interlude round, or plays)',run:'running',done:'done',fail:'failed',quiet:'stayed quiet',tools:'tools',model:'model',times:'×',tin:'tokens in',tout:'out',
116
+ src:{owner:'You',qq:'QQ',phone:'Phone',check:'Picked up phone',interlude:'Interlude',schedule:'Scheduled',play:'Play'},
117
+ phase:{advance:'advance','follow-up':'follow-up',intent:'intent',seed:'seed',diary:'diary'},
118
+ act:{qq:'QQ reply',reply:'Replied',image:'Image',sticker:'Kept sticker',saw:'Saw',like:'Like',comment:'Comment',follow:'Follow',play:'Play',install:'Install app',diary:'Diary',interlude:'Interlude',contact:'Reached out',approval:'Approval',look:'Looked'},
119
+ via:{web:'web',phone:'phone',computer:'computer'}};
120
+ let sceneN=30;try{sceneN=+localStorage.getItem('dot.scenes')||30}catch(e){}
121
+ const openScenes=new Set();
122
+ const srcLabel=(src)=>{const k=T.src[src.kind]||src.kind||'';if(!src.name)return k;if(src.kind==='phone')return k+'·'+src.name;if(src.kind==='interlude'||src.kind==='schedule')return k+' · '+(T.phase[src.name]||src.name);if(src.kind==='play')return k+' · '+src.name;return k+' '+src.name;};
123
+ const actLabel=(a)=>(T.act[a.k]||a.k)+(a.k==='look'&&a.via?'('+(T.via[a.via]||a.via)+')':'');
124
+ function renderActivity(act){
125
+ $('actTitle').textContent=T.title(sceneN);
126
+ const list=act&&act.scenes;
127
+ if(act&&act.error){$('activity').innerHTML='<span class="mute">'+esc(act.error)+'</span>';return}
128
+ if(!list||!list.length){$('activity').innerHTML='<span class="mute">'+esc(T.none)+'</span>';return}
129
+ $('activity').innerHTML=list.map((sc)=>{
130
+ const id=sc.at+'|'+sc.session+'|'+sc.source.kind;
131
+ const st=sc.status==='running'?'<span class="st run">'+T.run+'</span>':sc.status==='failed'?'<span class="st fail">'+T.fail+'</span>':'<span class="st">'+T.done+'</span>';
132
+ const first=sc.actions[0];
133
+ const prev=first?'<span class="tag">'+esc(actLabel(first))+'</span>'+esc(first.text)+(sc.actions.length>1?' <span class="mute">+'+(sc.actions.length-1)+'</span>':''):'<span class="mute">'+esc(sc.quiet?T.quiet:(sc.trigger||''))+'</span>';
134
+ const f=sc.stats||{},foot=[];
135
+ if(f.tools)foot.push(T.tools+' '+f.tools+T.times);
136
+ if(f.model)foot.push(T.model+' '+f.model+T.times);
137
+ if(f.in||f.out)foot.push(T.tin+' '+fmt(f.in)+' / '+T.tout+' '+fmt(f.out));
138
+ let body='';
139
+ if(sc.trigger)body+='<div class="mute">「'+esc(sc.trigger)+'」'+(sc.count>1?' ×'+sc.count:'')+'</div>';
140
+ if(sc.actions.length)body+='<ul class="acts">'+sc.actions.map((a)=>'<li><span class="tag">'+esc(actLabel(a))+'</span>'+esc(a.text)+'</li>').join('')+'</ul>';
141
+ else if(sc.quiet)body+='<div class="mute">'+esc(T.quiet)+'</div>';
142
+ if(foot.length)body+='<div class="sfoot">'+esc(foot.join(' · '))+'</div>';
143
+ return '<details class="scene" data-id="'+esc(id)+'"'+(openScenes.has(id)?' open':'')+'><summary><span class="smeta"><span class="mute">'+esc(at(sc.at))+'</span>'+st+'<b>'+esc(srcLabel(sc.source))+'</b></span><span class="sprev">'+prev+'</span></summary><div class="sbody">'+(body||'<span class="mute">—</span>')+'</div></details>';
144
+ }).join('');
145
+ }
146
+ document.addEventListener('toggle',(e)=>{const d=e.target;if(!d.classList||!d.classList.contains('scene'))return;if(d.open)openScenes.add(d.dataset.id);else openScenes.delete(d.dataset.id);},true);
76
147
  function render(s){
77
148
  const d=s.devices||{}, it=s.interlude, m=s.memory, dot=s.dot;
78
149
  let b='';
@@ -119,13 +190,15 @@ function render(s){
119
190
  if(it&&it.script&&it.script.length){
120
191
  $('script').innerHTML=it.script.slice().reverse().map(e=>'<div style="margin-bottom:8px"><b class="mute">'+esc(e.head)+'</b><div class="pre">'+esc(e.text)+'</div></div>').join('');
121
192
  } else $('script').innerHTML='<span class="mute">还没有剧本</span>';
193
+ renderActivity(s.activity);
122
194
  $('foot').textContent='更新于 '+new Date(s.at).toLocaleTimeString('zh-CN');
123
195
  }
124
196
  async function tick(){
125
197
  if(document.hidden) return;
126
- try{const r=await fetch('api/state',{cache:'no-store'});if(!r.ok)throw new Error('HTTP '+r.status);render(await r.json());$('err').textContent='';}
198
+ try{const r=await fetch('api/state?scenes='+sceneN,{cache:'no-store'});if(!r.ok)throw new Error('HTTP '+r.status);render(await r.json());$('err').textContent='';}
127
199
  catch(e){$('err').textContent='读取状态失败:'+e.message}
128
200
  }
201
+ $('actN').value=String(sceneN);$('actN').addEventListener('change',(e)=>{sceneN=+e.target.value||30;try{localStorage.setItem('dot.scenes',String(sceneN))}catch(err){}tick()});
129
202
  tick();setInterval(tick,3000);document.addEventListener('visibilitychange',()=>{if(!document.hidden)tick()});
130
203
  </script></body></html>`;
131
204
  }
@@ -144,7 +217,7 @@ export function mountPanel(ctx, webServer, logger, connection = ctx.get?.('conne
144
217
  if (req.method !== 'GET') { res.writeHead(405).end(); return; }
145
218
  if (sub === '' || sub === '/') { res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }).end(html); return; }
146
219
  if (sub === '/api/state') {
147
- try { res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(await collectState(ctx))); }
220
+ try { res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(await collectState(ctx, { scenes: url.searchParams.get('scenes') }))); }
148
221
  catch (err) { logger?.warn?.(`panel state failed: ${err.message}`); res.writeHead(500, { 'content-type': 'application/json' }).end(JSON.stringify({ error: err.message })); }
149
222
  return;
150
223
  }
@@ -8,8 +8,15 @@ import { dirname, join } from 'node:path';
8
8
  const MAX = 300;
9
9
  export const STICKER_MAX_BYTES = 4 * 1024 * 1024;
10
10
 
11
- /** An image segment's data → is it a sticker? (NapCat and SnowLuma both set sub_type 1 on 表情包.) */
12
- export const isSticker = (d) => String(d?.sub_type ?? '') === '1' || /表情/.test(String(d?.summary ?? ''));
11
+ /**
12
+ * An image segment's data → is it a sticker? NapCat and SnowLuma both set sub_type 1 on 表情包; QQ's
13
+ * own big stickers (mface) come as images whose summary is a short bracketed name — `[?]`, `[doge]`
14
+ * — without the word 表情. A plain picture's `[图片]` is not one.
15
+ */
16
+ export const isSticker = (d) => {
17
+ const summary = String(d?.summary ?? '').trim();
18
+ return String(d?.sub_type ?? '') === '1' || /表情/.test(summary) || (/^\[.{1,8}\]$/u.test(summary) && !/^\[(图片|image|picture|photo)\]$/i.test(summary));
19
+ };
13
20
 
14
21
  export function createStickers(file, { fetch = globalThis.fetch } = {}) {
15
22
  const dir = join(dirname(file), 'stickers');