-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
586 lines (514 loc) · 18 KB
/
Copy pathmain.js
File metadata and controls
586 lines (514 loc) · 18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
const { app, BrowserWindow, ipcMain, shell, clipboard, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const http = require('http');
const https = require('https');
// ===================== Global uncaught exception handler =====================
process.on('uncaughtException', (err) => {
const msg = err.message || '';
let hint = '';
if (msg.includes('EACCES')) {
hint = 'Port is occupied, please close other proxy programs first.';
} else if (msg.includes('EADDRINUSE')) {
hint = 'Port is already in use, please stop other proxies first.';
} else {
hint = `Error: ${msg}`;
}
dialog.showErrorBox('Startup Failed', `Proxy failed to start\n\n${hint}`);
});
// ===================== Built-in Node.js proxy (replaces Python codex-relay + filter proxy) =====================
class NodeProxy {
constructor() {
this.server = null;
this.port = null;
this.upstream = null;
this.apiKey = null;
this.filterImages = false;
}
start(options) {
this.port = options.port;
this.upstream = options.upstream.replace(/\/+$/, '');
this.apiKey = options.apiKey;
this.filterImages = options.filterImages || false;
return new Promise((resolve, reject) => {
try {
this.server = http.createServer((req, res) => this._handle(req, res));
this.server.listen(this.port, '127.0.0.1', () => resolve());
this.server.on('error', (err) => {
this.server = null;
reject(err);
});
} catch (err) {
reject(err);
}
});
}
stop() {
if (this.server) {
try { this.server.close(); } catch (e) { /* ignore */ }
this.server = null;
}
}
isRunning() {
return this.server !== null;
}
_handle(clientReq, clientRes) {
const chunks = [];
clientReq.on('data', chunk => chunks.push(chunk));
clientReq.on('end', () => {
let body = Buffer.concat(chunks);
const isStream = clientReq.headers['accept'] === 'text/event-stream';
// Check if path needs rewriting: /v1/responses -> /v1/chat/completions
const clientPath = clientReq.url || '/';
const needsRewrite = clientPath.includes('/responses');
// Filter out non-text content (needed for DeepSeek)
if (this.filterImages && body.length > 0) {
body = this._filterBody(body, clientReq.headers['content-type']);
}
// Translate request body: Responses API -> Chat Completions
if (needsRewrite && body.length > 0) {
body = this._translateRequest(body);
}
const upstreamUrl = new URL(this.upstream);
// Rewrite path: /v1/responses -> /v1/chat/completions
const upstreamPath = needsRewrite
? clientPath.replace('/responses', '/chat/completions')
: clientPath;
const options = {
hostname: upstreamUrl.hostname,
port: upstreamUrl.port || (upstreamUrl.protocol === 'https:' ? 443 : 80),
path: upstreamPath,
method: clientReq.method,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
'Accept': clientReq.headers['accept'] || 'application/json',
'User-Agent': 'codex-setup/1.0'
},
rejectUnauthorized: true
};
const proxyReq = https.request(options, (proxyRes) => {
const resHeaders = {};
for (const [k, v] of Object.entries(proxyRes.headers)) {
if (!['transfer-encoding', 'content-encoding', 'connection'].includes(k)) {
resHeaders[k] = v;
}
}
if (proxyRes.statusCode !== 200) {
const errChunks = [];
proxyRes.on('data', c => errChunks.push(c));
proxyRes.on('end', () => {
clientRes.writeHead(proxyRes.statusCode, resHeaders);
clientRes.end(Buffer.concat(errChunks));
});
return;
}
// Translate response: Chat Completions -> Responses API
if (needsRewrite && isStream) {
// Streaming: translate line by line
clientRes.writeHead(200, resHeaders);
this._translateStreamResponse(proxyRes, clientRes);
} else if (needsRewrite) {
// Non-streaming: translate entire body
const outChunks = [];
proxyRes.on('data', c => outChunks.push(c));
proxyRes.on('end', () => {
const translated = this._translateResponse(Buffer.concat(outChunks));
clientRes.writeHead(200, { ...resHeaders, 'content-length': String(Buffer.byteLength(translated)) });
clientRes.end(translated);
});
} else {
clientRes.writeHead(200, resHeaders);
proxyRes.pipe(clientRes);
}
});
proxyReq.on('error', (err) => {
clientRes.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
clientRes.end(`Proxy connection failed: ${err.message}`);
});
proxyReq.setTimeout(30000, () => {
proxyReq.destroy();
try { clientRes.writeHead(504); clientRes.end('Proxy timeout'); } catch (e) { /* ignore */ }
});
if (body.length > 0) proxyReq.write(body);
proxyReq.end();
});
clientReq.on('error', () => {
try { clientRes.writeHead(502); clientRes.end('Request error'); } catch (e) { /* ignore */ }
});
}
/**
* Extract plain text from a Responses API content field.
* content can be a string, an array of content blocks, or undefined.
*/
_extractText(content) {
if (typeof content === 'string') return content;
if (Array.isArray(content)) {
return content
.filter(c => c && (c.type === 'text' || c.type === 'input_text'))
.map(c => c.text || '')
.join('\n');
}
return '';
}
/**
* Map non-standard roles to standard Chat Completions roles.
* Third-party APIs do not support "developer" etc.
*/
_mapRole(role) {
if (role === 'developer') return 'system';
return role;
}
_translateRequest(body) {
try {
const req = JSON.parse(body.toString('utf-8'));
const messages = [];
// instructions → system message
if (req.instructions) {
messages.push({ role: 'system', content: req.instructions });
}
// input → message history
if (typeof req.input === 'string') {
messages.push({ role: 'user', content: req.input });
} else if (Array.isArray(req.input)) {
for (const item of req.input) {
if (typeof item === 'string') {
messages.push({ role: 'user', content: item });
} else if (item && item.role) {
// content may be string OR array of content blocks
messages.push({
role: this._mapRole(item.role),
content: this._extractText(item.content)
});
} else if (item && item.type === 'text') {
messages.push({ role: 'user', content: item.text || '' });
}
}
}
// Build Chat Completions request body
const chatReq = {
model: req.model,
messages: messages,
stream: req.stream !== undefined ? req.stream : true,
max_tokens: req.max_output_tokens || 4096,
temperature: req.temperature || 0.7,
top_p: req.top_p || 0.95
};
// Forward tool definitions if present
if (req.tools) chatReq.tools = req.tools;
return Buffer.from(JSON.stringify(chatReq), 'utf-8');
} catch (e) {
// Parse failure: forward body unchanged
return body;
}
}
/** Translate response body: Chat Completions -> Responses API (non-streaming) */
_translateResponse(body) {
try {
const chatRes = JSON.parse(body.toString('utf-8'));
// Extract content
let text = '';
if (chatRes.choices && chatRes.choices.length > 0) {
const choice = chatRes.choices[0];
text = choice.message?.content || choice.delta?.content || '';
}
// Build Responses API format
const respRes = {
id: chatRes.id || ('resp_' + Date.now()),
object: 'response',
status: 'completed',
created: Math.floor(Date.now() / 1000),
model: chatRes.model || '',
output: text ? [{ type: 'text', text }] : [],
usage: chatRes.usage || { input_tokens: 0, output_tokens: 0, total_tokens: 0 }
};
return Buffer.from(JSON.stringify(respRes), 'utf-8');
} catch (e) {
return body;
}
}
/** Translate streaming response SSE: Chat Completions SSE -> Responses API SSE */
_translateStreamResponse(proxyRes, clientRes) {
let buffer = '';
proxyRes.on('data', (chunk) => {
buffer += chunk.toString('utf-8');
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // keep incomplete lines
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6).trim();
// Chat Completions SSE end-of-stream marker
if (data === '[DONE]') {
// Send Responses API end-of-stream marker
clientRes.write('data: [DONE]\n\n');
continue;
}
try {
const chatChunk = JSON.parse(data);
// Only translate chunks with content
const content = chatChunk.choices?.[0]?.delta?.content || '';
const finishReason = chatChunk.choices?.[0]?.finish_reason;
const respChunk = {
id: chatChunk.id || ('resp_' + Date.now()),
object: 'response',
status: finishReason === 'stop' ? 'completed' : 'in_progress',
type: 'response.output_text.delta',
delta: content,
output: content ? [{ type: 'text', text: content }] : []
};
clientRes.write(`data: ${JSON.stringify(respChunk)}\n\n`);
if (finishReason === 'stop') {
// Send usage if available
if (chatChunk.usage) {
const usageChunk = {
id: chatChunk.id,
object: 'response',
status: 'completed',
type: 'response.usage',
usage: chatChunk.usage
};
clientRes.write(`data: ${JSON.stringify(usageChunk)}\n\n`);
}
clientRes.write('data: [DONE]\n\n');
}
} catch (e) {
// Forward unparseable chunks as-is
clientRes.write(line + '\n');
}
}
});
proxyRes.on('end', () => {
clientRes.end();
});
proxyRes.on('error', () => {
try { clientRes.end(); } catch (e) { /* ignore */ }
});
}
_filterBody(body, contentType) {
if (!body || !contentType || !contentType.includes('json')) return body;
try {
const data = JSON.parse(body.toString('utf-8'));
const NON_TEXT_TYPES = new Set(['image_url', 'input_image', 'file']);
const sanitize = (obj) => {
if (Array.isArray(obj)) return obj.map(sanitize);
if (obj && typeof obj === 'object') {
if (obj.content && Array.isArray(obj.content)) {
obj.content = obj.content.map(item => {
if (item && typeof item === 'object' && NON_TEXT_TYPES.has(item.type)) {
return { type: 'text', text: '[图片无法识别]' };
}
return sanitize(item);
});
}
for (const [k, v] of Object.entries(obj)) {
obj[k] = sanitize(v);
}
}
return obj;
};
return Buffer.from(JSON.stringify(sanitize(data)), 'utf-8');
} catch {
return body;
}
}
}
// ===================== Provider configuration =====================
const PROVIDERS = [
{
id: 'deepseek',
name: 'DeepSeek (深度求索)',
modelName: 'deepseek-v4-pro',
registerUrl: 'https://platform.deepseek.com/sign_in',
guide: '1. 打开 DeepSeek 官网并注册账号\n2. 登录后进入 API Keys 页面\n3. 点击"创建 API Key",复制生成的密钥(以 sk- 开头)',
proxy: {
port: 4445,
upstream: 'https://api.deepseek.com/v1',
filterImages: true
},
codex: {
configToml: (modelName) => `model = "${modelName}"
model_provider = "codex-proxy"
[model_providers.codex-proxy]
name = "codex-proxy"
base_url = "http://127.0.0.1:4445/v1"
api_key = "sk-codex-relay"
wire_api = "responses"`
}
},
{
id: 'qwen',
name: '通义千问 (阿里云)',
modelName: 'qwen-max',
registerUrl: 'https://bailian.console.aliyun.com/',
guide: '1. 打开阿里云百炼平台并登录(用支付宝/手机号注册)\n2. 开通"模型服务"后进入 API-KEY 管理\n3. 创建 API Key,复制保存',
proxy: {
port: 4448,
upstream: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
filterImages: false
},
codex: {
configToml: (modelName) => `model = "${modelName}"
model_provider = "codex-proxy"
[model_providers.codex-proxy]
name = "codex-proxy"
base_url = "http://127.0.0.1:4448/v1"
api_key = "sk-codex-relay"
wire_api = "responses"`
}
},
{
id: 'glm',
name: '智谱 GLM (智谱AI)',
modelName: 'glm-4-plus',
registerUrl: 'https://open.bigmodel.cn/usercenter/project-manage',
guide: '1. 打开智谱 AI 官网并注册(国内手机号即可)\n2. 登录后进入"项目管理"页面\n3. 创建项目或查看已有项目,复制 API Key',
proxy: {
port: 4447,
upstream: 'https://open.bigmodel.cn/api/paas/v4',
filterImages: false
},
codex: {
configToml: (modelName) => `model = "${modelName}"
model_provider = "codex-proxy"
[model_providers.codex-proxy]
name = "codex-proxy"
base_url = "http://127.0.0.1:4447/v1"
api_key = "sk-codex-relay"
wire_api = "responses"`
}
}
];
// ===================== Global state =====================
let currentProxy = null;
let configDir = path.join(os.homedir(), '.codex');
let setupConfigPath = path.join(configDir, 'setup-config.json');
// ===================== Window =====================
function createWindow() {
const win = new BrowserWindow({
width: 600,
height: 720,
resizable: false,
maximizable: false,
title: 'OpenAI Codex 一键配置',
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false
}
});
win.loadFile(path.join(__dirname, 'src', 'index.html'));
if (process.argv.includes('--dev')) {
win.webContents.openDevTools({ mode: 'bottom' });
}
}
app.whenReady().then(createWindow);
app.on('window-all-closed', () => app.quit());
// ===================== IPC: Get model list =====================
ipcMain.handle('get-model-providers', async () => {
return PROVIDERS.map(p => ({
id: p.id,
name: p.name,
modelName: p.modelName,
guide: p.guide,
registerUrl: p.registerUrl
}));
});
// ===================== IPC: Load saved config =====================
ipcMain.handle('load-config', async () => {
try {
if (fs.existsSync(setupConfigPath)) {
return JSON.parse(fs.readFileSync(setupConfigPath, 'utf-8'));
}
} catch (e) { /* ignore */ }
return { apiKey: '', providerId: '' };
});
// ===================== IPC: Save config =====================
ipcMain.handle('save-config', async (event, config) => {
try {
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
fs.writeFileSync(setupConfigPath, JSON.stringify(config, null, 2), 'utf-8');
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
// ===================== IPC: Clear config =====================
ipcMain.handle('clear-config', async () => {
try {
if (fs.existsSync(setupConfigPath)) fs.unlinkSync(setupConfigPath);
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
// ===================== IPC: Apply config (write config file) =====================
ipcMain.handle('apply-config', async (event, options) => {
const { providerId, apiKey } = options;
const provider = PROVIDERS.find(p => p.id === providerId);
if (!provider) throw new Error(`未知模型: ${providerId}`);
const paths = {
config: path.join(configDir, 'config.toml')
};
try {
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
// Write full config.toml
fs.writeFileSync(paths.config, provider.codex.configToml(provider.modelName), 'utf-8');
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
// ===================== IPC: Check proxy status =====================
ipcMain.handle('proxy-status', async () => {
return { running: currentProxy !== null && currentProxy.isRunning() };
});
// ===================== IPC: Start proxy (built-in Node.js) =====================
ipcMain.handle('start-proxy', async (event, options) => {
const { providerId, apiKey } = options;
const provider = PROVIDERS.find(p => p.id === providerId);
if (!provider) return { success: false, error: '未知模型' };
try {
// Stop existing proxy if running
if (currentProxy && currentProxy.isRunning()) {
currentProxy.stop();
currentProxy = null;
await sleep(300);
}
const proxy = new NodeProxy();
await proxy.start({
port: provider.proxy.port,
upstream: provider.proxy.upstream,
apiKey: apiKey,
filterImages: provider.proxy.filterImages
});
currentProxy = proxy;
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
// ===================== IPC: Stop proxy =====================
ipcMain.handle('stop-proxy', async () => {
if (currentProxy) {
currentProxy.stop();
currentProxy = null;
}
return { success: true };
});
// ===================== IPC: Copy text =====================
ipcMain.handle('copy-text', async (event, text) => {
clipboard.writeText(text);
return { success: true };
});
// ===================== IPC: Open external link =====================
ipcMain.handle('open-external', async (event, url) => {
await shell.openExternal(url);
});
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}