claude-codex-proxy 1.0.5-beta.34 → 1.0.5-beta.36

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.34",
3
+ "version": "1.0.5-beta.36",
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",
@@ -110,7 +110,7 @@
110
110
  <div class="flex flex-wrap items-center justify-between gap-4">
111
111
  <div>
112
112
  <div class="text-sm text-gray-300">Strategy</div>
113
- <div class="text-xs text-gray-500 font-mono">How accounts are selected when rate-limited</div>
113
+ <div class="text-xs text-gray-500 font-mono">How requests are distributed across available accounts</div>
114
114
  </div>
115
115
  <div class="inline-flex items-center gap-2">
116
116
  <button class="btn btn-xs" :class="accountStrategy === 'sticky' ? 'bg-neon-purple text-white' : 'btn-outline text-gray-400'"
@@ -119,5 +119,15 @@
119
119
  @click="setAccountStrategy('round-robin')" :disabled="strategySaving">Round-Robin</button>
120
120
  </div>
121
121
  </div>
122
+ <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mt-4">
123
+ <div class="rounded-lg border p-3" :class="accountStrategy === 'sticky' ? 'border-neon-purple/50 bg-neon-purple/5' : 'border-space-border bg-space-800/40'">
124
+ <div class="text-xs font-mono text-gray-300 mb-1">Sticky · Cache-Optimized</div>
125
+ <div class="text-xs text-gray-500">Keeps using the active account. If it becomes unavailable, switches to another usable account.</div>
126
+ </div>
127
+ <div class="rounded-lg border p-3" :class="accountStrategy === 'round-robin' ? 'border-neon-purple/50 bg-neon-purple/5' : 'border-space-border bg-space-800/40'">
128
+ <div class="text-xs font-mono text-gray-300 mb-1">Round-Robin · Session-Balanced</div>
129
+ <div class="text-xs text-gray-500">Distributes new sessions across accounts, then keeps each session on the same account for cache reuse.</div>
130
+ </div>
131
+ </div>
122
132
  </div>
123
133
  </div>
@@ -75,6 +75,12 @@ export class AccountRotator {
75
75
  return getMinWaitTimeMs(accounts, modelId);
76
76
  }
77
77
 
