codexmate 0.0.28 → 0.0.30

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 (50) hide show
  1. package/cli/builtin-proxy.js +107 -2
  2. package/cli/config-bootstrap.js +30 -12
  3. package/cli/config-health.js +117 -1
  4. package/cli/local-bridge.js +324 -0
  5. package/cli/openai-bridge.js +195 -31
  6. package/cli.js +245 -28
  7. package/lib/cli-webhook.js +126 -0
  8. package/package.json +1 -1
  9. package/web-ui/app.js +28 -8
  10. package/web-ui/index.html +1 -0
  11. package/web-ui/logic.codex.mjs +13 -0
  12. package/web-ui/modules/app.computed.dashboard.mjs +25 -2
  13. package/web-ui/modules/app.computed.session.mjs +22 -17
  14. package/web-ui/modules/app.methods.claude-config.mjs +12 -2
  15. package/web-ui/modules/app.methods.codex-config.mjs +25 -0
  16. package/web-ui/modules/app.methods.index.mjs +2 -0
  17. package/web-ui/modules/app.methods.navigation.mjs +39 -8
  18. package/web-ui/modules/app.methods.providers.mjs +125 -8
  19. package/web-ui/modules/app.methods.session-actions.mjs +1 -1
  20. package/web-ui/modules/app.methods.session-browser.mjs +1 -1
  21. package/web-ui/modules/app.methods.session-trash.mjs +3 -4
  22. package/web-ui/modules/app.methods.startup-claude.mjs +1 -0
  23. package/web-ui/modules/app.methods.webhook.mjs +79 -0
  24. package/web-ui/modules/i18n.dict.mjs +1109 -72
  25. package/web-ui/modules/i18n.mjs +9 -3
  26. package/web-ui/modules/skills.methods.mjs +1 -0
  27. package/web-ui/partials/index/layout-header.html +25 -0
  28. package/web-ui/partials/index/modals-basic.html +0 -3
  29. package/web-ui/partials/index/panel-config-claude.html +8 -2
  30. package/web-ui/partials/index/panel-config-codex.html +28 -3
  31. package/web-ui/partials/index/panel-dashboard.html +33 -0
  32. package/web-ui/partials/index/panel-market.html +3 -3
  33. package/web-ui/partials/index/panel-plugins.html +2 -2
  34. package/web-ui/partials/index/panel-sessions.html +1 -9
  35. package/web-ui/partials/index/panel-settings.html +71 -134
  36. package/web-ui/partials/index/panel-trash.html +88 -0
  37. package/web-ui/session-helpers.mjs +20 -2
  38. package/web-ui/styles/dashboard.css +132 -0
  39. package/web-ui/styles/docs-panel.css +63 -39
  40. package/web-ui/styles/layout-shell.css +54 -34
  41. package/web-ui/styles/plugins-panel.css +121 -80
  42. package/web-ui/styles/sessions-list.css +41 -43
  43. package/web-ui/styles/sessions-preview.css +34 -38
  44. package/web-ui/styles/sessions-toolbar-trash.css +31 -27
  45. package/web-ui/styles/settings-panel.css +197 -33
  46. package/web-ui/styles/skills-list.css +12 -10
  47. package/web-ui/styles/skills-market.css +67 -44
  48. package/web-ui/styles/trash-panel.css +90 -0
  49. package/web-ui/styles/webhook.css +81 -0
  50. package/web-ui/styles.css +2 -0
@@ -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 };