import { takeScreenshot } from "../tools/screenshot.js";
import { logger } from "../logger.js";
import { formatNowWithTz } from "./context.js";
const DEFAULT_MIN_INTERVAL_MS = 180_000;
const DEFAULT_MAX_PER_CYCLE = 2;
/**
 * Playwright tools that do not warrant a follow-up desktop screenshot.
 * Playwright's accessibility snapshot is usually enough for read-only
 * queries and low-impact form interactions.
 */
const PLAYWRIGHT_SCREENSHOT_EXCLUDED = new Set([
    "browser_snapshot",
    "browser_console_messages",
    "browser_network_events",
    "browser_type",
    "browser_hover",
    "browser_select_option",
]);
/**
 * Extract the base tool name from a possibly MCP-prefixed name.
 * e.g. "mcp__playwright__browser_click" -> "browser_click"
 */
function baseName(toolName) {
    const idx = toolName.lastIndexOf("__");
    return idx >= 0 ? toolName.slice(idx + 2) : toolName;
}
function isPlaywrightInteraction(toolName) {
    const name = baseName(toolName);
    const isBrowserMcp = toolName.includes("playwright") || toolName.includes("playwriter");
    if (!isBrowserMcp)
        return false;
    return !PLAYWRIGHT_SCREENSHOT_EXCLUDED.has(name);
}
/**
 * Automatically injects a desktop screenshot into the agent session
 * after Playwright MCP tool calls that mutate browser state.
 *
 * Computer-use tools already return screenshots in their tool output,
 * so only Playwright tools (which return text accessibility snapshots)
 * need this supplemental injection.
 */
export class ScreenshotInjector {
    lastInjectMs = 0;
    injectCount = 0;
    inFlight = false;
    minIntervalMs;
    maxPerCycle;
    constructor(options) {
        this.minIntervalMs = options?.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
        this.maxPerCycle = options?.maxPerCycle ?? DEFAULT_MAX_PER_CYCLE;
    }
    /**
     * Called from the PostToolUse hook after each tool completes.
     * If the tool is a Playwright interaction and rate limits allow,
     * captures a screenshot and injects it into the active session.
     */
    async onToolComplete(toolName, session) {
        // TODO: currently only inject screenshots for Playwright tools, but we may need to inject for non-playwright tools as well
        if (!isPlaywrightInteraction(toolName))
            return;
        if (this.inFlight)
            return;
        if (this.injectCount >= this.maxPerCycle)
            return;
        const now = Date.now();
        if (now - this.lastInjectMs < this.minIntervalMs)
            return;
        if (session.isInputClosed)
            return;
        this.inFlight = true;
        try {
            const { base64 } = await takeScreenshot();
            this.lastInjectMs = Date.now();
            this.injectCount++;
            const injected = session.injectMessage([
                {
                    type: "text",
                    text: `[Auto Screenshot] time=${formatNowWithTz()} — Desktop state after ${toolName}:`,
                },
                {
                    type: "image",
                    source: { type: "base64", media_type: "image/png", data: base64 },
                },
            ]);
            if (injected) {
                logger.debug(`[screenshot-injector] injected after ${toolName} (${this.injectCount}/${this.maxPerCycle})`);
            }
        }
        catch (err) {
            logger.warn(`[screenshot-injector] failed after ${toolName}: ${err instanceof Error ? err.message : String(err)}`);
        }
        finally {
            this.inFlight = false;
        }
    }
    /** Reset counters at the start of each wake cycle. */
    reset() {
        this.lastInjectMs = 0;
        this.injectCount = 0;
        this.inFlight = false;
    }
}
//# sourceMappingURL=screenshot-injector.js.map