import { Ba as normalizeOptionalSecretInput, Cu as formatCliCommand, Ii as resolveApiKeyForProfile, Ji as resolveDefaultSecretProviderAlias, Oa as loadPluginManifestRegistry, Pr as normalizeProviderId, Qt as readConfigFileSnapshot, Va as normalizeSecretInput, _n as parseDurationMs, di as resolveEnvApiKey, fa as upsertAuthProfile, ka as assertSupportedRuntime, ki as resolveAuthProfileOrder, ma as ensureAuthProfileStore, tn as writeConfigFile } from "./env-Dlz8aQHP.js";
import { x as resolveUserPath } from "./agent-paths-DUHGyU1s.js";
import { A as waitForGatewayReachable, E as resolveControlUiLinks, T as randomToken, d as DEFAULT_WORKSPACE, f as applyWizardMetadata, h as ensureWorkspaceAndSessions, s as resolvePluginProviders, v as handleOnboardingRepair } from "./model-catalog-B2mRe6cZ.js";
import { A as defaultRuntime, gt as resolveGatewayPort, j as restoreTerminalState } from "./entry.js";
import { a as readWalletProviderRegistry, f as setWalletProvidersEnabled, t as WALLET_PROVIDER_IDS } from "./wallet-provider-registry-CFNtQ2ZR.js";
import { or as clearDeviceAuthStore } from "./call-CjHZhgQk.js";
import { r as isGatewayDaemonRuntime, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-DLrkpkSD.js";
import { a as resolveHostedOnboardingGatewayStartupMode, n as gatewayInstallErrorHint, t as buildGatewayInstallPlan } from "./daemon-install-helpers-CzpeF_Bc.js";
import { r as isSystemdUserServiceAvailable } from "./systemd-7bMkfZjg.js";
import { t as resolveGatewayService } from "./service-CnO5S7Pz.js";
import { d as resolveCustomProviderId, l as parseNonInteractiveCustomApiFlags, o as CustomApiError, s as applyCustomApiConfig } from "./ipv4-Citn8Cno.js";
import { i as healthCommand } from "./health-C_g99tp_.js";
import { $ as applyLitellmConfig, At as validateAnthropicSetupToken, B as applyMistralConfig, Ct as setXaiApiKey, Dt as MINIMAX_HIGHSPEED_MODEL_ID, Et as MINIMAX_DEFAULT_MODEL_ID, F as applyMinimaxApiConfig, Ft as resolveManifestProviderAuthChoice, G as applyQwenCodingPlanConfig, H as applyMoonshotConfigCn, I as applyMinimaxApiConfigCn, J as applyTogetherConfig, K as applyQwenConfig, L as applyAuthProfileConfig$1, M as detectZaiEndpoint, Mt as normalizeSecretInputModeInput, N as applyGoogleGeminiModelDefault, P as applyOpencodeZenConfig, Pt as resolveManifestDeprecatedProviderAuthChoice, Q as applyZaiConfig, R as applyHuggingfaceConfig, St as setVolcengineApiKey, Tt as setZaiApiKey, U as applyOpenrouterConfig, V as applyMoonshotConfig, W as applyQianfanConfig, X as applyXaiConfig, Y as applyVeniceConfig, Z as applyXiaomiConfig, _t as setQwenCodingPlanApiKey, at as setGeminiApiKey, bt as setVeniceApiKey, c as applyDefaultModel, ct as setLitellmApiKey, d as resolveProviderMatch, dt as setMoonshotApiKey, et as applyCloudflareAiGatewayConfig, ft as setOpenaiApiKey, gt as setQwenApiKey, ht as setQianfanApiKey, i as applyOpenAIConfig, it as setCloudflareAiGatewayConfig, kt as buildTokenProfileId, l as mergeConfigPatch, lt as setMinimaxApiKey, m as applyPrimaryModel, mt as setOpenrouterApiKey, nt as setAnthropicApiKey, o as applyAuthProfileConfig, ot as setHuggingfaceApiKey, pt as setOpencodeZenApiKey, q as applySyntheticConfig, rt as setByteplusApiKey, s as buildApiKeyCredential, st as setKimiCodingApiKey, tt as applyVercelAiGatewayConfig, u as pickAuthMethod, ut as setMistralApiKey, vt as setSyntheticApiKey, wt as setXiaomiApiKey, xt as setVercelAiGatewayApiKey, yt as setTogetherApiKey, z as applyKimiCodeConfig } from "./auth-choice-DlcbJgp_.js";
import { a as normalizeLegacyOnboardAuthChoice, i as isDeprecatedAuthChoice, r as resolveOnboardProviderAuthFlags } from "./auth-choice-prompt-CcOEzXoi.js";
import { n as logConfigUpdated } from "./logging-B1pB3RkW.js";
import { a as applyRecommendedInternalHooks, i as isHostedSecurityCapableSession, n as applyHostingSecurity, o as applyOnboardingLocalWorkspaceConfig, r as configureFederationForOnboarding, t as runOnboardingWizard } from "./onboarding-DgTB_zq7.js";
import { t as WizardCancelledError } from "./prompts-DdS4bZNt.js";
import { t as createClackPrompter } from "./clack-prompter-CZlDqO1z.js";
import { n as ensureSystemdUserLingerNonInteractive } from "./systemd-linger-CAPmfIid.js";
import { t as formatHealthCheckFailure } from "./health-format-CFeARHgA.js";

//#region src/commands/onboard-interactive.ts
async function runInteractiveOnboarding(opts, runtime = defaultRuntime) {
	const prompter = createClackPrompter();
	let exitCode = null;
	try {
		await runOnboardingWizard(opts, runtime, prompter);
	} catch (err) {
		if (err instanceof WizardCancelledError) {
			exitCode = 1;
			return;
		}
		throw err;
	} finally {
		restoreTerminalState("onboarding finish", { resumeStdinIfPaused: false });
		if (exitCode !== null) runtime.exit(exitCode);
	}
}

//#endregion
//#region src/commands/onboard-non-interactive/local/auth-choice-inference.ts
function hasStringValue(value) {
	return typeof value === "string" ? value.trim().length > 0 : Boolean(value);
}
function inferAuthChoiceFromFlags(opts) {
	const matches = resolveOnboardProviderAuthFlags().filter(({ optionKey }) => hasStringValue(opts[optionKey])).map((flag) => ({
		optionKey: String(flag.optionKey),
		authChoice: flag.authChoice,
		label: flag.cliFlag
	}));
	if (hasStringValue(opts.customBaseUrl) || hasStringValue(opts.customModelId) || hasStringValue(opts.customApiKey)) matches.push({
		optionKey: "customBaseUrl",
		authChoice: "custom-api-key",
		label: "--custom-base-url/--custom-model-id/--custom-api-key"
	});
	return {
		choice: matches[0]?.authChoice,
		matches
	};
}

//#endregion
//#region src/commands/onboard-non-interactive/api-keys.ts
function parseEnvVarNameFromSourceLabel(source) {
	if (!source) return;
	return /^(?:shell env: |env: )([A-Z][A-Z0-9_]*)$/.exec(source.trim())?.[1];
}
async function resolveApiKeyFromProfiles(params) {
	const store = ensureAuthProfileStore(params.agentDir);
	const order = resolveAuthProfileOrder({
		cfg: params.cfg,
		store,
		provider: params.provider
	});
	for (const profileId of order) {
		if (store.profiles[profileId]?.type !== "api_key") continue;
		const resolved = await resolveApiKeyForProfile({
			cfg: params.cfg,
			store,
			profileId,
			agentDir: params.agentDir
		});
		if (resolved?.apiKey) return resolved.apiKey;
	}
	return null;
}
async function resolveNonInteractiveApiKey(params) {
	const flagKey = normalizeOptionalSecretInput(params.flagValue);
	const envResolved = resolveEnvApiKey(params.provider);
	const explicitEnvVar = params.envVarName?.trim();
	const explicitEnvKey = explicitEnvVar ? normalizeOptionalSecretInput(process.env[explicitEnvVar]) : void 0;
	const resolvedEnvKey = envResolved?.apiKey ?? explicitEnvKey;
	const resolvedEnvVarName = parseEnvVarNameFromSourceLabel(envResolved?.source) ?? explicitEnvVar;
	if (params.secretInputMode === "ref") {
		if (!resolvedEnvKey && flagKey) {
			params.runtime.error([`${params.flagName} cannot be used with --secret-input-mode ref unless ${params.envVar} is set in env.`, `Set ${params.envVar} in env and omit ${params.flagName}, or use --secret-input-mode plaintext.`].join("\n"));
			params.runtime.exit(1);
			return null;
		}
		if (resolvedEnvKey) {
			if (!resolvedEnvVarName) {
				params.runtime.error([`--secret-input-mode ref requires an explicit environment variable for provider "${params.provider}".`, `Set ${params.envVar} in env and retry, or use --secret-input-mode plaintext.`].join("\n"));
				params.runtime.exit(1);
				return null;
			}
			return {
				key: resolvedEnvKey,
				source: "env",
				envVarName: resolvedEnvVarName
			};
		}
	}
	if (flagKey) return {
		key: flagKey,
		source: "flag"
	};
	if (resolvedEnvKey) return {
		key: resolvedEnvKey,
		source: "env",
		envVarName: resolvedEnvVarName
	};
	if (params.allowProfile ?? true) {
		const profileKey = await resolveApiKeyFromProfiles({
			provider: params.provider,
			cfg: params.cfg,
			agentDir: params.agentDir
		});
		if (profileKey) return {
			key: profileKey,
			source: "profile"
		};
	}
	if (params.required === false) return null;
	const profileHint = params.allowProfile === false ? "" : `, or existing ${params.provider} API-key profile`;
	params.runtime.error(`Missing ${params.flagName} (or ${params.envVar} in env${profileHint}).`);
	params.runtime.exit(1);
	return null;
}

//#endregion
//#region src/commands/onboard-non-interactive/local/auth-choice.plugin-provider.ts
function resolveStoredSecretInput(params) {
	if (params.secretInputMode !== "ref") return {
		ok: true,
		value: params.resolved.key
	};
	if (params.resolved.source !== "env") return {
		ok: true,
		value: params.resolved.key
	};
	if (!params.resolved.envVarName) return {
		ok: false,
		error: [`Unable to determine which environment variable to store as a ref for provider "${params.authChoice}".`, `Set ${params.envVarLabel} in env and retry, or use --secret-input-mode plaintext.`].join("\n")
	};
	return {
		ok: true,
		value: {
			source: "env",
			provider: resolveDefaultSecretProviderAlias(params.baseConfig, "env", { preferFirstProviderForSource: true }),
			id: params.resolved.envVarName
		}
	};
}
function resolvePluginApiKeyEnvVarNames(params) {
	const envVars = loadPluginManifestRegistry({ config: params.config }).plugins.find((plugin) => plugin.id === params.pluginId)?.providerAuthEnvVars?.[params.providerId]?.filter((entry) => entry.trim().length > 0) ?? [];
	const populatedEnvVar = envVars.find((name) => {
		const value = process.env[name];
		return typeof value === "string" && value.trim().length > 0;
	});
	return {
		envVarLabel: envVars.length > 0 ? envVars.join(" or ") : "provider API key env var",
		...populatedEnvVar ?? envVars[0] ? { envVarName: populatedEnvVar ?? envVars[0] } : {}
	};
}
async function applyNonInteractivePluginProviderApiKeyChoice(params) {
	const manifestChoice = resolveManifestProviderAuthChoice(params.authChoice, {
		config: params.nextConfig,
		includeUntrustedWorkspacePlugins: false
	}) ?? resolveManifestDeprecatedProviderAuthChoice(params.authChoice, {
		config: params.nextConfig,
		includeUntrustedWorkspacePlugins: false
	});
	if (!manifestChoice) return;
	const provider = resolveProviderMatch(resolvePluginProviders({ config: params.nextConfig }), manifestChoice.providerId);
	if (!provider) {
		params.runtime.error(`Plugin auth provider "${manifestChoice.providerId}" is not available for non-interactive onboarding.`);
		params.runtime.exit(1);
		return null;
	}
	const method = pickAuthMethod(provider, manifestChoice.methodId);
	if (!method) {
		params.runtime.error(`Plugin auth method "${manifestChoice.methodId}" is not available for provider "${provider.id}".`);
		params.runtime.exit(1);
		return null;
	}
	if (method.kind !== "api_key") {
		params.runtime.error([
			`Plugin auth choice "${manifestChoice.choiceId}" uses ${method.kind} auth.`,
			"Non-interactive onboarding currently supports only manifest-driven API key methods.",
			"Use interactive onboarding/configure for OAuth or device flows."
		].join("\n"));
		params.runtime.exit(1);
		return null;
	}
	const flagValue = manifestChoice.optionKey && typeof params.opts[manifestChoice.optionKey] === "string" ? params.opts[manifestChoice.optionKey] : void 0;
	const { envVarLabel, envVarName } = resolvePluginApiKeyEnvVarNames({
		pluginId: manifestChoice.pluginId,
		providerId: manifestChoice.providerId,
		config: params.nextConfig
	});
	const resolved = await resolveNonInteractiveApiKey({
		provider: provider.id,
		cfg: params.baseConfig,
		flagValue,
		flagName: manifestChoice.cliFlag ?? `--auth-choice ${manifestChoice.choiceId}`,
		envVar: envVarLabel,
		envVarName,
		runtime: params.runtime,
		secretInputMode: params.secretInputMode
	});
	if (!resolved) return null;
	const storedSecretInput = resolveStoredSecretInput({
		resolved,
		authChoice: params.authChoice,
		baseConfig: params.baseConfig,
		secretInputMode: params.secretInputMode,
		envVarLabel
	});
	if (!storedSecretInput.ok) {
		params.runtime.error(storedSecretInput.error);
		params.runtime.exit(1);
		return null;
	}
	const profileId = `${provider.id}:default`;
	upsertAuthProfile({
		profileId,
		credential: buildApiKeyCredential(provider.id, storedSecretInput.value)
	});
	let nextConfig = applyAuthProfileConfig(params.nextConfig, {
		profileId,
		provider: provider.id,
		mode: "api_key"
	});
	if (provider.models) {
		nextConfig = mergeConfigPatch(nextConfig, { models: { providers: { [provider.id]: {
			...provider.models,
			apiKey: storedSecretInput.value,
			auth: provider.models.auth ?? "api-key"
		} } } });
		const defaultModel = provider.models.models[0]?.id;
		if (defaultModel) nextConfig = applyDefaultModel(nextConfig, `${provider.id}/${defaultModel}`);
	}
	return nextConfig;
}

//#endregion
//#region src/commands/onboard-non-interactive/local/auth-choice.ts
async function applyNonInteractiveAuthChoice(params) {
	const { authChoice, opts, runtime, baseConfig } = params;
	let nextConfig = params.nextConfig;
	const requestedSecretInputMode = normalizeSecretInputModeInput(opts.secretInputMode);
	if (opts.secretInputMode && !requestedSecretInputMode) {
		runtime.error("Invalid --secret-input-mode. Use \"plaintext\" or \"ref\".");
		runtime.exit(1);
		return null;
	}
	const apiKeyStorageOptions = requestedSecretInputMode ? { secretInputMode: requestedSecretInputMode } : void 0;
	const toStoredSecretInput = (resolved) => {
		if (requestedSecretInputMode !== "ref") return resolved.key;
		if (resolved.source !== "env") return resolved.key;
		if (!resolved.envVarName) {
			runtime.error([`Unable to determine which environment variable to store as a ref for provider "${authChoice}".`, "Set an explicit provider env var and retry, or use --secret-input-mode plaintext."].join("\n"));
			runtime.exit(1);
			return null;
		}
		return {
			source: "env",
			provider: resolveDefaultSecretProviderAlias(baseConfig, "env", { preferFirstProviderForSource: true }),
			id: resolved.envVarName
		};
	};
	const resolveApiKey = (input) => resolveNonInteractiveApiKey({
		...input,
		secretInputMode: requestedSecretInputMode
	});
	const maybeSetResolvedApiKey = async (resolved, setter) => {
		if (resolved.source === "profile") return true;
		const stored = toStoredSecretInput(resolved);
		if (!stored) return false;
		await setter(stored);
		return true;
	};
	if (authChoice === "claude-cli" || authChoice === "codex-cli") {
		runtime.error([`Auth choice "${authChoice}" is deprecated.`, "Use \"--auth-choice anthropic-oauth\", \"--auth-choice token\" (Anthropic setup-token), or \"--auth-choice openai-codex\"."].join("\n"));
		runtime.exit(1);
		return null;
	}
	if (authChoice === "setup-token") {
		runtime.error(["Auth choice \"setup-token\" requires interactive mode.", "Use \"--auth-choice token\" with --token and --token-provider anthropic."].join("\n"));
		runtime.exit(1);
		return null;
	}
	if (authChoice === "vllm") {
		runtime.error(["Auth choice \"vllm\" requires interactive mode.", "Use interactive onboard/configure to enter base URL, API key, and model ID."].join("\n"));
		runtime.exit(1);
		return null;
	}
	if (authChoice === "apiKey") {
		const resolved = await resolveApiKey({
			provider: "anthropic",
			cfg: baseConfig,
			flagValue: opts.anthropicApiKey,
			flagName: "--anthropic-api-key",
			envVar: "ANTHROPIC_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setAnthropicApiKey(value, void 0, apiKeyStorageOptions))) return null;
		return applyAuthProfileConfig$1(nextConfig, {
			profileId: "anthropic:default",
			provider: "anthropic",
			mode: "api_key"
		});
	}
	if (authChoice === "token") {
		const providerRaw = opts.tokenProvider?.trim();
		if (!providerRaw) {
			runtime.error("Missing --token-provider for --auth-choice token.");
			runtime.exit(1);
			return null;
		}
		const provider = normalizeProviderId(providerRaw);
		if (provider !== "anthropic") {
			runtime.error("Only --token-provider anthropic is supported for --auth-choice token.");
			runtime.exit(1);
			return null;
		}
		const tokenRaw = normalizeSecretInput(opts.token);
		if (!tokenRaw) {
			runtime.error("Missing --token for --auth-choice token.");
			runtime.exit(1);
			return null;
		}
		const tokenError = validateAnthropicSetupToken(tokenRaw);
		if (tokenError) {
			runtime.error(tokenError);
			runtime.exit(1);
			return null;
		}
		let expires;
		const expiresInRaw = opts.tokenExpiresIn?.trim();
		if (expiresInRaw) try {
			expires = Date.now() + parseDurationMs(expiresInRaw, { defaultUnit: "d" });
		} catch (err) {
			runtime.error(`Invalid --token-expires-in: ${String(err)}`);
			runtime.exit(1);
			return null;
		}
		const profileId = opts.tokenProfileId?.trim() || buildTokenProfileId({
			provider,
			name: ""
		});
		upsertAuthProfile({
			profileId,
			credential: {
				type: "token",
				provider,
				token: tokenRaw.trim(),
				...expires ? { expires } : {}
			}
		});
		return applyAuthProfileConfig$1(nextConfig, {
			profileId,
			provider,
			mode: "token"
		});
	}
	if (authChoice === "gemini-api-key") {
		const resolved = await resolveApiKey({
			provider: "google",
			cfg: baseConfig,
			flagValue: opts.geminiApiKey,
			flagName: "--gemini-api-key",
			envVar: "GEMINI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setGeminiApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "google:default",
			provider: "google",
			mode: "api_key"
		});
		return applyGoogleGeminiModelDefault(nextConfig).next;
	}
	if (authChoice === "zai-api-key" || authChoice === "zai-coding-global" || authChoice === "zai-coding-cn" || authChoice === "zai-global" || authChoice === "zai-cn") {
		const resolved = await resolveApiKey({
			provider: "zai",
			cfg: baseConfig,
			flagValue: opts.zaiApiKey,
			flagName: "--zai-api-key",
			envVar: "ZAI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setZaiApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "zai:default",
			provider: "zai",
			mode: "api_key"
		});
		let endpoint;
		let modelIdOverride;
		if (authChoice === "zai-coding-global") endpoint = "coding-global";
		else if (authChoice === "zai-coding-cn") endpoint = "coding-cn";
		else if (authChoice === "zai-global") endpoint = "global";
		else if (authChoice === "zai-cn") endpoint = "cn";
		else {
			const detected = await detectZaiEndpoint({ apiKey: resolved.key });
			if (detected) {
				endpoint = detected.endpoint;
				modelIdOverride = detected.modelId;
			} else endpoint = "global";
		}
		return applyZaiConfig(nextConfig, {
			endpoint,
			...modelIdOverride ? { modelId: modelIdOverride } : {}
		});
	}
	if (authChoice === "xiaomi-api-key") {
		const resolved = await resolveApiKey({
			provider: "xiaomi",
			cfg: baseConfig,
			flagValue: opts.xiaomiApiKey,
			flagName: "--xiaomi-api-key",
			envVar: "XIAOMI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setXiaomiApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "xiaomi:default",
			provider: "xiaomi",
			mode: "api_key"
		});
		return applyXiaomiConfig(nextConfig);
	}
	if (authChoice === "xai-api-key") {
		const resolved = await resolveApiKey({
			provider: "xai",
			cfg: baseConfig,
			flagValue: opts.xaiApiKey,
			flagName: "--xai-api-key",
			envVar: "XAI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setXaiApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "xai:default",
			provider: "xai",
			mode: "api_key"
		});
		return applyXaiConfig(nextConfig);
	}
	if (authChoice === "mistral-api-key") {
		const resolved = await resolveApiKey({
			provider: "mistral",
			cfg: baseConfig,
			flagValue: opts.mistralApiKey,
			flagName: "--mistral-api-key",
			envVar: "MISTRAL_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setMistralApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "mistral:default",
			provider: "mistral",
			mode: "api_key"
		});
		return applyMistralConfig(nextConfig);
	}
	if (authChoice === "volcengine-api-key") {
		const resolved = await resolveApiKey({
			provider: "volcengine",
			cfg: baseConfig,
			flagValue: opts.volcengineApiKey,
			flagName: "--volcengine-api-key",
			envVar: "VOLCANO_ENGINE_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setVolcengineApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "volcengine:default",
			provider: "volcengine",
			mode: "api_key"
		});
		return applyPrimaryModel(nextConfig, "volcengine-plan/ark-code-latest");
	}
	if (authChoice === "byteplus-api-key") {
		const resolved = await resolveApiKey({
			provider: "byteplus",
			cfg: baseConfig,
			flagValue: opts.byteplusApiKey,
			flagName: "--byteplus-api-key",
			envVar: "BYTEPLUS_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setByteplusApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "byteplus:default",
			provider: "byteplus",
			mode: "api_key"
		});
		return applyPrimaryModel(nextConfig, "byteplus-plan/ark-code-latest");
	}
	if (authChoice === "qianfan-api-key") {
		const resolved = await resolveApiKey({
			provider: "qianfan",
			cfg: baseConfig,
			flagValue: opts.qianfanApiKey,
			flagName: "--qianfan-api-key",
			envVar: "QIANFAN_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setQianfanApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "qianfan:default",
			provider: "qianfan",
			mode: "api_key"
		});
		return applyQianfanConfig(nextConfig);
	}
	if (authChoice === "openai-api-key") {
		const resolved = await resolveApiKey({
			provider: "openai",
			cfg: baseConfig,
			flagValue: opts.openaiApiKey,
			flagName: "--openai-api-key",
			envVar: "OPENAI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setOpenaiApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "openai:default",
			provider: "openai",
			mode: "api_key"
		});
		return applyOpenAIConfig(nextConfig);
	}
	if (authChoice === "openrouter-api-key") {
		const resolved = await resolveApiKey({
			provider: "openrouter",
			cfg: baseConfig,
			flagValue: opts.openrouterApiKey,
			flagName: "--openrouter-api-key",
			envVar: "OPENROUTER_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setOpenrouterApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "openrouter:default",
			provider: "openrouter",
			mode: "api_key"
		});
		return applyOpenrouterConfig(nextConfig);
	}
	if (authChoice === "qwen-coding-plan-api-key") {
		const resolved = await resolveApiKey({
			provider: "qwen-coding-plan",
			cfg: baseConfig,
			flagValue: opts.qwenCodingPlanApiKey,
			flagName: "--qwen-coding-plan-api-key",
			envVar: "BAILIAN_CODING_PLAN_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setQwenCodingPlanApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "qwen-coding-plan:default",
			provider: "qwen-coding-plan",
			mode: "api_key"
		});
		return applyQwenCodingPlanConfig(nextConfig);
	}
	if (authChoice === "qwen-api-key") {
		const resolved = await resolveApiKey({
			provider: "qwen",
			cfg: baseConfig,
			flagValue: opts.qwenApiKey,
			flagName: "--qwen-api-key",
			envVar: "DASHSCOPE_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setQwenApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "qwen:default",
			provider: "qwen",
			mode: "api_key"
		});
		return applyQwenConfig(nextConfig);
	}
	if (authChoice === "litellm-api-key") {
		const resolved = await resolveApiKey({
			provider: "litellm",
			cfg: baseConfig,
			flagValue: opts.litellmApiKey,
			flagName: "--litellm-api-key",
			envVar: "LITELLM_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setLitellmApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "litellm:default",
			provider: "litellm",
			mode: "api_key"
		});
		return applyLitellmConfig(nextConfig);
	}
	if (authChoice === "ai-gateway-api-key") {
		const resolved = await resolveApiKey({
			provider: "vercel-ai-gateway",
			cfg: baseConfig,
			flagValue: opts.aiGatewayApiKey,
			flagName: "--ai-gateway-api-key",
			envVar: "AI_GATEWAY_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setVercelAiGatewayApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "vercel-ai-gateway:default",
			provider: "vercel-ai-gateway",
			mode: "api_key"
		});
		return applyVercelAiGatewayConfig(nextConfig);
	}
	if (authChoice === "cloudflare-ai-gateway-api-key") {
		const accountId = opts.cloudflareAiGatewayAccountId?.trim() ?? "";
		const gatewayId = opts.cloudflareAiGatewayGatewayId?.trim() ?? "";
		if (!accountId || !gatewayId) {
			runtime.error(["Auth choice \"cloudflare-ai-gateway-api-key\" requires Account ID and Gateway ID.", "Use --cloudflare-ai-gateway-account-id and --cloudflare-ai-gateway-gateway-id."].join("\n"));
			runtime.exit(1);
			return null;
		}
		const resolved = await resolveApiKey({
			provider: "cloudflare-ai-gateway",
			cfg: baseConfig,
			flagValue: opts.cloudflareAiGatewayApiKey,
			flagName: "--cloudflare-ai-gateway-api-key",
			envVar: "CLOUDFLARE_AI_GATEWAY_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (resolved.source !== "profile") {
			const stored = toStoredSecretInput(resolved);
			if (!stored) return null;
			await setCloudflareAiGatewayConfig(accountId, gatewayId, stored, void 0, apiKeyStorageOptions);
		}
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "cloudflare-ai-gateway:default",
			provider: "cloudflare-ai-gateway",
			mode: "api_key"
		});
		return applyCloudflareAiGatewayConfig(nextConfig, {
			accountId,
			gatewayId
		});
	}
	const applyMoonshotApiKeyChoice = async (applyConfig) => {
		const resolved = await resolveApiKey({
			provider: "moonshot",
			cfg: baseConfig,
			flagValue: opts.moonshotApiKey,
			flagName: "--moonshot-api-key",
			envVar: "MOONSHOT_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setMoonshotApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "moonshot:default",
			provider: "moonshot",
			mode: "api_key"
		});
		return applyConfig(nextConfig);
	};
	if (authChoice === "moonshot-api-key") return await applyMoonshotApiKeyChoice(applyMoonshotConfig);
	if (authChoice === "moonshot-api-key-cn") return await applyMoonshotApiKeyChoice(applyMoonshotConfigCn);
	if (authChoice === "kimi-code-api-key") {
		const resolved = await resolveApiKey({
			provider: "kimi-coding",
			cfg: baseConfig,
			flagValue: opts.kimiCodeApiKey,
			flagName: "--kimi-code-api-key",
			envVar: "KIMI_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setKimiCodingApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "kimi-coding:default",
			provider: "kimi-coding",
			mode: "api_key"
		});
		return applyKimiCodeConfig(nextConfig);
	}
	if (authChoice === "synthetic-api-key") {
		const resolved = await resolveApiKey({
			provider: "synthetic",
			cfg: baseConfig,
			flagValue: opts.syntheticApiKey,
			flagName: "--synthetic-api-key",
			envVar: "SYNTHETIC_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setSyntheticApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "synthetic:default",
			provider: "synthetic",
			mode: "api_key"
		});
		return applySyntheticConfig(nextConfig);
	}
	if (authChoice === "venice-api-key") {
		const resolved = await resolveApiKey({
			provider: "venice",
			cfg: baseConfig,
			flagValue: opts.veniceApiKey,
			flagName: "--venice-api-key",
			envVar: "VENICE_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setVeniceApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "venice:default",
			provider: "venice",
			mode: "api_key"
		});
		return applyVeniceConfig(nextConfig);
	}
	if (authChoice === "minimax-cloud" || authChoice === "minimax-api" || authChoice === "minimax-api-key-cn" || authChoice === "minimax-api-lightning") {
		const isCn = authChoice === "minimax-api-key-cn";
		const providerId = isCn ? "minimax-cn" : "minimax";
		const profileId = `${providerId}:default`;
		const resolved = await resolveApiKey({
			provider: providerId,
			cfg: baseConfig,
			flagValue: opts.minimaxApiKey,
			flagName: "--minimax-api-key",
			envVar: "MINIMAX_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setMinimaxApiKey(value, void 0, profileId, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId,
			provider: providerId,
			mode: "api_key"
		});
		const modelId = authChoice === "minimax-api-lightning" ? MINIMAX_HIGHSPEED_MODEL_ID : MINIMAX_DEFAULT_MODEL_ID;
		return isCn ? applyMinimaxApiConfigCn(nextConfig, modelId) : applyMinimaxApiConfig(nextConfig, modelId);
	}
	if (authChoice === "opencode-zen") {
		const resolved = await resolveApiKey({
			provider: "opencode",
			cfg: baseConfig,
			flagValue: opts.opencodeZenApiKey,
			flagName: "--opencode-zen-api-key",
			envVar: "OPENCODE_API_KEY (or OPENCODE_ZEN_API_KEY)",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setOpencodeZenApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "opencode:default",
			provider: "opencode",
			mode: "api_key"
		});
		return applyOpencodeZenConfig(nextConfig);
	}
	if (authChoice === "together-api-key") {
		const resolved = await resolveApiKey({
			provider: "together",
			cfg: baseConfig,
			flagValue: opts.togetherApiKey,
			flagName: "--together-api-key",
			envVar: "TOGETHER_API_KEY",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setTogetherApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "together:default",
			provider: "together",
			mode: "api_key"
		});
		return applyTogetherConfig(nextConfig);
	}
	if (authChoice === "huggingface-api-key") {
		const resolved = await resolveApiKey({
			provider: "huggingface",
			cfg: baseConfig,
			flagValue: opts.huggingfaceApiKey,
			flagName: "--huggingface-api-key",
			envVar: "HF_TOKEN",
			runtime
		});
		if (!resolved) return null;
		if (!await maybeSetResolvedApiKey(resolved, (value) => setHuggingfaceApiKey(value, void 0, apiKeyStorageOptions))) return null;
		nextConfig = applyAuthProfileConfig$1(nextConfig, {
			profileId: "huggingface:default",
			provider: "huggingface",
			mode: "api_key"
		});
		return applyHuggingfaceConfig(nextConfig);
	}
	if (authChoice === "custom-api-key") try {
		const customAuth = parseNonInteractiveCustomApiFlags({
			baseUrl: opts.customBaseUrl,
			modelId: opts.customModelId,
			compatibility: opts.customCompatibility,
			apiKey: opts.customApiKey,
			providerId: opts.customProviderId,
			allowPrivateNetwork: opts.allowPrivateNetwork
		});
		const resolvedCustomApiKey = await resolveApiKey({
			provider: resolveCustomProviderId({
				config: nextConfig,
				baseUrl: customAuth.baseUrl,
				providerId: customAuth.providerId
			}).providerId,
			cfg: baseConfig,
			flagValue: customAuth.apiKey,
			flagName: "--custom-api-key",
			envVar: "CUSTOM_API_KEY",
			envVarName: "CUSTOM_API_KEY",
			runtime,
			required: false
		});
		let customApiKeyInput;
		if (resolvedCustomApiKey) if (requestedSecretInputMode === "ref") {
			const stored = toStoredSecretInput(resolvedCustomApiKey);
			if (!stored) return null;
			customApiKeyInput = stored;
		} else customApiKeyInput = resolvedCustomApiKey.key;
		const result = applyCustomApiConfig({
			config: nextConfig,
			baseUrl: customAuth.baseUrl,
			modelId: customAuth.modelId,
			compatibility: customAuth.compatibility,
			apiKey: customApiKeyInput,
			providerId: customAuth.providerId,
			allowPrivateNetwork: customAuth.allowPrivateNetwork
		});
		if (result.providerIdRenamedFrom && result.providerId) runtime.log(`Custom provider ID "${result.providerIdRenamedFrom}" already exists for a different base URL. Using "${result.providerId}".`);
		return result.config;
	} catch (err) {
		if (err instanceof CustomApiError) {
			switch (err.code) {
				case "missing_required":
				case "invalid_compatibility":
					runtime.error(err.message);
					break;
				default:
					runtime.error(`Invalid custom provider config: ${err.message}`);
					break;
			}
			runtime.exit(1);
			return null;
		}
		const reason = err instanceof Error ? err.message : String(err);
		runtime.error(`Invalid custom provider config: ${reason}`);
		runtime.exit(1);
		return null;
	}
	const pluginProviderConfig = await applyNonInteractivePluginProviderApiKeyChoice({
		authChoice,
		opts,
		runtime,
		baseConfig,
		nextConfig,
		secretInputMode: requestedSecretInputMode
	});
	if (pluginProviderConfig !== void 0) return pluginProviderConfig;
	if (authChoice === "oauth" || authChoice === "anthropic-oauth" || authChoice === "chutes" || authChoice === "openai-codex" || authChoice === "minimax-portal") {
		runtime.error("OAuth requires interactive mode.");
		runtime.exit(1);
		return null;
	}
	return nextConfig;
}

//#endregion
//#region src/commands/onboard-non-interactive/local/daemon-install.ts
async function installGatewayDaemonNonInteractive(params) {
	const { opts, runtime, port, gatewayToken } = params;
	if (!opts.installDaemon) return;
	const daemonRuntimeRaw = opts.daemonRuntime ?? DEFAULT_GATEWAY_DAEMON_RUNTIME;
	const systemdAvailable = process.platform === "linux" ? await isSystemdUserServiceAvailable() : true;
	if (process.platform === "linux" && !systemdAvailable) {
		runtime.log("Systemd user services are unavailable; skipping service install.");
		return;
	}
	if (!isGatewayDaemonRuntime(daemonRuntimeRaw)) {
		runtime.error("Invalid --daemon-runtime (use node or bun)");
		runtime.exit(1);
		return;
	}
	const service = resolveGatewayService();
	const startupMode = resolveHostedOnboardingGatewayStartupMode(opts.hostProfile);
	const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
		env: process.env,
		port,
		token: gatewayToken,
		runtime: daemonRuntimeRaw,
		warn: (message) => runtime.log(message),
		config: params.nextConfig,
		startupMode
	});
	try {
		await service.install({
			env: process.env,
			stdout: process.stdout,
			programArguments,
			workingDirectory,
			environment
		});
	} catch (err) {
		runtime.error(`Gateway service install failed: ${String(err)}`);
		runtime.log(gatewayInstallErrorHint());
		return;
	}
	await ensureSystemdUserLingerNonInteractive({ runtime });
}

