@restregular/dsh-memory 0.19.2 → 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.
@@ -40,16 +40,46 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
40
40
  /** 范围外访问的处理方式(与 provider 的会话可见域一致)。 */
41
41
 
42
42
 
43
+ /** 一次范围外审批的结局:允许一次 / 用户拒绝 / 超时未答 / 当前版本不支持审批。 */
44
+
45
+
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
+
66
+
43
67
 
44
68
 
45
69
                  
46
70
 
47
71
 
48
72
 
49
- /** provider 解析出的生效可见域;undefined = 没有覆盖(不限制)。 */
73
+ /**
74
+ * provider 解析出的生效可见域。0.20.0 起 provider 永远返回一份策略:
75
+ * 没有显式覆盖时是「会话 + 项目 + global」+ 普通限制,`source === 'default'`。
76
+ * 老 provider 仍可能返回 undefined(视为不限制)。
77
+ */
50
78
 
51
79
 
52
80
 
81
+                         
82
+
53
83
 
54
84
 
55
85
  /** 一条范围外命中,交给审批浮层展示。 */
@@ -64,9 +94,25 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
64
94
 
65
95
 
66
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
+
67
114
  /** 只有这一层需要的能力子集(provider 在宿主里提供,测试里可以 mock)。 */
68
-
69
-
115
+
70
116
 
71
117
 
72
118
 
@@ -81,10 +127,19 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
81
127
           
82
128
 
83
129
 
84
-                         
130
+                            
85
131
 
86
-                             
87
-
132
+
133
+                               
134
+                
135
+
136
+
137
+
138
+                             
139
+                                 
140
+             
141
+
142
+
88
143
                            
89
144
 
90
145
                 
@@ -103,6 +158,12 @@ import { canonicalWorkspacePath, normalizeScopeInput, resolveScopeRef } from '..
103
158
 
104
159
              
105
160
 
161
+
162
+                   
163
+                    
164
+                        
165
+
166
+
106
167
 
107
168
 
108
169
  const SCOPE_DESCRIPTION =
@@ -150,7 +211,8 @@ function projectKey(opts , service , agent
150
211
  }
151
212
 
152
213
  /**
153
- * 显式「可见范围」白名单;undefined = 没有覆盖(保持旧行为,不限制显式 scope)。
214
+ * 显式「可见范围」白名单;undefined = 本会话没有显式覆盖(注入半边用它判断
215
+ * 要不要关掉 extraScopes,工具层不用它做读限制 —— 那是 visibilityPolicy 的事)。
154
216
  * provider 方法抛错时按"没有覆盖"处理:可见范围是防越界,不应该让一个 provider
155
217
  * 内部错误把所有读取都锁死。
156
218
  */
@@ -162,18 +224,34 @@ function visibleScopeList(service , agent )
162
224
  return undefined
163
225
  }
164
226
 
165
- /** 完整可见域;老 provider / 解析失败时退化为 undefined(不限制)。 */
227
+ /**
228
+ * 完整可见域;老 provider / 解析失败时退化为 undefined(不限制)。
229
+ * 0.20 的 provider 永远返回策略:没有显式覆盖时是默认策略(source='default'),
230
+ * 默认范围 = 会话 + 项目 + global,等级 = normal。
231
+ */
166
232
  function visibilityPolicy(service , agent ) {
167
233
  try {
168
234
  const policy = service.visibilityPolicy?.(agent)
169
235
  if (policy !== undefined && policy !== null) {
170
236
  const level = policy.level === 'absolute' || policy.level === 'none' ? policy.level : 'normal'
171
- return { level, scopes: Array.isArray(policy.scopes) ? policy.scopes : [] }
237
+ const source = policy.source === 'explicit' || policy.source === 'inherited' || policy.source === 'default'
238
+ ? policy.source
239
+ : undefined
240
+ return {
241
+ level,
242
+ scopes: Array.isArray(policy.scopes) ? policy.scopes : [],
243
+ ...(source !== undefined ? { source } : {}),
244
+ }
172
245
  }
173
246
  } catch { /* 降级为不限制 */ }
174
247
  return undefined
175
248
  }
