claude-codex-proxy 1.0.5-beta.2 → 1.0.5-beta.4

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.
@@ -0,0 +1,92 @@
1
+ <div x-show="activeTab === 'logs'" x-transition class="view-container h-full flex flex-col">
2
+ <div class="flex items-center justify-between gap-4 mb-6">
3
+ <div class="flex flex-wrap items-center gap-4">
4
+ <h1 class="text-2xl font-bold text-white tracking-tight">Server Logs</h1>
5
+ <div class="flex items-center h-6 px-3 rounded-full bg-space-800/80 border border-space-border/50 shadow-sm backdrop-blur-sm">
6
+ <span class="text-[10px] font-mono text-gray-400 uppercase tracking-wider">Real-time log stream</span>
7
+ </div>
8
+ </div>
9
+ <div class="flex items-center gap-3">
10
+ <div class="text-[10px] font-mono text-gray-600">
11
+ <span x-text="logs.length"></span> entries
12
+ </div>
13
+ <button class="btn btn-xs btn-ghost text-gray-400 hover:text-white" @click="clearLogs()" title="Clear logs">
14
+ <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
15
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
16
+ </svg>
17
+ </button>
18
+ </div>
19
+ </div>
20
+
21
+ <div class="view-card !p-0 flex flex-col flex-1 min-h-0">
22
+ <div class="bg-space-900 flex items-center p-2 px-4 border-b border-space-border gap-4">
23
+ <div class="flex gap-2">
24
+ <div class="w-3 h-3 rounded-full bg-red-500/20 border border-red-500/50"></div>
25
+ <div class="w-3 h-3 rounded-full bg-yellow-500/20 border border-yellow-500/50"></div>
26
+ <div class="w-3 h-3 rounded-full bg-green-500/20 border border-green-500/50"></div>
27
+ </div>
28
+ <span class="text-xs font-mono text-gray-500 hidden sm:inline-block">~/logs</span>
29
+
30
+ <div class="flex-1 flex items-center justify-center gap-4">
31
+ <div class="relative w-full max-w-xs">
32
+ <input type="text" x-model="logSearchQuery" placeholder="Search logs..."
33
+ class="w-full h-7 bg-space-950 border border-space-border rounded text-xs font-mono pl-7 pr-2 focus:border-neon-purple focus:outline-none transition-colors placeholder-gray-700 text-gray-300">
34
+ <svg class="w-3 h-3 absolute left-2.5 top-2 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
35
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
36
+ </svg>
37
+ </div>
38
+
39
+ <div class="hidden md:flex gap-3 text-[10px] font-mono font-bold uppercase select-none">
40
+ <label class="flex items-center gap-1.5 cursor-pointer text-blue-400 opacity-50 hover:opacity-100 transition-opacity" :class="{'opacity-100': logFilters.INFO}">
41
+ <input type="checkbox" class="checkbox checkbox-xs rounded-[2px] w-3 h-3" x-model="logFilters.INFO"> INFO
42
+ </label>
43
+ <label class="flex items-center gap-1.5 cursor-pointer text-green-400 opacity-50 hover:opacity-100 transition-opacity" :class="{'opacity-100': logFilters.SUCCESS}">
44
+ <input type="checkbox" class="checkbox checkbox-xs rounded-[2px] w-3 h-3" x-model="logFilters.SUCCESS"> SUCCESS
45
+ </label>
46
+ <label class="flex items-center gap-1.5 cursor-pointer text-yellow-400 opacity-50 hover:opacity-100 transition-opacity" :class="{'opacity-100': logFilters.WARN}">
47
+ <input type="checkbox" class="checkbox checkbox-xs rounded-[2px] w-3 h-3" x-model="logFilters.WARN"> WARN
48
+ </label>
49
+ <label class="flex items-center gap-1.5 cursor-pointer text-red-500 opacity-50 hover:opacity-100 transition-opacity" :class="{'opacity-100': logFilters.ERROR}">
50
+ <input type="checkbox" class="checkbox checkbox-xs rounded-[2px] w-3 h-3" x-model="logFilters.ERROR"> ERROR
51
+ </label>
52
+ </div>
53
+ </div>
54
+ </div>
55
+
56
+ <div id="logs-container" class="flex-1 overflow-auto p-4 font-mono text-[11px] leading-relaxed bg-space-950 custom-scrollbar">
57
+ <template x-for="(log, idx) in filteredLogs" :key="idx">
58
+ <div class="flex gap-3 px-2 py-1 -mx-2 hover:bg-white/[0.03] transition-colors group border-b border-space-border/10">
59
+ <span class="text-zinc-600 w-16 shrink-0 select-none group-hover:text-zinc-500 transition-colors"
60
+ x-text="new Date(log.timestamp).toLocaleTimeString([], {hour12:false})"></span>
61
+ <div class="w-16 shrink-0 flex items-center">
62
+ <span class="px-1.5 py-0.5 rounded-[2px] text-[10px] font-bold uppercase tracking-wider leading-none border"
63
+ :class="{
64
+ 'bg-blue-500/10 text-blue-400 border-blue-500/20': log.level === 'INFO',
65
+ 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20': log.level === 'WARN',
66
+ 'bg-red-500/10 text-red-500 border-red-500/20': log.level === 'ERROR',
67
+ 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20': log.level === 'SUCCESS',
68
+ 'bg-purple-500/10 text-purple-400 border-purple-500/20': log.level === 'DEBUG'
69
+ }" x-text="log.level"></span>
70
+ </div>
71
+ <div class="flex-1 flex flex-col gap-0.5 min-w-0">
72
+ <span class="text-zinc-200 break-all group-hover:text-white transition-colors"
73
+ x-text="formatLogMessage(log.message)"></span>
74
+ <template x-if="getLogDetails(log.message)">
75
+ <div class="flex flex-wrap gap-2 text-[10px] text-zinc-500 mt-0.5">
76
+ <template x-for="(detail, key) in getLogDetails(log.message)" :key="key">
77
+ <span class="px-1.5 py-0.5 bg-space-800/50 rounded border border-space-border/30">
78
+ <span class="text-zinc-600" x-text="key"></span>=<span class="text-zinc-400" x-text="detail"></span>
79
+ </span>
80
+ </template>
81
+ </div>
82
+ </template>
83
+ </div>
84
+ </div>
85
+ </template>
86
+ <div class="h-3 w-1.5 bg-zinc-600 animate-pulse mt-1 inline-block" x-show="filteredLogs.length === logs.length && !logSearchQuery"></div>
87
+ <div x-show="filteredLogs.length === 0 && logs.length > 0" class="text-zinc-700 italic mt-8 text-center">
88
+ No logs match filter
89
+ </div>
90
+ </div>
91
+ </div>
92
+ </div>
@@ -0,0 +1,123 @@
1
+ <div x-show="activeTab === 'settings'" x-transition class="view-container">
2
+ <div class="flex items-center justify-between gap-4 mb-6">
3
+ <div class="flex flex-wrap items-center gap-4">
4
+ <h1 class="text-2xl font-bold text-white tracking-tight">Settings</h1>
5
+ <div class="flex items-center h-6 px-3 rounded-full bg-space-800/80 border border-space-border/50 shadow-sm backdrop-blur-sm">
6
+ <span class="text-[10px] font-mono text-gray-400 uppercase tracking-wider">Server configuration</span>
7
+ </div>
8
+ </div>
9
+ </div>
10
+
11
+ <div class="view-card">
12
+ <div class="flex items-center gap-2.5 mb-4">
13
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4 text-neon-cyan">
14
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
15
+ </svg>
16
+ <h3 class="text-xs font-mono text-gray-400 uppercase tracking-widest">Server Info</h3>
17
+ </div>
18
+ <div class="space-y-3">
19
+ <div class="flex items-center justify-between py-2 border-b border-space-border/30">
20
+ <span class="text-sm text-gray-400">Server URL</span>
21
+ <span class="font-mono text-sm text-white" x-text="serverUrl"></span>
22
+ </div>
23
+ <div class="flex items-center justify-between py-2 border-b border-space-border/30">
24
+ <span class="text-sm text-gray-400">Config Path</span>
25
+ <span class="font-mono text-sm text-white" x-text="configPath"></span>
26
+ </div>
27
+ <div class="flex items-center justify-between py-2">
28
+ <span class="text-sm text-gray-400">Auto Token Refresh</span>
29
+ <span class="text-xs font-mono text-neon-green">Every 55 minutes</span>
30
+ </div>
31
+ </div>
32
+ </div>
33
+
34
+ <div class="view-card mt-6">
35
+ <div class="flex items-center gap-2.5 mb-4">
36
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4 text-yellow-400">
37
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
38
+ </svg>
39
+ <h3 class="text-xs font-mono text-gray-400 uppercase tracking-widest">Raw Proxy Payload Logs</h3>
40
+ </div>
41
+ <div class="flex flex-wrap items-center justify-between gap-4">
42
+ <div>
43
+ <div class="text-sm text-gray-300">Capture raw request/response payloads</div>
44
+ <div class="text-xs text-gray-500 font-mono">Logs Claude Code requests, OpenAI/Codex upstream requests, completed responses, and upstream errors. May include prompts and tool results.</div>
45
+ </div>
46
+ <label class="flex items-center gap-3 cursor-pointer select-none">
47
+ <span class="text-xs font-mono" :class="logRawProxyPayloads ? 'text-yellow-400' : 'text-gray-500'" x-text="logRawProxyPayloads ? 'ENABLED' : 'DISABLED'"></span>
48
+ <input type="checkbox" class="toggle toggle-warning" :checked="logRawProxyPayloads" @change="setRawProxyLogs($event.target.checked)" :disabled="rawProxyLogsSaving">
49
+ </label>
50
+ </div>
51
+ </div>
52
+
53
+ <div class="view-card mt-6">
54
+ <div class="flex flex-wrap items-center justify-between gap-4 mb-4">
55
+ <div class="flex items-center gap-2.5">
56
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4 text-neon-cyan">
57
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7h5l2 3h11M3 17h5l2-3h11M14 4l3 3-3 3M14 20l3-3-3-3"></path>
58
+ </svg>
59
+ <h3 class="text-xs font-mono text-gray-400 uppercase tracking-widest">Model Mapping</h3>
60
+ </div>
61
+ <div class="flex flex-wrap items-center gap-2">
62
+ <button class="btn btn-xs btn-outline text-gray-400" @click="resetModelMapSetting()" :disabled="modelMapSaving">Reset Defaults</button>
63
+ <button class="btn btn-xs bg-neon-purple hover:bg-purple-600 border-none text-white" @click="saveModelMapSetting()" :disabled="modelMapSaving">Save Mapping</button>
64
+ </div>
65
+ </div>
66
+
67
+ <template x-if="modelMapLoading">
68
+ <div class="text-xs text-gray-500 font-mono">Loading model mapping...</div>
69
+ </template>
70
+
71
+ <div class="grid gap-3">
72
+ <div class="grid grid-cols-1 md:grid-cols-[160px_1fr] gap-2 md:items-center">
73
+ <div>
74
+ <div class="text-sm text-gray-300">Claude Opus</div>
75
+ <div class="text-xs text-gray-500 font-mono">opus</div>
76
+ </div>
77
+ <input type="text" x-model="modelMappings.opus" placeholder="gpt-5.5"
78
+ class="input bg-space-800 border-space-border text-white font-mono text-sm">
79
+ </div>
80
+
81
+ <div class="grid grid-cols-1 md:grid-cols-[160px_1fr] gap-2 md:items-center">
82
+ <div>
83
+ <div class="text-sm text-gray-300">Claude Sonnet</div>
84
+ <div class="text-xs text-gray-500 font-mono">sonnet</div>
85
+ </div>
86
+ <input type="text" x-model="modelMappings.sonnet" placeholder="gpt-5.5"
87
+ class="input bg-space-800 border-space-border text-white font-mono text-sm">
88
+ </div>
89
+
90
+ <div class="grid grid-cols-1 md:grid-cols-[160px_1fr] gap-2 md:items-center">
91
+ <div>
92
+ <div class="text-sm text-gray-300">Claude Haiku</div>
93
+ <div class="text-xs text-gray-500 font-mono">haiku</div>
94
+ </div>
95
+ <input type="text" x-model="modelMappings.haiku" placeholder="gpt-5.4-mini"
96
+ class="input bg-space-800 border-space-border text-white font-mono text-sm">
97
+ </div>
98
+
99
+ <div class="text-xs text-gray-500 font-mono">Map each Claude family to a GPT/Codex model available to your ChatGPT account.</div>
100
+ </div>
101
+ </div>
102
+
103
+ <div class="view-card mt-6">
104
+ <div class="flex items-center gap-2.5 mb-4">
105
+ <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" class="w-4 h-4 text-neon-purple">
106
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
107
+ </svg>
108
+ <h3 class="text-xs font-mono text-gray-400 uppercase tracking-widest">Account Selection Strategy</h3>
109
+ </div>
110
+ <div class="flex flex-wrap items-center justify-between gap-4">
111
+ <div>
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>
114
+ </div>
115
+ <div class="inline-flex items-center gap-2">
116
+ <button class="btn btn-xs" :class="accountStrategy === 'sticky' ? 'bg-neon-purple text-white' : 'btn-outline text-gray-400'"
117
+ @click="setAccountStrategy('sticky')" :disabled="strategySaving">Sticky</button>
118
+ <button class="btn btn-xs" :class="accountStrategy === 'round-robin' ? 'bg-neon-purple text-white' : 'btn-outline text-gray-400'"
119
+ @click="setAccountStrategy('round-robin')" :disabled="strategySaving">Round-Robin</button>
120
+ </div>
121
+ </div>
122
+ </div>
123
+ </div>
@@ -117,18 +117,6 @@ export function clearExpiredLimits(accounts) {
117
117
  return clearedCount;
118
118
  }
