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 Live calls speak in each bot's own voice
phelix00179ac30c3bc96
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.tsindex 68c0b8a8af..90367e23cd 100644--- a/packages/phone-protocol/src/live-call-wire.ts+++ b/packages/phone-protocol/src/live-call-wire.ts@@ -139,6 +139,8 @@ export interface LiveElevenLabsSession {session_id: string;signed_url: string;instructions: string;+ /** The bot's own ElevenLabs voice, sent as the conversation's voice override; absent when the call keeps the agent's voice. */+ voice_id?: string;/** ISO time by which the client must connect */expires_at: string;}diff --git a/server/live-call.ts b/server/live-call.tsindex aec8c61b9d..824bdc76a3 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -148,6 +148,8 @@ export interface LiveBot {name: string;title?: string;description?: string;+ /** The voice the bot speaks with in chat; an ElevenLabs Live call uses it when it is an ElevenLabs voice id. */+ voice?: string;}export interface LiveHistoryMessage {diff --git a/server/live-elevenlabs.test.ts b/server/live-elevenlabs.test.tsindex e1d846e7de..a9cae97cfc 100644--- a/server/live-elevenlabs.test.ts+++ b/server/live-elevenlabs.test.ts@@ -117,3 +117,52 @@ describe("an ElevenLabs Live call's session", () => {await expect(create(fetchImpl)).rejects.toMatchObject({ status: 429 });});});++// Spec: a bot's Live call speaks with the bot's own ElevenLabs voice (the voice it uses in chat), by the conversation's+// voice override, so one agent can serve every bot. Written for the change adding `voice_id` to the ElevenLabs Live session.+describe("an ElevenLabs Live call's voice", () => {+ const VOICE = "Kysvuk17R9MDAP9l089v";+ const withVoice = (fetchImpl: typeof fetch, voice: string | undefined, endpoint = elevenLabsLiveEndpoint("agent_1", {})) =>+ createElevenLabsLiveSession({ key: "k", endpoint, bot: { name: "Rigel", voice }, history: [], cloudHome: false, fetchImpl, now: () => NOW });+ const agentWith = (voiceOverride: boolean) => () => Response.json({ platform_settings: { overrides: { conversation_config_override: { tts: { voice_id: voiceOverride } } } } });++ it("sets up new agents so a conversation may bring its own voice", async () => {+ const fetchImpl = fakeElevenLabs();+ await setUpElevenLabsAgent("k", elevenLabsLiveEndpoint(null, {}), "P", fetchImpl);+ const agent = JSON.parse(String(fetchImpl.mock.calls[1]![1]!.body));+ expect(agent.platform_settings.overrides.conversation_config_override.tts).toEqual({ voice_id: true });+ });++ it("sends the bot's ElevenLabs voice and leaves an agent that already allows it alone", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/agent_1": agentWith(true) });+ expect((await withVoice(fetchImpl, VOICE)).voice_id).toBe(VOICE);+ expect(fetchImpl.mock.calls.some(([, init]) => init?.method === "PATCH")).toBe(false);+ });++ it("lets an older agent take a voice, once, before the call", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/agent_1": agentWith(false) });+ expect((await withVoice(fetchImpl, VOICE)).voice_id).toBe(VOICE);+ const patch = fetchImpl.mock.calls.find(([, init]) => init?.method === "PATCH")!;+ expect(JSON.parse(String(patch[1]!.body))).toEqual({ platform_settings: { overrides: { conversation_config_override: { tts: { voice_id: true } } } } });+ });++ it("sends no voice for a bot without one, or whose voice is not an ElevenLabs voice id, and never touches the agent", async () => {+ for (const voice of [undefined, "", "alloy", "a".repeat(32), "../../x"]) {+ const fetchImpl = fakeElevenLabs();+ expect(await withVoice(fetchImpl, voice)).not.toHaveProperty("voice_id");+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ }+ });++ it("keeps the agent's voice, and still calls, when the key may not change agents", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/agent_1": () => new Response("", { status: 403 }) });+ const session = await withVoice(fetchImpl, VOICE);+ expect(session).not.toHaveProperty("voice_id");+ expect(session.signed_url).toBe(SIGNED);+ });++ it("says when the agent is gone, so it can be set up again", async () => {+ const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/agent_1": () => new Response("", { status: 404 }) });+ await expect(withVoice(fetchImpl, VOICE)).rejects.toMatchObject({ elevenlabsStatus: 404 });+ });+});diff --git a/server/live-elevenlabs.ts b/server/live-elevenlabs.tsindex 1746c8570e..1145acdce6 100644--- a/server/live-elevenlabs.ts+++ b/server/live-elevenlabs.ts@@ -12,6 +12,8 @@ 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}$/;+/** An ElevenLabs voice id: the voice a bot speaks with in chat, which its Live calls use too. Any other saved voice is not one. */+const VOICE_ID = /^[A-Za-z0-9]{20}$/;/** 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.";@@ -35,11 +37,11 @@ export function usableElevenLabsAgent(live: LiveConfig | undefined, key: string)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>> {+async function elevenLabsRequest(fetchImpl: typeof fetch, key: string, url: string, body?: unknown, method: "GET" | "POST" | "PATCH" = body === undefined ? "GET" : "POST"): Promise<Record<string, unknown>> {let response: Response;try {response = await fetchImpl(url, {- method: body === undefined ? "GET" : "POST",+ method,headers: { "xi-api-key": key.trim(), ...(body === undefined ? {} : { "content-type": "application/json" }) },redirect: "error",...(body === undefined ? {} : { body: JSON.stringify(body) }),@@ -83,7 +85,7 @@ export async function setUpElevenLabsAgent(key: string, endpoint: LiveEndpoint,},// Without the override ElevenLabs refuses the prompt each conversation sends. With auth on, a conversation needs a// signed URL, which only the harness can get with the key: knowing the agent id is not enough to spend the person's credits.- platform_settings: { overrides: { conversation_config_override: { agent: { prompt: { prompt: true } } } }, auth: { enable_auth: true } },+ platform_settings: { overrides: { conversation_config_override: { agent: { prompt: { prompt: true } }, tts: { voice_id: true } } }, auth: { enable_auth: true } },});const agentId = typeof agent.agent_id === "string" && AGENT_ID.test(agent.agent_id) ? agent.agent_id : "";if (!agentId) throw new LiveSessionError(UNEXPECTED, 502);@@ -96,6 +98,23 @@ export async function setUpElevenLabsAgent(key: string, endpoint: LiveEndpoint,}}+/** Agents set up before bots had their own call voice refuse a voice in a conversation; this lets the agent take one. A key that+ * may not change agents leaves the agent as it is: the call then speaks in the agent's voice. An agent gone from the account+ * still fails, so the caller sets it up again. */+async function allowVoiceOverride(fetchImpl: typeof fetch, key: string, apiBase: string, agentId: string): Promise<boolean> {+ const url = `${apiBase}/agents/${encodeURIComponent(agentId)}`;+ try {+ const agent = await elevenLabsRequest(fetchImpl, key, url);+ const settings = agent.platform_settings as { overrides?: { conversation_config_override?: { tts?: { voice_id?: unknown } } } } | undefined;+ if (settings?.overrides?.conversation_config_override?.tts?.voice_id === true) return true;+ await elevenLabsRequest(fetchImpl, key, url, { platform_settings: { overrides: { conversation_config_override: { tts: { voice_id: true } } } } }, "PATCH");+ return true;+ } catch (error) {+ if ((error as { elevenlabsStatus?: number }).elevenlabsStatus === 404) throw error;+ return false;+ }+}+export interface CreateElevenLabsSessionInput {key: string;endpoint: LiveEndpoint;@@ -111,7 +130,10 @@ export interface CreateElevenLabsSessionInput {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 → AI → Other services 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 fetchImpl = input.fetchImpl ?? fetch;+ const saved = input.bot.voice?.trim() ?? "";+ const voiceId = VOICE_ID.test(saved) && await allowVoiceOverride(fetchImpl, key, input.endpoint.apiBase, input.endpoint.model) ? saved : "";+ const answer = await elevenLabsRequest(fetchImpl, 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:");@@ -120,6 +142,7 @@ export async function createElevenLabsLiveSession(input: CreateElevenLabsSessionsession_id: `elevenlabs_${randomBytes(12).toString("hex")}`,signed_url: url,instructions: fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }),+ ...(voiceId ? { voice_id: voiceId } : {}),expires_at: new Date((input.now ?? Date.now)() + CONNECT_WITHIN_MS).toISOString(),};}diff --git a/src/lib/live-call-elevenlabs.test.ts b/src/lib/live-call-elevenlabs.test.tsindex 2406f91462..65e8694daa 100644--- a/src/lib/live-call-elevenlabs.test.ts+++ b/src/lib/live-call-elevenlabs.test.ts@@ -53,7 +53,7 @@ class FakeAudio implements GeminiAudio {close() { this.closed = true; }}-function harness({ denied = false, held = false } = {}) {+function harness({ denied = false, held = false, session = SESSION } = {}) {const sockets: FakeSocket[] = [];const audios: FakeAudio[] = [];const start = elevenLabsSessionStarter({@@ -64,7 +64,7 @@ function harness({ denied = false, held = false } = {}) {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 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 () => {@@ -79,6 +79,13 @@ const AUDIO = btoa(String.fromCharCode(1, 0, 2, 0));const settle = () => new Promise((resolve) => setTimeout(resolve, 0));describe("an ElevenLabs Live session", () => {+ // Spec: the bot's own voice goes in the conversation's override; without one the agent keeps its voice.+ it("sends the bot's voice with the instructions when the session has one", () => {+ const t = harness({ session: { ...SESSION, voice_id: "Kysvuk17R9MDAP9l089v" } });+ t.socket().open();+ expect(t.socket().sent[0]).toMatchObject({ conversation_config_override: { agent: { prompt: { prompt: SESSION.instructions } }, tts: { voice_id: "Kysvuk17R9MDAP9l089v" } } });+ });+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);diff --git a/src/lib/live-call-elevenlabs.ts b/src/lib/live-call-elevenlabs.tsindex 16f94ae538..c0229e933c 100644--- a/src/lib/live-call-elevenlabs.ts+++ b/src/lib/live-call-elevenlabs.ts@@ -86,7 +86,7 @@ class ElevenLabsLiveSession implements FishAgentSession {socket.onopen = () => {socket.send(JSON.stringify({type: "conversation_initiation_client_data",- conversation_config_override: { agent: { prompt: { prompt: session.instructions } } },+ conversation_config_override: { agent: { prompt: { prompt: session.instructions } }, ...(session.voice_id ? { tts: { voice_id: session.voice_id } } : {}) },}));};socket.onmessage = (event) => {