xt8 commited on
Commit
8ea739d
·
verified ·
1 Parent(s): eaa6ff0

Create main.ts

Browse files
Files changed (1) hide show
  1. main.ts +298 -0
main.ts ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const COOKIES = `__gads=ID=fa119d4bd4f0deb4:T=1767802127:RT=1769915891:S=ALNI_MadOwOvOyuYGa63fhmTXAOSMuMPzA; __gpi=UID=000011dec0f55e42:T=1767802127:RT=1769915891:S=ALNI_MbmxAr7exkcHsXJpxvp5Jda40UEhQ; __eoi=ID=1b168e49673ee98a:T=1767802127:RT=1769915891:S=AA-Afjb1OtBK1G-c16acoNoP6uKS; NEXT_LOCALE=zh; u_device_id=d403ec97-7698-4c1a-a5ad-4121004056df; home_chat_id=f2b45c03-aeee-4c9e-862f-50aa2e7ba549; __Secure-authjs.callback-url=https%3A%2F%2Fapp.unlimitedai.chat; __Host-authjs.csrf-token=85724d6088bf62366e70be6dca13329f84a248a2e682b9469ea9c4edea86294b%7Cb6d8881d70b2a9fcb7b3bdc9c67cec59c17caba2225b24909cddbc1d6092d9c3; _clck=1ehq05y%5E2%5Eg5e%5E0%5E2302; _clsk=1j5vo0j%5E1776785008641%5E1%5E1%5Ez.clarity.ms%2Fcollect`;
2
+
3
+ // 目标 API 地址
4
+ const TARGET_API = "https://app.unlimitedai.chat/api/chat";
5
+
6
+ // 模拟的设备 ID (保持会话连续性)
7
+ const DEVICE_ID = "d403ec97-7698-4c1a-a5ad-4121004056de";
8
+
9
+ // --- 核心逻辑 ---
10
+
11
+ async function handler(req: Request): Promise<Response> {
12
+ const url = new URL(req.url);
13
+
14
+ // CORS 处理
15
+ if (req.method === 'OPTIONS') {
16
+ return new Response(null, {
17
+ status: 204,
18
+ headers: corsHeaders()
19
+ });
20
+ }
21
+
22
+ // 静态页面
23
+ if (url.pathname === '/') {
24
+ return new Response(getUI(), {
25
+ headers: { 'Content-Type': 'text/html; charset=utf-8' }
26
+ });
27
+ }
28
+
29
+ // 模型列表
30
+ if (url.pathname === '/v1/models' && req.method === 'GET') {
31
+ return new Response(JSON.stringify({
32
+ object: "list",
33
+ data: [
34
+ { id: "chat-model-reasoning", object: "model", created: Date.now(), owned_by: "unlimitedai" }
35
+ ]
36
+ }), {
37
+ headers: { 'Content-Type': 'application/json', ...corsHeaders() }
38
+ });
39
+ }
40
+
41
+ // 聊天补全
42
+ if (url.pathname === '/v1/chat/completions' && req.method === 'POST') {
43
+ return handleChatCompletion(req);
44
+ }
45
+
46
+ return new Response("Not Found", { status: 404 });
47
+ }
48
+
49
+ async function handleChatCompletion(req: Request): Promise<Response> {
50
+ try {
51
+ const body = await req.json();
52
+ const model = body.model || "chat-model-reasoning";
53
+ const openAiMessages = body.messages || [];
54
+
55
+ // 1. 构建 UnlimitedAI 格式的请求体
56
+ // 需要为每条消息生成 ID 和时间戳
57
+ const now = new Date().toISOString();
58
+ const uaiMessages = openAiMessages.map((msg: any, index: number) => ({
59
+ id: crypto.randomUUID(),
60
+ role: msg.role,
61
+ content: msg.content,
62
+ parts: [{ type: "text", text: msg.content }], // UnlimitedAI 特有的 parts 结构
63
+ createdAt: now
64
+ }));
65
+
66
+ // 生成一个新的会话 ID (实际生产中可能需要根据历史消息复用 ID)
67
+ // 这里为了简单演示,每次请求生成一个新的 Chat ID
68
+ const chatId = crypto.randomUUID();
69
+
70
+ const payload = {
71
+ chatId: chatId,
72
+ messages: uaiMessages,
73
+ selectedChatModel: model,
74
+ selectedCharacter: null,
75
+ selectedStory: null,
76
+ deviceId: DEVICE_ID,
77
+ locale: "zh"
78
+ };
79
+
80
+ // 2. 构建请求头 (完全模拟抓包数据)
81
+ const headers: Record<string, string> = {
82
+ "accept": "*/*",
83
+ "content-type": "application/json",
84
+ "cookie": COOKIES,
85
+ "origin": "https://app.unlimitedai.chat",
86
+ "referer": "https://app.unlimitedai.chat/zh",
87
+ "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36 Edg/147.0.0.0",
88
+ "x-next-intl-locale": "zh",
89
+ "sec-ch-ua": '"Microsoft Edge";v="147", "Not.A/Brand";v="8", "Chromium";v="147"',
90
+ "sec-ch-ua-mobile": "?0",
91
+ "sec-ch-ua-platform": '"Windows"',
92
+ "sec-fetch-dest": "empty",
93
+ "sec-fetch-mode": "cors",
94
+ "sec-fetch-site": "same-origin"
95
+ };
96
+
97
+ // 3. 发起上游请求
98
+ const upstreamRes = await fetch(TARGET_API, {
99
+ method: "POST",
100
+ headers,
101
+ body: JSON.stringify(payload)
102
+ });
103
+
104
+ if (!upstreamRes.ok) {
105
+ const errText = await upstreamRes.text();
106
+ return new Response(JSON.stringify({ error: { message: `Upstream Error ${upstreamRes.status}: ${errText}` } }), {
107
+ status: upstreamRes.status,
108
+ headers: { 'Content-Type': 'application/json' }
109
+ });
110
+ }
111
+
112
+ // 4. 流式转换处理 (NDJSON -> SSE)
113
+ const { readable, writable } = new TransformStream();
114
+ const writer = writable.getWriter();
115
+ const encoder = new TextEncoder();
116
+
117
+ // 用于跟踪会话 ID
118
+ const openAiChatId = crypto.randomUUID();
119
+
120
+ (async () => {
121
+ try {
122
+ const reader = upstreamRes.body?.getReader();
123
+ if (!reader) throw new Error("No body");
124
+ const decoder = new TextDecoder();
125
+ let buffer = "";
126
+
127
+ while (true) {
128
+ const { done, value } = await reader.read();
129
+ if (done) break;
130
+
131
+ buffer += decoder.decode(value, { stream: true });
132
+ const lines = buffer.split('\n');
133
+ buffer = lines.pop() || ""; // 保留最后一个可能不完整的块
134
+
135
+ for (const line of lines) {
136
+ if (!line.trim()) continue;
137
+ try {
138
+ const json = JSON.parse(line);
139
+
140
+ // UnlimitedAI 返回格式: {"type":"delta","delta":"你好!"}
141
+ if (json.type === 'delta' && json.delta) {
142
+ const content = json.delta;
143
+
144
+ // 转换为 OpenAI SSE 格式
145
+ const sseChunk = {
146
+ id: openAiChatId,
147
+ object: "chat.completion.chunk",
148
+ created: Math.floor(Date.now() / 1000),
149
+ model: model,
150
+ choices: [{
151
+ index: 0,
152
+ delta: { content: content },
153
+ finish_reason: null
154
+ }]
155
+ };
156
+
157
+ writer.write(encoder.encode(`data: ${JSON.stringify(sseChunk)}\n\n`));
158
+ }
159
+ } catch (e) {
160
+ console.error("Parse error", e);
161
+ }
162
+ }
163
+ }
164
+
165
+ // 发送结束标记
166
+ writer.write(encoder.encode(`data: ${JSON.stringify({
167
+ id: openAiChatId,
168
+ object: "chat.completion.chunk",
169
+ created: Math.floor(Date.now() / 1000),
170
+ model: model,
171
+ choices: [{
172
+ index: 0,
173
+ delta: {},
174
+ finish_reason: "stop"
175
+ }]
176
+ })}\n\n`));
177
+
178
+ writer.write(encoder.encode('data: [DONE]\n\n'));
179
+
180
+ } catch (err: any) {
181
+ console.error("Stream processing error:", err);
182
+ writer.write(encoder.encode(`data: ${JSON.stringify({ error: { message: err.message } })}\n\n`));
183
+ } finally {
184
+ writer.close();
185
+ }
186
+ })();
187
+
188
+ return new Response(readable, {
189
+ headers: {
190
+ "Content-Type": "text/event-stream; charset=utf-8",
191
+ "Cache-Control": "no-cache",
192
+ "Connection": "keep-alive",
193
+ ...corsHeaders()
194
+ }
195
+ });
196
+
197
+ } catch (error: any) {
198
+ return new Response(JSON.stringify({ error: { message: error.message } }), {
199
+ status: 500,
200
+ headers: { 'Content-Type': 'application/json' }
201
+ });
202
+ }
203
+ }
204
+
205
+ // --- 辅助函数 ---
206
+
207
+ function corsHeaders() {
208
+ return {
209
+ 'Access-Control-Allow-Origin': '*',
210
+ 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
211
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
212
+ 'Access-Control-Max-Age': '86400',
213
+ };
214
+ }
215
+
216
+ // --- 简单的测试 UI ---
217
+
218
+ function getUI() {
219
+ return `<!DOCTYPE html>
220
+ <html lang="zh-CN">
221
+ <head>
222
+ <meta charset="UTF-8">
223
+ <title>UnlimitedAI Proxy Test</title>
224
+ <style>
225
+ body { font-family: sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; background: #f5f5f5; }
226
+ .container { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
227
+ textarea { width: 100%; height: 100px; margin-bottom: 10px; padding: 10px; border-radius: 5px; border: 1px solid #ccc; }
228
+ button { padding: 10px 20px; background: #007AFF; color: white; border: none; border-radius: 5px; cursor: pointer; }
229
+ button:disabled { background: #ccc; }
230
+ #output { margin-top: 20px; background: #333; color: #fff; padding: 15px; border-radius: 5px; min-height: 100px; white-space: pre-wrap; font-family: monospace; }
231
+ </style>
232
+ </head>
233
+ <body>
234
+ <div class="container">
235
+ <h2>UnlimitedAI Proxy (OpenAI 兼容)</h2>
236
+ <p>API Endpoint: <code>http://localhost:8000/v1/chat/completions</code></p>
237
+ <textarea id="prompt" placeholder="输入问题...">介绍一下人工智能</textarea>
238
+ <button id="sendBtn" onclick="send()">发送</button>
239
+ <div id="output">等待响应...</div>
240
+ </div>
241
+
242
+ <script>
243
+ async function send() {
244
+ const btn = document.getElementById('sendBtn');
245
+ const out = document.getElementById('output');
246
+ const prompt = document.getElementById('prompt').value;
247
+
248
+ btn.disabled = true;
249
+ out.textContent = '';
250
+
251
+ try {
252
+ const res = await fetch('/v1/chat/completions', {
253
+ method: 'POST',
254
+ headers: { 'Content-Type': 'application/json' },
255
+ body: JSON.stringify({
256
+ model: 'chat-model-reasoning',
257
+ messages: [{ role: 'user', content: prompt }],
258
+ stream: true
259
+ })
260
+ });
261
+
262
+ const reader = res.body.getReader();
263
+ const decoder = new TextDecoder();
264
+
265
+ while (true) {
266
+ const { done, value } = await reader.read();
267
+ if (done) break;
268
+ const chunk = decoder.decode(value);
269
+ const lines = chunk.split('\\n');
270
+
271
+ for (const line of lines) {
272
+ if (line.startsWith('data: ')) {
273
+ const dataStr = line.substring(6);
274
+ if (dataStr === '[DONE]') continue;
275
+ try {
276
+ const data = JSON.parse(dataStr);
277
+ const content = data.choices?.[0]?.delta?.content || '';
278
+ out.textContent += content;
279
+ } catch (e) {}
280
+ }
281
+ }
282
+ }
283
+ } catch (err) {
284
+ out.textContent = 'Error: ' + err.message;
285
+ } finally {
286
+ btn.disabled = false;
287
+ }
288
+ }
289
+ </script>
290
+ </body>
291
+ </html>`;
292
+ }
293
+
294
+ // --- 启动服务 ---
295
+
296
+ const PORT = 7860;
297
+ console.log(`UnlimitedAI Proxy running on http://localhost:${PORT}`);
298
+ await Deno.serve({ port: PORT }, handler);