Skip to content

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

10.6 KB
Raw Blame
// 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 { LiveFishRelayCommand, LiveFishRelayEvent, LiveProvider, LiveSettings } from "../../shared/wire.ts";
import { GEMINI_LIVE_VOICE_OPTIONS, liveHistoryLimitError, parseGeminiLiveModel } from "../../shared/live-call.ts";
import { azureLiveDeployment, azureOpenAiRoot, customLiveApiBase, customLiveModel, LiveSessionError, MAX_SDP_BYTES } from "../live-call.ts";
import { LIVE_STANDBY_IDLE_SECONDS_MAX, LIVE_STANDBY_IDLE_SECONDS_MIN } from "../live-config.ts";
import { LiveCallBusyError, type LiveCallController } from "../live-call-controller.ts";
import { LIVE_CODEX_REFUSAL } from "../live-access.ts";
import { RELAY_POLL_MS } from "../live-fish.ts";
import { PASS, type RouteContext, type RouteHandler } from "./table.ts";

export interface LiveRouteDeps {
  calls: Pick<LiveCallController, "start" | "end" | "current" | "deviceRevoked"> & Partial<Pick<LiveCallController, "codexRefusal">>;
  /** The companion unpaired this phone: its closed-app alerts end too. */
  deviceRevoked?: (device: string) => void;
  resolveTarget(botId: string, threadId: string | undefined): { botId: string; botName: string; threadId: string } | null;
  settings(): LiveSettings;
  saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; customEndpoint?: string; customModel?: string; voice?: string; geminiVoice?: string; geminiModel?: string; readTypedReplies?: boolean; idleMinutes?: number; standby?: boolean; standbyIdleSeconds?: number; historyMessages?: number; historyMessageChars?: number; historyTotalChars?: number }): Promise<LiveSettings>;
  /** A running relayed (Fish Audio, Gemini or ElevenLabs) call's relay, only for the token its start answered with. */
  fishRelay(sessionId: string, token: string): { receive(events: LiveFishRelayEvent[], from?: number): void; poll(waitMs: number): Promise<{ commands: LiveFishRelayCommand[]; closed: boolean }> } | null;
}

const id = z.string().regex(/^[\w-]{1,120}$/);
const sessionBody = z.object({
  botId: id,
  threadId: id.optional(),
  // Not trimmed: the SDP offer goes to OpenAI byte for byte. Absent on a relayed call, which has no offer.
  sdp: z.string().min(1).refine((sdp) => Buffer.byteLength(sdp) <= MAX_SDP_BYTES).optional(),
  client: z.enum(["desktop", "web", "ios", "android"]),
  // The relayed sessions a phone app runs itself (Gemini Live); a phone that sends none keeps being sent to the desktop app.
  relays: z.array(z.enum(["gemini"])).max(4).optional(),
}).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(),
  from: z.number().int().min(0).max(1_000_000).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", "fish", "gemini", "elevenlabs", "custom", "codex"]).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(),
  // The same for a custom endpoint: https, or http only on this computer's loopback.
  customEndpoint: z.string().trim().max(300).refine((url) => url === "" || customLiveApiBase(url) !== null).optional(),
  customModel: z.string().trim().max(64).refine((name) => name === "" || customLiveModel(name) === name).optional(),
  voice: z.string().trim().max(40).regex(/^[a-z]*$/).optional(),
  // "" goes back to the default voice.
  geminiVoice: z.string().trim().refine((name) => name === "" || GEMINI_LIVE_VOICE_OPTIONS.some((option) => option.id === name)).optional(),
  // "" goes back to the default model.
  geminiModel: z.string().trim().max(80).transform((name) => name.replace(/^models\//, "")).refine((name) => name === "" || parseGeminiLiveModel(name) !== undefined).optional(),
  readTypedReplies: z.boolean().optional(),
  idleMinutes: z.number().int().min(1).max(60).optional(),
  standby: z.boolean().optional(),
  standbyIdleSeconds: z.number().int().min(LIVE_STANDBY_IDLE_SECONDS_MIN).max(LIVE_STANDBY_IDLE_SECONDS_MAX).optional(),
  historyMessages: z.number().int().min(0).max(200).optional(),
  historyMessageChars: z.number().int().min(100).max(12_000).optional(),
  historyTotalChars: z.number().int().min(500).max(60_000).optional(),
}).strict();

