// R-004:工作台集中审批中心。拦截十席会话的原生 approval/request,提供并发安全的 // list/answer 通道;非十席一律 next()。不改变 DSH 审批规则,不自动批准,不持久化答案。 import { randomUUID } from 'node:crypto' export class ApprovalCenterError extends Error { constructor(code, message) { super(message); this.name = 'ApprovalCenterError'; this.code = code } } export const APPROVAL_STATUSES = Object.freeze(['pending', 'answered', 'cancelled', 'error']) const OUTCOME_BY_CHOICE = new Map([['allow', 'allowed-once'], ['reject', 'rejected']]) const NATIVE_OUTCOMES = new Set(['allowed-once', 'rejected', 'cancelled', 'unavailable']) function cleanText(value) { return typeof value === 'string' ? value.trim() : '' } function copy(value) { try { return structuredClone(value) } catch { return JSON.parse(JSON.stringify(value)) } } // 只保留宿主可安全展示的详情节字段,并做长度限制。 export function redactApprovalDetail(detail) { if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return { text: '', code: '' } const text = cleanText(detail.text ?? detail.message ?? '') const code = cleanText(detail.code ?? '') return { text: text.slice(0, 500), code: code.slice(0, 200) } } export function createApprovalCenter({ ctx = {}, resolveSeatBySessionId, now = () => Date.now(), idFactory = randomUUID } = {}) { if (typeof resolveSeatBySessionId !== 'function') throw new ApprovalCenterError('sansheng/approval-config', '需要 resolveSeatBySessionId') const clock = typeof now === 'function' ? now : () => Number(now) const pending = new Map() const listeners = new Set() let disposed = false let installed = false function emit(event) { for (const listener of [...listeners]) { try { listener(copy(event)) } catch { /* 通知失败不影响结清 */ } } } function onEvent(listener) { if (typeof listener !== 'function') return () => {} listeners.add(listener) return () => listeners.delete(listener) } function finalize(entry, outcome) { if (!entry || entry.settled) return false entry.settled = true entry.status = outcome === 'unavailable' ? 'error' : (outcome === 'cancelled' ? 'cancelled' : 'answered') pending.delete(entry.id) entry.resolve(outcome) emit({ type: 'closed', entry: publicEntry(entry), status: entry.status, outcome }) return true } function publicEntry(entry) { return { id: entry.id, sessionId: entry.sessionId, projectId: entry.projectId, seatId: entry.seatId, tool: entry.tool, reason: entry.reason, detail: entry.detail, callId: entry.callId, at: entry.at, status: entry.status, } } async function handle(request = {}, next) { if (disposed) return typeof next === 'function' ? next() : undefined const sessionId = cleanText(request.sessionId ?? request.agent?.session?.id ?? request.agent?.id) if (!sessionId) return typeof next === 'function' ? next() : undefined let located = null try { located = await resolveSeatBySessionId(sessionId) } catch { located = null } if (!located || !located.projectId || !located.seatId) return typeof next === 'function' ? next() : undefined const id = idFactory() const entry = { id, sessionId, projectId: located.projectId, seatId: located.seatId, tool: cleanText(request.toolName ?? request.tool ?? request.name), reason: cleanText(request.reason ?? request.message ?? ''), detail: redactApprovalDetail(request.detail ?? request.data), callId: cleanText(request.callId ?? request.id) || null, at: clock(), status: 'pending', settled: false, resolve: null, } const outcomePromise = new Promise(resolve => { entry.resolve = resolve }) // 先建 Promise/监听,再登记与通知,防止“同步应答”时找不到 entry。 const onAbort = () => finalize(entry, 'cancelled') const originalSignal = request.signal if (originalSignal) { if (originalSignal.aborted) return 'cancelled' try { originalSignal.addEventListener('abort', onAbort, { once: true }) } catch { /* ignore */ } } pending.set(id, entry) emit({ type: 'open', entry: publicEntry(entry) }) // 工作台与原生卡共用一个结果。原生卡的应答按 DSH 的结果码透传。 void Promise.resolve().then(async () => { if (entry.settled) return const native = await next?.() finalize(entry, NATIVE_OUTCOMES.has(native) ? native : 'unavailable') }).catch(() => finalize(entry, 'unavailable')) try { return await outcomePromise } finally { try { originalSignal?.removeEventListener?.('abort', onAbort) } catch { /* ignore */ } } } function list(projectId) { const out = [] for (const entry of pending.values()) { if (projectId && entry.projectId !== projectId) continue out.push(publicEntry(entry)) } return out.sort((a, b) => a.at - b.at) } function answer(id, identity = {}, choice) { if (disposed) throw new ApprovalCenterError('sansheng/approval-disposed', '审批中心已卸载') if (!OUTCOME_BY_CHOICE.has(choice)) throw new ApprovalCenterError('sansheng/approval-invalid', 'choice 必须是 allow 或 reject') const entry = pending.get(cleanText(id)) if (!entry) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在') if (identity.projectId !== entry.projectId || identity.seatId !== entry.seatId || identity.sessionId !== entry.sessionId) { throw new ApprovalCenterError('sansheng/approval-forbidden', '审批归属不匹配') } const ok = finalize(entry, OUTCOME_BY_CHOICE.get(choice)) if (!ok) throw new ApprovalCenterError('sansheng/approval-stale', '审批已处理或不存在') return { ok: true, status: 'answered', choice } } function waitsFor(sessionId) { for (const entry of pending.values()) if (entry.sessionId === sessionId) return true return false } function cancelForSession(sessionId) { let count = 0 for (const entry of [...pending.values()]) { if (entry.sessionId === sessionId && finalize(entry, 'cancelled')) count += 1 } return count } function status() { const eventBusAvailable = typeof ctx.on === 'function' const available = installed && !disposed && eventBusAvailable return { available, degraded: !available, pendingCount: pending.size, eventBusAvailable, reason: disposed ? 'disposed' : !installed ? 'not-installed' : !eventBusAvailable ? 'event-bus-unavailable' : null, } } function install() { if (installed) return () => {} installed = true let off = null if (typeof ctx.on === 'function') { off = ctx.on('approval/request', (request, next) => handle(request, next), { prepend: true }) } return () => { try { off?.() } catch { /* ignore */ } dispose() } } function dispose() { if (disposed) return disposed = true for (const entry of [...pending.values()]) finalize(entry, 'cancelled') listeners.clear() } return { handle, install, list, answer, waitsFor, cancelForSession, dispose, status, onEvent, publicEntry, redactApprovalDetail } }