File size: 4,863 Bytes
ddebc3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
"""LiveKit transport — fetch session token and open the WebSocket.

``fetch_livekit_token`` POSTs to /rest/livekit/tokens with proxy support.
``connect_livekit_ws`` opens the wss:// connection and returns a
``WebSocketConnection`` that the products layer can read/write.
"""

from typing import Any, Dict, Optional

import orjson

from app.platform.logging.logger import logger
from app.platform.config.snapshot import get_config
from app.platform.errors import UpstreamError
from app.control.proxy.models import ProxyFeedback, ProxyFeedbackKind, ProxyScope, RequestKind
from app.dataplane.proxy import get_proxy_runtime
from app.dataplane.proxy.adapters.headers import build_http_headers, build_ws_headers
from app.dataplane.reverse.protocol.xai_livekit import (
    LIVEKIT_TOKEN_URL,
    build_token_request_payload,
    build_ws_url,
)
from app.dataplane.reverse.transport.http import post_json
from app.dataplane.reverse.transport.websocket import WebSocketClient, WebSocketConnection
from app.dataplane.reverse.transport._proxy_feedback import upstream_feedback


# ------------------------------------------------------------------
# Token fetch
# ------------------------------------------------------------------

async def fetch_livekit_token(
    token:       str,
    *,
    voice:              str   = "ara",
    personality:        str   = "assistant",
    speed:              float = 1.0,
    custom_instruction: str   = "",
) -> Dict[str, Any]:
    """Fetch a LiveKit session token for *token*.

    Returns the parsed JSON body from /rest/livekit/tokens.
    Raises ``UpstreamError`` on failure.
    """
    cfg       = get_config()
    timeout_s = cfg.get_float("voice.timeout", 60.0)

    proxy = await get_proxy_runtime()
    lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.HTTP)

    payload = build_token_request_payload(
        voice              = voice,
        personality        = personality,
        speed              = speed,
        custom_instruction = custom_instruction,
    )

    try:
        result = await post_json(
            LIVEKIT_TOKEN_URL,
            token,
            payload,
            lease     = lease,
            timeout_s = timeout_s,
            origin    = "https://grok.com",
            referer   = "https://grok.com/",
        )
    except UpstreamError as exc:
        await proxy.feedback(lease, upstream_feedback(exc))
        raise
    except Exception as exc:
        await proxy.feedback(lease, ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR))
        raise UpstreamError(f"fetch_livekit_token: transport error: {exc}") from exc

    await proxy.feedback(
        lease,
        ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200),
    )
    logger.debug("livekit session token fetched")
    return result


# ------------------------------------------------------------------
# WebSocket connect
# ------------------------------------------------------------------

async def connect_livekit_ws(
    token:           str,
    access_token:    str,
    *,
    timeout_s:       Optional[float] = None,
) -> WebSocketConnection:
    """Open a WebSocket connection to the LiveKit RTC endpoint.

    Args:
        token:        SSO session cookie — used for WebSocket headers.
        access_token: Short-lived LiveKit token from ``fetch_livekit_token``.
        timeout_s:    Connection + read timeout; defaults to ``voice.timeout`` config.

    Returns:
        ``WebSocketConnection`` wrapping the live aiohttp WS connection.

    Raises:
        ``UpstreamError`` on connection failure.
    """
    cfg     = get_config()
    timeout = timeout_s if timeout_s is not None else cfg.get_float("voice.timeout", 120.0)

    proxy = await get_proxy_runtime()
    lease = await proxy.acquire(scope=ProxyScope.APP, kind=RequestKind.WEBSOCKET)

    url     = build_ws_url(access_token)
    headers = build_ws_headers(token=token, lease=lease)
    client  = WebSocketClient()

    async def _on_close() -> None:
        try:
            await proxy.feedback(
                lease,
                ProxyFeedback(kind=ProxyFeedbackKind.SUCCESS, status_code=200),
            )
        except Exception:
            pass

    try:
        connection = await client.connect(
            url,
            headers  = headers,
            timeout  = timeout,
            lease    = lease,
            on_close = _on_close,
        )
    except Exception as exc:
        await proxy.feedback(
            lease,
            ProxyFeedback(kind=ProxyFeedbackKind.TRANSPORT_ERROR),
        )
        logger.error("livekit websocket connect failed: error={}", exc)
        raise UpstreamError(f"connect_livekit_ws: {exc}") from exc

    logger.debug("livekit websocket connected: url={}", url)
    return connection


__all__ = ["fetch_livekit_token", "connect_livekit_ws"]