Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
copilot: stop-nudge when navigation succeeds but scraping keeps failing (#5634)
Andrew Neilson71316dbc01a2
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex ff5e7e012..91aeae717 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -189,6 +189,13 @@ class CopilotContext(AgentContext):# run produces real data. Used to escalate when the agent is stuck# retrying extraction against a page that doesn't contain the data.null_data_streak_count: int = 0+ # Consecutive failed runs where navigation completed but the scraper+ # could not read the page (generic "failed to load the website" template).+ # Resets on any non-matching run outcome. Streak crosses workflow-shape+ # changes deliberately — the frontier fingerprint resets each time the+ # copilot rewrites the workflow, but the underlying site-block pattern is+ # shape-independent.+ probable_site_block_streak_count: int = 0# Per-request frontier state. `verified_block_outputs` and# `verified_prefix_labels` are populated ONLY from fully-successful runs —diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 73dc0952f..fd52080a2 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -37,6 +37,10 @@ NULL_DATA_STREAK_ESCALATE_AT = 2# Streak levels for repeated-failure (same frontier + same failure signature).REPEATED_FRONTIER_STREAK_ESCALATE_AT = 2REPEATED_FRONTIER_STREAK_STOP_AT = 3+# Stop after this many consecutive runs where navigation succeeded but the+# scraper could not read the page. Aligned with MAX_FAILED_TEST_NUDGES so the+# copilot gets one generic retry nudge, then stops on the second occurrence.+PROBABLE_SITE_BLOCK_STREAK_STOP_AT = 2MIN_BLOCKS_FOR_AUTO_COMPLETE = 10TOTAL_TIMEOUT_SECONDS = 600# Belt-and-braces cap alongside the elapsed-time budget. Per-nudge caps@@ -219,6 +223,21 @@ POST_PARAMETER_BINDING_STOP_NUDGE = ("same parameter-binding drift.")+POST_PROBABLE_SITE_BLOCK_STOP_NUDGE = (+ "STOP — the target site has failed to scrape on every attempt across "+ "multiple workflow shapes. Every run navigated successfully but the "+ 'scraper could not read the page ("failed to load the website" / '+ '"page may have navigated unexpectedly"). This pattern indicates the '+ "site is either blocking automated access, genuinely unresponsive in "+ "this environment, or rendering content Skyvern cannot read reliably.\n"+ "Do NOT retry with another workflow variation. Do NOT call "+ "update_and_run_blocks or run_blocks_and_collect_debug again.\n"+ "Reply to the user now: state that the site could not be loaded after "+ "multiple attempts, quote the last failure_reason verbatim, and ask "+ "whether to try a different URL, configure a proxy, or provide an "+ "alternate entry point."+)+POST_ANTI_BOT_FAILED_TEST_NUDGE = ("STOP — your last test run failed due to an anti-bot/WAF block ""(Access Denied, Cloudflare, Akamai, etc.).\n"@@ -428,6 +447,16 @@ def _needs_suspicious_success_nudge(ctx: Any) -> bool:return bool(getattr(ctx, "last_test_suspicious_success", False))+def _needs_probable_site_block_stop_nudge(ctx: Any) -> bool:+ """Return True when the site-block-wall streak has reached the stop level.++ The streak is maintained in :func:`tools._record_run_blocks_result` and+ crosses workflow-shape changes deliberately (the repeated-frontier streak+ resets on shape edits; this one tracks the shape-independent scrape wall).+ """+ return _get_int(ctx, "probable_site_block_streak_count") >= PROBABLE_SITE_BLOCK_STREAK_STOP_AT++def _needs_repeated_null_data_nudge(ctx: Any) -> bool:"""Return True when suspicious-success has happened enough times to escalate."""# Same as above: non-retriable nav state never belongs on this branch.@@ -525,6 +554,15 @@ def _check_enforcement(ctx: Any, result: RunResultStreaming | None = None) -> stif _needs_suspicious_success_nudge(ctx):return POST_SUSPICIOUS_SUCCESS_NUDGE+ # Checked before the generic failed-test nudge so a scrape-wall streak+ # emits the specific STOP text and does not also consume a+ # failed_test_nudge_count slot. The two states are orthogonal by+ # construction (scrape-wall requires a completed nav block;+ # non_retriable_nav / anti_bot / suspicious_success populate different+ # ctx fields).+ if _needs_probable_site_block_stop_nudge(ctx):+ return POST_PROBABLE_SITE_BLOCK_STOP_NUDGE+if _needs_failed_test_nudge(ctx):ctx.failed_test_nudge_count += 1if getattr(ctx, "last_test_anti_bot", None):@@ -824,6 +862,7 @@ _NUDGE_TYPE_BY_MESSAGE: dict[str, str] = {POST_PARAMETER_BINDING_WARN_NUDGE: "parameter_binding_warn",POST_PARAMETER_BINDING_STOP_NUDGE: "parameter_binding_stop",POST_ANTI_BOT_FAILED_TEST_NUDGE: "anti_bot_block",+ POST_PROBABLE_SITE_BLOCK_STOP_NUDGE: "probable_site_block_stop",POST_FAILED_TEST_NUDGE: "post_failed_test",SCREENSHOT_DROPPED_NUDGE: "screenshot_dropped_on_recovery",}diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 9ed4429fc..7f1612650 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -1977,6 +1977,59 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[return anti_bot_match, empty_data_blocks, categories+# Generic failure-reason template emitted by the shared agent when the+# browser-side scraper catches ScrapingFailed / NoElementFound. Matching on+# the template (not the shared classifier) lets the copilot notice a repeated+# site-block/unreadable-page pattern even though the classifier routes it to+# DATA_EXTRACTION_FAILURE, not ANTI_BOT_DETECTION.+# Coupling note: these substrings come from the run-level failure_reason+# produced when the shared scraper raises ScrapingFailed. If the template+# wording changes, update this tuple and the test that locks it in+# (tests/unit/test_copilot_probable_site_block.py).+_PROBABLE_SITE_BLOCK_FAILURE_REASON_SUBSTRINGS = (+ "failed to load the website",+ "page may have navigated unexpectedly",+)++_NAV_BLOCK_TYPES = ("goto_url", "navigation")+++def _detect_probable_site_block_wall(result: dict[str, Any]) -> bool:+ """Return True when the run shows the "site-block-wall" pattern: a+ navigation block completed successfully but every subsequent block+ failed to scrape the page.++ Pattern:+ - ``ok`` is false (run failed)+ - at least one ``goto_url`` / ``navigation`` block completed successfully+ - at least one block's ``failure_reason`` matches the generic+ "Skyvern failed to load the website..." template+ """+ if bool(result.get("ok", False)):+ return False+ data = result.get("data")+ if not isinstance(data, dict):+ return False+ blocks = data.get("blocks")+ if not isinstance(blocks, list):+ return False++ nav_completed = False+ matched_reason = False+ for block in blocks:+ if not isinstance(block, dict):+ continue+ if block.get("block_type") in _NAV_BLOCK_TYPES and block.get("status") == "completed":+ nav_completed = True+ reason = block.get("failure_reason")+ if isinstance(reason, str):+ lowered = reason.lower()+ if any(sub in lowered for sub in _PROBABLE_SITE_BLOCK_FAILURE_REASON_SUBSTRINGS):+ matched_reason = True++ return nav_completed and matched_reason++def _detect_non_retriable_nav_error(result: dict[str, Any]) -> str | None:"""Return the first failure_reason that matches SKIP_INNER_NAV_RETRY_ERRORS(DNS / cert / SSL / invalid URL), preferring run-level over block-level.@@ -2022,10 +2075,13 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:"(missing, empty, or all-null fields). ""The workflow may not be working correctly.")+ # Clean-ish success (no scrape-fail pattern): reset the streak.+ copilot_ctx.probable_site_block_streak_count = 0update_repeated_failure_state(copilot_ctx, result)returncopilot_ctx.failed_test_nudge_count = 0copilot_ctx.null_data_streak_count = 0+ copilot_ctx.probable_site_block_streak_count = 0copilot_ctx.last_failed_workflow_yaml = None# Real success: clear the signature latch so a subsequent bad URL in# the same session can re-fire the stop nudge.@@ -2035,6 +2091,10 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:copilot_ctx.last_failed_workflow_yaml = getattr(copilot_ctx, "workflow_yaml", None)copilot_ctx.last_test_non_retriable_nav_error = _detect_non_retriable_nav_error(result)+ if _detect_probable_site_block_wall(result):+ copilot_ctx.probable_site_block_streak_count += 1+ else:+ copilot_ctx.probable_site_block_streak_count = 0data = result.get("data")if isinstance(data, dict):diff --git a/tests/unit/test_copilot_probable_site_block.py b/tests/unit/test_copilot_probable_site_block.pynew file mode 100644index 000000000..6be50e050--- /dev/null+++ b/tests/unit/test_copilot_probable_site_block.py@@ -0,0 +1,235 @@+"""Tests for the probable-site-block-wall detector and stop nudge.++Covers the copilot's response to a scrape-wall pattern where navigation+reports success but the page is unreadable — a symptom of site blocking+that the shared anti-bot classifier does not recognise (it routes to+``DATA_EXTRACTION_FAILURE`` rather than ``ANTI_BOT_DETECTION``). The+copilot tracks its own shape-independent streak so workflow-shape+rewrites cannot perpetually reset a repeated-frontier counter while the+site keeps refusing to load.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest++from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.enforcement import (+ POST_PROBABLE_SITE_BLOCK_STOP_NUDGE,+ PROBABLE_SITE_BLOCK_STREAK_STOP_AT,+ _needs_probable_site_block_stop_nudge,+)+from skyvern.forge.sdk.copilot.tools import (+ _detect_probable_site_block_wall,+ _record_run_blocks_result,+)++_SCRAPE_WALL_REASON = (+ "Skyvern failed to load the website. The page may have navigated "+ "unexpectedly or become unresponsive during analysis."+)+++def _fresh_context() -> CopilotContext:+ return CopilotContext(+ organization_id="o",+ workflow_id="w",+ workflow_permanent_id="wp",+ workflow_yaml="",+ browser_session_id=None,+ stream=SimpleNamespace(), # type: ignore[arg-type]+ )+++def _scrape_wall_result() -> dict:+ return {+ "ok": False,+ "data": {+ "blocks": [+ {"block_type": "goto_url", "status": "completed"},+ {+ "block_type": "extraction",+ "status": "failed",+ "failure_reason": _SCRAPE_WALL_REASON,+ },+ ]+ },+ }+++# ---------------------------------------------------------------------------+# _detect_probable_site_block_wall+# ---------------------------------------------------------------------------+++def test_detect_matches_completed_nav_plus_scrape_wall() -> None:+ assert _detect_probable_site_block_wall(_scrape_wall_result()) is True+++def test_detect_matches_page_navigated_unexpectedly_phrasing() -> None:+ result = {+ "ok": False,+ "data": {+ "blocks": [+ {"block_type": "navigation", "status": "completed"},+ {+ "block_type": "extraction",+ "status": "failed",+ "failure_reason": "We think the page may have navigated unexpectedly during analysis.",+ },+ ]+ },+ }+ assert _detect_probable_site_block_wall(result) is True+++def test_detect_returns_false_when_run_ok() -> None:+ result = _scrape_wall_result()+ result["ok"] = True+ assert _detect_probable_site_block_wall(result) is False+++def test_detect_returns_false_without_completed_nav() -> None:+ result = {+ "ok": False,+ "data": {+ "blocks": [+ {"block_type": "goto_url", "status": "failed"},+ {"block_type": "extraction", "status": "failed", "failure_reason": _SCRAPE_WALL_REASON},+ ]+ },+ }+ assert _detect_probable_site_block_wall(result) is False+++def test_detect_returns_false_for_other_failure_reasons() -> None:+ result = {+ "ok": False,+ "data": {+ "blocks": [+ {"block_type": "goto_url", "status": "completed"},+ {+ "block_type": "extraction",+ "status": "failed",+ "failure_reason": "Timeout waiting for selector #submit",+ },+ ]+ },+ }+ assert _detect_probable_site_block_wall(result) is False+++def test_detect_tolerates_missing_data() -> None:+ assert _detect_probable_site_block_wall({"ok": False}) is False+ assert _detect_probable_site_block_wall({"ok": False, "data": "not a dict"}) is False+ assert _detect_probable_site_block_wall({"ok": False, "data": {}}) is False+++# ---------------------------------------------------------------------------+# Streak maintenance in _record_run_blocks_result+# ---------------------------------------------------------------------------+++def test_streak_increments_on_consecutive_scrape_walls() -> None:+ ctx = _fresh_context()+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 1+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 2+++def test_streak_resets_on_real_success() -> None:+ ctx = _fresh_context()+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 1+ success = {+ "ok": True,+ "data": {+ "blocks": [+ {+ "block_type": "extraction",+ "status": "completed",+ "extracted_data": {"answer": "42"},+ }+ ]+ },+ }+ _record_run_blocks_result(ctx, success)+ assert ctx.probable_site_block_streak_count == 0+++def test_streak_resets_on_failure_without_pattern() -> None:+ ctx = _fresh_context()+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 1+ other_failure = {+ "ok": False,+ "data": {+ "blocks": [+ {"block_type": "goto_url", "status": "completed"},+ {+ "block_type": "extraction",+ "status": "failed",+ "failure_reason": "Timeout waiting for selector #submit",+ },+ ]+ },+ }+ _record_run_blocks_result(ctx, other_failure)+ assert ctx.probable_site_block_streak_count == 0+++def test_streak_stays_zero_when_navigation_itself_failed() -> None:+ # Orthogonality contract: when the navigation block did not reach+ # status=completed (e.g. non-retriable nav error — DNS, SSL, invalid URL),+ # the scrape-wall detector must not count the run even if a later block+ # also emitted the generic load-failure template. That case belongs to+ # _detect_non_retriable_nav_error, not the probable-site-block streak.+ ctx = _fresh_context()+ nav_failed_with_wall_text = {+ "ok": False,+ "data": {+ "blocks": [+ {+ "block_type": "goto_url",+ "status": "failed",+ "failure_reason": (+ "Failed to navigate to url https://x.invalid. Error message: net::ERR_NAME_NOT_RESOLVED"+ ),+ },+ {+ "block_type": "extraction",+ "status": "failed",+ "failure_reason": _SCRAPE_WALL_REASON,+ },+ ]+ },+ }+ _record_run_blocks_result(ctx, nav_failed_with_wall_text)+ assert ctx.probable_site_block_streak_count == 0+++# ---------------------------------------------------------------------------+# Enforcement gate+# ---------------------------------------------------------------------------++[email protected]("streak", [0, 1])+def test_gate_does_not_fire_below_threshold(streak: int) -> None:+ ctx = _fresh_context()+ ctx.probable_site_block_streak_count = streak+ assert not _needs_probable_site_block_stop_nudge(ctx)+++def test_gate_fires_at_stop_threshold() -> None:+ ctx = _fresh_context()+ ctx.probable_site_block_streak_count = PROBABLE_SITE_BLOCK_STREAK_STOP_AT+ assert _needs_probable_site_block_stop_nudge(ctx)+++def test_nudge_text_is_stop_oriented() -> None:+ # Sanity-check the stop nudge tells the agent not to retry.+ assert "STOP" in POST_PROBABLE_SITE_BLOCK_STOP_NUDGE+ assert "Do NOT" in POST_PROBABLE_SITE_BLOCK_STOP_NUDGE