claude-codex-proxy 1.0.5-beta.3 → 1.0.5-beta.31
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 +195 -116
- package/public/login.html +32 -32
- package/public/views/accounts-modals.html +90 -29
- 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 +86 -13
- 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
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
import { CONFIG_DIR } from './account-manager.js';
|
|
5
|
+
|
|
6
|
+
const USAGE_FILE = join(CONFIG_DIR, 'client-key-usage.json');
|
|
7
|
+
export const MICRO_USD_PER_USD = 1_000_000;
|
|
8
|
+
|
|
9
|
+
function loadUsage(usageFile = USAGE_FILE) {
|
|
10
|
+
if (!existsSync(usageFile)) return {};
|
|
11
|
+
|
|
12
|
+
try {
|
|
13
|
+
const data = JSON.parse(readFileSync(usageFile, 'utf8'));
|
|
14
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
15
|
+
throw new Error('usage file must contain a JSON object');
|
|
16
|
+
}
|
|
17
|
+
return data;
|
|
18
|
+
} catch (error) {
|
|
19
|
+
throw new Error(`[ClientKeyUsage] Failed to read ${usageFile}: ${error.message}`, { cause: error });
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function saveUsage(usage, usageFile = USAGE_FILE) {
|
|
24
|
+
const usageDirectory = dirname(usageFile);
|
|
25
|
+
if (!existsSync(usageDirectory)) {
|
|
26
|
+
mkdirSync(usageDirectory, { recursive: true, mode: 0o700 });
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const tempFile = `${usageFile}.${process.pid}.${randomUUID()}.tmp`;
|
|
30
|
+
try {
|
|
31
|
+
writeFileSync(tempFile, JSON.stringify(usage, null, 2), { mode: 0o600 });
|
|
32
|
+
renameSync(tempFile, usageFile);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
try {
|
|
35
|
+
rmSync(tempFile, { force: true });
|
|
36
|
+
} catch {
|
|
37
|
+
// Preserve the original write error.
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Returns the current weekly period start in the server's local time zone.
|
|
45
|
+
* A period begins at Monday 08:00 and ends at the following Monday 08:00.
|
|
46
|
+
*/
|
|
47
|
+
export function getCurrentPeriodStart(now = new Date()) {
|
|
48
|
+
const periodStart = new Date(now);
|
|
49
|
+
const daysSinceMonday = (periodStart.getDay() + 6) % 7;
|
|
50
|
+
periodStart.setDate(periodStart.getDate() - daysSinceMonday);
|
|
51
|
+
periodStart.setHours(8, 0, 0, 0);
|
|
52
|
+
|
|
53
|
+
if (now < periodStart) {
|
|
54
|
+
periodStart.setDate(periodStart.getDate() - 7);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return periodStart.toISOString();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function getNextPeriodStart(now = new Date()) {
|
|
61
|
+
const nextPeriodStart = new Date(getCurrentPeriodStart(now));
|
|
62
|
+
nextPeriodStart.setDate(nextPeriodStart.getDate() + 7);
|
|
63
|
+
return nextPeriodStart.toISOString();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const FIVE_HOURS_MS = 5 * 60 * 60 * 1000;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Returns the start of the current globally aligned five-hour window.
|
|
70
|
+
* Boundaries occur every five hours from the Unix epoch and always fall on
|
|
71
|
+
* an exact hour.
|
|
72
|
+
*/
|
|
73
|
+
export function getCurrentFiveHourPeriodStart(now = new Date()) {
|
|
74
|
+
return new Date(Math.floor(now.getTime() / FIVE_HOURS_MS) * FIVE_HOURS_MS).toISOString();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function getNextFiveHourPeriodStart(now = new Date()) {
|
|
78
|
+
return new Date(new Date(getCurrentFiveHourPeriodStart(now)).getTime() + FIVE_HOURS_MS).toISOString();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function usdToMicrousd(usd) {
|
|
82
|
+
return Math.round(Number(usd) * MICRO_USD_PER_USD);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function microusdToUsd(microusd) {
|
|
86
|
+
return Number(microusd) / MICRO_USD_PER_USD;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Returns a key's usage after lazily resetting it for a new weekly period.
|
|
91
|
+
*/
|
|
92
|
+
export function getClientKeyUsage(keyId, now = new Date()) {
|
|
93
|
+
const usage = loadUsage();
|
|
94
|
+
const periodStart = getCurrentPeriodStart(now);
|
|
95
|
+
const fiveHourPeriodStart = getCurrentFiveHourPeriodStart(now);
|
|
96
|
+
const entry = usage[keyId];
|
|
97
|
+
const consumedMicrousd = entry?.periodStart === periodStart && Number.isSafeInteger(entry.consumedMicrousd)
|
|
98
|
+
? Math.max(0, entry.consumedMicrousd)
|
|
99
|
+
: 0;
|
|
100
|
+
const fiveHourConsumedMicrousd = entry?.fiveHourPeriodStart === fiveHourPeriodStart
|
|
101
|
+
&& Number.isSafeInteger(entry.fiveHourConsumedMicrousd)
|
|
102
|
+
? Math.max(0, entry.fiveHourConsumedMicrousd)
|
|
103
|
+
: 0;
|
|
104
|
+
|
|
105
|
+
if (!entry
|
|
106
|
+
|| entry.periodStart !== periodStart
|
|
107
|
+
|| entry.consumedMicrousd !== consumedMicrousd
|
|
108
|
+
|| entry.fiveHourPeriodStart !== fiveHourPeriodStart
|
|
109
|
+
|| entry.fiveHourConsumedMicrousd !== fiveHourConsumedMicrousd) {
|
|
110
|
+
usage[keyId] = {
|
|
111
|
+
periodStart,
|
|
112
|
+
consumedMicrousd,
|
|
113
|
+
fiveHourPeriodStart,
|
|
114
|
+
fiveHourConsumedMicrousd
|
|
115
|
+
};
|
|
116
|
+
saveUsage(usage);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
periodStart,
|
|
121
|
+
nextPeriodStart: getNextPeriodStart(now),
|
|
122
|
+
consumedMicrousd,
|
|
123
|
+
fiveHourPeriodStart,
|
|
124
|
+
nextFiveHourPeriodStart: getNextFiveHourPeriodStart(now),
|
|
125
|
+
fiveHourConsumedMicrousd
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Records actual USD consumption for a client key. Call this only after an
|
|
131
|
+
* upstream response provides a verified per-request charge.
|
|
132
|
+
*/
|
|
133
|
+
export function recordClientKeyUsage(keyId, consumedMicrousd, now = new Date()) {
|
|
134
|
+
if (!Number.isSafeInteger(consumedMicrousd) || consumedMicrousd < 0) {
|
|
135
|
+
throw new TypeError('consumedMicrousd must be a non-negative safe integer');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const current = getClientKeyUsage(keyId, now);
|
|
139
|
+
const usage = loadUsage();
|
|
140
|
+
usage[keyId] = {
|
|
141
|
+
periodStart: current.periodStart,
|
|
142
|
+
consumedMicrousd: current.consumedMicrousd + consumedMicrousd,
|
|
143
|
+
fiveHourPeriodStart: current.fiveHourPeriodStart,
|
|
144
|
+
fiveHourConsumedMicrousd: current.fiveHourConsumedMicrousd + consumedMicrousd
|
|
145
|
+
};
|
|
146
|
+
saveUsage(usage);
|
|
147
|
+
return usage[keyId];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export function deleteClientKeyUsage(keyId) {
|
|
151
|
+
const usage = loadUsage();
|
|
152
|
+
if (!(keyId in usage)) return;
|
|
153
|
+
delete usage[keyId];
|
|
154
|
+
saveUsage(usage);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Returns a key's current quota summary without charging any request.
|
|
159
|
+
*/
|
|
160
|
+
export function getClientKeyQuota(keyId, weeklyLimitUsd, fiveHourLimit = {}, now = new Date()) {
|
|
161
|
+
// Preserve the previous third-argument `now` form for internal callers and tests.
|
|
162
|
+
if (fiveHourLimit instanceof Date) {
|
|
163
|
+
now = fiveHourLimit;
|
|
164
|
+
fiveHourLimit = {};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const usage = getClientKeyUsage(keyId, now);
|
|
168
|
+
const weeklyLimitMicrousd = usdToMicrousd(weeklyLimitUsd);
|
|
169
|
+
const remainingMicrousd = Math.max(0, weeklyLimitMicrousd - usage.consumedMicrousd);
|
|
170
|
+
const fiveHourLimitEnabled = fiveHourLimit.enabled === true;
|
|
171
|
+
const fiveHourLimitMicrousd = usdToMicrousd(fiveHourLimit.usd ?? 0);
|
|
172
|
+
const fiveHourRemainingMicrousd = Math.max(
|
|
173
|
+
0,
|
|
174
|
+
fiveHourLimitMicrousd - usage.fiveHourConsumedMicrousd
|
|
175
|
+
);
|
|
176
|
+
|
|
177
|
+
return {
|
|
178
|
+
...usage,
|
|
179
|
+
weeklyLimitMicrousd,
|
|
180
|
+
remainingMicrousd,
|
|
181
|
+
weeklyLimitUsd: microusdToUsd(weeklyLimitMicrousd),
|
|
182
|
+
consumedUsd: microusdToUsd(usage.consumedMicrousd),
|
|
183
|
+
remainingUsd: microusdToUsd(remainingMicrousd),
|
|
184
|
+
fiveHourLimitEnabled,
|
|
185
|
+
fiveHourLimitMicrousd,
|
|
186
|
+
fiveHourRemainingMicrousd,
|
|
187
|
+
fiveHourLimitUsd: microusdToUsd(fiveHourLimitMicrousd),
|
|
188
|
+
fiveHourConsumedUsd: microusdToUsd(usage.fiveHourConsumedMicrousd),
|
|
189
|
+
fiveHourRemainingUsd: microusdToUsd(fiveHourRemainingMicrousd)
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export { USAGE_FILE, loadUsage, saveUsage };
|
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,18 +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
17
|
|
|
18
|
-
function shouldLogRawProxyPayloads() {
|
|
19
|
-
return getServerSettings().logRawProxyPayloads === true;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
18
|
function createAnthropicUsage(upstreamUsage = {}) {
|
|
23
19
|
const usage = {
|
|
24
20
|
input_tokens: upstreamUsage.input_tokens || 0,
|
|
@@ -30,6 +26,10 @@ function createAnthropicUsage(upstreamUsage = {}) {
|
|
|
30
26
|
value: upstreamUsage.cache_read_input_tokens || upstreamUsage.input_tokens_details?.cached_tokens || 0,
|
|
31
27
|
enumerable: false
|
|
32
28
|
});
|
|
29
|
+
Object.defineProperty(usage, 'upstreamCacheWriteInputTokens', {
|
|
30
|
+
value: upstreamUsage.input_tokens_details?.cache_write_tokens || 0,
|
|
31
|
+
enumerable: false
|
|
32
|
+
});
|
|
33
33
|
return usage;
|
|
34
34
|
}
|
|
35
35
|
|
|
@@ -134,9 +134,7 @@ async function createResponsesAPIStreamResponse(anthropicRequest, accessToken, a
|
|
|
134
134
|
if (response.ok) return response;
|
|
135
135
|
|
|
136
136
|
const errorText = await response.text();
|
|
137
|
-
|
|
138
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
139
|
-
}
|
|
137
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
140
138
|
|
|
141
139
|
if (response.status === 401) {
|
|
142
140
|
if (accountRotator && currentEmail) {
|
|
@@ -202,9 +200,7 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
202
200
|
|
|
203
201
|
if (!response.ok) {
|
|
204
202
|
const errorText = await response.text();
|
|
205
|
-
|
|
206
|
-
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
207
|
-
}
|
|
203
|
+
logger.info('[OpenAI Error]', { status: response.status, body: errorText });
|
|
208
204
|
|
|
209
205
|
if (response.status === 401) {
|
|
210
206
|
throw createHTTPError('AUTH_EXPIRED: Token expired or revoked. Please re-authenticate.', 401, 'authentication_error', response.status);
|
|
@@ -220,6 +216,10 @@ export async function sendMessage(anthropicRequest, accessToken, accountId, cont
|
|
|
220
216
|
throw error;
|
|
221
217
|
}
|
|
222
218
|
|
|
219
|
+
if (response.status === 400) {
|
|
220
|
+
throw createHTTPError(`INVALID_REQUEST: ${errorText}`, 400, 'invalid_request_error', response.status);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
223
|
throw createUpstreamHTTPError(response, errorText);
|
|
224
224
|
}
|
|
225
225
|
|
package/src/format-converter.js
CHANGED
|
@@ -8,6 +8,7 @@ import { cleanCacheControl, processAssistantContent, hasUnsignedThinkingBlocks }
|
|
|
8
8
|
import { getCachedSignature, cacheSignature, cacheThinkingSignature, SIGNATURE_CONSTANTS } from './signature-cache.js';
|
|
9
9
|
|
|
10
10
|
const { MIN_SIGNATURE_LENGTH } = SIGNATURE_CONSTANTS;
|
|
11
|
+
const SUPPORTED_REASONING_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
11
12
|
|
|
12
13
|
/**
|
|
13
14
|
* Convert Anthropic tool ID to OpenAI fc_ format
|
|
@@ -146,11 +147,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
146
147
|
const instructions = extractSystemPrompt(system);
|
|
147
148
|
|
|
148
149
|
const request = {
|
|
149
|
-
model: model
|
|
150
|
+
model: model,
|
|
150
151
|
input: convertMessagesToInput(cleanedMessages),
|
|
151
152
|
tools: tools ? convertAnthropicToolsToOpenAI(tools) : [],
|
|
152
|
-
tool_choice:
|
|
153
|
-
parallel_tool_calls: true,
|
|
153
|
+
tool_choice: 'auto',
|
|
154
|
+
parallel_tool_calls: tool_choice?.disable_parallel_tool_use !== true,
|
|
154
155
|
store: false,
|
|
155
156
|
stream: true,
|
|
156
157
|
include: []
|
|
@@ -162,6 +163,11 @@ export function convertAnthropicToResponsesAPI(anthropicRequest) {
|
|
|
162
163
|
request.instructions = '';
|
|
163
164
|
}
|
|
164
165
|
|
|
166
|
+
const effort = anthropicRequest.output_config?.effort;
|
|
167
|
+
if (SUPPORTED_REASONING_EFFORTS.has(effort)) {
|
|
168
|
+
request.reasoning = { effort };
|
|
169
|
+
}
|
|
170
|
+
|
|
165
171
|
return request;
|
|
166
172
|
}
|
|
167
173
|
|
|
@@ -177,23 +183,7 @@ function convertMessagesToInput(messages) {
|
|
|
177
183
|
|
|
178
184
|
for (const msg of messages) {
|
|
179
185
|
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
|
-
}
|
|
186
|
+
input.push(...convertUserContent(msg.content));
|
|
197
187
|
} else if (msg.role === 'assistant') {
|
|
198
188
|
// Process assistant content: restore signatures, reorder, sanitize
|
|
199
189
|
let msgContent = msg.content;
|
|
@@ -225,34 +215,62 @@ function convertMessagesToInput(messages) {
|
|
|
225
215
|
}
|
|
226
216
|
|
|
227
217
|
/**
|
|
228
|
-
* Convert user content
|
|
218
|
+
* Convert Anthropic user content while preserving block order.
|
|
229
219
|
*/
|
|
230
220
|
function convertUserContent(content) {
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
221
|
+
const inputItems = [];
|
|
222
|
+
let messageParts = [];
|
|
223
|
+
|
|
224
|
+
const flushMessageParts = () => {
|
|
225
|
+
if (messageParts.length === 0) return;
|
|
226
|
+
|
|
227
|
+
const messageContent =
|
|
228
|
+
messageParts.length === 1 && messageParts[0].type === 'input_text'
|
|
229
|
+
? messageParts[0].text
|
|
230
|
+
: messageParts;
|
|
231
|
+
|
|
232
|
+
inputItems.push({
|
|
233
|
+
type: 'message',
|
|
234
|
+
role: 'user',
|
|
235
|
+
content: messageContent
|
|
236
|
+
});
|
|
237
|
+
messageParts = [];
|
|
238
|
+
};
|
|
239
|
+
|
|
234
240
|
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);
|
|
241
|
+
messageParts.push({ type: 'input_text', text: content });
|
|
242
|
+
flushMessageParts();
|
|
243
|
+
return inputItems;
|
|
244
|
+
}
|
|
242
245
|
|
|
243
|
-
|
|
244
|
-
|
|
246
|
+
if (!Array.isArray(content)) {
|
|
247
|
+
return inputItems;
|
|
248
|
+
}
|
|
245
249
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
250
|
+
for (const block of content) {
|
|
251
|
+
if (!block || typeof block !== 'object') continue;
|
|
252
|
+
|
|
253
|
+
if (block.type === 'text') {
|
|
254
|
+
messageParts.push({ type: 'input_text', text: block.text || '' });
|
|
255
|
+
} else if (block.type === 'image') {
|
|
256
|
+
const image = convertAnthropicImageToResponsesInputImage(block);
|
|
257
|
+
if (image) messageParts.push(image);
|
|
258
|
+
} else if (block.type === 'tool_result') {
|
|
259
|
+
flushMessageParts();
|
|
260
|
+
|
|
261
|
+
const outputContent = convertToolResultContentToResponsesOutput(block);
|
|
262
|
+
const callId = toOpenAIToolId(block.tool_use_id);
|
|
263
|
+
|
|
264
|
+
inputItems.push({
|
|
265
|
+
type: 'function_call_output',
|
|
266
|
+
call_id: callId,
|
|
267
|
+
output: block.is_error ? prefixToolErrorOutput(outputContent) : outputContent
|
|
268
|
+
});
|
|
252
269
|
}
|
|
253
270
|
}
|
|
254
|
-
|
|
255
|
-
|
|
271
|
+
|
|
272
|
+
flushMessageParts();
|
|
273
|
+
return inputItems;
|
|
256
274
|
}
|
|
257
275
|
|
|
258
276
|
/**
|
|
@@ -310,19 +328,36 @@ function convertAssistantContentToOpenAI(content) {
|
|
|
310
328
|
}
|
|
311
329
|
|
|
312
330
|
/**
|
|
313
|
-
* Convert Anthropic tools to OpenAI
|
|
331
|
+
* Convert Anthropic tools to OpenAI Responses API tool format.
|
|
314
332
|
*/
|
|
315
333
|
function convertAnthropicToolsToOpenAI(tools) {
|
|
316
334
|
if (!Array.isArray(tools)) {
|
|
317
335
|
return [];
|
|
318
336
|
}
|
|
319
337
|
|
|
320
|
-
return tools.map(tool =>
|
|
321
|
-
type
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
338
|
+
return tools.map(tool => {
|
|
339
|
+
if (tool.type === 'web_search_20250305' && tool.name === 'web_search') {
|
|
340
|
+
const webSearchTool = {
|
|
341
|
+
type: 'web_search',
|
|
342
|
+
external_web_access: true
|
|
343
|
+
};
|
|
344
|
+
|
|
345
|
+
if (Array.isArray(tool.allowed_domains)) {
|
|
346
|
+
webSearchTool.filters = {
|
|
347
|
+
allowed_domains: tool.allowed_domains
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
return webSearchTool;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
type: 'function',
|
|
356
|
+
name: tool.name,
|
|
357
|
+
description: tool.description || '',
|
|
358
|
+
parameters: sanitizeSchema(tool.input_schema || { type: 'object' })
|
|
359
|
+
};
|
|
360
|
+
});
|
|
326
361
|
}
|
|
327
362
|
|
|
328
363
|
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
|