codexmate 0.0.32 → 0.0.33

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