The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: Gemini and Copilot keep their reasoning carriers across turns
Teknium2b2e4d908dff
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 619e01340e0..c3344338be1 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -1516,6 +1516,9 @@ def extract_reasoning(agent, assistant_message) -> Optional[str]:parts.append(text)_add(getattr(assistant_message, "reasoning", None))_add(getattr(assistant_message, "reasoning_content", None))+ if not parts: # Copilot /chat/completions names its readable reasoning ``reasoning_text``+ from agent.reasoning_carriers import field+ _add(field(assistant_message, "reasoning_text"))# reasoning_details: [{"type": "reasoning.summary", "summary": "...", ...}, ...]for detail in getattr(assistant_message, "reasoning_details", None) or []:if isinstance(detail, dict):diff --git a/agent/auxiliary_wire.py b/agent/auxiliary_wire.pyindex a865f135be2..565d1c05a16 100644--- a/agent/auxiliary_wire.py+++ b/agent/auxiliary_wire.py@@ -14,7 +14,11 @@ def prepare_chat_messages(client, kwargs: dict) -> dict:"""if not isinstance(client, (OpenAI, AsyncOpenAI)) or "messages" not in kwargs:return kwargs+ from agent.reasoning_carriers import shape_wire_carriers++ base_url = str(getattr(client, "base_url", "") or "")messages = ChatCompletionsTransport().convert_messages(- kwargs["messages"], model=kwargs.get("model"), base_url=str(getattr(client, "base_url", "") or ""),+ shape_wire_carriers(kwargs["messages"], model=kwargs.get("model"), base_url=base_url),+ model=kwargs.get("model"), base_url=base_url,)return {**kwargs, "messages": messages}diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 55a0a9a3e51..3a66e8d9954 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1494,6 +1494,8 @@ def _build_chat_completions_kwargs(agent, api_messages, tools_for_api, reasoning_profile = get_provider_profile(agent.provider)_ephemeral_out = _consume_ephemeral_max_output(agent)+ from agent.reasoning_carriers import shape_wire_carriers+ api_messages = shape_wire_carriers(api_messages, model=agent.model, base_url=agent.base_url)# Strip image parts for non-vision models on BOTH paths (registered# providers with profiles used to bypass it)._common = dict(model=agent.model, messages=agent._prepare_messages_for_non_vision_model(api_messages),@@ -1658,6 +1660,11 @@ def _assistant_tool_call_dict(agent, tool_call, index: int) -> dict:extra = getattr(tool_call, "extra_content", None)if extra is not None:tc_dict["extra_content"] = _dump_if_model(extra)+ # Copilot's Gemini 3 variant signs the call inside ``function`` (replayed only to Copilot).+ from agent.reasoning_carriers import field+ fn_sig = field(tool_call, "thought_signature") or getattr(tool_call.function, "thought_signature", None)+ if isinstance(fn_sig, str) and fn_sig:+ tc_dict["function"]["thought_signature"] = fn_sigreturn tc_dict@@ -1754,6 +1761,13 @@ def build_assistant_message(agent, assistant_message, finish_reason: str) -> dic_reset_read_dedup_caches(task_id, session_id=getattr(agent, "session_id", None) or "")+ from agent.reasoning_carriers import carrier_record+ if record := carrier_record(assistant_message):+ # Gemini text-turn signature / Copilot reasoning_opaque+text: top-level for the live+ # history, a private reasoning_details record for persistence (reasoning_carriers.py).+ msg.update({k: v for k, v in record.items() if k != "type"})+ msg["reasoning_details"] = [*msg.get("reasoning_details", ()), record]+if assistant_tool_calls:msg["tool_calls"] = [_assistant_tool_call_dict(agent, tc, i) for i, tc in enumerate(assistant_tool_calls)]return msg@@ -2769,6 +2783,9 @@ class _ToolCallAccumulator:entry["function"]["name"] = tc_function.nameif getattr(tc_function, "arguments", None):parts.append(tc_function.arguments)+ from agent.reasoning_carriers import field+ if isinstance(fn_sig := field(tc_function, "thought_signature"), str) and fn_sig:+ entry["thought_signature"] = fn_sigextra = getattr(tc_delta, "extra_content", None)if extra is None and hasattr(tc_delta, "model_extra"):extra = (tc_delta.model_extra if isinstance(tc_delta.model_extra, dict) else {}).get("extra_content")@@ -3096,6 +3113,8 @@ class _StreamingCall(StreamingWaitMonitor):pending_text_parts: list[str] = []tool_calls = _ToolCallAccumulator()tool_calls_acc = tool_calls.acc+ from agent.reasoning_carriers import StreamCarriers+ carriers = StreamCarriers()finish_reason = model_name = usage_obj = Noneresponse_id = upstream_provider = None # the provider's own id / serving upstream, from the chunksrole = "assistant"@@ -3177,6 +3196,10 @@ class _StreamingCall(StreamingWaitMonitor):# whose deltas carry only this field otherwise trips the empty-stream guard (#56516).if reasoning_text is None and isinstance(getattr(delta, "model_extra", None), dict):reasoning_text = delta.model_extra.get("reasoning_content") or delta.model_extra.get("reasoning")+ # Copilot /chat/completions names its readable reasoning ``reasoning_text``.+ copilot_reasoning = carriers.feed(delta)+ if reasoning_text is None:+ reasoning_text = copilot_reasoningif reasoning_text:# Summary-part models omit the separator between markdown blocks; re-insert it.reasoning_text = separate_glued_reasoning_blocks(@@ -3266,6 +3289,8 @@ class _StreamingCall(StreamingWaitMonitor):"length" if runaway else finish_reason, model_name, usage_obj, flush_pending=_flush_pending_stream_text,response_id=response_id, upstream_provider=upstream_provider, reasoning_details=reasoning_details,refusal_parts=refusal_parts)+ if getattr(response, "choices", None):+ carriers.apply(response.choices[0].message)if runaway:# Cut, not finished: the length path ends the turn on this mark instead of continuing.response._runaway_repetition = True@@ -3340,7 +3365,8 @@ class _StreamingCall(StreamingWaitMonitor):mock_tool_calls.append(SimpleNamespace(id=tc["id"], type=tc["type"], extra_content=tc.get("extra_content"),function=SimpleNamespace(name=tc["function"]["name"], arguments=arguments,- args_repaired=arguments != tc["function"]["arguments"])))+ args_repaired=arguments != tc["function"]["arguments"],+ thought_signature=tc.get("thought_signature"))))return mock_tool_calls or None, has_truncated_tool_argsdef _finish_chat_stream(self, stream, role, content_parts, reasoning_parts, tool_calls_acc, finish_reason,diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.pyindex eeb22a45bdf..53fe8905ee5 100644--- a/agent/gemini_native_adapter.py+++ b/agent/gemini_native_adapter.py@@ -423,6 +423,11 @@ def _build_gemini_contents(if (call_id := _tool_call_id(tool_call)) and tool_name:tool_name_by_call_id[call_id] = tool_nameparts.append(_translate_tool_call_to_gemini(tool_call, include_ids=include_tool_call_ids))+ # Text-turn signature goes back on the last part, where it was received (a functionCall part+ # keeps its own signature).+ if role == "assistant" and parts and "functionCall" not in parts[-1] and (+ sig := _tool_call_extra_signature(msg)):+ parts[-1] = {**parts[-1], "thoughtSignature": sig}if parts:contents.append({"role": "model" if role == "assistant" else "user", "parts": parts})joined_system = "\n".join(part for part in system_text_parts if part).strip()@@ -611,6 +616,14 @@ def _part_text(part: dict[str, Any]) -> tuple[Optional[str], bool]:return (text, part.get("thought") is True) if isinstance(text, str) else (None, False)+def _text_part_signature(part: dict[str, Any]) -> Optional[str]:+ """``thoughtSignature`` on a non-functionCall part (a text turn's last part; in streams an empty-text+ part). Replay is optional, but the server rehydrates the turn's thoughts from it (live: 31 -> 237+ prompt tokens), so it is kept as the message-level ``extra_content`` signature."""+ sig = part.get("thoughtSignature")+ return sig if isinstance(sig, str) and sig and "functionCall" not in part else None++def _part_function_call(part: dict[str, Any]) -> Optional[dict[str, Any]]:fc = part.get("functionCall")return fc if isinstance(fc, dict) and fc.get("name") else None@@ -625,19 +638,22 @@ def translate_gemini_response(resp: dict[str, Any], model: str) -> SimpleNamespaparts = content_obj.get("parts") if isinstance(content_obj, dict) else []pieces: dict[bool, list[str]] = {False: [], True: []} # is_thought → text piecestool_calls: list[SimpleNamespace] = []+ text_signature = Nonefor index, part in enumerate(parts or []):if not isinstance(part, dict):continuetext, is_thought = _part_text(part)if text is not None:pieces[is_thought].append(text)+ text_signature = _text_part_signature(part) or text_signatureelif fc := _part_function_call(part):tool_calls.append(_tool_call_ns(str(fc["name"]), _dump_call_args(fc), index, _new_call_id(fc), _tool_call_extra_from_part(part)))finish_reason = "tool_calls" if tool_calls else _FINISH_REASON_MAP.get(str((cand or {}).get("finishReason") or "").upper(), "stop")usage = _usage_from_metadata((resp.get("usageMetadata") or {}) if cand is not None else {})reasoning = "".join(pieces[True]) or Nonemessage = SimpleNamespace(role="assistant", content="".join(pieces[False]) if pieces[False] else ("" if cand is None else None),- tool_calls=tool_calls or None, reasoning=reasoning, reasoning_content=reasoning, reasoning_details=None)+ tool_calls=tool_calls or None, reasoning=reasoning, reasoning_content=reasoning, reasoning_details=None,+ extra_content=_tool_call_extra_from_part({"thoughtSignature": text_signature}))return _envelope(model, "chat.completion", SimpleNamespace(index=0, message=message, finish_reason=finish_reason), usage)@@ -646,13 +662,15 @@ class _GeminiStreamChunk(SimpleNamespace): ...def _make_stream_chunk(*, model: str, content: str = "", tool_call_delta: Optional[dict[str, Any]] = None, finish_reason: Optional[str] = None, reasoning: str = "",+ text_signature: Optional[str] = None,) -> _GeminiStreamChunk:d = tool_call_deltatool_calls = None if d is None else [_tool_call_ns(d.get("name") or "", d.get("arguments") or "", d.get("index", 0), _new_call_id(d), d.get("extra_content"))]delta = SimpleNamespace(role="assistant", content=content or None, tool_calls=tool_calls, reasoning=reasoning or None,- reasoning_content=reasoning or None)+ reasoning_content=reasoning or None,+ extra_content=_tool_call_extra_from_part({"thoughtSignature": text_signature}))choice = SimpleNamespace(index=0, delta=delta, finish_reason=finish_reason)return _envelope(model, "chat.completion.chunk", choice, None, cls=_GeminiStreamChunk)@@ -735,6 +753,8 @@ def translate_stream_event(event: dict[str, Any], model: str, tool_call_indices:continueif text:chunks.append(_make_stream_chunk(model=model, content=text))+ if sig := _text_part_signature(part):+ chunks.append(_make_stream_chunk(model=model, text_signature=sig))if fc := _part_function_call(part):name = str(fc["name"])args_str = _dump_call_args(fc, sort_keys=True)diff --git a/agent/reasoning_carriers.py b/agent/reasoning_carriers.pynew file mode 100644index 00000000000..af078ef4086--- /dev/null+++ b/agent/reasoning_carriers.py@@ -0,0 +1,143 @@+"""Provider-native assistant reasoning carriers outside the standard reasoning fields.++* Gemini text-turn ``thought_signature`` (message-level ``extra_content.google`` on the OpenAI-compat+ and Vertex endpoints; the non-functionCall ``thoughtSignature`` part on the native API). Replaying it+ makes the server rehydrate the turn's thoughts (live: 31 -> 237/250 prompt tokens).+* GitHub Copilot ``/chat/completions`` ``reasoning_text`` / ``reasoning_opaque`` (top-level assistant+ keys, replayed by the Copilot editor clients) and the Gemini-3 ``function.thought_signature``.++Capture stores them top-level on the live assistant dict AND as ONE private ``reasoning_details`` record,+so they persist in the existing column and survive gateway/resume replay. Its type ends in ``.native_assistant``, which no profile declares, so+the chat-completions transport never forwards the record itself; ``shape_wire_carriers`` lifts each+field back onto the wire copy only for the route that reads it and strips it everywhere else.+"""++from __future__ import annotations++from typing import Any, Optional++CARRIER_TYPE = "hermes.native_assistant"+_MESSAGE_KEYS = ("extra_content", "reasoning_opaque", "reasoning_text")+++def field(obj: Any, name: str) -> Any:+ """``obj.<name>``, else the same key from pydantic ``model_extra`` (unknown SDK fields park there)."""+ value = getattr(obj, name, None)+ for side in ("model_extra", "provider_data"): # pydantic unknown fields / normalized responses+ if value is None and isinstance(getattr(obj, side, None), dict):+ value = getattr(obj, side).get(name)+ dump = getattr(value, "model_dump", None)+ return dump() if callable(dump) else value+++def thought_signature(extra: Any) -> Optional[str]:+ """Gemini signature inside an ``extra_content`` dict (``google.thought_signature`` or flat)."""+ if not isinstance(extra, dict):+ return None+ google = extra.get("google")+ sig = google.get("thought_signature") if isinstance(google, dict) else extra.get("thought_signature")+ return sig if isinstance(sig, str) and sig.strip() else None+++def carrier_record(assistant_message: Any) -> Optional[dict]:+ """The private ``reasoning_details`` record for one response message, or None when it has no carrier."""+ record: dict[str, Any] = {}+ if sig := thought_signature(field(assistant_message, "extra_content")):+ record["extra_content"] = {"google": {"thought_signature": sig}}+ for key in ("reasoning_opaque", "reasoning_text"):+ value = field(assistant_message, key)+ if isinstance(value, str) and value:+ record[key] = value+ return {"type": CARRIER_TYPE, **record} if record else None+++class StreamCarriers:+ """Accumulates the carriers from streamed deltas: the latest signature / opaque blob (Claude on+ Copilot sends a new opaque before each tool call; the editor clients replay only the latest) and+ the concatenated ``reasoning_text``."""++ def __init__(self) -> None:+ self.signature: Optional[str] = None+ self.opaque: Optional[str] = None+ self.text_parts: list[str] = []++ def feed(self, delta: Any) -> Optional[str]:+ """Absorb one delta; returns its ``reasoning_text`` fragment (Copilot's readable reasoning)."""+ self.signature = thought_signature(field(delta, "extra_content")) or self.signature+ opaque = field(delta, "reasoning_opaque")+ self.opaque = opaque if isinstance(opaque, str) and opaque else self.opaque+ text = field(delta, "reasoning_text")+ if not (isinstance(text, str) and text):+ return None+ self.text_parts.append(text)+ return text++ def apply(self, message: Any) -> None:+ if self.signature:+ message.extra_content = {"google": {"thought_signature": self.signature}}+ if self.opaque:+ message.reasoning_opaque = self.opaque+ if self.text_parts:+ message.reasoning_text = "".join(self.text_parts)+++def _route_reads(model: Any, base_url: Any) -> tuple[str, ...]:+ """Message-level carrier keys this route consumes."""+ from agent.transports.chat_completions import _model_consumes_thought_signature+ from utils import base_url_host_matches++ # Same gate as tool-call extra_content, so the two signature carriers can never disagree.+ gemini = ("extra_content",) if _model_consumes_thought_signature(model) else ()+ copilot = ("reasoning_opaque", "reasoning_text") if base_url_host_matches(str(base_url or ""), "githubcopilot.com") else ()+ return gemini + copilot+++def _strip_function_signature(tool_calls: list) -> list:+ return [+ {**tc, "function": {k: v for k, v in tc["function"].items() if k != "thought_signature"}}+ if isinstance(tc, dict) and isinstance(tc.get("function"), dict) and "thought_signature" in tc["function"]+ else tc+ for tc in tool_calls+ ]+++def _shape(msg: Any, reads: tuple[str, ...], copilot: bool) -> Any:+ if not isinstance(msg, dict) or msg.get("role") != "assistant":+ return msg+ details = msg.get("reasoning_details")+ details = details if isinstance(details, list) else []+ record = next((d for d in details if isinstance(d, dict) and d.get("type") == CARRIER_TYPE), None)+ tool_calls = msg.get("tool_calls")+ tool_calls = tool_calls if isinstance(tool_calls, list) else []+ fn_sig = not copilot and any(+ isinstance(tc, dict) and isinstance(tc.get("function"), dict) and "thought_signature" in tc["function"]+ for tc in tool_calls)+ if record is None and not fn_sig and not any(k in msg for k in _MESSAGE_KEYS):+ return msg+ out = {k: v for k, v in msg.items() if k not in _MESSAGE_KEYS}+ # Live history carries the keys top-level; a resumed row only has the persisted record.+ values = {**(record or {}), **{k: msg[k] for k in _MESSAGE_KEYS if k in msg}}+ if record is not None:+ rest = [d for d in details if d is not record]+ if rest:+ out["reasoning_details"] = rest+ else:+ out.pop("reasoning_details", None)+ for key in reads:+ # Copilot clients send reasoning_text only next to the opaque blob it belongs to.+ if values.get(key) and (key != "reasoning_text" or values.get("reasoning_opaque")):+ out[key] = values[key]+ if fn_sig:+ out["tool_calls"] = _strip_function_signature(tool_calls)+ return out+++def shape_wire_carriers(messages: list, *, model: Any, base_url: Any) -> list:+ """Wire copy of ``messages`` with each carrier on the route that reads it and nowhere else.+ Never mutates the input; unchanged messages are returned by identity."""+ from utils import base_url_host_matches++ reads = _route_reads(model, base_url)+ copilot = base_url_host_matches(str(base_url or ""), "githubcopilot.com")+ shaped = [_shape(m, reads, copilot) for m in messages]+ return messages if all(a is b for a, b in zip(shaped, messages)) else shapeddiff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex 030caf1d28d..09a4aee495b 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -645,6 +645,10 @@ class ChatCompletionsTransport(ProviderTransport):provider_data["reasoning_content"] = reasoning_contentif getattr(msg, "reasoning_details", None):provider_data["reasoning_details"] = msg.reasoning_details+ # Message-level carriers (Gemini text-turn signature, Copilot reasoning): agent/reasoning_carriers.py.+ for key in ("extra_content", "reasoning_opaque", "reasoning_text"):+ if (value := _attr_or_model_extra(msg, key)) is not None:+ provider_data[key] = _dump_extra_content(value)# OpenAI structured refusal (``message.refusal`` set, ``content`` empty); without# promotion the loop retries a deterministic refusal as an empty response.@@ -677,9 +681,12 @@ class ChatCompletionsTransport(ProviderTransport):name = alias_map.get(name, name)arguments = getattr(tc_function, "arguments", None)extra = _attr_or_model_extra(tc, "extra_content")+ fn_sig = _attr_or_model_extra(tc_function, "thought_signature") # Copilot's Gemini 3 variant+ provider_data = {k: v for k, v in (("extra_content", None if extra is None else _dump_extra_content(extra)),+ ("thought_signature", fn_sig)) if v is not None}call = ToolCall(id=getattr(tc, "id", None), name=name, arguments="{}" if arguments is None else arguments,- provider_data=None if extra is None else {"extra_content": _dump_extra_content(extra)},+ provider_data=provider_data or None,)if getattr(tc_function, "args_repaired", False) is True:call.args_repaired = True # stream assembly fixed the JSON; read by tool-call quality metricsdiff --git a/tests/agent/test_reasoning_carriers.py b/tests/agent/test_reasoning_carriers.pynew file mode 100644index 00000000000..db37591dea7--- /dev/null+++ b/tests/agent/test_reasoning_carriers.py@@ -0,0 +1,83 @@+"""Gemini text-turn signatures and Copilot reasoning carriers survive capture and reach only their route."""++import copy+from types import SimpleNamespace++from openai.types.chat import ChatCompletion++from agent.chat_completion_helpers import build_assistant_message+from agent.gemini_native_adapter import _build_gemini_contents, translate_gemini_response, translate_stream_event+from agent.reasoning_carriers import shape_wire_carriers+from agent.transports.chat_completions import ChatCompletionsTransport+++class _Agent:+ stream_delta_callback = _stream_callback = reasoning_callback = None+ verbose_logging = False++ def _extract_reasoning(self, msg):+ from agent.agent_runtime_helpers import extract_reasoning+ return extract_reasoning(self, msg)++ def _strip_think_blocks(self, text):+ return text++ def _needs_thinking_reasoning_pad(self):+ return False++ def _split_responses_tool_id(self, raw):+ return (None, None)++ def _derive_responses_function_call_id(self, call_id, item_id):+ return item_id++ def _deterministic_call_id(self, *a):+ return "call_x"+++def _stored(response):+ return build_assistant_message(_Agent(), ChatCompletionsTransport().normalize_response(response), "stop")+++def test_gemini_native_text_turn_signature_is_captured_and_replayed_on_the_last_part():+ resp = {"candidates": [{"content": {"parts": [{"text": "thinking", "thought": True},+ {"text": "391", "thoughtSignature": "SIG_TEXT"}]},+ "finishReason": "STOP"}]}+ stored = _stored(translate_gemini_response(resp, "gemini-3.6-flash"))+ # Streams deliver the signature on a trailing empty-text part.+ chunks = translate_stream_event({"candidates": [{"content": {"parts": [{"text": "", "thoughtSignature": "SIG_S"}]}}]},+ "gemini-3.6-flash", {})+ assert [c.choices[0].delta.extra_content for c in chunks] == [{"google": {"thought_signature": "SIG_S"}}]++ history = [{"role": "user", "content": "q"}, stored, {"role": "user", "content": "again"}]+ resumed = [{k: v for k, v in m.items() if k != "extra_content"} for m in history] # state.db keeps only the record+ for msgs in (history, resumed):+ wire = shape_wire_carriers(msgs, model="gemini-3.6-flash", base_url="https://generativelanguage.googleapis.com/v1beta")+ contents, _ = _build_gemini_contents(wire, is_gemini3=True)+ assert contents[1]["parts"][-1] == {"text": "391", "thoughtSignature": "SIG_TEXT"}+++def test_copilot_reasoning_and_function_signature_reach_only_copilot():+ resp = ChatCompletion.model_validate({+ "id": "c", "object": "chat.completion", "created": 0, "model": "gemini-3.6-pro",+ "choices": [{"index": 0, "finish_reason": "tool_calls", "message": {+ "role": "assistant", "content": None, "reasoning_text": "plan it", "reasoning_opaque": "OPAQUE",+ "tool_calls": [{"id": "t1", "type": "function",+ "function": {"name": "f", "arguments": "{}", "thought_signature": "FSIG"}}]}}]})+ stored = _stored(resp)+ assert stored["reasoning"] == "plan it"+ snapshot = copy.deepcopy(stored)++ copilot = shape_wire_carriers([stored], model="gemini-3.6-pro", base_url="https://api.githubcopilot.com")[0]+ assert (copilot["reasoning_opaque"], copilot["reasoning_text"]) == ("OPAQUE", "plan it")+ assert copilot["tool_calls"][0]["function"]["thought_signature"] == "FSIG"+ assert "reasoning_details" not in copilot++ for base_url in ("https://api.fireworks.ai/inference/v1", "https://openrouter.ai/api/v1"):+ other = ChatCompletionsTransport().convert_messages(+ shape_wire_carriers([stored], model="claude-sonnet-5", base_url=base_url), model="claude-sonnet-5",+ base_url=base_url)[0]+ assert not {"reasoning_opaque", "reasoning_text", "extra_content"} & other.keys()+ assert "thought_signature" not in other["tool_calls"][0]["function"]+ assert all(d.get("type") != "hermes.native_assistant" for d in other.get("reasoning_details") or ())+ assert stored == snapshot