/** * Copyright 2026 aphrody-code * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * bxc google — Google Ecosystem client, keyless APIs, & Gemini Web */ import { GoogleClient } from "../google/client.ts"; import { EXIT, type CommonOptions, logger } from "./shared.ts"; import { KeylessGoogleClient } from "../google/keyless.ts"; import { GeminiWebClient } from "../google/gemini-web.ts"; import { GeminiScraper } from "../google/gemini-scraper.ts"; import { join } from "node:path"; import readline from "node:readline"; function printUsage(): void { Bun.stdout.write( `bxc google — Google Ecosystem client & auditor (mandate compliant) Usage: bxc google search Perform a search on Google Web bxc google open Visit a Google domain with mandate guard & audit bxc google audit Perform a massive concurrent audit on Google pages # Keyless & Anonymous Google APIs bxc google dns [type] Query Google Public DNS-over-HTTPS (default type: A) bxc google books Search the public Google Books catalog bxc google translate Translate text (supports STDIN, --detail, --tts, --format) bxc google translate --detect Detect language of text bxc google translate --languages List 195 supported Google Cloud Translation languages bxc google translate --serve Start drop-in Google Cloud Translation API v2 REST server bxc google tts Synthesize Text-to-Speech audio MP3 via Google Translate TTS bxc google suggest Get autocomplete search query suggestions bxc google calendar Fetch and parse events from public Google iCal feed bxc google sheet [gid] Export a public Google Sheet to CSV bxc google doc Export a public Google Doc to plain text bxc google download Download a public Google Drive file by ID # Gemini Web (Cookie-based chat UI) bxc google chat [prompt] Interact with Gemini Web client (interactive REPL if no prompt) bxc google conversations List recent conversation history bxc google resume [prompt] Resume a conversation by conversation ID bxc google delete Delete a conversation by ID bxc google scrape Scrape & analyze static code/RPCs of Gemini Web App bxc google auto-upgrade Run the autonomous scraping and upgrade loop for Gemini Web Client Options: --profile stealth (default) | static | max --type DNS query type (A, AAAA, MX, TXT, etc.) --max-results Max results for books search (default: 10) --start Start index for books search (default: 0) --target Translate target language code (default: en) --source Translate source language code (default: auto) --detail, -d Display rich phonetic pronunciation, dictionary, definitions & typos --tts [file.mp3] Generate Text-to-Speech audio MP3 --speed TTS audio playback speed (default: 1) --client Autocomplete client ID (default: chrome) --cid Conversation ID for chat --rid Response ID for chat --rcid Candidate response ID for chat --thread Return JSON metadata with reply and conversation IDs --repl Force entering REPL in chat / resume --model Select Gemini model (flash, flash-lite, pro) (default: flash) --out Save scrape report to Markdown file --json-out Save scrape data to JSON file --help, -h this help `, ); } function parseArgs(argv: readonly string[]) { const positional: string[] = []; const flags: Record = {}; for (let i = 0; i < argv.length; i++) { const arg = argv[i]; if (arg.startsWith("--")) { const eqIdx = arg.indexOf("="); if (eqIdx !== -1) { const key = arg.slice(2, eqIdx); const val = arg.slice(eqIdx + 1); flags[key] = val === "true" ? true : val === "false" ? false : val; } else { const key = arg.slice(2); if (i + 1 < argv.length && !argv[i + 1].startsWith("-")) { const nextVal = argv[i + 1]; flags[key] = nextVal === "true" ? true : nextVal === "false" ? false : nextVal; i++; } else { flags[key] = true; } } } else if (arg !== "-" && arg.startsWith("-")) { const key = arg.slice(1); if (key === "h") { flags["help"] = true; } else if (key === "d") { flags["detail"] = true; } else { flags[key] = true; } } else { positional.push(arg); } } return { positional, flags }; } export async function main( argv: readonly string[], baseOpts: CommonOptions, ): Promise { const { positional, flags } = parseArgs(argv); const action = positional[0]; if (!action || flags["help"] || flags["h"]) { printUsage(); process.exit(action ? 0 : EXIT.MISUSE); } try { switch (action) { case "search": { const query = positional.slice(1).join(" "); if (!query) { logger.error("search — missing query argument"); process.exit(EXIT.MISUSE); } const client = new GoogleClient({ profile: (flags["profile"] as any) || "stealth", proxy: baseOpts.proxy, }); const results = await client.search(query); Bun.stdout.write(JSON.stringify(results, null, 2) + "\n"); break; } case "open": { const targetUrl = positional[1]; if (!targetUrl) { logger.error("open — missing URL argument"); process.exit(EXIT.MISUSE); } const client = new GoogleClient({ profile: (flags["profile"] as any) || "stealth", proxy: baseOpts.proxy, }); const { page, audit } = await client.open(targetUrl); try { const title = await page.title(); const content = await page.content(); Bun.stdout.write( JSON.stringify( { url: targetUrl, title, htmlLength: content.length, audit, }, null, 2, ) + "\n", ); } finally { await page.close().catch(() => {}); } break; } case "audit": { const seeds = positional.slice(1); if (seeds.length === 0) { logger.error("audit — missing seed URL arguments"); process.exit(EXIT.MISUSE); } const client = new GoogleClient({ profile: (flags["profile"] as any) || "stealth", proxy: baseOpts.proxy, }); const results = await client.auditMassive(seeds); Bun.stdout.write(JSON.stringify(results, null, 2) + "\n"); break; } case "dns": { const name = positional[1]; if (!name) { logger.error("dns [type] — missing name argument"); process.exit(EXIT.MISUSE); } const type = (flags["type"] as string) || positional[2] || "A"; const client = new KeylessGoogleClient(); const res = await client.resolveDns(name, type); Bun.stdout.write(JSON.stringify(res, null, 2) + "\n"); break; } case "books": { const query = positional.slice(1).join(" "); if (!query) { logger.error("books — missing query argument"); process.exit(EXIT.MISUSE); } const maxResults = Number(flags["max-results"]) || 10; const start = Number(flags["start"]) || 0; const client = new KeylessGoogleClient(); const res = await client.searchBooks(query, maxResults, start); Bun.stdout.write(JSON.stringify(res, null, 2) + "\n"); break; } case "book": { const volumeId = positional[1]; if (!volumeId) { logger.error("book — missing volume_id argument"); process.exit(EXIT.MISUSE); } const client = new KeylessGoogleClient(); const res = await client.getBook(volumeId); Bun.stdout.write(JSON.stringify(res, null, 2) + "\n"); break; } case "translate": { const { defaultTranslateEngine, detectLanguages, languageRegistry, createTranslateServer, defaultTTS } = await import("../google/translate/index.ts"); if (flags["serve"]) { const port = Number(flags["port"]) || 8089; const hostname = (flags["host"] as string) || "127.0.0.1"; createTranslateServer({ port, hostname }); logger.log(`Google Cloud Translation API v2 drop-in emulator running on http://${hostname}:${port}`); logger.log("Endpoints:"); logger.log(` POST/GET http://${hostname}:${port}/language/translate/v2`); logger.log(` POST/GET http://${hostname}:${port}/language/translate/v2/detect`); logger.log(` GET http://${hostname}:${port}/language/translate/v2/languages`); logger.log(` GET/POST http://${hostname}:${port}/language/translate/v2/tts`); await new Promise(() => {}); break; } if (flags["languages"]) { const target = (flags["target"] as string) || undefined; const res = languageRegistry.getSupportedLanguages(target); Bun.stdout.write(`${JSON.stringify(res, null, 2)}\n`); break; } if (flags["detect"]) { const queryText = positional.slice(1).join(" ") || (typeof flags["detect"] === "string" ? flags["detect"] : ""); if (!queryText) { logger.error("translate --detect — missing text argument"); process.exit(EXIT.MISUSE); } const res = await detectLanguages(queryText); Bun.stdout.write(`${JSON.stringify(res, null, 2)}\n`); break; } let text = positional.slice(1).join(" "); if (text === "-" || (!text && flags["stdin"])) { text = (await Bun.stdin.text()).trim(); } if (!text) { logger.error("translate — missing text argument (use --languages, --detect, --serve, or '-' for stdin)"); process.exit(EXIT.MISUSE); } const target = (flags["target"] as string) || "en"; const source = (flags["source"] as string) || undefined; const format = (flags["format"] as "text" | "html") || "text"; const isDetailed = Boolean(flags["detail"] || flags["d"]); if (isDetailed) { const res = await defaultTranslateEngine.translateDetailed({ q: text, target, source, format, }); if (flags["json"] || flags["raw"]) { Bun.stdout.write(`${JSON.stringify(res, null, 2)}\n`); } else { for (const item of res.data.translations) { Bun.stdout.write(`\n\x1b[1m\x1b[36m=== Traduction [${item.detectedSourceLanguage || source || "auto"} -> ${target}] ===\x1b[0m\n`); Bun.stdout.write(`\x1b[1m\x1b[32m${item.translatedText}\x1b[0m\n`); if (item.pronunciation) { Bun.stdout.write(`\x1b[90mPrononciation : ${item.pronunciation}\x1b[0m\n`); } if (item.correction) { Bun.stdout.write(`\n\x1b[33mSuggestion orthographique : ${item.correction.correctedText}\x1b[0m\n`); } if (item.dictionary && item.dictionary.length > 0) { Bun.stdout.write(`\n\x1b[1m\x1b[35m--- Dictionnaire Bilingue ---\x1b[0m\n`); for (const dict of item.dictionary) { Bun.stdout.write(` \x1b[1m[${dict.partOfSpeech}]\x1b[0m ${dict.terms.join(", ")}\n`); for (const d of dict.details.slice(0, 4)) { const rev = d.reverseTranslations.length > 0 ? ` (${d.reverseTranslations.slice(0, 3).join(", ")})` : ""; const art = d.article ? `${d.article} ` : ""; Bun.stdout.write(` • ${art}\x1b[34m${d.word}\x1b[0m${rev}\n`); } } } if (item.definitions && item.definitions.length > 0) { Bun.stdout.write(`\n\x1b[1m\x1b[34m--- Définitions ---\x1b[0m\n`); for (const def of item.definitions) { Bun.stdout.write(` \x1b[1m[${def.partOfSpeech}]\x1b[0m\n`); for (const d of def.definitions.slice(0, 3)) { Bun.stdout.write(` • ${d.definition}\n`); if (d.example) Bun.stdout.write(` \x1b[90mEx: "${d.example}"\x1b[0m\n`); } } } if (item.possibleTranslations && item.possibleTranslations.length > 1) { Bun.stdout.write(`\n\x1b[90mVariantes : ${item.possibleTranslations.slice(0, 6).join(" | ")}\x1b[0m\n`); } } } } else { const res = await defaultTranslateEngine.translate({ q: text, target, source, format, }); if (flags["json"] || flags["raw"]) { Bun.stdout.write(`${JSON.stringify(res, null, 2)}\n`); } else { const output = res.data.translations.map((t) => t.translatedText).join("\n"); Bun.stdout.write(`${output}\n`); } } // Optional TTS synthesis on translate output if (flags["tts"] || flags["audio"]) { const outFile = typeof flags["tts"] === "string" ? flags["tts"] : `${text.slice(0, 20).replace(/[^a-zA-Z0-9]/g, "_")}_${target}.mp3`; const transRes = await defaultTranslateEngine.translate({ q: text, target, source, format }); const translatedText = transRes.data.translations[0]?.translatedText || text; await defaultTTS.saveToFile({ text: translatedText, lang: target }, outFile); logger.log(`\x1b[32mAudio TTS généré avec succès dans : ${outFile}\x1b[0m`); } break; } case "tts": { const { defaultTTS } = await import("../google/translate/index.ts"); let text = positional.slice(1).join(" "); if (text === "-" || (!text && flags["stdin"])) { text = (await Bun.stdin.text()).trim(); } if (!text) { logger.error("tts — missing text to synthesize (use '-' for stdin)"); process.exit(EXIT.MISUSE); } const target = (flags["target"] as string) || (flags["lang"] as string) || "en"; const speed = Number(flags["speed"]) || 1; const outFile = (flags["out"] as string) || `${text.slice(0, 20).replace(/[^a-zA-Z0-9]/g, "_")}_${target}.mp3`; logger.log(`Synthèse vocale pour "${text.slice(0, 40)}..." [lang=${target}]...`); await defaultTTS.saveToFile({ text, lang: target, speed }, outFile); logger.log(`\x1b[32mAudio MP3 sauvegardé : ${outFile}\x1b[0m`); break; } case "suggest": { const query = positional.slice(1).join(" "); if (!query) { logger.error("suggest — missing query argument"); process.exit(EXIT.MISUSE); } const autocompleteClient = (flags["client"] as string) || "chrome"; const client = new KeylessGoogleClient(); const res = await client.autocomplete(query, autocompleteClient); Bun.stdout.write(JSON.stringify(res) + "\n"); break; } case "calendar": { const calendarId = positional[1]; if (!calendarId) { logger.error("calendar — missing calendar_id argument"); process.exit(EXIT.MISUSE); } const client = new KeylessGoogleClient(); const res = await client.getPublicCalendarEvents(calendarId); Bun.stdout.write(JSON.stringify(res, null, 2) + "\n"); break; } case "sheet": { const spreadsheetId = positional[1]; if (!spreadsheetId) { logger.error("sheet [gid] — missing spreadsheet_id argument"); process.exit(EXIT.MISUSE); } const gid = (flags["gid"] as string) || positional[2] || undefined; const client = new KeylessGoogleClient(); const res = await client.exportPublicSheetToCsv(spreadsheetId, gid); Bun.stdout.write(res + "\n"); break; } case "doc": { const documentId = positional[1]; if (!documentId) { logger.error("doc — missing document_id argument"); process.exit(EXIT.MISUSE); } const client = new KeylessGoogleClient(); const res = await client.exportPublicDocToText(documentId); Bun.stdout.write(res + "\n"); break; } case "download": { const fileId = positional[1]; const dest = positional[2]; if (!fileId || !dest) { logger.error("download — missing arguments"); process.exit(EXIT.MISUSE); } const client = new KeylessGoogleClient(); const res = await client.downloadPublicDriveFile(fileId); await Bun.write(dest, res); Bun.stdout.write(JSON.stringify({ saved: dest, bytes: res.length }, null, 2) + "\n"); break; } case "chat": { const prompt = positional.slice(1).join(" "); const cid = (flags["cid"] as string) || undefined; const rid = (flags["rid"] as string) || undefined; const rcid = (flags["rcid"] as string) || undefined; const thread = !!flags["thread"]; const repl = !!flags["repl"]; const model = (flags["model"] as string) || "flash"; const client = new GeminiWebClient({ model }); await client.init(); if (cid) { client.resume(cid, rid, rcid); } if (prompt && !repl) { if (thread) { const reply = await client.generate(prompt, { keepContext: true }); const [cidOut, ridOut, rcidOut] = client.conversation; Bun.stdout.write( JSON.stringify( { reply, title: client.lastTitle, conversation: { cid: cidOut, rid: ridOut, rcid: rcidOut, }, }, null, 2, ) + "\n", ); } else { const reply = await client.generate(prompt, { keepContext: false }); Bun.stdout.write(JSON.stringify(reply) + "\n"); } return; } // Interactive REPL console.log("Starting interactive Gemini Web session. Type 'exit' or 'quit' to end."); if (client.lastTitle) { console.log(`Resumed thread: ${client.lastTitle}`); } else if (cid) { console.log(`Resumed thread ID: ${cid}`); } if (prompt && repl) { process.stdout.write("Gemini: "); const reply = await client.generate(prompt, { keepContext: true }); console.log(reply); } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const askQuestion = () => { rl.question("\nYou: ", async (input) => { const trimmed = input.trim(); if (trimmed.toLowerCase() === "exit" || trimmed.toLowerCase() === "quit") { rl.close(); return; } if (!trimmed) { askQuestion(); return; } process.stdout.write("Gemini: "); try { const reply = await client.generate(trimmed, { keepContext: true }); console.log(reply); } catch (err) { console.error("\nError:", err instanceof Error ? err.message : String(err)); } askQuestion(); }); }; askQuestion(); break; } case "conversations": { const model = (flags["model"] as string) || "flash"; const client = new GeminiWebClient({ model }); await client.init(); const history = await client.listConversations(); Bun.stdout.write(JSON.stringify(history, null, 2) + "\n"); break; } case "resume": { const cid = positional[1]; if (!cid) { logger.error("resume [prompt] — missing conversation ID"); process.exit(EXIT.MISUSE); } const prompt = positional.slice(2).join(" "); const rid = (flags["rid"] as string) || undefined; const rcid = (flags["rcid"] as string) || undefined; const thread = !!flags["thread"]; const repl = !!flags["repl"]; const model = (flags["model"] as string) || "flash"; const client = new GeminiWebClient({ model }); await client.init(); client.resume(cid, rid, rcid); if (prompt && !repl) { if (thread) { const reply = await client.generate(prompt, { keepContext: true }); const [cidOut, ridOut, rcidOut] = client.conversation; Bun.stdout.write( JSON.stringify( { reply, title: client.lastTitle, conversation: { cid: cidOut, rid: ridOut, rcid: rcidOut, }, }, null, 2, ) + "\n", ); } else { const reply = await client.generate(prompt, { keepContext: false }); Bun.stdout.write(JSON.stringify(reply) + "\n"); } return; } // Interactive REPL console.log("Starting interactive Gemini Web session. Type 'exit' or 'quit' to end."); if (client.lastTitle) { console.log(`Resumed thread: ${client.lastTitle}`); } else { console.log(`Resumed thread ID: ${cid}`); } if (prompt && repl) { process.stdout.write("Gemini: "); const reply = await client.generate(prompt, { keepContext: true }); console.log(reply); } const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const askQuestion = () => { rl.question("\nYou: ", async (input) => { const trimmed = input.trim(); if (trimmed.toLowerCase() === "exit" || trimmed.toLowerCase() === "quit") { rl.close(); return; } if (!trimmed) { askQuestion(); return; } process.stdout.write("Gemini: "); try { const reply = await client.generate(trimmed, { keepContext: true }); console.log(reply); } catch (err) { console.error("\nError:", err instanceof Error ? err.message : String(err)); } askQuestion(); }); }; askQuestion(); break; } case "delete": { const cid = positional[1]; if (!cid) { logger.error("delete — missing conversation ID"); process.exit(EXIT.MISUSE); } const model = (flags["model"] as string) || "flash"; const client = new GeminiWebClient({ model }); await client.init(); await client.deleteConversation(cid); Bun.stdout.write(JSON.stringify({ deleted: cid }, null, 2) + "\n"); break; } case "scrape": { const out = flags["out"] as string; const jsonOut = flags["json-out"] as string; const scraper = new GeminiScraper(); const data = await scraper.scrape(); if (jsonOut) { await Bun.write(jsonOut, JSON.stringify(data, null, 2)); } const reportMd = scraper.formatMarkdownReport(data); if (out) { await Bun.write(out, reportMd); } Bun.stdout.write( JSON.stringify( { script_bundles_count: data.script_urls.length, css_classes_count: data.css_classes.length, css_variables_count: data.css_variables.length, rpc_services_count: data.rpc_services.length, rpc_methods_count: data.rpc_methods.length, rpc_mappings_count: Object.keys(data.rpc_mappings).length, boq_hashes_count: data.boq_hashes.length, buttons_count: data.buttons.length, models_found: data.models, markdown_saved_to: out || null, json_saved_to: jsonOut || null, }, null, 2, ) + "\n", ); break; } case "auto-upgrade": { logger.log("Initializing static code crawler for Gemini App..."); const scraper = new GeminiScraper(); const data = await scraper.scrape(); const clientFile = join(process.cwd(), "src/google/gemini-web.ts"); const originalCode = await Bun.file(clientFile).text(); let listHash: string | null = null; let deleteHash: string | null = null; for (const [h, m] of Object.entries(data.rpc_mappings)) { if (m === "BardFrontendService.ListConversations") { listHash = h; } else if (m === "BardFrontendService.DeleteConversation") { deleteHash = h; } } const listBlockMatch = originalCode.match( /async listConversations\(\): Promise \{([\s\S]*?)\}/, ); const deleteBlockMatch = originalCode.match( /async deleteConversation\(cid: string\): Promise \{([\s\S]*?)\}/, ); let currentListHash = "MaZiqc"; let currentDeleteHash = "GzXR5e"; if (listBlockMatch) { const hashMatch = listBlockMatch[1].match(/"([A-Za-z0-9_]{5,6})"/); if (hashMatch) currentListHash = hashMatch[1]; } if (deleteBlockMatch) { const hashMatch = deleteBlockMatch[1].match(/"([A-Za-z0-9_]{5,6})"/); if (hashMatch) currentDeleteHash = hashMatch[1]; } let updatedCode = originalCode; const replacements = []; if (listHash && listHash !== currentListHash) { logger.log(`Detected new ListConversations hash: ${listHash}`); updatedCode = updatedCode.replace(new RegExp(`"${currentListHash}"`, "g"), `"${listHash}"`); replacements.push({ target: currentListHash, replacement: listHash }); } if (deleteHash && deleteHash !== currentDeleteHash) { logger.log(`Detected new DeleteConversation hash: ${deleteHash}`); updatedCode = updatedCode.replace(new RegExp(`"${currentDeleteHash}"`, "g"), `"${deleteHash}"`); replacements.push({ target: currentDeleteHash, replacement: deleteHash }); } if (replacements.length > 0) { logger.log(`Applying ${replacements.length} code replacements...`); await Bun.write(clientFile, updatedCode); logger.log("Running code quality validations..."); const typecheckProc = Bun.spawn(["bun", "run", "typecheck"]); const typecheckExit = await typecheckProc.exited; const lintProc = Bun.spawn(["bun", "run", "lint"]); const lintExit = await lintProc.exited; const testProc = Bun.spawn(["bun", "test", "test/", "packages/", "src/"]); const testExit = await testProc.exited; if (typecheckExit !== 0 || lintExit !== 0 || testExit !== 0) { logger.error("Validation failed! Rolling back changes to original state."); await Bun.write(clientFile, originalCode); throw new Error("Autonomous upgrade failed validation tests. Rolled back successfully."); } else { logger.log("Validation passed successfully! Code upgraded."); } } else { logger.log("No upgrades required. Codebase features are fully up to date."); } Bun.stdout.write( JSON.stringify( { success: true, scraped_mappings_count: Object.keys(data.rpc_mappings).length, replacements_applied: replacements, upgraded: replacements.length > 0, }, null, 2, ) + "\n", ); break; } default: { logger.error(`Unknown action: ${action}`); printUsage(); process.exit(EXIT.MISUSE); } } } catch (err) { logger.error(err instanceof Error ? err.message : String(err)); process.exit(EXIT.DATA_ERR); } }