Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Ollama models get a context window big enough for a bot (#4181)
Milind Soni9022b06ba82e
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdxindex 03d3734cf8..e0f83cd090 100644--- a/apps/docs/content/docs/providers/model-providers.mdx+++ b/apps/docs/content/docs/providers/model-providers.mdx@@ -185,6 +185,24 @@ and your Claude bots follow it:Not yet. Codex bots use your ChatGPT sign-in, or your organisation's models.+## Ollama's context window++Below 23 GB of graphics memory, Ollama gives a model a 4,096-token context window+unless told otherwise, and it drops whatever doesn't fit without an error. That is+less than a bot's instructions and tools, so OpenMausBot sets a larger window the+first time a bot uses a model.++You'll see the result in `ollama list` as a second name, such as+`qwen3.5:4b-omb-64k`. It uses the same weights, so it takes no extra disk space.+Removing it is safe: OpenMausBot makes it again when it needs it. To free the disk+space a model uses, remove both names.++The window is 16K, 32K or 64K tokens, depending on your memory and the model's size.+To choose your own, set `num_ctx` in a Modelfile or start Ollama with+`OLLAMA_CONTEXT_LENGTH`. A `num_ctx` in a Modelfile is always left alone. With+`OLLAMA_CONTEXT_LENGTH`, keep the model loaded before the first turn, because+OpenMausBot can only see that setting on a running model.+## Current limitsThere is no shared provider list that configures every engine. Use eachdiff --git a/server/drivers/local-inject.ts b/server/drivers/local-inject.tsindex 3333b4c486..d73ca42822 100644--- a/server/drivers/local-inject.ts+++ b/server/drivers/local-inject.ts@@ -4,7 +4,8 @@ import { readFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";-import type { ModelCatalog } from "../contracts.ts";+import type { ModelCatalog, ProviderInstance } from "../contracts.ts";+import { isContextName, pickedName, servedModel, serveWithWindow } from "./ollama-context.ts";export interface LocalHost {id: string;@@ -49,8 +50,10 @@ export function contextWindowsFromPs(extra: unknown): Map<string, number> {const id = typeof row.model === "string" ? row.model : typeof row.name === "string" ? row.name : null;const ctx = typeof row.context_length === "number" && Number.isFinite(row.context_length) && row.context_length > 0 ? row.context_length : null;if (id && ctx) {+ const picked = pickedName(id);out.set(id, ctx);- const baseId = id.split(":")[0]!;+ out.set(picked, ctx);+ const baseId = picked.split(":")[0]!;const current = out.get(baseId);out.set(baseId, current === undefined ? ctx : Math.min(current, ctx));}@@ -62,14 +65,42 @@ export function encodeInjectId(host: string, model: string): string {return `${host}${INJECT_SEP}${model}`;}+const isOllamaHost = (host: string) => host === "ollama" || host === "local_ollama";+const hostOrigin = (host: LocalHost) => host.baseUrl.replace(/\/v1\/?$/, "");+export function decodeInjectId(id: string | null | undefined): { host: string; model: string } | null {if (!id) return null;const sep = id.indexOf(INJECT_SEP);if (sep <= 0) return null;const host = id.slice(0, sep);const model = id.slice(sep + INJECT_SEP.length);- if (!HOST_BY_ID.has(host) || !MODEL_ID.test(model)) return null;- return { host, model };+ const known = HOST_BY_ID.get(host);+ if (!known || !MODEL_ID.test(model)) return null;+ // Every engine reads the model it sends from here, so all of them use the name that carries the window.+ return { host, model: (isOllamaHost(host) ? servedModel(hostOrigin(known), model)?.model : undefined) ?? model };+}++/** The window a local pick will run with, once its turn has decided it. */+export function injectedContextWindow(id: string | null | undefined): number | undefined {+ const sep = id?.indexOf(INJECT_SEP) ?? -1;+ if (sep <= 0) return undefined;+ const known = HOST_BY_ID.get(id!.slice(0, sep));+ return known && isOllamaHost(known.id) ? servedModel(hostOrigin(known), id!.slice(sep + INJECT_SEP.length))?.window : undefined;+}++/** Before a turn on an Ollama pick, settle the name that carries its window. */+export function withLocalContext(instance: ProviderInstance): ProviderInstance {+ const adapter = instance.adapter;+ (instance as { adapter: ProviderInstance["adapter"] }).adapter = {+ ...adapter,+ sendTurn: async (input) => {+ const sep = input.model?.indexOf(INJECT_SEP) ?? -1;+ const host = sep > 0 ? HOST_BY_ID.get(input.model!.slice(0, sep)) : undefined;+ if (host && isOllamaHost(host.id)) await serveWithWindow(hostOrigin(host), input.model!.slice(sep + INJECT_SEP.length));+ return adapter.sendTurn(input);+ },+ };+ return instance;}export function localHost(id: string): LocalHost | undefined {@@ -186,7 +217,8 @@ function idsFromModelsPayload(payload: unknown): string[] {const id = (record as { id?: unknown; name?: unknown }).id ?? (record as { name?: unknown }).name;if (typeof id !== "string" || !MODEL_ID.test(id)) return [];const low = id.toLowerCase();- if (low.includes("embed") || low.includes("bge-") || low.includes("nomic")) return [];+ // Our own names for a model's window are that model, not another one to pick.+ if (low.includes("embed") || low.includes("bge-") || low.includes("nomic") || isContextName(id)) return [];return [id];});}@@ -217,7 +249,8 @@ async function timedJson(export function loadedIdsFromPayloads(_host: LocalHost, catalog: unknown, extra: unknown): Set<string> {const loaded = new Set<string>();const catalogIds = new Set(idsFromModelsPayload(catalog));- const add = (id: string) => {+ const add = (raw: string) => {+ const id = pickedName(raw);const base = id.split(":")[0]!;if (catalogIds.size && !catalogIds.has(id) && !catalogIds.has(base)) return;if (!MODEL_ID.test(id)) return;@@ -381,6 +414,8 @@ export async function mergeLocalInject(const vitest = env.VITEST ?? process.env.VITEST;const probe = env.OPENMAUSBOT_PROBE_LOCAL_INJECT ?? process.env.OPENMAUSBOT_PROBE_LOCAL_INJECT;if (vitest === "true" && probe !== "1") return catalog;+ // An engine's own config lists whatever it was last told to run, which may be a name that carries a window.+ catalog = { ...catalog, options: catalog.options.filter((option) => !isContextName(option.id)) };const extras = await probeLocalInjects(env, fetchImpl);if (!extras.length) return catalog;const liveApiIds = new Set(extras.map((extra) => extra.model));@@ -434,5 +469,7 @@ export function applyClaudeInject(env.ANTHROPIC_AUTH_TOKEN = key;env.ANTHROPIC_API_KEY = key;env.ANTHROPIC_MODEL = inject.model;+ const window = injectedContextWindow(modelId);+ if (window) env.CLAUDE_CODE_MAX_CONTEXT_TOKENS = String(window);return { model: inject.model, injected: true };}diff --git a/server/drivers/ollama-context.test.ts b/server/drivers/ollama-context.test.tsnew file mode 100644index 0000000000..703aff83aa--- /dev/null+++ b/server/drivers/ollama-context.test.ts@@ -0,0 +1,287 @@+import { randomUUID } from "node:crypto";+import { createServer } from "node:http";+import type { AddressInfo } from "node:net";++import { afterEach, describe, expect, it, vi } from "vitest";++import { recordEvents } from "../testing/events.ts";+import { OpenAICompatDriver } from "./openai-compat.ts";++import { applyClaudeInject, decodeInjectId, encodeInjectId, injectedContextWindow, localHost, withLocalContext } from "./local-inject.ts";+import { forgetServedModels, isContextName, isOllama, pickedName, servedModel, serveWithWindow, showFacts, windowFor } from "./ollama-context.ts";+import type { ProviderInstance } from "../contracts.ts";++const GB = 1024 ** 3;+const ORIGIN = "http://127.0.0.1:11434";++afterEach(() => forgetServedModels());++/** A server speaking the routes this reads, recording what it was asked to create. */+function ollama(options: { show?: unknown; size?: number; running?: unknown[]; createStatus?: number; gone?: string[] } = {}) {+ const created: Array<{ model: string; from: string; parameters: { num_ctx: number }; stream: boolean }> = [];+ const asked: string[] = [];+ const server = (async (url: string, init?: RequestInit) => {+ const path = new URL(url).pathname;+ asked.push(path);+ const reply = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });+ if (path === "/api/version") return reply({ version: "0.40.13" });+ if (path === "/api/show" && options.gone?.includes((JSON.parse(String(init?.body)) as { model: string }).model)) return reply({ error: "not found" }, 404);+ if (path === "/api/show") return reply(options.show ?? { model_info: { "qwen3.context_length": 262_144 }, parameters: "temperature 1" });+ if (path === "/api/ps") return reply({ models: options.running ?? [] });+ if (path === "/api/tags") return reply({ models: [{ name: "qwen3.5:4b", size: options.size ?? 3 * GB }] });+ if (path === "/api/create") {+ created.push(JSON.parse(String(init?.body)));+ return reply({ status: "success" }, options.createStatus ?? 200);+ }+ return reply({}, 404);+ }) as typeof fetch;+ return { server, created, asked };+}++describe("windowFor", () => {+ it.each([+ ["16 GB laptop, small model", 3, 16, undefined, 65_536],+ ["16 GB laptop, 12 GB model", 12, 16, undefined, 16_384],+ ["24 GB laptop, 2B model", 2.7, 24, undefined, 65_536],+ ["32 GB laptop, 22 GB model", 22, 32, undefined, 32_768],+ ["128 GB workstation", 40, 128, undefined, 65_536],+ ["a model trained on less", 3, 64, 8_192, 8_192],+ ["an unknown size stays small", undefined, 64, undefined, 16_384],+ ])("%s", (_label, model, memory, trained, expected) => {+ expect(windowFor(model === undefined ? undefined : model * GB, trained, memory * GB)).toBe(expected);+ });+});++describe("showFacts", () => {+ it("reads a Modelfile's window and the trained one", () => {+ expect(showFacts({ parameters: "stop \"a\"\nnum_ctx 8192\ntemperature 1", model_info: { "gemma4.context_length": 256_000 } })).toEqual({ pinned: 8192, trained: 256_000, remote: false });+ });++ it("sees a model that runs elsewhere", () => {+ expect(showFacts({ remote_host: "https://ollama.com", remote_model: "x" }).remote).toBe(true);+ });++ it("survives a body with nothing in it", () => {+ expect(showFacts(null)).toEqual({ remote: false });+ });+});++describe("serveWithWindow", () => {+ it("creates one name that carries the window, from the same weights, and remembers it", async () => {+ const lab = ollama();+ const served = await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ expect(served).toEqual({ model: "qwen3.5:4b-omb-64k", window: 65_536 });+ expect(lab.created).toEqual([{ model: "qwen3.5:4b-omb-64k", from: "qwen3.5:4b", parameters: { num_ctx: 65_536 }, stream: false }]);+ await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ expect(lab.created).toHaveLength(1);+ expect(servedModel(ORIGIN, "qwen3.5:4b")?.model).toBe("qwen3.5:4b-omb-64k");+ });++ describe("once our name exists", () => {+ afterEach(() => { vi.restoreAllMocks(); });+ const aMinuteLater = () => { const now = Date.now(); vi.spyOn(Date, "now").mockReturnValue(now + 61_000); };++ it("makes it again if someone removed it", async () => {+ const gone: string[] = [];+ const lab = ollama({ gone });+ await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ gone.push("qwen3.5:4b-omb-64k");+ aMinuteLater();+ expect((await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB)).model).toBe("qwen3.5:4b-omb-64k");+ expect(lab.created).toHaveLength(2);+ });++ it("keeps it through a server that is only busy", async () => {+ const lab = ollama();+ await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ aMinuteLater();+ const dead = (async () => { throw new Error("timeout"); }) as unknown as typeof fetch;+ expect((await serveWithWindow(ORIGIN, "qwen3.5:4b", dead, 24 * GB)).model).toBe("qwen3.5:4b-omb-64k");+ expect(lab.created).toHaveLength(1);+ });++ it("does not ask again within the minute", async () => {+ const lab = ollama();+ await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ const asked = lab.asked.length;+ await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB);+ expect(lab.asked).toHaveLength(asked);+ });+ });++ it("names a model with no tag", async () => {+ expect((await serveWithWindow(ORIGIN, "mymodel", ollama().server, 24 * GB)).model).toBe("mymodel:latest-omb-16k");+ });++ it("shares one decision between turns that start together", async () => {+ const lab = ollama();+ await Promise.all([serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server), serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server)]);+ expect(lab.created).toHaveLength(1);+ });++ it("leaves a window the person set in a Modelfile alone", async () => {+ const lab = ollama({ show: { parameters: "num_ctx 200000" } });+ expect(await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server)).toEqual({ model: "qwen3.5:4b", window: 200_000 });+ expect(lab.created).toEqual([]);+ });++ it("leaves a model already running with enough alone", async () => {+ const lab = ollama({ running: [{ name: "qwen3.5:4b", context_length: 262_144 }] });+ expect(await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 64 * GB)).toEqual({ model: "qwen3.5:4b", window: 262_144 });+ expect(lab.created).toEqual([]);+ });++ it("replaces a model running on the small default", async () => {+ const lab = ollama({ running: [{ name: "qwen3.5:4b", context_length: 4_096 }] });+ expect((await serveWithWindow(ORIGIN, "qwen3.5:4b", lab.server, 24 * GB)).window).toBe(65_536);+ expect(lab.created).toHaveLength(1);+ });++ it("leaves a cloud model alone", async () => {+ const lab = ollama({ show: { remote_host: "https://ollama.com" } });+ expect(await serveWithWindow(ORIGIN, "glm-5:cloud", lab.server)).toEqual({ model: "glm-5:cloud" });+ expect(lab.created).toEqual([]);+ });++ it.each([+ ["a refused create", ollama({ createStatus: 500 }).server],+ ["a dead server", (async () => { throw new Error("ECONNREFUSED"); }) as unknown as typeof fetch],+ ])("falls back to the model as it was on %s", async (_label, server) => {+ expect(await serveWithWindow(ORIGIN, "qwen3.5:4b", server)).toEqual({ model: "qwen3.5:4b" });+ });++ it("never wraps a name that already carries a window", async () => {+ const lab = ollama();+ expect(await serveWithWindow(ORIGIN, "qwen3.5:4b-omb-64k", lab.server)).toEqual({ model: "qwen3.5:4b-omb-64k" });+ expect(lab.asked).toEqual([]);+ });+});++describe("names", () => {+ it("goes back to the name a person picked", () => {+ expect(pickedName("qwen3.5:4b-omb-64k")).toBe("qwen3.5:4b");+ expect(pickedName("mymodel:latest-omb-16k")).toBe("mymodel:latest");+ expect(pickedName("llama3.2:latest")).toBe("llama3.2:latest");+ expect(isContextName("qwen3.5:4b")).toBe(false);+ });+});++describe("isOllama", () => {+ it("is true only for a server that answers with a version", async () => {+ expect(await isOllama("http://a", ollama().server)).toBe(true);+ expect(await isOllama("http://b", (async () => new Response("{}", { status: 404 })) as unknown as typeof fetch)).toBe(false);+ expect(await isOllama("http://c", (async () => new Response('{"ok":true}')) as unknown as typeof fetch)).toBe(false);+ });+});++describe("every engine picks up the name", () => {+ const pick = encodeInjectId("ollama", "qwen3.5:4b");+ const origin = localHost("ollama")!.baseUrl.replace(/\/v1$/, "");++ it("decodes to the picked name until a turn has decided, then to the one with the window", async () => {+ expect(decodeInjectId(pick)).toEqual({ host: "ollama", model: "qwen3.5:4b" });+ expect(injectedContextWindow(pick)).toBeUndefined();+ await serveWithWindow(origin, "qwen3.5:4b", ollama().server, 24 * GB);+ expect(decodeInjectId(pick)).toEqual({ host: "ollama", model: "qwen3.5:4b-omb-64k" });+ expect(injectedContextWindow(pick)).toBe(65_536);+ });++ it("tells Claude Code the window it really has", async () => {+ await serveWithWindow(origin, "qwen3.5:4b", ollama().server, 24 * GB);+ const env: Record<string, string | undefined> = {};+ expect(applyClaudeInject(env, pick)).toEqual({ model: "qwen3.5:4b-omb-64k", injected: true });+ expect(env).toMatchObject({ ANTHROPIC_MODEL: "qwen3.5:4b-omb-64k", CLAUDE_CODE_MAX_CONTEXT_TOKENS: "65536" });+ });++ it("does not touch another host's pick", async () => {+ const lmstudio = encodeInjectId("lmstudio", "qwen3.5:4b");+ await serveWithWindow(origin, "qwen3.5:4b", ollama().server, 24 * GB);+ expect(decodeInjectId(lmstudio)?.model).toBe("qwen3.5:4b");+ expect(injectedContextWindow(lmstudio)).toBeUndefined();+ });++ it("settles the name before a turn starts, and only for an Ollama pick", async () => {+ const sent: string[] = [];+ const instance = { adapter: { sendTurn: async (input: { model?: string }) => { sent.push(decodeInjectId(input.model)?.model ?? String(input.model)); return { turnId: "t" }; } } } as unknown as ProviderInstance;+ const realFetch = globalThis.fetch;+ const lab = ollama();+ globalThis.fetch = lab.server;+ try {+ const wrapped = withLocalContext(instance);+ await wrapped.adapter.sendTurn({ threadId: "t", text: "hi", model: "claude-opus" });+ expect(lab.asked).toEqual([]);+ await wrapped.adapter.sendTurn({ threadId: "t", text: "hi", model: pick });+ } finally {+ globalThis.fetch = realFetch;+ }+ expect(sent).toEqual(["claude-opus", expect.stringMatching(/^qwen3\.5:4b-omb-\d+k$/)]);+ });+});++describe("the chat engine on a server someone added by URL", () => {+ async function server(routes: "ollama" | "other") {+ const sent: string[] = [];+ const created: string[] = [];+ const http = createServer(async (request, response) => {+ let data = "";+ for await (const part of request) data += part.toString();+ const path = request.url ?? "";+ const json = (body: unknown) => { response.setHeader("content-type", "application/json"); response.end(JSON.stringify(body)); };+ if (path === "/v1/models") return json({ data: [{ id: "qwen3.5:4b" }, { id: "qwen3.5:4b-omb-64k" }] });+ if (path === "/v1/chat/completions") {+ sent.push((JSON.parse(data) as { model: string }).model);+ response.writeHead(200, { "content-type": "text/event-stream" });+ response.write(`data: ${JSON.stringify({ choices: [{ index: 0, delta: { content: "Hi." }, finish_reason: "stop" }] })}\n\n`);+ return response.end("data: [DONE]\n\n");+ }+ // Some other servers answer part of Ollama's API, but never its version.+ if (path === "/api/version" && routes === "ollama") return json({ version: "0.40.13" });+ if (path === "/api/show") return json({ model_info: { "qwen3.context_length": 262_144 } });+ if (path === "/api/ps") return json({ models: [] });+ if (path === "/api/tags") return json({ models: [{ name: "qwen3.5:4b", size: 3 * GB }] });+ if (path === "/api/create") { created.push((JSON.parse(data) as { model: string }).model); return json({ status: "success" }); }+ response.statusCode = 404;+ response.end("{}");+ });+ await new Promise<void>((resolve) => http.listen(0, "127.0.0.1", resolve));+ const { port } = http.address() as AddressInfo;+ const instance = await OpenAICompatDriver.create({+ instanceId: randomUUID(), displayName: "Fixture", enabled: true,+ config: { url: `http://127.0.0.1:${port}/v1`, apiKeyEnv: "FIXTURE_KEY" }, environment: { FIXTURE_KEY: "k" },+ });+ await instance.refreshModels?.();+ const recorder = recordEvents(instance.adapter);+ const stop = async () => {+ recorder.stop();+ await instance.dispose();+ http.closeAllConnections();+ await new Promise<void>((resolve) => http.close(() => resolve()));+ };+ const turn = async () => {+ await instance.adapter.sendTurn({ threadId: randomUUID(), text: "hi", model: "qwen3.5:4b" });+ await recorder.until((event) => event.type === "turn.completed");+ };+ return { instance, sent, created, stop, turn };+ }++ it("sends the name that carries the window, keeps it out of the picker, and knows the window", async () => {+ const f = await server("ollama");+ try {+ expect(f.instance.models.options.map((option) => option.id)).toEqual(["qwen3.5:4b"]);+ await f.turn();+ expect(f.created).toHaveLength(1);+ expect(f.sent).toEqual(f.created);+ expect(f.sent[0]).toMatch(/^qwen3\.5:4b-omb-\d+k$/);+ expect(f.instance.models.options.find((option) => option.id === "qwen3.5:4b")?.contextWindow).toBeGreaterThanOrEqual(16_384);+ } finally { await f.stop(); }+ });++ it("never asks a server that only imitates Ollama to create anything", async () => {+ const f = await server("other");+ try {+ await f.turn();+ expect(f.sent).toEqual(["qwen3.5:4b"]);+ expect(f.created).toEqual([]);+ } finally { await f.stop(); }+ });+});diff --git a/server/drivers/ollama-context.ts b/server/drivers/ollama-context.tsnew file mode 100644index 0000000000..27dae1de7d--- /dev/null+++ b/server/drivers/ollama-context.ts@@ -0,0 +1,138 @@+// Ollama picks a context window from the machine's VRAM unless told otherwise: 4,096 tokens below 23 GB, which on a+// laptop is less than our system prompt and tool list, and it drops the excess without an error. The OpenAI and Anthropic+// routes every engine here speaks cannot set it (OpenAI's request has no such field), and /api/ps only knows a model once+// it runs. So a model gets a second name that carries the window: /api/create from the same weights copies nothing but a+// small manifest, and every engine can use that name as is.+import { totalmem } from "node:os";++const SUFFIX = /-omb-(\d+)k$/;+const MIN_WINDOW = 16_384;+const MAX_WINDOW = 65_536;+/** An estimate, generous on purpose: what a token of window costs in memory varies with the architecture. */+const WINDOW_BYTES_PER_TOKEN = 64 * 1024;+/** What macOS lets the GPU wire by default, and a fair share of a PC's memory. */+const MEMORY_SHARE = 0.75;++const nameFor = (model: string, window: number) => `${model.includes(":") ? model : `${model}:latest`}-omb-${window / 1024}k`;++export const isContextName = (model: string) => SUFFIX.test(model);++/** The name a person picked, for one of ours coming back in a server's lists. */+export const pickedName = (model: string) => model.replace(SUFFIX, "");++/** The largest power of two that leaves the weights room, between what an agent needs and what stays fast on a laptop. */+export function windowFor(modelBytes: number | undefined, trained: number | undefined, memoryBytes = totalmem()): number {+ const room = modelBytes === undefined ? 0 : memoryBytes * MEMORY_SHARE - modelBytes;+ let window = MIN_WINDOW;+ while (window < MAX_WINDOW && room / WINDOW_BYTES_PER_TOKEN >= window * 2) window *= 2;+ return trained && trained < window ? trained : window;+}++interface ShowFacts {+ /** A window the person set in a Modelfile. */+ pinned?: number;+ trained?: number;+ remote: boolean;+}++export function showFacts(show: unknown): ShowFacts {+ const row = (show && typeof show === "object" ? show : {}) as { parameters?: unknown; model_info?: unknown; remote_host?: unknown; remote_model?: unknown };+ const pinned = typeof row.parameters === "string" ? /^\s*num_ctx\s+(\d+)\s*$/m.exec(row.parameters)?.[1] : undefined;+ const info = row.model_info && typeof row.model_info === "object" ? Object.entries(row.model_info) : [];+ const trained = info.find(([key, value]) => key.endsWith(".context_length") && typeof value === "number" && value > 0)?.[1] as number | undefined;+ return { ...(pinned ? { pinned: Number(pinned) } : {}), ...(trained ? { trained } : {}), remote: Boolean(row.remote_host || row.remote_model) };+}++export interface ServedModel {+ model: string;+ /** Known only once decided; absent leaves the catalog's own figure. */+ window?: number;+}++const decided = new Map<string, ServedModel>();+const checkedAt = new Map<string, number>();+const deciding = new Map<string, Promise<ServedModel>>();+const cacheKey = (origin: string, model: string) => `${origin}\n${model}`;++/** What was decided for this model, without asking the server. */+export function servedModel(origin: string, model: string): ServedModel | undefined {+ return decided.get(cacheKey(origin, model));+}++async function json(fetchImpl: typeof fetch, url: string, init: RequestInit, timeoutMs: number): Promise<unknown> {+ const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ return response.json();+}++const post = (body: unknown): RequestInit => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });++async function decide(origin: string, model: string, fetchImpl: typeof fetch, memoryBytes: number | undefined): Promise<ServedModel> {+ const facts = showFacts(await json(fetchImpl, `${origin}/api/show`, post({ model }), 3_000));+ if (facts.remote) return { model };+ if (facts.pinned) return { model, window: facts.pinned };+ const running = await json(fetchImpl, `${origin}/api/ps`, {}, 3_000).catch(() => null) as { models?: Array<{ name?: unknown; model?: unknown; context_length?: unknown }> } | null;+ const loaded = running?.models?.find((entry) => entry.name === model || entry.model === model || entry.name === `${model}:latest`)?.context_length;+ const tags = await json(fetchImpl, `${origin}/api/tags`, {}, 3_000).catch(() => null) as { models?: Array<{ name?: unknown; size?: unknown }> } | null;+ const row = tags?.models?.find((entry) => entry.name === model || entry.name === `${model}:latest`);+ const window = windowFor(typeof row?.size === "number" ? row.size : undefined, facts.trained, memoryBytes);+ // Already running with enough, from the person's OLLAMA_CONTEXT_LENGTH or a large machine's default: leave it so.+ if (typeof loaded === "number" && loaded >= window) return { model, window: loaded };+ const name = nameFor(model, window);+ await json(fetchImpl, `${origin}/api/create`, post({ model: name, from: model, parameters: { num_ctx: window }, stream: false }), 15_000);+ return { model: name, window };+}++const RETRY_AFTER_MS = 60_000;+const RECHECK_AFTER_MS = 60_000;+const forgetLater = (forget: () => void) => { setTimeout(forget, RETRY_AFTER_MS).unref(); };++/** Never throws: anything that goes wrong (another server on this port, an older Ollama, a name it refuses) leaves the+ * model as it was for a minute, then tries again. */+export function serveWithWindow(origin: string, model: string, fetchImpl: typeof fetch = fetch, memoryBytes?: number): Promise<ServedModel> {+ if (isContextName(model)) return Promise.resolve({ model });+ const key = cacheKey(origin, model);+ const known = decided.get(key);+ if (known && (known.model === model || Date.now() - (checkedAt.get(key) ?? 0) < RECHECK_AFTER_MS)) return Promise.resolve(known);+ const running = deciding.get(key);+ if (running) return running;+ // Someone tidying `ollama list` may have removed our name. Only a clear "not found" counts: a busy server is still fine.+ const stillThere = known+ ? fetchImpl(`${origin}/api/show`, { ...post({ model: known.model }), signal: AbortSignal.timeout(3_000) }).then((response) => response.status !== 404, () => true)+ : Promise.resolve(false);+ const attempt = stillThere+ .then((there) => there ? known! : decide(origin, model, fetchImpl, memoryBytes))+ .then((served) => { decided.set(key, served); checkedAt.set(key, Date.now()); return served; })+ .catch(() => {+ const unchanged = { model };+ decided.set(key, unchanged);+ forgetLater(() => { if (decided.get(key) === unchanged) decided.delete(key); });+ return unchanged;+ })+ .finally(() => { deciding.delete(key); });+ deciding.set(key, attempt);+ return attempt;+}++const answersAsOllama = new Map<string, Promise<boolean>>();++/** The one thing only Ollama answers: `/api/version` with a version. */+export function isOllama(origin: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {+ let answer = answersAsOllama.get(origin);+ if (!answer) {+ answer = json(fetchImpl, `${origin}/api/version`, {}, 2_000)+ .then((body) => typeof (body as { version?: unknown } | null)?.version === "string")+ .catch(() => false);+ answersAsOllama.set(origin, answer);+ // A server that was simply not up yet must not be written off for good.+ void answer.then((yes) => { if (!yes) forgetLater(() => answersAsOllama.delete(origin)); });+ }+ return answer;+}++export function forgetServedModels(): void {+ decided.clear();+ checkedAt.clear();+ deciding.clear();+ answersAsOllama.clear();+}diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 696fb33d0d..4ef56271ec 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -119,6 +119,8 @@ interface RuntimeOptions<Config> {computerUse?: boolean;/** A text-only model keeps the computer and browser tools but never receives a screenshot or attachment. */imageInput?: (model: string) => boolean;+ /** The name to send for a model, when its server knows it by another. */+ servedModel?: (model: string) => Promise<string>;/** Smaller models announce a step and end the turn without calling a tool; such a reply gets a nudge, at most three* per turn and each only after tool progress since the last. */nudgeAnnouncedAction?: boolean;@@ -288,10 +290,11 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)? AbortSignal.any([signal, timeoutController.signal]): timeoutController.signal;+ const served = options.servedModel ? await options.servedModel(model) : model;const payload = JSON.stringify(route === "responses"- ? responsesRequest({ model, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model) })+ ? responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model) }): {- ...options.requestBody(model, messages, stream),+ ...options.requestBody(served, messages, stream),...(route === "chat-reasoning-off" ? { reasoning_effort: "none" } : {}),...(tools.length ? { tools } : {}),});diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 4150faa45e..fe6deaede4 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -3,6 +3,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 { createOpenAIChatRuntime } from "./openai-chat.ts";import {freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,@@ -233,7 +234,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {const options: ModelCatalog["options"] = [];for (const row of rows) {const id = typeof row.id === "string" ? row.id : "";- if (!id || seen.has(id)) continue;+ if (!id || seen.has(id) || isContextName(id)) continue;seen.add(id);const label = typeof row.name === "string" && row.name.trim() ? row.name : id;const contextWindow = advertisedContextWindow(row);@@ -275,9 +276,19 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {fetchModels(),]) : null;+ const origin = onThisNetwork(config.url) ? config.url.replace(/\/v1$/, "") : null;+ const servedModel = origin ? async (model: string) => {+ if (!await isOllama(origin)) return model;+ const served = await serveWithWindow(origin, model);+ const option = served.window ? catalog.options.find((entry) => entry.id === model) : undefined;+ if (option) option.contextWindow = served.window;+ return served.model;+ } : undefined;+const runtime = createOpenAIChatRuntime({input,driverKind: DRIVER_KIND,+ ...(servedModel ? { servedModel } : {}),apiKey,apiUrl: config.url,tools: config.tools,diff --git a/server/harness/registry.ts b/server/harness/registry.tsindex ad664f0cc8..ddcfdcecd0 100644--- a/server/harness/registry.ts+++ b/server/harness/registry.ts@@ -4,6 +4,7 @@ import { installNpmEngine, npmAvailable, serverInstallFor, standaloneLookupPathimport { installStandaloneEngine, isAppStandaloneCopy, type StandaloneInstalled } from "../engine-standalone.ts";import { withEngineMemory } from "../engine-memory.ts";import { withEngineHomes } from "../engine-homes/engine-homes.ts";+import { withLocalContext } from "../drivers/local-inject.ts";import { engineStatusFile, snapshotFrom } from "./engine-status-file.ts";import { withUnaskedStops } from "./unasked-stop.ts";export { engineMemory } from "../engine-memory.ts";@@ -172,13 +173,13 @@ export class ProviderRegistry {// The RAW config: decodeConfig fills in the driver default, which would flag every instance as overridden.const rawCli = cliOfRaw(entry.config);if (rawCli) this.cliByInstance.set(instanceId, rawCli);- const live = withUnaskedStops(withEngineHomes(withEngineMemory(await driver.create({+ const live = withLocalContext(withUnaskedStops(withEngineHomes(withEngineMemory(await driver.create({instanceId,displayName: entry.displayName ?? driver.metadata.displayName,environment: entry.environment ?? {},enabled: entry.enabled ?? true,config,- }))));+ })))));this.shareSnapshot(live);return { instanceId, live: decorate ? decorate(live) : live };} catch (e) {diff --git a/server/model-context-window.ts b/server/model-context-window.tsindex e60cd14230..4a881ef57f 100644--- a/server/model-context-window.ts+++ b/server/model-context-window.ts@@ -1,5 +1,9 @@+import { injectedContextWindow } from "./drivers/local-inject.ts";+export function modelContextWindow(model: string | undefined): number | undefined {if (!model) return undefined;+ const local = injectedContextWindow(model);+ if (local) return local;const id = model.toLowerCase();// Opus 5.5 and Sonnet 5.5 are 1M without a `[1m]` suffix: only the exact slug, alone or after a slash or provider dot.if (/(?:^|[/.])claude-(?:opus|sonnet)-5(?:-5|\.5)$/.test(id)) return 1_000_000;