Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ Log in with `/connect` and the provider shows up. Switch providers on or off in
| [Gemini CLI](docs/readme/providers.md#gemini-cli)\* | Business |
| GitHub Copilot | Personal · [Business](docs/readme/providers.md#github-copilot)\* |
| [Google AGY](docs/readme/providers.md#google-agy-quick-setup)\* | Personal · Business |
| Mistral AI | Personal · Business |
| Ollama Cloud | Personal |
| OpenAI | Personal · Business |
| OpenCode Go | Personal |
Expand Down
4 changes: 4 additions & 0 deletions docs/readme/providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ Most providers work automatically. `Automatic` means OpenCode Quota reuses the l
| Cursor | [Needs setup](#cursor) | Local estimate | Budget and spend |
| GitHub Copilot | Automatic | Remote API | Budget and usage |
| Google AGY | [Needs setup](#google-agy-quick-setup) | Remote API | Quota |
| Mistral AI | Automatic | Remote API | Budget |
| Ollama Cloud | Automatic | Remote API | Quota and balance |
| OpenAI | Automatic | Remote API | Quota and credits |
| OpenCode Go | Automatic | Remote API | Quota |
Expand All @@ -45,13 +46,16 @@ Most providers work automatically. `Automatic` means OpenCode Quota reuses the l
| Gemini CLI | [Needs setup](#gemini-cli) | Remote API | Quota |
| GitHub Copilot | [Needs setup](#github-copilot) | Remote API | Budget and usage |
| Google AGY | [Needs setup](#google-agy-quick-setup) | Remote API | Quota |
| Mistral AI | Automatic | Remote API | Budget |
| OpenAI | Automatic | Remote API | Quota and credits |
| OpenCode Zen | Automatic | Remote API | Budget and balance |
| OpenRouter | Automatic | Remote API | Budget and spend |
| xAI | Automatic | Remote API | Quota |

These tables show which plans a vendor sells. Except for Copilot organization/enterprise billing, each integration reports one signed-in account, seat, API key, or workspace.

Mistral AI uses `MISTRAL_API_KEY`, an OpenCode Mistral API-key login, or the configured Mistral key. It queries the budget API and console `whoami` API with that key. The plan type selects **Vibe budget** for Chat or **API budget** for API; if the matching budget is unavailable, no other budget is substituted.

</details>

### Chinese providers
Expand Down
12 changes: 12 additions & 0 deletions src/lib/provider-registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,18 @@ export const QUOTA_PROVIDER_REGISTRATION_SOURCE = [
skipBrokenLogins: true,
},
},
{
id: "mistral",
label: "Mistral AI",
runtimeIds: ["mistral"],
synonyms: ["mistralai"],
rowKeys: ["vibe_budget", "api_budget"],
apiKey: {
envVars: ["MISTRAL_API_KEY"],
providerKeys: ["mistral"],
skipBrokenLogins: true,
},
},
{
id: "xai",
label: "xAI",
Expand Down
1 change: 1 addition & 0 deletions src/lib/quota-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1145,6 +1145,7 @@ const DEBUG_DETAILS = {
zai: {},
zhipu: {},
deepseek: {},
mistral: {},
xai: {},
"minimax-coding-plan": { api_endpoint: oneOf("international", "china") },
"minimax-china-coding-plan": { api_endpoint: oneOf("international", "china") },
Expand Down
149 changes: 149 additions & 0 deletions src/providers/mistral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/** Mistral AI: select the budget belonging to the key's Chat/Vibe or API plan. */
import { API_KEY_VENDORS, readVendorKeys } from "../lib/api-key-resolver.js";
import { sanitizeDisplaySnippet } from "../lib/display-sanitize.js";
import type { QuotaProvider, QuotaProviderContext } from "../lib/entries.js";
import { errorWords, failureFacts, requestJson } from "../lib/http.js";
import { isRecord, nonEmptyString } from "../lib/json-guards.js";
import { modelProviderIncludesAny } from "../lib/provider-model-matching.js";
import { accountingDecimalFromNumber } from "./accounting-decimal.js";
import { vendorKeysPolicy } from "./cache-policies.js";
import {
failedAccount,
fetchError,
type ProviderFetchResult,
type ProviderRow,
} from "./contract.js";
import { fetchStoredKeys, isKeyVendorAvailable } from "./key-vendor.js";
import { vendorKeyDetails } from "./result-helpers.js";

const BUDGET_URL = "https://api.mistral.ai/v1/billing/budget";
const WHOAMI_URL = "https://console.mistral.ai/api/vibe/whoami";
const NAME = "Mistral AI";
const SPEC = API_KEY_VENDORS.mistral;

type BudgetResult = { row: ProviderRow; plan: string };
type FetchResult = BudgetResult | { error: string; facts?: ReturnType<typeof failureFacts> };

function parseBudget(budget: unknown, identity: unknown): BudgetResult {
if (!isRecord(identity)) throw new Error("Mistral plan response has an unexpected shape");
const planType = nonEmptyString(identity.plan_type)?.toUpperCase();
const key = planType === "CHAT" ? "vibe_budget" : planType === "API" ? "api_budget" : null;
if (!key) throw new Error("Mistral plan type is unavailable or unsupported");
if (!isRecord(budget)) throw new Error("Mistral budget response has an unexpected shape");
// The top-level budget can refer to API even for a Chat plan. Never substitute it for a
// missing plan-specific section: that could report a different, unenforced limit.
const section = budget[key];
if (!isRecord(section)) throw new Error(`Mistral ${key} is unavailable`);
const percentage = section.usage_percentage;
const limit = section.initial_budget;
const currency = nonEmptyString(section.currency)?.toUpperCase();
if (
typeof percentage !== "number" ||
!Number.isFinite(percentage) ||
percentage < 0 ||
typeof limit !== "number" ||
!Number.isFinite(limit) ||
limit < 0 ||
!currency ||
!/^[A-Z]{3}$/.test(currency)
) {
throw new Error(`Mistral ${key} has invalid budget values`);
}
const reset = nonEmptyString(section.reset_at);
const resetMs = reset ? Date.parse(reset) : NaN;
const unit = { kind: "currency" as const, code: currency };
const row: ProviderRow = {
key,
label: planType === "CHAT" ? "Vibe budget" : "API budget",
type: "budget",
method: "remote_api",
authority: "provider_reported",
prominence: "primary",
window: "month",
percentRemaining: Math.max(0, Math.min(100, 100 - percentage)),
limit: { decimal: accountingDecimalFromNumber(limit), unit },
...(Number.isFinite(resetMs) ? { resetsAt: new Date(resetMs).toISOString() } : {}),
};
return { row, plan: planType === "CHAT" ? "Vibe" : "API" };
}

async function queryBudget(apiKey: string, timeoutMs?: number): Promise<FetchResult> {
const options = {
method: "GET" as const,
headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
secrets: [apiKey],
timeoutMs,
};
const identityReply = await requestJson(WHOAMI_URL, options);
if (!identityReply.ok) {
const { failure } = identityReply;
return {
error:
failure.kind === "http"
? `Mistral plan API error ${failure.status}${errorWords(sanitizeDisplaySnippet(failure.detail, 120))}`
: failure.detail,
facts: failureFacts(failure),
};
}
const reply = await requestJson(BUDGET_URL, options);
if (!reply.ok) {
const { failure } = reply;
return {
error:
failure.kind === "http"
? `Mistral budget API error ${failure.status}${errorWords(sanitizeDisplaySnippet(failure.detail, 120))}`
: failure.detail,
facts: failureFacts(failure),
};
}
try {
return parseBudget(reply.json, identityReply.json);
} catch (error) {
return { error: error instanceof Error ? error.message : "Invalid Mistral budget response" };
}
}

export const mistralProvider: QuotaProvider = {
id: "mistral",
cachePolicy: vendorKeysPolicy("mistral"),
async isAvailable(ctx: QuotaProviderContext): Promise<boolean> {
return isKeyVendorAvailable({
ctx,
providerId: "mistral",
availability: "listed-or-key",
readKeys: () => readVendorKeys(SPEC, ctx.locationDirectory),
});
},
matchesCurrentModel(model: string): boolean {
return modelProviderIncludesAny(model, ["mistral"]);
},
async fetch(ctx: QuotaProviderContext): Promise<ProviderFetchResult> {
const keys = await readVendorKeys(SPEC, ctx.locationDirectory);
const debug = vendorKeyDetails(SPEC, keys, ctx.locationDirectory);
const query = (key: string) => queryBudget(key, ctx.config?.requestTimeoutMs);
if (keys.envOrConfig) {
const result = await query(keys.envOrConfig.key);
return {
attempted: true,
accounts: [
"row" in result
? { name: result.plan, rows: [result.row], errors: [] }
: failedAccount(NAME, result.error, result.facts),
],
debug,
};
}
const { attempted, accounts } = await fetchStoredKeys({
providerName: NAME,
keys,
brokenFirst: false,
async fetchKey(key) {
const result = await query(key);
return "row" in result
? { rows: [result.row], errors: [], fallbackName: result.plan }
: { rows: [], errors: [fetchError(result.error, result.facts)] };
},
});
return { attempted, accounts, debug };
},
};
2 changes: 2 additions & 0 deletions src/providers/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
minimaxChinaCodingPlanProvider,
minimaxCodingPlanProvider,
} from "./minimax-coding-plan.js";
import { mistralProvider } from "./mistral.js";
import { ollamaCloudProvider } from "./ollama-cloud.js";
import { openaiProvider } from "./openai.js";
import { opencodeGoProvider } from "./opencode-go.js";
Expand Down Expand Up @@ -51,6 +52,7 @@ const PROVIDERS_BY_ID = {
"kimi-code-plan-global": kimiCodePlanGlobalProvider,
"kimi-code-plan-cn": kimiCodePlanCnProvider,
deepseek: deepseekProvider,
mistral: mistralProvider,
xai: xaiProvider,
xiaomi: xiaomiProvider,
"opencode-go": opencodeGoProvider,
Expand Down
7 changes: 7 additions & 0 deletions tests/lib.api-key-resolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ const EXPECTED_API_KEY_VENDORS: Record<string, ApiKeyLoginSpec> = {
authKeys: ["deepseek"],
skipBrokenLogins: true,
},
mistral: {
displayName: "Mistral AI",
envVars: ["MISTRAL_API_KEY"],
providerKeys: ["mistral"],
authKeys: ["mistral"],
skipBrokenLogins: true,
},
"ollama-cloud": {
displayName: "Ollama Cloud",
envVars: ["OLLAMA_API_KEY"],
Expand Down
1 change: 1 addition & 0 deletions tests/lib.quota-status-details.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ const PROVIDER_FILES: Readonly<Record<string, readonly string[]>> = {
"google-gemini-cli.ts": ["google-gemini-cli"],
"kimi-code.ts": ["kimi-code-plan-global", "kimi-code-plan-cn"],
"mimo.ts": ["xiaomi"],
"mistral.ts": ["mistral"],
"minimax-coding-plan.ts": ["minimax-coding-plan", "minimax-china-coding-plan"],
"ollama-cloud.ts": ["ollama-cloud"],
"openai.ts": ["openai"],
Expand Down
1 change: 1 addition & 0 deletions tests/lib.quota-status.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2464,6 +2464,7 @@ describe("statusReport", () => {
const KEY_PROVIDERS = [
"commandcode",
"deepseek",
"mistral",
"ollama-cloud",
"zai",
"zhipu",
Expand Down
101 changes: 101 additions & 0 deletions tests/providers.mistral.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { mistralProvider } from "../src/providers/mistral.js";
import {
fakeHttp,
fetchRows,
keyLogin,
requestHeader,
rowSummary,
useProviderWorld,
} from "./helpers/provider-fetch.js";

const world = useProviderWorld();
const RESET = "2026-12-01T00:00:00Z";
const budget = {
vibe_budget: { usage_percentage: 20, initial_budget: 150, currency: "USD", reset_at: RESET },
api_budget: { usage_percentage: 60, initial_budget: 15, currency: "USD", reset_at: RESET },
usage_percentage: 60,
initial_budget: 15,
currency: "USD",
reset_at: RESET,
};

afterEach(() => vi.unstubAllGlobals());

function responses(planType: string, planName: string, body: unknown = budget) {
return fakeHttp((url) =>
url.endsWith("/api/vibe/whoami") ? { plan_type: planType, plan_name: planName } : body,
);
}

describe("Mistral AI provider", () => {
it.each([
["CHAT", "EDU", "mistral.vibe_budget", "Vibe", "Vibe budget", 80, "150"],
["api", "INDIVIDUAL", "mistral.api_budget", "API", "API budget", 40, "15"],
["CHAT", "FREE", "mistral.vibe_budget", "Vibe", "Vibe budget", 80, "150"],
["API", "TEAM", "mistral.api_budget", "API", "API budget", 40, "15"],
])("selects %s %s budget only", async (planType, planName, id, account, label, left, limit) => {
process.env.MISTRAL_API_KEY = "sk-mistral-test";
const http = responses(planType, planName);
const fetched = await fetchRows(mistralProvider);

expect(fetched.error).toBeUndefined();
expect(rowSummary(fetched.rows)).toEqual([
[id, account, label, "month", `${left} (? of ${limit} USD)`, "2026-12-01T00:00:00.000Z"],
]);
expect(fetched.rows[0]).toMatchObject({ type: "budget", method: "remote_api" });
expect(http.mock.calls.map(([url]) => url)).toEqual([
"https://console.mistral.ai/api/vibe/whoami",
"https://api.mistral.ai/v1/billing/budget",
]);
expect(http.mock.calls.map(([, init]) => requestHeader(init, "Authorization"))).toEqual([
"Bearer sk-mistral-test",
"Bearer sk-mistral-test",
]);
});

it("does not fall back to the top-level or opposite plan budget", async () => {
process.env.MISTRAL_API_KEY = "sk-test";
responses("CHAT", "EDU", { api_budget: budget.api_budget, initial_budget: 15 });
const fetched = await fetchRows(mistralProvider);
expect(fetched.rows).toEqual([]);
expect(fetched.error).toMatchObject({ code: "no_data" });
});

it("rejects unknown plan types instead of guessing from the top-level budget", async () => {
process.env.MISTRAL_API_KEY = "sk-test";
responses("OTHER", "EDU");
const fetched = await fetchRows(mistralProvider);
expect(fetched.rows).toEqual([]);
expect(fetched.error).toBeDefined();
});

it("reads stored keys independently and identifies each plan", async () => {
world.storeLogins([
keyLogin("student", "mistral", "key-student"),
keyLogin("team", "mistral", "key-team"),
]);
const http = fakeHttp((_url, init) => {
const team = requestHeader(init, "Authorization") === "Bearer key-team";
return _url.endsWith("/whoami")
? { plan_type: team ? "API" : "CHAT", plan_name: team ? "TEAM" : "EDU" }
: budget;
});
const fetched = await fetchRows(mistralProvider);
expect(fetched.rows.map((row) => [row.id, row.account, row.limit?.decimal]).sort()).toEqual([
["mistral.api_budget", "API", "15"],
["mistral.vibe_budget", "Vibe", "150"],
]);
expect(fetched.rowLogins?.sort()).toEqual(["student", "team"]);
expect(http).toHaveBeenCalledTimes(4);
});

it("reports a failed identity request without querying an ambiguous budget", async () => {
process.env.MISTRAL_API_KEY = "sk-test";
const http = fakeHttp(() => new Response("denied", { status: 401 }));
const fetched = await fetchRows(mistralProvider);
expect(fetched.rows).toEqual([]);
expect(fetched.error).toMatchObject({ code: "login_expired", status: 401 });
expect(http).toHaveBeenCalledTimes(1);
});
});
1 change: 1 addition & 0 deletions tests/providers.registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const EXPECTED_PROVIDER_ORDER = [
"kimi-code-plan-global",
"kimi-code-plan-cn",
"deepseek",
"mistral",
"xai",
"xiaomi",
"opencode-go",
Expand Down