//#endregion
//#region src/commands/onboard-non-interactive/local/gateway-config.ts
const HOSTED_TAILSCALE_TRUSTED_PROXIES = ["127.0.0.1/32", "::1/128"];
function applyNonInteractiveGatewayConfig(params) {
	const { opts, runtime } = params;
	const hasGatewayPort = opts.gatewayPort !== void 0;
	if (hasGatewayPort && (!Number.isFinite(opts.gatewayPort) || (opts.gatewayPort ?? 0) <= 0)) {
		runtime.error("Invalid --gateway-port");
		runtime.exit(1);
		return null;
	}
	const port = hasGatewayPort ? opts.gatewayPort : params.defaultPort;
	let bind = opts.gatewayBind ?? "loopback";
	const authModeRaw = opts.gatewayAuth ?? "token";
	if (authModeRaw !== "token" && authModeRaw !== "password") {
		runtime.error("Invalid --gateway-auth (use token|password).");
		runtime.exit(1);
		return null;
	}
	let authMode = authModeRaw;
	const hostingProfile = opts.hostProfile === "hosting";
	const tailscaleMode = hostingProfile ? "serve" : opts.tailscale ?? "off";
	const tailscaleResetOnExit = Boolean(opts.tailscaleResetOnExit);
	if (hostingProfile) bind = "loopback";
	else if (tailscaleMode !== "off" && bind !== "loopback") bind = "loopback";
	if (tailscaleMode === "funnel" && authMode !== "password") authMode = "password";
	let nextConfig = params.nextConfig;
	let gatewayToken = opts.gatewayToken?.trim() || void 0;
	if (authMode === "token") {
		if (!gatewayToken) gatewayToken = randomToken();
		nextConfig = {
			...nextConfig,
			gateway: {
				...nextConfig.gateway,
				auth: {
					...nextConfig.gateway?.auth,
					mode: "token",
					token: gatewayToken
				}
			}
		};
	}
	if (authMode === "password") {
		const password = opts.gatewayPassword?.trim();
		if (!password) {
			runtime.error("Missing --gateway-password for password auth.");
			runtime.exit(1);
			return null;
		}
		nextConfig = {
			...nextConfig,
			gateway: {
				...nextConfig.gateway,
				auth: {
					...nextConfig.gateway?.auth,
					mode: "password",
					password
				}
			}
		};
	}
	nextConfig = {
		...nextConfig,
		gateway: {
			...nextConfig.gateway,
			port,
			bind,
			trustedProxies: hostingProfile && tailscaleMode === "serve" ? Array.from(new Set([...nextConfig.gateway?.trustedProxies ?? [], ...HOSTED_TAILSCALE_TRUSTED_PROXIES])) : nextConfig.gateway?.trustedProxies,
			controlUi: hostingProfile && tailscaleMode === "serve" ? {
				...nextConfig.gateway?.controlUi,
				allowInsecureAuth: true
			} : nextConfig.gateway?.controlUi,
			tailscale: {
				...nextConfig.gateway?.tailscale,
				mode: tailscaleMode,
				resetOnExit: tailscaleResetOnExit
			}
		}
	};
	return {
		nextConfig,
		port,
		bind,
		authMode,
		tailscaleMode,
		tailscaleResetOnExit,
		gatewayToken
	};
}

