Skip to content

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

7.8 KB
Raw Blame
import type { LiveHistoryLimits, LiveKeySource, LiveProvider, LiveSettings, WireBot } from "../shared/wire.ts";
import { saveConfig, syncCredentialEnv, type AppConfig } from "./config.ts";
import { azureLiveEndpoint, customLiveEndpoint, LIVE_NEEDS_AZURE, LIVE_NEEDS_CUSTOM, LIVE_NEEDS_ELEVENLABS, LIVE_NEEDS_FISH, LIVE_NEEDS_GEMINI, LIVE_NEEDS_KEY, openAiLiveEndpoint, type LiveEndpoint } from "./live-call.ts";
import { LIVE_STANDBY_IDLE_SECONDS_MAX, LIVE_STANDBY_IDLE_SECONDS_MIN, liveProvider, liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";
import { LIVE_STANDBY_IDLE_SECONDS_DEFAULT, resolveLiveHistoryLimits } from "../shared/live-call.ts";
import { fishLiveEndpoint, usableFishAgent } from "./live-fish.ts";
import { voiceCredential } from "./included-services.ts";
import { elevenLabsLiveEndpoint, usableElevenLabsAgent } from "./live-elevenlabs.ts";
import { geminiLiveEndpoint } from "./live-gemini.ts";

export const LIVE_IDLE_MINUTES_DEFAULT = 5;

type LiveConfig = Pick<AppConfig, "live" | "openai" | "tts">;

/** A saved Live key goes only to the provider and host it was saved for (`usableLiveKey`), the OpenAI API key only ever to
 * OpenAI, the Fish Audio key only to Fish Audio, the Gemini key only to Gemini and the person's own ElevenLabs key only to
 * ElevenLabs. A custom endpoint gets only the key saved for it. */
export function liveCallKey(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): { key: string; source: LiveKeySource } | null {
  if (cfg.live?.useCodex) return null;
  if (cfg.live?.provider === "fish") {
    const fish = cfg.tts?.fishKey?.trim();
    return fish ? { key: fish, source: "fishAudio" } : null;
  }
  if (cfg.live?.provider === "gemini") {
    const gemini = cfg.tts?.geminiKey?.trim();
    return gemini ? { key: gemini, source: "gemini" } : null;
  }
  if (cfg.live?.provider === "elevenlabs") {
    // Only the person's own key: Cloud's included voice token, even handed back as `tts.key`, goes only to its relay.
    const elevenlabs = voiceCredential(cfg.tts?.key?.trim() || undefined, env);
    return elevenlabs && !elevenlabs.included ? { key: elevenlabs.token, source: "elevenlabs" } : null;
  }
  const live = usableLiveKey(cfg.live);
  if (live) return { key: live, source: "live" };
  if (cfg.live?.provider === "azure" || cfg.live?.provider === "custom") return null;
  const openai = cfg.openai?.key?.trim();
  return openai ? { key: openai, source: "openai" } : null;
}

/** null when Azure (or a custom endpoint) is chosen but its endpoint or deployment (model) is missing or not valid. On Fish Audio, `model` is "" until the
 * harness has set up an agent on the account of the Fish Audio key. */
export function liveCallEndpoint(cfg: LiveConfig, env: NodeJS.ProcessEnv = process.env): LiveEndpoint | null {
  if (cfg.live?.useCodex) return { provider: "codex", apiBase: "", model: "" };
  if (cfg.live?.provider === "azure") return azureLiveEndpoint(cfg.live.azureEndpoint, cfg.live.azureDeployment);
  if (cfg.live?.provider === "custom") return customLiveEndpoint(cfg.live.customEndpoint, cfg.live.customModel);
  if (cfg.live?.provider === "fish") return fishLiveEndpoint(usableFishAgent(cfg.live, cfg.tts?.fishKey ?? ""), env);
  if (cfg.live?.provider === "gemini") return geminiLiveEndpoint(env, cfg.live.geminiModel);
  if (cfg.live?.provider === "elevenlabs") return elevenLabsLiveEndpoint(usableElevenLabsAgent(cfg.live, cfg.tts?.key ?? ""), env);
  return openAiLiveEndpoint(env);
}

export function liveSetupProblem(cfg: LiveConfig): string | null {
  const provider = liveProvider(cfg.live);
  if (provider === "codex") return null;
  const missing = provider === "azure" ? LIVE_NEEDS_AZURE : provider === "fish" ? LIVE_NEEDS_FISH : provider === "gemini" ? LIVE_NEEDS_GEMINI
    : provider === "elevenlabs" ? LIVE_NEEDS_ELEVENLABS : provider === "custom" ? LIVE_NEEDS_CUSTOM : 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. */
export function saveLiveSettings(cfg: Pick<AppConfig, "live">, { provider, ...patch }: Omit<LiveConfigSection, "provider"> & { provider?: LiveProvider }): void {
  const live = liveSavePatch(cfg.live, provider === "codex" ? { ...patch, useCodex: true }
    : provider ? { ...patch, provider, useCodex: false } : patch);
  saveConfig({ live });
  syncCredentialEnv({ live });
}

/** What a call start reads, once: its key, endpoint and provider all come from this one reading. */
export function liveCallSettings(cfg: AppConfig, override?: WireBot["liveOverride"]) {
  const effective = override ? { ...cfg, live: { ...cfg.live, provider: override.provider, useCodex: false } } : cfg;
  const agentId = override?.provider === "fish" ? override.fishAgentId : undefined;
  const endpoint = agentId ? { ...fishLiveEndpoint(agentId), fixedAgent: true as const } : liveCallEndpoint(effective);
  const setupProblem = agentId && !endpoint?.model ? "The bot's Fish Audio agent ID is invalid." : liveSetupProblem(effective);
  return { key: liveCallKey(effective)?.key ?? "", endpoint, setupProblem, ...liveSettingsFor(effective) };
}

/** A caller without the admin scope learns which service calls use, not which Azure resource or custom endpoint. */
export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeployment: _deployment, customEndpoint: _custom, customModel: _model, ...settings }: LiveSettings): LiveSettings {
  return settings;
}

