Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
OpenAI-compatible servers: let one behind a tunnel count as local
erywimb14f59343410
diff --git a/server/agents-bridge-switch.test.ts b/server/agents-bridge-switch.test.tsindex eee930522f..3a207db8d4 100644--- a/server/agents-bridge-switch.test.ts+++ b/server/agents-bridge-switch.test.ts@@ -539,6 +539,11 @@ describe("a bot on a local model gets the bridge without the switch", () => {expect(agentsToolBridgeRefusal({}, onOllama, onServer("https://openrouter.ai/api/v1"), {})).toBeNull();});+ it("on a tunnel address the person marked local", () => {+ expect(agentsToolBridgeRefusal({}, {}, { driverKind: "openai-compat", config: { url: "https://tunnel.example.test/v1", local: true } }, {})).toBeNull();+ expect(agentsToolBridgeRefusal({}, {}, { driverKind: "openai-compat", config: { url: "https://tunnel.example.test/v1" } }, {})).toBe("the switch is off");+ });+it("not on a hosted model", () => {expect(agentsToolBridgeRefusal({}, { modelSelection: { model: "gpt-5" } }, onServer("https://openrouter.ai/api/v1"), {})).toBe("the switch is off");expect(agentsToolBridgeRefusal({}, {}, { driverKind: "grok", config: { url: "http://127.0.0.1:1/v1" } }, {})).toBe("the switch is off");diff --git a/server/agents-bridge-switch.ts b/server/agents-bridge-switch.tsindex bfc386c324..29141fb0ab 100644--- a/server/agents-bridge-switch.ts+++ b/server/agents-bridge-switch.ts@@ -11,7 +11,7 @@ import { parseToolScope } from "../shared/tool-scope.ts";import { bridgedCallName } from "./agents-bridge-names.ts";import { TOOL_BRIDGE_ENV } from "./drivers/agents-bridge.ts";import { decodeInjectId } from "./drivers/local-inject.ts";-import { onThisNetwork } from "./drivers/openai-compat.ts";+import { servesLocalModel } from "./drivers/openai-compat.ts";import { resolveClaudeConfigDir } from "./drivers/claude.ts"; import { claudeCliSupports, parseClaudeCliVersion } from "./drivers/claude-cli-version.ts";import { claudeToolSearchOn, claudeToolSearchSetting } from "./drivers/claude-tool-search.ts";import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";@@ -38,12 +38,12 @@ export function agentsToolBridgeEnabled(cfg: BridgeConfig, env: NodeJS.ProcessEn}/** A model on this machine or network reads the whole list on every turn, out of a small window and at laptop speed:- * about 15,000 tokens before the person has said anything. OMB_AGENTS_TOOL_BRIDGE=0 still wins. */+ * about 15,000 tokens before the person has said anything. A server marked local is treated the same. OMB_AGENTS_TOOL_BRIDGE=0 still wins. */function runsLocalModel(bot: { modelSelection?: { model?: unknown } } | null | undefined, engine: BridgeEngine | null | undefined): boolean {const model = bot?.modelSelection?.model;if (typeof model === "string" && decodeInjectId(model)) return true;- const url = (engine?.config as { url?: unknown } | undefined)?.url;- return engine?.driverKind === "openai-compat" && typeof url === "string" && onThisNetwork(url);+ const config = engine?.config as { url?: unknown; local?: unknown } | undefined;+ return engine?.driverKind === "openai-compat" && typeof config?.url === "string" && servesLocalModel({ url: config.url, local: config.local === true });}/** The engine a turn runs on, as far as the decision reads it. */diff --git a/server/drivers/openai-chat-local-model.test.ts b/server/drivers/openai-chat-local-model.test.tsindex f2dc933f47..83d5501f54 100644--- a/server/drivers/openai-chat-local-model.test.ts+++ b/server/drivers/openai-chat-local-model.test.ts@@ -50,7 +50,7 @@ const structured = (response: ServerResponse, name: string, id: string) =>const cleanups: Array<() => Promise<void>> = [];afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });-async function fixture(script: Script, driver: "local" | "hosted" = "local") {+async function fixture(script: Script, driver: "local" | "hosted" = "local", config: { host?: string; local?: boolean } = {}) {const directory = mkdtempSync(join(tmpdir(), "omb-chat-local-"));const requests: ChatRequest[] = [];const server = createServer(async (request, response) => {@@ -71,7 +71,7 @@ async function fixture(script: Script, driver: "local" | "hosted" = "local") {writeFileSync(helper, MCP_SCRIPT);const instance: ProviderInstance = await (driver === "hosted" ? GrokDriver : OpenAICompatDriver).create({instanceId: randomUUID(), displayName: "Local fixture", enabled: true,- config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY" },+ config: { url: `http://${config.host ?? "127.0.0.1"}:${address.port}/v1`, apiKeyEnv: "FIXTURE_CHAT_KEY", ...(config.local ? { local: true } : {}) },environment: { FIXTURE_CHAT_KEY: "fixture-key" },});const recorder = recordEvents(instance.adapter);@@ -175,6 +175,23 @@ describe("a tool call a local model wrote as text", () => {expect(f.requests).toHaveLength(1);expect(f.shown()).toBe(TAGGED);});++ it("does all of this for a server marked local behind a tunnel address", async () => {+ const f = await fixture((_body, response, round) => round === 1 ? say(response, TAGGED) : say(response, "Stored."), "local", { host: "0.0.0.0", local: true });+ await f.start();+ expect(await f.completed()).toMatchObject({ ok: true });+ expect(f.effects()).toEqual([{ name: "receipt" }]);+ expect(f.shown()).not.toContain("tool_call");+ });++ it("leaves a tunnel address alone without the mark", async () => {+ const f = await fixture((_body, response) => say(response, TAGGED), "local", { host: "0.0.0.0" });+ await f.start();+ await f.completed();+ expect(f.effects()).toEqual([]);+ expect(f.requests).toHaveLength(1);+ expect(f.shown()).toBe(TAGGED);+ });});describe("a local model repeating itself", () => {diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex b32087796d..2e4968887a 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -6,7 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { recordEvents } from "../testing/events.ts";import { buildTurnContext, replaysNatively } from "../turn-context.ts";import { instanceConfigs } from "../config.ts";-import { OpenAICompatDriver } from "./openai-compat.ts";+import { OpenAICompatDriver, servesLocalModel } from "./openai-compat.ts";import { flushNativeLogs } from "./native.ts";describe("OpenAICompatDriver", () => {@@ -1344,6 +1344,21 @@ it("openai-compat preserves an explicit tools-off connection and rejects ambiguoexpect(() => OpenAICompatDriver.decodeConfig({ tools: "false" })).toThrow("tools must be a boolean");});+describe("a server marked local", () => {+ it("keeps the mark only when it is true, and refuses a non-boolean", () => {+ expect(OpenAICompatDriver.decodeConfig({ url: "https://tunnel.example.test/v1", local: true })).toMatchObject({ local: true });+ expect(OpenAICompatDriver.decodeConfig({ url: "https://tunnel.example.test/v1", local: false })).not.toHaveProperty("local");+ expect(OpenAICompatDriver.decodeConfig({ url: "https://tunnel.example.test/v1" })).not.toHaveProperty("local");+ expect(() => OpenAICompatDriver.decodeConfig({ local: "yes" })).toThrow("local must be a boolean");+ });++ it("counts as local at any address, and an unmarked one only on this network", () => {+ expect(servesLocalModel({ url: "https://tunnel.example.test/v1", local: true })).toBe(true);+ expect(servesLocalModel({ url: "https://tunnel.example.test/v1" })).toBe(false);+ expect(servesLocalModel({ url: "http://10.0.0.5:11434/v1" })).toBe(true);+ });+});+describe("how long a turn waits for a reply", () => {it("accepts 1 to 60 whole minutes and refuses anything else", () => {expect(OpenAICompatDriver.decodeConfig({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: 20 })).toMatchObject({ replyWaitMinutes: 20 });diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex 6ac94a5fff..dd7d80a172 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -106,6 +106,15 @@ export interface OpenAICompatConfig {reasoningEfforts?: Record<string, string[]>;/** How long a turn waits for the next piece of a reply before giving up; unset follows the server's default. */replyWaitMinutes?: number;+ /** The server serves a local model from an address that is not on this machine or network: a tunnel, a VPN+ * hostname or a reverse proxy in front of Ollama, LM Studio or llama.cpp. Local-model turn handling applies. */+ local?: boolean;+}++/** Whether a turn on this server gets local-model handling: text-form tool-call recovery, the repeat guard and+ * corrective rounds. An address on this network says yes on its own; `local` opts in one that is not. */+export function servesLocalModel(config: Pick<OpenAICompatConfig, "url" | "local">): boolean {+ return config.local === true || onThisNetwork(config.url);}const CATALOGS = ["openai", "lmstudio", "ollama"] as const;@@ -163,6 +172,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {const ownKey = typeof config.apiKeyEnv === "string" && OWN_KEY_ENVS.has(config.apiKeyEnv);if (config.catalog !== undefined && !CATALOGS.includes(config.catalog as never)) throw new Error("catalog must be \"openai\", \"lmstudio\" or \"ollama\"");if (config.replyWaitMinutes !== undefined && !isReplyWait(config.replyWaitMinutes)) throw new Error(`replyWaitMinutes must be a whole number from 1 to ${MAX_REPLY_WAIT_MINUTES}`);+ if (config.local !== undefined && typeof config.local !== "boolean") throw new Error("local must be a boolean");const envUrl = ownKey ? undefined : process.env.OPENAI_COMPAT_URL;const inherits = !ownKey && onWorkspaceServer(config.url, envUrl);return {@@ -170,6 +180,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {...(config.managedModels ? { managedModels: config.managedModels as string[] } : {}),...(reasoningEfforts ? { reasoningEfforts } : {}),...(isReplyWait(config.replyWaitMinutes) ? { replyWaitMinutes: config.replyWaitMinutes } : {}),+ ...(config.local === true ? { local: true } : {}),url: (typeof config.url === "string" && config.url ? config.url : envUrl || "https://openrouter.ai/api/v1").replace(/\/+$/, ""),apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv@@ -433,7 +444,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {missingKeyError: missingKey,unavailableReason: missingKey,timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),- ...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),+ ...(servesLocalModel(config) ? { livenessEveryMs: livenessEveryMs(), localModel: true } : {}),reasoning: true,billing: "metered",includeUsageInCompleted: true,diff --git a/server/openai-compat-endpoints.ts b/server/openai-compat-endpoints.tsindex 13ce4602af..9982f79f17 100644--- a/server/openai-compat-endpoints.ts+++ b/server/openai-compat-endpoints.ts@@ -32,6 +32,7 @@ export const addEndpointSchema = z.object({key: z.string().trim().min(1).max(4096),models: z.array(z.string().trim().min(1).max(200)).max(64).optional(),catalog: z.enum(["lmstudio", "ollama"]).optional(),+ local: z.boolean().optional(),}).strict();export type AddEndpoint = z.infer<typeof addEndpointSchema>;@@ -55,7 +56,7 @@ export function addEndpoint(instances: InstanceConfigMap, body: AddEndpoint): {const models = [...new Set(body.models ?? [])];instances[instanceId] = {driver: "openai-compat", displayName: body.displayName, access: "api",- config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}) },+ config: { key: body.key, url, ...(models.length ? { managedModels: models } : {}), ...(body.catalog ? { catalog: body.catalog } : {}), ...(body.local === true ? { local: true } : {}) },};return { instanceId };}diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.tsindex 846528b6e5..eafedff279 100644--- a/src/components/OpenAiCompatServers.test.ts+++ b/src/components/OpenAiCompatServers.test.ts@@ -66,7 +66,7 @@ describe("other OpenAI-compatible servers", () => {describe("adding another OpenAI-compatible server", () => {const KEY = "sk-ZZtestSECRET0123456789";- type Props = { children?: ReactNode; servers?: unknown; onChange?: (event: { target: { value: string } }) => void; onClick?: () => void; "aria-label"?: string };+ type Props = { children?: ReactNode; servers?: unknown; type?: string; onChange?: (event: { target: { value?: string; checked?: boolean } }) => void; onClick?: () => void; "aria-label"?: string };const nodes = (tree: ReactNode): Array<ReactElement<Props>> =>Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve(); };@@ -106,6 +106,19 @@ describe("adding another OpenAI-compatible server", () => {expect(JSON.stringify(fixture.track.mock.calls)).not.toMatch(/ada|example|ZZtest|SECRET/);});+ it("marks a server behind a tunnel as local only when the box is ticked", async () => {+ const box = () => form().find((node) => node.type === "input" && node.props.type === "checkbox")!;+ expect(JSON.stringify(form().map((node) => node.props.children ?? ""))).toContain("tunnel");+ fixture.values = [];+ fixture.api.mockReset();+ fixture.api.mockResolvedValue({ instances: [] });+ await add();+ expect(JSON.parse(String(fixture.api.mock.calls.at(-1)![1].body))).not.toHaveProperty("local");+ box().props.onChange!({ target: { checked: true } });+ await add();+ expect(JSON.parse(String(fixture.api.mock.calls.at(-1)![1].body))).toMatchObject({ local: true });+ });+it("fills in Google Gemini, so only the AI Studio key is left to paste", async () => {fixture.values = [];fixture.api.mockReset();diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsxindex fcc203afa9..1f11b0a9f6 100644--- a/src/components/OpenAiCompatServers.tsx+++ b/src/components/OpenAiCompatServers.tsx@@ -92,6 +92,8 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })const [url, setUrl] = useState("");const [key, setKey] = useState("");const [models, setModels] = useState("");+ /** The server serves a local model from a tunnel, VPN or reverse-proxy address. */+ const [local, setLocal] = useState(false);const [busy, setBusy] = useState<"add" | "other" | null>(null);/** The last failure, and the server whose model-ID editor it belongs to (shown there instead of below the add form). */const [error, setError] = useState<{ text: string; at?: string } | null>(null);@@ -124,12 +126,12 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })"add",() => api("/api/instances/openai-compat", {method: "POST",- body: JSON.stringify({ displayName: name.trim(), url: url.trim(), key: key.trim(), ...(modelIds(models).length ? { models: modelIds(models) } : {}) }),+ body: JSON.stringify({ displayName: name.trim(), url: url.trim(), key: key.trim(), ...(modelIds(models).length ? { models: modelIds(models) } : {}), ...(local ? { local: true } : {}) }),}).then((added) => { keySaved("custom_endpoint", "settings", "unverified"); return added; },(cause: unknown) => { keySaved("custom_endpoint", "settings", "error"); throw cause; },),- () => { setName(""); setUrl(""); setKey(""); setModels(""); },+ () => { setName(""); setUrl(""); setKey(""); setModels(""); setLocal(false); },);return (@@ -258,6 +260,13 @@ function AddedServers({ servers }: { servers: ReturnType<typeof addedServers> })<input value={models} onChange={(e) => setModels(e.target.value)} placeholder={t("apiInstances.models")} aria-label={t("apiInstances.models")}spellCheck={false} disabled={busy !== null} className={INPUT} /><p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.modelsHint")}</p>+ <label className="flex items-start gap-2 text-[13px]">+ <input className="mt-1 accent-accent" type="checkbox" checked={local} onChange={(e) => setLocal(e.target.checked)} disabled={busy !== null} />+ <span className="text-ink">+ {t("apiInstances.localModel")}+ <span className="mt-0.5 block text-[12px] leading-4 text-ink-secondary">{t("apiInstances.localModelHint")}</span>+ </span>+ </label><buttontype="button"onClick={add}diff --git a/src/locales/en.json b/src/locales/en.jsonindex cf38252006..03f49c2cd5 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7700,6 +7700,8 @@"apiInstances.key": "API key","apiInstances.models": "Model IDs, separated by commas (optional)","apiInstances.modelsHint": "Leave the model IDs empty to detect them. If the model picker then shows only sample models, this server does not list its models: enter them here.",+ "apiInstances.localModel": "This server runs a local model",+ "apiInstances.localModelHint": "Turn this on when the address is a tunnel, VPN or reverse proxy in front of Ollama, LM Studio or llama.cpp. Bots then handle this model's tool calls the way they do for a model on this machine.","apiInstances.geminiPreset": "Fill in Google Gemini","apiInstances.geminiKeyHint": "Paste a Gemini API key from Google AI Studio (aistudio.google.com/apikey). Models are detected after you add it.","apiInstances.add": "Add server",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 0dd3959498..9de2e5a918 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7311,6 +7311,8 @@"apiInstances.key": "Chave de API","apiInstances.models": "IDs de modelos, separados por vírgulas (opcional)","apiInstances.modelsHint": "Deixe os IDs em branco para detectar os modelos automaticamente. Se o seletor mostrar só modelos de exemplo, este servidor não lista os modelos disponíveis. Nesse caso, digite os IDs aqui.",+ "apiInstances.localModel": "Este servidor roda um modelo local",+ "apiInstances.localModelHint": "Ative quando o endereço for um túnel, VPN ou proxy reverso na frente do Ollama, LM Studio ou llama.cpp. Os bots passam a tratar as chamadas de ferramenta deste modelo como as de um modelo nesta máquina.","apiInstances.geminiPreset": "Preencher com Google Gemini","apiInstances.geminiKeyHint": "Cole uma chave de API do Gemini gerada no Google AI Studio (aistudio.google.com/apikey). O app detecta os modelos depois que você adiciona a chave.","apiInstances.add": "Adicionar servidor",