codexmate 0.0.21 → 0.0.23

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 (115) hide show
  1. package/README.md +390 -284
  2. package/README.zh.md +322 -0
  3. package/cli/agents-files.js +224 -162
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +359 -359
  6. package/cli/builtin-proxy.js +1044 -580
  7. package/cli/claude-proxy.js +998 -998
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/openai-bridge.js +950 -0
  11. package/cli/openclaw-config.js +629 -629
  12. package/cli/session-usage.concurrent.js +28 -0
  13. package/cli/session-usage.js +112 -0
  14. package/cli/session-usage.models.js +176 -0
  15. package/cli/skills.js +1141 -1141
  16. package/cli/zip-commands.js +510 -510
  17. package/cli.js +13214 -13129
  18. package/lib/cli-file-utils.js +151 -151
  19. package/lib/cli-models-utils.js +419 -419
  20. package/lib/cli-network-utils.js +164 -164
  21. package/lib/cli-path-utils.js +69 -69
  22. package/lib/cli-session-utils.js +121 -121
  23. package/lib/cli-sessions.js +386 -386
  24. package/lib/cli-utils.js +155 -155
  25. package/lib/download-artifacts.js +77 -77
  26. package/lib/mcp-stdio.js +440 -440
  27. package/lib/task-orchestrator.js +869 -869
  28. package/lib/text-diff.js +303 -303
  29. package/lib/workflow-engine.js +340 -340
  30. package/package.json +74 -74
  31. package/res/json5.min.js +1 -1
  32. package/res/logo.png +0 -0
  33. package/res/vue.global.prod.js +13 -13
  34. package/web-ui/app.js +626 -530
  35. package/web-ui/index.html +34 -33
  36. package/web-ui/logic.agents-diff.mjs +386 -386
  37. package/web-ui/logic.claude.mjs +168 -168
  38. package/web-ui/logic.mjs +5 -5
  39. package/web-ui/logic.runtime.mjs +128 -124
  40. package/web-ui/logic.sessions.mjs +614 -581
  41. package/web-ui/modules/api.mjs +90 -90
  42. package/web-ui/modules/app.computed.dashboard.mjs +126 -113
  43. package/web-ui/modules/app.computed.index.mjs +17 -15
  44. package/web-ui/modules/app.computed.main-tabs.mjs +202 -195
  45. package/web-ui/modules/app.computed.session.mjs +653 -507
  46. package/web-ui/modules/app.constants.mjs +15 -15
  47. package/web-ui/modules/app.methods.agents.mjs +544 -493
  48. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  49. package/web-ui/modules/app.methods.codex-config.mjs +795 -640
  50. package/web-ui/modules/app.methods.index.mjs +92 -88
  51. package/web-ui/modules/app.methods.install.mjs +177 -149
  52. package/web-ui/modules/app.methods.navigation.mjs +662 -619
  53. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  54. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  55. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  56. package/web-ui/modules/app.methods.providers.mjs +404 -363
  57. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  58. package/web-ui/modules/app.methods.session-actions.mjs +537 -520
  59. package/web-ui/modules/app.methods.session-browser.mjs +691 -626
  60. package/web-ui/modules/app.methods.session-timeline.mjs +448 -448
  61. package/web-ui/modules/app.methods.session-trash.mjs +422 -422
  62. package/web-ui/modules/app.methods.startup-claude.mjs +417 -412
  63. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -471
  64. package/web-ui/modules/config-mode.computed.mjs +126 -126
  65. package/web-ui/modules/config-template-confirm-pref.mjs +33 -0
  66. package/web-ui/modules/i18n.mjs +1823 -0
  67. package/web-ui/modules/plugins.computed.mjs +3 -0
  68. package/web-ui/modules/plugins.methods.mjs +3 -0
  69. package/web-ui/modules/plugins.storage.mjs +11 -0
  70. package/web-ui/modules/sessions-filters-url.mjs +85 -0
  71. package/web-ui/modules/skills.computed.mjs +107 -107
  72. package/web-ui/modules/skills.methods.mjs +481 -481
  73. package/web-ui/partials/index/layout-footer.html +13 -13
  74. package/web-ui/partials/index/layout-header.html +461 -402
  75. package/web-ui/partials/index/modal-config-template-agents.html +175 -125
  76. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  77. package/web-ui/partials/index/modal-health-check.html +72 -72
  78. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  79. package/web-ui/partials/index/modal-skills.html +200 -184
  80. package/web-ui/partials/index/modals-basic.html +165 -156
  81. package/web-ui/partials/index/panel-config-claude.html +159 -126
  82. package/web-ui/partials/index/panel-config-codex.html +255 -237
  83. package/web-ui/partials/index/panel-config-openclaw.html +78 -78
  84. package/web-ui/partials/index/panel-docs.html +147 -130
  85. package/web-ui/partials/index/panel-market.html +174 -174
  86. package/web-ui/partials/index/panel-orchestration.html +388 -397
  87. package/web-ui/partials/index/panel-plugins.html +273 -0
  88. package/web-ui/partials/index/panel-sessions.html +298 -292
  89. package/web-ui/partials/index/panel-settings.html +258 -190
  90. package/web-ui/partials/index/panel-usage.html +353 -213
  91. package/web-ui/session-helpers.mjs +573 -559
  92. package/web-ui/source-bundle.cjs +233 -233
  93. package/web-ui/styles/base-theme.css +264 -271
  94. package/web-ui/styles/controls-forms.css +369 -360
  95. package/web-ui/styles/docs-panel.css +247 -182
  96. package/web-ui/styles/feedback.css +108 -108
  97. package/web-ui/styles/health-check-dialog.css +144 -144
  98. package/web-ui/styles/layout-shell.css +602 -376
  99. package/web-ui/styles/modals-core.css +464 -464
  100. package/web-ui/styles/navigation-panels.css +390 -348
  101. package/web-ui/styles/openclaw-structured.css +266 -266
  102. package/web-ui/styles/plugins-panel.css +523 -0
  103. package/web-ui/styles/responsive.css +456 -450
  104. package/web-ui/styles/sessions-list.css +400 -400
  105. package/web-ui/styles/sessions-preview.css +411 -411
  106. package/web-ui/styles/sessions-toolbar-trash.css +268 -243
  107. package/web-ui/styles/sessions-usage.css +879 -628
  108. package/web-ui/styles/settings-panel.css +166 -0
  109. package/web-ui/styles/skills-list.css +303 -296
  110. package/web-ui/styles/skills-market.css +406 -335
  111. package/web-ui/styles/task-orchestration.css +822 -776
  112. package/web-ui/styles/titles-cards.css +408 -408
  113. package/web-ui/styles.css +20 -18
  114. package/web-ui.html +17 -17
  115. package/README.en.md +0 -349
