Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

refactor(llm): single source of truth for provider/model request params — dialects, matrix tests, fail-soft, live canary (#1620)

Gabriel Stein961a1b6933c2
diff --git a/.github/workflows/llm-canary.yml b/.github/workflows/llm-canary.yml
new file mode 100644
index 000000000..9b2bf6633
--- /dev/null
+++ b/.github/workflows/llm-canary.yml
@@ -0,0 +1,54 @@
+# Weekly live check that every LLM provider still accepts the exact request
+# shapes the app sends (reasoning params, token-limit param, temperature), plus
+# a model-catalog drift diff. Deliberately NOT part of PR CI: it exercises
+# external APIs and their failures are provider news, not code regressions.
+name: llm-canary
+
+on:
+ schedule:
+ - cron: "0 6 * * 1" # Mondays 06:00 UTC
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ issues: write
+
+jobs:
+ canary:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - name: Run canary
+ id: canary
+ env:
+ LLM_CANARY_OPENAI_KEY: ${{ secrets.LLM_CANARY_OPENAI_KEY }}
+ LLM_CANARY_GROQ_KEY: ${{ secrets.LLM_CANARY_GROQ_KEY }}
+ LLM_CANARY_TINFOIL_KEY: ${{ secrets.LLM_CANARY_TINFOIL_KEY }}
+ LLM_CANARY_GEMINI_KEY: ${{ secrets.LLM_CANARY_GEMINI_KEY }}
+ LLM_CANARY_OPENROUTER_KEY: ${{ secrets.LLM_CANARY_OPENROUTER_KEY }}
+ LLM_CANARY_MISTRAL_KEY: ${{ secrets.LLM_CANARY_MISTRAL_KEY }}
+ LLM_CANARY_DEEPSEEK_KEY: ${{ secrets.LLM_CANARY_DEEPSEEK_KEY }}
+ LLM_CANARY_CEREBRAS_KEY: ${{ secrets.LLM_CANARY_CEREBRAS_KEY }}
+ run: |
+ set -o pipefail
+ node --import tsx scripts/llm-canary.mjs | tee canary-report.md
+ - name: File or update failure issue
+ if: failure() && steps.canary.outcome == 'failure'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ title="LLM canary: provider request-shape check failing"
+ body="$(cat canary-report.md)
+
+ _Run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}_"
+ existing=$(gh issue list --label llm-canary --state open --json number --jq '.[0].number // empty')
+ if [ -n "$existing" ]; then
+ gh issue comment "$existing" --body "$body"
+ else
+ gh issue create --title "$title" --body "$body" --label llm-canary
+ fi
diff --git a/scripts/llm-canary.mjs b/scripts/llm-canary.mjs
new file mode 100644
index 000000000..51a3c8919
--- /dev/null
+++ b/scripts/llm-canary.mjs
@@ -0,0 +1,185 @@
+/**
+ * Live LLM request-shape canary. Sends a ~1-token request per provider ×
+ * constrained model family using the app's REAL shaping code, so a provider
+ * rejecting one of our shaped params (reasoning_effort, chat_template_kwargs,
+ * thinking, temperature, token param) surfaces here on a schedule instead of
+ * in a customer report (#990, #844, #1260, #1417, #1611). Also diffs each
+ * provider's live /models catalog against modelRegistryData.json: a vanished
+ * pinned id or a new member of a constrained family is exactly the drift that
+ * caused Tinfoil+gpt-oss to break unnoticed.
+ *
+ * Run: node --import tsx scripts/llm-canary.mjs
+ * Keys come from LLM_CANARY_<PROVIDER>_KEY env vars; providers without a key
+ * are skipped and listed. Exit 1 when any probe on a keyed provider fails.
+ */
+import { applyChatCompletionsParams } from "../src/services/ai/chatRequestBody.ts";
+import registryData from "../src/models/modelRegistryData.json" with { type: "json" };
+
+const CONSTRAINED_FAMILY = /gpt-oss|qwen|magistral/i;
+
+const PROVIDERS = [
+ {
+ id: "openai",
+ keyEnv: "LLM_CANARY_OPENAI_KEY",
+ base: "https://api.openai.com/v1",
+ models: ["gpt-4o-mini", "gpt-5-mini"],
+ },
+ {
+ id: "groq",
+ keyEnv: "LLM_CANARY_GROQ_KEY",
+ base: "https://api.groq.com/openai/v1",
+ models: ["openai/gpt-oss-120b", "qwen/qwen3-32b", "llama-3.3-70b-versatile"],
+ },
+ {
+ id: "tinfoil",
+ keyEnv: "LLM_CANARY_TINFOIL_KEY",
+ base: "https://inference.tinfoil.sh/v1",
+ models: ["gpt-oss-120b", "deepseek-v4-flash", "llama3-3-70b"],
+ },
+ {
+ id: "gemini",
+ keyEnv: "LLM_CANARY_GEMINI_KEY",
+ base: "https://generativelanguage.googleapis.com/v1beta/openai",
+ models: ["gemini-3-flash-preview"],
+ },
+ {
+ id: "openrouter",
+ keyEnv: "LLM_CANARY_OPENROUTER_KEY",
+ base: "https://openrouter.ai/api/v1",
+ models: ["openai/gpt-4o-mini", "anthropic/claude-haiku-4-5"],
+ skipCatalogDiff: true, // thousands of ids; registry pins none of them
+ },
+ {
+ id: "custom", // endpoint dialects ride the custom provider
+ label: "mistral",
+ keyEnv: "LLM_CANARY_MISTRAL_KEY",
+ base: "https://api.mistral.ai/v1",
+ models: ["mistral-small-latest", "magistral-small-latest"],
+ skipCatalogDiff: true,
+ },
+ {
+ id: "custom",
+ label: "deepseek",
+ keyEnv: "LLM_CANARY_DEEPSEEK_KEY",
+ base: "https://api.deepseek.com/v1",
+ models: ["deepseek-chat"],
+ skipCatalogDiff: true,
+ },
+ {
+ id: "custom",
+ label: "cerebras",
+ keyEnv: "LLM_CANARY_CEREBRAS_KEY",
+ base: "https://api.cerebras.ai/v1",
+ models: ["gpt-oss-120b"],
+ skipCatalogDiff: true,
+ },
+];
+
+const registryIdsByProvider = new Map(
+ registryData.cloudProviders.map((p) => [p.id, p.models.map((m) => m.id)])
+);
+
+function buildProbeBody(model, provider, endpoint) {
+ const body = {
+ model,
+ messages: [
+ { role: "system", content: "You are a health check." },
+ { role: "user", content: "Reply with OK." },
+ ],
+ };
+ // disableThinking exercises the suppression dialect — the shape that has
+ // historically 400'd; maxTokens floor keeps thinking families from needing
+ // room to reason before emitting content.
+ applyChatCompletionsParams(body, {
+ model,
+ provider,
+ endpoint,
+ config: { systemPrompt: "You are a health check.", disableThinking: true },
+ maxTokens: 256,
+ });
+ return body;
+}
+
+async function probe(entry, model, apiKey) {
+ const body = buildProbeBody(model, entry.id, entry.base);
+ const res = await fetch(`${entry.base}/chat/completions`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(60_000),
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ return { ok: false, detail: `HTTP ${res.status}: ${text.slice(0, 300)}` };
+ }
+ const content = JSON.parse(text)?.choices?.[0]?.message?.content;
+ if (!content || !content.trim()) {
+ return { ok: false, detail: `2xx but empty content: ${text.slice(0, 300)}` };
+ }
+ return { ok: true };
+}
+
+async function catalogDiff(entry, apiKey) {
+ const res = await fetch(`${entry.base}/models`, {
+ headers: { Authorization: `Bearer ${apiKey}` },
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!res.ok) return { error: `models list HTTP ${res.status}` };
+ const live = ((await res.json())?.data ?? []).map((m) => m.id).filter(Boolean);
+ const pinned = registryIdsByProvider.get(entry.id) ?? [];
+ const vanished = pinned.filter((id) => !live.includes(id));
+ const probed = new Set(entry.models);
+ const newConstrained = live.filter((id) => CONSTRAINED_FAMILY.test(id) && !probed.has(id));
+ return { vanished, newConstrained };
+}
+
+const report = [];
+const failures = [];
+const skipped = [];
+
+for (const entry of PROVIDERS) {
+ const label = entry.label ?? entry.id;
+ const apiKey = process.env[entry.keyEnv];
+ if (!apiKey) {
+ skipped.push(label);
+ continue;
+ }
+
+ for (const model of entry.models) {
+ const result = await probe(entry, model, apiKey).catch((err) => ({
+ ok: false,
+ detail: err.message,
+ }));
+ const line = `| ${label} | ${model} | ${result.ok ? "✅" : `❌ ${result.detail}`} |`;
+ report.push(line);
+ if (!result.ok) failures.push(`${label}/${model}: ${result.detail}`);
+ }
+
+ if (!entry.skipCatalogDiff) {
+ const diff = await catalogDiff(entry, apiKey).catch((err) => ({ error: err.message }));
+ if (diff.error) {
+ report.push(`| ${label} | _catalog_ | ⚠️ ${diff.error} |`);
+ } else {
+ if (diff.vanished.length) {
+ report.push(`| ${label} | _catalog_ | ⚠️ registry ids missing live: ${diff.vanished.join(", ")} |`);
+ failures.push(`${label}: registry ids vanished from live catalog: ${diff.vanished.join(", ")}`);
+ }
+ if (diff.newConstrained.length) {
+ report.push(
+ `| ${label} | _catalog_ | ℹ️ unprobed constrained-family ids: ${diff.newConstrained.slice(0, 10).join(", ")} |`
+ );
+ }
+ }
+ }
+}
+
+console.log("## LLM request-shape canary\n");
+console.log("| provider | model | result |\n|---|---|---|");
+for (const line of report) console.log(line);
+if (skipped.length) console.log(`\nSkipped (no key configured): ${skipped.join(", ")}`);
+if (failures.length) {
+ console.log(`\n### ${failures.length} failure(s)\n`);
+ for (const f of failures) console.log(`- ${f}`);
+ process.exit(1);
+}
+console.log("\nAll probes passed.");
diff --git a/src/models/ModelRegistry.ts b/src/models/ModelRegistry.ts
index 57bc884c5..3a5efb30a 100644
--- a/src/models/ModelRegistry.ts
+++ b/src/models/ModelRegistry.ts
@@ -497,8 +497,12 @@ export function getOpenAiApiConfig(modelId: string, provider?: string): OpenAiAp
// OpenRouter's vendor-prefixed ids (openai/gpt-4o, anthropic/claude-…) speak
// standard Chat Completions. Scoped to the provider so vendor-prefixed ids on
// custom endpoints keep the request shape they had before OpenRouter landed.
+ // Sampling params pass through to the upstream vendor, so a model the
+ // registry knows rejects temperature (Claude Opus 4.7+, #1417) must keep it
+ // omitted here too — OpenRouter forwards the 400 rather than stripping it.
if (provider === "openrouter" && modelId.includes("/")) {
- return { tokenParam: "max_tokens", supportsTemperature: true };
+ const upstream = getCloudModel(modelId.slice(modelId.lastIndexOf("/") + 1));
+ return { tokenParam: "max_tokens", supportsTemperature: upstream?.supportsTemperature ?? true };
}
// Fallback for models not in the registry (custom model IDs, etc.)
diff --git a/src/models/modelRegistryData.json b/src/models/modelRegistryData.json
index f094fce20..753f6b1ff 100644
--- a/src/models/modelRegistryData.json
+++ b/src/models/modelRegistryData.json
@@ -475,6 +475,7 @@
"name": "Gemini 3.1 Pro",
"description": "Next-gen flagship model for complex reasoning",
"descriptionKey": "models.descriptions.cloud.gemini_gemini_3_1_pro_preview",
+ "supportsThinking": true,
"supportsVision": true
},
{
@@ -482,6 +483,7 @@
"name": "Gemini 3 Flash",
"description": "Ultra-fast, high-capability next-gen model",
"descriptionKey": "models.descriptions.cloud.gemini_gemini_3_flash_preview",
+ "supportsThinking": true,
"supportsVision": true
},
{
diff --git a/src/services/ReasoningService.ts b/src/services/ReasoningService.ts
index 774004a61..9b943f370 100644
--- a/src/services/ReasoningService.ts
+++ b/src/services/ReasoningService.ts
@@ -25,7 +25,12 @@ import {
resolveConfiguredOpenAIBase,
resolveSelfHostedOpenAIBase,
} from "./ai/openaiBase";
-import { applyThinkingSuppression } from "./ai/thinkingSuppression";
+import {
+ applyChatCompletionsParams,
+ fetchWithParamFallback,
+ isTruncatedFinishReason,
+} from "./ai/chatRequestBody";
+import { getModelFamilyConstraints } from "./ai/modelFamilyConstraints";
import { detectEndpointDialect } from "./ai/thinkingSuppressionDialects";
import { extractApiErrorMessage } from "./ai/apiErrorMessage";
import { clearTinfoilClientCache } from "./ai/tinfoilClient";
@@ -89,20 +94,9 @@ function assertAgentSessionAllowedByPolicy(provider: string, mode: InferenceMode
assertReasoningAllowedByPolicy(provider, mode);
}
-// Old Ollama/strict proxies reject the `reasoning` object; drop it and retry once.
-async function fetchWithReasoningFieldFallback(
- doFetch: () => Promise<Response>,
- requestBody: Record<string, unknown>,
- logEvent: string
-): Promise<Response> {
- let res = await doFetch();
- if (!res.ok && (res.status === 400 || res.status === 422) && requestBody.reasoning) {
- logger.logReasoning(logEvent, { status: res.status });
- delete requestBody.reasoning;
- void res.body?.cancel();
- res = await doFetch();
- }
- return res;
+function logParamFallback(logEvent: string) {
+ return (details: { status: number; stripped: string[] }) =>
+ logger.logReasoning(logEvent, details);
}
class ReasoningService extends BaseReasoningService {
@@ -288,11 +282,13 @@ class ReasoningService extends BaseReasoningService {
{ role: "user", content: userPrompt },
];
- const requestBody: any = {
+ const requestBody: any = { model, messages };
+ applyChatCompletionsParams(requestBody, {
model,
- messages,
- temperature: config.temperature ?? (isCleanup ? 0 : 0.3),
- max_tokens:
+ provider: providerName,
+ endpoint,
+ config,
+ maxTokens:
config.maxTokens ||
Math.max(
4096,
@@ -303,19 +299,7 @@ class ReasoningService extends BaseReasoningService {
TOKEN_LIMITS.TOKEN_MULTIPLIER
)
),
- };
-
- // gpt-oss defaults to medium reasoning effort; low cuts hidden reasoning
- // tokens (latency) and the tendency to answer the transcript instead of
- // cleaning it. Selection edits need it too: at higher efforts Groq's
- // gpt-oss can leave the whole reply in the reasoning channel and return
- // whitespace content, failing the edit. applyThinkingSuppression still
- // wins when thinking is disabled by the user.
- if ((isCleanup || config.requireCompleteOutput) && model.includes("gpt-oss")) {
- requestBody.reasoning_effort = "low";
- }
-
- applyThinkingSuppression(requestBody, model, providerName, config, endpoint);
+ });
logger.logReasoning(`${providerName.toUpperCase()}_REQUEST`, {
endpoint,
@@ -335,7 +319,7 @@ class ReasoningService extends BaseReasoningService {
headers["Authorization"] = `Bearer ${apiKey}`;
}
- const res = await fetchWithReasoningFieldFallback(
+ const res = await fetchWithParamFallback(
() =>
fetch(endpoint, {
method: "POST",
@@ -344,7 +328,7 @@ class ReasoningService extends BaseReasoningService {
signal: controller.signal,
}),
requestBody,
- `${providerName.toUpperCase()}_REASONING_FIELD_RETRY`
+ logParamFallback(`${providerName.toUpperCase()}_PARAM_FALLBACK`)
);
if (!res.ok) {
@@ -404,7 +388,7 @@ class ReasoningService extends BaseReasoningService {
}
const choice = response.choices[0];
- if (config.requireCompleteOutput && ["length", "max_tokens"].includes(choice?.finish_reason)) {
+ if (config.requireCompleteOutput && isTruncatedFinishReason(choice?.finish_reason)) {
throw new Error("Model output was truncated before the selection edit completed");
}
// Reasoning models leak <think> blocks into non-streamed output; strip them
@@ -571,29 +555,19 @@ class ReasoningService extends BaseReasoningService {
);
}
- // A known endpoint host knows its own request shape better than the model id does.
- const apiConfig = detectEndpointDialect(endpoint) ?? getOpenAiApiConfig(model, provider);
- const useOldTokenParam = isLocalProvider || isLanChat || provider === "groq";
-
const requestBody: Record<string, unknown> = {
model,
messages,
stream: true,
};
- const maxTokens = config.maxTokens || Math.max(4096, TOKEN_LIMITS.MAX_TOKENS);
-
- if (useOldTokenParam) {
- requestBody.temperature = config.temperature ?? 0.3;
- requestBody.max_tokens = maxTokens;
- } else {
- requestBody[apiConfig.tokenParam] = maxTokens;
- if (apiConfig.supportsTemperature) {
- requestBody.temperature = config.temperature ?? 0.3;
- }
- }
-
- applyThinkingSuppression(requestBody, model, isLanChat ? "lan" : provider, config, endpoint);
+ applyChatCompletionsParams(requestBody, {
+ model,
+ provider: isLanChat ? "lan" : isLocalProvider ? "local" : provider,
+ endpoint,
+ config,
+ maxTokens: config.maxTokens || Math.max(4096, TOKEN_LIMITS.MAX_TOKENS),
+ });
logger.logReasoning("AGENT_STREAM_REQUEST", {
endpoint,
@@ -617,7 +591,7 @@ class ReasoningService extends BaseReasoningService {
let response: Response;
try {
- response = await fetchWithReasoningFieldFallback(
+ response = await fetchWithParamFallback(
() =>
fetch(endpoint, {
method: "POST",
@@ -626,7 +600,7 @@ class ReasoningService extends BaseReasoningService {
signal: controller.signal,
}),
requestBody,
- "AGENT_STREAM_REASONING_FIELD_RETRY"
+ logParamFallback("AGENT_STREAM_PARAM_FALLBACK")
);
} catch (error) {
clearTimeout(timeoutId);
@@ -794,7 +768,15 @@ class ReasoningService extends BaseReasoningService {
provider === "groq" && (modelDef?.disableThinking || userSuppressesThinking);
const needsGeminiMinimalThinking = provider === "gemini" && userSuppressesThinking;
const providerOptions = {
- ...(needsGroqDisableThinking ? { groq: { reasoningEffort: "none" } } : {}),
+ // The effort value is a family fact: gpt-oss has no "none" (#1611).
+ ...(needsGroqDisableThinking
+ ? {
+ groq: {
+ reasoningEffort:
+ getModelFamilyConstraints(model)?.reasoningEffort?.suppressValue ?? "none",
+ },
+ }
+ : {}),
...(needsGeminiMinimalThinking
? { google: { thinkingConfig: { thinkingLevel: "minimal", includeThoughts: false } } }
: {}),
diff --git a/src/services/ai/chatRequestBody.ts b/src/services/ai/chatRequestBody.ts
new file mode 100644
index 000000000..940308c04
--- /dev/null
+++ b/src/services/ai/chatRequestBody.ts
@@ -0,0 +1,123 @@
+import type { ReasoningConfig } from "../BaseReasoningService";
+import { getOpenAiApiConfig } from "../../models/ModelRegistry";
+import { detectEndpointDialect } from "./thinkingSuppressionDialects";
+import { getModelFamilyConstraints } from "./modelFamilyConstraints";
+import { applyThinkingSuppression } from "./thinkingSuppression";
+
+/**
+ * Providers whose OpenAI-compat chat endpoints speak the legacy shape: always
+ * `max_tokens`, always `temperature`. Groq's registry entries carry no
+ * tokenParam and its ids don't match the OpenAI fallback heuristics; Tinfoil's
+ * catalog is dynamic (models outside the registry must not fall through to
+ * `max_completion_tokens`); local/lan are llama.cpp-style servers.
+ */
+const LEGACY_CHAT_COMPLETIONS_PROVIDERS = new Set(["local", "lan", "groq", "tinfoil", "corti"]);
+
+/**
+ * Single place that turns (model, provider, endpoint, config) into the
+ * parameter set of an OpenAI-compatible chat-completions body: token-limit
+ * param, temperature, family reasoning effort, and thinking suppression.
+ * Callers own `model`/`messages`/`stream`; this owns every tunable param, so
+ * a family or provider fact changed in the data tables reaches all transports
+ * at once instead of one call site at a time (#1611).
+ */
+export function applyChatCompletionsParams(
+ requestBody: Record<string, unknown>,
+ {
+ model,
+ provider,
+ endpoint,
+ config,
+ maxTokens,
+ }: {
+ model: string;
+ provider: string;
+ endpoint?: string | null;
+ config: ReasoningConfig;
+ maxTokens: number;
+ }
+): void {
+ const providerKey = provider.toLowerCase();
+ // No systemPrompt override means the default cleanup path: a deterministic
+ // transform, so zero temperature.
+ const defaultTemperature = config.systemPrompt ? 0.3 : 0;
+
+ if (LEGACY_CHAT_COMPLETIONS_PROVIDERS.has(providerKey)) {
+ requestBody.max_tokens = maxTokens;
+ requestBody.temperature = config.temperature ?? defaultTemperature;
+ } else {
+ // A known endpoint host knows its own request shape better than the model id does.
+ const apiConfig = detectEndpointDialect(endpoint) ?? getOpenAiApiConfig(model, providerKey);
+ requestBody[apiConfig.tokenParam] = maxTokens;
+ if (apiConfig.supportsTemperature) {
+ requestBody.temperature = config.temperature ?? defaultTemperature;
+ }
+ }
+
+ // Deterministic transforms (cleanup, selection edits) pin the family's
+ // preferred effort — see modelFamilyConstraints for the gpt-oss rationale.
+ // applyThinkingSuppression still wins when thinking is disabled by the user.
+ const familyEffort = getModelFamilyConstraints(model)?.reasoningEffort;
+ if (familyEffort?.cleanupValue && (!config.systemPrompt || config.requireCompleteOutput)) {
+ requestBody.reasoning_effort = familyEffort.cleanupValue;
+ }
+
+ applyThinkingSuppression(requestBody, model, provider, config, endpoint ?? undefined);
+}
+
+/** Finish reasons that mean the output hit the token cap, across providers. */
+export function isTruncatedFinishReason(reason: unknown): boolean {
+ return reason === "length" || reason === "max_tokens";
+}
+
+/**
+ * Shaped params a backend may reject by name with a 400/422. Only params this
+ * module's shaping layer added are strippable — never messages or model — so a
+ * retry degrades the request (model reasons when asked not to, default
+ * sampling) instead of failing it outright. The strip is logged loudly: a
+ * fallback that fires on every request is a dialect bug to fix, not a rescue.
+ */
+const STRIPPABLE_SHAPED_PARAMS = [
+ "reasoning_effort",
+ "chat_template_kwargs",
+ "thinking",
+ "think",
+ "temperature",
+] as const;
+
+/**
+ * Fetch with a bounded param-stripping ladder for 400/422 rejections.
+ * Rung 1 (blind): old Ollama/strict proxies reject the `reasoning` object
+ * without naming it — drop it and retry once. Rung 2 (named): strip exactly
+ * the shaped params the error body names and retry once. At most two retries;
+ * the caller must build the body inside `doFetch` so retries re-serialize.
+ */
+export async function fetchWithParamFallback(
+ doFetch: () => Promise<Response>,
+ requestBody: Record<string, unknown>,
+ logRejection: (details: { status: number; stripped: string[] }) => void
+): Promise<Response> {
+ let res = await doFetch();
+ if (res.ok || (res.status !== 400 && res.status !== 422)) return res;
+
+ if (requestBody.reasoning) {
+ logRejection({ status: res.status, stripped: ["reasoning"] });
+ delete requestBody.reasoning;
+ void res.body?.cancel();
+ res = await doFetch();
+ if (res.ok || (res.status !== 400 && res.status !== 422)) return res;
+ }
+
+ const errorText = await res
+ .clone()
+ .text()
+ .catch(() => "");
+ const named = STRIPPABLE_SHAPED_PARAMS.filter((p) => p in requestBody && errorText.includes(p));
+ if (named.length > 0) {
+ logRejection({ status: res.status, stripped: named });
+ for (const param of named) delete requestBody[param];
+ void res.body?.cancel();
+ res = await doFetch();
+ }
+ return res;
+}
diff --git a/src/services/ai/inferenceProviders/openai.ts b/src/services/ai/inferenceProviders/openai.ts
index 4eef5e0f8..8be68a03d 100644
--- a/src/services/ai/inferenceProviders/openai.ts
+++ b/src/services/ai/inferenceProviders/openai.ts
@@ -5,7 +5,11 @@ import { getSettings } from "../../../stores/settingsStore";
import { withRetry, createApiRetryStrategy, httpError } from "../../../utils/retry";
import logger from "../../../utils/logger";
import { canBorrowCleanupCustomKey, resolveConfiguredOpenAIBase } from "../openaiBase";
-import { applyThinkingSuppression } from "../thinkingSuppression";
+import {
+ applyChatCompletionsParams,
+ fetchWithParamFallback,
+ isTruncatedFinishReason,
+} from "../chatRequestBody";
import { detectEndpointDialect } from "../thinkingSuppressionDialects";
import { extractApiErrorMessage } from "../apiErrorMessage";
import { wrapCleanupTranscript } from "../../../config/prompts";
@@ -225,36 +229,42 @@ export const openaiProvider: InferenceProvider = {
)
);
- // A known endpoint host knows its own request shape better than the model id does.
- const apiConfig = dialect ?? getOpenAiApiConfig(model, resolvedProvider);
const requestBody: Record<string, unknown> = { model };
if (type === "responses") {
requestBody.input = buildMessages(type);
requestBody.store = false;
requestBody.max_output_tokens = maxTokens;
+ // A known endpoint host knows its own request shape better than the model id does.
+ const apiConfig = dialect ?? getOpenAiApiConfig(model, resolvedProvider);
+ if (apiConfig.supportsTemperature) {
+ requestBody.temperature = config.temperature ?? (config.systemPrompt ? 0.3 : 0);
+ }
} else {
requestBody.messages = buildMessages(type);
- requestBody[apiConfig.tokenParam] = maxTokens;
- if (!config.systemPrompt && model.includes("gpt-oss")) {
- requestBody.reasoning_effort = "low";
- }
- applyThinkingSuppression(requestBody, model, resolvedProvider, config, openAiBase);
- }
-
- if (apiConfig.supportsTemperature) {
- requestBody.temperature = config.temperature ?? (config.systemPrompt ? 0.3 : 0);
+ applyChatCompletionsParams(requestBody, {
+ model,
+ provider: resolvedProvider,
+ endpoint: openAiBase,
+ config,
+ maxTokens,
+ });
}
- const res = await fetch(endpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
- },
- body: JSON.stringify(requestBody),
- signal: controller.signal,
- });
+ const res = await fetchWithParamFallback(
+ () =>
+ fetch(endpoint, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
+ },
+ body: JSON.stringify(requestBody),
+ signal: controller.signal,
+ }),
+ requestBody,
+ (details) => logger.logReasoning("OPENAI_PARAM_FALLBACK", { endpoint, ...details })
+ );
if (!res.ok) {
const errorData = await res.json().catch(() => ({ error: res.statusText }));
@@ -309,9 +319,7 @@ export const openaiProvider: InferenceProvider = {
const responseIncomplete =
response?.status === "incomplete" ||
!!response?.incomplete_details ||
- response?.choices?.some((choice: any) =>
- ["length", "max_tokens"].includes(choice?.finish_reason)
- );
+ response?.choices?.some((choice: any) => isTruncatedFinishReason(choice?.finish_reason));
if (responseIncomplete) {
throw new Error("Model output was truncated before the selection edit completed");
}
diff --git a/src/services/ai/inferenceProviders/tinfoil.ts b/src/services/ai/inferenceProviders/tinfoil.ts
index 8fe7d0326..0efad49a8 100644
--- a/src/services/ai/inferenceProviders/tinfoil.ts
+++ b/src/services/ai/inferenceProviders/tinfoil.ts
@@ -2,7 +2,7 @@ import type { InferenceProvider } from "./types";
import { TOKEN_LIMITS } from "../../../config/constants";
import { withRetry, createApiRetryStrategy } from "../../../utils/retry";
import logger from "../../../utils/logger";
-import { applyThinkingSuppression } from "../thinkingSuppression";
+import { applyChatCompletionsParams, isTruncatedFinishReason } from "../chatRequestBody";
import { getTinfoilChatClient } from "../tinfoilClient";
import { wrapCleanupTranscript } from "../../../config/prompts";
@@ -37,14 +37,8 @@ export const tinfoilProvider: InferenceProvider = {
)
);
- const requestBody: Record<string, unknown> = {
- model,
- messages,
- max_tokens: maxTokens,
- temperature: config.temperature ?? (config.systemPrompt ? 0.3 : 0),
- };
-
- applyThinkingSuppression(requestBody, model, "tinfoil", config);
+ const requestBody: Record<string, unknown> = { model, messages };
+ applyChatCompletionsParams(requestBody, { model, provider: "tinfoil", config, maxTokens });
// 30s per attempt like sibling providers; SDK-internal retries off so
// withRetry stays the single retry layer.
@@ -65,9 +59,7 @@ export const tinfoilProvider: InferenceProvider = {
if (
config.requireCompleteOutput &&
- response.choices?.some((choice: any) =>
- ["length", "max_tokens"].includes(choice?.finish_reason)
- )
+ response.choices?.some((choice: any) => isTruncatedFinishReason(choice?.finish_reason))
) {
throw new Error("Model output was truncated before the selection edit completed");
}
diff --git a/src/services/ai/modelFamilyConstraints.ts b/src/services/ai/modelFamilyConstraints.ts
new file mode 100644
index 000000000..47102cb1b
--- /dev/null
+++ b/src/services/ai/modelFamilyConstraints.ts
@@ -0,0 +1,61 @@
+/**
+ * Request constraints that belong to a model family, independent of which
+ * provider serves it. Storing a family fact inside a provider branch is what
+ * broke Tinfoil gpt-oss (#1611: the "no reasoning off switch" rule lived under
+ * `providerKey === "groq"`, so every other provider sent the rejected "none").
+ * New family facts must land here, never in a provider conditional.
+ *
+ * Kept free of runtime imports so the table stays unit-testable on its own,
+ * like thinkingSuppressionDialects.
+ */
+export interface ModelFamilyConstraints {
+ family: "gpt-oss" | "qwen" | "magistral";
+ reasoningEffort?: {
+ /** Value that best approximates "thinking off" for reasoning_effort. */
+ suppressValue: string;
+ /**
+ * Effort for deterministic transforms (cleanup, selection edits). gpt-oss
+ * defaults to medium; low cuts hidden reasoning tokens (latency) and the
+ * tendency to answer the transcript instead of cleaning it. At higher
+ * efforts gpt-oss can leave the whole reply in the reasoning channel and
+ * return whitespace content, failing selection edits.
+ */
+ cleanupValue?: string;
+ };
+ /** Family reasons natively and may reject reasoning params outright. */
+ omitReasoningParams?: boolean;
+}
+
+const FAMILIES: Array<ModelFamilyConstraints & { match: RegExp }> = [
+ {
+ family: "gpt-oss",
+ match: /gpt-oss/,
+ // gpt-oss accepts low|medium|high only; it has no off switch. Confirmed
+ // live on Groq and Tinfoil (#1611): "none" is a 400 on both.
+ reasoningEffort: { suppressValue: "low", cleanupValue: "low" },
+ },
+ {
+ family: "qwen",
+ match: /qwen/,
+ // qwen3 accepts none|default only (Groq's enum; "none" is also what the
+ // generic dialect sends everywhere, so the fact is provider-agnostic).
+ reasoningEffort: { suppressValue: "none" },
+ },
+ {
+ family: "magistral",
+ match: /magistral/,
+ // Legacy magistral models reason natively and may reject reasoning_effort.
+ // Verified only against the Mistral API, so the mistral dialect is the
+ // sole consumer today — a canary run should confirm other hosts before
+ // the generic dialect honors it.
+ omitReasoningParams: true,
+ },
+];
+
+export function getModelFamilyConstraints(
+ model: string | null | undefined
+): ModelFamilyConstraints | null {
+ const id = (model || "").toLowerCase();
+ if (!id) return null;
+ return FAMILIES.find((f) => f.match.test(id)) ?? null;
+}
diff --git a/src/services/ai/thinkingSuppression.ts b/src/services/ai/thinkingSuppression.ts
index d65076ec3..21d181ddd 100644
--- a/src/services/ai/thinkingSuppression.ts
+++ b/src/services/ai/thinkingSuppression.ts
@@ -13,7 +13,9 @@ export function applyThinkingSuppression(
const providerKey = detectEndpointDialect(baseUrl)?.key ?? provider.toLowerCase();
const cloudModel = getCloudModel(model);
- if (cloudModel?.disableThinking && providerKey === "groq") {
+ // A registry model flagged disableThinking is force-suppressed on every
+ // provider — scoping this to one provider is the #1611 bug pattern.
+ if (cloudModel?.disableThinking) {
suppressThinking(requestBody, providerKey, model);
return;
}
diff --git a/src/services/ai/thinkingSuppressionDialects.ts b/src/services/ai/thinkingSuppressionDialects.ts
index 215607fc9..935d14d3f 100644
--- a/src/services/ai/thinkingSuppressionDialects.ts
+++ b/src/services/ai/thinkingSuppressionDialects.ts
@@ -1,9 +1,14 @@
+import { getModelFamilyConstraints } from "./modelFamilyConstraints";
+
/**
- * Per-provider dialects for turning a model's thinking off. Kept free of runtime
- * imports so the dialect table stays unit-testable on its own.
+ * Per-provider dialects for turning a model's thinking off. Model-family
+ * constraints (which reasoning_effort values a family accepts) come from
+ * modelFamilyConstraints; this module only knows how each provider wants the
+ * suppression expressed. Kept free of heavier runtime imports so the dialect
+ * table stays unit-testable on its own.
*/
export interface EndpointDialect {
- key: "mistral";
+ key: "mistral" | "deepseek" | "cerebras";
tokenParam: "max_tokens" | "max_completion_tokens";
supportsTemperature: boolean;
}
@@ -23,6 +28,12 @@ export function detectEndpointDialect(baseUrl: string | null | undefined): Endpo
if (host === "mistral.ai" || host.endsWith(".mistral.ai")) {
return { key: "mistral", tokenParam: "max_tokens", supportsTemperature: true };
}
+ if (host === "deepseek.com" || host.endsWith(".deepseek.com")) {
+ return { key: "deepseek", tokenParam: "max_tokens", supportsTemperature: true };
+ }
+ if (host === "cerebras.ai" || host.endsWith(".cerebras.ai")) {
+ return { key: "cerebras", tokenParam: "max_tokens", supportsTemperature: true };
+ }
return null;
}
@@ -32,10 +43,7 @@ export function suppressThinking(
providerKey: string,
model: string
): void {
- const modelFamily = (model || "").toLowerCase();
- // gpt-oss accepts low|medium|high only; it has no off switch. A property of the
- // model family, not the provider — Tinfoil 400s on "none" just like Groq would.
- const isGptOss = modelFamily.includes("gpt-oss");
+ const family = getModelFamilyConstraints(model);
if (providerKey === "gemini") {
requestBody.reasoning_effort = "minimal";
@@ -49,22 +57,27 @@ export function suppressThinking(
return;
}
- // Groq rejects unknown fields outright and takes a different reasoning_effort
- // enum per model family, so send nothing unless the family is known.
- if (providerKey === "groq") {
- if (modelFamily.includes("qwen")) {
- // qwen3 accepts none|default only.
- requestBody.reasoning_effort = "none";
- } else if (isGptOss) {
- requestBody.reasoning_effort = "low";
+ // Groq and Cerebras reject unknown fields outright (Cerebras 400s on
+ // chat_template_kwargs, #831) and take a per-family reasoning_effort enum,
+ // so send nothing unless the family is known.
+ if (providerKey === "groq" || providerKey === "cerebras") {
+ if (family?.reasoningEffort) {
+ requestBody.reasoning_effort = family.reasoningEffort.suppressValue;
}
return;
}
+ // DeepSeek's API rejects reasoning_effort "none" (its enum has no off value,
+ // #1260); thinking: {type} is its native switch. Family facts don't apply —
+ // deepseek models on other hosts (e.g. Tinfoil) accept the generic shape.
+ if (providerKey === "deepseek") {
+ requestBody.thinking = { type: "disabled" };
+ return;
+ }
+
// Mistral rejects unknown fields with a 422; reasoning_effort is its native switch.
if (providerKey === "mistral") {
- // Legacy magistral models reason natively and may reject reasoning_effort.
- if (modelFamily.includes("magistral")) return;
+ if (family?.omitReasoningParams) return;
requestBody.reasoning_effort = "none";
return;
}
@@ -76,7 +89,7 @@ export function suppressThinking(
// disables Ollama thinking; other backends drop it (flat reasoning_effort trips vLLM).
requestBody.reasoning = { effort: "none" };
} else {
- requestBody.reasoning_effort = isGptOss ? "low" : "none";
+ requestBody.reasoning_effort = family?.reasoningEffort?.suppressValue ?? "none";
}
requestBody.chat_template_kwargs = { enable_thinking: false };
}
diff --git a/test/helpers/thinkingSuppressionDialects.test.js b/test/helpers/thinkingSuppressionDialects.test.js
index 914ade218..aa0b5dd99 100644
--- a/test/helpers/thinkingSuppressionDialects.test.js
+++ b/test/helpers/thinkingSuppressionDialects.test.js
@@ -196,3 +196,29 @@ test("detectEndpointDialect returns null for unparseable or missing input", asyn
assert.equal(detectEndpointDialect(undefined), null);
assert.equal(detectEndpointDialect(null), null);
});
+
+test("deepseek hosts get the native thinking switch, never reasoning_effort (#1260)", async () => {
+ const { suppressThinking, detectEndpointDialect } = await load();
+
+ const dialect = detectEndpointDialect("https://api.deepseek.com/v1");
+ assert.deepEqual(dialect, { key: "deepseek", tokenParam: "max_tokens", supportsTemperature: true });
+
+ const body = {};
+ suppressThinking(body, "deepseek", "deepseek-chat");
+ assert.deepEqual(body, { thinking: { type: "disabled" } });
+});
+
+test("cerebras hosts are strict like groq: family effort only, no chat_template_kwargs (#831)", async () => {
+ const { suppressThinking, detectEndpointDialect } = await load();
+
+ const dialect = detectEndpointDialect("https://api.cerebras.ai/v1");
+ assert.equal(dialect?.key, "cerebras");
+
+ const gptOss = {};
+ suppressThinking(gptOss, "cerebras", "gpt-oss-120b");
+ assert.deepEqual(gptOss, { reasoning_effort: "low" });
+
+ const unknown = {};
+ suppressThinking(unknown, "cerebras", "llama-4-maverick");
+ assert.deepEqual(unknown, {});
+});
diff --git a/test/services/fetchWithParamFallback.test.js b/test/services/fetchWithParamFallback.test.js
new file mode 100644
index 000000000..8f243c3b5
--- /dev/null
+++ b/test/services/fetchWithParamFallback.test.js
@@ -0,0 +1,106 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/ai/chatRequestBody.ts");
+
+// Each spec is [status, body]; a fresh Response is minted per call because a
+// consumed body can't be re-read. The last spec repeats for later calls.
+function jsonResponse(status, body) {
+ return [status, body];
+}
+
+function fetcher(...specs) {
+ const calls = [];
+ const doFetch = () => {
+ calls.push(1);
+ const [status, body] = specs[Math.min(calls.length - 1, specs.length - 1)];
+ return Promise.resolve(new Response(JSON.stringify(body), { status }));
+ };
+ doFetch.count = () => calls.length;
+ return doFetch;
+}
+
+test("2xx passes through with a single attempt", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(jsonResponse(200, { ok: true }));
+ const body = { reasoning: { effort: "none" } };
+
+ const res = await fetchWithParamFallback(doFetch, body, () => assert.fail("no fallback"));
+ assert.equal(res.status, 200);
+ assert.equal(doFetch.count(), 1);
+ assert.ok(body.reasoning, "body untouched on success");
+});
+
+test("400 with a reasoning object strips it blind and retries (old Ollama proxies)", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(jsonResponse(400, { error: "bad request" }), jsonResponse(200, {}));
+ const body = { reasoning: { effort: "none" }, max_tokens: 10 };
+ const logged = [];
+
+ const res = await fetchWithParamFallback(doFetch, body, (d) => logged.push(d));
+ assert.equal(res.status, 200);
+ assert.equal(doFetch.count(), 2);
+ assert.ok(!("reasoning" in body));
+ assert.deepEqual(logged, [{ status: 400, stripped: ["reasoning"] }]);
+});
+
+test("400 naming a shaped param strips exactly that param and retries (#1611 class)", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(
+ jsonResponse(400, { error: "Harmony does not support reasoning_effort='none'" }),
+ jsonResponse(200, {})
+ );
+ const body = { reasoning_effort: "none", chat_template_kwargs: {}, max_tokens: 10 };
+ const logged = [];
+
+ const res = await fetchWithParamFallback(doFetch, body, (d) => logged.push(d));
+ assert.equal(res.status, 200);
+ assert.ok(!("reasoning_effort" in body));
+ assert.ok("chat_template_kwargs" in body, "unnamed params stay");
+ assert.ok("max_tokens" in body, "token cap is never stripped");
+ assert.deepEqual(logged, [{ status: 400, stripped: ["reasoning_effort"] }]);
+});
+
+test("422 naming temperature strips it (#1417 class)", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(
+ jsonResponse(422, { error: "`temperature` is deprecated for this model" }),
+ jsonResponse(200, {})
+ );
+ const body = { temperature: 0.3, max_tokens: 10 };
+
+ const res = await fetchWithParamFallback(doFetch, body, () => {});
+ assert.equal(res.status, 200);
+ assert.ok(!("temperature" in body));
+});
+
+test("400 naming nothing strippable returns the failure without retrying", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(jsonResponse(400, { error: "model not found" }));
+ const body = { max_tokens: 10 };
+
+ const res = await fetchWithParamFallback(doFetch, body, () => assert.fail("no fallback"));
+ assert.equal(res.status, 400);
+ assert.equal(doFetch.count(), 1);
+});
+
+test("the ladder is bounded: at most two retries even when everything fails", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(jsonResponse(400, { error: "reasoning_effort and thinking rejected" }));
+ const body = { reasoning: {}, reasoning_effort: "low", thinking: { type: "disabled" } };
+
+ const res = await fetchWithParamFallback(doFetch, body, () => {});
+ assert.equal(res.status, 400);
+ assert.equal(doFetch.count(), 3);
+});
+
+test("non-4xx server errors never trigger stripping", async () => {
+ const { fetchWithParamFallback } = await load();
+ const doFetch = fetcher(jsonResponse(500, { error: "reasoning_effort exploded" }));
+ const body = { reasoning_effort: "low" };
+
+ const res = await fetchWithParamFallback(doFetch, body, () => assert.fail("no fallback"));
+ assert.equal(res.status, 500);
+ assert.equal(doFetch.count(), 1);
+ assert.ok("reasoning_effort" in body);
+});
diff --git a/test/services/llmRequestShapeMatrix.test.js b/test/services/llmRequestShapeMatrix.test.js
new file mode 100644
index 000000000..2f40bb70e
--- /dev/null
+++ b/test/services/llmRequestShapeMatrix.test.js
@@ -0,0 +1,103 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+// Exhaustive provider × model-family snapshot of every tunable request param
+// the chat-completions shaping layer produces. Each row asserts the FULL param
+// set (presence and absence), so any change to a dialect, family constraint,
+// or registry capability flag shows up here as a reviewable one-line diff.
+// Rationale: #1611 shipped green because no test looked at the whole body a
+// given provider×model pair actually gets.
+
+const load = () => import("../../src/services/ai/chatRequestBody.ts");
+
+const MAX_TOKENS = 1000;
+const CLEANUP = {};
+const CLEANUP_NO_THINK = { disableThinking: true };
+const AGENT = { systemPrompt: "You are an agent." };
+const AGENT_NO_THINK = { systemPrompt: "You are an agent.", disableThinking: true };
+const SELECTION_EDIT = { systemPrompt: "Edit the selection.", requireCompleteOutput: true };
+
+// [description, provider, model, endpoint, config, expected params]
+const MATRIX = [
+ // --- Groq (strict: rejects unknown fields; per-family reasoning_effort enum) ---
+ ["groq gpt-oss cleanup pins the family's low effort", "Groq", "openai/gpt-oss-120b", null, CLEANUP,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "low" }],
+ ["groq gpt-oss suppression floors at low, never none (#990)", "Groq", "openai/gpt-oss-120b", null, CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "low" }],
+ ["groq qwen is registry-flagged disableThinking and always suppressed", "Groq", "qwen/qwen3-32b", null, CLEANUP,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "none" }],
+ ["groq unknown family gets no guessed reasoning params", "Groq", "llama-3.3-70b-versatile", null, CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0 }],
+
+ // --- Tinfoil (dynamic catalog: legacy shape for registry and unknown ids alike) ---
+ ["tinfoil gpt-oss cleanup pins low effort (same family fact as Groq)", "tinfoil", "gpt-oss-120b", null, CLEANUP,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "low" }],
+ ["tinfoil gpt-oss suppression sends low, not the rejected none (#1611)", "tinfoil", "gpt-oss-120b", null, CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "low", chat_template_kwargs: { enable_thinking: false } }],
+ ["tinfoil selection edits on gpt-oss also pin low effort", "tinfoil", "gpt-oss-120b", null, SELECTION_EDIT,
+ { max_tokens: MAX_TOKENS, temperature: 0.3, reasoning_effort: "low" }],
+ ["tinfoil model outside the registry keeps the legacy shape", "tinfoil", "deepseek-v4-flash", null, CLEANUP,
+ { max_tokens: MAX_TOKENS, temperature: 0 }],
+
+ // --- OpenAI / custom / OpenRouter (registry-driven shape) ---
+ ["openai legacy model keeps max_tokens and temperature", "openai", "gpt-4o", null, CLEANUP,
+ { max_tokens: MAX_TOKENS, temperature: 0 }],
+ ["openai gpt-5 family uses max_completion_tokens and omits temperature", "openai", "gpt-5-mini", null, CLEANUP,
+ { max_completion_tokens: MAX_TOKENS }],
+ ["openrouter vendor-prefixed id speaks plain chat completions", "openrouter", "openai/gpt-4o", null, AGENT,
+ { max_tokens: MAX_TOKENS, temperature: 0.3 }],
+ ["openrouter forwards sampling upstream: temperature-rejecting Claude omits it (#1417)", "openrouter", "anthropic/claude-sonnet-5", null, AGENT,
+ { max_tokens: MAX_TOKENS }],
+ ["openrouter suppression uses its native reasoning toggle", "openrouter", "openai/gpt-4o", null, AGENT_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0.3, reasoning: { enabled: false } }],
+
+ // --- Endpoint dialects (host beats provider and model id) ---
+ ["mistral host: max_tokens, temperature, no reasoning params on magistral", "custom", "magistral-small-latest", "https://api.mistral.ai/v1", CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0 }],
+ ["mistral host: reasoning_effort none is its native off switch (#844)", "custom", "mistral-small-latest", "https://api.mistral.ai/v1", CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning_effort: "none" }],
+ ["deepseek host: thinking object, never reasoning_effort none (#1260)", "custom", "deepseek-chat", "https://api.deepseek.com/v1", CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, thinking: { type: "disabled" } }],
+ ["cerebras host: strict like groq, no chat_template_kwargs (#831)", "custom", "gpt-oss-120b", "https://api.cerebras.ai/v1", AGENT_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0.3, reasoning_effort: "low" }],
+ ["cerebras host: unknown family gets no guessed reasoning params", "custom", "llama-4-maverick", "https://api.cerebras.ai/v1", AGENT_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0.3 }],
+
+ // --- Self-hosted ---
+ ["lan disables Ollama thinking via the nested reasoning object (#1021)", "lan", "qwen3.5:9b", null, CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, reasoning: { effort: "none" }, chat_template_kwargs: { enable_thinking: false } }],
+ ["local llama.cpp gets think false plus chat_template_kwargs (#783)", "local", "qwen3.5-4b-gguf", null, CLEANUP_NO_THINK,
+ { max_tokens: MAX_TOKENS, temperature: 0, think: false, chat_template_kwargs: { enable_thinking: false } }],
+
+ // --- Corti (registry max_tokens; legacy set keeps unknown ids stable) ---
+ ["corti keeps the legacy chat-completions shape", "Corti", "corti-s1", null, AGENT,
+ { max_tokens: MAX_TOKENS, temperature: 0.3 }],
+
+ // --- Gemini through its OpenAI-compat endpoint (agent streaming route) ---
+ ["gemini openai-compat: fallback config, no temperature param", "gemini", "gemini-3-flash-preview", null, AGENT,
+ { max_completion_tokens: MAX_TOKENS }],
+];
+
+for (const [name, provider, model, endpoint, config, expectedParams] of MATRIX) {
+ test(`matrix: ${name}`, async () => {
+ const { applyChatCompletionsParams } = await load();
+ const body = { model, messages: [] };
+ applyChatCompletionsParams(body, { model, provider, endpoint, config, maxTokens: MAX_TOKENS });
+
+ const { model: _m, messages: _msgs, ...params } = body;
+ assert.deepEqual(params, expectedParams);
+ });
+}
+
+test("matrix: explicit temperature and maxTokens overrides always win", async () => {
+ const { applyChatCompletionsParams } = await load();
+ const body = { model: "gpt-4o", messages: [] };
+ applyChatCompletionsParams(body, {
+ model: "gpt-4o",
+ provider: "openai",
+ config: { temperature: 0.7, maxTokens: 42 },
+ maxTokens: 42,
+ });
+ assert.equal(body.temperature, 0.7);
+ assert.equal(body.max_tokens, 42);
+});
diff --git a/test/services/modelFamilyConstraints.test.js b/test/services/modelFamilyConstraints.test.js
new file mode 100644
index 000000000..dca9b380a
--- /dev/null
+++ b/test/services/modelFamilyConstraints.test.js
@@ -0,0 +1,25 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const load = () => import("../../src/services/ai/modelFamilyConstraints.ts");
+
+test("family lookup matches anywhere in the id, case-insensitively", async () => {
+ const { getModelFamilyConstraints } = await load();
+ assert.equal(getModelFamilyConstraints("openai/GPT-OSS-120b")?.family, "gpt-oss");
+ assert.equal(getModelFamilyConstraints("gpt-oss-safeguard-120b")?.family, "gpt-oss");
+ assert.equal(getModelFamilyConstraints("qwen/qwen3-32b")?.family, "qwen");
+ assert.equal(getModelFamilyConstraints("magistral-small-latest")?.family, "magistral");
+});
+
+test("unknown, empty, and missing ids resolve to no constraints", async () => {
+ const { getModelFamilyConstraints } = await load();
+ assert.equal(getModelFamilyConstraints("gpt-4o"), null);
+ assert.equal(getModelFamilyConstraints(""), null);
+ assert.equal(getModelFamilyConstraints(undefined), null);
+});
+
+test("gpt-oss has no reasoning off switch: suppress and cleanup both floor at low", async () => {
+ const { getModelFamilyConstraints } = await load();
+ const effort = getModelFamilyConstraints("gpt-oss-120b")?.reasoningEffort;
+ assert.deepEqual(effort, { suppressValue: "low", cleanupValue: "low" });
+});