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

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