import Foundation import BrowserKit import FactoryKit extension BrowserCDPEngine { func captureScreenshotPNG(fullPage: Bool = true) async throws -> Data { var params: [String: Any] = ["format": "png"] if fullPage { params["captureBeyondViewport"] = true } let result = try await sendCommand(method: "Page.captureScreenshot", params: params) guard let base64String = result["data"] as? String, let imageData = Data(base64Encoded: base64String) else { throw BrowserCDPError.invalidResponsePayload } return imageData } } @MainActor func main() async { let engine = BrowserCDPEngine(host: "127.0.0.1", port: 9222) do { try await engine.connectToBrowser(at: URL(string: "http://127.0.0.1:9222")!) let targets = try await engine.discoverTargets() // Locate the active inspectable webpage target let pageTargets = targets.filter { $0.type == "page" && !$0.url.starts(with: "devtools://") } guard let activeTarget = pageTargets.first else { print("āŒ No active webpage tab found in Chrome on port 9222.") exit(1) } guard let wsURL = activeTarget.webSocketDebuggerUrl, !wsURL.isEmpty else { print("āŒ Active target missing webSocketDebuggerUrl.") exit(1) } try await engine.connect(targetWebSocketUrl: wsURL) // Small pause to allow frame buffer and layout to settle try await Task.sleep(nanoseconds: 400_000_000) // Default to full-page capture unless explicitly passed --viewport let isFull = !CommandLine.arguments.contains("--viewport") let imageData = try await engine.captureScreenshotPNG(fullPage: isFull) let outputPath = "/tmp/chrome_active_view.png" let outputURL = URL(fileURLWithPath: outputPath) try imageData.write(to: outputURL, options: .atomic) let pageTitle = activeTarget.title.isEmpty ? "Webpage" : activeTarget.title let targetURL = activeTarget.url let modeLabel = isFull ? "Full Page" : "Visible Viewport" // Resolve target agent from CLI arguments (--to or --agent ) var targetAgent = "Bob 2.0" let args = CommandLine.arguments if let toIndex = args.firstIndex(of: "--to"), toIndex + 1 < args.count { targetAgent = args[toIndex + 1] } else if let agentIndex = args.firstIndex(of: "--agent"), agentIndex + 1 < args.count { targetAgent = args[agentIndex + 1] } else if let envAgent = ProcessInfo.processInfo.environment["TARGET_AGENT"], !envAgent.isEmpty { targetAgent = envAgent } // Dispatch visual chip directly to calling agent prompt field via CrossTalk Inbound NotificationCenter.postDistributed( Notification.Name("com.higginsoft.factory.agent.inbound"), userInfo: [ "target_agent": targetAgent, "message": "šŸ“ø Active Chrome Tab (\(modeLabel)): \(pageTitle)\n🌐 \(targetURL)", "image_path": outputPath ] ) print("āœ… Captured active tab (\(modeLabel)): '\(pageTitle)' -> \(outputPath)") } catch { print("āŒ Failed to capture Chrome active tab: \(error.localizedDescription)") exit(1) } } await main()