Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
#5512: Fish Live calls use the Fish Audio key and set up their own agent
milind-soni1f52d3f74081
diff --git a/docs/verification/live-calls.md b/docs/verification/live-calls.mdindex c4fac90e93..baa34a6483 100644--- a/docs/verification/live-calls.md+++ b/docs/verification/live-calls.md@@ -121,24 +121,33 @@ so a caller who gets through stops at the setup prompt.## Fish Audio Live 3 as the Live provider-With `live.provider: "fish"` (`OMB_LIVE_PROVIDER=fish`) a call starts the-person's published Fish Audio agent (`live.fishAgentId`, `OMB_FISH_LIVE_AGENT_ID`,-letters, digits, `-` and `_`): `POST https://api.fish.audio/v1/agent/sessions`-with `{ agent_id, overrides: { system_prompt } }` and the key as a bearer token,+With `live.provider: "fish"` (`OMB_LIVE_PROVIDER=fish`) a call uses the Fish+Audio key from Settings → API keys (`tts.fishKey`, `OMB_FISH_AUDIO_API_KEY`),+the same key Fish voices use; nothing else is asked. On the first call the+harness sets up an agent on that key's account (`server/live-fish.ts`+`setUpFishAgent`): a client tool `delegate` (`POST /v1/agent/tools`), an agent+on the `live3` engine in English with that tool (`POST /v1/agent/agents`),+`overrides_allowed: ["system_prompt"]` (`PATCH /v1/agent/agents/{id}`), and a+publish. It saves the agent as `live.fishAgentId` with `live.fishAgentFor`, a+short SHA-256 print of the key, so a key for another account sets up its own+agent. A saved agent that Fish answers `404` for is set up again once.+`OMB_FISH_LIVE_AGENT_ID` names an operator's own agent, used with any key and+never replaced. A Fish key saved as the Live key (`keyFor: "fish"`) is read as+the Fish Audio key while none is saved.++Each call is `POST https://api.fish.audio/v1/agent/sessions` with+`{ agent_id, overrides: { system_prompt } }` and the key as a bearer token,redirects refused. Fish answers with a LiveKit token, which goes to the clientas `transport: { type: "fish", session, relayToken }`; the client joins with-`@fishaudio/agent-client` 1.x, which holds the microphone and the agent's+`@fishaudio/agent-client` 1.0.0, which holds the microphone and the agent'saudio. The agent's voice is its own; the Voice setting is hidden. Hanging upalso calls `POST /v1/agent/sessions/{id}/end`. `OMB_FISH_LIVE_URL` points theharness at a fake Fish for tests and is honoured only as `http://127.0.0.1:<port>`;anything else falls back to Fish's own host.-The key is only `live.key`, saved with `keyFor: "fish"`; an OpenAI or Azure key-is never sent to Fish, and switching the Service forgets the key as for Azure.-In the environment, `OMB_OPENAI_LIVE_KEY` with `OMB_LIVE_PROVIDER=fish` and-`OMB_FISH_LIVE_AGENT_ID` is the operator's pairing. Without the key or a valid-agent id, `POST /api/live/session` answers `409` with `needsKey` and the Fish-setup sentence.+An OpenAI or Azure key is never sent to Fish, and the Fish key never to them.+Without a Fish Audio key, `POST /api/live/session` answers `409` with+`needsKey` and the Fish setup sentence.Fish has no server sideband. The client reports what it hears (final usertranscripts, the agent's speaking spans, the `delegate` tool call, the end) to@@ -159,16 +168,12 @@ server can start one.` The phone apps do not carry the Fish SDK yet, so a callfrom iOS or Android answers `400`. The client must report `connected` within`FISH_ATTACH_TIMEOUT_MS` (25 s, to allow a first microphone prompt).-To activate, the person needs:+The person needs a Fish Audio API key with Agent credit (about $0.07 per+minute of call). Live 3 speaks English only.-- A Fish Audio API key with Agent credit (about $0.07 per minute of call).-- An agent on the `live3` engine with a voice, `overrides_allowed` including- `system_prompt`, and a client tool named `delegate` with `expects_response`- and a timeout of 15–30 s attached through `tool_ids`; the agent published.-- English as the call language.--Checked with fixtures only: `server/live-fish.test.ts` (session request,-errors, relay), `server/live-call-controller.test.ts` "with Fish Audio chosen"+Checked with fixtures only: `server/live-fish.test.ts` (agent setup, session request,+errors, relay), `server/live-session-wiring.test.ts` (first-call setup, a+removed agent, an operator's agent), `server/live-call-controller.test.ts` "with Fish Audio chosen"(a real `FishRelay` as the sideband: heard, delegated, the bot's answer back asthe delegate result, End and Fish's own end), `server/routes/live.test.ts`(relay route), `server/live-settings.test.ts`, `server/live-access.test.ts`,diff --git a/server/config.ts b/server/config.tsindex 14c18b5520..e9009e2323 100644--- a/server/config.ts+++ b/server/config.ts@@ -28,7 +28,7 @@ import { settledFileCache, settledFileStamp } from "./settled-file.ts";import { isRemoteMcpServer, mcpServerServes, parseStoredMcpServer } from "./mcp-registry.ts"; import { postizKeyHeaders } from "./postiz/connection.ts";import { parseJson, schemaIssue, type JsonObject, type JsonValue } from "./schema.ts";import { deciderConfigSchema, type DeciderConfig } from "./decider/config.ts";-import { liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts";+import { fishKeyFromLiveKey, liveConfigSchema, liveConfigWithEnv, liveSettingEnv, type LiveConfig } from "./live-config.ts";import { browserEngineConfigSchema, isValidCdpTarget, type BrowserEngineConfig } from "./browser/config.ts";import { roomContextSettings } from "./room-context-settings.ts";import { localVmConfigSchema } from "./local-vm-settings.ts";@@ -763,7 +763,7 @@ export function loadConfig(): AppConfig {cfg.decider = { ...cfg.decider };if (process.env.OMB_JEV_API_KEY !== undefined) cfg.decider.key = process.env.OMB_JEV_API_KEY;if (process.env.OMB_OPENROUTER_DECIDER_KEY !== undefined) cfg.decider.openrouterKey = process.env.OMB_OPENROUTER_DECIDER_KEY; if (process.env.OMB_WORKERS_AI_TOKEN !== undefined) cfg.decider.workersAiToken = process.env.OMB_WORKERS_AI_TOKEN;- cfg.live = liveConfigWithEnv(cfg.live);+ cfg.live = liveConfigWithEnv(cfg.live); fishKeyFromLiveKey(cfg);cfg.imageGen = { ...cfg.imageGen };if (process.env.OMB_OPENAI_IMAGE_KEY !== undefined) cfg.imageGen.key = process.env.OMB_OPENAI_IMAGE_KEY;if (process.env.OMB_CUSTOM_IMAGE_KEY !== undefined) cfg.imageGen.customApiKey = process.env.OMB_CUSTOM_IMAGE_KEY;diff --git a/server/live-call.ts b/server/live-call.tsindex b5e6573603..89dd50ae6f 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -9,7 +9,7 @@ export const DEFAULT_LIVE_VOICE = "marin";export const MAX_SDP_BYTES = 64 * 1024;export const LIVE_NEEDS_KEY = "Live calls use your own OpenAI key. Add it in Settings → API keys.";export const LIVE_NEEDS_AZURE = "Live calls through Azure OpenAI need the resource endpoint, the GPT-Live deployment name and its key. Add them in Call settings.";-export const LIVE_NEEDS_FISH = "Live calls through Fish Audio need a Fish Audio API key and the id of a published Fish Audio agent. 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.";/** The client's data channel is untrusted: it may only hang up; every append goes over the sideband.* Exception: Azure OpenAI refuses `session.client`, so an Azure call goes without this list and its caller's channel keeps@@ -45,7 +45,7 @@ export interface LiveEndpoint {provider: LiveProvider;/** The versioned API root, e.g. `https://api.openai.com/v1` or `https://my-res.openai.azure.com/openai/v1`. */apiBase: string;- /** The OpenAI model id, the Azure deployment name, or the Fish Audio agent id. */+ /** The OpenAI model id, the Azure deployment name, or the Fish Audio agent id ('' until one is set up). */model: string;}diff --git a/server/live-config.ts b/server/live-config.tsindex 6f09294f7b..b113c39827 100644--- a/server/live-config.ts+++ b/server/live-config.ts@@ -4,7 +4,7 @@ import { z } from "zod";export const LIVE_KEY_NEEDS_ENDPOINT = "Save the Azure endpoint first: a Live key works only with the endpoint it was saved for.";const NOWHERE = "nowhere";-/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish" it is a Fish Audio API key and is required. `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 published Fish Audio agent a "fish" call starts; its voice is the agent's. `voice` is a GPT-Live voice. */+/** Live calls: `key` is a key for Live calls only; with `provider` "openai" (the default) a call without one uses `openai.key`, with "azure" it is the Azure resource's key and is required, with "fish" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`). `keyFor` says where `key` may go (`liveKeyTarget`): the server sets it when the key is saved and never takes it from a request; absent, the key is from before Azure was offered, so OpenAI's. `azureEndpoint` is the resource URL and `azureDeployment` the gpt-live-1 deployment name. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key. `voice` is a GPT-Live voice. */export const liveConfigSchema = z.object({key: z.string().optional(),keyFor: z.string().max(300).optional(),@@ -12,6 +12,7 @@ export const liveConfigSchema = z.object({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(),voice: z.string().trim().max(40).regex(/^[a-z]*$/, "a Live voice is a lowercase built-in voice name").optional(),readTypedReplies: z.boolean().optional(),idleMinutes: z.number().int().min(1).max(60).optional(),@@ -24,14 +25,15 @@ export interface LiveConfig {azureEndpoint?: string;azureDeployment?: string;fishAgentId?: string;+ fishAgentFor?: string;voice?: string;readTypedReplies?: boolean;idleMinutes?: number;}-/** Where a key saved now may go: "openai", "fish" (Fish Audio's own API host), or "azure:<host>"; null while Azure is chosen with no endpoint to tie it to. */+/** Where a key saved now may go: "openai", or "azure:<host>"; null while Azure is chosen with no endpoint to tie it to.+ * Fish Audio calls never use this key, so with Fish chosen it stays OpenAI's. */export function liveKeyTarget(live: LiveConfig | undefined): string | null {- if (live?.provider === "fish") return "fish";if (live?.provider !== "azure") return "openai";try {const host = new URL(live.azureEndpoint?.trim() ?? "").host.toLowerCase();@@ -73,11 +75,13 @@ export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.Procif (provider === "openai" || provider === "azure" || provider === "fish") 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 !== undefined) next.fishAgentId = env.OMB_FISH_LIVE_AGENT_ID.trim();+ if (env.OMB_FISH_LIVE_AGENT_ID?.trim()) {+ next.fishAgentId = env.OMB_FISH_LIVE_AGENT_ID.trim();+ delete next.fishAgentFor;+ }// Set together in the environment, the key and the Azure endpoint are the operator's own pairing. A `keyFor` from the// file stands: saves mirror settings into the environment, so they must not be able to pair a forgotten key.if (envKey?.trim() && provider === "azure" && env.OMB_AZURE_OPENAI_LIVE_ENDPOINT?.trim() && next.keyFor === undefined) next.keyFor = liveKeyTarget(next) ?? NOWHERE;- if (envKey?.trim() && provider === "fish" && env.OMB_FISH_LIVE_AGENT_ID?.trim() && next.keyFor === undefined) next.keyFor = "fish";return next;}@@ -87,6 +91,11 @@ export function liveSettingEnv(live: LiveConfig | undefined): Array<[value: stri[live?.provider, "OMB_LIVE_PROVIDER"],[live?.azureEndpoint, "OMB_AZURE_OPENAI_LIVE_ENDPOINT"],[live?.azureDeployment, "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT"],- [live?.fishAgentId, "OMB_FISH_LIVE_AGENT_ID"],];}++/** A Fish Audio key saved as the Live key (`keyFor: "fish"`) is the Fish Audio key while none is saved; it is never used as a Live key. */+export function fishKeyFromLiveKey(cfg: { live?: LiveConfig; tts?: { fishKey?: string } }): void {+ const saved = cfg.live?.keyFor === "fish" ? cfg.live.key?.trim() : undefined;+ if (saved && !cfg.tts?.fishKey?.trim()) cfg.tts = { ...cfg.tts, fishKey: saved };+}diff --git a/server/live-fish.test.ts b/server/live-fish.test.tsindex 2fa6b36708..85ac3b82a1 100644--- a/server/live-fish.test.ts+++ b/server/live-fish.test.ts@@ -1,11 +1,11 @@import { describe, expect, it, vi } from "vitest";import { LiveSessionError } from "./live-call.ts";import {- createFishLiveSession, endFishLiveSession, fishErrorMessage, fishInstructions, fishLiveBaseUrl, fishLiveEndpoint, FishRelays,- FISH_UPDATE_PREFIX, isFishAgentId,+ createFishLiveSession, endFishLiveSession, fishErrorMessage, fishInstructions, fishKeyPrint, fishLiveBaseUrl, fishLiveEndpoint, FishRelays,+ FISH_UPDATE_PREFIX, setUpFishAgent, usableFishAgent,} from "./live-fish.ts";-const ENDPOINT = fishLiveEndpoint("agent_123", {})!;+const ENDPOINT = fishLiveEndpoint("agent_123", {});const TOKEN = {transport: "livekit", session_id: "sess_1", expires_at: "2026-11-11T00:00:00Z", max_duration_seconds: 900,livekit_url: "wss://lk.fish.audio", token: "jwt.part.sig",@@ -24,12 +24,49 @@ describe("the Fish Audio endpoint", () => {}});- it("needs an agent id of word characters and dashes", () => {+ it("names an agent id of word characters and dashes, and none otherwise", () => {expect(ENDPOINT).toEqual({ provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_123" });- expect(fishLiveEndpoint(" agent-9 ", {})?.model).toBe("agent-9");- for (const id of [undefined, "", " ", "a/b", "../x", "a b", "x".repeat(129)]) expect(fishLiveEndpoint(id, {}), String(id)).toBeNull();- expect(isFishAgentId("ok_id-1")).toBe(true);- expect(isFishAgentId("no?query")).toBe(false);+ expect(fishLiveEndpoint(" agent-9 ", {}).model).toBe("agent-9");+ for (const id of [undefined, null, "", " ", "a/b", "../x", "a b", "x".repeat(129)]) expect(fishLiveEndpoint(id, {}).model, String(id)).toBe("");+ });+});++describe("the Fish agent for Live calls", () => {+ it("is used only with the key of the account it was set up on, or with any key when the operator chose it", () => {+ const own = { fishAgentId: "agent_1", fishAgentFor: fishKeyPrint("key-a") };+ expect(fishKeyPrint(" key-a ")).toBe(fishKeyPrint("key-a"));+ expect(fishKeyPrint("key-a")).not.toContain("key-a");+ expect(usableFishAgent(own, "key-a")).toBe("agent_1");+ expect(usableFishAgent(own, "key-b")).toBeNull();+ expect(usableFishAgent(own, "")).toBeNull();+ expect(usableFishAgent({ fishAgentId: "agent_op" }, "anything")).toBe("agent_op");+ expect(usableFishAgent({ fishAgentId: "../x" }, "k")).toBeNull();+ expect(usableFishAgent(undefined, "k")).toBeNull();+ });++ it("is set up as a published Live 3 agent with the delegate client tool and an overridable system prompt", async () => {+ const answers: Record<string, unknown> = { "POST /tools": { tool_id: "tool_1" }, "POST /agents": { agent_id: "agent_new" }, "PATCH /agents/agent_new": {}, "POST /agents/agent_new/publish": { version_number: 1 } };+ const fetchImpl = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ const route = `${init!.method} ${String(url).replace(ENDPOINT.apiBase, "")}`;+ return new Response(JSON.stringify(answers[route] ?? {}), { status: route in answers ? 200 : 404 });+ });+ await expect(setUpFishAgent(" fish-key ", { ...ENDPOINT, model: "" }, fetchImpl)).resolves.toBe("agent_new");+ const calls = fetchImpl.mock.calls.map(([url, init]) => ({ route: `${init!.method} ${String(url).replace(ENDPOINT.apiBase, "")}`, body: JSON.parse(String(init!.body)), init: init! }));+ expect(calls.map((call) => call.route)).toEqual(Object.keys(answers));+ expect(calls[0]!.body).toMatchObject({ name: "delegate", tool_type: "client", expects_response: true });+ expect(calls[1]!.body.config).toEqual({ voice: { engine: "live3", speaking_language: "en" }, tools: { enabled: true, tool_ids: ["tool_1"] } });+ expect(calls[2]!.body).toEqual({ overrides_allowed: ["system_prompt"] });+ for (const call of calls) {+ expect((call.init.headers as Record<string, string>).authorization).toBe("Bearer fish-key");+ expect(call.init.redirect).toBe("error");+ }+ });++ it("stops at Fish's first refusal with the user's next step, never Fish's body", async () => {+ const fetchImpl = fakeFetch(401, { message: "raw fish-key detail" });+ await expect(setUpFishAgent("fish-key", ENDPOINT, fetchImpl)).rejects.toMatchObject({ status: 502, message: fishErrorMessage(401) });+ expect(fetchImpl).toHaveBeenCalledTimes(1);+ await expect(setUpFishAgent("fish-key", ENDPOINT, fakeFetch(201, {}))).rejects.toMatchObject({ status: 502 });});});@@ -77,6 +114,7 @@ describe("creating a Fish Audio session", () => {expect((error as LiveSessionError).message).toBe(fishErrorMessage(status));expect((error as LiveSessionError).message).not.toContain("fish-key");expect((error as LiveSessionError).status).toBe(status === 429 ? 429 : 502);+ expect((error as { fishStatus?: number }).fishStatus).toBe(status);}});diff --git a/server/live-fish.ts b/server/live-fish.tsindex 324ca7b3dd..3ce73fc1f2 100644--- a/server/live-fish.ts+++ b/server/live-fish.ts@@ -1,13 +1,15 @@// Fish Audio Live 3 calls. The Fish key never leaves the harness: the client gets only Fish's single-use session token,// and Fish has no server sideband, so the client relays what was said and the harness answers through FishRelay.-import { randomBytes, timingSafeEqual } from "node:crypto";+import { createHash, randomBytes, timingSafeEqual } from "node:crypto";import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken } from "../shared/wire.ts";import type { LiveSocket } from "./live-call-controller.ts";import { liveInstructions, LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";+import type { LiveConfig } from "./live-config.ts";const FISH_BASE = "https://api.fish.audio";const CREATE_TIMEOUT_MS = 20_000;const END_TIMEOUT_MS = 5_000;+const SETUP_TIMEOUT_MS = 8_000;/** Fish agent ids as the dashboard and `GET /v1/agent/agents` show them. */const AGENT_ID = /^[\w-]{1,128}$/;const HISTORY_MESSAGES = 8;@@ -26,13 +28,71 @@ export function fishLiveBaseUrl(env: NodeJS.ProcessEnv = process.env): string {return /^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(override) ? override : FISH_BASE;}-export function fishLiveEndpoint(agentId: string | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {+/** `model` is the agent id, "" while no usable one is saved. */+export function fishLiveEndpoint(agentId: string | null | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint {const id = agentId?.trim() ?? "";- return AGENT_ID.test(id) ? { provider: "fish", apiBase: `${fishLiveBaseUrl(env)}/v1/agent`, model: id } : null;+ return { provider: "fish", apiBase: `${fishLiveBaseUrl(env)}/v1/agent`, model: AGENT_ID.test(id) ? id : "" };}-export function isFishAgentId(value: string): boolean {- return AGENT_ID.test(value);+/** Which Fish Audio account an agent was set up on, without keeping its key. */+export function fishKeyPrint(key: string): string {+ return createHash("sha256").update(key.trim()).digest("hex").slice(0, 16);+}++/** The saved agent, while it belongs to the account of `key` or was set by the operator (no `fishAgentFor`). */+export function usableFishAgent(live: LiveConfig | undefined, key: string): string | null {+ const id = live?.fishAgentId?.trim() ?? "";+ if (!AGENT_ID.test(id)) return null;+ return live?.fishAgentFor === undefined || (key.trim() !== "" && live.fishAgentFor === fishKeyPrint(key)) ? id : null;+}++/** Fish API v1: a Live 3 agent in English with the client tool `delegate` and a system prompt each session may override+ * (`createFishLiveSession` sends one), published so sessions can start. Returns its id. */+export async function setUpFishAgent(key: string, endpoint: LiveEndpoint, fetchImpl: typeof fetch = fetch): Promise<string> {+ const call = (method: string, path: string, body: unknown) => fishSetupRequest(fetchImpl, key, method, `${endpoint.apiBase}${path}`, body);+ const tool = await call("POST", "/tools", {+ name: FISH_DELEGATE_TOOL,+ tool_type: "client",+ 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,+ timeout_seconds: 30,+ });+ const toolId = typeof tool.tool_id === "string" ? tool.tool_id : "";+ if (!toolId) throw new LiveSessionError(FISH_UNEXPECTED, 502);+ const agent = await call("POST", "/agents", {+ name: "OpenMausBot Live calls",+ config: { voice: { engine: "live3", speaking_language: "en" }, tools: { enabled: true, tool_ids: [toolId] } },+ });+ const agentId = typeof agent.agent_id === "string" && AGENT_ID.test(agent.agent_id) ? agent.agent_id : "";+ if (!agentId) throw new LiveSessionError(FISH_UNEXPECTED, 502);+ await call("PATCH", `/agents/${encodeURIComponent(agentId)}`, { overrides_allowed: ["system_prompt"] });+ await call("POST", `/agents/${encodeURIComponent(agentId)}/publish`, {});+ return agentId;+}++const FISH_UNEXPECTED = "Fish Audio returned an unexpected answer. Try the call again.";++async function fishSetupRequest(fetchImpl: typeof fetch, key: string, method: string, url: string, body: unknown): Promise<Record<string, unknown>> {+ let response: Response;+ try {+ response = await fetchImpl(url, {+ method,+ headers: { authorization: `Bearer ${key.trim()}`, "content-type": "application/json" },+ redirect: "error",+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(SETUP_TIMEOUT_MS),+ });+ } catch (error) {+ const timedOut = error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError");+ throw new LiveSessionError(timedOut ? "Fish Audio did not answer in time. Try the call again." : "Could not reach Fish Audio. Check the internet connection.", 502);+ }+ if (!response.ok) {+ await response.body?.cancel().catch(() => undefined);+ throw new LiveSessionError(fishErrorMessage(response.status), response.status === 429 ? 429 : 502);+ }+ const answer = await response.json().catch(() => null) as unknown;+ return answer && typeof answer === "object" ? answer as Record<string, unknown> : {};}/** The Fish agent's system prompt for this call: the GPT-Live instructions, how this agent delegates, and the recent chat. */@@ -76,10 +136,11 @@ export interface CreateFishSessionInput {timeoutMs?: number;}-/** Fish API v1 `POST /v1/agent/sessions`. Errors carry a status and a message fit for the user: never the key, never Fish's raw body. */+/** Fish API v1 `POST /v1/agent/sessions`. Errors carry a status and a message fit for the user: never the key, never Fish's raw+ * body; `fishStatus` is Fish's own status. */export async function createFishLiveSession(input: CreateFishSessionInput): Promise<LiveFishSessionToken> {const key = input.key.trim();- if (!key) throw new LiveSessionError("Add a Fish Audio API key to use Live calls.", 409);+ if (!key) throw new LiveSessionError("Add a Fish Audio API key in Settings → API keys to use Live calls.", 409);const body = {agent_id: input.endpoint.model,// Fish refuses an override the agent's `overrides_allowed` does not list (400).@@ -100,12 +161,12 @@ export async function createFishLiveSession(input: CreateFishSessionInput): Prom}if (!response.ok) {await response.body?.cancel().catch(() => undefined);- throw new LiveSessionError(fishErrorMessage(response.status), response.status === 429 ? 429 : 502);+ throw Object.assign(new LiveSessionError(fishErrorMessage(response.status), response.status === 429 ? 429 : 502), { fishStatus: response.status });}const token = await response.json().catch(() => null) as Partial<LiveFishSessionToken> | null;if (!token || token.transport !== "livekit" || typeof token.session_id !== "string" || !token.session_id|| typeof token.token !== "string" || !token.token || typeof token.livekit_url !== "string" || !/^(wss|https):\/\//.test(token.livekit_url)) {- throw new LiveSessionError("Fish Audio returned an unexpected answer. Try the call again.", 502);+ throw new LiveSessionError(FISH_UNEXPECTED, 502);}return {transport: "livekit",@@ -135,12 +196,12 @@ export async function endFishLiveSession(sessionId: string, key: string, endpoinexport function fishErrorMessage(status: number): string {switch (status) {- case 400: return "Fish Audio rejected the call settings. In the agent's settings, allow the system prompt override.";- case 401: return "Fish Audio rejected the API key. Check the key for Live calls.";+ case 400: return "Fish Audio rejected the call settings (HTTP 400).";+ case 401: return "Fish Audio rejected the API key. Check the Fish Audio key in Settings → API keys.";case 402: return "The Fish Audio account has no credit for agent calls.";- case 403: return "This Fish Audio key may not start that agent.";- case 404: return "Fish Audio has no agent with that id. Check the agent id in Call settings.";- case 409: return "The Fish Audio agent has not been published. Publish it in Fish Audio, then call again.";+ case 403: return "This Fish Audio key may not start agent calls.";+ case 404: return "Fish Audio could not find the agent for Live calls. Try the call again.";+ case 409: return "The Fish Audio agent for Live calls is not ready yet. Try the call again in a moment.";case 422: return "Fish Audio could not use the call request (HTTP 422).";case 429: return "Fish Audio is limiting agent sessions right now. Try again in a moment.";default: return status >= 500 ? "Fish Audio had a problem starting the call. Try again in a moment." : `Fish Audio could not start the call (HTTP ${status}).`;diff --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex 06b0037896..062801d81b 100644--- a/server/live-settings.test.ts+++ b/server/live-settings.test.ts@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";import type { AppConfig } from "./config.ts";import { nestedKeyStatus } from "./key-hint.ts";import { LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_KEY } from "./live-call.ts";-import { LIVE_KEY_NEEDS_ENDPOINT, liveConfigWithEnv, liveKeyTarget, liveSavePatch, usableLiveKey, type LiveConfig } from "./live-config.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";describe("live settings", () => {@@ -93,9 +94,9 @@ describe("Live calls through Azure OpenAI", () => {});describe("Live calls through Fish Audio", () => {- const fish = { provider: "fish" as const, fishAgentId: "agent_1" };+ const fish = { provider: "fish" as const };- it("never use the OpenAI API key, or a key saved for OpenAI or Azure, as the Fish key", () => {+ it("use only the Fish Audio key, never the OpenAI API key or a key saved for OpenAI or Azure", () => {const openai = { key: "sk-openai" };for (const live of [fish, { ...fish, key: "k", keyFor: "openai" }, { ...fish, key: "k", keyFor: "azure:a.openai.azure.com" }, { ...fish, key: "old" }]) {const cfg = { live, openai } as AppConfig;@@ -104,48 +105,51 @@ describe("Live calls through Fish Audio", () => {}});- it("are ready with a key saved for Fish and a valid agent id, and report none of the key", () => {- const cfg = { live: { ...fish, key: "fish-secret", keyFor: "fish" } } as AppConfig;- expect(liveCallKey(cfg)).toEqual({ key: "fish-secret", source: "live" });- expect(liveCallEndpoint(cfg, {})).toEqual({ provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_1" });+ it("are ready with the Fish Audio key, and report none of it", () => {+ const cfg = { live: fish, tts: { fishKey: " fish-secret " } } as AppConfig;+ expect(liveCallKey(cfg)).toEqual({ key: "fish-secret", source: "fishAudio" });+ expect(liveCallEndpoint(cfg, {})).toEqual({ provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "" });expect(liveSetupProblem(cfg)).toBeNull();const settings = liveSettingsFor(cfg);- expect(settings).toMatchObject({ configured: true, keySource: "live", provider: "fish", fishAgentId: "agent_1" });+ expect(settings).toMatchObject({ configured: true, keySource: "fishAudio", provider: "fish" });expect(JSON.stringify(settings)).not.toContain("fish-secret");});- it("are not ready without a valid agent id", () => {- for (const fishAgentId of [undefined, "", "../x"]) {- const cfg = { live: { provider: "fish", fishAgentId, key: "k", keyFor: "fish" } } as AppConfig;- expect(liveCallEndpoint(cfg, {}), String(fishAgentId)).toBeNull();- expect(liveSetupProblem(cfg)).toBe(LIVE_NEEDS_FISH);- }+ it("start the agent set up for the account of the Fish Audio key, and set one up for another account", () => {+ const live = { ...fish, fishAgentId: "agent_1", fishAgentFor: fishKeyPrint("key-a") };+ expect(liveCallEndpoint({ live, tts: { fishKey: "key-a" } } as AppConfig, {})?.model).toBe("agent_1");+ expect(liveCallEndpoint({ live, tts: { fishKey: "key-b" } } as AppConfig, {})?.model).toBe("");+ expect(JSON.stringify(liveSettingsFor({ live, tts: { fishKey: "key-a" } } as AppConfig))).not.toContain("agent_1");});it("name the provider in what a call start reads, so the Fish limit sees it before setup is done", () => {- expect(liveCallSettings({ live: { provider: "fish" } } as AppConfig)).toMatchObject({ provider: "fish", endpoint: null, key: "", setupProblem: LIVE_NEEDS_FISH });+ expect(liveCallSettings({ live: { provider: "fish" } } as AppConfig)).toMatchObject({ provider: "fish", key: "", setupProblem: LIVE_NEEDS_FISH });});- it("tell a caller without the admin scope the service, not which agent", () => {- const client = liveSettingsForClient(liveSettingsFor({ live: { ...fish, key: "k", keyFor: "fish" } } as AppConfig));- expect(client).toEqual({ configured: true, keySource: "live", provider: "fish", voice: "", readTypedReplies: true, idleMinutes: 5 });- expect(JSON.stringify(client)).not.toContain("agent_1");+ it("leave a Live key saved for OpenAI usable after a switch to Fish and back", () => {+ const saved = { key: "k", keyFor: "openai" };+ expect(liveSavePatch(saved, { provider: "fish" })).toEqual({ provider: "fish" });+ expect(usableLiveKey({ ...saved, provider: "fish" })).toBe("k");+ expect(liveSavePatch({ ...fish, key: "k", keyFor: "openai" }, { provider: "openai" })).toEqual({ provider: "openai" });});- it("tie a key saved for Fish to Fish, and forget it on a switch either way", () => {- expect(liveKeyTarget(fish)).toBe("fish");- expect(liveSavePatch(fish, { key: "new" })).toEqual({ key: "new", keyFor: "fish" });- expect(liveSavePatch({ ...fish, key: "k", keyFor: "fish" }, { fishAgentId: "agent_2" })).toEqual({ fishAgentId: "agent_2" });- expect(liveSavePatch({ ...fish, key: "k", keyFor: "fish" }, { provider: "openai" })).toEqual({ provider: "openai", key: "", keyFor: "nowhere" });- expect(liveSavePatch({ key: "k", keyFor: "openai" }, { provider: "fish" })).toEqual({ provider: "fish", key: "", keyFor: "nowhere" });- expect(usableLiveKey({ ...fish, key: "k", keyFor: "fish", provider: "openai" })).toBeUndefined();+ it("read a Fish key saved as the Live key as the Fish Audio key, without replacing a saved one", () => {+ const cfg = { live: { ...fish, key: " old-fish ", keyFor: "fish" }, tts: {} } as AppConfig;+ fishKeyFromLiveKey(cfg);+ expect(cfg.tts?.fishKey).toBe("old-fish");+ const both = { live: { ...fish, key: "old-fish", keyFor: "fish" }, tts: { fishKey: "current" } } as AppConfig;+ fishKeyFromLiveKey(both);+ expect(both.tts?.fishKey).toBe("current");+ const openai = { live: { key: "sk-live", keyFor: "openai" }, tts: {} } as AppConfig;+ fishKeyFromLiveKey(openai);+ expect(openai.tts?.fishKey).toBeUndefined();+ expect(liveCallKey({ live: { ...fish, key: "old-fish", keyFor: "fish" } } as AppConfig)).toBeNull();});- it("are set up from the environment by an operator, pairing the key only when key, provider and agent are set together", () => {- const env = { OMB_OPENAI_LIVE_KEY: "operators", OMB_LIVE_PROVIDER: "fish", OMB_FISH_LIVE_AGENT_ID: " agent_9 " };- expect(liveConfigWithEnv(undefined, env)).toEqual({ key: "operators", provider: "fish", fishAgentId: "agent_9", keyFor: "fish" });- expect(liveConfigWithEnv(undefined, { ...env, OMB_FISH_LIVE_AGENT_ID: undefined }).keyFor).toBeUndefined();- expect(usableLiveKey(liveConfigWithEnv({ key: "", keyFor: "nowhere" }, env))).toBeUndefined();+ it("take an operator's agent from the environment for any key", () => {+ const live = liveConfigWithEnv({ fishAgentId: "agent_1", fishAgentFor: "abc" }, { OMB_LIVE_PROVIDER: "fish", OMB_FISH_LIVE_AGENT_ID: " agent_9 " });+ expect(live).toEqual({ provider: "fish", fishAgentId: "agent_9" });+ expect(liveConfigWithEnv({ fishAgentId: "agent_1", fishAgentFor: "abc" }, {})).toEqual({ fishAgentId: "agent_1", fishAgentFor: "abc" });});});diff --git a/server/live-settings.ts b/server/live-settings.tsindex d9dd2c88e0..8722e124c1 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -2,25 +2,31 @@ import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_FISH, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";import { liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";-import { fishLiveEndpoint } from "./live-fish.ts";+import { fishLiveEndpoint, usableFishAgent } from "./live-fish.ts";export const LIVE_IDLE_MINUTES_DEFAULT = 5;-type LiveConfig = Pick<AppConfig, "live" | "openai">;+type LiveConfig = Pick<AppConfig, "live" | "openai" | "tts">;-/** A saved Live key goes only to the provider and host it was saved for (`usableLiveKey`), and the OpenAI API key only ever to OpenAI. */+/** A saved Live key goes only to the provider and host it was saved for (`usableLiveKey`), the OpenAI API key only ever to+ * OpenAI, and the Fish Audio key only to Fish Audio. */export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySource } | null {+ if (cfg.live?.provider === "fish") {+ const fish = cfg.tts?.fishKey?.trim();+ return fish ? { key: fish, source: "fishAudio" } : null;+ }const live = usableLiveKey(cfg.live);if (live) return { key: live, source: "live" };- if (cfg.live?.provider === "azure" || cfg.live?.provider === "fish") return null;+ if (cfg.live?.provider === "azure") return null;const openai = cfg.openai?.key?.trim();return openai ? { key: openai, source: "openai" } : null;}-/** null when Azure is chosen but its endpoint or deployment is missing or not valid, or Fish Audio without a valid agent id. */+/** null when Azure is chosen but its endpoint or deployment is missing or not valid. On Fish Audio, `model` is "" until the+ * harness has set up an agent on the account of the Fish Audio key. */export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {if (cfg.live?.provider === "azure") return azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment);- if (cfg.live?.provider === "fish") return fishLiveEndpoint(cfg.live.fishAgentId, env);+ if (cfg.live?.provider === "fish") return fishLiveEndpoint(usableFishAgent(cfg.live, cfg.tts?.fishKey ?? ""), env);return openAiLiveEndpoint(env);}@@ -43,8 +49,8 @@ export function liveCallSettings(cfg: AppConfig) {return { key: liveCallKey(cfg)?.key ?? "", endpoint: liveCallEndpoint(cfg), setupProblem: liveSetupProblem(cfg), ...liveSettingsFor(cfg) };}-/** A caller without the admin scope learns which service calls use, not which Azure resource or Fish agent. */-export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeployment: _deployment, fishAgentId: _agent, ...settings }: LiveSettings): LiveSettings {+/** A caller without the admin scope learns which service calls use, not which Azure resource. */+export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeployment: _deployment, ...settings }: LiveSettings): LiveSettings {return settings;}@@ -58,7 +64,6 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {...(provider === "azure" || provider === "fish" ? { provider } : {}),...(cfg.live?.azureEndpoint ? { azureEndpoint: cfg.live.azureEndpoint } : {}),...(cfg.live?.azureDeployment ? { azureDeployment: cfg.live.azureDeployment } : {}),- ...(cfg.live?.fishAgentId ? { fishAgentId: cfg.live.fishAgentId } : {}),voice: cfg.live?.voice ?? "",readTypedReplies: cfg.live?.readTypedReplies ?? true,idleMinutes: Number.isInteger(minutes) && minutes! >= 1 && minutes! <= 60 ? minutes! : LIVE_IDLE_MINUTES_DEFAULT,diff --git a/server/routes/live.test.ts b/server/routes/live.test.tsindex 7fab696ed4..e79f4ffc39 100644--- a/server/routes/live.test.ts+++ b/server/routes/live.test.ts@@ -152,14 +152,13 @@ describe("live routes", () => {expect((await request(d, "PATCH", "/api/live/settings", { azureEndpoint: "", azureDeployment: "" })).status).toBe(200);expect(d.saved).toEqual([azure, { azureEndpoint: "", azureDeployment: "" }]);});- it("saves a Fish Audio provider and agent id, refusing an id that is not one", async () => {+ it("saves Fish Audio as the provider, and takes no agent from a request", async () => {const d = deps();- expect(await request(d, "PATCH", "/api/live/settings", { provider: "fish", fishAgentId: " agent_1 " })).toMatchObject({ status: 200, body: { live: { provider: "fish", fishAgentId: "agent_1" } } });- for (const fishAgentId of ["../x", "a b", "x".repeat(129), 7]) {- expect(await request(d, "PATCH", "/api/live/settings", { fishAgentId }), String(fishAgentId)).toMatchObject({ status: 400 });+ expect(await request(d, "PATCH", "/api/live/settings", { provider: "fish" })).toMatchObject({ status: 200, body: { live: { provider: "fish" } } });+ for (const patch of [{ fishAgentId: "agent_1" }, { fishAgentFor: "abc" }]) {+ expect(await request(d, "PATCH", "/api/live/settings", patch), JSON.stringify(patch)).toMatchObject({ status: 400 });}- expect((await request(d, "PATCH", "/api/live/settings", { fishAgentId: "" })).status).toBe(200);- expect(d.saved).toEqual([{ provider: "fish", fishAgentId: "agent_1" }, { fishAgentId: "" }]);+ expect(d.saved).toEqual([{ provider: "fish" }]);});it("saves nothing for an empty patch", async () => {diff --git a/server/routes/live.ts b/server/routes/live.tsindex e648b6c2f4..ece8a71892 100644--- a/server/routes/live.ts+++ b/server/routes/live.ts@@ -4,14 +4,14 @@ import { z } from "zod";import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveProvider, LiveSettings } from "../../shared/wire.ts";import { azureLiveDeployment, azureOpenAiRoot, LiveSessionError, MAX_SDP_BYTES } from "../live-call.ts";import { LiveCallBusyError, type LiveCallController } from "../live-call-controller.ts";-import { isFishAgentId, RELAY_POLL_MS } from "../live-fish.ts";+import { RELAY_POLL_MS } from "../live-fish.ts";import { PASS, type RouteContext, type RouteHandler } from "./table.ts";export interface LiveRouteDeps {calls: Pick<LiveCallController, "start" | "end" | "current" | "deviceRevoked">;resolveTarget(botId: string, threadId: string | undefined): { botId: string; botName: string; threadId: string } | null;settings(): LiveSettings;- saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; fishAgentId?: string; voice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;+ saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; voice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;/** A running Fish Audio call's relay, only for the token its start answered with. */fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[], from?: number): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;}@@ -47,7 +47,6 @@ const settingsBody = z.object({// "" 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(),- fishAgentId: z.string().trim().max(128).refine((id) => id === "" || isFishAgentId(id)).optional(),voice: z.string().trim().max(40).regex(/^[a-z]*$/).optional(),readTypedReplies: z.boolean().optional(),idleMinutes: z.number().int().min(1).max(60).optional(),@@ -123,7 +122,6 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {const field = parsed.error.issues[0]?.path[0];if (field === "azureEndpoint") return json(res, 400, { error: "The Azure endpoint must be the https address of an Azure OpenAI resource, like https://my-resource.openai.azure.com." });if (field === "azureDeployment") return json(res, 400, { error: "The Azure deployment name may use letters, digits, '-', '_' and '.', up to 64 characters." });- if (field === "fishAgentId") return json(res, 400, { error: "The Fish Audio agent id may use letters, digits, '-' and '_', up to 128 characters." });return json(res, 400, { error: "Those Live settings are not valid." });}if (!Object.keys(parsed.data).length) return json(res, 400, { error: "nothing to save" });diff --git a/shared/live-call-wire.ts b/shared/live-call-wire.tsindex cbed7e4f75..512843acb7 100644--- a/shared/live-call-wire.ts+++ b/shared/live-call-wire.ts@@ -46,25 +46,24 @@ export interface LiveCallRecord {}/** Who runs a Live call's voice session: OpenAI itself, a GPT-Live deployment on the user's own Azure OpenAI / Foundry- * resource, or a published Fish Audio agent (Fish Audio Live 3), whose session the client joins with Fish's SDK. */+ * resource, or a Fish Audio Live 3 agent the harness sets up on the person's Fish Audio account, whose session the client joins with Fish's SDK. */export type LiveProvider = "openai" | "azure" | "fish";-/** `live`: the key saved for Live calls only; `openai`: the OpenAI API key from Settings → API keys, used when there is no `live` key. */-export type LiveKeySource = "live" | "openai";+/** `live`: the key saved for Live calls only; `openai`: the OpenAI API key from Settings → API keys, used when there is no `live` key;+ * `fishAudio`: the Fish Audio key from Settings → API keys, the only key a Fish Audio call uses. */+export type LiveKeySource = "live" | "openai" | "fishAudio";/** 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), for Azure a valid endpoint and deployment, and for Fish Audio an agent id. */+ /** 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" or "fish" only the `live` key is used, never the OpenAI API key. */+ /** Absent means "openai". With "azure" only the `live` key is used and with "fish" only the Fish Audio 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;/** The Azure deployment of gpt-live-1; empty means "gpt-live-1". */azureDeployment?: string;- /** The published Fish Audio agent a "fish" call starts. Not a secret. */- fishAgentId?: string;voice: string;readTypedReplies: boolean;idleMinutes: number;diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsxindex ddf5589728..eb0f196b79 100644--- a/src/components/LiveCallSettings.tsx+++ b/src/components/LiveCallSettings.tsx@@ -28,6 +28,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {const azure = live.provider === "azure";const fish = live.provider === "fish";const copy = liveKeyCopy(live.provider);+ const hasKey = live.keySource === (fish ? "fishAudio" : "live");const voice = live.voice || "marin";const known = LIVE_VOICE_OPTIONS.some((option) => option.id === voice);@@ -125,7 +126,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {)}</span></div>- {live.keySource !== "live" && (azure || fish) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}+ {!hasKey && (azure || fish) && <div className="-mt-2 text-[12px] text-ink-tertiary">{t(copy.missing)}</div>}{live.keySource !== "live" && !azure && !fish && (<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>)}diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsxindex 7b53b38129..3b750e5c59 100644--- a/src/components/LiveKeyNeeded.tsx+++ b/src/components/LiveKeyNeeded.tsx@@ -17,7 +17,7 @@ export function LiveKeyNeeded() {const fish = live?.provider === "fish";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)) || fish) && live?.keySource !== "live";+ const keyForm = (azure && Boolean(live?.azureEndpoint) && live?.keySource !== "live") || (fish && live?.keySource !== "fishAudio");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" />diff --git a/src/components/LiveKeySetup.tsx b/src/components/LiveKeySetup.tsxindex 6435a1afdf..293e768cab 100644--- a/src/components/LiveKeySetup.tsx+++ b/src/components/LiveKeySetup.tsx@@ -36,8 +36,8 @@ export function LiveKeySetup({ onSaved, onSaving, locked = false, compact = falssetError(null);try {const status: ConfigStatus = window.ogb?.setCredential- ? await window.ogb.setCredential("openaiLiveKey", value)- : await api("/api/config", { method: "PUT", body: JSON.stringify({ live: { key: value } }) });+ ? await window.ogb.setCredential(fish ? "fishAudioKey" : "openaiLiveKey", value)+ : await api("/api/config", { method: "PUT", body: JSON.stringify(fish ? { tts: { fishKey: 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;diff --git a/src/components/LiveProviderSettings.tsx b/src/components/LiveProviderSettings.tsxindex b20bcc1cc2..2173a2d77c 100644--- a/src/components/LiveProviderSettings.tsx+++ b/src/components/LiveProviderSettings.tsx@@ -6,22 +6,20 @@ import type { LiveProvider, LiveSettings } from "../../shared/wire";import { Select } from "./Select";import { KEY_FIELD } from "./keys/KeyRow";-type ProviderPatch = Partial<Pick<LiveSettings, "provider" | "azureEndpoint" | "azureDeployment" | "fishAgentId">>;+type ProviderPatch = Partial<Pick<LiveSettings, "provider" | "azureEndpoint" | "azureDeployment">>;const FIELD = KEY_FIELD;-/** `locked` holds the provider, Azure endpoint and Fish agent while a key save is pending; `onSaving` reports a pending change to them. */+/** `locked` holds the provider and Azure endpoint while a key save is pending; `onSaving` reports a pending change to them. */export function LiveProviderSettings({ locked = false, onSaving }: { locked?: boolean; onSaving?: (saving: boolean) => void } = {}) {const { state, dispatch } = useStore();const live: LiveSettings = state.config?.live ?? { configured: false, voice: "", readTypedReplies: true, idleMinutes: 5 };const provider: LiveProvider = live.provider ?? "openai";const [endpoint, setEndpoint] = useState(live.azureEndpoint ?? "");const [deployment, setDeployment] = useState(live.azureDeployment ?? "");- const [agentId, setAgentId] = useState(live.fishAgentId ?? "");const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);const azureChanged = endpoint.trim() !== (live.azureEndpoint ?? "") || deployment.trim() !== (live.azureDeployment ?? "");- const agentChanged = agentId.trim() !== (live.fishAgentId ?? "");const save = async (patch: ProviderPatch) => {if (locked) return;@@ -99,37 +97,7 @@ export function LiveProviderSettings({ locked = false, onSaving }: { locked?: bo)}</form>)}- {provider === "fish" && (- <form- className="flex flex-col gap-2"- onSubmit={(event) => {- event.preventDefault();- void save({ fishAgentId: agentId.trim() });- }}- >- <label className="flex flex-col gap-1.5">- <span className="text-[13px] font-medium leading-[18px] text-ink">{t("call.live.fishAgentId")}</span>- <input- type="text"- autoComplete="off"- spellCheck={false}- value={agentId}- onChange={(event) => setAgentId(event.target.value)}- className={FIELD}- />- </label>- <div className="text-[12px] leading-4 text-ink-secondary">{t("call.live.fishHint")}</div>- {agentChanged && (- <button- type="submit"- disabled={saving || locked}- className="ui-button ui-button-md self-end rounded-full"- >- {t("common.save")}- </button>- )}- </form>- )}+ {provider === "fish" && <div className="text-[12px] leading-4 text-ink-secondary">{t("call.live.fishHint")}</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 b4b2519a71..53dbb6d498 100644--- a/src/components/keys/KeysPage.dom.test.ts+++ b/src/components/keys/KeysPage.dom.test.ts@@ -132,8 +132,8 @@ describe("the keys page", () => {expect(row("liveCalls")).not.toBeNull();});- it("with Fish Audio chosen, the Live key row asks for a required Fish key and its agent id, with no OpenAI wording", () => {- setConfig({ ...fx.config, live: { configured: false, provider: "fish", fishAgentId: "agent_1", voice: "", readTypedReplies: true, idleMinutes: 5 } });+ it("with Fish Audio chosen, the Live key row is the required Fish Audio key, with no OpenAI wording and nothing else to fill in", () => {+ setConfig({ ...fx.config, live: { configured: false, provider: "fish", voice: "", readTypedReplies: true, idleMinutes: 5 } });page();const fish = row("liveKey")!;expect(fish.textContent).toContain("Fish Audio");@@ -141,7 +141,8 @@ describe("the keys page", () => {expect(fish.textContent).not.toContain("instead of your OpenAI key");expect([...fish.querySelectorAll("input")].map((input) => input.placeholder)).not.toContain("sk-…");expect(fish.querySelector<HTMLAnchorElement>('a[href*="platform.openai.com"]')).toBeNull();- expect([...fish.querySelectorAll<HTMLInputElement>("input")].some((input) => input.value === "agent_1")).toBe(true);+ expect(fish.querySelector<HTMLAnchorElement>('a[href*="fish.audio"]')).not.toBeNull();+ expect([...fish.querySelectorAll<HTMLInputElement>("input")].every((input) => input.type === "password")).toBe(true);expect(row("liveCalls")).toBeNull();});@@ -166,8 +167,8 @@ describe("the keys page", () => {expect(host.querySelector("[data-keys-empty]")!.textContent).toBe("No keys match “zzz”.");});- it("holds the Live provider and Fish agent while a key save is pending, and the key while a provider change is", async () => {- const live = { configured: false, provider: "fish", fishAgentId: "agent_1", voice: "", readTypedReplies: true, idleMinutes: 5 };+ it("saves a Fish key as the Fish Audio key, holding the Live provider while it saves and the key while a provider change does", async () => {+ const live = { configured: false, provider: "fish", voice: "", readTypedReplies: true, idleMinutes: 5 };setConfig({ ...fx.config, live });let answer: (value: unknown) => void = () => {};fx.api.mockImplementation(() => new Promise((resolve) => { answer = resolve; }));@@ -176,14 +177,10 @@ describe("the keys page", () => {const saveKey = () => host.querySelector<HTMLInputElement>('input[type="password"]')!.closest("form")!.querySelector<HTMLButtonElement>('button[type="submit"]')!;type(host.querySelector<HTMLInputElement>('input[type="password"]')!, "fish-key");flushSync(() => saveKey().click());- expect(fx.api).toHaveBeenCalledWith("/api/config", expect.objectContaining({ method: "PUT" }));+ expect(fx.api).toHaveBeenCalledWith("/api/config", expect.objectContaining({ method: "PUT", body: JSON.stringify({ tts: { fishKey: "fish-key" } }) }));expect(provider().disabled).toBe(true);- const agentForm = [...host.querySelectorAll("form")].find((form) => !form.querySelector('input[type="password"]'))!;- type(agentForm.querySelector<HTMLInputElement>("input")!, "agent_2");- expect(agentForm.querySelector<HTMLButtonElement>('button[type="submit"]')!.disabled).toBe(true);- flushSync(() => agentForm.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })));expect(fx.api).toHaveBeenCalledTimes(1);- await answered(() => answer({ ...fx.config, live: { ...live, keySource: "live" } }));+ await answered(() => answer({ ...fx.config, live: { ...live, keySource: "fishAudio" } }));expect(provider().disabled).toBe(false);setConfig({ ...fx.config, live });diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.tsindex 4e007d623f..f71fed9a21 100644--- a/src/components/keys/key-catalog.ts+++ b/src/components/keys/key-catalog.ts@@ -216,14 +216,15 @@ export function keyEntry(id: KeyId): KeyEntry {return entry;}-/** With Azure OpenAI or Fish Audio chosen for Live calls, the row for their key is about that service: required, and no OpenAI key. */+/** With Azure OpenAI or Fish Audio chosen for Live calls, the row for their key is about that service: required, and no OpenAI+ * key. With Fish Audio it is the Fish Audio key itself, which Fish voices use too. */export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefined): KeyEntry {const entry = keyEntry(id);const provider = config?.live?.provider;if (id !== "liveKey" || (provider !== "azure" && provider !== "fish") || !entry.target) return entry;const { shape: _openAiShape, ...target } = entry.target;if (provider === "fish") {- return { ...entry, name: "Fish Audio", labelKey: "call.live.fishKeyField", purposeKey: "keys.purpose.liveKeyFish", target: { ...target, placeholder: "…", href: "https://fish.audio/app/api-keys/" } };+ return { ...entry, name: "Fish Audio", labelKey: "keys.label.fishAudio", purposeKey: "keys.purpose.liveKeyFish", target: keyEntry("fishAudio").target };}return { ...entry, name: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };}@@ -238,13 +239,13 @@ export function savedState(entry: KeyEntry, config: ConfigStatus | null | undefireturn entry.target?.saved(config) ?? entry.status?.(config) ?? { configured: false };}-/** With `config`, the row is matched as shown: the Live key row by the provider Live calls use. *//** With Azure or Fish Audio chosen, Live calls do not use the OpenAI key the Live calls row points at, so that row is hidden. */export function keyHidden(id: KeyId, config: ConfigStatus | null | undefined): boolean {const provider = config?.live?.provider;return id === "liveCalls" && (provider === "azure" || provider === "fish");}+/** With `config`, the row is matched as shown: the Live key row by the provider Live calls use. */export function keyMatches(entry: KeyEntry, query: string, config?: ConfigStatus | null): boolean {const q = query.trim().toLowerCase();if (!q) return true;diff --git a/src/locales/en.json b/src/locales/en.jsonindex f8987bfced..5934212c6e 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6750,15 +6750,14 @@"call.live.disclosureAzure": "A Live call sends your voice to your Azure OpenAI resource, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The Azure key stays on your computer.","call.live.disclosureAzureCloud": "A Live call sends your voice to your Azure OpenAI resource, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. The Azure key stays in the Cloud.","call.live.provider.fish": "Fish Audio Live 3",- "call.live.fishAgentId": "Fish Audio agent id",- "call.live.fishHint": "On Fish Audio, create an agent with the Live 3 engine and a voice, allow its system prompt to be overridden, add a client tool named delegate, publish the agent, then paste its id. Fish Audio Live 3 speaks English only. Its calls work in the desktop app and in a browser, for the owner of this computer.",+ "call.live.fishHint": "Fish Audio Live 3 speaks English only. Its calls work in the desktop app and in a browser, for the owner of this computer.","call.live.fishKey": "Fish Audio key",- "call.live.fishNeedsKey": "Add the API key of the Fish Audio account that owns the agent with Change key.",+ "call.live.fishNeedsKey": "Add your Fish Audio API key with Change key. Fish voices use the same key.","call.live.fishKeyTitle": "Live calls through Fish Audio",- "call.live.fishKeyExplain": "Paste an API key of the Fish Audio account that owns the agent. Fish Audio bills the call to that account; the bot's own work is billed as usual.",- "call.live.fishKeyField": "Fish Audio key for Live calls",+ "call.live.fishKeyExplain": "Paste a Fish Audio API key. Fish Audio bills the call to that account; the bot's own work is billed as usual. Fish voices use the same key.",+ "call.live.fishKeyField": "Fish Audio API key","call.live.fishCost": "Via Fish Audio Live 3 on your Fish Audio account, about $0.07 per minute.",- "call.live.needsFish": "Live calls through Fish Audio need a Fish Audio API key and the id of a published Fish Audio agent.",+ "call.live.needsFish": "Live calls through Fish Audio need your Fish Audio API key.","call.live.disclosureFish": "A Live call sends your voice to Fish Audio, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Fish Audio hears on to the bot. The Fish Audio key stays on your computer.","call.live.disclosureFishCloud": "A Live call sends your voice to Fish Audio, along with the chat's recent messages, the bot's answers and the details of any approval it asks for. This app passes what Fish Audio hears on to the bot. The Fish Audio key stays in the Cloud.","call.live.keyFromApiKeys": "Uses your OpenAI API key from Settings → API keys.",@@ -7891,7 +7890,7 @@"keys.purpose.liveCalls": "Live calls use the same key as OpenAI's models","keys.purpose.liveKey": "Optional. Live calls use it instead of your OpenAI key","keys.purpose.liveKeyAzure": "Required. A key of the Azure resource your Live calls use",- "keys.purpose.liveKeyFish": "Required. A Fish Audio API key for the agent your Live calls use",+ "keys.purpose.liveKeyFish": "Required. Live calls through Fish Audio use your Fish Audio 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",