//#endregion
//#region src/commands/onboard-non-interactive/local/output.ts
function logNonInteractiveOnboardingJson(params) {
	if (!params.opts.json) return;
	params.runtime.log(JSON.stringify({
		mode: params.mode,
		workspace: params.workspaceDir,
		authChoice: params.authChoice,
		gateway: params.gateway,
		installDaemon: Boolean(params.installDaemon),
		daemonRuntime: params.daemonRuntime,
		skipSkills: Boolean(params.skipSkills),
		skipHealth: Boolean(params.skipHealth),
		fastHealth: Boolean(params.fastHealth),
		wallet: params.wallet
	}, null, 2));
}

//#endregion
//#region src/commands/onboard-non-interactive/local/skills-config.ts
function applyNonInteractiveSkillsConfig(params) {
	const { nextConfig, opts, runtime } = params;
	if (opts.skipSkills) return nextConfig;
	const nodeManager = opts.nodeManager ?? "npm";
	if (![
		"npm",
		"pnpm",
		"bun"
	].includes(nodeManager)) {
		runtime.error("Invalid --node-manager (use npm, pnpm, or bun)");
		runtime.exit(1);
		return nextConfig;
	}
	return {
		...nextConfig,
		skills: {
			...nextConfig.skills,
			install: {
				...nextConfig.skills?.install,
				nodeManager
			}
		}
	};
}

