Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep SSL protocol and cipher-mismatch failures in the Copilot repair loop (SKY-17156) (#8731)
Andrew Neilson695c05698eba
diff --git a/skyvern/forge/sdk/copilot/nav_attribution.py b/skyvern/forge/sdk/copilot/nav_attribution.pyindex f6ee7598d..d982b47a6 100644--- a/skyvern/forge/sdk/copilot/nav_attribution.py+++ b/skyvern/forge/sdk/copilot/nav_attribution.py@@ -29,7 +29,20 @@ TERMINAL_NAV_ERROR_CODES = tuple(code for code in SKIP_INNER_NAV_RETRY_ERRORS if# itself reports (contrast PROXY_TRANSPORT_NAV_ERRORS, which are). It stands in for a# resolver-corroborated dead host -- the driver's own code for that case is a borrowed proxy# transport code -- so it belongs on the target side of the split even though it is not one.-_TARGET_OWNED_NAV_ERROR_CODES = (*TERMINAL_NAV_ERROR_CODES, NO_ADDRESS_RECORD_NAV_ERROR_CODE)+_NOT_PROXY_OWNED_NAV_ERROR_CODES = (*TERMINAL_NAV_ERROR_CODES, NO_ADDRESS_RECORD_NAV_ERROR_CODE)++# Of the ERR_SSL_ family only these name the server's certificate or identity. The rest (a failed+# handshake, an alert, a client-certificate problem) do not say which TLS peer broke, so they name no owner.+_TARGET_OWNED_SSL_NAV_ERROR_CODES = (+ "net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN",+ "net::ERR_SSL_SERVER_CERT_CHANGED",+ "net::ERR_SSL_SERVER_CERT_BAD_FORMAT",+ "net::ERR_SSL_KEY_USAGE_INCOMPATIBLE",+)+_TARGET_OWNED_NAV_ERROR_CODES = (+ *(code for code in _NOT_PROXY_OWNED_NAV_ERROR_CODES if code != "net::ERR_SSL_"),+ *_TARGET_OWNED_SSL_NAV_ERROR_CODES,+)def proxy_owns_nav_codes(codes: Iterable[str | None]) -> bool:@@ -41,20 +54,17 @@ def proxy_owns_nav_codes(codes: Iterable[str | None]) -> bool:reported = [code for code in codes if isinstance(code, str) and code]if not reported:return False- # constants.py lists ERR_CERT_ and ERR_SSL_ as prefixes, not whole codes, so a target-owned- # code has to be matched by prefix or every certificate failure reads as unclaimed.- if any(code.startswith(terminal) for code in reported for terminal in _TARGET_OWNED_NAV_ERROR_CODES):+ # constants.py lists ERR_CERT_ and ERR_SSL_ as prefixes, not whole codes, so a vetoing code has to+ # be matched by prefix or every certificate or TLS failure reads as the proxy's.+ if any(code.startswith(terminal) for code in reported for terminal in _NOT_PROXY_OWNED_NAV_ERROR_CODES):return Falsereturn any(code in PROXY_TRANSPORT_NAV_ERRORS for code in reported)def target_owns_nav_codes(codes: Iterable[str | None]) -> bool:- """True when the driver's own codes name the target: DNS, certificate, SSL, a refused URL, or a- resolver-corroborated dead host.-- Same contract as :func:`proxy_owns_nav_codes` -- the codes must be ones the driver produced,- never tokens recovered from a failure sentence.- """+ """True when the driver's own codes name the target: DNS, a server certificate, a refused URL, or a+ resolver-corroborated dead host. The codes must be ones the driver produced, never tokens recovered+ from a failure sentence."""reported = [code for code in codes if isinstance(code, str) and code]return any(code.startswith(terminal) for code in reported for terminal in _TARGET_OWNED_NAV_ERROR_CODES)diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex 506928c84..e9aeb46ca 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -897,6 +897,57 @@ def test_failed_run_injects_pending_runtime_authoring_context_before_page_observassert contract.repair_decision.target_blocks == ["search_registry"]+ ("codes", "repairs"),+ [+ pytest.param(["net::ERR_SSL_PROTOCOL_ERROR"], True, id="ssl_protocol_error_names_no_owner_and_repairs"),+ pytest.param(+ ["net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_SSL_PROTOCOL_ERROR"],+ True,+ id="ssl_beside_a_tunnel_code_is_not_proxy_owned_and_repairs",+ ),+ pytest.param(["net::ERR_CERT_DATE_INVALID"], False, id="certificate_names_the_target_and_stops"),+ pytest.param(["net::ERR_SSL_PINNED_KEY_NOT_IN_CERT_CHAIN"], False, id="pinned_key_names_the_target_and_stops"),+ pytest.param(["net::ERR_SSL_SERVER_CERT_CHANGED"], False, id="server_cert_changed_names_the_target_and_stops"),+ pytest.param(["net::ERR_SSL_SERVER_CERT_BAD_FORMAT"], False, id="bad_server_cert_names_the_target_and_stops"),+ pytest.param(["net::ERR_SSL_KEY_USAGE_INCOMPATIBLE"], False, id="key_usage_names_the_target_and_stops"),+ ],+)+def test_a_driver_tls_failure_reaches_repair_only_when_it_names_no_owner(codes: list[str], repairs: bool) -> None:+ code = codes[-1]+ ctx = _ctx()+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ run_result = {+ "ok": False,+ "error": "Run failed.",+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "blocks": [+ {+ "label": "open_report",+ "status": "failed",+ "failure_reason": f"Failed to navigate to url https://localhost:8900/tls_repair/. Error message: "+ f"Page.goto: {code} at https://localhost:8900/tls_repair/",+ "error_codes": codes,+ }+ ],+ },+ }++ run_execution_module._record_run_blocks_result(ctx, run_result)+ inject_runtime_authoring_repair_context(ctx, run_result)+ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result=run_result,+ ctx=ctx,+ workflow_updated=True,+ )++ assert ("authoring_repair_context" in run_result["data"]) is repairs+ assert contract.repair_decision.next_action == (RepairNextAction.REPAIR if repairs else RepairNextAction.STOP)++def test_runtime_repair_context_keeps_a_runner_denials_named_replacement_whole() -> None:# The secure runner's listener denial names its replacement after ~500 characters; the recorder# must carry the block's failure reason far enough for the repair prompt to see that route.diff --git a/tests/unit/test_copilot_non_retriable_nav.py b/tests/unit/test_copilot_non_retriable_nav.pyindex 8f8f58318..e08732a1d 100644--- a/tests/unit/test_copilot_non_retriable_nav.py+++ b/tests/unit/test_copilot_non_retriable_nav.py@@ -8,6 +8,7 @@ the model tries to narrate a completion. A failure inside Skyvern's own proxy hofrom __future__ import annotationsimport asyncio+import jsonfrom datetime import UTC, datetimefrom types import SimpleNamespacefrom unittest import mock@@ -45,7 +46,7 @@ from skyvern.forge.sdk.copilot.nav_attribution import (proxy_owns_nav_codes,)from skyvern.forge.sdk.copilot.output_utils import BUILD_TEST_PACKET_KEY-from skyvern.forge.sdk.copilot.run_outcome import _DISPLAY_REASON_MAX_CHARS+from skyvern.forge.sdk.copilot.run_outcome import _DISPLAY_REASON_MAX_CHARS, RecordedRunOutcomefrom skyvern.forge.sdk.copilot.runtime import mcp_to_copilotfrom skyvern.forge.sdk.copilot.runtime_authoring_repair import _error_text_requires_stopfrom skyvern.forge.sdk.copilot.secret_scrub import register_secret_scrub_value@@ -66,12 +67,13 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.schemas.tasks import TaskStatus+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlockfrom skyvern.schemas.proxy_location import GeoTarget, ProxyLocationInputfrom skyvern.schemas.runs import ProxyLocationfrom skyvern.schemas.workflows import BlockTypefrom skyvern.webeye.navigation import driver_nav_error_code-from tests.unit.copilot_test_helpers import install_run_blocks_harness, make_copilot_ctx+from tests.unit.copilot_test_helpers import install_run_blocks_harness, make_copilot_ctx, stub_copilot_agent_loopfrom tests.unit.force_stub_app import admit_block_dispatchfrom tests.unit.test_missing_starter_url import _mock_block_execute_deps, _output_parameter@@ -269,7 +271,6 @@ _TARGET_OWNED_ARMS = ["net::ERR_NAME_RESOLUTION_FAILED",id="name_resolution_mid_string",),- pytest.param("SSL error: net::ERR_SSL_PROTOCOL_ERROR", "net::ERR_SSL_PROTOCOL_ERROR", id="ssl_prefixed"),pytest.param(_DNS_FAILURE_WITH_PROXY_TOKEN_IN_URL, "net::ERR_NAME_NOT_RESOLVED", id="dns_alongside_proxy_code"),pytest.param("net::ERR_SOCKS_CONNECTION_FAILED then net::ERR_CERT_DATE_INVALID on retry",@@ -624,6 +625,11 @@ def test_proxy_codes_are_subtracted_from_the_browser_skip_set() -> None:False,id="a_target_code_alongside_disqualifies",),+ pytest.param(+ ["net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_SSL_PROTOCOL_ERROR"],+ False,+ id="an_ssl_code_alongside_a_proxy_code_disqualifies",+ ),pytest.param(["FILE_PARSER_ERROR"], False, id="an_unrelated_block_code"),pytest.param([], False, id="the_driver_reported_nothing"),],@@ -696,6 +702,97 @@ def test_proxy_transport_run_keeps_proposal_and_reaches_repair(reason: str, blocassert "verify the URL" not in outcome.display_reason+ ("code", "extra_codes"),+ [+ pytest.param("net::ERR_SSL_PROTOCOL_ERROR", [], id="protocol_error"),+ pytest.param("net::ERR_SSL_VERSION_OR_CIPHER_MISMATCH", [], id="version_or_cipher_mismatch"),+ pytest.param("net::ERR_SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY", [], id="client_certificate_problem"),+ pytest.param(+ "net::ERR_SSL_PROTOCOL_ERROR", ["net::ERR_TUNNEL_CONNECTION_FAILED"], id="ssl_alongside_a_tunnel_code"+ ),+ ],+)+async def test_unknown_owner_ssl_run_keeps_reply_and_draft_without_latching(+ monkeypatch: pytest.MonkeyPatch, code: str, extra_codes: list[str]+) -> None:+ url = "https://localhost:8900/tls_repair/"+ driver_message = f'Page.goto: {code} at {url}\nCall log:\n - navigating to "{url}", waiting until "load"\n'+ reason = str(FailedToNavigateToUrl(url, driver_message))+ reply = "The page load failed with a TLS protocol error, so the draft is untested."+ contexts: list[CopilotContext] = []+ outcomes: list[RecordedRunOutcome | None] = []++ # Ends the way run_with_enforcement does, so a latched stop reaches the agent's own exit handler.+ async def ssl_turn(*, ctx: CopilotContext, **_kwargs: object) -> SimpleNamespace:+ ctx.test_after_update_done = True+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES+ ctx.has_staged_proposal = True+ ctx.staged_workflow_yaml = "title: staged"+ contexts.append(ctx)+ outcomes.append(+ _record_run_blocks_result(+ ctx,+ {+ "ok": False,+ "data": {+ "blocks": [+ {+ "label": "failed_navigation",+ "block_type": "navigation",+ "status": "failed",+ "failure_reason": reason,+ "error_codes": [*extra_codes, driver_nav_error_code(driver_message)],+ }+ ]+ },+ },+ )+ )+ _maybe_raise_non_retriable_nav(ctx)+ return SimpleNamespace(final_output=json.dumps({"type": "REPLY", "user_response": reply}), new_items=[])++ stub_copilot_agent_loop(monkeypatch, ssl_turn)+ result = await agent_module.run_copilot_agent(+ stream=mock.MagicMock(),+ organization_id="org-1",+ chat_request=WorkflowCopilotChatRequest(+ workflow_permanent_id="wfp-1",+ workflow_id="wf-1",+ workflow_copilot_chat_id="chat-1",+ message="run this workflow and tell me Monday's high tide",+ workflow_yaml="",+ ),+ chat_history=[],+ global_llm_context=None,+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),+ raw_secret_safety_handler=AsyncMock(+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}+ ),+ api_key="sk-test",+ )++ assert result.user_response == reply+ assert result.turn_outcome is not None+ assert result.turn_outcome.terminal_reason is None+ assert result.staged_workflow_yaml == "title: staged"++ (ctx,) = contexts+ (outcome,) = outcomes+ assert outcome is not None+ assert ctx.last_test_non_retriable_nav_error is None+ assert ctx.last_test_proxy_owned_failure is False+ assert ctx.has_staged_proposal is True+ assert ctx.last_test_ok is False+ assert ctx.verified_terminal_proposal_ready is False+ assert outcome.verdict == "not_demonstrated"+ assert outcome.display_reason is not None+ assert code in outcome.display_reason+ assert not outcome.display_reason.startswith("Skyvern proxy hop failed")+ assert "verify the URL" not in outcome.display_reason++@pytest.mark.parametrize(("blocks", "run_codes", "connect_failure_reason", "proxy_location", "labelled", "displayed", "stop"),[