Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(decider): offer Gemini on OpenRouter in the decision model picker (#5712)
Bugfixer 25c5d6f33a656
diff --git a/docs/decision-model.md b/docs/decision-model.mdindex 5be9d31e85..a0c21ca31d 100644--- a/docs/decision-model.md+++ b/docs/decision-model.md@@ -68,12 +68,17 @@ A failed decision falls back as described in "It fails open".answer in the same shape through chat completions, and its probabilitiesare its own estimate.-The model list holds decisions models only: a curated set, in the order of-OpenRouter's decisions ranking, that shows only what OpenRouter's public-catalog (`/models?output_modalities=decisions`) still lists, then the rest of-that catalog. Chat models are not offered, though one saved by hand with-`openrouterApi: "chat"` still works. If OpenRouter's catalog cannot be-loaded, Settings shows the curated list and says so. A model saved by id (`decider.openrouterModel`) is+The model list holds decisions models first: a curated set, in the order of+OpenRouter's decisions ranking (Google's Gemini Decision 1 included), that+shows only what OpenRouter's public catalog+(`/models?output_modalities=decisions`) still lists, then the rest of that+catalog. Last, under **Gemini chat models (not calibrated)**, come the Gemini+Flash chat models that catalog's text list (`/models?output_modalities=text`)+says take a strict JSON schema; picking one saves `openrouterApi: "chat"`, so+its probabilities are its own estimate (and extraction uses it too, as with+any chat model). Use **Test** to check it answers in time. Other chat models are not offered, though+one saved by hand with `openrouterApi: "chat"` still works. If OpenRouter's+catalog cannot be loaded, Settings shows the curated list and says so. A model saved by id (`decider.openrouterModel`) isused even if the list does not carry it. **Test** shows how long the model took;above 1.5 seconds, rooms would fall back to the lead, so pick a faster one.diff --git a/server/decider/openrouter-models.test.ts b/server/decider/openrouter-models.test.tsindex 78779dbe02..e8a6f966d4 100644--- a/server/decider/openrouter-models.test.ts+++ b/server/decider/openrouter-models.test.ts@@ -1,8 +1,9 @@import { describe, expect, it, vi } from "vitest";-import { OPENROUTER_DECIDER_MODELS, createOpenRouterModelCatalog, decisionsModels, mergeModels } from "./openrouter-models.ts";+import { OPENROUTER_DECIDER_MODELS, createOpenRouterModelCatalog, decisionsModels, geminiChatModels, mergeModels } from "./openrouter-models.ts";const URL_OK = "https://openrouter.ai/api/v1/models?output_modalities=decisions";+const URL_TEXT = "https://openrouter.ai/api/v1/models?output_modalities=text";const model = (id: string, extra: Record<string, unknown> = {}) => ({id,name: `Name of ${id}`,@@ -11,6 +12,8 @@ const model = (id: string, extra: Record<string, unknown> = {}) => ({...extra,});const catalog = (...models: unknown[]) => new Response(JSON.stringify({ data: models }), { status: 200 });+const chat = (id: string, extra: Record<string, unknown> = {}) =>+ model(id, { supported_parameters: ["max_tokens", "temperature", "response_format", "structured_outputs"], architecture: { output_modalities: ["text"] }, ...extra });describe("which OpenRouter models the picker offers", () => {it("keeps decisions models, saveable ids only, and drops chat models and ~aliases", () => {@@ -50,6 +53,29 @@ describe("which OpenRouter models the picker offers", () => {expect(mergeModels(new Map([["alpha/model", "Alpha"]])).source).toBe("builtin");});+ it("offers Gemini Flash chat models that take every chat parameter, as uncalibrated chat models sorted by name (#5712)", () => {+ const found = geminiChatModels({+ data: [+ chat("google/gemini-3.5-flash", { name: "Google: Gemini 3.5 Flash" }),+ chat("google/gemini-2.5-flash", { name: "Google: Gemini 2.5 Flash" }),+ chat("google/gemini-3.5-flash:batch"),+ chat("google/gemini-3-pro-image", { architecture: { output_modalities: ["image", "text"] } }),+ chat("google/gemini-omni-1.2-flash", { architecture: { output_modalities: ["text", "video"] } }),+ chat("google/gemini-old-flash", { supported_parameters: ["max_tokens", "temperature", "response_format"] }),+ chat("google/gemini-2.5-pro"),+ chat("google/gemma-4"),+ chat("acme/gemini-clone"),+ chat("google/gemini-flash-no-arch", { architecture: undefined }),+ "junk",+ ],+ });+ expect(found).toEqual([+ { id: "google/gemini-2.5-flash", name: "Google: Gemini 2.5 Flash", group: "chat", api: "chat" },+ { id: "google/gemini-3.5-flash", name: "Google: Gemini 3.5 Flash", group: "chat", api: "chat" },+ ]);+ expect(geminiChatModels({ error: "nope" })).toBeNull();+ });+it("is all decisions models, led by the default", () => {expect(OPENROUTER_DECIDER_MODELS[0]!.id).toBe("typesafe/jev-1.13");expect(new Set(OPENROUTER_DECIDER_MODELS.map((m) => m.id)).size).toBe(OPENROUTER_DECIDER_MODELS.length);@@ -57,23 +83,26 @@ describe("which OpenRouter models the picker offers", () => {});describe("the model catalog", () => {- it("asks for decisions models only, loads once and caches for an hour; sends no key and refuses redirects", async () => {+ it("asks for decisions models and the Gemini text list, loads each once and caches for an hour; sends no key and refuses redirects", async () => {let clock = 1_000;- const fetchImpl = vi.fn<typeof fetch>(async () => catalog(model(OPENROUTER_DECIDER_MODELS[0]!.id), model("alpha/model")));+ const fetchImpl = vi.fn<typeof fetch>(async (url) =>+ String(url) === URL_TEXT ? catalog(chat("google/gemini-2.5-flash")) : catalog(model(OPENROUTER_DECIDER_MODELS[0]!.id), model("alpha/model")));const models = createOpenRouterModelCatalog({ fetch: fetchImpl, now: () => clock });const first = await models.load();expect(first).toMatchObject({ source: "openrouter" });expect(first.models.find((m) => m.id === "alpha/model")).toMatchObject({ group: "more", api: "decisions" });- const [url, init] = fetchImpl.mock.calls[0]!;- expect(String(url)).toBe(URL_OK);- expect(init?.headers).not.toHaveProperty("authorization");- expect(init?.redirect).toBe("error");+ expect(first.models.at(-1)).toMatchObject({ id: "google/gemini-2.5-flash", group: "chat", api: "chat" });+ expect(fetchImpl.mock.calls.map(([url]) => String(url)).sort()).toEqual([URL_OK, URL_TEXT]);+ for (const [, init] of fetchImpl.mock.calls) {+ expect(init?.headers).not.toHaveProperty("authorization");+ expect(init?.redirect).toBe("error");+ }clock += 59 * 60_000;await models.load();- expect(fetchImpl).toHaveBeenCalledTimes(1);+ expect(fetchImpl).toHaveBeenCalledTimes(2);clock += 2 * 60_000;await models.load();- expect(fetchImpl).toHaveBeenCalledTimes(2);+ expect(fetchImpl).toHaveBeenCalledTimes(4);});it.each([@@ -91,10 +120,28 @@ describe("the model catalog", () => {expect(list.models.every((m) => m.group === "recommended" && m.api === "decisions")).toBe(true);clock += 30_000;await models.load();- expect(fetchImpl).toHaveBeenCalledTimes(1);+ expect(fetchImpl).toHaveBeenCalledTimes(2);clock += 31_000;await models.load();- expect(fetchImpl).toHaveBeenCalledTimes(2);+ expect(fetchImpl).toHaveBeenCalledTimes(4);+ });++ it("still lists the decisions models when only the Gemini catalog fails, and image catalogs never ask for it", async () => {+ const fetchImpl = vi.fn<typeof fetch>(async (url) =>+ String(url) === URL_TEXT ? new Response("no", { status: 500 }) : catalog(model(OPENROUTER_DECIDER_MODELS[0]!.id)));+ const list = await createOpenRouterModelCatalog({ fetch: fetchImpl }).load();+ expect(list.source).toBe("openrouter");+ expect(list.models.some((m) => m.group === "chat")).toBe(false);+ // Nor beside the built-in list, whose note says the catalog could not be loaded; and never an id twice.+ const decisionsDown = vi.fn<typeof fetch>(async (url) => String(url) === URL_TEXT ? catalog(chat("google/gemini-2.5-flash")) : new Response("no", { status: 500 }));+ expect((await createOpenRouterModelCatalog({ fetch: decisionsDown }).load()).models.some((m) => m.group === "chat")).toBe(false);+ const both = vi.fn<typeof fetch>(async (url) =>+ String(url) === URL_TEXT ? catalog(chat("google/gemini-x-flash")) : catalog(model(OPENROUTER_DECIDER_MODELS[0]!.id), model("google/gemini-x-flash")));+ const ids = (await createOpenRouterModelCatalog({ fetch: both }).load()).models.filter((m) => m.id === "google/gemini-x-flash");+ expect(ids).toEqual([expect.objectContaining({ api: "decisions" })]);+ const imageFetch = vi.fn<typeof fetch>(async () => catalog(model("acme/painter", { architecture: { output_modalities: ["image"] } })));+ await createOpenRouterModelCatalog({ fetch: imageFetch, output: "image", curated: [{ id: "acme/painter", name: "Painter" }] }).load();+ expect(imageFetch).toHaveBeenCalledTimes(1);});it("never fetches from an address a key could not be sent to", async () => {diff --git a/server/decider/openrouter-models.ts b/server/decider/openrouter-models.tsindex 80c5fc3cd8..2ec5430e55 100644--- a/server/decider/openrouter-models.ts+++ b/server/decider/openrouter-models.ts@@ -4,8 +4,9 @@ import { OPENROUTER_DEFAULT_MODEL, openrouterEndpoint } from "./openrouter.ts";export interface OpenRouterModel {id: string;name: string;- group: "recommended" | "more";- api: CatalogOutput;+ group: "recommended" | "more" | "chat";+ /** `chat`: a chat model answering through the JSON schema, not calibrated like a decisions model. */+ api: CatalogOutput | "chat";}/** The OpenRouter output modality a catalog lists; it also tags each model. */@@ -26,8 +27,14 @@ export const OPENROUTER_DECIDER_MODELS: ReadonlyArray<{ id: string; name: string{ id: "inception/mercury-decide", name: "Inception: Mercury Decide" },{ id: "cloudflare/clef", name: "Cloudflare: Clef" },{ id: "nace-ai/drex-v2.0", name: "Nace.AI: Drex v2.0" },+ { id: "google/gemini-decision-1", name: "Google: Gemini Decision 1" },];+/** Gemini chat models (#5712): the fast Flash tier only (a decision must answer within 1.5 s), no `:batch` or other variant. */+const GEMINI_CHAT_ID = /^google\/gemini-[^:]*flash[^:]*$/;+/** Every parameter the chat request sends (`openrouterRequestBody`); it asks OpenRouter for hosts that honour them all. */+const CHAT_PARAMETERS = ["max_tokens", "temperature", "response_format", "structured_outputs"];+const FETCH_TIMEOUT_MS = 3_000;const OK_TTL_MS = 60 * 60_000;const FAILED_TTL_MS = 60_000;@@ -62,6 +69,24 @@ export function modelsWithOutput(body: unknown, output: CatalogOutput): Map<strireturn found;}+/** Gemini chat models for the decision picker: text out only (no image or video makers), and every parameter+ * the chat path sends. Listed apart because their probabilities are not calibrated. */+export function geminiChatModels(body: unknown): OpenRouterModel[] | null {+ if (!isRecord(body) || !Array.isArray(body.data)) return null;+ const found: OpenRouterModel[] = [];+ for (const entry of body.data) {+ if (!isRecord(entry) || typeof entry.id !== "string" || !GEMINI_CHAT_ID.test(entry.id)) continue;+ if (entry.id.length > OPENROUTER_MODEL_ID_MAX || !OPENROUTER_MODEL_ID.test(entry.id)) continue;+ const outputs = isRecord(entry.architecture) ? entry.architecture.output_modalities : undefined;+ if (!Array.isArray(outputs) || outputs.length === 0 || outputs.some((output) => output !== "text")) continue;+ const parameters = entry.supported_parameters;+ if (!Array.isArray(parameters) || !CHAT_PARAMETERS.every((parameter) => parameters.includes(parameter))) continue;+ const name = typeof entry.name === "string" && entry.name.trim() ? entry.name.trim() : entry.id;+ found.push({ id: entry.id, name, group: "chat", api: "chat" });+ }+ return found.sort((a, b) => a.name.localeCompare(b.name)).slice(0, MORE_MAX);+}+export function mergeModels(found: Map<string, string>, curated: Curated = OPENROUTER_DECIDER_MODELS, api: CatalogOutput = "decisions"): OpenRouterModelList {const recommended = curated.filter((model) => found.has(model.id))@@ -90,9 +115,9 @@ export function createOpenRouterModelCatalog(deps: OpenRouterModelCatalogDeps =const now = deps.now ?? (() => Date.now());const output = deps.output ?? "decisions";const curated = deps.curated ?? OPENROUTER_DECIDER_MODELS;- const cache = new Map<string, { until: number; list: OpenRouterModelList }>();+ const cache = new Map<string, { until: number; value: unknown }>();- async function fetchList(endpoint: URL): Promise<OpenRouterModelList | null> {+ async function fetchBody(endpoint: URL): Promise<unknown> {try {const response = await fetchImpl(endpoint, {headers: { accept: "application/json" },@@ -103,24 +128,39 @@ export function createOpenRouterModelCatalog(deps: OpenRouterModelCatalogDeps =await response.body?.cancel().catch(() => undefined);return null;}- const found = modelsWithOutput(await response.json(), output);- return found ? mergeModels(found, curated, output) : null;+ return await response.json();} catch {return null;}}+ /** One catalog modality, read by `read` (null = unusable): cached an hour, or a minute as `fallback` when unusable. */+ async function cachedLoad<T>(baseUrl: string | null | undefined, modality: string, read: (body: unknown) => T | null, fallback: T): Promise<T> {+ const endpoint = openrouterEndpoint(baseUrl, "models");+ if (!endpoint) return fallback;+ endpoint.searchParams.set("output_modalities", modality);+ const cached = cache.get(endpoint.href);+ if (cached && cached.until > now()) return cached.value as T;+ const read_ = read(await fetchBody(endpoint));+ const value = read_ ?? fallback;+ cache.set(endpoint.href, { until: now() + (read_ === null ? FAILED_TTL_MS : OK_TTL_MS), value });+ return value;+ }++ const readList = (body: unknown): OpenRouterModelList | null => {+ const found = modelsWithOutput(body, output);+ const list = found ? mergeModels(found, curated, output) : null;+ return list?.source === "openrouter" ? list : null;+ };return {async load(baseUrl?: string | null): Promise<OpenRouterModelList> {- const endpoint = openrouterEndpoint(baseUrl, "models");- if (!endpoint) return builtin(curated, output);- endpoint.searchParams.set("output_modalities", output);- const cached = cache.get(endpoint.href);- if (cached && cached.until > now()) return cached.list;- const fetched = await fetchList(endpoint);- const list = fetched?.source === "openrouter" ? fetched : builtin(curated, output);- cache.set(endpoint.href, { until: now() + (list.source === "openrouter" ? OK_TTL_MS : FAILED_TTL_MS), list });- return list;+ const list = cachedLoad(baseUrl, output, readList, builtin(curated, output));+ if (output !== "decisions") return list;+ // The Gemini chat models (#5712) come after the live decisions list; none beside the built-in one.+ const [decisions, chat] = await Promise.all([list, cachedLoad(baseUrl, "text", geminiChatModels, [])]);+ if (decisions.source !== "openrouter" || !chat.length) return decisions;+ const ids = new Set(decisions.models.map((model) => model.id));+ return { ...decisions, models: [...decisions.models, ...chat.filter((model) => !ids.has(model.id))] };},};}diff --git a/src/components/DecisionModelSettings.tsx b/src/components/DecisionModelSettings.tsxindex 163061d26f..dab5a4c843 100644--- a/src/components/DecisionModelSettings.tsx+++ b/src/components/DecisionModelSettings.tsx@@ -14,7 +14,8 @@ const KEY_URL = { jev: "https://typesafe.ai", openrouter: "https://openrouter.aiconst ROOM_BUDGET_MS = 1_500;type Provider = "jev" | "openrouter";-type ModelList = { source: "openrouter" | "builtin"; models: Array<{ id: string; name: string; group: "recommended" | "more"; api?: "chat" | "decisions" }> };+type ModelList = { source: "openrouter" | "builtin"; models: Array<{ id: string; name: string; group: "recommended" | "more" | "chat"; api?: "chat" | "decisions" }> };+const MODEL_GROUP = { recommended: "decider.model.recommended", more: "decider.model.more", chat: "decider.model.geminiChat" } as const satisfies Record<string, LocaleKey>;type TestResult = { ok: true; latencyMs: number } | { ok: false; reason: string; status?: number };const FAILURES: Record<string, LocaleKey> = {@@ -259,10 +260,10 @@ export function DecisionModelSettings() {{decider?.model && !models?.models.some((model) => model.id === decider.model) && (<option value={decider.model}>{decider.model}</option>)}- {(["recommended", "more"] as const).map((group) => {+ {(["recommended", "more", "chat"] as const).map((group) => {const inGroup = models?.models.filter((model) => model.group === group) ?? [];return inGroup.length > 0 && (- <optgroup key={group} label={t(group === "recommended" ? "decider.model.recommended" : "decider.model.more")}>+ <optgroup key={group} label={t(MODEL_GROUP[group])}>{inGroup.map((model) => <option key={model.id} value={model.id}>{model.name}</option>)}</optgroup>);diff --git a/src/locales/en.json b/src/locales/en.jsonindex 93c5e67a71..2ae7895e0c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -4123,6 +4123,7 @@"decider.model.label": "Model","decider.model.recommended": "Recommended","decider.model.more": "More models",+ "decider.model.geminiChat": "Gemini chat models (not calibrated)","decider.model.builtinNote": "OpenRouter's model catalog could not be loaded, so this is the built-in list.","decider.openrouter.master": "Use OpenRouter for fast decisions","decider.openrouter.key.label": "OpenRouter API key",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex b1de15c1f0..14cf29c859 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -3929,6 +3929,7 @@"decider.model.label": "Modelo","decider.model.recommended": "Recomendados","decider.model.more": "Mais modelos",+ "decider.model.geminiChat": "Modelos de chat Gemini (não calibrados)","decider.model.builtinNote": "Não foi possível carregar o catálogo de modelos do OpenRouter. Por isso, esta é a lista que vem com o app.","decider.openrouter.master": "Usar o OpenRouter para decisões rápidas","decider.openrouter.key.label": "Chave de API do OpenRouter",diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.jsonindex 74adbc6493..d394d95d18 100644--- a/src/locales/source-hashes.json+++ b/src/locales/source-hashes.json@@ -36732,7 +36732,8 @@"settings.browser.proxyConfigured": "05565d7de5c36e10f5859900c77b9a3600c48ccf213cfbe5ebb5afd1225f5cd8","settings.browser.proxyInactive": "ab2ef0c1c52fc3ffb24536578e5eb2a8d06a7027291bfd480eb577a4a3d1b9da","settings.browser.proxySave": "1509f561f2416598629b886ad7d3c05a7e221e4e0675c84bbff4ee6d9e03913d",- "settings.browser.proxyClear": "c3812fc4acb861d5182fc2b8155f327f736fbe5e5eb86a7bd7afcb6dc5497282"+ "settings.browser.proxyClear": "c3812fc4acb861d5182fc2b8155f327f736fbe5e5eb86a7bd7afcb6dc5497282",+ "decider.model.geminiChat": "2fa5b94b52ece98b2ad0a021d1c80d226031b3a885fd78d5f82e630bfa9305a9"},"zh": {"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",