prepare-primary-runtime.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. /** Prepare pinned, relocatable script interpreters without installing into the build host. */
  2. import { execFileSync } from 'node:child_process'
  3. import { createHash } from 'node:crypto'
  4. import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  5. import { cp } from 'node:fs/promises'
  6. import { createRequire } from 'node:module'
  7. import { tmpdir } from 'node:os'
  8. import { dirname, join, resolve } from 'node:path'
  9. import extractZip from 'extract-zip'
  10. import { x as extractTar } from 'tar'
  11. import { workspaceDependencyPaths, type PrimaryRuntimeManifest } from '../../desktop-host/src/primary-runtime.ts'
  12. import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
  13. import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
  14. import lock from './primary-runtime-lock.json' with { type: 'json' }
  15. /**
  16. * Download or reuse an archive only when its bytes match the release lock.
  17. * @param url - Locked archive URL.
  18. * @param sha256 - Expected SHA-256 digest.
  19. * @param cache - Download cache directory.
  20. * @returns Verified local archive path.
  21. */
  22. export async function downloadPrimaryRuntimeAsset(url: string, sha256: string, cache: string): Promise<string> {
  23. const destination = join(cache, sha256)
  24. let bytes: Buffer
  25. try { bytes = readFileSync(destination) } catch (error) {
  26. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  27. const response = await fetch(url)
  28. if (!response.ok) throw new Error(`primary runtime download: ${String(response.status)} ${url}`)
  29. bytes = Buffer.from(await response.arrayBuffer())
  30. }
  31. if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw new Error(`primary runtime download: checksum mismatch for ${url}`)
  32. writeFileSync(destination, bytes)
  33. return destination
  34. }
  35. async function pythonArchive(target: keyof typeof lock.targets, cache: string): Promise<string> {
  36. const artifact = lock.targets[target]
  37. const filename = `cpython-${lock.pythonVersion}+${lock.pythonRelease}-${artifact.pythonTarget}-install_only_stripped.tar.gz`
  38. return downloadPrimaryRuntimeAsset(`https://github.com/astral-sh/python-build-standalone/releases/download/${lock.pythonRelease}/${encodeURIComponent(filename)}`, artifact.pythonSha256, cache)
  39. }
  40. /**
  41. * Identify the inputs that assemble one target's payload, excluding unrelated target locks.
  42. * @param target - Desktop target whose archives are installed.
  43. * @param runtimeLock - Locked interpreter and wheel inputs.
  44. * @param pnpmVersion - Package-manager version copied into the payload.
  45. * @returns SHA-256 payload identity for installation reuse.
  46. */
  47. export function primaryRuntimePayloadDigest(target: keyof typeof lock.targets, runtimeLock: typeof lock, pnpmVersion: string): string {
  48. const { pythonVersion, pythonRelease, nodeVersion, wheels, pythonPackages } = runtimeLock
  49. // Identity preserves key order within the selected target, wheel records and distribution map, plus wheel-entry order.
  50. // Bump format when extraction or assembly changes payload bytes without changing locked inputs.
  51. return createHash('sha256').update(JSON.stringify({
  52. format: 2, target, pythonVersion, pythonRelease, nodeVersion,
  53. artifact: runtimeLock.targets[target], wheels, pythonPackages, pnpm: pnpmVersion,
  54. })).digest('hex')
  55. }
  56. /**
  57. * Unpack a locked library wheel, retaining auxiliary scripts in its distribution data directory.
  58. * @param archive - Hash-verified wheel archive.
  59. * @param destination - Absolute site-packages directory.
  60. * @returns Resolves after extraction without command wrappers; rejects other wheel installation schemes.
  61. */
  62. export async function unpackPrimaryRuntimeWheel(archive: string, destination: string): Promise<void> {
  63. await extractZip(archive, {
  64. dir: destination,
  65. onEntry: (entry) => {
  66. const [directory, scheme] = entry.fileName.split('/')
  67. if (directory?.endsWith('.data') && scheme !== '' && scheme !== 'scripts') {
  68. throw new Error(`primary runtime: wheel requires unsupported installation paths: ${entry.fileName}`)
  69. }
  70. },
  71. })
  72. }
  73. /**
  74. * Copy the skill package's complete asset tree to ordinary filesystem resources.
  75. * @param source - The package's assets directory.
  76. * @param destination - Desktop runtime resource directory outside ASAR.
  77. * @returns Resolves after replacing the external assets with the complete package tree.
  78. */
  79. export async function prepareOfficeSkillAssets(source: string, destination: string): Promise<void> {
  80. rmSync(destination, { recursive: true, force: true })
  81. await cp(source, destination, { recursive: true, dereference: true })
  82. }
  83. /**
  84. * Materialize the selected Desktop target's primary runtime in its build resources.
  85. * @param options - Signed Windows packaging defers execution until its supervised signing stage.
  86. * @returns Resolves after materialization and, unless deferred, native-target execution checks.
  87. */
  88. export async function preparePrimaryRuntime(options: { deferSmoke?: boolean } = {}): Promise<void> {
  89. const target = resolveDesktopBuildTarget()
  90. const paths = resolveDesktopTargetBuildPaths()
  91. const artifact = lock.targets[target]
  92. mkdirSync(paths.runtime, { recursive: true })
  93. mkdirSync(paths.downloads, { recursive: true })
  94. const staging = mkdtempSync(join(tmpdir(), 'dsh-primary-'))
  95. try {
  96. const output = join(staging, 'payload')
  97. const dependencies = join(output, 'dependencies')
  98. mkdirSync(dependencies, { recursive: true })
  99. const nodeFilename = `node-v${lock.nodeVersion}-${artifact.nodeArchive}`
  100. const nodeArchive = await downloadPrimaryRuntimeAsset(`https://nodejs.org/dist/v${lock.nodeVersion}/${nodeFilename}`, artifact.nodeSha256, paths.downloads)
  101. const unpackedNode = join(staging, 'node')
  102. mkdirSync(unpackedNode)
  103. if (target === 'win-x64') await extractZip(nodeArchive, { dir: unpackedNode })
  104. else await extractTar({ file: nodeArchive, cwd: unpackedNode })
  105. const nodeSource = join(unpackedNode, nodeFilename.replace(/\.(?:zip|tar\.gz)$/u, ''))
  106. mkdirSync(join(dependencies, 'node', 'bin'), { recursive: true })
  107. mkdirSync(join(dependencies, 'node', 'node_modules'))
  108. writeFileSync(join(dependencies, 'node', 'node_modules', 'README.txt'), 'Reserved for bundled Node packages. pnpm uses its default installation directories.\n')
  109. cpSync(join(nodeSource, ...(target === 'win-x64' ? ['node.exe'] : ['bin', 'node'])),
  110. join(dependencies, 'node', 'bin', target === 'win-x64' ? 'node.exe' : 'node'))
  111. cpSync(join(nodeSource, 'LICENSE'), join(dependencies, 'node', 'LICENSE'))
  112. await extractTar({ file: await pythonArchive(target, paths.downloads), cwd: dependencies })
  113. const require = createRequire(import.meta.url)
  114. const pnpmManifest = require.resolve('pnpm')
  115. const pnpm = JSON.parse(readFileSync(pnpmManifest, 'utf8')) as { version: string }
  116. await cp(dirname(pnpmManifest), join(dependencies, 'pnpm'), { recursive: true, dereference: true })
  117. const desktop = JSON.parse(readFileSync(join(import.meta.dirname, '..', 'package.json'), 'utf8')) as { version: string }
  118. const manifest: PrimaryRuntimeManifest = {
  119. desktopVersion: desktop.version,
  120. platform: target === 'win-x64' ? 'win32' : 'darwin',
  121. arch: target === 'mac-arm64' ? 'arm64' : 'x64',
  122. payloadDigest: primaryRuntimePayloadDigest(target, lock, pnpm.version),
  123. pythonPackages: lock.pythonPackages,
  124. components: {
  125. python: lock.pythonVersion, node: lock.nodeVersion, pnpm: pnpm.version,
  126. numpy: lock.pythonPackages.numpy, pandas: lock.pythonPackages.pandas,
  127. },
  128. }
  129. const entries = workspaceDependencyPaths(output, manifest)
  130. for (const wheel of [...artifact.wheels, ...lock.wheels]) {
  131. await unpackPrimaryRuntimeWheel(await downloadPrimaryRuntimeAsset(wheel.url, wheel.sha256, paths.downloads), entries.pythonPackages)
  132. }
  133. writeFileSync(join(output, 'runtime.json'), `${JSON.stringify(manifest, undefined, 2)}\n`)
  134. const destination = join(paths.runtime, 'primary-runtime')
  135. rmSync(destination, { recursive: true, force: true })
  136. await cp(output, destination, { recursive: true, dereference: true })
  137. } finally {
  138. rmSync(staging, { recursive: true, force: true })
  139. }
  140. const hostRequire = createRequire(resolve(import.meta.dirname, '..', '..', 'desktop-host', 'package.json'))
  141. await prepareOfficeSkillAssets(join(dirname(hostRequire.resolve('@deepseek-ai/dsh-skill-office/package.json')), 'assets'),
  142. join(paths.runtime, 'office-skills'))
  143. if (!options.deferSmoke) smokePrimaryRuntime(join(paths.runtime, 'primary-runtime'))
  144. }
  145. /**
  146. * Execute the native payload's interpreters, package manager and Python libraries.
  147. * @param root - Final payload directory, including any platform signatures.
  148. */
  149. export function smokePrimaryRuntime(root: string): void {
  150. const manifest = JSON.parse(readFileSync(join(root, 'runtime.json'), 'utf8')) as PrimaryRuntimeManifest
  151. if (manifest.platform !== process.platform || manifest.arch !== process.arch) return
  152. if (manifest.pythonPackages === undefined) throw new Error('primary runtime: missing Python distribution versions; prepare the payload before running its smoke checks.')
  153. const entries = workspaceDependencyPaths(root, manifest)
  154. const options = { stdio: 'inherit', timeout: 120_000, env: scrubWindowsSigningEnvironment(process.env) } as const
  155. execFileSync(entries.python, ['-I', '-c', 'import decimal, xml.parsers.expat, lzma, uuid, numpy, pandas; assert numpy.arange(4).sum() == 6; assert pandas.DataFrame({"n": [1, 2]}).n.sum() == 3'], options)
  156. execFileSync(entries.python, ['-I', '-B', join(import.meta.dirname, 'smoke-primary-runtime.py'), JSON.stringify(manifest.pythonPackages),
  157. manifest.components.python, join(dirname(root), 'office-skills', 'scripts', 'check_office.py')], options)
  158. execFileSync(entries.python, ['-I', '-B', '-m', 'pip', 'check'], options)
  159. execFileSync(entries.node, ['-e', `if (process.versions.node !== ${JSON.stringify(manifest.components.node)}) process.exit(1)`], options)
  160. execFileSync(entries.node, [entries.pnpm, '--version'], options)
  161. }
  162. if (import.meta.main) await preparePrimaryRuntime()