codexmate 0.0.40 → 0.0.41
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 +168 -156
- package/README.zh.md +168 -156
- package/cli/agents-files.js +230 -230
- package/cli/analytics-export-args.js +68 -68
- package/cli/archive-helpers.js +453 -453
- package/cli/auth-profiles.js +375 -375
- package/cli/builtin-proxy.js +2144 -2144
- package/cli/claude-proxy.js +1022 -1022
- package/cli/config-bootstrap.js +407 -407
- package/cli/config-health.js +454 -454
- package/cli/doctor-core.js +903 -903
- package/cli/import-skills-url.js +356 -356
- package/cli/local-bridge.js +556 -556
- package/cli/openai-bridge.js +1984 -1984
- package/cli/openclaw-config.js +629 -629
- package/cli/session-convert-args.js +69 -69
- package/cli/session-convert-io.js +82 -82
- package/cli/session-convert.js +150 -150
- package/cli/session-usage.concurrent.js +28 -28
- package/cli/session-usage.js +304 -304
- package/cli/session-usage.models.js +176 -176
- package/cli/skills.js +1141 -1141
- package/cli/update.js +171 -171
- package/cli/zip-commands.js +510 -510
- package/cli.js +16458 -16341
- package/lib/automation.js +404 -404
- package/lib/cli-file-utils.js +151 -151
- package/lib/cli-models-utils.js +440 -440
- package/lib/cli-network-utils.js +190 -190
- package/lib/cli-path-utils.js +85 -85
- package/lib/cli-session-utils.js +121 -121
- package/lib/cli-sessions.js +427 -427
- package/lib/cli-utils.js +155 -155
- package/lib/cli-webhook.js +154 -154
- package/lib/download-artifacts.js +92 -92
- package/lib/mcp-stdio.js +453 -453
- package/lib/task-orchestrator.js +869 -869
- package/lib/text-diff.js +303 -303
- package/lib/win-tray.js +119 -119
- package/lib/workflow-engine.js +340 -340
- package/package.json +77 -77
- package/plugins/README.md +20 -20
- package/plugins/README.zh-CN.md +20 -20
- package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
- package/plugins/prompt-templates/computed.mjs +311 -311
- package/plugins/prompt-templates/index.mjs +8 -8
- package/plugins/prompt-templates/manifest.mjs +18 -18
- package/plugins/prompt-templates/methods.mjs +553 -553
- package/plugins/prompt-templates/overview.mjs +91 -91
- package/plugins/prompt-templates/ownership.mjs +19 -19
- package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
- package/plugins/prompt-templates/storage.mjs +64 -64
- package/plugins/registry.mjs +16 -16
- package/web-ui/app.js +695 -695
- package/web-ui/index.html +37 -37
- package/web-ui/logic.agents-diff.mjs +386 -386
- package/web-ui/logic.claude.mjs +172 -172
- package/web-ui/logic.codex.mjs +69 -69
- package/web-ui/logic.mjs +5 -5
- package/web-ui/logic.runtime.mjs +128 -128
- package/web-ui/logic.session-convert.mjs +70 -70
- package/web-ui/logic.sessions.mjs +782 -782
- package/web-ui/modules/api.mjs +90 -90
- package/web-ui/modules/app.computed.dashboard.mjs +252 -252
- package/web-ui/modules/app.computed.index.mjs +17 -17
- package/web-ui/modules/app.computed.main-tabs.mjs +214 -214
- package/web-ui/modules/app.computed.session.mjs +876 -876
- package/web-ui/modules/app.constants.mjs +15 -15
- package/web-ui/modules/app.methods.agents.mjs +651 -651
- package/web-ui/modules/app.methods.claude-config.mjs +412 -412
- package/web-ui/modules/app.methods.codex-config.mjs +869 -869
- package/web-ui/modules/app.methods.index.mjs +96 -96
- package/web-ui/modules/app.methods.install.mjs +205 -205
- package/web-ui/modules/app.methods.navigation.mjs +804 -804
- package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
- package/web-ui/modules/app.methods.openclaw-editing.mjs +420 -420
- package/web-ui/modules/app.methods.openclaw-persist.mjs +375 -375
- package/web-ui/modules/app.methods.providers.mjs +601 -601
- package/web-ui/modules/app.methods.runtime.mjs +420 -420
- package/web-ui/modules/app.methods.session-actions.mjs +591 -591
- package/web-ui/modules/app.methods.session-browser.mjs +1018 -1018
- package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
- package/web-ui/modules/app.methods.session-trash.mjs +468 -468
- package/web-ui/modules/app.methods.startup-claude.mjs +554 -554
- package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
- package/web-ui/modules/app.methods.tool-config-permissions.mjs +87 -87
- package/web-ui/modules/app.methods.webhook.mjs +87 -87
- package/web-ui/modules/config-mode.computed.mjs +124 -124
- package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
- package/web-ui/modules/i18n/locales/en.mjs +1140 -1140
- package/web-ui/modules/i18n/locales/ja.mjs +1130 -1130
- package/web-ui/modules/i18n/locales/vi.mjs +239 -239
- package/web-ui/modules/i18n/locales/zh.mjs +1143 -1143
- package/web-ui/modules/i18n.dict.mjs +14 -14
- package/web-ui/modules/i18n.mjs +111 -111
- package/web-ui/modules/plugins.computed.mjs +3 -3
- package/web-ui/modules/plugins.methods.mjs +3 -3
- package/web-ui/modules/plugins.storage.mjs +11 -11
- package/web-ui/modules/provider-url-display.mjs +17 -17
- package/web-ui/modules/sessions-filters-url.mjs +138 -138
- package/web-ui/modules/skills.computed.mjs +107 -107
- package/web-ui/modules/skills.methods.mjs +513 -513
- package/web-ui/partials/index/layout-footer.html +13 -13
- package/web-ui/partials/index/layout-header.html +478 -478
- package/web-ui/partials/index/modal-config-template-agents.html +185 -185
- package/web-ui/partials/index/modal-confirm-toast.html +32 -32
- package/web-ui/partials/index/modal-health-check.html +45 -45
- package/web-ui/partials/index/modal-openclaw-config.html +344 -344
- package/web-ui/partials/index/modal-skills.html +200 -200
- package/web-ui/partials/index/modal-webhook.html +42 -42
- package/web-ui/partials/index/modals-basic.html +263 -263
- package/web-ui/partials/index/panel-config-claude.html +187 -187
- package/web-ui/partials/index/panel-config-codex.html +205 -205
- package/web-ui/partials/index/panel-config-openclaw.html +89 -89
- package/web-ui/partials/index/panel-dashboard.html +171 -171
- package/web-ui/partials/index/panel-docs.html +114 -114
- package/web-ui/partials/index/panel-market.html +104 -104
- package/web-ui/partials/index/panel-orchestration.html +391 -391
- package/web-ui/partials/index/panel-plugins.html +253 -253
- package/web-ui/partials/index/panel-sessions.html +319 -319
- package/web-ui/partials/index/panel-settings.html +181 -181
- package/web-ui/partials/index/panel-trash.html +82 -82
- package/web-ui/partials/index/panel-usage.html +181 -181
- package/web-ui/res/json5.min.js +1 -1
- package/web-ui/res/vue.global.prod.js +13 -13
- package/web-ui/res/vue.runtime.global.prod.js +7 -7
- package/web-ui/res/web-ui-render.precompiled.js +7666 -7666
- package/web-ui/session-helpers.mjs +602 -602
- package/web-ui/source-bundle.cjs +305 -305
- package/web-ui/styles/base-theme.css +291 -291
- package/web-ui/styles/bridge-pool.css +266 -266
- package/web-ui/styles/controls-forms.css +532 -532
- package/web-ui/styles/dashboard.css +438 -438
- package/web-ui/styles/docs-panel.css +245 -245
- package/web-ui/styles/feedback.css +108 -108
- package/web-ui/styles/health-check-dialog.css +144 -144
- package/web-ui/styles/layout-shell.css +711 -711
- package/web-ui/styles/modals-core.css +499 -499
- package/web-ui/styles/navigation-panels.css +399 -399
- package/web-ui/styles/openclaw-structured.css +616 -616
- package/web-ui/styles/plugins-panel.css +564 -564
- package/web-ui/styles/responsive.css +501 -501
- package/web-ui/styles/sessions-list.css +683 -683
- package/web-ui/styles/sessions-preview.css +407 -407
- package/web-ui/styles/sessions-toolbar-trash.css +518 -518
- package/web-ui/styles/sessions-usage.css +849 -849
- package/web-ui/styles/settings-panel.css +419 -419
- package/web-ui/styles/skills-list.css +305 -305
- package/web-ui/styles/skills-market.css +723 -723
- package/web-ui/styles/task-orchestration.css +822 -822
- package/web-ui/styles/titles-cards.css +486 -486
- package/web-ui/styles/trash-panel.css +90 -90
- package/web-ui/styles/webhook.css +115 -115
- package/web-ui/styles.css +24 -24
- package/web-ui.html +17 -17
package/cli/local-bridge.js
CHANGED
|
@@ -1,556 +1,556 @@
|
|
|
1
|
-
const fs = require('fs');
|
|
2
|
-
const http = require('http');
|
|
3
|
-
const https = require('https');
|
|
4
|
-
const { URL } = require('url');
|
|
5
|
-
const {
|
|
6
|
-
readOpenaiBridgeSettings,
|
|
7
|
-
convertResponsesRequestToChatCompletions,
|
|
8
|
-
streamChatCompletionsAsResponsesSse,
|
|
9
|
-
proxyRequestJson,
|
|
10
|
-
ensureResponseMetadata,
|
|
11
|
-
sendResponsesSse,
|
|
12
|
-
extractAuthorizationToken,
|
|
13
|
-
readRequestBody,
|
|
14
|
-
parseJsonOrError,
|
|
15
|
-
extractChatCompletionResult,
|
|
16
|
-
buildResponsesPayloadFromChatResult,
|
|
17
|
-
retryTransientRequest,
|
|
18
|
-
shouldFallbackFromUpstreamResponses,
|
|
19
|
-
isTransientNetworkError,
|
|
20
|
-
isLoopbackAddress
|
|
21
|
-
} = require('./openai-bridge');
|
|
22
|
-
const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
|
|
23
|
-
|
|
24
|
-
const BUILTIN_PROXY_PROVIDER_NAME = 'codexmate-proxy';
|
|
25
|
-
const BUILTIN_LOCAL_PROVIDER_NAME = 'local';
|
|
26
|
-
const CLAUDE_LOCAL_PROVIDER_NAME = 'claude-local';
|
|
27
|
-
const CLAUDE_LOCAL_EXCLUDED_KEY = 'claudeLocalExcluded';
|
|
28
|
-
const CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
29
|
-
const CIRCUIT_BREAKER_COOLDOWN_MS = 5 * 60 * 1000;
|
|
30
|
-
|
|
31
|
-
function buildUpstreamPool(readConfigFn, openaiBridgeFile, excludedProviders) {
|
|
32
|
-
let config;
|
|
33
|
-
try { config = readConfigFn(); } catch (e) { return { error: '读取配置失败' }; }
|
|
34
|
-
const providers = (config && typeof config.model_providers === 'object' && !Array.isArray(config.model_providers))
|
|
35
|
-
? config.model_providers : {};
|
|
36
|
-
const pool = [];
|
|
37
|
-
const excludedSet = new Set(
|
|
38
|
-
(Array.isArray(excludedProviders) ? excludedProviders : [])
|
|
39
|
-
.filter(n => typeof n === 'string' && n.trim())
|
|
40
|
-
.map(n => n.trim().toLowerCase())
|
|
41
|
-
);
|
|
42
|
-
for (const [name, p] of Object.entries(providers)) {
|
|
43
|
-
if (!p || typeof p !== 'object') continue;
|
|
44
|
-
const lower = name.toLowerCase();
|
|
45
|
-
if (lower === BUILTIN_LOCAL_PROVIDER_NAME || lower === BUILTIN_PROXY_PROVIDER_NAME) continue;
|
|
46
|
-
if (excludedSet.has(lower)) continue;
|
|
47
|
-
const bridge = typeof p.codexmate_bridge === 'string' ? p.codexmate_bridge.trim() : '';
|
|
48
|
-
if (bridge === 'local') continue; // avoid loop: local→local
|
|
49
|
-
const baseUrl = typeof p.base_url === 'string' ? p.base_url.trim() : '';
|
|
50
|
-
if (!isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
|
|
51
|
-
const authMethod = typeof p.preferred_auth_method === 'string' ? p.preferred_auth_method.trim() : '';
|
|
52
|
-
pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), authMethod, requiresOpenaiAuth: !!p.requires_openai_auth });
|
|
53
|
-
}
|
|
54
|
-
if (pool.length === 0) return { error: '请先添加上游 provider' };
|
|
55
|
-
return { pool };
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function buildClaudeUpstreamPool(claudeProvidersFile, excludedProviders) {
|
|
59
|
-
let raw;
|
|
60
|
-
try {
|
|
61
|
-
if (!fs.existsSync(claudeProvidersFile)) return { error: '暂无可用上游 provider,请先添加 Claude 提供商' };
|
|
62
|
-
raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
|
|
63
|
-
} catch (e) { return { error: '读取 Claude 提供商配置失败' }; }
|
|
64
|
-
const providers = (raw && typeof raw.providers === 'object' && !Array.isArray(raw.providers))
|
|
65
|
-
? raw.providers : {};
|
|
66
|
-
const pool = [];
|
|
67
|
-
const excludedSet = new Set(
|
|
68
|
-
(Array.isArray(excludedProviders) ? excludedProviders : [])
|
|
69
|
-
.filter(n => typeof n === 'string' && n.trim())
|
|
70
|
-
.map(n => n.trim().toLowerCase())
|
|
71
|
-
);
|
|
72
|
-
for (const [name, p] of Object.entries(providers)) {
|
|
73
|
-
if (!p || typeof p !== 'object') continue;
|
|
74
|
-
if (excludedSet.has(name.toLowerCase())) continue;
|
|
75
|
-
const baseUrl = typeof p.baseUrl === 'string' ? p.baseUrl.trim() : '';
|
|
76
|
-
if (!baseUrl || !isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
|
|
77
|
-
pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), apiKey: typeof p.apiKey === 'string' ? p.apiKey : '', model: typeof p.model === 'string' ? p.model.trim() : '' });
|
|
78
|
-
}
|
|
79
|
-
if (pool.length === 0) return { error: '请先添加可用的 Claude 上游提供商' };
|
|
80
|
-
return { pool };
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function resolveUpstreamAuth(entry, openaiBridgeFile, reqAuthToken) {
|
|
84
|
-
if (entry.authMethod === 'codexmate' || entry.requiresOpenaiAuth) {
|
|
85
|
-
const token = reqAuthToken || '';
|
|
86
|
-
return token ? (token.startsWith('sk-') ? `Bearer ${token}` : `Bearer ${token}`) : '';
|
|
87
|
-
}
|
|
88
|
-
if (entry.authMethod === 'openai-bridge') {
|
|
89
|
-
const settings = readOpenaiBridgeSettings(openaiBridgeFile);
|
|
90
|
-
const upstream = settings.providers ? settings.providers[entry.name] : null;
|
|
91
|
-
if (upstream && upstream.apiKey) {
|
|
92
|
-
return upstream.apiKey.startsWith('Bearer ') ? upstream.apiKey : `Bearer ${upstream.apiKey}`;
|
|
93
|
-
}
|
|
94
|
-
}
|
|
95
|
-
return '';
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
function createLocalBridgeHttpHandler(options = {}) {
|
|
99
|
-
const readConfigFn = options.readConfigFn;
|
|
100
|
-
const openaiBridgeFile = options.openaiBridgeFile;
|
|
101
|
-
const claudeProvidersFile = options.claudeProvidersFile || '';
|
|
102
|
-
const expectedToken = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
|
|
103
|
-
const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
|
|
104
|
-
const httpAgent = options.httpAgent;
|
|
105
|
-
const httpsAgent = options.httpsAgent;
|
|
106
|
-
const maxUpstreamBytes = Number.isFinite(options.maxUpstreamBytes) && options.maxUpstreamBytes > 0
|
|
107
|
-
? Math.floor(options.maxUpstreamBytes)
|
|
108
|
-
: Math.max(16 * 1024 * 1024, maxBodySize > 0 ? maxBodySize * 4 : 0);
|
|
109
|
-
|
|
110
|
-
if (typeof readConfigFn !== 'function') throw new Error('createLocalBridgeHttpHandler 缺少 readConfigFn');
|
|
111
|
-
|
|
112
|
-
const circuitState = new Map(); // name → { failures, openUntil }
|
|
113
|
-
let rrIndex = 0;
|
|
114
|
-
|
|
115
|
-
function pickUpstream(pool) {
|
|
116
|
-
const now = Date.now();
|
|
117
|
-
for (let i = 0; i < pool.length; i++) {
|
|
118
|
-
const idx = rrIndex++ % pool.length;
|
|
119
|
-
const entry = pool[idx];
|
|
120
|
-
const st = circuitState.get(entry.name);
|
|
121
|
-
if (st && st.openUntil > now) continue; // circuit open
|
|
122
|
-
return { entry, idx };
|
|
123
|
-
}
|
|
124
|
-
// all circuits open, reset and retry first
|
|
125
|
-
circuitState.clear();
|
|
126
|
-
return { entry: pool[0], idx: 0 };
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
function recordFailure(name) {
|
|
130
|
-
let st = circuitState.get(name);
|
|
131
|
-
if (!st) { st = { failures: 0, openUntil: 0 }; circuitState.set(name, st); }
|
|
132
|
-
st.failures++;
|
|
133
|
-
if (st.failures >= CIRCUIT_BREAKER_THRESHOLD) {
|
|
134
|
-
st.openUntil = Date.now() + CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
function recordSuccess(name) {
|
|
139
|
-
circuitState.delete(name);
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
const localBridgeSettingsFile = options.localBridgeSettingsFile || '';
|
|
143
|
-
|
|
144
|
-
function readExcludedProviders() {
|
|
145
|
-
if (!localBridgeSettingsFile) return [];
|
|
146
|
-
try {
|
|
147
|
-
if (!fs.existsSync(localBridgeSettingsFile)) return [];
|
|
148
|
-
const raw = JSON.parse(fs.readFileSync(localBridgeSettingsFile, 'utf-8'));
|
|
149
|
-
const excluded = Array.isArray(raw.excludedProviders)
|
|
150
|
-
? raw.excludedProviders.filter(n => typeof n === 'string' && n.trim())
|
|
151
|
-
: [];
|
|
152
|
-
// 解二: auto-exclude lastActiveProvider
|
|
153
|
-
const last = typeof raw.lastActiveProvider === 'string' ? raw.lastActiveProvider.trim() : '';
|
|
154
|
-
if (last && !excluded.some(n => n.toLowerCase() === last.toLowerCase())) {
|
|
155
|
-
excluded.push(last);
|
|
156
|
-
}
|
|
157
|
-
return excluded;
|
|
158
|
-
} catch (e) { return []; }
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
function streamClaudeUpstream(targetUrl, options) {
|
|
162
|
-
const parsed = new URL(targetUrl);
|
|
163
|
-
const transport = parsed.protocol === 'https:' ? https : http;
|
|
164
|
-
const bodyText = options.body || '';
|
|
165
|
-
const headers = {
|
|
166
|
-
'Accept': 'text/event-stream',
|
|
167
|
-
'Content-Type': 'application/json',
|
|
168
|
-
...(options.headers || {})
|
|
169
|
-
};
|
|
170
|
-
if (bodyText) {
|
|
171
|
-
headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
|
|
172
|
-
}
|
|
173
|
-
const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : 0;
|
|
174
|
-
const res = options.res;
|
|
175
|
-
|
|
176
|
-
return new Promise((resolve) => {
|
|
177
|
-
let settled = false;
|
|
178
|
-
let upstreamReq = null;
|
|
179
|
-
const finish = (value) => { if (!settled) { settled = true; resolve(value); } };
|
|
180
|
-
const abortUpstream = () => { if (upstreamReq) try { upstreamReq.destroy(new Error('client aborted')); } catch (_) {} };
|
|
181
|
-
if (res && typeof res.once === 'function') res.once('close', abortUpstream);
|
|
182
|
-
|
|
183
|
-
upstreamReq = transport.request({
|
|
184
|
-
protocol: parsed.protocol,
|
|
185
|
-
hostname: parsed.hostname,
|
|
186
|
-
port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
|
|
187
|
-
method: options.method || 'POST',
|
|
188
|
-
path: `${parsed.pathname}${parsed.search}`,
|
|
189
|
-
headers,
|
|
190
|
-
agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
|
|
191
|
-
}, (upstreamRes) => {
|
|
192
|
-
const status = upstreamRes.statusCode || 0;
|
|
193
|
-
if (status >= 400) {
|
|
194
|
-
const chunks = [];
|
|
195
|
-
let size = 0;
|
|
196
|
-
upstreamRes.on('data', (chunk) => {
|
|
197
|
-
if (!chunk) return;
|
|
198
|
-
if (maxBytes > 0) { size += chunk.length; if (size > maxBytes) { finish({ ok: false, status, error: 'response too large' }); return; } }
|
|
199
|
-
chunks.push(chunk);
|
|
200
|
-
});
|
|
201
|
-
upstreamRes.on('end', () => finish({ ok: false, status, error: chunks.length ? Buffer.concat(chunks).toString('utf-8') : 'Upstream error' }));
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
// SSE: pipe directly to client
|
|
205
|
-
if (!res.headersSent) {
|
|
206
|
-
res.writeHead(200, {
|
|
207
|
-
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
208
|
-
'Cache-Control': 'no-cache',
|
|
209
|
-
'Connection': 'keep-alive',
|
|
210
|
-
'X-Accel-Buffering': 'no'
|
|
211
|
-
});
|
|
212
|
-
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
213
|
-
}
|
|
214
|
-
upstreamRes.pipe(res);
|
|
215
|
-
upstreamRes.on('end', () => finish({ ok: true, status }));
|
|
216
|
-
upstreamRes.on('error', (err) => finish({ ok: false, status, error: err.message }));
|
|
217
|
-
});
|
|
218
|
-
upstreamReq.on('error', (err) => finish({ ok: false, error: err.message }));
|
|
219
|
-
upstreamReq.setTimeout(5 * 60 * 1000, () => { try { upstreamReq.destroy(new Error('timeout')); } catch (_) {} });
|
|
220
|
-
if (bodyText) upstreamReq.write(bodyText);
|
|
221
|
-
upstreamReq.end();
|
|
222
|
-
});
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
function readClaudeExcludedProviders() {
|
|
226
|
-
if (!claudeProvidersFile) return [];
|
|
227
|
-
try {
|
|
228
|
-
if (!fs.existsSync(claudeProvidersFile)) return [];
|
|
229
|
-
const raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
|
|
230
|
-
return Array.isArray(raw.excludedProviders)
|
|
231
|
-
? raw.excludedProviders.filter(n => typeof n === 'string' && n.trim())
|
|
232
|
-
: [];
|
|
233
|
-
} catch (e) { return []; }
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
async function handleClaudeLocalBridge(req, res, parsedUrl) {
|
|
237
|
-
try {
|
|
238
|
-
const token = extractAuthorizationToken(req);
|
|
239
|
-
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
240
|
-
const isLoopback = isLoopbackAddress(remoteAddr);
|
|
241
|
-
if (!isLoopback && !expectedToken) {
|
|
242
|
-
res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
243
|
-
res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
|
|
244
|
-
return;
|
|
245
|
-
}
|
|
246
|
-
if (!token && !isLoopback) {
|
|
247
|
-
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
248
|
-
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
249
|
-
return;
|
|
250
|
-
}
|
|
251
|
-
if (!isLoopback && token && token !== expectedToken) {
|
|
252
|
-
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
253
|
-
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
const poolResult = buildClaudeUpstreamPool(claudeProvidersFile, readClaudeExcludedProviders());
|
|
258
|
-
if (poolResult.error) {
|
|
259
|
-
res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
260
|
-
res.end(JSON.stringify({ error: poolResult.error }));
|
|
261
|
-
return;
|
|
262
|
-
}
|
|
263
|
-
const pool = poolResult.pool;
|
|
264
|
-
const { entry } = pickUpstream(pool);
|
|
265
|
-
|
|
266
|
-
const suffix = (parsedUrl.pathname || '').replace(/^\/bridge\/claude-local\/?/, '');
|
|
267
|
-
if (!suffix) {
|
|
268
|
-
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
269
|
-
res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
270
|
-
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
|
271
|
-
return;
|
|
272
|
-
}
|
|
273
|
-
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
274
|
-
res.end(JSON.stringify({ object: 'codexmate.claude_local_bridge', provider: entry.name, model: entry.model || '', status: 'ok', pool: pool.map(p => p.name) }));
|
|
275
|
-
return;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
// Proxy Anthropic Messages API requests
|
|
279
|
-
const bodyResult = await readRequestBody(req, maxBodySize);
|
|
280
|
-
if (bodyResult.error) {
|
|
281
|
-
res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
282
|
-
res.end(JSON.stringify({ error: bodyResult.error }));
|
|
283
|
-
return;
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
let parsedBody;
|
|
287
|
-
try { parsedBody = bodyResult.body ? JSON.parse(bodyResult.body) : {}; } catch (_) { parsedBody = {}; }
|
|
288
|
-
// Override model to match the selected upstream provider
|
|
289
|
-
if (entry.model && parsedBody && typeof parsedBody === 'object') {
|
|
290
|
-
parsedBody.model = entry.model;
|
|
291
|
-
}
|
|
292
|
-
const wantsStream = !!(parsedBody && parsedBody.stream);
|
|
293
|
-
const bodyToForward = JSON.stringify(parsedBody);
|
|
294
|
-
const upstreamUrl = joinApiUrl(entry.baseUrl.replace(/\/+$/, ''), suffix);
|
|
295
|
-
const headers = { 'Content-Type': 'application/json' };
|
|
296
|
-
if (entry.apiKey) {
|
|
297
|
-
headers['x-api-key'] = entry.apiKey.startsWith('Bearer ') ? entry.apiKey.slice(7) : entry.apiKey;
|
|
298
|
-
}
|
|
299
|
-
if (token && !entry.apiKey) {
|
|
300
|
-
headers['x-api-key'] = token.startsWith('Bearer ') ? token.slice(7) : token;
|
|
301
|
-
}
|
|
302
|
-
headers['anthropic-version'] = '2023-06-01';
|
|
303
|
-
|
|
304
|
-
if (wantsStream) {
|
|
305
|
-
// Streaming proxy: pipe upstream SSE directly to client
|
|
306
|
-
const upstreamResult = await streamClaudeUpstream(upstreamUrl, {
|
|
307
|
-
method: req.method || 'POST',
|
|
308
|
-
body: bodyToForward,
|
|
309
|
-
headers,
|
|
310
|
-
maxBytes: maxUpstreamBytes,
|
|
311
|
-
httpAgent,
|
|
312
|
-
httpsAgent,
|
|
313
|
-
res
|
|
314
|
-
});
|
|
315
|
-
if (!upstreamResult.ok) {
|
|
316
|
-
recordFailure(entry.name);
|
|
317
|
-
if (!res.headersSent) {
|
|
318
|
-
res.writeHead(upstreamResult.status || 502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
319
|
-
res.end(JSON.stringify({ error: upstreamResult.error || 'Upstream error' }));
|
|
320
|
-
}
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
recordSuccess(entry.name);
|
|
324
|
-
return;
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
// Non-streaming proxy
|
|
328
|
-
const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
|
|
329
|
-
method: req.method || 'POST',
|
|
330
|
-
body: bodyToForward || null,
|
|
331
|
-
headers,
|
|
332
|
-
maxBytes: maxUpstreamBytes,
|
|
333
|
-
httpAgent,
|
|
334
|
-
httpsAgent
|
|
335
|
-
}));
|
|
336
|
-
|
|
337
|
-
if (!upstreamResult.ok) {
|
|
338
|
-
recordFailure(entry.name);
|
|
339
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
340
|
-
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
|
|
341
|
-
return;
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
recordSuccess(entry.name);
|
|
345
|
-
const statusCode = Number.isFinite(upstreamResult.status) ? upstreamResult.status : 200;
|
|
346
|
-
res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
347
|
-
res.end(upstreamResult.bodyText || '{}');
|
|
348
|
-
} catch (e) {
|
|
349
|
-
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
350
|
-
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
|
|
354
|
-
const handler = (req, res) => {
|
|
355
|
-
let parsedUrl;
|
|
356
|
-
try { parsedUrl = new URL(req.url || '/', 'http://localhost'); } catch (_) { return false; }
|
|
357
|
-
const pathname = parsedUrl.pathname || '/';
|
|
358
|
-
|
|
359
|
-
// Claude local bridge: /bridge/claude-local/v1/messages
|
|
360
|
-
if (pathname.startsWith('/bridge/claude-local/')) {
|
|
361
|
-
if (!claudeProvidersFile) return false;
|
|
362
|
-
void handleClaudeLocalBridge(req, res, parsedUrl);
|
|
363
|
-
return true;
|
|
364
|
-
}
|
|
365
|
-
|
|
366
|
-
// Codex local bridge: /bridge/local/v1
|
|
367
|
-
if (!pathname.startsWith('/bridge/local/')) return false;
|
|
368
|
-
const suffix = pathname.replace(/^\/bridge\/local\/?/, '');
|
|
369
|
-
if (!suffix.startsWith('v1')) return false;
|
|
370
|
-
|
|
371
|
-
void (async () => {
|
|
372
|
-
try {
|
|
373
|
-
const token = extractAuthorizationToken(req);
|
|
374
|
-
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
375
|
-
const isLoopback = isLoopbackAddress(remoteAddr);
|
|
376
|
-
if (!isLoopback && !expectedToken) {
|
|
377
|
-
res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
378
|
-
res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
|
|
379
|
-
return;
|
|
380
|
-
}
|
|
381
|
-
if (!token && !isLoopback) {
|
|
382
|
-
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
383
|
-
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
384
|
-
return;
|
|
385
|
-
}
|
|
386
|
-
if (!isLoopback && token && token !== expectedToken) {
|
|
387
|
-
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
388
|
-
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
389
|
-
return;
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
const poolResult = buildUpstreamPool(readConfigFn, openaiBridgeFile, readExcludedProviders());
|
|
393
|
-
if (poolResult.error) {
|
|
394
|
-
res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
395
|
-
res.end(JSON.stringify({ error: poolResult.error }));
|
|
396
|
-
return;
|
|
397
|
-
}
|
|
398
|
-
const pool = poolResult.pool;
|
|
399
|
-
|
|
400
|
-
const { entry, idx } = pickUpstream(pool);
|
|
401
|
-
const authHeader = resolveUpstreamAuth(entry, openaiBridgeFile, token);
|
|
402
|
-
|
|
403
|
-
const normalizedSuffix = suffix.replace(/^v1\/?/, '');
|
|
404
|
-
const upstreamBase = entry.baseUrl.replace(/\/+$/, '');
|
|
405
|
-
|
|
406
|
-
if (!normalizedSuffix) {
|
|
407
|
-
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
408
|
-
res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
409
|
-
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
|
410
|
-
return;
|
|
411
|
-
}
|
|
412
|
-
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
413
|
-
res.end(JSON.stringify({ object: 'codexmate.local_bridge', provider: entry.name, status: 'ok', pool: pool.map(p => p.name) }));
|
|
414
|
-
return;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
if (normalizedSuffix === 'responses' && (req.method || 'GET').toUpperCase() === 'POST') {
|
|
418
|
-
const bodyResult = await readRequestBody(req, maxBodySize);
|
|
419
|
-
if (bodyResult.error) {
|
|
420
|
-
res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
421
|
-
res.end(JSON.stringify({ error: bodyResult.error }));
|
|
422
|
-
return;
|
|
423
|
-
}
|
|
424
|
-
const parsed = parseJsonOrError(bodyResult.body);
|
|
425
|
-
if (parsed.error) {
|
|
426
|
-
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
427
|
-
res.end(JSON.stringify({ error: parsed.error }));
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
const responsesRequest = parsed.value;
|
|
431
|
-
const wantsSse = !!(responsesRequest && responsesRequest.stream);
|
|
432
|
-
const upstreamResponsesUrl = joinApiUrl(upstreamBase, 'responses');
|
|
433
|
-
const upstreamResponsesResult = await retryTransientRequest(() => proxyRequestJson(upstreamResponsesUrl, {
|
|
434
|
-
method: 'POST',
|
|
435
|
-
body: bodyResult.body,
|
|
436
|
-
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
437
|
-
maxBytes: maxUpstreamBytes,
|
|
438
|
-
httpAgent,
|
|
439
|
-
httpsAgent
|
|
440
|
-
}));
|
|
441
|
-
|
|
442
|
-
if (upstreamResponsesResult.ok && upstreamResponsesResult.status < 400) {
|
|
443
|
-
recordSuccess(entry.name);
|
|
444
|
-
const upstreamPayload = parseJsonOrError(upstreamResponsesResult.bodyText);
|
|
445
|
-
if (upstreamPayload.error) {
|
|
446
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
447
|
-
res.end(JSON.stringify({ error: `Upstream parse failed: ${upstreamPayload.error}` }));
|
|
448
|
-
return;
|
|
449
|
-
}
|
|
450
|
-
if (wantsSse) {
|
|
451
|
-
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
452
|
-
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
453
|
-
sendResponsesSse(res, upstreamPayload.value);
|
|
454
|
-
res.end();
|
|
455
|
-
return;
|
|
456
|
-
}
|
|
457
|
-
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
458
|
-
res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload.value)));
|
|
459
|
-
return;
|
|
460
|
-
}
|
|
461
|
-
|
|
462
|
-
if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400 && !shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
|
|
463
|
-
recordFailure(entry.name);
|
|
464
|
-
res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
465
|
-
res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
466
|
-
return;
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
if (!upstreamResponsesResult.ok) {
|
|
470
|
-
recordFailure(entry.name);
|
|
471
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
472
|
-
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
|
|
473
|
-
return;
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// fallthrough to chat/completions conversion
|
|
477
|
-
recordSuccess(entry.name);
|
|
478
|
-
const converted = convertResponsesRequestToChatCompletions(responsesRequest);
|
|
479
|
-
if (converted.error) {
|
|
480
|
-
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
481
|
-
res.end(JSON.stringify({ error: converted.error }));
|
|
482
|
-
return;
|
|
483
|
-
}
|
|
484
|
-
const chatUrl = joinApiUrl(upstreamBase, 'chat/completions');
|
|
485
|
-
const chatResult = await retryTransientRequest(() => proxyRequestJson(chatUrl, {
|
|
486
|
-
method: 'POST',
|
|
487
|
-
body: JSON.stringify(converted.chat),
|
|
488
|
-
headers: { ...(authHeader ? { Authorization: authHeader } : {}), 'Content-Type': 'application/json' },
|
|
489
|
-
maxBytes: maxUpstreamBytes,
|
|
490
|
-
httpAgent,
|
|
491
|
-
httpsAgent
|
|
492
|
-
}));
|
|
493
|
-
if (!chatResult.ok) {
|
|
494
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
495
|
-
res.end(JSON.stringify({ error: `Upstream request failed: ${chatResult.error}` }));
|
|
496
|
-
return;
|
|
497
|
-
}
|
|
498
|
-
const chatJson = parseJsonOrError(chatResult.bodyText);
|
|
499
|
-
if (chatResult.status >= 400) {
|
|
500
|
-
res.writeHead(chatResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
501
|
-
res.end(chatResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
502
|
-
return;
|
|
503
|
-
}
|
|
504
|
-
if (chatJson.error) {
|
|
505
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
506
|
-
res.end(JSON.stringify({ error: `Upstream parse failed: ${chatJson.error}` }));
|
|
507
|
-
return;
|
|
508
|
-
}
|
|
509
|
-
const extracted = extractChatCompletionResult(chatJson.value);
|
|
510
|
-
const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
|
|
511
|
-
const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
|
|
512
|
-
const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
|
|
513
|
-
const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, chatJson.value);
|
|
514
|
-
if (wantsSse) {
|
|
515
|
-
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
516
|
-
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
517
|
-
sendResponsesSse(res, responsesPayload);
|
|
518
|
-
res.end();
|
|
519
|
-
return;
|
|
520
|
-
}
|
|
521
|
-
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
522
|
-
res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
|
|
523
|
-
return;
|
|
524
|
-
}
|
|
525
|
-
|
|
526
|
-
// passthrough for other v1/* paths
|
|
527
|
-
const upstreamUrl = joinApiUrl(upstreamBase, normalizedSuffix);
|
|
528
|
-
const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
|
|
529
|
-
method: req.method || 'GET',
|
|
530
|
-
body: null,
|
|
531
|
-
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
532
|
-
maxBytes: maxUpstreamBytes,
|
|
533
|
-
httpAgent,
|
|
534
|
-
httpsAgent
|
|
535
|
-
}));
|
|
536
|
-
if (!upstreamResult.ok) {
|
|
537
|
-
recordFailure(entry.name);
|
|
538
|
-
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
539
|
-
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
|
|
540
|
-
return;
|
|
541
|
-
}
|
|
542
|
-
recordSuccess(entry.name);
|
|
543
|
-
res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
544
|
-
res.end(upstreamResult.bodyText);
|
|
545
|
-
} catch (e) {
|
|
546
|
-
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
547
|
-
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
|
|
548
|
-
}
|
|
549
|
-
})();
|
|
550
|
-
return true;
|
|
551
|
-
};
|
|
552
|
-
|
|
553
|
-
return handler;
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
module.exports = { createLocalBridgeHttpHandler };
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const http = require('http');
|
|
3
|
+
const https = require('https');
|
|
4
|
+
const { URL } = require('url');
|
|
5
|
+
const {
|
|
6
|
+
readOpenaiBridgeSettings,
|
|
7
|
+
convertResponsesRequestToChatCompletions,
|
|
8
|
+
streamChatCompletionsAsResponsesSse,
|
|
9
|
+
proxyRequestJson,
|
|
10
|
+
ensureResponseMetadata,
|
|
11
|
+
sendResponsesSse,
|
|
12
|
+
extractAuthorizationToken,
|
|
13
|
+
readRequestBody,
|
|
14
|
+
parseJsonOrError,
|
|
15
|
+
extractChatCompletionResult,
|
|
16
|
+
buildResponsesPayloadFromChatResult,
|
|
17
|
+
retryTransientRequest,
|
|
18
|
+
shouldFallbackFromUpstreamResponses,
|
|
19
|
+
isTransientNetworkError,
|
|
20
|
+
isLoopbackAddress
|
|
21
|
+
} = require('./openai-bridge');
|
|
22
|
+
const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
|
|
23
|
+
|
|
24
|
+
const BUILTIN_PROXY_PROVIDER_NAME = 'codexmate-proxy';
|
|
25
|
+
const BUILTIN_LOCAL_PROVIDER_NAME = 'local';
|
|
26
|
+
const CLAUDE_LOCAL_PROVIDER_NAME = 'claude-local';
|
|
27
|
+
const CLAUDE_LOCAL_EXCLUDED_KEY = 'claudeLocalExcluded';
|
|
28
|
+
const CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
29
|
+
const CIRCUIT_BREAKER_COOLDOWN_MS = 5 * 60 * 1000;
|
|
30
|
+
|
|
31
|
+
function buildUpstreamPool(readConfigFn, openaiBridgeFile, excludedProviders) {
|
|
32
|
+
let config;
|
|
33
|
+
try { config = readConfigFn(); } catch (e) { return { error: '读取配置失败' }; }
|
|
34
|
+
const providers = (config && typeof config.model_providers === 'object' && !Array.isArray(config.model_providers))
|
|
35
|
+
? config.model_providers : {};
|
|
36
|
+
const pool = [];
|
|
37
|
+
const excludedSet = new Set(
|
|
38
|
+
(Array.isArray(excludedProviders) ? excludedProviders : [])
|
|
39
|
+
.filter(n => typeof n === 'string' && n.trim())
|
|
40
|
+
.map(n => n.trim().toLowerCase())
|
|
41
|
+
);
|
|
42
|
+
for (const [name, p] of Object.entries(providers)) {
|
|
43
|
+
if (!p || typeof p !== 'object') continue;
|
|
44
|
+
const lower = name.toLowerCase();
|
|
45
|
+
if (lower === BUILTIN_LOCAL_PROVIDER_NAME || lower === BUILTIN_PROXY_PROVIDER_NAME) continue;
|
|
46
|
+
if (excludedSet.has(lower)) continue;
|
|
47
|
+
const bridge = typeof p.codexmate_bridge === 'string' ? p.codexmate_bridge.trim() : '';
|
|
48
|
+
if (bridge === 'local') continue; // avoid loop: local→local
|
|
49
|
+
const baseUrl = typeof p.base_url === 'string' ? p.base_url.trim() : '';
|
|
50
|
+
if (!isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
|
|
51
|
+
const authMethod = typeof p.preferred_auth_method === 'string' ? p.preferred_auth_method.trim() : '';
|
|
52
|
+
pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), authMethod, requiresOpenaiAuth: !!p.requires_openai_auth });
|
|
53
|
+
}
|
|
54
|
+
if (pool.length === 0) return { error: '请先添加上游 provider' };
|
|
55
|
+
return { pool };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function buildClaudeUpstreamPool(claudeProvidersFile, excludedProviders) {
|
|
59
|
+
let raw;
|
|
60
|
+
try {
|
|
61
|
+
if (!fs.existsSync(claudeProvidersFile)) return { error: '暂无可用上游 provider,请先添加 Claude 提供商' };
|
|
62
|
+
raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
|
|
63
|
+
} catch (e) { return { error: '读取 Claude 提供商配置失败' }; }
|
|
64
|
+
const providers = (raw && typeof raw.providers === 'object' && !Array.isArray(raw.providers))
|
|
65
|
+
? raw.providers : {};
|
|
66
|
+
const pool = [];
|
|
67
|
+
const excludedSet = new Set(
|
|
68
|
+
(Array.isArray(excludedProviders) ? excludedProviders : [])
|
|
69
|
+
.filter(n => typeof n === 'string' && n.trim())
|
|
70
|
+
.map(n => n.trim().toLowerCase())
|
|
71
|
+
);
|
|
72
|
+
for (const [name, p] of Object.entries(providers)) {
|
|
73
|
+
if (!p || typeof p !== 'object') continue;
|
|
74
|
+
if (excludedSet.has(name.toLowerCase())) continue;
|
|
75
|
+
const baseUrl = typeof p.baseUrl === 'string' ? p.baseUrl.trim() : '';
|
|
76
|
+
if (!baseUrl || !isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
|
|
77
|
+
pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), apiKey: typeof p.apiKey === 'string' ? p.apiKey : '', model: typeof p.model === 'string' ? p.model.trim() : '' });
|
|
78
|
+
}
|
|
79
|
+
if (pool.length === 0) return { error: '请先添加可用的 Claude 上游提供商' };
|
|
80
|
+
return { pool };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function resolveUpstreamAuth(entry, openaiBridgeFile, reqAuthToken) {
|
|
84
|
+
if (entry.authMethod === 'codexmate' || entry.requiresOpenaiAuth) {
|
|
85
|
+
const token = reqAuthToken || '';
|
|
86
|
+
return token ? (token.startsWith('sk-') ? `Bearer ${token}` : `Bearer ${token}`) : '';
|
|
87
|
+
}
|
|
88
|
+
if (entry.authMethod === 'openai-bridge') {
|
|
89
|
+
const settings = readOpenaiBridgeSettings(openaiBridgeFile);
|
|
90
|
+
const upstream = settings.providers ? settings.providers[entry.name] : null;
|
|
91
|
+
if (upstream && upstream.apiKey) {
|
|
92
|
+
return upstream.apiKey.startsWith('Bearer ') ? upstream.apiKey : `Bearer ${upstream.apiKey}`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return '';
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function createLocalBridgeHttpHandler(options = {}) {
|
|
99
|
+
const readConfigFn = options.readConfigFn;
|
|
100
|
+
const openaiBridgeFile = options.openaiBridgeFile;
|
|
101
|
+
const claudeProvidersFile = options.claudeProvidersFile || '';
|
|
102
|
+
const expectedToken = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
|
|
103
|
+
const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
|
|
104
|
+
const httpAgent = options.httpAgent;
|
|
105
|
+
const httpsAgent = options.httpsAgent;
|
|
106
|
+
const maxUpstreamBytes = Number.isFinite(options.maxUpstreamBytes) && options.maxUpstreamBytes > 0
|
|
107
|
+
? Math.floor(options.maxUpstreamBytes)
|
|
108
|
+
: Math.max(16 * 1024 * 1024, maxBodySize > 0 ? maxBodySize * 4 : 0);
|
|
109
|
+
|
|
110
|
+
if (typeof readConfigFn !== 'function') throw new Error('createLocalBridgeHttpHandler 缺少 readConfigFn');
|
|
111
|
+
|
|
112
|
+
const circuitState = new Map(); // name → { failures, openUntil }
|
|
113
|
+
let rrIndex = 0;
|
|
114
|
+
|
|
115
|
+
function pickUpstream(pool) {
|
|
116
|
+
const now = Date.now();
|
|
117
|
+
for (let i = 0; i < pool.length; i++) {
|
|
118
|
+
const idx = rrIndex++ % pool.length;
|
|
119
|
+
const entry = pool[idx];
|
|
120
|
+
const st = circuitState.get(entry.name);
|
|
121
|
+
if (st && st.openUntil > now) continue; // circuit open
|
|
122
|
+
return { entry, idx };
|
|
123
|
+
}
|
|
124
|
+
// all circuits open, reset and retry first
|
|
125
|
+
circuitState.clear();
|
|
126
|
+
return { entry: pool[0], idx: 0 };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function recordFailure(name) {
|
|
130
|
+
let st = circuitState.get(name);
|
|
131
|
+
if (!st) { st = { failures: 0, openUntil: 0 }; circuitState.set(name, st); }
|
|
132
|
+
st.failures++;
|
|
133
|
+
if (st.failures >= CIRCUIT_BREAKER_THRESHOLD) {
|
|
134
|
+
st.openUntil = Date.now() + CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function recordSuccess(name) {
|
|
139
|
+
circuitState.delete(name);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const localBridgeSettingsFile = options.localBridgeSettingsFile || '';
|
|
143
|
+
|
|
144
|
+
function readExcludedProviders() {
|
|
145
|
+
if (!localBridgeSettingsFile) return [];
|
|
146
|
+
try {
|
|
147
|
+
if (!fs.existsSync(localBridgeSettingsFile)) return [];
|
|
148
|
+
const raw = JSON.parse(fs.readFileSync(localBridgeSettingsFile, 'utf-8'));
|
|
149
|
+
const excluded = Array.isArray(raw.excludedProviders)
|
|
150
|
+
? raw.excludedProviders.filter(n => typeof n === 'string' && n.trim())
|
|
151
|
+
: [];
|
|
152
|
+
// 解二: auto-exclude lastActiveProvider
|
|
153
|
+
const last = typeof raw.lastActiveProvider === 'string' ? raw.lastActiveProvider.trim() : '';
|
|
154
|
+
if (last && !excluded.some(n => n.toLowerCase() === last.toLowerCase())) {
|
|
155
|
+
excluded.push(last);
|
|
156
|
+
}
|
|
157
|
+
return excluded;
|
|
158
|
+
} catch (e) { return []; }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function streamClaudeUpstream(targetUrl, options) {
|
|
162
|
+
const parsed = new URL(targetUrl);
|
|
163
|
+
const transport = parsed.protocol === 'https:' ? https : http;
|
|
164
|
+
const bodyText = options.body || '';
|
|
165
|
+
const headers = {
|
|
166
|
+
'Accept': 'text/event-stream',
|
|
167
|
+
'Content-Type': 'application/json',
|
|
168
|
+
...(options.headers || {})
|
|
169
|
+
};
|
|
170
|
+
if (bodyText) {
|
|
171
|
+
headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
|
|
172
|
+
}
|
|
173
|
+
const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0 ? options.maxBytes : 0;
|
|
174
|
+
const res = options.res;
|
|
175
|
+
|
|
176
|
+
return new Promise((resolve) => {
|
|
177
|
+
let settled = false;
|
|
178
|
+
let upstreamReq = null;
|
|
179
|
+
const finish = (value) => { if (!settled) { settled = true; resolve(value); } };
|
|
180
|
+
const abortUpstream = () => { if (upstreamReq) try { upstreamReq.destroy(new Error('client aborted')); } catch (_) {} };
|
|
181
|
+
if (res && typeof res.once === 'function') res.once('close', abortUpstream);
|
|
182
|
+
|
|
183
|
+
upstreamReq = transport.request({
|
|
184
|
+
protocol: parsed.protocol,
|
|
185
|
+
hostname: parsed.hostname,
|
|
186
|
+
port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
|
|
187
|
+
method: options.method || 'POST',
|
|
188
|
+
path: `${parsed.pathname}${parsed.search}`,
|
|
189
|
+
headers,
|
|
190
|
+
agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
|
|
191
|
+
}, (upstreamRes) => {
|
|
192
|
+
const status = upstreamRes.statusCode || 0;
|
|
193
|
+
if (status >= 400) {
|
|
194
|
+
const chunks = [];
|
|
195
|
+
let size = 0;
|
|
196
|
+
upstreamRes.on('data', (chunk) => {
|
|
197
|
+
if (!chunk) return;
|
|
198
|
+
if (maxBytes > 0) { size += chunk.length; if (size > maxBytes) { finish({ ok: false, status, error: 'response too large' }); return; } }
|
|
199
|
+
chunks.push(chunk);
|
|
200
|
+
});
|
|
201
|
+
upstreamRes.on('end', () => finish({ ok: false, status, error: chunks.length ? Buffer.concat(chunks).toString('utf-8') : 'Upstream error' }));
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
// SSE: pipe directly to client
|
|
205
|
+
if (!res.headersSent) {
|
|
206
|
+
res.writeHead(200, {
|
|
207
|
+
'Content-Type': 'text/event-stream; charset=utf-8',
|
|
208
|
+
'Cache-Control': 'no-cache',
|
|
209
|
+
'Connection': 'keep-alive',
|
|
210
|
+
'X-Accel-Buffering': 'no'
|
|
211
|
+
});
|
|
212
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
213
|
+
}
|
|
214
|
+
upstreamRes.pipe(res);
|
|
215
|
+
upstreamRes.on('end', () => finish({ ok: true, status }));
|
|
216
|
+
upstreamRes.on('error', (err) => finish({ ok: false, status, error: err.message }));
|
|
217
|
+
});
|
|
218
|
+
upstreamReq.on('error', (err) => finish({ ok: false, error: err.message }));
|
|
219
|
+
upstreamReq.setTimeout(5 * 60 * 1000, () => { try { upstreamReq.destroy(new Error('timeout')); } catch (_) {} });
|
|
220
|
+
if (bodyText) upstreamReq.write(bodyText);
|
|
221
|
+
upstreamReq.end();
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function readClaudeExcludedProviders() {
|
|
226
|
+
if (!claudeProvidersFile) return [];
|
|
227
|
+
try {
|
|
228
|
+
if (!fs.existsSync(claudeProvidersFile)) return [];
|
|
229
|
+
const raw = JSON.parse(fs.readFileSync(claudeProvidersFile, 'utf-8'));
|
|
230
|
+
return Array.isArray(raw.excludedProviders)
|
|
231
|
+
? raw.excludedProviders.filter(n => typeof n === 'string' && n.trim())
|
|
232
|
+
: [];
|
|
233
|
+
} catch (e) { return []; }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function handleClaudeLocalBridge(req, res, parsedUrl) {
|
|
237
|
+
try {
|
|
238
|
+
const token = extractAuthorizationToken(req);
|
|
239
|
+
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
240
|
+
const isLoopback = isLoopbackAddress(remoteAddr);
|
|
241
|
+
if (!isLoopback && !expectedToken) {
|
|
242
|
+
res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
243
|
+
res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (!token && !isLoopback) {
|
|
247
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
248
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
if (!isLoopback && token && token !== expectedToken) {
|
|
252
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
253
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const poolResult = buildClaudeUpstreamPool(claudeProvidersFile, readClaudeExcludedProviders());
|
|
258
|
+
if (poolResult.error) {
|
|
259
|
+
res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
260
|
+
res.end(JSON.stringify({ error: poolResult.error }));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
const pool = poolResult.pool;
|
|
264
|
+
const { entry } = pickUpstream(pool);
|
|
265
|
+
|
|
266
|
+
const suffix = (parsedUrl.pathname || '').replace(/^\/bridge\/claude-local\/?/, '');
|
|
267
|
+
if (!suffix) {
|
|
268
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
269
|
+
res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
270
|
+
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
274
|
+
res.end(JSON.stringify({ object: 'codexmate.claude_local_bridge', provider: entry.name, model: entry.model || '', status: 'ok', pool: pool.map(p => p.name) }));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Proxy Anthropic Messages API requests
|
|
279
|
+
const bodyResult = await readRequestBody(req, maxBodySize);
|
|
280
|
+
if (bodyResult.error) {
|
|
281
|
+
res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
282
|
+
res.end(JSON.stringify({ error: bodyResult.error }));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
let parsedBody;
|
|
287
|
+
try { parsedBody = bodyResult.body ? JSON.parse(bodyResult.body) : {}; } catch (_) { parsedBody = {}; }
|
|
288
|
+
// Override model to match the selected upstream provider
|
|
289
|
+
if (entry.model && parsedBody && typeof parsedBody === 'object') {
|
|
290
|
+
parsedBody.model = entry.model;
|
|
291
|
+
}
|
|
292
|
+
const wantsStream = !!(parsedBody && parsedBody.stream);
|
|
293
|
+
const bodyToForward = JSON.stringify(parsedBody);
|
|
294
|
+
const upstreamUrl = joinApiUrl(entry.baseUrl.replace(/\/+$/, ''), suffix);
|
|
295
|
+
const headers = { 'Content-Type': 'application/json' };
|
|
296
|
+
if (entry.apiKey) {
|
|
297
|
+
headers['x-api-key'] = entry.apiKey.startsWith('Bearer ') ? entry.apiKey.slice(7) : entry.apiKey;
|
|
298
|
+
}
|
|
299
|
+
if (token && !entry.apiKey) {
|
|
300
|
+
headers['x-api-key'] = token.startsWith('Bearer ') ? token.slice(7) : token;
|
|
301
|
+
}
|
|
302
|
+
headers['anthropic-version'] = '2023-06-01';
|
|
303
|
+
|
|
304
|
+
if (wantsStream) {
|
|
305
|
+
// Streaming proxy: pipe upstream SSE directly to client
|
|
306
|
+
const upstreamResult = await streamClaudeUpstream(upstreamUrl, {
|
|
307
|
+
method: req.method || 'POST',
|
|
308
|
+
body: bodyToForward,
|
|
309
|
+
headers,
|
|
310
|
+
maxBytes: maxUpstreamBytes,
|
|
311
|
+
httpAgent,
|
|
312
|
+
httpsAgent,
|
|
313
|
+
res
|
|
314
|
+
});
|
|
315
|
+
if (!upstreamResult.ok) {
|
|
316
|
+
recordFailure(entry.name);
|
|
317
|
+
if (!res.headersSent) {
|
|
318
|
+
res.writeHead(upstreamResult.status || 502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
319
|
+
res.end(JSON.stringify({ error: upstreamResult.error || 'Upstream error' }));
|
|
320
|
+
}
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
recordSuccess(entry.name);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// Non-streaming proxy
|
|
328
|
+
const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
|
|
329
|
+
method: req.method || 'POST',
|
|
330
|
+
body: bodyToForward || null,
|
|
331
|
+
headers,
|
|
332
|
+
maxBytes: maxUpstreamBytes,
|
|
333
|
+
httpAgent,
|
|
334
|
+
httpsAgent
|
|
335
|
+
}));
|
|
336
|
+
|
|
337
|
+
if (!upstreamResult.ok) {
|
|
338
|
+
recordFailure(entry.name);
|
|
339
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
340
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
recordSuccess(entry.name);
|
|
345
|
+
const statusCode = Number.isFinite(upstreamResult.status) ? upstreamResult.status : 200;
|
|
346
|
+
res.writeHead(statusCode, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
347
|
+
res.end(upstreamResult.bodyText || '{}');
|
|
348
|
+
} catch (e) {
|
|
349
|
+
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
350
|
+
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const handler = (req, res) => {
|
|
355
|
+
let parsedUrl;
|
|
356
|
+
try { parsedUrl = new URL(req.url || '/', 'http://localhost'); } catch (_) { return false; }
|
|
357
|
+
const pathname = parsedUrl.pathname || '/';
|
|
358
|
+
|
|
359
|
+
// Claude local bridge: /bridge/claude-local/v1/messages
|
|
360
|
+
if (pathname.startsWith('/bridge/claude-local/')) {
|
|
361
|
+
if (!claudeProvidersFile) return false;
|
|
362
|
+
void handleClaudeLocalBridge(req, res, parsedUrl);
|
|
363
|
+
return true;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
// Codex local bridge: /bridge/local/v1
|
|
367
|
+
if (!pathname.startsWith('/bridge/local/')) return false;
|
|
368
|
+
const suffix = pathname.replace(/^\/bridge\/local\/?/, '');
|
|
369
|
+
if (!suffix.startsWith('v1')) return false;
|
|
370
|
+
|
|
371
|
+
void (async () => {
|
|
372
|
+
try {
|
|
373
|
+
const token = extractAuthorizationToken(req);
|
|
374
|
+
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
375
|
+
const isLoopback = isLoopbackAddress(remoteAddr);
|
|
376
|
+
if (!isLoopback && !expectedToken) {
|
|
377
|
+
res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
378
|
+
res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (!token && !isLoopback) {
|
|
382
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
383
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (!isLoopback && token && token !== expectedToken) {
|
|
387
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
388
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const poolResult = buildUpstreamPool(readConfigFn, openaiBridgeFile, readExcludedProviders());
|
|
393
|
+
if (poolResult.error) {
|
|
394
|
+
res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
395
|
+
res.end(JSON.stringify({ error: poolResult.error }));
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const pool = poolResult.pool;
|
|
399
|
+
|
|
400
|
+
const { entry, idx } = pickUpstream(pool);
|
|
401
|
+
const authHeader = resolveUpstreamAuth(entry, openaiBridgeFile, token);
|
|
402
|
+
|
|
403
|
+
const normalizedSuffix = suffix.replace(/^v1\/?/, '');
|
|
404
|
+
const upstreamBase = entry.baseUrl.replace(/\/+$/, '');
|
|
405
|
+
|
|
406
|
+
if (!normalizedSuffix) {
|
|
407
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
408
|
+
res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
409
|
+
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
413
|
+
res.end(JSON.stringify({ object: 'codexmate.local_bridge', provider: entry.name, status: 'ok', pool: pool.map(p => p.name) }));
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
if (normalizedSuffix === 'responses' && (req.method || 'GET').toUpperCase() === 'POST') {
|
|
418
|
+
const bodyResult = await readRequestBody(req, maxBodySize);
|
|
419
|
+
if (bodyResult.error) {
|
|
420
|
+
res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
421
|
+
res.end(JSON.stringify({ error: bodyResult.error }));
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const parsed = parseJsonOrError(bodyResult.body);
|
|
425
|
+
if (parsed.error) {
|
|
426
|
+
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
427
|
+
res.end(JSON.stringify({ error: parsed.error }));
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const responsesRequest = parsed.value;
|
|
431
|
+
const wantsSse = !!(responsesRequest && responsesRequest.stream);
|
|
432
|
+
const upstreamResponsesUrl = joinApiUrl(upstreamBase, 'responses');
|
|
433
|
+
const upstreamResponsesResult = await retryTransientRequest(() => proxyRequestJson(upstreamResponsesUrl, {
|
|
434
|
+
method: 'POST',
|
|
435
|
+
body: bodyResult.body,
|
|
436
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
437
|
+
maxBytes: maxUpstreamBytes,
|
|
438
|
+
httpAgent,
|
|
439
|
+
httpsAgent
|
|
440
|
+
}));
|
|
441
|
+
|
|
442
|
+
if (upstreamResponsesResult.ok && upstreamResponsesResult.status < 400) {
|
|
443
|
+
recordSuccess(entry.name);
|
|
444
|
+
const upstreamPayload = parseJsonOrError(upstreamResponsesResult.bodyText);
|
|
445
|
+
if (upstreamPayload.error) {
|
|
446
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
447
|
+
res.end(JSON.stringify({ error: `Upstream parse failed: ${upstreamPayload.error}` }));
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
if (wantsSse) {
|
|
451
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
452
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
453
|
+
sendResponsesSse(res, upstreamPayload.value);
|
|
454
|
+
res.end();
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
458
|
+
res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload.value)));
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400 && !shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
|
|
463
|
+
recordFailure(entry.name);
|
|
464
|
+
res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
465
|
+
res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
if (!upstreamResponsesResult.ok) {
|
|
470
|
+
recordFailure(entry.name);
|
|
471
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
472
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// fallthrough to chat/completions conversion
|
|
477
|
+
recordSuccess(entry.name);
|
|
478
|
+
const converted = convertResponsesRequestToChatCompletions(responsesRequest);
|
|
479
|
+
if (converted.error) {
|
|
480
|
+
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
481
|
+
res.end(JSON.stringify({ error: converted.error }));
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
const chatUrl = joinApiUrl(upstreamBase, 'chat/completions');
|
|
485
|
+
const chatResult = await retryTransientRequest(() => proxyRequestJson(chatUrl, {
|
|
486
|
+
method: 'POST',
|
|
487
|
+
body: JSON.stringify(converted.chat),
|
|
488
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}), 'Content-Type': 'application/json' },
|
|
489
|
+
maxBytes: maxUpstreamBytes,
|
|
490
|
+
httpAgent,
|
|
491
|
+
httpsAgent
|
|
492
|
+
}));
|
|
493
|
+
if (!chatResult.ok) {
|
|
494
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
495
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${chatResult.error}` }));
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const chatJson = parseJsonOrError(chatResult.bodyText);
|
|
499
|
+
if (chatResult.status >= 400) {
|
|
500
|
+
res.writeHead(chatResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
501
|
+
res.end(chatResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (chatJson.error) {
|
|
505
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
506
|
+
res.end(JSON.stringify({ error: `Upstream parse failed: ${chatJson.error}` }));
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
const extracted = extractChatCompletionResult(chatJson.value);
|
|
510
|
+
const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
|
|
511
|
+
const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
|
|
512
|
+
const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
|
|
513
|
+
const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, chatJson.value);
|
|
514
|
+
if (wantsSse) {
|
|
515
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
516
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
517
|
+
sendResponsesSse(res, responsesPayload);
|
|
518
|
+
res.end();
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
522
|
+
res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// passthrough for other v1/* paths
|
|
527
|
+
const upstreamUrl = joinApiUrl(upstreamBase, normalizedSuffix);
|
|
528
|
+
const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
|
|
529
|
+
method: req.method || 'GET',
|
|
530
|
+
body: null,
|
|
531
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
532
|
+
maxBytes: maxUpstreamBytes,
|
|
533
|
+
httpAgent,
|
|
534
|
+
httpsAgent
|
|
535
|
+
}));
|
|
536
|
+
if (!upstreamResult.ok) {
|
|
537
|
+
recordFailure(entry.name);
|
|
538
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
539
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
recordSuccess(entry.name);
|
|
543
|
+
res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
544
|
+
res.end(upstreamResult.bodyText);
|
|
545
|
+
} catch (e) {
|
|
546
|
+
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
547
|
+
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
|
|
548
|
+
}
|
|
549
|
+
})();
|
|
550
|
+
return true;
|
|
551
|
+
};
|
|
552
|
+
|
|
553
|
+
return handler;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
module.exports = { createLocalBridgeHttpHandler };
|