//#endregion
//#region src/commands/onboard-non-interactive/local/wallet-config.ts
const DEFAULT_WALLET_CHAINS = ["solana"];
const DEFAULT_WALLET_RUNTIME_HOST = "127.0.0.1";
const DEFAULT_WALLET_RUNTIME_PORT = 19444;
const DEFAULT_WALLET_RUNTIME_VERSION = "0.1.1";
const DEFAULT_SOLANA_MAX_PER_TX = "1000000000";
const DEFAULT_SOLANA_MAX_DAILY = "5000000000";
function isManagedGatewayMode(opts, env = process.env) {
	const mode = (env.FASED_GATEWAY_MODE ?? "").trim().toLowerCase();
	if (mode === "managed") return true;
	if (mode === "local" || mode === "gateway") return false;
	if (opts.mode === "remote") return false;
	return opts.flow !== "advanced";
}
function splitCsvList(value) {
	return (value ?? "").split(",").map((item) => item.trim()).filter(Boolean);
}
function normalizeChains(chains) {
	const out = /* @__PURE__ */ new Set();
	for (const chain of chains ?? []) if (chain === "solana") out.add(chain);
	if (out.size === 0) return [...DEFAULT_WALLET_CHAINS];
	return [...out];
}
function applyWalletConfig(base, runtimeConfig) {
	const { defaultProviderId, ...walletRuntimeConfig } = runtimeConfig;
	const providerId = defaultProviderId ?? parseWalletProviderId(base.wallet?.provider?.id);
	const provider = {
		...base.wallet?.provider,
		...providerId ? { id: providerId } : {}
	};
	if (!providerId) delete provider.id;
	return {
		...base,
		wallet: {
			...base.wallet,
			provider,
			runtime: {
				...base.wallet?.runtime,
				...walletRuntimeConfig
			}
		}
	};
}
function parseWalletMode(raw) {
	if (!raw) return null;
	const normalized = raw.trim().toLowerCase();
	if (normalized === "managed" || normalized === "external") return normalized;
	return null;
}
function parseWalletRuntime(raw) {
	if (!raw) return null;
	const normalized = raw.trim().toLowerCase();
	if (normalized === "external-docker" || normalized === "external-custom") return normalized;
	return null;
}
function parseWalletProviderId(raw) {
	switch ((raw ?? "").trim()) {
		case "embedded-keystore":
		case "local-socket-signer":
		case "alchemy":
		case "turnkey":
		case "privy": return raw;
		default: return null;
	}
}
function parseToolAccessMode(raw) {
	if (!raw) return null;
	const normalized = raw.trim().toLowerCase();
	if (normalized === "owner-only" || normalized === "allowlist" || normalized === "all") return normalized;
	return null;
}
function hasConfiguredWalletMaterial(registry) {
	return registry.wallets.length > 0;
}
const LOCAL_SIGNER_ENV_KEYS = [
	"FASED_WALLET_LOCAL_SIGNER_SOCKET",
	"FASED_WALLET_LOCAL_SIGNER_BACKEND_SOCKET",
	"FASED_WALLET_SIGNER_STATE_DIR",
	"FASED_WALLET_LOCAL_SIGNER_RUN_AS_USER",
	"FASED_WALLET_LOCAL_SIGNER_BIN",
	"FASED_WALLET_PASSPHRASE_FILE"
];
function clearLocalSignerEnv(base) {
	for (const key of LOCAL_SIGNER_ENV_KEYS) delete process.env[key];
	const vars = { ...base.env?.vars };
	for (const key of LOCAL_SIGNER_ENV_KEYS) delete vars[key];
	return {
		...base,
		env: {
			...base.env,
			vars
		}
	};
}
function setConfigEnvVar$1(config, key, value) {
	const vars = { ...config.env?.vars };
	if (value === void 0 || value === "") delete vars[key];
	else vars[key] = value;
	return {
		...config,
		env: {
			...config.env,
			vars
		}
	};
}
function applyHostedLocalSignerDefaults(base) {
	const signerUser = String(process.env.FASED_SIGNER_USER ?? "fased-signer").trim();
	if (!signerUser) return base;
	const appHome = String(process.env.HOME ?? "/home/app").trim() || "/home/app";
	const signerHome = `/home/${signerUser}`;
	const defaults = {
		FASED_WALLET_LOCAL_SIGNER_SOCKET: `${appHome}/.fased/wallet/local-signer.sock`,
		FASED_WALLET_LOCAL_SIGNER_BACKEND_SOCKET: `${signerHome}/.fased/wallet/local-signer.sock`,
		FASED_WALLET_SIGNER_STATE_DIR: `${signerHome}/.fased/wallet`,
		FASED_WALLET_LOCAL_SIGNER_RUN_AS_USER: signerUser,
		FASED_WALLET_LOCAL_SIGNER_BIN: `${signerHome}/.fased/bin/fased-signerd`,
		FASED_WALLET_PASSPHRASE_FILE: `${signerHome}/.fased/wallet/passphrase`
	};
	let next = base;
	for (const [key, value] of Object.entries(defaults)) {
		const existing = String(process.env[key] ?? base.env?.vars?.[key] ?? "").trim();
		if (existing) {
			process.env[key] = existing;
			next = setConfigEnvVar$1(next, key, existing);
			continue;
		}
		process.env[key] = value;
		next = setConfigEnvVar$1(next, key, value);
	}
	return next;
}
function applyNonInteractiveWalletConfig(params) {
	const { nextConfig, opts, runtime } = params;
	const current = nextConfig.wallet?.runtime;
	const managedMode = isManagedGatewayMode(opts);
	const registry = readWalletProviderRegistry(process.env);
	const configuredWalletMaterial = hasConfiguredWalletMaterial(registry);
	if (!(opts.walletEnabled ?? (current?.enabled === false ? false : Boolean(current?.enabled && configuredWalletMaterial)))) {
		setWalletProvidersEnabled({
			enabledProviders: [],
			env: process.env
		});
		return applyWalletConfig(clearLocalSignerEnv(nextConfig), { enabled: false });
	}
	const providersFromOption = typeof opts.walletProviders === "string" ? opts.walletProviders.split(",").map((entry) => parseWalletProviderId(entry.trim())).filter((entry) => Boolean(entry)) : null;
	const invalidProviders = typeof opts.walletProviders === "string" ? opts.walletProviders.split(",").map((entry) => entry.trim()).filter((entry) => Boolean(entry)).filter((entry) => !parseWalletProviderId(entry)) : [];
	if (invalidProviders.length > 0) {
		runtime.error(`Invalid --wallet-providers values: ${invalidProviders.join(", ")} (use ${WALLET_PROVIDER_IDS.join(",")}).`);
		runtime.exit(1);
		return nextConfig;
	}
	const defaultProviderFromOption = parseWalletProviderId(opts.walletDefaultProvider);
	if (opts.walletDefaultProvider && !defaultProviderFromOption) {
		runtime.error(`Invalid --wallet-default-provider value: ${opts.walletDefaultProvider} (use ${WALLET_PROVIDER_IDS.join("|")}).`);
		runtime.exit(1);
		return nextConfig;
	}
	const existingEnabledProviders = WALLET_PROVIDER_IDS.filter((providerId) => registry.providers[providerId]?.enabled);
	const defaultProviderFromConfig = parseWalletProviderId(nextConfig.wallet?.provider?.id);
	const defaultProvider = defaultProviderFromOption ?? (defaultProviderFromConfig === "embedded-keystore" ? "local-socket-signer" : defaultProviderFromConfig) ?? providersFromOption?.[0] ?? "local-socket-signer";
	const enabledProviders = providersFromOption ? [...providersFromOption] : existingEnabledProviders.length > 0 ? [...existingEnabledProviders] : [defaultProvider];
	if (!enabledProviders.includes(defaultProvider)) enabledProviders.unshift(defaultProvider);
	setWalletProvidersEnabled({
		enabledProviders,
		env: process.env
	});
	const runtimeSource = parseWalletRuntime(opts.walletRuntime) ?? (current?.runtime === "external-docker" || current?.runtime === "external-custom" ? current.runtime : parseWalletMode(opts.walletMode) === "external" ? "external-custom" : current?.mode === "external" ? "external-custom" : "external-custom");
	const mode = "external";
	const chainsInput = splitCsvList(opts.walletChains);
	const parsedChains = chainsInput.length ? chainsInput.map((chain) => chain.toLowerCase()).filter(Boolean) : current?.chains ?? DEFAULT_WALLET_CHAINS;
	const invalidChains = parsedChains.filter((chain) => chain !== "solana");
	if (invalidChains.length > 0) {
		runtime.error(`Invalid --wallet-chains values: ${invalidChains.join(", ")} (use solana).`);
		runtime.exit(1);
		return nextConfig;
	}
	const chains = normalizeChains(parsedChains);
	const host = opts.walletHost?.trim() || current?.service?.host?.trim() || DEFAULT_WALLET_RUNTIME_HOST;
	const port = opts.walletPort ?? current?.service?.port ?? DEFAULT_WALLET_RUNTIME_PORT;
	if (!Number.isFinite(port) || port <= 0 || port > 65535) {
		runtime.error("Invalid --wallet-port (must be 1-65535).");
		runtime.exit(1);
		return nextConfig;
	}
	const installEnabled = false;
	const installVersion = opts.walletInstallVersion?.trim() || current?.install?.version?.trim() || DEFAULT_WALLET_RUNTIME_VERSION;
	const authMode = current?.auth?.mode === "jwt-bootstrap" || current?.auth?.mode === "static-token-compat" ? current.auth.mode : "static-token-compat";
	const authBootstrapUrl = current?.auth?.bootstrapUrl?.trim() || void 0;
	const sourceRef = current?.source?.ref?.trim() || void 0;
	const directSigning = opts.walletDirectSigning ?? current?.policy?.directSigning ?? managedMode;
	const toolAccessMode = parseToolAccessMode(opts.walletToolAccessMode) ?? current?.toolAccess?.mode ?? "owner-only";
	if (!toolAccessMode) {
		runtime.error("Invalid --wallet-tool-access-mode (use owner-only|allowlist|all).");
		runtime.exit(1);
		return nextConfig;
	}
	const allowAgents = toolAccessMode === "allowlist" ? splitCsvList(opts.walletToolAccessAllowAgents).length > 0 ? splitCsvList(opts.walletToolAccessAllowAgents) : current?.toolAccess?.allowAgents ?? [] : [];
	const solanaAllowPrograms = splitCsvList(opts.walletSolanaAllowPrograms).length > 0 ? splitCsvList(opts.walletSolanaAllowPrograms) : current?.policy?.solana?.allowPrograms ?? [];
	const solanaMaxPerTx = opts.walletSolanaMaxPerTx?.trim() || current?.policy?.solana?.maxPerTx?.trim() || DEFAULT_SOLANA_MAX_PER_TX;
	const solanaMaxDaily = opts.walletSolanaMaxDaily?.trim() || current?.policy?.solana?.maxDaily?.trim() || DEFAULT_SOLANA_MAX_DAILY;
	return applyWalletConfig(opts.hostProfile === "hosting" && defaultProvider === "local-socket-signer" ? applyHostedLocalSignerDefaults(nextConfig) : nextConfig, {
		enabled: true,
		defaultProviderId: defaultProvider,
		mode,
		runtime: runtimeSource,
		external: { kind: runtimeSource === "external-docker" ? "docker" : "custom" },
		chains,
		service: {
			host,
			port: Math.floor(port)
		},
		install: {
			enabled: installEnabled,
			version: installVersion
		},
		auth: {
			mode: authMode,
			bootstrapUrl: authBootstrapUrl
		},
		source: sourceRef ? { ref: sourceRef } : void 0,
		policy: {
			directSigning,
			solana: {
				allowPrograms: solanaAllowPrograms,
				maxPerTx: solanaMaxPerTx,
				maxDaily: solanaMaxDaily
			}
		},
		toolAccess: {
			mode: toolAccessMode,
			allowAgents
		}
	});
}

