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Q,MAAM,uBAAwB,EAAQ,GAEtD,CACA,OAAO,OAAO,IACV,QAAQ,MAAM,gBAAiB,GAC/B,QAAQ,KAAK,EAAE","file":"/npm/cdp-tools-mcp@0.4.1/build/index.js","sourceRoot":"","sourcesContent":["/**\n * Minified by jsDelivr using Terser v5.39.0.\n * Original file: /npm/cdp-tools-mcp@0.4.1/build/index.js\n *\n * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files\n */\n","#!/usr/bin/env node\n// Early stderr logging for debugging startup issues\nconsole.error(`[cdp-tools] Process starting (PID: ${process.pid})`);\n// Capture startup time immediately before any imports\nconst STARTUP_TIME = performance.now();\n/**\n * cdp-tools-mcp\n * MCP server providing Chrome DevTools Protocol debugging capabilities to AI assistants\n */\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';\nimport { z } from 'zod';\nimport { CDPManager } from './cdp-manager.js';\nimport { SourceMapHandler } from './sourcemap-handler.js';\nimport { ChromeLauncher } from './chrome-launcher.js';\nimport { PuppeteerManager } from './puppeteer-manager.js';\nimport { ConsoleMonitor } from './console-monitor.js';\nimport { NetworkMonitor } from './network-monitor.js';\nimport { ConnectionManager } from './connection-manager.js';\nimport { LogpointExecutionTracker } from './logpoint-execution-tracker.js';\nimport { PortReserver } from './port-reserver.js';\nimport { validateParams, createTool } from './validation-helpers.js';\nimport { ClickableCache } from './clickable-cache.js';\nimport { CommandRecorder } from './command-recorder.js';\nimport { createBreakpointTools } from './tools/breakpoint-tools.js';\nimport { createExecutionTools } from './tools/execution-tools.js';\nimport { createInspectionTools } from './tools/inspection-tools.js';\nimport { createSourceTools } from './tools/source-tools.js';\nimport { createConsoleTools } from './tools/console-tools.js';\nimport { createNetworkTools } from './tools/network-tools.js';\nimport { createPageTools } from './tools/page-tools.js';\nimport { createDOMTools } from './tools/dom-tools.js';\nimport { createScreenshotTools } from './tools/screenshot-tools.js';\nimport { createInputTools } from './tools/input-tools.js';\nimport { createContentTools } from './tools/content-tools.js';\nimport { createStorageTools } from './tools/storage-tools.js';\nimport { createTabTools } from './tools/tab-tools.js';\nimport { createDownloadTools } from './tools/download-tools.js';\nimport { createModalTools } from './tools/modal-tools.js';\nimport { createReplayTools } from './tools/replay-tools.js';\nimport { createServerTools } from './tools/server-tools.js';\nimport { createConfigTools } from './tools/config-tools.js';\nimport { createIssuesTools } from './tools/issues-tools.js';\nimport { ServerManager } from './server-manager.js';\nimport { configManager } from './config.js';\nimport { checkPortFailures, checkBreakpointPause, checkBugBlocking, checkPendingStartups, prependToResponse, appendToResponse, buildStatusSuffix } from './tool-response.js';\nimport { createSuccessResponse, createErrorResponse } from './messages.js';\nimport { setChromeLauncher } from './error-helpers.js';\nimport { createServer } from 'net';\nimport { readFile } from 'fs/promises';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { debugLog, enableDebugLogging, disableDebugLogging, isDebugEnabled, enableHistoryLogging, setStartupMetrics } from './debug-logger.js';\nimport { validateReference, requireValidReference, UNNAMED_CONNECTION, InvalidReferenceError } from './reference-validator.js';\nimport { initializePaths } from './helpers/paths.js';\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n/**\n * Find an available port starting from the given port\n */\nasync function findAvailablePort(startPort) {\n    return new Promise((resolve, reject) => {\n        const server = createServer();\n        // Explicitly bind to IPv4 localhost to match Chrome's behavior\n        server.listen(startPort, '127.0.0.1', () => {\n            const port = server.address().port;\n            console.error(`[cdp-tools] findAvailablePort: Port ${port} is available`);\n            server.close(() => resolve(port));\n        });\n        server.on('error', (err) => {\n            if (err.code === 'EADDRINUSE') {\n                // Port in use, try next one\n                console.error(`[cdp-tools] findAvailablePort: Port ${startPort} is in use, trying ${startPort + 1}`);\n                resolve(findAvailablePort(startPort + 1));\n            }\n            else {\n                reject(err);\n            }\n        });\n    });\n}\n/**\n * Find starting port from environment variable or auto-assign\n */\nasync function findStartingPort() {\n    const envPort = process.env.MCP_DEBUG_PORT;\n    const startingPort = configManager.getChromeConfig().startingDebugPort;\n    if (envPort) {\n        const port = parseInt(envPort, 10);\n        if (isNaN(port) || port < 1024 || port > 65535) {\n            console.error(`Invalid MCP_DEBUG_PORT: ${envPort}. Using auto-assigned port.`);\n            return findAvailablePort(startingPort);\n        }\n        return port;\n    }\n    return findAvailablePort(startingPort);\n}\n/**\n * Load instructions from docs/instructions.md\n */\nasync function loadInstructions() {\n    try {\n        const instructionsPath = join(__dirname, '..', 'docs', 'instructions.md');\n        return await readFile(instructionsPath, 'utf-8');\n    }\n    catch (error) {\n        console.error('[cdp-tools] Failed to load instructions file:', error instanceof Error ? error.message : error);\n        return undefined;\n    }\n}\n// Initialize global managers\nconst sourceMapHandler = new SourceMapHandler();\nconst chromeLauncher = new ChromeLauncher();\nconst connectionManager = new ConnectionManager();\nconst logpointTracker = new LogpointExecutionTracker();\nconst clickableCache = new ClickableCache();\nconst commandRecorder = new CommandRecorder();\nconst portReserver = new PortReserver();\nconst serverManager = new ServerManager();\n// Configure connection manager to kill Chrome when last connection closes\nconnectionManager.setChromeLauncher(chromeLauncher);\n// Set ChromeLauncher reference for error-helpers (used to verify Chrome is running)\nsetChromeLauncher(chromeLauncher);\n// Set up Chrome exit callback to clean up connections and reserve a new port\nchromeLauncher.setOnExitCallback(async (event) => {\n    const { port } = event;\n    await debugLog('index', `Chrome exited on port ${port} (reason: ${event.reason})`);\n    // Clean up all connections for the dead Chrome instance\n    // Note: ChromeLauncher only launches on localhost, so this is always correct\n    const connectionsToClose = connectionManager.getConnectionsForBrowser('localhost', port);\n    for (const conn of connectionsToClose) {\n        try {\n            await connectionManager.closeConnection(conn.id);\n            await debugLog('index', `Closed connection ${conn.id} after Chrome exit`);\n        }\n        catch (closeError) {\n            await debugLog('index', `Failed to close connection ${conn.id}: ${closeError}`);\n        }\n    }\n    // Reserve a new port for future launches\n    try {\n        const startingPort = configManager.getChromeConfig().startingDebugPort;\n        const newPort = await findAvailablePort(startingPort);\n        await portReserver.reserve(newPort);\n        configManager.setCurrentPort(newPort);\n        await debugLog('index', `Reserved new port ${newPort}`);\n    }\n    catch (error) {\n        await debugLog('index', `Failed to reserve new port after Chrome exit: ${error}`);\n    }\n});\n/**\n * Create and configure the MCP server with instructions\n */\nasync function createMCPServer() {\n    const instructions = await loadInstructions();\n    return new Server({\n        name: 'cdp-tools-debugger',\n        version: '0.1.0',\n    }, {\n        capabilities: {\n            tools: {},\n        },\n        instructions,\n    });\n}\n/**\n * Wait for Chrome debugging port to become ready\n * Polls the /json/version endpoint until Chrome is inspectable\n */\nasync function waitForChromeReady(port, maxAttempts = 10) {\n    for (let i = 0; i < maxAttempts; i++) {\n        try {\n            const controller = new AbortController();\n            const timeoutId = setTimeout(() => controller.abort(), 1000);\n            const response = await fetch(`http://localhost:${port}/json/version`, {\n                signal: controller.signal\n            });\n            clearTimeout(timeoutId);\n            if (response.ok) {\n                // Chrome is ready and inspectable\n                return;\n            }\n        }\n        catch (error) {\n            // Chrome not ready yet, continue polling\n        }\n        // Exponential backoff: 500ms + (attempt * 200ms)\n        await new Promise(resolve => setTimeout(resolve, 500 + i * 200));\n    }\n    throw new Error(`Chrome debugging port ${port} failed to become inspectable within timeout. Try increasing the wait time or check if Chrome started correctly.`);\n}\n/**\n * Check if Chrome is running and accessible on the specified port\n * Returns true if Chrome is responding to debug protocol requests\n * Returns false if port is reserved (chrome-not-running) or connection fails\n */\nasync function isChromeRunning(port) {\n    try {\n        const controller = new AbortController();\n        const timeoutId = setTimeout(() => controller.abort(), 1000);\n        const response = await fetch(`http://localhost:${port}/json/version`, {\n            signal: controller.signal\n        });\n        clearTimeout(timeoutId);\n        // Check if this is the port reserver responding\n        const text = await response.text();\n        if (text.trim() === 'chrome-not-running') {\n            return false;\n        }\n        // Otherwise, check if we got a valid Chrome response\n        return response.ok;\n    }\n    catch {\n        return false;\n    }\n}\n// Connection management tools\nconst connectionTools = {\n    launchChrome: createTool('Launch Chrome with debugging', z.object({\n        url: z.string().optional().describe('URL to open (default: blank page)'),\n        autoConnect: z.boolean().optional().default(true).describe('Automatically connect debugger after launch'),\n        port: z.number().optional().describe('The debugging port (optional, defaults to this session\\'s reserved port). Use this to launch multiple Chrome instances on different ports.'),\n        headless: z.boolean().optional().default(false).describe('Launch in headless mode (no visible window, prevents focus stealing). Default: false'),\n        reference: z.string().optional().describe('Connection reference name (3 descriptive words). If not provided, defaults to \"unnamed-connection-default\". Use this to identify the connection when calling other tools.'),\n        width: z.number().optional().describe('Viewport width in pixels (optional). If set, the browser viewport will be resized after launch.'),\n        height: z.number().optional().describe('Viewport height in pixels (optional). If set, the browser viewport will be resized after launch.'),\n    }).strict(), async (args) => {\n        // Validate reference FIRST, before launching Chrome\n        const userReference = args.reference;\n        if (userReference) {\n            requireValidReference(userReference); // Throws InvalidReferenceError if invalid\n        }\n        // Use reserved port unless explicitly specified\n        const port = args.port || configManager.getCurrentPort();\n        await debugLog('index', `launchChrome called: port=${port}, requested=${args.port}, reserved=${configManager.getCurrentPort()}, url=${args.url}, autoConnect=${args.autoConnect}, reference=${args.reference}`);\n        const url = args.url;\n        const autoConnect = args.autoConnect ?? true;\n        // Check if a connection with this reference already exists - reuse it instead of creating a new tab\n        // Use validated lookup to auto-cleanup dead connections (e.g., if Chrome was killed externally)\n        if (userReference) {\n            const existingConnection = await connectionManager.findConnectionByReferenceValidated(userReference);\n            if (existingConnection) {\n                const sanitizedRef = validateReference(userReference).sanitized;\n                await debugLog('index', `Connection with reference \"${sanitizedRef}\" already exists, reusing`);\n                // Set as active connection\n                connectionManager.setActiveConnection(existingConnection.id);\n                updateActiveManagers(existingConnection.id);\n                // Get current page info\n                let title = 'Unknown';\n                let pageUrl = 'about:blank';\n                if (existingConnection.puppeteerManager) {\n                    const page = existingConnection.puppeteerManager.getPage();\n                    pageUrl = page.url();\n                    title = await page.title();\n                }\n                return createSuccessResponse('CHROME_CONNECTION_REUSED', {\n                    reference: sanitizedRef,\n                    title,\n                    url: pageUrl\n                });\n            }\n        }\n        try {\n            // Check if Chrome is already running on this port\n            // We check both connectionManager (tracked connections) and chromeLauncher (actual process)\n            // This handles the case where a tab was closed but Chrome is still running\n            const browserAlreadyExists = connectionManager.hasBrowser('localhost', port) || chromeLauncher.isRunning(port);\n            await debugLog('index', `browserAlreadyExists: ${browserAlreadyExists} (hasBrowser: ${connectionManager.hasBrowser('localhost', port)}, isRunning: ${chromeLauncher.isRunning(port)})`);\n            let isNewBrowser = false;\n            if (!browserAlreadyExists) {\n                await debugLog('index', `Launching new Chrome instance on port ${port}...`);\n                // Launch new Chrome instance (will release port reservation)\n                // Don't pass URL to launch if auto-connect is enabled - let Puppeteer handle navigation\n                // This prevents race condition where Chrome starts loading before monitors are set up\n                const launchUrl = autoConnect ? undefined : url;\n                const result = await chromeLauncher.launch(port, launchUrl, portReserver, args.headless);\n                await debugLog('index', `Chrome launched successfully: ${JSON.stringify(result)}`);\n                isNewBrowser = true;\n            }\n            // Auto-connect if requested\n            let connectionId;\n            let runtimeType;\n            let title = 'New Tab';\n            let pageUrl = 'about:blank';\n            let consoleStats = '';\n            let viewportSet;\n            if (autoConnect) {\n                try {\n                    // Chrome is already ready (launch() waits for port binding)\n                    // Add small delay for new browser to ensure full initialization\n                    if (isNewBrowser) {\n                        await debugLog('index', `Waiting 500ms for new Chrome browser to stabilize...`);\n                        await new Promise(resolve => setTimeout(resolve, 500));\n                    }\n                    // Create connection managers for this tab\n                    const cdpManager = new CDPManager(sourceMapHandler);\n                    const puppeteerManager = new PuppeteerManager();\n                    const consoleMonitor = new ConsoleMonitor();\n                    const networkMonitor = new NetworkMonitor();\n                    // For existing browser, connect Puppeteer first and create/reuse a tab\n                    // This ensures we have a target to connect CDP to (handles case where all tabs were closed)\n                    let targetId;\n                    if (browserAlreadyExists) {\n                        await debugLog('index', `Browser exists, connecting Puppeteer and creating new tab first...`);\n                        await puppeteerManager.connect('localhost', port);\n                        // Get all existing pages\n                        const existingPages = await puppeteerManager.getPages();\n                        await debugLog('index', `Found ${existingPages.length} existing pages`);\n                        // Create a new page for this connection\n                        const page = await puppeteerManager.newPage();\n                        // Close any existing blank pages to avoid clutter\n                        for (const existingPage of existingPages) {\n                            try {\n                                const pageUrl = existingPage.url();\n                                if (pageUrl === 'about:blank' || pageUrl === 'chrome://newtab/') {\n                                    await debugLog('index', `Closing blank page: ${pageUrl}`);\n                                    await existingPage.close();\n                                }\n                            }\n                            catch (e) {\n                                // Page might already be closed, ignore\n                            }\n                        }\n                        // Get the target ID of the new page so we can connect CDP to it specifically\n                        const target = page.target();\n                        targetId = target._targetId || target._targetInfo?.targetId;\n                        await debugLog('index', `Created new tab with targetId: ${targetId}`);\n                    }\n                    // Connect to CDP (with specific target if we created a new tab)\n                    await cdpManager.connect('localhost', port, targetId);\n                    runtimeType = cdpManager.getRuntimeType();\n                    // Connect Puppeteer for Chrome (if not already connected)\n                    if (runtimeType === 'chrome' && !browserAlreadyExists) {\n                        await puppeteerManager.connect('localhost', port);\n                    }\n                    if (runtimeType === 'chrome') {\n                        // Start monitoring console and network\n                        const page = puppeteerManager.getPage();\n                        consoleMonitor.startMonitoring(page);\n                        networkMonitor.startMonitoring(page);\n                        // Register logpoint tracker callback on this connection's console monitor\n                        consoleMonitor.onMessage((message) => {\n                            logpointTracker.handleConsoleMessage(message);\n                        });\n                        // Set viewport dimensions if specified\n                        if (args.width !== undefined || args.height !== undefined) {\n                            const currentViewport = page.viewport() || { width: 800, height: 600 };\n                            const newViewport = {\n                                width: args.width ?? currentViewport.width,\n                                height: args.height ?? currentViewport.height,\n                            };\n                            await page.setViewport(newViewport);\n                            viewportSet = newViewport;\n                            await debugLog('index', `Set viewport to ${newViewport.width}x${newViewport.height}`);\n                        }\n                        // Navigate to URL if provided\n                        if (url) {\n                            await debugLog('index', `Navigating to URL: ${url}`);\n                            await page.goto(url, { waitUntil: 'load', timeout: 30000 });\n                            await debugLog('index', `Navigation to ${url} completed`);\n                        }\n                        // Auto-reload page to capture initial console logs (only if not navigating and has content)\n                        const currentUrl = page.url();\n                        if (!url && currentUrl && currentUrl !== 'about:blank') {\n                            try {\n                                await page.reload({ waitUntil: 'load', timeout: 5000 });\n                                await new Promise(resolve => setTimeout(resolve, 500));\n                            }\n                            catch (reloadError) {\n                                console.error(`[cdp-tools] Warning: Page reload failed: ${reloadError.message}`);\n                            }\n                        }\n                    }\n                    // Get page index for tracking\n                    const pages = await puppeteerManager.getPages();\n                    const currentPage = puppeteerManager.getPage();\n                    const pageIndex = pages.findIndex(p => p === currentPage);\n                    // Register connection with user-provided reference or default\n                    // Reference was already validated at the start of the handler\n                    let connectionReference = UNNAMED_CONNECTION;\n                    if (userReference) {\n                        // Use the sanitized version (lowercase with hyphens)\n                        const validation = validateReference(userReference);\n                        connectionReference = validation.sanitized;\n                    }\n                    connectionId = connectionManager.createConnection(cdpManager, puppeteerManager, consoleMonitor, networkMonitor, 'localhost', port, connectionReference, pageIndex);\n                    // Update active manager references\n                    updateActiveManagers(connectionId);\n                    // Get page info for Chrome connections\n                    if (runtimeType === 'chrome') {\n                        const page = puppeteerManager.getPage();\n                        pageUrl = page.url();\n                        title = await page.title();\n                        // Get console stats and update cursor so first tool call doesn't re-report these\n                        const logStats = consoleMonitor.getLogStats();\n                        if (logStats.totalMessages > 0) {\n                            const details = [];\n                            const errorCount = logStats.newErrors;\n                            const warnCount = logStats.newWarnings;\n                            const otherCount = logStats.totalMessages - errorCount - warnCount;\n                            if (errorCount > 0)\n                                details.push(`${errorCount} err`);\n                            if (warnCount > 0)\n                                details.push(`${warnCount} warn`);\n                            if (otherCount > 0)\n                                details.push(`${otherCount} log`);\n                            consoleStats = `\\n**Console:** ${details.join('/')}`;\n                        }\n                    }\n                }\n                catch (connectError) {\n                    // Log the auto-connect failure\n                    await debugLog('index', `Auto-connect failed: ${connectError}`);\n                    // If auto-connect fails, return detailed error\n                    const errorMessage = connectError instanceof Error ? connectError.message : String(connectError);\n                    return createSuccessResponse('CHROME_LAUNCH_AUTO_CONNECT_FAILED', {\n                        port: port.toString(),\n                        error: errorMessage,\n                        suggestion: 'Chrome launched but auto-connect failed. Try manually connecting with connectDebugger().'\n                    }, {\n                        port: port,\n                        isNewBrowser,\n                    });\n                }\n            }\n            // Format response based on whether auto-connect was used\n            if (autoConnect) {\n                const connection = connectionManager.getConnection(connectionId);\n                const reference = connection?.reference || UNNAMED_CONNECTION;\n                return createSuccessResponse('CHROME_LAUNCH_SUCCESS', {\n                    reference,\n                    title: title || '(no title)',\n                    url: pageUrl,\n                    consoleStats: consoleStats || undefined,\n                    hasUserReference: !!userReference,\n                    viewport: viewportSet,\n                });\n            }\n            else {\n                return createSuccessResponse('CHROME_LAUNCH_NO_CONNECT', { port: port.toString() }, { port, isNewBrowser });\n            }\n        }\n        catch (error) {\n            return createErrorResponse('CHROME_SPAWN_FAILED', { error: `${error}` });\n        }\n    }),\n    killChrome: createTool('Kill Chrome process', z.object({\n        reason: z.string().describe('Why Chrome needs to be killed'),\n        port: z.number().optional().describe('Port of specific Chrome instance to kill. If not provided, kills all Chrome instances.'),\n    }).strict(), async (args) => {\n        try {\n            const port = args.port;\n            await debugLog('index', `killChrome called - reason: ${args.reason}, port: ${port ?? 'all'}`);\n            // Set the close reason before killing (used for close event tracking)\n            if (port !== undefined) {\n                chromeLauncher.setPendingCloseReason(port, 'manual');\n            }\n            else {\n                for (const p of chromeLauncher.getRunningPorts()) {\n                    chromeLauncher.setPendingCloseReason(p, 'manual');\n                }\n            }\n            // Kill Chrome - the exit callback handles connection cleanup and port re-reservation\n            await chromeLauncher.kill(port);\n            return createSuccessResponse('CHROME_KILLED', {\n                port: port ?? 'all',\n                reason: args.reason\n            });\n        }\n        catch (error) {\n            return createErrorResponse('CHROME_KILL_FAILED', { error: `${error}` });\n        }\n    }),\n    resetChromeLauncher: createTool('Reset Chrome launcher', z.object({\n        reason: z.string().describe('Why Chrome launcher needs to be reset'),\n    }).strict(), async (args) => {\n        // Log the reason for audit purposes\n        console.error(`[cdp-tools] resetChromeLauncher called - Reason: ${args.reason}`);\n        chromeLauncher.reset();\n        return createSuccessResponse('CHROME_LAUNCHER_RESET');\n    }),\n    getChromeStatus: createTool('Get Chrome status', z.object({}).strict(), async () => {\n        const status = chromeLauncher.getStatus();\n        // Format for template rendering\n        const formattedStatus = {\n            ...status,\n            lastCloseEvents: status.lastCloseEvents.map(event => ({\n                ...event,\n                timestamp: event.timestamp.toISOString(),\n                hasExitCode: event.exitCode !== null && event.exitCode !== undefined,\n            })),\n        };\n        return createSuccessResponse('CHROME_STATUS', formattedStatus, status);\n    }),\n    setDebugLogging: createTool('Toggle debug logging', z.object({\n        enabled: z.boolean().describe('Set to true to enable debug logging, false to disable'),\n    }).strict(), async (args) => {\n        if (args.enabled) {\n            await enableDebugLogging(); // Now async to log startup metrics\n            return createSuccessResponse('DEBUG_LOGGING_ENABLED', {\n                message: 'Debug logging enabled. Logs will be written to .cdp-tools/logs/debug.log'\n            }, {\n                enabled: true,\n                message: 'Debug logging enabled. Logs will be written to .cdp-tools/logs/debug.log'\n            });\n        }\n        else {\n            disableDebugLogging();\n            return createSuccessResponse('DEBUG_LOGGING_DISABLED', {\n                message: 'Debug logging disabled'\n            }, {\n                enabled: false,\n                message: 'Debug logging disabled'\n            });\n        }\n    }),\n    getDebugLoggingStatus: createTool('Check debug logging status', z.object({}).strict(), async () => {\n        const enabled = isDebugEnabled();\n        return createSuccessResponse('DEBUG_LOGGING_STATUS', {\n            status: enabled ? 'enabled' : 'disabled',\n            enabled, // Pass boolean for conditionals\n            logFile: '.cdp-tools/logs/debug.log'\n        }, {\n            enabled,\n            logFile: '.cdp-tools/logs/debug.log'\n        });\n    }),\n    connectDebugger: createTool('Connect to debugger', z.object({\n        reference: z.string().describe('3 descriptive words describing this debugging activity'),\n        host: z.string().optional().default('localhost').describe('The debugger host (default: localhost)'),\n        port: z.number().optional().describe('The debugger port (optional, defaults to this session\\'s auto-assigned port). Use this to connect to debuggers on different ports (e.g., Node.js on 9229, Chrome on 9222).'),\n    }).strict(), async (args) => {\n        // Validate reference\n        // Validate and get sanitized reference (throws if invalid)\n        const reference = requireValidReference(args.reference);\n        // Check for duplicate reference - use validated lookup to auto-cleanup dead connections\n        const existingConnection = await connectionManager.findConnectionByReferenceValidated(reference);\n        if (existingConnection) {\n            return createErrorResponse('REFERENCE_IN_USE', {\n                reference\n            });\n        }\n        const host = args.host || 'localhost';\n        const port = args.port || configManager.getCurrentPort();\n        const defaultPort = configManager.getCurrentPort();\n        const isDefaultPort = port === defaultPort;\n        await debugLog('index', `connectDebugger called: host=${host}, port=${port}, defaultPort=${defaultPort}`);\n        try {\n            // Check if Chrome/debugger is running before attempting connection\n            await debugLog('index', `Checking if Chrome is running on port ${port}...`);\n            const isRunning = await isChromeRunning(port);\n            await debugLog('index', `isChromeRunning result: ${isRunning}`);\n            if (!isRunning) {\n                await debugLog('index', `Chrome not running on port ${port}, returning error`);\n                // Provide clear error message based on port type\n                if (isDefaultPort && host === 'localhost') {\n                    return createErrorResponse('DEBUGGER_NOT_RUNNING', {\n                        port: port.toString(),\n                        message: `Chrome is not running on port ${port}. Use \\`launchChrome()\\` to start Chrome first.`\n                    });\n                }\n                else {\n                    return createErrorResponse('DEBUGGER_NOT_RUNNING', {\n                        port: port.toString(),\n                        message: `No debugger found on ${host}:${port}. For Chrome, use \\`launchChrome({ port: ${port} })\\`. For Node.js, start with \\`node --inspect=${port} app.js\\``\n                    });\n                }\n            }\n            // Check if browser already exists on this port\n            const browserAlreadyExists = connectionManager.hasBrowser(host, port);\n            // Create new managers for this tab/connection\n            const cdpManager = new CDPManager(sourceMapHandler);\n            const puppeteerManager = new PuppeteerManager();\n            const consoleMonitor = new ConsoleMonitor();\n            const networkMonitor = new NetworkMonitor();\n            // Connect CDP first to detect runtime type\n            await cdpManager.connect(host, port);\n            const runtimeType = cdpManager.getRuntimeType();\n            const features = ['debugging'];\n            // Only connect Puppeteer for Chrome (browser automation)\n            if (runtimeType === 'chrome') {\n                await puppeteerManager.connect(host, port);\n                // Create new tab if browser already existed\n                if (browserAlreadyExists) {\n                    await puppeteerManager.newPage();\n                }\n                // Start monitoring console and network\n                const page = puppeteerManager.getPage();\n                consoleMonitor.startMonitoring(page);\n                networkMonitor.startMonitoring(page);\n                // Auto-reload page to capture initial console logs\n                // Skip reload for blank pages (nothing to reload)\n                const currentUrl = page.url();\n                if (currentUrl && currentUrl !== 'about:blank') {\n                    try {\n                        // Use 'load' instead of 'networkidle0' for compatibility with file:// URLs\n                        await page.reload({ waitUntil: 'load', timeout: 5000 });\n                        // Wait a bit more for all scripts to execute and errors to fire\n                        await new Promise(resolve => setTimeout(resolve, 500));\n                    }\n                    catch (reloadError) {\n                        // Log warning but don't fail - page might already be loaded\n                        console.error(`[cdp-tools] Warning: Page reload failed: ${reloadError.message}`);\n                    }\n                }\n                features.push('browser-automation', 'console-monitoring', 'network-monitoring');\n            }\n            else {\n                // For Node.js debugging, set up console monitoring via CDP Runtime.consoleAPICalled\n                // Set up value expander to get full object details (passes maxDepth from consoleMonitor)\n                consoleMonitor.setValueExpander((objectId, maxDepth) => cdpManager.expandObjectById(objectId, maxDepth));\n                cdpManager.setConsoleMessageCallback((message) => {\n                    consoleMonitor.addCDPConsoleMessage(message);\n                });\n                consoleMonitor.enableWithoutPage();\n                features.push('console-monitoring');\n            }\n            // Register logpoint tracker callback on this connection's console monitor\n            // This ensures logpoint executions are tracked for both Chrome and Node.js connections\n            consoleMonitor.onMessage((message) => {\n                logpointTracker.handleConsoleMessage(message);\n            });\n            // Get page index for tracking\n            let pageIndex;\n            if (runtimeType === 'chrome') {\n                const pages = await puppeteerManager.getPages();\n                const currentPage = puppeteerManager.getPage();\n                pageIndex = pages.findIndex(p => p === currentPage);\n            }\n            // Register connection with ConnectionManager\n            // Note: consoleMonitor is always passed now (works for both Chrome and Node.js)\n            const connectionId = connectionManager.createConnection(cdpManager, runtimeType === 'chrome' ? puppeteerManager : undefined, consoleMonitor, // Always include - works for both Chrome (via Puppeteer) and Node.js (via CDP)\n            runtimeType === 'chrome' ? networkMonitor : undefined, host, port, reference, // Set reference from parameter\n            pageIndex);\n            // Update active manager references\n            updateActiveManagers(connectionId);\n            // Build console stats for Chrome connections\n            let consoleStats;\n            if (runtimeType === 'chrome') {\n                const connection = connectionManager.getConnection(connectionId);\n                if (connection?.consoleMonitor) {\n                    // Get console stats and update cursor so first tool call doesn't re-report these\n                    const logStats = connection.consoleMonitor.getLogStats();\n                    if (logStats.totalMessages > 0) {\n                        const details = [];\n                        if (logStats.newErrors > 0)\n                            details.push(`${logStats.newErrors} err`);\n                        if (logStats.newWarnings > 0)\n                            details.push(`${logStats.newWarnings} warn`);\n                        const otherCount = logStats.totalMessages - logStats.newErrors - logStats.newWarnings;\n                        if (otherCount > 0)\n                            details.push(`${otherCount} log`);\n                        consoleStats = details.join('/');\n                    }\n                }\n            }\n            return createSuccessResponse('DEBUGGER_CONNECT_SUCCESS', {\n                runtimeType,\n                host,\n                port: port.toString(),\n                reference,\n                features: features.join(', '),\n                consoleStats,\n                isChrome: runtimeType === 'chrome',\n                isNode: runtimeType === 'node'\n            });\n        }\n        catch (error) {\n            return createErrorResponse('DEBUGGER_CONNECT_FAILED', {\n                host,\n                port: port.toString(),\n                error: `${error}`\n            });\n        }\n    }),\n    disconnectDebugger: createTool('Disconnect debugger', z.object({\n        reason: z.string().describe('Why the connection needs to be disconnected'),\n        reference: z.string().describe('3 descriptive words of the connection to disconnect'),\n    }).strict(), async (args) => {\n        // Log the reason for audit purposes\n        console.error(`[cdp-tools] disconnectDebugger called - Reason: ${args.reason}, Reference: ${args.reference}`);\n        // Find connection by reference\n        const connection = connectionManager.findConnectionByReference(args.reference);\n        if (!connection) {\n            return createErrorResponse('CONNECTION_NOT_FOUND', {\n                reference: args.reference\n            });\n        }\n        const success = await connectionManager.closeConnection(connection.id);\n        if (success) {\n            return createSuccessResponse('DEBUGGER_DISCONNECT_SUCCESS', { reference: args.reference });\n        }\n        else {\n            return createErrorResponse('CONNECTION_SWITCH_FAILED', { reference: args.reference });\n        }\n    }),\n    loadSourceMaps: createTool('Load source maps', z.object({\n        directory: z.string().describe('The directory containing .js.map files'),\n    }).strict(), async (args) => {\n        const { directory } = args;\n        try {\n            const registered = await sourceMapHandler.registerSourceMapsFromDirectory(directory);\n            return createSuccessResponse('SOURCE_MAPS_LOADED', {\n                count: registered.toString(),\n                directory\n            }, { registered, note: 'Source maps registered for lazy loading (will be loaded on demand)' });\n        }\n        catch (error) {\n            return createErrorResponse('SOURCE_MAPS_FAILED', { error: `${error}` });\n        }\n    }),\n    getDebuggerStatus: createTool('Get debugger status', z.object({\n        reference: z.string().describe('3 descriptive words of the connection to check'),\n    }).strict(), async (args) => {\n        // Find connection by reference\n        const connection = connectionManager.findConnectionByReference(args.reference);\n        if (!connection) {\n            return createErrorResponse('CONNECTION_NOT_FOUND', {\n                reference: args.reference\n            });\n        }\n        const cdpManager = connection.cdpManager;\n        const puppeteerManager = connection.puppeteerManager;\n        const consoleMonitor = connection.consoleMonitor;\n        const networkMonitor = connection.networkMonitor;\n        const connected = cdpManager.isConnected();\n        const runtimeType = cdpManager.getRuntimeType();\n        const paused = cdpManager.isPaused();\n        const breakpointCounts = cdpManager.getBreakpointCounts();\n        const sourceMaps = sourceMapHandler.getLoadedSourceMaps();\n        const puppeteerConnected = puppeteerManager?.isConnected() || false;\n        const statusData = {\n            reference: connection.reference || UNNAMED_CONNECTION,\n            connected,\n            runtimeType,\n            puppeteerConnected,\n            paused,\n            breakpoints: breakpointCounts.breakpoints,\n            logpoints: breakpointCounts.logpoints,\n            totalBreakpoints: breakpointCounts.total,\n            sourceMapCount: sourceMaps.length,\n            consoleMonitoring: consoleMonitor?.isActive() ? 'active' : 'inactive',\n            networkMonitoring: networkMonitor?.isActive() ? 'active' : 'inactive',\n            totalConnections: connectionManager.getConnectionCount(),\n        };\n        return createSuccessResponse('CONNECTION_STATUS', {}, statusData);\n    }),\n    listConnections: createTool('List debugger connections', z.object({}).strict(), async () => {\n        const connections = connectionManager.listConnections();\n        const activeId = connectionManager.getActiveConnectionId();\n        const activeConnection = activeId ? connectionManager.getConnection(activeId) : null;\n        const activeReference = activeConnection?.reference || UNNAMED_CONNECTION;\n        const connectionList = connections.map(conn => ({\n            reference: conn.reference || UNNAMED_CONNECTION,\n            type: conn.type,\n            host: conn.host,\n            port: conn.port,\n            active: conn.id === activeId,\n            connected: conn.cdpManager.isConnected(),\n            paused: conn.cdpManager.isPaused(),\n            createdAt: new Date(conn.createdAt).toISOString(),\n        }));\n        return createSuccessResponse('CONNECTIONS_LIST', {\n            totalConnections: connections.length.toString()\n        }, {\n            activeReference,\n            connections: connectionList,\n        });\n    }),\n    switchConnection: createTool('Switch debugger connection', z.object({\n        reference: z.string().describe('3 descriptive words of the connection to switch to'),\n    }).strict(), async (args) => {\n        // Find connection by reference\n        const connection = connectionManager.findConnectionByReference(args.reference);\n        if (!connection) {\n            return createErrorResponse('CONNECTION_NOT_FOUND', {\n                reference: args.reference\n            });\n        }\n        const success = connectionManager.setActiveConnection(connection.id);\n        if (success) {\n            // Update active manager references\n            updateActiveManagers(connection.id);\n            return createSuccessResponse('CONNECTION_SWITCH_SUCCESS', { reference: args.reference });\n        }\n        else {\n            return createErrorResponse('CONNECTION_SWITCH_FAILED', { reference: args.reference });\n        }\n    }),\n};\n// Active connection manager references (updated when connection is made/switched)\nlet activeCdpManager = null;\nlet activePuppeteerManager = null;\nlet activeConsoleMonitor = null;\nlet activeNetworkMonitor = null;\n// Helper to update active manager references\nconst updateActiveManagers = (connectionId) => {\n    const connection = connectionManager.getConnection(connectionId);\n    if (connection) {\n        activeCdpManager = connection.cdpManager;\n        activePuppeteerManager = connection.puppeteerManager || null;\n        activeConsoleMonitor = connection.consoleMonitor || null;\n        activeNetworkMonitor = connection.networkMonitor || null;\n        // Update activity timestamp whenever connection is accessed\n        connectionManager.updateActivity(connection.id);\n    }\n};\n/**\n * Resolve a connection from a connectionReason (task description)\n * Sanitizes the reason, looks for existing tab, or creates new one\n */\nasync function resolveConnectionFromReason(connectionReason) {\n    // Sanitize: lowercase, trim, spaces to hyphens\n    const reference = connectionReason.toLowerCase().trim().replace(/\\s+/g, '-');\n    // Find connection by reference only\n    const connection = connectionManager.findConnectionByReference(reference);\n    // If not found, return null to show error\n    if (!connection) {\n        return null;\n    }\n    // Update activity timestamp when connection is accessed\n    connectionManager.updateActivity(connection.id);\n    return {\n        connection,\n        cdpManager: connection.cdpManager,\n        puppeteerManager: connection.puppeteerManager || null,\n        consoleMonitor: connection.consoleMonitor || null,\n        networkMonitor: connection.networkMonitor || null,\n    };\n}\n// Create proxy managers that delegate to active connection\nconst proxyHandlerForManager = {\n    get(target, prop) {\n        // For CDPManager\n        if (target.constructor.name === 'CDPManager' && activeCdpManager) {\n            return activeCdpManager[prop];\n        }\n        // For PuppeteerManager\n        if (target.constructor.name === 'PuppeteerManager' && activePuppeteerManager) {\n            return activePuppeteerManager[prop];\n        }\n        // For ConsoleMonitor\n        if (target.constructor.name === 'ConsoleMonitor' && activeConsoleMonitor) {\n            return activeConsoleMonitor[prop];\n        }\n        // For NetworkMonitor\n        if (target.constructor.name === 'NetworkMonitor' && activeNetworkMonitor) {\n            return activeNetworkMonitor[prop];\n        }\n        return target[prop];\n    },\n};\n// Create proxy managers\nconst proxyCdpManager = new Proxy(new CDPManager(sourceMapHandler), proxyHandlerForManager);\nconst proxyPuppeteerManager = new Proxy(new PuppeteerManager(), proxyHandlerForManager);\nconst proxyConsoleMonitor = new Proxy(new ConsoleMonitor(), proxyHandlerForManager);\nconst proxyNetworkMonitor = new Proxy(new NetworkMonitor(), proxyHandlerForManager);\n// Register logpoint tracker callbacks\nproxyConsoleMonitor.onMessage((message) => {\n    logpointTracker.handleConsoleMessage(message);\n});\nlogpointTracker.setLimitExceededCallback((metadata) => {\n    proxyCdpManager.handleLogpointLimitExceeded({\n        breakpointId: metadata.breakpointId,\n        url: metadata.url,\n        lineNumber: metadata.lineNumber,\n        logMessage: metadata.logMessage,\n        executionCount: metadata.executionCount,\n        maxExecutions: metadata.maxExecutions,\n        logs: metadata.logs,\n    });\n});\n/**\n * Execute a tool call - used by replay system\n */\nasync function executeToolCall(toolName, params) {\n    const tool = allTools[toolName];\n    if (!tool) {\n        throw new Error(`Unknown tool: ${toolName}`);\n    }\n    const validation = validateParams(params, tool.zodSchema, toolName);\n    if (!validation.success) {\n        throw new Error(`Validation failed: ${JSON.stringify(validation.error)}`);\n    }\n    const result = await tool.handler(validation.data);\n    // If tool returned an error, throw it as a ToolError so it propagates correctly\n    if (result?.isError) {\n        throw new ToolError(result);\n    }\n    return result;\n}\n/**\n * Error that wraps a tool error response for propagation\n */\nclass ToolError extends Error {\n    response;\n    constructor(response) {\n        super(response?.content?.[0]?.text || 'Tool error');\n        this.response = response;\n    }\n}\n// Combine all tools (conditionally based on config)\nconst allTools = {\n    // Connection tools (Chrome/debugger)\n    ...(configManager.isToolEnabled('connection') ? connectionTools : {}),\n    // Tab Management tools\n    ...(configManager.isToolEnabled('tab') ? createTabTools(connectionManager, sourceMapHandler, updateActiveManagers, logpointTracker) : {}),\n    // CDP Debugging tools\n    ...(configManager.isToolEnabled('breakpoint') ? createBreakpointTools(proxyCdpManager, sourceMapHandler, logpointTracker, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('execution') ? createExecutionTools(proxyCdpManager, resolveConnectionFromReason, connectionManager) : {}),\n    ...(configManager.isToolEnabled('inspection') ? createInspectionTools(proxyCdpManager, sourceMapHandler, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('source') ? createSourceTools(proxyCdpManager, sourceMapHandler, resolveConnectionFromReason) : {}),\n    // Browser Automation tools\n    ...(configManager.isToolEnabled('console') ? createConsoleTools(proxyPuppeteerManager, proxyConsoleMonitor, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('network') ? createNetworkTools(proxyPuppeteerManager, proxyNetworkMonitor, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('page') ? createPageTools(proxyPuppeteerManager, proxyCdpManager, proxyConsoleMonitor, proxyNetworkMonitor, connectionManager, resolveConnectionFromReason, clickableCache, executeToolCall) : {}),\n    ...(configManager.isToolEnabled('dom') ? createDOMTools(proxyPuppeteerManager, proxyCdpManager, connectionManager, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('screenshot') ? createScreenshotTools(proxyPuppeteerManager, proxyCdpManager, connectionManager, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('input') ? createInputTools(proxyPuppeteerManager, proxyCdpManager, connectionManager, resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('content') ? createContentTools(proxyPuppeteerManager, proxyCdpManager, connectionManager, resolveConnectionFromReason, clickableCache) : {}),\n    ...(configManager.isToolEnabled('modal') ? createModalTools(resolveConnectionFromReason) : {}),\n    ...(configManager.isToolEnabled('storage') ? createStorageTools(proxyPuppeteerManager, proxyCdpManager, resolveConnectionFromReason) : {}),\n    // Download tools\n    ...(configManager.isToolEnabled('download') ? createDownloadTools() : {}),\n    // Replay tools\n    ...(configManager.isToolEnabled('replay') ? createReplayTools(commandRecorder, executeToolCall, async (connectionReason) => {\n        const resolved = await resolveConnectionFromReason(connectionReason);\n        if (!resolved?.puppeteerManager)\n            return null;\n        return resolved.puppeteerManager.getPage();\n    }) : {}),\n    // Server management tools\n    ...(configManager.isToolEnabled('server') ? createServerTools(serverManager) : {}),\n    // Config management tools (always enabled - not toggleable)\n    ...createConfigTools(),\n    // Issues tracking tools\n    ...(configManager.isToolEnabled('issues') ? createIssuesTools(executeToolCall, async (name) => {\n        // Helper to get sequence path by name\n        const sequences = commandRecorder.listSequences();\n        const sequence = sequences.find(s => s.name === name || s.id === name);\n        if (!sequence)\n            return null;\n        // Try to find saved file\n        const sequencesDir = commandRecorder.getSequencesDir();\n        const filename = name.replace(/[^a-z0-9-_]/gi, '-').toLowerCase() + '.json';\n        const { join } = await import('path');\n        const { existsSync } = await import('fs');\n        const filepath = join(sequencesDir, filename);\n        if (existsSync(filepath))\n            return filepath;\n        return null;\n    }, async (connectionReason) => {\n        const resolved = await resolveConnectionFromReason(connectionReason);\n        if (!resolved?.puppeteerManager)\n            return null;\n        return resolved.puppeteerManager.getPage();\n    }) : {}),\n};\n/**\n * Register tool handlers on the server\n */\nfunction registerToolHandlers(server) {\n    server.setRequestHandler(ListToolsRequestSchema, async () => {\n        return {\n            tools: Object.entries(allTools).map(([name, tool]) => ({\n                name,\n                description: tool.description,\n                inputSchema: tool.inputSchema,\n            })),\n        };\n    });\n    server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n        const toolName = request.params.name;\n        const tool = allTools[toolName];\n        if (!tool) {\n            return {\n                content: [\n                    {\n                        type: 'text',\n                        text: JSON.stringify({\n                            success: false,\n                            error: `Unknown tool: ${toolName}`,\n                            code: 'UNKNOWN_TOOL',\n                            availableTools: Object.keys(allTools).sort()\n                        }, null, 2),\n                    },\n                ],\n                isError: true\n            };\n        }\n        // Check for tool dependency conflicts (blocks ALL tools except config)\n        if (toolName !== 'config' && configManager.hasDependencyConflicts()) {\n            const conflicts = configManager.getDependencyConflicts();\n            const configPath = configManager.getStatus().loadedFrom || '.cdp-tools/config.json';\n            return {\n                content: [\n                    {\n                        type: 'text',\n                        text: `Tool dependency conflict - all tools blocked.\n\n${conflicts.join('\\n\\n')}\n\nEdit ${configPath} to resolve, then restart the MCP server.`,\n                    },\n                ],\n                isError: true\n            };\n        }\n        // All tools now use Zod validation\n        const validation = validateParams(request.params.arguments || {}, tool.zodSchema, toolName);\n        if (!validation.success) {\n            return {\n                content: [\n                    {\n                        type: 'text',\n                        text: JSON.stringify(validation.error, null, 2),\n                    },\n                ],\n                isError: true\n            };\n        }\n        // Record command if recording is active (but don't record replay tool calls)\n        // Capture the command index for the repeat hint\n        let commandIndex = null;\n        if (toolName !== 'replay') {\n            await commandRecorder.recordCommand(toolName, validation.data);\n            commandIndex = commandRecorder.getCurrentHistoryIndex();\n        }\n        // Check for failed monitored ports\n        const portMonitor = serverManager.getPortMonitor();\n        const failedPorts = portMonitor.getFailedPorts();\n        const portCheck = checkPortFailures(failedPorts, toolName);\n        if (portCheck.blocked) {\n            return portCheck.response;\n        }\n        // Check for breakpoint pauses (block tools until acknowledged or resumed)\n        const allConnections = connectionManager.getAllConnections();\n        const breakpointCheck = checkBreakpointPause(allConnections, toolName);\n        if (breakpointCheck.blocked) {\n            return breakpointCheck.response;\n        }\n        // Check for pending startup failures (block tools until acknowledged)\n        const pendingStartupFailures = serverManager.getPendingStartupFailures();\n        const pendingStartupCheck = checkPendingStartups(pendingStartupFailures, toolName);\n        if (pendingStartupCheck.blocked) {\n            return pendingStartupCheck.response;\n        }\n        // Check for blocking bugs from recordings\n        const bugCheck = await checkBugBlocking(toolName, validation.data);\n        if (bugCheck.blocked) {\n            return bugCheck.response;\n        }\n        // Pass validated data to handler\n        try {\n            const result = await tool.handler(validation.data, extra?.signal);\n            // Prepend port failure prefix if any\n            if (portCheck.prefix) {\n                prependToResponse(result, portCheck.prefix);\n                if (portCheck.markAsError) {\n                    result.isError = true;\n                }\n            }\n            // Prepend breakpoint pause prefix if any (for allowed tools when paused)\n            if (breakpointCheck.prefix) {\n                prependToResponse(result, breakpointCheck.prefix);\n            }\n            // Collect status lines to append to response\n            const statusItems = [];\n            // Append server log status to all tool responses\n            const serverLogStats = serverManager.getLogStats();\n            if (serverLogStats.length > 0) {\n                const parts = serverLogStats\n                    .filter(s => s.newStderr > 0 || s.newStdout > 0)\n                    .map(s => `${s.serverId} (${s.newStderr} err/${s.newStdout} out)`);\n                if (parts.length > 0) {\n                    statusItems.push({ label: 'Server Logs', value: parts.join(' | ') });\n                }\n            }\n            // Append console log status if tool used a connectionReason\n            const connectionReason = validation.data?.connectionReason;\n            if (connectionReason) {\n                const connection = connectionManager.findConnectionByReference(connectionReason);\n                if (connection?.consoleMonitor) {\n                    const logStats = connection.consoleMonitor.getLogStats();\n                    if (logStats.newMessages > 0) {\n                        const details = [];\n                        if (logStats.newErrors > 0)\n                            details.push(`${logStats.newErrors} err`);\n                        if (logStats.newWarnings > 0)\n                            details.push(`${logStats.newWarnings} warn`);\n                        const otherCount = logStats.newMessages - logStats.newErrors - logStats.newWarnings;\n                        if (otherCount > 0)\n                            details.push(`${otherCount} log`);\n                        statusItems.push({ label: 'Console', value: details.join('/') });\n                    }\n                }\n            }\n            // Add replay hint with history index\n            if (commandIndex !== null) {\n                statusItems.push({\n                    label: 'Repeat',\n                    value: `\\`replay({ action: 'repeat', indices: [${commandIndex}] })\\``\n                });\n            }\n            // Append all status lines if any\n            const statusSuffix = buildStatusSuffix(statusItems);\n            if (statusSuffix) {\n                appendToResponse(result, statusSuffix);\n            }\n            return result;\n        }\n        catch (error) {\n            // Check for ToolError and return its response directly\n            if (error instanceof ToolError) {\n                return error.response;\n            }\n            // Check for InvalidReferenceError and return its formatted response\n            if (error instanceof InvalidReferenceError) {\n                return error.response;\n            }\n            return {\n                content: [\n                    {\n                        type: 'text',\n                        text: error instanceof Error ? error.message : `${error}`,\n                    },\n                ],\n                isError: true\n            };\n        }\n    });\n}\n// Start the server\nasync function main() {\n    console.error(`[cdp-tools] main() called (PID: ${process.pid})`);\n    // Initialize path configuration early (before any file operations)\n    const pathConfig = initializePaths();\n    console.error(`[cdp-tools] Path config: global=${pathConfig.globalBase}, workingDir=${pathConfig.workingDirBase ?? 'none (using global fallback)'}`);\n    // Capture import time (time from script start to main() being called)\n    const importTime = performance.now() - STARTUP_TIME;\n    // Initialize and reserve debug port with retry logic\n    const portReservationStart = performance.now();\n    let reservationSucceeded = false;\n    let attempts = 0;\n    const maxAttempts = 10;\n    while (!reservationSucceeded && attempts < maxAttempts) {\n        const port = await findStartingPort();\n        configManager.setCurrentPort(port);\n        // Reserve the port by binding a socket to it\n        try {\n            await portReserver.reserve(port);\n            console.error(`[cdp-tools] Reserved debug port: ${port}`);\n            reservationSucceeded = true;\n        }\n        catch (error) {\n            attempts++;\n            console.error(`[cdp-tools] Port ${port} reservation failed (attempt ${attempts}/${maxAttempts}), trying next port...`);\n            if (attempts >= maxAttempts) {\n                console.error(`[cdp-tools] Failed to reserve a port after ${maxAttempts} attempts`);\n                process.exit(1);\n            }\n            // Try the next port\n            process.env.MCP_DEBUG_PORT = String(port + 1);\n        }\n    }\n    const portReservationTime = performance.now() - portReservationStart;\n    // Create server with instructions\n    const serverCreationStart = performance.now();\n    const server = await createMCPServer();\n    const serverCreationTime = performance.now() - serverCreationStart;\n    // Register tool handlers\n    const toolRegistrationStart = performance.now();\n    registerToolHandlers(server);\n    const toolRegistrationTime = performance.now() - toolRegistrationStart;\n    // Connect to transport\n    console.error(`[cdp-tools] Connecting to transport (PID: ${process.pid})`);\n    const transportStart = performance.now();\n    const transport = new StdioServerTransport();\n    await server.connect(transport);\n    const transportTime = performance.now() - transportStart;\n    console.error(`[cdp-tools] Transport connected (PID: ${process.pid})`);\n    // Load configuration\n    await configManager.load();\n    // Apply debug config from configuration file\n    const debugConfig = configManager.getDebugConfig();\n    if (debugConfig.enabled) {\n        await enableDebugLogging();\n    }\n    if (debugConfig.historyLogEnabled) {\n        enableHistoryLogging();\n    }\n    // Initialize server manager - recover running servers and start auto-run servers\n    const serverInitResult = await serverManager.initialize();\n    if (serverInitResult.recovered.length > 0) {\n        console.error(`[cdp-tools] Recovered ${serverInitResult.recovered.length} running server(s): ${serverInitResult.recovered.join(', ')}`);\n    }\n    if (serverInitResult.started.length > 0) {\n        console.error(`[cdp-tools] Auto-started ${serverInitResult.started.length} server(s): ${serverInitResult.started.join(', ')}`);\n    }\n    if (serverInitResult.failed.length > 0) {\n        console.error(`[cdp-tools] Failed to auto-start ${serverInitResult.failed.length} server(s): ${serverInitResult.failed.join(', ')}`);\n    }\n    console.error(`[cdp-tools] Server ready (PID: ${process.pid})`);\n    // Calculate total startup time and store metrics for later logging\n    const totalStartupTime = performance.now() - STARTUP_TIME;\n    setStartupMetrics({\n        totalMs: Math.round(totalStartupTime),\n        importMs: Math.round(importTime),\n        portReservationMs: Math.round(portReservationTime),\n        portAttempts: attempts + 1,\n        serverCreationMs: Math.round(serverCreationTime),\n        toolRegistrationMs: Math.round(toolRegistrationTime),\n        transportMs: Math.round(transportTime),\n        capturedAt: new Date().toISOString(),\n    });\n    // Start periodic cleanup of inactive connections\n    const chromeConfig = configManager.getChromeConfig();\n    const CLEANUP_INTERVAL = chromeConfig.inactivityPollingMinutes * 60 * 1000;\n    const INACTIVITY_THRESHOLD = chromeConfig.inactivityTimeoutMinutes * 60 * 1000;\n    // Only start cleanup interval if inactivity timeout is enabled (> 0)\n    const cleanupInterval = INACTIVITY_THRESHOLD > 0 ? setInterval(async () => {\n        try {\n            const inactiveConnections = connectionManager.getInactiveConnections(INACTIVITY_THRESHOLD);\n            if (inactiveConnections.length > 0) {\n                await debugLog('index', `Found ${inactiveConnections.length} inactive connection(s) to close`);\n                for (const conn of inactiveConnections) {\n                    await debugLog('index', `Closing inactive connection: ${conn.id} (inactive for ${Math.round(conn.inactiveForMs / 1000)}s)`);\n                }\n            }\n            const closedCount = await connectionManager.closeInactiveConnections(INACTIVITY_THRESHOLD);\n            if (closedCount > 0) {\n                console.error(`[cdp-tools] Closed ${closedCount} inactive connection(s)`);\n                await debugLog('index', `Closed ${closedCount} inactive connection(s)`);\n                // If no connections remain and Chrome is running, check for browser activity before killing\n                if (!connectionManager.hasConnections() && chromeLauncher.isRunning()) {\n                    // Check if there's been recent browser activity (network requests, console messages)\n                    // This prevents killing Chrome when user is actively browsing\n                    let hasBrowserActivity = false;\n                    // Check all connections for recent activity\n                    for (const conn of connectionManager.getAllConnections()) {\n                        if (conn.networkMonitor?.hasRecentActivity(INACTIVITY_THRESHOLD)) {\n                            hasBrowserActivity = true;\n                            await debugLog('index', `Connection ${conn.id} has recent network activity, skipping Chrome kill`);\n                            break;\n                        }\n                        if (conn.consoleMonitor?.hasRecentActivity(INACTIVITY_THRESHOLD)) {\n                            hasBrowserActivity = true;\n                            await debugLog('index', `Connection ${conn.id} has recent console activity, skipping Chrome kill`);\n                            break;\n                        }\n                    }\n                    if (hasBrowserActivity) {\n                        await debugLog('index', `Browser has recent activity, not killing Chrome`);\n                    }\n                    else {\n                        const runningPorts = chromeLauncher.getRunningPorts();\n                        console.error('[cdp-tools] No active connections or browser activity, killing Chrome due to inactivity...');\n                        await debugLog('index', `No active connections or browser activity, killing Chrome on ports: ${runningPorts.join(', ')} due to inactivity`);\n                        // Set the close reason before killing\n                        for (const port of runningPorts) {\n                            chromeLauncher.setPendingCloseReason(port, 'inactivity');\n                            await debugLog('index', `Set pending close reason 'inactivity' for port ${port}`);\n                        }\n                        await chromeLauncher.kill();\n                        await debugLog('index', `Chrome killed due to inactivity`);\n                    }\n                }\n            }\n        }\n        catch (error) {\n            console.error(`[cdp-tools] Error during cleanup: ${error}`);\n            await debugLog('index', `Error during inactivity cleanup: ${error}`);\n        }\n    }, CLEANUP_INTERVAL) : null;\n    // Cleanup function for graceful shutdown\n    let isCleaningUp = false;\n    const cleanup = async (signal) => {\n        if (isCleaningUp) {\n            return; // Prevent multiple cleanup calls\n        }\n        isCleaningUp = true;\n        console.error(`[cdp-tools] Received ${signal}, cleaning up...`);\n        try {\n            if (cleanupInterval)\n                clearInterval(cleanupInterval); // Stop periodic cleanup\n            await connectionManager.closeAll();\n            sourceMapHandler.clear();\n            await chromeLauncher.kill();\n            await portReserver.release();\n            console.error('[cdp-tools] Cleanup complete');\n        }\n        catch (error) {\n            console.error(`[cdp-tools] Cleanup error: ${error}`);\n        }\n        process.exit(0);\n    };\n    // Handle various termination signals\n    process.on('SIGINT', () => cleanup('SIGINT')); // Ctrl+C\n    process.on('SIGTERM', () => cleanup('SIGTERM')); // Graceful shutdown (systemd, Docker, etc.)\n    process.on('SIGHUP', () => cleanup('SIGHUP')); // Terminal hangup\n    // Handle stdin close - this catches when the parent process (Claude Code) terminates\n    // without sending a signal. MCP uses stdin/stdout for communication, so if stdin closes,\n    // the parent is gone and we should clean up.\n    process.stdin.on('close', () => cleanup('stdin-close'));\n    process.stdin.on('end', () => cleanup('stdin-end'));\n    // Handle normal exit (catch-all)\n    process.on('exit', () => {\n        if (!isCleaningUp) {\n            console.error('[cdp-tools] Process exiting');\n        }\n    });\n    // Catch uncaught exceptions and unhandled rejections for debugging\n    process.on('uncaughtException', (error, origin) => {\n        console.error(`[cdp-tools] UNCAUGHT EXCEPTION (${origin}):`, error);\n        console.error('[cdp-tools] Stack:', error.stack);\n    });\n    process.on('unhandledRejection', (reason, promise) => {\n        console.error('[cdp-tools] UNHANDLED REJECTION:', reason);\n        console.error('[cdp-tools] Promise:', promise);\n    });\n}\nmain().catch((error) => {\n    console.error('Server error:', error);\n    process.exit(1);\n});\n"]}