119
119
 
120
- /**
121
- * Reset all rate limits for all accounts (optimistic retry)
122
- * @param {Array} accounts - Array of account objects
123
- */
124
- export function resetAllRateLimits(accounts) {
125
- if (!accounts || accounts.length === 0) return;
126
- for (const account of accounts) {
127
- account.modelRateLimits = {};
128
- }
129
- logger.info('Reset all rate limits for all accounts (optimistic retry)');
130
- }
131
-
132
120
  /**
133
121
  * Mark an account as rate-limited for a specific model
134
122
  * @param {Array} accounts - Array of account objects
@@ -235,20 +223,6 @@ export function getMinWaitTimeMs(accounts, modelId) {
235
223
  return minWait === Infinity ? 0 : minWait;
236
224
  }
237
225
 
238
- /**
239
- * Get rate limit info for a specific account and model
240
- * @param {Array} accounts - Array of account objects
241
- * @param {string} email - Account email
242
- * @param {string} modelId - Model identifier
243
- * @returns {Object|null} Rate limit info object or null
244
- */
245
- export function getRateLimitInfo(accounts, email, modelId) {
246
- const account = accounts?.find(a => a.email === email);
247
- if (!account) return null;
248
-
249
- return account.modelRateLimits?.[modelId] || null;
250
- }
251
-
252
226
  /**
253
227
  * Check if an account is currently cooling down
254
228
  * @param {Object} account - Account object
@@ -75,23 +75,6 @@ export async function updateClaudeConfig(updates) {
75
75
  }
76
76
  }
77
77
 
78
- export async function setProxyMode(proxyUrl, models = {}) {
79
- const updates = {
80
- env: {
81
- ANTHROPIC_BASE_URL: proxyUrl,
82
- ANTHROPIC_API_KEY: 'sk-ant-proxy',
83
- ANTHROPIC_AUTH_TOKEN: undefined, // Explicitly unset to avoid conflict
84
- ANTHROPIC_DEFAULT_OPUS_MODEL: models.opus || 'claude-opus',
85
- ANTHROPIC_DEFAULT_SONNET_MODEL: models.sonnet || 'claude-sonnet',
86
- ANTHROPIC_DEFAULT_HAIKU_MODEL: models.haiku || 'claude-haiku',
87
- CLAUDE_CODE_AUTO_COMPACT_WINDOW: '258000'
88
- },
89
- autoCompactEnabled: true
90
- };
91
-
92
- return await updateClaudeConfig(updates);
93
- }
94
-
95
78
  export async function setDirectMode(apiKey) {
96
79
  const updates = {
97
80
  env: {
@@ -148,7 +131,6 @@ export default {
148
131
  readClaudeConfig,
149
132
  readClaudeConfigSync,
150
133
  updateClaudeConfig,
151
- setProxyMode,
152
134
  setDirectMode,
153
135
  setApiEndpoint
154
136
  };
@@ -0,0 +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 };
package/src/deployment.js CHANGED
@@ -1,49 +1,49 @@
1
- /**
2
- * Deployment policy helpers shared by server, routes and auth middleware.
3
- */
4
-
5
- const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
6
-
7
- /**
8
- * Returns the validated deployment mode, defaulting to local when unset.
9
- * @returns {'local'|'public'}
10
- */
11
- export function getDeploymentMode() {
12
- const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
13
- if (!VALID_DEPLOYMENT_MODES.has(mode)) {
14
- throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
15
- }
16
- return mode;
17
- }
18
-
19
- /**
20
- * Indicates whether the proxy is running in public deployment mode.
21
- * @returns {boolean}
22
- */
23
- export function isPublicDeployment() {
24
- return getDeploymentMode() === 'public';
25
- }
26
-
27
- /**
28
- * Returns the host address the main HTTP server should bind to.
29
- * @returns {string}
30
- */
31
- export function getServerHost() {
32
- if (process.env.HOST) {
33
- return process.env.HOST;
34
- }
35
- return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
36
- }
37
-
38
- /**
39
- * Returns a display URL for logs and local helper responses.
40
- * @param {number|string} port
41
- * @returns {string}
42
- */
43
- export function getLocalBaseUrl(port) {
44
- const host = getServerHost();
45
- const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
46
- return `http://${displayHost}:${port}`;
47
- }
48
-
49
- export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
1
+ /**
2
+ * Deployment policy helpers shared by server, routes and auth middleware.
3
+ */
4
+
5
+ const VALID_DEPLOYMENT_MODES = new Set(['local', 'public']);
6
+
7
+ /**
8
+ * Returns the validated deployment mode, defaulting to local when unset.
9
+ * @returns {'local'|'public'}
10
+ */
11
+ export function getDeploymentMode() {
12
+ const mode = process.env.PROXY_DEPLOYMENT_MODE || 'local';
13
+ if (!VALID_DEPLOYMENT_MODES.has(mode)) {
14
+ throw new Error(`Invalid PROXY_DEPLOYMENT_MODE "${mode}". Expected "local" or "public".`);
15
+ }
16
+ return mode;
17
+ }
18
+
19
+ /**
20
+ * Indicates whether the proxy is running in public deployment mode.
21
+ * @returns {boolean}
22
+ */
23
+ export function isPublicDeployment() {
24
+ return getDeploymentMode() === 'public';
25
+ }
26
+
27
+ /**
28
+ * Returns the host address the main HTTP server should bind to.
29
+ * @returns {string}
30
+ */
31
+ export function getServerHost() {
32
+ if (process.env.HOST) {
33
+ return process.env.HOST;
34
+ }
35
+ return isPublicDeployment() ? '0.0.0.0' : '127.0.0.1';
36
+ }
37
+
38
+ /**
39
+ * Returns a display URL for logs and local helper responses.
40
+ * @param {number|string} port
41
+ * @returns {string}
42
+ */
43
+ export function getLocalBaseUrl(port) {
44
+ const host = getServerHost();
45
+ const displayHost = host === '0.0.0.0' || host === '::' ? 'localhost' : host;
46
+ return `http://${displayHost}:${port}`;
47
+ }
48
+
49
+ export default { getDeploymentMode, isPublicDeployment, getServerHost, getLocalBaseUrl };
package/src/direct-api.js CHANGED
@@ -7,17 +7,14 @@ import os from 'os';
7
7
  import { createRequire } from 'module';
