@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.
@@ -5,6 +5,11 @@
5
5
  * 注意力;系统提示是每步都会看见的位置,且文本稳定时可以跟着前缀缓存。
6
6
  * 只放"不可机械校验"的规则 —— 能写成检查的规则应该进钩子(代码强制)。
7
7
  *
8
+ * 0.9.6 起:
9
+ * - 已被新规则 supersede 的旧规则不进入常驻段,保留历史用于 memory_get/search;
10
+ * - mandatory/pinned 标签的规则排在最前,超出预算时给出明确警告,不静默丢弃;
11
+ * - 任何因条数/预算未展示的规则都会在段尾报告数量,并写入审计。
12
+ *
8
13
  * 增量提醒(0.9.0 起):系统提示段每步都会按内存快照重渲染,但"规则是别的会话里
9
14
  * 新加/改过的"这件事只改文本、不产生任何对话消息;模型在旧会话里继续聊时未必会
10
15
  * 重新读一遍系统提示,而且规则段有 token 预算,新规则可能被旧规则挤出常驻段。
@@ -14,6 +19,7 @@
14
19
 
15
20
  import { estimateTokens } from '../provider/rerank.js'
16
21
 
22
+ import { supersededIds } from './digest.js'
17
23
 
18
24
  export const RULES_HEADER =
19
25
  '以下是必须遵守的硬性规则(来自 kind=rule 的长期记忆;除非用户明确要求破例,否则按它做):'
@@ -21,6 +27,16 @@ export const RULES_HEADER =
21
27
  export const RULES_DELTA_HEADER =
22
28
  '以下是新增或变更的硬性规则(来自 kind=rule 的长期记忆;从现在起按它做):'
23
29
 
30
+ /** mandatory/pinned 是显式的标签约定,不把全部 kind=rule 自动升级。 */
31
+ const MANDATORY_TAGS = new Set(['mandatory', 'pinned', '必含', '强制'])
32
+
33
+ export function isMandatoryRule(record ) {
34
+ return (record.tags ?? []).some((tag) => {
35
+ const value = String(tag).trim().toLowerCase()
36
+ return MANDATORY_TAGS.has(value) || value.startsWith('mandatory:') || value.startsWith('pinned:')
37
+ })
38
+ }
39
+
24
40
  /**
25
41
  * 一条规则的渲染行。常驻段与增量块共用同一个格式 —— 增量靠"逐行比对"判断
26
42
  * 会话是否已经见过某条规则,两边只要有一个字符不同就会重复提醒。
@@ -29,41 +45,150 @@ export function ruleLine(record ) {
29
45
  return `- ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
30
46
  }
31
47
 
32
- /** 规则排序:重要度优先,其次新的在前,最后按内容稳定排序(两个实例结果一致)。 */
48
+ /** 规则排序:mandatory 优先,其次重要度、新的在前,最后按内容稳定排序。 */
33
49
  export function orderRules(records ) {
34
50
  return [...records].sort(
35
51
  (a, b) =>
52
+ Number(isMandatoryRule(b)) - Number(isMandatoryRule(a)) ||
36
53
  b.importance - a.importance ||
37
54
  b.updatedAt - a.updatedAt ||
38
55
  a.content.localeCompare(b.content),
39
56
  )
40
57
  }
41
58
 
