codexmate 0.0.27 → 0.0.28

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 (137) hide show
  1. package/README.md +421 -421
  2. package/README.zh.md +354 -354
  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 +1620 -1299
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +1489 -1091
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -65
  15. package/cli/session-convert-io.js +82 -82
  16. package/cli/session-convert.js +43 -43
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15264 -15251
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +440 -379
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/download-artifacts.js +92 -92
  32. package/lib/mcp-stdio.js +453 -453
  33. package/lib/task-orchestrator.js +869 -869
  34. package/lib/text-diff.js +303 -303
  35. package/lib/workflow-engine.js +340 -340
  36. package/package.json +3 -1
  37. package/plugins/README.md +20 -20
  38. package/plugins/README.zh-CN.md +20 -20
  39. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  40. package/plugins/prompt-templates/computed.mjs +253 -253
  41. package/plugins/prompt-templates/index.mjs +8 -8
  42. package/plugins/prompt-templates/manifest.mjs +15 -15
  43. package/plugins/prompt-templates/methods.mjs +553 -619
  44. package/plugins/prompt-templates/overview.mjs +91 -90
  45. package/plugins/prompt-templates/ownership.mjs +19 -19
  46. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  47. package/plugins/prompt-templates/storage.mjs +64 -64
  48. package/plugins/registry.mjs +16 -16
  49. package/web-ui/app.js +625 -634
  50. package/web-ui/index.html +35 -35
  51. package/web-ui/logic.agents-diff.mjs +386 -386
  52. package/web-ui/logic.claude.mjs +168 -168
  53. package/web-ui/logic.codex.mjs +56 -0
  54. package/web-ui/logic.mjs +5 -5
  55. package/web-ui/logic.runtime.mjs +128 -128
  56. package/web-ui/logic.session-convert.mjs +70 -70
  57. package/web-ui/logic.sessions.mjs +765 -765
  58. package/web-ui/modules/api.mjs +90 -90
  59. package/web-ui/modules/app.computed.dashboard.mjs +225 -171
  60. package/web-ui/modules/app.computed.index.mjs +17 -17
  61. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  62. package/web-ui/modules/app.computed.session.mjs +994 -994
  63. package/web-ui/modules/app.constants.mjs +15 -15
  64. package/web-ui/modules/app.methods.agents.mjs +632 -632
  65. package/web-ui/modules/app.methods.claude-config.mjs +190 -184
  66. package/web-ui/modules/app.methods.codex-config.mjs +892 -860
  67. package/web-ui/modules/app.methods.index.mjs +92 -92
  68. package/web-ui/modules/app.methods.install.mjs +205 -205
  69. package/web-ui/modules/app.methods.navigation.mjs +743 -743
  70. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  71. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  72. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  73. package/web-ui/modules/app.methods.providers.mjs +412 -404
  74. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  75. package/web-ui/modules/app.methods.session-actions.mjs +593 -596
  76. package/web-ui/modules/app.methods.session-browser.mjs +984 -989
  77. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  78. package/web-ui/modules/app.methods.session-trash.mjs +439 -439
  79. package/web-ui/modules/app.methods.startup-claude.mjs +533 -526
  80. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  81. package/web-ui/modules/config-mode.computed.mjs +124 -124
  82. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  83. package/web-ui/modules/i18n.dict.mjs +2109 -2131
  84. package/web-ui/modules/i18n.mjs +56 -56
  85. package/web-ui/modules/plugins.computed.mjs +3 -3
  86. package/web-ui/modules/plugins.methods.mjs +3 -3
  87. package/web-ui/modules/plugins.storage.mjs +11 -11
  88. package/web-ui/modules/provider-url-display.mjs +17 -0
  89. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  90. package/web-ui/modules/skills.computed.mjs +107 -107
  91. package/web-ui/modules/skills.methods.mjs +481 -481
  92. package/web-ui/partials/index/layout-footer.html +13 -13
  93. package/web-ui/partials/index/layout-header.html +475 -475
  94. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  95. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  96. package/web-ui/partials/index/modal-health-check.html +45 -45
  97. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  98. package/web-ui/partials/index/modal-skills.html +200 -200
  99. package/web-ui/partials/index/modals-basic.html +165 -165
  100. package/web-ui/partials/index/panel-config-claude.html +188 -187
  101. package/web-ui/partials/index/panel-config-codex.html +312 -283
  102. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  103. package/web-ui/partials/index/panel-dashboard.html +186 -186
  104. package/web-ui/partials/index/panel-docs.html +147 -147
  105. package/web-ui/partials/index/panel-market.html +177 -177
  106. package/web-ui/partials/index/panel-orchestration.html +391 -391
  107. package/web-ui/partials/index/panel-plugins.html +253 -279
  108. package/web-ui/partials/index/panel-sessions.html +316 -326
  109. package/web-ui/partials/index/panel-settings.html +253 -274
  110. package/web-ui/partials/index/panel-usage.html +371 -371
  111. package/web-ui/res/json5.min.js +1 -1
  112. package/web-ui/res/vue.global.prod.js +13 -13
  113. package/web-ui/session-helpers.mjs +576 -576
  114. package/web-ui/source-bundle.cjs +233 -233
  115. package/web-ui/styles/base-theme.css +281 -268
  116. package/web-ui/styles/controls-forms.css +422 -423
  117. package/web-ui/styles/dashboard.css +274 -274
  118. package/web-ui/styles/docs-panel.css +247 -247
  119. package/web-ui/styles/feedback.css +108 -108
  120. package/web-ui/styles/health-check-dialog.css +144 -144
  121. package/web-ui/styles/layout-shell.css +606 -603
  122. package/web-ui/styles/modals-core.css +466 -464
  123. package/web-ui/styles/navigation-panels.css +391 -390
  124. package/web-ui/styles/openclaw-structured.css +266 -266
  125. package/web-ui/styles/plugins-panel.css +523 -523
  126. package/web-ui/styles/responsive.css +454 -454
  127. package/web-ui/styles/sessions-list.css +419 -415
  128. package/web-ui/styles/sessions-preview.css +411 -411
  129. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  130. package/web-ui/styles/sessions-usage.css +1040 -1040
  131. package/web-ui/styles/settings-panel.css +185 -185
  132. package/web-ui/styles/skills-list.css +303 -303
  133. package/web-ui/styles/skills-market.css +406 -406
  134. package/web-ui/styles/task-orchestration.css +822 -822
  135. package/web-ui/styles/titles-cards.css +472 -408
  136. package/web-ui/styles.css +21 -21
  137. package/web-ui.html +17 -17
