dsh-agent-soul 0.9.12 → 0.9.13

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.
@@ -1,232 +1,235 @@
1
- /**
2
- * 宿主装配 · inject.js
3
- * 由 lib/host/runtime.js 按职责拆出(2026-11-06 模块化重构),函数体保持原样。
4
- */
5
- import { trimMap } from '../../core/lru.js'
6
- import { ECHO_LINE_MAX_CHARS, ECHO_SECTION_MAX_CHARS, RECALL_SEEN_MAX } from '../meta.js'
7
- import { cardsFor, loadConfig, moodState } from '../../store.js'
8
- import { digestDiaries, readRecentChat, readRecentDiaries, todayKey } from '../../diary.js'
9
- import { hasHumanInputThisTurn } from './turns.js'
10
- import { isSubagentSession } from '../../extract.js'
11
- import { note } from '../../env.js'
12
- import { randomUUID } from 'node:crypto'
13
- import { recallSeenBySession } from './state.js'
14
- import { renderRecallOnly } from '../../memory.js'
15
- import { takeTone, toneLevelOf } from '../../tone.js'
16
- import { wrapUntrusted } from '../../core/prompt-guard.js'
17
-
18
-
19
-
20
- /**
21
- * 把缓冲里的条目渲染成一个小节;没有条目时返回空串。
22
- *
23
- * @param {Array<{ text: string }>} items takeEcho 的返回值
24
- * @returns {string}
25
- */
26
- export function renderEchoSection(items) {
27
- if (!Array.isArray(items) || items.length === 0) return ''
28
- const lines = []
29
- for (const item of items) {
30
- // 换行折成空格:一条记忆里就算带了换行,回执也必须是一行,否则列表结构会断。
31
- const text = String(item?.text ?? '').replace(/\s+/g, ' ').trim()
32
- if (text === '') continue
33
- const shown = text.length > ECHO_LINE_MAX_CHARS ? `${text.slice(0, ECHO_LINE_MAX_CHARS)}…` : text
34
- lines.push(`- ${shown}`)
35
- }
36
- if (lines.length === 0) return ''
37
- // 回执是刚写下的用户原话,同样按不可信数据包裹(S2 / P1-4)。
38
- //
39
- // 2026-11-07 R10 / P2-18:原来是**先包边界、再 slice 截断** ——
40
- // 超预算时会切在闭合标签中间,那一段边界就不完整了(模型会以为数据还没结束)。
41
- // 这违反了 segment-memory 里写明的「先裁正文、再包标签」不变量。
42
- // 现在先算包裹的固定开销(标签 + 换行,nonce 长度固定),把正文裁进预算再包。
43
- const label = '刚记下的记忆'
44
- const headerChars = '## 刚记下的\n'.length
45
- const budgetForBody = Math.max(0, ECHO_SECTION_MAX_CHARS - wrapUntrusted(label, '').length - headerChars)
46
- let body = lines.join('\n')
47
- if (body.length > budgetForBody) {
48
- body = budgetForBody > 1 ? `${body.slice(0, budgetForBody - 1)}…` : ''
49
- }
50
- if (body === '') return ''
51
- return `## 刚记下的\n${wrapUntrusted(label, body)}`
52
- }
53
-
54
-
55
-
56
- /**
57
- * 新会话第一轮额外注入的「最近」(2026-10-31)。
58
- *
59
- * 补的是这条断层:树树不会在一个对话里做完所有事 —— 修插件、QQ 聊天、
60
- * 闲聊是分开的会话。记忆卡给的是零碎事实(「树树大二」「不喜欢机械」),
61
- * 日记又只写到「昨天」。所以新开一个对话时,她不知道今天早些时候
62
- * 在别的对话里做过什么,也不知道昨天具体是怎么过的。
63
- *
64
- * 这里并两块:
65
- * ① 前几天的日记(叙事,接得上「昨天我们干了什么」)
66
- * ② 今天到目前为止的流水(conversations/<今天>.jsonl 是所有会话汇总的)
67
- *
68
- * 只在第一轮注入,不每轮重复。私密日记默认不进(见配置项)。
69
- *
70
- * @returns {string} 空串 = 没有可注入的内容
71
- */
72
- export function renderRecentSection(cfg) {
73
- try {
74
- const days = Number(cfg.memoryRecentDiaryDays)
75
- const chatChars = Number(cfg.memoryRecentChatChars)
76
- const today = todayKey(Date.now())
77
- const parts = []
78
-
79
- if (Number.isFinite(days) && days > 0) {
80
- const recent = readRecentDiaries(today, Math.min(Math.trunc(days), 7))
81
- const raw = cfg.memoryRecentDiaryIncludePrivate === true ? recent.all : recent.public
82
- const body = typeof raw === 'string' ? raw.trim() : ''
83
- if (body !== '') {
84
- // 2026-11-05:整篇 → 每篇一行摘要。两篇日记约 3000 字,占开场最大的一块,
85
- // 而它的用处只是「接得上昨天」。摘要里带日期和全文字数,要细看再按日期读文件。
86
- const digest = digestDiaries(body, 300)
87
- if (digest !== '') parts.push(`### 前几天的日记(每篇一段摘要,全文在 agents/diary/public/<日期>.md)\n\n${digest}`)
88
- }
89
- }
90
-
91
- if (Number.isFinite(chatChars) && chatChars > 0) {
92
- // 2026-11-04:流水里主人怎么标也跟着配置走(空 = 中性的「对方」)
93
- const chat = readRecentChat(today, Math.min(Math.trunc(chatChars), 12000), cfg.ownerName)
94
- if (typeof chat === 'string' && chat.trim() !== '') {
95
- parts.push(`### 今天到目前为止(可能来自别的对话)\n\n${chat.trim()}`)
96
- }
97
- }
98
-
99
- if (parts.length === 0) return ''
100
- return `\n\n## 最近\n\n${parts.join('\n\n')}`
101
- } catch (error) {
102
- note('memory', `注入「最近」失败:${error instanceof Error ? error.message : error}`)
103
- return ''
104
- }
105
- }
106
-
107
-
108
-
109
- /** 第一轮之后的「想起来了」:按当前这句话召回,并排除本会话已经说过的。 */
110
- export function recallForTurn(cwd, cfg, query, sessionId, maxChars) {
111
- let seen = recallSeenBySession.get(sessionId)
112
- if (seen === undefined) {
113
- trimMap(recallSeenBySession, 200)
114
- seen = new Set()
115
- recallSeenBySession.set(sessionId, seen)
116
- }
117
- // cardsFor 返回的是 { scope, card } 包一层的外壳,renderRecallOnly 要的是裸卡数组。
118
- // 2026-10-30 修:以前直接把外壳传进去,被它的 Array.isArray(card.records) 过滤掉,
119
- // 这条「第一轮之后唯一的记忆通路」一直是空跑 —— 日志不报错,只是永远想不起来。
120
- // 2026-11-04 修 B4:这里原来没传 cfg,cardsFor 用默认值 →
121
- // 关掉 projectMemoryEnabled 之后整卡路径没了项目卡,但这条「想起来了」的路
122
- // 每轮仍在从项目卡召回注入。同一个开关必须在两条路上都生效。
123
- // 2026-11-04 回声:maxChars 只在有回声、预算被回执占掉时才传 ——
124
- // 不传时行为跟以前逐字节一致(renderRecallOnly 自己用默认 260)。
125
- const recallOptions = { config: cfg, query, exclude: seen }
126
- if (Number.isFinite(maxChars) && maxChars > 0) recallOptions.maxChars = maxChars
127
- const cards = cardsFor(cwd, cfg).map((entry) => entry.card)
128
- let recalled = renderRecallOnly(cards, recallOptions)
129
-
130
- // 空着,而且是被"说过了"挡空的 → 这套记忆在这个会话里已经讲完了,放开重来一次。
131
- // 只有 blocked > 0 才算(真的没有相关记忆时不该白跑一遍)。
132
- if (recalled.text === '' && (recalled.blocked ?? 0) > 0) {
133
- const blockedBefore = recalled.blocked
134
- // ⚠️ 不能 seen.clear():清完 exclude 为空,而 renderRecallOnly 是纯函数、
135
- // 排序确定,重试结果就是这份 query 的历史最高分那几条 —— 多半跟上一轮
136
- // 刚说过的整段重合,正中"同一件事别连着刷屏"的反面。
137
- // 只留最近一半(最近说过的那几条),把更早的旧账放出来。
138
- const keep = [...seen].slice(-Math.floor(RECALL_SEEN_MAX / 2))
139
- seen.clear()
140
- for (const key of keep) seen.add(key)
141
- recalled = renderRecallOnly(cards, recallOptions)
142
- // 重置即记录:不管重试有没有结果都要留痕,否则去重表被悄悄削掉没人知道
143
- note('memory', `「想起来了」被去重挡空(挡掉 ${blockedBefore} 条),已把去重表收到 ${keep.length} 条重试`)
144
- }
145
- if (recalled.text === '') return ''
146
-
147
- for (const key of recalled.keys) seen.add(key)
148
- // 只留最近 N 条(Set 保插入顺序,最老的先出)
149
- while (seen.size > RECALL_SEEN_MAX) {
150
- const oldest = seen.values().next().value
151
- if (oldest === undefined) break
152
- seen.delete(oldest)
153
- }
154
- return recalled.text
155
- }
156
-
157
-
158
-
159
- /**
160
- * 每轮算一次心情档位(计数器语义见 tone.js),该发的时候在当前消息后追加一条。
161
- *
162
- * 只在 `soul:memory` 的 text() 里调用,那是每轮必经之路。
163
- */
164
- export function registerToneForTurn(agent, llm) {
165
- const cfg = loadConfig()
166
- if (cfg.enabled === false || cfg.moodEnabled === false) return
167
- if (agent === null || agent === undefined) return
168
- if (isSubagentSession(agent)) return
169
-
170
- const session = agent.session
171
- const id = String(session?.header?.id ?? '')
172
- if (id === '') return
173
-
174
- // 心情状态按 cwd 读(跟主注入同源),档位是纯查表,很便宜
175
- const cwd = session?.header?.cwd ?? ''
176
- let state = null
177
- try {
178
- state = moodState(cwd)
179
- } catch (error) {
180
- // 2026-11-04:原来是裸 `catch { return }`。正因为什么都不留,
181
- // 「moodState 没导入」这个错误整整藏了一个多月 —— 每轮都抛 ReferenceError,
182
- // 每轮都被这里吞掉,三个语气配置项全是摆设而日志一片干净。
183
- // 静默兜底和静默失效只差一行日志,这行必须有。
184
- note('mood', `读心情失败,这轮不注入语气:${error instanceof Error ? error.message : error}`)
185
- return
186
- }
187
- const level = toneLevelOf(state, cfg)
188
- if (level === 'low' || level === 'high') {
189
- // 只有真要挂的时候才检查 —— 中档本来就不投,不必扫事件。
190
- // 空轮不投,而且**不计入节流计数**(takeTone 根本不会被调用),
191
- // 否则「定时任务撞了几次空轮」会把本该隔 3 轮的语气提前触发。
192
- if (hasHumanInputThisTurn(agent) === false) return
193
- }
194
- const { emit, text } = takeTone(id, level, cfg)
195
- if (emit === false || text === '') return
196
-
197
- // 投一条 user 消息(不是 assistant)—— 它是「当时的心情」,属于对话的一部分。
198
- //
199
- // ── 字段名是 role,不是 type(2026-11-04 三次修,这次是线上事故)──
200
- // 宿主序列化发给模型的 messages 时要求 `role` 字段。我前两版写的是
201
- // `type: 'user'` —— 那是**事件**(session.append)的字段名,消息体用的是 role。
202
- // 后果不是静默失败,而是整轮对话直接 500:
203
- // Failed to deserialize the JSON body: messages[202]: missing field `role`
204
- // 而且这条坏消息已经进了会话历史,之后每一轮都会带着它一起失败。
205
- //
206
- // 教训:拼消息体不要靠猜。优先走 llm.createUserMessage(宿主自己补全字段),
207
- // 兜底手拼时字段名照抄 dsh-onebot-channel/deliver.js:80 ——
208
- // 那是唯一一处已经被线上验证过的写法。
209
- try {
210
- const inbox = agent.inbox
211
- if (inbox === null || inbox === undefined || typeof inbox.append !== 'function') return
212
- const blocks = [{ type: 'text', text }]
213
- let message
214
- if (llm !== null && llm !== undefined && typeof llm.createUserMessage === 'function') {
215
- message = llm.createUserMessage({ content: blocks, source: { kind: 'soul-tone' } })
216
- if (message !== null && typeof message === 'object' && typeof message.id !== 'string') {
217
- message = { ...message, id: randomUUID() }
218
- }
219
- } else {
220
- message = {
221
- id: randomUUID(),
222
- role: 'user',
223
- content: blocks,
224
- source: { kind: 'soul-tone', plugin: 'dsh-agent-soul' }
225
- }
226
- }
227
- inbox.append('next-step', message)
228
- note('mood', `语气注入:${level}`)
229
- } catch (error) {
230
- note('mood', `语气注入失败:${error instanceof Error ? error.message : error}`)
231
- }
232
- }
1
+ /**
2
+ * 宿主装配 · inject.js
3
+ * 由 lib/host/runtime.js 按职责拆出(2026-11-06 模块化重构),函数体保持原样。
4
+ */
5
+ import { trimMap } from '../../core/lru.js'
6
+ import { ECHO_LINE_MAX_CHARS, ECHO_SECTION_MAX_CHARS, RECALL_SEEN_MAX } from '../meta.js'
7
+ import { cardsFor, loadConfig, moodState } from '../../store.js'
8
+ import { digestDiaries, readRecentChat, readRecentDiaries, todayKey } from '../../diary.js'
9
+ import { hasHumanInputThisTurn } from './turns.js'
10
+ import { isSubagentSession } from '../../extract.js'
11
+ import { note } from '../../env.js'
12
+ import { randomUUID } from 'node:crypto'
13
+ import { recallSeenBySession } from './state.js'
14
+ import { renderRecallOnly } from '../../memory.js'
15
+ import { takeTone, toneLevelOf } from '../../tone.js'
16
+ import { wrapUntrusted } from '../../core/prompt-guard.js'
17
+ import { mark } from '../../evidence.js'
18
+
19
+
20
+
21
+ /**
22
+ * 把缓冲里的条目渲染成一个小节;没有条目时返回空串。
23
+ *
24
+ * @param {Array<{ text: string }>} items takeEcho 的返回值
25
+ * @returns {string}
26
+ */
27
+ export function renderEchoSection(items) {
28
+ if (!Array.isArray(items) || items.length === 0) return ''
29
+ const lines = []
30
+ for (const item of items) {
31
+ // 换行折成空格:一条记忆里就算带了换行,回执也必须是一行,否则列表结构会断。
32
+ const text = String(item?.text ?? '').replace(/\s+/g, ' ').trim()
33
+ if (text === '') continue
34
+ const shown = text.length > ECHO_LINE_MAX_CHARS ? `${text.slice(0, ECHO_LINE_MAX_CHARS)}…` : text
35
+ lines.push(`- ${shown}`)
36
+ }
37
+ if (lines.length === 0) return ''
38
+ // 回执是刚写下的用户原话,同样按不可信数据包裹(S2 / P1-4)。
39
+ //
40
+ // 2026-11-07 R10 / P2-18:原来是**先包边界、再 slice 截断** ——
41
+ // 超预算时会切在闭合标签中间,那一段边界就不完整了(模型会以为数据还没结束)。
42
+ // 这违反了 segment-memory 里写明的「先裁正文、再包标签」不变量。
43
+ // 现在先算包裹的固定开销(标签 + 换行,nonce 长度固定),把正文裁进预算再包。
44
+ const label = '刚记下的记忆'
45
+ const headerChars = '## 刚记下的\n'.length
46
+ const budgetForBody = Math.max(0, ECHO_SECTION_MAX_CHARS - wrapUntrusted(label, '').length - headerChars)
47
+ let body = lines.join('\n')
48
+ if (body.length > budgetForBody) {
49
+ body = budgetForBody > 1 ? `${body.slice(0, budgetForBody - 1)}…` : ''
50
+ }
51
+ if (body === '') return ''
52
+ return `## 刚记下的\n${wrapUntrusted(label, body)}`
53
+ }
54
+
55
+
56
+
57
+ /**
58
+ * 新会话第一轮额外注入的「最近」(2026-10-31)。
59
+ *
60
+ * 补的是这条断层:树树不会在一个对话里做完所有事 —— 修插件、QQ 聊天、
61
+ * 闲聊是分开的会话。记忆卡给的是零碎事实(「树树大二」「不喜欢机械」),
62
+ * 日记又只写到「昨天」。所以新开一个对话时,她不知道今天早些时候
63
+ * 在别的对话里做过什么,也不知道昨天具体是怎么过的。
64
+ *
65
+ * 这里并两块:
66
+ * ① 前几天的日记(叙事,接得上「昨天我们干了什么」)
67
+ * ② 今天到目前为止的流水(conversations/<今天>.jsonl 是所有会话汇总的)
68
+ *
69
+ * 只在第一轮注入,不每轮重复。私密日记默认不进(见配置项)。
70
+ *
71
+ * @returns {string} 空串 = 没有可注入的内容
72
+ */
73
+ export function renderRecentSection(cfg) {
74
+ try {
75
+ const days = Number(cfg.memoryRecentDiaryDays)
76
+ const chatChars = Number(cfg.memoryRecentChatChars)
77
+ const today = todayKey(Date.now())
78
+ const parts = []
79
+
80
+ if (Number.isFinite(days) && days > 0) {
81
+ const recent = readRecentDiaries(today, Math.min(Math.trunc(days), 7))
82
+ const raw = cfg.memoryRecentDiaryIncludePrivate === true ? recent.all : recent.public
83
+ const body = typeof raw === 'string' ? raw.trim() : ''
84
+ if (body !== '') {
85
+ // 2026-11-05:整篇 → 每篇一行摘要。两篇日记约 3000 字,占开场最大的一块,
86
+ // 而它的用处只是「接得上昨天」。摘要里带日期和全文字数,要细看再按日期读文件。
87
+ const digest = digestDiaries(body, 300)
88
+ if (digest !== '') parts.push(`### 前几天的日记(每篇一段摘要,全文在 agents/diary/public/<日期>.md)\n\n${digest}`)
89
+ }
90
+ }
91
+
92
+ if (Number.isFinite(chatChars) && chatChars > 0) {
93
+ // 2026-11-04:流水里主人怎么标也跟着配置走(空 = 中性的「对方」)
94
+ const chat = readRecentChat(today, Math.min(Math.trunc(chatChars), 12000), cfg.ownerName)
95
+ if (typeof chat === 'string' && chat.trim() !== '') {
96
+ parts.push(`### 今天到目前为止(可能来自别的对话)\n\n${chat.trim()}`)
97
+ }
98
+ }
99
+
100
+ if (parts.length === 0) return ''
101
+ return `\n\n## 最近\n\n${parts.join('\n\n')}`
102
+ } catch (error) {
103
+ note('memory', `注入「最近」失败:${error instanceof Error ? error.message : error}`)
104
+ return ''
105
+ }
106
+ }
107
+
108
+
109
+
110
+ /** 第一轮之后的「想起来了」:按当前这句话召回,并排除本会话已经说过的。 */
111
+ export function recallForTurn(cwd, cfg, query, sessionId, maxChars) {
112
+ let seen = recallSeenBySession.get(sessionId)
113
+ if (seen === undefined) {
114
+ trimMap(recallSeenBySession, 200)
115
+ seen = new Set()
116
+ recallSeenBySession.set(sessionId, seen)
117
+ }
118
+ // cardsFor 返回的是 { scope, card } 包一层的外壳,renderRecallOnly 要的是裸卡数组。
119
+ // 2026-10-30 修:以前直接把外壳传进去,被它的 Array.isArray(card.records) 过滤掉,
120
+ // 这条「第一轮之后唯一的记忆通路」一直是空跑 —— 日志不报错,只是永远想不起来。
121
+ // 2026-11-04 修 B4:这里原来没传 cfg,cardsFor 用默认值 →
122
+ // 关掉 projectMemoryEnabled 之后整卡路径没了项目卡,但这条「想起来了」的路
123
+ // 每轮仍在从项目卡召回注入。同一个开关必须在两条路上都生效。
124
+ // 2026-11-04 回声:maxChars 只在有回声、预算被回执占掉时才传 ——
125
+ // 不传时行为跟以前逐字节一致(renderRecallOnly 自己用默认 260)。
126
+ const recallOptions = { config: cfg, query, exclude: seen }
127
+ if (Number.isFinite(maxChars) && maxChars > 0) recallOptions.maxChars = maxChars
128
+ const cards = cardsFor(cwd, cfg).map((entry) => entry.card)
129
+ let recalled = renderRecallOnly(cards, recallOptions)
130
+
131
+ // 空着,而且是被"说过了"挡空的 → 这套记忆在这个会话里已经讲完了,放开重来一次。
132
+ // 只有 blocked > 0 才算(真的没有相关记忆时不该白跑一遍)。
133
+ if (recalled.text === '' && (recalled.blocked ?? 0) > 0) {
134
+ const blockedBefore = recalled.blocked
135
+ // ⚠️ 不能 seen.clear():清完 exclude 为空,而 renderRecallOnly 是纯函数、
136
+ // 排序确定,重试结果就是这份 query 的历史最高分那几条 —— 多半跟上一轮
137
+ // 刚说过的整段重合,正中"同一件事别连着刷屏"的反面。
138
+ // 只留最近一半(最近说过的那几条),把更早的旧账放出来。
139
+ const keep = [...seen].slice(-Math.floor(RECALL_SEEN_MAX / 2))
140
+ seen.clear()
141
+ for (const key of keep) seen.add(key)
142
+ recalled = renderRecallOnly(cards, recallOptions)
143
+ // 重置即记录:不管重试有没有结果都要留痕,否则去重表被悄悄削掉没人知道
144
+ note('memory', `「想起来了」被去重挡空(挡掉 ${blockedBefore} 条),已把去重表收到 ${keep.length} 条重试`)
145
+ }
146
+ if (recalled.text === '') return ''
147
+
148
+ for (const key of recalled.keys) seen.add(key)
149
+ // 只留最近 N 条(Set 保插入顺序,最老的先出)
150
+ while (seen.size > RECALL_SEEN_MAX) {
151
+ const oldest = seen.values().next().value
152
+ if (oldest === undefined) break
153
+ seen.delete(oldest)
154
+ }
155
+ return recalled.text
156
+ }
157
+
158
+
159
+
160
+ /**
161
+ * 每轮算一次心情档位(计数器语义见 tone.js),该发的时候在当前消息后追加一条。
162
+ *
163
+ * 只在 `soul:memory` 的 text() 里调用,那是每轮必经之路。
164
+ */
165
+ export function registerToneForTurn(agent, llm) {
166
+ const cfg = loadConfig()
167
+ if (cfg.enabled === false || cfg.moodEnabled === false) return
168
+ if (agent === null || agent === undefined) return
169
+ if (isSubagentSession(agent)) return
170
+
171
+ const session = agent.session
172
+ const id = String(session?.header?.id ?? '')
173
+ if (id === '') return
174
+
175
+ // 心情状态按 cwd 读(跟主注入同源),档位是纯查表,很便宜
176
+ const cwd = session?.header?.cwd ?? ''
177
+ let state = null
178
+ try {
179
+ state = moodState(cwd)
180
+ } catch (error) {
181
+ // 2026-11-04:原来是裸 `catch { return }`。正因为什么都不留,
182
+ // 「moodState 没导入」这个错误整整藏了一个多月 —— 每轮都抛 ReferenceError,
183
+ // 每轮都被这里吞掉,三个语气配置项全是摆设而日志一片干净。
184
+ // 静默兜底和静默失效只差一行日志,这行必须有。
185
+ note('mood', `读心情失败,这轮不注入语气:${error instanceof Error ? error.message : error}`)
186
+ return
187
+ }
188
+ const level = toneLevelOf(state, cfg)
189
+ if (level === 'low' || level === 'high') {
190
+ // 只有真要挂的时候才检查 —— 中档本来就不投,不必扫事件。
191
+ // 空轮不投,而且**不计入节流计数**(takeTone 根本不会被调用),
192
+ // 否则「定时任务撞了几次空轮」会把本该隔 3 轮的语气提前触发。
193
+ if (hasHumanInputThisTurn(agent) === false) return
194
+ }
195
+ const { emit, text } = takeTone(id, level, cfg)
196
+ if (emit === false || text === '') return
197
+
198
+ // 投一条 user 消息(不是 assistant)—— 它是「当时的心情」,属于对话的一部分。
199
+ //
200
+ // ── 字段名是 role,不是 type(2026-11-04 三次修,这次是线上事故)──
201
+ // 宿主序列化发给模型的 messages 时要求 `role` 字段。我前两版写的是
202
+ // `type: 'user'` —— 那是**事件**(session.append)的字段名,消息体用的是 role。
203
+ // 后果不是静默失败,而是整轮对话直接 500:
204
+ // Failed to deserialize the JSON body: messages[202]: missing field `role`
205
+ // 而且这条坏消息已经进了会话历史,之后每一轮都会带着它一起失败。
206
+ //
207
+ // 教训:拼消息体不要靠猜。优先走 llm.createUserMessage(宿主自己补全字段),
208
+ // 兜底手拼时字段名照抄 dsh-onebot-channel/deliver.js:80 ——
209
+ // 那是唯一一处已经被线上验证过的写法。
210
+ try {
211
+ const inbox = agent.inbox
212
+ if (inbox === null || inbox === undefined || typeof inbox.append !== 'function') return
213
+ const blocks = [{ type: 'text', text }]
214
+ let message
215
+ if (llm !== null && llm !== undefined && typeof llm.createUserMessage === 'function') {
216
+ message = llm.createUserMessage({ content: blocks, source: { kind: 'soul-tone' } })
217
+ if (message !== null && typeof message === 'object' && typeof message.id !== 'string') {
218
+ message = { ...message, id: randomUUID() }
219
+ }
220
+ } else {
221
+ message = {
222
+ id: randomUUID(),
223
+ role: 'user',
224
+ content: blocks,
225
+ source: { kind: 'soul-tone', plugin: 'dsh-agent-soul' }
226
+ }
227
+ }
228
+ inbox.append('next-step', message)
229
+ // 2026-11-10 R18-C:动态证据 —— 语气**真的进了她的收件箱**(不是「开关开着」)
230
+ mark('moodTone', `挂了「${text.slice(0, 12)}」`)
231
+ note('mood', `语气注入:${level}`)
232
+ } catch (error) {
233
+ note('mood', `语气注入失败:${error instanceof Error ? error.message : error}`)
234
+ }
235
+ }