import "./auth-profiles-D11Xw15i.js";
import "./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 { i as loadConfig } 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 { M as resolveModelProfile } from "./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 "./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 "./session-cost-usage-CJWHHY-C.js";
import "./breakdown-Cszrv-Lf.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 "./links-Dnmd-RS-.js";
import "./cli-utils-DXfA5936.js";
import "./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 "./catalog-BQgWCFTH.js";
import "./prompt-style-CZGg35Py.js";
import "./install-safe-path-BdxXJux8.js";
import "./skill-scanner-BC3PyNso.js";
import "./channels-status-issues-BTvrA4nx.js";
import "./runtime-guard-LRRZ73eX.js";
import "./onboard-helpers-t7tI9KSA.js";
import "./systemd-CNnW7Chw.js";
import "./service-DYpU1ajf.js";
import "./diagnostics-D2oNwzue.js";
import "./table-D0JXlEhQ.js";
import "./audit-DyncRBKq.js";
import "./status-BEZotN01.js";
import "./health-Dkwuq8ta.js";
import "./outbound-send-deps-BCyarBRf.js";
import "./control-ui-assets-Dnz69KRU.js";
import "./update-check-DLOnLuop.js";
import { n as handleGatewayRequest } from "./server-methods-DTkVQH8Q.js";
import "./push-apns-HNg0rTkI.js";
import "./agent-CB5yb-7V.js";
import "./agents.config-CqfMQEiy.js";
import "./dm-policy-shared-BtrdvOIT.js";
import "./node-service-CZlyWmxa.js";
import "./status.update-DW6VHYmK.js";
import "./skills-install-CZE8W7lV.js";
import "./update-runner-Cext3X8r.js";

