claude-codex-proxy 1.0.5-beta.2 → 1.0.5-beta.20
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 +210 -9
- package/public/index.html +32 -926
- package/public/js/app.js +168 -737
- package/public/login.html +32 -0
- package/public/views/accounts-modals.html +218 -0
- package/public/views/accounts.html +202 -0
- package/public/views/client-api-keys-modals.html +55 -0
- package/public/views/client-api-keys.html +69 -0
- package/public/views/dashboard.html +90 -0
- package/public/views/empty.html +0 -0
- package/public/views/logs.html +99 -0
- package/public/views/settings.html +123 -0
- package/src/account-manager.js +34 -3
- package/src/account-rotation/rate-limits.js +4 -26
- 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/claude-config.js +0 -18
- package/src/client-key-usage.js +125 -0
- package/src/deployment.js +49 -49
- package/src/direct-api.js +16 -13
- package/src/format-converter.js +77 -48
- package/src/index.js +13 -4
- package/src/middleware/auth.js +46 -11
- package/src/middleware/credentials.js +13 -3
- package/src/model-api.js +60 -0
- package/src/model-pricing.js +127 -0
- package/src/response-streamer.js +17 -7
- package/src/routes/accounts-route.js +106 -2
- package/src/routes/api-routes.js +61 -35
- package/src/routes/chat-route.js +25 -4
- package/src/routes/claude-config-route.js +22 -15
- package/src/routes/client-quota-route.js +25 -0
- package/src/routes/logs-route.js +21 -2
- package/src/routes/messages-route.js +45 -14
- package/src/routes/settings-route.js +36 -5
- package/src/server-settings.js +18 -2
- package/src/utils/logger.js +18 -0
- package/src/utils/proxy-logging.js +5 -0
|
@@ -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 = 4 * 60 * 1000;
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
|
@@ -220,6 +219,10 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
220
219
|
throw error;
|
|
221
220
|
}
|
|
222
221
|
|
|
222
|
+
if (response.status === 400) {
|
|
223
|
+
throw createHTTPError(`INVALID_REQUEST: ${errorText}`, 400, 'invalid_request_error', response.status);
|
|
224
|
+
}
|
|
225
|
+
|
|
223
226
|
throw createUpstreamHTTPError(response, errorText);
|
|
224
227
|
}
|
|
225
228
|
|
package/src/format-converter.js
CHANGED
|
@@ -146,11 +146,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
146
146
|
const instructions = extractSystemPrompt(system);
|
|
147
147
|
|
|
148
148
|
const request = {
|
|
149
|
-
model: model
|
|
149
|
+
model: model,
|
|
150
150
|
input: convertMessagesToInput(cleanedMessages),
|
|
151
151
|
tools: tools ? convertAnthropicToolsToOpenAI(tools) : [],
|
|
152
|
-
tool_choice:
|
|
153
|
-
parallel_tool_calls: true,
|
|
152
|
+
tool_choice: 'auto',
|
|
153
|
+
parallel_tool_calls: tool_choice?.disable_parallel_tool_use !== true,
|
|
154
154
|
store: false,
|
|
155
155
|
stream: true,
|
|
156
156
|
include: []
|
|
@@ -177,23 +177,7 @@ function convertMessagesToInput(messages) {
|
|
|
177
177
|
|
|
178
178
|
for (const msg of messages) {
|
|
179
179
|
if (msg.role === 'user') {
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (textParts.length > 0) {
|
|
183
|
-
// API accepts: string OR array of {type: 'input_text', text: '...'}
|
|
184
|
-
const content = textParts.length === 1
|
|
185
|
-
? textParts[0] // Use string for single text
|
|
186
|
-
: textParts.map(text => ({ type: 'input_text', text }));
|
|
187
|
-
input.push({
|
|
188
|
-
type: 'message',
|
|
189
|
-
role: 'user',
|
|
190
|
-
content
|
|
191
|
-
});
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
for (const result of toolResults) {
|
|
195
|
-
input.push(result);
|
|
196
|
-
}
|
|
180
|
+
input.push(...convertUserContent(msg.content));
|
|
197
181
|
} else if (msg.role === 'assistant') {
|
|
198
182
|
// Process assistant content: restore signatures, reorder, sanitize
|
|
199
183
|
let msgContent = msg.content;
|
|
@@ -225,34 +209,62 @@ function convertMessagesToInput(messages) {
|
|
|
225
209
|
}
|
|
226
210
|
|
|
227
211
|
/**
|
|
228
|
-
* Convert user content
|
|
212
|
+
* Convert Anthropic user content while preserving block order.
|
|
229
213
|
*/
|
|
230
214
|
function convertUserContent(content) {
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
215
|
+
const inputItems = [];
|
|
216
|
+
let messageParts = [];
|
|
217
|
+
|
|
218
|
+
const flushMessageParts = () => {
|
|
219
|
+
if (messageParts.length === 0) return;
|
|
220
|
+
|
|
221
|
+
const messageContent =
|
|
222
|
+
messageParts.length === 1 && messageParts[0].type === 'input_text'
|
|
223
|
+
? messageParts[0].text
|
|
224
|
+
: messageParts;
|
|
225
|
+
|
|
226
|
+
inputItems.push({
|
|
227
|
+
type: 'message',
|
|
228
|
+
role: 'user',
|
|
229
|
+
content: messageContent
|
|
230
|
+
});
|
|
231
|
+
messageParts = [];
|
|
232
|
+
};
|
|
233
|
+
|
|
234
234
|
if (typeof content === 'string') {
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
textParts.push(block.text);
|
|
240
|
-
} else if (block.type === 'tool_result') {
|
|
241
|
-
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
235
|
+
messageParts.push({ type: 'input_text', text: content });
|
|
236
|
+
flushMessageParts();
|
|
237
|
+
return inputItems;
|
|
238
|
+
}
|
|
242
239
|
|
|
243
|
-
|
|
244
|
-
|
|
240
|
+
if (!Array.isArray(content)) {
|
|
241
|
+
return inputItems;
|
|
242
|
+
}
|
|
245
243
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
244
|
+
for (const block of content) {
|
|
245
|
+
if (!block || typeof block !== 'object') continue;
|
|
246
|
+
|
|
247
|
+
if (block.type === 'text') {
|
|
248
|
+
messageParts.push({ type: 'input_text', text: block.text || '' });
|
|
249
|
+
} else if (block.type === 'image') {
|
|
250
|
+
const image = convertAnthropicImageToResponsesInputImage(block);
|
|
251
|
+
if (image) messageParts.push(image);
|
|
252
|
+
} else if (block.type === 'tool_result') {
|
|
253
|
+
flushMessageParts();
|
|
254
|
+
|
|
255
|
+
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
256
|
+
const callId = toOpenAIToolId(block.tool_use_id);
|
|
257
|
+
|
|
258
|
+
inputItems.push({
|
|
259
|
+
type: 'function_call_output',
|
|
260
|
+
call_id: callId,
|
|
261
|
+
output: block.is_error ? prefixToolErrorOutput(outputContent) : outputContent
|
|
262
|
+
});
|
|
252
263
|
}
|
|
253
264
|
}
|
|
254
|
-
|
|
255
|
-
|
|
265
|
+
|
|
266
|
+
flushMessageParts();
|
|
267
|
+
return inputItems;
|
|
256
268
|
}
|
|
257
269
|
|
|
258
270
|
/**
|
|
@@ -310,19 +322,36 @@ function convertAssistantContentToOpenAI(content) {
|
|
|
310
322
|
}
|
|
311
323
|
|
|
312
324
|
/**
|
|
313
|
-
* Convert Anthropic tools to OpenAI
|
|
325
|
+
* Convert Anthropic tools to OpenAI Responses API tool format.
|
|
314
326
|
*/
|
|
315
327
|
function convertAnthropicToolsToOpenAI(tools) {
|
|
316
328
|
if (!Array.isArray(tools)) {
|
|
317
329
|
return [];
|
|
318
330
|
}
|
|
319
331
|
|
|
320
|
-
return tools.map(tool =>
|
|
321
|
-
type
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
332
|
+
return tools.map(tool => {
|
|
333
|
+
if (tool.type === 'web_search_20250305' && tool.name === 'web_search') {
|
|
334
|
+
const webSearchTool = {
|
|
335
|
+
type: 'web_search',
|
|
336
|
+
external_web_access: true
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
if (Array.isArray(tool.allowed_domains)) {
|
|
340
|
+
webSearchTool.filters = {
|
|
341
|
+
allowed_domains: tool.allowed_domains
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return webSearchTool;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
return {
|
|
349
|
+
type: 'function',
|
|
350
|
+
name: tool.name,
|
|
351
|
+
description: tool.description || '',
|
|
352
|
+
parameters: sanitizeSchema(tool.input_schema || { type: 'object' })
|
|
353
|
+
};
|
|
354
|
+
});
|
|
326
355
|
}
|
|
327
356
|
|
|
328
357
|
function sanitizeAnthropicToolInput(name, input) {
|
package/src/index.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { createRequire } from 'module';
|
|
7
7
|
import { getDeploymentMode, getLocalBaseUrl, getServerHost } from './deployment.js';
|
|
8
|
+
import { getAdminPath } from './admin-path.js';
|
|
8
9
|
import { startServer } from './server.js';
|
|
9
10
|
import { logger } from './utils/logger.js';
|
|
10
11
|
import { getStatus, ACCOUNTS_FILE } from './account-manager.js';
|
|
@@ -21,6 +22,14 @@ try {
|
|
|
21
22
|
}
|
|
22
23
|
const HOST = getServerHost();
|
|
23
24
|
const BASE_URL = getLocalBaseUrl(PORT);
|
|
25
|
+
let ADMIN_PATH;
|
|
26
|
+
try {
|
|
27
|
+
ADMIN_PATH = getAdminPath();
|
|
28
|
+
} catch (error) {
|
|
29
|
+
console.error(error.message);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
const ADMIN_URL = `${BASE_URL}${ADMIN_PATH}`;
|
|
24
33
|
const BANNER_WIDTH = 62;
|
|
25
34
|
|
|
26
35
|
if (DEPLOYMENT_MODE === 'public' && !process.env.PROXY_ADMIN_KEY) {
|
|
@@ -45,10 +54,10 @@ console.log(`
|
|
|
45
54
|
╠══════════════════════════════════════════════════════════════╣
|
|
46
55
|
${bannerLine('Host:', HOST)}
|
|
47
56
|
${bannerLine('Server:', BASE_URL)}
|
|
48
|
-
${bannerLine('WebUI:',
|
|
57
|
+
${bannerLine('WebUI:', ADMIN_URL)}
|
|
49
58
|
${bannerLine('Health:', `${BASE_URL}/health`)}
|
|
50
|
-
${bannerLine('Accounts:', `${
|
|
51
|
-
${bannerLine('Logs:', `${
|
|
59
|
+
${bannerLine('Accounts:', `${ADMIN_URL}/accounts`)}
|
|
60
|
+
${bannerLine('Logs:', `${ADMIN_URL}/api/logs/stream`)}
|
|
52
61
|
╠══════════════════════════════════════════════════════════════╣
|
|
53
62
|
║ Features: ║
|
|
54
63
|
║ ✓ Native tool calling support ║
|
|
@@ -66,7 +75,7 @@ const status = getStatus();
|
|
|
66
75
|
logger.info(`Accounts: ${status.total} total, Active: ${status.active || 'None'}`);
|
|
67
76
|
|
|
68
77
|
if (status.total === 0) {
|
|
69
|
-
logger.warn(`No accounts configured. Open ${
|
|
78
|
+
logger.warn(`No accounts configured. Open ${ADMIN_URL} to add one.`);
|
|
70
79
|
}
|
|
71
80
|
|
|
72
81
|
// Expose config path in logs for convenience
|
package/src/middleware/auth.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import crypto from 'crypto';
|
|
2
2
|
import { isPublicDeployment } from '../deployment.js';
|
|
3
|
-
import { getServerSettings } from '../server-settings.js';
|
|
3
|
+
import { getServerSettings, DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD } from '../server-settings.js';
|
|
4
|
+
import { getClientKeyQuota } from '../client-key-usage.js';
|
|
4
5
|
|
|
5
6
|
function timingSafeEqualString(a, b) {
|
|
6
7
|
const left = Buffer.from(String(a));
|
|
@@ -44,10 +45,8 @@ function sendUnauthorized(req, res) {
|
|
|
44
45
|
return res.status(401).json({ success: false, error: 'Unauthorized' });
|
|
45
46
|
}
|
|
46
47
|
|
|
47
|
-
function
|
|
48
|
-
return
|
|
49
|
-
expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey)
|
|
50
|
-
));
|
|
48
|
+
function matchesKey(requestKey, expectedKey) {
|
|
49
|
+
return expectedKey && requestKey && timingSafeEqualString(requestKey, expectedKey);
|
|
51
50
|
}
|
|
52
51
|
|
|
53
52
|
function requireKeys(getExpectedKeys) {
|
|
@@ -58,7 +57,7 @@ function requireKeys(getExpectedKeys) {
|
|
|
58
57
|
|
|
59
58
|
const expectedKeys = getExpectedKeys();
|
|
60
59
|
const requestKey = getRequestApiKey(req);
|
|
61
|
-
if (!
|
|
60
|
+
if (!expectedKeys.some((expectedKey) => matchesKey(requestKey, expectedKey))) {
|
|
62
61
|
return sendUnauthorized(req, res);
|
|
63
62
|
}
|
|
64
63
|
|
|
@@ -66,14 +65,50 @@ function requireKeys(getExpectedKeys) {
|
|
|
66
65
|
};
|
|
67
66
|
}
|
|
68
67
|
|
|
68
|
+
function sendQuotaExceeded(res, quota) {
|
|
69
|
+
return res.status(429).json({
|
|
70
|
+
type: 'error',
|
|
71
|
+
error: {
|
|
72
|
+
type: 'rate_limit_error',
|
|
73
|
+
message: `Weekly client key quota exhausted. Resets at ${quota.nextPeriodStart}`
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function findClientKey(requestKey) {
|
|
79
|
+
return getServerSettings().clientApiKeys.find(({ key }) => matchesKey(requestKey, key));
|
|
80
|
+
}
|
|
81
|
+
|
|
69
82
|
const getAdminKeys = () => [process.env.PROXY_ADMIN_KEY].filter(Boolean);
|
|
70
|
-
const getClientKeys = () => [
|
|
71
|
-
...getServerSettings().clientApiKeys.map(({ key }) => key),
|
|
72
|
-
process.env.PROXY_CLIENT_KEY
|
|
73
|
-
].filter(Boolean);
|
|
74
83
|
|
|
75
84
|
export const requireAdminAuth = requireKeys(getAdminKeys);
|
|
76
|
-
|
|
85
|
+
|
|
86
|
+
export function requireClientAuth(req, res, next) {
|
|
87
|
+
const requestKey = getRequestApiKey(req);
|
|
88
|
+
const clientKey = findClientKey(requestKey);
|
|
89
|
+
if (isPublicDeployment() && !clientKey) {
|
|
90
|
+
return sendUnauthorized(req, res);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (!clientKey) {
|
|
94
|
+
return next();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const quota = getClientKeyQuota(
|
|
98
|
+
clientKey.id,
|
|
99
|
+
clientKey.weeklyLimitUsd ?? DEFAULT_CLIENT_KEY_WEEKLY_LIMIT_USD
|
|
100
|
+
);
|
|
101
|
+
const isModelRequest = req.method === 'POST' && (
|
|
102
|
+
req.path === '/v1/messages' || req.path === '/v1/chat/completions'
|
|
103
|
+
);
|
|
104
|
+
if (isModelRequest && quota.remainingMicrousd <= 0) {
|
|
105
|
+
return sendQuotaExceeded(res, quota);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
req.clientApiKey = { id: clientKey.id, name: clientKey.name };
|
|
109
|
+
req.clientApiKeyQuota = quota;
|
|
110
|
+
return next();
|
|
111
|
+
}
|
|
77
112
|
|
|
78
113
|
export { isPublicDeployment };
|
|
79
114
|
|
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
getActiveAccount,
|
|
9
9
|
refreshAccountToken,
|
|
10
10
|
isTokenExpiredOrExpiringSoon,
|
|
11
|
+
isAccountExpired,
|
|
11
12
|
loadAccounts
|
|
12
13
|
} from '../account-manager.js';
|
|
13
14
|
import { logger } from '../utils/logger.js';
|
|
@@ -26,6 +27,11 @@ export async function getCredentialsOrError() {
|
|
|
26
27
|
return null;
|
|
27
28
|
}
|
|
28
29
|
|
|
30
|
+
if (isAccountExpired(account)) {
|
|
31
|
+
logger.info(`Account ${account.email} has expired`);
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
29
35
|
if (!account.accessToken || !account.accountId) {
|
|
30
36
|
logger.info(`Account ${account.email} missing token or accountId`);
|
|
31
37
|
return null;
|
|
@@ -41,8 +47,8 @@ export async function getCredentialsOrError() {
|
|
|
41
47
|
}
|
|
42
48
|
|
|
43
49
|
const refreshedAccount = getActiveAccount();
|
|
44
|
-
if (!refreshedAccount) {
|
|
45
|
-
logger.error('Failed to get refreshed account');
|
|
50
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) {
|
|
51
|
+
logger.error('Failed to get refreshed active account');
|
|
46
52
|
return null;
|
|
47
53
|
}
|
|
48
54
|
|
|
@@ -74,6 +80,10 @@ export async function getCredentialsForAccount(email) {
|
|
|
74
80
|
return null;
|
|
75
81
|
}
|
|
76
82
|
|
|
83
|
+
if (isAccountExpired(account)) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
77
87
|
if (!account.accessToken || !account.accountId) {
|
|
78
88
|
return null;
|
|
79
89
|
}
|
|
@@ -85,7 +95,7 @@ export async function getCredentialsForAccount(email) {
|
|
|
85
95
|
}
|
|
86
96
|
const refreshedData = loadAccounts();
|
|
87
97
|
const refreshedAccount = refreshedData.accounts.find(a => a.email === email);
|
|
88
|
-
if (!refreshedAccount) return null;
|
|
98
|
+
if (!refreshedAccount || isAccountExpired(refreshedAccount)) return null;
|
|
89
99
|
|
|
90
100
|
return {
|
|
91
101
|
accessToken: refreshedAccount.accessToken,
|