@restregular/dsh-memory 0.20.0 → 0.21.0

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.
@@ -182,6 +182,34 @@ export function apply(ctx , config = {}) {
182
182
 
183
183
  /** 会话级注入状态(正文/标签/版本)与审计。 */
184
184
  const injectionState = new InjectionState()
185
+ /**
186
+ * 给工具半边用的会话上下文去重视图(0.21.0)。
187
+ *
188
+ * memory_search / memory_list 返回的摘要也属于“条目已进入上下文”:同一条记忆
189
+ * 同版本再次命中时只回 id,正文仍由 memory_get 显式取。状态只有一份(注入半边
190
+ * 的 InjectionState),工具侧通过 ctx.get('memoryContextDedup') 惰性读取 ——
191
+ * 拿不到(注入半边被禁用/旧版本)就自然退化为不去重。
192
+ *
193
+ * 用 ctx.provide 而不是把方法挂到 memory 服务上:provider 不需要知道去重实现,
194
+ * 工具半边也不需要依赖注入半边的内部类。
195
+ */
196
+ try {
197
+ ctx.provide('memoryContextDedup', {
198
+ /** 这批记录里哪些已经以同版本进过上下文(摘要或正文)。 */
199
+ seen(sessionId , records ) {
200
+ return injectionState.seenInContext(sessionId, records)
201
+ },
202
+ /** memory_search 返回了摘要 / memory_list 返回了正文。 */
203
+ markSummary(sessionId , records ) {
204
+ injectionState.markSummary(sessionId, records)
205
+ },
206
+ markContent(sessionId , records ) {
207
+ injectionState.markContent(sessionId, records)
208
+ },
209
+ })
210
+ } catch (error) {
211
+ console.warn(`[dsh-memory] 会话上下文去重服务未能注册(工具将不去重): ${error instanceof Error ? error.message : String(error)}`)
212
+ }
185
213
  const audit = new InjectAuditStore()
186
214
  const signals = new BehaviorSignalStore()
187
215
  const callMeta = new Map ()
@@ -8,6 +8,8 @@ export const POLICY_TEXT = `## 记忆系统
8
8
 
9
9
  memory_search 只返回印象(ID、作用域、类型、标签和少量摘要);判断相关后再用 memory_get(ids, fields) 取正文。fields 省略 = content + scope + kind + tags;只要摘要用 ["summary"],只要正文用 ["content"],需要重要度 / 时间 / 触发词等再显式加上对应字段。
10
10
 
11
+ 同一会话里已经出现过的记忆,memory_search / memory_list 只回 ID 并注明“摘要因上下文去重被省略”;那不是没找到,需要正文时直接用 memory_get 取。
12
+
11
13
  遇到以下情况先查记忆,不要凭猜测开始:
12
14
  - 不确定这个项目以前怎么做、有没有既定约定、某个坑是否踩过;
13
15
  - 用户的话里出现「上次 / 之前 / 还是那样」这类指代。
@@ -13,7 +13,7 @@
13
13
  * 行格式(短键,减小体积):
14
14
  * 快照 {"v":1,"d":1,"e":[["id",2,version,at],...]}
15
15
  * 增量 {"d":1,"e":[...]}
16
- * status: 1=hint_injected, 2=content_injected; d=1 表示本会话摘要已做过
16
+ * status: 1=hint_injected, 2=content_injected, 3=summary_injected; d=1 表示本会话摘要已做过
17
17
  *
18
18
  * 只存记录 id / 状态 / 版本 / 时间戳与摘要标记,不落正文,也不落 lastQuery
19
19
  * (查询可能含凭据)。
@@ -29,10 +29,12 @@ import { createHash } from 'node:crypto'
29
29
  const STATUS_CODE = {
30
30
  hint_injected: 1,
31
31
  content_injected: 2,
32
+ summary_injected: 3,
32
33
  }
33
34
  const STATUS_BY_CODE = {
34
35
  1: 'hint_injected',
35
36
  2: 'content_injected',
37
+ 3: 'summary_injected',
36
38
  }
37
39
  const SNAPSHOT_VERSION = 1
38
40
  const DEFAULT_DEBOUNCE_MS = 250
@@ -5,17 +5,21 @@
5
5
  * "正文已注入"与"只给了标签"。这里按 sessionId 保存:
6
6
  * - not_seen → 没有任何记录(默认)
7
7
  * - hint_injected → 只进过截断标签索引,正文仍未加载
8
+ * - summary_injected→ 记忆摘要(memory_search / memory_list 的短摘要)已进入上下文
8
9
  * - content_injected→ 正文已进入当前上下文
9
10
  *
10
11
  * 版本 = record.updatedAt。内容更新后允许重新注入;上下文重建(压缩/新会话)
11
12
  * 由调用方 clear(),绝不用"历史上出现过"代替"当前仍在上下文里"。
12
13
  *
14
+ * 0.21.0 加 summary_injected:memory_search / memory_list 返回过的摘要也算
15
+ * "条目已出现",再次命中同版本时只回 id(见 memoryContextDedup 服务)。
16
+ *
13
17
  * 0.17.0 起可挂一个按会话的持久化 store(见 session-state-store.ts):状态在
14
18
  * 插件重载 / 宿主重启后仍能恢复;读盘只在第一次接触该会话时发生,写入由 store
15
19
  * 自己做合并与阈值 compact。
16
20
  */
17
21
 
18
-
22
+
19
23
 
20
24
 
21
25
 
@@ -28,6 +32,7 @@
28
32
 
29
33
 
30
34
 
35
+
31
36
 
32
37
 
33
38
 
@@ -160,7 +165,8 @@ export class InjectionState {
160
165
  const changed = []
161
166
  for (const record of records) {
162
167
  const previous = state.entries.get(record.id)
163
- if (previous?.status === 'content_injected') continue
168
+ // 标签是比摘要/正文更弱的证据:已经进过摘要或正文时不能往回降级。
169
+ if (previous?.status === 'content_injected' || previous?.status === 'summary_injected') continue
164
170
  const entry = { status: 'hint_injected' , version: record.updatedAt, at: now }
165
171
  state.entries.set(record.id, entry)
166
172
  changed.push({ id: record.id, ...entry })
@@ -169,6 +175,26 @@ export class InjectionState {
169
175
  this.trim(state, sessionId)
170
176
  }
171
177
 
178
+ /**
179
+ * 记录"摘要已进入上下文"(memory_search / memory_list 返回过的条目)。
180
+ * 同版本的正文已注入时不降级:正文比摘要更强。
181
+ */
182
+ markSummary(sessionId , records ) {
183
+ const state = this.stateOf(sessionId)
184
+ const now = Date.now()
185
+ const changed = []
186
+ for (const record of records) {
187
+ const previous = state.entries.get(record.id)
188
+ if (previous?.status === 'content_injected' && previous.version === record.updatedAt) continue
189
+ if (previous?.status === 'summary_injected' && previous.version === record.updatedAt) continue
190
+ const entry = { status: 'summary_injected' , version: record.updatedAt, at: now }
191
+ state.entries.set(record.id, entry)
192
+ changed.push({ id: record.id, ...entry })
193
+ }
194
+ if (changed.length > 0) this.storeOf(sessionId)?.append(changed)
195
+ this.trim(state, sessionId)
196
+ }
197
+
172
198
  /** 记录"正文已注入"(hint 状态被正文覆盖)。 */
173
199
  markContent(sessionId , records ) {
174
200
  const state = this.stateOf(sessionId)
@@ -207,6 +233,27 @@ export class InjectionState {
207
233
  return { fresh, deduplicated, updated }
208
234
  }
209
235
 
236
+ /**
237
+ * 从工具结果去重的角度:这批记录里哪些已经以同版本进入过上下文。
238
+ *
239
+ * 只认摘要 / 正文(content_injected、summary_injected)——标签索引只给了
240
+ * id + tags,不包含摘要,所以 hint_injected 不算“摘要已出现”。
241
+ * 版本(updatedAt)变了等于内容变了,允许重新返回摘要。
242
+ */
243
+ seenInContext(
244
+ sessionId ,
245
+ records ,
246
+ ) {
247
+ const state = this.stateOf(sessionId)
248
+ const seen = new Set ()
249
+ for (const record of records) {
250
+ const entry = state.entries.get(record.id)
251
+ if (entry === undefined || entry.version !== record.updatedAt) continue
252
+ if (entry.status === 'content_injected' || entry.status === 'summary_injected') seen.add(record.id)
253
+ }
254
+ return seen
255
+ }
256
+
210
257
  /** 同一上下文里是否已经注入过同一段文本(最后一道按内容幂等)。 */
211
258
  lastTextOf(sessionId ) {
212
259
  return this.stateOf(sessionId).lastText
@@ -260,12 +307,13 @@ export class InjectionState {
260
307
  snapshot(sessionId ) {
261
308
  const state = this.sessions.get(sessionId)
262
309
  if (state === undefined) {
263
- return { sessionId, hintCount: 0, contentCount: 0, lastText: '', lastQuery: '', entries: [] }
310
+ return { sessionId, hintCount: 0, summaryCount: 0, contentCount: 0, lastText: '', lastQuery: '', entries: [] }
264
311
  }
265
312
  const entries = [...state.entries.entries()].map(([id, entry]) => ({ id, ...entry }))
266
313
  return {
267
314
  sessionId,
268
315
  hintCount: entries.filter((entry) => entry.status === 'hint_injected').length,
316
+ summaryCount: entries.filter((entry) => entry.status === 'summary_injected').length,
269
317
  contentCount: entries.filter((entry) => entry.status === 'content_injected').length,
270
318
  lastText: state.lastText,
271
319
  lastQuery: state.lastQuery,
package/lib/panel.js CHANGED
@@ -683,7 +683,15 @@ async function handle(ctx, routePath, req, res) {
683
683
  if (id === '') throw new ApiError(400, 'APPROVAL_ID_REQUIRED', 'id 不能为空')
684
684
  const outcome = body?.outcome === 'allowed-once' ? 'allowed-once' : body?.outcome === 'rejected' ? 'rejected' : ''
685
685
  if (outcome === '') throw new ApiError(400, 'APPROVAL_OUTCOME_INVALID', 'outcome 必须是 allowed-once 或 rejected')
686
- const answered = memory.answerVisibilityApproval(id, outcome)
686
+ // 0.21.0:逐条允许。省略 = 全部允许;空数组 = 一条都不允许(按拒绝处理)。
687
+ const rawIds = body?.allowedIds
688
+ if (rawIds !== undefined && rawIds !== null && !Array.isArray(rawIds)) {
689
+ throw new ApiError(400, 'APPROVAL_IDS_INVALID', 'allowedIds 必须是字符串数组')
690
+ }
691
+ const allowedIds = Array.isArray(rawIds) ? rawIds.filter((value) => typeof value === 'string' && value !== '') : undefined
692
+ const answered = allowedIds === undefined
693
+ ? memory.answerVisibilityApproval(id, outcome)
694
+ : memory.answerVisibilityApproval(id, outcome, allowedIds)
687
695
  writeJson(res, { ok: true, value: { answered } })
688
696
  return
689
697
  }
@@ -293,9 +293,9 @@ export class CordisMemoryService extends Service {
293
293
  return this.impl.pendingVisibilityApprovals(sessionId)
294
294
  }
295
295
 
296
- /** 面板:回答一条待审批。 */
297
- answerVisibilityApproval(id , outcome ) {
298
- return this.impl.answerVisibilityApproval(id, outcome)
296
+ /** 面板:回答一条待审批(可带逐条勾选的 allowedIds)。 */
297
+ answerVisibilityApproval(id , outcome , allowedIds ) {
298
+ return this.impl.answerVisibilityApproval(id, outcome, allowedIds)
299
299
  }
300
300
 
301
301
  /** 写路径默认 scope(省略 scope 时落到哪)。 */
@@ -548,8 +548,20 @@ export function resolveConfig(config = {}) {
548
548
 
549
549
 
550
550
 
551
+ /** 一次审批的结局:允许(可只允许其中几条) / 拒绝 / 超时。 */
552
+
553
+
554
+ /**
555
+ * 审批结论(0.21.0)。`allowedIds` 省略 = 本次请求的所有条目都允许;
556
+ * 用户在审批卡里逐条勾选时只带被勾选的条目 id。
557
+ */
558
+
559
+
560
+
561
+
562
+
551
563
 
552
-
564
+
553
565
 
554
566
 
555
567
 
@@ -1646,25 +1658,25 @@ export class LocalMemoryService {
1646
1658
 
1647
1659
 
1648
1660
  ,
1649
- ) {
1650
- if (input.items.length === 0) return Promise.resolve('allowed-once')
1651
- if (input.signal?.aborted) return Promise.resolve('rejected')
1661
+ ) {
1662
+ if (input.items.length === 0) return Promise.resolve({ outcome: 'allowed-once' })
1663
+ if (input.signal?.aborted) return Promise.resolve({ outcome: 'rejected' })
1652
1664
  const sessionId = this.rawSessionIdOf(agent) ?? ''
1653
1665
  const id = `vis-${Date.now().toString(36)}-${++this.approvalSeq}`
1654
1666
  const createdAt = Date.now()
1655
1667
  const expiresAt = createdAt + VISIBILITY_APPROVAL_TTL_MS
1656
1668
  return new Promise((resolve) => {
1657
1669
  let timer
1658
- const onAbort = () => finish('rejected')
1659
- const finish = (outcome ) => {
1670
+ const onAbort = () => finish({ outcome: 'rejected' })
1671
+ const finish = (answer ) => {
1660
1672
  const pending = this.pendingApprovals.get(id)
1661
1673
  if (pending === undefined) return
1662
1674
  this.pendingApprovals.delete(id)
1663
1675
  if (timer !== undefined) clearTimeout(timer)
1664
1676
  try { input.signal?.removeEventListener('abort', onAbort) } catch { /* 已卸载 */ }
1665
- pending.resolve(outcome)
1677
+ pending.resolve(answer)
1666
1678
  }
1667
- timer = setTimeout(() => finish('timeout'), VISIBILITY_APPROVAL_TTL_MS)
1679
+ timer = setTimeout(() => finish({ outcome: 'timeout' }), VISIBILITY_APPROVAL_TTL_MS)
1668
1680
  timer.unref?.()
1669
1681
  this.pendingApprovals.set(id, {
1670
1682
  id,
@@ -1710,12 +1722,27 @@ export class LocalMemoryService {
1710
1722
  }
1711
1723
 
1712
1724
  /** 面板:回答一条待审批。返回 false = 已经不存在/已超时。 */
1713
- answerVisibilityApproval(id , outcome ) {
1725
+ answerVisibilityApproval(id , outcome , allowedIds ) {
1714
1726
  const pending = this.pendingApprovals.get(id)
1715
1727
  if (pending === undefined) return false
1716
1728
  this.pendingApprovals.delete(id)
1717
1729
  if (pending.timer !== undefined) clearTimeout(pending.timer)
1718
- pending.resolve(outcome)
1730
+ let answer
1731
+ if (outcome !== 'allowed-once') {
1732
+ answer = { outcome }
1733
+ } else if (Array.isArray(allowedIds)) {
1734
+ const known = new Set(pending.items.map((item) => item.id))
1735
+ const picked = [...new Set(allowedIds.map(String).filter((itemId) => known.has(itemId)))]
1736
+ // 一条都没勾选 = 拒绝;全部勾选退化成老口径(不传 allowedIds = 全部允许)。
1737
+ answer = picked.length === 0
1738
+ ? { outcome: 'rejected' }
1739
+ : picked.length === known.size
1740
+ ? { outcome: 'allowed-once' }
1741
+ : { outcome: 'allowed-once', allowedIds: picked }
1742
+ } else {
1743
+ answer = { outcome: 'allowed-once' }
1744
+ }
1745
+ pending.resolve(answer)
1719
1746
  return true
1720
1747
  }
1721
1748
 
@@ -15,11 +15,12 @@
15
15
  import { defineTool } from '@deepseek-ai/dsh-tools'
16
16
  import {
17
17
  memoryTools,
18
+
18
19
 
19
20
 
20
21
 
21
22
  } from './index.js'
22
- import { renderGetResult, renderSearchResult, renderWithheldNote } from './render.js'
23
+ import { renderGetResult, renderListResult, renderSearchResult } from './render.js'
23
24
  import { resolveCurrentScopes, scopeKind, } from '../provider/scope.js'
24
25
 
25
26
  export const name = 'dsh-tool-memory'
@@ -30,8 +31,27 @@ export const inject = ['tools', 'memory']
30
31
 
31
32
                         
32
33
 
34
+
35
+                  
36
+                            
37
+
38
+
33
39
 
34
40
 
41
+ /** 注入半边提供的服务(只在单包里存在;独立安装工具半边时可能没有)。 */
42
+
43
+
44
+
45
+
46
+
47
+
48
+ /** 工具执行时的会话 id(与注入半边同一口径:agent.session.id)。 */
49
+ function sessionIdOf(exec ) {
50
+ const session = (exec )?.agent?.session
51
+ const id = session?.id
52
+ return typeof id === 'string' && id !== '' ? id : undefined
53
+ }
54
+
35
55
  export function apply(ctx , config = {}) {
36
56
  const memory = ctx.memory
37
57
  /** 调用时的项目键:显式配置 > 会话 cwd > 进程 cwd。 */
@@ -39,10 +59,32 @@ export function apply(ctx , config = {}) {
39
59
  if (config.projectScope !== undefined) return config.projectScope
40
60
  return resolveCurrentScopes((exec )?.agent).project
41
61
  }
62
+ /**
63
+ * 惰性取注入半边的去重服务:apply 执行时它可能还没 provide(两边不保证顺序),
64
+ * 所以每次工具执行时再 ctx.get,而不是在 apply 里取样(见记忆里的冷启动丢注册坑)。
65
+ */
66
+ const contextDedup = (exec ) => {
67
+ if (config.contextDedup === false) return undefined
68
+ const sessionId = sessionIdOf(exec)
69
+ if (sessionId === undefined) return undefined
70
+ try {
71
+ const service = ctx.get('memoryContextDedup')
72
+ if (service === undefined || typeof service.seen !== 'function') return undefined
73
+ return {
74
+ seen: (records) => service.seen(sessionId, records),
75
+ markSummary: (records) => service.markSummary(sessionId, records),
76
+ markContent: (records) => service.markContent(sessionId, records),
77
+ }
78
+ } catch {
79
+ // 去重是纯优化;服务不可用时照常返回摘要。
80
+ return undefined
81
+ }
82
+ }
42
83
  const opts = {
43
84
  getService: () => memory,
44
85
  defaultScope: config.defaultScope ?? 'session',
45
86
  projectScope: config.projectScope,
87
+ contextDedup,
46
88
  }
47
89
  const tools = memoryTools(opts)
48
90
 
@@ -112,12 +154,9 @@ export function apply(ctx , config = {}) {
112
154
 
113
155
  register(tools.memory_list, (value, _args, exec) => {
114
156
  const agent = (exec )?.agent
115
- const body = value.records.length === 0
116
- ? '该作用域还没有记忆。'
117
- : value.records.map((r) => `(${renderScope(r.scope, agent)}/${r.kind}) ${r.content}`).join('\n')
157
+ const body = renderListResult(value, (scope) => renderScope(scope, agent))
118
158
  const summary = scopeSummary(value, agent)
119
- const note = renderWithheldNote(value.withheld)
120
- return [body, summary, note].filter((part) => part !== '').join('\n')
159
+ return [body, summary].filter((part) => part !== '').join('\n')
121
160
  })
122
161
 
123
162
  register(tools.memory_get, (value, _args, exec) => {