@restregular/dsh-memory 0.20.0 → 0.22.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,10 @@ 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
+
13
+ 本会话「记忆范围」为普通限制时(默认),调用任一 memory_* 工具都必须带 description 字段:用一句话说明这次调用要做什么(例如「查发布流程的坑」)。它只用于范围外访问的审批弹窗,不写进记忆;漏了会被工具直接拒绝。绝对限制 / 无限制下可省略。
14
+
11
15
  遇到以下情况先查记忆,不要凭猜测开始:
12
16
  - 不确定这个项目以前怎么做、有没有既定约定、某个坑是否踩过;
13
17
  - 用户的话里出现「上次 / 之前 / 还是那样」这类指代。
@@ -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 时落到哪)。 */
@@ -543,13 +543,27 @@ export function resolveConfig(config = {}) {
543
543
 
544
544
                     
545
545
 
546
+                             
547
+
546
548
 
547
549
 
548
550
 
549
551
 
550
552
 
553
+ /** 一次审批的结局:允许(可只允许其中几条) / 拒绝 / 超时。 */
554
+
555
+
556
+ /**
557
+ * 审批结论(0.21.0)。`allowedIds` 省略 = 本次请求的所有条目都允许;
558
+ * 用户在审批卡里逐条勾选时只带被勾选的条目 id。
559
+ */
560
+
561
+
562
+
563
+
564
+
551
565
 
552
-
566
+
553
567
 
554
568
 
555
569
 
@@ -1643,28 +1657,31 @@ export class LocalMemoryService {
1643
1657
                      
1644
1658
 
1645
1659
 
1660
+                       
1661
+
1646
1662
 
1647
1663
 
1648
1664
  ,
1649
- ) {
1650
- if (input.items.length === 0) return Promise.resolve('allowed-once')
1651
- if (input.signal?.aborted) return Promise.resolve('rejected')
1665
+ ) {
1666
+ if (input.items.length === 0) return Promise.resolve({ outcome: 'allowed-once' })
1667
+ if (input.signal?.aborted) return Promise.resolve({ outcome: 'rejected' })
1652
1668
  const sessionId = this.rawSessionIdOf(agent) ?? ''
1653
1669
  const id = `vis-${Date.now().toString(36)}-${++this.approvalSeq}`
1654
1670
  const createdAt = Date.now()
1655
1671
  const expiresAt = createdAt + VISIBILITY_APPROVAL_TTL_MS
1672
+ const description = typeof input.description === 'string' ? input.description.replace(/\s+/g, ' ').trim().slice(0, 500) : ''
1656
1673
  return new Promise((resolve) => {
1657
1674
  let timer
1658
- const onAbort = () => finish('rejected')
1659
- const finish = (outcome ) => {
1675
+ const onAbort = () => finish({ outcome: 'rejected' })
1676
+ const finish = (answer ) => {
1660
1677
  const pending = this.pendingApprovals.get(id)
1661
1678
  if (pending === undefined) return
1662
1679
  this.pendingApprovals.delete(id)
1663
1680
  if (timer !== undefined) clearTimeout(timer)
1664
1681
  try { input.signal?.removeEventListener('abort', onAbort) } catch { /* 已卸载 */ }
1665
- pending.resolve(outcome)
1682
+ pending.resolve(answer)
1666
1683
  }
1667
- timer = setTimeout(() => finish('timeout'), VISIBILITY_APPROVAL_TTL_MS)
1684
+ timer = setTimeout(() => finish({ outcome: 'timeout' }), VISIBILITY_APPROVAL_TTL_MS)
1668
1685
  timer.unref?.()
1669
1686
  this.pendingApprovals.set(id, {
1670
1687
  id,
@@ -1672,6 +1689,7 @@ export class LocalMemoryService {
1672
1689
  tool: input.tool,
1673
1690
  action: input.action ?? 'read',
1674
1691
  query: input.query,
1692
+ ...(description !== '' ? { description } : {}),
1675
1693
  items: input.items.slice(0, VISIBILITY_APPROVAL_MAX_ITEMS).map((item) => ({
1676
1694
  ...item,
1677
1695
  tags: [...item.tags],
@@ -1696,6 +1714,7 @@ export class LocalMemoryService {
1696
1714
  tool: pending.tool,
1697
1715
  action: pending.action,
1698
1716
  query: pending.query,
1717
+ ...(pending.description !== undefined ? { description: pending.description } : {}),
1699
1718
  // 轮询载荷保持轻量:正文截到 1200 字,悬浮需要全文时面板再按 id 取一次。
1700
1719
  items: pending.items.map((item) => ({
1701
1720
  ...item,
@@ -1710,12 +1729,27 @@ export class LocalMemoryService {
1710
1729
  }
1711
1730
 
1712
1731
  /** 面板:回答一条待审批。返回 false = 已经不存在/已超时。 */
1713
- answerVisibilityApproval(id , outcome ) {
1732
+ answerVisibilityApproval(id , outcome , allowedIds ) {
1714
1733
  const pending = this.pendingApprovals.get(id)
1715
1734
  if (pending === undefined) return false
1716
1735
  this.pendingApprovals.delete(id)
1717
1736
  if (pending.timer !== undefined) clearTimeout(pending.timer)
1718
- pending.resolve(outcome)
1737
+ let answer
1738
+ if (outcome !== 'allowed-once') {
1739
+ answer = { outcome }
1740
+ } else if (Array.isArray(allowedIds)) {
1741
+ const known = new Set(pending.items.map((item) => item.id))
1742
+ const picked = [...new Set(allowedIds.map(String).filter((itemId) => known.has(itemId)))]
1743
+ // 一条都没勾选 = 拒绝;全部勾选退化成老口径(不传 allowedIds = 全部允许)。
1744
+ answer = picked.length === 0
1745
+ ? { outcome: 'rejected' }
1746
+ : picked.length === known.size
1747
+ ? { outcome: 'allowed-once' }
1748
+ : { outcome: 'allowed-once', allowedIds: picked }
1749
+ } else {
1750
+ answer = { outcome: 'allowed-once' }
1751
+ }
1752
+ pending.resolve(answer)
1719
1753
  return true
1720
1754
  }
1721
1755
 
@@ -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) => {