// PlainSearch: one search box, real websites ranked by fit and relevance. // Gemini with Google Search grounding finds and ranks pages; every result is // checked against the grounding sources or a live request before it is shown. const MODELS_DEFAULT = ["gemini-3.5-flash-lite", "gemini-flash-latest"]; const MAX_RESULTS = 10; const CACHE_SECONDS = 6 * 60 * 60; export default { async fetch(request, env, ctx) { const url = new URL(request.url); if (url.hostname === "www.plainsearch.ai") { url.hostname = "plainsearch.ai"; return Response.redirect(url.toString(), 301); } switch (url.pathname) { case "/": return html(PAGE); case "/api/search": return search(request, env, ctx, url); case "/favicon.svg": return new Response(FAVICON, { headers: { "content-type": "image/svg+xml", "cache-control": "public, max-age=86400" } }); case "/favicon.ico": return Response.redirect(url.origin + "/favicon.svg", 302); case "/robots.txt": return text("User-agent: *\nAllow: /\nDisallow: /api/\nSitemap: https://plainsearch.ai/sitemap.xml\n"); case "/sitemap.xml": return new Response(`\nhttps://plainsearch.ai/\n`, { headers: { "content-type": "application/xml" } }); case "/opensearch.xml": return new Response(OPENSEARCH, { headers: { "content-type": "application/opensearchdescription+xml" } }); default: return html(PAGE.replace("", "404"), 404); } }, }; function html(body, status = 200) { return new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=300", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", "content-security-policy": "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'", }, }); } function text(body) { return new Response(body, { headers: { "content-type": "text/plain; charset=utf-8" } }); } function json(obj, status = 200, extra = {}) { return new Response(JSON.stringify(obj), { status, headers: { "content-type": "application/json; charset=utf-8", "referrer-policy": "no-referrer", ...extra }, }); } async function search(request, env, ctx, url) { const q = (url.searchParams.get("q") || "").replace(/\s+/g, " ").trim().slice(0, 300); if (!q) return json({ error: "Type something to search for." }, 400); if (!env.GEMINI_API_KEY) return json({ error: "Search is not set up yet." }, 503); const cacheKey = new Request("https://plainsearch.ai/cache/v1?q=" + encodeURIComponent(q.toLowerCase())); const cache = caches.default; const hit = await cache.match(cacheKey); if (hit) return hit; let data; try { data = await runSearch(q, env); } catch (err) { console.log("search failed", String(err && err.stack || err)); return json({ error: "Search is busy right now. Try again in a moment." }, 502); } const res = json(data, 200, { "cache-control": `public, max-age=${CACHE_SECONDS}` }); if (data.results.length) ctx.waitUntil(cache.put(cacheKey, res.clone())); return res; } async function runSearch(q, env) { const started = Date.now(); const models = (env.GEMINI_MODEL ? [env.GEMINI_MODEL] : []).concat(MODELS_DEFAULT); const prompt = `You are the ranking engine of a web search engine. Use Google Search to find the best real web pages for this query: "${q}" Return the ${MAX_RESULTS} most useful pages, best first. Rank by how well each page fits what the person is most likely looking for (intent), then by relevance, authority and freshness. Prefer the official site or the original source when one exists. Use exact, working URLs of specific pages that you found in the search results; never invent or guess a URL. No duplicates, at most two pages from the same site. Reply with only a JSON array, no prose and no code fences. Each item: {"title": "page title", "url": "https://...", "snippet": "one or two plain sentences on what the page offers for this query", "score": 0-100 fit}`; // Two independent grounded passes run side by side and are merged. If a // round still comes back empty, run another round (up to 3, within ~20s), // pooling everything found so far, so people never see an empty page. const poolText = []; const poolChunks = []; let results = []; let lastErr; for (let round = 0; round < 3 && !results.length; round++) { if (round && Date.now() - started > 20000) break; const runs = await Promise.allSettled([askModels(models, prompt, env), askModels(models, prompt + MORE, env)]); const ok = runs.filter((r) => r.status === "fulfilled").map((r) => r.value); if (!ok.length) { lastErr = runs[0].reason; continue; } for (const o of ok) { poolText.push(...parseArray(o.text)); poolChunks.push(...o.chunks); } results = await buildResults({ text: JSON.stringify(poolText), chunks: poolChunks }); } if (!results.length) results = fallbackResults(poolText, poolChunks); if (!results.length && lastErr) throw lastErr; return { query: q, results, ms: Date.now() - started }; } // Last resort when verification removed everything: show the model's own picks // and the raw Google source links (they redirect to the real pages). function fallbackResults(items, chunks) { const out = []; const seen = new Set(); const perHost = {}; const add = (title, url, snippet, site) => { if (out.length >= MAX_RESULTS || !(isWebUrl(url) || (site && /^https:\/\/vertexaisearch\.cloud\.google\.com\//.test(url)))) return; const n = normalize(url); const h = site || host(url); if (seen.has(n) || (perHost[h] || 0) >= 2) return; seen.add(n); perHost[h] = (perHost[h] || 0) + 1; out.push({ title: title || h, url, snippet: snippet || "", score: 0, site: h }); }; for (const it of items) if (it && typeof it.url === "string") add(clean(it.title), it.url.trim(), clean(it.snippet)); // Google's source titles are usually the site's domain. for (const c of chunks) add(c.title || "", c.uri, "", /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(c.title || "") ? c.title.toLowerCase() : ""); return out; } const MORE = ` Cast a wide net: run several different searches for this query (official sources, guides, references, reviews, news) so you can return a full list of 10 distinct pages.`; async function askModels(models, prompt, env) { let lastErr; for (const model of [...new Set(models)]) { try { return await callGemini(model, prompt, env.GEMINI_API_KEY); } catch (err) { lastErr = err; if (!(err && err.retryable)) break; } } throw lastErr; } async function callGemini(model, prompt, key) { const res = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent`, { method: "POST", headers: { "content-type": "application/json", "x-goog-api-key": key }, body: JSON.stringify({ contents: [{ role: "user", parts: [{ text: prompt }] }], tools: [{ google_search: {} }], generationConfig: { temperature: 0.2 }, }), }); if (!res.ok) { const body = await res.text(); const err = new Error(`Gemini ${model} ${res.status}: ${body.slice(0, 300)}`); err.retryable = res.status === 404 || res.status === 429 || res.status >= 500; throw err; } const data = await res.json(); const cand = (data.candidates || [])[0] || {}; const textOut = ((cand.content || {}).parts || []).map((p) => p.text || "").join(""); const chunks = ((cand.groundingMetadata || {}).groundingChunks || []) .map((c) => c.web) .filter((w) => w && w.uri); return { text: textOut, chunks }; } async function buildResults({ text, chunks }) { // Resolve grounding redirect links to the real pages they point at. const grounded = (await Promise.all(chunks.map(async (c) => ({ title: c.title || "", url: await resolveRedirect(c.uri) })))) .filter((g) => g.url && isWebUrl(g.url)); const groundedHosts = new Set(grounded.map((g) => host(g.url))); let items = parseArray(text) .filter((it) => it && typeof it.url === "string" && isWebUrl(it.url)) .map((it) => ({ title: clean(it.title) || host(it.url), url: it.url.trim(), snippet: clean(it.snippet), score: Math.max(0, Math.min(100, Number(it.score) || 0)), })); // Keep a model result if its site was in the live search results, or if the page answers. const checked = await Promise.all( items.map(async (it) => (groundedHosts.has(host(it.url)) || (await pageExists(it.url)) ? it : null)), ); items = checked.filter(Boolean); // Add grounded pages the model did not list, after its ranked picks. const have = new Set(items.map((it) => normalize(it.url))); for (const g of grounded) { if (items.length >= MAX_RESULTS) break; if (have.has(normalize(g.url))) continue; have.add(normalize(g.url)); items.push({ title: g.title || host(g.url), url: g.url, snippet: "", score: 0 }); } const seen = new Set(); const perHost = {}; const out = []; for (const it of items.sort((a, b) => b.score - a.score)) { const n = normalize(it.url); const h = host(it.url); if (seen.has(n) || (perHost[h] || 0) >= 2) continue; seen.add(n); perHost[h] = (perHost[h] || 0) + 1; out.push({ ...it, site: h }); if (out.length >= MAX_RESULTS) break; } return out; } async function resolveRedirect(uri) { if (!/vertexaisearch\.cloud\.google\.com\/grounding-api-redirect/.test(uri)) return uri; try { const res = await fetch(uri, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(4000) }); return res.headers.get("location") || ""; } catch { return ""; } } async function pageExists(u) { try { const res = await fetch(u, { method: "GET", redirect: "follow", headers: { "user-agent": "Mozilla/5.0 (compatible; PlainSearchBot/1.0; +https://plainsearch.ai)" }, signal: AbortSignal.timeout(3500), }); try { res.body && res.body.cancel(); } catch {} // Many sites refuse bots (401/403/429); the page still exists. Only treat missing pages as dead. return res.status !== 404 && res.status !== 410 && res.status < 500; } catch { return false; } } function parseArray(t) { if (!t) return []; const s = t.replace(/```(?:json)?/gi, ""); const a = s.indexOf("["), b = s.lastIndexOf("]"); if (a < 0 || b <= a) return []; try { const v = JSON.parse(s.slice(a, b + 1)); return Array.isArray(v) ? v : []; } catch { return []; } } function isWebUrl(u) { try { const p = new URL(u); return (p.protocol === "https:" || p.protocol === "http:") && !/vertexaisearch\.cloud\.google\.com/.test(p.hostname); } catch { return false; } } function host(u) { try { return new URL(u).hostname.replace(/^www\./, ""); } catch { return ""; } } function normalize(u) { try { const p = new URL(u); return (p.hostname.replace(/^www\./, "") + p.pathname.replace(/\/+$/, "") + p.search).toLowerCase(); } catch { return u; } } function clean(s) { return typeof s === "string" ? s.replace(/\s+/g, " ").trim().slice(0, 400) : ""; } const FAVICON = ``; const OPENSEARCH = ` PlainSearch Search the web with PlainSearch UTF-8 https://plainsearch.ai/favicon.svg `; const PAGE = ` PlainSearch
${FAVICON}PlainSearch

Real websites, ranked by how well they fit.

${FAVICON}PlainSearch
    `;