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-use"; const LEGACY_GITHUB_REPO = "yunyingk/seal-use"; const UPDATE_URL_ENV = "SEAL_USE_UPDATE_URL"; const LEGACY_UPDATE_URL_ENV = "SEAL_USE_UPDATE_URL"; const GITHUB_REPO_ENV = "SEAL_USE_GITHUB_REPO"; const LEGACY_GITHUB_REPO_ENV = "SEAL_USE_GITHUB_REPO"; export type UpdateOptions = { checkOnly?: boolean; changelogOnly?: boolean; limit?: number; 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 }; const repo = options.repo || process.env[GITHUB_REPO_ENV]?.trim() || process.env[LEGACY_GITHUB_REPO_ENV]?.trim() || DEFAULT_GITHUB_REPO; const rawTarget = options.targetVersion?.trim(); const targetVersion = rawTarget && rawTarget.toLowerCase() !== "latest" ? rawTarget : undefined; // Validate targetVersion: prevent downgrade to older versions if (targetVersion) { const cleanTarget = targetVersion.replace(/^v/, ""); const cmp = compareSemVer(cleanTarget, VERSION); if (cmp < 0) { printJson({ updated: false, currentVersion: VERSION, targetVersion: cleanTarget, mode: isCompiledBinary() ? "binary" : "source", message: `Cannot downgrade seal-use from v${VERSION} to older version v${cleanTarget}. Updates must be forward-only.` }); return; } if (cmp === 0 && !options.force) { printJson({ updated: false, currentVersion: VERSION, targetVersion: cleanTarget, mode: isCompiledBinary() ? "binary" : "source", message: `seal-use is already at version v${VERSION}. Use --force to reinstall.` }); return; } } // 1. Changelog / Release History query if (options.changelogOnly) { const releases = await fetchGitHubReleases(repo, options.limit ?? 10); printJson({ currentVersion: VERSION, totalQueried: releases.length, releases: releases.map((r) => ({ version: r.version, tagName: r.tagName, publishedAt: r.publishedAt, author: r.author, releaseNotes: r.notes, releaseUrl: r.htmlUrl, isCurrent: r.version === VERSION, isNewer: isNewerVersion(r.version, VERSION) })) }); return; } // 2. Source development mode (running via bun/node) if (!isCompiledBinary()) { if (options.checkOnly) { const releases = await fetchGitHubReleases(repo, 30); const latestRelease = releases[0]; const latestVersion = latestRelease?.version ?? VERSION; const currentRelease = releases.find((r) => r.version === VERSION); const isUpgrade = isNewerVersion(latestVersion, VERSION); const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); printJson({ updated: false, updateAvailable: isUpgrade, currentVersion: VERSION, currentVersionPublishedAt: currentRelease?.publishedAt, latestVersion, latestVersionPublishedAt: latestRelease?.publishedAt, behindCount: pendingReleases.length, pendingReleases: pendingReleases.map((r) => ({ version: r.version, tagName: r.tagName, publishedAt: r.publishedAt, author: r.author, releaseNotes: r.notes, releaseUrl: r.htmlUrl })), releaseNotes: latestRelease?.notes ?? "", releaseUrl: latestRelease?.htmlUrl ?? "", mode: "source", message: "Running in source development mode. Run 'seal-use 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; } // 3. Standalone binary mode: check GitHub Releases const platform = detectPlatform(); const arch = detectArch(); const releases = await fetchGitHubReleases(repo, 30); const release = targetVersion ? (releases.find((r) => r.version === targetVersion || r.tagName === targetVersion || r.tagName === `v${targetVersion}`) ?? await fetchGitHubRelease(repo, targetVersion)) : (releases[0] ?? await fetchGitHubRelease(repo)); if (!release) { printJson({ updated: false, currentVersion: VERSION, mode: "binary", message: `Failed to query releases from repository '${repo}'` }); return; } const latestVersion = release.version; const currentRelease = releases.find((r) => r.version === VERSION); const isUpgrade = isNewerVersion(latestVersion, VERSION); const shouldUpdate = isUpgrade || Boolean(options.force); const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION)); if (options.checkOnly) { printJson({ updated: false, updateAvailable: isUpgrade, currentVersion: VERSION, currentVersionPublishedAt: currentRelease?.publishedAt, latestVersion, latestVersionPublishedAt: release.publishedAt, behindCount: pendingReleases.length, pendingReleases: pendingReleases.map((r) => ({ version: r.version, tagName: r.tagName, publishedAt: r.publishedAt, author: r.author, releaseNotes: r.notes, releaseUrl: r.htmlUrl })), releaseNotes: release.notes, releaseUrl: release.htmlUrl, mode: "binary" }); return; } if (!shouldUpdate) { printJson({ updated: false, currentVersion: VERSION, currentVersionPublishedAt: currentRelease?.publishedAt, latestVersion, latestVersionPublishedAt: release.publishedAt, mode: "binary", message: `seal-use 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, release.tagName, asset.name); 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; name?: string; publishedAt?: string; author?: string; notes: string; htmlUrl: string; assets: GitHubAsset[]; }; async function fetchGitHubReleases(repo: string, limit = 20): Promise { const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; const headers: Record = { "User-Agent": `seal-use/${VERSION}`, Accept: "application/vnd.github.v3+json", ...(token ? { Authorization: `Bearer ${token}` } : {}) }; const urls = [ `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`, `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases?per_page=${limit}`, `https://api.github.com/repos/${repo}/releases?per_page=${limit}` ]; if (repo !== LEGACY_GITHUB_REPO) { urls.push(`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases?per_page=${limit}`); } for (const url of urls) { try { const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) }); if (!res.ok) continue; const json = (await res.json()) as Array<{ tag_name?: string; name?: string; body?: string; html_url?: string; published_at?: string; author?: { login?: string }; assets?: Array<{ name: string; browser_download_url: string; size?: number }>; }>; if (!Array.isArray(json) || json.length === 0) continue; const list: GitHubRelease[] = []; for (const item of json) { const tagName = item.tag_name ?? ""; const version = tagName.replace(/^v/, ""); if (!version) continue; const assets: GitHubAsset[] = (item.assets ?? []).map((a) => ({ name: a.name, downloadUrl: a.browser_download_url, size: a.size ?? 0 })); list.push({ version, tagName, name: item.name ?? tagName, publishedAt: item.published_at, author: item.author?.login, notes: item.body ?? "", htmlUrl: item.html_url ?? "", assets }); } if (list.length > 0) return list; } catch { // try next source } } return []; } async function fetchGitHubRelease(repo: string, targetVersion?: string): Promise { const tag = targetVersion ? (targetVersion.startsWith("v") ? targetVersion : `v${targetVersion}`) : undefined; const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN; const headers: Record = { "User-Agent": `seal-use/${VERSION}`, Accept: "application/vnd.github.v3+json", ...(token ? { Authorization: `Bearer ${token}` } : {}) }; const urls = tag ? [ `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`, `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/tags/${tag}`, `https://api.github.com/repos/${repo}/releases/tags/${tag}`, ...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/tags/${tag}`] : []) ] : [ `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`, `https://git.ying-qing.cn/api/v1/repos/gitea/seal-use/releases/latest`, `https://api.github.com/repos/${repo}/releases/latest`, ...(repo !== LEGACY_GITHUB_REPO ? [`https://api.github.com/repos/${LEGACY_GITHUB_REPO}/releases/latest`] : []) ]; let fallbackRelease: GitHubRelease | undefined; for (const url of urls) { try { const res = await fetch(url, { headers, signal: AbortSignal.timeout(5000) }); if (!res.ok) continue; const json = (await res.json()) as { tag_name?: string; name?: string; body?: string; html_url?: string; published_at?: string; author?: { login?: string }; assets?: Array<{ name: string; browser_download_url: string; size?: number }>; }; const tagName = json.tag_name ?? ""; const version = tagName.replace(/^v/, ""); if (!version) continue; const assets: GitHubAsset[] = (json.assets ?? []).map((item) => ({ name: item.name, downloadUrl: item.browser_download_url, size: item.size ?? 0 })); const candidateRelease: GitHubRelease = { version, tagName, name: json.name ?? tagName, publishedAt: json.published_at, author: json.author?.login, notes: json.body ?? "", htmlUrl: json.html_url ?? "", assets }; // If this source already has uploaded assets, return it immediately. if (assets.length > 0) { return candidateRelease; } // Otherwise keep as fallback (in case all sources have no assets) if (!fallbackRelease) { fallbackRelease = candidateRelease; } } catch { // try next source } } return fallbackRelease; } 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]; } function logProgress(msg: string) { try { process.stderr.write(`${msg}\n`); } catch { // ignore } } async function downloadFile(url: string, destPath: string, tagName?: string, assetName?: string) { const candidates: string[] = []; const tag = tagName ? (tagName.startsWith("v") ? tagName : `v${tagName}`) : undefined; const fileName = assetName || url.split("/").pop() || ""; // 1. High-speed Gitea direct mirror first if (tag && fileName) { candidates.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${tag}/${fileName}`); } if (url.startsWith("https://git.ying-qing.cn")) { candidates.push(url); } // 2. Fast GitHub CDN proxies and direct GitHub fallback if (tag && fileName) { const ghDirectUrl = `https://github.com/${DEFAULT_GITHUB_REPO}/releases/download/${tag}/${fileName}`; candidates.push(`https://ghfast.top/${ghDirectUrl}`); candidates.push(`https://gh.ddlc.top/${ghDirectUrl}`); candidates.push(ghDirectUrl); } else if (url.includes("github.com")) { candidates.push(`https://ghfast.top/${url}`); candidates.push(`https://gh.ddlc.top/${url}`); candidates.push(url); } else { candidates.push(url); } // Deduplicate candidates const uniqueCandidates = Array.from(new Set(candidates)); let lastError: Error | undefined; const CONNECT_TIMEOUT_MS = 6000; // 6s connection & headers timeout const WARMUP_WINDOW_MS = 6000; // 6s initial grace window const WARMUP_MIN_BYTES = 300 * 1024; // Must download at least 300 KB within first 6s (otherwise switch) const STALL_TIMEOUT_MS = 10000; // 10s completely stalled (0 bytes received) before giving up const MAX_TOTAL_TIMEOUT_MS = 180000; // 3m max safety limit for (let i = 0; i < uniqueCandidates.length; i++) { const candidate = uniqueCandidates[i]!; const controller = new AbortController(); let abortReason = ""; const abortWith = (reason: string) => { abortReason = reason; try { controller.abort(); } catch { // ignore } }; let connectTimer: ReturnType | undefined = setTimeout(() => { abortWith("Connection timed out (no response headers within 6s)"); }, CONNECT_TIMEOUT_MS); let maxTimer: ReturnType | undefined; let warmupTimer: ReturnType | undefined; try { logProgress(`==> [${i + 1}/${uniqueCandidates.length}] Downloading via: ${candidate}`); const res = await fetch(candidate, { signal: controller.signal }); if (connectTimer) { clearTimeout(connectTimer); connectTimer = undefined; } if (!res.ok) { throw new Error(`HTTP ${res.status} ${res.statusText}`); } maxTimer = setTimeout(() => { abortWith("Overall download time exceeded 3 minutes"); }, MAX_TOTAL_TIMEOUT_MS); const totalBytes = Number(res.headers.get("content-length")) || 0; const reader = res.body?.getReader(); if (!reader) { const buffer = Buffer.from(await res.arrayBuffer()); if (buffer.length < 1000) { throw new Error(`Downloaded content is suspiciously small (${buffer.length} bytes)`); } writeFileSync(destPath, buffer); logProgress(`✓ Download succeeded (${(buffer.length / 1024 / 1024).toFixed(1)} MB)`); return; } const chunks: Uint8Array[] = []; let receivedBytes = 0; let lastReport = 0; // Initial 6-second warmup speed check: must reach 300KB warmupTimer = setTimeout(() => { if (receivedBytes < WARMUP_MIN_BYTES) { const kb = (receivedBytes / 1024).toFixed(1); abortWith(`Initial transfer too slow (${kb} KB < 300 KB in 6s), switching mirror...`); } }, WARMUP_WINDOW_MS); while (true) { // Read next chunk with 10s stall timeout const readPromise = reader.read(); let chunkTimeoutTimer: ReturnType | undefined; const stallPromise = new Promise((_, reject) => { chunkTimeoutTimer = setTimeout(() => { reject(new Error("Data transfer stalled (no chunk received for 10s)")); }, STALL_TIMEOUT_MS); }); let result: { done: boolean; value?: Uint8Array }; try { result = await Promise.race([readPromise, stallPromise]); } finally { if (chunkTimeoutTimer) clearTimeout(chunkTimeoutTimer); } const { done, value } = result; if (done) break; if (value) { chunks.push(value); receivedBytes += value.length; // Clear warmup timer early if we already passed 300KB if (warmupTimer && receivedBytes >= WARMUP_MIN_BYTES) { clearTimeout(warmupTimer); warmupTimer = undefined; } const now = Date.now(); if (now - lastReport > 200) { lastReport = now; const percent = totalBytes ? Math.round((receivedBytes / totalBytes) * 100) : 0; const receivedMb = (receivedBytes / (1024 * 1024)).toFixed(1); const totalMb = totalBytes ? (totalBytes / (1024 * 1024)).toFixed(1) : "?"; try { process.stderr.write(`\r ↳ Progress: ${percent}% (${receivedMb} / ${totalMb} MB)...`); } catch { // ignore } } } } try { process.stderr.write("\n"); } catch { // ignore } const completeBuffer = Buffer.concat(chunks); if (completeBuffer.length < 1000) { throw new Error(`Downloaded content is suspiciously small (${completeBuffer.length} bytes)`); } writeFileSync(destPath, completeBuffer); logProgress(`✓ Download completed successfully (${(completeBuffer.length / 1024 / 1024).toFixed(1)} MB)`); return; } catch (err) { if (connectTimer) clearTimeout(connectTimer); if (warmupTimer) clearTimeout(warmupTimer); if (maxTimer) clearTimeout(maxTimer); const msg = abortReason || (err instanceof Error ? err.message : String(err)); lastError = new Error(msg); logProgress(`\n ↳ Mirror failed: ${lastError.message}`); } finally { if (connectTimer) clearTimeout(connectTimer); if (warmupTimer) clearTimeout(warmupTimer); if (maxTimer) clearTimeout(maxTimer); } } throw new Error(`Failed to download asset from all mirrors: ${lastError?.message}`); } 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-use.exe" : "seal-use"; 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-use.exe" : "seal-use"; 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 compareSemVer(v1: string, v2: string): number { const p1 = v1.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0); const p2 = v2.replace(/^v/, "").split(".").map((n) => Number.parseInt(n, 10) || 0); for (let i = 0; i < Math.max(p1.length, p2.length); i++) { const a = p1[i] ?? 0; const b = p2[i] ?? 0; if (a > b) return 1; if (a < b) return -1; } return 0; } export function isNewerVersion(latest: string, current: string): boolean { return compareSemVer(latest, current) > 0; } 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}`); } }