@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.
@@ -43,8 +43,26 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
43
43
  /** 一次范围外审批的结局:允许一次 / 用户拒绝 / 超时未答 / 当前版本不支持审批。 */
44
44
 
45
45
 
46
- /** 被可见域挡住、没有返回给模型的原因(absolute 模式不会出现:一律视为不存在)。 */
47
-
46
+ /**
47
+ * 一次范围外审批的结论(0.21.0)。
48
+ *
49
+ * `allowed-once` 默认 = 本次请求**全部**允许;用户在审批卡里逐条勾选时,可带
50
+ * `allowedIds` 只允许其中一部分。老 provider 可能仍直接返回字符串,工具层兼容。
51
+ */
52
+
53
+
54
+                        
55
+
56
+
57
+
58
+ /** provider 的 requestOutOfScope 可以返回裸字符串(旧口径)或带 allowedIds 的对象。 */
59
+
60
+
61
+ /**
62
+ * 被可见域挡住、没有返回给模型的原因(absolute 模式不会出现:一律视为不存在)。
63
+ * `partial` = 用户只允许了其中几条,其余按拒绝处理。
64
+ */
65
+
48
66
 
49
67
 
50
68
 
@@ -76,6 +94,23 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
76
94
 
77
95
 
78
96
 
97
+ /**
98
+ * 一个会话的上下文去重视图(0.21.0)。由入口从注入半边提供的
99
+ * `memoryContextDedup` 服务接进来;没有时工具保持老行为(每次都带摘要)。
100
+ *
101
+ * 为什么要它:memory_search / memory_list 的摘要在同一会话里重复命中时
102
+ * 会把同样的内容反复塞回上下文。工具层只问“这条是否已经以同版本出现过”,
103
+ * 具体状态(摘要/正文/版本)由注入半边的 InjectionState 统一维护。
104
+ */
105
+
106
+                     
107
+
108
+       
109
+
110
+       
111
+
112
+
113
+
79
114
  /** 只有这一层需要的能力子集(provider 在宿主里提供,测试里可以 mock)。 */
80
115
 
81
116
 
@@ -103,8 +138,10 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
103
138
 
104
139
                              
105
140
                                  
141
+             
142
+                            
106
143
 
107
-
144
+
108
145
                            
109
146
 
110
147
                 
@@ -123,6 +160,12 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
123
160
 
124
161
              
125
162
 
163
+
164
+                   
165
+                    
166
+                        
167
+
168
+
126
169
 
127
170
 
128
171
  const SCOPE_DESCRIPTION =
@@ -229,6 +272,38 @@ function outsideReason(policy , scope )
229
272
  return scopeInPolicy(policy, scope) ? 'kind' : 'scope'
230
273
  }
231
274
 
