Skip to content

Commit 2bf4e3d

Browse files
authored
feat(web-search): live gemini executor on the Antigravity CCA transport (lidge-jun#2188 L8) (lidge-jun#2243)
* feat(web-search): gemini executor on the Antigravity CCA transport (lidge-jun#2188 L8) runGeminiWebSearch sends the CCA envelope (registry-pinned endpoint, IDE fingerprint UA, discovered projectId, google_search tool, effort-mapped thinkingLevel) with the stored Antigravity OAuth and maps candidates[0] text + groundingMetadata.groundingChunks to the sidecar outcome. planWebSearch's gemini arm goes live fail-closed on OAuth or projectId absence; the loop arm fails closed without a resolved provider; the registry activates the backend on the same predicate. * fix(web-search): redact all thrown branches and pin the gemini request shape Non-Error throws reached tool results unredacted in both new executors. Adds the reviewer-demanded request-shape test (registry destination despite a malicious baseUrl, manual redirect, bearer + IDE UA, full CCA envelope) and the gemini loop fail-closed regression mirroring xai. * test(web-search): assert the effort-to-thinkingLevel mapping reaches the CCA envelope * fix(web-search): harden Gemini snapshot and body reads Bind the bearer token and Cloud Code Assist project to one OAuthAccessSnapshot so an active-account switch cannot cross-pair credentials. Guard the response body immediately after headers, then consume success and error payloads through the shared 64 KiB byte bound with linked cancellation and strict UTF-8 JSON parsing. Add regressions for account switching, post-header abort settlement, and oversized success/error cancellation. Evidence: bun test tests/gemini-web-search.test.ts tests/cancel-body-on-abort.test.ts tests/bounded-body.test.ts (50 pass); bun x tsc --noEmit; bun run privacy:scan.
1 parent b29edeb commit 2bf4e3d

7 files changed

Lines changed: 493 additions & 5 deletions

File tree

‎src/server/responses/core.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3587,6 +3587,7 @@ async function handleResponsesInner(
35873587
forwardProvider: wsPlan.forwardSidecar?.provider,
35883588
anthropicSidecar: wsPlan.anthropicSidecar,
35893589
xaiSidecar: wsPlan.xaiSidecar,
3590+
geminiSidecar: wsPlan.geminiSidecar,
35903591
xaiSearchOptions: wsPlan.xaiSearchOptions,
35913592
hostedTool: wsPlan.hostedTool,
35923593
selectedForwardHeaders: wsPlan.forwardSidecar?.headers ?? selectedForwardHeaders,

‎src/web-search/backends.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,19 @@ export const WEB_SEARCH_BACKENDS: readonly WebSearchBackendDescriptor[] = [
6666
},
6767
eligibleModel: candidate => candidate.provider === "xai",
6868
},
69+
{
70+
backend: "gemini",
71+
// Probe = usable Antigravity OAuth + discovered projectId (findGeminiSidecarProvider's predicate).
72+
isActive: (_auth, config) => {
73+
const provider = config.providers["google-antigravity"];
74+
if (!provider || provider.disabled === true || provider.authMode !== "oauth") return false;
75+
const set = getAccountSet("google-antigravity");
76+
const active = set?.accounts.find(account => account.id === set.activeAccountId);
77+
if (!active || active.needsReauth === true) return false;
78+
return !!(active.credential as { projectId?: string } | undefined)?.projectId;
79+
},
80+
eligibleModel: candidate => candidate.provider === "google-antigravity",
81+
},
6982
];
7083

7184
/**

‎src/web-search/gemini-executor.ts‎

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
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+
}

‎src/web-search/index.ts‎

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,15 @@ export { runWithWebSearch } from "./loop";
1414
export { buildWebSearchTool, extractHostedWebSearch, WEB_SEARCH_TOOL_NAME };
1515
export { runAnthropicWebSearch, parseAnthropicSidecarSSE } from "./anthropic-executor";
1616
export { runXaiWebSearch, parseXaiResponsesSSE, validateXaiSearchOptions, type XaiSearchOptions } from "./xai-executor";
17+
export { runGeminiWebSearch, mapCcaGroundedResponse } from "./gemini-executor";
1718

1819
const DEFAULT_SIDECAR_MODEL = "gpt-5.6-luna";
1920
// Default Claude model for the anthropic-backed sidecar (used when cfg.model is unset).
2021
const DEFAULT_ANTHROPIC_SIDECAR_MODEL = "claude-sonnet-5";
2122
// Default Grok model for the xai-backed sidecar (probe-verified with hosted tools, devlog 003).
2223
const DEFAULT_XAI_SIDECAR_MODEL = "grok-4.6";
24+
// Default Gemini model for the gemini-backed sidecar (CCA grounding probe, devlog 002).
25+
const DEFAULT_GEMINI_SIDECAR_MODEL = "gemini-3.7-flash";
2326
// "low" is the lightest effort the ChatGPT backend allows with web_search ("minimal" is rejected:
2427
// "tools cannot be used with reasoning.effort 'minimal'") — keeps the sidecar fast/cheap.
2528
const DEFAULT_SIDECAR_REASONING = "low";
@@ -114,6 +117,23 @@ export function findXaiSidecarProvider(config: OcxConfig): { providerName: strin
114117
return undefined;
115118
}
116119

120+
/**
121+
* First usable Antigravity credential holder: the "google-antigravity" provider
122+
* (registry id = OAuth store key, same narrowing as findXaiSidecarProvider) whose
123+
* active stored account is healthy AND carries a discovered CCA projectId — the
124+
* executor cannot form the envelope without it.
125+
*/
126+
export function findGeminiSidecarProvider(config: OcxConfig): { providerName: string; provider: OcxProviderConfig } | undefined {
127+
const provider = config.providers["google-antigravity"];
128+
if (!provider || provider.disabled === true || provider.authMode !== "oauth") return undefined;
129+
const set = getAccountSet("google-antigravity");
130+
const active = set?.accounts.find(account => account.id === set.activeAccountId);
131+
if (!active || active.needsReauth === true) return undefined;
132+
const projectId = (active.credential as { projectId?: string } | undefined)?.projectId;
133+
if (!projectId) return undefined;
134+
return { providerName: "google-antigravity", provider };
135+
}
136+
117137
/** Lift the persisted xSearch config block into executor options (absent block = web_search only). */
118138
export function xaiSearchOptionsFromConfig(cfg: Pick<OcxWebSearchSidecarConfig, "xSearch">): XaiSearchOptions {
119139
const x = cfg.xSearch;
@@ -154,6 +174,8 @@ export interface SidecarPlan {
154174
anthropicSidecar?: AnthropicSidecarProvider;
155175
/** Present for the xai backend (stored Grok OAuth /v1/responses path). */
156176
xaiSidecar?: { providerName: string; provider: OcxProviderConfig };
177+
/** Present for the gemini backend (Antigravity CCA grounding path). */
178+
geminiSidecar?: { providerName: string; provider: OcxProviderConfig };
157179
/** Opt-in x_search options for the xai backend (validated at the management layer and again in the executor). */
158180
xaiSearchOptions?: XaiSearchOptions;
159181
hostedTool: Record<string, unknown>;
@@ -206,9 +228,9 @@ export function planWebSearch(
206228
? { providerName: auth.anthropicProviderName, provider: auth.anthropicProvider }
207229
: undefined;
208230
const backend = resolveSidecarBackend(cfg.backend);
209-
// Inert arms (roadmap 060): gemini/exa stay fail-closed until their executor
210-
// layers land. The xai arm went live in L7 below.
211-
if (backend === "gemini" || backend === "exa") return undefined;
231+
// Inert arm (roadmap 060): exa stays fail-closed until its executor layer lands.
232+
// xai went live in L7; gemini in L8 below.
233+
if (backend === "exa") return undefined;
212234
const maxSearches = cfg.maxSearchesPerTurn ?? DEFAULT_MAX_SEARCHES;
213235
const stallTimeoutSec = webSearchStallTimeoutSec(
214236
config.stallTimeoutSec,
@@ -260,6 +282,23 @@ export function planWebSearch(
260282
};
261283
}
262284

285+
// Gemini backend (L8): explicit-only, authenticated by the stored Antigravity CCA
286+
// OAuth credential; requires the discovered projectId. Fail-closed like the others.
287+
if (backend === "gemini") {
288+
const geminiSidecar = findGeminiSidecarProvider(config);
289+
if (!geminiSidecar) return undefined;
290+
return {
291+
backend: "gemini",
292+
geminiSidecar,
293+
hostedTool: parsed._webSearch,
294+
settings: { model: cfg.model ?? DEFAULT_GEMINI_SIDECAR_MODEL, reasoning, timeoutMs, describeImages },
295+
maxSearches,
296+
routedModelStallTimeoutMs,
297+
stallTimeoutSec,
298+
streamRoutedModelOutput,
299+
};
300+
}
301+
263302
// OpenAI backend: needs a ChatGPT login (main) and a forward provider to reach server-side web_search.
264303
if (!openAiSidecar) return undefined;
265304
return {

‎src/web-search/loop.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { bridgeToResponsesSSE } from "../bridge";
77
import { runWebSearch, type SidecarOutcome, type SidecarOutcomeRecorder, type SidecarSettings } from "./executor";
88
import { runAnthropicWebSearch } from "./anthropic-executor";
99
import { runXaiWebSearch, type XaiSearchOptions } from "./xai-executor";
10+
import { runGeminiWebSearch } from "./gemini-executor";
1011
import type { WebSearchBackendId } from "./index";
1112
import { clearableDeadline } from "../lib/abort";
1213
import { redactSecretString } from "../lib/redact";
@@ -264,6 +265,8 @@ export interface WebSearchLoopDeps {
264265
anthropicSidecar?: { providerName: string; provider: OcxProviderConfig };
265266
/** Required for the xai backend: the stored Grok OAuth provider (L7). */
266267
xaiSidecar?: { providerName: string; provider: OcxProviderConfig };
268+
/** Required for the gemini backend: the stored Antigravity CCA provider (L8). */
269+
geminiSidecar?: { providerName: string; provider: OcxProviderConfig };
267270
/** Opt-in x_search options for the xai backend. */
268271
xaiSearchOptions?: XaiSearchOptions;
269272
hostedTool: Record<string, unknown>;
@@ -677,6 +680,11 @@ export async function runWithWebSearch(deps: WebSearchLoopDeps): Promise<Respons
677680
outcome = deps.xaiSidecar
678681
? await runXaiWebSearch(query, deps.xaiSidecar.providerName, deps.xaiSidecar.provider, settings, deps.xaiSearchOptions ?? {}, signal)
679682
: { text: "", sources: [], error: "xai backend selected without a resolved Grok OAuth provider" };
683+
} else if (backend === "gemini") {
684+
// L8: Antigravity CCA grounding; same fail-closed invariant stance as xai.
685+
outcome = deps.geminiSidecar
686+
? await runGeminiWebSearch(query, deps.geminiSidecar.providerName, deps.geminiSidecar.provider, settings, signal)
687+
: { text: "", sources: [], error: "gemini backend selected without a resolved Antigravity provider" };
680688
} else {
681689
outcome = await runWebSearch(query, hostedTool, forwardProvider!, selectedForwardHeaders, settings, signal, recordSidecarOutcome);
682690
}

‎src/web-search/xai-executor.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,7 @@ export async function runXaiWebSearch(
127127
} catch (e) {
128128
const kind = e instanceof Error && e.name === "TimeoutError" ? "timeout" : "connect_error";
129129
console.warn(`[web-search] xai sidecar ${kind} (${Date.now() - t0}ms)`);
130-
return { text: "", sources: [], error: e instanceof Error ? redactSecretString(e.message) : String(e) };
130+
return { text: "", sources: [], error: redactSecretString(e instanceof Error ? e.message : String(e)) };
131131
} finally {
132132
sidecarExit();
133133
linkedSignal.cleanup();
@@ -208,7 +208,7 @@ export async function parseXaiResponsesSSE(response: Response): Promise<SidecarO
208208
}
209209
}
210210
} catch (e) {
211-
error = e instanceof Error ? redactSecretString(e.message) : String(e);
211+
error = redactSecretString(e instanceof Error ? e.message : String(e));
212212
} finally {
213213
reader.releaseLock();
214214
}

0 commit comments

Comments
 (0)