@restregular/dsh-memory 0.17.1 → 0.19.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.
@@ -103,10 +103,12 @@ import { canonicalWorkspacePath } from '../provider/scope.js'
103
103
 
104
104
  /** provider 在注入侧能提供的那部分能力(多余的方法都用可选判断)。 */
105
105
 
106
-
106
+
107
107
 
108
108
 
109
109
 
110
+                    
111
+
110
112
 
111
113
 
112
114
  /** 轮末提醒的文案:短、祈使句,不占预算。 */
@@ -114,6 +116,39 @@ const NUDGE_TEXT =
114
116
  '上一轮若产生了可复用的结论(决策、踩坑、流程、口径),先 memory_save 记一条再继续;' +
115
117
  '没有就忽略这条提醒。'
116
118
 
119
+ /** 可见域配置的最小子集(避免注入半边依赖 provider 的实现类型)。 */
120
+
121
+
122
+
123
+
124
+
125
+ const VISIBILITY_LEVEL_TEXT = {
126
+ absolute: '绝对限制:可见域外的记忆一律查不到,即使工具内部命中也不会返回。',
127
+ normal: '普通限制:可见域外的记忆命中时会向用户发起一次审批;用户拒绝或超时则不返回。',
128
+ none: '无限制:可以读取所有作用域与类型(当前选择仅作为下次切换的偏好保留)。',
129
+ }
130
+
131
+ /**
132
+ * 可见域变更后的上下文通知(以 user 消息注入)。
133
+ * 只描述规则,不回显任何记忆正文 —— 它要告诉模型"边界变了",不是给它数据。
134
+ */
135
+ export function renderVisibilityNotice(config ) {
136
+ if (config === null) {
137
+ return '【记忆可见范围已恢复默认】本会话不再有显式可见域;memory_search / memory_get / memory_list 回到"会话 + 项目 + global"的默认读取集合。'
138
+ }
139
+ const scopes = config.scopes.length > 0
140
+ ? config.scopes.map((rule) => (rule.kinds !== undefined && rule.kinds.length > 0
141
+ ? `${rule.scope}(仅 ${rule.kinds.join(' / ')})`
142
+ : rule.scope)).join('、')
143
+ : '(无)'
144
+ return [
145
+ '【记忆可见域已更新】用户修改了本会话(及其子 Agent)的记忆可见范围。',
146
+ `可见域:${scopes}`,
147
+ `限制等级:${VISIBILITY_LEVEL_TEXT[config.level]}`,
148
+ '后续 memory_search / memory_get / memory_list 请按这个边界工作;需要范围外信息时,先向用户说明要查什么,不要绕过限制。',
149
+ ].join('\n')
150
+ }
151
+
117
152
  export const name = 'dsh-memory-inject'
118
153
 
