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

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