dsh-agent-soul 0.2.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +236 -125
- package/docs/preview.html +8 -8
- package/lib/api.js +304 -30
- package/lib/client/api.js +39 -0
- package/lib/client/app.js +3 -1
- package/lib/client/diary-tab.js +347 -0
- package/lib/client/memory-tab.js +26 -4
- package/lib/client/mood-tab.js +12 -10
- package/lib/client/overview-tab.js +33 -0
- package/lib/client/persona-tab.js +1 -0
- package/lib/client/settings-tab.js +1 -1
- package/lib/client.js +464 -16
- package/lib/diary.js +1265 -0
- package/lib/env.js +57 -9
- package/lib/extract.js +323 -9
- package/lib/index.js +498 -67
- package/lib/memory.js +1377 -807
- package/lib/mood.js +270 -23
- package/lib/paths.js +196 -168
- package/lib/purpose.js +195 -1
- package/lib/refine.js +221 -0
- package/lib/registry.js +236 -236
- package/lib/store.js +697 -383
- package/lib/tool.js +27 -8
- package/package.json +84 -71
- package/tools/build-client.mjs +1 -0
- package/tools/sync.mjs +131 -0
package/lib/index.js
CHANGED
|
@@ -25,22 +25,25 @@
|
|
|
25
25
|
*/
|
|
26
26
|
import { note, serviceOf } from './env.js'
|
|
27
27
|
import { composePersona } from './persona.js'
|
|
28
|
-
import { collectCandidates, ingestCandidates } from './extract.js'
|
|
29
|
-
import {
|
|
28
|
+
import { collectCandidates, currentUserText, ingestCandidates, isPromotable, isSubagentSession } from './extract.js'
|
|
29
|
+
import { refineCandidates } from './refine.js'
|
|
30
|
+
import { addRecord, recallQueryTerms, renderRecallOnly } from './memory.js'
|
|
31
|
+
import { collectForDiary, startDiaryTimer, runCatchUp, readRecentDiaries, readRecentChat, todayKey } from './diary.js'
|
|
30
32
|
import {
|
|
31
33
|
cardsFor,
|
|
32
34
|
globalCard,
|
|
33
35
|
loadConfig,
|
|
34
36
|
maintain,
|
|
35
37
|
projectCard,
|
|
36
|
-
|
|
38
|
+
renderMemoryBlockRecalled,
|
|
37
39
|
saveGlobalCard,
|
|
38
40
|
saveProjectCard,
|
|
41
|
+
writeAutoMemories,
|
|
39
42
|
applyMoodDelta
|
|
40
43
|
} from './store.js'
|
|
41
44
|
import { purposeState, savePurposeState } from './store.js'
|
|
42
|
-
import { satisfyDrives, summarize, openGoals, renderPurpose } from './purpose.js'
|
|
43
|
-
import { observeAgent, unobserveAll, normalizeMoodConfig } from './mood.js'
|
|
45
|
+
import { markServed, satisfyDrives, settleServed, summarize, openGoals, renderPurpose } from './purpose.js'
|
|
46
|
+
import { lastAssistantTextOf, observeAgent, unobserveAll, normalizeMoodConfig } from './mood.js'
|
|
44
47
|
import { registerMemoryTool, registerGoalTool, setFallbackCwd } from './tool.js'
|
|
45
48
|
import { registerApi, registerAssets } from './api.js'
|
|
46
49
|
|
|
@@ -54,55 +57,365 @@ const MAINTAIN_INTERVAL_MS = 10 * 60 * 1000
|
|
|
54
57
|
|
|
55
58
|
let lastMaintainAt = 0
|
|
56
59
|
|
|
57
|
-
/**
|
|
58
|
-
let
|
|
60
|
+
/** 提炼链:一次只跑一批,避免两批候选同时改同一张卡。 */
|
|
61
|
+
let refineChain = Promise.resolve()
|
|
59
62
|
|
|
60
63
|
/**
|
|
61
|
-
*
|
|
64
|
+
* 把候选交给模型提炼,再落盘(异步,不阻塞注入)。
|
|
62
65
|
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
66
|
+
* 为什么不 await:tick 跑在 systemPrompt.context 的 text() 里,是**同步**的、
|
|
67
|
+
* 每回合都要走一遍的路。等一次 30 秒的模型调用 = 每轮对话都卡 30 秒。
|
|
68
|
+
* 所以排队后台跑:这一轮注入用旧卡,下一轮就看得到新记忆。
|
|
69
|
+
*
|
|
70
|
+
* 提炼失败(超时 / 报错 / 格式崩)一律退回原话直存 —— 宁可记糙,不能把信息丢掉。
|
|
67
71
|
*/
|
|
68
|
-
function
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
72
|
+
function queueRefine(agent, cwd, candidates, config, llm) {
|
|
73
|
+
refineChain = refineChain
|
|
74
|
+
.then(async () => {
|
|
75
|
+
const refined = await refineCandidates(llm, agent, candidates, {
|
|
76
|
+
note,
|
|
77
|
+
owner: String(config.moodOwnerName || '树树'),
|
|
78
|
+
provider: String(config.memoryRefineProvider || ''),
|
|
79
|
+
model: String(config.memoryRefineModel || '')
|
|
80
|
+
})
|
|
81
|
+
if (refined === null) {
|
|
82
|
+
note('memory', `提炼失败,${candidates.length} 条候选退回原话直存`)
|
|
83
|
+
ingestRaw(cwd, candidates, config)
|
|
84
|
+
return
|
|
85
|
+
}
|
|
86
|
+
if (refined.length === 0) {
|
|
87
|
+
// 2026-10-31:原来只记「候选 N 条,没提炼出值得记的」—— 数字有了,
|
|
88
|
+
// **内容没了**。她永远不知道自己哪句话被当成废话丢掉了。
|
|
89
|
+
// 现在把每条候选的开头记下来,至少能回头看「当时被丢掉的是什么」。
|
|
90
|
+
// 这不是要推翻提炼的判断,是让「被丢弃」这件事本身留下证据。
|
|
91
|
+
const preview = candidates
|
|
92
|
+
.slice(0, 5)
|
|
93
|
+
.map((c) => {
|
|
94
|
+
const text = String(c?.text ?? c?.content ?? c ?? '').replace(/\s+/g, ' ').trim()
|
|
95
|
+
return text === '' ? '(空)' : text.slice(0, 40) + (text.length > 40 ? '…' : '')
|
|
96
|
+
})
|
|
97
|
+
.join(' | ')
|
|
98
|
+
note('memory', `候选 ${candidates.length} 条,没提炼出值得记的(寒暄/废话)。被丢弃的内容:${preview || '(空)'}`)
|
|
99
|
+
return
|
|
100
|
+
}
|
|
101
|
+
const report = writeAutoMemories(cwd, refined, config)
|
|
102
|
+
if (report.written > 0) {
|
|
103
|
+
note('memory', `提炼出 ${report.written} 条记忆(候选 ${candidates.length})${report.promoted > 0 ? `,${report.promoted} 条进全局卡` : ''}`)
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
.catch((error) => {
|
|
107
|
+
note('memory', `提炼链失败:${error instanceof Error ? error.message : error}`)
|
|
108
|
+
})
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* 老的直存路径:候选原话直接进卡(不提炼)。
|
|
113
|
+
*
|
|
114
|
+
* 只在「没有模型服务」或「配置里关了提炼」时走 —— 也是提炼失败时的兜底。
|
|
115
|
+
* 自动记进**项目卡**(有 cwd 时),否则全局卡:跟随当前工作上下文,避免跨项目污染。
|
|
116
|
+
*/
|
|
117
|
+
function ingestRaw(cwd, candidates, config) {
|
|
118
|
+
const useProject = String(cwd ?? '').trim() !== '' && config.projectMemoryEnabled !== false
|
|
119
|
+
const card = useProject ? projectCard(cwd) : globalCard()
|
|
120
|
+
const written = ingestCandidates(card, addRecord, candidates, config, Date.now())
|
|
121
|
+
if (written > 0) {
|
|
122
|
+
if (useProject) saveProjectCard(cwd, card)
|
|
123
|
+
else saveGlobalCard(card)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---- 跨工作区双写(2026-10-29) ----
|
|
127
|
+
// addRecord 按文本去重,重复写只是刷新召回次数,不会堆条目。
|
|
128
|
+
if (useProject) {
|
|
129
|
+
const threshold = config.globalPromoteImportance ?? 62
|
|
130
|
+
const promo = candidates.filter((candidate) => isPromotable(candidate, threshold))
|
|
131
|
+
if (promo.length > 0) {
|
|
132
|
+
const gcard = globalCard()
|
|
133
|
+
const promoted = ingestCandidates(gcard, addRecord, promo, config, Date.now())
|
|
134
|
+
if (promoted > 0) {
|
|
135
|
+
saveGlobalCard(gcard)
|
|
136
|
+
note('extract', `跨工作区记下 ${promoted} 条(重要度 ≥ ${threshold} 且关于本人)`)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 每个会话已经「想起来过」的记忆(原文),避免同一件事连着好几轮刷屏。 */
|
|
143
|
+
const recallSeenBySession = new Map()
|
|
144
|
+
|
|
145
|
+
// ---- 粘性召回(2026-10-30) ----
|
|
146
|
+
//
|
|
147
|
+
// 问题:DSH 只在**整段运行时快照文本变化时**才重新追加一条 user/message
|
|
148
|
+
// (RuntimeContextProjection.project 里 `if (this.retained?.text === snapshot) return`)。
|
|
149
|
+
// 记忆段的相关区是拿「当前这句话」算出来的,句句不同 → 快照每轮都变 →
|
|
150
|
+
// 每轮都追加一条,历史里越堆越多,等于每轮重付一遍。
|
|
151
|
+
//
|
|
152
|
+
// 做法:话题没变就**不重算**,直接返回上次那段文本(必须逐字节一致,
|
|
153
|
+
// 不能重新拼串 —— 拼接顺序、时间戳、标点差一个字节都不算「没变」)。
|
|
154
|
+
// 只有用户明显换了话题才重算相关区。
|
|
155
|
+
//
|
|
156
|
+
// 为什么 key 必须用 session id:这张表里存的是别人会话的记忆原文,
|
|
157
|
+
// 串一次就是把 A 的私事塞进 B 的提示词。取不到 id 就一律不粘(见 text() 里)。
|
|
158
|
+
const stickyRecallBySession = new Map()
|
|
159
|
+
/** 表上限:会话开多了不能一直涨;超了按最久未用淘汰。 */
|
|
160
|
+
const STICKY_MAX_SESSIONS = 32
|
|
161
|
+
/** 话题重合度阈值:Jaccard ≥ 0.6 视为「还是这个话题」。 */
|
|
162
|
+
const STICKY_TOPIC_JACCARD = 0.6
|
|
163
|
+
/** 复用日志的限频:同一会话 10 分钟内只记一次,别把日志刷成噪音。 */
|
|
164
|
+
const STICKY_NOTE_INTERVAL_MS = 10 * 60 * 1000
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 两个词集合的 Jaccard 相似度 = |A∩B| / |A∪B|。
|
|
168
|
+
*
|
|
169
|
+
* 选 Jaccard 而不是「命中数 / 上次词数」:后者对「这次句子特别长」不敏感 ——
|
|
170
|
+
* 只要把上次的词全说一遍,再堆一堆新词进去也还是 1.0,话题其实早换了。
|
|
171
|
+
* 分母用并集,新词多就自然掉下来。
|
|
172
|
+
*
|
|
173
|
+
* @param {Set<string>} a 上次召回用的词集合
|
|
174
|
+
* @param {Set<string>} b 这次召回用的词集合
|
|
175
|
+
*/
|
|
176
|
+
function jaccardOf(a, b) {
|
|
177
|
+
if (a.size === 0 || b.size === 0) return 0
|
|
178
|
+
let intersection = 0
|
|
179
|
+
for (const term of a) if (b.has(term)) intersection += 1
|
|
180
|
+
return intersection / (a.size + b.size - intersection)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 取(或建)一个会话的粘性状态,顺手做 LRU 淘汰。
|
|
185
|
+
*
|
|
186
|
+
* 状态字段:
|
|
187
|
+
* · terms —— 上次用于召回的词集合,下次算 Jaccard 用;
|
|
188
|
+
* · text —— 上次注入的完整文本,命中时**原样返回**;
|
|
189
|
+
* · rendered —— 有没有「上次」可沿用。空串也是一次有效渲染,
|
|
190
|
+
* 不能拿 text === '' 当「没渲染过」,否则没召回出东西的会话
|
|
191
|
+
* 每轮都会退整卡。
|
|
192
|
+
* · lastUsedAt / lastNoteAt —— 淘汰顺序与日志限频。
|
|
193
|
+
*/
|
|
194
|
+
function stickyStateFor(sessionId, now) {
|
|
195
|
+
const existed = stickyRecallBySession.get(sessionId)
|
|
196
|
+
if (existed !== undefined) {
|
|
197
|
+
existed.lastUsedAt = now
|
|
198
|
+
return existed
|
|
199
|
+
}
|
|
200
|
+
const state = { terms: new Set(), text: '', rendered: false, lastUsedAt: now, lastNoteAt: 0 }
|
|
201
|
+
stickyRecallBySession.set(sessionId, state)
|
|
202
|
+
if (stickyRecallBySession.size > STICKY_MAX_SESSIONS) {
|
|
203
|
+
let oldestId = ''
|
|
204
|
+
let oldestAt = Infinity
|
|
205
|
+
for (const [id, item] of stickyRecallBySession) {
|
|
206
|
+
if (id === sessionId) continue
|
|
207
|
+
if (item.lastUsedAt < oldestAt) {
|
|
208
|
+
oldestAt = item.lastUsedAt
|
|
209
|
+
oldestId = id
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (oldestId !== '') stickyRecallBySession.delete(oldestId)
|
|
74
213
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
214
|
+
return state
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* 「因话题未变而复用上次注入」记一次日志(限频)。
|
|
219
|
+
*
|
|
220
|
+
* 这条是判断粘性到底有没有生效的唯一依据:日志里出现了,说明某一轮真的没重算;
|
|
221
|
+
* 一直不出现,要么话题一直在跳,要么判定逻辑根本没跑到。
|
|
222
|
+
*/
|
|
223
|
+
function noteStickyReuse(sessionId, state, now) {
|
|
224
|
+
if (now - state.lastNoteAt < STICKY_NOTE_INTERVAL_MS) return
|
|
225
|
+
state.lastNoteAt = now
|
|
226
|
+
note('memory', `话题未变,复用上次记忆注入(会话 ${sessionId.slice(0, 8)},${state.text.length} 字)`)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* 短于 4 字的 query 当退化情况处理(「嗯」「好的」「继续」这类)。
|
|
231
|
+
*
|
|
232
|
+
* 它们切不出有意义的词集合,Jaccard 恒为 0 —— 拿去重算只会让文本在
|
|
233
|
+
* 「空串 ↔ 某条记忆」之间来回抖,等于每轮都追加一条快照。
|
|
234
|
+
*/
|
|
235
|
+
function isDegenerateQuery(query) {
|
|
236
|
+
return String(query ?? '').trim().length < 4
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* 新会话第一轮额外注入的「最近」(2026-10-31)。
|
|
241
|
+
*
|
|
242
|
+
* 补的是这条断层:树树不会在一个对话里做完所有事 —— 修插件、QQ 聊天、
|
|
243
|
+
* 闲聊是分开的会话。记忆卡给的是零碎事实(「树树大二」「不喜欢机械」),
|
|
244
|
+
* 日记又只写到「昨天」。所以新开一个对话时,她不知道今天早些时候
|
|
245
|
+
* 在别的对话里做过什么,也不知道昨天具体是怎么过的。
|
|
246
|
+
*
|
|
247
|
+
* 这里并两块:
|
|
248
|
+
* ① 前几天的日记(叙事,接得上「昨天我们干了什么」)
|
|
249
|
+
* ② 今天到目前为止的流水(conversations/<今天>.jsonl 是所有会话汇总的)
|
|
250
|
+
*
|
|
251
|
+
* 只在第一轮注入,不每轮重复。私密日记默认不进(见配置项)。
|
|
252
|
+
*
|
|
253
|
+
* @returns {string} 空串 = 没有可注入的内容
|
|
254
|
+
*/
|
|
255
|
+
function renderRecentSection(cfg) {
|
|
83
256
|
try {
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
257
|
+
const days = Number(cfg.memoryRecentDiaryDays)
|
|
258
|
+
const chatChars = Number(cfg.memoryRecentChatChars)
|
|
259
|
+
const today = todayKey(Date.now())
|
|
260
|
+
const parts = []
|
|
261
|
+
|
|
262
|
+
if (Number.isFinite(days) && days > 0) {
|
|
263
|
+
const recent = readRecentDiaries(today, Math.min(Math.trunc(days), 7))
|
|
264
|
+
const raw = cfg.memoryRecentDiaryIncludePrivate === true ? recent.all : recent.public
|
|
265
|
+
const body = typeof raw === 'string' ? raw.trim() : ''
|
|
266
|
+
if (body !== '') {
|
|
267
|
+
// 日记正序拼接(旧在前),尾部才是最近的 —— 超长时留尾部。
|
|
268
|
+
// 上限 6000 字:两三篇日记正常够用,异常长的也不会把开场撑爆。
|
|
269
|
+
const capped = body.length > 6000 ? `(更早的部分已省略)\n\n${body.slice(-6000)}` : body
|
|
270
|
+
parts.push(`### 前几天的日记\n\n${capped}`)
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (Number.isFinite(chatChars) && chatChars > 0) {
|
|
275
|
+
const chat = readRecentChat(today, Math.min(Math.trunc(chatChars), 12000))
|
|
276
|
+
if (typeof chat === 'string' && chat.trim() !== '') {
|
|
277
|
+
parts.push(`### 今天到目前为止(可能来自别的对话)\n\n${chat.trim()}`)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (parts.length === 0) return ''
|
|
282
|
+
return `\n\n## 最近\n\n${parts.join('\n\n')}`
|
|
283
|
+
} catch (error) {
|
|
284
|
+
note('memory', `注入「最近」失败:${error instanceof Error ? error.message : error}`)
|
|
285
|
+
return ''
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** 第一轮之后的「想起来了」:按当前这句话召回,并排除本会话已经说过的。 */
|
|
290
|
+
function recallForTurn(cwd, cfg, query, sessionId) {
|
|
291
|
+
let seen = recallSeenBySession.get(sessionId)
|
|
292
|
+
if (seen === undefined) {
|
|
293
|
+
if (recallSeenBySession.size > 200) recallSeenBySession.clear()
|
|
294
|
+
seen = new Set()
|
|
295
|
+
recallSeenBySession.set(sessionId, seen)
|
|
92
296
|
}
|
|
93
|
-
|
|
297
|
+
// cardsFor 返回的是 { scope, card } 包一层的外壳,renderRecallOnly 要的是裸卡数组。
|
|
298
|
+
// 2026-10-30 修:以前直接把外壳传进去,被它的 Array.isArray(card.records) 过滤掉,
|
|
299
|
+
// 这条「第一轮之后唯一的记忆通路」一直是空跑 —— 日志不报错,只是永远想不起来。
|
|
300
|
+
const cards = cardsFor(cwd).map((entry) => entry.card)
|
|
301
|
+
const recalled = renderRecallOnly(cards, { config: cfg, query, exclude: seen })
|
|
302
|
+
if (recalled.text === '') return ''
|
|
303
|
+
for (const key of recalled.keys) seen.add(key)
|
|
304
|
+
return recalled.text
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 每个会话的扫描游标(2026-10-31)。
|
|
309
|
+
*
|
|
310
|
+
* 只扫「上次之后新增的事件」,不每次从头数 —— text() 是同步的装配路径,
|
|
311
|
+
* 长会话全量重扫等于每一步都白跑几千条事件。
|
|
312
|
+
* 表要有上限:会话开多了不能一直涨。
|
|
313
|
+
*/
|
|
314
|
+
const turnCursorBySession = new Map()
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* 这个会话是不是还停在「第一轮对话」里(2026-10-30,2026-10-31 改增量)。
|
|
318
|
+
*
|
|
319
|
+
* 判据是「会话里出现过几条真人 user/message」:
|
|
320
|
+
* ① 同一轮内会装配多次(重试 / 标题生成),用调用计数会被提前消耗掉;
|
|
321
|
+
* ② 冷启动恢复的会话仍有历史,天然不会再注入整卡;
|
|
322
|
+
* ③ 游标按 seq 单调推进,压缩/裁剪造成的断档不会让判断倒退。
|
|
323
|
+
* 读不到事件时返回 true(宁可多注入一次,也不让新会话失忆)。
|
|
324
|
+
*/
|
|
325
|
+
function isFirstTurnOfSession(agent) {
|
|
326
|
+
const session = agent?.session
|
|
327
|
+
if (session === undefined || session === null) return true
|
|
328
|
+
const seq = Number(session.seq)
|
|
329
|
+
if (!Number.isFinite(seq)) return true
|
|
330
|
+
const id = String(session.header?.id ?? '')
|
|
331
|
+
if (id === '') return true
|
|
332
|
+
|
|
333
|
+
let state = turnCursorBySession.get(id)
|
|
334
|
+
if (state === undefined) {
|
|
335
|
+
if (turnCursorBySession.size > 200) turnCursorBySession.clear()
|
|
336
|
+
// cursor = -1:第一次见到这个会话,从最早开始扫一次,把真实条数拿到
|
|
337
|
+
state = { cursor: -1, human: 0 }
|
|
338
|
+
turnCursorBySession.set(id, state)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
let events = []
|
|
94
342
|
try {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
343
|
+
if (typeof session.snapshotEvents === 'function') {
|
|
344
|
+
// snapshotEvents(from, to) 是半开区间,和 extract.js 的 currentUserText 同款用法
|
|
345
|
+
events = session.snapshotEvents(Math.max(0, state.cursor + 1), seq + 1) || []
|
|
346
|
+
} else if (Array.isArray(session.events)) {
|
|
347
|
+
events = session.events.filter((event) => {
|
|
348
|
+
const at = Number(event?.seq)
|
|
349
|
+
return Number.isFinite(at) ? at > state.cursor : true
|
|
350
|
+
})
|
|
351
|
+
} else {
|
|
352
|
+
return true
|
|
353
|
+
}
|
|
354
|
+
} catch {
|
|
355
|
+
return true
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
if (!Array.isArray(events)) return true
|
|
359
|
+
for (const event of events) {
|
|
360
|
+
const kind = event?.type ?? event?.kind
|
|
361
|
+
if (kind !== 'user/message') continue
|
|
362
|
+
const sourceKind = event?.source?.kind ?? event?.payload?.source?.kind ?? event?.data?.source?.kind
|
|
363
|
+
// 没有 source 信息的老事件也算一轮:判宽一点,别把第二轮当成第一轮
|
|
364
|
+
if (sourceKind === undefined || sourceKind === 'user') state.human += 1
|
|
100
365
|
}
|
|
101
|
-
|
|
366
|
+
state.cursor = Math.max(state.cursor, seq)
|
|
367
|
+
return state.human <= 1
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* 人格隔多少轮补注一次(2026-10-31)。
|
|
372
|
+
*
|
|
373
|
+
* 树树的话:人格不该是教条,做事方式靠上下文推理就够了 —— 这点对。
|
|
374
|
+
* 但「我叫糖糖」不是推理出来的,是事实。推理推不出自己的名字。
|
|
375
|
+
*
|
|
376
|
+
* 只在首轮注入的风险:对话长到触发上下文压缩,历史被压成摘要,
|
|
377
|
+
* 人格正文就真的没了,而 `isFirstTurnOfSession` 还是恒 false,不会补。
|
|
378
|
+
* 那时会变成「记得聊过什么,但不记得自己是谁」。
|
|
379
|
+
*
|
|
380
|
+
* 所以折中:首轮注入 + 每隔这么多轮补一次。
|
|
381
|
+
* 15 轮补一次(树树定的):注入之后它就留在上下文里了,不用每轮重发;
|
|
382
|
+
* 但隔一段时间补一次,压缩之后能自己找回来。成本相对于十五轮对话可以忽略。
|
|
383
|
+
*/
|
|
384
|
+
const PERSONA_REFRESH_TURNS = 15
|
|
385
|
+
const personaInjectAtBySession = new Map()
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* 这次该不该注入人格段。
|
|
389
|
+
*
|
|
390
|
+
* @returns {boolean} true = 注入(并记下这次的位置)
|
|
391
|
+
*/
|
|
392
|
+
function shouldInjectPersona(agent) {
|
|
393
|
+
// 先跑一次 isFirstTurnOfSession:它会把 human 计数推进到最新
|
|
394
|
+
const first = isFirstTurnOfSession(agent)
|
|
395
|
+
const id = String(agent?.session?.header?.id ?? '')
|
|
396
|
+
if (id === '') return true
|
|
397
|
+
|
|
398
|
+
const human = turnCursorBySession.get(id)?.human ?? 0
|
|
399
|
+
const last = personaInjectAtBySession.get(id)
|
|
400
|
+
|
|
401
|
+
// 同一轮内会装配多次(重试 / 标题生成)。已经为这个 human 计数注入过,
|
|
402
|
+
// 就不要再注入一遍 —— 否则「省消耗」反而变成一轮发好几份人格。
|
|
403
|
+
if (last !== undefined && human === last) return false
|
|
404
|
+
|
|
405
|
+
// 首轮、或从来没记过注入点(重启后 Map 是空的,补一次)、或隔得够远了
|
|
406
|
+
if (first || last === undefined || human - last >= PERSONA_REFRESH_TURNS) {
|
|
407
|
+
if (personaInjectAtBySession.size > 200) personaInjectAtBySession.clear()
|
|
408
|
+
personaInjectAtBySession.set(id, human)
|
|
409
|
+
return true
|
|
410
|
+
}
|
|
411
|
+
return false
|
|
102
412
|
}
|
|
103
413
|
|
|
104
414
|
/** 注入时的轻量维护:衰减/压缩按自己的节奏,提取每回合都做(增量,很便宜)。 */
|
|
105
|
-
function tick(agent, cwd, config, { allowMaintain = true } = {}) {
|
|
415
|
+
function tick(agent, cwd, config, { allowMaintain = true, llm = null } = {}) {
|
|
416
|
+
// 子会话整段跳过:不维护、不提取、不写日记。
|
|
417
|
+
// 这是「会不会产生写入」的唯一收敛点 —— 判断只写在这里,别在调用方散写。
|
|
418
|
+
if (isSubagentSession(agent)) return
|
|
106
419
|
const now = Date.now()
|
|
107
420
|
if (allowMaintain && now - lastMaintainAt > MAINTAIN_INTERVAL_MS) {
|
|
108
421
|
lastMaintainAt = now
|
|
@@ -116,27 +429,28 @@ function tick(agent, cwd, config, { allowMaintain = true } = {}) {
|
|
|
116
429
|
}
|
|
117
430
|
}
|
|
118
431
|
|
|
119
|
-
if (agent === undefined || agent === null)
|
|
120
|
-
diag(agent, '【tick 在此返回,记忆提取根本没跑】')
|
|
121
|
-
return
|
|
122
|
-
}
|
|
432
|
+
if (agent === undefined || agent === null) return
|
|
123
433
|
try {
|
|
124
|
-
const
|
|
125
|
-
const { candidates } = result
|
|
126
|
-
// 诊断:把「扫到几个事件 / 游标在哪 / 候选几个」写进日志
|
|
127
|
-
diag(agent, `scanned=${result.scanned} from=${result.from} to=${result.to} 候选=${candidates.length}`)
|
|
434
|
+
const { candidates } = collectCandidates(agent, { limit: config.maxPerTick ?? 12 })
|
|
128
435
|
if (candidates.length === 0) return
|
|
129
|
-
//
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
if (useProject) saveProjectCard(cwd, card)
|
|
135
|
-
else saveGlobalCard(card)
|
|
436
|
+
// 有模型就走「提炼成记忆」;没有模型 / 关掉了就退回原话直存(老路径,不丢信息)
|
|
437
|
+
if (llm !== null && llm !== undefined && config.memoryRefine !== false) {
|
|
438
|
+
queueRefine(agent, cwd, candidates, config, llm)
|
|
439
|
+
} else {
|
|
440
|
+
ingestRaw(cwd, candidates, config)
|
|
136
441
|
}
|
|
137
442
|
} catch (error) {
|
|
138
443
|
note('extract', `提取失败:${error instanceof Error ? error.message : error}`)
|
|
139
444
|
}
|
|
445
|
+
|
|
446
|
+
// ---- 日记:顺手把新对话追加到当天 JSONL ----
|
|
447
|
+
// 游标独立于 extract.js,不干扰记忆提取。收 user/message + assistant/message,
|
|
448
|
+
// 过滤口径与 extract.js 一致(跳过 runtime-context / schedule 等注入消息)。
|
|
449
|
+
try {
|
|
450
|
+
collectForDiary(agent)
|
|
451
|
+
} catch (error) {
|
|
452
|
+
note('diary', `对话记录失败:${error instanceof Error ? error.message : error}`)
|
|
453
|
+
}
|
|
140
454
|
}
|
|
141
455
|
|
|
142
456
|
export function apply(ctx) {
|
|
@@ -165,6 +479,13 @@ export function apply(ctx) {
|
|
|
165
479
|
return
|
|
166
480
|
}
|
|
167
481
|
|
|
482
|
+
// llm 服务提前取:心情判断要用(异步),记忆提炼也要用(异步)。
|
|
483
|
+
// 拿不到不影响人格/记忆注入 —— 只是那两条路退回"不调模型"的老做法。
|
|
484
|
+
const llm = serviceOf(ctx, 'llm')
|
|
485
|
+
if (llm === undefined || llm === null) {
|
|
486
|
+
note('apply', '宿主没有 llm 服务:心情判断不跑,记忆只在过滤后原话直存(不提炼)')
|
|
487
|
+
}
|
|
488
|
+
|
|
168
489
|
// 注入前先取服务:有些宿主把它挂在 ctx 属性上,有些只走 ctx.get()。
|
|
169
490
|
// 只认一种的话,另一种会静默失效 —— 表现是「设置里看得见插件,但人格没注入」。
|
|
170
491
|
const systemPrompt = serviceOf(ctx, 'systemPrompt')
|
|
@@ -179,8 +500,15 @@ export function apply(ctx) {
|
|
|
179
500
|
return systemPrompt.context({
|
|
180
501
|
name: 'soul:persona',
|
|
181
502
|
order: 260,
|
|
503
|
+
// required:人格是「她是谁」,不能因为是精简上下文(includeRuntimeContext=false)
|
|
504
|
+
// 就整个丢掉 —— 那种模式下 agent 会变得没有身份。
|
|
505
|
+
required: true,
|
|
182
506
|
text: (context) => {
|
|
183
507
|
if (loadConfig().enabled === false) return ''
|
|
508
|
+
// 2026-10-31:人格只在会话首轮注入,之后每隔 PERSONA_REFRESH_TURNS 轮补一次。
|
|
509
|
+
// 不每轮重发(树树说的:不想让用不到的东西持续做无用消耗),
|
|
510
|
+
// 也不注入一次就再也不管(上下文压缩之后会把自己是谁也压掉)。
|
|
511
|
+
if (!shouldInjectPersona(context?.agent)) return ''
|
|
184
512
|
const cwd = context?.agent?.session?.header?.cwd ?? ''
|
|
185
513
|
const composed = composePersona({ cwd, config: loadConfig() })
|
|
186
514
|
if (composed.truncated) note('persona', '人格正文超过上限,已截断')
|
|
@@ -203,15 +531,67 @@ export function apply(ctx) {
|
|
|
203
531
|
return systemPrompt.context({
|
|
204
532
|
name: 'soul:memory',
|
|
205
533
|
order: 250,
|
|
534
|
+
// required:includeRuntimeContext=false 的 agent 也要拿到记忆卡,
|
|
535
|
+
// 否则「她是谁 / 她记得什么」在这类 agent 上直接失忆(见 DSH 的
|
|
536
|
+
// assemble:contexts.filter(entry => !suppressed || entry.required === true))。
|
|
537
|
+
required: true,
|
|
206
538
|
text: (context) => {
|
|
207
539
|
const cfg = loadConfig()
|
|
208
540
|
if (cfg.enabled === false || cfg.memoryEnabled === false) return ''
|
|
209
541
|
const agent = context?.agent
|
|
210
542
|
const cwd = agent?.session?.header?.cwd ?? ''
|
|
211
543
|
if (typeof cwd === 'string' && cwd !== '') setFallbackCwd(cwd)
|
|
212
|
-
//
|
|
213
|
-
|
|
214
|
-
|
|
544
|
+
// 顺手做增量提取与例行维护:不阻塞注入。
|
|
545
|
+
// 提取本身很快(扫事件+过滤),真正调模型的"提炼"是排队后台跑的。
|
|
546
|
+
// 子会话的挡板在 tick 里(唯一收敛点),这里只负责不注入整卡。
|
|
547
|
+
tick(agent, cwd, cfg, { llm })
|
|
548
|
+
if (isSubagentSession(agent)) return ''
|
|
549
|
+
const query = currentUserText(agent)
|
|
550
|
+
// 2026-10-30:整卡只在会话第一轮注入;之后只按当前这句话召回。
|
|
551
|
+
// 这条分支**不写粘性状态** —— 一旦把整卡记成「上次文本」,
|
|
552
|
+
// 下一轮就会原样把它再发一遍,正好是要修的那个毛病。
|
|
553
|
+
// 2026-10-31:第一轮再带上「最近」(前几天日记 + 今天流水),
|
|
554
|
+
// 否则新开对话时不知道今天在别的对话里做过什么。
|
|
555
|
+
if (isFirstTurnOfSession(agent)) {
|
|
556
|
+
return `${renderMemoryBlockRecalled(cwd, cfg, query)}${renderRecentSection(cfg)}`
|
|
557
|
+
}
|
|
558
|
+
// 关掉相关区 = 整卡老路:逐字节等于改动前,也不必进粘性状态(没有相关区可粘)。
|
|
559
|
+
if (cfg.memoryRecall !== true) return renderMemoryBlockRecalled(cwd, cfg, query)
|
|
560
|
+
|
|
561
|
+
const now = Date.now()
|
|
562
|
+
const sessionId = String(agent?.session?.header?.id ?? '')
|
|
563
|
+
// 取不到 id 就退回每次重算:宁可多付 token,也不能让新会话拿到别人的记忆。
|
|
564
|
+
const sticky = sessionId === '' ? null : stickyStateFor(sessionId, now)
|
|
565
|
+
|
|
566
|
+
// 退化 query(纯注入 / 装配早于事件落库 / 「嗯」「好的」):沿用上次,
|
|
567
|
+
// 绝不因为「这一轮没听懂人话」把文本重新拼一遍。
|
|
568
|
+
if (isDegenerateQuery(query)) {
|
|
569
|
+
if (sticky !== null && sticky.rendered === true) return sticky.text
|
|
570
|
+
// 没有上次可沿用才走整卡。这一段本身也记进粘性状态:
|
|
571
|
+
// 否则同一个会话每遇到一句「嗯」,整卡就会被重新拼一次、再追加一条快照。
|
|
572
|
+
const whole = renderMemoryBlockRecalled(cwd, cfg, '')
|
|
573
|
+
if (sticky !== null) {
|
|
574
|
+
sticky.terms = new Set()
|
|
575
|
+
sticky.text = whole
|
|
576
|
+
sticky.rendered = true
|
|
577
|
+
}
|
|
578
|
+
return whole
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
const terms = recallQueryTerms(query)
|
|
582
|
+
// 话题没变 → 直接交回上次那段文本,一个字节都不重拼(见函数头注释)。
|
|
583
|
+
if (sticky !== null && sticky.rendered === true && jaccardOf(sticky.terms, terms) >= STICKY_TOPIC_JACCARD) {
|
|
584
|
+
noteStickyReuse(sessionId, sticky, now)
|
|
585
|
+
return sticky.text
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const text = recallForTurn(cwd, cfg, query, sessionId)
|
|
589
|
+
if (sticky !== null) {
|
|
590
|
+
sticky.terms = terms
|
|
591
|
+
sticky.text = text
|
|
592
|
+
sticky.rendered = true
|
|
593
|
+
}
|
|
594
|
+
return text
|
|
215
595
|
}
|
|
216
596
|
})
|
|
217
597
|
} catch (error) {
|
|
@@ -229,11 +609,26 @@ export function apply(ctx) {
|
|
|
229
609
|
return systemPrompt.context({
|
|
230
610
|
name: 'soul:purpose',
|
|
231
611
|
order: 240,
|
|
232
|
-
|
|
612
|
+
// required:惦记的事是她主动性的来源,精简上下文时也不该被砍掉。
|
|
613
|
+
required: true,
|
|
614
|
+
text: (context) => {
|
|
233
615
|
const cfg = loadConfig()
|
|
234
616
|
if (cfg.enabled === false || cfg.purposeEnabled === false) return ''
|
|
235
617
|
try {
|
|
236
|
-
|
|
618
|
+
const state = purposeState()
|
|
619
|
+
// 先消化上一轮:渲染出去的目标,她有没有真的说出口。
|
|
620
|
+
// satisfyDrives 只在这里被调用 —— 在此之前它是一段没人接的死代码。
|
|
621
|
+
const settled = settleServed(state, {
|
|
622
|
+
assistantText: lastAssistantTextOf(context?.agent?.session)
|
|
623
|
+
})
|
|
624
|
+
if (settled.sent.length > 0) {
|
|
625
|
+
note('purpose', `惦记的事说出口了 ${settled.sent.length} 条,驱动回落`)
|
|
626
|
+
}
|
|
627
|
+
const text = renderPurpose(state, { maxGoals: 3 })
|
|
628
|
+
// 记下这一轮渲染出去的目标,下一轮才有得可查
|
|
629
|
+
const marked = markServed(state, openGoals(state, { limit: 3 }))
|
|
630
|
+
if (settled.sent.length > 0 || settled.skipped.length > 0 || marked) savePurposeState(state)
|
|
631
|
+
return text
|
|
237
632
|
} catch (error) {
|
|
238
633
|
note('purpose', `渲染失败:${error instanceof Error ? error.message : error}`)
|
|
239
634
|
return ''
|
|
@@ -252,10 +647,10 @@ export function apply(ctx) {
|
|
|
252
647
|
// ---- 4. 心情:每轮钩子(返回空串 = 零注入) ----
|
|
253
648
|
// text() 每次装配都被调用、拿得到 agent —— 正好在这里懒挂 turn-stopping。
|
|
254
649
|
// 判断是异步的、结果只落盘(mood/ 目录),不占提示词预算、没有挂饰。
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
650
|
+
//
|
|
651
|
+
// 2026-10-30 为什么不加 required:这段永远返回空串,被 includeRuntimeContext=false
|
|
652
|
+
// 过滤掉不损失任何提示词内容;用 required 保活一个空串,等于为了跑副作用去占
|
|
653
|
+
// 「必需上下文」的名额,名不副实。副作用(心情记账)只该跟着真正注入的上下文走。
|
|
259
654
|
ctx.effect(() => {
|
|
260
655
|
const dispose = (() => {
|
|
261
656
|
try {
|
|
@@ -266,6 +661,8 @@ export function apply(ctx) {
|
|
|
266
661
|
const cfg = loadConfig()
|
|
267
662
|
if (cfg.enabled === false || cfg.moodEnabled === false) return ''
|
|
268
663
|
const agent = context?.agent
|
|
664
|
+
// 子会话不判心情:它是一次性任务上下文,判断结果会按 cwd 记进主会话的账上。
|
|
665
|
+
if (isSubagentSession(agent)) return ''
|
|
269
666
|
if (agent !== undefined && agent !== null && llm !== undefined && llm !== null) {
|
|
270
667
|
// 幂等:observeAgent 内部按 agent 去重,挂一次就够
|
|
271
668
|
observeAgent(agent, {
|
|
@@ -300,12 +697,46 @@ export function apply(ctx) {
|
|
|
300
697
|
}, 'dsh-agent-soul: mood hook')
|
|
301
698
|
|
|
302
699
|
note('apply', `注入已就绪:人格/记忆/目的三段 + 心情记账,模式=${loadConfig().mode}`)
|
|
700
|
+
|
|
701
|
+
// ---- 5. 日记:定时器 + 启动补写 ----
|
|
702
|
+
// 定时器独立于注入开关(enabled=false 时 tick 不跑 → 无对话可记 → 日记自然写"今天没有对话"),
|
|
703
|
+
// 但日记自己的开关 diaryEnabled=false 时完全不启动。
|
|
704
|
+
if (loadConfig().diaryEnabled !== false) {
|
|
705
|
+
try {
|
|
706
|
+
const stopDiary = startDiaryTimer(ctx)
|
|
707
|
+
if (typeof ctx.effect === 'function') {
|
|
708
|
+
ctx.effect(() => stopDiary, 'dsh-agent-soul: diary timer')
|
|
709
|
+
}
|
|
710
|
+
note('apply', '日记定时器已启动')
|
|
711
|
+
} catch (error) {
|
|
712
|
+
note('diary', `定时器启动失败:${error instanceof Error ? error.message : error}`)
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// 启动补写:找最近缺失日,只补那一天
|
|
716
|
+
if (loadConfig().diaryCatchUp !== false) {
|
|
717
|
+
try {
|
|
718
|
+
void runCatchUp(ctx)
|
|
719
|
+
} catch (error) {
|
|
720
|
+
note('diary', `补写失败:${error instanceof Error ? error.message : error}`)
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
}
|
|
303
724
|
}
|
|
304
725
|
|
|
305
726
|
/** 测试用:重置内部计时器与心情钩子。 */
|
|
306
727
|
export function __resetForTest() {
|
|
307
728
|
lastMaintainAt = 0
|
|
729
|
+
turnCursorBySession.clear()
|
|
730
|
+
// 2026-10-30:粘性状态与「说过了」集合也是模块级缓存,测试之间必须清掉,
|
|
731
|
+
// 否则上一个用例的文本会被下一个用例当成「上次注入」复用了。
|
|
732
|
+
stickyRecallBySession.clear()
|
|
733
|
+
recallSeenBySession.clear()
|
|
308
734
|
unobserveAll()
|
|
309
735
|
}
|
|
310
736
|
|
|
311
|
-
|
|
737
|
+
/** 测试用:粘性状态表的当前规模(验证上限淘汰真的生效)。 */
|
|
738
|
+
export function __stickyStatsForTest() {
|
|
739
|
+
return { size: stickyRecallBySession.size, max: STICKY_MAX_SESSIONS }
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
export { cardsFor, summarize, openGoals, satisfyDrives, savePurposeState, applyMoodDelta, isFirstTurnOfSession }
|