Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-9644): make site-block stop nudge proxy-aware (#5883)
Andrew Neilson78260728829e
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 0ab6c4122..6380ca428 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -258,6 +258,15 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> streturn user_response+def _shape_ask_question_response(user_response: str, ctx: CopilotContext) -> str:+ from skyvern.forge.sdk.copilot.enforcement import build_probable_site_block_user_question++ site_block_question = build_probable_site_block_user_question(ctx)+ if site_block_question is not None:+ return site_block_question+ return user_response++def _verified_workflow_or_none(ctx: CopilotContext) -> tuple[Any, str | None]:"""Surface a proposal only when it passed a test this turn AND yaml is on hand."""if ctx.last_workflow is not None and ctx.last_workflow_yaml and ctx.last_test_ok is True:@@ -519,7 +528,9 @@ def _translate_to_agent_result(# cannot test. The generic rewrite would replace it with a vague# "Could you share more context", so skip it for ASK_QUESTION (and for# salvaged replies, which already describe the verified prefix).- if resp_type != "ASK_QUESTION" and not salvaged_reply:+ if resp_type == "ASK_QUESTION":+ user_response = _shape_ask_question_response(str(user_response), ctx)+ elif not salvaged_reply:user_response = _rewrite_failed_test_response(str(user_response), ctx)verified_workflow, verified_yaml = _verified_workflow_or_none(ctx)# Default-true preserves backwards-compat with stale prompts and missing fields.diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex dd208659e..081f56430 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -207,6 +207,7 @@ class CopilotContext(AgentContext):probable_site_block_streak_count: int = 0probable_site_block_stop_nudge_count: int = 0per_tool_budget_nudge_count: int = 0+ effective_workflow_proxy_location: Any | None = None# 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 0e7e42c37..d33a936d6 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -255,7 +255,7 @@ POST_PER_TOOL_BUDGET_NUDGE = ("navigation_goal scope, or reply with a blocker explanation.")-POST_PROBABLE_SITE_BLOCK_STOP_NUDGE = (+_PROBABLE_SITE_BLOCK_STOP_NUDGE_PREFIX = ("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" / '@@ -265,9 +265,13 @@ POST_PROBABLE_SITE_BLOCK_STOP_NUDGE = ("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."+ "multiple attempts, quote the last failure_reason verbatim, keep the "+ "message concise, and ask "+)++POST_PROBABLE_SITE_BLOCK_STOP_NUDGE = (+ _PROBABLE_SITE_BLOCK_STOP_NUDGE_PREFIX+ + "whether to try a different URL, configure a proxy, or provide an alternate entry point.")POST_ANTI_BOT_FAILED_TEST_NUDGE = (@@ -317,6 +321,76 @@ def _is_progress_narration(user_response: Any) -> bool:return any(pattern.search(user_response) for pattern in _PROGRESS_NARRATION_PATTERNS)+def _normalized_proxy_label(proxy_location: Any) -> str | None:+ if proxy_location is None:+ return None+ raw_value = getattr(proxy_location, "value", proxy_location)+ if isinstance(raw_value, dict):+ country = raw_value.get("country")+ subdivision = raw_value.get("subdivision")+ city = raw_value.get("city")+ parts = [str(part).strip() for part in (country, subdivision, city) if part]+ return "-".join(parts) if parts else None+ value = str(raw_value).strip()+ if not value or value.upper() in {"NONE", "NULL", "NO_PROXY"}:+ return None+ return value+++def _effective_proxy_label(ctx: Any) -> str | None:+ effective_raw = getattr(ctx, "effective_workflow_proxy_location", None)+ if effective_raw is not None:+ return _normalized_proxy_label(effective_raw)+ workflow = getattr(ctx, "last_workflow", None)+ if workflow is None:+ return None+ return _normalized_proxy_label(getattr(workflow, "proxy_location", None))+++def _probable_site_block_proxy_options(ctx: Any, *, include_whether: bool = True) -> str:+ proxy_label = _effective_proxy_label(ctx)+ if proxy_label is None:+ options = "try a different URL, configure a proxy, or provide an alternate entry point."+ return f"whether to {options}" if include_whether else options+ if proxy_label == "RESIDENTIAL":+ options = (+ "try a different proxy location (for example US-CA or US-NY), use a different "+ "residential/ISP option if supported, or provide an alternate entry point."+ )+ return f"whether to {options}" if include_whether else options+ options = (+ f"try a different proxy/location than {proxy_label}, use a different residential/ISP option if supported, "+ "or provide an alternate entry point."+ )+ return f"whether to {options}" if include_whether else options+++def _probable_site_block_stop_nudge(ctx: Any) -> str:+ return _PROBABLE_SITE_BLOCK_STOP_NUDGE_PREFIX + _probable_site_block_proxy_options(ctx)+++def _single_line_failure_reason(ctx: Any) -> str:+ reason = getattr(ctx, "last_test_failure_reason", None)+ if not isinstance(reason, str) or not reason.strip():+ return "Skyvern failed to load the website."+ return " ".join(reason.split())+++def build_probable_site_block_user_question(ctx: Any) -> str | None:+ """Return a concise user-facing blocker question after the site-block stop nudge."""+ if _get_int(ctx, "probable_site_block_stop_nudge_count") <= 0:+ return None++ failure_reason = _single_line_failure_reason(ctx)+ options = _probable_site_block_proxy_options(ctx, include_whether=False)+ return (+ "The site could not be loaded after repeated attempts. "+ f'The latest failure_reason was: "{failure_reason}". '+ "Repeating the same IP/workflow shape is unlikely to help, so I should stop retrying that path.\n\n"+ f"Would you like me to {options}"+ )++class CopilotTotalTimeoutError(Exception):"""Raised when the copilot agent exceeds the total allowed runtime."""@@ -630,7 +704,7 @@ def _check_enforcement(ctx: Any, result: RunResultStreaming | None = None) -> st# 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) + 1- return POST_PROBABLE_SITE_BLOCK_STOP_NUDGE+ return _probable_site_block_stop_nudge(ctx)if _needs_failed_test_nudge(ctx):ctx.failed_test_nudge_count += 1@@ -938,6 +1012,12 @@ _NUDGE_TYPE_BY_MESSAGE: dict[str, str] = {}+def _nudge_type_for_log(nudge: str) -> str:+ if nudge.startswith(_PROBABLE_SITE_BLOCK_STOP_NUDGE_PREFIX):+ return "probable_site_block_stop"+ return _NUDGE_TYPE_BY_MESSAGE.get(nudge, "intermediate_success")++def _strip_input_images(current_input: str | list) -> tuple[str | list, bool]:"""Replace ``input_image`` parts in *current_input* with a text placeholder.@@ -1234,7 +1314,7 @@ async def run_with_enforcement(return resultctx.post_update_nudge_count += 1- nudge_type = _NUDGE_TYPE_BY_MESSAGE.get(nudge, "intermediate_success")+ nudge_type = _nudge_type_for_log(nudge)LOG.info("Enforcement nudge", nudge_type=nudge_type, iteration=iteration)# OpenAI rejects images in tool messages, so a queued post-rundiff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 7ded0c8c9..18eadde8b 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -94,6 +94,7 @@ class AgentContext:workflow_persisted: bool = Falselast_workflow: Any | None = Nonelast_workflow_yaml: str | None = None+ effective_workflow_proxy_location: Any | None = Nonecopilot_run_start_monotonic: float | None = Nonediff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex c20b971b5..262cee1db 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -61,6 +61,7 @@ from skyvern.forge.sdk.workflow.models.parameter import (WorkflowParameterType,)from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus+from skyvern.schemas.proxy_location import ProxyLocationfrom skyvern.schemas.workflows import BlockTypefrom skyvern.utils.yaml_loader import safe_load_no_datesfrom skyvern.webeye.navigation import is_skip_inner_retry_error@@ -2498,6 +2499,7 @@ def _record_workflow_update_result(copilot_ctx: Any, result: dict[str, Any]) ->wf = result["_workflow"]copilot_ctx.last_workflow = wfcopilot_ctx.last_workflow_yaml = copilot_ctx.workflow_yaml or None+ copilot_ctx.effective_workflow_proxy_location = getattr(wf, "proxy_location", None) or ProxyLocation.RESIDENTIALdata = result.get("data")if isinstance(data, dict):block_count = data.get("block_count")diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 0949f7ca0..ff4d53b12 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -432,6 +432,40 @@ workflow_definition:assert agent_result.unvalidated is Falseassert agent_result.response_type == "ASK_QUESTION"+ def test_probable_site_block_ask_question_is_concise_and_proxy_aware(self) -> None:+ ctx = _ctx(+ last_test_ok=False,+ last_test_failure_reason="Skyvern failed to load the website. The page may have navigated unexpectedly.",+ probable_site_block_stop_nudge_count=1,+ effective_workflow_proxy_location="RESIDENTIAL",+ )+ verbose_response = (+ "Diagnostic recap:\n"+ "- I tried several workflow shapes with the same browser state.\n"+ '- global_llm_context: {"workflow_state": "many internal details"}\n'+ "- The final failure_reason was: Skyvern failed to load the website. "+ "The page may have navigated unexpectedly.\n"+ "- More implementation details that should not be user-facing.\n"+ "Would you like me to configure a proxy?"+ )+ result = _fake_run_result({"type": "ASK_QUESTION", "user_response": verbose_response})++ agent_result = agent_module._translate_to_agent_result(+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"+ )++ assert agent_result.response_type == "ASK_QUESTION"+ assert len(agent_result.user_response.splitlines()) <= 8+ assert "global_llm_context" not in agent_result.user_response+ assert "configure a proxy" not in agent_result.user_response.lower()+ assert "Would you like me to whether" not in agent_result.user_response+ assert "different proxy location" in agent_result.user_response.lower()+ assert "US-CA" in agent_result.user_response+ assert "Skyvern failed to load the website. The page may have navigated unexpectedly." in (+ agent_result.user_response+ )+ assert "same IP/workflow shape" in agent_result.user_response+def test_reply_still_rewrites_after_failed_test(self) -> None:ctx = _ctx(last_update_block_count=2,diff --git a/tests/unit/test_copilot_probable_site_block.py b/tests/unit/test_copilot_probable_site_block.pyindex cdcf3aa81..8fd05ceef 100644--- a/tests/unit/test_copilot_probable_site_block.py+++ b/tests/unit/test_copilot_probable_site_block.py@@ -14,6 +14,7 @@ from skyvern.forge.sdk.copilot.enforcement import (POST_PROBABLE_SITE_BLOCK_STOP_NUDGE,PROBABLE_SITE_BLOCK_STREAK_STOP_AT,REPEATED_FRONTIER_STREAK_ESCALATE_AT,+ _check_enforcement,_needs_probable_site_block_stop_nudge,_repeated_frontier_failure_nudge,)@@ -345,6 +346,32 @@ def test_nudge_text_is_stop_oriented() -> None:assert "Do NOT" in POST_PROBABLE_SITE_BLOCK_STOP_NUDGE+def test_stop_nudge_uses_different_proxy_advice_when_effective_proxy_is_active() -> None:+ ctx = _fresh_context()+ ctx.probable_site_block_streak_count = PROBABLE_SITE_BLOCK_STREAK_STOP_AT+ ctx.effective_workflow_proxy_location = "RESIDENTIAL"++ nudge = _check_enforcement(ctx)++ assert nudge is not None+ assert "configure a proxy" not in nudge.lower()+ assert "different proxy location" in nudge.lower()+ assert "US-CA" in nudge+ assert "US-NY" in nudge+ assert "residential/ISP" in nudge+++def test_stop_nudge_keeps_configure_proxy_advice_when_proxy_is_none() -> None:+ ctx = _fresh_context()+ ctx.probable_site_block_streak_count = PROBABLE_SITE_BLOCK_STREAK_STOP_AT+ ctx.effective_workflow_proxy_location = "NONE"++ nudge = _check_enforcement(ctx)++ assert nudge is not None+ assert "configure a proxy" in nudge.lower()++def test_detects_challenge_named_wait_block() -> None:assert _detect_timing_only_challenge_wait_blocks(_CHALLENGE_WAIT_WORKFLOW) == ["wait_challenge"]