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

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