@restregular/dsh-memory 0.5.6 → 0.6.1
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 +56 -10
- package/lib/client.js +370 -1
- package/lib/inject/apply.js +221 -98
- package/lib/inject/digest.js +65 -0
- package/lib/inject/inject.js +106 -8
- package/lib/inject/policy.js +21 -0
- package/lib/inject/rules.js +31 -0
- package/lib/panel.js +51 -5
- package/lib/provider/apply.js +44 -0
- package/lib/provider/index.js +207 -2
- package/lib/provider/inject-settings.js +142 -0
- package/lib/provider/store.js +11 -0
- package/lib/tools/index.js +43 -2
- package/package.json +1 -1
package/lib/inject/apply.js
CHANGED
|
@@ -1,101 +1,224 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cordis wiring for dsh-memory-inject. Loaded only inside DSH
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
topK: config.topK ?? defaultInjectConfig.topK,
|
|
39
|
-
}
|
|
40
|
-
const extraScopes = normalizeExtraScopes(config.extraScopes ?? [])
|
|
41
|
-
const readScopesFor = (memory , agent ) =>
|
|
42
|
-
resolveInjectScopes(memory, agent, extraScopes, ctx.get?.('sessions') )
|
|
43
|
-
|
|
44
|
-
// One injector per activation: its repeat-suppression state must live across
|
|
45
|
-
// the steps of a turn (a per-step instance would re-inject every step).
|
|
46
|
-
const injector = new MemoryInjector(
|
|
47
|
-
async (query, signal, scopes) => {
|
|
48
|
-
const memory = ctx.get('memory')
|
|
49
|
-
if (!memory?.search) return []
|
|
50
|
-
return memory.search({
|
|
51
|
-
text: query,
|
|
52
|
-
signal,
|
|
53
|
-
topK: cfg.topK,
|
|
54
|
-
...(scopes !== undefined ? { scopes: [...scopes] } : {}),
|
|
55
|
-
})
|
|
56
|
-
},
|
|
57
|
-
cfg,
|
|
58
|
-
)
|
|
59
|
-
|
|
60
|
-
ctx.on('agent/pre-step', async (input, next) => {
|
|
61
|
-
// Runs outermost (prepend), so `next()` yields the fully assembled decision.
|
|
62
|
-
const decision = await next()
|
|
63
|
-
// A rejected step must pass through untouched — never rebuild the decision.
|
|
64
|
-
if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
|
|
65
|
-
// optional capability: absence (or partial load) → pass through untouched
|
|
66
|
-
const memory = ctx.get('memory')
|
|
67
|
-
if (!memory) return decision
|
|
68
|
-
|
|
69
|
-
// 会话上下文只在 pre-step 里拿得到:交给 search 的 `scopes`,与 memory_search 的
|
|
70
|
-
// 默认合并集合用同一套解析(provider 的 resolveReadScopes)。
|
|
71
|
-
const scopes = readScopesFor(memory, (input ).agent)
|
|
72
|
-
const text = await injector.maybeInject(
|
|
73
|
-
{ messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}) },
|
|
74
|
-
{ messages: decision.messages },
|
|
75
|
-
)
|
|
76
|
-
if (!text) return decision
|
|
77
|
-
const message = createUserMessage({
|
|
78
|
-
content: [{ type: 'text', text }],
|
|
79
|
-
source: { kind: 'memory', form: 'recall' },
|
|
80
|
-
})
|
|
81
|
-
// Last-resort guard: a malformed message aborts the whole turn downstream
|
|
82
|
-
// (consumers read message.source.kind), so never publish one.
|
|
83
|
-
if (!isWellFormedMessage(message)) return decision
|
|
84
|
-
return { ...decision, messages: [...decision.messages, message] }
|
|
85
|
-
}, { prepend: true })
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
|
|
89
|
-
|
|
90
|
-
/** Structural check against the host Message contract (id/role/content/source.kind). */
|
|
91
|
-
function isWellFormedMessage(message ) {
|
|
92
|
-
const m = message
|
|
93
|
-
if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
|
|
94
|
-
if (!Array.isArray(m.content) || m.content.length === 0) return false
|
|
95
|
-
if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
|
|
96
|
-
const source = m.source
|
|
97
|
-
return typeof source?.kind === 'string'
|
|
98
|
-
}
|
|
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
|
+
* 另有 turnEnd —— 轮末提醒(下一轮开头提示"上一轮若有结论就记一条"),默认关。
|
|
10
|
+
*
|
|
11
|
+
* Message construction MUST go through createUserMessage: the loop reads
|
|
12
|
+
* `decision.kind` and downstream consumers read `message.source.kind`, so a
|
|
13
|
+
* hand-rolled `{ role, content }` object aborts the turn with
|
|
14
|
+
* "Cannot read properties of undefined (reading 'kind')" (incident 2026-10-10).
|
|
15
|
+
*
|
|
16
|
+
* Memory is an OPTIONAL dependency (ctx.get) by design — this plugin must not
|
|
17
|
+
* sit PENDING when no provider is loaded; it just stays passive.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
MemoryDigester,
|
|
24
|
+
MemoryInjector,
|
|
25
|
+
hasRecallMessage,
|
|
26
|
+
normalizeExtraScopes,
|
|
27
|
+
resolveInjectScopes,
|
|
28
|
+
sessionIdOf,
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
} from './inject.js'
|
|
34
|
+
import { renderDigestBlock } from './digest.js'
|
|
35
|
+
import { renderRulesBlock } from './rules.js'
|
|
36
|
+
import { POLICY_TEXT } from './policy.js'
|
|
37
|
+
import { normalizeInjectSettings, } from '../provider/inject-settings.js'
|
|
99
38
|
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
/** provider 在注入侧能提供的那部分能力(多余的方法都用可选判断)。 */
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
/** 轮末提醒的文案:短、祈使句,不占预算。 */
|
|
55
|
+
const NUDGE_TEXT =
|
|
56
|
+
'上一轮若产生了可复用的结论(决策、踩坑、流程、口径),先 memory_save 记一条再继续;' +
|
|
57
|
+
'没有就忽略这条提醒。'
|
|
58
|
+
|
|
59
|
+
export const name = 'dsh-memory-inject'
|
|
60
|
+
|
|
61
|
+
export function apply(ctx , config = {}) {
|
|
62
|
+
// 配置只作为兜底;provider 的 settings.json(面板可改)优先。
|
|
63
|
+
const fallback = normalizeInjectSettings(config)
|
|
64
|
+
const enabled = config.enabled !== false
|
|
65
|
+
|
|
66
|
+
const settingsOf = () => {
|
|
67
|
+
const memory = ctx.get('memory')
|
|
68
|
+
try {
|
|
69
|
+
const live = memory?.injectSettings?.()
|
|
70
|
+
if (live) return live
|
|
71
|
+
} catch { /* 拿不到就用配置里的 */ }
|
|
72
|
+
return fallback
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const recallCfg = () => {
|
|
76
|
+
const settings = settingsOf().recall
|
|
77
|
+
return { enabled: enabled && settings.enabled, topK: settings.topK, tokenBudget: settings.tokenBudget }
|
|
78
|
+
}
|
|
79
|
+
const impressionCfg = () => {
|
|
80
|
+
const settings = settingsOf().impression
|
|
81
|
+
return { impression: settings.enabled, chars: settings.chars }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const extraScopes = normalizeExtraScopes(config.extraScopes ?? [])
|
|
85
|
+
const readScopesFor = (memory , agent ) =>
|
|
86
|
+
resolveInjectScopes(memory, agent, extraScopes, ctx.get?.('sessions') )
|
|
87
|
+
|
|
88
|
+
// One injector per activation: its repeat-suppression state must live across
|
|
89
|
+
// the steps of a turn (a per-step instance would re-inject every step).
|
|
90
|
+
const injector = new MemoryInjector(
|
|
91
|
+
async (query, signal, scopes) => {
|
|
92
|
+
const memory = ctx.get('memory')
|
|
93
|
+
if (!memory?.search) return []
|
|
94
|
+
return memory.search({
|
|
95
|
+
text: query,
|
|
96
|
+
signal,
|
|
97
|
+
topK: recallCfg().topK,
|
|
98
|
+
...(scopes !== undefined ? { scopes: [...scopes] } : {}),
|
|
99
|
+
})
|
|
100
|
+
},
|
|
101
|
+
recallCfg,
|
|
102
|
+
impressionCfg,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
// 摘要:provider 没有 list(旧版/半边加载失败)时自动退化为"不发摘要"。
|
|
106
|
+
const digester = new MemoryDigester(async (scopes) => {
|
|
107
|
+
const memory = ctx.get('memory')
|
|
108
|
+
if (!memory?.list) return []
|
|
109
|
+
return memory.list({
|
|
110
|
+
...(scopes !== undefined ? { scopes: [...scopes] } : {}),
|
|
111
|
+
limit: 200,
|
|
112
|
+
})
|
|
113
|
+
})
|
|
114
|
+
|
|
115
|
+
// 系统提示:记忆使用策略(常驻) + 硬性规则(kind='rule')。
|
|
116
|
+
// 两者都用函数形式,面板开关/规则改动下一步就生效;文本稳定时可随前缀缓存。
|
|
117
|
+
ctx.inject(['systemPrompt'], (scoped ) => {
|
|
118
|
+
const systemPrompt = (scoped ).systemPrompt
|
|
119
|
+
if (!systemPrompt?.section) return
|
|
120
|
+
try {
|
|
121
|
+
systemPrompt.section({
|
|
122
|
+
name: 'memory:policy',
|
|
123
|
+
order: 650,
|
|
124
|
+
text: () => (enabled && settingsOf().policy.enabled ? POLICY_TEXT : ''),
|
|
125
|
+
})
|
|
126
|
+
systemPrompt.section({
|
|
127
|
+
name: 'memory:rules',
|
|
128
|
+
order: 660,
|
|
129
|
+
text: (context ) => {
|
|
130
|
+
if (!enabled || !settingsOf().rules.enabled) return ''
|
|
131
|
+
const memory = ctx.get('memory')
|
|
132
|
+
if (!memory?.listSync) return ''
|
|
133
|
+
let scopes = ['global']
|
|
134
|
+
try {
|
|
135
|
+
scopes = (memory.resolveReadScopes?.(context?.agent) ) ?? ['global']
|
|
136
|
+
} catch { scopes = ['global'] }
|
|
137
|
+
try {
|
|
138
|
+
return renderRulesBlock(memory.listSync({ scopes, kind: 'rule', limit: 100 }), settingsOf().rules) ?? ''
|
|
139
|
+
} catch {
|
|
140
|
+
return ''
|
|
141
|
+
}
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
} catch {
|
|
145
|
+
/* 重复注册或老宿主没有 section 契约:规则段缺席不影响注入 */
|
|
146
|
+
}
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
// 轮末提醒:本轮跑过多步(不是闲聊),下一轮第一步附带一句提醒。
|
|
150
|
+
let maxStep = 0
|
|
151
|
+
let pendingNudge = false
|
|
152
|
+
ctx.on('agent/turn-stopping', () => {
|
|
153
|
+
if (!enabled || !settingsOf().turnEnd.enabled) return
|
|
154
|
+
if (maxStep >= 2) pendingNudge = true
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
ctx.on('agent/pre-step', async (input, next) => {
|
|
158
|
+
// Runs outermost (prepend), so `next()` yields the fully assembled decision.
|
|
159
|
+
const decision = await next()
|
|
160
|
+
// A rejected step must pass through untouched — never rebuild the decision.
|
|
161
|
+
if (!decision || decision.kind === 'reject' || input.signal?.aborted) return decision
|
|
162
|
+
// optional capability: absence (or partial load) → pass through untouched
|
|
163
|
+
const memory = ctx.get('memory')
|
|
164
|
+
if (!memory) return decision
|
|
165
|
+
|
|
166
|
+
const agent = (input ).agent
|
|
167
|
+
const step = (input ).step ?? 1
|
|
168
|
+
if (step === 1) maxStep = 0
|
|
169
|
+
maxStep = Math.max(maxStep, step)
|
|
170
|
+
|
|
171
|
+
// 会话上下文只在 pre-step 里拿得到:交给 search 的 `scopes`,与 memory_search 的
|
|
172
|
+
// 默认合并集合用同一套解析(provider 的 resolveReadScopes)。
|
|
173
|
+
const scopes = readScopesFor(memory, agent)
|
|
174
|
+
|
|
175
|
+
// 摘要(每个会话一次)、召回(每轮有新内容时)、轮末提醒(下一轮首步)合成
|
|
176
|
+
// 同一条消息:内容没变就什么都不加,避免一步两张卡片。
|
|
177
|
+
const parts = []
|
|
178
|
+
if (pendingNudge && step === 1) {
|
|
179
|
+
pendingNudge = false
|
|
180
|
+
parts.push(NUDGE_TEXT)
|
|
181
|
+
}
|
|
182
|
+
if (enabled) {
|
|
183
|
+
const settings = settingsOf()
|
|
184
|
+
if (settings.digest.enabled) {
|
|
185
|
+
const digest = await digester.maybeDigest(sessionIdOf(agent), scopes, (records) =>
|
|
186
|
+
renderDigestBlock(records, settings.digest)?.text ?? null)
|
|
187
|
+
if (digest) parts.push(digest)
|
|
188
|
+
}
|
|
189
|
+
const recall = await injector.maybeInject(
|
|
190
|
+
{ messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}) },
|
|
191
|
+
{ messages: decision.messages },
|
|
192
|
+
)
|
|
193
|
+
if (recall) parts.push(recall)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const text = parts.join('\n\n')
|
|
197
|
+
if (!text) return decision
|
|
198
|
+
// 幂等:同一段内容已经在 decision 里(另一个激活实例放进去的),不再追加。
|
|
199
|
+
// 宿主把 entry 应用两次时,两个注入器会各自注入一条逐字相同的消息。
|
|
200
|
+
if (hasRecallMessage(decision.messages , text)) return decision
|
|
201
|
+
const message = createUserMessage({
|
|
202
|
+
content: [{ type: 'text', text }],
|
|
203
|
+
source: { kind: 'memory', form: 'recall' },
|
|
204
|
+
})
|
|
205
|
+
// Last-resort guard: a malformed message aborts the whole turn downstream
|
|
206
|
+
// (consumers read message.source.kind), so never publish one.
|
|
207
|
+
if (!isWellFormedMessage(message)) return decision
|
|
208
|
+
return { ...decision, messages: [...decision.messages, message] }
|
|
209
|
+
}, { prepend: true })
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const VALID_BLOCK_TYPES = new Set(['text', 'reasoning', 'image', 'file', 'tool-call', 'tool-addition', 'tool-removal'])
|
|
213
|
+
|
|
214
|
+
/** Structural check against the host Message contract (id/role/content/source.kind). */
|
|
215
|
+
function isWellFormedMessage(message ) {
|
|
216
|
+
const m = message
|
|
217
|
+
if (!m || typeof m.id !== 'string' || typeof m.role !== 'string') return false
|
|
218
|
+
if (!Array.isArray(m.content) || m.content.length === 0) return false
|
|
219
|
+
if (!m.content.every((block) => typeof (block )?.type === 'string' && VALID_BLOCK_TYPES.has((block ).type))) return false
|
|
220
|
+
const source = m.source
|
|
221
|
+
return typeof source?.kind === 'string'
|
|
222
|
+
}
|
|
100
223
|
|
|
101
224
|
//# sourceURL=source/memory-inject/src/apply.ts
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话摘要(L1):会话第一步给一次"这个项目/全局已经记了什么"的全景。
|
|
3
|
+
*
|
|
4
|
+
* 与逐轮召回的分工:召回按这一轮的问题找;摘要不按问题,按重要度 × 新鲜度
|
|
5
|
+
* 挑几条,让模型一开始就知道有哪些旧结论可复用,而不是先搜一遍。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { estimateTokens } from '../provider/rerank.js'
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
const HEADER =
|
|
12
|
+
'以下是本项目 / 全局已有的长期记忆摘要(按重要度挑出的前几条;' +
|
|
13
|
+
'需要原文用 memory_search,删除用 memory_forget):'
|
|
14
|
+
|
|
15
|
+
/** scope 的中文标签:global/项目/会话/自定义。 */
|
|
16
|
+
export function digestScopeLabel(scope ) {
|
|
17
|
+
if (scope === 'global') return '全局'
|
|
18
|
+
if (scope === 'project' || scope.startsWith('project:')) return '项目'
|
|
19
|
+
if (scope === 'session' || scope.startsWith('session:')) return '会话'
|
|
20
|
+
return scope
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 摘要排序:与淘汰规则同一套"新鲜度(30 天半衰期)× 重要度",并列时按作用域
|
|
25
|
+
* 优先级(会话 > 项目 > 自定义 > 全局),最后按内容稳定排序 —— 同样的输入必须
|
|
26
|
+
* 给出同样的摘要,否则两个注入实例的内容会对不上。
|
|
27
|
+
*/
|
|
28
|
+
export function rankForDigest(records , now = Date.now()) {
|
|
29
|
+
const weight = (scope ) => {
|
|
30
|
+
if (scope.startsWith('session:')) return 3
|
|
31
|
+
if (scope.startsWith('project:')) return 2
|
|
32
|
+
if (scope === 'global') return 0
|
|
33
|
+
return 1
|
|
34
|
+
}
|
|
35
|
+
return [...records].sort((a, b) => {
|
|
36
|
+
const ra = Math.pow(0.5, Math.max(0, now - a.updatedAt) / 86_400_000 / 30) * (0.1 + a.importance)
|
|
37
|
+
const rb = Math.pow(0.5, Math.max(0, now - b.updatedAt) / 86_400_000 / 30) * (0.1 + b.importance)
|
|
38
|
+
if (rb !== ra) return rb - ra
|
|
39
|
+
const wa = weight(a.scope)
|
|
40
|
+
const wb = weight(b.scope)
|
|
41
|
+
if (wa !== wb) return wb - wa
|
|
42
|
+
return a.content.localeCompare(b.content)
|
|
43
|
+
})
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 渲染摘要块;没有记录返回 null,每条截 160 字,在预算内贪心填充。 */
|
|
47
|
+
export function renderDigestBlock(
|
|
48
|
+
records ,
|
|
49
|
+
cfg ,
|
|
50
|
+
) {
|
|
51
|
+
if (records.length === 0) return null
|
|
52
|
+
let tokens = estimateTokens(HEADER) + 4
|
|
53
|
+
const lines = []
|
|
54
|
+
for (const record of rankForDigest(records).slice(0, cfg.topK)) {
|
|
55
|
+
const line = `- ${record.id.slice(0, 8)} [${digestScopeLabel(record.scope)}/${record.kind}] ${record.content.replace(/\s+/g, ' ').slice(0, 160)}`
|
|
56
|
+
const cost = estimateTokens(line) + 1
|
|
57
|
+
if (tokens + cost > cfg.tokenBudget) break
|
|
58
|
+
lines.push(line)
|
|
59
|
+
tokens += cost
|
|
60
|
+
}
|
|
61
|
+
if (lines.length === 0) return null
|
|
62
|
+
return { text: `${HEADER}\n${lines.join('\n')}`, tokens, count: lines.length }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
//# sourceURL=source/memory-inject/src/digest.ts
|
package/lib/inject/inject.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* is a single `context` block with `contextForm: 'recall'`, prepended to the
|
|
6
6
|
* messages that enter the step via the agent/pre-step waterfall.
|
|
7
7
|
*/
|
|
8
|
-
|
|
8
|
+
|
|
9
9
|
import { estimateTokens } from '../provider/rerank.js'
|
|
10
10
|
import { normalizeScopeInput } from '../provider/scope.js'
|
|
11
11
|
|
|
@@ -128,14 +128,56 @@ export function pickQueryText(messages ) {
|
|
|
128
128
|
return ''
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
/**
|
|
132
|
+
* 这一步的 messages 里是否已经有一条内容完全相同的召回块。
|
|
133
|
+
*
|
|
134
|
+
* 正常情况下永远不会命中:一个激活只有一个 MemoryInjector,而它自己用 lastText
|
|
135
|
+
* 去重。但只要宿主把这条 entry 应用了两次(热重载/重新启用时旧 fiber 的
|
|
136
|
+
* agent/pre-step 监听没被清掉),两个注入器就会各追加一条逐字相同的消息 ——
|
|
137
|
+
* 表现在会话轨迹里就是同一轮「上下轮」卡片连着出现两次(2026-10-17 实况)。
|
|
138
|
+
* 注入本身是"多一条也无害、少一条也不坏"的提示块,所以这里按内容做一次幂等:
|
|
139
|
+
* 另一个实例已经放进去的同一段,就不要再放。
|
|
140
|
+
*/
|
|
141
|
+
export function hasRecallMessage(
|
|
142
|
+
messages ,
|
|
143
|
+
text ,
|
|
144
|
+
) {
|
|
145
|
+
for (const m of messages) {
|
|
146
|
+
if (m.role !== 'user') continue
|
|
147
|
+
if (m.source?.kind !== 'memory') continue
|
|
148
|
+
const joined = (m.content ?? [])
|
|
149
|
+
.filter((b) => b.type === 'text' && typeof b.text === 'string')
|
|
150
|
+
.map((b) => b.text )
|
|
151
|
+
.join('\n')
|
|
152
|
+
if (joined === text) return true
|
|
153
|
+
}
|
|
154
|
+
return false
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 召回的两种形态:旧的长文(300 字)与新的"印象"(短摘要 + 指路取全文)。 */
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
|
|
131
165
|
/** Render hits into a recall text block, greedily within the token budget. */
|
|
132
|
-
export function renderRecallBlock(
|
|
166
|
+
export function renderRecallBlock(
|
|
167
|
+
hits ,
|
|
168
|
+
cfg ,
|
|
169
|
+
options = {},
|
|
170
|
+
) {
|
|
133
171
|
if (hits.length === 0) return null
|
|
134
|
-
const
|
|
172
|
+
const impression = options.impression === true
|
|
173
|
+
const chars = impression ? (options.chars ?? 120) : 300
|
|
174
|
+
const header = impression
|
|
175
|
+
? '以下是与你这次请求可能相关的记忆摘要:'
|
|
176
|
+
: '以下是与此请求可能相关的长期记忆,供参考(可用 memory_search 核实,用 memory_forget 删除):'
|
|
135
177
|
let tokens = estimateTokens(header) + 4
|
|
136
178
|
const lines = []
|
|
137
179
|
for (const h of hits.slice(0, cfg.topK)) {
|
|
138
|
-
const line = `- ${h.record.content.replace(/\s+/g, ' ').slice(0,
|
|
180
|
+
const line = `- ${h.record.id.slice(0, 8)} ${h.record.content.replace(/\s+/g, ' ').slice(0, chars)}`
|
|
139
181
|
const cost = estimateTokens(line) + 1
|
|
140
182
|
if (tokens + cost > cfg.tokenBudget) break
|
|
141
183
|
lines.push(line)
|
|
@@ -159,24 +201,31 @@ export function recallText(text ) {
|
|
|
159
201
|
* Repeated identical injections are suppressed so a multi-step turn does not
|
|
160
202
|
* repeat the same block before every model call.
|
|
161
203
|
*/
|
|
204
|
+
/** 配置既可以给静态值,也可以给 getter —— 面板改了设置,下一步就生效。 */
|
|
205
|
+
|
|
206
|
+
|
|
162
207
|
export class MemoryInjector {
|
|
163
208
|
lastText = ''
|
|
164
209
|
search
|
|
165
|
-
cfg
|
|
210
|
+
cfg
|
|
211
|
+
renderOptions
|
|
166
212
|
|
|
167
213
|
constructor(
|
|
168
214
|
search ,
|
|
169
|
-
cfg
|
|
215
|
+
cfg ,
|
|
216
|
+
renderOptions = {},
|
|
170
217
|
) {
|
|
171
218
|
this.search = search
|
|
172
219
|
this.cfg = cfg
|
|
220
|
+
this.renderOptions = renderOptions
|
|
173
221
|
}
|
|
174
222
|
|
|
175
223
|
async maybeInject(
|
|
176
224
|
input ,
|
|
177
225
|
_decision ,
|
|
178
226
|
) {
|
|
179
|
-
|
|
227
|
+
const cfg = typeof this.cfg === 'function' ? this.cfg() : this.cfg
|
|
228
|
+
if (!cfg.enabled) return undefined
|
|
180
229
|
const query = pickQueryText(input.messages)
|
|
181
230
|
if (!query) return undefined
|
|
182
231
|
|
|
@@ -187,13 +236,62 @@ export class MemoryInjector {
|
|
|
187
236
|
return undefined // retrieval failure never breaks the agent loop
|
|
188
237
|
}
|
|
189
238
|
|
|
190
|
-
const
|
|
239
|
+
const options = typeof this.renderOptions === 'function' ? this.renderOptions() : this.renderOptions
|
|
240
|
+
const block = renderRecallBlock(hits, cfg, options)
|
|
191
241
|
if (!block || block.text === this.lastText) return undefined
|
|
192
242
|
this.lastText = block.text
|
|
193
243
|
|
|
194
244
|
return block.text
|
|
195
245
|
}
|
|
196
246
|
}
|
|
247
|
+
|
|
248
|
+
/** 从 agent 上取会话 id;取不到就没有"每个会话只发一次摘要"的锚点。 */
|
|
249
|
+
export function sessionIdOf(agent ) {
|
|
250
|
+
const id = (agent )?.session?.id
|
|
251
|
+
return typeof id === 'string' && id.length > 0 ? id : undefined
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 摘要注入最多记住多少个会话(一个进程里开过的会话上界,防止 Set 无限长)。 */
|
|
255
|
+
const MAX_DIGESTED_SESSIONS = 500
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 会话摘要注入器:一个会话只注入一次"已有哪些记忆"的摘要。
|
|
259
|
+
* 检索失败或结果为空也标记为已完成 —— 摘要不是必需品,不能每步重试。
|
|
260
|
+
*/
|
|
261
|
+
export class MemoryDigester {
|
|
262
|
+
done = new Set ()
|
|
263
|
+
list
|
|
264
|
+
|
|
265
|
+
constructor(
|
|
266
|
+
list ,
|
|
267
|
+
) {
|
|
268
|
+
this.list = list
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
async maybeDigest(
|
|
272
|
+
sessionId ,
|
|
273
|
+
scopes ,
|
|
274
|
+
render ,
|
|
275
|
+
) {
|
|
276
|
+
if (sessionId === undefined || this.done.has(sessionId)) return undefined
|
|
277
|
+
this.markDone(sessionId)
|
|
278
|
+
let records
|
|
279
|
+
try {
|
|
280
|
+
records = await this.list(scopes)
|
|
281
|
+
} catch {
|
|
282
|
+
return undefined
|
|
283
|
+
}
|
|
284
|
+
return render(records) ?? undefined
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
markDone(sessionId ) {
|
|
288
|
+
this.done.add(sessionId)
|
|
289
|
+
if (this.done.size > MAX_DIGESTED_SESSIONS) {
|
|
290
|
+
const oldest = this.done.values().next()
|
|
291
|
+
if (!oldest.done) this.done.delete(oldest.value)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
197
295
|
|
|
198
296
|
|
|
199
297
|
//# sourceURL=source/memory-inject/src/inject.ts
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「记忆使用策略」常驻段:告诉模型什么时候查、查到怎么用、查不到怎么办。
|
|
3
|
+
* 只写操作口径,不写具体记忆内容 —— 内容由摘要 / 召回 / 规则段负责。
|
|
4
|
+
*/
|
|
5
|
+
export const POLICY_TEXT = `## 长期记忆
|
|
6
|
+
|
|
7
|
+
本会话挂着一个本地记忆库,工具:memory_search / memory_list / memory_get / memory_save / memory_forget(可按会话、项目、全局等作用域读写)。
|
|
8
|
+
|
|
9
|
+
遇到以下情况先查记忆,不要凭猜测开始:
|
|
10
|
+
- 不确定这个项目以前怎么做、有没有既定约定、某个坑是否踩过;
|
|
11
|
+
- 用户的话里出现「上次 / 之前 / 还是那样」这类指代。
|
|
12
|
+
|
|
13
|
+
查到就直接复用,并说明依据来自记忆。记忆与当前代码或文件冲突时,以现场为准,更新过时的记忆并明确告诉用户哪些过时记忆已变更。
|
|
14
|
+
|
|
15
|
+
查不到时:
|
|
16
|
+
- 低风险、可回退的:按仓库现有风格推断着做,明确标出你的假设;
|
|
17
|
+
- 影响面大、不可逆、涉及外部系统 / 凭据 / 发布:先问用户,给出 2~3 个具体选项和你的推荐,不要只问「怎么办」。
|
|
18
|
+
|
|
19
|
+
本轮产生了可复用的结论(决策、踩坑、流程、口径)时,用 memory_save 记一条;写之前先 memory_search 去重。不要编造记忆,也不要把一次性细节记进去。`
|
|
20
|
+
|
|
21
|
+
//# sourceURL=source/memory-inject/src/policy.ts
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 硬性规则段:来自 kind='rule' 的记忆,进系统提示常驻段。
|
|
3
|
+
*
|
|
4
|
+
* 为什么放系统提示而不是每轮消息:规则要"一直在场",但每轮复制会膨胀并稀释
|
|
5
|
+
* 注意力;系统提示是每步都会看见的位置,且文本稳定时可以跟着前缀缓存。
|
|
6
|
+
* 只放"不可机械校验"的规则 —— 能写成检查的规则应该进钩子(代码强制)。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { estimateTokens } from '../provider/rerank.js'
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
const HEADER = '以下是必须遵守的硬性规则(来自 kind=rule 的长期记忆;除非用户明确要求破例,否则按它做):'
|
|
13
|
+
|
|
14
|
+
/** 渲染规则段。重要性优先,其次新的在前;每条截 240 字,超出预算截断。 */
|
|
15
|
+
export function renderRulesBlock(records , cfg ) {
|
|
16
|
+
if (records.length === 0) return null
|
|
17
|
+
const ordered = [...records].sort((a, b) => b.importance - a.importance || b.updatedAt - a.updatedAt || a.content.localeCompare(b.content))
|
|
18
|
+
let tokens = estimateTokens(HEADER) + 4
|
|
19
|
+
const lines = []
|
|
20
|
+
for (const record of ordered.slice(0, cfg.maxItems)) {
|
|
21
|
+
const line = `- ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
|
|
22
|
+
const cost = estimateTokens(line) + 1
|
|
23
|
+
if (tokens + cost > cfg.tokenBudget) break
|
|
24
|
+
lines.push(line)
|
|
25
|
+
tokens += cost
|
|
26
|
+
}
|
|
27
|
+
if (lines.length === 0) return null
|
|
28
|
+
return `${HEADER}\n${lines.join('\n')}`
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
//# sourceURL=source/memory-inject/src/rules.ts
|