dashboardController.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. import { execFile, spawn } from 'node:child_process'
  2. import { promisify } from 'node:util'
  3. import { isAbsolute } from 'node:path'
  4. import { dashboardCommandIndex, standaloneDashboardCommand } from './dashboardCommand.js'
  5. import { LoopbackTransport } from './loopbackAuthorization.js'
  6. export interface DashboardController {
  7. readonly canRestart: boolean
  8. readonly unavailableReason?: string
  9. refresh?(): Promise<void>
  10. restart(): Promise<void>
  11. }
  12. type Run = (command: string, args: string[]) => Promise<string>
  13. type Launch = (command: string, args: string[], cwd: string) => Promise<number>
  14. interface Options {
  15. platform?: NodeJS.Platform
  16. uid?: number
  17. run?: Run
  18. healthy?: (origin: string) => Promise<boolean>
  19. readyTimeoutMs?: number
  20. pollIntervalMs?: number
  21. launch?: Launch
  22. }
  23. type Service = { kind: 'launchagent'; target: string; pid: number }
  24. | { kind: 'standalone'; command: string; args: string[]; cwd: string; pid: number }
  25. interface OwnedDashboard extends DashboardController { suspendChecks?(): () => void }
  26. const execFileAsync = promisify(execFile)
  27. const labels = ['com.samien.hermes.dashboard.local', 'ai.hermes.dashboard']
  28. const localOrigin = 'http://127.0.0.1:9119'
  29. async function healthy(origin: string): Promise<boolean> {
  30. const transport = new LoopbackTransport()
  31. try {
  32. const response = await transport.fetch(new URL(`${origin}/api/health`), { signal: AbortSignal.timeout(1000) })
  33. await response.body?.cancel()
  34. return response.ok
  35. } catch { return false } finally { transport.close() }
  36. }
  37. const launch: Launch = (command, args, cwd) => new Promise((resolve, reject) => {
  38. const env = { ...process.env }
  39. for (const key of Object.keys(env)) if (key.startsWith('HERMES_YAOYAO_') || key.startsWith('ELECTRON_')) delete env[key]
  40. const child = spawn(command, args, { cwd, env, detached: true, stdio: 'ignore' })
  41. child.once('error', reject)
  42. child.once('spawn', () => { child.unref(); child.pid ? resolve(child.pid) : reject(new Error('Hermes Dashboard 启动失败。')) })
  43. })
  44. /** Runs only in the Yaoyao server. No browser, desktop IPC or client-supplied target is used. */
  45. export class ServerDashboardController implements DashboardController {
  46. private readonly platform: NodeJS.Platform
  47. private readonly uid: number | undefined
  48. private readonly run: Run
  49. private readonly healthy: NonNullable<Options['healthy']>
  50. private readonly timeout: number
  51. private readonly interval: number
  52. private readonly launch: Launch
  53. private launchedPid?: number
  54. private service: Service | undefined
  55. private restarting = false
  56. private stopped = false
  57. constructor(private readonly upstream: URL, private readonly owned?: OwnedDashboard, options: Options = {}) {
  58. this.platform = options.platform ?? process.platform
  59. this.uid = options.uid ?? process.getuid?.()
  60. this.run = options.run ?? (async (command, args) => (await execFileAsync(command, args, { timeout: 3000, maxBuffer: 256 * 1024 })).stdout)
  61. this.healthy = options.healthy ?? healthy
  62. this.timeout = options.readyTimeoutMs ?? 30000
  63. this.interval = options.pollIntervalMs ?? 250
  64. this.launch = options.launch ?? launch
  65. }
  66. get canRestart(): boolean {
  67. return !this.stopped && this.upstream.origin === localOrigin && (!!this.owned?.canRestart || !!this.service)
  68. }
  69. get unavailableReason(): string {
  70. if (this.upstream.origin !== localOrigin) return '此 Hermes 不在夭夭服务端可管理的本机地址,请在 Hermes 所在节点重启。'
  71. if (this.platform !== 'darwin') return '夭夭服务端尚未支持此系统的外部 Dashboard 服务管理,请在 Hermes 所在节点重启。'
  72. return '夭夭服务端未识别到当前账号可管理的 9119 Hermes Dashboard 进程;请确认由本机 Hermes 命令启动且与夭夭使用同一系统账号。'
  73. }
  74. async refresh(): Promise<void> {
  75. if (this.restarting || this.stopped) return
  76. const service = this.owned?.canRestart ? undefined : await this.discover()
  77. if (!this.restarting && !this.stopped) this.service = service
  78. }
  79. stop(): void { this.stopped = true; this.service = undefined }
  80. private async discover(): Promise<Service | undefined> {
  81. if (this.stopped || this.upstream.origin !== localOrigin || this.platform !== 'darwin' || this.uid === undefined) return
  82. const pids = await this.listeners().catch(() => [])
  83. if (pids.length !== 1) return
  84. const pid = pids[0]!
  85. for (const label of labels) {
  86. const service = await this.launchAgent(label, pid)
  87. if (service) return service
  88. }
  89. // Custom labels are common in manual installs. The listener PID, rather than
  90. // a label alone, identifies the only candidate we may inspect and restart.
  91. let jobs: { pid: number; label: string }[]
  92. try {
  93. const listing = await this.run('/bin/launchctl', ['list'])
  94. jobs = [...listing.matchAll(/^\s*(\d+)\s+-?\d+\s+(\S+)\s*$/gm)].map(m => ({ pid: Number(m[1]), label: m[2]! }))
  95. } catch { return }
  96. const job = jobs.find(job => job.pid === pid)
  97. if (job) return this.launchAgent(job.label, pid)
  98. const process = await this.process(pid)
  99. if (!process || process.uid !== this.uid || this.uid === 0 || (pid !== this.launchedPid && jobs.some(job => job.pid === process.parent))) return
  100. const invocation = standaloneDashboardCommand(process.command)
  101. if (!invocation) return
  102. if (process.parent !== 1 && pid !== this.launchedPid) {
  103. const parent = await this.process(process.parent)
  104. if (!parent || parent.uid !== this.uid || !/^(?:\S*\/)?-?(?:zsh|bash|sh|fish)(?:\s|$)/.test(parent.command)) return
  105. }
  106. // Module entry points can depend on the original working directory.
  107. try {
  108. const detail = await this.run('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'])
  109. const paths = detail.split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1))
  110. const cwd = paths[0]
  111. if (paths.length === 1 && cwd && isAbsolute(cwd) && !/[\r\0]/.test(cwd)) return { kind: 'standalone', pid, cwd, ...invocation }
  112. } catch { /* Do not stop a process we cannot reliably relaunch. */ }
  113. }
  114. private async listeners(): Promise<number[]> {
  115. try {
  116. const listeners = await this.run('/usr/sbin/lsof', ['-nP', '-a', '-iTCP:9119', '-sTCP:LISTEN', '-Fp'])
  117. return [...new Set([...listeners.matchAll(/^p(\d+)$/gm)].map(match => Number(match[1])))]
  118. } catch (error) {
  119. if ((error as { code?: number }).code === 1) return []
  120. throw error
  121. }
  122. }
  123. private async launchAgent(label: string, listener: number): Promise<Service | undefined> {
  124. if (!/^[A-Za-z0-9_.-]+$/.test(label)) return
  125. const target = `gui/${this.uid}/${label}`
  126. try {
  127. const detail = await this.run('/bin/launchctl', ['print', target])
  128. const pid = Number(detail.match(/^\s*pid = (\d+)\s*$/m)?.[1])
  129. const args = detail.match(/^\s*arguments = \{\n([\s\S]*?)^\s*\}/m)?.[1]?.trim().split('\n').map(line => line.trim()) ?? []
  130. if (pid === listener && dashboardCommandIndex(args) !== undefined) return { kind: 'launchagent', target, pid }
  131. } catch { /* Missing job or unknown command: fail closed. */ }
  132. }
  133. private async process(pid: number): Promise<{ uid: number; parent: number; command: string } | undefined> {
  134. try {
  135. const detail = await this.run('/bin/ps', ['-p', String(pid), '-o', 'uid=', '-o', 'ppid=', '-o', 'command='])
  136. const match = /^\s*(\d+)\s+(\d+)\s+([^\r\n]+)\s*$/.exec(detail)
  137. if (match) return { uid: Number(match[1]), parent: Number(match[2]), command: match[3]!.trim() }
  138. } catch { /* Process has exited or is unreadable. */ }
  139. }
  140. private async restartStandalone(service: Extract<Service, { kind: 'standalone' }>): Promise<void> {
  141. // discover() has just checked the owner, executable and sole listener.
  142. await this.run('/bin/kill', ['-TERM', String(service.pid)])
  143. const deadline = Date.now() + this.timeout
  144. while (!this.stopped && await this.process(service.pid)) {
  145. if (Date.now() >= deadline) throw new Error('Hermes Dashboard 未能停止,请在所在节点检查。')
  146. await new Promise(resolve => setTimeout(resolve, this.interval))
  147. }
  148. if (this.stopped || (await this.listeners()).length) throw new Error('9119 已被其他进程占用,未启动新的 Dashboard。')
  149. this.launchedPid = await this.launch(service.command, service.args, service.cwd)
  150. }
  151. async restart(): Promise<void> {
  152. if (this.restarting) throw new Error('服务端 Hermes Dashboard 正在重启。')
  153. if (this.stopped || this.upstream.origin !== localOrigin) throw new Error(this.unavailableReason)
  154. this.restarting = true
  155. this.service = undefined
  156. let resumeChecks: (() => void) | undefined
  157. try {
  158. const owned = !!this.owned?.canRestart
  159. let previous: Service | undefined
  160. if (owned) await this.owned!.restart()
  161. else {
  162. resumeChecks = this.owned?.suspendChecks?.()
  163. // Refresh ownership at action time, even if the UI previously reported restart availability.
  164. previous = await this.discover()
  165. if (!previous || this.stopped) throw new Error(this.unavailableReason)
  166. if (previous.kind === 'launchagent') await this.run('/bin/launchctl', ['kickstart', '-k', previous.target])
  167. else await this.restartStandalone(previous)
  168. }
  169. const deadline = Date.now() + this.timeout
  170. while (!this.stopped && Date.now() < deadline) {
  171. const replacement = owned ? undefined : await this.discover()
  172. const replaced = owned ? this.owned?.canRestart : replacement && previous && replacement.pid !== previous.pid
  173. && (replacement.kind === 'launchagent' && previous.kind === 'launchagent' ? replacement.target === previous.target
  174. : replacement.kind === 'standalone' && previous.kind === 'standalone' && replacement.pid === this.launchedPid
  175. && replacement.command === previous.command && replacement.cwd === previous.cwd && JSON.stringify(replacement.args) === JSON.stringify(previous.args))
  176. if (replaced && await this.healthy(this.upstream.origin) && !this.stopped) {
  177. this.service = replacement
  178. return
  179. }
  180. await new Promise(resolve => setTimeout(resolve, this.interval))
  181. }
  182. throw new Error('服务端 Hermes Dashboard 重启后未恢复健康,请重新检查。')
  183. } finally { resumeChecks?.(); this.restarting = false }
  184. }
  185. }