hermes-yaoyao.mjs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. #!/usr/bin/env node
  2. import { execFileSync } from 'node:child_process'
  3. import { existsSync, readFileSync, realpathSync } from 'node:fs'
  4. import { chmod, mkdir, readdir, stat, unlink, writeFile } from 'node:fs/promises'
  5. import { homedir } from 'node:os'
  6. import { dirname, join, resolve } from 'node:path'
  7. import { setTimeout as delay } from 'node:timers/promises'
  8. import { fileURLToPath } from 'node:url'
  9. import { normalizeReleaseSource } from './lib/release-source.mjs'
  10. import { resolveDataHome } from './lib/data-home.mjs'
  11. import { migrateDataHome } from './lib/data-migration.mjs'
  12. import { prepareKernel, verifyKernel } from './lib/kernel-setup.mjs'
  13. const label = 'com.samien.hermes-yaoyao'
  14. const sourceProjectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
  15. const serviceRoot = resolve(process.env.HERMES_YAOYAO_SERVICE_ROOT || sourceProjectRoot)
  16. const uid = process.getuid?.() ?? 501
  17. const domain = `gui/${uid}`
  18. const launchAgents = join(homedir(), 'Library', 'LaunchAgents')
  19. const plistPath = join(launchAgents, `${label}.plist`)
  20. const dataHome = resolveDataHome(process.env.YAOYAO_HOME || process.env.HERMES_YAOYAO_HOME)
  21. const logDir = join(homedir(), 'Library', 'Logs')
  22. const serverEntry = join(serviceRoot, 'dist-server', 'server', 'index.js')
  23. function run(command, args, options = {}) {
  24. return execFileSync(command, args, { encoding: 'utf8', stdio: options.inherit ? 'inherit' : 'pipe' })
  25. }
  26. function escapeXml(value) {
  27. return String(value)
  28. .replaceAll('&', '&')
  29. .replaceAll('<', '&lt;')
  30. .replaceAll('>', '&gt;')
  31. .replaceAll('"', '&quot;')
  32. .replaceAll("'", '&apos;')
  33. }
  34. function environment(env = process.env) {
  35. const allowed = [
  36. 'HERMES_YAOYAO_HOST',
  37. 'HERMES_YAOYAO_PORT',
  38. 'HERMES_YAOYAO_UPSTREAM',
  39. 'HERMES_YAOYAO_UPSTREAM_USERNAME',
  40. 'HERMES_YAOYAO_UPSTREAM_PASSWORD_FILE',
  41. 'HERMES_YAOYAO_ALLOWED_HOSTS',
  42. 'HERMES_YAOYAO_HOME',
  43. 'HERMES_YAOYAO_TLS_CERT',
  44. 'HERMES_YAOYAO_TLS_KEY',
  45. 'HERMES_YAOYAO_ALLOW_INSECURE_LAN',
  46. 'HERMES_YAOYAO_SUPERVISE_DASHBOARD',
  47. 'HERMES_YAOYAO_CHAT_CACHE_MODE',
  48. 'HERMES_YAOYAO_RELEASE_SOURCE',
  49. 'HERMES_YAOYAO_RELEASE_ROOT',
  50. 'HERMES_YAOYAO_ALLOW_REMOTE_UPDATE',
  51. 'HERMES_YAOYAO_APNS_KEY_FILE',
  52. 'HERMES_YAOYAO_APNS_KEY_ID',
  53. 'HERMES_YAOYAO_APNS_TEAM_ID',
  54. 'HERMES_YAOYAO_APNS_TOPIC',
  55. 'HERMES_YAOYAO_FCM_SERVICE_ACCOUNT_FILE',
  56. 'HERMES_YAOYAO_FCM_PROJECT_ID',
  57. 'HERMES_YAOYAO_FCM_PACKAGE_NAME',
  58. 'HERMES_YAOYAO_SERVICE_ROOT',
  59. ]
  60. return { ...Object.fromEntries(allowed.flatMap(key => env[key] ? [[key, env[key]]] : [])),
  61. HERMES_YAOYAO_RELEASE_SOURCE: normalizeReleaseSource(env.HERMES_YAOYAO_RELEASE_SOURCE) }
  62. }
  63. export function launchAgentPlist(options = {}) {
  64. const plistServiceRoot = resolve(options.serviceRoot || serviceRoot)
  65. const plistServerEntry = join(plistServiceRoot, 'dist-server', 'server', 'index.js')
  66. const node = process.execPath
  67. const envEntries = {
  68. PATH: `${dirname(node)}:${join(homedir(), '.local', 'bin')}:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
  69. NODE_ENV: 'production',
  70. HERMES_YAOYAO_PORT: '15300',
  71. HERMES_YAOYAO_UPSTREAM: 'http://127.0.0.1:9119',
  72. HERMES_YAOYAO_SUPERVISE_DASHBOARD: '1',
  73. ...environment(options.environment),
  74. HERMES_YAOYAO_HOME: resolveDataHome(options.environment?.YAOYAO_HOME || options.environment?.HERMES_YAOYAO_HOME || dataHome),
  75. YAOYAO_HOME: resolveDataHome(options.environment?.YAOYAO_HOME || options.environment?.HERMES_YAOYAO_HOME || dataHome),
  76. HERMES_YAOYAO_HOST: '0.0.0.0',
  77. HERMES_YAOYAO_ALLOW_INSECURE_LAN: '1',
  78. }
  79. const envXml = Object.entries(envEntries).map(([key, value]) => (
  80. ` <key>${escapeXml(key)}</key>\n <string>${escapeXml(value)}</string>`
  81. )).join('\n')
  82. const logPath = join(logDir, 'hermes-yaoyao.log')
  83. return `<?xml version="1.0" encoding="UTF-8"?>
  84. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  85. <plist version="1.0">
  86. <dict>
  87. <key>Label</key><string>${label}</string>
  88. <key>ProgramArguments</key>
  89. <array><string>${escapeXml(node)}</string><string>${escapeXml(plistServerEntry)}</string></array>
  90. <key>WorkingDirectory</key><string>${escapeXml(plistServiceRoot)}</string>
  91. <key>EnvironmentVariables</key>
  92. <dict>
  93. ${envXml}
  94. </dict>
  95. <key>RunAtLoad</key><true/>
  96. <key>KeepAlive</key><true/>
  97. <key>ThrottleInterval</key><integer>10</integer>
  98. <key>ProcessType</key><string>Interactive</string>
  99. <key>Umask</key><integer>63</integer>
  100. <key>StandardOutPath</key><string>${escapeXml(logPath)}</string>
  101. <key>StandardErrorPath</key><string>${escapeXml(logPath)}</string>
  102. </dict>
  103. </plist>
  104. `
  105. }
  106. function loaded() {
  107. try {
  108. run('launchctl', ['print', `${domain}/${label}`])
  109. return true
  110. } catch {
  111. return false
  112. }
  113. }
  114. function launchctlBootstrapRetryable(error) {
  115. const detail = [error?.message, error?.stdout, error?.stderr]
  116. .filter(Boolean)
  117. .map(String)
  118. .join('\n')
  119. return /Bootstrap failed:\s*5:\s*Input\/output error/i.test(detail)
  120. }
  121. export async function bootstrapLaunchAgent(
  122. runCommand = run,
  123. wait = delay,
  124. options = {},
  125. ) {
  126. const timeoutMs = options.timeoutMs ?? 20_000
  127. const initialDelayMs = options.initialDelayMs ?? 250
  128. const maximumDelayMs = options.maximumDelayMs ?? 2_000
  129. const now = options.now ?? Date.now
  130. const deadline = now() + timeoutMs
  131. let retryDelayMs = initialDelayMs
  132. for (;;) {
  133. try {
  134. return runCommand('launchctl', ['bootstrap', domain, plistPath])
  135. } catch (error) {
  136. if (!launchctlBootstrapRetryable(error)) throw error
  137. const remainingMs = deadline - now()
  138. if (remainingMs <= 0) throw error
  139. const waitMs = Math.min(retryDelayMs, maximumDelayMs, remainingMs)
  140. await wait(waitMs)
  141. retryDelayMs = Math.min(retryDelayMs * 2, maximumDelayMs)
  142. }
  143. }
  144. }
  145. async function install() {
  146. if (!existsSync(serverEntry)) {
  147. throw new Error('未找到生产构建,请先运行 npm run build')
  148. }
  149. await mkdir(launchAgents, { recursive: true })
  150. await mkdir(logDir, { recursive: true })
  151. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  152. migrateDataHome(dataHome)
  153. await mkdir(dataHome, { recursive: true, mode: 0o700 })
  154. await writeFile(plistPath, launchAgentPlist(), { mode: 0o600 })
  155. await chmod(plistPath, 0o600)
  156. run('plutil', ['-lint', plistPath], { inherit: true })
  157. await bootstrapLaunchAgent()
  158. process.stdout.write(`已安装并启动 ${label}\n`)
  159. }
  160. async function start() {
  161. if (!existsSync(plistPath)) throw new Error('服务尚未安装')
  162. if (!loaded()) await bootstrapLaunchAgent()
  163. else run('launchctl', ['kickstart', '-k', `${domain}/${label}`])
  164. process.stdout.write(`已启动 ${label}\n`)
  165. }
  166. async function restart() {
  167. if (!existsSync(plistPath)) throw new Error('服务尚未安装,请先运行 yaoyao service install')
  168. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  169. await bootstrapLaunchAgent()
  170. process.stdout.write(`已重启 ${label}\n`)
  171. }
  172. function stop() {
  173. if (loaded()) run('launchctl', ['bootout', `${domain}/${label}`])
  174. process.stdout.write(`已停止 ${label};Hermes 9119 未被操作\n`)
  175. }
  176. async function uninstall() {
  177. stop()
  178. if (existsSync(plistPath)) await unlink(plistPath)
  179. process.stdout.write(`已卸载 ${label};运行数据保留在 ${dataHome}\n`)
  180. }
  181. function status() {
  182. if (!loaded()) {
  183. process.stdout.write(`${label}: stopped\n`)
  184. process.exitCode = 3
  185. return
  186. }
  187. process.stdout.write(run('launchctl', ['print', `${domain}/${label}`]))
  188. }
  189. async function pruneUploads(args) {
  190. const index = args.indexOf('--older-than')
  191. const days = index >= 0 ? Number(args[index + 1]) : 30
  192. if (!Number.isFinite(days) || days < 1) throw new Error('--older-than 必须是大于 0 的天数')
  193. if (!args.includes('--yes')) {
  194. throw new Error('这是显式清理操作,请增加 --yes')
  195. }
  196. const root = join(dataHome, 'uploads', 'pending')
  197. if (!existsSync(root)) return
  198. const cutoff = Date.now() - days * 86_400_000
  199. let removed = 0
  200. for (const entry of await readdir(root)) {
  201. const target = join(root, entry)
  202. const info = await stat(target)
  203. if (info.isFile() && info.mtimeMs < cutoff) {
  204. await unlink(target)
  205. removed += 1
  206. }
  207. }
  208. process.stdout.write(`已清理 ${removed} 个未提交上传文件\n`)
  209. }
  210. async function main() {
  211. const [, , group, command, ...args] = process.argv
  212. if (group === 'version' || group === '--version' || group === '-v') {
  213. const { version } = JSON.parse(readFileSync(join(sourceProjectRoot, 'package.json'), 'utf8'))
  214. process.stdout.write(`${version}\n`)
  215. return
  216. }
  217. if (group === 'service') {
  218. if (command === 'install') return install()
  219. if (command === 'start') return start()
  220. if (command === 'restart') return restart()
  221. if (command === 'stop') return stop()
  222. if (command === 'status') return status()
  223. if (command === 'uninstall') return uninstall()
  224. }
  225. if (group === 'uploads' && command === 'prune') return pruneUploads(args)
  226. if (group === 'setup') { await prepareKernel({ root: serviceRoot, force: command === '--force' }); process.stdout.write('内置 Hermes 内核已就绪\n'); return }
  227. if (group === 'doctor') { verifyKernel({ root: serviceRoot }); return }
  228. process.stdout.write(`夭夭 AI\n\n用法:\n yaoyao setup [--force] 准备内置 Hermes 内核\n yaoyao doctor 检查内置 Hermes 内核\n yaoyao service install|start|restart|stop|status|uninstall\n yaoyao version | --version | -v\n yaoyao uploads prune --older-than 30 --yes\n`)
  229. }
  230. export function isMainModule(entry = process.argv[1]) {
  231. if (!entry) return false
  232. try {
  233. return realpathSync(entry) === realpathSync(fileURLToPath(import.meta.url))
  234. } catch {
  235. return resolve(entry) === fileURLToPath(import.meta.url)
  236. }
  237. }
  238. if (isMainModule()) {
  239. main().catch(error => {
  240. process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`)
  241. process.exitCode = 1
  242. })
  243. }