codexmate 0.0.32 → 0.0.34

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 (148) hide show
  1. package/README.md +147 -363
  2. package/README.zh.md +147 -371
  3. package/cli/agents-files.js +230 -224
  4. package/cli/archive-helpers.js +453 -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 +556 -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 +171 -0
  23. package/cli/zip-commands.js +510 -510
  24. package/cli.js +16079 -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 +154 -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 +654 -647
  54. package/web-ui/index.html +37 -36
  55. package/web-ui/logic.agents-diff.mjs +386 -386
  56. package/web-ui/logic.claude.mjs +172 -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 +306 -200
  70. package/web-ui/modules/app.methods.codex-config.mjs +869 -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 +788 -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 +1011 -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 +547 -537
  84. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  85. package/web-ui/modules/app.methods.webhook.mjs +87 -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 +3195 -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/modal-webhook.html +42 -0
  105. package/web-ui/partials/index/modals-basic.html +223 -162
  106. package/web-ui/partials/index/panel-config-claude.html +155 -136
  107. package/web-ui/partials/index/panel-config-codex.html +176 -196
  108. package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
  109. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  110. package/web-ui/partials/index/panel-dashboard.html +186 -219
  111. package/web-ui/partials/index/panel-docs.html +114 -114
  112. package/web-ui/partials/index/panel-market.html +177 -177
  113. package/web-ui/partials/index/panel-orchestration.html +391 -391
  114. package/web-ui/partials/index/panel-plugins.html +253 -253
  115. package/web-ui/partials/index/panel-sessions.html +319 -313
  116. package/web-ui/partials/index/panel-settings.html +158 -190
  117. package/web-ui/partials/index/panel-trash.html +82 -82
  118. package/web-ui/partials/index/panel-usage.html +137 -137
  119. package/web-ui/res/json5.min.js +1 -1
  120. package/web-ui/res/vue.global.prod.js +13 -13
  121. package/web-ui/session-helpers.mjs +591 -591
  122. package/web-ui/source-bundle.cjs +233 -233
  123. package/web-ui/styles/base-theme.css +281 -281
  124. package/web-ui/styles/bridge-pool.css +266 -197
  125. package/web-ui/styles/controls-forms.css +433 -433
  126. package/web-ui/styles/dashboard.css +406 -406
  127. package/web-ui/styles/docs-panel.css +245 -245
  128. package/web-ui/styles/feedback.css +108 -108
  129. package/web-ui/styles/health-check-dialog.css +144 -144
  130. package/web-ui/styles/layout-shell.css +628 -638
  131. package/web-ui/styles/modals-core.css +499 -466
  132. package/web-ui/styles/navigation-panels.css +391 -391
  133. package/web-ui/styles/openclaw-structured.css +266 -266
  134. package/web-ui/styles/plugins-panel.css +564 -564
  135. package/web-ui/styles/responsive.css +392 -392
  136. package/web-ui/styles/sessions-list.css +683 -647
  137. package/web-ui/styles/sessions-preview.css +407 -407
  138. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  139. package/web-ui/styles/sessions-usage.css +588 -588
  140. package/web-ui/styles/settings-panel.css +415 -349
  141. package/web-ui/styles/skills-list.css +305 -305
  142. package/web-ui/styles/skills-market.css +429 -429
  143. package/web-ui/styles/task-orchestration.css +822 -822
  144. package/web-ui/styles/titles-cards.css +472 -472
  145. package/web-ui/styles/trash-panel.css +90 -90
  146. package/web-ui/styles/webhook.css +115 -81
  147. package/web-ui/styles.css +24 -24
  148. package/web-ui.html +17 -17
@@ -1,324 +1,556 @@
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 : '', 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 };