42
- function renderLines(records , header , cfg , budget ) {
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+
71
+
72
+
73
+
74
+
75
+
76
+
77
+
78
+
79
+ function renderLines(
80
+ records ,
81
+ header ,
82
+ cfg ,
83
+ budget ,
84
+ ) {
85
+ const retired = supersededIds(records)
86
+ const active = []
87
+ let omittedSuperseded = 0
88
+ for (const record of records) {
89
+ if (retired.has(record.id)) { omittedSuperseded += 1; continue }
90
+ active.push(record)
91
+ }
92
+
43
93
  let tokens = estimateTokens(header) + 4
44
94
  const lines = []
45
- for (const record of orderRules(records).slice(0, cfg.maxItems)) {
95
+ let omittedTopK = 0
96
+ let omittedBudget = 0
97
+ let budgetExhausted = false
98
+ let mandatoryInjected = 0
99
+ let mandatoryOmitted = 0
100
+ const mandatoryTotal = active.filter(isMandatoryRule).length
101
+
102
+ for (const [index, record] of orderRules(active).entries()) {
103
+ const mandatory = isMandatoryRule(record)
104
+ if (index >= cfg.maxItems) {
105
+ omittedTopK += 1
106
+ if (mandatory) mandatoryOmitted += 1
107
+ continue
108
+ }
109
+ if (budgetExhausted) {
110
+ omittedBudget += 1
111
+ if (mandatory) mandatoryOmitted += 1
112
+ continue
113
+ }
46
114
  const line = ruleLine(record)
47
115
  const cost = estimateTokens(line) + 1
48
- if (tokens + cost > budget) break
116
+ if (tokens + cost > budget) {
117
+ budgetExhausted = true
118
+ omittedBudget += 1
119
+ if (mandatory) mandatoryOmitted += 1
120
+ continue
121
+ }
49
122
  lines.push(line)
50
123
  tokens += cost
124
+ if (mandatory) mandatoryInjected += 1
125
+ }
126
+
127
+ if (lines.length === 0 && active.length === 0) {
128
+ return {
129
+ text: '', tokens: 0, count: 0,
130
+ stats: {
131
+ candidates: records.length, active: 0, injected: 0,
132
+ omittedTopK, omittedBudget, omittedSuperseded,
133
+ mandatory: 0, mandatoryInjected: 0, mandatoryOmitted: 0, truncated: omittedSuperseded > 0,
134
+ },
135
+ }
136
+ }
137
+ // 一条都装不下且不是 mandatory 溢出的情况:文本为空,但统计仍保留给审计。
138
+ // 系统提示的调用方(renderRulesBlock)会把空文本转成 null,保持旧行为。
139
+
140
+ const notes = []
141
+ const noBody = lines.length === 0 && mandatoryOmitted === 0
142
+ const omitted = omittedTopK + omittedBudget
143
+ if (!noBody && omitted > 0) {
144
+ const parts = []
145
+ if (omittedTopK > 0) parts.push(`条数上限 ${omittedTopK}`)
146
+ if (omittedBudget > 0) parts.push(`预算 ${omittedBudget}`)
147
+ notes.push(`(另有 ${omitted} 条规则未展示:${parts.join(' / ')};需要时用 memory_search 查 kind=rule)`)
148
+ }
149
+ if (!noBody && mandatoryOmitted > 0) {
150
+ notes.push(`(警告:${mandatoryOmitted} 条 mandatory / pinned 规则未展示,当前规则不完整)`)
151
+ }
152
+ const text = [lines.length > 0 ? `${header}\n${lines.join('\n')}` : '', ...notes].filter(Boolean).join('\n')
153
+ const extraTokens = notes.reduce((sum, note) => sum + estimateTokens(note) + 1, 0)
154
+
155
+ return {
156
+ text,
157
+ tokens: tokens + extraTokens,
158
+ count: lines.length,
159
+ stats: {
160
+ candidates: records.length,
161
+ active: active.length,
162
+ injected: lines.length,
163
+ omittedTopK,
164
+ omittedBudget,
165
+ omittedSuperseded,
166
+ mandatory: mandatoryTotal,
167
+ mandatoryInjected,
168
+ mandatoryOmitted,
169
+ truncated: omitted > 0,
170
+ },
51
171
  }
52
- if (lines.length === 0) return null
53
- return `${header}\n${lines.join('\n')}`
54
172
  }
55
173
 
56
- /** 渲染规则段(系统提示常驻)。重要性优先,新的在前;每条截 240 字,超出预算截断。 */
57
- export function renderRulesBlock(records , cfg ) {
174
+ /** 渲染规则段(系统提示常驻)及其审计统计。没有可展示的规则时 text 为空串。 */
175
+ export function renderRules(records , cfg ) {
58
176
  return renderLines(records, RULES_HEADER, cfg, cfg.tokenBudget)
59
177
  }
60
178
 
179
+ /** 渲染规则段(系统提示常驻),只要文本;空文本返回 null。 */
180
+ export function renderRulesBlock(records , cfg ) {
181
+ const text = renderRules(records, cfg).text
182
+ return text === '' ? null : text
183
+ }
184
+
61
185
  /**
62
186
  * 渲染"新增/变更的规则"块。预算比常驻段留宽一点:增量块本来就是常驻段装不下
63
187
  * 时才需要的补充,用同一个 300 token 的上限容易把最该提醒的一条又截掉。
64
188
  */
65
189
  export function renderRulesDeltaBlock(records , cfg ) {
66
- return renderLines(records, RULES_DELTA_HEADER, cfg, Math.max(cfg.tokenBudget, 600))
190
+ const text = renderLines(records, RULES_DELTA_HEADER, cfg, Math.max(cfg.tokenBudget, 600)).text
191
+ return text === '' ? null : text
67
192
  }
68
193
 
69
194
  /** 模型可见历史里的一小部分形状(只读;不依赖宿主的 Message 类型)。 */
@@ -0,0 +1,396 @@
1
+ /**
2
+ * 行为信号 → 自动召回查询。
3
+ *
4
+ * 只消费宿主**公开**的可观测信号:
5
+ * - session/event 的 `tool/call`(name + arguments,含工具自带的 description)
6
+ * - session/event 的 `tool/result`(error / message.isError)
7
+ * - compaction 事件(上下文重建)
8
+ *
9
+ * “模式”就是一组标签(release / deploy / database / credentials ...),
10
+ * 由设置提供、来自记忆里实际使用的标签;工具名/description/参数命中任一标签
11
+ * 就触发一次定向召回。失败调用始终触发,并优先用 description 作为查询。
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
+                      
39
+
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+ const DEFAULT_MAX_QUERY = 240
51
+
52
+ const RELEASE_TAGS = new Set(['release', 'publish', 'push', '发布', '推送'])
53
+ const DEPLOY_TAGS = new Set([
54
+ 'deploy', 'deployment', 'rollback', 'restore', 'backup',
55
+ 'database', 'migration', 'migrate', 'schema', 'production', 'prod',
56
+ '部署', '回滚', '恢复', '备份', '数据库', '迁移', '生产',
57
+ ])
58
+ const SPECIFIC_TAGS = new Set([
59
+ 'database', 'migration', 'migrate', 'schema', 'credentials', 'credential',
60
+ 'auth', 'token', 'secret', 'permission', 'security', 'destructive', 'drop', 'truncate',
61
+ '数据库', '迁移', '凭据', '认证', '权限', '安全', '删除', '清空',
62
+ ])
63
+
64
+ function truncate(value , max ) {
65
+ const limit = Math.max(20, max ?? DEFAULT_MAX_QUERY)
66
+ return value.replace(/\s+/g, ' ').trim().slice(0, limit)
67
+ }
68
+
69
+ /** 中英标签的最小同义词表:记忆标签常是英文,Agent 文本常是中文。 */
70
+ const TAG_ALIASES = {
71
+ release: ['发布'],
72
+ publish: ['发布', '推送'],
73
+ deploy: ['部署'],
74
+ deployment: ['部署'],
75
+ database: ['数据库'],
76
+ migration: ['迁移'],
77
+ migrate: ['迁移'],
78
+ schema: ['结构', '迁移'],
79
+ credentials: ['凭据'],
80
+ credential: ['凭据'],
81
+ auth: ['认证'],
82
+ permission: ['权限'],
83
+ security: ['安全'],
84
+ destructive: ['删除', '清空'],
85
+ delete: ['删除'],
86
+ drop: ['删除'],
87
+ truncate: ['清空'],
88
+ backup: ['备份'],
89
+ restore: ['恢复'],
90
+ rollback: ['回滚'],
91
+ install: ['安装'],
92
+ upgrade: ['升级'],
93
+ production: ['生产'],
94
+ server: ['服务器'],
95
+ network: ['网络'],
96
+ }
97
+
98
+ /** 标签及其同义词(双向:英文标签匹配中文文本,中文标签也匹配英文文本)。 */
99
+ function aliasesFor(tag ) {
100
+ const needle = tag.trim().toLowerCase()
101
+ const out = new Set ([needle])
102
+ for (const alias of TAG_ALIASES[needle] ?? []) out.add(alias.toLowerCase())
103
+ for (const [key, aliases] of Object.entries(TAG_ALIASES)) {
104
+ if (aliases.some((alias) => alias.toLowerCase() === needle)) out.add(key)
105
+ }
106
+ return [...out]
107
+ }
108
+
109
+ /** 标签是否出现在文本里。ASCII 标签按词边界匹配并容忍复数 s;中文按子串。 */
110
+ export function textHasTag(text , tag ) {
111
+ const haystack = text.toLowerCase()
112
+ for (const needle of aliasesFor(tag)) {
113
+ if (needle === '') continue
114
+ if (/^[a-z0-9][a-z0-9_-]*$/.test(needle)) {
115
+ const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
116
+ if (new RegExp(`(^|[^a-z0-9_])${escaped}s?(?=$|[^a-z0-9_])`).test(haystack)) return true
117
+ } else if (haystack.includes(needle)) {
118
+ return true
119
+ }
120
+ }
121
+ return false
122
+ }
123
+
124
+ /**
125
+ * 工具参数里的 description。很多工具(ops_bash / workflow / run_code 等)要求
126
+ * 模型写一句 "这个命令在干什么",它比命令本身更适合做记忆检索查询。
127
+ * 解析失败或没有该字段时返回 undefined。
128
+ */
129
+ export function toolCallDescription(argumentsText ) {
130
+ let value = argumentsText
131
+ if (typeof argumentsText === 'string') {
132
+ const text = argumentsText.trim()
133
+ if (text === '') return undefined
134
+ try { value = JSON.parse(text) } catch { return undefined }
135
+ }
136
+ if (!value || typeof value !== 'object') return undefined
137
+ const description = (value ).description
138
+ if (typeof description !== 'string') return undefined
139
+ const trimmed = description.replace(/\s+/g, ' ').trim()
140
+ return trimmed === '' ? undefined : trimmed
141
+ }
142
+
143
+ /** 稳定短 hash:让不同失败描述各自触发一次召回,又不在状态里保存原文。 */
144
+ function hashKey(value ) {
145
+ let hash = 2166136261
146
+ for (let i = 0; i < value.length; i++) {
147
+ hash ^= value.charCodeAt(i)
148
+ hash = Math.imul(hash, 16777619)
149
+ }
150
+ return (hash >>> 0).toString(36)
151
+ }
152
+
153
+ /** 从用户可见文本推断任务阶段;不确定就返回 unknown,不伪造。 */
154
+ export function detectPhase(text ) {
155
+ const value = String(text ?? '').toLowerCase()
156
+ if (/(?:npm|pnpm|yarn)\s+(?:publish|stage)|git\s+push|\brelease\b|\bpublish\b|发布|推送/.test(value)) return 'release'
157
+ if (/(?:deploy|rollout|kubectl|terraform\s+apply|部署)/.test(value)) return 'deploy'
158
+ if (/(?:implement|refactor|fix|add)\b|开发|实现|修复|新增|重构|添加/.test(value)) return 'development'
159
+ return 'unknown'
160
+ }
161
+
162
+ function phaseForTag(tag , fallback ) {
163
+ const value = tag.toLowerCase()
164
+ if (RELEASE_TAGS.has(value)) return 'release'
165
+ if (DEPLOY_TAGS.has(value)) return 'deploy'
166
+ return fallback
167
+ }
168
+
169
+ /** 同一段文本命中多个标签时,优先保留更具体的语义(release > database > deploy > 普通)。 */
170
+ function tagPriority(tag ) {
171
+ const value = tag.toLowerCase()
172
+ if (RELEASE_TAGS.has(value)) return 4
173
+ if (SPECIFIC_TAGS.has(value)) return 3
174
+ if (DEPLOY_TAGS.has(value)) return 2
175
+ return 1
176
+ }
177
+
178
+ /**
179
+ * 工具名 + description + 参数是否命中某个可配置触发标签。
180
+ * 命中后用 description(若开启)或标签本身作为检索查询。
181
+ */
182
+ export function highRiskSignal(tool , argumentsText , options = {}) {
183
+ const tags = options.tags ?? []
184
+ const description = options.useToolDescription === false ? undefined : options.description
185
+ const haystack = `${tool} ${description ?? ''} ${argumentsText}`
186
+ const ordered = [...tags]
187
+ .map((tag, index) => ({ tag, index, priority: tagPriority(tag) }))
188
+ .sort((a, b) => b.priority - a.priority || a.index - b.index)
189
+ for (const { tag } of ordered) {
190
+ if (!textHasTag(haystack, tag)) continue
191
+ return {
192
+ key: `auto-tag:${tag.toLowerCase()}`,
193
+ reason: 'before_high_risk_tool',
194
+ query: truncate(description ?? tag, options.maxQueryChars),
195
+ phase: phaseForTag(tag, 'unknown'),
196
+ tool,
197
+ tag,
198
+ source: 'tool',
199
+ }
200
+ }
201
+ return undefined
202
+ }
203
+
204
+ /**
205
+ * 任意可见文本(assistant 输出、todo、命令、goal)命中记忆标签时的召回信号。
206
+ * 查询 = 标签 + 命中位置附近的一小段文本,既保留标签的精确性,也给检索一点上下文。
207
+ */
208
+ export function textTagSignal(
209
+ text ,
210
+ options = {},
211
+ ) {
212
+ const tags = options.tags ?? []
213
+ const body = String(text ?? '').replace(/\s+/g, ' ').trim()
214
+ if (body === '') return undefined
215
+ const ordered = [...tags]
216
+ .map((tag, index) => ({ tag, index, priority: tagPriority(tag) }))
217
+ .sort((a, b) => b.priority - a.priority || a.index - b.index)
218
+ for (const { tag } of ordered) {
219
+ if (!textHasTag(body, tag)) continue
220
+ const lower = body.toLowerCase()
221
+ const at = lower.indexOf(tag.toLowerCase())
222
+ const start = Math.max(0, at - 80)
223
+ const snippet = body.slice(start, Math.min(body.length, at + tag.length + 120))
224
+ const source = options.source ?? 'text'
225
+ return {
226
+ key: `text-tag:${source}:${tag.toLowerCase()}`,
227
+ reason: 'text_tag_match',
228
+ query: truncate(`${tag} ${snippet}`, options.maxQueryChars),
229
+ phase: phaseForTag(tag, 'unknown'),
230
+ tag,
231
+ source,
232
+ }
233
+ }
234
+ return undefined
235
+ }
236
+
237
+ /** 从 assistant message 的 content 里取**可见文本**块;不读 reasoning / 隐藏 CoT。 */
238
+ export function visibleTextContent(content ) {
239
+ if (!Array.isArray(content)) return ''
240
+ return content
241
+ .filter((block) => block && typeof block === 'object'
242
+ && (block ).type === 'text'
243
+ && typeof (block ).text === 'string')
244
+ .map((block) => (block ).text)
245
+ .join('\n')
246
+ .trim()
247
+ }
248
+
249
+ /** `assistant/message` 的可见文本。 */
250
+ export function assistantVisibleText(event ) {
251
+ const data = (event )?.data
252
+ const message = data?.message
253
+ const text = visibleTextContent(message?.content)
254
+ return text === '' ? undefined : text
255
+ }
256
+
257
+ /** `todo/write` 的任务清单文本。 */
258
+ export function todoText(event ) {
259
+ const data = (event )?.data
260
+ const todos = data?.todos
261
+ if (!Array.isArray(todos)) return undefined
262
+ const text = todos
263
+ .map((todo) => (todo && typeof todo === 'object' ? (todo ).content : undefined))
264
+ .filter((content) => typeof content === 'string' && content.trim() !== '')
265
+ .join('\n')
266
+ .trim()
267
+ return text === '' ? undefined : text
268
+ }
269
+
270
+ /** `command/run` 的命令名与参数。 */
271
+ export function commandText(event ) {
272
+ const data = (event )?.data
273
+ const name = typeof data?.name === 'string' ? data.name : ''
274
+ const args = typeof data?.args === 'string' ? data.args : ''
275
+ const text = `${name} ${args}`.trim()
276
+ return text === '' ? undefined : text
277
+ }
278
+
279
+ /** `goal/change` 的目标文本(只取明确的 objective/title/description)。 */
280
+ export function goalText(event ) {
281
+ const data = (event )?.data
282
+ const goal = data?.goal
283
+ if (!goal || typeof goal !== 'object') return undefined
284
+ const values = [goal.objective, goal.title, goal.description]
285
+ .filter((value) => typeof value === 'string' && value.trim() !== '')
286
+ return values.length > 0 ? values.join('\n') : undefined
287
+ }
288
+
289
+ /**
290
+ * 工具失败分类。失败时**优先用工具调用自己的 description** 做检索查询;
291
+ * 没有 description 才退回错误类别关键词。只根据 code/消息里的类别词判断,
292
+ * 不保存原始消息。
293
+ */
294
+ export function failureSignal(
295
+ tool ,
296
+ code ,
297
+ message ,
298
+ options = {},
299
+ ) {
300
+ const haystack = `${code ?? ''} ${message ?? ''}`.toLowerCase()
301
+ let errorClass = 'TOOL_FAILED'
302
+ let fallbackQuery = `failure diagnostics ${tool ?? 'tool'}`
303
+ let phase = 'unknown'
304
+ if (/credential|missing.*token|no.*token|unauthori[sz]ed|e401|401|auth(?:entication)?\s+required/.test(haystack)) {
305
+ errorClass = 'MISSING_CREDENTIAL'
306
+ fallbackQuery = 'credentials npm publish devcred token missing'
307
+ phase = 'release'
308
+ } else if (/permission|denied|forbidden|e403|403|eacces|eperm/.test(haystack)) {
309
+ errorClass = 'PERMISSION_DENIED'
310
+ fallbackQuery = 'permission denied sandbox approval credentials'
311
+ } else if (/timeout|timed\s*out|etimedout/.test(haystack)) {
312
+ errorClass = 'TIMEOUT'
313
+ fallbackQuery = 'timeout retry long running command'
314
+ } else if (/abort|cancel|interrupt/.test(haystack)) {
315
+ errorClass = 'ABORTED_UNKNOWN'
316
+ fallbackQuery = 'aborted command diagnosis retry'
317
+ }
318
+
319
+ const description = options.description?.replace(/\s+/g, ' ').trim()
320
+ const extra = errorClass === 'MISSING_CREDENTIAL' ? 'credentials token auth'
321
+ : errorClass === 'PERMISSION_DENIED' ? 'permission sandbox approval'
322
+ : errorClass === 'TIMEOUT' ? 'timeout retry'
323
+ : errorClass === 'ABORTED_UNKNOWN' ? 'aborted retry diagnosis'
324
+ : 'failure diagnostics'
325
+ const query = truncate(description !== undefined && description !== ''
326
+ ? `${description} ${extra}`
327
+ : fallbackQuery, options.maxQueryChars)
328
+ const key = `tool-failure:${tool ?? 'unknown'}:${errorClass}:${hashKey(description ?? message ?? '')}`
329
+ return {
330
+ key,
331
+ reason: 'tool_failure',
332
+ query,
333
+ phase,
334
+ ...(tool !== undefined ? { tool } : {}),
335
+ errorClass,
336
+ source: 'failure',
337
+ }
338
+ }
339
+
340
+ /** 从一个 tool/result 事件里取错误信息(已做防御性读取)。 */
341
+ export function toolResultFailure(event ) {
342
+ const data = (event )?.data
343
+ const error = data?.error
344
+ const message = data?.message
345
+ const text = Array.isArray(message?.content)
346
+ ? message.content.filter((block) => block?.type === 'text' && typeof block.text === 'string').map((block) => block.text ).join(' ')
347
+ : ''
348
+ const code = typeof error?.code === 'string'
349
+ ? error.code
350
+ : typeof error?.name === 'string' ? error.name : undefined
351
+ return {
352
+ ...(code !== undefined ? { code } : {}),
353
+ ...(text !== '' ? { message: text.slice(0, 240) } : {}),
354
+ isError: message?.isError === true || error !== undefined,
355
+ }
356
+ }
357
+
358
+ /**
359
+ * 每个会话只保留**最新一条未消费**的信号;相同 key 不重复排队。
360
+ * `take()` 消费后保留 lastKey,同一失败不会因为重复事件反复搜索。
361
+ */
362
+ export class BehaviorSignalStore {
363
+ bySession = new Map ()
364
+
365
+ note(sessionId , signal ) {
366
+ if (sessionId === undefined) return false
367
+ const key = sessionId
368
+ const state = this.bySession.get(key) ?? { lastKey: '' }
369
+ if (signal.key === state.lastKey) return false
370
+ state.pending = signal
371
+ state.lastKey = signal.key
372
+ this.bySession.set(key, state)
373
+ if (this.bySession.size > 500) {
374
+ const oldest = this.bySession.keys().next()
375
+ if (!oldest.done) this.bySession.delete(oldest.value)
376
+ }
377
+ return true
378
+ }
379
+
380
+ take(sessionId ) {
381
+ if (sessionId === undefined) return undefined
382
+ const state = this.bySession.get(sessionId)
383
+ if (state?.pending === undefined) return undefined
384
+ const signal = state.pending
385
+ state.pending = undefined
386
+ return signal
387
+ }
388
+
389
+ clear(sessionId ) {
390
+ if (sessionId === undefined) return
391
+ this.bySession.delete(sessionId)
392
+ }
393
+ }
394
+
395
+
396
+ //# sourceURL=source/memory-inject/src/signals.ts