176
249
 
250
+ /** 是否"用户显式设过的策略"(默认策略不算):决定普通限制下要不要把范围外也搜一遍。 */
251
+ function explicitPolicy(policy ) {
252
+ return policy !== undefined && policy.source !== 'default'
253
+ }
254
+
177
255
  function scopeInPolicy(policy , scope ) {
178
256
  if (policy === undefined || policy.level === 'none') return true
179
257
  return policy.scopes.some((rule) => rule.scope === scope)
@@ -209,9 +287,20 @@ function recordsToApprovalItems(
209
287
  }
210
288
 
211
289
  /**
212
- * 普通限制:把范围外命中交给用户审批一次。
213
- * provider 不支持审批(旧版本)时按拒绝处理 —— 不能静默把范围外记忆放出去。
290
+ * 普通限制:把范围外访问交给用户审批一次。
291
+ * 结局必须可区分:允许一次 / 用户拒绝 / 超时 / 旧 provider 不支持审批。
292
+ * `agent` 省略 = 不审批(工具层在拿不到会话时退回 provider 的护栏)。
293
+ * 允许写/删时要带 `approvedItems` 之类的合成条目,浮层才显示得出来。
294
+ *
295
+ * 0.21.0:允许的条目可以是"全部"(allowedIds 省略)或用户在审批卡里逐条勾选的
296
+ * 一部分;后者通过 `allowedIds` 返回,调用方只放行这些 id。
214
297
  */
298
+
299
+
300
+             
301
+
302
+
303
+
215
304
  async function askOutOfScope(
216
305
  service ,
217
306
  agent ,
@@ -219,35 +308,73 @@ async function askOutOfScope(
219
308
  tool ,
220
309
  query ,
221
310
  records ,
311
+ action ,
222
312
  signal ,
223
- ) {
224
- if (records.length === 0) return true
225
- if (typeof service.requestOutOfScope !== 'function') return false
226
- if (signal?.aborted) return false
313
+ ) {
314
+ if (records.length === 0) return { outcome: 'allowed-once' }
315
+ if (typeof service.requestOutOfScope !== 'function') return { outcome: 'unavailable' }
316
+ if (signal?.aborted) return { outcome: 'rejected' }
227
317
  try {
228
- const outcome = await service.requestOutOfScope(agent, {
318
+ const answer = await service.requestOutOfScope(agent, {
229
319
  tool,
320
+ action,
230
321
  query,
231
322
  items: recordsToApprovalItems(policy, records),
232
323
  ...(signal !== undefined ? { signal } : {}),
233
324
  })
234
- return outcome === 'allowed-once'
325
+ // 老 provider 直接返回字符串;新 provider 返回 { outcome, allowedIds }。
326
+ const decision = typeof answer === 'string' ? { outcome: answer } : answer ?? { outcome: 'unavailable' }
327
+ const outcome = decision.outcome === 'allowed-once' || decision.outcome === 'timeout' || decision.outcome === 'unavailable'
328
+ ? decision.outcome
329
+ : 'rejected'
330
+ const ids = outcome === 'allowed-once' && Array.isArray(decision.allowedIds)
331
+ ? new Set(decision.allowedIds.map(String))
332
+ : undefined
333
+ // 逐条勾选但一条都没选中 = 用户拒绝了这次访问。
334
+ if (ids !== undefined && ids.size === 0) return { outcome: 'rejected' }
335
+ return { outcome, ...(ids !== undefined ? { allowedIds: ids } : {}) }
235
336
  } catch {
236
- return false
337
+ return { outcome: 'unavailable' }
237
338
  }
238
339
  }
239
340
 
240
- /** 显式询问一个不在可见范围内的 scope 时给出明确错误,而不是返回空结果。 */
241
- function assertScopeVisible(service , agent , scope ) {
242
- const policy = visibilityPolicy(service, agent)
243
- if (policy === undefined || policy.level === 'none' || scopeInPolicy(policy, scope)) return
244
- const visible = policy.scopes.map((rule) => rule.scope)
245
- throw new MemoryToolError(
246
- 'SCOPE_NOT_VISIBLE',
247
- `当前会话的「记忆可见域」不包含 ${scope};只能读取: ${visible.length > 0 ? visible.join(', ') : '(无)'}`,
341
+ /** 这次审批是否允许这一条(没有 allowedIds = 全部允许)。 */
342
+ function verdictAllows(verdict , id ) {
343
+ if (verdict.outcome !== 'allowed-once') return false
344
+ return verdict.allowedIds === undefined || verdict.allowedIds.has(id)
345
+ }
346
+
347
+ /** 审批没通过时给模型的真实原因(写/删路径直接抛这个错误)。 */
348
+ function visibilityError(outcome , action , scope ) {
349
+ const verb = action === 'write' ? '写入' : '删除'
350
+ if (outcome === 'rejected') {
351
+ return new MemoryToolError(
352
+ 'VISIBILITY_REJECTED',
353
+ `用户拒绝了本次${verb}请求(作用域 ${scope},当前限制等级:普通限制),没有执行。如需${verb},请让用户调整「记忆范围」后重试。`,
354
+ )
355
+ }
356
+ if (outcome === 'timeout') {
357
+ return new MemoryToolError(
358
+ 'VISIBILITY_TIMEOUT',
359
+ `等待用户审批超时(5 分钟没有答复),本次${verb}没有执行(作用域 ${scope},当前限制等级:普通限制)。`,
360
+ )
361
+ }
362
+ return new MemoryToolError(
363
+ 'VISIBILITY_UNAVAILABLE',
364
+ `当前环境无法就范围外访问发起审批,本次${verb}没有执行(作用域 ${scope})。`,
248
365
  )
249
366
  }
250
367
 
368
+ /** 写入/删除前判断一个 scope 是否可操作(可见范围 = 可操作范围)。 */
369
+ function scopeOperable(service , agent , policy , scope ) {
370
+ if (policy === undefined || policy.level === 'none') return true
371
+ try {
372
+ const verdict = service.isScopeOperable?.(agent, scope)
373
+ if (typeof verdict === 'boolean') return verdict
374
+ } catch { /* 退回本地判断 */ }
375
+ return scopeInPolicy(policy, scope)
376
+ }
377
+
251
378
  /** 规范里所有已知 scope(用来在普通限制下把范围外也搜一遍,看看有没有可审批的命中)。 */
252
379
  function allKnownScopes(service ) {
253
380
  try {
@@ -367,6 +494,7 @@ export function memorySaveTool(opts )
367
494
  if (args.importance !== undefined && (args.importance < 0 || args.importance > 1)) {
368
495
  throw new MemoryToolError('IMPORTANCE_RANGE', 'importance must be between 0 and 1')
369
496
  }
497
+ const content = args.content.trim()
370
498
  // 写路径:省略 scope → provider 按 tools.defaultScope(缺省 session,拿不到会话回退
371
499
  // project)。默认值的最终权威是 provider 的 `save` —— 省略时干脆不带 scope 字段,
372
500
  // 但要把会话上下文(exec.agent)带过去,否则它没法知道"当前会话"是谁。
@@ -395,13 +523,52 @@ export function memorySaveTool(opts )
395
523
  explicit = resolved
396
524
  }
397
525
 
526
+ // 写入护栏(0.20.0):可见范围 = 可操作范围。范围外写入:
527
+ // - absolute → 按"作用域不存在/不可写"处理,不暴露可见域配置;
528
+ // - normal → 先向用户审批一次,拒绝/超时把真实原因抛给模型;
529
+ // - none → 不限制。
530
+ // 拿不到会话(老宿主 / 无 exec)时不判断:没有会话就没有"本会话的可见域"。
531
+ const policy = agent === undefined ? undefined : visibilityPolicy(service, agent)
532
+ const level = policy?.level ?? 'none'
533
+ const target = explicit ?? (typeof service.resolveWriteScope === 'function' ? service.resolveWriteScope(agent) : undefined)
534
+ let approved = false
535
+ if (level !== 'none' && target !== undefined && !scopeOperable(service, agent, policy, target)) {
536
+ if (level === 'absolute') {
537
+ throw new MemoryToolError('SCOPE_NOT_WRITABLE', `作用域 ${target} 不存在或不可写`)
538
+ }
539
+ const draft = {
540
+ id: 'new-record',
541
+ scope: target,
542
+ kind: args.kind ?? 'note',
543
+ content: content,
544
+ tags: Array.isArray(args.tags) ? args.tags : [],
545
+ importance: typeof args.importance === 'number' ? args.importance : 0,
546
+ updatedAt: Date.now(),
547
+ }
548
+ const verdict = await askOutOfScope(
549
+ service,
550
+ agent,
551
+ policy,
552
+ 'memory_save',
553
+ summarize(content, 80),
554
+ [draft],
555
+ 'write',
556
+ (exec )?.signal,
557
+ )
558
+ if (!verdictAllows(verdict, draft.id)) {
559
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'write', target)
560
+ }
561
+ approved = true
562
+ }
563
+
398
564
  try {
399
565
  const record = await service.save({
400
566
  ...(explicit !== undefined ? { scope: explicit } : {}),
401
567
  ...(alias !== undefined ? { name: alias } : {}),
402
568
  ...(agent !== undefined ? { agent } : {}),
569
+ ...(approved ? { visibilityApproved: true } : {}),
403
570
  kind: args.kind ?? 'note',
404
- content: args.content.trim(),
571
+ content: content,
405
572
  ...(args.tags ? { tags: args.tags } : {}),
406
573
  ...(args.importance !== undefined ? { importance: args.importance } : {}),
407
574
  ...(args.supersedes ? { supersedes: args.supersedes } : {}),
@@ -434,6 +601,30 @@ export function summarize(content , chars = DEFAULT_SUMMARY_CHARS
434
601
  return flat.length <= chars ? flat : `${flat.slice(0, chars)}…`
435
602
  }
436
603
 
604
+ /**
605
+ * memory_search 的上下文去重(0.21.0):
606
+ * - 同一条记忆、同一个 updatedAt 版本已经出现在上下文里 → 摘要置空并标 deduped;
607
+ * - 没出现过的(含内容更新后的新版本)→ 照常带摘要,并记为“摘要已出现”。
608
+ * 注入半边不在时 `contextDedup` 返回 undefined,保持老行为。
609
+ */
610
+ function applySummaryDedupe(opts , exec , records ) {
611
+ if (records.length === 0) return
612
+ const dedup = opts.contextDedup?.(exec)
613
+ if (dedup === undefined) return
614
+ const seen = dedup.seen(records)
615
+ const newlyShown = []
616
+ for (const record of records) {
617
+ if (seen.has(record.id)) {
618
+ record.summary = ''
619
+ record.deduped = true
620
+ } else {
621
+ newlyShown.push(record)
622
+ }
623
+ }
624
+ // 只把这次真的带摘要返回的条目记为已出现;被省略的本来就是已出现。
625
+ if (newlyShown.length > 0) dedup.markSummary(newlyShown)
626
+ }
627
+
437
628
 
438
629
 
439
630
 
@@ -453,12 +644,20 @@ export function summarize(content , chars = DEFAULT_SUMMARY_CHARS
453
644
 
454
645
                     
455
646
 
647
+
648
+                           
649
+               
650
+
651
+
456
652
 
457
653
 
458
654
 
459
655
 
460
-                            
461
-
656
+
657
+                                   
658
+                         
659
+
660
+
462
661
 
463
662
 
464
663
  export function memorySearchTool(opts ) {
@@ -480,10 +679,12 @@ export function memorySearchTool(opts )
480
679
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
481
680
  const agent = agentOf(exec)
482
681
  const policy = visibilityPolicy(service, agent)
483
- const level = policy?.level
484
- const visible = policy !== undefined && level !== 'none'
485
- ? policy.scopes.map((rule) => rule.scope)
486
- : visibleScopeList(service, agent)
682
+ const level = policy?.level ?? 'none'
683
+ // level=none 时策略里的 scopes 只是偏好,不参与限制(等价于没有可见域)。
684
+ const visible = policy !== undefined && policy.level !== 'none' ? policy.scopes.map((rule) => rule.scope) : undefined
685
+ // 只有"用户显式设过"的普通限制才把磁盘上其它 scope 也搜一遍(才有范围外命中
686
+ // 可以审批)。默认策略下普通检索就只搜默认的三路集合,避免每次都弹审批。
687
+ const expand = level === 'normal' && explicitPolicy(policy)
487
688
  let scopes
488
689
  if (resolved.all) {
489
690
  if (visible !== undefined) {
@@ -496,9 +697,7 @@ export function memorySearchTool(opts )
496
697
  } else if (resolved.scope === undefined) {
497
698
  // 省略 scope:三路合并(会话 + 项目 + global),或显式可见范围。
498
699
  const merged = readScopes(opts, service, agent)
499
- scopes = level === 'normal' ? [...new Set([...merged, ...allKnownScopes(service)])] : merged
500
- } else if (level === 'absolute') {
501
- assertScopeVisible(service, agent, resolved.scope)
700
+ scopes = expand ? [...new Set([...merged, ...allKnownScopes(service)])] : merged
502
701
  }
503
702
  const chars = resolveSummaryChars(args.summaryChars)
504
703
  try {
@@ -513,19 +712,31 @@ export function memorySearchTool(opts )
513
712
  })
514
713
  const inside = hits.filter((hit) => recordAllowed(policy, hit.record.scope, hit.record.kind))
515
714
  const outside = hits.filter((hit) => !recordAllowed(policy, hit.record.scope, hit.record.kind))
516
- let granted = false
715
+ // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
716
+ let verdict
517
717
  if (outside.length > 0 && level === 'normal') {
518
- granted = await askOutOfScope(
718
+ verdict = await askOutOfScope(
519
719
  service,
520
720
  agent,
521
721
  policy,
522
722
  'memory_search',
523
723
  args.query,
524
724
  outside.map((hit) => hit.record),
725
+ 'read',
525
726
  (exec )?.signal,
526
727
  )
527
728
  }
528
- const selected = granted ? hits : inside
729
+ // verdict 为空 = 没有发起审批(绝对限制 / 没有范围外命中):范围外一律不放行。
730
+ const approvedOutside = verdict === undefined
731
+ ? []
732
+ : verdict.outcome !== 'allowed-once'
733
+ ? []
734
+ : verdict.allowedIds === undefined
735
+ ? outside
736
+ : outside.filter((hit) => verdict .allowedIds .has(hit.record.id))
737
+ const insideIds = new Set(inside.map((hit) => hit.record.id))
738
+ const approvedOutsideIds = new Set(approvedOutside.map((hit) => hit.record.id))
739
+ const selected = hits.filter((hit) => insideIds.has(hit.record.id) || approvedOutsideIds.has(hit.record.id))
529
740
  const result = {
530
741
  records: selected.map((h) => ({
531
742
  id: h.record.id,
@@ -537,10 +748,14 @@ export function memorySearchTool(opts )
537
748
  summary: summarize(h.record.content, chars),
538
749
  })),
539
750
  }
540
- if (!granted && outside.length > 0) {
541
- result.withheld = { count: outside.length, reason: level === 'normal' ? 'rejected' : 'absolute' }
751
+ // absolute:范围外视为不存在,连"被挡住"都不告诉模型。
752
+ if (verdict !== undefined) {
753
+ const denied = outside.length - approvedOutside.length
754
+ if (denied > 0) result.withheld = { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome }
542
755
  }
543
756
  if (wantedTopK !== undefined) result.records = result.records.slice(0, wantedTopK)
757
+ // 上下文去重:同一条记忆同版本已经出现过 → 只回 id,摘要让 memory_get 按需取。
758
+ applySummaryDedupe(opts, exec, result.records)
544
759
  return result
545
760
  } catch (error) {
546
761
  throw toolError(error)
@@ -573,21 +788,90 @@ export function memoryForgetTool(opts )
573
788
  const service = svc(opts)
574
789
  if (!args.id && !args.query) throw new MemoryToolError('TARGET_REQUIRED', 'provide id or query')
575
790
  if (args.id && args.query) throw new MemoryToolError('TARGET_AMBIGUOUS', 'provide id or query, not both')
576
- // id 路径本来就跨 scope(精确 id 不会误删),不解析 scope。
791
+ const agent = agentOf(exec)
792
+ // 没有会话就不判断可见域:护栏只对"本会话的 Agent"生效(与 provider 一致)。
793
+ const policy = agent === undefined ? undefined : visibilityPolicy(service, agent)
794
+ const level = policy?.level ?? 'none'
795
+ const signal = (exec )?.signal
796
+ // ---- 按 id 删除:先查出这条记录在哪个 scope,再按可操作范围判断 ----
577
797
  if (args.id) {
798
+ const matches = (service.getByIds?.([args.id]) ?? []).filter((record) => record.id === args.id)
799
+ const blocked = matches.filter((record) => !recordAllowed(policy, record.scope, record.kind))
800
+ let approved = false
801
+ if (blocked.length > 0) {
802
+ if (level === 'absolute') {
803
+ // 绝对限制:范围外的记录"视为不存在",与真的没有这条 id 完全一样。
804
+ throw new MemoryToolError('RECORD_NOT_FOUND', `id ${args.id} not found`)
805
+ }
806
+ if (level === 'normal') {
807
+ const verdict = await askOutOfScope(
808
+ service,
809
+ agent,
810
+ policy,
811
+ 'memory_forget',
812
+ args.id,
813
+ blocked,
814
+ 'delete',
815
+ signal,
816
+ )
817
+ if (!verdictAllows(verdict, args.id)) {
818
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'delete', blocked[0] .scope)
819
+ }
820
+ approved = true
821
+ }
822
+ }
578
823
  try {
579
- return await service.forget({ id: args.id })
824
+ return await service.forget({
825
+ id: args.id,
826
+ ...(agent !== undefined ? { agent } : {}),
827
+ ...(approved ? { visibilityApproved: true } : {}),
828
+ })
580
829
  } catch (error) {
581
830
  throw toolError(error)
582
831
  }
583
832
  }
833
+ // ---- 按 query 删除:目标 scope 必须在可操作范围内 ----
584
834
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
585
835
  if (resolved.all) {
586
836
  throw new MemoryToolError('SCOPE_NOT_WRITABLE', "scope 'all' cannot be combined with query; name the scope you mean")
587
837
  }
588
- const scope = resolved.scope ?? readScopes(opts, service, agentOf(exec))[0]
838
+ const scope = resolved.scope ?? readScopes(opts, service, agent)[0]
839
+ let approved = false
840
+ if (level !== 'none' && scope !== undefined && !scopeOperable(service, agent, policy, scope)) {
841
+ if (level === 'absolute') {
842
+ // 绝对限制:这个作用域"不存在",按一条都没匹配处理(不删、也不泄露原因)。
843
+ return { removed: 0, ids: [] }
844
+ }
845
+ const verdict = await askOutOfScope(
846
+ service,
847
+ agent,
848
+ policy,
849
+ 'memory_forget',
850
+ `删除 ${scope} 中匹配「${args.query}」的记忆`,
851
+ [{
852
+ id: `query:${scope}`,
853
+ scope,
854
+ kind: 'note',
855
+ content: `按关键词「${args.query}」删除该作用域中匹配的记忆`,
856
+ tags: [],
857
+ importance: 0,
858
+ updatedAt: Date.now(),
859
+ }],
860
+ 'delete',
861
+ signal,
862
+ )
863
+ if (!verdictAllows(verdict, `query:${scope}`)) {
864
+ throw visibilityError(verdict.outcome === 'allowed-once' ? 'rejected' : verdict.outcome, 'delete', scope)
865
+ }
866
+ approved = true
867
+ }
589
868
  try {
590
- return await service.forget({ query: args.query, ...(scope !== undefined ? { scope } : {}) })
869
+ return await service.forget({
870
+ query: args.query,
871
+ ...(scope !== undefined ? { scope } : {}),
872
+ ...(agent !== undefined ? { agent } : {}),
873
+ ...(approved ? { visibilityApproved: true } : {}),
874
+ })
591
875
  } catch (error) {
592
876
  throw toolError(error)
593
877
  }
@@ -602,11 +886,14 @@ export function memoryForgetTool(opts )
602
886
 
603
887
 
604
888
 
605
-
889
+
606
890
                                 
607
891
 
608
-                            
609
-
892
+
893
+                              
894
+                   
895
+
896
+
610
897
 
611
898
 
612
899
  export function memoryListTool(opts ) {
@@ -623,10 +910,9 @@ export function memoryListTool(opts )
623
910
  const resolved = resolveScope(opts, service, exec, args.scope, 'read')
624
911
  const agent = agentOf(exec)
625
912
  const policy = visibilityPolicy(service, agent)
626
- const level = policy?.level
627
- const visible = policy !== undefined && level !== 'none'
628
- ? policy.scopes.map((rule) => rule.scope)
629
- : visibleScopeList(service, agent)
913
+ const level = policy?.level ?? 'none'
914
+ // level=none 时策略里的 scopes 只是偏好,不参与限制(等价于没有可见域)。
915
+ const visible = policy !== undefined && policy.level !== 'none' ? policy.scopes.map((rule) => rule.scope) : undefined
630
916
  let scopes
631
917
  if (resolved.all) {
632
918
  if (visible !== undefined) {
@@ -638,8 +924,6 @@ export function memoryListTool(opts )
638
924
  // 省略 scope:默认**只列当前会话**(按需求;读全部请显式 'all')。
639
925
  // 这是有意为之的窄口径,不因为"普通限制"就去列范围外的东西。
640
926
  scopes = readScopes(opts, service, agent).slice(0, 1)
641
- } else if (level === 'absolute') {
642
- assertScopeVisible(service, agent, resolved.scope)
643
927
  }
644
928
  let records
645
929
  let withheld
@@ -654,19 +938,32 @@ export function memoryListTool(opts )
654
938
  })
655
939
  const inside = raw.filter((record) => recordAllowed(policy, record.scope, record.kind))
656
940
  const outside = raw.filter((record) => !recordAllowed(policy, record.scope, record.kind))
657
- let granted = false
941
+ // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
942
+ let verdict
658
943
  if (outside.length > 0 && level === 'normal') {
659
- granted = await askOutOfScope(
944
+ verdict = await askOutOfScope(
660
945
  service,
661
946
  agent,
662
947
  policy,
663
948
  'memory_list',
664
949
  resolved.scope ?? args.scope ?? 'all',
665
950
  outside,
951
+ 'read',
666
952
  (exec )?.signal,
667
953
  )
668
954
  }
669
- const selected = (granted ? raw : inside).slice(0, limit)
955
+ const approvedOutside = verdict === undefined
956
+ ? []
957
+ : verdict.outcome !== 'allowed-once'
958
+ ? []
959
+ : verdict.allowedIds === undefined
960
+ ? outside
961
+ : outside.filter((record) => verdict .allowedIds .has(record.id))
962
+ const insideIds = new Set(inside.map((record) => record.id))
963
+ const approvedOutsideIds = new Set(approvedOutside.map((record) => record.id))
964
+ const selected = raw
965
+ .filter((record) => insideIds.has(record.id) || approvedOutsideIds.has(record.id))
966
+ .slice(0, limit)
670
967
  records = selected.map((r) => ({
671
968
  id: r.id,
672
969
  scope: r.scope,
@@ -674,8 +971,24 @@ export function memoryListTool(opts )
674
971
  updatedAt: r.updatedAt,
675
972
  content: r.content,
676
973
  }))
677
- if (!granted && outside.length > 0) {
678
- withheld = { count: outside.length, reason: level === 'normal' ? 'rejected' : 'absolute' }
974
+ if (verdict !== undefined) {
975
+ const denied = outside.length - approvedOutside.length
976
+ if (denied > 0) withheld = { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome }
977
+ }
978
+ // 上下文去重:同版本已经出现过 → 只回 id,正文让 memory_get 按需取。
979
+ const dedup = opts.contextDedup?.(exec)
980
+ if (dedup !== undefined && records.length > 0) {
981
+ const seen = dedup.seen(records)
982
+ const newlyShown = []
983
+ records = records.map((record) => {
984
+ if (!seen.has(record.id)) {
985
+ newlyShown.push(record)
986
+ return record
987
+ }
988
+ return { ...record, content: '', deduped: true }
989
+ })
990
+ // 这次真的把正文放进上下文的条目,后续检索/召回都按"已出现"处理。
991
+ if (newlyShown.length > 0) dedup.markContent(newlyShown)
679
992
  }
680
993
  } catch (error) {
681
994
  throw toolError(error)
@@ -728,8 +1041,11 @@ export const DEFAULT_GET_FIELDS = ['content', 'scope', 'kind', 'tags
728
1041
                            
729
1042
 
730
1043
 
731
-                              
732
-
1044
+
1045
+                                
1046
+                   
1047
+
1048
+
733
1049
 
734
1050
 
735
1051
  const FIELD_BY_LOWER = new Map (GET_FIELDS.map((field) => [field.toLowerCase(), field]))
@@ -815,28 +1131,41 @@ export function memoryGetTool(opts )
815
1131
  // 可见域是白名单:即使知道 id,也不能直接读别的范围/别的类型的正文。
816
1132
  const agent = agentOf(exec)
817
1133
  const policy = visibilityPolicy(service, agent)
818
- const level = policy?.level
1134
+ const level = policy?.level ?? 'none'
819
1135
  const inside = all.filter((record) => recordAllowed(policy, record.scope, record.kind))
820
1136
  const outside = all.filter((record) => !recordAllowed(policy, record.scope, record.kind))
821
- let granted = false
1137
+ // undefined = 没有范围外命中 / 绝对限制(不审批);只有普通限制会真的问一次。
1138
+ let verdict
822
1139
  if (outside.length > 0 && level === 'normal') {
823
- granted = await askOutOfScope(
1140
+ verdict = await askOutOfScope(
824
1141
  service,
825
1142
  agent,
826
1143
  policy,
827
1144
  'memory_get',
828
1145
  ids.join(' '),
829
1146
  outside,
1147
+ 'read',
830
1148
  (exec )?.signal,
831
1149
  )
832
1150
  }
833
- const found = granted ? all : inside
1151
+ // verdict 为空 = 没有发起审批(绝对限制):范围外一律按不存在处理。
1152
+ const approvedOutside = verdict === undefined
1153
+ ? []
1154
+ : verdict.outcome !== 'allowed-once'
1155
+ ? []
1156
+ : verdict.allowedIds === undefined
1157
+ ? outside
1158
+ : outside.filter((record) => verdict .allowedIds .has(record.id))
1159
+ const insideIds = new Set(inside.map((record) => record.id))
1160
+ const approvedIds = new Set(approvedOutside.map((record) => record.id))
1161
+ const found = all.filter((record) => insideIds.has(record.id) || approvedIds.has(record.id))
1162
+ const denied = outside.length - approvedOutside.length
834
1163
  return {
835
1164
  records: found.map((r) => pickGetFields(r, fields, chars)),
836
1165
  fields,
837
1166
  missing: ids.filter((token) => !found.some((r) => r.id === token || r.id.startsWith(token))),
838
- ...(!granted && outside.length > 0
839
- ? { withheld: { count: outside.length, reason: level === 'normal' ? 'rejected' : 'absolute' } }
1167
+ ...(verdict !== undefined && denied > 0
1168
+ ? { withheld: { count: denied, reason: verdict.outcome === 'allowed-once' ? 'partial' : verdict.outcome } }
840
1169
  : {}),
841
1170
  }
842
1171
  } catch (error) {