//#endregion
//#region src/commands/onboard-non-interactive/local/workspace.ts
function resolveNonInteractiveWorkspaceDir(params) {
	return resolveUserPath((params.opts.workspace ?? params.baseConfig.agents?.defaults?.workspace ?? params.defaultWorkspaceDir).trim());
}

//#endregion
//#region src/commands/onboard-non-interactive/local.ts
const nonInteractiveFederationPrompter = {
	intro: async () => {},
	outro: async () => {},
	note: async () => {},
	select: async (params) => params.options[0].value,
	multiselect: async () => [],
	text: async (params) => params.initialValue ?? "",
	secret: async () => "",
	confirm: async () => true,
	progress: () => ({
		update: () => {},
		stop: () => {}
	})
};
function setConfigEnvVar(config, key, value) {
	const nextVars = { ...config.env?.vars ?? {} };
	if (value === void 0 || value === "") delete nextVars[key];
	else nextVars[key] = value;
	return {
		...config,
		env: {
			...config.env,
			vars: nextVars
		}
	};
}
function applyFederationSettings(config, federation, hostProfile) {
	let nextConfig = setConfigEnvVar(config, "FASED_FEDERATION_AUTO_CONNECT", federation.enabled ? "1" : "0");
	nextConfig = setConfigEnvVar(nextConfig, "FASED_FEDERATION_BASE_URL", federation.enabled ? federation.baseUrl : void 0);
	nextConfig = setConfigEnvVar(nextConfig, "FASED_FEDERATION_HANDLE", federation.enabled ? federation.handle : void 0);
	nextConfig = setConfigEnvVar(nextConfig, "FASED_A2A_HANDLE", federation.enabled ? federation.handle : void 0);
	if (hostProfile === "hosting" || federation.enabled) nextConfig = setConfigEnvVar(nextConfig, "FASED_GATEWAY_MODE", "managed");
	return nextConfig;
}
async function runNonInteractiveOnboardingLocal(params) {
	const { opts, runtime, baseConfig } = params;
	const mode = "local";
	const hostSecurityCapable = isHostedSecurityCapableSession(opts.hostSecurityCapable === true);
	if (typeof opts.hostProfile === "string" && opts.hostProfile !== "local" && opts.hostProfile !== "hosting") {
		runtime.error("Invalid --host-profile. Use local or hosting.");
		runtime.exit(1);
		return;
	}
	if (opts.hostProfile === "hosting" && !hostSecurityCapable && opts.hostMaintenanceSession !== true) {
		runtime.error(["Hosted non-interactive onboarding requires a root-started installer session.", `Re-run ${formatCliCommand("./install.sh")} from root and select a hosting profile there, or use the explicit hosted installer flags from root.`].join("\n"));
		runtime.exit(1);
		return;
	}
	const workspaceDir = resolveNonInteractiveWorkspaceDir({
		opts,
		baseConfig,
		defaultWorkspaceDir: DEFAULT_WORKSPACE
	});
	const hostSecurity = await applyHostingSecurity({
		opts,
		runtime
	});
	if (hostSecurity.profile === "hosting" && hostSecurity.checks.length > 0) {
		runtime.log("Hosting host security checklist:");
		for (const check of hostSecurity.checks) runtime.log(`${check.ok ? "✓" : "✗"} ${check.name}: ${check.detail}`);
	}
	let nextConfig = applyOnboardingLocalWorkspaceConfig(baseConfig, workspaceDir);
	const inferredAuthChoice = inferAuthChoiceFromFlags(opts);
	if (!opts.authChoice && inferredAuthChoice.matches.length > 1) {
		runtime.error([
			"Multiple API key flags were provided for non-interactive onboarding.",
			"Use a single provider flag or pass --auth-choice explicitly.",
			`Flags: ${inferredAuthChoice.matches.map((match) => match.label).join(", ")}`
		].join("\n"));
		runtime.exit(1);
		return;
	}
	const authChoice = opts.authChoice ?? inferredAuthChoice.choice ?? "skip";
	const nextConfigAfterAuth = await applyNonInteractiveAuthChoice({
		nextConfig,
		authChoice,
		opts,
		runtime,
		baseConfig
	});
	if (!nextConfigAfterAuth) return;
	nextConfig = nextConfigAfterAuth;
	const gatewayBasePort = resolveGatewayPort(baseConfig);
	const gatewayResult = applyNonInteractiveGatewayConfig({
		nextConfig,
		opts,
		runtime,
		defaultPort: gatewayBasePort
	});
	if (!gatewayResult) return;
	nextConfig = gatewayResult.nextConfig;
	const hostProfile = opts.hostProfile === "hosting" ? "hosting" : "local";
	const federation = await configureFederationForOnboarding({
		flow: opts.flow === "advanced" || opts.flow === "manual" ? "advanced" : "quickstart",
		hostProfile,
		baseConfig: nextConfig,
		prompter: nonInteractiveFederationPrompter
	});
	nextConfig = applyFederationSettings(nextConfig, federation, hostProfile);
	nextConfig = applyNonInteractiveSkillsConfig({
		nextConfig,
		opts,
		runtime
	});
	nextConfig = applyRecommendedInternalHooks(nextConfig);
	nextConfig = applyNonInteractiveWalletConfig({
		nextConfig,
		opts,
		runtime
	});
	nextConfig = applyWizardMetadata(nextConfig, {
		command: "onboard",
		mode
	});
	await writeConfigFile(nextConfig);
	logConfigUpdated(runtime);
	await ensureWorkspaceAndSessions(workspaceDir, runtime, { skipBootstrap: Boolean(nextConfig.agents?.defaults?.skipBootstrap) });
	try {
		const { syncLocalSocketSignerFromConfig } = await import("./onboarding.wallet-CcoV0W6U.js").then((n) => n.i);
		await syncLocalSocketSignerFromConfig({
			config: nextConfig,
			env: process.env,
			restart: true
		});
	} catch (err) {
		runtime.error(`Wallet signer refresh failed: ${err instanceof Error ? err.message : String(err)}`);
		runtime.exit(1);
		return;
	}
	await installGatewayDaemonNonInteractive({
		nextConfig,
		opts,
		runtime,
		port: gatewayResult.port,
		gatewayToken: gatewayResult.gatewayToken
	});
	const daemonRuntimeRaw = opts.daemonRuntime ?? DEFAULT_GATEWAY_DAEMON_RUNTIME;
	if (!opts.skipHealth) {
		const links = resolveControlUiLinks({
			bind: gatewayResult.bind,
			port: gatewayResult.port,
			customBindHost: nextConfig.gateway?.customBindHost,
			basePath: void 0
		});
		const fastHealth = Boolean(opts.fastHealth);
		const fastProbeTimeoutMs = 1500;
		let fastHealthSatisfied = false;
		if (fastHealth) {
			let fastProbe = await waitForGatewayReachable({
				url: links.wsUrl,
				token: gatewayResult.gatewayToken,
				deadlineMs: 1500,
				probeTimeoutMs: fastProbeTimeoutMs,
				pollMs: 200
			});
			if (!fastProbe.ok && String(fastProbe.detail ?? "").toLowerCase().includes("device token mismatch")) {
				const cleared = clearDeviceAuthStore(process.env);
				runtime.log(cleared ? "Detected stale local device auth cache; cleared and retrying fast health probe once." : "Detected device token mismatch; cache already empty, retrying fast health probe once.");
				fastProbe = await waitForGatewayReachable({
					url: links.wsUrl,
					token: gatewayResult.gatewayToken,
					deadlineMs: 1500,
					probeTimeoutMs: fastProbeTimeoutMs,
					pollMs: 200
				});
			}
			if (fastProbe.ok) {
				fastHealthSatisfied = true;
				runtime.log("Fast health mode: gateway already healthy; skipping extended health waits.");
			}
		}
		if (!fastHealthSatisfied) {
			await waitForGatewayReachable({
				url: links.wsUrl,
				token: gatewayResult.gatewayToken,
				deadlineMs: 15e3
			});
			try {
				await healthCommand({
					json: false,
					timeoutMs: 1e4
				}, runtime);
			} catch (err) {
				let finalError = err;
				if (String(err).toLowerCase().includes("device token mismatch")) {
					const cleared = clearDeviceAuthStore(process.env);
					runtime.log(cleared ? "Detected stale local device auth cache; cleared and retrying health check once." : "Detected device token mismatch; cache already empty, retrying health check once.");
					try {
						await healthCommand({
							json: false,
							timeoutMs: 1e4
						}, runtime);
						finalError = null;
					} catch (retryErr) {
						finalError = retryErr;
					}
				}
				if (finalError) {
					runtime.error(formatHealthCheckFailure(finalError));
					runtime.exit(1);
					return;
				}
			}
		}
	}
	logNonInteractiveOnboardingJson({
		opts,
		runtime,
		mode,
		workspaceDir,
		authChoice,
		gateway: {
			port: gatewayResult.port,
			bind: gatewayResult.bind,
			authMode: gatewayResult.authMode,
			tailscaleMode: gatewayResult.tailscaleMode
		},
		installDaemon: Boolean(opts.installDaemon),
		daemonRuntime: opts.installDaemon ? daemonRuntimeRaw : void 0,
		skipSkills: Boolean(opts.skipSkills),
		skipHealth: Boolean(opts.skipHealth),
		fastHealth: Boolean(opts.fastHealth),
		wallet: {
			enabled: nextConfig.wallet?.runtime?.enabled ?? false,
			mode: nextConfig.wallet?.runtime?.mode ?? "managed",
			chains: nextConfig.wallet?.runtime?.chains ?? [],
			toolAccessMode: nextConfig.wallet?.runtime?.toolAccess?.mode ?? "owner-only",
			directSigning: nextConfig.wallet?.runtime?.policy?.directSigning ?? false
		}
	});
	if (!opts.json) {
		if (!opts.installDaemon) runtime.log(`Start runtime with: ${formatCliCommand("fased start")}`);
		runtime.log(`Tip: run \`${formatCliCommand("fased configure --section web")}\` to select a web_search provider and store its API key. Docs: https://docs.fased.ai/tools/web`);
	}
}

