Skip to content

Commit d3f4530

Browse files
authored
feat(google): allow operator headers on Gemini web search (#115549)
* feat(google): support Gemini web search headers * fix(google): validate Gemini search headers * docs(changelog): credit Gemini headers * test(secrets): route config contracts through collector * chore: remove release-owned changelog entry * test(google): cover resolved search headers
1 parent f0b7256 commit d3f4530

13 files changed

Lines changed: 430 additions & 30 deletions
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"core": 2307,
33
"channel": 3692,
4-
"plugin": 4055
4+
"plugin": 4057
55
}
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
00b1e5142ead3ba8522cc4815dfb6f8d3fb5ea4e2937df93da280d44506308d7 config-baseline.json
1+
6b02737084409d3a0c92611049077284826bafbe29e7227b3eda591ead80c2e3 config-baseline.json
22
b89715475e4b18a0d32765fda42bcce38537f6d49f949bb4ff0c7d1630101882 config-baseline.core.json
33
e9a81ee89ff032033012413e161316e4d07e8f6b206382a25fed2f8485151b5e config-baseline.channel.json
4-
d0352edda9ee2e6ff3c52b163bf2364ffef6a1d0d2ffe3b0b38de28756fd6c1b config-baseline.plugin.json
4+
c097c0bee74849e691bf295b070ce189d4e0e501bd770e448922d9f399c4901f config-baseline.plugin.json

‎docs/reference/secretref-credential-surface.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ The lists below are generated from the source target registry and checked agains
5050
- `plugins.entries.firecrawl.config.webFetch.apiKey`
5151
- `plugins.entries.google-meet.config.realtime.providers.*.apiKey`
5252
- `plugins.entries.google.config.webSearch.apiKey`
53+
- `plugins.entries.google.config.webSearch.headers.*`
5354
- `plugins.entries.xai.config.webSearch.apiKey`
5455
- `plugins.entries.moonshot.config.webSearch.apiKey`
5556
- `plugins.entries.perplexity.config.webSearch.apiKey`

‎docs/reference/secretref-user-supplied-credentials-matrix.json‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,13 @@
633633
"secretShape": "secret_input",
634634
"optIn": true
635635
},
636+
{
637+
"id": "plugins.entries.google.config.webSearch.headers.*",
638+
"configFile": "openclaw.json",
639+
"path": "plugins.entries.google.config.webSearch.headers.*",
640+
"secretShape": "secret_input",
641+
"optIn": true
642+
},
636643
{
637644
"id": "plugins.entries.minimax.config.webSearch.apiKey",
638645
"configFile": "openclaw.json",

‎docs/tools/gemini-search.md‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ read_when:
44
- You want to use Gemini for web_search
55
- You need a GEMINI_API_KEY or models.providers.google.apiKey
66
- You want Google Search grounding
7+
- Your Gemini gateway requires request headers
78
title: "Gemini search"
89
---
910

@@ -41,6 +42,14 @@ citations.
4142
webSearch: {
4243
apiKey: "AIza...", // optional if GEMINI_API_KEY or models.providers.google.apiKey is set
4344
baseUrl: "https://generativelanguage.googleapis.com/v1beta", // optional; falls back to models.providers.google.baseUrl
45+
headers: {
46+
"X-Routing-Target": "staging",
47+
"X-Gateway-Token": {
48+
source: "env",
49+
provider: "default",
50+
id: "GEMINI_GATEWAY_TOKEN",
51+
},
52+
},
4453
model: "gemini-2.5-flash", // default
4554
},
4655
},
@@ -65,6 +74,30 @@ then `models.providers.google.apiKey`. For base URLs, the dedicated
6574

6675
For a gateway install, put env keys in `~/.openclaw/.env`.
6776