119
154
  export function apply(ctx , config = {}) {
@@ -238,6 +273,11 @@ export function apply(ctx , config = {}) {
238
273
 
239
274
  /** 系统提示 rules 段实际使用的 scope(与 section 回调保持同一口径)。 */
240
275
  const promptScopesFor = (memory , agent ) => {
276
+ try {
277
+ // 显式可见范围是白名单,空数组也照用(表示本会话看不到任何规则)。
278
+ const explicit = memory.visibleScopes?.(agent)
279
+ if (Array.isArray(explicit)) return explicit
280
+ } catch { /* fallthrough */ }
241
281
  try {
242
282
  const resolved = memory.resolveReadScopes?.(agent)
243
283
  if (Array.isArray(resolved) && resolved.length > 0) return resolved
@@ -248,13 +288,32 @@ export function apply(ctx , config = {}) {
248
288
  const sameScopes = (a , b ) =>
249
289
  a.length === b.length && a.every((scope, index) => scope === b[index])
250
290
 
291
+ /** 可见域的类型白名单(scope → kinds);undefined = 不按类型过滤。 */
292
+ const visibilityKindsFor = (memory , agent ) => {
293
+ try {
294
+ const policy = memory.visibilityPolicy?.(agent)
295
+ if (policy === undefined || policy.level === 'none') return undefined
296
+ const out = {}
297
+ for (const rule of policy.scopes) {
298
+ if (rule.kinds !== undefined && rule.kinds.length > 0) out[rule.scope] = [...rule.kinds]
299
+ }
300
+ return Object.keys(out).length > 0 ? out : undefined
301
+ } catch {
302
+ return undefined
303
+ }
304
+ }
305
+
251
306
  const renderRulesFor = (
252
307
  memory ,
253
308
  scopes ,
254
309
  cfg ,
310
+ agent ,
255
311
  ) => {
256
312
  try {
257
- return { ok: true, render: renderRules(memory.listSync?.({ scopes: [...scopes], kind: 'rule', limit: 100 }) ?? [], cfg) }
313
+ return {
314
+ ok: true,
315
+ render: renderRules(memory.listSync?.({ scopes: [...scopes], kind: 'rule', limit: 100, ...(agent !== undefined ? { agent } : {}) }) ?? [], cfg),
316
+ }
258
317
  } catch {
259
318
  return { ok: false, errorCode: 'source_load_failed' }
260
319
  }
@@ -490,7 +549,7 @@ export function apply(ctx , config = {}) {
490
549
  }
491
550
 
492
551
  const injector = new MemoryInjector(
493
- async (query, signal, scopes) => {
552
+ async (query, signal, scopes, kinds) => {
494
553
  const memory = ctx.get('memory')
495
554
  if (!memory?.search) return []
496
555
  return memory.search({
@@ -498,6 +557,7 @@ export function apply(ctx , config = {}) {
498
557
  signal,
499
558
  topK: recallCfg().topK,
500
559
  ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
560
+ ...(kinds !== undefined ? { kinds } : {}),
501
561
  })
502
562
  },
503
563
  recallCfg,
@@ -506,12 +566,13 @@ export function apply(ctx , config = {}) {
506
566
  )
507
567
 
508
568
  // 摘要:provider 没有 list(旧版/半边加载失败)时自动退化为"不发摘要"。
509
- const digester = new MemoryDigester(async (scopes) => {
569
+ const digester = new MemoryDigester(async (scopes, agent) => {
510
570
  const memory = ctx.get('memory')
511
571
  if (!memory?.list) return []
512
572
  return memory.list({
513
573
  ...(scopes !== undefined ? { scopes: [...scopes] } : {}),
514
574
  limit: 200,
575
+ ...(agent !== undefined ? { agent } : {}),
515
576
  })
516
577
  })
517
578
  // 持久化状态恢复后,把「摘要已做过」同步给摘要器,避免插件重载后重复注入。
@@ -695,7 +756,7 @@ export function apply(ctx , config = {}) {
695
756
  if (cached !== undefined && started !== undefined && cached.at >= started && sameScopes(cached.scopes, scopes)) {
696
757
  return cached.render.text
697
758
  }
698
- const rendered = renderRulesFor(memory, scopes, settingsOf().rules)
759
+ const rendered = renderRulesFor(memory, scopes, settingsOf().rules, context?.agent)
699
760
  if (!rendered.ok) return ''
700
761
  if (sessionId !== undefined) rulesCache.set(sessionId, { at: Date.now(), scopes, render: rendered.render })
701
762
  return rendered.render.text
@@ -712,7 +773,7 @@ export function apply(ctx , config = {}) {
712
773
  const sessionId = sessionIdOf(context?.agent)
713
774
  let records = []
714
775
  try {
715
- records = memory.listSync({ scopes: [...scopes], kind: 'procedure', limit: 200 })
776
+ records = memory.listSync({ scopes: [...scopes], kind: 'procedure', limit: 200, ...(context?.agent !== undefined ? { agent: context.agent } : {}) })
716
777
  } catch {
717
778
  return ''
718
779
  }
@@ -764,6 +825,11 @@ export function apply(ctx , config = {}) {
764
825
  attachSessionState(sessionId, workspaceOf(agent))
765
826
  if (sessionId !== undefined) rulesStepStart.set(sessionId, stepStartedAt)
766
827
  const scopes = readScopesFor(memory, agent)
828
+ // 可见域的类型白名单:召回/摘要/规则/流程索引都按它收窄,避免"只让看 global
829
+ // 的 rule"之后又从其它类型里召回正文。
830
+ const visibleKinds = visibilityKindsFor(memory, agent)
831
+ // 面板保存可见域后,下一次 pre-step 用一条 user 消息告知 Agent 边界已变。
832
+ const visibilityNotice = memory.takeVisibilityNotice?.(agent)
767
833
  if (sessionId !== undefined && scopes !== undefined) sessionScopes.set(sessionId, [...scopes])
768
834
  let autoScopes
769
835
  try { autoScopes = autoRecallScopes(memory.resolveReadScopes?.(agent) ) } catch { autoScopes = undefined }
@@ -817,6 +883,17 @@ export function apply(ctx , config = {}) {
817
883
  const messageChannels = new Set ()
818
884
  const stage = (entry ) => { staged.push(entry) }
819
885
 
886
+ // 可见域刚被用户改过:先告知边界,再走后续召回/摘要。只注入规则说明,不回显记忆。
887
+ if (visibilityNotice !== undefined) {
888
+ const noticeText = renderVisibilityNotice(visibilityNotice.config)
889
+ parts.push(noticeText)
890
+ messageChannels.add('policy')
891
+ stage(auditBase('policy', {
892
+ kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'visibility_changed',
893
+ delivery: { status: 'unknown', appended: null, textChars: noticeText.length, textHash: hashAuditText(noticeText) },
894
+ }))
895
+ }
896
+
820
897
  if (signal !== undefined && usableSignal === undefined) {
821
898
  recordAudit(auditBase('signal', {
822
899
  kind: 'signal', stage: 'signal_dropped', outcome: 'skipped',
@@ -904,7 +981,7 @@ export function apply(ctx , config = {}) {
904
981
  const rendered = renderDigest(records, settings.digest)
905
982
  digestStats = rendered?.stats
906
983
  return rendered
907
- })
984
+ }, agent)
908
985
  // 失败也记 done(与内存行为一致:摘要不逐轮重试);落盘后重载不再重复发。
909
986
  if (sessionId !== undefined && outcome.status !== 'skipped') injectionState.markDigestDone(sessionId)
910
987
  if (outcome.status === 'failed') {
@@ -966,7 +1043,7 @@ export function apply(ctx , config = {}) {
966
1043
  stage(auditBase('rules', { kind: 'evaluation', stage: 'skipped', outcome: 'skipped', reasonCode: 'system_prompt_unavailable' }))
967
1044
  } else {
968
1045
  const promptScopes = promptScopesFor(memory, agent)
969
- const rendered = renderRulesFor(memory, promptScopes, settings.rules)
1046
+ const rendered = renderRulesFor(memory, promptScopes, settings.rules, agent)
970
1047
  if (!rendered.ok) {
971
1048
  stage(auditBase('rules', {
972
1049
  kind: 'evaluation', stage: 'source_load', outcome: 'failed', reasonCode: rendered.errorCode,
@@ -1054,7 +1131,13 @@ export function apply(ctx , config = {}) {
1054
1131
  })
1055
1132
  }
1056
1133
  const recall = await injector.maybeInjectDetailed(
1057
- { messages: input.messages , signal: input.signal, ...(recallScopes !== undefined ? { scopes: recallScopes } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
1134
+ {
1135
+ messages: input.messages ,
1136
+ signal: input.signal,
1137
+ ...(recallScopes !== undefined ? { scopes: recallScopes } : {}),
1138
+ ...(visibleKinds !== undefined ? { kinds: visibleKinds } : {}),
1139
+ ...(sessionId !== undefined ? { sessionId } : {}),
1140
+ },
1058
1141
  { messages: decision.messages },
1059
1142
  {
1060
1143
  ...(sessionId !== undefined ? { sessionId } : {}),
@@ -35,6 +35,13 @@ export const defaultInjectConfig = {
35
35
 
36
36
 
37
37
 
38
+
39
+                              
40
+              
41
+
42
+
43
+                              
44
+
38
45
                             
39
46
 
40
47
                            
@@ -88,6 +95,15 @@ export function resolveInjectScopes(
88
95
  extraScopes ,
89
96
  sessions ,
90
97
  ) {
98
+ // 会话设置了显式可见范围时,它就是白名单:extraScopes / 父会话都不能把它撑大。
99
+ // 空数组也要原样返回(表示什么都不允许读),不能当成"没设置"。
100
+ let explicit
101
+ try {
102
+ const visible = memory.visibleScopes?.(agent)
103
+ if (Array.isArray(visible)) explicit = [...visible]
104
+ } catch { /* 拿不到覆盖就按默认集合 */ }
105
+ if (explicit !== undefined) return explicit
106
+
91
107
  const scopes = []
92
108
  try {
93
109
  for (const scope of memory.resolveReadScopes?.(agent) ?? []) {
@@ -126,6 +142,8 @@ export function resolveInjectScopes(
126
142
                                   
127
143
 
128
144
 
145
+                             
146
+
129
147
                              
130
148
 
131
149
 
@@ -309,13 +327,13 @@ export function recallText(text ) {
309
327
  * - 同一段文本 = 最后一道幂等。
310
328
  */
311
329
  export class MemoryInjector {
312
- search
330
+ search
313
331
  cfg
314
332
  renderOptions
315
333
  state
316
334
 
317
335
  constructor(
318
- search ,
336
+ search ,
319
337
  cfg ,
320
338
  renderOptions = {},
321
339
  state = new InjectionState(),
@@ -348,7 +366,7 @@ export class MemoryInjector {
348
366
 
349
367
  let hits
350
368
  try {
351
- hits = await this.search(query, input.signal, input.scopes)
369
+ hits = await this.search(query, input.signal, input.scopes, input.kinds)
352
370
  } catch {
353
371
  // 检索失败不能打断 agent 循环;审计会区分"失败"与"成功但无结果"。
354
372
  return {
@@ -446,10 +464,10 @@ const MAX_DIGESTED_SESSIONS = 500
446
464
  */
447
465
  export class MemoryDigester {
448
466
  done = new Set ()
449
- list
467
+ list
450
468
 
451
469
  constructor(
452
- list ,
470
+ list ,
453
471
  ) {
454
472
  this.list = list
455
473
  }
@@ -491,6 +509,7 @@ export class MemoryDigester {
491
509
  sessionId ,
492
510
  scopes ,
493
511
  render ,
512
+ agent ,
494
513
  )
495
514
 
496
515
 
@@ -501,7 +520,7 @@ export class MemoryDigester {
501
520
  this.markDone(sessionId)
502
521
  let records
503
522
  try {
504
- records = await this.list(scopes)
523
+ records = await this.list(scopes, agent)
505
524
  } catch {
506
525
  return { status: 'failed', errorCode: 'source_load_failed' }
507
526
  }
@@ -22,10 +22,12 @@ import { estimateTokens } from '../provider/rerank.js'
22
22
  import { supersededIds } from './digest.js'
23
23
 
24
24
  export const RULES_HEADER =
25
- '以下是必须遵守的硬性规则(来自 kind=rule 的记忆;除非用户明确要求破例,否则按它做):'
25
+ '以下是必须遵守的硬性规则(来自 kind=rule 的记忆,只注入摘要;每条开头的短 ID 可用于取全文,' +
26
+ '需要原文或细节时用 memory_get 按 ID 获取。除非用户明确要求破例,否则按它做):'
26
27
 
27
28
  export const RULES_DELTA_HEADER =
28
- '以下是新增或变更的硬性规则(来自 kind=rule 的记忆;从现在起按它做):'
29
+ '以下是新增或变更的硬性规则(来自 kind=rule 的记忆,只注入摘要;' +
30
+ '需要原文或细节时用 memory_get 按 ID 获取;从现在起按它做):'
29
31
 
30
32
  /** mandatory/pinned 是显式的标签约定,不把全部 kind=rule 自动升级。 */
31
33
  const MANDATORY_TAGS = new Set(['mandatory', 'pinned', '必含', '强制'])
@@ -40,9 +42,12 @@ export function isMandatoryRule(record ) {
40
42
  /**
41
43
  * 一条规则的渲染行。常驻段与增量块共用同一个格式 —— 增量靠"逐行比对"判断
42
44
  * 会话是否已经见过某条规则,两边只要有一个字符不同就会重复提醒。
45
+ *
46
+ * 0.18.0 起行首带 8 位短 ID(与摘要/召回索引同一口径):注入的是摘要,正文可能被
47
+ * 截断,模型需要完整规则时用 memory_get(前缀) 取。
43
48
  */
44
49
  export function ruleLine(record ) {
45
- return `- ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
50
+ return `- \`${record.id.slice(0, 8)}\` ${record.content.replace(/\s+/g, ' ').slice(0, 240)}`
46
51
  }
47
52
 
48
53
  /** 规则排序:mandatory 优先,其次重要度、新的在前,最后按内容稳定排序。 */
package/lib/panel.js CHANGED
@@ -26,7 +26,7 @@
26
26
  // scope 规范化与 provider 共用同一份实现。路径按**源码树位置**写:构建脚本的改写表
27
27
  // 会把它落成产物里的 `../provider/scope.js`(`lib/panel.js` → `lib/provider/scope.js`),
28
28
  // 在源码树里同一路径直接命中 source/memory-local/src —— 测试与真实加载都能解析。
29
- import { normalizeScopeInput } from './provider/scope.js'
29
+ import { normalizeScopeInput, resolveCurrentScopes } from './provider/scope.js'
30
30
 
31
31
 
32
32
  function writeJson(res, body, status = 200) {
@@ -40,7 +40,7 @@ function writeJson(res, body, status = 200) {
40
40
  const CLIENT_ERROR_CODES = new Set([
41
41
  'SCOPE_INVALID', 'SCOPE_DISABLED', 'CONTENT_EMPTY', 'CONTENT_TOO_LONG',
42
42
  'SECRET_DETECTED', 'IMPORT_INVALID', 'IMPORT_TOO_LARGE', 'KIND_INVALID',
43
- 'QUERY_EMPTY', 'QUERY_INVALID',
43
+ 'QUERY_EMPTY', 'QUERY_INVALID', 'SESSION_REQUIRED', 'SCOPE_EMPTY', 'SCOPE_NOT_VISIBLE',
44
44
  ])
45
45
 
46
46
  function writeError(res, error) {
@@ -470,6 +470,81 @@ function resolveScopeSelection(memory, rawScope) {
470
470
  return normalized.scope ?? null
471
471
  }
472
472
 
473
+ /** 面板已知的记忆类型(与工具的 kind enum 一致)。 */
474
+ const KNOWN_KINDS = ['fact', 'decision', 'preference', 'procedure', 'note', 'rule', 'state']
475
+
476
+ /**
477
+ * 会话「记忆可见域」的完整快照:自己的覆盖 + 生效策略 + 可选范围目录(含每个 scope
478
+ * 的类型统计)。
479
+ *
480
+ * 自己的覆盖(null = 没设置)用于面板上的"恢复默认";effective 用于预选(子 Agent
481
+ * 会话会继承父会话的覆盖);scopes 是本次会话可以勾选的全部具体作用域键 + 类型。
482
+ */
483
+ function visibilityPayload(ctx, memory, sessionId) {
484
+ let session
485
+ try { session = ctx.get('sessions')?.get?.(sessionId) } catch { session = undefined }
486
+ const agentLike = { session: session !== undefined ? session : { id: sessionId } }
487
+ const own = typeof memory.sessionVisibility === 'function' ? memory.sessionVisibility(sessionId) : null
488
+ let effective = null
489
+ let inherited = false
490
+ try {
491
+ if (typeof memory.visibilityPolicy === 'function') {
492
+ const policy = memory.visibilityPolicy(agentLike)
493
+ if (policy !== undefined && policy !== null) {
494
+ effective = policy
495
+ inherited = own === null
496
+ }
497
+ }
498
+ } catch { /* 可见域是增强;拿不到就只返回自己的覆盖 */ }
499
+
500
+ let refs
501
+ try { if (session !== undefined) refs = resolveCurrentScopes({ session }) } catch { refs = undefined }
502
+ const stats = typeof memory.scopeStats === 'function' ? memory.scopeStats() : []
503
+ const kindStats = typeof memory.scopeKindStats === 'function' ? memory.scopeKindStats() : []
504
+ const byScope = new Map()
505
+ for (const item of Array.isArray(stats) ? stats : []) {
506
+ if (item && typeof item.scope === 'string') byScope.set(item.scope, { ...item, kinds: [] })
507
+ }
508
+ // 即使还没有任何记录,也要能把"当前会话 / 当前项目 / global"勾进可见范围。
509
+ const ensure = (scope) => {
510
+ if (typeof scope === 'string' && scope !== '' && !byScope.has(scope)) {
511
+ byScope.set(scope, { scope, records: 0, pendingEmbeds: 0, kinds: [] })
512
+ }
513
+ }
514
+ ensure(refs?.session)
515
+ ensure(refs?.project)
516
+ ensure('global')
517
+ for (const item of Array.isArray(kindStats) ? kindStats : []) {
518
+ const bucket = item && typeof item.scope === 'string' ? byScope.get(item.scope) : undefined
519
+ if (bucket === undefined || typeof item.kind !== 'string' || item.kind === '') continue
520
+ bucket.kinds.push({ kind: item.kind, records: Number(item.records) || 0 })
521
+ }
522
+ const rank = (scope) => scope === refs?.session ? 0 : scope === refs?.project ? 1 : scope === 'global' ? 2 : 3
523
+ const scopes = [...byScope.values()]
524
+ .sort((a, b) => rank(a.scope) - rank(b.scope) || String(a.scope).localeCompare(String(b.scope)))
525
+ .map((item) => ({
526
+ ...item,
527
+ kinds: [...item.kinds].sort((a, b) => KNOWN_KINDS.indexOf(a.kind) - KNOWN_KINDS.indexOf(b.kind) || a.kind.localeCompare(b.kind)),
528
+ label: item.name ?? scopeLabel(ctx, item.scope),
529
+ }))
530
+ // 没有显式覆盖时,面板仍预选"当前默认读取集合"(会话 + 项目 + global),
531
+ // 让用户看到 Agent 现在实际能看到什么;保存后才变成显式覆盖。
532
+ let defaults = []
533
+ try {
534
+ const resolved = memory.resolveReadScopes?.(agentLike)
535
+ if (Array.isArray(resolved)) defaults = resolved
536
+ } catch { /* 降级为空 */ }
537
+ return {
538
+ sessionId,
539
+ override: own,
540
+ effective,
541
+ inherited,
542
+ defaults,
543
+ scopes,
544
+ kinds: KNOWN_KINDS,
545
+ }
546
+ }
547
+
473
548
  async function handle(ctx, routePath, req, res) {
474
549
  const url = new URL(req.url ?? '/', 'http://dsh.local')
475
550
  const path = url.pathname.slice(routePath.length) || '/'
@@ -539,6 +614,82 @@ async function handle(ctx, routePath, req, res) {
539
614
  // memories from earlier sessions included) — best-effort discovery, cached.
540
615
  discoverScopes(memory, store)
541
616
 
617
+ // 会话级「记忆可见范围」:输入框旁的按钮读写这一对接口。
618
+ if (method === 'GET' && path === '/visibility') {
619
+ if (typeof memory.sessionVisibility !== 'function') {
620
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
621
+ }
622
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
623
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
624
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
625
+ return
626
+ }
627
+ if (method === 'POST' && path === '/visibility') {
628
+ if (typeof memory.setSessionVisibility !== 'function') {
629
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话可见范围接口(请升级 @restregular/dsh-memory)')
630
+ }
631
+ const body = await readJsonBody(req)
632
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
633
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
634
+ let next = null
635
+ const rawConfig = body?.visibility
636
+ // 新协议:{ visibility: { scopes: [{ scope, kinds? }], level } } | null
637
+ // 兼容 0.18 的 { scopes: string[] | null }:按"绝对限制 + 全部类型"处理。
638
+ const rawScopes = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object'
639
+ ? rawConfig.scopes
640
+ : body?.scopes
641
+ if (rawScopes !== null && rawScopes !== undefined) {
642
+ if (!Array.isArray(rawScopes)) throw new ApiError(400, 'SCOPE_INVALID', 'scopes 必须是数组或 null')
643
+ if (rawScopes.length === 0) throw new ApiError(400, 'SCOPE_EMPTY', '至少选择一个可见范围')
644
+ const scopes = []
645
+ for (const raw of rawScopes) {
646
+ const scopeRaw = typeof raw === 'string' ? raw : raw?.scope
647
+ if (typeof scopeRaw !== 'string' || scopeRaw.trim() === '') {
648
+ throw new ApiError(400, 'SCOPE_INVALID', 'scope 必须是非空字符串')
649
+ }
650
+ const normalized = normalizeScopeInput(scopeRaw)
651
+ if (!normalized.ok) throw new ApiError(400, normalized.code, normalized.message)
652
+ if (normalized.kind === 'all' || normalized.kind === 'current-project' || normalized.kind === 'current-session') {
653
+ throw new ApiError(400, 'SCOPE_INVALID', `可见范围必须是具体作用域键: ${JSON.stringify(scopeRaw)}`)
654
+ }
655
+ if (normalized.scope === undefined || scopes.some((item) => item.scope === normalized.scope)) continue
656
+ const kinds = raw !== null && typeof raw === 'object' && Array.isArray(raw.kinds)
657
+ ? [...new Set(raw.kinds.map((kind) => String(kind).trim()).filter((kind) => kind !== ''))]
658
+ : []
659
+ scopes.push(kinds.length > 0 ? { scope: normalized.scope, kinds } : { scope: normalized.scope })
660
+ }
661
+ const levelRaw = rawConfig !== null && rawConfig !== undefined && typeof rawConfig === 'object' ? rawConfig.level : 'absolute'
662
+ const level = levelRaw === 'normal' || levelRaw === 'none' ? levelRaw : 'absolute'
663
+ next = { scopes, level }
664
+ }
665
+ memory.setSessionVisibility(sessionId, next)
666
+ writeJson(res, { ok: true, value: visibilityPayload(ctx, memory, sessionId) })
667
+ return
668
+ }
669
+
670
+ // 普通限制下的范围外访问审批:客户端浮层轮询待审批,用户点「拒绝 / 允许一次」后回写。
671
+ if (method === 'GET' && path === '/approvals') {
672
+ if (typeof memory.pendingVisibilityApprovals !== 'function') {
673
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
674
+ }
675
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
676
+ writeJson(res, { ok: true, value: { approvals: memory.pendingVisibilityApprovals(sessionId === '' ? undefined : sessionId) } })
677
+ return
678
+ }
679
+ if (method === 'POST' && path === '/approvals') {
680
+ if (typeof memory.answerVisibilityApproval !== 'function') {
681
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供可见域审批接口(请升级 @restregular/dsh-memory)')
682
+ }
683
+ const body = await readJsonBody(req)
684
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
685
+ if (id === '') throw new ApiError(400, 'APPROVAL_ID_REQUIRED', 'id 不能为空')
686
+ const outcome = body?.outcome === 'allowed-once' ? 'allowed-once' : body?.outcome === 'rejected' ? 'rejected' : ''
687
+ if (outcome === '') throw new ApiError(400, 'APPROVAL_OUTCOME_INVALID', 'outcome 必须是 allowed-once 或 rejected')
688
+ const answered = memory.answerVisibilityApproval(id, outcome)
689
+ writeJson(res, { ok: true, value: { answered } })
690
+ return
691
+ }
692
+
542
693
  if (method === 'GET' && path === '/status') {
543
694
  const stats = typeof memory.scopeStats === 'function'
544
695
  ? memory.scopeStats()
@@ -27,6 +27,15 @@ export class CordisMemoryService extends Service {
27
27
  constructor(ctx , config = {}) {
28
28
  super(ctx, 'memory')
29
29
  this.impl = new LocalMemoryService(config)
30
+ // 会话可见范围的继承要沿 parentSession 链走;这里只放一个惰性查询,
31
+ // sessions 服务晚于本插件就绪也能在真正解析时拿到。
32
+ this.impl.setSessionLookup((id) => {
33
+ try {
34
+ return (ctx.get('sessions') )?.get?.(id)
35
+ } catch {
36
+ return undefined
37
+ }
38
+ })
30
39
  // 0.11.1:同一个目录因为 `D:/x` 与 `D:\x` 写法不同而分叉成两个 scope 的历史数据,
31
40
  // 在装配期合并一次(每进程一次;失败只影响合并,不影响读写)。
32
41
  try {
@@ -229,6 +238,61 @@ export class CordisMemoryService extends Service {
229
238
  return this.impl.resolveReadScopes(agent)
230
239
  }
231
240
 
241
+ /** 显式「可见范围」覆盖(undefined = 未设置);工具用它判断是否限制 memory_get。 */
242
+ visibleScopes(agent ) {
243
+ return this.impl.visibleScopes(agent)
244
+ }
245
+
246
+ /** 完整可见域(等级 + 每个 scope 的类型白名单)。 */
247
+ visibilityPolicy(agent ) {
248
+ return this.impl.visibilityPolicy(agent)
249
+ }
250
+
251
+ /** 某个 scope 下允许的记忆类型(undefined = 不限制)。 */
252
+ visibleKinds(agent , scope ) {
253
+ return this.impl.visibleKinds(agent, scope)
254
+ }
255
+
256
+ /** 一条记录是否落在当前可见域内。 */
257
+ isRecordVisible(agent , scope , kind ) {
258
+ return this.impl.isRecordVisible(agent, scope, kind)
259
+ }
260
+
261
+ /** 面板:读取某会话自己的可见域(null = 未设置)。 */
262
+ sessionVisibility(sessionId ) {
263
+ return this.impl.sessionVisibility(sessionId)
264
+ }
265
+
266
+ /** 面板:设置/清除某会话的可见域(null = 恢复默认)。 */
267
+ setSessionVisibility(sessionId , config ) {
268
+ return this.impl.setSessionVisibility(sessionId, config)
269
+ }
270
+
271
+ /** 注入半边:下一次 pre-step 要注入的可见域变更通知(取走即删)。 */
272
+ takeVisibilityNotice(agent ) {
273
+ return this.impl.takeVisibilityNotice(agent)
274
+ }
275
+
276
+ /** 面板:每个 scope 下按类型统计条数。 */
277
+ scopeKindStats() {
278
+ return this.impl.scopeKindStats()
279
+ }
280
+
281
+ /** 普通限制:范围外访问审批(挂起,等面板回答)。 */
282
+ requestOutOfScope(agent , input ) {
283
+ return this.impl.requestOutOfScope(agent, input)
284
+ }
285
+
286
+ /** 面板:当前待审批列表。 */
287
+ pendingVisibilityApprovals(sessionId ) {
288
+ return this.impl.pendingVisibilityApprovals(sessionId)
289
+ }
290
+
291
+ /** 面板:回答一条待审批。 */
292
+ answerVisibilityApproval(id , outcome ) {
293
+ return this.impl.answerVisibilityApproval(id, outcome)
294
+ }
295
+
232
296
  /** 写路径默认 scope(省略 scope 时落到哪)。 */
233
297
  resolveWriteScope(agent , requested ) {
234
298
  return this.impl.resolveWriteScope(agent, requested)