Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Add Gemini Live as a live call provider

Bugfixer 2c26f998dd11d
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.ts
index 512843acb7..f82ed59d4b 100644
--- a/packages/phone-protocol/src/live-call-wire.ts
+++ b/packages/phone-protocol/src/live-call-wire.ts
@@ -46,19 +46,22 @@ export interface LiveCallRecord {
}
/** Who runs a Live call's voice session: OpenAI itself, a GPT-Live deployment on the user's own Azure OpenAI / Foundry
- * resource, or a Fish Audio Live 3 agent the harness sets up on the person's Fish Audio account, whose session the client joins with Fish's SDK. */
-export type LiveProvider = "openai" | "azure" | "fish";
+ * resource, a Fish Audio Live 3 agent the harness sets up on the person's Fish Audio account, whose session the client joins with Fish's SDK,
+ * or the Gemini Live API on the person's Gemini key, which the client reaches with a single-use token the harness creates. */
+export type LiveProvider = "openai" | "azure" | "fish" | "gemini";
/** `live`: the key saved for Live calls only; `openai`: the OpenAI API key from Settings → API keys, used when there is no `live` key;
- * `fishAudio`: the Fish Audio key from Settings → API keys, the only key a Fish Audio call uses. */
-export type LiveKeySource = "live" | "openai" | "fishAudio";
+ * `fishAudio`: the Fish Audio key from Settings → API keys, the only key a Fish Audio call uses;
+ * `gemini`: the Gemini key from Settings → API keys, the only key a Gemini call uses. */
+export type LiveKeySource = "live" | "openai" | "fishAudio" | "gemini";
/** Non-secret Live settings, as GET /api/config and PATCH /api/live/settings report them. */
export interface LiveSettings {
/** A Live call has everything it needs: a key (`keySource` says which; never the key itself), and for Azure a valid endpoint and deployment. */
configured: boolean;
keySource?: LiveKeySource;
- /** Absent means "openai". With "azure" only the `live` key is used and with "fish" only the Fish Audio key, never the OpenAI API key. */
+ /** Absent means "openai". With "azure" only the `live` key is used, with "fish" only the Fish Audio key and with "gemini" only the
+ * Gemini key, never the OpenAI API key. */
provider?: LiveProvider;
/** The Azure resource endpoint as saved, e.g. `https://my-resource.openai.azure.com`. Not a secret. */
azureEndpoint?: string;
@@ -89,7 +92,28 @@ export interface LiveFishTransport {
relayToken: string;
}
-/** What the client of a "fish" call reports on POST /api/live/relay. Times are ms since the client joined the session. */
+/** A Gemini Live session the client opens itself: `token` is a single-use Gemini ephemeral token (`auth_tokens/…`) whose
+ * setup (model, instructions, tools) the harness locked when it created it, so the client's own setup is ignored. Holds no API key. */
+export interface LiveGeminiSession {
+ /** The harness's own id for the call's relay; Gemini has none before the client connects. */
+ session_id: string;
+ token: string;
+ /** The BidiGenerateContentConstrained WebSocket, without the token. */
+ ws_url: string;
+ /** e.g. `models/gemini-3.8-live` */
+ model: string;
+ /** ISO time by which the client must connect */
+ expires_at: string;
+}
+
+/** A "gemini" call's transport, answered only to the client that started the call; it relays as a "fish" call does. */
+export interface LiveGeminiTransport {
+ type: "gemini";
+ session: LiveGeminiSession;
+ relayToken: string;
+}
+
+/** What the client of a "fish" or "gemini" call reports on POST /api/live/relay. Times are ms since the client joined the session. */
export type LiveFishRelayEvent =
| { type: "connected" }
| { type: "heard"; text: string; startMs: number; endMs: number }
@@ -98,7 +122,7 @@ export type LiveFishRelayEvent =
| { type: "ended"; reason: string }
| { type: "error"; code: string };
-/** What the harness hands the client of a "fish" call: words for the agent to speak or know (`kind` as on GPT-Live), or the end of the call. */
+/** What the harness hands the client of a "fish" or "gemini" call: words for the agent to speak or know (`kind` as on GPT-Live), or the end of the call. */
export type LiveFishRelayCommand =
| { type: "append"; kind: "instructions" | "thinking" | "commentary"; content: string; delegationId: string | null }
| { type: "close" };
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
index 1c955ea1e5..3ec46be7e6 100644
--- a/packages/phone-protocol/src/wire.ts
+++ b/packages/phone-protocol/src/wire.ts
@@ -39,7 +39,7 @@ import type { CompanionEndpointsSnapshot } from "./responses.ts";
/** What a team bot's main chat is called, beside each person's own chats. */
export const SHARED_CHAT_TITLE = "Shared chat";
-export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
+export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveGeminiSession, LiveGeminiTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
export type { AuthPairResponse, BotsResponse, CompanionE2EDescriptor, CompanionEndpointsSnapshot, PairedDevice, PairedSession, PairResponse, WireComputerControl, WireMessagePage } from "./responses.ts";
diff --git a/server/live-access.test.ts b/server/live-access.test.ts
index 3aa67c4a39..c05a8c7868 100644
--- a/server/live-access.test.ts
+++ b/server/live-access.test.ts
@@ -6,7 +6,7 @@ import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { teamRoleScopes, type TeamRole } from "./cloud-team.ts";
-import { azureLiveCallRefusal, fishLiveCallRefusal, LIVE_AZURE_REFUSAL, LIVE_FISH_REFUSAL, liveScopeRefusal } from "./live-access.ts";
+import { azureLiveCallRefusal, fishLiveCallRefusal, geminiLiveCallRefusal, LIVE_AZURE_REFUSAL, LIVE_FISH_REFUSAL, LIVE_GEMINI_REFUSAL, liveScopeRefusal } from "./live-access.ts";
import { requiredScope, resolveRequestAuth, type RequestAuth, type ResolveOptions } from "./request-auth.ts";
import { SessionRegistry, type Scope, type SessionRecord } from "./sessions.ts";
import { moveInRefusal } from "./team-move-in.ts";
@@ -27,7 +27,7 @@ afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
-interface Place { resolve?: Partial<ResolveOptions>; othersOnLoopback?: boolean; provider?: "azure" | "openai" | "fish" }
+interface Place { resolve?: Partial<ResolveOptions>; othersOnLoopback?: boolean; provider?: "azure" | "openai" | "fish" | "gemini" }
/** "gets a call", or the words the person reads and who said them. */
function verdict(headers: Record<string, string>, place: Place = {}): string {
@@ -37,7 +37,7 @@ function verdict(headers: Record<string, string>, place: Place = {}): string {
...place.resolve,
});
if (!auth) return `sign-in gate ${status}: ${error}`;
- const refuse = place.provider === "fish" ? fishLiveCallRefusal : azureLiveCallRefusal;
+ const refuse = place.provider === "fish" ? fishLiveCallRefusal : place.provider === "gemini" ? geminiLiveCallRefusal : azureLiveCallRefusal;
const refusal = refuse(auth, { othersOnLoopback: place.othersOnLoopback ?? false });
return refusal ? `limit: ${refusal}` : "gets a call";
}
@@ -178,6 +178,7 @@ describe("the words for a session without the admin scope", () => {
expect(liveScopeRefusal({}, "POST", LIVE)).toBeNull();
expect(liveScopeRefusal({ live: { provider: "fish" } }, "POST", LIVE)).toBe(LIVE_FISH_REFUSAL);
expect(liveScopeRefusal({ live: { provider: "fish" } }, "POST", "/api/live/relay")).toBeNull();
+ expect(liveScopeRefusal({ live: { provider: "gemini" } }, "POST", LIVE)).toBe(LIVE_GEMINI_REFUSAL);
});
it("change no one's scope: every Live route stays closed to a client session", () => {
for (const [method, path] of [["POST", LIVE], ["POST", "/api/live/call/end"], ["GET", "/api/live/call"], ["PATCH", "/api/live/settings"], ["POST", "/api/live/device-revoked"], ["POST", "/api/live/relay"]] as const) {
@@ -205,3 +206,20 @@ describe("a Fish Audio Live call", () => {
expect(fishLiveCallRefusal(unknown, { othersOnLoopback: false })).toBe(LIVE_FISH_REFUSAL);
});
});
+
+describe("a Gemini Live call", () => {
+ const GEMINI = { provider: "gemini" as const };
+ const TEAM = { ...GEMINI, ...SERVICE, othersOnLoopback: true };
+
+ it("goes to the owner and a team admin, as on Fish Audio", () => {
+ expect(verdict(LOCAL, GEMINI)).toBe(CALL);
+ expect(verdict(device(["admin", "client"]), GEMINI)).toBe(CALL);
+ expect(verdict(teamMember("admin"), TEAM)).toBe(CALL);
+ });
+
+ it("is refused in its own words to a chat-only session, a team User and a local request others share", () => {
+ expect(verdict(device(["client"]), GEMINI)).toBe(`sign-in gate 403: ${LIVE_GEMINI_REFUSAL}`);
+ expect(verdict(teamMember("member"), TEAM)).toBe(`sign-in gate 403: ${LIVE_GEMINI_REFUSAL}`);
+ expect(verdict(LOCAL, { ...GEMINI, othersOnLoopback: true })).toBe(`limit: ${LIVE_GEMINI_REFUSAL}`);
+ });
+});
diff --git a/server/live-access.ts b/server/live-access.ts
index b243e86c09..a1c8598506 100644
--- a/server/live-access.ts
+++ b/server/live-access.ts
@@ -1,10 +1,11 @@
-// Who may hold a Live call through Azure OpenAI or Fish Audio. LIVE_DATA_CHANNEL in live-call.ts says why Azure is limited;
-// on Fish Audio the harness hears the call only through its client's own reports (FishRelay in live-fish.ts).
+// Who may hold a Live call through Azure OpenAI, Fish Audio or Gemini. LIVE_DATA_CHANNEL in live-call.ts says why Azure is
+// limited; on Fish Audio and Gemini the harness hears the call only through its client's own reports (FishRelay in live-fish.ts).
import type { AppConfig } from "./config.ts";
import type { RequestAuth } from "./request-auth.ts";
export const LIVE_AZURE_REFUSAL = "Live calls here go through Azure OpenAI, so only an admin or the owner of this server can start one. Ask an admin if you need a call.";
export const LIVE_FISH_REFUSAL = "Live calls here go through Fish Audio, so only an admin or the owner of this server can start one. Ask an admin if you need a call.";
+export const LIVE_GEMINI_REFUSAL = "Live calls here go through Gemini, so only an admin or the owner of this server can start one. Ask an admin if you need a call.";
export interface LiveCallPlace {
/** A local request may not be the owner, because other people use this server and every bot's shell is a local caller
@@ -25,8 +26,13 @@ export function fishLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): st
return azureLiveCallRefusal(auth, place, LIVE_FISH_REFUSAL);
}
+export function geminiLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): string | null {
+ return azureLiveCallRefusal(auth, place, LIVE_GEMINI_REFUSAL);
+}
+
/** The words for a session without the admin scope, which never reaches a Live route. Only the words: the request is refused either way. */
export function liveScopeRefusal(cfg: Pick<AppConfig, "live">, method: string, path: string): string | null {
if (method.toUpperCase() !== "POST" || path !== "/api/live/session") return null;
- return cfg.live?.provider === "azure" ? LIVE_AZURE_REFUSAL : cfg.live?.provider === "fish" ? LIVE_FISH_REFUSAL : null;
+ const provider = cfg.live?.provider;
+ return provider === "azure" ? LIVE_AZURE_REFUSAL : provider === "fish" ? LIVE_FISH_REFUSAL : provider === "gemini" ? LIVE_GEMINI_REFUSAL : null;
}
diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.ts
index 20c86b1062..7830d5a76e 100644
--- a/server/live-call-controller.test.ts
+++ b/server/live-call-controller.test.ts
@@ -2,12 +2,12 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { LiveCallState } from "../shared/wire.ts";
import {
ATTACH_TIMEOUT_MS, CLOSE_TIMEOUT_MS, CONSENT_SETTLE_MS, DELEGATION_SETTLE_MS, FISH_ATTACH_TIMEOUT_MS, GOODBYE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
- LIVE_FISH_NEEDS_APP, LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
+ LIVE_FISH_NEEDS_APP, LIVE_GEMINI_NEEDS_APP, LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
} from "./live-call-controller.ts";
import { LIVE_COPY } from "../shared/live-approval.ts";
import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY, LiveSessionError, type LiveEndpoint } from "./live-call.ts";
import { FishRelays, FISH_AGENT_VOICE } from "./live-fish.ts";
-import type { LiveFishSessionToken } from "../shared/wire.ts";
+import type { LiveFishSessionToken, LiveGeminiSession } from "../shared/wire.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { Message, StoreChange } from "./store.ts";
@@ -53,6 +53,7 @@ function setup(overrides: Partial<LiveCallDeps> = {}) {
settings: () => settings,
azureRefusal: vi.fn(() => null),
fishRefusal: vi.fn(() => null),
+ geminiRefusal: vi.fn(() => null),
createSession: vi.fn(async () => ({ sessionId: "sess_1", sdp: "answer-sdp" })),
openSocket: (url, key) => { const socket = new FakeSocket(url, key); sockets.push(socket); return socket; },
attachUrl: (id) => `ws://fake/${id}/attach`,
@@ -467,6 +468,88 @@ describe("LiveCallController lifecycle", () => {
expect(vi.getTimerCount()).toBe(0);
});
+ describe("with Gemini chosen", () => {
+ const GEMINI: LiveEndpoint = { provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-3.8-live" };
+ const SESSION: LiveGeminiSession = {
+ session_id: "gemini_1", token: "auth_tokens/abc", model: "models/gemini-3.8-live", expires_at: "2026-11-14T00:01:00Z",
+ ws_url: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained",
+ };
+ const gemini = (overrides: Partial<LiveCallDeps> = {}) => {
+ const relays = new FishRelays();
+ let relayToken = "";
+ const t = setup({
+ createSession: vi.fn(async () => {
+ relayToken = relays.open(SESSION.session_id, async () => undefined).token;
+ return { sessionId: SESSION.session_id, gemini: { type: "gemini" as const, session: SESSION, relayToken } };
+ }),
+ openSocket: (url) => relays.socket(url),
+ attachUrl: (id) => id,
+ ...overrides,
+ });
+ t.settings.endpoint = GEMINI;
+ t.settings.provider = "gemini";
+ const relay = () => relays.find(SESSION.session_id, relayToken)!;
+ return { ...t, relays, relay };
+ };
+
+ it("asks who is calling, starts with no SDP, and answers with Gemini's token and the relay's token", async () => {
+ const t = gemini();
+ const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ expect(t.deps.geminiRefusal).toHaveBeenCalledWith(owner);
+ expect(t.deps.fishRefusal).not.toHaveBeenCalled();
+ expect(t.deps.azureRefusal).not.toHaveBeenCalled();
+ expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: GEMINI, sdp: "" }));
+ expect(started.sdp).toBeUndefined();
+ expect(started.fish).toBeUndefined();
+ expect(started.gemini).toEqual({ type: "gemini", session: SESSION, relayToken: expect.stringMatching(/^[\w-]{43}$/) });
+ expect(started).not.toHaveProperty("sessionId");
+ });
+
+ it("refuses with the reason as a 403 before any session is taken", async () => {
+ const t = gemini({ geminiRefusal: () => "not you" });
+ await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 403, message: "not you" });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ });
+
+ it("sends a phone to the desktop app or a browser", async () => {
+ for (const client of ["ios", "android"] as const) {
+ const t = gemini();
+ await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_GEMINI_NEEDS_APP });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ }
+ });
+
+ it("never calls Gemini with a key saved for another provider", async () => {
+ const t = gemini();
+ t.settings.endpoint = { provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_1" };
+ await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 409 });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ });
+
+ it("waits as long as for Fish Audio for the client to join, then says Gemini could not connect", async () => {
+ const t = gemini();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ await vi.advanceTimersByTimeAsync(FISH_ATTACH_TIMEOUT_MS + 1);
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost", error: "The call could not connect to Gemini." });
+ });
+
+ it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {
+ const t = gemini();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ const callId = t.controller.current()!.callId;
+ t.relay().receive([{ type: "connected" }]);
+ expect(t.controller.current()?.status).toBe("live");
+ t.relay().receive([{ type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "fc_1", atMs: 950 }]);
+ await vi.advanceTimersByTimeAsync(DELEGATION_SETTLE_MS + 1);
+ expect(t.deps.send).toHaveBeenCalledWith({ auth: owner, botId: "bot1", threadId: "t1", text: "check my mail", callId });
+ t.message({ id: "b1", text: "You have two new emails.", requestMessageId: "m1" });
+ t.patch({ id: "b1", text: "You have two new emails.", requestMessageId: "m1", turnTerminal: true, turnSucceeded: true });
+ await vi.advanceTimersByTimeAsync(0);
+ const { commands } = await t.relay().poll(0);
+ expect(commands).toContainEqual({ type: "append", kind: "commentary", content: "You have two new emails.", delegationId: "fc_1" });
+ });
+ });
+
describe("a start cancelled while OpenAI creates the session", () => {
function pendingSession() {
let resolve!: (value: { sessionId: string; sdp: string }) => void;
diff --git a/server/live-call-controller.ts b/server/live-call-controller.ts
index 16516a6438..49b6a0ad88 100644
--- a/server/live-call-controller.ts
+++ b/server/live-call-controller.ts
@@ -6,7 +6,7 @@ import {
} from "../shared/live-approval.ts";
import { clampAppend, commentaryChunks, LiveTranscript } from "../shared/live-call.ts";
import { signInWaits } from "../shared/sign-in-request.ts";
-import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveFishTransport, LiveProvider } from "../shared/wire.ts";
+import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveFishTransport, LiveGeminiTransport, LiveProvider } from "../shared/wire.ts";
import { FISH_AGENT_VOICE } from "./live-fish.ts";
import { LIVE_NEEDS_KEY, liveAuthHeaders, liveCallSummaryLine, liveProviderName, LiveSessionError, liveVoice, spokenHangUp, type LiveEndpoint } from "./live-call.ts";
import type { RequestAuth } from "./request-auth.ts";
@@ -40,9 +40,13 @@ export interface LiveSocket {
}
export type LiveActivity = "idle" | "working" | "waiting";
-export type LiveSessionAnswer = { sessionId: string; sdp: string } | { sessionId: string; fish: LiveFishTransport };
-export type LiveCallStarted = { call: LiveCallState; sdp: string; fish?: undefined } | { call: LiveCallState; sdp?: undefined; fish: LiveFishTransport };
+export type LiveSessionAnswer = { sessionId: string; sdp: string } | { sessionId: string; fish: LiveFishTransport } | { sessionId: string; gemini: LiveGeminiTransport };
+export type LiveCallStarted =
+ | { call: LiveCallState; sdp: string; fish?: undefined; gemini?: undefined }
+ | { call: LiveCallState; sdp?: undefined; fish: LiveFishTransport; gemini?: undefined }
+ | { call: LiveCallState; sdp?: undefined; fish?: undefined; gemini: LiveGeminiTransport };
export const LIVE_FISH_NEEDS_APP = "Live calls through Fish Audio work in the desktop app or a web browser, not in the phone app yet.";
+export const LIVE_GEMINI_NEEDS_APP = "Live calls through Gemini work in the desktop app or a web browser, not in the phone app yet.";
export type LiveSendResult = { kind: "started" | "steered"; messageId: string } | { kind: "queued"; queueId: string };
export type LiveRespondResult = { ok: true } | { ok: false; error: string };
@@ -59,9 +63,10 @@ export interface LiveCallDeps {
settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; readTypedReplies: boolean; idleMinutes: number };
/** Why this caller may not hold a call through Azure OpenAI; null when they may. Required, so no wiring can leave it out. */
azureRefusal(auth: RequestAuth): string | null;
- /** The same for Fish Audio, where the harness hears the call only through its client's reports. Required too. */
+ /** The same for Fish Audio and Gemini, where the harness hears the call only through its client's reports. Required too. */
fishRefusal(auth: RequestAuth): string | null;
- /** `sdp` is "" on Fish Audio, which answers with `fish` instead of an SDP answer. */
+ geminiRefusal(auth: RequestAuth): string | null;
+ /** `sdp` is "" on Fish Audio and Gemini, which answer with `fish` or `gemini` instead of an SDP answer. */
createSession(input: { key: string; endpoint: LiveEndpoint; sdp: string; botId: string; threadId: string; voice: string }): Promise<LiveSessionAnswer>;
openSocket(url: string, key: string, endpoint: LiveEndpoint): LiveSocket;
attachUrl(sessionId: string, endpoint: LiveEndpoint): string;
@@ -167,32 +172,35 @@ export class LiveCallController {
async start(input: { auth: RequestAuth; device?: string; botId: string; botName: string; threadId: string; client: LiveClient; sdp?: string }): Promise<LiveCallStarted> {
const settings = this.deps.settings();
- // First: someone refused here is not told about a running call, or sent to set Azure or Fish Audio up.
+ // First: someone refused here is not told about a running call, or sent to set Azure, Fish Audio or Gemini up.
+ // The chosen relayed service comes before a key's endpoint, so its refusal and its mismatch check apply.
+ const relayedChoice = settings.provider === "fish" || settings.provider === "gemini" ? settings.provider : null;
const limited = settings.provider === "azure" || settings.endpoint?.provider === "azure" ? "azure"
- : settings.provider === "fish" || settings.endpoint?.provider === "fish" ? "fish" : null;
+ : relayedChoice ?? (settings.endpoint?.provider === "fish" || settings.endpoint?.provider === "gemini" ? settings.endpoint.provider : null);
if (limited) {
- const refusal = limited === "azure" ? this.deps.azureRefusal(input.auth) : this.deps.fishRefusal(input.auth);
+ const refusal = limited === "azure" ? this.deps.azureRefusal(input.auth) : limited === "fish" ? this.deps.fishRefusal(input.auth) : this.deps.geminiRefusal(input.auth);
if (refusal) {
this.deps.log(`[live] call refused bot=${input.botId} client=${input.client} provider=${limited}`);
throw new LiveSessionError(refusal, 403);
}
}
- const fish = limited === "fish";
- if (fish && (input.client === "ios" || input.client === "android")) throw new LiveSessionError(LIVE_FISH_NEEDS_APP, 400);
- if (!fish && !input.sdp) throw new LiveSessionError("The call request was not valid.", 400);
+ // Fish Audio and Gemini calls are relayed: the client holds the provider's session and reports what it heard.
+ const relayed = limited === "fish" || limited === "gemini" ? limited : null;
+ if (relayed && (input.client === "ios" || input.client === "android")) throw new LiveSessionError(relayed === "fish" ? LIVE_FISH_NEEDS_APP : LIVE_GEMINI_NEEDS_APP, 400);
+ if (!relayed && !input.sdp) throw new LiveSessionError("The call request was not valid.", 400);
if (this.call && this.call.state.status !== "ended") throw new LiveCallBusyError({ ...this.call.state });
if (input.device && this.revokedDevices.has(input.device)) throw new LiveCallSignedOutError();
const key = settings.key.trim();
const endpoint = settings.endpoint;
if (settings.setupProblem || !key || !endpoint) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);
- if (fish !== (endpoint.provider === "fish")) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);
- const voice = fish ? FISH_AGENT_VOICE : liveVoice(settings.voice);
+ if (relayed !== (endpoint.provider === "fish" || endpoint.provider === "gemini" ? endpoint.provider : null)) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);
+ const voice = relayed ? FISH_AGENT_VOICE : liveVoice(settings.voice);
const call = this.newCall(input, key, endpoint, voice);
// Taken before the first await: a second start in the same tick is refused.
this.call = call;
let session: LiveSessionAnswer;
try {
- session = await this.deps.createSession({ key, endpoint, sdp: fish ? "" : input.sdp ?? "", botId: input.botId, threadId: input.threadId, voice });
+ session = await this.deps.createSession({ key, endpoint, sdp: relayed ? "" : input.sdp ?? "", botId: input.botId, threadId: input.threadId, voice });
} catch (error) {
if (this.call === call) this.call = null;
this.deps.log(`[live] call failed bot=${input.botId} client=${input.client} status=${error instanceof LiveSessionError ? error.status : "error"}`);
@@ -221,7 +229,10 @@ export class LiveCallController {
if (!sidebandOpened) this.closeOrphan(session.sessionId, key, endpoint);
throw error;
}
- return "fish" in session ? { call: { ...call.state }, fish: session.fish } : { call: { ...call.state }, sdp: session.sdp };
+ const state = { ...call.state };
+ if ("fish" in session) return { call: state, fish: session.fish };
+ if ("gemini" in session) return { call: state, gemini: session.gemini };
+ return { call: state, sdp: session.sdp };
}
async end(callId: string): Promise<LiveCallState | null> {
@@ -311,7 +322,7 @@ export class LiveCallController {
call.socket = socket;
const attachTimer = this.later(call, () => {
if (!call.attached) this.finish(call, "sideband-lost", `The call could not connect to ${liveProviderName(call.endpoint.provider)}.`);
- }, call.endpoint.provider === "fish" ? FISH_ATTACH_TIMEOUT_MS : ATTACH_TIMEOUT_MS);
+ }, call.endpoint.provider === "fish" || call.endpoint.provider === "gemini" ? FISH_ATTACH_TIMEOUT_MS : ATTACH_TIMEOUT_MS);
socket.onopen = () => {
call.attached = true;
this.clear(call, attachTimer);
diff --git a/server/live-call.ts b/server/live-call.ts
index 89dd50ae6f..e072978713 100644
--- a/server/live-call.ts
+++ b/server/live-call.ts
@@ -10,6 +10,7 @@ export const MAX_SDP_BYTES = 64 * 1024;
export const LIVE_NEEDS_KEY = "Live calls use your own OpenAI key. Add it in Settings → API keys.";
export const LIVE_NEEDS_AZURE = "Live calls through Azure OpenAI need the resource endpoint, the GPT-Live deployment name and its key. Add them in Call settings.";
export const LIVE_NEEDS_FISH = "Live calls through Fish Audio use your Fish Audio API key. Add it in Settings → API keys.";
+export const LIVE_NEEDS_GEMINI = "Live calls through Gemini use your Gemini API key. Add it in Settings → API keys.";
/** The client's data channel is untrusted: it may only hang up; every append goes over the sideband.
* Exception: Azure OpenAI refuses `session.client`, so an Azure call goes without this list and its caller's channel keeps
@@ -45,12 +46,12 @@ export interface LiveEndpoint {
provider: LiveProvider;
/** The versioned API root, e.g. `https://api.openai.com/v1` or `https://my-res.openai.azure.com/openai/v1`. */
apiBase: string;
- /** The OpenAI model id, the Azure deployment name, or the Fish Audio agent id ('' until one is set up). */
+ /** The OpenAI model id, the Azure deployment name, the Fish Audio agent id ('' until one is set up) or the Gemini Live model id. */
model: string;
}
export function liveProviderName(provider: LiveProvider): string {
- return provider === "azure" ? "Azure OpenAI" : provider === "fish" ? "Fish Audio" : "OpenAI";
+ return provider === "azure" ? "Azure OpenAI" : provider === "fish" ? "Fish Audio" : provider === "gemini" ? "Gemini" : "OpenAI";
}
/** Only a loopback http URL is accepted, read at call time. */
diff --git a/server/live-config.ts b/server/live-config.ts
index b113c39827..ca04b7dd5e 100644
--- a/server/live-config.ts
+++ b/server/live-config.ts
@@ -4,11 +4,11 @@ import { z } from "zod";
export const LIVE_KEY_NEEDS_ENDPOINT = "Save the Azure endpoint first: a Live key works only with the endpoint it was saved for.";
const NOWHERE = "nowhere";
-/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`). `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key. `voice` is a GPT-Live voice. */
+/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish" or "gemini" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`) and Gemini calls the Gemini key (`tts.geminiKey`). `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key. `voice` is a GPT-Live voice. */
export const liveConfigSchema = z.object({
key: z.string().optional(),
keyFor: z.string().max(300).optional(),
- provider: z.enum(["openai", "azure", "fish"]).optional(),
+ provider: z.enum(["openai", "azure", "fish", "gemini"]).optional(),
azureEndpoint: z.string().trim().max(300).optional(),
azureDeployment: z.string().trim().max(64).optional(),
fishAgentId: z.string().trim().max(128).optional(),
@@ -21,7 +21,7 @@ export const liveConfigSchema = z.object({
export interface LiveConfig {
key?: string;
keyFor?: string;
- provider?: "openai" | "azure" | "fish";
+ provider?: "openai" | "azure" | "fish" | "gemini";
azureEndpoint?: string;
azureDeployment?: string;
fishAgentId?: string;
@@ -32,7 +32,7 @@ export interface LiveConfig {
}
/** Where a key saved now may go: "openai", or "azure:<host>"; null while Azure is chosen with no endpoint to tie it to.
- * Fish Audio calls never use this key, so with Fish chosen it stays OpenAI's. */
+ * Fish Audio and Gemini calls never use this key, so with either chosen it stays OpenAI's. */
export function liveKeyTarget(live: LiveConfig | undefined): string | null {
if (live?.provider !== "azure") return "openai";
try {
@@ -72,7 +72,7 @@ export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.Proc
next.key = envKey;
}
const provider = env.OMB_LIVE_PROVIDER?.trim().toLowerCase();
- if (provider === "openai" || provider === "azure" || provider === "fish") next.provider = provider;
+ if (provider === "openai" || provider === "azure" || provider === "fish" || provider === "gemini") next.provider = provider;
if (env.OMB_AZURE_OPENAI_LIVE_ENDPOINT !== undefined) next.azureEndpoint = env.OMB_AZURE_OPENAI_LIVE_ENDPOINT.trim();
if (env.OMB_AZURE_OPENAI_LIVE_DEPLOYMENT !== undefined) next.azureDeployment = env.OMB_AZURE_OPENAI_LIVE_DEPLOYMENT.trim();
if (env.OMB_FISH_LIVE_AGENT_ID?.trim()) {
diff --git a/server/live-gemini.test.ts b/server/live-gemini.test.ts
new file mode 100644
index 0000000000..47e68b6068
--- /dev/null
+++ b/server/live-gemini.test.ts
@@ -0,0 +1,89 @@
+import { describe, expect, it, vi } from "vitest";
+import { createGeminiLiveSession, geminiErrorMessage, geminiFieldMask, geminiLiveBaseUrl, geminiLiveEndpoint, geminiLiveSetup, GEMINI_LIVE_MODEL } from "./live-gemini.ts";
+import { FISH_DELEGATE_TOOL } from "./live-fish.ts";
+
+const NOW = Date.parse("2026-11-14T10:00:00Z");
+const ENDPOINT = geminiLiveEndpoint({});
+
+function fakeGemini(answer: () => Response = () => new Response(JSON.stringify({ name: "auth_tokens/tok-1" }), { status: 200 })) {
+ return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => answer());
+}
+
+const create = (fetchImpl: typeof fetch, key = " gemini-secret ") =>
+ createGeminiLiveSession({ key, endpoint: ENDPOINT, bot: { name: "Rigel" }, history: [], cloudHome: false, fetchImpl, now: () => NOW });
+
+describe("Gemini Live endpoint", () => {
+ it("talks to Google's v1beta API with the default Live model", () => {
+ expect(ENDPOINT).toEqual({ provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: GEMINI_LIVE_MODEL });
+ });
+
+ it("takes a model id from OMB_GEMINI_LIVE_MODEL and ignores anything else", () => {
+ expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "models/gemini-3.8-live-extended-thinking" }).model).toBe("gemini-3.8-live-extended-thinking");
+ expect(geminiLiveEndpoint({ OMB_GEMINI_LIVE_MODEL: "../evil?x=1" }).model).toBe(GEMINI_LIVE_MODEL);
+ });
+
+ it("accepts only a loopback override of the API's address", () => {
+ expect(geminiLiveBaseUrl({ OMB_GEMINI_LIVE_URL: "http://127.0.0.1:9123" })).toBe("http://127.0.0.1:9123");
+ expect(geminiLiveBaseUrl({ OMB_GEMINI_LIVE_URL: "https://evil.example" })).toBe("https://generativelanguage.googleapis.com");
+ });
+});
+
+describe("a Gemini Live call's token", () => {
+ it("is asked for with the key in a header, once, with the setup locked except session resumption", async () => {
+ const fetchImpl = fakeGemini();
+ const session = await create(fetchImpl);
+ const [url, init] = fetchImpl.mock.calls[0]!;
+ expect(String(url)).toBe("https://generativelanguage.googleapis.com/v1beta/auth_tokens");
+ expect(init!.headers).toMatchObject({ "x-goog-api-key": "gemini-secret" });
+ const body = JSON.parse(String(init!.body));
+ expect(body).toMatchObject({ uses: 1, newSessionExpireTime: "2026-11-14T10:01:00.000Z", expireTime: "2026-11-14T11:00:00.000Z" });
+ expect(body.bidiGenerateContentSetup).toMatchObject({ model: `models/${GEMINI_LIVE_MODEL}`, generationConfig: { responseModalities: ["AUDIO"] } });
+ expect(body.bidiGenerateContentSetup.systemInstruction.parts[0].text).toContain("Rigel");
+ expect(body.bidiGenerateContentSetup.tools[0].functionDeclarations[0]).toMatchObject({ name: FISH_DELEGATE_TOOL, behavior: "NON_BLOCKING" });
+ expect(body.fieldMask.split(",")).toEqual(expect.arrayContaining(["model", "generationConfig.responseModalities", "systemInstruction.parts", "tools", "contextWindowCompression.slidingWindow"]));
+ expect(body.fieldMask).not.toContain("sessionResumption");
+ expect(JSON.stringify(session)).not.toContain("gemini-secret");
+ expect(session).toEqual({
+ session_id: expect.stringMatching(/^gemini_[0-9a-f]{24}$/),
+ token: "auth_tokens/tok-1",
+ ws_url: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained",
+ model: `models/${GEMINI_LIVE_MODEL}`,
+ expires_at: "2026-11-14T10:01:00.000Z",
+ });
+ });
+
+ it("locks every field it sets, nested ones by their inner keys", () => {
+ expect(geminiFieldMask(geminiLiveSetup("m", "hi"))).toBe(
+ "model,generationConfig.responseModalities,systemInstruction.parts,tools,inputAudioTranscription,outputAudioTranscription,contextWindowCompression.slidingWindow");
+ });
+
+ it("connects a loopback override over ws", async () => {
+ const endpoint = geminiLiveEndpoint({ OMB_GEMINI_LIVE_URL: "http://127.0.0.1:9123" });
+ const session = await createGeminiLiveSession({ key: "k", endpoint, bot: { name: "R" }, history: [], cloudHome: false, fetchImpl: fakeGemini(), now: () => NOW });
+ expect(session.ws_url).toBe("ws://127.0.0.1:9123/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContentConstrained");
+ });
+
+ it("is never asked for without a key", async () => {
+ const fetchImpl = fakeGemini();
+ await expect(create(fetchImpl, " ")).rejects.toMatchObject({ status: 409 });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it("fails in words fit for the person, never Gemini's body", async () => {
+ const fetchImpl = fakeGemini(() => new Response("API key not valid: gemini-secret", { status: 400 }));
+ await expect(create(fetchImpl)).rejects.toMatchObject({ status: 502, message: geminiErrorMessage(400) });
+ await expect(create(fakeGemini(() => new Response("{}", { status: 403 })))).rejects.toMatchObject({ message: expect.stringContaining("rejected the API key") });
+ await expect(create(fakeGemini(() => new Response("{}", { status: 429 })))).rejects.toMatchObject({ status: 429 });
+ });
+
+ it("refuses an answer that is not a token", async () => {
+ for (const name of [undefined, "", "tokens/x", "auth_tokens/../x y"]) {
+ await expect(create(fakeGemini(() => new Response(JSON.stringify({ name }), { status: 200 })))).rejects.toMatchObject({ status: 502 });
+ }
+ });
+
+ it("says when Gemini cannot be reached", async () => {
+ const fetchImpl = vi.fn(async () => { throw new TypeError("fetch failed"); });
+ await expect(create(fetchImpl as unknown as typeof fetch)).rejects.toMatchObject({ status: 502, message: "Could not reach Gemini. Check the internet connection." });
+ });
+});
diff --git a/server/live-gemini.ts b/server/live-gemini.ts
new file mode 100644
index 0000000000..9721489353
--- /dev/null
+++ b/server/live-gemini.ts
@@ -0,0 +1,119 @@
+// Gemini Live calls. The Gemini key never leaves the harness: the client gets only a single-use ephemeral token whose setup
+// (model, instructions, the `delegate` tool) the harness locks here, and it relays what was said as a Fish Audio call does.
+import { randomBytes } from "node:crypto";
+import type { LiveGeminiSession } from "../shared/wire.ts";
+import { LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";
+import { FISH_DELEGATE_TOOL, fishInstructions } from "./live-fish.ts";
+
+const GEMINI_BASE = "https://generativelanguage.googleapis.com";
+const API_VERSION = "v1beta";
+export const GEMINI_LIVE_MODEL = "gemini-3.8-live";
+const MODEL = /^[\w.-]{1,80}$/;
+const CREATE_TIMEOUT_MS = 20_000;
+/** How long the client has to connect, and how long the call may then run, reconnecting with session resumption. */
+const CONNECT_WITHIN_MS = 60_000;
+const CALL_AT_MOST_MS = 60 * 60_000;
+const TOKEN = /^auth_tokens\/[\w.-]{1,512}$/;
+
+/** Only a loopback http URL is accepted, read at call time. */
+export function geminiLiveBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
+ const override = env.OMB_GEMINI_LIVE_URL?.trim() ?? "";
+ return /^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(override) ? override : GEMINI_BASE;
+}
+
+/** `model` is OMB_GEMINI_LIVE_MODEL when that is a model id, else the default Live model. */
+export function geminiLiveEndpoint(env: NodeJS.ProcessEnv = process.env): LiveEndpoint {
+ const model = env.OMB_GEMINI_LIVE_MODEL?.trim().replace(/^models\//, "") ?? "";
+ return { provider: "gemini", apiBase: `${geminiLiveBaseUrl(env)}/${API_VERSION}`, model: MODEL.test(model) ? model : GEMINI_LIVE_MODEL };
+}
+
+/** The setup every connection of the call gets, whatever the client sends: Gemini Live API `BidiGenerateContentSetup`. */
+export function geminiLiveSetup(model: string, instructions: string): Record<string, unknown> {
+ return {
+ model: `models/${model}`,
+ generationConfig: { responseModalities: ["AUDIO"] },
+ systemInstruction: { parts: [{ text: instructions }] },
+ tools: [{ functionDeclarations: [{
+ name: FISH_DELEGATE_TOOL,
+ description: "Hands the user's request to the assistant that does the work: looking things up, using apps and files, running tasks.",
+ parameters: { type: "OBJECT", properties: { request: { type: "STRING", description: "What the user asked for, in their own words." } }, required: ["request"] },
+ behavior: "NON_BLOCKING",
+ }] }],
+ inputAudioTranscription: {},
+ outputAudioTranscription: {},
+ // Audio-only sessions stop at 15 minutes without it.
+ contextWindowCompression: { slidingWindow: {} },
+ };
+}
+
+/** The locked fields, as @google/genai's `getFieldMasks` writes them. Session resumption is left out, so the client can
+ * reconnect the call with its handle when Gemini ends a connection (about every 10 minutes). */
+export function geminiFieldMask(setup: Record<string, unknown>): string {
+ return Object.entries(setup).flatMap(([key, value]) => value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length
+ ? Object.keys(value).map((inner) => `${key}.${inner}`)
+ : [key]).join(",");
+}
+
+export interface CreateGeminiSessionInput {
+ key: string;
+ endpoint: LiveEndpoint;
+ bot: LiveBot;
+ history: LiveHistoryMessage[];
+ cloudHome: boolean;
+ fetchImpl?: typeof fetch;
+ now?: () => number;
+}
+
+/** Gemini API `POST /v1beta/auth_tokens`. Errors carry a status and a message fit for the user: never the key, never
+ * Gemini's raw body. */
+export async function createGeminiLiveSession(input: CreateGeminiSessionInput): Promise<LiveGeminiSession> {
+ const key = input.key.trim();
+ if (!key) throw new LiveSessionError("Add a Gemini API key in Settings → API keys to use Live calls.", 409);
+ const now = (input.now ?? Date.now)();
+ const setup = geminiLiveSetup(input.endpoint.model, fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }));
+ const expiresAt = new Date(now + CONNECT_WITHIN_MS).toISOString();
+ let response: Response;
+ try {
+ response = await (input.fetchImpl ?? fetch)(`${input.endpoint.apiBase}/auth_tokens`, {
+ method: "POST",
+ headers: { "x-goog-api-key": key, "content-type": "application/json" },
+ redirect: "error",
+ body: JSON.stringify({
+ uses: 1,
+ expireTime: new Date(now + CALL_AT_MOST_MS).toISOString(),
+ newSessionExpireTime: expiresAt,
+ bidiGenerateContentSetup: setup,
+ fieldMask: geminiFieldMask(setup),
+ }),
+ signal: AbortSignal.timeout(CREATE_TIMEOUT_MS),
+ });
+ } catch (error) {
+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");
+ throw new LiveSessionError(timedOut ? "Gemini did not answer in time. Try the call again." : "Could not reach Gemini. Check the internet connection.", 502);
+ }
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => undefined);
+ throw new LiveSessionError(geminiErrorMessage(response.status), response.status === 429 ? 429 : 502);
+ }
+ const answer = await response.json().catch(() => null) as { name?: unknown } | null;
+ if (typeof answer?.name !== "string" || !TOKEN.test(answer.name)) throw new LiveSessionError("Gemini returned an unexpected answer. Try the call again.", 502);
+ const root = input.endpoint.apiBase.replace(/\/v1\w*$/, "").replace(/^http/, "ws");
+ return {
+ session_id: `gemini_${randomBytes(12).toString("hex")}`,
+ token: answer.name,
+ ws_url: `${root}/ws/google.ai.generativelanguage.${API_VERSION}.GenerativeService.BidiGenerateContentConstrained`,
+ model: `models/${input.endpoint.model}`,
+ expires_at: expiresAt,
+ };
+}
+
+export function geminiErrorMessage(status: number): string {
+ switch (status) {
+ case 400: return "Gemini rejected the call settings (HTTP 400).";
+ case 401:
+ case 403: return "Gemini rejected the API key. Check the Gemini key in Settings → API keys.";
+ case 404: return "Gemini could not find the Live model for calls.";
+ case 429: return "Gemini is limiting Live sessions on this key right now. Try again in a moment.";
+ default: return status >= 500 ? "Gemini had a problem starting the call. Try again in a moment." : `Gemini could not start the call (HTTP ${status}).`;
+ }
+}
diff --git a/server/live-session-wiring.test.ts b/server/live-session-wiring.test.ts
index 568a5427ba..586893b871 100644
--- a/server/live-session-wiring.test.ts
+++ b/server/live-session-wiring.test.ts
@@ -71,3 +71,26 @@ describe("a Fish Audio call's session", () => {
expect(() => w.calls.openSocket("sess_9", "k", endpoint)).toThrow("no relay for that session");
});
});
+
+describe("a Gemini Live call's session", () => {
+ const gemini = { provider: "gemini" as const, apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-3.8-live" };
+
+ it("takes a token from Gemini and answers with it and a relay, never the key", async () => {
+ const fetchImpl = vi.fn(async () => new Response(JSON.stringify({ name: "auth_tokens/t1" }), { status: 200 }));
+ const w = wiring(fetchImpl as unknown as typeof fetch);
+ const answer = await w.calls.createSession({ ...start, key: "gemini-secret", endpoint: gemini });
+ expect(fetchImpl).toHaveBeenCalledOnce();
+ expect(answer).toMatchObject({ gemini: { type: "gemini", session: { token: "auth_tokens/t1" } } });
+ expect(JSON.stringify(answer)).not.toContain("gemini-secret");
+ const { session, relayToken } = (answer as { gemini: { session: { session_id: string }; relayToken: string } }).gemini;
+ expect(answer.sessionId).toBe(session.session_id);
+ expect(w.fishRelay(session.session_id, relayToken)).not.toBeNull();
+ expect(w.calls.attachUrl(session.session_id, gemini)).toBe(session.session_id);
+ expect(w.calls.openSocket(session.session_id, "k", gemini)).toBeTruthy();
+ });
+
+ it("asks who is calling as for Fish Audio", () => {
+ const w = wiring(fakeFish());
+ expect(w.calls.geminiRefusal({ kind: "loopback", scopes: ["admin", "client"] })).toBeNull();
+ });
+});
diff --git a/server/live-session-wiring.ts b/server/live-session-wiring.ts
index d26c16be14..96a96c1688 100644
--- a/server/live-session-wiring.ts
+++ b/server/live-session-wiring.ts
@@ -2,9 +2,10 @@ import { productName } from "./brand.ts";
import type { LiveCallDeps } from "./live-call-controller.ts";
import { openLiveSocket } from "./live-call-controller.ts";
import { createLiveSession, liveAttachUrl, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";
-import { fishLiveCallRefusal } from "./live-access.ts";
+import { fishLiveCallRefusal, geminiLiveCallRefusal } from "./live-access.ts";
import type { LiveConfig } from "./live-config.ts";
import { createFishLiveSession, endFishLiveSession, fishKeyPrint, FishRelays, setUpFishAgent } from "./live-fish.ts";
+import { createGeminiLiveSession } from "./live-gemini.ts";
import type { LiveRouteDeps } from "./routes/live.ts";
export interface LiveSessionWiringInput {
@@ -21,12 +22,13 @@ export interface LiveSessionWiringInput {
}
/** How a Live call's session starts and is followed, per provider: GPT-Live's WebRTC session and sideband on OpenAI or
- * Azure, or a Fish Audio agent session followed through its client's relay. */
+ * Azure, or a Fish Audio agent or Gemini Live session followed through its client's relay. */
export function liveSessionWiring(input: LiveSessionWiringInput): {
- calls: Pick<LiveCallDeps, "fishRefusal" | "createSession" | "openSocket" | "attachUrl">;
+ calls: Pick<LiveCallDeps, "fishRefusal" | "geminiRefusal" | "createSession" | "openSocket" | "attachUrl">;
fishRelay: LiveRouteDeps["fishRelay"];
} {
const relays = new FishRelays();
+ const relayed = (endpoint: LiveEndpoint) => endpoint.provider === "fish" || endpoint.provider === "gemini";
const env = input.env ?? process.env;
const fetchImpl = input.fetchImpl ?? fetch;
@@ -54,7 +56,14 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {
fishRelay: (sessionId, token) => relays.find(sessionId, token),
calls: {
fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
+ geminiRefusal: (auth) => geminiLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {
+ if (endpoint.provider === "gemini") {
+ const session = await createGeminiLiveSession({ key, endpoint, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl });
+ // Gemini has nothing to end: the session ends when the client closes it, and the token is single use.
+ const { token } = relays.open(session.session_id, async () => undefined);
+ return { sessionId: session.session_id, gemini: { type: "gemini", session, relayToken: token } };
+ }
if (endpoint.provider !== "fish") {
return createLiveSession({ key, endpoint, sdp, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });
}
@@ -62,8 +71,8 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {
const { token } = relays.open(session.session_id, () => endFishLiveSession(session.session_id, key, agent, fetchImpl));
return { sessionId: session.session_id, fish: { type: "fish", session, relayToken: token } };
},
- openSocket: (url, key, endpoint) => endpoint.provider === "fish" ? relays.socket(url) : openLiveSocket(url, key, endpoint),
- attachUrl: (sessionId, endpoint) => endpoint.provider === "fish" ? sessionId : liveAttachUrl(sessionId, endpoint),
+ openSocket: (url, key, endpoint) => relayed(endpoint) ? relays.socket(url) : openLiveSocket(url, key, endpoint),
+ attachUrl: (sessionId, endpoint) => relayed(endpoint) ? sessionId : liveAttachUrl(sessionId, endpoint),
},
};
}
diff --git a/server/live-settings.test.ts b/server/live-settings.test.ts
index 062801d81b..49bca951b3 100644
--- a/server/live-settings.test.ts
+++ b/server/live-settings.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { AppConfig } from "./config.ts";
import { nestedKeyStatus } from "./key-hint.ts";
-import { LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_KEY } from "./live-call.ts";
+import { LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_GEMINI, LIVE_NEEDS_KEY } from "./live-call.ts";
import { fishKeyFromLiveKey, LIVE_KEY_NEEDS_ENDPOINT, liveConfigWithEnv, liveKeyTarget, liveSavePatch, usableLiveKey, type LiveConfig } from "./live-config.ts";
import { fishKeyPrint } from "./live-fish.ts";
import { LIVE_IDLE_MINUTES_DEFAULT, liveCallEndpoint, liveCallKey, liveCallSettings, liveSettingsFor, liveSettingsForClient, liveSetupProblem } from "./live-settings.ts";
@@ -291,3 +291,29 @@ describe("a saved Live key", () => {
});
});
});
+
+describe("Live calls through Gemini", () => {
+ const gemini = { provider: "gemini" as const };
+
+ it("use only the Gemini key, never the OpenAI API key or a key saved for another provider", () => {
+ for (const live of [gemini, { ...gemini, key: "k", keyFor: "openai" }, { ...gemini, key: "k", keyFor: "fish" }]) {
+ const cfg = { live, openai: { key: "sk-openai" }, tts: { fishKey: "fish" } } as AppConfig;
+ expect(liveCallKey(cfg), JSON.stringify(live)).toBeNull();
+ expect(liveSetupProblem(cfg)).toBe(LIVE_NEEDS_GEMINI);
+ }
+ });
+
+ it("are ready with the Gemini key that Gemini voices use, and report none of it", () => {
+ const cfg = { live: gemini, tts: { geminiKey: " gemini-secret " } } as AppConfig;
+ expect(liveCallKey(cfg)).toEqual({ key: "gemini-secret", source: "gemini" });
+ expect(liveCallEndpoint(cfg, {})).toEqual({ provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-3.8-live" });
+ expect(liveSetupProblem(cfg)).toBeNull();
+ const settings = liveSettingsFor(cfg);
+ expect(settings).toMatchObject({ configured: true, keySource: "gemini", provider: "gemini" });
+ expect(JSON.stringify(settings)).not.toContain("gemini-secret");
+ });
+
+ it("name the provider in what a call start reads, so the Gemini limit sees it before setup is done", () => {
+ expect(liveCallSettings({ live: gemini } as AppConfig)).toMatchObject({ provider: "gemini", key: "", setupProblem: LIVE_NEEDS_GEMINI });
+ });
+});
diff --git a/server/live-settings.ts b/server/live-settings.ts
index 8722e124c1..21d1c0deda 100644
--- a/server/live-settings.ts
+++ b/server/live-settings.ts
@@ -1,20 +1,25 @@
import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";
import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";
-import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";
+import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_GEMINI, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";
import { liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";
import { fishLiveEndpoint, usableFishAgent } from "./live-fish.ts";
+import { geminiLiveEndpoint } from "./live-gemini.ts";
export const LIVE_IDLE_MINUTES_DEFAULT = 5;
type LiveConfig = Pick<AppConfig, "live" | "openai" | "tts">;
/** A saved Live key goes only to the provider and host it was saved for (`usableLiveKey`), the OpenAI API key only ever to
- * OpenAI, and the Fish Audio key only to Fish Audio. */
+ * OpenAI, the Fish Audio key only to Fish Audio and the Gemini key only to Gemini. */
export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySource } | null {
if (cfg.live?.provider === "fish") {
const fish = cfg.tts?.fishKey?.trim();
return fish ? { key: fish, source: "fishAudio" } : null;
}
+ if (cfg.live?.provider === "gemini") {
+ const gemini = cfg.tts?.geminiKey?.trim();
+ return gemini ? { key: gemini, source: "gemini" } : null;
+ }
const live = usableLiveKey(cfg.live);
if (live) return { key: live, source: "live" };
if (cfg.live?.provider === "azure") return null;
@@ -27,12 +32,13 @@ export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySour
export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {
if (cfg.live?.provider === "azure") return azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment);
if (cfg.live?.provider === "fish") return fishLiveEndpoint(usableFishAgent(cfg.live, cfg.tts?.fishKey ?? ""), env);
+ if (cfg.live?.provider === "gemini") return geminiLiveEndpoint(env);
return openAiLiveEndpoint(env);
}
export function liveSetupProblem(cfg: LiveConfig): string | null {
const provider = cfg.live?.provider;
- const missing = provider === "azure" ? LIVE_NEEDS_AZURE : provider === "fish" ? LIVE_NEEDS_FISH : LIVE_NEEDS_KEY;
+ const missing = provider === "azure" ? LIVE_NEEDS_AZURE : provider === "fish" ? LIVE_NEEDS_FISH : provider === "gemini" ? LIVE_NEEDS_GEMINI : LIVE_NEEDS_KEY;
if (!liveCallKey(cfg)) return missing;
return liveCallEndpoint(cfg) ? null : missing;
}
@@ -61,7 +67,7 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {
return {
configured: liveSetupProblem(cfg) === null,
...(key ? { keySource: key.source } : {}),
- ...(provider === "azure" || provider === "fish" ? { provider } : {}),
+ ...(provider === "azure" || provider === "fish" || provider === "gemini" ? { provider } : {}),
...(cfg.live?.azureEndpoint ? { azureEndpoint: cfg.live.azureEndpoint } : {}),
...(cfg.live?.azureDeployment ? { azureDeployment: cfg.live.azureDeployment } : {}),
voice: cfg.live?.voice ?? "",
diff --git a/server/routes/live.ts b/server/routes/live.ts
index ece8a71892..74cba983e2 100644
--- a/server/routes/live.ts
+++ b/server/routes/live.ts
@@ -12,7 +12,7 @@ export interface LiveRouteDeps {
resolveTarget(botId: string, threadId: string | undefined): { botId: string; botName: string; threadId: string } | null;
settings(): LiveSettings;
saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; voice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;
- /** A running Fish Audio call's relay, only for the token its start answered with. */
+ /** A running Fish Audio or Gemini call's relay, only for the token its start answered with. */
fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[], from?: number): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
}
@@ -20,7 +20,7 @@ const id = z.string().regex(/^[\w-]{1,120}$/);
const sessionBody = z.object({
botId: id,
threadId: id.optional(),
- // Not trimmed: the SDP offer goes to OpenAI byte for byte. Absent on a Fish Audio call, which has no offer.
+ // Not trimmed: the SDP offer goes to OpenAI byte for byte. Absent on a Fish Audio or Gemini call, which has no offer.
sdp: z.string().min(1).refine((sdp) => Buffer.byteLength(sdp) <= MAX_SDP_BYTES).optional(),
client: z.enum(["desktop", "web", "ios", "android"]),
}).strict();
@@ -43,7 +43,7 @@ const relayBody = z.object({
}).strict();
// Strict, so `key` is refused rather than ignored: the key is saved only through the credential store or PUT /api/config.
const settingsBody = z.object({
- provider: z.enum(["openai", "azure", "fish"]).optional(),
+ provider: z.enum(["openai", "azure", "fish", "gemini"]).optional(),
// "" clears the field. Anything else must be an https Azure OpenAI host, since the key is sent there.
azureEndpoint: z.string().trim().max(300).refine((url) => url === "" || azureOpenAiRoot(url) !== null).optional(),
azureDeployment: z.string().trim().max(64).refine((name) => name === "" || azureLiveDeployment(name) === name).optional(),
@@ -81,7 +81,7 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
try {
const device = companionDevice(req);
const started = await deps.calls.start({ auth, ...(device ? { device } : {}), ...target, client: parsed.data.client, ...(parsed.data.sdp ? { sdp: parsed.data.sdp } : {}) });
- return json(res, 201, { call: started.call, transport: started.fish ?? { type: "webrtc", sdp: started.sdp } });
+ return json(res, 201, { call: started.call, transport: started.fish ?? started.gemini ?? { type: "webrtc", sdp: started.sdp } });
} catch (error) {
if (error instanceof LiveCallBusyError) return json(res, 409, { error: error.message, activeCall: error.call });
if (error instanceof LiveSessionError) {
diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsx
index eb0f196b79..468db87e0a 100644
--- a/src/components/LiveCallSettings.tsx
+++ b/src/components/LiveCallSettings.tsx
@@ -27,8 +27,9 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
}, []);
const azure = live.provider === "azure";
const fish = live.provider === "fish";
+ const gemini = live.provider === "gemini";
const copy = liveKeyCopy(live.provider);
- const hasKey = live.keySource === (fish ? "fishAudio" : "live");
+ const hasKey = live.keySource === (fish ? "fishAudio" : gemini ? "gemini" : "live");
const voice = live.voice || "marin";
const known = LIVE_VOICE_OPTIONS.some((option) => option.id === voice);
@@ -74,7 +75,8 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
}}
>
<LiveProviderSettings locked={keySaving} onSaving={setProviderSaving} />
- {!fish && <>
+ {/* Relayed calls speak in the provider's own voice. */}
+ {!fish && !gemini && <>
<label className="flex items-center justify-between gap-2">
<span className="text-ink-secondary">{t("call.live.voice")}</span>
<Select
@@ -126,13 +128,13 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
)}
</span>
</div>
- {!hasKey && (azure || fish) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}
- {live.keySource !== "live" && !azure && !fish && (
+ {!hasKey && (azure || fish || gemini) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}
+ {live.keySource !== "live" && !azure && !fish && !gemini && (
<div className="-mt-2 text-[12px] text-ink-tertiary">{t(live.keySource === "openai" ? "call.live.keyFromApiKeys" : "call.live.needsKey")} <KeysLink id="openai" purpose="liveCalls" /></div>
)}
{/* Keyed by provider: a key typed for one provider is never saved for another. */}
{changingKey && <LiveKeySetup key={state.config?.live?.provider ?? "openai"} compact locked={providerSaving} onSaving={setKeySaving} onSaved={() => setChangingKey(false)} />}
- <div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} {t(copy.cost)}</div>
+ <div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish, gemini })} {t(copy.cost)}</div>
{error && <div className="text-[12px] text-danger">{error}</div>}
</div>
);
diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsx
index 3b750e5c59..93c87f63db 100644
--- a/src/components/LiveKeyNeeded.tsx
+++ b/src/components/LiveKeyNeeded.tsx
@@ -15,18 +15,19 @@ export function LiveKeyNeeded() {
const live = state.config?.live;
const azure = live?.provider === "azure";
const fish = live?.provider === "fish";
+ const gemini = live?.provider === "gemini";
const copy = liveKeyCopy(live?.provider);
// A key is tied to the endpoint it is saved for, so the endpoint comes first.
- const keyForm = (azure && Boolean(live?.azureEndpoint) && live?.keySource !== "live") || (fish && live?.keySource !== "fishAudio");
+ const keyForm = (azure && Boolean(live?.azureEndpoint) && live?.keySource !== "live") || (fish && live?.keySource !== "fishAudio") || (gemini && live?.keySource !== "gemini");
return <section aria-labelledby={titleId} className="flex flex-col gap-2.5 rounded-xl border border-hairline bg-panel p-4 text-left text-[13px]">
<div className="flex items-start gap-2.5">
<KeyRound size={16} className="mt-0.5 shrink-0 text-ink-secondary" aria-hidden="true" />
<h2 id={titleId} className="text-[14px] font-medium leading-[1.4] text-ink">{t(copy.needs)}</h2>
</div>
<ProviderAndKey provider={live?.provider ?? "openai"} keyForm={keyForm} />
- {(azure || fish) && <DismissWhenReady ready={live?.configured === true} />}
- {!azure && !fish && <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(openKeySettings("openai", "liveCalls")); }}>{t("call.live.openApiKeys")}</button>}
- <p className="text-[12px] leading-[1.45] text-ink-tertiary">{!keyForm && `${liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} `}{t(copy.cost)}</p>
+ {(azure || fish || gemini) && <DismissWhenReady ready={live?.configured === true} />}
+ {!azure && !fish && !gemini && <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(openKeySettings("openai", "liveCalls")); }}>{t("call.live.openApiKeys")}</button>}
+ <p className="text-[12px] leading-[1.45] text-ink-tertiary">{!keyForm && `${liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish, gemini })} `}{t(copy.cost)}</p>
</section>;
}
diff --git a/src/components/LiveKeySetup.tsx b/src/components/LiveKeySetup.tsx
index 293e768cab..7982e6b524 100644
--- a/src/components/LiveKeySetup.tsx
+++ b/src/components/LiveKeySetup.tsx
@@ -19,6 +19,7 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = fals
const provider = state.config?.live?.provider;
const azure = provider === "azure";
const fish = provider === "fish";
+ const gemini = provider === "gemini";
const copy = liveKeyCopy(provider);
const [key, setKey] = useState("");
const [saving, setSaving] = useState(false);
@@ -36,8 +37,8 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = fals
setError(null);
try {
const status: ConfigStatus = window.ogb?.setCredential
- ? await window.ogb.setCredential(fish ? "fishAudioKey" : "openaiLiveKey", value)
- : await api("/api/config", { method: "PUT", body: JSON.stringify(fish ? { tts: { fishKey: value } } : { live: { key: value } }) });
+ ? await window.ogb.setCredential(fish ? "fishAudioKey" : gemini ? "geminiTtsKey" : "openaiLiveKey", value)
+ : await api("/api/config", { method: "PUT", body: JSON.stringify(fish ? { tts: { fishKey: value } } : gemini ? { tts: { geminiKey: value } } : { live: { key: value } }) });
dispatch({ type: "configStatus", config: status });
// The save may finish after the prompt was dismissed; never turn it into a call the user already cancelled.
if (!mounted.current) return;
@@ -63,14 +64,14 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = fals
>
<div className="text-[14px] font-medium text-ink">{t(copy.title)}</div>
<div className="text-[13px] leading-[1.45] text-ink-secondary">{t(copy.explain)}</div>
- <div className="text-[13px] leading-[1.45] text-ink-secondary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })}</div>
+ <div className="text-[13px] leading-[1.45] text-ink-secondary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish, gemini })}</div>
<input
type="password"
autoComplete="off"
spellCheck={false}
value={key}
onChange={(event) => setKey(event.target.value)}
- placeholder={azure || fish ? "…" : "sk-…"}
+ placeholder={azure || fish || gemini ? "…" : "sk-…"}
aria-label={t(copy.field)}
className="rounded-lg border border-hairline bg-inset px-3 py-2 text-[13px] text-ink outline-none focus:border-accent/60"
/>
diff --git a/src/components/LiveProviderSettings.tsx b/src/components/LiveProviderSettings.tsx
index 2173a2d77c..2b6c1ba9eb 100644
--- a/src/components/LiveProviderSettings.tsx
+++ b/src/components/LiveProviderSettings.tsx
@@ -50,6 +50,7 @@ export function LiveProviderSettings({ locked = false, onSaving }: { locked?: bo
<option value="openai">{t("call.live.provider.openai")}</option>
<option value="azure">{t("call.live.provider.azure")}</option>
<option value="fish">{t("call.live.provider.fish")}</option>
+ <option value="gemini">{t("call.live.provider.gemini")}</option>
</Select>
</label>
{provider === "azure" && (
@@ -98,6 +99,7 @@ export function LiveProviderSettings({ locked = false, onSaving }: { locked?: bo
</form>
)}
{provider === "fish" && <div className="text-[12px] leading-4 text-ink-secondary">{t("call.live.fishHint")}</div>}
+ {provider === "gemini" && <div className="text-[12px] leading-4 text-ink-secondary">{t("call.live.geminiHint")}</div>}
{error && <div className="text-[12px] text-danger">{error}</div>}
</div>
);
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index 0dd571b17e..fae215ffc3 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -220,16 +220,19 @@ export function keyEntry(id: KeyId): KeyEntry {
return entry;
}
-/** With Azure OpenAI or Fish Audio chosen for Live calls, the row for their key is about that service: required, and no OpenAI
- * key. With Fish Audio it is the Fish Audio key itself, which Fish voices use too. */
+/** With Azure OpenAI, Fish Audio or Gemini chosen for Live calls, the row for their key is about that service: required, and
+ * no OpenAI key. With Fish Audio or Gemini it is that service's key itself, which its voices use too. */
export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefined): KeyEntry {
const entry = keyEntry(id);
const provider = config?.live?.provider;
- if (id !== "liveKey" || (provider !== "azure" && provider !== "fish") || !entry.target) return entry;
+ if (id !== "liveKey" || (provider !== "azure" && provider !== "fish" && provider !== "gemini") || !entry.target) return entry;
const { shape: _openAiShape, ...target } = entry.target;
if (provider === "fish") {
return { ...entry, name: "Fish Audio", labelKey: "keys.label.fishAudio", purposeKey: "keys.purpose.liveKeyFish", target: keyEntry("fishAudio").target };
}
+ if (provider === "gemini") {
+ return { ...entry, name: "Gemini", labelKey: "keys.label.geminiTts", purposeKey: "keys.purpose.liveKeyGemini", target: keyEntry("geminiTts").target };
+ }
return { ...entry, name: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };
}
@@ -243,10 +246,11 @@ export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefi
return entry.target?.saved(config) ?? entry.status?.(config) ?? { configured: false };
}
-/** With Azure or Fish Audio chosen, Live calls do not use the OpenAI key the Live calls row points at, so that row is hidden. */
+/** With Azure, Fish Audio or Gemini chosen, Live calls do not use the OpenAI key the Live calls row points at, so that row is
+ * hidden. */
export function keyHidden(id: KeyId, config: ConfigStatus | null | undefined): boolean {
const provider = config?.live?.provider;
- return id === "liveCalls" && (provider === "azure" || provider === "fish");
+ return id === "liveCalls" && (provider === "azure" || provider === "fish" || provider === "gemini");
}
/** With `config`, the row is matched as shown: the Live key row by the provider Live calls use. */
diff --git a/src/lib/call-mode.ts b/src/lib/call-mode.ts
index 88299b7170..6ac3a21faf 100644
--- a/src/lib/call-mode.ts
+++ b/src/lib/call-mode.ts
@@ -12,13 +12,14 @@ export const CALL_MODES: ReadonlyArray<{ id: CallMode; label: LocaleKey }> = [
{ id: "live", label: "call.mode.live" },
];
-export function liveDisclosure({ cloudHome = false, azure = false, fish = false }: { cloudHome?: boolean; azure?: boolean; fish?: boolean } = {}): string {
+export function liveDisclosure({ cloudHome = false, azure = false, fish = false, gemini = false }: { cloudHome?: boolean; azure?: boolean; fish?: boolean; gemini?: boolean } = {}): string {
if (azure) return t(cloudHome ? "call.live.disclosureAzureCloud" : "call.live.disclosureAzure");
if (fish) return t(cloudHome ? "call.live.disclosureFishCloud" : "call.live.disclosureFish");
+ if (gemini) return t(cloudHome ? "call.live.disclosureGeminiCloud" : "call.live.disclosureGemini");
return t(cloudHome ? "call.live.disclosureCloud" : "call.live.disclosure");
}
-/** The copy about a Live call's key: Azure and Fish Audio need a key of their own, OpenAI can borrow the OpenAI key. */
+/** The copy about a Live call's key: Azure, Fish Audio and Gemini need a key of their own, OpenAI can borrow the OpenAI key. */
export function liveKeyCopy(provider: LiveProvider | undefined) {
if (provider === "azure") {
return { title: "call.live.azureKeyTitle", explain: "call.live.azureKeyExplain", field: "call.live.azureKeyField", key: "call.live.azureKey", missing: "call.live.azureNeedsKey", needs: "call.live.needsAzure", cost: "call.live.azureCost" } as const;
@@ -26,6 +27,9 @@ export function liveKeyCopy(provider: LiveProvider | undefined) {
if (provider === "fish") {
return { title: "call.live.fishKeyTitle", explain: "call.live.fishKeyExplain", field: "call.live.fishKeyField", key: "call.live.fishKey", missing: "call.live.fishNeedsKey", needs: "call.live.needsFish", cost: "call.live.fishCost" } as const;
}
+ if (provider === "gemini") {
+ return { title: "call.live.geminiKeyTitle", explain: "call.live.geminiKeyExplain", field: "call.live.geminiKeyField", key: "call.live.geminiKey", missing: "call.live.geminiNeedsKey", needs: "call.live.needsGemini", cost: "call.live.geminiCost" } as const;
+ }
return { title: "call.live.keyTitle", explain: "call.live.keyExplain", field: "call.live.keyField", key: "call.live.key", missing: "call.live.needsKey", needs: "call.live.needsKey", cost: "call.live.cost" } as const;
}
diff --git a/src/lib/live-call-fish.ts b/src/lib/live-call-fish.ts
index 684ce304da..9324cf675a 100644
--- a/src/lib/live-call-fish.ts
+++ b/src/lib/live-call-fish.ts
@@ -1,6 +1,6 @@
-// A Fish Audio call: Fish's SDK holds the microphone and the agent's audio; the harness hears the call only through what
-// this relays to POST /api/live/relay, and the bot's replies come back the same way.
-import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport } from "../../shared/wire";
+// A Fish Audio or Gemini Live call: the provider's session holds the microphone and the agent's audio; the harness hears
+// the call only through what this relays to POST /api/live/relay, and the bot's replies come back the same way.
+import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken } from "../../shared/wire";
/** The client tool the Fish agent calls to delegate; set up on the agent as a client tool with `expects_response`. */
export const FISH_DELEGATE_TOOL = "delegate";
@@ -20,8 +20,11 @@ export interface FishAgentSession {
end(): Promise<void>;
}
-export interface FishSessionOptions {
- sessionToken: LiveFishSessionToken;
+/** What a relayed call's client gets from the harness: the provider's session and the relay's token. */
+export type RelaySession = { session_id: string };
+
+export interface FishSessionOptions<S extends RelaySession = LiveFishSessionToken> {
+ sessionToken: S;
clientTools: Record<string, (params: Record<string, unknown>, context: { callId: string }) => Promise<unknown>>;
clientToolTimeoutMs: number;
callbacks: {
@@ -34,7 +37,7 @@ export interface FishSessionOptions {
};
}
-export type FishSessionStarter = (options: FishSessionOptions) => Promise<FishAgentSession>;
+export type FishSessionStarter<S extends RelaySession = LiveFishSessionToken> = (options: FishSessionOptions<S>) => Promise<FishAgentSession>;
/** Loaded on the first Fish call only. */
export const startFishAgentSession: FishSessionStarter = async (options) => {
@@ -53,17 +56,17 @@ export interface FishCallHooks {
heard(text: string): void;
/** What the agent is saying, for the caption. */
said(text: string): void;
- /** Fish ended the session. */
+ /** The provider ended the session. */
ended(reason: string): void;
now(): number;
}
type RelayAnswer = { commands: LiveFishRelayCommand[]; closed: boolean };
-export class FishCall {
- private readonly transport: LiveFishTransport;
+export class FishCall<S extends RelaySession = LiveFishSessionToken> {
+ private readonly transport: { session: S; relayToken: string };
private readonly hooks: FishCallHooks;
- private readonly starter: FishSessionStarter;
+ private readonly starter: FishSessionStarter<S>;
private readonly startedAt: number;
private session: FishAgentSession | null = null;
private closed = false;
@@ -75,14 +78,14 @@ export class FishCall {
private speakingSince: number | null = null;
private readonly waiting = new Map<string, (content: string | null) => void>();
- constructor(transport: LiveFishTransport, hooks: FishCallHooks, starter: FishSessionStarter = startFishAgentSession) {
+ constructor(transport: { session: S; relayToken: string }, hooks: FishCallHooks, starter: FishSessionStarter<S>) {
this.transport = transport;
this.hooks = hooks;
this.starter = starter;
this.startedAt = hooks.now();
}
- /** Joins the session; rejects as Fish's SDK does, e.g. with code `mic_permission_denied`. */
+ /** Joins the session; rejects as the starter does, e.g. with code `mic_permission_denied` or a NotAllowedError. */
async start(): Promise<void> {
const session = await this.starter({
sessionToken: this.transport.session,
@@ -116,7 +119,7 @@ export class FishCall {
void this.session?.setMicMuted(muted).catch(() => undefined);
}
- /** Ends the Fish session and stops relaying. */
+ /** Ends the provider's session and stops relaying. */
close(): void {
if (this.closed) return;
this.closed = true;
diff --git a/src/lib/live-call-gemini-audio.ts b/src/lib/live-call-gemini-audio.ts
new file mode 100644
index 0000000000..38c350291c
--- /dev/null
+++ b/src/lib/live-call-gemini-audio.ts
@@ -0,0 +1,127 @@
+// The microphone and speaker of a Gemini Live call: Gemini takes 16 kHz 16-bit PCM and answers with 24 kHz 16-bit PCM.
+const MIC_RATE = 16_000;
+const SPEAKER_RATE = 24_000;
+/** About 100 ms of microphone audio per message. */
+const MIC_CHUNK = MIC_RATE / 10;
+
+export interface GeminiAudio {
+ /** Opens the microphone; rejects as getUserMedia does, e.g. with NotAllowedError. */
+ startMic(onChunk: (pcm: ArrayBuffer) => void): Promise<void>;
+ play(pcm: ArrayBuffer): void;
+ /** Stops what is playing and queued, when the person talks over the agent. */
+ flush(): void;
+ idle(): boolean;
+ /** Called when the last queued audio has played. */
+ onIdle: (() => void) | null;
+ close(): void;
+}
+
+// Posts the input as it comes; the page resamples, so the worklet does not depend on the device's rate.
+const WORKLET = `registerProcessor("omb-mic", class extends AudioWorkletProcessor {
+ process(inputs) { const c = inputs[0] && inputs[0][0]; if (c) this.port.postMessage(c.slice(0)); return true; }
+});`;
+
+/** Linear resampling to 16 kHz 16-bit PCM; keeps the fractional position between calls. */
+export class MicResampler {
+ private readonly step: number;
+ private position = 0;
+ private last = 0;
+ private pending: number[] = [];
+
+ constructor(inputRate: number) {
+ this.step = inputRate / MIC_RATE;
+ }
+
+ /** Returns whole chunks of MIC_CHUNK samples ready to send. */
+ push(input: Float32Array): ArrayBuffer[] {
+ const at = (i: number) => (i < 0 ? this.last : input[i]);
+ while (this.position < input.length - 1) {
+ const base = Math.floor(this.position);
+ const frac = this.position - base;
+ const value = at(base) + (at(base + 1) - at(base)) * frac;
+ this.pending.push(Math.max(-1, Math.min(1, value)));
+ this.position += this.step;
+ }
+ this.position -= input.length;
+ if (input.length) this.last = input[input.length - 1];
+ const chunks: ArrayBuffer[] = [];
+ while (this.pending.length >= MIC_CHUNK) {
+ const samples = this.pending.splice(0, MIC_CHUNK);
+ const pcm = new Int16Array(samples.length);
+ samples.forEach((s, i) => (pcm[i] = s < 0 ? s * 0x8000 : s * 0x7fff));
+ chunks.push(pcm.buffer);
+ }
+ return chunks;
+ }
+}
+
+export function pcm16ToFloat(pcm: ArrayBuffer): Float32Array<ArrayBuffer> {
+ const view = new DataView(pcm);
+ const out = new Float32Array(Math.floor(pcm.byteLength / 2));
+ for (let i = 0; i < out.length; i++) out[i] = view.getInt16(i * 2, true) / 0x8000;
+ return out;
+}
+
+export function browserGeminiAudio(): GeminiAudio {
+ let context: AudioContext | null = new AudioContext();
+ let stream: MediaStream | null = null;
+ let node: AudioWorkletNode | null = null;
+ const playing = new Set<AudioBufferSourceNode>();
+ let nextAt = 0;
+ const audio: GeminiAudio = {
+ onIdle: null,
+ async startMic(onChunk) {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
+ if (!context) return void stream.getTracks().forEach((track) => track.stop());
+ await context.resume().catch(() => undefined);
+ const url = URL.createObjectURL(new Blob([WORKLET], { type: "application/javascript" }));
+ try {
+ await context.audioWorklet.addModule(url);
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ if (!context) return;
+ const resampler = new MicResampler(context.sampleRate);
+ node = new AudioWorkletNode(context, "omb-mic");
+ node.port.onmessage = (event: MessageEvent<Float32Array>) => resampler.push(event.data).forEach(onChunk);
+ context.createMediaStreamSource(stream).connect(node);
+ },
+ play(pcm) {
+ if (!context) return;
+ const samples = pcm16ToFloat(pcm);
+ if (!samples.length) return;
+ const buffer = context.createBuffer(1, samples.length, SPEAKER_RATE);
+ buffer.copyToChannel(samples, 0);
+ const source = context.createBufferSource();
+ source.buffer = buffer;
+ source.connect(context.destination);
+ nextAt = Math.max(nextAt, context.currentTime);
+ source.start(nextAt);
+ nextAt += buffer.duration;
+ playing.add(source);
+ source.onended = () => {
+ playing.delete(source);
+ if (!playing.size) audio.onIdle?.();
+ };
+ },
+ flush() {
+ for (const source of playing) {
+ source.onended = null;
+ try { source.stop(); } catch { /* not started yet */ }
+ }
+ playing.clear();
+ nextAt = 0;
+ },
+ idle: () => playing.size === 0,
+ close() {
+ audio.flush();
+ node?.disconnect();
+ node = null;
+ stream?.getTracks().forEach((track) => track.stop());
+ stream = null;
+ void context?.close().catch(() => undefined);
+ context = null;
+ },
+ };
+ return audio;
+}
diff --git a/src/lib/live-call-gemini.test.ts b/src/lib/live-call-gemini.test.ts
new file mode 100644
index 0000000000..9d4fb6ae9d
--- /dev/null
+++ b/src/lib/live-call-gemini.test.ts
@@ -0,0 +1,305 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { LiveGeminiSession, LiveGeminiTransport } from "../../shared/wire";
+import { FISH_DELEGATE_TOOL, type FishSessionOptions } from "./live-call-fish";
+import { MicResampler, pcm16ToFloat, type GeminiAudio } from "./live-call-gemini-audio";
+import { geminiSessionStarter, type GeminiSocket } from "./live-call-gemini";
+import { configureLiveMedia, liveMedia, resetLiveMedia, startLiveCall } from "./live-call-media";
+
+const SESSION: LiveGeminiSession = {
+ session_id: "gemini_1", token: "auth_tokens/a b", model: "models/gemini-3.8-live", expires_at: "",
+ ws_url: "wss://gemini.example/ws/BidiGenerateContentConstrained",
+};
+
+class FakeSocket implements GeminiSocket {
+ binaryType = "blob";
+ readyState = 0;
+ sent: Array<Record<string, any>> = [];
+ closed: number | null = null;
+ onopen: ((event: unknown) => void) | null = null;
+ onmessage: ((event: { data: unknown }) => void) | null = null;
+ onclose: ((event: { code: number }) => void) | null = null;
+ onerror: ((event: unknown) => void) | null = null;
+ constructor(readonly url: string) {}
+ send(data: string) { this.sent.push(JSON.parse(data)); }
+ close(code = 1000) { this.readyState = 3; this.closed = code; }
+ open() { this.readyState = 1; this.onopen?.({}); }
+ receive(message: Record<string, unknown>, binary = false) {
+ const text = JSON.stringify(message);
+ this.onmessage?.({ data: binary ? new TextEncoder().encode(text).buffer : text });
+ }
+ drop(code = 1011) { this.readyState = 3; this.onclose?.({ code }); }
+}
+
+class FakeAudio implements GeminiAudio {
+ onIdle: (() => void) | null = null;
+ played: number[] = [];
+ playing = 0;
+ flushed = 0;
+ closed = false;
+ mic: ((pcm: ArrayBuffer) => void) | null = null;
+ constructor(readonly denied = false) {}
+ async startMic(onChunk: (pcm: ArrayBuffer) => void) {
+ if (this.denied) throw Object.assign(new Error("denied"), { name: "NotAllowedError" });
+ this.mic = onChunk;
+ }
+ play(pcm: ArrayBuffer) { this.played.push(pcm.byteLength); this.playing += 1; }
+ flush() { this.flushed += 1; this.playing = 0; }
+ idle() { return this.playing === 0; }
+ finish() { this.playing = 0; this.onIdle?.(); }
+ close() { this.closed = true; }
+}
+
+function harness({ denied = false } = {}) {
+ const sockets: FakeSocket[] = [];
+ const audios: FakeAudio[] = [];
+ const start = geminiSessionStarter({
+ openSocket: (url) => { const socket = new FakeSocket(url); sockets.push(socket); return socket; },
+ audio: () => { const audio = new FakeAudio(denied); audios.push(audio); return audio; },
+ });
+ const callbacks = {
+ onConnect: vi.fn(), onDisconnect: vi.fn(), onModeChange: vi.fn(), onUserTranscript: vi.fn(), onAgentResponseDelta: vi.fn(), onError: vi.fn(),
+ };
+ const delegate = vi.fn(async (_params: Record<string, unknown>, _context: { callId: string }) => "On it.");
+ const options: FishSessionOptions<LiveGeminiSession> = { sessionToken: SESSION, clientTools: { [FISH_DELEGATE_TOOL]: delegate }, clientToolTimeoutMs: 12_000, callbacks };
+ const starting = start(options);
+ const socket = () => sockets.at(-1)!;
+ const connect = async () => {
+ socket().open();
+ socket().receive({ setupComplete: {} });
+ return await starting;
+ };
+ return { sockets, audios, callbacks, delegate, starting, socket, connect, audio: () => audios.at(-1)! };
+}
+
+const AUDIO = btoa(String.fromCharCode(1, 0, 2, 0));
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe("a Gemini Live session", () => {
+ it("connects with the token, sends only the model and resumption, and joins once Gemini and the microphone are ready", async () => {
+ const t = harness();
+ expect(t.socket().url).toBe(`${SESSION.ws_url}?access_token=auth_tokens%2Fa%20b`);
+ expect(t.socket().binaryType).toBe("arraybuffer");
+ t.socket().open();
+ expect(t.socket().sent).toEqual([{ setup: { model: SESSION.model, sessionResumption: {} } }]);
+ expect(t.callbacks.onConnect).not.toHaveBeenCalled();
+ t.socket().receive({ setupComplete: {} }, true);
+ await t.starting;
+ expect(t.callbacks.onConnect).toHaveBeenCalledWith({ sessionId: "gemini_1" });
+ t.audio().mic!(new Int16Array([1, 2]).buffer);
+ expect(t.socket().sent.at(-1)).toEqual({ realtimeInput: { audio: { mimeType: "audio/pcm;rate=16000", data: btoa(String.fromCharCode(1, 0, 2, 0)) } } });
+ });
+
+ it("rejects as the browser does when the microphone is refused, and closes the connection", async () => {
+ const t = harness({ denied: true });
+ t.socket().open();
+ t.socket().receive({ setupComplete: {} });
+ await expect(t.starting).rejects.toMatchObject({ name: "NotAllowedError" });
+ expect(t.socket().closed).toBe(1000);
+ expect(t.audio().closed).toBe(true);
+ expect(t.callbacks.onConnect).not.toHaveBeenCalled();
+ });
+
+ it("rejects when Gemini closes before the setup is taken", async () => {
+ const t = harness();
+ t.socket().open();
+ t.socket().drop(1008);
+ await expect(t.starting).rejects.toMatchObject({ code: "gemini_1008" });
+ });
+
+ it("plays the agent, speaking until its turn is done and played, then listening", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ serverContent: { modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm;rate=24000", data: AUDIO } }] } } });
+ expect(t.audio().played).toEqual([4]);
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("speaking");
+ t.socket().receive({ serverContent: { turnComplete: true } });
+ expect(t.callbacks.onModeChange).toHaveBeenCalledTimes(1);
+ t.audio().finish();
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");
+ });
+
+ it("stops the agent's audio when the person talks over it", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ serverContent: { modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm", data: AUDIO } }] } } });
+ t.socket().receive({ serverContent: { interrupted: true } });
+ expect(t.audio().flushed).toBe(1);
+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");
+ });
+
+ it("captions the person as they speak, final once the agent answers, and the agent's whole turn", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ serverContent: { inputTranscription: { text: "check " } } });
+ t.socket().receive({ serverContent: { inputTranscription: { text: "my mail" } } });
+ expect(t.callbacks.onUserTranscript).toHaveBeenLastCalledWith({ segmentId: "s0", text: "check my mail", final: false });
+ t.socket().receive({ serverContent: { outputTranscription: { text: "Sure, " } } });
+ expect(t.callbacks.onUserTranscript).toHaveBeenLastCalledWith({ segmentId: "s0", text: "check my mail", final: true });
+ t.socket().receive({ serverContent: { outputTranscription: { text: "checking." } } });
+ expect(t.callbacks.onAgentResponseDelta).toHaveBeenLastCalledWith({ segmentId: "a1", text: "Sure, checking." });
+ t.socket().receive({ serverContent: { turnComplete: true } });
+ t.socket().receive({ serverContent: { outputTranscription: { text: "Done." } } });
+ expect(t.callbacks.onAgentResponseDelta).toHaveBeenLastCalledWith({ segmentId: "a1", text: "Done." });
+ });
+
+ it("hands a delegate call over once what was heard is final, and answers Gemini when the agent is idle", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ serverContent: { inputTranscription: { text: "book a table" } } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: { request: "book a table" } }] } });
+ expect(t.callbacks.onUserTranscript).toHaveBeenLastCalledWith({ segmentId: "s0", text: "book a table", final: true });
+ expect(t.delegate).toHaveBeenCalledWith({ request: "book a table" }, { callId: "fc_1" });
+ await settle();
+ expect(t.socket().sent.at(-1)).toEqual({ toolResponse: { functionResponses: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, response: { result: "On it.", scheduling: "WHEN_IDLE" } }] } });
+ });
+
+ it("passes the bot's updates on, answering only those meant to be heard", async () => {
+ const t = harness();
+ const session = await t.connect();
+ session.sendUserMessage("[OpenMausBot] two emails", { audio: true });
+ session.sendUserMessage("[OpenMausBot] still looking", { audio: false });
+ expect(t.socket().sent.slice(-2)).toEqual([
+ { clientContent: { turns: [{ role: "user", parts: [{ text: "[OpenMausBot] two emails" }] }], turnComplete: true } },
+ { clientContent: { turns: [{ role: "user", parts: [{ text: "[OpenMausBot] still looking" }] }], turnComplete: false } },
+ ]);
+ });
+
+ it("holds the bot's updates while the agent speaks, so they do not cut it off", async () => {
+ const t = harness();
+ const session = await t.connect();
+ t.socket().receive({ serverContent: { modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm", data: AUDIO } }] } } });
+ session.sendUserMessage("[OpenMausBot] two emails", { audio: true });
+ expect(t.socket().sent.at(-1)).not.toHaveProperty("clientContent");
+ t.socket().receive({ serverContent: { turnComplete: true } });
+ expect(t.socket().sent.at(-1)).not.toHaveProperty("clientContent");
+ t.audio().finish();
+ expect(t.socket().sent.at(-1)).toEqual({ clientContent: { turns: [{ role: "user", parts: [{ text: "[OpenMausBot] two emails" }] }], turnComplete: true } });
+ });
+
+ it("sends no microphone audio while muted", async () => {
+ const t = harness();
+ const session = await t.connect();
+ await session.setMicMuted(true);
+ expect(t.socket().sent.at(-1)).toEqual({ realtimeInput: { audioStreamEnd: true } });
+ const sent = t.socket().sent.length;
+ t.audio().mic!(new Int16Array([1]).buffer);
+ expect(t.socket().sent).toHaveLength(sent);
+ await session.setMicMuted(false);
+ t.audio().mic!(new Int16Array([1]).buffer);
+ expect(t.socket().sent).toHaveLength(sent + 1);
+ });
+
+ it("goes on over a new connection with the resumption handle when Gemini ends one", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
+ t.socket().receive({ goAway: { timeLeft: "5s" } });
+ t.socket().drop(1000);
+ expect(t.sockets).toHaveLength(2);
+ t.socket().open();
+ expect(t.socket().sent).toEqual([{ setup: { model: SESSION.model, sessionResumption: { handle: "h-2" } } }]);
+ t.socket().receive({ setupComplete: {} });
+ expect(t.callbacks.onDisconnect).not.toHaveBeenCalled();
+ expect(t.callbacks.onConnect).toHaveBeenCalledTimes(1);
+ expect(t.audios).toHaveLength(1);
+ t.audio().mic!(new Int16Array([1]).buffer);
+ expect(t.socket().sent.at(-1)).toHaveProperty("realtimeInput");
+ });
+
+ it("keeps tool answers and updates made between connections for the resumed one, in order", async () => {
+ const t = harness();
+ const session = await t.connect();
+ t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
+ t.socket().receive({ toolCall: { functionCalls: [{ id: "fc_1", name: FISH_DELEGATE_TOOL, args: { request: "x" } }] } });
+ t.socket().drop(1000);
+ await settle();
+ session.sendUserMessage("[OpenMausBot] done", { audio: true });
+ t.socket().open();
+ expect(t.socket().sent).toHaveLength(1);
+ t.socket().receive({ setupComplete: {} });
+ expect(t.socket().sent.slice(1).map((m) => Object.keys(m)[0])).toEqual(["toolResponse", "clientContent"]);
+ });
+
+ it("ends the call when a resumed connection is refused instead of trying again", async () => {
+ const t = harness();
+ await t.connect();
+ t.socket().receive({ sessionResumptionUpdate: { newHandle: "h-2", resumable: true } });
+ t.socket().receive({ goAway: { timeLeft: "1s" } });
+ t.socket().drop(1000);
+ t.socket().open();
+ t.socket().drop(1008);
+ expect(t.sockets).toHaveLength(2);
+ expect(t.callbacks.onDisconnect).toHaveBeenCalledWith({ reason: "conversation_timeout" });
+ expect(t.audio().closed).toBe(true);
+ });
+
+ it("ends the call when a connection drops with nothing to resume, saying whether Gemini's time ran out", async () => {
+ const lost = harness();
+ await lost.connect();
+ lost.socket().drop();
+ expect(lost.callbacks.onDisconnect).toHaveBeenCalledWith({ reason: "connection_lost" });
+ expect(lost.audio().closed).toBe(true);
+ const timedOut = harness();
+ await timedOut.connect();
+ timedOut.socket().receive({ goAway: { timeLeft: "1s" } });
+ timedOut.socket().drop();
+ expect(timedOut.callbacks.onDisconnect).toHaveBeenCalledWith({ reason: "conversation_timeout" });
+ });
+
+ it("on end closes the connection and the audio without reporting a disconnect", async () => {
+ const t = harness();
+ const session = await t.connect();
+ await session.end();
+ expect(t.socket().closed).toBe(1000);
+ expect(t.audio().closed).toBe(true);
+ session.sendUserMessage("late");
+ expect(t.socket().sent.at(-1)).not.toHaveProperty("clientContent");
+ expect(t.callbacks.onDisconnect).not.toHaveBeenCalled();
+ });
+});
+
+describe("Gemini call audio", () => {
+ it("resamples the microphone to 16 kHz in 100 ms chunks, across calls", () => {
+ const resampler = new MicResampler(48_000);
+ const input = new Float32Array(2_400).fill(0.5);
+ expect(resampler.push(input)).toEqual([]);
+ const chunks = resampler.push(input);
+ expect(chunks).toHaveLength(1);
+ const pcm = new Int16Array(chunks[0]!);
+ expect(pcm).toHaveLength(1_600);
+ expect(pcm.every((s) => s === Math.round(0.5 * 0x7fff) || s === Math.floor(0.5 * 0x7fff))).toBe(true);
+ });
+
+ it("reads Gemini's 16-bit little-endian PCM", () => {
+ expect(Array.from(pcm16ToFloat(new Int16Array([0, 16384, -32768]).buffer))).toEqual([0, 0.5, -1]);
+ });
+});
+
+describe("a Gemini Live call on screen", () => {
+ const live = { callId: "c1", botId: "b1", threadId: "t1", client: "web", voice: "agent", startedAt: 5, status: "connecting" } as const;
+ const transport: LiveGeminiTransport = { type: "gemini", session: SESSION, relayToken: "relay-token" };
+
+ beforeEach(() => {
+ vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
+ resetLiveMedia();
+ });
+ afterEach(() => { resetLiveMedia(); vi.unstubAllGlobals(); });
+
+ it("asks the harness for a session without an offer and starts Gemini's, not Fish's", async () => {
+ const request = vi.fn(async (path: string) => {
+ if (path === "/api/live/session") return { call: live, transport };
+ return { commands: [], closed: false };
+ });
+ const startFish = vi.fn();
+ const startGemini = vi.fn(async () => ({ sendUserMessage: vi.fn(), setMicMuted: vi.fn(async () => {}), end: vi.fn(async () => {}) }));
+ const getUserMedia = vi.fn();
+ configureLiveMedia({ request: request as never, startFish: startFish as never, startGemini: startGemini as never, getUserMedia: getUserMedia as never, createPeer: vi.fn() as never });
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "gemini" });
+ const [, init] = request.mock.calls.find(([path]) => path === "/api/live/session")! as unknown as [string, RequestInit];
+ expect(JSON.parse(String(init.body))).toEqual({ botId: "b1", threadId: "t1", client: "web" });
+ expect(getUserMedia).not.toHaveBeenCalled();
+ expect(startFish).not.toHaveBeenCalled();
+ expect(startGemini).toHaveBeenCalledWith(expect.objectContaining({ sessionToken: SESSION }));
+ expect(liveMedia()).toMatchObject({ phase: "starting", callId: "c1", provider: "gemini" });
+ });
+});
diff --git a/src/lib/live-call-gemini.ts b/src/lib/live-call-gemini.ts
new file mode 100644
index 0000000000..7ac32a5f49
--- /dev/null
+++ b/src/lib/live-call-gemini.ts
@@ -0,0 +1,293 @@
+// A Gemini Live call: this page holds Gemini's WebSocket, the microphone and the agent's audio, and FishCall relays what
+// was said to the harness as on a Fish Audio call. The token's setup is locked by the harness (server/live-gemini.ts), so
+// the setup sent here only names the model and the session to resume.
+import type { LiveGeminiSession } from "../../shared/wire";
+import { browserGeminiAudio, type GeminiAudio } from "./live-call-gemini-audio";
+import type { FishAgentSession, FishSessionOptions, FishSessionStarter } from "./live-call-fish";
+
+const MIC_MIME = "audio/pcm;rate=16000";
+/** Gemini ends each connection after about 10 minutes; the call goes on over a new one, this many times at most. */
+const MAX_RECONNECTS = 12;
+
+/** The part of the browser WebSocket a call uses. */
+export interface GeminiSocket {
+ binaryType: string;
+ readyState: number;
+ onopen: ((event: unknown) => void) | null;
+ onmessage: ((event: { data: unknown }) => void) | null;
+ onclose: ((event: { code: number }) => void) | null;
+ onerror: ((event: unknown) => void) | null;
+ send(data: string): void;
+ close(code?: number): void;
+}
+
+export interface GeminiSessionDeps {
+ openSocket(url: string): GeminiSocket;
+ audio(): GeminiAudio;
+}
+
+const browserDeps: GeminiSessionDeps = {
+ openSocket: (url) => new WebSocket(url) as unknown as GeminiSocket,
+ audio: browserGeminiAudio,
+};
+
+type ServerMessage = {
+ setupComplete?: unknown;
+ serverContent?: {
+ modelTurn?: { parts?: Array<{ inlineData?: { mimeType?: string; data?: string } }> };
+ inputTranscription?: { text?: string };
+ outputTranscription?: { text?: string };
+ interrupted?: boolean;
+ turnComplete?: boolean;
+ };
+ toolCall?: { functionCalls?: Array<{ id?: string; name?: string; args?: Record<string, unknown> }> };
+ goAway?: unknown;
+ sessionResumptionUpdate?: { newHandle?: string; resumable?: boolean };
+};
+
+export function geminiSessionStarter(deps: GeminiSessionDeps = browserDeps): FishSessionStarter<LiveGeminiSession> {
+ return (options) => new GeminiLiveSession(options, deps).start();
+}
+
+export const startGeminiLiveSession = geminiSessionStarter();
+
+function decodeBase64(data: string): ArrayBuffer {
+ const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));
+ return bytes.buffer;
+}
+
+function encodeBase64(buffer: ArrayBuffer): string {
+ const bytes = new Uint8Array(buffer);
+ let text = "";
+ for (let i = 0; i < bytes.length; i += 0x8000) text += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
+ return btoa(text);
+}
+
+class GeminiLiveSession implements FishAgentSession {
+ private readonly options: FishSessionOptions<LiveGeminiSession>;
+ private readonly deps: GeminiSessionDeps;
+ private socket: GeminiSocket | null = null;
+ private audio: GeminiAudio | null = null;
+ private ready = false;
+ private ended = false;
+ private muted = false;
+ private handle: string | null = null;
+ private reconnects = 0;
+ private wentAway = false;
+ /** The connection now being resumed was ended by Gemini, e.g. at the call's time limit. */
+ private resumingAfterGoAway = false;
+ /** A connection is set up and can take messages. */
+ private linked = false;
+ /** Tool answers and the bot's words, in order, held while there is no connection or, for words, while the agent speaks:
+ * client content interrupts what Gemini is saying. */
+ private outbox: Array<{ toolResponse: unknown } | { clientContent: unknown }> = [];
+ private segment = 0;
+ private heard = "";
+ /** What the agent has said this turn: the caption shows the whole turn, Gemini sends it in pieces. */
+ private said = "";
+ private speaking = false;
+ private turnDone = false;
+
+ constructor(options: FishSessionOptions<LiveGeminiSession>, deps: GeminiSessionDeps) {
+ this.options = options;
+ this.deps = deps;
+ }
+
+ /** Resolves once Gemini has taken the setup and the microphone is open. */
+ start(): Promise<FishAgentSession> {
+ return new Promise((resolve, reject) => {
+ this.connect(async () => {
+ try {
+ this.audio = this.deps.audio();
+ this.audio.onIdle = () => this.playbackIdle();
+ await this.audio.startMic((pcm) => this.sendAudio(pcm));
+ } catch (error) {
+ this.shut();
+ return reject(error);
+ }
+ if (this.ended) return resolve(this);
+ this.ready = true;
+ this.options.callbacks.onConnect({ sessionId: this.options.sessionToken.session_id });
+ resolve(this);
+ }, (code) => reject(Object.assign(new Error("Gemini closed the call before it started."), { code: `gemini_${code}` })));
+ });
+ }
+
+ sendUserMessage(text: string, options?: { audio?: boolean }): void {
+ // Without turnComplete the words join the context and Gemini does not answer them.
+ this.post({ clientContent: { turns: [{ role: "user", parts: [{ text }] }], turnComplete: options?.audio !== false } });
+ }
+
+ async setMicMuted(muted: boolean): Promise<void> {
+ if (muted && !this.muted) this.send({ realtimeInput: { audioStreamEnd: true } });
+ this.muted = muted;
+ }
+
+ async end(): Promise<void> {
+ this.ended = true;
+ this.shut();
+ }
+
+ private shut(): void {
+ const socket = this.socket;
+ this.socket = null;
+ if (socket) {
+ socket.onclose = null;
+ socket.close(1000);
+ }
+ this.audio?.close();
+ this.audio = null;
+ }
+
+ private connect(onSetup: () => void, onEarlyClose: (code: number) => void): void {
+ const session = this.options.sessionToken;
+ const socket = this.deps.openSocket(`${session.ws_url}?access_token=${encodeURIComponent(session.token)}`);
+ socket.binaryType = "arraybuffer";
+ this.socket = socket;
+ let setUp = false;
+ socket.onopen = () => {
+ socket.send(JSON.stringify({ setup: { model: session.model, sessionResumption: this.handle ? { handle: this.handle } : {} } }));
+ };
+ socket.onmessage = (event) => {
+ const message = this.parse(event.data);
+ if (!message) return;
+ if (message.setupComplete !== undefined && !setUp) {
+ setUp = true;
+ this.linked = true;
+ onSetup();
+ this.flush();
+ return;
+ }
+ this.onMessage(message);
+ };
+ socket.onerror = () => undefined;
+ socket.onclose = (event) => {
+ if (this.socket !== socket) return;
+ this.socket = null;
+ this.linked = false;
+ if (setUp) return this.lost(true);
+ // A resume Gemini refused, e.g. past the token's time limit, is not tried again.
+ if (this.ready) return this.lost(false);
+ this.shut();
+ onEarlyClose(event.code);
+ };
+ }
+
+ /** A connection Gemini ended goes on over a new one while the session can be resumed. */
+ private lost(resumable: boolean): void {
+ if (this.ended) return;
+ if (resumable && this.handle && this.reconnects < MAX_RECONNECTS) {
+ this.reconnects += 1;
+ this.resumingAfterGoAway = this.wentAway;
+ this.wentAway = false;
+ this.connect(() => undefined, () => undefined);
+ return;
+ }
+ const reason = this.wentAway || (!resumable && this.resumingAfterGoAway) ? "conversation_timeout" : "connection_lost";
+ this.ended = true;
+ this.shut();
+ this.options.callbacks.onDisconnect({ reason });
+ }
+
+ private parse(data: unknown): ServerMessage | null {
+ try {
+ const text = typeof data === "string" ? data : new TextDecoder().decode(data as ArrayBuffer);
+ const message = JSON.parse(text) as unknown;
+ return message && typeof message === "object" ? message as ServerMessage : null;
+ } catch {
+ return null;
+ }
+ }
+
+ private onMessage(message: ServerMessage): void {
+ const content = message.serverContent;
+ if (content) {
+ const heard = content.inputTranscription?.text;
+ if (heard) {
+ this.heard += heard;
+ this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text: this.heard, final: false });
+ }
+ for (const part of content.modelTurn?.parts ?? []) {
+ if (!part.inlineData?.data || !part.inlineData.mimeType?.startsWith("audio/")) continue;
+ this.finishHeard();
+ this.turnDone = false;
+ this.audio?.play(decodeBase64(part.inlineData.data));
+ if (!this.speaking) {
+ this.speaking = true;
+ this.options.callbacks.onModeChange("speaking");
+ }
+ }
+ const said = content.outputTranscription?.text;
+ if (said) {
+ this.finishHeard();
+ this.said += said;
+ this.options.callbacks.onAgentResponseDelta({ segmentId: `a${this.segment}`, text: this.said });
+ }
+ if (content.interrupted || content.turnComplete) this.said = "";
+ if (content.interrupted) {
+ this.audio?.flush();
+ this.turnDone = true;
+ this.playbackIdle();
+ }
+ if (content.turnComplete) {
+ this.finishHeard();
+ this.turnDone = true;
+ if (this.audio?.idle() !== false) this.playbackIdle();
+ }
+ }
+ for (const call of message.toolCall?.functionCalls ?? []) this.onToolCall(call);
+ if (message.goAway !== undefined) this.wentAway = true;
+ const update = message.sessionResumptionUpdate;
+ if (update?.resumable && typeof update.newHandle === "string" && update.newHandle) this.handle = update.newHandle;
+ }
+
+ private finishHeard(): void {
+ if (!this.heard) return;
+ const text = this.heard;
+ this.heard = "";
+ this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text, final: true });
+ this.segment += 1;
+ }
+
+ private playbackIdle(): void {
+ if (!this.speaking || !this.turnDone) return;
+ this.speaking = false;
+ this.options.callbacks.onModeChange("listening");
+ this.flush();
+ }
+
+ private onToolCall(call: { id?: string; name?: string; args?: Record<string, unknown> }): void {
+ // The harness reads the request from what it heard, so that goes first.
+ this.finishHeard();
+ const id = call.id ?? "";
+ const name = call.name ?? "";
+ const tool = this.options.clientTools[name];
+ const answer = tool ? tool(call.args ?? {}, { callId: id }) : Promise.resolve(`There is no tool named ${name}.`);
+ void answer.then((result) => {
+ this.post({ toolResponse: { functionResponses: [{ id, name, response: { result: String(result), scheduling: "WHEN_IDLE" } }] } });
+ }, () => undefined);
+ }
+
+ private sendAudio(pcm: ArrayBuffer): void {
+ if (!this.ready || this.muted) return;
+ this.send({ realtimeInput: { audio: { mimeType: MIC_MIME, data: encodeBase64(pcm) } } });
+ }
+
+ /** Sent now, or kept for the next connection and, for the bot's words, for when the agent stops speaking. */
+ private post(message: { toolResponse: unknown } | { clientContent: unknown }): void {
+ if (this.ended) return;
+ this.outbox.push(message);
+ this.flush();
+ }
+
+ private flush(): void {
+ while (this.linked && this.socket?.readyState === 1 && this.outbox.length && !(this.speaking && "clientContent" in this.outbox[0])) {
+ this.send(this.outbox.shift());
+ }
+ }
+
+ private send(message: unknown): void {
+ if (this.ended || this.socket?.readyState !== 1) return;
+ this.socket.send(JSON.stringify(message));
+ }
+}
diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.ts
index c6144610dc..7513f54556 100644
--- a/src/lib/live-call-media.ts
+++ b/src/lib/live-call-media.ts
@@ -1,11 +1,12 @@
// Its data channel may only send session.close; everything else about the call runs on the harness.
import { useSyncExternalStore } from "react";
-import type { LiveCallState, LiveEndReason, LiveFishTransport, LiveProvider } from "../../shared/wire";
+import type { LiveCallState, LiveEndReason, LiveFishTransport, LiveGeminiSession, LiveGeminiTransport, LiveProvider } from "../../shared/wire";
import { api, ApiError } from "@/state/store";
import { openExternalLink } from "./app-links";
import { endCall, startCall } from "./call";
import { desktopCapabilitiesNow } from "./desktop";
-import { FishCall, isFishMicDenied, startFishAgentSession, type FishSessionStarter } from "./live-call-fish";
+import { FishCall, isFishMicDenied, startFishAgentSession, type FishCallHooks, type FishSessionStarter } from "./live-call-fish";
+import { startGeminiLiveSession } from "./live-call-gemini";
import { t } from "./i18n";
export type LiveMediaPhase = "idle" | "starting" | "live" | "ending" | "ended" | "failed";
@@ -46,6 +47,7 @@ export interface LiveMediaDeps {
pageMicrophone(): Promise<"allowed" | "refused" | undefined>;
openInBrowser(url: string): void;
startFish: FishSessionStarter;
+ startGemini: FishSessionStarter<LiveGeminiSession>;
}
const IDLE: LiveMediaState = {
@@ -91,6 +93,7 @@ const defaults: LiveMediaDeps = {
},
openInBrowser: (url) => void openExternalLink(url).catch(() => undefined),
startFish: startFishAgentSession,
+ startGemini: startGeminiLiveSession,
};
let deps: LiveMediaDeps = defaults;
@@ -99,7 +102,7 @@ let generation = 0;
let microphone: MediaStream | null = null;
let peer: RTCPeerConnection | null = null;
let channel: RTCDataChannel | null = null;
-let fishCall: FishCall | null = null;
+let fishCall: Pick<FishCall, "setMuted" | "close"> | null = null;
let fishConnected = false;
let heardTimer: ReturnType<typeof setTimeout> | null = null;
let noticeTimer: ReturnType<typeof setTimeout> | null = null;
@@ -193,7 +196,7 @@ export async function startLiveCall(target: { botId: string; threadId: string; p
set({ ...IDLE, phase: "starting", ...where });
startCall(target.botId);
try {
- if (target.provider === "fish") return await startFishCall(target, mine);
+ if (target.provider === "fish" || target.provider === "gemini") return await startFishCall(target, mine);
const stream = await deps.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
if (mine !== generation) return void stream.getTracks().forEach((track) => track.stop());
microphone = stream;
@@ -269,9 +272,10 @@ export async function startLiveCall(target: { botId: string; threadId: string; p
}
}
-/** Fish's SDK opens the microphone and plays the agent itself; the harness follows the call through the relay. */
+/** Fish's SDK, or the Gemini session here, opens the microphone and plays the agent; the harness follows the call through
+ * the relay. */
async function startFishCall(target: { botId: string; threadId: string }, mine: number): Promise<void> {
- const result = await deps.request<{ call: LiveCallState; transport: LiveFishTransport | { type: "webrtc" } }>("/api/live/session", {
+ const result = await deps.request<{ call: LiveCallState; transport: LiveFishTransport | LiveGeminiTransport | { type: "webrtc" } }>("/api/live/session", {
method: "POST",
body: JSON.stringify({ botId: target.botId, threadId: target.threadId, client: liveClient(deps.capabilities()) }),
timeoutMs: 35_000,
@@ -282,11 +286,12 @@ async function startFishCall(target: { botId: string; threadId: string }, mine:
}
const seen = serverCall;
set({ callId: result.call.callId });
- if (result.transport.type !== "fish") throw new Error(t("call.live.dropped"));
+ const transport = result.transport;
+ if (transport.type === "webrtc") throw new Error(t("call.live.dropped"));
applyServerCall(result.call);
if (seen?.callId === result.call.callId) applyServerCall(seen);
if (mine !== generation) return;
- const call = new FishCall(result.transport, {
+ const hooks: FishCallHooks = {
request: deps.request,
connected: () => {
if (mine !== generation) return;
@@ -307,7 +312,8 @@ async function startFishCall(target: { botId: string; threadId: string }, mine:
onSessionClosed();
},
now: () => Date.now(),
- }, deps.startFish);
+ };
+ const call = transport.type === "gemini" ? new FishCall(transport, hooks, deps.startGemini) : new FishCall(transport, hooks, deps.startFish);
fishCall = call;
// Started only now: the SDK's start includes the microphone prompt, which may take the person a while.
await call.start();
diff --git a/src/locales/en.json b/src/locales/en.json
index 8e7141ff4f..569cb2a724 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6835,6 +6835,17 @@
"call.live.needsFish": "Live calls through Fish Audio need your Fish Audio API key.",
"call.live.disclosureFish": "A Live call sends your voice to Fish Audio, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Fish Audio hears on to the bot. The Fish Audio key stays on your computer.",
"call.live.disclosureFishCloud": "A Live call sends your voice to Fish Audio, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Fish Audio hears on to the bot. The Fish Audio key stays in the Cloud.",
+ "call.live.provider.gemini": "Gemini Live",
+ "call.live.geminiHint": "Gemini Live calls work in the desktop app and in a browser, for the owner of this computer. They use the Gemini API key that Gemini voices use.",
+ "call.live.geminiKey": "Gemini key",
+ "call.live.geminiNeedsKey": "Add your Gemini API key with Change key. Gemini voices use the same key.",
+ "call.live.geminiKeyTitle": "Live calls through Gemini",
+ "call.live.geminiKeyExplain": "Paste a Gemini API key from Google AI Studio. Google bills the call to that account; the bot's own work is billed as usual.",
+ "call.live.geminiKeyField": "Gemini API key",
+ "call.live.geminiCost": "Via Gemini Live on your Gemini API account, billed by Google for the audio sent and heard.",
+ "call.live.needsGemini": "Live calls through Gemini need your Gemini API key.",
+ "call.live.disclosureGemini": "A Live call sends your voice to Google's Gemini API, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Gemini hears on to the bot. The Gemini key stays on your computer; the call gets a short-lived token only.",
+ "call.live.disclosureGeminiCloud": "A Live call sends your voice to Google's Gemini API, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Gemini hears on to the bot. The Gemini key stays in the Cloud; the call gets a short-lived token only.",
"call.live.keyFromApiKeys": "Uses your OpenAI API key from Settings → API keys.",
"settings.group.you": "You",
"settings.group.ai": "AI",
@@ -7974,6 +7985,7 @@
"keys.purpose.liveKey": "Optional. Live calls use it instead of your OpenAI key",
"keys.purpose.liveKeyAzure": "Required. A key of the Azure resource your Live calls use",
"keys.purpose.liveKeyFish": "Required. Live calls through Fish Audio use your Fish Audio key",
+ "keys.purpose.liveKeyGemini": "Required. Live calls through Gemini use your Gemini key",
"keys.purpose.elevenlabs": "Voices for spoken replies and calls",
"keys.purpose.fishAudio": "Fish Audio voices for spoken replies and calls",
"keys.purpose.box": "Cloud desktops your bots can use",