@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.
@@ -502,12 +502,26 @@ export function resolveConfig(config = {}) {
502
502
 
503
503
 
504
504
 
505
- /** 生效中的可见域(已剔除被 scope 开关禁用的项)。 */
505
+ /**
506
+ * 生效中的可见域(已剔除被 scope 开关禁用的项)。
507
+ *
508
+ * 0.20.0 起**永远有值**:没有显式覆盖时返回默认策略 ——
509
+ * 「当前会话 + 当前项目 + global」+ 普通限制。`source` 说明这份策略从哪来:
510
+ * - `explicit` = 本会话自己保存过可见范围;
511
+ * - `inherited` = 沿 parentSession 链继承来的显式范围;
512
+ * - `default` = 没有显式覆盖,用的默认策略。
513
+ * 工具层用 `source === 'default'` 区分"默认普通限制"(普通检索不主动把范围外
514
+ * 也搜一遍)与"用户显式设的普通限制"。
515
+ */
506
516
 
507
517
 
508
518
 
519
+
509
520
 
510
521
 
522
+ /** 范围外访问的动作(读取 / 写入 / 删除);审批浮层按它换文案。 */
523
+
524
+
511
525
  /** 一条"范围外"命中:给审批浮层展示的完整快照(不落盘,进程内存)。 */
512
526
 
513
527
 
@@ -525,6 +539,8 @@ export function resolveConfig(config = {}) {
525
539
 
526
540
 
527
541
 
542
+                         
543
+
528
544
                     
529
545
 
530
546
 
@@ -532,8 +548,20 @@ export function resolveConfig(config = {}) {
532
548
 
533
549
 
534
550
 
551
+ /** 一次审批的结局:允许(可只允许其中几条) / 拒绝 / 超时。 */
552
+
553
+
554
+ /**
555
+ * 审批结论(0.21.0)。`allowedIds` 省略 = 本次请求的所有条目都允许;
556
+ * 用户在审批卡里逐条勾选时只带被勾选的条目 id。
557
+ */
558
+
559
+
560
+
561
+
562
+
535
563
 
536
-
564
+
537
565
 
538
566
 
539
567
 
@@ -542,6 +570,12 @@ const VISIBILITY_APPROVAL_TTL_MS = 5 * 60_000
542
570
  /** 审批浮层一次最多展示多少条范围外命中(工具侧仍会返回全部允许的命中)。 */
543
571
  const VISIBILITY_APPROVAL_MAX_ITEMS = 20
544
572
 
573
+ /**
574
+ * 没有显式覆盖时的默认限制等级(0.20.0 起)。
575
+ * 默认范围 = 当前会话 + 当前项目 + global;范围外命中走一次审批。
576
+ */
577
+ export const DEFAULT_VISIBILITY_LEVEL = 'normal'
578
+
545
579
  export class LocalMemoryService {
546
580
  cfg
547
581
  store
@@ -1389,14 +1423,18 @@ export class LocalMemoryService {
1389
1423
  *
1390
1424
  * 起点用**当前会话自己的 id**(不是 resolveCurrentScopes 映射后的父会话):
1391
1425
  * 子 Agent 自己也可以有一份覆盖;没有时才沿链继承父会话 / 根会话。
1426
+ * `inherited` = 找到的那份覆盖不属于当前会话自己。
1392
1427
  */
1393
- visibilityForSession(sessionId ) {
1394
- let id = sessionId ?? ''
1428
+ resolveVisibility(
1429
+ sessionId ,
1430
+ ) {
1431
+ const own = sessionId ?? ''
1432
+ let id = own
1395
1433
  const seen = new Set ()
1396
1434
  while (id !== '' && !seen.has(id)) {
1397
1435
  seen.add(id)
1398
1436
  const found = this.visibility.get(id)
1399
- if (found !== undefined) return found
1437
+ if (found !== undefined) return { config: found, inherited: id !== own }
1400
1438
  let parent
1401
1439
  try {
1402
1440
  const session = this.sessionLookup?.(id)
@@ -1420,42 +1458,66 @@ export class LocalMemoryService {
1420
1458
  }
1421
1459
  }
1422
1460
 
1461
+ /** 没有显式覆盖时的默认可见域范围(当前会话 + 当前项目 + global,各自开关生效)。 */
1462
+ defaultReadScopes(agent ) {
1463
+ const refs = this.scopeRefs(agent)
1464
+ const out = []
1465
+ const push = (scope , enabled ) => {
1466
+ if (scope === undefined || !enabled || out.includes(scope)) return
1467
+ out.push(scope)
1468
+ }
1469
+ push(refs.session, this.cfg.sessionEnabled)
1470
+ push(refs.project, this.cfg.projectEnabled)
1471
+ push('global', this.cfg.globalEnabled)
1472
+ return out
1473
+ }
1474
+
1423
1475
  /**
1424
- * 显式「记忆可见域」的完整策略(含等级与每个 scope 的类型白名单)。
1425
- * undefined = 没有覆盖;level='none' 时 scopes 仍保留(供面板/下次切换),
1426
- * 但**不参与**读取限制。
1476
+ * 生效的「记忆可见域」。**永远有值**(0.20.0 起):没有显式覆盖时返回默认策略。
1477
+ * level='none' 时 scopes 仍保留(供面板/下次切换),但**不参与**读写限制。
1427
1478
  */
1428
- visibilityPolicy(agent ) {
1429
- const explicit = this.visibilityForSession(this.rawSessionIdOf(agent))
1430
- if (explicit === undefined) return undefined
1431
- return { level: explicit.level, scopes: this.filterEnabledRules(explicit.scopes) }
1479
+ visibilityPolicy(agent ) {
1480
+ const resolved = this.resolveVisibility(this.rawSessionIdOf(agent))
1481
+ if (resolved === undefined) {
1482
+ return {
1483
+ level: DEFAULT_VISIBILITY_LEVEL,
1484
+ scopes: this.defaultReadScopes(agent).map((scope) => ({ scope })),
1485
+ source: 'default',
1486
+ }
1487
+ }
1488
+ return {
1489
+ level: resolved.config.level,
1490
+ scopes: this.filterEnabledRules(resolved.config.scopes),
1491
+ source: resolved.inherited ? 'inherited' : 'explicit',
1492
+ }
1432
1493
  }
1433
1494
 
1434
1495
  /**
1435
- * 显式「记忆可见范围」的 scope 键列表。
1436
- * undefined = 不限制(没有覆盖,或等级为 none);
1496
+ * **显式**「可见范围」的 scope 键列表(不含默认策略,注入半边用它判断是否被
1497
+ * 显式白名单收窄,并决定要不要把 inject.extraScopes 关掉)。
1498
+ * undefined = 本会话没有显式覆盖(或等级为 none);
1437
1499
  * [] = 显式设置了范围但全部被 scope 开关禁用,调用方必须按空处理。
1438
1500
  */
1439
1501
  visibleScopes(agent ) {
1440
- const policy = this.visibilityPolicy(agent)
1441
- if (policy === undefined || policy.level === 'none') return undefined
1442
- return policy.scopes.map((rule) => this.canonicalScope(rule.scope))
1502
+ const resolved = this.resolveVisibility(this.rawSessionIdOf(agent))
1503
+ if (resolved === undefined || resolved.config.level === 'none') return undefined
1504
+ return this.filterEnabledRules(resolved.config.scopes).map((rule) => this.canonicalScope(rule.scope))
1443
1505
  }
1444
1506
 
1445
1507
  /** 某个 scope 下允许的记忆类型;undefined = 不限制(可见且没有类型白名单)。 */
1446
1508
  visibleKinds(agent , scope ) {
1447
1509
  const policy = this.visibilityPolicy(agent)
1448
- if (policy === undefined || policy.level === 'none') return undefined
1510
+ if (policy.level === 'none') return undefined
1449
1511
  const key = this.canonicalScope(scope)
1450
1512
  const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1451
1513
  if (rule === undefined) return []
1452
1514
  return rule.kinds !== undefined && rule.kinds.length > 0 ? [...rule.kinds] : undefined
1453
1515
  }
1454
1516
 
1455
- /** 一条记录(scope + kind)是否落在当前可见域内;等级 none / 无覆盖时恒为 true。 */
1517
+ /** 一条记录(scope + kind)是否落在当前可见域内;等级 none 时恒为 true。 */
1456
1518
  isRecordVisible(agent , scope , kind ) {
1457
1519
  const policy = this.visibilityPolicy(agent)
1458
- if (policy === undefined || policy.level === 'none') return true
1520
+ if (policy.level === 'none') return true
1459
1521
  const key = this.canonicalScope(scope)
1460
1522
  const rule = policy.scopes.find((item) => this.canonicalScope(item.scope) === key)
1461
1523
  if (rule === undefined) return false
@@ -1463,13 +1525,24 @@ export class LocalMemoryService {
1463
1525
  return rule.kinds.includes(kind)
1464
1526
  }
1465
1527
 
1528
+ /**
1529
+ * 一个作用域是否可读**且可写**(0.20.0 起「可见范围 = 可操作范围」,
1530
+ * save / forget 与读取共用这一份口径)。等级 none 时恒为 true。
1531
+ */
1532
+ isScopeOperable(agent , scope ) {
1533
+ const policy = this.visibilityPolicy(agent)
1534
+ if (policy.level === 'none') return true
1535
+ const key = this.canonicalScope(scope)
1536
+ return policy.scopes.some((item) => this.canonicalScope(item.scope) === key)
1537
+ }
1538
+
1466
1539
  /**
1467
1540
  * 批量过滤用的可见域判定(策略只解析一次,避免每条记录都走一遍 parentSession 链)。
1468
1541
  * undefined = 不限制。
1469
1542
  */
1470
1543
  visibilityFilterFor(agent ) {
1471
1544
  const policy = this.visibilityPolicy(agent)
1472
- if (policy === undefined || policy.level === 'none') return undefined
1545
+ if (policy.level === 'none') return undefined
1473
1546
  const byScope = new Map ()
1474
1547
  for (const rule of policy.scopes) {
1475
1548
  byScope.set(this.canonicalScope(rule.scope), rule.kinds !== undefined && rule.kinds.length > 0 ? rule.kinds : undefined)
@@ -1570,34 +1643,46 @@ export class LocalMemoryService {
1570
1643
  return out
1571
1644
  }
1572
1645
 
1573
- /** 普通限制:范围外命中时创建一条待审批,等待面板回答(超时按拒绝)。 */
1646
+ /**
1647
+ * 普通限制:范围外命中时创建一条待审批,等待面板回答。
1648
+ * 超时返回 `'timeout'`(和用户主动拒绝区分开,工具层要把真实原因告诉模型);
1649
+ * 调用被中止按拒绝处理。
1650
+ */
1574
1651
  requestOutOfScope(
1575
1652
  agent ,
1576
- input ,
1577
- ) {
1578
- if (input.items.length === 0) return Promise.resolve('allowed-once')
1579
- if (input.signal?.aborted) return Promise.resolve('rejected')
1653
+ input
1654
+
1655
+                     
1656
+
1657
+
1658
+
1659
+
1660
+ ,
1661
+ ) {
1662
+ if (input.items.length === 0) return Promise.resolve({ outcome: 'allowed-once' })
1663
+ if (input.signal?.aborted) return Promise.resolve({ outcome: 'rejected' })
1580
1664
  const sessionId = this.rawSessionIdOf(agent) ?? ''
1581
1665
  const id = `vis-${Date.now().toString(36)}-${++this.approvalSeq}`
1582
1666
  const createdAt = Date.now()
1583
1667
  const expiresAt = createdAt + VISIBILITY_APPROVAL_TTL_MS
1584
1668
  return new Promise((resolve) => {
1585
1669
  let timer
1586
- const onAbort = () => finish('rejected')
1587
- const finish = (outcome ) => {
1670
+ const onAbort = () => finish({ outcome: 'rejected' })
1671
+ const finish = (answer ) => {
1588
1672
  const pending = this.pendingApprovals.get(id)
1589
1673
  if (pending === undefined) return
1590
1674
  this.pendingApprovals.delete(id)
1591
1675
  if (timer !== undefined) clearTimeout(timer)
1592
1676
  try { input.signal?.removeEventListener('abort', onAbort) } catch { /* 已卸载 */ }
1593
- pending.resolve(outcome)
1677
+ pending.resolve(answer)
1594
1678
  }
1595
- timer = setTimeout(() => finish('rejected'), VISIBILITY_APPROVAL_TTL_MS)
1679
+ timer = setTimeout(() => finish({ outcome: 'timeout' }), VISIBILITY_APPROVAL_TTL_MS)
1596
1680
  timer.unref?.()
1597
1681
  this.pendingApprovals.set(id, {
1598
1682
  id,
1599
1683
  sessionId,
1600
1684
  tool: input.tool,
1685
+ action: input.action ?? 'read',
1601
1686
  query: input.query,
1602
1687
  items: input.items.slice(0, VISIBILITY_APPROVAL_MAX_ITEMS).map((item) => ({
1603
1688
  ...item,
@@ -1621,6 +1706,7 @@ export class LocalMemoryService {
1621
1706
  id: pending.id,
1622
1707
  sessionId: pending.sessionId,
1623
1708
  tool: pending.tool,
1709
+ action: pending.action,
1624
1710
  query: pending.query,
1625
1711
  // 轮询载荷保持轻量:正文截到 1200 字,悬浮需要全文时面板再按 id 取一次。
1626
1712
  items: pending.items.map((item) => ({
@@ -1636,41 +1722,72 @@ export class LocalMemoryService {
1636
1722
  }
1637
1723
 
1638
1724
  /** 面板:回答一条待审批。返回 false = 已经不存在/已超时。 */
1639
- answerVisibilityApproval(id , outcome ) {
1725
+ answerVisibilityApproval(id , outcome , allowedIds ) {
1640
1726
  const pending = this.pendingApprovals.get(id)
1641
1727
  if (pending === undefined) return false
1642
1728
  this.pendingApprovals.delete(id)
1643
1729
  if (pending.timer !== undefined) clearTimeout(pending.timer)
1644
- 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)
1645
1746
  return true
1646
1747
  }
1647
1748
 
1648
1749
  /**
1649
1750
  * 无显式 scope 时的**读取**合并集合:当前会话 + 当前项目 + global(各自开关生效、按 key 去重)。
1650
1751
  * 工具 / 注入都用它。会话设置了「可见范围」时以覆盖为准(不再并入默认集合)。
1752
+ * 没有显式覆盖时返回默认三路集合 —— 与默认可见域(`visibilityPolicy().source==='default'`)
1753
+ * 完全相同,所以"默认并没有限制"这句话在 0.20 之后不再成立。
1651
1754
  */
1652
1755
  resolveReadScopes(agent ) {
1653
1756
  const explicit = this.visibleScopes(agent)
1654
1757
  // level='none' 时 visibleScopes 返回 undefined:不限制读取,继续用默认三路集合。
1655
1758
  if (explicit !== undefined) return explicit
1656
- const refs = this.scopeRefs(agent)
1657
- const out = []
1658
- const push = (scope , enabled ) => {
1659
- if (scope === undefined || !enabled || out.includes(scope)) return
1660
- out.push(scope)
1759
+ return this.defaultReadScopes(agent)
1760
+ }
1761
+
1762
+ /**
1763
+ * 写入/删除护栏(0.20.0):可见范围 = 可操作范围。
1764
+ *
1765
+ * - absolute:范围外一律拒绝,而且**不暴露**这是可见域限制(视为不存在);
1766
+ * - normal:没经过审批就拒绝(工具层会用 `requestOutOfScope` 先问一次,
1767
+ * 批准后带 `visibilityApproved` 再调进来);
1768
+ * - none:不限制。
1769
+ */
1770
+ assertOperable(agent , scope ) {
1771
+ if (this.isScopeOperable(agent, scope)) return
1772
+ const level = this.visibilityPolicy(agent).level
1773
+ if (level === 'absolute') {
1774
+ throw memoryError('SCOPE_NOT_WRITABLE', `作用域 ${scope} 不存在或不可写`)
1661
1775
  }
1662
- push(refs.session, this.cfg.sessionEnabled)
1663
- push(refs.project, this.cfg.projectEnabled)
1664
- push('global', this.cfg.globalEnabled)
1665
- return out
1776
+ throw memoryError('VISIBILITY_APPROVAL_REQUIRED', `作用域 ${scope} 不在本会话的可操作范围内,需要用户审批`)
1666
1777
  }
1667
1778
 
1668
1779
  async save(input ) {
1669
1780
  // 省略 scope 时按当前会话落点 —— 会话上下文必须**从调用方带进来**
1670
1781
  // (工具 handler 拿得到 exec.agent,provider 自己看不到)。
1671
- const requestedScope = input.scope ?? this.resolveWriteScope((input ).agent)
1782
+ const saveAgent = (input ).agent
1783
+ const requestedScope = input.scope ?? this.resolveWriteScope(saveAgent)
1672
1784
  const scope = this.canonicalScope(requestedScope)
1673
1785
  this.assertScopeAllowed(scope)
1786
+ // 写入护栏:可见范围 = 可操作范围。工具层在普通限制下会先审批,批准后带
1787
+ // `visibilityApproved` 再来;面板写入不带 agent,不受会话可见域约束(用户本人操作)。
1788
+ if (saveAgent !== undefined && (input ).visibilityApproved !== true) {
1789
+ this.assertOperable(saveAgent, scope)
1790
+ }
1674
1791
  // 0.7.0:项目作用域可以带一个显示名(别名)。同一路径同名幂等,不同路径同名拒绝。
1675
1792
  const requestedName = (input ).name
1676
1793
  if (requestedName !== undefined && requestedName !== null && String(requestedName).trim() !== '') {
@@ -2072,11 +2189,28 @@ export class LocalMemoryService {
2072
2189
  return undefined
2073
2190
  }
2074
2191
 
2075
- async forget(input ) {
2192
+ /**
2193
+ * 删除记录。`agent` + 未审批时按可见域护栏处理(0.20.0):
2194
+ * 范围外一律**当作不存在** —— id 找不到、query 没有匹配,不泄露"被限制";
2195
+ * 普通限制下工具层会先审批,批准后带 `visibilityApproved` 再调进来。
2196
+ */
2197
+ async forget(input
2198
+
2199
+
2200
+
2201
+
2202
+
2203
+
2204
+ ) {
2205
+ const guardAgent = input.agent
2206
+ const approved = input.visibilityApproved === true
2207
+ const operable = (scope ) =>
2208
+ guardAgent === undefined || approved || this.isScopeOperable(guardAgent, scope)
2076
2209
  const ids = []
2077
2210
  if (input.id) {
2078
2211
  // 按 id 删除天然跨 scope:调用方给的是精确 id,不存在误删别的 scope 的风险。
2079
2212
  for (const s of this.store.allScopes()) {
2213
+ if (!operable(s.scope)) continue
2080
2214
  if (s.remove(input.id)) ids.push(input.id)
2081
2215
  }
2082
2216
  if (ids.length === 0) throw memoryError('RECORD_NOT_FOUND', `id ${input.id} not found`)
@@ -2092,6 +2226,7 @@ export class LocalMemoryService {
2092
2226
  for (const scope of targets) {
2093
2227
  if (seen.has(scope)) continue
2094
2228
  seen.add(scope)
2229
+ if (!operable(scope)) continue
2095
2230
  const store = this.store.peek(scope) // 读/删路径不创建
2096
2231
  if (!store) continue
2097
2232
  const hit = this.store.findIdsByQuery(scope, input.query)
@@ -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 } 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,11 +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
- return summary ? `${body}\n${summary}` : body
159
+ return [body, summary].filter((part) => part !== '').join('\n')
120
160
  })
121
161
 
122
162
  register(tools.memory_get, (value, _args, exec) => {