hermes-yaoyao.mjs 9.6 KB

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