import "./paths-WcYpcMAY.js";
import "./exec-CmvuUufz.js";
import "./image-ops-D0pBQqKh.js";
import { _ as withCdpSocket, d as normalizeCdpWsUrl, g as getHeadersWithAuth, m as fetchJson, p as appendCdpPath, t as getChromeWebSocketUrl } from "./chrome-BTLLz_O2.js";
import { n as formatErrorMessage } from "./errors-BlUw40-o.js";
import "./tool-images-B4eVOjD0.js";
import { a as jsonResult, o as readNumberParam, t as ToolInputError, u as readStringParam } from "./common-CxpUJZLb.js";
import { r as optionalStringEnum } from "./typebox-C14oleuH.js";
import path from "node:path";
import fs from "node:fs/promises";
import { Type } from "@sinclair/typebox";
import { chromium } from "playwright-core";

//#region src/agents/tools/misc/architect-pipeline-tool.ts
const ArchitectPipelineToolSchema = Type.Object({
	action: optionalStringEnum([
		"init",
		"get",
		"update",
		"decision_gate"
	]),
	path: Type.Optional(Type.String()),
	project: Type.Optional(Type.String()),
	currentPhase: optionalStringEnum([
		"planning",
		"construction",
		"validation"
	]),
	currentStep: Type.Optional(Type.Number({ minimum: 1 })),
	status: optionalStringEnum([
		"running",
		"blocked",
		"complete",
		"escalated"
	]),
	retryCount: Type.Optional(Type.Number({ minimum: 0 })),
	conceptBriefPath: Type.Optional(Type.String()),
	prdPath: Type.Optional(Type.String()),
	wireframesPath: Type.Optional(Type.String()),
	schemaPath: Type.Optional(Type.String()),
	designSystemPath: Type.Optional(Type.String()),
	infraReady: Type.Optional(Type.Boolean()),
	codeReady: Type.Optional(Type.Boolean()),
	securityReportPath: Type.Optional(Type.String()),
	deployInstructionsPath: Type.Optional(Type.String()),
	report: optionalStringEnum([
		"PASS",
		"FAIL",
		"ERROR"
	]),
	findings: Type.Optional(Type.String()),
	maxRetries: Type.Optional(Type.Number({ minimum: 1 }))
});
function defaultState(project = "unnamed-project") {
	return {
		project,
		currentPhase: "planning",
		currentStep: 1,
		retryCount: 0,
		status: "running",
		sharedContext: {
			conceptBriefPath: "concept_brief.json",
			prdPath: "prd.md",
			wireframesPath: "wireframes.md",
			schemaPath: "data-schema.json",
			designSystemPath: "design-system.md"
		},
		artifacts: {
			infraReady: false,
			codeReady: false,
			securityReportPath: "security-report.md",
			deployInstructionsPath: "DEPLOY_INSTRUCTIONS.md"
		}
	};
}
function isWithinWorkspace(candidatePath, workspaceDir) {
	const rel = path.relative(workspaceDir, candidatePath);
	return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
}
function resolveStatePath(params) {
	const workspaceDir = path.resolve(params.workspaceDir);
	const rawPath = params.rawPath?.trim();
	const statePath = rawPath ? path.resolve(workspaceDir, rawPath) : path.join(workspaceDir, "state.json");
	if (!isWithinWorkspace(statePath, workspaceDir)) throw new ToolInputError("path must stay within the workspace directory");
	return statePath;
}
async function readState(statePath) {
	try {
		const raw = await fs.readFile(statePath, "utf-8");
		return JSON.parse(raw);
	} catch (error) {
		if (error.code === "ENOENT") return null;
		throw error;
	}
}
async function writeState(statePath, state) {
	await fs.mkdir(path.dirname(statePath), { recursive: true });
	await fs.writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf-8");
}
function createArchitectPipelineTool(options) {
	return {
		label: "Architect Pipeline",
		name: "architect_pipeline",
		description: "Manage Architect CEO orchestration state.json and enforce audit decision gates for retries/escalation.",
		parameters: ArchitectPipelineToolSchema,
		execute: async (_callId, input) => {
			const params = input ?? {};
			const action = readStringParam(params, "action") ?? "get";
			const statePath = resolveStatePath({
				workspaceDir: options.workspaceDir,
				rawPath: readStringParam(params, "path")
			});
			if (action === "init") {
				const state = defaultState(readStringParam(params, "project") ?? "unnamed-project");
				await writeState(statePath, state);
				return jsonResult({
					action,
					path: statePath,
					state
				});
			}
			const current = await readState(statePath);
			if (!current) throw new ToolInputError(`state file not found at ${statePath}. Run action=init first or provide an existing path.`);
			if (action === "get") return jsonResult({
				action,
				path: statePath,
				state: current
			});
			if (action === "update") {
				const next = {
					...current,
					project: readStringParam(params, "project") ?? current.project,
					currentPhase: readStringParam(params, "currentPhase") ?? current.currentPhase,
					currentStep: readNumberParam(params, "currentStep", { integer: true }) ?? current.currentStep,
					retryCount: readNumberParam(params, "retryCount", { integer: true }) ?? current.retryCount,
					status: readStringParam(params, "status") ?? current.status,
					sharedContext: {
						...current.sharedContext,
						conceptBriefPath: readStringParam(params, "conceptBriefPath") ?? current.sharedContext.conceptBriefPath,
						prdPath: readStringParam(params, "prdPath") ?? current.sharedContext.prdPath,
						wireframesPath: readStringParam(params, "wireframesPath") ?? current.sharedContext.wireframesPath,
						schemaPath: readStringParam(params, "schemaPath") ?? current.sharedContext.schemaPath,
						designSystemPath: readStringParam(params, "designSystemPath") ?? current.sharedContext.designSystemPath
					},
					artifacts: {
						...current.artifacts,
						infraReady: typeof params.infraReady === "boolean" ? params.infraReady : current.artifacts.infraReady,
						codeReady: typeof params.codeReady === "boolean" ? params.codeReady : current.artifacts.codeReady,
						securityReportPath: readStringParam(params, "securityReportPath") ?? current.artifacts.securityReportPath,
						deployInstructionsPath: readStringParam(params, "deployInstructionsPath") ?? current.artifacts.deployInstructionsPath
					}
				};
				await writeState(statePath, next);
				return jsonResult({
					action,
					path: statePath,
					state: next
				});
			}
			if (action === "decision_gate") {
				const report = readStringParam(params, "report", { required: true }).toUpperCase();
				const findings = readStringParam(params, "findings");
				const maxRetries = readNumberParam(params, "maxRetries", { integer: true }) ?? 5;
				const retryCount = report === "PASS" ? current.retryCount : current.retryCount + 1;
				const status = report === "PASS" ? "complete" : retryCount >= maxRetries ? "escalated" : "running";
				const next = {
					...current,
					currentPhase: report === "PASS" ? "validation" : current.currentPhase,
					retryCount,
					status,
					latestAudit: {
						report,
						findings,
						at: (/* @__PURE__ */ new Date()).toISOString(),
						retryCount
					}
				};
				await writeState(statePath, next);
				return jsonResult({
					action,
					path: statePath,
					report,
					status,
					retryCount,
					maxRetries,
					nextAction: report === "PASS" ? "package_app_and_generate_deploy_instructions" : status === "escalated" ? "escalate_to_human" : "send_findings_to_builder_then_reaudit",
					state: next
				});
			}
			throw new ToolInputError("Unknown action.");
		}
	};
}

