Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Merge #7336: configurable Live call history limits
milind-soniaed0f1b87861
diff --cc packages/phone-protocol/src/live-call-wire.tsindex af70662105,edc48b5c89..b02cae9665--- a/packages/phone-protocol/src/live-call-wire.ts+++ b/packages/phone-protocol/src/live-call-wire.ts@@@ -91,10 -94,9 +97,13 @@@ export interface LiveSettingsgeminiVoice?: string;readTypedReplies: boolean;idleMinutes: number;+ /** Opts direct OpenAI GPT-Live WebRTC calls into speech-wake standby; absent or false keeps active inference. */+ standby?: boolean;+ /** Whole seconds before standby, from 5 to 60; defaults to 15 when enabled. */+ standbyIdleSeconds?: number;+ historyMessages?: number;+ historyMessageChars?: number;+ historyTotalChars?: number;}/** The single-use token Fish Audio returns for one agent session (Fish API v1 `LiveKitSessionToken`), passed verbatim todiff --cc server/live-call.tsindex 8ca8dcd6af,a9f1e15690..591b5ede90--- a/server/live-call.ts+++ b/server/live-call.ts@@@ -1,8 -1,8 +1,9 @@@// The provider key never leaves the harness: the renderer only ever holds the SDP answer and its media connection.import { CLOUD_HOME_PLACE } from "./system-prompt.ts";- import type { LiveProvider } from "../shared/wire.ts";+ import type { LiveHistoryLimits, LiveProvider } from "../shared/wire.ts";+ import { resolveLiveHistoryLimits } from "../shared/live-call.ts";import type { Message } from "./store.ts";+import { LIVE_STANDBY_IDLE_SECONDS_DEFAULT } from "../shared/live-call.ts";export const LIVE_MODEL = "gpt-live-1";const OPENAI_BASE = "https://api.openai.com";@@@ -262,8 -275,7 +278,9 @@@ export interface CreateLiveSessionInpucloudHome: boolean;voice?: string;endpoint?: LiveEndpoint;+ standby?: boolean;+ standbyIdleSeconds?: number;+ historyLimits?: Partial<LiveHistoryLimits>;fetchImpl?: typeof fetch;timeoutMs?: number;}diff --cc server/live-config.tsindex c7c9d18fa5,9f79291ad0..34f3338e12--- a/server/live-config.ts+++ b/server/live-config.ts@@@ -25,8 -24,9 +26,11 @@@ export const liveConfigSchema = z.objecgeminiVoice: z.string().trim().max(40).regex(/^[A-Za-z]*$/, "a Gemini Live voice is a built-in voice name").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 {@@@ -46,8 -46,9 +50,11 @@@geminiVoice?: string;readTypedReplies?: boolean;idleMinutes?: number;+ standby?: boolean;+ standbyIdleSeconds?: number;+ historyMessages?: number;+ historyMessageChars?: number;+ historyTotalChars?: number;}/** Where a key saved now may go: "openai", "azure:<host>" or "custom:<host>"; null while Azure or a custom endpoint is chosendiff --cc server/live-fish.tsindex e77dbb3a82,5d060bd4c3..6a31386730--- a/server/live-fish.ts+++ b/server/live-fish.ts@@@ -11,10 -11,7 +11,7 @@@ const CREATE_TIMEOUT_MS = 20_000const END_TIMEOUT_MS = 5_000;const SETUP_TIMEOUT_MS = 8_000;/** Fish agent ids as the dashboard and `GET /v1/agent/agents` show them. */-const AGENT_ID = /^[\w-]{1,128}$/;+export const FISH_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";diff --cc server/live-session-wiring.tsindex 4ed4b83bc8,2c7068c846..0ac417281a--- a/server/live-session-wiring.ts+++ b/server/live-session-wiring.ts@@@ -63,8 -65,7 +65,8 @@@ export function liveSessionWiring(input};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 };+ const session = { key, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, historyLimits: input.historyLimits?.(), fetchImpl };+ if (endpoint.fixedAgent) return { agent: endpoint, token: await createFishLiveSession({ ...session, endpoint }) };const language = fishSpeakingLanguage(input.language?.());if (endpoint.model) await speakLanguage(key, endpoint, language);let agent = endpoint.model ? endpoint : await setUpAgent(key, endpoint, language);@@@ -102,9 -103,10 +104,10 @@@fishRefusal: (auth) => fishLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),geminiRefusal: (auth) => geminiLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),elevenlabsRefusal: (auth) => elevenLabsLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),- createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {+ createSession: async ({ key, endpoint, sdp, botId, threadId, voice, standby, standbyIdleSeconds }) => {+ const historyLimits = input.historyLimits?.();if (endpoint.provider === "gemini") {- const session = await createGeminiLiveSession({ key, endpoint, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, fetchImpl });+ const session = await createGeminiLiveSession({ key, endpoint, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, historyLimits, fetchImpl });// Gemini has nothing to end: the session ends when the client closes it, and the token is single use.const { token } = relays.open(session.session_id, async () => undefined);return { sessionId: session.session_id, gemini: { type: "gemini", session, relayToken: token } };@@@ -116,7 -118,7 +119,7 @@@return { sessionId: session.session_id, elevenlabs: { type: "elevenlabs", session, relayToken: token } };}if (endpoint.provider !== "fish") {- return createLiveSession({ key, endpoint, sdp, voice, standby, standbyIdleSeconds, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome });- return createLiveSession({ key, endpoint, sdp, voice, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, historyLimits, fetchImpl });++ return createLiveSession({ key, endpoint, sdp, voice, standby, standbyIdleSeconds, bot: input.bot(botId), history: input.history(threadId), cloudHome: input.cloudHome, historyLimits, fetchImpl });}const { agent, token: session } = await startFish(key, endpoint, botId, threadId);const { token } = relays.open(session.session_id, () => endFishLiveSession(session.session_id, key, agent, fetchImpl));diff --cc server/live-settings.tsindex 2df9b9ab7f,8d5432f475..0a532113c5--- a/server/live-settings.ts+++ b/server/live-settings.ts@@@ -1,8 -1,8 +1,9 @@@- import type { LiveKeySource, LiveSettings, WireBot } from "../shared/wire.ts";-import type { LiveHistoryLimits, LiveKeySource, LiveProvider, LiveSettings } from "../shared/wire.ts";++import type { LiveHistoryLimits, LiveKeySource, LiveProvider, LiveSettings, WireBot } from "../shared/wire.ts";+ import { resolveLiveHistoryLimits } from "../shared/live-call.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 { liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";+import { LIVE_STANDBY_IDLE_SECONDS_MAX, LIVE_STANDBY_IDLE_SECONDS_MIN, liveSavePatch, usableLiveKey, type LiveConfig as LiveConfigSection } from "./live-config.ts";+import { LIVE_STANDBY_IDLE_SECONDS_DEFAULT } 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";@@@ -92,10 -98,6 +103,11 @@@ export function liveSettingsFor(cfg: Ap...(cfg.live?.geminiVoice ? { geminiVoice: cfg.live.geminiVoice } : {}),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),};}diff --cc server/routes/live.tsindex 0354ec1e51,2d4956e76a..0fc4a5ea0c--- a/server/routes/live.ts+++ b/server/routes/live.ts@@@ -2,9 -2,8 +2,9 @@@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 } from "../../shared/live-call.ts";+ import { GEMINI_LIVE_VOICE_OPTIONS, liveHistoryLimitError } 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 { RELAY_POLL_MS } from "../live-fish.ts";import { PASS, type RouteContext, type RouteHandler } from "./table.ts";@@@ -15,7 -14,7 +15,7 @@@ export interface LiveRouteDepsdeviceRevoked?: (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; readTypedReplies?: boolean; idleMinutes?: number; standby?: boolean; standbyIdleSeconds?: number }): Promise<LiveSettings>;- saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; customEndpoint?: string; customModel?: string; voice?: string; geminiVoice?: string; readTypedReplies?: boolean; idleMinutes?: number; historyMessages?: number; historyMessageChars?: number; historyTotalChars?: number }): Promise<LiveSettings>;++ saveSettings(patch: { provider?: LiveProvider; azureEndpoint?: string; azureDeployment?: string; customEndpoint?: string; customModel?: string; voice?: string; geminiVoice?: 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;}@@@ -61,8 -58,9 +61,11 @@@ const settingsBody = z.object(geminiVoice: z.string().trim().refine((name) => name === "" || GEMINI_LIVE_VOICE_OPTIONS.some((option) => option.id === name)).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}$/;diff --cc src/components/LiveCallSettings.tsxindex de019965fc,682baf565d..7d73544548--- a/src/components/LiveCallSettings.tsx+++ b/src/components/LiveCallSettings.tsx@@@ -1,10 -1,13 +1,13 @@@import { useCallback, useId, useState } from "react";- import { GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_STANDBY_IDLE_SECONDS_DEFAULT, LIVE_VOICE_OPTIONS } from "../../shared/live-call";- import { t } from "@/lib/i18n";+ import {- GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_HISTORY_MIN, LIVE_VOICE_OPTIONS,++ GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_HISTORY_MIN, LIVE_STANDBY_IDLE_SECONDS_DEFAULT, LIVE_VOICE_OPTIONS,+ liveHistoryCaps, resolveLiveHistoryLimits,+ } from "../../shared/live-call";+ import { intlLocale, t } from "@/lib/i18n";import { liveDisclosure, liveKeyCopy, liveKeyFormKey } from "@/lib/call-mode";import { api, useStore, type Bot, type ConfigStatus } from "@/state/store";- import type { LiveSettings } from "../../shared/wire";+ import type { LiveHistoryLimits, LiveSettings } from "../../shared/wire";import { LiveKeySetup } from "./LiveKeySetup";import { LiveProviderSettings } from "./LiveProviderSettings";import { BotLiveVoiceSelect } from "./BotLiveVoiceSelect";@@@ -12,10 -15,18 +15,19 @@@ import { KeysLink } from "./keys/KeysLiimport { Select } from "./Select";const IDLE_CHOICES = [1, 2, 3, 5, 10, 15, 30, 60];+const STANDBY_CHOICES = Array.from({ length: 56 }, (_, index) => index + 5);+ const HISTORY_MESSAGE_CHOICES = [0, 4, 8, 16, 32, 64, 100, 128, 200];+ const HISTORY_MESSAGE_CHAR_CHOICES = [200, 400, 600, 1_000, 2_000, 4_000, 8_000, 12_000];+ const HISTORY_TOTAL_CHAR_CHOICES = [1_000, 3_000, 6_000, 12_000, 20_000, 24_000, 40_000, 60_000];++ function limitChoices(choices: number[], current: number, min: number, max: number): number[] {+ const allowed = choices.filter((value) => value >= min && value <= max);+ if (current >= min && current <= max && !allowed.includes(current)) allowed.push(current);+ return allowed.sort((a, b) => a - b);+ }/** With `bot`, the bot on the call: it can have a voice of its own, and the other voice is the default for every other bot. */-export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "name" | "liveVoice">; onClose: () => void }) {+export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "name" | "liveVoice" | "liveOverride">; onClose: () => void }) {const { state, dispatch } = useStore();const live: LiveSettings = state.config?.live ?? { configured: false, voice: "", readTypedReplies: true, idleMinutes: 5 };const [saving, setSaving] = useState(false);@@@ -43,7 -51,7 +55,7 @@@const voice = gemini ? geminiLiveVoice(live.geminiVoice) : live.voice || "marin";const known = voiceOptions.some((option) => option.id === voice);- const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes" | "standby" | "standbyIdleSeconds">>) => {- const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes" | keyof LiveHistoryLimits>>) => {++ const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes" | "standby" | "standbyIdleSeconds" | keyof LiveHistoryLimits>>) => {setSaving(true);setError(null);try {@@@ -128,32 -165,29 +169,55 @@@))}</Select></label>+ {openai && <>+ <label className="flex items-center justify-between gap-2">+ <span className="text-ink-secondary">{t("call.live.standby")}</span>+ <input+ type="checkbox"+ checked={live.standby === true}+ disabled={saving}+ aria-describedby={standbyHintId}+ onChange={(event) => void save({ standby: event.target.checked, ...(event.target.checked ? { standbyIdleSeconds: live.standbyIdleSeconds ?? LIVE_STANDBY_IDLE_SECONDS_DEFAULT } : {}) })}+ />+ </label>+ <div id={standbyHintId} className="-mt-2 text-[12px] text-ink-tertiary">{t("call.live.standbyHint")}</div>+ {live.standby === true && <label className="flex items-center justify-between gap-2">+ <span className="text-ink-secondary">{t("call.live.standbyTimeout")}</span>+ <Select+ size="sm"+ value={live.standbyIdleSeconds ?? LIVE_STANDBY_IDLE_SECONDS_DEFAULT}+ disabled={saving}+ onChange={(event) => void save({ standbyIdleSeconds: Number(event.target.value) })}+ >+ {STANDBY_CHOICES.map((seconds) => (+ <option key={seconds} value={seconds}>{seconds}s</option>+ ))}+ </Select>+ </label>}+ </>}+ {historyRows.map((row) => (+ <label key={row.key} className="flex items-center justify-between gap-2">+ <span className="text-ink-secondary">{t(row.label)}</span>+ <Select+ size="sm"+ value={row.value}+ disabled={saving}+ aria-describedby={historyHintId}+ onChange={(event) => void save({ [row.key]: Number(event.target.value) })}+ >+ {row.options.map((count) => (+ <option key={count} value={count}>{count.toLocaleString(intlLocale())}</option>+ ))}+ </Select>+ </label>+ ))}+ <div id={historyHintId} className="-mt-2 text-[12px] text-ink-tertiary">+ {t("call.live.historyHint", {+ messages: historyCaps.maxMessages.toLocaleString(intlLocale()),+ messageChars: historyCaps.maxMessageChars.toLocaleString(intlLocale()),+ totalChars: historyCaps.maxTotalChars.toLocaleString(intlLocale()),+ })}+ </div><div className="flex items-center justify-between gap-2 border-t border-hairline/60 pt-2"><span className="text-ink-secondary">{t(copy.key)}</span><span className="flex gap-2">diff --cc src/locales/en.jsonindex 3827598e0d,e110fd9ae7..c8e211affc--- a/src/locales/en.json+++ b/src/locales/en.json@@@ -7119,9 -6980,10 +7119,13 @@@"call.live.readTyped": "Read replies to typed messages","call.live.readTypedHint": "When this is off, messages you type during a call and the bot's answers to them are not sent to OpenAI.","call.live.idle": "Hang up after this many minutes of silence",+ "call.live.standby": "Use lower-cost standby during silence",+ "call.live.standbyHint": "OpenAI pauses inference at a lower rate after this delay. Your microphone and call stay connected; speaking resumes the same conversation.",+ "call.live.standbyTimeout": "Pause after this many seconds",+ "call.live.historyMessages": "Chat history messages",+ "call.live.historyMessageChars": "Chars per message",+ "call.live.historyTotalChars": "Total history chars",+ "call.live.historyHint": "Sent at call start, up to {messages} messages, {messageChars} per message, {totalChars} total for this provider.","call.live.key": "OpenAI key","call.live.keyChange": "Change key","call.live.keyRemove": "Remove key",diff --cc src/locales/pt-br.jsonindex 3686541dab,efaf9d244c..319be2096d--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@@ -6748,9 -6641,10 +6748,13 @@@"call.live.readTyped": "Ler em voz alta as respostas a mensagens digitadas","call.live.readTypedHint": "Com esta opção desligada, as mensagens que você digita durante uma chamada e as respostas do bot a elas não são enviadas à OpenAI.","call.live.idle": "Minutos de silêncio até desligar",+ "call.live.standby": "Usar modo de espera de menor custo durante o silêncio",+ "call.live.standbyHint": "Após esse tempo, a OpenAI pausa a inferência e cobra uma tarifa menor. O microfone continua ligado e a chamada permanece conectada. Ao falar, você retoma a mesma conversa.",+ "call.live.standbyTimeout": "Segundos de silêncio até pausar",+ "call.live.historyMessages": "Mensagens do histórico do chat",+ "call.live.historyMessageChars": "Caracteres por mensagem",+ "call.live.historyTotalChars": "Total de caracteres do histórico",+ "call.live.historyHint": "Enviado no início da chamada, até {messages} mensagens, {messageChars} por mensagem e {totalChars} no total para este provedor.","call.live.key": "Chave da OpenAI","call.live.keyChange": "Trocar chave","call.live.keyRemove": "Remover chave",