import { Context, Session } from 'koishi'; import { BotManager } from './bot-manager'; import type { BotPersonaConfig } from './types'; import { AsyncLocalStorage } from 'node:async_hooks'; /** * Session 虚拟化器 * 通过 Proxy 包装 Session 对象和配置对象,实现多 bot 隔离 */ export declare class SessionVirtualizer { private ctx; private botManager; private readonly logger; private readonly originalDatabaseGet; private readonly debugEnabled; private readonly botPrompts; private readonly botReasonerModels; private readonly botNotReasonerModels; private readonly botFavorabilityConfigs; private readonly botMoodConfigs; readonly asyncContext: AsyncLocalStorage; private originalAPIClient; private originalSATConfig; private apiClientCache; private apiClientConfigVersions; private configInterceptStats; private lastAccessBotId; private interceptFlushTimer; constructor(ctx: Context, botManager: BotManager); /** * 计算配置哈希值,用于检测配置变更 */ private getConfigHash; /** * 使 APIClient 缓存失效 * 在配置变更时调用 */ private invalidateAPIClientCache; /** * 设置 bot 的提示词(人设) */ setBotPrompt(botId: string, prompt: string): void; /** * 设置 bot 的深度思考模型配置 * 配置变更时自动失效 APIClient 缓存 */ setBotReasonerModel(botId: string, config: { model: string; baseURL?: string; apiKey?: string[]; }): void; /** * 设置 bot 的非思考模型配置 * 配置变更时自动失效 APIClient 缓存 */ setBotNotReasonerModel(botId: string, config: { model: string; baseURL?: string; apiKey?: string[]; }): void; /** * 设置 bot 的好感度配置 */ setBotFavorabilityConfig(botId: string, config: BotPersonaConfig['favorabilityConfig']): void; /** * 设置 bot 的心情配置 */ setBotMoodConfig(botId: string, config: BotPersonaConfig['moodConfig']): void; /** * 跟踪配置访问(用于检测 botId 变化) */ private trackConfigAccess; /** * 跟踪配置拦截(延迟聚合输出) */ private trackConfigIntercept; /** * 输出配置拦截统计(聚合日志) */ private flushConfigInterceptStats; /** * 创建虚拟化的 Session * 通过 Proxy 拦截 userId 和 channelId 属性访问 */ createVirtualSession(session: Session, botId: string): Session; /** * 从虚拟化的 userId 还原真实 userId */ resolveRealUserId(virtualUserId: string): string; /** * 从虚拟化的 channelId 还原真实 channelId */ resolveRealChannelId(virtualChannelId: string): string; /** * 从虚拟化的 userId 提取 botId */ extractBotId(virtualUserId: string): string; /** * 包装数据库 get 方法,拦截对 p_system 表的查询 * 将虚拟化的 userId 映射回真实的 userId,并添加 botId 过滤 */ wrapDatabaseGet(): void; /** * 恢复原始的数据库 get 方法 */ unwrapDatabaseGet(): void; /** * 获取当前 async 上下文中的 botId */ private getCurrentBotId; /** * 包装 satori-ai 的 SAT 实例 * 使用 monkey-patch 直接修改原始实例,确保所有现有引用都能使用我们的包装逻辑 */ wrapSATInstance(satInstance: any): any; /** * 输出调试日志 */ private debug; }