Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(brain): replay Gemini tool history natively with thought signatures
Ruben Lütke3dcc3f45dbf0
diff --git a/jarvis/brain/tool_use_loop.py b/jarvis/brain/tool_use_loop.pyindex b5446a53cf..a67d606f88 100644--- a/jarvis/brain/tool_use_loop.py+++ b/jarvis/brain/tool_use_loop.py@@ -721,12 +721,19 @@ class ToolUseLoop:if agg.text:assistant_content.append({"type": "text", "text": agg.text})for tc in agg.tool_calls:- assistant_content.append({+ tool_use_part: dict[str, Any] = {"type": "tool_use","id": tc.get("id", f"call_{uuid4().hex[:8]}"),"name": tc.get("name", ""),"input": tc.get("input", {}),- })+ }+ # Gemini 3 thinking models require their functionCall+ # thought_signature back VERBATIM when the call is replayed+ # in history (400 INVALID_ARGUMENT otherwise). Providers that+ # never emit the key are unaffected.+ if tc.get("thought_signature"):+ tool_use_part["thought_signature"] = tc["thought_signature"]+ assistant_content.append(tool_use_part)current_messages.append(BrainMessage(role="assistant",content=assistant_content if assistant_content else agg.text,diff --git a/jarvis/plugins/brain/gemini.py b/jarvis/plugins/brain/gemini.pyindex 350ffbffc9..ca3161b83f 100644--- a/jarvis/plugins/brain/gemini.py+++ b/jarvis/plugins/brain/gemini.py@@ -12,6 +12,7 @@ where the Google SDK dependency graph has no installable wheel."""from __future__ import annotations+import base64import jsonimport loggingimport os@@ -102,39 +103,97 @@ def _is_thinking_config_rejected_error(exc: Exception) -> bool:return "budget" in msg or "invalid" in msg or "thinking mode" in msg-def _to_gemini_contents(messages: tuple[BrainMessage, ...]) -> list[dict[str, Any]]:+def _to_gemini_contents(+ messages: tuple[BrainMessage, ...],+ tool_name_map: dict[str, str] | None = None,+) -> list[dict[str, Any]]:"""BrainMessages → Gemini contents array. Role mapping: assistant→model.Multimodal: `BrainMessage.images` are appended as `inline_data` parts(`{"inline_data": {"mime_type": ..., "data": ...}}`) — only for usermessages, since Gemini doesn't accept model-role images as input.++ Tool history rides NATIVELY (2026-07-17): an assistant ``tool_use`` part+ becomes a ``functionCall`` part and a tool result a clean+ ``functionResponse`` — never JSON-dumped prose. The old text fallback fed+ the model its OWN prior calls as JSON text, so from round 2 of a tool+ loop it mimicked that format and "called" tools in plain text (the leak+ the ``extract_leaked_tool_calls`` recovery has to repair — observed on+ every delegated research turn). ``tool_name_map`` (original → wire name)+ keeps history names consistent with the sanitized declarations."""+ name_map = tool_name_map or {}contents: list[dict[str, Any]] = []for m in messages:if m.role == "system":continue # system goes via system_instructionrole = "user" if m.role in ("user", "tool") else "model"if m.role == "tool":- # FunctionResponse+ # FunctionResponse. The tool loop wraps results in an+ # Anthropic-style envelope list — unwrap to the payload text so+ # the model sees the result, not a serialized wrapper.+ payload = m.content+ result_text: str+ if isinstance(payload, list):+ inner = [+ str(part.get("content", ""))+ for part in payload+ if isinstance(part, dict) and part.get("type") == "tool_result"+ ]+ result_text = (+ "\n".join(t for t in inner if t)+ or json.dumps(payload, default=str)+ )+ else:+ result_text = str(payload)+ tool_name = m.name or ""contents.append({"role": "user","parts": [{"functionResponse": {- "name": m.name or "",- "response": {"result": str(m.content)},+ "name": name_map.get(tool_name, tool_name),+ "response": {"result": result_text},}}],})continue- text = m.content if isinstance(m.content, str) else json.dumps(m.content, default=str)- # Multimodal only makes sense on the user role — images are appended to- # the text part. If text is empty, we leave the text part out.# `getattr` for backwards-compat (Protocol pre-Wave-1-B1 had no images).images = getattr(m, "images", ()) or ()parts: list[dict[str, Any]] = []- if text:- parts.append({"text": text})+ if isinstance(m.content, str):+ if m.content:+ parts.append({"text": m.content})+ else:+ for part in m.content:+ if not isinstance(part, dict):+ parts.append({"text": str(part)})+ elif part.get("type") == "text":+ if part.get("text"):+ parts.append({"text": str(part["text"])})+ elif (+ part.get("type") == "tool_use"+ and role == "model"+ and isinstance(part.get("thought_signature"), str)+ and part["thought_signature"]+ ):+ # Native replay is only VALID with the original+ # thought_signature: Gemini 3 thinking models 400 on a+ # replayed functionCall part without it. The stream loop+ # captures it (base64) on every native call, so this+ # covers all Gemini-originated calls.+ call_name = str(part.get("name", ""))+ call_args = part.get("input")+ parts.append({+ "functionCall": {+ "name": name_map.get(call_name, call_name),+ "args": call_args if isinstance(call_args, dict) else {},+ },+ "thought_signature": part["thought_signature"],+ })+ else:+ # Unknown block type: keep the previous lossless behavior.+ parts.append({"text": json.dumps(part, default=str)})if m.role == "user" and images:for img in images:parts.append({@@ -586,7 +645,6 @@ class GeminiBrain:yield deltareturn- contents = _to_gemini_contents(req.messages)system_parts: list[str] = [m.content for m in req.messagesif m.role == "system" and isinstance(m.content, str)]if req.system:@@ -599,6 +657,9 @@ class GeminiBrain:system_text = "\n\n".join(system_parts) if system_parts else ""# One pass builds both the outbound declarations and the name map.tools_payload, _tool_name_map = _build_gemini_tool_declarations(req.tools)+ # Contents AFTER the name map exists: prior tool calls/results in the+ # history must carry the same sanitized names as the declarations.+ contents = _to_gemini_contents(req.messages, _tool_name_map)# Inbound resolution: Gemini calls back the SANITIZED name; the tool# executor only knows the original. Invert the forward map (empty when# there are no tools). See _build_gemini_tool_declarations.@@ -801,11 +862,25 @@ class GeminiBrain:if hasattr(args, "items"):args = dict(args)yielded_delta = True- yield BrainDelta(tool_call={+ call: dict[str, Any] = {"id": f"gemini_{uuid4().hex[:8]}","name": tool_name_reverse.get(name, name),"input": args,- })+ }+ # Gemini 3 thinking models stamp each functionCall+ # part with a thought_signature and REQUIRE it back+ # verbatim when the call is replayed in history+ # (400 INVALID_ARGUMENT otherwise). Carry it on the+ # provider-neutral call dict; other providers'+ # converters simply never read the key.+ signature = getattr(part, "thought_signature", None)+ if signature:+ call["thought_signature"] = (+ base64.b64encode(signature).decode("ascii")+ if isinstance(signature, (bytes, bytearray))+ else str(signature)+ )+ yield BrainDelta(tool_call=call)finish = getattr(cand, "finish_reason", None)if finish:yielded_delta = Truediff --git a/tests/unit/brain/test_gemini_native_tool_history.py b/tests/unit/brain/test_gemini_native_tool_history.pynew file mode 100644index 0000000000..a8e511f85c--- /dev/null+++ b/tests/unit/brain/test_gemini_native_tool_history.py@@ -0,0 +1,131 @@+"""Gemini tool-loop history must ride as NATIVE function parts.++Live forensic 2026-07-17 (delegated research turns, and turn af736681+rounds 4-5): the old conversion JSON-dumped an assistant tool_use turn into+plain text, so from round 2 of a tool loop Gemini saw its OWN prior calls as+JSON prose and mimicked that format — every later "tool call" leaked as text+("tool_use_loop: recovered 1 text-serialized tool call(s)") and had to be+repaired by the lossy leak-recovery parser, costing decode time and rounds.++Gemini 3 thinking models stamp every native functionCall with a+``thought_signature`` and 400 on a replayed call WITHOUT it — so native+replay applies exactly to signature-carrying calls (all Gemini-originated+ones; the stream loop captures the signature), while signature-less calls+(leak-recovered, cross-provider history) keep the proven text form.++Contract under test:+ 1. An assistant tool_use part WITH a thought_signature converts to a+ native ``functionCall`` part (never a JSON text dump), wire-sanitized+ name, signature attached verbatim.+ 2. A tool-result message converts to a ``functionResponse`` carrying the+ unwrapped payload text and the same sanitized name.+ 3. A signature-less tool_use part keeps the legacy text serialization+ (valid wire format; native replay would 400).+ 4. Plain text turns and user messages keep their previous shape.+"""+from __future__ import annotations++import json++from jarvis.core.protocols import BrainMessage+from jarvis.plugins.brain.gemini import _to_gemini_contents++_NAME_MAP = {"github/search": "github_search"}+++def _tool_loop_history() -> tuple[BrainMessage, ...]:+ return (+ BrainMessage(role="user", content="find the repo"),+ BrainMessage(+ role="assistant",+ content=[+ {"type": "text", "text": "Looking it up."},+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "github/search",+ "input": {"query": "personal jarvis"},+ "thought_signature": "c2lnbmF0dXJl",+ },+ ],+ ),+ BrainMessage(+ role="tool",+ content=[{+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": '{"success": true, "output": "1 repo found"}',+ }],+ tool_call_id="call_1",+ name="github/search",+ ),+ )+++def test_assistant_tool_use_becomes_native_function_call() -> None:+ contents = _to_gemini_contents(_tool_loop_history(), _NAME_MAP)++ model_turn = contents[1]+ assert model_turn["role"] == "model"+ assert {"text": "Looking it up."} in model_turn["parts"]+ call_parts = [p for p in model_turn["parts"] if "functionCall" in p]+ assert call_parts, "tool_use must convert to a functionCall part"+ call = call_parts[0]["functionCall"]+ assert call["name"] == "github_search" # wire-sanitized, matches declaration+ assert call["args"] == {"query": "personal jarvis"}+ # Gemini 3 validation: the original signature must ride on the part.+ assert call_parts[0]["thought_signature"] == "c2lnbmF0dXJl"+ # The leak trigger: no part may contain the JSON-dumped tool_use text.+ for part in model_turn["parts"]:+ assert "tool_use" not in json.dumps(part.get("text", ""))+++def test_tool_result_becomes_unwrapped_function_response() -> None:+ contents = _to_gemini_contents(_tool_loop_history(), _NAME_MAP)++ tool_turn = contents[2]+ assert tool_turn["role"] == "user"+ response = tool_turn["parts"][0]["functionResponse"]+ assert response["name"] == "github_search"+ # Unwrapped payload — not the serialized envelope list.+ assert response["response"]["result"] == (+ '{"success": true, "output": "1 repo found"}'+ )+ assert "tool_result" not in response["response"]["result"]+++def test_signature_less_tool_use_keeps_text_form() -> None:+ contents = _to_gemini_contents(+ (+ BrainMessage(+ role="assistant",+ content=[{+ "type": "tool_use",+ "id": "call_x",+ "name": "search_web",+ "input": {"query": "divo"},+ }],+ ),+ ),+ )++ parts = contents[0]["parts"]+ assert all("functionCall" not in p for p in parts), (+ "a signature-less call must NOT replay natively — Gemini 3 rejects "+ "functionCall parts without their thought_signature (400)"+ )+ assert any("tool_use" in str(p.get("text", "")) for p in parts)+++def test_plain_turns_keep_their_shape() -> None:+ contents = _to_gemini_contents(+ (+ BrainMessage(role="user", content="hello"),+ BrainMessage(role="assistant", content="hi there"),+ ),+ )++ assert contents == [+ {"role": "user", "parts": [{"text": "hello"}]},+ {"role": "model", "parts": [{"text": "hi there"}]},+ ]