Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(local-models): a local model's reply wait goes past 5 minutes; a dead server stops it early
Aditya Umale0bfaa886dbad
diff --git a/package.json b/package.jsonindex 07628b9d27..29dde9d2e2 100644--- a/package.json+++ b/package.json@@ -133,6 +133,7 @@"tailwind-merge": "^3.3.1","tar": "7.5.22","tldts": "7.4.18",+ "undici": "8.11.2","vega": "6.4.0","vega-embed": "7.3.0","vega-interpreter": "2.3.2",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e639fd95a9..7dae8dfe01 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -144,6 +144,9 @@ importers:tldts:specifier: 7.4.18version: 7.4.18+ undici:+ specifier: 8.11.2+ version: 8.11.2vega:specifier: 6.4.0version: 6.4.0@@ -4993,6 +4996,10 @@ packages:resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}engines: {node: '>=20.18.1'}+ resolution: {integrity: sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==}+ engines: {node: '>=22.19.0'}+resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==}@@ -10304,6 +10311,8 @@ snapshots:+ [email protected]: {}+dependencies:pathe: 2.0.3diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex 82b24de043..bba4f32511 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -26,6 +26,7 @@ import { requestTooLargeMessage } from "../../shared/request-too-large.ts";import { toolSchemaProfileFor } from "../tool-schema-profile.ts";import { classifyContinuable, writeTurnHandoff } from "../turn-continuation.ts";import { KEY_REJECTED_REASON, keyRejected, noteKeyAccepted, noteKeyRejected, rejectsKey } from "../key-rejections.ts";+import { Agent, fetch as fetchWithoutLimits } from "undici";export interface OpenAIChatMessage {role: "system" | "user" | "assistant" | "tool";@@ -99,6 +100,16 @@ interface NativeLog {incoming(completion: Completion): unknown;}+// Node's fetch (undici 7.29 in Electron 43, 8.9 in Node 26) fails a request after 300 s without response headers+// or body bytes, whatever its signal allows. A local model sends nothing until its first token.+const FETCH_LIMIT_MS = 300_000;+const LIVENESS_MISSES = 3;+let unlimitedAgent: Agent | undefined;+function fetchPastLimit(url: string, init: RequestInit): Promise<Response> {+ unlimitedAgent ??= new Agent({ headersTimeout: 0, bodyTimeout: 0 });+ return fetchWithoutLimits(url, { ...init, dispatcher: unlimitedAgent } as Parameters<typeof fetchWithoutLimits>[1]) as unknown as Promise<Response>;+}+interface RuntimeOptions<Config> {input: DriverCreateInput<Config>;driverKind: string;@@ -110,6 +121,9 @@ interface RuntimeOptions<Config> {missingKeyError: string;unavailableReason: string;timeoutMs: number;+ /** Ask a server on this machine or network for its models this often while a reply is pending, and stop the reply+ * when it misses LIVENESS_MISSES checks in a row: it crashed, froze or left the network. */+ livenessEveryMs?: number;nativeLog: NativeLog;refreshModels?: () => Promise<void>;generateModel?: () => string;@@ -306,6 +320,19 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)createdAt: new Date().toISOString(),});+ const watchServer = (everyMs: number, stop: (reason: Error) => void) => {+ let misses = 0;+ const timer = setInterval(() => {+ fetch(`${options.apiUrl}/models`, { headers: { authorization: `Bearer ${options.apiKey}` }, signal: AbortSignal.timeout(everyMs) })+ .then((response) => { misses = 0; void response.body?.cancel(); })+ .catch(() => {+ if (++misses === LIVENESS_MISSES) stop(new Error(`The model server at ${new URL(options.apiUrl).host} stopped answering, so the reply was stopped.`));+ });+ }, everyMs);+ timer.unref();+ return timer;+ };+const complete = async (messages: OpenAIChatMessage[],model: string,@@ -325,6 +352,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)};resetIdleTimer();+ const liveness = options.livenessEveryMs ? watchServer(options.livenessEveryMs, (reason) => timeoutController.abort(reason)) : null;try {const activeSignal = signal@@ -335,7 +363,8 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)...options.requestBody(model, messages, stream),...(tools.length ? { tools } : {}),});- const response = await fetch(`${options.apiUrl}/chat/completions`, {+ const send = options.timeoutMs > FETCH_LIMIT_MS ? fetchPastLimit : fetch;+ const response = await send(`${options.apiUrl}/chat/completions`, {method: "POST",...(messages.some(message => Array.isArray(message.content) && message.content.some(part => part.type === "image_url")) ? { redirect: "error" as const } : {}),headers: { authorization: `Bearer ${options.apiKey}`, "content-type": "application/json" },@@ -488,6 +517,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)return { text, reasoning, usage, toolCalls: calls.finish(finishReason, malformedFrame), finishReason, protocolReasoning, protocolReasoningDetails: details.blocks };} finally {if (idleTimer) clearTimeout(idleTimer);+ if (liveness) clearInterval(liveness);}};diff --git a/server/drivers/openai-compat-idle.test.ts b/server/drivers/openai-compat-idle.test.tsindex 4dcc29dc1c..393a1ff88a 100644--- a/server/drivers/openai-compat-idle.test.ts+++ b/server/drivers/openai-compat-idle.test.ts@@ -1,6 +1,6 @@import { createServer } from "node:http";import { afterEach, expect, it, vi } from "vitest";-import { OpenAICompatDriver } from "./openai-compat.ts";+import { OpenAICompatDriver, onThisNetwork } from "./openai-compat.ts";import { recordEvents } from "../testing/events.ts";afterEach(() => vi.unstubAllEnvs());@@ -49,3 +49,74 @@ it.each(["json", "http-error", "truncated", "interrupt"] as const)("settles a reawait new Promise<void>((resolve) => upstream.close(() => resolve()));}}, 10_000);++async function localServer(handle: (req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse) => void) {+ const upstream = createServer(handle);+ await new Promise<void>((resolve) => upstream.listen(0, "127.0.0.1", resolve));+ const address = upstream.address();+ if (!address || typeof address === "string") throw new Error("No fixture port");+ const inst = await OpenAICompatDriver.create({+ instanceId: "local-wait", displayName: "Loopback fixture", enabled: true,+ config: { url: `http://127.0.0.1:${address.port}/v1`, apiKeyEnv: "FIXTURE_KEY", model: "fixture" },+ environment: { FIXTURE_KEY: "synthetic-not-a-secret" },+ });+ const recorder = recordEvents(inst.adapter);+ return {+ inst, recorder,+ async close() {+ recorder.stop();+ await inst.dispose();+ upstream.closeAllConnections();+ await new Promise<void>((resolve) => upstream.close(() => resolve()));+ },+ };+}++it("stops waiting soon after a local server stops answering, long before the reply wait", async () => {+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_IDLE_TIMEOUT_MS", "60000");+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_PROBE_MS", "200");+ let frozen = false;+ const fixture = await localServer((req, res) => {+ if (req.url === "/v1/models" && !frozen) { res.end(JSON.stringify({ data: [] })); return; }+ frozen = true;+ });+ try {+ const started = Date.now();+ await fixture.inst.adapter.sendTurn({ threadId: "frozen", text: "fixture" });+ const done = await fixture.recorder.until((event) => event.type === "turn.completed", 10_000);+ expect(done).toMatchObject({ ok: false });+ expect(Date.now() - started).toBeLessThan(10_000);+ expect(fixture.recorder.events.find((event) => event.type === "runtime.error")).toMatchObject({ message: expect.stringContaining("stopped answering") });+ } finally {+ await fixture.close();+ }+}, 15_000);++it("keeps waiting for a slow first token while the local server still answers", async () => {+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_IDLE_TIMEOUT_MS", "60000");+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_PROBE_MS", "200");+ const fixture = await localServer((req, res) => {+ if (req.url === "/v1/models") { res.end(JSON.stringify({ data: [] })); return; }+ setTimeout(() => {+ res.writeHead(200, { "content-type": "text/event-stream" });+ res.end('data: {"choices":[{"index":0,"delta":{"content":"slow hello"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n');+ }, 2_000);+ });+ try {+ await fixture.inst.adapter.sendTurn({ threadId: "slow", text: "fixture" });+ const done = await fixture.recorder.until((event) => event.type === "turn.completed", 10_000);+ expect(done).toMatchObject({ ok: true });+ expect(fixture.recorder.events.find((event) => event.type === "item.completed")).toMatchObject({ text: "slow hello" });+ } finally {+ await fixture.close();+ }+}, 15_000);++it("checks only servers on this machine or network, never a cloud provider", () => {+ for (const url of ["http://127.0.0.1:11434/v1", "http://localhost:1234/v1", "http://[::1]:8080/v1", "http://192.168.1.20:11434/v1", "http://10.0.0.5/v1", "http://172.20.1.2/v1", "http://studio.local:1234/v1"]) {+ expect(onThisNetwork(url), url).toBe(true);+ }+ for (const url of ["https://openrouter.ai/api/v1", "https://api.together.xyz/v1", "http://172.32.0.1/v1", "not a url"]) {+ expect(onThisNetwork(url), url).toBe(false);+ }+});diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex c4f3bf983d..353458411d 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -1,6 +1,7 @@// Transcript-replay driver for OpenRouter, Groq, Together, llama.cpp, and// other endpoints that speak the OpenAI chat-completions contract.import type { ModelCatalog, ProviderDriver } from "../contracts.ts";+import { isLoopback } from "../provider-key-check.ts";import { lmStudioV1Catalog } from "./local-inject.ts";import { createOpenAIChatRuntime } from "./openai-chat.ts";import {@@ -16,6 +17,17 @@ const idleTimeoutMs = () => {const value = Number(raw);return Number.isSafeInteger(value) && value >= 1_000 && value <= 2_147_483_647 ? value : DEFAULT_IDLE_TIMEOUT_MS;};+const LIVENESS_EVERY_MS = 30_000;+const livenessEveryMs = () => {+ const value = Number(process.env.OPENMAUS_OPENAI_COMPAT_PROBE_MS);+ return Number.isSafeInteger(value) && value >= 100 ? value : LIVENESS_EVERY_MS;+};+/** Ollama, LM Studio or llama.cpp on this machine or a home or office network: asking it for its models is free. */+export function onThisNetwork(url: string): boolean {+ let host: string;+ try { host = new URL(url).hostname.replace(/^\[|\]$/g, ""); } catch { return false; }+ return isLoopback(host) || host.endsWith(".local") || /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(host) || /^f[cd][0-9a-f]{2}:/i.test(host);+}const DEFAULT_MODELS: ModelCatalog = {default: "meta-llama/llama-3.3-70b-instruct",options: [@@ -286,6 +298,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {missingKeyError: missingKey,unavailableReason: missingKey,timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),+ ...(onThisNetwork(config.url) ? { livenessEveryMs: livenessEveryMs() } : {}),reasoning: true,billing: "metered",includeUsageInCompleted: true,