kernel-setup.mjs 4.4 KB

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