Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Tighten how a server counts as Ollama, and what a model is
milind-soni478f1156559b
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdxindex a562b1c29d..ed78a790ff 100644--- a/apps/docs/content/docs/providers/model-providers.mdx+++ b/apps/docs/content/docs/providers/model-providers.mdx@@ -243,7 +243,8 @@ list only over HTTPS or to this computer. Check that:A chat engine whose address is Ollama shows up as **Ollama**, with Ollama'smark, in Settings and the model picker. MausBot treats an address as Ollama-when it uses Ollama's port (11434) or when it answers Ollama's own API. An+when it uses Ollama's port (11434), or when an address on this computer or your+network answers Ollama's own API. Anaddress you added before keeps its name, key and model.- Ollama needs no API key.diff --git a/server/drivers/ollama.test.ts b/server/drivers/ollama.test.tsindex cf9dd30dff..82a9709f28 100644--- a/server/drivers/ollama.test.ts+++ b/server/drivers/ollama.test.ts@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { recordEvents } from "../testing/events.ts";import { instanceLook } from "../provider-icon.ts";@@ -29,6 +29,7 @@ interface FakeModel { name: string; size?: number; details?: Record<string, unkn/** A server speaking Ollama's own routes and its OpenAI-compatible chat, recording each chat request. */async function fakeOllama(options: { models?: FakeModel[]; version?: string | null; tags?: boolean } = {}) {+ // Read per request, so a test can change what the server answers.const models = options.models ?? [];const chats: Array<{ model: string; tools?: unknown[] }> = [];const asked: string[] = [];@@ -133,6 +134,13 @@ describe("finding Ollama", () => {expect(answeredAsOllama(url)).toBe(true);});+ it("goes by what a model can do over what it is called, once the server says", async () => {+ const assistant: FakeModel = { name: "embedded-assistant:latest", details: { family: "llama" }, capabilities: ["completion"] };+ const vectors: FakeModel = { name: "search-vectors:latest", details: { family: "custom" }, capabilities: ["embedding"] };+ const { url } = await fakeOllama({ models: [assistant, vectors] });+ expect((await probeOllama(url, { capabilities: true })).models.map((model) => model.name)).toEqual(["embedded-assistant:latest"]);+ });+it("says when nothing is pulled yet, with the command that pulls a model", async () => {const { url } = await fakeOllama({ models: [EMBED] });const status = await probeOllama(url);@@ -170,6 +178,18 @@ describe("finding Ollama", () => {expect(answeredAsOllama(imitation.url)).toBe(false);});+ it("keeps a yes through a failed version request, but not through a server that stops answering as Ollama", async () => {+ const options: Parameters<typeof fakeOllama>[0] = { models: [LLAMA] };+ const { url } = await fakeOllama(options);+ await probeOllama(url);+ options.version = null;+ await probeOllama(url);+ expect(answeredAsOllama(url)).toBe(true);+ options.tags = false;+ await probeOllama(url);+ expect(answeredAsOllama(url)).toBe(false);+ });+it("takes the first address that runs, else what the first address said", async () => {const { url } = await fakeOllama({ models: [LLAMA] });const closed = await closedPort();@@ -191,6 +211,14 @@ describe("an OpenAI-compatible server that is really Ollama", () => {expect(isOllamaServer({ url: `${url}/v1` })).toBe(true);});+ it("stops being one on Ollama's port once something else has answered there", async () => {+ const config = { url: "http://127.0.0.1:11434/v1" };+ expect(isOllamaServer(config)).toBe(true);+ await probeOllama(config.url, { fetchImpl: (async () => new Response("{}", { status: 404 })) as typeof fetch });+ expect(isOllamaServer(config)).toBe(false);+ expect(instanceLook({ driver: "openai-compat", config })).toEqual({});+ });+it("shows as Ollama: its mark, and its name unless someone named it", () => {const builtIn = { driver: "openai-compat", config: { url: "http://localhost:11434/v1" } };expect(instanceLook(builtIn)).toEqual({ icon: { kind: "preset", preset: "ollama" }, serverKind: "ollama", displayName: "Ollama" });@@ -259,6 +287,51 @@ describe("the chat engine on Ollama", () => {} finally { await instance.dispose(); }});+ it("keeps a fixed model list on Ollama, and still knows which of them can call tools", async () => {+ const { url, chats } = await fakeOllama({ models: [LLAMA, GEMMA] });+ const instance = await create({ url: `${url}/v1`, catalog: "ollama", managedModels: ["gemma2:2b"] });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ expect(instance.models).toEqual({ default: "gemma2:2b", options: [{ id: "gemma2:2b", label: "gemma2:2b" }] });+ const threadId = randomUUID();+ await instance.adapter.sendTurn({ threadId, text: "hi", model: "gemma2:2b" });+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);+ expect(chats[0]!.tools).toBeUndefined();+ } finally {+ recorder.stop();+ await instance.dispose();+ }+ });++ it("tells a text-only model on the network about an attachment instead of refusing the turn", async () => {+ const replies: Record<string, unknown> = {+ "/api/tags": { models: [GEMMA] }, "/api/version": { version: "0.12.6" }, "/api/show": { capabilities: ["completion"] }, "/api/ps": { models: [] }, "/api/create": { status: "success" },+ };+ const bodies: string[] = [];+ vi.stubGlobal("fetch", vi.fn<typeof fetch>(async (url, init) => {+ const path = new URL(String(url)).pathname;+ if (path === "/v1/chat/completions") {+ bodies.push(String(init!.body));+ return new Response(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Hi." }, finish_reason: "stop" }] })}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } });+ }+ return new Response(JSON.stringify(replies[path] ?? {}), { status: replies[path] ? 200 : 404 });+ }));+ const instance = await create({ url: "http://192.168.1.20:11434/v1", catalog: "ollama" });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ const threadId = randomUUID();+ await instance.adapter.sendTurn({ threadId, text: "what is this?", model: "gemma2:2b", images: [{ path: "/not-read.png", mime: "image/png", bytes: 1 }] });+ await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);+ expect(bodies[0]).toContain("this model cannot see images");+ } finally {+ recorder.stop();+ await instance.dispose();+ vi.unstubAllGlobals();+ }+ });+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" });diff --git a/server/drivers/ollama.ts b/server/drivers/ollama.tsindex 899bfce544..090bb0bf11 100644--- a/server/drivers/ollama.ts+++ b/server/drivers/ollama.ts@@ -49,8 +49,8 @@ export function onOllamaPort(url: string): boolean {const EMBEDDING = /embed|(?:^|[/:-])bge-|minilm/i;const text = (value: unknown) => typeof value === "string" && value.trim() ? value.trim() : undefined;-/** The chat models in an /api/tags answer, or null when the answer is not one. Embedding models answer no chat, and- * a name that carries a context window is the model it was made from. */+/** The chat models in an /api/tags answer, or null when the answer is not one. An embedding model answers no chat (its+ * name only counts where Ollama gives no family), and a name that carries a context window is the model it was made from. */export function ollamaTags(payload: unknown): OllamaModel[] | null {const rows = payload && typeof payload === "object" ? (payload as { models?: unknown }).models : undefined;if (!Array.isArray(rows)) return null;@@ -62,7 +62,7 @@ export function ollamaTags(payload: unknown): OllamaModel[] | null {const name = text(entry.name) ?? text(entry.model);const details = (entry.details && typeof entry.details === "object" ? entry.details : {}) as { family?: unknown; families?: unknown; parameter_size?: unknown; quantization_level?: unknown };const families = [details.family, ...(Array.isArray(details.families) ? details.families : [])].filter((family): family is string => typeof family === "string");- if (!name || seen.has(name) || isContextName(name) || EMBEDDING.test(name) || families.some((family) => /bert$/i.test(family))) continue;+ if (!name || seen.has(name) || isContextName(name) || families.some((family) => /bert$/i.test(family)) || (!families.length && EMBEDDING.test(name))) continue;seen.add(name);const parameters = text(details.parameter_size), quantization = text(details.quantization_level);models.push({@@ -82,6 +82,12 @@ export function showCapabilities(show: unknown): Pick<OllamaModel, "tools" | "vireturn { tools: capabilities.includes("tools"), vision: capabilities.includes("vision") };}+/** False only for a model /api/show says cannot chat. */+function answersChats(show: unknown): boolean {+ const capabilities = show && typeof show === "object" ? (show as { capabilities?: unknown }).capabilities : undefined;+ return !Array.isArray(capabilities) || capabilities.includes("completion");+}+function nobodyListening(error: unknown): boolean {const cause = (error as { cause?: { code?: unknown; errors?: unknown } } | undefined)?.cause;if (cause?.code === "ECONNREFUSED") return true;@@ -92,8 +98,8 @@ const timedOut = (error: unknown) => (error as { name?: unknown } | undefined)?.const answered = new Map<string, boolean>();-/** Whether this server answered as Ollama when last asked: /api/tags with a list and /api/version with a version- * (some other servers imitate /api/tags alone). Undefined until asked. */+/** Whether this server has answered as Ollama: /api/tags with a list and /api/version with a version (some other servers+ * imitate /api/tags alone). Undefined until asked; a failed version request alone doesn't undo a yes. */export function answeredAsOllama(url: string): boolean | undefined {return answered.get(ollamaOrigin(url));}@@ -130,17 +136,22 @@ export async function probeOllama(url: string, options: ProbeOptions = {}): Promif (nobodyListening(error)) return { state: "not-running", url: origin, models: [] };return { state: "unreachable", url: origin, models: [], problem: timedOut(error) ? "timeout" : "network" };}- answered.set(origin, models !== null && version !== undefined);+ if (models === null) answered.set(origin, false);+ else if (version) answered.set(origin, true);+ else if (!answered.has(origin)) answered.set(origin, false);if (!models) return { state: "unreachable", url: origin, models: [], problem: "not-ollama" };if (options.capabilities) {- models = await Promise.all(models.map(async (model) => {+ const asked = await Promise.all(models.map(async (model) => {try {const response = await ask("/api/show", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: model.name }) });- return response.ok ? { ...model, ...showCapabilities(await response.json()) } : model;+ if (!response.ok) return model;+ const show: unknown = await response.json();+ return answersChats(show) ? { ...model, ...showCapabilities(show) } : null;} catch {return model;}}));+ models = asked.filter((model) => model !== null);}return { state: models.length ? "ready" : "no-models", url: origin, ...(version ? { version } : {}), models };}@@ -158,19 +169,21 @@ export function ollamaUnavailable(status: OllamaStatus): string | null {const RANK: Record<OllamaState, number> = { ready: 0, "no-models": 1, unreachable: 2, "not-running": 3 };-/** Ollama on this computer, or at an address someone set: the first that runs, else what the first address said. */+/** Ollama on this computer, or at an address someone set: the first that runs, else the most telling answer. */export async function findOllama(urls: readonly string[] = [], options: ProbeOptions = {}): Promise<OllamaStatus> {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);}-/** An OpenAI-compatible instance that is really Ollama: added as Ollama, on Ollama's port, or it answered as Ollama. */+/** An OpenAI-compatible instance that is really Ollama: added as Ollama, it answered as Ollama, or it is on Ollama's port+ * and nothing there has answered otherwise. */export function isOllamaServer(config: unknown): boolean {const { url, catalog } = (config && typeof config === "object" ? config : {}) as { url?: unknown; catalog?: unknown };if (catalog === "ollama") return true;if (catalog !== undefined || typeof url !== "string") return false;- return onOllamaPort(url) || answeredAsOllama(url) === true;+ const answer = answeredAsOllama(url);+ return answer === true || (answer === undefined && onOllamaPort(url));}export function forgetOllamaAnswers(): void {diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex a40aa1743a..7f831c4889 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -515,7 +515,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const sendTurn = async (turn: SendTurnInput) => {if (!options.apiKey) throw new Error(options.missingKeyError);if (active.has(turn.threadId)) throw new Error("a turn is already running on this thread");- if (options.computerUse && (turn.images?.length || turn.integrations?.localComputer || turn.integrations?.browser)) assertImageTransport(options.apiUrl);+ if (options.computerUse && ((turn.images?.length && seesImages(turn)) || turn.integrations?.localComputer || turn.integrations?.browser)) assertImageTransport(options.apiUrl);const turnId = newId();const abort = new AbortController();diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 5fabba0f77..606e3b5bd9 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -228,6 +228,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {if (!isOllamaServer(config) || (status.state !== "ready" && status.state !== "no-models")) return false;facts.clear();for (const model of status.models) facts.set(model.name, model);+ if (config.managedModels) return true;const options: ModelCatalog["options"] = status.models.map((model) => ({ id: model.name, label: model.name, custom: true, local: localFacts(model) }));if (config.model && !options.some((model) => model.id === config.model)) options.unshift({ id: config.model, label: config.model, custom: true });catalog = { default: config.model ?? options[0]?.id ?? "", options };@@ -235,9 +236,9 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {};const fetchModels = async () => {- if (config.managedModels) return;if (!apiKey) return;if (ollamaCandidate && await listOllama()) return;+ if (config.managedModels) return;try {// Only a server added as LM Studio: any other local server would get a request it never serves.const nativeUrl = config.catalog === "lmstudio" ? loopbackLmStudioV1Url(config.url) : null;diff --git a/server/provider-icon.ts b/server/provider-icon.tsindex 724e49a58d..73d1a63f70 100644--- a/server/provider-icon.ts+++ b/server/provider-icon.ts@@ -22,7 +22,7 @@ export function withInstanceIcon(cfg: AppConfig, instanceId: string, icon: Provi}/** Who runs a server, by its host. `*` is one DNS label, or the rest of one. Only providers we have a mark for:- * Groq, Together, Fireworks and LM Studio servers keep the driver's own mark; Ollama is told by its answers. */+ * Groq, Together, Fireworks and LM Studio servers keep the driver's own mark; Ollama isn't told by its host. */const SERVER_HOSTS: Record<string, ProviderIconPreset> = {"api.openai.com": "openai", "*.api.openai.com": "openai","*.openai.azure.com": "azure", "*.services.ai.azure.com": "azure", "*.cognitiveservices.azure.com": "azure",diff --git a/src/components/SimpleModelMenu.tsx b/src/components/SimpleModelMenu.tsxindex d60eb04e84..f116c9eb57 100644--- a/src/components/SimpleModelMenu.tsx+++ b/src/components/SimpleModelMenu.tsx@@ -60,8 +60,8 @@ function MenuModel({ instance, row, onPick }: { instance: InstanceInfo; row: Mendata-org-blocked={row.blocked || undefined}disabled={row.blocked}aria-pressed={row.current}- aria-label={[modelOptionLabel(option), option.provider, reason].filter(Boolean).join(" · ")}- title={[modelOptionLabel(option), option.provider, reason].filter(Boolean).join(" · ")}+ aria-label={[modelOptionLabel(option), option.provider, row.detail, reason].filter(Boolean).join(" · ")}+ title={[modelOptionLabel(option), option.provider, row.detail, reason].filter(Boolean).join(" · ")}tabIndex={-1}onClick={() => onPick(instance, row.model ?? option.id, row.variant)}className={SIMPLE_MENU_ROW}diff --git a/src/lib/simple-model-menu.test.ts b/src/lib/simple-model-menu.test.tsindex 1dd33f6d65..32b9c628d2 100644--- a/src/lib/simple-model-menu.test.ts+++ b/src/lib/simple-model-menu.test.ts@@ -67,6 +67,11 @@ describe("Ollama in the Simple model menu", () => {]);});+ it("says what the selected model is too", () => {+ const built = menu([ollama], { selection: { instanceId: "openaiCompat", model: "gemma2:2b" } });+ expect(built.current).toMatchObject({ label: "gemma2:2b", meta: "2.6B · 912 MB · No tools", title: "Ollama · gemma2:2b · 2.6B · 912 MB · No tools" });+ });+it("keeps the API key heading for another OpenAI-compatible server", () => {expect(menu([openaiKey]).groups.map((group) => group.label)).toEqual(["OpenAI · API key"]);});diff --git a/src/lib/simple-model-menu.ts b/src/lib/simple-model-menu.tsindex 8619266923..d69d3a4a8e 100644--- a/src/lib/simple-model-menu.ts+++ b/src/lib/simple-model-menu.ts@@ -143,7 +143,8 @@ function currentRow(input: SimpleMenuInput): MenuCurrent {const active = instances.find((instance) => instance.instanceId === selection.instanceId);const option = active?.models.options.find((candidate) => candidate.id === selection.model);const name = option ? modelOptionLabel(option) : selection.model;- const row = { instance: active, label: modelName(active, selection.model, selection.variant), title: active ? `${engineDisplayName(active)} · ${name}${variantSuffix(active, selection.model, selection.variant)}` : name, warning: false, pending: false };+ const detail = localModelDetail(option?.local);+ const row = { instance: active, label: modelName(active, selection.model, selection.variant), title: `${active ? `${engineDisplayName(active)} · ${name}${variantSuffix(active, selection.model, selection.variant)}` : name}${detail ? ` · ${detail}` : ""}`, warning: false, pending: false };if (!active) return loading ? { ...row, pending: true } : { ...row, meta: t("model.simple.unavailable"), warning: true };if (!option && input.refreshing === active.instanceId) return { ...row, pending: true };if (option?.orgBlocked) return { ...row, meta: t("model.orgBlocked"), warning: true, blocked: true };@@ -154,7 +155,7 @@ function currentRow(input: SimpleMenuInput): MenuCurrent {const family = signInFamily(active);const accounts = family ? instances.filter((instance) => signInFamily(instance) === family).length : 0;if (accounts > 1 || active.snapshot.chatgptPlan) return { ...row, meta: engineDisplayName(active) };- return option?.provider ? { ...row, meta: option.provider } : row;+ return option?.provider || detail ? { ...row, meta: option?.provider ?? detail } : row;}export function simpleModelMenu(input: SimpleMenuInput): SimpleMenu {