//#endregion
//#region src/commands/onboard-non-interactive/remote.ts
async function runNonInteractiveOnboardingRemote(params) {
	const { opts, runtime, baseConfig } = params;
	const mode = "remote";
	const remoteUrl = opts.remoteUrl?.trim();
	if (!remoteUrl) {
		runtime.error("Missing --remote-url for remote mode.");
		runtime.exit(1);
		return;
	}
	let nextConfig = {
		...baseConfig,
		gateway: {
			...baseConfig.gateway,
			mode: "remote",
			remote: {
				url: remoteUrl,
				token: opts.remoteToken?.trim() || void 0
			}
		}
	};
	nextConfig = applyWizardMetadata(nextConfig, {
		command: "onboard",
		mode
	});
	await writeConfigFile(nextConfig);
	logConfigUpdated(runtime);
	const payload = {
		mode,
		remoteUrl,
		auth: opts.remoteToken ? "token" : "none"
	};
	if (opts.json) runtime.log(JSON.stringify(payload, null, 2));
	else {
		runtime.log(`Remote gateway: ${remoteUrl}`);
		runtime.log(`Auth: ${payload.auth}`);
		runtime.log(`Tip: run \`${formatCliCommand("fased configure --section web")}\` to select a web_search provider and store its API key. Docs: https://docs.fased.ai/tools/web`);
	}
}

