1
0

build-exe-for-python-sdk.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /**
  2. * Build the SDK runtime executables and Python node carrier. The fixed
  3. * `@yao-pkg/pkg --sea` route, deploy flags, and artifact layout are owned by
  4. * .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.
  5. * The staged closure is symlink-free, and whole-tree assets cover Cordis's
  6. * runtime imports that pkg cannot discover statically.
  7. */
  8. import { spawn } from 'node:child_process'
  9. import { existsSync, statSync } from 'node:fs'
  10. import { chmod, copyFile, cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
  11. import { basename, dirname, join, resolve, sep } from 'node:path'
  12. import { parseArgs } from 'node:util'
  13. const root = resolve(import.meta.dirname, '..')
  14. /** The closure manifest whose dependencies define the executable. */
  15. const DEPLOY_ROOT_PACKAGE = 'dsh-jsonrpc-agent-pkg'
  16. /** The closed-runtime app entry inside the deployed closure. */
  17. const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-jsonrpc-demo/lib/packaged-bin.js'
  18. const OUTPUT_BASENAME = 'dsh-jsonrpc-agent-pkg'
  19. /** Default Node major; SEA mode requires at least Node 22. */
  20. const DEFAULT_NODE_RANGE = 'node24'
  21. /** Pinned for reproducible builds. */
  22. const PKG_SPEC = '@yao-pkg/pkg@6.21.0'
  23. const OUT_DIR = 'dist-exe'
  24. /** Python package destination; created when absent. */
  25. const PYTHON_RUNTIME_DIR = 'python/sdk-runtime/src/deepseek_harness_runtime/runtime'
  26. /** The deployed closure doubles as the node-mode carrier. */
  27. const PYTHON_NODE_SUBDIR = 'node'
  28. /** Legacy deploy may hoist peer-specialized workspace packages back here. */
  29. const DEPLOY_SOURCE_NODE_MODULES = 'python/sdk-runtime/node_modules'
  30. /** Documentation excluded from the generated runtime directory. */
  31. const DEPLOY_ONLY_DOCS = ['README.md', 'README.zh.md', 'README.i18n.yaml']
  32. /**
  33. * Whole-tree assets cover Cordis's runtime bare-package imports, which pkg's
  34. * static analysis cannot see. Package manifests are explicit because bare-name
  35. * resolution depends on them.
  36. */
  37. const ASSET_GLOBS = [
  38. 'package.json',
  39. 'node_modules/**/*.js',
  40. 'node_modules/**/*.cjs',
  41. 'node_modules/**/*.mjs',
  42. 'node_modules/**/package.json',
  43. 'node_modules/**/*.json',
  44. 'node_modules/**/*.node',
  45. 'node_modules/**/*.wasm',
  46. ]
  47. const PLATFORMS = ['linux', 'macos'] as const
  48. const ARCHES = ['x64', 'arm64'] as const
  49. type Platform = (typeof PLATFORMS)[number]
  50. type Arch = (typeof ARCHES)[number]
  51. function isPlatform(value: string): value is Platform {
  52. return (PLATFORMS as readonly string[]).includes(value)
  53. }
  54. function isArch(value: string): value is Arch {
  55. return (ARCHES as readonly string[]).includes(value)
  56. }
  57. /**
  58. * A parsed pkg target triple, constructed from `--targets` or the host.
  59. */
  60. class Target {
  61. private constructor(
  62. /** pkg Node range (`node<major>`). */
  63. readonly nodeRange: string,
  64. /**
  65. * pkg platform tag. Windows is a documented non-goal
  66. * (.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md).
  67. */
  68. readonly platform: Platform,
  69. /** pkg CPU tag. */
  70. readonly arch: Arch,
  71. ) {}
  72. /** The pkg `--targets` spec string `<nodeRange>-<platform>-<arch>`. */
  73. get spec(): string {
  74. return `${this.nodeRange}-${this.platform}-${this.arch}`
  75. }
  76. /**
  77. * Parse one target spec, rejecting malformed triples and unsupported platform or architecture.
  78. * @param spec - the raw triple, e.g. `node24-linux-x64`.
  79. * @returns the parsed target.
  80. */
  81. static parse(spec: string): Target {
  82. const parts = spec.split('-')
  83. const [nodeRange, platform, arch] = parts
  84. if (parts.length !== 3 || nodeRange === undefined || platform === undefined || arch === undefined) {
  85. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)} must be <nodeRange>-<platform>-<arch>, e.g. node24-linux-x64.`)
  86. }
  87. if (!/^node\d+$/.test(nodeRange)) {
  88. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: node range must look like node24, got ${JSON.stringify(nodeRange)}.`)
  89. }
  90. if (!isPlatform(platform)) {
  91. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: platform must be one of ${PLATFORMS.join(', ')}, got ${JSON.stringify(platform)}.`)
  92. }
  93. if (!isArch(arch)) {
  94. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: arch must be one of ${ARCHES.join(', ')}, got ${JSON.stringify(arch)}.`)
  95. }
  96. return new Target(nodeRange, platform, arch)
  97. }
  98. /**
  99. * Resolve the host-platform default on Node 24.
  100. * @returns the host target; throws on an unsupported host platform or arch.
  101. */
  102. static host(): Target {
  103. const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : undefined
  104. if (platform === undefined) {
  105. throw new Error(`build-exe-for-python-sdk: unsupported host platform ${process.platform}; pass --targets explicitly.`)
  106. }
  107. const arch = process.arch === 'x64' || process.arch === 'arm64' ? process.arch : undefined
  108. if (arch === undefined) {
  109. throw new Error(`build-exe-for-python-sdk: unsupported host arch ${process.arch}; pass --targets explicitly.`)
  110. }
  111. return new Target(DEFAULT_NODE_RANGE, platform, arch)
  112. }
  113. }
  114. /**
  115. * Validated CLI configuration; construction owns help and parse-error exits.
  116. */
  117. class BuildCli {
  118. private constructor(
  119. /** Build targets; defaults to the host platform only. */
  120. readonly targets: readonly Target[],
  121. /** Skip step 1 (`pnpm run build`); lib/ artifacts must already exist. */
  122. readonly skipBuild: boolean,
  123. /** Print every command and config patch instead of executing. */
  124. readonly dryRun: boolean,
  125. ) {}
  126. /**
  127. * Parse argv. Help exits 0; malformed flags exit 1; invalid or colliding
  128. * targets throw.
  129. * @param argv - the raw arguments (`process.argv.slice(2)`).
  130. * @returns the parsed, validated configuration.
  131. */
  132. static parse(argv: string[]): BuildCli {
  133. let values: ReturnType<typeof BuildCli.parseRaw>
  134. try {
  135. values = BuildCli.parseRaw(argv)
  136. } catch (error) {
  137. console.error(`build-exe-for-python-sdk: ${error instanceof Error ? error.message : String(error)}\n`)
  138. console.error(BuildCli.usage())
  139. process.exit(1)
  140. }
  141. if (values.help) {
  142. console.log(BuildCli.usage())
  143. process.exit(0)
  144. }
  145. const targets = values.targets === undefined
  146. ? [Target.host()]
  147. : values.targets.split(',').map(part => part.trim()).filter(part => part !== '').map(spec => Target.parse(spec))
  148. if (targets.length === 0) throw new Error('build-exe-for-python-sdk: --targets is empty.')
  149. const seen = new Set<string>()
  150. for (const target of targets) {
  151. const key = `${target.platform}-${target.arch}`
  152. if (seen.has(key)) {
  153. throw new Error(`build-exe-for-python-sdk: duplicate platform-arch ${key} in --targets; canonical product names would collide.`)
  154. }
  155. seen.add(key)
  156. }
  157. return new BuildCli(targets, values['skip-build'], values['dry-run'])
  158. }
  159. private static parseRaw(argv: string[]) {
  160. return parseArgs({
  161. args: argv,
  162. options: {
  163. 'targets': { type: 'string' },
  164. 'skip-build': { type: 'boolean', default: false },
  165. 'dry-run': { type: 'boolean', default: false },
  166. 'help': { type: 'boolean', default: false },
  167. },
  168. }).values
  169. }
  170. private static usage(): string {
  171. return [
  172. 'Usage: pnpm exec tsx scripts/build-exe-for-python-sdk.ts [flags]',
  173. '',
  174. ' --targets=<t1,t2,...> pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64.',
  175. ' Default: the host platform only (on node24).',
  176. ' --skip-build skip `pnpm run build` (lib/ artifacts must already exist).',
  177. ' --dry-run print every command and config patch without executing.',
  178. ' --help print this help.',
  179. '',
  180. `Build route: ${PKG_SPEC} --sea; see .agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md.`,
  181. `Stages the node carrier in ${PYTHON_RUNTIME_DIR}/${PYTHON_NODE_SUBDIR} and writes executables to ${OUT_DIR}/.`,
  182. ].join('\n')
  183. }
  184. }
  185. function pnpmBin(): string {
  186. return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
  187. }
  188. /**
  189. * Render a command for logs and errors, quoting arguments with spaces.
  190. * @param command - the executable.
  191. * @param args - its arguments.
  192. * @returns the printable command line.
  193. */
  194. function formatCommand(command: string, args: string[]): string {
  195. return [command, ...args].map(part => (part.includes(' ') ? JSON.stringify(part) : part)).join(' ')
  196. }
  197. /**
  198. * Sequential build pipeline. Subprocesses inherit stdio and errors include
  199. * the command; dry runs print commands and filesystem changes.
  200. */
  201. class SingleExeBuild {
  202. /**
  203. * The cleared deploy target, pkg input, and Python node-mode carrier. The
  204. * checked-in default `cordis.yml` remains in its parent directory.
  205. */
  206. readonly staging = resolve(root, PYTHON_RUNTIME_DIR, PYTHON_NODE_SUBDIR)
  207. private readonly outDir = resolve(root, OUT_DIR)
  208. constructor(private readonly cli: BuildCli) {}
  209. /** Verify the closure before compiling or packaging. */
  210. async verifyClosure(): Promise<void> {
  211. await this.run('runtime dependency closure', pnpmBin(), ['run', 'verify-runtime-closure'])
  212. }
  213. /** Build all package artifacts unless `--skip-build` was passed. */
  214. async build(): Promise<void> {
  215. if (this.cli.skipBuild) {
  216. console.log('build-exe-for-python-sdk: skipping pnpm run build (--skip-build)')
  217. return
  218. }
  219. await this.run('build', pnpmBin(), ['run', 'build'])
  220. }
  221. /** Clear and deploy the runtime closure into the node carrier. */
  222. async deployStaging(): Promise<void> {
  223. if (this.staging === root || root.startsWith(this.staging + sep)) {
  224. throw new Error(`build-exe-for-python-sdk: refusing to clear staging dir ${this.staging}: it contains the repo root.`)
  225. }
  226. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${this.staging}`)
  227. else await rm(this.staging, { recursive: true, force: true })
  228. await this.run('deploy', pnpmBin(), [
  229. '--filter',
  230. DEPLOY_ROOT_PACKAGE,
  231. 'deploy',
  232. '--legacy',
  233. '--prod',
  234. '--config.node-linker=hoisted',
  235. '--config.auto-install-peers=false',
  236. '--config.link-workspace-packages=true',
  237. this.staging,
  238. ])
  239. await this.restoreLegacyHoists()
  240. if (this.cli.dryRun) {
  241. for (const name of DEPLOY_ONLY_DOCS) console.log(`build-exe-for-python-sdk: [dry-run] rm -f ${join(this.staging, name)}`)
  242. } else {
  243. await Promise.all(DEPLOY_ONLY_DOCS.map(name => rm(join(this.staging, name), { force: true })))
  244. }
  245. }
  246. /**
  247. * Restore direct packages that pnpm's legacy hoister places beside the deploy
  248. * source instead of in the target. The runtime manifest supplies every peer,
  249. * so package-local node_modules trees are omitted to preserve one flat Cordis
  250. * instance and a symlink-free packaged payload.
  251. */
  252. private async restoreLegacyHoists(): Promise<void> {
  253. if (this.cli.dryRun) {
  254. console.log('build-exe-for-python-sdk: [dry-run] restore direct dependencies omitted by legacy deploy')
  255. return
  256. }
  257. const manifestPath = join(this.staging, 'package.json')
  258. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as {
  259. dependencies?: Record<string, string>
  260. }
  261. const sourceNodeModules = resolve(root, DEPLOY_SOURCE_NODE_MODULES)
  262. const restored: string[] = []
  263. for (const dependency of Object.keys(manifest.dependencies ?? {}).sort()) {
  264. const destination = join(this.staging, 'node_modules', dependency)
  265. if (existsSync(destination)) continue
  266. const source = join(sourceNodeModules, dependency)
  267. if (!existsSync(source)) {
  268. throw new Error(
  269. `build-exe-for-python-sdk: deployed dependency ${dependency} is absent from both ${destination} and ${source}.`,
  270. )
  271. }
  272. await mkdir(dirname(destination), { recursive: true })
  273. const nestedNodeModules = join(source, 'node_modules')
  274. await cp(source, destination, {
  275. recursive: true,
  276. filter: path => path !== nestedNodeModules && !path.startsWith(nestedNodeModules + sep),
  277. })
  278. restored.push(dependency)
  279. }
  280. const stillMissing = Object.keys(manifest.dependencies ?? {})
  281. .filter(dependency => !existsSync(join(this.staging, 'node_modules', dependency)))
  282. if (stillMissing.length > 0) {
  283. throw new Error(`build-exe-for-python-sdk: staged dependencies remain missing: ${stillMissing.join(', ')}.`)
  284. }
  285. if (restored.length > 0) {
  286. console.log(`build-exe-for-python-sdk: restored legacy deploy hoists: ${restored.join(', ')}`)
  287. }
  288. }
  289. /** Add the executable entry and pkg assets to the staged manifest. */
  290. async injectPkgConfig(): Promise<void> {
  291. const patch = { bin: ENTRY_BIN, pkg: { assets: ASSET_GLOBS } }
  292. const manifestPath = join(this.staging, 'package.json')
  293. if (this.cli.dryRun) {
  294. console.log(`build-exe-for-python-sdk: [dry-run] patch ${manifestPath} with ${JSON.stringify(patch)}`)
  295. return
  296. }
  297. if (!existsSync(manifestPath)) {
  298. throw new Error(`build-exe-for-python-sdk: ${manifestPath} missing — pnpm deploy did not produce a staged package.`)
  299. }
  300. if (!existsSync(join(this.staging, ENTRY_BIN))) {
  301. throw new Error(`build-exe-for-python-sdk: ${join(this.staging, ENTRY_BIN)} missing — run without --skip-build so lib/ artifacts exist.`)
  302. }
  303. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
  304. await writeFile(manifestPath, `${JSON.stringify({ ...manifest, ...patch }, null, 2)}\n`)
  305. console.log(`build-exe-for-python-sdk: injected pkg config into ${manifestPath}`)
  306. }
  307. /**
  308. * Package one target; SEA mode accepts one target per invocation.
  309. * @param target - the pkg target triple to build.
  310. * @returns the executable path and, on macOS, its helper path.
  311. */
  312. async pack(target: Target): Promise<string[]> {
  313. const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`)
  314. await this.prepareNativePty(target)
  315. if (!this.cli.dryRun) await mkdir(this.outDir, { recursive: true })
  316. await this.run(`pkg ${target.spec}`, pnpmBin(), [
  317. 'dlx',
  318. PKG_SPEC,
  319. this.staging,
  320. '--sea',
  321. '--targets',
  322. target.spec,
  323. '--output',
  324. product,
  325. ])
  326. if (!this.cli.dryRun && !existsSync(product)) {
  327. throw new Error(`build-exe-for-python-sdk: product ${product} is missing after the pkg run; inspect ${this.outDir}.`)
  328. }
  329. if (target.platform !== 'macos') return [product]
  330. const spawnHelper = `${product}-spawn-helper`
  331. const source = join(this.staging, 'node_modules', 'node-pty', 'prebuilds', `darwin-${target.arch}`, 'spawn-helper')
  332. if (this.cli.dryRun) {
  333. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${spawnHelper}`)
  334. } else {
  335. await copyFile(source, spawnHelper)
  336. await chmod(spawnHelper, 0o755)
  337. }
  338. return [product, spawnHelper]
  339. }
  340. /**
  341. * Put the target node-pty addon in the staged closure. Linux npm installs
  342. * build it from source, but legacy deploy omits that side-effect directory.
  343. * @param target - the pkg target whose native addon is being staged.
  344. */
  345. private async prepareNativePty(target: Target): Promise<void> {
  346. const stagedBuild = join(this.staging, 'node_modules', 'node-pty', 'build')
  347. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${stagedBuild}`)
  348. else await rm(stagedBuild, { recursive: true, force: true })
  349. if (target.platform !== 'linux') return
  350. const source = join(root, 'packages', 'subprocess', 'subprocess-local', 'node_modules', 'node-pty', 'build', 'Release', 'pty.node')
  351. const destination = join(stagedBuild, 'Release', 'pty.node')
  352. if (this.cli.dryRun) {
  353. console.log(`build-exe-for-python-sdk: [dry-run] cp ${source} ${destination}`)
  354. return
  355. }
  356. const host = Target.host()
  357. if (target.platform !== host.platform || target.arch !== host.arch) {
  358. throw new Error(
  359. 'build-exe-for-python-sdk: build the Linux runtime on its target architecture; '
  360. + `target ${target.platform}-${target.arch} does not match host ${host.platform}-${host.arch}.`,
  361. )
  362. }
  363. await mkdir(dirname(destination), { recursive: true })
  364. await copyFile(source, destination)
  365. }
  366. /**
  367. * Print each product path and, outside dry-run mode, its size.
  368. * @param products - the product paths returned by {@link pack}.
  369. */
  370. printProducts(products: string[]): void {
  371. console.log(this.cli.dryRun ? 'build-exe-for-python-sdk: [dry-run] would produce:' : 'build-exe-for-python-sdk: products:')
  372. for (const path of products) {
  373. if (this.cli.dryRun) {
  374. console.log(` ${path}`)
  375. continue
  376. }
  377. const megabytes = statSync(path).size / (1024 * 1024)
  378. console.log(` ${path} (${megabytes.toFixed(1)} MB)`)
  379. }
  380. }
  381. /**
  382. * Copy each product into the Python runtime package. The deployed node
  383. * carrier is already in place, and `dist-exe/` retains upload copies.
  384. * @param products - the product paths returned by {@link pack}.
  385. */
  386. async syncToPythonRuntime(products: string[]): Promise<void> {
  387. const destDir = resolve(root, PYTHON_RUNTIME_DIR)
  388. if (this.cli.dryRun) {
  389. for (const path of products) {
  390. console.log(`build-exe-for-python-sdk: [dry-run] cp ${path} ${join(destDir, basename(path))}`)
  391. }
  392. return
  393. }
  394. await mkdir(destDir, { recursive: true })
  395. for (const path of products) {
  396. const destination = join(destDir, basename(path))
  397. await copyFile(path, destination)
  398. await chmod(destination, statSync(path).mode & 0o777)
  399. console.log(`build-exe-for-python-sdk: synced ${destination}`)
  400. }
  401. }
  402. /**
  403. * Run one subprocess with inherited stdio. Spawn and non-zero-exit errors
  404. * include the command; dry runs only print it.
  405. * @param label - the step name used in logs and error messages.
  406. * @param command - the executable.
  407. * @param args - its arguments.
  408. */
  409. private async run(label: string, command: string, args: string[]): Promise<void> {
  410. const printable = formatCommand(command, args)
  411. if (this.cli.dryRun) {
  412. console.log(`build-exe-for-python-sdk: [dry-run] ${printable}`)
  413. return
  414. }
  415. console.log(`build-exe-for-python-sdk: ${label}: ${printable}`)
  416. await new Promise<void>((resolvePromise, reject) => {
  417. const child = spawn(command, args, {
  418. cwd: root,
  419. stdio: 'inherit',
  420. // Artifact builds must not mutate or validate a developer's Git hooks.
  421. env: { ...process.env, CI: 'true' },
  422. })
  423. child.once('error', (error) => {
  424. reject(new Error(`build-exe-for-python-sdk: ${label} failed to spawn: ${error.message} (${printable})`))
  425. })
  426. child.once('exit', (code, signal) => {
  427. if (code === 0) {
  428. resolvePromise()
  429. return
  430. }
  431. const cause = code === null ? `signal ${signal ?? 'unknown'}` : `exit code ${code}`
  432. reject(new Error(`build-exe-for-python-sdk: ${label} failed (${cause}): ${printable}`))
  433. })
  434. })
  435. }
  436. }
  437. async function main(): Promise<void> {
  438. const cli = BuildCli.parse(process.argv.slice(2))
  439. const pipeline = new SingleExeBuild(cli)
  440. console.log(`build-exe-for-python-sdk: targets: ${cli.targets.map(target => target.spec).join(', ')}`)
  441. console.log(`build-exe-for-python-sdk: staging: ${pipeline.staging}`)
  442. await pipeline.verifyClosure()
  443. await pipeline.build()
  444. await pipeline.deployStaging()
  445. await pipeline.injectPkgConfig()
  446. const products: string[] = []
  447. for (const target of cli.targets) products.push(...await pipeline.pack(target))
  448. pipeline.printProducts(products)
  449. await pipeline.syncToPythonRuntime(products)
  450. }
  451. await main()