session.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. /**
  2. * 会话编排
  3. * ========
  4. * 一个老师 = 一套隔离的运行环境,四个部件:
  5. *
  6. * Engine 引擎进程(DSH_HOME 独立,patch 里带自己的 apiKey 与技能目录)
  7. * RemoteBrowser 独立 Chromium(独立 user-data-dir,登录态互不可见)
  8. * PageBridge /page/* 通道(把桌面端外壳那半边补上)
  9. * Files 工作区 + 下载 + 页面取文件的短时地址
  10. *
  11. * 引擎和浏览器都是重资源:一个引擎约 200–400MB、一个 Chromium 约 150–300MB。
  12. * 所以有 idle 回收和并发上限;老师再来时按需重建(工作区在磁盘上,不丢东西)。
  13. */
  14. import fsp from 'node:fs/promises'
  15. import path from 'node:path'
  16. import crypto from 'node:crypto'
  17. import { config, userDirs, ensureDirs } from '../config.js'
  18. import { Engine } from './engine.js'
  19. import { PageBridge } from './bridge.js'
  20. import { ApiBridge } from './apibridge.js'
  21. import { Files } from './files.js'
  22. import { buildPatch } from './patch.js'
  23. import { listModels } from './platform.js'
  24. // RemoteBrowser 不在这里静态 import:API 模式下永不加载它(连带 cdp.js),
  25. // 少一份常驻模块,也少一次"浏览器没装"导致的启动失败。
  26. const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
  27. function userIdOf (user) {
  28. const explicit = String(user.userid || '').trim()
  29. if (explicit) return explicit
  30. return `k${crypto.createHash('sha256').update(String(user.apiKey || '')).digest('hex').slice(0, 12)}`
  31. }
  32. export class Session {
  33. constructor (user, logger) {
  34. this.user = user
  35. this.uid = userIdOf(user)
  36. this.dir = userDirs(this.uid)
  37. this.log = logger
  38. this.engine = null
  39. this.browser = null
  40. this.bridge = null
  41. this.files = null
  42. this.startedAt = 0
  43. this.lastUsed = Date.now()
  44. this.starting = null
  45. this.problem = ''
  46. }
  47. touch () {
  48. this.lastUsed = Date.now()
  49. }
  50. async ensure () {
  51. // browser 只存在于 browser 模式,不能作为"就绪"的判定条件 ——
  52. // 否则 API 模式下每次 ensure 都会重新 boot 一遍引擎。
  53. if (this.engine && this.bridge) return this
  54. if (this.starting) return this.starting
  55. this.starting = this.#boot().catch((err) => {
  56. this.starting = null
  57. throw err
  58. })
  59. return this.starting
  60. }
  61. async #boot () {
  62. ensureDirs(this.dir)
  63. await fsp.mkdir(this.dir.workspace, { recursive: true })
  64. await fsp.mkdir(this.dir.downloads, { recursive: true })
  65. // 1) 登录态:插件每次调用都读这个文件,换 key 不用重启引擎
  66. const auth = {
  67. apiBase: this.user.region ? config.regions[this.user.region].platform : config.regions[config.defaultRegion].platform,
  68. apiKey: this.user.apiKey,
  69. token: this.user.apiKey,
  70. userid: this.user.userid || this.uid,
  71. username: this.user.username || '',
  72. organizeId: this.user.organizeId || '',
  73. organizeName: this.user.organizeName || '',
  74. mock: false
  75. }
  76. await fsp.writeFile(this.dir.authFile, JSON.stringify(auth, null, 2), { mode: 0o600 })
  77. // 2) 模型清单:拿不到就用配置里的默认模型,不让启动因此失败
  78. const listed = await listModels({
  79. baseURL: config.llm.baseURL,
  80. apiKey: this.user.apiKey,
  81. modelsHint: config.llm.models
  82. })
  83. if (!listed.ok) this.log(`[session ${this.uid}] 模型清单不可用(${listed.message}),用默认模型 ${config.llm.model}`)
  84. // 3) patch:先生成,再起引擎(插件启动时就会读 bridgeFile)
  85. const patch = buildPatch({
  86. workspaceDir: this.dir.workspace,
  87. authFile: this.dir.authFile,
  88. bridgeFile: this.dir.bridgeFile,
  89. apiBase: auth.apiBase,
  90. pluginEntry: config.pluginDir,
  91. brandEntry: config.brandDir,
  92. skillsDir: config.skillsDir,
  93. skillDirs: [config.skillsDir],
  94. llm: {
  95. baseURL: config.llm.baseURL,
  96. // 网关没给出清单(401 / 断网 / 空列表)时退回配置里的默认模型,
  97. // 不能让"取不到清单"变成"起不来"
  98. model: listed.models.some((m) => m.id === config.llm.model)
  99. ? config.llm.model
  100. : (listed.models[0] ? listed.models[0].id : config.llm.model),
  101. models: listed.models.length ? listed.models : [{ id: config.llm.model, name: config.llm.model }],
  102. protocol: config.llm.protocol,
  103. userId: this.user.userid || '',
  104. orgId: this.user.organizeId || ''
  105. },
  106. locale: this.user.locale || 'zh-CN'
  107. })
  108. await fsp.writeFile(this.dir.patchFile, patch, 'utf8')
  109. // 4) 页面通道的另一端:browser 模式起 Chromium,api 模式只挂一个应答端
  110. this.files = new Files({ roots: [this.dir.workspace, this.dir.downloads] })
  111. const publicBase = config.publicBase || `http://127.0.0.1:${config.port}`
  112. let browser = null
  113. if (config.pageMode === 'browser') {
  114. const { RemoteBrowser } = await import('./browser.js')
  115. browser = new RemoteBrowser({
  116. exe: config.chrome,
  117. userDataDir: this.dir.browser,
  118. downloadDir: this.dir.downloads,
  119. headless: config.headless,
  120. noSandbox: config.noSandbox,
  121. width: config.viewport.width,
  122. height: config.viewport.height,
  123. log: this.log
  124. })
  125. await browser.start()
  126. this.browser = browser
  127. }
  128. // 5) 页面通道:写 {port, token} 到引擎要读的位置。
  129. // 两种模式写的是同一个文件名、同一个 JSON 形状 —— 插件不需要知道有没有浏览器。
  130. const bridge = browser
  131. ? new PageBridge({
  132. browser,
  133. tokenFile: this.dir.bridgeFile,
  134. fileUrl: (filePath) => this.files.blobUrl(filePath, publicBase),
  135. log: this.log
  136. })
  137. : new ApiBridge({
  138. tokenFile: this.dir.bridgeFile,
  139. platformBase: auth.apiBase,
  140. filesUrl: publicBase,
  141. log: this.log
  142. })
  143. await bridge.start()
  144. this.bridge = bridge
  145. // 6) 引擎
  146. const engine = new Engine({
  147. entry: config.engineEntry,
  148. node: config.engineNode,
  149. patchFile: this.dir.patchFile,
  150. cwd: this.dir.workspace,
  151. bootMs: config.engineBootMs,
  152. env: {
  153. DSH_HOME: this.dir.home,
  154. COCOROBO_LLM_KEY: this.user.apiKey,
  155. CC_LLM_KEY: this.user.apiKey,
  156. LANG: 'C.UTF-8',
  157. TZ: process.env.TZ || 'Asia/Shanghai'
  158. },
  159. log: this.log
  160. })
  161. try {
  162. await engine.start()
  163. } catch (err) {
  164. // browser 在 API 模式下是 null,这里必须判空(`browser?.stop().catch` 会抛,
  165. // 因为可选链只保护 stop() 本身,不保护后面的 .catch)
  166. try { if (browser) await browser.stop() } catch { /* 已经停了 */ }
  167. await bridge.stop().catch(() => {})
  168. this.browser = null
  169. this.bridge = null
  170. throw err
  171. }
  172. this.engine = engine
  173. this.startedAt = Date.now()
  174. this.touch()
  175. this.log(`[session ${this.uid}] 就绪 engine=${engine.port} bridge=${this.bridge.info.port}`)
  176. return this
  177. }
  178. async stop (reason = '') {
  179. this.log(`[session ${this.uid}] 停止${reason ? `(${reason})` : ''}`)
  180. try { await this.engine?.stop() } catch { /* 已经停了 */ }
  181. try { await this.bridge?.stop() } catch { /* 已经停了 */ }
  182. try { await this.browser?.stop() } catch { /* 已经停了 */ }
  183. try { this.files?.dispose() } catch { /* 已经释放 */ }
  184. this.engine = null
  185. this.bridge = null
  186. this.browser = null
  187. this.files = null
  188. this.starting = null
  189. }
  190. }
  191. export class SessionManager {
  192. constructor (logger) {
  193. this.log = logger
  194. this.sessions = new Map() // uid → Session
  195. this.timer = setInterval(() => this.#reap(), 60_000)
  196. this.timer.unref?.()
  197. }
  198. async get (user) {
  199. const session = this.getOrCreate(user)
  200. session.user.locale = user.locale
  201. await session.ensure()
  202. return session
  203. }
  204. /** 只建对象、不启动环境:调用方拿到后可以自己决定什么时候 ensure(首屏要快) */
  205. getOrCreate (user) {
  206. const uid = userIdOf(user)
  207. let session = this.sessions.get(uid)
  208. if (!session) {
  209. if (this.sessions.size >= config.maxSessions) this.#evictOne().catch(() => {})
  210. session = new Session(user, this.log)
  211. session.user.locale = user.locale
  212. this.sessions.set(uid, session)
  213. }
  214. // apiKey 可能续期/换账号:更新内存里的身份,auth.json 下次启动时刷新
  215. session.user.apiKey = user.apiKey
  216. session.user.organizeId = user.organizeId || session.user.organizeId
  217. session.touch()
  218. return session
  219. }
  220. /** 给已登录但"还没起环境"的请求用:只查不建 */
  221. peek (user) {
  222. return this.sessions.get(userIdOf(user)) || null
  223. }
  224. async #evictOne () {
  225. const idle = [...this.sessions.values()]
  226. .filter((s) => !s.starting)
  227. .sort((a, b) => a.lastUsed - b.lastUsed)[0]
  228. if (!idle) return
  229. this.sessions.delete(idle.uid)
  230. await idle.stop('并发上限').catch(() => {})
  231. }
  232. async #reap () {
  233. const limit = Date.now() - config.idleMinutes * 60_000
  234. for (const [uid, session] of this.sessions) {
  235. if (session.starting) continue
  236. if (session.lastUsed < limit) {
  237. this.sessions.delete(uid)
  238. await session.stop('空闲回收').catch(() => {})
  239. }
  240. }
  241. }
  242. async stopAll () {
  243. clearInterval(this.timer)
  244. await Promise.all([...this.sessions.values()].map((s) => s.stop('服务退出').catch(() => {})))
  245. this.sessions.clear()
  246. }
  247. stats () {
  248. return [...this.sessions.values()].map((s) => ({
  249. uid: s.uid,
  250. engine: s.engine ? s.engine.port : 0,
  251. bridge: s.bridge && s.bridge.info ? s.bridge.info.port : 0,
  252. tabs: s.browser ? s.browser.list().length : 0,
  253. idleMs: Date.now() - s.lastUsed,
  254. startedAt: s.startedAt
  255. }))
  256. }
  257. /** 等引擎端口可代理(刚登录时用它,别让第一屏白屏) */
  258. async waitEngine (session, timeoutMs = 20_000) {
  259. const deadline = Date.now() + timeoutMs
  260. while (Date.now() < deadline) {
  261. if (session.engine && session.engine.port) return session.engine.port
  262. await sleep(120)
  263. }
  264. throw new Error('引擎还没就绪')
  265. }
  266. }