import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { spawnSync } from "node:child_process"; import { isCompiledBinary } from "../../core/runtime.js"; import { syncGlobalSkillIfPresent } from "../../core/embedded-skill.js"; import { VERSION } from "../../version.js"; import { runServiceCommand, serviceStatus } from "../service.js"; import { printJson } from "../printer.js"; import { STATE_DIR } from "./service.js"; import type { CliRuntime } from "../types.js"; const DEFAULT_GITHUB_REPO = "yunyingk/seal-home"; const UPDATE_URL_ENV = "SEAL_HOME_UPDATE_URL"; const GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO"; export type UpdateOptions = { checkOnly?: boolean; force?: boolean; targetVersion?: string; repo?: string; }; export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) { const serviceConfig = { appRoot: runtime.appRoot, entryFile: runtime.entryFile, stateDir: STATE_DIR, version: VERSION, launcher: runtime.launcher }; // 1. Source development mode (running via bun/node) if (!isCompiledBinary()) { if (options.checkOnly) { printJson({ updated: false, version: VERSION, mode: "source", message: "Running in source development mode. Run 'seal-home update' to git pull & bun install." }); return; } const wasRunning = serviceStatus(serviceConfig).running; if (wasRunning) await runServiceCommand("stop", serviceConfig); try { runCommand("git", ["-C", runtime.appRoot, "pull", "--ff-only"]); } catch (err) { console.error(`git pull skipped: ${err instanceof Error ? err.message : String(err)}`); } runCommand("bun", ["install"], { cwd: runtime.appRoot }); if (wasRunning) await runServiceCommand("start", serviceConfig); printJson({ updated: true, serviceRestarted: wasRunning, version: VERSION, mode: "source" }); return; } // 2. Standalone binary mode: check GitHub Releases const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO; const platform = detectPlatform(); const arch = detectArch(); const release = await fetchGitHubRelease(repo, options.targetVersion); if (!release) { printJson({ updated: false, currentVersion: VERSION, mode: "binary", message: `Failed to query releases from GitHub repository '${repo}'` }); return; } const latestVersion = release.version; const isUpgrade = isNewerVersion(latestVersion, VERSION); const shouldUpdate = options.force || Boolean(options.targetVersion) || isUpgrade; if (options.checkOnly) { printJson({ updated: false, updateAvailable: isUpgrade, currentVersion: VERSION, latestVersion, releaseNotes: release.notes, releaseUrl: release.htmlUrl, mode: "binary" }); return; } if (!shouldUpdate) { printJson({ updated: false, currentVersion: VERSION, latestVersion, mode: "binary", message: `seal-home is already up to date (v${VERSION})` }); return; } // Find matching asset const asset = matchAssetForPlatform(release.assets, platform, arch); if (!asset) { throw new Error( `No compatible binary found for ${platform}-${arch} in release v${latestVersion}. ` + `Available assets: ${release.assets.map((a) => a.name).join(", ")}` ); } // Download binary or archive const wasRunning = serviceStatus(serviceConfig).running; if (wasRunning) await runServiceCommand("stop", serviceConfig); const execPath = process.execPath; const execDir = dirname(execPath); const tmpDir = join(execDir, `.tmp-update-${Date.now()}`); mkdirSync(tmpDir, { recursive: true }); try { const downloadedFile = join(tmpDir, asset.name); await downloadFile(asset.downloadUrl, downloadedFile); let newBinaryPath = downloadedFile; if (asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz")) { newBinaryPath = extractTarGz(downloadedFile, tmpDir, platform); } else if (asset.name.endsWith(".zip")) { newBinaryPath = extractZip(downloadedFile, tmpDir, platform); } chmodSync(newBinaryPath, 0o755); // Re-sign on macOS ad-hoc if codesign exists if (process.platform === "darwin") { try { spawnSync("/usr/bin/codesign", ["--remove-signature", newBinaryPath], { stdio: "ignore" }); spawnSync("/usr/bin/codesign", ["--force", "--sign", "-", newBinaryPath], { stdio: "ignore" }); } catch { // ignore } } // Atomic replace if (process.platform === "win32") { const oldBinary = `${execPath}.old.${Date.now()}`; try { renameSync(execPath, oldBinary); } catch { // ignore } renameSync(newBinaryPath, execPath); } else { renameSync(newBinaryPath, execPath); } if (wasRunning) await runServiceCommand("start", serviceConfig); const skillSync = syncGlobalSkillIfPresent(); printJson({ updated: true, fromVersion: VERSION, toVersion: latestVersion, serviceRestarted: wasRunning, skillSynced: skillSync.synced ? skillSync.targetDir : false, mode: "binary" }); } finally { try { rmSync(tmpDir, { recursive: true, force: true }); } catch { // ignore } } } function detectPlatform(): "darwin" | "linux" | "windows" { if (process.platform === "darwin") return "darwin"; if (process.platform === "win32") return "windows"; return "linux"; } function detectArch(): "arm64" | "x64" { return process.arch === "arm64" ? "arm64" : "x64"; } type GitHubAsset = { name: string; downloadUrl: string; size: number; }; type GitHubRelease = { version: string; tagName: string; notes: string; htmlUrl: string; assets: GitHubAsset[]; }; async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise { const url = targetVersion ? `https://api.github.com/repos/${repo}/releases/tags/${targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`}` : `https://api.github.com/repos/${repo}/releases/latest`; const headers: Record = { "User-Agent": `seal-home/${VERSION}`, Accept: "application/vnd.github.v3+json" }; const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; if (token) { headers.Authorization = `Bearer ${token}`; } try { const res = await fetch(url, { headers }); if (!res.ok) return undefined; const json = (await res.json()) as { tag_name?: string; body?: string; html_url?: string; assets?: Array<{ name: string; browser_download_url: string; size?: number }>; }; const tagName = json.tag_name ?? ""; const version = tagName.replace(/^v/, ""); if (!version) return undefined; const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({ name: item.name, downloadUrl: item.browser_download_url, size: item.size ?? 0 })); return { version, tagName, notes: json.body ?? "", htmlUrl: json.html_url ?? "", assets }; } catch { return undefined; } } function matchAssetForPlatform( assets: GitHubAsset[], platform: "darwin" | "linux" | "windows", arch: "arm64" | "x64" ): GitHubAsset | undefined { const platformKeywords: Record = { darwin: ["darwin", "macos", "osx", "apple"], linux: ["linux"], windows: ["windows", "win32", "win"] }; const archKeywords: Record = { arm64: ["arm64", "aarch64"], x64: ["x64", "x86_64", "amd64"] }; const pKeys = platformKeywords[platform] || []; const aKeys = archKeywords[arch] || []; const matched = assets.filter((asset) => { const lower = asset.name.toLowerCase(); const matchesP = pKeys.some((k) => lower.includes(k)); const matchesA = aKeys.some((k) => lower.includes(k)); return matchesP && matchesA; }); // Prefer direct raw executable over tar.gz / zip if both exist const directBinary = matched.find( (asset) => !asset.name.endsWith(".tar.gz") && !asset.name.endsWith(".tgz") && !asset.name.endsWith(".zip") && !asset.name.endsWith(".sha256") ); if (directBinary) return directBinary; // Fallback to archive const archive = matched.find( (asset) => asset.name.endsWith(".tar.gz") || asset.name.endsWith(".tgz") || asset.name.endsWith(".zip") ); return archive || matched[0]; } async function downloadFile(url: string, destPath: string) { const res = await fetch(url); if (!res.ok) { throw new Error(`Failed to download asset from ${url}: ${res.status} ${res.statusText}`); } const buffer = Buffer.from(await res.arrayBuffer()); writeFileSync(destPath, buffer); } function extractTarGz(archivePath: string, targetDir: string, platform: string): string { const result = spawnSync("tar", ["-xzf", archivePath, "-C", targetDir], { stdio: "pipe" }); if (result.status !== 0) { throw new Error(`Failed to extract tar archive: ${result.stderr.toString()}`); } unlinkSync(archivePath); // Look for executable in targetDir const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home"; const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }) .stdout.trim() .split("\n") .filter(Boolean); const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); if (exact) return exact; return files[0] || archivePath; } function extractZip(archivePath: string, targetDir: string, platform: string): string { const result = spawnSync("unzip", ["-q", "-o", archivePath, "-d", targetDir], { stdio: "pipe" }); if (result.status !== 0) { throw new Error(`Failed to extract zip archive: ${result.stderr.toString()}`); } unlinkSync(archivePath); const expectedName = platform === "windows" ? "seal-home.exe" : "seal-home"; const files = spawnSync("find", [targetDir, "-type", "f"], { encoding: "utf8" }) .stdout.trim() .split("\n") .filter(Boolean); const exact = files.find((f) => f.endsWith(`/${expectedName}`) || f.endsWith(expectedName)); if (exact) return exact; return files[0] || archivePath; } export function isNewerVersion(latest: string, current: string): boolean { const lParts = latest.split(".").map(Number); const cParts = current.split(".").map(Number); for (let i = 0; i < Math.max(lParts.length, cParts.length); i++) { const l = lParts[i] ?? 0; const c = cParts[i] ?? 0; if (l > c) return true; if (l < c) return false; } return false; } function runCommand(command: string, args: string[], options: { cwd?: string } = {}) { const result = spawnSync(command, args, { cwd: options.cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); if (result.stdout) console.error(result.stdout.trimEnd()); if (result.stderr) console.error(result.stderr.trimEnd()); if (result.status !== 0) { throw new Error(`${command} ${args.join(" ")} failed with status ${result.status}`); } }