#!/usr/bin/env bun import { chmodSync, copyFileSync, cpSync, existsSync, mkdirSync, rmSync, symlinkSync } from "node:fs"; import { spawnSync } from "node:child_process"; import { homedir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); export interface DevOverrideOptions { dryRun: boolean; targetPath?: string; } export function parseDevOverrideArgs(argv: string[]): DevOverrideOptions { return { dryRun: argv.includes("--dry-run") || argv.includes("--dryRun"), targetPath: argv.find((arg) => arg.startsWith("--target-path="))?.slice("--target-path=".length), }; } export function globalBinCandidates(commandName = "hose-use"): string[] { return [ "/opt/homebrew/bin", "/usr/local/bin", join(homedir(), ".local", "bin"), join(homedir(), "bin"), ].map((dir) => join(dir, commandName)); } export function resolveTargetBinaryPath(commandName = "hose-use"): string { try { const whichRes = spawnSync("which", [commandName], { encoding: "utf8" }); if (whichRes.status === 0 && whichRes.stdout) { const path = whichRes.stdout.trim(); if (path && existsSync(path)) return path; } } catch { // Fall back to conventional user-level locations. } for (const candidate of globalBinCandidates(commandName)) { if (existsSync(dirname(candidate))) return candidate; } const defaultDir = join(homedir(), ".local", "bin"); mkdirSync(defaultDir, { recursive: true }); return join(defaultDir, commandName); } function runBuild(): string { const result = spawnSync("node", ["scripts/build/build-binary.mjs"], { cwd: ROOT, stdio: ["ignore", "inherit", "inherit"], }); if (result.error) throw result.error; if (result.status !== 0) throw new Error(`构建开发版二进制失败,退出码: ${result.status ?? 1}`); const localBinary = join(ROOT, "dist", "bin", "hose-use"); if (!existsSync(localBinary)) throw new Error(`未找到构建产物: ${localBinary}`); return localBinary; } function stopRunningService(targetPath: string): boolean { try { const statusRes = spawnSync(targetPath, ["service", "status", "--json"], { encoding: "utf8" }); if (statusRes.status !== 0 || !statusRes.stdout) return false; const status = JSON.parse(statusRes.stdout) as { running?: boolean }; if (!status.running) return false; console.error("==> [dev:override] 停止正在运行的后台服务..."); const stopRes = spawnSync(targetPath, ["service", "stop"], { stdio: "ignore" }); if (stopRes.status !== 0) throw new Error("无法停止后台服务,已中止替换操作"); return true; } catch (error) { if (error instanceof Error && error.message.includes("无法停止")) throw error; return false; } } function installBinary(localBinary: string, targetPath: string): void { const targetDir = dirname(targetPath); mkdirSync(targetDir, { recursive: true }); const temporaryPath = `${targetPath}.tmp.${process.pid}.${Date.now()}`; try { copyFileSync(localBinary, temporaryPath); chmodSync(temporaryPath, 0o755); if (process.platform === "darwin") { spawnSync("/usr/bin/codesign", ["--remove-signature", temporaryPath], { stdio: "ignore" }); spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", temporaryPath], { stdio: "ignore" }); } // copyFileSync follows an existing symlink, so a package-manager shim is not // accidentally replaced by a regular file. copyFileSync(temporaryPath, targetPath); chmodSync(targetPath, 0o755); } finally { rmSync(temporaryPath, { force: true }); } } function syncAgentSkills(): string[] { const synced: string[] = []; for (const name of ["hose-use", "hose-aipro"]) { const source = join(ROOT, "skills", name); const target = join(homedir(), ".agents", "skills", name); if (existsSync(source)) { mkdirSync(dirname(target), { recursive: true }); cpSync(source, target, { recursive: true, force: true }); synced.push(target); } } return synced; } export async function main(argv = process.argv.slice(2)): Promise { const options = parseDevOverrideArgs(argv); const targetPath = options.targetPath || resolveTargetBinaryPath(); console.error("==> [dev:override] 将当前工作区安装为全局开发版 hose-use / hose-aipro"); console.error(` 工作区: ${ROOT}`); console.error(` 目标: ${targetPath}`); if (options.dryRun) { console.error("[DRY-RUN] 将执行: 构建 dist/bin/hose-use、替换全局二进制、同步 ~/.agents/skills/{hose-use,hose-aipro}"); return 0; } const builtBinary = runBuild(); const serviceWasRunning = stopRunningService(targetPath); installBinary(builtBinary, targetPath); const aiproPath = join(dirname(targetPath), "hose-aipro"); if (aiproPath !== targetPath) { rmSync(aiproPath, { force: true }); symlinkSync(targetPath, aiproPath); } try { const skillTargets = syncAgentSkills(); if (skillTargets.length > 0) { console.error(`✓ [dev:override] 已同步 Agent Skills:\n${skillTargets.map((t) => ` ${t}`).join("\n")}`); } } catch (error) { console.error(`⚠️ [dev:override] Agent Skill 同步失败: ${error}`); } if (serviceWasRunning) { console.error("==> [dev:override] 使用新二进制重启后台服务..."); const startRes = spawnSync(targetPath, ["service", "start"], { stdio: "ignore" }); if (startRes.status !== 0) console.error("⚠️ [dev:override] 后台服务重启失败,请手动运行 hose-use service start"); } const versionRes = spawnSync(targetPath, ["version"], { encoding: "utf8" }); if (versionRes.status !== 0) throw new Error(versionRes.stderr || "开发版安装后校验失败"); console.error("✨ [dev:override] 全局开发版安装完成"); process.stdout.write(versionRes.stdout || ""); return 0; } if (import.meta.main) { main().catch((error) => { console.error(`❌ [dev:override] ${error instanceof Error ? error.message : String(error)}`); process.exitCode = 1; }); }