Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Live calls: make startup chat history limits configurable
jonathanwxh-cellf4e861e187e2
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.tsindex 90367e23cd..edc48b5c89 100644--- a/packages/phone-protocol/src/live-call-wire.ts+++ b/packages/phone-protocol/src/live-call-wire.ts@@ -67,6 +67,12 @@ export type LiveProvider = "openai" | "azure" | "fish" | "gemini" | "elevenlabs"* `elevenlabs`: the person's own ElevenLabs key from Settings → API keys, the only key an ElevenLabs call uses. */export type LiveKeySource = "live" | "openai" | "fishAudio" | "gemini" | "elevenlabs";+export interface LiveHistoryLimits {+ historyMessages: number;+ historyMessageChars: number;+ historyTotalChars: number;+}+/** Non-secret Live settings, as GET /api/config and PATCH /api/live/settings report them. */export interface LiveSettings {/** A Live call has everything it needs: a key (`keySource` says which; never the key itself), and for Azure a valid endpoint and deployment. */@@ -88,6 +94,9 @@ export interface LiveSettings {geminiVoice?: string;readTypedReplies: boolean;idleMinutes: 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 --git a/packages/phone-protocol/src/live-call.ts b/packages/phone-protocol/src/live-call.tsindex becbae8022..b3ac98d526 100644--- a/packages/phone-protocol/src/live-call.ts+++ b/packages/phone-protocol/src/live-call.ts@@ -2,7 +2,7 @@// *that* it wants help, never *what*: `session.delegation.created` carries an id// and a timeline offset, so the request is rebuilt from the input transcript.-import type { LiveSpokenLine } from "./live-call-wire.ts";+import type { LiveHistoryLimits, LiveProvider, LiveSpokenLine } from "./live-call-wire.ts";export interface TranscriptSegment {text: string;@@ -226,3 +226,74 @@ export function formatCallDuration(seconds: number): string {export function liveCallRowText(botName: string, seconds: number): string {return `Call with ${botName} · ${formatCallDuration(seconds)}`;}++export interface LiveHistoryCaps {+ maxMessages: number;+ maxMessageChars: number;+ maxTotalChars: number;+}++export const DEFAULT_LIVE_HISTORY_LIMITS: LiveHistoryLimits = {+ historyMessages: 8,+ historyMessageChars: 600,+ historyTotalChars: 6_000,+};++export const LIVE_HISTORY_MIN: LiveHistoryLimits = {+ historyMessages: 0,+ historyMessageChars: 100,+ historyTotalChars: 500,+};++export const LIVE_HISTORY_PROVIDER_CAPS: Record<LiveProvider, LiveHistoryCaps> = {+ openai: { maxMessages: 128, maxMessageChars: 8_000, maxTotalChars: 24_000 },+ azure: { maxMessages: 128, maxMessageChars: 8_000, maxTotalChars: 24_000 },+ custom: { maxMessages: 128, maxMessageChars: 8_000, maxTotalChars: 24_000 },+ fish: { maxMessages: 100, maxMessageChars: 4_000, maxTotalChars: 20_000 },+ elevenlabs: { maxMessages: 100, maxMessageChars: 4_000, maxTotalChars: 20_000 },+ gemini: { maxMessages: 200, maxMessageChars: 12_000, maxTotalChars: 60_000 },+};++/** Maximum history limits supported by `provider` (defaults to OpenAI's ceilings). */+export function liveHistoryCaps(provider?: LiveProvider): LiveHistoryCaps {+ return provider ? LIVE_HISTORY_PROVIDER_CAPS[provider] : LIVE_HISTORY_PROVIDER_CAPS.openai;+}++function clampHistoryLimit(value: unknown, fallback: number, min: number, max: number): number {+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;+ return Math.min(max, Math.max(min, Math.trunc(value)));+}++/** Clamps partial history limits into valid bounds for `provider`, filling missing or non-finite values with defaults. */+export function resolveLiveHistoryLimits(+ limits?: Partial<LiveHistoryLimits>,+ provider?: LiveProvider,+): LiveHistoryLimits {+ const caps = liveHistoryCaps(provider);+ return {+ historyMessages: clampHistoryLimit(limits?.historyMessages, DEFAULT_LIVE_HISTORY_LIMITS.historyMessages, LIVE_HISTORY_MIN.historyMessages, caps.maxMessages),+ historyMessageChars: clampHistoryLimit(limits?.historyMessageChars, DEFAULT_LIVE_HISTORY_LIMITS.historyMessageChars, LIVE_HISTORY_MIN.historyMessageChars, caps.maxMessageChars),+ historyTotalChars: clampHistoryLimit(limits?.historyTotalChars, DEFAULT_LIVE_HISTORY_LIMITS.historyTotalChars, LIVE_HISTORY_MIN.historyTotalChars, caps.maxTotalChars),+ };+}++/** Validates user-supplied history limits against `provider`'s ceiling, returning a descriptive error or null. */+export function liveHistoryLimitError(+ limits: Partial<LiveHistoryLimits>,+ provider?: LiveProvider,+): string | null {+ const caps = liveHistoryCaps(provider);+ const checks: Array<[keyof LiveHistoryLimits, number, number, string]> = [+ ["historyMessages", LIVE_HISTORY_MIN.historyMessages, caps.maxMessages, "messages"],+ ["historyMessageChars", LIVE_HISTORY_MIN.historyMessageChars, caps.maxMessageChars, "chars per message"],+ ["historyTotalChars", LIVE_HISTORY_MIN.historyTotalChars, caps.maxTotalChars, "total chars"],+ ];+ for (const [key, min, max, label] of checks) {+ const value = limits[key];+ if (value === undefined) continue;+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {+ return `Chat history ${label} must be between ${min} and ${max} for this voice provider.`;+ }+ }+ return null;+}diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.tsindex 44d4465638..d11de65c7c 100644--- a/packages/phone-protocol/src/wire.ts+++ b/packages/phone-protocol/src/wire.ts@@ -39,7 +39,7 @@ import type { CompanionEndpointsSnapshot } from "./responses.ts";/** What a team bot's main chat is called, beside each person's own chats. */export const SHARED_CHAT_TITLE = "Shared chat";-export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveElevenLabsSession, LiveElevenLabsTransport, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveGeminiSession, LiveGeminiTransport, LiveKeySource, LiveProvider, LiveSettings, LiveSpokenLine } from "./live-call-wire.ts";+export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveElevenLabsSession, LiveElevenLabsTransport, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveGeminiSession, LiveGeminiTransport, LiveHistoryLimits, LiveKeySource, LiveProvider, LiveSettings, LiveSpokenLine } from "./live-call-wire.ts";export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";export type { AuthPairResponse, AuthSessionResponse, BotCreateResponse, BotsResponse, BotUpdateResponse, CompanionE2EDescriptor, CompanionEndpointsSnapshot, InstancesResponse, LoopbackSessionResponse, PairedDevice, PairedSession, PairRequest, PairResponse, RoomCreateResponse, RoomTaskCreateResponse, RoomTaskUpdateResponse, RoomUpdateResponse, SearchHit, SearchResponse, SignedInSessionResponse, TaskResponse, WireComputerControl, WireInstance, WireMessagePage, WireModelOption } from "./responses.ts";diff --git a/server/index.ts b/server/index.tsindex a91036467f..9bf637e8c6 100644--- a/server/index.ts+++ b/server/index.ts@@ -12301,7 +12301,7 @@ function liveCallTitle(botId: string, threadId: string, excerpt: string): Promisconst gate = threadTitleGate(bot);return gate.ok ? generateThreadTitle(gate.instance, excerpt, "call") : null;}-const liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); }, language: appLanguage, fishAgentLanguage: () => cfg.live?.fishAgentLanguage });+const liveWiring = liveSessionWiring({ bot: liveBotFor, history: liveHistoryFor, cloudHome: Boolean(CLOUD_HOME), othersOnLoopback: adminActivityRecording, saveAgent: (agent) => { saveConfig({ live: agent }); Object.assign(cfg, loadConfig()); }, language: appLanguage, fishAgentLanguage: () => cfg.live?.fishAgentLanguage, historyLimits: () => cfg.live });const liveCalls = new LiveCallController({store,send: async ({ auth, botId, threadId, text, callId }) => {diff --git a/server/live-call.test.ts b/server/live-call.test.tsindex e01043f2db..a7ad064f36 100644--- a/server/live-call.test.ts+++ b/server/live-call.test.ts@@ -427,3 +427,48 @@ describe("spokenHangUp", () => {}});});++describe("configurable live startup history limits", () => {+ it("applies custom limits, supports zero messages, and clamps to the provider cap", async () => {+ const { selectLiveHistory } = await import("./live-call.ts");+ const history = Array.from({ length: 150 }, (_, index) => ({+ role: index % 2 ? "assistant" as const : "user" as const,+ text: `msg-${index} ${"a".repeat(250)}`,+ }));++ expect(liveInitialInput(history, { historyMessages: 16, historyMessageChars: 100, historyTotalChars: 1_600 })).toHaveLength(16);+ expect(liveInitialInput(history, { historyMessages: 16, historyMessageChars: 80, historyTotalChars: 1_500 })).toHaveLength(15);+ expect(liveInitialInput(history, { historyMessages: 0 })).toEqual([]);++ const picked = selectLiveHistory(history, { historyMessages: 200, historyMessageChars: 150, historyTotalChars: 60_000 }, "openai");+ expect(picked).toHaveLength(128);+ expect(picked.at(-1)?.text.startsWith("msg-149 ")).toBe(true);+ for (const item of picked) expect(item.text.length).toBeLessThanOrEqual(150);++ const cappedByTotal = selectLiveHistory(history, { historyMessages: 200, historyMessageChars: 200, historyTotalChars: 60_000 }, "openai");+ expect(cappedByTotal).toHaveLength(120);++ const longNewest = [{ role: "user" as const, text: "older" }, { role: "assistant" as const, text: `lead-${"q".repeat(7_000)}` }];+ const singleOversized = selectLiveHistory(longNewest, { historyMessages: 8, historyMessageChars: 8_000, historyTotalChars: 6_000 }, "openai");+ expect(singleOversized).toHaveLength(1);+ expect(singleOversized[0]).toEqual({ role: "assistant", text: `lead-${"q".repeat(5_995)}` });+ });++ it("forwards historyLimits into createLiveSession input", async () => {+ const fetchImpl = okFetch();+ const history = Array.from({ length: 20 }, (_, index) => ({ role: "user" as const, text: `line ${index} ${"z".repeat(400)}` }));+ await createLiveSession({+ key: "sk-test",+ sdp: OFFER,+ bot: BOT,+ history,+ cloudHome: false,+ historyLimits: { historyMessages: 12, historyMessageChars: 120, historyTotalChars: 2_000 },+ fetchImpl,+ });+ const body = JSON.parse(String(fetchImpl.mock.calls[0][1]?.body));+ expect(body.session.input).toHaveLength(12);+ expect(body.session.input[0].content[0].text).toMatch(/^line 8 /);+ expect(body.session.input[0].content[0].text.length).toBe(120);+ });+});diff --git a/server/live-call.ts b/server/live-call.tsindex f00f582834..a9f1e15690 100644--- a/server/live-call.ts+++ b/server/live-call.ts@@ -1,6 +1,7 @@// 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";export const LIVE_MODEL = "gpt-live-1";@@ -138,10 +139,7 @@ export function liveAuthHeaders(provider: LiveProvider, key: string): Record<strreturn provider === "azure" ? { "api-key": key } : { authorization: `Bearer ${key}` };}-// The API caps startup history at 128 messages / 8,192 tokens; stay well inside it.-const HISTORY_MESSAGES = 8;-const HISTORY_MESSAGE_CHARS = 600;-const HISTORY_TOTAL_CHARS = 6_000;+// Provider startup caps live in shared/live-call.ts; defaults stay 8 messages / 600 chars / 6,000 total.const CREATE_TIMEOUT_MS = 20_000;export interface LiveBot {@@ -229,18 +227,36 @@ export function spokenHangUp(text: string): boolean {|| ZH_HANG_UP.test(text.trim().replace(ZH_HANG_UP_LEAD, ""));}-export function liveInitialInput(history: LiveHistoryMessage[]) {+/** Picks the newest non-empty messages inside the configured chat-history limits, capped by `provider`. */+export function selectLiveHistory(+ history: LiveHistoryMessage[],+ limits?: Partial<LiveHistoryLimits>,+ provider: LiveProvider = "openai",+): LiveHistoryMessage[] {+ const { historyMessages, historyMessageChars, historyTotalChars } = resolveLiveHistoryLimits(limits, provider);+ if (historyMessages <= 0 || historyMessageChars <= 0 || historyTotalChars <= 0) return [];const picked: LiveHistoryMessage[] = [];let total = 0;for (const message of [...history].reverse()) {- if (picked.length >= HISTORY_MESSAGES) break;- const text = message.text.replace(/\s+/g, " ").trim().slice(0, HISTORY_MESSAGE_CHARS);+ if (picked.length >= historyMessages) break;+ const text = message.text.replace(/\s+/g, " ").trim().slice(0, historyMessageChars);if (!text) continue;- if (total + text.length > HISTORY_TOTAL_CHARS) break;+ if (total + text.length > historyTotalChars) {+ if (picked.length === 0) picked.unshift({ role: message.role, text: text.slice(0, historyTotalChars) });+ break;+ }total += text.length;picked.unshift({ role: message.role, text });}- return picked.map((message) => message.role === "user"+ return picked;+}++export function liveInitialInput(+ history: LiveHistoryMessage[],+ limits?: Partial<LiveHistoryLimits>,+ provider: LiveProvider = "openai",+) {+ return selectLiveHistory(history, limits, provider).map((message) => message.role === "user"? { type: "message" as const, role: "user" as const, content: [{ type: "input_text" as const, text: message.text }] }: { type: "message" as const, role: "assistant" as const, content: [{ type: "output_text" as const, text: message.text }] });}@@ -259,6 +275,7 @@ export interface CreateLiveSessionInput {cloudHome: boolean;voice?: string;endpoint?: LiveEndpoint;+ historyLimits?: Partial<LiveHistoryLimits>;fetchImpl?: typeof fetch;timeoutMs?: number;}@@ -272,7 +289,7 @@ export async function createLiveSession(input: CreateLiveSessionInput): Promise<if (!input.sdp.trim() || Buffer.byteLength(input.sdp) > MAX_SDP_BYTES) {throw new LiveSessionError("The call could not start: the connection offer was invalid.", 400);}- const initialInput = liveInitialInput(input.history);+ const initialInput = liveInitialInput(input.history, input.historyLimits, endpoint.provider);const body = {session: {model: endpoint.model,diff --git a/server/live-config.ts b/server/live-config.tsindex 6a1a448a59..9f79291ad0 100644--- a/server/live-config.ts+++ b/server/live-config.ts@@ -1,5 +1,6 @@// Live calls' settings in config.json: schema, type and environment overrides, kept out of server/config.ts.import { z } from "zod";+import { liveHistoryLimitError } from "../shared/live-call.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.";@@ -23,6 +24,9 @@ export const liveConfigSchema = z.object({geminiVoice: 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(),+ 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 {@@ -42,6 +46,9 @@ export interface LiveConfig {geminiVoice?: string;readTypedReplies?: boolean;idleMinutes?: 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 chosen@@ -68,6 +75,8 @@ export function usableLiveKey(live: LiveConfig | undefined): string | undefined* 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 });diff --git a/server/live-elevenlabs.test.ts b/server/live-elevenlabs.test.tsindex 8698f09ea2..1a837abd02 100644--- a/server/live-elevenlabs.test.ts+++ b/server/live-elevenlabs.test.ts@@ -166,4 +166,20 @@ describe("an ElevenLabs Live call's voice", () => {const fetchImpl = fakeElevenLabs({ "/v1/convai/agents/agent_1": () => new Response("", { status: 404 }) });await expect(withVoice(fetchImpl, VOICE)).rejects.toMatchObject({ elevenlabsStatus: 404 });});++ it("forwards configurable historyLimits up to ElevenLabs' ceiling", async () => {+ const fetchImpl = fakeElevenLabs();+ const history = Array.from({ length: 15 }, (_, i) => ({ role: "user" as const, text: `el-${i}` }));+ const session = await createElevenLabsLiveSession({+ key: "k",+ endpoint: elevenLabsLiveEndpoint("agent_1", {}),+ bot: { name: "Rigel" },+ history,+ cloudHome: false,+ historyLimits: { historyMessages: 12, historyMessageChars: 1_000, historyTotalChars: 10_000 },+ fetchImpl,+ now: () => NOW,+ });+ expect(session.instructions.match(/^User: /gm)).toHaveLength(12);+ });});diff --git a/server/live-elevenlabs.ts b/server/live-elevenlabs.tsindex 7d7e79b4f2..25d796a03f 100644--- a/server/live-elevenlabs.ts+++ b/server/live-elevenlabs.ts@@ -2,7 +2,7 @@// tool `delegate` on the person's account once, and for each call asks ElevenLabs for a signed URL the client opens; the// client relays what was said as on a Fish Audio call.import { randomBytes } from "node:crypto";-import type { LiveElevenLabsSession } from "../shared/wire.ts";+import type { LiveElevenLabsSession, LiveHistoryLimits } from "../shared/wire.ts";import { LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";import type { LiveConfig } from "./live-config.ts";import { elevenLabsProviderApi } from "./included-services.ts";@@ -124,6 +124,7 @@ export interface CreateElevenLabsSessionInput {bot: LiveBot;history: LiveHistoryMessage[];cloudHome: boolean;+ historyLimits?: Partial<LiveHistoryLimits>;fetchImpl?: typeof fetch;now?: () => number;}@@ -144,7 +145,11 @@ export async function createElevenLabsLiveSession(input: CreateElevenLabsSessionreturn {session_id: `elevenlabs_${randomBytes(12).toString("hex")}`,signed_url: url,- instructions: fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }),+ instructions: fishInstructions(input.bot, input.history, {+ cloudHome: input.cloudHome,+ historyLimits: input.historyLimits,+ provider: "elevenlabs",+ }),...(voiceId ? { voice_id: voiceId } : {}),expires_at: new Date((input.now ?? Date.now)() + CONNECT_WITHIN_MS).toISOString(),};diff --git a/server/live-fish.test.ts b/server/live-fish.test.tsindex 141224c205..7c0c43d67a 100644--- a/server/live-fish.test.ts+++ b/server/live-fish.test.ts@@ -100,6 +100,52 @@ describe("the Fish agent's instructions", () => {expect(text.match(/^(User|You): /gm)).toHaveLength(8);expect(text).not.toContain("x".repeat(601));});++ it("honors configurable history limits and enforces provider caps across prompt-based callers", async () => {+ const history = Array.from({ length: 140 }, (_, i) => ({+ role: i % 2 ? "assistant" as const : "user" as const,+ text: `msg-${i} ${"x".repeat(120)}`,+ }));+ const expanded = fishInstructions({ name: "Rigel" }, history, {+ historyLimits: { historyMessages: 16, historyMessageChars: 100, historyTotalChars: 2_000 },+ });+ expect(expanded.match(/^(User|You): /gm)).toHaveLength(16);+ expect(expanded).not.toContain("x".repeat(101));++ const minClamped = fishInstructions({ name: "Rigel" }, history, {+ historyLimits: { historyMessages: 2, historyMessageChars: 40, historyTotalChars: 200 },+ });+ expect(minClamped.match(/^(User|You): /gm)).toHaveLength(2);+ expect(minClamped).not.toContain("x".repeat(101));++ const zeroed = fishInstructions({ name: "Rigel" }, history, { historyLimits: { historyMessages: 0 } });+ expect(zeroed.match(/^(User|You): /gm) ?? []).toHaveLength(0);++ const cappedFish = fishInstructions({ name: "Rigel" }, history, {+ historyLimits: { historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 },+ provider: "fish",+ });+ expect(cappedFish.match(/^(User|You): /gm)).toHaveLength(100);++ const cappedGemini = fishInstructions({ name: "Rigel" }, history, {+ historyLimits: { historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 },+ provider: "gemini",+ });+ expect(cappedGemini.match(/^(User|You): /gm)).toHaveLength(140);++ const fetchImpl = fakeFetch(201, TOKEN);+ await createFishLiveSession({+ key: "fish-key",+ endpoint: ENDPOINT,+ bot: { name: "Rigel" },+ history: history.slice(0, 20),+ cloudHome: false,+ historyLimits: { historyMessages: 12, historyMessageChars: 120, historyTotalChars: 3_000 },+ fetchImpl,+ });+ const prompt = JSON.parse(String(fetchImpl.mock.calls[0]![1]!.body)).overrides.system_prompt as string;+ expect(prompt.match(/^(User|You): /gm)).toHaveLength(12);+ });});describe("creating a Fish Audio session", () => {diff --git a/server/live-fish.ts b/server/live-fish.tsindex 31adbb20ce..5d060bd4c3 100644--- a/server/live-fish.ts+++ b/server/live-fish.ts@@ -1,9 +1,9 @@// Fish Audio Live 3 calls. The Fish key never leaves the harness: the client gets only Fish's single-use session token,// and Fish has no server sideband, so the client relays what was said and the harness answers through FishRelay.import { createHash, randomBytes, timingSafeEqual } from "node:crypto";-import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken } from "../shared/wire.ts";+import type { LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveHistoryLimits, LiveProvider } from "../shared/wire.ts";import type { LiveSocket } from "./live-call-controller.ts";-import { liveInstructions, LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";+import { liveInstructions, LiveSessionError, selectLiveHistory, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";import type { LiveConfig } from "./live-config.ts";const FISH_BASE = "https://api.fish.audio";@@ -12,9 +12,6 @@ const 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}$/;-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";@@ -117,7 +114,17 @@ async function fishSetupRequest(fetchImpl: typeof fetch, key: string, method: st}/** The Fish agent's system prompt for this call: the GPT-Live instructions, how this agent delegates, and the recent chat. */-export function fishInstructions(bot: LiveBot, history: LiveHistoryMessage[], { cloudHome = false }: { cloudHome?: boolean } = {}): string {+export interface FishInstructionsOptions {+ cloudHome?: boolean;+ historyLimits?: Partial<LiveHistoryLimits>;+ provider?: LiveProvider;+}++export function fishInstructions(+ bot: LiveBot,+ history: LiveHistoryMessage[],+ { cloudHome = false, historyLimits, provider = "fish" }: FishInstructionsOptions = {},+): string {const lines = [liveInstructions(bot, { cloudHome }),"",@@ -125,7 +132,7 @@ export function fishInstructions(bot: LiveBot, history: LiveHistoryMessage[], {`A user message that starts with ${FISH_UPDATE_PREFIX} is not the user speaking: it is a later result or a status note from your work. Speak it to the user naturally, in the first person, without reading the prefix.`,"Do not end the call yourself. When the user asks to hang up, delegate it.",];- const recent = recentHistory(history);+ const recent = selectLiveHistory(history, historyLimits, provider);if (recent.length) {lines.push("", "The conversation so far, most recent last:");for (const message of recent) lines.push(`${message.role === "user" ? "User" : "You"}: ${message.text}`);@@ -133,26 +140,13 @@ export function fishInstructions(bot: LiveBot, history: LiveHistoryMessage[], {return lines.join("\n");}-function recentHistory(history: LiveHistoryMessage[]): LiveHistoryMessage[] {- const picked: LiveHistoryMessage[] = [];- let total = 0;- for (const message of [...history].reverse()) {- if (picked.length >= HISTORY_MESSAGES) break;- const text = message.text.replace(/\s+/g, " ").trim().slice(0, HISTORY_MESSAGE_CHARS);- if (!text) continue;- if (total + text.length > HISTORY_TOTAL_CHARS) break;- total += text.length;- picked.unshift({ role: message.role, text });- }- return picked;-}-export interface CreateFishSessionInput {key: string;endpoint: LiveEndpoint;bot: LiveBot;history: LiveHistoryMessage[];cloudHome: boolean;+ historyLimits?: Partial<LiveHistoryLimits>;fetchImpl?: typeof fetch;timeoutMs?: number;}@@ -165,7 +159,13 @@ export async function createFishLiveSession(input: CreateFishSessionInput): Promconst body = {agent_id: input.endpoint.model,// Fish refuses an override the agent's `overrides_allowed` does not list (400).- overrides: { system_prompt: fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }) },+ overrides: {+ system_prompt: fishInstructions(input.bot, input.history, {+ cloudHome: input.cloudHome,+ historyLimits: input.historyLimits,+ provider: "fish",+ }),+ },};let response: Response;try {diff --git a/server/live-gemini.test.ts b/server/live-gemini.test.tsindex fcb8cf8061..844ebeb5bf 100644--- a/server/live-gemini.test.ts+++ b/server/live-gemini.test.ts@@ -97,4 +97,22 @@ describe("a Gemini Live call's token", () => {const fetchImpl = vi.fn(async () => { throw new TypeError("fetch failed"); });await expect(create(fetchImpl as unknown as typeof fetch)).rejects.toMatchObject({ status: 502, message: "Could not reach Gemini. Check the internet connection." });});++ it("sends configured history up to Gemini's higher cap", async () => {+ const fetchImpl = fakeGemini();+ const history = Array.from({ length: 150 }, (_, i) => ({ role: "user" as const, text: `gem-${i}` }));+ await createGeminiLiveSession({+ key: "k",+ endpoint: ENDPOINT,+ voice: "Puck",+ bot: { name: "Rigel" },+ history,+ cloudHome: false,+ historyLimits: { historyMessages: 150, historyMessageChars: 1_000, historyTotalChars: 40_000 },+ fetchImpl,+ now: () => NOW,+ });+ const text = JSON.parse(String(fetchImpl.mock.calls[0]![1]!.body)).bidiGenerateContentSetup.systemInstruction.parts[0].text as string;+ expect(text.match(/^User: /gm)).toHaveLength(150);+ });});diff --git a/server/live-gemini.ts b/server/live-gemini.tsindex 90821b682b..ff1400cdd2 100644--- a/server/live-gemini.ts+++ b/server/live-gemini.ts@@ -2,7 +2,7 @@// (model, instructions, the `delegate` tool) the harness locks here, and it relays what was said as a Fish Audio call does.import { randomBytes } from "node:crypto";import { geminiLiveVoice } from "../shared/live-call.ts";-import type { LiveGeminiSession } from "../shared/wire.ts";+import type { LiveGeminiSession, LiveHistoryLimits } from "../shared/wire.ts";import { LiveSessionError, type LiveBot, type LiveEndpoint, type LiveHistoryMessage } from "./live-call.ts";import { FISH_DELEGATE_TOOL, fishInstructions } from "./live-fish.ts";@@ -63,6 +63,7 @@ export interface CreateGeminiSessionInput {bot: LiveBot;history: LiveHistoryMessage[];cloudHome: boolean;+ historyLimits?: Partial<LiveHistoryLimits>;fetchImpl?: typeof fetch;now?: () => number;}@@ -73,7 +74,12 @@ export async function createGeminiLiveSession(input: CreateGeminiSessionInput):const key = input.key.trim();if (!key) throw new LiveSessionError("Add a Gemini API key in Settings → AI → Other services to use Live calls.", 409);const now = (input.now ?? Date.now)();- const setup = geminiLiveSetup(input.endpoint.model, fishInstructions(input.bot, input.history, { cloudHome: input.cloudHome }), input.voice);+ const instructions = fishInstructions(input.bot, input.history, {+ cloudHome: input.cloudHome,+ historyLimits: input.historyLimits,+ provider: "gemini",+ });+ const setup = geminiLiveSetup(input.endpoint.model, instructions, input.voice);const expiresAt = new Date(now + CONNECT_WITHIN_MS).toISOString();let response: Response;try {diff --git a/server/live-session-wiring.test.ts b/server/live-session-wiring.test.tsindex 322c19f143..612a2191ab 100644--- a/server/live-session-wiring.test.ts+++ b/server/live-session-wiring.test.ts@@ -210,4 +210,34 @@ describe("an ElevenLabs call's session", () => {const w = wiring(fakeFish());expect(w.calls.elevenlabsRefusal({ kind: "loopback", scopes: ["admin", "client"] })).toBeNull();});++ it("forwards configured historyLimits to Gemini, ElevenLabs, Fish Audio and OpenAI sessions", async () => {+ const history = Array.from({ length: 14 }, (_, i) => ({ role: "user" as const, text: `w-${i}` }));+ const fishFetch = fakeFish();+ const geminiFetch = vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => new Response(JSON.stringify({ name: "auth_tokens/t1" }), { status: 200 }));+ const elevenFetch = fakeElevenLabs();+ const openAiFetch = vi.fn(async (_url: string | URL | Request, _init?: RequestInit) => new Response(JSON.stringify({ session: { id: "s1" }, transport: { type: "webrtc", sdp: "v=0\r\na=1" } }), { status: 201 }));+ const wireWith = (fetchImpl: typeof fetch) => liveSessionWiring({+ bot: () => ({ name: "Rigel" }),+ history: () => history,+ cloudHome: false,+ othersOnLoopback: () => false,+ saveAgent: vi.fn(),+ env: {},+ fetchImpl,+ historyLimits: () => ({ historyMessages: 12, historyMessageChars: 800, historyTotalChars: 8_000 }),+ });++ await wireWith(fishFetch as unknown as typeof fetch).calls.createSession({ ...start, endpoint: fishLiveEndpoint("agent_saved", {}) });+ expect((JSON.parse(String(fishFetch.mock.calls[0]![1]!.body)).overrides.system_prompt as string).match(/^User: /gm)).toHaveLength(12);++ await wireWith(geminiFetch as unknown as typeof fetch).calls.createSession({ ...start, key: "g", endpoint: { provider: "gemini", apiBase: "https://generativelanguage.googleapis.com/v1beta", model: "gemini-3.8-live" } });+ expect((JSON.parse(String(geminiFetch.mock.calls[0]![1]!.body)).bidiGenerateContentSetup.systemInstruction.parts[0].text as string).match(/^User: /gm)).toHaveLength(12);++ const elSession = await wireWith(elevenFetch as unknown as typeof fetch).calls.createSession({ ...start, key: "e", endpoint: elevenLabsLiveEndpoint("agent_1", {}) });+ expect((elSession as { elevenlabs: { session: { instructions: string } } }).elevenlabs.session.instructions.match(/^User: /gm)).toHaveLength(12);++ await wireWith(openAiFetch as unknown as typeof fetch).calls.createSession({ ...start, key: "o", sdp: "v=0\r\n", endpoint: { provider: "openai", apiBase: "https://api.openai.com/v1", model: "gpt-realtime" } });+ expect(JSON.parse(String(openAiFetch.mock.calls[0]![1]!.body)).session.input).toHaveLength(12);+ });});diff --git a/server/live-session-wiring.ts b/server/live-session-wiring.tsindex 936498d8aa..2c7068c846 100644--- a/server/live-session-wiring.ts+++ b/server/live-session-wiring.ts@@ -1,3 +1,4 @@+import type { LiveHistoryLimits } from "../shared/wire.ts";import { productName } from "./brand.ts";import type { LiveCallDeps } from "./live-call-controller.ts";import { openLiveSocket, relayedProvider } from "./live-call-controller.ts";@@ -22,6 +23,7 @@ export interface LiveSessionWiringInput {fishAgentLanguage?(): string | undefined;/** The name a person reads, which names the agent on their account; the brand's own by default. */productName?(): string;+ historyLimits?(): Partial<LiveHistoryLimits> | undefined;env?: NodeJS.ProcessEnv;fetchImpl?: typeof fetch;}@@ -63,7 +65,7 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {};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 };const language = fishSpeakingLanguage(input.language?.());if (endpoint.model) await speakLanguage(key, endpoint, language);let agent = endpoint.model ? endpoint : await setUpAgent(key, endpoint, language);@@ -85,7 +87,7 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {};const startElevenLabs = 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 };try {return await createElevenLabsLiveSession({ ...session, endpoint: endpoint.model ? endpoint : await setUpElevenLabs(key, endpoint) });} catch (error) {@@ -102,8 +104,9 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {geminiRefusal: (auth) => geminiLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),elevenlabsRefusal: (auth) => elevenLabsLiveCallRefusal(auth, { othersOnLoopback: input.othersOnLoopback() }),createSession: async ({ key, endpoint, sdp, botId, threadId, voice }) => {+ 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 } };@@ -115,7 +118,7 @@ export function liveSessionWiring(input: LiveSessionWiringInput): {return { sessionId: session.session_id, elevenlabs: { type: "elevenlabs", session, relayToken: token } };}if (endpoint.provider !== "fish") {- return createLiveSession({ key, endpoint, sdp, voice, 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 });}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 --git a/server/live-settings.test.ts b/server/live-settings.test.tsindex 32b3a658e5..e8dce4a6b3 100644--- a/server/live-settings.test.ts+++ b/server/live-settings.test.ts@@ -353,3 +353,19 @@ describe("Live calls through ElevenLabs", () => {expect(JSON.stringify(settings)).not.toContain("eleven-secret");});});++describe("live history limit settings", () => {+ it("keeps defaults omitted until configured and clamps over-cap limits to the active provider", () => {+ expect(liveSettingsFor({ live: { provider: "gemini", historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 } } as AppConfig))+ .toMatchObject({ provider: "gemini", historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 });+ expect(liveSettingsFor({ live: { provider: "openai", historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 } } as AppConfig))+ .toMatchObject({ historyMessages: 128, historyMessageChars: 8_000, historyTotalChars: 24_000 });+ });++ it("validates history limit patches against the effective provider's limit", () => {+ expect(() => liveSavePatch({ provider: "openai" }, { historyMessages: 200 })).toThrow(expect.objectContaining({ status: 400 }));+ expect(() => liveSavePatch({ provider: "fish" }, { historyMessageChars: 6_000 })).toThrow(expect.objectContaining({ status: 400 }));+ expect(liveSavePatch({ provider: "openai" }, { provider: "gemini", historyMessages: 200, historyMessageChars: 10_000, historyTotalChars: 50_000 }))+ .toEqual({ provider: "gemini", historyMessages: 200, historyMessageChars: 10_000, historyTotalChars: 50_000 });+ });+});diff --git a/server/live-settings.ts b/server/live-settings.tsindex 6224d4d612..8d5432f475 100644--- a/server/live-settings.ts+++ b/server/live-settings.ts@@ -1,4 +1,5 @@-import type { LiveKeySource, LiveSettings } from "../shared/wire.ts";+import type { LiveHistoryLimits, LiveKeySource, LiveProvider, LiveSettings } 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";@@ -71,6 +72,16 @@ export function liveSettingsForClient({ azureEndpoint: _endpoint, azureDeploymenreturn 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);@@ -87,5 +98,6 @@ export function liveSettingsFor(cfg: AppConfig): LiveSettings {...(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,+ ...liveHistorySettings(cfg.live, provider),};}diff --git a/server/routes/live.test.ts b/server/routes/live.test.tsindex 042a10d291..9d97cc390b 100644--- a/server/routes/live.test.ts+++ b/server/routes/live.test.ts@@ -303,3 +303,16 @@ describe("a Fish Audio call", () => {expect(fishRelay).not.toHaveBeenCalled();});});++describe("live history limit route validation", () => {+ it("accepts history limits within the provider's cap and rejects exceeding or out-of-range values", async () => {+ const d = deps();+ expect(await request(d, "PATCH", "/api/live/settings", { historyMessages: 32, historyMessageChars: 2_000, historyTotalChars: 12_000 }))+ .toMatchObject({ status: 200, body: { live: { historyMessages: 32, historyMessageChars: 2_000, historyTotalChars: 12_000 } } });+ expect((await request(d, "PATCH", "/api/live/settings", { historyMessages: 200 })).status).toBe(400);+ expect((await request(d, "PATCH", "/api/live/settings", { historyMessageChars: 99 })).status).toBe(400);+ expect((await request(d, "PATCH", "/api/live/settings", { historyTotalChars: 499 })).status).toBe(400);+ expect(await request(d, "PATCH", "/api/live/settings", { provider: "gemini", historyMessages: 200 }))+ .toMatchObject({ status: 200, body: { live: { provider: "gemini", historyMessages: 200 } } });+ });+});diff --git a/server/routes/live.ts b/server/routes/live.tsindex 5a00df5aac..2d4956e76a 100644--- a/server/routes/live.ts+++ b/server/routes/live.ts@@ -2,7 +2,7 @@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 { LiveCallBusyError, type LiveCallController } from "../live-call-controller.ts";import { RELAY_POLL_MS } from "../live-fish.ts";@@ -14,7 +14,7 @@ export interface LiveRouteDeps {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; readTypedReplies?: boolean; idleMinutes?: 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>;/** 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;}@@ -58,6 +58,9 @@ 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(),+ 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}$/;@@ -136,6 +139,8 @@ export function createLiveRoutes(deps: LiveRouteDeps): RouteHandler {return json(res, 400, { error: "Those Live settings are not valid." });}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) });}diff --git a/shared/live-call.test.ts b/shared/live-call.test.tsindex d0092deef7..2b75592b32 100644--- a/shared/live-call.test.ts+++ b/shared/live-call.test.ts@@ -1,6 +1,10 @@import { describe, expect, it } from "vitest";-import { botCallVoice, clampAppend, commentaryChunks, formatCallDuration, FULL_ANSWER_IN_CHAT, geminiLiveVoice, isBotLiveVoice, joinFragments, LIVE_VOICE_OPTIONS, LiveTranscript, liveCallRowText, SpokenLines } from "./live-call.ts";+import {+ botCallVoice, clampAppend, commentaryChunks, DEFAULT_LIVE_HISTORY_LIMITS, formatCallDuration, FULL_ANSWER_IN_CHAT,+ geminiLiveVoice, isBotLiveVoice, joinFragments, LIVE_HISTORY_MIN, LIVE_HISTORY_PROVIDER_CAPS, LIVE_VOICE_OPTIONS,+ LiveTranscript, liveCallRowText, liveHistoryCaps, resolveLiveHistoryLimits, SpokenLines,+} from "./live-call.ts";describe("Live call voices", () => {it.each(["nuri", "juni", "flitz", "brise", "sillage", "nira", "harema", "shida", "noeul"])("offers %s as a bot's OpenAI voice without using it for Gemini", (voice) => {@@ -190,3 +194,34 @@ describe("a call's length", () => {expect(liveCallRowText("Ada", 3_725)).toBe("Call with Ada · 1:02:05");});});++describe("Live call history limits", () => {+ it("starts at the existing defaults and exposes provider ceilings", () => {+ expect(DEFAULT_LIVE_HISTORY_LIMITS).toEqual({+ historyMessages: 8,+ historyMessageChars: 600,+ historyTotalChars: 6_000,+ });+ expect(LIVE_HISTORY_MIN).toEqual({+ historyMessages: 0,+ historyMessageChars: 100,+ historyTotalChars: 500,+ });+ expect(liveHistoryCaps(undefined)).toEqual(LIVE_HISTORY_PROVIDER_CAPS.openai);+ expect(liveHistoryCaps("openai")).toEqual({ maxMessages: 128, maxMessageChars: 8_000, maxTotalChars: 24_000 });+ expect(liveHistoryCaps("fish")).toEqual({ maxMessages: 100, maxMessageChars: 4_000, maxTotalChars: 20_000 });+ expect(liveHistoryCaps("gemini")).toEqual({ maxMessages: 200, maxMessageChars: 12_000, maxTotalChars: 60_000 });+ });++ it("clamps configured limits between provider bounds and ignores non-finite values", () => {+ expect(resolveLiveHistoryLimits(undefined, "openai")).toEqual(DEFAULT_LIVE_HISTORY_LIMITS);+ expect(resolveLiveHistoryLimits({ historyMessages: 0, historyMessageChars: 200, historyTotalChars: 1_500 }, "openai"))+ .toEqual({ historyMessages: 0, historyMessageChars: 200, historyTotalChars: 1_500 });+ expect(resolveLiveHistoryLimits({ historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 }, "gemini"))+ .toEqual({ historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 });+ expect(resolveLiveHistoryLimits({ historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 }, "openai"))+ .toEqual({ historyMessages: 128, historyMessageChars: 8_000, historyTotalChars: 24_000 });+ expect(resolveLiveHistoryLimits({ historyMessages: -5, historyMessageChars: Number.NaN, historyTotalChars: 50 }, "openai"))+ .toEqual({ historyMessages: 0, historyMessageChars: 600, historyTotalChars: 500 });+ });+});diff --git a/src/components/LiveCallBar.render.test.ts b/src/components/LiveCallBar.render.test.tsindex b4a57aabb3..16d025bcb3 100644--- a/src/components/LiveCallBar.render.test.ts+++ b/src/components/LiveCallBar.render.test.ts@@ -229,3 +229,28 @@ describe("LiveKeySetup", () => {expect(markup).not.toContain("stays on your computer");});});++describe("LiveCallSettings history limits", () => {+ function renderWithLive(live: LiveSettings) {+ const config = { cloudHome: false, live } as AppState["config"];+ const value = { state: { ...initialState, config }, dispatch: vi.fn(), flushBotPatches: async () => null, refreshInstances: async () => {}, refreshModels: async () => {} };+ return renderToStaticMarkup(createElement(BotEditorStore, { value, children: createElement(LiveCallSettings, { onClose: vi.fn() }) }));+ }++ it("shows configurable history selects capped by the active provider", () => {+ const openai = renderWithLive({ configured: true, provider: "openai", voice: "marin", readTypedReplies: true, idleMinutes: 5 });+ expect(openai).toContain("Chat history messages");+ expect(openai).toContain("Chars per message");+ expect(openai).toContain("Total history chars");+ const messagesSelect = /Chat history messages[\s\S]*?<select[\s\S]*?<\/select>/.exec(openai)?.[0] ?? "";+ expect(messagesSelect).toContain('value="128"');+ expect(messagesSelect).not.toContain('value="200"');+ expect(openai).toContain('value="24000"');+ expect(openai).not.toContain('value="60000"');++ const gemini = renderWithLive({ configured: true, provider: "gemini", voice: "marin", readTypedReplies: true, idleMinutes: 5, historyMessages: 200, historyMessageChars: 12_000, historyTotalChars: 60_000 });+ const geminiMessagesSelect = /Chat history messages[\s\S]*?<select[\s\S]*?<\/select>/.exec(gemini)?.[0] ?? "";+ expect(geminiMessagesSelect).toContain('value="200"');+ expect(gemini).toContain('value="60000"');+ });+});diff --git a/src/components/LiveCallSettings.tsx b/src/components/LiveCallSettings.tsxindex bd9bfcf7ba..682baf565d 100644--- a/src/components/LiveCallSettings.tsx+++ b/src/components/LiveCallSettings.tsx@@ -1,10 +1,13 @@import { useCallback, useId, useState } from "react";-import { GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_VOICE_OPTIONS } from "../../shared/live-call";-import { t } from "@/lib/i18n";+import {+ GEMINI_LIVE_VOICE_OPTIONS, geminiLiveVoice, LIVE_HISTORY_MIN, 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,6 +15,15 @@ import { KeysLink } from "./keys/KeysLink";import { Select } from "./Select";const IDLE_CHOICES = [1, 2, 3, 5, 10, 15, 30, 60];+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 }) {@@ -39,7 +51,7 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "namconst 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">>) => {+ const save = async (patch: Partial<Pick<LiveSettings, "voice" | "geminiVoice" | "readTypedReplies" | "idleMinutes" | keyof LiveHistoryLimits>>) => {setSaving(true);setError(null);try {@@ -67,6 +79,35 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam}};+ const historyCaps = liveHistoryCaps(live.provider);+ const historyLimits = resolveLiveHistoryLimits(live, live.provider);+ const historyRows: Array<{+ key: keyof LiveHistoryLimits;+ label: "call.live.historyMessages" | "call.live.historyMessageChars" | "call.live.historyTotalChars";+ options: number[];+ value: number;+ }> = [+ {+ key: "historyMessages",+ label: "call.live.historyMessages",+ options: limitChoices(HISTORY_MESSAGE_CHOICES, historyLimits.historyMessages, LIVE_HISTORY_MIN.historyMessages, historyCaps.maxMessages),+ value: historyLimits.historyMessages,+ },+ {+ key: "historyMessageChars",+ label: "call.live.historyMessageChars",+ options: limitChoices(HISTORY_MESSAGE_CHAR_CHOICES, historyLimits.historyMessageChars, LIVE_HISTORY_MIN.historyMessageChars, historyCaps.maxMessageChars),+ value: historyLimits.historyMessageChars,+ },+ {+ key: "historyTotalChars",+ label: "call.live.historyTotalChars",+ options: limitChoices(HISTORY_TOTAL_CHAR_CHOICES, historyLimits.historyTotalChars, LIVE_HISTORY_MIN.historyTotalChars, historyCaps.maxTotalChars),+ value: historyLimits.historyTotalChars,+ },+ ];+ const historyHintId = useId();+return (<divref={focusOnOpen}@@ -124,6 +165,29 @@ export function LiveCallSettings({ bot, onClose }: { bot?: Pick<Bot, "id" | "nam))}</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 --git a/src/locales/en.json b/src/locales/en.jsonindex 116fdc079a..e110fd9ae7 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6980,6 +6980,10 @@"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.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",