Skip to content

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

9.3 KB
Raw Blame
// Live calls' settings in config.json: schema, type and environment overrides, kept out of server/config.ts.
import { z } from "zod";
import { liveHistoryLimitError, parseGeminiLiveModel } from "../shared/live-call.ts";
import type { LiveProvider } from "../shared/wire.ts";

export const LIVE_KEY_NEEDS_ENDPOINT = "Save the Azure endpoint first: a Live key works only with the endpoint it was saved for.";
export const LIVE_KEY_NEEDS_CUSTOM_ENDPOINT = "Save the custom endpoint first: a Live key works only with the endpoint it was saved for.";
const NOWHERE = "nowhere";
export const LIVE_STANDBY_IDLE_SECONDS_MIN = 5;
export const LIVE_STANDBY_IDLE_SECONDS_MAX = 60;

/** 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", "gemini" or "elevenlabs" it is not used: Fish Audio calls use the Fish Audio key (`tts.fishKey`), Gemini calls the Gemini key (`tts.geminiKey`) and ElevenLabs calls the ElevenLabs key (`tts.key`). `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; with "custom", `key` is the key of the OpenAI-compatible server at `customEndpoint` and is required, and `customModel` its model. `fishAgentId` is the Fish Audio agent a "fish" call starts, which the harness sets up on the account of the key whose `fishKeyPrint` is `fishAgentFor`; without `fishAgentFor` (an operator's OMB_FISH_LIVE_AGENT_ID) it is used with any key, and `fishAgentLanguage` is the language the harness last set it to speak (absent: English, as agents were first set up). `elevenlabsAgentId` and `elevenlabsAgentFor` are the same for an "elevenlabs" call's ElevenLabs agent. `voice` is a GPT-Live voice, `geminiVoice` a Gemini Live voice, `standby` opts direct OpenAI GPT-Live WebRTC calls into speech wake, and `standbyIdleSeconds` sets the 5–60 second pause timeout. */
export const liveConfigSchema = z.object({
  key: z.string().optional(),
  keyFor: z.string().max(300).optional(),
  provider: z.enum(["openai", "azure", "fish", "gemini", "elevenlabs", "custom"]).optional(),
  useCodex: z.boolean().optional(),
  azureEndpoint: z.string().trim().max(300).optional(),
  azureDeployment: z.string().trim().max(64).optional(),
  customEndpoint: z.string().trim().max(300).optional(),
  customModel: z.string().trim().max(64).optional(),
  fishAgentId: z.string().trim().max(128).optional(),
  fishAgentFor: z.string().max(64).optional(),
  fishAgentLanguage: z.string().max(8).optional(),
  elevenlabsAgentId: z.string().trim().max(128).optional(),
  elevenlabsAgentFor: z.string().max(64).optional(),
  voice: z.string().trim().max(40).regex(/^[a-z]*$/, "a Live voice is a lowercase built-in voice name").optional(),
  geminiVoice: z.string().trim().max(40).regex(/^[A-Za-z]*$/, "a Gemini Live voice is a built-in voice name").optional(),
  geminiModel: z.string().trim().max(80).transform((name) => name.replace(/^models\//, "")).refine((name) => name === "" || parseGeminiLiveModel(name) !== undefined, "a Gemini Live model is a Gemini model id").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(),
});

export interface LiveConfig {
  key?: string;
  keyFor?: string;
  provider?: Exclude<LiveProvider, "codex">;
  /** Use the local CLI for Live calls. Older releases still read the saved service and its key. */
  useCodex?: boolean;
  azureEndpoint?: string;
  azureDeployment?: string;
  customEndpoint?: string;
  customModel?: string;
  fishAgentId?: string;
  fishAgentFor?: string;
  fishAgentLanguage?: string;
  elevenlabsAgentId?: string;
  elevenlabsAgentFor?: string;
  voice?: string;
  geminiVoice?: string;
  geminiModel?: string;
  readTypedReplies?: boolean;
  idleMinutes?: number;
  standby?: boolean;
  standbyIdleSeconds?: number;
  historyMessages?: number;
  historyMessageChars?: number;
  historyTotalChars?: number;
}

export function liveProvider(live: LiveConfig | undefined): LiveProvider | undefined {
  return live?.useCodex ? "codex" : live?.provider;
}

/** Where a key saved now may go: "openai", "azure:<host>" or "custom:<host>"; null while Azure or a custom endpoint is chosen
 * with no endpoint to tie it to. Fish Audio, Gemini and ElevenLabs calls never use this key, so with any of them chosen it stays OpenAI's. */
export function liveKeyTarget(live: LiveConfig | undefined): string | null {
  if (live?.provider !== "azure" && live?.provider !== "custom") return "openai";
  try {
    const host = new URL((live.provider === "azure" ? live.azureEndpoint : live.customEndpoint)?.trim() ?? "").host.toLowerCase();
    return host ? `${live.provider}:${host}` : null;
  } catch {
    return null;
  }
}

/** The saved key, only while calls go where it was saved for. */
export function usableLiveKey(live: LiveConfig | undefined): string | undefined {
  const key = live?.key?.trim();
  const target = liveKeyTarget(live);
  return key && target && (live?.keyFor ?? "openai") === target ? key : undefined;
}

/** What to save for a change to `live`: a new key is tied to where calls now go, and any other change of where they go
 * forgets the old one. On the desktop the OS store keeps a copy the server cannot delete, which comes back as
 * OMB_OPENAI_LIVE_KEY at the next launch: "nowhere" keeps that copy unusable until a key is saved again. */
export function liveSavePatch(current: LiveConfig | undefined, patch: LiveConfig): LiveConfig {
  const { keyFor: _fromRequest, ...asked } = patch;
  const historyError = liveHistoryLimitError(asked, asked.provider ?? current?.provider);
  if (historyError) throw Object.assign(new Error(historyError), { status: 400 });
  const target = liveKeyTarget({ ...current, ...asked });
  if (asked.key?.trim()) {
    if (!target) throw Object.assign(new Error({ ...current, ...asked }.provider === "custom" ? LIVE_KEY_NEEDS_CUSTOM_ENDPOINT : LIVE_KEY_NEEDS_ENDPOINT), { status: 400 });
    return { ...asked, keyFor: target };
  }
  return asked.key !== undefined || target !== liveKeyTarget(current) ? { ...asked, key: "", keyFor: NOWHERE } : asked;
}

export function liveConfigWithEnv(live: LiveConfig | undefined, env: NodeJS.ProcessEnv = process.env): LiveConfig {
  const next = { ...live };
  const envKey = env.OMB_OPENAI_LIVE_KEY;
  if (envKey !== undefined) {
    // A different key from the environment is not the one `keyFor` was saved for.
    if (next.key?.trim() && next.key.trim() !== envKey.trim()) delete next.keyFor;
    next.key = envKey;
  }
  const provider = env.OMB_LIVE_PROVIDER?.trim().toLowerCase();
  if (provider === "codex") next.useCodex = true;
  if (provider === "openai" || provider === "azure" || provider === "fish" || provider === "gemini" || provider === "elevenlabs" || provider === "custom") {
    next.provider = provider;
    if (next.useCodex) next.useCodex = false;
  }
  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_CUSTOM_LIVE_ENDPOINT !== undefined) next.customEndpoint = env.OMB_CUSTOM_LIVE_ENDPOINT.trim();
  if (env.OMB_CUSTOM_LIVE_MODEL !== undefined) next.customModel = env.OMB_CUSTOM_LIVE_MODEL.trim();
  if (env.OMB_FISH_LIVE_AGENT_ID?.trim()) {
    next.fishAgentId = env.OMB_FISH_LIVE_AGENT_ID.trim();
    delete next.fishAgentFor;
    delete next.fishAgentLanguage;
  }
  // Set together in the environment, the key and the Azure (or custom) 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.
  const envEndpoint = provider === "azure" ? env.OMB_AZURE_OPENAI_LIVE_ENDPOINT : provider === "custom" ? env.OMB_CUSTOM_LIVE_ENDPOINT : undefined;
  if (envKey?.trim() && envEndpoint?.trim() && next.keyFor === undefined) next.keyFor = liveKeyTarget(next) ?? NOWHERE;
  return next;
}

/** The non-secret Live settings a settings patch mirrors into the environment. */
export function liveSettingEnv(live: LiveConfig | undefined): Array<[value: string | undefined, name: string]> {
  return [
    [liveProvider(live), "OMB_LIVE_PROVIDER"],
    [live?.azureEndpoint, "OMB_AZURE_OPENAI_LIVE_ENDPOINT"],
    [live?.azureDeployment, "OMB_AZURE_OPENAI_LIVE_DEPLOYMENT"],
    [live?.customEndpoint, "OMB_CUSTOM_LIVE_ENDPOINT"],
    [live?.customModel, "OMB_CUSTOM_LIVE_MODEL"],
  ];
}

/** A Fish Audio key saved as the Live key (`keyFor: "fish"`) is the Fish Audio key while none is saved; it is never used as a Live key. */
export function fishKeyFromLiveKey(cfg: { live?: LiveConfig; tts?: { fishKey?: string } }): void {
  const saved = cfg.live?.keyFor === "fish" ? cfg.live.key?.trim() : undefined;
  if (saved && !cfg.tts?.fishKey?.trim()) cfg.tts = { ...cfg.tts, fishKey: saved };
}