#!/usr/bin/env bun import { cp, mkdir, rm, chmod, stat, rename } from "node:fs/promises" import { join, resolve, sep } from "node:path" import { $ } from "bun" import { runtimeFiles, validateRuntimeBundle } from "./runtime-bundle" // Build the PaaS standalone directory on the target OS/architecture first. // A host Python installation is never copied into a user's installer. const source = process.env.LAMBDA_AGENT_RUNTIME_DIR if (!source) throw new Error("请设置 LAMBDA_AGENT_RUNTIME_DIR,指向包含 agentpaas 原生可执行文件的发行目录。") const name = process.platform === "win32" ? "agentpaas.exe" : "agentpaas" const binary = join(resolve(source), name) if (!(await stat(binary)).isFile()) throw new Error("运行组件缺少 agentpaas 可执行文件。") const info = await $`${binary} desktop-info`.quiet().json() if (info.desktop_protocol !== 1) throw new Error("运行组件不支持当前 Desktop 配置协议。") if (info.platform !== process.platform || info.arch !== process.arch) throw new Error("运行组件架构与当前构建平台不匹配。") const target = resolve("resources/agentpaas-runtime") if (target === resolve(source) || target.startsWith(resolve(source) + sep) || resolve(source).startsWith(target + sep)) throw new Error("运行组件源目录与目标目录必须分开,不能互相包含。") const staging = `${target}.staging-${crypto.randomUUID()}` const previous = `${target}.previous-${crypto.randomUUID()}` await mkdir(staging, { recursive: true }) try { await cp(resolve(source), staging, { recursive: true, dereference: true }) await chmod(join(staging, name), 0o755) await Bun.write( join(staging, "desktop-runtime.json"), JSON.stringify( { protocol: 1, platform: process.platform, arch: process.arch, files: await runtimeFiles(staging), }, null, 2, ), ) await validateRuntimeBundle(staging) const existed = await stat(target).then( () => true, () => false, ) if (existed) await rename(target, previous) try { await rename(staging, target) } catch (error) { if (existed) await rename(previous, target) throw error } await rm(previous, { recursive: true, force: true }) } finally { await rm(staging, { recursive: true, force: true }) } console.log("Desktop 本地运行组件已准备。")