@mupt-ai/dari-gateway 1.0.297 → 1.0.299

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,8 @@ export declare class HttpError extends Error {
4
4
  readonly code: string;
5
5
  readonly param?: string;
6
6
  readonly headers?: Record<string, string>;
7
- constructor(status: number, message: string, code?: string, param?: string, headers?: Record<string, string>);
7
+ readonly body?: Record<string, unknown>;
8
+ constructor(status: number, message: string, code?: string, param?: string, headers?: Record<string, string>, body?: Record<string, unknown>);
8
9
  }
9
10
  export declare function errorResponseHeaders(error: unknown): Record<string, string>;
10
11
  export declare function httpErrorFrom(error: RouterCoreError): HttpError;
@@ -6,12 +6,16 @@ export class HttpError extends Error {
6
6
  param;
7
7
  // Response headers the error carries to the client, such as retry-after.
8
8
  headers;
9
- constructor(status, message, code = "invalid_request_error", param, headers) {
9
+ // Fields that replace or extend the OpenAI-shaped error object, for clients
10
+ // that read more than the message (such as Codex's usage-limit type).
11
+ body;
12
+ constructor(status, message, code = "invalid_request_error", param, headers, body) {
10
13
  super(message);
11
14
  this.status = status;
12
15
  this.code = code;
13
16
  this.param = param;
14
17
  this.headers = headers;
18
+ this.body = body;
15
19
  }
16
20
  }
17
21
  export function errorResponseHeaders(error) {
@@ -49,6 +53,7 @@ export function errorResponse(error) {
49
53
  type: openAiErrorType(normalized.status),
50
54
  code: normalized.code,
51
55
  ...(normalized.param ? { param: normalized.param } : {}),
56
+ ...(error instanceof HttpError ? error.body : undefined),
52
57
  },
53
58
  }, { status: normalized.status, headers: errorResponseHeaders(error) });
54
59
  }
