Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(copilot): make scrape-wall stop nudge actually work in production (#5828)
Andrew Neilson4bd475844dc2
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex 358c908cf..ff9d4f1bb 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -205,6 +205,7 @@ class CopilotContext(AgentContext):# copilot rewrites the workflow, but the underlying site-block pattern is# shape-independent.probable_site_block_streak_count: int = 0+ probable_site_block_stop_nudge_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 e462f4fbb..78479ff9c 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -46,6 +46,12 @@ REPEATED_FRONTIER_STREAK_STOP_AT = 3# 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 = 2+# Caps how many times the stop nudge can re-fire — without this, the streak+# stays latched while no new test runs reset it and every subsequent turn+# re-injects the same nudge until MAX_ITERATIONS. Independent of+# PROBABLE_SITE_BLOCK_STREAK_STOP_AT (both default to 2 but tune different+# axes: streak depth vs nudge count).+MAX_PROBABLE_SITE_BLOCK_STOP_NUDGES = 2MIN_BLOCKS_FOR_AUTO_COMPLETE = 10TOTAL_TIMEOUT_SECONDS = 600# Belt-and-braces cap alongside the elapsed-time budget. Per-nudge caps@@ -465,13 +471,11 @@ def _needs_suspicious_success_nudge(ctx: Any) -> bool: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+ """Return True when the site-block-wall streak has reached the stop level+ AND the per-streak nudge cap has not been exhausted."""+ if _get_int(ctx, "probable_site_block_streak_count") < PROBABLE_SITE_BLOCK_STREAK_STOP_AT:+ return False+ return _get_int(ctx, "probable_site_block_stop_nudge_count") < MAX_PROBABLE_SITE_BLOCK_STOP_NUDGESdef _needs_repeated_null_data_nudge(ctx: Any) -> bool:@@ -499,6 +503,11 @@ def _repeated_frontier_failure_nudge(ctx: Any) -> str | None:# repeated-frontier nudge smuggle different retry advice past the gate.if getattr(ctx, "last_test_non_retriable_nav_error", None):return None+ # Defer to the probable-site-block stop path once the wall has been+ # confirmed across ≥ PROBABLE_SITE_BLOCK_STREAK_STOP_AT shape-independent+ # attempts — at that point "try yet another shape" is empirically wrong.+ if _get_int(ctx, "probable_site_block_streak_count") >= PROBABLE_SITE_BLOCK_STREAK_STOP_AT:+ return Nonestreak = _get_int(ctx, "repeated_failure_streak_count")emitted = _get_int(ctx, "repeated_failure_nudge_emitted_at_streak")top_category = getattr(ctx, "last_failure_category_top", None)@@ -574,11 +583,9 @@ def _check_enforcement(ctx: Any, result: RunResultStreaming | None = None) -> st# 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).+ # failed_test_nudge_count slot.if _needs_probable_site_block_stop_nudge(ctx):+ ctx.probable_site_block_stop_nudge_count = getattr(ctx, "probable_site_block_stop_nudge_count", 0) + 1return POST_PROBABLE_SITE_BLOCK_STOP_NUDGEif _needs_failed_test_nudge(ctx):diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 58202e4b8..222314652 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -2399,22 +2399,15 @@ _PROBABLE_SITE_BLOCK_FAILURE_REASON_SUBSTRINGS = ("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- """+ """True when a block failed with the site-load template and the failure is+ not a non-retriable nav error (DNS / SSL / invalid URL are owned by+ :func:`_detect_non_retriable_nav_error`)."""if bool(result.get("ok", False)):return False+ if _detect_non_retriable_nav_error(result):+ return Falsedata = result.get("data")if not isinstance(data, dict):return False@@ -2422,20 +2415,15 @@ def _detect_probable_site_block_wall(result: dict[str, Any]) -> bool:if not isinstance(blocks, list):return False- nav_completed = False- matched_reason = Falsefor 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 = Truereason = 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+ return True+ return Falsedef _detect_non_retriable_nav_error(result: dict[str, Any]) -> str | None:diff --git a/tests/unit/test_copilot_probable_site_block.py b/tests/unit/test_copilot_probable_site_block.pyindex 6be50e050..9dcf864f6 100644--- a/tests/unit/test_copilot_probable_site_block.py+++ b/tests/unit/test_copilot_probable_site_block.py@@ -1,13 +1,6 @@-"""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.-"""+"""Tests for the probable-site-block-wall detector and stop nudge — the+copilot's own shape-independent streak for sites that the shared classifier+routes to ``DATA_EXTRACTION_FAILURE`` rather than ``ANTI_BOT_DETECTION``."""from __future__ import annotations@@ -17,9 +10,12 @@ import pytestfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.enforcement import (+ MAX_PROBABLE_SITE_BLOCK_STOP_NUDGES,POST_PROBABLE_SITE_BLOCK_STOP_NUDGE,PROBABLE_SITE_BLOCK_STREAK_STOP_AT,+ REPEATED_FRONTIER_STREAK_ESCALATE_AT,_needs_probable_site_block_stop_nudge,+ _repeated_frontier_failure_nudge,)from skyvern.forge.sdk.copilot.tools import (_detect_probable_site_block_wall,@@ -48,9 +44,9 @@ def _scrape_wall_result() -> dict:"ok": False,"data": {"blocks": [- {"block_type": "goto_url", "status": "completed"},+ {"block_type": "GOTO_URL", "status": "completed"},{- "block_type": "extraction",+ "block_type": "EXTRACTION","status": "failed","failure_reason": _SCRAPE_WALL_REASON,},@@ -73,9 +69,9 @@ def test_detect_matches_page_navigated_unexpectedly_phrasing() -> None:"ok": False,"data": {"blocks": [- {"block_type": "navigation", "status": "completed"},+ {"block_type": "NAVIGATION", "status": "completed"},{- "block_type": "extraction",+ "block_type": "EXTRACTION","status": "failed","failure_reason": "We think the page may have navigated unexpectedly during analysis.",},@@ -91,13 +87,39 @@ def test_detect_returns_false_when_run_ok() -> None:assert _detect_probable_site_block_wall(result) is False-def test_detect_returns_false_without_completed_nav() -> None:+def test_detect_matches_nav_only_failure_with_template_reason() -> None:result = {"ok": False,"data": {"blocks": [- {"block_type": "goto_url", "status": "failed"},- {"block_type": "extraction", "status": "failed", "failure_reason": _SCRAPE_WALL_REASON},+ {+ "block_type": "NAVIGATION",+ "status": "failed",+ "failure_reason": _SCRAPE_WALL_REASON,+ },+ ]+ },+ }+ assert _detect_probable_site_block_wall(result) is True+++def test_detect_returns_false_when_non_retriable_nav() -> None:+ result = {+ "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,+ },]},}@@ -109,9 +131,9 @@ def test_detect_returns_false_for_other_failure_reasons() -> None:"ok": False,"data": {"blocks": [- {"block_type": "goto_url", "status": "completed"},+ {"block_type": "GOTO_URL", "status": "completed"},{- "block_type": "extraction",+ "block_type": "EXTRACTION","status": "failed","failure_reason": "Timeout waiting for selector #submit",},@@ -140,6 +162,28 @@ def test_streak_increments_on_consecutive_scrape_walls() -> None:assert ctx.probable_site_block_streak_count == 2+def test_streak_holds_through_intermediate_nav_only_template_failure() -> None:+ ctx = _fresh_context()+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 1+ nav_only_template_failure = {+ "ok": False,+ "data": {+ "blocks": [+ {+ "block_type": "NAVIGATION",+ "status": "failed",+ "failure_reason": _SCRAPE_WALL_REASON,+ },+ ]+ },+ }+ _record_run_blocks_result(ctx, nav_only_template_failure)+ assert ctx.probable_site_block_streak_count == 2+ _record_run_blocks_result(ctx, _scrape_wall_result())+ assert ctx.probable_site_block_streak_count == 3++def test_streak_resets_on_real_success() -> None:ctx = _fresh_context()_record_run_blocks_result(ctx, _scrape_wall_result())@@ -149,7 +193,7 @@ def test_streak_resets_on_real_success() -> None:"data": {"blocks": [{- "block_type": "extraction",+ "block_type": "EXTRACTION","status": "completed","extracted_data": {"answer": "42"},}@@ -168,9 +212,9 @@ def test_streak_resets_on_failure_without_pattern() -> None:"ok": False,"data": {"blocks": [- {"block_type": "goto_url", "status": "completed"},+ {"block_type": "GOTO_URL", "status": "completed"},{- "block_type": "extraction",+ "block_type": "EXTRACTION","status": "failed","failure_reason": "Timeout waiting for selector #submit",},@@ -193,14 +237,14 @@ def test_streak_stays_zero_when_navigation_itself_failed() -> None:"data": {"blocks": [{- "block_type": "goto_url",+ "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",+ "block_type": "EXTRACTION","status": "failed","failure_reason": _SCRAPE_WALL_REASON,},@@ -229,6 +273,27 @@ def test_gate_fires_at_stop_threshold() -> None:assert _needs_probable_site_block_stop_nudge(ctx)+def test_gate_does_not_fire_after_cap_reached() -> None:+ ctx = _fresh_context()+ ctx.probable_site_block_streak_count = PROBABLE_SITE_BLOCK_STREAK_STOP_AT+ ctx.probable_site_block_stop_nudge_count = MAX_PROBABLE_SITE_BLOCK_STOP_NUDGES+ assert not _needs_probable_site_block_stop_nudge(ctx)+++def test_frontier_warn_defers_to_wall_when_both_apply() -> None:+ ctx = _fresh_context()+ ctx.repeated_failure_streak_count = REPEATED_FRONTIER_STREAK_ESCALATE_AT+ ctx.probable_site_block_streak_count = PROBABLE_SITE_BLOCK_STREAK_STOP_AT+ assert _repeated_frontier_failure_nudge(ctx) is None+++def test_frontier_warn_still_fires_when_wall_below_threshold() -> None:+ ctx = _fresh_context()+ ctx.repeated_failure_streak_count = REPEATED_FRONTIER_STREAK_ESCALATE_AT+ ctx.probable_site_block_streak_count = 1+ assert _repeated_frontier_failure_nudge(ctx) is not None++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