"use strict";
importScripts("build-config.js", "shared.js", "services/GoogleSheetsService.js", "services/SkillsService.js", "agent/JobManager.js");
var BrowserAgentBackground;
(function (BrowserAgentBackground) {
    const sessionId = BrowserAgent.createId("session");
    const recentEvents = [];
    let stopRequested = false;
    let running = false;
    let lastScreenshotAt = 0;
    let currentRunId;
    let jobManagerInstance = null;
    chrome.runtime.onInstalled.addListener(() => {
        if (chrome.sidePanel?.setPanelBehavior) {
            chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true }).catch(() => undefined);
        }
    });
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        handleMessage(message, sender)
            .then(sendResponse)
            .catch((error) => sendResponse({ ok: false, error: BrowserAgent.normalizeError(error) }));
        return true;
    });
    async function handleMessage(message, sender) {
        switch (message.type) {
            case "START_AGENT":
                if (!jobManagerInstance) {
                    const overrides = (message.payload?.config || {});
                    jobManagerInstance = new BrowserAgentAgent.JobManager({
                        spreadsheetId: message.payload.spreadsheetId,
                        sourceSheetName: overrides.sourceSheetName || BrowserAgentAgent.DEFAULT_SOURCE_SHEET_NAME,
                        resultSheetName: "",
                        columns: overrides.columns || BrowserAgentAgent.DEFAULT_SOURCE_COLUMNS,
                        batchSize: overrides.batchSize ?? 10,
                        scrapeTimeoutMs: overrides.scrapeTimeoutMs,
                        cloudflareGraceMs: overrides.cloudflareGraceMs,
                        interRowDelayMs: overrides.interRowDelayMs,
                        extractSkillSlug: overrides.extractSkillSlug
                    }, (msg) => {
                        emit({ level: "info", title: "Job Manager", message: msg, type: "agent.log" });
                    }, (event) => {
                        if (event.kind === "run.completed") {
                            emit({
                                level: "success",
                                title: "Run completed",
                                message: `Result sheet: ${event.sheetTitle}`,
                                type: "agent.run.completed",
                                data: { sheetUrl: event.sheetUrl, sheetTitle: event.sheetTitle, sheetId: event.sheetId }
                            });
                        }
                    });
                }
                jobManagerInstance.start();
                return { ok: true };
            case "STOP_AGENT":
                if (jobManagerInstance) {
                    jobManagerInstance.stop();
                    jobManagerInstance = null;
                }
                return { ok: true };
            case "CHECK_ACCESS":
                return BrowserAgentAgent.GoogleSheetsService.checkAccess(message.payload.spreadsheetId);
            case "GET_SERVICE_ACCOUNT":
                return BrowserAgentAgent.GoogleSheetsService.getServiceAccountEmail();
            case "GET_SOURCE_STATS": {
                const sheetName = message.payload?.sourceSheetName || BrowserAgentAgent.DEFAULT_SOURCE_SHEET_NAME;
                const columns = message.payload?.columns || BrowserAgentAgent.DEFAULT_SOURCE_COLUMNS;
                return BrowserAgentAgent.GoogleSheetsService.getSourceStats(message.payload.spreadsheetId, sheetName, columns.extracted, columns.searchTerm);
            }
            case "GET_CONFIG":
                return { ok: true, config: await getConfig(), sessionId };
            case "SAVE_CONFIG":
                return saveConfig(message.payload?.config || {});
            case "TEST_CONFIG":
                return testConfig(message.payload?.config);
            case "OBSERVE_TAB":
                return observeForPanel();
            case "EXECUTE_MANUAL_ACTION":
                return executeManualAction(message.payload?.action);
            case "RUN_TASK":
                return startRun(message.payload?.task || "");
            case "EXECUTE_SKILL_IN_TAB":
                return executeSkillInTab(message.payload?.js || "", message.payload?.parameters || {});
            case "STOP_RUN":
                stopRequested = true;
                emit({ level: "warn", title: "Stop requested", message: "The current run will stop after the active action finishes." });
                return { ok: true };
            case "PAGESJAUNES_NEEDS_HELP":
                return surfaceTabForUserAction(sender?.tab?.id, sender?.tab?.windowId, message.payload?.reason);
            default:
                return { ok: false, error: { code: "UNKNOWN_MESSAGE", message: `Unknown message type: ${message.type}` } };
        }
    }
    async function surfaceTabForUserAction(tabId, windowId, reason) {
        if (!tabId) {
            return { ok: false, error: { code: "NO_TAB", message: "Sender did not include a tab id." } };
        }
        try {
            await chrome.tabs.update(tabId, { active: true });
            if (windowId !== undefined) {
                await chrome.windows.update(windowId, { focused: true });
            }
        }
        catch (error) {
            return { ok: false, error: BrowserAgent.normalizeError(error, "TAB_FOCUS_FAILED") };
        }
        emit({
            level: "warn",
            title: "Action needed",
            message: reason === "cloudflare"
                ? "Solve the Cloudflare challenge in the focused tab. The agent will resume automatically."
                : `User action requested${reason ? `: ${reason}` : "."}`,
            type: "user.action_needed"
        });
        return { ok: true };
    }
    async function getConfig() {
        const items = await chromeStorageGet(BrowserAgent.CONFIG_KEY);
        return BrowserAgent.mergeConfig(items[BrowserAgent.CONFIG_KEY]);
    }
    async function saveConfig(config) {
        const merged = BrowserAgent.mergeConfig(config);
        await chromeStorageSet({ [BrowserAgent.CONFIG_KEY]: merged });
        return { ok: true, config: merged };
    }
    async function testConfig(configValue) {
        const config = BrowserAgent.mergeConfig(configValue || await getConfig());
        const requestId = BrowserAgent.createId("request");
        const configError = BrowserAgent.validateConfig(config);
        if (configError) {
            return { ok: false, error: configError };
        }
        try {
            const data = await requestJson(config, "/v1/browser-agent/test", {
                sessionId,
                requestId,
                model: config.model,
                client: "browser-agent-extension",
                timestamp: new Date().toISOString()
            }, requestId);
            emit({ level: "success", title: "Config test passed", message: "Server accepted the test request.", data, requestId, type: "config.test.ok" });
            return { ok: true, data };
        }
        catch (error) {
            const normalized = BrowserAgent.normalizeError(error, "CONFIG_TEST_FAILED", "Check the server URL, proxy token, and model name.");
            emit({ level: "error", title: "Config test failed", message: normalized.message, data: normalized, error: normalized, requestId, type: "config.test.failed" });
            return { ok: false, error: normalized };
        }
    }
    async function observeForPanel() {
        const observation = await observeActiveTab(await getConfig());
        emit({
            level: observation.warnings.some((warning) => warning.code === "PAGE_RESTRICTED") ? "warn" : "success",
            title: "Observed tab",
            message: observation.snapshot ? "Captured DOM and screenshot state." : "Captured tab metadata with warnings.",
            data: {
                warnings: observation.warnings,
                snapshot: observation.snapshot?.metadata,
                screenshot: summarizeScreenshot(observation.screenshot)
            },
            tab: observation.tab,
            type: "observation.manual"
        });
        return { ok: true, observation };
    }
    async function startRun(task) {
        if (running) {
            return {
                ok: false,
                error: {
                    code: "RUN_ALREADY_ACTIVE",
                    message: "A run is already active.",
                    suggestion: "Stop the current run before starting another task."
                }
            };
        }
        if (!task.trim()) {
            return {
                ok: false,
                error: {
                    code: "TASK_EMPTY",
                    message: "Task text is required."
                }
            };
        }
        const runId = BrowserAgent.createId("run");
        currentRunId = runId;
        stopRequested = false;
        running = true;
        runTask(task, runId).catch((error) => {
            const normalized = BrowserAgent.normalizeError(error);
            emit({ level: "error", title: "Run failed", message: normalized.message, data: error, error: normalized, runId, type: "run.failed" });
        }).finally(() => {
            emit({ level: "info", title: "Run idle", message: "Autopilot is idle.", runId, type: "run.idle" });
            currentRunId = undefined;
            running = false;
        });
        return { ok: true, runId };
    }
    async function runTask(task, runId) {
        const config = await getConfig();
        const configError = BrowserAgent.validateConfig(config);
        if (configError) {
            emit({ level: "error", title: "Configuration error", message: configError.message, data: configError, error: configError, runId, type: "config.invalid" });
            return;
        }
        if (!config.autopilot) {
            emit({ level: "warn", title: "Autopilot disabled", message: "Enable autopilot in configuration to run server actions.", runId, type: "run.autopilot.disabled" });
            return;
        }
        const actionLog = [];
        emit({ level: "info", title: "Run started", message: task, runId, type: "run.started", data: { task } });
        for (let step = 1; step <= config.maxSteps; step += 1) {
            if (stopRequested) {
                emit({ level: "warn", title: "Run stopped", message: "Stopped by user.", runId, type: "run.stopped" });
                return;
            }
            const observation = await observeActiveTab(config);
            emit({
                level: "info",
                title: `Step ${step} observation`,
                message: observation.snapshot
                    ? `${observation.snapshot.interactiveElements.length} controls, ${observation.snapshot.links.length} links, ${observation.snapshot.tables.length} tables.`
                    : "Captured tab metadata.",
                runId,
                type: "observation.captured",
                tab: observation.tab,
                data: {
                    warnings: observation.warnings,
                    snapshot: observation.snapshot?.metadata,
                    screenshot: summarizeScreenshot(observation.screenshot)
                }
            });
            const requestId = BrowserAgent.createId("request");
            const response = await requestJson(config, "/v1/browser-agent/run", {
                sessionId,
                runId,
                requestId,
                task,
                model: config.model,
                step,
                source: "extension",
                tab: observation.tab,
                snapshot: observation.snapshot,
                screenshot: observation.screenshot,
                warnings: observation.warnings,
                actionLog,
                events: recentEvents.slice(-20)
            }, requestId);
            emit({ level: "info", title: "Server response", message: response.mode || "response received", data: response, requestId, runId, type: "server.response", tab: observation.tab });
            const finalText = response.final || response.message;
            if (finalText && !(response.actions || response.toolActions)?.length) {
                emit({ level: "success", title: "Run complete", message: finalText, data: response, requestId, runId, type: "run.complete", tab: observation.tab });
                return;
            }
            const actions = response.actions || response.toolActions || [];
            if (!Array.isArray(actions)) {
                emit({
                    level: "error",
                    title: "Malformed server response",
                    message: "Server response must include an actions array or final text.",
                    data: response,
                    requestId,
                    runId,
                    type: "server.response.malformed",
                    tab: observation.tab
                });
                return;
            }
            if (actions.length === 0) {
                emit({
                    level: "warn",
                    title: "No server actions",
                    message: finalText || "Server returned no final text and no actions.",
                    data: response,
                    requestId,
                    runId,
                    type: "server.response.empty",
                    tab: observation.tab
                });
                return;
            }
            for (const action of actions) {
                if (stopRequested) {
                    emit({ level: "warn", title: "Run stopped", message: "Stopped by user.", runId, requestId, type: "run.stopped", tab: observation.tab });
                    return;
                }
                const result = await executeAction(action, config);
                actionLog.push(result);
                emit({
                    level: result.ok ? "success" : "error",
                    title: `${action.type}: ${result.ok ? "ok" : "failed"}`,
                    message: result.message,
                    data: { action, result },
                    error: result.error,
                    runId,
                    requestId,
                    actionId: result.actionId,
                    type: result.ok ? "action.ok" : "action.failed",
                    tab: observation.tab
                });
                if (!result.ok) {
                    return;
                }
            }
        }
        emit({
            level: "warn",
            title: "Max steps reached",
            message: `Stopped after ${config.maxSteps} autopilot steps.`,
            data: actionLog,
            runId,
            type: "run.max_steps"
        });
    }
    async function observeActiveTab(config) {
        const tab = await getActiveTab();
        const warnings = [];
        let snapshot;
        let screenshot;
        const restrictedWarning = restrictedPageWarning(tab.url);
        if (restrictedWarning) {
            warnings.push(restrictedWarning);
            return {
                tab: {
                    id: tab.id,
                    url: tab.url,
                    title: tab.title,
                    status: tab.status
                },
                warnings
            };
        }
        if (config.captureDom) {
            try {
                await ensureContentScript(tab.id);
                const response = await sendTabMessage(tab.id, {
                    type: "GET_PAGE_SNAPSHOT",
                    payload: { maxTextChars: config.maxDomTextChars }
                });
                if (!response?.ok) {
                    throw new Error(response?.error?.message || "Content script did not return a snapshot.");
                }
                snapshot = response.snapshot;
            }
            catch (error) {
                warnings.push(BrowserAgent.normalizeError(error, "DOM_SNAPSHOT_FAILED", "Reload the page or grant host access, then try again."));
            }
        }
        if (config.captureScreenshot) {
            try {
                screenshot = await captureVisibleScreenshot(config);
            }
            catch (error) {
                warnings.push(BrowserAgent.normalizeError(error, "SCREENSHOT_FAILED", "Use a normal web page tab and avoid restricted Chrome pages."));
            }
        }
        return {
            tab: {
                id: tab.id,
                url: tab.url,
                title: tab.title,
                status: tab.status
            },
            snapshot,
            screenshot,
            warnings
        };
    }
    async function executeManualAction(action) {
        if (!action) {
            return { ok: false, error: { code: "ACTION_MISSING", message: "Manual action is missing." } };
        }
        const config = await getConfig();
        const result = await executeAction(action, config);
        return { ok: result.ok, result };
    }
    async function executeSkillInTab(js, parameters) {
        if (!js) {
            return { ok: false, error: { code: "SKILL_EMPTY", message: "No JS code provided." } };
        }
        try {
            const tab = await getActiveTab();
            const restrictedWarning = restrictedPageWarning(tab.url);
            if (restrictedWarning) {
                return { ok: false, error: restrictedWarning };
            }
            await ensureContentScript(tab.id);
            const response = await sendTabMessage(tab.id, {
                type: "EXECUTE_SKILL",
                payload: { js, parameters }
            });
            return response;
        }
        catch (error) {
            return {
                ok: false,
                result: {
                    ok: false,
                    tabUrl: "",
                    error: BrowserAgent.normalizeError(error, "SKILL_INJECTION_FAILED")
                }
            };
        }
    }
    async function executeAction(action, config) {
        const actionId = BrowserAgent.actionId(action);
        const startedAt = BrowserAgent.nowIso();
        const startedTime = performance.now();
        try {
            if (!action.type) {
                throw new Error("Action type is required.");
            }
            if (action.type === "captureScreenshot") {
                const screenshot = await captureVisibleScreenshot(config);
                await showPageToast("Captured screenshot");
                return withActionTiming({
                    ok: true,
                    actionId,
                    message: "Captured visible tab screenshot.",
                    data: { screenshot },
                    animation: { type: "toast", durationMs: 1800 }
                }, startedAt, startedTime);
            }
            const tab = await getActiveTab();
            if (action.type === "navigate") {
                const url = String(action.args?.url || action.target?.text || "");
                if (!url) {
                    throw new Error("Navigate action requires args.url.");
                }
                await showPageToast(`Navigating to ${url}`);
                await chromeTabsUpdate(tab.id, { url });
                return withActionTiming({ ok: true, actionId, message: `Navigated to ${url}.`, animation: { type: "toast", durationMs: 1800 } }, startedAt, startedTime);
            }
            if (action.type === "goBack") {
                await showPageToast("Going back");
                await chrome.tabs.goBack(tab.id);
                return withActionTiming({ ok: true, actionId, message: "Navigated back.", animation: { type: "toast", durationMs: 1800 } }, startedAt, startedTime);
            }
            if (action.type === "goForward") {
                await showPageToast("Going forward");
                await chrome.tabs.goForward(tab.id);
                return withActionTiming({ ok: true, actionId, message: "Navigated forward.", animation: { type: "toast", durationMs: 1800 } }, startedAt, startedTime);
            }
            if (action.type === "askForHelp") {
                await showPageToast("Agent stopped to ask for help.");
                return withActionTiming({ ok: false, actionId, message: "Agent requested help: " + (action.args?.reason || "No reason given.") }, startedAt, startedTime);
            }
            await ensureContentScript(tab.id);
            const response = await sendTabMessage(tab.id, {
                type: "EXECUTE_ACTION",
                payload: { action: { ...action, id: actionId }, maxTextChars: config.maxDomTextChars }
            });
            if (!response?.ok) {
                throw new Error(response?.error?.message || "Action failed in the page.");
            }
            return response.result;
        }
        catch (error) {
            return {
                ok: false,
                actionId,
                message: BrowserAgent.normalizeError(error).message,
                error: BrowserAgent.normalizeError(error, "ACTION_FAILED"),
                startedAt,
                endedAt: BrowserAgent.nowIso(),
                durationMs: Math.round(performance.now() - startedTime)
            };
        }
    }
    async function getActiveTab() {
        const tabs = await chromeTabsQuery({ active: true, currentWindow: true });
        const tab = tabs[0] || (await chromeTabsQuery({ active: true, lastFocusedWindow: true }))[0];
        if (!tab?.id) {
            throw new Error("No active tab is available.");
        }
        return tab;
    }
    async function ensureContentScript(tabId) {
        try {
            const ping = await sendTabMessage(tabId, { type: "PING" });
            if (ping?.ok) {
                return;
            }
        }
        catch {
            // Inject below.
        }
        try {
            await chromeScriptingExecuteScript({
                target: { tabId, allFrames: false },
                files: ["shared.js", "content-script.js"]
            });
        }
        catch (error) {
            throw new Error(`Unable to inject content script: ${BrowserAgent.normalizeError(error).message}`);
        }
    }
    async function captureVisibleScreenshot(config) {
        const now = Date.now();
        const elapsed = now - lastScreenshotAt;
        if (elapsed < 600) {
            await delay(600 - elapsed);
        }
        lastScreenshotAt = Date.now();
        const dataUrl = await chromeTabsCaptureVisibleTab({ format: "jpeg", quality: 80 });
        return resizeScreenshot(dataUrl, config.maxScreenshotWidth).catch(() => dataUrl);
    }
    async function resizeScreenshot(dataUrl, maxWidth) {
        if (!("OffscreenCanvas" in self) || !("createImageBitmap" in self)) {
            return dataUrl;
        }
        const blob = await (await fetch(dataUrl)).blob();
        const bitmap = await createImageBitmap(blob);
        if (bitmap.width <= maxWidth) {
            return dataUrl;
        }
        const scale = maxWidth / bitmap.width;
        const width = Math.round(bitmap.width * scale);
        const height = Math.round(bitmap.height * scale);
        const canvas = new OffscreenCanvas(width, height);
        const context = canvas.getContext("2d");
        if (!context) {
            return dataUrl;
        }
        context.drawImage(bitmap, 0, 0, width, height);
        const outputBlob = await canvas.convertToBlob({ type: "image/jpeg", quality: 0.78 });
        const buffer = await outputBlob.arrayBuffer();
        const bytes = new Uint8Array(buffer);
        let binary = "";
        for (const byte of bytes) {
            binary += String.fromCharCode(byte);
        }
        return `data:image/jpeg;base64,${btoa(binary)}`;
    }
    async function requestJson(config, path, body, requestId) {
        const controller = new AbortController();
        const timer = setTimeout(() => controller.abort(), config.requestTimeoutMs);
        try {
            const response = await fetch(BrowserAgent.endpointUrl(config, path), {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    ...(requestId ? { "X-Request-ID": requestId } : {}),
                    ...(config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {})
                },
                body: JSON.stringify(body),
                signal: controller.signal
            });
            const text = await response.text();
            let parsed;
            try {
                parsed = text ? JSON.parse(text) : {};
            }
            catch {
                throw new Error(`Server returned non-JSON response (${response.status}): ${text.slice(0, 160)}`);
            }
            if (!response.ok) {
                const serverError = extractServerError(parsed);
                const suffix = serverError.requestId ? ` Request ID: ${serverError.requestId}.` : "";
                throw new Error(`${serverError.message || `Server returned HTTP ${response.status}.`}${suffix}`);
            }
            return parsed;
        }
        catch (error) {
            if (error.name === "AbortError") {
                throw new Error(`Server request timed out after ${config.requestTimeoutMs}ms.`);
            }
            throw error;
        }
        finally {
            clearTimeout(timer);
        }
    }
    function emit(event) {
        const enriched = {
            ...event,
            sessionId,
            runId: event.runId || currentRunId,
            source: event.source || "extension",
            type: event.type || event.title.toLowerCase().replace(/[^a-z0-9]+/g, ".").replace(/^\.+|\.+$/g, ""),
            timestamp: event.timestamp || BrowserAgent.nowIso()
        };
        chrome.runtime.sendMessage({ type: "RUN_EVENT", event: enriched }).catch(() => undefined);
        rememberAndSendLog(enriched);
    }
    function rememberAndSendLog(event) {
        const logEvent = {
            sessionId: event.sessionId,
            runId: event.runId,
            requestId: event.requestId,
            actionId: event.actionId,
            level: event.level,
            source: event.source || "extension",
            type: event.type || "event",
            message: event.message,
            tab: event.tab,
            payload: sanitizeForLog(event.data),
            error: event.error,
            timestamp: event.timestamp || BrowserAgent.nowIso()
        };
        recentEvents.push(logEvent);
        if (recentEvents.length > 80) {
            recentEvents.splice(0, recentEvents.length - 80);
        }
        sendLogEvent(logEvent).catch(() => undefined);
    }
    async function sendLogEvent(event) {
        const config = await getConfig();
        if (BrowserAgent.validateConfig(config)) {
            return;
        }
        await fetch(BrowserAgent.endpointUrl(config, "/v1/browser-agent/logs"), {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                ...(config.authToken ? { Authorization: `Bearer ${config.authToken}` } : {})
            },
            body: JSON.stringify({ events: [event] })
        });
    }
    function restrictedPageWarning(url) {
        if (!url) {
            return null;
        }
        const restrictedPrefixes = ["chrome://", "chrome-extension://", "edge://", "about:"];
        const restrictedHosts = ["chrome.google.com", "chromewebstore.google.com"];
        if (restrictedPrefixes.some((prefix) => url.startsWith(prefix))) {
            return pageRestrictedWarning(url);
        }
        try {
            const parsed = new URL(url);
            if (restrictedHosts.includes(parsed.hostname)) {
                return pageRestrictedWarning(url);
            }
        }
        catch {
            return null;
        }
        return null;
    }
    function pageRestrictedWarning(url) {
        return {
            code: "PAGE_RESTRICTED",
            message: "Chrome does not allow extensions to inspect this page. Open a normal website tab and try again.",
            details: { url },
            suggestion: "Open http://localhost:14173 or another regular website tab before using Observe or Run."
        };
    }
    async function showPageToast(message) {
        try {
            const tab = await getActiveTab();
            if (restrictedPageWarning(tab.url)) {
                return;
            }
            await ensureContentScript(tab.id);
            await sendTabMessage(tab.id, { type: "SHOW_TOAST", payload: { message } });
        }
        catch {
            // Toasts are helpful but not required for action success.
        }
    }
    function withActionTiming(result, startedAt, startedTime) {
        return {
            ...result,
            startedAt,
            endedAt: BrowserAgent.nowIso(),
            durationMs: Math.round(performance.now() - startedTime)
        };
    }
    function summarizeScreenshot(screenshot) {
        if (!screenshot) {
            return undefined;
        }
        return {
            present: true,
            bytesApprox: Math.round(screenshot.length * 0.75),
            dataUrlPrefix: screenshot.slice(0, 30)
        };
    }
    function sanitizeForLog(value) {
        if (typeof value === "string") {
            return value.startsWith("data:image/") ? summarizeScreenshot(value) : value;
        }
        if (Array.isArray(value)) {
            return value.map(sanitizeForLog);
        }
        if (value && typeof value === "object") {
            const output = {};
            for (const [key, item] of Object.entries(value)) {
                output[key] = key.toLowerCase().includes("screenshot") ? summarizeScreenshot(String(item || "")) : sanitizeForLog(item);
            }
            return output;
        }
        return value;
    }
    function delay(ms) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }
    function chromeStorageGet(key) {
        return new Promise((resolve, reject) => {
            chrome.storage.local.get([key], (items) => {
                const error = chrome.runtime.lastError;
                if (error) {
                    reject(error);
                    return;
                }
                resolve(items);
            });
        });
    }
    function chromeStorageSet(value) {
        return new Promise((resolve, reject) => {
            chrome.storage.local.set(value, () => {
                const error = chrome.runtime.lastError;
                if (error) {
                    reject(error);
                    return;
                }
                resolve();
            });
        });
    }
    function chromeTabsQuery(query) {
        return chrome.tabs.query(query);
    }
    function chromeTabsUpdate(tabId, update) {
        return chrome.tabs.update(tabId, update);
    }
    function chromeTabsCaptureVisibleTab(options) {
        return chrome.tabs.captureVisibleTab(options);
    }
    function chromeScriptingExecuteScript(details) {
        return chrome.scripting.executeScript(details);
    }
    function sendTabMessage(tabId, message) {
        return chrome.tabs.sendMessage(tabId, message);
    }
    function extractServerError(parsed) {
        if (!parsed || typeof parsed !== "object") {
            return {};
        }
        const value = parsed;
        return {
            message: value.error?.message ? String(value.error.message) : value.message ? String(value.message) : undefined,
            requestId: value.error?.requestId ? String(value.error.requestId) : value.requestId ? String(value.requestId) : undefined
        };
    }
})(BrowserAgentBackground || (BrowserAgentBackground = {}));
//# sourceMappingURL=background.js.map