import { Mt as pathExists, Q as theme, _ as defaultRuntime, yt as resolveStateDir } from "./entry.js";
import "./auth-profiles-D11Xw15i.js";
import { n as resolveCliName, t as replaceCliName } from "./cli-name-DY75UA5M.js";
import { t as formatCliCommand } from "./command-format-B3nkKRhC.js";
import { t as resolveSymiPackageRoot } from "./symi-root-Ctw1Rb_n.js";
import { t as runCommandWithTimeout } from "./exec-CzwIUObA.js";
import "./agent-scope-C-Jte08L.js";
import "./model-selection-CMx1evaF.js";
import "./file-lock-DrmXX3vL.js";
import "./agent-paths-DryQawbH.js";
import "./pi-auth-json-mn8xSJKs.js";
import "./model-B4Btg-Q6.js";
import "./pi-model-discovery-EgBaDO8n.js";
import "./frontmatter-PrEWR41G.js";
import "./skills-cLBEdkqu.js";
import "./manifest-registry-CVLmi8rz.js";
import "./skills-status-g3ssrjuX.js";
import { l as writeConfigFile, o as readConfigFileSnapshot } from "./config-D7TcU4qN.js";
import "./shell-env-CTYaxUs_.js";
import "./client-BOd5o3Kp.js";
import "./call-DTshgdlW.js";
import "./message-channel-DXToSaWK.js";
import "./pairing-token-B-OTYROz.js";
import "./subagent-registry-CVhLz4p3.js";
import "./sessions-Dn6VXn4p.js";
import "./plugins-BsEhWvLn.js";
import "./send-Dq252-bi.js";
import "./with-timeout-B9GM8DPj.js";
import "./deliver-DIK2emIV.js";
import "./diagnostic-IdKKvrDQ.js";
import "./diagnostic-session-state-CIjIGxEE.js";
import "./pi-embedded-helpers-BQjRftRI.js";
import "./sandbox-DjKcZavm.js";
import "./chrome-D1eO2jfe.js";
import "./tailscale-FeJ1M0mP.js";
import "./auth-pHRwjgkx.js";
import "./server-context-DrAh6Cgw.js";
import "./routes-wLkmjLj9.js";
import "./redact-Dj3r1_tS.js";
import "./errors-BmdGLmRC.js";
import "./fs-safe-D0xrTzGw.js";
import "./paths-8yCI1Car.js";
import "./ssrf-BZFvPKEu.js";
import "./image-ops-FPBHTBd0.js";
import "./ports-uA7P2qIK.js";
import "./trash-Bx4LIudf.js";
import "./dock-DZ6SgvTh.js";
import "./paths-DtiEyjsC.js";
import "./thinking-BZDIJMl_.js";
import "./model-auth-Byr7Gic_.js";
import "./github-copilot-token-B5y4__YM.js";
import "./models-config-CiR_RUxw.js";
import "./reply-prefix-DV3KhOhL.js";
import "./memory-C02Znuee.js";
import "./manager-DH00nlW8.js";
import "./sqlite-9jF_eajd.js";
import "./chunk-B2lBXhR0.js";
import "./markdown-tables-BEdkErjm.js";
import "./fetch-guard-3_W2W6u_.js";
import "./local-roots-Bm30yHHs.js";
import "./commands-BiW8npr7.js";
import "./commands-registry-D8LQ9fss.js";
import "./tool-display-DxbOx1Kx.js";
import "./tokens-CC6jvm1-.js";
import "./skills-remote-DSGpkPJE.js";
import { c as trimLogTail } from "./redact-identifier-BOxAUdff.js";
import "./workspace-dirs-wlRR65M3.js";
import "./model-catalog-CzKsiNZA.js";
import "./session-utils-Zpe3t68b.js";
import "./skill-commands-BXP2zJNy.js";
import "./pairing-store-C4KBIVqJ.js";
import "./exec-approvals-DEjIocmZ.js";
import "./nodes-screen-_JvT4DjZ.js";
import { r as formatDurationPrecise } from "./format-duration-CIjmjQST.js";
import "./session-cost-usage-CJWHHY-C.js";
import "./breakdown-Cszrv-Lf.js";
import { c as resolveGatewayLaunchAgentLabel, d as resolveGatewaySystemdServiceName, f as resolveGatewayWindowsTaskName } from "./constants-BP_JoSwO.js";
import "./control-service-CG6l_Yap.js";
import "./stagger-DUVGiPYV.js";
import "./channel-selection-CmU8iVio.js";
import "./delivery-queue-B2oigbh4.js";
import "./bindings-BRZBH7eX.js";
import "./resolve-route-BVJ4-d9c.js";
import { t as formatDocsLink } from "./links-Dnmd-RS-.js";
import "./cli-utils-DXfA5936.js";
import { t as formatHelpExamples } from "./help-format-Dbp8yEhl.js";
import "./progress-CI19Xh3z.js";
import "./memory-cli-083UJtVJ.js";
import "./logging-UO6tk8Em.js";
import "./replies-CLREUzzB.js";
import "./pi-tools.policy-06k__URR.js";
import { n as inheritOptionFromParent } from "./command-options-BFvvecvU.js";
import "./catalog-BQgWCFTH.js";
import { n as stylePromptMessage } from "./prompt-style-CZGg35Py.js";
import "./note-BIAQpZxi.js";
import "./plugin-auto-enable-DaR6Z6BC.js";
import "./install-safe-path-BdxXJux8.js";
import "./npm-registry-spec-BPgK9EL7.js";
import "./skill-scanner-BC3PyNso.js";
import "./installs-Dunp9UFl.js";
import "./channels-status-issues-BTvrA4nx.js";
import "./register.subclis-QXO75pUm.js";
import "./command-registry-DBbzZvh6.js";
import "./program-context-B_0V80zV.js";
import { r as installCompletion } from "./completion-cli-DoQrkCAd.js";
import "./daemon-runtime-AkgOtHR6.js";
import { r as parseSemver } from "./runtime-guard-LRRZ73eX.js";
import "./onboard-helpers-t7tI9KSA.js";
import "./systemd-CNnW7Chw.js";
import { t as resolveGatewayService } from "./service-DYpU1ajf.js";
import "./lifecycle-core-YmWzkN43.js";
import "./systemd-hints-BoFy3-m1.js";
import { i as runDaemonInstall, r as runDaemonRestart } from "./daemon-cli-dbAPTgGm.js";
import "./diagnostics-D2oNwzue.js";
import { t as renderTable } from "./table-D0JXlEhQ.js";
import "./health-Dkwuq8ta.js";
import "./control-ui-assets-Dnz69KRU.js";
import { a as resolveNpmChannelTag, c as DEFAULT_PACKAGE_CHANNEL, d as formatUpdateChannelLabel, g as resolveUpdateChannelDisplay, h as resolveEffectiveUpdateChannel, m as normalizeUpdateChannel, n as compareSemverStrings, r as fetchNpmTagVersion, s as DEFAULT_GIT_CHANNEL, t as checkUpdateStatus, u as channelToNpmTag } from "./update-check-DLOnLuop.js";
import "./dm-policy-shared-BtrdvOIT.js";
import { i as resolveUpdateAvailability, n as formatUpdateOneLiner, t as formatUpdateAvailableHint } from "./status.update-DW6VHYmK.js";
import { a as globalInstallArgs, c as readPackageVersion, i as detectGlobalInstallManagerForRoot, n as cleanupGlobalRenameDirs, o as resolveGlobalPackageRoot, r as detectGlobalInstallManagerByPresence, s as readPackageName, t as runGatewayUpdate } from "./update-runner-Cext3X8r.js";
import "./logging-Ev3fNJEG.js";
import { n as updateNpmInstalledPlugins, t as syncPluginsForUpdateChannel } from "./update-B7qKOIqP.js";
import "./doctor-config-flow-BIBJeoRl.js";
import "./systemd-linger-CctFkWNE.js";
import "./health-format-6tfMqkNX.js";
import { n as doctorCommand, t as selectStyled } from "./prompt-select-styled-b752FPLG.js";
import { r as ensureCompletionCacheExists, t as checkShellCompletionStatus } from "./doctor-completion-Bk55g4MP.js";
import { spawn, spawnSync } from "node:child_process";
import os from "node:os";
import path from "node:path";
import fs from "node:fs/promises";
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 SYMI_REPO_URL = "https://github.com/symi/symi.git";
const MAX_LOG_CHARS = 8e3;
const DEFAULT_PACKAGE_NAME = "symi";
const CORE_PACKAGE_NAMES = new Set([DEFAULT_PACKAGE_NAME]);
function normalizeTag(value) {
	if (!value) return null;
	const trimmed = value.trim();
	if (!trimmed) return null;
	if (trimmed.startsWith("symi@")) return trimmed.slice(5);
	if (trimmed.startsWith(`${DEFAULT_PACKAGE_NAME}@`)) return trimmed.slice(`${DEFAULT_PACKAGE_NAME}@`.length);
	return trimmed;
}
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) {
	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.SYMI_GIT_DIR?.trim();
	if (override) return path.resolve(override);
	return resolveDefaultGitDir();
}
function resolveDefaultGitDir() {
	return resolveStateDir(process.env, os.homedir);
}
function resolveNodeRunner() {
	const base = path.basename(process.execPath).toLowerCase();
	if (base === "node" || base === "node.exe") return process.execPath;
	return "node";
}
async function resolveUpdateRoot() {
	return await resolveSymiPackageRoot({
		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,
		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) {
	if (!await pathExists(params.dir)) return await runUpdateStep({
		name: "git clone",
		argv: [
			"git",
			"clone",
			SYMI_REPO_URL,
			params.dir
		],
		timeoutMs: params.timeoutMs,
		progress: params.progress
	});
	if (!await isGitCheckout(params.dir)) {
		if (!await isEmptyDir(params.dir)) throw new Error(`SYMI_GIT_DIR points at a non-git directory: ${params.dir}. Set SYMI_GIT_DIR to an empty folder or an symi checkout.`);
		return await runUpdateStep({
			name: "git clone",
			argv: [
				"git",
				"clone",
				SYMI_REPO_URL,
				params.dir
			],
			cwd: params.dir,
			timeoutMs: params.timeoutMs,
			progress: params.progress
		});
	}
	if (!await isCorePackage(params.dir)) throw new Error(`SYMI_GIT_DIR does not look like a core checkout: ${params.dir}.`);
	return null;
}
async function resolveGlobalManager(params) {
	const runCommand = async (argv, options) => {
		const res = await runCommandWithTimeout(argv, options);
		return {
			stdout: res.stdout,
			stderr: res.stderr,
			code: res.code
		};
	};
	if (params.installKind === "package") {
		const detected = await detectGlobalInstallManagerForRoot(runCommand, params.root, params.timeoutMs);
		if (detected) return detected;
	}
	return await detectGlobalInstallManagerByPresence(runCommand, params.timeoutMs) ?? "npm";
}
async function tryWriteCompletionCache(root, jsonMode) {
	const binPath = path.join(root, "symi.mjs");
	if (!await pathExists(binPath)) return;
	const result = spawnSync(resolveNodeRunner(), [
		binPath,
		"completion",
		"--write-state"
	], {
		cwd: root,
		env: process.env,
		encoding: "utf-8"
	});
	if (result.error) {
		if (!jsonMode) defaultRuntime.log(theme.warn(`Completion cache update failed: ${String(result.error)}`));
		return;
	}
	if (result.status !== 0 && !jsonMode) {
		const stderr = (result.stderr ?? "").toString().trim();
		const detail = stderr ? ` (${stderr})` : "";
		defaultRuntime.log(theme.warn(`Completion cache update failed${detail}.`));
	}
}

//#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.log(JSON.stringify({
			update,
			channel: {
				value: channelInfo.channel,
				source: channelInfo.source,
				label: channelLabel,
				config: configChannel
			},
			availability: updateAvailability
		}, null, 2));
		return;
	}
	const tableWidth = Math.max(60, (process.stdout.columns ?? 120) - 1);
	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("Symi 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/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",
	"symi doctor entry": "Checking doctor entrypoint",
	"symi doctor": "Running doctor checks",
	"git rev-parse HEAD (after)": "Verifying update",
	"global update": "Updating via package manager",
	"global install": "Installing global package"
};
function getStepLabel(step) {
	return STEP_LABELS[step.name] ?? step.name;
}
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.log(JSON.stringify(result, null, 2));
		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)}`);
			}
		}
	}
	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 string is safe for embedding in a batch (cmd.exe) script. */
function isBatchSafe(value) {
	return /^[A-Za-z0-9 _\-().]+$/.test(value);
}
function resolveSystemdUnit(env) {
	const override = env.SYMI_SYSTEMD_UNIT?.trim();
	if (override) return override.endsWith(".service") ? override : `${override}.service`;
	return `${resolveGatewaySystemdServiceName(env.SYMI_PROFILE)}.service`;
}
function resolveLaunchdLabel(env) {
	const override = env.SYMI_LAUNCHD_LABEL?.trim();
	if (override) return override;
	return resolveGatewayLaunchAgentLabel(env.SYMI_PROFILE);
}
function resolveWindowsTaskName(env) {
	const override = env.SYMI_WINDOWS_TASK_NAME?.trim();
	if (override) return override;
	return resolveGatewayWindowsTaskName(env.SYMI_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) {
	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));
			filename = `symi-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
