Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Support reasoning effort for OpenAI-compatible models
reisen-wwecdb29827d85
diff --git a/apps/docs/content/docs/providers/model-providers.mdx b/apps/docs/content/docs/providers/model-providers.mdxindex 4593f895e9..fe6533ba75 100644--- a/apps/docs/content/docs/providers/model-providers.mdx+++ b/apps/docs/content/docs/providers/model-providers.mdx@@ -120,8 +120,28 @@ To use more than one provider at once, add extra `openai-compat` engines toGive each one its own key. An engine without a key uses the key fromConnections and sends it to that engine's address.-With an OpenAI key or OpenRouter, a model that reasons gets a thinking control-in the picker: Low, Medium or High. Leave it unset for the model's default.+The model picker shows the reasoning levels an endpoint advertises. For other+OpenAI-compatible models that don't list levels, it offers Low, Medium, High, Xhigh and+Max as manual choices. They are compatibility options, not a guarantee the+provider accepts them. With the control unset, the initial request sends no+level and uses the provider's default. If the provider requires reasoning to be+disabled for tools, the existing compatibility fallback may retry with reasoning+off. When an explicit choice is rejected or marked unsupported, the turn reports+an error rather than silently using another level.++When adding an `openai-compat` engine in `config.json`, you can override the+listed levels in that engine's `config` object, for example:++```json+{+ "reasoningEfforts": { "vendor/model": ["low", "medium", "high", "max"] }+}+```++When a catalog is read, its explicit declaration that a model does not support+reasoning takes precedence over this list. A fixed `managedModels` list keeps+its existing behavior and does not fetch a catalog. Refresh the models after a+provider changes its catalog.### Free OpenRouter modelsdiff --git a/server/drivers/compat-reasoning.test.ts b/server/drivers/compat-reasoning.test.tsnew file mode 100644index 0000000000..95c1ba5727--- /dev/null+++ b/server/drivers/compat-reasoning.test.ts@@ -0,0 +1,217 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { recordEvents } from "../testing/events.ts";+import { advertisedReasoning, reasoningChoices } from "./compat-reasoning.ts";+import { OpenAICompatDriver } from "./openai-compat.ts";++const variants = (models: { options: Array<{ id: string; variants?: Array<{ id: string }> }> }, id: string) =>+ models.options.find((option) => option.id === id)?.variants?.map((choice) => choice.id);+const answer = () => new Response('data: {"choices":[{"index":0,"delta":{"content":"done"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n',+ { headers: { "content-type": "text/event-stream" } });++afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });++describe("OpenAI-compatible reasoning choices", () => {+ it("uses the advertised wire format over a provider's default", () => {+ const advertised = advertisedReasoning({ supported_parameters: ["reasoning_effort"], reasoning_efforts: ["max"] });+ expect(advertised?.wire).toBe("flat");+ expect(reasoningChoices({+ model: "model", catalog: { default: "model", options: [{ id: "model", label: "model" }] },+ metadata: new Map([["model", advertised!]]), manual: true, wire: "nested",+ })?.wire).toBe("flat");+ });++ it("discovers declared levels, hides explicit refusals, and offers choices to new unknown models", async () => {+ let rows: Record<string, unknown>[] = [+ { id: "vendor-a/known", effort: { supported_levels: ["low", "max", "future"] } },+ { id: "vendor-b/unknown" },+ { id: "vendor-c/no-reasoning", supports_reasoning_effort: false },+ ];+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ data: rows })));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-catalog", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY" },+ environment: { FIXTURE_KEY: "fixture" },+ });+ try {+ await instance.refreshModels?.();+ expect(instance.adapter.capabilities.modelVariants).toBe(true);+ expect(variants(instance.models, "vendor-a/known")).toEqual(["low", "max", "future"]);+ expect(variants(instance.models, "vendor-b/unknown")).toEqual(["low", "medium", "high", "xhigh", "max"]);+ expect(variants(instance.models, "vendor-c/no-reasoning")).toBeUndefined();+ rows = [{ id: "vendor-a/known" }, { id: "vendor-d/new" }];+ await instance.refreshModels?.();+ expect(variants(instance.models, "vendor-a/known")).toEqual(["low", "medium", "high", "xhigh", "max"]);+ expect(variants(instance.models, "vendor-d/new")).toEqual(["low", "medium", "high", "xhigh", "max"]);+ } finally { await instance.dispose(); }+ });++ it("keeps fixed model lists private and accepts only valid explicit overrides", async () => {+ const calls = vi.fn(async () => Response.json({ data: [{ id: "must-not-be-listed" }] }));+ vi.stubGlobal("fetch", calls);+ const declared = { "vendor/model": ["low", "xhigh", "max"] };+ const config = OpenAICompatDriver.decodeConfig({ url: "https://example.test/v1", key: "fixture", managedModels: ["vendor/model"], reasoningEfforts: declared });+ declared["vendor/model"] = ["changed"];+ expect(config.reasoningEfforts).toEqual({ "vendor/model": ["low", "xhigh", "max"] });+ for (const reasoningEfforts of [null, [], {}, { x: [] }, { x: ["max", "max"] }, { x: [3] }]) {+ expect(() => OpenAICompatDriver.decodeConfig({ reasoningEfforts })).toThrow(/reasoningEfforts/);+ }+ const instance = await OpenAICompatDriver.create({ instanceId: "fixed-models", displayName: "Fixture", enabled: true, config, environment: {} });+ try {+ await instance.refreshModels?.();+ expect(calls).not.toHaveBeenCalled();+ expect(instance.models.options.map((option) => option.id)).toEqual(["vendor/model"]);+ expect(variants(instance.models, "vendor/model")).toEqual(["low", "xhigh", "max"]);+ } finally { await instance.dispose(); }+ });++ it.each([+ ["flat", { id: "vendor/future" }, "reasoning_effort"],+ ["nested", { id: "vendor/future", supported_parameters: ["reasoning"], reasoning_efforts: ["low", "max"] }, "reasoning"],+ ])("sends the exact choice in the %s format, but omits it by default", async (_name, model, property) => {+ const bodies: Array<Record<string, any>> = [];+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return Response.json({ data: [model] });+ bodies.push(JSON.parse(String(init?.body)));+ return answer();+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-send", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY", tools: false },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ await instance.adapter.sendTurn({ threadId: "default", text: "hello", model: "vendor/future" });+ expect(await recorder.until((event) => event.type === "turn.completed" && event.threadId === "default")).toMatchObject({ ok: true });+ await instance.adapter.sendTurn({ threadId: "max", text: "hello", model: "vendor/future", variant: "max" });+ expect(await recorder.until((event) => event.type === "turn.completed" && event.threadId === "max")).toMatchObject({ ok: true });+ expect(bodies[0]).not.toHaveProperty("reasoning_effort");+ expect(bodies[0]).not.toHaveProperty("reasoning");+ expect(bodies[1]![property]).toEqual(property === "reasoning" ? { effort: "max" } : "max");+ } finally { recorder.stop(); await instance.dispose(); }+ });++ it("reports an unavailable selected level before sending a request", async () => {+ const bodies: unknown[] = [];+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return Response.json({ data: [{ id: "vendor/future", reasoning_efforts: ["low", "max"] }] });+ bodies.push(init?.body);+ return answer();+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-invalid", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY", tools: false },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ await instance.adapter.sendTurn({ threadId: "invalid", text: "hello", model: "vendor/future", variant: "xhigh" });+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: false });+ expect(recorder.events).toContainEqual(expect.objectContaining({ type: "runtime.error", message: expect.stringContaining("unavailable") }));+ expect(bodies).toEqual([]);+ } finally { recorder.stop(); await instance.dispose(); }+ });++ it("reports an endpoint rejection without retrying at a different level", async () => {+ const bodies: Array<Record<string, unknown>> = [];+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return Response.json({ data: [{ id: "vendor/future" }] });+ bodies.push(JSON.parse(String(init?.body)));+ return Response.json({ error: { message: "Unsupported reasoning_effort" } }, { status: 400 });+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-rejected", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY", tools: false },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ await instance.adapter.sendTurn({ threadId: "rejected", text: "hello", model: "vendor/future", variant: "max" });+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: false });+ expect(bodies).toHaveLength(1);+ expect(bodies[0]).toHaveProperty("reasoning_effort", "max");+ expect(recorder.events).toContainEqual(expect.objectContaining({ type: "runtime.error" }));+ } finally { recorder.stop(); await instance.dispose(); }+ });++ it("waits for initial model metadata before applying an explicit level", async () => {+ let release!: (response: Response) => void;+ const metadata = new Promise<Response>((resolve) => { release = resolve; });+ const bodies: Array<Record<string, unknown>> = [];+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return metadata;+ bodies.push(JSON.parse(String(init?.body)));+ return answer();+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-startup", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY", tools: false },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.adapter.sendTurn({ threadId: "startup", text: "hi", model: "vendor/future", variant: "future-level" });+ await recorder.until((event) => event.type === "turn.started");+ expect(bodies).toEqual([]);+ release(Response.json({ data: [{ id: "vendor/future", reasoning_efforts: ["future-level"] }] }));+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });+ expect(bodies[0]).toHaveProperty("reasoning_effort", "future-level");+ } finally { recorder.stop(); await instance.dispose(); }+ });++ it("can interrupt a turn while the initial model catalog is still loading", async () => {+ let release!: (response: Response) => void;+ const metadata = new Promise<Response>((resolve) => { release = resolve; });+ const bodies: unknown[] = [];+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return metadata;+ bodies.push(init?.body);+ return answer();+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-cancel-startup", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY", tools: false },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ const { turnId } = await instance.adapter.sendTurn({ threadId: "startup", text: "hi", model: "vendor/future", variant: "max" });+ await instance.adapter.interruptTurn("startup", turnId);+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: false, stopReason: "interrupted" });+ release(Response.json({ data: [{ id: "vendor/future" }] }));+ await instance.refreshModels?.();+ expect(bodies).toEqual([]);+ } finally { release(Response.json({ data: [] })); recorder.stop(); await instance.dispose(); }+ });++ it("keeps the selected effort on each round after a tool call", async () => {+ const bodies: Array<Record<string, any>> = [];+ const argumentsJson = JSON.stringify({ questions: [{ question: "Proceed?", options: [{ label: "Yes" }, { label: "No" }] }] });+ const call = { choices: [{ index: 0, delta: { tool_calls: [{ index: 0, id: "ask1", type: "function", function: { name: "ask_user", arguments: argumentsJson } }] } }] };+ vi.stubGlobal("fetch", vi.fn(async (url, init) => {+ if (String(url).endsWith("/models")) return Response.json({ data: [{ id: "vendor/future" }] });+ bodies.push(JSON.parse(String(init?.body)));+ if (bodies.length > 1) return answer();+ return new Response("data: " + JSON.stringify(call) + '\n\ndata: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n',+ { headers: { "content-type": "text/event-stream" } });+ }));+ const instance = await OpenAICompatDriver.create({+ instanceId: "reasoning-tool-round", displayName: "Fixture", enabled: true,+ config: { url: "https://example.test/v1", apiKeyEnv: "FIXTURE_KEY" },+ environment: { FIXTURE_KEY: "fixture" },+ });+ const recorder = recordEvents(instance.adapter);+ try {+ await instance.refreshModels?.();+ await instance.adapter.sendTurn({ threadId: "thread", text: "hi", model: "vendor/future", variant: "max" });+ const opened = await recorder.until((event) => event.type === "request.opened");+ expect(await instance.adapter.respondToRequest("thread", opened.requestId!, { behavior: "answer", message: "Yes" })).toBe("answered");+ expect(await recorder.until((event) => event.type === "turn.completed")).toMatchObject({ ok: true });+ expect(bodies).toHaveLength(2);+ expect(bodies.map((body) => body.reasoning_effort)).toEqual(["max", "max"]);+ } finally { recorder.stop(); await instance.dispose(); }+ }, 20_000);+});diff --git a/server/drivers/compat-reasoning.ts b/server/drivers/compat-reasoning.tsnew file mode 100644index 0000000000..d00a68da9c--- /dev/null+++ b/server/drivers/compat-reasoning.ts@@ -0,0 +1,123 @@+import { isModelVariant, type ModelCatalog, type ModelVariantOption } from "../contracts.ts";++export type ReasoningWire = "flat" | "nested";+export interface ReasoningChoices {+ choices: ModelVariantOption[];+ wire?: ReasoningWire;+ inferred?: boolean;+}++const MANUAL_CHOICES = ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id }));+const record = (value: unknown): Record<string, unknown> | undefined =>+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;++export async function waitForCatalog(loading: Promise<unknown>, signal: AbortSignal): Promise<void> {+ signal.throwIfAborted();+ let cancel!: () => void;+ const stopped = new Promise<never>((_resolve, reject) => {+ cancel = () => reject(signal.reason);+ signal.addEventListener("abort", cancel, { once: true });+ });+ try { await Promise.race([loading, stopped]); }+ finally { signal.removeEventListener("abort", cancel); }+ signal.throwIfAborted();+}++function choices(value: unknown): ModelVariantOption[] | undefined {+ if (!Array.isArray(value) || value.length > 32) return undefined;+ const seen = new Set<string>();+ const result: ModelVariantOption[] = [];+ for (const item of value) {+ const entry = record(item);+ const id = typeof item === "string" ? item : entry?.value ?? entry?.id;+ if (!isModelVariant(id)) return undefined;+ if (seen.has(id)) continue;+ seen.add(id);+ const label = typeof entry?.label === "string" && entry.label.trim() && entry.label.length <= 256 ? entry.label : id;+ result.push({ id, label });+ }+ return result;+}++export function decodeReasoningEfforts(value: unknown): Record<string, string[]> | undefined {+ if (value === undefined) return undefined;+ const entries = Object.entries(record(value) ?? {});+ if (!entries.length || entries.length > 1024) throw new Error("reasoningEfforts must map 1 to 1024 model IDs to effort lists");+ for (const [model, levels] of entries) {+ const parsed = choices(levels);+ if (!model.trim() || model.length > 500 || !Array.isArray(levels) || !levels.length ||+ levels.some((level) => typeof level !== "string") || !parsed || parsed.length !== levels.length) {+ throw new Error("reasoningEfforts contains an invalid model ID or effort list");+ }+ }+ return Object.fromEntries(entries.map(([model, levels]) => [model, [...levels as string[]]]));+}++export function advertisedReasoning(row: Record<string, unknown>): ReasoningChoices | undefined {+ const caps = record(row.capabilities);+ if (row.supports_reasoning_effort === false || caps?.supports_reasoning === false || caps?.supports_reasoning_effort === false) {+ return { choices: [] };+ }+ const params = Array.isArray(row.supported_parameters) ? row.supported_parameters : undefined;+ const nested = params?.includes("reasoning") === true;+ const flat = params?.includes("reasoning_effort") === true;+ const wire = nested === flat ? undefined : nested ? "nested" : "flat";+ for (const value of [record(row.effort)?.supported_levels, row.reasoning_efforts, row.supported_reasoning_efforts, caps?.reasoning_effort, caps?.reasoning_efforts]) {+ const parsed = choices(value);+ if (parsed !== undefined) return { choices: parsed, wire };+ }+ if (params && !params.includes("reasoning") && !params.includes("reasoning_effort")) return { choices: [], wire };+ if (row.supports_reasoning_effort === true || caps?.supports_reasoning === true || params?.some((param) => param === "reasoning" || param === "reasoning_effort")) {+ return { choices: MANUAL_CHOICES, wire, inferred: true };+ }+ return undefined;+}++export function rememberReasoning(metadata: Map<string, ReasoningChoices>, rows: unknown[], normalize: (id: string) => string | null): void {+ for (const value of rows) {+ const row = record(value);+ if (typeof row?.id !== "string") continue;+ const id = normalize(row.id);+ if (!id) continue;+ const advertised = advertisedReasoning(row);+ if (advertised) metadata.set(id, advertised);+ else metadata.delete(id);+ }+}++export function reasoningChoices(input: {+ model: string;+ catalog: ModelCatalog;+ configured?: Record<string, string[]>;+ metadata: Map<string, ReasoningChoices>;+ manual: boolean;+ wire: ReasoningWire;+}): ReasoningChoices | undefined {+ const advertised = input.metadata.get(input.model);+ const wire = advertised?.wire ?? input.wire;+ if (advertised?.choices.length === 0) return { ...advertised, wire };+ if (input.configured && Object.hasOwn(input.configured, input.model)) {+ return { choices: input.configured[input.model].map((id) => ({ id, label: id })), wire };+ }+ if (advertised?.inferred && !input.manual && input.catalog.options.find((option) => option.id === input.model)?.variants !== undefined) return undefined;+ if (advertised) return { ...advertised, wire };+ if (input.catalog.options.find((option) => option.id === input.model)?.variants !== undefined) return undefined;+ return input.manual ? { choices: MANUAL_CHOICES, wire } : undefined;+}++export function reasoningCatalog(catalog: ModelCatalog, selection: (id: string) => ReasoningChoices | undefined): ModelCatalog {+ return { ...catalog, options: catalog.options.map((option) => {+ const selected = selection(option.id);+ if (!selected) return option;+ const { variants: _old, ...rest } = option;+ return selected.choices.length ? { ...rest, variants: selected.choices } : rest;+ }) };+}++export function reasoningBody(selected: ReasoningChoices | undefined, variant: string | undefined): Record<string, unknown> | undefined {+ if (!selected || !variant) return undefined;+ if (!selected.choices.some((choice) => choice.id === variant)) {+ throw new Error("Selected reasoning effort is unavailable for this model. Refresh models and choose a supported effort or use the provider default.");+ }+ return selected.wire === "nested" ? { reasoning: { effort: variant } } : { reasoning_effort: variant };+}diff --git a/server/drivers/ollama.test.ts b/server/drivers/ollama.test.tsindex 731c3a681b..dd008da5b1 100644--- a/server/drivers/ollama.test.ts+++ b/server/drivers/ollama.test.ts@@ -335,7 +335,10 @@ describe("the chat engine on Ollama", () => {const instance = await create({ url: `${url}/v1`, apiKeyEnv: "FIXTURE_KEY" }, { FIXTURE_KEY: "fixture-key" });try {await instance.refreshModels?.();- expect(instance.models.options).toEqual([{ id: "llama3.2:latest", label: "llama3.2:latest", custom: true }]);+ expect(instance.models.options).toEqual([{+ id: "llama3.2:latest", label: "llama3.2:latest", custom: true,+ variants: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })),+ }]);expect(await instance.snapshot()).toMatchObject({ state: "available" });expect(instanceLook({ driver: "openai-compat", displayName: "Local", config: { url: `${url}/v1` } })).toEqual({});} finally { await instance.dispose(); }diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.tsindex df0bdaa502..c7ea25c82c 100644--- a/server/drivers/openai-chat-tools.test.ts+++ b/server/drivers/openai-chat-tools.test.ts@@ -386,15 +386,19 @@ describe("a searched MCP catalog", () => {describe("approvals that follow the other engines", () => {it("runs OpenMausBot's own agents tools without a card, while a configured server's tool still asks", async () => {+ const auditReady = deferred();const f = await fixture((_body, response, round) => {- if (round === 1) sse(response, [chunk({ tool_calls: [toolCall("agents_write", '{"name":"peer","value":"sent"}', "call_agents")] }, "tool_calls")]);+ if (round === 1) void auditReady.promise.then(() => sse(response, [chunk({ tool_calls: [toolCall("agents_write", '{"name":"peer","value":"sent"}', "call_agents")] }, "tool_calls")]));else if (round === 2) sse(response, [chunk({ tool_calls: [toolCall("audit_write", '{"name":"receipt","value":"done"}', "call_audit")] }, "tool_calls")]);else answer(response);});const agents = f.integrations!.custom!.audit as NonNullable<SendTurnInput["integrations"]>["agents"];await f.start({ integrations: { ...f.integrations, agents } });+ await settledServer("audit");+ auditReady.resolve();const opened = await f.recorder.until((event) => event.type === "request.opened");expect(opened).toMatchObject({ requestType: "permission", tool: "audit_write" });+ expect(f.requests[1].tools?.map((tool) => tool.function.name)).toContain("audit_write");expect(f.effects()).toEqual([{ name: "peer", value: "sent" }]);await f.instance.adapter.respondToRequest(f.threadId, opened.requestId!, { behavior: "allow" });expect(await f.completed()).toMatchObject({ ok: true });diff --git a/server/drivers/openai-chat.ts b/server/drivers/openai-chat.tsindex cb3fde387f..1491e1533e 100644--- a/server/drivers/openai-chat.ts+++ b/server/drivers/openai-chat.ts@@ -24,7 +24,7 @@ import { ChatProtocolError, ChatReasoningDetails, ChatToolCalls, object, replayaimport { completionError, httpErrorDetail, refusedToolCall, refusedToolCallFailure, rejectsReasoningReplay, rejectsToolsParameter, RejectedToolCallError, StreamTruncatedError, UnsupportedChatToolsError, UnsupportedReasoningReplayError, type ProviderBody } from "./openai-chat-refusals.ts";import { ChatRepeatGuard } from "./chat-repeat-guard.ts";import { TextCallHoldback, textToolCalls } from "./chat-text-tool-calls.ts";-import { createModelRoutes, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, type ModelRoute, type ResponseItem } from "./openai-responses.ts";+import { createModelRoutes, ModelRouteRefused, noRouteLeft, readResponsesStream, responsesRequest, routeRefusal, selectedReasoningEffort, type ModelRoute, type ResponseItem } from "./openai-responses.ts";import { appendNative } from "./native.ts";import { classifyError, computeBackoff, interruptibleDelay, RETRY_MAX_ATTEMPTS } from "./retry.ts";import { plainFailure } from "./engine-errors.ts";@@ -37,7 +37,6 @@ import { classifyContinuable, writeTurnHandoff } from "../turn-continuation.ts";import { KEY_REJECTED_REASON, keyRejected, noteKeyAccepted, noteKeyRejected, rejectsKey } from "../key-rejections.ts";import { FETCH_LIMIT_MS, fetchPastLimit } from "./openai-chat-fetch.ts";import { announcesAction } from "./chat-announcement.ts";-export interface OpenAIChatMessage {role: "system" | "user" | "assistant" | "tool";content: string | ChatContentPart[] | null;@@ -52,7 +51,6 @@ interface Usage {input: number;output: number;}-export interface Completion {text: string;reasoning: string;@@ -92,6 +90,7 @@ interface RuntimeOptions<Config> {apiKey: string;apiUrl: string;models: () => ModelCatalog;+ prepareTurn?: (turn: SendTurnInput, signal: AbortSignal) => Promise<void> | undefined;requestBody(model: string, messages: OpenAIChatMessage[], stream: boolean, variant?: string, threadId?: string): Record<string, unknown>;httpErrorLabel: string;/** A refusal this provider words itself: the sentence the person sees instead of the HTTP line, or undefined. */@@ -278,10 +277,12 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>): timeoutController.signal;const served = options.servedModel ? await options.servedModel(model) : model;+ const requestBody = options.requestBody(served, messages, stream, variant, threadId);+ const effort = selectedReasoningEffort(requestBody, route, variant);const payload = JSON.stringify(route === "responses"- ? responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model), effort: options.requestBody(served, messages, stream, variant).reasoning_effort })+ ? responsesRequest({ model: served, messages, tools, replay: (message) => responseOutputs.get(message), summaries: routes.summaries(model), effort }): {- ...options.requestBody(served, messages, stream, variant, threadId),+ ...requestBody,...(route === "chat-reasoning-off" ? (options.reasoningOffBody?.(served) ?? { reasoning_effort: "none" }) : {}),...(tools.length ? { tools } : {}),});@@ -523,7 +524,7 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const request = messages.at(-1)!;const retainImages = chatImageBudget();for (const message of messages) retainImages(message.content);- const model = turn.model || options.models().default;+ let model = turn.model || options.models().default;const maskable = (value: unknown): value is string => typeof value === "string" && value.length >= 8; // a short placeholder key ("1") would redact every matchconst secrets = [options.apiKey].filter(maskable);for (const integration of Object.values(turn.integrations ?? {})) {@@ -580,7 +581,6 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const turnEntry = { abort, turnId, done, approval, asides: [] as string[], ending: false };active.set(turn.threadId, turnEntry);emit({ ...base(turn.threadId, turnId), type: "turn.started" });- emit({ ...base(turn.threadId, turnId), type: "session.started", sessionId: null, model });void (async () => {let tools: ChatToolSession | undefined;@@ -601,6 +601,13 @@ export function createOpenAIChatRuntime<Config>(options: RuntimeOptions<Config>)const repeats = options.localModel ? new ChatRepeatGuard() : undefined;let unreadable = false, askedAgain = false;try {+ const preparation = options.prepareTurn?.(turn, abort.signal);+ if (preparation) {+ await preparation;+ abort.signal.throwIfAborted();+ model = turn.model || options.models().default;+ }+ emit({ ...base(turn.threadId, turnId), type: "session.started", sessionId: null, model });const parsed = parseToolScope(turn.toolScope);if (!parsed.ok) throw new Error(parsed.error);const scope = parsed.scope;diff --git a/server/drivers/openai-compat-reasoning.test.ts b/server/drivers/openai-compat-reasoning.test.tsindex 5fd0e918a4..6beb38afd8 100644--- a/server/drivers/openai-compat-reasoning.test.ts+++ b/server/drivers/openai-compat-reasoning.test.ts@@ -36,8 +36,9 @@ async function turn(instance: ProviderInstance, model: string, variant?: string)const recorder = recordEvents(instance.adapter);const threadId = randomUUID();await instance.adapter.sendTurn({ threadId, text: "hi", model, ...(variant ? { variant } : {}) });- await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);+ const completed = await recorder.until((event) => event.type === "turn.completed" && event.threadId === threadId);recorder.stop();+ return completed;}const variantsOf = (instance: ProviderInstance) => Object.fromEntries(instance.models.options.map((option) => [option.id, option.variants?.map((choice) => choice.id)]));@@ -56,8 +57,9 @@ describe("reasoning effort on an API key", () => {});await turn(instance, "gpt-5.2", "low");await turn(instance, "gpt-5.2");- await turn(instance, "gpt-4.1", "low");- expect(chats.map((chat) => chat.reasoning_effort)).toEqual(["low", undefined, undefined]);+ expect(await turn(instance, "gpt-4.1", "low")).toMatchObject({ ok: false });+ expect(await turn(instance, "gpt-5.2", "max")).toMatchObject({ ok: false });+ expect(chats.map((chat) => chat.reasoning_effort)).toEqual(["low", undefined]);} finally { await instance.dispose(); }});@@ -66,22 +68,24 @@ describe("reasoning effort on an API key", () => {const instance = await create({ url: "https://openrouter.ai/api/v1" });try {expect(instance.adapter.capabilities.modelVariants).toBe(true);- expect(variantsOf(instance)).toMatchObject({ "acme/thinker": ["low", "medium", "high"], "acme/plain": undefined });+ expect(variantsOf(instance)).toMatchObject({ "acme/thinker": ["low", "medium", "high", "xhigh", "max"], "acme/plain": undefined });await turn(instance, "acme/thinker", "high");- await turn(instance, "acme/plain", "high");- expect(chats.map((chat) => chat.reasoning)).toEqual([{ effort: "high" }, undefined]);+ await turn(instance, "acme/thinker", "max");+ expect(await turn(instance, "acme/thinker", "ultra")).toMatchObject({ ok: false });+ expect(await turn(instance, "acme/plain", "high")).toMatchObject({ ok: false });+ expect(chats.map((chat) => chat.reasoning)).toEqual([{ effort: "high" }, { effort: "max" }]);expect(chats.every((chat) => chat.reasoning_effort === undefined)).toBe(true);} finally { await instance.dispose(); }});- it("sends nothing to any other server, and offers it no control", async () => {+ it("offers a compatible server the advertised control and sends its nested field", async () => {const chats = server([{ id: "gpt-5.2", supported_parameters: ["reasoning"] }]);const instance = await create({ url: "https://llm.example.test/v1" });try {- expect(instance.adapter.capabilities.modelVariants).toBeUndefined();+ expect(instance.adapter.capabilities.modelVariants).toBe(true);await turn(instance, "gpt-5.2", "high");expect(chats[0]).not.toHaveProperty("reasoning_effort");- expect(chats[0]).not.toHaveProperty("reasoning");+ expect(chats[0]).toHaveProperty("reasoning", { effort: "high" });} finally { await instance.dispose(); }});});diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex f08f2d0f51..782726f0df 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -334,8 +334,8 @@ describe("OpenAICompatDriver", () => {expect(inst.models).toEqual({default: "vendor/model-a",options: [- { id: "vendor/model-a", label: "Model A", custom: true },- { id: "vendor/model-b", label: "vendor/model-b", custom: true },+ { id: "vendor/model-a", label: "Model A", custom: true, variants: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })) },+ { id: "vendor/model-b", label: "vendor/model-b", custom: true, variants: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })) },],});await inst.dispose();diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex e2dbe1ad23..a6149d6d7f 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -7,6 +7,7 @@ import { lmStudioV1Catalog } from "./local-inject.ts";import { isContextName, isOllama, pickedName, serveWithWindow } from "./ollama-context.ts";import { isOllamaServer, OLLAMA_PLACEHOLDER_KEY, ollamaOrigin, ollamaUnavailable, onOllamaPort, probeOllama, thinkingEffort, type OllamaModel, type OllamaStatus } from "./ollama.ts";import { createOpenAIChatRuntime } from "./openai-chat.ts";+import { decodeReasoningEfforts, reasoningBody, reasoningCatalog, reasoningChoices, rememberReasoning, waitForCatalog, type ReasoningChoices } from "./compat-reasoning.ts";import {freeDefault, freeFallbackCatalog, freeLabel, freeToolModels, freeToolsFirst, isOpenRouterOrigin, openRouterFreeTier,withOpenRouterTurns, type OpenRouterModelRow,@@ -98,6 +99,8 @@ export interface OpenAICompatConfig {model?: string;provider?: string;managedModels?: string[];+ /** Optional model-specific reasoning choices for endpoints that do not advertise them. */+ 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;}@@ -151,6 +154,7 @@ function loopbackLmStudioV1Url(baseUrl: string): string | null {function decodeConfig(raw: unknown): OpenAICompatConfig {const config = (raw ?? {}) as Record<string, unknown>;+ const reasoningEfforts = decodeReasoningEfforts(config.reasoningEfforts);if (config.tools !== undefined && typeof config.tools !== "boolean") throw new Error("tools must be a boolean");if (config.managedModels !== undefined && (!Array.isArray(config.managedModels) || !config.managedModels.length || config.managedModels.some(model => typeof model !== "string" || !model.trim()))) throw new Error("Invalid managed models.");const ownKey = typeof config.apiKeyEnv === "string" && OWN_KEY_ENVS.has(config.apiKeyEnv);@@ -160,6 +164,7 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {return {...(config.tools !== undefined ? { tools: config.tools as boolean } : {}),...(config.managedModels ? { managedModels: config.managedModels as string[] } : {}),+ ...(reasoningEfforts ? { reasoningEfforts } : {}),...(isReplyWait(config.replyWaitMinutes) ? { replyWaitMinutes: config.replyWaitMinutes } : {}),url: (typeof config.url === "string" && config.url ? config.url : envUrl || "https://openrouter.ai/api/v1").replace(/\/+$/, ""),@@ -230,6 +235,12 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {const freeTier = () => openRouter ? openRouterFreeTier(apiKey, config.url) : Promise.resolve(null);const facts = new Map<string, OllamaModel>();+ const reasoningMetadata = new Map<string, ReasoningChoices>();+ const reasoningFor = (model: string) => reasoningChoices({+ model, catalog, metadata: reasoningMetadata, configured: config.reasoningEfforts,+ manual: config.catalog !== "openai" && !isOllamaServer(config),+ wire: isOpenRouterOrigin(config.url) ? "nested" : "flat",+ });const fact = (model: string) => facts.get(model) ?? facts.get(`${model}:latest`);let ollama: { at: number; status: Promise<OllamaStatus> } | null = null;const checkOllama = () => {@@ -256,7 +267,13 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {const takesEffort = (id: string, row: OpenRouterModelRow) => config.catalog === "openai" ? OPENAI_REASONING.test(id): openRouter && Array.isArray(row.supported_parameters) && row.supported_parameters.includes("reasoning");const apiEffort = (model: string, variant: string | undefined) => {- if (!variant || !catalog.options.find((option) => option.id === model)?.variants?.some((choice) => choice.id === variant)) return {};+ const explicit = reasoningBody(reasoningFor(model), variant);+ if (explicit) return explicit;+ if (!variant) return {};+ if (!catalog.options.find((option) => option.id === model)?.variants?.some((choice) => choice.id === variant)) {+ if (config.catalog === "openai" || openRouter) throw new Error("Selected reasoning effort is unavailable for this model. Refresh models and choose a supported effort or use the provider default.");+ return {};+ }return config.catalog === "openai" ? { reasoning_effort: variant } : openRouter ? { reasoning: { effort: variant } } : {};};@@ -304,6 +321,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {type Row = OpenRouterModelRow & Record<string, unknown> & { name?: unknown; created?: unknown; owned_by?: unknown };const json = await response.json() as { data?: Row[] } | Row[];let rows = Array.isArray(json) ? json : Array.isArray(json.data) ? json.data : [];+ rememberReasoning(reasoningMetadata, rows, (id) => gemini ? geminiChatModelId(id) : id);// OpenAI lists its catalog unordered and mixed with non-chat models.if (config.catalog === "openai") {rows = rows@@ -379,7 +397,8 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {tools: config.tools,computerUse: true,nudgeAnnouncedAction: true,- models: () => catalog,+ models: () => reasoningCatalog(catalog, reasoningFor),+ prepareTurn: (turn, signal) => loading && (turn.variant || isOllamaServer(config)) ? waitForCatalog(loading, signal) : undefined,refreshModels: fetchModels,imageInput: (model) => fact(model)?.vision ?? true,toolUse: (model) => fact(model)?.tools ?? true,@@ -391,7 +410,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {return reason ? { reason, ollama: { state: status.state, url: status.url, ...(status.problem ? { problem: status.problem } : {}) } } : null;},} : {}),- modelVariants: ollamaCandidate || config.catalog === "openai" || openRouter,+ modelVariants: true,requestBody: (model, messages, stream, variant, threadId) => ({model,messages,@@ -427,10 +446,6 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {}),},});- if (loading && isOllamaServer(config)) {- const send = runtime.adapter.sendTurn;- runtime.adapter.sendTurn = async (turn) => { await loading; return send(turn); };- }return openRouter && loading ? withOpenRouterTurns(runtime, loading) : runtime;},};diff --git a/server/drivers/openai-responses.test.ts b/server/drivers/openai-responses.test.tsindex c4c8876cd5..183e0a444f 100644--- a/server/drivers/openai-responses.test.ts+++ b/server/drivers/openai-responses.test.ts@@ -261,6 +261,17 @@ describe("a model that refuses tools over Chat Completions, at OpenAI's address"expect(f.calls[2]!.body.reasoning).toEqual({ summary: "auto" });});+ it("keeps a nested reasoning level when the request moves to Responses", async () => {+ const f = await fixture((call, response) => {+ if (call.path.endsWith("/chat/completions")) reject(response, 400, refusalOf(MODEL));+ else answer(response);+ }, OPENAI, [{ id: MODEL, supported_parameters: ["reasoning"], reasoning_efforts: ["max"] }]);+ await f.instance.refreshModels?.();+ expect(await f.turn({ variant: "max" })).toMatchObject({ end: { ok: true } });+ expect(f.calls[0]!.body.reasoning).toEqual({ effort: "max" });+ expect(f.calls[1]!.body.reasoning).toEqual({ effort: "max", summary: "auto" });+ });+it("leaves a model that accepts tools on Chat Completions", async () => {const f = await fixture((_call, response) => {response.writeHead(200, { "content-type": "text/event-stream" });@@ -607,6 +618,16 @@ describe("the fallback when Responses is not an option", () => {});describe("the same refusal from another provider", () => {+ it("reports a refusal rather than silently switching a selected effort off", async () => {+ const f = await fixture((_call, response) => reject(response, 400, refusalOf(MODEL)), "relay", [{ id: MODEL }]);+ await f.instance.refreshModels?.();+ const { end, events: seen } = await f.turn({ variant: "max" });+ expect(end).toMatchObject({ ok: false });+ expect(f.paths()).toEqual(["/v1/chat/completions"]);+ expect(f.calls[0]!.body.reasoning_effort).toBe("max");+ expect(failureOf(seen)).toContain("selected effort was not changed");+ });+it("stays on Chat Completions with reasoning off, and remembers per model", async () => {const f = await fixture((call, response) => {if (call.body.reasoning_effort !== "none") return reject(response, 400, refusalOf(MODEL));diff --git a/server/drivers/openai-responses.ts b/server/drivers/openai-responses.tsindex ebed66822c..12af226f0b 100644--- a/server/drivers/openai-responses.ts+++ b/server/drivers/openai-responses.ts@@ -12,6 +12,14 @@ export type ResponseItem = Record<string, unknown>;export type ModelRoute = "chat" | "responses" | "chat-reasoning-off";export type RouteRefusal = "tools-need-responses" | "responses-unavailable" | "summaries-refused";+export function selectedReasoningEffort(body: Record<string, unknown>, route: ModelRoute, variant?: string): unknown {+ const effort = body.reasoning_effort ?? object(body.reasoning)?.effort;+ if (route === "chat-reasoning-off" && variant && effort !== undefined && effort !== "none") {+ throw new ChatProtocolError("This endpoint requires disabling reasoning to use tools. Your selected effort was not changed; use the provider default or choose another endpoint.");+ }+ return effort;+}+export class ModelRouteRefused extends Error {readonly refusal: RouteRefusal;constructor(refusal: RouteRefusal, message: string) {diff --git a/server/openai-compat-reasoning.e2e.test.ts b/server/openai-compat-reasoning.e2e.test.tsnew file mode 100644index 0000000000..3f6b9d82db--- /dev/null+++ b/server/openai-compat-reasoning.e2e.test.ts@@ -0,0 +1,99 @@+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";+import { launchVerificationServer, runControlOmb, verificationServerEnvironment } from "../scripts/control-omb.ts";+import { waitForExit } from "./testing/cleanup.ts";++it("retains a custom API's selected reasoning level and sends it after restart", async () => {+ const rows: Array<Record<string, unknown>> = [{ id: "fixture/future", reasoning_efforts: ["low", "high", "xhigh", "max"] }];+ const bodies: Array<Record<string, any>> = [];+ const provider = createServer(async (request, response) => {+ if (request.url === "/v1/models") {+ response.writeHead(200, { "content-type": "application/json" });+ response.end(JSON.stringify({ data: rows }));+ return;+ }+ if (request.url !== "/v1/chat/completions" || request.method !== "POST") {+ response.writeHead(404).end();+ return;+ }+ let body = "";+ for await (const part of request) body += part.toString();+ bodies.push(JSON.parse(body));+ response.writeHead(200, { "content-type": "text/event-stream" });+ response.end('data: {"choices":[{"index":0,"delta":{"content":"Done."},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n');+ });+ await new Promise<void>((resolve) => provider.listen(0, "127.0.0.1", resolve));+ const address = provider.address();+ if (!address || typeof address === "string") throw new Error("fixture did not bind TCP");+ const fixture = await launchVerificationServer();+ const { dataDir, url, logPath } = fixture.info;+ let restarted: ChildProcess | undefined;+ const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": "application/json", origin: url },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(30_000),+ });+ const result = await response.json() as any;+ expect(response.ok, method + " " + path + ": " + JSON.stringify(result)).toBe(true);+ return result;+ };+ const control = (...args: string[]) => runControlOmb([...args, "--url", url]) as Promise<any>;+ const restart = async () => {+ await waitForExit(restarted ?? fixture.child, { signal: "SIGTERM" });+ const log = openSync(logPath, "a", 0o600);+ restarted = spawn(process.execPath, ["--experimental-strip-types", fileURLToPath(new URL("./index.ts", import.meta.url))], {+ cwd: fileURLToPath(new URL("..", import.meta.url)),+ env: verificationServerEnvironment({}, dataDir, Number(new URL(url).port)), stdio: ["ignore", log, log],+ });+ closeSync(log);+ await expect.poll(async () => {+ try { return (await fetch(url + "/api/health", { signal: AbortSignal.timeout(1_000) })).ok; } catch { return false; }+ }, { timeout: 25_000 }).toBe(true);+ };+ try {+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const configPath = join(dataDir, "config.json");+ const config = JSON.parse(readFileSync(configPath, "utf8"));+ config.instances.compatFixture = {+ driver: "openai-compat", displayName: "Compatible fixture",+ config: { url: "http://127.0.0.1:" + address.port + "/v1", key: "fixture-key", tools: false },+ };+ writeFileSync(configPath, JSON.stringify(config));+ await restart();+ const refreshed = await api("POST", "/api/instances/compatFixture/refresh-models", {});+ const engine = refreshed.instances.find((entry: any) => entry.instanceId === "compatFixture");+ expect(engine.capabilities.modelVariants).toBe(true);+ expect(engine.models.options.find((option: any) => option.id === "fixture/future").variants.map((variant: any) => variant.id))+ .toEqual(["low", "high", "xhigh", "max"]);+ const created = (await control("new-bot", "--name", "Compatible reasoning fixture")).bot;+ const threadId = created.activeTaskId ?? created.threadId;+ const selection = { instanceId: "compatFixture", model: "fixture/future", variant: "max" };+ await api("PATCH", "/api/bots/" + created.id + "/tasks/" + threadId, { modelSelection: selection, updateBotDefault: true, requireAvailableModel: true });+ expect((await control("send", "--bot", created.id, "--task", threadId, "--text", "Fixture selection check.")).success).toBe(true);+ expect((await control("wait", "--bot", created.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");+ expect(bodies.some((body) => body.model === "fixture/future" && body.reasoning_effort === "max")).toBe(true);++ await restart();+ const saved = (await api("GET", "/api/bots")).bots.find((bot: any) => bot.id === created.id);+ expect(saved.modelSelection).toEqual(selection);+ expect(saved.tasks.find((task: any) => task.threadId === threadId).modelSelection).toEqual(selection);+ rows.push({ id: "another/new-model" });+ const afterRestart = await api("POST", "/api/instances/compatFixture/refresh-models", {});+ const newModel = afterRestart.instances.find((entry: any) => entry.instanceId === "compatFixture")+ .models.options.find((option: any) => option.id === "another/new-model");+ expect(newModel.variants.map((variant: any) => variant.id)).toEqual(["low", "medium", "high", "xhigh", "max"]);+ const before = bodies.length;+ expect((await control("send", "--bot", created.id, "--task", threadId, "--text", "Check after restart.")).success).toBe(true);+ expect((await control("wait", "--bot", created.id, "--task", threadId, "--timeout", "30")).status).toBe("settled");+ expect(bodies.slice(before).some((body) => body.model === "fixture/future" && body.reasoning_effort === "max")).toBe(true);+ } finally {+ await waitForExit(restarted, { signal: "SIGTERM" });+ await fixture.close();+ provider.closeAllConnections();+ await new Promise<void>((resolve) => provider.close(() => resolve()));+ }+}, 120_000);