Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add organization IDs to invalid custom LLM warnings (SKY-15488) (#8422)
LawyZheng603963f144b6
diff --git a/skyvern/constants.py b/skyvern/constants.pyindex d3fd8ef9a..68f0f7a54 100644--- a/skyvern/constants.py+++ b/skyvern/constants.py@@ -43,6 +43,20 @@ PROXY_SENSITIVE_NAV_ERRORS = (# The outer context-recreation retry in get_or_create_page may still attempt# recovery for proxy-sensitive errors by picking a different proxy node.SKIP_INNER_NAV_RETRY_ERRORS = PERMANENT_NAV_ERRORS + PROXY_SENSITIVE_NAV_ERRORS+# The subset of PROXY_SENSITIVE_NAV_ERRORS that attributes a navigation failure to our own+# egress rather than to the site. PROXY_SENSITIVE_NAV_ERRORS is deliberately wider because it+# answers a different question -- whether retrying on a different proxy node is worth it -- and+# it includes cert failures a plain expired certificate on the target site also produces.+# ERR_CERT_AUTHORITY_INVALID is the one cert code that means an untrusted issuer, i.e. something+# terminating TLS in front of us.+EGRESS_ATTRIBUTABLE_NAV_ERRORS = (+ "net::ERR_TUNNEL_CONNECTION_FAILED",+ "net::ERR_SOCKS_CONNECTION_FAILED",+ "net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE",+ "net::ERR_NAME_NOT_RESOLVED",+ "net::ERR_NAME_RESOLUTION_FAILED",+ "net::ERR_CERT_AUTHORITY_INVALID",+)AUTO_COMPLETION_POTENTIAL_VALUES_COUNT = 3DROPDOWN_MENU_MAX_DISTANCE = 100diff --git a/skyvern/forge/sdk/api/llm/custom_llm_registry.py b/skyvern/forge/sdk/api/llm/custom_llm_registry.pyindex 2afff04d7..4f166d75e 100644--- a/skyvern/forge/sdk/api/llm/custom_llm_registry.py+++ b/skyvern/forge/sdk/api/llm/custom_llm_registry.py@@ -188,6 +188,7 @@ async def load_custom_llm_configs_for_organization(database: AgentDB, organizatiLOG.warning("Skipping invalid custom LLM config",custom_llm_id=token.id,+ organization_id=token.organization_id,error_type=type(exc).__name__,)continue@@ -236,6 +237,7 @@ async def ensure_custom_llm_registered_for_org(LOG.warning("Skipping invalid custom LLM config",custom_llm_id=token.id,+ organization_id=token.organization_id,error_type=type(exc).__name__,)return False@@ -275,6 +277,7 @@ async def load_custom_llm_configs_from_database(database: AgentDB) -> None:LOG.warning("Skipping invalid custom LLM config",custom_llm_id=token.id,+ organization_id=token.organization_id,error_type=type(exc).__name__,)continuediff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 538f94bb2..9a6c07eb0 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -268,7 +268,12 @@ from skyvern.webeye.browser_factory import rebind_download_dirfrom skyvern.webeye.browser_object_predicates import is_page_likefrom skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnosticfrom skyvern.webeye.cdp_download_interceptor import normalize_download_filename, settle_browser_downloads_for_context-from skyvern.webeye.navigation import default_navigation_settle, navigate_with_retry, redact_url_secrets+from skyvern.webeye.navigation import (+ default_navigation_settle,+ is_egress_attributable_navigation_error,+ navigate_with_retry,+ redact_url_secrets,+)from skyvern.webeye.playwright_input import playwright_input_defaults_for_pagefrom skyvern.webeye.real_browser_state import RealBrowserStatefrom skyvern.webeye.utils.captcha_solver import CaptchaChallengeUnsolvedError, solve_challenge_ladder@@ -1968,11 +1973,32 @@ class BaseTaskBlock(Block):)except Exception as e:- LOG.exception(- "Failed to get browser state for first task",- task_id=task.task_id,- workflow_run_id=workflow_run_id,- )+ if (+ isinstance(e, FailedToNavigateToUrl)+ and not isinstance(e, BlockedNavigationDestination)+ and not is_egress_attributable_navigation_error(e.error_message)+ ):+ # The target site did not load. Site-caused, and already surfaced on the run+ # through the failure_reason recorded below. Two classes stay at error+ # because they are ours rather than the site's: BlockedNavigationDestination+ # is the SSRF guard tripping, and EGRESS_ATTRIBUTABLE_NAV_ERRORS is our own+ # egress failing, which get_or_create_page may recover from on a different+ # proxy node. The block-execution handler above applies only the first of+ # those two carve-outs; see the PR discussion.+ LOG.warning(+ "Failed to get browser state for first task",+ task_id=task.task_id,+ workflow_run_id=workflow_run_id,+ url=e.url,+ exc_info=True,+ )+ else:+ LOG.exception(+ "Failed to get browser state for first task",+ task_id=task.task_id,+ workflow_run_id=workflow_run_id,+ url=getattr(e, "url", None),+ )await self._handle_task_failure_with_error_detection(task=task,step=step,diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex e2d0de170..0ef5817b8 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -5038,7 +5038,10 @@ class ActionHandler:LOG.exception("LLM error in action handler", action=action, exc_info=True)actions_result.append(ActionFailure(e))except ImaginarySecretValue as e:- LOG.exception("Imaginary secret value", action=action, exc_info=True)+ # The model referenced a secret placeholder that is not in the run's secrets. Handled:+ # it becomes an ActionFailure below and reaches the run that way. Warning rather than+ # info because it is secret-adjacent.+ LOG.warning("Imaginary secret value", action=action, exc_info=True)actions_result.append(ActionFailure(e))except CaptchaSolveError as e:LOG.warning(diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.pyindex 598bec719..5eaff361a 100644--- a/skyvern/webeye/navigation.py+++ b/skyvern/webeye/navigation.py@@ -9,7 +9,11 @@ from urllib.parse import urlsplitimport structlogfrom skyvern.config import settings-from skyvern.constants import PERMANENT_NAV_ERRORS, SKIP_INNER_NAV_RETRY_ERRORS+from skyvern.constants import (+ EGRESS_ATTRIBUTABLE_NAV_ERRORS,+ PERMANENT_NAV_ERRORS,+ SKIP_INNER_NAV_RETRY_ERRORS,+)from skyvern.exceptions import BlockedHost, BlockedNavigationDestination, FailedToNavigateToUrl, InvalidUrlfrom skyvern.utils.url_validators import canonical_navigation_host, is_blocked_host@@ -118,6 +122,10 @@ def is_permanent_navigation_error(error_message: str) -> bool:return any(pattern in error_message for pattern in PERMANENT_NAV_ERRORS)+def is_egress_attributable_navigation_error(error_message: str) -> bool:+ return any(pattern in error_message for pattern in EGRESS_ATTRIBUTABLE_NAV_ERRORS)++def redact_url_secrets(url: str) -> str:"""Reduce a URL to scheme and host for display.diff --git a/tests/unit/test_custom_llms.py b/tests/unit/test_custom_llms.pyindex 87054c24f..5f36b5257 100644--- a/tests/unit/test_custom_llms.py+++ b/tests/unit/test_custom_llms.py@@ -5,6 +5,7 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+import structlogfrom skyvern.config import settingsfrom skyvern.exceptions import BlockedHost, SkyvernHTTPException@@ -1115,3 +1116,90 @@ def test_custom_ollama_chat_models_skip_max_token_parameters() -> None:assert "max_completion_tokens" not in paramsassert "max_tokens" not in paramsassert params["temperature"] == 0.1+++_LEAK_CANARY = "custom-llm-leak-canary"+_INVALID_CONFIG_JSON = '{"provider": "gemini", "api_key": "' + _LEAK_CANARY + '"}'+_ALLOWED_WARNING_KEYS = {"event", "log_level", "custom_llm_id", "organization_id", "error_type"}+++def _invalid_custom_llm_token(token_id: str, organization_id: str) -> OrganizationAuthToken:+ now = datetime.now(timezone.utc)+ return OrganizationAuthToken(+ id=token_id,+ organization_id=organization_id,+ token_type=OrganizationAuthTokenType.custom_llm,+ token=_INVALID_CONFIG_JSON,+ valid=True,+ created_at=now,+ modified_at=now,+ )+++def _skipping_warnings(logs: list[dict]) -> list[dict]:+ return [entry for entry in logs if entry.get("event") == "Skipping invalid custom LLM config"]+++def _assert_no_payload_leak(logs: list[dict]) -> None:+ assert _LEAK_CANARY not in repr(logs)+ for entry in _skipping_warnings(logs):+ assert set(entry) <= _ALLOWED_WARNING_KEYS+ for forbidden in ("token", "api_key", "api_base", "config", "exception", "exc_info", "traceback"):+ assert forbidden not in entry+++async def test_load_all_orgs_warns_with_organization_id(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(custom_llm_registry, "_custom_llm_configs", {})+ organizations = FakeOrganizationsRepository()+ organizations.tokens.append(_invalid_custom_llm_token("oat_batch_invalid", "o_batch"))+ database = SimpleNamespace(organizations=organizations)++ with structlog.testing.capture_logs() as logs:+ await custom_llm_registry.load_custom_llm_configs_from_database(database)++ warnings = _skipping_warnings(logs)+ assert len(warnings) == 1+ assert warnings[0]["organization_id"] == "o_batch"+ assert warnings[0]["custom_llm_id"] == "oat_batch_invalid"+ assert warnings[0]["error_type"] == "ValidationError"+ _assert_no_payload_leak(logs)+++async def test_load_org_configs_warns_with_organization_id(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(custom_llm_registry, "_custom_llm_configs", {})+ organizations = FakeOrganizationsRepository()+ organizations.tokens.append(_invalid_custom_llm_token("oat_org_invalid", "o_single"))+ database = SimpleNamespace(organizations=organizations)++ with structlog.testing.capture_logs() as logs:+ await custom_llm_registry.load_custom_llm_configs_for_organization(database, "o_single")++ warnings = _skipping_warnings(logs)+ assert len(warnings) == 1+ assert warnings[0]["organization_id"] == "o_single"+ assert warnings[0]["custom_llm_id"] == "oat_org_invalid"+ assert warnings[0]["error_type"] == "ValidationError"+ _assert_no_payload_leak(logs)+++async def test_ensure_registered_warns_with_organization_id(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(custom_llm_registry, "_custom_llm_configs", {})+ organizations = FakeOrganizationsRepository()+ organizations.tokens.append(_invalid_custom_llm_token("oat_ensure_invalid", "o_ensure"))+ database = SimpleNamespace(organizations=organizations)++ with structlog.testing.capture_logs() as logs:+ registered = await custom_llm_registry.ensure_custom_llm_registered_for_org(+ "oat_ensure_invalid", "o_ensure", database+ )++ assert registered is False+ warnings = _skipping_warnings(logs)+ assert len(warnings) == 1+ assert warnings[0]["organization_id"] == "o_ensure"+ assert warnings[0]["custom_llm_id"] == "oat_ensure_invalid"+ assert warnings[0]["error_type"] == "ValidationError"+ _assert_no_payload_leak(logs)diff --git a/tests/unit/test_missing_starter_url.py b/tests/unit/test_missing_starter_url.pyindex 6ee454df9..76c2f6bd3 100644--- a/tests/unit/test_missing_starter_url.py+++ b/tests/unit/test_missing_starter_url.py@@ -17,7 +17,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest-from skyvern.exceptions import InvalidWorkflowTaskURLState, MissingStarterUrl+from skyvern.exceptions import FailedToNavigateToUrl, InvalidWorkflowTaskURLState, MissingStarterUrlfrom skyvern.forge.agent import ForgeAgent, resolve_inherited_workflow_task_pagefrom skyvern.forge.sdk.schemas.tasks import TaskStatusfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext@@ -121,6 +121,7 @@ def _mock_block_execute_deps(working_page_url: str) -> Iterator[dict[str, Any]]:"tasks_db": tasks_db,"agent": agent,"browser_state": browser_state,+ "browser_manager": browser_manager,}@@ -169,6 +170,56 @@ async def test_execute_fails_early_when_first_block_has_no_url(blank_url: str) -)+ ("error_message", "expect_level"),+ [+ ("Page.goto: net::ERR_CERT_DATE_INVALID at https://vendor.example.com/", "warning"),+ ("Page.goto: net::ERR_CONNECTION_REFUSED at https://vendor.example.com/", "warning"),+ ("Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://vendor.example.com/", "exception"),+ ("Page.goto: net::ERR_NAME_NOT_RESOLVED at https://vendor.example.com/", "exception"),+ ("Page.goto: net::ERR_CERT_AUTHORITY_INVALID at https://vendor.example.com/", "exception"),+ ],+ ids=["expired_cert", "connection_refused", "tunnel", "dns", "untrusted_ca"],+)+async def test_first_task_navigation_failure_log_level_splits_site_from_egress(+ error_message: str, expect_level: str+) -> None:+ """A site that will not load is the customer's problem and is already on the run via+ failure_reason, so it logs at warning. Our own egress failing -- proxy tunnel, SOCKS, DNS, or a+ TLS interceptor we do not trust -- must keep an error-level record, because that is a+ proxy-pool signal nothing else pages on. Dropping the egress guard makes the last three+ cases warn."""++ block = TaskBlock(+ label="open_vendor_url",+ output_parameter=_output_parameter(),+ title="Open vendor URL",+ url="https://vendor.example.com/",+ )++ with _mock_block_execute_deps(working_page_url="https://vendor.example.com/") as deps:+ deps["browser_manager"].get_or_create_for_workflow_run = AsyncMock(+ side_effect=FailedToNavigateToUrl(url="https://vendor.example.com/", error_message=error_message)+ )+ with patch("skyvern.forge.sdk.workflow.models.block.LOG") as log_mock:+ with pytest.raises(FailedToNavigateToUrl):+ await block.execute(+ workflow_run_id="wr_missing_starter_url_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ def _logged(level: str) -> bool:+ return any(+ call.args and "Failed to get browser state for first task" in str(call.args[0])+ for call in getattr(log_mock, level).call_args_list+ )++ assert _logged(expect_level), f"expected {expect_level} for {error_message}"+ assert not _logged("exception" if expect_level == "warning" else "warning")++def _workflow_run_for_create_task() -> SimpleNamespace:return SimpleNamespace(workflow_run_id="wr_missing_starter_url_test",