dsh-world 0.7.5 → 0.7.6
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/CHANGELOG.md +33 -0
- package/CONTRIBUTING.md +11 -0
- package/NOTES.md +41 -2
- package/README.md +3 -2
- package/client/index.js +13 -8
- package/lib/compaction.d.ts +6 -1
- package/lib/compaction.js +8 -3
- package/lib/ecosystem/qq-native/images.d.ts +5 -1
- package/lib/ecosystem/qq-native/images.js +16 -9
- package/lib/ecosystem/qq-native/index.js +4 -4
- package/lib/ecosystem/wechat/index.d.ts +5 -0
- package/lib/ecosystem/wechat/index.js +3 -1
- package/lib/ecosystem/wechat/presence.d.ts +5 -1
- package/lib/ecosystem/wechat/presence.js +22 -13
- package/lib/elsewhere.d.ts +34 -0
- package/lib/elsewhere.js +40 -0
- package/lib/history.d.ts +5 -0
- package/lib/history.js +5 -0
- package/lib/hostContract.d.ts +6 -0
- package/lib/index.js +8 -1
- package/lib/memoryTools.d.ts +3 -2
- package/lib/memoryTools.js +10 -3
- package/lib/mood.d.ts +5 -1
- package/lib/mood.js +25 -8
- package/lib/promptSection.d.ts +2 -0
- package/lib/runtime.js +44 -17
- package/lib/sessionNews.d.ts +17 -0
- package/lib/sessionNews.js +55 -0
- package/lib/store.d.ts +6 -0
- package/lib/store.js +17 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# 更新日志
|
|
2
2
|
|
|
3
|
+
## 0.7.6 — 2026-11-15
|
|
4
|
+
|
|
5
|
+
本版让她知道别处发生了什么:新增「别处的动静」,有未读的微信群和她其他会话里的新发言,按「多少条、最后是谁、多久前」告诉她,不带正文,群会话里另有一句不把私聊内容带进群里的约束;心情快照改为每一步都放,并写着心情停了多久;QQ 商店表情和部分动图也能收;兼容 DSH 0.2.2-rc.3;控制台的心情挪进「健康」。
|
|
6
|
+
|
|
7
|
+
### 升级前请看
|
|
8
|
+
|
|
9
|
+
- **她每一步看到的内容变多了一点**:每一步末尾多一条心情快照(几十个 token),有新动静时多一条「别处的动静」。都是只往后追加,不影响前面的缓存;一百多步的一轮大约多一万 token。上下文的排法和原因见 [注意事项](NOTES.md#她每一步看到的上下文)。
|
|
10
|
+
- **群聊概况挪了位置**:有未读的微信群不再写在闹钟消息里,改由「别处的动静」在有新消息时说;闹钟上那行只留没有未读的群各安静了多久。
|
|
11
|
+
- **别处的动静从升级后开始算**:她其他会话里升级前说过的话不会一次倒给她;重启 DSH 后也从当时开始算。新装的只有一个家,什么都不放。
|
|
12
|
+
- **群会话里的约束只是提示词**:群会话的近期记忆和别处的动静末尾会多一句「家里和私聊的话不带进群里说」,她仍然看得到这些内容,靠的是她自己守住。
|
|
13
|
+
- **自定义了 `world-prompt.md` 的**:不用改。别处的动静开头自带一句说明,心情快照末尾写着怎么改。
|
|
14
|
+
|
|
15
|
+
### 别处的动静
|
|
16
|
+
|
|
17
|
+
- **新增「别处的动静」**:她不在场的地方攒下的消息,以事实的形式告诉她:有多少条她还没看到、最后是谁、过了多久,不带正文,开头一句说明这只是让她知道,要不要看、要不要回由她决定。每轮开头放在新消息前面,一轮中途有新的就在下一步末尾补一条,没有新的就不放,同一件事不重复说。现在接进来两种:
|
|
18
|
+
- 有未读的微信群:以前只在闹钟响时附一行群聊概况,现在有新消息就会说;闹钟上那行只留没有未读的群各安静了多久。
|
|
19
|
+
- 她的其他会话(家、群会话、你另开的窗口):以前要等记忆块重建(会话刚打开、压缩后、很久没说话再开口)才知道别处说过什么,现在下一步就知道那边有几条新的;用 `memory_find` 带上那一行的 sourceId 翻最新的一页就算看过。
|
|
20
|
+
群会话也能看到别处的动静。群会话里的近期记忆本来就带着家里和私聊的原话,所以在群会话里,近期记忆和别处的动静末尾都多一句:家里和私聊的话不把原话和细节带进群里说、不替谁转述,被问起就带过去。家和 DSH 里另开的窗口不加。
|
|
21
|
+
只往后追加,压缩时清掉、压缩后重新说一次还没看的,不进归档。新用户只有一个家、没有别处,什么都不放;老用户和宿主里已有会话的用户,从升级后第一次说话开始算,以前的不补;重启 DSH 后也从当时开始算。以后接入的推特、B 站等来源都走这一块,规定见 [注意事项](NOTES.md#她每一步看到的上下文) 和 [贡献协议](CONTRIBUTING.md#新的消息来源怎么进她的上下文)。
|
|
22
|
+
|
|
23
|
+
### 心情
|
|
24
|
+
|
|
25
|
+
- **心情快照每一步都放,并写着停了多久**:0.7.5 只在心情变了之后、或者每轮开头放一条快照。她一次醒来能连着做一百多步,那条快照很快沉到十几万 token 之后,她不再注意到,心情一两天没动过。现在每一步都在时间块前面追加一条,末尾写着「最后改于 2 天 3 小时前」这样的停留时长,要不要改由她决定;插件仍然不替她改、不提醒、不让数值衰减。和时间块一样只往后追加,不影响前面的缓存,每一步多几十个 token。删掉 `mood.md` 后仍然只说一次「之前那条不再算数」;没有 `mood.md` 的新用户什么都不放。详见 [注意事项](NOTES.md#心情快照为什么只追加不替换)。
|
|
26
|
+
- **心情挪进控制台的「健康」**:0.7.5 的「心情」卡片原先单独挨着「家」,现在放进概览的「健康」卡片,插件的故障在上、她的心情在下,看她现在怎么样只看一处。内容和读法不变,仍然只读;世界还没开始过时也能看到。
|
|
27
|
+
|
|
28
|
+
### QQ
|
|
29
|
+
|
|
30
|
+
- **QQ 商店表情和部分动图也能收了**(#44,感谢 @endlessstary 实测):这类图 `get_image` 取不到直链,或者给出的不是 `multimedia.nt.qq.com.cn` 的链接,0.7.5 会直接丢掉,她只看到「本次有 QQ 图片未能读取」。现在仍然先走 `get_image`;取不到时改用消息里那张图自带的链接。可下载的域名从 `multimedia.nt.qq.com.cn` 一个放宽到 `qq.com` 和 `qq.com.cn` 下的所有子域名(比如表情商店的 `gxh.vip.qq.com`),仍然只走默认端口的 https,不跟随跳转;其他域名的链接不下载。每批张数、超时和大小限制不变。
|
|
31
|
+
|
|
32
|
+
### 宿主兼容
|
|
33
|
+
|
|
34
|
+
- **兼容 DSH 0.2.2-rc.3**:rc.3 把 `LlmError` 构造时的错误码在类型上收窄到 DSH 自带的那些,插件转发压缩失败和「会话已离开世界」时用的是自己的错误码,按 rc.3 编译会报错;运行时 DSH 照样接受任意错误码,所以 0.7.5 装在 rc.3 上不受影响。现在两处改用同一个转发函数,0.2.1、0.2.2-rc.1 和 rc.3 都能编译。CI 加上 rc.3 一组。
|
|
35
|
+
|
|
3
36
|
## 0.7.5 — 2026-11-13
|
|
4
37
|
|
|
5
38
|
本版不再把 DSH 的会话预设整份写进 profile,旧版留下的副本可以在世界控制台一键还原;世界里的会话改为只用人设和世界模板作系统提示词;心情值固定成 11 个,新增 `set_mood` 工具和控制台「心情」卡片;相册可以收藏她眼前的任意一张图和电脑上的图片文件;QQ 能收图,适配 Windows 微信 4.2.0.52,并修复生活线启动和卸载的时序。
|
package/CONTRIBUTING.md
CHANGED
|
@@ -59,6 +59,17 @@ dsh-world 养的是一个伙伴,不是一个按日程执行的助手。**她
|
|
|
59
59
|
|
|
60
60
|
改动闹钟、家会话、每日回顾、世界提示词、记忆块注入,或者给她新增工具,都属于生活线核心改动:**先开 Issue 讨论,再写代码**,并在 PR 里按下节说明内核影响。
|
|
61
61
|
|
|
62
|
+
## 新的消息来源怎么进她的上下文
|
|
63
|
+
|
|
64
|
+
接入新的平台或外部程序时,先分清它带来的是哪一类,再放到对应的位置(排法和原因见 [注意事项](NOTES.md#她每一步看到的上下文)):
|
|
65
|
+
|
|
66
|
+
- **对她说的话**:作为一条用户消息交给她,带结构化身份(见上节)。
|
|
67
|
+
- **随这句话来的上下文**(之前的聊天、引用、图片):贴在那句话前面,标明属于哪条消息,不放到末尾。
|
|
68
|
+
- **不需要她回答的动静**(群里没叫她的消息、通知、另一个会话里的新发言):属于事件,统一进「别处的动静」,不在上下文末尾另加一块。每个来源只报有多少条她还没看到、最后是谁、过了多久,不带正文;写明她用哪个工具去看,读到最新后清零。不写待办、不写「你应该」,要不要看、要不要回由她决定。
|
|
69
|
+
- **状态**(像心情值、时间,每一步都要是最新的):每一步跟在末尾。新增一种状态属于生活线核心改动,先开 Issue。
|
|
70
|
+
|
|
71
|
+
这几类都只往后追加,不替换、不删除历史里已有的,压缩时清掉,不进归档。新来源要写明它的动静能流到哪些会话,并遵守上一节的世界边界。这一块不带正文;群会话里凡是会见到别处原话或指向别处的地方(近期记忆、别处的动静),都要附上 `history.ts` 的 `GROUP_PRIVACY`,不另写一份措辞。
|
|
72
|
+
|
|
62
73
|
## 涉及内核时必须说明
|
|
63
74
|
|
|
64
75
|
这里的“内核”指 dsh-world 的公共行为,不仅指某个目录:
|
package/NOTES.md
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
- [安装与升级](#安装与升级)
|
|
7
7
|
- [人设与提示词](#人设与提示词)
|
|
8
8
|
- [压缩与记忆](#压缩与记忆)
|
|
9
|
+
- [她每一步看到的上下文](#她每一步看到的上下文)
|
|
9
10
|
- [心情值](#心情值)
|
|
10
11
|
- [世界范围与会话](#世界范围与会话)
|
|
11
12
|
- [微信](#微信)
|
|
@@ -120,6 +121,42 @@ DSH 从预设里删掉某一行时,这份副本还留着它,DSH 找不到那
|
|
|
120
121
|
|
|
121
122
|
归档写不进去(比如磁盘满、数据库被占用)、某个会话的日志一时读不出来,或者记忆块建不出来时,她照常回话,问题显示在控制台的「健康」里。这期间说的话不会丢:它们在宿主的会话日志里,插件记着每个会话归档到了哪里,问题解决后,这个会话下一次有动静或 DSH 下次启动时,会从断点补进归档,不会重复。记忆块建不出来时,她眼前还是上一块(刚压缩完就没有),下一步会再试。补不回来的只有一种:宿主的会话日志在磁盘上坏了、一直读不出来,那个会话里的话就进不了归档,健康里会一直显示它。
|
|
122
123
|
|
|
124
|
+
## 她每一步看到的上下文
|
|
125
|
+
|
|
126
|
+
### 上下文怎么排
|
|
127
|
+
|
|
128
|
+
她每一次请求模型(一步)带的是到这一刻为止的全部内容:历史一直往后接,什么都不等一轮结束才加。一轮里的排法是:
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
[历史……] [别处的动静] [群上下文、引用、图片] [新消息] [心情] [时间] ← 这一轮第一步
|
|
132
|
+
…… [她的回复和工具结果] [别处又来的动静] [心情] [时间] ← 之后的每一步
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
插件放进上下文的东西分三类,各有各的位置:
|
|
136
|
+
|
|
137
|
+
- **随消息来的上下文**:群里这句话之前在聊什么、引用的原消息、图片。它说明的是某一句话,所以贴在那句话前面。
|
|
138
|
+
- **状态**:心情值、时间。说的是「现在是什么样」,每一步都要是最新的,所以每一步都跟在最后,时间在最末。
|
|
139
|
+
- **事件**:别处的动静。说的是「刚才发生了什么」,发生过的说一次就够。每轮开头放在新消息前面,说这条消息进来之前别处攒下了什么;一轮还在进行时别处又有新的,下一步在末尾追加一条,只写新增的部分;没有新的就不放。
|
|
140
|
+
|
|
141
|
+
### 为什么状态每一步都放、事件只放一次
|
|
142
|
+
|
|
143
|
+
这几块都只往后追加,不替换、不删除历史里的旧的:替换会让从那个位置往后的缓存全部失效。追加一条只多它自己那几十个 token,前面的照样命中,压缩时一起清掉。
|
|
144
|
+
|
|
145
|
+
状态每一步都放,是心情值那次的教训:0.7.5 只在心情变了时放一条,她一次醒来能连着做一百多步,那条很快沉到十几万 token 之后,她不再注意到,心情一两天没动过。事件不这样放,是因为同样的事每一步念一遍只是重复;她没去看,未读数还在,下一次有新动静时会带上最新的累计数,不会漏掉。
|
|
146
|
+
|
|
147
|
+
### 别处的动静只报事实
|
|
148
|
+
|
|
149
|
+
「别处」是她不在场的地方:已配置的微信群、她的其他会话(家、群会话、你在她工作区另开的窗口),以后接入的推特、B 站等也一样。每个来源只报几件事实:有多少条她还没看到、最后是谁、过了多久,**不带正文**。这一块开头有一句说明,告诉她这只是让她知道,不是对她说的话,要不要看、要不要回由她决定,所以自己改过世界提示词的用户也不用补说明。想看就用各来源写明的工具(微信群用 `wechat_history`,别的会话用 `memory_find`),读到最新的以后,那个来源的未读清零。
|
|
150
|
+
|
|
151
|
+
这一块本身不带正文,原话不会因为它进到别的会话里;她要看,用的还是原来就有的工具,能看到哪些会话照旧由归档范围决定。
|
|
152
|
+
|
|
153
|
+
别处的动静都会流进家,群会话也能看到。群会话里原本就有近期记忆(里面有家里和私聊的原话),现在又多了「家里有几条新的」,所以在群会话里,近期记忆和别处的动静末尾都会多一句:「我现在在群里。家里和私聊里的话是我和对方之间的:不把原话和细节带进群里说,也不替谁转述;群里有人问起,就带过去,不乱说。」家和你在 DSH 里另开的窗口不加这句。这是提示词上的约束,不是硬性拦截:她仍然看得到这些内容,靠的是她自己守住。这也和插件不往对话里推提醒的原则一致(见 [贡献协议](CONTRIBUTING.md#生活线与她的主动性)):给她能感知的事实,不替她决定。
|
|
154
|
+
|
|
155
|
+
现在接进来的有两种:
|
|
156
|
+
|
|
157
|
+
- **微信群**:适配器在线时,有未读的群各一行,比如「微信群「家人」12 条我还没看到,最后是阿明(5 分钟前)」。没有未读的群各安静了多久,仍然只附在她的闹钟消息上,那是给她决定要不要主动开口用的。
|
|
158
|
+
- **她的其他会话**:家、群会话、你在她工作区另开的窗口,各一行,比如「家有 6 条我在这边没看到,最后是我自己(刚刚);sourceId:chat:session-…」。数的是那边归档进来的发言(双方的都算),从这个会话开始听的那一刻算起:升级或重启 DSH 之后从当时开始,以前的不补。她用 `memory_find` 带上那个 sourceId、不写 query 翻最新的一页,就算看过了,那边之后的才再算。
|
|
159
|
+
|
|
123
160
|
## 心情值
|
|
124
161
|
|
|
125
162
|
### 心情值为什么是固定的一组
|
|
@@ -129,12 +166,14 @@ DSH 从预设里删掉某一行时,这份副本还留着它,DSH 找不到那
|
|
|
129
166
|
这 11 个按「愉快/不愉快 × 激动/平静」四个角各取几个,再加上跟人有关的孤单和想念;原来的「困」并进了「累」。
|
|
130
167
|
|
|
131
168
|
- 用 `set_mood` 写了组外的词,这次不写入,并告诉她能用哪些。
|
|
132
|
-
-
|
|
169
|
+
- 直接改文件写了组外的词,文件不改,快照和控制台「健康」里的心情会说哪几个没算进去。
|
|
133
170
|
- 0.7.4 时写过自己的词的,升级后那几行不再算进心情值,快照里会提示一次,她下次用 `set_mood` 换成组里最接近的那个就好。
|
|
134
171
|
|
|
135
172
|
### 心情快照为什么只追加、不替换
|
|
136
173
|
|
|
137
|
-
|
|
174
|
+
每一步,插件都在时间块前面追加一条心情快照,写着她最后改它是多久以前;旧的留在历史里,以最新一条为准,压缩时一起清掉。不去替换历史里的旧快照,是因为替换会让从那个位置往后的缓存全部失效:心情是她随时会改的,三十轮没变、改一次,这三十轮的内容就都要按未命中缓存重新计费;追加一条每次只多几十个 token。
|
|
175
|
+
|
|
176
|
+
0.7.5 只在心情变了、或者每轮开头才放一条。实际用下来,她一次醒来能连着做一百多步(整理文件、查资料),那条快照很快沉到十几万 token 之后,她不再注意到它,心情一两天都没动过。0.7.6 起每一步都放,和时间块一样跟在最后:她每一步都看得到现在的心情、以及它停了多久,要不要改由她自己决定。代价是每一步多几十个 token,一百多步的一轮大约多一万,比起这一轮本身涨的十几万很小;只往后追加,前面的缓存照样命中。
|
|
138
177
|
|
|
139
178
|
### 她为什么有 set_mood 工具
|
|
140
179
|
|
package/README.md
CHANGED
|
@@ -20,7 +20,8 @@
|
|
|
20
20
|
- **近期记忆**:你们最近数轮的对话原文,每次开始对话、每次压缩之后,以及一个窗口隔了很久(默认 24 小时,控制台可改)再开口时,都放在她眼前,谁、什么时候、说了什么,一字不差。轮数在控制台里填,默认 200。
|
|
21
21
|
- **日记**:人生里重要的事,她自己写进日记,一天一篇。这是她的长期记忆。
|
|
22
22
|
- **我是谁**:她写给自己的一份自述,随着她变化而改写。每晚回顾前,插件会留一份当时的版本,改过的都找得回来。
|
|
23
|
-
- **心情值**:`room/mood.md` 是她自己写的,一行一件:`开心 6` 这样的「名字 数值」是一种心情(0 到 10 的整数),不以数字结尾的行是心情旁边的几件小事(最多三行)。名字是固定的 11 个:开心、兴奋、平静、安心、烦、生气、紧张、难过、累、孤单、想念,没写的算 0;更细的感受写进小事,为什么这样定见 [注意事项](NOTES.md#心情值为什么是固定的一组)。她世界里的会话都有 `set_mood`
|
|
23
|
+
- **心情值**:`room/mood.md` 是她自己写的,一行一件:`开心 6` 这样的「名字 数值」是一种心情(0 到 10 的整数),不以数字结尾的行是心情旁边的几件小事(最多三行)。名字是固定的 11 个:开心、兴奋、平静、安心、烦、生气、紧张、难过、累、孤单、想念,没写的算 0;更细的感受写进小事,为什么这样定见 [注意事项](NOTES.md#心情值为什么是固定的一组)。她世界里的会话都有 `set_mood` 工具,一次调用就整份记下,格式不对时不写入并告诉她哪里错了;直接改文件也一样。她世界里的会话每一步都把当前的心情值作为一条快照放在时间块前面,写着她最后改它是多久以前;和时间块一样只往后追加,旧的不删,以最新一条为准,压缩时一起清掉,不打乱缓存。插件只读、不判断、不衰减、不提醒她改;没有 `mood.md` 就什么都不放。快照不进归档;写错的行只在快照里告诉她,文件读不出来才进健康状态。控制台概览的「健康」里,插件的故障下面是她的心情,只读,显示她现在的心情值、旁边的小事和她最后改的时间。
|
|
24
|
+
- **别处的动静**:她不在场的地方攒下的消息,只报有多少条她还没看到、最后是谁、过了多久,不带正文:有未读的微信群,以及她的其他会话(家、群会话、你另开的窗口)。每轮开头放在新消息前面,一轮中途有新的就在下一步末尾补一条,没有新的就不放;要不要看、要不要回由她决定,排法和原因见 [注意事项](NOTES.md#她每一步看到的上下文)。
|
|
24
25
|
- **范围内的原文留着**:按天归档用户和助手的正文。近期记忆以外的事,她可以自己去翻。
|
|
25
26
|
- **找回过去**:`memory_find` 与 `memory_read` 两个工具(一次默认只返回 8 条、每条约 200 字的摘录,要更多自己翻页或读原文,免得每轮重发的上下文越滚越大),按原文里的字面线索、时间、种类或来源,在聊天原文和日记里统一查找,并读原文。控制台的「档案」页是同一份查找的只读入口。
|
|
26
27
|
|
|
@@ -80,7 +81,7 @@ dsh-world 开放了一个本地的「桥」:桌宠之类的程序可以把你
|
|
|
80
81
|
|
|
81
82
|
微信作为独立模块接入同一个家,使用她的独立账号收发指定私聊或群聊。她可用 `wechat_chats` 查询已配置目标,用 `wechat_history` 主动分页查看群消息,无需等别人 @,历史里的图片用 `wechat_image` 按消息 ID 一张张看;读完以同一个 `chatId` 调用 `wechat_send` 自主联系对方或回复消息,文字、图片和表情共用同一发送队列;一批话没发出或结果不明时,发起的会话会在下一步收到一条说明(不会因此被叫醒),平时不用逐条查回执,需要时仍可用 `wechat_delivery` 查询。普通最终回答不会自动转发到微信。Windows 适配器和配置步骤见 [微信模块](src/ecosystem/wechat/windows/README.md)。B 站尚未接入。
|
|
82
83
|
|
|
83
|
-
**群聊动静**:适配器在线时,已配置群里未 @
|
|
84
|
+
**群聊动静**:适配器在线时,已配置群里未 @ 她的消息只更新未读数、最后发言人和时间,不唤醒模型,也不把正文加入上下文。有未读的群出现在她的「别处的动静」里,每有新消息说一次;她原有的闹钟响起时,还会附上一行没有未读的群各安静了多久。是否去看、是否发言,由她自己决定。成功读取群的最新一页后清零未读,自己的发言不计入未读;计数保存在适配器状态中,重启保留。插件不会改写你的 `alarm.md`、`world-prompt.md` 或「我是谁」。
|
|
84
85
|
|
|
85
86
|
微信的支持版本、账号风险、图片与表情包、表情库、@、退出重开等注意事项,见 [注意事项·微信](NOTES.md#微信);首次接入与升级见 [注意事项·安装与升级](NOTES.md#微信首次接入与升级)。
|
|
86
87
|
|
package/client/index.js
CHANGED
|
@@ -691,9 +691,9 @@
|
|
|
691
691
|
msg ? h('div', { className: msg.indexOf('失败') >= 0 ? 'dw-bad' : 'dw-muted', role: 'status' }, msg) : null)
|
|
692
692
|
}
|
|
693
693
|
// Read-only: what she wrote in mood.md and reads before each turn's time block. Only she changes it.
|
|
694
|
-
function
|
|
694
|
+
function Mood(props) {
|
|
695
695
|
var mood = props.mood
|
|
696
|
-
|
|
696
|
+
return !mood || mood.kind === 'none' ? h('div', { className: 'dw-muted' }, '她还没有写 mood.md')
|
|
697
697
|
: mood.kind === 'failed' ? h('div', { className: 'dw-bad' }, 'mood.md 读不出来:' + mood.message)
|
|
698
698
|
: [
|
|
699
699
|
h('div', { key: 'v', className: 'dw-trail' }, list(mood.values).map(function (v) { return h('span', { key: v.name, className: v.value ? null : 'dw-muted' }, v.name + ' ' + v.value) })),
|
|
@@ -702,11 +702,17 @@
|
|
|
702
702
|
mood.unread ? h('div', { key: 'u', className: 'dw-muted' }, '有 ' + mood.unread + ' 行没读懂,她在快照里能看到') : null,
|
|
703
703
|
h('div', { key: 'at', className: 'dw-muted', style: { marginTop: 8 } }, mood.updatedAt ? '她最后改于 ' + local(mood.updatedAt, props.zone) : ''),
|
|
704
704
|
]
|
|
705
|
-
|
|
705
|
+
}
|
|
706
|
+
// Her mood sits with the plugin's faults: one place to see how things are with her.
|
|
707
|
+
function Health(props) {
|
|
708
|
+
var faults = list(props.faults)
|
|
709
|
+
return h(Card, { title: '健康', delay: 120 },
|
|
710
|
+
faults.length ? faults.map(function (f, i) { return h('div', { key: i, className: 'dw-bad' }, '● ' + f) }) : h('div', { className: 'dw-ok' }, '● 一切正常'),
|
|
711
|
+
props.mood ? h('div', { style: { marginTop: 12 } }, KV([['心情', h(Mood, { mood: props.mood, zone: props.zone })]])) : null)
|
|
706
712
|
}
|
|
707
713
|
function Overview(props) {
|
|
708
714
|
var snap = props.snap, zone = snap.timeZone, life = snap.life, alarm = life && life.alarm, mem = snap.memory
|
|
709
|
-
var
|
|
715
|
+
var wakes = life ? list(life.recentWakes) : []
|
|
710
716
|
var welcome = !snap.running && !life
|
|
711
717
|
return h('div', { className: 'dw-pane' },
|
|
712
718
|
welcome ? h(Card, null, h('div', { className: 'dw-welcome' },
|
|
@@ -725,10 +731,9 @@
|
|
|
725
731
|
['会话', String(life.homeSessionId || '还没有家').replace(/^session-/, '').slice(0, 8)],
|
|
726
732
|
['下次回顾', life.review ? local(life.review.at, zone) : '—'],
|
|
727
733
|
['最近', wakes.length ? h('div', { className: 'dw-trail' }, wakes.map(function (w, i) { return h('span', { key: i }, local(w.deliveredAt, zone) + ' ' + (sourceLabel[w.source] || w.source) + (w.lateMs >= 120000 ? ' · 晚 ' + Math.round(w.lateMs / 60000) + ' 分' : '')) })) : '—'],
|
|
728
|
-
])),
|
|
729
|
-
h(MoodCard, { mood: snap.mood, zone: zone })) : null,
|
|
734
|
+
]))) : null,
|
|
730
735
|
h('div', { className: 'dw-grid' },
|
|
731
|
-
h(
|
|
736
|
+
h(Health, { faults: snap.health, mood: snap.mood, zone: zone }),
|
|
732
737
|
h(CompactionPreset, { info: snap.compactionPreset, refresh: props.refresh }),
|
|
733
738
|
h(Memory, { mem: mem, onSaved: props.refresh }),
|
|
734
739
|
h(Budget, { budget: snap.budget, onSaved: props.refresh }),
|
|
@@ -928,7 +933,7 @@
|
|
|
928
933
|
return h(View, { snap: snap, error: error, tick: tick, refresh: function () { if (loadRef.current) loadRef.current() } })
|
|
929
934
|
}
|
|
930
935
|
|
|
931
|
-
return { Console: Console, test: {
|
|
936
|
+
return { Console: Console, test: { Health: Health, Memory: Memory, MemorySearch: MemorySearch, latest: latest, searchMemory: searchMemory, memoryQuery: memoryQuery, dayStartIso: dayStartIso, WorkspacePermission: WorkspacePermission, CompactAfterReview: CompactAfterReview, Schedule: Schedule, Modules: Modules, HomeApply: HomeApply, PhotoAlbum: PhotoAlbum, Wechat: Wechat, Activity: Activity, Diary: Diary, Qq: Qq, Panel: Panel, View: View, Overview: Overview, PersonaEditor: PersonaEditor, PromptEditor: PromptEditor, loadSnapshot: loadSnapshot, renderPersona: renderPersona } }
|
|
932
937
|
}
|
|
933
938
|
|
|
934
939
|
async function loadWorldIds() {
|
package/lib/compaction.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis';
|
|
|
2
2
|
import z from '@deepseek-ai/schemastery';
|
|
3
3
|
import { CompactionEngine, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from '@deepseek-ai/dsh-compaction';
|
|
4
4
|
import type { CommandId } from '@deepseek-ai/dsh-commands/brand';
|
|
5
|
-
import { type Message } from '@deepseek-ai/dsh-llm';
|
|
5
|
+
import { LlmError, type LlmFailure, type Message } from '@deepseek-ai/dsh-llm';
|
|
6
6
|
import { type SessionSeq } from '@deepseek-ai/dsh-session';
|
|
7
7
|
import { type RegionAgent, type SummaryResult } from './compactionRegion.ts';
|
|
8
8
|
import './hostContract.ts';
|
|
@@ -59,6 +59,11 @@ export declare function compactionThreshold(input: {
|
|
|
59
59
|
* tool result, tool schema and reasoning block from the compacted span, then
|
|
60
60
|
* replaces the whole conversation with one summary paragraph.
|
|
61
61
|
*/
|
|
62
|
+
/**
|
|
63
|
+
* Raises a failure with its own code, ours or a provider's. DSH 0.2.2-rc.3 narrows the constructor's code to its built-in
|
|
64
|
+
* ones (only `LlmError.fromFailure`, which 0.2.1 lacks, takes any); the runtime check is unchanged.
|
|
65
|
+
*/
|
|
66
|
+
export declare const llmError: (failure: LlmFailure) => LlmError;
|
|
62
67
|
/** Whether a session's compaction service is this one, which can summarize inside a running turn; DSH's stock one cannot. */
|
|
63
68
|
export declare const compactsWhole: (engine: unknown) => engine is Pick<ToolFreeCompaction, "compactWhole">;
|
|
64
69
|
export default class ToolFreeCompaction extends CompactionEngine {
|
package/lib/compaction.js
CHANGED
|
@@ -10,14 +10,14 @@ const summaryInstruction = [
|
|
|
10
10
|
'现在暂停对话,改为执行上下文压缩:把上面这段会话中双方的交流整理成一段精炼的中文摘要,供你之后接着对话使用。',
|
|
11
11
|
'保留用户的意图、情绪与关系进展、明确要求、重要事实、已作决定、未完成事项和最近进展;最后一条用户发言尽量按原意完整保留。以“以下是此前交流的摘要”开头的消息是更早的摘要,请与新内容合并为同一段。',
|
|
12
12
|
'以【我的时间】(较早的是【你的时间】)开头的消息是你自己定的闹钟和留给自己的话,不是用户说的话;把它们当作你自己的安排来记,不要算作用户发言。',
|
|
13
|
-
'
|
|
13
|
+
'开头写着“这是我们最近的聊天记录”(较早的写着“最近的聊天记忆”或“最近的相处记忆”)的记忆资料、系统提示里的世界提示词(含「我是谁」)、以【我的心情值】开头的心情快照、以【别处的动静】开头的未读计数和“Time sampled”开头的时间块会在压缩后重新提供,不要写进摘要。工具调用过程已从会话中删除,不要提及工具。',
|
|
14
14
|
'保留准确的姓名、日期、数字和标识,分清每件事是谁说的、谁做的。不要标题、列表或分段,不要开头语,不要补写原文没有的事实,不要调用任何工具,直接输出摘要正文。',
|
|
15
15
|
].join('\n');
|
|
16
16
|
// The model tends to echo the checkpoint lead it saw on earlier summaries; the frame adds it once.
|
|
17
17
|
const leadEcho = /^以下是此前交流的摘要[^::]{0,40}[::]\s*/;
|
|
18
18
|
const checkpointLead = '以下是此前交流的摘要,工具调用过程已省略;请把它当作已知背景,直接接着当前对话继续:';
|
|
19
19
|
// Re-injected after every successful compaction by the memory runtime; replayed only as cacheable prefix.
|
|
20
|
-
const injectedSources = new Set(['time-context', 'dsh-world-history', 'dsh-world-mood']);
|
|
20
|
+
const injectedSources = new Set(['time-context', 'dsh-world-history', 'dsh-world-mood', 'dsh-world-elsewhere']);
|
|
21
21
|
/**
|
|
22
22
|
* The compacted span exactly as the conversation request sent it, minus every
|
|
23
23
|
* tool call and tool result, so the summary request shares the longest possible
|
|
@@ -83,6 +83,11 @@ class TargetConfigError extends Error {
|
|
|
83
83
|
* tool result, tool schema and reasoning block from the compacted span, then
|
|
84
84
|
* replaces the whole conversation with one summary paragraph.
|
|
85
85
|
*/
|
|
86
|
+
/**
|
|
87
|
+
* Raises a failure with its own code, ours or a provider's. DSH 0.2.2-rc.3 narrows the constructor's code to its built-in
|
|
88
|
+
* ones (only `LlmError.fromFailure`, which 0.2.1 lacks, takes any); the runtime check is unchanged.
|
|
89
|
+
*/
|
|
90
|
+
export const llmError = (failure) => new LlmError(failure.message, failure.code, failure);
|
|
86
91
|
/** Whether a session's compaction service is this one, which can summarize inside a running turn; DSH's stock one cannot. */
|
|
87
92
|
export const compactsWhole = (engine) => typeof engine?.compactWhole === 'function';
|
|
88
93
|
export default class ToolFreeCompaction extends CompactionEngine {
|
|
@@ -294,7 +299,7 @@ export default class ToolFreeCompaction extends CompactionEngine {
|
|
|
294
299
|
signal?.throwIfAborted();
|
|
295
300
|
const finish = assembler.finish;
|
|
296
301
|
if (finish.kind === 'error' || finish.kind === 'aborted')
|
|
297
|
-
throw
|
|
302
|
+
throw llmError(finish.failure);
|
|
298
303
|
if (finish.kind !== 'stop')
|
|
299
304
|
throw new Error(`dsh-world: compaction summary truncated or invalid (${finish.kind})`);
|
|
300
305
|
const rawOutput = assembler.blocks();
|
|
@@ -2,8 +2,12 @@ import type { Context } from '@deepseek-ai/cordis';
|
|
|
2
2
|
import type { ContentBlock } from '@deepseek-ai/dsh-llm';
|
|
3
3
|
import type { SpeakerIdentity } from '../shared/identity.ts';
|
|
4
4
|
export declare const MAX_BATCH_IMAGES = 4;
|
|
5
|
-
|
|
5
|
+
/** One image segment as QQ sent it: the id get_image takes, and the link some images (shop stickers, animated ones) carry instead. */
|
|
6
|
+
export interface QqImageSegment {
|
|
6
7
|
file: unknown;
|
|
8
|
+
url: unknown;
|
|
9
|
+
}
|
|
10
|
+
export interface QqImage extends QqImageSegment {
|
|
7
11
|
identity: SpeakerIdentity;
|
|
8
12
|
}
|
|
9
13
|
export declare function admitQqImages(ctx: Context, images: readonly QqImage[], getImage?: (file: string) => Promise<string>): Promise<ContentBlock[]>;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
export const MAX_BATCH_IMAGES = 4;
|
|
2
2
|
const DOWNLOAD_TIMEOUT_MS = 10_000;
|
|
3
|
-
|
|
3
|
+
// QQ's own image hosts: the CDN behind get_image (multimedia.nt.qq.com.cn) and the sticker shop (gxh.vip.qq.com) (#44).
|
|
4
|
+
const QQ_IMAGE_DOMAINS = ['qq.com', 'qq.com.cn'];
|
|
5
|
+
const onQqHost = (url) => QQ_IMAGE_DOMAINS.some(domain => url.hostname === domain || url.hostname.endsWith(`.${domain}`));
|
|
4
6
|
async function downloadImage(link, limits) {
|
|
5
|
-
// shortcut: only the verified SnowLuma CDN is supported, add hosts when their gateway responses are verified.
|
|
6
7
|
const url = new URL(link);
|
|
7
|
-
if (url.protocol !== 'https:' || url.
|
|
8
|
+
if (url.protocol !== 'https:' || url.port || !onQqHost(url) || url.username || url.password)
|
|
8
9
|
throw new Error('QQ 图片链接不受支持');
|
|
9
10
|
const controller = new AbortController();
|
|
10
11
|
try {
|
|
@@ -32,20 +33,26 @@ async function downloadImage(link, limits) {
|
|
|
32
33
|
controller.abort();
|
|
33
34
|
}
|
|
34
35
|
}
|
|
36
|
+
// get_image first, as verified for ordinary pictures; the segment's own link when get_image has no usable answer.
|
|
37
|
+
async function fetchQqImage({ file, url }, limits, getImage) {
|
|
38
|
+
const viaFile = typeof file === 'string' && /^[a-z0-9_-][a-z0-9_.-]{0,255}$/i.test(file) && getImage
|
|
39
|
+
? getImage(file).then(link => downloadImage(link, limits)) : Promise.reject(new Error('QQ 图片标识无效'));
|
|
40
|
+
return viaFile.catch(error => {
|
|
41
|
+
if (typeof url !== 'string' || !url)
|
|
42
|
+
throw error;
|
|
43
|
+
return downloadImage(url, limits);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
35
46
|
export async function admitQqImages(ctx, images, getImage) {
|
|
36
47
|
if (!images.length)
|
|
37
48
|
return [];
|
|
38
49
|
const unavailable = { type: 'text', text: '本次有 QQ 图片未能读取,请勿假装看过。' };
|
|
39
50
|
const store = ctx.get('attachments');
|
|
40
|
-
if (!store
|
|
51
|
+
if (!store)
|
|
41
52
|
return [unavailable];
|
|
42
53
|
const limits = store.imageLimits;
|
|
43
54
|
const selected = images.slice(0, Math.min(MAX_BATCH_IMAGES, limits.maxImagesPerMessage));
|
|
44
|
-
const downloads = await Promise.allSettled(selected.map(
|
|
45
|
-
if (typeof file !== 'string' || !/^[a-z0-9_-][a-z0-9_.-]{0,255}$/i.test(file))
|
|
46
|
-
throw new Error('QQ 图片标识无效');
|
|
47
|
-
return downloadImage(await getImage(file), limits);
|
|
48
|
-
}));
|
|
55
|
+
const downloads = await Promise.allSettled(selected.map(image => fetchQqImage(image, limits, getImage)));
|
|
49
56
|
const content = [];
|
|
50
57
|
let remainingBytes = limits.maxMessageImageBytes;
|
|
51
58
|
let saved = 0;
|
|
@@ -219,9 +219,9 @@ export function createQqNativeModule(deps) {
|
|
|
219
219
|
pushContext(key, { id: messageId || String(Date.now()), occurredAt: new Date().toISOString(), text, identity }, config.contextMessages);
|
|
220
220
|
return;
|
|
221
221
|
}
|
|
222
|
-
const
|
|
223
|
-
.slice(0, MAX_BATCH_IMAGES + 1).map(segment => segment.data?.file);
|
|
224
|
-
batches.add(key, { text, identity, who: speakerName,
|
|
222
|
+
const images = (message.segments ?? []).filter(segment => segment?.type === 'image')
|
|
223
|
+
.slice(0, MAX_BATCH_IMAGES + 1).map(segment => ({ file: segment.data?.file, url: segment.data?.url }));
|
|
224
|
+
batches.add(key, { text, identity, who: speakerName, images });
|
|
225
225
|
}
|
|
226
226
|
async function answer(key, gathered) {
|
|
227
227
|
const config = settings();
|
|
@@ -234,7 +234,7 @@ export function createQqNativeModule(deps) {
|
|
|
234
234
|
const text = gathered.length === 1 ? gathered[0].text : gathered.map(item => isGroup && item.who ? `${item.who}: ${item.text}` : item.text).join('\n');
|
|
235
235
|
answering.add(key);
|
|
236
236
|
try {
|
|
237
|
-
const images = gathered.flatMap(item => item.
|
|
237
|
+
const images = gathered.flatMap(item => item.images.map(image => ({ ...image, identity: item.identity })));
|
|
238
238
|
const reply = await home.ask(text, identity, contexts.get(key) ?? [], images.length
|
|
239
239
|
? () => admitQqImages(deps.ctx, images, client?.getImage?.bind(client))
|
|
240
240
|
: undefined);
|
|
@@ -20,7 +20,12 @@ export declare function createWechatModule(deps: {
|
|
|
20
20
|
record?(reply: PreparedReply): Promise<string>;
|
|
21
21
|
receipt?(receipt: WechatReceipt): Promise<void>;
|
|
22
22
|
}): {
|
|
23
|
+
/** The quiet groups, for her alarm; groups with unread messages are news from elsewhere instead. */
|
|
23
24
|
presence: (now: Date) => string | undefined;
|
|
25
|
+
elsewhere: {
|
|
26
|
+
look: string;
|
|
27
|
+
news: (now: Date) => import("../../elsewhere.ts").ElsewhereNews[];
|
|
28
|
+
};
|
|
24
29
|
status(): {
|
|
25
30
|
contextMessages: number;
|
|
26
31
|
bufferSeconds: number;
|
|
@@ -180,7 +180,9 @@ export function createWechatModule(deps) {
|
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
182
|
return {
|
|
183
|
-
|
|
183
|
+
/** The quiet groups, for her alarm; groups with unread messages are news from elsewhere instead. */
|
|
184
|
+
presence: (now) => !stopped && accountState === 'online' ? presence.quiet(now) : undefined,
|
|
185
|
+
elsewhere: { look: '微信群用 wechat_history 看', news: now => !stopped && accountState === 'online' ? presence.unread(now) : [] },
|
|
184
186
|
status() { return { ...sending.status(), lastContactAt: lastContactAt ?? null, account: accountState ?? null, ...settings() }; },
|
|
185
187
|
start() {
|
|
186
188
|
durableWrite(deps.file, JSON.stringify({ origin: deps.origin(), token, path, pid: process.pid, protocol: 4, references: true }, null, 2));
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
import { type ElsewhereNews } from '../../elsewhere.ts';
|
|
1
2
|
/** Ephemeral host view of the adapter's durable, account-bound counters. */
|
|
2
3
|
export declare function createWechatPresence(): {
|
|
3
4
|
clear(): void;
|
|
4
5
|
accept(value: unknown): void;
|
|
5
|
-
|
|
6
|
+
/** Groups with messages she has not read: news from elsewhere, told once per change. */
|
|
7
|
+
unread(now: Date): ElsewhereNews[];
|
|
8
|
+
/** How long the groups with nothing unread have been quiet, for her alarm: whether to speak up there is hers. */
|
|
9
|
+
quiet(now: Date): string | undefined;
|
|
6
10
|
};
|
|
@@ -1,13 +1,16 @@
|
|
|
1
|
+
import { ago } from "../../elsewhere.js";
|
|
1
2
|
const clean = (value) => [...value.replace(/[\r\n\u0000-\u001f「」]/g, ' ')].slice(0, 40).join('');
|
|
2
3
|
// The adapter permits a 60-second poll; leave one poll and a control-request margin before expiry.
|
|
3
4
|
const PRESENCE_TTL_MS = 2 * 60_000 + 5_000;
|
|
4
|
-
function ago(milliseconds) {
|
|
5
|
-
const minutes = Math.max(0, Math.floor(milliseconds / 60_000));
|
|
6
|
-
return minutes < 1 ? '刚刚' : minutes < 60 ? `${minutes} 分钟前` : minutes < 1440 ? `${Math.floor(minutes / 60)} 小时前` : `${Math.floor(minutes / 1440)} 天前`;
|
|
7
|
-
}
|
|
8
5
|
/** Ephemeral host view of the adapter's durable, account-bound counters. */
|
|
9
6
|
export function createWechatPresence() {
|
|
10
7
|
let groups = [], observedAt = 0;
|
|
8
|
+
/** What the adapter last reported, while it is recent enough to stand for now; stale data cannot assert a quiet group. */
|
|
9
|
+
const current = (now) => {
|
|
10
|
+
const age = now.getTime() - observedAt;
|
|
11
|
+
return age < -60_000 || age > PRESENCE_TTL_MS ? [] : groups;
|
|
12
|
+
};
|
|
13
|
+
const speaker = (row) => row.lastSelf ? '我自己' : row.lastSpeaker;
|
|
11
14
|
return {
|
|
12
15
|
clear() { groups = []; observedAt = 0; },
|
|
13
16
|
accept(value) {
|
|
@@ -38,18 +41,24 @@ export function createWechatPresence() {
|
|
|
38
41
|
groups = next;
|
|
39
42
|
observedAt = at;
|
|
40
43
|
},
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
/** Groups with messages she has not read: news from elsewhere, told once per change. */
|
|
45
|
+
unread(now) {
|
|
46
|
+
return current(now).filter(row => row.count > 0).sort((a, b) => b.lastAt - a.lastAt).map(row => ({
|
|
47
|
+
key: `wechat:${row.chatId}`, mark: `${row.count}:${row.lastAt}`,
|
|
48
|
+
text: `微信群「${row.name}」${row.count > 99 ? '99+' : row.count} 条我还没看到,最后是${speaker(row)}(${ago(now.getTime() - row.lastAt)})`,
|
|
49
|
+
}));
|
|
50
|
+
},
|
|
51
|
+
/** How long the groups with nothing unread have been quiet, for her alarm: whether to speak up there is hers. */
|
|
52
|
+
quiet(now) {
|
|
53
|
+
const rows = current(now).filter(row => !row.count);
|
|
54
|
+
if (!rows.length)
|
|
44
55
|
return;
|
|
45
|
-
const entries = [...
|
|
46
|
-
const speaker = row.lastSelf ? '我自己' : row.lastSpeaker;
|
|
56
|
+
const entries = [...rows].sort((a, b) => b.lastAt - a.lastAt).slice(0, 8).map(row => {
|
|
47
57
|
const elapsed = ago(now.getTime() - row.lastAt);
|
|
48
|
-
return
|
|
49
|
-
: `「${row.name}」${elapsed.endsWith('前') ? elapsed.slice(0, -1) + '没人说话' : '刚刚有发言'},最后是${speaker}`;
|
|
58
|
+
return `「${row.name}」${elapsed.endsWith('前') ? elapsed.slice(0, -1) + '没人说话' : '刚刚有发言'},最后是${speaker(row)}`;
|
|
50
59
|
});
|
|
51
|
-
if (
|
|
52
|
-
entries.push(`另有 ${
|
|
60
|
+
if (rows.length > entries.length)
|
|
61
|
+
entries.push(`另有 ${rows.length - entries.length} 个群`);
|
|
53
62
|
return '微信:' + entries.join(';');
|
|
54
63
|
},
|
|
55
64
|
};
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Session } from '@deepseek-ai/dsh-session';
|
|
2
|
+
/** One place she is not, as facts only (how many she has not seen, who spoke last, how long ago), never the words. */
|
|
3
|
+
export interface ElsewhereNews {
|
|
4
|
+
/** Stable for the place, e.g. `wechat:family@chatroom`. */
|
|
5
|
+
key: string;
|
|
6
|
+
/** Changes whenever there is something new there; the same mark is not told twice. */
|
|
7
|
+
mark: string;
|
|
8
|
+
text: string;
|
|
9
|
+
}
|
|
10
|
+
/** Where news comes from: a WeChat account's groups, her other sessions, later other platforms. */
|
|
11
|
+
export interface ElsewhereSource {
|
|
12
|
+
/** How she looks for herself, e.g. `微信群用 wechat_history 看`. */
|
|
13
|
+
look: string;
|
|
14
|
+
/** What is pending for this session now; a place with nothing she has not seen is left out. */
|
|
15
|
+
news(now: Date, session: Session): ElsewhereNews[];
|
|
16
|
+
}
|
|
17
|
+
export declare function ago(milliseconds: number): string;
|
|
18
|
+
export declare const ELSEWHERE_HEADER = "\u3010\u522B\u5904\u7684\u52A8\u9759\u3011\u6211\u4E0D\u5728\u573A\u7684\u5730\u65B9\u6512\u4E0B\u7684\u6D88\u606F\uFF0C\u53EA\u662F\u8BA9\u6211\u77E5\u9053\uFF0C\u4E0D\u662F\u5BF9\u6211\u8BF4\u7684\u8BDD\uFF1B\u8981\u4E0D\u8981\u770B\u3001\u8981\u4E0D\u8981\u56DE\uFF0C\u6211\u81EA\u5DF1\u51B3\u5B9A\u3002";
|
|
19
|
+
export declare function renderElsewhere(groups: readonly {
|
|
20
|
+
look: string;
|
|
21
|
+
news: readonly ElsewhereNews[];
|
|
22
|
+
}[]): string;
|
|
23
|
+
/**
|
|
24
|
+
* The one way news from elsewhere reaches her: sources register here, and each session is told what is new since it
|
|
25
|
+
* was last told. An event is told once; whatever she has not looked at comes back with the next news from that place.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createElsewhere(): {
|
|
28
|
+
register(source: ElsewhereSource): () => void;
|
|
29
|
+
/** The block of what is new for this session, marking it told; undefined when nothing is. */
|
|
30
|
+
take(session: Session, now: Date): string | undefined;
|
|
31
|
+
/** What she was told is gone from her view (compaction, leaving her world): tell again what is still pending. */
|
|
32
|
+
retell(session: Session): void;
|
|
33
|
+
};
|
|
34
|
+
export type Elsewhere = ReturnType<typeof createElsewhere>;
|
package/lib/elsewhere.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export function ago(milliseconds) {
|
|
2
|
+
const minutes = Math.max(0, Math.floor(milliseconds / 60_000));
|
|
3
|
+
return minutes < 1 ? '刚刚' : minutes < 60 ? `${minutes} 分钟前` : minutes < 1440 ? `${Math.floor(minutes / 60)} 小时前` : `${Math.floor(minutes / 1440)} 天前`;
|
|
4
|
+
}
|
|
5
|
+
export const ELSEWHERE_HEADER = '【别处的动静】我不在场的地方攒下的消息,只是让我知道,不是对我说的话;要不要看、要不要回,我自己决定。';
|
|
6
|
+
export function renderElsewhere(groups) {
|
|
7
|
+
return [ELSEWHERE_HEADER, ...groups.flatMap(group => group.news.map(news => `- ${news.text}`)), `(${groups.map(group => group.look).join(';')})`].join('\n');
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The one way news from elsewhere reaches her: sources register here, and each session is told what is new since it
|
|
11
|
+
* was last told. An event is told once; whatever she has not looked at comes back with the next news from that place.
|
|
12
|
+
*/
|
|
13
|
+
export function createElsewhere() {
|
|
14
|
+
const sources = new Set();
|
|
15
|
+
const told = new WeakMap();
|
|
16
|
+
return {
|
|
17
|
+
register(source) {
|
|
18
|
+
sources.add(source);
|
|
19
|
+
return () => { sources.delete(source); };
|
|
20
|
+
},
|
|
21
|
+
/** The block of what is new for this session, marking it told; undefined when nothing is. */
|
|
22
|
+
take(session, now) {
|
|
23
|
+
const previous = told.get(session) ?? new Map();
|
|
24
|
+
const marks = new Map(), groups = [];
|
|
25
|
+
for (const source of sources) {
|
|
26
|
+
const pending = source.news(now, session);
|
|
27
|
+
for (const news of pending)
|
|
28
|
+
marks.set(news.key, news.mark);
|
|
29
|
+
const fresh = pending.filter(news => previous.get(news.key) !== news.mark);
|
|
30
|
+
if (fresh.length)
|
|
31
|
+
groups.push({ look: source.look, news: fresh });
|
|
32
|
+
}
|
|
33
|
+
// A place she has since caught up with is forgotten, so its next message is news again.
|
|
34
|
+
told.set(session, marks);
|
|
35
|
+
return groups.length ? renderElsewhere(groups) : undefined;
|
|
36
|
+
},
|
|
37
|
+
/** What she was told is gone from her view (compaction, leaving her world): tell again what is still pending. */
|
|
38
|
+
retell(session) { told.delete(session); },
|
|
39
|
+
};
|
|
40
|
+
}
|
package/lib/history.d.ts
CHANGED
|
@@ -15,4 +15,9 @@ export declare function shortenLocalImages(content: string): string;
|
|
|
15
15
|
* name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
|
|
16
16
|
* memory is her time at home.
|
|
17
17
|
*/
|
|
18
|
+
/**
|
|
19
|
+
* Said wherever a group session meets what was said elsewhere (her recent chats, news from elsewhere): those words
|
|
20
|
+
* are between her and one person, and a group is the wrong place to repeat them.
|
|
21
|
+
*/
|
|
22
|
+
export declare const GROUP_PRIVACY = "\u6211\u73B0\u5728\u5728\u7FA4\u91CC\u3002\u5BB6\u91CC\u548C\u79C1\u804A\u91CC\u7684\u8BDD\u662F\u6211\u548C\u5BF9\u65B9\u4E4B\u95F4\u7684\uFF1A\u4E0D\u628A\u539F\u8BDD\u548C\u7EC6\u8282\u5E26\u8FDB\u7FA4\u91CC\u8BF4\uFF0C\u4E5F\u4E0D\u66FF\u8C01\u8F6C\u8FF0\uFF1B\u7FA4\u91CC\u6709\u4EBA\u95EE\u8D77\uFF0C\u5C31\u5E26\u8FC7\u53BB\uFF0C\u4E0D\u4E71\u8BF4\u3002";
|
|
18
23
|
export declare function renderHistory(turns: readonly ConversationTurn[], timeZone: string, names: WorldNames, homeOnly?: boolean): string;
|
package/lib/history.js
CHANGED
|
@@ -98,6 +98,11 @@ function sentState({ status, confirmed, total }) {
|
|
|
98
98
|
* name, so the memory reads as hers rather than a generic assistant's. `homeOnly` (archiveScope home) says the
|
|
99
99
|
* memory is her time at home.
|
|
100
100
|
*/
|
|
101
|
+
/**
|
|
102
|
+
* Said wherever a group session meets what was said elsewhere (her recent chats, news from elsewhere): those words
|
|
103
|
+
* are between her and one person, and a group is the wrong place to repeat them.
|
|
104
|
+
*/
|
|
105
|
+
export const GROUP_PRIVACY = '我现在在群里。家里和私聊里的话是我和对方之间的:不把原话和细节带进群里说,也不替谁转述;群里有人问起,就带过去,不乱说。';
|
|
101
106
|
export function renderHistory(turns, timeZone, names, homeOnly = false) {
|
|
102
107
|
const selfName = names.companion;
|
|
103
108
|
if (!turns.length)
|
package/lib/hostContract.d.ts
CHANGED
|
@@ -29,6 +29,12 @@ declare module '@deepseek-ai/dsh-llm' {
|
|
|
29
29
|
form: 'snapshot';
|
|
30
30
|
worldId: string;
|
|
31
31
|
};
|
|
32
|
+
/** 别处的动静:她不在场的地方攒下多少条、最后是谁,只是事实,不是谁说的话,不进归档。 */
|
|
33
|
+
'dsh-world-elsewhere': {
|
|
34
|
+
kind: 'dsh-world-elsewhere';
|
|
35
|
+
form: 'notice';
|
|
36
|
+
worldId: string;
|
|
37
|
+
};
|
|
32
38
|
'dsh-world-channel-context': {
|
|
33
39
|
kind: 'dsh-world-channel-context';
|
|
34
40
|
form: 'recall';
|
package/lib/index.js
CHANGED
|
@@ -21,6 +21,7 @@ import { createLifeRuntime } from "./life/runtime.js";
|
|
|
21
21
|
import { createOutlet } from "./ecosystem/shared/outlets.js";
|
|
22
22
|
import { readPersona, writePersona } from "./persona.js";
|
|
23
23
|
import { MOOD_FILE } from "./mood.js";
|
|
24
|
+
import { createElsewhere } from "./elsewhere.js";
|
|
24
25
|
import { qqRoute } from "./ecosystem/qq/route.js";
|
|
25
26
|
import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
|
|
26
27
|
import { createMemory } from "./memory.js";
|
|
@@ -160,6 +161,8 @@ export function apply(ctx, config) {
|
|
|
160
161
|
// Her self-description lives in her room whether or not the life line runs; she writes it with her file tools.
|
|
161
162
|
const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
|
|
162
163
|
const moodFile = join(roomDir, MOOD_FILE);
|
|
164
|
+
/** Every source of news from where she is not registers here; the world runtime tells her sessions. */
|
|
165
|
+
const elsewhere = createElsewhere();
|
|
163
166
|
const personaFile = config.personaFile || join(worldDir, 'persona.md');
|
|
164
167
|
const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
|
|
165
168
|
const options = { worldDir, roomDir, diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, schedule: () => ({ review: power.reviewTime(), wake: power.wakeTime() }), timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
|
|
@@ -203,7 +206,7 @@ export function apply(ctx, config) {
|
|
|
203
206
|
return;
|
|
204
207
|
try {
|
|
205
208
|
const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
|
|
206
|
-
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
|
|
209
|
+
memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService, elsewhere }, power.memoryTurns, power.coldHours);
|
|
207
210
|
await memory.start({ fresh });
|
|
208
211
|
faults.clear('memory');
|
|
209
212
|
}
|
|
@@ -302,6 +305,7 @@ export function apply(ctx, config) {
|
|
|
302
305
|
let adapter;
|
|
303
306
|
let channels;
|
|
304
307
|
let unregisterWechat;
|
|
308
|
+
let unregisterWechatNews;
|
|
305
309
|
let lifeStop;
|
|
306
310
|
let wechatClosing = Promise.resolve();
|
|
307
311
|
/** Starts the WeChat module (its tools, route and, when configured, the adapter) against the running life line. */
|
|
@@ -317,6 +321,7 @@ export function apply(ctx, config) {
|
|
|
317
321
|
...createWechatRecorder(store, config.worldId, archiveSession) });
|
|
318
322
|
wechat.start();
|
|
319
323
|
unregisterWechat = webServer.register(wechat.route);
|
|
324
|
+
unregisterWechatNews = elsewhere.register(wechat.elsewhere);
|
|
320
325
|
if (config.wechatAdapter?.python && config.wechatAdapter.config) {
|
|
321
326
|
adapter = createAdapterSupervisor({ python: config.wechatAdapter.python, config: config.wechatAdapter.config, logFile: join(worldDir, 'wechat-adapter.log'), log: message => lifeCtx.logger.warn(message) });
|
|
322
327
|
adapter.start();
|
|
@@ -326,6 +331,8 @@ export function apply(ctx, config) {
|
|
|
326
331
|
function stopWechat() {
|
|
327
332
|
unregisterWechat?.();
|
|
328
333
|
unregisterWechat = undefined;
|
|
334
|
+
unregisterWechatNews?.();
|
|
335
|
+
unregisterWechatNews = undefined;
|
|
329
336
|
const closingAdapter = adapter?.stop();
|
|
330
337
|
adapter = undefined;
|
|
331
338
|
const closing = Promise.all([closingAdapter, wechat?.stop()]).then(() => { });
|
package/lib/memoryTools.d.ts
CHANGED
|
@@ -9,13 +9,14 @@ import type { MemoryService } from './memory.ts';
|
|
|
9
9
|
*/
|
|
10
10
|
/** What a tool call returns is resent on every later turn of the loop, so it is kept short: fewer hits, shorter excerpts, no bookkeeping fields. */
|
|
11
11
|
export declare const TOOL_FIND_LIMIT = 8, TOOL_EXCERPT_CHARS = 200, TOOL_READ_LIMIT = 2000;
|
|
12
|
-
|
|
12
|
+
/** `looked`: she paged the newest lines of one chat source (no query, newest first, first page), so it is caught up. */
|
|
13
|
+
export declare function memoryTools(service: MemoryService, inside: () => boolean, looked?: (sourceId: string) => void): ToolDefinition[];
|
|
13
14
|
/**
|
|
14
15
|
* Gives world sessions their tools (long-term memory, her mood), whatever the life line does: a session has them
|
|
15
16
|
* while it is in her world, and loses them when it leaves. A registration that fails is a fault, never a broken agent.
|
|
16
17
|
*/
|
|
17
18
|
export declare function createWorldToolRegistry(deps: {
|
|
18
|
-
tools(inside: () => boolean): ToolDefinition[];
|
|
19
|
+
tools(inside: () => boolean, agent: Agent): ToolDefinition[];
|
|
19
20
|
inWorld(agent: Agent): boolean;
|
|
20
21
|
faults: Faults;
|
|
21
22
|
logger: {
|
package/lib/memoryTools.js
CHANGED
|
@@ -21,7 +21,8 @@ function compactFind(page) {
|
|
|
21
21
|
...(page.coverage.state === 'ready' ? {} : { coverage: page.coverage }),
|
|
22
22
|
};
|
|
23
23
|
}
|
|
24
|
-
|
|
24
|
+
/** `looked`: she paged the newest lines of one chat source (no query, newest first, first page), so it is caught up. */
|
|
25
|
+
export function memoryTools(service, inside, looked) {
|
|
25
26
|
const checked = async (work) => {
|
|
26
27
|
if (!inside())
|
|
27
28
|
throw new OutsideWorldError();
|
|
@@ -39,7 +40,13 @@ export function memoryTools(service, inside) {
|
|
|
39
40
|
linkedTo: { type: 'string' }, order: { type: 'string' }, limit: { type: 'integer' }, cursor: { type: 'string' },
|
|
40
41
|
},
|
|
41
42
|
output,
|
|
42
|
-
execute: async (input) =>
|
|
43
|
+
execute: async (input) => {
|
|
44
|
+
const found = compactFind(await checked(() => service.find({ limit: TOOL_FIND_LIMIT, ...input })));
|
|
45
|
+
const { sourceId, query, cursor, order } = input;
|
|
46
|
+
if (typeof sourceId === 'string' && sourceId.startsWith('chat:') && !query && !cursor && (order ?? 'newest') === 'newest')
|
|
47
|
+
looked?.(sourceId);
|
|
48
|
+
return JSON.stringify(found);
|
|
49
|
+
},
|
|
43
50
|
}),
|
|
44
51
|
defineTool({
|
|
45
52
|
name: 'memory_read',
|
|
@@ -79,7 +86,7 @@ export function createWorldToolRegistry(deps) {
|
|
|
79
86
|
return false;
|
|
80
87
|
const done = [];
|
|
81
88
|
try {
|
|
82
|
-
for (const tool of deps.tools(() => deps.inWorld(agent)))
|
|
89
|
+
for (const tool of deps.tools(() => deps.inWorld(agent), agent))
|
|
83
90
|
done.push(registerScopedTool(agent, tool, () => deps.inWorld(agent)));
|
|
84
91
|
registered.set(agent, done);
|
|
85
92
|
deps.faults.clear(key(agent));
|
package/lib/mood.d.ts
CHANGED
|
@@ -38,7 +38,11 @@ export declare function moodValues(mood: Extract<Mood, {
|
|
|
38
38
|
kind: 'mood';
|
|
39
39
|
}>): MoodValue[];
|
|
40
40
|
/** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
|
|
41
|
-
|
|
41
|
+
/** When she last changed the file, or undefined when it is gone since it was read. */
|
|
42
|
+
export declare function moodUpdatedAt(path: string): number | undefined;
|
|
43
|
+
/** How long her mood has stood, so she can tell an old one from a fresh one; the plugin never ages the values themselves. */
|
|
44
|
+
export declare function moodAge(updatedAt: number, now: number): string;
|
|
45
|
+
export declare function moodText(mood: Mood, age?: string): string | undefined;
|
|
42
46
|
export type MoodView = {
|
|
43
47
|
kind: 'none';
|
|
44
48
|
} | {
|
package/lib/mood.js
CHANGED
|
@@ -67,12 +67,33 @@ export function moodValues(mood) {
|
|
|
67
67
|
}
|
|
68
68
|
const outsideNote = (names) => `(${names.join('、')} 不在固定的心情里,没有算进去;换成最接近的那个,细的写进小事)`;
|
|
69
69
|
/** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
|
|
70
|
-
|
|
70
|
+
/** When she last changed the file, or undefined when it is gone since it was read. */
|
|
71
|
+
export function moodUpdatedAt(path) {
|
|
72
|
+
try {
|
|
73
|
+
return statSync(path).mtimeMs;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** How long her mood has stood, so she can tell an old one from a fresh one; the plugin never ages the values themselves. */
|
|
80
|
+
export function moodAge(updatedAt, now) {
|
|
81
|
+
const minutes = Math.floor(Math.max(0, now - updatedAt) / 60_000);
|
|
82
|
+
if (minutes < 1)
|
|
83
|
+
return '刚改过';
|
|
84
|
+
if (minutes < 60)
|
|
85
|
+
return `最后改于 ${minutes} 分钟前`;
|
|
86
|
+
const hours = Math.floor(minutes / 60), days = Math.floor(hours / 24);
|
|
87
|
+
if (!days)
|
|
88
|
+
return `最后改于 ${hours} 小时前`;
|
|
89
|
+
return `最后改于 ${days} 天${hours % 24 ? ` ${hours % 24} 小时` : ''}前`;
|
|
90
|
+
}
|
|
91
|
+
export function moodText(mood, age) {
|
|
71
92
|
if (mood.kind === 'none')
|
|
72
93
|
return undefined;
|
|
73
94
|
if (mood.kind === 'failed')
|
|
74
95
|
return '【我的心情值】mood.md 读不出来,之前那条不再算数;可以用 set_mood 重新记。';
|
|
75
|
-
const lines = [`【我的心情值】${moodValues(mood).map(value => `${value.name} ${value.value}`).join(' · ')}
|
|
96
|
+
const lines = [`【我的心情值】${moodValues(mood).map(value => `${value.name} ${value.value}`).join(' · ')}(以最新一条为准,${age ? `${age},` : ''}用 set_mood 改)`];
|
|
76
97
|
if (mood.trivia.length)
|
|
77
98
|
lines.push(`旁边:${mood.trivia.join(';')}${mood.cut ? '……后面还有' : ''}`);
|
|
78
99
|
if (mood.outside.length)
|
|
@@ -86,10 +107,6 @@ export function moodView(path) {
|
|
|
86
107
|
const mood = readMood(path);
|
|
87
108
|
if (mood.kind !== 'mood')
|
|
88
109
|
return mood;
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
updatedAt = statSync(path).mtime.toISOString();
|
|
92
|
-
}
|
|
93
|
-
catch { /* removed since it was read; the values still stand */ }
|
|
94
|
-
return { kind: 'mood', values: moodValues(mood), trivia: mood.trivia, cut: mood.cut, unread: mood.unread, outside: mood.outside, updatedAt };
|
|
110
|
+
const changed = moodUpdatedAt(path);
|
|
111
|
+
return { kind: 'mood', values: moodValues(mood), trivia: mood.trivia, cut: mood.cut, unread: mood.unread, outside: mood.outside, updatedAt: changed === undefined ? null : new Date(changed).toISOString() };
|
|
95
112
|
}
|
package/lib/promptSection.d.ts
CHANGED
|
@@ -18,6 +18,8 @@ export interface WorldPromptSource {
|
|
|
18
18
|
inWorkspace?(sessionId: string): boolean;
|
|
19
19
|
/** Long-term memory; its two tools are registered on world sessions. */
|
|
20
20
|
memory?: import('./memory.ts').MemoryService;
|
|
21
|
+
/** News from where she is not, told to her world sessions. */
|
|
22
|
+
elsewhere?: import('./elsewhere.ts').Elsewhere;
|
|
21
23
|
}
|
|
22
24
|
/** Replace the system prompt only for this world's preset and workspace. */
|
|
23
25
|
export declare function createPromptSections(config: WorldConfig, world: WorldPromptSource, token: symbol, deps: {
|
package/lib/runtime.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
-
import { createSystemMessage, createUserMessage, isAgentLoopRequest
|
|
2
|
+
import { createSystemMessage, createUserMessage, isAgentLoopRequest } from '@deepseek-ai/dsh-llm';
|
|
3
3
|
import { appendPluginRecord, pluginRecordOf, SessionLogOffset } from '@deepseek-ai/dsh-session';
|
|
4
4
|
import "./hostContract.js";
|
|
5
5
|
import { isOrdinarySession } from "./archive.js";
|
|
6
|
-
import { compactsWhole } from "./compaction.js";
|
|
6
|
+
import { compactsWhole, llmError } from "./compaction.js";
|
|
7
7
|
import { compactionFor } from "./console/homeApply.js";
|
|
8
8
|
import { Faults } from "./faults.js";
|
|
9
|
-
import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
|
|
10
|
-
import { MOOD_CLEARED, moodText, readMood } from "./mood.js";
|
|
9
|
+
import { createHistory, excludePresentMessages, GROUP_PRIVACY, renderHistory } from "./history.js";
|
|
10
|
+
import { MOOD_CLEARED, moodAge, moodText, moodUpdatedAt, readMood } from "./mood.js";
|
|
11
11
|
import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
|
|
12
12
|
import { moodTools } from "./moodTools.js";
|
|
13
|
+
import { createSessionNews } from "./sessionNews.js";
|
|
13
14
|
import { assembledWorlds, createPromptSections } from "./promptSection.js";
|
|
14
15
|
import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
|
|
15
16
|
import { worldNames } from "./worldPrompt.js";
|
|
@@ -17,6 +18,7 @@ import { reassembleOnChange } from "./worldScope.js";
|
|
|
17
18
|
import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
|
|
18
19
|
const memorySource = 'dsh-world-history';
|
|
19
20
|
const moodSource = 'dsh-world-mood';
|
|
21
|
+
const elsewhereSource = 'dsh-world-elsewhere';
|
|
20
22
|
const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
|
|
21
23
|
const promptRecord = 'plugin:dsh-world/system-prompt';
|
|
22
24
|
const legacyPromptReset = 'plugin:dsh-world/legacy-prompt-reset';
|
|
@@ -54,7 +56,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
|
|
|
54
56
|
}
|
|
55
57
|
if (!log.reset && event.type === 'user/message') {
|
|
56
58
|
const kind = event.data.source.kind;
|
|
57
|
-
log.sawWorldContext ||= kind === memorySource || kind === moodSource || kind === 'dsh-world-channel-context';
|
|
59
|
+
log.sawWorldContext ||= kind === memorySource || kind === moodSource || kind === elsewhereSource || kind === 'dsh-world-channel-context';
|
|
58
60
|
}
|
|
59
61
|
if (event.type === legacyPromptReset && pluginRecordOf(event))
|
|
60
62
|
log.reset = true;
|
|
@@ -90,7 +92,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
|
|
|
90
92
|
});
|
|
91
93
|
}
|
|
92
94
|
const revoked = (source, session) => {
|
|
93
|
-
if (source?.kind === memorySource || source?.kind === moodSource)
|
|
95
|
+
if (source?.kind === memorySource || source?.kind === moodSource || source?.kind === elsewhereSource)
|
|
94
96
|
return !session || !authorize(session, source.worldId);
|
|
95
97
|
return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
|
|
96
98
|
};
|
|
@@ -155,7 +157,7 @@ export function guardWorldContext(ctx, authorize, hasWorldRoom) {
|
|
|
155
157
|
}
|
|
156
158
|
yield* next();
|
|
157
159
|
if (compaction && session && scope && authorize(session, prompt?.worldId) !== scope)
|
|
158
|
-
throw
|
|
160
|
+
throw llmError(failure);
|
|
159
161
|
});
|
|
160
162
|
}
|
|
161
163
|
/**
|
|
@@ -195,7 +197,11 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
195
197
|
const prompts = world && createPromptSections(config, world, scopeToken, { logger: ctx.logger });
|
|
196
198
|
const memory = new WeakMap();
|
|
197
199
|
const service = world?.memory;
|
|
198
|
-
const
|
|
200
|
+
const sessionNews = world?.elsewhere ? createSessionNews({ store, isHome: id => !!world.isHome(id), partner: () => world.names?.().partner ?? world.prompt.names.partner }) : undefined;
|
|
201
|
+
const worldTools = (inside, agent) => [
|
|
202
|
+
...service ? memoryTools(service, inside, sourceId => sessionNews?.looked(agent.session, sourceId.slice('chat:'.length))) : [],
|
|
203
|
+
...config.moodFile ? moodTools(config.moodFile, inside) : [],
|
|
204
|
+
];
|
|
199
205
|
const tools = service || config.moodFile ? createWorldToolRegistry({ tools: worldTools, inWorld: agent => !stopped && included(agent.session), faults, logger: ctx.logger }) : undefined;
|
|
200
206
|
/** The world tools (memory, mood) follow world membership, whatever the life line does. */
|
|
201
207
|
const syncTools = (agent) => !tools ? false : included(agent.session) ? tools.attach(agent) : tools.detach(agent);
|
|
@@ -264,8 +270,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
264
270
|
return event?.type === 'user/message' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') : undefined;
|
|
265
271
|
}
|
|
266
272
|
/**
|
|
267
|
-
* Her mood rides just before the time block, appended like it
|
|
268
|
-
*
|
|
273
|
+
* Her mood rides just before the time block on every step, appended like it and never replacing an old one, so the
|
|
274
|
+
* cached prefix stays whole and compaction clears them all. Every step, because one wake can run a hundred steps: a
|
|
275
|
+
* snapshot shown only when it changed sank far behind her work and she stopped noticing it, so it never moved.
|
|
269
276
|
*/
|
|
270
277
|
function moodMessage(session) {
|
|
271
278
|
if (!config.moodFile)
|
|
@@ -275,9 +282,22 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
275
282
|
faults.set('mood', `mood.md 读不出来:${mood.message}`);
|
|
276
283
|
else
|
|
277
284
|
faults.clear('mood');
|
|
278
|
-
const
|
|
279
|
-
const
|
|
280
|
-
|
|
285
|
+
const updatedAt = mood.kind === 'mood' ? moodUpdatedAt(config.moodFile) : undefined;
|
|
286
|
+
const shown = moodText(mood, updatedAt === undefined ? undefined : moodAge(updatedAt, now()));
|
|
287
|
+
const latest = shown === undefined ? latestMood(session) : undefined;
|
|
288
|
+
// A removed file is said once, so the old values stop counting.
|
|
289
|
+
const text = shown ?? (latest === undefined || latest === MOOD_CLEARED ? undefined : MOOD_CLEARED);
|
|
290
|
+
return text === undefined ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
|
|
291
|
+
}
|
|
292
|
+
const inGroup = (session) => store.channelType(session.id) === 'group';
|
|
293
|
+
/**
|
|
294
|
+
* News from elsewhere is an event, told once: at a turn's start it comes before the new message (what gathered
|
|
295
|
+
* before it arrived), later in the turn at the step's end, ahead of her mood and the time.
|
|
296
|
+
*/
|
|
297
|
+
function elsewhereMessage(session) {
|
|
298
|
+
const news = world?.elsewhere?.take(session, new Date(now()));
|
|
299
|
+
const text = news && inGroup(session) ? `${news}\n${GROUP_PRIVACY}` : news;
|
|
300
|
+
return text === undefined ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: elsewhereSource, form: 'notice', worldId: config.worldId } });
|
|
281
301
|
}
|
|
282
302
|
function flushRetired(session, state, position) {
|
|
283
303
|
const retiring = state.retiring;
|
|
@@ -315,7 +335,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
315
335
|
async function freshBlock(session, state) {
|
|
316
336
|
const turns = await history.loadRecentTurns(memoryTurns(), archivedByScope);
|
|
317
337
|
const present = new Set(session.deriveMessages().map(message => message.id));
|
|
318
|
-
const
|
|
338
|
+
const rendered = renderHistory(excludePresentMessages(turns, present), config.timeZone, names(), config.archiveScope === 'home');
|
|
339
|
+
const text = rendered && inGroup(session) ? `${rendered}\n\n${GROUP_PRIVACY}` : rendered;
|
|
319
340
|
// A session entering this workspace can still carry an inherited recall from another world.
|
|
320
341
|
retireMemory(session, state, included(session));
|
|
321
342
|
return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall', worldId: config.worldId } }) : undefined;
|
|
@@ -330,6 +351,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
330
351
|
/** `fresh`: her world was just started from the console, so what was said while it was stopped is not archived. */
|
|
331
352
|
async function start(options = {}) {
|
|
332
353
|
try {
|
|
354
|
+
if (sessionNews && world?.elsewhere)
|
|
355
|
+
disposers.push(world.elsewhere.register(sessionNews.source));
|
|
333
356
|
disposers.push(ctx.on('session/event', (session, event) => {
|
|
334
357
|
if (event.type === 'agent-preset/selected') {
|
|
335
358
|
const agent = ctx.agents.get(session.id);
|
|
@@ -346,6 +369,7 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
346
369
|
}
|
|
347
370
|
if (state && compacted) {
|
|
348
371
|
state.reload = true;
|
|
372
|
+
world?.elsewhere?.retell(session);
|
|
349
373
|
}
|
|
350
374
|
// The host assembles the system prompt after turn/start, so a cold session's first request already has both.
|
|
351
375
|
const cold = !!state && event.type === 'turn/start' && state.lastRequestAt !== undefined && now() - state.lastRequestAt >= coldHours() * 60 * 60_000;
|
|
@@ -388,6 +412,8 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
388
412
|
await attach(agent);
|
|
389
413
|
const state = memory.get(agent.session);
|
|
390
414
|
const leave = () => {
|
|
415
|
+
if (state.inScope)
|
|
416
|
+
world?.elsewhere?.retell(agent.session);
|
|
391
417
|
state.restart ||= state.inScope;
|
|
392
418
|
state.inScope = false;
|
|
393
419
|
retireMemory(agent.session, state);
|
|
@@ -402,9 +428,10 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
|
|
|
402
428
|
signal.throwIfAborted();
|
|
403
429
|
if (!included(agent.session))
|
|
404
430
|
return leave();
|
|
405
|
-
const mood = moodMessage(agent.session);
|
|
406
|
-
|
|
407
|
-
|
|
431
|
+
const news = elsewhereMessage(agent.session), mood = moodMessage(agent.session);
|
|
432
|
+
const head = news && step === 1 ? [news] : [], tail = [...(news && step > 1 ? [news] : []), ...(mood ? [mood] : [])];
|
|
433
|
+
if (head.length || tail.length)
|
|
434
|
+
decision = { ...decision, messages: [...head, ...decision.messages, ...tail] };
|
|
408
435
|
if (!state.reload)
|
|
409
436
|
return decision;
|
|
410
437
|
// A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Session } from '@deepseek-ai/dsh-session';
|
|
2
|
+
import { type ElsewhereSource } from './elsewhere.ts';
|
|
3
|
+
import type { ArchiveStore } from './store.ts';
|
|
4
|
+
/**
|
|
5
|
+
* Her other sessions as a source of news: what was archived there since this session started hearing, counted per
|
|
6
|
+
* session, never the words. It starts at the archive's end, so an upgrade or a restart tells nothing old; she reads a
|
|
7
|
+
* place with memory_find on its sourceId, and once she has paged its newest lines it is caught up.
|
|
8
|
+
*/
|
|
9
|
+
export declare function createSessionNews(deps: {
|
|
10
|
+
store: Pick<ArchiveStore, 'readSince' | 'lastSequence'>;
|
|
11
|
+
isHome(sessionId: string): boolean;
|
|
12
|
+
partner(): string;
|
|
13
|
+
}): {
|
|
14
|
+
source: ElsewhereSource;
|
|
15
|
+
/** She paged the newest lines of that session from this one: it is caught up. */
|
|
16
|
+
looked(session: Session, sessionId: string): void;
|
|
17
|
+
};
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { chatLabel, chatName } from "./ecosystem/shared/identity.js";
|
|
2
|
+
import { ago } from "./elsewhere.js";
|
|
3
|
+
import { sessionMarker } from "./history.js";
|
|
4
|
+
/**
|
|
5
|
+
* Her other sessions as a source of news: what was archived there since this session started hearing, counted per
|
|
6
|
+
* session, never the words. It starts at the archive's end, so an upgrade or a restart tells nothing old; she reads a
|
|
7
|
+
* place with memory_find on its sourceId, and once she has paged its newest lines it is caught up.
|
|
8
|
+
*/
|
|
9
|
+
export function createSessionNews(deps) {
|
|
10
|
+
const seen = new WeakMap();
|
|
11
|
+
const labelOf = (sessionId, record) => deps.isHome(sessionId) ? '家'
|
|
12
|
+
: record.channel && record.conversationType === 'group' ? chatLabel(record.channel, 'group', chatName(record) ?? record.conversationId ?? '') : undefined;
|
|
13
|
+
/** Reads what was archived since the last look, keeping only other sessions' lines. */
|
|
14
|
+
function catchUp(session) {
|
|
15
|
+
const state = seen.get(session);
|
|
16
|
+
if (!state) {
|
|
17
|
+
const fresh = { scanned: deps.store.lastSequence(), places: new Map() };
|
|
18
|
+
seen.set(session, fresh);
|
|
19
|
+
return fresh;
|
|
20
|
+
}
|
|
21
|
+
for (let batch = deps.store.readSince(state.scanned); batch.length; batch = deps.store.readSince(state.scanned)) {
|
|
22
|
+
for (const { sequence, record } of batch) {
|
|
23
|
+
state.scanned = sequence;
|
|
24
|
+
const id = record.sourceSessionId;
|
|
25
|
+
if (id === session.id)
|
|
26
|
+
continue;
|
|
27
|
+
const place = state.places.get(id) ?? { count: 0, lastSequence: sequence, last: record };
|
|
28
|
+
place.count += 1;
|
|
29
|
+
place.lastSequence = sequence;
|
|
30
|
+
place.last = record;
|
|
31
|
+
place.label ??= labelOf(id, record);
|
|
32
|
+
state.places.set(id, place);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return state;
|
|
36
|
+
}
|
|
37
|
+
const source = {
|
|
38
|
+
look: '别的会话用 memory_find 带上那一行的 sourceId 翻最新的',
|
|
39
|
+
news(now, session) {
|
|
40
|
+
return [...catchUp(session).places].sort(([, a], [, b]) => b.lastSequence - a.lastSequence).map(([id, place]) => {
|
|
41
|
+
const who = place.last.role === 'assistant' ? '我自己' : place.last.speakerName ?? deps.partner();
|
|
42
|
+
const label = place.label ?? `另一个窗口(${sessionMarker(id)})`;
|
|
43
|
+
return {
|
|
44
|
+
key: `session:${id}`, mark: `${place.count}:${place.lastSequence}`,
|
|
45
|
+
text: `${label}有 ${place.count} 条我在这边没看到,最后是${who}(${ago(now.getTime() - Date.parse(place.last.occurredAt))});sourceId:chat:${id}`,
|
|
46
|
+
};
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
source,
|
|
52
|
+
/** She paged the newest lines of that session from this one: it is caught up. */
|
|
53
|
+
looked(session, sessionId) { catchUp(session).places.delete(sessionId); },
|
|
54
|
+
};
|
|
55
|
+
}
|
package/lib/store.d.ts
CHANGED
|
@@ -12,6 +12,11 @@ export declare function createArchiveStore(config: WorldConfig & {
|
|
|
12
12
|
hasRecord: (recordId: string) => boolean;
|
|
13
13
|
updateRecord: (recordId: string, revise: (record: ConversationRecord) => Pick<ConversationRecord, "content" | "wechatDelivery"> & Partial<SpeakerIdentity>) => Promise<void>;
|
|
14
14
|
readPage: (query: PageQuery) => Promise<RecordPage>;
|
|
15
|
+
readSince: (sequence: number, limit?: number) => {
|
|
16
|
+
sequence: number;
|
|
17
|
+
record: ConversationRecord;
|
|
18
|
+
}[];
|
|
19
|
+
lastSequence: () => number;
|
|
15
20
|
readTurn: (turnId: string, afterSeq?: number, limit?: number) => Promise<ConversationRecord[]>;
|
|
16
21
|
progress: (sessionId: string) => ExportProgress;
|
|
17
22
|
forgetProgress: (sessionId: string) => void;
|
|
@@ -22,6 +27,7 @@ export declare function createArchiveStore(config: WorldConfig & {
|
|
|
22
27
|
};
|
|
23
28
|
close: () => void;
|
|
24
29
|
channelSession: (key: string) => string | undefined;
|
|
30
|
+
channelType: (sessionId: string) => "private" | "group" | undefined;
|
|
25
31
|
bindChannelSession: (key: string, sessionId: string) => void;
|
|
26
32
|
delivery: (recordId: string) => DeliveryState | undefined;
|
|
27
33
|
registerDelivery: (recordId: string, total: number) => void;
|
package/lib/store.js
CHANGED
|
@@ -115,7 +115,7 @@ export function createArchiveStore(config) {
|
|
|
115
115
|
async function readPage(query) {
|
|
116
116
|
flushExports();
|
|
117
117
|
const before = query.before;
|
|
118
|
-
const maxSequence = before?.maxSequence ??
|
|
118
|
+
const maxSequence = before?.maxSequence ?? lastSequence();
|
|
119
119
|
const rows = (before
|
|
120
120
|
? db.prepare('SELECT * FROM records WHERE sequence<=? AND (day, occurredAt, recordId)<(?,?,?) ORDER BY day DESC, occurredAt DESC, recordId DESC LIMIT ?').all(maxSequence, before.date, before.occurredAt, before.recordId, query.limit + 1)
|
|
121
121
|
: db.prepare('SELECT * FROM records WHERE sequence<=? ORDER BY day DESC, occurredAt DESC, recordId DESC LIMIT ?').all(maxSequence, query.limit + 1));
|
|
@@ -146,6 +146,13 @@ export function createArchiveStore(config) {
|
|
|
146
146
|
});
|
|
147
147
|
flushExports();
|
|
148
148
|
}
|
|
149
|
+
function lastSequence() {
|
|
150
|
+
return Number(db.prepare('SELECT COALESCE(MAX(sequence),0) AS n FROM records').get()?.n);
|
|
151
|
+
}
|
|
152
|
+
/** Records in the order they were archived, after a point: what is new since then. */
|
|
153
|
+
function readSince(sequence, limit = pageSize) {
|
|
154
|
+
return db.prepare('SELECT * FROM records WHERE sequence>? ORDER BY sequence LIMIT ?').all(sequence, limit).map(row => ({ sequence: Number(row.sequence), record: decode(row) }));
|
|
155
|
+
}
|
|
149
156
|
async function readTurn(turnId, afterSeq = -1, limit = pageSize) {
|
|
150
157
|
flushExports();
|
|
151
158
|
return db.prepare('SELECT * FROM records WHERE turnId=? AND sourceSeq>? ORDER BY sourceSeq LIMIT ?').all(turnId, afterSeq, limit).map(decode);
|
|
@@ -179,6 +186,13 @@ export function createArchiveStore(config) {
|
|
|
179
186
|
function channelSession(key) {
|
|
180
187
|
return db.prepare('SELECT sessionId FROM channelSessions WHERE conversationKey=? LIMIT 1').get(key)?.sessionId;
|
|
181
188
|
}
|
|
189
|
+
/** Whether a session is one of her channel conversations, and which kind; undefined for home and DSH windows. */
|
|
190
|
+
function channelType(sessionId) {
|
|
191
|
+
const key = db.prepare('SELECT conversationKey FROM channelSessions WHERE sessionId=? LIMIT 1').get(sessionId)?.conversationKey;
|
|
192
|
+
if (typeof key !== 'string')
|
|
193
|
+
return undefined;
|
|
194
|
+
return JSON.parse(key)[2] === 'group' ? 'group' : 'private';
|
|
195
|
+
}
|
|
182
196
|
function bindChannelSession(key, sessionId) {
|
|
183
197
|
transaction(() => { db.prepare('INSERT INTO channelSessions VALUES (?,?) ON CONFLICT(conversationKey) DO UPDATE SET sessionId=excluded.sessionId').run(key, sessionId); });
|
|
184
198
|
}
|
|
@@ -197,6 +211,6 @@ export function createArchiveStore(config) {
|
|
|
197
211
|
db.prepare('UPDATE channelDeliveries SET body=? WHERE recordId=?').run(JSON.stringify(revise(previous)), recordId);
|
|
198
212
|
});
|
|
199
213
|
}
|
|
200
|
-
return { commitRecords, hasRecord, updateRecord, readPage, readTurn, progress, forgetProgress, sourcePage, stats, close,
|
|
201
|
-
channelSession, bindChannelSession, delivery, registerDelivery, updateDelivery, memory, snapshotTo };
|
|
214
|
+
return { commitRecords, hasRecord, updateRecord, readPage, readSince, lastSequence, readTurn, progress, forgetProgress, sourcePage, stats, close,
|
|
215
|
+
channelSession, channelType, bindChannelSession, delivery, registerDelivery, updateDelivery, memory, snapshotTo };
|
|
202
216
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-world",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.6",
|
|
4
4
|
"description": "Cross-session memory, persona and life routines for DSH, with a world console, tool-free compaction, native QQ and Windows WeChat messaging, group history and quoted replies",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|