codexmate 0.0.29 → 0.0.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +363 -421
- package/README.zh.md +371 -354
- package/cli/agents-files.js +224 -224
- package/cli/archive-helpers.js +446 -446
- package/cli/auth-profiles.js +375 -375
- package/cli/builtin-proxy.js +1725 -1725
- package/cli/claude-proxy.js +1022 -1022
- package/cli/config-bootstrap.js +402 -384
- package/cli/config-health.js +454 -338
- package/cli/doctor-core.js +903 -903
- package/cli/import-skills-url.js +356 -356
- package/cli/local-bridge.js +324 -0
- package/cli/openai-bridge.js +1653 -1576
- package/cli/openclaw-config.js +629 -629
- package/cli/session-convert-args.js +69 -65
- package/cli/session-convert-io.js +82 -82
- package/cli/session-convert.js +150 -43
- package/cli/session-usage.concurrent.js +28 -28
- package/cli/session-usage.js +118 -118
- package/cli/session-usage.models.js +176 -176
- package/cli/skills.js +1141 -1141
- package/cli/zip-commands.js +510 -510
- package/cli.js +15778 -15340
- package/lib/automation.js +404 -404
- package/lib/cli-file-utils.js +151 -151
- package/lib/cli-models-utils.js +440 -440
- package/lib/cli-network-utils.js +190 -190
- package/lib/cli-path-utils.js +85 -85
- package/lib/cli-session-utils.js +121 -121
- package/lib/cli-sessions.js +417 -417
- package/lib/cli-utils.js +155 -155
- package/lib/cli-webhook.js +126 -126
- package/lib/download-artifacts.js +92 -92
- package/lib/mcp-stdio.js +453 -453
- package/lib/task-orchestrator.js +869 -869
- package/lib/text-diff.js +303 -303
- package/lib/workflow-engine.js +340 -340
- package/package.json +76 -76
- package/plugins/README.md +20 -20
- package/plugins/README.zh-CN.md +20 -20
- package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
- package/plugins/prompt-templates/computed.mjs +253 -253
- package/plugins/prompt-templates/index.mjs +8 -8
- package/plugins/prompt-templates/manifest.mjs +15 -15
- package/plugins/prompt-templates/methods.mjs +553 -553
- package/plugins/prompt-templates/overview.mjs +91 -91
- package/plugins/prompt-templates/ownership.mjs +19 -19
- package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
- package/plugins/prompt-templates/storage.mjs +64 -64
- package/plugins/registry.mjs +16 -16
- package/web-ui/app.js +646 -639
- package/web-ui/index.html +36 -36
- package/web-ui/logic.agents-diff.mjs +386 -386
- package/web-ui/logic.claude.mjs +168 -168
- package/web-ui/logic.codex.mjs +69 -69
- package/web-ui/logic.mjs +5 -5
- package/web-ui/logic.runtime.mjs +128 -128
- package/web-ui/logic.session-convert.mjs +70 -70
- package/web-ui/logic.sessions.mjs +765 -765
- package/web-ui/modules/api.mjs +90 -90
- package/web-ui/modules/app.computed.dashboard.mjs +248 -225
- package/web-ui/modules/app.computed.index.mjs +17 -17
- package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
- package/web-ui/modules/app.computed.session.mjs +999 -999
- package/web-ui/modules/app.constants.mjs +15 -15
- package/web-ui/modules/app.methods.agents.mjs +632 -632
- package/web-ui/modules/app.methods.claude-config.mjs +200 -200
- package/web-ui/modules/app.methods.codex-config.mjs +841 -892
- package/web-ui/modules/app.methods.index.mjs +94 -94
- package/web-ui/modules/app.methods.install.mjs +205 -205
- package/web-ui/modules/app.methods.navigation.mjs +774 -761
- package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
- package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
- package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
- package/web-ui/modules/app.methods.providers.mjs +529 -493
- package/web-ui/modules/app.methods.runtime.mjs +345 -345
- package/web-ui/modules/app.methods.session-actions.mjs +591 -593
- package/web-ui/modules/app.methods.session-browser.mjs +984 -984
- package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
- package/web-ui/modules/app.methods.session-trash.mjs +438 -438
- package/web-ui/modules/app.methods.startup-claude.mjs +534 -533
- package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
- package/web-ui/modules/app.methods.webhook.mjs +79 -79
- package/web-ui/modules/config-mode.computed.mjs +124 -124
- package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
- package/web-ui/modules/i18n.dict.mjs +3174 -3131
- package/web-ui/modules/i18n.mjs +62 -62
- package/web-ui/modules/plugins.computed.mjs +3 -3
- package/web-ui/modules/plugins.methods.mjs +3 -3
- package/web-ui/modules/plugins.storage.mjs +11 -11
- package/web-ui/modules/provider-url-display.mjs +17 -17
- package/web-ui/modules/sessions-filters-url.mjs +85 -85
- package/web-ui/modules/skills.computed.mjs +107 -107
- package/web-ui/modules/skills.methods.mjs +482 -481
- package/web-ui/partials/index/layout-footer.html +13 -13
- package/web-ui/partials/index/layout-header.html +500 -500
- package/web-ui/partials/index/modal-config-template-agents.html +174 -174
- package/web-ui/partials/index/modal-confirm-toast.html +32 -32
- package/web-ui/partials/index/modal-health-check.html +45 -45
- package/web-ui/partials/index/modal-openclaw-config.html +280 -280
- package/web-ui/partials/index/modal-skills.html +200 -200
- package/web-ui/partials/index/modals-basic.html +162 -162
- package/web-ui/partials/index/panel-config-claude.html +194 -194
- package/web-ui/partials/index/panel-config-codex.html +357 -323
- package/web-ui/partials/index/panel-config-codex.html.bak +337 -0
- package/web-ui/partials/index/panel-config-openclaw.html +83 -83
- package/web-ui/partials/index/panel-dashboard.html +219 -186
- package/web-ui/partials/index/panel-docs.html +147 -147
- package/web-ui/partials/index/panel-market.html +177 -177
- package/web-ui/partials/index/panel-orchestration.html +391 -391
- package/web-ui/partials/index/panel-plugins.html +253 -253
- package/web-ui/partials/index/panel-sessions.html +302 -316
- package/web-ui/partials/index/panel-settings.html +190 -190
- package/web-ui/partials/index/panel-trash.html +88 -88
- package/web-ui/partials/index/panel-usage.html +371 -371
- package/web-ui/res/json5.min.js +1 -1
- package/web-ui/res/vue.global.prod.js +13 -13
- package/web-ui/session-helpers.mjs +591 -576
- package/web-ui/source-bundle.cjs +233 -233
- package/web-ui/styles/base-theme.css +281 -281
- package/web-ui/styles/bridge-pool.css +197 -0
- package/web-ui/styles/controls-forms.css +422 -422
- package/web-ui/styles/dashboard.css +406 -274
- package/web-ui/styles/docs-panel.css +271 -271
- package/web-ui/styles/feedback.css +108 -108
- package/web-ui/styles/health-check-dialog.css +144 -144
- package/web-ui/styles/layout-shell.css +626 -626
- package/web-ui/styles/modals-core.css +466 -466
- package/web-ui/styles/navigation-panels.css +391 -391
- package/web-ui/styles/openclaw-structured.css +266 -266
- package/web-ui/styles/plugins-panel.css +564 -523
- package/web-ui/styles/responsive.css +454 -454
- package/web-ui/styles/sessions-list.css +417 -419
- package/web-ui/styles/sessions-preview.css +407 -411
- package/web-ui/styles/sessions-toolbar-trash.css +348 -330
- package/web-ui/styles/sessions-usage.css +1040 -1040
- package/web-ui/styles/settings-panel.css +349 -349
- package/web-ui/styles/skills-list.css +305 -303
- package/web-ui/styles/skills-market.css +429 -406
- package/web-ui/styles/task-orchestration.css +822 -822
- package/web-ui/styles/titles-cards.css +472 -472
- package/web-ui/styles/trash-panel.css +90 -90
- package/web-ui/styles/webhook.css +81 -81
- package/web-ui/styles.css +24 -23
- package/web-ui.html +17 -17
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const { URL } = require('url');
|
|
3
|
+
const {
|
|
4
|
+
readOpenaiBridgeSettings,
|
|
5
|
+
convertResponsesRequestToChatCompletions,
|
|
6
|
+
streamChatCompletionsAsResponsesSse,
|
|
7
|
+
proxyRequestJson,
|
|
8
|
+
ensureResponseMetadata,
|
|
9
|
+
sendResponsesSse,
|
|
10
|
+
extractAuthorizationToken,
|
|
11
|
+
readRequestBody,
|
|
12
|
+
parseJsonOrError,
|
|
13
|
+
extractChatCompletionResult,
|
|
14
|
+
buildResponsesPayloadFromChatResult,
|
|
15
|
+
retryTransientRequest,
|
|
16
|
+
shouldFallbackFromUpstreamResponses,
|
|
17
|
+
isTransientNetworkError,
|
|
18
|
+
isLoopbackAddress
|
|
19
|
+
} = require('./openai-bridge');
|
|
20
|
+
const { isValidHttpUrl, normalizeBaseUrl, joinApiUrl } = require('../lib/cli-utils');
|
|
21
|
+
|
|
22
|
+
const BUILTIN_PROXY_PROVIDER_NAME = 'codexmate-proxy';
|
|
23
|
+
const BUILTIN_LOCAL_PROVIDER_NAME = 'local';
|
|
24
|
+
const CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
25
|
+
const CIRCUIT_BREAKER_COOLDOWN_MS = 5 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
function buildUpstreamPool(readConfigFn, openaiBridgeFile, excludedProviders) {
|
|
28
|
+
let config;
|
|
29
|
+
try { config = readConfigFn(); } catch (e) { return { error: '读取配置失败' }; }
|
|
30
|
+
const providers = (config && typeof config.model_providers === 'object' && !Array.isArray(config.model_providers))
|
|
31
|
+
? config.model_providers : {};
|
|
32
|
+
const pool = [];
|
|
33
|
+
const excludedSet = new Set(
|
|
34
|
+
(Array.isArray(excludedProviders) ? excludedProviders : [])
|
|
35
|
+
.filter(n => typeof n === 'string' && n.trim())
|
|
36
|
+
.map(n => n.trim().toLowerCase())
|
|
37
|
+
);
|
|
38
|
+
for (const [name, p] of Object.entries(providers)) {
|
|
39
|
+
if (!p || typeof p !== 'object') continue;
|
|
40
|
+
const lower = name.toLowerCase();
|
|
41
|
+
if (lower === BUILTIN_LOCAL_PROVIDER_NAME || lower === BUILTIN_PROXY_PROVIDER_NAME) continue;
|
|
42
|
+
if (excludedSet.has(lower)) continue;
|
|
43
|
+
const bridge = typeof p.codexmate_bridge === 'string' ? p.codexmate_bridge.trim() : '';
|
|
44
|
+
if (bridge === 'local') continue; // avoid loop: local→local
|
|
45
|
+
const baseUrl = typeof p.base_url === 'string' ? p.base_url.trim() : '';
|
|
46
|
+
if (!isValidHttpUrl(normalizeBaseUrl(baseUrl))) continue;
|
|
47
|
+
const authMethod = typeof p.preferred_auth_method === 'string' ? p.preferred_auth_method.trim() : '';
|
|
48
|
+
pool.push({ name, baseUrl: normalizeBaseUrl(baseUrl), authMethod, requiresOpenaiAuth: !!p.requires_openai_auth });
|
|
49
|
+
}
|
|
50
|
+
if (pool.length === 0) return { error: '请先添加上游 provider' };
|
|
51
|
+
return { pool };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function resolveUpstreamAuth(entry, openaiBridgeFile, reqAuthToken) {
|
|
55
|
+
if (entry.authMethod === 'codexmate' || entry.requiresOpenaiAuth) {
|
|
56
|
+
const token = reqAuthToken || '';
|
|
57
|
+
return token ? (token.startsWith('sk-') ? `Bearer ${token}` : `Bearer ${token}`) : '';
|
|
58
|
+
}
|
|
59
|
+
if (entry.authMethod === 'openai-bridge') {
|
|
60
|
+
const settings = readOpenaiBridgeSettings(openaiBridgeFile);
|
|
61
|
+
const upstream = settings.providers ? settings.providers[entry.name] : null;
|
|
62
|
+
if (upstream && upstream.apiKey) {
|
|
63
|
+
return upstream.apiKey.startsWith('Bearer ') ? upstream.apiKey : `Bearer ${upstream.apiKey}`;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return '';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function createLocalBridgeHttpHandler(options = {}) {
|
|
70
|
+
const readConfigFn = options.readConfigFn;
|
|
71
|
+
const openaiBridgeFile = options.openaiBridgeFile;
|
|
72
|
+
const expectedToken = typeof options.expectedToken === 'string' ? options.expectedToken.trim() : '';
|
|
73
|
+
const maxBodySize = Number.isFinite(options.maxBodySize) ? options.maxBodySize : 0;
|
|
74
|
+
const httpAgent = options.httpAgent;
|
|
75
|
+
const httpsAgent = options.httpsAgent;
|
|
76
|
+
const maxUpstreamBytes = Number.isFinite(options.maxUpstreamBytes) && options.maxUpstreamBytes > 0
|
|
77
|
+
? Math.floor(options.maxUpstreamBytes)
|
|
78
|
+
: Math.max(16 * 1024 * 1024, maxBodySize > 0 ? maxBodySize * 4 : 0);
|
|
79
|
+
|
|
80
|
+
if (typeof readConfigFn !== 'function') throw new Error('createLocalBridgeHttpHandler 缺少 readConfigFn');
|
|
81
|
+
|
|
82
|
+
const circuitState = new Map(); // name → { failures, openUntil }
|
|
83
|
+
let rrIndex = 0;
|
|
84
|
+
|
|
85
|
+
function pickUpstream(pool) {
|
|
86
|
+
const now = Date.now();
|
|
87
|
+
for (let i = 0; i < pool.length; i++) {
|
|
88
|
+
const idx = rrIndex++ % pool.length;
|
|
89
|
+
const entry = pool[idx];
|
|
90
|
+
const st = circuitState.get(entry.name);
|
|
91
|
+
if (st && st.openUntil > now) continue; // circuit open
|
|
92
|
+
return { entry, idx };
|
|
93
|
+
}
|
|
94
|
+
// all circuits open, reset and retry first
|
|
95
|
+
circuitState.clear();
|
|
96
|
+
return { entry: pool[0], idx: 0 };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function recordFailure(name) {
|
|
100
|
+
let st = circuitState.get(name);
|
|
101
|
+
if (!st) { st = { failures: 0, openUntil: 0 }; circuitState.set(name, st); }
|
|
102
|
+
st.failures++;
|
|
103
|
+
if (st.failures >= CIRCUIT_BREAKER_THRESHOLD) {
|
|
104
|
+
st.openUntil = Date.now() + CIRCUIT_BREAKER_COOLDOWN_MS;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function recordSuccess(name) {
|
|
109
|
+
circuitState.delete(name);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const localBridgeSettingsFile = options.localBridgeSettingsFile || '';
|
|
113
|
+
|
|
114
|
+
function readExcludedProviders() {
|
|
115
|
+
if (!localBridgeSettingsFile) return [];
|
|
116
|
+
try {
|
|
117
|
+
if (!fs.existsSync(localBridgeSettingsFile)) return [];
|
|
118
|
+
const raw = JSON.parse(fs.readFileSync(localBridgeSettingsFile, 'utf-8'));
|
|
119
|
+
const excluded = Array.isArray(raw.excludedProviders)
|
|
120
|
+
? raw.excludedProviders.filter(n => typeof n === 'string' && n.trim())
|
|
121
|
+
: [];
|
|
122
|
+
// 解二: auto-exclude lastActiveProvider
|
|
123
|
+
const last = typeof raw.lastActiveProvider === 'string' ? raw.lastActiveProvider.trim() : '';
|
|
124
|
+
if (last && !excluded.some(n => n.toLowerCase() === last.toLowerCase())) {
|
|
125
|
+
excluded.push(last);
|
|
126
|
+
}
|
|
127
|
+
return excluded;
|
|
128
|
+
} catch (e) { return []; }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const handler = (req, res) => {
|
|
132
|
+
let parsedUrl;
|
|
133
|
+
try { parsedUrl = new URL(req.url || '/', 'http://localhost'); } catch (_) { return false; }
|
|
134
|
+
const pathname = parsedUrl.pathname || '/';
|
|
135
|
+
if (!pathname.startsWith('/bridge/local/')) return false;
|
|
136
|
+
const suffix = pathname.replace(/^\/bridge\/local\/?/, '');
|
|
137
|
+
if (!suffix.startsWith('v1')) return false;
|
|
138
|
+
|
|
139
|
+
void (async () => {
|
|
140
|
+
try {
|
|
141
|
+
const token = extractAuthorizationToken(req);
|
|
142
|
+
const remoteAddr = req && req.socket ? req.socket.remoteAddress : '';
|
|
143
|
+
const isLoopback = isLoopbackAddress(remoteAddr);
|
|
144
|
+
if (!isLoopback && !expectedToken) {
|
|
145
|
+
res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
146
|
+
res.end(JSON.stringify({ error: 'Remote access is disabled (set CODEXMATE_HTTP_TOKEN)' }));
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (!token && !isLoopback) {
|
|
150
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
151
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
if (!isLoopback && token && token !== expectedToken) {
|
|
155
|
+
res.writeHead(401, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
156
|
+
res.end(JSON.stringify({ error: 'Unauthorized' }));
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const poolResult = buildUpstreamPool(readConfigFn, openaiBridgeFile, readExcludedProviders());
|
|
161
|
+
if (poolResult.error) {
|
|
162
|
+
res.writeHead(503, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
163
|
+
res.end(JSON.stringify({ error: poolResult.error }));
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const pool = poolResult.pool;
|
|
167
|
+
|
|
168
|
+
const { entry, idx } = pickUpstream(pool);
|
|
169
|
+
const authHeader = resolveUpstreamAuth(entry, openaiBridgeFile, token);
|
|
170
|
+
|
|
171
|
+
const normalizedSuffix = suffix.replace(/^v1\/?/, '');
|
|
172
|
+
const upstreamBase = entry.baseUrl.replace(/\/+$/, '');
|
|
173
|
+
|
|
174
|
+
if (!normalizedSuffix) {
|
|
175
|
+
if ((req.method || 'GET').toUpperCase() !== 'GET') {
|
|
176
|
+
res.writeHead(405, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
177
|
+
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
181
|
+
res.end(JSON.stringify({ object: 'codexmate.local_bridge', provider: entry.name, status: 'ok', pool: pool.map(p => p.name) }));
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (normalizedSuffix === 'responses' && (req.method || 'GET').toUpperCase() === 'POST') {
|
|
186
|
+
const bodyResult = await readRequestBody(req, maxBodySize);
|
|
187
|
+
if (bodyResult.error) {
|
|
188
|
+
res.writeHead(413, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
189
|
+
res.end(JSON.stringify({ error: bodyResult.error }));
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
const parsed = parseJsonOrError(bodyResult.body);
|
|
193
|
+
if (parsed.error) {
|
|
194
|
+
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
195
|
+
res.end(JSON.stringify({ error: parsed.error }));
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const responsesRequest = parsed.value;
|
|
199
|
+
const wantsSse = !!(responsesRequest && responsesRequest.stream);
|
|
200
|
+
const upstreamResponsesUrl = joinApiUrl(upstreamBase, 'responses');
|
|
201
|
+
const upstreamResponsesResult = await retryTransientRequest(() => proxyRequestJson(upstreamResponsesUrl, {
|
|
202
|
+
method: 'POST',
|
|
203
|
+
body: bodyResult.body,
|
|
204
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
205
|
+
maxBytes: maxUpstreamBytes,
|
|
206
|
+
httpAgent,
|
|
207
|
+
httpsAgent
|
|
208
|
+
}));
|
|
209
|
+
|
|
210
|
+
if (upstreamResponsesResult.ok && upstreamResponsesResult.status < 400) {
|
|
211
|
+
recordSuccess(entry.name);
|
|
212
|
+
const upstreamPayload = parseJsonOrError(upstreamResponsesResult.bodyText);
|
|
213
|
+
if (upstreamPayload.error) {
|
|
214
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
215
|
+
res.end(JSON.stringify({ error: `Upstream parse failed: ${upstreamPayload.error}` }));
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (wantsSse) {
|
|
219
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
220
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
221
|
+
sendResponsesSse(res, upstreamPayload.value);
|
|
222
|
+
res.end();
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
226
|
+
res.end(JSON.stringify(ensureResponseMetadata(upstreamPayload.value)));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (upstreamResponsesResult.ok && upstreamResponsesResult.status >= 400 && !shouldFallbackFromUpstreamResponses(upstreamResponsesResult.status, upstreamResponsesResult.bodyText)) {
|
|
231
|
+
recordFailure(entry.name);
|
|
232
|
+
res.writeHead(upstreamResponsesResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
233
|
+
res.end(upstreamResponsesResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
if (!upstreamResponsesResult.ok) {
|
|
238
|
+
recordFailure(entry.name);
|
|
239
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
240
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResponsesResult.error}` }));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// fallthrough to chat/completions conversion
|
|
245
|
+
recordSuccess(entry.name);
|
|
246
|
+
const converted = convertResponsesRequestToChatCompletions(responsesRequest);
|
|
247
|
+
if (converted.error) {
|
|
248
|
+
res.writeHead(400, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
249
|
+
res.end(JSON.stringify({ error: converted.error }));
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
const chatUrl = joinApiUrl(upstreamBase, 'chat/completions');
|
|
253
|
+
const chatResult = await retryTransientRequest(() => proxyRequestJson(chatUrl, {
|
|
254
|
+
method: 'POST',
|
|
255
|
+
body: JSON.stringify(converted.chat),
|
|
256
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}), 'Content-Type': 'application/json' },
|
|
257
|
+
maxBytes: maxUpstreamBytes,
|
|
258
|
+
httpAgent,
|
|
259
|
+
httpsAgent
|
|
260
|
+
}));
|
|
261
|
+
if (!chatResult.ok) {
|
|
262
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
263
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${chatResult.error}` }));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const chatJson = parseJsonOrError(chatResult.bodyText);
|
|
267
|
+
if (chatResult.status >= 400) {
|
|
268
|
+
res.writeHead(chatResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
269
|
+
res.end(chatResult.bodyText || JSON.stringify({ error: 'Upstream error' }));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (chatJson.error) {
|
|
273
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
274
|
+
res.end(JSON.stringify({ error: `Upstream parse failed: ${chatJson.error}` }));
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
const extracted = extractChatCompletionResult(chatJson.value);
|
|
278
|
+
const text = extracted && typeof extracted.text === 'string' ? extracted.text : '';
|
|
279
|
+
const toolCalls = extracted && Array.isArray(extracted.toolCalls) ? extracted.toolCalls : [];
|
|
280
|
+
const model = typeof converted.chat.model === 'string' ? converted.chat.model : '';
|
|
281
|
+
const responsesPayload = buildResponsesPayloadFromChatResult(model, text, toolCalls, chatJson.value);
|
|
282
|
+
if (wantsSse) {
|
|
283
|
+
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'X-Accel-Buffering': 'no' });
|
|
284
|
+
if (typeof res.flushHeaders === 'function') res.flushHeaders();
|
|
285
|
+
sendResponsesSse(res, responsesPayload);
|
|
286
|
+
res.end();
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
290
|
+
res.end(JSON.stringify(ensureResponseMetadata(responsesPayload)));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// passthrough for other v1/* paths
|
|
295
|
+
const upstreamUrl = joinApiUrl(upstreamBase, normalizedSuffix);
|
|
296
|
+
const upstreamResult = await retryTransientRequest(() => proxyRequestJson(upstreamUrl, {
|
|
297
|
+
method: req.method || 'GET',
|
|
298
|
+
body: null,
|
|
299
|
+
headers: { ...(authHeader ? { Authorization: authHeader } : {}) },
|
|
300
|
+
maxBytes: maxUpstreamBytes,
|
|
301
|
+
httpAgent,
|
|
302
|
+
httpsAgent
|
|
303
|
+
}));
|
|
304
|
+
if (!upstreamResult.ok) {
|
|
305
|
+
recordFailure(entry.name);
|
|
306
|
+
res.writeHead(502, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
307
|
+
res.end(JSON.stringify({ error: `Upstream request failed: ${upstreamResult.error}` }));
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
recordSuccess(entry.name);
|
|
311
|
+
res.writeHead(upstreamResult.status, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
312
|
+
res.end(upstreamResult.bodyText);
|
|
313
|
+
} catch (e) {
|
|
314
|
+
res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
|
|
315
|
+
res.end(JSON.stringify({ error: e && e.message ? e.message : 'Internal Error' }));
|
|
316
|
+
}
|
|
317
|
+
})();
|
|
318
|
+
return true;
|
|
319
|
+
};
|
|
320
|
+
|
|
321
|
+
return handler;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
module.exports = { createLocalBridgeHttpHandler };
|