/** * 会话编排 * ======== * 一个老师 = 一套隔离的运行环境,四个部件: * * Engine 引擎进程(DSH_HOME 独立,patch 里带自己的 apiKey 与技能目录) * RemoteBrowser 独立 Chromium(独立 user-data-dir,登录态互不可见) * PageBridge /page/* 通道(把桌面端外壳那半边补上) * Files 工作区 + 下载 + 页面取文件的短时地址 * * 引擎和浏览器都是重资源:一个引擎约 200–400MB、一个 Chromium 约 150–300MB。 * 所以有 idle 回收和并发上限;老师再来时按需重建(工作区在磁盘上,不丢东西)。 */ import fsp from 'node:fs/promises' import path from 'node:path' import crypto from 'node:crypto' import { config, userDirs, ensureDirs } from '../config.js' import { Engine } from './engine.js' import { PageBridge } from './bridge.js' import { ApiBridge } from './apibridge.js' import { Files } from './files.js' import { buildPatch } from './patch.js' import { listModels } from './platform.js' // RemoteBrowser 不在这里静态 import:API 模式下永不加载它(连带 cdp.js), // 少一份常驻模块,也少一次"浏览器没装"导致的启动失败。 const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) function userIdOf (user) { const explicit = String(user.userid || '').trim() if (explicit) return explicit return `k${crypto.createHash('sha256').update(String(user.apiKey || '')).digest('hex').slice(0, 12)}` } export class Session { constructor (user, logger) { this.user = user this.uid = userIdOf(user) this.dir = userDirs(this.uid) this.log = logger this.engine = null this.browser = null this.bridge = null this.files = null this.startedAt = 0 this.lastUsed = Date.now() this.starting = null this.problem = '' } touch () { this.lastUsed = Date.now() } async ensure () { // browser 只存在于 browser 模式,不能作为"就绪"的判定条件 —— // 否则 API 模式下每次 ensure 都会重新 boot 一遍引擎。 if (this.engine && this.bridge) return this if (this.starting) return this.starting this.starting = this.#boot().catch((err) => { this.starting = null throw err }) return this.starting } async #boot () { ensureDirs(this.dir) await fsp.mkdir(this.dir.workspace, { recursive: true }) await fsp.mkdir(this.dir.downloads, { recursive: true }) // 1) 登录态:插件每次调用都读这个文件,换 key 不用重启引擎 const auth = { apiBase: this.user.region ? config.regions[this.user.region].platform : config.regions[config.defaultRegion].platform, apiKey: this.user.apiKey, token: this.user.apiKey, userid: this.user.userid || this.uid, username: this.user.username || '', organizeId: this.user.organizeId || '', organizeName: this.user.organizeName || '', mock: false } await fsp.writeFile(this.dir.authFile, JSON.stringify(auth, null, 2), { mode: 0o600 }) // 2) 模型清单:拿不到就用配置里的默认模型,不让启动因此失败 const listed = await listModels({ baseURL: config.llm.baseURL, apiKey: this.user.apiKey, modelsHint: config.llm.models }) if (!listed.ok) this.log(`[session ${this.uid}] 模型清单不可用(${listed.message}),用默认模型 ${config.llm.model}`) // 3) patch:先生成,再起引擎(插件启动时就会读 bridgeFile) const patch = buildPatch({ workspaceDir: this.dir.workspace, authFile: this.dir.authFile, bridgeFile: this.dir.bridgeFile, apiBase: auth.apiBase, pluginEntry: config.pluginDir, brandEntry: config.brandDir, skillsDir: config.skillsDir, skillDirs: [config.skillsDir], llm: { baseURL: config.llm.baseURL, // 网关没给出清单(401 / 断网 / 空列表)时退回配置里的默认模型, // 不能让"取不到清单"变成"起不来" model: listed.models.some((m) => m.id === config.llm.model) ? config.llm.model : (listed.models[0] ? listed.models[0].id : config.llm.model), models: listed.models.length ? listed.models : [{ id: config.llm.model, name: config.llm.model }], protocol: config.llm.protocol, userId: this.user.userid || '', orgId: this.user.organizeId || '' }, locale: this.user.locale || 'zh-CN' }) await fsp.writeFile(this.dir.patchFile, patch, 'utf8') // 4) 页面通道的另一端:browser 模式起 Chromium,api 模式只挂一个应答端 this.files = new Files({ roots: [this.dir.workspace, this.dir.downloads] }) const publicBase = config.publicBase || `http://127.0.0.1:${config.port}` let browser = null if (config.pageMode === 'browser') { const { RemoteBrowser } = await import('./browser.js') browser = new RemoteBrowser({ exe: config.chrome, userDataDir: this.dir.browser, downloadDir: this.dir.downloads, headless: config.headless, noSandbox: config.noSandbox, width: config.viewport.width, height: config.viewport.height, log: this.log }) await browser.start() this.browser = browser } // 5) 页面通道:写 {port, token} 到引擎要读的位置。 // 两种模式写的是同一个文件名、同一个 JSON 形状 —— 插件不需要知道有没有浏览器。 const bridge = browser ? new PageBridge({ browser, tokenFile: this.dir.bridgeFile, fileUrl: (filePath) => this.files.blobUrl(filePath, publicBase), log: this.log }) : new ApiBridge({ tokenFile: this.dir.bridgeFile, platformBase: auth.apiBase, filesUrl: publicBase, log: this.log }) await bridge.start() this.bridge = bridge // 6) 引擎 const engine = new Engine({ entry: config.engineEntry, node: config.engineNode, patchFile: this.dir.patchFile, cwd: this.dir.workspace, bootMs: config.engineBootMs, env: { DSH_HOME: this.dir.home, COCOROBO_LLM_KEY: this.user.apiKey, CC_LLM_KEY: this.user.apiKey, LANG: 'C.UTF-8', TZ: process.env.TZ || 'Asia/Shanghai' }, log: this.log }) try { await engine.start() } catch (err) { // browser 在 API 模式下是 null,这里必须判空(`browser?.stop().catch` 会抛, // 因为可选链只保护 stop() 本身,不保护后面的 .catch) try { if (browser) await browser.stop() } catch { /* 已经停了 */ } await bridge.stop().catch(() => {}) this.browser = null this.bridge = null throw err } this.engine = engine this.startedAt = Date.now() this.touch() this.log(`[session ${this.uid}] 就绪 engine=${engine.port} bridge=${this.bridge.info.port}`) return this } async stop (reason = '') { this.log(`[session ${this.uid}] 停止${reason ? `(${reason})` : ''}`) try { await this.engine?.stop() } catch { /* 已经停了 */ } try { await this.bridge?.stop() } catch { /* 已经停了 */ } try { await this.browser?.stop() } catch { /* 已经停了 */ } try { this.files?.dispose() } catch { /* 已经释放 */ } this.engine = null this.bridge = null this.browser = null this.files = null this.starting = null } } export class SessionManager { constructor (logger) { this.log = logger this.sessions = new Map() // uid → Session this.timer = setInterval(() => this.#reap(), 60_000) this.timer.unref?.() } async get (user) { const session = this.getOrCreate(user) session.user.locale = user.locale await session.ensure() return session } /** 只建对象、不启动环境:调用方拿到后可以自己决定什么时候 ensure(首屏要快) */ getOrCreate (user) { const uid = userIdOf(user) let session = this.sessions.get(uid) if (!session) { if (this.sessions.size >= config.maxSessions) this.#evictOne().catch(() => {}) session = new Session(user, this.log) session.user.locale = user.locale this.sessions.set(uid, session) } // apiKey 可能续期/换账号:更新内存里的身份,auth.json 下次启动时刷新 session.user.apiKey = user.apiKey session.user.organizeId = user.organizeId || session.user.organizeId session.touch() return session } /** 给已登录但"还没起环境"的请求用:只查不建 */ peek (user) { return this.sessions.get(userIdOf(user)) || null } async #evictOne () { const idle = [...this.sessions.values()] .filter((s) => !s.starting) .sort((a, b) => a.lastUsed - b.lastUsed)[0] if (!idle) return this.sessions.delete(idle.uid) await idle.stop('并发上限').catch(() => {}) } async #reap () { const limit = Date.now() - config.idleMinutes * 60_000 for (const [uid, session] of this.sessions) { if (session.starting) continue if (session.lastUsed < limit) { this.sessions.delete(uid) await session.stop('空闲回收').catch(() => {}) } } } async stopAll () { clearInterval(this.timer) await Promise.all([...this.sessions.values()].map((s) => s.stop('服务退出').catch(() => {}))) this.sessions.clear() } stats () { return [...this.sessions.values()].map((s) => ({ uid: s.uid, engine: s.engine ? s.engine.port : 0, bridge: s.bridge && s.bridge.info ? s.bridge.info.port : 0, tabs: s.browser ? s.browser.list().length : 0, idleMs: Date.now() - s.lastUsed, startedAt: s.startedAt })) } /** 等引擎端口可代理(刚登录时用它,别让第一屏白屏) */ async waitEngine (session, timeoutMs = 20_000) { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { if (session.engine && session.engine.port) return session.engine.port await sleep(120) } throw new Error('引擎还没就绪') } }