Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Surface the provider's reasoning summary on Task V3 action rows where available (#8364)
pedrohsdb4fb1aff30f1e
diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex 2c64b7b59..39429437e 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -1450,6 +1450,44 @@ class LLMAPIHandlerFactory:check_model = model_labelreturn check_model+ @staticmethod+ def uses_openai_responses_bridge(llm_config: LLMConfig | LLMRouterConfig) -> bool:+ """Whether calls built from this config land on an OpenAI gpt-5.6 model, which litellm+ silently bridges from /v1/chat/completions to /v1/responses when tools are present (see+ _record_served_service_tier's docstring). Only the responses bridge accepts the dict form+ of reasoning_effort (mapped to Reasoning(**dict)); a plain chat-completions model 400s on+ it ("Unknown parameter: 'reasoning'" observed).++ A router deployment can hide the model behind an opaque alias (e.g. an Azure deployment+ name) in its dispatched litellm model string, so this also checks the deployment's+ declared model_info label -- router configs set that to the real model name for exactly+ this kind of identification.+ """++ def _is_bridge_model(candidate: Any) -> bool:+ return isinstance(candidate, str) and candidate.rsplit("/", 1)[-1].lower().startswith(+ _OPENAI_GPT5_6_MODEL_PREFIX+ )++ # litellm decides the bridge from the DISPATCHED model string alone, so this check reads+ # exactly that and nothing else (a model_info label saying gpt-5.6 would answer True where+ # litellm will not bridge, sending the dict to a chat-completions endpoint).+ if isinstance(llm_config, LLMRouterConfig):+ # EVERY deployment that can serve the call (main + fallback groups, same filter as+ # _resolve_tool_choice_support) must be a bridge model: a mixed router could hand the+ # dict reasoning_effort to a non-bridge fallback, which rejects it.+ groups = {llm_config.main_model_group}+ fallback_group = llm_config.fallback_model_group+ if isinstance(fallback_group, str):+ groups.add(fallback_group)+ elif fallback_group:+ groups.update(fallback_group)+ deployments = [deployment for deployment in llm_config.model_list if deployment.model_name in groups]+ if not deployments:+ return False+ return all(_is_bridge_model(deployment.litellm_params.get("model")) for deployment in deployments)+ return _is_bridge_model(llm_config.model_name)+@staticmethoddef is_github_copilot_endpoint() -> bool:"""Check if the OPENAI_COMPATIBLE endpoint is GitHub Copilot."""@@ -3209,6 +3247,29 @@ class LLMCaller:def clear_tool_results(self) -> None:self.current_tool_results = []+ def uses_openai_responses_bridge(self) -> bool:+ """Whether THIS caller's calls actually go through litellm's chat->responses bridge. The+ raw AsyncOpenAI/openrouter dispatch branches never bridge, whatever the model is named --+ a dict reasoning_effort there is a schema violation on every call."""+ if self.openai_client is not None or self._custom_openrouter:+ return False+ # Custom/BYO keys (openrouter or openai-compatible) point litellm at an arbitrary api_base+ # that is not guaranteed to implement /v1/responses, whatever the model is named.+ if is_custom_llm_key(self.original_llm_key):+ return False+ # Same risk for any built-in openai-provider config with an explicit api_base (e.g. the+ # OPENAI_COMPATIBLE registration, whose key name is configurable): only real OpenAI and+ # Azure endpoints are known to serve the bridge, and real OpenAI needs no api_base.+ litellm_params = getattr(self.llm_config, "litellm_params", None)+ if (+ isinstance(self.llm_config, LLMConfig)+ and litellm_params is not None+ and litellm_params.get("api_base")+ and not self.llm_config.model_name.startswith("azure/")+ ):+ return False+ return LLMAPIHandlerFactory.uses_openai_responses_bridge(self.llm_config)+def supports_tool_choice(self) -> bool:"""Whether the resolved model can be sent a ``tool_choice`` parameter.diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 728e58f34..5c5683a46 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -182,9 +182,36 @@ def _build_call_kwargs(step: Any, llm_caller: Any) -> dict[str, Any] | None:call_kwargs["step"] = stepif settings.TASK_V3_TOOL_CHOICE_REQUIRED and llm_caller.supports_tool_choice():call_kwargs["tool_choice"] = "required"+ reasoning_with_summary = _reasoning_effort_with_summary(llm_caller)+ if reasoning_with_summary is not None:+ call_kwargs["reasoning_effort"] = reasoning_with_summaryreturn call_kwargs or None+def _reasoning_effort_with_summary(llm_caller: Any) -> dict[str, str] | None:+ """A call-level reasoning_effort override that adds a summary request, for Task V3 loop calls+ only: `{"effort": <the effort the config would otherwise send>, "summary": "auto"}`. Passed as+ an LLMCaller.call() kwarg, which is applied after (and so wins over) the config-derived+ parameters -- this never changes how hard the model reasons, only whether litellm's+ chat->responses bridge joins a readable summary into message.reasoning_content.++ Only gpt-5.6 models routed through that bridge accept the dict form; a plain dict sent to any+ other model 400s ("Unknown parameter: 'reasoning'" observed), so this is gated to those models+ and returns None otherwise -- surfacing the provider's reasoning summary where available, since+ a continuation turn's tool call often carries empty message.content and no summary either.+ """+ llm_config = getattr(llm_caller, "llm_config", None)+ if llm_config is None:+ return None+ effort = getattr(llm_config, "reasoning_effort", None)+ # The caller-level check also covers the raw-client dispatch branches (custom/BYO models),+ # which never bridge regardless of the model's name.+ bridge_check = getattr(llm_caller, "uses_openai_responses_bridge", None)+ if effort is None or bridge_check is None or not bridge_check():+ return None+ return {"effort": effort, "summary": "auto"}++async def run_task_v3_agent_loop(*,page_provider: PageProvider,diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 5d8896fff..bbcdc63c6 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -135,6 +135,16 @@ def _extract_text(response: Any) -> str | None:return _get(message, "content")+def _extract_reasoning_summary(response: Any) -> str | None:+ """The provider's reasoning summary (message.reasoning_content), when litellm's chat->responses+ bridge returned one -- surfaces the provider's reasoning summary where available; a tool call+ with empty message.content on a continuation turn often has none either."""+ message = _extract_message(response)+ if message is None:+ return None+ return _get(message, "reasoning_content")++def _extract_tool_calls(response: Any) -> list[tuple[str, str, dict[str, Any]]]:message = _extract_message(response)if message is None:@@ -1635,18 +1645,23 @@ async def run_agent_tool_loop(active_call_kwargs = dict(call_kwargs or {})def _degrade_tool_choice(exc: BaseException) -> bool:- """Drop tool_choice and report whether the turn is worth re-issuing.+ """Drop the optional call parameters (tool_choice, the reasoning-summary dict) and report+ whether the turn is worth re-issuing.Called only when the turn is otherwise about to end the run, so the cost is one extra callon a run that was already failing. A context-window overflow is excluded because dropping a- parameter provably cannot fix it.+ parameter provably cannot fix it. Dropping reasoning_effort reverts to the config's own+ value, so a provider that rejects the dict form cannot end the run on turn 1."""if isinstance(exc, SkyvernContextWindowExceededError):return False- if active_call_kwargs.pop("tool_choice", None) is None:- return False- LOG.warning("taskv3 loop retrying without tool_choice", turn=turns, exc_info=True)- return True+ # One parameter per degrade, least-proven first: a provider that rejects only the summary+ # dict keeps its independently supported tool_choice; a second rejection drops that too.+ for key in ("reasoning_effort", "tool_choice"):+ if active_call_kwargs.pop(key, None) is not None:+ LOG.warning("taskv3 loop retrying without optional call param", dropped=key, turn=turns, exc_info=True)+ return True+ return Falseturns = 0no_tool_call_turns = 0@@ -1766,6 +1781,7 @@ async def run_agent_tool_loop(activity.tokens_remaining = None if max_tokens is None else max_tokens - total_tokenstext = _extract_text(response)+ reasoning_summary = _extract_reasoning_summary(response)tool_calls = _extract_tool_calls(response)assistant_message: dict[str, Any] = {"role": "assistant", "content": text or None}@@ -2617,7 +2633,7 @@ async def run_agent_tool_loop(# persistence hiccup must not abort an otherwise-good run, so failures are contained here.if round_actions and on_action_round is not None:try:- await on_action_round(round_actions, text or None)+ await on_action_round(round_actions, text or reasoning_summary or None)except Exception:LOG.warning("taskv3 on_action_round callback failed", turn=turns, exc_info=True)diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex e87b8cf43..caca418b9 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -15,6 +15,7 @@ import aiohttpimport pytestimport yarl+from skyvern.forge.sdk.api.llm.api_handler_factory import LLMAPIHandlerFactoryfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.taskv3 import engine as engine_mod@@ -441,6 +442,109 @@ async def test_engine_requests_tool_choice_when_enabled(monkeypatch: pytest.Monkassert captured["call_kwargs"] == {"step": step}+async def test_engine_requests_reasoning_summary_for_bridge_routed_model(monkeypatch: pytest.MonkeyPatch) -> None:+ # Only gpt-5.6 models are routed through litellm's chat->responses bridge, which is the only+ # path that accepts the dict form of reasoning_effort -- so only those calls should carry it.+ from skyvern.forge.taskv3.loop import LoopOutcome+ from skyvern.schemas.llm import LLMConfig++ captured: dict[str, object] = {}++ async def _capture(**kwargs: object) -> LoopOutcome:+ captured.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", _capture)++ caller = _ScriptedCaller([])+ caller.uses_openai_responses_bridge = lambda: LLMAPIHandlerFactory.uses_openai_responses_bridge(caller.llm_config)+ caller.llm_config = LLMConfig(+ model_name="gpt-5.6-luna",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ await run_task_v3_agent_loop(page_provider=_fixed_page_provider(_FakePage()), llm_caller=caller, goal="x")++ # The configured effort is preserved verbatim, never hardcoded.+ assert captured["call_kwargs"] == {"reasoning_effort": {"effort": "high", "summary": "auto"}}+++async def test_engine_requests_reasoning_summary_for_gpt56_dispatched_router_deployment(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # litellm bridges from the DISPATCHED model string, so a router deployment qualifies only when+ # its litellm model is gpt-5.6-named; an opaque alias must not (litellm would not bridge it).+ from skyvern.forge.taskv3.loop import LoopOutcome+ from skyvern.schemas.llm import LLMRouterConfig, LLMRouterModelConfig++ captured: dict[str, object] = {}++ async def _capture(**kwargs: object) -> LoopOutcome:+ captured.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", _capture)++ caller = _ScriptedCaller([])+ caller.uses_openai_responses_bridge = lambda: LLMAPIHandlerFactory.uses_openai_responses_bridge(caller.llm_config)+ caller.llm_config = LLMRouterConfig(+ model_name="azure-gpt-5-6-sol-flex-fallback-router",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ model_list=[+ LLMRouterModelConfig(+ model_name="azure-gpt-5-6-sol-flex",+ litellm_params={"model": "azure/gpt-5.6-sol-deployment"},+ model_info={"model_name": "azure/gpt-5.6-sol"},+ ),+ ],+ main_model_group="azure-gpt-5-6-sol-flex",+ reasoning_effort="medium",+ )+ await run_task_v3_agent_loop(page_provider=_fixed_page_provider(_FakePage()), llm_caller=caller, goal="x")++ assert captured["call_kwargs"] == {"reasoning_effort": {"effort": "medium", "summary": "auto"}}++ captured.clear()+ caller.llm_config.model_list[0].litellm_params["model"] = "azure/some-opaque-deployment-name"+ await run_task_v3_agent_loop(page_provider=_fixed_page_provider(_FakePage()), llm_caller=caller, goal="x")+ assert "reasoning_effort" not in (captured.get("call_kwargs") or {})+++async def test_engine_omits_reasoning_summary_for_non_bridge_model(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.forge.taskv3.loop import LoopOutcome+ from skyvern.schemas.llm import LLMConfig++ captured: dict[str, object] = {}++ async def _capture(**kwargs: object) -> LoopOutcome:+ captured.update(kwargs)+ return LoopOutcome(status="completed", reason="ok")++ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", _capture)++ caller = _ScriptedCaller([])+ caller.uses_openai_responses_bridge = lambda: LLMAPIHandlerFactory.uses_openai_responses_bridge(caller.llm_config)+ caller.llm_config = LLMConfig(+ model_name="claude-fable-5",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ await run_task_v3_agent_loop(page_provider=_fixed_page_provider(_FakePage()), llm_caller=caller, goal="x")++ # A plain dict reasoning_effort on a non-bridge model 400s ("Unknown parameter: 'reasoning'"),+ # so this model must never get it -- and no other call kwarg applies here either.+ assert captured["call_kwargs"] is None++@pytest.mark.asyncioasync def test_engine_wires_failure_evidence_gate() -> None:# End-to-end wiring: the engine's own ActivityRecency reaches both the loop (which records the@@ -1066,3 +1170,163 @@ async def test_page_free_run_never_gets_auto_observe_guidance_even_with_the_flagawait run_task_v3_agent_loop(page_provider=no_page, llm_caller=_ScriptedCaller([]), goal="decide", page_free=True)assert loop_kwargs["auto_observe"] is Falseassert "act from that snapshot instead of calling observe again" not in loop_kwargs["system_prompt"]+++def test_caller_level_bridge_check_denies_raw_client_dispatch() -> None:+ # A custom/BYO model can be NAMED gpt-5.6-* yet dispatch through the raw OpenAI client branch,+ # which never bridges — the dict form there is a schema violation on every call. The caller-level+ # check must deny on dispatch path, whatever the name says.+ from types import SimpleNamespace++ from skyvern.forge.sdk.api.llm.api_handler_factory import LLMCaller+ from skyvern.schemas.llm import LLMConfig++ config = LLMConfig(+ model_name="openrouter/gpt-5.6-custom",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ raw_client_self = SimpleNamespace(+ openai_client=object(), _custom_openrouter=False, llm_config=config, original_llm_key="X"+ )+ assert LLMCaller.uses_openai_responses_bridge(raw_client_self) is False+ openrouter_self = SimpleNamespace(+ openai_client=None, _custom_openrouter=True, llm_config=config, original_llm_key="X"+ )+ assert LLMCaller.uses_openai_responses_bridge(openrouter_self) is False+ litellm_self = SimpleNamespace(+ openai_client=None, _custom_openrouter=False, llm_config=config, original_llm_key="X"+ )+ assert LLMCaller.uses_openai_responses_bridge(litellm_self) is True+++def test_engine_omits_summary_when_caller_denies_the_bridge() -> None:+ from skyvern.schemas.llm import LLMConfig++ caller = _ScriptedCaller([])+ caller.uses_openai_responses_bridge = lambda: False+ caller.llm_config = LLMConfig(+ model_name="gpt-5.6-luna",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ assert engine_mod._reasoning_effort_with_summary(caller) is None+++def test_bridge_check_mirrors_litellm_dispatched_name_only() -> None:+ # litellm decides the bridge from the DISPATCHED model string alone. A model_info label saying+ # gpt-5.6 must NOT flip the gate for an opaque deployment alias: litellm would not bridge that+ # call, and the dict form would reach a chat-completions endpoint.+ from skyvern.schemas.llm import LiteLLMParams, LLMConfig++ aliased = LLMConfig(+ model_name="azure/opaque-deployment-alias",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ litellm_params=LiteLLMParams(model_info={"model_name": "azure/gpt-5.6-sol"}),+ )+ assert LLMAPIHandlerFactory.uses_openai_responses_bridge(aliased) is False+ dispatched_named = LLMConfig(+ model_name="azure/gpt-5.6-sol-deployment",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ assert LLMAPIHandlerFactory.uses_openai_responses_bridge(dispatched_named) is True+++def test_bridge_check_denies_router_with_non_bridge_fallback_group() -> None:+ # A mixed router could hand the dict reasoning_effort to a non-bridge fallback deployment,+ # which rejects it — every serving deployment must qualify.+ from skyvern.schemas.llm import LLMRouterConfig, LLMRouterModelConfig++ config = LLMRouterConfig(+ model_name="mixed-router",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ model_list=[+ LLMRouterModelConfig(+ model_name="primary-group",+ litellm_params={"model": "gpt-5.6-luna"},+ model_info={"model_name": "gpt-5.6-luna"},+ ),+ LLMRouterModelConfig(+ model_name="fallback-group",+ litellm_params={"model": "gpt-4.1"},+ model_info={"model_name": "gpt-4.1"},+ ),+ ],+ main_model_group="primary-group",+ fallback_model_group="fallback-group",+ reasoning_effort="high",+ )+ assert LLMAPIHandlerFactory.uses_openai_responses_bridge(config) is False+++def test_caller_level_bridge_check_denies_custom_llm_keys() -> None:+ # A custom/BYO key routes litellm at an arbitrary api_base that need not implement+ # /v1/responses, whatever the user named the model — default-deny.+ from types import SimpleNamespace++ from skyvern.forge.sdk.api.llm.api_handler_factory import LLMCaller+ from skyvern.forge.sdk.api.llm.custom_llm_registry import CUSTOM_LLM_KEY_PREFIX+ from skyvern.schemas.llm import LLMConfig++ config = LLMConfig(+ model_name="openai/gpt-5.6-byo",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ )+ custom_self = SimpleNamespace(+ openai_client=None,+ _custom_openrouter=False,+ llm_config=config,+ original_llm_key=f"{CUSTOM_LLM_KEY_PREFIX}abc123",+ )+ assert LLMCaller.uses_openai_responses_bridge(custom_self) is False+++def test_caller_level_bridge_check_denies_openai_provider_with_custom_api_base() -> None:+ # The built-in OPENAI_COMPATIBLE registration (configurable key name) dispatches openai/<model>+ # at an arbitrary api_base that need not implement /v1/responses — deny. Azure legitimately+ # carries an api_base and does bridge.+ from types import SimpleNamespace++ from skyvern.forge.sdk.api.llm.api_handler_factory import LLMCaller+ from skyvern.schemas.llm import LiteLLMParams, LLMConfig++ compat = LLMConfig(+ model_name="openai/gpt-5.6-selfhosted",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ litellm_params=LiteLLMParams(api_base="https://byo.example.internal/v1"),+ )+ compat_self = SimpleNamespace(+ openai_client=None, _custom_openrouter=False, llm_config=compat, original_llm_key="OPENAI_COMPATIBLE"+ )+ assert LLMCaller.uses_openai_responses_bridge(compat_self) is False++ azure = LLMConfig(+ model_name="azure/gpt-5.6-sol-deployment",+ required_env_vars=[],+ supports_vision=True,+ add_assistant_prefix=False,+ reasoning_effort="high",+ litellm_params=LiteLLMParams(api_base="https://example.openai.azure.com"),+ )+ azure_self = SimpleNamespace(+ openai_client=None, _custom_openrouter=False, llm_config=azure, original_llm_key="AZURE_OPENAI_GPT5_6_SOL"+ )+ assert LLMCaller.uses_openai_responses_bridge(azure_self) is Truediff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex 3440a8042..922d3b8f3 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -64,11 +64,20 @@ from skyvern.forge.taskv3.opaque_refs import mask_opaque_urlsclass _ScriptedCaller:"""Emits one queued turn per ``call``. Each turn is a list of (tool_name, args)."""- def __init__(self, script: list[list[tuple[str, dict[str, Any]]]], texts: list[str] | None = None) -> None:+ def __init__(+ self,+ script: list[list[tuple[str, dict[str, Any]]]],+ texts: list[str] | None = None,+ reasoning_contents: list[str | None] | None = None,+ ) -> None:self._script = script# Per-turn assistant text, indexed like `script`; falls back to a fixed placeholder so# existing callers that don't care about the text still get a non-empty one.self._texts = texts+ # Per-turn message.reasoning_content, indexed like `script`. Mirrors the litellm+ # responses-bridge field a real gpt-5.6 call can return; unset by default so existing+ # callers see no reasoning_content key at all, matching a non-bridge response shape.+ self._reasoning_contents = reasoning_contentsself.calls = 0self.message_history: list[dict[str, Any]] = []self.sent_tools: list[dict[str, Any]] | None = None@@ -109,8 +118,13 @@ class _ScriptedCaller:idx = self.callsturn = self._script[idx] if idx < len(self._script) else []text = self._texts[idx] if self._texts and idx < len(self._texts) else "reasoning..."+ reasoning_content = (+ self._reasoning_contents[idx] if self._reasoning_contents and idx < len(self._reasoning_contents) else None+ )self.calls += 1message: dict[str, Any] = {"content": text}+ if reasoning_content is not None:+ message["reasoning_content"] = reasoning_contentif turn:message["tool_calls"] = [{"id": f"call_{i}", "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}@@ -164,9 +178,10 @@ async def _run(tools: list[ToolSpec],*,texts: list[str] | None = None,+ reasoning_contents: list[str | None] | None = None,**kwargs: Any,):- caller = _ScriptedCaller(script, texts=texts)+ caller = _ScriptedCaller(script, texts=texts, reasoning_contents=reasoning_contents)defaults = {"max_turns": 20, "max_tool_calls": 100}defaults.update(kwargs)outcome = await run_agent_tool_loop(@@ -2346,6 +2361,80 @@ async def test_on_action_round_fires_once_per_action_round() -> None:assert round_texts == [texts[1]]+async def test_on_action_round_falls_back_to_reasoning_summary_when_text_empty() -> None:+ # Production gpt-5.6 tool calls arrive with empty message.content; the responses-bridge+ # reasoning summary (message.reasoning_content) is the only readable turn text available.+ round_texts: list[str | None] = []++ async def _on_round(_actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None) -> None:+ round_texts.append(turn_text)++ clk = []+ click = _recording_tool("click", clk)+ click.billable = True+ script = [+ [("click", {"selector": "#a"})],+ [("finish", {"status": "completed", "reason": "ok"})],+ ]+ outcome, _ = await _run(+ script,+ [click, make_finish_tool()],+ on_action_round=_on_round,+ texts=[""],+ reasoning_contents=["clicked the primary submit button"],+ )+ assert outcome.status == "completed"+ assert round_texts == ["clicked the primary submit button"]+++async def test_on_action_round_prefers_content_over_reasoning_summary() -> None:+ round_texts: list[str | None] = []++ async def _on_round(_actions: list[tuple[str, dict[str, Any], bool]], turn_text: str | None) -> None:+ round_texts.append(turn_text)++ clk = []+ click = _recording_tool("click", clk)+ click.billable = True+ script = [+ [("click", {"selector": "#a"})],+ [("finish", {"status": "completed", "reason": "ok"})],+ ]+ outcome, _ = await _run(+ script,+ [click, make_finish_tool()],+ on_action_round=_on_round,+ texts=["typed the field"],+ reasoning_contents=["a reasoning summary that should be ignored"],+ )+ assert outcome.status == "completed"+ assert round_texts == ["typed the field"]+++async def test_transcript_content_stays_none_when_text_empty_despite_reasoning_summary() -> None:+ # PERSISTENCE-ONLY contract: the reasoning summary reaches on_action_round (asserted above)+ # but must never enter the transcript the model re-reads next turn -- only actual message+ # content does.+ clk = []+ click = _recording_tool("click", clk)+ click.billable = True+ script = [+ [("click", {"selector": "#a"})],+ [("finish", {"status": "completed", "reason": "ok"})],+ ]+ outcome, _ = await _run(+ script,+ [click, make_finish_tool()],+ texts=["", "done"],+ reasoning_contents=["a readable summary that must stay out of the transcript"],+ )+ assistant_messages = [m for m in outcome.messages if m.get("role") == "assistant"]+ assert assistant_messages[0]["content"] is None++@pytest.mark.asyncioasync def test_on_action_round_fires_for_all_failed_round_with_failure_flag() -> None:# A dispatched billable round consumes budget even when every call errors; it must reach the@@ -8555,3 +8644,76 @@ async def test_auto_observe_consumes_a_refresh_signal_the_observe_handler_raisesfires = [e for e in logs if e.get("event") == "taskv3 auto observe"]refresh_fires = [f for f in fires if f.get("fired") is False and f.get("reason") == "refresh"]assert len(refresh_fires) == 1+++class _ReasoningDictSensitiveCaller(_ScriptedCaller):+ """Rejects any call carrying a dict reasoning_effort, as a provider without the responses+ bridge would."""++ def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:+ super().__init__(script)+ self.reasoning_per_call: list[Any] = []++ async def call(self, **kwargs: Any) -> dict[str, Any]:+ self.reasoning_per_call.append(kwargs.get("reasoning_effort"))+ if isinstance(kwargs.get("reasoning_effort"), dict):+ raise LLMProviderErrorRetryableTask("TEST_KEY")+ return await super().call(**kwargs)+++async def test_loop_drops_reasoning_dict_and_retries_the_turn_after_a_call_failure() -> None:+ # A bridge-gate false positive must degrade to the config's own reasoning_effort, not end the+ # run on turn 1.+ caller = _ReasoningDictSensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])+ outcome = await run_agent_tool_loop(+ llm_caller=caller,+ system_prompt="sys",+ user_prompt="goal",+ tools=[make_finish_tool()],+ max_turns=5,+ max_tool_calls=10,+ call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}},+ retryable_call_exceptions=(LLMProviderErrorRetryableTask,),+ max_call_retries=2,+ call_retry_base_delay=0.0,+ )++ assert outcome.status == "completed"+ dict_calls = [r for r in caller.reasoning_per_call if isinstance(r, dict)]+ assert dict_calls and caller.reasoning_per_call[-1] is None+++class _ReasoningDictOnlySensitiveCaller(_ScriptedCaller):+ """Rejects only the dict reasoning_effort; tool_choice is independently supported."""++ def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:+ super().__init__(script)+ self.kwargs_per_call: list[tuple[Any, Any]] = []++ async def call(self, **kwargs: Any) -> dict[str, Any]:+ self.kwargs_per_call.append((kwargs.get("reasoning_effort"), kwargs.get("tool_choice")))+ if isinstance(kwargs.get("reasoning_effort"), dict):+ raise LLMProviderErrorRetryableTask("TEST_KEY")+ return await super().call(**kwargs)+++async def test_degrading_the_summary_dict_keeps_tool_choice() -> None:+ caller = _ReasoningDictOnlySensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])+ outcome = await run_agent_tool_loop(+ llm_caller=caller,+ system_prompt="sys",+ user_prompt="goal",+ tools=[make_finish_tool()],+ max_turns=5,+ max_tool_calls=10,+ call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}, "tool_choice": "required"},+ retryable_call_exceptions=(LLMProviderErrorRetryableTask,),+ max_call_retries=2,+ call_retry_base_delay=0.0,+ )+ assert outcome.status == "completed"+ final_reasoning, final_tool_choice = caller.kwargs_per_call[-1]+ assert final_reasoning is None+ assert final_tool_choice == "required"