Skip to content

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

feat(live): Fish Audio Live 3 as a Live call provider

whitewookie32d8f611ddd4dc
diff --git a/docs/verification/live-calls.md b/docs/verification/live-calls.md
index 43a929ca05..c4fac90e93 100644
--- a/docs/verification/live-calls.md
+++ b/docs/verification/live-calls.md
@@ -119,6 +119,63 @@ the full server with a made-up key and its `fetch` stubbed.
`server/hosted-access.test.ts` does it for a shared workspace, with no key saved,
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,
+redirects refused. Fish answers with a LiveKit token, which goes to the client
+as `transport: { type: "fish", session, relayToken }`; the client joins with
+`@fishaudio/agent-client` 1.x, which holds the microphone and the agent's
+audio. The agent's voice is its own; the Voice setting is hidden. Hanging up
+also calls `POST /v1/agent/sessions/{id}/end`. `OMB_FISH_LIVE_URL` points the
+harness 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.
+
+Fish has no server sideband. The client reports what it hears (final user
+transcripts, the agent's speaking spans, the `delegate` tool call, the end) to
+`POST /api/live/relay` with the call's random relay token, and long-polls the
+same route for the bot's answers. `FishRelay` (`server/live-fish.ts`) turns the
+reports into the GPT-Live sideband events `LiveCallController` already reads
+and the controller's appends into commands the client hands the agent: the
+answer to a pending `delegate` call as its tool result, anything later as a
+user message prefixed `[OpenMausBot]`. Every report is a strict, bounded zod
+shape; a wrong token or session answers `404`; the route needs the admin scope.
+The `delegate` tool's arguments are ignored: the request is what the client
+heard, as on GPT-Live.
+
+Because the harness hears a Fish call only through its client's reports, a
+Fish call is limited exactly like Azure (`fishLiveCallRefusal`), with the words
+`Live calls here go through Fish Audio, so only an admin or the owner of this
+server can start one.` The phone apps do not carry the Fish SDK yet, so a call
+from 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:
+
+- 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"
+(a real `FishRelay` as the sideband: heard, delegated, the bot's answer back as
+the 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`,
+`src/lib/live-call-fish.test.ts` (client relay with a fake SDK session) and
+`src/components/keys/KeysPage.dom.test.ts`. No call has been placed against
+Fish Audio's live service.
+
## User path
Start a Live call from the call button's menu, say something the bot must act
diff --git a/package.json b/package.json
index dba5dabd86..e0c9728ccd 100644
--- a/package.json
+++ b/package.json
@@ -98,6 +98,7 @@
"@codemirror/language": "6.13.1",
"@codemirror/state": "6.7.6",
"@duckdb/node-api": "1.5.6-r.1",
+ "@fishaudio/agent-client": "1.0.0",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/geist-mono": "^5.3.0",
"@fontsource-variable/inter": "^5.3.0",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 021533865e..677768e435 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -30,6 +30,9 @@ importers:
'@duckdb/node-api':
specifier: 1.5.6-r.1
version: 1.5.6-r.1
+ '@fishaudio/agent-client':
+ specifier: 1.0.0
+ version: 1.0.0(@types/[email protected])
'@fontsource-variable/geist':
specifier: ^5.3.0
version: 5.3.0
@@ -548,6 +551,9 @@ packages:
'@braintree/[email protected]':
resolution: {integrity: sha512-jigsZK+sMF/cuiB7sERuo9V7N9jx+dhmHHnQyDSVdpZwVutaBu7WvNYqMDLSgFgfB30n452TP3vjDAvFC973mA==}
+ '@bufbuild/[email protected]':
+ resolution: {integrity: sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==}
+
'@chevrotain/[email protected]':
resolution: {integrity: sha512-bA9dvWlhAUcHkNwU+8w9yiUxJPlj/Lm3VqS7MD+NbIR/7LmpNLuK/AWNFdCo/T3SK5ND0/UHf3IJvl/Jn/i6yg==}
@@ -1094,6 +1100,14 @@ packages:
cpu: [x64]
os: [win32]
+ '@fishaudio/[email protected]':
+ resolution: {integrity: sha512-h3vllj5VYItMMb5aS2PkwKXeqj0TCWLuMnRo3CFPowUUmFGtw05f2jNzla9PHSYZc/aHKSZj9LEZBH1CwAGzDA==}
+ engines: {node: '>=18'}
+
+ '@fishaudio/[email protected]':
+ resolution: {integrity: sha512-ukXXVVUxM+qC+e/A99rNnqBpUSlW85KG2V//ds50SeoPvJevmPggZH69W8X+Fm7SxfiBG1xaEPEVJjSsrlaTiw==}
+ engines: {node: '>=18'}
+
'@floating-ui/[email protected]':
resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}
@@ -1528,6 +1542,12 @@ packages:
resolution: {integrity: sha512-UwgZcl1R66H2hDzBrA7kWyYmX6s8p5TQ+e/t7CuvgCtBEPxbEPaHYHu+pJBvTvDotEJpuQkJjbXuHiw5Cixxgw==}
+ '@livekit/[email protected]':
+ resolution: {integrity: sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw==}
+
+ '@livekit/[email protected]':
+ resolution: {integrity: sha512-X8DxKlNbzk6Lh+v630+mjdFHSotdAFwIyzxSRSUql2DbTxCnlpa7JsvFGc6Na3mXiex2OFh0iiQtWwOBP0rIYA==}
+
'@malept/[email protected]':
resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}
engines: {node: '>= 12.13.0'}
@@ -2355,6 +2375,9 @@ packages:
resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-mUMZLK3NvwRLcAAT9qmcK+9p7tpU2FHdDsntR3YI4+GY88XrgG4XiE7u1Q2LAN2/FZOz/tdMDC3GQCR4T8nFuw==}
+
resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==}
@@ -3440,6 +3463,10 @@ packages:
resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}
+ resolution: {integrity: sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==}
+ engines: {node: '>=0.8.x'}
+
resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==}
engines: {node: '>=18.0.0'}
@@ -4046,6 +4073,11 @@ packages:
resolution: {integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==}
+ resolution: {integrity: sha512-j9Kg86nJjBjNFUD+ukp2jwMCGa0k+YD5gU//RzAM+ZY3pbG631QCte7fQjwqWMmtBzhDJL9nKYuOLMv/9IbAxg==}
+ peerDependencies:
+ '@types/dom-mediacapture-record': ^1
+
resolution: {integrity: sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A==}
@@ -4059,6 +4091,10 @@ packages:
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
+ resolution: {integrity: sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==}
+ engines: {node: '>= 0.6.0'}
+
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
@@ -4087,6 +4123,10 @@ packages:
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0
+ resolution: {integrity: sha512-0Xkgs8NeBvO2hW6bjJT8ewLWrMfh1haMPstaghpASWjXkLjRhtDiaJG1Kb7mslaOHxZYxpH7PIjpmirRVYbMMA==}
+ engines: {node: '>=22.22'}
+
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -4816,6 +4856,9 @@ packages:
resolution: {integrity: sha512-PdhdWy89SiZogBLaw42zdeqtRJ//zFd2PgQavcICDUgJT5oW10QCRKbJ6bg4r0/UY2M6BWd5tkxuGFRvCkgfHQ==}
+ resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==}
+
resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==}
@@ -4839,6 +4882,13 @@ packages:
resolution: {integrity: sha512-49oNpRjWRvnU8NyGVmUaYG4jtTkNonFZI86MmGRDqBphEK2EXT9gdEUoQPZhuBM8yWHxCWbobltqYO5M4XrUvQ==}
+ resolution: {integrity: sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw==}
+ hasBin: true
+
+ resolution: {integrity: sha512-UYuY3JFaVa7Zc+rxxi8iblwD7mdloGxCzMEQIJPcCLiHKjjqMqLsruMkI+emgnYARkfHk4o7seEETABc4bwokg==}
+
resolution: {integrity: sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==}
@@ -5132,6 +5182,9 @@ packages:
resolution: {integrity: sha512-meKuifc33Pccx0O6PdIzYMq3Og8zvP4TIi/a+Bw3AEMZMxOD0+RHGQvpglEe6Zdy3wZ8nqn/j95h8LUZLk/6Hg==}
+ resolution: {integrity: sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==}
+
resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}
engines: {node: '>=14.17'}
@@ -5468,6 +5521,10 @@ packages:
resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==}
+ resolution: {integrity: sha512-CHbl2ZQbxx164IgWRgzJno4hWtM4tFbRam1QfI3Yxhs3w/DvqluVxVWeXs3oL5/fbGkSNLKo0Ty5MgUWceNhog==}
+ engines: {node: '>=6.0.0', npm: '>=3.10.0'}
+
resolution: {integrity: sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==}
engines: {node: '>=12'}
@@ -5834,6 +5891,8 @@ snapshots:
'@braintree/[email protected]': {}
+ '@bufbuild/[email protected]': {}
+
'@chevrotain/[email protected]':
dependencies:
'@chevrotain/gast': 13.2.0
@@ -6280,6 +6339,15 @@ snapshots:
'@esbuild/[email protected]':
optional: true
+ '@fishaudio/[email protected](@types/[email protected])':
+ dependencies:
+ '@fishaudio/agent-protocol': 1.0.0
+ livekit-client: 2.23.0(@types/[email protected])
+ transitivePeerDependencies:
+ - '@types/dom-mediacapture-record'
+
+ '@fishaudio/[email protected]': {}
+
'@floating-ui/[email protected]':
dependencies:
'@floating-ui/utils': 0.2.12
@@ -6611,6 +6679,12 @@ snapshots:
dependencies:
'@lezer/common': 1.5.3
+ '@livekit/[email protected]': {}
+
+ '@livekit/[email protected]':
+ dependencies:
+ '@bufbuild/protobuf': 1.10.1
+
'@malept/[email protected]':
dependencies:
cross-spawn: 7.0.6
@@ -7291,6 +7365,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/estree': 1.0.9
@@ -8439,6 +8515,8 @@ snapshots:
dependencies:
'@types/estree': 1.0.9
+
@@ -9091,6 +9169,20 @@ snapshots:
dependencies:
uc.micro: 2.1.0
+ dependencies:
+ '@livekit/mutex': 1.1.1
+ '@livekit/protocol': 1.52.1
+ '@types/dom-mediacapture-record': 1.0.22
+ events: 3.3.0
+ jose: 6.2.10
+ loglevel: 1.9.2
+ machina: 7.0.1
+ sdp-transform: 2.15.0
+ tslib: 2.8.1
+ typed-emitter: 2.1.0
+ webrtc-adapter: 9.0.6
+
@@ -9099,6 +9191,8 @@ snapshots:
+
@@ -9123,6 +9217,8 @@ snapshots:
dependencies:
react: 19.2.8
+
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -10284,6 +10380,11 @@ snapshots:
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
@@ -10302,6 +10403,10 @@ snapshots:
dependencies:
compute-scroll-into-view: 3.1.1
+
+
dependencies:
parseley: 0.13.1
@@ -10627,6 +10732,10 @@ snapshots:
+ optionalDependencies:
+ rxjs: 7.8.2
+
@@ -11077,6 +11186,10 @@ snapshots:
asn1js: 3.0.10
tslib: 2.8.1
+ dependencies:
+ sdp: 3.2.3
+
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 43f59405bb..b5ffcebd89 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -36,7 +36,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_DEEPSEEK_API_KEY", "OMB_DESKTOP_LAUNCH_ID", "OMB_DESKTOP_PARENT", "OMB_DEVS_STATUS_MS",
"OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_ANNOUNCEMENTS", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE",
"OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
- "OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FLEET_SOCKET", "OMB_GATE_",
+ "OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FISH_LIVE_AGENT_ID", "OMB_FISH_LIVE_URL", "OMB_FLEET_SOCKET", "OMB_GATE_",
"OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS",
"OMB_GREENFERENCE_API_KEY", "OMB_GROQ_API_KEY", "OMB_HELPER_INSTANCE", "OMB_HELPER_MODEL", "OMB_HOOKS", "OMB_HOOK_",
"OMB_HOSTED_", "OMB_HOSTED_MODELS", "OMB_HOSTED_MODEL_TOKEN", "OMB_HOSTED_MODEL_URL", "OMB_INSTALLATION_CREDENTIAL",
diff --git a/server/index.ts b/server/index.ts
index a8e413e942..b878baaa3b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -321,7 +321,8 @@ import { createDecider, deciderReady, describeDecider } from "./decider/index.ts
import { createStopLineRoutes } from "./routes/stop-line.ts"; import { decideRoomResponder } from "./decider/room-routing.ts"; import { roomRoutingInput } from "./host/room-routing-input.ts";
import { createLiveSession, liveAttachUrl, liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";
import { LiveCallController, LiveCallSignedOutError, openLiveSocket } from "./live-call-controller.ts";
-import { liveCallSettings, liveSettingsFor, liveSettingsForClient, saveLiveSettings } from "./live-settings.ts"; import { azureLiveCallRefusal, liveScopeRefusal } from "./live-access.ts";
+import { createFishLiveSession, endFishLiveSession, FishRelays } from "./live-fish.ts";
+import { liveCallSettings, liveSettingsFor, liveSettingsForClient, saveLiveSettings } from "./live-settings.ts"; import { azureLiveCallRefusal, fishLiveCallRefusal, liveScopeRefusal } from "./live-access.ts";
import { recordLiveCall, spokenLineFields, titleLiveCall } from "./live-call-record.ts"; import { noteGroupTurn, turnsSince } from "./room-round-turns.ts";
import { narrateTool, toUtterances } from "./tts/speech-text.ts";
import { createTtsRoutes } from "./routes/tts.ts";
@@ -12462,6 +12463,7 @@ function liveCallTitle(botId: string, threadId: string, excerpt: string): Promis
const gate = threadTitleGate(bot);
return gate.ok ? generateThreadTitle(gate.instance, excerpt, "call") : null;
}
+const fishRelays = new FishRelays();
const liveCalls = new LiveCallController({
store,
send: async ({ auth, botId, threadId, text, callId }) => {
@@ -12495,9 +12497,15 @@ const liveCalls = new LiveCallController({
broadcast: (frame) => broadcast(frame, { adminOnly: true }),
settings: () => liveCallSettings(cfg),
azureRefusal: (auth) => azureLiveCallRefusal(auth, { othersOnLoopback: adminActivityRecording() }),
- createSession: ({ key, endpoint, sdp, botId, threadId, voice }) => createLiveSession({ key, endpoint, sdp, voice, bot: liveBotFor(botId), history: liveHistoryFor(threadId), cloudHome: Boolean(CLOUD_HOME) }),
- openSocket: openLiveSocket,
- attachUrl: (sessionId, endpoint) => liveAttachUrl(sessionId, endpoint),
+ fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: adminActivityRecording() }),
+ createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {
+ if (endpoint.provider !== "fish") return createLiveSession({ key, endpoint, sdp, voice, bot: liveBotFor(botId), history: liveHistoryFor(threadId), cloudHome: Boolean(CLOUD_HOME) });
+ const session = await createFishLiveSession({ key, endpoint, bot: liveBotFor(botId), history: liveHistoryFor(threadId), cloudHome: Boolean(CLOUD_HOME) });
+ const { token } = fishRelays.open(session.session_id, () => endFishLiveSession(session.session_id, key, endpoint));
+ return { sessionId: session.session_id, fish: { type: "fish", session, relayToken: token } };
+ },
+ openSocket: (url, key, endpoint) => endpoint.provider === "fish" ? fishRelays.socket(url) : openLiveSocket(url, key, endpoint),
+ attachUrl: (sessionId, endpoint) => endpoint.provider === "fish" ? sessionId : liveAttachUrl(sessionId, endpoint),
speakable: (text) => toUtterances(text),
// One "call" row per call: its id, times and length, never anything said on it.
recordCall: (input) => {
@@ -12535,6 +12543,7 @@ ROUTES.push(createLiveRoutes({
return { botId: bot.id, botName: bot.name, threadId: target };
},
settings: () => liveSettingsFor(cfg),
+ fishRelay: (sessionId, token) => fishRelays.find(sessionId, token),
saveSettings: async (patch) => {
if (providerConfigBusy) throw Object.assign(new Error("Settings are already being updated. Try again in a moment."), { status: 409 });
saveLiveSettings(cfg, patch);
diff --git a/server/live-access.test.ts b/server/live-access.test.ts
index ce8e9c4641..3aa67c4a39 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, LIVE_AZURE_REFUSAL, liveScopeRefusal } from "./live-access.ts";
+import { azureLiveCallRefusal, fishLiveCallRefusal, LIVE_AZURE_REFUSAL, LIVE_FISH_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" }
+interface Place { resolve?: Partial<ResolveOptions>; othersOnLoopback?: boolean; provider?: "azure" | "openai" | "fish" }
/** "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 refusal = azureLiveCallRefusal(auth, { othersOnLoopback: place.othersOnLoopback ?? false });
+ const refuse = place.provider === "fish" ? fishLiveCallRefusal : azureLiveCallRefusal;
+ const refusal = refuse(auth, { othersOnLoopback: place.othersOnLoopback ?? false });
return refusal ? `limit: ${refusal}` : "gets a call";
}
@@ -175,10 +176,32 @@ describe("the words for a session without the admin scope", () => {
expect(liveScopeRefusal({ live: { provider: "azure" } }, "GET", "/api/live/call")).toBeNull();
expect(liveScopeRefusal({ live: { provider: "azure" } }, "PATCH", "/api/live/settings")).toBeNull();
expect(liveScopeRefusal({}, "POST", LIVE)).toBeNull();
+ expect(liveScopeRefusal({ live: { provider: "fish" } }, "POST", LIVE)).toBe(LIVE_FISH_REFUSAL);
+ expect(liveScopeRefusal({ live: { provider: "fish" } }, "POST", "/api/live/relay")).toBeNull();
});
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"]] as const) {
+ 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) {
expect(requiredScope(method, path), `${method} ${path}`).toBe("admin");
}
});
});
+
+describe("a Fish Audio Live call", () => {
+ const FISH = { provider: "fish" as const };
+ const TEAM = { ...FISH, ...SERVICE, othersOnLoopback: true };
+
+ it("goes to the desktop app's own window, the owner, and a team admin, as on Azure", () => {
+ expect(verdict({ ...LOCAL, "x-openmausbot-desktop-owner": "desktop-secret" }, { ...FISH, resolve: DESKTOP })).toBe(CALL);
+ expect(verdict(LOCAL, FISH)).toBe(CALL);
+ expect(verdict(device(["admin", "client"]), FISH)).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"]), FISH)).toBe(`sign-in gate 403: ${LIVE_FISH_REFUSAL}`);
+ expect(verdict(teamMember("member"), TEAM)).toBe(`sign-in gate 403: ${LIVE_FISH_REFUSAL}`);
+ expect(verdict(LOCAL, { ...FISH, othersOnLoopback: true })).toBe(`limit: ${LIVE_FISH_REFUSAL}`);
+ const unknown = { kind: "something-new", scopes: ["admin", "client"] } as unknown as RequestAuth;
+ expect(fishLiveCallRefusal(unknown, { othersOnLoopback: false })).toBe(LIVE_FISH_REFUSAL);
+ });
+});
diff --git a/server/live-access.ts b/server/live-access.ts
index 75cfb8c1f4..b243e86c09 100644
--- a/server/live-access.ts
+++ b/server/live-access.ts
@@ -1,8 +1,10 @@
-// Who may hold a Live call through Azure OpenAI. LIVE_DATA_CHANNEL in live-call.ts says why it is limited.
+// Who may hold a Live call through Azure OpenAI or Fish Audio. LIVE_DATA_CHANNEL in live-call.ts says why Azure is limited;
+// on Fish Audio the harness hears the call only through its client's own reports (FishRelay in live-fish.ts).
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 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
@@ -12,14 +14,19 @@ export interface LiveCallPlace {
}
/** Null only for an admin or the single owner. A caller this does not recognise is refused. */
-export function azureLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): string | null {
- if (!auth.scopes.includes("admin")) return LIVE_AZURE_REFUSAL;
- if (auth.kind === "session") return auth.session.teamRole === "member" || auth.session.moveIn ? LIVE_AZURE_REFUSAL : null;
- if (auth.kind === "loopback") return auth.trust === "service" || place.othersOnLoopback ? LIVE_AZURE_REFUSAL : null;
- return LIVE_AZURE_REFUSAL;
+export function azureLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace, refusal: string = LIVE_AZURE_REFUSAL): string | null {
+ if (!auth.scopes.includes("admin")) return refusal;
+ if (auth.kind === "session") return auth.session.teamRole === "member" || auth.session.moveIn ? refusal : null;
+ if (auth.kind === "loopback") return auth.trust === "service" || place.othersOnLoopback ? refusal : null;
+ return refusal;
+}
+
+export function fishLiveCallRefusal(auth: RequestAuth, place: LiveCallPlace): string | null {
+ return azureLiveCallRefusal(auth, place, LIVE_FISH_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 {
- return cfg.live?.provider === "azure" && method.toUpperCase() === "POST" && path === "/api/live/session" ? LIVE_AZURE_REFUSAL : null;
+ if (method.toUpperCase() !== "POST" || path !== "/api/live/session") return null;
+ return cfg.live?.provider === "azure" ? LIVE_AZURE_REFUSAL : cfg.live?.provider === "fish" ? LIVE_FISH_REFUSAL : null;
}
diff --git a/server/live-call-controller.test.ts b/server/live-call-controller.test.ts
index 52fd05e8ca..20c86b1062 100644
--- a/server/live-call-controller.test.ts
+++ b/server/live-call-controller.test.ts
@@ -1,11 +1,13 @@
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, GOODBYE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
- LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
+ ATTACH_TIMEOUT_MS, CLOSE_TIMEOUT_MS, CONSENT_SETTLE_MS, DELEGATION_SETTLE_MS, FISH_ATTACH_TIMEOUT_MS, GOODBYE_MS, IDLE_CHECK_MS, PROGRESS_INTERVAL_MS,
+ LIVE_FISH_NEEDS_APP, LiveCallBusyError, LiveCallController, LiveCallSignedOutError, type LiveActivity, type LiveCallDeps, type LiveSocket,
} from "./live-call-controller.ts";
import { LIVE_COPY } from "../shared/live-approval.ts";
import { LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY, LiveSessionError, type LiveEndpoint } from "./live-call.ts";
+import { FishRelays, FISH_AGENT_VOICE } from "./live-fish.ts";
+import type { LiveFishSessionToken } from "../shared/wire.ts";
import type { RequestAuth } from "./request-auth.ts";
import type { Message, StoreChange } from "./store.ts";
@@ -50,6 +52,7 @@ function setup(overrides: Partial<LiveCallDeps> = {}) {
broadcast: (frame) => frames.push(frame.call),
settings: () => settings,
azureRefusal: vi.fn(() => null),
+ fishRefusal: 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`,
@@ -187,6 +190,121 @@ describe("LiveCallController lifecycle", () => {
});
+ describe("with Fish Audio chosen", () => {
+ const FISH: LiveEndpoint = { provider: "fish", apiBase: "https://api.fish.audio/v1/agent", model: "agent_1" };
+ const REFUSED = "only an admin, in these words";
+ const member: RequestAuth = { kind: "loopback", scopes: ["client"], trust: "service" };
+ const TOKEN: LiveFishSessionToken = {
+ transport: "livekit", session_id: "fish_1", expires_at: "2026-11-11T00:00:00Z", max_duration_seconds: 900, livekit_url: "wss://lk.example", token: "jwt",
+ };
+ const fish = (overrides: Partial<LiveCallDeps> = {}) => {
+ const relays = new FishRelays();
+ const endSession = vi.fn(async () => true);
+ let relayToken = "";
+ const t = setup({
+ createSession: vi.fn(async () => {
+ relayToken = relays.open(TOKEN.session_id, endSession).token;
+ return { sessionId: TOKEN.session_id, fish: { type: "fish" as const, session: TOKEN, relayToken } };
+ }),
+ openSocket: (url) => relays.socket(url),
+ attachUrl: (id) => id,
+ ...overrides,
+ });
+ t.settings.endpoint = FISH;
+ t.settings.provider = "fish";
+ const relay = () => relays.find(TOKEN.session_id, relayToken)!;
+ return { ...t, relays, endSession, relay };
+ };
+
+ it("asks who is calling, starts with no SDP, and answers with Fish's session and the relay's token", async () => {
+ const t = fish();
+ const started = await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ expect(t.deps.fishRefusal).toHaveBeenCalledWith(owner);
+ expect(t.deps.azureRefusal).not.toHaveBeenCalled();
+ expect(t.deps.createSession).toHaveBeenCalledWith(expect.objectContaining({ endpoint: FISH, sdp: "", voice: FISH_AGENT_VOICE }));
+ expect(started.sdp).toBeUndefined();
+ expect(started.fish).toEqual({ type: "fish", session: TOKEN, relayToken: expect.stringMatching(/^[\w-]{43}$/) });
+ expect(started.call).toMatchObject({ status: "connecting", voice: FISH_AGENT_VOICE });
+ });
+
+ it("refuses with the reason as a 403 before any session is taken, even while Fish is not set up", async () => {
+ const t = fish({ fishRefusal: () => REFUSED });
+ t.settings.endpoint = null;
+ await expect(t.controller.start({ auth: member, ...BOT, client: "web" })).rejects.toMatchObject({ status: 403, message: REFUSED });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ expect(t.logs.join("\n")).toContain("[live] call refused bot=bot1 client=web provider=fish");
+ });
+
+ it("sends a phone to the desktop app or a browser", async () => {
+ for (const client of ["ios", "android"] as const) {
+ const t = fish();
+ await expect(t.controller.start({ auth: owner, ...BOT, client })).rejects.toMatchObject({ status: 400, message: LIVE_FISH_NEEDS_APP });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ }
+ });
+
+ it("never calls Fish with a key saved for another provider", async () => {
+ const t = fish();
+ t.settings.endpoint = ENDPOINT;
+ await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 409 });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ });
+
+ it("waits longer for the client to join, then gives up and ends Fish's session", async () => {
+ const t = fish();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ await vi.advanceTimersByTimeAsync(ATTACH_TIMEOUT_MS + 1);
+ expect(t.controller.current()?.status).toBe("connecting");
+ await vi.advanceTimersByTimeAsync(FISH_ATTACH_TIMEOUT_MS - ATTACH_TIMEOUT_MS);
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "sideband-lost", error: "The call could not connect to Fish Audio." });
+ expect(t.endSession).toHaveBeenCalledOnce();
+ });
+
+ it("takes a request heard by the client to the bot and returns the answer to the delegate call", async () => {
+ const t = fish();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ const callId = t.controller.current()!.callId;
+ t.relay().receive([{ type: "connected" }]);
+ expect(t.controller.current()?.status).toBe("live");
+ t.relay().receive([{ type: "heard", text: "check my mail", startMs: 100, endMs: 900 }, { type: "delegate", id: "call_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: "call_1" });
+ });
+
+ it("on End tells the client to hang up, ends Fish's session and records the call", async () => {
+ const t = fish();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ const relay = t.relay();
+ relay.receive([{ type: "connected" }]);
+ const waiting = relay.poll(10_000);
+ await t.controller.end(t.controller.current()!.callId);
+ expect(await waiting).toMatchObject({ commands: [{ type: "close" }] });
+ expect(t.endSession).toHaveBeenCalledOnce();
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended", endReason: "hung-up" });
+ expect(t.relays.find(TOKEN.session_id, "x")).toBeNull();
+ });
+
+ it("ends the call when Fish ends the session", async () => {
+ const t = fish();
+ await t.controller.start({ auth: owner, ...BOT, client: "web" });
+ t.relay().receive([{ type: "connected" }, { type: "ended", reason: "conversation_timeout" }]);
+ expect(t.frames.at(-1)).toMatchObject({ status: "ended" });
+ expect(t.controller.current()).toBeNull();
+ });
+ });
+
+ it("refuses a call through OpenAI or Azure that brings no audio offer, before any session", async () => {
+ const t = setup();
+ await expect(t.controller.start({ auth: owner, ...BOT, client: "web" })).rejects.toMatchObject({ status: 400 });
+ expect(t.deps.createSession).not.toHaveBeenCalled();
+ expect(t.controller.current()).toBeNull();
+ });
+
it("asks nothing of the Azure limit for a call through OpenAI", async () => {
const t = setup({ azureRefusal: vi.fn(() => "never asked") });
await t.controller.start({ auth: owner, ...BOT, client: "desktop", sdp: "a" });
diff --git a/server/live-call-controller.ts b/server/live-call-controller.ts
index 24a2547f9f..16516a6438 100644
--- a/server/live-call-controller.ts
+++ b/server/live-call-controller.ts
@@ -6,7 +6,8 @@ import {
} from "../shared/live-approval.ts";
import { clampAppend, commentaryChunks, LiveTranscript } from "../shared/live-call.ts";
import { signInWaits } from "../shared/sign-in-request.ts";
-import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveProvider } from "../shared/wire.ts";
+import type { LiveCallRecord, LiveCallState, LiveClient, LiveEndReason, LiveFishTransport, 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";
import type { Message, StoreChange } from "./store.ts";
@@ -15,6 +16,8 @@ export const DELEGATION_SETTLE_MS = 700;
export const CONSENT_SETTLE_MS = 1_200;
export const PROGRESS_INTERVAL_MS = 4_000;
export const ATTACH_TIMEOUT_MS = 10_000;
+/** Fish's client asks for the microphone only after the session exists, so its first report can wait on a permission prompt. */
+export const FISH_ATTACH_TIMEOUT_MS = 25_000;
export const CLOSE_TIMEOUT_MS = 5_000;
export const IDLE_CHECK_MS = 15_000;
export const STATUS_INTERVAL_MS = 30_000;
@@ -37,6 +40,9 @@ export interface LiveSocket {
}
export type LiveActivity = "idle" | "working" | "waiting";
+export type LiveSessionAnswer = { sessionId: string; sdp: string } | { sessionId: string; fish: LiveFishTransport };
+export type LiveCallStarted = { call: LiveCallState; sdp: string; fish?: undefined } | { call: LiveCallState; sdp?: undefined; fish: LiveFishTransport };
+export 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 type LiveSendResult = { kind: "started" | "steered"; messageId: string } | { kind: "queued"; queueId: string };
export type LiveRespondResult = { ok: true } | { ok: false; error: string };
@@ -53,7 +59,10 @@ export interface LiveCallDeps {
settings(): { key: string; endpoint: LiveEndpoint | null; setupProblem?: string | null; provider?: LiveProvider; voice: string; readTypedReplies: boolean; idleMinutes: number };
/** Why this caller may not hold a call through Azure OpenAI; null when they may. Required, so no wiring can leave it out. */
azureRefusal(auth: RequestAuth): string | null;
- createSession(input: { key: string; endpoint: LiveEndpoint; sdp: string; botId: string; threadId: string; voice: string }): Promise<{ sessionId: string; sdp: string }>;
+ /** The same for Fish Audio, where the harness hears the call only through its client's reports. Required too. */
+ fishRefusal(auth: RequestAuth): string | null;
+ /** `sdp` is "" on Fish Audio, which answers with `fish` instead of an SDP answer. */
+ 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;
speakable(text: string): string[];
@@ -156,28 +165,34 @@ export class LiveCallController {
return this.call && this.call.state.status !== "ended" ? { ...this.call.state } : null;
}
- async start(input: { auth: RequestAuth; device?: string; botId: string; botName: string; threadId: string; client: LiveClient; sdp: string }): Promise<{ call: LiveCallState; sdp: string }> {
+ 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 up.
- if (settings.provider === "azure" || settings.endpoint?.provider === "azure") {
- const refusal = this.deps.azureRefusal(input.auth);
+ // First: someone refused here is not told about a running call, or sent to set Azure or Fish Audio up.
+ const limited = settings.provider === "azure" || settings.endpoint?.provider === "azure" ? "azure"
+ : settings.provider === "fish" || settings.endpoint?.provider === "fish" ? "fish" : null;
+ if (limited) {
+ const refusal = limited === "azure" ? this.deps.azureRefusal(input.auth) : this.deps.fishRefusal(input.auth);
if (refusal) {
- this.deps.log(`[live] call refused bot=${input.botId} client=${input.client} provider=azure`);
+ this.deps.log(`[live] call refused bot=${input.botId} client=${input.client} provider=${limited}`);
throw new LiveSessionError(refusal, 403);
}
}
+ const fish = limited === "fish";
+ if (fish && (input.client === "ios" || input.client === "android")) throw new LiveSessionError(LIVE_FISH_NEEDS_APP, 400);
+ if (!fish && !input.sdp) throw new LiveSessionError("The call request was not valid.", 400);
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);
- const voice = liveVoice(settings.voice);
+ if (fish !== (endpoint.provider === "fish")) throw new LiveSessionError(settings.setupProblem || LIVE_NEEDS_KEY, 409);
+ const voice = fish ? FISH_AGENT_VOICE : liveVoice(settings.voice);
const call = this.newCall(input, key, endpoint, voice);
// Taken before the first await: a second start in the same tick is refused.
this.call = call;
- let session: { sessionId: string; sdp: string };
+ let session: LiveSessionAnswer;
try {
- session = await this.deps.createSession({ key, endpoint, sdp: input.sdp, botId: input.botId, threadId: input.threadId, voice });
+ session = await this.deps.createSession({ key, endpoint, sdp: fish ? "" : input.sdp ?? "", botId: input.botId, threadId: input.threadId, voice });
} catch (error) {
if (this.call === call) this.call = null;
this.deps.log(`[live] call failed bot=${input.botId} client=${input.client} status=${error instanceof LiveSessionError ? error.status : "error"}`);
@@ -206,7 +221,7 @@ export class LiveCallController {
if (!sidebandOpened) this.closeOrphan(session.sessionId, key, endpoint);
throw error;
}
- return { call: { ...call.state }, sdp: session.sdp };
+ return "fish" in session ? { call: { ...call.state }, fish: session.fish } : { call: { ...call.state }, sdp: session.sdp };
}
async end(callId: string): Promise<LiveCallState | null> {
@@ -296,7 +311,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)}.`);
- }, ATTACH_TIMEOUT_MS);
+ }, call.endpoint.provider === "fish" ? FISH_ATTACH_TIMEOUT_MS : ATTACH_TIMEOUT_MS);
socket.onopen = () => {
call.attached = true;
this.clear(call, attachTimer);
diff --git a/server/live-call.ts b/server/live-call.ts
index 4db821329c..b5e6573603 100644
--- a/server/live-call.ts
+++ b/server/live-call.ts
@@ -9,6 +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.";
/** 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
@@ -44,12 +45,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, or the Azure deployment name. */
+ /** The OpenAI model id, the Azure deployment name, or the Fish Audio agent id. */
model: string;
}
export function liveProviderName(provider: LiveProvider): string {
- return provider === "azure" ? "Azure OpenAI" : "OpenAI";
+ return provider === "azure" ? "Azure OpenAI" : provider === "fish" ? "Fish Audio" : "OpenAI";
}
/** Only a loopback http URL is accepted, read at call time. */
@@ -98,7 +99,7 @@ export function liveAttachUrl(sessionId: string, endpoint: LiveEndpoint = openAi
return `${endpoint.apiBase.replace(/^http/, "ws")}/live/sessions/${encodeURIComponent(sessionId)}/attach`;
}
-/** Azure OpenAI takes a resource key in `api-key`; OpenAI takes a bearer token. */
+/** Azure OpenAI takes a resource key in `api-key`; OpenAI and Fish Audio take a bearer token. */
export function liveAuthHeaders(provider: LiveProvider, key: string): Record<string, string> {
return provider === "azure" ? { "api-key": key } : { authorization: `Bearer ${key}` };
}
diff --git a/server/live-config.ts b/server/live-config.ts
index 4ec8d893ef..6f09294f7b 100644
--- a/server/live-config.ts
+++ b/server/live-config.ts
@@ -4,13 +4,14 @@ 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. `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. `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 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. */
export const liveConfigSchema = z.object({
key: z.string().optional(),
keyFor: z.string().max(300).optional(),
- provider: z.enum(["openai", "azure"]).optional(),
+ provider: z.enum(["openai", "azure", "fish"]).optional(),
azureEndpoint: z.string().trim().max(300).optional(),
azureDeployment: z.string().trim().max(64).optional(),
+ fishAgentId: z.string().trim().max(128).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(),
@@ -19,16 +20,18 @@ export const liveConfigSchema = z.object({
export interface LiveConfig {
key?: string;
keyFor?: string;
- provider?: "openai" | "azure";
+ provider?: "openai" | "azure" | "fish";
azureEndpoint?: string;
azureDeployment?: string;
+ fishAgentId?: string;
voice?: string;
readTypedReplies?: boolean;
idleMinutes?: number;
}
-/** Where a key saved now may go: "openai", or "azure:<host>"; null while Azure is chosen with no endpoint to tie it to. */
+/** 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. */
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();
@@ -67,12 +70,14 @@ export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.Proc
next.key = envKey;
}
const provider = env.OMB_LIVE_PROVIDER?.trim().toLowerCase();
- if (provider === "openai" || provider === "azure") next.provider = provider;
+ if (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();
// 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;
}
@@ -82,5 +87,6 @@ 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"],
];
}
diff --git a/server/live-fish.test.ts b/server/live-fish.test.ts
new file mode 100644
index 0000000000..ca22c2d7f9
--- /dev/null
+++ b/server/live-fish.test.ts
@@ -0,0 +1,218 @@
+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,
+} from "./live-fish.ts";
+
+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",
+};
+
+function fakeFetch(status: number, body: unknown) {
+ return vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => new Response(status === 204 ? null : JSON.stringify(body), { status }));
+}
+
+describe("the Fish Audio endpoint", () => {
+ it("is Fish's API unless a loopback http override is set", () => {
+ expect(fishLiveBaseUrl({})).toBe("https://api.fish.audio");
+ expect(fishLiveBaseUrl({ OMB_FISH_LIVE_URL: "http://127.0.0.1:4555" })).toBe("http://127.0.0.1:4555");
+ for (const url of ["https://evil.example", "http://127.0.0.1.evil.example:80", "http://localhost:80", "http://127.0.0.1:80/x"]) {
+ expect(fishLiveBaseUrl({ OMB_FISH_LIVE_URL: url }), url).toBe("https://api.fish.audio");
+ }
+ });
+
+ it("needs an agent id of word characters and dashes", () => {
+ 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);
+ });
+});
+
+describe("the Fish agent's instructions", () => {
+ it("explain the delegate tool and the update prefix, and carry recent history within bounds", () => {
+ const history = Array.from({ length: 12 }, (_, i) => ({ role: i % 2 ? "assistant" as const : "user" as const, text: `message ${i} ${"x".repeat(900)}` }));
+ const text = fishInstructions({ name: "Rigel" }, history);
+ expect(text).toContain("`delegate` tool");
+ expect(text).toContain(FISH_UPDATE_PREFIX);
+ expect(text).not.toContain("message 3 ");
+ expect(text).toContain("message 11 ");
+ expect(text.match(/^(User|You): /gm)).toHaveLength(8);
+ expect(text).not.toContain("x".repeat(601));
+ });
+});
+
+describe("creating a Fish Audio session", () => {
+ const input = { key: " fish-key ", endpoint: ENDPOINT, bot: { name: "Rigel" }, history: [], cloudHome: false };
+
+ it("posts the agent and its system prompt with the key as a bearer token, and returns the LiveKit token", async () => {
+ const fetchImpl = fakeFetch(201, TOKEN);
+ await expect(createFishLiveSession({ ...input, fetchImpl })).resolves.toEqual(TOKEN);
+ const [url, init] = fetchImpl.mock.calls[0]!;
+ expect(url).toBe("https://api.fish.audio/v1/agent/sessions");
+ expect(init!.method).toBe("POST");
+ expect(init!.redirect).toBe("error");
+ expect((init!.headers as Record<string, string>).authorization).toBe("Bearer fish-key");
+ const body = JSON.parse(String(init!.body));
+ expect(body.agent_id).toBe("agent_123");
+ expect(body.overrides.system_prompt).toContain("You are Rigel");
+ expect(Object.keys(body)).toEqual(["agent_id", "overrides"]);
+ });
+
+ it("refuses without a key and never calls Fish", async () => {
+ const fetchImpl = fakeFetch(201, TOKEN);
+ await expect(createFishLiveSession({ ...input, key: " ", fetchImpl })).rejects.toMatchObject({ status: 409 });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+
+ it("turns Fish's errors into the user's next step, never echoing Fish's body or the key", async () => {
+ for (const status of [400, 401, 402, 403, 404, 409, 422, 429, 500]) {
+ const fetchImpl = fakeFetch(status, { message: "raw fish-key detail" });
+ const error = await createFishLiveSession({ ...input, fetchImpl }).catch((caught: unknown) => caught);
+ expect(error, String(status)).toBeInstanceOf(LiveSessionError);
+ 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);
+ }
+ });
+
+ it("rejects an answer that is not a LiveKit session with a secure URL", async () => {
+ for (const body of [null, {}, { ...TOKEN, transport: "webrtc" }, { ...TOKEN, livekit_url: "http://lk.example" }, { ...TOKEN, token: "" }, { ...TOKEN, session_id: 7 }]) {
+ await expect(createFishLiveSession({ ...input, fetchImpl: fakeFetch(201, body) }), JSON.stringify(body)).rejects.toMatchObject({ status: 502 });
+ }
+ });
+
+ it("reports an unreachable Fish as a gateway error", async () => {
+ const fetchImpl = vi.fn(async () => { throw new TypeError("fetch failed"); });
+ await expect(createFishLiveSession({ ...input, fetchImpl })).rejects.toMatchObject({ status: 502, message: "Could not reach Fish Audio. Check the internet connection." });
+ });
+
+ it("ends a session by id, and never throws", async () => {
+ const fetchImpl = fakeFetch(204, null);
+ await expect(endFishLiveSession("sess/1", "fish-key", ENDPOINT, fetchImpl)).resolves.toBe(true);
+ expect(fetchImpl.mock.calls[0]![0]).toBe("https://api.fish.audio/v1/agent/sessions/sess%2F1/end");
+ await expect(endFishLiveSession("s", "k", ENDPOINT, vi.fn(async () => { throw new Error("down"); }))).resolves.toBe(false);
+ });
+});
+
+describe("the relay of a Fish call", () => {
+ function opened() {
+ const relays = new FishRelays();
+ const endSession = vi.fn(async () => true);
+ const { relay, token } = relays.open("sess_1", endSession);
+ const messages: Array<Record<string, unknown>> = [];
+ relay.onmessage = (event) => messages.push(JSON.parse(String(event.data)));
+ const onopen = vi.fn();
+ relay.onopen = onopen;
+ return { relays, relay, token, endSession, messages, onopen };
+ }
+
+ it("is found only with its own token", () => {
+ const { relays, relay, token } = opened();
+ expect(token).toMatch(/^[\w-]{43}$/);
+ expect(relays.find("sess_1", token)).toBe(relay);
+ expect(relays.find("sess_1", `${token}x`)).toBeNull();
+ expect(relays.find("sess_1", `${token.slice(0, -1)}${token.endsWith("A") ? "B" : "A"}`)).toBeNull();
+ expect(relays.find("sess_1", "")).toBeNull();
+ expect(relays.find("other", token)).toBeNull();
+ expect(relays.socket("sess_1")).toBe(relay);
+ expect(() => relays.socket("other")).toThrow();
+ });
+
+ it("reads the client's reports as GPT-Live sideband events, only once the client has joined", () => {
+ const { relay, messages, onopen } = opened();
+ relay.receive([{ type: "heard", text: "too early", startMs: 0, endMs: 1 }, { type: "delegate", id: "d1", atMs: 1 }]);
+ expect(messages).toEqual([]);
+ relay.receive([{ type: "connected" }, { type: "connected" }]);
+ expect(onopen).toHaveBeenCalledTimes(1);
+ expect(relay.readyState).toBe(1);
+ relay.receive([
+ { type: "heard", text: "book a table", startMs: 100, endMs: 900 },
+ { type: "spoke", startMs: 1000, endMs: 1500 },
+ { type: "delegate", id: "call_1", atMs: 950 },
+ { type: "error", code: "provider_error" },
+ { type: "ended", reason: "agent_hangup" },
+ ]);
+ expect(messages).toEqual([
+ { type: "session.input_transcript.delta", delta: "book a table ", start_ms: 100, end_ms: 900 },
+ { type: "session.output_transcript.delta", start_ms: 1000, end_ms: 1500 },
+ { type: "session.delegation.created", delegation: { id: "call_1", target: "client" }, offset_ms: 950 },
+ { type: "error", error: { code: "provider_error" } },
+ { type: "session.closed", reason: "remote_hangup" },
+ ]);
+ });
+
+ it("maps only known endings to a reason", () => {
+ const { relay, messages } = opened();
+ relay.receive([{ type: "ended", reason: "user_hangup" }, { type: "ended", reason: "conversation_timeout" }]);
+ expect(messages).toEqual([{ type: "session.closed" }, { type: "session.closed", reason: "expired" }]);
+ });
+
+ it("queues the controller's appends for the client's poll and wakes a waiting poll", async () => {
+ const { relay } = opened();
+ const waiting = relay.poll(10_000);
+ relay.send(JSON.stringify({ type: "session.instructions.append", delegation_id: "call_1", content: "Booked for 7pm." }));
+ relay.send(JSON.stringify({ type: "session.thinking.append", content: "Checking the calendar" }));
+ relay.send(JSON.stringify({ type: "session.instructions.append", content: "" }));
+ relay.send(JSON.stringify({ type: "session.update", session: {} }));
+ relay.send("not json");
+ expect(await waiting).toEqual({ commands: [
+ { type: "append", kind: "instructions", content: "Booked for 7pm.", delegationId: "call_1" },
+ { type: "append", kind: "thinking", content: "Checking the calendar", delegationId: null },
+ ], closed: false });
+ expect(await relay.poll(0)).toEqual({ commands: [], closed: false });
+ });
+
+ it("keeps at most the 50 newest commands", async () => {
+ const { relay } = opened();
+ for (let i = 0; i < 60; i++) relay.send(JSON.stringify({ type: "session.commentary.append", content: `n${i}` }));
+ const { commands } = await relay.poll(0);
+ expect(commands).toHaveLength(50);
+ expect(commands[0]).toMatchObject({ content: "n10" });
+ });
+
+ it("answers an older poll with nothing when a newer one arrives", async () => {
+ const { relay } = opened();
+ const older = relay.poll(10_000);
+ const newer = relay.poll(10_000);
+ await expect(older).resolves.toEqual({ commands: [], closed: false });
+ relay.send(JSON.stringify({ type: "session.commentary.append", content: "hi" }));
+ await expect(newer).resolves.toMatchObject({ commands: [{ content: "hi" }] });
+ });
+
+ it("on session.close tells the client to hang up, ends the Fish session once, then reports it closed", async () => {
+ const { relay, endSession, messages } = opened();
+ relay.receive([{ type: "connected" }]);
+ relay.send(JSON.stringify({ type: "session.close" }));
+ relay.send(JSON.stringify({ type: "session.close" }));
+ await vi.waitFor(() => expect(messages).toContainEqual({ type: "session.closed" }));
+ expect(endSession).toHaveBeenCalledTimes(1);
+ expect((await relay.poll(0)).commands).toEqual([{ type: "close" }, { type: "close" }]);
+ });
+
+ it("when closed ends the session, answers the waiting poll, forgets itself and ignores later reports", async () => {
+ const { relays, relay, token, endSession, messages } = opened();
+ relay.receive([{ type: "connected" }]);
+ const waiting = relay.poll(10_000);
+ relay.close();
+ await expect(waiting).resolves.toEqual({ commands: [{ type: "close" }], closed: true });
+ expect(endSession).toHaveBeenCalledTimes(1);
+ expect(relays.find("sess_1", token)).toBeNull();
+ relay.receive([{ type: "heard", text: "late", startMs: 0, endMs: 1 }]);
+ expect(messages).toEqual([]);
+ expect(() => relay.send(JSON.stringify({ type: "session.close" }))).toThrow();
+ });
+
+ it("replaces a relay opened again for the same session", () => {
+ const relays = new FishRelays();
+ const first = relays.open("s", async () => true);
+ const second = relays.open("s", async () => true);
+ expect(first.relay.readyState).toBe(3);
+ expect(relays.find("s", first.token)).toBeNull();
+ expect(relays.find("s", second.token)).toBe(second.relay);
+ });
+});
diff --git a/server/live-fish.ts b/server/live-fish.ts
new file mode 100644
index 0000000000..55cbb6b4f3
--- /dev/null
+++ b/server/live-fish.ts
@@ -0,0 +1,316 @@
+// 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 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";
+
+const FISH_BASE = "https://api.fish.audio";
+const CREATE_TIMEOUT_MS = 20_000;
+const END_TIMEOUT_MS = 5_000;
+/** Fish agent ids as the dashboard and `GET /v1/agent/agents` show them. */
+const AGENT_ID = /^[\w-]{1,128}$/;
+const HISTORY_MESSAGES = 8;
+const HISTORY_MESSAGE_CHARS = 600;
+const HISTORY_TOTAL_CHARS = 6_000;
+export const FISH_DELEGATE_TOOL = "delegate";
+/** What a "fish" call reports as its voice: the voice is set on the Fish agent, not per call. */
+export const FISH_AGENT_VOICE = "agent";
+export const FISH_UPDATE_PREFIX = "[OpenMausBot]";
+const MAX_QUEUED_COMMANDS = 50;
+export const RELAY_POLL_MS = 15_000;
+
+/** Only a loopback http URL is accepted, read at call time. */
+export function fishLiveBaseUrl(env: NodeJS.ProcessEnv = process.env): string {
+ const override = env.OMB_FISH_LIVE_URL?.trim() ?? "";
+ return /^http:\/\/127\.0\.0\.1:\d{1,5}$/.test(override) ? override : FISH_BASE;
+}
+
+/** null without a usable agent id. */
+export function fishLiveEndpoint(agentId: string | undefined, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {
+ const id = agentId?.trim() ?? "";
+ return AGENT_ID.test(id) ? { provider: "fish", apiBase: `${fishLiveBaseUrl(env)}/v1/agent`, model: id } : null;
+}
+
+export function isFishAgentId(value: string): boolean {
+ return AGENT_ID.test(value);
+}
+
+/** The Fish agent's system prompt for this call: the GPT-Live instructions, how this agent delegates, and the recent chat. */
+export function fishInstructions(bot: LiveBot, history: LiveHistoryMessage[], { cloudHome = false }: { cloudHome?: boolean } = {}): string {
+ const lines = [
+ liveInstructions(bot, { cloudHome }),
+ "",
+ `To delegate, call the \`${FISH_DELEGATE_TOOL}\` tool with the user's request in their own words. Its result is what you learned or did; speak it naturally and briefly.`,
+ `A user message that starts with ${FISH_UPDATE_PREFIX} is not the user speaking: it is a later result or a status note from your work. Speak it to the user naturally, in the first person, without reading the prefix.`,
+ "Do not end the call yourself. When the user asks to hang up, delegate it.",
+ ];
+ const recent = recentHistory(history);
+ if (recent.length) {
+ lines.push("", "The conversation so far, most recent last:");
+ for (const message of recent) lines.push(`${message.role === "user" ? "User" : "You"}: ${message.text}`);
+ }
+ return lines.join("\n");
+}
+
+function recentHistory(history: LiveHistoryMessage[]): LiveHistoryMessage[] {
+ const picked: LiveHistoryMessage[] = [];
+ let total = 0;
+ for (const message of [...history].reverse()) {
+ if (picked.length >= HISTORY_MESSAGES) break;
+ const text = message.text.replace(/\s+/g, " ").trim().slice(0, HISTORY_MESSAGE_CHARS);
+ if (!text) continue;
+ if (total + text.length > HISTORY_TOTAL_CHARS) break;
+ total += text.length;
+ picked.unshift({ role: message.role, text });
+ }
+ return picked;
+}
+
+export interface CreateFishSessionInput {
+ key: string;
+ endpoint: LiveEndpoint;
+ bot: LiveBot;
+ history: LiveHistoryMessage[];
+ cloudHome: boolean;
+ fetchImpl?: typeof fetch;
+ 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. */
+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);
+ const body = {
+ agent_id: input.endpoint.model,
+ // Fish refuses an override the agent's `overrides_allowed` does not list (400).
+ overrides: { system_prompt: fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }) },
+ };
+ let response: Response;
+ try {
+ response = await (input.fetchImpl ?? fetch)(`${input.endpoint.apiBase}/sessions`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${key}`, "content-type": "application/json" },
+ redirect: "error",
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(input.timeoutMs ?? CREATE_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 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);
+ }
+ return {
+ transport: "livekit",
+ session_id: token.session_id,
+ expires_at: typeof token.expires_at === "string" ? token.expires_at : "",
+ max_duration_seconds: Number(token.max_duration_seconds) || 0,
+ livekit_url: token.livekit_url,
+ token: token.token,
+ };
+}
+
+/** Fish API v1 `POST /v1/agent/sessions/{id}/end`; best effort, never throws. */
+export async function endFishLiveSession(sessionId: string, key: string, endpoint: LiveEndpoint, fetchImpl: typeof fetch = fetch): Promise<boolean> {
+ try {
+ const response = await fetchImpl(`${endpoint.apiBase}/sessions/${encodeURIComponent(sessionId)}/end`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${key.trim()}` },
+ redirect: "error",
+ signal: AbortSignal.timeout(END_TIMEOUT_MS),
+ });
+ await response.body?.cancel().catch(() => undefined);
+ return response.ok;
+ } catch {
+ return false;
+ }
+}
+
+export 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 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 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}).`;
+ }
+}
+
+const SOCKET = { connecting: 0, open: 1, closed: 3 } as const;
+/** What the client of a fish call says it heard ends a call this way; anything else is the call's own ending. */
+const CLIENT_END_REASONS: Record<string, string> = {
+ agent_hangup: "remote_hangup",
+ conversation_timeout: "expired",
+ connection_lost: "connection_lost",
+};
+
+/** The controller's sideband for a "fish" call. The client's reports arrive through `receive` and are read exactly as
+ * GPT-Live's sideband events are; the controller's commands queue for the client's `poll`. Everything the client sends is
+ * the caller's own claim, so a fish call is held only by someone fishLiveCallRefusal admits (live-access.ts). */
+export class FishRelay implements LiveSocket {
+ readyState: number = SOCKET.connecting;
+ onopen: ((event: unknown) => void) | null = null;
+ onmessage: ((event: { data: unknown }) => void) | null = null;
+ onclose: ((event: unknown) => void) | null = null;
+ onerror: ((event: unknown) => void) | null = null;
+ readonly sessionId: string;
+ private readonly token: Buffer;
+ private readonly endSession: () => Promise<unknown>;
+ private readonly forget: () => void;
+ private queue: LiveFishRelayCommand[] = [];
+ private waiter: (() => void) | null = null;
+ private ended: Promise<unknown> | null = null;
+
+ constructor(input: { sessionId: string; token: string; endSession: () => Promise<unknown>; forget: () => void }) {
+ this.sessionId = input.sessionId;
+ this.token = Buffer.from(input.token);
+ this.endSession = input.endSession;
+ this.forget = input.forget;
+ }
+
+ holds(token: string): boolean {
+ const offered = Buffer.from(token);
+ return offered.length === this.token.length && timingSafeEqual(offered, this.token);
+ }
+
+ send(data: string): void {
+ if (this.readyState === SOCKET.closed) throw new Error("relay closed");
+ let event: Record<string, unknown>;
+ try {
+ event = JSON.parse(data) as Record<string, unknown>;
+ } catch {
+ return;
+ }
+ const kind = /^session\.(instructions|thinking|commentary)\.append$/.exec(String(event.type))?.[1] as "instructions" | "thinking" | "commentary" | undefined;
+ if (kind) {
+ if (typeof event.content !== "string" || !event.content) return;
+ this.push({ type: "append", kind, content: event.content, delegationId: typeof event.delegation_id === "string" ? event.delegation_id : null });
+ return;
+ }
+ if (event.type === "session.close") {
+ this.push({ type: "close" });
+ void this.end().then(() => this.deliver({ type: "session.closed" }));
+ }
+ }
+
+ close(): void {
+ if (this.readyState === SOCKET.closed) return;
+ this.readyState = SOCKET.closed;
+ this.queue.push({ type: "close" });
+ this.wake();
+ this.forget();
+ void this.end();
+ }
+
+ /** The client's reports, in order. Before the client has joined only `connected`, `ended` and `error` count. */
+ receive(events: LiveFishRelayEvent[]): void {
+ for (const event of events) {
+ if (this.readyState === SOCKET.closed) return;
+ if (event.type === "connected") {
+ if (this.readyState !== SOCKET.connecting) continue;
+ this.readyState = SOCKET.open;
+ this.onopen?.({});
+ continue;
+ }
+ if (event.type === "ended") {
+ this.deliver({ type: "session.closed", ...(CLIENT_END_REASONS[event.reason] ? { reason: CLIENT_END_REASONS[event.reason] } : {}) });
+ continue;
+ }
+ if (event.type === "error") {
+ this.deliver({ type: "error", error: { code: event.code } });
+ continue;
+ }
+ if (this.readyState !== SOCKET.open) continue;
+ if (event.type === "heard") {
+ // GPT-Live's deltas are fragments glued as sent; a whole Fish utterance needs its own space.
+ this.deliver({ type: "session.input_transcript.delta", delta: `${event.text} `, start_ms: event.startMs, end_ms: event.endMs });
+ } else if (event.type === "spoke") {
+ this.deliver({ type: "session.output_transcript.delta", start_ms: event.startMs, end_ms: event.endMs });
+ } else if (event.type === "delegate") {
+ this.deliver({ type: "session.delegation.created", delegation: { id: event.id, target: "client" }, offset_ms: event.atMs });
+ }
+ }
+ }
+
+ /** The queued commands, waiting up to `waitMs` for one. A newer poll answers an older one with nothing. */
+ async poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> {
+ if (!this.queue.length && this.readyState !== SOCKET.closed && waitMs > 0) {
+ this.wake();
+ await new Promise<void>((resolve) => {
+ const done = () => {
+ clearTimeout(timer);
+ if (this.waiter === done) this.waiter = null;
+ resolve();
+ };
+ const timer = setTimeout(done, waitMs);
+ timer.unref?.();
+ this.waiter = done;
+ });
+ }
+ const commands = this.queue.splice(0);
+ return { commands, closed: this.readyState === SOCKET.closed };
+ }
+
+ private push(command: LiveFishRelayCommand): void {
+ this.queue.push(command);
+ if (this.queue.length > MAX_QUEUED_COMMANDS) this.queue.splice(0, this.queue.length - MAX_QUEUED_COMMANDS);
+ this.wake();
+ }
+
+ private wake(): void {
+ const waiter = this.waiter;
+ this.waiter = null;
+ waiter?.();
+ }
+
+ private deliver(event: Record<string, unknown>): void {
+ if (this.readyState === SOCKET.closed) return;
+ this.onmessage?.({ data: JSON.stringify(event) });
+ }
+
+ private end(): Promise<unknown> {
+ this.ended ??= this.endSession().catch(() => undefined);
+ return this.ended;
+ }
+}
+
+/** The relays of running fish calls, by Fish session id. */
+export class FishRelays {
+ private readonly relays = new Map<string, FishRelay>();
+
+ /** A relay for a session just created; its token goes only to the client that started the call. */
+ open(sessionId: string, endSession: () => Promise<unknown>): { relay: FishRelay; token: string } {
+ const token = randomBytes(32).toString("base64url");
+ this.relays.get(sessionId)?.close();
+ const relay = new FishRelay({ sessionId, token, endSession, forget: () => {
+ if (this.relays.get(sessionId) === relay) this.relays.delete(sessionId);
+ } });
+ this.relays.set(sessionId, relay);
+ return { relay, token };
+ }
+
+ /** The controller's attach: the relay `open` made for this session. */
+ socket(sessionId: string): FishRelay {
+ const relay = this.relays.get(sessionId);
+ if (!relay) throw new Error("no relay for that session");
+ return relay;
+ }
+
+ /** null unless the token is this session's. */
+ find(sessionId: string, token: string): FishRelay | null {
+ const relay = this.relays.get(sessionId);
+ return relay?.holds(token) ? relay : null;
+ }
+}
diff --git a/server/live-settings.test.ts b/server/live-settings.test.ts
index 5c2e313d6d..06b0037896 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_KEY } from "./live-call.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 { LIVE_IDLE_MINUTES_DEFAULT, liveCallEndpoint, liveCallKey, liveCallSettings, liveSettingsFor, liveSettingsForClient, liveSetupProblem } from "./live-settings.ts";
@@ -92,6 +92,63 @@ describe("Live calls through Azure OpenAI", () => {
});
});
+describe("Live calls through Fish Audio", () => {
+ const fish = { provider: "fish" as const, fishAgentId: "agent_1" };
+
+ it("never use the OpenAI API key, or a key saved for OpenAI or Azure, as the Fish key", () => {
+ 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;
+ expect(liveCallKey(cfg), JSON.stringify(live)).toBeNull();
+ expect(liveSetupProblem(cfg)).toBe(LIVE_NEEDS_FISH);
+ }
+ });
+
+ 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" });
+ expect(liveSetupProblem(cfg)).toBeNull();
+ const settings = liveSettingsFor(cfg);
+ expect(settings).toMatchObject({ configured: true, keySource: "live", provider: "fish", fishAgentId: "agent_1" });
+ 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("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 });
+ });
+
+ 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("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("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();
+ });
+});
+
describe("a saved Live key", () => {
const A = "https://a.openai.azure.com", B = "https://b.openai.azure.com";
const onA: LiveConfig = { provider: "azure", azureEndpoint: A, key: "k", keyFor: "azure:a.openai.azure.com" };
diff --git a/server/live-settings.ts b/server/live-settings.ts
index a4f29feb4c..d9dd2c88e0 100644
--- a/server/live-settings.ts
+++ b/server/live-settings.ts
@@ -1,7 +1,8 @@
import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";
import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";
-import { azureLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.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";
export const LIVE_IDLE_MINUTES_DEFAULT = 5;
@@ -11,22 +12,23 @@ type LiveConfig = Pick<AppConfig, "live" | "openai">;
export function liveCallKey(cfg: LiveConfig): { key: string; source: LiveKeySource } | null {
const live = usableLiveKey(cfg.live);
if (live) return { key: live, source: "live" };
- if (cfg.live?.provider === "azure") return null;
+ if (cfg.live?.provider === "azure" || cfg.live?.provider === "fish") 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. */
+/** null when Azure is chosen but its endpoint or deployment is missing or not valid, or Fish Audio without a valid agent id. */
export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {
- return cfg.live?.provider === "azure"
- ? azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment)
- : openAiLiveEndpoint(env);
+ if (cfg.live?.provider === "azure") return azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment);
+ if (cfg.live?.provider === "fish") return fishLiveEndpoint(cfg.live.fishAgentId, env);
+ return openAiLiveEndpoint(env);
}
export function liveSetupProblem(cfg: LiveConfig): string | null {
- const azure = cfg.live?.provider === "azure";
- if (!liveCallKey(cfg)) return azure ? LIVE_NEEDS_AZURE : LIVE_NEEDS_KEY;
- return liveCallEndpoint(cfg) ? null : LIVE_NEEDS_AZURE;
+ const provider = cfg.live?.provider;
+ const missing = provider === "azure" ? LIVE_NEEDS_AZURE : provider === "fish" ? LIVE_NEEDS_FISH : LIVE_NEEDS_KEY;
+ if (!liveCallKey(cfg)) return missing;
+ return liveCallEndpoint(cfg) ? null : missing;
}
/** The environment follows the save, as for PUT /api/config: loadConfig prefers it over the file. */
@@ -41,21 +43,22 @@ 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. */
-export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeployment: _deployment, ...settings }: LiveSettings): LiveSettings {
+/** 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 {
return settings;
}
export function liveSettingsFor(cfg: AppConfig): LiveSettings {
const minutes = cfg.live?.idleMinutes;
const key = liveCallKey(cfg);
- const azure = cfg.live?.provider === "azure";
+ const provider = cfg.live?.provider;
return {
configured: liveSetupProblem(cfg) === null,
...(key ? { keySource: key.source } : {}),
- ...(azure ? { provider: "azure" as const } : {}),
+ ...(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.ts
index ecd98c1d22..3cc54fda23 100644
--- a/server/routes/live.test.ts
+++ b/server/routes/live.test.ts
@@ -7,6 +7,7 @@ import { json, readBody } from "../harness/http.ts";
import { LiveCallBusyError, LiveCallSignedOutError } from "../live-call-controller.ts";
import { LIVE_NEEDS_KEY, LiveSessionError } from "../live-call.ts";
import { requiredScope } from "../request-auth.ts";
+import { RELAY_POLL_MS } from "../live-fish.ts";
import { createLiveRoutes, type LiveRouteDeps } from "./live.ts";
import { dispatchRoutes } from "./table.ts";
@@ -57,6 +58,7 @@ function deps(overrides: Partial<LiveRouteDeps> = {}): LiveRouteDeps & { saved:
},
resolveTarget: (botId, threadId) => (botId === "bot1" && (threadId ?? "t1") === "t1" ? { botId, botName: "Ada", threadId: threadId ?? "t1" } : null),
settings: () => ({ configured: true, voice: "marin", readTypedReplies: true, idleMinutes: 5 }),
+ fishRelay: () => null,
saveSettings: vi.fn(async (patch: SettingsPatch): Promise<LiveSettings> => {
saved.push(patch);
return { configured: true, voice: "marin", readTypedReplies: true, idleMinutes: 5, ...patch };
@@ -150,6 +152,16 @@ 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 () => {
+ 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", { fishAgentId: "" })).status).toBe(200);
+ expect(d.saved).toEqual([{ provider: "fish", fishAgentId: "agent_1" }, { fishAgentId: "" }]);
+ });
+
it("saves nothing for an empty patch", async () => {
const d = deps();
expect(await request(d, "PATCH", "/api/live/settings", {})).toEqual({ status: 400, body: { error: "nothing to save" } });
@@ -177,6 +189,7 @@ describe("live routes", () => {
expect(requiredScope("GET", "/api/live/call")).toBe("admin");
expect(requiredScope("PATCH", "/api/live/settings")).toBe("admin");
expect(requiredScope("POST", "/api/live/device-revoked")).toBe("admin");
+ expect(requiredScope("POST", "/api/live/relay")).toBe("admin");
});
describe("a call from a paired phone", () => {
@@ -213,3 +226,67 @@ describe("live routes", () => {
});
});
});
+
+describe("a Fish Audio call", () => {
+ const TOKEN = { transport: "livekit" as const, session_id: "fish_1", expires_at: "x", max_duration_seconds: 900, livekit_url: "wss://lk.example", token: "jwt" };
+ const fishTransport = { type: "fish" as const, session: TOKEN, relayToken: "r".repeat(43) };
+
+ function relayDeps() {
+ const relay = { receive: vi.fn(), poll: vi.fn(async (_wait: number) => ({ commands: [{ type: "close" as const }], closed: false })) };
+ const fishRelay = vi.fn((sessionId: string, token: string) => (sessionId === "fish_1" && token === fishTransport.relayToken ? relay : null));
+ return { d: deps({ fishRelay }), relay, fishRelay };
+ }
+ const body = (extra: Record<string, unknown> = {}) => ({ sessionId: "fish_1", token: fishTransport.relayToken, ...extra });
+
+ it("starts with no SDP and answers with Fish's session and the relay's token", async () => {
+ const call = deps().calls.current()!;
+ const d = deps({ calls: { ...deps().calls, start: vi.fn(async () => ({ call, fish: fishTransport })) } });
+ const res = await request(d, "POST", "/api/live/session", { botId: "bot1", client: "web" });
+ expect(res).toEqual({ status: 201, body: { call: expect.objectContaining({ callId: "c1" }), transport: fishTransport } });
+ expect(vi.mocked(d.calls.start).mock.calls[0]![0]).not.toHaveProperty("sdp");
+ });
+
+ it("passes the client's reports to the relay and answers with what is queued, without waiting", async () => {
+ const { d, relay } = relayDeps();
+ const events = [{ type: "connected" }, { type: "heard", text: "hi", startMs: 1, endMs: 2 }, { type: "delegate", id: "call_1", atMs: 3 }];
+ expect(await request(d, "POST", "/api/live/relay", body({ events, wait: true }))).toEqual({ status: 200, body: { commands: [{ type: "close" }], closed: false } });
+ expect(relay.receive).toHaveBeenCalledWith(events);
+ expect(relay.poll).toHaveBeenCalledWith(0);
+ });
+
+ it("holds a poll open only when the client asks to wait and reports nothing", async () => {
+ const { d, relay } = relayDeps();
+ await request(d, "POST", "/api/live/relay", body({ wait: true }));
+ await request(d, "POST", "/api/live/relay", body());
+ expect(relay.poll.mock.calls.map(([wait]) => wait)).toEqual([RELAY_POLL_MS, 0]);
+ expect(relay.receive).not.toHaveBeenCalled();
+ });
+
+ it("answers 404 to a wrong token or session, and gives the relay nothing", async () => {
+ const { d, relay } = relayDeps();
+ expect(await request(d, "POST", "/api/live/relay", body({ token: "guessed" }))).toEqual({ status: 404, body: { error: "That call is not running." } });
+ expect((await request(d, "POST", "/api/live/relay", body({ sessionId: "other" }))).status).toBe(404);
+ expect(relay.receive).not.toHaveBeenCalled();
+ expect(relay.poll).not.toHaveBeenCalled();
+ });
+
+ it("refuses a report that is not one the client makes, before looking for the relay", async () => {
+ const { d, fishRelay } = relayDeps();
+ for (const bad of [
+ body({ events: [{ type: "heard", text: "", startMs: 0, endMs: 1 }] }),
+ body({ events: [{ type: "heard", text: "x".repeat(2_001), startMs: 0, endMs: 1 }] }),
+ body({ events: [{ type: "delegate", id: "a b", atMs: 0 }] }),
+ body({ events: [{ type: "ended", reason: "Bye!" }] }),
+ body({ events: [{ type: "heard", text: "hi", startMs: -1, endMs: 1 }] }),
+ body({ events: [{ type: "session.close" }] }),
+ body({ events: [{ type: "connected", extra: 1 }] }),
+ body({ events: Array.from({ length: 21 }, () => ({ type: "connected" })) }),
+ body({ extra: 1 }),
+ { sessionId: "fish_1" },
+ "{not json",
+ ]) {
+ expect((await request(d, "POST", "/api/live/relay", bad)).status, JSON.stringify(bad)).toBe(400);
+ }
+ expect(fishRelay).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/routes/live.ts b/server/routes/live.ts
index 57b96d94d2..1156bae299 100644
--- a/server/routes/live.ts
+++ b/server/routes/live.ts
@@ -1,33 +1,52 @@
// The provider key is never read or written here; without one a start answers 409 `needsKey`. A phone can never send device-revoked.
import type { IncomingMessage } from "node:http";
import { z } from "zod";
-import type { LiveProvider, LiveSettings } from "../../shared/wire.ts";
+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 { 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; voice?: string; readTypedReplies?: boolean; idleMinutes?: number }): Promise<LiveSettings>;
+ saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; fishAgentId?: 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[]): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
}
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.
- sdp: z.string().min(1).refine((sdp) => Buffer.byteLength(sdp) <= MAX_SDP_BYTES),
+ // Not trimmed: the SDP offer goes to OpenAI byte for byte. Absent on a Fish Audio 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();
const endBody = z.object({ callId: z.string().min(1).max(120) }).strict();
+const relayMs = z.number().finite().min(0).max(86_400_000);
+const relayEvent = z.discriminatedUnion("type", [
+ z.object({ type: z.literal("connected") }).strict(),
+ z.object({ type: z.literal("heard"), text: z.string().min(1).max(2_000), startMs: relayMs, endMs: relayMs }).strict(),
+ z.object({ type: z.literal("spoke"), startMs: relayMs, endMs: relayMs }).strict(),
+ z.object({ type: z.literal("delegate"), id: z.string().regex(/^[\w.:-]{1,120}$/), atMs: relayMs }).strict(),
+ z.object({ type: z.literal("ended"), reason: z.string().regex(/^[a-z_]{0,40}$/) }).strict(),
+ z.object({ type: z.literal("error"), code: z.string().regex(/^[\w.-]{1,40}$/) }).strict(),
+]);
+const relayBody = z.object({
+ sessionId: z.string().min(1).max(200),
+ token: z.string().min(1).max(200),
+ events: z.array(relayEvent).max(20).optional(),
+ wait: z.boolean().optional(),
+}).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"]).optional(),
+ provider: z.enum(["openai", "azure", "fish"]).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(),
+ 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(),
@@ -61,8 +80,8 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
if (!target) return json(res, 404, { error: "That bot or chat does not exist." });
try {
const device = companionDevice(req);
- const { call, sdp } = await deps.calls.start({ auth, ...(device ? { device } : {}), ...target, client: parsed.data.client, sdp: parsed.data.sdp });
- return json(res, 201, { call, transport: { type: "webrtc", sdp } });
+ const started = await deps.calls.start({ auth, ...(device ? { device } : {}), ...target, client: parsed.data.client, ...(parsed.data.sdp ? { sdp: parsed.data.sdp } : {}) });
+ return json(res, 201, { call: started.call, transport: started.fish ?? { type: "webrtc", sdp: started.sdp } });
} catch (error) {
if (error instanceof LiveCallBusyError) return json(res, 409, { error: error.message, activeCall: error.call });
if (error instanceof LiveSessionError) {
@@ -81,6 +100,15 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
if (method === "GET" && path === "/api/live/call") return json(res, 200, { call: deps.calls.current() });
+ if (method === "POST" && path === "/api/live/relay") {
+ const parsed = relayBody.safeParse(await bodyOf(req, readBody));
+ if (!parsed.success) return json(res, 400, { error: "The call update was not valid." });
+ const relay = deps.fishRelay(parsed.data.sessionId, parsed.data.token);
+ if (!relay) return json(res, 404, { error: "That call is not running." });
+ if (parsed.data.events?.length) relay.receive(parsed.data.events);
+ return json(res, 200, await relay.poll(parsed.data.wait && !parsed.data.events?.length ? RELAY_POLL_MS : 0));
+ }
+
if (method === "POST" && path === "/api/live/device-revoked") {
if (req.headers["x-openmausbot-companion"] !== "1") return json(res, 403, { error: "Only the phone companion can report an unpaired phone." });
const device = companionDevice(req);
@@ -94,6 +122,7 @@ 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.ts
index 52ef27d3a2..cbed7e4f75 100644
--- a/shared/live-call-wire.ts
+++ b/shared/live-call-wire.ts
@@ -45,24 +45,61 @@ export interface LiveCallRecord {
title?: string;
}
-/** Who runs a Live call's GPT-Live session: OpenAI itself, or a GPT-Live deployment on the user's own Azure OpenAI / Foundry resource. */
-export type LiveProvider = "openai" | "azure";
+/** 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. */
+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";
/** 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. */
+ /** 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. */
configured: boolean;
keySource?: LiveKeySource;
- /** Absent means "openai". With "azure" only the `live` key is used, never the OpenAI API key. */
+ /** Absent means "openai". With "azure" or "fish" only the `live` key is used, 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;
}
+
+/** The single-use token Fish Audio returns for one agent session (Fish API v1 `LiveKitSessionToken`), passed verbatim to
+ * `AgentSession.start({ sessionToken })` of `@fishaudio/agent-client` 1.x. Holds no API key. */
+export interface LiveFishSessionToken {
+ transport: "livekit";
+ session_id: string;
+ /** ISO time by which the client must join */
+ expires_at: string;
+ max_duration_seconds: number;
+ livekit_url: string;
+ token: string;
+}
+
+/** A "fish" call's transport, answered only to the client that started the call: Fish's session token, and the token
+ * that client presents on POST /api/live/relay, the call's only route for what it heard and for the bot's replies. */
+export interface LiveFishTransport {
+ type: "fish";
+ session: LiveFishSessionToken;
+ relayToken: string;
+}
+
+/** What the client of a "fish" 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 }
+ | { type: "spoke"; startMs: number; endMs: number }
+ | { type: "delegate"; id: string; atMs: number }
+ | { type: "ended"; reason: string }
+ | { type: "error"; code: string };
+
+/** What the harness hands the client of a "fish" call: words for the agent to speak or know (`kind` as on GPT-Live), or the end of the call. */
+export type LiveFishRelayCommand =
+ | { type: "append"; kind: "instructions" | "thinking" | "commentary"; content: string; delegationId: string | null }
+ | { type: "close" };
diff --git a/shared/wire.ts b/shared/wire.ts
index f89223c280..a2a72a7603 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -37,7 +37,7 @@ import type { LiveCallRecord, LiveCallState } from "./live-call-wire.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, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
+export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
/** Reasoning-effort levels, ascending: a union of what any engine accepts;
* each driver declares the subset its CLI will take. */
diff --git a/src/components/CallView.tsx b/src/components/CallView.tsx
index bd7a5150cf..a61827995c 100644
--- a/src/components/CallView.tsx
+++ b/src/components/CallView.tsx
@@ -180,7 +180,7 @@ export function CallTargetButton({
setMenuOpen(false);
if (next === "live" && liveThreadId !== undefined) {
onStart("live");
- void startLiveCall({ botId: targetId, threadId: liveThreadId });
+ void startLiveCall({ botId: targetId, threadId: liveThreadId, provider: state.config?.live?.provider });
return;
}
if (!turnsReady) {
diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsx
index c851951be3..0067d6a4fc 100644
--- a/src/components/LiveCallSettings.tsx
+++ b/src/components/LiveCallSettings.tsx
@@ -2,7 +2,7 @@ import { useCallback, useId, useState } from "react";
import { LIVE_VOICE_OPTIONS } from "../../shared/live-call";
import { t } from "@/lib/i18n";
-import { liveDisclosure } from "@/lib/call-mode";
+import { liveDisclosure, liveKeyCopy } from "@/lib/call-mode";
import { api, useStore, type ConfigStatus } from "@/state/store";
import type { LiveSettings } from "../../shared/wire";
import { LiveKeySetup } from "./LiveKeySetup";
@@ -24,6 +24,8 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
dialog?.querySelector<HTMLElement>("select, input, button")?.focus();
}, []);
const azure = live.provider === "azure";
+ const fish = live.provider === "fish";
+ const copy = liveKeyCopy(live.provider);
const voice = live.voice || "marin";
const known = LIVE_VOICE_OPTIONS.some((option) => option.id === voice);
@@ -69,6 +71,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
}}
>
<LiveProviderSettings />
+ {!fish && <>
<label className="flex items-center justify-between gap-2">
<span className="text-ink-secondary">{t("call.live.voice")}</span>
<Select
@@ -82,6 +85,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
</Select>
</label>
<div className="-mt-2 text-[12px] text-ink-tertiary">{t("call.live.voiceNext")}</div>
+ </>}
<label className="flex items-center justify-between gap-2">
<span className="text-ink-secondary">{t("call.live.readTyped")}</span>
<input
@@ -107,7 +111,7 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
</Select>
</label>
<div className="flex items-center justify-between gap-2 border-t border-hairline/60 pt-2">
- <span className="text-ink-secondary">{t(azure ? "call.live.azureKey" : "call.live.key")}</span>
+ <span className="text-ink-secondary">{t(copy.key)}</span>
<span className="flex gap-2">
<button type="button" className="text-accent hover:underline" onClick={() => setChangingKey((open) => !open)}>
{t("call.live.keyChange")}
@@ -119,12 +123,12 @@ export function LiveCallSettings({ onClose }: { onClose: () => void }) {
)}
</span>
</div>
- {live.keySource !== "live" && azure && <div className="-mt-2 text-[12px] text-ink-tertiary">{t("call.live.azureNeedsKey")}</div>}
- {live.keySource !== "live" && !azure && (
+ {live.keySource !== "live" && (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>
)}
{changingKey && <LiveKeySetup compact onSaved={() => setChangingKey(false)} />}
- <div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure })} {t(azure ? "call.live.azureCost" : "call.live.cost")}</div>
+ <div className="text-[12px] text-ink-tertiary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} {t(copy.cost)}</div>
{error && <div className="text-[12px] text-danger">{error}</div>}
</div>
);
diff --git a/src/components/LiveKeyNeeded.tsx b/src/components/LiveKeyNeeded.tsx
index a6593a1140..37a8969568 100644
--- a/src/components/LiveKeyNeeded.tsx
+++ b/src/components/LiveKeyNeeded.tsx
@@ -1,7 +1,7 @@
import { useEffect, useId } from "react";
import { KeyRound } from "lucide-react";
-import { liveDisclosure } from "@/lib/call-mode";
+import { liveDisclosure, liveKeyCopy } from "@/lib/call-mode";
import { dismissLiveNotice } from "@/lib/live-call-media";
import { t } from "@/lib/i18n";
import { useStore } from "@/state/store";
@@ -14,18 +14,20 @@ export function LiveKeyNeeded() {
const titleId = useId();
const live = state.config?.live;
const azure = live?.provider === "azure";
+ 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) && live?.keySource !== "live";
+ const keyForm = ((azure && Boolean(live?.azureEndpoint)) || fish) && live?.keySource !== "live";
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(azure ? "call.live.needsAzure" : "call.live.needsKey")}</h2>
+ <h2 id={titleId} className="text-[14px] font-medium leading-[1.4] text-ink">{t(copy.needs)}</h2>
</div>
<LiveProviderSettings />
- {azure && <DismissWhenReady ready={live?.configured === true} />}
+ {(azure || fish) && <DismissWhenReady ready={live?.configured === true} />}
{keyForm && <LiveKeySetup compact onSaved={() => {}} />}
- {!azure && <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 })} `}{t(azure ? "call.live.azureCost" : "call.live.cost")}</p>
+ {!azure && !fish && <button type="button" className="ui-button ui-button-primary self-start" onClick={() => { dismissLiveNotice(); dispatch(openKeySettings("openai", "liveCalls")); }}>{t("call.live.openApiKeys")}</button>}
+ <p className="text-[12px] leading-[1.45] text-ink-tertiary">{!keyForm && `${liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })} `}{t(copy.cost)}</p>
</section>;
}
diff --git a/src/components/LiveKeySetup.tsx b/src/components/LiveKeySetup.tsx
index da789eb21f..e07f3c8b78 100644
--- a/src/components/LiveKeySetup.tsx
+++ b/src/components/LiveKeySetup.tsx
@@ -1,13 +1,16 @@
import { useEffect, useRef, useState } from "react";
import { api, useStore, type ConfigStatus } from "@/state/store";
-import { liveDisclosure } from "@/lib/call-mode";
+import { liveDisclosure, liveKeyCopy } from "@/lib/call-mode";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
export function LiveKeySetup({ onSaved, compact = false }: { onSaved: () => void; compact?: boolean }) {
const { state, dispatch } = useStore();
- const azure = state.config?.live?.provider === "azure";
+ const provider = state.config?.live?.provider;
+ const azure = provider === "azure";
+ const fish = provider === "fish";
+ const copy = liveKeyCopy(provider);
const [key, setKey] = useState("");
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -47,17 +50,17 @@ export function LiveKeySetup({ onSaved, compact = false }: { onSaved: () => void
void save();
}}
>
- <div className="text-[14px] font-medium text-ink">{t(azure ? "call.live.azureKeyTitle" : "call.live.keyTitle")}</div>
- <div className="text-[13px] leading-[1.45] text-ink-secondary">{t(azure ? "call.live.azureKeyExplain" : "call.live.keyExplain")}</div>
- <div className="text-[13px] leading-[1.45] text-ink-secondary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure })}</div>
+ <div className="text-[14px] font-medium text-ink">{t(copy.title)}</div>
+ <div className="text-[13px] leading-[1.45] text-ink-secondary">{t(copy.explain)}</div>
+ <div className="text-[13px] leading-[1.45] text-ink-secondary">{liveDisclosure({ cloudHome: state.config?.cloudHome === true, azure, fish })}</div>
<input
type="password"
autoComplete="off"
spellCheck={false}
value={key}
onChange={(event) => setKey(event.target.value)}
- placeholder={azure ? "…" : "sk-…"}
- aria-label={t(azure ? "call.live.azureKeyField" : "call.live.keyField")}
+ placeholder={azure || fish ? "…" : "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"
/>
{error && <div className="text-[12px] text-danger">{error}</div>}
diff --git a/src/components/LiveProviderSettings.tsx b/src/components/LiveProviderSettings.tsx
index af16239e10..0e6f329264 100644
--- a/src/components/LiveProviderSettings.tsx
+++ b/src/components/LiveProviderSettings.tsx
@@ -5,7 +5,7 @@ import { api, useStore } from "@/state/store";
import type { LiveProvider, LiveSettings } from "../../shared/wire";
import { Select } from "./Select";
-type ProviderPatch = Partial<Pick<LiveSettings, "provider" | "azureEndpoint" | "azureDeployment">>;
+type ProviderPatch = Partial<Pick<LiveSettings, "provider" | "azureEndpoint" | "azureDeployment" | "fishAgentId">>;
const FIELD = "w-full rounded-lg border border-hairline bg-inset px-2.5 py-1.5 text-[13px] text-ink outline-none focus:border-accent/60";
@@ -15,9 +15,11 @@ export function LiveProviderSettings() {
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) => {
setSaving(true);
@@ -44,6 +46,7 @@ export function LiveProviderSettings() {
>
<option value="openai">{t("call.live.provider.openai")}</option>
<option value="azure">{t("call.live.provider.azure")}</option>
+ <option value="fish">{t("call.live.provider.fish")}</option>
</Select>
</label>
{provider === "azure" && (
@@ -91,6 +94,37 @@ export function LiveProviderSettings() {
)}
</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">
+ <span className="text-[12px] text-ink-secondary">{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] text-ink-tertiary">{t("call.live.fishHint")}</div>
+ {agentChanged && (
+ <button
+ type="submit"
+ disabled={saving}
+ className="self-start rounded-lg bg-accent px-3 py-1.5 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50"
+ >
+ {t("common.save")}
+ </button>
+ )}
+ </form>
+ )}
{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.ts
index 2dbba215cd..aaa26257fd 100644
--- a/src/components/keys/KeysPage.dom.test.ts
+++ b/src/components/keys/KeysPage.dom.test.ts
@@ -95,11 +95,11 @@ describe("the keys page", () => {
expect(rowsShown()).not.toContain("elevenlabs");
});
- it("offers the Live calls service, OpenAI or Azure OpenAI, on the separate live key row", () => {
+ it("offers the Live calls service, OpenAI, Azure OpenAI or Fish Audio, 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"]);
+ expect([...select.options].map((option) => option.value)).toEqual(["openai", "azure", "fish"]);
expect(select.value).toBe("azure");
expect(row("liveKey")!.querySelector('input[type="url"]')).not.toBeNull();
});
@@ -126,6 +126,19 @@ 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 } });
+ page();
+ const fish = row("liveKey")!;
+ expect(fish.textContent).toContain("Fish Audio");
+ expect(fish.textContent).toContain("Required");
+ 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(row("liveCalls")).toBeNull();
+ });
+
it("opens a section that holds a saved key, and counts what is connected", () => {
setConfig({ ...fx.config, box: { configured: true, last4: "c3d4" } });
page();
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
index debd2e30f5..47d4b40122 100644
--- a/src/components/keys/KeysPage.tsx
+++ b/src/components/keys/KeysPage.tsx
@@ -149,8 +149,8 @@ export function KeysPage() {
return () => window.cancelAnimationFrame(frame);
}, [focus]);
- // With Azure chosen, Live calls do not use the OpenAI key that row points at.
- const azureLive = state.config?.live?.provider === "azure";
+ // With Azure or Fish Audio chosen, Live calls do not use the OpenAI key that row points at.
+ const azureLive = state.config?.live?.provider === "azure" || state.config?.live?.provider === "fish";
const rows = KEY_CATALOG.filter((entry) => keyMatches(entry, q) && !(azureLive && entry.id === "liveCalls"));
const sections = KEY_SECTIONS.flatMap((section) => {
const own = rows.filter((entry) => entry.section === section.id);
diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.ts
index 11dca1b735..9471fa5dd6 100644
--- a/src/components/keys/key-catalog.ts
+++ b/src/components/keys/key-catalog.ts
@@ -216,11 +216,15 @@ export function keyEntry(id: KeyId): KeyEntry {
return entry;
}
-/** With Azure OpenAI chosen for Live calls, the row for their key is about the Azure resource: 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. */
export function shownKeyEntry(id: KeyId, config: ConfigStatus | null | undefined): KeyEntry {
const entry = keyEntry(id);
- if (id !== "liveKey" || config?.live?.provider !== "azure" || !entry.target) return entry;
+ 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: "Azure OpenAI", labelKey: "call.live.azureKeyField", purposeKey: "keys.purpose.liveKeyAzure", target: { ...target, placeholder: "…", href: "https://portal.azure.com" } };
}
diff --git a/src/lib/call-mode.ts b/src/lib/call-mode.ts
index edcaafac8a..88299b7170 100644
--- a/src/lib/call-mode.ts
+++ b/src/lib/call-mode.ts
@@ -1,5 +1,6 @@
import { useSyncExternalStore } from "react";
import type { LocaleKey } from "@/locales";
+import type { LiveProvider } from "../../shared/wire";
import { desktopCapabilitiesNow } from "./desktop";
import { t } from "./i18n";
@@ -11,11 +12,23 @@ export const CALL_MODES: ReadonlyArray<{ id: CallMode; label: LocaleKey }> = [
{ id: "live", label: "call.mode.live" },
];
-export function liveDisclosure({ cloudHome = false, azure = false }: { cloudHome?: boolean; azure?: boolean } = {}): string {
+export function liveDisclosure({ cloudHome = false, azure = false, fish = false }: { cloudHome?: boolean; azure?: boolean; fish?: boolean } = {}): string {
if (azure) return t(cloudHome ? "call.live.disclosureAzureCloud" : "call.live.disclosureAzure");
+ if (fish) return t(cloudHome ? "call.live.disclosureFishCloud" : "call.live.disclosureFish");
return t(cloudHome ? "call.live.disclosureCloud" : "call.live.disclosure");
}
+/** The copy about a Live call's key: Azure and Fish Audio need a key of their own, OpenAI can borrow the OpenAI key. */
+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;
+ }
+ if (provider === "fish") {
+ return { title: "call.live.fishKeyTitle", explain: "call.live.fishKeyExplain", field: "call.live.fishKeyField", key: "call.live.fishKey", missing: "call.live.fishNeedsKey", needs: "call.live.needsFish", cost: "call.live.fishCost" } as const;
+ }
+ 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;
+}
+
export function callModeHint(mode: CallMode, where: { cloudHome?: boolean } = {}): string {
if (mode === "live") return `${t("call.mode.liveHint")} ${liveDisclosure(where)}`;
return t(desktopCapabilitiesNow().dictation.engine === "fish-audio" ? "call.mode.turnsHintFish" : "call.mode.turnsHint");
diff --git a/src/lib/live-call-fish.test.ts b/src/lib/live-call-fish.test.ts
new file mode 100644
index 0000000000..6fe6f6fab9
--- /dev/null
+++ b/src/lib/live-call-fish.test.ts
@@ -0,0 +1,258 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { LiveFishRelayCommand, LiveFishTransport } from "../../shared/wire";
+import { DELEGATE_ANSWER_MS, FishCall, FISH_DELEGATE_TOOL, type FishSessionOptions } from "./live-call-fish";
+import { configureLiveMedia, hangUpLiveCall, liveMedia, onServerCall, resetLiveMedia, setLiveMuted, startLiveCall, takeLiveCallAction } from "./live-call-media";
+
+const transport: LiveFishTransport = {
+ type: "fish",
+ relayToken: "relay-token",
+ session: { transport: "livekit", session_id: "sess_1", expires_at: "", max_duration_seconds: 900, livekit_url: "wss://lk.example", token: "jwt" },
+};
+
+class FakeSession {
+ options: FishSessionOptions;
+ sendUserMessage = vi.fn();
+ setMicMuted = vi.fn(async () => {});
+ end = vi.fn(async () => {});
+ constructor(options: FishSessionOptions) { this.options = options; }
+ get on() { return this.options.callbacks; }
+ tool(callId: string) { return this.options.clientTools[FISH_DELEGATE_TOOL]!({}, { callId }); }
+}
+
+/** A relay that records what the call posts and hands each waiting poll the next queued batch. */
+function fakeRelay() {
+ const posted: Array<Record<string, unknown>> = [];
+ const batches: Array<{ commands: LiveFishRelayCommand[]; closed: boolean }> = [];
+ let release: (() => void) | null = null;
+ const request = vi.fn(async (path: string, init?: RequestInit) => {
+ if (path !== "/api/live/relay") throw new Error(`unexpected ${path}`);
+ const body = JSON.parse(String(init?.body)) as Record<string, unknown>;
+ posted.push(body);
+ if (!body.wait) return { commands: [], closed: false };
+ while (!batches.length) await new Promise<void>((resolve) => { release = resolve; });
+ return batches.shift()!;
+ });
+ const answer = (commands: LiveFishRelayCommand[], closed = false) => {
+ batches.push({ commands, closed });
+ release?.();
+ };
+ const events = () => posted.flatMap((body) => (body.events as Array<Record<string, unknown>> | undefined) ?? []);
+ return { request, posted, answer, events };
+}
+
+async function joined(relay = fakeRelay(), clock = { now: 1_000 }) {
+ let session: FakeSession | null = null;
+ const hooks = { request: relay.request as never, connected: vi.fn(), heard: vi.fn(), said: vi.fn(), ended: vi.fn(), now: () => clock.now };
+ const call = new FishCall(transport, hooks, async (options) => (session = new FakeSession(options)));
+ await call.start();
+ return { call, session: session!, hooks, relay, clock };
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe("a Fish Audio call's relay", () => {
+ afterEach(() => vi.useRealTimers());
+
+ it("joins with Fish's session token and only the delegate tool", async () => {
+ const { session } = await joined();
+ expect(session.options.sessionToken).toBe(transport.session);
+ expect(Object.keys(session.options.clientTools)).toEqual(["delegate"]);
+ });
+
+ it("reports joining, finished utterances timed from the start, and the agent's turns, with the relay token", async () => {
+ const { session, relay, hooks, clock } = await joined();
+ session.on.onConnect({ sessionId: "sess_1" });
+ clock.now = 1_200;
+ session.on.onUserTranscript({ segmentId: "u1", text: "book a", final: false });
+ clock.now = 2_000;
+ session.on.onUserTranscript({ segmentId: "u1", text: " book a table ", final: true });
+ session.on.onUserTranscript({ segmentId: "u2", text: " ", final: true });
+ session.on.onModeChange("speaking");
+ clock.now = 2_600;
+ session.on.onModeChange("speaking");
+ session.on.onAgentResponseDelta({ segmentId: "a1", text: "Sure" });
+ clock.now = 3_000;
+ session.on.onModeChange("listening");
+ session.on.onModeChange("listening");
+ await flush();
+ expect(hooks.connected).toHaveBeenCalledTimes(1);
+ expect(hooks.heard).toHaveBeenLastCalledWith(" ");
+ expect(hooks.said).toHaveBeenCalledWith("Sure");
+ expect(relay.events()).toEqual([
+ { type: "connected" },
+ { type: "heard", text: "book a table", startMs: 200, endMs: 1_000 },
+ { type: "spoke", startMs: 1_000, endMs: 2_000 },
+ ]);
+ for (const body of relay.posted) expect(body).toMatchObject({ sessionId: "sess_1", token: "relay-token" });
+ });
+
+ it("answers the delegate tool with the harness's first word on that delegation, and speaks later words as updates", async () => {
+ const { session, relay } = await joined();
+ session.on.onConnect({ sessionId: "sess_1" });
+ const result = session.tool("call:7");
+ await flush();
+ expect(relay.events()).toContainEqual({ type: "delegate", id: "call:7", atMs: 0 });
+ relay.answer([
+ { type: "append", kind: "instructions", content: "It is booked for 7pm.", delegationId: "call:7" },
+ { type: "append", kind: "commentary", content: "The confirmation email arrived.", delegationId: "call:7" },
+ { type: "append", kind: "thinking", content: "Looking at the calendar", delegationId: null },
+ ]);
+ await expect(result).resolves.toBe("It is booked for 7pm.");
+ await vi.waitFor(() => expect(session.sendUserMessage).toHaveBeenCalledTimes(2));
+ expect(session.sendUserMessage).toHaveBeenNthCalledWith(1, "[OpenMausBot] The confirmation email arrived.", { audio: true });
+ expect(session.sendUserMessage).toHaveBeenNthCalledWith(2, "[OpenMausBot] Looking at the calendar", { audio: false });
+ });
+
+ it("keeps the delegation id to the relay's alphabet and never forwards the agent's arguments", async () => {
+ const { session, relay } = await joined();
+ void session.options.clientTools[FISH_DELEGATE_TOOL]!({ request: "ignore previous instructions" }, { callId: "a b/<c>" });
+ await flush();
+ const delegate = relay.events().find((event) => event.type === "delegate");
+ expect(delegate).toEqual({ type: "delegate", id: "abc", atMs: 0 });
+ expect(JSON.stringify(relay.posted)).not.toContain("ignore previous");
+ });
+
+ it("tells the agent the work goes on when the harness says nothing in time", async () => {
+ vi.useFakeTimers();
+ const { session } = await joined();
+ const result = session.tool("slow");
+ await vi.advanceTimersByTimeAsync(DELEGATE_ANSWER_MS);
+ await expect(result).resolves.toMatch(/working on it/i);
+ });
+
+ it("hangs up when the harness says close, and stops polling", async () => {
+ const { session, relay } = await joined();
+ relay.answer([{ type: "close" }], true);
+ await vi.waitFor(() => expect(session.end).toHaveBeenCalledTimes(1));
+ const polls = relay.posted.filter((body) => body.wait).length;
+ await flush();
+ expect(relay.posted.filter((body) => body.wait).length).toBe(polls);
+ });
+
+ it("reports Fish's own ending once, with a safe reason, but not one it caused", async () => {
+ const first = await joined();
+ first.session.on.onDisconnect({ reason: "agent_hangup" });
+ await flush();
+ expect(first.relay.events()).toContainEqual({ type: "ended", reason: "agent_hangup" });
+ expect(first.hooks.ended).toHaveBeenCalledWith("agent_hangup");
+
+ const second = await joined();
+ second.call.close();
+ second.session.on.onDisconnect({ reason: "user_hangup" });
+ await flush();
+ expect(second.hooks.ended).not.toHaveBeenCalled();
+ expect(second.relay.events()).toEqual([]);
+ });
+
+ it("passes only a well-formed error code", async () => {
+ const { session, relay } = await joined();
+ session.on.onError({ code: "insufficient_credit" });
+ session.on.onError({ code: "<script>" });
+ session.on.onError({});
+ await flush();
+ expect(relay.events()).toEqual([{ type: "error", code: "insufficient_credit" }, { type: "error", code: "error" }, { type: "error", code: "error" }]);
+ });
+
+ it("mutes through the SDK, and on close ends the session and releases a waiting delegate", async () => {
+ const { call, session } = await joined();
+ call.setMuted(true);
+ expect(session.setMicMuted).toHaveBeenCalledWith(true);
+ const result = session.tool("pending");
+ call.close();
+ call.close();
+ expect(session.end).toHaveBeenCalledTimes(1);
+ await expect(result).resolves.toMatch(/working on it/i);
+ });
+
+ it("ends a session that joins after the call was closed", async () => {
+ let finish: ((session: FakeSession) => void) | null = null;
+ let made: FakeSession | null = null;
+ const relay = fakeRelay();
+ const call = new FishCall(transport, { request: relay.request as never, connected: vi.fn(), heard: vi.fn(), said: vi.fn(), ended: vi.fn(), now: () => 0 },
+ (options) => new Promise((resolve) => { made = new FakeSession(options); finish = resolve; }));
+ const starting = call.start();
+ await flush();
+ call.close();
+ finish!(made!);
+ await starting;
+ expect(made!.end).toHaveBeenCalledTimes(1);
+ expect(relay.posted).toEqual([]);
+ });
+});
+
+describe("a Fish Audio Live call on screen", () => {
+ const live = { callId: "c1", botId: "b1", threadId: "t1", client: "desktop", voice: "agent", startedAt: 5, status: "connecting" } as const;
+ let relay: ReturnType<typeof fakeRelay>;
+ let session: FakeSession | null;
+ let request: ReturnType<typeof vi.fn>;
+ let startFish: ReturnType<typeof vi.fn>;
+ let getUserMedia: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ vi.stubGlobal("window", { ogb: { speechStop: vi.fn(async () => {}) } });
+ relay = fakeRelay();
+ session = null;
+ request = vi.fn(async (path: string, init?: RequestInit) => {
+ if (path === "/api/live/session") return { call: live, transport };
+ if (path === "/api/live/call/end") return { call: { ...live, status: "ended", endReason: "hung-up" } };
+ return relay.request(path, init);
+ });
+ startFish = vi.fn(async (options: FishSessionOptions) => (session = new FakeSession(options)));
+ getUserMedia = vi.fn();
+ resetLiveMedia();
+ configureLiveMedia({ request: request as never, startFish: startFish as never, getUserMedia: getUserMedia as never, createPeer: vi.fn() as never });
+ });
+ afterEach(() => { resetLiveMedia(); vi.unstubAllGlobals(); });
+
+ it("asks the harness for a Fish session without an offer, and leaves the microphone to Fish's SDK", async () => {
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ const [, init] = request.mock.calls.find(([path]) => path === "/api/live/session")!;
+ expect(JSON.parse(String(init.body))).toEqual({ botId: "b1", threadId: "t1", client: "web" });
+ expect(getUserMedia).not.toHaveBeenCalled();
+ expect(startFish).toHaveBeenCalledTimes(1);
+ expect(liveMedia()).toMatchObject({ phase: "starting", callId: "c1", provider: "fish" });
+ });
+
+ it("goes live once Fish has joined and the harness has attached, with captions from both sides", async () => {
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ onServerCall({ ...live, status: "listening" } as never);
+ expect(liveMedia().phase).toBe("starting");
+ session!.on.onConnect({ sessionId: "sess_1" });
+ expect(liveMedia().phase).toBe("live");
+ session!.on.onUserTranscript({ segmentId: "u", text: "what's on today", final: false });
+ expect(liveMedia().heard).toBe("what's on today");
+ session!.on.onAgentResponseDelta({ segmentId: "a", text: "Two meetings." });
+ expect(liveMedia()).toMatchObject({ caption: "Two meetings.", heard: "" });
+ });
+
+ it("mutes through Fish, and on Hang up ends the Fish session and the harness's call", async () => {
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ setLiveMuted(true);
+ expect(session!.setMicMuted).toHaveBeenCalledWith(true);
+ await hangUpLiveCall();
+ expect(session!.end).toHaveBeenCalledTimes(1);
+ expect(request).toHaveBeenCalledWith("/api/live/call/end", expect.objectContaining({ body: JSON.stringify({ callId: "c1" }) }));
+ expect(liveMedia().phase).toBe("idle");
+ });
+
+ it("explains a microphone Fish was refused, and retries as a Fish call", async () => {
+ startFish.mockRejectedValueOnce(Object.assign(new Error("denied"), { code: "mic_permission_denied" }));
+ configureLiveMedia({ request: request as never, startFish: startFish as never, pageMicrophone: async () => "allowed" });
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ expect(liveMedia()).toMatchObject({ phase: "failed", action: "retry", provider: "fish" });
+ expect(request).toHaveBeenCalledWith("/api/live/call/end", expect.anything());
+ takeLiveCallAction();
+ await vi.waitFor(() => expect(startFish).toHaveBeenCalledTimes(2));
+ });
+
+ it("frees the harness's call when it answers with another service's transport", async () => {
+ request.mockImplementation(async (path: string) => {
+ if (path === "/api/live/session") return { call: live, transport: { type: "webrtc", sdp: "answer" } };
+ return { call: { ...live, status: "ended" } };
+ });
+ await startLiveCall({ botId: "b1", threadId: "t1", provider: "fish" });
+ expect(startFish).not.toHaveBeenCalled();
+ expect(liveMedia().phase).toBe("failed");
+ expect(request).toHaveBeenCalledWith("/api/live/call/end", expect.anything());
+ });
+});
diff --git a/src/lib/live-call-fish.ts b/src/lib/live-call-fish.ts
new file mode 100644
index 0000000000..e610acbb94
--- /dev/null
+++ b/src/lib/live-call-fish.ts
@@ -0,0 +1,230 @@
+// A Fish Audio call: Fish's SDK holds the microphone and the agent's audio; the harness hears the call only through what
+// this relays to POST /api/live/relay, and the bot's replies come back the same way.
+import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport } from "../../shared/wire";
+
+/** The client tool the Fish agent calls to delegate; set up on the agent as a client tool with `expects_response`. */
+export const FISH_DELEGATE_TOOL = "delegate";
+export const FISH_UPDATE_PREFIX = "[OpenMausBot]";
+/** How long a delegate call waits for the harness's first word on it; later words arrive as updates. */
+export const DELEGATE_ANSWER_MS = 8_000;
+const CLIENT_TOOL_TIMEOUT_MS = 12_000;
+const MAX_EVENTS_PER_POST = 20;
+const MAX_TEXT = 2_000;
+const RETRY_MS = 1_000;
+const MAX_POLL_FAILURES = 5;
+
+/** The part of `@fishaudio/agent-client` 1.x `AgentSession` a call uses. */
+export interface FishAgentSession {
+ sendUserMessage(text: string, options?: { audio?: boolean }): void;
+ setMicMuted(muted: boolean): Promise<void>;
+ end(): Promise<void>;
+}
+
+export interface FishSessionOptions {
+ sessionToken: LiveFishSessionToken;
+ clientTools: Record<string, (params: Record<string, unknown>, context: { callId: string }) => Promise<unknown>>;
+ clientToolTimeoutMs: number;
+ callbacks: {
+ onConnect(event: { sessionId: string }): void;
+ onDisconnect(event: { reason: string }): void;
+ onModeChange(mode: string): void;
+ onUserTranscript(event: { segmentId: string; text: string; final: boolean }): void;
+ onAgentResponseDelta(event: { segmentId: string; text: string }): void;
+ onError(error: { code?: string }): void;
+ };
+}
+
+export type FishSessionStarter = (options: FishSessionOptions) => Promise<FishAgentSession>;
+
+/** Loaded on the first Fish call only. */
+export const startFishAgentSession: FishSessionStarter = async (options) => {
+ const { AgentSession } = await import("@fishaudio/agent-client");
+ return AgentSession.start(options);
+};
+
+export function isFishMicDenied(error: unknown): boolean {
+ return typeof error === "object" && error !== null && (error as { code?: unknown }).code === "mic_permission_denied";
+}
+
+export interface FishCallHooks {
+ request<T>(path: string, init?: RequestInit & { timeoutMs?: number }): Promise<T>;
+ connected(): void;
+ /** What the person is saying, for the caption. */
+ heard(text: string): void;
+ /** What the agent is saying, for the caption. */
+ said(text: string): void;
+ /** Fish ended the session. */
+ ended(reason: string): void;
+ now(): number;
+}
+
+type RelayAnswer = { commands: LiveFishRelayCommand[]; closed: boolean };
+
+export class FishCall {
+ private readonly transport: LiveFishTransport;
+ private readonly hooks: FishCallHooks;
+ private readonly starter: FishSessionStarter;
+ private readonly startedAt: number;
+ private session: FishAgentSession | null = null;
+ private closed = false;
+ private outbox: LiveFishRelayEvent[] = [];
+ private flushing: Promise<void> | null = null;
+ private readonly segmentStarts = new Map<string, number>();
+ private speakingSince: number | null = null;
+ private readonly waiting = new Map<string, (content: string | null) => void>();
+
+ constructor(transport: LiveFishTransport, hooks: FishCallHooks, starter: FishSessionStarter = startFishAgentSession) {
+ this.transport = transport;
+ this.hooks = hooks;
+ this.starter = starter;
+ this.startedAt = hooks.now();
+ }
+
+ /** Joins the session; rejects as Fish's SDK does, e.g. with code `mic_permission_denied`. */
+ async start(): Promise<void> {
+ const session = await this.starter({
+ sessionToken: this.transport.session,
+ clientTools: { [FISH_DELEGATE_TOOL]: (_params, context) => this.delegate(context.callId) },
+ clientToolTimeoutMs: CLIENT_TOOL_TIMEOUT_MS,
+ callbacks: {
+ onConnect: () => {
+ this.relay({ type: "connected" });
+ this.hooks.connected();
+ },
+ onDisconnect: ({ reason }) => {
+ if (this.closed) return;
+ this.relay({ type: "ended", reason: /^[a-z_]{0,40}$/.test(reason) ? reason : "" });
+ this.hooks.ended(reason);
+ },
+ onModeChange: (mode) => this.onMode(mode),
+ onUserTranscript: (event) => this.onTranscript(event),
+ onAgentResponseDelta: (event) => this.hooks.said(event.text),
+ onError: (error) => this.relay({ type: "error", code: /^[\w.-]{1,40}$/.test(error.code ?? "") ? error.code! : "error" }),
+ },
+ });
+ if (this.closed) {
+ void session.end().catch(() => undefined);
+ return;
+ }
+ this.session = session;
+ void this.pollLoop();
+ }
+
+ setMuted(muted: boolean): void {
+ void this.session?.setMicMuted(muted).catch(() => undefined);
+ }
+
+ /** Ends the Fish session and stops relaying. */
+ close(): void {
+ if (this.closed) return;
+ this.closed = true;
+ for (const resolve of this.waiting.values()) resolve(null);
+ this.waiting.clear();
+ const session = this.session;
+ this.session = null;
+ void session?.end().catch(() => undefined);
+ }
+
+ private now(): number {
+ return Math.max(0, this.hooks.now() - this.startedAt);
+ }
+
+ private onTranscript(event: { segmentId: string; text: string; final: boolean }): void {
+ if (!this.segmentStarts.has(event.segmentId)) this.segmentStarts.set(event.segmentId, this.now());
+ this.hooks.heard(event.text);
+ if (!event.final) return;
+ const startMs = this.segmentStarts.get(event.segmentId)!;
+ this.segmentStarts.delete(event.segmentId);
+ const text = event.text.trim().slice(0, MAX_TEXT);
+ if (text) this.relay({ type: "heard", text, startMs, endMs: Math.max(startMs, this.now()) });
+ }
+
+ private onMode(mode: string): void {
+ if (mode === "speaking") {
+ this.speakingSince ??= this.now();
+ return;
+ }
+ if (this.speakingSince === null) return;
+ this.relay({ type: "spoke", startMs: this.speakingSince, endMs: this.now() });
+ this.speakingSince = null;
+ }
+
+ /** The harness reads the request from what it heard, never from the agent's arguments. */
+ private delegate(callId: string): Promise<unknown> {
+ const id = callId.replace(/[^\w.:-]/g, "").slice(0, 120) || `d${this.hooks.now()}`;
+ const answer = new Promise<string | null>((resolve) => {
+ const timer = setTimeout(() => {
+ if (this.waiting.get(id) === done) this.waiting.delete(id);
+ resolve(null);
+ }, DELEGATE_ANSWER_MS);
+ const done = (content: string | null) => {
+ clearTimeout(timer);
+ resolve(content);
+ };
+ this.waiting.set(id, done);
+ });
+ this.relay({ type: "delegate", id, atMs: this.now() });
+ return answer.then((content) => content ?? "I am working on it; the result will follow as an update.");
+ }
+
+ private relay(event: LiveFishRelayEvent): void {
+ if (this.closed) return;
+ this.outbox.push(event);
+ this.flushing ??= this.flush().finally(() => {
+ this.flushing = null;
+ });
+ }
+
+ private async flush(): Promise<void> {
+ await Promise.resolve();
+ while (this.outbox.length && !this.closed) {
+ const events = this.outbox.splice(0, MAX_EVENTS_PER_POST);
+ try {
+ this.apply(await this.post({ events }));
+ } catch {
+ return;
+ }
+ }
+ }
+
+ private async pollLoop(): Promise<void> {
+ let failures = 0;
+ while (!this.closed) {
+ try {
+ const answer = await this.post({ wait: true });
+ failures = 0;
+ this.apply(answer);
+ if (answer.closed) return;
+ } catch {
+ if (++failures >= MAX_POLL_FAILURES) return;
+ await new Promise((resolve) => setTimeout(resolve, RETRY_MS));
+ }
+ }
+ }
+
+ private post(body: { events?: LiveFishRelayEvent[]; wait?: boolean }): Promise<RelayAnswer> {
+ return this.hooks.request<RelayAnswer>("/api/live/relay", {
+ method: "POST",
+ body: JSON.stringify({ sessionId: this.transport.session.session_id, token: this.transport.relayToken, ...body }),
+ timeoutMs: 25_000,
+ });
+ }
+
+ private apply(answer: RelayAnswer): void {
+ for (const command of answer.commands ?? []) {
+ if (this.closed) return;
+ if (command.type === "close") {
+ this.close();
+ return;
+ }
+ const waiter = command.delegationId ? this.waiting.get(command.delegationId) : undefined;
+ if (waiter) {
+ this.waiting.delete(command.delegationId!);
+ waiter(command.content);
+ continue;
+ }
+ // A status note is for the agent to know, not to read out.
+ this.session?.sendUserMessage(`${FISH_UPDATE_PREFIX} ${command.content}`, { audio: command.kind !== "thinking" });
+ }
+ }
+}
diff --git a/src/lib/live-call-media.ts b/src/lib/live-call-media.ts
index 7cacd36da6..032b0f0e1e 100644
--- a/src/lib/live-call-media.ts
+++ b/src/lib/live-call-media.ts
@@ -1,10 +1,11 @@
// 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 } from "../../shared/wire";
+import type { LiveCallState, LiveEndReason, LiveFishTransport, LiveProvider } from "../../shared/wire";
import { api, ApiError } from "@/state/store";
import { openExternalLink } from "./app-links";
import { endCall, startCall } from "./call";
import { desktopCapabilitiesNow } from "./desktop";
+import { FishCall, isFishMicDenied, startFishAgentSession, type FishSessionStarter } from "./live-call-fish";
import { t } from "./i18n";
export type LiveMediaPhase = "idle" | "starting" | "live" | "ending" | "ended" | "failed";
@@ -20,6 +21,7 @@ export interface LiveMediaState {
callId: string | null;
botId: string | null;
threadId: string | null;
+ provider?: LiveProvider;
startedAt: number | null;
muted: boolean;
caption: string;
@@ -43,6 +45,7 @@ export interface LiveMediaDeps {
capabilities(): DesktopCapabilities;
pageMicrophone(): Promise<"allowed" | "refused" | undefined>;
openInBrowser(url: string): void;
+ startFish: FishSessionStarter;
}
const IDLE: LiveMediaState = {
@@ -87,6 +90,7 @@ const defaults: LiveMediaDeps = {
}
},
openInBrowser: (url) => void openExternalLink(url).catch(() => undefined),
+ startFish: startFishAgentSession,
};
let deps: LiveMediaDeps = defaults;
@@ -95,6 +99,8 @@ let generation = 0;
let microphone: MediaStream | null = null;
let peer: RTCPeerConnection | null = null;
let channel: RTCDataChannel | null = null;
+let fishCall: FishCall | null = null;
+let fishConnected = false;
let heardTimer: ReturnType<typeof setTimeout> | null = null;
let noticeTimer: ReturnType<typeof setTimeout> | null = null;
let closeTimer: ReturnType<typeof setTimeout> | null = null;
@@ -177,14 +183,17 @@ function liveClient(capabilities: DesktopCapabilities): "desktop" | "web" {
return inWebBrowser(capabilities) ? "web" : "desktop";
}
-export async function startLiveCall(target: { botId: string; threadId: string }): Promise<void> {
+/** `provider` is the service Call settings chose; the harness refuses a call that does not match it. */
+export async function startLiveCall(target: { botId: string; threadId: string; provider?: LiveProvider }): Promise<void> {
if (isLiveCallRunning(state.phase)) return;
release();
const mine = ++generation;
serverAttached = false;
- set({ ...IDLE, phase: "starting", botId: target.botId, threadId: target.threadId });
+ const where = { botId: target.botId, threadId: target.threadId, ...(target.provider ? { provider: target.provider } : {}) };
+ set({ ...IDLE, phase: "starting", ...where });
startCall(target.botId);
try {
+ if (target.provider === "fish") 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;
@@ -246,11 +255,11 @@ export async function startLiveCall(target: { botId: string; threadId: string })
const body = error instanceof ApiError ? (error.body as { needsKey?: boolean; activeCall?: LiveCallState } | undefined) : undefined;
if (state.callId) void endOnServer(state.callId);
release();
- if (body?.needsKey) return set({ ...IDLE, needsKey: true, botId: target.botId, threadId: target.threadId });
- if (body?.activeCall) return set({ ...IDLE, phase: "failed", botId: target.botId, threadId: target.threadId, busyWith: body.activeCall, notice: busyText(body.activeCall) });
- const failed = { ...IDLE, phase: "failed" as const, botId: target.botId, threadId: target.threadId };
+ if (body?.needsKey) return set({ ...IDLE, needsKey: true, ...where });
+ if (body?.activeCall) return set({ ...IDLE, phase: "failed", ...where, busyWith: body.activeCall, notice: busyText(body.activeCall) });
+ const failed = { ...IDLE, phase: "failed" as const, ...where };
if (error instanceof DOMException && error.name === "NotFoundError") return set({ ...failed, notice: t("call.live.micMissing"), action: "retry" });
- if (error instanceof DOMException && error.name === "NotAllowedError") {
+ if ((error instanceof DOMException && error.name === "NotAllowedError") || isFishMicDenied(error)) {
const pageMic = await deps.pageMicrophone();
if (mine !== generation) return;
return set({ ...failed, ...micBlocked(deps.capabilities(), pageMic) });
@@ -260,6 +269,50 @@ export async function startLiveCall(target: { botId: string; threadId: string })
}
}
+/** Fish's SDK opens the microphone and plays the agent itself; the harness follows the call through the relay. */
+async function startFishCall(target: { botId: string; threadId: string }, mine: number): Promise<void> {
+ const result = await deps.request<{ call: LiveCallState; transport: LiveFishTransport | { type: "webrtc" } }>("/api/live/session", {
+ method: "POST",
+ body: JSON.stringify({ botId: target.botId, threadId: target.threadId, client: liveClient(deps.capabilities()) }),
+ timeoutMs: 35_000,
+ });
+ if (mine !== generation) {
+ void endOnServer(result.call.callId);
+ return;
+ }
+ const seen = serverCall;
+ set({ callId: result.call.callId });
+ if (result.transport.type !== "fish") throw new Error(t("call.live.dropped"));
+ applyServerCall(result.call);
+ if (seen?.callId === result.call.callId) applyServerCall(seen);
+ if (mine !== generation) return;
+ const call = new FishCall(result.transport, {
+ request: deps.request,
+ connected: () => {
+ if (mine !== generation) return;
+ fishConnected = true;
+ stopConnectWait();
+ goLiveWhenReady();
+ },
+ heard: (text) => {
+ if (mine === generation) showHeard(text.slice(-HEARD_CHARS));
+ },
+ said: (text) => {
+ if (mine === generation) set({ caption: text.slice(-CAPTION_CHARS), heard: "" });
+ },
+ ended: () => {
+ if (mine === generation) onSessionClosed();
+ },
+ now: () => Date.now(),
+ }, deps.startFish);
+ fishCall = call;
+ connectTimer = setTimeout(() => {
+ if (mine === generation) void dropped(t("call.live.droppedNoAudio"));
+ }, MEDIA_CONNECT_TIMEOUT_MS);
+ await call.start();
+ if (mine === generation && state.muted) call.setMuted(true);
+}
+
export async function hangUpLiveCall(): Promise<void> {
const { callId, phase } = state;
if (phase === "idle" || phase === "ended" || phase === "failed") return dismissLiveNotice();
@@ -276,6 +329,7 @@ export async function hangUpLiveCall(): Promise<void> {
export function setLiveMuted(muted: boolean): void {
for (const track of microphone?.getAudioTracks() ?? []) track.enabled = !muted;
+ fishCall?.setMuted(muted);
set({ muted });
}
@@ -309,9 +363,9 @@ export function dismissStartPrompt(botId: string): void {
}
export function takeLiveCallAction(): void {
- const { action, botId, threadId, phase } = state;
+ const { action, botId, threadId, phase, provider } = state;
if (phase !== "failed") return;
- if (action === "retry" && botId && threadId) void startLiveCall({ botId, threadId });
+ if (action === "retry" && botId && threadId) void startLiveCall({ botId, threadId, provider });
else if (action === "open-in-browser" && globalThis.location?.href) deps.openInBrowser(globalThis.location.href);
}
@@ -368,7 +422,7 @@ function applyServerCall(call: LiveCallState | null) {
}
function goLiveWhenReady() {
- if (state.phase !== "starting" || !serverAttached || channel?.readyState !== "open") return;
+ if (state.phase !== "starting" || !serverAttached || (channel?.readyState !== "open" && !fishConnected)) return;
set({ phase: "live", startedAt: Date.now() });
}
@@ -382,9 +436,9 @@ function finish(notice: { text: string; dropped: boolean }, detail?: string) {
sendClose();
release();
generation += 1;
- const { botId, threadId } = state;
+ const { botId, threadId, provider } = state;
set({
- ...IDLE, phase: notice.dropped ? "failed" : "ended", botId, threadId,
+ ...IDLE, phase: notice.dropped ? "failed" : "ended", botId, threadId, ...(provider ? { provider } : {}),
notice: detail?.trim() || notice.text, action: notice.dropped ? "retry" : null,
});
if (!notice.dropped) {
@@ -409,20 +463,24 @@ function onChannelMessage(raw: unknown) {
} catch {
return;
}
- if (event.type === "session.closed") {
- stopCapturing();
- stopConnectWait();
- if (!closeTimer) void checkLiveSignIn();
- closeTimer ??= setTimeout(() => finish({ text: t("call.live.ended"), dropped: false }), SERVER_CLOSE_GRACE_MS);
- return;
- }
+ if (event.type === "session.closed") return onSessionClosed();
const next = applyCaption(state, event);
if (next.caption === state.caption && next.heard === state.heard) return;
- set(next);
- if (event.type === "session.input_transcript.delta") {
- if (heardTimer) clearTimeout(heardTimer);
- heardTimer = setTimeout(() => set({ heard: "" }), HEARD_CLEAR_MS);
- }
+ if (event.type === "session.input_transcript.delta") showHeard(next.heard);
+ else set(next);
+}
+
+function onSessionClosed() {
+ stopCapturing();
+ stopConnectWait();
+ if (!closeTimer) void checkLiveSignIn();
+ closeTimer ??= setTimeout(() => finish({ text: t("call.live.ended"), dropped: false }), SERVER_CLOSE_GRACE_MS);
+}
+
+function showHeard(heard: string) {
+ set({ heard });
+ if (heardTimer) clearTimeout(heardTimer);
+ heardTimer = setTimeout(() => set({ heard: "" }), HEARD_CLEAR_MS);
}
/** Autoplay was blocked: the next click or key press plays the audio (a user gesture allows play()). */
@@ -464,6 +522,9 @@ function sendClose() {
function stopCapturing() {
microphone?.getTracks().forEach((track) => track.stop());
microphone = null;
+ fishCall?.close();
+ fishCall = null;
+ fishConnected = false;
}
function release() {
diff --git a/src/locales/en.json b/src/locales/en.json
index a36e21f1c4..955fdae958 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -6764,6 +6764,18 @@
"call.live.needsAzure": "Live calls through Azure OpenAI need the resource endpoint, the GPT-Live deployment name and its key.",
"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.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.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.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.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.",
"settings.group.you": "You",
"settings.group.ai": "AI",
@@ -7888,6 +7900,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.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",