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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /**
  2. * Build the single-file SDK runtime executables
  3. * (docs/rfc/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md).
  4. *
  5. * Every settled decision is hardcoded — the PoC judged @yao-pkg/pkg's
  6. * standard mode unusable for this architecture (its ESM→CJS transform breaks
  7. * every runtime `import()`), so the pipeline is fixed on `--sea` mode, plain
  8. * ESM entry, plain-source assets, and a hoisted (symlink-free) staged tree.
  9. *
  10. * Pipeline — every step fails loud with the command it ran:
  11. *
  12. * 1. `pnpm run build` — all packages emit `lib/` (skippable via --skip-build).
  13. * 2. `pnpm --filter dsh-jsonrpc-agent-pkg deploy` — materialize the
  14. * closure-manifest package (python/sdk-runtime/package.json — the single
  15. * source of truth for the exe's plugin set) into the staging dir
  16. * (cleared first; pnpm refuses a non-empty deploy target). Flags, all
  17. * verified against pnpm 11.7: `--legacy` because the workspace does not
  18. * set `inject-workspace-packages=true`; `node-linker=hoisted` for a plain
  19. * file tree with zero symlinks (the safe shape for pkg's VFS, and it
  20. * physically guarantees a single cordis copy); `auto-install-peers=false`
  21. * so transitive `^0.0.x` peers on unpublished packages never hit the
  22. * registry; `link-workspace-packages=true` so the closure resolves to
  23. * workspace/vendor sources.
  24. * 3. Inject the pkg config into the staged package.json: `bin` = the ESM
  25. * `node_modules/@deepseek-ai/dsh-jsonrpc-agent/lib/bin.js` (SEA mode
  26. * hands it to Node's default ESM loader — no CJS shim), plus whole-tree
  27. * asset globs. The cordis Loader resolves plugins
  28. * through runtime dynamic `import()` of bare package names, so pkg's
  29. * static analysis discovers none of them — the entire staged tree must be
  30. * globbed in explicitly.
  31. * 4. `pnpm dlx @yao-pkg/pkg@<pinned> <staging> --sea --targets <t> --output
  32. * <out>/dsh-jsonrpc-agent-pkg-<platform>-<arch>` — once per target (SEA mode
  33. * packs a single target per invocation), so each product gets its
  34. * canonical name directly.
  35. * 5. Sync into the Python runtime package
  36. * (python/sdk-runtime/src/deepseek_harness_runtime/runtime/,
  37. * created if missing): each product under its canonical filename (exe
  38. * mode), plus the whole staged closure into runtime/node/ (node mode —
  39. * `node runtime/node/node_modules/@deepseek-ai/dsh-jsonrpc-agent/lib/bin.js`
  40. * runs it directly; the injected pkg
  41. * fields are harmless to node). dist-exe/ keeps the originals for CI
  42. * artifact upload.
  43. *
  44. * `pnpm exec tsx scripts/build-exe-for-python-sdk.ts` → host-platform exe into dist-exe/
  45. * `pnpm exec tsx scripts/build-exe-for-python-sdk.ts --targets=node24-linux-x64,node24-linux-arm64,node24-macos-arm64`
  46. * `pnpm exec tsx scripts/build-exe-for-python-sdk.ts --dry-run` → print the plan without executing
  47. */
  48. import { spawn } from 'node:child_process'
  49. import { existsSync, mkdirSync, statSync } from 'node:fs'
  50. import { copyFile, readFile, rm, writeFile } from 'node:fs/promises'
  51. import { basename, join, resolve, sep } from 'node:path'
  52. import { parseArgs } from 'node:util'
  53. const root = resolve(import.meta.dirname, '..')
  54. /**
  55. * The deploy root: the closure-manifest package (python/sdk-runtime) whose
  56. * dependencies define the exe's contents; the runnable entry inside the
  57. * closure is {@link ENTRY_BIN}.
  58. */
  59. const DEPLOY_ROOT_PACKAGE = 'dsh-jsonrpc-agent-pkg'
  60. /** The bin entry inside the deployed closure (the dsh-jsonrpc-agent app bin). */
  61. const ENTRY_BIN = 'node_modules/@deepseek-ai/dsh-jsonrpc-agent/lib/bin.js'
  62. /** Basename of every product; the canonical name appends `-<platform>-<arch>`. */
  63. const OUTPUT_BASENAME = 'dsh-jsonrpc-agent-pkg'
  64. /** Default exe Node major; SEA mode requires >= node22, the repo tracks node24. */
  65. const DEFAULT_NODE_RANGE = 'node24'
  66. /** Pinned pkg version (the one the PoC and acceptance ran on) for reproducible builds. */
  67. const PKG_SPEC = '@yao-pkg/pkg@6.21.0'
  68. /** Staging dir for the deployed closure — cleared on every run (gitignored). */
  69. // (No external staging dir: the deploy target IS the Python runtime's
  70. // node-mode carrier — see PYTHON_RUNTIME_DIR/PYTHON_NODE_SUBDIR.)
  71. /** Product output dir (gitignored). */
  72. const OUT_DIR = 'dist-exe'
  73. /**
  74. * Python runtime package dir the products are synced into. A parallel change
  75. * owns the directory and its .gitignore; this script's only contract is the
  76. * destination path, so a missing dir is created, never an error.
  77. */
  78. const PYTHON_RUNTIME_DIR = 'python/sdk-runtime/src/deepseek_harness_runtime/runtime'
  79. /** Subdir of {@link PYTHON_RUNTIME_DIR} carrying the staged closure for node-mode execution. */
  80. const PYTHON_NODE_SUBDIR = 'node'
  81. /**
  82. * Whole-tree asset globs. The cordis Loader dynamic-imports bare package names
  83. * at runtime, invisible to pkg's static analysis, so every runtime file in the
  84. * closure is listed; SEA mode ships them as plain source in the VFS. Every
  85. * package.json must ride along — bare-name resolution dies without them (the
  86. * json glob would already match, but the manifests are resolution-critical, so
  87. * they get their own explicit entry).
  88. */
  89. const ASSET_GLOBS = [
  90. 'package.json',
  91. 'node_modules/**/*.js',
  92. 'node_modules/**/*.cjs',
  93. 'node_modules/**/*.mjs',
  94. 'node_modules/**/package.json',
  95. 'node_modules/**/*.json',
  96. 'node_modules/**/*.node',
  97. 'node_modules/**/*.wasm',
  98. ]
  99. const PLATFORMS = ['linux', 'macos'] as const
  100. const ARCHES = ['x64', 'arm64'] as const
  101. type Platform = (typeof PLATFORMS)[number]
  102. type Arch = (typeof ARCHES)[number]
  103. /** True when `value` is a supported pkg platform tag. */
  104. function isPlatform(value: string): value is Platform {
  105. return (PLATFORMS as readonly string[]).includes(value)
  106. }
  107. /** True when `value` is a supported pkg CPU tag. */
  108. function isArch(value: string): value is Arch {
  109. return (ARCHES as readonly string[]).includes(value)
  110. }
  111. /**
  112. * One pkg target triple, e.g. `node24-linux-x64`, as an immutable value.
  113. * Construction goes through {@link Target.parse} (a `--targets` entry) or
  114. * {@link Target.host} (the default), which own all validation.
  115. */
  116. class Target {
  117. private constructor(
  118. /** pkg Node range (`node<major>`); pins the official base binary pkg pulls. */
  119. readonly nodeRange: string,
  120. /**
  121. * pkg platform tag. Windows is a documented non-goal
  122. * (docs/rfc/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md).
  123. */
  124. readonly platform: Platform,
  125. /** pkg CPU tag. */
  126. readonly arch: Arch,
  127. ) {}
  128. /** The pkg `--targets` spec string `<nodeRange>-<platform>-<arch>`. */
  129. get spec(): string {
  130. return `${this.nodeRange}-${this.platform}-${this.arch}`
  131. }
  132. /**
  133. * Parse and validate one target spec; throws on any malformed component.
  134. * @param spec - the raw triple, e.g. `node24-linux-x64`.
  135. * @returns the parsed target.
  136. */
  137. static parse(spec: string): Target {
  138. const parts = spec.split('-')
  139. const [nodeRange, platform, arch] = parts
  140. if (parts.length !== 3 || nodeRange === undefined || platform === undefined || arch === undefined) {
  141. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)} must be <nodeRange>-<platform>-<arch>, e.g. node24-linux-x64.`)
  142. }
  143. if (!/^node\d+$/.test(nodeRange)) {
  144. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: node range must look like node24, got ${JSON.stringify(nodeRange)}.`)
  145. }
  146. if (!isPlatform(platform)) {
  147. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: platform must be one of ${PLATFORMS.join(', ')} (Windows is a docs/rfc/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md non-goal), got ${JSON.stringify(platform)}.`)
  148. }
  149. if (!isArch(arch)) {
  150. throw new Error(`build-exe-for-python-sdk: target ${JSON.stringify(spec)}: arch must be one of ${ARCHES.join(', ')}, got ${JSON.stringify(arch)}.`)
  151. }
  152. return new Target(nodeRange, platform, arch)
  153. }
  154. /**
  155. * The default target when --targets is omitted: the host platform on node24.
  156. * @returns the host target; throws on an unsupported host platform or arch.
  157. */
  158. static host(): Target {
  159. const platform = process.platform === 'darwin' ? 'macos' : process.platform === 'linux' ? 'linux' : undefined
  160. if (platform === undefined) {
  161. throw new Error(`build-exe-for-python-sdk: unsupported host platform ${process.platform}; pass --targets explicitly.`)
  162. }
  163. const arch = process.arch === 'x64' || process.arch === 'arm64' ? process.arch : undefined
  164. if (arch === undefined) {
  165. throw new Error(`build-exe-for-python-sdk: unsupported host arch ${process.arch}; pass --targets explicitly.`)
  166. }
  167. return new Target(DEFAULT_NODE_RANGE, platform, arch)
  168. }
  169. }
  170. /**
  171. * Parsed CLI configuration. {@link BuildCli.parse} is the only constructor
  172. * path — it owns flag parsing, target validation, and the --help / bad-flag
  173. * process exits, so an instance always holds a valid plan.
  174. */
  175. class BuildCli {
  176. private constructor(
  177. /** Build targets; defaults to the host platform only. */
  178. readonly targets: readonly Target[],
  179. /** Skip step 1 (`pnpm run build`); lib/ artifacts must already exist. */
  180. readonly skipBuild: boolean,
  181. /** Print every command and config patch instead of executing. */
  182. readonly dryRun: boolean,
  183. ) {}
  184. /**
  185. * Parse argv into a validated configuration. Exits the process for --help
  186. * (code 0, usage) and for unknown/malformed flags (code 1, usage on
  187. * stderr); throws on invalid or colliding targets.
  188. * @param argv - the raw arguments (`process.argv.slice(2)`).
  189. * @returns the parsed, validated configuration.
  190. */
  191. static parse(argv: string[]): BuildCli {
  192. let values: ReturnType<typeof BuildCli.parseRaw>
  193. try {
  194. values = BuildCli.parseRaw(argv)
  195. } catch (error) {
  196. console.error(`build-exe-for-python-sdk: ${error instanceof Error ? error.message : String(error)}\n`)
  197. console.error(BuildCli.usage())
  198. process.exit(1)
  199. }
  200. if (values.help) {
  201. console.log(BuildCli.usage())
  202. process.exit(0)
  203. }
  204. const targets = values.targets === undefined
  205. ? [Target.host()]
  206. : values.targets.split(',').map(part => part.trim()).filter(part => part !== '').map(spec => Target.parse(spec))
  207. if (targets.length === 0) throw new Error('build-exe-for-python-sdk: --targets is empty.')
  208. const seen = new Set<string>()
  209. for (const target of targets) {
  210. const key = `${target.platform}-${target.arch}`
  211. if (seen.has(key)) {
  212. throw new Error(`build-exe-for-python-sdk: duplicate platform-arch ${key} in --targets; canonical product names would collide.`)
  213. }
  214. seen.add(key)
  215. }
  216. return new BuildCli(targets, values['skip-build'], values['dry-run'])
  217. }
  218. /** The flag grammar in one place; parseArgs throws on any unknown flag. */
  219. private static parseRaw(argv: string[]) {
  220. return parseArgs({
  221. args: argv,
  222. options: {
  223. 'targets': { type: 'string' },
  224. 'skip-build': { type: 'boolean', default: false },
  225. 'dry-run': { type: 'boolean', default: false },
  226. 'help': { type: 'boolean', default: false },
  227. },
  228. }).values
  229. }
  230. /** The --help text; also printed under flag-parse errors. */
  231. private static usage(): string {
  232. return [
  233. 'Usage: pnpm exec tsx scripts/build-exe-for-python-sdk.ts [flags]',
  234. '',
  235. ' --targets=<t1,t2,...> pkg targets, e.g. node24-linux-x64,node24-linux-arm64,node24-macos-arm64.',
  236. ' Default: the host platform only (on node24).',
  237. ' --skip-build skip `pnpm run build` (lib/ artifacts must already exist).',
  238. ' --dry-run print every command and config patch without executing.',
  239. ' --help print this help.',
  240. '',
  241. 'Settled decisions are hardcoded (docs/rfc/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md): pkg runs in --sea mode',
  242. `(standard mode breaks runtime import()), pinned to ${PKG_SPEC}; the deploy tree is`,
  243. `hoisted/symlink-free; the closure deploys straight into ${PYTHON_RUNTIME_DIR}/${PYTHON_NODE_SUBDIR} and products land in ${OUT_DIR}/.`,
  244. ].join('\n')
  245. }
  246. }
  247. /** The pnpm executable name for the host OS. */
  248. function pnpmBin(): string {
  249. return process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
  250. }
  251. /**
  252. * Render a command line for logs and error messages, quoting arguments that
  253. * contain spaces.
  254. * @param command - the executable.
  255. * @param args - its arguments.
  256. * @returns the printable command line.
  257. */
  258. function formatCommand(command: string, args: string[]): string {
  259. return [command, ...args].map(part => (part.includes(' ') ? JSON.stringify(part) : part)).join(' ')
  260. }
  261. /**
  262. * The four-step build pipeline over one parsed CLI. Steps are sequential
  263. * async methods; every subprocess inherits stdio and fails loud with the
  264. * exact command it ran. In --dry-run the command/filesystem layer prints
  265. * what it would do instead of executing.
  266. */
  267. class SingleExeBuild {
  268. /**
  269. * Absolute staging dir — the Python runtime's node-mode carrier: step 2
  270. * deploys the closure DIRECTLY here (cleared first; it is a pure build
  271. * product, the checked-in default `cordis.yml` lives one level up), step 4
  272. * reads it as the pkg input, and node mode runs it in place.
  273. */
  274. readonly staging = resolve(root, PYTHON_RUNTIME_DIR, PYTHON_NODE_SUBDIR)
  275. /** Absolute product output dir. */
  276. private readonly outDir = resolve(root, OUT_DIR)
  277. constructor(private readonly cli: BuildCli) {}
  278. /** Step 1: `pnpm run build` — all packages emit `lib/` (skipped via --skip-build). */
  279. async build(): Promise<void> {
  280. if (this.cli.skipBuild) {
  281. console.log('build-exe-for-python-sdk: skipping pnpm run build (--skip-build)')
  282. return
  283. }
  284. await this.run('build', pnpmBin(), ['run', 'build'])
  285. }
  286. /** Step 2: clear the staging dir and deploy the bridge closure into it. */
  287. async deployStaging(): Promise<void> {
  288. if (this.staging === root || root.startsWith(this.staging + sep)) {
  289. throw new Error(`build-exe-for-python-sdk: refusing to clear staging dir ${this.staging}: it contains the repo root.`)
  290. }
  291. if (this.cli.dryRun) console.log(`build-exe-for-python-sdk: [dry-run] rm -rf ${this.staging}`)
  292. else await rm(this.staging, { recursive: true, force: true })
  293. await this.run('deploy', pnpmBin(), [
  294. '--filter',
  295. DEPLOY_ROOT_PACKAGE,
  296. 'deploy',
  297. '--legacy',
  298. '--prod',
  299. '--config.node-linker=hoisted',
  300. '--config.auto-install-peers=false',
  301. '--config.link-workspace-packages=true',
  302. this.staging,
  303. ])
  304. }
  305. /** Step 3: patch the staged package.json with the bin entry + pkg asset globs. */
  306. async injectPkgConfig(): Promise<void> {
  307. const patch = { bin: ENTRY_BIN, pkg: { assets: ASSET_GLOBS } }
  308. const manifestPath = join(this.staging, 'package.json')
  309. if (this.cli.dryRun) {
  310. console.log(`build-exe-for-python-sdk: [dry-run] patch ${manifestPath} with ${JSON.stringify(patch)}`)
  311. return
  312. }
  313. if (!existsSync(manifestPath)) {
  314. throw new Error(`build-exe-for-python-sdk: ${manifestPath} missing — pnpm deploy did not produce a staged package.`)
  315. }
  316. if (!existsSync(join(this.staging, ENTRY_BIN))) {
  317. throw new Error(`build-exe-for-python-sdk: ${join(this.staging, ENTRY_BIN)} missing — run without --skip-build so lib/ artifacts exist.`)
  318. }
  319. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as Record<string, unknown>
  320. await writeFile(manifestPath, `${JSON.stringify({ ...manifest, ...patch }, null, 2)}\n`)
  321. console.log(`build-exe-for-python-sdk: injected pkg config into ${manifestPath}`)
  322. }
  323. /**
  324. * Step 4: run @yao-pkg/pkg over the staged tree for ONE target (SEA mode
  325. * packs a single target per invocation) and return the product path.
  326. * @param target - the pkg target triple to build.
  327. * @returns the canonical product path `<out>/dsh-jsonrpc-agent-pkg-<platform>-<arch>`.
  328. */
  329. async pack(target: Target): Promise<string> {
  330. const product = join(this.outDir, `${OUTPUT_BASENAME}-${target.platform}-${target.arch}`)
  331. if (!this.cli.dryRun) mkdirSync(this.outDir, { recursive: true })
  332. await this.run(`pkg ${target.spec}`, pnpmBin(), [
  333. 'dlx',
  334. PKG_SPEC,
  335. this.staging,
  336. '--sea',
  337. '--targets',
  338. target.spec,
  339. '--output',
  340. product,
  341. ])
  342. if (!this.cli.dryRun && !existsSync(product)) {
  343. throw new Error(`build-exe-for-python-sdk: product ${product} is missing after the pkg run; inspect ${this.outDir}.`)
  344. }
  345. return product
  346. }
  347. /**
  348. * Print each product path (and size, when it exists on disk).
  349. * @param products - the product paths returned by {@link pack}.
  350. */
  351. printProducts(products: string[]): void {
  352. console.log(this.cli.dryRun ? 'build-exe-for-python-sdk: [dry-run] would produce:' : 'build-exe-for-python-sdk: products:')
  353. for (const product of products) {
  354. if (this.cli.dryRun) {
  355. console.log(` ${product}`)
  356. continue
  357. }
  358. const megabytes = statSync(product).size / (1024 * 1024)
  359. console.log(` ${product} (${megabytes.toFixed(1)} MB)`)
  360. }
  361. }
  362. /**
  363. * Step 5: copy every product into the Python runtime package under its
  364. * canonical filename (exe mode). The node-mode carrier needs no sync — step
  365. * 2 deployed the closure into it directly. dist-exe/ keeps the originals
  366. * for CI artifact upload; the destination dir is created if missing.
  367. * @param products - the product paths returned by {@link pack}.
  368. */
  369. async syncToPythonRuntime(products: string[]): Promise<void> {
  370. const destDir = resolve(root, PYTHON_RUNTIME_DIR)
  371. if (this.cli.dryRun) {
  372. for (const product of products) {
  373. console.log(`build-exe-for-python-sdk: [dry-run] cp ${product} ${join(destDir, basename(product))}`)
  374. }
  375. return
  376. }
  377. mkdirSync(destDir, { recursive: true })
  378. for (const product of products) {
  379. const destination = join(destDir, basename(product))
  380. await copyFile(product, destination)
  381. console.log(`build-exe-for-python-sdk: synced ${destination}`)
  382. }
  383. }
  384. /**
  385. * Run one pipeline step as a subprocess with inherited stdio; reject —
  386. * carrying the printable command — on spawn failure and non-zero exit
  387. * alike. In --dry-run, print the command instead of executing.
  388. * @param label - the step name used in logs and error messages.
  389. * @param command - the executable.
  390. * @param args - its arguments.
  391. */
  392. private async run(label: string, command: string, args: string[]): Promise<void> {
  393. const printable = formatCommand(command, args)
  394. if (this.cli.dryRun) {
  395. console.log(`build-exe-for-python-sdk: [dry-run] ${printable}`)
  396. return
  397. }
  398. console.log(`build-exe-for-python-sdk: ${label}: ${printable}`)
  399. await new Promise<void>((resolvePromise, reject) => {
  400. const child = spawn(command, args, { cwd: root, stdio: 'inherit' })
  401. child.once('error', (error) => {
  402. reject(new Error(`build-exe-for-python-sdk: ${label} failed to spawn: ${error.message} (${printable})`))
  403. })
  404. child.once('exit', (code, signal) => {
  405. if (code === 0) {
  406. resolvePromise()
  407. return
  408. }
  409. const cause = code === null ? `signal ${signal ?? 'unknown'}` : `exit code ${code}`
  410. reject(new Error(`build-exe-for-python-sdk: ${label} failed (${cause}): ${printable}`))
  411. })
  412. })
  413. }
  414. }
  415. /** Entry point: parse the CLI, then await each pipeline step in order. */
  416. async function main(): Promise<void> {
  417. const cli = BuildCli.parse(process.argv.slice(2))
  418. const pipeline = new SingleExeBuild(cli)
  419. console.log(`build-exe-for-python-sdk: targets: ${cli.targets.map(target => target.spec).join(', ')}`)
  420. console.log(`build-exe-for-python-sdk: staging: ${pipeline.staging}`)
  421. await pipeline.build()
  422. await pipeline.deployStaging()
  423. await pipeline.injectPkgConfig()
  424. const products: string[] = []
  425. for (const target of cli.targets) products.push(await pipeline.pack(target))
  426. pipeline.printProducts(products)
  427. await pipeline.syncToPythonRuntime(products)
  428. }
  429. await main()