import { i as __exportAll } from "./tool-display-B7qTeoCS.js";
import { t as createSubsystemLogger } from "./subsystem-ocBR131w.js";
import { o as loadConfig } from "./config-DJ3A5x_1.js";
import { v as ensureChromeExtensionRelayServer } from "./chrome-BQkAVfz8.js";
import { a as resolveProfile, f as ensureBrowserControlAuth, i as resolveBrowserConfig, n as listKnownProfileNames, t as createBrowserRouteContext } from "./server-context-s_zNpSdX.js";

//#region src/browser/server-lifecycle.ts
async function ensureExtensionRelayForProfiles(params) {
	for (const name of Object.keys(params.resolved.profiles)) {
		const profile = resolveProfile(params.resolved, name);
		if (!profile || profile.driver !== "extension") continue;
		await ensureChromeExtensionRelayServer({
			cdpUrl: profile.cdpUrl,
			allowRemote: profile.allowRemote
		}).catch((err) => {
			params.onWarn(`Chrome extension relay init failed for profile "${name}": ${String(err)}`);
		});
	}
}
async function stopKnownBrowserProfiles(params) {
	const current = params.getState();
	if (!current) return;
	const ctx = createBrowserRouteContext({
		getState: params.getState,
		refreshConfigFromDisk: true
	});
	try {
		for (const name of listKnownProfileNames(current)) try {
			await ctx.forProfile(name).stopRunningBrowser();
		} catch {}
	} catch (err) {
		params.onWarn(`openclaw browser stop failed: ${String(err)}`);
	}
}

//#endregion
//#region src/browser/control-service.ts
var control_service_exports = /* @__PURE__ */ __exportAll({
	createBrowserControlContext: () => createBrowserControlContext,
	getBrowserControlState: () => getBrowserControlState,
	startBrowserControlServiceFromConfig: () => startBrowserControlServiceFromConfig,
	stopBrowserControlService: () => stopBrowserControlService
});
let state = null;
const logService = createSubsystemLogger("browser").child("service");
function getBrowserControlState() {
	return state;
}
function createBrowserControlContext() {
	return createBrowserRouteContext({
		getState: () => state,
		refreshConfigFromDisk: true
	});
}
async function startBrowserControlServiceFromConfig() {
	if (state) return state;
	const cfg = loadConfig();
	const resolved = resolveBrowserConfig(cfg.browser, cfg);
	if (!resolved.enabled) return null;
	try {
		if ((await ensureBrowserControlAuth({ cfg })).generatedToken) logService.info("No browser auth configured; generated gateway.auth.token automatically.");
	} catch (err) {
		logService.warn(`failed to auto-configure browser auth: ${String(err)}`);
	}
	state = {
		server: null,
		port: resolved.controlPort,
		resolved,
		profiles: /* @__PURE__ */ new Map()
	};
	await ensureExtensionRelayForProfiles({
		resolved,
		onWarn: (message) => logService.warn(message)
	});
	logService.info(`Browser control service ready (profiles=${Object.keys(resolved.profiles).length}, default=${resolved.defaultProfile})`);
	const defaultProfile = resolveProfile(resolved, resolved.defaultProfile);
	if (defaultProfile && defaultProfile.driver !== "extension" && defaultProfile.cdpIsLoopback) (async () => {
		try {
			await createBrowserRouteContext({
				getState: () => state,
				refreshConfigFromDisk: false
			}).forProfile(resolved.defaultProfile).ensureBrowserAvailable();
			const mod = await import("./pw-session-CbQgHkmS.js").catch(() => null);
			if (mod?.getPageForTargetId) await mod.getPageForTargetId({ cdpUrl: defaultProfile.cdpUrl }).catch(() => {});
			logService.info("Playwright warmup complete for default profile");
		} catch (err) {
			logService.debug?.(`Playwright warmup skipped: ${String(err)}`);
		}
	})();
	return state;
}
async function stopBrowserControlService() {
	if (!state) return;
	await stopKnownBrowserProfiles({
		getState: () => state,
		onWarn: (message) => logService.warn(message)
	});
	state = null;
	try {
		await (await import("./pw-ai-DlBE6jn5.js")).closePlaywrightBrowserConnection();
	} catch {}
}

//#endregion
export { createBrowserControlContext as n, startBrowserControlServiceFromConfig as r, control_service_exports as t };