systemctl --user restart '${escaped}'
# Self-cleanup
rm -f "$0"
`;
		} else if (platform === "darwin") {
			const escaped = shellEscape(resolveLaunchdLabel(env));
			const uid = process.getuid ? process.getuid() : 501;
			filename = `symi-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
launchctl kickstart -k 'gui/${uid}/${escaped}'
# Self-cleanup
rm -f "$0"
`;
		} else if (platform === "win32") {
			const taskName = resolveWindowsTaskName(env);
			if (!isBatchSafe(taskName)) return null;
			filename = `symi-restart-${timestamp}.bat`;
			scriptContent = `@echo off
REM Standalone restart script — survives parent process termination.
REM Wait briefly to ensure file locks are released after update.
timeout /t 2 /nobreak >nul
schtasks /End /TN "${taskName}"
schtasks /Run /TN "${taskName}"
REM Self-cleanup
del "%~f0"
`;
		} 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 ? ["/c", scriptPath] : [scriptPath], {
		detached: true,
		stdio: "ignore"
	}).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 UPDATE_QUIPS = [
	"Leveled up! New skills unlocked. You're welcome.",
	"Fresh code, same symi. 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.",
	"Symi has evolved. Smarter, faster, better.",
	"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.";
}
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("symi 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 runCommand = async (argv, options) => {
		const res = await runCommandWithTimeout(argv, options);
		return {
			stdout: res.stdout,
			stderr: res.stderr,
			code: res.code
		};
	};
	const pkgRoot = await resolveGlobalPackageRoot(manager, runCommand, params.timeoutMs);
	const packageName = (pkgRoot ? await readPackageName(pkgRoot) : await readPackageName(params.root)) ?? DEFAULT_PACKAGE_NAME;
	const beforeVersion = pkgRoot ? await readPackageVersion(pkgRoot) : null;
	if (pkgRoot) await cleanupGlobalRenameDirs({
		globalRoot: path.dirname(pkgRoot),
		packageName
	});
	const steps = [await runUpdateStep({
		name: "global update",
		argv: globalInstallArgs(manager, `${packageName}@${params.tag}`),
		timeoutMs: params.timeoutMs,
		progress: params.progress
	})];
	let afterVersion = beforeVersion;
	if (pkgRoot) {
		afterVersion = await readPackageVersion(pkgRoot);
		const entryPath = path.join(pkgRoot, "dist", "entry.js");
		if (await pathExists(entryPath)) {
			const doctorStep = await runUpdateStep({
				name: `${CLI_NAME} doctor`,
				argv: [
					resolveNodeRunner(),
					entryPath,
					"doctor",
					"--non-interactive"
				],
				timeoutMs: params.timeoutMs,
				progress: params.progress
			});
			steps.push(doctorStep);
		}
	}
	const failedStep = steps.find((step) => step.exitCode !== 0);
	return {
		status: failedStep ? "error" : "ok",
		mode: manager,
		root: pkgRoot ?? params.root,
		reason: failedStep ? failedStep.name : void 0,
		before: { version: beforeVersion },
		after: { version: afterVersion },
		steps,
		durationMs: Date.now() - params.startedAt
	};
}
async function runGitUpdate(params) {
	const updateRoot = params.switchToGit ? resolveGitInstallDir() : params.root;
	const effectiveTimeout = params.timeoutMs ?? 20 * 6e4;
	const cloneStep = params.switchToGit ? await ensureGitCheckout({
		dir: updateRoot,
		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
	});
	const steps = [...cloneStep ? [cloneStep] : [], ...updateResult.steps];
	if (params.switchToGit && updateResult.status === "ok") {
		const installStep = await runUpdateStep({
			name: "global install",
			argv: globalInstallArgs(await resolveGlobalManager({
				root: params.root,
				installKind: params.installKind,
				timeoutMs: effectiveTimeout
			}), updateRoot),
			cwd: updateRoot,
			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;
	}
	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 syncResult = await syncPluginsForUpdateChannel({
		config: params.configSnapshot.config,
		channel: params.channel,
		workspaceDir: params.root,
		logger: pluginLogger
	});
	let pluginConfig = syncResult.config;
	const npmResult = await updateNpmInstalledPlugins({
		config: pluginConfig,
		skipIds: new Set(syncResult.summary.switchedToNpm),
		logger: pluginLogger
	});
	pluginConfig = npmResult.config;
	if (syncResult.changed || npmResult.changed) await writeConfigFile(pluginConfig);
	if (params.opts.json) return;
	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));
	}
}
async function maybeRestartService(params) {
	if (params.shouldRestart) {
		if (!params.opts.json) {
			defaultRuntime.log("");
			defaultRuntime.log(theme.heading("Restarting service..."));
		}
		try {
			let restarted = false;
			let restartInitiated = false;
			if (params.refreshServiceEnv) try {
				await runDaemonInstall({
					force: true,
					json: params.opts.json
				});
			} catch (err) {
				if (!params.opts.json) defaultRuntime.log(theme.warn(`Failed to refresh gateway service environment from updated install: ${String(err)}`));
			}
			if (params.restartScriptPath) {
				await runRestartScript(params.restartScriptPath);
				restartInitiated = true;
			} else restarted = await runDaemonRestart();
			if (!params.opts.json && restarted) {
				defaultRuntime.log(theme.success("Daemon restarted successfully."));
				defaultRuntime.log("");
				process.env.SYMI_UPDATE_IN_PROGRESS = "1";
				try {
					await doctorCommand(defaultRuntime, { nonInteractive: !(Boolean(process.stdin.isTTY) && !params.opts.json && params.opts.yes !== true) });
				} catch (err) {
					defaultRuntime.log(theme.warn(`Doctor failed: ${String(err)}`));
				} finally {
					delete process.env.SYMI_UPDATE_IN_PROGRESS;
				}
			}
			if (!params.opts.json && restartInitiated) {
				defaultRuntime.log(theme.success("Daemon restart initiated."));
				defaultRuntime.log(theme.muted(`Verify with \`${replaceCliName(formatCliCommand("symi gateway status"), CLI_NAME)}\` once the gateway is back.`));
				defaultRuntime.log("");
			}
		} 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("symi gateway restart"), CLI_NAME)}`));
			}
		}
		return;
	}
	if (!params.opts.json) {
		defaultRuntime.log("");
		if (params.result.mode === "npm" || params.result.mode === "pnpm") defaultRuntime.log(theme.muted(`Tip: Run \`${replaceCliName(formatCliCommand("symi doctor"), CLI_NAME)}\`, then \`${replaceCliName(formatCliCommand("symi gateway restart"), CLI_NAME)}\` to apply updates to a running gateway.`));
		else defaultRuntime.log(theme.muted(`Tip: Run \`${replaceCliName(formatCliCommand("symi gateway restart"), CLI_NAME)}\` to apply updates to a running gateway.`));
	}
}
async function updateCommand(opts) {
	suppressDeprecations();
	const timeoutMs = parseTimeoutMsOrExit(opts.timeout);
	const shouldRestart = opts.restart !== false;
	if (timeoutMs === null) return;
	const root = await resolveUpdateRoot();
	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 = configSnapshot.issues.map((issue) => `- ${issue.path}: ${issue.message}`);
		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" ? DEFAULT_GIT_CHANNEL : DEFAULT_PACKAGE_CHANNEL);
	const explicitTag = normalizeTag(opts.tag);
	let tag = explicitTag ?? channelToNpmTag(channel);
	if (updateInstallKind !== "git") {
		const currentVersion = switchToPackage ? null : await readPackageVersion(root);
		let fallbackToLatest = false;
		const targetVersion = explicitTag ? await resolveTargetVersion(tag, timeoutMs) : 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;
		if (!fallbackToLatest && currentVersion != null && (targetVersion == null || cmp != null && cmp > 0) && !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 ok = await confirm({
				message: stylePromptMessage(`Downgrading from ${currentVersion} to ${targetVersion ?? `${tag} (unknown)`} can break configuration. Continue?`),
				initialValue: false
			});
			if (isCancel(ok) || !ok) {
				if (!opts.json) defaultRuntime.log(theme.muted("Update cancelled."));
				defaultRuntime.exit(0);
				return;
			}
		}
	} else if (opts.tag && !opts.json) defaultRuntime.log(theme.muted("Note: --tag applies to npm installs only; git updates ignore it."));
	if (requestedChannel && configSnapshot.valid) {
		await writeConfigFile({
			...configSnapshot.config,
			update: {
				...configSnapshot.config.update,
				channel: requestedChannel
			}
		});
		if (!opts.json) defaultRuntime.log(theme.muted(`Update channel set to ${requestedChannel}.`));
	}
	const showProgress = !opts.json && process.stdout.isTTY;
	if (!opts.json) {
		defaultRuntime.log(theme.heading("Updating Symi..."));
		defaultRuntime.log("");
	}
	const { progress, stop } = createUpdateProgress(showProgress);
	const startedAt = Date.now();
	let restartScriptPath = null;
	let refreshGatewayServiceEnv = false;
	if (shouldRestart) try {
		if (await resolveGatewayService().isLoaded({ env: process.env })) {
			restartScriptPath = await prepareRestartScript(process.env);
			refreshGatewayServiceEnv = true;
		}
	} catch {}
	const result = switchToPackage ? await runPackageInstallUpdate({
		root,
		installKind,
		tag,
		timeoutMs: timeoutMs ?? 20 * 6e4,
		startedAt,
		progress
	}) : await runGitUpdate({
		root,
		switchToGit,
		installKind,
		timeoutMs,
		startedAt,
		progress,
		channel,
		tag,
		showProgress,
		opts,
		stop
	});
	stop();
	printResult(result, {
		...opts,
		hideSteps: showProgress
	});
	if (result.status === "error") {
		defaultRuntime.exit(1);
		return;
	}
	if (result.status === "skipped") {
		if (result.reason === "dirty") defaultRuntime.log(theme.warn("Skipped: working directory has uncommitted changes. Commit or stash them first."));
		if (result.reason === "not-git-install") {
			defaultRuntime.log(theme.warn(`Skipped: this Symi install isn't a git checkout, and the package manager couldn't be detected. Update via your package manager, then run \`${replaceCliName(formatCliCommand("symi doctor"), CLI_NAME)}\` and \`${replaceCliName(formatCliCommand("symi gateway restart"), CLI_NAME)}\`.`));
			defaultRuntime.log(theme.muted(`Examples: \`${replaceCliName("npm i -g symi@latest", CLI_NAME)}\` or \`${replaceCliName("pnpm add -g symi@latest", CLI_NAME)}\``));
		}
		defaultRuntime.exit(0);
		return;
	}
	await updatePluginsAfterCoreUpdate({
		root,
		channel,
		configSnapshot,
		opts
	});
	await tryWriteCompletionCache(root, Boolean(opts.json));
	await tryInstallShellCompletion({
		jsonMode: Boolean(opts.json),
		skipPrompt: Boolean(opts.yes)
	});
	await maybeRestartService({
		shouldRestart,
		result,
		opts,
		refreshServiceEnv: refreshGatewayServiceEnv,
		restartScriptPath
	});
	if (!opts.json) defaultRuntime.log(theme.muted(pickUpdateQuip()));
}

