engine.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. /**
  2. * 引擎进程
  3. * =======
  4. * 和桌面端 electron/sidecar.js 同一套启动方式:
  5. *
  6. * node <dsh>/lib/bin.js --profile web --patch <patch.yml> --port 0 --no-open
  7. *
  8. * 端口由系统分配,从输出里抓 `http://127.0.0.1:<port>/`。区别只有三处:
  9. * · DSH_HOME 指到老师自己的目录(会话、设置互不串);
  10. * · CC_LLM_KEY 用这个老师自己的 apiKey;
  11. * · 进程按进程组管理,主服务退出时一起收掉(不留孤儿 node 进程)。
  12. */
  13. import { spawn } from 'node:child_process'
  14. const URL_RE = /https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)\/\S*/
  15. const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
  16. export class Engine {
  17. constructor (options) {
  18. this.entry = options.entry
  19. this.node = options.node || process.execPath
  20. this.patchFile = options.patchFile
  21. this.cwd = options.cwd
  22. this.env = options.env || {}
  23. this.bootMs = options.bootMs || 90_000
  24. this.log = options.log || (() => {})
  25. this.child = null
  26. this.port = 0
  27. this.token = ''
  28. this.startedAt = 0
  29. this.tail = []
  30. this.stopping = false
  31. }
  32. get url () {
  33. return this.port ? `http://127.0.0.1:${this.port}/` : ''
  34. }
  35. args () {
  36. const args = ['--profile', 'web']
  37. if (this.patchFile) args.push('--patch', this.patchFile)
  38. args.push('--port', '0', '--no-open')
  39. return args
  40. }
  41. async start () {
  42. if (this.child) return { port: this.port, url: this.url }
  43. this.stopping = false
  44. this.startedAt = Date.now()
  45. const child = spawn(this.node, [this.entry, ...this.args()], {
  46. cwd: this.cwd || undefined,
  47. env: { ...process.env, ...this.env },
  48. stdio: ['ignore', 'pipe', 'pipe'],
  49. // POSIX 上单独一个进程组,停止时整组发信号;Windows 走 taskkill /T
  50. detached: process.platform !== 'win32',
  51. windowsHide: true
  52. })
  53. this.child = child
  54. const ready = new Promise((resolve, reject) => {
  55. let settled = false
  56. const timer = setTimeout(() => {
  57. if (settled) return
  58. settled = true
  59. this.stop().catch(() => {})
  60. reject(new Error(`引擎 ${Math.round(this.bootMs / 1000)} 秒内没有就绪。最近日志:\n${this.tailText(15)}`))
  61. }, this.bootMs)
  62. timer.unref?.()
  63. const onData = (buf) => {
  64. const text = buf.toString('utf8')
  65. for (const line of text.split(/\r?\n/)) {
  66. if (!line.trim()) continue
  67. this.log(`[engine] ${line}`)
  68. this.tail.push(line)
  69. if (this.tail.length > 200) this.tail.shift()
  70. if (settled) continue
  71. const m = line.match(URL_RE)
  72. if (!m) continue
  73. settled = true
  74. clearTimeout(timer)
  75. this.port = Number(m[1])
  76. // 引擎启动时会打印带 token 的地址;桌面端直接把整条 URL 交给 BrowserWindow,
  77. // 第一次访问靠 ?token= 换成 cookie。Web 版必须在代理层补这一步(见 index.js)。
  78. try { this.token = new URL(m[0]).searchParams.get('token') || '' } catch { this.token = '' }
  79. this.waitHealthy(`http://127.0.0.1:${this.port}/`)
  80. .then(() => resolve({ port: this.port, url: this.url }))
  81. .catch(reject)
  82. }
  83. }
  84. child.stdout.on('data', onData)
  85. child.stderr.on('data', onData)
  86. child.on('error', (err) => {
  87. clearTimeout(timer)
  88. if (settled) return
  89. settled = true
  90. reject(err)
  91. })
  92. child.on('exit', (code, signal) => {
  93. clearTimeout(timer)
  94. this.child = null
  95. if (this.stopping) return
  96. if (settled) {
  97. this.log(`[engine] 进程退出 code=${code} signal=${signal}`)
  98. return
  99. }
  100. settled = true
  101. reject(new Error(`引擎启动即退出(code=${code})。最近日志:\n${this.tailText(20)}`))
  102. })
  103. })
  104. return ready
  105. }
  106. async waitHealthy (url, attempts = 60) {
  107. for (let i = 0; i < attempts; i += 1) {
  108. try {
  109. const res = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(2000) })
  110. if (res.status < 500) return true
  111. } catch { /* 端口刚开,还没人接 */ }
  112. await sleep(250)
  113. }
  114. throw new Error(`引擎端口 ${this.port} 起来了但健康检查一直失败`)
  115. }
  116. tailText (n) {
  117. return this.tail.slice(-n).join('\n')
  118. }
  119. async stop () {
  120. const child = this.child
  121. if (!child) return
  122. this.stopping = true
  123. this.child = null
  124. const pid = child.pid
  125. try {
  126. if (process.platform === 'win32') {
  127. spawn('taskkill', ['/pid', String(pid), '/T', '/F'], { windowsHide: true }).on('error', () => {})
  128. } else {
  129. try { process.kill(-pid, 'SIGTERM') } catch { child.kill('SIGTERM') }
  130. const timer = setTimeout(() => {
  131. try { process.kill(-pid, 'SIGKILL') } catch { /* 已经退了 */ }
  132. }, 3000)
  133. timer.unref?.()
  134. }
  135. } catch { /* 进程已经没了 */ }
  136. this.port = 0
  137. }
  138. }