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
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
7 changes: 7 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 及以上 |

### 提供商说明
Expand All @@ -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 额度池显示。
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand All @@ -24,6 +24,7 @@
"grok",
"kimi",
"antigravity",
"mistral",
"claude"
],
"files": [
Expand Down
2 changes: 1 addition & 1 deletion src/format.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
}
Expand Down
206 changes: 206 additions & 0 deletions src/providers/mistral.ts
Original file line number Diff line number Diff line change
@@ -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<Record<string, string>> = {
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<string, unknown> | 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<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: 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);
}
64 changes: 64 additions & 0 deletions src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<string, unknown>;
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",
Expand Down Expand Up @@ -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 {
Expand Down
Loading