8
8
  import { convertAnthropicToResponsesAPI, convertOutputToAnthropic, generateMessageId } from './format-converter.js';
9
9
  import { streamResponsesAPI, parseResponsesAPIResponse, createResponsesAPIError } from './response-streamer.js';
10
- import { getServerSettings } from './server-settings.js';
11
10
  import { logger } from './utils/logger.js';
11
+ import { shouldLogRawProxyPayloads } from './utils/proxy-logging.js';
12
12
 
13
13
  const require = createRequire(import.meta.url);
14
14
  const packageJson = require('../package.json');
15
15
  const API_URL = 'https://chatgpt.com/backend-api/codex/responses';
16
16
  const APP_VERSION = packageJson.version;
17
-
18
- function shouldLogRawProxyPayloads() {
19
- return getServerSettings().logRawProxyPayloads === true;
20
- }
17
+ const UPSTREAM_REQUEST_TIMEOUT_MS = 120000;
21
18
 
22
19
  function createAnthropicUsage(upstreamUsage = {}) {
23
20
  const usage = {
@@ -30,6 +27,10 @@ function createAnthropicUsage(upstreamUsage = {}) {
30
27
  value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
31
28
  enumerable: false
32
29
  });
30
+ Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
31
+ value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
32
+ enumerable: false
33
+ });
33
34
  return usage;
