|
| 1 | +/** |
| 2 | + * Execute ONE web search via Gemini google_search grounding on the Antigravity |
| 3 | + * Cloud Code Assist transport (#2188 L8). Live-probed 2026-08-20/21 (devlog 002): |
| 4 | + * the CCA envelope with tools [{google_search:{}}] returns a grounded answer |
| 5 | + * plus groundingMetadata; a non-IDE User-Agent gets 404, so the request reuses |
| 6 | + * the adapter's fingerprint constants. The OAuth bearer only ever travels to |
| 7 | + * the REGISTRY-pinned endpoint — a config-level baseUrl override is never |
| 8 | + * trusted for token transmission (same rule as src/server/images.ts). |
| 9 | + * Never throws — returns {error} so the caller injects a graceful tool result. |
| 10 | + */ |
| 11 | +import type { OcxProviderConfig } from "../types"; |
| 12 | +import { getValidAccessTokenSnapshot, publicOAuthAuthenticationErrorMessage } from "../oauth"; |
| 13 | +import { fetchWithResetRetry } from "../lib/upstream-retry"; |
| 14 | +import { cancelBodyOnAbort, signalWithTimeout } from "../lib/abort"; |
| 15 | +import { readBoundedResponseBytes } from "../lib/bounded-body"; |
| 16 | +import { sidecarEnter } from "../lib/sidecar-tracker"; |
| 17 | +import { redactSecretString } from "../lib/redact"; |
| 18 | +import { ANTIGRAVITY_REQUEST_UA } from "../adapters/google-antigravity-wire"; |
| 19 | +import { resolveAntigravityEffortWireModel } from "../providers/antigravity-models"; |
| 20 | +import { getProviderRegistryEntry } from "../providers/registry"; |
| 21 | +import { MAX_SIDECAR_RESPONSE_BYTES, type WebSearchSource } from "./parse"; |
| 22 | +import { BASE_INSTRUCTION, IMAGE_INSTRUCTION, type SidecarOutcome, type SidecarSettings } from "./executor"; |
| 23 | + |
| 24 | +const CCA_FALLBACK_BASE = "https://daily-cloudcode-pa.googleapis.com"; |
| 25 | + |
| 26 | +function isRec(v: unknown): v is Record<string, unknown> { |
| 27 | + return !!v && typeof v === "object" && !Array.isArray(v); |
| 28 | +} |
| 29 | + |
| 30 | +export async function runGeminiWebSearch( |
| 31 | + query: string, |
| 32 | + providerName: string, |
| 33 | + _provider: OcxProviderConfig, |
| 34 | + settings: SidecarSettings, |
| 35 | + abortSignal?: AbortSignal, |
| 36 | +): Promise<SidecarOutcome> { |
| 37 | + let token: string; |
| 38 | + let project: string | undefined; |
| 39 | + try { |
| 40 | + const snapshot = await getValidAccessTokenSnapshot(providerName); |
| 41 | + token = snapshot.accessToken; |
| 42 | + project = snapshot.projectId; |
| 43 | + } catch (e) { |
| 44 | + return { text: "", sources: [], error: `gemini sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(e)}` }; |
| 45 | + } |
| 46 | + if (!project) { |
| 47 | + return { text: "", sources: [], error: "gemini sidecar missing Cloud Code Assist project id — re-run ocx login google-antigravity" }; |
| 48 | + } |
| 49 | + // Destination pinned to the registry endpoint (see module doc). |
| 50 | + const base = getProviderRegistryEntry("google-antigravity")?.baseUrl ?? CCA_FALLBACK_BASE; |
| 51 | + const { wireModelId, thinkingLevel } = resolveAntigravityEffortWireModel(settings.model, settings.reasoning, base); |
| 52 | + const instruction = settings.describeImages ? BASE_INSTRUCTION + IMAGE_INSTRUCTION : BASE_INSTRUCTION; |
| 53 | + const envelope = { |
| 54 | + model: wireModelId, |
| 55 | + userAgent: "antigravity", |
| 56 | + requestType: "agent", |
| 57 | + project, |
| 58 | + requestId: `agent-${crypto.randomUUID()}`, |
| 59 | + request: { |
| 60 | + systemInstruction: { role: "user", parts: [{ text: instruction }] }, |
| 61 | + contents: [{ role: "user", parts: [{ text: query }] }], |
| 62 | + tools: [{ google_search: {} }], |
| 63 | + sessionId: crypto.randomUUID(), |
| 64 | + ...(thinkingLevel ? { generationConfig: { thinkingConfig: { thinkingLevel } } } : {}), |
| 65 | + }, |
| 66 | + }; |
| 67 | + const linkedSignal = signalWithTimeout(settings.timeoutMs, abortSignal); |
| 68 | + const sidecarExit = sidecarEnter("web-search"); |
| 69 | + const t0 = Date.now(); |
| 70 | + try { |
| 71 | + const res = await fetchWithResetRetry( |
| 72 | + () => fetch(`${base}/v1internal:generateContent`, { |
| 73 | + method: "POST", |
| 74 | + headers: { |
| 75 | + "Content-Type": "application/json", |
| 76 | + "Authorization": `Bearer ${token}`, |
| 77 | + "User-Agent": ANTIGRAVITY_REQUEST_UA, |
| 78 | + }, |
| 79 | + body: JSON.stringify(envelope), |
| 80 | + signal: linkedSignal.signal, |
| 81 | + redirect: "manual", |
| 82 | + }), |
| 83 | + { abortSignal: linkedSignal.signal, label: "gemini-web-search-sidecar" }, |
| 84 | + ); |
| 85 | + const detachBodyGuard = cancelBodyOnAbort(res.body, linkedSignal.signal); |
| 86 | + try { |
| 87 | + const bounded = await readBoundedResponseBytes(res, { |
| 88 | + maxBytes: MAX_SIDECAR_RESPONSE_BYTES, |
| 89 | + signal: linkedSignal.signal, |
| 90 | + }); |
| 91 | + if (bounded.oversized) { |
| 92 | + const prefix = res.ok ? "gemini sidecar response" : `gemini sidecar HTTP ${res.status} response`; |
| 93 | + return { text: "", sources: [], error: `${prefix} exceeded byte bound` }; |
| 94 | + } |
| 95 | + const text = new TextDecoder("utf-8", { fatal: true }).decode(bounded.bytes); |
| 96 | + if (!res.ok) { |
| 97 | + return { text: "", sources: [], error: `gemini sidecar HTTP ${res.status}: ${redactSecretString(text.slice(0, 200))}` }; |
| 98 | + } |
| 99 | + let payload: unknown = null; |
| 100 | + try { |
| 101 | + payload = JSON.parse(text); |
| 102 | + } catch { |
| 103 | + // The mapper owns the stable malformed/empty JSON outcome. |
| 104 | + } |
| 105 | + return mapCcaGroundedResponse(payload); |
| 106 | + } finally { |
| 107 | + detachBodyGuard(); |
| 108 | + } |
| 109 | + } catch (e) { |
| 110 | + const kind = e instanceof Error && e.name === "TimeoutError" ? "timeout" : "connect_error"; |
| 111 | + console.warn(`[web-search] gemini sidecar ${kind} (${Date.now() - t0}ms)`); |
| 112 | + return { text: "", sources: [], error: redactSecretString(e instanceof Error ? e.message : String(e)) }; |
| 113 | + } finally { |
| 114 | + sidecarExit(); |
| 115 | + linkedSignal.cleanup(); |
| 116 | + } |
| 117 | +} |
| 118 | + |
| 119 | +/** Map a CCA generateContent payload (possibly wrapped in {response}) to text + grounding sources. */ |
| 120 | +export function mapCcaGroundedResponse(payload: unknown): SidecarOutcome { |
| 121 | + const root = isRec(payload) && isRec(payload.response) ? payload.response : payload; |
| 122 | + if (!isRec(root)) return { text: "", sources: [], error: "gemini sidecar returned a non-JSON or empty body" }; |
| 123 | + const candidate = Array.isArray(root.candidates) && isRec(root.candidates[0]) ? root.candidates[0] : undefined; |
| 124 | + if (!candidate) return { text: "", sources: [], error: "gemini sidecar returned no candidates" }; |
| 125 | + const parts = isRec(candidate.content) && Array.isArray(candidate.content.parts) ? candidate.content.parts : []; |
| 126 | + const text = parts.map(p => (isRec(p) && typeof p.text === "string" ? p.text : "")).join(""); |
| 127 | + const sources: WebSearchSource[] = []; |
| 128 | + const seen = new Set<string>(); |
| 129 | + const gm = isRec(candidate.groundingMetadata) ? candidate.groundingMetadata : undefined; |
| 130 | + if (gm && Array.isArray(gm.groundingChunks)) { |
| 131 | + for (const chunk of gm.groundingChunks) { |
| 132 | + const web = isRec(chunk) && isRec(chunk.web) ? chunk.web : undefined; |
| 133 | + const uri = web && typeof web.uri === "string" ? web.uri : undefined; |
| 134 | + if (!uri || seen.has(uri)) continue; |
| 135 | + seen.add(uri); |
| 136 | + sources.push({ url: uri, ...(typeof web?.title === "string" && web.title.length > 0 ? { title: web.title } : {}) }); |
| 137 | + } |
| 138 | + } |
| 139 | + if (text.length === 0) return { text: "", sources, error: "gemini sidecar returned no text" }; |
| 140 | + return { text, sources }; |
| 141 | +} |
0 commit comments