Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(live): ElevenLabs Agents as a Live call provider
Bugfixer 270c5be5e812f
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.tsindex 0c5459b702..f9aadafd8d 100644--- a/packages/phone-protocol/src/live-call-wire.ts+++ b/packages/phone-protocol/src/live-call-wire.ts@@ -47,21 +47,23 @@ 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, 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";+ * the Gemini Live API on the person's Gemini key, which the client reaches with a single-use token the harness creates, or an+ * ElevenLabs agent the harness sets up on the person's ElevenLabs account, which the client reaches with a signed URL. */+export type LiveProvider = "openai" | "azure" | "fish" | "gemini" | "elevenlabs";/** `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;- * `gemini`: the Gemini key from Settings → API keys, the only key a Gemini call uses. */-export type LiveKeySource = "live" | "openai" | "fishAudio" | "gemini";+ * `gemini`: the Gemini key from Settings → API keys, the only key a Gemini call uses;+ * `elevenlabs`: the person's own ElevenLabs key from Settings → API keys, the only key an ElevenLabs call uses. */+export type LiveKeySource = "live" | "openai" | "fishAudio" | "gemini" | "elevenlabs";/** 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, with "fish" only the Fish Audio key and with "gemini" only the- * Gemini key, never the OpenAI API key. */+ /** Absent means "openai". With "azure" only the `live` key is used, with "fish" only the Fish Audio key, with "gemini" only the+ * Gemini key and with "elevenlabs" only the ElevenLabs 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;@@ -115,7 +117,26 @@ export interface LiveGeminiTransport {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. */+/** An ElevenLabs agent conversation the client opens itself: `signed_url` is a short-lived WebSocket URL ElevenLabs signed for+ * the harness's agent, and `instructions` the system prompt the client sends as the conversation's prompt override. Holds no+ * API key. */+export interface LiveElevenLabsSession {+ /** The harness's own id for the call's relay; ElevenLabs names the conversation only once the client connects. */+ session_id: string;+ signed_url: string;+ instructions: string;+ /** ISO time by which the client must connect */+ expires_at: string;+}++/** An "elevenlabs" call's transport, answered only to the client that started the call; it relays as a "fish" call does. */+export interface LiveElevenLabsTransport {+ type: "elevenlabs";+ session: LiveElevenLabsSession;+ relayToken: string;+}++/** What the client of a "fish", "gemini" or "elevenlabs" 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 }@@ -124,7 +145,7 @@ export type LiveFishRelayEvent =| { type: "ended"; reason: string }| { type: "error"; code: string };-/** 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. */+/** What the harness hands the client of a relayed ("fish", "gemini" or "elevenlabs") 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.tsindex 3ec46be7e6..4cc019555c 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, LiveGeminiSession, LiveGeminiTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";+export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveElevenLabsSession, LiveElevenLabsTransport, 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/index.ts b/server/index.tsindex c8175661e2..b5eee19db3 100644--- a/server/index.ts+++ b/server/index.ts@@ -12430,7 +12430,7 @@ function liveCallTitle(botId: string, threadId: string, excerpt: string): Promisconst gate = threadTitleGate(bot);return gate.ok ? generateThreadTitle(gate.instance, excerpt, "call") : null;}-const liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveFishAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); } });+const liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); } });const liveCalls = new LiveCallController({store,send: async ({ auth, botId, threadId, text, callId }) => {diff --git a/server/live-access.test.ts b/server/live-access.test.tsindex c05a8c7868..756b1dbf4f 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, geminiLiveCallRefusal, LIVE_AZURE_REFUSAL, LIVE_FISH_REFUSAL, LIVE_GEMINI_REFUSAL, liveScopeRefusal } from "./live-access.ts";+import { azureLiveCallRefusal, elevenLabsLiveCallRefusal, fishLiveCallRefusal, geminiLiveCallRefusal, LIVE_AZURE_REFUSAL, LIVE_ELEVENLABS_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" | "gemini" }+interface Place { resolve?: Partial<ResolveOptions>; othersOnLoopback?: boolean; provider?: "azure" | "openai" | "fish" | "gemini" | "elevenlabs" }/** "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,8 @@ 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 : place.provider === "gemini" ? geminiLiveCallRefusal : azureLiveCallRefusal;+ const refuse = place.provider === "fish" ? fishLiveCallRefusal : place.provider === "gemini" ? geminiLiveCallRefusal+ : place.provider === "elevenlabs" ? elevenLabsLiveCallRefusal : azureLiveCallRefusal;const refusal = refuse(auth, { othersOnLoopback: place.othersOnLoopback ?? false });return refusal ? `limit: ${refusal}` : "gets a call";}@@ -179,6 +180,7 @@ describe("the words for a session without the admin scope", () => {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);+ expect(liveScopeRefusal({ live: { provider: "elevenlabs" } }, "POST", LIVE)).toBe(LIVE_ELEVENLABS_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) {@@ -223,3 +225,20 @@ describe("a Gemini Live call", () => {expect(verdict(LOCAL, { ...GEMINI, othersOnLoopback: true })).toBe(`limit: ${LIVE_GEMINI_REFUSAL}`);});});++describe("an ElevenLabs Live call", () => {+ const ELEVENLABS = { provider: "elevenlabs" as const };+ const TEAM = { ...ELEVENLABS, ...SERVICE, othersOnLoopback: true };++ it("goes to the owner and a team admin, as on Fish Audio", () => {+ expect(verdict(LOCAL, ELEVENLABS)).toBe(CALL);+ expect(verdict(device(["admin", "client"]), ELEVENLABS)).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"]), ELEVENLABS)).toBe(`sign-in gate 403: ${LIVE_ELEVENLABS_REFUSAL}`);+ expect(verdict(teamMember("member"), TEAM)).toBe(`sign-in gate 403: ${LIVE_ELEVENLABS_REFUSAL}`);+ expect(verdict(LOCAL, { ...ELEVENLABS, othersOnLoopback: true })).toBe(`limit: ${LIVE_ELEVENLABS_REFUSAL}`);+ });+});diff --git a/server/live-access.ts b/server/live-access.tsindex a1c8598506..c983d510b3 100644--- a/server/live-access.ts+++ b/server/live-access.ts@@ -1,11 +1,12 @@-// 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).+// Who may hold a Live call through Azure OpenAI, Fish Audio, Gemini or ElevenLabs. LIVE_DATA_CHANNEL in live-call.ts says why Azure is+// limited; on the relayed providers 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 const LIVE_ELEVENLABS_REFUSAL = "Live calls here go through ElevenLabs, 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@@ -30,9 +31,14 @@ export function geminiLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace):return azureLiveCallRefusal(auth, place, LIVE_GEMINI_REFUSAL);}+export function elevenLabsLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): string | null {+ return azureLiveCallRefusal(auth, place, LIVE_ELEVENLABS_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;const provider = cfg.live?.provider;- return provider === "azure" ? LIVE_AZURE_REFUSAL : provider === "fish" ? LIVE_FISH_REFUSAL : provider === "gemini" ? LIVE_GEMINI_REFUSAL : null;+ return provider === "azure" ? LIVE_AZURE_REFUSAL : provider === "fish" ? LIVE_FISH_REFUSAL : provider === "gemini" ? LIVE_GEMINI_REFUSAL+ : provider === "elevenlabs" ? LIVE_ELEVENLABS_REFUSAL : null;}diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.tsindex 8dc34ae299..41abac4f29 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, LIVE_GEMINI_NEEDS_APP, LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,+ LIVE_FISH_NEEDS_APP, LIVE_ELEVENLABS_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, LiveGeminiSession } from "../shared/wire.ts";+import type { LiveElevenLabsSession, LiveFishSessionToken, LiveGeminiSession } from "../shared/wire.ts";import type { RequestAuth } from "./request-auth.ts";import type { Message, StoreChange } from "./store.ts";@@ -54,6 +54,7 @@ function setup(overrides: Partial<LiveCallDeps> = {}) {azureRefusal: vi.fn(() => null),fishRefusal: vi.fn(() => null),geminiRefusal: vi.fn(() => null),+ elevenlabsRefusal: 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`,@@ -561,6 +562,85 @@ describe("LiveCallController lifecycle", () => {});});+ describe("with ElevenLabs chosen", () => {+ const ELEVENLABS: LiveEndpoint = { provider: "elevenlabs", apiBase: "https://api.elevenlabs.io/v1/convai", model: "agent_1" };+ const SESSION: LiveElevenLabsSession = {+ session_id: "elevenlabs_1", signed_url: "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=agent_1&conversation_signature=s",+ instructions: "Be brief.", expires_at: "2026-11-14T00:01:00Z",+ };+ const elevenlabs = (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, elevenlabs: { type: "elevenlabs" as const, session: SESSION, relayToken } };+ }),+ openSocket: (url) => relays.socket(url),+ attachUrl: (id) => id,+ ...overrides,+ });+ t.settings.endpoint = ELEVENLABS;+ t.settings.provider = "elevenlabs";+ const relay = () => relays.find(SESSION.session_id, relayToken)!;+ return { ...t, relay };+ };++ it("asks who is calling, starts with no SDP, and answers with the signed URL and the relay's token", async () => {+ const t = elevenlabs();+ const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });+ expect(t.deps.elevenlabsRefusal).toHaveBeenCalledWith(owner);+ expect(t.deps.geminiRefusal).not.toHaveBeenCalled();+ expect(t.deps.fishRefusal).not.toHaveBeenCalled();+ expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: ELEVENLABS, sdp: "", voice: FISH_AGENT_VOICE }));+ expect(started.sdp).toBeUndefined();+ expect(started.gemini).toBeUndefined();+ expect(started.elevenlabs).toEqual({ type: "elevenlabs", session: SESSION, relayToken: expect.stringMatching(/^[\w-]{43}$/) });+ });++ it("refuses with the reason as a 403 before any session is taken", async () => {+ const t = elevenlabs({ elevenlabsRefusal: () => "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 = elevenlabs();+ await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_ELEVENLABS_NEEDS_APP });+ expect(t.deps.createSession).not.toHaveBeenCalled();+ }+ });++ it("never calls ElevenLabs with a key saved for another provider", async () => {+ const t = elevenlabs();+ t.settings.endpoint = { provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "m" };+ 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 ElevenLabs could not connect", async () => {+ const t = elevenlabs();+ 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 ElevenLabs." });+ });++ it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {+ const t = elevenlabs();+ await t.controller.start({ auth: owner, ...BOT, client: "web" });+ const callId = t.controller.current()!.callId;+ t.relay().receive([{ type: "connected" }, { type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "tc_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: "tc_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.tsindex 8e0b32283c..32d6c72d4a 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, geminiLiveVoice, LiveTranscript } from "../shared/live-call.ts";import { signInWaits } from "../shared/sign-in-request.ts";-import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveFishTransport, LiveGeminiTransport, LiveProvider } from "../shared/wire.ts";+import type { LiveCallRecord, LiveCallState, LiveClient, LiveElevenLabsTransport, 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,13 +40,21 @@ export interface LiveSocket {}export type LiveActivity = "idle" | "working" | "waiting";-export type LiveSessionAnswer = { sessionId: string; sdp: string } | { sessionId: string; fish: LiveFishTransport } | { sessionId: string; gemini: LiveGeminiTransport };+export type LiveSessionAnswer = { sessionId: string; sdp: string } | { sessionId: string; fish: LiveFishTransport } | { sessionId: string; gemini: LiveGeminiTransport }+ | { sessionId: string; elevenlabs: LiveElevenLabsTransport };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 };+ | { call: LiveCallState; sdp: string; fish?: undefined; gemini?: undefined; elevenlabs?: undefined }+ | { call: LiveCallState; sdp?: undefined; fish: LiveFishTransport; gemini?: undefined; elevenlabs?: undefined }+ | { call: LiveCallState; sdp?: undefined; fish?: undefined; gemini: LiveGeminiTransport; elevenlabs?: undefined }+ | { call: LiveCallState; sdp?: undefined; fish?: undefined; gemini?: undefined; elevenlabs: LiveElevenLabsTransport };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 const LIVE_ELEVENLABS_NEEDS_APP = "Live calls through ElevenLabs work in the desktop app or a web browser, not in the phone app yet.";++/** Fish Audio, Gemini and ElevenLabs calls are relayed: the client holds the provider's session and reports what it heard. */+export function relayedProvider(provider: LiveProvider | undefined): "fish" | "gemini" | "elevenlabs" | null {+ return provider === "fish" || provider === "gemini" || provider === "elevenlabs" ? provider : null;+}export type LiveSendResult = { kind: "started" | "steered"; messageId: string } | { kind: "queued"; queueId: string };export type LiveRespondResult = { ok: true } | { ok: false; error: string };@@ -63,10 +71,11 @@ export interface LiveCallDeps {settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; geminiVoice?: 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 and Gemini, where the harness hears the call only through its client's reports. Required too. */+ /** The same for the relayed providers, where the harness hears the call only through its client's reports. Required too. */fishRefusal(auth: RequestAuth): string | null;geminiRefusal(auth: RequestAuth): string | null;- /** `sdp` is "" on Fish Audio and Gemini, which answer with `fish` or `gemini` instead of an SDP answer. */+ elevenlabsRefusal(auth: RequestAuth): string | null;+ /** `sdp` is "" on relayed calls, which answer with `fish`, `gemini` or `elevenlabs` 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;@@ -172,28 +181,28 @@ 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, Fish Audio or Gemini up.+ // First: someone refused here is not told about a running call, or sent to set Azure or a relayed service 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 relayedChoice = relayedProvider(settings.provider);const limited = settings.provider === "azure" || settings.endpoint?.provider === "azure" ? "azure"- : relayedChoice ?? (settings.endpoint?.provider === "fish" || settings.endpoint?.provider === "gemini" ? settings.endpoint.provider : null);+ : relayedChoice ?? relayedProvider(settings.endpoint?.provider);if (limited) {- const refusal = limited === "azure" ? this.deps.azureRefusal(input.auth) : limited === "fish" ? this.deps.fishRefusal(input.auth) : this.deps.geminiRefusal(input.auth);+ const refusal = limited === "azure" ? this.deps.azureRefusal(input.auth) : limited === "fish" ? this.deps.fishRefusal(input.auth)+ : limited === "gemini" ? this.deps.geminiRefusal(input.auth) : this.deps.elevenlabsRefusal(input.auth);if (refusal) {this.deps.log(`[live] call refused bot=${input.botId} client=${input.client} provider=${limited}`);throw new LiveSessionError(refusal, 403);}}- // 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);+ const relayed = limited === "azure" ? null : limited;+ if (relayed && (input.client === "ios" || input.client === "android")) throw new LiveSessionError(relayed === "fish" ? LIVE_FISH_NEEDS_APP : relayed === "gemini" ? LIVE_GEMINI_NEEDS_APP : LIVE_ELEVENLABS_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 (relayed !== (endpoint.provider === "fish" || endpoint.provider === "gemini" ? endpoint.provider : null)) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);+ if (relayed !== relayedProvider(endpoint.provider)) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);const voice = relayed === "gemini" ? geminiLiveVoice(settings.geminiVoice) : 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.@@ -232,6 +241,7 @@ export class LiveCallController {const state = { ...call.state };if ("fish" in session) return { call: state, fish: session.fish };if ("gemini" in session) return { call: state, gemini: session.gemini };+ if ("elevenlabs" in session) return { call: state, elevenlabs: session.elevenlabs };return { call: state, sdp: session.sdp };}@@ -322,7 +332,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" || call.endpoint.provider === "gemini" ? FISH_ATTACH_TIMEOUT_MS : ATTACH_TIMEOUT_MS);+ }, relayedProvider(call.endpoint.provider) ? 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.tsindex e072978713..9bd60fcd30 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -11,6 +11,7 @@ export const LIVE_NEEDS_KEY = "Live calls use your own OpenAI key. Add it in Setexport 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.";+export const LIVE_NEEDS_ELEVENLABS = "Live calls through ElevenLabs use your ElevenLabs 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@@ -46,12 +47,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, the Fish Audio agent id ('' until one is set up) or the Gemini Live model id. */+ /** The OpenAI model id, the Azure deployment name, the Fish Audio agent id or ElevenLabs 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" : provider === "gemini" ? "Gemini" : "OpenAI";+ return provider === "azure" ? "Azure OpenAI" : provider === "fish" ? "Fish Audio" : provider === "gemini" ? "Gemini" : provider === "elevenlabs" ? "ElevenLabs" : "OpenAI";}/** Only a loopback http URL is accepted, read at call time. */diff --git a/server/live-config.ts b/server/live-config.tsindex 5f9503fe3b..9d5c64cde4 100644--- a/server/live-config.ts+++ b/server/live-config.ts@@ -4,15 +4,17 @@ 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" 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, `geminiVoice` a Gemini 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", "gemini" or "elevenlabs" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`), Gemini calls the Gemini key (`tts.geminiKey`) and ElevenLabs calls the ElevenLabs key (`tts.key`). `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. `elevenlabsAgentId` and `elevenlabsAgentFor` are the same for an "elevenlabs" call's ElevenLabs agent. `voice` is a GPT-Live voice, `geminiVoice` a Gemini Live voice. */export const liveConfigSchema = z.object({key: z.string().optional(),keyFor: z.string().max(300).optional(),- provider: z.enum(["openai", "azure", "fish", "gemini"]).optional(),+ provider: z.enum(["openai", "azure", "fish", "gemini", "elevenlabs"]).optional(),azureEndpoint: z.string().trim().max(300).optional(),azureDeployment: z.string().trim().max(64).optional(),fishAgentId: z.string().trim().max(128).optional(),fishAgentFor: z.string().max(64).optional(),+ elevenlabsAgentId: z.string().trim().max(128).optional(),+ elevenlabsAgentFor: z.string().max(64).optional(),voice: z.string().trim().max(40).regex(/^[a-z]*$/, "a Live voice is a lowercase built-in voice name").optional(),geminiVoice: z.string().trim().max(40).regex(/^[A-Za-z]*$/, "a Gemini Live voice is a built-in voice name").optional(),readTypedReplies: z.boolean().optional(),@@ -22,11 +24,13 @@ export const liveConfigSchema = z.object({export interface LiveConfig {key?: string;keyFor?: string;- provider?: "openai" | "azure" | "fish" | "gemini";+ provider?: "openai" | "azure" | "fish" | "gemini" | "elevenlabs";azureEndpoint?: string;azureDeployment?: string;fishAgentId?: string;fishAgentFor?: string;+ elevenlabsAgentId?: string;+ elevenlabsAgentFor?: string;voice?: string;geminiVoice?: string;readTypedReplies?: boolean;@@ -34,7 +38,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 and Gemini calls never use this key, so with either chosen it stays OpenAI's. */+ * Fish Audio, Gemini and ElevenLabs calls never use this key, so with any of them chosen it stays OpenAI's. */export function liveKeyTarget(live: LiveConfig | undefined): string | null {if (live?.provider !== "azure") return "openai";try {@@ -74,7 +78,7 @@ export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.Procnext.key = envKey;}const provider = env.OMB_LIVE_PROVIDER?.trim().toLowerCase();- if (provider === "openai" || provider === "azure" || provider === "fish" || provider === "gemini") next.provider = provider;+ if (provider === "openai" || provider === "azure" || provider === "fish" || provider === "gemini" || provider === "elevenlabs") 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-elevenlabs.test.ts b/server/live-elevenlabs.test.tsnew file mode 100644index 0000000000..1bef321b4f--- /dev/null+++ b/server/live-elevenlabs.test.ts@@ -0,0 +1,117 @@+import { describe, expect, it, vi } from "vitest";+import { createElevenLabsLiveSession, elevenLabsErrorMessage, elevenLabsLiveEndpoint, setUpElevenLabsAgent, usableElevenLabsAgent } from "./live-elevenlabs.ts";+import { FISH_DELEGATE_TOOL, fishKeyPrint } from "./live-fish.ts";+import { LiveSessionError } from "./live-call.ts";++const NOW = Date.parse("2026-11-14T10:00:00Z");+const SIGNED = "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=agent_1&conversation_signature=sig";++function fakeElevenLabs(answers: Record<string, () => Response> = {}) {+ return vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {+ const path = new URL(String(url)).pathname;+ const answer = answers[path];+ if (answer) return answer();+ if (path.endsWith("/tools")) return Response.json({ id: "tool_1" });+ if (path.endsWith("/agents/create")) return Response.json({ agent_id: "agent_1" });+ return Response.json({ signed_url: SIGNED });+ });+}++const create = (fetchImpl: typeof fetch, endpoint = elevenLabsLiveEndpoint("agent_1", {}), key = " eleven-secret ") =>+ createElevenLabsLiveSession({ key, endpoint, bot: { name: "Rigel" }, history: [{ role: "user", text: "hi there" }], cloudHome: false, fetchImpl, now: () => NOW });++describe("ElevenLabs Live endpoint", () => {+ it("talks to ElevenLabs' Agents API with the saved agent, or none yet", () => {+ expect(elevenLabsLiveEndpoint("agent_1", {})).toEqual({ provider: "elevenlabs", apiBase: "https://api.elevenlabs.io/v1/convai", model: "agent_1" });+ expect(elevenLabsLiveEndpoint("../evil", {}).model).toBe("");+ expect(elevenLabsLiveEndpoint(undefined, {}).model).toBe("");+ });++ it("uses the ElevenLabs API root ElevenLabs voices use", () => {+ expect(elevenLabsLiveEndpoint("agent_1", { OMB_ELEVENLABS_API: "http://127.0.0.1:9124/v1/" }).apiBase).toBe("http://127.0.0.1:9124/v1/convai");+ });++ it("uses a saved agent only with the key of the account it was set up on", () => {+ const live = { elevenlabsAgentId: "agent_1", elevenlabsAgentFor: fishKeyPrint("eleven-secret") };+ expect(usableElevenLabsAgent(live, " eleven-secret ")).toBe("agent_1");+ expect(usableElevenLabsAgent(live, "another-key")).toBeNull();+ expect(usableElevenLabsAgent({ elevenlabsAgentId: "agent_1" }, "eleven-secret")).toBeNull();+ expect(usableElevenLabsAgent(live, "")).toBeNull();+ });+});++describe("an ElevenLabs agent for Live calls", () => {+ it("is set up with the delegate client tool and a prompt each conversation may override", async () => {+ const fetchImpl = fakeElevenLabs();+ expect(await setUpElevenLabsAgent(" eleven-secret ", elevenLabsLiveEndpoint(null, {}), "OpenMausBot", fetchImpl)).toBe("agent_1");+ const [[toolUrl, toolInit], [agentUrl, agentInit]] = fetchImpl.mock.calls;+ expect(String(toolUrl)).toBe("https://api.elevenlabs.io/v1/convai/tools");+ expect(toolInit!.headers).toMatchObject({ "xi-api-key": "eleven-secret" });+ expect(JSON.parse(String(toolInit!.body)).tool_config).toMatchObject({ type: "client", name: FISH_DELEGATE_TOOL, expects_response: true });+ expect(String(agentUrl)).toBe("https://api.elevenlabs.io/v1/convai/agents/create");+ const agent = JSON.parse(String(agentInit!.body));+ expect(agent).toMatchObject({+ name: "OpenMausBot Live calls",+ conversation_config: { agent: { prompt: { tool_ids: ["tool_1"] } }, asr: { user_input_audio_format: "pcm_16000" }, tts: { agent_output_audio_format: "pcm_16000" } },+ platform_settings: { overrides: { conversation_config_override: { agent: { prompt: { prompt: true } } } } },+ });+ });++ it("fails with words for the person, never ElevenLabs' body, when ElevenLabs refuses or answers oddly", async () => {+ const refused = fakeElevenLabs({ "/v1/convai/tools": () => new Response("secret detail", { status: 401 }) });+ await expect(setUpElevenLabsAgent("k", elevenLabsLiveEndpoint(null, {}), "P", refused)).rejects.toMatchObject({ status: 502, message: elevenLabsErrorMessage(401) });+ const odd = fakeElevenLabs({ "/v1/convai/agents/create": () => Response.json({ agent_id: "../x" }) });+ await expect(setUpElevenLabsAgent("k", elevenLabsLiveEndpoint(null, {}), "P", odd)).rejects.toBeInstanceOf(LiveSessionError);+ });++ it("removes the tool again when the agent is not created", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/create": () => new Response("", { status: 500 }), "/v1/convai/tools/tool_1": () => new Response(null, { status: 204 }) });+ await expect(setUpElevenLabsAgent("k", elevenLabsLiveEndpoint(null, {}), "P", fetchImpl)).rejects.toMatchObject({ status: 502 });+ const [url, init] = fetchImpl.mock.calls.at(-1)!;+ expect(String(url)).toBe("https://api.elevenlabs.io/v1/convai/tools/tool_1");+ expect(init).toMatchObject({ method: "DELETE", headers: { "xi-api-key": "k" } });+ });+});++describe("an ElevenLabs Live call's session", () => {+ it("asks for a signed URL with the key in a header and answers with it and the call's instructions, never the key", async () => {+ const fetchImpl = fakeElevenLabs();+ const session = await create(fetchImpl);+ const [url, init] = fetchImpl.mock.calls[0]!;+ expect(String(url)).toBe("https://api.elevenlabs.io/v1/convai/conversation/get-signed-url?agent_id=agent_1");+ expect(init).toMatchObject({ method: "GET", redirect: "error", headers: { "xi-api-key": "eleven-secret" } });+ expect(JSON.stringify(session)).not.toContain("eleven-secret");+ expect(session).toEqual({+ session_id: expect.stringMatching(/^elevenlabs_[0-9a-f]{24}$/),+ signed_url: SIGNED,+ instructions: expect.stringContaining("Rigel"),+ expires_at: "2026-11-14T10:01:00.000Z",+ });+ expect(session.instructions).toContain(`\`${FISH_DELEGATE_TOOL}\``);+ expect(session.instructions).toContain("User: hi there");+ });++ it("takes a loopback ws URL only from a loopback override", async () => {+ const local = "ws://127.0.0.1:9124/v1/convai/conversation?agent_id=agent_1";+ const fetchImpl = fakeElevenLabs({ "/v1/convai/conversation/get-signed-url": () => Response.json({ signed_url: local }) });+ const loopback = elevenLabsLiveEndpoint("agent_1", { OMB_ELEVENLABS_API: "http://127.0.0.1:9124/v1" });+ expect((await create(fetchImpl, loopback)).signed_url).toBe(local);+ await expect(create(fetchImpl)).rejects.toMatchObject({ status: 502 });+ });++ it("refuses a missing key before asking ElevenLabs", async () => {+ const fetchImpl = fakeElevenLabs();+ await expect(create(fetchImpl, undefined, " ")).rejects.toMatchObject({ status: 409 });+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it("says when the agent is gone, so it can be set up again", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/conversation/get-signed-url": () => new Response("{}", { status: 404 }) });+ await expect(create(fetchImpl)).rejects.toMatchObject({ elevenlabsStatus: 404, message: elevenLabsErrorMessage(404) });+ });++ it("keeps a rate limit as a rate limit", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/conversation/get-signed-url": () => new Response("{}", { status: 429 }) });+ await expect(create(fetchImpl)).rejects.toMatchObject({ status: 429 });+ });+});diff --git a/server/live-elevenlabs.ts b/server/live-elevenlabs.tsnew file mode 100644index 0000000000..cda060ee5d--- /dev/null+++ b/server/live-elevenlabs.ts@@ -0,0 +1,128 @@+// ElevenLabs Agents Live calls. The ElevenLabs key never leaves the harness: the harness sets up an agent with the client+// tool `delegate` on the person's account once, and for each call asks ElevenLabs for a signed URL the client opens; the+// client relays what was said as on a Fish Audio call.+import { randomBytes } from "node:crypto";+import type { LiveElevenLabsSession } from "../shared/wire.ts";+import { LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";+import type { LiveConfig } from "./live-config.ts";+import { elevenLabsProviderApi } from "./included-services.ts";+import { FISH_DELEGATE_TOOL, fishInstructions, fishKeyPrint } from "./live-fish.ts";++const REQUEST_TIMEOUT_MS = 20_000;+/** A signed URL is good for about 15 minutes; the client connects at once. */+const CONNECT_WITHIN_MS = 60_000;+const AGENT_ID = /^[\w-]{1,128}$/;+/** The agent's audio both ways: 16 kHz 16-bit PCM, as the client sends and plays it. */+const AUDIO_FORMAT = "pcm_16000";+const UNEXPECTED = "ElevenLabs returned an unexpected answer. Try the call again.";++/** `model` is the agent id, "" while no usable one is saved. The API root is the one ElevenLabs voices use (OMB_ELEVENLABS_API). */+export function elevenLabsLiveEndpoint(agentId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint {+ const id = agentId?.trim() ?? "";+ return { provider: "elevenlabs", apiBase: `${elevenLabsProviderApi(env).replace(/\/+$/, "")}/convai`, model: AGENT_ID.test(id) ? id : "" };+}++/** The saved agent, while it belongs to the account of `key`. */+export function usableElevenLabsAgent(live: LiveConfig | undefined, key: string): string | null {+ const id = live?.elevenlabsAgentId?.trim() ?? "";+ return AGENT_ID.test(id) && key.trim() !== "" && live?.elevenlabsAgentFor === fishKeyPrint(key) ? id : null;+}++async function elevenLabsRequest(fetchImpl: typeof fetch, key: string, url: string, body?: unknown): Promise<Record<string, unknown>> {+ let response: Response;+ try {+ response = await fetchImpl(url, {+ method: body === undefined ? "GET" : "POST",+ headers: { "xi-api-key": key.trim(), ...(body === undefined ? {} : { "content-type": "application/json" }) },+ redirect: "error",+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),+ });+ } catch (error) {+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");+ throw new LiveSessionError(timedOut ? "ElevenLabs did not answer in time. Try the call again." : "Could not reach ElevenLabs. Check the internet connection.", 502);+ }+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ throw Object.assign(new LiveSessionError(elevenLabsErrorMessage(response.status), response.status === 429 ? 429 : 502), { elevenlabsStatus: response.status });+ }+ const answer = await response.json().catch(() => null) as unknown;+ return answer && typeof answer === "object" ? answer as Record<string, unknown> : {};+}++/** ElevenLabs API v1: the client tool `delegate`, then an English agent named for `product` that uses it and whose prompt each+ * conversation may override (the client sends the call's instructions). Returns the agent's id. */+export async function setUpElevenLabsAgent(key: string, endpoint: LiveEndpoint, product: string, fetchImpl: typeof fetch = fetch): Promise<string> {+ const tool = await elevenLabsRequest(fetchImpl, key, `${endpoint.apiBase}/tools`, {+ tool_config: {+ type: "client",+ 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"] },+ expects_response: true,+ response_timeout_secs: 30,+ },+ });+ const toolId = typeof tool.id === "string" ? tool.id : "";+ if (!toolId) throw new LiveSessionError(UNEXPECTED, 502);+ try {+ const agent = await elevenLabsRequest(fetchImpl, key, `${endpoint.apiBase}/agents/create`, {+ name: `${product} Live calls`.slice(0, 120),+ conversation_config: {+ agent: { first_message: "", language: "en", prompt: { prompt: `You are ${product} on a live voice call.`, tool_ids: [toolId] } },+ asr: { user_input_audio_format: AUDIO_FORMAT },+ tts: { agent_output_audio_format: AUDIO_FORMAT },+ },+ // Without this ElevenLabs refuses the prompt each conversation sends.+ platform_settings: { overrides: { conversation_config_override: { agent: { prompt: { prompt: true } } } } },+ });+ const agentId = typeof agent.agent_id === "string" && AGENT_ID.test(agent.agent_id) ? agent.agent_id : "";+ if (!agentId) throw new LiveSessionError(UNEXPECTED, 502);+ return agentId;+ } catch (error) {+ // No agent uses the tool, so it is not left on the person's account.+ await fetchImpl(`${endpoint.apiBase}/tools/${encodeURIComponent(toolId)}`, { method: "DELETE", headers: { "xi-api-key": key.trim() }, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) })+ .then((response) => response.body?.cancel(), () => undefined).catch(() => undefined);+ throw error;+ }+}++export interface CreateElevenLabsSessionInput {+ key: string;+ endpoint: LiveEndpoint;+ bot: LiveBot;+ history: LiveHistoryMessage[];+ cloudHome: boolean;+ fetchImpl?: typeof fetch;+ now?: () => number;+}++/** ElevenLabs API v1 `GET /v1/convai/conversation/get-signed-url`. Errors carry a status and a message fit for the user: never+ * the key, never ElevenLabs' raw body; `elevenlabsStatus` is ElevenLabs' own status. */+export async function createElevenLabsLiveSession(input: CreateElevenLabsSessionInput): Promise<LiveElevenLabsSession> {+ const key = input.key.trim();+ if (!key) throw new LiveSessionError("Add an ElevenLabs API key in Settings → API keys to use Live calls.", 409);+ const answer = await elevenLabsRequest(input.fetchImpl ?? fetch, key, `${input.endpoint.apiBase}/conversation/get-signed-url?agent_id=${encodeURIComponent(input.endpoint.model)}`);+ const url = typeof answer.signed_url === "string" ? answer.signed_url : "";+ // ElevenLabs answers with a wss URL; only a loopback override may answer with a loopback ws one.+ const loopback = input.endpoint.apiBase.startsWith("http://127.0.0.1:");+ if (!/^wss:\/\/\S+$/.test(url) && !(loopback && /^ws:\/\/127\.0\.0\.1:\d{1,5}\/\S*$/.test(url))) throw new LiveSessionError(UNEXPECTED, 502);+ return {+ session_id: `elevenlabs_${randomBytes(12).toString("hex")}`,+ signed_url: url,+ instructions: fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }),+ expires_at: new Date((input.now ?? Date.now)() + CONNECT_WITHIN_MS).toISOString(),+ };+}++export function elevenLabsErrorMessage(status: number): string {+ switch (status) {+ case 400:+ case 422: return `ElevenLabs rejected the call settings (HTTP ${status}).`;+ case 401:+ case 403: return "ElevenLabs rejected the API key, or the key may not use Agents. Check the ElevenLabs key in Settings → API keys.";+ case 404: return "ElevenLabs could not find the agent for calls.";+ case 429: return "ElevenLabs is limiting calls on this key right now. Try again in a moment.";+ default: return status >= 500 ? "ElevenLabs had a problem starting the call. Try again in a moment." : `ElevenLabs could not start the call (HTTP ${status}).`;+ }+}diff --git a/server/live-session-wiring.test.ts b/server/live-session-wiring.test.tsindex 586893b871..66cce75657 100644--- a/server/live-session-wiring.test.ts+++ b/server/live-session-wiring.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from "vitest";import { fishKeyPrint, fishLiveEndpoint } from "./live-fish.ts";+import { elevenLabsLiveEndpoint } from "./live-elevenlabs.ts";import { liveSessionWiring } from "./live-session-wiring.ts";const TOKEN = { transport: "livekit", session_id: "sess_1", expires_at: "x", max_duration_seconds: 900, livekit_url: "wss://lk.fish.audio", token: "jwt" };@@ -17,9 +18,9 @@ function fakeFish({ goneAgents = [] as string[] } = {}) {}function wiring(fetchImpl: typeof fetch, env: NodeJS.ProcessEnv = {}) {- const saveFishAgent = vi.fn();- const wired = liveSessionWiring({ bot: () => ({ name: "Rigel" }), history: () => [], cloudHome: false, othersOnLoopback: () => false, saveFishAgent, productName: () => "Acme", env, fetchImpl });- return { ...wired, saveFishAgent };+ const saveAgent = vi.fn();+ const wired = liveSessionWiring({ bot: () => ({ name: "Rigel" }), history: () => [], cloudHome: false, othersOnLoopback: () => false, saveAgent, productName: () => "Acme", env, fetchImpl });+ return { ...wired, saveAgent };}const start = { key: "fish-key", sdp: "", botId: "b1", threadId: "t1", voice: "agent" };@@ -31,7 +32,7 @@ describe("a Fish Audio call's session", () => {const w = wiring(fetchImpl);const answer = await w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("", {}) });expect(routes(fetchImpl)).toEqual(["POST /tools", "POST /agents", "PATCH /agents/agent_new", "POST /agents/agent_new/publish", "POST /sessions"]);- expect(w.saveFishAgent).toHaveBeenCalledWith({ fishAgentId: "agent_new", fishAgentFor: fishKeyPrint("fish-key") });+ expect(w.saveAgent).toHaveBeenCalledWith({ fishAgentId: "agent_new", fishAgentFor: fishKeyPrint("fish-key") });const created = fetchImpl.mock.calls.find(([url, init]) => init!.method === "POST" && String(url).endsWith("/agents"))!;expect(JSON.parse(String(created[1]!.body)).name).toBe("Acme Live calls");expect(answer).toMatchObject({ sessionId: "sess_1", fish: { type: "fish", session: TOKEN } });@@ -45,7 +46,7 @@ describe("a Fish Audio call's session", () => {const w = wiring(fetchImpl);await w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_saved", {}) });expect(routes(fetchImpl)).toEqual(["POST /sessions"]);- expect(w.saveFishAgent).not.toHaveBeenCalled();+ expect(w.saveAgent).not.toHaveBeenCalled();});it("sets up a new agent once when the saved one is gone on Fish Audio", async () => {@@ -53,7 +54,7 @@ describe("a Fish Audio call's session", () => {const w = wiring(fetchImpl);await expect(w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_saved", {}) })).resolves.toMatchObject({ sessionId: "sess_1" });expect(routes(fetchImpl)).toEqual(["POST /sessions", "POST /tools", "POST /agents", "PATCH /agents/agent_new", "POST /agents/agent_new/publish", "POST /sessions"]);- expect(w.saveFishAgent).toHaveBeenCalledTimes(1);+ expect(w.saveAgent).toHaveBeenCalledTimes(1);});it("never replaces an agent the operator chose", async () => {@@ -61,7 +62,7 @@ describe("a Fish Audio call's session", () => {const w = wiring(fetchImpl, { OMB_FISH_LIVE_AGENT_ID: "agent_op" });await expect(w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_op", {}) })).rejects.toMatchObject({ status: 502 });expect(routes(fetchImpl)).toEqual(["POST /sessions"]);- expect(w.saveFishAgent).not.toHaveBeenCalled();+ expect(w.saveAgent).not.toHaveBeenCalled();});it("follows the call through its relay, not a socket to Fish", () => {@@ -94,3 +95,53 @@ describe("a Gemini Live call's session", () => {expect(w.calls.geminiRefusal({ kind: "loopback", scopes: ["admin", "client"] })).toBeNull();});});++describe("an ElevenLabs call's session", () => {+ const SIGNED = "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=agent_new&conversation_signature=s";+ function fakeElevenLabs({ goneAgents = [] as string[] } = {}) {+ return vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {+ const { pathname, searchParams } = new URL(String(url));+ if (pathname.endsWith("/tools")) return Response.json({ id: "tool_1" });+ if (pathname.endsWith("/agents/create")) return Response.json({ agent_id: "agent_new" });+ const agent = searchParams.get("agent_id") ?? "";+ return goneAgents.includes(agent) ? new Response("{}", { status: 404 }) : Response.json({ signed_url: SIGNED });+ });+ }+ const paths = (fetchImpl: ReturnType<typeof fakeElevenLabs>) => fetchImpl.mock.calls.map(([url]) => new URL(String(url)).pathname.replace("/v1/convai", ""));+ const eleven = { ...start, key: "eleven-key" };++ it("sets up an agent on the first call, saves it for that key's account, and answers with a relay, never the key", async () => {+ const fetchImpl = fakeElevenLabs();+ const w = wiring(fetchImpl as unknown as typeof fetch);+ const answer = await w.calls.createSession({ ...eleven, endpoint: elevenLabsLiveEndpoint(null, {}) });+ expect(paths(fetchImpl)).toEqual(["/tools", "/agents/create", "/conversation/get-signed-url"]);+ expect(w.saveAgent).toHaveBeenCalledWith({ elevenlabsAgentId: "agent_new", elevenlabsAgentFor: fishKeyPrint("eleven-key") });+ expect(answer).toMatchObject({ elevenlabs: { type: "elevenlabs", session: { signed_url: SIGNED } } });+ expect(JSON.stringify(answer)).not.toContain("eleven-key");+ const { session, relayToken } = (answer as { elevenlabs: { session: { session_id: string }; relayToken: string } }).elevenlabs;+ expect(answer.sessionId).toBe(session.session_id);+ expect(w.fishRelay(session.session_id, relayToken)).not.toBeNull();+ expect(w.calls.attachUrl(session.session_id, elevenLabsLiveEndpoint("agent_new", {}))).toBe(session.session_id);+ });++ it("uses the saved agent without setting one up", async () => {+ const fetchImpl = fakeElevenLabs();+ const w = wiring(fetchImpl as unknown as typeof fetch);+ await w.calls.createSession({ ...eleven, endpoint: elevenLabsLiveEndpoint("agent_1", {}) });+ expect(paths(fetchImpl)).toEqual(["/conversation/get-signed-url"]);+ expect(w.saveAgent).not.toHaveBeenCalled();+ });++ it("sets the agent up again when it was removed on ElevenLabs", async () => {+ const fetchImpl = fakeElevenLabs({ goneAgents: ["agent_old"] });+ const w = wiring(fetchImpl as unknown as typeof fetch);+ await w.calls.createSession({ ...eleven, endpoint: elevenLabsLiveEndpoint("agent_old", {}) });+ expect(paths(fetchImpl)).toEqual(["/conversation/get-signed-url", "/tools", "/agents/create", "/conversation/get-signed-url"]);+ expect(w.saveAgent).toHaveBeenCalledTimes(1);+ });++ it("asks who is calling as for Fish Audio", () => {+ const w = wiring(fakeFish());+ expect(w.calls.elevenlabsRefusal({ kind: "loopback", scopes: ["admin", "client"] })).toBeNull();+ });+});diff --git a/server/live-session-wiring.ts b/server/live-session-wiring.tsindex b8749b0a26..7b91d6dd3f 100644--- a/server/live-session-wiring.ts+++ b/server/live-session-wiring.ts@@ -1,10 +1,11 @@import { productName } from "./brand.ts";import type { LiveCallDeps } from "./live-call-controller.ts";-import { openLiveSocket } from "./live-call-controller.ts";+import { openLiveSocket, relayedProvider } from "./live-call-controller.ts";import { createLiveSession, liveAttachUrl, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";-import { fishLiveCallRefusal, geminiLiveCallRefusal } from "./live-access.ts";+import { elevenLabsLiveCallRefusal, fishLiveCallRefusal, geminiLiveCallRefusal } from "./live-access.ts";import type { LiveConfig } from "./live-config.ts";import { createFishLiveSession, endFishLiveSession, fishKeyPrint, FishRelays, setUpFishAgent } from "./live-fish.ts";+import { createElevenLabsLiveSession, setUpElevenLabsAgent } from "./live-elevenlabs.ts";import { createGeminiLiveSession } from "./live-gemini.ts";import type { LiveRouteDeps } from "./routes/live.ts";@@ -13,28 +14,28 @@ export interface LiveSessionWiringInput {history(threadId: string): LiveHistoryMessage[];cloudHome: boolean;othersOnLoopback(): boolean;- /** Saves the Fish Audio agent the harness set up, with the account it belongs to. */- saveFishAgent(agent: Required<Pick<LiveConfig, "fishAgentId" | "fishAgentFor">>): void;- /** The name a person reads, which names the Fish agent on their account; the brand's own by default. */+ /** Saves the Fish Audio or ElevenLabs agent the harness set up, with the account it belongs to. */+ saveAgent(agent: Required<Pick<LiveConfig, "fishAgentId" | "fishAgentFor">> | Required<Pick<LiveConfig, "elevenlabsAgentId" | "elevenlabsAgentFor">>): void;+ /** The name a person reads, which names the agent on their account; the brand's own by default. */productName?(): string;env?: NodeJS.ProcessEnv;fetchImpl?: typeof fetch;}/** 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 or Gemini Live session followed through its client's relay. */+ * Azure, or a Fish Audio agent, Gemini Live session or ElevenLabs agent conversation followed through its client's relay. */export function liveSessionWiring(input: LiveSessionWiringInput): {- calls: Pick<LiveCallDeps, "fishRefusal" | "geminiRefusal" | "createSession" | "openSocket" | "attachUrl">;+ calls: Pick<LiveCallDeps, "fishRefusal" | "geminiRefusal" | "elevenlabsRefusal" | "createSession" | "openSocket" | "attachUrl">;fishRelay: LiveRouteDeps["fishRelay"];} {const relays = new FishRelays();- const relayed = (endpoint: LiveEndpoint) => endpoint.provider === "fish" || endpoint.provider === "gemini";+ const relayed = (endpoint: LiveEndpoint) => relayedProvider(endpoint.provider) !== null;const env = input.env ?? process.env;const fetchImpl = input.fetchImpl ?? fetch;const setUpAgent = async (key: string, endpoint: LiveEndpoint): Promise<LiveEndpoint> => {const fishAgentId = await setUpFishAgent(key, endpoint, (input.productName ?? productName)(), fetchImpl);- input.saveFishAgent({ fishAgentId, fishAgentFor: fishKeyPrint(key) });+ input.saveAgent({ fishAgentId, fishAgentFor: fishKeyPrint(key) });return { ...endpoint, model: fishAgentId };};@@ -52,11 +53,29 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {}};+ const setUpElevenLabs = async (key: string, endpoint: LiveEndpoint): Promise<LiveEndpoint> => {+ const elevenlabsAgentId = await setUpElevenLabsAgent(key, endpoint, (input.productName ?? productName)(), fetchImpl);+ input.saveAgent({ elevenlabsAgentId, elevenlabsAgentFor: fishKeyPrint(key) });+ return { ...endpoint, model: elevenlabsAgentId };+ };++ const startElevenLabs = async (key: string, endpoint: LiveEndpoint, botId: string, threadId: string) => {+ const session = { key, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl };+ try {+ return await createElevenLabsLiveSession({ ...session, endpoint: endpoint.model ? endpoint : await setUpElevenLabs(key, endpoint) });+ } catch (error) {+ // An agent removed on ElevenLabs is set up again.+ if ((error as { elevenlabsStatus?: number }).elevenlabsStatus !== 404 || !endpoint.model) throw error;+ return createElevenLabsLiveSession({ ...session, endpoint: await setUpElevenLabs(key, endpoint) });+ }+ };+return {fishRelay: (sessionId, token) => relays.find(sessionId, token),calls: {fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),geminiRefusal: (auth) => geminiLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),+ elevenlabsRefusal: (auth) => elevenLabsLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {if (endpoint.provider === "gemini") {const session = await createGeminiLiveSession({ key, endpoint, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl });@@ -64,6 +83,12 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {const { token } = relays.open(session.session_id, async () => undefined);return { sessionId: session.session_id, gemini: { type: "gemini", session, relayToken: token } };}+ if (endpoint.provider === "elevenlabs") {+ const session = await startElevenLabs(key, endpoint, botId, threadId);+ // ElevenLabs has nothing to end either: the conversation ends when the client closes it.+ const { token } = relays.open(session.session_id, async () => undefined);+ return { sessionId: session.session_id, elevenlabs: { type: "elevenlabs", session, relayToken: token } };+ }if (endpoint.provider !== "fish") {return createLiveSession({ key, endpoint, sdp, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });}diff --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex b3b3c94825..32b3a658e5 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_GEMINI, LIVE_NEEDS_KEY } from "./live-call.ts";+import { LIVE_NEEDS_AZURE, LIVE_NEEDS_ELEVENLABS, 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";@@ -322,3 +322,34 @@ describe("Live calls through Gemini", () => {expect(liveCallSettings({ live: gemini } as AppConfig)).toMatchObject({ provider: "gemini", key: "", setupProblem: LIVE_NEEDS_GEMINI });});});++describe("Live calls through ElevenLabs", () => {+ const elevenlabs = { provider: "elevenlabs" as const };++ it("use only the person's ElevenLabs key, never the OpenAI API key or a key saved for another provider", () => {+ for (const live of [elevenlabs, { ...elevenlabs, key: "k", keyFor: "openai" }]) {+ const cfg = { live, openai: { key: "sk-openai" }, tts: { fishKey: "fish", geminiKey: "gem" } } as AppConfig;+ expect(liveCallKey(cfg), JSON.stringify(live)).toBeNull();+ expect(liveSetupProblem(cfg)).toBe(LIVE_NEEDS_ELEVENLABS);+ }+ });++ it("never use Cloud's included voice token, which goes only to its relay", () => {+ const env = { OMB_CLOUD_VOICE_URL: "https://cloud.example.test/api/cloud/services/voice/v1", OMB_CLOUD_VOICE_TOKEN: "omb_voice_included" };+ expect(liveCallKey({ live: elevenlabs, tts: {} } as AppConfig, env)).toBeNull();+ expect(liveCallKey({ live: elevenlabs, tts: { key: "omb_voice_included" } } as AppConfig, env)).toBeNull();+ expect(liveCallKey({ live: elevenlabs, tts: { key: "own-key" } } as AppConfig, env)).toEqual({ key: "own-key", source: "elevenlabs" });+ });++ it("are ready with the ElevenLabs key that ElevenLabs voices use, with the agent saved for it, and report none of it", () => {+ const live = { ...elevenlabs, elevenlabsAgentId: "agent_1", elevenlabsAgentFor: fishKeyPrint("eleven-secret") };+ const cfg = { live, tts: { key: " eleven-secret " } } as AppConfig;+ expect(liveCallKey(cfg)).toEqual({ key: "eleven-secret", source: "elevenlabs" });+ expect(liveCallEndpoint(cfg, {})).toEqual({ provider: "elevenlabs", apiBase: "https://api.elevenlabs.io/v1/convai", model: "agent_1" });+ expect(liveCallEndpoint({ ...cfg, tts: { key: "another-account" } }, {})).toMatchObject({ model: "" });+ expect(liveSetupProblem(cfg)).toBeNull();+ const settings = liveSettingsFor(cfg);+ expect(settings).toMatchObject({ configured: true, keySource: "elevenlabs", provider: "elevenlabs" });+ expect(JSON.stringify(settings)).not.toContain("eleven-secret");+ });+});diff --git a/server/live-settings.ts b/server/live-settings.tsindex 225bdf303d..756d6d1d86 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -1,8 +1,10 @@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_GEMINI, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";+import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_ELEVENLABS, 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 { voiceCredential } from "./included-services.ts";+import { elevenLabsLiveEndpoint, usableElevenLabsAgent } from "./live-elevenlabs.ts";import { geminiLiveEndpoint } from "./live-gemini.ts";export const LIVE_IDLE_MINUTES_DEFAULT = 5;@@ -10,8 +12,9 @@ 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, 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 {+ * OpenAI, the Fish Audio key only to Fish Audio, the Gemini key only to Gemini and the person's own ElevenLabs key only to+ * ElevenLabs. */+export function liveCallKey(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): { key: string; source: LiveKeySource } | null {if (cfg.live?.provider === "fish") {const fish = cfg.tts?.fishKey?.trim();return fish ? { key: fish, source: "fishAudio" } : null;@@ -20,6 +23,11 @@ export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySourconst gemini = cfg.tts?.geminiKey?.trim();return gemini ? { key: gemini, source: "gemini" } : null;}+ if (cfg.live?.provider === "elevenlabs") {+ // Only the person's own key: Cloud's included voice token, even handed back as `tts.key`, goes only to its relay.+ const elevenlabs = voiceCredential(cfg.tts?.key?.trim() || undefined, env);+ return elevenlabs && !elevenlabs.included ? { key: elevenlabs.token, source: "elevenlabs" } : null;+ }const live = usableLiveKey(cfg.live);if (live) return { key: live, source: "live" };if (cfg.live?.provider === "azure") return null;@@ -33,12 +41,14 @@ export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = proceif (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);+ if (cfg.live?.provider === "elevenlabs") return elevenLabsLiveEndpoint(usableElevenLabsAgent(cfg.live, cfg.tts?.key ?? ""), 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 : provider === "gemini" ? LIVE_NEEDS_GEMINI : LIVE_NEEDS_KEY;+ const missing = provider === "azure" ? LIVE_NEEDS_AZURE : provider === "fish" ? LIVE_NEEDS_FISH : provider === "gemini" ? LIVE_NEEDS_GEMINI+ : provider === "elevenlabs" ? LIVE_NEEDS_ELEVENLABS : LIVE_NEEDS_KEY;if (!liveCallKey(cfg)) return missing;return liveCallEndpoint(cfg) ? null : missing;}@@ -67,7 +77,7 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {return {configured: liveSetupProblem(cfg) === null,...(key ? { keySource: key.source } : {}),- ...(provider === "azure" || provider === "fish" || provider === "gemini" ? { provider } : {}),+ ...(provider === "azure" || provider === "fish" || provider === "gemini" || provider === "elevenlabs" ? { 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.tsindex 58f3138838..0b20cdb32f 100644--- a/server/routes/live.ts+++ b/server/routes/live.ts@@ -13,7 +13,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; geminiVoice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;- /** A running Fish Audio or Gemini call's relay, only for the token its start answered with. */+ /** A running relayed (Fish Audio, Gemini or ElevenLabs) 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;}@@ -21,7 +21,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 or Gemini call, which has no offer.+ // Not trimmed: the SDP offer goes to OpenAI byte for byte. Absent on a relayed 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();@@ -44,7 +44,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", "gemini"]).optional(),+ provider: z.enum(["openai", "azure", "fish", "gemini", "elevenlabs"]).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(),@@ -84,7 +84,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 ?? started.gemini ?? { type: "webrtc", sdp: started.sdp } });+ return json(res, 201, { call: started.call, transport: started.fish ?? started.gemini ?? started.elevenlabs ?? { 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.tsxindex ec7d730fef..ce764ad969 100644--- a/src/components/LiveCallSettings.tsx+++ b/src/components/LiveCallSettings.tsx@@ -28,8 +28,9 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {const azure = live.provider === "azure";const fish = live.provider === "fish";const gemini = live.provider === "gemini";+ const elevenlabs = live.provider === "elevenlabs";const copy = liveKeyCopy(live.provider);- const hasKey = live.keySource === (fish ? "fishAudio" : gemini ? "gemini" : "live");+ const hasKey = live.keySource === (fish ? "fishAudio" : gemini ? "gemini" : elevenlabs ? "elevenlabs" : "live");// Gemini has its own voices, kept apart from the GPT-Live one.const voiceOptions = gemini ? GEMINI_LIVE_VOICE_OPTIONS : LIVE_VOICE_OPTIONS;const voice = gemini ? geminiLiveVoice(live.geminiVoice) : live.voice || "marin";@@ -77,8 +78,8 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {}}><LiveProviderSettings locked={keySaving} onSaving={setProviderSaving} />- {/* Fish Audio calls speak in the agent's own voice. */}- {!fish && <>+ {/* Fish Audio and ElevenLabs calls speak in their agent's own voice. */}+ {!fish && !elevenlabs && <><label className="flex items-center justify-between gap-2"><span className="text-ink-secondary">{t("call.live.voice")}</span><Select@@ -130,13 +131,13 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {)}</span></div>- {!hasKey && (azure || fish || gemini) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}- {live.keySource !== "live" && !azure && !fish && !gemini && (+ {!hasKey && (azure || fish || gemini || elevenlabs) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}+ {live.keySource !== "live" && !azure && !fish && !gemini && !elevenlabs && (<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, gemini })} {t(copy.cost)}</div>+ <div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish, gemini, elevenlabs })} {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.tsxindex 93c87f63db..c05576788d 100644--- a/src/components/LiveKeyNeeded.tsx+++ b/src/components/LiveKeyNeeded.tsx@@ -16,18 +16,20 @@ export function LiveKeyNeeded() {const azure = live?.provider === "azure";const fish = live?.provider === "fish";const gemini = live?.provider === "gemini";+ const elevenlabs = live?.provider === "elevenlabs";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") || (gemini && live?.keySource !== "gemini");+ const keyForm = (azure && Boolean(live?.azureEndpoint) && live?.keySource !== "live") || (fish && live?.keySource !== "fishAudio") || (gemini && live?.keySource !== "gemini")+ || (elevenlabs && live?.keySource !== "elevenlabs");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 || 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>+ {(azure || fish || gemini || elevenlabs) && <DismissWhenReady ready={live?.configured === true} />}+ {!azure && !fish && !gemini && !elevenlabs && <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, elevenlabs })} `}{t(copy.cost)}</p></section>;}diff --git a/src/components/LiveKeySetup.tsx b/src/components/LiveKeySetup.tsxindex 7982e6b524..419353624b 100644--- a/src/components/LiveKeySetup.tsx+++ b/src/components/LiveKeySetup.tsx@@ -20,6 +20,7 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = falsconst azure = provider === "azure";const fish = provider === "fish";const gemini = provider === "gemini";+ const elevenlabs = provider === "elevenlabs";const copy = liveKeyCopy(provider);const [key, setKey] = useState("");const [saving, setSaving] = useState(false);@@ -37,8 +38,8 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = falssetError(null);try {const status: ConfigStatus = window.ogb?.setCredential- ? 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 } }) });+ ? await window.ogb.setCredential(fish ? "fishAudioKey" : gemini ? "geminiTtsKey" : elevenlabs ? "ttsKey" : "openaiLiveKey", value)+ : await api("/api/config", { method: "PUT", body: JSON.stringify(fish ? { tts: { fishKey: value } } : gemini ? { tts: { geminiKey: value } } : elevenlabs ? { tts: { key: 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;@@ -64,14 +65,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, gemini })}</div>+ <div className="text-[13px] leading-[1.45] text-ink-secondary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish, gemini, elevenlabs })}</div><inputtype="password"autoComplete="off"spellCheck={false}value={key}onChange={(event) => setKey(event.target.value)}- placeholder={azure || fish || gemini ? "…" : "sk-…"}+ placeholder={azure || fish || gemini ? "…" : elevenlabs ? "sk_…" : "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.tsxindex 2b6c1ba9eb..9275c3b3d4 100644--- a/src/components/LiveProviderSettings.tsx+++ b/src/components/LiveProviderSettings.tsx@@ -51,6 +51,7 @@ export function LiveProviderSettings({ locked = false, onSaving }: { locked?: bo<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>+ <option value="elevenlabs">{t("call.live.provider.elevenlabs")}</option></Select></label>{provider === "azure" && (@@ -100,6 +101,7 @@ export function LiveProviderSettings({ locked = false, onSaving }: { locked?: bo)}{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>}+ {provider === "elevenlabs" && <div className="text-[12px] leading-4 text-ink-secondary">{t("call.live.elevenLabsHint")}</div>}{error && <div className="text-[12px] text-danger">{error}</div>}</div>);diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.tsindex 214350aeb1..f7018ab6e6 100644--- a/src/components/keys/KeysPage.dom.test.ts+++ b/src/components/keys/KeysPage.dom.test.ts@@ -101,11 +101,11 @@ describe("the keys page", () => {expect(rowsShown()).not.toContain("elevenlabs");});- it("offers the Live calls service, OpenAI, Azure OpenAI, Fish Audio or Gemini, on the separate live key row", () => {+ it("offers the Live calls service, OpenAI, Azure OpenAI, Fish Audio, Gemini or ElevenLabs, on the separate live key row", () => {setConfig({ ...fx.config, live: { configured: false, provider: "azure", voice: "", readTypedReplies: true, idleMinutes: 5 } });page();const select = row("liveKey")!.querySelector<HTMLSelectElement>("select")!;- expect([...select.options].map((option) => option.value)).toEqual(["openai", "azure", "fish", "gemini"]);+ expect([...select.options].map((option) => option.value)).toEqual(["openai", "azure", "fish", "gemini", "elevenlabs"]);expect(select.value).toBe("azure");expect(row("liveKey")!.querySelector('input[type="url"]')).not.toBeNull();});diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.tsindex fae215ffc3..8a8285f89d 100644--- a/src/components/keys/key-catalog.ts+++ b/src/components/keys/key-catalog.ts@@ -220,12 +220,12 @@ export function keyEntry(id: KeyId): KeyEntry {return entry;}-/** 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. */+/** With Azure OpenAI, Fish Audio, Gemini or ElevenLabs chosen for Live calls, the row for their key is about that service:+ * required, and no OpenAI key. With Fish Audio, Gemini or ElevenLabs 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" && provider !== "gemini") || !entry.target) return entry;+ if (id !== "liveKey" || (provider !== "azure" && provider !== "fish" && provider !== "gemini" && provider !== "elevenlabs") || !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 };@@ -233,6 +233,9 @@ export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefinedif (provider === "gemini") {return { ...entry, name: "Gemini", labelKey: "keys.label.geminiTts", purposeKey: "keys.purpose.liveKeyGemini", target: keyEntry("geminiTts").target };}+ if (provider === "elevenlabs") {+ return { ...entry, name: "ElevenLabs", labelKey: "keys.label.elevenlabs", purposeKey: "keys.purpose.liveKeyElevenLabs", target: keyEntry("elevenlabs").target };+ }return { ...entry, name: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };}@@ -246,11 +249,11 @@ export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefireturn entry.target?.saved(config) ?? entry.status?.(config) ?? { configured: false };}-/** 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+/** With Azure, Fish Audio, Gemini or ElevenLabs 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" || provider === "gemini");+ return id === "liveCalls" && (provider === "azure" || provider === "fish" || provider === "gemini" || provider === "elevenlabs");}/** 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.tsindex 6ac3a21faf..49b3372482 100644--- a/src/lib/call-mode.ts+++ b/src/lib/call-mode.ts@@ -12,14 +12,15 @@ export const CALL_MODES: ReadonlyArray<{ id: CallMode; label: LocaleKey }> = [{ id: "live", label: "call.mode.live" },];-export function liveDisclosure({ cloudHome = false, azure = false, fish = false, gemini = false }: { cloudHome?: boolean; azure?: boolean; fish?: boolean; gemini?: boolean } = {}): string {+export function liveDisclosure({ cloudHome = false, azure = false, fish = false, gemini = false, elevenlabs = false }: { cloudHome?: boolean; azure?: boolean; fish?: boolean; gemini?: boolean; elevenlabs?: 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");+ if (elevenlabs) return t(cloudHome ? "call.live.disclosureElevenLabsCloud" : "call.live.disclosureElevenLabs");return t(cloudHome ? "call.live.disclosureCloud" : "call.live.disclosure");}-/** 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. */+/** The copy about a Live call's key: Azure, Fish Audio, Gemini and ElevenLabs 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;@@ -30,6 +31,9 @@ export function liveKeyCopy(provider: LiveProvider | undefined) {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;}+ if (provider === "elevenlabs") {+ return { title: "call.live.elevenLabsKeyTitle", explain: "call.live.elevenLabsKeyExplain", field: "call.live.elevenLabsKeyField", key: "call.live.elevenLabsKey", missing: "call.live.elevenLabsNeedsKey", needs: "call.live.needsElevenLabs", cost: "call.live.elevenLabsCost" } 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-elevenlabs.test.ts b/src/lib/live-call-elevenlabs.test.tsnew file mode 100644index 0000000000..6e87b6f2bc--- /dev/null+++ b/src/lib/live-call-elevenlabs.test.ts@@ -0,0 +1,259 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { LiveElevenLabsSession, LiveElevenLabsTransport } from "../../shared/wire";+import { FISH_DELEGATE_TOOL, type FishSessionOptions } from "./live-call-fish";+import type { GeminiAudio } from "./live-call-gemini-audio";+import type { GeminiSocket } from "./live-call-gemini";+import { elevenLabsPlaybackRate, elevenLabsSessionStarter } from "./live-call-elevenlabs";+import { configureLiveMedia, liveMedia, resetLiveMedia, startLiveCall } from "./live-call-media";++const SESSION: LiveElevenLabsSession = {+ session_id: "elevenlabs_1", signed_url: "wss://api.elevenlabs.io/v1/convai/conversation?agent_id=a&conversation_signature=s",+ instructions: "You are Rigel. Be brief.", expires_at: "",+};+const METADATA = { type: "conversation_initiation_metadata", conversation_initiation_metadata_event: { conversation_id: "conv_1", agent_output_audio_format: "pcm_16000" } };++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>) { this.onmessage?.({ data: JSON.stringify(message) }); }+ 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 rate: number, 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 = elevenLabsSessionStarter({+ openSocket: (url) => { const socket = new FakeSocket(url); sockets.push(socket); return socket; },+ audio: (rate) => { const audio = new FakeAudio(rate, 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<LiveElevenLabsSession> = { 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(METADATA);+ 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));+/** Longer than the pause that ends the agent's turn. */+const pause = () => new Promise((resolve) => setTimeout(resolve, 350));++describe("an ElevenLabs Live session", () => {+ it("opens the signed URL, sends the call's instructions first, and joins once ElevenLabs and the microphone are ready", async () => {+ const t = harness();+ expect(t.socket().url).toBe(SESSION.signed_url);+ t.socket().open();+ expect(t.socket().sent).toEqual([{+ type: "conversation_initiation_client_data",+ conversation_config_override: { agent: { prompt: { prompt: SESSION.instructions } } },+ }]);+ expect(t.callbacks.onConnect).not.toHaveBeenCalled();+ t.socket().receive(METADATA);+ await t.starting;+ expect(t.callbacks.onConnect).toHaveBeenCalledWith({ sessionId: "elevenlabs_1" });+ expect(t.audio().rate).toBe(16_000);+ t.audio().mic!(new Int16Array([1, 2]).buffer);+ expect(t.socket().sent.at(-1)).toEqual({ user_audio_chunk: AUDIO });+ });++ it("plays the agent at the rate ElevenLabs names", () => {+ expect(elevenLabsPlaybackRate("pcm_24000")).toBe(24_000);+ expect(elevenLabsPlaybackRate("ulaw_8000")).toBe(16_000);+ expect(elevenLabsPlaybackRate(undefined)).toBe(16_000);+ });++ 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(METADATA);+ 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 ElevenLabs closes before the conversation starts", async () => {+ const t = harness();+ t.socket().open();+ t.socket().drop(1008);+ await expect(t.starting).rejects.toMatchObject({ code: "elevenlabs_1008" });+ });++ it("answers ElevenLabs' pings so the conversation stays open", async () => {+ const t = harness();+ await t.connect();+ t.socket().receive({ type: "ping", ping_event: { event_id: 7, ping_ms: 50 } });+ expect(t.socket().sent.at(-1)).toEqual({ type: "pong", event_id: 7 });+ });++ it("plays the agent, speaking until its audio has played, captions both sides, and stops at an interruption", async () => {+ const t = harness();+ await t.connect();+ t.socket().receive({ type: "user_transcript", user_transcription_event: { user_transcript: " check my mail " } });+ expect(t.callbacks.onUserTranscript).toHaveBeenCalledWith({ segmentId: "s0", text: "check my mail", final: true });+ t.socket().receive({ type: "agent_response", agent_response_event: { agent_response: "Checking now." } });+ expect(t.callbacks.onAgentResponseDelta).toHaveBeenCalledWith({ segmentId: "a1", text: "Checking now." });+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 1 } });+ expect(t.audio().played).toEqual([4]);+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("speaking");+ t.audio().finish();+ await pause();+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 2 } });+ t.socket().receive({ type: "interruption", interruption_event: { event_id: 3 } });+ expect(t.audio().flushed).toBe(1);+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");+ // The interrupted answer's audio still on its way is not played; the next answer's is.+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 3 } });+ expect(t.audio().played).toEqual([4, 4]);+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 4 } });+ expect(t.audio().played).toEqual([4, 4, 4]);+ });++ it("keeps speaking through a short gap between the agent's audio chunks", async () => {+ const t = harness();+ const session = await t.connect();+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 1 } });+ session.sendUserMessage("[OpenMausBot] You have two new emails.");+ t.audio().finish();+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO, event_id: 1 } });+ await pause();+ expect(t.callbacks.onModeChange).not.toHaveBeenCalledWith("listening");+ expect(t.socket().sent.map((m) => m.type)).not.toContain("user_message");+ t.audio().finish();+ await pause();+ expect(t.callbacks.onModeChange).toHaveBeenLastCalledWith("listening");+ expect(t.socket().sent.at(-1)).toEqual({ type: "user_message", text: "[OpenMausBot] You have two new emails." });+ });++ it("answers the delegate tool call with the harness's words", async () => {+ const t = harness();+ await t.connect();+ t.socket().receive({ type: "client_tool_call", client_tool_call: { tool_name: FISH_DELEGATE_TOOL, tool_call_id: "tc_1", parameters: { request: "check mail" } } });+ expect(t.delegate).toHaveBeenCalledWith({ request: "check mail" }, { callId: "tc_1" });+ await settle();+ expect(t.socket().sent.at(-1)).toEqual({ type: "client_tool_result", tool_call_id: "tc_1", result: "On it.", is_error: false });+ t.socket().receive({ type: "client_tool_call", client_tool_call: { tool_name: "other", tool_call_id: "tc_2", parameters: {} } });+ await settle();+ expect(t.socket().sent.at(-1)).toEqual({ type: "client_tool_result", tool_call_id: "tc_2", result: "There is no tool named other.", is_error: true });+ t.delegate.mockRejectedValueOnce(new Error("relay down"));+ t.socket().receive({ type: "client_tool_call", client_tool_call: { tool_name: FISH_DELEGATE_TOOL, tool_call_id: "tc_3", parameters: {} } });+ await settle();+ expect(t.socket().sent.at(-1)).toEqual({ type: "client_tool_result", tool_call_id: "tc_3", result: "The request failed.", is_error: true });+ });++ it("holds the bot's words while the agent speaks, and sends a quiet update as context", async () => {+ const t = harness();+ const session = await t.connect();+ t.socket().receive({ type: "audio", audio_event: { audio_base_64: AUDIO } });+ session.sendUserMessage("[OpenMausBot] You have two new emails.");+ expect(t.socket().sent.at(-1)).not.toHaveProperty("type", "user_message");+ session.sendUserMessage("[OpenMausBot] still looking", { audio: false });+ expect(t.socket().sent.at(-1)).not.toHaveProperty("type", "contextual_update");+ t.audio().finish();+ await pause();+ expect(t.socket().sent.slice(-2)).toEqual([+ { type: "user_message", text: "[OpenMausBot] You have two new emails." },+ { type: "contextual_update", text: "[OpenMausBot] still looking" },+ ]);+ });++ it("stops sending the microphone while muted", async () => {+ const t = harness();+ const session = await t.connect();+ await session.setMicMuted(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("ends the call when ElevenLabs closes the conversation", async () => {+ const t = harness();+ await t.connect();+ t.socket().drop(1000);+ expect(t.callbacks.onDisconnect).toHaveBeenCalledWith({ reason: "connection_lost" });+ expect(t.audio().closed).toBe(true);+ });++ 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("type", "user_message");+ expect(t.callbacks.onDisconnect).not.toHaveBeenCalled();+ });+});++describe("an ElevenLabs Live call on screen", () => {+ const live = { callId: "c1", botId: "b1", threadId: "t1", client: "web", voice: "agent", startedAt: 5, status: "connecting" } as const;+ const transport: LiveElevenLabsTransport = { type: "elevenlabs", 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 ElevenLabs', not Fish's or Gemini'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();+ const startElevenLabs = 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, startElevenLabs: startElevenLabs as never, getUserMedia: getUserMedia as never, createPeer: vi.fn() as never });+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "elevenlabs" });+ 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).not.toHaveBeenCalled();+ expect(startElevenLabs).toHaveBeenCalledWith(expect.objectContaining({ sessionToken: SESSION }));+ expect(liveMedia()).toMatchObject({ phase: "starting", callId: "c1", provider: "elevenlabs" });+ });+});diff --git a/src/lib/live-call-elevenlabs.ts b/src/lib/live-call-elevenlabs.tsnew file mode 100644index 0000000000..5a8a1b09a5--- /dev/null+++ b/src/lib/live-call-elevenlabs.ts@@ -0,0 +1,263 @@+// An ElevenLabs Agents Live call: this page holds the conversation's WebSocket (a signed URL the harness asked for, so the+// key stays on the harness), the microphone and the agent's audio, and FishCall relays what was said to the harness as on a+// Fish Audio call. The agent allows this conversation to set its prompt, so the call's instructions go in the first message.+import type { LiveElevenLabsSession } from "../../shared/wire";+import { browserGeminiAudio, type GeminiAudio } from "./live-call-gemini-audio";+import type { FishAgentSession, FishSessionOptions, FishSessionStarter } from "./live-call-fish";+import { decodeBase64, encodeBase64, type GeminiSocket } from "./live-call-gemini";++/** The agent is set up to answer with 16 kHz PCM; the first message names the format. */+const DEFAULT_RATE = 16_000;+/** ElevenLabs sends no end of the agent's turn, so a pause in its audio this long ends it, not a late chunk. */+const IDLE_GRACE_MS = 300;++export interface ElevenLabsSessionDeps {+ openSocket(url: string): GeminiSocket;+ /** Plays the agent at `rate` Hz. */+ audio(rate: number): GeminiAudio;+}++const browserDeps: ElevenLabsSessionDeps = {+ openSocket: (url) => new WebSocket(url) as unknown as GeminiSocket,+ audio: browserGeminiAudio,+};++/** ElevenLabs Agents WebSocket events this call reads. */+type ServerMessage = {+ type?: string;+ conversation_initiation_metadata_event?: { conversation_id?: string; agent_output_audio_format?: string };+ audio_event?: { audio_base_64?: string; event_id?: number };+ interruption_event?: { event_id?: number };+ user_transcription_event?: { user_transcript?: string };+ agent_response_event?: { agent_response?: string };+ ping_event?: { event_id?: number };+ client_tool_call?: { tool_name?: string; tool_call_id?: string; parameters?: Record<string, unknown> };+};++type Outgoing = { type: "client_tool_result" | "user_message" | "contextual_update" } & Record<string, unknown>;++export function elevenLabsSessionStarter(deps: ElevenLabsSessionDeps = browserDeps): FishSessionStarter<LiveElevenLabsSession> {+ return (options) => new ElevenLabsLiveSession(options, deps).start();+}++export const startElevenLabsLiveSession = elevenLabsSessionStarter();++/** The playback rate of a `pcm_<rate>` format. */+export function elevenLabsPlaybackRate(format: string | undefined): number {+ const rate = Number(/^pcm_(\d{4,6})$/.exec(format ?? "")?.[1]);+ return rate >= 8_000 && rate <= 48_000 ? rate : DEFAULT_RATE;+}++class ElevenLabsLiveSession implements FishAgentSession {+ private readonly options: FishSessionOptions<LiveElevenLabsSession>;+ private readonly deps: ElevenLabsSessionDeps;+ private socket: GeminiSocket | null = null;+ private audio: GeminiAudio | null = null;+ private ready = false;+ private ended = false;+ private muted = false;+ /** Tool answers and the bot's words, in order; a user message interrupts the agent, so it waits while the agent speaks. */+ private outbox: Outgoing[] = [];+ private segment = 0;+ private speaking = false;+ private idleTimer: ReturnType<typeof setTimeout> | null = null;+ /** Audio of an interrupted answer still on its way is not played. */+ private interruptedAt = -1;++ constructor(options: FishSessionOptions<LiveElevenLabsSession>, deps: ElevenLabsSessionDeps) {+ this.options = options;+ this.deps = deps;+ }++ /** Resolves once ElevenLabs has started the conversation and the microphone is open. */+ start(): Promise<FishAgentSession> {+ return new Promise((resolve, reject) => {+ const session = this.options.sessionToken;+ const socket = this.deps.openSocket(session.signed_url);+ socket.binaryType = "arraybuffer";+ this.socket = socket;+ let started = false;+ socket.onopen = () => {+ socket.send(JSON.stringify({+ type: "conversation_initiation_client_data",+ conversation_config_override: { agent: { prompt: { prompt: session.instructions } } },+ }));+ };+ socket.onmessage = (event) => {+ const message = this.parse(event.data);+ if (!message) return;+ if (message.type === "conversation_initiation_metadata" && !started) {+ started = true;+ void this.open(elevenLabsPlaybackRate(message.conversation_initiation_metadata_event?.agent_output_audio_format), resolve, reject);+ return;+ }+ this.onMessage(message);+ };+ socket.onerror = () => undefined;+ socket.onclose = (event) => {+ if (this.socket !== socket) return;+ this.socket = null;+ if (this.ready) return this.lost();+ this.shut();+ if (!started) reject(Object.assign(new Error("ElevenLabs closed the call before it started."), { code: `elevenlabs_${event.code}` }));+ };+ });+ }++ private async open(rate: number, resolve: (session: FishAgentSession) => void, reject: (error: unknown) => void): Promise<void> {+ try {+ this.audio = this.deps.audio(rate);+ this.audio.onIdle = () => this.playbackPaused();+ await this.audio.startMic((pcm) => this.sendAudio(pcm));+ } catch (error) {+ this.shut();+ return reject(error);+ }+ if (this.ended) return resolve(this);+ if (!this.socket) {+ this.shut();+ return reject(Object.assign(new Error("ElevenLabs closed the call before it started."), { code: "elevenlabs_closed" }));+ }+ this.ready = true;+ this.options.callbacks.onConnect({ sessionId: this.options.sessionToken.session_id });+ resolve(this);+ this.flush();+ }++ sendUserMessage(text: string, options?: { audio?: boolean }): void {+ // A contextual update joins what the agent knows without an answer; a user message is answered aloud.+ this.post(options?.audio === false ? { type: "contextual_update", text } : { type: "user_message", text });+ }++ async setMicMuted(muted: boolean): Promise<void> {+ 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.clearIdleTimer();+ this.audio?.close();+ this.audio = null;+ }++ /** ElevenLabs ended the conversation or the connection dropped: the call cannot go on over a new one. */+ private lost(): void {+ if (this.ended) return;+ this.ended = true;+ this.shut();+ this.options.callbacks.onDisconnect({ reason: "connection_lost" });+ }++ 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 {+ switch (message.type) {+ case "ping":+ return this.send({ type: "pong", event_id: message.ping_event?.event_id });+ case "audio": {+ const data = message.audio_event?.audio_base_64;+ const id = message.audio_event?.event_id;+ if (!data || !this.audio || (id !== undefined && id <= this.interruptedAt)) return;+ this.clearIdleTimer();+ this.audio.play(decodeBase64(data));+ if (!this.speaking) {+ this.speaking = true;+ this.options.callbacks.onModeChange("speaking");+ }+ return;+ }+ case "user_transcript": {+ const text = message.user_transcription_event?.user_transcript?.trim();+ if (!text) return;+ this.options.callbacks.onUserTranscript({ segmentId: `s${this.segment}`, text, final: true });+ this.segment += 1;+ return;+ }+ case "agent_response": {+ const text = message.agent_response_event?.agent_response?.trim();+ if (text) this.options.callbacks.onAgentResponseDelta({ segmentId: `a${this.segment}`, text });+ return;+ }+ case "interruption":+ this.interruptedAt = message.interruption_event?.event_id ?? this.interruptedAt;+ this.clearIdleTimer();+ this.audio?.flush();+ return this.playbackIdle();+ case "client_tool_call":+ return this.onToolCall(message.client_tool_call ?? {});+ }+ }++ private playbackPaused(): void {+ this.clearIdleTimer();+ this.idleTimer = setTimeout(() => {+ this.idleTimer = null;+ this.playbackIdle();+ }, IDLE_GRACE_MS);+ }++ private clearIdleTimer(): void {+ if (this.idleTimer) clearTimeout(this.idleTimer);+ this.idleTimer = null;+ }++ private playbackIdle(): void {+ if (!this.speaking) return;+ this.speaking = false;+ this.options.callbacks.onModeChange("listening");+ this.flush();+ }++ private onToolCall(call: { tool_name?: string; tool_call_id?: string; parameters?: Record<string, unknown> }): void {+ const id = call.tool_call_id ?? "";+ const name = call.tool_name ?? "";+ const tool = this.options.clientTools[name];+ const answer = tool ? tool(call.parameters ?? {}, { callId: id }) : Promise.resolve(`There is no tool named ${name}.`);+ void answer.then((result) => {+ this.post({ type: "client_tool_result", tool_call_id: id, result: String(result), is_error: !tool });+ }, () => {+ this.post({ type: "client_tool_result", tool_call_id: id, result: "The request failed.", is_error: true });+ });+ }++ private sendAudio(pcm: ArrayBuffer): void {+ if (!this.ready || this.muted) return;+ this.send({ user_audio_chunk: encodeBase64(pcm) });+ }++ /** Sent now, or kept until the conversation has started and, for a user message, until the agent stops speaking. */+ private post(message: Outgoing): void {+ if (this.ended) return;+ this.outbox.push(message);+ this.flush();+ }++ private flush(): void {+ while (this.ready && this.socket?.readyState === 1 && this.outbox.length && !(this.speaking && this.outbox[0]!.type === "user_message")) {+ 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-gemini-audio.ts b/src/lib/live-call-gemini-audio.tsindex ab4338e2c7..b8d8df7926 100644--- a/src/lib/live-call-gemini-audio.ts+++ b/src/lib/live-call-gemini-audio.ts@@ -1,4 +1,5 @@-// The microphone and speaker of a Gemini Live call: Gemini takes 16 kHz 16-bit PCM and answers with 24 kHz 16-bit PCM.+// The microphone and speaker of a Gemini or ElevenLabs Live call: both take 16 kHz 16-bit PCM; Gemini answers with 24 kHz+// 16-bit PCM, ElevenLabs at the rate its agent is set up for.const MIC_RATE = 16_000;const SPEAKER_RATE = 24_000;/** About 100 ms of microphone audio per message. */@@ -69,7 +70,7 @@ export function pcm16ToFloat(pcm: ArrayBuffer): Float32Array<ArrayBuffer> {return out;}-export function browserGeminiAudio(): GeminiAudio {+export function browserGeminiAudio(speakerRate = SPEAKER_RATE): GeminiAudio {let context: AudioContext | null = new AudioContext();let stream: MediaStream | null = null;let node: AudioWorkletNode | null = null;@@ -102,7 +103,7 @@ export function browserGeminiAudio(): GeminiAudio {if (!context) return;const samples = pcm16ToFloat(pcm);if (!samples.length) return;- const buffer = context.createBuffer(1, samples.length, SPEAKER_RATE);+ const buffer = context.createBuffer(1, samples.length, speakerRate);buffer.copyToChannel(samples, 0);const source = context.createBufferSource();source.buffer = buffer;diff --git a/src/lib/live-call-gemini.ts b/src/lib/live-call-gemini.tsindex 55dfe8a07d..a91842dbdf 100644--- a/src/lib/live-call-gemini.ts+++ b/src/lib/live-call-gemini.ts@@ -59,12 +59,12 @@ export function geminiSessionStarter(deps: GeminiSessionDeps = browserDeps): Fisexport const startGeminiLiveSession = geminiSessionStarter();-function decodeBase64(data: string): ArrayBuffer {+export function decodeBase64(data: string): ArrayBuffer {const bytes = Uint8Array.from(atob(data), (c) => c.charCodeAt(0));return bytes.buffer;}-function encodeBase64(buffer: ArrayBuffer): string {+export 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));diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.tsindex 7513f54556..15591aa2e0 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, LiveGeminiSession, LiveGeminiTransport, LiveProvider } from "../../shared/wire";+import type { LiveCallState, LiveElevenLabsSession, LiveElevenLabsTransport, 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 FishCallHooks, type FishSessionStarter } from "./live-call-fish";+import { startElevenLabsLiveSession } from "./live-call-elevenlabs";import { startGeminiLiveSession } from "./live-call-gemini";import { t } from "./i18n";@@ -48,6 +49,7 @@ export interface LiveMediaDeps {openInBrowser(url: string): void;startFish: FishSessionStarter;startGemini: FishSessionStarter<LiveGeminiSession>;+ startElevenLabs: FishSessionStarter<LiveElevenLabsSession>;}const IDLE: LiveMediaState = {@@ -94,6 +96,7 @@ const defaults: LiveMediaDeps = {openInBrowser: (url) => void openExternalLink(url).catch(() => undefined),startFish: startFishAgentSession,startGemini: startGeminiLiveSession,+ startElevenLabs: startElevenLabsLiveSession,};let deps: LiveMediaDeps = defaults;@@ -196,7 +199,7 @@ export async function startLiveCall(target: { botId: string; threadId: string; pset({ ...IDLE, phase: "starting", ...where });startCall(target.botId);try {- if (target.provider === "fish" || target.provider === "gemini") return await startFishCall(target, mine);+ if (target.provider === "fish" || target.provider === "gemini" || target.provider === "elevenlabs") 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;@@ -272,10 +275,10 @@ export async function startLiveCall(target: { botId: string; threadId: string; p}}-/** Fish's SDK, or the Gemini session here, opens the microphone and plays the agent; the harness follows the call through+/** Fish's SDK, or the Gemini or ElevenLabs 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 | LiveGeminiTransport | { type: "webrtc" } }>("/api/live/session", {+ const result = await deps.request<{ call: LiveCallState; transport: LiveFishTransport | LiveGeminiTransport | LiveElevenLabsTransport | { type: "webrtc" } }>("/api/live/session", {method: "POST",body: JSON.stringify({ botId: target.botId, threadId: target.threadId, client: liveClient(deps.capabilities()) }),timeoutMs: 35_000,@@ -313,7 +316,8 @@ async function startFishCall(target: { botId: string; threadId: string }, mine:},now: () => Date.now(),};- const call = transport.type === "gemini" ? new FishCall(transport, hooks, deps.startGemini) : new FishCall(transport, hooks, deps.startFish);+ const call = transport.type === "gemini" ? new FishCall(transport, hooks, deps.startGemini)+ : transport.type === "elevenlabs" ? new FishCall(transport, hooks, deps.startElevenLabs) : 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.jsonindex 569cb2a724..8d649952fe 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6846,6 +6846,17 @@"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.provider.elevenlabs": "ElevenLabs Agents",+ "call.live.elevenLabsHint": "ElevenLabs Live calls work in the desktop app and in a browser, for the owner of this computer. They use the ElevenLabs API key that ElevenLabs voices use, and set up one agent for calls on that account.",+ "call.live.elevenLabsKey": "ElevenLabs key",+ "call.live.elevenLabsNeedsKey": "Add your ElevenLabs API key with Change key. ElevenLabs voices use the same key.",+ "call.live.elevenLabsKeyTitle": "Live calls through ElevenLabs",+ "call.live.elevenLabsKeyExplain": "Paste an ElevenLabs API key that may use Agents. The first call sets up an agent for calls on that account. ElevenLabs bills the call to that account; the bot's own work is billed as usual.",+ "call.live.elevenLabsKeyField": "ElevenLabs API key",+ "call.live.elevenLabsCost": "Via ElevenLabs Agents on your ElevenLabs account, billed by ElevenLabs for the call's minutes.",+ "call.live.needsElevenLabs": "Live calls through ElevenLabs need your ElevenLabs API key.",+ "call.live.disclosureElevenLabs": "A Live call sends your voice to ElevenLabs, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what ElevenLabs hears on to the bot. The ElevenLabs key stays on your computer; the call gets a short-lived signed link only.",+ "call.live.disclosureElevenLabsCloud": "A Live call sends your voice to ElevenLabs, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what ElevenLabs hears on to the bot. The ElevenLabs key stays in the Cloud; the call gets a short-lived signed link only.","call.live.keyFromApiKeys": "Uses your OpenAI API key from Settings → API keys.","settings.group.you": "You","settings.group.ai": "AI",@@ -7986,6 +7997,7 @@"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.liveKeyElevenLabs": "Required. Live calls through ElevenLabs use your ElevenLabs 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",