//#endregion
//#region src/commands/onboard-non-interactive.ts
async function runNonInteractiveOnboarding(opts, runtime = defaultRuntime) {
	const snapshot = await readConfigFileSnapshot();
	if (snapshot.exists && !snapshot.valid) {
		runtime.error(`Config invalid. Run \`${formatCliCommand("fased doctor")}\` to repair it, then re-run onboarding.`);
		runtime.exit(1);
		return;
	}
	const baseConfig = snapshot.valid ? snapshot.config : {};
	const mode = opts.mode ?? "local";
	if (mode !== "local" && mode !== "remote") {
		runtime.error(`Invalid --mode "${String(mode)}" (use local|remote).`);
		runtime.exit(1);
		return;
	}
	if (mode === "remote") {
		await runNonInteractiveOnboardingRemote({
			opts,
			runtime,
			baseConfig
		});
		return;
	}
	await runNonInteractiveOnboardingLocal({
		opts,
		runtime,
		baseConfig
	});
}

//#endregion
//#region src/commands/onboard.ts
const VALID_REPAIR_SCOPES = new Set([
	"sessions",
	"auth",
	"auth+sessions"
]);
async function onboardCommand(opts, runtime = defaultRuntime) {
	assertSupportedRuntime(runtime);
	const originalAuthChoice = opts.authChoice;
	const normalizedAuthChoice = normalizeLegacyOnboardAuthChoice(originalAuthChoice);
	if (opts.nonInteractive && isDeprecatedAuthChoice(originalAuthChoice)) {
		runtime.error([`Auth choice "${String(originalAuthChoice)}" is deprecated.`, "Use \"--auth-choice anthropic-oauth\", \"--auth-choice token\" (Anthropic setup-token), or \"--auth-choice openai-codex\"."].join("\n"));
		runtime.exit(1);
		return;
	}
	if (originalAuthChoice === "claude-cli") runtime.log("Auth choice \"claude-cli\" is deprecated; using setup-token flow instead.");
	if (originalAuthChoice === "codex-cli") runtime.log("Auth choice \"codex-cli\" is deprecated; using OpenAI sign-in instead.");
	const flow = opts.flow === "manual" ? "advanced" : opts.flow;
	const normalizedOpts = normalizedAuthChoice === opts.authChoice && flow === opts.flow ? opts : {
		...opts,
		authChoice: normalizedAuthChoice,
		flow
	};
	if (normalizedOpts.secretInputMode && normalizedOpts.secretInputMode !== "plaintext" && normalizedOpts.secretInputMode !== "ref") {
		runtime.error("Invalid --secret-input-mode. Use \"plaintext\" or \"ref\".");
		runtime.exit(1);
		return;
	}
	if (normalizedOpts.resetScope && !VALID_REPAIR_SCOPES.has(normalizedOpts.resetScope)) {
		runtime.error("Invalid --reset-scope. Use \"sessions\", \"auth\", or \"auth+sessions\".");
		runtime.exit(1);
		return;
	}
	if (normalizedOpts.nonInteractive && normalizedOpts.acceptRisk !== true) {
		runtime.error([
			"Non-interactive onboarding requires explicit risk acknowledgement.",
			"Read: https://docs.fased.ai/security",
			`Re-run with: ${formatCliCommand("fased onboard --non-interactive --accept-risk ...")}`
		].join("\n"));
		runtime.exit(1);
		return;
	}
	if (normalizedOpts.reset) await handleOnboardingRepair(normalizedOpts.resetScope ?? "auth+sessions", runtime);
	if (process.platform === "win32") runtime.log([
		"Windows detected — FasedAgent runs great on WSL2!",
		"Native Windows might be trickier.",
		"Quick setup: wsl --install (one command, one reboot)",
		"Guide: https://docs.fased.ai/windows"
	].join("\n"));
	const previousSuppressOverwrite = process.env.FASED_SUPPRESS_CONFIG_OVERWRITE_LOG;
	process.env.FASED_SUPPRESS_CONFIG_OVERWRITE_LOG = "1";
	try {
		if (normalizedOpts.nonInteractive) {
			await runNonInteractiveOnboarding(normalizedOpts, runtime);
			return;
		}
		await runInteractiveOnboarding(normalizedOpts, runtime);
	} finally {
		if (previousSuppressOverwrite === void 0) delete process.env.FASED_SUPPRESS_CONFIG_OVERWRITE_LOG;
		else process.env.FASED_SUPPRESS_CONFIG_OVERWRITE_LOG = previousSuppressOverwrite;
	}
}

//#endregion
export { onboardCommand as t };