Transport that connects to a remote Codex app-server via WebSocket.
Requires the websockets package (pip install codexed[websocket]).
Source code in src/codexed/transport.py
| class WebSocketTransport:
"""Transport that connects to a remote Codex app-server via WebSocket.
Requires the ``websockets`` package (``pip install codexed[websocket]``).
"""
def __init__(
self,
url: str,
*,
auth_token: str | None = None,
extra_headers: dict[str, str] | None = None,
) -> None:
self._url = url
self._auth_token = auth_token
self._extra_headers = extra_headers or {}
self._ws: Any = None
self._writer_lock = asyncio.Lock()
async def start(self) -> None:
import websockets
if self._ws is not None:
return
headers = dict(self._extra_headers)
if self._auth_token:
headers["Authorization"] = f"Bearer {self._auth_token}"
self._ws = await websockets.connect(self._url, additional_headers=headers)
async def stop(self) -> None:
if self._ws is None:
return
with contextlib.suppress(Exception):
await self._ws.close()
self._ws = None
async def send(self, message: dict[str, Any]) -> None:
if self._ws is None:
raise TransportClosedError("WebSocket not connected")
async with self._writer_lock:
await self._ws.send(anyenv.dump_json(message))
async def receive(self) -> dict[str, Any] | None:
if self._ws is None:
return None
while True:
try:
raw: str | bytes = await self._ws.recv()
except Exception as exc: # noqa: BLE001
logger.debug("WebSocket closed: %s", exc)
return None
if isinstance(raw, bytes):
raw = raw.decode(errors="replace")
if (message := _parse_line(raw)) is not None:
return message
@property
def is_connected(self) -> bool:
return self._ws is not None
|