Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Only ask a server for Ollama's model list once it has answered as Ollama
milind-soni5a53e17a5b63
diff --git a/server/drivers/ollama.test.ts b/server/drivers/ollama.test.tsindex 2561e2f4a3..cf9dd30dff 100644--- a/server/drivers/ollama.test.ts+++ b/server/drivers/ollama.test.ts@@ -31,10 +31,12 @@ interface FakeModel { name: string; size?: number; details?: Record<string, unknasync function fakeOllama(options: { models?: FakeModel[]; version?: string | null; tags?: boolean } = {}) {const models = options.models ?? [];const chats: Array<{ model: string; tools?: unknown[] }> = [];+ const asked: string[] = [];const server = createServer(async (request, response) => {let data = "";for await (const part of request) data += part.toString();const path = request.url ?? "";+ asked.push(path);const json = (body: unknown, status = 200) => {response.writeHead(status, { "content-type": "application/json" });response.end(JSON.stringify(body));@@ -58,7 +60,7 @@ async function fakeOllama(options: { models?: FakeModel[]; version?: string | nu});await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));running.push(server);- return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, chats };+ return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`, chats, asked };}/** An address nothing listens on. */@@ -171,9 +173,9 @@ describe("finding Ollama", () => {it("takes the first address that runs, else what the first address said", async () => {const { url } = await fakeOllama({ models: [LLAMA] });const closed = await closedPort();- expect(await findOllama([closed, url])).toMatchObject({ state: "ready", url });+ expect(await findOllama([closed], { localUrls: [url] })).toMatchObject({ state: "ready", url });const silent = await silentServer();- expect(await findOllama([closed, silent], { timeoutMs: 150 })).toMatchObject({ state: "unreachable", url: silent });+ expect(await findOllama([closed, silent], { timeoutMs: 150, localUrls: [] })).toMatchObject({ state: "unreachable", url: silent });});});@@ -257,6 +259,18 @@ describe("the chat engine on Ollama", () => {} finally { await instance.dispose(); }});+ it("never asks another server on this network for Ollama's model list", async () => {+ const { url, asked } = await fakeOllama({ models: [LLAMA], version: null });+ const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY" }, { FIXTURE_KEY: "fixture-key" });+ try {+ await instance.refreshModels?.();+ await instance.snapshot();+ expect(asked).toContain("/api/version");+ expect(asked).not.toContain("/api/tags");+ expect(instance.models.options.map((option) => option.id)).toEqual(["llama3.2:latest"]);+ } finally { await instance.dispose(); }+ });+it("asks nothing of a server on this network that has a fixed model list", async () => {const { url } = await fakeOllama({ models: [LLAMA] });const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY", managedModels: ["llama3.2:latest"] }, { FIXTURE_KEY: "fixture-key" });diff --git a/server/drivers/ollama.ts b/server/drivers/ollama.tsindex 38784fabb9..899bfce544 100644--- a/server/drivers/ollama.ts+++ b/server/drivers/ollama.ts@@ -105,6 +105,8 @@ export interface ProbeOptions {key?: string;/** Also ask /api/show what each model can do. */capabilities?: boolean;+ /** Where "this computer" is looked for, when not Ollama's defaults. */+ localUrls?: readonly string[];}/** Never throws. */@@ -158,7 +160,7 @@ const RANK: Record<OllamaState, number> = { ready: 0, "no-models": 1, unreachabl/** Ollama on this computer, or at an address someone set: the first that runs, else what the first address said. */export async function findOllama(urls: readonly string[] = [], options: ProbeOptions = {}): Promise<OllamaStatus> {- const origins = [...new Set([...urls, ...OLLAMA_LOCAL_URLS].map(ollamaOrigin))];+ const origins = [...new Set([...urls, ...(options.localUrls ?? OLLAMA_LOCAL_URLS)].map(ollamaOrigin))];const found = await Promise.all(origins.map((origin) => probeOllama(origin, options)));return found.reduce((best, status) => RANK[status.state] < RANK[best.state] ? status : best);}diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 938a07e789..5fabba0f77 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -4,7 +4,7 @@ import type { ModelCatalog, ProviderDriver } from "../contracts.ts";import { isLoopback } from "../provider-key-check.ts";import { lmStudioV1Catalog } from "./local-inject.ts";import { isContextName, isOllama, serveWithWindow } from "./ollama-context.ts";-import { answeredAsOllama, isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaUnavailable, onOllamaPort, probeOllama, type OllamaModel, type OllamaStatus } from "./ollama.ts";+import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, type OllamaModel, type OllamaStatus } from "./ollama.ts";import { createOpenAIChatRuntime } from "./openai-chat.ts";import {freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,@@ -192,7 +192,9 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {"";// A server someone gave a fixed model list to is not asked what else it might be, unless it is on Ollama's own port.const ollamaCandidate = config.catalog === "ollama" || (config.catalog === undefined && (onOllamaPort(config.url) || (onThisNetwork(config.url) && !config.managedModels)));- if (!savedKey && ollamaCandidate && !isOllamaServer(config)) await probeOllama(config.url, { timeoutMs: 1_500 });+ // Another server on this network is only asked for Ollama's model list once it has answered Ollama's version route.+ const answersAsOllama = () => isOllamaServer(config) || isOllama(ollamaOrigin(config.url));+ if (!savedKey && ollamaCandidate && !isOllamaServer(config) && await answersAsOllama()) await probeOllama(config.url, { timeoutMs: 1_500 });const apiKey = savedKey || (ollamaCandidate && isOllamaServer(config) ? OLLAMA_PLACEHOLDER_KEY : "");const missingKey = !ownKeyVariable || OWN_KEY_ENVS.has(config.apiKeyEnv)? "No API key — open Settings → API keys."@@ -220,6 +222,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {return ollama.status;};const listOllama = async (): Promise<boolean> => {+ if (!await answersAsOllama()) return false;const status = await probeOllama(config.url, { key: apiKey, timeoutMs: 8_000, capabilities: true });ollama = { at: Date.now(), status: Promise.resolve(status) };if (!isOllamaServer(config) || (status.state !== "ready" && status.state !== "no-models")) return false;@@ -352,9 +355,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {toolUse: (model) => fact(model)?.tools ?? true,...(ollamaCandidate ? {serverUnavailable: async () => {- if (config.catalog !== "ollama" && !onOllamaPort(config.url) && answeredAsOllama(config.url) === false) return null;- const status = await checkOllama();- return isOllamaServer(config) ? ollamaUnavailable(status) : null;+ return isOllamaServer(config) ? ollamaUnavailable(await checkOllama()) : null;},} : {}),requestBody: (model, messages, stream) => ({