@@ -13,6 +13,12 @@ import type { ClientHarness, ProviderCredential, ProviderKeySource, ResolvedRout
13
13
  * log, and continue.
14
14
  */
15
15
  export type GatewayPlatform = {
16
+ /**
17
+ * Optional. The web page where users manage their subscriptions; usage-limit
18
+ * errors link to it, with `?buy=<provider>` to add another plan. Without
19
+ * one they point at `dari accounts`.
20
+ */
21
+ accountsUrl?: string;
16
22
  /**
17
23
  * Authenticate the request's key and return the router it may use, with
18
24
  * decrypted provider credentials and the prefix-cache evidence matching
@@ -0,0 +1,10 @@
1
+ import type { SubscriptionUsage } from "./subscription_limits.js";
2
+ export declare function readCodexUsage(args: {
3
+ credentialId: string;
4
+ accessToken: string;
5
+ baseUrl?: string;
6
+ now?: number;
7
+ fetch?: typeof fetch;
8
+ }): Promise<SubscriptionUsage | null>;
9
+ /** The most used window with a future reset, or null when the report has none. */
10
+ export declare function codexUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null;
@@ -0,0 +1,66 @@
1
+ // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
2
+ // usage never reaches the gateway as response headers. The ChatGPT backend's
3
+ // usage report (the endpoint behind the Codex CLI's /status) has the same
4
+ // windows; read it after a served call, at most once a minute per subscription.
5
+ const CODEX_USAGE_INTERVAL_MS = 60_000;
6
+ const CODEX_USAGE_TIMEOUT_MS = 8_000;
7
+ const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
8
+ const ACCOUNT_CLAIM = "https://api.openai.com/auth";
9
+ const readAt = new Map();
10
+ export async function readCodexUsage(args) {
11
+ const now = args.now ?? Date.now();
12
+ const last = readAt.get(args.credentialId);
13
+ if (last !== undefined && now - last < CODEX_USAGE_INTERVAL_MS)
14
+ return null;
15
+ readAt.set(args.credentialId, now);
16
+ const accountId = codexAccountId(args.accessToken);
17
+ const response = await (args.fetch ?? globalThis.fetch)(`${(args.baseUrl ?? DEFAULT_CODEX_BASE_URL).replace(/\/$/, "")}/wham/usage`, {
18
+ headers: {
19
+ Accept: "application/json",
20
+ Authorization: `Bearer ${args.accessToken}`,
21
+ ...(accountId === null ? {} : { "ChatGPT-Account-Id": accountId }),
22
+ },
23
+ signal: AbortSignal.timeout(CODEX_USAGE_TIMEOUT_MS),
24
+ });
25
+ if (!response.ok)
26
+ throw new Error(`Codex usage report failed with status ${response.status}.`);
27
+ return codexUsageFromReport(await response.json(), new Date(now));
28
+ }
29
+ /** The most used window with a future reset, or null when the report has none. */
30
+ export function codexUsageFromReport(report, now) {
31
+ const rateLimit = isRecord(report) && isRecord(report.rate_limit) ? report.rate_limit : {};
32
+ let binding = null;
33
+ for (const name of ["primary_window", "secondary_window"]) {
34
+ const window = rateLimit[name];
35
+ if (!isRecord(window))
36
+ continue;
37
+ const used = window.used_percent;
38
+ const resetAt = window.reset_at;
39
+ if (typeof used !== "number" || !Number.isFinite(used) || typeof resetAt !== "number")
40
+ continue;
41
+ const resetsAt = new Date(resetAt * 1000);
42
+ if (resetsAt <= now)
43
+ continue;
44
+ const utilization = Math.max(0, Math.min(1, used / 100));
45
+ if (binding === null || utilization > binding.utilization)
46
+ binding = { utilization, resetsAt };
47
+ }
48
+ return binding;
49
+ }
50
+ function codexAccountId(token) {
51
+ const [, payload] = token.split(".");
52
+ if (payload === undefined)
53
+ return null;
54
+ try {
55
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
56
+ const auth = isRecord(claims) ? claims[ACCOUNT_CLAIM] : undefined;
57
+ const accountId = isRecord(auth) ? auth.chatgpt_account_id : undefined;
58
+ return typeof accountId === "string" && accountId ? accountId : null;
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ function isRecord(value) {
65
+ return typeof value === "object" && value !== null && !Array.isArray(value);
66
+ }
@@ -12,7 +12,8 @@ import { runProviderAttemptPlan, } from "./provider_attempt_runner.js";
12
12
  import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } from "./cancel_estimate.js";
13
13
  import { providerResponseCaptureFromError } from "./response_capture.js";
14
14
  import { createStreamFinalizer } from "./stream_finalization.js";
15
- import { detectSubscriptionUsageLimit, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
15
+ import { readCodexUsage } from "./codex_usage.js";
16
+ import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
16
17
  export async function executeNonStreaming(args) {
17
18
  const result = await completeNonStreaming(args);
18
19
  if (result.reportBarrierError !== undefined) {
@@ -243,7 +244,9 @@ async function throwProviderFailure(args) {
243
244
  throw new HttpError(503, subscriptionSwitchedMessage(limit), "subscription_switched", undefined, { "retry-after": "1" });
244
245
  }
245
246
  if (limit !== null) {
246
- throw new HttpError(429, subscriptionUsageLimitMessage(limit), "subscription_usage_limit", undefined, { "retry-after": String(retryAfterSeconds(limit)) });
247
+ const accountsUrl = gatewayPlatform().accountsUrl;
248
+ const codex = codexUsageLimitError(limit, accountsUrl);
249
+ throw new HttpError(429, subscriptionUsageLimitMessage(limit, accountsUrl), "subscription_usage_limit", undefined, { "retry-after": String(retryAfterSeconds(limit)), ...codex?.headers }, codex?.body);
247
250
  }
248
251
  throw new HttpError(502, providerFailureMessage(result.failure), "provider_execution_failed");
249
252
  }
@@ -520,21 +523,29 @@ function onNextSubscription(choice, next) {
520
523
  // it without waiting, and never fail the request over it.
521
524
  function noteSubscriptionUsage(execution, responseCapture) {
522
525
  const platform = gatewayPlatform();
523
- const headers = responseCapture?.succeeded;
524
- if (platform.recordSubscriptionUsage === undefined ||
525
- headers === undefined ||
526
- execution.subscriptionUserId === undefined ||
527
- execution.subscriptionCredentialId === undefined) {
526
+ const userId = execution.subscriptionUserId;
527
+ const credentialId = execution.subscriptionCredentialId;
528
+ if (platform.recordSubscriptionUsage === undefined || userId === undefined || credentialId === undefined) {
528
529
  return;
529
530
  }
530
- const usage = subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
531
- if (usage === null)
532
- return;
533
- platform.recordSubscriptionUsage({
534
- userId: execution.subscriptionUserId,
535
- credentialId: execution.subscriptionCredentialId,
536
- usage,
537
- }).catch((error) => {
531
+ const record = platform.recordSubscriptionUsage.bind(platform);
532
+ const headers = responseCapture?.succeeded;
533
+ const fromHeaders = headers === undefined
534
+ ? null
535
+ : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
536
+ // Codex's WebSocket transport carries no headers; its usage report does.
537
+ const usage = fromHeaders !== null
538
+ ? Promise.resolve(fromHeaders)
539
+ : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
540
+ ? readCodexUsage({
541
+ credentialId,
542
+ accessToken: execution.apiKey,
543
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
544
+ })
545
+ : Promise.resolve(null);
546
+ usage
547
+ .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
548
+ .catch((error) => {
538
549
  console.error("subscription usage record failed", error);
539
550
  captureOperationalError(error, { code: "subscription_usage_record_failed" });
540
551
  });
@@ -18,9 +18,7 @@ export type SubscriptionUsage = {
18
18
  };
19
19
  /**
20
20
  * The quota a successful subscription response reports used, or null when it
21
- * reports none. Only Claude Code plans report usage on every response; a
22
- * ChatGPT plan reports it inside the response stream, which the provider
23
- * client does not surface, so its plans are switched only on a usage limit.
21
+ * reports none: the most used of the plan's windows.
24
22
  */
25
23
  export declare function subscriptionUsageFromHeaders(provider: string, keySource: ProviderKeySource, headers: Headers, now?: Date): SubscriptionUsage | null;
26
24
  export declare const DEFAULT_USAGE_LIMIT_WINDOW_MS: number;
@@ -44,6 +42,22 @@ export declare function detectSubscriptionUsageLimit(args: {
44
42
  /** Tag a provider failure so telemetry and the terminal error know why. */
45
43
  export declare function failureWithSubscriptionUsageLimit(failure: Record<string, unknown>, limit: SubscriptionUsageLimit): Record<string, unknown>;
46
44
  export declare function subscriptionUsageLimitFromFailure(failure: Record<string, unknown>): SubscriptionUsageLimit | null;
47
- export declare function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit): string;
45
+ /**
46
+ * The error for a plan out of quota with nothing to switch to. With the
47
+ * platform's accounts page it links there; without one (a self-hosted
48
+ * gateway) it points at `dari accounts`, which manages either.
49
+ */
50
+ export declare function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit, accountsUrl?: string): string;
51
+ /**
52
+ * Codex shows its own usage-limit notice and drops the message of any other
53
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
54
+ * the body type Codex recognizes, and how to add another plan as its promo
55
+ * message. Codex renders "You've hit your usage limit. <promo>, or try again
56
+ * at <reset>."
57
+ */
58
+ export declare function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?: string): {
59
+ body: Record<string, unknown>;
60
+ headers: Record<string, string>;
61
+ } | null;
48
62
  export declare function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string;
49
63
  export declare function retryAfterSeconds(limit: SubscriptionUsageLimit, now?: Date): number;
@@ -4,22 +4,33 @@ import { providerFailureMessage } from "../runtime/provider_stream_outcome.js";
4
4
  // same headers Claude Code itself reads: `-utilization` as a fraction of the
5
5
  // window and `-reset` in unix seconds.
6
6
  const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"];
7
+ // The ChatGPT backend reports each Codex window on every response, the same
8
+ // headers the Codex CLI reads: `-used-percent` out of 100 and `-reset-at` in
9
+ // unix seconds.
10
+ const CODEX_USAGE_WINDOWS = ["primary", "secondary"];
7
11
  /**
8
12
  * The quota a successful subscription response reports used, or null when it
9
- * reports none. Only Claude Code plans report usage on every response; a
10
- * ChatGPT plan reports it inside the response stream, which the provider
11
- * client does not surface, so its plans are switched only on a usage limit.
13
+ * reports none: the most used of the plan's windows.
12
14
  */
13
15
  export function subscriptionUsageFromHeaders(provider, keySource, headers, now = new Date()) {
14
- if (subscriptionOAuthProviderFor(provider, keySource) !== "anthropic_claude_code")
15
- return null;
16
+ const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
17
+ const windows = oauthProvider === "anthropic_claude_code"
18
+ ? CLAUDE_CODE_USAGE_WINDOWS.map((window) => ({
19
+ used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
20
+ reset: headers.get(`anthropic-ratelimit-unified-${window}-reset`),
21
+ }))
22
+ : oauthProvider === "openai_codex"
23
+ ? CODEX_USAGE_WINDOWS.map((window) => ({
24
+ used: Number(headers.get(`x-codex-${window}-used-percent`) ?? NaN) / 100,
25
+ reset: headers.get(`x-codex-${window}-reset-at`),
26
+ }))
27
+ : [];
16
28
  let binding = null;
17
- for (const window of CLAUDE_CODE_USAGE_WINDOWS) {
18
- const raw = Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN);
19
- const resetsAt = unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now);
20
- if (!Number.isFinite(raw) || resetsAt === null)
29
+ for (const { used, reset } of windows) {
30
+ const resetsAt = unixSecondsDeadline(reset, now);
31
+ if (!Number.isFinite(used) || resetsAt === null)
21
32
  continue;
22
- const utilization = Math.max(0, Math.min(1, raw));
33
+ const utilization = Math.max(0, Math.min(1, used));
23
34
  if (binding === null || utilization > binding.utilization)
24
35
  binding = { utilization, resetsAt };
25
36
  }
@@ -35,6 +46,8 @@ const SUBSCRIPTION_LABEL = {
35
46
  openai_codex: "ChatGPT",
36
47
  meta_muse: "Muse Code",
37
48
  };
49
+ // Providers whose plan page the accounts page links to for buying another.
50
+ const BUYABLE_SUBSCRIPTIONS = new Set(["anthropic_claude_code", "openai_codex"]);
38
51
  export function subscriptionOAuthProviderFor(provider, keySource) {
39
52
  if (keySource !== "subscription")
40
53
  return null;
@@ -189,10 +202,40 @@ export function subscriptionUsageLimitFromFailure(failure) {
189
202
  ...(marker.switched === true ? { switched: true } : {}),
190
203
  };
191
204
  }
192
- export function subscriptionUsageLimitMessage(limit) {
193
- return `Your ${SUBSCRIPTION_LABEL[limit.oauthProvider]} subscription usage limit is reached. `
194
- + `It resets at ${limit.resetsAt.toISOString()}. `
195
- + "Mark it available early at https://app.dari.dev/credentials.";
205
+ /**
206
+ * The error for a plan out of quota with nothing to switch to. With the
207
+ * platform's accounts page it links there; without one (a self-hosted
208
+ * gateway) it points at `dari accounts`, which manages either.
209
+ */
210
+ export function subscriptionUsageLimitMessage(limit, accountsUrl) {
211
+ const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
212
+ const reached = `Your ${label} subscription usage limit is reached. It resets at ${limit.resetsAt.toISOString()}. `;
213
+ if (accountsUrl === undefined) {
214
+ return reached
215
+ + `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
216
+ }
217
+ const buy = BUYABLE_SUBSCRIPTIONS.has(limit.oauthProvider)
218
+ ? ` To keep going now, add another ${label} subscription at ${accountsUrl}?buy=${limit.oauthProvider}.`
219
+ : "";
220
+ return `${reached}Mark it available early at ${accountsUrl}.${buy}`;
221
+ }
222
+ /**
223
+ * Codex shows its own usage-limit notice and drops the message of any other
224
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
225
+ * the body type Codex recognizes, and how to add another plan as its promo
226
+ * message. Codex renders "You've hit your usage limit. <promo>, or try again
227
+ * at <reset>."
228
+ */
229
+ export function codexUsageLimitError(limit, accountsUrl) {
230
+ if (limit.oauthProvider !== "openai_codex")
231
+ return null;
232
+ const promo = accountsUrl === undefined
233
+ ? "Add another ChatGPT subscription with `dari accounts`"
234
+ : `Add another ChatGPT subscription at ${accountsUrl}?buy=openai_codex`;
235
+ return {
236
+ body: { type: "usage_limit_reached", resets_at: Math.ceil(limit.resetsAt.getTime() / 1000) },
237
+ headers: { "x-codex-promo-message": promo },
238
+ };
196
239
  }
197
240
  export function subscriptionSwitchedMessage(limit) {
198
241
  const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.297",
3
+ "version": "1.0.299",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.297",
54
+ "@mupt-ai/dari-router": "1.0.299",
55
55
  "@mupt-ai/pi-ai": "1.4.0-mupt.3"
56
56
  },
57
57
  "devDependencies": {
@@ -7,6 +7,9 @@ export class HttpError extends Error {
7
7
  readonly param?: string;
8
8
  // Response headers the error carries to the client, such as retry-after.
9
9
  readonly headers?: Record<string, string>;
10
+ // Fields that replace or extend the OpenAI-shaped error object, for clients
11
+ // that read more than the message (such as Codex's usage-limit type).
12
+ readonly body?: Record<string, unknown>;
10
13
 
11
14
  constructor(
12
15
  status: number,
@@ -14,12 +17,14 @@ export class HttpError extends Error {
14
17
  code = "invalid_request_error",
15
18
  param?: string,
16
19
  headers?: Record<string, string>,
20
+ body?: Record<string, unknown>,
17
21
  ) {
18
22
  super(message);
19
23
  this.status = status;
20
24
  this.code = code;
21
25
  this.param = param;
22
26
  this.headers = headers;
27
+ this.body = body;
23
28
  }
24
29
  }
25
30
 
@@ -66,6 +71,7 @@ export function errorResponse(error: unknown): Response {
66
71
  type: openAiErrorType(normalized.status),
67
72
  code: normalized.code,
68
73
  ...(normalized.param ? { param: normalized.param } : {}),
74
+ ...(error instanceof HttpError ? error.body : undefined),
69
75
  },
70
76
  },
71
77
  { status: normalized.status, headers: errorResponseHeaders(error) }
@@ -23,6 +23,12 @@ import type {
23
23
  * log, and continue.
24
24
  */
25
25
  export type GatewayPlatform = {
26
+ /**
27
+ * Optional. The web page where users manage their subscriptions; usage-limit
28
+ * errors link to it, with `?buy=<provider>` to add another plan. Without
29
+ * one they point at `dari accounts`.
30
+ */
31
+ accountsUrl?: string;
26
32
  /**
27
33
  * Authenticate the request's key and return the router it may use, with
28
34
  * decrypted provider credentials and the prefix-cache evidence matching
@@ -0,0 +1,75 @@
1
+ import type { SubscriptionUsage } from "./subscription_limits.js";
2
+
3
+ // Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
4
+ // usage never reaches the gateway as response headers. The ChatGPT backend's
5
+ // usage report (the endpoint behind the Codex CLI's /status) has the same
6
+ // windows; read it after a served call, at most once a minute per subscription.
7
+ const CODEX_USAGE_INTERVAL_MS = 60_000;
8
+ const CODEX_USAGE_TIMEOUT_MS = 8_000;
9
+ const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
10
+ const ACCOUNT_CLAIM = "https://api.openai.com/auth";
11
+
12
+ const readAt = new Map<string, number>();
13
+
14
+ export async function readCodexUsage(args: {
15
+ credentialId: string;
16
+ accessToken: string;
17
+ baseUrl?: string;
18
+ now?: number;
19
+ fetch?: typeof fetch;
20
+ }): Promise<SubscriptionUsage | null> {
21
+ const now = args.now ?? Date.now();
22
+ const last = readAt.get(args.credentialId);
23
+ if (last !== undefined && now - last < CODEX_USAGE_INTERVAL_MS) return null;
24
+ readAt.set(args.credentialId, now);
25
+
26
+ const accountId = codexAccountId(args.accessToken);
27
+ const response = await (args.fetch ?? globalThis.fetch)(
28
+ `${(args.baseUrl ?? DEFAULT_CODEX_BASE_URL).replace(/\/$/, "")}/wham/usage`,
29
+ {
30
+ headers: {
31
+ Accept: "application/json",
32
+ Authorization: `Bearer ${args.accessToken}`,
33
+ ...(accountId === null ? {} : { "ChatGPT-Account-Id": accountId }),
34
+ },
35
+ signal: AbortSignal.timeout(CODEX_USAGE_TIMEOUT_MS),
36
+ },
37
+ );
38
+ if (!response.ok) throw new Error(`Codex usage report failed with status ${response.status}.`);
39
+ return codexUsageFromReport(await response.json(), new Date(now));
40
+ }
41
+
42
+ /** The most used window with a future reset, or null when the report has none. */
43
+ export function codexUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null {
44
+ const rateLimit = isRecord(report) && isRecord(report.rate_limit) ? report.rate_limit : {};
45
+ let binding: SubscriptionUsage | null = null;
46
+ for (const name of ["primary_window", "secondary_window"]) {
47
+ const window = rateLimit[name];
48
+ if (!isRecord(window)) continue;
49
+ const used = window.used_percent;
50
+ const resetAt = window.reset_at;
51
+ if (typeof used !== "number" || !Number.isFinite(used) || typeof resetAt !== "number") continue;
52
+ const resetsAt = new Date(resetAt * 1000);
53
+ if (resetsAt <= now) continue;
54
+ const utilization = Math.max(0, Math.min(1, used / 100));
55
+ if (binding === null || utilization > binding.utilization) binding = { utilization, resetsAt };
56
+ }
57
+ return binding;
58
+ }
59
+
60
+ function codexAccountId(token: string): string | null {
61
+ const [, payload] = token.split(".");
62
+ if (payload === undefined) return null;
63
+ try {
64
+ const claims: unknown = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
65
+ const auth = isRecord(claims) ? claims[ACCOUNT_CLAIM] : undefined;
66
+ const accountId = isRecord(auth) ? auth.chatgpt_account_id : undefined;
67
+ return typeof accountId === "string" && accountId ? accountId : null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ function isRecord(value: unknown): value is Record<string, unknown> {
74
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75
+ }
@@ -47,8 +47,11 @@ import {
47
47
  import type { NextSubscription } from "../platform/platform.js";
48
48
  import { providerResponseCaptureFromError, type ProviderResponseCapture } from "./response_capture.js";
49
49
  import { createStreamFinalizer } from "./stream_finalization.js";
50
+ import { readCodexUsage } from "./codex_usage.js";
50
51
  import {
51
52
  detectSubscriptionUsageLimit,
53
+ codexUsageLimitError,
54
+ subscriptionOAuthProviderFor,
52
55
  subscriptionUsageFromHeaders,
53
56
  failureWithSubscriptionUsageLimit,
54
57
  retryAfterSeconds,
@@ -436,12 +439,15 @@ async function throwProviderFailure(args: {
436
439
  );
437
440
  }
438
441
  if (limit !== null) {
442
+ const accountsUrl = gatewayPlatform().accountsUrl;
443
+ const codex = codexUsageLimitError(limit, accountsUrl);
439
444
  throw new HttpError(
440
445
  429,
441
- subscriptionUsageLimitMessage(limit),
446
+ subscriptionUsageLimitMessage(limit, accountsUrl),
442
447
  "subscription_usage_limit",
443
448
  undefined,
444
- { "retry-after": String(retryAfterSeconds(limit)) },
449
+ { "retry-after": String(retryAfterSeconds(limit)), ...codex?.headers },
450
+ codex?.body,
445
451
  );
446
452
  }
447
453
  throw new HttpError(
@@ -828,25 +834,32 @@ function noteSubscriptionUsage(
828
834
  responseCapture: ProviderResponseCapture | undefined,
829
835
  ): void {
830
836
  const platform = gatewayPlatform();
831
- const headers = responseCapture?.succeeded;
832
- if (
833
- platform.recordSubscriptionUsage === undefined ||
834
- headers === undefined ||
835
- execution.subscriptionUserId === undefined ||
836
- execution.subscriptionCredentialId === undefined
837
- ) {
837
+ const userId = execution.subscriptionUserId;
838
+ const credentialId = execution.subscriptionCredentialId;
839
+ if (platform.recordSubscriptionUsage === undefined || userId === undefined || credentialId === undefined) {
838
840
  return;
839
841
  }
840
- const usage = subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
841
- if (usage === null) return;
842
- platform.recordSubscriptionUsage({
843
- userId: execution.subscriptionUserId,
844
- credentialId: execution.subscriptionCredentialId,
845
- usage,
846
- }).catch((error: unknown) => {
847
- console.error("subscription usage record failed", error);
848
- captureOperationalError(error, { code: "subscription_usage_record_failed" });
849
- });
842
+ const record = platform.recordSubscriptionUsage.bind(platform);
843
+ const headers = responseCapture?.succeeded;
844
+ const fromHeaders = headers === undefined
845
+ ? null
846
+ : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
847
+ // Codex's WebSocket transport carries no headers; its usage report does.
848
+ const usage = fromHeaders !== null
849
+ ? Promise.resolve(fromHeaders)
850
+ : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
851
+ ? readCodexUsage({
852
+ credentialId,
853
+ accessToken: execution.apiKey,
854
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
855
+ })
856
+ : Promise.resolve(null);
857
+ usage
858
+ .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
859
+ .catch((error: unknown) => {
860
+ console.error("subscription usage record failed", error);
861
+ captureOperationalError(error, { code: "subscription_usage_record_failed" });
862
+ });
850
863
  }
851
864
 
852
865
  // Never fails the request: the provider already refused. Resolves whether
@@ -30,11 +30,14 @@ export type SubscriptionUsage = {
30
30
  // window and `-reset` in unix seconds.
31
31
  const CLAUDE_CODE_USAGE_WINDOWS = ["5h", "7d"] as const;
32
32
 
33
+ // The ChatGPT backend reports each Codex window on every response, the same
34
+ // headers the Codex CLI reads: `-used-percent` out of 100 and `-reset-at` in
35
+ // unix seconds.
36
+ const CODEX_USAGE_WINDOWS = ["primary", "secondary"] as const;
37
+
33
38
  /**
34
39
  * The quota a successful subscription response reports used, or null when it
35
- * reports none. Only Claude Code plans report usage on every response; a
36
- * ChatGPT plan reports it inside the response stream, which the provider
37
- * client does not surface, so its plans are switched only on a usage limit.
40
+ * reports none: the most used of the plan's windows.
38
41
  */
39
42
  export function subscriptionUsageFromHeaders(
40
43
  provider: string,
@@ -42,13 +45,23 @@ export function subscriptionUsageFromHeaders(
42
45
  headers: Headers,
43
46
  now = new Date(),
44
47
  ): SubscriptionUsage | null {
45
- if (subscriptionOAuthProviderFor(provider, keySource) !== "anthropic_claude_code") return null;
48
+ const oauthProvider = subscriptionOAuthProviderFor(provider, keySource);
49
+ const windows = oauthProvider === "anthropic_claude_code"
50
+ ? CLAUDE_CODE_USAGE_WINDOWS.map((window) => ({
51
+ used: Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN),
52
+ reset: headers.get(`anthropic-ratelimit-unified-${window}-reset`),
53
+ }))
54
+ : oauthProvider === "openai_codex"
55
+ ? CODEX_USAGE_WINDOWS.map((window) => ({
56
+ used: Number(headers.get(`x-codex-${window}-used-percent`) ?? NaN) / 100,
57
+ reset: headers.get(`x-codex-${window}-reset-at`),
58
+ }))
59
+ : [];
46
60
  let binding: SubscriptionUsage | null = null;
47
- for (const window of CLAUDE_CODE_USAGE_WINDOWS) {
48
- const raw = Number(headers.get(`anthropic-ratelimit-unified-${window}-utilization`) ?? NaN);
49
- const resetsAt = unixSecondsDeadline(headers.get(`anthropic-ratelimit-unified-${window}-reset`), now);
50
- if (!Number.isFinite(raw) || resetsAt === null) continue;
51
- const utilization = Math.max(0, Math.min(1, raw));
61
+ for (const { used, reset } of windows) {
62
+ const resetsAt = unixSecondsDeadline(reset, now);
63
+ if (!Number.isFinite(used) || resetsAt === null) continue;
64
+ const utilization = Math.max(0, Math.min(1, used));
52
65
  if (binding === null || utilization > binding.utilization) binding = { utilization, resetsAt };
53
66
  }
54
67
  return binding;
@@ -67,6 +80,9 @@ const SUBSCRIPTION_LABEL: Record<SubscriptionOAuthProvider, string> = {
67
80
  meta_muse: "Muse Code",
68
81
  };
69
82
 
83
+ // Providers whose plan page the accounts page links to for buying another.
84
+ const BUYABLE_SUBSCRIPTIONS = new Set<SubscriptionOAuthProvider>(["anthropic_claude_code", "openai_codex"]);
85
+
70
86
  export function subscriptionOAuthProviderFor(
71
87
  provider: string,
72
88
  keySource: ProviderKeySource,
@@ -247,10 +263,43 @@ export function subscriptionUsageLimitFromFailure(
247
263
  };
248
264
  }
249
265
 
250
- export function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit): string {
251
- return `Your ${SUBSCRIPTION_LABEL[limit.oauthProvider]} subscription usage limit is reached. `
252
- + `It resets at ${limit.resetsAt.toISOString()}. `
253
- + "Mark it available early at https://app.dari.dev/credentials.";
266
+ /**
267
+ * The error for a plan out of quota with nothing to switch to. With the
268
+ * platform's accounts page it links there; without one (a self-hosted
269
+ * gateway) it points at `dari accounts`, which manages either.
270
+ */
271
+ export function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit, accountsUrl?: string): string {
272
+ const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
273
+ const reached = `Your ${label} subscription usage limit is reached. It resets at ${limit.resetsAt.toISOString()}. `;
274
+ if (accountsUrl === undefined) {
275
+ return reached
276
+ + `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
277
+ }
278
+ const buy = BUYABLE_SUBSCRIPTIONS.has(limit.oauthProvider)
279
+ ? ` To keep going now, add another ${label} subscription at ${accountsUrl}?buy=${limit.oauthProvider}.`
280
+ : "";
281
+ return `${reached}Mark it available early at ${accountsUrl}.${buy}`;
282
+ }
283
+
284
+ /**
285
+ * Codex shows its own usage-limit notice and drops the message of any other
286
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
287
+ * the body type Codex recognizes, and how to add another plan as its promo
288
+ * message. Codex renders "You've hit your usage limit. <promo>, or try again
289
+ * at <reset>."
290
+ */
291
+ export function codexUsageLimitError(limit: SubscriptionUsageLimit, accountsUrl?: string): {
292
+ body: Record<string, unknown>;
293
+ headers: Record<string, string>;
294
+ } | null {
295
+ if (limit.oauthProvider !== "openai_codex") return null;
296
+ const promo = accountsUrl === undefined
297
+ ? "Add another ChatGPT subscription with `dari accounts`"
298
+ : `Add another ChatGPT subscription at ${accountsUrl}?buy=openai_codex`;
299
+ return {
300
+ body: { type: "usage_limit_reached", resets_at: Math.ceil(limit.resetsAt.getTime() / 1000) },
301
+ headers: { "x-codex-promo-message": promo },
302
+ };
254
303
  }
255
304
 
256
305
  export function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string {