claude-codex-proxy 1.0.5-beta.18 → 1.0.5-beta.19

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-codex-proxy",
3
- "version": "1.0.5-beta.18",
3
+ "version": "1.0.5-beta.19",
4
4
  "description": "Multi-account proxy server for OpenAI Codex CLI with Claude API compatibility",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/public/js/app.js CHANGED
@@ -117,7 +117,32 @@ document.addEventListener('alpine:init', () => {
117
117
  async loadRateLimitResetCredits(email) { this.resetCreditsLoading = true; this.resetCredits = []; this.resetCreditsAccountEmail = email; this.resetCreditRedeemRequestId = ''; const { ok, data } = await this.api(`/accounts/rate-limit-reset-credits?email=${encodeURIComponent(email)}`); this.resetCreditsLoading = false; if (this.resetCreditsAccountEmail !== email) return; if (ok) this.resetCredits = this.normalizeRateLimitResetCredits(data?.credits); else this.showToast(data?.error || 'Failed to load reset credits', 'error'); },
118
118
  availableRateLimitResetCredits() { return this.resetCredits.filter(credit => credit?.status === 'available').sort((a, b) => new Date(b.expires_at || 0).getTime() - new Date(a.expires_at || 0).getTime()); },
119
119
  resetCreditExpiryLabel(credit) { const date = credit?.expires_at && new Date(credit.expires_at); return date && !Number.isNaN(date.getTime()) ? date.toLocaleString() : '-'; },
120
- async redeemRateLimitResetCredit(creditId = null) { if (!this.selectedAccount || this.resetCreditsRedeeming) return; this.resetCreditsRedeeming = true; if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = crypto.randomUUID(); const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', { method: 'POST', body: JSON.stringify({ email: this.selectedAccount.email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId }) }); this.resetCreditsRedeeming = false; if (ok && data?.success) { this.showToast('Quota reset credit redeemed', 'success'); this.resetCreditRedeemRequestId = ''; await Promise.all([this.loadRateLimitResetCredits(this.selectedAccount.email), this.refreshAccounts()]); } else this.showToast(data?.error || 'Failed to redeem reset credit', 'error'); },
120
+ generateUUID() {
121
+ if (typeof globalThis.crypto?.randomUUID === 'function') {
122
+ return globalThis.crypto.randomUUID();
123
+ }
124
+
125
+ const bytes = new Uint8Array(16);
126
+ globalThis.crypto.getRandomValues(bytes);
127
+
128
+ // UUID v4
129
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
130
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
131
+
132
+ const hex = Array.from(
133
+ bytes,
134
+ byte => byte.toString(16).padStart(2, '0')
135
+ );
136
+
137
+ return [
138
+ hex.slice(0, 4).join(''),
139
+ hex.slice(4, 6).join(''),
140
+ hex.slice(6, 8).join(''),
141
+ hex.slice(8, 10).join(''),
142
+ hex.slice(10, 16).join('')
143
+ ].join('-');
144
+ },
145
+ async redeemRateLimitResetCredit(creditId = null) { if (!this.selectedAccount || this.resetCreditsRedeeming) return; this.resetCreditsRedeeming = true; if (!this.resetCreditRedeemRequestId) this.resetCreditRedeemRequestId = this.generateUUID(); const { ok, data } = await this.api('/accounts/rate-limit-reset-credits/consume', { method: 'POST', body: JSON.stringify({ email: this.selectedAccount.email, creditId: creditId || undefined, redeemRequestId: this.resetCreditRedeemRequestId }) }); this.resetCreditsRedeeming = false; if (ok && data?.success) { this.showToast('Quota reset credit redeemed', 'success'); this.resetCreditRedeemRequestId = ''; await Promise.all([this.loadRateLimitResetCredits(this.selectedAccount.email), this.refreshAccounts()]); } else this.showToast(data?.error || 'Failed to redeem reset credit', 'error'); },
121
146
  async testChat() { if (!this.testPrompt.trim()) return; this.testing = true; this.testResponse = ''; const { ok, data } = await this.api('/v1/chat/completions', { method: 'POST', body: JSON.stringify({ model: this.modelMappings?.sonnet || 'gpt-5.5', messages: [{ role: 'user', content: this.testPrompt }] }) }); this.testing = false; this.testResponse = ok && data.choices ? data.choices[0]?.message?.content || `[Empty response]\n\n${JSON.stringify(data, null, 2)}` : data?.error?.message || data?.error || 'Request failed'; },
122
147
  async loadAccountStrategySetting() { const { ok, data } = await this.api('/settings/account-strategy'); if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; }, async setAccountStrategy(strategy) { if (this.strategySaving || this.accountStrategy === strategy) return; this.strategySaving = true; const { ok, data } = await this.api('/settings/account-strategy', { method: 'POST', body: JSON.stringify({ accountStrategy: strategy }) }); this.strategySaving = false; if (ok && data?.accountStrategy) this.accountStrategy = data.accountStrategy; else this.showToast(data?.error || 'Failed to update strategy', 'error'); },
123
148
  async loadRawProxyLogsSetting() { const { ok, data } = await this.api('/settings/raw-proxy-logs'); if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; }, async setRawProxyLogs(enabled) { if (this.rawProxyLogsSaving || this.logRawProxyPayloads === enabled) return; this.rawProxyLogsSaving = true; const { ok, data } = await this.api('/settings/raw-proxy-logs', { method: 'POST', body: JSON.stringify({ enabled }) }); this.rawProxyLogsSaving = false; if (ok && typeof data?.logRawProxyPayloads === 'boolean') this.logRawProxyPayloads = data.logRawProxyPayloads; else this.showToast(data?.error || 'Failed to update raw proxy logging', 'error'); },
package/src/admin-path.js CHANGED
@@ -1,33 +1,33 @@
1
- /**
2
- * Resolves the non-public prefix used for the management UI and its APIs.
3
- */
4
-
5
- const DEFAULT_ADMIN_PATH = '/admin';
6
- const VALID_ADMIN_PATH = /^\/[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
7
- const RESERVED_PATHS = ['/v1', '/health', '/claude'];
8
-
9
- /**
10
- * Returns the validated management UI path prefix.
11
- * @returns {string}
12
- */
13
- export function getAdminPath() {
14
- const adminPath = process.env.PROXY_ADMIN_PATH || DEFAULT_ADMIN_PATH;
15
- if (!VALID_ADMIN_PATH.test(adminPath)) {
16
- throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". Use an absolute path without trailing slashes, query strings, or ".." segments.`);
17
- }
18
-
19
- const overlapsReservedPath = RESERVED_PATHS.some((reservedPath) => (
20
- adminPath === reservedPath
21
- || adminPath.startsWith(`${reservedPath}/`)
22
- || reservedPath.startsWith(`${adminPath}/`)
23
- ));
24
- if (overlapsReservedPath) {
25
- throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". The path must not overlap reserved routes: ${RESERVED_PATHS.join(', ')}.`);
26
- }
27
-
28
- return adminPath;
29
- }
30
-
31
- export { DEFAULT_ADMIN_PATH };
32
-
33
- export default { getAdminPath, DEFAULT_ADMIN_PATH };
1
+ /**
2
+ * Resolves the non-public prefix used for the management UI and its APIs.
3
+ */
4
+
5
+ const DEFAULT_ADMIN_PATH = '/admin';
6
+ const VALID_ADMIN_PATH = /^\/[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)*$/;
7
+ const RESERVED_PATHS = ['/v1', '/health', '/claude'];
8
+
9
+ /**
10
+ * Returns the validated management UI path prefix.
11
+ * @returns {string}
12
+ */
13
+ export function getAdminPath() {
14
+ const adminPath = process.env.PROXY_ADMIN_PATH || DEFAULT_ADMIN_PATH;
15
+ if (!VALID_ADMIN_PATH.test(adminPath)) {
16
+ throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". Use an absolute path without trailing slashes, query strings, or ".." segments.`);
17
+ }
18
+
19
+ const overlapsReservedPath = RESERVED_PATHS.some((reservedPath) => (
20
+ adminPath === reservedPath
21
+ || adminPath.startsWith(`${reservedPath}/`)
22
+ || reservedPath.startsWith(`${adminPath}/`)
23
+ ));
24
+ if (overlapsReservedPath) {
25
+ throw new Error(`Invalid PROXY_ADMIN_PATH "${adminPath}". The path must not overlap reserved routes: ${RESERVED_PATHS.join(', ')}.`);
26
+ }
27
+
28
+ return adminPath;
29
+ }
30
+
31
+ export { DEFAULT_ADMIN_PATH };
32
+
33
+ export default { getAdminPath, DEFAULT_ADMIN_PATH };
@@ -1,125 +1,125 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
2
- import { join } from 'path';
3
- import { CONFIG_DIR } from './account-manager.js';
4
-
5
- const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
6
- export const MICRO_USD_PER_USD = 1_000_000;
7
-
8
- function loadUsage() {
9
- if (!existsSync(USAGE_FILE)) return {};
10
-
11
- try {
12
- const data = JSON.parse(readFileSync(USAGE_FILE, 'utf8'));
13
- return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
14
- } catch (error) {
15
- console.error('[ClientKeyUsage] Failed to read usage:', error.message);
16
- return {};
17
- }
18
- }
19
-
20
- function saveUsage(usage) {
21
- if (!existsSync(CONFIG_DIR)) {
22
- mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
23
- }
24
- writeFileSync(USAGE_FILE, JSON.stringify(usage, null, 2), { mode: 0o600 });
25
- }
26
-
27
- /**
28
- * Returns the current weekly period start in the server's local time zone.
29
- * A period begins at Monday 08:00 and ends at the following Monday 08:00.
30
- */
31
- export function getCurrentPeriodStart(now = new Date()) {
32
- const periodStart = new Date(now);
33
- const daysSinceMonday = (periodStart.getDay() + 6) % 7;
34
- periodStart.setDate(periodStart.getDate() - daysSinceMonday);
35
- periodStart.setHours(8, 0, 0, 0);
36
-
37
- if (now < periodStart) {
38
- periodStart.setDate(periodStart.getDate() - 7);
39
- }
40
-
41
- return periodStart.toISOString();
42
- }
43
-
44
- export function getNextPeriodStart(now = new Date()) {
45
- const nextPeriodStart = new Date(getCurrentPeriodStart(now));
46
- nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
47
- return nextPeriodStart.toISOString();
48
- }
49
-
50
- export function usdToMicrousd(usd) {
51
- return Math.round(Number(usd) * MICRO_USD_PER_USD);
52
- }
53
-
54
- export function microusdToUsd(microusd) {
55
- return Number(microusd) / MICRO_USD_PER_USD;
56
- }
57
-
58
- /**
59
- * Returns a key's usage after lazily resetting it for a new weekly period.
60
- */
61
- export function getClientKeyUsage(keyId, now = new Date()) {
62
- const usage = loadUsage();
63
- const periodStart = getCurrentPeriodStart(now);
64
- const entry = usage[keyId];
65
- const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
66
- ? Math.max(0, entry.consumedMicrousd)
67
- : 0;
68
-
69
- if (!entry || entry.periodStart !== periodStart || entry.consumedMicrousd !== consumedMicrousd) {
70
- usage[keyId] = { periodStart, consumedMicrousd };
71
- saveUsage(usage);
72
- }
73
-
74
- return {
75
- periodStart,
76
- nextPeriodStart: getNextPeriodStart(now),
77
- consumedMicrousd
78
- };
79
- }
80
-
81
- /**
82
- * Records actual USD consumption for a client key. Call this only after an
83
- * upstream response provides a verified per-request charge.
84
- */
85
- export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
86
- if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
87
- throw new TypeError('consumedMicrousd must be a non-negative safe integer');
88
- }
89
-
90
- const current = getClientKeyUsage(keyId, now);
91
- const usage = loadUsage();
92
- usage[keyId] = {
93
- periodStart: current.periodStart,
94
- consumedMicrousd: current.consumedMicrousd + consumedMicrousd
95
- };
96
- saveUsage(usage);
97
- return usage[keyId];
98
- }
99
-
100
- export function deleteClientKeyUsage(keyId) {
101
- const usage = loadUsage();
102
- if (!(keyId in usage)) return;
103
- delete usage[keyId];
104
- saveUsage(usage);
105
- }
106
-
107
- /**
108
- * Returns a key's current quota summary without charging any request.
109
- */
110
- export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
111
- const usage = getClientKeyUsage(keyId, now);
112
- const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
113
- const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
114
-
115
- return {
116
- ...usage,
117
- weeklyLimitMicrousd,
118
- remainingMicrousd,
119
- weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
120
- consumedUsd: microusdToUsd(usage.consumedMicrousd),
121
- remainingUsd: microusdToUsd(remainingMicrousd)
122
- };
123
- }
124
-
125
- export { USAGE_FILE };
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { CONFIG_DIR } from './account-manager.js';
4
+
5
+ const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
6
+ export const MICRO_USD_PER_USD = 1_000_000;
7
+
8
+ function loadUsage() {
9
+ if (!existsSync(USAGE_FILE)) return {};
10
+
11
+ try {
12
+ const data = JSON.parse(readFileSync(USAGE_FILE, 'utf8'));
13
+ return data && typeof data === 'object' && !Array.isArray(data) ? data : {};
14
+ } catch (error) {
15
+ console.error('[ClientKeyUsage] Failed to read usage:', error.message);
16
+ return {};
17
+ }
18
+ }
19
+
20
+ function saveUsage(usage) {
21
+ if (!existsSync(CONFIG_DIR)) {
22
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
23
+ }
24
+ writeFileSync(USAGE_FILE, JSON.stringify(usage, null, 2), { mode: 0o600 });
25
+ }
26
+
27
+ /**
28
+ * Returns the current weekly period start in the server's local time zone.
29
+ * A period begins at Monday 08:00 and ends at the following Monday 08:00.
30
+ */
31
+ export function getCurrentPeriodStart(now = new Date()) {
32
+ const periodStart = new Date(now);
33
+ const daysSinceMonday = (periodStart.getDay() + 6) % 7;
34
+ periodStart.setDate(periodStart.getDate() - daysSinceMonday);
35
+ periodStart.setHours(8, 0, 0, 0);
36
+
37
+ if (now < periodStart) {
38
+ periodStart.setDate(periodStart.getDate() - 7);
39
+ }
40
+
41
+ return periodStart.toISOString();
42
+ }
43
+
44
+ export function getNextPeriodStart(now = new Date()) {
45
+ const nextPeriodStart = new Date(getCurrentPeriodStart(now));
46
+ nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
47
+ return nextPeriodStart.toISOString();
48
+ }
49
+
50
+ export function usdToMicrousd(usd) {
51
+ return Math.round(Number(usd) * MICRO_USD_PER_USD);
52
+ }
53
+
54
+ export function microusdToUsd(microusd) {
55
+ return Number(microusd) / MICRO_USD_PER_USD;
56
+ }
57
+
58
+ /**
59
+ * Returns a key's usage after lazily resetting it for a new weekly period.
60
+ */
61
+ export function getClientKeyUsage(keyId, now = new Date()) {
62
+ const usage = loadUsage();
63
+ const periodStart = getCurrentPeriodStart(now);
64
+ const entry = usage[keyId];
65
+ const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
66
+ ? Math.max(0, entry.consumedMicrousd)
67
+ : 0;
68
+
69
+ if (!entry || entry.periodStart !== periodStart || entry.consumedMicrousd !== consumedMicrousd) {
70
+ usage[keyId] = { periodStart, consumedMicrousd };
71
+ saveUsage(usage);
72
+ }
73
+
74
+ return {
75
+ periodStart,
76
+ nextPeriodStart: getNextPeriodStart(now),
77
+ consumedMicrousd
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Records actual USD consumption for a client key. Call this only after an
83
+ * upstream response provides a verified per-request charge.
84
+ */
85
+ export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
86
+ if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
87
+ throw new TypeError('consumedMicrousd must be a non-negative safe integer');
88
+ }
89
+
90
+ const current = getClientKeyUsage(keyId, now);
91
+ const usage = loadUsage();
92
+ usage[keyId] = {
93
+ periodStart: current.periodStart,
94
+ consumedMicrousd: current.consumedMicrousd + consumedMicrousd
95
+ };
96
+ saveUsage(usage);
97
+ return usage[keyId];
98
+ }
99
+
100
+ export function deleteClientKeyUsage(keyId) {
101
+ const usage = loadUsage();
102
+ if (!(keyId in usage)) return;
103
+ delete usage[keyId];
104
+ saveUsage(usage);
105
+ }
106
+
107
+ /**
108
+ * Returns a key's current quota summary without charging any request.
109
+ */
110
+ export function getClientKeyQuota(keyId, weeklyLimitUsd, now = new Date()) {
111
+ const usage = getClientKeyUsage(keyId, now);
112
+ const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
113
+ const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
114
+
115
+ return {
116
+ ...usage,
117
+ weeklyLimitMicrousd,
118
+ remainingMicrousd,
119
+ weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
120
+ consumedUsd: microusdToUsd(usage.consumedMicrousd),
121
+ remainingUsd: microusdToUsd(remainingMicrousd)
122
+ };
123
+ }
124
+
125
+ export { USAGE_FILE };
@@ -1,127 +1,127 @@
1
- /**
2
- * Upstream Codex model pricing in USD per one million tokens.
3
- * Long-context pricing applies when input tokens exceed 272,000.
4
- */
5
-
6
- export const PRICE_UNIT_TOKENS = 1_000_000;
7
- export const LONG_CONTEXT_THRESHOLD_TOKENS = 272_000;
8
- // For models without a configured price, billing is uniformly based on this model.
9
- export const DEFAULT_PRICING_MODEL = 'gpt-5.6-sol';
10
-
11
- const STANDARD_PRICING = {
12
- 'gpt-5.6-sol': {
13
- input: 5,
14
- cachedInput: 0.5,
15
- cacheWrite: 6.25,
16
- output: 30
17
- },
18
- 'gpt-5.6-terra': {
19
- input: 2.5,
20
- cachedInput: 0.25,
21
- cacheWrite: 3.125,
22
- output: 15
23
- },
24
- 'gpt-5.4-mini': {
25
- input: 0.75,
26
- cachedInput: 0.075,
27
- cacheWrite: 0,
28
- output: 4.5
29
- }
30
- };
31
-
32
- const LONG_CONTEXT_PRICING = {
33
- 'gpt-5.6-sol': {
34
- input: 10,
35
- cachedInput: 1,
36
- cacheWrite: 12.5,
37
- output: 45
38
- },
39
- 'gpt-5.6-terra': {
40
- input: 5,
41
- cachedInput: 0.5,
42
- cacheWrite: 6.25,
43
- output: 22.5
44
- }
45
- };
46
-
47
- /**
48
- * Returns the applicable USD-per-million-token price record for an upstream
49
- * model. Models without a configured price use DEFAULT_PRICING_MODEL.
50
- */
51
- export function getModelPricing(model, inputTokens = 0) {
52
- const requestedModel = String(model || '').trim().toLowerCase();
53
-
54
- // Use the current model if it has a price;
55
- // use the default pricing model if no price is configured.
56
- const pricingModel = STANDARD_PRICING[requestedModel]
57
- ? requestedModel
58
- : DEFAULT_PRICING_MODEL;
59
-
60
- const standard = STANDARD_PRICING[pricingModel];
61
-
62
- // Prevent DEFAULT_PRICING_MODEL configuration errors.
63
- if (!standard) {
64
- throw new Error(
65
- `Default pricing model "${DEFAULT_PRICING_MODEL}" is not configured`
66
- );
67
- }
68
-
69
- const usesLongContext =
70
- Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
71
-
72
- const longContext = usesLongContext
73
- ? LONG_CONTEXT_PRICING[pricingModel]
74
- : null;
75
-
76
- return {
77
- ...standard,
78
- ...(longContext || {}),
79
-
80
- // The model actually requested
81
- model: requestedModel,
82
-
83
- // The model actually used to calculate the price
84
- pricingModel,
85
-
86
- // Was the default price used?
87
- fallbackPricing: requestedModel !== pricingModel,
88
-
89
- priceUnitTokens: PRICE_UNIT_TOKENS,
90
- longContext: Boolean(longContext)
91
- };
92
- }
93
-
94
- /**
95
- * Calculates a request charge from Responses API usage and returns it in
96
- * integer microdollars. Cached input and cache-write tokens are included in
97
- * input_tokens, so both are removed from standard input before applying their
98
- * respective prices.
99
- */
100
- export function calculateUsageCostMicrousd(model, usage = {}) {
101
- const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
102
- const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
103
- const cachedInputTokens = Math.min(
104
- inputTokens,
105
- Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
106
- );
107
- const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
108
- const pricing = getModelPricing(model, inputTokens);
109
-
110
- const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
111
- const usd = (
112
- (uncachedInputTokens * pricing.input)
113
- + (cachedInputTokens * pricing.cachedInput)
114
- + (cacheWriteTokens * pricing.cacheWrite)
115
- + (outputTokens * pricing.output)
116
- ) / PRICE_UNIT_TOKENS;
117
-
118
- return Math.round(usd * 1_000_000);
119
- }
120
-
121
- export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
122
-
123
- export default {
124
- getModelPricing,
125
- calculateUsageCostMicrousd,
126
- DEFAULT_PRICING_MODEL
127
- };
1
+ /**
2
+ * Upstream Codex model pricing in USD per one million tokens.
3
+ * Long-context pricing applies when input tokens exceed 272,000.
4
+ */
5
+
6
+ export const PRICE_UNIT_TOKENS = 1_000_000;
7
+ export const LONG_CONTEXT_THRESHOLD_TOKENS = 272_000;
8
+ // For models without a configured price, billing is uniformly based on this model.
9
+ export const DEFAULT_PRICING_MODEL = 'gpt-5.6-sol';
10
+
11
+ const STANDARD_PRICING = {
12
+ 'gpt-5.6-sol': {
13
+ input: 5,
14
+ cachedInput: 0.5,
15
+ cacheWrite: 6.25,
16
+ output: 30
17
+ },
18
+ 'gpt-5.6-terra': {
19
+ input: 2.5,
20
+ cachedInput: 0.25,
21
+ cacheWrite: 3.125,
22
+ output: 15
23
+ },
24
+ 'gpt-5.4-mini': {
25
+ input: 0.75,
26
+ cachedInput: 0.075,
27
+ cacheWrite: 0,
28
+ output: 4.5
29
+ }
30
+ };
31
+
32
+ const LONG_CONTEXT_PRICING = {
33
+ 'gpt-5.6-sol': {
34
+ input: 10,
35
+ cachedInput: 1,
36
+ cacheWrite: 12.5,
37
+ output: 45
38
+ },
39
+ 'gpt-5.6-terra': {
40
+ input: 5,
41
+ cachedInput: 0.5,
42
+ cacheWrite: 6.25,
43
+ output: 22.5
44
+ }
45
+ };
46
+
47
+ /**
48
+ * Returns the applicable USD-per-million-token price record for an upstream
49
+ * model. Models without a configured price use DEFAULT_PRICING_MODEL.
50
+ */
51
+ export function getModelPricing(model, inputTokens = 0) {
52
+ const requestedModel = String(model || '').trim().toLowerCase();
53
+
54
+ // Use the current model if it has a price;
55
+ // use the default pricing model if no price is configured.
56
+ const pricingModel = STANDARD_PRICING[requestedModel]
57
+ ? requestedModel
58
+ : DEFAULT_PRICING_MODEL;
59
+
60
+ const standard = STANDARD_PRICING[pricingModel];
61
+
62
+ // Prevent DEFAULT_PRICING_MODEL configuration errors.
63
+ if (!standard) {
64
+ throw new Error(
65
+ `Default pricing model "${DEFAULT_PRICING_MODEL}" is not configured`
66
+ );
67
+ }
68
+
69
+ const usesLongContext =
70
+ Number(inputTokens) > LONG_CONTEXT_THRESHOLD_TOKENS;
71
+
72
+ const longContext = usesLongContext
73
+ ? LONG_CONTEXT_PRICING[pricingModel]
74
+ : null;
75
+
76
+ return {
77
+ ...standard,
78
+ ...(longContext || {}),
79
+
80
+ // The model actually requested
81
+ model: requestedModel,
82
+
83
+ // The model actually used to calculate the price
84
+ pricingModel,
85
+
86
+ // Was the default price used?
87
+ fallbackPricing: requestedModel !== pricingModel,
88
+
89
+ priceUnitTokens: PRICE_UNIT_TOKENS,
90
+ longContext: Boolean(longContext)
91
+ };
92
+ }
93
+
94
+ /**
95
+ * Calculates a request charge from Responses API usage and returns it in
96
+ * integer microdollars. Cached input and cache-write tokens are included in
97
+ * input_tokens, so both are removed from standard input before applying their
98
+ * respective prices.
99
+ */
100
+ export function calculateUsageCostMicrousd(model, usage = {}) {
101
+ const inputTokens = Math.max(0, Number(usage.input_tokens) || 0);
102
+ const outputTokens = Math.max(0, Number(usage.output_tokens) || 0);
103
+ const cachedInputTokens = Math.min(
104
+ inputTokens,
105
+ Math.max(0, Number(usage.cache_read_input_tokens ?? usage.input_tokens_details?.cached_tokens) || 0)
106
+ );
107
+ const cacheWriteTokens = Math.max(0, Number(usage.input_tokens_details?.cache_write_tokens) || 0);
108
+ const pricing = getModelPricing(model, inputTokens);
109
+
110
+ const uncachedInputTokens = Math.max(0, inputTokens - cachedInputTokens - cacheWriteTokens);
111
+ const usd = (
112
+ (uncachedInputTokens * pricing.input)
113
+ + (cachedInputTokens * pricing.cachedInput)
114
+ + (cacheWriteTokens * pricing.cacheWrite)
115
+ + (outputTokens * pricing.output)
116
+ ) / PRICE_UNIT_TOKENS;
117
+
118
+ return Math.round(usd * 1_000_000);
119
+ }
120
+
121
+ export { STANDARD_PRICING, LONG_CONTEXT_PRICING };
122
+
123
+ export default {
124
+ getModelPricing,
125
+ calculateUsageCostMicrousd,
126
+ DEFAULT_PRICING_MODEL
127
+ };
@@ -1,5 +1,5 @@
1
- import { getServerSettings } from '../server-settings.js';
2
-
3
- export function shouldLogRawProxyPayloads() {
4
- return getServerSettings().logRawProxyPayloads === true;
5
- }
1
+ import { getServerSettings } from '../server-settings.js';
2
+
3
+ export function shouldLogRawProxyPayloads() {
4
+ return getServerSettings().logRawProxyPayloads === true;
5
+ }