@restregular/dsh-memory 0.24.1 → 0.25.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.
package/lib/client.js CHANGED
@@ -496,7 +496,7 @@ window.__ModuleLoader__.load({
496
496
  '.mem-scope-btn.is-absolute:hover,.mem-scope-btn.is-normal:hover,.mem-scope-btn.is-none:hover{background:var(--dsw-alias-interactive-bg-hover)}',
497
497
  '.mem-scope-btn svg{flex:none}',
498
498
  // 毛玻璃浮窗:半透明 + backdrop blur;不支持 backdrop-filter 时退回实心底。
499
- '.mem-scope-pop{position:fixed;z-index:80;width:340px;max-height:min(520px,72vh);display:flex;flex-direction:column;gap:8px;padding:12px;border:1px solid color-mix(in srgb,var(--dsw-alias-border-l2,var(--dsw-alias-border-l1)) 60%,transparent);border-radius:14px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 78%,transparent);-webkit-backdrop-filter:blur(20px) saturate(1.35);backdrop-filter:blur(20px) saturate(1.35);box-shadow:0 10px 28px rgba(0,0,0,.18);color:var(--dsw-alias-label-primary);font-size:13px;overflow:hidden}',
499
+ '.mem-scope-pop{position:fixed;z-index:80;width:340px;max-height:min(640px,84vh);display:flex;flex-direction:column;gap:8px;padding:12px;border:1px solid color-mix(in srgb,var(--dsw-alias-border-l2,var(--dsw-alias-border-l1)) 60%,transparent);border-radius:14px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 78%,transparent);-webkit-backdrop-filter:blur(20px) saturate(1.35);backdrop-filter:blur(20px) saturate(1.35);box-shadow:0 10px 28px rgba(0,0,0,.18);color:var(--dsw-alias-label-primary);font-size:13px;overflow:hidden}',
500
500
  '@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.mem-scope-pop{background:var(--dsw-specific-menu,var(--dsw-alias-bg-layer-1))}}',
501
501
  '.mem-scope-head{display:flex;align-items:center;gap:8px}',
502
502
  '.mem-scope-head h4{margin:0;font-size:13px;font-weight:600;line-height:1.4}',
@@ -549,6 +549,22 @@ window.__ModuleLoader__.load({
549
549
  '.mem-scope-reset:disabled,.mem-scope-save:disabled{opacity:.5;cursor:default;filter:none}',
550
550
  '.mem-scope-save:disabled{color:var(--dsw-alias-label-primary-foreground)}',
551
551
  '.mem-scope-err{padding:5px 8px;border-radius:8px;background:color-mix(in srgb,var(--dsw-alias-state-error-primary,#d33) 10%,transparent);color:var(--dsw-alias-state-error-primary,#d33);font-size:12px;line-height:1.5}',
552
+ // 0.25.0:面板改名「记忆权限」——展示 Agent 申请到的会话授权,可逐条撤销。
553
+ '.mem-grant-box{flex:none;display:flex;flex-direction:column;gap:5px;padding:6px 7px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:color-mix(in srgb,var(--dsw-alias-bg-layer-1) 72%,transparent);max-height:min(150px,22vh);overflow:auto;scrollbar-width:thin}',
554
+ '.mem-grant-box::-webkit-scrollbar{width:8px}',
555
+ '.mem-grant-box::-webkit-scrollbar-thumb{background:color-mix(in srgb,var(--dsw-alias-label-secondary) 32%,transparent);border-radius:999px;border:2px solid transparent;background-clip:padding-box}',
556
+ '.mem-grant-head{display:flex;align-items:center;gap:6px;font-size:11.5px;font-weight:600;line-height:1.5}',
557
+ '.mem-grant-head .spacer{flex:1}',
558
+ '.mem-grant-head .count{font-weight:400;color:var(--dsw-alias-label-secondary);font-size:10.5px}',
559
+ '.mem-grant-hint{font-size:10.5px;line-height:1.5;color:var(--dsw-alias-label-secondary)}',
560
+ '.mem-grant-item{display:flex;align-items:center;gap:6px;min-width:0;padding:3px 2px 0;border-top:1px dashed color-mix(in srgb,var(--dsw-alias-border-l1) 70%,transparent)}',
561
+ '.mem-grant-scope{flex:1;min-width:0;font-size:11.5px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
562
+ '.mem-grant-perm{flex:none;font-size:10px;color:var(--dsw-alias-label-secondary);padding:0 6px;border:1px solid var(--dsw-alias-border-l1);border-radius:999px;line-height:1.7;white-space:nowrap}',
563
+ '.mem-grant-pill{flex:none;font-size:9.5px;color:var(--dsw-alias-label-secondary);border:1px dashed var(--dsw-alias-border-l1);border-radius:999px;padding:0 6px;line-height:1.7;white-space:nowrap}',
564
+ '.mem-grant-revoke{flex:none;padding:1px 8px;border:1px solid color-mix(in srgb,var(--dsw-alias-state-error-primary,#d33) 45%,var(--dsw-alias-border-l1));border-radius:7px;background:transparent;color:color-mix(in srgb,var(--dsw-alias-state-error-primary,#d33) 78%,var(--dsw-alias-label-primary));font-size:10.5px;line-height:1.7;cursor:pointer}',
565
+ '.mem-grant-revoke:hover:not(:disabled){border-color:var(--dsw-alias-state-error-primary,#d33);color:var(--dsw-alias-state-error-primary,#d33)}',
566
+ '.mem-grant-revoke:disabled{opacity:.45;cursor:default}',
567
+ '.mem-grant-empty{font-size:10.5px;color:var(--dsw-alias-label-secondary);line-height:1.55}',
552
568
  // 范围外访问审批卡(0.21.0):注册在 conversation.input.dock,只在所属会话里显示。
553
569
  // 版式照抄宿主 dsh-client-ui-approval 的审批卡(strip + body + 右对齐动作行),
554
570
  // 尺寸/圆角/底色/阴影全走同一批主题 token;缺少 composer 变量时给出同样的回退值。
@@ -4570,6 +4586,9 @@ window.__ModuleLoader__.load({
4570
4586
  const [catalog, setCatalog] = React.useState([])
4571
4587
  const [search, setSearch] = React.useState('')
4572
4588
  const [anchor, setAnchor] = React.useState(null)
4589
+ const [grants, setGrants] = React.useState([])
4590
+ const [grantBusy, setGrantBusy] = React.useState('')
4591
+ const [grantError, setGrantError] = React.useState('')
4573
4592
  const wrapRef = React.useRef(null)
4574
4593
 
4575
4594
  React.useEffect(() => {
@@ -4680,6 +4699,46 @@ window.__ModuleLoader__.load({
4680
4699
  .finally(() => setLoading(false))
4681
4700
  }
4682
4701
 
4702
+ /**
4703
+ * 0.25.0:本会话的 Agent 授权(grants)。
4704
+ * 工具调用授予 / 面板撤销都会改变它,所以浮窗打开期间按 3 秒轮询,
4705
+ * 用户不重开面板也能看到 Agent 刚申请到的权限。
4706
+ */
4707
+ const loadGrants = () => {
4708
+ if (typeof sessionId !== 'string' || sessionId === '') return
4709
+ api(`grants?session=${encodeURIComponent(sessionId)}`)
4710
+ .then((value) => {
4711
+ setGrants(Array.isArray(value.grants) ? value.grants : [])
4712
+ setGrantError('')
4713
+ })
4714
+ .catch((e) => setGrantError(String((e && e.message) || e)))
4715
+ }
4716
+
4717
+ React.useEffect(() => {
4718
+ if (!open) return undefined
4719
+ loadGrants()
4720
+ if (typeof setInterval !== 'function') return undefined
4721
+ const timer = setInterval(() => {
4722
+ if (typeof document !== 'undefined' && document.hidden) return
4723
+ loadGrants()
4724
+ }, 3000)
4725
+ return () => clearInterval(timer)
4726
+ }, [open, sessionId])
4727
+
4728
+ /** 撤销一条本会话授权(继承自父会话的授权只能到父会话撤销)。 */
4729
+ const revokeGrant = (grant) => {
4730
+ if (!grant || grant.inherited === true) return
4731
+ const id = typeof grant.id === 'string' ? grant.id : ''
4732
+ if (id === '') return
4733
+ const owner = typeof grant.ownerSession === 'string' && grant.ownerSession !== '' ? grant.ownerSession : sessionId
4734
+ setGrantBusy(id)
4735
+ setGrantError('')
4736
+ api('grants', { session: owner, id, view: sessionId })
4737
+ .then((value) => setGrants(Array.isArray(value.grants) ? value.grants : []))
4738
+ .catch((e) => setGrantError(String((e && e.message) || e)))
4739
+ .finally(() => setGrantBusy(''))
4740
+ }
4741
+
4683
4742
  // 打开会话就加载一次:按钮上的数字来自这个会话的设置,不需要用户先点按钮。
4684
4743
  React.useEffect(() => {
4685
4744
  if (typeof sessionId !== 'string' || sessionId === '') return
@@ -4808,8 +4867,8 @@ window.__ModuleLoader__.load({
4808
4867
  h('button', {
4809
4868
  type: 'button',
4810
4869
  className: `mem-scope-btn is-${buttonLevel}`,
4811
- title: `${sourceText}记忆范围:${scopeCountText} · ${buttonLevelLabel}`,
4812
- 'aria-label': `${sourceText}记忆范围,${scopeCountText},${buttonLevelLabel}`,
4870
+ title: `${sourceText}记忆权限:${scopeCountText} · ${buttonLevelLabel}`,
4871
+ 'aria-label': `${sourceText}记忆权限,${scopeCountText},${buttonLevelLabel}`,
4813
4872
  'aria-expanded': open,
4814
4873
  onMouseDown: (event) => { try { event.preventDefault() } catch { /* keepFocus */ } },
4815
4874
  onClick: toggle,
@@ -4817,14 +4876,14 @@ window.__ModuleLoader__.load({
4817
4876
  h(NavLineIcon, { size: 14 }),
4818
4877
  data === null ? null : h('span', null, String(effectiveCount)),
4819
4878
  ),
4820
- open ? h('div', { className: 'mem-scope-pop', style: popStyle, role: 'dialog', 'aria-label': '记忆范围' },
4879
+ open ? h('div', { className: 'mem-scope-pop', style: popStyle, role: 'dialog', 'aria-label': '记忆权限' },
4821
4880
  h('div', { className: 'mem-scope-head' },
4822
- h('h4', null, '记忆范围'),
4881
+ h('h4', null, '记忆权限'),
4823
4882
  h('span', { className: 'spacer' }),
4824
4883
  h('span', { className: 'mem-scope-count' }, `已选 ${selectedCount}`),
4825
4884
  ),
4826
4885
  h('div', { className: 'hint' },
4827
- 'Agent 只能检索、读取、写入和删除勾选的作用域;限制等级决定范围外怎么处理。'),
4886
+ '可见范围内的作用域 Agent 能检索、读取、写入和删除;范围外与 Agent 申请到的会话授权见下方,限制等级决定范围外怎么处理。'),
4828
4887
  data && data.inherited
4829
4888
  ? h('div', { className: 'hint' }, '当前继承自父会话;保存后在本会话独立生效。')
4830
4889
  : null,
@@ -4842,6 +4901,37 @@ window.__ModuleLoader__.load({
4842
4901
  level === 'none'
4843
4902
  ? h('div', { className: 'mem-scope-note' }, '无限制:范围选择会保存,但暂不参与读取限制。')
4844
4903
  : null,
4904
+ // 0.25.0:Agent 申请到的会话授权(实时轮询 + 逐条撤销)。
4905
+ h('div', { className: 'mem-grant-box', 'aria-label': '本会话授权' },
4906
+ h('div', { className: 'mem-grant-head' },
4907
+ h('span', null, 'Agent 会话授权'),
4908
+ h('span', { className: 'spacer' }),
4909
+ h('span', { className: 'count' }, grants.length > 0 ? `${grants.length} 条` : '暂无'),
4910
+ ),
4911
+ h('div', { className: 'mem-grant-hint' }, 'Agent 通过 memory_scopes request 申请后出现在这里;撤销后它需要重新申请。'),
4912
+ grants.length === 0
4913
+ ? h('div', { className: 'mem-grant-empty' }, '暂无授权。')
4914
+ : grants.map((grant) => h('div', { className: 'mem-grant-item', key: grant.id || `${grant.scope}:${grant.grantedAt}` },
4915
+ h('span', {
4916
+ className: 'mem-grant-scope',
4917
+ title: `${grant.scope}${grant.grantedAt ? ` · ${fmtTime(grant.grantedAt)}` : ''}`,
4918
+ }, grant.label || grant.scope),
4919
+ h('span', { className: 'mem-grant-perm' },
4920
+ (Array.isArray(grant.permissions) ? grant.permissions : [])
4921
+ .map((permission) => (permission === 'write' ? '可写' : '只读')).join(' / ')),
4922
+ grant.inherited === true ? h('span', { className: 'mem-grant-pill' }, '继承') : null,
4923
+ h('button', {
4924
+ type: 'button',
4925
+ className: 'mem-grant-revoke',
4926
+ disabled: grant.inherited === true || grantBusy === grant.id,
4927
+ title: grant.inherited === true
4928
+ ? '继承自父会话的授权,请到父会话撤销'
4929
+ : '撤销这条授权(Agent 需要重新申请)',
4930
+ onClick: () => revokeGrant(grant),
4931
+ }, grantBusy === grant.id ? '撤销中…' : '撤销'),
4932
+ )),
4933
+ grantError ? h('div', { className: 'mem-scope-err' }, grantError) : null,
4934
+ ),
4845
4935
  h('div', { className: 'mem-scope-search' },
4846
4936
  h('input', {
4847
4937
  type: 'search',
@@ -5338,14 +5428,14 @@ window.__ModuleLoader__.load({
5338
5428
  } catch (error) {
5339
5429
  console.warn('[dsh-memory] 记忆审计视图注册失败:', error?.message)
5340
5430
  }
5341
- // 输入框工具行右侧:本会话「记忆可见范围」按钮。session 作用域的 list 槽,
5431
+ // 输入框工具行右侧:本会话「记忆权限」按钮。session 作用域的 list 槽,
5342
5432
  // owner 会把 sessionId 作为标准 prop 传进来;旧宿主没有这个槽时只少一个入口。
5343
5433
  try {
5344
5434
  slots.inject('conversation.input.right', () => slots.register({
5345
5435
  name: 'conversation.input.right',
5346
5436
  id: 'memory-visibility',
5347
5437
  order: 30,
5348
- label: () => '记忆范围',
5438
+ label: () => '记忆权限',
5349
5439
  }, MemoryVisibilityButton))
5350
5440
  } catch (error) {
5351
5441
  console.warn('[dsh-memory] 记忆可见范围按钮注册失败:', error?.message)
@@ -109,6 +109,13 @@ import { canonicalWorkspacePath } from '../provider/scope.js'
109
109
 
110
110
                     
111
111
 
112
+                      
113
+
114
+
115
+
116
+
117
+                        
118
+
112
119
 
113
120
 
114
121
  /** 轮末提醒的文案:短、祈使句,不占预算。 */
@@ -128,27 +135,80 @@ const VISIBILITY_LEVEL_TEXT = {
128
135
  none: '无限制:可以读写所有作用域(当前选择仅作为下次切换的偏好保留)。',
129
136
  }
130
137
 
131
- /**
132
- * 可见域变更后的上下文通知(以 user 消息注入)。
133
- * 只描述规则,不回显任何记忆正文 —— 它要告诉模型"边界变了",不是给它数据。
134
- */
135
- export function renderVisibilityNotice(config ) {
136
- if (config === null) {
137
- return '【记忆可见范围已恢复默认】'
138
- + '本会话不再有显式可见域,改回默认设置:当前会话 + 当前项目 + global 三个作用域,限制等级 = 普通限制'
139
- + '(范围外命中会先向用户审批;写入 / 删除范围外同样需要审批)。'
140
- }
141
- const scopes = config.scopes.length > 0
142
- ? config.scopes.map((rule) => (rule.kinds !== undefined && rule.kinds.length > 0
138
+ const VISIBILITY_LEVEL_SHORT = {
139
+ absolute: '绝对限制',
140
+ normal: '普通限制',
141
+ none: '无限制',
142
+ }
143
+
144
+ /** 一条权限变更(与 provider 的 PermissionNoticeChange 同形;注入半边不依赖其实现类型)。 */
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+             
153
+
154
+                       
155
+
156
+                        
157
+
158
+               
159
+
160
+                            
161
+
162
+
163
+
164
+ function permissionText(permissions ) {
165
+ const read = permissions.includes('read')
166
+ const write = permissions.includes('write')
167
+ if (read && write) return '读 + 写'
168
+ if (write) return '写入 / 删除'
169
+ return '只读'
170
+ }
171
+
172
+ function scopeListText(rules ) {
173
+ return rules.length > 0
174
+ ? rules.map((rule) => (rule.kinds !== undefined && rule.kinds.length > 0
143
175
  ? `${rule.scope}(仅 ${rule.kinds.join(' / ')})`
144
176
  : rule.scope)).join('、')
145
177
  : '(无)'
146
- return [
147
- '【记忆可见域已更新】用户修改了本会话(及其子 Agent)的记忆可见范围。',
148
- `可见域:${scopes}`,
149
- `限制等级:${VISIBILITY_LEVEL_TEXT[config.level]}`,
150
- '后续 memory_search / memory_get / memory_list 请按这个边界工作;需要范围外信息时,先向用户说明要查什么,不要绕过限制。',
151
- ].join('\n')
178
+ }
179
+
180
+ /**
181
+ * 「记忆权限」变更后的上下文通知(0.25.0,统一入口)。
182
+ *
183
+ * 0.25.0 起输入框的「记忆范围」改名「记忆权限」:可见范围变化与 Agent / 面板造成的
184
+ * 授权变化都走这一条 user 消息。只描述边界与权限,不回显任何记忆正文。
185
+ */
186
+ export function renderPermissionNotice(input ) {
187
+ const lines = ['【记忆权限已更新】']
188
+ if (input.visibilityChanged) {
189
+ if (input.visibility === null) {
190
+ lines.push('可见范围:已恢复默认(会话 + 项目 + global 及工作区绑定的作用域,限制等级:普通限制)。')
191
+ } else {
192
+ lines.push(`可见范围:${scopeListText(input.visibility.scopes)}`)
193
+ lines.push(`限制等级:${VISIBILITY_LEVEL_TEXT[input.visibility.level]}`)
194
+ }
195
+ } else if (input.effective !== undefined && input.effective !== null) {
196
+ lines.push(`可见范围(未变):${scopeListText(input.effective.scopes)},限制等级:${VISIBILITY_LEVEL_SHORT[input.effective.level]}。`)
197
+ }
198
+ const changes = input.changes ?? []
199
+ if (changes.length > 0) {
200
+ lines.push('本次授权变更:')
201
+ for (const change of changes) {
202
+ lines.push(`- ${change.event === 'granted' ? '已授予' : '已撤销'}:${change.scope}(${permissionText(change.permissions)})`)
203
+ }
204
+ }
205
+ if (input.grants !== undefined) {
206
+ lines.push(input.grants.length > 0
207
+ ? `当前会话授权:${input.grants.map((grant) => `${grant.scope}(${permissionText(grant.permissions)})`).join('、')}`
208
+ : '当前会话授权:(无)')
209
+ }
210
+ lines.push('请按新的权限边界工作:需要范围外信息时用 memory_scopes request 申请后再读取;被撤销的权限必须重新申请,不要绕过限制。')
211
+ return lines.join('\n')
152
212
  }
153
213
 
154
214
  export const name = 'dsh-memory-inject'
@@ -858,8 +918,25 @@ export function apply(ctx , config = {}) {
858
918
  // 可见域的类型白名单:召回/摘要/规则/流程索引都按它收窄,避免"只让看 global
859
919
  // 的 rule"之后又从其它类型里召回正文。
860
920
  const visibleKinds = visibilityKindsFor(memory, agent)
861
- // 面板保存可见域后,下一次 pre-step 用一条 user 消息告知 Agent 边界已变。
921
+ // 面板保存可见范围 / Agent 申请或用户撤销授权后,下一次 pre-step 用一条 user
922
+ // 消息告知 Agent 权限边界已变(0.25.0:两种变更统一走 renderPermissionNotice)。
862
923
  const visibilityNotice = memory.takeVisibilityNotice?.(agent)
924
+ const permissionNotice = memory.takePermissionNotice?.(agent)
925
+ const permissionChanges = (permissionNotice?.changes ?? [])
926
+ .filter((change) => change !== null && change !== undefined && typeof change.scope === 'string' && change.scope !== '')
927
+ .map((change) => ({
928
+ event: change.event === 'revoked' ? 'revoked' : 'granted' ,
929
+ scope: String(change.scope),
930
+ permissions: (Array.isArray(change.permissions) ? change.permissions : [])
931
+ .filter((permission) => permission === 'read' || permission === 'write'),
932
+ }))
933
+ const permissionGrants = (permissionNotice?.grants ?? [])
934
+ .filter((grant) => grant !== null && grant !== undefined && typeof grant.scope === 'string' && grant.scope !== '')
935
+ .map((grant) => ({
936
+ scope: String(grant.scope),
937
+ permissions: (Array.isArray(grant.permissions) ? grant.permissions : [])
938
+ .filter((permission) => permission === 'read' || permission === 'write'),
939
+ }))
863
940
  if (sessionId !== undefined && scopes !== undefined) sessionScopes.set(sessionId, [...scopes])
864
941
  let autoScopes
865
942
  try { autoScopes = autoRecallScopes(memory.resolveReadScopes?.(agent) ) } catch { autoScopes = undefined }
@@ -913,13 +990,32 @@ export function apply(ctx , config = {}) {
913
990
  const messageChannels = new Set ()
914
991
  const stage = (entry ) => { staged.push(entry) }
915
992
 
916
- // 可见域刚被用户改过:先告知边界,再走后续召回/摘要。只注入规则说明,不回显记忆。
917
- if (visibilityNotice !== undefined) {
918
- const noticeText = renderVisibilityNotice(visibilityNotice.config)
993
+ // 权限边界刚被改过(可见范围 / 会话授权):先告知,再走后续召回/摘要。只注入规则说明,不回显记忆。
994
+ if (visibilityNotice !== undefined || permissionChanges.length > 0) {
995
+ let effective
996
+ try {
997
+ const policy = memory.visibilityPolicy?.(agent)
998
+ if (policy !== undefined && policy !== null) {
999
+ const level = policy.level === 'absolute' || policy.level === 'none' ? policy.level : 'normal'
1000
+ const rules = Array.isArray(policy.scopes)
1001
+ ? policy.scopes.flatMap((rule) => (rule !== null && rule !== undefined && typeof rule.scope === 'string' && rule.scope !== ''
1002
+ ? [{ scope: rule.scope, ...(Array.isArray(rule.kinds) && rule.kinds.length > 0 ? { kinds: rule.kinds.map(String) } : {}) }]
1003
+ : []))
1004
+ : []
1005
+ effective = { level, scopes: rules }
1006
+ }
1007
+ } catch { effective = undefined }
1008
+ const noticeText = renderPermissionNotice({
1009
+ visibilityChanged: visibilityNotice !== undefined,
1010
+ visibility: visibilityNotice?.config ?? null,
1011
+ ...(effective !== undefined ? { effective } : {}),
1012
+ ...(permissionChanges.length > 0 ? { changes: permissionChanges } : {}),
1013
+ ...(permissionNotice?.grants !== undefined ? { grants: permissionGrants } : {}),
1014
+ })
919
1015
  parts.push(noticeText)
920
1016
  messageChannels.add('policy')
921
1017
  stage(auditBase('policy', {
922
- kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'visibility_changed',
1018
+ kind: 'evaluation', stage: 'rendered', outcome: 'success', reasonCode: 'permission_changed',
923
1019
  delivery: { status: 'unknown', appended: null, textChars: noticeText.length, textHash: hashAuditText(noticeText) },
924
1020
  }))
925
1021
  }
package/lib/panel.js CHANGED
@@ -589,6 +589,39 @@ function visibilityPayload(ctx, memory, sessionId) {
589
589
  }
590
590
  }
591
591
 
592
+ /**
593
+ * 面板「记忆权限」的授权快照(0.25.0)。
594
+ *
595
+ * grants 由 Agent 通过 memory_scopes request 申请、用户批准产生;这里只暴露
596
+ * scope / 权限 / 授予时间,不返回任何记忆正文。`inherited` 表示这条授权属于父会话。
597
+ */
598
+ function grantsPayload(ctx, memory, sessionId) {
599
+ const list = []
600
+ let grants = []
601
+ try {
602
+ grants = typeof memory.sessionGrants === 'function' ? memory.sessionGrants(sessionId) : []
603
+ } catch { grants = [] }
604
+ for (const grant of Array.isArray(grants) ? grants : []) {
605
+ if (!grant || typeof grant.scope !== 'string' || grant.scope === '') continue
606
+ const permissions = Array.isArray(grant.permissions)
607
+ ? grant.permissions.filter((permission) => permission === 'read' || permission === 'write')
608
+ : []
609
+ if (permissions.length === 0) continue
610
+ const ownerSession = typeof grant.sessionId === 'string' && grant.sessionId !== '' ? grant.sessionId : sessionId
611
+ list.push({
612
+ id: typeof grant.id === 'string' ? grant.id : '',
613
+ scope: grant.scope,
614
+ label: scopeLabel(ctx, grant.scope),
615
+ permissions,
616
+ grantedAt: typeof grant.grantedAt === 'number' ? grant.grantedAt : 0,
617
+ ownerSession,
618
+ inherited: ownerSession !== sessionId,
619
+ })
620
+ }
621
+ list.sort((a, b) => a.grantedAt - b.grantedAt || a.scope.localeCompare(b.scope))
622
+ return { sessionId, grants: list }
623
+ }
624
+
592
625
  async function handle(ctx, routePath, req, res) {
593
626
  const url = new URL(req.url ?? '/', 'http://dsh.local')
594
627
  const path = url.pathname.slice(routePath.length) || '/'
@@ -771,6 +804,32 @@ async function handle(ctx, routePath, req, res) {
771
804
  return
772
805
  }
773
806
 
807
+ // 面板「记忆权限」:Agent 申请到的会话授权 + 撤销(0.25.0)。
808
+ if (method === 'GET' && path === '/grants') {
809
+ if (typeof memory.sessionGrants !== 'function') {
810
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供会话授权接口(请升级 @restregular/dsh-memory)')
811
+ }
812
+ const sessionId = (url.searchParams.get('session') ?? '').trim()
813
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 参数不能为空')
814
+ writeJson(res, { ok: true, value: grantsPayload(ctx, memory, sessionId) })
815
+ return
816
+ }
817
+ if (method === 'POST' && path === '/grants') {
818
+ if (typeof memory.revokeGrant !== 'function') {
819
+ throw new ApiError(501, 'NOT_SUPPORTED', 'provider 未提供授权撤销接口(请升级 @restregular/dsh-memory)')
820
+ }
821
+ const body = await readJsonBody(req)
822
+ const sessionId = typeof body?.session === 'string' ? body.session.trim() : ''
823
+ const id = typeof body?.id === 'string' ? body.id.trim() : ''
824
+ if (sessionId === '') throw new ApiError(400, 'SESSION_REQUIRED', 'session 不能为空')
825
+ if (id === '') throw new ApiError(400, 'GRANT_ID_REQUIRED', 'id 不能为空')
826
+ const revoked = memory.revokeGrant(sessionId, id)
827
+ if (!revoked) throw new ApiError(404, 'GRANT_NOT_FOUND', '没有找到这条授权(可能已撤销或已过期)')
828
+ const view = typeof body?.view === 'string' && body.view.trim() !== '' ? body.view.trim() : sessionId
829
+ writeJson(res, { ok: true, value: grantsPayload(ctx, memory, view) })
830
+ return
831
+ }
832
+
774
833
  if (method === 'GET' && path === '/status') {
775
834
  const stats = typeof memory.scopeStats === 'function'
776
835
  ? memory.scopeStats()
@@ -338,6 +338,16 @@ export class CordisMemoryService extends Service {
338
338
  return this.impl.takeVisibilityNotice(agent)
339
339
  }
340
340
 
341
+ /** 面板「记忆权限」:某会话当前有效授权(含父会话继承)。 */
342
+ sessionGrants(sessionId ) {
343
+ return this.impl.sessionGrants(sessionId)
344
+ }
345
+
346
+ /** 注入半边:下一次 pre-step 要注入的权限变更通知(取走即删)。 */
347
+ takePermissionNotice(agent ) {
348
+ return this.impl.takePermissionNotice(agent)
349
+ }
350
+
341
351
  /** 面板:每个 scope 下按类型统计条数。 */
342
352
  scopeKindStats() {
343
353
  return this.impl.scopeKindStats()
@@ -70,6 +70,23 @@ import {
70
70
  import { probeHardware, } from './hardware.js'
71
71
  import { pickFlavor, recommendModel } from './recommend.js'
72
72
 
73
+ /**
74
+ * 一条权限变更(授予 / 撤销)。面板改名「记忆权限」后,工具授予与面板撤销
75
+ * 都通过它进入注入链路,Agent 下一轮就能看到自己的权限边界变了。
76
+ */
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+ /** 注入半边要的权限快照:本次变更 + 当前有效授权。 */
85
+
86
+
87
+
88
+
89
+
73
90
  /** Recursive byte count; 0 for anything unreadable. */
74
91
  function pathSize(path ) {
75
92
  try {
@@ -689,6 +706,8 @@ export class LocalMemoryService {
689
706
  approvalAudit
690
707
  /** 可见域变更通知:下一次 pre-step 注入给 Agent 后删除(按会话)。 */
691
708
  visibilityNotices = new Map ()
709
+ /** 权限变更通知(0.25.0):授予 / 撤销;下一次 pre-step 注入给 Agent 后删除。 */
710
+ permissionNotices = new Map ()
692
711
  /** 普通限制下等待用户审批的范围外访问(按审批 id)。 */
693
712
  pendingApprovals = new Map ()
694
713
  approvalSeq = 0
@@ -2158,6 +2177,12 @@ export class LocalMemoryService {
2158
2177
  ...(meta !== undefined ? { scopeGeneration: meta.generation } : {}),
2159
2178
  })
2160
2179
  granted.push(grant)
2180
+ this.recordPermissionNotice(sessionId, {
2181
+ event: 'granted',
2182
+ scope: item.scope,
2183
+ permissions: [item.permission],
2184
+ by: 'agent',
2185
+ })
2161
2186
  this.approvalAudit.append({
2162
2187
  at: Date.now(),
2163
2188
  event: 'granted',
@@ -2180,10 +2205,67 @@ export class LocalMemoryService {
2180
2205
  return this.validGrants(agent)
2181
2206
  }
2182
2207
 
2183
- /** 面板:撤销某会话的一条授权。 */
2208
+ /**
2209
+ * 面板「记忆权限」:某会话当前有效授权(含父会话继承)。
2210
+ * grant.sessionId 标明授权来自哪个会话;与入参不同 = 继承自父会话,面板不可直接撤销。
2211
+ */
2212
+ sessionGrants(sessionId ) {
2213
+ if (typeof sessionId !== 'string' || sessionId.trim() === '') return []
2214
+ const agentLike = { session: { header: { id: sessionId.trim() } } }
2215
+ try {
2216
+ return this.validGrants(agentLike)
2217
+ } catch {
2218
+ return []
2219
+ }
2220
+ }
2221
+
2222
+ /**
2223
+ * 取出并删除待注入的「权限变更」通知(0.25.0),同时附上当前有效授权快照。
2224
+ * 沿 parentSession 链找:子 Agent 继承父会话的授权,也应当收到父会话的授权变化。
2225
+ */
2226
+ takePermissionNotice(agent ) {
2227
+ let id = this.rawSessionIdOf(agent) ?? ''
2228
+ const seen = new Set ()
2229
+ while (id !== '' && !seen.has(id)) {
2230
+ seen.add(id)
2231
+ const found = this.permissionNotices.get(id)
2232
+ if (found !== undefined) {
2233
+ this.permissionNotices.delete(id)
2234
+ let grants = []
2235
+ try { grants = this.validGrants(agent) } catch { grants = [] }
2236
+ return { changes: [...found.changes], grants }
2237
+ }
2238
+ let parent
2239
+ try {
2240
+ const session = this.sessionLookup?.(id)
2241
+ parent = typeof session?.header?.parentSession === 'string' && session.header.parentSession !== ''
2242
+ ? session.header.parentSession
2243
+ : undefined
2244
+ } catch { parent = undefined }
2245
+ id = parent ?? ''
2246
+ }
2247
+ return undefined
2248
+ }
2249
+
2250
+ /** 记一条待注入的权限变更(同一会话合并,pre-step 一次性取走)。 */
2251
+ recordPermissionNotice(sessionId , change ) {
2252
+ if (typeof sessionId !== 'string' || sessionId === '') return
2253
+ const existing = this.permissionNotices.get(sessionId)
2254
+ if (existing === undefined) {
2255
+ this.permissionNotices.set(sessionId, { at: Date.now(), changes: [change] })
2256
+ return
2257
+ }
2258
+ existing.changes.push(change)
2259
+ existing.at = Date.now()
2260
+ }
2261
+
2262
+ /** 面板:撤销某会话的一条授权。已撤销 / 已过期的 id 返回 false(幂等语义下也算未找到)。 */
2184
2263
  revokeGrant(sessionId , id ) {
2185
2264
  if (typeof sessionId !== 'string' || sessionId === '') return false
2265
+ // list() 已过滤撤销 / 过期:拿不到 before 说明这条授权已经不在生效集合里,
2266
+ // 不能再让 store.revoke() 对历史条目再写一次撤销(否则面板会 404 之外还误报成功)。
2186
2267
  const before = this.grants.list(sessionId).find((grant) => grant.id === id)
2268
+ if (before === undefined) return false
2187
2269
  const ok = this.grants.revoke(sessionId, id)
2188
2270
  if (ok) {
2189
2271
  this.approvalAudit.append({
@@ -2194,9 +2276,16 @@ export class LocalMemoryService {
2194
2276
  tool: 'memory_scopes',
2195
2277
  action: 'revoke',
2196
2278
  mode: 'grant',
2197
- ...(before !== undefined ? { scopes: [before.scope], permissions: before.permissions } : {}),
2279
+ scopes: [before.scope],
2280
+ permissions: before.permissions,
2198
2281
  outcome: 'revoked',
2199
2282
  })
2283
+ this.recordPermissionNotice(sessionId, {
2284
+ event: 'revoked',
2285
+ scope: before.scope,
2286
+ permissions: [...before.permissions],
2287
+ by: 'user',
2288
+ })
2200
2289
  }
2201
2290
  return ok
2202
2291
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.24.1",
3
+ "version": "0.25.0",
4
4
  "description": "DeepSeek Harness 记忆系统(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",