//#region src/gateway/glass-ui-ws.ts
const SESSION_KEY = "agent:main:main";
/** Synthetic client used for all glass-ui bridge requests. */
const GLASS_UI_CLIENT = { connect: {
	minProtocol: 3,
	maxProtocol: 3,
	client: {
		id: "webchat",
		version: "1.0.0",
		platform: "server",
		mode: "webchat"
	},
	role: "operator",
	scopes: ["operator.admin"],
	caps: [],
	auth: {},
	userAgent: "symi-glass-ui-bridge/1.0.0",
	locale: "en-US"
} };
function isWebchatConnect() {
	return true;
}
function safeSend(ws, data) {
	try {
		if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(data));
	} catch {}
}
function createGlassUiBridge(opts) {
	const { wss, context, extraHandlers, onBroadcast } = opts;
	const browserClients = /* @__PURE__ */ new Map();
	let broadcastSeq = 0;
	function broadcastToBrowsers(msg, seq) {
		for (const [, state] of browserClients) {
			if (seq <= state.lastBroadcastSeq) continue;
			state.lastBroadcastSeq = seq;
			safeSend(state.ws, msg);
		}
	}
	const broadcastUnsub = onBroadcast((event, payload) => {
		broadcastSeq++;
		const seq = broadcastSeq;
		if (event === "chat") broadcastToBrowsers({
			type: "chat",
			payload,
			_seq: seq
		}, seq);
		else if (event === "agent") broadcastToBrowsers({
			type: "agent",
			payload,
			_seq: seq
		}, seq);
		else if (event === "subagent") broadcastToBrowsers({
			type: "subagent",
			payload,
			_seq: seq
		}, seq);
		else if (event === "profile") broadcastToBrowsers({
			type: "profile",
			payload,
			_seq: seq
		}, seq);
	});
	/** Dispatch an RPC method through the gateway's internal handler. */
	async function dispatchRpc(method, params) {
		return new Promise((resolve) => {
			const req = {
				type: "req",
				id: "glass-bridge",
				method,
				params
			};
			const respond = (ok, payload, error) => {
				resolve({
					ok,
					payload,
					error
				});
			};
			handleGatewayRequest({
				req,
				client: GLASS_UI_CLIENT,
				isWebchatConnect,
				respond,
				context,
				extraHandlers
			});
		});
	}
	async function loadAndSendHistory(ws, attempt = 1) {
		const maxAttempts = 3;
		try {
			const result = await dispatchRpc("chat.history", { sessionKey: SESSION_KEY });
			if (result.ok) {
				const payload = result.payload;
				safeSend(ws, {
					type: "history",
					messages: payload.messages ?? [],
					total: payload.total ?? 0,
					hasMore: payload.hasMore ?? false,
					startIndex: payload.startIndex ?? 0
				});
			} else if (attempt < maxAttempts) setTimeout(() => void loadAndSendHistory(ws, attempt + 1), 1500 * attempt);
			else safeSend(ws, {
				type: "history",
				messages: [],
				total: 0,
				hasMore: false,
				startIndex: 0,
				error: "history.unavailable",
				recoverable: true
			});
		} catch {
			if (attempt < maxAttempts) setTimeout(() => void loadAndSendHistory(ws, attempt + 1), 1500 * attempt);
			else safeSend(ws, {
				type: "history",
				messages: [],
				total: 0,
				hasMore: false,
				startIndex: 0,
				error: "history.unavailable",
				recoverable: true
			});
		}
	}
	function sendInitialProfile(ws) {
		try {
			const cfg = loadConfig();
			const modelId = cfg.agents?.defaults?.model?.primary;
			if (!modelId) return;
			safeSend(ws, {
				type: "profile",
				payload: {
					event: "profile",
					profile: resolveModelProfile(modelId, cfg.models?.profiles),
					modelId
				}
			});
		} catch {}
	}
	wss.on("connection", (ws) => {
		browserClients.set(ws, {
			ws,
			lastBroadcastSeq: broadcastSeq
		});
		safeSend(ws, {
			type: "status",
			connected: true
		});
		sendInitialProfile(ws);
		loadAndSendHistory(ws);
		ws.on("message", (data) => {
			let msg;
			try {
				const text = Buffer.isBuffer(data) ? data.toString("utf8") : data instanceof ArrayBuffer ? Buffer.from(data).toString("utf8") : Array.isArray(data) ? Buffer.concat(data).toString("utf8") : "";
				msg = JSON.parse(text);
			} catch {
				return;
			}
			const type = msg.type;
			if (type === "chat.send") {
				(async () => {
					try {
						await dispatchRpc("chat.send", {
							sessionKey: SESSION_KEY,
							message: msg.message,
							idempotencyKey: crypto.randomUUID()
						});
					} catch (err) {
						safeSend(ws, {
							type: "error",
							message: String(err)
						});
					}
				})();
				return;
			}
			if (type === "chat.abort") {
				(async () => {
					try {
						const params = { sessionKey: SESSION_KEY };
						if (msg.runId) params.runId = msg.runId;
						await dispatchRpc("chat.abort", params);
					} catch (err) {
						safeSend(ws, {
							type: "error",
							message: String(err)
						});
					}
				})();
				return;
			}
			if (type === "rpc") {
				const rpcId = msg.id;
				const method = msg.method;
				const params = msg.params ?? {};
				(async () => {
					try {
						const result = await dispatchRpc(method, params);
						safeSend(ws, {
							type: "rpc.response",
							id: rpcId,
							ok: result.ok,
							payload: result.payload,
							error: result.error
						});
					} catch (err) {
						safeSend(ws, {
							type: "rpc.response",
							id: rpcId,
							ok: false,
							error: { message: String(err) }
						});
					}
				})();
				return;
			}
		});
		ws.on("close", () => {
			browserClients.delete(ws);
		});
		ws.on("error", () => {
			browserClients.delete(ws);
		});
	});
	return () => {
		broadcastUnsub();
		for (const [, state] of browserClients) try {
			state.ws.close();
		} catch {}
		browserClients.clear();
	};
}

//#endregion
export { createGlassUiBridge };