import { v as restoreTerminalState } from "./entry.js";
import "./auth-profiles-CgnoZiYS.js";
import { r as resolveCliName, t as formatCliCommand } from "./command-format-CRiwV99s.js";
import { v as DEFAULT_BOOTSTRAP_FILENAME } from "./agent-scope-Cezno7_M.js";
import { m as pathExists, v as resolveUserPath } from "./utils-CD6tCvSG.js";
import "./core-root-CmA71BTT.js";
import "./logger-BcqRk323.js";
import "./exec-CaapFZaD.js";
import "./registry-CBFkaKwt.js";
import "./github-copilot-token-DHTToceK.js";
import "./manifest-registry-DdFBL-mx.js";
import "./version-sf9dgjHP.js";
import "./dock-MGfYkqVd.js";
import "./tokens-RCFQ-amj.js";
import "./compact-DGr2hadh.js";
import "./accounts-DQj4GURA.js";
import "./plugins-D7VGnP8X.js";
import "./logging-JZEg5nDp.js";
import "./send-CVUi_VO-.js";
import "./send-B_LE3LuQ.js";
import "./with-timeout-B6VGlljS.js";
import "./deliver-DmWt0aVn.js";
import "./diagnostic-D0TTrgNC.js";
import "./accounts-F1jmiu3k.js";
import "./image-ops-DxLQocoR.js";
import "./send-DZcZ8m6m.js";
import "./pi-model-discovery-BMNFsJrD.js";
import "./message-channel-DelDwlJy.js";
import "./pi-embedded-helpers-Jygiu_rm.js";
import "./sandbox-DapwL3Y3.js";
import "./tool-catalog-DwAGTRaX.js";
import "./chrome-CNj5RXTP.js";
import "./tailscale-5K9XNlhO.js";
import "./tailnet-mjXbAxqf.js";
import "./ws-GlDBWD0H.js";
import "./auth-V2FS08vr.js";
import "./server-context-BF4RP1eP.js";
import "./frontmatter-B5GM2mXS.js";
import "./skills-CE-unP39.js";
import "./path-alias-guards-CNxRjVah.js";
import "./paths-BDDFj5Fw.js";
import "./redact-CC_d52A1.js";
import "./errors-DAcI6n_m.js";
import "./fs-safe-qdP8sV7U.js";
import "./proxy-env-B6UxsfXo.js";
import "./store-B5eeaWQa.js";
import "./ports-D8nInYfq.js";
import "./trash-CrF5N5Zh.js";
import "./server-middleware-BniDse6Q.js";
import "./sessions-CSzvEM0w.js";
import "./accounts-BMuunqOS.js";
import "./paths-COzEpwhO.js";
import "./chat-envelope-BUdriZB0.js";
import "./tool-images-Dtu-s5JK.js";
import "./thinking-BYXvmTqG.js";
import "./models-config-BVwpS5BT.js";
import "./exec-approvals-allowlist-DLolanQl.js";
import "./exec-safe-bin-runtime-policy-yz_-h-RQ.js";
import "./model-catalog-BqfN8gX9.js";
import "./fetch-syFYVRt3.js";
import "./audio-transcription-runner-BVW6o6TV.js";
import "./fetch-guard-CcDaj5My.js";
import "./image-D4aFv0X1.js";
import "./tool-display-B_FNOYTS.js";
import "./api-key-rotation-DLAEpbFc.js";
import "./proxy-fetch-TWpl-yhl.js";
import "./ir-BCFPWtL_.js";
import "./render-C9LkRUhd.js";
import "./target-errors-Ci3M951J.js";
import "./commands-CmZqo7n4.js";
import "./commands-registry-CaALqeCJ.js";
import "./session-cost-usage-WqkA7nWJ.js";
import "./sqlite-BkaDx2XJ.js";
import "./client-B8ehJjd1.js";
import "./call-BAwuZELF.js";
import "./pairing-token-01jjmach.js";
import "./fetch-1d1K1Sbw.js";
import "./pairing-store-Da6gxB-g.js";
import "./exec-approvals-B2nfDOCa.js";
import "./nodes-screen-D9eByp18.js";
import "./system-run-command-C9eoW3Ze.js";
import "./session-utils-CfyCGZX2.js";
import "./skill-commands-B4itYgGX.js";
import "./pi-tools.policy-vXZNXpv0.js";
import "./workspace-dirs-CEAXZCb7.js";
import "./channel-activity-CtGt6xvS.js";
import "./tables-gNfYyl-h.js";
import "./server-lifecycle-BH1bn6N4.js";
import "./stagger-C4U8O7GM.js";
import "./channel-selection-CccMG0Tp.js";
import "./plugin-auto-enable-BG8smK-4.js";
import "./send-CipSFPME.js";
import "./outbound-attachment-Bx3xWzM0.js";
import "./delivery-queue-BU5OeQMD.js";
import "./send-Dp0h-d5B.js";
import "./proxy-Dgwoliym.js";
import "./timeouts-3s3tygPw.js";
import "./runtime-config-collectors-C7Cs7evp.js";
import "./command-secret-targets-AV-RDTsr.js";
import { _ as resolveControlUiLinks, f as openUrl, h as probeGatewayReachable, i as detectBrowserOpenSupport, o as formatControlUiSshHint, x as waitForGatewayReachable } from "./onboard-helpers-DePmX0qT.js";
import "./prompt-style-Bi8LEJM5.js";
import "./pairing-labels-DL4tko6o.js";
import "./memory-cli-BEJgeUeO.js";
import "./manager-C7W4Rpg2.js";
import "./links-C87Xouo6.js";
import "./cli-utils-DWSfnwCw.js";
import "./help-format-Cwn7EEhh.js";
import "./progress-DiO7soys.js";
import "./note-BUcnHAZz.js";
import { r as installCompletion } from "./completion-cli-CFH815US.js";
import "./register.subclis-CDvfGbJM.js";
import "./command-registry-DVdwLzHN.js";
import "./program-context-COiVfSLD.js";
import { n as gatewayInstallErrorHint, t as buildGatewayInstallPlan } from "./daemon-install-helpers-DTPc4NMd.js";
import "./runtime-guard-kCSrmbox.js";
import { n as GATEWAY_DAEMON_RUNTIME_OPTIONS, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-mYDSc4SR.js";
import { t as resolveGatewayInstallToken } from "./gateway-install-token-DucYO_m0.js";
import { r as isSystemdUserServiceAvailable } from "./systemd-CfCex-1t.js";
import { t as resolveGatewayService } from "./service-Bew1C9AA.js";
import "./resolve-configured-secret-input-string-CUXB8Sxr.js";
import { r as healthCommand } from "./health-DhLRfOA0.js";
import { t as ensureControlUiAssetsBuilt } from "./control-ui-assets-CX1Lq4PF.js";
import { t as resolveOnboardingSecretInputString } from "./onboarding.secret-input-D1HVfJYL.js";
import { t as formatHealthCheckFailure } from "./health-format-BM1-cBqH.js";
import { r as ensureCompletionCacheExists, t as checkShellCompletionStatus } from "./doctor-completion-8OX5MgLL.js";
import { t as runTui } from "./tui-D1yVmGy_.js";
import os from "node:os";
import path from "node:path";
import fs from "node:fs/promises";

//#region src/wizard/onboarding.completion.ts
async function resolveProfileHint(shell) {
	const home = process.env.HOME || os.homedir();
	if (shell === "zsh") return "~/.zshrc";
	if (shell === "bash") return await pathExists(path.join(home, ".bashrc")) ? "~/.bashrc" : "~/.bash_profile";
	if (shell === "fish") return "~/.config/fish/config.fish";
	return "$PROFILE";
}
function formatReloadHint(shell, profileHint) {
	if (shell === "powershell") return "Restart your shell (or reload your PowerShell profile).";
	return `Restart your shell or run: source ${profileHint}`;
}
async function setupOnboardingShellCompletion(params) {
	const deps = {
		resolveCliName,
		checkShellCompletionStatus,
		ensureCompletionCacheExists,
		installCompletion,
		...params.deps
	};
	const cliName = deps.resolveCliName();
	const completionStatus = await deps.checkShellCompletionStatus(cliName);
	if (completionStatus.usesSlowPattern) {
		if (await deps.ensureCompletionCacheExists(cliName)) await deps.installCompletion(completionStatus.shell, true, cliName);
		return;
	}
	if (completionStatus.profileInstalled && !completionStatus.cacheExists) {
		await deps.ensureCompletionCacheExists(cliName);
		return;
	}
	if (!completionStatus.profileInstalled) {
		if (!(params.flow === "quickstart" ? true : await params.prompter.confirm({
			message: `Enable ${completionStatus.shell} shell completion for ${cliName}?`,
			initialValue: true
		}))) return;
		if (!await deps.ensureCompletionCacheExists(cliName)) {
			await params.prompter.note(`Failed to generate completion cache. Run \`${cliName} completion --install\` later.`, "Shell completion");
			return;
		}
		await deps.installCompletion(completionStatus.shell, true, cliName);
		const profileHint = await resolveProfileHint(completionStatus.shell);
		await params.prompter.note(`Shell completion installed. ${formatReloadHint(completionStatus.shell, profileHint)}`, "Shell completion");
	}
}

//#endregion
//#region src/wizard/onboarding.finalize.ts
async function finalizeOnboardingWizard(options) {
	const { flow, opts, baseConfig, nextConfig, settings, prompter, runtime } = options;
	const withWizardProgress = async (label, options, work) => {
		const progress = prompter.progress(label);
		try {
			return await work(progress);
		} finally {
			progress.stop(options.doneMessage);
		}
	};
	const systemdAvailable = process.platform === "linux" ? await isSystemdUserServiceAvailable() : true;
	if (process.platform === "linux" && !systemdAvailable) await prompter.note("Systemd user services are unavailable. Skipping lingering checks and service install.", "Systemd");
	if (process.platform === "linux" && systemdAvailable) {
		const { ensureSystemdUserLingerInteractive } = await import("./systemd-linger-DNH6yR1i.js").then((n) => n.r);
		await ensureSystemdUserLingerInteractive({
			runtime,
			prompter: {
				confirm: prompter.confirm,
				note: prompter.note
			},
			reason: "Linux installs use a systemd user service by default. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.",
			requireConfirm: false
		});
	}
	const explicitInstallDaemon = typeof opts.installDaemon === "boolean" ? opts.installDaemon : void 0;
	let installDaemon;
	if (explicitInstallDaemon !== void 0) installDaemon = explicitInstallDaemon;
	else if (process.platform === "linux" && !systemdAvailable) installDaemon = false;
	else if (flow === "quickstart") installDaemon = true;
	else installDaemon = await prompter.confirm({
		message: "Install Gateway service (recommended)",
		initialValue: true
	});
	if (process.platform === "linux" && !systemdAvailable && installDaemon) {
		await prompter.note("Systemd user services are unavailable; skipping service install. Use your container supervisor or `docker compose up -d`.", "Gateway service");
		installDaemon = false;
	}
	if (installDaemon) {
		const daemonRuntime = flow === "quickstart" ? DEFAULT_GATEWAY_DAEMON_RUNTIME : await prompter.select({
			message: "Gateway service runtime",
			options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
			initialValue: opts.daemonRuntime ?? DEFAULT_GATEWAY_DAEMON_RUNTIME
		});
		if (flow === "quickstart") await prompter.note("QuickStart uses Node for the Gateway service (stable + supported).", "Gateway service runtime");
		const service = resolveGatewayService();
		const loaded = await service.isLoaded({ env: process.env });
		if (loaded) {
			const action = await prompter.select({
				message: "Gateway service already installed",
				options: [
					{
						value: "restart",
						label: "Restart"
					},
					{
						value: "reinstall",
						label: "Reinstall"
					},
					{
						value: "skip",
						label: "Skip"
					}
				]
			});
			if (action === "restart") await withWizardProgress("Gateway service", { doneMessage: "Gateway service restarted." }, async (progress) => {
				progress.update("Restarting Gateway service…");
				await service.restart({
					env: process.env,
					stdout: process.stdout
				});
			});
			else if (action === "reinstall") await withWizardProgress("Gateway service", { doneMessage: "Gateway service uninstalled." }, async (progress) => {
				progress.update("Uninstalling Gateway service…");
				await service.uninstall({
					env: process.env,
					stdout: process.stdout
				});
			});
		}
		if (!loaded || loaded && !await service.isLoaded({ env: process.env })) {
			const progress = prompter.progress("Gateway service");
			let installError = null;
			try {
				progress.update("Preparing Gateway service…");
				const tokenResolution = await resolveGatewayInstallToken({
					config: nextConfig,
					env: process.env
				});
				for (const warning of tokenResolution.warnings) await prompter.note(warning, "Gateway service");
				if (tokenResolution.unavailableReason) installError = [
					"Gateway install blocked:",
					tokenResolution.unavailableReason,
					"Fix gateway auth config/token input and rerun onboarding."
				].join(" ");
				else {
					const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
						env: process.env,
						port: settings.port,
						token: tokenResolution.token,
						runtime: daemonRuntime,
						warn: (message, title) => prompter.note(message, title),
						config: nextConfig
					});
					progress.update("Installing Gateway service…");
					await service.install({
						env: process.env,
						stdout: process.stdout,
						programArguments,
						workingDirectory,
						environment
					});
				}
			} catch (err) {
				installError = err instanceof Error ? err.message : String(err);
			} finally {
				progress.stop(installError ? "Gateway service install failed." : "Gateway service installed.");
			}
			if (installError) {
				await prompter.note(`Gateway service install failed: ${installError}`, "Gateway");
				await prompter.note(gatewayInstallErrorHint(), "Gateway");
			}
		}
	}
	if (!opts.skipHealth) {
		await waitForGatewayReachable({
			url: resolveControlUiLinks({
				bind: nextConfig.gateway?.bind ?? "loopback",
				port: settings.port,
				customBindHost: nextConfig.gateway?.customBindHost,
				basePath: void 0
			}).wsUrl,
			token: settings.gatewayToken,
			deadlineMs: 15e3
		});
		try {
			await healthCommand({
				json: false,
				timeoutMs: 1e4
			}, runtime);
		} catch (err) {
			runtime.error(formatHealthCheckFailure(err));
			await prompter.note([
				"Docs:",
				"https://docs.gensparx.com/gateway/health",
				"https://docs.gensparx.com/gateway/troubleshooting"
			].join("\n"), "Health check help");
		}
	}
	const controlUiEnabled = nextConfig.gateway?.controlUi?.enabled ?? baseConfig.gateway?.controlUi?.enabled ?? true;
	if (!opts.skipUi && controlUiEnabled) {
		const controlUiAssets = await ensureControlUiAssetsBuilt(runtime);
		if (!controlUiAssets.ok && controlUiAssets.message) runtime.error(controlUiAssets.message);
	}
	await prompter.note([
		"Add nodes for extra features:",
		"- macOS app (system + notifications)",
		"- iOS app (camera/canvas)",
		"- Android app (camera/canvas)"
	].join("\n"), "Optional apps");
	const controlUiBasePath = nextConfig.gateway?.controlUi?.basePath ?? baseConfig.gateway?.controlUi?.basePath;
	const links = resolveControlUiLinks({
		bind: settings.bind,
		port: settings.port,
		customBindHost: settings.customBindHost,
		basePath: controlUiBasePath
	});
	const authedUrl = settings.authMode === "token" && settings.gatewayToken ? `${links.httpUrl}#token=${encodeURIComponent(settings.gatewayToken)}` : links.httpUrl;
	let resolvedGatewayPassword = "";
	if (settings.authMode === "password") try {
		resolvedGatewayPassword = await resolveOnboardingSecretInputString({
			config: nextConfig,
			value: nextConfig.gateway?.auth?.password,
			path: "gateway.auth.password",
			env: process.env
		}) ?? "";
	} catch (error) {
		await prompter.note(["Could not resolve gateway.auth.password SecretRef for onboarding auth.", error instanceof Error ? error.message : String(error)].join("\n"), "Gateway auth");
	}
	const gatewayProbe = await probeGatewayReachable({
		url: links.wsUrl,
		token: settings.authMode === "token" ? settings.gatewayToken : void 0,
		password: settings.authMode === "password" ? resolvedGatewayPassword : ""
	});
	const gatewayStatusLine = gatewayProbe.ok ? "Gateway: reachable" : `Gateway: not detected${gatewayProbe.detail ? ` (${gatewayProbe.detail})` : ""}`;
	const bootstrapPath = path.join(resolveUserPath(options.workspaceDir), DEFAULT_BOOTSTRAP_FILENAME);
	const hasBootstrap = await fs.access(bootstrapPath).then(() => true).catch(() => false);
	await prompter.note([
		`Web UI: ${links.httpUrl}`,
		settings.authMode === "token" && settings.gatewayToken ? `Web UI (with token): ${authedUrl}` : void 0,
		`Gateway WS: ${links.wsUrl}`,
		gatewayStatusLine,
		"Docs: https://docs.gensparx.com/web/control-ui"
	].filter(Boolean).join("\n"), "Control UI");
	let controlUiOpened = false;
	let controlUiOpenHint;
	let hatchChoice = null;
	let launchedTui = false;
	if (!opts.skipUi && gatewayProbe.ok) {
		if (hasBootstrap) await prompter.note([
			"This is the defining action that makes your agent you.",
			"Please take your time.",
			"The more you tell it, the better the experience will be.",
			"We will send: \"Wake up, my friend!\""
		].join("\n"), "Start TUI (best option!)");
		await prompter.note([
			"Gateway token: shared auth for the Gateway + Control UI.",
			"Stored in: ~/.gensparx/gensparx.json (gateway.auth.token) or GENSPARX_GATEWAY_TOKEN.",
			`View token: ${formatCliCommand("gensparx config get gateway.auth.token")}`,
			`Generate token: ${formatCliCommand("gensparx doctor --generate-gateway-token")}`,
			"Web UI stores a copy in this browser's localStorage (gensparx.control.settings.v1).",
			`Open the dashboard anytime: ${formatCliCommand("gensparx dashboard --no-open")}`,
			"If prompted: paste the token into Control UI settings (or use the tokenized dashboard URL)."
		].join("\n"), "Token");
		hatchChoice = await prompter.select({
			message: "How do you want to hatch your bot?",
			options: [
				{
					value: "tui",
					label: "Hatch in TUI (recommended)"
				},
				{
					value: "web",
					label: "Open the Web UI"
				},
				{
					value: "later",
					label: "Do this later"
				}
			],
			initialValue: "tui"
		});
		if (hatchChoice === "tui") {
			restoreTerminalState("pre-onboarding tui", { resumeStdinIfPaused: true });
			await runTui({
				url: links.wsUrl,
				token: settings.authMode === "token" ? settings.gatewayToken : void 0,
				password: settings.authMode === "password" ? resolvedGatewayPassword : "",
				deliver: false,
				message: hasBootstrap ? "Wake up, my friend!" : void 0
			});
			launchedTui = true;
		} else if (hatchChoice === "web") {
			if ((await detectBrowserOpenSupport()).ok) {
				controlUiOpened = await openUrl(authedUrl);
				if (!controlUiOpened) controlUiOpenHint = formatControlUiSshHint({
					port: settings.port,
					basePath: controlUiBasePath,
					token: settings.authMode === "token" ? settings.gatewayToken : void 0
				});
			} else controlUiOpenHint = formatControlUiSshHint({
				port: settings.port,
				basePath: controlUiBasePath,
				token: settings.authMode === "token" ? settings.gatewayToken : void 0
			});
			await prompter.note([
				`Dashboard link (with token): ${authedUrl}`,
				controlUiOpened ? "Opened in your browser. Keep that tab to control Gensparx." : "Copy/paste this URL in a browser on this machine to control Gensparx.",
				controlUiOpenHint
			].filter(Boolean).join("\n"), "Dashboard ready");
		} else await prompter.note(`When you're ready: ${formatCliCommand("gensparx dashboard --no-open")}`, "Later");
	} else if (opts.skipUi) await prompter.note("Skipping Control UI/TUI prompts.", "Control UI");
	await prompter.note(["Back up your agent workspace.", "Docs: https://docs.gensparx.com/concepts/agent-workspace"].join("\n"), "Workspace backup");
	await prompter.note("Running agents on your computer is risky — harden your setup: https://docs.gensparx.com/security", "Security");
	await setupOnboardingShellCompletion({
		flow,
		prompter
	});
	if (!opts.skipUi && settings.authMode === "token" && Boolean(settings.gatewayToken) && hatchChoice === null) {
		if ((await detectBrowserOpenSupport()).ok) {
			controlUiOpened = await openUrl(authedUrl);
			if (!controlUiOpened) controlUiOpenHint = formatControlUiSshHint({
				port: settings.port,
				basePath: controlUiBasePath,
				token: settings.gatewayToken
			});
		} else controlUiOpenHint = formatControlUiSshHint({
			port: settings.port,
			basePath: controlUiBasePath,
			token: settings.gatewayToken
		});
		await prompter.note([
			`Dashboard link (with token): ${authedUrl}`,
			controlUiOpened ? "Opened in your browser. Keep that tab to control Gensparx." : "Copy/paste this URL in a browser on this machine to control Gensparx.",
			controlUiOpenHint
		].filter(Boolean).join("\n"), "Dashboard ready");
	}
	const webSearchProvider = nextConfig.tools?.web?.search?.provider ?? "brave";
	const webSearchKey = webSearchProvider === "perplexity" ? (nextConfig.tools?.web?.search?.perplexity?.apiKey ?? "").trim() : (nextConfig.tools?.web?.search?.apiKey ?? "").trim();
	const webSearchEnv = webSearchProvider === "perplexity" ? (process.env.PERPLEXITY_API_KEY ?? "").trim() : (process.env.BRAVE_API_KEY ?? "").trim();
	const hasWebSearchKey = Boolean(webSearchKey || webSearchEnv);
	await prompter.note(hasWebSearchKey ? [
		"Web search is enabled, so your agent can look things up online when needed.",
		"",
		`Provider: ${webSearchProvider === "perplexity" ? "Perplexity Search" : "Brave Search"}`,
		webSearchKey ? `API key: stored in config (tools.web.search.${webSearchProvider === "perplexity" ? "perplexity.apiKey" : "apiKey"}).` : `API key: provided via ${webSearchProvider === "perplexity" ? "PERPLEXITY_API_KEY" : "BRAVE_API_KEY"} env var (Gateway environment).`,
		"Docs: https://docs.gensparx.com/tools/web"
	].join("\n") : [
		"To enable web search, your agent will need an API key for either Perplexity Search or Brave Search.",
		"",
		"Set it up interactively:",
		`- Run: ${formatCliCommand("gensparx configure --section web")}`,
		"- Choose a provider and paste your API key",
		"",
		"Alternative: set PERPLEXITY_API_KEY or BRAVE_API_KEY in the Gateway environment (no config changes).",
		"Docs: https://docs.gensparx.com/tools/web"
	].join("\n"), "Web search (optional)");
	await prompter.note("What now: https://gensparx.com/showcase (\"What People Are Building\").", "What now");
	await prompter.outro(controlUiOpened ? "Onboarding complete. Dashboard opened; keep that tab to control Gensparx." : "Onboarding complete. Use the dashboard link above to control Gensparx.");
	return { launchedTui };
}

//#endregion
export { finalizeOnboardingWizard };