Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Route reasoning_effort via extra_body on the partner-hosted DeepSeek config (SKY-12750) (#7938)
Shuchang Zheng7314beaa428e
diff --git a/skyvern/cli/core/mcp_http_auth.py b/skyvern/cli/core/mcp_http_auth.pyindex da6486814..0866ac3ab 100644--- a/skyvern/cli/core/mcp_http_auth.py+++ b/skyvern/cli/core/mcp_http_auth.py@@ -622,7 +622,7 @@ class MCPAPIKeyMiddleware:AccessToken(token="mcp-http-session-owner",client_id=organization_id,- subject=hash_api_key_for_cache(api_key),+ subject=hashlib.sha256(api_key.encode("utf-8")).hexdigest(),scopes=[],))diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex cbcc2cc87..4396f0c27 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -2242,10 +2242,12 @@ class AgentFunction:return Nonedef try_import_static_script(self, script_path: str) -> Any | None:- """Try to import a static script module as a fallback when spec_from_file_location fails.+ """Import the live platform module for a static (marker) pin.- Override in subclass for platform-specific import logic.- Returns the loaded module or None.+ The loader calls this BEFORE exec-ing the stored script body, so marker+ pins always run the deployed module. Override in subclass for+ platform-specific import logic. Returns the loaded module, or None for+ a markerless (generated) script or a failed import."""return Nonediff --git a/skyvern/forge/sdk/copilot/model_resolver.py b/skyvern/forge/sdk/copilot/model_resolver.pyindex 1ea8e3512..86fdbf9dd 100644--- a/skyvern/forge/sdk/copilot/model_resolver.py+++ b/skyvern/forge/sdk/copilot/model_resolver.py@@ -55,7 +55,7 @@ _REGISTRY_STYLE_ALIAS = re.compile(r"[A-Z0-9]+(?:[-_.][A-Z0-9]+)*")# Keys in litellm_params that are routed elsewhere (top-level kwargs to# LitellmModel or the dedicated ModelSettings.extra_headers slot), so they# don't count as "unrouted" when we log dropped keys.-_TOP_LEVEL_ROUTED_FIELDS = frozenset({"api_base", "api_key", "extra_headers"})+_TOP_LEVEL_ROUTED_FIELDS = frozenset({"api_base", "api_key", "extra_headers", "extra_body"})# LiteLLMParams fields that LiteLLM consumes as call-level kwargs (splatted# via ``extra_args`` by the Agents SDK into ``litellm.acompletion(**kwargs)``).@@ -207,6 +207,7 @@ def resolve_model_config(extra_args: dict[str, Any] = {}extra_headers: dict[str, str] | None = None+ extra_body: dict[str, Any] | None = Nonebase_url: str | None = Noneapi_key: str | None = None@@ -236,6 +237,10 @@ def resolve_model_config(if headers:extra_headers = dict(headers)+ body = lp.get("extra_body")+ if body:+ extra_body = dict(body)+# Warn if litellm_params has keys we don't explicitly route. Covers both# future additions to the LiteLLMParams TypedDict and runtime-only keys# (typos, dynamically-injected values). Without this, such keys are@@ -263,6 +268,7 @@ def resolve_model_config(include_usage=True,extra_args=extra_args or None,extra_headers=extra_headers,+ extra_body=extra_body,)provider = CopilotLitellmProvider(base_url=base_url, api_key=api_key)diff --git a/skyvern/forge/sdk/routes/__init__.py b/skyvern/forge/sdk/routes/__init__.pyindex d8c4f8495..a5087d704 100644--- a/skyvern/forge/sdk/routes/__init__.py+++ b/skyvern/forge/sdk/routes/__init__.py@@ -1,5 +1,8 @@import importlib.util+# `streaming` is imported by name below because the `from ...routes.streaming import x` lines+# bind only x: a re-import of this package that leaves the subpackage itself cached in+# sys.modules would otherwise rebuild it with no `streaming` attribute for patch targets to walk.from skyvern.forge.sdk.routes import agent_protocol # noqa: F401from skyvern.forge.sdk.routes import browser_profiles # noqa: F401from skyvern.forge.sdk.routes import browser_sessions # noqa: F401@@ -12,6 +15,7 @@ from skyvern.forge.sdk.routes import runtime_config # noqa: F401from skyvern.forge.sdk.routes import scripts # noqa: F401from skyvern.forge.sdk.routes import sdk # noqa: F401from skyvern.forge.sdk.routes import self_heal # noqa: F401+from skyvern.forge.sdk.routes import streaming # noqa: F401from skyvern.forge.sdk.routes import webhooks # noqa: F401from skyvern.forge.sdk.routes import workflow_schedules # noqa: F401from skyvern.forge.sdk.routes.streaming import cdp_input # noqa: F401diff --git a/skyvern/forge/sdk/services/oauth_consent.py b/skyvern/forge/sdk/services/oauth_consent.pyindex ade57d16e..02caf8ed4 100644--- a/skyvern/forge/sdk/services/oauth_consent.py+++ b/skyvern/forge/sdk/services/oauth_consent.py@@ -10,6 +10,7 @@ a challenge started by someone else simply resolves to a row that does not existfrom __future__ import annotationsimport hashlib+import hmacimport secretsfrom skyvern.config import settings@@ -17,7 +18,6 @@ from skyvern.config import settings# Callers with no resolvable user (raw API key, no UI session) share this binding; they# already hold org-wide credentials, so there is no narrower identity to bind them to._UNIDENTIFIED_INITIATOR = "\x00unidentified"-_CONSENT_NONCE_KDF_ITERATIONS = 120_000def generate_consent_state() -> str:@@ -32,9 +32,4 @@ def consent_nonce(state: str, initiator_id: str | None) -> str:such callback fails the lookup instead of falling through to the token exchange."""material = f"{initiator_id or _UNIDENTIFIED_INITIATOR}\x00{state}".encode()- return hashlib.pbkdf2_hmac(- "sha256",- settings.SECRET_KEY.encode(),- material,- _CONSENT_NONCE_KDF_ITERATIONS,- ).hex()+ return hmac.new(settings.SECRET_KEY.encode(), material, hashlib.sha256).hexdigest()diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 9fd06555a..01212c239 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -923,23 +923,48 @@ class Block(BaseModel, abc.ABC):},exclude_none=True,)+ # The description is a pure function of the rendered prompt, and a+ # workflow's blocks are identical run over run — cache on a hash of the+ # prompt itself so repeat runs skip the LLM call entirely and a template+ # change naturally invalidates the cache. output_parameter is reduced to+ # its key first: its row ids/timestamps vary per workflow revision+ # without changing what the description says. Cache failures fall+ # through to generation; only non-empty summaries are cached.+ prompt_block_data = dict(block_data)+ output_parameter_data = prompt_block_data.get("output_parameter")+ if isinstance(output_parameter_data, dict):+ prompt_block_data["output_parameter"] = output_parameter_data.get("key")description_generation_prompt = prompt_engine.load_prompt("generate_workflow_run_block_description",- block=block_data,- )- json_response = await app.SECONDARY_LLM_API_HANDLER(- prompt=description_generation_prompt,- prompt_name="generate-workflow-run-block-description",- workflow_run_block_id=workflow_run_block_id,- organization_id=organization_id,- )- description = json_response.get("summary")- LOG.info(- "Generated description for the workflow run block",- sampling=True,- description=description,- workflow_run_block_id=workflow_run_block_id,+ block=prompt_block_data,)+ cache_key = "wrb-description:" + hashlib.sha256(description_generation_prompt.encode()).hexdigest()+ try:+ cached_description = await app.CACHE.get(cache_key)+ except Exception:+ LOG.debug("Failed to read cached workflow run block description", exc_info=True)+ cached_description = None+ if isinstance(cached_description, str) and cached_description:+ description = cached_description+ else:+ json_response = await app.SECONDARY_LLM_API_HANDLER(+ prompt=description_generation_prompt,+ prompt_name="generate-workflow-run-block-description",+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ description = json_response.get("summary")+ LOG.info(+ "Generated description for the workflow run block",+ sampling=True,+ description=description,+ workflow_run_block_id=workflow_run_block_id,+ )+ if isinstance(description, str) and description:+ try:+ await app.CACHE.set(cache_key, description)+ except Exception:+ LOG.debug("Failed to cache workflow run block description", exc_info=True)except Exception as e:LOG.exception("Failed to generate description for the workflow run block", error=e)diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 323362949..119b11a95 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -601,6 +601,52 @@ def _resolve_first_block_url(return None+# Written by ensure_static_script as the first line of a static pin's main.py;+# must stay in sync with try_import_static_script's marker parsing.+_STATIC_MODULE_MARKER = "# __static_module__: "+++def _script_has_static_module_marker(script_path: str) -> bool:+ try:+ with open(script_path) as script_file:+ return script_file.readline().startswith(_STATIC_MODULE_MARKER)+ except OSError:+ return False+++def _load_user_script_module(script_path: str, spec: "importlib.machinery.ModuleSpec") -> Any | None:+ """Load a cached script's main.py for execution.++ Static (marker) pins must import the live platform module FIRST: the stored+ main.py is a point-in-time copy of the platform script, and exec-ing it+ silently shadows every fix shipped since the pin was created+ (``_pinned_script_is_current_static`` keeps such pins on the promise that+ the loader imports the deployed module). A marker pin whose live import+ fails loads as None — blocks drop to the agent — because exec-ing its+ stored body would resurrect the same staleness, and the marker-only pin+ check would never supersede it. Only a markerless pin (a generated script)+ executes its stored body.+ """+ loaded_script_module = app.AGENT_FUNCTION.try_import_static_script(script_path)+ if loaded_script_module is not None:+ return loaded_script_module+ if _script_has_static_module_marker(script_path):+ LOG.warning(+ "Static pin's live module import failed; refusing to exec the stale stored body",+ script_path=script_path,+ )+ return None+ if not spec.loader:+ return None+ loaded_script_module = importlib.util.module_from_spec(spec)+ try:+ spec.loader.exec_module(loaded_script_module)+ except Exception:+ LOG.warning("exec_module failed for stored script body", script_path=script_path, exc_info=True)+ return None+ return loaded_script_module++_RUN_SIGNATURE_CACHE_KEY_RE = re.compile(r"""cache_key\s*=\s*(['"])(?P<key>.+?)\1""")@@ -3923,15 +3969,7 @@ class WorkflowService:spec = importlib.util.spec_from_file_location("user_script", script_path)if spec and spec.loader:- loaded_script_module = importlib.util.module_from_spec(spec)- try:- spec.loader.exec_module(loaded_script_module)- except Exception:- # Static scripts may fail with spec_from_file_location- # due to circular imports. Delegate to AgentFunction for- # platform-specific fallback loading.- LOG.warning("exec_module failed, trying import_module fallback", exc_info=True)- loaded_script_module = app.AGENT_FUNCTION.try_import_static_script(script_path)+ loaded_script_module = _load_user_script_module(script_path, spec)param_cls = (getattr(loaded_script_module, "GeneratedWorkflowParameters", None)if loaded_script_modulediff --git a/skyvern/schemas/llm.py b/skyvern/schemas/llm.pyindex 510f2292f..d026b6a30 100644--- a/skyvern/schemas/llm.py+++ b/skyvern/schemas/llm.py@@ -49,6 +49,11 @@ class LiteLLMParams(TypedDict, total=False):service_tier: str | Noneextra_headers: dict[str, str] | Nonetimeout: float | None+ # Raw request-body keys, passed through without LiteLLM's per-provider+ # translation. Use only when a provider accepts a param that LiteLLM would+ # strip under drop_params=True (unrecognized model + provider pairing);+ # prefer a real field above whenever LiteLLM knows how to translate it.+ extra_body: dict[str, Any] | Nonedef _settings() -> Any:diff --git a/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.py b/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.pyindex 906b28a71..5d8ffd64c 100644--- a/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.py+++ b/tests/unit/forge/sdk/routes/streaming/test_vnc_routed_url.py@@ -13,7 +13,7 @@ from types import SimpleNamespaceimport pytestfrom skyvern.exceptions import MissingRoutedVncAddressError-from skyvern.forge.sdk.routes.streaming.channels import vnc as vnc_channel+from skyvern.forge.sdk.routes.streaming.channels import vncfrom skyvern.forge.sdk.routes.streaming.channels.vnc import (_build_vnc_url_from_browser_address,loop_stream_vnc,@@ -89,7 +89,7 @@ async def test_a_session_with_no_routable_address_fails_instead_of_streaming(dialed.append(url)raise AssertionError("live view must not dial when no routed address exists")- monkeypatch.setattr(vnc_channel.websockets, "connect", _record_connect)+ monkeypatch.setattr(vnc.websockets, "connect", _record_connect)with pytest.raises(MissingRoutedVncAddressError):await loop_stream_vnc(_channel(POD_ADDRESS)) # type: ignore[arg-type]diff --git a/tests/unit/forge/sdk/routes/test_routes_package.py b/tests/unit/forge/sdk/routes/test_routes_package.pynew file mode 100644index 000000000..adc6c3acb--- /dev/null+++ b/tests/unit/forge/sdk/routes/test_routes_package.py@@ -0,0 +1,33 @@+"""What the routes package has to keep exposing as attributes (SKY-13287).++Patch targets are dotted strings that both pytest and unittest.mock resolve by walking+attributes, so anything reachable at skyvern.forge.sdk.routes.<x> has to stay reachable that way.+"""++from __future__ import annotations++import importlib+import sys++import skyvern.forge.sdk+import skyvern.forge.sdk.routes # noqa: F401++ROUTES = "skyvern.forge.sdk.routes"+STREAMING = "skyvern.forge.sdk.routes.streaming"+++def test_streaming_survives_a_re_import_that_leaves_the_subpackage_cached() -> None:+ """A fresh import binds routes.streaming through the import machinery. A re-import that+ evicts only the parent does not, because the subpackage is served from sys.modules and never+ loaded again - so routes/__init__.py has to bind the name itself."""+ original = sys.modules[ROUTES]+ del sys.modules[ROUTES]++ try:+ rebuilt = importlib.import_module(ROUTES)++ assert rebuilt is not original+ assert rebuilt.streaming is sys.modules[STREAMING]+ finally:+ sys.modules[ROUTES] = original+ skyvern.forge.sdk.routes = originaldiff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.pyindex 25efe44b0..4959ee497 100644--- a/tests/unit/test_api_handler_factory.py+++ b/tests/unit/test_api_handler_factory.py@@ -1750,3 +1750,56 @@ async def test_truncation_retry_skipped_when_fallback_served(monkeypatch: pytestawait handler(prompt='{"actions": []}', prompt_name="extract-actions")assert router_cls.last_instance.calls == ["primary-group"]+++async def test_extra_body_from_litellm_params_reaches_completion(monkeypatch: pytest.MonkeyPatch) -> None:+ """litellm_params["extra_body"] must survive to the acompletion call.++ A top-level reasoning_effort is stripped by drop_params=True whenever LiteLLM+ does not recognize the model as a reasoning model, which silently disables+ thinking on custom OpenAI-compatible deployments. extra_body is the escape+ hatch: LiteLLM forwards it verbatim, so it must not be swallowed en route.+ """+ context = MagicMock()+ context.vertex_cache_name = None+ context.use_prompt_caching = False+ context.cached_static_prompt = None+ context.hashed_href_map = {}++ llm_config = LLMConfig(+ model_name="openai/some-custom-deployment",+ required_env_vars=[],+ supports_vision=False,+ add_assistant_prefix=False,+ litellm_params={+ "api_key": "test-key",+ "api_base": "https://llm.example.test/openai/v1",+ "extra_body": {"reasoning_effort": "high"},+ },+ )++ monkeypatch.setattr(+ "skyvern.forge.sdk.api.llm.api_handler_factory.LLMConfigRegistry.get_config", lambda _: llm_config+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.api.llm.api_handler_factory.LLMConfigRegistry.is_router_config", lambda _: False+ )+ monkeypatch.setattr("skyvern.forge.sdk.api.llm.api_handler_factory.skyvern_context.current", lambda: context)+ monkeypatch.setattr(+ api_handler_factory, "llm_messages_builder", AsyncMock(return_value=[{"role": "user", "content": "test"}])+ )+ monkeypatch.setattr(api_handler_factory.litellm, "completion_cost", lambda _: 0.0)++ completion_params: dict[str, Any] = {}++ async def mock_acompletion(*args: Any, **kwargs: Any) -> FakeLLMResponse:+ completion_params.update(kwargs)+ return FakeLLMResponse("some-custom-deployment")++ monkeypatch.setattr(api_handler_factory.litellm, "acompletion", AsyncMock(side_effect=mock_acompletion))++ handler = LLMAPIHandlerFactory.get_llm_api_handler("TEST_EXTRA_BODY_PASSTHROUGH")+ await handler(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME)++ assert completion_params["extra_body"] == {"reasoning_effort": "high"}diff --git a/tests/unit/test_block_description_caching.py b/tests/unit/test_block_description_caching.pyindex 2bdc97bab..9ba9cc1ff 100644--- a/tests/unit/test_block_description_caching.py+++ b/tests/unit/test_block_description_caching.py@@ -1,8 +1,11 @@-"""Tests for skipping block description LLM calls on for-loop iterations.+"""Tests for skipping block description LLM calls on for-loop iterations,+and for the content-hash cache that skips regeneration across runs.Validates that execute_safe only dispatches description generation whencurrent_index is None (not in a loop) or 0 (first iteration), and skips-it for current_index > 0 (subsequent iterations).+it for current_index > 0 (subsequent iterations). Also validates that+_generate_workflow_run_block_description serves identical block configs+from app.CACHE instead of re-calling the LLM every run."""from datetime import UTC, datetime@@ -122,3 +125,71 @@ class TestDescriptionSkippedOnLoopIterations:await block.execute_safe(workflow_run_id="wr_1", current_index=i)assert mock_gen_desc.call_count == 1+++class TestDescriptionContentHashCache:+ def _patch_app(self, mock_app: MagicMock, cached: object = None, cache_error: bool = False) -> AsyncMock:+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()+ if cache_error:+ mock_app.CACHE.get = AsyncMock(side_effect=RuntimeError("redis down"))+ mock_app.CACHE.set = AsyncMock(side_effect=RuntimeError("redis down"))+ else:+ mock_app.CACHE.get = AsyncMock(return_value=cached)+ mock_app.CACHE.set = AsyncMock()+ llm = AsyncMock(return_value={"summary": "fresh summary"})+ mock_app.SECONDARY_LLM_API_HANDLER = llm+ return llm++ @pytest.mark.asyncio+ async def test_cache_hit_skips_llm_call(self) -> None:+ block = _make_block()+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:+ llm = self._patch_app(mock_app, cached="cached summary")++ await block._generate_workflow_run_block_description("wrb_1", "org_1")++ llm.assert_not_called()+ mock_app.DATABASE.observer.update_workflow_run_block.assert_awaited_once()+ assert (+ mock_app.DATABASE.observer.update_workflow_run_block.await_args.kwargs["description"]+ == "cached summary"+ )++ @pytest.mark.asyncio+ async def test_cache_miss_generates_and_stores(self) -> None:+ block = _make_block()+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:+ llm = self._patch_app(mock_app, cached=None)++ await block._generate_workflow_run_block_description("wrb_1", "org_1")++ llm.assert_awaited_once()+ mock_app.CACHE.set.assert_awaited_once()+ key, value = mock_app.CACHE.set.await_args.args+ assert key.startswith("wrb-description:")+ assert value == "fresh summary"++ @pytest.mark.asyncio+ async def test_identical_blocks_share_a_cache_key(self) -> None:+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:+ self._patch_app(mock_app, cached=None)++ await _make_block()._generate_workflow_run_block_description("wrb_1", "org_1")+ await _make_block()._generate_workflow_run_block_description("wrb_2", "org_1")++ keys = {call.args[0] for call in mock_app.CACHE.get.await_args_list}+ assert len(keys) == 1++ @pytest.mark.asyncio+ async def test_cache_errors_fall_through_to_generation(self) -> None:+ block = _make_block()+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:+ llm = self._patch_app(mock_app, cache_error=True)++ await block._generate_workflow_run_block_description("wrb_1", "org_1")++ llm.assert_awaited_once()+ mock_app.DATABASE.observer.update_workflow_run_block.assert_awaited_once()+ assert (+ mock_app.DATABASE.observer.update_workflow_run_block.await_args.kwargs["description"] == "fresh summary"+ )diff --git a/tests/unit/test_copilot_model_resolver.py b/tests/unit/test_copilot_model_resolver.pyindex efecfb28c..8a67e90be 100644--- a/tests/unit/test_copilot_model_resolver.py+++ b/tests/unit/test_copilot_model_resolver.py@@ -235,6 +235,7 @@ class TestModelResolver:"thinking_level": "high","service_tier": "flex","extra_headers": {"X-Skyvern-Route": "copilot"},+ "extra_body": {"reasoning_effort": "high"},"timeout": 900.0,}config = LLMConfig(@@ -252,6 +253,7 @@ class TestModelResolver:assert ms is not Noneassert ms.extra_headers == {"X-Skyvern-Route": "copilot"}+ assert ms.extra_body == {"reasoning_effort": "high"}assert ms.extra_args is not Noneassert ms.extra_args["thinking"] == lp["thinking"]