feat(clients): live: Gemini Live API over WebSocket, RFC 6455 client, session, relay, discovery check

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-24 04:40:00 +02:00
co-authored by Claude Sonnet 5.5
parent 6d744a433f
commit fe2afe0b97
35 changed files with 4441 additions and 3 deletions
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Checks src/google/live/live_spec.h against Google's published machine-readable specs.
python3 stdlib only, no credentials.
1. Every row whose source is "<service>/<version>" must name a schema that
exists in that service's Discovery document and a field that is one of
its properties.
2. Every row whose source is "docs:<url>" must have its field name present
in the text of that documentation page (weaker: the Live API envelopes
are WebSocket messages and appear in no Discovery document).
3. The WebSocket endpoints are probed with an unauthenticated upgrade
request: the server must answer 101 Switching Protocols with the correct
Sec-WebSocket-Accept (it closes the socket right after, for lack of
credentials). Pass --no-probe to skip.
Exit 0 when everything holds, 1 otherwise. Prints one line per failure and a
summary.
"""
import base64
import hashlib
import json
import os
import re
import socket
import ssl
import sys
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
SPEC = os.path.join(HERE, "..", "live_spec.h")
DISCOVERY = {
"generativelanguage": "https://generativelanguage.googleapis.com/$discovery/rest?version=%s",
"aiplatform": "https://aiplatform.googleapis.com/$discovery/rest?version=%s",
}
PROBES = [
("wss://us-central1-aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1.LlmBidiService/BidiGenerateContent"),
("wss://us-central1-aiplatform.googleapis.com/ws/google.cloud.aiplatform.v1beta1.LlmBidiService/BidiGenerateContent"),
("wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent"),
]
def fetch(url):
with urllib.request.urlopen(url, timeout=60) as r:
return r.read().decode("utf-8", "replace")
def parse_spec(path):
text = open(path, encoding="utf-8").read()
text = "\n".join(l for l in text.splitlines() if not l.lstrip().startswith("//"))
macros = dict(re.findall(r'#define\s+(LIVE_\w+)\s+"([^"]*)"', text))
rows = []
for m in re.finditer(r'\{"(\w+)",\s*"(\w+)",\s*(LIVE_\w+|"[^"]*")\}', text):
schema, field, src = m.groups()
src = macros[src] if src in macros else src.strip('"')
rows.append((schema, field, src))
return rows
def probe(url):
host = url.split("/")[2]
path = url[len("wss://") + len(host):]
key = base64.b64encode(os.urandom(16)).decode()
ctx = ssl.create_default_context()
ctx.set_alpn_protocols(["http/1.1"])
with socket.create_connection((host, 443), timeout=20) as raw:
with ctx.wrap_socket(raw, server_hostname=host) as s:
s.settimeout(20)
s.sendall(("GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, host, key)).encode())
buf = b""
while b"\r\n\r\n" not in buf and len(buf) < 16384:
chunk = s.recv(4096)
if not chunk:
break
buf += chunk
head = buf.split(b"\r\n\r\n")[0].decode("latin-1")
want = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
ok = head.startswith("HTTP/1.1 101") and want in head
return ok, head.split("\r\n")[0]
def main():
rows = parse_spec(SPEC)
failures = []
docs = {}
disc = {}
checked = 0
for schema, field, src in rows:
if src.startswith("docs:"):
url = src[5:]
if url not in docs:
docs[url] = fetch(url)
if field not in docs[url]:
failures.append("docs: %s.%s not found on %s" % (schema, field, url))
checked += 1
continue
svc, ver = src.split("/")
if src not in disc:
disc[src] = json.loads(fetch(DISCOVERY[svc] % ver))["schemas"]
s = disc[src]
if schema not in s:
failures.append("discovery %s: schema %s missing" % (src, schema))
elif field not in s[schema].get("properties", {}):
failures.append("discovery %s: %s.%s missing" % (src, schema, field))
checked += 1
for url in ([] if "--no-probe" in sys.argv else PROBES):
try:
ok, line = probe(url)
except Exception as e: # network trouble is a failure, loudly
ok, line = False, "error: %s" % e
print("%s upgrade probe %s -> %s" % ("ok " if ok else "FAIL", url.split("/ws/")[1], line))
if not ok:
failures.append("probe failed: " + url)
for f in failures:
print("FAIL", f)
print("%d spec rows checked (%d discovery docs, %d doc pages), %d failures"
% (checked, len(disc), len(docs), len(failures)))
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())