const DEVICE_ID = /^[\w-]{1,128}$/;

/** The companion sends its own id for the phone that authenticated, never one the phone chose. */
function companionDevice(req: IncomingMessage): string | undefined {
  if (req.headers["x-openmausbot-companion"] !== "1") return undefined;
  const device = req.headers["x-openmausbot-companion-device"];
  return typeof device === "string" && DEVICE_ID.test(device) ? device : undefined;
}

async function bodyOf(req: IncomingMessage, readBody: RouteContext["readBody"]): Promise<unknown> {
  try {
    return await readBody(req);
  } catch {
    return undefined;
  }
}

export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {
  return async ({ req, res, path, method, auth, json, readBody }) => {
    if (!path.startsWith("/api/live/")) return PASS;

    if (method === "POST" && path === "/api/live/session") {
      const parsed = sessionBody.safeParse(await bodyOf(req, readBody));
      if (!parsed.success) return json(res, 400, { error: "The call request was not valid." });
      const target = deps.resolveTarget(parsed.data.botId, parsed.data.threadId);
      if (!target) return json(res, 404, { error: "That bot or chat does not exist." });
      try {
        const device = companionDevice(req);
        const started = await deps.calls.start({ auth, ...(device ? { device } : {}), ...target, client: parsed.data.client, ...(parsed.data.sdp ? { sdp: parsed.data.sdp } : {}),
          ...(parsed.data.relays ? { relays: parsed.data.relays } : {}) });
        return json(res, 201, { call: started.call, transport: started.fish ?? started.gemini ?? started.elevenlabs ?? { type: "webrtc", sdp: started.sdp } });
      } catch (error) {
        if (error instanceof LiveCallBusyError) return json(res, 409, { error: error.message, activeCall: error.call });
        if (error instanceof LiveSessionError) {
          return json(res, error.status, error.status === 409 ? { error: error.message, needsKey: true } : { error: error.message });
        }
        throw error;
      }
    }

    if (method === "POST" && path === "/api/live/call/end") {
      const parsed = endBody.safeParse(await bodyOf(req, readBody));
      if (!parsed.success) return json(res, 400, { error: "The request was not valid." });
      const call = await deps.calls.end(parsed.data.callId);
      return call ? json(res, 200, { call }) : json(res, 404, { error: "That call is not running." });
    }

    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, parsed.data.from);
      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);
      if (!device) return json(res, 400, { error: "The unpaired phone was not named." });
      deps.deviceRevoked?.(device);
      return json(res, 200, { call: deps.calls.deviceRevoked(device) });
    }

    if (method === "PATCH" && path === "/api/live/settings") {
      const parsed = settingsBody.safeParse(await bodyOf(req, readBody));
      if (!parsed.success) {
        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 === "customEndpoint") return json(res, 400, { error: "The custom endpoint must be an https address, like https://gateway.example.com/v1, or http only on this computer (127.0.0.1 or localhost)." });
        if (field === "customModel") return json(res, 400, { error: "The model may use letters, digits, '-', '_', '.', ':' and '/', up to 64 characters." });
        return json(res, 400, { error: "Those Live settings are not valid." });
      }
      if (parsed.data.provider === "codex") {
        const refusal = deps.calls.codexRefusal ? deps.calls.codexRefusal(auth) : LIVE_CODEX_REFUSAL;
        if (refusal) return json(res, 403, { error: refusal });
      }
      if (!Object.keys(parsed.data).length) return json(res, 400, { error: "nothing to save" });
      const historyError = liveHistoryLimitError(parsed.data, parsed.data.provider ?? deps.settings().provider);
      if (historyError) return json(res, 400, { error: historyError });
      return json(res, 200, { live: await deps.saveSettings(parsed.data) });
    }

    return PASS;
  };
}