77+
### Request headers
78+
79+
Set `plugins.entries.google.config.webSearch.headers` when an operator gateway
80+
needs extra request metadata. Plain string values use normal config handling;
81+
they are not automatically treated as secret merely because they are headers.
82+
When a header contains a secret, use a [SecretRef](/gateway/secrets) value as
83+
shown above. OpenClaw resolves that value at runtime and applies the existing
84+
secret redaction path to it.
85+
86+
The Gemini request keeps ownership of `Content-Type`, `x-goog-api-key`, and
87+
`x-goog-api-client`; those values override same-named configured headers.
88+
`models.providers.google.headers` are not inherited because they belong to the
89+
model provider endpoint, which can differ from the web-search endpoint.
90+
91+
Empty plain-string values are valid. Invalid fields and transport-owned or
92+
framing names such as `Content-Length`, `Host`, and `Transfer-Encoding` fail the
93+
current search before cache lookup or network I/O.
94+
95+
Effective header names and values partition the in-memory search cache through a
96+
digest, so two routing targets do not share results. Configured values for the
97+
provider-owned names above are ignored and do not partition the cache. On a
98+
cross-origin redirect, the guarded fetch path retains only its standard safe
99+
redirect headers.
100+
68101
## How it works
69102

70103
Unlike traditional search providers that return a list of links and snippets,

‎extensions/google/manifest.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
// Google tests cover manifest plugin behavior.
22
import { readFileSync } from "node:fs";
3+
import { buildJsonPluginConfigSchema } from "openclaw/plugin-sdk/core";
4+
import type { JsonSchemaObject } from "openclaw/plugin-sdk/json-schema-runtime";
35
import { describe, expect, it } from "vitest";
46

57
type GoogleManifest = {
@@ -25,6 +27,13 @@ type GoogleManifest = {
2527
reason?: string;
2628
}>;
2729
};
30+
configSchema?: JsonSchemaObject;
31+
configContracts?: {
32+
secretInputs?: {
33+
paths?: Array<{ path?: string; expected?: string }>;
34+
};
35+
};
36+
uiHints?: Record<string, { sensitive?: boolean }>;
2837
};
2938

3039
const RETIRED_GEMINI_CHAT_MODELS = [
@@ -128,3 +137,45 @@ describe("google manifest model catalog", () => {
128137
}
129138
});
130139
});
140+
141+
describe("google manifest webSearch headers", () => {
142+
function validateWebSearchConfig(webSearch: unknown): { success: boolean } {
143+
const schema = loadManifest().configSchema;
144+
if (!schema) {
145+
throw new Error("expected google manifest configSchema");
146+
}
147+
const safeParse = buildJsonPluginConfigSchema(schema).safeParse;
148+
if (!safeParse) {
149+
throw new Error("expected a safeParse validator for the google config schema");
150+
}
151+
return safeParse({ webSearch });
152+
}
153+
154+
it("accepts plain and SecretRef header values", () => {
155+
expect(validateWebSearchConfig({ headers: { "X-Routing-Target": "staging" } }).success).toBe(
156+
true,
157+
);
158+
expect(
159+
validateWebSearchConfig({
160+
headers: {
161+
"X-Gateway-Token": {
162+
source: "env",
163+
provider: "default",
164+
id: "GEMINI_GATEWAY_TOKEN",
165+
},
166+
},
167+
}).success,
168+
).toBe(true);
169+
expect(validateWebSearchConfig({ headers: { "X-Retry-Count": 3 } }).success).toBe(false);
170+
});
171+
172+
it("uses the existing SecretRef contract without classifying plain headers as sensitive", () => {
173+
const manifest = loadManifest();
174+
expect(manifest.configContracts?.secretInputs?.paths).toContainEqual({
175+
path: "webSearch.headers.*",
176+
expected: "string",
177+
});
178+
expect(manifest.uiHints?.["webSearch.headers"]?.sensitive).not.toBe(true);
179+
expect(manifest.uiHints?.["webSearch.headers.*"]?.sensitive).not.toBe(true);
180+
});
181+
});

‎extensions/google/openclaw.plugin.json‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,16 @@
718718
"webSearch.baseUrl": {
719719
"label": "Gemini Search Base URL",
720720
"help": "Optional Gemini API base URL for web search grounding proxies."
721+
},
722+
"webSearch.headers": {
723+
"label": "Gemini Search Headers",
724+
"help": "Optional headers merged into Gemini web search requests. Use a SecretRef value when a header contains a secret.",
725+
"advanced": true
726+
}
727+
},
728+
"configContracts": {
729+
"secretInputs": {
730+
"paths": [{ "path": "webSearch.headers.*", "expected": "string" }]
721731
}
722732
},
723733
"contracts": {
@@ -763,6 +773,12 @@
763773
},
764774
"baseUrl": {
765775
"type": "string"
776+
},
777+
"headers": {
778+
"type": "object",
779+
"additionalProperties": {
780+
"type": ["string", "object"]
781+
}
766782
}
767783
}
768784
}