//#endregion
//#region src/browser/pw-session.ts
const pageStates = /* @__PURE__ */ new WeakMap();
const contextStates = /* @__PURE__ */ new WeakMap();
const observedContexts = /* @__PURE__ */ new WeakSet();
const observedPages = /* @__PURE__ */ new WeakSet();
const roleRefsByTarget = /* @__PURE__ */ new Map();
const MAX_ROLE_REFS_CACHE = 50;
const MAX_CONSOLE_MESSAGES = 500;
const MAX_PAGE_ERRORS = 200;
const MAX_NETWORK_REQUESTS = 500;
let cached = null;
let connecting = null;
function normalizeCdpUrl(raw) {
	return raw.replace(/\/$/, "");
}
function findNetworkRequestById(state, id) {
	for (let i = state.requests.length - 1; i >= 0; i -= 1) {
		const candidate = state.requests[i];
		if (candidate && candidate.id === id) return candidate;
	}
}
function roleRefsKey(cdpUrl, targetId) {
	return `${normalizeCdpUrl(cdpUrl)}::${targetId}`;
}
function rememberRoleRefsForTarget(opts) {
	const targetId = opts.targetId.trim();
	if (!targetId) return;
	roleRefsByTarget.set(roleRefsKey(opts.cdpUrl, targetId), {
		refs: opts.refs,
		...opts.frameSelector ? { frameSelector: opts.frameSelector } : {},
		...opts.mode ? { mode: opts.mode } : {}
	});
	while (roleRefsByTarget.size > MAX_ROLE_REFS_CACHE) {
		const first = roleRefsByTarget.keys().next();
		if (first.done) break;
		roleRefsByTarget.delete(first.value);
	}
}
function storeRoleRefsForTarget(opts) {
	const state = ensurePageState(opts.page);
	state.roleRefs = opts.refs;
	state.roleRefsFrameSelector = opts.frameSelector;
	state.roleRefsMode = opts.mode;
	if (!opts.targetId?.trim()) return;
	rememberRoleRefsForTarget({
		cdpUrl: opts.cdpUrl,
		targetId: opts.targetId,
		refs: opts.refs,
		frameSelector: opts.frameSelector,
		mode: opts.mode
	});
}
function restoreRoleRefsForTarget(opts) {
	const targetId = opts.targetId?.trim() || "";
	if (!targetId) return;
	const cached = roleRefsByTarget.get(roleRefsKey(opts.cdpUrl, targetId));
	if (!cached) return;
	const state = ensurePageState(opts.page);
	if (state.roleRefs) return;
	state.roleRefs = cached.refs;
	state.roleRefsFrameSelector = cached.frameSelector;
	state.roleRefsMode = cached.mode;
}
function ensurePageState(page) {
	const existing = pageStates.get(page);
	if (existing) return existing;
	const state = {
		console: [],
		errors: [],
		requests: [],
		requestIds: /* @__PURE__ */ new WeakMap(),
		nextRequestId: 0,
		armIdUpload: 0,
		armIdDialog: 0,
		armIdDownload: 0
	};
	pageStates.set(page, state);
	if (!observedPages.has(page)) {
		observedPages.add(page);
		page.on("console", (msg) => {
			const entry = {
				type: msg.type(),
				text: msg.text(),
				timestamp: (/* @__PURE__ */ new Date()).toISOString(),
				location: msg.location()
			};
			state.console.push(entry);
			if (state.console.length > MAX_CONSOLE_MESSAGES) state.console.shift();
		});
		page.on("pageerror", (err) => {
			state.errors.push({
				message: err?.message ? String(err.message) : String(err),
				name: err?.name ? String(err.name) : void 0,
				stack: err?.stack ? String(err.stack) : void 0,
				timestamp: (/* @__PURE__ */ new Date()).toISOString()
			});
			if (state.errors.length > MAX_PAGE_ERRORS) state.errors.shift();
		});
		page.on("request", (req) => {
			state.nextRequestId += 1;
			const id = `r${state.nextRequestId}`;
			state.requestIds.set(req, id);
			state.requests.push({
				id,
				timestamp: (/* @__PURE__ */ new Date()).toISOString(),
				method: req.method(),
				url: req.url(),
				resourceType: req.resourceType()
			});
			if (state.requests.length > MAX_NETWORK_REQUESTS) state.requests.shift();
		});
		page.on("response", (resp) => {
			const req = resp.request();
			const id = state.requestIds.get(req);
			if (!id) return;
			const rec = findNetworkRequestById(state, id);
			if (!rec) return;
			rec.status = resp.status();
			rec.ok = resp.ok();
		});
		page.on("requestfailed", (req) => {
			const id = state.requestIds.get(req);
			if (!id) return;
			const rec = findNetworkRequestById(state, id);
			if (!rec) return;
			rec.failureText = req.failure()?.errorText;
			rec.ok = false;
		});
		page.on("close", () => {
			pageStates.delete(page);
			observedPages.delete(page);
		});
	}
	return state;
}
function observeContext(context) {
	if (observedContexts.has(context)) return;
	observedContexts.add(context);
	ensureContextState(context);
	for (const page of context.pages()) ensurePageState(page);
	context.on("page", (page) => ensurePageState(page));
}
function ensureContextState(context) {
	const existing = contextStates.get(context);
	if (existing) return existing;
	const state = { traceActive: false };
	contextStates.set(context, state);
	return state;
}
function observeBrowser(browser) {
	for (const context of browser.contexts()) observeContext(context);
}
async function connectBrowser(cdpUrl) {
	const normalized = normalizeCdpUrl(cdpUrl);
	if (cached?.cdpUrl === normalized) return cached;
	if (connecting) return await connecting;
	const connectWithRetry = async () => {
		let lastErr;
		for (let attempt = 0; attempt < 2; attempt += 1) try {
			const timeout = 3e3 + attempt * 2e3;
			const endpoint = await getChromeWebSocketUrl(normalized, timeout).catch(() => null) ?? normalized;
			const headers = getHeadersWithAuth(endpoint);
			const browser = await chromium.connectOverCDP(endpoint, {
				timeout,
				headers
			});
			const onDisconnected = () => {
				if (cached?.browser === browser) cached = null;
			};
			const connected = {
				browser,
				cdpUrl: normalized,
				onDisconnected
			};
			cached = connected;
			browser.on("disconnected", onDisconnected);
			observeBrowser(browser);
			return connected;
		} catch (err) {
			lastErr = err;
			const delay = 200 + attempt * 200;
			await new Promise((r) => setTimeout(r, delay));
		}
		if (lastErr instanceof Error) throw lastErr;
		const message = lastErr ? formatErrorMessage(lastErr) : "CDP connect failed";
		throw new Error(message);
	};
	connecting = connectWithRetry().finally(() => {
		connecting = null;
	});
	return await connecting;
}
async function getAllPages(browser) {
	return browser.contexts().flatMap((c) => c.pages());
}
async function pageTargetId(page) {
	const session = await page.context().newCDPSession(page);
	try {
		const info = await session.send("Target.getTargetInfo");
		return String(info?.targetInfo?.targetId ?? "").trim() || null;
	} finally {
		await session.detach().catch(() => {});
	}
}
async function findPageByTargetId(browser, targetId, cdpUrl) {
	const pages = await getAllPages(browser);
	let resolvedViaCdp = false;
	for (const page of pages) {
		let tid = null;
		try {
			tid = await pageTargetId(page);
			resolvedViaCdp = true;
		} catch {
			tid = null;
		}
		if (tid && tid === targetId) return page;
	}
	if (!resolvedViaCdp && pages.length === 1) return pages[0];
	if (cdpUrl) try {
		const listUrl = `${cdpUrl.replace(/\/+$/, "").replace(/^ws:/, "http:").replace(/\/cdp$/, "")}/json/list`;
		const response = await fetch(listUrl, { headers: getHeadersWithAuth(listUrl) });
		if (response.ok) {
			const targets = await response.json();
			const target = targets.find((t) => t.id === targetId);
			if (target) {
				const urlMatch = pages.filter((p) => p.url() === target.url);
				if (urlMatch.length === 1) return urlMatch[0];
				if (urlMatch.length > 1) {
					const sameUrlTargets = targets.filter((t) => t.url === target.url);
					if (sameUrlTargets.length === urlMatch.length) {
						const idx = sameUrlTargets.findIndex((t) => t.id === targetId);
						if (idx >= 0 && idx < urlMatch.length) return urlMatch[idx];
					}
				}
			}
		}
	} catch {}
	return null;
}
async function getPageForTargetId(opts) {
	const { browser } = await connectBrowser(opts.cdpUrl);
	const pages = await getAllPages(browser);
	if (!pages.length) throw new Error("No pages available in the connected browser.");
	const first = pages[0];
	if (!opts.targetId) return first;
	const found = await findPageByTargetId(browser, opts.targetId, opts.cdpUrl);
	if (!found) {
		if (pages.length === 1) return first;
		throw new Error("tab not found");
	}
	return found;
}
function refLocator(page, ref) {
	const normalized = ref.startsWith("@") ? ref.slice(1) : ref.startsWith("ref=") ? ref.slice(4) : ref;
	if (/^e\d+$/.test(normalized)) {
		const state = pageStates.get(page);
		if (state?.roleRefsMode === "aria") return (state.roleRefsFrameSelector ? page.frameLocator(state.roleRefsFrameSelector) : page).locator(`aria-ref=${normalized}`);
		const info = state?.roleRefs?.[normalized];
		if (!info) throw new Error(`Unknown ref "${normalized}". Run a new snapshot and use a ref from that snapshot.`);
		const locAny = state?.roleRefsFrameSelector ? page.frameLocator(state.roleRefsFrameSelector) : page;
		const locator = info.name ? locAny.getByRole(info.role, {
			name: info.name,
			exact: true
		}) : locAny.getByRole(info.role);
		return info.nth !== void 0 ? locator.nth(info.nth) : locator;
	}
	return page.locator(`aria-ref=${normalized}`);
}
async function closePlaywrightBrowserConnection() {
	const cur = cached;
	cached = null;
	connecting = null;
	if (!cur) return;
	if (cur.onDisconnected && typeof cur.browser.off === "function") cur.browser.off("disconnected", cur.onDisconnected);
	await cur.browser.close().catch(() => {});
}
function normalizeCdpHttpBaseForJsonEndpoints(cdpUrl) {
	try {
		const url = new URL(cdpUrl);
		if (url.protocol === "ws:") url.protocol = "http:";
		else if (url.protocol === "wss:") url.protocol = "https:";
		url.pathname = url.pathname.replace(/\/devtools\/browser\/.*$/, "");
		url.pathname = url.pathname.replace(/\/cdp$/, "");
		return url.toString().replace(/\/$/, "");
	} catch {
		return cdpUrl.replace(/^ws:/, "http:").replace(/^wss:/, "https:").replace(/\/devtools\/browser\/.*$/, "").replace(/\/cdp$/, "").replace(/\/$/, "");
	}
}
function cdpSocketNeedsAttach(wsUrl) {
	try {
		const pathname = new URL(wsUrl).pathname;
		return pathname === "/cdp" || pathname.endsWith("/cdp") || pathname.includes("/devtools/browser/");
	} catch {
		return false;
	}
}
async function tryTerminateExecutionViaCdp(opts) {
	const cdpHttpBase = normalizeCdpHttpBaseForJsonEndpoints(opts.cdpUrl);
	const pages = await fetchJson(appendCdpPath(cdpHttpBase, "/json/list"), 2e3).catch(() => null);
	if (!pages || pages.length === 0) return;
	const target = pages.find((p) => String(p.id ?? "").trim() === opts.targetId);
	const wsUrlRaw = String(target?.webSocketDebuggerUrl ?? "").trim();
	if (!wsUrlRaw) return;
	const wsUrl = normalizeCdpWsUrl(wsUrlRaw, cdpHttpBase);
	const needsAttach = cdpSocketNeedsAttach(wsUrl);
	const runWithTimeout = async (work, ms) => {
		let timer;
		const timeoutPromise = new Promise((_, reject) => {
			timer = setTimeout(() => reject(/* @__PURE__ */ new Error("CDP command timed out")), ms);
		});
		try {
			return await Promise.race([work, timeoutPromise]);
		} finally {
			if (timer) clearTimeout(timer);
		}
	};
	await withCdpSocket(wsUrl, async (send) => {
		let sessionId;
		try {
			if (needsAttach) {
				const attached = await runWithTimeout(send("Target.attachToTarget", {
					targetId: opts.targetId,
					flatten: true
				}), 1500);
				if (typeof attached?.sessionId === "string" && attached.sessionId.trim()) sessionId = attached.sessionId;
			}
			await runWithTimeout(send("Runtime.terminateExecution", void 0, sessionId), 1500);
			if (sessionId) send("Target.detachFromTarget", { sessionId }).catch(() => {});
		} catch {}
	}, { handshakeTimeoutMs: 2e3 }).catch(() => {});
}
/**
* Best-effort cancellation for stuck page operations.
*
* Playwright serializes CDP commands per page; a long-running or stuck operation (notably evaluate)
* can block all subsequent commands. We cannot safely "cancel" an individual command, and we do
* not want to close the actual Chromium tab. Instead, we disconnect Playwright's CDP connection
* so in-flight commands fail fast and the next request reconnects transparently.
*
* IMPORTANT: We CANNOT call Connection.close() because Playwright shares a single Connection
* across all objects (BrowserType, Browser, etc.). Closing it corrupts the entire Playwright
* instance, preventing reconnection.
*
* Instead we:
* 1. Null out `cached` so the next call triggers a fresh connectOverCDP
* 2. Fire-and-forget browser.close() — it may hang but won't block us
* 3. The next connectBrowser() creates a completely new CDP WebSocket connection
*
* The old browser.close() eventually resolves when the in-browser evaluate timeout fires,
* or the old connection gets GC'd. Either way, it doesn't affect the fresh connection.
*/
async function forceDisconnectPlaywrightForTarget(opts) {
	const normalized = normalizeCdpUrl(opts.cdpUrl);
	if (cached?.cdpUrl !== normalized) return;
	const cur = cached;
	cached = null;
	connecting = null;
	if (cur) {
		if (cur.onDisconnected && typeof cur.browser.off === "function") cur.browser.off("disconnected", cur.onDisconnected);
		const targetId = opts.targetId?.trim() || "";
		if (targetId) await tryTerminateExecutionViaCdp({
			cdpUrl: normalized,
			targetId
		}).catch(() => {});
		cur.browser.close().catch(() => {});
	}
}
/**
* List all pages/tabs from the persistent Playwright connection.
* Used for remote profiles where HTTP-based /json/list is ephemeral.
*/
async function listPagesViaPlaywright(opts) {
	const { browser } = await connectBrowser(opts.cdpUrl);
	const pages = await getAllPages(browser);
	const results = [];
	for (const page of pages) {
		const tid = await pageTargetId(page).catch(() => null);
		if (tid) results.push({
			targetId: tid,
			title: await page.title().catch(() => ""),
			url: page.url(),
			type: "page"
		});
	}
	return results;
}
/**
* Create a new page/tab using the persistent Playwright connection.
* Used for remote profiles where HTTP-based /json/new is ephemeral.
* Returns the new page's targetId and metadata.
*/
async function createPageViaPlaywright(opts) {
	const { browser } = await connectBrowser(opts.cdpUrl);
	const context = browser.contexts()[0] ?? await browser.newContext();
	ensureContextState(context);
	const page = await context.newPage();
	ensurePageState(page);
	const targetUrl = opts.url.trim() || "about:blank";
	if (targetUrl !== "about:blank") await page.goto(targetUrl, { timeout: 3e4 }).catch(() => {});
	const tid = await pageTargetId(page).catch(() => null);
	if (!tid) throw new Error("Failed to get targetId for new page");
	return {
		targetId: tid,
		title: await page.title().catch(() => ""),
		url: page.url(),
		type: "page"
	};
}
/**
* Close a page/tab by targetId using the persistent Playwright connection.
* Used for remote profiles where HTTP-based /json/close is ephemeral.
*/
async function closePageByTargetIdViaPlaywright(opts) {
	const { browser } = await connectBrowser(opts.cdpUrl);
	const page = await findPageByTargetId(browser, opts.targetId, opts.cdpUrl);
	if (!page) throw new Error("tab not found");
	await page.close();
}
/**
* Focus a page/tab by targetId using the persistent Playwright connection.
* Used for remote profiles where HTTP-based /json/activate can be ephemeral.
*/
async function focusPageByTargetIdViaPlaywright(opts) {
	const { browser } = await connectBrowser(opts.cdpUrl);
	const page = await findPageByTargetId(browser, opts.targetId, opts.cdpUrl);
	if (!page) throw new Error("tab not found");
	try {
		await page.bringToFront();
	} catch (err) {
		const session = await page.context().newCDPSession(page);
		try {
			await session.send("Page.bringToFront");
			return;
		} catch {
			throw err;
		} finally {
			await session.detach().catch(() => {});
		}
	}
}

//#endregion
export { ensurePageState as a, getPageForTargetId as c, createArchitectPipelineTool, rememberRoleRefsForTarget as d, restoreRoleRefsForTarget as f, ensureContextState as i, listPagesViaPlaywright as l, closePlaywrightBrowserConnection as n, focusPageByTargetIdViaPlaywright as o, storeRoleRefsForTarget as p, createPageViaPlaywright as r, forceDisconnectPlaywrightForTarget as s, closePageByTargetIdViaPlaywright as t, refLocator as u };