mirror of
https://github.com/BigBodyCobain/Shadowbroker.git
synced 2026-12-06 01:24:28 +01:00
U8-judge: restore non-Gemini realtime dial suffix + open PTT gate to gemini_live
- voice_broker._ws_url_for: re-append /realtime?model=<id> on the
openai_realtime and compatible_ws branches (1fb3ecf dropped it,
silently breaking provider #1 and compat dials); gemini BidiSetup
URL unchanged.
- useVoiceAgent.isRealtimeProvider: add gemini_live so a resolved
Gemini Live provider actually opens a VoiceAudioClient session on
PTT (was dead end-to-end from the UI); helper now exported.
- voice_gemini.gemini_event_to_client: content translates first —
usageMetadata no longer takes an exclusive branch, so Gemini's
common turnComplete+usageMetadata message still yields response.done;
the relay meters straight off the raw event instead. Stale 'model
rides the setup message, not the URL' comments corrected.
- relay session.update patch forwarding guarded off Gemini sockets
(OpenAI-style build_session_config JSON would be a protocol error).
- Tests: dial-URL regression pins for openai/compat/gemini branches;
combined-event translation pin; realtimeProviderGate frontend test.
This commit is contained in:
1 parent
1fb3ecfe70
commit
68a73db375
6 files changed
+141
-20
No files matched your search
@@ -539,9 +539,11 @@ def _ws_url_for(provider_info: dict[str, Any], model_id: str) -> tuple[str, dict
|
||||
if not url.endswith("/v1"):
|
||||
url = f"{url}/v1"
|
||||
headers = {"Authorization": f"Bearer {provider_info['openaiKey']}", "OpenAI-Beta": "realtime=v1"}
|
||||
url = f"{url}/realtime?model={model_id}"
|
||||
elif provider_info["resolved"] == "gemini_live":
|
||||
# Gemini carries its key in the query (Google's browser-less WS
|
||||
# contract); model rides the setup message, not the URL.
|
||||
# contract); the model is mirrored in the query AND authored into the
|
||||
# server-side setup message (drift tolerance).
|
||||
from services.voice_gemini import gemini_ws_url
|
||||
|
||||
url = gemini_ws_url(provider_info["geminiBase"], provider_info["geminiKey"], provider_info["geminiModel"])
|
||||
@@ -552,6 +554,7 @@ def _ws_url_for(provider_info: dict[str, Any], model_id: str) -> tuple[str, dict
|
||||
headers = {}
|
||||
if provider_info["compatKey"]:
|
||||
headers["Authorization"] = f"Bearer {provider_info['compatKey']}"
|
||||
url = f"{url}/realtime?model={model_id}"
|
||||
return url, headers
|
||||
|
||||
|
||||
@@ -761,7 +764,13 @@ async def pump_client_to_upstream(
|
||||
client_ws,
|
||||
{"type": "error", "code": "patch_rejected", "keys": sorted(rejected)},
|
||||
)
|
||||
if state.upstream is not None and accepted:
|
||||
if (
|
||||
state.upstream is not None
|
||||
and accepted
|
||||
# build_session_config is OpenAI-style wire JSON — a protocol
|
||||
# error on a Gemini socket, whose setup is server-authored.
|
||||
and state.session.provider != "gemini_live"
|
||||
):
|
||||
try:
|
||||
await state.upstream.send(json.dumps(build_session_config(state.session)))
|
||||
except Exception:
|
||||
@@ -836,8 +845,14 @@ async def pump_upstream_to_client(client_ws: Any, state: _RelayState) -> str:
|
||||
await client_ws.send_text(json.dumps(payload))
|
||||
except Exception:
|
||||
return "upstream_closed"
|
||||
elif kind == "usage":
|
||||
prompt, completion = gemini_usage_to_tokens(payload)
|
||||
# Metering rides the RAW event, not an exclusive translation
|
||||
# branch: Gemini commonly attaches usageMetadata to ordinary
|
||||
# content messages (e.g. turnComplete), so translating usage
|
||||
# first would drop the response.done and strand the client in
|
||||
# 'speaking'. Forward content, then bill.
|
||||
usage = event.get("usageMetadata")
|
||||
if isinstance(usage, dict) and usage:
|
||||
prompt, completion = gemini_usage_to_tokens(usage)
|
||||
await state.meter_response_done(
|
||||
client_ws, {"prompt_tokens": prompt, "completion_tokens": completion}
|
||||
)
|
||||
|
||||
@@ -51,7 +51,9 @@ def gemini_model(settings: Any = None) -> str:
|
||||
|
||||
def gemini_ws_url(base: str, api_key: str, model: str) -> str:
|
||||
"""Build the BidiSetup dial URL. Key travels in the query per Google's
|
||||
browser-less WS contract; never logged (caller owns redaction)."""
|
||||
browser-less WS contract (never logged — caller owns redaction); the
|
||||
model is mirrored in the query for drift tolerance AND authored into the
|
||||
server-side setup message, which stays authoritative."""
|
||||
base = str(base or GEMINI_DEFAULT_BASE).rstrip("/")
|
||||
if "/ws" not in base:
|
||||
base = f"{base}/ws"
|
||||
@@ -158,8 +160,12 @@ def gemini_event_to_client(event: dict[str, Any]) -> tuple[str, Any]:
|
||||
Returns ``(kind, payload)`` where kind is:
|
||||
``audio`` — payload is RAW PCM16 LE bytes (24 kHz) → send as binary
|
||||
``text`` — payload is an OpenAI-style JSON frame → forward verbatim
|
||||
``usage`` — payload is a usage dict → metering tap
|
||||
``none`` — nothing to forward
|
||||
|
||||
Content translates FIRST: Gemini commonly attaches ``usageMetadata`` to
|
||||
ordinary content messages (e.g. turnComplete), so an exclusive usage
|
||||
branch would drop the response.done and strand the client in 'speaking'.
|
||||
The relay meters directly from the raw event's usageMetadata instead.
|
||||
"""
|
||||
if not isinstance(event, dict):
|
||||
return ("none", None)
|
||||
@@ -167,10 +173,6 @@ def gemini_event_to_client(event: dict[str, Any]) -> tuple[str, Any]:
|
||||
if "setupComplete" in event:
|
||||
return ("text", {"type": "ready"})
|
||||
|
||||
usage = event.get("usageMetadata")
|
||||
if isinstance(usage, dict) and usage:
|
||||
return ("usage", usage)
|
||||
|
||||
server = event.get("serverContent")
|
||||
if isinstance(server, dict):
|
||||
if server.get("interrupted"):
|
||||
|
||||
@@ -143,16 +143,28 @@ class TestGeminiEventTranslation:
|
||||
assert payload["name"] == "map_fly_to"
|
||||
assert payload["args"] == {"lat": 1.0}
|
||||
|
||||
def test_usage_metadata_routes_to_metering(self):
|
||||
from services.voice_gemini import gemini_event_to_client
|
||||
def test_usage_metadata_does_not_drop_translated_content(self):
|
||||
"""Gemini attaches usageMetadata to ordinary content messages (e.g.
|
||||
turnComplete). Content must translate FIRST — an exclusive usage
|
||||
branch dropped the response.done and stranded the client 'speaking';
|
||||
the relay meters from the raw event instead."""
|
||||
from services.voice_gemini import gemini_event_to_client, gemini_usage_to_tokens
|
||||
|
||||
kind, payload = gemini_event_to_client(
|
||||
{"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5}}
|
||||
)
|
||||
assert kind == "usage"
|
||||
from services.voice_gemini import gemini_usage_to_tokens
|
||||
event = {
|
||||
"serverContent": {"turnComplete": True},
|
||||
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5},
|
||||
}
|
||||
assert gemini_event_to_client(event) == ("text", {"type": "response.done"})
|
||||
assert gemini_usage_to_tokens(event["usageMetadata"]) == (10, 5)
|
||||
|
||||
assert gemini_usage_to_tokens(payload) == (10, 5)
|
||||
def test_usage_only_event_still_yields_metering_shape_via_relay_path(self):
|
||||
"""Usage-only events carry no content; the relay meters straight off
|
||||
``event['usageMetadata']`` — no dedicated translation branch needed."""
|
||||
from services.voice_gemini import gemini_event_to_client, gemini_usage_to_tokens
|
||||
|
||||
event = {"usageMetadata": {"promptTokenCount": 7, "responseTokenCount": 3}}
|
||||
assert gemini_event_to_client(event) == ("none", None)
|
||||
assert gemini_usage_to_tokens(event["usageMetadata"]) == (7, 3)
|
||||
|
||||
def test_hostile_events_degrade_to_none(self):
|
||||
from services.voice_gemini import gemini_event_to_client
|
||||
|
||||
@@ -285,6 +285,73 @@ class TestTokenTtlAndSessionBinding:
|
||||
assert consume_voice_session_token(rebound, session_id="sess-A") is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Upstream dial URL — regression pin (U8 judge): the shared
|
||||
# ``/realtime?model=`` suffix must survive on BOTH non-Gemini branches;
|
||||
# 1fb3ecf silently dropped it and no relay test inspected the dialed URL.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestUpstreamDialUrl:
|
||||
def test_openai_realtime_dial_carries_realtime_path_and_model(self, voice_env):
|
||||
from services.voice_broker import _ws_url_for
|
||||
|
||||
url, headers = _ws_url_for(
|
||||
{
|
||||
"resolved": "openai_realtime",
|
||||
"openaiBase": "https://api.openai.test",
|
||||
"openaiKey": "o-key",
|
||||
},
|
||||
"gpt-realtime",
|
||||
)
|
||||
assert url == "wss://api.openai.test/v1/realtime?model=gpt-realtime"
|
||||
assert headers["Authorization"] == "Bearer o-key"
|
||||
assert headers["OpenAI-Beta"] == "realtime=v1"
|
||||
|
||||
def test_openai_base_already_ending_in_v1_is_not_suffixed_twice(self, voice_env):
|
||||
from services.voice_broker import _ws_url_for
|
||||
|
||||
url, _headers = _ws_url_for(
|
||||
{
|
||||
"resolved": "openai_realtime",
|
||||
"openaiBase": "https://api.openai.com/v1",
|
||||
"openaiKey": "o-key",
|
||||
},
|
||||
"m",
|
||||
)
|
||||
assert url == "wss://api.openai.com/v1/realtime?model=m"
|
||||
|
||||
def test_compatible_ws_dial_carries_realtime_path_and_model(self, voice_env):
|
||||
from services.voice_broker import _ws_url_for
|
||||
|
||||
url, headers = _ws_url_for(
|
||||
{
|
||||
"resolved": "compatible_ws",
|
||||
"compatBase": "https://gw.example.com/v1",
|
||||
"compatKey": "",
|
||||
},
|
||||
"compat-model-x",
|
||||
)
|
||||
assert url == "wss://gw.example.com/v1/realtime?model=compat-model-x"
|
||||
assert headers == {}
|
||||
|
||||
def test_gemini_branch_keeps_bidi_setup_url_without_realtime_suffix(self, voice_env):
|
||||
from services.voice_broker import _ws_url_for
|
||||
|
||||
url, headers = _ws_url_for(
|
||||
{
|
||||
"resolved": "gemini_live",
|
||||
"geminiBase": "wss://generativelanguage.googleapis.com/ws",
|
||||
"geminiKey": "g-key",
|
||||
"geminiModel": "gemini-2.0-flash-live-001",
|
||||
},
|
||||
"ignored",
|
||||
)
|
||||
assert "BidiSetup" in url
|
||||
assert "/realtime?" not in url
|
||||
assert headers == {}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Item 23 — metering tap, warn/cap push, broker-side cap enforcement
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* U8 judge regression — the PTT realtime gate must accept EVERY provider
|
||||
* that resolves to the §4.3 binary relay. 1fb3ecf added gemini_live
|
||||
* server-side but never widened this gate, so a resolved Gemini Live
|
||||
* provider left PTT dead end-to-end from the UI.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { isRealtimeProvider } from '@/hooks/useVoiceAgent';
|
||||
|
||||
describe('useVoiceAgent realtime provider gate', () => {
|
||||
it('opens audio sessions for all three realtime providers', () => {
|
||||
expect(isRealtimeProvider('openai_realtime')).toBe(true);
|
||||
expect(isRealtimeProvider('compatible_ws')).toBe(true);
|
||||
expect(isRealtimeProvider('gemini_live')).toBe(true);
|
||||
});
|
||||
|
||||
it('stays closed for text-only and unresolved providers', () => {
|
||||
expect(isRealtimeProvider('local_text')).toBe(false);
|
||||
expect(isRealtimeProvider(null)).toBe(false);
|
||||
expect(isRealtimeProvider(undefined)).toBe(false);
|
||||
expect(isRealtimeProvider('')).toBe(false);
|
||||
expect(isRealtimeProvider('unknown_provider')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -40,8 +40,8 @@ export interface UseVoiceAgentResult {
|
||||
const STATUS_POLL_MS = 60000;
|
||||
|
||||
/** Providers that speak the §4.3 realtime wire protocol (binary PCM16 relay). */
|
||||
function isRealtimeProvider(resolved: string | null | undefined): boolean {
|
||||
return resolved === 'openai_realtime' || resolved === 'compatible_ws';
|
||||
export function isRealtimeProvider(resolved: string | null | undefined): boolean {
|
||||
return resolved === 'openai_realtime' || resolved === 'compatible_ws' || resolved === 'gemini_live';
|
||||
}
|
||||
|
||||
/** Broker cost snapshot → controller applyCost shape (defensive mapping). */
|
||||
|
||||
Reference in new issue
Block a user