@restregular/dsh-memory 0.9.5 → 0.9.7

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,236 +1,536 @@
1
- /**
2
- * Cordis wiring for dsh-memory-inject. Loaded only inside DSH.
3
- *
4
- * 注入分四层,全部可以在面板「记忆 → 设置」里单独开关:
5
- * 1. recall —— 每轮按查询召回(可有可无;内容没变就不重复注入)
6
- * 2. digest —— 会话第一步给一次"已有记忆"的摘要
7
- * 3. policy —— 系统提示里的「记忆使用策略」常驻段
8
- * 4. rules —— 系统提示里的「硬性规则」段(kind='rule' 的记忆)
9
- * 另有 rulesDelta —— 旧会话在下一轮补一条新增/变更的规则(0.9.0;随 rules 开关)
10
- * 另有 turnEnd —— 轮末提醒(下一轮开头提示"上一轮若有结论就记一条"),默认关。
11
- *
12
- * Message construction MUST go through createUserMessage: the loop reads
13
- * `decision.kind` and downstream consumers read `message.source.kind`, so a
14
- * hand-rolled `{ role, content }` object aborts the turn with
15
- * "Cannot read properties of undefined (reading 'kind')" (incident 2026-10-10).
16
- *
17
- * Memory is an OPTIONAL dependency (ctx.get) by design — this plugin must not
18
- * sit PENDING when no provider is loaded; it just stays passive.
19
- */
20
-
21
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
22
-
23
- import {
24
- MemoryDigester,
25
- MemoryInjector,
26
- hasRecallMessage,
27
- normalizeExtraScopes,
28
- resolveInjectScopes,
29
- sessionIdOf,
30
-
31
-
32
-
33
-
34
- } from './inject.js'
35
- import { renderDigestBlock } from './digest.js'
36
- import { renderRulesBlock } from './rules.js'
37
- import { RulesDeltaInjector } from './rules-delta.js'
38
- import { POLICY_TEXT } from './policy.js'
39
- import { normalizeInjectSettings, } from '../provider/inject-settings.js'
1
+ /**
2
+ * Cordis wiring for dsh-memory-inject. Loaded only inside DSH.
3
+ *
4
+ * 注入分四层,全部可以在面板「记忆 → 设置」里单独开关:
5
+ * 1. recall —— 每轮按查询召回(可有可无;内容没变就不重复注入)
6
+ * 2. digest —— 会话第一步给一次"已有记忆"的摘要 + 截断标签索引
7
+ * 3. policy —— 系统提示里的「记忆使用策略」常驻段
8
+ * 4. rules —— 系统提示里的「硬性规则」段(kind='rule' 的记忆)
9
+ * 另有 rulesDelta —— 旧会话在下一轮补一条新增/变更的规则(0.9.0;随 rules 开关)
10
+ * 另有 turnEnd —— 轮末提醒(下一轮开头提示"上一轮若有结论就记一条"),默认关。
11
+ *
12
+ * 0.9.6 起多了两条可验证的路径:
13
+ * - digest 的正文/标签/省略统计会写进 `InjectAuditStore`;
14
+ * - `session/event` 的 tool/call、tool/result、compaction 事件会生成行为信号,
15
+ * 在下一个 pre-step 做一次增量自动召回(已注入正文按会话 + 记忆 id/版本去重)。
16
+ *
17
+ * Message construction MUST go through createUserMessage: the loop reads
18
+ * `decision.kind` and downstream consumers read `message.source.kind`, so a
19
+ * hand-rolled `{ role, content }` object aborts the turn with
20
+ * "Cannot read properties of undefined (reading 'kind')" (incident 2026-10-10).
21
+ *
22
+ * Memory is an OPTIONAL dependency (ctx.get) by design — this plugin must not
23
+ * sit PENDING when no provider is loaded; it just stays passive.
24
+ */
25
+
26
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
27
+
28
+ import {
29
+ MemoryDigester,
30
+ MemoryInjector,
31
+ hasRecallMessage,
32
+ normalizeExtraScopes,
33
+ pickQueryText,
34
+ resolveInjectScopes,
35
+ sessionIdOf,
36
+
37
+
38
+
39
+
40
+ } from './inject.js'
41
+ import { renderDigest, } from './digest.js'
42
+ import { renderRules, renderRulesBlock } from './rules.js'
43
+ import { RulesDeltaInjector } from './rules-delta.js'
44
+ import { POLICY_TEXT } from './policy.js'
45
+ import { InjectionState } from './state.js'
46
+ import { InjectAuditStore, auditBudget, auditQuery, } from './audit.js'
47
+ import {
48
+ BehaviorSignalStore,
49
+ assistantVisibleText,
50
+ commandText,
51
+ detectPhase,
52
+ failureSignal,
53
+ goalText,
54
+ highRiskSignal,
55
+ textTagSignal,
56
+ todoText,
57
+ toolCallDescription,
58
+ toolResultFailure,
59
+
60
+ } from './signals.js'
61
+ import { normalizeInjectSettings, } from '../provider/inject-settings.js'
62
+
63
+
64
+
65
+
66
+
67
+
68
+                        
69
+
70
+
71
+
72
+ /** provider 在注入侧能提供的那部分能力(多余的方法都用可选判断)。 */
73
+
74
+
75
+
76
+
77
+
78
+
79
+ /** 轮末提醒的文案:短、祈使句,不占预算。 */
80
+ const NUDGE_TEXT =
81
+ '上一轮若产生了可复用的结论(决策、踩坑、流程、口径),先 memory_save 记一条再继续;' +
82
+ '没有就忽略这条提醒。'
83
+
84
+ export const name = 'dsh-memory-inject'
85
+
86
+ export function apply(ctx , config = {}) {
87
+ // 配置只作为兜底;provider 的 settings.json(面板可改)优先。
88
+ const fallback = normalizeInjectSettings(config)
89
+ const enabled = config.enabled !== false
90
+
91
+ const settingsOf = () => {
92
+ const memory = ctx.get('memory')
93
+ try {
94
+ const live = memory?.injectSettings?.()
95
+ if (live) return live
96
+ } catch { /* 拿不到就用配置里的 */ }
97
+ return fallback
98
+ }
99
+
100
+ const recallCfg = () => {
101
+ const settings = settingsOf().recall
102
+ return { enabled: enabled && settings.enabled, topK: settings.topK, tokenBudget: settings.tokenBudget }
103
+ }
104
+ const impressionCfg = () => {
105
+ const settings = settingsOf().impression
106
+ return { impression: settings.enabled, chars: settings.chars }
107
+ }
108
+
109
+ const extraScopes = normalizeExtraScopes(config.extraScopes ?? [])
110
+ const readScopesFor = (memory , agent ) =>
111
+ resolveInjectScopes(memory, agent, extraScopes, ctx.get?.('sessions') )
112
+
113
+ /** 会话级注入状态(正文/标签/版本)与审计。 */
114
+ const injectionState = new InjectionState()
115
+ const audit = new InjectAuditStore()
116
+ const signals = new BehaviorSignalStore()
117
+ const callMeta = new Map ()
118
+ const sessionScopes = new Map ()
119
+ const tagCache = new Map ()
120
+ let attachedMemory = null
121
+
122
+ const attachAudit = (memory ) => {
123
+ const target = memory
124
+ if (!target || target === attachedMemory || typeof target.attachInjectAudit !== 'function') return
125
+ try {
126
+ target.attachInjectAudit(audit)
127
+ attachedMemory = target
128
+ } catch { /* 审计是可选增强 */ }
129
+ }
130
+
131
+ const recordAudit = (entry ) => {
132
+ audit.record({ at: Date.now(), ...entry })
133
+ }
134
+
135
+ const rememberCallMeta = (callId , name , description ) => {
136
+ if (typeof callId !== 'string' || callId === '') return
137
+ callMeta.set(callId, { name, ...(description !== undefined ? { description } : {}) })
138
+ if (callMeta.size > 500) {
139
+ const oldest = callMeta.keys().next()
140
+ if (!oldest.done) callMeta.delete(oldest.value)
141
+ }
142
+ }
143
+
144
+ const excludedIds = (memory , scopes ) => {
145
+ try {
146
+ return new Set(memory.supersededIds?.(scopes === undefined ? undefined : [...scopes]) ?? [])
147
+ } catch {
148
+ return new Set()
149
+ }
150
+ }
151
+
152
+ // One injector per activation: its repeat-suppression state must live across
153
+ // the steps of a turn (a per-step instance would re-inject every step).
154
+ const scopesForSession = (sessionId , memory , session ) => {
155
+ const known = sessionScopes.get(sessionId)
156
+ if (known !== undefined) return known
157
+ try {
158
+ const resolved = memory.resolveReadScopes?.({ session })
159
+ if (Array.isArray(resolved)) {
160
+ sessionScopes.set(sessionId, resolved)
161
+ return resolved
162
+ }
163
+ } catch { /* 拿不到就用空集合;下次 pre-step 会补 */ }
164
+ return []
165
+ }
166
+
167
+ /**
168
+ * 触发词 = 设置里的额外标签 ∪ 当前记忆库里已有的标签(可关)。
169
+ * 后者让“记忆标签”本身成为触发词,不需要用户把每个标签抄进设置。
170
+ * listSync 只读内存快照;30 秒缓存避免每条 assistant 消息都扫一遍。
171
+ */
172
+ const triggerTags = (
173
+ memory ,
174
+ sessionId ,
175
+ scopes ,
176
+ auto ,
177
+ ) => {
178
+ const configured = auto.tags
179
+ if (!auto.useMemoryTags || !memory?.listSync) return configured
180
+ const cacheKey = `${sessionId}|${scopes.join('|')}`
181
+ const now = Date.now()
182
+ const cached = tagCache.get(cacheKey)
183
+ if (cached !== undefined && now - cached.at < 30_000) return cached.tags
184
+ const tags = []
185
+ const seen = new Set ()
186
+ const add = (tag ) => {
187
+ const value = tag.trim()
188
+ const key = value.toLowerCase()
189
+ if (value === '' || seen.has(key)) return
190
+ seen.add(key)
191
+ tags.push(value)
192
+ }
193
+ for (const tag of configured) add(tag)
194
+ try {
195
+ const records = memory.listSync({ scopes: [...scopes], limit: 1000 })
196
+ for (const record of records) for (const tag of record.tags ?? []) add(String(tag))
197
+ } catch { /* 读不到记忆标签就只用配置标签 */ }
198
+ const limited = tags.slice(0, 200)
199
+ tagCache.set(cacheKey, { at: now, tags: limited })
200
+ if (tagCache.size > 200) {
201
+ const oldest = tagCache.keys().next()
202
+ if (!oldest.done) tagCache.delete(oldest.value)
203
+ }
204
+ return limited
205
+ }
206
+
207
+ const observeSignal = (sessionId , signal ) => {
208
+ if (!signal || !signals.note(sessionId, signal)) return
209
+ recordAudit({
210
+ sessionId,
211
+ trigger: signal.reason,
212
+ phase: signal.phase,
213
+ query: signal.query,
214
+ candidates: 0, contentIds: [], hintIds: [], omitted: [], dedupSkipped: 0, budgets: {},
215
+ retrieval: { ok: true, count: 0 },
216
+ signal: {
217
+ reason: signal.reason,
218
+ ...(signal.errorClass ? { errorClass: signal.errorClass } : {}),
219
+ ...(signal.tool ? { tool: signal.tool } : {}),
220
+ ...(signal.tag ? { tag: signal.tag } : {}),
221
+ ...(signal.source ? { source: signal.source } : {}),
222
+ },
223
+ })
224
+ }
225
+
226
+ const injector = new MemoryInjector(
227
+ async (query, signal, scopes) => {
228
+ const memory = ctx.get('memory')
229
+ if (!memory?.search) return []
230
+ return memory.search({
231
+ text: query,
232
+ signal,
233
+ topK: recallCfg().topK,
234
+ ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
235
+ })
236
+ },
237
+ recallCfg,
238
+ impressionCfg,
239
+ injectionState,
240
+ )
241
+
242
+ // 摘要:provider 没有 list(旧版/半边加载失败)时自动退化为"不发摘要"。
243
+ const digester = new MemoryDigester(async (scopes) => {
244
+ const memory = ctx.get('memory')
245
+ if (!memory?.list) return []
246
+ return memory.list({
247
+ ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
248
+ limit: 200,
249
+ })
250
+ })
251
+
252
+ // 规则增量:一个激活一个实例,跨轮记住每条规则上一轮的样子(编辑后才补提醒)。
253
+ const rulesDelta = new RulesDeltaInjector()
254
+
255
+ /**
256
+ * 可观测行为信号 → 下一次 pre-step 的定向召回。
257
+ * 只消费宿主公开的 session/event;不读取隐藏思维链,不记录工具原始参数。
258
+ */
259
+ try {
260
+ ctx.on('session/event', (session , event ) => {
261
+ try {
262
+ const sessionId = (session )?.id
263
+ if (typeof sessionId !== 'string' || sessionId === '') return
264
+ const type = (event )?.type
265
+ const data = (event )?.data ?? {}
266
+ const memory = ctx.get('memory')
267
+ if (memory) attachAudit(memory)
268
+
269
+ if (type === 'compaction/start' || type === 'compaction/end') {
270
+ // 上下文重建:旧去重状态不再可信,允许摘要/正文重新进入。
271
+ injectionState.clear(sessionId)
272
+ signals.clear(sessionId)
273
+ digester.reset(sessionId)
274
+ sessionScopes.delete(sessionId)
275
+ for (const key of tagCache.keys()) if (key.startsWith(`${sessionId}|`)) tagCache.delete(key)
276
+ callMeta.clear()
277
+ return
278
+ }
279
+ const settings = enabled ? settingsOf() : undefined
280
+ const auto = settings?.autoRecall
281
+ if (!auto?.enabled) return
282
+ const scopes = scopesForSession(sessionId, memory , session)
283
+ const tags = triggerTags(memory , sessionId, scopes, auto)
284
+
285
+ if (type === 'tool/call') {
286
+ const tool = typeof data.name === 'string' ? data.name : 'tool'
287
+ const args = typeof data.arguments === 'string'
288
+ ? data.arguments
289
+ : (() => { try { return JSON.stringify(data.arguments ?? '') } catch { return '' } })()
290
+ const description = auto.useToolDescription ? toolCallDescription(data.arguments) : undefined
291
+ rememberCallMeta(data.callId, tool, description)
292
+ observeSignal(sessionId, highRiskSignal(tool, args, {
293
+ tags,
294
+ ...(description !== undefined ? { description } : {}),
295
+ useToolDescription: auto.useToolDescription,
296
+ maxQueryChars: auto.maxQueryChars,
297
+ }))
298
+ return
299
+ }
300
+ if (type === 'tool/result') {
301
+ const failure = toolResultFailure(event)
302
+ if (!failure.isError) return
303
+ const message = data.message
304
+ const callId = message?.source?.callId
305
+ const meta = typeof callId === 'string' ? callMeta.get(callId) : undefined
306
+ const description = auto.useToolDescription ? meta?.description : undefined
307
+ observeSignal(sessionId, failureSignal(meta?.name, failure.code, failure.message, {
308
+ ...(description !== undefined ? { description } : {}),
309
+ maxQueryChars: auto.maxQueryChars,
310
+ }))
311
+ return
312
+ }
313
+ // 可见 assistant 输出 / 任务清单 / 命令 / goal:命中记忆标签就排队一次召回。
314
+ // 只读 text 块,不读 reasoning/隐藏思维链。
315
+ if (type === 'assistant/message' || type === 'todo/write' || type === 'command/run' || type === 'goal/change') {
316
+ const text = type === 'assistant/message' ? assistantVisibleText(event)
317
+ : type === 'todo/write' ? todoText(event)
318
+ : type === 'command/run' ? commandText(event)
319
+ : goalText(event)
320
+ const source = type === 'assistant/message' ? 'assistant'
321
+ : type === 'todo/write' ? 'todo'
322
+ : type === 'command/run' ? 'command' : 'goal'
323
+ observeSignal(sessionId, text === undefined ? undefined : textTagSignal(text, {
324
+ tags,
325
+ source,
326
+ maxQueryChars: auto.maxQueryChars,
327
+ }))
328
+ return
329
+ }
330
+ } catch { /* 观察者失败绝不影响会话事件发布 */ }
331
+ })
332
+ } catch { /* 老宿主没有 session/event:行为召回自动缺席 */ }
333
+
334
+ // 系统提示:记忆使用策略(常驻) + 硬性规则(kind='rule')。
335
+ // 两者都用函数形式,面板开关/规则改动下一步就生效;文本稳定时可随前缀缓存。
336
+ ctx.inject(['systemPrompt'], (scoped ) => {
337
+ const systemPrompt = (scoped ).systemPrompt
338
+ if (!systemPrompt?.section) return
339
+ try {
340
+ systemPrompt.section({
341
+ name: 'memory:policy',
342
+ order: 650,
343
+ text: () => (enabled && settingsOf().policy.enabled ? POLICY_TEXT : ''),
344
+ })
345
+ systemPrompt.section({
346
+ name: 'memory:rules',
347
+ order: 660,
348
+ text: (context ) => {
349
+ if (!enabled || !settingsOf().rules.enabled) return ''
350
+ const memory = ctx.get('memory')
351
+ if (!memory?.listSync) return ''
352
+ let scopes = ['global']
353
+ try {
354
+ scopes = (memory.resolveReadScopes?.(context?.agent) ) ?? ['global']
355
+ } catch { scopes = ['global'] }
356
+ try {
357
+ return renderRulesBlock(memory.listSync({ scopes, kind: 'rule', limit: 100 }), settingsOf().rules) ?? ''
358
+ } catch {
359
+ return ''
360
+ }
361
+ },
362
+ })
363
+ } catch {
364
+ /* 重复注册或老宿主没有 section 契约:规则段缺席不影响注入 */
365
+ }
366
+ })
367
+
368
+ // 轮末提醒:本轮跑过多步(不是闲聊),下一轮第一步附带一句提醒。
369
+ let maxStep = 0
370
+ let pendingNudge = false
371
+ ctx.on('agent/turn-stopping', () => {
372
+ if (!enabled || !settingsOf().turnEnd.enabled) return
373
+ if (maxStep >= 2) pendingNudge = true
374
+ })
375
+
376
+ ctx.on('agent/pre-step', async (input, next) => {
377
+ // Runs outermost (prepend), so `next()` yields the fully assembled decision.
378
+ const decision = await next()
379
+ // A rejected step must pass through untouched — never rebuild the decision.
380
+ if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
381
+ // optional capability: absence (or partial load) → pass through untouched
382
+ const memory = ctx.get('memory')
383
+ if (!memory) return decision
384
+ attachAudit(memory)
385
+
386
+ const agent = (input ).agent
387
+ const step = (input ).step ?? 1
388
+ if (step === 1) maxStep = 0
389
+ maxStep = Math.max(maxStep, step)
390
+
391
+ const sessionId = sessionIdOf(agent)
392
+ const scopes = readScopesFor(memory, agent)
393
+ if (sessionId !== undefined && scopes !== undefined) sessionScopes.set(sessionId, [...scopes])
394
+ const exclude = excludedIds(memory, scopes)
395
+ const signal = sessionId === undefined ? undefined : signals.take(sessionId)
396
+ const userQuery = pickQueryText(input.messages )
397
+
398
+ // 摘要(每个会话一次)、召回(每轮有新内容时)、轮末提醒(下一轮首步)合成
399
+ // 同一条消息:内容没变就什么都不加,避免一步两张卡片。
400
+ const settings = enabled ? settingsOf() : undefined
401
+ const parts = []
402
+ // 规则增量:别的会话新加/改过的规则,在本轮第一步给旧会话补一次。
403
+ // `delta !== false` 而不是 `=== true`:老 provider 的 settings 快照没有这个
404
+ // 字段时要按"开"处理,否则升级当天等于静默关掉。
405
+ if (settings && step === 1 && settings.rules.enabled && settings.rules.delta !== false) {
406
+ const delta = rulesDelta.maybeInject(agent, memory, settings.rules)
407
+ if (delta) parts.push(delta)
408
+ }
409
+ if (pendingNudge && step === 1) {
410
+ pendingNudge = false
411
+ parts.push(NUDGE_TEXT)
412
+ }
413
+ if (settings) {
414
+ if (settings.digest.enabled) {
415
+ let digestStats
416
+ const digest = await digester.maybeDigestDetailed(sessionId, scopes, (records) => {
417
+ const rendered = renderDigest(records, settings.digest)
418
+ digestStats = rendered?.stats
419
+ return rendered
420
+ })
421
+ if (digest) {
422
+ if (sessionId !== undefined && digestStats !== undefined) {
423
+ injectionState.markContent(sessionId, digestStats.bodyEntries)
424
+ injectionState.markHint(sessionId, digestStats.hintEntries)
425
+ }
426
+ parts.push(digest.text)
427
+ if (digestStats !== undefined) {
428
+ recordAudit({
429
+ ...(sessionId !== undefined ? { sessionId } : {}),
430
+ trigger: 'turn_start', phase: 'unknown',
431
+ candidates: digestStats.candidates,
432
+ contentIds: digestStats.bodyIds,
433
+ hintIds: digestStats.hintIds,
434
+ omitted: digestStats.omitted.map((entry) => ({ id: entry.id, reason: entry.reason })),
435
+ dedupSkipped: 0,
436
+ budgets: {
437
+ digest: auditBudget(settings.digest.tokenBudget, digest.tokens),
438
+ hints: auditBudget(settings.digest.hintBudget, digestStats.hint.tokens),
439
+ },
440
+ retrieval: { ok: true, count: digestStats.candidates },
441
+ })
442
+ }
443
+ }
444
+ }
445
+
446
+ // 规则段每步都会在系统提示里重渲染;只在第一步记录一次审计,避免 200 条缓冲被刷爆。
447
+ if (step === 1 && settings.rules.enabled) {
448
+ try {
449
+ const rendered = renderRules(memory.listSync?.({ scopes, kind: 'rule', limit: 100 }) ?? [], settings.rules)
450
+ if (rendered) {
451
+ recordAudit({
452
+ ...(sessionId !== undefined ? { sessionId } : {}),
453
+ trigger: 'rules', phase: 'unknown',
454
+ candidates: rendered.stats.candidates,
455
+ contentIds: [], hintIds: [], omitted: [], dedupSkipped: 0,
456
+ budgets: { rules: auditBudget(settings.rules.tokenBudget, rendered.tokens) },
457
+ retrieval: { ok: true, count: rendered.stats.candidates },
458
+ rules: {
459
+ injected: rendered.stats.injected,
460
+ omittedTopK: rendered.stats.omittedTopK,
461
+ omittedBudget: rendered.stats.omittedBudget,
462
+ omittedSuperseded: rendered.stats.omittedSuperseded,
463
+ mandatory: rendered.stats.mandatory,
464
+ mandatoryOmitted: rendered.stats.mandatoryOmitted,
465
+ },
466
+ })
467
+ }
468
+ } catch { /* 审计不是注入的前置条件 */ }
469
+ }
470
+
471
+ // 行为信号优先:发布/推送/失败事件触发定向查询;没有信号才走普通用户消息召回。
472
+ // 同一轮普通 query 已处理过时跳过重复检索(去重状态仍会兜底)。
473
+ const skipNormalRecall = signal === undefined && step > 1 && sessionId !== undefined
474
+ && userQuery !== '' && injectionState.lastQueryOf(sessionId) === userQuery
475
+ if (!skipNormalRecall) {
476
+ const recall = await injector.maybeInjectDetailed(
477
+ { messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
478
+ { messages: decision.messages },
479
+ {
480
+ ...(sessionId !== undefined ? { sessionId } : {}),
481
+ ...(signal !== undefined ? { query: signal.query, trigger: signal.reason, force: true } : { trigger: 'turn_start' }),
482
+ excludeIds: exclude,
483
+ },
484
+ )
485
+ if (recall?.text) parts.push(recall.text)
486
+ if (recall) {
487
+ recordAudit({
488
+ ...(sessionId !== undefined ? { sessionId } : {}),
489
+ trigger: signal?.reason ?? 'turn_start',
490
+ phase: signal?.phase ?? detectPhase(userQuery),
491
+ ...(auditQuery(recall.query) !== undefined ? { query: auditQuery(recall.query) } : {}),
492
+ candidates: recall.candidates,
493
+ contentIds: recall.ids,
494
+ hintIds: [],
495
+ omitted: recall.omitted.map((entry) => ({ id: entry.id, reason: entry.reason })),
496
+ dedupSkipped: recall.dedupSkipped,
497
+ budgets: { recall: auditBudget(settings.recall.tokenBudget, recall.tokens) },
498
+ retrieval: recall.retrieval,
499
+ ...(signal !== undefined
500
+ ? { signal: { reason: signal.reason, ...(signal.errorClass ? { errorClass: signal.errorClass } : {}), ...(signal.tool ? { tool: signal.tool } : {}) } }
501
+ : {}),
502
+ })
503
+ }
504
+ }
505
+ }
506
+
507
+ const text = parts.join('\n\n')
508
+ if (!text) return decision
509
+ // 幂等:同一段内容已经在 decision 里(另一个激活实例放进去的),不再追加。
510
+ // 宿主把 entry 应用两次时,两个注入器会各自注入一条逐字相同的消息。
511
+ if (hasRecallMessage(decision.messages , text)) return decision
512
+ const message = createUserMessage({
513
+ content: [{ type: 'text', text }],
514
+ source: { kind: 'memory', form: 'recall' },
515
+ })
516
+ // Last-resort guard: a malformed message aborts the whole turn downstream
517
+ // (consumers read message.source.kind), so never publish one.
518
+ if (!isWellFormedMessage(message)) return decision
519
+ return { ...decision, messages: [...decision.messages, message] }
520
+ }, { prepend: true })
521
+ }
522
+
523
+ const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
524
+
525
+ /** Structural check against the host Message contract (id/role/content/source.kind). */
526
+ function isWellFormedMessage(message ) {
527
+ const m = message
528
+ if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
529
+ if (!Array.isArray(m.content) || m.content.length === 0) return false
530
+ if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
531
+ const source = m.source
532
+ return typeof source?.kind === 'string'
533
+ }
40
534
 
41
-
42
-
43
-
44
-
45
-
46
-                        
47
-
48
-
49
-
50
- /** provider 在注入侧能提供的那部分能力(多余的方法都用可选判断)。 */
51
-
52
-
53
-
54
-
55
-
56
- /** 轮末提醒的文案:短、祈使句,不占预算。 */
57
- const NUDGE_TEXT =
58
- '上一轮若产生了可复用的结论(决策、踩坑、流程、口径),先 memory_save 记一条再继续;' +
59
- '没有就忽略这条提醒。'
60
-
61
- export const name = 'dsh-memory-inject'
62
-
63
- export function apply(ctx , config = {}) {
64
- // 配置只作为兜底;provider 的 settings.json(面板可改)优先。
65
- const fallback = normalizeInjectSettings(config)
66
- const enabled = config.enabled !== false
67
-
68
- const settingsOf = () => {
69
- const memory = ctx.get('memory')
70
- try {
71
- const live = memory?.injectSettings?.()
72
- if (live) return live
73
- } catch { /* 拿不到就用配置里的 */ }
74
- return fallback
75
- }
76
-
77
- const recallCfg = () => {
78
- const settings = settingsOf().recall
79
- return { enabled: enabled && settings.enabled, topK: settings.topK, tokenBudget: settings.tokenBudget }
80
- }
81
- const impressionCfg = () => {
82
- const settings = settingsOf().impression
83
- return { impression: settings.enabled, chars: settings.chars }
84
- }
85
-
86
- const extraScopes = normalizeExtraScopes(config.extraScopes ?? [])
87
- const readScopesFor = (memory , agent ) =>
88
- resolveInjectScopes(memory, agent, extraScopes, ctx.get?.('sessions') )
89
-
90
- // One injector per activation: its repeat-suppression state must live across
91
- // the steps of a turn (a per-step instance would re-inject every step).
92
- const injector = new MemoryInjector(
93
- async (query, signal, scopes) => {
94
- const memory = ctx.get('memory')
95
- if (!memory?.search) return []
96
- return memory.search({
97
- text: query,
98
- signal,
99
- topK: recallCfg().topK,
100
- ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
101
- })
102
- },
103
- recallCfg,
104
- impressionCfg,
105
- )
106
-
107
- // 摘要:provider 没有 list(旧版/半边加载失败)时自动退化为"不发摘要"。
108
- const digester = new MemoryDigester(async (scopes) => {
109
- const memory = ctx.get('memory')
110
- if (!memory?.list) return []
111
- return memory.list({
112
- ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
113
- limit: 200,
114
- })
115
- })
116
-
117
- // 规则增量:一个激活一个实例,跨轮记住每条规则上一轮的样子(编辑后才补提醒)。
118
- const rulesDelta = new RulesDeltaInjector()
119
-
120
- // 系统提示:记忆使用策略(常驻) + 硬性规则(kind='rule')。
121
- // 两者都用函数形式,面板开关/规则改动下一步就生效;文本稳定时可随前缀缓存。
122
- ctx.inject(['systemPrompt'], (scoped ) => {
123
- const systemPrompt = (scoped ).systemPrompt
124
- if (!systemPrompt?.section) return
125
- try {
126
- systemPrompt.section({
127
- name: 'memory:policy',
128
- order: 650,
129
- text: () => (enabled && settingsOf().policy.enabled ? POLICY_TEXT : ''),
130
- })
131
- systemPrompt.section({
132
- name: 'memory:rules',
133
- order: 660,
134
- text: (context ) => {
135
- if (!enabled || !settingsOf().rules.enabled) return ''
136
- const memory = ctx.get('memory')
137
- if (!memory?.listSync) return ''
138
- let scopes = ['global']
139
- try {
140
- scopes = (memory.resolveReadScopes?.(context?.agent) ) ?? ['global']
141
- } catch { scopes = ['global'] }
142
- try {
143
- return renderRulesBlock(memory.listSync({ scopes, kind: 'rule', limit: 100 }), settingsOf().rules) ?? ''
144
- } catch {
145
- return ''
146
- }
147
- },
148
- })
149
- } catch {
150
- /* 重复注册或老宿主没有 section 契约:规则段缺席不影响注入 */
151
- }
152
- })
153
-
154
- // 轮末提醒:本轮跑过多步(不是闲聊),下一轮第一步附带一句提醒。
155
- let maxStep = 0
156
- let pendingNudge = false
157
- ctx.on('agent/turn-stopping', () => {
158
- if (!enabled || !settingsOf().turnEnd.enabled) return
159
- if (maxStep >= 2) pendingNudge = true
160
- })
161
-
162
- ctx.on('agent/pre-step', async (input, next) => {
163
- // Runs outermost (prepend), so `next()` yields the fully assembled decision.
164
- const decision = await next()
165
- // A rejected step must pass through untouched — never rebuild the decision.
166
- if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
167
- // optional capability: absence (or partial load) → pass through untouched
168
- const memory = ctx.get('memory')
169
- if (!memory) return decision
170
-
171
- const agent = (input ).agent
172
- const step = (input ).step ?? 1
173
- if (step === 1) maxStep = 0
174
- maxStep = Math.max(maxStep, step)
175
-
176
- // 会话上下文只在 pre-step 里拿得到:交给 search 的 `scopes`,与 memory_search 的
177
- // 默认合并集合用同一套解析(provider 的 resolveReadScopes)。
178
- const scopes = readScopesFor(memory, agent)
179
-
180
- // 摘要(每个会话一次)、召回(每轮有新内容时)、轮末提醒(下一轮首步)合成
181
- // 同一条消息:内容没变就什么都不加,避免一步两张卡片。
182
- const settings = enabled ? settingsOf() : undefined
183
- const parts = []
184
- // 规则增量:别的会话新加/改过的规则,在本轮第一步给旧会话补一次。
185
- // `delta !== false` 而不是 `=== true`:老 provider 的 settings 快照没有这个
186
- // 字段时要按"开"处理,否则升级当天等于静默关掉。
187
- if (settings && step === 1 && settings.rules.enabled && settings.rules.delta !== false) {
188
- const delta = rulesDelta.maybeInject(agent, memory, settings.rules)
189
- if (delta) parts.push(delta)
190
- }
191
- if (pendingNudge && step === 1) {
192
- pendingNudge = false
193
- parts.push(NUDGE_TEXT)
194
- }
195
- if (settings) {
196
- if (settings.digest.enabled) {
197
- const digest = await digester.maybeDigest(sessionIdOf(agent), scopes, (records) =>
198
- renderDigestBlock(records, settings.digest)?.text ?? null)
199
- if (digest) parts.push(digest)
200
- }
201
- const recall = await injector.maybeInject(
202
- { messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}) },
203
- { messages: decision.messages },
204
- )
205
- if (recall) parts.push(recall)
206
- }
207
-
208
- const text = parts.join('\n\n')
209
- if (!text) return decision
210
- // 幂等:同一段内容已经在 decision 里(另一个激活实例放进去的),不再追加。
211
- // 宿主把 entry 应用两次时,两个注入器会各自注入一条逐字相同的消息。
212
- if (hasRecallMessage(decision.messages , text)) return decision
213
- const message = createUserMessage({
214
- content: [{ type: 'text', text }],
215
- source: { kind: 'memory', form: 'recall' },
216
- })
217
- // Last-resort guard: a malformed message aborts the whole turn downstream
218
- // (consumers read message.source.kind), so never publish one.
219
- if (!isWellFormedMessage(message)) return decision
220
- return { ...decision, messages: [...decision.messages, message] }
221
- }, { prepend: true })
222
- }
223
-
224
- const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
225
-
226
- /** Structural check against the host Message contract (id/role/content/source.kind). */
227
- function isWellFormedMessage(message ) {
228
- const m = message
229
- if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
230
- if (!Array.isArray(m.content) || m.content.length === 0) return false
231
- if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
232
- const source = m.source
233
- return typeof source?.kind === 'string'
234
- }
235
535
 
236
536
  //# sourceURL=source/memory-inject/src/apply.ts