File size: 9,531 Bytes
55a0975
c4004bc
e97c1d1
783fb1f
dd2b18e
3727a06
1ec87c7
3727a06
 
950df70
e286b80
55a0975
e97c1d1
3727a06
 
e286b80
5a97b06
3727a06
 
 
 
 
 
 
 
5a97b06
 
 
1ec87c7
 
 
 
 
 
 
 
 
 
 
e286b80
1ec87c7
e97c1d1
1ec87c7
 
 
 
 
e97c1d1
1ec87c7
 
 
 
 
 
e97c1d1
1ec87c7
e286b80
c4004bc
1ec87c7
 
 
 
 
 
 
 
 
 
 
 
 
 
3727a06
1ec87c7
1922b30
 
1136faa
1ec87c7
e97c1d1
3727a06
 
5a97b06
3727a06
5a97b06
1ec87c7
1136faa
e97c1d1
 
 
 
783fb1f
 
1136faa
 
 
1922b30
1136faa
 
 
 
 
 
 
 
 
 
 
50bb115
3727a06
1136faa
 
 
50bb115
e97c1d1
1136faa
 
 
 
 
50bb115
 
1ec87c7
 
e286b80
1ec87c7
50bb115
1136faa
1ec87c7
 
 
 
 
 
 
 
 
 
 
50bb115
 
1ec87c7
e286b80
1136faa
 
 
 
e97c1d1
1ec87c7
 
 
 
3727a06
1ec87c7
55a0975
1ec87c7
1136faa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ec87c7
3727a06
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
import { JSDOM } from "jsdom";
import { createHash } from "node:crypto";
import { Buffer } from "node:buffer";
import UserAgent from "user-agents";

// Глобальное управление потоком
let activeRequests = 0;
const MAX_CONCURRENT = 50; // Сколько всего запросов может "висеть" одновременно
let lastRequestStartTime = 0;
const MIN_GAP_MS = 500; // ЖЕСТКИЙ ИНТЕРВАЛ: 2 запроса в секунду (МАКСИМАЛЬНАЯ БЕЗОПАСНОСТЬ)

export class DuckAI {
  
  // Функция "Диспетчер" - гарантирует, что запросы стартуют строго по очереди с паузой
  private async waitInQueue(reqId: string): Promise<void> {
      const now = Date.now();
      
      // Вычисляем, когда этому запросу разрешено стартовать
      const targetStartTime = Math.max(now, lastRequestStartTime + MIN_GAP_MS);
      lastRequestStartTime = targetStartTime;

      const waitTime = targetStartTime - now;
      if (waitTime > 0) {
          // console.log(`[${reqId}] [Queue] Waiting ${waitTime}ms to maintain pace...`);
          await new Promise(r => setTimeout(r, waitTime));
      }
  }

  private async solveChallenge(vqdHash: string, reqId: string): Promise<string> {
    try {
        const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');
        const dom = new JSDOM(
          `<iframe id="jsa" sandbox="allow-scripts allow-same-origin" srcdoc="<!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'">
    </head>
    <body></body>
    </html>" style="position: absolute; left: -9999px; top: -9999px;"></iframe>`,
          { runScripts: 'dangerously', resources: "usable", url: "https://duckduckgo.com/" }
        );

        const window = dom.window as any;
        window.screen = { width: 1920, height: 1080, availWidth: 1920, availHeight: 1080 };
        window.chrome = { runtime: {} };
        window.top.__DDG_BE_VERSION__ = 1;
        window.top.__DDG_FE_CHAT_HASH__ = 1;

        const jsa = window.document.querySelector('#jsa');
        const contentDoc = jsa.contentDocument || jsa.contentWindow.document;
        const meta = contentDoc.createElement('meta');
        meta.setAttribute('http-equiv', 'Content-Security-Policy');
        meta.setAttribute('content', "default-src 'none'; script-src 'unsafe-inline';");
        contentDoc.head.appendChild(meta);

        const result = await window.eval(jsScript) as any;
        if (!result) throw new Error("Challenge script returned nothing");

        result.client_hashes[0] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36';
        
        const solved = btoa(JSON.stringify({
            ...result,
            client_hashes: result.client_hashes.map((t: string) => {
                const hash = createHash('sha256');
                hash.update(t);
                return hash.digest('base64');
            })
        }));

        dom.window.close();
        return solved;
    } catch (e: any) {
        throw new Error(`Challenge Failed: ${e.message}`);
    }
  }

