kernel-setup.mjs 4.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Prepares the embedded Hermes kernel (Python 3.11 + locked dependencies).
  2. // Adapted from yaovi-agent bin/lib/agent-setup.mjs (Apache-2.0).
  3. import {spawnSync} from 'node:child_process'
  4. import {createHash} from 'node:crypto'
  5. import {existsSync,mkdirSync,mkdtempSync,readFileSync,rmSync,writeFileSync} from 'node:fs'
  6. import {tmpdir} from 'node:os'
  7. import {dirname,join} from 'node:path'
  8. const UV_VERSION='0.13.0'
  9. /** Virtual environment for the kernel: packaged apps keep it outside their read-only bundle. */
  10. export function kernelVenv(root,env=process.env){
  11. return env.YAOYAO_KERNEL_VENV||join(root,'.venv')
  12. }
  13. /** Interpreter used for runtime/worker.py and runtime/hermes_service.py. */
  14. export function kernelPython(root,env=process.env){
  15. return env.YAOYAO_KERNEL_PYTHON||(existsSync(join(root,'runtime/python/bin/python3'))?join(root,'runtime/python/bin/python3'):join(kernelVenv(root,env),'bin/python'))
  16. }
  17. function runCommand(command,args,{cwd,env,input,quiet=false}={}){
  18. const result=spawnSync(command,args,{cwd,env,input,encoding:'utf8',stdio:input!==undefined?['pipe','inherit','inherit']:quiet?'pipe':'inherit',timeout:600000})
  19. if(result.error)throw result.error
  20. if(result.status!==0)throw new Error(`${command} 执行失败(${result.status})`)
  21. }
  22. export function verifyKernel({root,env=process.env,python=kernelPython(root,env),run=runCommand}){
  23. if(!existsSync(python))throw new Error('Hermes 内核未安装,请运行 yaoyao setup(源码目录使用 npm run kernel:setup)。')
  24. const home=mkdtempSync(join(env.TMPDIR||tmpdir(),'yaoyao-kernel-check-'))
  25. try{
  26. run(python,['-c',"import sys,runpy;sys.path.insert(0,'runtime/hermes');from run_agent import AIAgent;service=runpy.run_path('runtime/hermes_service.py');service['_bootstrap']();assert service['op_providers_catalog']({})['providers'];print('Hermes 内核及模型服务已就绪')"],
  27. {cwd:root,env:{...env,HOME:home,HERMES_HOME:home,YAOVI_KERNEL:'1',YAOVI_HERMES_TEST_OFFLINE:'1',HERMES_SKIP_UPDATE_CHECK:'1'}})
  28. }finally{rmSync(home,{recursive:true,force:true})}
  29. return python
  30. }
  31. async function resolveUv(root,env,run,fetchImpl){
  32. if(env.YAOYAO_UV){run(env.YAOYAO_UV,['--version'],{cwd:root,env,quiet:true});return env.YAOYAO_UV}
  33. const tools=env.YAOYAO_KERNEL_VENV?join(dirname(env.YAOYAO_KERNEL_VENV),'tool-bin'):join(root,'.tool-bin')
  34. const local=join(tools,'uv')
  35. if(existsSync(local))return local
  36. try{run('uv',['--version'],{cwd:root,env,quiet:true});return 'uv'}catch{/* install a private copy below */}
  37. console.log(`正在安装内核依赖管理器 uv ${UV_VERSION}…`)
  38. const response=await fetchImpl(`https://astral.sh/uv/${UV_VERSION}/install.sh`,{signal:AbortSignal.timeout(60000)})
  39. if(!response.ok)throw new Error(`uv 下载失败(HTTP ${response.status})`)
  40. const installer=await response.text()
  41. if(installer.length>1024*1024)throw new Error('uv 安装脚本大小异常')
  42. mkdirSync(tools,{recursive:true})
  43. run('sh',[],{cwd:root,env:{...env,UV_UNMANAGED_INSTALL:tools,UV_NO_MODIFY_PATH:'1'},input:installer})
  44. if(!existsSync(local))throw new Error('uv 安装未生成可执行文件')
  45. return local
  46. }
  47. /** Writes only installation artifacts under the package root; never opens a user's Hermes home. */
  48. export async function prepareKernel({root,env=process.env,run=runCommand,fetchImpl=fetch,force=false}){
  49. if(!['darwin','linux'].includes(process.platform))throw new Error('内置 Hermes 内核目前支持 macOS 和 Linux。')
  50. const python=kernelPython(root,env)
  51. if(env.YAOYAO_KERNEL_PYTHON)return verifyKernel({root,env,python,run})
  52. if(python===join(root,'runtime/python/bin/python3'))return python
  53. const fingerprint=createHash('sha256').update(readFileSync(join(root,'runtime/requirements.lock'))).digest('hex')
  54. const venv=kernelVenv(root,env)
  55. const marker=join(venv,'.yaoyao-requirements')
  56. if(!force&&existsSync(python)&&existsSync(marker)&&readFileSync(marker,'utf8')===fingerprint)return python
  57. // A previous successful fingerprint must not survive a failed repair.
  58. rmSync(marker,{force:true})
  59. try{
  60. const installEnv={...env,UV_PYTHON_INSTALL_DIR:env.YAOYAO_KERNEL_VENV?join(dirname(venv),'python'):join(root,'.python'),UV_PYTHON_DOWNLOADS:'automatic'}
  61. const uv=await resolveUv(root,installEnv,run,fetchImpl)
  62. if(!existsSync(python))run(uv,['venv','--managed-python','--python','3.11',venv],{cwd:root,env:installEnv})
  63. console.log('正在准备 Hermes 内核依赖…')
  64. run(uv,['pip','sync','--python',python,'--require-hashes',join(root,'runtime/requirements.lock')],{cwd:root,env:installEnv})
  65. verifyKernel({root,env,python,run})
  66. writeFileSync(marker,fingerprint)
  67. return python
  68. }catch(error){throw new Error(`Hermes 内核准备失败:${error.message};请检查网络和目录权限后运行 yaoyao setup 重试。`)}
  69. }