@@ -1,1091 +1,1489 @@
1
- const http = require('http');
2
- const https = require('https');
3
- const crypto = require('crypto');
4
- const { readJsonFile, writeJsonAtomic } = require('../lib/cli-file-utils');
5
- const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
6
-
7
- const DEFAULT_BRIDGE_TOKEN = 'codexmate';
8
- const SETTINGS_VERSION = 1;
9
-
10
- function normalizeText(value) {
11
- return typeof value === 'string' ? value.trim() : '';
12
- }
13
-
14
- function normalizeProviderName(value) {
15
- // Provider name validation is done elsewhere; keep this conservative.
16
- return normalizeText(value);
17
- }
18
-
19
- function normalizeOpenaiUpstreamBaseUrl(rawValue) {
20
- const normalized = normalizeBaseUrl(rawValue);
21
- if (!normalized) return '';
22
- try {
23
- const parsed = new URL(normalized);
24
- let pathname = String(parsed.pathname || '').replace(/\/+$/g, '');
25
-
26
- // If user accidentally pasted a full endpoint, strip it back to the base URL.
27
- // Keep direct provider routes (e.g. /project/ym) intact.
28
- pathname = pathname
29
- .replace(/\/v1\/chat\/completions$/i, '/v1')
30
- .replace(/\/chat\/completions$/i, '')
31
- .replace(/\/v1\/responses$/i, '/v1')
32
- .replace(/\/responses$/i, '')
33
- .replace(/\/v1\/models$/i, '/v1')
34
- .replace(/\/models$/i, '');
35
-
36
- // Normalize empty/root path.
37
- if (pathname === '/') pathname = '';
38
-
39
- const rebuilt = `${parsed.origin}${pathname}`;
40
- return normalizeBaseUrl(rebuilt);
41
- } catch (_) {
42
- return normalized;
43
- }
44
- }
45
-
46
- function normalizeUpstreamEntry(entry) {
47
- if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
48
- return null;
49
- }
50
- const baseUrl = normalizeOpenaiUpstreamBaseUrl(entry.baseUrl || entry.base_url || '');
51
- const apiKey = normalizeText(entry.apiKey || entry.api_key || entry.key || '');
52
- const headersRaw = entry.headers || entry.extraHeaders || entry.extra_headers || null;
53
- const headers = normalizeHeadersMap(headersRaw);
54
- if (!baseUrl || !isValidHttpUrl(baseUrl)) {
55
- return null;
56
- }
57
- return { baseUrl, apiKey, headers };
58
- }
59
-
60
- function normalizeHeadersMap(value) {
61
- if (!value || typeof value !== 'object' || Array.isArray(value)) {
62
- return {};
63
- }
64
- const forbidden = new Set([
65
- 'authorization',
66
- 'host',
67
- 'content-length',
68
- 'connection',
69
- 'transfer-encoding',
70
- 'keep-alive',
71
- 'proxy-authenticate',
72
- 'proxy-authorization',
73
- 'te',
74
- 'trailer',
75
- 'upgrade'
76
- ]);
77
- const result = {};
78
- for (const [rawKey, rawVal] of Object.entries(value)) {
79
- const key = typeof rawKey === 'string' ? rawKey.trim() : '';
80
- if (!key) continue;
81
- const lower = key.toLowerCase();
82
- if (forbidden.has(lower)) continue;
83
- if (typeof rawVal !== 'string') continue;
84
- result[key] = rawVal;
85
- }
86
- return result;
87
- }
88
-
89
- function readOpenaiBridgeSettings(filePath) {
90
- const parsed = readJsonFile(filePath, null);
91
- const providers = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
92
- ? parsed.providers
93
- : null;
94
- const providerMap = providers && typeof providers === 'object' && !Array.isArray(providers)
95
- ? providers
96
- : {};
97
- return {
98
- version: SETTINGS_VERSION,
99
- providers: providerMap
100
- };
101
- }
102
-
103
- function upsertOpenaiBridgeProvider(filePath, providerName, upstreamBaseUrl, apiKey, headers) {
104
- const name = normalizeProviderName(providerName);
105
- const baseUrl = normalizeOpenaiUpstreamBaseUrl(upstreamBaseUrl);
106
- const key = normalizeText(apiKey);
107
- const nextHeaders = normalizeHeadersMap(headers);
108
-
109
- if (!name) {
110
- return { error: 'Provider name is required' };
111
- }
112
- if (!baseUrl || !isValidHttpUrl(baseUrl)) {
113
- return { error: 'Upstream base URL is invalid' };
114
- }
115
-
116
- const settings = readOpenaiBridgeSettings(filePath);
117
- const existing = settings && settings.providers ? settings.providers[name] : null;
118
- const existingHeaders = existing && typeof existing === 'object' && !Array.isArray(existing)
119
- ? normalizeHeadersMap(existing.headers || existing.extraHeaders || existing.extra_headers || null)
120
- : {};
121
- const next = {
122
- version: SETTINGS_VERSION,
123
- providers: {
124
- ...(settings.providers || {}),
125
- [name]: {
126
- baseUrl,
127
- apiKey: key,
128
- headers: Object.keys(nextHeaders).length ? nextHeaders : existingHeaders
129
- }
130
- }
131
- };
132
- writeJsonAtomic(filePath, next);
133
- return { success: true };
134
- }
135
-
136
- function resolveOpenaiBridgeUpstream(filePath, providerName) {
137
- const name = normalizeProviderName(providerName);
138
- if (!name) return { error: 'Provider name is required' };
139
- const settings = readOpenaiBridgeSettings(filePath);
140
- const entry = settings.providers ? settings.providers[name] : null;
141
- const normalized = normalizeUpstreamEntry(entry);
142
- if (!normalized) {
143
- return { error: `OpenAI 转换未配置: ${name}` };
144
- }
145
- return { provider: name, ...normalized };
146
- }
147
-
148
- function extractAuthorizationToken(req) {
149
- const header = typeof req.headers.authorization === 'string' ? req.headers.authorization.trim() : '';
150
- if (!header) return '';
151
- if (/^bearer\s+/i.test(header)) {
152
- return header.replace(/^bearer\s+/i, '').trim();
153
- }
154
- return header;
155
- }
156
-
157
- function readRequestBody(req, maxBytes) {
158
- return new Promise((resolve) => {
159
- let body = '';
160
- let size = 0;
161
- let aborted = false;
162
- req.on('data', (chunk) => {
163
- if (aborted) return;
164
- size += chunk.length;
165
- if (Number.isFinite(maxBytes) && maxBytes > 0 && size > maxBytes) {
166
- aborted = true;
167
- try { req.destroy(); } catch (_) {}
168
- resolve({ error: '请求体过大' });
169
- return;
170
- }
171
- body += chunk;
172
- });
173
- req.on('end', () => {
174
- if (aborted) return;
175
- resolve({ body });
176
- });
177
- req.on('error', (err) => resolve({ error: err && err.message ? err.message : 'request failed' }));
178
- });
179
- }
180
-
181
- function parseJsonOrError(text) {
182
- if (typeof text !== 'string' || !text.trim()) {
183
- return { value: null, error: 'empty body' };
184
- }
185
- try {
186
- return { value: JSON.parse(text), error: '' };
187
- } catch (e) {
188
- return { value: null, error: e && e.message ? e.message : 'invalid json' };
189
- }
190
- }
191
-
192
- function extractChatCompletionResult(payload) {
193
- if (!payload || typeof payload !== 'object') return { text: '', toolCalls: [] };
194
- const choice = Array.isArray(payload.choices) ? payload.choices[0] : null;
195
- const message = choice && typeof choice === 'object' ? choice.message : null;
196
- const toolCalls = message && typeof message === 'object' && Array.isArray(message.tool_calls)
197
- ? message.tool_calls
198
- : [];
199
- const content = message && typeof message === 'object' ? message.content : '';
200
- let text = '';
201
- if (typeof content === 'string') {
202
- text = content;
203
- } else if (Array.isArray(content)) {
204
- text = content
205
- .map((item) => {
206
- if (!item) return '';
207
- if (typeof item === 'string') return item;
208
- if (typeof item === 'object') {
209
- if (typeof item.text === 'string') return item.text;
210
- if (typeof item.content === 'string') return item.content;
211
- }
212
- return '';
213
- })
214
- .filter(Boolean)
215
- .join('');
216
- }
217
- return { text, toolCalls };
218
- }
219
-
220
- function normalizeResponsesInputToChatMessages(input) {
221
- // 支持:
222
- // - string
223
- // - { role, content }(单条 message)
224
- // - { type:"input_text"|"input_image", ... }(单个 block)
225
- // - [{ role, content: [...] }](messages array)
226
- // - [{ type:"input_text"|"input_image", ... }](blocks array -> 单条 user 消息)
227
- if (typeof input === 'string') {
228
- return [{ role: 'user', content: input }];
229
- }
230
-
231
- const toChatContent = (blocks) => {
232
- if (!Array.isArray(blocks)) return '';
233
- const out = [];
234
- for (const block of blocks) {
235
- if (!block || typeof block !== 'object') continue;
236
- const type = typeof block.type === 'string' ? block.type : '';
237
- if ((type === 'input_text' || type === 'output_text') && typeof block.text === 'string') {
238
- out.push({ type: 'text', text: block.text });
239
- continue;
240
- }
241
- if ((type === 'reasoning' || type === 'reasoning_text' || type === 'reasoning_content') && typeof block.text === 'string') {
242
- out.push({ type: 'text', text: block.text });
243
- continue;
244
- }
245
- if (type === 'input_image') {
246
- const raw = block.image_url != null ? block.image_url : block.imageUrl;
247
- const url = typeof raw === 'string'
248
- ? raw
249
- : (raw && typeof raw === 'object' && typeof raw.url === 'string' ? raw.url : '');
250
- if (url) {
251
- out.push({ type: 'image_url', image_url: { url } });
252
- }
253
- continue;
254
- }
255
- // 容错:兼容已是 chat content 的 {type:"text"} / {type:"image_url"}
256
- if (type === 'text' && typeof block.text === 'string') {
257
- out.push({ type: 'text', text: block.text });
258
- continue;
259
- }
260
- if (type === 'image_url' && block.image_url) {
261
- out.push({ type: 'image_url', image_url: block.image_url });
262
- continue;
263
- }
264
- const text = typeof block.text === 'string'
265
- ? block.text
266
- : (typeof block.content === 'string' ? block.content : '');
267
- if (text) {
268
- out.push({ type: 'text', text });
269
- continue;
270
- }
271
- try {
272
- const raw = JSON.stringify(block);
273
- if (raw) {
274
- out.push({ type: 'text', text: raw.slice(0, 4000) });
275
- }
276
- } catch (_) {}
277
- }
278
- if (out.length === 0) return '';
279
- return out;
280
- };
281
-
282
- const toRole = (value) => {
283
- const roleRaw = typeof value === 'string' ? value.trim().toLowerCase() : '';
284
- return roleRaw === 'assistant' ? 'assistant' : (roleRaw === 'system' ? 'system' : 'user');
285
- };
286
-
287
- if (input && typeof input === 'object' && !Array.isArray(input)) {
288
- if (typeof input.role === 'string' && input.content != null) {
289
- const role = toRole(input.role);
290
- const content = Array.isArray(input.content)
291
- ? toChatContent(input.content)
292
- : input.content;
293
- return content ? [{ role, content }] : [];
294
- }
295
- if (typeof input.type === 'string') {
296
- const content = toChatContent([input]);
297
- return content ? [{ role: 'user', content }] : [];
298
- }
299
- return [];
300
- }
301
-
302
- if (!Array.isArray(input)) {
303
- return [];
304
- }
305
-
306
- const messages = [];
307
- for (const item of input) {
308
- if (!item || typeof item !== 'object') continue;
309
-
310
- // Tool calls (Responses): { type: "function_call", call_id, name, arguments }
311
- // Chat Completions equivalent: assistant message with tool_calls
312
- if (typeof item.type === 'string' && item.type === 'function_call') {
313
- const callId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
314
- const name = typeof item.name === 'string' ? item.name.trim() : '';
315
- const args = typeof item.arguments === 'string' ? item.arguments : '';
316
- if (callId && name) {
317
- messages.push({
318
- role: 'assistant',
319
- tool_calls: [{
320
- id: callId,
321
- type: 'function',
322
- function: { name, arguments: args || '' }
323
- }]
324
- });
325
- }
326
- continue;
327
- }
328
-
329
- // Tool results (Responses): { type: "function_call_output", call_id, output }
330
- // Chat Completions equivalent: { role: "tool", tool_call_id, content }
331
- if (typeof item.type === 'string' && item.type === 'function_call_output') {
332
- const toolCallId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
333
- let content = item.output;
334
- if (typeof content !== 'string') {
335
- try {
336
- content = JSON.stringify(content);
337
- } catch (_) {
338
- content = String(content ?? '');
339
- }
340
- }
341
- if (toolCallId) {
342
- messages.push({ role: 'tool', tool_call_id: toolCallId, content: String(content || '') });
343
- }
344
- continue;
345
- }
346
-
347
- // message form
348
- if (typeof item.role === 'string' && item.content != null) {
349
- const role = toRole(item.role);
350
- const content = Array.isArray(item.content)
351
- ? toChatContent(item.content)
352
- : item.content;
353
- if (content) {
354
- messages.push({ role, content });
355
- }
356
- continue;
357
- }
358
- }
359
-
360
- if (messages.length > 0) {
361
- return messages;
362
- }
363
-
364
- // 退化:把 input array 当作单条 user content blocks
365
- const fallbackContent = toChatContent(input);
366
- if (fallbackContent) {
367
- return [{ role: 'user', content: fallbackContent }];
368
- }
369
- return [];
370
- }
371
-
372
-
373
- function normalizeResponsesToolsToChatTools(tools) {
374
- if (!Array.isArray(tools)) return tools;
375
- return tools
376
- .map((tool) => {
377
- if (!tool || typeof tool !== 'object') return null;
378
- if (tool.type !== 'function') return null;
379
- const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
380
- ? tool.function
381
- : {};
382
- const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
383
- ? sourceFn.name.trim()
384
- : (typeof tool.name === 'string' ? tool.name.trim() : '');
385
- if (!name) return null;
386
- const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
387
- ? sourceFn.parameters
388
- : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : {});
389
- const fn = { name, parameters };
390
- const description = typeof sourceFn.description === 'string'
391
- ? sourceFn.description
392
- : (typeof tool.description === 'string' ? tool.description : undefined);
393
- const strict = typeof sourceFn.strict === 'boolean'
394
- ? sourceFn.strict
395
- : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
396
- if (description !== undefined) fn.description = description;
397
- if (strict !== undefined) fn.strict = strict;
398
- return { type: 'function', function: fn };
399
- })
400
- .filter(Boolean);
401
- }
402
-
403
- function normalizeResponsesToolChoiceToChatToolChoice(toolChoice) {
404
- if (!toolChoice || typeof toolChoice !== 'object' || Array.isArray(toolChoice)) return toolChoice;
405
- if (toolChoice.type === 'function' && typeof toolChoice.name === 'string' && toolChoice.name.trim()) {
406
- return { type: 'function', function: { name: toolChoice.name.trim() } };
407
- }
408
- return toolChoice;
409
- }
410
-
411
- function normalizeResponsesToolsForResponsesApi(tools) {
412
- if (!Array.isArray(tools)) return tools;
413
- return tools
414
- .map((tool) => {
415
- if (!tool || typeof tool !== 'object') return null;
416
- if (tool.type !== 'function') return null;
417
- const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
418
- ? tool.function
419
- : {};
420
- const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
421
- ? sourceFn.name.trim()
422
- : (typeof tool.name === 'string' ? tool.name.trim() : '');
423
- if (!name) return null;
424
- const out = { type: 'function', name };
425
- const description = typeof sourceFn.description === 'string'
426
- ? sourceFn.description
427
- : (typeof tool.description === 'string' ? tool.description : undefined);
428
- const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
429
- ? sourceFn.parameters
430
- : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : undefined);
431
- const strict = typeof sourceFn.strict === 'boolean'
432
- ? sourceFn.strict
433
- : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
434
- if (description !== undefined) out.description = description;
435
- if (parameters !== undefined) out.parameters = parameters;
436
- if (strict !== undefined) out.strict = strict;
437
- return out;
438
- })
439
- .filter(Boolean);
440
- }
441
-
442
- function convertResponsesRequestToChatCompletions(payload) {
443
- const body = payload && typeof payload === 'object' ? payload : {};
444
- const model = typeof body.model === 'string' ? body.model.trim() : '';
445
- if (!model) {
446
- return { error: 'responses 请求缺少 model' };
447
- }
448
-
449
- const messages = [];
450
- // Align with Maxx/CLIProxyAPI style: map "instructions" to a leading system message.
451
- if (typeof body.instructions === 'string' && body.instructions.trim()) {
452
- messages.push({ role: 'system', content: body.instructions.trim() });
453
- }
454
- messages.push(...normalizeResponsesInputToChatMessages(body.input));
455
- if (!messages.length) {
456
- // codex sometimes sends empty input for probes; tolerate.
457
- messages.push({ role: 'user', content: '' });
458
- }
459
-
460
- const maxOutputTokens = Number.parseInt(String(body.max_output_tokens), 10);
461
- const stream = body.stream === true;
462
-
463
- const chat = {
464
- model,
465
- messages,
466
- stream: false,
467
- temperature: Number.isFinite(body.temperature) ? Number(body.temperature) : undefined,
468
- top_p: Number.isFinite(body.top_p) ? Number(body.top_p) : undefined,
469
- max_tokens: Number.isFinite(maxOutputTokens) && maxOutputTokens > 0 ? maxOutputTokens : undefined
470
- };
471
- if (Array.isArray(body.stop) && body.stop.length) {
472
- chat.stop = body.stop.filter((item) => typeof item === 'string' && item.trim());
473
- }
474
- if (Array.isArray(body.tools) && body.tools.length) {
475
- chat.tools = normalizeResponsesToolsToChatTools(body.tools);
476
- }
477
- if (body.tool_choice !== undefined) {
478
- chat.tool_choice = normalizeResponsesToolChoiceToChatToolChoice(body.tool_choice);
479
- }
480
- if (body.response_format !== undefined) {
481
- chat.response_format = body.response_format;
482
- }
483
- if (body.metadata !== undefined) {
484
- chat.metadata = body.metadata;
485
- }
486
-
487
- // Remove undefined keys
488
- Object.keys(chat).forEach((key) => chat[key] === undefined && delete chat[key]);
489
-
490
- return { chat, streamRequested: stream };
491
- }
492
-
493
- function buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamPayload) {
494
- const responseId = `resp_${crypto.randomBytes(10).toString('hex')}`;
495
- const usage = upstreamPayload && upstreamPayload.usage && typeof upstreamPayload.usage === 'object'
496
- ? upstreamPayload.usage
497
- : null;
498
- const createdAt = Math.floor(Date.now() / 1000);
499
- const output = [];
500
- const trimmedText = typeof text === 'string' ? text : '';
501
- if (trimmedText) {
502
- output.push({
503
- id: `msg_${crypto.randomBytes(8).toString('hex')}`,
504
- type: 'message',
505
- role: 'assistant',
506
- content: [{ type: 'output_text', text: trimmedText }]
507
- });
508
- }
509
-
510
- // Convert chat.completions tool_calls into Responses-style function_call output items.
511
- // This is important for Codex, which appends function_call + function_call_output back into `input`.
512
- if (Array.isArray(toolCalls)) {
513
- for (const call of toolCalls) {
514
- if (!call || typeof call !== 'object') continue;
515
- const callId = typeof call.id === 'string' && call.id.trim() ? call.id.trim() : `call_${crypto.randomBytes(8).toString('hex')}`;
516
- const fn = call.function && typeof call.function === 'object' ? call.function : {};
517
- const name = typeof fn.name === 'string' ? fn.name : '';
518
- const args = typeof fn.arguments === 'string' ? fn.arguments : '';
519
- if (!name) continue;
520
- output.push({
521
- type: 'function_call',
522
- call_id: callId,
523
- name,
524
- arguments: args
525
- });
526
- }
527
- }
528
-
529
- const payload = {
530
- id: responseId,
531
- object: 'response',
532
- model,
533
- created_at: createdAt,
534
- status: 'completed',
535
- output,
536
- output_text: trimmedText
537
- };
538
-
539
- if (usage) {
540
- // Map chat.completions usage -> responses usage shape when possible.
541
- const promptTokens = Number.isFinite(usage.prompt_tokens) ? Number(usage.prompt_tokens) : null;
542
- const completionTokens = Number.isFinite(usage.completion_tokens) ? Number(usage.completion_tokens) : null;
543
- const totalTokens = Number.isFinite(usage.total_tokens) ? Number(usage.total_tokens) : null;
544
- if (promptTokens !== null || completionTokens !== null || totalTokens !== null) {
545
- payload.usage = {
546
- input_tokens: promptTokens ?? undefined,
547
- output_tokens: completionTokens ?? undefined,
548
- total_tokens: totalTokens ?? undefined
549
- };
550
- Object.keys(payload.usage).forEach((key) => payload.usage[key] === undefined && delete payload.usage[key]);
551
- } else {
552
- payload.usage = usage;
553
- }
554
- }
555
-
556
- return payload;
557
- }
558
-
559
- function ensureResponseMetadata(response) {
560
- const payload = response && typeof response === 'object' ? response : {};
561
- if (typeof payload.object !== 'string' || !payload.object.trim()) {
562
- payload.object = 'response';
563
- }
564
- if (typeof payload.created_at !== 'number') {
565
- payload.created_at = Math.floor(Date.now() / 1000);
566
- }
567
- if (typeof payload.status !== 'string' || !payload.status.trim()) {
568
- payload.status = 'completed';
569
- }
570
- if (!Array.isArray(payload.output)) {
571
- payload.output = [];
572
- }
573
- return payload;
574
- }
575
-
576
- function sendResponsesSse(res, responsePayload) {
577
- const response = ensureResponseMetadata(responsePayload);
578
- const responseId = typeof response.id === 'string' && response.id.trim()
579
- ? response.id.trim()
580
- : `resp_${crypto.randomBytes(10).toString('hex')}`;
581
- const model = typeof response.model === 'string' ? response.model : '';
582
-
583
- let sequence = 0;
584
- const nextSeq = () => {
585
- sequence += 1;
586
- return sequence;
587
- };
588
-
589
- writeSse(res, 'response.created', {
590
- type: 'response.created',
591
- response: {
592
- id: responseId,
593
- model,
594
- created_at: response.created_at
595
- }
596
- });
597
-
598
- const output = Array.isArray(response.output) ? response.output : [];
599
- for (let outputIndex = 0; outputIndex < output.length; outputIndex += 1) {
600
- const item = output[outputIndex];
601
- if (!item || typeof item !== 'object') continue;
602
- const itemType = typeof item.type === 'string' ? item.type : '';
603
- const itemId = typeof item.id === 'string' && item.id.trim()
604
- ? item.id.trim()
605
- : (typeof item.call_id === 'string' && item.call_id.trim() ? item.call_id.trim() : `item_${crypto.randomBytes(8).toString('hex')}`);
606
-
607
- // Emit item added so Codex can anchor subsequent deltas by output_index/content_index/item_id.
608
- writeSse(res, 'response.output_item.added', {
609
- type: 'response.output_item.added',
610
- output_index: outputIndex,
611
- item: { ...item, id: itemId }
612
- });
613
-
614
- if (itemType === 'message') {
615
- const content = Array.isArray(item.content) ? item.content : [];
616
- for (let contentIndex = 0; contentIndex < content.length; contentIndex += 1) {
617
- const block = content[contentIndex];
618
- if (!block || typeof block !== 'object') continue;
619
- if (block.type !== 'output_text') continue;
620
- const text = typeof block.text === 'string' ? block.text : '';
621
- if (text) {
622
- writeSse(res, 'response.output_text.delta', {
623
- type: 'response.output_text.delta',
624
- item_id: itemId,
625
- output_index: outputIndex,
626
- content_index: contentIndex,
627
- delta: text,
628
- sequence_number: nextSeq()
629
- });
630
- }
631
- writeSse(res, 'response.output_text.done', {
632
- type: 'response.output_text.done',
633
- item_id: itemId,
634
- output_index: outputIndex,
635
- content_index: contentIndex,
636
- text,
637
- sequence_number: nextSeq()
638
- });
639
- }
640
- }
641
-
642
- // Emit item done for all item types (message/function_call/etc).
643
- writeSse(res, 'response.output_item.done', {
644
- type: 'response.output_item.done',
645
- output_index: outputIndex,
646
- item: { ...item, id: itemId },
647
- sequence_number: nextSeq()
648
- });
649
- }
650
-
651
- writeSse(res, 'response.completed', { type: 'response.completed', response });
652
- writeSse(res, 'done', '[DONE]');
653
- }
654
-
655
- function extractResponsesOutputText(payload) {
656
- if (!payload || typeof payload !== 'object') return '';
657
- const output = Array.isArray(payload.output) ? payload.output : [];
658
- for (const item of output) {
659
- if (!item || typeof item !== 'object') continue;
660
- if (item.type !== 'message') continue;
661
- const content = Array.isArray(item.content) ? item.content : [];
662
- for (const block of content) {
663
- if (!block || typeof block !== 'object') continue;
664
- if (block.type !== 'output_text') continue;
665
- if (typeof block.text === 'string') return block.text;
666
- }
667
- }
668
- if (typeof payload.output_text === 'string') return payload.output_text;
669
- return '';
670
- }
671
-
672
- function toUpstreamNonStreamingResponsesPayload(payload) {
673
- const body = payload && typeof payload === 'object' ? payload : {};
674
- const normalized = { ...body, stream: false };
675
- if (Array.isArray(body.tools)) {
676
- normalized.tools = normalizeResponsesToolsForResponsesApi(body.tools);
677
- }
678
- return normalized;
679
- }
680
-
681
- function shouldFallbackFromUpstreamResponses(status, bodyText) {
682
- if (!Number.isFinite(status)) return false;
683
- // Common "unsupported" status codes for a route.
684
- if (status === 404 || status === 405 || status === 501) return true;
685
-
686
- // Some OpenAI-compatible gateways respond with 500 + "not implemented" (e.g. convert_request_failed)
687
- // instead of 404/405 for unsupported endpoints. In that case we can safely fallback to chat/completions.
688
- const text = String(bodyText || '');
689
- if (!text) return false;
690
- if (/not implemented/i.test(text)) return true;
691
- if (/convert_request_failed/i.test(text)) return true;
692
- if (/unknown (endpoint|route)/i.test(text)) return true;
693
- if (/unsupported.*\/?v1\/responses/i.test(text)) return true;
694
- if (/does not support.*responses/i.test(text)) return true;
695
- if (/name['"`]?\s+is a required property/i.test(text) && /tools/i.test(text) && /function/i.test(text)) return true;
696
-
697
- // Best-effort parse for structured error codes.
698
- try {
699
- const parsed = JSON.parse(text);
700
- const code = parsed && parsed.error && typeof parsed.error.code === 'string' ? parsed.error.code : '';
701
- const msg = parsed && parsed.error && typeof parsed.error.message === 'string' ? parsed.error.message : '';
702
- if (code === 'convert_request_failed') return true;
703
- if (/not implemented/i.test(msg)) return true;
704
- if (/unknown (endpoint|route)/i.test(msg)) return true;
705
- if (/unsupported.*\/?v1\/responses/i.test(msg)) return true;
706
- if (/does not support.*responses/i.test(msg)) return true;
707
- if (/name['"`]?\s+is a required property/i.test(msg) && /tools/i.test(msg) && /function/i.test(msg)) return true;
708
- } catch (_) {}
709
-
710
- return false;
711
- }
712
-
713
- function isLoopbackAddress(address) {
714
- if (!address) return false;
715
- const value = String(address);
716
- return value === '127.0.0.1' || value === '::1' || value === '::ffff:127.0.0.1';
717
- }
718
-
719
- function writeSse(res, eventName, dataObj) {
720
- if (eventName) {
721
- res.write(`event: ${eventName}\n`);
722
- }
723
- if (dataObj === '[DONE]') {
724
- res.write('data: [DONE]\n\n');
725
- return;
726
- }
727
- res.write(`data: ${JSON.stringify(dataObj)}\n\n`);
728
- }
729
-
730
- async function proxyRequestJson(targetUrl, options = {}) {
731
- const parsed = new URL(targetUrl);
732
- const transport = parsed.protocol === 'https:' ? https : http;
733
- const bodyText = options.body ? JSON.stringify(options.body) : '';
734
- const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
735
- ? Math.floor(options.maxBytes)
736
- : 0;
737
- const headers = {
738
- 'Accept': 'application/json',
739
- ...(options.body ? { 'Content-Type': 'application/json' } : {}),
740
- ...(options.headers || {})
741
- };
742
- if (options.body) {
743
- headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
744
- }
745
-
746
- const timeoutMs = Number.isFinite(options.timeoutMs)
747
- ? Math.max(1000, Number(options.timeoutMs))
748
- : 30000;
749
- return new Promise((resolve) => {
750
- let settled = false;
751
- const finish = (value) => {
752
- if (settled) return;
753
- settled = true;
754
- resolve(value);
755
- };
756
- const req = transport.request({
757
- protocol: parsed.protocol,
758
- hostname: parsed.hostname,
759
- port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
760
- method: options.method || 'GET',
761
- path: `${parsed.pathname}${parsed.search}`,
762
- headers,
763
- agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
764
- }, (upstreamRes) => {
765
- const chunks = [];
766
- let size = 0;
767
- upstreamRes.on('data', (chunk) => {
768
- if (!chunk) return;
769
- if (maxBytes > 0) {
770
- size += chunk.length;
771
- if (size > maxBytes) {
772
- chunks.length = 0;
773
- try { upstreamRes.destroy(new Error('response too large')); } catch (_) {}
774
- try { req.destroy(new Error('response too large')); } catch (_) {}
775
- finish({ ok: false, error: 'response too large' });
776
- return;
777
- }
778
- }
779
- chunks.push(chunk);
780
- });
781
- upstreamRes.on('end', () => {
782
- const text = chunks.length ? Buffer.concat(chunks).toString('utf-8') : '';
783
- finish({
784
- ok: true,
785
- status: upstreamRes.statusCode || 0,
786
- headers: upstreamRes.headers || {},
787
- bodyText: text
788
- });
789
- });
790
- });
791
- req.setTimeout(timeoutMs, () => {
792
- try { req.destroy(new Error('timeout')); } catch (_) {}
793
- finish({ ok: false, error: 'timeout' });
794
- });
795
- req.on('error', (err) => finish({ ok: false, error: err && err.message ? err.message : 'request failed' }));
796
- if (bodyText) {
797
- req.write(bodyText);
798
- }
799
- req.end();
800
- });
801
- }
802
-
803
- function createOpenaiBridgeHttpHandler(options = {}) {
804
- const settingsFile = options.settingsFile;
805
- const expectedTokenRaw = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
806
- const expectedToken = Object.prototype.hasOwnProperty.call(options, 'expectedToken')
807
- ? expectedTokenRaw
808
- : (expectedTokenRaw || DEFAULT_BRIDGE_TOKEN);
809
- const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
810
- const httpAgent = options.httpAgent;
811
- const httpsAgent = options.httpsAgent;
812
- const maxUpstreamBytes = Number.isFinite(options.maxUpstreamBytes) && options.maxUpstreamBytes > 0
813
- ? Math.floor(options.maxUpstreamBytes)
814
- : Math.max(16 * 1024 * 1024, maxBodySize > 0 ? maxBodySize * 4 : 0);
815
-
816
- if (!settingsFile) {
817
- throw new Error('createOpenaiBridgeHttpHandler 缺少 settingsFile');
818
- }
819
-
820
- const matchPath = (requestPath) => {
821
- const normalized = String(requestPath || '');
822
- const prefix = '/bridge/openai/';
823
- if (!normalized.startsWith(prefix)) return null;
824
- const rest = normalized.slice(prefix.length);
825
- const [provider, ...tail] = rest.split('/').filter((part) => part.length > 0);
826
- if (!provider) return null;
827
- const tailPath = '/' + tail.join('/');
828
- if (!tailPath.startsWith('/v1')) return null;
829
- const suffix = tailPath === '/v1' ? '' : tailPath.replace(/^\/v1\/?/, '');
830
- return { provider, suffix };
831
- };
832
-
833
- const handler = (req, res) => {
834
- let parsedUrl;
835
- try {
836
- parsedUrl = new URL(req.url || '/', 'http://localhost');
837
- } catch (_) {
838
- return false;
839
- }
840
- const match = matchPath(parsedUrl.pathname || '/');
841
- if (!match) return false;
842
-
843
- void (async () => {
844
- try {
845
- const token = extractAuthorizationToken(req);
846
- // 兼容:某些客户端在自定义 base_url 时可能不带 Authorization。
847
- // 为避免在 LAN 暴露无鉴权的代理,这里仅允许 loopback 连接缺省 token。
848
- const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
849
- const isLoopback = isLoopbackAddress(remoteAddr);
850
- if (!isLoopback && !expectedToken) {
851
- res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
852
- res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
853
- return;
854
- }
855
- if (!token && !isLoopback) {
856
- res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
857
- res.end(JSON.stringify({ error: 'Unauthorized' }));
858
- return;
859
- }
860
- // loopback 上的本地代理:允许客户端携带任意 Authorization(例如 Codex 会附带 provider apiKey)。
861
- // loopback 时仍强制校验 expectedToken,避免局域网被未授权调用。
862
- if (!isLoopback && token && token !== expectedToken) {
863
- res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
864
- res.end(JSON.stringify({ error: 'Unauthorized' }));
865
- return;
866
- }
867
-
868
- const upstream = resolveOpenaiBridgeUpstream(settingsFile, match.provider);
869
- if (upstream.error) {
870
- res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
871
- res.end(JSON.stringify({ error: upstream.error }));
872
- return;
873
- }
874
-
875
- const suffix = match.suffix || '';
876
- const normalizedSuffix = suffix.replace(/^\/+/, '');
877
-
878
- const authHeader = upstream.apiKey
879
- ? (/^bearer\s+/i.test(upstream.apiKey) ? upstream.apiKey : `Bearer ${upstream.apiKey}`)
880
- : '';
881
- const upstreamHeaders = upstream && upstream.headers && typeof upstream.headers === 'object' && !Array.isArray(upstream.headers)
882
- ? upstream.headers
883
- : {};
884
-
885
- if (!normalizedSuffix) {
886
- if ((req.method || 'GET').toUpperCase() !== 'GET') {
887
- res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
888
- res.end(JSON.stringify({ error: 'Method Not Allowed' }));
889
- return;
890
- }
891
- res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
892
- res.end(JSON.stringify({
893
- object: 'codexmate.openai_bridge',
894
- provider: match.provider,
895
- status: 'ok',
896
- endpoints: ['/v1/responses', '/v1/models']
897
- }));
898
- return;
899
- }
900
-
901
- if (normalizedSuffix === 'models') {
902
- if ((req.method || 'GET').toUpperCase() !== 'GET') {
903
- res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
904
- res.end(JSON.stringify({ error: 'Method Not Allowed' }));
905
- return;
906
- }
907
-
908
- const url = joinApiUrl(upstream.baseUrl, 'models');
909
- const result = await proxyRequestJson(url, {
910
- method: 'GET',
911
- headers: {
912
- ...(authHeader ? { Authorization: authHeader } : {}),
913
- ...upstreamHeaders
914
- },
915
- maxBytes: maxUpstreamBytes,
916
- httpAgent,
917
- httpsAgent
918
- });
919
- if (!result.ok) {
920
- res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
921
- res.end(JSON.stringify({ error: `Upstream request failed: ${result.error}` }));
922
- return;
923
- }
924
- res.writeHead(result.status || 502, { 'Content-Type': 'application/json; charset=utf-8' });
925
- res.end(result.bodyText || '');
926
- return;
927
- }
928
-
929
- if (normalizedSuffix !== 'responses') {
930
- res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
931
- res.end(JSON.stringify({ error: 'Not Found' }));
932
- return;
933
- }
934
-
935
- if ((req.method || 'GET').toUpperCase() !== 'POST') {
936
- res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
937
- res.end(JSON.stringify({ error: 'Method Not Allowed' }));
938
- return;
939
- }
940
-
941
- const { body, error: bodyErr } = await readRequestBody(req, maxBodySize);
942
- if (bodyErr) {
943
- res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
944
- res.end(JSON.stringify({ error: bodyErr }));
945
- return;
946
- }
947
- const parsed = parseJsonOrError(body);
948
- if (parsed.error) {
949
- res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
950
- res.end(JSON.stringify({ error: `Invalid JSON: ${parsed.error}` }));
951
- return;
952
- }
953
-
954
- const responsesRequest = parsed.value;
955
- const streamRequested = !!(responsesRequest && typeof responsesRequest === 'object' && responsesRequest.stream === true);
956
- const acceptHeader = req && req.headers ? (req.headers.accept || req.headers.Accept || '') : '';
957
- const wantsSse = /text\/event-stream/i.test(String(acceptHeader || ''));
958
-
959
- // Maxx-style behavior: prefer upstream /responses if supported.
960
- // Fallback to /chat/completions conversion when upstream does not implement /responses (404/405).
961
- const upstreamResponsesUrl = joinApiUrl(upstream.baseUrl, 'responses');
962
- const upstreamResponsesResult = await proxyRequestJson(upstreamResponsesUrl, {
963
- method: 'POST',
964
- body: toUpstreamNonStreamingResponsesPayload(responsesRequest),
965
- headers: {
966
- ...(authHeader ? { Authorization: authHeader } : {}),
967
- ...upstreamHeaders
968
- },
969
- maxBytes: maxUpstreamBytes,
970
- httpAgent,
971
- httpsAgent
972
- });
973
-
974
- if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 200 && upstreamResponsesResult.status < 300) {
975
- const upstreamJson = parseJsonOrError(upstreamResponsesResult.bodyText);
976
- if (upstreamJson.error) {
977
- res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
978
- res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
979
- return;
980
- }
981
- const upstreamPayload = upstreamJson.value;
982
- if (streamRequested && wantsSse) {
983
- res.writeHead(200, {
984
- 'Content-Type': 'text/event-stream; charset=utf-8',
985
- 'Cache-Control': 'no-cache',
986
- 'Connection': 'keep-alive',
987
- 'X-Accel-Buffering': 'no'
988
- });
989
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
990
- sendResponsesSse(res, upstreamPayload);
991
- res.end();
992
- return;
993
- }
994
-
995
- res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
996
- res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload)));
997
- return;
998
- }
999
-
1000
- if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400) {
1001
- if (!shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
1002
- res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
1003
- res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
1004
- return;
1005
- }
1006
- // fallthrough to chat/completions conversion
1007
- }
1008
-
1009
- if (!upstreamResponsesResult.ok) {
1010
- res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1011
- res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
1012
- return;
1013
- }
1014
-
1015
- const converted = convertResponsesRequestToChatCompletions(responsesRequest);
1016
- if (converted.error) {
1017
- res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
1018
- res.end(JSON.stringify({ error: converted.error }));
1019
- return;
1020
- }
1021
-
1022
- const upstreamUrl = joinApiUrl(upstream.baseUrl, 'chat/completions');
1023
- const upstreamResult = await proxyRequestJson(upstreamUrl, {
1024
- method: 'POST',
1025
- body: converted.chat,
1026
- headers: {
1027
- ...(authHeader ? { Authorization: authHeader } : {}),
1028
- ...upstreamHeaders
1029
- },
1030
- maxBytes: maxUpstreamBytes,
1031
- httpAgent,
1032
- httpsAgent
1033
- });
1034
- if (!upstreamResult.ok) {
1035
- res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1036
- res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
1037
- return;
1038
- }
1039
-
1040
- const upstreamJson = parseJsonOrError(upstreamResult.bodyText);
1041
- if (upstreamResult.status >= 400) {
1042
- res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
1043
- res.end(upstreamResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
1044
- return;
1045
- }
1046
- if (upstreamJson.error) {
1047
- res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1048
- res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
1049
- return;
1050
- }
1051
-
1052
- const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
1053
- const extracted = extractChatCompletionResult(upstreamJson.value);
1054
- const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
1055
- const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
1056
- const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamJson.value);
1057
-
1058
- if (converted.streamRequested && wantsSse) {
1059
- res.writeHead(200, {
1060
- 'Content-Type': 'text/event-stream; charset=utf-8',
1061
- 'Cache-Control': 'no-cache',
1062
- 'Connection': 'keep-alive',
1063
- 'X-Accel-Buffering': 'no'
1064
- });
1065
- if (typeof res.flushHeaders === 'function') res.flushHeaders();
1066
- sendResponsesSse(res, responsesPayload);
1067
- res.end();
1068
- return;
1069
- }
1070
-
1071
- res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1072
- res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
1073
- } catch (e) {
1074
- res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
1075
- res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
1076
- }
1077
- })();
1078
-
1079
- return true;
1080
- };
1081
-
1082
- handler.matchPath = matchPath;
1083
- return handler;
1084
- }
1085
-
1086
- module.exports = {
1087
- readOpenaiBridgeSettings,
1088
- upsertOpenaiBridgeProvider,
1089
- resolveOpenaiBridgeUpstream,
1090
- createOpenaiBridgeHttpHandler
1091
- };
1
+ const http = require('http');
2
+ const https = require('https');
3
+ const crypto = require('crypto');
4
+ const { readJsonFile, writeJsonAtomic } = require('../lib/cli-file-utils');
5
+ const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
6
+
7
+ const DEFAULT_BRIDGE_TOKEN = 'codexmate';
8
+ const SETTINGS_VERSION = 1;
9
+
10
+ function normalizeText(value) {
11
+ return typeof value === 'string' ? value.trim() : '';
12
+ }
13
+
14
+ function normalizeProviderName(value) {
15
+ // Provider name validation is done elsewhere; keep this conservative.
16
+ return normalizeText(value);
17
+ }
18
+
19
+ function normalizeOpenaiUpstreamBaseUrl(rawValue) {
20
+ const normalized = normalizeBaseUrl(rawValue);
21
+ if (!normalized) return '';
22
+ try {
23
+ const parsed = new URL(normalized);
24
+ let pathname = String(parsed.pathname || '').replace(/\/+$/g, '');
25
+
26
+ // If user accidentally pasted a full endpoint, strip it back to the base URL.
27
+ // Keep direct provider routes (e.g. /project/ym) intact.
28
+ pathname = pathname
29
+ .replace(/\/v1\/chat\/completions$/i, '/v1')
30
+ .replace(/\/chat\/completions$/i, '')
31
+ .replace(/\/v1\/responses$/i, '/v1')
32
+ .replace(/\/responses$/i, '')
33
+ .replace(/\/v1\/models$/i, '/v1')
34
+ .replace(/\/models$/i, '');
35
+
36
+ // Normalize empty/root path.
37
+ if (pathname === '/') pathname = '';
38
+
39
+ const rebuilt = `${parsed.origin}${pathname}`;
40
+ return normalizeBaseUrl(rebuilt);
41
+ } catch (_) {
42
+ return normalized;
43
+ }
44
+ }
45
+
46
+ function normalizeUpstreamEntry(entry) {
47
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
48
+ return null;
49
+ }
50
+ const baseUrl = normalizeOpenaiUpstreamBaseUrl(entry.baseUrl || entry.base_url || '');
51
+ const apiKey = normalizeText(entry.apiKey || entry.api_key || entry.key || '');
52
+ const headersRaw = entry.headers || entry.extraHeaders || entry.extra_headers || null;
53
+ const headers = normalizeHeadersMap(headersRaw);
54
+ if (!baseUrl || !isValidHttpUrl(baseUrl)) {
55
+ return null;
56
+ }
57
+ return { baseUrl, apiKey, headers };
58
+ }
59
+
60
+ function normalizeHeadersMap(value) {
61
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
62
+ return {};
63
+ }
64
+ const forbidden = new Set([
65
+ 'authorization',
66
+ 'host',
67
+ 'content-length',
68
+ 'connection',
69
+ 'transfer-encoding',
70
+ 'keep-alive',
71
+ 'proxy-authenticate',
72
+ 'proxy-authorization',
73
+ 'te',
74
+ 'trailer',
75
+ 'upgrade'
76
+ ]);
77
+ const result = {};
78
+ for (const [rawKey, rawVal] of Object.entries(value)) {
79
+ const key = typeof rawKey === 'string' ? rawKey.trim() : '';
80
+ if (!key) continue;
81
+ const lower = key.toLowerCase();
82
+ if (forbidden.has(lower)) continue;
83
+ if (typeof rawVal !== 'string') continue;
84
+ result[key] = rawVal;
85
+ }
86
+ return result;
87
+ }
88
+
89
+ function readOpenaiBridgeSettings(filePath) {
90
+ const parsed = readJsonFile(filePath, null);
91
+ const providers = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
92
+ ? parsed.providers
93
+ : null;
94
+ const providerMap = providers && typeof providers === 'object' && !Array.isArray(providers)
95
+ ? providers
96
+ : {};
97
+ return {
98
+ version: SETTINGS_VERSION,
99
+ providers: providerMap
100
+ };
101
+ }
102
+
103
+ function upsertOpenaiBridgeProvider(filePath, providerName, upstreamBaseUrl, apiKey, headers) {
104
+ const name = normalizeProviderName(providerName);
105
+ const baseUrl = normalizeOpenaiUpstreamBaseUrl(upstreamBaseUrl);
106
+ const key = normalizeText(apiKey);
107
+ const nextHeaders = normalizeHeadersMap(headers);
108
+
109
+ if (!name) {
110
+ return { error: 'Provider name is required' };
111
+ }
112
+ if (!baseUrl || !isValidHttpUrl(baseUrl)) {
113
+ return { error: 'Upstream base URL is invalid' };
114
+ }
115
+
116
+ const settings = readOpenaiBridgeSettings(filePath);
117
+ const existing = settings && settings.providers ? settings.providers[name] : null;
118
+ const existingHeaders = existing && typeof existing === 'object' && !Array.isArray(existing)
119
+ ? normalizeHeadersMap(existing.headers || existing.extraHeaders || existing.extra_headers || null)
120
+ : {};
121
+ const next = {
122
+ version: SETTINGS_VERSION,
123
+ providers: {
124
+ ...(settings.providers || {}),
125
+ [name]: {
126
+ baseUrl,
127
+ apiKey: key,
128
+ headers: Object.keys(nextHeaders).length ? nextHeaders : existingHeaders
129
+ }
130
+ }
131
+ };
132
+ writeJsonAtomic(filePath, next);
133
+ return { success: true };
134
+ }
135
+
136
+ function resolveOpenaiBridgeUpstream(filePath, providerName) {
137
+ const name = normalizeProviderName(providerName);
138
+ if (!name) return { error: 'Provider name is required' };
139
+ const settings = readOpenaiBridgeSettings(filePath);
140
+ const entry = settings.providers ? settings.providers[name] : null;
141
+ const normalized = normalizeUpstreamEntry(entry);
142
+ if (!normalized) {
143
+ return { error: `OpenAI 转换未配置: ${name}` };
144
+ }
145
+ return { provider: name, ...normalized };
146
+ }
147
+
148
+ function extractAuthorizationToken(req) {
149
+ const header = typeof req.headers.authorization === 'string' ? req.headers.authorization.trim() : '';
150
+ if (!header) return '';
151
+ if (/^bearer\s+/i.test(header)) {
152
+ return header.replace(/^bearer\s+/i, '').trim();
153
+ }
154
+ return header;
155
+ }
156
+
157
+ function readRequestBody(req, maxBytes) {
158
+ return new Promise((resolve) => {
159
+ let body = '';
160
+ let size = 0;
161
+ let aborted = false;
162
+ req.on('data', (chunk) => {
163
+ if (aborted) return;
164
+ size += chunk.length;
165
+ if (Number.isFinite(maxBytes) && maxBytes > 0 && size > maxBytes) {
166
+ aborted = true;
167
+ try { req.destroy(); } catch (_) {}
168
+ resolve({ error: '请求体过大' });
169
+ return;
170
+ }
171
+ body += chunk;
172
+ });
173
+ req.on('end', () => {
174
+ if (aborted) return;
175
+ resolve({ body });
176
+ });
177
+ req.on('error', (err) => resolve({ error: err && err.message ? err.message : 'request failed' }));
178
+ });
179
+ }
180
+
181
+ function parseJsonOrError(text) {
182
+ if (typeof text !== 'string' || !text.trim()) {
183
+ return { value: null, error: 'empty body' };
184
+ }
185
+ try {
186
+ return { value: JSON.parse(text), error: '' };
187
+ } catch (e) {
188
+ return { value: null, error: e && e.message ? e.message : 'invalid json' };
189
+ }
190
+ }
191
+
192
+ function extractChatCompletionResult(payload) {
193
+ if (!payload || typeof payload !== 'object') return { text: '', toolCalls: [] };
194
+ const choice = Array.isArray(payload.choices) ? payload.choices[0] : null;
195
+ const message = choice && typeof choice === 'object' ? choice.message : null;
196
+ const toolCalls = message && typeof message === 'object' && Array.isArray(message.tool_calls)
197
+ ? message.tool_calls
198
+ : [];
199
+ const content = message && typeof message === 'object' ? message.content : '';
200
+ let text = '';
201
+ if (typeof content === 'string') {
202
+ text = content;
203
+ } else if (Array.isArray(content)) {
204
+ text = content
205
+ .map((item) => {
206
+ if (!item) return '';
207
+ if (typeof item === 'string') return item;
208
+ if (typeof item === 'object') {
209
+ if (typeof item.text === 'string') return item.text;
210
+ if (typeof item.content === 'string') return item.content;
211
+ }
212
+ return '';
213
+ })
214
+ .filter(Boolean)
215
+ .join('');
216
+ }
217
+ return { text, toolCalls };
218
+ }
219
+
220
+ function normalizeResponsesInputToChatMessages(input) {
221
+ // 支持:
222
+ // - string
223
+ // - { role, content }(单条 message)
224
+ // - { type:"input_text"|"input_image", ... }(单个 block)
225
+ // - [{ role, content: [...] }](messages array)
226
+ // - [{ type:"input_text"|"input_image", ... }](blocks array -> 单条 user 消息)
227
+ if (typeof input === 'string') {
228
+ return [{ role: 'user', content: input }];
229
+ }
230
+
231
+ const toChatContent = (blocks) => {
232
+ if (!Array.isArray(blocks)) return '';
233
+ const out = [];
234
+ for (const block of blocks) {
235
+ if (!block || typeof block !== 'object') continue;
236
+ const type = typeof block.type === 'string' ? block.type : '';
237
+ if ((type === 'input_text' || type === 'output_text') && typeof block.text === 'string') {
238
+ out.push({ type: 'text', text: block.text });
239
+ continue;
240
+ }
241
+ if ((type === 'reasoning' || type === 'reasoning_text' || type === 'reasoning_content') && typeof block.text === 'string') {
242
+ out.push({ type: 'text', text: block.text });
243
+ continue;
244
+ }
245
+ if (type === 'input_image') {
246
+ const raw = block.image_url != null ? block.image_url : block.imageUrl;
247
+ const url = typeof raw === 'string'
248
+ ? raw
249
+ : (raw && typeof raw === 'object' && typeof raw.url === 'string' ? raw.url : '');
250
+ if (url) {
251
+ out.push({ type: 'image_url', image_url: { url } });
252
+ }
253
+ continue;
254
+ }
255
+ // 容错:兼容已是 chat content 的 {type:"text"} / {type:"image_url"}
256
+ if (type === 'text' && typeof block.text === 'string') {
257
+ out.push({ type: 'text', text: block.text });
258
+ continue;
259
+ }
260
+ if (type === 'image_url' && block.image_url) {
261
+ out.push({ type: 'image_url', image_url: block.image_url });
262
+ continue;
263
+ }
264
+ const text = typeof block.text === 'string'
265
+ ? block.text
266
+ : (typeof block.content === 'string' ? block.content : '');
267
+ if (text) {
268
+ out.push({ type: 'text', text });
269
+ continue;
270
+ }
271
+ try {
272
+ const raw = JSON.stringify(block);
273
+ if (raw) {
274
+ out.push({ type: 'text', text: raw.slice(0, 4000) });
275
+ }
276
+ } catch (_) {}
277
+ }
278
+ if (out.length === 0) return '';
279
+ return out;
280
+ };
281
+
282
+ const toRole = (value) => {
283
+ const roleRaw = typeof value === 'string' ? value.trim().toLowerCase() : '';
284
+ return roleRaw === 'assistant' ? 'assistant' : (roleRaw === 'system' ? 'system' : 'user');
285
+ };
286
+
287
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
288
+ if (typeof input.role === 'string' && input.content != null) {
289
+ const role = toRole(input.role);
290
+ const content = Array.isArray(input.content)
291
+ ? toChatContent(input.content)
292
+ : input.content;
293
+ return content ? [{ role, content }] : [];
294
+ }
295
+ if (typeof input.type === 'string') {
296
+ const content = toChatContent([input]);
297
+ return content ? [{ role: 'user', content }] : [];
298
+ }
299
+ return [];
300
+ }
301
+
302
+ if (!Array.isArray(input)) {
303
+ return [];
304
+ }
305
+
306
+ const messages = [];
307
+ for (const item of input) {
308
+ if (!item || typeof item !== 'object') continue;
309
+
310
+ // Tool calls (Responses): { type: "function_call", call_id, name, arguments }
311
+ // Chat Completions equivalent: assistant message with tool_calls
312
+ if (typeof item.type === 'string' && item.type === 'function_call') {
313
+ const callId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
314
+ const name = typeof item.name === 'string' ? item.name.trim() : '';
315
+ const args = typeof item.arguments === 'string' ? item.arguments : '';
316
+ if (callId && name) {
317
+ messages.push({
318
+ role: 'assistant',
319
+ tool_calls: [{
320
+ id: callId,
321
+ type: 'function',
322
+ function: { name, arguments: args || '' }
323
+ }]
324
+ });
325
+ }
326
+ continue;
327
+ }
328
+
329
+ // Tool results (Responses): { type: "function_call_output", call_id, output }
330
+ // Chat Completions equivalent: { role: "tool", tool_call_id, content }
331
+ if (typeof item.type === 'string' && item.type === 'function_call_output') {
332
+ const toolCallId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
333
+ let content = item.output;
334
+ if (typeof content !== 'string') {
335
+ try {
336
+ content = JSON.stringify(content);
337
+ } catch (_) {
338
+ content = String(content ?? '');
339
+ }
340
+ }
341
+ if (toolCallId) {
342
+ messages.push({ role: 'tool', tool_call_id: toolCallId, content: String(content || '') });
343
+ }
344
+ continue;
345
+ }
346
+
347
+ // message form
348
+ if (typeof item.role === 'string' && item.content != null) {
349
+ const role = toRole(item.role);
350
+ const content = Array.isArray(item.content)
351
+ ? toChatContent(item.content)
352
+ : item.content;
353
+ if (content) {
354
+ messages.push({ role, content });
355
+ }
356
+ continue;
357
+ }
358
+ }
359
+
360
+ if (messages.length > 0) {
361
+ return messages;
362
+ }
363
+
364
+ // 退化:把 input array 当作单条 user content blocks
365
+ const fallbackContent = toChatContent(input);
366
+ if (fallbackContent) {
367
+ return [{ role: 'user', content: fallbackContent }];
368
+ }
369
+ return [];
370
+ }
371
+
372
+
373
+ function normalizeResponsesToolsToChatTools(tools) {
374
+ if (!Array.isArray(tools)) return tools;
375
+ return tools
376
+ .map((tool) => {
377
+ if (!tool || typeof tool !== 'object') return null;
378
+ if (tool.type !== 'function') return null;
379
+ const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
380
+ ? tool.function
381
+ : {};
382
+ const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
383
+ ? sourceFn.name.trim()
384
+ : (typeof tool.name === 'string' ? tool.name.trim() : '');
385
+ if (!name) return null;
386
+ const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
387
+ ? sourceFn.parameters
388
+ : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : {});
389
+ const fn = { name, parameters };
390
+ const description = typeof sourceFn.description === 'string'
391
+ ? sourceFn.description
392
+ : (typeof tool.description === 'string' ? tool.description : undefined);
393
+ const strict = typeof sourceFn.strict === 'boolean'
394
+ ? sourceFn.strict
395
+ : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
396
+ if (description !== undefined) fn.description = description;
397
+ if (strict !== undefined) fn.strict = strict;
398
+ return { type: 'function', function: fn };
399
+ })
400
+ .filter(Boolean);
401
+ }
402
+
403
+ function normalizeResponsesToolChoiceToChatToolChoice(toolChoice) {
404
+ if (!toolChoice || typeof toolChoice !== 'object' || Array.isArray(toolChoice)) return toolChoice;
405
+ if (toolChoice.type === 'function' && typeof toolChoice.name === 'string' && toolChoice.name.trim()) {
406
+ return { type: 'function', function: { name: toolChoice.name.trim() } };
407
+ }
408
+ return toolChoice;
409
+ }
410
+
411
+ function normalizeResponsesToolsForResponsesApi(tools) {
412
+ if (!Array.isArray(tools)) return tools;
413
+ return tools
414
+ .map((tool) => {
415
+ if (!tool || typeof tool !== 'object') return null;
416
+ if (tool.type !== 'function') return null;
417
+ const sourceFn = tool.function && typeof tool.function === 'object' && !Array.isArray(tool.function)
418
+ ? tool.function
419
+ : {};
420
+ const name = typeof sourceFn.name === 'string' && sourceFn.name.trim()
421
+ ? sourceFn.name.trim()
422
+ : (typeof tool.name === 'string' ? tool.name.trim() : '');
423
+ if (!name) return null;
424
+ const out = { type: 'function', name };
425
+ const description = typeof sourceFn.description === 'string'
426
+ ? sourceFn.description
427
+ : (typeof tool.description === 'string' ? tool.description : undefined);
428
+ const parameters = sourceFn.parameters && typeof sourceFn.parameters === 'object' && !Array.isArray(sourceFn.parameters)
429
+ ? sourceFn.parameters
430
+ : (tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) ? tool.parameters : undefined);
431
+ const strict = typeof sourceFn.strict === 'boolean'
432
+ ? sourceFn.strict
433
+ : (typeof tool.strict === 'boolean' ? tool.strict : undefined);
434
+ if (description !== undefined) out.description = description;
435
+ if (parameters !== undefined) out.parameters = parameters;
436
+ if (strict !== undefined) out.strict = strict;
437
+ return out;
438
+ })
439
+ .filter(Boolean);
440
+ }
441
+
442
+ function convertResponsesRequestToChatCompletions(payload) {
443
+ const body = payload && typeof payload === 'object' ? payload : {};
444
+ const model = typeof body.model === 'string' ? body.model.trim() : '';
445
+ if (!model) {
446
+ return { error: 'responses 请求缺少 model' };
447
+ }
448
+
449
+ const messages = [];
450
+ // Align with Maxx/CLIProxyAPI style: map "instructions" to a leading system message.
451
+ if (typeof body.instructions === 'string' && body.instructions.trim()) {
452
+ messages.push({ role: 'system', content: body.instructions.trim() });
453
+ }
454
+ messages.push(...normalizeResponsesInputToChatMessages(body.input));
455
+ if (!messages.length) {
456
+ // codex sometimes sends empty input for probes; tolerate.
457
+ messages.push({ role: 'user', content: '' });
458
+ }
459
+
460
+ const maxOutputTokens = Number.parseInt(String(body.max_output_tokens), 10);
461
+ const stream = body.stream === true;
462
+
463
+ const chat = {
464
+ model,
465
+ messages,
466
+ stream: false,
467
+ temperature: Number.isFinite(body.temperature) ? Number(body.temperature) : undefined,
468
+ top_p: Number.isFinite(body.top_p) ? Number(body.top_p) : undefined,
469
+ max_tokens: Number.isFinite(maxOutputTokens) && maxOutputTokens > 0 ? maxOutputTokens : undefined
470
+ };
471
+ if (Array.isArray(body.stop) && body.stop.length) {
472
+ chat.stop = body.stop.filter((item) => typeof item === 'string' && item.trim());
473
+ }
474
+ if (Array.isArray(body.tools) && body.tools.length) {
475
+ chat.tools = normalizeResponsesToolsToChatTools(body.tools);
476
+ }
477
+ if (body.tool_choice !== undefined) {
478
+ chat.tool_choice = normalizeResponsesToolChoiceToChatToolChoice(body.tool_choice);
479
+ }
480
+ if (body.response_format !== undefined) {
481
+ chat.response_format = body.response_format;
482
+ }
483
+ if (body.metadata !== undefined) {
484
+ chat.metadata = body.metadata;
485
+ }
486
+
487
+ // Remove undefined keys
488
+ Object.keys(chat).forEach((key) => chat[key] === undefined && delete chat[key]);
489
+
490
+ return { chat, streamRequested: stream };
491
+ }
492
+
493
+ function buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamPayload) {
494
+ const responseId = `resp_${crypto.randomBytes(10).toString('hex')}`;
495
+ const usage = upstreamPayload && upstreamPayload.usage && typeof upstreamPayload.usage === 'object'
496
+ ? upstreamPayload.usage
497
+ : null;
498
+ const createdAt = Math.floor(Date.now() / 1000);
499
+ const output = [];
500
+ const trimmedText = typeof text === 'string' ? text : '';
501
+ if (trimmedText) {
502
+ output.push({
503
+ id: `msg_${crypto.randomBytes(8).toString('hex')}`,
504
+ type: 'message',
505
+ role: 'assistant',
506
+ content: [{ type: 'output_text', text: trimmedText }]
507
+ });
508
+ }
509
+
510
+ // Convert chat.completions tool_calls into Responses-style function_call output items.
511
+ // This is important for Codex, which appends function_call + function_call_output back into `input`.
512
+ if (Array.isArray(toolCalls)) {
513
+ for (const call of toolCalls) {
514
+ if (!call || typeof call !== 'object') continue;
515
+ const callId = typeof call.id === 'string' && call.id.trim() ? call.id.trim() : `call_${crypto.randomBytes(8).toString('hex')}`;
516
+ const fn = call.function && typeof call.function === 'object' ? call.function : {};
517
+ const name = typeof fn.name === 'string' ? fn.name : '';
518
+ const args = typeof fn.arguments === 'string' ? fn.arguments : '';
519
+ if (!name) continue;
520
+ output.push({
521
+ type: 'function_call',
522
+ call_id: callId,
523
+ name,
524
+ arguments: args
525
+ });
526
+ }
527
+ }
528
+
529
+ const payload = {
530
+ id: responseId,
531
+ object: 'response',
532
+ model,
533
+ created_at: createdAt,
534
+ status: 'completed',
535
+ output,
536
+ output_text: trimmedText
537
+ };
538
+
539
+ if (usage) {
540
+ // Map chat.completions usage -> responses usage shape when possible.
541
+ const promptTokens = Number.isFinite(usage.prompt_tokens) ? Number(usage.prompt_tokens) : null;
542
+ const completionTokens = Number.isFinite(usage.completion_tokens) ? Number(usage.completion_tokens) : null;
543
+ const totalTokens = Number.isFinite(usage.total_tokens) ? Number(usage.total_tokens) : null;
544
+ if (promptTokens !== null || completionTokens !== null || totalTokens !== null) {
545
+ payload.usage = {
546
+ input_tokens: promptTokens ?? undefined,
547
+ output_tokens: completionTokens ?? undefined,
548
+ total_tokens: totalTokens ?? undefined
549
+ };
550
+ Object.keys(payload.usage).forEach((key) => payload.usage[key] === undefined && delete payload.usage[key]);
551
+ } else {
552
+ payload.usage = usage;
553
+ }
554
+ }
555
+
556
+ return payload;
557
+ }
558
+
559
+ function ensureResponseMetadata(response) {
560
+ const payload = response && typeof response === 'object' ? response : {};
561
+ if (typeof payload.object !== 'string' || !payload.object.trim()) {
562
+ payload.object = 'response';
563
+ }
564
+ if (typeof payload.created_at !== 'number') {
565
+ payload.created_at = Math.floor(Date.now() / 1000);
566
+ }
567
+ if (typeof payload.status !== 'string' || !payload.status.trim()) {
568
+ payload.status = 'completed';
569
+ }
570
+ if (!Array.isArray(payload.output)) {
571
+ payload.output = [];
572
+ }
573
+ return payload;
574
+ }
575
+
576
+ function sendResponsesSse(res, responsePayload) {
577
+ const response = ensureResponseMetadata(responsePayload);
578
+ const responseId = typeof response.id === 'string' && response.id.trim()
579
+ ? response.id.trim()
580
+ : `resp_${crypto.randomBytes(10).toString('hex')}`;
581
+ const model = typeof response.model === 'string' ? response.model : '';
582
+
583
+ let sequence = 0;
584
+ const nextSeq = () => {
585
+ sequence += 1;
586
+ return sequence;
587
+ };
588
+
589
+ writeSse(res, 'response.created', {
590
+ type: 'response.created',
591
+ response: {
592
+ id: responseId,
593
+ model,
594
+ created_at: response.created_at
595
+ }
596
+ });
597
+
598
+ const output = Array.isArray(response.output) ? response.output : [];
599
+ for (let outputIndex = 0; outputIndex < output.length; outputIndex += 1) {
600
+ const item = output[outputIndex];
601
+ if (!item || typeof item !== 'object') continue;
602
+ const itemType = typeof item.type === 'string' ? item.type : '';
603
+ const itemId = typeof item.id === 'string' && item.id.trim()
604
+ ? item.id.trim()
605
+ : (typeof item.call_id === 'string' && item.call_id.trim() ? item.call_id.trim() : `item_${crypto.randomBytes(8).toString('hex')}`);
606
+
607
+ // Emit item added so Codex can anchor subsequent deltas by output_index/content_index/item_id.
608
+ writeSse(res, 'response.output_item.added', {
609
+ type: 'response.output_item.added',
610
+ output_index: outputIndex,
611
+ item: { ...item, id: itemId }
612
+ });
613
+
614
+ if (itemType === 'message') {
615
+ const content = Array.isArray(item.content) ? item.content : [];
616
+ for (let contentIndex = 0; contentIndex < content.length; contentIndex += 1) {
617
+ const block = content[contentIndex];
618
+ if (!block || typeof block !== 'object') continue;
619
+ if (block.type !== 'output_text') continue;
620
+ const text = typeof block.text === 'string' ? block.text : '';
621
+ if (text) {
622
+ writeSse(res, 'response.output_text.delta', {
623
+ type: 'response.output_text.delta',
624
+ item_id: itemId,
625
+ output_index: outputIndex,
626
+ content_index: contentIndex,
627
+ delta: text,
628
+ sequence_number: nextSeq()
629
+ });
630
+ }
631
+ writeSse(res, 'response.output_text.done', {
632
+ type: 'response.output_text.done',
633
+ item_id: itemId,
634
+ output_index: outputIndex,
635
+ content_index: contentIndex,
636
+ text,
637
+ sequence_number: nextSeq()
638
+ });
639
+ }
640
+ }
641
+
642
+ // Emit item done for all item types (message/function_call/etc).
643
+ writeSse(res, 'response.output_item.done', {
644
+ type: 'response.output_item.done',
645
+ output_index: outputIndex,
646
+ item: { ...item, id: itemId },
647
+ sequence_number: nextSeq()
648
+ });
649
+ }
650
+
651
+ writeSse(res, 'response.completed', { type: 'response.completed', response });
652
+ writeSse(res, 'done', '[DONE]');
653
+ }
654
+
655
+ function extractResponsesOutputText(payload) {
656
+ if (!payload || typeof payload !== 'object') return '';
657
+ const output = Array.isArray(payload.output) ? payload.output : [];
658
+ for (const item of output) {
659
+ if (!item || typeof item !== 'object') continue;
660
+ if (item.type !== 'message') continue;
661
+ const content = Array.isArray(item.content) ? item.content : [];
662
+ for (const block of content) {
663
+ if (!block || typeof block !== 'object') continue;
664
+ if (block.type !== 'output_text') continue;
665
+ if (typeof block.text === 'string') return block.text;
666
+ }
667
+ }
668
+ if (typeof payload.output_text === 'string') return payload.output_text;
669
+ return '';
670
+ }
671
+
672
+ function toUpstreamNonStreamingResponsesPayload(payload) {
673
+ const body = payload && typeof payload === 'object' ? payload : {};
674
+ const normalized = { ...body, stream: false };
675
+ if (Array.isArray(body.tools)) {
676
+ normalized.tools = normalizeResponsesToolsForResponsesApi(body.tools);
677
+ }
678
+ return normalized;
679
+ }
680
+
681
+ function shouldFallbackFromUpstreamResponses(status, bodyText) {
682
+ if (!Number.isFinite(status)) return false;
683
+ // Common "unsupported" status codes for a route.
684
+ if (status === 404 || status === 405 || status === 501) return true;
685
+
686
+ // Some OpenAI-compatible gateways respond with 500 + "not implemented" (e.g. convert_request_failed)
687
+ // instead of 404/405 for unsupported endpoints. In that case we can safely fallback to chat/completions.
688
+ const text = String(bodyText || '');
689
+ if (!text) return false;
690
+ if (/not implemented/i.test(text)) return true;
691
+ if (/convert_request_failed/i.test(text)) return true;
692
+ if (/unknown (endpoint|route)/i.test(text)) return true;
693
+ if (/unsupported.*\/?v1\/responses/i.test(text)) return true;
694
+ if (/does not support.*responses/i.test(text)) return true;
695
+ if (/name['"`]?\s+is a required property/i.test(text) && /tools/i.test(text) && /function/i.test(text)) return true;
696
+
697
+ // Best-effort parse for structured error codes.
698
+ try {
699
+ const parsed = JSON.parse(text);
700
+ const code = parsed && parsed.error && typeof parsed.error.code === 'string' ? parsed.error.code : '';
701
+ const msg = parsed && parsed.error && typeof parsed.error.message === 'string' ? parsed.error.message : '';
702
+ if (code === 'convert_request_failed') return true;
703
+ if (/not implemented/i.test(msg)) return true;
704
+ if (/unknown (endpoint|route)/i.test(msg)) return true;
705
+ if (/unsupported.*\/?v1\/responses/i.test(msg)) return true;
706
+ if (/does not support.*responses/i.test(msg)) return true;
707
+ if (/name['"`]?\s+is a required property/i.test(msg) && /tools/i.test(msg) && /function/i.test(msg)) return true;
708
+ } catch (_) {}
709
+
710
+ return false;
711
+ }
712
+
713
+ function isLoopbackAddress(address) {
714
+ if (!address) return false;
715
+ const value = String(address);
716
+ return value === '127.0.0.1' || value === '::1' || value === '::ffff:127.0.0.1';
717
+ }
718
+
719
+ function writeSse(res, eventName, dataObj) {
720
+ if (!res || res.writableEnded || res.destroyed) return;
721
+ if (eventName) {
722
+ res.write(`event: ${eventName}\n`);
723
+ }
724
+ if (dataObj === '[DONE]') {
725
+ res.write('data: [DONE]\n\n');
726
+ return;
727
+ }
728
+ res.write(`data: ${JSON.stringify(dataObj)}\n\n`);
729
+ }
730
+
731
+ function appendChatStreamToolCall(target, toolCall) {
732
+ if (!toolCall || typeof toolCall !== 'object') return;
733
+ const index = Number.isFinite(toolCall.index) ? toolCall.index : target.length;
734
+ if (!target[index]) {
735
+ target[index] = {
736
+ id: '',
737
+ type: 'function',
738
+ function: { name: '', arguments: '' }
739
+ };
740
+ }
741
+ const current = target[index];
742
+ if (typeof toolCall.id === 'string' && toolCall.id) current.id = toolCall.id;
743
+ if (typeof toolCall.type === 'string' && toolCall.type) current.type = toolCall.type;
744
+ const fn = toolCall.function && typeof toolCall.function === 'object' ? toolCall.function : null;
745
+ if (fn) {
746
+ if (typeof fn.name === 'string' && fn.name) current.function.name = fn.name;
747
+ if (typeof fn.arguments === 'string') current.function.arguments += fn.arguments;
748
+ }
749
+ }
750
+
751
+ function writeChatCompletionChunkAsResponsesSse(state, chunk) {
752
+ if (!chunk || typeof chunk !== 'object') return;
753
+ if (typeof chunk.model === 'string' && chunk.model) {
754
+ state.model = chunk.model;
755
+ }
756
+ const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
757
+ for (const choice of choices) {
758
+ const delta = choice && choice.delta && typeof choice.delta === 'object' ? choice.delta : null;
759
+ if (!delta) continue;
760
+
761
+ if (typeof delta.content === 'string' && delta.content) {
762
+ if (!state.messageItem) {
763
+ state.messageItem = {
764
+ id: `msg_${crypto.randomBytes(8).toString('hex')}`,
765
+ type: 'message',
766
+ role: 'assistant',
767
+ content: [{ type: 'output_text', text: '' }]
768
+ };
769
+ state.output.push(state.messageItem);
770
+ writeSse(state.res, 'response.output_item.added', {
771
+ type: 'response.output_item.added',
772
+ output_index: state.output.length - 1,
773
+ item: state.messageItem
774
+ });
775
+ }
776
+ state.messageText += delta.content;
777
+ state.messageItem.content[0].text = state.messageText;
778
+ writeSse(state.res, 'response.output_text.delta', {
779
+ type: 'response.output_text.delta',
780
+ item_id: state.messageItem.id,
781
+ output_index: state.output.length - 1,
782
+ content_index: 0,
783
+ delta: delta.content,
784
+ sequence_number: state.nextSeq()
785
+ });
786
+ }
787
+
788
+ if (Array.isArray(delta.tool_calls)) {
789
+ for (const toolCall of delta.tool_calls) {
790
+ appendChatStreamToolCall(state.toolCalls, toolCall);
791
+ }
792
+ }
793
+ }
794
+ }
795
+
796
+ function finishChatStreamResponsesSse(state) {
797
+ if (!state || state.finished) return;
798
+ state.finished = true;
799
+
800
+ if (state.messageItem) {
801
+ const outputIndex = state.output.indexOf(state.messageItem);
802
+ writeSse(state.res, 'response.output_text.done', {
803
+ type: 'response.output_text.done',
804
+ item_id: state.messageItem.id,
805
+ output_index: outputIndex,
806
+ content_index: 0,
807
+ text: state.messageText,
808
+ sequence_number: state.nextSeq()
809
+ });
810
+ writeSse(state.res, 'response.output_item.done', {
811
+ type: 'response.output_item.done',
812
+ output_index: outputIndex,
813
+ item: state.messageItem,
814
+ sequence_number: state.nextSeq()
815
+ });
816
+ }
817
+
818
+ for (const toolCall of state.toolCalls) {
819
+ if (!toolCall) continue;
820
+ const name = toolCall.function && typeof toolCall.function.name === 'string' ? toolCall.function.name : '';
821
+ if (!name) continue;
822
+ const item = {
823
+ type: 'function_call',
824
+ call_id: toolCall.id || `call_${crypto.randomBytes(8).toString('hex')}`,
825
+ name,
826
+ arguments: toolCall.function && typeof toolCall.function.arguments === 'string' ? toolCall.function.arguments : ''
827
+ };
828
+ const outputIndex = state.output.length;
829
+ state.output.push(item);
830
+ writeSse(state.res, 'response.output_item.added', {
831
+ type: 'response.output_item.added',
832
+ output_index: outputIndex,
833
+ item
834
+ });
835
+ writeSse(state.res, 'response.output_item.done', {
836
+ type: 'response.output_item.done',
837
+ output_index: outputIndex,
838
+ item,
839
+ sequence_number: state.nextSeq()
840
+ });
841
+ }
842
+
843
+ const response = ensureResponseMetadata({
844
+ id: state.responseId,
845
+ model: state.model,
846
+ created_at: state.createdAt,
847
+ status: 'completed',
848
+ output: state.output,
849
+ output_text: state.messageText
850
+ });
851
+ writeSse(state.res, 'response.completed', { type: 'response.completed', response });
852
+ writeSse(state.res, 'done', '[DONE]');
853
+ if (!state.res.writableEnded && !state.res.destroyed) {
854
+ state.res.end();
855
+ }
856
+ }
857
+
858
+ function failChatStreamResponsesSse(state, errorMessage) {
859
+ if (!state || state.finished) return;
860
+ state.finished = true;
861
+ writeSse(state.res, 'response.failed', {
862
+ type: 'response.failed',
863
+ response: ensureResponseMetadata({
864
+ id: state.responseId,
865
+ model: state.model,
866
+ created_at: state.createdAt,
867
+ status: 'failed',
868
+ output: state.output,
869
+ output_text: state.messageText
870
+ }),
871
+ error: String(errorMessage || 'upstream stream failed')
872
+ });
873
+ writeSse(state.res, 'done', '[DONE]');
874
+ if (!state.res.writableEnded && !state.res.destroyed) {
875
+ state.res.end();
876
+ }
877
+ }
878
+
879
+ function formatUpstreamStreamError(errorValue) {
880
+ if (!errorValue) return 'upstream stream failed';
881
+ if (typeof errorValue === 'string') return errorValue;
882
+ if (typeof errorValue === 'object') {
883
+ if (typeof errorValue.message === 'string' && errorValue.message) return errorValue.message;
884
+ try { return JSON.stringify(errorValue); } catch (_) {}
885
+ }
886
+ return String(errorValue || 'upstream stream failed');
887
+ }
888
+
889
+ function streamChatCompletionsAsResponsesSse(targetUrl, options = {}) {
890
+ const parsed = new URL(targetUrl);
891
+ const transport = parsed.protocol === 'https:' ? https : http;
892
+ const bodyText = options.body ? JSON.stringify(options.body) : '';
893
+ const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
894
+ ? Math.floor(options.maxBytes)
895
+ : 0;
896
+ const headers = {
897
+ 'Accept': 'text/event-stream',
898
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
899
+ ...(options.headers || {})
900
+ };
901
+ if (options.body) {
902
+ headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
903
+ }
904
+ const timeoutMs = Number.isFinite(options.timeoutMs)
905
+ ? Math.max(1000, Number(options.timeoutMs))
906
+ : 30000;
907
+ const res = options.res;
908
+ const fallbackModel = typeof options.model === 'string' ? options.model : '';
909
+
910
+ return new Promise((resolve) => {
911
+ let settled = false;
912
+ let upstreamReq = null;
913
+ const finish = (value) => {
914
+ if (settled) return;
915
+ settled = true;
916
+ resolve(value);
917
+ };
918
+ const abortUpstream = () => {
919
+ if (upstreamReq) {
920
+ try { upstreamReq.destroy(new Error('client aborted')); } catch (_) {}
921
+ }
922
+ };
923
+ if (res && typeof res.once === 'function') {
924
+ res.once('close', abortUpstream);
925
+ }
926
+
927
+ upstreamReq = transport.request({
928
+ protocol: parsed.protocol,
929
+ hostname: parsed.hostname,
930
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
931
+ method: options.method || 'POST',
932
+ path: `${parsed.pathname}${parsed.search}`,
933
+ headers,
934
+ agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
935
+ }, (upstreamRes) => {
936
+ const status = upstreamRes.statusCode || 0;
937
+ const chunks = [];
938
+ let size = 0;
939
+ const contentType = String(upstreamRes.headers && upstreamRes.headers['content-type'] || '');
940
+
941
+ const collectChunk = (chunk) => {
942
+ if (!chunk) return true;
943
+ if (maxBytes > 0) {
944
+ size += chunk.length;
945
+ if (size > maxBytes) {
946
+ chunks.length = 0;
947
+ try { upstreamRes.destroy(new Error('response too large')); } catch (_) {}
948
+ try { upstreamReq.destroy(new Error('response too large')); } catch (_) {}
949
+ finish({ ok: false, status, error: 'response too large' });
950
+ return false;
951
+ }
952
+ }
953
+ chunks.push(chunk);
954
+ return true;
955
+ };
956
+
957
+ if (status >= 400) {
958
+ upstreamRes.on('data', collectChunk);
959
+ upstreamRes.on('end', () => finish({
960
+ ok: false,
961
+ status,
962
+ bodyText: chunks.length ? Buffer.concat(chunks).toString('utf-8') : ''
963
+ }));
964
+ return;
965
+ }
966
+
967
+ if (!res.headersSent) {
968
+ res.writeHead(200, {
969
+ 'Content-Type': 'text/event-stream; charset=utf-8',
970
+ 'Cache-Control': 'no-cache',
971
+ 'Connection': 'keep-alive',
972
+ 'X-Accel-Buffering': 'no'
973
+ });
974
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
975
+ }
976
+
977
+ if (!/text\/event-stream/i.test(contentType)) {
978
+ upstreamRes.on('data', collectChunk);
979
+ upstreamRes.on('end', () => {
980
+ const text = chunks.length ? Buffer.concat(chunks).toString('utf-8') : '';
981
+ const parsedJson = parseJsonOrError(text);
982
+ if (parsedJson.error) {
983
+ writeSse(res, 'response.failed', { type: 'response.failed', error: `invalid upstream response: ${parsedJson.error}` });
984
+ writeSse(res, 'done', '[DONE]');
985
+ if (!res.writableEnded && !res.destroyed) res.end();
986
+ finish({ ok: true });
987
+ return;
988
+ }
989
+ const extracted = extractChatCompletionResult(parsedJson.value);
990
+ sendResponsesSse(res, buildResponsesPayloadFromChatResult(fallbackModel, extracted.text, extracted.toolCalls, parsedJson.value));
991
+ if (!res.writableEnded && !res.destroyed) res.end();
992
+ finish({ ok: true });
993
+ });
994
+ return;
995
+ }
996
+
997
+ let sequence = 0;
998
+ const state = {
999
+ res,
1000
+ responseId: `resp_${crypto.randomBytes(10).toString('hex')}`,
1001
+ model: fallbackModel,
1002
+ createdAt: Math.floor(Date.now() / 1000),
1003
+ output: [],
1004
+ messageItem: null,
1005
+ messageText: '',
1006
+ toolCalls: [],
1007
+ finished: false,
1008
+ sawDone: false,
1009
+ nextSeq: () => {
1010
+ sequence += 1;
1011
+ return sequence;
1012
+ }
1013
+ };
1014
+ writeSse(res, 'response.created', {
1015
+ type: 'response.created',
1016
+ response: {
1017
+ id: state.responseId,
1018
+ model: state.model,
1019
+ created_at: state.createdAt
1020
+ }
1021
+ });
1022
+
1023
+ let buffer = '';
1024
+ const handleEventBlock = (block) => {
1025
+ const dataLines = String(block || '')
1026
+ .split(/\r?\n/)
1027
+ .filter((line) => line.startsWith('data:'))
1028
+ .map((line) => line.slice(5).trimStart());
1029
+ if (dataLines.length === 0) return;
1030
+ const data = dataLines.join('\n').trim();
1031
+ if (!data) return;
1032
+ if (data === '[DONE]') {
1033
+ state.sawDone = true;
1034
+ finishChatStreamResponsesSse(state);
1035
+ finish({ ok: true });
1036
+ return;
1037
+ }
1038
+ const parsedChunk = parseJsonOrError(data);
1039
+ if (!parsedChunk.error) {
1040
+ if (parsedChunk.value && typeof parsedChunk.value === 'object' && parsedChunk.value.error) {
1041
+ failChatStreamResponsesSse(state, formatUpstreamStreamError(parsedChunk.value.error));
1042
+ finish({ ok: true });
1043
+ return;
1044
+ }
1045
+ writeChatCompletionChunkAsResponsesSse(state, parsedChunk.value);
1046
+ }
1047
+ };
1048
+
1049
+ upstreamRes.on('data', (chunk) => {
1050
+ if (!chunk) return;
1051
+ buffer += chunk.toString('utf-8');
1052
+ let boundary = buffer.search(/\r?\n\r?\n/);
1053
+ while (boundary >= 0) {
1054
+ const block = buffer.slice(0, boundary);
1055
+ const match = buffer.slice(boundary).match(/^\r?\n\r?\n/);
1056
+ buffer = buffer.slice(boundary + (match ? match[0].length : 2));
1057
+ handleEventBlock(block);
1058
+ boundary = buffer.search(/\r?\n\r?\n/);
1059
+ }
1060
+ });
1061
+ upstreamRes.on('end', () => {
1062
+ if (buffer.trim()) handleEventBlock(buffer);
1063
+ if (!state.finished && !state.sawDone) {
1064
+ failChatStreamResponsesSse(state, 'upstream stream ended before [DONE]');
1065
+ finish({ ok: true });
1066
+ return;
1067
+ }
1068
+ finishChatStreamResponsesSse(state);
1069
+ finish({ ok: true });
1070
+ });
1071
+ upstreamRes.on('aborted', () => {
1072
+ failChatStreamResponsesSse(state, 'upstream stream aborted');
1073
+ finish({ ok: true });
1074
+ });
1075
+ upstreamRes.on('error', (err) => {
1076
+ failChatStreamResponsesSse(state, err && err.message ? err.message : 'upstream stream failed');
1077
+ finish({ ok: true });
1078
+ });
1079
+ });
1080
+ upstreamReq.setTimeout(timeoutMs, () => {
1081
+ try { upstreamReq.destroy(new Error('timeout')); } catch (_) {}
1082
+ finish({ ok: false, error: 'timeout' });
1083
+ });
1084
+ upstreamReq.on('error', (err) => finish({ ok: false, error: err && err.message ? err.message : 'request failed' }));
1085
+ if (bodyText) upstreamReq.write(bodyText);
1086
+ upstreamReq.end();
1087
+ });
1088
+ }
1089
+
1090
+ async function proxyRequestJson(targetUrl, options = {}) {
1091
+ const parsed = new URL(targetUrl);
1092
+ const transport = parsed.protocol === 'https:' ? https : http;
1093
+ const bodyText = options.body ? JSON.stringify(options.body) : '';
1094
+ const maxBytes = Number.isFinite(options.maxBytes) && options.maxBytes > 0
1095
+ ? Math.floor(options.maxBytes)
1096
+ : 0;
1097
+ const headers = {
1098
+ 'Accept': 'application/json',
1099
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
1100
+ ...(options.headers || {})
1101
+ };
1102
+ if (options.body) {
1103
+ headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
1104
+ }
1105
+
1106
+ const timeoutMs = Number.isFinite(options.timeoutMs)
1107
+ ? Math.max(1000, Number(options.timeoutMs))
1108
+ : 30000;
1109
+ return new Promise((resolve) => {
1110
+ let settled = false;
1111
+ const finish = (value) => {
1112
+ if (settled) return;
1113
+ settled = true;
1114
+ resolve(value);
1115
+ };
1116
+ const req = transport.request({
1117
+ protocol: parsed.protocol,
1118
+ hostname: parsed.hostname,
1119
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
1120
+ method: options.method || 'GET',
1121
+ path: `${parsed.pathname}${parsed.search}`,
1122
+ headers,
1123
+ agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
1124
+ }, (upstreamRes) => {
1125
+ const chunks = [];
1126
+ let size = 0;
1127
+ upstreamRes.on('data', (chunk) => {
1128
+ if (!chunk) return;
1129
+ if (maxBytes > 0) {
1130
+ size += chunk.length;
1131
+ if (size > maxBytes) {
1132
+ chunks.length = 0;
1133
+ try { upstreamRes.destroy(new Error('response too large')); } catch (_) {}
1134
+ try { req.destroy(new Error('response too large')); } catch (_) {}
1135
+ finish({ ok: false, error: 'response too large' });
1136
+ return;
1137
+ }
1138
+ }
1139
+ chunks.push(chunk);
1140
+ });
1141
+ upstreamRes.on('end', () => {
1142
+ const text = chunks.length ? Buffer.concat(chunks).toString('utf-8') : '';
1143
+ finish({
1144
+ ok: true,
1145
+ status: upstreamRes.statusCode || 0,
1146
+ headers: upstreamRes.headers || {},
1147
+ bodyText: text
1148
+ });
1149
+ });
1150
+ });
1151
+ req.setTimeout(timeoutMs, () => {
1152
+ try { req.destroy(new Error('timeout')); } catch (_) {}
1153
+ finish({ ok: false, error: 'timeout' });
1154
+ });
1155
+ req.on('error', (err) => finish({ ok: false, error: err && err.message ? err.message : 'request failed' }));
1156
+ if (bodyText) {
1157
+ req.write(bodyText);
1158
+ }
1159
+ req.end();
1160
+ });
1161
+ }
1162
+
1163
+ function createOpenaiBridgeHttpHandler(options = {}) {
1164
+ const settingsFile = options.settingsFile;
1165
+ const expectedTokenRaw = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
1166
+ const expectedToken = Object.prototype.hasOwnProperty.call(options, 'expectedToken')
1167
+ ? expectedTokenRaw
1168
+ : (expectedTokenRaw || DEFAULT_BRIDGE_TOKEN);
1169
+ const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
1170
+ const httpAgent = options.httpAgent;
1171
+ const httpsAgent = options.httpsAgent;
1172
+ const maxUpstreamBytes = Number.isFinite(options.maxUpstreamBytes) && options.maxUpstreamBytes > 0
1173
+ ? Math.floor(options.maxUpstreamBytes)
1174
+ : Math.max(16 * 1024 * 1024, maxBodySize > 0 ? maxBodySize * 4 : 0);
1175
+
1176
+ if (!settingsFile) {
1177
+ throw new Error('createOpenaiBridgeHttpHandler 缺少 settingsFile');
1178
+ }
1179
+
1180
+ const matchPath = (requestPath) => {
1181
+ const normalized = String(requestPath || '');
1182
+ const prefix = '/bridge/openai/';
1183
+ if (!normalized.startsWith(prefix)) return null;
1184
+ const rest = normalized.slice(prefix.length);
1185
+ const [provider, ...tail] = rest.split('/').filter((part) => part.length > 0);
1186
+ if (!provider) return null;
1187
+ const tailPath = '/' + tail.join('/');
1188
+ if (!tailPath.startsWith('/v1')) return null;
1189
+ const suffix = tailPath === '/v1' ? '' : tailPath.replace(/^\/v1\/?/, '');
1190
+ return { provider, suffix };
1191
+ };
1192
+
1193
+ const handler = (req, res) => {
1194
+ let parsedUrl;
1195
+ try {
1196
+ parsedUrl = new URL(req.url || '/', 'http://localhost');
1197
+ } catch (_) {
1198
+ return false;
1199
+ }
1200
+ const match = matchPath(parsedUrl.pathname || '/');
1201
+ if (!match) return false;
1202
+
1203
+ void (async () => {
1204
+ try {
1205
+ const token = extractAuthorizationToken(req);
1206
+ // 兼容:某些客户端在自定义 base_url 时可能不带 Authorization。
1207
+ // 为避免在 LAN 暴露无鉴权的代理,这里仅允许 loopback 连接缺省 token。
1208
+ const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
1209
+ const isLoopback = isLoopbackAddress(remoteAddr);
1210
+ if (!isLoopback && !expectedToken) {
1211
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
1212
+ res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
1213
+ return;
1214
+ }
1215
+ if (!token && !isLoopback) {
1216
+ res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
1217
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
1218
+ return;
1219
+ }
1220
+ // loopback 上的本地代理:允许客户端携带任意 Authorization(例如 Codex 会附带 provider apiKey)。
1221
+ // 非 loopback 时仍强制校验 expectedToken,避免局域网被未授权调用。
1222
+ if (!isLoopback && token && token !== expectedToken) {
1223
+ res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
1224
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
1225
+ return;
1226
+ }
1227
+
1228
+ const upstream = resolveOpenaiBridgeUpstream(settingsFile, match.provider);
1229
+ if (upstream.error) {
1230
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
1231
+ res.end(JSON.stringify({ error: upstream.error }));
1232
+ return;
1233
+ }
1234
+
1235
+ const suffix = match.suffix || '';
1236
+ const normalizedSuffix = suffix.replace(/^\/+/, '');
1237
+
1238
+ const authHeader = upstream.apiKey
1239
+ ? (/^bearer\s+/i.test(upstream.apiKey) ? upstream.apiKey : `Bearer ${upstream.apiKey}`)
1240
+ : '';
1241
+ const upstreamHeaders = upstream && upstream.headers && typeof upstream.headers === 'object' && !Array.isArray(upstream.headers)
1242
+ ? upstream.headers
1243
+ : {};
1244
+
1245
+ if (!normalizedSuffix) {
1246
+ if ((req.method || 'GET').toUpperCase() !== 'GET') {
1247
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
1248
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
1249
+ return;
1250
+ }
1251
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1252
+ res.end(JSON.stringify({
1253
+ object: 'codexmate.openai_bridge',
1254
+ provider: match.provider,
1255
+ status: 'ok',
1256
+ endpoints: ['/v1/responses', '/v1/models']
1257
+ }));
1258
+ return;
1259
+ }
1260
+
1261
+ if (normalizedSuffix === 'models') {
1262
+ if ((req.method || 'GET').toUpperCase() !== 'GET') {
1263
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
1264
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
1265
+ return;
1266
+ }
1267
+
1268
+ const url = joinApiUrl(upstream.baseUrl, 'models');
1269
+ const result = await proxyRequestJson(url, {
1270
+ method: 'GET',
1271
+ headers: {
1272
+ ...(authHeader ? { Authorization: authHeader } : {}),
1273
+ ...upstreamHeaders
1274
+ },
1275
+ maxBytes: maxUpstreamBytes,
1276
+ httpAgent,
1277
+ httpsAgent
1278
+ });
1279
+ if (!result.ok) {
1280
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1281
+ res.end(JSON.stringify({ error: `Upstream request failed: ${result.error}` }));
1282
+ return;
1283
+ }
1284
+ res.writeHead(result.status || 502, { 'Content-Type': 'application/json; charset=utf-8' });
1285
+ res.end(result.bodyText || '');
1286
+ return;
1287
+ }
1288
+
1289
+ if (normalizedSuffix !== 'responses') {
1290
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
1291
+ res.end(JSON.stringify({ error: 'Not Found' }));
1292
+ return;
1293
+ }
1294
+
1295
+ if ((req.method || 'GET').toUpperCase() !== 'POST') {
1296
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
1297
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
1298
+ return;
1299
+ }
1300
+
1301
+ const { body, error: bodyErr } = await readRequestBody(req, maxBodySize);
1302
+ if (bodyErr) {
1303
+ res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
1304
+ res.end(JSON.stringify({ error: bodyErr }));
1305
+ return;
1306
+ }
1307
+ const parsed = parseJsonOrError(body);
1308
+ if (parsed.error) {
1309
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
1310
+ res.end(JSON.stringify({ error: `Invalid JSON: ${parsed.error}` }));
1311
+ return;
1312
+ }
1313
+
1314
+ const responsesRequest = parsed.value;
1315
+ const streamRequested = !!(responsesRequest && typeof responsesRequest === 'object' && responsesRequest.stream === true);
1316
+ const acceptHeader = req && req.headers ? (req.headers.accept || req.headers.Accept || '') : '';
1317
+ const wantsSse = /text\/event-stream/i.test(String(acceptHeader || ''));
1318
+
1319
+ if (streamRequested && wantsSse) {
1320
+ const converted = convertResponsesRequestToChatCompletions(responsesRequest);
1321
+ if (converted.error) {
1322
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
1323
+ res.end(JSON.stringify({ error: converted.error }));
1324
+ return;
1325
+ }
1326
+ const upstreamUrl = joinApiUrl(upstream.baseUrl, 'chat/completions');
1327
+ const chatBody = { ...converted.chat, stream: true };
1328
+ const streamed = await streamChatCompletionsAsResponsesSse(upstreamUrl, {
1329
+ method: 'POST',
1330
+ body: chatBody,
1331
+ headers: {
1332
+ ...(authHeader ? { Authorization: authHeader } : {}),
1333
+ ...upstreamHeaders
1334
+ },
1335
+ maxBytes: maxUpstreamBytes,
1336
+ httpAgent,
1337
+ httpsAgent,
1338
+ res,
1339
+ model: typeof chatBody.model === 'string' ? chatBody.model : ''
1340
+ });
1341
+ if (!streamed.ok) {
1342
+ if (res.writableEnded || res.destroyed) {
1343
+ return;
1344
+ }
1345
+ if (!res.headersSent) {
1346
+ res.writeHead(streamed.status && streamed.status >= 400 ? streamed.status : 502, { 'Content-Type': 'application/json; charset=utf-8' });
1347
+ res.end(streamed.bodyText || JSON.stringify({ error: streamed.error || 'Upstream request failed' }));
1348
+ } else if (!res.writableEnded && !res.destroyed) {
1349
+ writeSse(res, 'response.failed', { type: 'response.failed', error: streamed.error || streamed.bodyText || 'Upstream request failed' });
1350
+ writeSse(res, 'done', '[DONE]');
1351
+ res.end();
1352
+ }
1353
+ }
1354
+ return;
1355
+ }
1356
+
1357
+ // Maxx-style behavior: prefer upstream /responses if supported.
1358
+ // Fallback to /chat/completions conversion when upstream does not implement /responses (404/405).
1359
+ const upstreamResponsesUrl = joinApiUrl(upstream.baseUrl, 'responses');
1360
+ const upstreamResponsesResult = await proxyRequestJson(upstreamResponsesUrl, {
1361
+ method: 'POST',
1362
+ body: toUpstreamNonStreamingResponsesPayload(responsesRequest),
1363
+ headers: {
1364
+ ...(authHeader ? { Authorization: authHeader } : {}),
1365
+ ...upstreamHeaders
1366
+ },
1367
+ maxBytes: maxUpstreamBytes,
1368
+ httpAgent,
1369
+ httpsAgent
1370
+ });
1371
+
1372
+ if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 200 && upstreamResponsesResult.status < 300) {
1373
+ const upstreamJson = parseJsonOrError(upstreamResponsesResult.bodyText);
1374
+ if (upstreamJson.error) {
1375
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1376
+ res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
1377
+ return;
1378
+ }
1379
+ const upstreamPayload = upstreamJson.value;
1380
+ if (streamRequested && wantsSse) {
1381
+ res.writeHead(200, {
1382
+ 'Content-Type': 'text/event-stream; charset=utf-8',
1383
+ 'Cache-Control': 'no-cache',
1384
+ 'Connection': 'keep-alive',
1385
+ 'X-Accel-Buffering': 'no'
1386
+ });
1387
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
1388
+ sendResponsesSse(res, upstreamPayload);
1389
+ res.end();
1390
+ return;
1391
+ }
1392
+
1393
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1394
+ res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload)));
1395
+ return;
1396
+ }
1397
+
1398
+ if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400) {
1399
+ if (!shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
1400
+ res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
1401
+ res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
1402
+ return;
1403
+ }
1404
+ // fallthrough to chat/completions conversion
1405
+ }
1406
+
1407
+ if (!upstreamResponsesResult.ok) {
1408
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1409
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
1410
+ return;
1411
+ }
1412
+
1413
+ const converted = convertResponsesRequestToChatCompletions(responsesRequest);
1414
+ if (converted.error) {
1415
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
1416
+ res.end(JSON.stringify({ error: converted.error }));
1417
+ return;
1418
+ }
1419
+
1420
+ const upstreamUrl = joinApiUrl(upstream.baseUrl, 'chat/completions');
1421
+ const upstreamResult = await proxyRequestJson(upstreamUrl, {
1422
+ method: 'POST',
1423
+ body: converted.chat,
1424
+ headers: {
1425
+ ...(authHeader ? { Authorization: authHeader } : {}),
1426
+ ...upstreamHeaders
1427
+ },
1428
+ maxBytes: maxUpstreamBytes,
1429
+ httpAgent,
1430
+ httpsAgent
1431
+ });
1432
+ if (!upstreamResult.ok) {
1433
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1434
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
1435
+ return;
1436
+ }
1437
+
1438
+ const upstreamJson = parseJsonOrError(upstreamResult.bodyText);
1439
+ if (upstreamResult.status >= 400) {
1440
+ res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
1441
+ res.end(upstreamResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
1442
+ return;
1443
+ }
1444
+ if (upstreamJson.error) {
1445
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
1446
+ res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
1447
+ return;
1448
+ }
1449
+
1450
+ const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
1451
+ const extracted = extractChatCompletionResult(upstreamJson.value);
1452
+ const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
1453
+ const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
1454
+ const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamJson.value);
1455
+
1456
+ if (converted.streamRequested && wantsSse) {
1457
+ res.writeHead(200, {
1458
+ 'Content-Type': 'text/event-stream; charset=utf-8',
1459
+ 'Cache-Control': 'no-cache',
1460
+ 'Connection': 'keep-alive',
1461
+ 'X-Accel-Buffering': 'no'
1462
+ });
1463
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
1464
+ sendResponsesSse(res, responsesPayload);
1465
+ res.end();
1466
+ return;
1467
+ }
1468
+
1469
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
1470
+ res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
1471
+ } catch (e) {
1472
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
1473
+ res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
1474
+ }
1475
+ })();
1476
+
1477
+ return true;
1478
+ };
1479
+
1480
+ handler.matchPath = matchPath;
1481
+ return handler;
1482
+ }
1483
+
1484
+ module.exports = {
1485
+ readOpenaiBridgeSettings,
1486
+ upsertOpenaiBridgeProvider,
1487
+ resolveOpenaiBridgeUpstream,
1488
+ createOpenaiBridgeHttpHandler
1489
+ };