  async chat(request: any): Promise<{ message: string, vqd: string | null }> {
    const reqId = Math.random().toString(36).substring(7).toUpperCase();
    
    // 1. Становимся в очередь на старт
    await this.waitInQueue(reqId);
    
    activeRequests++;
    const startTime = Date.now();
    const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36';
    const headers: any = {
        "User-Agent": userAgent,
        "Accept": "text/event-stream",
        "x-vqd-accept": "1",
        "x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300" 
    };

    if (request.vqd) {
        headers["x-vqd-4"] = request.vqd;
    }

    try {
        console.log(`[${reqId}] [Chat] EXECUTING (Parallel: ${activeRequests}, HasVQD: ${!!request.vqd})`);

        let solvedVqd = "";
        // Если VQD нет, получаем хэш и решаем челлендж
        if (!request.vqd) {
            const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });
            const hashHeader = statusRes.headers.get("x-vqd-hash-1");
            if (!hashHeader) throw new Error(`Status ${statusRes.status}: No VQD Hash`);
            solvedVqd = await this.solveChallenge(hashHeader, reqId);
        }

        // Сам запрос
        const chatHeaders: any = { ...headers, "Content-Type": "application/json" };
        if (solvedVqd) chatHeaders["x-vqd-hash-1"] = solvedVqd;

        const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {
            method: "POST",
            headers: chatHeaders,
            body: JSON.stringify({
                model: request.model,
                messages: request.messages
            })
        });

        if (!response.ok) {
            const body = await response.text();
            throw new Error(`DDG Error ${response.status}: ${body.substring(0, 50)}`);
        }

        const newVqd = response.headers.get("x-vqd-4");
        const text = await response.text();
        let llmResponse = "";
        const lines = text.split("\n");
        for (const line of lines) {
          if (line.startsWith("data: ")) {
            try {
              const chunk = line.slice(6);
              if (chunk === "[DONE]") break;
              const json = JSON.parse(chunk);
              if (json.message) llmResponse += json.message;
            } catch (e) {}
          }
        }
        
        console.log(`[${reqId}] [Chat] SUCCESS (${Date.now() - startTime}ms)`);
        return { 
            message: llmResponse.trim() || "Empty response",
            vqd: newVqd
        };

    } catch (error: any) {
        console.error(`[${reqId}] [Chat] FAILED: ${error.message}`);
        throw error;
    } finally {
        activeRequests--;
    }
  }

  async chatStream(request: any): Promise<{ stream: ReadableStream<string>, vqd: string | null }> {
    const reqId = Math.random().toString(36).substring(7).toUpperCase();
    await this.waitInQueue(reqId);
    
    activeRequests++;
    const userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36';
    const headers: any = {
        "User-Agent": userAgent,
        "Accept": "text/event-stream",
        "x-vqd-accept": "1",
        "x-fe-version": "serp_20250401_100419_ET-19d438eb199b2bf7c300" 
    };

    if (request.vqd) {
        headers["x-vqd-4"] = request.vqd;
    }

    try {
        let solvedVqd = "";
        if (!request.vqd) {
            const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });
            const hashHeader = statusRes.headers.get("x-vqd-hash-1");
            if (!hashHeader) throw new Error(`Status ${statusRes.status}: No VQD Hash`);
            solvedVqd = await this.solveChallenge(hashHeader, reqId);
        }

        const chatHeaders: any = { ...headers, "Content-Type": "application/json" };
        if (solvedVqd) chatHeaders["x-vqd-hash-1"] = solvedVqd;

        const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {
            method: "POST",
            headers: chatHeaders,
            body: JSON.stringify({
                model: request.model,
                messages: request.messages
            })
        });

        if (!response.ok) {
            const body = await response.text();
            throw new Error(`DDG Error ${response.status}: ${body.substring(0, 50)}`);
        }

        const newVqd = response.headers.get("x-vqd-4");
        
        const stream = new ReadableStream({
            async start(controller) {
                const reader = response.body?.getReader();
                if (!reader) {
                    controller.close();
                    return;
                }

                const decoder = new TextDecoder();
                try {
                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;

                        const chunk = decoder.decode(value, { stream: true });
                        const lines = chunk.split("\n");
                        for (const line of lines) {
                            if (line.startsWith("data: ")) {
                                try {
                                    const data = line.slice(6);
                                    if (data === "[DONE]") continue;
                                    const json = JSON.parse(data);
                                    if (json.message) controller.enqueue(json.message);
                                } catch (e) {}
                            }
                        }
                    }
                } catch (e) {
                    controller.error(e);
                } finally {
                    controller.close();
                    activeRequests--;
                }
            }
        });

        return { stream, vqd: newVqd };

    } catch (error: any) {
        activeRequests--;
        throw error;
    }
  }

  getAvailableModels() { return ["gpt-4o-mini", "gpt-5-mini", "openai/gpt-oss-120b"]; }
}