Skip to content
1 change: 1 addition & 0 deletions packages/ai/src/env-api-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ function getApiKeyEnvVars(provider: string): readonly string[] | undefined {
zai: "ZAI_API_KEY",
"zai-coding-cn": "ZAI_CODING_CN_API_KEY",
mistral: "MISTRAL_API_KEY",
"mistral-vibe": "MISTRAL_VIBE_API_KEY",
minimax: "MINIMAX_API_KEY",
"minimax-cn": "MINIMAX_CN_API_KEY",
moonshotai: "MOONSHOT_API_KEY",
Expand Down
2 changes: 2 additions & 0 deletions packages/ai/src/providers/all.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { metaProvider } from "./meta.ts";
import { minimaxProvider } from "./minimax.ts";
import { minimaxCnProvider } from "./minimax-cn.ts";
import { mistralProvider } from "./mistral.ts";
import { mistralVibeProvider } from "./mistral-vibe.ts";
import { moonshotaiProvider } from "./moonshotai.ts";
import { moonshotaiCnProvider } from "./moonshotai-cn.ts";
import { nvidiaProvider } from "./nvidia.ts";
Expand Down Expand Up @@ -159,6 +160,7 @@ export function builtinProviders(): Provider[] {
minimaxProvider(),
minimaxCnProvider(),
mistralProvider(),
mistralVibeProvider(),
moonshotaiProvider(),
moonshotaiCnProvider(),
nvidiaProvider(),
Expand Down
71 changes: 71 additions & 0 deletions packages/ai/src/providers/mistral-vibe-transport.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/** Normalize typed Mistral text/thinking chunks for the OpenAI SSE adapter. */
export function normalizeMistralDelta(delta: Record<string, unknown>): void {
if (!Array.isArray(delta.content)) return;
let text = "";
let thinking = "";
const unpack = (value: unknown): string => {
if (typeof value === "string") return value;
if (!Array.isArray(value)) throw new Error("Unsupported Mistral content block");
return value.map((block) => {
if (!block || typeof block !== "object" || block.type !== "text" || typeof block.text !== "string") {
throw new Error("Unsupported Mistral content block");
}
return block.text;
}).join("");
};
for (const block of delta.content) {
if (!block || typeof block !== "object") throw new Error("Unsupported Mistral streamed content block");
if (block.type === "text") text += unpack(block.text);
else if (block.type === "thinking") thinking += unpack(block.thinking);
else throw new Error("Unsupported Mistral streamed content block");
}
delta.content = text;
if (thinking) {
delta.reasoning_content = (typeof delta.reasoning_content === "string" ? delta.reasoning_content : "") + thinking;
}
}

export function normalizeMistralStream(response: Response): Response {
if (!response.ok || !response.body || !response.headers.get("content-type")?.includes("text/event-stream")) {
return response;
}
let pending = "";
const normalizeLine = (line: string): string => {
if (!line.startsWith("data:")) return line;
const data = line.slice(5).trim();
if (!data || data === "[DONE]") return line;
let parsed: unknown;
try {
parsed = JSON.parse(data);
} catch {
return line;
}
if (parsed && typeof parsed === "object" && "choices" in parsed && Array.isArray(parsed.choices)) {
for (const choice of parsed.choices) {
if (choice?.delta && typeof choice.delta === "object") normalizeMistralDelta(choice.delta);
}
}
return `data: ${JSON.stringify(parsed)}`;
};
const body = response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(new TransformStream<string, string>({
transform(chunk, controller) {
pending += chunk;
let index = pending.indexOf("\n");
while (index !== -1) {
controller.enqueue(`${normalizeLine(pending.slice(0, index).replace(/\r$/, ""))}\n`);
pending = pending.slice(index + 1);
index = pending.indexOf("\n");
}
},
flush(controller) {
if (pending) controller.enqueue(normalizeLine(pending));
},
}))
.pipeThrough(new TextEncoderStream());
const headers = new Headers(response.headers);
headers.delete("content-length");
headers.delete("content-encoding");
return new Response(body, { status: response.status, statusText: response.statusText, headers });
}
215 changes: 215 additions & 0 deletions packages/ai/src/providers/mistral-vibe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
import { openAICompletionsApi } from "../api/openai-completions.lazy.ts";
import { envApiKeyAuth } from "../auth/helpers.ts";
import type { Credential } from "../auth/types.ts";
import { createProvider, isModelType, type Provider } from "../models.ts";
import type { Model, SimpleStreamOptions } from "../types.ts";
import { normalizeMistralStream } from "./mistral-vibe-transport.ts";

const ID = "mistral-vibe";
const BASE_URL = "https://api.mistral.ai/v1";
const FALLBACK_MODEL = "mistral-vibe-cli-latest";
const CATALOG_TTL = 60 * 60 * 1000;

async function fingerprint(key: string): Promise<string> {
const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}

function credentialKey(credential?: Credential): string | undefined {
const envKey = typeof process !== "undefined" ? process.env.MISTRAL_VIBE_API_KEY?.trim() : undefined;
return (credential?.type === "api_key" ? credential.key?.trim() : undefined) || envKey;
}

/** Mistral does not return pricing metadata. Zero here is a placeholder, not free inference. */
export function mistralVibeModel(id: string, row: Record<string, unknown> = {}): Model<"openai-completions"> {
const capabilities =
row.capabilities && typeof row.capabilities === "object"
? (row.capabilities as Record<string, unknown>)
: {};
const reported = row.max_context_length;
const contextWindow =
typeof reported === "number" && Number.isSafeInteger(reported) && reported > 0 ? reported : 128_000;
const maxTokens = Math.min(contextWindow, id === "deepseek-v4-1-flash-1017" ? 65_536 : 8192);
return {
id,
name: typeof row.name === "string" && row.name ? row.name : id,
provider: ID,
api: "openai-completions",
baseUrl: BASE_URL,
reasoning: false,
input: capabilities.vision === true ? ["text", "image"] : ["text"],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow,
maxTokens,
compat: {
supportsStore: false,
supportsDeveloperRole: false,
supportsReasoningEffort: false,
maxTokensField: "max_tokens",
},
};
}

/** Only expose chat-capable models; the list depends on the current Vibe key. */
export function parseMistralVibeCatalog(payload: unknown): Model<"openai-completions">[] {
if (!payload || typeof payload !== "object" || !("data" in payload) || !Array.isArray(payload.data)) {
throw new Error("Invalid Mistral Vibe model catalog");
}
const result = new Map<string, Model<"openai-completions">>();
for (const entry of payload.data) {
if (!entry || typeof entry !== "object") continue;
const row = entry as Record<string, unknown>;
if (typeof row.id !== "string" || !row.id.trim() || row.id !== row.id.trim()) continue;
const capabilities = row.capabilities;
if (
!capabilities ||
typeof capabilities !== "object" ||
(capabilities as Record<string, unknown>).completion_chat !== true
) continue;
result.set(row.id, mistralVibeModel(row.id, row));
}
return [...result.values()];
}

/**
* The Vibe subscription key is independent of MISTRAL_API_KEY and the normal
* Mistral Conversations provider. Only the dedicated key is used here.
*/
export function mistralVibeProvider(fetcher: typeof fetch = fetch): Provider<"openai-completions"> {
const fallback = mistralVibeModel(FALLBACK_MODEL);
let catalog: Model<"openai-completions">[] = [fallback];
let currentScope: string | undefined;
let activeKey: string | undefined;
// filterModels is synchronous, but AuthContext.env is async.
// Capture the effective key during auth resolution.
let lastResolvedKey: string | undefined;
let refreshedAt = 0;
const api = openAICompletionsApi();
const apiKeyAuth = envApiKeyAuth("Mistral Vibe API key", ["MISTRAL_VIBE_API_KEY"]);

const requestOptions = (model: Model<"openai-completions">, options: SimpleStreamOptions = {}): SimpleStreamOptions => {
const key = options.apiKey?.trim();
if (!key) throw new Error("Missing Mistral Vibe API key");
if (model.baseUrl.replace(/\/$/, "") !== BASE_URL) throw new Error("Mistral Vibe endpoint override blocked");
if (
model.id !== FALLBACK_MODEL &&
(activeKey !== key || !catalog.some((candidate) => candidate.id === model.id))
) throw new Error("Model not found in the current Mistral Vibe key's catalog");
const transport = options.fetch ?? fetcher;
return {
...options,
maxRetries: 0,
fetch: async (input, init) => {
const url = new URL(input instanceof Request ? input.url : String(input));
if (url.href !== `${BASE_URL}/chat/completions`) {
throw new Error("Mistral Vibe request destination blocked");
}
return normalizeMistralStream(await transport(input, { ...init, redirect: "error" }));
},
onPayload: async (payload, currentModel) => {
const replacement = await options.onPayload?.(payload, currentModel);
const body = { ...((replacement ?? payload) as Record<string, unknown>) };
if (body.model !== model.id) throw new Error("Mistral Vibe model substitution blocked");
if (Array.isArray(body.messages)) {
body.messages = body.messages.map((message: unknown) => {
if (!message || typeof message !== "object" || !("role" in message) || message.role !== "assistant") {
return message;
}
const cleaned = { ...(message as Record<string, unknown>) };
for (const field of ["reasoning_content", "reasoning_text", "reasoning", "reasoning_details"]) {
delete cleaned[field];
}
return cleaned;
});
}
return body;
},
};
};

const base = createProvider<"openai-completions">({
id: ID,
name: "Mistral Vibe (unofficial)",
baseUrl: BASE_URL,
auth: {
apiKey: {
...apiKeyAuth,
async resolve(input) {
const result = await apiKeyAuth.resolve(input);
lastResolvedKey = result?.auth.apiKey?.trim();
return result;
},
},
},
models: [],
api: {
...api,
stream: (model, context, options) => api.stream(model, context, requestOptions(model as Model<"openai-completions">, options)),
streamSimple: (model, context, options) =>
api.streamSimple(model, context, requestOptions(model as Model<"openai-completions">, options)),
},
});

return {
...base,
getModels: () => catalog,
filterModels: (models, credential) => {
// checkAuth resolves the effective key before getAvailable invokes this filter.
const key = lastResolvedKey ?? credentialKey(credential);
return key && activeKey === key
? models
: models.filter((model) => model.id === FALLBACK_MODEL);
},
async refreshModels(context) {
const key = credentialKey(context.credential);
// The first refresh phase runs without network access and can receive no
// credential when the key comes from an injected AuthContext. Keep the
// last known catalog until the resolved credential is available in phase two.
// Otherwise every refresh deletes the cache before discovering the same key.
if (!context.allowNetwork && !key) return;
const nextScope = key ? await fingerprint(key) : undefined;
if (currentScope !== nextScope) {
const restored =
nextScope && context.stored?.etag === nextScope
? context.stored.models.filter(
(model): model is Model<"openai-completions"> =>
model.provider === ID && model.api === "openai-completions" &&
isModelType(model, "chat") && model.baseUrl === BASE_URL,
)
: [];
const result = await context.publish({
...(context.stored?.etag !== nextScope ? { persist: null } : {}),
update: () => {
catalog = restored.length ? restored : [fallback];
currentScope = nextScope;
activeKey = key;
refreshedAt = 0;
},
});
if (!result) return;
}
if (!key || !context.allowNetwork || context.signal.aborted) return;
if (context.baseUrl && context.baseUrl.replace(/\/$/, "") !== BASE_URL) {
throw new Error("Mistral Vibe catalog endpoint override blocked");
}
if (!context.force && refreshedAt && Date.now() - refreshedAt < CATALOG_TTL) return;
const response = await fetcher(`${BASE_URL}/models`, {
headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
signal: AbortSignal.any([context.signal, AbortSignal.timeout(8000)]),
redirect: "error",
});
if (!response.ok) throw new Error(`Mistral Vibe model discovery failed (HTTP ${response.status})`);
const discovered = parseMistralVibeCatalog(await response.json());
const refreshed = [fallback, ...discovered.filter((model) => model.id !== FALLBACK_MODEL)];
await context.publish({
persist: { models: refreshed, etag: nextScope, checkedAt: Date.now() },
update: () => {
catalog = refreshed;
currentScope = nextScope;
activeKey = key;
refreshedAt = Date.now();
},
});
},
};
}
1 change: 1 addition & 0 deletions packages/ai/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ export type KnownProvider =
| "zai"
| "zai-coding-cn"
| "mistral"
| "mistral-vibe"
| "minimax"
| "minimax-cn"
| "moonshotai"
Expand Down
Loading
Loading