‎extensions/google/src/gemini-web-search-provider.runtime.ts‎

Lines changed: 105 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Google provider module implements model/runtime integration.
2+
import { createHash } from "node:crypto";
23
import {
34
createProviderHttpError,
45
formatProviderHttpErrorMessage,
@@ -24,6 +25,7 @@ import {
2425
wrapWebContent,
2526
writeCachedSearchPayload,
2627
} from "openclaw/plugin-sdk/provider-web-search";
28+
import { normalizeResolvedSecretInputString } from "openclaw/plugin-sdk/secret-input-runtime";
2729
import { isRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
2830
import { resolveGoogleApiClientHeaders } from "../google-api-client-header.js";
2931
import {
@@ -63,6 +65,28 @@ type GeminiGroundingResponse = {
6365
};
6466
};
6567

68+
const GEMINI_PROVIDER_OWNED_HEADER_NAMES = new Set([
69+
"content-type",
70+
"x-goog-api-client",
71+
"x-goog-api-key",
72+
]);
73+
74+
// Headers validates field syntax, but Undici does not implement Fetch's
75+
// forbidden-request-header checks. These names can otherwise be consumed,
76+
// ignored, or rejected only after the request reaches the transport.
77+
const GEMINI_UNSAFE_REQUEST_HEADER_NAMES = new Set([
78+
"connection",
79+
"content-length",
80+
"expect",
81+
"host",
82+
"keep-alive",
83+
"proxy-connection",
84+
"te",
85+
"trailer",
86+
"transfer-encoding",
87+
"upgrade",
88+
]);
89+
6690
function throwMalformedGeminiResponse(): never {
6791
throw new Error("Gemini API error: malformed JSON response");
6892
}
@@ -178,6 +202,69 @@ function resolveGeminiRuntimeApiKey(gemini?: GeminiConfig): string | undefined {
178202
);
179203
}
180204

205+
function resolveGeminiWebSearchHeaders(gemini?: GeminiConfig): Record<string, string> | undefined {
206+
if (!isRecord(gemini?.headers)) {
207+
return undefined;
208+
}
209+
const headers = new Headers();
210+
for (const [name, input] of Object.entries(gemini.headers)) {
211+
const path = `plugins.entries.google.config.webSearch.headers[${JSON.stringify(name)}]`;
212+
const value =
213+
typeof input === "string"
214+
? input
215+
: normalizeResolvedSecretInputString({ value: input, path });
216+
if (value === undefined) {
217+
throw new Error(`${path} must be a string or resolved SecretRef.`);
218+
}
219+
let normalizedName: string;
220+
let normalizedValue: string;
221+
try {
222+
const candidate = new Headers([[name, value]]);
223+
const [entry] = candidate.entries();
224+
if (!entry) {
225+
throw new Error("missing normalized header entry");
226+
}
227+
[normalizedName, normalizedValue] = entry;
228+
} catch {
229+
throw new Error(`${path} is not a valid HTTP header.`);
230+
}
231+
if (GEMINI_UNSAFE_REQUEST_HEADER_NAMES.has(normalizedName)) {
232+
throw new Error(`${path} uses a reserved or framing HTTP header.`);
233+
}
234+
if (GEMINI_PROVIDER_OWNED_HEADER_NAMES.has(normalizedName)) {
235+
continue;
236+
}
237+
headers.set(normalizedName, normalizedValue);
238+
}
239+
const entries = [...headers.entries()];
240+
return entries.length > 0 ? Object.fromEntries(entries) : undefined;
241+
}
242+
243+
function buildGeminiRequestHeaders(params: {
244+
apiKey: string;
245+
baseUrl: string;
246+
operatorHeaders?: Record<string, string>;
247+
}): HeadersInit {
248+
const providerHeaders = {
249+
"Content-Type": "application/json",
250+
"x-goog-api-key": params.apiKey,
251+
...resolveGoogleApiClientHeaders({
252+
baseUrl: params.baseUrl,
253+
api: "google-generative-ai",
254+
capability: "other",
255+
transport: "http",
256+
}),
257+
};
258+
if (!params.operatorHeaders) {
259+
return providerHeaders;
260+
}
261+
const headers = new Headers(params.operatorHeaders);
262+
for (const [name, value] of Object.entries(providerHeaders)) {
263+
headers.set(name, value);
264+
}
265+
return headers;
266+
}
267+
181268
async function runGeminiSearch(params: {
182269
query: string;
183270
apiKey: string;
@@ -186,6 +273,7 @@ async function runGeminiSearch(params: {
186273
timeoutSeconds: number;
187274
signal?: AbortSignal;
188275
timeRangeFilter?: GeminiTimeRangeFilter;
276+
headers?: Record<string, string>;
189277
}): Promise<{ content: string; citations: Array<{ url: string; title?: string }> }> {
190278
const endpoint = `${params.baseUrl}/models/${params.model}:generateContent`;
191279
const googleSearch =
@@ -198,16 +286,11 @@ async function runGeminiSearch(params: {
198286
signal: params.signal,
199287
init: {
200288
method: "POST",
201-
headers: {
202-
"Content-Type": "application/json",
203-
"x-goog-api-key": params.apiKey,
204-
...resolveGoogleApiClientHeaders({
205-
baseUrl: params.baseUrl,
206-
api: "google-generative-ai",
207-
capability: "other",
208-
transport: "http",
209-
}),
210-
},
289+
headers: buildGeminiRequestHeaders({
290+
apiKey: params.apiKey,
291+
baseUrl: params.baseUrl,
292+
operatorHeaders: params.headers,
293+
}),
211294
body: JSON.stringify({
212295
contents: [{ parts: [{ text: params.query }] }],
213296
tools: [{ google_search: googleSearch }],
@@ -338,6 +421,16 @@ export async function executeGeminiSearch(
338421
undefined;
339422
const model = resolveGeminiModel(geminiConfig);
340423
const baseUrl = resolveGeminiBaseUrl(geminiConfig);
424+
const headers = resolveGeminiWebSearchHeaders(geminiConfig);
425+
const headersCacheKey = headers
426+
? createHash("sha256")
427+
.update(
428+
JSON.stringify(
429+
Object.entries(headers).toSorted(([left], [right]) => left.localeCompare(right)),
430+
),
431+
)
432+
.digest("hex")
433+
: undefined;
341434
const cacheKey = buildSearchCacheKey([
342435
"gemini",
343436
query,
@@ -347,6 +440,7 @@ export async function executeGeminiSearch(
347440
timeRange.freshness,
348441
timeRange.timeRangeFilter?.startTime,
349442
timeRange.timeRangeFilter?.endTime,
443+
headersCacheKey,
350444
]);
351445
const cached = readCachedSearchPayload(cacheKey);
352446
if (cached) {
@@ -362,6 +456,7 @@ export async function executeGeminiSearch(
362456
timeoutSeconds: resolveSearchTimeoutSeconds(searchConfig),
363457
signal: context?.signal,
364458
timeRangeFilter: timeRange.timeRangeFilter,
459+
headers,
365460
});
366461
const payload = {
367462
query,

‎extensions/google/src/gemini-web-search-provider.shared.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const DEFAULT_GEMINI_WEB_SEARCH_MODEL = "gemini-2.5-flash";
1010
export type GeminiConfig = {
1111
apiKey?: unknown;
1212
baseUrl?: unknown;
13+
headers?: unknown;
1314
model?: unknown;
1415
providerApiKey?: unknown;
1516
providerBaseUrl?: unknown;

‎extensions/google/src/gemini-web-search-provider.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ function withGoogleModelProviderFallbacks(
9797
if (provider.baseUrl !== undefined) {
9898
gemini.providerBaseUrl = provider.baseUrl;
9999
}
100+
// Provider headers stay scoped to the provider base URL. Web-search headers
101+
// are configured explicitly under the Google plugin for its own endpoint.
100102
Object.defineProperty(mergedSearchConfig, "gemini", {
101103
value: gemini,
102104
enumerable: geminiDescriptor?.enumerable ?? false,

0 commit comments

Comments
 (0)