GeminiBot commited on
Commit ·
50bb115
1
Parent(s): d819405
Add retry logic for 418 errors and fix undefined document in eval
Browse files149 unmodified lines15015115215315415515615715815926 unmodified lines1861871881891901911921 unmodified line194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246149 unmodified linesreturn "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";};mockWindow.top.__DDG_BE_VERSION__ = 1;mockWindow.top.__DDG_FE_CHAT_HASH__ = 1;const result = await mockWindow.eval(jsScript) as any;if (!result || !result.client_hashes) {throw new Error("Invalid Challenge Response");26 unmodified linesreturn { status: "unknown" };}async chat(request: any): Promise<string> {const ua = new UserAgent({ deviceCategory: 'desktop' }).toString();const headers: any = {"User-Agent": ua,1 unmodified line"x-vqd-accept": "1"};console.log("[DuckAI] Fetching status...");const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });console.log(`[DuckAI] Status response: ${statusRes.status}`);const hashHeader = statusRes.headers.get("x-vqd-hash-1");console.log(`[DuckAI] x-vqd-hash-1: ${hashHeader ? "FOUND" : "MISSING"}`);if (!hashHeader) throw new Error("Missing x-vqd-hash-1 - DuckDuckGo might be blocking this IP or Challenge failed.");console.log("[DuckAI] Solving challenge...");const solvedVqd = await this.solveChallenge(hashHeader, ua);console.log("[DuckAI] Challenge solved (or fallback used).");const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: { ...headers, "x-vqd-hash-1": solvedVqd, "Content-Type": "application/json" },body: JSON.stringify(request)});console.log(`[DuckAI] Chat response status: ${response.status}`);if (!response.ok) {const errorText = await response.text();console.log(`[DuckAI] Error body: ${errorText}`);throw new Error(`DuckDuckGo API Error (${response.status}): ${errorText.substring(0, 100)}`);}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) {}}}if (!llmResponse) {console.log("[DuckAI] Warning: Empty LLM response extracted.");throw new Error("Empty response from DuckDuckGo");}return llmResponse.trim();}}149 unmodified lines15015115215315415515615715815916016116216316416526 unmodified lines1921931941951961971981 unmodified line200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268149 unmodified linesreturn "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";};// Ensure document is globally available for eval(mockWindow as any).document = mockWindow.document;const result = await mockWindow.eval(`(function() {const window = this;const document = this.document;${jsScript}}).call(window)`) as any;if (!result || !result.client_hashes) {throw new Error("Invalid Challenge Response");26 unmodified linesreturn { status: "unknown" };}async chat(request: any, retries = 1): Promise<string> {const ua = new UserAgent({ deviceCategory: 'desktop' }).toString();const headers: any = {"User-Agent": ua,1 unmodified line"x-vqd-accept": "1"};try {console.log("[DuckAI] Fetching status...");const statusRes = await fetch("https://duckduckgo.com/duckchat/v1/status?q=1", { headers });console.log(`[DuckAI] Status response: ${statusRes.status}`);const hashHeader = statusRes.headers.get("x-vqd-hash-1");console.log(`[DuckAI] x-vqd-hash-1: ${hashHeader ? "FOUND" : "MISSING"}`);if (!hashHeader) throw new Error("Missing x-vqd-hash-1 - DuckDuckGo might be blocking this IP or Challenge failed.");console.log("[DuckAI] Solving challenge...");const solvedVqd = await this.solveChallenge(hashHeader, ua);console.log("[DuckAI] Challenge solved (or fallback used).");const response = await fetch("https://duckduckgo.com/duckchat/v1/chat", {method: "POST",headers: { ...headers, "x-vqd-hash-1": solvedVqd, "Content-Type": "application/json" },body: JSON.stringify(request)});console.log(`[DuckAI] Chat response status: ${response.status}`);if (!response.ok) {const errorText = await response.text();// Если ошибка 418 (Challenge Failed) и есть попытки - пробуем сноваif (response.status === 418 && retries > 0) {console.log(`[DuckAI] Got 418 Error. Retrying... (${retries} attempts left)`);return this.chat(request, retries - 1);}console.log(`[DuckAI] Error body: ${errorText}`);throw new Error(`DuckDuckGo API Error (${response.status}): ${errorText.substring(0, 100)}`);}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) {}}}if (!llmResponse) {console.log("[DuckAI] Warning: Empty LLM response extracted.");throw new Error("Empty response from DuckDuckGo");}return llmResponse.trim();} catch (error: any) {// Если была ошибка сети или другая, и есть попытки - тоже ретраимif (retries > 0) {console.log(`[DuckAI] Error: ${error.message}. Retrying... (${retries} attempts left)`);return this.chat(request, retries - 1);}throw error;}}}
src/duckai.ts+72-50