function liveHistorySettings(live: AppConfig["live"], provider: LiveProvider | undefined): Partial<LiveHistoryLimits> {
  if (!live) return {};
  const resolved = resolveLiveHistoryLimits(live, provider);
  const out: Partial<LiveHistoryLimits> = {};
  if (typeof live.historyMessages === "number" && Number.isInteger(live.historyMessages)) out.historyMessages = resolved.historyMessages;
  if (typeof live.historyMessageChars === "number" && Number.isInteger(live.historyMessageChars)) out.historyMessageChars = resolved.historyMessageChars;
  if (typeof live.historyTotalChars === "number" && Number.isInteger(live.historyTotalChars)) out.historyTotalChars = resolved.historyTotalChars;
  return out;
}

export function liveSettingsFor(cfg: AppConfig): LiveSettings {
  const minutes = cfg.live?.idleMinutes;
  const key = liveCallKey(cfg);
  const provider = liveProvider(cfg.live);
  return {
    configured: liveSetupProblem(cfg) === null,
    ...(key ? { keySource: key.source } : {}),
    ...(provider === "azure" || provider === "fish" || provider === "gemini" || provider === "elevenlabs" || provider === "custom" || provider === "codex" ? { provider } : {}),
    ...(cfg.live?.azureEndpoint ? { azureEndpoint: cfg.live.azureEndpoint } : {}),
    ...(cfg.live?.azureDeployment ? { azureDeployment: cfg.live.azureDeployment } : {}),
    ...(cfg.live?.customEndpoint ? { customEndpoint: cfg.live.customEndpoint } : {}),
    ...(cfg.live?.customModel ? { customModel: cfg.live.customModel } : {}),
    voice: cfg.live?.voice ?? "",
    ...(cfg.live?.geminiVoice ? { geminiVoice: cfg.live.geminiVoice } : {}),
    ...(cfg.live?.geminiModel ? { geminiModel: cfg.live.geminiModel } : {}),
    readTypedReplies: cfg.live?.readTypedReplies ?? true,
    idleMinutes: Number.isInteger(minutes) && minutes! >= 1 && minutes! <= 60 ? minutes! : LIVE_IDLE_MINUTES_DEFAULT,
    ...(cfg.live?.standby === true ? { standby: true } : {}),
    ...(cfg.live?.standby === true || cfg.live?.standbyIdleSeconds !== undefined ? {
      standbyIdleSeconds: Number.isInteger(cfg.live.standbyIdleSeconds) && cfg.live.standbyIdleSeconds! >= LIVE_STANDBY_IDLE_SECONDS_MIN && cfg.live.standbyIdleSeconds! <= LIVE_STANDBY_IDLE_SECONDS_MAX
        ? cfg.live.standbyIdleSeconds! : LIVE_STANDBY_IDLE_SECONDS_DEFAULT,
    } : {}),
    ...liveHistorySettings(cfg.live, provider),
  };
}