claude-codex-proxy 1.0.5-beta.31 → 1.0.5-beta.33
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 +1 -1
- package/src/daily-anchor-ping.js +149 -0
- package/src/middleware/sse.js +3 -1
- package/src/routes/chat-route.js +4 -3
- package/src/routes/messages-route.js +17 -9
- package/src/server.js +4 -0
- package/src/utils/logger.js +2 -0
package/package.json
CHANGED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Daily Anchor Ping
|
|
3
|
+
* Every day at a fixed local hour (default 09:00) this module sends a minimal
|
|
4
|
+
* "你好" message to every configured account so the upstream Codex five-hour
|
|
5
|
+
* usage window is re-anchored to that moment. Because the upstream window
|
|
6
|
+
* advances from the first usage of the window, an anchor ping at 09:00 local
|
|
7
|
+
* time makes the upstream reset time settle at 14:00 local time (09:00 + 5h).
|
|
8
|
+
*
|
|
9
|
+
* The scheduler uses a self-rescheduling setTimeout that targets the exact
|
|
10
|
+
* next anchor instant, so the ping lands at 09:00:00.000 even across long
|
|
11
|
+
* uptimes; on the first run after a restart it only fires if 09:00 has not
|
|
12
|
+
* passed yet today, so it never disturbs an already-active window.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { loadAccounts } from './account-manager.js';
|
|
16
|
+
import { getCredentialsForAccount } from './middleware/credentials.js';
|
|
17
|
+
import { sendMessage } from './direct-api.js';
|
|
18
|
+
import { resolveModelRouting } from './model-mapper.js';
|
|
19
|
+
import { logger } from './utils/logger.js';
|
|
20
|
+
|
|
21
|
+
/** Local hour at which the anchor ping runs every day. */
|
|
22
|
+
export const ANCHOR_HOUR = 9;
|
|
23
|
+
|
|
24
|
+
/** Payload text sent upstream to advance the five-hour window start. */
|
|
25
|
+
export const PING_TEXT = '你好';
|
|
26
|
+
|
|
27
|
+
/** Maximum completion tokens for the anchor ping; only a single reply is needed. */
|
|
28
|
+
const PING_MAX_TOKENS = 16;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Hard cap for one anchor ping round. `sendMessage` has no built-in request
|
|
32
|
+
* timeout, so a hung upstream response could otherwise stall `pingAllAccounts`
|
|
33
|
+
* forever and break the self-rescheduling chain.
|
|
34
|
+
*/
|
|
35
|
+
const PING_TIMEOUT_MS = 5 * 60 * 1000;
|
|
36
|
+
|
|
37
|
+
/** Sample Claude model used to resolve the active upstream Codex model. */
|
|
38
|
+
const SAMPLE_MODEL = 'claude-sonnet-4-5';
|
|
39
|
+
|
|
40
|
+
let anchorTimer = null;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Computes the next Date at the given local hour (minutes/seconds zeroed)
|
|
44
|
+
* that is strictly after `now`.
|
|
45
|
+
*
|
|
46
|
+
* @param {Date} now - current time
|
|
47
|
+
* @param {number} [anchorHour] - local hour of the anchor
|
|
48
|
+
* @returns {Date} the next anchor instant
|
|
49
|
+
*/
|
|
50
|
+
export function getNextAnchorTime(now, anchorHour = ANCHOR_HOUR) {
|
|
51
|
+
const next = new Date(now);
|
|
52
|
+
next.setHours(anchorHour, 0, 0, 0);
|
|
53
|
+
if (next.getTime() <= now.getTime()) {
|
|
54
|
+
next.setDate(next.getDate() + 1);
|
|
55
|
+
}
|
|
56
|
+
return next;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Builds the minimal Anthropic-style request used for the anchor ping.
|
|
61
|
+
*/
|
|
62
|
+
function buildAnchorRequest() {
|
|
63
|
+
const { upstreamModel } = resolveModelRouting(SAMPLE_MODEL);
|
|
64
|
+
return {
|
|
65
|
+
model: upstreamModel,
|
|
66
|
+
max_tokens: PING_MAX_TOKENS,
|
|
67
|
+
messages: [{ role: 'user', content: PING_TEXT }]
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Sends the anchor message to every configured account. Each account is
|
|
73
|
+
* handled independently so a single failure never aborts the rest.
|
|
74
|
+
*/
|
|
75
|
+
async function pingAllAccounts() {
|
|
76
|
+
const data = loadAccounts();
|
|
77
|
+
const accounts = data.accounts || [];
|
|
78
|
+
if (accounts.length === 0) {
|
|
79
|
+
logger.info('[AnchorPing] No accounts configured; skipping daily ping');
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const request = buildAnchorRequest();
|
|
84
|
+
logger.info(`[AnchorPing] Sending "${PING_TEXT}" to ${accounts.length} account(s) to anchor the five-hour window`);
|
|
85
|
+
|
|
86
|
+
for (const account of accounts) {
|
|
87
|
+
try {
|
|
88
|
+
const creds = await getCredentialsForAccount(account.email);
|
|
89
|
+
if (!creds) {
|
|
90
|
+
logger.warn(`[AnchorPing] Skip ${account.email}: no valid credentials`);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
await sendMessage(request, creds.accessToken, creds.accountId, {}, null, creds.email);
|
|
94
|
+
logger.info(`[AnchorPing] Sent "${PING_TEXT}" via ${account.email}`);
|
|
95
|
+
} catch (error) {
|
|
96
|
+
logger.warn(`[AnchorPing] Failed for ${account.email}: ${error.message}`);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Starts the daily anchor ping scheduler. Safe to call multiple times.
|
|
103
|
+
*/
|
|
104
|
+
export function startDailyAnchorPing() {
|
|
105
|
+
if (anchorTimer) return;
|
|
106
|
+
|
|
107
|
+
const scheduleNext = () => {
|
|
108
|
+
const next = getNextAnchorTime(new Date());
|
|
109
|
+
const delay = next.getTime() - Date.now();
|
|
110
|
+
logger.info(`[AnchorPing] Next ping scheduled at ${next.toLocaleString()}`);
|
|
111
|
+
anchorTimer = setTimeout(async () => {
|
|
112
|
+
// Race the whole ping round against a hard cap: even if one `sendMessage`
|
|
113
|
+
// hangs upstream, `scheduleNext()` in the `finally` block still runs and
|
|
114
|
+
// tomorrow's ping is never lost. A stray hung request may linger in the
|
|
115
|
+
// background, but it can no longer break the daily chain.
|
|
116
|
+
const guard = new Promise(resolve => setTimeout(resolve, PING_TIMEOUT_MS));
|
|
117
|
+
try {
|
|
118
|
+
await Promise.race([pingAllAccounts(), guard]);
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// Guard against any unforeseen error so the loop always reschedules.
|
|
121
|
+
logger.warn(`[AnchorPing] Unexpected ping error: ${error.message}`);
|
|
122
|
+
} finally {
|
|
123
|
+
scheduleNext();
|
|
124
|
+
}
|
|
125
|
+
}, delay);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
scheduleNext();
|
|
129
|
+
logger.info(`[AnchorPing] Daily anchor ping enabled at local hour ${ANCHOR_HOUR}:00`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Stops the daily anchor ping scheduler and clears any pending timer.
|
|
134
|
+
*/
|
|
135
|
+
export function stopDailyAnchorPing() {
|
|
136
|
+
if (anchorTimer) {
|
|
137
|
+
clearTimeout(anchorTimer);
|
|
138
|
+
anchorTimer = null;
|
|
139
|
+
}
|
|
140
|
+
logger.info('[AnchorPing] Daily anchor ping stopped');
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export default {
|
|
144
|
+
startDailyAnchorPing,
|
|
145
|
+
stopDailyAnchorPing,
|
|
146
|
+
getNextAnchorTime,
|
|
147
|
+
ANCHOR_HOUR,
|
|
148
|
+
PING_TEXT
|
|
149
|
+
};
|
package/src/middleware/sse.js
CHANGED
|
@@ -66,8 +66,9 @@ export async function pipeSSEStream(res, eventStream) {
|
|
|
66
66
|
* @param {Error} error
|
|
67
67
|
* @param {string} model
|
|
68
68
|
* @param {number} startTime
|
|
69
|
+
* @param {string} [requestedModel] Client-provided model name before routing.
|
|
69
70
|
*/
|
|
70
|
-
export function handleStreamError(res, error, model, startTime) {
|
|
71
|
+
export function handleStreamError(res, error, model, startTime, requestedModel) {
|
|
71
72
|
const duration = Date.now() - startTime;
|
|
72
73
|
const status = getErrorStatus(error);
|
|
73
74
|
const errorType = getAnthropicErrorType(error, status);
|
|
@@ -77,6 +78,7 @@ export function handleStreamError(res, error, model, startTime) {
|
|
|
77
78
|
const isStreamError = res.headersSent;
|
|
78
79
|
const logDetails = {
|
|
79
80
|
model: loggedModel,
|
|
81
|
+
requestedModel,
|
|
80
82
|
transport: isStreamError ? 'sse' : 'http',
|
|
81
83
|
clientHttpStatus: isStreamError ? res.statusCode : status,
|
|
82
84
|
errorType,
|
package/src/routes/chat-route.js
CHANGED
|
@@ -39,7 +39,7 @@ export async function handleChatCompletion(req, res) {
|
|
|
39
39
|
|
|
40
40
|
const creds = await getCredentialsOrError();
|
|
41
41
|
if (!creds) {
|
|
42
|
-
logger.response(401, { error: 'No active account' });
|
|
42
|
+
logger.response(401, { model: upstreamModel, requestedModel, error: 'No active account' });
|
|
43
43
|
return sendAuthError(res, 'No active account. Add an account via /accounts/add');
|
|
44
44
|
}
|
|
45
45
|
|
|
@@ -47,6 +47,7 @@ export async function handleChatCompletion(req, res) {
|
|
|
47
47
|
|
|
48
48
|
logger.request('POST', '/v1/chat/completions', {
|
|
49
49
|
model: upstreamModel,
|
|
50
|
+
requestedModel,
|
|
50
51
|
account: creds.email,
|
|
51
52
|
messages: body.messages?.length || 0,
|
|
52
53
|
tools: body.tools?.length || 0
|
|
@@ -57,11 +58,11 @@ export async function handleChatCompletion(req, res) {
|
|
|
57
58
|
recordRequestUsage(req.clientApiKey?.id, upstreamModel, response.usage);
|
|
58
59
|
|
|
59
60
|
const duration = Date.now() - startTime;
|
|
60
|
-
logger.response(200, { model: upstreamModel, ...getTokenDetails(response.usage), duration });
|
|
61
|
+
logger.response(200, { model: upstreamModel, requestedModel, ...getTokenDetails(response.usage), duration });
|
|
61
62
|
|
|
62
63
|
res.json(_buildOpenAIResponse(response, requestedModel));
|
|
63
64
|
} catch (error) {
|
|
64
|
-
handleStreamError(res, error, upstreamModel, startTime);
|
|
65
|
+
handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
65
66
|
}
|
|
66
67
|
}
|
|
67
68
|
|
|
@@ -56,6 +56,14 @@ export async function handleMessages(req, res) {
|
|
|
56
56
|
|
|
57
57
|
const { upstreamModel } = resolveModelRouting(requestedModel);
|
|
58
58
|
|
|
59
|
+
logger.request('POST', '/v1/messages', {
|
|
60
|
+
model: upstreamModel,
|
|
61
|
+
requestedModel,
|
|
62
|
+
stream: isStreaming,
|
|
63
|
+
messages: body.messages?.length || 0,
|
|
64
|
+
tools: body.tools?.length || 0
|
|
65
|
+
});
|
|
66
|
+
|
|
59
67
|
const rotator = getAccountRotator();
|
|
60
68
|
|
|
61
69
|
rotator.clearExpiredLimits();
|
|
@@ -68,7 +76,7 @@ export async function handleMessages(req, res) {
|
|
|
68
76
|
if (minWait > 0) {
|
|
69
77
|
const waitSeconds = Math.round(minWait / 1000);
|
|
70
78
|
logger.info(`[Messages] All accounts temporarily unavailable. Next possible reset: ${waitSeconds}s`);
|
|
71
|
-
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime);
|
|
79
|
+
return handleStreamError(res, new Error(`RESOURCE_EXHAUSTED: All accounts rate-limited. Wait ${waitSeconds}s`), upstreamModel, startTime, requestedModel);
|
|
72
80
|
}
|
|
73
81
|
}
|
|
74
82
|
|
|
@@ -105,7 +113,7 @@ export async function handleMessages(req, res) {
|
|
|
105
113
|
return;
|
|
106
114
|
} catch (error) {
|
|
107
115
|
if (res.headersSent) {
|
|
108
|
-
return handleStreamError(res, error, upstreamModel, startTime);
|
|
116
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
109
117
|
}
|
|
110
118
|
|
|
111
119
|
if (error.message.startsWith('RATE_LIMITED:')) {
|
|
@@ -113,7 +121,7 @@ export async function handleMessages(req, res) {
|
|
|
113
121
|
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
|
|
114
122
|
if (!replacement) {
|
|
115
123
|
logger.info(`[Messages] Rate limit on ${account.email}; no other account available, stopping retry`);
|
|
116
|
-
return handleStreamError(res, error, upstreamModel, startTime);
|
|
124
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
117
125
|
}
|
|
118
126
|
|
|
119
127
|
logger.info(`[Messages] Rate limit on ${account.email}; switched to ${replacement.email}`);
|
|
@@ -126,7 +134,7 @@ export async function handleMessages(req, res) {
|
|
|
126
134
|
const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
|
|
127
135
|
if (!replacement) {
|
|
128
136
|
logger.info(`[Messages] Auth expired on ${account.email}; no other account available, stopping retry`);
|
|
129
|
-
return handleStreamError(res, error, upstreamModel, startTime);
|
|
137
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
130
138
|
}
|
|
131
139
|
|
|
132
140
|
logger.info(`[Messages] Auth expired on ${account.email}; switched to ${replacement.email}`);
|
|
@@ -136,14 +144,14 @@ export async function handleMessages(req, res) {
|
|
|
136
144
|
|
|
137
145
|
if (error.status === 400 || error.anthropicErrorType === 'invalid_request_error') {
|
|
138
146
|
logger.info(`[Messages] Invalid request on ${account.email}; stopping account rotation`);
|
|
139
|
-
return handleStreamError(res, error, upstreamModel, startTime);
|
|
147
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
140
148
|
}
|
|
141
149
|
|
|
142
|
-
return handleStreamError(res, error, upstreamModel, startTime);
|
|
150
|
+
return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
|
|
143
151
|
}
|
|
144
152
|
}
|
|
145
153
|
|
|
146
|
-
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime);
|
|
154
|
+
return handleStreamError(res, new Error('Max retries exceeded'), upstreamModel, startTime, requestedModel);
|
|
147
155
|
}
|
|
148
156
|
|
|
149
157
|
async function _streamDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
@@ -151,14 +159,14 @@ async function _streamDirectWithRotation(res, anthropicRequest, creds, responseM
|
|
|
151
159
|
initSSEResponse(res);
|
|
152
160
|
const usage = await pipeSSEStream(res, stream);
|
|
153
161
|
recordRequestUsage(clientKeyId, anthropicRequest.model, usage);
|
|
154
|
-
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
162
|
+
logger.response(200, { model: anthropicRequest.model, requestedModel: responseModel, ...getTokenDetails(usage), duration: Date.now() - startTime });
|
|
155
163
|
}
|
|
156
164
|
|
|
157
165
|
async function _sendDirectWithRotation(res, anthropicRequest, creds, responseModel, startTime, rotator, requestContext, clientKeyId) {
|
|
158
166
|
const response = await sendMessage(anthropicRequest, creds.accessToken, creds.accountId, requestContext, rotator, creds.email);
|
|
159
167
|
recordRequestUsage(clientKeyId, anthropicRequest.model, response.usage);
|
|
160
168
|
const duration = Date.now() - startTime;
|
|
161
|
-
logger.response(200, { model: anthropicRequest.model, ...getTokenDetails(response.usage), duration });
|
|
169
|
+
logger.response(200, { model: anthropicRequest.model, requestedModel: responseModel, ...getTokenDetails(response.usage), duration });
|
|
162
170
|
res.json({ ...response, model: responseModel });
|
|
163
171
|
}
|
|
164
172
|
|
package/src/server.js
CHANGED
|
@@ -9,6 +9,7 @@ import cors from 'cors';
|
|
|
9
9
|
import { ensureAccountsPersist, startAutoRefresh } from './account-manager.js';
|
|
10
10
|
import { getServerHost } from './deployment.js';
|
|
11
11
|
import { registerApiRoutes } from './routes/api-routes.js';
|
|
12
|
+
import { startDailyAnchorPing } from './daily-anchor-ping.js';
|
|
12
13
|
|
|
13
14
|
export function createServer({ port, testMode = false, startBackgroundJobs = true, persistAccounts = true }) {
|
|
14
15
|
if (!testMode && persistAccounts) {
|
|
@@ -16,6 +17,9 @@ export function createServer({ port, testMode = false, startBackgroundJobs = tru
|
|
|
16
17
|
}
|
|
17
18
|
if (!testMode && startBackgroundJobs) {
|
|
18
19
|
startAutoRefresh();
|
|
20
|
+
// Every day at 09:00 local time, re-anchor each account's upstream
|
|
21
|
+
// five-hour usage window so its reset time settles at 14:00.
|
|
22
|
+
startDailyAnchorPing();
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
const app = express();
|
package/src/utils/logger.js
CHANGED
|
@@ -160,6 +160,7 @@ class Logger extends EventEmitter {
|
|
|
160
160
|
request(method, path, details = {}) {
|
|
161
161
|
const parts = [`${method}`, path];
|
|
162
162
|
if (details.model) parts.push(`model=${details.model}`);
|
|
163
|
+
if (details.requestedModel) parts.push(`requested_model=${details.requestedModel}`);
|
|
163
164
|
if (details.account) parts.push(`account=${details.account}`);
|
|
164
165
|
if (details.stream !== undefined) parts.push(`stream=${details.stream}`);
|
|
165
166
|
if (details.messages) parts.push(`messages=${details.messages}`);
|
|
@@ -170,6 +171,7 @@ class Logger extends EventEmitter {
|
|
|
170
171
|
response(status, details = {}) {
|
|
171
172
|
const parts = [`status=${status}`];
|
|
172
173
|
if (details.model) parts.push(`model=${details.model}`);
|
|
174
|
+
if (details.requestedModel) parts.push(`requested_model=${details.requestedModel}`);
|
|
173
175
|
if (details.tokens !== undefined) parts.push(`tokens=${details.tokens}`);
|
|
174
176
|
if (details.inputTokens !== undefined) parts.push(`input_tokens=${details.inputTokens}`);
|
|
175
177
|
if (details.outputTokens !== undefined) parts.push(`output_tokens=${details.outputTokens}`);
|