diff --git a/README.md b/README.md index 69d6da7..df5442c 100644 --- a/README.md +++ b/README.md @@ -40,6 +40,7 @@ To sign in, run `/login`, pick `Sign in with an account` (Account below) or `Sig | xAI Grok | Account → `xAI` | `1w` and/or `1m` | — | | | Kimi Coding | Account → `Kimi For Coding` | `5h`, `1w`, membership level | — | | | Antigravity | Account → `Antigravity` | Gemini (`5h`, `1w`), Claude and GPT (`5h`, `1w`), Gemini 4 Argon (`1w`), plan, email, project | — | [`@specode/pi-antigravity`](https://github.com/specode/pi-antigravity) | +| Mistral | Account → `Mistral` | `1m` Vibe Code and API budgets in dollars, plan, pay-as-you-go | — | [`pi-mistral-subscription`](https://github.com/5omeOtherGuy/pi-mistral-subscription) | | Claude (Claude Code) | None; signed in through Claude Code | `5h`, `1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 or later | ### Provider Notes @@ -66,6 +67,12 @@ Several packages have similar names. The extension recognizes the `antigravity` | `@estebanforge/pi-antigravity-bridge`, `@thoth-agents/pi-antigravity-bridge` | Register `antigravity` but run models through a local Antigravity bridge (`agy-bridge://`): unsupported, so the footer stays empty and `/usage` explains why | | `@cortexkit/pi-antigravity-auth` (`google`), `pi-antigravity-acp-provider` and `@dapidev/pi-antigravity-pure` (`antigravity-acp`), `@ackneal/pi-agy-bridge` (`agy`) | Register a different provider id; not supported | +#### Mistral + +Requires [`pi-mistral-subscription`](https://github.com/5omeOtherGuy/pi-mistral-subscription) ([npm](https://www.npmjs.com/package/pi-mistral-subscription)). Install it with `pi install npm:pi-mistral-subscription`; `Mistral` then appears under `Sign in with an account` in `/login`. The extension recognizes the `mistral` provider id that 0.2.0 registers, and the deprecated `mistral-subscription` id of the releases before it. + +A Mistral plan is a monthly budget shared by Studio, the API and Vibe Code, not a window of requests, so `/usage` shows the allowance in dollars next to the percentage: the Vibe Code budget, the API budget, the plan, and whether pay-as-you-go is on. The footer tracks the Vibe Code budget, which is where subscription sign-in requests are counted. Usage comes from `GET /v1/billing/subscription` and `GET /v1/billing/budget` on `api.mistral.ai`, the endpoints Vibe Code reads. The budget needs the `see_org_inference_usage` permission: a key without it shows `Unsupported` in `/usage` with the reason and nothing in the footer. + #### Claude (Claude Code) Requires [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) by elidickinson ([GitHub](https://github.com/elidickinson/pi-claude-bridge)), version 0.9.3 or later. 0.9.3 is the first version that passes Claude Code's usage reports on to Pi. Install it with `pi install npm:pi-claude-bridge` and sign in to Claude Code itself; there is no Pi login. Usage covers models under the `claude-bridge` provider; Claude models served by Antigravity use the Antigravity pool above. diff --git a/README.zh-CN.md b/README.zh-CN.md index d3c5095..b0aafde 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -40,6 +40,7 @@ OpenAI Codex | xAI Grok | Account → `xAI` | `1w` 和/或 `1m` | — | | | Kimi Coding | Account → `Kimi For Coding` | `5h`、`1w`、会员等级 | — | | | Antigravity | Account → `Antigravity` | Gemini(`5h`、`1w`)、Claude 与 GPT(`5h`、`1w`)、Gemini 4 Argon(`1w`)、套餐、邮箱、项目 | — | [`@specode/pi-antigravity`](https://github.com/specode/pi-antigravity) | +| Mistral | Account → `Mistral` | `1m` 的 Vibe Code 与 API 额度(美元)、套餐、是否按量付费 | — | [`pi-mistral-subscription`](https://github.com/5omeOtherGuy/pi-mistral-subscription) | | Claude (Claude Code) | 无需在 Pi 登录,使用 Claude Code 的登录 | `5h`、`1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 及以上 | ### 提供商说明 @@ -66,6 +67,12 @@ npm 上有好几个名字相近的包。扩展按 `antigravity` 这个 provider | `@estebanforge/pi-antigravity-bridge`、`@thoth-agents/pi-antigravity-bridge` | 注册了 `antigravity`,但模型经由本地 Antigravity 桥(`agy-bridge://`)运行:不支持,底部状态栏为空,`/usage` 会说明原因 | | `@cortexkit/pi-antigravity-auth`(`google`)、`pi-antigravity-acp-provider` 与 `@dapidev/pi-antigravity-pure`(`antigravity-acp`)、`@ackneal/pi-agy-bridge`(`agy`) | 注册的是别的 provider id,不支持 | +#### Mistral + +需要 [`pi-mistral-subscription`](https://github.com/5omeOtherGuy/pi-mistral-subscription)([npm](https://www.npmjs.com/package/pi-mistral-subscription))。用 `pi install npm:pi-mistral-subscription` 安装,之后 `/login` 的 `Sign in with an account` 列表里才会出现 `Mistral`。扩展识别 0.2.0 注册的 `mistral`,也识别更早版本使用的 `mistral-subscription`。 + +Mistral 的套餐是一个按月计算的额度,由 Studio、API 和 Vibe Code 共用,不是按请求数计算的窗口,所以 `/usage` 在百分比旁边显示美元额度:Vibe Code 额度、API 额度、套餐,以及是否开启按量付费。底部状态栏显示 Vibe Code 额度,订阅登录产生的用量记在这里。数据来自 `api.mistral.ai` 上的 `GET /v1/billing/subscription` 和 `GET /v1/billing/budget`,也就是 Vibe Code 读取的两个接口。额度需要 `see_org_inference_usage` 权限:没有该权限的 key 在 `/usage` 里显示 `Unsupported` 并说明原因,底部状态栏不显示内容。 + #### Claude (Claude Code) 需要 elidickinson 发布的 [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge)([GitHub](https://github.com/elidickinson/pi-claude-bridge))0.9.3 及以上版本,0.9.3 是第一个把 Claude Code 的用量数据转交给 Pi 的版本。用 `pi install npm:pi-claude-bridge` 安装,并在 Claude Code 里登录,Pi 这边不用登录。这里指 `claude-bridge` 提供商下的模型;通过 Antigravity 使用的 Claude 模型按上文的 Antigravity 额度池显示。 diff --git a/package.json b/package.json index 57dcc35..96e1fa7 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@specode/pi-subscription-usage", "version": "1.5.0", - "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, Antigravity, and Claude (via pi-claude-bridge), plus OpenAI and Codex account reset credits in Pi", + "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, Antigravity, Mistral, and Claude (via pi-claude-bridge), plus OpenAI and Codex account reset credits in Pi", "type": "module", "license": "MIT", "author": "Specode", @@ -24,6 +24,7 @@ "grok", "kimi", "antigravity", + "mistral", "claude" ], "files": [ diff --git a/src/format.ts b/src/format.ts index 3c1b7f6..c916140 100644 --- a/src/format.ts +++ b/src/format.ts @@ -103,7 +103,7 @@ function formatBucket( bucket.limit !== 100 && // x/100 duplicates the percent exactly selectedAmount !== undefined ) { - return `${bar} ${percent} ${qualifier} · ${formatNumber(selectedAmount)}/${formatNumber(bucket.limit)}${reset}`; + return `${bar} ${percent} ${qualifier} · ${formatValue(selectedAmount, bucket.unit)}/${formatValue(bucket.limit, bucket.unit)}${reset}`; } return `${bar} ${percent} ${qualifier}${reset}`; } diff --git a/src/providers/mistral.ts b/src/providers/mistral.ts new file mode 100644 index 0000000..a7c96c7 --- /dev/null +++ b/src/providers/mistral.ts @@ -0,0 +1,206 @@ +// Mistral subscription budget, read from the public billing API Vibe Code uses. +import { sanitizeDisplayText } from "../core.ts"; +import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts"; + +export const MISTRAL_PROVIDER_ID = "mistral"; +/** pi-mistral-subscription registered this id before 0.2.0. */ +export const MISTRAL_LEGACY_PROVIDER_ID = "mistral-subscription"; +export const MISTRAL_OFFICIAL_ORIGINS = ["https://api.mistral.ai"] as const; +export const MISTRAL_SUBSCRIPTION_URL = + "https://api.mistral.ai/v1/billing/subscription"; +export const MISTRAL_BUDGET_URL = "https://api.mistral.ai/v1/billing/budget"; + +/** The plan's allowance covers a calendar month, shared by Studio, the API and Vibe Code. */ +const MONTHLY_WINDOW_MINUTES = 43_200; +const MAX_LABEL_LENGTH = 80; +export const MISTRAL_VIBE_GROUP_ID = "vibe-code"; +export const MISTRAL_API_GROUP_ID = "api"; + +const MISTRAL_PLAN_NAMES: Readonly> = { + INDIVIDUAL: "Individual", + TEAM: "Team", + ENTERPRISE: "Enterprise", +}; + +export function normalizeMistralUsage( + budgetPayload: unknown, + capturedAt: number, + subscriptionPayload?: unknown, +): UsageReport { + const root = asObject(budgetPayload); + if (!root) throw new Error("Mistral budget response was not an object."); + const vibeDetail = asObject(root.vibe_budget); + const apiDetail = asObject(root.api_budget); + // Platforms that predate the split serve the Vibe Code budget at the top level. + const legacyDetail = vibeDetail || apiDetail ? undefined : root; + + const buckets: UsageBucket[] = []; + const metrics: UsageMetric[] = []; + const vibe = budgetBucket( + MISTRAL_VIBE_GROUP_ID, + "Vibe Code", + vibeDetail ?? legacyDetail, + ); + if (vibe) { + buckets.push(vibe.bucket); + if (vibe.metric) metrics.push(vibe.metric); + } + const api = budgetBucket(MISTRAL_API_GROUP_ID, "API", apiDetail); + if (api) { + buckets.push(api.bucket); + if (api.metric) metrics.push(api.metric); + } + if (buckets.length === 0) { + throw new Error( + "Mistral budget endpoint returned no displayable allowance.", + ); + } + + const plan = planName(subscriptionPayload); + if (plan) metrics.push({ id: "plan", label: "Plan", value: plan }); + const payg = payAsYouGo(subscriptionPayload) ?? payAsYouGo(vibeDetail); + if (payg !== undefined) { + metrics.push({ + id: "payg", + label: "Pay-as-you-go", + value: payg ? "on" : "off", + }); + } + + return { + providerId: MISTRAL_PROVIDER_ID, + providerName: "Mistral", + capturedAt, + source: "mistral-billing", + semantics: { + kind: "consumer-subscription", + label: "Mistral subscription budget", + }, + // A subscription key spends the Vibe Code allowance; API keys spend the API one. + defaultGroupId: vibe + ? MISTRAL_VIBE_GROUP_ID + : api + ? MISTRAL_API_GROUP_ID + : undefined, + buckets, + metrics, + }; +} + +function budgetBucket( + groupId: string, + groupLabel: string, + detail: Record | undefined, +): { bucket: UsageBucket; metric?: UsageMetric } | undefined { + if (!detail) return undefined; + const usedPercent = asPercent(detail.usage_percentage); + const limit = asPositiveNumber(detail.initial_budget); + if (usedPercent === undefined || limit === undefined) return undefined; + const resetsAt = parseDate(detail.reset_at); + const window = { + period: "monthly", + windowMinutes: MONTHLY_WINDOW_MINUTES, + ...(resetsAt === undefined ? {} : { resetsAt }), + }; + const id = `${groupId}:budget`; + const label = `${groupLabel} budget`; + const currency = asCurrency(detail.currency); + if (currency !== undefined && currency !== "USD") { + // Keep the percentage exact and show the allowance in its own currency. + return { + bucket: { + id, + label, + groupId, + groupLabel, + used: usedPercent, + remaining: clampPercent(100 - usedPercent), + limit: 100, + unit: "percent", + ...window, + }, + metric: { + id: `${groupId}-allowance`, + label: `${groupLabel} allowance`, + value: `${formatAmount(limit)} ${currency}`, + }, + }; + } + const used = roundMoney((limit * usedPercent) / 100); + return { + bucket: { + id, + label, + groupId, + groupLabel, + used, + remaining: roundMoney(limit - used), + limit, + unit: "usd", + ...window, + }, + }; +} + +function planName(payload: unknown): string | undefined { + const name = asObject(payload)?.plan_name; + if (typeof name !== "string") return undefined; + const plan = sanitizeDisplayText(name, MAX_LABEL_LENGTH); + if (!plan) return undefined; + return Object.hasOwn(MISTRAL_PLAN_NAMES, plan) + ? MISTRAL_PLAN_NAMES[plan] + : plan; +} + +function payAsYouGo(payload: unknown): boolean | undefined { + const value = asObject(payload)?.payg_enabled; + return typeof value === "boolean" ? value : undefined; +} + +function asCurrency(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const currency = value.trim().toUpperCase(); + return /^[A-Z]{3}$/u.test(currency) ? currency : undefined; +} + +function asObject(value: unknown): Record | undefined { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : undefined; +} + +function asPositiveNumber(value: unknown): number | undefined { + const parsed = asFiniteNumber(value); + return parsed !== undefined && parsed > 0 ? parsed : undefined; +} + +/** The endpoint reports a percentage already, not a fraction. */ +function asPercent(value: unknown): number | undefined { + const parsed = asFiniteNumber(value); + return parsed === undefined ? undefined : clampPercent(parsed); +} + +function asFiniteNumber(value: unknown): number | undefined { + if (typeof value !== "number" && typeof value !== "string") return undefined; + if (typeof value === "string" && !value.trim()) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; +} + +function parseDate(value: unknown): number | undefined { + if (typeof value !== "string" || !value.trim()) return undefined; + const parsed = Date.parse(value); + return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1_000); +} + +function clampPercent(value: number): number { + return Math.min(100, Math.max(0, value)); +} + +function roundMoney(value: number): number { + return Math.round(value * 100) / 100; +} + +function formatAmount(value: number): string { + return Number.isInteger(value) ? String(value) : value.toFixed(2); +} diff --git a/src/query.ts b/src/query.ts index 9d019ea..70c8f49 100644 --- a/src/query.ts +++ b/src/query.ts @@ -38,6 +38,14 @@ import { shouldProbeGrokMonthly, } from "./providers/grok.ts"; import { normalizeKimiUsage } from "./providers/kimi.ts"; +import { + MISTRAL_BUDGET_URL, + MISTRAL_LEGACY_PROVIDER_ID, + MISTRAL_OFFICIAL_ORIGINS, + MISTRAL_PROVIDER_ID, + MISTRAL_SUBSCRIPTION_URL, + normalizeMistralUsage, +} from "./providers/mistral.ts"; import { OPENAI_PROVIDER_ID, normalizeOpenAIPlanUsage, @@ -169,6 +177,56 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [ ); }, }, + { + id: MISTRAL_PROVIDER_ID, + displayName: "Mistral", + providerIds: [MISTRAL_PROVIDER_ID, MISTRAL_LEGACY_PROVIDER_ID], + officialOrigins: [...MISTRAL_OFFICIAL_ORIGINS], + semantics: { + kind: "consumer-subscription", + label: "Mistral subscription budget", + }, + async query(auth, signal, timeoutMs) { + // The plan is decoration; attach the handler now so a budget failure + // cannot leave this request as an unhandled rejection. + const subscription = fetchProviderJson( + MISTRAL_SUBSCRIPTION_URL, + auth, + signal, + timeoutMs, + "Mistral subscription endpoint", + ).then( + (payload) => payload, + () => undefined, + ); + let budget: Record; + try { + budget = await fetchProviderJson( + MISTRAL_BUDGET_URL, + auth, + signal, + timeoutMs, + "Mistral budget endpoint", + ); + } catch (error) { + if (isAbortError(error) || signal.aborted) throw error; + const status = httpStatus(error); + if (status === 403) { + throw new UsageUnsupportedError( + "Mistral did not grant this key the see_org_inference_usage permission, so the monthly budget cannot be read.", + ); + } + if (status === 404) { + throw new UsageUnsupportedError( + "This Mistral platform does not serve the billing endpoints.", + ); + } + throw error; + } + const planPayload = await subscription; + return normalizeMistralUsage(budget, Date.now(), planPayload); + }, + }, { id: "xai", displayName: "Grok", @@ -325,6 +383,12 @@ async function fetchAntigravityJson( : new Error(`${description} failed.`); } +/** HTTP failures carry `status`; network failures surface as fetch's TypeError. */ +function httpStatus(error: unknown): number | undefined { + const status = (error as { status?: unknown } | null)?.status; + return typeof status === "number" ? status : undefined; +} + export function adapterForProvider( providerId: string | undefined, ): UsageProviderAdapter | undefined { diff --git a/test/mistral.test.ts b/test/mistral.test.ts new file mode 100644 index 0000000..561d307 --- /dev/null +++ b/test/mistral.test.ts @@ -0,0 +1,293 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { formatUsageReport } from "../src/format.ts"; +import { + MISTRAL_API_GROUP_ID, + MISTRAL_BUDGET_URL, + MISTRAL_LEGACY_PROVIDER_ID, + MISTRAL_PROVIDER_ID, + MISTRAL_SUBSCRIPTION_URL, + MISTRAL_VIBE_GROUP_ID, + normalizeMistralUsage, +} from "../src/providers/mistral.ts"; +import { + adapterForProvider, + queryProviderUsage, + UsageUnsupportedError, +} from "../src/query.ts"; +import { formatUsageStatusline } from "../src/status.ts"; +import type { ResolvedUsageAuth } from "../src/types.ts"; + +const capturedAt = Date.parse("2026-11-20T10:00:00Z"); + +const FIXTURE_BUDGET = { + vibe_budget: { + usage_percentage: 0.07373884133333333, + initial_budget: 300, + currency: "USD", + reset_at: "2026-12-01T00:00:00Z", + payg_enabled: false, + }, + api_budget: { + usage_percentage: 25, + initial_budget: 30, + currency: "USD", + reset_at: "2026-12-01T00:00:00Z", + payg_enabled: false, + }, + usage_percentage: 25, + initial_budget: 30, + currency: "USD", + reset_at: "2026-12-01T00:00:00Z", +}; + +const FIXTURE_SUBSCRIPTION = { + plan_name: "INDIVIDUAL", + payg_enabled: false, + vibe_payg_enabled: false, + enterprise: false, +}; + +test("normalizes the Vibe Code and API budgets", () => { + const report = normalizeMistralUsage( + FIXTURE_BUDGET, + capturedAt, + FIXTURE_SUBSCRIPTION, + ); + assert.equal(report.providerId, MISTRAL_PROVIDER_ID); + assert.equal(report.providerName, "Mistral"); + assert.equal(report.defaultGroupId, MISTRAL_VIBE_GROUP_ID); + assert.deepEqual( + report.buckets.map((bucket) => [ + bucket.groupId, + bucket.unit, + bucket.used, + bucket.remaining, + bucket.limit, + ]), + [ + [MISTRAL_VIBE_GROUP_ID, "usd", 0.22, 299.78, 300], + [MISTRAL_API_GROUP_ID, "usd", 7.5, 22.5, 30], + ], + ); + assert.equal(report.buckets[0]?.windowMinutes, 43_200); + assert.equal(report.buckets[0]?.resetsAt, Date.parse("2026-12-01T00:00:00Z") / 1_000); + assert.deepEqual(report.metrics, [ + { id: "plan", label: "Plan", value: "Individual" }, + { id: "payg", label: "Pay-as-you-go", value: "off" }, + ]); +}); + +test("keeps the footer on the Vibe Code budget", () => { + const report = normalizeMistralUsage( + FIXTURE_BUDGET, + capturedAt, + FIXTURE_SUBSCRIPTION, + ); + assert.equal( + formatUsageStatusline( + report, + { provider: MISTRAL_PROVIDER_ID, id: "mistral-large-4" }, + "remaining", + capturedAt, + ), + "1m 100% ↻10d14h", + ); +}); + +test("shows a USD budget in dollars", () => { + const report = normalizeMistralUsage(FIXTURE_BUDGET, capturedAt); + const text = formatUsageReport(report); + assert.match(text, /\$299\.78\/\$300\.00/u); + assert.match(text, /\$22\.50\/\$30\.00/u); +}); + +test("falls back to the legacy top-level budget", () => { + const report = normalizeMistralUsage( + { + usage_percentage: 40, + initial_budget: 25, + currency: "USD", + reset_at: "2026-12-01T00:00:00Z", + }, + capturedAt, + ); + assert.equal(report.defaultGroupId, MISTRAL_VIBE_GROUP_ID); + assert.equal(report.buckets.length, 1); + assert.equal(report.buckets[0]?.used, 10); + assert.equal(report.buckets[0]?.remaining, 15); +}); + +test("does not read the top-level mirror as a second Vibe Code budget", () => { + const report = normalizeMistralUsage( + { ...FIXTURE_BUDGET, vibe_budget: undefined }, + capturedAt, + ); + assert.equal(report.defaultGroupId, MISTRAL_API_GROUP_ID); + assert.deepEqual( + report.buckets.map((bucket) => bucket.groupId), + [MISTRAL_API_GROUP_ID], + ); +}); + +test("keeps a non-USD budget as a percentage with its allowance", () => { + const report = normalizeMistralUsage( + { + vibe_budget: { + usage_percentage: 12.5, + initial_budget: 200, + currency: "eur", + reset_at: "2026-12-01T00:00:00Z", + }, + }, + capturedAt, + ); + assert.equal(report.buckets[0]?.unit, "percent"); + assert.equal(report.buckets[0]?.used, 12.5); + assert.equal(report.buckets[0]?.remaining, 87.5); + assert.deepEqual(report.metrics, [ + { id: "vibe-code-allowance", label: "Vibe Code allowance", value: "200 EUR" }, + ]); +}); + +test("rejects a budget without a usable allowance", () => { + assert.throws( + () => normalizeMistralUsage({ vibe_budget: { usage_percentage: 10 } }, capturedAt), + /Mistral budget endpoint returned no displayable allowance/u, + ); + assert.throws( + () => normalizeMistralUsage({ vibe_budget: { initial_budget: 300 } }, capturedAt), + /Mistral budget endpoint returned no displayable allowance/u, + ); + assert.throws(() => normalizeMistralUsage([], capturedAt), /was not an object/u); +}); + +test("reads the Mistral billing endpoints for the subscription budget", async () => { + const adapter = adapterForProvider(MISTRAL_PROVIDER_ID); + assert.ok(adapter); + const calls: string[] = []; + const original = globalThis.fetch; + globalThis.fetch = async (input) => { + const url = String(input); + calls.push(url); + return jsonResponse( + url === MISTRAL_SUBSCRIPTION_URL ? FIXTURE_SUBSCRIPTION : FIXTURE_BUDGET, + ); + }; + try { + const report = await queryProviderUsage( + adapter, + mistralAuth(), + new AbortController().signal, + 5_000, + ); + assert.deepEqual(calls, [MISTRAL_SUBSCRIPTION_URL, MISTRAL_BUDGET_URL]); + assert.equal(report.providerId, MISTRAL_PROVIDER_ID); + assert.equal(report.buckets[0]?.remaining, 299.78); + } finally { + globalThis.fetch = original; + } +}); + +test("recognizes the deprecated mistral-subscription provider id", () => { + assert.equal( + adapterForProvider(MISTRAL_LEGACY_PROVIDER_ID)?.id, + MISTRAL_PROVIDER_ID, + ); +}); + +test("keeps the budget when the plan endpoint fails", async () => { + const adapter = adapterForProvider(MISTRAL_PROVIDER_ID); + assert.ok(adapter); + const original = globalThis.fetch; + globalThis.fetch = async (input) => + String(input) === MISTRAL_SUBSCRIPTION_URL + ? jsonResponse({ error: "unavailable" }, 500) + : jsonResponse(FIXTURE_BUDGET); + try { + const report = await queryProviderUsage( + adapter, + mistralAuth(), + new AbortController().signal, + 5_000, + ); + assert.deepEqual( + report.metrics.map((metric) => metric.id), + ["payg"], + ); + assert.equal(report.buckets.length, 2); + } finally { + globalThis.fetch = original; + } +}); + +test("reports a missing usage permission as unsupported", async () => { + const adapter = adapterForProvider(MISTRAL_PROVIDER_ID); + assert.ok(adapter); + const original = globalThis.fetch; + globalThis.fetch = async (input) => + String(input) === MISTRAL_SUBSCRIPTION_URL + ? jsonResponse(FIXTURE_SUBSCRIPTION) + : jsonResponse({ detail: "forbidden" }, 403); + try { + await assert.rejects( + queryProviderUsage( + adapter, + mistralAuth(), + new AbortController().signal, + 5_000, + ), + (error: Error) => { + assert.ok(error instanceof UsageUnsupportedError); + assert.match(error.message, /see_org_inference_usage/u); + return true; + }, + ); + } finally { + globalThis.fetch = original; + } +}); + +test("surfaces a failing budget endpoint as an error", async () => { + const adapter = adapterForProvider(MISTRAL_PROVIDER_ID); + assert.ok(adapter); + const original = globalThis.fetch; + globalThis.fetch = async (input) => + String(input) === MISTRAL_SUBSCRIPTION_URL + ? jsonResponse(FIXTURE_SUBSCRIPTION) + : jsonResponse({ error: "unavailable" }, 500); + try { + await assert.rejects( + queryProviderUsage( + adapter, + mistralAuth(), + new AbortController().signal, + 5_000, + ), + (error: Error) => { + assert.equal(error instanceof UsageUnsupportedError, false); + assert.match(error.message, /Mistral budget endpoint returned 500/u); + return true; + }, + ); + } finally { + globalThis.fetch = original; + } +}); + +function mistralAuth(): ResolvedUsageAuth { + return { + actualProviderId: MISTRAL_PROVIDER_ID, + headers: { Authorization: "Bearer fixture-token" }, + fingerprint: "fp", + secrets: ["fixture-token"], + model: { provider: MISTRAL_PROVIDER_ID, id: "mistral-large-4" }, + }; +} + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json" }, + }); +}