dsh-better-chat/src/client/chat/permission-policy.ts

323 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 功能二:权限策略 —— 去掉「完全权限」选项,新会话默认「自动审查」。
*
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供,开启后才
* 出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里也选不到它。
*
* 本模块做两件事:
* 1. 界面移除「完全权限」:观察 DOM,把选择器/菜单/设置下拉里标签为「完全
* 权限 / Full access」的选项摘掉。只动界面,手动输入命令仍可达。
* 2. 新建/空白会话默认「自动审查」:首次见到空白顶层会话且其权限不是 auto
* 时,通过宿主命令通道 `/permission auto` 切过去。已处理过的会话 id 会
* 持久化在 localStorage(`dsh.better-chat.permission-handled.v1`),且已
* 有对话内容的会话(`blank === false`)和子代理会话不会被改写;用户手
* 动切回只读/工作区修改后,刷新或重载也不会被覆盖。
*/
/** 完全权限的预设机器值。 */
export const FULL_ACCESS_PRESET = 'danger-full-access'
/** 自动审查的预设机器值。 */
export const AUTO_REVIEW_PRESET = 'auto'
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
export const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
/** 已处理会话 id 的浏览器持久化键,避免刷新后覆盖用户手动改过的权限。 */
export const HANDLED_STORAGE_KEY = 'dsh.better-chat.permission-handled.v1'
const MAX_HANDLED_IDS = 500
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
export function isFullAccessLabel(text: unknown): boolean {
if (typeof text !== 'string') return false
const trimmed = text.trim()
return FULL_ACCESS_LABELS.some((label) => trimmed === label || trimmed.startsWith(label))
}
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
export function shouldAutoSwitch(preset: string | undefined | null, alreadyHandled: boolean): boolean {
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
}
export interface LiveSession {
id: string
live: any
}
/**
* 防御式枚举宿主的 live 会话:
* 1. `keys() + binding()`(测试桩或旧形状)
* 2. DSH 0.2.2 `ClientSessions`:`scopes` Map 与 `list.getSnapshot()`(`ids` / `byId`)配合 `binding(id)`
* 3. `list()` 函数回退
* 服务形状对不上时安静返回空数组,绝不抛错。
*/
export function liveSessions(sessions: any): LiveSession[] {
const out: LiveSession[] = []
if (!sessions || typeof sessions !== 'object') return out
try {
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
for (const id of sessions.keys()) {
const live = sessions.binding(id)?.session
if (live) out.push({ id, live })
}
return out
}
if (typeof sessions.binding === 'function' || sessions.scopes instanceof Map) {
const seen = new Set<string>()
const addCandidate = (id: unknown) => {
if (typeof id !== 'string' || !id || seen.has(id)) return
const live =
(typeof sessions.binding === 'function' ? sessions.binding(id)?.session : undefined) ??
(sessions.scopes instanceof Map ? sessions.scopes.get(id)?.binding?.session : undefined)
if (live) {
seen.add(id)
out.push({ id, live })
}
}
if (sessions.scopes instanceof Map) {
for (const id of sessions.scopes.keys()) addCandidate(id)
}
const listSnap = typeof sessions.list?.getSnapshot === 'function' ? sessions.list.getSnapshot() : undefined
if (Array.isArray(listSnap?.ids)) {
for (const id of listSnap.ids) addCandidate(id)
}
if (listSnap?.byId && typeof listSnap.byId === 'object') {
for (const id of Object.keys(listSnap.byId)) addCandidate(id)
}
if (out.length > 0 || typeof sessions.list !== 'function') return out
}
if (typeof sessions.list === 'function') {
for (const session of (sessions.list() ?? []) as any[]) {
if (session && session.sessionId) out.push({ id: session.sessionId, live: session })
}
}
} catch {
// 服务形状不同:放弃枚举
}
return out
}
/**
* 读会话当前的权限预设值(投影不可用时返回 undefined)。
* 兼容 DSH 0.2.2 的 `{ currentValue: string }` 投影视图与直接返回字符串的测试桩。
*/
export function currentPreset(live: any): string | undefined {
try {
const snap = live?.projections?.faceOf?.('permissions')?.getSnapshot?.()
if (typeof snap === 'string') return snap
if (snap && typeof snap === 'object' && typeof (snap as { currentValue?: unknown }).currentValue === 'string') {
return (snap as { currentValue: string }).currentValue
}
return undefined
} catch {
return undefined
}
}
/**
* 判定会话是否允许执行首次默认自动审查切换:
* - 已有对话内容的会话(`blank === false`)不改;
* - 子代理会话(`origin === 'subagent'`)不改;
* - 其余空白新建会话(以及未提供 blank 元数据的轻量测试桩)允许首次切换。
*/
export function isAutoSwitchEligible(id: string, live: any, sessions?: any): boolean {
try {
if (live?.getSnapshot?.()?.blank === false) return false
const summary = sessions?.list?.getSnapshot?.()?.byId?.[id]
if (summary?.blank === false) return false
if (summary?.origin === 'subagent') return false
} catch {
// 忽略元数据读取异常
}
return true
}
function loadHandledIds(doc: Document): Set<string> {
const set = new Set<string>()
try {
const storage = (doc as any)?.defaultView?.localStorage
const raw = storage?.getItem?.(HANDLED_STORAGE_KEY)
if (typeof raw === 'string' && raw) {
const parsed = JSON.parse(raw)
if (Array.isArray(parsed)) {
for (const item of parsed) {
if (typeof item === 'string' && item) set.add(item)
}
}
}
} catch {
// localStorage 不可用时仅在内存保存
}
return set
}
function saveHandledIds(doc: Document, set: Set<string>): void {
try {
const storage = (doc as any)?.defaultView?.localStorage
if (!storage?.setItem) return
const items = [...set].slice(-MAX_HANDLED_IDS)
storage.setItem(HANDLED_STORAGE_KEY, JSON.stringify(items))
} catch {
// 忽略写入异常
}
}
/**
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
* @returns 摘掉的个数
*/
export function pruneFullAccess(doc: Document): number {
let removed = 0
for (const option of doc.querySelectorAll('option')) {
if (isFullAccessLabel(option.textContent)) {
option.remove()
removed++
}
}
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
if (isFullAccessLabel(item.textContent)) {
item.remove()
removed++
}
}
return removed
}
export interface PolicyTimers {
setInterval?: (fn: () => void, ms: number) => number
clearInterval?: (id: number) => void
setTimeout: (fn: () => void, ms: number) => number
clearTimeout: (id: number) => void
}
const defaultTimers: Required<PolicyTimers> = {
setInterval: (fn, ms) => setInterval(fn, ms) as unknown as number,
clearInterval: (id) => clearInterval(id),
setTimeout: (fn, ms) => setTimeout(fn, ms) as unknown as number,
clearTimeout: (id) => clearTimeout(id),
}
/**
* 安装权限策略:
* 1. 观察 DOM、摘掉「完全权限」选项;
* 2. 观察/轮询空白新建会话,首次见到时自动切到 `auto`(自动审查)。
* @returns 卸载函数
*/
export function installPermissionPolicy(
doc: Document,
getSessions?: () => any,
timers: PolicyTimers = defaultTimers,
): () => void {
let disposed = false
let scanTimer = 0
const setTimerInterval = timers.setInterval ?? defaultTimers.setInterval
const clearTimerInterval = timers.clearInterval ?? defaultTimers.clearInterval
const scheduleScan = (): void => {
if (disposed || scanTimer) return
scanTimer = timers.setTimeout(() => {
scanTimer = 0
if (!disposed) pruneFullAccess(doc)
}, 120)
}
const observer = new MutationObserver(scheduleScan)
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
pruneFullAccess(doc)
const handled = loadHandledIds(doc)
const inFlight = new Set<string>()
const projectionUnsubs = new Map<string, () => void>()
let listUnsub: (() => void) | undefined
const markHandled = (id: string): void => {
if (!handled.has(id)) {
handled.add(id)
saveHandledIds(doc, handled)
}
const unsub = projectionUnsubs.get(id)
if (unsub) {
projectionUnsubs.delete(id)
try { unsub() } catch { /* ignore */ }
}
}
const watchProjection = (id: string, live: any): void => {
if (projectionUnsubs.has(id) || handled.has(id)) return
const face = live?.projections?.faceOf?.('permissions')
if (typeof face?.subscribe !== 'function') return
try {
const unsub = face.subscribe(() => {
if (!disposed) void tick()
})
if (typeof unsub === 'function') projectionUnsubs.set(id, unsub)
} catch {
// ignore
}
}
const tick = async (): Promise<void> => {
if (disposed || typeof getSessions !== 'function') return
let sessions: any
try {
sessions = getSessions()
} catch {
return
}
if (!listUnsub && typeof sessions?.list?.subscribe === 'function') {
try {
listUnsub = sessions.list.subscribe(() => {
if (!disposed) void tick()
})
} catch {
// ignore
}
}
for (const { id, live } of liveSessions(sessions)) {
if (handled.has(id) || inFlight.has(id)) continue
if (!isAutoSwitchEligible(id, live, sessions)) {
markHandled(id)
continue
}
const preset = currentPreset(live)
if (!shouldAutoSwitch(preset, handled.has(id))) {
if (preset !== undefined && preset !== null) {
markHandled(id)
} else {
watchProjection(id, live)
}
continue
}
markHandled(id)
if (typeof live?.command !== 'function') continue
inFlight.add(id)
try {
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`)
if (!result?.ok) {
console.info('[dsh-better-chat] auto review not applied for session', id, result?.error?.code ?? '')
}
} catch {
console.info('[dsh-better-chat] auto review switch failed for session', id)
} finally {
inFlight.delete(id)
}
}
}
const intervalId = typeof getSessions === 'function' ? setTimerInterval(() => { void tick() }, 2500) : 0
if (typeof getSessions === 'function') void tick()
return () => {
disposed = true
observer.disconnect()
if (scanTimer) timers.clearTimeout(scanTimer)
if (intervalId) clearTimerInterval(intervalId)
if (listUnsub) {
try { listUnsub() } catch { /* ignore */ }
listUnsub = undefined
}
for (const unsub of projectionUnsubs.values()) {
try { unsub() } catch { /* ignore */ }
}
projectionUnsubs.clear()
}
}