275
+ /** memory_* 的 description 参数说明(模型可见)。 */
276
+ const DESCRIPTION_PARAM_DESCRIPTION =
277
+ '本次调用要做什么(一句话,给用户看)。本会话「记忆范围」为普通限制时必填:审批范围外记忆时,弹窗会把它展示给用户。'
278
+
279
+ /**
280
+ * 把模型的 description 收拾成一行(审批弹窗里展示)。
281
+ * 省略/空白 = undefined(是否合法由 requireDescription 按限制等级判断)。
282
+ */
283
+ function descriptionOf(raw ) {
284
+ if (typeof raw !== 'string') return undefined
285
+ const value = raw.replace(/\s+/g, ' ').trim()
286
+ return value === '' ? undefined : value.slice(0, 500)
287
+ }
288
+
289
+ /**
290
+ * 「记忆范围」为普通限制时,memory_* 必须写 description:审批弹窗要把 Agent 的
291
+ * 意图展示给用户,只有工具名 + 查询词不够判断该不该放行。
292
+ *
293
+ * 拿不到会话(老宿主 / 测试 mock / 面板直调)时不强制 —— 没有会话就没有审批弹窗;
294
+ * absolute / none 也不强制(前者范围外一律视为不存在,后者不需要审批)。
295
+ */
296
+ function requireDescription(service , agent , raw ) {
297
+ if (agent === undefined) return
298
+ const policy = visibilityPolicy(service, agent)
299
+ if (policy === undefined || policy.level !== 'normal') return
300
+ if (descriptionOf(raw) !== undefined) return
301
+ throw new MemoryToolError(
302
+ 'DESCRIPTION_REQUIRED',
303
+ '本会话「记忆范围」为普通限制:调用 memory_* 工具时必须提供 description 字段,用一句话说明这次调用要做什么(审批范围外记忆时弹窗会展示给用户)。',
304
+ )
305
+ }
306
+
232
307
  function recordsToApprovalItems(
233
308
  policy ,
234
309
  records ,
@@ -250,7 +325,16 @@ function recordsToApprovalItems(
250
325
  * 结局必须可区分:允许一次 / 用户拒绝 / 超时 / 旧 provider 不支持审批。
251
326
  * `agent` 省略 = 不审批(工具层在拿不到会话时退回 provider 的护栏)。
252
327
  * 允许写/删时要带 `approvedItems` 之类的合成条目,浮层才显示得出来。
328
+ *
329
+ * 0.21.0:允许的条目可以是"全部"(allowedIds 省略)或用户在审批卡里逐条勾选的
330
+ * 一部分;后者通过 `allowedIds` 返回,调用方只放行这些 id。
253
331
  */
332
+
333
+
334
+             
335
+
336
+
337
+
254
338
  async function askOutOfScope(
255
339
  service ,
256
340
  agent ,
@@ -260,25 +344,42 @@ async function askOutOfScope(
260
344
  records ,
261
345
  action ,
262
346
  signal ,
347
+ description ,
263
348
  ) {
264
- if (records.length === 0) return 'allowed-once'
265
- if (typeof service.requestOutOfScope !== 'function') return 'unavailable'
266
- if (signal?.aborted) return 'rejected'
349
+ if (records.length === 0) return { outcome: 'allowed-once' }
350
+ if (typeof service.requestOutOfScope !== 'function') return { outcome: 'unavailable' }
351
+ if (signal?.aborted) return { outcome: 'rejected' }
267
352
  try {
268
- const outcome = await service.requestOutOfScope(agent, {
353
+ const answer = await service.requestOutOfScope(agent, {
269
354
  tool,
270
355
  action,
271
356
  query,
357
+ ...(description !== undefined ? { description } : {}),
272
358
  items: recordsToApprovalItems(policy, records),
273
359
  ...(signal !== undefined ? { signal } : {}),
274
360
  })
275
- if (outcome === 'allowed-once' || outcome === 'timeout' || outcome === 'unavailable') return outcome
276
- return 'rejected'
361
+ // 老 provider 直接返回字符串;新 provider 返回 { outcome, allowedIds }。
362
+ const decision = typeof answer === 'string' ? { outcome: answer } : answer ?? { outcome: 'unavailable' }
363
+ const outcome = decision.outcome === 'allowed-once' || decision.outcome === 'timeout' || decision.outcome === 'unavailable'
364
+ ? decision.outcome
365
+ : 'rejected'
366
+ const ids = outcome === 'allowed-once' && Array.isArray(decision.allowedIds)
367
+ ? new Set(decision.allowedIds.map(String))
368
+ : undefined
369
+ // 逐条勾选但一条都没选中 = 用户拒绝了这次访问。
370
+ if (ids !== undefined && ids.size === 0) return { outcome: 'rejected' }
371
+ return { outcome, ...(ids !== undefined ? { allowedIds: ids } : {}) }
277
372
  } catch {
278
- return 'unavailable'
373
+ return { outcome: 'unavailable' }
279
374
  }
280
375
  }
281
376
 
377
+ /** 这次审批是否允许这一条(没有 allowedIds = 全部允许)。 */
378
+ function verdictAllows(verdict , id ) {
379
+ if (verdict.outcome !== 'allowed-once') return false
380
+ return verdict.allowedIds === undefined || verdict.allowedIds.has(id)
381
+ }
382
+
282
383
  /** 审批没通过时给模型的真实原因(写/删路径直接抛这个错误)。 */
283
384
  function visibilityError(outcome , action , scope ) {
284
385
  const verb = action === 'write' ? '写入' : '删除'
@@ -382,6 +483,8 @@ function resolveScope(
382
483
 
383
484
                              
384
485
 
486
+                             
487
+
385
488
 
386
489
 
387
490
 
@@ -420,9 +523,12 @@ export function memorySaveTool(opts )
420
523
  expiresAt: { type: 'number', description: '过期时间(毫秒时间戳)。kind=state 不传时按设置里的默认 TTL(7 天)' },
421
524
  ttlMs: { type: 'number', description: '相对有效期(毫秒)。与 expiresAt 二选一,expiresAt 优先' },
422
525
  triggers: { type: 'array', items: { type: 'string' }, description: '流程触发词(kind=procedure):工具名/关键词/路径;缺省用 tags' },
526
+ description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
423
527
  },
424
528
  async execute(args , exec ) {
425
529
  const service = svc(opts)
530
+ const agent = agentOf(exec)
531
+ requireDescription(service, agent, args.description)
426
532
  if (typeof args.content !== 'string' || args.content.trim().length === 0) {
427
533
  throw new MemoryToolError('CONTENT_EMPTY', 'content must be a non-empty string')
428
534
  }
@@ -434,7 +540,6 @@ export function memorySaveTool(opts )
434
540
  // project)。默认值的最终权威是 provider 的 `save` —— 省略时干脆不带 scope 字段,
435
541
  // 但要把会话上下文(exec.agent)带过去,否则它没法知道"当前会话"是谁。
436
542
  const requested = args.scope?.trim()
437
- const agent = agentOf(exec)
438
543
  const pathArg = typeof args.path === 'string' ? args.path.trim() : ''
439
544
 
440
545
  let explicit
@@ -480,7 +585,7 @@ export function memorySaveTool(opts )
480
585
  importance: typeof args.importance === 'number' ? args.importance : 0,
481
586
  updatedAt: Date.now(),
482
587
  }
483
- const outcome = await askOutOfScope(
588
+ const verdict = await askOutOfScope(
484
589
  service,
485
590
  agent,
486
591
  policy,
@@ -489,8 +594,11 @@ export function memorySaveTool(opts )
489
594
  [draft],
490
595
  'write',
491
596
  (exec )?.signal,
597
+ descriptionOf(args.description),
492
598
  )
493
- if (outcome !== 'allowed-once') throw visibilityError(outcome, 'write', target)
599
+ if (!verdictAllows(verdict, draft.id)) {
600
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'write', target)
601
+ }
494
602
  approved = true
495
603
  }
496
604
 
@@ -534,6 +642,30 @@ export function summarize(content , chars = DEFAULT_SUMMARY_CHARS
534
642
  return flat.length <= chars ? flat : `${flat.slice(0, chars)}…`
535
643
  }
536
644
 
645
+ /**
646
+ * memory_search 的上下文去重(0.21.0):
647
+ * - 同一条记忆、同一个 updatedAt 版本已经出现在上下文里 → 摘要置空并标 deduped;
648
+ * - 没出现过的(含内容更新后的新版本)→ 照常带摘要,并记为“摘要已出现”。
649
+ * 注入半边不在时 `contextDedup` 返回 undefined,保持老行为。
650
+ */
651
+ function applySummaryDedupe(opts , exec , records ) {
652
+ if (records.length === 0) return
653
+ const dedup = opts.contextDedup?.(exec)
654
+ if (dedup === undefined) return
655
+ const seen = dedup.seen(records)
656
+ const newlyShown = []
657
+ for (const record of records) {
658
+ if (seen.has(record.id)) {
659
+ record.summary = ''
660
+ record.deduped = true
661
+ } else {
662
+ newlyShown.push(record)
663
+ }
664
+ }
665
+ // 只把这次真的带摘要返回的条目记为已出现;被省略的本来就是已出现。
666
+ if (newlyShown.length > 0) dedup.markSummary(newlyShown)
667
+ }
668
+
537
669
 
538
670
 
539
671
 
@@ -542,6 +674,8 @@ export function summarize(content , chars = DEFAULT_SUMMARY_CHARS
542
674
 
543
675
                
544
676
 
677
+                             
678
+
545
679
 
546
680
 
547
681
 
@@ -553,6 +687,11 @@ export function summarize(content , chars = DEFAULT_SUMMARY_CHARS
553
687
 
554
688
                     
555
689
 
690
+
691
+                           
692
+               
693
+
694
+
556
695
 
557
696
 
558
697
 
@@ -574,14 +713,16 @@ export function memorySearchTool(opts )
574
713
  topK: { type: 'number', description: '1~20' },
575
714
  includeSuperseded: { type: 'boolean', description: '默认 false;true 时把已被 supersede 的旧版本也返回(历史核对)' },
576
715
  summaryChars: { type: 'number', description: `每条摘要的字数上限(默认 ${DEFAULT_SUMMARY_CHARS},20~2000)` },
716
+ description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
577
717
  },
578
718
  async execute(args , exec ) {
579
719
  const service = svc(opts)
720
+ const agent = agentOf(exec)
721
+ requireDescription(service, agent, args.description)
580
722
  if (typeof args.query !== 'string' || args.query.trim().length === 0) {
581
723
  throw new MemoryToolError('QUERY_EMPTY', 'query must be a non-empty string')
582
724
  }
583
725
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
584
- const agent = agentOf(exec)
585
726
  const policy = visibilityPolicy(service, agent)
586
727
  const level = policy?.level ?? 'none'
587
728
  // level=none 时策略里的 scopes 只是偏好,不参与限制(等价于没有可见域)。
@@ -617,9 +758,9 @@ export function memorySearchTool(opts )
617
758
  const inside = hits.filter((hit) => recordAllowed(policy, hit.record.scope, hit.record.kind))
618
759
  const outside = hits.filter((hit) => !recordAllowed(policy, hit.record.scope, hit.record.kind))
619
760
  // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
620
- let outcome
761
+ let verdict
621
762
  if (outside.length > 0 && level === 'normal') {
622
- outcome = await askOutOfScope(
763
+ verdict = await askOutOfScope(
623
764
  service,
624
765
  agent,
625
766
  policy,
@@ -628,10 +769,20 @@ export function memorySearchTool(opts )
628
769
  outside.map((hit) => hit.record),
629
770
  'read',
630
771
  (exec )?.signal,
772
+ descriptionOf(args.description),
631
773
  )
632
774
  }
633
- const allowed = outside.length === 0 || outcome === 'allowed-once'
634
- const selected = allowed ? hits : inside
775
+ // verdict 为空 = 没有发起审批(绝对限制 / 没有范围外命中):范围外一律不放行。
776
+ const approvedOutside = verdict === undefined
777
+ ? []
778
+ : verdict.outcome !== 'allowed-once'
779
+ ? []
780
+ : verdict.allowedIds === undefined
781
+ ? outside
782
+ : outside.filter((hit) => verdict .allowedIds .has(hit.record.id))
783
+ const insideIds = new Set(inside.map((hit) => hit.record.id))
784
+ const approvedOutsideIds = new Set(approvedOutside.map((hit) => hit.record.id))
785
+ const selected = hits.filter((hit) => insideIds.has(hit.record.id) || approvedOutsideIds.has(hit.record.id))
635
786
  const result = {
636
787
  records: selected.map((h) => ({
637
788
  id: h.record.id,
@@ -644,10 +795,13 @@ export function memorySearchTool(opts )
644
795
  })),
645
796
  }
646
797
  // absolute:范围外视为不存在,连"被挡住"都不告诉模型。
647
- if (!allowed && outcome !== undefined) {
648
- result.withheld = { count: outside.length, reason: outcome }
798
+ if (verdict !== undefined) {
799
+ const denied = outside.length - approvedOutside.length
800
+ if (denied > 0) result.withheld = { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome }
649
801
  }
650
802
  if (wantedTopK !== undefined) result.records = result.records.slice(0, wantedTopK)
803
+ // 上下文去重:同一条记忆同版本已经出现过 → 只回 id,摘要让 memory_get 按需取。
804
+ applySummaryDedupe(opts, exec, result.records)
651
805
  return result
652
806
  } catch (error) {
653
807
  throw toolError(error)
@@ -660,6 +814,8 @@ export function memorySearchTool(opts )
660
814
 
661
815
 
662
816
 
817
+                             
818
+
663
819
 
664
820
 
665
821
 
@@ -675,12 +831,14 @@ export function memoryForgetTool(opts )
675
831
  id: { type: 'string', description: 'Exact record id' },
676
832
  query: { type: 'string', description: 'Substring match; by default only the current session scope' },
677
833
  scope: { type: 'string', description: "省略=当前会话;显式指定只删那一个作用域。'all' 不能与 query 同用(防批量误删)。" },
834
+ description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
678
835
  },
679
836
  async execute(args , exec ) {
680
837
  const service = svc(opts)
838
+ const agent = agentOf(exec)
839
+ requireDescription(service, agent, args.description)
681
840
  if (!args.id && !args.query) throw new MemoryToolError('TARGET_REQUIRED', 'provide id or query')
682
841
  if (args.id && args.query) throw new MemoryToolError('TARGET_AMBIGUOUS', 'provide id or query, not both')
683
- const agent = agentOf(exec)
684
842
  // 没有会话就不判断可见域:护栏只对"本会话的 Agent"生效(与 provider 一致)。
685
843
  const policy = agent === undefined ? undefined : visibilityPolicy(service, agent)
686
844
  const level = policy?.level ?? 'none'
@@ -696,7 +854,7 @@ export function memoryForgetTool(opts )
696
854
  throw new MemoryToolError('RECORD_NOT_FOUND', `id ${args.id} not found`)
697
855
  }
698
856
  if (level === 'normal') {
699
- const outcome = await askOutOfScope(
857
+ const verdict = await askOutOfScope(
700
858
  service,
701
859
  agent,
702
860
  policy,
@@ -705,8 +863,11 @@ export function memoryForgetTool(opts )
705
863
  blocked,
706
864
  'delete',
707
865
  signal,
866
+ descriptionOf(args.description),
708
867
  )
709
- if (outcome !== 'allowed-once') throw visibilityError(outcome, 'delete', blocked[0] .scope)
868
+ if (!verdictAllows(verdict, args.id)) {
869
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'delete', blocked[0] .scope)
870
+ }
710
871
  approved = true
711
872
  }
712
873
  }
@@ -732,7 +893,7 @@ export function memoryForgetTool(opts )
732
893
  // 绝对限制:这个作用域"不存在",按一条都没匹配处理(不删、也不泄露原因)。
733
894
  return { removed: 0, ids: [] }
734
895
  }
735
- const outcome = await askOutOfScope(
896
+ const verdict = await askOutOfScope(
736
897
  service,
737
898
  agent,
738
899
  policy,
@@ -749,8 +910,11 @@ export function memoryForgetTool(opts )
749
910
  }],
750
911
  'delete',
751
912
  signal,
913
+ descriptionOf(args.description),
752
914
  )
753
- if (outcome !== 'allowed-once') throw visibilityError(outcome, 'delete', scope)
915
+ if (!verdictAllows(verdict, `query:${scope}`)) {
916
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'delete', scope)
917
+ }
754
918
  approved = true
755
919
  }
756
920
  try {
@@ -771,10 +935,12 @@ export function memoryForgetTool(opts )
771
935
 
772
936
 
773
937
 
938
+                             
939
+
774
940
 
775
941
 
776
942
 
777
-
943
+
778
944
                                 
779
945
 
780
946
 
@@ -792,11 +958,13 @@ export function memoryListTool(opts )
792
958
  scope: { type: 'string', description: "省略=当前会话;'all'=所有作用域;其他值只列该作用域。" },
793
959
  kind: { type: 'string' },
794
960
  limit: { type: 'number', description: '1~200' },
961
+ description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
795
962
  },
796
963
  async execute(args , exec ) {
797
964
  const service = svc(opts)
798
- const resolved = resolveScope(opts, service, exec, args.scope, 'read')
799
965
  const agent = agentOf(exec)
966
+ requireDescription(service, agent, args.description)
967
+ const resolved = resolveScope(opts, service, exec, args.scope, 'read')
800
968
  const policy = visibilityPolicy(service, agent)
801
969
  const level = policy?.level ?? 'none'
802
970
  // level=none 时策略里的 scopes 只是偏好,不参与限制(等价于没有可见域)。
@@ -827,9 +995,9 @@ export function memoryListTool(opts )
827
995
  const inside = raw.filter((record) => recordAllowed(policy, record.scope, record.kind))
828
996
  const outside = raw.filter((record) => !recordAllowed(policy, record.scope, record.kind))
829
997
  // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
830
- let outcome
998
+ let verdict
831
999
  if (outside.length > 0 && level === 'normal') {
832
- outcome = await askOutOfScope(
1000
+ verdict = await askOutOfScope(
833
1001
  service,
834
1002
  agent,
835
1003
  policy,
@@ -838,10 +1006,21 @@ export function memoryListTool(opts )
838
1006
  outside,
839
1007
  'read',
840
1008
  (exec )?.signal,
1009
+ descriptionOf(args.description),
841
1010
  )
842
1011
  }
843
- const allowed = outside.length === 0 || outcome === 'allowed-once'
844
- const selected = (allowed ? raw : inside).slice(0, limit)
1012
+ const approvedOutside = verdict === undefined
1013
+ ? []
1014
+ : verdict.outcome !== 'allowed-once'
1015
+ ? []
1016
+ : verdict.allowedIds === undefined
1017
+ ? outside
1018
+ : outside.filter((record) => verdict .allowedIds .has(record.id))
1019
+ const insideIds = new Set(inside.map((record) => record.id))
1020
+ const approvedOutsideIds = new Set(approvedOutside.map((record) => record.id))
1021
+ const selected = raw
1022
+ .filter((record) => insideIds.has(record.id) || approvedOutsideIds.has(record.id))
1023
+ .slice(0, limit)
845
1024
  records = selected.map((r) => ({
846
1025
  id: r.id,
847
1026
  scope: r.scope,
@@ -849,8 +1028,24 @@ export function memoryListTool(opts )
849
1028
  updatedAt: r.updatedAt,
850
1029
  content: r.content,
851
1030
  }))
852
- if (!allowed && outcome !== undefined) {
853
- withheld = { count: outside.length, reason: outcome }
1031
+ if (verdict !== undefined) {
1032
+ const denied = outside.length - approvedOutside.length
1033
+ if (denied > 0) withheld = { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome }
1034
+ }
1035
+ // 上下文去重:同版本已经出现过 → 只回 id,正文让 memory_get 按需取。
1036
+ const dedup = opts.contextDedup?.(exec)
1037
+ if (dedup !== undefined && records.length > 0) {
1038
+ const seen = dedup.seen(records)
1039
+ const newlyShown = []
1040
+ records = records.map((record) => {
1041
+ if (!seen.has(record.id)) {
1042
+ newlyShown.push(record)
1043
+ return record
1044
+ }
1045
+ return { ...record, content: '', deduped: true }
1046
+ })
1047
+ // 这次真的把正文放进上下文的条目,后续检索/召回都按"已出现"处理。
1048
+ if (newlyShown.length > 0) dedup.markContent(newlyShown)
854
1049
  }
855
1050
  } catch (error) {
856
1051
  throw toolError(error)
@@ -894,6 +1089,8 @@ export const DEFAULT_GET_FIELDS = ['content', 'scope', 'kind', 'tags
894
1089
 
895
1090
              
896
1091
 
1092
+                             
1093
+
897
1094
 
898
1095
 
899
1096
 
@@ -976,9 +1173,12 @@ export function memoryGetTool(opts )
976
1173
  description: `只取这些字段,省略=${DEFAULT_GET_FIELDS.join('+')};可选:${GET_FIELDS.join(' / ')}(id 始终返回)`,
977
1174
  },
978
1175
  summaryChars: { type: 'number', description: `summary 字段的字数上限(默认 ${DEFAULT_SUMMARY_CHARS},20~2000)` },
1176
+ description: { type: 'string', description: DESCRIPTION_PARAM_DESCRIPTION },
979
1177
  },
980
1178
  async execute(args , exec ) {
981
1179
  const service = svc(opts)
1180
+ const agent = agentOf(exec)
1181
+ requireDescription(service, agent, args.description)
982
1182
  const ids = Array.isArray(args.ids)
983
1183
  ? [...new Set(args.ids.map(String).filter((id) => id.trim() !== ''))].slice(0, 50)
984
1184
  : []
@@ -991,15 +1191,14 @@ export function memoryGetTool(opts )
991
1191
  try {
992
1192
  const all = service.getByIds(ids)
993
1193
  // 可见域是白名单:即使知道 id,也不能直接读别的范围/别的类型的正文。
994
- const agent = agentOf(exec)
995
1194
  const policy = visibilityPolicy(service, agent)
996
1195
  const level = policy?.level ?? 'none'
997
1196
  const inside = all.filter((record) => recordAllowed(policy, record.scope, record.kind))
998
1197
  const outside = all.filter((record) => !recordAllowed(policy, record.scope, record.kind))
999
1198
  // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
1000
- let outcome
1199
+ let verdict
1001
1200
  if (outside.length > 0 && level === 'normal') {
1002
- outcome = await askOutOfScope(
1201
+ verdict = await askOutOfScope(
1003
1202
  service,
1004
1203
  agent,
1005
1204
  policy,
@@ -1008,16 +1207,27 @@ export function memoryGetTool(opts )
1008
1207
  outside,
1009
1208
  'read',
1010
1209
  (exec )?.signal,
1210
+ descriptionOf(args.description),
1011
1211
  )
1012
1212
  }
1013
- const allowed = outside.length === 0 || outcome === 'allowed-once'
1014
- const found = allowed ? all : inside
1213
+ // verdict 为空 = 没有发起审批(绝对限制):范围外一律按不存在处理。
1214
+ const approvedOutside = verdict === undefined
1215
+ ? []
1216
+ : verdict.outcome !== 'allowed-once'
1217
+ ? []
1218
+ : verdict.allowedIds === undefined
1219
+ ? outside
1220
+ : outside.filter((record) => verdict .allowedIds .has(record.id))
1221
+ const insideIds = new Set(inside.map((record) => record.id))
1222
+ const approvedIds = new Set(approvedOutside.map((record) => record.id))
1223
+ const found = all.filter((record) => insideIds.has(record.id) || approvedIds.has(record.id))
1224
+ const denied = outside.length - approvedOutside.length
1015
1225
  return {
1016
1226
  records: found.map((r) => pickGetFields(r, fields, chars)),
1017
1227
  fields,
1018
1228
  missing: ids.filter((token) => !found.some((r) => r.id === token || r.id.startsWith(token))),
1019
- ...(!allowed && outcome !== undefined
1020
- ? { withheld: { count: outside.length, reason: outcome } }
1229
+ ...(verdict !== undefined && denied > 0
1230
+ ? { withheld: { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome } }
1021
1231
  : {}),
1022
1232
  }
1023
1233
  } catch (error) {
@@ -9,7 +9,7 @@
9
9
  * 写进渲染文本。绝对限制下工具根本不会带 withheld(视为不存在),所以这里
10
10
  * 不需要也不应该提"被挡住"。
11
11
  */
12
-
12
+
13
13
 
14
14
  /** 把 scope 键渲染成展示文案(宿主能查到会话标题时用它,否则用短 id)。 */
15
15
 
@@ -17,7 +17,13 @@
17
17
  /** 有内容没返回时的原因(absolute 模式不会走到这里)。 */
18
18
 
19
19
 
20
- const shortId = (id ) => id.slice(0, 8)
20
+ /**
21
+ * 上下文去重的提示语(0.21.0)。memory_search / memory_list 里已经出现过的条目
22
+ * 只回 id、不再回摘要/正文;这条提示告诉模型为什么少了东西、以及怎么取全文。
23
+ */
24
+ export const DEDUPE_NOTE = '本次请求部分记忆摘要因上下文去重机制被省略,若要获取完整内容请使用 memory_get'
25
+
26
+ export const shortId = (id ) => id.slice(0, 8)
21
27
 
22
28
  const day = (value ) =>
23
29
  typeof value === 'number' && Number.isFinite(value) ? new Date(value).toISOString().slice(0, 10) : ''
@@ -39,6 +45,8 @@ export function renderWithheldNote(withheld ) {
39
45
  return `另有 ${count} 条记忆在本会话的可见域外,审批在 5 分钟内没有得到答复,已按拒绝处理,未返回。如确实需要,请让用户调整「记忆范围」后重试。`
40
46
  case 'unavailable':
41
47
  return `另有 ${count} 条记忆在本会话的可见域外,当前环境无法发起审批,未返回。`
48
+ case 'partial':
49
+ return `另有 ${count} 条记忆在本会话的可见域外,用户在本次审批中只允许了其余条目(限制等级:普通限制),未返回。如确实需要,请让用户调整「记忆范围」后重试。`
42
50
  default:
43
51
  return ''
44
52
  }
@@ -51,12 +59,43 @@ export function renderSearchResult(value , label )
51
59
  if (note === '') return '没有找到相关记忆。'
52
60
  return `没有找到可见范围内的相关记忆。\n${note}`
53
61
  }
54
- const body = value.records.map((hit) => {
62
+ // 已出现过的条目(上下文去重)只回 id:不带作用域/类型/标签/摘要。
63
+ // 它们单独成块、与带摘要的条目之间空一行 —— 否则一串裸 id 看起来像上一条的
64
+ // 续行,模型分不清哪些条目「这次有摘要」哪些「只是占位 id」(0.22.0)。
65
+ const shown = []
66
+ const bare = []
67
+ for (const hit of value.records) {
68
+ if (hit.deduped === true) {
69
+ bare.push(shortId(hit.id))
70
+ continue
71
+ }
55
72
  const tags = joinList(hit.tags)
56
73
  const meta = `${label(hit.scope)}/${hit.kind}${tags === '' ? '' : ` · ${tags}`}`
57
- return `[${hit.score.toFixed(3)}] ${shortId(hit.id)} (${meta}) ${hit.summary}`
58
- }).join('\n')
59
- return note === '' ? body : `${body}\n\n${note}`
74
+ shown.push(`[${hit.score.toFixed(3)}] ${shortId(hit.id)} (${meta}) ${hit.summary}`)
75
+ }
76
+ const body = [shown.join('\n'), bare.join('\n')].filter((part) => part !== '').join('\n\n')
77
+ const tail = [bare.length > 0 ? DEDUPE_NOTE : '', note].filter((part) => part !== '').join('\n\n')
78
+ return tail === '' ? body : `${body}\n\n${tail}`
79
+ }
80
+
81
+ /**
82
+ * memory_list 的渲染:每条「(作用域/类型) 正文」;上下文去重过的条目只给 id。
83
+ * `scopeStats` 的尾部摘要由 apply.ts 追加(那里能查会话标题)。
84
+ */
85
+ export function renderListResult(value , label ) {
86
+ let omitted = 0
87
+ const body = value.records.length === 0
88
+ ? '该作用域还没有记忆。'
89
+ : value.records.map((record) => {
90
+ if (record.deduped === true) {
91
+ omitted += 1
92
+ return shortId(record.id)
93
+ }
94
+ return `(${label(record.scope)}/${record.kind}) ${record.content}`
95
+ }).join('\n')
96
+ const note = renderWithheldNote(value.withheld)
97
+ const tail = [omitted > 0 ? DEDUPE_NOTE : '', note].filter((part) => part !== '').join('\n\n')
98
+ return tail === '' ? body : `${body}\n\n${tail}`
60
99
  }
61
100
 
62
101
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",