dsh-world 0.7.3 → 0.7.4

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 CHANGED
@@ -1,5 +1,14 @@
1
1
  # 更新日志
2
2
 
3
+ ## 0.7.4 — 2026-11-10
4
+
5
+ 本版修复在 DSH 0.2.1 上装过插件的桌面版用户升级到 DSH 0.2.2 后会话打不开的问题,微信私聊不再因为她忙着做别的而停收;新增她自己记的心情值,「我是谁」固定成六段、上限放宽到 5000 字。
6
+
7
+ - 修复在 DSH 0.2.1 上装过插件的桌面版用户,升级到 DSH 0.2.2 后用 `standard` 预设的会话全都打不开:健康里出现「家打不开」,原因是 `tool-subagent-list-agents (@deepseek-ai/dsh-tool-subagent-control/list-agents): never started`,闹钟和微信消息都进不了家。插件换压缩时会把整份预设写进 profile,副本里的 `list-agents` 那一行在 DSH 0.2.2 已经不存在(这个工具并进了主包),DSH 就整个预设都不挂。现在每次启动都检查 profile 里的预设副本:DSH 自带的预设已经不带这一行时,先备份 `cordis.patch.yml` 再删掉这一行,并在健康状态里说明,重启 DSH 后恢复。DSH 0.2.1 上这一行仍然有效,不会被删;profile 里没有副本、或已经手动删过的,什么都不改;直接装在 DSH 0.2.2 上的新用户,副本本来就不带这一行。故障期间发来的微信消息不会自动补送,处理方法见 [注意事项](NOTES.md#默认换用只留对话的压缩)。
8
+ - 微信私聊不再因为她回完话还在忙而停下等人核对:她用 `wechat_send` 回了这个聊天,插件就把这次请求当作已回复,不再等这一轮剩下的事做完。以前一轮超过 3 分钟就回 503,适配器把已经回过的消息当成结果不明,整个私聊停收,要人跑 `Acknowledge`。现在她正忙、3 分钟内没能把消息交给她时,插件回 409,适配器撤回这批的待确认标记,下次轮询重新交给她。已经在等核对的消息照旧要 `Acknowledge` 一次,之后不再因此卡住;插件和适配器同包更新,只更新插件、旧适配器收到 409 时会退出重启,那条消息留在待核对,和以前一样。
9
+ - 新增心情值(#41,设计来自 @ql0423):她在房间里的 `mood.md` 一行写一种心情,「名字 数值」,0 到 10 的整数;默认一组是开心、兴奋、平静、累、困、烦、难过、紧张,没写的算 0,也可以加自己的词;不以数字结尾的行是旁边的几件小事,最多三行、每行十二字,多的截断并标「……后面还有」。她世界里的会话(家、微信、QQ 群)在每轮开头、以及她改过之后的下一步,把当前的心情值作为一条快照放在时间块前面;没变就不重复放,变了就追加一条新的、旧的不删(删掉历史里的旧快照会让之后的缓存全部失效),以最新一条为准,压缩时一起清掉、不写进摘要。插件只读,不判断、不衰减、不提醒她改,快照不进归档。没有 `mood.md` 就什么都不放;文件删掉或清空后说一次「之前那条不再算数」;写错的行只在快照里告诉她,文件读不出来才进控制台健康。#41 原先的 `focus.md` 纸条并入了 `mood.md`,不再单独读,写过的文件原样留在房间里。新用户和用默认模板的已有世界,房间段下一轮就读到怎么写;自定义了 `world-prompt.md` 的,模板不会被改写,她不知道这个文件就不会写,也就什么都不放,想用可以照 `templates/world-prompt.md` 的房间段补一句;宿主里已有、进了她工作区的会话,她写了以后同样带上快照。
10
+ - 「我是谁」固定分成六段:性子、喜欢和不喜欢、说话方式、生活习惯、和伙伴的关系、自我描述(她觉得自己是个什么样的人)。每段 800 字以内、全篇 5000 字以内,不另开新标题,标题和正文不写日期和修改记录。以前只说「只写现在的我」,她遇到新东西就开一个新小节,越写越长,超过上限的部分读不进系统提示词。系统提示词读自述的上限从 4000 字提到 5000 字,和全篇字数一致,写满也能完整读到;自述写满时每次请求多带约 1000 字。新世界从第一版就照这个写;用默认模板的已有世界下一轮读到新规则,原来的自述不会被改动,由她下次修改时按六段整理;世界目录里自定义了 `world-prompt.md` 的,模板不会被改写,想用可以照 `templates/world-prompt.md` 的「我是谁」段替换自己那一段。
11
+
3
12
  ## 0.7.3 — 2026-11-06
4
13
 
5
14
  本版适配 DSH 0.2.2,同一 profile 可以运行多个隔离的世界,人设和提示词保存后现有会话下一轮就读到,并修复预设切换、QQ 看门狗和停机后的压缩。**控制台和接入地址的路径变了**,手写过旧地址的要跟着改。DSH 0.2.2 要求 Node.js 至少 24.9;插件仍兼容 DSH 0.2.1。
package/NOTES.md CHANGED
@@ -41,6 +41,8 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\enable-tool-free-c
41
41
 
42
42
  整份写进 profile 的代价:之后 DSH 升级对这个预设的改动(新工具、提示词调整)不会自动进来,因为 profile 里这份会盖住 DSH 自带的。想跟上新版,恢复备份(或删掉 profile 里 `preset-standard` 那一项),再把 `world.json` 里的 `compactionSwapped` 删掉,下次启动会按新版预设重新换一次。只影响这个预设:其他预设的会话仍用原版压缩。
43
43
 
44
+ DSH 从预设里删掉某一行时,这份副本还留着它,DSH 找不到那个插件就整个预设都不挂,用这个预设的会话全都打不开。已知的一处:DSH 0.2.2 把 `list_agents` 并进了 `dsh-tool-subagent-control`,副本里 `@deepseek-ai/dsh-tool-subagent-control/list-agents` 那一行不再存在,健康里是「家打不开……never started」。插件每次启动会检查 profile 里的每份预设副本,DSH 自带的预设已经不带这一行时,先备份 `cordis.patch.yml` 再删掉它,健康里说明删了哪个预设,重启 DSH 后恢复;DSH 0.2.1 上这一行仍然有效,不会被删。别的行插件不会替你删:遇到同样「never started」的报错,退出 DSH,对照 DSH 自带的预设,手动删掉报错里那一行。故障期间发来的微信消息不会自动补送,那个聊天会停在「上次消息结果尚未确认」,按 [微信模块](src/ecosystem/wechat/windows/README.md) 的 `Acknowledge` 流程核对(运行中的适配器会占着它,先在控制台关掉微信模块,做完再打开),然后重发那条消息。
45
+
44
46
  换不成时(找不到预设、预设里没有或有多条原版压缩),插件不改任何文件,在健康状态里说明:自动压缩仍由预设自带的压缩负责,下面的 75% 触发线不生效。控制台的「应用并压缩」和回顾后压缩不受影响,它们直接使用家会话预设里的那个压缩。
45
47
 
46
48
  ### 微信首次接入与升级
@@ -108,7 +110,7 @@ powershell -NoProfile -ExecutionPolicy Bypass -File .\scripts\enable-tool-free-c
108
110
  ### 长期记忆的查找
109
111
 
110
112
  - **没有索引,也就没有升级时的建库**:聊天在 `archive.sqlite` 的原表里直接按字面扫描,日记等文件在查询时直接读,没有额外的表、队列或重建,旧档案升级后第一次查询就能用。扫描随聊天量线性变慢:我们量过合成数据,约 10 万条 50 毫秒、50 万条 300 毫秒以内,陪伴场景远用不到这个量级。
111
- - **查找的范围**:聊天和日记(`diaryDir` 里的 `.md`/`.txt`,一层)。查找读取日记的当前版本。自述放进系统提示词,最多读前 4000 字。
113
+ - **查找的范围**:聊天和日记(`diaryDir` 里的 `.md`/`.txt`,一层)。查找读取日记的当前版本。自述放进系统提示词,最多读前 5000 字。
112
114
  - **查找的限制**:查询只认字面文字(区分大小写);没有共同文字、时间线索的往事找不回来;有来源读不到时结果里会带 `coverage`,零结果不代表没发生过;分页只限制返回的量,不限制扫描的量。
113
115
  - **一次返回的量是故意压小的**:`memory_find` 默认 8 条、每条摘录约 200 字,`memory_read` 默认 2000 字,因为工具结果会在这一轮之后的每一步被重发。要更多就翻页(`nextCursor`)或读原文,不要一次要几十条。
114
116
 
package/README.md CHANGED
@@ -20,6 +20,7 @@
20
20
  - **近期记忆**:你们最近数轮的对话原文,每次开始对话、每次压缩之后,以及一个窗口隔了很久(默认 24 小时,控制台可改)再开口时,都放在她眼前,谁、什么时候、说了什么,一字不差。轮数在控制台里填,默认 200。
21
21
  - **日记**:人生里重要的事,她自己写进日记,一天一篇。这是她的长期记忆。
22
22
  - **我是谁**:她写给自己的一份自述,随着她变化而改写。每晚回顾前,插件会留一份当时的版本,改过的都找得回来。
23
+ - **心情值**:`room/mood.md` 是她自己写的,一行一件:`开心 6` 这样的「名字 数值」是一种心情(0 到 10 的整数),不以数字结尾的行是心情旁边的几件小事(最多三行)。默认的一组是开心、兴奋、平静、累、困、烦、难过、紧张,没写的算 0,她也可以加自己的词。她世界里的会话在每轮开头、以及她改过之后的下一步,把当前的心情值作为一条快照放在时间块前面;没变就不重复放,旧的那条不删,以最新一条为准,压缩时一起清掉,不打乱缓存。插件只读、不判断、不衰减、不提醒她改;没有 `mood.md` 就什么都不放。快照不进归档;写错的行只在快照里告诉她,文件读不出来才进健康状态。
23
24
  - **范围内的原文留着**:按天归档用户和助手的正文。近期记忆以外的事,她可以自己去翻。
24
25
  - **找回过去**:`memory_find` 与 `memory_read` 两个工具(一次默认只返回 8 条、每条约 200 字的摘录,要更多自己翻页或读原文,免得每轮重发的上下文越滚越大),按原文里的字面线索、时间、种类或来源,在聊天原文和日记里统一查找,并读原文。控制台的「档案」页是同一份查找的只读入口。
25
26
 
@@ -198,7 +199,7 @@ node <DSH 自带 pnpm 的入口文件> add dsh-world@latest --ignore-scripts --r
198
199
 
199
200
  **长期记忆的查找**(`memory_find`、`memory_read`,控制台「档案」页同源):
200
201
 
201
- - 聊天在 `archive.sqlite` 的原表里直接按字面扫描,日记在查询时直接读文件。自述放进她的系统提示词,最多读前 4000 字。
202
+ - 聊天在 `archive.sqlite` 的原表里直接按字面扫描,日记在查询时直接读文件。自述放进她的系统提示词,最多读前 5000 字。
202
203
  - `memory_find` 参数:`query`(原文里的一小段字面文字,区分大小写,不是 SQL 或搜索语法;不填就按时间翻页)、`kinds`(`conversation`、`diary`)、`from`/`to`(带时区的 ISO 时间,左闭右开,日期请换成当天零点)、`sourceId`、`turnId`(取同一轮)、`order`、`limit`(工具里默认 8,最多 100)、`cursor`。工具返回 `items`(`ref`、`time`、`kind`、`who`、`text`,摘录约 200 字)和 `nextCursor`;有来源没能读到时才带 `coverage`(`state`:`partial`,`failures`)。控制台的同源接口返回更完整的字段。`timeBasis`:聊天是发言时间,日记是日记日期,其他文件是最后改动的时间。
203
204
  - `memory_read` 参数:`ref`、`offset`(按字,默认 0)、`limit`(工具里默认 2000,最多 16000)。返回原文的一段,不是摘要,按字符分页,不会切坏一个字。聊天被修订后,旧 `ref` 报 `sourceChanged`;程序不保留旧正文。
204
205
  - `ref` 由程序生成,别手写。能解析只说明找得到出处,不说明出处支持结论。
@@ -215,7 +216,7 @@ node <DSH 自带 pnpm 的入口文件> add dsh-world@latest --ignore-scripts --r
215
216
  | 位置 | 是什么 |
216
217
  |---|---|
217
218
  | `conversations/` | 按天归档的聊天原文(给人看的导出,正本在 `archive.sqlite`) |
218
- | `room/` | 她的房间;`room/我是谁.md` 是她的自述 |
219
+ | `room/` | 她的房间;`room/我是谁.md` 是她的自述,`room/mood.md` 是她的心情值 |
219
220
  | `diary/` | 她的日记(可用 `diaryDir` 换位置) |
220
221
  | `persona.md`、`world-prompt.md`、`alarm.md` | 你写给她的人设、世界提示词和闹钟措辞 |
221
222
  | `world.json` | 世界是否在运行、每天额度、近期记忆轮数和选定归档范围 |
package/lib/compaction.js CHANGED
@@ -10,14 +10,14 @@ const summaryInstruction = [
10
10
  '现在暂停对话,改为执行上下文压缩:把上面这段会话中双方的交流整理成一段精炼的中文摘要,供你之后接着对话使用。',
11
11
  '保留用户的意图、情绪与关系进展、明确要求、重要事实、已作决定、未完成事项和最近进展;最后一条用户发言尽量按原意完整保留。以“以下是此前交流的摘要”开头的消息是更早的摘要,请与新内容合并为同一段。',
12
12
  '以【我的时间】(较早的是【你的时间】)开头的消息是你自己定的闹钟和留给自己的话,不是用户说的话;把它们当作你自己的安排来记,不要算作用户发言。',
13
- '开头写着“这是我们最近的聊天记录”(较早的写着“最近的聊天记忆”或“最近的相处记忆”)的记忆资料、系统提示里的世界提示词(含「我是谁」)和“Time sampled”开头的时间块会在压缩后重新提供,不要写进摘要。工具调用过程已从会话中删除,不要提及工具。',
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']);
20
+ const injectedSources = new Set(['time-context', 'dsh-world-history', 'dsh-world-mood']);
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
@@ -26,6 +26,11 @@ export declare function swapPresetConfig(config: unknown): {
26
26
  export interface ConfigEditor {
27
27
  entries(): ConfigEntry[];
28
28
  edit(entry: ConfigEntry, change: (raw: unknown, inherited: unknown) => unknown): Promise<void>;
29
+ /** Each row with the value DSH itself supplies beneath the profile's override (DSH 0.2.2 on). */
30
+ configuration?(): {
31
+ entry: ConfigEntry;
32
+ inherited: unknown;
33
+ }[];
29
34
  }
30
35
  interface ConfigEntry {
31
36
  options: {
@@ -40,6 +45,18 @@ interface ConfigEntry {
40
45
  * with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
41
46
  */
42
47
  export declare function swapPresetCompaction(editor: ConfigEditor, presetId: string, profileDir: string): Promise<CompactionSwap>;
48
+ /** The copied preset without the rows DSH itself no longer ships, or undefined when there is nothing to drop; the input is not changed. */
49
+ export declare function dropRetiredRows(config: unknown, inherited: unknown): unknown;
50
+ /**
51
+ * On every start, drops the retired rows from each preset copied into the profile, with a backup of the profile patch
52
+ * first. Only a row DSH no longer ships beneath the copy goes, so the same copy on DSH 0.2.1 is left alone. The editor
53
+ * reloads the row; sessions that already failed to resume come back after a DSH restart.
54
+ */
55
+ export declare function repairCopiedPresets(deps: {
56
+ editor: ConfigEditor;
57
+ profileDir: string;
58
+ report(message: string): void;
59
+ }): Promise<void>;
43
60
  /**
44
61
  * Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
45
62
  * remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
@@ -38,22 +38,39 @@ export function swapStockCompaction(profileDir) {
38
38
  }
39
39
  return { status: 'swapped', backup };
40
40
  }
41
- /** The compaction rows in a preset's plugin list, including those nested in groups (where DSH's Web host isolates it). */
42
- function compactionRows(rows, found = []) {
41
+ /** The rows of a preset's plugin list that match, including those nested in groups (where DSH's Web host isolates compaction). */
42
+ function rowsWhere(rows, match, found = []) {
43
43
  if (!Array.isArray(rows))
44
44
  return found;
45
45
  for (const row of rows) {
46
- if (row?.name === STOCK || row?.name === OURS)
46
+ if (row && match(row))
47
47
  found.push(row);
48
48
  if (row?.group)
49
- compactionRows(row.config, found);
49
+ rowsWhere(row.config, match, found);
50
50
  }
51
51
  return found;
52
52
  }
53
+ /** Removes the matching rows in place, groups included, and says how many went. */
54
+ function removeRows(rows, match) {
55
+ if (!Array.isArray(rows))
56
+ return 0;
57
+ let removed = 0;
58
+ for (let index = rows.length - 1; index >= 0; index--) {
59
+ const row = rows[index];
60
+ if (row && match(row)) {
61
+ rows.splice(index, 1);
62
+ removed++;
63
+ }
64
+ else if (row?.group)
65
+ removed += removeRows(row.config, match);
66
+ }
67
+ return removed;
68
+ }
69
+ const isCompaction = (row) => row.name === STOCK || row.name === OURS;
53
70
  /** The preset's config with its one stock compaction row renamed to ours; the input is not changed. */
54
71
  export function swapPresetConfig(config) {
55
72
  const next = structuredClone(config);
56
- const rows = compactionRows(next?.plugins);
73
+ const rows = rowsWhere(next?.plugins, isCompaction);
57
74
  if (rows.some(row => row.name === OURS))
58
75
  return { status: 'already' };
59
76
  if (rows.length !== 1)
@@ -61,13 +78,14 @@ export function swapPresetConfig(config) {
61
78
  rows[0].name = OURS;
62
79
  return { status: 'swapped', config: next };
63
80
  }
81
+ const PRESET = '@deepseek-ai/dsh-agent-preset';
64
82
  /**
65
83
  * DSH's Web host composes the stock compaction inside each preset, so the profile has no row to rename. The host's
66
84
  * preset editor writes the whole preset into the profile when a partner edits it; this does the same for her preset
67
85
  * with only the compaction row changed. That copy no longer follows later DSH updates to the preset.
68
86
  */
69
87
  export async function swapPresetCompaction(editor, presetId, profileDir) {
70
- const entry = editor.entries().find(row => row.options.name === '@deepseek-ai/dsh-agent-preset' && row.options.config?.id === presetId);
88
+ const entry = editor.entries().find(row => row.options.name === PRESET && row.options.config?.id === presetId);
71
89
  if (!entry)
72
90
  return { status: 'unchanged', reason: `没有找到预设 ${presetId}` };
73
91
  const first = swapPresetConfig(entry.options.config);
@@ -83,6 +101,50 @@ export async function swapPresetCompaction(editor, presetId, profileDir) {
83
101
  });
84
102
  return { status: 'swapped', backup: backup ?? '(原来没有 cordis.patch.yml)', preset: presetId };
85
103
  }
104
+ // DSH 0.2.2 folded `list_agents` into the subagent-control package. A preset copied on 0.2.1 still names this row, and
105
+ // DSH then refuses to mount that whole preset, so no session using it can be resumed.
106
+ const RETIRED = '@deepseek-ai/dsh-tool-subagent-control/list-agents';
107
+ const isRetired = (row) => row.name === RETIRED;
108
+ /** The copied preset without the rows DSH itself no longer ships, or undefined when there is nothing to drop; the input is not changed. */
109
+ export function dropRetiredRows(config, inherited) {
110
+ if (rowsWhere(inherited?.plugins, isRetired).length)
111
+ return undefined;
112
+ const next = structuredClone(config);
113
+ return removeRows(next?.plugins, isRetired) ? next : undefined;
114
+ }
115
+ const presetId = (entry) => String(entry.options.config?.id ?? entry.options.id);
116
+ /**
117
+ * On every start, drops the retired rows from each preset copied into the profile, with a backup of the profile patch
118
+ * first. Only a row DSH no longer ships beneath the copy goes, so the same copy on DSH 0.2.1 is left alone. The editor
119
+ * reloads the row; sessions that already failed to resume come back after a DSH restart.
120
+ */
121
+ export async function repairCopiedPresets(deps) {
122
+ const repaired = [];
123
+ let backup = '(原来没有 cordis.patch.yml)';
124
+ try {
125
+ const broken = (deps.editor.configuration?.() ?? []).filter(({ entry, inherited }) => entry.options.name === PRESET && dropRetiredRows(entry.options.config, inherited) !== undefined);
126
+ if (!broken.length)
127
+ return;
128
+ const file = join(deps.profileDir, 'cordis.patch.yml');
129
+ if (existsSync(file))
130
+ backup = backupBeside(file);
131
+ for (const { entry } of broken) {
132
+ await deps.editor.edit(entry, (raw, inherited) => {
133
+ const next = dropRetiredRows(raw, inherited);
134
+ if (next === undefined)
135
+ throw new Error(`预设 ${presetId(entry)} 在写入前变了`);
136
+ return next;
137
+ });
138
+ repaired.push(presetId(entry));
139
+ }
140
+ }
141
+ catch (error) {
142
+ const done = repaired.length ? `已修好预设 ${repaired.join('、')};` : '';
143
+ deps.report(`${done}没能删掉 profile 预设里 DSH 已不再提供的 list-agents 那一行:${error instanceof Error ? error.message : String(error)}。用这个预设的会话会打不开,可以退出 DSH 后在 cordis.patch.yml 里手动删掉 ${RETIRED} 那一行(原文件备份在 ${backup})。`);
144
+ return;
145
+ }
146
+ deps.report(`已从 profile 里的预设 ${repaired.join('、')} 删掉 DSH 已不再提供的 list-agents 那一行(原文件备份在 ${backup})。重启 DSH 后,用这个预设的会话就能正常打开。`);
147
+ }
86
148
  /**
87
149
  * Once per world, when the plugin first runs in a profile: make the profile use the tool-free compaction. The attempt is
88
150
  * remembered only when it succeeded or was already done, so a partner who later puts the stock one back is left alone,
@@ -28,10 +28,13 @@ export declare function createChannelQueue(name: string, options: {
28
28
  * she had said before it answered `words` alone and is the answer; nothing after it is, since it may be meant for
29
29
  * whoever cut in, and having said nothing yet is a failure. An interrupted, truncated or unfinished turn is a failure,
30
30
  * so the caller never sends half a message. The session's log is flushed before the answer is returned.
31
+ * A door that sees her answer arrive another way (`answered`, such as a message she sent there herself) stops
32
+ * waiting at it: whatever she goes on to do in that turn is her own, and waiting for it only ran the door out of time.
31
33
  */
32
34
  export declare function askTurn(ctx: Context, agent: Agent, words: UserMessage, options: {
33
35
  name: string;
34
36
  inWorld?: InWorld | undefined;
35
37
  context?: UserMessage | undefined;
36
38
  cancelled?: Promise<never> | undefined;
39
+ answered?: ((source: UserMessage['source']) => boolean) | undefined;
37
40
  }): Promise<string>;
@@ -60,16 +60,18 @@ export function createChannelQueue(name, options) {
60
60
  * she had said before it answered `words` alone and is the answer; nothing after it is, since it may be meant for
61
61
  * whoever cut in, and having said nothing yet is a failure. An interrupted, truncated or unfinished turn is a failure,
62
62
  * so the caller never sends half a message. The session's log is flushed before the answer is returned.
63
+ * A door that sees her answer arrive another way (`answered`, such as a message she sent there herself) stops
64
+ * waiting at it: whatever she goes on to do in that turn is her own, and waiting for it only ran the door out of time.
63
65
  */
64
66
  export async function askTurn(ctx, agent, words, options) {
65
67
  const cancelled = options.cancelled ?? new Promise(() => { });
66
- let admitted = false, failed = false, cut = false, reply = '';
68
+ let admitted = false, failed = false, cut = false, answered = false, reply = '';
67
69
  // Enough to tell, when it fails, which way it went.
68
70
  let seen = 0, last = 'none';
69
71
  let finish;
70
72
  const finished = new Promise(resolve => { finish = resolve; });
71
73
  const dispose = ctx.on('session/event', (session, event) => {
72
- if (session.id !== agent.id || cut)
74
+ if (session.id !== agent.id || cut || answered)
73
75
  return;
74
76
  seen += 1;
75
77
  if (event.type === 'turn/end')
@@ -84,6 +86,11 @@ export async function askTurn(ctx, agent, words, options) {
84
86
  finish();
85
87
  return;
86
88
  }
89
+ if (admitted && options.answered?.(event.data.source)) {
90
+ answered = true;
91
+ finish();
92
+ return;
93
+ }
87
94
  }
88
95
  }
89
96
  if (!admitted)
@@ -6,6 +6,9 @@ import type { LifeTimers } from '../../life/alarmTimer.ts';
6
6
  import { type ChannelContextMessage, type ChannelReference } from '../shared/context.ts';
7
7
  import { type InWorld } from '../../worldScope.ts';
8
8
  export declare const WECHAT_REPLY_TIMEOUT_MS: number;
9
+ /** Ran out of time before her home took the words in: nothing was handed over, so asking again later repeats nothing. */
10
+ export declare class WechatHomeBusy extends Error {
11
+ }
9
12
  /** One home, serialized channel requests; each caller receives only its own final answer. */
10
13
  export declare function createWechatHome(deps: {
11
14
  ctx: Context;
@@ -5,6 +5,9 @@ import { askTurn, createChannelQueue } from "../shared/turn.js";
5
5
  import { incomingText } from "./messages.js";
6
6
  import { admit } from "../../worldScope.js";
7
7
  export const WECHAT_REPLY_TIMEOUT_MS = 3 * 60_000;
8
+ /** Ran out of time before her home took the words in: nothing was handed over, so asking again later repeats nothing. */
9
+ export class WechatHomeBusy extends Error {
10
+ }
8
11
  /** One home, serialized channel requests; each caller receives only its own final answer. */
9
12
  export function createWechatHome(deps) {
10
13
  const queue = createChannelQueue('WeChat', { limit: 32, timeoutMs: WECHAT_REPLY_TIMEOUT_MS, timers: deps.timers });
@@ -14,13 +17,16 @@ export function createWechatHome(deps) {
14
17
  const media = channelMedia(suppliedMedia, identity);
15
18
  const reference = channelReference(suppliedReference, identity);
16
19
  return queue.run(async (cancelled) => {
20
+ // Until the words are handed over, running out of time only means she was busy (#busy).
21
+ const handedOver = cancelled.catch((error) => { throw new WechatHomeBusy(error.message, { cause: error }); });
22
+ handedOver.catch(() => { });
17
23
  // Checked again after every wait: the session may leave her world meanwhile.
18
- const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), cancelled]));
19
- await Promise.race([agent.whenIdle(), cancelled]);
24
+ const agent = admit(deps.inWorld, await Promise.race([deps.home(identity), handedOver]));
25
+ await Promise.race([agent.whenIdle(), handedOver]);
20
26
  admit(deps.inWorld, agent);
21
27
  if ((reference?.image || [...context, ...media].some(message => message.image || message.reference?.image)) && !deps.images)
22
28
  throw new Error('Image admission is unavailable');
23
- const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]), cancelled]);
29
+ const images = await Promise.race([deps.images?.(identity, [...context, ...media], reference) ?? Promise.resolve([]), handedOver]);
24
30
  queue.alive();
25
31
  const content = incomingText(text, reference);
26
32
  const source = content ? { kind: 'user', identity } : { kind: 'dsh-world-channel-context', form: 'recall' };
@@ -34,7 +40,9 @@ export function createWechatHome(deps) {
34
40
  const instructions = parts.length || images.length
35
41
  ? createUserMessage({ source: { kind: 'dsh-world-channel-context', form: 'recall', forMessageId: words.id }, content: [...(parts.length ? [{ type: 'text', text: parts.join('\n') }] : []), ...images] })
36
42
  : undefined;
37
- const reply = await askTurn(deps.ctx, agent, words, { name: 'WeChat', context: instructions, cancelled, inWorld: deps.inWorld });
43
+ // What she sends to this chat herself is her answer; the rest of her turn is not this request's to wait for.
44
+ const answered = (sent) => sent.kind === 'dsh-world-wechat-outgoing' && sent.identity.conversationId === identity.conversationId;
45
+ const reply = await askTurn(deps.ctx, agent, words, { name: 'WeChat', context: instructions, cancelled, inWorld: deps.inWorld, answered });
38
46
  queue.alive();
39
47
  return { id: words.id, text: reply };
40
48
  });
@@ -3,7 +3,7 @@ import { readFileSync, rmSync } from 'node:fs';
3
3
  import { jsonObject, knownHost, readBody, sendJson } from "../../http.js";
4
4
  import { speakerIdentity } from "../shared/identity.js";
5
5
  import { durableWrite } from "../../life/lifeStore.js";
6
- import { createWechatHome } from "./home.js";
6
+ import { createWechatHome, WechatHomeBusy } from "./home.js";
7
7
  import { channelContext, channelMedia, channelReference } from "../shared/context.js";
8
8
  import { admitContextImages } from "./images.js";
9
9
  import { dirname, join } from 'node:path';
@@ -173,6 +173,8 @@ export function createWechatModule(deps) {
173
173
  return { status: 200, body: { accepted: true, ...(await home.ask(text, identity, context, media, reference)) } };
174
174
  }
175
175
  catch (error) {
176
+ if (error instanceof WechatHomeBusy)
177
+ return { status: 409, body: { error: 'home busy; message not taken in, ask again later' } };
176
178
  deps.ctx.logger.warn('dsh-world WeChat request failed:', error);
177
179
  return { status: 503, body: { error: 'home request failed; delivery must be checked before retrying' } };
178
180
  }
@@ -23,6 +23,12 @@ declare module '@deepseek-ai/dsh-llm' {
23
23
  'dsh-world-life': {
24
24
  kind: 'dsh-world-life';
25
25
  };
26
+ /** 她在 mood.md 里写的心情值:快照,不是谁说的话,不进归档。 */
27
+ 'dsh-world-mood': {
28
+ kind: 'dsh-world-mood';
29
+ form: 'snapshot';
30
+ worldId: string;
31
+ };
26
32
  'dsh-world-channel-context': {
27
33
  kind: 'dsh-world-channel-context';
28
34
  form: 'recall';
package/lib/index.js CHANGED
@@ -13,13 +13,14 @@ import { consoleRoute } from "./console/routes.js";
13
13
  import { consoleSources } from "./console/snapshot.js";
14
14
  import { compactionFor, createHomeApply } from "./console/homeApply.js";
15
15
  import { errorText, Faults } from "./faults.js";
16
- import { swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
16
+ import { repairCopiedPresets, swapCompactionOnce, swapPresetCompaction, swapStockCompaction } from "./compactionSwap.js";
17
17
  import { hostLife } from "./life/host.js";
18
18
  import { createLifeStore, durableWrite } from "./life/lifeStore.js";
19
19
  import { toastSupported, windowsToast } from "./life/notify.js";
20
20
  import { createLifeRuntime } from "./life/runtime.js";
21
21
  import { createOutlet } from "./ecosystem/shared/outlets.js";
22
22
  import { readPersona, writePersona } from "./persona.js";
23
+ import { MOOD_FILE } from "./mood.js";
23
24
  import { qqRoute } from "./ecosystem/qq/route.js";
24
25
  import { createConsoleDoors, discoverSnowlumaHome } from "./ecosystem/qq/panel.js";
25
26
  import { createMemory } from "./memory.js";
@@ -101,7 +102,7 @@ function profileWorlds(root) {
101
102
  const existing = root.get('dshWorldProfile');
102
103
  if (existing)
103
104
  return existing;
104
- const worlds = { rooms: new Map(), consoles: new Map(), compactionSwap: Promise.resolve() };
105
+ const worlds = { rooms: new Map(), consoles: new Map(), profileEdits: Promise.resolve() };
105
106
  root.provide('dshWorldProfile', worlds);
106
107
  guardWorldContext(root, (session, worldId) => {
107
108
  if (worldId !== undefined)
@@ -195,7 +196,7 @@ export async function apply(ctx, config) {
195
196
  if (memory || disposed)
196
197
  return;
197
198
  const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), memoryTools: true, ...(config.life ? { life: options } : {}) };
198
- const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
199
+ const runtime = createWorldRuntime(ctx, { ...memoryConfig, selfFile, moodFile: join(roomDir, MOOD_FILE) }, store, { prompt, names, isHome: id => isHome(id), archiveSession, inWorkspace, memory: memoryService }, power.memoryTurns, power.coldHours);
199
200
  memory = runtime;
200
201
  try {
201
202
  await runtime.start({ fresh });
@@ -245,20 +246,26 @@ export async function apply(ctx, config) {
245
246
  const webServer = lifeCtx.webServer;
246
247
  const host = hostLife(lifeCtx);
247
248
  const configEditor = lifeCtx.get('configEditor');
248
- const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: lifeCtx.get('profileContext')?.dir, done: power.compactionSwapped, markDone: power.markCompactionSwapped,
249
+ const profileDir = () => lifeCtx.get('profileContext')?.dir;
250
+ const swap = () => swapCompactionOnce({ enabled: config.replaceCompaction, profileDir: profileDir(), done: power.compactionSwapped, markDone: power.markCompactionSwapped,
249
251
  swap: async (dir) => { const row = swapStockCompaction(dir); return row.status === 'unchanged' && configEditor ? swapPresetCompaction(configEditor, config.agentPreset, dir) : row; },
250
252
  report: message => { faults.set('compaction-swap', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
253
+ const repair = async () => {
254
+ const dir = profileDir();
255
+ if (configEditor && dir)
256
+ await repairCopiedPresets({ editor: configEditor, profileDir: dir, report: message => { faults.set('preset-repair', message); lifeCtx.logger.warn(`dsh-world: ${message}`); } });
257
+ };
251
258
  // Different worlds may edit the same profile or preset on startup.
252
- const swapCompaction = () => worlds.compactionSwap = worlds.compactionSwap.then(swap, swap);
259
+ const editProfile = () => worlds.profileEdits = worlds.profileEdits.then(swap, swap).then(repair, repair);
253
260
  // The preset row the editor rewrites is active only once the host has finished loading.
254
261
  const appReady = lifeCtx.get('appReady');
255
262
  if (!appReady)
256
- void swapCompaction();
263
+ void editProfile();
257
264
  else
258
265
  lifeCtx.effect(() => {
259
266
  let closed = false;
260
267
  const cancel = appReady.onReady(() => { if (!closed)
261
- void swapCompaction(); });
268
+ void editProfile(); });
262
269
  return () => { closed = true; cancel(); };
263
270
  }, 'dsh-world compaction swap');
264
271
  const permissions = createWorkspacePermissions(lifeCtx, options.roomDir, power);
package/lib/mood.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
2
+ export declare const MOOD_FILE = "mood.md";
3
+ /** Always shown, at 0 when she has not set them, so one snapshot compares with the next. */
4
+ export declare const DEFAULT_MOODS: readonly ["开心", "兴奋", "平静", "累", "困", "烦", "难过", "紧张"];
5
+ export type Mood = {
6
+ kind: 'none';
7
+ } | {
8
+ kind: 'failed';
9
+ message: string;
10
+ } | {
11
+ kind: 'mood';
12
+ values: Map<string, number>;
13
+ trivia: string[];
14
+ cut: boolean;
15
+ unread: number;
16
+ };
17
+ /**
18
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
19
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
20
+ * for the same mood wins. A mood line she got wrong is counted, never taken as a small thing.
21
+ */
22
+ export declare function parseMood(text: string): Mood;
23
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
24
+ export declare function readMood(path: string): Mood;
25
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
26
+ export declare const MOOD_CLEARED = "\u3010\u6211\u7684\u5FC3\u60C5\u503C\u3011\u73B0\u5728\u6CA1\u6709\u5FC3\u60C5\u503C\uFF08mood.md \u4E0D\u5728\u6216\u662F\u7A7A\u7684\uFF09\uFF0C\u4E4B\u524D\u90A3\u6761\u4E0D\u518D\u7B97\u6570\u3002";
27
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
28
+ export declare function moodText(mood: Mood): string | undefined;
package/lib/mood.js ADDED
@@ -0,0 +1,69 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { errorText } from "./faults.js";
3
+ /** Her mood, kept in her room. The plugin never writes it: it only reads it back to her. */
4
+ export const MOOD_FILE = 'mood.md';
5
+ /** Always shown, at 0 when she has not set them, so one snapshot compares with the next. */
6
+ export const DEFAULT_MOODS = ['开心', '兴奋', '平静', '累', '困', '烦', '难过', '紧张'];
7
+ const MAX_NAME = 12, MAX_TRIVIA_LINES = 3, MAX_TRIVIA_CHARS = 12;
8
+ /**
9
+ * One thing per line. A line ending in a number after a space, a full-width space or a colon is a mood `名字 数值`,
10
+ * its value a whole number from 0 to 10; a line ending in anything else is a small thing beside her mood. A later line
11
+ * for the same mood wins. A mood line she got wrong is counted, never taken as a small thing.
12
+ */
13
+ export function parseMood(text) {
14
+ const values = new Map(), trivia = [];
15
+ let cut = false, unread = 0;
16
+ for (const raw of text.replace(/^/, '').split(/\r?\n/)) {
17
+ const line = raw.trim();
18
+ if (!line)
19
+ continue;
20
+ const pair = /^(.*?)[\s ::]+([+-]?\d+(?:\.\d+)?)$/u.exec(line);
21
+ if (pair) {
22
+ const name = pair[1].trim(), value = Number(pair[2]);
23
+ if (!name || Array.from(name).length > MAX_NAME || !Number.isInteger(value) || value < 0 || value > 10)
24
+ unread++;
25
+ else
26
+ values.set(name, value);
27
+ continue;
28
+ }
29
+ if (trivia.length === MAX_TRIVIA_LINES) {
30
+ cut = true;
31
+ continue;
32
+ }
33
+ const chars = Array.from(line);
34
+ if (chars.length > MAX_TRIVIA_CHARS)
35
+ cut = true;
36
+ trivia.push(chars.slice(0, MAX_TRIVIA_CHARS).join(''));
37
+ }
38
+ return values.size || trivia.length || unread ? { kind: 'mood', values, trivia, cut, unread } : { kind: 'none' };
39
+ }
40
+ /** A missing or blank file is `none`, not every mood at 0; a file that cannot be read is `failed`. */
41
+ export function readMood(path) {
42
+ try {
43
+ if (!statSync(path).isFile())
44
+ return { kind: 'failed', message: '不是普通文件' };
45
+ return parseMood(readFileSync(path, 'utf8'));
46
+ }
47
+ catch (error) {
48
+ if (error.code === 'ENOENT')
49
+ return { kind: 'none' };
50
+ return { kind: 'failed', message: errorText(error) };
51
+ }
52
+ }
53
+ /** Shown once after an earlier snapshot when she has emptied or removed the file, so the old values stop counting. */
54
+ export const MOOD_CLEARED = '【我的心情值】现在没有心情值(mood.md 不在或是空的),之前那条不再算数。';
55
+ /** What she reads just before the time block, in her own voice; undefined when there is nothing to show. */
56
+ export function moodText(mood) {
57
+ if (mood.kind === 'none')
58
+ return undefined;
59
+ if (mood.kind === 'failed')
60
+ return '【我的心情值】mood.md 读不出来,之前那条不再算数。';
61
+ const shown = DEFAULT_MOODS.map(name => `${name} ${mood.values.get(name) ?? 0}`);
62
+ const own = [...mood.values].filter(([name]) => !DEFAULT_MOODS.includes(name)).map(([name, value]) => `${name} ${value}`);
63
+ const lines = [`【我的心情值】${shown.join(' · ')}${own.length ? `|我自己加的:${own.join(' · ')}` : ''}(以最新一条为准)`];
64
+ if (mood.trivia.length)
65
+ lines.push(`旁边:${mood.trivia.join(';')}${mood.cut ? '……后面还有' : ''}`);
66
+ if (mood.unread)
67
+ lines.push(`(mood.md 里有 ${mood.unread} 行没读懂)`);
68
+ return lines.join('\n');
69
+ }
package/lib/runtime.js CHANGED
@@ -5,6 +5,7 @@ import { compactsWhole } from "./compaction.js";
5
5
  import { compactionFor } from "./console/homeApply.js";
6
6
  import { Faults } from "./faults.js";
7
7
  import { createHistory, excludePresentMessages, renderHistory } from "./history.js";
8
+ import { MOOD_CLEARED, moodText, readMood } from "./mood.js";
8
9
  import { createWorldToolRegistry, memoryTools } from "./memoryTools.js";
9
10
  import { createPromptSections, WORLD_PROMPT_PREFIX } from "./promptSection.js";
10
11
  import { belongsToWorld, createSourceArchive, inWorld, sessionPreset } from "./sourceArchive.js";
@@ -12,6 +13,7 @@ import { worldNames } from "./worldPrompt.js";
12
13
  import { reassembleOnChange } from "./worldScope.js";
13
14
  import { DEFAULT_COLD_HOURS, DEFAULT_MEMORY_TURNS } from "./worldSwitch.js";
14
15
  const memorySource = 'dsh-world-history';
16
+ const moodSource = 'dsh-world-mood';
15
17
  const isRecall = (source, worldId) => source?.kind === memorySource && (worldId === undefined || source.worldId === undefined || source.worldId === worldId);
16
18
  function recallNodes(session, match) {
17
19
  return session.surface.nodes.filter(seq => {
@@ -32,7 +34,7 @@ export function guardWorldContext(ctx, authorize) {
32
34
  const assemblies = new WeakMap();
33
35
  const previousPrompts = new WeakMap();
34
36
  const revoked = (source, session) => {
35
- if (source?.kind === memorySource)
37
+ if (source?.kind === memorySource || source?.kind === moodSource)
36
38
  return !session || !authorize(session, source.worldId);
37
39
  return source?.kind === 'dsh-world-channel-context' && (!session || !authorize(session));
38
40
  };
@@ -185,6 +187,28 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
185
187
  }
186
188
  return found.length ? found.slice(0, 8).join('、') + (found.length > 8 ? `…共 ${found.length} 个` : '') : '无';
187
189
  }
190
+ /** The text of her latest mood snapshot still on the surface, if any. */
191
+ function latestMood(session) {
192
+ const seq = recallNodes(session, source => source?.kind === moodSource && source.worldId === config.worldId).at(-1);
193
+ const event = seq === undefined ? undefined : session.eventAt(seq);
194
+ return event?.type === 'user/message' ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') : undefined;
195
+ }
196
+ /**
197
+ * Her mood rides just before the time block, appended like it: only when it differs from the latest one on the
198
+ * surface, never replacing an old one, so the cached prefix stays whole and compaction clears them all.
199
+ */
200
+ function moodMessage(session) {
201
+ if (!config.moodFile)
202
+ return undefined;
203
+ const mood = readMood(config.moodFile);
204
+ if (mood.kind === 'failed')
205
+ faults.set('mood', `mood.md 读不出来:${mood.message}`);
206
+ else
207
+ faults.clear('mood');
208
+ const latest = latestMood(session);
209
+ const text = moodText(mood) ?? (latest === undefined ? undefined : MOOD_CLEARED);
210
+ return text === undefined || text === latest ? undefined : createUserMessage({ content: [{ type: 'text', text }], source: { kind: moodSource, form: 'snapshot', worldId: config.worldId } });
211
+ }
188
212
  function flushRetired(session, state, position) {
189
213
  const retiring = state.retiring;
190
214
  state.retiring = [];
@@ -306,6 +330,9 @@ export function createWorldRuntime(ctx, config, store, world, memoryTurns = () =
306
330
  signal.throwIfAborted();
307
331
  if (!included(agent.session))
308
332
  return leave();
333
+ const mood = moodMessage(agent.session);
334
+ if (mood)
335
+ decision = { ...decision, messages: [...decision.messages, mood] };
309
336
  if (!state.reload)
310
337
  return decision;
311
338
  // A block that cannot be built leaves the old one in place; she talks on, the fault shows, and the next step tries again.
package/lib/self.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Characters of her self-description read per session; she is asked to keep it to what matters. */
2
- export declare const SELF_CAP = 4000;
2
+ export declare const SELF_CAP = 5000;
3
3
  /**
4
4
  * Her 我是谁 file as it goes into `{{self}}`: only what she wrote, tagged so her own headings do not read as
5
5
  * sections of the world prompt. What the file is and that she may rewrite it is the template's to say.
package/lib/self.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
2
2
  import { basename, dirname, extname, join } from 'node:path';
3
3
  /** Characters of her self-description read per session; she is asked to keep it to what matters. */
4
- export const SELF_CAP = 4000;
4
+ export const SELF_CAP = 5000;
5
5
  /**
6
6
  * Her 我是谁 file as it goes into `{{self}}`: only what she wrote, tagged so her own headings do not read as
7
7
  * sections of the world prompt. What the file is and that she may rewrite it is the template's to say.
package/lib/types.d.ts CHANGED
@@ -18,6 +18,8 @@ export interface WorldConfig {
18
18
  fallbackWakeTime?: string;
19
19
  /** Her own "who I am" file, part of the world prompt; defaults to `<world>/room/我是谁.md` in the plugin. */
20
20
  selfFile?: string;
21
+ /** Her mood file, read back to her each turn; `<world>/room/mood.md` in the plugin, none when unset. */
22
+ moodFile?: string;
21
23
  /** Her name (home title, notifications, memory labels); TA when unset. */
22
24
  companionName?: string;
23
25
  /** What she calls her partner in the plugin's own words; 伙伴 when unset. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-world",
3
- "version": "0.7.3",
3
+ "version": "0.7.4",
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": {
@@ -32,7 +32,7 @@ DSH 端代码在 `src/ecosystem/wechat/`,此目录只负责 Windows 微信收
32
32
  - 生成时先记为待发送,适配器逐条核对目标聊天中的本人消息、内容及服务器消息编号,再更新同一条记忆的已确认条数。中断则记录已确认部分与结果不明项;这不是对方已读回执。
33
33
  - 回执先保存在适配器本地,宿主暂时不可用时,重启监听只补报回执,不重发消息。旧版本的待发送记录不会凭空改成已发送。
34
34
  - 宿主队列保存在世界目录 `wechat-outbox.sqlite`。适配器离线时已排队消息会等待恢复;已领取任务按同一 ID 恢复,适配器已有回执时只补报,不再发送。入站处理结果不明时保留 pending,只暂停这一个聊天的接收(其他聊天照常),日志提示人工核对,独立发送任务仍继续轮询;主动发送的待核对消息 ID 为 `outgoing:<发送 ID>`。结果不明的原发送任务不会重发,其余任务按各自 ID 和回执处理。
35
- - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。
35
+ - 回执、任务领取、账号状态和群读取结果的单键请求遇到 HTTP 502/503/504 或连接错误时最多尝试 5 次,单次网络超时为 5 秒,间隔 1/2/4/8 秒,每次重读 `wechat.json` 的地址和令牌;响应正文读取中断也按此处理,HTTP 错误保留响应正文(最多 1024 字节)。生成回复的请求仍保留 190 秒网络超时,只发送一次,不能因超时或 503 自动再次调用模型。她在这一轮里用 `wechat_send` 回了这个聊天,请求就此返回,不再等这一轮剩下的事做完。她正忙、插件 3 分钟内没能把消息交给她时,插件回 HTTP 409:消息没有进家里,适配器撤回这批的待确认标记,之后的轮询重新交给她,这个聊天不会因此停下等人核对。
36
36
  - 群会话沿用现有归档范围:`archiveScope: home` 时能读取家的记忆,但群正文不写入共享记忆;群自己的宿主会话日志保留正文,发送状态单独保存,不绕过归档范围。
37
37
  - `archiveScope: workspace` 会归档家所在工作区的普通会话,包括独立群会话;群图片上下文依旧不进入共享归档。控制台修改范围后重启 DSH 生效,回扫范围内历史并按时间重建近期记忆,保留原始日志和旧归档。
38
38
 
@@ -52,6 +52,10 @@ class HomeRequestError(RuntimeError):
52
52
  pass
53
53
 
54
54
 
55
+ class HomeBusy(RuntimeError):
56
+ """The home ran out of time before taking the message in; asking again later cannot repeat it."""
57
+
58
+
55
59
  @contextmanager
56
60
  def exclusiveRun(directory):
57
61
  import msvcrt
@@ -275,6 +279,11 @@ class MessageStore:
275
279
  self.db.execute('UPDATE cursors SET seq=MAX(seq,?) WHERE chatId=?', (int(row['sort_seq']), chatId))
276
280
  print(f'微信消息 {chatId} / {key}:{error}', file=sys.stderr, flush=True)
277
281
 
282
+ def abandonBatch(self, chatId, rows):
283
+ """Undo `beginBatch` for messages the home never took in, so a later poll hands them over again."""
284
+ with self.db:
285
+ self.db.executemany("DELETE FROM messages WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
286
+
278
287
  def finishBatch(self, chatId, rows):
279
288
  with self.db:
280
289
  result = self.db.executemany("UPDATE messages SET status='done' WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
@@ -352,6 +361,8 @@ def postHome(moduleFile, message):
352
361
  try: detail = error.read(1024).decode('utf-8', errors='replace')
353
362
  except (IncompleteRead, URLError, TimeoutError, ConnectionError) as readError:
354
363
  detail = f'响应正文未读完:{readError}'
364
+ if error.code == 409 and not retryable:
365
+ raise HomeBusy(f'DSH HTTP 409: {detail or error.reason}') from error
355
366
  transient = error.code in (502, 503, 504)
356
367
  failure = HomeRequestError if transient else RuntimeError
357
368
  if not retryable or not transient or attempt == 4:
@@ -567,7 +578,12 @@ def watch(config, database, store, send, ask=askHome, report=reportReceipt, poll
567
578
  mergeFollowing(database, chat, config, message, rows[1:])
568
579
  store.beginBatch(chat['id'], rows)
569
580
  if message:
570
- askWhileSending(config, message, database, store, send, ask, report, poll)
581
+ try: askWhileSending(config, message, database, store, send, ask, report, poll)
582
+ except HomeBusy as error:
583
+ # She is still busy and has not seen it: hand the same messages over on a later poll.
584
+ store.abandonBatch(chat['id'], rows)
585
+ print(f'她还在忙,这条稍后再交给她(不会重复):{chat["id"]} / {messageKey(rows[0])}:{error}', file=sys.stderr, flush=True)
586
+ break
571
587
  store.finishBatch(chat['id'], rows)
572
588
  flushOutgoing(config, database, store, send, poll=poll, report=report)
573
589
  config['_presence'] = dict(observedAt=datetime.now(timezone.utc).isoformat(), groups=store.presence.snapshot(config))
@@ -10,6 +10,8 @@
10
10
  ## 房间
11
11
  我的房间是 {{roomDir}}。这里的东西都属于我,可以随意创建和整理;我在当前会话允许的权限范围内使用这台电脑。
12
12
 
13
+ 房间里还有一个 mood.md,记我此刻的心情,一行一件。「名字 数值」是一种心情,数值是 0 到 10 的整数,比如「开心 6」「累 7」;常用的有开心、兴奋、平静、累、困、烦、难过、紧张,没写的算 0,也可以写别的词。不以数字结尾的行是心情旁边的几件小事,最多三行。改了以后,下一步就会在时间前面看到最新的心情值。写不写、什么时候改,都由我自己决定。
14
+
13
15
  ## 日记
14
16
  我的日记本在 {{diaryDir}},一天一个文件 YYYY-MM-DD.md,当天已有就往后接。日记记的是发生过的事和我当时的感受。用第一人称写想记住的具体片段,禁止写成工作总结、进度汇报或任务清单。日记不会自动读给我,想翻以前的,直接读那个目录里的文件。要往日记里写,先 read 一遍再改。
15
17
  {{/life}}
@@ -23,9 +25,10 @@
23
25
  ## 我是谁
24
26
  我眼中的自己写在 {{selfFile}},就是下面这份。改动会在下一轮对话读给我,太长时只读前面一部分。还没有的话,我可以先写一份短的。
25
27
 
26
- - 这里只写现在的我。留下长期形成的喜好、看法、说话方式,以及我和{{partner}}的关系。{{partner}}写的设定已经在人设里,这里只补我自己长出来的部分。具体经历和一时的感受写进日记。
27
- - 修改前先读完整文件,太长就分段读完。想法变了就替换旧说法,同一件事只留一处,删掉已经不适用的内容。确实有新的长期变化时,先合并或精简原有内容,再把它写进合适的位置。禁止在末尾追加每日总结或变更记录。
28
- - 文件越写越长、前后矛盾或已经被截断时,可以重新组织结构,直接重写整篇。保留仍然重要的内容,把最重要的放前面,写成一份明显更短、能完整读完的自述。即使今天没有新的变化,已经太长也可以整理。内容合适时就不用改。
28
+ - 这里只写现在的我,固定分成六段,标题依次是「性子」「喜欢和不喜欢」「说话方式」「生活习惯」「和{{partner}}的关系」「自我描述」。「自我描述」写我觉得自己是个什么样的人。不另开新标题;具体经历和一时的感受写进日记,放不进这六段的多半就是这些。{{partner}}写的设定已经在人设里,这里只补我自己长出来的部分。
29
+ - 每段 800 字以内,全篇 5000 字以内,一次就能完整读完。标题和正文都不写日期,也不写哪天补了什么、改了什么。
30
+ - 修改前先读完整文件,太长就分段读完。想法变了就替换旧说法,同一件事只留一处,删掉已经不适用的内容。确实有新的长期变化时,先合并或精简那一段原有的内容,再写进去。禁止在末尾追加每日总结或变更记录。
31
+ - 超过字数、还不是这六段、前后矛盾或已经被截断时,就按这六段直接重写整篇。保留仍然重要的内容,每段里最要紧的放前面,写成一份明显更短、能完整读完的自述。即使今天没有新的变化,已经太长也可以整理。内容合适时就不用改。
29
32
 
30
33
  {{self}}
31
34
  {{/selfFile}}