@@ -0,0 +1,950 @@
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 === 'input_image') {
242
+ const raw = block.image_url != null ? block.image_url : block.imageUrl;
243
+ const url = typeof raw === 'string'
244
+ ? raw
245
+ : (raw && typeof raw === 'object' && typeof raw.url === 'string' ? raw.url : '');
246
+ if (url) {
247
+ out.push({ type: 'image_url', image_url: { url } });
248
+ }
249
+ continue;
250
+ }
251
+ // 容错:兼容已是 chat content 的 {type:"text"} / {type:"image_url"}
252
+ if (type === 'text' && typeof block.text === 'string') {
253
+ out.push({ type: 'text', text: block.text });
254
+ continue;
255
+ }
256
+ if (type === 'image_url' && block.image_url) {
257
+ out.push({ type: 'image_url', image_url: block.image_url });
258
+ }
259
+ }
260
+ if (out.length === 0) return '';
261
+ return out;
262
+ };
263
+
264
+ const toRole = (value) => {
265
+ const roleRaw = typeof value === 'string' ? value.trim().toLowerCase() : '';
266
+ return roleRaw === 'assistant' ? 'assistant' : (roleRaw === 'system' ? 'system' : 'user');
267
+ };
268
+
269
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
270
+ if (typeof input.role === 'string' && input.content != null) {
271
+ const role = toRole(input.role);
272
+ const content = Array.isArray(input.content)
273
+ ? toChatContent(input.content)
274
+ : input.content;
275
+ return content ? [{ role, content }] : [];
276
+ }
277
+ if (typeof input.type === 'string') {
278
+ const content = toChatContent([input]);
279
+ return content ? [{ role: 'user', content }] : [];
280
+ }
281
+ return [];
282
+ }
283
+
284
+ if (!Array.isArray(input)) {
285
+ return [];
286
+ }
287
+
288
+ const messages = [];
289
+ for (const item of input) {
290
+ if (!item || typeof item !== 'object') continue;
291
+
292
+ // Tool calls (Responses): { type: "function_call", call_id, name, arguments }
293
+ // Chat Completions equivalent: assistant message with tool_calls
294
+ if (typeof item.type === 'string' && item.type === 'function_call') {
295
+ const callId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
296
+ const name = typeof item.name === 'string' ? item.name.trim() : '';
297
+ const args = typeof item.arguments === 'string' ? item.arguments : '';
298
+ if (callId && name) {
299
+ messages.push({
300
+ role: 'assistant',
301
+ tool_calls: [{
302
+ id: callId,
303
+ type: 'function',
304
+ function: { name, arguments: args || '' }
305
+ }]
306
+ });
307
+ }
308
+ continue;
309
+ }
310
+
311
+ // Tool results (Responses): { type: "function_call_output", call_id, output }
312
+ // Chat Completions equivalent: { role: "tool", tool_call_id, content }
313
+ if (typeof item.type === 'string' && item.type === 'function_call_output') {
314
+ const toolCallId = typeof item.call_id === 'string' ? item.call_id.trim() : '';
315
+ let content = item.output;
316
+ if (typeof content !== 'string') {
317
+ try {
318
+ content = JSON.stringify(content);
319
+ } catch (_) {
320
+ content = String(content ?? '');
321
+ }
322
+ }
323
+ if (toolCallId) {
324
+ messages.push({ role: 'tool', tool_call_id: toolCallId, content: String(content || '') });
325
+ }
326
+ continue;
327
+ }
328
+
329
+ // message form
330
+ if (typeof item.role === 'string' && item.content != null) {
331
+ const role = toRole(item.role);
332
+ const content = Array.isArray(item.content)
333
+ ? toChatContent(item.content)
334
+ : item.content;
335
+ if (content) {
336
+ messages.push({ role, content });
337
+ }
338
+ continue;
339
+ }
340
+ }
341
+
342
+ if (messages.length > 0) {
343
+ return messages;
344
+ }
345
+
346
+ // 退化:把 input array 当作单条 user content blocks
347
+ const fallbackContent = toChatContent(input);
348
+ if (fallbackContent) {
349
+ return [{ role: 'user', content: fallbackContent }];
350
+ }
351
+ return [];
352
+ }
353
+
354
+ function convertResponsesRequestToChatCompletions(payload) {
355
+ const body = payload && typeof payload === 'object' ? payload : {};
356
+ const model = typeof body.model === 'string' ? body.model.trim() : '';
357
+ if (!model) {
358
+ return { error: 'responses 请求缺少 model' };
359
+ }
360
+
361
+ const messages = [];
362
+ // Align with Maxx/CLIProxyAPI style: map "instructions" to a leading system message.
363
+ if (typeof body.instructions === 'string' && body.instructions.trim()) {
364
+ messages.push({ role: 'system', content: body.instructions.trim() });
365
+ }
366
+ messages.push(...normalizeResponsesInputToChatMessages(body.input));
367
+ if (!messages.length) {
368
+ // codex sometimes sends empty input for probes; tolerate.
369
+ messages.push({ role: 'user', content: '' });
370
+ }
371
+
372
+ const maxOutputTokens = Number.parseInt(String(body.max_output_tokens), 10);
373
+ const stream = body.stream === true;
374
+
375
+ const chat = {
376
+ model,
377
+ messages,
378
+ stream: false,
379
+ temperature: Number.isFinite(body.temperature) ? Number(body.temperature) : undefined,
380
+ top_p: Number.isFinite(body.top_p) ? Number(body.top_p) : undefined,
381
+ max_tokens: Number.isFinite(maxOutputTokens) && maxOutputTokens > 0 ? maxOutputTokens : undefined
382
+ };
383
+ if (Array.isArray(body.stop) && body.stop.length) {
384
+ chat.stop = body.stop.filter((item) => typeof item === 'string' && item.trim());
385
+ }
386
+ // Best-effort: pass through tool definitions (most OpenAI-compatible providers accept these fields).
387
+ if (Array.isArray(body.tools) && body.tools.length) {
388
+ chat.tools = body.tools;
389
+ }
390
+ if (body.tool_choice !== undefined) {
391
+ chat.tool_choice = body.tool_choice;
392
+ }
393
+ if (body.response_format !== undefined) {
394
+ chat.response_format = body.response_format;
395
+ }
396
+ if (body.metadata !== undefined) {
397
+ chat.metadata = body.metadata;
398
+ }
399
+
400
+ // Remove undefined keys
401
+ Object.keys(chat).forEach((key) => chat[key] === undefined && delete chat[key]);
402
+
403
+ return { chat, streamRequested: stream };
404
+ }
405
+
406
+ function buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamPayload) {
407
+ const responseId = `resp_${crypto.randomBytes(10).toString('hex')}`;
408
+ const usage = upstreamPayload && upstreamPayload.usage && typeof upstreamPayload.usage === 'object'
409
+ ? upstreamPayload.usage
410
+ : null;
411
+ const createdAt = Math.floor(Date.now() / 1000);
412
+ const output = [];
413
+ const trimmedText = typeof text === 'string' ? text : '';
414
+ if (trimmedText) {
415
+ output.push({
416
+ id: `msg_${crypto.randomBytes(8).toString('hex')}`,
417
+ type: 'message',
418
+ role: 'assistant',
419
+ content: [{ type: 'output_text', text: trimmedText }]
420
+ });
421
+ }
422
+
423
+ // Convert chat.completions tool_calls into Responses-style function_call output items.
424
+ // This is important for Codex, which appends function_call + function_call_output back into `input`.
425
+ if (Array.isArray(toolCalls)) {
426
+ for (const call of toolCalls) {
427
+ if (!call || typeof call !== 'object') continue;
428
+ const callId = typeof call.id === 'string' && call.id.trim() ? call.id.trim() : `call_${crypto.randomBytes(8).toString('hex')}`;
429
+ const fn = call.function && typeof call.function === 'object' ? call.function : {};
430
+ const name = typeof fn.name === 'string' ? fn.name : '';
431
+ const args = typeof fn.arguments === 'string' ? fn.arguments : '';
432
+ if (!name) continue;
433
+ output.push({
434
+ type: 'function_call',
435
+ call_id: callId,
436
+ name,
437
+ arguments: args
438
+ });
439
+ }
440
+ }
441
+
442
+ const payload = {
443
+ id: responseId,
444
+ object: 'response',
445
+ model,
446
+ created_at: createdAt,
447
+ status: 'completed',
448
+ output,
449
+ output_text: trimmedText
450
+ };
451
+
452
+ if (usage) {
453
+ // Map chat.completions usage -> responses usage shape when possible.
454
+ const promptTokens = Number.isFinite(usage.prompt_tokens) ? Number(usage.prompt_tokens) : null;
455
+ const completionTokens = Number.isFinite(usage.completion_tokens) ? Number(usage.completion_tokens) : null;
456
+ const totalTokens = Number.isFinite(usage.total_tokens) ? Number(usage.total_tokens) : null;
457
+ if (promptTokens !== null || completionTokens !== null || totalTokens !== null) {
458
+ payload.usage = {
459
+ input_tokens: promptTokens ?? undefined,
460
+ output_tokens: completionTokens ?? undefined,
461
+ total_tokens: totalTokens ?? undefined
462
+ };
463
+ Object.keys(payload.usage).forEach((key) => payload.usage[key] === undefined && delete payload.usage[key]);
464
+ } else {
465
+ payload.usage = usage;
466
+ }
467
+ }
468
+
469
+ return payload;
470
+ }
471
+
472
+ function ensureResponseMetadata(response) {
473
+ const payload = response && typeof response === 'object' ? response : {};
474
+ if (typeof payload.created_at !== 'number') {
475
+ payload.created_at = Math.floor(Date.now() / 1000);
476
+ }
477
+ if (typeof payload.status !== 'string' || !payload.status.trim()) {
478
+ payload.status = 'completed';
479
+ }
480
+ if (!Array.isArray(payload.output)) {
481
+ payload.output = [];
482
+ }
483
+ return payload;
484
+ }
485
+
486
+ function sendResponsesSse(res, responsePayload) {
487
+ const response = ensureResponseMetadata(responsePayload);
488
+ const responseId = typeof response.id === 'string' && response.id.trim()
489
+ ? response.id.trim()
490
+ : `resp_${crypto.randomBytes(10).toString('hex')}`;
491
+ const model = typeof response.model === 'string' ? response.model : '';
492
+
493
+ let sequence = 0;
494
+ const nextSeq = () => {
495
+ sequence += 1;
496
+ return sequence;
497
+ };
498
+
499
+ writeSse(res, 'response.created', {
500
+ type: 'response.created',
501
+ response: {
502
+ id: responseId,
503
+ model,
504
+ created_at: response.created_at
505
+ }
506
+ });
507
+
508
+ const output = Array.isArray(response.output) ? response.output : [];
509
+ for (let outputIndex = 0; outputIndex < output.length; outputIndex += 1) {
510
+ const item = output[outputIndex];
511
+ if (!item || typeof item !== 'object') continue;
512
+ const itemType = typeof item.type === 'string' ? item.type : '';
513
+ const itemId = typeof item.id === 'string' && item.id.trim()
514
+ ? item.id.trim()
515
+ : (typeof item.call_id === 'string' && item.call_id.trim() ? item.call_id.trim() : `item_${crypto.randomBytes(8).toString('hex')}`);
516
+
517
+ // Emit item added so Codex can anchor subsequent deltas by output_index/content_index/item_id.
518
+ writeSse(res, 'response.output_item.added', {
519
+ type: 'response.output_item.added',
520
+ output_index: outputIndex,
521
+ item: { ...item, id: itemId }
522
+ });
523
+
524
+ if (itemType === 'message') {
525
+ const content = Array.isArray(item.content) ? item.content : [];
526
+ for (let contentIndex = 0; contentIndex < content.length; contentIndex += 1) {
527
+ const block = content[contentIndex];
528
+ if (!block || typeof block !== 'object') continue;
529
+ if (block.type !== 'output_text') continue;
530
+ const text = typeof block.text === 'string' ? block.text : '';
531
+ if (text) {
532
+ writeSse(res, 'response.output_text.delta', {
533
+ type: 'response.output_text.delta',
534
+ item_id: itemId,
535
+ output_index: outputIndex,
536
+ content_index: contentIndex,
537
+ delta: text,
538
+ sequence_number: nextSeq()
539
+ });
540
+ }
541
+ writeSse(res, 'response.output_text.done', {
542
+ type: 'response.output_text.done',
543
+ item_id: itemId,
544
+ output_index: outputIndex,
545
+ content_index: contentIndex,
546
+ text,
547
+ sequence_number: nextSeq()
548
+ });
549
+ }
550
+ }
551
+
552
+ // Emit item done for all item types (message/function_call/etc).
553
+ writeSse(res, 'response.output_item.done', {
554
+ type: 'response.output_item.done',
555
+ output_index: outputIndex,
556
+ item: { ...item, id: itemId },
557
+ sequence_number: nextSeq()
558
+ });
559
+ }
560
+
561
+ writeSse(res, 'response.completed', { type: 'response.completed', response });
562
+ writeSse(res, 'done', '[DONE]');
563
+ }
564
+
565
+ function extractResponsesOutputText(payload) {
566
+ if (!payload || typeof payload !== 'object') return '';
567
+ const output = Array.isArray(payload.output) ? payload.output : [];
568
+ for (const item of output) {
569
+ if (!item || typeof item !== 'object') continue;
570
+ if (item.type !== 'message') continue;
571
+ const content = Array.isArray(item.content) ? item.content : [];
572
+ for (const block of content) {
573
+ if (!block || typeof block !== 'object') continue;
574
+ if (block.type !== 'output_text') continue;
575
+ if (typeof block.text === 'string') return block.text;
576
+ }
577
+ }
578
+ if (typeof payload.output_text === 'string') return payload.output_text;
579
+ return '';
580
+ }
581
+
582
+ function toUpstreamNonStreamingResponsesPayload(payload) {
583
+ const body = payload && typeof payload === 'object' ? payload : {};
584
+ return { ...body, stream: false };
585
+ }
586
+
587
+ function shouldFallbackFromUpstreamResponses(status, bodyText) {
588
+ if (!Number.isFinite(status)) return false;
589
+ // Common "unsupported" status codes for a route.
590
+ if (status === 404 || status === 405 || status === 501) return true;
591
+
592
+ // Some OpenAI-compatible gateways respond with 500 + "not implemented" (e.g. convert_request_failed)
593
+ // instead of 404/405 for unsupported endpoints. In that case we can safely fallback to chat/completions.
594
+ const text = String(bodyText || '');
595
+ if (!text) return false;
596
+ if (/not implemented/i.test(text)) return true;
597
+ if (/convert_request_failed/i.test(text)) return true;
598
+ if (/unknown (endpoint|route)/i.test(text)) return true;
599
+ if (/unsupported.*\/?v1\/responses/i.test(text)) return true;
600
+ if (/does not support.*responses/i.test(text)) return true;
601
+
602
+ // Best-effort parse for structured error codes.
603
+ try {
604
+ const parsed = JSON.parse(text);
605
+ const code = parsed && parsed.error && typeof parsed.error.code === 'string' ? parsed.error.code : '';
606
+ const msg = parsed && parsed.error && typeof parsed.error.message === 'string' ? parsed.error.message : '';
607
+ if (code === 'convert_request_failed') return true;
608
+ if (/not implemented/i.test(msg)) return true;
609
+ if (/unknown (endpoint|route)/i.test(msg)) return true;
610
+ if (/unsupported.*\/?v1\/responses/i.test(msg)) return true;
611
+ if (/does not support.*responses/i.test(msg)) return true;
612
+ } catch (_) {}
613
+
614
+ return false;
615
+ }
616
+
617
+ function isLoopbackAddress(address) {
618
+ if (!address) return false;
619
+ const value = String(address);
620
+ return value === '127.0.0.1' || value === '::1' || value === '::ffff:127.0.0.1';
621
+ }
622
+
623
+ function writeSse(res, eventName, dataObj) {
624
+ if (eventName) {
625
+ res.write(`event: ${eventName}\n`);
626
+ }
627
+ if (dataObj === '[DONE]') {
628
+ res.write('data: [DONE]\n\n');
629
+ return;
630
+ }
631
+ res.write(`data: ${JSON.stringify(dataObj)}\n\n`);
632
+ }
633
+
634
+ async function proxyRequestJson(targetUrl, options = {}) {
635
+ const parsed = new URL(targetUrl);
636
+ const transport = parsed.protocol === 'https:' ? https : http;
637
+ const bodyText = options.body ? JSON.stringify(options.body) : '';
638
+ const headers = {
639
+ 'Accept': 'application/json',
640
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
641
+ ...(options.headers || {})
642
+ };
643
+ if (options.body) {
644
+ headers['Content-Length'] = Buffer.byteLength(bodyText, 'utf-8');
645
+ }
646
+
647
+ const timeoutMs = Number.isFinite(options.timeoutMs)
648
+ ? Math.max(1000, Number(options.timeoutMs))
649
+ : 30000;
650
+ return new Promise((resolve) => {
651
+ let settled = false;
652
+ const finish = (value) => {
653
+ if (settled) return;
654
+ settled = true;
655
+ resolve(value);
656
+ };
657
+ const req = transport.request({
658
+ protocol: parsed.protocol,
659
+ hostname: parsed.hostname,
660
+ port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
661
+ method: options.method || 'GET',
662
+ path: `${parsed.pathname}${parsed.search}`,
663
+ headers,
664
+ agent: parsed.protocol === 'https:' ? options.httpsAgent : options.httpAgent
665
+ }, (upstreamRes) => {
666
+ const chunks = [];
667
+ upstreamRes.on('data', (chunk) => chunk && chunks.push(chunk));
668
+ upstreamRes.on('end', () => {
669
+ const text = chunks.length ? Buffer.concat(chunks).toString('utf-8') : '';
670
+ finish({
671
+ ok: true,
672
+ status: upstreamRes.statusCode || 0,
673
+ headers: upstreamRes.headers || {},
674
+ bodyText: text
675
+ });
676
+ });
677
+ });
678
+ req.setTimeout(timeoutMs, () => {
679
+ try { req.destroy(new Error('timeout')); } catch (_) {}
680
+ finish({ ok: false, error: 'timeout' });
681
+ });
682
+ req.on('error', (err) => finish({ ok: false, error: err && err.message ? err.message : 'request failed' }));
683
+ if (bodyText) {
684
+ req.write(bodyText);
685
+ }
686
+ req.end();
687
+ });
688
+ }
689
+
690
+ function createOpenaiBridgeHttpHandler(options = {}) {
691
+ const settingsFile = options.settingsFile;
692
+ const expectedToken = typeof options.expectedToken === 'string' && options.expectedToken.trim()
693
+ ? options.expectedToken.trim()
694
+ : DEFAULT_BRIDGE_TOKEN;
695
+ const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
696
+ const httpAgent = options.httpAgent;
697
+ const httpsAgent = options.httpsAgent;
698
+
699
+ if (!settingsFile) {
700
+ throw new Error('createOpenaiBridgeHttpHandler 缺少 settingsFile');
701
+ }
702
+
703
+ const matchPath = (requestPath) => {
704
+ const normalized = String(requestPath || '');
705
+ const prefix = '/bridge/openai/';
706
+ if (!normalized.startsWith(prefix)) return null;
707
+ const rest = normalized.slice(prefix.length);
708
+ const [provider, ...tail] = rest.split('/').filter((part) => part.length > 0);
709
+ if (!provider) return null;
710
+ const tailPath = '/' + tail.join('/');
711
+ if (!tailPath.startsWith('/v1')) return null;
712
+ const suffix = tailPath === '/v1' ? '' : tailPath.replace(/^\/v1\/?/, '');
713
+ return { provider, suffix };
714
+ };
715
+
716
+ const handler = (req, res) => {
717
+ let parsedUrl;
718
+ try {
719
+ parsedUrl = new URL(req.url || '/', 'http://localhost');
720
+ } catch (_) {
721
+ return false;
722
+ }
723
+ const match = matchPath(parsedUrl.pathname || '/');
724
+ if (!match) return false;
725
+
726
+ void (async () => {
727
+ try {
728
+ const token = extractAuthorizationToken(req);
729
+ // 兼容:某些客户端在自定义 base_url 时可能不带 Authorization。
730
+ // 为避免在 LAN 暴露无鉴权的代理,这里仅允许 loopback 连接缺省 token。
731
+ const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
732
+ const isLoopback = isLoopbackAddress(remoteAddr);
733
+ if (!token && !isLoopback) {
734
+ res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
735
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
736
+ return;
737
+ }
738
+ // loopback 上的本地代理:允许客户端携带任意 Authorization(例如 Codex 会附带 provider apiKey)。
739
+ // 非 loopback 时仍强制校验 expectedToken,避免局域网被未授权调用。
740
+ if (!isLoopback && token && token !== expectedToken) {
741
+ res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
742
+ res.end(JSON.stringify({ error: 'Unauthorized' }));
743
+ return;
744
+ }
745
+
746
+ const upstream = resolveOpenaiBridgeUpstream(settingsFile, match.provider);
747
+ if (upstream.error) {
748
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
749
+ res.end(JSON.stringify({ error: upstream.error }));
750
+ return;
751
+ }
752
+
753
+ const suffix = match.suffix || '';
754
+ const normalizedSuffix = suffix.replace(/^\/+/, '');
755
+
756
+ const authHeader = upstream.apiKey
757
+ ? (/^bearer\s+/i.test(upstream.apiKey) ? upstream.apiKey : `Bearer ${upstream.apiKey}`)
758
+ : '';
759
+ const upstreamHeaders = upstream && upstream.headers && typeof upstream.headers === 'object' && !Array.isArray(upstream.headers)
760
+ ? upstream.headers
761
+ : {};
762
+
763
+ if (!normalizedSuffix || normalizedSuffix === 'models') {
764
+ if ((req.method || 'GET').toUpperCase() !== 'GET') {
765
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
766
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
767
+ return;
768
+ }
769
+
770
+ const url = joinApiUrl(upstream.baseUrl, 'models');
771
+ const result = await proxyRequestJson(url, {
772
+ method: 'GET',
773
+ headers: {
774
+ ...(authHeader ? { Authorization: authHeader } : {}),
775
+ ...upstreamHeaders
776
+ },
777
+ httpAgent,
778
+ httpsAgent
779
+ });
780
+ if (!result.ok) {
781
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
782
+ res.end(JSON.stringify({ error: `Upstream request failed: ${result.error}` }));
783
+ return;
784
+ }
785
+ res.writeHead(result.status || 502, { 'Content-Type': 'application/json; charset=utf-8' });
786
+ res.end(result.bodyText || '');
787
+ return;
788
+ }
789
+
790
+ if (normalizedSuffix !== 'responses') {
791
+ res.writeHead(404, { 'Content-Type': 'application/json; charset=utf-8' });
792
+ res.end(JSON.stringify({ error: 'Not Found' }));
793
+ return;
794
+ }
795
+
796
+ if ((req.method || 'GET').toUpperCase() !== 'POST') {
797
+ res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
798
+ res.end(JSON.stringify({ error: 'Method Not Allowed' }));
799
+ return;
800
+ }
801
+
802
+ const { body, error: bodyErr } = await readRequestBody(req, maxBodySize);
803
+ if (bodyErr) {
804
+ res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
805
+ res.end(JSON.stringify({ error: bodyErr }));
806
+ return;
807
+ }
808
+ const parsed = parseJsonOrError(body);
809
+ if (parsed.error) {
810
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
811
+ res.end(JSON.stringify({ error: `Invalid JSON: ${parsed.error}` }));
812
+ return;
813
+ }
814
+
815
+ const responsesRequest = parsed.value;
816
+ const streamRequested = !!(responsesRequest && typeof responsesRequest === 'object' && responsesRequest.stream === true);
817
+ const acceptHeader = req && req.headers ? (req.headers.accept || req.headers.Accept || '') : '';
818
+ const wantsSse = /text\/event-stream/i.test(String(acceptHeader || ''));
819
+
820
+ // Maxx-style behavior: prefer upstream /responses if supported.
821
+ // Fallback to /chat/completions conversion when upstream does not implement /responses (404/405).
822
+ const upstreamResponsesUrl = joinApiUrl(upstream.baseUrl, 'responses');
823
+ const upstreamResponsesResult = await proxyRequestJson(upstreamResponsesUrl, {
824
+ method: 'POST',
825
+ body: toUpstreamNonStreamingResponsesPayload(responsesRequest),
826
+ headers: {
827
+ ...(authHeader ? { Authorization: authHeader } : {}),
828
+ ...upstreamHeaders
829
+ },
830
+ httpAgent,
831
+ httpsAgent
832
+ });
833
+
834
+ if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 200 && upstreamResponsesResult.status < 300) {
835
+ const upstreamJson = parseJsonOrError(upstreamResponsesResult.bodyText);
836
+ if (upstreamJson.error) {
837
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
838
+ res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
839
+ return;
840
+ }
841
+ const upstreamPayload = upstreamJson.value;
842
+ if (streamRequested && wantsSse) {
843
+ res.writeHead(200, {
844
+ 'Content-Type': 'text/event-stream; charset=utf-8',
845
+ 'Cache-Control': 'no-cache',
846
+ 'Connection': 'keep-alive',
847
+ 'X-Accel-Buffering': 'no'
848
+ });
849
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
850
+ sendResponsesSse(res, upstreamPayload);
851
+ res.end();
852
+ return;
853
+ }
854
+
855
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
856
+ res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload)));
857
+ return;
858
+ }
859
+
860
+ if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400) {
861
+ if (!shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
862
+ res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
863
+ res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
864
+ return;
865
+ }
866
+ // fallthrough to chat/completions conversion
867
+ }
868
+
869
+ if (!upstreamResponsesResult.ok) {
870
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
871
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
872
+ return;
873
+ }
874
+
875
+ const converted = convertResponsesRequestToChatCompletions(responsesRequest);
876
+ if (converted.error) {
877
+ res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
878
+ res.end(JSON.stringify({ error: converted.error }));
879
+ return;
880
+ }
881
+
882
+ const upstreamUrl = joinApiUrl(upstream.baseUrl, 'chat/completions');
883
+ const upstreamResult = await proxyRequestJson(upstreamUrl, {
884
+ method: 'POST',
885
+ body: converted.chat,
886
+ headers: {
887
+ ...(authHeader ? { Authorization: authHeader } : {}),
888
+ ...upstreamHeaders
889
+ },
890
+ httpAgent,
891
+ httpsAgent
892
+ });
893
+ if (!upstreamResult.ok) {
894
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
895
+ res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
896
+ return;
897
+ }
898
+
899
+ const upstreamJson = parseJsonOrError(upstreamResult.bodyText);
900
+ if (upstreamResult.status >= 400) {
901
+ res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
902
+ res.end(upstreamResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
903
+ return;
904
+ }
905
+ if (upstreamJson.error) {
906
+ res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
907
+ res.end(JSON.stringify({ error: `Upstream JSON parse failed: ${upstreamJson.error}` }));
908
+ return;
909
+ }
910
+
911
+ const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
912
+ const extracted = extractChatCompletionResult(upstreamJson.value);
913
+ const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
914
+ const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
915
+ const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, upstreamJson.value);
916
+
917
+ if (converted.streamRequested && wantsSse) {
918
+ res.writeHead(200, {
919
+ 'Content-Type': 'text/event-stream; charset=utf-8',
920
+ 'Cache-Control': 'no-cache',
921
+ 'Connection': 'keep-alive',
922
+ 'X-Accel-Buffering': 'no'
923
+ });
924
+ if (typeof res.flushHeaders === 'function') res.flushHeaders();
925
+ sendResponsesSse(res, responsesPayload);
926
+ res.end();
927
+ return;
928
+ }
929
+
930
+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
931
+ res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
932
+ } catch (e) {
933
+ res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
934
+ res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
935
+ }
936
+ })();
937
+
938
+ return true;
939
+ };
940
+
941
+ handler.matchPath = matchPath;
942
+ return handler;
943
+ }
944
+
945
+ module.exports = {
946
+ readOpenaiBridgeSettings,
947
+ upsertOpenaiBridgeProvider,
948
+ resolveOpenaiBridgeUpstream,
949
+ createOpenaiBridgeHttpHandler
950
+ };