GeminiBot commited on
Commit ·
e286b80
1
Parent(s): 5a97b06
Implement pacing (400ms start interval) to prevent DDG burst bans
Browse files3 unmodified lines456789101112131415161718192021222324252627282930315 unmodified lines373839404142434445464748492 unmodified lines52535455565758596061629 unmodified lines7273747576777879808182836 unmodified lines909192939495969798991001011021031041051 unmodified line1071081091101111121131141151161171181191201213 unmodified lines12512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616710 unmodified lines1781791801811821831845 unmodified lines1901911921933 unmodified linesimport UserAgent from "user-agents";let activeRequests = 0;const MAX_CONCURRENT_CHATS = 5; // Максимум 5 одновременных запросов к DDGconst requestQueue: (() => void)[] = [];export class DuckAI {// Метод для ожидания своей очередиprivate async acquireSlot(reqId: string): Promise<void> {if (activeRequests < MAX_CONCURRENT_CHATS) {activeRequests++;return;}console.log(`[${reqId}] [Queue] Space busy (${activeRequests} active). Waiting for slot...`);return new Promise((resolve) => {requestQueue.push(() => {activeRequests++;resolve();});});}// Освобождение слотаprivate releaseSlot() {activeRequests--;if (requestQueue.length > 0) {5 unmodified linesprivate async solveChallenge(vqdHash: string, reqId: string): Promise<string> {const start = Date.now();const memBefore = process.memoryUsage().heapUsed / 1024 / 1024;console.log(`[${reqId}] [Challenge] START. Mem: ${memBefore.toFixed(2)}MB`);try {const jsScript = Buffer.from(vqdHash, 'base64').toString('utf-8');console.log(`[${reqId}] [Challenge] Creating JSDOM...`);const dom = new JSDOM(`<iframe id="jsa" sandbox="allow-scripts allow-same-origin" srcdoc="<!DOCTYPE html><html>2 unmodified lines</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;9 unmodified linesmeta.setAttribute('content', "default-src 'none'; script-src 'unsafe-inline';");contentDoc.head.appendChild(meta);console.log(`[${reqId}] [Challenge] Running Eval...`);const evalStart = Date.now();const result = await window.eval(jsScript) as any;console.log(`[${reqId}] [Challenge] Eval finished in ${Date.now() - evalStart}ms`);if (!result) throw new Error("Challenge script returned nothing (possible JSDOM crash)");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';6 unmodified lines})}));const duration = Date.now() - start;const memAfter = process.memoryUsage().heapUsed / 1024 / 1024;console.log(`[${reqId}] [Challenge] SUCCESS. Time: ${duration}ms. Mem Delta: +( ${(memAfter - memBefore).toFixed(2)} )MB`);// Очистка JSDOM для экономии памятиdom.window.close();return solved;} catch (e: any) {console.error(`[${reqId}] [Challenge] CRITICAL ERROR: ${e.message}\n${e.stack}`);throw e;}}1 unmodified lineasync chat(request: any): Promise<string> {const reqId = Math.random().toString(36).substring(7).toUpperCase();// Ждем свободный слот (максимум 5 параллельно)await this.acquireSlot(reqId);const startTime = Date.now();console.log(`[${reqId}] [Chat] STARTING (Active: ${activeRequests}, Queued: ${requestQueue.length})`);// Добавляем Jitter (случайную задержку 0-500мс), чтобы не долбить DDG пачкойawait new Promise(r => setTimeout(resolve => r(resolve), Math.random() * 500));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 = {"User-Agent": userAgent,3 unmodified lines};try {let hashHeader = null;let statusAttempt = 0;// Ретрай для получения статуса (VQD)while (!hashHeader && statusAttempt < 3) {console.log(`[${reqId}] [Chat] Fetching status (Attempt ${statusAttempt + 1})...`);const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });hashHeader = statusRes.headers.get("x-vqd-hash-1");if (!hashHeader) {if (statusRes.status === 429) {console.log(`[${reqId}] [Chat] Status 429 detected. Waiting...`);await new Promise(r => setTimeout(resolve => r(resolve), 1000 * (statusAttempt + 1)));} else {throw new Error(`Status ${statusRes.status}: Missing VQD hash`);}}statusAttempt++;}if (!hashHeader) throw new Error("Failed to obtain VQD hash after retries");const solvedVqd = await this.solveChallenge(hashHeader, reqId);console.log(`[${reqId}] [Chat] Sending request to DDG...`);const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: { ...headers, "Content-Type": "application/json", "x-vqd-hash-1": solvedVqd },body: JSON.stringify(request)});console.log(`[${reqId}] [Chat] DDG response status: ${response.status}`);if (!response.ok) {const body = await response.text();console.error(`[${reqId}] [Chat] DDG ERROR BODY: ${body}`);throw new Error(`DDG Error ${response.status}: ${body.substring(0, 100)}`);}const text = await response.text();10 unmodified lines}}console.log(`[${reqId}] [Chat] SUCCESS. Total time: ${Date.now() - startTime}ms`);return llmResponse.trim() || "Empty response";} catch (error: any) {5 unmodified lines}getAvailableModels() { return ["gpt-4o-mini", "gpt-5-mini", "openai/gpt-oss-120b"]; }}3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839405 unmodified lines464748495051525354552 unmodified lines585960616263649 unmodified lines74757677787980816 unmodified lines888990919293949596971 unmodified line991001011021031041051061071083 unmodified lines11211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814910 unmodified lines1601611621631641651665 unmodified lines1721731741753 unmodified linesimport UserAgent from "user-agents";let activeRequests = 0;const MAX_CONCURRENT_CHATS = 20; // Увеличиваем до 20 одновременныхconst requestQueue: (() => void)[] = [];// Переменные для контроля темпа (Rate Limit)let lastStartTime = 0;const MIN_START_INTERVAL = 400; // Начинать новый запрос не чаще чем раз в 400мс (~2.5 зап/сек)export class DuckAI {// Ожидание слота + соблюдение темпаprivate async acquireSlot(reqId: string): Promise<void> {// 1. Ждем свободный слот из 20if (activeRequests >= MAX_CONCURRENT_CHATS) {console.log(`[${reqId}] [Queue] All slots full (${activeRequests}). Waiting...`);await new Promise((resolve) => requestQueue.push(() => resolve()));}activeRequests++;// 2. Соблюдаем темп старта (чтобы не пугать DDG всплесками)const now = Date.now();const timeSinceLastStart = now - lastStartTime;const wait = Math.max(0, MIN_START_INTERVAL - timeSinceLastStart);lastStartTime = now + wait; // Бронируем время стартаif (wait > 0) {// console.log(`[${reqId}] [Queue] Pacing: waiting ${wait}ms...`);await new Promise(r => setTimeout(r, wait));}}private releaseSlot() {activeRequests--;if (requestQueue.length > 0) {5 unmodified linesprivate async solveChallenge(vqdHash: string, reqId: string): Promise<string> {const start = Date.now();const memBefore = process.memoryUsage().heapUsed / 1024 / 1024;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>2 unmodified lines</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;9 unmodified linesmeta.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';6 unmodified lines})}));dom.window.close();return solved;} catch (e: any) {console.error(`[${reqId}] [Challenge] ERROR: ${e.message}`);throw e;}}1 unmodified lineasync chat(request: any): Promise<string> {const reqId = Math.random().toString(36).substring(7).toUpperCase();// Плавный вход в системуawait this.acquireSlot(reqId);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 = {"User-Agent": userAgent,3 unmodified lines};try {console.log(`[${reqId}] [Chat] START (Active: ${activeRequests}, Queued: ${requestQueue.length})`);let hashHeader = null;let statusAttempt = 0;while (!hashHeader && statusAttempt < 2) {const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });hashHeader = statusRes.headers.get("x-vqd-hash-1");if (!hashHeader) {if (statusRes.status === 429) {await new Promise(r => setTimeout(r, 1000));} else {throw new Error(`Status ${statusRes.status}: No VQD`);}}statusAttempt++;}if (!hashHeader) throw new Error("Failed VQD after retries");const solvedVqd = await this.solveChallenge(hashHeader, reqId);const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: { ...headers, "Content-Type": "application/json", "x-vqd-hash-1": solvedVqd },body: JSON.stringify(request)});if (!response.ok) {const body = await response.text();throw new Error(`DDG Error ${response.status}: ${body.substring(0, 50)}`);}const text = await response.text();10 unmodified lines}}console.log(`[${reqId}] [Chat] SUCCESS (${Date.now() - startTime}ms)`);return llmResponse.trim() || "Empty response";} catch (error: any) {5 unmodified lines}getAvailableModels() { return ["gpt-4o-mini", "gpt-5-mini", "openai/gpt-oss-120b"]; }}
src/duckai.ts+35-53