"""Native Messaging host for Chrome Extension communication.""" import asyncio import json import struct import sys import threading import uuid from typing import Any, Literal from ..browser.manager import browser_manager from ..graph.orchestrator import orchestrator from ..hitl.handler import hitl_handler from ..protocol import ( BackendToExtensionMessage, CloseSessionMessage, ErrorMessage, ExecuteTaskMessage, GetSessionStatusMessage, HITLActionType, HITLRequestMessage, HITLResponseMessage, InitAckMessage, InitMessage, LogMessage, MessageType, PongMessage, SessionsListMessage, SessionStatus, SessionStatusMessage, TaskCompletedMessage, TaskFailedMessage, TaskStartedMessage, ) LogLevel = Literal["debug", "info", "warning", "error"] class NativeMessagingHost: """Native Messaging host for stdin/stdout communication with Chrome Extension.""" def __init__(self) -> None: self._running = False self._session_callbacks: dict[str, asyncio.Queue[Any]] = {} self._init_event = asyncio.Event() self._loop: asyncio.AbstractEventLoop self._thread: threading.Thread self._hitl_listener_registered = False def start(self) -> None: """Start the Native Messaging host.""" self._running = True # Run the async event loop in a separate thread self._loop = asyncio.new_event_loop() hitl_handler.add_listener(self._on_hitl_request) self._hitl_listener_registered = True self._thread = threading.Thread(target=self._run_loop, daemon=True) self._thread.start() def _run_loop(self) -> None: """Run the async event loop.""" asyncio.set_event_loop(self._loop) self._loop.run_until_complete(self._process_messages()) async def _process_messages(self) -> None: """Process incoming messages from stdin.""" reader = asyncio.StreamReader() protocol = asyncio.StreamReaderProtocol(reader) await self._loop.connect_read_pipe(lambda: protocol, sys.stdin) while self._running: try: # Read message length (4 bytes, native endian) length_bytes = await reader.readexactly(4) if not length_bytes: break length = struct.unpack("@I", length_bytes)[0] # Read message message_bytes = await reader.readexactly(length) message_str = message_bytes.decode("utf-8") message = json.loads(message_str) # Process message asynchronously asyncio.create_task(self._handle_message(message)) except asyncio.IncompleteReadError: break except json.JSONDecodeError as e: await self._send_error("INVALID_JSON", f"Failed to parse message: {e}") except Exception as e: # noqa: BLE001 - protocol boundary reports errors to the extension await self._send_error("PROCESSING_ERROR", str(e)) async def _handle_message(self, message: dict[str, Any]) -> None: """Handle an incoming message.""" try: msg_type = message.get("type") if msg_type == MessageType.INIT: await self._handle_init(message) elif msg_type == MessageType.EXECUTE_TASK: await self._handle_execute_task(message) elif msg_type == MessageType.GET_SESSION_STATUS: await self._handle_get_session_status(message) elif msg_type == MessageType.LIST_SESSIONS: await self._handle_list_sessions(message) elif msg_type == MessageType.CLOSE_SESSION: await self._handle_close_session(message) elif msg_type == MessageType.HITL_RESPONSE: await self._handle_hitl_response(message) elif msg_type == MessageType.PING: await self._send_message(PongMessage()) else: await self._send_error("UNKNOWN_MESSAGE_TYPE", f"Unknown message type: {msg_type}") except Exception as e: # noqa: BLE001 - protocol boundary reports errors to the extension await self._send_error("HANDLER_ERROR", str(e)) async def _handle_init(self, message: dict[str, Any]) -> None: """Handle initialization message.""" InitMessage(**message) # validate the handshake payload # Start browser manager await browser_manager.start() # Register progress callback orchestrator.register_progress_callback( "global", self._on_progress_update, ) # Send ack await self._send_message(InitAckMessage( backend_version="0.1.0", supported_capabilities=[ "browser_automation", "persistent_contexts", "hitl", "screenshots", "javascript_execution", ], )) self._init_event.set() async def _handle_execute_task(self, message: dict[str, Any]) -> None: """Handle execute task message.""" exec_msg = ExecuteTaskMessage(**message) # Create or get session session_id = exec_msg.session_id or f"session_{uuid.uuid4().hex[:8]}" # Create browser session await browser_manager.create_session(session_id, exec_msg.context_id) # Register progress callback for this session orchestrator.register_progress_callback( session_id, self._on_session_progress, ) # Send task started await self._send_message(TaskStartedMessage( task_id=session_id, session_id=session_id, )) # Run task result = await orchestrator.run_task( session_id, exec_msg.task, exec_msg.context_id, ) # Unregister callback orchestrator.unregister_progress_callback(session_id) # Send result if result["status"] == SessionStatus.COMPLETED: await self._send_message(TaskCompletedMessage( task_id=session_id, session_id=session_id, result={"steps": result["results"]}, )) else: await self._send_message(TaskFailedMessage( task_id=session_id, session_id=session_id, error=result.get("error", "Unknown error"), )) async def _handle_get_session_status(self, message: dict[str, Any]) -> None: """Handle get session status message.""" msg = GetSessionStatusMessage(**message) session = await browser_manager.get_session_status(msg.session_id) if session: await self._send_message(SessionStatusMessage( session_id=session.session_id, status=session.status, context_id=session.context_id, )) else: await self._send_error("SESSION_NOT_FOUND", f"Session {msg.session_id} not found") async def _handle_list_sessions(self, message: dict[str, Any]) -> None: """Handle list sessions message.""" sessions = await browser_manager.list_sessions() await self._send_message(SessionsListMessage(sessions=sessions)) async def _handle_close_session(self, message: dict[str, Any]) -> None: """Handle close session message.""" msg = CloseSessionMessage(**message) await browser_manager.close_session(msg.session_id) orchestrator.unregister_progress_callback(msg.session_id) await self._send_message(LogMessage( level="info", message=f"Session {msg.session_id} closed", session_id=msg.session_id, )) async def _handle_hitl_response(self, message: dict[str, Any]) -> None: """Handle HITL response message.""" msg = HITLResponseMessage(**message) pending = hitl_handler.get_pending_request(msg.request_id) if pending is None: await self._send_error( "HITL_REQUEST_NOT_FOUND", f"No pending HITL request {msg.request_id}", ) return await orchestrator.provide_hitl_response( pending["session_id"], msg.request_id, msg.approved, msg.data, ) def _on_hitl_request(self, payload: dict[str, Any]) -> None: """Forward a broker HITL request to the extension on the host loop.""" try: request = HITLRequestMessage( request_id=payload["request_id"], session_id=payload["session_id"], action_type=HITLActionType(payload["action_type"]), title=payload["title"], message=payload["message"], details=payload["details"], timeout=payload["timeout"], ) except (KeyError, TypeError, ValueError): return loop = getattr(self, "_loop", None) if loop is None or loop.is_closed(): return asyncio.run_coroutine_threadsafe(self._send_message(request), loop) async def _on_progress_update(self, message: BackendToExtensionMessage) -> None: """Callback for global progress updates (orchestrator awaits it).""" await self._send_message(message) async def _on_session_progress(self, message: BackendToExtensionMessage) -> None: """Callback for session-specific progress updates.""" await self._send_message(message) async def _send_message(self, message: BackendToExtensionMessage) -> None: """Send a message to stdout.""" # Convert to dict, handling UUID and datetime msg_dict = message.model_dump(mode="json") # Encode as JSON json_str = json.dumps(msg_dict, separators=(",", ":")) json_bytes = json_str.encode("utf-8") # Write length prefix (4 bytes, native endian) length_bytes = struct.pack("@I", len(json_bytes)) # Write to stdout sys.stdout.buffer.write(length_bytes) sys.stdout.buffer.write(json_bytes) sys.stdout.buffer.flush() async def _send_error(self, code: str, message: str) -> None: """Send an error message.""" await self._send_message(ErrorMessage( code=code, message=message, )) async def _send_log( self, level: LogLevel, message: str, session_id: str | None = None, data: dict[str, Any] | None = None, ) -> None: """Send a log message.""" await self._send_message(LogMessage( level=level, message=message, session_id=session_id, data=data, )) def stop(self) -> None: """Stop the host.""" self._running = False if self._hitl_listener_registered: hitl_handler.remove_listener(self._on_hitl_request) self._hitl_listener_registered = False if hasattr(self, "_loop"): self._loop.call_soon_threadsafe(self._loop.stop) def main() -> None: """Entry point for Native Messaging host.""" host = NativeMessagingHost() host.start() # Keep main thread alive try: host._thread.join() except KeyboardInterrupt: host.stop() if __name__ == "__main__": main()