//#endregion
//#region src/cli/update-cli/wizard.ts
async function updateWizardCommand(opts = {}) {
	if (!process.stdin.isTTY) {
		defaultRuntime.error("Update wizard requires a TTY. Use `symi 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(`SYMI_GIT_DIR points at a non-git directory: ${gitDir}. Set SYMI_GIT_DIR to an empty folder or an symi checkout.`);
					defaultRuntime.exit(1);
					return;
				}
			}
			const ok = await confirm({
				message: stylePromptMessage(`Create a git checkout at ${gitDir}? (override via SYMI_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: Boolean(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) {
	const update = program.command("update").description("Update Symi 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("--channel <stable|beta|dev>", "Persist update channel (git + npm)").option("--tag <dist-tag|version>", "Override npm dist-tag or version for this update").option("--timeout <seconds>", "Timeout for each update step in seconds (default: 1200)").option("--yes", "Skip confirmation prompts (non-interactive)", false).addHelpText("after", () => {
		const fmtExamples = [
			["symi update", "Update a source checkout (git)"],
			["symi update --channel beta", "Switch to beta channel (git + npm)"],
			["symi update --channel dev", "Switch to dev channel (git + npm)"],
			["symi update --tag beta", "One-off update to a dist-tag or version"],
			["symi update --no-restart", "Update without restarting the service"],
			["symi update --json", "Output result as JSON"],
			["symi update --yes", "Non-interactive (accept downgrade prompts)"],
			["symi update wizard", "Interactive update wizard"],
			["symi --update", "Shorthand for symi update"]
		].map(([cmd, desc]) => `  ${theme.command(cmd)} ${theme.muted(`# ${desc}`)}`).join("\n");
		return `
${theme.heading("What this does:")}
  - Git checkouts: fetches, rebases, installs deps, builds, and runs doctor
  - npm installs: updates via detected package manager

${theme.heading("Switch channels:")}
  - Use --channel stable|beta|dev to persist the update channel in config
  - Run symi update status to see the active channel and source
  - Use --tag <dist-tag|version> for a one-off npm update without persisting

${theme.heading("Non-interactive:")}
  - Use --yes to accept downgrade prompts
  - Combine with --channel/--tag/--restart/--json/--timeout as needed

${theme.heading("Examples:")}
${fmtExamples}

${theme.heading("Notes:")}
  - 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.symi.ai/cli/update")}`;
	}).action(async (opts) => {
		try {
			await updateCommand({
				json: Boolean(opts.json),
				restart: Boolean(opts.restart),
				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: 1200)").addHelpText("after", `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/update", "docs.symi.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("Examples:")}\n${formatHelpExamples([
		["symi update status", "Show channel + version status."],
		["symi update status --json", "JSON output."],
		["symi update status --timeout 10", "Custom timeout."]
	])}\n\n${theme.heading("Notes:")}\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.symi.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 };