Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Assist: a registry of hosted LLM providers, and the adapters that call them

Adarsh29331966fab6
diff --git a/src/lib/catalog/llm-providers.ts b/src/lib/catalog/llm-providers.ts
new file mode 100644
index 00000000..949a7fea
--- /dev/null
+++ b/src/lib/catalog/llm-providers.ts
@@ -0,0 +1,820 @@
+import type { AssistEffort } from "../assist";
+
+/**
+ * The LLM providers Assist can plan with: their official hosts, how their wire differs from
+ * OpenAI's, and the models worth offering, with prices, context, tools, vision, open weights and
+ * free status. Pure data (no secrets, safe in the browser); src/lib/assist-models.ts ranks it and
+ * src/server/llm/hosted.ts calls it. Facts come from each provider's own docs, model and pricing pages
+ * (the `sources` of each entry), read on LLM_REGISTRY_CHECKED. Ids and prices change monthly:
+ * update this file (a data-only change) rather than code.
+ */
+export const LLM_REGISTRY_CHECKED = "2026-10-31";
+
+export type LlmAdapter = "anthropic" | "openai-chat" | "openai-responses" | "local";
+export type ProviderGroup = "labs" | "china" | "hosts" | "local";
+
+/** USD (or CNY) per 1M tokens. `until`: the last day this price applies (a dated change follows it). */
+export interface PriceStep {
+ until?: string;
+ in: number;
+ out: number;
+}
+
+/** A Fuobe effort → the value this model's API takes; null: the model doesn't offer that level. */
+export type EffortMap = Partial<Record<AssistEffort, string | null>>;
+
+export interface LlmModelDef {
+ /** The wire id, exactly as the provider's docs give it. */
+ id: string;
+ name: string;
+ /** 1: each maker's flagship reasoning model; 2: other flagships and strong mid models; 3: fast or cheap; 4: small. */
+ tier: 1 | 2 | 3 | 4;
+ speed: "fast" | "normal" | "slow";
+ /** Why Smart and Free never pick it (Manual still lists it). */
+ manualOnly?: string;
+ /** Tokens. */
+ context: number;
+ maxOut: number;
+ /** "unverified": the docs don't say it calls tools on this API, so Smart and Free skip it. */
+ tools: true | "unverified";
+ vision: boolean;
+ /** Pictures per request, where the provider caps it. */
+ maxImages?: number;
+ /** Open weights, with the licence the maker gives. Absent: closed, or the docs don't confirm it. */
+ open?: { licence: string; nonCommercial?: true };
+ price?: PriceStep[];
+ /** China regions are billed in CNY. */
+ priceCny?: PriceStep[];
+ /** Why there is no price (Cohere's page doesn't list one). */
+ priceNote?: string;
+ /** A price step inside a long chat. */
+ longContext?: { above: number; text: string };
+ /** "model": $0 on any key; "plan": free only while the provider's free-plan tick is on. */
+ free?: "model" | "plan";
+ efforts?: EffortMap;
+ status?: "preview";
+ /** The last day a free model is offered. */
+ expires?: string;
+ /** Assist has been run with it for real. */
+ tested?: true;
+ /** A host's copy of another provider's model ("zai/glm-5.3"): the maker's own API comes first. */
+ same?: string;
+ /** OpenRouter's Free Models Router: picks a random free model each time, so it always comes last. */
+ router?: true;
+ /** A longer wait than the provider's usual one (Gemini 4 Argon can think for minutes). */
+ timeoutMs?: number;
+ note?: string;
+}
+
+/** How a provider's Chat Completions wire differs from OpenAI's (read by src/server/llm/hosted.ts). */
+export interface Quirks {
+ /** Default max_completion_tokens. */
+ maxTokensField?: "max_tokens" | "max_completion_tokens";
+ /** "omit": the provider documents no tool_choice (MiniMax, Cohere). Default "auto". */
+ toolChoice?: "auto" | "omit";
+ /** "developer": the system prompt goes as role developer (Cohere). */
+ systemRole?: "system" | "developer";
+ /** Where the effort goes. Default reasoning_effort. */
+ effortField?: "reasoning_effort" | "reasoning.effort" | "thinking_budget" | "none";
+ /**
+ * "required": every earlier turn of this provider carries its reasoning back, or a request with tools is
+ * refused (DeepSeek). "preserve": sent back when there is some. Default: none sent back.
+ */
+ replayReasoning?: "required" | "preserve";
+ /** The key reasoning goes back under (Together answers with either, and wants the same one back). */
+ reasoningKey?: "reasoning_content" | "reasoning";
+ /** "flatten": tool calls other models made are sent as text (DeepSeek refuses calls it didn't make). */
+ foreignToolCalls?: "flatten";
+ /** Gemini's thought signatures on tool calls (extra_content). */
+ signatures?: "gemini";
+ /** "nine": tool-call ids of nine letters and digits (Mistral). */
+ toolIds?: "nine";
+ /** The image_url part as a plain string (Mistral's examples); default {url}. */
+ imageUrl?: "string";
+ /** Picture types the provider takes; others are sent as PNG. Default png, jpeg, webp and gif. */
+ imageTypes?: string[];
+ /** Fields every request carries. */
+ extraBody?: Record<string, unknown>;
+ headers?: Record<string, string>;
+ /** xAI: a header naming the chat, for cache hits. */
+ chatHeader?: string;
+ /** MiniMax answers some errors with HTTP 200 and base_resp.status_code. */
+ errorEnvelope?: "minimax";
+ /** Ask for usage on the stream (stream_options.include_usage). */
+ streamUsage?: true;
+ /** Output room cap: requests are charged their max tokens up front (Cerebras). */
+ maxOutCap?: number;
+ timeoutMs?: number;
+}
+
+export interface FreePlan {
+ /** "plan": free while the account is on the provider's free plan (the owner ticks it). "trial": credits that run out; never counted as free. */
+ kind: "plan" | "trial";
+ /** The tick, for plans. */
+ setting?: string;
+ limits: string;
+ caveat?: string;
+ /** Why the free plan can't run Assist (Groq: 8,000 tokens a minute). */
+ tooSmall?: string;
+}
+
+export interface Region {
+ id: string;
+ label: string;
+ /** Qwen's hosts carry the workspace id: {workspace}. */
+ baseUrl: string;
+ note?: string;
+ /** Prices here are in CNY. */
+ cny?: true;
+}
+
+export interface LlmProviderDef {
+ id: string;
+ label: string;
+ /** The provider's name in a sentence: "Google", "DeepSeek". */
+ short: string;
+ group: ProviderGroup;
+ adapter: LlmAdapter;
+ /** Official hosts only; the first is the default. */
+ regions?: Region[];
+ baseUrl?: string;
+ /** The Settings entry that holds the key (src/server/settings.ts). */
+ keySetting?: string;
+ regionSetting?: string;
+ workspaceSetting?: string;
+ /** What a key looks like, for Settings' hint. */
+ keyHint?: { pattern: string; text: string };
+ keysUrl?: string;
+ billingUrl?: string;
+ /** Lists its models at {base}/models with the key (a free call: Settings' Test). */
+ modelsPath?: string;
+ quirks: Quirks;
+ freePlan?: FreePlan;
+ /** Free models' account-wide limits (OpenRouter's :free cap covers every free model on the key). */
+ freeLimits?: { text: string; caveat?: string; shared?: true };
+ /** Not wired yet: shown greyed with this line. */
+ soon?: string;
+ models: LlmModelDef[];
+ sources: string[];
+}
+
+const EVERY: EffortMap = { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "max" };
+const LOW_MED_HIGH: EffortMap = { low: "low", medium: "medium", high: "high", xhigh: "high", max: "high" };
+/** Kimi K3 and GLM-5.3 take low, high and max. */
+const LOW_HIGH_MAX: EffortMap = { low: "low", medium: "high", high: "high", xhigh: "max", max: "max" };
+/** Mistral Small and Cohere's reasoning: thinking off or on. */
+const NONE_HIGH: EffortMap = { low: "none", medium: "high", high: "high", xhigh: "high", max: "high" };
+const usd = (inp: number, out: number, until?: string): PriceStep => ({ in: inp, out, ...(until && { until }) });
+
+const M = 1_000_000;
+/** OpenAI's price step: GPT-5.4 and later cost more for the whole message past 272K tokens. */
+const OPENAI_LONG = { above: 272_000, text: "Over 272K tokens: twice the input price and 1.5× the output price for the whole message" };
+/** Qwen takes a thinking budget in tokens; "" sends none (no limit). Fuobe's numbers: the docs set no levels. */
+const QWEN_BUDGET: EffortMap = { low: "2048", medium: "8192", high: "16384", xhigh: "32768", max: "" };
+/** The dummy thought signature Gemini's docs allow for tool calls another model made. */
+export const GEMINI_DUMMY_SIGNATURE = "skip_thought_signature_validator";
+
+export const LLM_PROVIDERS: LlmProviderDef[] = [
+ // -------------------------------------------------------------------------
+ // Big labs
+ {
+ id: "anthropic",
+ label: "Anthropic",
+ short: "Anthropic",
+ group: "labs",
+ adapter: "anthropic",
+ keySetting: "anthropicKey",
+ keyHint: { pattern: "^sk-ant-\\S+$", text: "Anthropic keys start with sk-ant-" },
+ keysUrl: "https://console.anthropic.com/settings/keys",
+ quirks: {},
+ // Opus's price is the repo's own note (src/lib/catalog/llm-models.ts); Sonnet, Haiku and Fable are OpenRouter's catalog figures.
+ models: [
+ { id: "claude-opus-5-5", name: "Claude Opus 5.5", tier: 1, speed: "normal", context: M, maxOut: 64_000, tools: true, vision: true, price: [usd(4, 20)], efforts: EVERY, tested: true },
+ { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5", tier: 2, speed: "normal", context: M, maxOut: 64_000, tools: true, vision: true, price: [usd(2, 10)], efforts: EVERY, tested: true },
+ { id: "claude-haiku-5-5", name: "Claude Haiku 5.5", tier: 3, speed: "fast", context: M, maxOut: 64_000, tools: true, vision: true, price: [usd(0.1, 0.5)], efforts: EVERY, tested: true },
+ { id: "claude-fable-5-1", name: "Claude Fable 5.1", tier: 1, speed: "slow", manualOnly: "Most capable, slowest, priciest", context: M, maxOut: 64_000, tools: true, vision: true, price: [usd(10, 50)], efforts: EVERY, tested: true },
+ ],
+ sources: ["https://openrouter.ai/api/v1/models"],
+ },
+ {
+ id: "openai",
+ label: "OpenAI",
+ short: "OpenAI",
+ group: "labs",
+ adapter: "openai-responses",
+ regions: [
+ { id: "global", label: "Global", baseUrl: "https://api.openai.com/v1" },
+ { id: "us", label: "United States", baseUrl: "https://us.api.openai.com/v1", note: "Data stays in the US: 10% more on models from 5 March 2026 on" },
+ { id: "eu", label: "Europe", baseUrl: "https://eu.api.openai.com/v1", note: "Data stays in the EU (needs an EU project): 10% more on models from 5 March 2026 on" },
+ ],
+ keySetting: "openaiKey",
+ regionSetting: "openaiRegion",
+ keyHint: { pattern: "^sk-\\S+$", text: "OpenAI keys start with sk-" },
+ keysUrl: "https://platform.openai.com/api-keys",
+ billingUrl: "https://platform.openai.com/settings/organization/billing",
+ modelsPath: "/models",
+ quirks: { timeoutMs: 1_200_000 },
+ models: [
+ { id: "gpt-6.1-sol", name: "GPT-6.1 Sol", tier: 1, speed: "normal", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(2, 10)], efforts: EVERY, longContext: OPENAI_LONG },
+ { id: "gpt-6.1-terra", name: "GPT-6.1 Terra", tier: 3, speed: "fast", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(1, 5)], efforts: EVERY, longContext: OPENAI_LONG, note: "Fast, with strong visual reasoning" },
+ { id: "gpt-6-luna", name: "GPT-6 Luna", tier: 3, speed: "fast", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(0.1, 0.5)], efforts: LOW_MED_HIGH, longContext: OPENAI_LONG, note: "OpenAI's cheapest" },
+ { id: "gpt-5.4-mini", name: "GPT-5.4 Mini", tier: 3, speed: "fast", context: 400_000, maxOut: 128_000, tools: true, vision: true, price: [usd(0.75, 4.5)], efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: null }, longContext: OPENAI_LONG },
+ { id: "gpt-6-astra", name: "GPT-6 Astra", tier: 1, speed: "slow", manualOnly: "Flagship; slowest and priciest", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(10, 50)], efforts: EVERY, longContext: OPENAI_LONG },
+ ],
+ sources: [
+ "https://developers.openai.com/api/docs/models.md",
+ "https://developers.openai.com/api/docs/pricing.md",
+ "https://developers.openai.com/api/docs/guides/migrate-to-responses.md",
+ "https://developers.openai.com/api/docs/guides/reasoning.md",
+ "https://developers.openai.com/api/docs/guides/streaming-responses.md",
+ ],
+ },
+ {
+ id: "google",
+ label: "Google Gemini",
+ short: "Google",
+ group: "labs",
+ adapter: "openai-chat",
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/openai",
+ keySetting: "googleKey",
+ keyHint: { pattern: "^AIza[\\w-]{20,}$", text: "Gemini API keys start with AIza" },
+ keysUrl: "https://aistudio.google.com/apikey",
+ billingUrl: "https://aistudio.google.com/usage",
+ modelsPath: "/models",
+ // Signatures on tool calls; never temperature; reasoning_effort only (never with thinking_config).
+ quirks: { maxTokensField: "max_tokens", signatures: "gemini", timeoutMs: 600_000 },
+ freePlan: {
+ kind: "plan",
+ setting: "googleFreeTier",
+ limits: "Limits per project, shown only in Google AI Studio; daily limits reset at midnight Pacific",
+ caveat: "Google uses free-tier prompts to improve its products.",
+ },
+ models: [
+ {
+ id: "gemini-4-argon",
+ name: "Gemini 4 Argon",
+ tier: 1,
+ speed: "slow",
+ context: 1_048_576,
+ maxOut: 65_536,
+ tools: true,
+ vision: true,
+ price: [usd(2, 10, "2026-11-30"), usd(4, 20)],
+ efforts: LOW_MED_HIGH,
+ timeoutMs: 1_200_000,
+ note: "Can take several minutes to answer",
+ },
+ { id: "gemini-3.8-flash", name: "Gemini 3.8 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, price: [usd(0.75, 3.75, "2026-12-31"), usd(1.5, 7.5)], free: "plan", efforts: LOW_MED_HIGH },
+ { id: "gemini-3.6-flash", name: "Gemini 3.6 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, price: [usd(0.75, 3.75, "2026-12-31"), usd(1.5, 7.5)], free: "plan", efforts: LOW_MED_HIGH },
+ { id: "gemini-3.5-flash-lite", name: "Gemini 3.5 Flash-Lite", tier: 3, speed: "fast", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, price: [usd(0.3, 2.5)], free: "plan", efforts: LOW_MED_HIGH },
+ { id: "gemini-3.1-flash-lite", name: "Gemini 3.1 Flash-Lite", tier: 3, speed: "fast", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, price: [usd(0.25, 1.5)], free: "plan", efforts: LOW_MED_HIGH, note: "Shuts down 7 May 2027" },
+ {
+ id: "gemini-3.1-pro-preview",
+ name: "Gemini 3.1 Pro (preview)",
+ tier: 2,
+ speed: "normal",
+ context: 1_048_576,
+ maxOut: 65_536,
+ tools: true,
+ vision: true,
+ price: [usd(2, 12)],
+ efforts: LOW_MED_HIGH,
+ status: "preview",
+ longContext: { above: 200_000, text: "Over 200K tokens: $4 in, $18 out per million tokens" },
+ },
+ { id: "gemma-4-31b-it", name: "Gemma 4 31B", tier: 3, speed: "normal", context: 262_144, maxOut: 32_768, tools: "unverified", vision: true, open: { licence: "Apache-2.0" }, free: "plan", note: "Free tier only; Google's docs don't say it calls tools here" },
+ ],
+ sources: [
+ "https://ai.google.dev/gemini-api/docs/openai",
+ "https://ai.google.dev/gemini-api/docs/pricing",
+ "https://ai.google.dev/gemini-api/docs/rate-limits",
+ "https://ai.google.dev/gemini-api/docs/thought-signatures",
+ "https://ai.google.dev/gemini-api/docs/models",
+ ],
+ },
+ {
+ id: "xai",
+ label: "xAI (Grok)",
+ short: "xAI",
+ group: "labs",
+ adapter: "openai-chat",
+ regions: [
+ { id: "global", label: "Global", baseUrl: "https://api.x.ai/v1" },
+ { id: "us", label: "United States", baseUrl: "https://us.api.x.ai/v1", note: "US only: 10% more, and only Grok 4.7 and 4.6" },
+ ],
+ keySetting: "xaiKey",
+ regionSetting: "xaiRegion",
+ keyHint: { pattern: "^xai-\\S+$", text: "xAI keys start with xai-" },
+ keysUrl: "https://console.x.ai",
+ modelsPath: "/models",
+ quirks: { imageTypes: ["image/jpeg", "image/png"], chatHeader: "x-grok-conv-id", timeoutMs: 1_200_000 },
+ models: [
+ {
+ id: "grok-4.7",
+ name: "Grok 4.7",
+ tier: 1,
+ speed: "normal",
+ context: 500_000,
+ maxOut: 128_000,
+ tools: true,
+ vision: true,
+ price: [usd(2, 6)],
+ efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "xhigh" },
+ longContext: { above: 200_000, text: "From 200K tokens on, every token costs twice as much ($4 in, $12 out per million)" },
+ },
+ { id: "grok-4.6", name: "Grok 4.6", tier: 2, speed: "normal", context: 500_000, maxOut: 128_000, tools: true, vision: true, price: [usd(2, 6)], efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "xhigh" } },
+ {
+ id: "grok-4.3",
+ name: "Grok 4.3",
+ tier: 3,
+ speed: "fast",
+ context: M,
+ maxOut: 128_000,
+ tools: true,
+ vision: true,
+ price: [usd(1.25, 2.5)],
+ efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "xhigh" },
+ longContext: { above: 200_000, text: "From 200K tokens on, every token costs twice as much" },
+ },
+ { id: "grok-4.20-0309-non-reasoning", name: "Grok 4.20 (no reasoning)", tier: 3, speed: "fast", context: M, maxOut: 128_000, tools: true, vision: true, price: [usd(1.25, 2.5)] },
+ ],
+ sources: ["https://docs.x.ai/docs/models", "https://docs.x.ai/docs/guides/function-calling", "https://docs.x.ai/docs/guides/reasoning"],
+ },
+ {
+ id: "meta",
+ label: "Meta (Muse)",
+ short: "Meta",
+ group: "labs",
+ adapter: "openai-chat",
+ baseUrl: "https://api.meta.ai/v1",
+ keySetting: "metaKey",
+ keyHint: { pattern: "^LLM_\\d+_\\S+$", text: "Meta Model API keys look like LLM_<number>_<secret>" },
+ keysUrl: "https://dev.meta.ai",
+ modelsPath: "/models",
+ quirks: { timeoutMs: 1_200_000 },
+ models: [
+ { id: "muse-spark-1.3", name: "Muse Spark 1.3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, price: [usd(1.25, 4.25)], efforts: EVERY },
+ {
+ id: "muse-spark-1.3-contributor",
+ name: "Muse Spark 1.3 (contributor)",
+ tier: 3,
+ speed: "normal",
+ context: 1_048_576,
+ maxOut: 131_072,
+ tools: true,
+ vision: true,
+ price: [usd(0.1, 0.2)],
+ efforts: { ...EVERY, max: "xhigh" },
+ note: "Meta may train on these chats",
+ },
+ { id: "muse-wonder-1.0", name: "Muse Wonder", tier: 1, speed: "normal", manualOnly: "Preview", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, price: [usd(4, 20)], efforts: EVERY, status: "preview" },
+ ],
+ sources: ["https://dev.meta.ai/docs/models", "https://dev.meta.ai/docs/protocols/chat-completions", "https://dev.meta.ai/docs/pricing-rate-limits"],
+ },
+ {
+ id: "mistral",
+ label: "Mistral",
+ short: "Mistral",
+ group: "labs",
+ adapter: "openai-chat",
+ baseUrl: "https://api.mistral.ai/v1",
+ keySetting: "mistralKey",
+ keysUrl: "https://admin.mistral.ai/organization/api-keys",
+ modelsPath: "/models",
+ quirks: { maxTokensField: "max_tokens", toolIds: "nine", imageUrl: "string", streamUsage: true },
+ freePlan: {
+ kind: "plan",
+ setting: "mistralFreePlan",
+ limits: "Monthly usage included; Mistral doesn't publish how much",
+ caveat: "Stops when it's used up (or bills, if pay-as-you-go is on).",
+ },
+ models: [
+ { id: "mistral-large-4", name: "Mistral Large 4", tier: 2, speed: "normal", context: M, maxOut: 32_768, tools: true, vision: true, open: { licence: "Mistral Ecosystem Open Weight Licence" }, price: [usd(0.7, 2.1)], free: "plan", efforts: LOW_MED_HIGH, status: "preview" },
+ { id: "mistral-small-2603", name: "Mistral Small 4", tier: 3, speed: "fast", context: 256_000, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.15, 0.6)], free: "plan", efforts: NONE_HIGH },
+ { id: "ministral-14b-2512", name: "Ministral 3 14B", tier: 4, speed: "fast", context: 256_000, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.2, 0.2)], free: "plan" },
+ { id: "zai-glm-5-3", name: "GLM-5.3 (on Mistral)", tier: 2, speed: "normal", context: M, maxOut: 128_000, tools: true, vision: false, open: { licence: "MIT" }, price: [usd(1.4, 4.4)], free: "plan", efforts: LOW_HIGH_MAX, same: "zai/glm-5.3" },
+ { id: "zai-glm-5-3-flash", name: "GLM-5.3 Flash (on Mistral)", tier: 3, speed: "fast", context: M, maxOut: 128_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.15, 0.5)], free: "plan", same: "zai/glm-5.3-flash" },
+ { id: "deepseek-v4-1-flash-1017", name: "DeepSeek V4.1 Flash (on Mistral)", tier: 3, speed: "fast", context: M, maxOut: 128_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.3, 1.2)], free: "plan", status: "preview", same: "deepseek/deepseek-flash" },
+ ],
+ sources: ["https://docs.mistral.ai/getting-started/models/", "https://mistral.ai/pricing", "https://docs.mistral.ai/capabilities/function_calling/", "https://docs.mistral.ai/deployment/laplateforme/tier/"],
+ },
+ {
+ id: "cohere",
+ label: "Cohere",
+ short: "Cohere",
+ group: "labs",
+ adapter: "openai-chat",
+ baseUrl: "https://api.cohere.ai/compatibility/v1",
+ keySetting: "cohereKey",
+ keysUrl: "https://dashboard.cohere.com/api-keys",
+ quirks: { maxTokensField: "max_tokens", toolChoice: "omit", systemRole: "developer" },
+ freePlan: { kind: "plan", setting: "cohereTrialKey", limits: "1,000 calls a month, 20 a minute", caveat: "Not for commercial use (Cohere's terms for trial keys)." },
+ models: [
+ {
+ id: "command-a-plus-05-2026",
+ name: "Command A+",
+ tier: 2,
+ speed: "normal",
+ context: 128_000,
+ maxOut: 64_000,
+ tools: true,
+ vision: true,
+ open: { licence: "Apache-2.0" },
+ price: [usd(2.5, 10)],
+ free: "plan",
+ efforts: NONE_HIGH,
+ note: "Self-serve keys are trial-limited (Cohere: contact sales)",
+ },
+ { id: "command-a-03-2025", name: "Command A", tier: 3, speed: "normal", context: 256_000, maxOut: 8_000, tools: true, vision: false, priceNote: "Cohere's price page doesn't list it", free: "plan" },
+ { id: "command-r7b-12-2024", name: "Command R7B", tier: 4, speed: "fast", context: 128_000, maxOut: 4_000, tools: true, vision: false, open: { licence: "CC-BY-NC-4.0", nonCommercial: true }, price: [usd(0.0375, 0.15)], free: "plan" },
+ ],
+ sources: ["https://docs.cohere.com/v2/docs/models.md", "https://docs.cohere.com/v2/docs/compatibility-api.md", "https://docs.cohere.com/v2/docs/rate-limits.md", "https://cohere.com/pricing"],
+ },
+ // -------------------------------------------------------------------------
+ // China
+ {
+ id: "deepseek",
+ label: "DeepSeek",
+ short: "DeepSeek",
+ group: "china",
+ adapter: "openai-chat",
+ baseUrl: "https://api.deepseek.com",
+ keySetting: "deepseekKey",
+ keyHint: { pattern: "^sk-\\S+$", text: "DeepSeek keys start with sk-" },
+ keysUrl: "https://platform.deepseek.com/api_keys",
+ billingUrl: "https://platform.deepseek.com/top_up",
+ modelsPath: "/models",
+ quirks: { maxTokensField: "max_tokens", replayReasoning: "required", foreignToolCalls: "flatten", extraBody: { thinking: { type: "enabled" } } },
+ models: [
+ {
+ id: "deepseek-v4-pro",
+ name: "DeepSeek V4 Pro",
+ tier: 2,
+ speed: "normal",
+ context: M,
+ maxOut: 384_000,
+ tools: true,
+ vision: false,
+ open: { licence: "MIT" },
+ price: [usd(1.32, 3.96)],
+ efforts: { low: "low", medium: "high", high: "high", xhigh: "high", max: "max" },
+ // Open weights: V4's (MIT); DeepSeek's docs don't say whether the 0813 update's weights are out.
+ note: "Half price off-peak",
+ },
+ { id: "deepseek-flash", name: "DeepSeek V4.1 Flash", tier: 3, speed: "fast", context: M, maxOut: 384_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.3, 1.2)], efforts: { low: "low", medium: "high", high: "high", xhigh: "high", max: "max" }, note: "Half price off-peak" },
+ ],
+ sources: ["https://api-docs.deepseek.com/quick_start/pricing", "https://api-docs.deepseek.com/guides/thinking_mode", "https://api-docs.deepseek.com/guides/function_calling"],
+ },
+ {
+ id: "moonshot",
+ label: "Kimi (Moonshot)",
+ short: "Kimi",
+ group: "china",
+ adapter: "openai-chat",
+ regions: [
+ { id: "international", label: "International", baseUrl: "https://api.moonshot.ai/v1" },
+ { id: "china", label: "China", baseUrl: "https://api.moonshot.cn/v1", cny: true, note: "Keys belong to the platform they were made on" },
+ ],
+ keySetting: "moonshotKey",
+ regionSetting: "moonshotRegion",
+ keyHint: { pattern: "^sk-\\S+$", text: "Kimi keys start with sk-" },
+ keysUrl: "https://platform.kimi.ai/console/api-keys",
+ modelsPath: "/models",
+ // Temperature, top_p, n and the penalties are fixed: Fuobe never sends them.
+ quirks: { replayReasoning: "preserve" },
+ models: [
+ { id: "kimi-k3.1-pro", name: "Kimi K3.1 Pro", tier: 1, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, price: [usd(2, 10)], priceCny: [usd(13, 68)], efforts: LOW_HIGH_MAX, note: "Open weights promised by 4 Nov" },
+ {
+ id: "kimi-k3.1-pro-highspeed",
+ name: "Kimi K3.1 Pro Highspeed",
+ tier: 1,
+ speed: "fast",
+ manualOnly: "The same model as K3.1 Pro, 2–3× faster, at twice the price",
+ context: 1_048_576,
+ maxOut: 131_072,
+ tools: true,
+ vision: true,
+ price: [usd(4, 20)],
+ priceCny: [usd(26, 136)],
+ efforts: LOW_HIGH_MAX,
+ },
+ { id: "kimi-k3", name: "Kimi K3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Kimi licence (other)" }, price: [usd(3, 15)], priceCny: [usd(20, 100)], efforts: LOW_HIGH_MAX },
+ ],
+ sources: ["https://platform.kimi.ai/docs/models", "https://platform.kimi.ai/docs/pricing/chat", "https://platform.kimi.ai/docs/guide/use-reasoning-effort", "https://platform.kimi.com/docs/pricing/chat"],
+ },
+ {
+ id: "zai",
+ label: "Z.ai (GLM)",
+ short: "Z.ai",
+ group: "china",
+ adapter: "openai-chat",
+ regions: [
+ { id: "international", label: "International (Z.ai)", baseUrl: "https://api.z.ai/api/paas/v4" },
+ { id: "china", label: "China (BigModel)", baseUrl: "https://open.bigmodel.cn/api/paas/v4", cny: true },
+ ],
+ keySetting: "zaiKey",
+ regionSetting: "zaiRegion",
+ keysUrl: "https://z.ai/manage-apikey/apikey-list",
+ quirks: { maxTokensField: "max_tokens", replayReasoning: "preserve" },
+ freeLimits: { text: "Free per token; limits only in Z.ai's console" },
+ models: [
+ { id: "glm-5.3", name: "GLM-5.3", tier: 2, speed: "normal", context: M, maxOut: 128_000, tools: true, vision: false, open: { licence: "GLM licence (other)" }, price: [usd(1.4, 4.4)], priceCny: [usd(8, 28)], efforts: LOW_HIGH_MAX },
+ { id: "glm-5.3-flash", name: "GLM-5.3 Flash", tier: 3, speed: "fast", context: M, maxOut: 128_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.15, 0.5)], priceCny: [usd(0.8, 2.8)], efforts: LOW_HIGH_MAX },
+ { id: "glm-5.3-flashx", name: "GLM-5.3 FlashX", tier: 3, speed: "fast", context: M, maxOut: 128_000, tools: true, vision: true, price: [usd(0.37, 1.25)], priceCny: [usd(2, 7)], efforts: LOW_HIGH_MAX },
+ { id: "glm-4.7-flash", name: "GLM-4.7 Flash", tier: 4, speed: "fast", context: 200_000, maxOut: 128_000, tools: true, vision: false, open: { licence: "MIT" }, free: "model" },
+ { id: "glm-4.6v-flash", name: "GLM-4.6V Flash", tier: 4, speed: "fast", context: 128_000, maxOut: 32_000, tools: true, vision: true, open: { licence: "MIT" }, free: "model" },
+ ],
+ sources: ["https://docs.z.ai/guides/overview/pricing", "https://docs.z.ai/api-reference/llm/chat-completion", "https://docs.bigmodel.cn/cn/guide/start/model-overview"],
+ },
+ {
+ id: "qwen",
+ label: "Qwen (Alibaba Model Studio)",
+ short: "Qwen",
+ group: "china",
+ adapter: "openai-chat",
+ regions: [
+ { id: "singapore", label: "Singapore (International)", baseUrl: "https://{workspace}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1" },
+ { id: "virginia", label: "US (Virginia)", baseUrl: "https://{workspace}.us-east-1.maas.aliyuncs.com/compatible-mode/v1" },
+ { id: "beijing", label: "China (Beijing)", baseUrl: "https://{workspace}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", cny: true },
+ { id: "hongkong", label: "Hong Kong", baseUrl: "https://{workspace}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1" },
+ { id: "tokyo", label: "Tokyo", baseUrl: "https://{workspace}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1" },
+ ],
+ keySetting: "qwenKey",
+ regionSetting: "qwenRegion",
+ workspaceSetting: "qwenWorkspace",
+ keyHint: { pattern: "^sk-\\S+$", text: "Model Studio keys start with sk-" },
+ keysUrl: "https://modelstudio.console.alibabacloud.com/?tab=globalset#/efm/api_key",
+ modelsPath: "/models",
+ // The effort is a thinking budget (Fuobe's numbers: the docs set no levels).
+ quirks: { maxTokensField: "max_tokens", effortField: "thinking_budget", extraBody: { enable_thinking: true }, streamUsage: true },
+ freePlan: { kind: "trial", limits: "1M tokens per model for 90 days (Singapore only), then billed unless Free Quota Only is on" },
+ models: [
+ { id: "qwen3.8-max", name: "Qwen3.8-Max", tier: 1, speed: "normal", context: 991_808, maxOut: 131_072, tools: true, vision: true, price: [usd(2, 6)], efforts: QWEN_BUDGET },
+ { id: "qwen3.8-2.4t-a95b", name: "Qwen3.8 2.4T-A95B", tier: 2, speed: "normal", context: 991_808, maxOut: 131_072, tools: true, vision: false, open: { licence: "Qwen licence (other)" }, price: [usd(2, 6)], efforts: QWEN_BUDGET },
+ {
+ id: "qwen3.7-plus",
+ name: "Qwen3.7-Plus",
+ tier: 3,
+ speed: "normal",
+ context: 991_808,
+ maxOut: 131_072,
+ tools: true,
+ vision: true,
+ price: [usd(0.4, 1.6)],
+ efforts: QWEN_BUDGET,
+ longContext: { above: 256_000, text: "Over 256K tokens: $1.20 in, $4.80 out per million tokens" },
+ },
+ { id: "qwen3.8-flash", name: "Qwen3.8-Flash", tier: 3, speed: "fast", context: 991_808, maxOut: 131_072, tools: true, vision: true, price: [usd(0.15, 0.47)], efforts: QWEN_BUDGET },
+ { id: "qwen3.8-27b", name: "Qwen3.8 27B", tier: 3, speed: "normal", context: 991_808, maxOut: 131_072, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.5, 3)], efforts: QWEN_BUDGET },
+ ],
+ sources: ["https://www.alibabacloud.com/help/en/model-studio/models", "https://www.alibabacloud.com/help/en/model-studio/model-pricing", "https://www.alibabacloud.com/help/en/model-studio/compatibility-of-openai-with-dashscope", "https://www.alibabacloud.com/help/en/model-studio/new-free-quota"],
+ },
+ {
+ id: "minimax",
+ label: "MiniMax",
+ short: "MiniMax",
+ group: "china",
+ adapter: "openai-chat",
+ regions: [
+ { id: "international", label: "International", baseUrl: "https://api.minimax.io/v1" },
+ { id: "china", label: "China", baseUrl: "https://api.minimax.cn/v1", cny: true },
+ ],
+ keySetting: "minimaxKey",
+ regionSetting: "minimaxRegion",
+ keysUrl: "https://platform.minimax.io/user-center/basic-information/interface-key",
+ quirks: { toolChoice: "omit", replayReasoning: "preserve", errorEnvelope: "minimax", streamUsage: true },
+ models: [
+ {
+ id: "MiniMax-M3",
+ name: "MiniMax M3",
+ tier: 2,
+ speed: "normal",
+ context: M,
+ maxOut: 131_072,
+ tools: true,
+ vision: true,
+ open: { licence: "MiniMax licence (other)" },
+ price: [usd(0.3, 1.2)],
+ priceCny: [usd(2.1, 8.4)],
+ longContext: { above: 512_000, text: "Over 512K tokens: $0.60 in, $2.40 out per million tokens" },
+ },
+ { id: "MiniMax-M3.1-Flash", name: "MiniMax M3.1 Flash", tier: 3, speed: "fast", context: M, maxOut: 131_072, tools: true, vision: true, open: { licence: "MiniMax licence (other)" }, price: [usd(0.15, 0.6)], priceCny: [usd(1, 4)], efforts: EVERY },
+ ],
+ sources: ["https://platform.minimax.io/docs/guides/models-intro", "https://platform.minimax.io/docs/api-reference/text-chat-openai", "https://platform.minimax.io/docs/pricing/overview"],
+ },
+ // -------------------------------------------------------------------------
+ // Hosts and routers
+ {
+ id: "openrouter",
+ label: "OpenRouter",
+ short: "OpenRouter",
+ group: "hosts",
+ adapter: "openai-chat",
+ baseUrl: "https://openrouter.ai/api/v1",
+ keySetting: "openrouterKey",
+ keyHint: { pattern: "^sk-or-\\S+$", text: "OpenRouter keys start with sk-or-" },
+ keysUrl: "https://openrouter.ai/settings/keys",
+ billingUrl: "https://openrouter.ai/settings/credits",
+ modelsPath: "/models",
+ // Its name only: never HTTP-Referer, which would name this install's address.
+ quirks: { effortField: "reasoning.effort", replayReasoning: "preserve", headers: { "X-OpenRouter-Title": "Fuobe" } },
+ freeLimits: {
+ text: "20 a minute, 50 a day (1,000 a day once you've bought 10 credits)",
+ caveat: "Some free models' providers may log prompts (OpenRouter → Settings → Privacy).",
+ shared: true,
+ },
+ models: [
+ { id: "nvidia/nemotron-3-ultra-550b-a55b:free", name: "Nemotron 3 Ultra", tier: 2, speed: "normal", context: 1_000_000, maxOut: 65_536, tools: true, vision: false, open: { licence: "licence not stated" }, free: "model" },
+ { id: "thinkingmachines/inkling:free", name: "Inkling", tier: 3, speed: "normal", context: 1_048_576, maxOut: 262_144, tools: true, vision: true, open: { licence: "licence not stated" }, free: "model" },
+ { id: "nvidia/nemotron-3.5-super-vl:free", name: "Nemotron 3.5 Super VL", tier: 3, speed: "normal", context: 1_000_000, maxOut: 131_072, tools: true, vision: true, open: { licence: "licence not stated" }, free: "model" },
+ { id: "google/gemma-4-31b-it:free", name: "Gemma 4 31B", tier: 3, speed: "normal", context: 262_144, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, free: "model" },
+ { id: "nvidia/nemotron-3.5-lightning:free", name: "Nemotron 3.5 Lightning", tier: 4, speed: "fast", context: 1_000_000, maxOut: 65_536, tools: true, vision: false, open: { licence: "OpenMDW-1.1" }, free: "model" },
+ { id: "thinkingmachines/inkling-small:free", name: "Inkling Small", tier: 4, speed: "fast", context: 1_048_576, maxOut: 262_144, tools: true, vision: true, open: { licence: "licence not stated" }, free: "model" },
+ { id: "xingchen-agi/xing4.0-29b-a4b:free", name: "Xing4.0 29B", tier: 4, speed: "fast", context: 262_144, maxOut: 235_929, tools: true, vision: false, open: { licence: "licence not stated" }, free: "model" },
+ { id: "recursive/flint-v1.0:free", name: "Flint", tier: 4, speed: "normal", context: 262_144, maxOut: 235_929, tools: true, vision: false, open: { licence: "licence not stated" }, free: "model" },
+ { id: "cohere/north-mini-code:free", name: "North Mini Code", tier: 4, speed: "fast", context: 256_000, maxOut: 64_000, tools: true, vision: false, open: { licence: "Apache-2.0" }, free: "model", note: "Made for coding" },
+ { id: "openrouter/free", name: "Free Models Router", tier: 4, speed: "normal", context: 200_000, maxOut: 32_768, tools: true, vision: false, free: "model", router: true, note: "A random free model each time" },
+ { id: "anthropic/claude-opus-5.5", name: "Claude Opus 5.5", tier: 1, speed: "normal", context: M, maxOut: 64_000, tools: true, vision: true, price: [usd(4, 20)], efforts: EVERY, same: "anthropic/claude-opus-5-5" },
+ { id: "openai/gpt-6.1-sol", name: "GPT-6.1 Sol", tier: 1, speed: "normal", context: 1_050_000, maxOut: 128_000, tools: true, vision: true, price: [usd(2, 10)], efforts: EVERY, same: "openai/gpt-6.1-sol" },
+ { id: "google/gemini-4-argon", name: "Gemini 4 Argon", tier: 1, speed: "slow", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, price: [usd(2, 10)], efforts: LOW_MED_HIGH, same: "google/gemini-4-argon", timeoutMs: 1_200_000 },
+ { id: "x-ai/grok-4.7", name: "Grok 4.7", tier: 1, speed: "normal", context: 500_000, maxOut: 128_000, tools: true, vision: true, price: [usd(2, 6)], efforts: { low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "xhigh" }, same: "xai/grok-4.7" },
+ { id: "moonshotai/kimi-k3.1-pro", name: "Kimi K3.1 Pro", tier: 1, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, price: [usd(2, 10)], efforts: LOW_HIGH_MAX, same: "moonshot/kimi-k3.1-pro" },
+ { id: "qwen/qwen3.8-max-0902", name: "Qwen3.8-Max", tier: 1, speed: "normal", context: M, maxOut: 131_072, tools: true, vision: true, price: [usd(2, 6)], same: "qwen/qwen3.8-max" },
+ { id: "z-ai/glm-5.3", name: "GLM-5.3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 128_000, tools: true, vision: false, open: { licence: "GLM licence (other)" }, price: [usd(0.0699, 1.4)], efforts: LOW_HIGH_MAX, same: "zai/glm-5.3" },
+ { id: "mistralai/mistral-large-4-0", name: "Mistral Large 4", tier: 2, speed: "normal", context: 1_048_576, maxOut: 32_768, tools: true, vision: true, open: { licence: "Mistral Ecosystem Open Weight Licence" }, price: [usd(0.7, 2.1)], same: "mistral/mistral-large-4" },
+ { id: "deepseek/deepseek-v4.1-flash-1017", name: "DeepSeek V4.1 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.15, 0.6)], same: "deepseek/deepseek-flash" },
+ { id: "minimax/minimax-m3.1-flash", name: "MiniMax M3.1 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "MiniMax licence (other)" }, price: [usd(0.15, 0.6)], same: "minimax/MiniMax-M3.1-Flash" },
+ ],
+ sources: [
+ "https://openrouter.ai/docs/api_reference/limits.md",
+ "https://openrouter.ai/docs/api_reference/streaming.md",
+ "https://openrouter.ai/docs/guides/features/tool-calling.md",
+ "https://openrouter.ai/docs/guides/best-practices/reasoning-tokens.md",
+ "https://openrouter.ai/api/v1/models?supported_parameters=tools",
+ ],
+ },
+ {
+ id: "groq",
+ label: "Groq",
+ short: "Groq",
+ group: "hosts",
+ adapter: "openai-chat",
+ baseUrl: "https://api.groq.com/openai/v1",
+ keySetting: "groqKey",
+ keyHint: { pattern: "^gsk_\\S+$", text: "Groq keys start with gsk_" },
+ keysUrl: "https://console.groq.com/keys",
+ modelsPath: "/models",
+ quirks: { extraBody: { reasoning_format: "parsed" } },
+ freePlan: {
+ kind: "plan",
+ setting: "groqFreePlan",
+ limits: "30 a minute, 1,000 a day, 8,000 tokens a minute",
+ tooSmall: "Too small for Assist: one Assist step is about 9,000 tokens",
+ },
+ models: [
+ { id: "openai/gpt-oss-120b", name: "gpt-oss-120b", tier: 3, speed: "fast", context: 131_072, maxOut: 65_536, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.15, 0.6)], free: "plan", efforts: LOW_MED_HIGH },
+ { id: "openai/gpt-oss-20b", name: "gpt-oss-20b", tier: 4, speed: "fast", context: 131_072, maxOut: 65_536, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.075, 0.3)], free: "plan", efforts: LOW_MED_HIGH },
+ { id: "qwen/qwen3.8-27b", name: "Qwen3.8 27B", tier: 3, speed: "fast", context: 131_072, maxOut: 16_384, tools: true, vision: true, maxImages: 3, open: { licence: "Apache-2.0" }, price: [usd(0.8, 4)], free: "plan", efforts: LOW_MED_HIGH, status: "preview" },
+ ],
+ sources: ["https://console.groq.com/docs/models", "https://console.groq.com/docs/rate-limits", "https://console.groq.com/docs/openai.md", "https://console.groq.com/docs/reasoning.md"],
+ },
+ {
+ id: "cerebras",
+ label: "Cerebras",
+ short: "Cerebras",
+ group: "hosts",
+ adapter: "openai-chat",
+ baseUrl: "https://api.cerebras.ai/v1",
+ keySetting: "cerebrasKey",
+ keyHint: { pattern: "^csk-\\S+$", text: "Cerebras keys start with csk-" },
+ keysUrl: "https://cloud.cerebras.ai",
+ modelsPath: "/models",
+ quirks: { imageTypes: ["image/png", "image/jpeg"], maxOutCap: 16_384 },
+ freePlan: { kind: "trial", limits: "$5 of credits for 30 days, after adding a card" },
+ models: [
+ { id: "gpt-oss-120b", name: "gpt-oss-120b", tier: 3, speed: "fast", context: 131_072, maxOut: 40_000, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.35, 0.75)], efforts: LOW_MED_HIGH, note: "About 3,000 tokens a second" },
+ { id: "qwen-3.8-27b", name: "Qwen3.8 27B", tier: 3, speed: "fast", context: 128_000, maxOut: 40_000, tools: true, vision: true, maxImages: 10, open: { licence: "Apache-2.0" }, price: [usd(0.99, 1.49)], efforts: LOW_MED_HIGH },
+ ],
+ sources: ["https://inference-docs.cerebras.ai/models/overview", "https://inference-docs.cerebras.ai/support/rate-limits.md", "https://inference-docs.cerebras.ai/resources/openai.md"],
+ },
+ {
+ id: "together",
+ label: "Together AI",
+ short: "Together",
+ group: "hosts",
+ adapter: "openai-chat",
+ regions: [
+ { id: "global", label: "Global", baseUrl: "https://api.together.ai/v1" },
+ { id: "us", label: "United States", baseUrl: "https://us-api.together.ai/v1", note: "US-only processing, 1.25× the price, on some models" },
+ ],
+ keySetting: "togetherKey",
+ regionSetting: "togetherRegion",
+ keysUrl: "https://api.together.ai/settings/api-keys",
+ modelsPath: "/models",
+ quirks: { maxTokensField: "max_tokens", replayReasoning: "preserve", streamUsage: true },
+ models: [
+ { id: "moonshotai/Kimi-K3", name: "Kimi K3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Kimi licence (other)" }, price: [usd(3, 15)], same: "moonshot/kimi-k3" },
+ { id: "zai-org/GLM-5.3", name: "GLM-5.3", tier: 2, speed: "normal", context: 1_048_575, maxOut: 128_000, tools: true, vision: false, open: { licence: "GLM licence (other)" }, price: [usd(1.4, 4.4)], same: "zai/glm-5.3" },
+ { id: "deepseek-ai/DeepSeek-V4-Pro-0813", name: "DeepSeek V4 Pro", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: false, open: { licence: "MIT" }, price: [usd(1.32, 3.96)], same: "deepseek/deepseek-v4-pro" },
+ { id: "meta-models/Muse-Spark-Open-816B-A42B", name: "Muse Spark Open", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: false, open: { licence: "Muse Model Licence" }, price: [usd(1.25, 4.25)] },
+ { id: "zai-org/GLM-5.3-Flash", name: "GLM-5.3 Flash", tier: 3, speed: "fast", context: 1_048_575, maxOut: 128_000, tools: true, vision: false, open: { licence: "MIT" }, price: [usd(0.15, 0.5)], same: "zai/glm-5.3-flash" },
+ { id: "deepseek-ai/DeepSeek-V4.1-Flash-1017", name: "DeepSeek V4.1 Flash", tier: 3, speed: "fast", context: M, maxOut: 131_072, tools: true, vision: false, open: { licence: "MIT" }, price: [usd(0.3, 1.2)], same: "deepseek/deepseek-flash" },
+ { id: "MiniMaxAI/MiniMax-M3.1-Flash", name: "MiniMax M3.1 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 131_072, tools: true, vision: false, open: { licence: "MiniMax licence (other)" }, price: [usd(0.15, 0.6)], same: "minimax/MiniMax-M3.1-Flash" },
+ { id: "nvidia/NVIDIA-Nemotron-3.5-Super-VL", name: "Nemotron 3.5 Super VL", tier: 3, speed: "fast", context: 262_144, maxOut: 65_536, tools: true, vision: true, open: { licence: "licence not stated" }, price: [usd(0.15, 0.5)] },
+ { id: "openai/gpt-oss-120b", name: "gpt-oss-120b", tier: 3, speed: "fast", context: 131_072, maxOut: 65_536, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.15, 0.6)], efforts: LOW_MED_HIGH },
+ { id: "Qwen/Qwen3.8-Flash", name: "Qwen3.8 Flash", tier: 3, speed: "fast", context: M, maxOut: 131_072, tools: true, vision: false, price: [usd(0.15, 0.47)], same: "qwen/qwen3.8-flash" },
+ { id: "Qwen/Qwen3.5-9B", name: "Qwen3.5 9B", tier: 4, speed: "fast", context: 262_144, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.17, 0.25)] },
+ ],
+ sources: ["https://docs.together.ai/docs/serverless/models.md", "https://docs.together.ai/docs/billing.md", "https://docs.together.ai/docs/inference/chat/reasoning.md"],
+ },
+ {
+ id: "fireworks",
+ label: "Fireworks AI",
+ short: "Fireworks",
+ group: "hosts",
+ adapter: "openai-chat",
+ baseUrl: "https://api.fireworks.ai/inference/v1",
+ keySetting: "fireworksKey",
+ keyHint: { pattern: "^fw_\\S+$", text: "Fireworks keys start with fw_" },
+ keysUrl: "https://app.fireworks.ai/settings/users/api-keys",
+ modelsPath: "/models",
+ // Without "error", Fireworks quietly lowers max_tokens when a chat is long.
+ quirks: { maxTokensField: "max_tokens", replayReasoning: "preserve", extraBody: { context_length_exceeded_behavior: "error" } },
+ models: [
+ { id: "accounts/fireworks/models/kimi-k3", name: "Kimi K3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Kimi licence (other)" }, price: [usd(3, 15)], same: "moonshot/kimi-k3" },
+ { id: "accounts/fireworks/models/glm-5p3", name: "GLM-5.3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 128_000, tools: true, vision: false, open: { licence: "GLM licence (other)" }, price: [usd(1.4, 4.4)], same: "zai/glm-5.3" },
+ { id: "accounts/fireworks/models/minimax-m3", name: "MiniMax M3", tier: 2, speed: "normal", context: 512_000, maxOut: 131_072, tools: true, vision: false, open: { licence: "MiniMax licence (other)" }, price: [usd(0.3, 1.2)], same: "minimax/MiniMax-M3" },
+ { id: "accounts/fireworks/models/muse-spark-open", name: "Muse Spark Open", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Muse Model Licence" }, price: [usd(1.25, 4.25)] },
+ { id: "accounts/fireworks/models/qwen3p8-max", name: "Qwen3.8 2.4T-A95B", tier: 2, speed: "normal", context: 991_808, maxOut: 131_072, tools: true, vision: true, open: { licence: "Qwen licence (other)" }, price: [usd(2, 6)], note: "Fireworks calls it Qwen 3.8 Max; it is the open 2.4T model", same: "qwen/qwen3.8-2.4t-a95b" },
+ { id: "accounts/fireworks/models/nemotron-3-ultra-nvfp4", name: "Nemotron 3 Ultra", tier: 2, speed: "normal", context: 262_144, maxOut: 65_536, tools: true, vision: false, open: { licence: "licence not stated" }, price: [usd(0.6, 2.4)], status: "preview" },
+ { id: "accounts/fireworks/models/glm-5p3-flash", name: "GLM-5.3 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 128_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.15, 0.5)], same: "zai/glm-5.3-flash" },
+ { id: "accounts/fireworks/models/deepseek-v4p1-flash-1017", name: "DeepSeek V4.1 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.3, 1.2)], same: "deepseek/deepseek-flash" },
+ { id: "accounts/fireworks/models/gpt-oss-120b", name: "gpt-oss-120b", tier: 3, speed: "fast", context: 131_072, maxOut: 65_536, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.15, 0.6)], efforts: LOW_MED_HIGH },
+ { id: "accounts/fireworks/models/nemotron-lightning-3p5-30b-a3b", name: "Nemotron 3.5 Lightning", tier: 4, speed: "fast", context: 262_144, maxOut: 65_536, tools: true, vision: false, open: { licence: "OpenMDW-1.1" }, price: [usd(0.05, 0.2)] },
+ ],
+ sources: ["https://docs.fireworks.ai/serverless/pricing.md", "https://docs.fireworks.ai/tools-sdks/openai-compatibility.md", "https://docs.fireworks.ai/guides/reasoning.md"],
+ },
+ {
+ id: "huggingface",
+ label: "Hugging Face",
+ short: "Hugging Face",
+ group: "hosts",
+ adapter: "openai-chat",
+ baseUrl: "https://router.huggingface.co/v1",
+ keySetting: "huggingfaceToken",
+ keyHint: { pattern: "^hf_\\S+$", text: "Hugging Face tokens start with hf_ (a fine-grained one, with Inference Providers on)" },
+ keysUrl: "https://huggingface.co/settings/tokens",
+ modelsPath: "/models",
+ quirks: { maxTokensField: "max_tokens", streamUsage: true },
+ freePlan: { kind: "trial", limits: "PRO accounts get $2 of credits a month; others pay per use" },
+ // Each id names the cheapest provider that calls tools (Hugging Face's router list, 31 Oct 2026).
+ models: [
+ { id: "zai-org/GLM-5.3:deepinfra", name: "GLM-5.3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 128_000, tools: true, vision: false, open: { licence: "GLM licence (other)" }, price: [usd(0.9, 4)], same: "zai/glm-5.3" },
+ { id: "moonshotai/Kimi-K3:deepinfra", name: "Kimi K3", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Kimi licence (other)" }, price: [usd(2.85, 14.25)], same: "moonshot/kimi-k3" },
+ { id: "meta-models/Muse-Spark-Open-816B-A42B:baseten", name: "Muse Spark Open", tier: 2, speed: "normal", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "Muse Model Licence" }, price: [usd(1.25, 4.25)] },
+ { id: "deepseek-ai/DeepSeek-V4.1-Flash-1017:novita", name: "DeepSeek V4.1 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 131_072, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.3, 1.2)], same: "deepseek/deepseek-flash" },
+ { id: "zai-org/GLM-5.3-Flash:novita", name: "GLM-5.3 Flash", tier: 3, speed: "fast", context: 1_048_576, maxOut: 128_000, tools: true, vision: true, open: { licence: "MIT" }, price: [usd(0.15, 0.5)], same: "zai/glm-5.3-flash" },
+ { id: "MiniMaxAI/MiniMax-M3.1-Flash:novita", name: "MiniMax M3.1 Flash", tier: 3, speed: "fast", context: M, maxOut: 131_072, tools: true, vision: true, open: { licence: "MiniMax licence (other)" }, price: [usd(0.15, 0.6)], same: "minimax/MiniMax-M3.1-Flash" },
+ { id: "Qwen/Qwen3.8-27B:cerebras", name: "Qwen3.8 27B", tier: 3, speed: "fast", context: 65_536, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.99, 1.49)] },
+ { id: "google/gemma-4-31B-it:novita", name: "Gemma 4 31B", tier: 3, speed: "normal", context: 262_144, maxOut: 32_768, tools: true, vision: true, open: { licence: "Apache-2.0" }, price: [usd(0.14, 0.4)] },
+ { id: "nvidia/NVIDIA-Nemotron-3.5-Super-VL-120B-A12B-NVFP4:baseten", name: "Nemotron 3.5 Super VL", tier: 3, speed: "fast", context: 1_048_576, maxOut: 65_536, tools: true, vision: true, open: { licence: "licence not stated" }, price: [usd(0.2, 0.5)] },
+ { id: "openai/gpt-oss-120b:deepinfra", name: "gpt-oss-120b", tier: 3, speed: "fast", context: 131_072, maxOut: 65_536, tools: true, vision: false, open: { licence: "Apache-2.0" }, price: [usd(0.037, 0.17)], efforts: LOW_MED_HIGH },
+ ],
+ sources: ["https://huggingface.co/docs/inference-providers/index.md", "https://huggingface.co/docs/inference-providers/pricing.md", "https://router.huggingface.co/v1/models"],
+ },
+ // -------------------------------------------------------------------------
+ // On this machine: models come from the server (src/server/llm/servers.ts).
+ { id: "ollama", label: "Ollama", short: "Ollama", group: "local", adapter: "local", quirks: {}, models: [], sources: ["https://docs.ollama.com/api"] },
+ { id: "lmstudio", label: "LM Studio", short: "LM Studio", group: "local", adapter: "local", quirks: {}, models: [], sources: ["https://lmstudio.ai/docs/developer"] },
+ { id: "unsloth", label: "Unsloth Studio", short: "Unsloth Studio", group: "local", adapter: "local", quirks: {}, models: [], sources: ["https://unsloth.ai/docs/basics/api"] },
+ { id: "custom", label: "Other OpenAI-compatible server", short: "your local server", group: "local", adapter: "local", quirks: {}, models: [], sources: [] },
+];
+
+
+
+/**
+ * Local models Fuobe knows by name (the 32 GB picks), for ranking and the open-weights label. A model
+ * that isn't here is tier 4 and sees pictures only when its server says so.
+ */
+export const KNOWN_LOCAL_MODELS: { match: RegExp; name: string; vision: boolean; licence: string }[] = [
+ { match: /qwen3\.8.*27b/i, name: "Qwen3.8 27B", vision: true, licence: "Apache-2.0" },
+ { match: /muse-glimmer/i, name: "Muse Glimmer 30B", vision: true, licence: "Apache-2.0" },
+ { match: /gemma-?4.*31b/i, name: "Gemma 4 31B", vision: true, licence: "Apache-2.0" },
+ { match: /gemma-?4.*26b/i, name: "Gemma 4 26B", vision: true, licence: "Apache-2.0" },
+ { match: /qwen3\.6.*(27|35)b/i, name: "Qwen3.6", vision: true, licence: "Apache-2.0" },
+ { match: /glm-4\.7-flash/i, name: "GLM-4.7 Flash", vision: false, licence: "MIT" },
+ { match: /gpt-oss.*20b/i, name: "gpt-oss-20b", vision: false, licence: "Apache-2.0" },
+ { match: /nemotron-3\.5-lightning/i, name: "Nemotron 3.5 Lightning", vision: false, licence: "OpenMDW-1.1" },
+];
+
+export const getLlmProvider = (id: string | null | undefined): LlmProviderDef | undefined => LLM_PROVIDERS.find((p) => p.id === id);
+
+export const getLlmModel = (provider: string | null | undefined, model: string | null | undefined): LlmModelDef | undefined => getLlmProvider(provider)?.models.find((m) => m.id === model);
+
+/** The price in effect on a day (YYYY-MM-DD): the first step whose `until` hasn't passed. */
+export function priceOn(steps: PriceStep[] | undefined, day: string): PriceStep | undefined {
+ return steps?.find((s) => !s.until || day <= s.until) ?? steps?.at(-1);
+}
+
+/** The key of a provider's own model ("zai/glm-5.3"), as hosts' `same` names it. */
+export const modelKey = (provider: string, model: string) => `${provider}/${model}`;
diff --git a/src/lib/connections.ts b/src/lib/connections.ts
index 73007757..641ce224 100644
--- a/src/lib/connections.ts
+++ b/src/lib/connections.ts
@@ -3,6 +3,7 @@
* connection test route: which settings each provider's test reads, what a well-formed key or
* address looks like, when to offer the first-run guide, and each connection's one-line status.
*/
+import { LLM_PROVIDERS } from "./catalog/llm-providers";
export type TestProvider = "fal" | "replicate" | "comfyui" | "llm" | "civitai" | "ai-toolkit";
@@ -28,6 +29,32 @@ export const PROVIDER_SETTINGS = {
"llmModel",
"llmKey",
"llmContext",
+ // Assist's hosted providers: keys, regions and Qwen's workspace (src/lib/catalog/llm-providers.ts).
+ "openaiKey",
+ "openaiRegion",
+ "googleKey",
+ "xaiKey",
+ "xaiRegion",
+ "metaKey",
+ "mistralKey",
+ "cohereKey",
+ "deepseekKey",
+ "moonshotKey",
+ "moonshotRegion",
+ "zaiKey",
+ "zaiRegion",
+ "qwenKey",
+ "qwenRegion",
+ "qwenWorkspace",
+ "minimaxKey",
+ "minimaxRegion",
+ "openrouterKey",
+ "groqKey",
+ "cerebrasKey",
+ "togetherKey",
+ "togetherRegion",
+ "fireworksKey",
+ "huggingfaceToken",
],
// Not a model provider: the key that downloads a recipe's civitai LoRAs (Settings → LoRAs).
civitai: ["civitaiKey"],
@@ -111,7 +138,12 @@ export function settingProblem(name: string, raw: string): string | null {
return addressProblem(v, DEFAULT_AI_TOOLKIT_URL);
case "aiToolkitDatasetDir":
return v.startsWith("/") || /^[A-Za-z]:[\\/]/.test(v) ? null : "Use a full path, like /mnt/shared/datasets";
+ case "qwenWorkspace":
+ return /^[a-z0-9-]{1,64}$/.test(v) ? null : "Use the workspace id from Model Studio's Workspace page (lowercase letters, digits and hyphens), not an address";
}
+ // An LLM provider's key: the format its docs give.
+ const hint = LLM_PROVIDERS.find((p) => p.keySetting === name)?.keyHint;
+ if (hint) return new RegExp(hint.pattern).test(v) ? null : hint.text;
return null;
}
diff --git a/src/server/llm/hosted-errors.ts b/src/server/llm/hosted-errors.ts
new file mode 100644
index 00000000..7637e478
--- /dev/null
+++ b/src/server/llm/hosted-errors.ts
@@ -0,0 +1,101 @@
+import "server-only";
+import type { LlmModelDef, LlmProviderDef } from "@/lib/catalog/llm-providers";
+import { mask } from "../settings";
+import { errorDetail } from "./errors";
+
+/*
+ * What went wrong with a hosted provider, in words that say what to do: check the key, add credit,
+ * pick another model, wait for a limit. The provider's own words are kept, with the key taken out
+ * (some echo part of it back).
+ */
+
+/** The key out of a text: the whole key masked, and any long run of its characters too. */
+export function scrubKey(text: string, key: string): string {
+ if (!key || key.length < 8) return text;
+ let out = text.split(key).join(mask(key));
+ // "Incorrect API key provided: sk-abc1…wxyz" and friends quote a piece of it.
+ for (let i = 0; i + 12 <= key.length; i++) {
+ const piece = key.slice(i, i + 12);
+ if (out.includes(piece)) out = out.split(piece).join("••••");
+ }
+ return out;
+}
+
+/** A free model's limit ran out: Free moves the chat to its next free choice (P3), or says when it comes back. */
+export class FreeLimitError extends Error {
+ constructor(
+ message: string,
+ /** "day": the provider's free requests are gone until tomorrow; "minute": wait a little. */
+ readonly span: "day" | "minute",
+ readonly provider: string,
+ ) {
+ super(message);
+ }
+}
+
+/** The chat no longer fits the model's context. */
+export class ContextError extends Error {}
+
+export class HostedError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly provider: string,
+ ) {
+ super(message);
+ }
+}
+
+const CONTEXT = /context_length_exceeded|context (?:length|window|size)|maximum context|prompt is too long|too many tokens|input is too long|exceeds? the (?:model'?s? )?(?:context|maximum)/i;
+const NO_MODEL = /model[^.]{0,80}(?:not found|does not exist|doesn't exist|is not available|unknown|no such|invalid|not supported)|unknown model|model_not_found|no such model|invalid model/i;
+const FREE_CAP = /free[- ]models?-per-(day|min)|free_model|free tier|free-tier|quota|free requests/i;
+
+/** "This chat is too long for GPT-6.1 Sol (about 1.1M tokens)…" */
+export function tooLongText(model: Pick<LlmModelDef, "name">, tokens?: number): string {
+ const n = tokens ? ` (about ${tokens >= 1_000_000 ? `${(tokens / 1_000_000).toFixed(1)}M` : `${Math.round(tokens / 1000)}K`} tokens)` : "";
+ return `This chat is too long for ${model.name}${n}. Start a new chat, or pick a model with a longer context in Manual.`;
+}
+
+/** Seconds to wait, from Retry-After (seconds, or an HTTP date). */
+export function retryAfter(h: string | null): number | null {
+ if (!h) return null;
+ const s = Number(h);
+ if (Number.isFinite(s)) return Math.max(0, s);
+ const at = Date.parse(h);
+ return Number.isNaN(at) ? null : Math.max(0, Math.round((at - Date.now()) / 1000));
+}
+
+/**
+ * A non-2xx answer (or an error inside a stream) as an error to show. `free`: the model was a free one, so a
+ * 429 means its free limit ran out.
+ */
+export function hostedError(p: LlmProviderDef, status: number, body: string, model: LlmModelDef | null, key: string, opts: { free?: boolean; wait?: number | null } = {}): Error {
+ const detail = scrubKey(errorDetail(body), key);
+ const label = p.label;
+ const where = `Settings → AI helper → ${label}`;
+ const said = detail ? ` (${detail})` : "";
+ if (status === 401 || status === 403) {
+ const extra = p.id === "zai" ? " Z.ai's Standard and Coding Plan keys are separate." : p.id === "qwen" ? " Model Studio keys only work in the region they were made in." : p.id === "huggingface" ? " It needs a fine-grained token with Inference Providers on." : "";
+ return new HostedError(`${label} rejected the key${said}. Check it in ${where}.${extra}`, status, p.id);
+ }
+ if (status === 402 || /billing_not_configured|insufficient[_ ]balance|insufficient credits|no credit/i.test(body)) {
+ const billing = p.billingUrl ?? p.keysUrl;
+ const or = p.id === "openrouter" ? " A negative balance also blocks free models." : "";
+ return new HostedError(`${label} says the account has no credit${said}.${billing ? ` Add credit at ${billing}.` : ""}${or}`, 402, p.id);
+ }
+ if (CONTEXT.test(detail) || /"context_length_exceeded"/.test(body)) return new ContextError(tooLongText(model ?? { name: "this model" }));
+ if (p.id === "openrouter" && status === 404 && /data policy|no endpoints/i.test(detail)) {
+ return new HostedError(`No OpenRouter provider serves ${model?.name ?? "that model"} with your privacy settings. Allow it in OpenRouter → Settings → Privacy, or pick another free model.`, 404, p.id);
+ }
+ if (status === 404 || NO_MODEL.test(detail)) return new HostedError(`${label} has no model ${model?.id ?? "by that name"} today (it may have been retired). Pick another in Manual.`, status, p.id);
+ if (status === 429) {
+ if (opts.free) {
+ const day = /per[- ]day|daily|today|per-day|rpd/i.test(detail) || FREE_CAP.test(detail);
+ return new FreeLimitError(day ? `${label}'s free requests for today are used up` : `${label}'s free requests are used up for the moment`, day ? "day" : "minute", p.id);
+ }
+ const wait = opts.wait ? ` Try again in ${opts.wait} s.` : " Try again in a minute.";
+ return new HostedError(`${label} is rate-limited right now.${wait}`, 429, p.id);
+ }
+ if (status >= 500) return new HostedError(`${label} had a problem on its side (${status})${said}. Try again in a moment.`, status, p.id);
+ return new HostedError(`${label} returned an error (${status})${said}`, status, p.id);
+}
diff --git a/src/server/llm/hosted-messages.ts b/src/server/llm/hosted-messages.ts
new file mode 100644
index 00000000..3c96e1a6
--- /dev/null
+++ b/src/server/llm/hosted-messages.ts
@@ -0,0 +1,147 @@
+import "server-only";
+import type Anthropic from "@anthropic-ai/sdk";
+import { GEMINI_DUMMY_SIGNATURE, type LlmModelDef, type LlmProviderDef } from "@/lib/catalog/llm-providers";
+import { CONTEXT_UPDATE_LABEL, wireId } from "./messages";
+import type { ChatMessage, ChatToolCall, Replay } from "./types";
+
+type MessageParam = Anthropic.Beta.BetaMessageParam;
+type Block = Exclude<MessageParam["content"], string>[number];
+type Stored = MessageParam & { replay?: Replay };
+
+/*
+ * Assist's history (Claude's shape) as chat messages for a hosted provider. Each provider gets back
+ * only what it made: its own reasoning (for the same model), its own tool ids and Gemini's signatures.
+ * Turns other models made go without them, which the providers' docs allow, except where they don't:
+ * Gemini wants a signature on the first call of every step (the documented dummy stands in), DeepSeek
+ * wants reasoning on every turn and refuses calls it didn't make (those become text).
+ */
+
+export interface HostedTarget {
+ provider: LlmProviderDef;
+ model: LlmModelDef;
+}
+
+/** Anthropic's tool-id pattern: a provider id that fits is kept, so the chat can move back to Claude. */
+export const FITS_ID = /^[A-Za-z0-9_-]{1,64}$/;
+
+const isImage = (b: { type: string }): b is Anthropic.Beta.BetaImageBlockParam => b.type === "image";
+
+function picture(b: Anthropic.Beta.BetaImageBlockParam): { data: string; contentType: string } | null {
+ return b.source.type === "base64" ? { data: b.source.data, contentType: b.source.media_type } : null;
+}
+
+const pictureNote = (b: Anthropic.Beta.BetaImageBlockParam) => (b.source.type === "url" ? `[picture: ${b.source.url}]` : "[picture]");
+
+const NO_SIGHT = "This model can't see pictures; judge from the prompts.";
+
+/**
+ * The history as chat messages for one provider and model. `history` has its latest pictures read
+ * already (base64); older ones are left as [picture] notes, so a long chat doesn't resend every picture.
+ */
+export function toHostedMessages(system: { stable: string; turn: string }, history: Stored[], { provider, model }: HostedTarget): ChatMessage[] {
+ const q = provider.quirks;
+ const nine = q.toolIds === "nine";
+ // The last turn that carries the user's words or tool results: only its pictures are sent.
+ const lastUser = history.findLastIndex((m) => m.role === "user");
+ const out: ChatMessage[] = [{ role: "system", content: `${system.stable}\n\n${system.turn}` }];
+ // Tool ids by stored id, for the results that follow; null: the call went out as text.
+ const ids = new Map<string, string | null>();
+ const names = new Map<string, string>();
+
+ history.forEach((m, i) => {
+ const role = m.role as "user" | "assistant" | "system";
+ const blocks: Block[] = typeof m.content === "string" ? [{ type: "text", text: m.content }] : m.content;
+ const texts = blocks.flatMap((b) => (b.type === "text" ? [b.text] : []));
+ if (role === "system") {
+ out.push({ role: "user", content: `${CONTEXT_UPDATE_LABEL}\n${texts.join("\n")}` });
+ return;
+ }
+ if (role === "assistant") {
+ const r = m.replay;
+ const own = r?.provider === provider.id;
+ const sameModel = own && r?.model === model.id;
+ const uses = blocks.filter((b): b is Anthropic.Beta.BetaToolUseBlockParam => b.type === "tool_use");
+ if (!own && uses.length && q.foreignToolCalls === "flatten") {
+ // DeepSeek refuses calls it didn't make: say what ran, in words.
+ for (const u of uses) {
+ ids.set(u.id, null);
+ names.set(u.id, u.name);
+ }
+ const ran = uses.map((u) => `${u.name} ${JSON.stringify(u.input ?? {})}`).join("; ");
+ out.push({ role: "assistant", content: [...texts, `(Earlier in this chat another model ran: ${ran})`].join("\n").trim(), ...(q.replayReasoning === "required" && { reasoning: { field: "reasoning_content", text: "" } }) });
+ return;
+ }
+ const calls: ChatToolCall[] = uses.map((u, n) => {
+ const wire = nine ? wireId(u.id) : own ? (r?.toolIds?.[u.id] ?? u.id) : u.id;
+ ids.set(u.id, wire);
+ names.set(u.id, u.name);
+ const sig = q.signatures === "gemini" && n === 0 ? ((own && r?.extra?.[u.id]) || { google: { thought_signature: GEMINI_DUMMY_SIGNATURE } }) : own ? r?.extra?.[u.id] : undefined;
+ return { id: wire, name: u.name, input: u.input, ...(sig !== undefined && { extra: sig }) };
+ });
+ const reasoning = sameModel && q.replayReasoning && r?.reasoning?.text ? { field: q.reasoningKey ?? r.reasoning.field, text: r.reasoning.text } : q.replayReasoning === "required" ? { field: "reasoning_content", text: "" } : undefined;
+ out.push({
+ role: "assistant",
+ content: texts.join("\n"),
+ ...(calls.length && { toolCalls: calls }),
+ ...(reasoning && { reasoning: reasoning.field === "thinking" ? { ...reasoning, field: "reasoning_content" } : reasoning }),
+ ...(sameModel && r?.details?.length && { details: r.details }),
+ // OpenAI's Responses API: the turn as it came, encrypted reasoning included.
+ ...(sameModel && r?.items?.length && { items: r.items }),
+ });
+ return;
+ }
+ // A user turn: tool results first (they answer the turn before), then the words.
+ const latest = i === lastUser;
+ const shown: { data: string; contentType: string }[] = [];
+ const flat: string[] = [];
+ const from: string[] = [];
+ for (const b of blocks) {
+ if (b.type !== "tool_result") continue;
+ const parts = typeof b.content === "string" ? [{ type: "text" as const, text: b.content }] : (b.content ?? []);
+ const words: string[] = [];
+ for (const c of parts) {
+ if (c.type === "text") words.push(c.text);
+ else if (isImage(c)) {
+ const pic = latest && model.vision ? picture(c) : null;
+ if (pic) shown.push(pic);
+ else words.push(model.vision ? pictureNote(c) : NO_SIGHT);
+ }
+ }
+ const text = `${b.is_error ? "Error: " : ""}${[...new Set(words)].join("\n")}`;
+ const wire = ids.get(b.tool_use_id);
+ const name = names.get(b.tool_use_id) ?? "a tool";
+ if (wire === null) flat.push(`Result of ${name}: ${text}`);
+ else out.push({ role: "tool", toolCallId: wire ?? (nine ? wireId(b.tool_use_id) : b.tool_use_id), toolName: name, content: text });
+ if (shown.length && !from.includes(name)) from.push(name);
+ }
+ if (flat.length) out.push({ role: "user", content: flat.join("\n\n") });
+ // A tool message takes text only: its pictures follow in a user turn.
+ if (shown.length) out.push({ role: "user", content: `Pictures from ${from.join(" and ")}:`, images: shown });
+ // The user's own pictures: their words already list the files by URL, so older ones need no note.
+ const attached = blocks.filter((b) => b.type === "image").flatMap((b) => (isImage(b) ? [b] : []));
+ const pics = latest && model.vision ? attached.flatMap((b) => picture(b) ?? []) : [];
+ const words = texts.join("\n");
+ if (words || pics.length) out.push({ role: "user", content: words, ...(pics.length && { images: pics }) });
+ });
+
+ // Strict providers want turns that alternate: user turns in a row become one.
+ const merged: ChatMessage[] = [];
+ for (const m of out) {
+ const last = merged.at(-1);
+ if (m.role === "user" && last?.role === "user") {
+ last.content = [last.content, m.content].filter(Boolean).join("\n\n");
+ if (m.images?.length) last.images = [...(last.images ?? []), ...m.images];
+ } else merged.push({ ...m });
+ }
+ // At most the provider's picture count per request (Groq 3), the newest kept.
+ const cap = model.maxImages;
+ if (cap) {
+ let left = cap;
+ for (const m of [...merged].reverse()) {
+ if (!m.images?.length) continue;
+ m.images = m.images.slice(Math.max(0, m.images.length - left));
+ left -= m.images.length;
+ }
+ }
+ return merged;
+}
diff --git a/src/server/llm/hosted.ts b/src/server/llm/hosted.ts
new file mode 100644
index 00000000..d4916b8d
--- /dev/null
+++ b/src/server/llm/hosted.ts
@@ -0,0 +1,445 @@
+import "server-only";
+import { createHash } from "node:crypto";
+import net from "node:net";
+import type { AssistEffort } from "@/lib/assist";
+import { getLlmProvider, LLM_PROVIDERS, type LlmModelDef, type LlmProviderDef, type Quirks } from "@/lib/catalog/llm-providers";
+import { isPrivateAddress } from "../remote-fetch";
+import { getSetting, type SettingName } from "../settings";
+import { tenant } from "../tenant";
+import { ContextError, hostedError, HostedError, retryAfter, scrubKey, tooLongText } from "./hosted-errors";
+import { FITS_ID } from "./hosted-messages";
+import { healToolCalls } from "./messages";
+import { chatResponses } from "./responses";
+import { readChatStream, StreamError, type StreamUsage } from "./sse";
+import type { ChatMessage, ChatTool, ChatToolCall, Replay } from "./types";
+import { newToolId, stripThink, toolInput } from "./wire";
+
+/*
+ * Assist on the owner's hosted LLM providers (src/lib/catalog/llm-providers.ts): OpenAI, Gemini, xAI,
+ * DeepSeek, Kimi, GLM, Qwen, OpenRouter… Each provider's address comes from the registry's official
+ * hosts only, its key from Settings. Calls are streamed (a long think never meets a gateway timeout),
+ * never follow a redirect (a 3xx can't carry the key elsewhere), and never run for an account or a
+ * guest: their work never uses the studio's keys.
+ */
+
+export interface Endpoint {
+ provider: LlmProviderDef;
+ /** No trailing slash. */
+ baseUrl: string;
+ key: string;
+ /** A China region: prices in CNY. */
+ cny: boolean;
+}
+
+export interface HostedRequest {
+ messages: ChatMessage[];
+ tools?: ChatTool[];
+ effort?: AssistEffort | null;
+ /** Output room; by default 32K tokens (64K at Extra and Max), within the model's own limit. */
+ maxTokens?: number;
+ /** The chat, for providers that cache by conversation (xAI): sent as a hash. */
+ threadKey?: string;
+ signal?: AbortSignal;
+}
+
+export interface HostedResult {
+ text: string;
+ /** Ids fit Anthropic's pattern (the chat can move back to Claude); the provider's own is in replay.toolIds. */
+ toolCalls: ChatToolCall[];
+ stop: "end" | "tool_use" | "length";
+ model: string;
+ thought: boolean;
+ /** What this provider needs back on this turn later (stored on the assistant message). */
+ replay: Replay;
+ usage: StreamUsage | null;
+ finish: string | null;
+}
+
+export const NOT_FOR_ACCOUNTS = "Accounts and guests can't use the studio's own LLM keys.";
+
+/** Hosted providers Fuobe calls with a key (not Anthropic, which has its own SDK path, and not the local servers). */
+export const HOSTED_PROVIDERS = LLM_PROVIDERS.filter((p) => p.adapter === "openai-chat" || p.adapter === "openai-responses");
+
+const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]);
+
+/**
+ * FUOBE_LLM_TEST_BASE ("deepseek=http://127.0.0.1:3399/v1,…"): a stand-in provider on this machine,
+ * for tests and local checks. Only addresses on this machine are taken; anything else is ignored.
+ */
+function testBase(id: string): string | null {
+ for (const part of (process.env.FUOBE_LLM_TEST_BASE ?? "").split(",")) {
+ const [name, url] = part.split("=").map((s) => s?.trim());
+ if (name !== id || !url) continue;
+ try {
+ const u = new URL(url);
+ if ((u.protocol === "http:" || u.protocol === "https:") && LOOPBACK.has(u.hostname) && !u.username && !u.password) return url.replace(/\/+$/, "");
+ } catch {}
+ }
+ return null;
+}
+
+/** The key's setting, region and workspace in effect. */
+const setting = (name: string | undefined) => (name ? getSetting(name as SettingName) : "");
+
+/** A provider's free plan is ticked in Settings (Fuobe can't see it from the key). */
+export const freePlanOn = (p: LlmProviderDef): boolean => p.freePlan?.kind === "plan" && !!p.freePlan.setting && setting(p.freePlan.setting) === "1";
+
+/** A model that costs nothing on this account: free on any key, or free on the plan the owner ticked. */
+export const isFree = (p: LlmProviderDef, m: LlmModelDef): boolean => m.free === "model" || (m.free === "plan" && freePlanOn(p));
+
+/**
+ * Where a provider's calls go, with its key: the registry's host for the region in Settings (Qwen's with the
+ * workspace id), never a free URL. Null: no key (or Qwen without its workspace). Throws for an account or a guest.
+ */
+export function endpointFor(id: string): Endpoint | null {
+ if (tenant()) throw new Error(NOT_FOR_ACCOUNTS);
+ const provider = getLlmProvider(id);
+ if (!provider || (provider.adapter !== "openai-chat" && provider.adapter !== "openai-responses") || !provider.keySetting) return null;
+ const key = setting(provider.keySetting);
+ if (!key) return null;
+ const region = provider.regions ? (provider.regions.find((r) => r.id === setting(provider.regionSetting)) ?? provider.regions[0]) : undefined;
+ let base = region?.baseUrl ?? provider.baseUrl;
+ if (!base) return null;
+ if (base.includes("{workspace}")) {
+ const ws = setting(provider.workspaceSetting);
+ if (!/^[a-z0-9-]{1,64}$/.test(ws)) return null;
+ base = base.replace("{workspace}", ws);
+ }
+ return { provider, baseUrl: testBase(id) ?? base, key, cny: !!region?.cny };
+}
+
+/** The hosted providers with a key set (no calls made). */
+export function connectedHosted(): Endpoint[] {
+ if (tenant()) return [];
+ return HOSTED_PROVIDERS.flatMap((p) => endpointFor(p.id) ?? []);
+}
+
+/** https, or plain http only to this machine or the LAN (the owner's own servers). Never a key over http to a public host. */
+export function checkBase(ep: Endpoint): string {
+ let u: URL;
+ try {
+ u = new URL(ep.baseUrl);
+ } catch {
+ throw new HostedError(`${ep.provider.label}'s address isn't a valid URL`, 0, ep.provider.id);
+ }
+ if (u.username || u.password) throw new HostedError(`${ep.provider.label}'s address can't carry a user name or password`, 0, ep.provider.id);
+ if (u.protocol === "https:") return ep.baseUrl.replace(/\/+$/, "");
+ const host = u.hostname.replace(/^\[|\]$/g, "");
+ if (u.protocol === "http:" && (host === "localhost" || (net.isIP(host) !== 0 && isPrivateAddress(host)))) return ep.baseUrl.replace(/\/+$/, "");
+ throw new HostedError(`Fuobe never sends ${ep.provider.label}'s key over plain http to a public address`, 0, ep.provider.id);
+}
+
+// ---------------------------------------------------------------------------
+// Request body (Chat Completions)
+
+/** Output room: 32K tokens, 64K at Extra and Max (as Claude gets), within the model's limit and the provider's cap. */
+export function outputRoom(p: LlmProviderDef, m: LlmModelDef, effort: AssistEffort | null | undefined, asked?: number): number {
+ const want = asked ?? (effort === "xhigh" || effort === "max" ? 64_000 : 32_000);
+ return Math.min(want, m.maxOut, p.quirks.maxOutCap ?? Infinity);
+}
+
+/** The effort as this provider takes it, from the model's map (nothing for a model without levels, or a level it doesn't offer). */
+function effortFields(q: Quirks, m: LlmModelDef, effort: AssistEffort | null | undefined): Record<string, unknown> {
+ const v = m.efforts?.[effort ?? "medium"];
+ if (v === undefined || v === null || v === "") return {};
+ switch (q.effortField ?? "reasoning_effort") {
+ case "reasoning.effort":
+ return { reasoning: { effort: v } };
+ case "thinking_budget":
+ return Number.isFinite(Number(v)) ? { thinking_budget: Number(v) } : {};
+ case "none":
+ return {};
+ default:
+ return { reasoning_effort: v };
+ }
+}
+
+type Part = { type: "text"; text: string } | { type: "image_url"; image_url: { url: string } | string };
+
+function wireMessage(m: ChatMessage, q: Quirks): Record<string, unknown> {
+ if (m.role === "system") return { role: q.systemRole ?? "system", content: m.content };
+ if (m.role === "tool") return { role: "tool", tool_call_id: m.toolCallId ?? "", content: m.content };
+ if (m.role === "assistant") {
+ const calls = m.toolCalls ?? [];
+ return {
+ role: "assistant",
+ content: m.content || (calls.length ? null : ""),
+ ...(calls.length && {
+ tool_calls: calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.input ?? {}) }, ...(c.extra !== undefined && { extra_content: c.extra }) })),
+ }),
+ ...(m.reasoning && { [m.reasoning.field]: m.reasoning.text }),
+ ...(m.details?.length && { reasoning_details: m.details }),
+ };
+ }
+ if (m.images?.length) {
+ const parts: Part[] = m.images.map((i) => {
+ const url = `data:${i.contentType};base64,${i.data}`;
+ return { type: "image_url", image_url: q.imageUrl === "string" ? url : { url } };
+ });
+ return { role: "user", content: [...parts, ...(m.content ? [{ type: "text", text: m.content } as Part] : [])] };
+ }
+ return { role: "user", content: m.content };
+}
+
+/** The Chat Completions body for one call: streamed, tools on every request, the provider's fields and nothing it refuses. */
+export function chatBody(p: LlmProviderDef, m: LlmModelDef, req: HostedRequest): Record<string, unknown> {
+ const q = p.quirks;
+ const tools = req.tools?.map((t) => ({ type: "function", function: { name: t.name, description: t.description ?? "", parameters: t.parameters } }));
+ return {
+ model: m.id,
+ messages: req.messages.map((x) => wireMessage(x, q)),
+ stream: true,
+ ...(q.streamUsage && { stream_options: { include_usage: true } }),
+ ...(tools?.length && { tools, ...(q.toolChoice !== "omit" && { tool_choice: "auto" }) }),
+ [q.maxTokensField ?? "max_completion_tokens"]: outputRoom(p, m, req.effort, req.maxTokens),
+ ...effortFields(q, m, req.effort),
+ ...q.extraBody,
+ };
+}
+
+/** Rough tokens of a request (characters ÷ 4; a picture as about 1,500), to stop before a call the model can't take. */
+export function estimateTokens(messages: ChatMessage[], tools: ChatTool[] = []): number {
+ let chars = JSON.stringify(tools).length;
+ let pictures = 0;
+ for (const m of messages) {
+ chars += m.content.length + JSON.stringify(m.toolCalls ?? []).length + (m.reasoning?.text.length ?? 0) + 16;
+ pictures += m.images?.length ?? 0;
+ }
+ return Math.ceil(chars / 4) + pictures * 1500;
+}
+
+const PICTURE_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
+
+/** Pictures in a type the provider takes: others go as PNG. */
+async function fitPictures(messages: ChatMessage[], types: string[] = PICTURE_TYPES): Promise<ChatMessage[]> {
+ if (!messages.some((m) => m.images?.some((i) => !types.includes(i.contentType)))) return messages;
+ const sharp = (await import("sharp")).default;
+ return Promise.all(
+ messages.map(async (m) =>
+ m.images?.some((i) => !types.includes(i.contentType))
+ ? {
+ ...m,
+ images: await Promise.all(
+ m.images.map(async (i) => (types.includes(i.contentType) ? i : { data: (await sharp(Buffer.from(i.data, "base64")).png().toBuffer()).toString("base64"), contentType: "image/png" })),
+ ),
+ }
+ : m,
+ ),
+ );
+}
+
+// ---------------------------------------------------------------------------
+// One call
+
+const RETRY = new Set([429, 500, 502, 503, 529]);
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** Why a fetch failed (ECONNREFUSED, a redirect it refused…), without the key. */
+function reason(e: unknown, key: string): string {
+ const err = e as { message?: string; cause?: { code?: string; message?: string } } | undefined;
+ return scrubKey(err?.cause?.code || err?.cause?.message || err?.message || "no answer", key);
+}
+
+/**
+ * POST with the key, never following a redirect. 429 and 5xx are tried once more after Retry-After (when it is
+ * 30 s or less); other failures become hostedError's plain words.
+ */
+export async function postHosted(ep: Endpoint, path: string, body: unknown, opts: { model: LlmModelDef | null; free?: boolean; headers?: Record<string, string>; signal?: AbortSignal; timeoutMs: number }): Promise<Response> {
+ const p = ep.provider;
+ const url = `${checkBase(ep)}${path}`;
+ const signal = opts.signal ? AbortSignal.any([opts.signal, AbortSignal.timeout(opts.timeoutMs)]) : AbortSignal.timeout(opts.timeoutMs);
+ for (let attempt = 0; ; attempt++) {
+ let res: Response;
+ try {
+ res = await fetch(url, {
+ method: "POST",
+ headers: { "content-type": "application/json", accept: "text/event-stream", authorization: `Bearer ${ep.key}`, ...p.quirks.headers, ...opts.headers },
+ body: JSON.stringify(body),
+ redirect: "error",
+ signal,
+ });
+ } catch (e) {
+ if (opts.signal?.aborted) throw e;
+ if ((e as Error)?.name === "TimeoutError") throw new HostedError(`${p.label} took too long to answer. Try again, or pick a faster model.`, 504, p.id);
+ throw new HostedError(`Couldn't reach ${p.label} (${reason(e, ep.key)})`, 0, p.id);
+ }
+ if (res.ok) return res;
+ const text = await res.text().catch(() => "");
+ const wait = retryAfter(res.headers.get("retry-after"));
+ if (attempt === 0 && RETRY.has(res.status) && (wait ?? 2) <= 30) {
+ await sleep((wait ?? 2) * 1000);
+ continue;
+ }
+ throw hostedError(p, res.status, text, opts.model, ep.key, { free: opts.free, wait });
+ }
+}
+
+/** A short, stable name for a chat (xAI caches by it): never the chat's own id. */
+const chatName = (key: string) => createHash("sha256").update(`fuobe:${key}`).digest("hex").slice(0, 32);
+
+/**
+ * One Assist step on a hosted model: the history (already shaped by toHostedMessages) with the tools, streamed,
+ * joined into one reply. Throws plain-English errors (hosted-errors.ts); never runs for an account or a guest.
+ */
+export async function chatHosted(ep: Endpoint, model: LlmModelDef, req: HostedRequest): Promise<HostedResult> {
+ if (tenant()) throw new Error(NOT_FOR_ACCOUNTS);
+ const p = ep.provider;
+ const room = outputRoom(p, model, req.effort, req.maxTokens);
+ const tokens = estimateTokens(req.messages, req.tools);
+ if (tokens > model.context - room) throw new ContextError(tooLongText(model, tokens));
+ if (p.adapter === "openai-responses") return chatResponses(ep, model, { ...req, maxTokens: room });
+ const q = p.quirks;
+ const free = isFree(p, model);
+ const messages = await fitPictures(req.messages, q.imageTypes);
+ const timeoutMs = model.timeoutMs ?? q.timeoutMs ?? 600_000;
+ const res = await postHosted(ep, "/chat/completions", chatBody(p, model, { ...req, messages }), {
+ model,
+ free,
+ timeoutMs,
+ signal: req.signal,
+ headers: q.chatHeader && req.threadKey ? { [q.chatHeader]: chatName(req.threadKey) } : undefined,
+ });
+ if (!res.body) throw new HostedError(`${p.label} sent an empty answer`, 502, p.id);
+ let out;
+ try {
+ out = await readChatStream(res.body, { errorEnvelope: q.errorEnvelope });
+ } catch (e) {
+ if (e instanceof StreamError) throw hostedError(p, e.status ?? 502, JSON.stringify({ error: { message: e.message, code: e.code } }), model, ep.key, { free });
+ throw e;
+ }
+ const toolIds: Record<string, string> = {};
+ const extra: Record<string, unknown> = {};
+ let toolCalls: ChatToolCall[] = out.toolCalls.map((c) => {
+ const id = FITS_ID.test(c.id) ? c.id : newToolId();
+ if (id !== c.id) toolIds[id] = c.id;
+ if (c.extra !== undefined) extra[id] = c.extra;
+ return { id, name: c.name, input: toolInput(c.arguments) };
+ });
+ let text = stripThink(out.text);
+ // A call written as text (<tool_call>{…}</tool_call>) instead of through the API.
+ if (req.tools?.length && !toolCalls.length && text) {
+ const healed = healToolCalls(text, new Set(req.tools.map((t) => t.name)));
+ if (healed.calls.length) ({ text, calls: toolCalls } = { text: healed.text, calls: healed.calls });
+ }
+ const reasoning = q.replayReasoning && out.reasoning?.text ? { field: out.reasoning.field === "thinking" ? "reasoning_content" : out.reasoning.field, text: out.reasoning.text } : undefined;
+ return {
+ text,
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : out.finish === "length" ? "length" : "end",
+ model: out.model ?? model.id,
+ thought: !!out.reasoning?.text,
+ replay: {
+ provider: p.id,
+ model: model.id,
+ ...(reasoning && { reasoning }),
+ ...(out.details?.length && { details: out.details }),
+ ...(Object.keys(toolIds).length && { toolIds }),
+ ...(Object.keys(extra).length && { extra }),
+ },
+ usage: out.usage,
+ finish: out.finish,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Settings: Test and Try a reply
+
+/** GET with the key (a free call), never following a redirect. */
+async function getHosted(ep: Endpoint, path: string): Promise<Response> {
+ const url = `${checkBase(ep)}${path}`;
+ try {
+ return await fetch(url, { headers: { authorization: `Bearer ${ep.key}`, ...ep.provider.quirks.headers }, redirect: "error", signal: AbortSignal.timeout(15_000) });
+ } catch (e) {
+ throw new HostedError(`Couldn't reach ${ep.provider.label} (${reason(e, ep.key)})`, 0, ep.provider.id);
+ }
+}
+
+export interface OpenRouterKey {
+ /** No credits bought yet: only the free models are offered. */
+ freeTier: boolean;
+ /** Free-model requests left today, and the day's limit. */
+ left: number | null;
+ limit: number | null;
+}
+
+declare global {
+ var __fuobeOpenRouterKey: { hash: string; at: number; info: OpenRouterKey | null } | undefined;
+}
+
+/** OpenRouter's GET /api/v1/key (a free call): whether credits were ever bought, and the free requests left today. Kept 60 s. */
+export async function openRouterKey(force = false): Promise<OpenRouterKey | null> {
+ const ep = endpointFor("openrouter");
+ if (!ep) return null;
+ const hash = createHash("sha256").update(`${ep.baseUrl}|${ep.key}`).digest("hex");
+ const c = globalThis.__fuobeOpenRouterKey;
+ if (!force && c?.hash === hash && Date.now() - c.at < 60_000) return c.info;
+ let info: OpenRouterKey | null = null;
+ try {
+ const res = await getHosted(ep, "/key");
+ if (res.ok) {
+ const d = ((await res.json()) as { data?: { is_free_tier?: unknown; free_model_daily_requests?: { remaining?: unknown; limit?: unknown } } }).data;
+ const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : null);
+ info = { freeTier: d?.is_free_tier === true, left: n(d?.free_model_daily_requests?.remaining), limit: n(d?.free_model_daily_requests?.limit) };
+ }
+ } catch {}
+ globalThis.__fuobeOpenRouterKey = { hash, at: Date.now(), info };
+ return info;
+}
+
+/** Settings → Test: the provider's model list with the key (free), or OpenRouter's key check. */
+export async function testHosted(id: string): Promise<{ ok: boolean; detail: string }> {
+ const p = getLlmProvider(id);
+ if (!p) return { ok: false, detail: "Unknown provider" };
+ let ep: Endpoint | null;
+ try {
+ ep = endpointFor(id);
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+ if (!ep) return { ok: false, detail: p.workspaceSetting && setting(p.keySetting) ? `Add your workspace id from ${p.label}` : `No ${p.label} key set` };
+ try {
+ if (p.id === "openrouter") {
+ const res = await getHosted(ep, "/key");
+ if (!res.ok) return { ok: false, detail: hostedError(p, res.status, await res.text().catch(() => ""), null, ep.key).message };
+ const info = await openRouterKey(true);
+ const left = info?.left !== null && info?.limit !== null && info ? ` · ${info.left} of ${info.limit} free requests left today` : "";
+ return { ok: true, detail: `Key works${left}${info?.freeTier ? " · no credits bought yet, so Assist uses the free models" : ""}` };
+ }
+ if (!p.modelsPath) return tryHosted(id);
+ const res = await getHosted(ep, p.modelsPath);
+ if (!res.ok) return { ok: false, detail: hostedError(p, res.status, await res.text().catch(() => ""), null, ep.key).message };
+ const j = (await res.json().catch(() => ({}))) as { data?: unknown[]; models?: unknown[] };
+ const n = (j.data ?? j.models ?? []).length;
+ return { ok: true, detail: `Key works · ${n} model${n === 1 ? "" : "s"} listed${freePlanOn(p) ? " · free plan" : ""}` };
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+}
+
+/** The cheapest model a provider offers here, for Try a reply. */
+function cheapest(p: LlmProviderDef): LlmModelDef | undefined {
+ const usable = p.models.filter((m) => m.tools === true && !m.router);
+ const cost = (m: LlmModelDef) => (isFree(p, m) ? 0 : m.price?.[0] ? (3 * m.price[0].in + m.price[0].out) / 4 : Infinity);
+ return [...usable].sort((a, b) => cost(a) - cost(b))[0];
+}
+
+/** Settings → Try a reply: one tiny chat call, timed ("Answered in 1.2 s with gpt-6.1-sol"). Costs a fraction of a cent on a paid model. */
+export async function tryHosted(id: string, modelId?: string | null): Promise<{ ok: boolean; detail: string; ms?: number; model?: string }> {
+ let ep: Endpoint | null;
+ try {
+ ep = endpointFor(id);
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+ if (!ep) return { ok: false, detail: `No ${getLlmProvider(id)?.label ?? id} key set` };
+ const model = (modelId && ep.provider.models.find((m) => m.id === modelId)) || cheapest(ep.provider);
+ if (!model) return { ok: false, detail: `${ep.provider.label} has no model Fuobe can try` };
+ const t0 = Date.now();
+ try {
+ const r = await chatHosted(ep, model, { messages: [{ role: "user", content: "Reply with the word OK." }], effort: "low", maxTokens: 1024 });
+ const ms = Date.now() - t0;
+ return { ok: true, ms, model: model.id, detail: `Answered in ${(ms / 1000).toFixed(1)} s with ${model.id}${r.text ? "" : " (it was still thinking)"}` };
+ } catch (e) {
+ return { ok: false, detail: (e as Error).message };
+ }
+}
diff --git a/src/server/llm/responses.ts b/src/server/llm/responses.ts
new file mode 100644
index 00000000..db913a08
--- /dev/null
+++ b/src/server/llm/responses.ts
@@ -0,0 +1,148 @@
+import "server-only";
+import type { LlmModelDef } from "@/lib/catalog/llm-providers";
+import { hostedError, HostedError } from "./hosted-errors";
+import type { Endpoint, HostedRequest, HostedResult } from "./hosted";
+import { postHosted } from "./hosted";
+import { FITS_ID } from "./hosted-messages";
+import { healToolCalls } from "./messages";
+import { readSse, StreamError, type StreamUsage } from "./sse";
+import type { ChatMessage, ChatToolCall } from "./types";
+import { newToolId, stripThink, toolInput } from "./wire";
+
+/*
+ * OpenAI's Responses API, which OpenAI's GPT-6.x models need for tool calls ("Starting with GPT-5.4, Chat
+ * Completions does not support tool calling with reasoning_effort values other than none"). Stateless
+ * (store: false): Fuobe's chat is the record, and a turn OpenAI made goes back as the output items it
+ * came as, encrypted reasoning included, so the model keeps its thinking across tool calls. The stream's
+ * typed events are read for the finished response only.
+ */
+
+type Item = Record<string, unknown> & { type?: string };
+
+/** The history as Responses input items; the system message becomes `instructions`. */
+export function responsesInput(messages: ChatMessage[]): { instructions: string; input: Item[] } {
+ const instructions = messages
+ .filter((m) => m.role === "system")
+ .map((m) => m.content)
+ .join("\n\n");
+ const input: Item[] = [];
+ for (const m of messages) {
+ if (m.role === "system") continue;
+ if (m.role === "tool") {
+ input.push({ type: "function_call_output", call_id: m.toolCallId ?? "", output: m.content });
+ continue;
+ }
+ if (m.role === "assistant") {
+ // OpenAI's own turn, as it came (reasoning items with encrypted_content, then messages and calls).
+ if (m.items?.length) {
+ input.push(...(m.items as Item[]));
+ continue;
+ }
+ if (m.content) input.push({ role: "assistant", content: [{ type: "output_text", text: m.content }] });
+ for (const c of m.toolCalls ?? []) input.push({ type: "function_call", call_id: c.id, name: c.name, arguments: JSON.stringify(c.input ?? {}) });
+ continue;
+ }
+ const parts: Item[] = [...(m.images ?? []).map((i) => ({ type: "input_image", image_url: `data:${i.contentType};base64,${i.data}` })), ...(m.content ? [{ type: "input_text", text: m.content }] : [])];
+ if (parts.length) input.push({ role: "user", content: parts });
+ }
+ return { instructions, input };
+}
+
+/** The request body: stateless, streamed, tools flat and not strict (Fuobe's schemas have optional fields). */
+export function responsesBody(model: LlmModelDef, req: HostedRequest & { maxTokens: number }): Record<string, unknown> {
+ const { instructions, input } = responsesInput(req.messages);
+ const effort = model.efforts?.[req.effort ?? "medium"];
+ return {
+ model: model.id,
+ instructions,
+ input,
+ ...(req.tools?.length && {
+ tools: req.tools.map((t) => ({ type: "function", name: t.name, description: t.description ?? "", parameters: t.parameters, strict: false })),
+ tool_choice: "auto",
+ parallel_tool_calls: true,
+ }),
+ ...(effort && { reasoning: { effort } }),
+ max_output_tokens: req.maxTokens,
+ store: false,
+ stream: true,
+ };
+}
+
+interface Response {
+ status?: string;
+ model?: string;
+ output?: Item[];
+ usage?: { input_tokens?: number; output_tokens?: number; input_tokens_details?: { cached_tokens?: number }; output_tokens_details?: { reasoning_tokens?: number } };
+ incomplete_details?: { reason?: string };
+ error?: { code?: string; message?: string };
+}
+
+/** One Assist step on OpenAI's Responses API. */
+export async function chatResponses(ep: Endpoint, model: LlmModelDef, req: HostedRequest & { maxTokens: number }): Promise<HostedResult> {
+ const p = ep.provider;
+ const res = await postHosted(ep, "/responses", responsesBody(model, req), { model, timeoutMs: model.timeoutMs ?? p.quirks.timeoutMs ?? 600_000, signal: req.signal });
+ if (!res.body) throw new HostedError(`${p.label} sent an empty answer`, 502, p.id);
+ let done: Response | null = null;
+ let failed: { status: number; message: string } | null = null;
+ try {
+ await readSse(res.body, (payload) => {
+ let e: { type?: string; response?: Response; code?: string; message?: string };
+ try {
+ e = JSON.parse(payload);
+ } catch {
+ return;
+ }
+ if (e.type === "response.completed" || e.type === "response.incomplete") {
+ done = e.response ?? null;
+ return "done";
+ }
+ if (e.type === "response.failed") {
+ failed = { status: 500, message: e.response?.error?.message ?? "The response failed" };
+ return "done";
+ }
+ if (e.type === "error") {
+ failed = { status: /rate_limit/.test(e.code ?? "") ? 429 : /context_length/.test(e.code ?? "") ? 400 : 500, message: e.message ?? "OpenAI reported an error" };
+ return "done";
+ }
+ });
+ } catch (e) {
+ if (e instanceof StreamError) throw hostedError(p, 502, JSON.stringify({ error: { message: e.message } }), model, ep.key);
+ throw e;
+ }
+ const fail = failed as { status: number; message: string } | null;
+ if (fail) throw hostedError(p, fail.status, JSON.stringify({ error: { message: fail.message } }), model, ep.key);
+ const r = done as Response | null;
+ if (!r) throw new HostedError(`${p.label}'s answer ended before it was complete`, 502, p.id);
+ const output = r.output ?? [];
+ const toolIds: Record<string, string> = {};
+ let toolCalls: ChatToolCall[] = output.flatMap((i) => {
+ if (i.type !== "function_call" || typeof i.name !== "string") return [];
+ const callId = String(i.call_id ?? "");
+ const id = FITS_ID.test(callId) ? callId : newToolId();
+ if (id !== callId) toolIds[id] = callId;
+ return [{ id, name: i.name, input: toolInput(i.arguments) }];
+ });
+ let text = stripThink(
+ output
+ .flatMap((i) => (i.type === "message" && Array.isArray(i.content) ? (i.content as { type?: string; text?: string }[]).flatMap((c) => (c.type === "output_text" && c.text ? [c.text] : [])) : []))
+ .join("\n"),
+ );
+ if (req.tools?.length && !toolCalls.length && text) {
+ const healed = healToolCalls(text, new Set(req.tools.map((t) => t.name)));
+ if (healed.calls.length) ({ text, calls: toolCalls } = { text: healed.text, calls: healed.calls });
+ }
+ const u = r.usage;
+ const usage: StreamUsage | null = u ? { input: u.input_tokens, output: u.output_tokens, cached: u.input_tokens_details?.cached_tokens, reasoning: u.output_tokens_details?.reasoning_tokens } : null;
+ const length = r.status === "incomplete" && r.incomplete_details?.reason === "max_output_tokens";
+ return {
+ text,
+ toolCalls,
+ stop: toolCalls.length ? "tool_use" : length ? "length" : "end",
+ model: r.model ?? model.id,
+ thought: output.some((i) => i.type === "reasoning"),
+ // The turn goes back as it came: its call ids are the ones in these items (stored ids map to them).
+ replay: { provider: p.id, model: model.id, items: output, ...(Object.keys(toolIds).length && { toolIds }) },
+ usage,
+ finish: r.status ?? null,
+ };
+}
diff --git a/src/server/llm/sse.ts b/src/server/llm/sse.ts
new file mode 100644
index 00000000..29e14c6d
--- /dev/null
+++ b/src/server/llm/sse.ts
@@ -0,0 +1,249 @@
+import "server-only";
+
+/*
+ * Chat Completions streams from hosted providers, read into one answer. Assist streams every hosted
+ * call so a long think never meets a gateway timeout (Meta answers 504 to a long call that isn't
+ * streamed; DeepSeek closes one whose inference hasn't started in 10 minutes), but it only uses the
+ * finished reply, so the pieces are joined here. The shapes are the providers' documented ones:
+ * comment lines (`: OPENROUTER PROCESSING`, `: keep-alive`), tool arguments in pieces joined by
+ * index, Gemini's signature in a chunk of its own, Mistral's content chunks, usage in three places,
+ * errors inside a 200 stream, and MiniMax's base_resp.
+ */
+
+export interface StreamedCall {
+ id: string;
+ name: string;
+ /** The arguments as the model wrote them (JSON text). */
+ arguments: string;
+ /** Gemini's thought signature (tool_calls[i].extra_content), sent back exactly as received. */
+ extra?: unknown;
+}
+
+export interface StreamUsage {
+ input?: number;
+ output?: number;
+ cached?: number;
+ reasoning?: number;
+}
+
+export interface StreamResult {
+ text: string;
+ /** The reply's reasoning, under the field it came in (it goes back under the same one). */
+ reasoning: { field: "reasoning_content" | "reasoning" | "thinking"; text: string } | null;
+ /** OpenRouter's reasoning_details, joined by index. */
+ details?: Record<string, unknown>[];
+ toolCalls: StreamedCall[];
+ finish: string | null;
+ usage: StreamUsage | null;
+ model?: string;
+}
+
+/** A failure the provider reported inside the stream (or went quiet). `status` is the HTTP status it means. */
+export class StreamError extends Error {
+ constructor(
+ message: string,
+ readonly status?: number,
+ readonly code?: string | number,
+ readonly idle = false,
+ ) {
+ super(message);
+ }
+}
+
+/** MiniMax answers some errors with HTTP 200 and a status code in base_resp. */
+const MINIMAX_STATUS: Record<number, number> = { 1002: 429, 1004: 401, 1008: 402, 2013: 400, 1039: 429 };
+
+type Delta = {
+ content?: unknown;
+ reasoning_content?: unknown;
+ reasoning?: unknown;
+ reasoning_details?: unknown;
+ tool_calls?: { index?: number; id?: string; function?: { name?: string; arguments?: string }; extra_content?: unknown }[];
+};
+type Chunk = {
+ model?: string;
+ choices?: { delta?: Delta; message?: Delta; finish_reason?: string | null }[];
+ usage?: Record<string, unknown> | null;
+ error?: { message?: string; code?: string | number; status?: number; metadata?: unknown };
+ base_resp?: { status_code?: number; status_msg?: string };
+};
+
+const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
+
+function readUsage(u: Record<string, unknown>): StreamUsage {
+ const pd = (u.prompt_tokens_details ?? {}) as Record<string, unknown>;
+ const cd = (u.completion_tokens_details ?? {}) as Record<string, unknown>;
+ const out: StreamUsage = { input: num(u.prompt_tokens), output: num(u.completion_tokens), cached: num(pd.cached_tokens) ?? num(u.cached_tokens), reasoning: num(cd.reasoning_tokens) ?? num(u.reasoning_tokens) };
+ return Object.fromEntries(Object.entries(out).filter(([, v]) => v !== undefined)) as StreamUsage;
+}
+
+/** Joins the chunks of one reply. */
+class Reply {
+ text = "";
+ reasoning: StreamResult["reasoning"] = null;
+ details: Record<string, unknown>[] = [];
+ calls: { id?: string; name?: string; args: string; extra?: unknown }[] = [];
+ finish: string | null = null;
+ usage: StreamUsage | null = null;
+ model?: string;
+
+ constructor(private readonly opts: { errorEnvelope?: "minimax" }) {}
+
+ private think(field: "reasoning_content" | "reasoning" | "thinking", t: string) {
+ if (!t) return;
+ // The first field a reply uses is the one it goes back under.
+ if (!this.reasoning) this.reasoning = { field, text: "" };
+ this.reasoning.text += t;
+ }
+
+ /** Mistral's content: a string, or chunks of {type:"text"} and {type:"thinking", thinking:[{text}]}. */
+ private content(c: unknown) {
+ if (typeof c === "string") this.text += c;
+ else if (Array.isArray(c)) {
+ for (const part of c as { type?: string; text?: string; thinking?: { text?: string }[] | string }[]) {
+ if (part?.type === "text" && typeof part.text === "string") this.text += part.text;
+ else if (part?.type === "thinking") this.think("thinking", typeof part.thinking === "string" ? part.thinking : (part.thinking ?? []).map((t) => t.text ?? "").join(""));
+ }
+ }
+ }
+
+ private detail(list: unknown) {
+ if (!Array.isArray(list)) return;
+ for (const d of list as Record<string, unknown>[]) {
+ if (!d || typeof d !== "object") continue;
+ const same = this.details.find((x) => x.index !== undefined && x.index === d.index && x.type === d.type);
+ if (!same) {
+ this.details.push({ ...d });
+ continue;
+ }
+ for (const [k, v] of Object.entries(d)) {
+ if ((k === "text" || k === "summary") && typeof v === "string") same[k] = `${(same[k] as string | undefined) ?? ""}${v}`;
+ else if (v !== undefined && v !== null && k !== "index" && k !== "type") same[k] = v;
+ }
+ }
+ }
+
+ add(j: Chunk) {
+ if (this.opts.errorEnvelope === "minimax" && j.base_resp?.status_code) {
+ const code = j.base_resp.status_code;
+ throw new StreamError(j.base_resp.status_msg || `MiniMax error ${code}`, MINIMAX_STATUS[code] ?? 500, code);
+ }
+ if (j.error) throw new StreamError(j.error.message || "The provider reported an error", num(j.error.status) ?? (typeof j.error.code === "number" ? j.error.code : undefined), j.error.code);
+ if (j.model) this.model = j.model;
+ if (j.usage) this.usage = readUsage(j.usage);
+ for (const ch of j.choices ?? []) {
+ const d = ch.delta ?? ch.message ?? {};
+ this.content(d.content);
+ if (typeof d.reasoning_content === "string") this.think("reasoning_content", d.reasoning_content);
+ if (typeof d.reasoning === "string") this.think("reasoning", d.reasoning);
+ this.detail(d.reasoning_details);
+ for (const t of d.tool_calls ?? []) {
+ // By index; without one, by id (a new id is a new call), else the call being written.
+ const known = t.id ? this.calls.findIndex((c) => c?.id === t.id) : -1;
+ const at = typeof t.index === "number" ? t.index : known >= 0 ? known : t.id || !this.calls.length ? this.calls.length : this.calls.length - 1;
+ const call = (this.calls[at] ??= { args: "" });
+ if (t.id && !call.id) call.id = t.id;
+ if (t.function?.name && !call.name) call.name = t.function.name;
+ if (typeof t.function?.arguments === "string") call.args += t.function.arguments;
+ if (t.extra_content !== undefined && call.extra === undefined) call.extra = t.extra_content;
+ }
+ if (ch.finish_reason) {
+ if (ch.finish_reason === "error") throw new StreamError("The provider stopped with an error partway through the reply");
+ this.finish = ch.finish_reason;
+ }
+ }
+ }
+
+ result(): StreamResult {
+ return {
+ text: this.text,
+ reasoning: this.reasoning,
+ ...(this.details.length && { details: this.details }),
+ toolCalls: this.calls.flatMap((c, i) => (c?.name ? [{ id: c.id || `call_${i}`, name: c.name, arguments: c.args, ...(c.extra !== undefined && { extra: c.extra }) }] : [])),
+ finish: this.finish,
+ usage: this.usage,
+ ...(this.model && { model: this.model }),
+ };
+ }
+}
+
+/** The next piece of the body, or a StreamError when nothing (not even a keep-alive) came for `idleMs`. */
+async function next(reader: ReadableStreamDefaultReader<Uint8Array>, idleMs: number) {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ reader.read(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new StreamError(`Nothing came back for ${Math.round(idleMs / 1000)} s`, undefined, undefined, true)), idleMs);
+ }),
+ ]);
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+/**
+ * Read a server-sent event stream: `onData` gets each event's data (comment lines and empty events are
+ * skipped) and returns "done" to stop early. Throws StreamError when nothing (not even a keep-alive)
+ * comes for `idleMs`.
+ */
+export async function readSse(body: ReadableStream<Uint8Array>, onData: (payload: string) => "done" | void, idleMs = 180_000): Promise<void> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buf = "";
+ let data: string[] = [];
+ let done = false;
+ const event = () => {
+ const payload = data.join("\n").trim();
+ data = [];
+ if (payload && onData(payload) === "done") done = true;
+ };
+ const line = (raw: string) => {
+ const l = raw.endsWith("\r") ? raw.slice(0, -1) : raw;
+ if (!l) return event();
+ if (l.startsWith(":")) return;
+ if (l.startsWith("data:")) data.push(l.slice(5).replace(/^ /, ""));
+ };
+ try {
+ while (!done) {
+ const { value, done: end } = await next(reader, idleMs);
+ if (end) break;
+ buf += decoder.decode(value, { stream: true });
+ let nl: number;
+ while (!done && (nl = buf.indexOf("\n")) >= 0) {
+ line(buf.slice(0, nl));
+ buf = buf.slice(nl + 1);
+ }
+ }
+ if (!done) {
+ buf += decoder.decode();
+ if (buf) line(buf);
+ event();
+ }
+ } finally {
+ reader.cancel().catch(() => {});
+ }
+}
+
+/**
+ * Read a Chat Completions stream to its end ([DONE], or the end of the body). Throws StreamError for
+ * an error the provider sends inside the stream, and when nothing arrives for `idleMs` (3 minutes).
+ */
+export async function readChatStream(body: ReadableStream<Uint8Array>, opts: { idleMs?: number; errorEnvelope?: "minimax" } = {}): Promise<StreamResult> {
+ const reply = new Reply(opts);
+ await readSse(
+ body,
+ (payload) => {
+ if (payload === "[DONE]") return "done";
+ let j: Chunk;
+ try {
+ j = JSON.parse(payload) as Chunk;
+ } catch {
+ return;
+ }
+ reply.add(j);
+ },
+ opts.idleMs,
+ );
+ return reply.result();
+}
diff --git a/src/server/llm/types.ts b/src/server/llm/types.ts
index 4d9bc738..9b132255 100644
--- a/src/server/llm/types.ts
+++ b/src/server/llm/types.ts
@@ -65,6 +65,8 @@ export interface ChatToolCall {
id: string;
name: string;
input: unknown;
+ /** Gemini's thought signature on the call (tool_calls[i].extra_content), sent back as received. */
+ extra?: unknown;
}
export interface ChatMessage {
@@ -77,6 +79,31 @@ export interface ChatMessage {
toolName?: string;
/** User turns: pictures for a model that can see (base64, JPEG, PNG, GIF or WebP); a text-only model answers from the words. */
images?: { data: string; contentType: string }[];
+ /** Assistant turns (hosted providers): the reasoning to send back, under the field it came in. */
+ reasoning?: { field: string; text: string };
+ /** Assistant turns on OpenRouter: reasoning_details, sent back as received. */
+ details?: unknown[];
+ /** Assistant turns on OpenAI's Responses API: the turn's output items (encrypted reasoning included), sent back unchanged. */
+ items?: unknown[];
+}
+
+/**
+ * What a hosted provider needs back on its own earlier turns, kept on the stored assistant message as
+ * `replay`. It goes back only to the provider that made it (reasoning only to the same model), and
+ * never to Anthropic (src/server/assist/agent.ts forAnthropic).
+ */
+export interface Replay {
+ provider: string;
+ model: string;
+ reasoning?: { field: string; text: string };
+ /** OpenRouter's reasoning_details. */
+ details?: unknown[];
+ /** OpenAI Responses: the turn's output items (encrypted reasoning included), replayed unchanged. */
+ items?: unknown[];
+ /** Stored tool_use id → the provider's own id, when its id didn't fit the stored pattern. */
+ toolIds?: Record<string, string>;
+ /** Stored tool_use id → Gemini's extra_content (its thought signature). */
+ extra?: Record<string, unknown>;
}
/** A JSON Schema the answer must follow (root object or array), or "object" for any JSON object. */
diff --git a/src/server/settings.ts b/src/server/settings.ts
index fa95ac7d..c5c75e83 100644
--- a/src/server/settings.ts
+++ b/src/server/settings.ts
@@ -25,8 +25,45 @@ export const SETTINGS = {
falKey: { key: "fal.key", env: "FAL_KEY", secret: true },
replicateToken: { key: "replicate.token", env: "REPLICATE_API_TOKEN", secret: true },
openaiKey: { key: "openai.key", env: "OPENAI_API_KEY", secret: true },
- googleKey: { key: "google.key", env: "GEMINI_API_KEY", secret: true },
+ googleKey: { key: "google.key", env: ["GEMINI_API_KEY", "GOOGLE_API_KEY"], secret: true },
anthropicKey: { key: "anthropic.key", env: "ANTHROPIC_API_KEY", secret: true },
+ /*
+ * Assist's hosted LLM providers (src/lib/catalog/llm-providers.ts): a key each, the region where the
+ * provider has several official hosts, and the tick for a free plan Fuobe can't see from the key.
+ */
+ xaiKey: { key: "xai.key", env: "XAI_API_KEY", secret: true },
+ /** Meta's docs name no environment variable for Model API keys. */
+ metaKey: { key: "meta.key", env: "FUOBE_META_API_KEY", secret: true },
+ mistralKey: { key: "mistral.key", env: "MISTRAL_API_KEY", secret: true },
+ cohereKey: { key: "cohere.key", env: ["CO_API_KEY", "COHERE_API_KEY"], secret: true },
+ deepseekKey: { key: "deepseek.key", env: "DEEPSEEK_API_KEY", secret: true },
+ moonshotKey: { key: "moonshot.key", env: "MOONSHOT_API_KEY", secret: true },
+ zaiKey: { key: "zai.key", env: ["ZAI_API_KEY", "ZHIPUAI_API_KEY"], secret: true },
+ qwenKey: { key: "qwen.key", env: "DASHSCOPE_API_KEY", secret: true },
+ minimaxKey: { key: "minimax.key", env: "MINIMAX_API_KEY", secret: true },
+ openrouterKey: { key: "openrouter.key", env: "OPENROUTER_API_KEY", secret: true },
+ groqKey: { key: "groq.key", env: "GROQ_API_KEY", secret: true },
+ cerebrasKey: { key: "cerebras.key", env: "CEREBRAS_API_KEY", secret: true },
+ togetherKey: { key: "together.key", env: "TOGETHER_API_KEY", secret: true },
+ fireworksKey: { key: "fireworks.key", env: "FIREWORKS_API_KEY", secret: true },
+ huggingfaceToken: { key: "huggingface.token", env: "HF_TOKEN", secret: true },
+ openaiRegion: { key: "openai.region", default: "global", options: ["global", "us", "eu"] },
+ xaiRegion: { key: "xai.region", default: "global", options: ["global", "us"] },
+ moonshotRegion: { key: "moonshot.region", default: "international", options: ["international", "china"] },
+ zaiRegion: { key: "zai.region", default: "international", options: ["international", "china"] },
+ minimaxRegion: { key: "minimax.region", default: "international", options: ["international", "china"] },
+ togetherRegion: { key: "together.region", default: "global", options: ["global", "us"] },
+ qwenRegion: { key: "qwen.region", default: "singapore", options: ["singapore", "virginia", "beijing", "hongkong", "tokyo"] },
+ /** Model Studio's workspace id: part of the official host name, never a URL. */
+ qwenWorkspace: { key: "qwen.workspace", env: "DASHSCOPE_WORKSPACE_ID" },
+ googleFreeTier: { key: "google.freeTier", default: "0", options: ["0", "1"] },
+ mistralFreePlan: { key: "mistral.freePlan", default: "0", options: ["0", "1"] },
+ cohereTrialKey: { key: "cohere.trialKey", default: "0", options: ["0", "1"] },
+ groqFreePlan: { key: "groq.freePlan", default: "0", options: ["0", "1"] },
+ /** Settings → AI helper → "Smart plans with": "auto", or "provider|model". */
+ smartPlan: { key: "assist.smartPlan", default: "auto" },
+ /** Settings → AI helper → "Free uses": the best free model, or the local one first. */
+ freeOrder: { key: "assist.freeOrder", default: "best", options: ["best", "local"] },
comfyUrl: { key: "comfyui.url", env: "COMFYUI_URL", default: "http://127.0.0.1:8188" },
comfyToken: { key: "comfyui.token", env: "COMFYUI_TOKEN", secret: true },
/** A second ComfyUI for workflows whose node packs can't share the main install (LatentSync 1.6, ThinkSound; scripts/comfy/README.md). */
@@ -138,6 +175,13 @@ export function validateSetting(name: SettingName, value: string): void {
if (name === "llmContext" && value !== "" && parseContext(value) === null) {
throw new Error("llmContext must be a number of tokens of at least 2048 (such as 16384 or 16k), or 0 to leave it to the server");
}
+ // It becomes part of a host name: letters, digits and hyphens only.
+ if (name === "qwenWorkspace" && value !== "" && !/^[a-z0-9-]{1,64}$/.test(value)) {
+ throw new Error("qwenWorkspace must be the workspace id from Model Studio (lowercase letters, digits and hyphens)");
+ }
+ if (name === "smartPlan" && value !== "" && value !== "auto" && !/^[a-z0-9-]{2,32}\|[\w.:/@+-]{1,200}$/.test(value)) {
+ throw new Error("smartPlan must be auto, or a provider and model as provider|model");
+ }
}
export function setSetting(name: SettingName, value: string): void {
diff --git a/tests/helpers/fake-llm.ts b/tests/helpers/fake-llm.ts
new file mode 100644
index 00000000..393126a7
--- /dev/null
+++ b/tests/helpers/fake-llm.ts
@@ -0,0 +1,314 @@
+import http from "node:http";
+
+/*
+ * A stand-in for the hosted LLM providers, on an OS-chosen port of this machine. It speaks OpenAI's
+ * Chat Completions (streamed, as Fuobe always asks), OpenAI's Responses API, the free model lists
+ * and OpenRouter's key check. In a strict `mode` it answers 400 the way each provider's docs say it
+ * does when a request breaks one of its rules, so a wrong request body fails the test that sent it.
+ */
+
+export interface Seen {
+ method: string;
+ url: string;
+ auth?: string;
+ headers: http.IncomingHttpHeaders;
+ body: Record<string, unknown> & { messages?: WireMsg[] };
+}
+
+export type WireMsg = {
+ role: string;
+ content?: unknown;
+ name?: string;
+ tool_call_id?: string;
+ tool_calls?: { id: string; type: string; function: { name: string; arguments: string }; extra_content?: unknown }[];
+ reasoning_content?: string;
+ reasoning?: string;
+ reasoning_details?: unknown[];
+};
+
+/** One scripted reply: a stream of chunks built from it, or an error. */
+export interface Reply {
+ text?: string;
+ calls?: { id?: string; name: string; args: unknown; extra?: unknown }[];
+ reasoning?: { field: "reasoning_content" | "reasoning"; text: string };
+ details?: unknown[];
+ usage?: { prompt_tokens: number; completion_tokens: number };
+ finish?: string;
+ /** An HTTP error instead: status, body and headers. */
+ status?: number;
+ error?: unknown;
+ headers?: Record<string, string>;
+ /** Responses API: the output items of response.completed. */
+ output?: unknown[];
+ /** Responses API: end with response.incomplete (max_output_tokens). */
+ incomplete?: boolean;
+}
+
+export type Mode =
+ | "openai"
+ | "meta"
+ | "moonshot"
+ | "deepseek"
+ | "google"
+ | "zai"
+ | "minimax"
+ | "cohere"
+ | "cerebras"
+ | "groq"
+ | "openrouter"
+ | "fireworks"
+ | "mistral"
+ | "together"
+ | "qwen"
+ | "xai"
+ | "huggingface";
+
+const sse = (o: unknown) => `data: ${JSON.stringify(o)}\n\n`;
+
+/** The rule a request breaks in this provider's docs, or null. */
+function broken(mode: Mode, b: Seen["body"], issued: Set<string>): string | null {
+ const msgs = b.messages ?? [];
+ const tools = Array.isArray(b.tools) && b.tools.length > 0;
+ if (b.stream !== true) return "stream must be true";
+ for (const t of (b.tools as { type?: string; function?: { name?: string; parameters?: unknown } }[] | undefined) ?? []) {
+ if (t.type !== "function" || !t.function?.name || !t.function.parameters) return "tools must be {type: function, function: {name, parameters}}";
+ }
+ if (msgs[0]?.role !== (mode === "cohere" ? "developer" : "system")) return `the first message must be ${mode === "cohere" ? "developer" : "system"}`;
+ if (msgs.slice(1).some((m) => m.role === "system" || m.role === "developer")) return "one system message, first";
+ // Every result answers a call of the assistant turn before it.
+ const calls = new Set<string>();
+ for (const m of msgs) {
+ if (m.role === "assistant") for (const c of m.tool_calls ?? []) calls.add(c.id);
+ if (m.role === "tool" && !calls.has(m.tool_call_id ?? "")) return `tool_call_id ${m.tool_call_id} answers no call`;
+ }
+ for (const m of msgs) {
+ for (const c of m.tool_calls ?? []) {
+ try {
+ JSON.parse(c.function.arguments);
+ } catch {
+ return "tool arguments must be a JSON string";
+ }
+ }
+ }
+ const temps = ["temperature", "top_p", "n", "presence_penalty", "frequency_penalty"];
+ switch (mode) {
+ case "meta":
+ if (tools && b.tool_choice !== "auto") return "tool_choice must be auto";
+ if ("max_output_tokens" in b || "max_tokens" in b) return "use max_completion_tokens";
+ break;
+ case "moonshot":
+ for (const k of temps) if (k in b) return `${k} can't be changed on this model`;
+ break;
+ case "deepseek":
+ if (tools) {
+ for (const m of msgs) {
+ if (m.role === "assistant" && typeof m.reasoning_content !== "string") return "The reasoning_content in the thinking mode must be passed back to the API.";
+ for (const c of m.tool_calls ?? []) if (!issued.has(c.id)) return `tool call ${c.id} was not made by this model`;
+ }
+ }
+ break;
+ case "google": {
+ // The first call of each step carries its signature (the documented dummy for other models' turns).
+ for (const m of msgs) {
+ const first = m.tool_calls?.[0] as { extra_content?: { google?: { thought_signature?: string } } } | undefined;
+ if (first && !first.extra_content?.google?.thought_signature) return "Function call is missing a thought_signature";
+ }
+ if ("thinking_config" in b && "reasoning_effort" in b) return "reasoning_effort and thinking_config can't both be set";
+ if (["minimal", "none"].includes(String(b.reasoning_effort))) return "this model doesn't take that reasoning_effort";
+ break;
+ }
+ case "zai":
+ if ("tool_choice" in b && b.tool_choice !== "auto") return "tool_choice only supports auto";
+ break;
+ case "minimax":
+ if ("tool_choice" in b) return "tool_choice is not supported";
+ break;
+ case "cerebras":
+ for (const m of msgs) {
+ if (!Array.isArray(m.content)) continue;
+ for (const p of m.content as { type: string; image_url?: { url?: string } }[]) {
+ if (p.type === "image_url" && !/^data:image\/(png|jpeg);base64,/.test(p.image_url?.url ?? "")) return "images must be base64 PNG or JPEG";
+ }
+ }
+ if (Number(b.max_completion_tokens) > 16_384) return "max_completion_tokens is charged up front: too large";
+ break;
+ case "groq":
+ if (msgs.some((m) => "name" in m)) return "'messages.name' is not supported";
+ break;
+ case "openrouter":
+ if (msgs.some((m) => m.role === "tool") && !tools) return "tools must be sent on every request";
+ if ("HTTP-Referer" in b) return "no";
+ break;
+ case "fireworks":
+ if (b.context_length_exceeded_behavior !== "error") return "expected context_length_exceeded_behavior";
+ break;
+ case "mistral":
+ for (const m of msgs) {
+ for (const c of m.tool_calls ?? []) if (!/^[A-Za-z0-9]{9}$/.test(c.id)) return "Tool call id has to be 9 letters and digits";
+ if (m.role === "tool" && !/^[A-Za-z0-9]{9}$/.test(m.tool_call_id ?? "")) return "Tool call id has to be 9 letters and digits";
+ }
+ break;
+ }
+ return null;
+}
+
+/**
+ * The Responses API's rules: stateless, instructions apart, flat tools that aren't strict, results that answer
+ * a call in the input, and a call this model made carrying its reasoning item back (OpenAI refuses a
+ * function_call "provided without its required reasoning item").
+ */
+function brokenResponses(b: Record<string, unknown>, needs: Map<string, string>): string | null {
+ if (b.store !== false) return "store must be false";
+ if (b.stream !== true) return "stream must be true";
+ if (typeof b.instructions !== "string" || !b.instructions) return "instructions expected";
+ if ("messages" in b) return "Unsupported parameter: messages";
+ for (const t of (b.tools as Record<string, unknown>[] | undefined) ?? []) {
+ if (t.type !== "function" || typeof t.name !== "string" || "function" in t || t.strict !== false) return "tools must be flat, with strict false";
+ }
+ const input = (b.input as Record<string, unknown>[] | undefined) ?? [];
+ const calls = new Set<string>();
+ const reasoning = new Set<string>();
+ for (const i of input) {
+ if (i.type === "reasoning" && typeof i.encrypted_content === "string") reasoning.add(i.encrypted_content);
+ if (i.type === "function_call") {
+ calls.add(String(i.call_id));
+ // An item that names the stored call (its fc_ id) comes with the reasoning it followed.
+ const need = typeof i.id === "string" ? needs.get(i.id) : undefined;
+ if (need && !reasoning.has(need)) return `Item of type 'function_call' was provided without its required 'reasoning' item`;
+ }
+ if (i.type === "function_call_output" && !calls.has(String(i.call_id))) return `No tool call found for function call output with call_id ${i.call_id}`;
+ if (i.role === "system") return "use instructions";
+ }
+ return null;
+}
+
+/** The Chat Completions stream for a reply, in small chunks (arguments split in two, the signature in a chunk of its own). */
+function chatStream(r: Reply, model: string, mode: Mode): string {
+ const chunk = (delta: object, finish: string | null = null, extra: object = {}) => sse({ id: "c1", object: "chat.completion.chunk", model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra });
+ let out = ": keep-alive\n\n";
+ if (r.reasoning) out += chunk({ [r.reasoning.field]: r.reasoning.text });
+ if (r.details) out += chunk({ reasoning_details: r.details });
+ if (r.text) {
+ const half = Math.ceil(r.text.length / 2);
+ out += chunk({ role: "assistant", content: r.text.slice(0, half) }) + chunk({ content: r.text.slice(half) });
+ }
+ (r.calls ?? []).forEach((c, i) => {
+ const args = JSON.stringify(c.args ?? {});
+ const cut = Math.ceil(args.length / 2);
+ out += chunk({ tool_calls: [{ index: i, id: c.id ?? `call_${i}`, type: "function", function: { name: c.name, arguments: args.slice(0, cut) } }] });
+ out += chunk({ tool_calls: [{ index: i, function: { arguments: args.slice(cut) } }] });
+ if (c.extra !== undefined) out += chunk({ tool_calls: [{ index: i, extra_content: c.extra }] });
+ });
+ const finish = r.finish ?? (r.calls?.length ? "tool_calls" : "stop");
+ const usage = r.usage ?? { prompt_tokens: 900, completion_tokens: 40 };
+ // Usage where each provider puts it: OpenRouter's one choice with an empty delta, Fireworks' on the finish chunk, else a last chunk with no choices.
+ if (mode === "fireworks") out += chunk({}, finish, { usage });
+ else if (mode === "openrouter") out += chunk({}, finish) + chunk({}, null, { usage });
+ else out += chunk({}, finish) + sse({ id: "c1", object: "chat.completion.chunk", model, choices: [], usage });
+ return `${out}data: [DONE]\n\n`;
+}
+
+/** A Responses API stream: typed events, the whole response in response.completed. */
+function responsesStream(r: Reply, model: string): string {
+ const output =
+ r.output ??
+ [
+ ...(r.text ? [{ type: "message", id: "msg_1", role: "assistant", status: "completed", content: [{ type: "output_text", text: r.text, annotations: [] }] }] : []),
+ ...(r.calls ?? []).map((c, i) => ({ type: "function_call", id: `fc_${i}`, call_id: c.id ?? `call_${i}`, name: c.name, arguments: JSON.stringify(c.args ?? {}), status: "completed" })),
+ ];
+ const response = { id: "resp_1", object: "response", model, status: r.incomplete ? "incomplete" : "completed", output, usage: { input_tokens: 900, output_tokens: 40, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 12 } }, ...(r.incomplete && { incomplete_details: { reason: "max_output_tokens" } }) };
+ const ev = (type: string, o: object) => `event: ${type}\ndata: ${JSON.stringify({ type, ...o })}\n\n`;
+ let out = ev("response.created", { response: { ...response, status: "in_progress", output: [] } });
+ if (r.text) out += ev("response.output_text.delta", { delta: r.text });
+ out += r.incomplete ? ev("response.incomplete", { response }) : ev("response.completed", { response });
+ return out;
+}
+
+export interface FakeLlm {
+ url: string;
+ seen: Seen[];
+ /** Chat Completions (or Responses) request bodies, in order. */
+ chats: () => Seen["body"][];
+ mode: Mode;
+ key: string;
+ /** Replies, in order; the last one repeats. Setting them starts from the first again. */
+ replies: Reply[];
+ /** Answers GET …/key (OpenRouter's limits). */
+ keyInfo?: Record<string, unknown>;
+ /** A redirect for every request, to this URL. */
+ redirect?: string;
+ models: string[];
+ /** Ids this fake's model made (DeepSeek refuses calls it didn't). */
+ issued: Set<string>;
+ /** Responses: a function_call item's id → the encrypted reasoning that must come back with it. */
+ needs: Map<string, string>;
+ start: () => Promise<void>;
+ close: () => Promise<void>;
+}
+
+export function fakeLlm(mode: Mode, key = "sk-test-0123456789abcdefghij"): FakeLlm {
+ const seen: Seen[] = [];
+ let served = 0;
+ let replies: Reply[] = [{ text: "OK" }];
+ const f: FakeLlm = {
+ url: "",
+ seen,
+ chats: () => seen.filter((r) => r.method === "POST").map((r) => r.body),
+ mode,
+ key,
+ get replies() {
+ return replies;
+ },
+ set replies(r: Reply[]) {
+ replies = r;
+ served = 0;
+ },
+ models: [],
+ issued: new Set(),
+ needs: new Map(),
+ start: () => new Promise<void>((done) => server.listen(0, "127.0.0.1", () => ((f.url = `http://127.0.0.1:${(server.address() as { port: number }).port}`), done()))),
+ close: () => new Promise<void>((done) => server.close(() => done())),
+ };
+ const server = http.createServer((req, res) => {
+ let raw = "";
+ req.on("data", (c) => (raw += c));
+ req.on("end", () => {
+ let body: Seen["body"] = {};
+ try {
+ body = raw ? (JSON.parse(raw) as Seen["body"]) : {};
+ } catch {}
+ const r: Seen = { method: req.method ?? "GET", url: req.url ?? "/", auth: req.headers.authorization, headers: req.headers, body };
+ seen.push(r);
+ const json = (status: number, o: unknown, headers: Record<string, string> = {}) => {
+ res.writeHead(status, { "content-type": "application/json", ...headers });
+ res.end(JSON.stringify(o));
+ };
+ if (f.redirect) {
+ res.writeHead(302, { location: f.redirect });
+ return res.end();
+ }
+ if (r.auth !== `Bearer ${f.key}`) return json(401, { error: { message: `Incorrect API key provided: ${(r.auth ?? "").slice(7, 19)}…`, type: "invalid_request_error", code: "invalid_api_key" } });
+ if (r.method === "GET" && /\/models$/.test(r.url)) return json(200, { object: "list", data: f.models.map((id) => ({ id, object: "model", owned_by: mode })) });
+ if (r.method === "GET" && /\/key$/.test(r.url)) return f.keyInfo ? json(200, { data: f.keyInfo }) : json(404, { error: { message: "Not found" } });
+ const reply = replies[Math.min(served, replies.length - 1)];
+ served++;
+ if (reply.status) return json(reply.status, reply.error ?? { error: { message: `error ${reply.status}` } }, reply.headers);
+ const model = String(body.model ?? "m");
+ if (/\/responses$/.test(r.url)) {
+ const bad = brokenResponses(body, f.needs);
+ if (bad) return json(400, { error: { message: bad, type: "invalid_request_error" } });
+ const out = (reply.output ?? []) as Record<string, unknown>[];
+ const enc = out.find((i) => i.type === "reasoning")?.encrypted_content;
+ if (typeof enc === "string") for (const i of out) if (i.type === "function_call") f.needs.set(String(i.id), enc);
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ return res.end(responsesStream(reply, model));
+ }
+ const wrong = broken(mode, body, f.issued);
+ if (wrong) return json(400, { error: { message: wrong, type: "invalid_request_error" } });
+ for (const c of reply.calls ?? []) if (c.id) f.issued.add(c.id);
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ res.end(chatStream(reply, model, mode));
+ });
+ });
+ return f;
+}
diff --git a/tests/llm-hosted.test.ts b/tests/llm-hosted.test.ts
new file mode 100644
index 00000000..a15e1d30
--- /dev/null
+++ b/tests/llm-hosted.test.ts
@@ -0,0 +1,351 @@
+import fs from "node:fs";
+import http from "node:http";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type Anthropic from "@anthropic-ai/sdk";
+import { getLlmModel, getLlmProvider, GEMINI_DUMMY_SIGNATURE, type LlmModelDef } from "@/lib/catalog/llm-providers";
+import { fakeLlm, type FakeLlm, type Mode } from "./helpers/fake-llm";
+
+/*
+ * The hosted providers' Chat Completions path, against fakes that enforce each provider's documented
+ * rules: the request body per provider (quirks), history with turns from other models (DeepSeek's
+ * flattened calls, Gemini's dummy signatures), what comes back for the next turn (replay), the errors
+ * in plain words with the key taken out, and the security rules (no redirects with a key, never inside
+ * an account's work, never a key over plain http to a public host).
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-hosted-"));
+process.env.FUOBE_DATA_DIR = dir;
+for (const k of Object.keys(process.env)) if (/_API_KEY$|^HF_TOKEN$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];
+
+const { setSetting } = await import("@/server/settings");
+const hosted = await import("@/server/llm/hosted");
+const { toHostedMessages } = await import("@/server/llm/hosted-messages");
+const { ContextError, FreeLimitError, HostedError } = await import("@/server/llm/hosted-errors");
+const { runAsTenant } = await import("@/server/tenant");
+
+type Stored = Anthropic.Beta.BetaMessageParam & { replay?: unknown };
+const system = { stable: "You are Fuobe Assist.", turn: "Today: 2026-10-31." };
+const tools = [
+ { name: "search_models", description: "Find models", parameters: { type: "object", properties: { kind: { type: "string" } } } },
+ { name: "generate", description: "Run jobs", parameters: { type: "object", properties: { jobs: { type: "array" } } } },
+];
+/** A 1×1 WebP, as an attachment the user sent. */
+const WEBP = "UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA==";
+
+const fakes: FakeLlm[] = [];
+async function fake(mode: Mode, provider: string = mode): Promise<FakeLlm> {
+ const f = fakeLlm(mode);
+ await f.start();
+ fakes.push(f);
+ const p = getLlmProvider(provider)!;
+ setSetting(p.keySetting as never, f.key);
+ const bases = (process.env.FUOBE_LLM_TEST_BASE ?? "").split(",").filter((x) => x && !x.startsWith(`${provider}=`));
+ process.env.FUOBE_LLM_TEST_BASE = [...bases, `${provider}=${f.url}/v1`].join(",");
+ return f;
+}
+afterAll(async () => {
+ await Promise.all(fakes.map((f) => f.close()));
+ delete process.env.FUOBE_LLM_TEST_BASE;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+/**
+ * A chat two models wrote: Claude asked for search_models (no replay), then this provider's model asked
+ * for generate (with its replay), then the results; the user's latest turn has a picture.
+ */
+function history(provider: string, model: LlmModelDef, own: { id: string; reasoning?: string; extra?: unknown }): Stored[] {
+ return [
+ { role: "user", content: [{ type: "text", text: "A fox in snow" }] },
+ { role: "assistant", content: [{ type: "text", text: "Looking." }, { type: "tool_use", id: "toolu_01AbCdEf", name: "search_models", input: { kind: "image" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01AbCdEf", content: '{"models":["flux"]}' }] },
+ {
+ role: "assistant",
+ content: [{ type: "tool_use", id: own.id, name: "generate", input: { jobs: [] } }],
+ replay: { provider, model: model.id, ...(own.reasoning && { reasoning: { field: "reasoning_content", text: own.reasoning } }), ...(own.extra !== undefined && { extra: { [own.id]: own.extra } }) },
+ },
+ {
+ role: "user",
+ content: [
+ { type: "tool_result", tool_use_id: own.id, content: '{"started":["g1"]}' },
+ { type: "text", text: "Make it brighter" },
+ { type: "image", source: { type: "base64", media_type: "image/webp", data: WEBP } },
+ ],
+ },
+ ] as Stored[];
+}
+
+async function call(provider: string, modelId: string, msgs: Stored[], extra: Partial<Parameters<typeof hosted.chatHosted>[2]> = {}) {
+ const ep = hosted.endpointFor(provider)!;
+ const model = getLlmModel(provider, modelId)!;
+ return hosted.chatHosted(ep, model, { messages: toHostedMessages(system, msgs as never, { provider: ep.provider, model }), tools, effort: "medium", ...extra });
+}
+
+describe("the request body per provider", () => {
+ const body = (provider: string, model: string, effort: "low" | "medium" | "high" | "xhigh" | "max" = "medium") =>
+ hosted.chatBody(getLlmProvider(provider)!, getLlmModel(provider, model)!, { messages: [{ role: "system", content: "s" }, { role: "user", content: "hi" }], tools, effort });
+
+ it("streams, sends tools nested with tool_choice auto, and names the max-tokens field the docs give", () => {
+ const b = body("meta", "muse-spark-1.3");
+ expect(b).toMatchObject({ model: "muse-spark-1.3", stream: true, tool_choice: "auto", max_completion_tokens: 32_000, reasoning_effort: "medium" });
+ expect(b.tools).toEqual(tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } })));
+ expect(body("deepseek", "deepseek-v4-pro")).toMatchObject({ max_tokens: 32_000, thinking: { type: "enabled" } });
+ expect(body("deepseek", "deepseek-v4-pro", "max")).toMatchObject({ max_tokens: 64_000, reasoning_effort: "max" });
+ });
+
+ it("maps efforts per model: Gemini never minimal, DeepSeek medium → high, OpenRouter's reasoning object, Qwen's budget", () => {
+ expect(body("google", "gemini-3.8-flash", "xhigh")).toMatchObject({ reasoning_effort: "high" });
+ expect(body("google", "gemini-3.8-flash", "low")).toMatchObject({ reasoning_effort: "low" });
+ expect(body("deepseek", "deepseek-v4-pro", "medium").reasoning_effort).toBe("high");
+ const or = body("openrouter", "x-ai/grok-4.7", "max");
+ expect(or.reasoning).toEqual({ effort: "xhigh" });
+ expect(or).not.toHaveProperty("reasoning_effort");
+ expect(body("qwen", "qwen3.8-max", "low")).toMatchObject({ thinking_budget: 2048, enable_thinking: true, stream_options: { include_usage: true } });
+ expect(body("qwen", "qwen3.8-max", "max")).not.toHaveProperty("thinking_budget");
+ // A model with no effort levels gets no effort field.
+ expect(body("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free")).not.toHaveProperty("reasoning");
+ expect(body("minimax", "MiniMax-M3")).not.toHaveProperty("reasoning_effort");
+ });
+
+ it("leaves tool_choice out where it isn't documented, and sends Cohere's system prompt as developer", () => {
+ expect(body("minimax", "MiniMax-M3.1-Flash")).not.toHaveProperty("tool_choice");
+ const co = body("cohere", "command-a-plus-05-2026");
+ expect(co).not.toHaveProperty("tool_choice");
+ expect((co.messages as { role: string }[])[0].role).toBe("developer");
+ });
+
+ it("caps output room where requests are charged up front, and adds each provider's fixed fields", () => {
+ expect(body("cerebras", "gpt-oss-120b", "max")).toMatchObject({ max_completion_tokens: 16_384 });
+ expect(body("fireworks", "accounts/fireworks/models/glm-5p3")).toMatchObject({ context_length_exceeded_behavior: "error", max_tokens: 32_000 });
+ expect(body("groq", "openai/gpt-oss-120b")).toMatchObject({ reasoning_format: "parsed" });
+ // Never temperature or sampling fields (Kimi refuses them; Gemini says to leave them out).
+ for (const p of ["moonshot", "google"]) for (const k of ["temperature", "top_p", "n", "presence_penalty", "frequency_penalty"]) expect(body(p, p === "moonshot" ? "kimi-k3" : "gemini-3.8-flash")).not.toHaveProperty(k);
+ });
+});
+
+describe("a chat on each provider's fake, with a turn from another model", () => {
+ beforeAll(async () => {
+ for (const m of ["meta", "moonshot", "deepseek", "google", "zai", "minimax", "cohere", "cerebras", "groq", "openrouter", "fireworks", "mistral", "together", "xai"] as Mode[]) await fake(m);
+ });
+
+ const cases: [Mode, string][] = [
+ ["meta", "muse-spark-1.3"],
+ ["moonshot", "kimi-k3"],
+ ["zai", "glm-5.3-flash"],
+ ["minimax", "MiniMax-M3.1-Flash"],
+ ["cohere", "command-a-plus-05-2026"],
+ ["groq", "qwen/qwen3.8-27b"],
+ ["openrouter", "x-ai/grok-4.7"],
+ ["fireworks", "accounts/fireworks/models/glm-5p3"],
+ ["together", "moonshotai/Kimi-K3"],
+ ["xai", "grok-4.7"],
+ ];
+ for (const [mode, model] of cases) {
+ it(`${mode}: the fake accepts the whole history and the reply comes back with a tool call`, async () => {
+ const f = fakes.find((x) => x.mode === mode)!;
+ f.replies = [{ text: "On it.", calls: [{ id: "call_x1", name: "generate", args: { jobs: [{ model_id: "flux" }] } }] }];
+ const r = await call(mode, model, history(mode, getLlmModel(mode, model)!, { id: "toolu_own1" }));
+ expect(r.text).toBe("On it.");
+ expect(r.stop).toBe("tool_use");
+ expect(r.toolCalls).toEqual([{ id: "call_x1", name: "generate", input: { jobs: [{ model_id: "flux" }] } }]);
+ expect(r.usage).toMatchObject({ input: 900, output: 40 });
+ });
+ }
+
+ it("xAI: names the chat in x-grok-conv-id (a hash, not the chat's id) and gets pictures as PNG", async () => {
+ const f = fakes.find((x) => x.mode === "xai")!;
+ f.replies = [{ text: "Fine." }];
+ await call("xai", "grok-4.7", history("xai", getLlmModel("xai", "grok-4.7")!, { id: "toolu_own1" }), { threadKey: "chat-123" });
+ const last = f.seen.at(-1)!;
+ expect(last.headers["x-grok-conv-id"]).toMatch(/^[a-f0-9]{32}$/);
+ expect(JSON.stringify(last.body)).not.toContain("chat-123");
+ expect(JSON.stringify(last.body)).toContain("data:image/png;base64,");
+ });
+
+ it("Cerebras: the WebP picture goes as a base64 PNG", async () => {
+ const f = fakes.find((x) => x.mode === "cerebras")!;
+ f.replies = [{ text: "Brighter it is." }];
+ const r = await call("cerebras", "qwen-3.8-27b", history("cerebras", getLlmModel("cerebras", "qwen-3.8-27b")!, { id: "toolu_own1" }), { effort: "max" });
+ expect(r.text).toBe("Brighter it is.");
+ expect(JSON.stringify(f.seen.at(-1)!.body)).toContain("data:image/png;base64,");
+ });
+
+ it("Mistral: tool ids go as nine letters and digits, and the picture as a plain image_url string", async () => {
+ const f = fakes.find((x) => x.mode === "mistral")!;
+ f.replies = [{ text: "Done." }];
+ const r = await call("mistral", "mistral-large-4", history("mistral", getLlmModel("mistral", "mistral-large-4")!, { id: "toolu_own1" }));
+ expect(r.text).toBe("Done.");
+ const user = (f.seen.at(-1)!.body.messages ?? []).findLast((m) => m.role === "user")!;
+ expect((user.content as { type: string; image_url?: unknown }[]).find((p) => p.type === "image_url")!.image_url).toMatch(/^data:image\/webp;base64,/);
+ });
+
+ it("DeepSeek: its own turn carries its reasoning back, another model's calls become text, and the picture stays out (text-only model)", async () => {
+ const f = fakes.find((x) => x.mode === "deepseek")!;
+ f.issued.add("call_ds1");
+ f.replies = [{ reasoning: { field: "reasoning_content", text: "Brighter means more exposure." }, text: "Brightening.", calls: [{ id: "call_ds2", name: "generate", args: { jobs: [] } }] }];
+ const r = await call("deepseek", "deepseek-v4-pro", history("deepseek", getLlmModel("deepseek", "deepseek-v4-pro")!, { id: "call_ds1", reasoning: "Thinking about foxes." }));
+ expect(r.toolCalls[0].id).toBe("call_ds2");
+ expect(r.replay).toMatchObject({ provider: "deepseek", model: "deepseek-v4-pro", reasoning: { field: "reasoning_content", text: "Brighter means more exposure." } });
+ const sent = f.seen.at(-1)!.body.messages!;
+ expect(sent.find((m) => m.tool_calls?.[0]?.id === "call_ds1")!.reasoning_content).toBe("Thinking about foxes.");
+ expect(JSON.stringify(sent)).toContain("search_models");
+ expect(sent.some((m) => m.tool_calls?.some((c) => c.id === "toolu_01AbCdEf"))).toBe(false);
+ expect(JSON.stringify(sent)).not.toContain("data:image");
+ });
+
+ it("Gemini: its own signature goes back on its call, and other models' first calls get the documented dummy", async () => {
+ const f = fakes.find((x) => x.mode === "google")!;
+ const sig = { google: { thought_signature: "c2lnLTE=" } };
+ f.replies = [{ text: "Here.", calls: [{ id: "function-call-1", name: "generate", args: { jobs: [] }, extra: { google: { thought_signature: "c2lnLTI=" } } }] }];
+ const r = await call("google", "gemini-3.8-flash", history("google", getLlmModel("google", "gemini-3.8-flash")!, { id: "toolu_own1", extra: sig }), { effort: "max" });
+ const sent = f.seen.at(-1)!.body;
+ expect(sent.reasoning_effort).toBe("high");
+ const steps = sent.messages!.filter((m) => m.tool_calls?.length);
+ expect(steps[0].tool_calls![0].extra_content).toEqual({ google: { thought_signature: GEMINI_DUMMY_SIGNATURE } });
+ expect(steps[1].tool_calls![0].extra_content).toEqual(sig);
+ expect(r.replay?.extra).toEqual({ "function-call-1": { google: { thought_signature: "c2lnLTI=" } } });
+ });
+
+ it("OpenRouter: reasoning_details go back as received to the same model only", async () => {
+ const f = fakes.find((x) => x.mode === "openrouter")!;
+ const details = [{ type: "reasoning.encrypted", data: "enc", index: 0 }];
+ f.replies = [{ reasoning: { field: "reasoning", text: "hm" }, details, text: "Ok." }];
+ const r = await call("openrouter", "x-ai/grok-4.7", [{ role: "user", content: "hi" }]);
+ expect(r.replay).toMatchObject({ provider: "openrouter", model: "x-ai/grok-4.7", details });
+ const msgs: Stored[] = [{ role: "user", content: "hi" }, { role: "assistant", content: [{ type: "text", text: "Ok." }], replay: r.replay } as Stored, { role: "user", content: "and?" }];
+ await call("openrouter", "x-ai/grok-4.7", msgs);
+ expect(f.seen.at(-1)!.body.messages![2]).toMatchObject({ role: "assistant", reasoning_details: details, reasoning: "hm" });
+ await call("openrouter", "openai/gpt-6.1-sol", msgs);
+ expect(f.seen.at(-1)!.body.messages![2]).not.toHaveProperty("reasoning_details");
+ });
+
+ it("keeps a provider id that fits Anthropic's pattern, and stores another one with the original kept for replay", async () => {
+ const f = fakes.find((x) => x.mode === "zai")!;
+ f.replies = [{ calls: [{ id: "call:7/odd id", name: "search_models", args: {} }] }];
+ const r = await call("zai", "glm-5.3", [{ role: "user", content: "hi" }]);
+ const stored = r.toolCalls[0].id;
+ expect(stored).toMatch(/^[A-Za-z0-9_-]{1,64}$/);
+ expect(r.replay?.toolIds).toEqual({ [stored]: "call:7/odd id" });
+ });
+});
+
+describe("errors, in words that say what to do", () => {
+ let f: FakeLlm;
+ beforeAll(async () => {
+ f = await fake("openai", "together");
+ });
+ const once = () => call("together", "moonshotai/Kimi-K3", [{ role: "user", content: "hi" }]);
+
+ it("a rejected key says where to fix it, without the key in the text", async () => {
+ const real = f.key;
+ f.key = "sk-other";
+ const e = (await once().catch((x) => x)) as Error;
+ f.key = real;
+ expect(e).toBeInstanceOf(HostedError);
+ expect(e.message).toMatch(/Together AI rejected the key.*Settings → AI helper → Together AI/);
+ expect(e.message).not.toContain(real.slice(3, 15));
+ });
+
+ it("no credit, a retired model, and a long chat each say so", async () => {
+ f.replies = [{ status: 402, error: { error: { message: "Insufficient balance" } } }];
+ await expect(once()).rejects.toThrow(/no credit/);
+ f.replies = [{ status: 404, error: { error: { message: "model not found" } } }];
+ await expect(once()).rejects.toThrow(/has no model moonshotai\/Kimi-K3 today/);
+ f.replies = [{ status: 400, error: { error: { message: "This model's maximum context length is 1048576 tokens", code: "context_length_exceeded" } } }];
+ await expect(once()).rejects.toBeInstanceOf(ContextError);
+ });
+
+ it("retries a 429 once after Retry-After, then says it's rate-limited", async () => {
+ f.replies = [{ status: 429, headers: { "retry-after": "0" } }, { text: "Second time lucky" }];
+ const before = f.seen.length;
+ expect((await once()).text).toBe("Second time lucky");
+ expect(f.seen.length - before).toBe(2);
+ f.replies = [{ status: 429, headers: { "retry-after": "0" } }];
+ await expect(once()).rejects.toThrow(/Together AI is rate-limited right now/);
+ // A wait longer than 30 s isn't waited for.
+ f.replies = [{ status: 503, headers: { "retry-after": "120" } }];
+ const n = f.seen.length;
+ await expect(once()).rejects.toThrow(/problem on its side/);
+ expect(f.seen.length - n).toBe(1);
+ });
+
+ it("a free model's 429 is its free limit running out", async () => {
+ const or = fakes.find((x) => x.mode === "openrouter")!;
+ or.replies = [{ status: 429, headers: { "retry-after": "0" }, error: { error: { code: 429, message: "Rate limit exceeded: free-models-per-day", metadata: { error_type: "rate_limit_exceeded" } } } }];
+ const e = await call("openrouter", "nvidia/nemotron-3-ultra-550b-a55b:free", [{ role: "user", content: "hi" }]).catch((x) => x);
+ expect(e).toBeInstanceOf(FreeLimitError);
+ expect((e as InstanceType<typeof FreeLimitError>).span).toBe("day");
+ });
+
+ it("stops before the call when the chat can't fit the model's context", async () => {
+ const big = "word ".repeat(140_000);
+ const n = f.seen.length;
+ await expect(call("together", "openai/gpt-oss-120b", [{ role: "user", content: big }])).rejects.toThrow(/This chat is too long for gpt-oss-120b/);
+ expect(f.seen.length).toBe(n);
+ });
+});
+
+describe("keys stay where they belong", () => {
+ it("never follows a redirect with the key: the second server never sees it", async () => {
+ const second = fakeLlm("openai");
+ await second.start();
+ const first = await fake("openai", "fireworks");
+ first.redirect = `${second.url}/v1/chat/completions`;
+ await expect(call("fireworks", "accounts/fireworks/models/glm-5p3", [{ role: "user", content: "hi" }])).rejects.toThrow();
+ expect(second.seen).toHaveLength(0);
+ await second.close();
+ });
+
+ it("refuses inside an account's or a guest's work, even with the key set", async () => {
+ await fake("openai", "huggingface");
+ expect(hosted.endpointFor("huggingface")).not.toBeNull();
+ expect(() => runAsTenant({ kind: "account", id: "a1" }, () => hosted.endpointFor("huggingface"))).toThrow(/studio's own/);
+ const ep = hosted.endpointFor("huggingface")!;
+ await expect(runAsTenant({ kind: "guest" }, () => hosted.chatHosted(ep, ep.provider.models[0], { messages: [{ role: "user", content: "hi" }] }))).rejects.toThrow(/studio's own/);
+ });
+
+ it("only takes a test address on this machine, and never sends a key over plain http to a public host", async () => {
+ setSetting("groqKey", "gsk_testkey0123456789");
+ process.env.FUOBE_LLM_TEST_BASE = "groq=http://example.com/v1";
+ expect(hosted.endpointFor("groq")!.baseUrl).toBe("https://api.groq.com/openai/v1");
+ const ep = { ...hosted.endpointFor("groq")!, baseUrl: "http://example.com/v1" };
+ await expect(hosted.chatHosted(ep, ep.provider.models[0], { messages: [{ role: "user", content: "hi" }] })).rejects.toThrow(/plain http/);
+ });
+
+ it("builds Qwen's host from its region and a checked workspace id only", () => {
+ setSetting("qwenKey", "sk-qwen0123456789");
+ expect(hosted.endpointFor("qwen")).toBeNull();
+ setSetting("qwenWorkspace", "ws-abc123");
+ setSetting("qwenRegion", "virginia");
+ expect(hosted.endpointFor("qwen")!.baseUrl).toBe("https://ws-abc123.us-east-1.maas.aliyuncs.com/compatible-mode/v1");
+ expect(() => setSetting("qwenWorkspace", "evil.example.com/x")).toThrow();
+ });
+
+ it("Test lists the models with the key (a free call) and says when the key is wrong", async () => {
+ const f = await fake("openai", "cerebras");
+ f.models = ["gpt-oss-120b", "qwen-3.8-27b"];
+ expect(await hosted.testHosted("cerebras")).toMatchObject({ ok: true, detail: expect.stringMatching(/Key works · 2 models/) });
+ expect(f.seen.at(-1)).toMatchObject({ method: "GET", url: "/v1/models" });
+ setSetting("cerebrasKey", "csk-wrong0123456789");
+ const r = await hosted.testHosted("cerebras");
+ expect(r.ok).toBe(false);
+ expect(r.detail).toMatch(/rejected the key/);
+ expect(r.detail).not.toContain("wrong0123456789");
+ });
+});
+
+describe("the fake itself", () => {
+ it("answers 400 to a request that breaks a rule (so the checks above mean something)", async () => {
+ const f = fakeLlm("minimax");
+ await f.start();
+ const res = await new Promise<number>((done) => {
+ const req = http.request(`${f.url}/v1/chat/completions`, { method: "POST", headers: { authorization: `Bearer ${f.key}`, "content-type": "application/json" } }, (r) => done(r.statusCode ?? 0));
+ req.end(JSON.stringify({ model: "m", stream: true, tool_choice: "auto", messages: [{ role: "system", content: "s" }] }));
+ });
+ expect(res).toBe(400);
+ await f.close();
+ });
+});
diff --git a/tests/llm-registry.test.ts b/tests/llm-registry.test.ts
new file mode 100644
index 00000000..32ba2e0d
--- /dev/null
+++ b/tests/llm-registry.test.ts
@@ -0,0 +1,153 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { ASSIST_EFFORTS } from "@/lib/assist";
+import { getLlmModel, LLM_PROVIDERS, LLM_REGISTRY_CHECKED, priceOn } from "@/lib/catalog/llm-providers";
+
+/*
+ * The provider registry is data: these checks keep it honest (official https hosts only, a price or a
+ * free status on every model, a licence on every open one, dated prices in order, nothing expired) and
+ * tied to Settings (every key is a secret setting, every region pick a validated one).
+ */
+
+process.env.FUOBE_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-registry-"));
+const { SETTINGS } = await import("@/server/settings");
+
+/** The hosts each provider's docs give. A base URL anywhere else is a mistake (or worse). */
+const OFFICIAL: Record<string, RegExp> = {
+ openai: /^(?:us\.|eu\.)?api\.openai\.com$/,
+ google: /^generativelanguage\.googleapis\.com$/,
+ xai: /^(?:us\.)?api\.x\.ai$/,
+ meta: /^api\.meta\.ai$/,
+ mistral: /^api\.mistral\.ai$/,
+ cohere: /^api\.cohere\.ai$/,
+ deepseek: /^api\.deepseek\.com$/,
+ moonshot: /^api\.moonshot\.(?:ai|cn)$/,
+ zai: /^(?:api\.z\.ai|open\.bigmodel\.cn)$/,
+ qwen: /^\{workspace\}\.(?:ap-southeast-1|us-east-1|cn-beijing|cn-hongkong|ap-northeast-1)\.maas\.aliyuncs\.com$/,
+ minimax: /^api\.minimax\.(?:io|cn)$/,
+ openrouter: /^openrouter\.ai$/,
+ groq: /^api\.groq\.com$/,
+ cerebras: /^api\.cerebras\.ai$/,
+ together: /^(?:us-)?api\.together\.ai$/,
+ fireworks: /^api\.fireworks\.ai$/,
+ huggingface: /^router\.huggingface\.co$/,
+};
+
+const hosted = LLM_PROVIDERS.filter((p) => p.adapter !== "local" && p.adapter !== "anthropic");
+const urls = (p: (typeof LLM_PROVIDERS)[number]) => [...(p.regions?.map((r) => r.baseUrl) ?? []), ...(p.baseUrl ? [p.baseUrl] : [])];
+
+describe("LLM provider registry", () => {
+ it("has unique provider ids and unique model ids within each provider", () => {
+ const ids = LLM_PROVIDERS.map((p) => p.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ for (const p of LLM_PROVIDERS) expect(new Set(p.models.map((m) => m.id)).size, p.id).toBe(p.models.length);
+ expect(LLM_REGISTRY_CHECKED).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ });
+
+ it("covers the big labs, China's providers and the hosts, with many models", () => {
+ for (const id of ["anthropic", "openai", "google", "xai", "meta", "mistral", "cohere", "deepseek", "moonshot", "zai", "qwen", "minimax", "openrouter", "groq", "cerebras", "together", "fireworks", "huggingface"]) {
+ expect(LLM_PROVIDERS.some((p) => p.id === id), id).toBe(true);
+ }
+ expect(LLM_PROVIDERS.flatMap((p) => p.models).length).toBeGreaterThan(100);
+ });
+
+ it("names only official https hosts, one per region, never a free URL", () => {
+ for (const p of hosted) {
+ const list = urls(p);
+ expect(list.length, p.id).toBeGreaterThan(0);
+ for (const u of list) {
+ expect(u.startsWith("https://"), `${p.id} ${u}`).toBe(true);
+ const host = u.slice("https://".length).split("/")[0];
+ expect(OFFICIAL[p.id]?.test(host), `${p.id} ${host}`).toBe(true);
+ }
+ if (p.regions) expect(new Set(p.regions.map((r) => r.id)).size).toBe(p.regions.length);
+ }
+ });
+
+ it("gives every model a price, a free status or a reason there's no price", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) expect(!!m.price?.length || !!m.free || !!m.priceNote, `${p.id}/${m.id}`).toBe(true);
+ }
+ });
+
+ it("keeps dated prices in order, with an open-ended last step", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) {
+ for (const steps of [m.price, m.priceCny]) {
+ if (!steps) continue;
+ const untils = steps.slice(0, -1).map((s) => s.until);
+ expect(untils.every(Boolean), `${m.id}`).toBe(true);
+ expect([...untils].sort(), m.id).toEqual(untils);
+ expect(steps.at(-1)!.until, m.id).toBeUndefined();
+ }
+ }
+ }
+ // Gemini 4 Argon's launch price ends on 30 Nov.
+ const argon = getLlmModel("google", "gemini-4-argon")!;
+ expect(priceOn(argon.price, "2026-10-31")).toMatchObject({ in: 2, out: 10 });
+ expect(priceOn(argon.price, "2026-12-01")).toMatchObject({ in: 4, out: 20 });
+ });
+
+ it("names a licence for every open-weight model, and marks non-commercial ones", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) {
+ if (m.open) expect(m.open.licence.trim().length, m.id).toBeGreaterThan(2);
+ if (m.open && /\bNC\b/.test(m.open.licence)) expect(m.open.nonCommercial, m.id).toBe(true);
+ }
+ }
+ // Weights only promised: closed until they're out.
+ expect(getLlmModel("moonshot", "kimi-k3.1-pro")!.open).toBeUndefined();
+ });
+
+ it("offers nothing expired, and no deprecated alias", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) if (m.expires) expect(m.expires >= LLM_REGISTRY_CHECKED, m.id).toBe(true);
+ }
+ const all = LLM_PROVIDERS.flatMap((p) => p.models.map((m) => m.id));
+ for (const gone of ["mistral-large-latest", "mistral-medium-3-5", "deepseek-chat", "deepseek-reasoner", "kimi-k2.6", "kimi-k2.7-code", "poolside/laguna-s-2.1:free", "poolside/laguna-xs-2.1:free", "command-a-vision-07-2025"]) {
+ expect(all, gone).not.toContain(gone);
+ }
+ });
+
+ it("calls tools on every model Smart or Free may pick, and says why when the docs don't confirm it", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) if (m.tools !== true) expect(m.note, m.id).toBeTruthy();
+ }
+ });
+
+ it("maps efforts to wire values for Fuobe's five levels only", () => {
+ const levels = new Set<string>(ASSIST_EFFORTS.map((e) => e.id));
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) for (const k of Object.keys(m.efforts ?? {})) expect(levels.has(k), `${m.id} ${k}`).toBe(true);
+ }
+ // Gemini never gets minimal or none; DeepSeek maps medium to high as it does itself.
+ expect(Object.values(getLlmModel("google", "gemini-3.8-flash")!.efforts!)).not.toContain("minimal");
+ expect(getLlmModel("deepseek", "deepseek-v4-pro")!.efforts!.medium).toBe("high");
+ });
+
+ it("points every host's copy at its maker's own model", () => {
+ for (const p of LLM_PROVIDERS) {
+ for (const m of p.models) {
+ if (!m.same) continue;
+ const [maker, ...rest] = m.same.split("/");
+ expect(getLlmModel(maker, rest.join("/")), `${p.id}/${m.id} → ${m.same}`).toBeTruthy();
+ }
+ }
+ });
+
+ it("keeps every key in a secret setting, and every region pick validated against the registry", () => {
+ const settings = SETTINGS as Record<string, { secret?: boolean; options?: readonly string[] }>;
+ for (const p of hosted) {
+ expect(p.keySetting, p.id).toBeTruthy();
+ expect(settings[p.keySetting!]?.secret, `${p.id} ${p.keySetting}`).toBe(true);
+ if (p.regions && p.regions.length > 1) {
+ expect(p.regionSetting, p.id).toBeTruthy();
+ expect(settings[p.regionSetting!]?.options, p.id).toEqual(p.regions.map((r) => r.id));
+ }
+ if (p.freePlan?.setting) expect(settings[p.freePlan.setting]?.options, p.id).toEqual(["0", "1"]);
+ }
+ expect(settings.anthropicKey.secret).toBe(true);
+ });
+});
diff --git a/tests/llm-responses.test.ts b/tests/llm-responses.test.ts
new file mode 100644
index 00000000..a684ac4c
--- /dev/null
+++ b/tests/llm-responses.test.ts
@@ -0,0 +1,126 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import type Anthropic from "@anthropic-ai/sdk";
+import { getLlmModel, getLlmProvider } from "@/lib/catalog/llm-providers";
+import { fakeLlm, type FakeLlm } from "./helpers/fake-llm";
+
+/*
+ * OpenAI direct, on the Responses API (GPT-6.x call tools only there): a stateless request
+ * (store: false) with the system prompt as instructions and flat, non-strict tools; calls and results
+ * paired by call_id; OpenAI's own turn sent back as the items it came as, so its encrypted reasoning
+ * stays with its calls (the fake refuses a call without it); and a reply cut off by the output limit.
+ */
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-llm-responses-"));
+process.env.FUOBE_DATA_DIR = dir;
+for (const k of Object.keys(process.env)) if (/_API_KEY$|^FUOBE_LLM_TEST_BASE$/.test(k)) delete process.env[k];
+
+const { setSetting } = await import("@/server/settings");
+const hosted = await import("@/server/llm/hosted");
+const { toHostedMessages } = await import("@/server/llm/hosted-messages");
+const { responsesBody } = await import("@/server/llm/responses");
+
+type Stored = Anthropic.Beta.BetaMessageParam & { replay?: unknown };
+const system = { stable: "You are Fuobe Assist.", turn: "Today: 2026-10-31." };
+const tools = [{ name: "generate", description: "Run jobs", parameters: { type: "object", properties: { jobs: { type: "array" } } } }];
+const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==";
+
+let f: FakeLlm;
+beforeAll(async () => {
+ f = fakeLlm("openai", "sk-proj-test0123456789abcdef");
+ await f.start();
+ setSetting("openaiKey", f.key);
+ process.env.FUOBE_LLM_TEST_BASE = `openai=${f.url}/v1`;
+});
+afterAll(async () => {
+ await f.close();
+ delete process.env.FUOBE_LLM_TEST_BASE;
+ try {
+ fs.rmSync(dir, { recursive: true, force: true });
+ } catch {}
+});
+
+const sol = () => getLlmModel("openai", "gpt-6.1-sol")!;
+async function step(msgs: Stored[], model = sol(), effort: "low" | "medium" | "max" = "medium") {
+ const ep = hosted.endpointFor("openai")!;
+ return hosted.chatHosted(ep, model, { messages: toHostedMessages(system, msgs as never, { provider: getLlmProvider("openai")!, model }), tools, effort });
+}
+
+describe("OpenAI's Responses API", () => {
+ it("sends a stateless request: instructions, input items, flat tools that aren't strict, the effort", () => {
+ const b = responsesBody(sol(), {
+ messages: [
+ { role: "system", content: "Be brief." },
+ { role: "user", content: "A fox", images: [{ data: PNG, contentType: "image/png" }] },
+ ],
+ tools,
+ effort: "max",
+ maxTokens: 64_000,
+ });
+ expect(b).toMatchObject({ model: "gpt-6.1-sol", instructions: "Be brief.", store: false, stream: true, tool_choice: "auto", parallel_tool_calls: true, reasoning: { effort: "max" }, max_output_tokens: 64_000 });
+ expect(b.tools).toEqual([{ type: "function", name: "generate", description: "Run jobs", parameters: tools[0].parameters, strict: false }]);
+ expect(b.input).toEqual([{ role: "user", content: [{ type: "input_image", image_url: `data:image/png;base64,${PNG}` }, { type: "input_text", text: "A fox" }] }]);
+ expect(b).not.toHaveProperty("messages");
+ // A level the model doesn't offer sends none.
+ expect(responsesBody(getLlmModel("openai", "gpt-5.4-mini")!, { messages: [{ role: "user", content: "x" }], effort: "max", maxTokens: 10 })).not.toHaveProperty("reasoning");
+ });
+
+ it("runs a tool loop: OpenAI's turn goes back with its encrypted reasoning, results pair by call_id", async () => {
+ const turn = [
+ { type: "reasoning", id: "rs_1", summary: [], encrypted_content: "gAAAA-secret-thinking" },
+ { type: "message", id: "msg_1", role: "assistant", status: "completed", content: [{ type: "output_text", text: "Making it.", annotations: [] }] },
+ { type: "function_call", id: "fc_1", call_id: "call_abc123", name: "generate", arguments: '{"jobs":[]}', status: "completed" },
+ ];
+ f.replies = [{ output: turn }];
+ const first: Stored[] = [{ role: "user", content: "A fox in snow" }];
+ const r = await step(first);
+ expect(r).toMatchObject({ text: "Making it.", stop: "tool_use", thought: true, toolCalls: [{ id: "call_abc123", name: "generate", input: { jobs: [] } }] });
+ expect(r.replay).toMatchObject({ provider: "openai", model: "gpt-6.1-sol", items: turn });
+ expect(r.usage).toMatchObject({ input: 900, output: 40, reasoning: 12 });
+
+ f.replies = [{ text: "Started." }];
+ const second: Stored[] = [
+ ...first,
+ { role: "assistant", content: [{ type: "text", text: "Making it." }, { type: "tool_use", id: "call_abc123", name: "generate", input: { jobs: [] } }], replay: r.replay } as Stored,
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "call_abc123", content: '{"started":["g1"]}' }] },
+ ];
+ expect((await step(second)).text).toBe("Started.");
+ const input = f.chats().at(-1)!.input as Record<string, unknown>[];
+ expect(input.slice(1, 4)).toEqual(turn);
+ expect(input[4]).toEqual({ type: "function_call_output", call_id: "call_abc123", output: '{"started":["g1"]}' });
+
+ // Another OpenAI model gets the turn as plain items (no stored item ids, no reasoning), which it takes.
+ f.replies = [{ text: "Terra here." }];
+ expect((await step(second, getLlmModel("openai", "gpt-6.1-terra")!)).text).toBe("Terra here.");
+ const plain = f.chats().at(-1)!.input as Record<string, unknown>[];
+ expect(plain.some((i) => i.type === "reasoning")).toBe(false);
+ expect(plain).toContainEqual({ type: "function_call", call_id: "call_abc123", name: "generate", arguments: '{"jobs":[]}' });
+ // The stored call without the reasoning it followed is what OpenAI (and the fake) refuse.
+ const broken = second.map((m) => (m.replay ? { ...m, replay: { ...(m.replay as object), items: turn.slice(1) } } : m));
+ await expect(step(broken)).rejects.toThrow(/required 'reasoning' item/);
+ });
+
+ it("sends another model's turn as plain items, and says when the reply hit the output limit", async () => {
+ f.replies = [{ incomplete: true, output: [{ type: "reasoning", id: "rs_9", summary: [] }] }];
+ const msgs: Stored[] = [
+ { role: "user", content: "hi" },
+ { role: "assistant", content: [{ type: "tool_use", id: "toolu_01Claude", name: "generate", input: {} }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01Claude", content: "ok" }, { type: "text", text: "now?" }] },
+ ];
+ const r = await step(msgs);
+ expect(r.stop).toBe("length");
+ const input = f.chats().at(-1)!.input as Record<string, unknown>[];
+ expect(input[1]).toEqual({ type: "function_call", call_id: "toolu_01Claude", name: "generate", arguments: "{}" });
+ expect(input[2]).toEqual({ type: "function_call_output", call_id: "toolu_01Claude", output: "ok" });
+ });
+
+ it("turns a failed key into plain words, without the key", async () => {
+ setSetting("openaiKey", "sk-proj-wrong0123456789abcdef");
+ const e = (await step([{ role: "user", content: "hi" }]).catch((x) => x)) as Error;
+ setSetting("openaiKey", f.key);
+ expect(e.message).toMatch(/OpenAI rejected the key/);
+ expect(e.message).not.toContain("wrong0123456");
+ });
+});
diff --git a/tests/llm-sse.test.ts b/tests/llm-sse.test.ts
new file mode 100644
index 00000000..31db81b7
--- /dev/null
+++ b/tests/llm-sse.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from "vitest";
+import { readChatStream, StreamError } from "@/server/llm/sse";
+
+/*
+ * The Chat Completions stream reader that every hosted provider goes through: the shapes their docs
+ * describe (comment lines, tool arguments in pieces, Gemini signatures in a chunk with no text,
+ * Mistral's content chunks, the three places usage turns up, errors inside a 200 stream).
+ */
+
+/** A body that arrives in awkward pieces: `cut` characters at a time, splitting lines and JSON. */
+function body(events: (string | object)[], cut = 7): ReadableStream<Uint8Array> {
+ const text = events.map((e) => (typeof e === "string" ? e : `data: ${JSON.stringify(e)}\n\n`)).join("");
+ const bytes = new TextEncoder().encode(text);
+ let i = 0;
+ return new ReadableStream({
+ pull(c) {
+ if (i >= bytes.length) return c.close();
+ c.enqueue(bytes.slice(i, i + cut));
+ i += cut;
+ },
+ });
+}
+
+const chunk = (delta: object, finish: string | null = null, extra: object = {}) => ({ id: "c1", object: "chat.completion.chunk", model: "m", choices: [{ index: 0, delta, finish_reason: finish }], ...extra });
+
+describe("readChatStream", () => {
+ it("skips comment and empty lines, joins text, and ends at [DONE]", async () => {
+ const r = await readChatStream(body([": OPENROUTER PROCESSING\n\n", ": keep-alive\n\n", chunk({ role: "assistant", content: "Hel" }), chunk({ content: "lo" }), chunk({}, "stop"), "data: [DONE]\n\n", "data: {not json after done\n\n"]));
+ expect(r.text).toBe("Hello");
+ expect(r.finish).toBe("stop");
+ expect(r.toolCalls).toEqual([]);
+ });
+
+ it("joins tool arguments split over chunks, for two parallel calls, keeping the first id and name", async () => {
+ const r = await readChatStream(
+ body([
+ chunk({ tool_calls: [{ index: 0, id: "call_a", type: "function", function: { name: "search_models", arguments: '{"ki' } }] }),
+ chunk({ tool_calls: [{ index: 1, id: "call_b", type: "function", function: { name: "list_elements", arguments: "" } }] }),
+ chunk({ tool_calls: [{ index: 0, function: { arguments: 'nd":"image"}' } }] }),
+ chunk({ tool_calls: [{ index: 1, function: { arguments: "{}" } }] }),
+ chunk({}, "tool_calls"),
+ "data: [DONE]\n\n",
+ ]),
+ );
+ expect(r.toolCalls).toEqual([
+ { id: "call_a", name: "search_models", arguments: '{"kind":"image"}' },
+ { id: "call_b", name: "list_elements", arguments: "{}" },
+ ]);
+ expect(r.finish).toBe("tool_calls");
+ });
+
+ it("keeps Gemini's signature when it arrives in a chunk with no text", async () => {
+ const sig = { google: { thought_signature: "c2lnLTE=" } };
+ const r = await readChatStream(
+ body([chunk({ tool_calls: [{ index: 0, id: "f1", type: "function", function: { name: "generate", arguments: "{}" } }] }), chunk({ content: "", tool_calls: [{ index: 0, extra_content: sig }] }), chunk({}, "tool_calls")]),
+ );
+ expect(r.toolCalls[0]).toEqual({ id: "f1", name: "generate", arguments: "{}", extra: sig });
+ });
+
+ it("reads Mistral's content chunks: thinking apart from the answer", async () => {
+ const r = await readChatStream(
+ body([chunk({ content: [{ type: "thinking", thinking: [{ type: "text", text: "Let me think." }] }] }), chunk({ content: [{ type: "text", text: "A fox" }] }), chunk({ content: " in snow." }, "stop")]),
+ );
+ expect(r.text).toBe("A fox in snow.");
+ expect(r.reasoning).toEqual({ field: "thinking", text: "Let me think." });
+ });
+
+ it("reads reasoning_content and reasoning under their own names, and OpenRouter's reasoning_details", async () => {
+ const a = await readChatStream(body([chunk({ reasoning_content: "Step 1. " }), chunk({ reasoning_content: "Step 2." }), chunk({ content: "Done" }, "stop")]));
+ expect(a.reasoning).toEqual({ field: "reasoning_content", text: "Step 1. Step 2." });
+ const b = await readChatStream(
+ body([
+ chunk({ reasoning: "Hm", reasoning_details: [{ type: "reasoning.text", text: "Hm", index: 0 }] }),
+ chunk({ reasoning: "m.", reasoning_details: [{ type: "reasoning.text", text: "m.", index: 0, signature: "sig" }] }),
+ chunk({ reasoning_details: [{ type: "reasoning.encrypted", data: "ZW5j", index: 1 }] }),
+ chunk({ content: "Ok" }, "stop"),
+ ]),
+ );
+ expect(b.reasoning).toEqual({ field: "reasoning", text: "Hmm." });
+ expect(b.details).toEqual([
+ { type: "reasoning.text", text: "Hmm.", index: 0, signature: "sig" },
+ { type: "reasoning.encrypted", data: "ZW5j", index: 1 },
+ ]);
+ });
+
+ it("finds usage in all three places providers put it", async () => {
+ // OpenAI: a last chunk with no choices.
+ const a = await readChatStream(body([chunk({ content: "x" }, "stop"), { id: "c1", choices: [], usage: { prompt_tokens: 900, completion_tokens: 20, prompt_tokens_details: { cached_tokens: 800 } } }]));
+ expect(a.usage).toEqual({ input: 900, output: 20, cached: 800 });
+ // OpenRouter: one choice with an empty delta.
+ const b = await readChatStream(body([chunk({ content: "x" }), chunk({}, "stop", { usage: { prompt_tokens: 10, completion_tokens: 5, completion_tokens_details: { reasoning_tokens: 3 } } })]));
+ expect(b.usage).toEqual({ input: 10, output: 5, reasoning: 3 });
+ // Together: details flat in usage.
+ const c = await readChatStream(body([chunk({ content: "x" }, "stop", { usage: { prompt_tokens: 7, completion_tokens: 2, cached_tokens: 4 } })]));
+ expect(c.usage).toEqual({ input: 7, output: 2, cached: 4 });
+ });
+
+ it("fails on an error chunk or finish_reason error, with the provider's words", async () => {
+ await expect(readChatStream(body([chunk({ content: "x" }), { error: { message: "Provider returned error", code: 502 }, choices: [{ index: 0, delta: {}, finish_reason: "error" }] }]))).rejects.toMatchObject({
+ message: "Provider returned error",
+ status: 502,
+ });
+ await expect(readChatStream(body([chunk({ content: "x" }, "error")]))).rejects.toBeInstanceOf(StreamError);
+ });
+
+ it("turns MiniMax's base_resp errors in a 200 stream into statuses", async () => {
+ const err = (code: number) => readChatStream(body([{ id: "x", choices: [], base_resp: { status_code: code, status_msg: `code ${code}` } }]), { errorEnvelope: "minimax" });
+ await expect(err(1002)).rejects.toMatchObject({ status: 429 });
+ await expect(err(1004)).rejects.toMatchObject({ status: 401 });
+ await expect(err(1008)).rejects.toMatchObject({ status: 402 });
+ await expect(err(2013)).rejects.toMatchObject({ status: 400 });
+ // status_code 0 is success.
+ const ok = await readChatStream(body([chunk({ content: "fine" }, "stop", { base_resp: { status_code: 0, status_msg: "" } })]), { errorEnvelope: "minimax" });
+ expect(ok.text).toBe("fine");
+ });
+
+ it("gives up when nothing arrives for too long, but keep-alives count", async () => {
+ const enc = new TextEncoder();
+ let n = 0;
+ const alive = new ReadableStream<Uint8Array>({
+ async pull(c) {
+ await new Promise((r) => setTimeout(r, 40));
+ if (n++ < 4) c.enqueue(enc.encode(": keep-alive\n\n"));
+ else {
+ c.enqueue(enc.encode(`data: ${JSON.stringify(chunk({ content: "late" }, "stop"))}\n\n`));
+ c.close();
+ }
+ },
+ });
+ expect((await readChatStream(alive, { idleMs: 120 })).text).toBe("late");
+ const silent = new ReadableStream<Uint8Array>({ pull: () => new Promise(() => {}) });
+ await expect(readChatStream(silent, { idleMs: 60 })).rejects.toMatchObject({ idle: true });
+ });
+
+ it("reads a body that ends without [DONE] or a final blank line", async () => {
+ const r = await readChatStream(body([chunk({ content: "a" }), `data: ${JSON.stringify(chunk({ content: "b" }, "stop"))}`], 3));
+ expect(r.text).toBe("ab");
+ expect(r.finish).toBe("stop");
+ });
+});