@mupt-ai/dari-gateway 1.0.296 → 1.0.298

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
  }
@@ -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,8 @@ 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 codex = codexUsageLimitError(limit);
248
+ throw new HttpError(429, subscriptionUsageLimitMessage(limit), "subscription_usage_limit", undefined, { "retry-after": String(retryAfterSeconds(limit)), ...codex?.headers }, codex?.body);
247
249
  }
248
250
  throw new HttpError(502, providerFailureMessage(result.failure), "provider_execution_failed");
249
251
  }
@@ -520,21 +522,29 @@ function onNextSubscription(choice, next) {
520
522
  // it without waiting, and never fail the request over it.
521
523
  function noteSubscriptionUsage(execution, responseCapture) {
522
524
  const platform = gatewayPlatform();
523
- const headers = responseCapture?.succeeded;
524
- if (platform.recordSubscriptionUsage === undefined ||
525
- headers === undefined ||
526
- execution.subscriptionUserId === undefined ||
527
- execution.subscriptionCredentialId === undefined) {
525
+ const userId = execution.subscriptionUserId;
526
+ const credentialId = execution.subscriptionCredentialId;
527
+ if (platform.recordSubscriptionUsage === undefined || userId === undefined || credentialId === undefined) {
528
528
  return;
529
529
  }
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) => {
530
+ const record = platform.recordSubscriptionUsage.bind(platform);
531
+ const headers = responseCapture?.succeeded;
532
+ const fromHeaders = headers === undefined
533
+ ? null
534
+ : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
535
+ // Codex's WebSocket transport carries no headers; its usage report does.
536
+ const usage = fromHeaders !== null
537
+ ? Promise.resolve(fromHeaders)
538
+ : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
539
+ ? readCodexUsage({
540
+ credentialId,
541
+ accessToken: execution.apiKey,
542
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
543
+ })
544
+ : Promise.resolve(null);
545
+ usage
546
+ .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
547
+ .catch((error) => {
538
548
  console.error("subscription usage record failed", error);
539
549
  captureOperationalError(error, { code: "subscription_usage_record_failed" });
540
550
  });
@@ -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;
@@ -45,5 +43,15 @@ export declare function detectSubscriptionUsageLimit(args: {
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
45
  export declare function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit): string;
46
+ /**
47
+ * Codex shows its own usage-limit notice and drops the message of any other
48
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
49
+ * the body type Codex recognizes, and the buy link as its promo message.
50
+ * Codex renders "You've hit your usage limit. <promo>, or try again at <reset>."
51
+ */
52
+ export declare function codexUsageLimitError(limit: SubscriptionUsageLimit): {
53
+ body: Record<string, unknown>;
54
+ headers: Record<string, string>;
55
+ } | null;
48
56
  export declare function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string;
49
57
  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 Dari's credentials 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;
@@ -192,7 +205,35 @@ export function subscriptionUsageLimitFromFailure(failure) {
192
205
  export function subscriptionUsageLimitMessage(limit) {
193
206
  return `Your ${SUBSCRIPTION_LABEL[limit.oauthProvider]} subscription usage limit is reached. `
194
207
  + `It resets at ${limit.resetsAt.toISOString()}. `
195
- + "Mark it available early at https://app.dari.dev/credentials.";
208
+ + "Mark it available early at https://app.dari.dev/credentials."
209
+ + subscriptionBuyHint(limit.oauthProvider);
210
+ }
211
+ // To keep going now: Dari's page links to subscribing another account and
212
+ // connects it.
213
+ function subscriptionBuyHint(provider) {
214
+ const action = subscriptionBuyAction(provider);
215
+ return action === null ? "" : ` To keep going now, ${action.charAt(0).toLowerCase()}${action.slice(1)}.`;
216
+ }
217
+ function subscriptionBuyAction(provider) {
218
+ if (!BUYABLE_SUBSCRIPTIONS.has(provider))
219
+ return null;
220
+ return `Add another ${SUBSCRIPTION_LABEL[provider]} subscription at `
221
+ + `https://app.dari.dev/credentials?buy=${provider}`;
222
+ }
223
+ /**
224
+ * Codex shows its own usage-limit notice and drops the message of any other
225
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
226
+ * the body type Codex recognizes, and the buy link as its promo message.
227
+ * Codex renders "You've hit your usage limit. <promo>, or try again at <reset>."
228
+ */
229
+ export function codexUsageLimitError(limit) {
230
+ if (limit.oauthProvider !== "openai_codex")
231
+ return null;
232
+ const promo = subscriptionBuyAction(limit.oauthProvider);
233
+ return {
234
+ body: { type: "usage_limit_reached", resets_at: Math.ceil(limit.resetsAt.getTime() / 1000) },
235
+ headers: promo === null ? {} : { "x-codex-promo-message": promo },
236
+ };
196
237
  }
197
238
  export function subscriptionSwitchedMessage(limit) {
198
239
  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.296",
3
+ "version": "1.0.298",
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.296",
54
+ "@mupt-ai/dari-router": "1.0.298",
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) }
@@ -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,14 @@ async function throwProviderFailure(args: {
436
439
  );
437
440
  }
438
441
  if (limit !== null) {
442
+ const codex = codexUsageLimitError(limit);
439
443
  throw new HttpError(
440
444
  429,
441
445
  subscriptionUsageLimitMessage(limit),
442
446
  "subscription_usage_limit",
443
447
  undefined,
444
- { "retry-after": String(retryAfterSeconds(limit)) },
448
+ { "retry-after": String(retryAfterSeconds(limit)), ...codex?.headers },
449
+ codex?.body,
445
450
  );
446
451
  }
447
452
  throw new HttpError(
@@ -828,25 +833,32 @@ function noteSubscriptionUsage(
828
833
  responseCapture: ProviderResponseCapture | undefined,
829
834
  ): void {
830
835
  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
- ) {
836
+ const userId = execution.subscriptionUserId;
837
+ const credentialId = execution.subscriptionCredentialId;
838
+ if (platform.recordSubscriptionUsage === undefined || userId === undefined || credentialId === undefined) {
838
839
  return;
839
840
  }
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
- });
841
+ const record = platform.recordSubscriptionUsage.bind(platform);
842
+ const headers = responseCapture?.succeeded;
843
+ const fromHeaders = headers === undefined
844
+ ? null
845
+ : subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
846
+ // Codex's WebSocket transport carries no headers; its usage report does.
847
+ const usage = fromHeaders !== null
848
+ ? Promise.resolve(fromHeaders)
849
+ : subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "openai_codex"
850
+ ? readCodexUsage({
851
+ credentialId,
852
+ accessToken: execution.apiKey,
853
+ baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
854
+ })
855
+ : Promise.resolve(null);
856
+ usage
857
+ .then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
858
+ .catch((error: unknown) => {
859
+ console.error("subscription usage record failed", error);
860
+ captureOperationalError(error, { code: "subscription_usage_record_failed" });
861
+ });
850
862
  }
851
863
 
852
864
  // 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 Dari's credentials 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,
@@ -250,7 +266,39 @@ export function subscriptionUsageLimitFromFailure(
250
266
  export function subscriptionUsageLimitMessage(limit: SubscriptionUsageLimit): string {
251
267
  return `Your ${SUBSCRIPTION_LABEL[limit.oauthProvider]} subscription usage limit is reached. `
252
268
  + `It resets at ${limit.resetsAt.toISOString()}. `
253
- + "Mark it available early at https://app.dari.dev/credentials.";
269
+ + "Mark it available early at https://app.dari.dev/credentials."
270
+ + subscriptionBuyHint(limit.oauthProvider);
271
+ }
272
+
273
+ // To keep going now: Dari's page links to subscribing another account and
274
+ // connects it.
275
+ function subscriptionBuyHint(provider: SubscriptionOAuthProvider): string {
276
+ const action = subscriptionBuyAction(provider);
277
+ return action === null ? "" : ` To keep going now, ${action.charAt(0).toLowerCase()}${action.slice(1)}.`;
278
+ }
279
+
280
+ function subscriptionBuyAction(provider: SubscriptionOAuthProvider): string | null {
281
+ if (!BUYABLE_SUBSCRIPTIONS.has(provider)) return null;
282
+ return `Add another ${SUBSCRIPTION_LABEL[provider]} subscription at `
283
+ + `https://app.dari.dev/credentials?buy=${provider}`;
284
+ }
285
+
286
+ /**
287
+ * Codex shows its own usage-limit notice and drops the message of any other
288
+ * 429, so an exhausted ChatGPT plan answers in the ChatGPT backend's shape:
289
+ * the body type Codex recognizes, and the buy link as its promo message.
290
+ * Codex renders "You've hit your usage limit. <promo>, or try again at <reset>."
291
+ */
292
+ export function codexUsageLimitError(limit: SubscriptionUsageLimit): {
293
+ body: Record<string, unknown>;
294
+ headers: Record<string, string>;
295
+ } | null {
296
+ if (limit.oauthProvider !== "openai_codex") return null;
297
+ const promo = subscriptionBuyAction(limit.oauthProvider);
298
+ return {
299
+ body: { type: "usage_limit_reached", resets_at: Math.ceil(limit.resetsAt.getTime() / 1000) },
300
+ headers: promo === null ? {} : { "x-codex-promo-message": promo },
301
+ };
254
302
  }
255
303
 
256
304
  export function subscriptionSwitchedMessage(limit: SubscriptionUsageLimit): string {