Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix(usage): handle MiniMax coding plan percent quotas
diegosouzapw0f900f1d568f
diff --git a/docs/reference/API_REFERENCE.md b/docs/reference/API_REFERENCE.mdindex b208f73741..43c6a71e7f 100644--- a/docs/reference/API_REFERENCE.md+++ b/docs/reference/API_REFERENCE.md@@ -266,6 +266,44 @@ For quota-share routing use `model: "qtSd/<group>/codex/<model>"`. Implemented i**Auth:** Bearer API key during handshake. The bundled HTTP server (`server-ws.mjs`)must be the active entrypoint (it is, by default, when `app/server-ws.mjs` exists).+#### Model id: use the bare ChatGPT id (no `codex/` prefix)++The OpenAI **Codex CLI** validates the model name client-side when+`supports_websockets = true` and **rejects provider-prefixed ids** like+`codex/gpt-5.5` (`The 'codex/gpt-5.5' model is not supported when using Codex with+a ChatGPT account`). Send the **bare** id (e.g. `gpt-5.5`). OmniRoute's bridge is+codex-only, so it re-resolves a bare id as a codex model+(`resolveCodexWsModelInfo`) before tunneling upstream — even though a bare+`gpt-5.5` would otherwise route to another provider over HTTP.++#### Configuring the OpenAI Codex CLI++Point the Codex CLI at OmniRoute by adding a custom provider with WebSocket+support to `~/.codex/config.toml` (use a separate `CODEX_HOME` to avoid touching+an existing config):++```toml+model = "gpt-5.5" # bare id — NOT "codex/gpt-5.5"+model_provider = "omniroute"++[model_providers.omniroute]+name = "OmniRoute (WS)"+base_url = "http://localhost:20128/v1" # no trailing slash; the WS URL is derived (use https/wss in production)+wire_api = "responses" # only supported value since Feb 2026+supports_websockets = true # enables the Responses-over-WS transport+env_key = "OMNIROUTE_API_KEY" # holds the OmniRoute API key (Bearer)+```++```bash+export OMNIROUTE_API_KEY=sk-... # an OmniRoute API key (any key if REQUIRE_API_KEY=false)+codex exec "Responda apenas: PONG"+```++The CLI upgrades `base_url + /responses` to a WebSocket and OmniRoute tunnels it+to the selected codex OAuth connection. Validated end-to-end against the local+server: ChatGPT returns `codex.rate_limits` + `response.created` and streams the+completion.+---## Quotas & Issues Reportingdiff --git a/open-sse/services/usage.ts b/open-sse/services/usage.tsindex 8e3ac88529..5e3a5ebefd 100644--- a/open-sse/services/usage.ts+++ b/open-sse/services/usage.ts@@ -406,7 +406,13 @@ function getMiniMaxQuotaResetAt(function isMiniMaxTextQuotaModel(modelName: string): boolean {const normalized = modelName.trim().toLowerCase();- return normalized.startsWith("minimax-m") || normalized.startsWith("coding-plan");+ return (+ normalized.startsWith("minimax-m") ||+ normalized.startsWith("coding-plan") ||+ // MiniMax Coding Plan surfaces the text/coding quota under model "general"+ // (media buckets like "video"/"image"/"music" are excluded).+ normalized === "general"+ );}function getMiniMaxSessionTotal(model: JsonRecord): number {@@ -444,6 +450,66 @@ function createMiniMaxQuotaFromCount(return createQuotaFromUsage(used, total, resetAt);}+/**+ * MiniMax Coding Plan exposes per-window remaining as a 0–100 percent+ * (`current_interval_remaining_percent` / `current_weekly_remaining_percent`)+ * with zero request counts. Read it defensively (string-encoded numbers ok).+ */+function getMiniMaxRemainingPercent(+ model: JsonRecord,+ snakeKey: string,+ camelKey: string+): number | null {+ const raw = getFieldValue(model, snakeKey, camelKey);+ if (raw === null || raw === undefined || raw === "") return null;+ const parsed = toNumber(raw, NaN);+ return Number.isFinite(parsed) ? Math.max(0, Math.min(100, parsed)) : null;+}++/** Build a 0–100 percent-based window quota (used = 100 − remaining). */+function createMiniMaxQuotaFromPercent(+ remainingPercent: number,+ resetAt: string | null+): UsageQuota {+ const clamped = Math.max(0, Math.min(100, remainingPercent));+ return createQuotaFromUsage(100 - clamped, 100, resetAt);+}++/**+ * Build one MiniMax usage window (session or weekly) from the representative+ * model. Token Plan keys report request counts (`*_total_count`); Coding Plan+ * keys report zero counts and a `*_remaining_percent` instead — fall back to+ * that so the Coding Plan still surfaces a quota. The percent signal is keyed+ * off "counts == 0 + percent present", NOT the endpoint URL, because the+ * `token_plan/remains` and `coding_plan/remains` endpoints return identical+ * Coding-Plan payloads for a Coding Plan key.+ */+function buildMiniMaxWindow(+ models: JsonRecord[],+ getTotal: (model: JsonRecord) => number,+ usageCountKeys: [string, string],+ percentKeys: [string, string],+ resetKeys: [string, string, string, string],+ capturedAtMs: number,+ countMeansRemaining: boolean+): UsageQuota | null {+ const model = pickMiniMaxRepresentativeModel(models, getTotal);+ if (!model) return null;++ const resetAt = getMiniMaxQuotaResetAt(model, capturedAtMs, ...resetKeys);+ const total = getTotal(model);++ if (total > 0) {+ const count = Math.max(0, toNumber(getFieldValue(model, ...usageCountKeys), 0));+ return createMiniMaxQuotaFromCount(total, count, resetAt, countMeansRemaining);+ }++ const remainingPercent = getMiniMaxRemainingPercent(model, ...percentKeys);+ return remainingPercent !== null+ ? createMiniMaxQuotaFromPercent(remainingPercent, resetAt)+ : null;+}+function getMiniMaxAuthErrorMessage(message: string): string {const normalized = message.toLowerCase();if (@@ -559,58 +625,31 @@ async function getMiniMaxUsage(apiKey: string, provider: "minimax" | "minimax-cnconst countMeansRemaining = usageUrl.includes("/coding_plan/remains");const quotas: Record<string, UsageQuota> = {};- const sessionModel = pickMiniMaxRepresentativeModel(textModels, getMiniMaxSessionTotal);- if (sessionModel) {- const total = getMiniMaxSessionTotal(sessionModel);- const count = Math.max(- 0,- toNumber(- getFieldValue(- sessionModel,- "current_interval_usage_count",- "currentIntervalUsageCount"- ),- 0- )- );- quotas["session (5h)"] = createMiniMaxQuotaFromCount(- total,- count,- getMiniMaxQuotaResetAt(- sessionModel,- capturedAtMs,- "remains_time",- "remainsTime",- "end_time",- "endTime"- ),- countMeansRemaining- );++ const sessionQuota = buildMiniMaxWindow(+ textModels,+ getMiniMaxSessionTotal,+ ["current_interval_usage_count", "currentIntervalUsageCount"],+ ["current_interval_remaining_percent", "currentIntervalRemainingPercent"],+ ["remains_time", "remainsTime", "end_time", "endTime"],+ capturedAtMs,+ countMeansRemaining+ );+ if (sessionQuota) {+ quotas["session (5h)"] = sessionQuota;}- const weeklyModel = pickMiniMaxRepresentativeModel(textModels, getMiniMaxWeeklyTotal);- if (weeklyModel && getMiniMaxWeeklyTotal(weeklyModel) > 0) {- const total = getMiniMaxWeeklyTotal(weeklyModel);- const count = Math.max(- 0,- toNumber(- getFieldValue(weeklyModel, "current_weekly_usage_count", "currentWeeklyUsageCount"),- 0- )- );- quotas["weekly (7d)"] = createMiniMaxQuotaFromCount(- total,- count,- getMiniMaxQuotaResetAt(- weeklyModel,- capturedAtMs,- "weekly_remains_time",- "weeklyRemainsTime",- "weekly_end_time",- "weeklyEndTime"- ),- countMeansRemaining- );+ const weeklyQuota = buildMiniMaxWindow(+ textModels,+ getMiniMaxWeeklyTotal,+ ["current_weekly_usage_count", "currentWeeklyUsageCount"],+ ["current_weekly_remaining_percent", "currentWeeklyRemainingPercent"],+ ["weekly_remains_time", "weeklyRemainsTime", "weekly_end_time", "weeklyEndTime"],+ capturedAtMs,+ countMeansRemaining+ );+ if (weeklyQuota) {+ quotas["weekly (7d)"] = weeklyQuota;}if (Object.keys(quotas).length === 0) {@@ -2947,6 +2986,9 @@ export const __testing = {getMiniMaxSessionTotal,getMiniMaxWeeklyTotal,createMiniMaxQuotaFromCount,+ createMiniMaxQuotaFromPercent,+ getMiniMaxRemainingPercent,+ getMiniMaxUsage,getMiniMaxAuthErrorMessage,getMiniMaxErrorSummary,mapCodeAssistSubscriptionToPlanLabel,diff --git a/src/app/api/internal/codex-responses-ws/modelResolution.ts b/src/app/api/internal/codex-responses-ws/modelResolution.tsnew file mode 100644index 0000000000..244e63d22d--- /dev/null+++ b/src/app/api/internal/codex-responses-ws/modelResolution.ts@@ -0,0 +1,48 @@+/**+ * Model resolution for the Codex Responses-over-WebSocket bridge.+ *+ * The bridge is codex-only, but the OpenAI Codex CLI rejects provider-prefixed+ * model ids (e.g. "codex/gpt-5.5") client-side when `supports_websockets` is+ * enabled — it only accepts bare ChatGPT model ids (e.g. "gpt-5.5"). Those bare+ * ids can resolve to a different default provider (openai / openrouter) under+ * OmniRoute's global model routing, which the bridge would then reject with+ * `codex_ws_provider_required` (or fail the credentials lookup).+ *+ * Since this endpoint only ever talks to the Codex upstream, re-resolve a bare+ * id under the `codex/` prefix so it is treated as codex. Provider-prefixed ids+ * (already containing a "/") are left untouched.+ *+ * See docs/reference/API_REFERENCE.md → "Responses over WebSocket (Codex)".+ */++export interface ResolvedModelInfo {+ provider?: string;+ model?: string;+ [key: string]: unknown;+}++export type ModelResolver = (modelStr: string) => Promise<ResolvedModelInfo>;++/**+ * Resolve a Responses-WebSocket model id, preferring the codex provider.+ *+ * @param requestedModel the bare/prefixed model id sent by the client+ * @param resolve a `getModelInfo`-style resolver+ * @returns the codex-preferred resolution, or the original resolution if the+ * model genuinely does not map to codex.+ */+export async function resolveCodexWsModelInfo(+ requestedModel: string,+ resolve: ModelResolver+): Promise<ResolvedModelInfo> {+ const info = await resolve(requestedModel);++ // Already codex, or explicitly provider-prefixed → respect it.+ if (info?.provider === "codex" || requestedModel.includes("/")) {+ return info;+ }++ // Bare id resolved to a non-codex provider; retry as a codex model.+ const codexInfo = await resolve(`codex/${requestedModel}`);+ return codexInfo?.provider === "codex" ? codexInfo : info;+}diff --git a/src/app/api/internal/codex-responses-ws/route.ts b/src/app/api/internal/codex-responses-ws/route.tsindex 078cee518b..abedfe79a9 100644--- a/src/app/api/internal/codex-responses-ws/route.ts+++ b/src/app/api/internal/codex-responses-ws/route.ts@@ -7,6 +7,7 @@ import { authorizeWebSocketHandshake, extractWsTokenFromRequest } from "@/lib/wsimport { getModelInfo } from "@/sse/services/model";import { getProviderCredentialsWithQuotaPreflight } from "@/sse/services/auth";import { checkAndRefreshToken } from "@/sse/services/tokenRefresh";+import { resolveCodexWsModelInfo } from "./modelResolution";const CODEX_RESPONSES_WS_URL = "wss://chatgpt.com/backend-api/codex/responses";const executor = new CodexExecutor();@@ -124,7 +125,9 @@ async function prepare(body: JsonRecord) {typeof responseBody.model === "string" && responseBody.model.trim()? responseBody.model.trim(): "gpt-5.5";- const modelInfo = await getModelInfo(requestedModel);+ // codex-only bridge: re-resolve bare ChatGPT model ids (the Codex CLI rejects+ // provider-prefixed ids client-side over WebSocket) as codex models.+ const modelInfo = await resolveCodexWsModelInfo(requestedModel, getModelInfo);const provider = modelInfo.provider;const model = modelInfo.model || requestedModel;diff --git a/tests/unit/codex-responses-ws-model-resolution.test.ts b/tests/unit/codex-responses-ws-model-resolution.test.tsnew file mode 100644index 0000000000..221bdd3cd1--- /dev/null+++ b/tests/unit/codex-responses-ws-model-resolution.test.ts@@ -0,0 +1,62 @@+/**+ * tests/unit/codex-responses-ws-model-resolution.test.ts+ *+ * The Codex Responses-over-WebSocket bridge is codex-only, but the OpenAI Codex+ * CLI rejects provider-prefixed model ids ("codex/gpt-5.5") client-side when+ * `supports_websockets` is enabled and sends bare ids ("gpt-5.5"). Those can+ * resolve to a non-codex default provider, which the bridge would reject.+ * `resolveCodexWsModelInfo` re-resolves bare ids under the codex/ prefix.+ *+ * Empirically: with the bare id, ChatGPT's codex backend accepts model+ * "gpt-5.5" and streams a response; without this re-resolution OmniRoute routed+ * "gpt-5.5" to openrouter ("No credentials for provider: openrouter").+ */++import test from "node:test";+import assert from "node:assert/strict";+import {+ resolveCodexWsModelInfo,+ type ModelResolver,+} from "../../src/app/api/internal/codex-responses-ws/modelResolution.ts";++// A resolver mirroring OmniRoute's real behavior: bare "gpt-5.5" → openrouter,+// but the codex/ prefix forces provider=codex with the prefix stripped.+const realisticResolver: ModelResolver = async (m) =>+ m.startsWith("codex/")+ ? { provider: "codex", model: m.slice("codex/".length) }+ : { provider: "openrouter", model: m };++test("bare ChatGPT model id re-resolves to codex provider with stripped model", async () => {+ const info = await resolveCodexWsModelInfo("gpt-5.5", realisticResolver);+ assert.equal(info.provider, "codex");+ assert.equal(info.model, "gpt-5.5", "model sent upstream must be the bare ChatGPT id");+});++test("provider-prefixed id is respected without a second resolve call", async () => {+ let calls = 0;+ const resolver: ModelResolver = async (m) => {+ calls += 1;+ return { provider: "codex", model: m.replace(/^codex\//, "") };+ };+ const info = await resolveCodexWsModelInfo("codex/gpt-5.5", resolver);+ assert.equal(info.provider, "codex");+ assert.equal(info.model, "gpt-5.5");+ assert.equal(calls, 1, "must not double-resolve an explicitly prefixed id");+});++test("first resolution already codex short-circuits", async () => {+ let calls = 0;+ const resolver: ModelResolver = async (m) => {+ calls += 1;+ return { provider: "codex", model: m };+ };+ const info = await resolveCodexWsModelInfo("gpt-5.5", resolver);+ assert.equal(info.provider, "codex");+ assert.equal(calls, 1);+});++test("genuinely non-codex model stays non-codex (bridge then rejects it)", async () => {+ const resolver: ModelResolver = async (m) => ({ provider: "openai", model: m });+ const info = await resolveCodexWsModelInfo("gpt-4o", resolver);+ assert.notEqual(info.provider, "codex");+});diff --git a/tests/unit/minimax-coding-plan-usage.test.ts b/tests/unit/minimax-coding-plan-usage.test.tsnew file mode 100644index 0000000000..ccea39b70d--- /dev/null+++ b/tests/unit/minimax-coding-plan-usage.test.ts@@ -0,0 +1,142 @@+/**+ * tests/unit/minimax-coding-plan-usage.test.ts+ *+ * MiniMax Coding Plan keys (`sk-cp-…`) expose quota as a remaining-PERCENT on a+ * model named "general" with zero request counts — both `token_plan/remains`+ * and `coding_plan/remains` return identical Coding-Plan payloads. The fetcher+ * previously (a) filtered "general" out and (b) computed only count-based+ * quotas, so the Coding Plan showed no quota at all. These tests lock in the+ * percent fallback and that Token Plan (count-based) behavior is unchanged.+ *+ * Response shape captured live from a real Coding Plan key (2026-06-02).+ */++import test from "node:test";+import assert from "node:assert/strict";+import { __testing } from "../../open-sse/services/usage.ts";++const {+ getMiniMaxUsage,+ isMiniMaxTextQuotaModel,+ getMiniMaxRemainingPercent,+ createMiniMaxQuotaFromPercent,+} = __testing;++type Quotas = Record<+ string,+ { used: number; total: number; remaining?: number; remainingPercentage?: number }+>;++function mockFetchOnce(payload: unknown) {+ const original = globalThis.fetch;+ globalThis.fetch = (async () =>+ new Response(JSON.stringify(payload), {+ status: 200,+ headers: { "content-type": "application/json" },+ })) as typeof fetch;+ return () => {+ globalThis.fetch = original;+ };+}++const CODING_PLAN_PAYLOAD = {+ base_resp: { status_code: 0, status_msg: "success" },+ model_remains: [+ {+ model_name: "general",+ current_interval_total_count: 0,+ current_interval_usage_count: 0,+ current_weekly_total_count: 0,+ current_weekly_usage_count: 0,+ current_interval_remaining_percent: 99,+ current_weekly_remaining_percent: 99,+ remains_time: 13815408,+ weekly_remains_time: 427670466,+ current_interval_status: 1,+ current_weekly_status: 1,+ },+ {+ model_name: "video",+ current_interval_total_count: 0,+ current_weekly_total_count: 0,+ current_interval_remaining_percent: 100,+ current_weekly_remaining_percent: 100,+ current_interval_status: 3,+ current_weekly_status: 3,+ },+ ],+};++test("getMiniMaxUsage: Coding Plan 'general' surfaces percent-based windows", async () => {+ const restore = mockFetchOnce(CODING_PLAN_PAYLOAD);+ try {+ const result = (await getMiniMaxUsage("sk-cp-test", "minimax")) as { quotas?: Quotas; message?: string };+ assert.ok(result.quotas, `expected quotas, got message: ${result.message}`);+ const session = result.quotas["session (5h)"];+ const weekly = result.quotas["weekly (7d)"];+ assert.ok(session, "session window must be present");+ assert.ok(weekly, "weekly window must be present");+ assert.equal(session.remainingPercentage, 99, "session = 99% remaining");+ assert.equal(weekly.remainingPercentage, 99, "weekly = 99% remaining");+ assert.equal(session.total, 100);+ assert.equal(session.remaining, 99);+ } finally {+ restore();+ }+});++test("getMiniMaxUsage: Token Plan stays count-based (regression guard)", async () => {+ const restore = mockFetchOnce({+ base_resp: { status_code: 0, status_msg: "success" },+ model_remains: [+ {+ model_name: "minimax-m1",+ current_interval_total_count: 1500,+ current_interval_usage_count: 300,+ current_weekly_total_count: 0,+ current_weekly_usage_count: 0,+ remains_time: 1000,+ },+ ],+ });+ try {+ const result = (await getMiniMaxUsage("sk-test", "minimax")) as { quotas?: Quotas; message?: string };+ assert.ok(result.quotas, `expected quotas, got message: ${result.message}`);+ const session = result.quotas["session (5h)"];+ assert.ok(session, "session window present");+ // token_plan/remains → countMeansRemaining=false → used = usage_count (300/1500 = 80% left)+ assert.equal(session.total, 1500);+ assert.equal(session.used, 300);+ assert.equal(session.remainingPercentage, 80);+ } finally {+ restore();+ }+});++test("isMiniMaxTextQuotaModel: accepts general + minimax-m, rejects media", () => {+ assert.equal(isMiniMaxTextQuotaModel("general"), true);+ assert.equal(isMiniMaxTextQuotaModel("General"), true);+ assert.equal(isMiniMaxTextQuotaModel("minimax-m1"), true);+ assert.equal(isMiniMaxTextQuotaModel("coding-plan-pro"), true);+ assert.equal(isMiniMaxTextQuotaModel("video"), false);+ assert.equal(isMiniMaxTextQuotaModel("image"), false);+ assert.equal(isMiniMaxTextQuotaModel("music"), false);+});++test("getMiniMaxRemainingPercent: reads + clamps + handles missing/string", () => {+ assert.equal(getMiniMaxRemainingPercent({ current_interval_remaining_percent: 99 }, "current_interval_remaining_percent", "x"), 99);+ assert.equal(getMiniMaxRemainingPercent({ x: "42" }, "x", "y"), 42);+ assert.equal(getMiniMaxRemainingPercent({ x: 150 }, "x", "y"), 100, "clamps above 100");+ assert.equal(getMiniMaxRemainingPercent({ x: -5 }, "x", "y"), 0, "clamps below 0");+ assert.equal(getMiniMaxRemainingPercent({}, "x", "y"), null, "missing → null");+ assert.equal(getMiniMaxRemainingPercent({ x: "" }, "x", "y"), null, "empty string → null");+});++test("createMiniMaxQuotaFromPercent: 0–100 percent window", () => {+ const q = createMiniMaxQuotaFromPercent(99, null);+ assert.equal(q.total, 100);+ assert.equal(q.used, 1);+ assert.equal(q.remaining, 99);+ assert.equal(q.remainingPercentage, 99);+ assert.equal(q.unlimited, false);+});