Skip to content

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

#5512: move the Fish Live call wiring out of server/index.ts

milind-sonibf10495ff8c1
diff --git a/server/index.ts b/server/index.ts
index 060980e2fa..098e13b730 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -319,10 +319,9 @@ import * as tts from "./tts/index.ts";
import { voiceNoteFailure } from "./tts/errors.ts";
import { createDecider, deciderReady, describeDecider } from "./decider/index.ts"; import { createExtractor, describeHelpers } from "./extractor/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 { 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 { liveHistoryFrom, LiveSessionError, type LiveBot, type LiveHistoryMessage } from "./live-call.ts";
+import { LiveCallController, LiveCallSignedOutError } from "./live-call-controller.ts"; import { liveSessionWiring } from "./live-session-wiring.ts";
+import { liveCallSettings, liveSettingsFor, liveSettingsForClient, saveLiveSettings } from "./live-settings.ts"; import { azureLiveCallRefusal, 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";
@@ -12468,7 +12467,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 liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveFishAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); } });
const liveCalls = new LiveCallController({
store,
send: async ({ auth, botId, threadId, text, callId }) => {
@@ -12502,15 +12501,7 @@ const liveCalls = new LiveCallController({
broadcast: (frame) => broadcast(frame, { adminOnly: true }),
settings: () => liveCallSettings(cfg),
azureRefusal: (auth) => azureLiveCallRefusal(auth, { othersOnLoopback: adminActivityRecording() }),
- 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),
+ ...liveWiring.calls,
speakable: (text) => toUtterances(text),
// One "call" row per call: its id, times and length, never anything said on it.
recordCall: (input) => {
@@ -12548,7 +12539,7 @@ ROUTES.push(createLiveRoutes({
return { botId: bot.id, botName: bot.name, threadId: target };
},
settings: () => liveSettingsFor(cfg),
- fishRelay: (sessionId, token) => fishRelays.find(sessionId, token),
+ fishRelay: liveWiring.fishRelay,
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-session-wiring.test.ts b/server/live-session-wiring.test.ts
new file mode 100644
index 0000000000..0895ede2f7
--- /dev/null
+++ b/server/live-session-wiring.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it, vi } from "vitest";
+import { fishKeyPrint, fishLiveEndpoint } from "./live-fish.ts";
+import { liveSessionWiring } from "./live-session-wiring.ts";
+
+const TOKEN = { transport: "livekit", session_id: "sess_1", expires_at: "x", max_duration_seconds: 900, livekit_url: "wss://lk.fish.audio", token: "jwt" };
+
+function fakeFish({ goneAgents = [] as string[] } = {}) {
+ return vi.fn(async (url: string | URL | Request, init?: RequestInit) => {
+ const route = `${init!.method} ${String(url).replace("https://api.fish.audio/v1/agent", "")}`;
+ if (route === "POST /sessions") {
+ const agent = JSON.parse(String(init!.body)).agent_id as string;
+ return goneAgents.includes(agent) ? new Response("{}", { status: 404 }) : new Response(JSON.stringify(TOKEN), { status: 201 });
+ }
+ const answers: Record<string, unknown> = { "POST /tools": { tool_id: "tool_1" }, "POST /agents": { agent_id: "agent_new" } };
+ return new Response(JSON.stringify(answers[route] ?? {}), { status: 200 });
+ });
+}
+
+function wiring(fetchImpl: typeof fetch, env: NodeJS.ProcessEnv = {}) {
+ const saveFishAgent = vi.fn();
+ const wired = liveSessionWiring({ bot: () => ({ name: "Rigel" }), history: () => [], cloudHome: false, othersOnLoopback: () => false, saveFishAgent, env, fetchImpl });
+ return { ...wired, saveFishAgent };
+}
+
+const start = { key: "fish-key", sdp: "", botId: "b1", threadId: "t1", voice: "agent" };
+const routes = (fetchImpl: ReturnType<typeof fakeFish>) => fetchImpl.mock.calls.map(([url, init]) => `${init!.method} ${String(url).replace("https://api.fish.audio/v1/agent", "")}`);
+
+describe("a Fish Audio call's session", () => {
+ it("sets up an agent on the first call, saves it for that key's account, and answers with a relay", async () => {
+ const fetchImpl = fakeFish();
+ const w = wiring(fetchImpl);
+ const answer = await w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("", {}) });
+ expect(routes(fetchImpl)).toEqual(["POST /tools", "POST /agents", "PATCH /agents/agent_new", "POST /agents/agent_new/publish", "POST /sessions"]);
+ expect(w.saveFishAgent).toHaveBeenCalledWith({ fishAgentId: "agent_new", fishAgentFor: fishKeyPrint("fish-key") });
+ expect(answer).toMatchObject({ sessionId: "sess_1", fish: { type: "fish", session: TOKEN } });
+ const relayToken = (answer as { fish: { relayToken: string } }).fish.relayToken;
+ expect(w.fishRelay("sess_1", relayToken)).not.toBeNull();
+ expect(w.fishRelay("sess_1", "guessed")).toBeNull();
+ });
+
+ it("starts the saved agent without setting one up", async () => {
+ const fetchImpl = fakeFish();
+ const w = wiring(fetchImpl);
+ await w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_saved", {}) });
+ expect(routes(fetchImpl)).toEqual(["POST /sessions"]);
+ expect(w.saveFishAgent).not.toHaveBeenCalled();
+ });
+
+ it("sets up a new agent once when the saved one is gone on Fish Audio", async () => {
+ const fetchImpl = fakeFish({ goneAgents: ["agent_saved"] });
+ const w = wiring(fetchImpl);
+ await expect(w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_saved", {}) })).resolves.toMatchObject({ sessionId: "sess_1" });
+ expect(routes(fetchImpl)).toEqual(["POST /sessions", "POST /tools", "POST /agents", "PATCH /agents/agent_new", "POST /agents/agent_new/publish", "POST /sessions"]);
+ expect(w.saveFishAgent).toHaveBeenCalledTimes(1);
+ });
+
+ it("never replaces an agent the operator chose", async () => {
+ const fetchImpl = fakeFish({ goneAgents: ["agent_op"] });
+ const w = wiring(fetchImpl, { OMB_FISH_LIVE_AGENT_ID: "agent_op" });
+ await expect(w.calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_op", {}) })).rejects.toMatchObject({ status: 502 });
+ expect(routes(fetchImpl)).toEqual(["POST /sessions"]);
+ expect(w.saveFishAgent).not.toHaveBeenCalled();
+ });
+
+ it("follows the call through its relay, not a socket to Fish", () => {
+ const w = wiring(fakeFish());
+ const endpoint = fishLiveEndpoint("agent_1", {});
+ expect(w.calls.attachUrl("sess_9", endpoint)).toBe("sess_9");
+ expect(() => w.calls.openSocket("sess_9", "k", endpoint)).toThrow("no relay for that session");
+ });
+});
diff --git a/server/live-session-wiring.ts b/server/live-session-wiring.ts
new file mode 100644
index 0000000000..f7a205c010
--- /dev/null
+++ b/server/live-session-wiring.ts
@@ -0,0 +1,66 @@
+import type { LiveCallDeps } from "./live-call-controller.ts";
+import { openLiveSocket } from "./live-call-controller.ts";
+import { createLiveSession, liveAttachUrl, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";
+import { fishLiveCallRefusal } from "./live-access.ts";
+import type { LiveConfig } from "./live-config.ts";
+import { createFishLiveSession, endFishLiveSession, fishKeyPrint, FishRelays, setUpFishAgent } from "./live-fish.ts";
+import type { LiveRouteDeps } from "./routes/live.ts";
+
+export interface LiveSessionWiringInput {
+ bot(botId: string): LiveBot;
+ history(threadId: string): LiveHistoryMessage[];
+ cloudHome: boolean;
+ othersOnLoopback(): boolean;
+ /** Saves the Fish Audio agent the harness set up, with the account it belongs to. */
+ saveFishAgent(agent: Required<Pick<LiveConfig, "fishAgentId" | "fishAgentFor">>): void;
+ env?: NodeJS.ProcessEnv;
+ fetchImpl?: typeof fetch;
+}
+
+/** How a Live call's session starts and is followed, per provider: GPT-Live's WebRTC session and sideband on OpenAI or
+ * Azure, or a Fish Audio agent session followed through its client's relay. */
+export function liveSessionWiring(input: LiveSessionWiringInput): {
+ calls: Pick<LiveCallDeps, "fishRefusal" | "createSession" | "openSocket" | "attachUrl">;
+ fishRelay: LiveRouteDeps["fishRelay"];
+} {
+ const relays = new FishRelays();
+ const env = input.env ?? process.env;
+ const fetchImpl = input.fetchImpl ?? fetch;
+
+ const setUpAgent = async (key: string, endpoint: LiveEndpoint): Promise<LiveEndpoint> => {
+ const fishAgentId = await setUpFishAgent(key, endpoint, fetchImpl);
+ input.saveFishAgent({ fishAgentId, fishAgentFor: fishKeyPrint(key) });
+ return { ...endpoint, model: fishAgentId };
+ };
+
+ const startFish = async (key: string, endpoint: LiveEndpoint, botId: string, threadId: string) => {
+ const session = { key, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl };
+ let agent = endpoint.model ? endpoint : await setUpAgent(key, endpoint);
+ try {
+ return { agent, token: await createFishLiveSession({ ...session, endpoint: agent }) };
+ } catch (error) {
+ // An agent removed on Fish Audio is set up again, unless the operator chose it.
+ const gone = (error as { fishStatus?: number }).fishStatus === 404 && endpoint.model !== "" && !env.OMB_FISH_LIVE_AGENT_ID?.trim();
+ if (!gone) throw error;
+ agent = await setUpAgent(key, endpoint);
+ return { agent, token: await createFishLiveSession({ ...session, endpoint: agent }) };
+ }
+ };
+
+ return {
+ fishRelay: (sessionId, token) => relays.find(sessionId, token),
+ calls: {
+ fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),
+ createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {
+ if (endpoint.provider !== "fish") {
+ return createLiveSession({ key, endpoint, sdp, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });
+ }
+ const { agent, token: session } = await startFish(key, endpoint, botId, threadId);
+ const { token } = relays.open(session.session_id, () => endFishLiveSession(session.session_id, key, agent, fetchImpl));
+ return { sessionId: session.session_id, fish: { type: "fish", session, relayToken: token } };
+ },
+ openSocket: (url, key, endpoint) => endpoint.provider === "fish" ? relays.socket(url) : openLiveSocket(url, key, endpoint),
+ attachUrl: (sessionId, endpoint) => endpoint.provider === "fish" ? sessionId : liveAttachUrl(sessionId, endpoint),
+ },
+ };
+}