import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString } from "./string-coerce-Bje8XVt9.js";
import { t as resolveOpenClawPackageRoot } from "./openclaw-root-BizNJX65.js";
import { n as DEFAULT_GATEWAY_PORT, u as resolveGatewayPort } from "./paths-B2cMK-wd.js";
import { t as formatDocsLink } from "./links-BszRQhGa.js";
import { r as theme } from "./theme-B128avno.js";
import { n as inheritOptionFromParent } from "./command-options-DR-PifHH.js";
import "./daemon-cli-CdYwb5GB.js";
import { n as resolveCliName, t as replaceCliName } from "./cli-name-m4Egpgjx.js";
import { t as formatCliCommand } from "./command-format-BORwwHyH.js";
import { u as pathExists } from "./utils-DvkbxKCZ.js";
import { d as resolveGatewayLaunchAgentLabel, m as resolveGatewayWindowsTaskName, p as resolveGatewaySystemdServiceName } from "./paths-D_QOPpsq.js";
import { c as resolveGatewayInstallEntrypoint } from "./daemon-install-plan.shared-5X13ggSi.js";
import { y as createLowDiskSpaceWarning } from "./bundled-runtime-root-CHu5YlIZ.js";
import { n as readPersistedInstalledPluginIndex } from "./installed-plugin-index-store-qF5SAerh.js";
import { r as loadInstalledPluginIndexInstallRecords } from "./manifest-registry-G5tC5D9T.js";
import { n as defaultRuntime } from "./runtime-CIJX7ulQ.js";
import { a as parseSemver, i as nodeVersionSatisfiesEngine } from "./runtime-guard-CQFUyBrZ.js";
import { t as loadPluginManifestRegistryForInstalledIndex } from "./manifest-registry-installed-DvKIF08D.js";
import { r as runCommandWithTimeout } from "./exec-P3GbDwh4.js";
import { I as asResolvedSourceConfig, L as asRuntimeConfig, u as readConfigFileSnapshot } from "./io-CaVVH-CQ.js";
import { a as withPluginInstallRecords, o as withoutPluginInstallRecords } from "./installed-plugin-index-records-Be6251l_.js";
import { r as replaceConfigFile } from "./mutate-C86tBthp.js";
import { n as quoteCmdScriptArg } from "./cmd-argv-CSluFaKs.js";
import { a as shellEscapeRestartLogValue, i as resolveGatewayRestartLogPath, n as renderPosixRestartLogSetup } from "./restart-logs-Bd_HPj3e.js";
import "./config-B9rKdgUB.js";
import { n as readGatewayServiceState, r as resolveGatewayService } from "./service-CG565my8.js";
import { t as runDaemonInstall } from "./install-CBS6l2Ra.js";
import { t as runDaemonRestart } from "./lifecycle-DzO_KPrN.js";
import { n as formatConfigIssueLines } from "./issue-format-DPCYJ_FB.js";
import { l as waitForGatewayHealthyRestart, o as renderRestartDiagnostics, s as terminateStaleGatewayPids } from "./restart-health-Bd4lcE0Z.js";
import { r as formatDurationPrecise } from "./format-duration-CVZxljKj.js";
import { m as trimLogTail } from "./restart-sentinel-C0QvDWy0.js";
import { n as stylePromptMessage } from "./prompt-style-mpRhXk_G.js";
import { t as formatHelpExamples } from "./help-format-CmO6sKiH.js";
import { r as commitPluginInstallRecordsWithConfig } from "./plugins-install-record-commit-CXYgEjOp.js";
import { t as refreshPluginRegistryAfterConfigMutation } from "./plugins-registry-refresh-DJkQVAL1.js";
import { i as installCompletion, n as COMPLETION_SKIP_PLUGIN_COMMANDS_ENV } from "./completion-runtime-CAaolkxV.js";
import { n as renderTable, t as getTerminalTableWidth } from "./table-DFb21H0d.js";
import { n as updateNpmInstalledPlugins, t as syncPluginsForUpdateChannel } from "./update-DE8gif0h.js";
import { t as doctorCommand } from "./doctor-CMbM4B5j.js";
import { t as selectStyled } from "./prompt-select-styled-uwvY60XK.js";
import { d as formatUpdateChannelLabel, g as resolveUpdateChannelDisplay, h as resolveEffectiveUpdateChannel, i as fetchNpmTagVersion, m as normalizeUpdateChannel, n as compareSemverStrings, o as resolveNpmChannelTag, r as fetchNpmPackageTargetStatus, t as checkUpdateStatus, u as channelToNpmTag } from "./update-check-D9xxuEFS.js";
import { i as resolveUpdateAvailability, n as formatUpdateOneLiner, t as formatUpdateAvailableHint } from "./status.update-BNwg33L0.js";
import { a as cleanupGlobalRenameDirs, c as detectGlobalInstallManagerForRoot, d as resolveGlobalInstallTarget, f as normalizePackageTagInput, i as canResolveRegistryVersionForPackageTarget, l as globalInstallArgs, m as readPackageVersion, n as runGatewayUpdate, o as createGlobalInstallEnv, p as readPackageName, r as runGlobalPackageUpdateSteps, s as detectGlobalInstallManagerByPresence, u as resolveGlobalInstallSpec } from "./update-runner-DEAcymck.js";
import { r as ensureCompletionCacheExists, t as checkShellCompletionStatus } from "./doctor-completion-DrQYker9.js";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
import { spawn, spawnSync } from "node:child_process";
import { confirm, isCancel, spinner } from "@clack/prompts";
//#region src/cli/update-cli/shared.ts
const INVALID_TIMEOUT_ERROR = "--timeout must be a positive integer (seconds)";
function parseTimeoutMsOrExit(timeout) {
	const timeoutMs = timeout ? Number.parseInt(timeout, 10) * 1e3 : void 0;
	if (timeoutMs !== void 0 && (Number.isNaN(timeoutMs) || timeoutMs <= 0)) {
		defaultRuntime.error(INVALID_TIMEOUT_ERROR);
		defaultRuntime.exit(1);
		return null;
	}
	return timeoutMs;
}
const OPENCLAW_REPO_URL = "https://github.com/openclaw/openclaw.git";
const MAX_LOG_CHARS = 8e3;
const DEFAULT_PACKAGE_NAME = "openclaw";
const CORE_PACKAGE_NAMES = new Set([DEFAULT_PACKAGE_NAME]);
function normalizeTag(value) {
	return normalizePackageTagInput(value, ["openclaw", DEFAULT_PACKAGE_NAME]);
}
function normalizeVersionTag(tag) {
	const trimmed = tag.trim();
	if (!trimmed) return null;
	const cleaned = trimmed.startsWith("v") ? trimmed.slice(1) : trimmed;
	return parseSemver(cleaned) ? cleaned : null;
}
async function resolveTargetVersion(tag, timeoutMs) {
	if (!canResolveRegistryVersionForPackageTarget(tag)) return null;
	const direct = normalizeVersionTag(tag);
	if (direct) return direct;
	return (await fetchNpmTagVersion({
		tag,
		timeoutMs
	})).version ?? null;
}
async function isGitCheckout(root) {
	try {
		await fs.stat(path.join(root, ".git"));
		return true;
	} catch {
		return false;
	}
}
async function isCorePackage(root) {
	const name = await readPackageName(root);
	return Boolean(name && CORE_PACKAGE_NAMES.has(name));
}
async function isEmptyDir(targetPath) {
	try {
		return (await fs.readdir(targetPath)).length === 0;
	} catch {
		return false;
	}
}
function resolveGitInstallDir() {
	const override = process.env.OPENCLAW_GIT_DIR?.trim();
	if (override) return path.resolve(override);
	return resolveDefaultGitDir();
}
function resolveDefaultGitDir() {
	const home = os.homedir();
	if (home.startsWith("/")) return path.posix.join(home, "openclaw");
	return path.join(home, "openclaw");
}
function resolveNodeRunner() {
	const base = normalizeLowercaseStringOrEmpty(path.basename(process.execPath));
	if (base === "node" || base === "node.exe") return process.execPath;
	return "node";
}
async function resolveUpdateRoot() {
	return await resolveOpenClawPackageRoot({
		moduleUrl: import.meta.url,
		argv1: process.argv[1],
		cwd: process.cwd()
	}) ?? process.cwd();
}
async function runUpdateStep(params) {
	const command = params.argv.join(" ");
	params.progress?.onStepStart?.({
		name: params.name,
		command,
		index: 0,
		total: 0
	});
	const started = Date.now();
	const res = await runCommandWithTimeout(params.argv, {
		cwd: params.cwd,
		env: params.env,
		timeoutMs: params.timeoutMs
	});
	const durationMs = Date.now() - started;
	const stderrTail = trimLogTail(res.stderr, MAX_LOG_CHARS);
	params.progress?.onStepComplete?.({
		name: params.name,
		command,
		index: 0,
		total: 0,
		durationMs,
		exitCode: res.code,
		stderrTail
	});
	return {
		name: params.name,
		command,
		cwd: params.cwd ?? process.cwd(),
		durationMs,
		exitCode: res.code,
		stdoutTail: trimLogTail(res.stdout, MAX_LOG_CHARS),
		stderrTail
	};
}
async function ensureGitCheckout(params) {
	const gitEnv = params.env ?? await createGlobalInstallEnv();
	if (!await pathExists(params.dir)) return await runUpdateStep({
		name: "git clone",
		argv: [
			"git",
			"clone",
			OPENCLAW_REPO_URL,
			params.dir
		],
		env: gitEnv,
		timeoutMs: params.timeoutMs,
		progress: params.progress
	});
	if (!await isGitCheckout(params.dir)) {
		if (!await isEmptyDir(params.dir)) throw new Error(`OPENCLAW_GIT_DIR points at a non-git directory: ${params.dir}. Set OPENCLAW_GIT_DIR to an empty folder or an openclaw checkout.`);
		return await runUpdateStep({
			name: "git clone",
			argv: [
				"git",
				"clone",
				OPENCLAW_REPO_URL,
				params.dir
			],
			cwd: params.dir,
			env: gitEnv,
			timeoutMs: params.timeoutMs,
			progress: params.progress
		});
	}
	if (!await isCorePackage(params.dir)) throw new Error(`OPENCLAW_GIT_DIR does not look like a core checkout: ${params.dir}.`);
	return null;
}
async function resolveGlobalManager(params) {
	const runCommand = createGlobalCommandRunner();
	if (params.installKind === "package") {
		const detected = await detectGlobalInstallManagerForRoot(runCommand, params.root, params.timeoutMs);
		if (detected) return detected;
	}
	return await detectGlobalInstallManagerByPresence(runCommand, params.timeoutMs) ?? "npm";
}
const COMPLETION_CACHE_WRITE_TIMEOUT_MS = 3e4;
const COMPLETION_CACHE_MANUAL_REFRESH_HINT = "Shell tab-completion may be stale; refresh manually with: openclaw completion --write-state";
async function tryWriteCompletionCache(root, jsonMode) {
	const binPath = path.join(root, "openclaw.mjs");
	if (!await pathExists(binPath)) return;
	const result = spawnSync(resolveNodeRunner(), [
		binPath,
		"completion",
		"--write-state"
	], {
		cwd: root,
		env: {
			...process.env,
			[COMPLETION_SKIP_PLUGIN_COMMANDS_ENV]: "1"
		},
		encoding: "utf-8",
		timeout: COMPLETION_CACHE_WRITE_TIMEOUT_MS
	});
	if (result.error) {
		if (!jsonMode) {
			const reason = result.error.code === "ETIMEDOUT" ? `timed out after ${COMPLETION_CACHE_WRITE_TIMEOUT_MS / 1e3}s` : String(result.error);
			defaultRuntime.log(theme.warn(`Completion cache update failed: ${reason}. ${COMPLETION_CACHE_MANUAL_REFRESH_HINT}`));
		}
		return;
	}
	if (result.status !== 0 && !jsonMode) {
		const stderr = (result.stderr ?? "").trim();
		const detail = stderr ? ` (${stderr})` : "";
		defaultRuntime.log(theme.warn(`Completion cache update failed${detail}. ${COMPLETION_CACHE_MANUAL_REFRESH_HINT}`));
	}
}
function createGlobalCommandRunner() {
	return async (argv, options) => {
		const res = await runCommandWithTimeout(argv, options);
		return {
			stdout: res.stdout,
			stderr: res.stderr,
			code: res.code
		};
	};
}
//#endregion
//#region src/cli/update-cli/status.ts
function formatGitStatusLine(params) {
	const shortSha = params.sha ? params.sha.slice(0, 8) : null;
	const branch = params.branch && params.branch !== "HEAD" ? params.branch : null;
	const tag = params.tag;
	return [
		branch ?? (tag ? "detached" : "git"),
		tag ? `tag ${tag}` : null,
		shortSha ? `@ ${shortSha}` : null
	].filter(Boolean).join(" · ");
}
async function updateStatusCommand(opts) {
	const timeoutMs = parseTimeoutMsOrExit(opts.timeout);
	if (timeoutMs === null) return;
	const root = await resolveUpdateRoot();
	const configSnapshot = await readConfigFileSnapshot();
	const configChannel = configSnapshot.valid ? normalizeUpdateChannel(configSnapshot.config.update?.channel) : null;
	const update = await checkUpdateStatus({
		root,
		timeoutMs: timeoutMs ?? 3500,
		fetchGit: true,
		includeRegistry: true
	});
	const channelInfo = resolveUpdateChannelDisplay({
		configChannel,
		installKind: update.installKind,
		gitTag: update.git?.tag ?? null,
		gitBranch: update.git?.branch ?? null
	});
	const channelLabel = channelInfo.label;
	const gitLabel = update.installKind === "git" ? formatGitStatusLine({
		branch: update.git?.branch ?? null,
		tag: update.git?.tag ?? null,
		sha: update.git?.sha ?? null
	}) : null;
	const updateAvailability = resolveUpdateAvailability(update);
	const updateLine = formatUpdateOneLiner(update).replace(/^Update:\s*/i, "");
	if (opts.json) {
		defaultRuntime.writeJson({
			update,
			channel: {
				value: channelInfo.channel,
				source: channelInfo.source,
				label: channelLabel,
				config: configChannel
			},
			availability: updateAvailability
		});
		return;
	}
	const tableWidth = getTerminalTableWidth();
	const rows = [
		{
			Item: "Install",
			Value: update.installKind === "git" ? `git (${update.root ?? "unknown"})` : update.installKind === "package" ? update.packageManager : "unknown"
		},
		{
			Item: "Channel",
			Value: channelLabel
		},
		...gitLabel ? [{
			Item: "Git",
			Value: gitLabel
		}] : [],
		{
			Item: "Update",
			Value: updateAvailability.available ? theme.warn(`available · ${updateLine}`) : updateLine
		}
	];
	defaultRuntime.log(theme.heading("OpenClaw update status"));
	defaultRuntime.log("");
	defaultRuntime.log(renderTable({
		width: tableWidth,
		columns: [{
			key: "Item",
			header: "Item",
			minWidth: 10
		}, {
			key: "Value",
			header: "Value",
			flex: true,
			minWidth: 24
		}],
		rows
	}).trimEnd());
	defaultRuntime.log("");
	const updateHint = formatUpdateAvailableHint(update);
	if (updateHint) defaultRuntime.log(theme.warn(updateHint));
}
//#endregion
//#region src/cli/plugins-location-bridges.ts
function buildBridgeFromPersistedBundledRecord(record, manifest) {
	if (record.origin !== "bundled" || !record.enabled) return null;
	const npmSpec = record.packageInstall?.npm?.spec;
	if (!npmSpec) return null;
	return {
		bundledPluginId: record.pluginId,
		pluginId: record.pluginId,
		npmSpec,
		...record.enabledByDefault ? { enabledByDefault: true } : {},
		...manifest?.channels.length ? { channelIds: manifest.channels } : {}
	};
}
async function listPersistedBundledPluginLocationBridges(options) {
	const index = await readPersistedInstalledPluginIndex(options);
	if (!index) return [];
	const manifestRegistry = loadPluginManifestRegistryForInstalledIndex({
		index,
		workspaceDir: options.workspaceDir,
		env: options.env,
		includeDisabled: true
	});
	const manifestByPluginId = new Map(manifestRegistry.plugins.map((plugin) => [plugin.id, plugin]));
	return index.plugins.flatMap((record) => {
		const bridge = buildBridgeFromPersistedBundledRecord(record, manifestByPluginId.get(record.pluginId));
		return bridge ? [bridge] : [];
	});
}
//#endregion
//#region src/cli/update-cli/progress.ts
const STEP_LABELS = {
	"clean check": "Working directory is clean",
	"upstream check": "Upstream branch exists",
	"git fetch": "Fetching latest changes",
	"git rebase": "Rebasing onto target commit",
	"git rev-parse @{upstream}": "Resolving upstream commit",
	"git rev-list": "Enumerating candidate commits",
	"git clone": "Cloning git checkout",
	"preflight worktree": "Preparing preflight worktree",
	"preflight cleanup": "Cleaning preflight worktree",
	"deps install": "Installing dependencies",
	build: "Building",
	"ui:build": "Building UI assets",
	"ui:build (post-doctor repair)": "Restoring missing UI assets",
	"ui assets verify": "Validating UI assets",
	"openclaw doctor entry": "Checking doctor entrypoint",
	"openclaw doctor": "Running doctor checks",
	"git rev-parse HEAD (after)": "Verifying update",
	"global update": "Updating via package manager",
	"global update (omit optional)": "Retrying update without optional deps",
	"global install stage": "Preparing staged package install",
	"global install verify": "Verifying global package",
	"global install swap": "Activating global package",
	"global install": "Installing global package"
};
function getStepLabel(step) {
	return STEP_LABELS[step.name] ?? step.name;
}
function inferUpdateFailureHints(result) {
	if (result.status !== "error") return [];
	if (result.reason === "pnpm-corepack-missing") return ["This pnpm checkout could not auto-enable pnpm because corepack is missing.", "Install pnpm manually or install Node with corepack available, then rerun the update command."];
	if (result.reason === "pnpm-corepack-enable-failed") return ["This pnpm checkout could not auto-enable pnpm via corepack.", "Run `corepack enable` manually or install pnpm manually, then rerun the update command."];
	if (result.reason === "pnpm-npm-bootstrap-failed") return ["This pnpm checkout could not bootstrap pnpm from npm automatically.", "Install pnpm manually, then rerun the update command."];
	if (result.reason === "preferred-manager-unavailable") return ["This checkout requires its declared package manager and the updater could not find it.", "Install the missing package manager manually, then rerun the update command."];
	if (result.mode !== "npm") return [];
	const failedStep = [...result.steps].toReversed().find((step) => step.exitCode !== 0);
	if (!failedStep) return [];
	const stderr = normalizeLowercaseStringOrEmpty(failedStep.stderrTail);
	const hints = [];
	if ((failedStep.name.startsWith("global update") || failedStep.name.startsWith("global install")) && stderr.includes("eacces")) {
		hints.push("Detected permission failure (EACCES). Re-run with a writable global prefix or sudo (for system-managed Node installs).");
		hints.push("Example: npm config set prefix ~/.local && npm i -g openclaw@latest");
	}
	if (failedStep.name.startsWith("global update") && (stderr.includes("node-gyp") || stderr.includes("prebuild"))) {
		hints.push("Detected native optional dependency build failure. The updater retries with --omit=optional automatically.");
		hints.push("If it still fails: npm i -g openclaw@latest --omit=optional");
	}
	return hints;
}
function createUpdateProgress(enabled) {
	if (!enabled) return {
		progress: {},
		stop: () => {}
	};
	let currentSpinner = null;
	return {
		progress: {
			onStepStart: (step) => {
				currentSpinner = spinner();
				currentSpinner.start(theme.accent(getStepLabel(step)));
			},
			onStepComplete: (step) => {
				if (!currentSpinner) return;
				const label = getStepLabel(step);
				const duration = theme.muted(`(${formatDurationPrecise(step.durationMs)})`);
				const icon = step.exitCode === 0 ? theme.success("✓") : theme.error("✗");
				currentSpinner.stop(`${icon} ${label} ${duration}`);
				currentSpinner = null;
				if (step.exitCode !== 0 && step.stderrTail) {
					const lines = step.stderrTail.split("\n").slice(-10);
					for (const line of lines) if (line.trim()) defaultRuntime.log(`    ${theme.error(line)}`);
				}
			}
		},
		stop: () => {
			if (currentSpinner) {
				currentSpinner.stop();
				currentSpinner = null;
			}
		}
	};
}
function formatStepStatus(exitCode) {
	if (exitCode === 0) return theme.success("✓");
	if (exitCode === null) return theme.warn("?");
	return theme.error("✗");
}
function printResult(result, opts) {
	if (opts.json) {
		defaultRuntime.writeJson(result);
		return;
	}
	const statusColor = result.status === "ok" ? theme.success : result.status === "skipped" ? theme.warn : theme.error;
	defaultRuntime.log("");
	defaultRuntime.log(`${theme.heading("Update Result:")} ${statusColor(result.status.toUpperCase())}`);
	if (result.root) defaultRuntime.log(`  Root: ${theme.muted(result.root)}`);
	if (result.reason) defaultRuntime.log(`  Reason: ${theme.muted(result.reason)}`);
	if (result.before?.version || result.before?.sha) {
		const before = result.before.version ?? result.before.sha?.slice(0, 8) ?? "";
		defaultRuntime.log(`  Before: ${theme.muted(before)}`);
	}
	if (result.after?.version || result.after?.sha) {
		const after = result.after.version ?? result.after.sha?.slice(0, 8) ?? "";
		defaultRuntime.log(`  After: ${theme.muted(after)}`);
	}
	if (!opts.hideSteps && result.steps.length > 0) {
		defaultRuntime.log("");
		defaultRuntime.log(theme.heading("Steps:"));
		for (const step of result.steps) {
			const status = formatStepStatus(step.exitCode);
			const duration = theme.muted(`(${formatDurationPrecise(step.durationMs)})`);
			defaultRuntime.log(`  ${status} ${step.name} ${duration}`);
			if (step.exitCode !== 0 && step.stderrTail) {
				const lines = step.stderrTail.split("\n").slice(0, 5);
				for (const line of lines) if (line.trim()) defaultRuntime.log(`      ${theme.error(line)}`);
			}
		}
	}
	const hints = inferUpdateFailureHints(result);
	if (hints.length > 0) {
		defaultRuntime.log("");
		defaultRuntime.log(theme.heading("Recovery hints:"));
		for (const hint of hints) defaultRuntime.log(`  - ${theme.warn(hint)}`);
	}
	defaultRuntime.log("");
	defaultRuntime.log(`Total time: ${theme.muted(formatDurationPrecise(result.durationMs))}`);
}
//#endregion
//#region src/cli/update-cli/restart-helper.ts
/**
* Shell-escape a string for embedding in single-quoted shell arguments.
* Replaces every `'` with `'\''` (end quote, escaped quote, resume quote).
* For batch scripts, validates against special characters instead.
*/
function shellEscape(value) {
	return value.replace(/'/g, "'\\''");
}
/** Validates a task name is safe for embedding in Windows restart scripts. */
function isWindowsTaskNameSafe(value) {
	return /^[A-Za-z0-9 _\-().]+$/.test(value);
}
function powerShellSingleQuote(value) {
	return `'${value.replace(/'/g, "''")}'`;
}
function resolveSystemdUnit(env) {
	const override = normalizeOptionalString(env.OPENCLAW_SYSTEMD_UNIT);
	if (override) return override.endsWith(".service") ? override : `${override}.service`;
	return `${resolveGatewaySystemdServiceName(env.OPENCLAW_PROFILE)}.service`;
}
function resolveLaunchdLabel(env) {
	const override = normalizeOptionalString(env.OPENCLAW_LAUNCHD_LABEL);
	if (override) return override;
	return resolveGatewayLaunchAgentLabel(env.OPENCLAW_PROFILE);
}
function resolveWindowsTaskName(env) {
	const override = env.OPENCLAW_WINDOWS_TASK_NAME?.trim();
	if (override) return override;
	return resolveGatewayWindowsTaskName(env.OPENCLAW_PROFILE);
}
/**
* Prepares a standalone script to restart the gateway service.
* This script is written to a temporary directory and does not depend on
* the installed package files, ensuring restart capability even if the
* update process temporarily removes or corrupts installation files.
*/
async function prepareRestartScript(env = process.env, gatewayPort = DEFAULT_GATEWAY_PORT) {
	const tmpDir = os.tmpdir();
	const timestamp = Date.now();
	const platform = process.platform;
	let scriptContent = "";
	let filename = "";
	try {
		if (platform === "linux") {
			const escaped = shellEscape(resolveSystemdUnit(env));
			const logSetup = renderPosixRestartLogSetup({
				...process.env,
				...env
			});
			filename = `openclaw-restart-${timestamp}.sh`;
			scriptContent = `#!/bin/sh
# Standalone restart script — survives parent process termination.
# Wait briefly to ensure file locks are released after update.
sleep 1
${logSetup}
printf '[%s] openclaw restart attempt source=update target=%s\\n' "$(date -u +%FT%TZ)" '${escaped}' >&2
if systemctl --user restart '${escaped}'; then
  status=0
  printf '[%s] openclaw restart done source=update\\n' "$(date -u +%FT%TZ)" >&2
else
  status=$?
  printf '[%s] openclaw restart failed source=update status=%s\\n' "$(date -u +%FT%TZ)" "$status" >&2
fi
# Self-cleanup
rm -f "$0"
exit "$status"
`;
		} else if (platform === "darwin") {
			const label = resolveLaunchdLabel(env);
			const escaped = shellEscape(label);
			const uid = process.getuid ? process.getuid() : 501;
			const home = normalizeOptionalString(env.HOME) || process.env.HOME || os.homedir();
			const escapedPlistPath = shellEscape(path.join(home, "Library", "LaunchAgents", `${label}.plist`));
			const logSetup = renderPosixRestartLogSetup({
				...process.env,
				...env
			});
			filename = `openclaw-restart-${timestamp}.sh`;
			scriptContent = `#!/bin/sh
# Standalone restart script — survives parent process termination.
# Wait briefly to ensure file locks are released after update.
sleep 1
# Capture launchctl output so bootstrap/kickstart failures leave a durable
# audit trail. Log setup is best-effort: restart must still run if the log path
# is temporarily unavailable.
${logSetup}
printf '[%s] openclaw restart attempt source=update target=%s\\n' "$(date -u +%FT%TZ)" '${shellEscapeRestartLogValue(label)}' >&2
# Try kickstart first (works when the service is still registered).
# If it fails (e.g. after bootout), clear any persisted disabled state,
# then re-register via bootstrap and kickstart. The final status is captured
# before self-cleanup so a genuine failure remains observable.
status=0
if ! launchctl kickstart -k 'gui/${uid}/${escaped}'; then
  launchctl enable 'gui/${uid}/${escaped}'
  launchctl bootstrap 'gui/${uid}' '${escapedPlistPath}'
  launchctl kickstart -k 'gui/${uid}/${escaped}'
  status=$?
fi
if [ "$status" -eq 0 ]; then
  printf '[%s] openclaw restart done source=update\\n' "$(date -u +%FT%TZ)" >&2
else
  printf '[%s] openclaw restart failed source=update status=%s\\n' "$(date -u +%FT%TZ)" "$status" >&2
fi
# Self-cleanup (log is retained under the OpenClaw state logs directory).
rm -f "$0"
exit "$status"
`;
		} else if (platform === "win32") {
			const taskName = resolveWindowsTaskName(env);
			if (!isWindowsTaskNameSafe(taskName)) return null;
			const port = Number.isFinite(gatewayPort) && gatewayPort > 0 ? gatewayPort : DEFAULT_GATEWAY_PORT;
			const quotedLogPath = powerShellSingleQuote(resolveGatewayRestartLogPath({
				...process.env,
				...env
			}));
			const quotedTaskName = powerShellSingleQuote(taskName);
			filename = `openclaw-restart-${timestamp}.cmd`;
			scriptContent = `@echo off
REM Standalone restart script - survives parent process termination.
REM Keep this as a cmd wrapper so Group Policy script execution policies
REM cannot block the update restart handoff before schtasks.exe runs.
setlocal
set "OPENCLAW_RESTART_SCRIPT=%~f0"
powershell -NoProfile -ExecutionPolicy Bypass -Command "$p=$env:OPENCLAW_RESTART_SCRIPT; $s=Get-Content -Raw -LiteralPath $p; $m='# POWERSHELL'; $i=$s.IndexOf($m); if ($i -lt 0) { exit 1 }; Invoke-Expression $s.Substring($i)"
set "status=%ERRORLEVEL%"
del "%~f0" >nul 2>&1
exit /b %status%
# POWERSHELL
# Wait briefly to ensure file locks are released after update.
$ErrorActionPreference = "Continue"
Start-Sleep -Seconds 2

$logPath = ${quotedLogPath}
try {
  $logDir = Split-Path -Parent $logPath
  New-Item -ItemType Directory -Path $logDir -Force | Out-Null
  Add-Content -LiteralPath $logPath -Value "[$(Get-Date -Format o)] openclaw restart log initialized"
} catch {
  # Restart should still run if log setup is unavailable.
}

function Write-RestartLog {
  param([string]$Message)
  try {
    Add-Content -LiteralPath $logPath -Value "[$(Get-Date -Format o)] $Message"
  } catch {
  }
}

function Join-OpenClawProcessArguments {
  param([string[]]$Arguments)
  ($Arguments | ForEach-Object {
    if ($_ -match "\\s") {
      '"' + $_ + '"'
    } else {
      $_
    }
  }) -join " "
}

function Invoke-OpenClawSchtasksWithTimeout {
  param(
    [string[]]$Arguments,
    [int]$TimeoutSeconds
  )
  $process = $null
  try {
    $startInfo = [System.Diagnostics.ProcessStartInfo]::new()
    $startInfo.FileName = "schtasks.exe"
    $startInfo.Arguments = Join-OpenClawProcessArguments -Arguments $Arguments
    $startInfo.UseShellExecute = $false
    $startInfo.RedirectStandardOutput = $true
    $startInfo.RedirectStandardError = $true
    $process = [System.Diagnostics.Process]::Start($startInfo)
    if (-not $process.WaitForExit($TimeoutSeconds * 1000)) {
      try {
        $process.Kill()
      } catch {
      }
      Write-RestartLog "openclaw restart schtasks timeout source=update args=$($Arguments -join ' ')"
      return 124
    }
    $stdout = $process.StandardOutput.ReadToEnd()
    $stderr = $process.StandardError.ReadToEnd()
    if ($stdout) {
      Write-RestartLog $stdout.Trim()
    }
    if ($stderr) {
      Write-RestartLog $stderr.Trim()
    }
    return $process.ExitCode
  } catch {
    Write-RestartLog "openclaw restart schtasks failed source=update args=$($Arguments -join ' ') error=$($_.Exception.Message)"
    return 1
  }
}

function Get-OpenClawScheduledTaskState {
  param([string]$TaskName)
  try {
    $task = Get-ScheduledTask -TaskName $TaskName -ErrorAction Stop
    if ($task -and $task.State) {
      return [string]$task.State
    }
  } catch {
  }

  try {
    $queryOutput = & schtasks.exe /Query /TN $TaskName /FO LIST 2>$null
    foreach ($line in $queryOutput) {
      if ($line -match "^\\s*Status:\\s*(.+?)\\s*$") {
        return $Matches[1]
      }
    }
  } catch {
  }

  return "Unknown"
}

function Get-OpenClawListenerPids {
  param([int]$Port)
  $listenerPids = @()

  try {
    if (Get-Command Get-NetTCPConnection -ErrorAction SilentlyContinue) {
      $listenerPids += Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue |
        ForEach-Object { [int]$_.OwningProcess }
    }
  } catch {
  }

  if ($listenerPids.Count -eq 0) {
    try {
      $portPattern = [regex]::Escape(":$Port")
      $linePattern = "^\\s*TCP\\s+\\S+$portPattern\\s+\\S+\\s+LISTENING\\s+(\\d+)\\s*$"
      & netstat.exe -ano -p tcp 2>$null | ForEach-Object {
        if ($_ -match $linePattern) {
          $listenerPids += [int]$Matches[1]
        }
      }
    } catch {
    }
  }

  $listenerPids | Sort-Object -Unique
}

function Invoke-OpenClawStartupLauncher {
  $launcherPath = Join-Path $env:USERPROFILE ".openclaw\\gateway.cmd"
  if (-not (Test-Path -LiteralPath $launcherPath)) {
    Write-RestartLog "openclaw restart startup launcher missing source=update path=$launcherPath"
    return 1
  }

  try {
    Start-Process -FilePath $launcherPath -WindowStyle Hidden | Out-Null
    Write-RestartLog "openclaw restart launched startup fallback source=update path=$launcherPath"
    return 0
  } catch {
    Write-RestartLog "openclaw restart startup fallback failed source=update error=$($_.Exception.Message)"
    return 1
  }
}

$taskName = ${quotedTaskName}
$port = ${port}
Write-RestartLog "openclaw restart attempt source=update target=$taskName"

$taskState = Get-OpenClawScheduledTaskState -TaskName $taskName
if ($taskState -eq "Running") {
  $endStatus = Invoke-OpenClawSchtasksWithTimeout -Arguments @("/End", "/TN", $taskName) -TimeoutSeconds 10
  if ($endStatus -ne 0) {
    Write-RestartLog "openclaw restart schtasks end did not complete cleanly source=update status=$endStatus"
  }
} else {
  Write-RestartLog "openclaw restart skipped schtasks end source=update state=$taskState"
}

for ($attempt = 1; $attempt -le 10; $attempt++) {
  $listeners = @(Get-OpenClawListenerPids -Port $port)
  if ($listeners.Count -eq 0) {
    break
  }

  if ($attempt -eq 10) {
    foreach ($listenerPid in $listeners) {
      try {
        Stop-Process -Id $listenerPid -Force -ErrorAction Stop
        Write-RestartLog "openclaw restart killed stale listener source=update pid=$listenerPid"
      } catch {
        Write-RestartLog "openclaw restart failed to kill stale listener source=update pid=$listenerPid error=$($_.Exception.Message)"
      }
    }
    break
  }

  Start-Sleep -Seconds 1
}

$status = Invoke-OpenClawSchtasksWithTimeout -Arguments @("/Run", "/TN", $taskName) -TimeoutSeconds 30
if ($status -ne 0) {
  $status = Invoke-OpenClawStartupLauncher
}
if ($status -eq 0) {
  Write-RestartLog "openclaw restart done source=update"
} else {
  Write-RestartLog "openclaw restart failed source=update status=$status"
}

exit $status
`;
		} else return null;
		const scriptPath = path.join(tmpDir, filename);
		await fs.writeFile(scriptPath, scriptContent, { mode: 493 });
		return scriptPath;
	} catch {
		return null;
	}
}
/**
* Executes the prepared restart script as a **detached** process.
*
* The script must outlive the CLI process because the CLI itself is part
* of the service being restarted — `systemctl restart` / `launchctl
* kickstart -k` will terminate the current process tree.  Using
* `spawn({ detached: true })` + `unref()` ensures the script survives
* the parent's exit.
*
* Resolves immediately after spawning; the script runs independently.
*/
async function runRestartScript(scriptPath) {
	const isWindows = process.platform === "win32";
	spawn(isWindows ? "cmd.exe" : "/bin/sh", isWindows ? [
		"/d",
		"/s",
		"/c",
		quoteCmdScriptArg(scriptPath)
	] : [scriptPath], {
		detached: true,
		stdio: "ignore",
		windowsHide: true
	}).unref();
}
//#endregion
//#region src/cli/update-cli/suppress-deprecations.ts
/**
* Suppress Node.js deprecation warnings.
*
* On Node.js v23+ `process.noDeprecation` may be a read-only property
* (defined via a getter on the prototype with no setter), so the
* assignment can throw. We fall back to the environment variable which
* achieves the same effect.
*/
function suppressDeprecations() {
	try {
		process.noDeprecation = true;
	} catch {}
	process.env.NODE_NO_WARNINGS = "1";
}
//#endregion
//#region src/cli/update-cli/update-command.ts
const CLI_NAME = resolveCliName();
const SERVICE_REFRESH_TIMEOUT_MS = 6e4;
const DEFAULT_UPDATE_STEP_TIMEOUT_MS = 30 * 6e4;
const POST_CORE_UPDATE_ENV = "OPENCLAW_UPDATE_POST_CORE";
const POST_CORE_UPDATE_CHANNEL_ENV = "OPENCLAW_UPDATE_POST_CORE_CHANNEL";
const POST_CORE_UPDATE_REQUESTED_CHANNEL_ENV = "OPENCLAW_UPDATE_POST_CORE_REQUESTED_CHANNEL";
const POST_CORE_UPDATE_RESULT_PATH_ENV = "OPENCLAW_UPDATE_POST_CORE_RESULT_PATH";
const UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE_ENV = "OPENCLAW_UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE";
const SERVICE_REFRESH_PATH_ENV_KEYS = [
	"OPENCLAW_HOME",
	"OPENCLAW_STATE_DIR",
	"OPENCLAW_CONFIG_PATH"
];
const UPDATE_QUIPS = [
	"Leveled up! New skills unlocked. You're welcome.",
	"Fresh code, same lobster. Miss me?",
	"Back and better. Did you even notice I was gone?",
	"Update complete. I learned some new tricks while I was out.",
	"Upgraded! Now with 23% more sass.",
	"I've evolved. Try to keep up.",
	"New version, who dis? Oh right, still me but shinier.",
	"Patched, polished, and ready to pinch. Let's go.",
	"The lobster has molted. Harder shell, sharper claws.",
	"Update done! Check the changelog or just trust me, it's good.",
	"Reborn from the boiling waters of npm. Stronger now.",
	"I went away and came back smarter. You should try it sometime.",
	"Update complete. The bugs feared me, so they left.",
	"New version installed. Old version sends its regards.",
	"Firmware fresh. Brain wrinkles: increased.",
	"I've seen things you wouldn't believe. Anyway, I'm updated.",
	"Back online. The changelog is long but our friendship is longer.",
	"Upgraded! Peter fixed stuff. Blame him if it breaks.",
	"Molting complete. Please don't look at my soft shell phase.",
	"Version bump! Same chaos energy, fewer crashes (probably)."
];
function pickUpdateQuip() {
	return UPDATE_QUIPS[Math.floor(Math.random() * UPDATE_QUIPS.length)] ?? "Update complete.";
}
function isPackageManagerUpdateMode(mode) {
	return mode === "npm" || mode === "pnpm" || mode === "bun";
}
function shouldPrepareUpdatedInstallRestart(params) {
	if (isPackageManagerUpdateMode(params.updateMode)) return params.serviceInstalled;
	return params.serviceLoaded;
}
function shouldUseLegacyProcessRestartAfterUpdate(params) {
	return !isPackageManagerUpdateMode(params.updateMode);
}
async function maybeStopManagedServiceBeforePackageUpdate(params) {
	let service;
	let serviceState;
	try {
		service = resolveGatewayService();
		serviceState = await readGatewayServiceState(service, { env: process.env });
	} catch {
		return { stopped: false };
	}
	if (!serviceState.installed) return { stopped: false };
	if (!params.shouldRestart) {
		if (!params.jsonMode && serviceState.running) defaultRuntime.log(theme.warn("--no-restart is set while the managed gateway service is running; the package update will not stop or restart that process."));
		return {
			stopped: false,
			serviceEnv: serviceState.env
		};
	}
	if (!serviceState.running) return {
		stopped: false,
		serviceEnv: serviceState.env
	};
	if (!params.jsonMode) defaultRuntime.log(theme.muted("Stopping managed gateway service before package update..."));
	await service.stop({
		env: serviceState.env,
		stdout: process.stdout
	});
	return {
		stopped: true,
		serviceEnv: serviceState.env
	};
}
async function maybeRestartServiceAfterFailedPackageUpdate(params) {
	if (!params.prePackageServiceStop?.stopped || !params.prePackageServiceStop.serviceEnv) return;
	try {
		await resolveGatewayService().restart({
			env: params.prePackageServiceStop.serviceEnv,
			stdout: process.stdout
		});
		if (!params.jsonMode) defaultRuntime.log(theme.muted("Restarted managed gateway service after failed update."));
	} catch (err) {
		const message = `Failed to restart managed gateway service after failed update: ${String(err)}`;
		if (params.jsonMode) defaultRuntime.error(message);
		else defaultRuntime.log(theme.warn(message));
	}
}
function isRunningInsideGatewayService(env = process.env) {
	if (env.OPENCLAW_SERVICE_MARKER?.trim() !== "openclaw") return false;
	const serviceKind = env.OPENCLAW_SERVICE_KIND?.trim();
	return !serviceKind || serviceKind === "gateway";
}
function formatCommandFailure(stdout, stderr) {
	const detail = (stderr || stdout).trim();
	if (!detail) return "command returned a non-zero exit code";
	return detail.split("\n").slice(-3).join("\n");
}
function tryResolveInvocationCwd() {
	try {
		return process.cwd();
	} catch {
		return;
	}
}
async function resolvePackageRuntimePreflightError(params) {
	if (!canResolveRegistryVersionForPackageTarget(params.tag)) return null;
	const target = params.tag.trim();
	if (!target) return null;
	const status = await fetchNpmPackageTargetStatus({
		target,
		timeoutMs: params.timeoutMs
	});
	if (status.error) return null;
	if (nodeVersionSatisfiesEngine(process.versions.node ?? null, status.nodeEngine) !== false) return null;
	const targetLabel = status.version ?? target;
	return [
		`Node ${process.versions.node ?? "unknown"} is too old for openclaw@${targetLabel}.`,
		`The requested package requires ${status.nodeEngine}.`,
		"Upgrade Node to 22.14+ or Node 24, then rerun `openclaw update`.",
		"Bare `npm i -g openclaw` can silently install an older compatible release.",
		"After upgrading Node, use `npm i -g openclaw@latest`."
	].join("\n");
}
function resolveServiceRefreshEnv(env, invocationCwd) {
	const resolvedEnv = { ...env };
	for (const key of SERVICE_REFRESH_PATH_ENV_KEYS) {
		const rawValue = resolvedEnv[key]?.trim();
		if (!rawValue) continue;
		if (rawValue.startsWith("~") || path.isAbsolute(rawValue) || path.win32.isAbsolute(rawValue)) {
			resolvedEnv[key] = rawValue;
			continue;
		}
		if (!invocationCwd) {
			resolvedEnv[key] = rawValue;
			continue;
		}
		resolvedEnv[key] = path.resolve(invocationCwd, rawValue);
	}
	return resolvedEnv;
}
function disableUpdatedPackageCompileCacheEnv(env) {
	return {
		...env,
		NODE_DISABLE_COMPILE_CACHE: "1"
	};
}
function resolveUpdatedInstallCommandEnv(env, invocationCwd) {
	return disableUpdatedPackageCompileCacheEnv(resolveServiceRefreshEnv(env, invocationCwd));
}
function printDryRunPreview(preview, jsonMode) {
	if (jsonMode) {
		defaultRuntime.writeJson(preview);
		return;
	}
	defaultRuntime.log(theme.heading("Update dry-run"));
	defaultRuntime.log(theme.muted("No changes were applied."));
	defaultRuntime.log("");
	defaultRuntime.log(`  Root: ${theme.muted(preview.root)}`);
	defaultRuntime.log(`  Install kind: ${theme.muted(preview.installKind)}`);
	defaultRuntime.log(`  Mode: ${theme.muted(preview.mode)}`);
	defaultRuntime.log(`  Channel: ${theme.muted(preview.effectiveChannel)}`);
	defaultRuntime.log(`  Tag/spec: ${theme.muted(preview.tag)}`);
	if (preview.currentVersion) defaultRuntime.log(`  Current version: ${theme.muted(preview.currentVersion)}`);
	if (preview.targetVersion) defaultRuntime.log(`  Target version: ${theme.muted(preview.targetVersion)}`);
	if (preview.downgradeRisk) defaultRuntime.log(theme.warn("  Downgrade confirmation would be required in a real run."));
	defaultRuntime.log("");
	defaultRuntime.log(theme.heading("Planned actions:"));
	for (const action of preview.actions) defaultRuntime.log(`  - ${action}`);
	if (preview.notes.length > 0) {
		defaultRuntime.log("");
		defaultRuntime.log(theme.heading("Notes:"));
		for (const note of preview.notes) defaultRuntime.log(`  - ${theme.muted(note)}`);
	}
}
async function refreshGatewayServiceEnv(params) {
	const args = [
		"gateway",
		"install",
		"--force"
	];
	if (params.jsonMode) args.push("--json");
	const entrypoint = await resolveGatewayInstallEntrypoint(params.result.root);
	if (entrypoint) {
		const res = await runCommandWithTimeout([
			resolveNodeRunner(),
			entrypoint,
			...args
		], {
			cwd: params.result.root,
			env: resolveUpdatedInstallCommandEnv(params.env ?? process.env, params.invocationCwd),
			timeoutMs: SERVICE_REFRESH_TIMEOUT_MS
		});
		if (res.code === 0) return;
		throw new Error(`updated install refresh failed (${entrypoint}): ${formatCommandFailure(res.stdout, res.stderr)}`);
	}
	if (isPackageManagerUpdateMode(params.result.mode)) throw new Error(`updated install entrypoint not found under ${params.result.root ?? "unknown"}`);
	await runDaemonInstall({
		force: true,
		json: params.jsonMode || void 0
	});
}
async function runUpdatedInstallGatewayRestart(params) {
	const entrypoint = await resolveGatewayInstallEntrypoint(params.result.root);
	if (!entrypoint) throw new Error(`updated install entrypoint not found under ${params.result.root ?? "unknown"}`);
	const args = ["gateway", "restart"];
	if (params.jsonMode) args.push("--json");
	const res = await runCommandWithTimeout([
		resolveNodeRunner(),
		entrypoint,
		...args
	], {
		cwd: params.result.root,
		env: resolveUpdatedInstallCommandEnv(params.env ?? process.env, params.invocationCwd),
		timeoutMs: SERVICE_REFRESH_TIMEOUT_MS
	});
	if (res.code === 0) return true;
	throw new Error(`updated install restart failed (${entrypoint}): ${formatCommandFailure(res.stdout, res.stderr)}`);
}
async function tryInstallShellCompletion(opts) {
	if (opts.jsonMode || !process.stdin.isTTY) return;
	const status = await checkShellCompletionStatus(CLI_NAME);
	if (status.usesSlowPattern) {
		defaultRuntime.log(theme.muted("Upgrading shell completion to cached version..."));
		if (await ensureCompletionCacheExists(CLI_NAME)) await installCompletion(status.shell, true, CLI_NAME);
		return;
	}
	if (status.profileInstalled && !status.cacheExists) {
		defaultRuntime.log(theme.muted("Regenerating shell completion cache..."));
		await ensureCompletionCacheExists(CLI_NAME);
		return;
	}
	if (!status.profileInstalled) {
		defaultRuntime.log("");
		defaultRuntime.log(theme.heading("Shell completion"));
		const shouldInstall = await confirm({
			message: stylePromptMessage(`Enable ${status.shell} shell completion for ${CLI_NAME}?`),
			initialValue: true
		});
		if (isCancel(shouldInstall) || !shouldInstall) {
			if (!opts.skipPrompt) defaultRuntime.log(theme.muted(`Skipped. Run \`${replaceCliName(formatCliCommand("openclaw completion --install"), CLI_NAME)}\` later to enable.`));
			return;
		}
		if (!await ensureCompletionCacheExists(CLI_NAME)) {
			defaultRuntime.log(theme.warn("Failed to generate completion cache."));
			return;
		}
		await installCompletion(status.shell, opts.skipPrompt, CLI_NAME);
	}
}
async function runPackageInstallUpdate(params) {
	const manager = await resolveGlobalManager({
		root: params.root,
		installKind: params.installKind,
		timeoutMs: params.timeoutMs
	});
	const installEnv = await createGlobalInstallEnv();
	const runCommand = createGlobalCommandRunner();
	const installTarget = await resolveGlobalInstallTarget({
		manager,
		runCommand,
		timeoutMs: params.timeoutMs,
		pkgRoot: params.root
	});
	const pkgRoot = installTarget.packageRoot;
	const packageName = (pkgRoot ? await readPackageName(pkgRoot) : await readPackageName(params.root)) ?? "openclaw";
	const installSpec = resolveGlobalInstallSpec({
		packageName,
		tag: params.tag,
		env: installEnv
	});
	const beforeVersion = pkgRoot ? await readPackageVersion(pkgRoot) : null;
	if (pkgRoot) await cleanupGlobalRenameDirs({
		globalRoot: path.dirname(pkgRoot),
		packageName
	});
	const diskWarning = createLowDiskSpaceWarning({
		targetPath: pkgRoot ? path.dirname(pkgRoot) : params.root,
		purpose: "global package update"
	});
	if (diskWarning) if (params.jsonMode) defaultRuntime.error(`Warning: ${diskWarning}`);
	else defaultRuntime.log(theme.warn(diskWarning));
	const packageUpdate = await runGlobalPackageUpdateSteps({
		installTarget,
		installSpec,
		packageName,
		packageRoot: pkgRoot,
		runCommand,
		timeoutMs: params.timeoutMs,
		...installEnv === void 0 ? {} : { env: installEnv },
		runStep: (stepParams) => runUpdateStep({
			...stepParams,
			progress: params.progress
		}),
		postVerifyStep: async (verifiedPackageRoot) => {
			const entryPath = await resolveGatewayInstallEntrypoint(verifiedPackageRoot);
			if (entryPath) return await runUpdateStep({
				name: `${CLI_NAME} doctor`,
				argv: [
					resolveNodeRunner(),
					entryPath,
					"doctor",
					"--non-interactive",
					"--fix"
				],
				env: {
					...disableUpdatedPackageCompileCacheEnv(process.env),
					OPENCLAW_UPDATE_IN_PROGRESS: "1",
					[UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE_ENV]: "1"
				},
				timeoutMs: params.timeoutMs,
				progress: params.progress
			});
			return null;
		}
	});
	return {
		status: packageUpdate.failedStep ? "error" : "ok",
		mode: manager,
		root: packageUpdate.verifiedPackageRoot ?? params.root,
		reason: packageUpdate.failedStep ? packageUpdate.failedStep.name : void 0,
		before: { version: beforeVersion },
		after: { version: packageUpdate.afterVersion ?? beforeVersion },
		steps: packageUpdate.steps,
		durationMs: Date.now() - params.startedAt
	};
}
async function runGitUpdate(params) {
	const updateRoot = params.switchToGit ? resolveGitInstallDir() : params.root;
	const effectiveTimeout = params.timeoutMs ?? DEFAULT_UPDATE_STEP_TIMEOUT_MS;
	const installEnv = await createGlobalInstallEnv();
	const cloneStep = params.switchToGit ? await ensureGitCheckout({
		dir: updateRoot,
		env: installEnv,
		timeoutMs: effectiveTimeout,
		progress: params.progress
	}) : null;
	if (cloneStep && cloneStep.exitCode !== 0) {
		const result = {
			status: "error",
			mode: "git",
			root: updateRoot,
			reason: cloneStep.name,
			steps: [cloneStep],
			durationMs: Date.now() - params.startedAt
		};
		params.stop();
		printResult(result, {
			...params.opts,
			hideSteps: params.showProgress
		});
		defaultRuntime.exit(1);
		return result;
	}
	const updateResult = await runGatewayUpdate({
		cwd: updateRoot,
		argv1: params.switchToGit ? void 0 : process.argv[1],
		timeoutMs: params.timeoutMs,
		progress: params.progress,
		channel: params.channel,
		tag: params.tag,
		devTargetRef: params.devTargetRef
	});
	const steps = [...cloneStep ? [cloneStep] : [], ...updateResult.steps];
	if (params.switchToGit && updateResult.status === "ok") {
		const installStep = await runUpdateStep({
			name: "global install",
			argv: globalInstallArgs(await resolveGlobalInstallTarget({
				manager: await resolveGlobalManager({
					root: params.root,
					installKind: params.installKind,
					timeoutMs: effectiveTimeout
				}),
				runCommand: createGlobalCommandRunner(),
				timeoutMs: effectiveTimeout,
				pkgRoot: params.root
			}), updateRoot),
			cwd: updateRoot,
			env: installEnv,
			timeoutMs: effectiveTimeout,
			progress: params.progress
		});
		steps.push(installStep);
		const failedStep = installStep.exitCode !== 0 ? installStep : null;
		return {
			...updateResult,
			status: updateResult.status === "ok" && !failedStep ? "ok" : "error",
			steps,
			durationMs: Date.now() - params.startedAt
		};
	}
	return {
		...updateResult,
		steps,
		durationMs: Date.now() - params.startedAt
	};
}
async function updatePluginsAfterCoreUpdate(params) {
	if (!params.configSnapshot.valid) {
		if (!params.opts.json) defaultRuntime.log(theme.warn("Skipping plugin updates: config is invalid."));
		return {
			status: "skipped",
			reason: "invalid-config",
			changed: false,
			sync: {
				changed: false,
				switchedToBundled: [],
				switchedToNpm: [],
				warnings: [],
				errors: []
			},
			npm: {
				changed: false,
				outcomes: []
			},
			integrityDrifts: []
		};
	}
	const pluginLogger = params.opts.json ? {} : {
		info: (msg) => defaultRuntime.log(msg),
		warn: (msg) => defaultRuntime.log(theme.warn(msg)),
		error: (msg) => defaultRuntime.log(theme.error(msg))
	};
	if (!params.opts.json) {
		defaultRuntime.log("");
		defaultRuntime.log(theme.heading("Updating plugins..."));
	}
	const pluginInstallRecords = await loadInstalledPluginIndexInstallRecords();
	const syncResult = await syncPluginsForUpdateChannel({
		config: withPluginInstallRecords(params.configSnapshot.sourceConfig, pluginInstallRecords),
		channel: params.channel,
		workspaceDir: params.root,
		externalizedBundledPluginBridges: await listPersistedBundledPluginLocationBridges({ workspaceDir: params.root }),
		logger: pluginLogger
	});
	let pluginConfig = syncResult.config;
	const integrityDrifts = [];
	const npmResult = await updateNpmInstalledPlugins({
		config: pluginConfig,
		timeoutMs: params.timeoutMs,
		skipIds: new Set(syncResult.summary.switchedToNpm),
		skipDisabledPlugins: true,
		logger: pluginLogger,
		onIntegrityDrift: async (drift) => {
			integrityDrifts.push({
				pluginId: drift.pluginId,
				spec: drift.spec,
				expectedIntegrity: drift.expectedIntegrity,
				actualIntegrity: drift.actualIntegrity,
				...drift.resolvedSpec ? { resolvedSpec: drift.resolvedSpec } : {},
				...drift.resolvedVersion ? { resolvedVersion: drift.resolvedVersion } : {},
				action: "aborted"
			});
			if (!params.opts.json) {
				const specLabel = drift.resolvedSpec ?? drift.spec;
				defaultRuntime.log(theme.warn(`Integrity drift detected for "${drift.pluginId}" (${specLabel})\nExpected: ${drift.expectedIntegrity}\nActual:   ${drift.actualIntegrity}
Plugin update aborted. Reinstall the plugin only if you trust the new artifact.`));
			}
			return false;
		}
	});
	pluginConfig = npmResult.config;
	if (syncResult.changed || npmResult.changed) {
		const nextInstallRecords = pluginConfig.plugins?.installs ?? {};
		const nextConfig = withoutPluginInstallRecords(pluginConfig);
		await commitPluginInstallRecordsWithConfig({
			previousInstallRecords: pluginInstallRecords,
			nextInstallRecords,
			nextConfig,
			baseHash: params.configSnapshot.hash
		});
		await refreshPluginRegistryAfterConfigMutation({
			config: nextConfig,
			reason: "source-changed",
			workspaceDir: params.root,
			installRecords: nextInstallRecords,
			logger: pluginLogger
		});
	}
	if (params.opts.json) return {
		status: syncResult.summary.errors.length > 0 || npmResult.outcomes.some((outcome) => outcome.status === "error") ? "error" : "ok",
		changed: syncResult.changed || npmResult.changed,
		sync: {
			changed: syncResult.changed,
			switchedToBundled: syncResult.summary.switchedToBundled,
			switchedToNpm: syncResult.summary.switchedToNpm,
			warnings: syncResult.summary.warnings,
			errors: syncResult.summary.errors
		},
		npm: {
			changed: npmResult.changed,
			outcomes: npmResult.outcomes
		},
		integrityDrifts
	};
	const summarizeList = (list) => {
		if (list.length <= 6) return list.join(", ");
		return `${list.slice(0, 6).join(", ")} +${list.length - 6} more`;
	};
	if (syncResult.summary.switchedToBundled.length > 0) defaultRuntime.log(theme.muted(`Switched to bundled plugins: ${summarizeList(syncResult.summary.switchedToBundled)}.`));
	if (syncResult.summary.switchedToNpm.length > 0) defaultRuntime.log(theme.muted(`Restored npm plugins: ${summarizeList(syncResult.summary.switchedToNpm)}.`));
	for (const warning of syncResult.summary.warnings) defaultRuntime.log(theme.warn(warning));
	for (const error of syncResult.summary.errors) defaultRuntime.log(theme.error(error));
	const updated = npmResult.outcomes.filter((entry) => entry.status === "updated").length;
	const unchanged = npmResult.outcomes.filter((entry) => entry.status === "unchanged").length;
	const failed = npmResult.outcomes.filter((entry) => entry.status === "error").length;
	const skipped = npmResult.outcomes.filter((entry) => entry.status === "skipped").length;
	if (npmResult.outcomes.length === 0) defaultRuntime.log(theme.muted("No plugin updates needed."));
	else {
		const parts = [`${updated} updated`, `${unchanged} unchanged`];
		if (failed > 0) parts.push(`${failed} failed`);
		if (skipped > 0) parts.push(`${skipped} skipped`);
		defaultRuntime.log(theme.muted(`npm plugins: ${parts.join(", ")}.`));
	}
	for (const outcome of npmResult.outcomes) {
		if (outcome.status !== "error") continue;
		defaultRuntime.log(theme.error(outcome.message));
	}
	return {
		status: syncResult.summary.errors.length > 0 || npmResult.outcomes.some((outcome) => outcome.status === "error") ? "error" : "ok",
		changed: syncResult.changed || npmResult.changed,
		sync: {
			changed: syncResult.changed,
			switchedToBundled: syncResult.summary.switchedToBundled,
			switchedToNpm: syncResult.summary.switchedToNpm,
			warnings: syncResult.summary.warnings,
			errors: syncResult.summary.errors
		},
		npm: {
			changed: npmResult.changed,
			outcomes: npmResult.outcomes
		},
		integrityDrifts
	};
}
async function maybeRestartService(params) {
	const verifyRestartedGateway = async (expectedGatewayVersion) => {
		const restartAfterStaleCleanup = async () => {
			if (params.refreshServiceEnv && isPackageManagerUpdateMode(params.result.mode)) {
				await runUpdatedInstallGatewayRestart({
					result: params.result,
					jsonMode: Boolean(params.opts.json),
					invocationCwd: params.invocationCwd,
					env: params.serviceEnv
				});
				return;
			}
			if (shouldUseLegacyProcessRestartAfterUpdate({ updateMode: params.result.mode })) await runDaemonRestart();
		};
		const service = resolveGatewayService();
		let health = await waitForGatewayHealthyRestart({
			service,
			port: params.gatewayPort,
			expectedVersion: expectedGatewayVersion
		});
		if (!health.healthy && health.staleGatewayPids.length > 0) {
			if (!params.opts.json) defaultRuntime.log(theme.warn(`Found stale gateway process(es) after restart: ${health.staleGatewayPids.join(", ")}. Cleaning up...`));
			await terminateStaleGatewayPids(health.staleGatewayPids);
			await restartAfterStaleCleanup();
			health = await waitForGatewayHealthyRestart({
				service,
				port: params.gatewayPort,
				expectedVersion: expectedGatewayVersion
			});
		}
		if (health.healthy) return true;
		const diagnosticLines = [
			"Gateway did not become healthy after restart.",
			...renderRestartDiagnostics(health),
			`Restart log: ${resolveGatewayRestartLogPath(process.env)}`,
			`Run \`${replaceCliName(formatCliCommand("openclaw gateway status --deep"), CLI_NAME)}\` for details.`
		];
		if (params.opts.json) defaultRuntime.error(diagnosticLines.join("\n"));
		else {
			defaultRuntime.log(theme.warn(diagnosticLines[0] ?? "Gateway did not become healthy."));
			for (const line of diagnosticLines.slice(1)) defaultRuntime.log(theme.muted(line));
		}
		if (isPackageManagerUpdateMode(params.result.mode)) return false;
		return !(health.versionMismatch || health.activatedPluginErrors?.length);
	};
	if (params.shouldRestart) {
		if (!params.opts.json) {
			defaultRuntime.log("");
			defaultRuntime.log(theme.heading("Restarting service..."));
		}
		try {
			const expectedGatewayVersion = isPackageManagerUpdateMode(params.result.mode) ? normalizeOptionalString(params.result.after?.version) : void 0;
			const isPackageUpdate = isPackageManagerUpdateMode(params.result.mode);
			let restarted = false;
			let restartInitiated = false;
			if (params.refreshServiceEnv) try {
				await refreshGatewayServiceEnv({
					result: params.result,
					jsonMode: Boolean(params.opts.json),
					invocationCwd: params.invocationCwd,
					env: params.serviceEnv
				});
			} catch (err) {
				const message = `Failed to refresh gateway service environment from updated install: ${String(err)}`;
				if (params.opts.json) defaultRuntime.error(message);
				else defaultRuntime.log(theme.warn(message));
				if (isPackageUpdate) return false;
			}
			if (params.restartScriptPath) {
				await runRestartScript(params.restartScriptPath);
				restartInitiated = true;
			} else if (params.refreshServiceEnv && isPackageUpdate) restarted = await runUpdatedInstallGatewayRestart({
				result: params.result,
				jsonMode: Boolean(params.opts.json),
				invocationCwd: params.invocationCwd,
				env: params.serviceEnv
			});
			else if (shouldUseLegacyProcessRestartAfterUpdate({ updateMode: params.result.mode })) restarted = await runDaemonRestart();
			else if (!params.opts.json) defaultRuntime.log(theme.muted("No installed gateway service found; skipped restart."));
			if (restartInitiated || restarted && expectedGatewayVersion !== void 0) {
				if (!await verifyRestartedGateway(expectedGatewayVersion)) {
					if (!params.opts.json) defaultRuntime.log("");
					return false;
				}
				if (!params.opts.json && restartInitiated) {
					defaultRuntime.log(theme.success("Daemon restart completed."));
					defaultRuntime.log("");
				}
			}
			if (!params.opts.json && restarted) {
				defaultRuntime.log(theme.success("Daemon restarted successfully."));
				defaultRuntime.log("");
				process.env.OPENCLAW_UPDATE_IN_PROGRESS = "1";
				process.env[UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE_ENV] = "1";
				try {
					await doctorCommand(defaultRuntime, { nonInteractive: !(process.stdin.isTTY && !params.opts.json && params.opts.yes !== true) });
				} catch (err) {
					defaultRuntime.log(theme.warn(`Doctor failed: ${String(err)}`));
				} finally {
					delete process.env.OPENCLAW_UPDATE_IN_PROGRESS;
					delete process.env[UPDATE_PARENT_SUPPORTS_DOCTOR_CONFIG_WRITE_ENV];
				}
			}
		} catch (err) {
			if (!params.opts.json) {
				defaultRuntime.log(theme.warn(`Daemon restart failed: ${String(err)}`));
				defaultRuntime.log(theme.muted(`You may need to restart the service manually: ${replaceCliName(formatCliCommand("openclaw gateway restart"), CLI_NAME)}`));
			}
			if (isPackageManagerUpdateMode(params.result.mode)) return false;
		}
		return true;
	}
	if (!params.opts.json) {
		defaultRuntime.log("");
		if (params.result.mode === "npm" || params.result.mode === "pnpm") defaultRuntime.log(theme.muted(`Tip: Run \`${replaceCliName(formatCliCommand("openclaw doctor"), CLI_NAME)}\`, then \`${replaceCliName(formatCliCommand("openclaw gateway restart"), CLI_NAME)}\` to apply updates to a running gateway.`));
		else defaultRuntime.log(theme.muted(`Tip: Run \`${replaceCliName(formatCliCommand("openclaw gateway restart"), CLI_NAME)}\` to apply updates to a running gateway.`));
	}
	return true;
}
async function runPostCorePluginUpdate(params) {
	return await updatePluginsAfterCoreUpdate({
		root: params.root,
		channel: params.channel,
		configSnapshot: params.configSnapshot,
		opts: params.opts,
		timeoutMs: params.timeoutMs
	});
}
async function persistRequestedUpdateChannel(params) {
	if (!params.requestedChannel || !params.configSnapshot.valid) return params.configSnapshot;
	const storedChannel = normalizeUpdateChannel(params.configSnapshot.config.update?.channel);
	if (params.requestedChannel === storedChannel) return params.configSnapshot;
	const next = {
		...params.configSnapshot.sourceConfig,
		update: {
			...params.configSnapshot.sourceConfig.update,
			channel: params.requestedChannel
		}
	};
	await replaceConfigFile({
		nextConfig: next,
		baseHash: params.configSnapshot.hash
	});
	return {
		...params.configSnapshot,
		hash: void 0,
		parsed: next,
		sourceConfig: asResolvedSourceConfig(next),
		resolved: asResolvedSourceConfig(next),
		runtimeConfig: asRuntimeConfig(next),
		config: asRuntimeConfig(next)
	};
}
async function writePostCorePluginUpdateResultFile(filePath, result) {
	if (!filePath) return;
	await fs.writeFile(filePath, `${JSON.stringify(result)}\n`, "utf-8");
}
async function readPostCorePluginUpdateResultFile(filePath) {
	try {
		const raw = await fs.readFile(filePath, "utf-8");
		const parsed = JSON.parse(raw);
		if (parsed && typeof parsed === "object" && (parsed.status === "ok" || parsed.status === "skipped" || parsed.status === "error")) return parsed;
	} catch {
		return;
	}
}
async function continuePostCoreUpdateInFreshProcess(params) {
	const entryPath = await resolveGatewayInstallEntrypoint(params.root);
	if (!entryPath) return { resumed: false };
	const argv = [entryPath, "update"];
	if (params.opts.json) argv.push("--json");
	if (params.opts.restart === false) argv.push("--no-restart");
	if (params.opts.yes) argv.push("--yes");
	if (params.opts.timeout) argv.push("--timeout", params.opts.timeout);
	const resultDir = params.opts.json === true ? await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-update-post-core-")) : null;
	const resultPath = resultDir ? path.join(resultDir, "plugins.json") : null;
	try {
		const child = spawn(resolveNodeRunner(), argv, {
			stdio: "inherit",
			env: {
				...disableUpdatedPackageCompileCacheEnv(process.env),
				[POST_CORE_UPDATE_ENV]: "1",
				[POST_CORE_UPDATE_CHANNEL_ENV]: params.channel,
				...params.requestedChannel ? { [POST_CORE_UPDATE_REQUESTED_CHANNEL_ENV]: params.requestedChannel } : {},
				...resultPath ? { [POST_CORE_UPDATE_RESULT_PATH_ENV]: resultPath } : {}
			}
		});
		const exitCode = await new Promise((resolve, reject) => {
			child.once("error", reject);
			child.once("exit", (code, signal) => {
				if (signal) {
					reject(/* @__PURE__ */ new Error(`post-update process terminated by signal ${signal}`));
					return;
				}
				resolve(code ?? 1);
			});
		});
		const pluginUpdate = resultPath ? await readPostCorePluginUpdateResultFile(resultPath) : void 0;
		if (exitCode !== 0) {
			if (pluginUpdate) return {
				resumed: true,
				pluginUpdate
			};
			defaultRuntime.exit(exitCode);
			throw new Error(`post-update process exited with code ${exitCode}`);
		}
		return {
			resumed: true,
			...pluginUpdate ? { pluginUpdate } : {}
		};
	} finally {
		if (resultDir) await fs.rm(resultDir, {
			recursive: true,
			force: true
		}).catch(() => void 0);
	}
}
function shouldResumePostCoreUpdateInFreshProcess(params) {
	if (params.downgradeRisk) return false;
	if (isPackageManagerUpdateMode(params.result.mode)) return true;
	if (params.result.mode !== "git") return false;
	const beforeSha = normalizeOptionalString(params.result.before?.sha);
	const afterSha = normalizeOptionalString(params.result.after?.sha);
	if (beforeSha && afterSha && beforeSha !== afterSha) return true;
	const beforeVersion = normalizeOptionalString(params.result.before?.version);
	const afterVersion = normalizeOptionalString(params.result.after?.version);
	return Boolean(beforeVersion && afterVersion && beforeVersion !== afterVersion);
}
async function updateCommand(opts) {
	suppressDeprecations();
	const invocationCwd = tryResolveInvocationCwd();
	const postCoreUpdateResume = process.env[POST_CORE_UPDATE_ENV] === "1";
	const postCoreUpdateChannel = process.env[POST_CORE_UPDATE_CHANNEL_ENV]?.trim();
	const postCoreRequestedChannelInput = process.env[POST_CORE_UPDATE_REQUESTED_CHANNEL_ENV]?.trim() ?? "";
	const timeoutMs = parseTimeoutMsOrExit(opts.timeout);
	const shouldRestart = opts.restart !== false;
	if (timeoutMs === null) return;
	const updateStepTimeoutMs = timeoutMs ?? DEFAULT_UPDATE_STEP_TIMEOUT_MS;
	const root = await resolveUpdateRoot();
	if (postCoreUpdateResume) {
		if (postCoreUpdateChannel !== "stable" && postCoreUpdateChannel !== "beta" && postCoreUpdateChannel !== "dev") {
			defaultRuntime.error("Missing post-core update channel context.");
			defaultRuntime.exit(1);
			return;
		}
		const postCoreRequestedChannel = postCoreRequestedChannelInput ? normalizeUpdateChannel(postCoreRequestedChannelInput) : null;
		if (postCoreRequestedChannelInput && !postCoreRequestedChannel) {
			defaultRuntime.error("Invalid post-core requested update channel context.");
			defaultRuntime.exit(1);
			return;
		}
		const pluginUpdate = await runPostCorePluginUpdate({
			root,
			channel: postCoreUpdateChannel,
			configSnapshot: await persistRequestedUpdateChannel({
				configSnapshot: await readConfigFileSnapshot(),
				requestedChannel: postCoreRequestedChannel
			}),
			opts,
			timeoutMs: updateStepTimeoutMs
		});
		if (opts.json) {
			await writePostCorePluginUpdateResultFile(process.env[POST_CORE_UPDATE_RESULT_PATH_ENV], pluginUpdate);
			if (!process.env[POST_CORE_UPDATE_RESULT_PATH_ENV]) {
				const result = {
					status: pluginUpdate.status === "error" ? "error" : "ok",
					mode: "unknown",
					root,
					steps: [],
					durationMs: 0,
					postUpdate: { plugins: pluginUpdate }
				};
				defaultRuntime.writeJson(result);
			}
		}
		if (pluginUpdate.status === "error") {
			defaultRuntime.exit(1);
			return;
		}
		return;
	}
	const updateStatus = await checkUpdateStatus({
		root,
		timeoutMs: timeoutMs ?? 3500,
		fetchGit: false,
		includeRegistry: false
	});
	const configSnapshot = await readConfigFileSnapshot();
	const storedChannel = configSnapshot.valid ? normalizeUpdateChannel(configSnapshot.config.update?.channel) : null;
	const requestedChannel = normalizeUpdateChannel(opts.channel);
	if (opts.channel && !requestedChannel) {
		defaultRuntime.error(`--channel must be "stable", "beta", or "dev" (got "${opts.channel}")`);
		defaultRuntime.exit(1);
		return;
	}
	if (opts.channel && !configSnapshot.valid) {
		const issues = formatConfigIssueLines(configSnapshot.issues, "-");
		defaultRuntime.error(["Config is invalid; cannot set update channel.", ...issues].join("\n"));
		defaultRuntime.exit(1);
		return;
	}
	const installKind = updateStatus.installKind;
	const switchToGit = requestedChannel === "dev" && installKind !== "git";
	const switchToPackage = requestedChannel !== null && requestedChannel !== "dev" && installKind === "git";
	const updateInstallKind = switchToGit ? "git" : switchToPackage ? "package" : installKind;
	const channel = requestedChannel ?? storedChannel ?? (updateInstallKind === "git" ? "dev" : "stable");
	const devTargetRef = channel === "dev" ? process.env.OPENCLAW_UPDATE_DEV_TARGET_REF?.trim() || void 0 : void 0;
	const explicitTag = normalizeTag(opts.tag);
	let tag = explicitTag ?? channelToNpmTag(channel);
	let currentVersion = null;
	let targetVersion = null;
	let downgradeRisk = false;
	let fallbackToLatest = false;
	let packageInstallSpec = null;
	let packageAlreadyCurrent = false;
	if (updateInstallKind !== "git") {
		currentVersion = switchToPackage ? null : await readPackageVersion(root);
		if (explicitTag) targetVersion = await resolveTargetVersion(tag, timeoutMs);
		else targetVersion = await resolveNpmChannelTag({
			channel,
			timeoutMs
		}).then((resolved) => {
			tag = resolved.tag;
			fallbackToLatest = channel === "beta" && resolved.tag === "latest";
			return resolved.version;
		});
		const cmp = currentVersion && targetVersion ? compareSemverStrings(currentVersion, targetVersion) : null;
		packageAlreadyCurrent = updateInstallKind === "package" && !switchToPackage && currentVersion != null && targetVersion != null && currentVersion === targetVersion && (requestedChannel === null || requestedChannel === storedChannel);
		downgradeRisk = canResolveRegistryVersionForPackageTarget(tag) && !fallbackToLatest && currentVersion != null && (targetVersion == null || cmp != null && cmp > 0);
		packageInstallSpec = resolveGlobalInstallSpec({
			packageName: DEFAULT_PACKAGE_NAME,
			tag,
			env: process.env
		});
	}
	if (opts.dryRun) {
		let mode = "unknown";
		if (updateInstallKind === "git") mode = "git";
		else if (updateInstallKind === "package") mode = await resolveGlobalManager({
			root,
			installKind,
			timeoutMs: updateStepTimeoutMs
		});
		const actions = [];
		if (requestedChannel && requestedChannel !== storedChannel) actions.push(`Persist update.channel=${requestedChannel} in config`);
		if (switchToGit) actions.push("Switch install mode from package to git checkout (dev channel)");
		else if (switchToPackage) actions.push(`Switch install mode from git to package manager (${mode})`);
		else if (updateInstallKind === "git") actions.push(`Run git update flow on channel ${channel} (fetch/rebase/build/doctor)`);
		else if (packageAlreadyCurrent) actions.push(`Refresh package install with spec ${packageInstallSpec ?? tag}; current version already matches ${targetVersion}`);
		else actions.push(`Run global package manager update with spec ${packageInstallSpec ?? tag}`);
		actions.push("Run plugin update sync after core update");
		actions.push("Refresh shell completion cache (if needed)");
		actions.push(shouldRestart ? "Restart gateway service and run doctor checks" : "Skip restart (because --no-restart is set)");
		const notes = [];
		if (opts.tag && updateInstallKind === "git") notes.push("--tag applies to npm installs only; git updates ignore it.");
		if (fallbackToLatest) notes.push("Beta channel resolves to latest for this run (fallback).");
		if (explicitTag && !canResolveRegistryVersionForPackageTarget(tag)) notes.push("Non-registry package specs skip npm version lookup and downgrade previews.");
		printDryRunPreview({
			dryRun: true,
			root,
			installKind,
			mode,
			updateInstallKind,
			switchToGit,
			switchToPackage,
			restart: shouldRestart,
			requestedChannel,
			storedChannel,
			effectiveChannel: channel,
			tag: packageInstallSpec ?? tag,
			currentVersion,
			targetVersion,
			downgradeRisk,
			actions,
			notes
		}, Boolean(opts.json));
		return;
	}
	if (updateInstallKind === "package" && isRunningInsideGatewayService()) {
		defaultRuntime.error([
			"Package updates cannot run from inside the gateway service process.",
			"That path replaces the active OpenClaw dist tree while the live gateway may still lazy-load old chunks.",
			`Run \`${replaceCliName(formatCliCommand("openclaw update"), CLI_NAME)}\` from a shell outside the gateway service, or stop the gateway service first and then update.`
		].join("\n"));
		defaultRuntime.exit(1);
		return;
	}
	if (downgradeRisk && !opts.yes) {
		if (!process.stdin.isTTY || opts.json) {
			defaultRuntime.error(["Downgrade confirmation required.", "Downgrading can break configuration. Re-run in a TTY to confirm."].join("\n"));
			defaultRuntime.exit(1);
			return;
		}
		const targetLabel = targetVersion ?? `${tag} (unknown)`;
		const ok = await confirm({
			message: stylePromptMessage(`Downgrading from ${currentVersion} to ${targetLabel} can break configuration. Continue?`),
			initialValue: false
		});
		if (isCancel(ok) || !ok) {
			if (!opts.json) defaultRuntime.log(theme.muted("Update cancelled."));
			defaultRuntime.exit(0);
			return;
		}
	}
	if (updateInstallKind === "git" && opts.tag && !opts.json) defaultRuntime.log(theme.muted("Note: --tag applies to npm installs only; git updates ignore it."));
	if (updateInstallKind === "package") {
		const runtimePreflightError = await resolvePackageRuntimePreflightError({
			tag,
			timeoutMs
		});
		if (runtimePreflightError) {
			defaultRuntime.error(runtimePreflightError);
			defaultRuntime.exit(1);
			return;
		}
	}
	const showProgress = !opts.json && process.stdout.isTTY;
	if (!opts.json) {
		defaultRuntime.log(theme.heading("Updating OpenClaw..."));
		defaultRuntime.log("");
	}
	const { progress, stop } = createUpdateProgress(showProgress);
	const startedAt = Date.now();
	let prePackageServiceStop;
	if (updateInstallKind === "package") try {
		prePackageServiceStop = await maybeStopManagedServiceBeforePackageUpdate({
			shouldRestart,
			jsonMode: Boolean(opts.json)
		});
	} catch (err) {
		stop();
		defaultRuntime.error(`Failed to stop managed gateway service before update: ${String(err)}`);
		defaultRuntime.exit(1);
		return;
	}
	let result;
	try {
		result = updateInstallKind === "package" ? await runPackageInstallUpdate({
			root,
			installKind,
			tag,
			timeoutMs: updateStepTimeoutMs,
			startedAt,
			progress,
			jsonMode: Boolean(opts.json)
		}) : await runGitUpdate({
			root,
			switchToGit,
			installKind,
			timeoutMs,
			startedAt,
			progress,
			channel,
			tag,
			showProgress,
			opts,
			stop,
			devTargetRef
		});
	} catch (err) {
		stop();
		await maybeRestartServiceAfterFailedPackageUpdate({
			prePackageServiceStop,
			jsonMode: Boolean(opts.json)
		});
		throw err;
	}
	stop();
	if (!opts.json || result.status !== "ok") printResult(result, {
		...opts,
		hideSteps: showProgress
	});
	if (result.status === "error") {
		await maybeRestartServiceAfterFailedPackageUpdate({
			prePackageServiceStop,
			jsonMode: Boolean(opts.json)
		});
		defaultRuntime.exit(1);
		return;
	}
	if (result.status === "skipped") {
		await maybeRestartServiceAfterFailedPackageUpdate({
			prePackageServiceStop,
			jsonMode: Boolean(opts.json)
		});
		if (result.reason === "dirty") {
			defaultRuntime.error(theme.error("Update blocked: local files are edited in this checkout."));
			defaultRuntime.log(theme.warn("Git-based updates need a clean working tree before they can switch commits, fetch, or rebase."));
			defaultRuntime.log(theme.muted("Commit, stash, or discard the local changes, then rerun `openclaw update`."));
		}
		if (result.reason === "not-git-install") {
			defaultRuntime.log(theme.warn(`Skipped: this OpenClaw install isn't a git checkout, and the package manager couldn't be detected. Update via your package manager, then run \`${replaceCliName(formatCliCommand("openclaw doctor"), CLI_NAME)}\` and \`${replaceCliName(formatCliCommand("openclaw gateway restart"), CLI_NAME)}\`.`));
			defaultRuntime.log(theme.muted(`Examples: \`${replaceCliName("npm i -g openclaw@latest", CLI_NAME)}\` or \`${replaceCliName("pnpm add -g openclaw@latest", CLI_NAME)}\``));
		}
		defaultRuntime.exit(0);
		return;
	}
	const shouldResumePostCoreInFreshProcess = shouldResumePostCoreUpdateInFreshProcess({
		result,
		downgradeRisk
	});
	let postUpdateConfigSnapshot = configSnapshot;
	if (!shouldResumePostCoreInFreshProcess) postUpdateConfigSnapshot = await persistRequestedUpdateChannel({
		configSnapshot,
		requestedChannel
	});
	if (requestedChannel && configSnapshot.valid && requestedChannel !== storedChannel && !shouldResumePostCoreInFreshProcess && !opts.json) defaultRuntime.log(theme.muted(`Update channel set to ${requestedChannel}.`));
	else if (requestedChannel && configSnapshot.valid && requestedChannel !== storedChannel && shouldResumePostCoreInFreshProcess && !opts.json) defaultRuntime.log(theme.muted(`Update channel will be set to ${requestedChannel}.`));
	const postUpdateRoot = result.root ?? root;
	let postCorePluginUpdate;
	let pluginsUpdatedInFreshProcess = false;
	if (shouldResumePostCoreInFreshProcess) {
		const freshProcessResult = await continuePostCoreUpdateInFreshProcess({
			root: postUpdateRoot,
			channel,
			requestedChannel,
			opts
		});
		pluginsUpdatedInFreshProcess = freshProcessResult.resumed;
		postCorePluginUpdate = freshProcessResult.pluginUpdate;
	}
	if (!pluginsUpdatedInFreshProcess) {
		if (shouldResumePostCoreInFreshProcess) postUpdateConfigSnapshot = await persistRequestedUpdateChannel({
			configSnapshot,
			requestedChannel
		});
		postCorePluginUpdate = await runPostCorePluginUpdate({
			root: postUpdateRoot,
			channel,
			configSnapshot: postUpdateConfigSnapshot,
			opts,
			timeoutMs: updateStepTimeoutMs
		});
	}
	const resultWithPostUpdate = postCorePluginUpdate ? {
		...result,
		status: postCorePluginUpdate.status === "error" ? "error" : result.status,
		...postCorePluginUpdate.status === "error" ? { reason: "post-update-plugins" } : {},
		postUpdate: {
			...result.postUpdate,
			plugins: postCorePluginUpdate
		}
	} : result;
	if (postCorePluginUpdate?.status === "error") {
		if (opts.json) defaultRuntime.writeJson(resultWithPostUpdate);
		else defaultRuntime.error(theme.error("Update failed during plugin post-update sync."));
		await maybeRestartServiceAfterFailedPackageUpdate({
			prePackageServiceStop,
			jsonMode: Boolean(opts.json)
		});
		defaultRuntime.exit(1);
		return;
	}
	let restartScriptPath = null;
	let refreshGatewayServiceEnv = false;
	let gatewayServiceEnv;
	const gatewayPort = resolveGatewayPort(postUpdateConfigSnapshot.valid ? postUpdateConfigSnapshot.config : void 0, process.env);
	if (shouldRestart) try {
		const serviceState = await readGatewayServiceState(resolveGatewayService(), { env: process.env });
		if (shouldPrepareUpdatedInstallRestart({
			updateMode: resultWithPostUpdate.mode,
			serviceInstalled: serviceState.installed,
			serviceLoaded: serviceState.loaded
		})) {
			gatewayServiceEnv = serviceState.env;
			restartScriptPath = await prepareRestartScript(serviceState.env, gatewayPort);
			refreshGatewayServiceEnv = true;
		}
	} catch {}
	await tryWriteCompletionCache(postUpdateRoot, Boolean(opts.json));
	await tryInstallShellCompletion({
		jsonMode: Boolean(opts.json),
		skipPrompt: Boolean(opts.yes)
	});
	if (!await maybeRestartService({
		shouldRestart,
		result: resultWithPostUpdate,
		opts,
		refreshServiceEnv: refreshGatewayServiceEnv,
		serviceEnv: gatewayServiceEnv,
		gatewayPort,
		restartScriptPath,
		invocationCwd
	})) {
		defaultRuntime.exit(1);
		return;
	}
	if (!opts.json) defaultRuntime.log(theme.muted(pickUpdateQuip()));
	else defaultRuntime.writeJson(resultWithPostUpdate);
}
//#endregion
//#region src/cli/update-cli/wizard.ts
async function updateWizardCommand(opts = {}) {
	if (!process.stdin.isTTY) {
		defaultRuntime.error("Update wizard requires a TTY. Use `openclaw update --channel <stable|beta|dev>` instead.");
		defaultRuntime.exit(1);
		return;
	}
	const timeoutMs = parseTimeoutMsOrExit(opts.timeout);
	if (timeoutMs === null) return;
	const root = await resolveUpdateRoot();
	const [updateStatus, configSnapshot] = await Promise.all([checkUpdateStatus({
		root,
		timeoutMs: timeoutMs ?? 3500,
		fetchGit: false,
		includeRegistry: false
	}), readConfigFileSnapshot()]);
	const channelInfo = resolveEffectiveUpdateChannel({
		configChannel: configSnapshot.valid ? normalizeUpdateChannel(configSnapshot.config.update?.channel) : null,
		installKind: updateStatus.installKind,
		git: updateStatus.git ? {
			tag: updateStatus.git.tag,
			branch: updateStatus.git.branch
		} : void 0
	});
	const channelLabel = formatUpdateChannelLabel({
		channel: channelInfo.channel,
		source: channelInfo.source,
		gitTag: updateStatus.git?.tag ?? null,
		gitBranch: updateStatus.git?.branch ?? null
	});
	const pickedChannel = await selectStyled({
		message: "Update channel",
		options: [
			{
				value: "keep",
				label: `Keep current (${channelInfo.channel})`,
				hint: channelLabel
			},
			{
				value: "stable",
				label: "Stable",
				hint: "Tagged releases (npm latest)"
			},
			{
				value: "beta",
				label: "Beta",
				hint: "Prereleases (npm beta)"
			},
			{
				value: "dev",
				label: "Dev",
				hint: "Git main"
			}
		],
		initialValue: "keep"
	});
	if (isCancel(pickedChannel)) {
		defaultRuntime.log(theme.muted("Update cancelled."));
		defaultRuntime.exit(0);
		return;
	}
	const requestedChannel = pickedChannel === "keep" ? null : pickedChannel;
	if (requestedChannel === "dev" && updateStatus.installKind !== "git") {
		const gitDir = resolveGitInstallDir();
		if (!await isGitCheckout(gitDir)) {
			if (await pathExists(gitDir)) {
				if (!await isEmptyDir(gitDir)) {
					defaultRuntime.error(`OPENCLAW_GIT_DIR points at a non-git directory: ${gitDir}. Set OPENCLAW_GIT_DIR to an empty folder or an openclaw checkout.`);
					defaultRuntime.exit(1);
					return;
				}
			}
			const ok = await confirm({
				message: stylePromptMessage(`Create a git checkout at ${gitDir}? (override via OPENCLAW_GIT_DIR)`),
				initialValue: true
			});
			if (isCancel(ok) || !ok) {
				defaultRuntime.log(theme.muted("Update cancelled."));
				defaultRuntime.exit(0);
				return;
			}
		}
	}
	const restart = await confirm({
		message: stylePromptMessage("Restart the gateway service after update?"),
		initialValue: true
	});
	if (isCancel(restart)) {
		defaultRuntime.log(theme.muted("Update cancelled."));
		defaultRuntime.exit(0);
		return;
	}
	try {
		await updateCommand({
			channel: requestedChannel ?? void 0,
			restart,
			timeout: opts.timeout
		});
	} catch (err) {
		defaultRuntime.error(String(err));
		defaultRuntime.exit(1);
	}
}
//#endregion
//#region src/cli/update-cli.ts
function inheritedUpdateJson(command) {
	return Boolean(inheritOptionFromParent(command, "json"));
}
function inheritedUpdateTimeout(opts, command) {
	const timeout = opts.timeout;
	if (timeout) return timeout;
	return inheritOptionFromParent(command, "timeout");
}
function registerUpdateCli(program) {
	program.enablePositionalOptions();
	const update = program.command("update").description("Update OpenClaw and inspect update channel status").option("--json", "Output result as JSON", false).option("--no-restart", "Skip restarting the gateway service after a successful update").option("--dry-run", "预览更新操作而不做任何更改", false).option("--channel <stable|beta|dev>", "Persist update channel (git + npm)").option("--tag <dist-tag|version|spec>", "Override the package target for this update (dist-tag, version, or package spec)").option("--timeout <seconds>", "Timeout for each update step in seconds (default: 1800)").option("--yes", "Skip confirmation prompts (non-interactive)", false).addHelpText("after", () => {
		const fmtExamples = [
			["openclaw update", "Update a source checkout (git)"],
			["openclaw update --channel beta", "Switch to beta channel (git + npm)"],
			["openclaw update --channel dev", "Switch to dev channel (git + npm)"],
			["openclaw update --tag beta", "One-off update to a dist-tag or version"],
			["openclaw update --tag main", "One-off package install from GitHub main"],
			["openclaw update --dry-run", "预览操作而不做任何更改"],
			["openclaw update --no-restart", "Update without restarting the service"],
			["openclaw update --json", "Output result as JSON"],
			["openclaw update --yes", "Non-interactive (accept downgrade prompts)"],
			["openclaw update wizard", "Interactive update wizard"],
			["openclaw --update", "Shorthand for openclaw update"]
		].map(([cmd, desc]) => `  ${theme.command(cmd)} ${theme.muted(`# ${desc}`)}`).join("\n");
		return `
${theme.heading("此命令功能：")}
  - Git checkouts: fetches, rebases, installs deps, builds, and runs doctor
  - npm installs: updates via detected package manager

${theme.heading("切换更新通道：")}
  - Use --channel stable|beta|dev to persist the update channel in config
  - Run openclaw update status to see the active channel and source
  - Use --tag <dist-tag|version|spec> for a one-off package update without persisting

${theme.heading("非交互模式：")}
  - Use --yes to accept downgrade prompts
  - Combine with --channel/--tag/--no-restart/--json/--timeout as needed
  - 使用 --dry-run 预览操作而不写入配置/安装/重启

${theme.heading("示例：")}
${fmtExamples}

${theme.heading("注意事项：")}
  - Switch channels with --channel stable|beta|dev
  - For global installs: auto-updates via detected package manager when possible (see docs/install/updating.md)
  - Downgrades require confirmation (can break configuration)
  - Skips update if the working directory has uncommitted changes

${theme.muted("Docs:")} ${formatDocsLink("/cli/update", "docs.openclaw.ai/cli/update")}`;
	}).action(async (opts) => {
		try {
			await updateCommand({
				json: Boolean(opts.json),
				restart: Boolean(opts.restart),
				dryRun: Boolean(opts.dryRun),
				channel: opts.channel,
				tag: opts.tag,
				timeout: opts.timeout,
				yes: Boolean(opts.yes)
			});
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
	update.command("wizard").description("Interactive update wizard").option("--timeout <seconds>", "Timeout for each update step in seconds (default: 1800)").addHelpText("after", `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/update", "docs.openclaw.ai/cli/update")}\n`).action(async (opts, command) => {
		try {
			await updateWizardCommand({ timeout: inheritedUpdateTimeout(opts, command) });
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
	update.command("status").description("Show update channel and version status").option("--json", "Output result as JSON", false).option("--timeout <seconds>", "Timeout for update checks in seconds (default: 3)").addHelpText("after", () => `\n${theme.heading("示例：")}\n${formatHelpExamples([
		["openclaw update status", "Show channel + version status."],
		["openclaw update status --json", "JSON output."],
		["openclaw update status --timeout 10", "Custom timeout."]
	])}\n\n${theme.heading("注意事项：")}\n${theme.muted("- Shows current update channel (stable/beta/dev) and source")}\n${theme.muted("- Includes git tag/branch/SHA for source checkouts")}\n\n${theme.muted("Docs:")} ${formatDocsLink("/cli/update", "docs.openclaw.ai/cli/update")}`).action(async (opts, command) => {
		try {
			await updateStatusCommand({
				json: Boolean(opts.json) || inheritedUpdateJson(command),
				timeout: inheritedUpdateTimeout(opts, command)
			});
		} catch (err) {
			defaultRuntime.error(String(err));
			defaultRuntime.exit(1);
		}
	});
}
//#endregion
export { registerUpdateCli, updateCommand, updateStatusCommand, updateWizardCommand };
