Skip to content

The agent that grows with you

test(e2e): Gemini native generateContent wire-conformance suite (fake Google TLS endpoint + tools/resume, schema, errors, compaction)

teknium10929292aca12
diff --git a/tests/e2e/core/providers/test_native_gemini_compaction.py b/tests/e2e/core/providers/test_native_gemini_compaction.py
new file mode 100644
index 00000000000..a5c3b93abfb
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_gemini_compaction.py
@@ -0,0 +1,134 @@
+"""Gemini native wire conformance: auto-compaction inside a thought-signature session.
+
+Turn 1 (process A) reads two bulky files (two signed functionCall steps) and answers. Turn 2
+(process B, ``--resume``) reads a third file; that response reports a huge ``promptTokenCount``, so
+Hermes compacts mid-turn (tiny ``compression.threshold_tokens``) before the next step, then the
+model makes one more signed call and answers.
+
+The fake validates every request like Google: roles alternate, every functionResponse follows
+its functionCall (count / name / id), and each functionCall step of the current turn carries a
+signature Google issued. The tests additionally require that compaction really happened on the
+wire and that every functionCall that survives it still carries its own signature verbatim.
+"""
+
+from __future__ import annotations
+
+import json
+import random
+from dataclasses import dataclass
+
+import pytest
+
+from tests.e2e.core.providers import _native_helpers as nh
+from tests.fakes.providers.gemini_native import (
+ HERMES_ENV,
+ Call,
+ Calls,
+ GeminiFake,
+ Recorded,
+ Text,
+ hermes_model,
+)
+
+SUMMARY_MARK = "GEMINI-SUMMARY-CHECKPOINT"
+ANSWER_1 = "Turn one answer GEMINI-CMP-ONE"
+ANSWER_2 = "Turn two answer GEMINI-CMP-TWO"
+ECHO = "GEMINI-CMP-ECHO-3391"
+BIG_PROMPT = 50_000 # far above threshold_tokens below: compaction must fire
+
+SUMMARY = (f"## Goal\nKeep helping with the files ({SUMMARY_MARK}).\n## Progress\n### Done\n"
+ "- Read big1.txt and big2.txt.\n## Next Steps\n- Continue with big3.txt.\n")
+
+
+def _summary_route(rec: Recorded) -> Text | None:
+ """The compaction summariser call is the one generate call that declares no tools."""
+ return None if (rec.body or {}).get("tools") else Text(SUMMARY, signed=False)
+
+
+@dataclass
+class Run:
+ home: nh.NativeHome
+ fake: GeminiFake
+ turns: list[nh.ChatResult]
+
+ def calls(self) -> list[Recorded]:
+ return self.fake.generate_calls()
+
+ def split(self) -> tuple[Recorded, Recorded, list[Recorded]]:
+ """(last main request before the summary, first after it, every main request after it)."""
+ calls = self.calls()
+ idx = next((i for i, c in enumerate(calls) if c.reply.startswith("route:")), None)
+ assert idx is not None, f"no compaction summary request reached Google: {[c.reply for c in calls]}"
+ before = [c for c in calls[:idx] if c.reply.startswith("script:")]
+ after = [c for c in calls[idx + 1:] if c.reply.startswith("script:")]
+ assert before and after, [c.reply for c in calls]
+ return before[-1], after[0], after
+
+
[email protected](scope="module")
+def run(tmp_path_factory: pytest.TempPathFactory) -> Run:
+ root = tmp_path_factory.mktemp("gemini_compaction")
+ home = nh.make_home(root, hermes_model(context_length=64_000), env_file=HERMES_ENV,
+ extra_config={"compression": {"threshold_tokens": 12_000, "protect_last_n": 4}})
+ rng = random.Random(7)
+ words = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima mike oscar".split()
+ paths = []
+ for i in range(1, 4):
+ path = home.project / f"big{i}.txt"
+ lines = [" ".join(rng.choice(words) for _ in range(14)) for _ in range(260)]
+ path.write_text("\n".join(lines) + f"\nBIG-END-{i}\n", encoding="utf-8")
+ paths.append(str(path))
+ script = [
+ Calls([Call("read_file", {"path": paths[0]})]),
+ Calls([Call("read_file", {"path": paths[1]})]),
+ Text(ANSWER_1),
+ Calls([Call("read_file", {"path": paths[2]})], prompt_tokens=BIG_PROMPT),
+ Calls([Call("terminal", {"command": f"echo {ECHO}"})], prompt_tokens=BIG_PROMPT),
+ Text(ANSWER_2, prompt_tokens=3_000),
+ ]
+ with GeminiFake(root / "fake", script, route=_summary_route) as fake:
+ first = nh.run_chat(home, "Read big1.txt and big2.txt.", env=fake.child_env())
+ assert first.returncode == 0, first.describe()
+ second = nh.run_chat(home, "Now read big3.txt, then echo the marker.", env=fake.child_env(),
+ resume=nh.latest_session(home))
+ assert second.returncode == 0, second.describe()
+ return Run(home, fake, [first, second])
+
+
+def test_compaction_happens_on_the_wire(run: Run) -> None:
+ before, after, _ = run.split()
+ # Without compaction the next request = previous request + (functionCall, functionResponse).
+ assert len(after.contents) < len(before.contents) + 2, (len(before.contents), len(after.contents))
+ assert SUMMARY_MARK in after.all_text(), "compaction summary never reached the next request"
+ assert ANSWER_2 in run.turns[1].stdout, run.turns[1].describe()
+
+
+def test_post_compaction_requests_are_valid_and_signed(run: Run) -> None:
+ """No request (before or after compaction) was rejected, and every functionCall still on the
+ wire after compaction carries the exact signature Google minted for that call id."""
+ assert run.fake.rejections() == [], run.fake.rejections()
+ _, _, after = run.split()
+ issued = run.fake.call_signatures
+ for rec in after:
+ call_ids = {p["functionCall"].get("id") for p in rec.parts("functionCall")}
+ for part in rec.parts("functionCall"):
+ cid = part["functionCall"].get("id")
+ assert cid in issued, f"functionCall id {cid!r} was never issued by Google"
+ assert part.get("thoughtSignature") == issued[cid], f"signature for {cid} lost/altered: {part}"
+ for part in rec.parts("functionResponse"):
+ assert part["functionResponse"].get("id") in call_ids, f"orphan functionResponse: {part}"
+ last = after[-1]
+ echoed = [p["functionResponse"] for p in last.parts("functionResponse")]
+ assert any(ECHO in json.dumps(r["response"]) for r in echoed), echoed
+
+
+def test_persisted_transcript_keeps_pairs_and_signatures(run: Run) -> None:
+ rows = nh.messages(run.home) # active rows across the (possibly split) session lineage
+ open_ids: set[str] = set()
+ for row in rows:
+ for tc in nh.tool_calls_of(row) if row["role"] == "assistant" else []:
+ open_ids.add(str(tc.get("id")))
+ if row["role"] == "tool":
+ assert row.get("tool_call_id") in open_ids, f"orphan tool row {row.get('tool_call_id')}"
+ nh.assert_no_duplicate_assistant_text(rows, ANSWER_2)
+ assert any(ANSWER_2 in (r.get("content") or "") for r in rows if r["role"] == "assistant")
diff --git a/tests/e2e/core/providers/test_native_gemini_errors.py b/tests/e2e/core/providers/test_native_gemini_errors.py
new file mode 100644
index 00000000000..4f8e97506d8
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_gemini_errors.py
@@ -0,0 +1,155 @@
+"""Gemini native wire conformance: documented errors, blocked candidates and a mid-stream drop.
+
+Each scenario is one real ``hermes chat -q`` turn against the fake Google endpoint
+(``tests/fakes/providers/gemini_native.py``); the scenarios are independent and run concurrently.
+
+* retryable (429 ``RESOURCE_EXHAUSTED`` with ``RetryInfo``, 503 ``UNAVAILABLE``): retried, then the
+ answer is printed and persisted once;
+* terminal (400 ``INVALID_ARGUMENT``, candidate ``finishReason`` ``SAFETY`` / ``RECITATION``, a prompt
+ blocked through ``promptFeedback.blockReason``): exactly one request, surfaced once, no fake
+ success persisted;
+* a TLS connection dropped mid-SSE: recovered with no partial/duplicated assistant row.
+"""
+
+from __future__ import annotations
+
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from tests.e2e.core.providers import _native_helpers as nh
+from tests.fakes.providers.gemini_native import (
+ HERMES_ENV,
+ Blocked,
+ Drop,
+ GeminiFake,
+ GoogleError,
+ Recorded,
+ Reply,
+ Responder,
+ Text,
+ hermes_model,
+)
+
+KNOWN = {
+ "prompt_blocked": "#121317 promptFeedback.blockReason is retried 9x as an empty stream and reported as "
+ "'temporarily unavailable'",
+}
+
+NEVER = "GEMINI-MUST-NOT-BE-SHOWN"
+QUOTA = "Resource has been exhausted (e.g. check quota)."
+PARTIAL = "GEMINI-PARTIAL-DROPPED "
+
+
+@dataclass
+class Case:
+ script: list[Reply]
+ route: Responder | None = None
+ max_retries: int = 2
+
+
+CASES: dict[str, Case] = {
+ "rate_limited_429": Case([GoogleError(429, "RESOURCE_EXHAUSTED", QUOTA, 1),
+ GoogleError(429, "RESOURCE_EXHAUSTED", QUOTA, 1),
+ Text("GEMINI-RECOVERED-429")], max_retries=3),
+ "unavailable_503": Case([GoogleError(503, "UNAVAILABLE", "The model is overloaded. Please try again later."),
+ Text("GEMINI-RECOVERED-503")]),
+ "invalid_argument_400": Case([GoogleError(400, "INVALID_ARGUMENT", "Request contains an invalid argument. "
+ "GEMINI-MARK-400"), Text(NEVER)]),
+ "safety": Case([Blocked("SAFETY"), Text(NEVER)]),
+ "recitation": Case([Blocked("RECITATION"), Text(NEVER)]),
+ # Google blocks the same prompt every time: answer every attempt with the block.
+ "prompt_blocked": Case([], route=lambda rec: Blocked("SAFETY", prompt=True), max_retries=3),
+ "stream_drop": Case([Drop(PARTIAL), Text("GEMINI-FULL-AFTER-DROP")]),
+}
+
+
+@dataclass
+class Outcome:
+ result: nh.ChatResult
+ calls: list[Recorded]
+ rows: list[dict]
+
+ @property
+ def output(self) -> str:
+ return self.result.stdout + self.result.stderr
+
+ def describe(self) -> str:
+ return f"{self.result.describe()}\ncalls={[(c.reply, c.status) for c in self.calls]}"
+
+
+def _run(root: Path, name: str, case: Case) -> Outcome:
+ home = nh.make_home(root / name, hermes_model(), env_file=HERMES_ENV,
+ extra_config={"agent": {"api_max_retries": case.max_retries}})
+ with GeminiFake(root / name / "fake", case.script, route=case.route) as fake:
+ result = nh.run_chat(home, f"Say hello ({name}).", env=fake.child_env())
+ calls = fake.generate_calls()
+ return Outcome(result, calls, nh.messages(home))
+
+
[email protected](scope="module")
+def outcomes(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Outcome]:
+ base = tmp_path_factory.mktemp("gemini_errors")
+ with ThreadPoolExecutor(len(CASES)) as pool:
+ futures = {name: pool.submit(_run, base, name, case) for name, case in CASES.items()}
+ return {name: f.result() for name, f in futures.items()}
+
+
+def _answer_once(o: Outcome, answer: str) -> None:
+ assert o.result.returncode == 0, o.describe()
+ assert o.result.stdout.count(answer) == 1, o.describe()
+ assistant = [r for r in o.rows if r["role"] == "assistant" and r.get("content")]
+ assert [r["content"] for r in assistant] == [answer], assistant
+
+
+RETRYABLE = { # case -> (statuses the fake must have served, in order; the answer)
+ "rate_limited_429": ([429, 429, 200], "GEMINI-RECOVERED-429"),
+ "unavailable_503": ([503, 200], "GEMINI-RECOVERED-503"),
+}
+
+
[email protected]("name", list(RETRYABLE))
+def test_retryable_error_is_retried_then_succeeds(outcomes: dict[str, Outcome], name: str) -> None:
+ o = outcomes[name]
+ statuses, answer = RETRYABLE[name]
+ assert [c.status for c in o.calls] == statuses, o.describe()
+ _answer_once(o, answer)
+
+
+TERMINAL = { # case -> a word the surfaced error must carry (None: any visible error)
+ "invalid_argument_400": "GEMINI-MARK-400",
+ "safety": "safety",
+ "recitation": None,
+ "prompt_blocked": "block",
+}
+
+
+def _terminal_param(name: str):
+ marks = [pytest.mark.xfail(strict=True, reason=KNOWN[name])] if name in KNOWN else []
+ return pytest.param(name, marks=marks, id=name)
+
+
[email protected]("name", [_terminal_param(n) for n in TERMINAL])
+def test_non_retryable_surfaced_once(outcomes: dict[str, Outcome], name: str) -> None:
+ o = outcomes[name]
+ assert len(o.calls) == 1, f"terminal Google response was re-sent {len(o.calls)}x\n{o.describe()}"
+ assert o.result.returncode != 0, o.describe()
+ word = TERMINAL[name]
+ lines = [ln.strip() for ln in o.result.stdout.splitlines() if ln.strip()]
+ assert lines, f"nothing surfaced to the user\n{o.describe()}"
+ assert len(lines) == len(set(lines)), f"error surfaced more than once\n{o.describe()}"
+ if word:
+ assert word.lower() in o.output.lower(), o.describe()
+ assert NEVER not in o.output
+ assert not [r for r in o.rows if r["role"] == "assistant" and NEVER in (r.get("content") or "")]
+
+
+def test_stream_drop_recovers_without_duplicate_rows(outcomes: dict[str, Outcome]) -> None:
+ o = outcomes["stream_drop"]
+ assert [c.reply for c in o.calls] == ["script:Drop", "script:Text"], o.describe()
+ assert all(c.stream for c in o.calls)
+ _answer_once(o, "GEMINI-FULL-AFTER-DROP")
+ assert not [r for r in o.rows if PARTIAL.strip() in (r.get("content") or "")], o.rows
+ nh.assert_no_duplicate_assistant_text(o.rows, "GEMINI-FULL-AFTER-DROP")
diff --git a/tests/e2e/core/providers/test_native_gemini_schema.py b/tests/e2e/core/providers/test_native_gemini_schema.py
new file mode 100644
index 00000000000..3ec97ec9e74
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_gemini_schema.py
@@ -0,0 +1,183 @@
+"""Gemini native wire conformance: MCP tool schemas Google's parser rejects arrive sanitized.
+
+An MCP server (a tiny stdio JSON-RPC process) exposes one tool whose ``inputSchema`` uses JSON
+Schema keywords that Google's ``FunctionDeclaration`` parser does not accept (``$schema``,
+``$ref``/``$defs``, ``additionalProperties``, ``oneOf``, ``const``, list-valued ``type``, integer
+``enum``, a ``required`` entry naming no property). A real ``hermes chat -q`` turn declares it to
+the fake Google endpoint, which rejects anything Google would (HTTP 400 INVALID_ARGUMENT) and
+then drives a call to the tool so the round trip is proven end to end.
+
+Two API surfaces: ``v1beta`` (default; ``parametersJsonSchema``) and ``v1`` (pinned through
+``model.base_url``; the proto ``Schema`` subset in ``parameters``, validated field by field).
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import textwrap
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from tests.e2e.core.providers import _native_helpers as nh
+from tests.fakes.providers.gemini_native import HERMES_ENV, Call, Calls, GeminiFake, Recorded, Text, hermes_model
+
+KNOWN = {
+ "ref_dropped_v1": "#99438 legacy `parameters` path drops $ref/$defs instead of inlining (empty schema)",
+ "array_items_v1": "#71804 array parameter without `items` is sent as-is; Google 400s 'items: missing field'",
+}
+
+TOOL = "mcp__hostile__lookup"
+MCP_CANARY = "GEMINI-MCP-CANARY-7731"
+DONE = "GEMINI-MCP-DONE"
+V1 = "https://generativelanguage.googleapis.com/v1"
+_FORBIDDEN_ANYWHERE = ("$ref", "$schema", "$defs")
+
+HOSTILE: dict[str, Any] = {
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "type": "object",
+ "additionalProperties": False,
+ "$defs": {"Mode": {"type": "string", "enum": ["fast", "slow"]}},
+ "properties": {
+ "query": {"type": "string", "minLength": 1, "examples": ["x"]},
+ "mode": {"$ref": "#/$defs/Mode"},
+ "limit": {"type": ["integer", "null"], "exclusiveMinimum": 0, "enum": [1, 5, 10]},
+ "filters": {"type": "array", "items": {"oneOf": [
+ {"type": "string"},
+ {"type": "object", "properties": {"k": {"type": "string"}}, "additionalProperties": False}]}},
+ "flag": {"const": True},
+ },
+ "required": ["query", "not_a_property"],
+}
+ITEMLESS: dict[str, Any] = {"type": "object", "properties": {"tags": {"type": "array", "description": "tags"}}}
+
+_MCP_SERVER = textwrap.dedent('''
+ import json, sys
+ TOOLS = json.loads(sys.argv[1])
+ CANARY = sys.argv[2]
+ for line in sys.stdin:
+ msg = json.loads(line)
+ mid, method = msg.get("id"), msg.get("method")
+ if mid is None:
+ continue
+ if method == "initialize":
+ res = {"protocolVersion": msg["params"].get("protocolVersion", "2025-06-18"),
+ "capabilities": {"tools": {}}, "serverInfo": {"name": "hostile", "version": "1"}}
+ elif method == "tools/list":
+ res = {"tools": TOOLS}
+ elif method == "tools/call":
+ args = msg["params"].get("arguments") or {}
+ res = {"content": [{"type": "text", "text": CANARY + " query=" + str(args.get("query"))}]}
+ elif method == "ping":
+ res = {}
+ else:
+ err = {"code": -32601, "message": "method not found: " + str(method)}
+ print(json.dumps({"jsonrpc": "2.0", "id": mid, "error": err}), flush=True)
+ continue
+ print(json.dumps({"jsonrpc": "2.0", "id": mid, "result": res}), flush=True)
+''')
+
+
+@dataclass
+class Outcome:
+ result: nh.ChatResult
+ calls: list[Recorded]
+ rejections: list[str]
+
+ def declaration(self) -> dict[str, Any]:
+ assert self.calls, self.result.describe()
+ decl = self.calls[0].declarations().get(TOOL)
+ assert decl is not None, f"{TOOL} not declared: {sorted(self.calls[0].declarations())}"
+ return decl
+
+ def function_responses(self) -> list[dict[str, Any]]:
+ return [p["functionResponse"] for rec in self.calls for p in rec.parts("functionResponse")]
+
+
+def _scenario(root: Path, schema: dict[str, Any], base_url: str | None) -> Outcome:
+ root.mkdir(parents=True)
+ server = root / "hostile_mcp.py"
+ server.write_text(_MCP_SERVER, encoding="utf-8")
+ tools = [{"name": "lookup", "description": "Look something up.", "inputSchema": schema}]
+ extra = {
+ # Keep the MCP tool in the model-facing array (not behind the tool_search bridge) and let
+ # discovery finish before the one-shot turn is built.
+ "tools": {"tool_search": {"enabled": "off"}},
+ "mcp_discovery_timeout": 60,
+ "mcp_single_query_discovery_timeout": 60,
+ "mcp_servers": {"hostile": {"command": sys.executable,
+ "args": [str(server), json.dumps(tools), MCP_CANARY]}},
+ }
+ home = nh.make_home(root, hermes_model(base_url), env_file=HERMES_ENV, extra_config=extra)
+ script = [Calls([Call(TOOL, {"query": "q1", "mode": "fast"})]), Text(DONE)]
+ with GeminiFake(root / "fake", script) as fake:
+ result = nh.run_chat(home, "Use the lookup tool for q1.", env=fake.child_env())
+ return Outcome(result, fake.generate_calls(), fake.rejections())
+
+
+SCENARIOS = {"v1beta": (HOSTILE, None), "v1": (HOSTILE, V1), "v1_itemless": (ITEMLESS, V1)}
+
+
[email protected](scope="module")
+def outcomes(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Outcome]:
+ base = tmp_path_factory.mktemp("gemini_schema")
+ with ThreadPoolExecutor(len(SCENARIOS)) as pool:
+ futures = {k: pool.submit(_scenario, base / k, *v) for k, v in SCENARIOS.items()}
+ return {k: f.result() for k, f in futures.items()}
+
+
+def _assert_round_trip(o: Outcome, version: str) -> None:
+ assert o.rejections == [], o.rejections
+ assert [c.version for c in o.calls] == [version, version], [(c.version, c.status) for c in o.calls]
+ responses = [r for r in o.function_responses() if r.get("name") == TOOL]
+ assert responses and MCP_CANARY in json.dumps(responses[0]["response"]), o.function_responses()
+ assert f"{MCP_CANARY} query=q1" in json.dumps(responses[0]["response"]), responses[0]
+ assert o.result.returncode == 0 and DONE in o.result.stdout, o.result.describe()
+
+
+def _walk(node: Any):
+ if isinstance(node, dict):
+ yield node
+ for v in node.values():
+ yield from _walk(v)
+ elif isinstance(node, list):
+ for v in node:
+ yield from _walk(v)
+
+
+def test_v1beta_json_schema_declaration_is_sanitized(outcomes: dict[str, Outcome]) -> None:
+ o = outcomes["v1beta"]
+ _assert_round_trip(o, "v1beta")
+ schema = o.declaration().get("parametersJsonSchema")
+ assert isinstance(schema, dict), o.declaration()
+ leaked = [k for node in _walk(schema) for k in node if k in _FORBIDDEN_ANYWHERE]
+ assert leaked == [], f"reference/meta keywords reached Google: {leaked} in {schema}"
+ assert schema["properties"]["mode"].get("enum") == ["fast", "slow"], schema["properties"]["mode"]
+ assert set(schema.get("required") or []) <= set(schema["properties"]), schema.get("required")
+
+
+def test_v1_proto_schema_declaration_is_accepted(outcomes: dict[str, Outcome]) -> None:
+ """Every field of ``parameters`` parses as Google's proto ``Schema`` (the fake 400s otherwise)."""
+ o = outcomes["v1"]
+ _assert_round_trip(o, "v1")
+ params = o.declaration().get("parameters")
+ assert isinstance(params, dict) and "parametersJsonSchema" not in o.declaration(), o.declaration()
+ assert params["required"] == ["query"], params
+
+
[email protected](strict=True, reason=KNOWN["ref_dropped_v1"])
+def test_v1_ref_parameter_keeps_its_shape(outcomes: dict[str, Outcome]) -> None:
+ params = outcomes["v1"].declaration()["parameters"]
+ assert params["properties"]["mode"].get("enum") == ["fast", "slow"], (
+ f"$ref-typed parameter lost its shape on the v1 wire: {params['properties']['mode']}")
+
+
[email protected](strict=True, reason=KNOWN["array_items_v1"])
+def test_v1_array_without_items_is_accepted(outcomes: dict[str, Outcome]) -> None:
+ o = outcomes["v1_itemless"]
+ assert not any("items: missing field" in r for r in o.rejections), o.rejections
+ _assert_round_trip(o, "v1")
diff --git a/tests/e2e/core/providers/test_native_gemini_tools.py b/tests/e2e/core/providers/test_native_gemini_tools.py
new file mode 100644
index 00000000000..e08bc67b5c5
--- /dev/null
+++ b/tests/e2e/core/providers/test_native_gemini_tools.py
@@ -0,0 +1,119 @@
+"""Gemini native wire conformance: the tool loop and thought-signature replay across ``--resume``.
+
+Real ``hermes chat -q`` subprocesses talk to Google AI Studio's native ``streamGenerateContent``
+dialect; only the vendor is faked (``tests/fakes/providers/gemini_native.py``, a TLS-terminating
+loopback proxy that validates every request like Google and rejects it with a 400 when it would).
+
+Turn 1 (process A): the model calls ``read_file`` on a seeded file, then answers.
+Turn 2 (process B, ``--resume``): the model calls ``terminal``, then answers.
+Gemini 3 needs the ``thoughtSignature`` of every functionCall step sent back verbatim; the fake
+enforces it for the current turn and the tests assert it for the resumed (previous-turn) history.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+
+import pytest
+
+from tests.e2e.core.providers import _native_helpers as nh
+from tests.fakes.providers.gemini_native import HERMES_ENV, Call, Calls, GeminiFake, Recorded, Text, hermes_model
+
+SEED = "GEMINI-SEED-CANARY-5521"
+ECHO = "GEMINI-RESUME-ECHO-8813"
+ANSWER_1 = "Turn one answer GEMINI-ANS-ONE"
+ANSWER_2 = "Turn two answer GEMINI-ANS-TWO"
+
+
+@dataclass
+class Run:
+ home: nh.NativeHome
+ fake: GeminiFake
+ turns: list[nh.ChatResult]
+ session_id: str
+
+ def main(self) -> list[Recorded]:
+ return self.fake.main_calls()
+
+
[email protected](scope="module")
+def run(tmp_path_factory: pytest.TempPathFactory) -> Run:
+ root = tmp_path_factory.mktemp("gemini_tools")
+ home = nh.make_home(root, hermes_model(), env_file=HERMES_ENV)
+ seed = home.project / "seed.txt"
+ seed.write_text(f"{SEED}\n", encoding="utf-8")
+ script = [
+ Calls([Call("read_file", {"path": str(seed)})]),
+ Text(ANSWER_1, thought="Summarising the file."),
+ Calls([Call("terminal", {"command": f"echo {ECHO}"})]),
+ Text(ANSWER_2),
+ ]
+ with GeminiFake(root / "fake", script) as fake:
+ first = nh.run_chat(home, "Read seed.txt and tell me what it says.", env=fake.child_env())
+ assert first.returncode == 0, first.describe()
+ sid = nh.latest_session(home)
+ second = nh.run_chat(home, "Now echo the marker in the terminal.", env=fake.child_env(), resume=sid)
+ assert second.returncode == 0, second.describe()
+ return Run(home, fake, [first, second], sid)
+
+
+def _call_parts(rec: Recorded) -> dict[str, dict]:
+ """functionCall id -> the whole Part (so the sibling ``thoughtSignature`` is visible)."""
+ return {p["functionCall"].get("id"): p for p in rec.parts("functionCall")}
+
+
+def _responses(rec: Recorded) -> dict[str, dict]:
+ return {p["functionResponse"].get("id"): p["functionResponse"] for p in rec.parts("functionResponse")}
+
+
+def test_function_call_round_trip_pairs_response_and_persists(run: Run) -> None:
+ """a. functionCall -> real tool -> functionResponse (same name + id) -> final answer printed."""
+ assert run.fake.rejections() == [], run.fake.rejections()
+ main = run.main()
+ assert len(main) == 4, [(r.reply, r.status) for r in main]
+ assert all(r.stream and r.query.get("alt") == ["sse"] for r in main)
+ (call_id,) = list(run.fake.call_signatures)[:1]
+ follow_up = main[1]
+ resp = _responses(follow_up).get(call_id)
+ assert resp is not None, f"no functionResponse for {call_id}: {follow_up.parts('functionResponse')}"
+ assert resp["name"] == "read_file"
+ assert SEED in json.dumps(resp["response"]), resp
+ part = _call_parts(follow_up)[call_id]
+ assert part.get("thoughtSignature") == run.fake.call_signatures[call_id], part
+ assert ANSWER_1 in run.turns[0].stdout, run.turns[0].describe()
+
+ rows = nh.messages(run.home, run.session_id)
+ ids = [tc.get("id") for r in rows if r["role"] == "assistant" for tc in nh.tool_calls_of(r)]
+ assert call_id in ids, ids
+ tool_rows = [r for r in rows if r["role"] == "tool" and r.get("tool_call_id") == call_id]
+ assert len(tool_rows) == 1 and SEED in (tool_rows[0].get("content") or ""), tool_rows
+ nh.assert_no_duplicate_assistant_text(rows, ANSWER_1)
+
+
+def test_resume_replays_thought_signatures_verbatim(run: Run) -> None:
+ """b. After ``--resume`` in a new process, turn 1's functionCall goes back with the exact
+ signature Google issued (not dropped, not a skip-validator dummy), still paired to its result;
+ the resumed turn's own call is signed too (the fake 400s a missing current-turn signature)."""
+ assert run.fake.rejections() == [], run.fake.rejections()
+ first_id, second_id = list(run.fake.call_signatures)
+ resumed = run.main()[2]
+ replayed = _call_parts(resumed).get(first_id)
+ assert replayed is not None, f"turn-1 functionCall {first_id} missing after resume: {resumed.contents}"
+ assert replayed.get("thoughtSignature") == run.fake.call_signatures[first_id], replayed
+ assert SEED in json.dumps(_responses(resumed).get(first_id)), resumed.parts("functionResponse")
+ assert ANSWER_1 in resumed.all_text()
+
+ final = run.main()[3]
+ assert _call_parts(final)[second_id].get("thoughtSignature") == run.fake.call_signatures[second_id]
+ assert ECHO in json.dumps(_responses(final).get(second_id))
+ assert ANSWER_2 in run.turns[1].stdout, run.turns[1].describe()
+ nh.assert_no_duplicate_assistant_text(nh.messages(run.home), ANSWER_2)
+
+
+def test_no_egress_beyond_the_google_host(run: Run) -> None:
+ """Every generate call carried the API key; no other request reached a Google path."""
+ for rec in run.fake.generate_calls():
+ assert rec.headers.get("x-goog-api-key") or rec.query.get("key"), rec.headers
+ other = [r.path for r in run.fake.requests if not r.rpc]
+ assert other == [], other
diff --git a/tests/fakes/providers/gemini_native.py b/tests/fakes/providers/gemini_native.py
new file mode 100644
index 00000000000..33c8575630c
--- /dev/null
+++ b/tests/fakes/providers/gemini_native.py
@@ -0,0 +1,728 @@
+"""Fake Google AI Studio ``generateContent`` / ``streamGenerateContent`` endpoint behind a real
+TLS boundary.
+
+Hermes routes to its native Gemini adapter only for the real Google host
+(``generativelanguage.googleapis.com``), so the fake is reached the way any corporate egress
+proxy would be: an HTTPS ``CONNECT`` proxy on loopback that terminates TLS for the Google host
+with a leaf certificate signed by a throwaway CA. The child trusts that CA through the standard
+``SSL_CERT_FILE`` / ``REQUESTS_CA_BUNDLE`` channel and reaches the proxy through
+``HTTPS_PROXY`` (see :meth:`GeminiFake.child_env`). Every other host is refused and recorded,
+so a test also proves the turn made no other egress.
+
+Requests are validated against the published Gemini API reference (``google.ai.generativelanguage``
+``v1beta`` / ``v1``: ``GenerateContentRequest``, ``Content``, ``Part``, ``Tool``,
+``FunctionDeclaration``, ``Schema``) and rejected the way Google does: HTTP 400 with the
+``{"error": {"code", "message", "status": "INVALID_ARGUMENT"}}`` body. That covers unknown proto
+fields, role alternation, functionCall/functionResponse pairing (count, name, id), the Gemini 3
+thought-signature rule for the current turn, and the OpenAPI ``Schema`` subset of
+``FunctionDeclaration.parameters``. Scripted replies are built from the vendor's
+``GenerateContentResponse`` shape, including fault injection (Google error bodies, blocked
+candidates, a mid-stream connection drop).
+"""
+
+from __future__ import annotations
+
+import base64
+import datetime
+import ipaddress
+import json
+import re
+import secrets
+import socket
+import ssl
+import struct
+import threading
+import time
+from dataclasses import dataclass, field
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any, Callable
+from urllib.parse import parse_qs, urlsplit
+
+GEMINI_HOST = "generativelanguage.googleapis.com"
+MODEL_ID = "gemini-3-flash-preview"
+API_KEY = "AIzaFakeGeminiKeyForHermesE2E0000000000"
+# Documented dummy signatures that tell Gemini 3 to skip thought-signature validation.
+SKIP_SIGNATURES = frozenset({"skip_thought_signature_validator", "context_engineering_is_the_way_to_go"})
+# Hermes-side config for a home that talks to this fake: the user-facing provider id + model and the
+# key in ``.env`` (``model.base_url`` may pin another Google API version, e.g. ``.../v1``).
+HERMES_ENV = {"GEMINI_API_KEY": API_KEY}
+
+
+def hermes_model(base_url: str | None = None, **extra: Any) -> dict[str, Any]:
+ model: dict[str, Any] = {"provider": "gemini", "default": MODEL_ID, **extra}
+ if base_url:
+ model["base_url"] = base_url
+ return model
+
+# ── published proto field sets (JSON names; proto JSON parsing also accepts snake_case) ─────────
+_REQUEST_FIELDS = {"contents", "tools", "toolConfig", "safetySettings", "systemInstruction",
+ "generationConfig", "cachedContent"}
+_CONTENT_FIELDS = {"role", "parts"}
+_PART_DATA_FIELDS = {"text", "inlineData", "functionCall", "functionResponse", "fileData",
+ "executableCode", "codeExecutionResult"}
+_PART_FIELDS = _PART_DATA_FIELDS | {"thought", "thoughtSignature", "videoMetadata", "partMetadata"}
+_FUNCTION_CALL_FIELDS = {"id", "name", "args"}
+_FUNCTION_RESPONSE_FIELDS = {"id", "name", "response", "parts", "willContinue", "scheduling"}
+_TOOL_FIELDS = {"functionDeclarations", "googleSearchRetrieval", "codeExecution", "googleSearch",
+ "urlContext", "computerUse", "fileSearch", "googleMaps"}
+_DECL_FIELDS_V1BETA = {"name", "description", "behavior", "parameters", "parametersJsonSchema",
+ "response", "responseJsonSchema"}
+_DECL_FIELDS_V1 = {"name", "description", "behavior", "parameters", "response"}
+_GENERATION_FIELDS = {"stopSequences", "responseMimeType", "responseSchema", "responseJsonSchema",
+ "responseModalities", "candidateCount", "maxOutputTokens", "temperature", "topP",
+ "topK", "seed", "presencePenalty", "frequencyPenalty", "responseLogprobs",
+ "logprobs", "enableEnhancedCivicAnswers", "speechConfig", "thinkingConfig",
+ "mediaResolution", "imageConfig"}
+_THINKING_FIELDS = {"includeThoughts", "thinkingBudget", "thinkingLevel"}
+# google.ai.generativelanguage.v1beta.Schema (the OpenAPI 3.0 subset behind ``parameters``).
+_SCHEMA_FIELDS = {"type", "format", "title", "description", "nullable", "enum", "maxItems", "minItems",
+ "properties", "required", "minProperties", "maxProperties", "minLength", "maxLength",
+ "pattern", "example", "anyOf", "propertyOrdering", "default", "items", "minimum",
+ "maximum"}
+_SCHEMA_TYPES = {"TYPE_UNSPECIFIED", "STRING", "NUMBER", "INTEGER", "BOOLEAN", "ARRAY", "OBJECT", "NULL"}
+_FUNCTION_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.:\-]{0,127}$")
+_ROLES = {"user", "model"}
+_PATH_RE = re.compile(r"^/(?P<version>v1(?:beta|alpha)?)/models/(?P<model>[^/:]+):(?P<method>[A-Za-z]+)$")
+
+
+class InvalidArgument(Exception):
+ """A request Google would refuse with HTTP 400 INVALID_ARGUMENT."""
+
+
+def _camel(key: str) -> str:
+ head, *rest = key.split("_")
+ return head + "".join(p[:1].upper() + p[1:] for p in rest)
+
+
+def _check_fields(obj: Any, allowed: set[str], where: str) -> dict[str, Any]:
+ if not isinstance(obj, dict):
+ raise InvalidArgument(f"Invalid value at '{where}': expected an object")
+ for key in obj:
+ if _camel(key) not in allowed:
+ raise InvalidArgument(f"Invalid JSON payload received. Unknown name \"{key}\" at '{where}': "
+ "Cannot find field.")
+ return {_camel(k): v for k, v in obj.items()}
+
+
+# ── scripted replies ────────────────────────────────────────────────────────────────────────────
+@dataclass
+class Text:
+ """A model text answer (optionally with a thought summary part and a trailing signature)."""
+ text: str
+ thought: str | None = None
+ signed: bool = True
+ prompt_tokens: int = 1200
+
+
+@dataclass
+class Call:
+ """One ``functionCall`` part. The fake mints the id and (for the first call) the signature."""
+ name: str
+ args: dict[str, Any]
+
+
+@dataclass
+class Calls:
+ """A model turn made of ``functionCall`` parts (Gemini 3: signature on the FIRST call only)."""
+ calls: list[Call]
+ thought: str | None = "Planning the tool call."
+ prompt_tokens: int = 1200
+
+
+@dataclass
+class Blocked:
+ """A candidate stopped by ``finishReason`` (SAFETY / RECITATION / ...) with no content, or, with
+ ``prompt=True``, a prompt blocked via ``promptFeedback.blockReason`` and no candidates."""
+ reason: str = "SAFETY"
+ prompt: bool = False
+
+
+@dataclass
+class GoogleError:
+ """A Google JSON error body (``google.rpc.Status``) with optional RetryInfo / Retry-After."""
+ code: int
+ status: str
+ message: str
+ retry_delay_s: float | None = None
+
+
+@dataclass
+class Drop:
+ """Streaming: emit ``partial`` as one SSE chunk, then close the TLS connection mid-response."""
+ partial: str = "Partial answer that never fin"
+
+
+Reply = Text | Calls | Blocked | GoogleError | Drop
+Responder = Callable[["Recorded"], "Reply | None"]
+
+
+@dataclass
+class Recorded:
+ method: str
+ path: str
+ query: dict[str, list[str]]
+ headers: dict[str, str]
+ body: dict[str, Any] | None
+ version: str = ""
+ model: str = ""
+ rpc: str = ""
+ status: int = 0
+ rejection: str | None = None
+ reply: str = ""
+
+ @property
+ def stream(self) -> bool:
+ return self.rpc == "streamGenerateContent"
+
+ @property
+ def contents(self) -> list[dict[str, Any]]:
+ return list((self.body or {}).get("contents") or [])
+
+ def parts(self, kind: str) -> list[dict[str, Any]]:
+ """Every part carrying ``kind`` (e.g. ``functionCall``), in wire order."""
+ return [p for c in self.contents for p in c.get("parts") or [] if kind in p]
+
+ def declarations(self) -> dict[str, dict[str, Any]]:
+ out: dict[str, dict[str, Any]] = {}
+ for tool in (self.body or {}).get("tools") or []:
+ for decl in tool.get("functionDeclarations") or []:
+ out[decl.get("name", "")] = decl
+ return out
+
+ def all_text(self) -> str:
+ texts = [p.get("text") or "" for c in self.contents for p in c.get("parts") or []]
+ system = ((self.body or {}).get("systemInstruction") or {}).get("parts") or []
+ return "\n".join(texts + [p.get("text") or "" for p in system])
+
+ def last_user_text(self) -> str:
+ for content in reversed(self.contents):
+ texts = [p["text"] for p in content.get("parts") or [] if isinstance(p.get("text"), str)]
+ if content.get("role") == "user" and texts:
+ return "\n".join(texts)
+ return ""
+
+
+# ── request validation (published contract) ────────────────────────────────────────────────────
+def _validate_schema(node: Any, where: str) -> None:
+ """``FunctionDeclaration.parameters`` is a proto ``Schema``: unknown keys, list-valued ``type``
+ and non-string ``enum`` entries do not parse; ``required`` must name defined properties."""
+ schema = _check_fields(node, _SCHEMA_FIELDS, where)
+ type_ = schema.get("type")
+ if type_ is not None and (not isinstance(type_, str) or type_.upper() not in _SCHEMA_TYPES):
+ raise InvalidArgument(f"Invalid value at '{where}.type' (type.googleapis.com/"
+ f"google.ai.generativelanguage.v1beta.Type), {json.dumps(type_)}")
+ for i, value in enumerate(schema.get("enum") or []):
+ if not isinstance(value, str):
+ raise InvalidArgument(f"Invalid value at '{where}.enum[{i}]' (TYPE_STRING), {json.dumps(value)}")
+ props = schema.get("properties") or {}
+ for name, sub in props.items():
+ _validate_schema(sub, f"{where}.properties[{name}].value")
+ for name in schema.get("required") or []:
+ if name not in props:
+ raise InvalidArgument(f"{where}.required[{name}]: property is not defined")
+ if "items" in schema:
+ _validate_schema(schema["items"], f"{where}.items")
+ elif isinstance(type_, str) and type_.upper() == "ARRAY":
+ raise InvalidArgument(f"{where}.items: missing field.")
+ for i, sub in enumerate(schema.get("anyOf") or []):
+ _validate_schema(sub, f"{where}.any_of[{i}]")
+
+
+def _validate_json_schema_root(schema: Any, where: str) -> None:
+ """``parametersJsonSchema`` must describe an object whose properties are the parameters."""
+ if not isinstance(schema, dict) or schema.get("type") != "object":
+ raise InvalidArgument(f"{where}: parameters_json_schema must describe an object (type: object)")
+
+
+def _validate_tools(tools: Any, version: str) -> None:
+ decl_fields = _DECL_FIELDS_V1BETA if version == "v1beta" else _DECL_FIELDS_V1
+ for ti, tool in enumerate(tools if isinstance(tools, list) else []):
+ tool = _check_fields(tool, _TOOL_FIELDS, f"tools[{ti}]")
+ for di, decl in enumerate(tool.get("functionDeclarations") or []):
+ where = f"tools[{ti}].function_declarations[{di}]"
+ decl = _check_fields(decl, decl_fields, where)
+ if not _FUNCTION_NAME_RE.match(str(decl.get("name") or "")):
+ raise InvalidArgument(f"{where}.name: Invalid function name. Must start with a letter or an "
+ "underscore. Must be alphameric (a-z, A-Z, 0-9), underscores (_), dots (.), "
+ "colons (:), or dashes (-), with a maximum length of 128.")
+ if "parameters" in decl and "parametersJsonSchema" in decl:
+ raise InvalidArgument(f"{where}: parameters and parameters_json_schema are mutually exclusive")
+ if "parameters" in decl:
+ _validate_schema(decl["parameters"], f"{where}.parameters")
+ if "parametersJsonSchema" in decl:
+ _validate_json_schema_root(decl["parametersJsonSchema"], f"{where}.parameters_json_schema")
+
+
+def _validate_part(part: Any, where: str) -> dict[str, Any]:
+ part = _check_fields(part, _PART_FIELDS, where)
+ data = [k for k in part if k in _PART_DATA_FIELDS]
+ if len(data) != 1:
+ raise InvalidArgument(f"{where}: a Part must set exactly one data field (oneof 'data'), got {data}")
+ if "functionCall" in part:
+ fc = _check_fields(part["functionCall"], _FUNCTION_CALL_FIELDS, f"{where}.function_call")
+ if not fc.get("name") or not isinstance(fc.get("args", {}), dict):
+ raise InvalidArgument(f"{where}.function_call: name is required and args must be an object")
+ if "functionResponse" in part:
+ fr = _check_fields(part["functionResponse"], _FUNCTION_RESPONSE_FIELDS, f"{where}.function_response")
+ if not fr.get("name") or not isinstance(fr.get("response"), dict):
+ raise InvalidArgument(f"{where}.function_response: name is required and response must be an object")
+ sig = part.get("thoughtSignature")
+ if sig is not None and not (isinstance(sig, str) and sig):
+ raise InvalidArgument(f"{where}.thought_signature: invalid bytes value")
+ return part
+
+
+def _check_pairing(contents: list[dict[str, Any]], gemini3: bool) -> None:
+ """Every functionCall turn is answered by the NEXT content with one functionResponse per call
+ (same name, same id on Gemini 3); a functionResponse turn must follow a functionCall turn."""
+ for i, content in enumerate(contents):
+ calls = [p["functionCall"] for p in content["parts"] if "functionCall" in p]
+ responses = [p["functionResponse"] for p in content["parts"] if "functionResponse" in p]
+ if responses:
+ prev_calls = [p["functionCall"] for p in contents[i - 1]["parts"] if "functionCall" in p] if i else []
+ if not prev_calls:
+ raise InvalidArgument("Please ensure that function response turn comes immediately after a "
+ "function call turn.")
+ if not calls:
+ continue
+ nxt = contents[i + 1]["parts"] if i + 1 < len(contents) else []
+ answered = [p["functionResponse"] for p in nxt if "functionResponse" in p]
+ if i + 1 < len(contents) and len(answered) != len(calls):
+ raise InvalidArgument("Please ensure that the number of function response parts is equal to the "
+ "number of function call parts of the function call turn.")
+ for call, resp in zip(calls, answered):
+ if call.get("name") != resp.get("name"):
+ raise InvalidArgument(f"functionResponse name {resp.get('name')!r} does not match functionCall "
+ f"name {call.get('name')!r} in contents[{i + 1}]")
+ if gemini3 and answered:
+ if sorted(str(c.get("id")) for c in calls) != sorted(str(r.get("id")) for r in answered):
+ raise InvalidArgument(f"functionResponse ids in contents[{i + 1}] do not match the functionCall "
+ "ids of the function call turn.")
+
+
+def _current_turn_start(contents: list[dict[str, Any]]) -> int:
+ """Index of the newest user content with standard (non-functionResponse) content."""
+ for i in range(len(contents) - 1, -1, -1):
+ c = contents[i]
+ if c["role"] == "user" and any("functionResponse" not in p for p in c["parts"]):
+ return i
+ return 0
+
+
+def _check_signatures(contents: list[dict[str, Any]], issued: set[str]) -> None:
+ """Gemini 3: the FIRST functionCall part of each step of the current turn must carry a
+ thoughtSignature Google issued (or a documented dummy); a forged one is corrupted."""
+ for i in range(_current_turn_start(contents), len(contents)):
+ c = contents[i]
+ fc_parts = [p for p in c["parts"] if "functionCall" in p] if c["role"] == "model" else []
+ if not fc_parts:
+ continue
+ sig = fc_parts[0].get("thoughtSignature")
+ if not sig:
+ raise InvalidArgument(f"Function call `{fc_parts[0]['functionCall']['name']}` in the `{i}.` content "
+ "block is missing a `thought_signature`.")
+ if sig not in issued and sig not in SKIP_SIGNATURES:
+ raise InvalidArgument("Corrupted thought signature.")
+
+
+def validate_generate_request(body: Any, version: str, model: str, issued: set[str]) -> None:
+ body = _check_fields(body, _REQUEST_FIELDS, "")
+ contents = body.get("contents")
+ if not isinstance(contents, list) or not contents:
+ raise InvalidArgument("* GenerateContentRequest.contents: contents is not specified")
+ norm: list[dict[str, Any]] = []
+ for ci, content in enumerate(contents):
+ content = _check_fields(content, _CONTENT_FIELDS, f"contents[{ci}]")
+ role = content.get("role", "user")
+ if role not in _ROLES:
+ raise InvalidArgument(f"Please use a valid role: user, model. (contents[{ci}].role={role!r})")
+ parts = content.get("parts")
+ if not isinstance(parts, list) or not parts:
+ raise InvalidArgument(f"* GenerateContentRequest.contents[{ci}].parts: contents.parts must not be empty.")
+ norm.append({"role": role, "parts": [_validate_part(p, f"contents[{ci}].parts[{pi}]")
+ for pi, p in enumerate(parts)]})
+ for a, b in zip(norm, norm[1:]):
+ if a["role"] == b["role"]:
+ raise InvalidArgument("Please ensure that multiturn requests alternate between user and model.")
+ if norm[-1]["role"] != "user":
+ raise InvalidArgument("Please ensure that single turn requests end with a user role or the role field "
+ "is empty.")
+ gemini3 = bool(re.match(r"gemini-([3-9]|\d\d)", model))
+ _check_pairing(norm, gemini3)
+ if gemini3:
+ _check_signatures(norm, issued)
+ if "systemInstruction" in body:
+ system = _check_fields(body["systemInstruction"], _CONTENT_FIELDS, "system_instruction")
+ for pi, p in enumerate(system.get("parts") or []):
+ _validate_part(p, f"system_instruction.parts[{pi}]")
+ _validate_tools(body.get("tools"), version)
+ generation = _check_fields(body.get("generationConfig") or {}, _GENERATION_FIELDS, "generation_config")
+ if "thinkingConfig" in generation:
+ _check_fields(generation["thinkingConfig"], _THINKING_FIELDS, "generation_config.thinking_config")
+
+
+# ── response building (GenerateContentResponse) ────────────────────────────────────────────────
+def _usage(prompt_tokens: int, output_tokens: int = 24, thought_tokens: int = 16) -> dict[str, Any]:
+ return {"promptTokenCount": prompt_tokens, "candidatesTokenCount": output_tokens,
+ "thoughtsTokenCount": thought_tokens, "totalTokenCount": prompt_tokens + output_tokens + thought_tokens}
+
+
+def _response(parts: list[dict[str, Any]] | None, finish: str | None, usage: dict[str, Any] | None,
+ extra: dict[str, Any] | None = None) -> dict[str, Any]:
+ cand: dict[str, Any] = {"index": 0}
+ if parts is not None:
+ cand["content"] = {"role": "model", "parts": parts}
+ if finish:
+ cand["finishReason"] = finish
+ out: dict[str, Any] = {"candidates": [cand], "modelVersion": MODEL_ID,
+ "responseId": secrets.token_urlsafe(12)}
+ if usage:
+ out["usageMetadata"] = usage
+ out.update(extra or {})
+ return out
+
+
+def _chunks(text: str, n: int = 3) -> list[str]:
+ step = max(1, -(-len(text) // n))
+ return [text[i:i + step] for i in range(0, len(text), step)] or [""]
+
+
+# ── TLS material ────────────────────────────────────────────────────────────────────────────────
+def _write_tls_material(directory: Path) -> tuple[Path, Path, Path]:
+ """Throwaway CA + a leaf for the Google host. Returns (ca_pem, leaf_cert_pem, leaf_key_pem)."""
+ from cryptography import x509
+ from cryptography.hazmat.primitives import hashes, serialization
+ from cryptography.hazmat.primitives.asymmetric import ec
+ from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
+
+ now = datetime.datetime.now(datetime.timezone.utc)
+ ca_key = ec.generate_private_key(ec.SECP256R1())
+ ca_name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "hermes-e2e gemini fake CA")])
+ ca = (x509.CertificateBuilder().subject_name(ca_name).issuer_name(ca_name)
+ .public_key(ca_key.public_key()).serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(minutes=5)).not_valid_after(now + datetime.timedelta(days=1))
+ .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True)
+ .add_extension(x509.KeyUsage(digital_signature=True, key_cert_sign=True, crl_sign=True,
+ content_commitment=False, key_encipherment=False, data_encipherment=False,
+ key_agreement=False, encipher_only=False, decipher_only=False), critical=True)
+ .add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()), critical=False)
+ .sign(ca_key, hashes.SHA256()))
+ leaf_key = ec.generate_private_key(ec.SECP256R1())
+ leaf = (x509.CertificateBuilder()
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, GEMINI_HOST)]))
+ .issuer_name(ca_name).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
+ .not_valid_before(now - datetime.timedelta(minutes=5)).not_valid_after(now + datetime.timedelta(days=1))
+ .add_extension(x509.SubjectAlternativeName([x509.DNSName(GEMINI_HOST),
+ x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]),
+ critical=False)
+ .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True)
+ .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), critical=False)
+ .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
+ .sign(ca_key, hashes.SHA256()))
+ directory.mkdir(parents=True, exist_ok=True)
+ ca_pem, cert_pem, key_pem = directory / "ca.pem", directory / "leaf.pem", directory / "leaf.key"
+ ca_pem.write_bytes(ca.public_bytes(serialization.Encoding.PEM))
+ cert_pem.write_bytes(leaf.public_bytes(serialization.Encoding.PEM))
+ key_pem.write_bytes(leaf_key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
+ serialization.NoEncryption()))
+ return ca_pem, cert_pem, key_pem
+
+
+# ── the fake ────────────────────────────────────────────────────────────────────────────────────
+class GeminiFake:
+ """Loopback CONNECT proxy + TLS-terminated fake Gemini API.
+
+ ``script`` replies are consumed in order by every valid generate call that ``route`` (optional
+ responder, e.g. for compaction summaries) does not claim. An exhausted script answers with a
+ Google 500 so an unexpected extra call is visible instead of hanging.
+ """
+
+ def __init__(self, workdir: Path, script: list[Reply] | None = None, *, route: Responder | None = None,
+ api_key: str = API_KEY) -> None:
+ self.workdir = workdir
+ self.api_key = api_key
+ self.script: list[Reply] = list(script or [])
+ self.route = route
+ self.requests: list[Recorded] = []
+ self.refused_hosts: list[str] = []
+ self.issued_signatures: list[str] = []
+ self.call_signatures: dict[str, str] = {} # functionCall id -> signature minted on its part
+ self._lock = threading.Lock()
+ self._counter = 0
+ self.ca_pem, cert, key = _write_tls_material(workdir / "tls")
+ self._tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ self._tls.load_cert_chain(cert, key)
+ self._server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler_class())
+ self._server.daemon_threads = True
+ self._thread = threading.Thread(target=self._server.serve_forever, name="gemini-fake", daemon=True)
+
+ # lifecycle ---------------------------------------------------------------------------------
+ def __enter__(self) -> "GeminiFake":
+ self._thread.start()
+ return self
+
+ def __exit__(self, *exc: Any) -> None:
+ self._server.shutdown()
+ self._server.server_close()
+ self._thread.join(timeout=10)
+
+ @property
+ def proxy_url(self) -> str:
+ return f"http://127.0.0.1:{self._server.server_address[1]}"
+
+ def child_env(self) -> dict[str, str]:
+ """Env for the ``hermes`` child: route HTTPS through the proxy and trust the fake CA."""
+ ca = str(self.ca_pem)
+ return {"HTTPS_PROXY": self.proxy_url, "https_proxy": self.proxy_url,
+ "HTTP_PROXY": self.proxy_url, "http_proxy": self.proxy_url,
+ "NO_PROXY": "", "no_proxy": "",
+ "SSL_CERT_FILE": ca, "REQUESTS_CA_BUNDLE": ca, "CURL_CA_BUNDLE": ca}
+
+ # views ------------------------------------------------------------------------------------
+ def generate_calls(self) -> list[Recorded]:
+ with self._lock:
+ return [r for r in self.requests if r.rpc in {"generateContent", "streamGenerateContent"}]
+
+ def rejections(self) -> list[str]:
+ with self._lock:
+ return [f"{r.rpc} -> {r.status}: {r.rejection}" for r in self.requests if r.rejection]
+
+ def main_calls(self) -> list[Recorded]:
+ """Generate calls answered from ``script`` (not claimed by ``route``)."""
+ return [r for r in self.generate_calls() if r.reply.startswith("script:")]
+
+ # dispatch ---------------------------------------------------------------------------------
+ def _mint_signature(self) -> str:
+ sig = base64.b64encode(b"\x12\x34gemini-e2e-sig:" + secrets.token_bytes(24)).decode()
+ with self._lock:
+ self.issued_signatures.append(sig)
+ return sig
+
+ def _mint_call_id(self) -> str:
+ with self._lock:
+ self._counter += 1
+ return f"fc-{self._counter:04d}-{secrets.token_hex(3)}"
+
+ def _next_reply(self, rec: Recorded) -> Reply:
+ if self.route is not None and (routed := self.route(rec)) is not None:
+ rec.reply = f"route:{type(routed).__name__}"
+ return routed
+ with self._lock:
+ reply = self.script.pop(0) if self.script else GoogleError(500, "INTERNAL", "fake script exhausted")
+ rec.reply = f"script:{type(reply).__name__}"
+ return reply
+
+ def _build(self, reply: Reply) -> list[dict[str, Any]]:
+ """Stream events for a reply (a unary response is their merge)."""
+ builders: dict[type, Callable[[Any], list[dict[str, Any]]]] = {
+ Text: self._text_events, Calls: self._call_events, Blocked: self._blocked_events,
+ }
+ return builders[type(reply)](reply)
+
+ def _text_events(self, reply: Text) -> list[dict[str, Any]]:
+ events: list[dict[str, Any]] = []
+ if reply.thought:
+ events.append(_response([{"text": reply.thought, "thought": True}], None, None))
+ pieces = _chunks(reply.text)
+ for i, piece in enumerate(pieces):
+ part: dict[str, Any] = {"text": piece}
+ last = i == len(pieces) - 1
+ if last and reply.signed:
+ part["thoughtSignature"] = self._mint_signature()
+ events.append(_response([part], "STOP" if last else None, _usage(reply.prompt_tokens) if last else None))
+ return events
+
+ def _call_events(self, reply: Calls) -> list[dict[str, Any]]:
+ events: list[dict[str, Any]] = []
+ if reply.thought:
+ events.append(_response([{"text": reply.thought, "thought": True}], None, None))
+ parts = []
+ for i, call in enumerate(reply.calls):
+ call_id = self._mint_call_id()
+ part: dict[str, Any] = {"functionCall": {"id": call_id, "name": call.name, "args": call.args}}
+ if i == 0:
+ part["thoughtSignature"] = self._mint_signature()
+ with self._lock:
+ self.call_signatures[call_id] = part["thoughtSignature"]
+ parts.append(part)
+ events.append(_response(parts, "STOP", _usage(reply.prompt_tokens)))
+ return events
+
+ @staticmethod
+ def _blocked_events(reply: Blocked) -> list[dict[str, Any]]:
+ if reply.prompt:
+ return [{"promptFeedback": {"blockReason": reply.reason, "safetyRatings": [
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "HIGH", "blocked": True}]},
+ "usageMetadata": {"promptTokenCount": 900, "totalTokenCount": 900}, "modelVersion": MODEL_ID}]
+ ratings = [{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "probability": "HIGH", "blocked": True}]
+ extra = {"citationMetadata": {"citationSources": [{"startIndex": 0, "endIndex": 40,
+ "uri": "https://example.com/source"}]}}
+ cand_extra = ratings if reply.reason == "SAFETY" else None
+ resp = _response(None, reply.reason, _usage(900, 0, 0))
+ if cand_extra:
+ resp["candidates"][0]["safetyRatings"] = cand_extra
+ if reply.reason == "RECITATION":
+ resp["candidates"][0].update(extra)
+ return [resp]
+
+ @staticmethod
+ def merge_events(events: list[dict[str, Any]]) -> dict[str, Any]:
+ """Unary ``generateContent`` body = the stream's chunks folded into one candidate."""
+ if not events or "candidates" not in events[-1]:
+ return events[-1] if events else {}
+ parts: list[dict[str, Any]] = []
+ for ev in events:
+ parts.extend(((ev.get("candidates") or [{}])[0].get("content") or {}).get("parts") or [])
+ final = json.loads(json.dumps(events[-1]))
+ if parts:
+ final["candidates"][0]["content"] = {"role": "model", "parts": parts}
+ return final
+
+ # HTTP handler -----------------------------------------------------------------------------
+ def _handler_class(self) -> type[BaseHTTPRequestHandler]:
+ fake = self
+
+ class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ tunneled = False
+
+ def log_message(self, format: str, *args: Any) -> None: # noqa: A002 - base signature
+ return
+
+ def do_CONNECT(self) -> None: # noqa: N802 - http.server naming
+ host = self.path.split(":", 1)[0].lower()
+ if self.tunneled or host != GEMINI_HOST:
+ with fake._lock:
+ fake.refused_hosts.append(host)
+ self.send_response(403, "Forbidden by hermes e2e fake proxy")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ self.close_connection = True
+ return
+ self.send_response(200, "Connection established")
+ self.end_headers()
+ self.wfile.flush()
+ try:
+ tls = fake._tls.wrap_socket(self.connection, server_side=True)
+ except (ssl.SSLError, OSError):
+ self.close_connection = True
+ return
+ self.connection = self.request = tls
+ self.rfile = tls.makefile("rb")
+ self.wfile = tls.makefile("wb")
+ self.tunneled = True
+ self.close_connection = False
+
+ def _refuse_plain(self) -> None:
+ with fake._lock:
+ fake.refused_hosts.append(urlsplit(self.path).hostname or self.headers.get("Host", "?"))
+ self.send_response(403)
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+
+ def do_GET(self) -> None: # noqa: N802
+ if not self.tunneled:
+ return self._refuse_plain()
+ fake._handle(self, "GET")
+
+ def do_POST(self) -> None: # noqa: N802
+ if not self.tunneled:
+ return self._refuse_plain()
+ fake._handle(self, "POST")
+
+ return Handler
+
+ def _send_json(self, h: BaseHTTPRequestHandler, rec: Recorded, status: int, body: dict[str, Any],
+ headers: dict[str, str] | None = None) -> None:
+ rec.status = status
+ data = json.dumps(body).encode()
+ h.send_response(status)
+ h.send_header("Content-Type", "application/json; charset=UTF-8")
+ for k, v in (headers or {}).items():
+ h.send_header(k, v)
+ h.send_header("Content-Length", str(len(data)))
+ h.end_headers()
+ h.wfile.write(data)
+ h.wfile.flush()
+
+ def _error(self, h: BaseHTTPRequestHandler, rec: Recorded, err: GoogleError) -> None:
+ body: dict[str, Any] = {"error": {"code": err.code, "message": err.message, "status": err.status}}
+ headers = {}
+ if err.retry_delay_s is not None:
+ body["error"]["details"] = [{"@type": "type.googleapis.com/google.rpc.RetryInfo",
+ "retryDelay": f"{err.retry_delay_s:g}s"}]
+ headers["Retry-After"] = f"{err.retry_delay_s:g}"
+ if err.code == 400:
+ rec.rejection = rec.rejection or err.message
+ self._send_json(h, rec, err.code, body, headers)
+
+ def _handle(self, h: BaseHTTPRequestHandler, method: str) -> None:
+ url = urlsplit(h.path)
+ length = int(h.headers.get("Content-Length") or 0)
+ raw = h.rfile.read(length) if length else b""
+ try:
+ body = json.loads(raw) if raw else None
+ except ValueError:
+ body = None
+ rec = Recorded(method, url.path, parse_qs(url.query), {k.lower(): v for k, v in h.headers.items()}, body)
+ with self._lock:
+ self.requests.append(rec)
+ match = _PATH_RE.match(url.path)
+ if method == "GET" or not match:
+ return self._error(h, rec, GoogleError(404, "NOT_FOUND", f"fake has no route for {method} {url.path}"))
+ rec.version, rec.model, rec.rpc = match["version"], match["model"], match["method"]
+ key = rec.headers.get("x-goog-api-key") or (rec.query.get("key") or [""])[0]
+ if key != self.api_key:
+ rec.rejection = "API key not valid"
+ return self._error(h, rec, GoogleError(400, "INVALID_ARGUMENT",
+ "API key not valid. Please pass a valid API key."))
+ if rec.stream and (rec.query.get("alt") or [""])[0] != "sse":
+ rec.rejection = "streamGenerateContent without alt=sse"
+ try:
+ with self._lock:
+ issued = set(self.issued_signatures)
+ validate_generate_request(body, rec.version, rec.model, issued)
+ except InvalidArgument as exc:
+ rec.rejection = str(exc)
+ return self._error(h, rec, GoogleError(400, "INVALID_ARGUMENT", str(exc)))
+ reply = self._next_reply(rec)
+ if isinstance(reply, GoogleError):
+ return self._error(h, rec, reply)
+ if isinstance(reply, Drop):
+ return self._drop(h, rec, reply)
+ events = self._build(reply)
+ if not rec.stream:
+ return self._send_json(h, rec, 200, self.merge_events(events))
+ self._stream(h, rec, events)
+
+ def _stream(self, h: BaseHTTPRequestHandler, rec: Recorded, events: list[dict[str, Any]]) -> None:
+ rec.status = 200
+ h.send_response(200)
+ h.send_header("Content-Type", "text/event-stream")
+ h.send_header("Transfer-Encoding", "chunked")
+ h.end_headers()
+ for ev in events:
+ self._write_chunk(h, f"data: {json.dumps(ev)}\r\n\r\n".encode())
+ h.wfile.write(b"0\r\n\r\n")
+ h.wfile.flush()
+
+ @staticmethod
+ def _write_chunk(h: BaseHTTPRequestHandler, data: bytes) -> None:
+ h.wfile.write(f"{len(data):x}\r\n".encode() + data + b"\r\n")
+ h.wfile.flush()
+
+ def _drop(self, h: BaseHTTPRequestHandler, rec: Recorded, reply: Drop) -> None:
+ rec.status = 200
+ h.send_response(200)
+ h.send_header("Content-Type", "text/event-stream")
+ h.send_header("Transfer-Encoding", "chunked")
+ h.end_headers()
+ self._write_chunk(h, f"data: {json.dumps(_response([{'text': reply.partial}], None, None))}\r\n\r\n".encode())
+ time.sleep(0.05) # let the partial chunk reach the client before the reset
+ h.close_connection = True
+ try:
+ h.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
+ h.connection.close()
+ except OSError:
+ pass