claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.30
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/README.md +0 -272
- package/bin/cli.js +37 -2
- package/package.json +1 -1
- package/public/css/style.css +132 -0
- package/public/index.html +60 -60
- package/public/js/app.js +194 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +61 -2
- package/public/views/accounts.html +29 -10
- package/public/views/client-api-keys-modals.html +15 -1
- package/public/views/client-api-keys.html +68 -31
- package/public/views/logs.html +10 -3
- package/src/account-manager.js +34 -3
- package/src/account-rotation/rate-limits.js +4 -0
- package/src/account-rotation/strategies/base-strategy.js +4 -0
- package/src/account-rotation/strategies/sticky-strategy.js +7 -0
- package/src/admin-path.js +33 -0
- package/src/client-key-usage.js +193 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +11 -11
- package/src/format-converter.js +83 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +54 -16
- package/src/middleware/credentials.js +17 -7
- package/src/middleware/sse.js +69 -29
- package/src/model-api.js +60 -0
- package/src/model-pricing.js +127 -0
- package/src/response-streamer.js +23 -7
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +59 -42
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +19 -10
- package/src/routes/client-quota-route.js +31 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +100 -51
- package/src/routes/settings-route.js +66 -5
- package/src/server-settings.js +25 -2
- package/src/utils/logger.js +30 -0
- package/src/utils/proxy-logging.js +5 -0
package/src/middleware/sse.js
CHANGED
|
@@ -7,6 +7,24 @@ import { resolveModelRouting } from '../model-mapper.js';
|
|
|
7
7
|
import { formatSSEEvent } from '../response-streamer.js';
|
|
8
8
|
import { logger } from '../utils/logger.js';
|
|
9
9
|
|
|
10
|
+
function createEmptyUsage() {
|
|
11
|
+
return {
|
|
12
|
+
input_tokens: 0,
|
|
13
|
+
output_tokens: 0,
|
|
14
|
+
cache_creation_input_tokens: 0,
|
|
15
|
+
cache_read_input_tokens: 0
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createErrorResponse(errorType, message, extraErrorFields = {}) {
|
|
20
|
+
return {
|
|
21
|
+
type: 'error',
|
|
22
|
+
error: { type: errorType, message, ...extraErrorFields },
|
|
23
|
+
// Claude Code may still read usage on exceptional responses (for example Agent startup failures).
|
|
24
|
+
usage: createEmptyUsage()
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
10
28
|
/**
|
|
11
29
|
* Sets the standard SSE response headers and flushes them.
|
|
12
30
|
* @param {import('express').Response} res
|
|
@@ -56,24 +74,48 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
56
74
|
const loggedModel = typeof model === 'string' && model.toLowerCase().startsWith('claude-')
|
|
57
75
|
? resolveModelRouting(model).upstreamModel
|
|
58
76
|
: model;
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
77
|
+
const isStreamError = res.headersSent;
|
|
78
|
+
const logDetails = {
|
|
79
|
+
model: loggedModel,
|
|
80
|
+
transport: isStreamError ? 'sse' : 'http',
|
|
81
|
+
clientHttpStatus: isStreamError ? res.statusCode : status,
|
|
82
|
+
errorType,
|
|
83
|
+
retrySignal: errorType === 'overloaded_error',
|
|
84
|
+
errorName: error?.name,
|
|
85
|
+
errorCode: error?.code,
|
|
86
|
+
upstreamStatus: error?.upstreamStatus,
|
|
87
|
+
isUpstreamError: error?.isUpstreamError === true,
|
|
88
|
+
error: error?.message,
|
|
89
|
+
duration
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
if (isStreamError) {
|
|
93
|
+
const socketDestroyed = res.destroyed === true || res.socket?.destroyed === true;
|
|
94
|
+
const writableEnded = res.writableEnded === true;
|
|
95
|
+
const sseWriteAttempted = !socketDestroyed && !writableEnded;
|
|
96
|
+
let sseWriteBackpressure = false;
|
|
97
|
+
if (sseWriteAttempted) {
|
|
98
|
+
sseWriteBackpressure = !res.write(
|
|
99
|
+
`event: error\ndata: ${JSON.stringify(createErrorResponse(errorType, getClientErrorMessage(error)))}\n\n`
|
|
100
|
+
);
|
|
101
|
+
res.end();
|
|
102
|
+
}
|
|
103
|
+
logger.response(status, {
|
|
104
|
+
...logDetails,
|
|
105
|
+
sseWriteAttempted,
|
|
106
|
+
sseWriteBackpressure,
|
|
107
|
+
socketDestroyed,
|
|
108
|
+
writableEnded
|
|
109
|
+
});
|
|
69
110
|
return;
|
|
70
111
|
}
|
|
71
112
|
|
|
113
|
+
logger.response(status, logDetails);
|
|
114
|
+
|
|
72
115
|
if (error.message.includes('AUTH_EXPIRED')) {
|
|
73
|
-
return res.status(401).json(
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
});
|
|
116
|
+
return res.status(401).json(
|
|
117
|
+
createErrorResponse('authentication_error', 'Token expired. Please refresh or re-authenticate.')
|
|
118
|
+
);
|
|
77
119
|
}
|
|
78
120
|
|
|
79
121
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -81,28 +123,23 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
81
123
|
const resetMs = parseInt(parts[1], 10);
|
|
82
124
|
const errorText = parts.slice(2).join(':') || error.message;
|
|
83
125
|
|
|
84
|
-
return res.status(429).json(
|
|
85
|
-
|
|
86
|
-
error: {
|
|
87
|
-
type: 'rate_limit_error',
|
|
88
|
-
message: errorText,
|
|
126
|
+
return res.status(429).json(
|
|
127
|
+
createErrorResponse('rate_limit_error', errorText, {
|
|
89
128
|
resetMs: resetMs,
|
|
90
129
|
resetSeconds: Math.round(resetMs / 1000)
|
|
91
|
-
}
|
|
92
|
-
|
|
130
|
+
})
|
|
131
|
+
);
|
|
93
132
|
}
|
|
94
133
|
|
|
95
134
|
if (error.message.includes('RESOURCE_EXHAUSTED')) {
|
|
96
|
-
return res.status(429).json(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
});
|
|
135
|
+
return res.status(429).json(
|
|
136
|
+
createErrorResponse('rate_limit_error', error.message)
|
|
137
|
+
);
|
|
100
138
|
}
|
|
101
139
|
|
|
102
|
-
res.status(status).json(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
});
|
|
140
|
+
res.status(status).json(
|
|
141
|
+
createErrorResponse(errorType, getClientErrorMessage(error))
|
|
142
|
+
);
|
|
106
143
|
}
|
|
107
144
|
|
|
108
145
|
function getErrorStatus(error) {
|
|
@@ -115,6 +152,9 @@ function getErrorStatus(error) {
|
|
|
115
152
|
}
|
|
116
153
|
|
|
117
154
|
function getAnthropicErrorType(error, status) {
|
|
155
|
+
// Claude Code retries streamed overload errors by their Anthropic error type.
|
|
156
|
+
// HTTP status is already committed after SSE starts, so preserve 5xx semantics here.
|
|
157
|
+
if (status >= 500) return 'overloaded_error';
|
|
118
158
|
if (error?.anthropicErrorType) return error.anthropicErrorType;
|
|
119
159
|
if (status === 401) return 'authentication_error';
|
|
120
160
|
if (status === 429) return 'rate_limit_error';
|
package/src/model-api.js
CHANGED
|
@@ -100,6 +100,64 @@ export async function fetchUsage(accessToken, accountId) {
|
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
+
/**
|
|
104
|
+
* Lists the account's available rate-limit reset credits.
|
|
105
|
+
* @param {string} accessToken
|
|
106
|
+
* @param {string} accountId
|
|
107
|
+
* @returns {Promise<object>}
|
|
108
|
+
*/
|
|
109
|
+
export async function fetchRateLimitResetCredits(accessToken, accountId) {
|
|
110
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits`, {
|
|
111
|
+
method: 'GET',
|
|
112
|
+
headers: {
|
|
113
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
114
|
+
'ChatGPT-Account-ID': accountId,
|
|
115
|
+
'Accept': 'application/json',
|
|
116
|
+
'User-Agent': 'codex-cli'
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
const errorText = await response.text();
|
|
122
|
+
throw new Error(`Failed to fetch rate-limit reset credits: ${response.status} - ${errorText}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return await response.json();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Redeems a rate-limit reset credit for an account.
|
|
130
|
+
* @param {string} accessToken
|
|
131
|
+
* @param {string} accountId
|
|
132
|
+
* @param {string} redeemRequestId Stable idempotency key for retries of this redemption.
|
|
133
|
+
* @param {string|null} creditId Specific credit to redeem, or null for server selection.
|
|
134
|
+
* @returns {Promise<object>}
|
|
135
|
+
*/
|
|
136
|
+
export async function consumeRateLimitResetCredit(accessToken, accountId, redeemRequestId, creditId = null) {
|
|
137
|
+
const body = { redeem_request_id: redeemRequestId };
|
|
138
|
+
if (creditId) body.credit_id = creditId;
|
|
139
|
+
|
|
140
|
+
const response = await fetch(`${CHATGPT_API_BASE}/wham/rate-limit-reset-credits/consume`, {
|
|
141
|
+
method: 'POST',
|
|
142
|
+
headers: {
|
|
143
|
+
'Authorization': `Bearer ${accessToken}`,
|
|
144
|
+
'ChatGPT-Account-ID': accountId,
|
|
145
|
+
'Content-Type': 'application/json',
|
|
146
|
+
'Accept': 'application/json',
|
|
147
|
+
'User-Agent': 'codex-cli'
|
|
148
|
+
},
|
|
149
|
+
body: JSON.stringify(body)
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (!response.ok) {
|
|
153
|
+
const errorText = await response.text();
|
|
154
|
+
throw new Error(`Failed to redeem rate-limit reset credit: ${response.status} - ${errorText}`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const text = await response.text();
|
|
158
|
+
return text ? JSON.parse(text) : {};
|
|
159
|
+
}
|
|
160
|
+
|
|
103
161
|
export async function fetchAccountCheck(accessToken, accountId) {
|
|
104
162
|
const url = `${CHATGPT_API_BASE}/wham/accounts/check`;
|
|
105
163
|
|
|
@@ -182,6 +240,8 @@ export function clearModelCache() {
|
|
|
182
240
|
export default {
|
|
183
241
|
fetchModels,
|
|
184
242
|
fetchUsage,
|
|
243
|
+
fetchRateLimitResetCredits,
|
|
244
|
+
consumeRateLimitResetCredit,
|
|
185
245
|
fetchAccountCheck,
|
|
186
246
|
getAccountQuota,
|
|
187
247
|
getModelsAndQuota,
|
|
@@ -0,0 +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,
|
|
20
|
+
cachedInput: 0.2,
|
|
21
|
+
cacheWrite: 2.5,
|
|
22
|
+
output: 12
|
|
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: 4,
|
|
41
|
+
cachedInput: 0.4,
|
|
42
|
+
cacheWrite: 5,
|
|
43
|
+
output: 18
|
|
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
|
+
};
|
package/src/response-streamer.js
CHANGED
|
@@ -5,15 +5,11 @@
|
|
|
5
5
|
|
|
6
6
|
import { generateMessageId, sanitizeAnthropicToolInputJson, toAnthropicToolId } from './format-converter.js';
|
|
7
7
|
import { cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
8
|
-
import { getServerSettings } from './server-settings.js';
|
|
9
8
|
import { logger } from './utils/logger.js';
|
|
9
|
+
import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
|
|
10
10
|
|
|
11
11
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
12
12
|
|
|
13
|
-
function shouldLogRawProxyPayloads() {
|
|
14
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
13
|
export function createResponsesAPIError(message, status = 502) {
|
|
18
14
|
const error = new Error(message);
|
|
19
15
|
error.status = status;
|
|
@@ -76,6 +72,7 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
76
72
|
let stopReason = 'end_turn';
|
|
77
73
|
let pendingArguments = '';
|
|
78
74
|
let usage = { input_tokens: 0, output_tokens: 0 };
|
|
75
|
+
let hasCompletedResponse = false;
|
|
79
76
|
|
|
80
77
|
const reader = response.body.getReader();
|
|
81
78
|
const decoder = new TextDecoder();
|
|
@@ -102,6 +99,7 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
102
99
|
|
|
103
100
|
// Extract usage from completed response
|
|
104
101
|
if (eventType === 'response.completed' && event.response?.usage) {
|
|
102
|
+
hasCompletedResponse = true;
|
|
105
103
|
if (shouldLogRawProxyPayloads()) {
|
|
106
104
|
logger.info('[OpenAI Response Completed]', event.response);
|
|
107
105
|
}
|
|
@@ -117,12 +115,22 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
117
115
|
value: event.response.usage.cache_read_input_tokens || event.response.usage.input_tokens_details?.cached_tokens || 0,
|
|
118
116
|
enumerable: false
|
|
119
117
|
});
|
|
118
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
119
|
+
value: event.response.usage.input_tokens_details?.cache_write_tokens || 0,
|
|
120
|
+
enumerable: false
|
|
121
|
+
});
|
|
120
122
|
}
|
|
121
123
|
|
|
122
124
|
// Handle output item added
|
|
123
125
|
if (eventType === 'response.output_item.added') {
|
|
124
126
|
const item = event.item;
|
|
125
|
-
|
|
127
|
+
|
|
128
|
+
// Codex executes hosted web searches upstream. Claude Code only
|
|
129
|
+
// needs the final output_text, not a client-side tool_use block.
|
|
130
|
+
if (item?.type === 'web_search_call') {
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
|
|
126
134
|
if (!hasEmittedStart) {
|
|
127
135
|
hasEmittedStart = true;
|
|
128
136
|
yield {
|
|
@@ -162,9 +170,13 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
162
170
|
data: { type: 'content_block_stop', index: blockIndex }
|
|
163
171
|
};
|
|
164
172
|
blockIndex++;
|
|
173
|
+
currentBlockType = null;
|
|
174
|
+
currentBlockId = null;
|
|
175
|
+
currentToolName = null;
|
|
165
176
|
}
|
|
166
177
|
|
|
167
|
-
// Start new block based on item type
|
|
178
|
+
// Start new block based on item type. Hosted web_search_call
|
|
179
|
+
// items are executed upstream and do not become Claude tool_use blocks.
|
|
168
180
|
if (item.type === 'message') {
|
|
169
181
|
currentBlockType = 'text';
|
|
170
182
|
currentBlockId = item.id;
|
|
@@ -331,6 +343,10 @@ export async function* streamResponsesAPI(response, model) {
|
|
|
331
343
|
}
|
|
332
344
|
}
|
|
333
345
|
|
|
346
|
+
if (!hasCompletedResponse) {
|
|
347
|
+
throw createResponsesAPIError('Upstream stream ended before response.completed');
|
|
348
|
+
}
|
|
349
|
+
|
|
334
350
|
// Handle no content received
|
|
335
351
|
if (!hasEmittedStart) {
|
|
336
352
|
hasEmittedStart = true;
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* GET /accounts/status
|
|
6
6
|
* GET /accounts/quota
|
|
7
7
|
* GET /accounts/quota/all
|
|
8
|
+
* GET /accounts/rate-limit-reset-credits
|
|
9
|
+
* POST /accounts/rate-limit-reset-credits/consume
|
|
8
10
|
* POST /accounts/add
|
|
9
11
|
* POST /accounts/add/manual
|
|
10
12
|
* POST /accounts/switch
|
|
@@ -12,6 +14,7 @@
|
|
|
12
14
|
* POST /accounts/refresh
|
|
13
15
|
* POST /accounts/refresh/all
|
|
14
16
|
* POST /accounts/:email/refresh
|
|
17
|
+
* PUT /accounts/:email/expiration
|
|
15
18
|
* POST /accounts/oauth/cleanup
|
|
16
19
|
* DELETE /accounts/:email
|
|
17
20
|
*/
|
|
@@ -30,7 +33,8 @@ import {
|
|
|
30
33
|
saveAccounts,
|
|
31
34
|
updateAccountAuth,
|
|
32
35
|
updateAccountQuota,
|
|
33
|
-
getAccountQuota
|
|
36
|
+
getAccountQuota,
|
|
37
|
+
updateAccountExpiration
|
|
34
38
|
} from '../account-manager.js';
|
|
35
39
|
|
|
36
40
|
import {
|
|
@@ -45,9 +49,13 @@ import {
|
|
|
45
49
|
} from '../oauth.js';
|
|
46
50
|
|
|
47
51
|
import {
|
|
48
|
-
getAccountQuota as fetchAccountQuota
|
|
52
|
+
getAccountQuota as fetchAccountQuota,
|
|
53
|
+
fetchRateLimitResetCredits,
|
|
54
|
+
consumeRateLimitResetCredit
|
|
49
55
|
} from '../model-api.js';
|
|
50
56
|
|
|
57
|
+
import { randomUUID } from 'crypto';
|
|
58
|
+
|
|
51
59
|
import { logger } from '../utils/logger.js';
|
|
52
60
|
|
|
53
61
|
// Tracks active OAuth callback servers keyed by port
|
|
@@ -172,6 +180,30 @@ export async function handleRefreshAllAccounts(req, res) {
|
|
|
172
180
|
res.json(result);
|
|
173
181
|
}
|
|
174
182
|
|
|
183
|
+
export function handleUpdateAccountExpiration(req, res) {
|
|
184
|
+
const email = decodeURIComponent(req.params.email);
|
|
185
|
+
const { accountExpiresAt } = req.body || {};
|
|
186
|
+
|
|
187
|
+
if (accountExpiresAt !== null && accountExpiresAt !== undefined) {
|
|
188
|
+
if (typeof accountExpiresAt !== 'string' || !accountExpiresAt.trim()) {
|
|
189
|
+
return res.status(400).json({ success: false, message: 'accountExpiresAt must be an ISO 8601 date or null' });
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const normalizedAccountExpiresAt = accountExpiresAt.trim();
|
|
193
|
+
const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
194
|
+
const expiresAt = new Date(normalizedAccountExpiresAt);
|
|
195
|
+
if (!isoDatePattern.test(normalizedAccountExpiresAt) || Number.isNaN(expiresAt.getTime())) {
|
|
196
|
+
return res.status(400).json({ success: false, message: 'accountExpiresAt must be a valid ISO 8601 date' });
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const result = updateAccountExpiration(email, expiresAt.toISOString());
|
|
200
|
+
return res.status(result.success ? 200 : 404).json(result);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const result = updateAccountExpiration(email, null);
|
|
204
|
+
return res.status(result.success ? 200 : 404).json(result);
|
|
205
|
+
}
|
|
206
|
+
|
|
175
207
|
export async function handleRefreshActiveAccount(req, res) {
|
|
176
208
|
const result = await refreshActiveAccount();
|
|
177
209
|
res.json(result);
|
|
@@ -232,6 +264,75 @@ export async function handleGetQuota(req, res) {
|
|
|
232
264
|
}
|
|
233
265
|
}
|
|
234
266
|
|
|
267
|
+
/**
|
|
268
|
+
* Lists an account's rate-limit reset credits.
|
|
269
|
+
*/
|
|
270
|
+
export async function handleGetRateLimitResetCredits(req, res) {
|
|
271
|
+
const { email } = req.query;
|
|
272
|
+
const account = email
|
|
273
|
+
? loadAccounts().accounts.find(a => a.email === email)
|
|
274
|
+
: getActiveAccount();
|
|
275
|
+
|
|
276
|
+
if (!account) {
|
|
277
|
+
return res.status(404).json({
|
|
278
|
+
success: false,
|
|
279
|
+
error: email ? `Account not found: ${email}` : 'No active account'
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
const credits = await fetchRateLimitResetCredits(account.accessToken, account.accountId);
|
|
285
|
+
res.json({ success: true, email: account.email, credits });
|
|
286
|
+
} catch (error) {
|
|
287
|
+
logger.error(`Failed to fetch rate-limit reset credits for ${account.email}: ${error.message}`);
|
|
288
|
+
res.status(502).json({ success: false, error: error.message });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Redeems one available rate-limit reset credit for an account.
|
|
294
|
+
*/
|
|
295
|
+
export async function handleConsumeRateLimitResetCredit(req, res) {
|
|
296
|
+
const { email, creditId, redeemRequestId } = req.body || {};
|
|
297
|
+
const account = email
|
|
298
|
+
? loadAccounts().accounts.find(a => a.email === email)
|
|
299
|
+
: getActiveAccount();
|
|
300
|
+
|
|
301
|
+
if (!account) {
|
|
302
|
+
return res.status(404).json({
|
|
303
|
+
success: false,
|
|
304
|
+
error: email ? `Account not found: ${email}` : 'No active account'
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
if (redeemRequestId !== undefined && (
|
|
309
|
+
typeof redeemRequestId !== 'string' ||
|
|
310
|
+
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(redeemRequestId.trim())
|
|
311
|
+
)) {
|
|
312
|
+
return res.status(400).json({ success: false, error: 'redeemRequestId must be a UUID string' });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (creditId !== undefined && (typeof creditId !== 'string' || !creditId.trim())) {
|
|
316
|
+
return res.status(400).json({ success: false, error: 'creditId must be a non-empty string when provided' });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const idempotencyKey = redeemRequestId?.trim() || randomUUID();
|
|
320
|
+
|
|
321
|
+
try {
|
|
322
|
+
const result = await consumeRateLimitResetCredit(
|
|
323
|
+
account.accessToken,
|
|
324
|
+
account.accountId,
|
|
325
|
+
idempotencyKey,
|
|
326
|
+
creditId?.trim() || null
|
|
327
|
+
);
|
|
328
|
+
logger.info(`Redeemed rate-limit reset credit for: ${account.email}`);
|
|
329
|
+
res.json({ success: true, email: account.email, redeemRequestId: idempotencyKey, result });
|
|
330
|
+
} catch (error) {
|
|
331
|
+
logger.error(`Failed to redeem rate-limit reset credit for ${account.email}: ${error.message}`);
|
|
332
|
+
res.status(502).json({ success: false, error: error.message, redeemRequestId: idempotencyKey });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
235
336
|
export async function handleGetAllQuotas(req, res) {
|
|
236
337
|
const { accounts: accountList } = listAccounts();
|
|
237
338
|
const results = [];
|
|
@@ -304,9 +405,12 @@ export default {
|
|
|
304
405
|
handleSwitchAccount,
|
|
305
406
|
handleRefreshAccount,
|
|
306
407
|
handleRefreshAllAccounts,
|
|
408
|
+
handleUpdateAccountExpiration,
|
|
307
409
|
handleRefreshActiveAccount,
|
|
308
410
|
handleRemoveAccount,
|
|
309
411
|
handleImportAccount,
|
|
310
412
|
handleGetQuota,
|
|
413
|
+
handleGetRateLimitResetCredits,
|
|
414
|
+
handleConsumeRateLimitResetCredit,
|
|
311
415
|
handleGetAllQuotas
|
|
312
416
|
};
|