feat(install): 支持 --system 与 --user 模式切换并自动清理残留二进制
- 在 scripts/install.sh 中默认安装至用户目录 ~/.local/bin,并自动清理历史遗留的 /opt/homebrew/bin/seal-use - 在 scripts/dev-override.ts 中优先命中 ~/.local/bin/seal-use,忽略 Homebrew 路径并自动清理残留 - 在 seal-use update 中支持 --system(提权迁移至 /usr/local/bin)与 --user(降权回归至 ~/.local/bin)选项,添加 seal-use migrate 别名 - 迁移与更新时自动清理另一端的非活动实体二进制(恪守 Single Binary Invariant) - 自更新权限预检:当目标位于系统目录且缺少写权限时,友好提示 sudo seal-use update 而非底层报错 - 在 seal-use doctor 中增加执行模式识别与多份二进制(PATH 阴影)检测告警
This commit is contained in:
1 parent
477cc630b4
commit
87bb10f527
12 files changed
+294
-34
No files matched your search
@@ -9,7 +9,7 @@ export const AREA_ALIASES: Readonly<Record<string, string>> = {
|
||||
}
|
||||
|
||||
export const UPDATE_ALIASES = new Set([
|
||||
"update", "upgrade", "up", "self-update", "selfupdate"
|
||||
"update", "upgrade", "up", "self-update", "selfupdate", "migrate"
|
||||
])
|
||||
|
||||
export function normalizeCliArea(area: string): string {
|
||||
|
||||
@@ -2,7 +2,18 @@ import { describe, expect, test } from "bun:test";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { compareSemVer, getMirrorMode, handleUpdateCommand, isNewerVersion, matchAssetForPlatform, pruneUpdateLeftovers } from "./update.js";
|
||||
import {
|
||||
SYSTEM_BINARY_PATH,
|
||||
cleanStaleBinaries,
|
||||
compareSemVer,
|
||||
getMirrorMode,
|
||||
getUserBinaryPath,
|
||||
handleUpdateCommand,
|
||||
isNewerVersion,
|
||||
isPathWritable,
|
||||
matchAssetForPlatform,
|
||||
pruneUpdateLeftovers
|
||||
} from "./update.js";
|
||||
|
||||
type Asset = { name: string; downloadUrl: string; size: number };
|
||||
|
||||
@@ -295,4 +306,51 @@ describe("update installation modes", () => {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects conflicting --system and --user flags", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-conflicting-flags-"));
|
||||
try {
|
||||
await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { system: true, user: true }))
|
||||
.rejects.toMatchObject({ exitCode: 13, message: "Cannot specify both --system and --user." });
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("rejects --system and --user in source development mode", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-source-mode-flags-"));
|
||||
try {
|
||||
await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { system: true }))
|
||||
.rejects.toMatchObject({ exitCode: 13 });
|
||||
await expect(handleUpdateCommand({ appRoot: dir, entryFile: join(dir, "src", "cli.ts") }, { user: true }))
|
||||
.rejects.toMatchObject({ exitCode: 13 });
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("isPathWritable verifies path and parent directory writability", () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "seal-writable-test-"));
|
||||
try {
|
||||
expect(isPathWritable(dir)).toBe(true);
|
||||
expect(isPathWritable(join(dir, "sub", "target"))).toBe(true);
|
||||
const testFile = join(dir, "file");
|
||||
writeFileSync(testFile, "test");
|
||||
expect(isPathWritable(testFile)).toBe(true);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("getUserBinaryPath returns user home directory path", () => {
|
||||
const userPath = getUserBinaryPath();
|
||||
expect(userPath).toContain(".local");
|
||||
expect(userPath).toContain("seal-use");
|
||||
expect(SYSTEM_BINARY_PATH).toBe("/usr/local/bin/seal-use");
|
||||
});
|
||||
|
||||
test("cleanStaleBinaries ignores activePath and returns list of cleaned files", () => {
|
||||
const cleaned = cleanStaleBinaries(SYSTEM_BINARY_PATH);
|
||||
expect(Array.isArray(cleaned)).toBe(true);
|
||||
});
|
||||
});
|
||||
+125
-17
@@ -1,4 +1,5 @@
|
||||
import { chmodSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { accessSync, chmodSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { isCompiledBinary } from "../../core/runtime.js";
|
||||
@@ -15,6 +16,61 @@ const LEGACY_GITHUB_REPO = "yunyingk/seal-home";
|
||||
const GITHUB_REPO_ENV = "SEAL_USE_GITHUB_REPO";
|
||||
const LEGACY_GITHUB_REPO_ENV = "SEAL_HOME_GITHUB_REPO";
|
||||
|
||||
export const SYSTEM_BINARY_PATH = "/usr/local/bin/seal-use";
|
||||
|
||||
export function getUserBinaryPath(): string {
|
||||
return join(homedir(), ".local", "bin", "seal-use");
|
||||
}
|
||||
|
||||
export function isPathWritable(targetPath: string): boolean {
|
||||
try {
|
||||
if (!existsSync(targetPath)) {
|
||||
const parent = dirname(targetPath);
|
||||
return isPathWritable(parent);
|
||||
}
|
||||
accessSync(targetPath, constants.W_OK);
|
||||
const stat = statSync(targetPath);
|
||||
if (!stat.isDirectory()) {
|
||||
accessSync(dirname(targetPath), constants.W_OK);
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanStaleBinaries(activePath: string): string[] {
|
||||
const cleaned: string[] = [];
|
||||
const home = homedir();
|
||||
const userBinary = getUserBinaryPath();
|
||||
const userAlias = join(home, ".local", "bin", "seal-home");
|
||||
const systemBinary = SYSTEM_BINARY_PATH;
|
||||
const systemAlias = "/usr/local/bin/seal-home";
|
||||
const homebrewBinary = "/opt/homebrew/bin/seal-use";
|
||||
const homebrewAlias = "/opt/homebrew/bin/seal-home";
|
||||
|
||||
const candidates = [homebrewBinary, homebrewAlias];
|
||||
if (activePath === systemBinary) {
|
||||
candidates.push(userBinary, userAlias);
|
||||
} else if (activePath === userBinary) {
|
||||
candidates.push(systemBinary, systemAlias);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (candidate === activePath) continue;
|
||||
try {
|
||||
lstatSync(candidate);
|
||||
rmSync(candidate, { force: true });
|
||||
cleaned.push(candidate);
|
||||
console.error(`✓ [update] Cleaned stale/shadowed binary at ${candidate}`);
|
||||
} catch {
|
||||
// ignore if non-existent or permission denied
|
||||
}
|
||||
}
|
||||
|
||||
return cleaned;
|
||||
}
|
||||
|
||||
export type UpdateOptions = {
|
||||
checkOnly?: boolean;
|
||||
changelogOnly?: boolean;
|
||||
@@ -23,9 +79,15 @@ export type UpdateOptions = {
|
||||
targetVersion?: string;
|
||||
repo?: string;
|
||||
bgSave?: boolean;
|
||||
system?: boolean;
|
||||
user?: boolean;
|
||||
};
|
||||
|
||||
export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOptions = {}) {
|
||||
if (options.system && options.user) {
|
||||
throw validationError("Cannot specify both --system and --user.");
|
||||
}
|
||||
|
||||
const repo = options.repo
|
||||
|| process.env[GITHUB_REPO_ENV]?.trim()
|
||||
|| process.env[LEGACY_GITHUB_REPO_ENV]?.trim()
|
||||
@@ -53,7 +115,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (cmp === 0 && !options.force) {
|
||||
if (cmp === 0 && !options.force && !options.system && !options.user) {
|
||||
printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
@@ -87,6 +149,13 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
|
||||
// 2. Source development mode (running via bun/node)
|
||||
if (!isCompiledBinary()) {
|
||||
if (options.system || options.user) {
|
||||
throw validationError(
|
||||
"Source development mode does not install binaries into system or user directories. Use 'bun run dev:override' for local testing.",
|
||||
"bun run dev:override"
|
||||
);
|
||||
}
|
||||
|
||||
if (options.checkOnly) {
|
||||
const releases = await fetchGitHubReleases(repo, 30);
|
||||
const latestRelease = releases[0];
|
||||
@@ -154,11 +223,33 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
const platform = detectPlatform();
|
||||
const arch = detectArch();
|
||||
|
||||
// Every binary-mode invocation sweeps here, not just real updates: the SWR
|
||||
// background check (`update check --bg-save`) is the only command many users
|
||||
// ever run after their last update, so it is what reclaims that update's
|
||||
// `.old.<timestamp>` backup (undeletable while its image was executing).
|
||||
pruneUpdateLeftovers(process.execPath);
|
||||
const execPath = process.execPath;
|
||||
const targetExecPath = options.system
|
||||
? SYSTEM_BINARY_PATH
|
||||
: options.user
|
||||
? getUserBinaryPath()
|
||||
: execPath;
|
||||
const isMigration = targetExecPath !== execPath;
|
||||
|
||||
// Pre-flight permission checks
|
||||
if (options.system && !isPathWritable(targetExecPath)) {
|
||||
throw validationError(
|
||||
`Target location ${targetExecPath} requires elevated (root) privileges to install.`,
|
||||
`sudo seal-use update --system`
|
||||
);
|
||||
}
|
||||
|
||||
if (!options.user && !isPathWritable(targetExecPath)) {
|
||||
throw validationError(
|
||||
`Active binary at ${targetExecPath} requires root privileges to update. Run with sudo, or migrate to user directory using 'seal-use update --user'.`,
|
||||
`sudo seal-use update`
|
||||
);
|
||||
}
|
||||
|
||||
pruneUpdateLeftovers(targetExecPath);
|
||||
if (targetExecPath !== execPath) {
|
||||
pruneUpdateLeftovers(execPath);
|
||||
}
|
||||
|
||||
const { releases, source } = await fetchReleasesWithSource(repo, 30);
|
||||
const release = targetVersion
|
||||
@@ -193,7 +284,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
const latestVersion = release.version;
|
||||
const currentRelease = releases.find((r) => r.version === VERSION);
|
||||
const isUpgrade = isNewerVersion(latestVersion, VERSION);
|
||||
const shouldUpdate = isUpgrade || Boolean(options.force);
|
||||
const shouldUpdate = isUpgrade || Boolean(options.force) || isMigration;
|
||||
const pendingReleases = releases.filter((r) => isNewerVersion(r.version, VERSION));
|
||||
|
||||
if (release?.version) {
|
||||
@@ -209,6 +300,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
}
|
||||
|
||||
if (options.checkOnly) {
|
||||
const installMode = targetExecPath === SYSTEM_BINARY_PATH ? "system" : targetExecPath.includes(".local/bin") ? "user" : "custom";
|
||||
printJson({
|
||||
updated: false,
|
||||
updateAvailable: isUpgrade,
|
||||
@@ -216,6 +308,8 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
installMode,
|
||||
activePath: targetExecPath,
|
||||
behindCount: pendingReleases.length,
|
||||
pendingReleases: pendingReleases.map((r) => ({
|
||||
version: r.version,
|
||||
@@ -233,12 +327,15 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
}
|
||||
|
||||
if (!shouldUpdate) {
|
||||
const cleaned = cleanStaleBinaries(targetExecPath);
|
||||
printJson({
|
||||
updated: false,
|
||||
currentVersion: VERSION,
|
||||
currentVersionPublishedAt: currentRelease?.publishedAt,
|
||||
latestVersion,
|
||||
latestVersionPublishedAt: release.publishedAt,
|
||||
targetPath: targetExecPath,
|
||||
cleanedPaths: cleaned.length ? cleaned : undefined,
|
||||
mode: "binary",
|
||||
message: `seal-use is already up to date (v${VERSION})`
|
||||
});
|
||||
@@ -255,9 +352,9 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
}
|
||||
|
||||
// Download binary or archive
|
||||
const execPath = process.execPath;
|
||||
const execDir = dirname(execPath);
|
||||
const tmpDir = join(execDir, `.tmp-update-${Date.now()}`);
|
||||
const targetDir = dirname(targetExecPath);
|
||||
mkdirSync(targetDir, { recursive: true });
|
||||
const tmpDir = join(targetDir, `.tmp-update-${Date.now()}`);
|
||||
mkdirSync(tmpDir, { recursive: true });
|
||||
|
||||
try {
|
||||
@@ -283,19 +380,22 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
}
|
||||
}
|
||||
|
||||
// Atomic replace
|
||||
// Atomic replace at targetExecPath
|
||||
if (process.platform === "win32") {
|
||||
const oldBinary = `${execPath}.old.${Date.now()}`;
|
||||
const oldBinary = `${targetExecPath}.old.${Date.now()}`;
|
||||
try {
|
||||
renameSync(execPath, oldBinary);
|
||||
renameSync(targetExecPath, oldBinary);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
renameSync(newBinaryPath, execPath);
|
||||
renameSync(newBinaryPath, targetExecPath);
|
||||
} else {
|
||||
renameSync(newBinaryPath, execPath);
|
||||
renameSync(newBinaryPath, targetExecPath);
|
||||
}
|
||||
|
||||
// Single binary invariant: clean stale/shadowed binaries
|
||||
const cleaned = cleanStaleBinaries(targetExecPath);
|
||||
|
||||
// Refresh the Agent Skill from the binary that is now on disk — never from this process.
|
||||
//
|
||||
// `renameSync` above advanced the file at `execPath`, but this process keeps executing the
|
||||
@@ -304,7 +404,7 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
// new one, leaving the agent a full release behind (and `skillSynced: <dir>` reported success
|
||||
// either way). One synchronous child reads the new image's embedded copy; it exits before this
|
||||
// function returns, and nothing is left running.
|
||||
const skillSync = installSkillFromInstalledBinary(execPath, latestVersion);
|
||||
const skillSync = installSkillFromInstalledBinary(targetExecPath, latestVersion);
|
||||
|
||||
saveUpdateCache({
|
||||
latestVersion,
|
||||
@@ -312,10 +412,18 @@ export async function handleUpdateCommand(runtime: CliRuntime, options: UpdateOp
|
||||
releaseUrl: release.htmlUrl
|
||||
});
|
||||
|
||||
if (isMigration) {
|
||||
console.error(`✨ [update] Successfully migrated seal-use to ${targetExecPath}`);
|
||||
}
|
||||
|
||||
printJson({
|
||||
updated: true,
|
||||
fromVersion: VERSION,
|
||||
toVersion: latestVersion,
|
||||
targetPath: targetExecPath,
|
||||
migrated: isMigration,
|
||||
fromPath: isMigration ? execPath : undefined,
|
||||
cleanedPaths: cleaned.length ? cleaned : undefined,
|
||||
skillSynced: skillSync.targetDir ?? false,
|
||||
skillVersion: skillSync.version ?? false,
|
||||
mode: "binary"
|
||||
|
||||
+13
-3
@@ -1416,12 +1416,22 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
commands: [
|
||||
{
|
||||
name: "",
|
||||
summary: "Update seal-use to latest or target version",
|
||||
summary: "Update seal-use to latest or target version, or migrate installation mode",
|
||||
usage: [
|
||||
"seal-use update [--check] [--force] [--version <v>]",
|
||||
"seal-use update [--system|--user] [--check] [--force] [--version <v>]",
|
||||
"seal-use update --system",
|
||||
"seal-use update --user",
|
||||
"seal-use update check",
|
||||
"seal-use update changelog [--limit <n>]",
|
||||
"seal-use changelog [--limit <n>]"
|
||||
"seal-use changelog [--limit <n>]",
|
||||
"seal-use migrate --system|--user"
|
||||
],
|
||||
options: [
|
||||
{ flag: "--system", description: "Migrate and update to system directory (/usr/local/bin, requires root)" },
|
||||
{ flag: "--user", description: "Migrate and update to user directory (~/.local/bin, sudo-free)" },
|
||||
{ flag: "--check", description: "Check whether updates are available without installing" },
|
||||
{ flag: "--force", description: "Force reinstall even if already at latest version" },
|
||||
{ flag: "--version <v>", description: "Target specific release version" }
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
"r", "raw-json", "rawJson", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
"summary", "system", "to-downloads", "toDownloads", "user", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
|
||||
+16
-3
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
import type { CorpConfig } from "../core/config/types.js";
|
||||
import { VERSION_INFO } from "../version.js";
|
||||
import { isUpdateCacheExpired, loadUpdateCache, triggerBackgroundUpdateCheck } from "../core/update-cache.js";
|
||||
import { classifyCliError, usageError } from "../core/errors.js";
|
||||
import { classifyCliError, usageError, validationError } from "../core/errors.js";
|
||||
import {
|
||||
booleanOption,
|
||||
materialPackFilePolicyOptions,
|
||||
@@ -185,10 +185,21 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<vo
|
||||
booleanOption(args.options["bg-save"]) === true ||
|
||||
booleanOption(args.options["silent-save"]) === true;
|
||||
|
||||
const isSystem = booleanOption(args.options.system) === true || lowerAction === "system";
|
||||
const isUser = booleanOption(args.options.user) === true || lowerAction === "user";
|
||||
|
||||
if (isSystem && isUser) {
|
||||
throw validationError("Cannot specify both --system and --user.");
|
||||
}
|
||||
|
||||
if (rawArea === "migrate" && !isSystem && !isUser) {
|
||||
throw usageError("Usage: seal-use migrate --system | --user", "seal-use migrate --user");
|
||||
}
|
||||
|
||||
const targetVersion =
|
||||
stringOption(args.options.version) ??
|
||||
stringOption(args.options.tag) ??
|
||||
(!isChangelog && !isCheck && !isBgSave && action && !action.startsWith("-") ? action : undefined);
|
||||
(!isChangelog && !isCheck && !isBgSave && !isSystem && !isUser && action && !action.startsWith("-") ? action : undefined);
|
||||
|
||||
await (await import("./commands/update.js")).handleUpdateCommand(runtime, {
|
||||
checkOnly: isCheck || isBgSave,
|
||||
@@ -197,7 +208,9 @@ async function dispatchUpdate(args: ParsedArgs, runtime: CliRuntime): Promise<vo
|
||||
force: booleanOption(args.options.force),
|
||||
targetVersion,
|
||||
repo: stringOption(args.options.repo),
|
||||
bgSave: isBgSave
|
||||
bgSave: isBgSave,
|
||||
system: isSystem,
|
||||
user: isUser
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user