78
+ commitSessionBinding(sessionId, email) {
79
+ if (this.strategy.commitSessionBinding) {
80
+ this.strategy.commitSessionBinding(sessionId, email);
81
+ }
82
+ }
83
+
78
84
  notifySuccess(account, modelId) {
79
85
  if (this.strategy.notifySuccess) {
80
86
  this.strategy.notifySuccess(account, modelId);
@@ -1,10 +1,20 @@
1
1
  import { BaseStrategy } from './base-strategy.js';
2
2
  import { logger } from '../../utils/logger.js';
3
3
 
4
+ const DEFAULT_SESSION_BINDING_TTL_MS = 24 * 60 * 60 * 1000;
5
+ const DEFAULT_SESSION_CLEANUP_INTERVAL_MS = 60 * 1000;
6
+ const DEFAULT_MAX_SESSION_BINDINGS = 10000;
7
+
4
8
  export class RoundRobinStrategy extends BaseStrategy {
5
- constructor(config) {
9
+ constructor(config = {}) {
6
10
  super(config, 'round-robin');
7
11
  this.cursor = 0;
12
+ this.sessionBindings = new Map();
13
+ this.sessionBindingTtlMs = config.sessionBindingTtlMs ?? DEFAULT_SESSION_BINDING_TTL_MS;
14
+ this.sessionCleanupIntervalMs = config.sessionCleanupIntervalMs ?? DEFAULT_SESSION_CLEANUP_INTERVAL_MS;
15
+ this.maxSessionBindings = config.maxSessionBindings ?? DEFAULT_MAX_SESSION_BINDINGS;
16
+ this.lastSessionCleanupAt = 0;
17
+ this.now = config.now ?? Date.now;
8
18
  }
9
19
 
10
20
  selectAccount(accounts, modelId, options = {}) {
@@ -12,6 +22,32 @@ export class RoundRobinStrategy extends BaseStrategy {
12
22
  return { account: null, index: 0, waitMs: 0 };
13
23
  }
14
24
 
25
+ const sessionId = this.#normalizeSessionId(options.sessionId);
26
+ const excludedEmails = new Set(options.excludeEmails || []);
27
+ const now = this.now();
28
+
29
+ if (sessionId) {
30
+ this.#cleanupSessionBindingsIfDue(now);
31
+ const binding = this.sessionBindings.get(sessionId);
32
+ if (binding && now - binding.lastUsedAt >= this.sessionBindingTtlMs) {
33
+ this.sessionBindings.delete(sessionId);
34
+ }
35
+ const currentBinding = this.sessionBindings.get(sessionId);
36
+ const boundIndex = currentBinding
37
+ ? accounts.findIndex(account => account.email === currentBinding.email)
38
+ : -1;
39
+ const boundAccount = boundIndex >= 0 ? accounts[boundIndex] : null;
40
+
41
+ if (boundAccount
42
+ && !excludedEmails.has(boundAccount.email)
43
+ && this.isAccountUsable(boundAccount, modelId)) {
44
+ boundAccount.lastUsed = now;
45
+ this.#storeSessionBinding(sessionId, boundAccount.email, now);
46
+ logger.debug(`RoundRobinStrategy: Reusing session account at index ${boundIndex}`);
47
+ return { account: boundAccount, index: boundIndex, waitMs: 0 };
48
+ }
49
+ }
50
+
15
51
  // Clamp cursor
16
52
  if (this.cursor >= accounts.length) {
17
53
  this.cursor = 0;
@@ -24,9 +60,12 @@ export class RoundRobinStrategy extends BaseStrategy {
24
60
  const checkIndex = (startIndex + i) % accounts.length;
25
61
  const account = accounts[checkIndex];
26
62
 
27
- if (this.isAccountUsable(account, modelId)) {
28
- account.lastUsed = Date.now();
63
+ if (!excludedEmails.has(account.email) && this.isAccountUsable(account, modelId)) {
64
+ account.lastUsed = now;
29
65
  this.cursor = checkIndex;
66
+ if (sessionId && !options.deferSessionBinding) {
67
+ this.#storeSessionBinding(sessionId, account.email, now);
68
+ }
30
69
  logger.debug(`RoundRobinStrategy: Using account at index ${checkIndex}`);
31
70
  return { account, index: checkIndex, waitMs: 0 };
32
71
  }
@@ -36,7 +75,43 @@ export class RoundRobinStrategy extends BaseStrategy {
36
75
  return { account: null, index: this.cursor, waitMs: 0 };
37
76
  }
38
77
 
78
+ commitSessionBinding(sessionId, email) {
79
+ const normalizedSessionId = this.#normalizeSessionId(sessionId);
80
+ if (!normalizedSessionId || !email) return;
81
+
82
+ const now = this.now();
83
+ this.#cleanupSessionBindingsIfDue(now);
84
+ this.#storeSessionBinding(normalizedSessionId, email, now);
85
+ }
86
+
39
87
  resetCursor() {
40
88
  this.cursor = 0;
41
89
  }
90
+
91
+ #normalizeSessionId(sessionId) {
92
+ if (typeof sessionId !== 'string' && typeof sessionId !== 'number') return null;
93
+ const normalized = String(sessionId).trim();
94
+ return normalized || null;
95
+ }
96
+
97
+ #storeSessionBinding(sessionId, email, now) {
98
+ this.sessionBindings.delete(sessionId);
99
+ this.sessionBindings.set(sessionId, { email, lastUsedAt: now });
100
+
101
+ while (this.sessionBindings.size > this.maxSessionBindings) {
102
+ const oldestSessionId = this.sessionBindings.keys().next().value;
103
+ this.sessionBindings.delete(oldestSessionId);
104
+ }
105
+ }
106
+
107
+ #cleanupSessionBindingsIfDue(now) {
108
+ if (now - this.lastSessionCleanupAt < this.sessionCleanupIntervalMs) return;
109
+
110
+ for (const [sessionId, binding] of this.sessionBindings) {
111
+ if (now - binding.lastUsedAt >= this.sessionBindingTtlMs) {
112
+ this.sessionBindings.delete(sessionId);
113
+ }
114
+ }
115
+ this.lastSessionCleanupAt = now;
116
+ }
42
117
  }
@@ -13,13 +13,32 @@ import { shouldLogRawProxyPayloads } from '../utils/proxy-logging.js';
13
13
  let accountRotator = null;
14
14
  let currentStrategy = null;
15
15
 
16
+ /**
17
+ * Resolves the session affinity identifier used by the upstream Codex request.
18
+ * Metadata is preferred for Claude Code compatibility, followed by Pi's
19
+ * supported session affinity headers.
20
+ */
16
21
  function getRequestContext(req) {
22
+ let metadataSessionId;
23
+
17
24
  try {
18
25
  const metadata = JSON.parse(req.body?.metadata?.user_id || '{}');
19
- return { sessionId: metadata.session_id };
26
+ metadataSessionId = metadata.session_id;
20
27
  } catch (_) {
21
- return { sessionId: undefined };
28
+ // Ignore malformed optional metadata and continue with HTTP headers.
22
29
  }
30
+
31
+ const getHeader = (name) => {
32
+ if (typeof req.get === 'function') return req.get(name);
33
+ return req.headers?.[name];
34
+ };
35
+
36
+ return {
37
+ sessionId: metadataSessionId
38
+ || getHeader('session-id')
39
+ || getHeader('x-session-id')
40
+ || getHeader('x-session-affinity')
41
+ };
23
42
  }
24
43
 
25
44
  function getAccountRotator() {
@@ -65,11 +84,14 @@ export async function handleMessages(req, res) {
65
84
  });
66
85
 
67
86
  const rotator = getAccountRotator();
68
-
87
+ const requestContext = getRequestContext(req);
88
+
69
89
  rotator.clearExpiredLimits();
70
-
90
+
71
91
  const maxAttempts = listAccounts().total;
72
- let { account } = rotator.selectAccount(upstreamModel);
92
+ let { account } = rotator.selectAccount(upstreamModel, {
93
+ sessionId: requestContext.sessionId
94
+ });
73
95
 
74
96
  if (!account && rotator.isAllRateLimited(upstreamModel)) {
75
97
  const minWait = rotator.getMinWaitTimeMs(upstreamModel);
@@ -85,14 +107,19 @@ export async function handleMessages(req, res) {
85
107
  }
86
108
 
87
109
  syncActiveAccount(account.email);
110
+ const attemptedEmails = new Set();
88
111
 
89
112
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
90
113
  logger.info(`[Messages] Using account ${account.email} for model ${upstreamModel}`);
91
114
 
92
115
  const creds = await getCredentialsForAccount(account.email);
93
116
  if (!creds) {
117
+ attemptedEmails.add(account.email);
94
118
  rotator.markInvalid(account.email, 'Failed to get credentials');
95
- const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
119
+ const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
120
+ sessionId: requestContext.sessionId,
121
+ excludeEmails: attemptedEmails
122
+ });
96
123
  if (!replacement) {
97
124
  return sendAuthError(res, 'No other available account');
98
125
  }
@@ -101,7 +128,6 @@ export async function handleMessages(req, res) {
101
128
  }
102
129
 
103
130
  const anthropicRequest = { ...body, model: upstreamModel };
104
- const requestContext = getRequestContext(req);
105
131
 
106
132
  try {
107
133
  if (isStreaming) {
@@ -117,8 +143,12 @@ export async function handleMessages(req, res) {
117
143
  }
118
144
 
119
145
  if (error.message.startsWith('RATE_LIMITED:')) {
146
+ attemptedEmails.add(account.email);
120
147
  rotator.notifyRateLimit(account, upstreamModel);
121
- const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
148
+ const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
149
+ sessionId: requestContext.sessionId,
150
+ excludeEmails: attemptedEmails
151
+ });
122
152
  if (!replacement) {
123
153
  logger.info(`[Messages] Rate limit on ${account.email}; no other account available, stopping retry`);
124
154
  return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
@@ -130,8 +160,12 @@ export async function handleMessages(req, res) {
130
160
  }
131
161
 
132
162
  if (error.message.includes('AUTH_EXPIRED')) {
163
+ attemptedEmails.add(account.email);
133
164
  rotator.markInvalid(account.email, 'Auth expired');
134
- const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel);
165
+ const replacement = switchToReplacementAccount(rotator, account.email, upstreamModel, {
166
+ sessionId: requestContext.sessionId,
167
+ excludeEmails: attemptedEmails
168
+ });
135
169
  if (!replacement) {
136
170
  logger.info(`[Messages] Auth expired on ${account.email}; no other account available, stopping retry`);
137
171
  return handleStreamError(res, error, upstreamModel, startTime, requestedModel);
@@ -193,8 +227,20 @@ function recordRequestUsage(clientKeyId, model, usage) {
193
227
  * Selects and activates a different usable account before allowing a retry.
194
228
  * @returns {object|null} The activated replacement account, or null when switching failed.
195
229
  */
196
- export function switchToReplacementAccount(rotator, failedEmail, modelId, activateAccount = setActiveAccount) {
197
- const { account } = rotator.selectAccount(modelId);
230
+ export function switchToReplacementAccount(
231
+ rotator,
232
+ failedEmail,
233
+ modelId,
234
+ selectionOptions = {},
235
+ activateAccount = setActiveAccount
236
+ ) {
237
+ const excludeEmails = new Set(selectionOptions.excludeEmails || []);
238
+ excludeEmails.add(failedEmail);
239
+ const { account } = rotator.selectAccount(modelId, {
240
+ ...selectionOptions,
241
+ excludeEmails,
242
+ deferSessionBinding: true
243
+ });
198
244
  if (!account || account.email === failedEmail) {
199
245
  return null;
200
246
  }
@@ -205,6 +251,7 @@ export function switchToReplacementAccount(rotator, failedEmail, modelId, activa
205
251
  return null;
206
252
  }
207
253
 
254
+ rotator.commitSessionBinding?.(selectionOptions.sessionId, account.email);
208
255
  return account;
209
256
  }
210
257