34
35
  }
35
36
 
@@ -128,15 +129,14 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
128
129
  const response = await fetch(API_URL, {
129
130
  method: 'POST',
130
131
  headers: buildOpencodeHeaders(accessToken, accountId, context),
131
- body: JSON.stringify(request)
132
+ body: JSON.stringify(request),
133
+ signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
132
134
  });
133
135
 
134
136
  if (response.ok) return response;
135
137
 
136
138
  const errorText = await response.text();
137
- if (shouldLogRawProxyPayloads()) {
138
- logger.info('[OpenAI Error]', { status: response.status, body: errorText });
139
- }
139
+ logger.info('[OpenAI Error]', { status: response.status, body: errorText });
140
140
 
141
141
  if (response.status === 401) {
142
142
  if (accountRotator && currentEmail) {
@@ -197,14 +197,13 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
197
197
  const response = await fetch(API_URL, {
198
198
  method: 'POST',
199
199
  headers: buildOpencodeHeaders(accessToken, accountId, context),
200
- body: JSON.stringify(request)
200
+ body: JSON.stringify(request),
201
+ signal: AbortSignal.timeout(UPSTREAM_REQUEST_TIMEOUT_MS)
201
202
  });
202
203
 
203
204
  if (!response.ok) {
204
205
  const errorText = await response.text();
205
- if (shouldLogRawProxyPayloads()) {
206
- logger.info('[OpenAI Error]', { status: response.status, body: errorText });
207
- }
206
+ logger.info('[OpenAI Error]', { status: response.status, body: errorText });
208
207
 
209
208
  if (response.status === 401) {
210
209
  throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);