Skip to content

Automate browser based workflows with AI

Copilot keeps the turn when Skyvern's own proxy tunnel fails (SKY-15738) (#8565)

Andrew Neilson000d8a303ed6
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index 186fb0efe..c0ebea0d9 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -96,6 +96,7 @@ from skyvern.schemas.action_log import ActionLogOutcome, project_action_event
from skyvern.schemas.run_blocks import CredentialType
from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.actions.handler_utils import strategy_aware_input
+from skyvern.webeye.navigation import reported_nav_error_code
from skyvern.webeye.utils.page import SkyvernFrame
from ._common import (
@@ -576,7 +577,16 @@ async def skyvern_navigate(
ok=False,
browser_context=ctx,
timing_ms=timer.timing_ms,
- error=make_error(ErrorCode.ACTION_FAILED, str(e), "Check that the URL is valid and accessible", exc=e),
+ error=make_error(
+ ErrorCode.ACTION_FAILED,
+ str(e),
+ "Check that the URL is valid and accessible",
+ # The driver's own code, read from the exception it raised. A caller deciding who
+ # owns the failure cannot get that from the message: this path returns str(e), and
+ # a page or a model can write any sentence.
+ details={"nav_error_code": await reported_nav_error_code(e, url)},
+ exc=e,
+ ),
)
finally:
# No publication made while navigation was in flight is trustworthy:
diff --git a/skyvern/exceptions.py b/skyvern/exceptions.py
index 5eb9a7af4..d730739b2 100644
--- a/skyvern/exceptions.py
+++ b/skyvern/exceptions.py
@@ -764,9 +764,13 @@ class WorkflowParameterNotFound(SkyvernHTTPException):
class FailedToNavigateToUrl(SkyvernException):
- def __init__(self, url: str, error_message: str) -> None:
+ def __init__(self, url: str, error_message: str, nav_error_code: str | None = None) -> None:
self.url = url
self.error_message = error_message
+ # The driver's own error code, read where the driver raised it. Downstream layers flatten
+ # this exception into a sentence, and a sentence cannot say who wrote it; carrying the code
+ # as a field is what lets a consumer attribute the failure without parsing prose.
+ self.nav_error_code = nav_error_code
super().__init__(f"Failed to navigate to url {url}. Error message: {error_message}")
@@ -785,6 +789,12 @@ class BlockedNavigationDestination(FailedToNavigateToUrl):
# error code stays in the message and would otherwise classify the failure as ours.
NO_ADDRESS_RECORD_NAV_ERROR_MARKER = "has no DNS address record"
+# Shaped like a driver code on purpose: the scrub/restore/preservation pipeline in
+# nav_attribution.py and block.py pattern-matches `net::ERR_[A-Z0-9_]+`, and this rides that same
+# path rather than needing its own case in every one of those gates. It is not a real Chromium
+# error, so no driver or page text can ever produce it; only UnresolvableNavigationHost sets it.
+NO_ADDRESS_RECORD_NAV_ERROR_CODE = "net::ERR_SKYVERN_UNRESOLVABLE_HOST"
+
class UnresolvableNavigationHost(FailedToNavigateToUrl):
"""The navigation target's host has no DNS address record, so no egress of ours can reach it.
@@ -800,6 +810,7 @@ class UnresolvableNavigationHost(FailedToNavigateToUrl):
super().__init__(
url=url,
error_message=f"{host} {NO_ADDRESS_RECORD_NAV_ERROR_MARKER}: {error_message}",
+ nav_error_code=NO_ADDRESS_RECORD_NAV_ERROR_CODE,
)
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index e3d6b69f4..aa6150f3d 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -3315,9 +3315,13 @@ class ForgeAgent:
)
return step, detailed_output, next_step
except FailedToNavigateToUrl as e:
- # Fail the task if we can't navigate to the URL and send the response.
- # Navigation failures are target-site/customer-caused and are surfaced on the run
- # via failure_reason below, so this is expected-and-handled, not an error.
+ # Fail the task if we can't navigate to the URL and send the response. Who owns the
+ # failure is decided downstream from the driver's code, not from this text: Skyvern's
+ # own egress can fail here too.
+ if e.nav_error_code:
+ nav_context = skyvern_context.current()
+ if nav_context is not None:
+ nav_context.task_nav_error_codes[task.task_id] = e.nav_error_code
LOG.warning(
"Failed to navigate to URL, marking task as failed, and sending webhook response",
url=e.url,
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 5cac0f0df..063465f46 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -250,6 +250,9 @@ class CodeBlockEngineFailure:
final_url: str | None = None
page_title: str | None = None
covering_element: str | None = None
+ # Read by the worker from the driver's own error, so a consumer can tell a real browser verdict
+ # from a sentence describing one.
+ nav_error_code: str | None = None
@dataclass(frozen=True)
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 7159c300f..fb28b73e1 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -1620,12 +1620,15 @@ def _normalize_failure_reason(failure_reason: str | None) -> str:
_FAILURE_FOLLOW_UP = {
"NAVIGATION_FAILURE": " Can you confirm the URL is correct?",
- "PROXY_ERROR": " Want me to retry with a different proxy location?",
+ "PROXY_ERROR": " Want me to re-test?",
"PAGE_LOAD_TIMEOUT": " Can you confirm the URL and try again in a moment?",
- "ANTI_BOT_DETECTION": " Want me to retry with a different proxy location?",
+ "ANTI_BOT_DETECTION": " Want me to retry?",
"AUTH_FAILURE": " The site rejected the login — is the stored password still valid?",
"CREDENTIAL_ERROR": " I couldn't find a credential to use — can you link one in Settings?",
}
+# A chat affirmative re-tests on the browser session the turn already holds, so neither offer may
+# promise a different proxy node.
+_SKYVERN_EGRESS_FOLLOW_UP = " That failure was in Skyvern's own proxy hop — want me to re-test?"
def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> str:
@@ -1675,9 +1678,15 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> st
f"Nothing was executed, so the draft is unverified.{keep_draft_affordance}"
)
- failure_summary = _normalize_failure_reason(ctx.last_test_failure_reason)
+ raw_failure_reason = ctx.last_test_failure_reason
+ failure_summary = _normalize_failure_reason(raw_failure_reason)
if not failure_summary.endswith("..."):
failure_summary = failure_summary.rstrip(".")
+ follow_up = _FAILURE_FOLLOW_UP.get(ctx.last_failure_category_top or "", "")
+ # Only the predicate tells Skyvern's own hop apart from a page that says "proxy error"; the
+ # classifier category on its own gets the target-neutral ask.
+ if raw_failure_reason and ctx.last_test_proxy_owned_failure:
+ follow_up = _SKYVERN_EGRESS_FOLLOW_UP
contract = ctx.latest_diagnosis_repair_contract
recorded_run = f"I created {draft_phrase} and tested it, but the test failed. Failure: {failure_summary}."
if contract is not None and (contract.challenge is not None or contract.levers):
@@ -1688,9 +1697,7 @@ def _rewrite_failed_test_response(user_response: str, ctx: CopilotContext) -> st
model_reply = user_response.strip()
if model_reply:
return f"{recorded_run} {model_reply}".rstrip() + keep_draft_affordance
- follow_up = _FAILURE_FOLLOW_UP.get(ctx.last_failure_category_top or "", "")
return f"{recorded_run}{follow_up}{keep_draft_affordance}"
- follow_up = _FAILURE_FOLLOW_UP.get(ctx.last_failure_category_top or "", "")
return f"{recorded_run}{follow_up}{keep_draft_affordance}"
if ctx.last_test_ok is None and block_count is not None and ctx.last_workflow is not None:
@@ -3365,28 +3372,17 @@ def _build_cancel_exit_result(ctx: CopilotContext, global_llm_context: str | Non
return _build_wip_exit_result(ctx, global_llm_context, cancelled=True)
-_PROXY_TRANSPORT_NAV_ERROR_CODES = (
- "net::ERR_TUNNEL_CONNECTION_FAILED",
- "net::ERR_SOCKS_CONNECTION_FAILED",
- "net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE",
-)
-
-
def _non_retriable_nav_reply(error_message: str) -> str:
_, separator, machine_error = error_message.rpartition(". Error message: ")
classification_source = machine_error if separator else error_message
- # Ahead of the proxy-transport branch: a dead domain reaches us wearing a proxy error code, and
- # answering it with "contact Skyvern Support" sends the user to us over a URL only they can fix.
+ # A dead domain reaches us wearing a proxy error code (a proxied browser delegates resolution to
+ # the proxy), and answering it with "contact Skyvern Support" sends the user to us over a URL
+ # only they can fix. This marker is driver-emitted, never model- or page-authored.
if NO_ADDRESS_RECORD_NAV_ERROR_MARKER in classification_source:
return (
f"The site's domain has no DNS record, so it cannot be reached from any network. "
f"Error: {error_message}. Please check the URL for a typo, or confirm the site is still online."
)
- if any(code in classification_source for code in _PROXY_TRANSPORT_NAV_ERROR_CODES):
- return (
- f"The site could not be reached through Skyvern's browser network. Error: {error_message}. "
- "Please try again later, or contact Skyvern Support if the problem continues."
- )
return f"The target URL could not be reached. Error: {error_message}. Please verify the URL and try again."
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 63a86bf17..dd18ad65b 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -36,6 +36,7 @@ from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_structured_prompt
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.workflow.models.workflow import Workflow
+from skyvern.schemas.proxy_location import ProxyLocationInput
LOG = structlog.get_logger()
@@ -1250,10 +1251,7 @@ class CopilotContext(AgentContext):
# (the same source that powers run_outcome SSE frames). Append-only across
# per-run pointer resets (``last_run_outcome = None``) and workflow edits.
run_outcome_trace: list[RecordedRunOutcome] = field(default_factory=list)
- # 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
- effective_workflow_proxy_location: Any | None = None
+ effective_workflow_proxy_location: ProxyLocationInput = None
# Per-request frontier state. `verified_block_outputs` and
# `verified_prefix_labels` are populated ONLY from fully-successful runs —
@@ -1278,11 +1276,8 @@ class CopilotContext(AgentContext):
latest_recorded_build_test_outcome: RecordedBuildTestOutcome | None = None
recorded_build_test_outcome_history: list[dict[str, object]] = field(default_factory=list)
recorded_persisted_block_run_workflow_run_id: str | None = None
- # Set by _record_run_blocks_result when the most recent failed run matches
- # SKIP_INNER_NAV_RETRY_ERRORS (DNS / cert / SSL / invalid URL). Drives the
- # one-shot non-retriable-nav stop nudge and the deterministic exit-path
- # exception in run_with_enforcement. Cleared at the top of every call to
- # _record_run_blocks_result so stale state can't leak across runs.
+ # Set by _record_run_blocks_result when the last failed run blames the target (DNS / cert / SSL / invalid URL),
+ # never Skyvern's own proxy hop; cleared at the top of every call so stale state can't leak across runs.
last_test_non_retriable_nav_error: str | None = None
# Secure-runner codes from the latest run that were faults of the sandbox itself, joined.
# Cleared per run in _record_run_blocks_result, so a later clean run releases the guard.
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
index 4fad5eaf8..e4fa083a8 100644
--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
@@ -24,11 +24,13 @@ from skyvern.forge.sdk.copilot.failure_tracking import (
from skyvern.forge.sdk.copilot.output_policy import url_origin
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.run_outcome import trusted_terminal_challenge_category_name
+from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
run_challenge_is_runtime_clearable,
run_id_from_result_data,
)
from skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE
+from skyvern.schemas.proxy_location import GeoTarget, ProxyLocationInput
from skyvern.webeye.actions.action_types import ActionType
if TYPE_CHECKING:
@@ -394,7 +396,9 @@ def _levers(
"unresolved" if solver_available is None else ("available" if solver_available else "unavailable")
),
),
- Lever(mechanism="proxy_location", knowledge_topic="proxy_location", availability=_proxy_label(ctx)),
+ Lever(
+ mechanism="proxy_location", knowledge_topic="proxy_location", availability=proxy_location_lever_label(ctx)
+ ),
Lever(mechanism="browser_profile", knowledge_topic="proxy_location"),
credential_lever,
human_lever,
@@ -433,38 +437,54 @@ def _solver_available_for_current_page(ctx: CopilotContext, data: dict[str, Any]
_NO_PROXY_VALUES = {"NONE", "NULL", "NO_PROXY"}
-def _raw_proxy_location(ctx: CopilotContext) -> Any:
- raw = getattr(ctx, "effective_workflow_proxy_location", None)
- if raw is None:
- raw = getattr(getattr(ctx, "last_workflow", None), "proxy_location", None)
- return raw
+def _raw_proxy_location(ctx: AgentContext, session_proxy_location: ProxyLocationInput = None) -> ProxyLocationInput:
+ """The proxy the failing hop acted through. A browser session's own proxy overrides the
+ workflow's declared one, the same override real_browser_manager applies when a session is
+ attached; the workflow answers only when no session made the hop."""
+ if session_proxy_location is not None:
+ return session_proxy_location
+ if ctx.effective_workflow_proxy_location is not None:
+ return ctx.effective_workflow_proxy_location
+ if ctx.last_workflow is not None:
+ return ctx.last_workflow.proxy_location
+ return None
def _declares_no_proxy(ctx: CopilotContext) -> bool:
"""True only when the run named a no-proxy location, never when it named nothing at all."""
raw = _raw_proxy_location(ctx)
- if raw is None or isinstance(raw, dict):
+ if raw is None or isinstance(raw, (dict, GeoTarget)):
return False
- value = _safe_str(getattr(raw, "value", raw))
- return value is not None and value.upper() in _NO_PROXY_VALUES
+ return raw.strip().upper() in _NO_PROXY_VALUES
-def _proxy_label(ctx: CopilotContext) -> str | None:
- """A non-secret label for the run's proxy. A custom proxy is a dict whose URL can embed
- credentials, so it is named by shape and never serialized."""
- raw = _raw_proxy_location(ctx)
- if raw is None:
+def proxy_location_label(proxy_location: ProxyLocationInput) -> str | None:
+ """A non-secret label for a proxy. Any dict is a custom proxy whose URL can embed credentials, so
+ it is named by shape and never serialized; a geo target is named by country alone, because
+ joining subdivision and city narrows the label past what naming the failing hop needs."""
+ if proxy_location is None:
return None
- if isinstance(raw, dict):
+ if isinstance(proxy_location, dict):
return "custom proxy"
- country = getattr(raw, "country", None)
- if country is not None:
- parts = [str(country)] + [
- str(part) for part in (getattr(raw, "subdivision", None), getattr(raw, "city", None)) if part
- ]
- return "-".join(parts)
- value = _safe_str(getattr(raw, "value", raw))
- return None if value is None or value.upper() in _NO_PROXY_VALUES else value
+ if isinstance(proxy_location, GeoTarget):
+ country = (proxy_location.country or "").strip()
+ return country or None
+ value = proxy_location.strip()
+ return None if not value or value.upper() in _NO_PROXY_VALUES else value
+
+
+def effective_proxy_label(ctx: AgentContext, session_proxy_location: ProxyLocationInput = None) -> str | None:
+ return proxy_location_label(_raw_proxy_location(ctx, session_proxy_location))
+
+
+def proxy_location_lever_label(ctx: AgentContext) -> str | None:
+ """The lever's availability has to tell one geo target from another or the model can re-propose
+ the location it just ran on, so it keeps the subdivision and city the hop label drops."""
+ raw = _raw_proxy_location(ctx)
+ if not isinstance(raw, GeoTarget):
+ return proxy_location_label(raw)
+ parts = [str(part).strip() for part in (raw.country, raw.subdivision, raw.city) if part and str(part).strip()]
+ return "-".join(parts) or None
def _dict(value: Any) -> dict[str, Any]:
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 4e376d2ce..4f24edbfe 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -52,7 +52,7 @@ from skyvern.forge.sdk.copilot.config import (
)
from skyvern.forge.sdk.copilot.credential_fill_fields import LIVE_SCOUT_CREDENTIAL_FIELDS
from skyvern.forge.sdk.copilot.credential_pause import maybe_credential_pause, release_credential_pause_gate
-from skyvern.forge.sdk.copilot.diagnosis_repair_contract import RepairNextAction
+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import RepairNextAction, effective_proxy_label
from skyvern.forge.sdk.copilot.human_input_wait import HumanInputWait
from skyvern.forge.sdk.copilot.narration import TransitionKind
from skyvern.forge.sdk.copilot.output_extraction_plan import (
@@ -107,6 +107,7 @@ from skyvern.forge.sdk.copilot.unrecoverable_tool_error import (
from skyvern.forge.sdk.copilot.unrecoverable_tool_error import (
_maybe_raise_unrecoverable_tool_error as _maybe_raise_unrecoverable_tool_error,
)
+from skyvern.schemas.proxy_location import ProxyLocationInput
from skyvern.utils.token_counter import count_tokens
if TYPE_CHECKING:
@@ -165,30 +166,21 @@ _TOOL_OUTPUT_TRUNCATION_SUFFIX = "\n... [older tool output truncated]"
_TOOL_OUTPUT_HEAD_TRUNCATION_SUFFIX = "\n... [truncated]"
-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 proxy_hop_failure_reason(
+ ctx: AgentContext,
+ reason: str,
+ session_proxy_location: ProxyLocationInput = None,
+ session_made_hop: bool = False,
+) -> str:
+ # A session that made the hop is the authority on the proxy it used. Reading the workflow's
+ # declared proxy when that session named none would label a location the hop never went through.
+ label = (
+ None
+ if session_made_hop and session_proxy_location is None
+ else effective_proxy_label(ctx, session_proxy_location)
+ )
+ hop = "Skyvern proxy hop failed" if label is None else f"Skyvern proxy hop failed (proxy_location={label})"
+ return f"{hop}: {reason}"
def _current_page_evidence_candidates(ctx: Any) -> list[dict[str, Any]]:
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 25000f84f..5fe404608 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import json
import logging
+import re
import time
from collections.abc import AsyncIterator, Awaitable, Callable
from contextlib import AsyncExitStack, asynccontextmanager
@@ -68,10 +69,12 @@ from skyvern.forge.sdk.copilot.screenshot_utils import (
enqueue_screenshot_from_result,
)
from skyvern.forge.sdk.copilot.secret_scrub import (
+ is_registered_scrub_value,
matching_origin_run_redaction_parameters,
scrub_secrets_from_structure,
)
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from skyvern.forge.sdk.workflow.models.block import parameter_strings
from skyvern.utils.contained_effects import contained_effect
from skyvern.webeye.browser_retirement import BrowserRetirementReason
from skyvern.webeye.browser_state import BrowserState
@@ -345,7 +348,9 @@ def _record_browser_call_outcome(
def _scrub_browser_call_outcome(ctx: AgentContext, outcome: _BrowserCallOutcome) -> _BrowserCallOutcome:
- scrubbed = outcome.with_raw_result(scrub_model_facing_tool_result(ctx, outcome.raw_result()))
+ scrubbed = outcome.with_raw_result(
+ scrub_model_facing_tool_result(ctx, outcome.raw_result(), tool_name=outcome.raw_tool_name)
+ )
if outcome.protocol_error_detail is None:
return scrubbed
detail_result = scrub_model_facing_tool_result(ctx, {"ok": False, "error": outcome.protocol_error_detail})
@@ -661,10 +666,19 @@ def _mapping_keys_preserved(source: Any, scrubbed: Any) -> bool:
return True
-def scrub_model_facing_tool_result(ctx: AgentContext, result: Any) -> dict[str, Any]:
- scrubbed_secrets = scrub_secrets_from_structure(ctx, result)
- if not isinstance(scrubbed_secrets, dict) or not _mapping_keys_preserved(result, scrubbed_secrets):
- return {}
+# A driver navigation token names a Chromium error, but a registered value occurring inside it (a
+# parameter "net") would corrupt it: the model would read a mangled code, and a proxy outage would
+# reach attribution as an authoring defect. A token that is itself a registered value is left scrubbed.
+_DRIVER_NAV_ERROR_CODE = re.compile(r"net::ERR_[A-Z0-9_]+")
+
+
+# Only the navigation tool reports a driver code, and only its own reader writes one. Preserving the
+# field for any tool would let one that echoes an argument into it disclose a registered value.
+_NAVIGATION_TOOL_NAME = "skyvern_navigate"
+
+
+def _active_parameter_sets(ctx: AgentContext) -> list[dict[str, Any]]:
+ """The redaction parameter sets this scrub applies, in the order it applies them."""
parameter_sets: list[dict[str, Any]] = []
parameters = getattr(ctx, "codeblock_redaction_parameters", None)
if isinstance(parameters, dict) and parameters:
@@ -672,9 +686,60 @@ def scrub_model_facing_tool_result(ctx: AgentContext, result: Any) -> dict[str,
origin_parameters = matching_origin_run_redaction_parameters(ctx)
if origin_parameters:
parameter_sets.append(origin_parameters)
+ return parameter_sets
+
+
+def _preserved_nav_code(ctx: AgentContext, tool_name: str | None, value: object) -> str | None:
+ if tool_name != _NAVIGATION_TOOL_NAME:
+ return None
+ if not isinstance(value, str) or not _DRIVER_NAV_ERROR_CODE.fullmatch(value):
+ return None
+ if is_registered_scrub_value(ctx, value):
+ return None
+ # The scrub redacts registered values AND the run's redaction parameters, so a guard that reads
+ # only the first restores whatever the second was hiding. A walk that does not finish cannot say
+ # the code is absent, so it refuses too.
+ for parameter_set in _active_parameter_sets(ctx):
+ carried_strings = parameter_strings(parameter_set)
+ if carried_strings is None or value in carried_strings:
+ return None
+ return value
+
+# Where a navigation code sits: the flattened Copilot result, and the raw MCP error's details.
+_NAV_ERROR_CODE_PARENTS: tuple[tuple[str, ...], ...] = ((), ("error", "details"))
+
+
+def _mapping_at(value: Any, path: tuple[str, ...]) -> dict[str, Any] | None:
+ for key in path:
+ value = value.get(key) if isinstance(value, dict) else None
+ return value if isinstance(value, dict) else None
+
+
+def scrub_model_facing_tool_result(ctx: AgentContext, result: Any, *, tool_name: str | None = None) -> dict[str, Any]:
+ driver_codes = {
+ path: code
+ for path in _NAV_ERROR_CODE_PARENTS
+ if (code := _preserved_nav_code(ctx, tool_name, (_mapping_at(result, path) or {}).get("nav_error_code")))
+ is not None
+ }
+ scrubbed = _scrub_model_facing_tool_result(ctx, result)
+ # An empty result is the fail-closed answer; writing a code into it would read as a successful call.
+ if not scrubbed:
+ return scrubbed
+ for path, code in driver_codes.items():
+ parent = _mapping_at(scrubbed, path)
+ if parent is not None:
+ parent["nav_error_code"] = code
+ return scrubbed
+
+
+def _scrub_model_facing_tool_result(ctx: AgentContext, result: Any) -> dict[str, Any]:
+ scrubbed_secrets = scrub_secrets_from_structure(ctx, result)
+ if not isinstance(scrubbed_secrets, dict) or not _mapping_keys_preserved(result, scrubbed_secrets):
+ return {}
scrubbed = scrubbed_secrets
- for parameter_set in parameter_sets:
+ for parameter_set in _active_parameter_sets(ctx):
candidate = app.AGENT_FUNCTION.redact_codeblock_parameter_values(scrubbed, parameter_set)
if not isinstance(candidate, dict) or not _mapping_keys_preserved(scrubbed, candidate):
return {}
@@ -1577,7 +1642,7 @@ class SkyvernOverlayMCPServer(MCPServer):
_record_browser_call_outcome(copilot_ctx, outcome, call_path="model")
result = _project_browser_call_outcome(outcome, display_tool_name=tool_name)
else:
- result = scrub_model_facing_tool_result(copilot_ctx, result)
+ result = scrub_model_facing_tool_result(copilot_ctx, result, tool_name=mcp_name)
LOG.info("Raw-secret safety blocked MCP browser tool", tool_name=tool_name)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, result)
return _copilot_to_call_tool_result(result, tool_name)
@@ -1611,7 +1676,7 @@ class SkyvernOverlayMCPServer(MCPServer):
_record_browser_call_outcome(copilot_ctx, outcome, call_path="model")
hook_result = _project_browser_call_outcome(outcome, display_tool_name=tool_name)
else:
- hook_result = scrub_model_facing_tool_result(copilot_ctx, hook_result)
+ hook_result = scrub_model_facing_tool_result(copilot_ctx, hook_result, tool_name=mcp_name)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, hook_result)
return _copilot_to_call_tool_result(hook_result, tool_name)
return None
@@ -1727,7 +1792,7 @@ class SkyvernOverlayMCPServer(MCPServer):
phases.pause()
# Scrub before the post hook so evidence the hooks record from raw_mcp
# (flow evidence, scout observations) is scrubbed too.
- raw_mcp = scrub_model_facing_tool_result(copilot_ctx, raw_mcp)
+ raw_mcp = scrub_model_facing_tool_result(copilot_ctx, raw_mcp, tool_name=mcp_name)
session_lost = False
error_code = browser_outcome.error_code if browser_outcome is not None else _browser_error_code(raw_mcp)
if (
@@ -1826,7 +1891,7 @@ class SkyvernOverlayMCPServer(MCPServer):
**binding.provenance(),
}
- copilot_result = scrub_model_facing_tool_result(copilot_ctx, copilot_result)
+ copilot_result = scrub_model_facing_tool_result(copilot_ctx, copilot_result, tool_name=mcp_name)
def _commit_evidence() -> None:
if browser_outcome is not None:
@@ -2145,7 +2210,7 @@ class SkyvernOverlayMCPServer(MCPServer):
result=_project_browser_call_outcome(outcome, display_tool_name=mcp_tool_name),
browser_outcome=outcome,
)
- return _InternalToolCallResult(result=scrub_model_facing_tool_result(ctx, result))
+ return _InternalToolCallResult(result=scrub_model_facing_tool_result(ctx, result, tool_name=mcp_tool_name))
phases.enter("session_prepare")
try:
err, continuity_result, continuity_disposition = await _prepare_browser_session_for_dispatch(
@@ -2392,7 +2457,7 @@ class SkyvernOverlayMCPServer(MCPServer):
phases.settle()
call_status = "error" if failed else post_dispatch_status
_log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, raw_mcp, "internal", call_status)
- scrubbed = scrub_model_facing_tool_result(ctx, raw_mcp)
+ scrubbed = scrub_model_facing_tool_result(ctx, raw_mcp, tool_name=mcp_tool_name)
error_code = browser_outcome.error_code if browser_outcome is not None else _browser_error_code(scrubbed)
if (
ctx.turn_origin != TurnOrigin.runtime_self_heal
diff --git a/skyvern/forge/sdk/copilot/nav_attribution.py b/skyvern/forge/sdk/copilot/nav_attribution.py
new file mode 100644
index 000000000..36634d022
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/nav_attribution.py
@@ -0,0 +1,189 @@
+"""Who owns a navigation failure: Skyvern's egress, or the target.
+
+Decided from the codes the driver itself reported — carried on the block result's ``error_codes``
+— never from the failure sentence. That sentence is model-authored on some paths
+(``skyvern/forge/agent.py`` copies a task's reasoning into ``failure_reason`` verbatim), so a page
+or a model can reproduce any wording; text can never say who wrote it.
+
+``error_codes`` also carries a block's declared error code, which the workflow author writes. The
+codes below are ``net::`` tokens a declaration would have to impersonate deliberately; that is a
+narrower surface than free prose, not an absent one.
+
+A leaf because enforcement imports runtime authoring repair, so the predicate cannot live in
+enforcement and still be read by both.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Iterable, Iterator
+
+from skyvern.constants import SKIP_INNER_NAV_RETRY_ERRORS
+from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_CODE
+
+# Skyvern's own CONNECT hop failing before the site is ever contacted. EGRESS_ATTRIBUTABLE_NAV_ERRORS
+# (skyvern/constants.py) adds DNS and certificate-authority codes; only these three rule out the target.
+PROXY_TRANSPORT_NAV_ERROR_CODES = (
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ "net::ERR_SOCKS_CONNECTION_FAILED",
+ "net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE",
+)
+
+
+_DRIVER_NAV_ERROR_CODE = re.compile(r"net::ERR_[A-Z0-9_]+")
+
+TERMINAL_NAV_ERROR_CODES = tuple(
+ code for code in SKIP_INNER_NAV_RETRY_ERRORS if code not in PROXY_TRANSPORT_NAV_ERROR_CODES
+)
+
+# NO_ADDRESS_RECORD_NAV_ERROR_CODE is a synthetic Skyvern sentinel, not one of the codes Chromium
+# itself reports (contrast PROXY_TRANSPORT_NAV_ERROR_CODES, 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)
+
+
+def proxy_owns_nav_codes(codes: Iterable[str | None]) -> bool:
+ """True when the driver's own codes name Skyvern's proxy hop and none of them names the target.
+
+ Callers must pass codes the driver produced — a block's ``error_codes`` or the browser state's
+ recorded code — never tokens recovered from a failure sentence.
+ """
+ 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):
+ return False
+ return any(code in PROXY_TRANSPORT_NAV_ERROR_CODES 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.
+ """
+ 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)
+
+
+def _declared_error_code(source: dict[str, object]) -> str | None:
+ """The error code this block's author declared and raised, if that is how it failed.
+
+ Such a code lands in ``error_codes`` beside driver-reported ones, and the author picks its
+ spelling -- in a copilot session that author is the model. Only the declared path names it in
+ the output, so it can be dropped without discarding what a driver reported alongside it.
+ """
+ output = source.get("output")
+ declared = output.get("declared_error_code") if isinstance(output, dict) else None
+ return declared if isinstance(declared, str) and declared else None
+
+
+def driver_nav_code_positions(result: object) -> list[tuple[int, int, str]]:
+ """``(holder, index, code)`` for each driver navigation code in a run result's ``error_codes``.
+
+ Holder 0 is the run, then each block in order. A caller that has to scrub the result snapshots
+ these first: a registered value occurring inside a code ("net") would otherwise corrupt the verdict.
+ Declared codes are left out, since their author chose the spelling.
+ """
+ data = result.get("data") if isinstance(result, dict) else None
+ if not isinstance(data, dict):
+ return []
+ blocks = data.get("blocks")
+ holders = [data, *(blocks if isinstance(blocks, list) else [])]
+ return [
+ (holder_index, code_index, code)
+ for holder_index, holder in enumerate(holders)
+ if isinstance(holder, dict) and isinstance(holder.get("error_codes"), list)
+ for code_index, code in enumerate(holder["error_codes"])
+ if isinstance(code, str) and _DRIVER_NAV_ERROR_CODE.fullmatch(code) and code != _declared_error_code(holder)
+ ]
+
+
+def restore_driver_nav_codes(result: object, positions: list[tuple[int, int, str]]) -> None:
+ data = result.get("data") if isinstance(result, dict) else None
+ if not isinstance(data, dict):
+ return
+ blocks = data.get("blocks")
+ holders = [data, *(blocks if isinstance(blocks, list) else [])]
+ for holder_index, code_index, code in positions:
+ holder = holders[holder_index] if holder_index < len(holders) else None
+ codes = holder.get("error_codes") if isinstance(holder, dict) else None
+ if isinstance(codes, list) and code_index < len(codes):
+ codes[code_index] = code
+
+
+def _codes_of(source: object) -> list[str]:
+ if not isinstance(source, dict):
+ return []
+ declared = _declared_error_code(source)
+ return [code for code in source.get("error_codes") or [] if isinstance(code, str) and code and code != declared]
+
+
+def _reason_of(source: dict[str, object]) -> str:
+ reason = source.get("failure_reason")
+ return reason if isinstance(reason, str) and reason else ""
+
+
+def iter_failure_reason_codes(result: object) -> Iterator[tuple[str, list[str]]]:
+ """Each failure a reader may see, paired with the codes reported for that same failure.
+
+ Paired by position rather than by matching reason text back to a block: two blocks can report
+ the same sentence, and resolving both occurrences to one of them hides the other's verdict.
+ Newest block first, matching the order a displayed reason is chosen in.
+ """
+ if not isinstance(result, dict):
+ return
+ data = result.get("data")
+ data = data if isinstance(data, dict) else {}
+ blocks = [block for block in data.get("blocks") or [] if isinstance(block, dict)]
+ run_level = data.get("failure_reason")
+ if isinstance(run_level, str) and run_level:
+ # The run reported the failure it ended on, and the block that reported that failure answers
+ # for it: the newest one that failed, which is also the sentence a reader is shown. A block
+ # the run was told to continue past is a failure the run carried on from, not this one.
+ ended_on = next((block for block in reversed(blocks) if _reason_of(block) or _codes_of(block)), None)
+ run_codes = _codes_of(data)
+ if ended_on is None or not _reason_of(ended_on):
+ # Nothing reported a sentence of its own, so the run's answers -- with the codes of the
+ # block it ended on, which would otherwise carry a verdict nothing reports.
+ yield run_level, run_codes or _codes_of(ended_on)
+ return
+ if run_codes:
+ yield run_level, run_codes
+ blocks = [ended_on]
+ for block in reversed(blocks):
+ reason = _reason_of(block)
+ if reason:
+ yield reason, _codes_of(block)
+
+
+def block_nav_error_codes(result: object, reason: str | None = None) -> list[str]:
+ """The driver-reported codes behind the reason a reader will see.
+
+ With a ``reason``, only the block that reported it answers: a run whose first block timed out
+ and whose second hit the proxy must not have the timeout attributed to Skyvern's egress. Without
+ one, every code on the result answers.
+ """
+ if not isinstance(result, dict):
+ return []
+ data = result.get("data")
+ data = data if isinstance(data, dict) else {}
+ blocks = [block for block in data.get("blocks") or [] if isinstance(block, dict)]
+ if reason is not None:
+ # Newest first: the displayed reason is selected from the newest block, so two blocks
+ # sharing reason text would otherwise attribute the older one's codes.
+ owner = next((block for block in reversed(blocks) if block.get("failure_reason") == reason), None)
+ if owner is not None:
+ return _codes_of(owner)
+ # A reason no block reported -- a connect failure, or text the recorder composed -- is not
+ # any one block's, so the run answers for it.
+ codes: list[str] = []
+ for source in (data, *blocks):
+ for code in _codes_of(source):
+ if code not in codes:
+ codes.append(code)
+ return codes
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index a5e32378f..28f89d7c4 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -55,6 +55,7 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.schemas.credentials import Credential
from skyvern.library.skyvern_browser import SkyvernBrowser
from skyvern.schemas.browser_session_close import BrowserSessionCloseReason
+from skyvern.schemas.proxy_location import ProxyLocationInput
from skyvern.webeye.browser_errors import (
BrowserCdpAcquisitionError,
BrowserCdpConnectionError,
@@ -81,6 +82,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.copilot.turn_halt import TurnHalt
from skyvern.forge.sdk.core.event_source_stream import EventSourceStream
from skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice
+ from skyvern.forge.sdk.workflow.models.workflow import Workflow
LOG = structlog.get_logger()
@@ -510,7 +512,7 @@ class AgentContext:
last_test_non_retriable_nav_error: str | None = None
last_infrastructure_tool_error: str | None = None
workflow_persisted: bool = False
- last_workflow: Any | None = None
+ last_workflow: Workflow | None = None
last_workflow_yaml: str | None = None
staged_workflow_yaml: str | None = None
staged_workflow: Any | None = None
@@ -528,7 +530,16 @@ class AgentContext:
request_policy: RequestPolicy | None = None
copilot_config: CopilotConfig | None = None
block_authoring_policy: BlockAuthoringPolicy = BlockAuthoringPolicy.STANDARD
- effective_workflow_proxy_location: Any | None = None
+ effective_workflow_proxy_location: ProxyLocationInput = None
+ # The proxy the last dispatched run acted through, which is the attached session's whenever it
+ # declares one. Kept apart from the declared location above, which the repair levers read.
+ last_run_proxy_location: ProxyLocationInput = None
+ # The run attached a browser session, so last_run_proxy_location is that session's answer and
+ # the workflow's declared proxy must not stand in for it.
+ last_run_proxy_from_session: bool = False
+ # Whether the driver's own codes on the last run named Skyvern's proxy hop. Computed once
+ # from the run result's error_codes so no later reader has to re-decide it from prose.
+ last_test_proxy_owned_failure: bool = False
copilot_run_start_monotonic: float | None = None
@@ -721,6 +732,13 @@ def mcp_to_copilot(mcp_result: dict[str, Any]) -> dict[str, Any]:
error_code = error.get("code")
if isinstance(error_code, str) and error_code:
result["error_code"] = error_code
+ # The message is flattened to a string here, which loses everything a reader needs to
+ # tell a real driver verdict from a sentence describing one. The driver's own navigation
+ # code is lifted out of details so it survives as a value rather than as prose.
+ details = error.get("details")
+ nav_error_code = details.get("nav_error_code") if isinstance(details, dict) else None
+ if isinstance(nav_error_code, str) and nav_error_code:
+ result["nav_error_code"] = nav_error_code
else:
result["error"] = str(error)
diff --git a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
index 19d4bd98e..ff2e1e0b6 100644
--- a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
+++ b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
@@ -675,6 +675,11 @@ def _error_text_requires_stop(copilot_ctx: Any, data: dict[str, Any], result: di
text_values = [data.get("failure_reason"), data.get("skip_reason")]
if result is not None:
text_values.append(result.get("error"))
+ # A failure in Skyvern's own egress is not a defect in the block, so authoring repair must not
+ # rewrite working code to chase it. This is the precedence the terminal-nav condition used to
+ # supply for these codes before that condition narrowed to target-owned failures.
+ if getattr(copilot_ctx, "last_test_proxy_owned_failure", False):
+ return True
text = " ".join(str(value).lower() for value in text_values if value)
return (
"browser session not found" in text
diff --git a/skyvern/forge/sdk/copilot/secret_scrub.py b/skyvern/forge/sdk/copilot/secret_scrub.py
index f28bd6c26..fdbf794b6 100644
--- a/skyvern/forge/sdk/copilot/secret_scrub.py
+++ b/skyvern/forge/sdk/copilot/secret_scrub.py
@@ -216,6 +216,15 @@ def scrub_all_registered_from_text(text: str) -> str:
return text
+def is_registered_scrub_value(ctx: AgentContext, value: object) -> bool:
+ """True when this exact string is one of the values registered for scrubbing.
+
+ A caller that preserves a machine token across a scrub asks this first: the token itself may be
+ the secret, and writing it back would undo the scrub for the one value that needed it.
+ """
+ return isinstance(value, str) and value in _registered_scrub_values(ctx)
+
+
def scrub_secrets_from_structure(ctx: AgentContext, obj: Any) -> Any:
return _scrub_structure(_registered_scrub_values(ctx), obj)
diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.py
index e7cd93926..bfc429821 100644
--- a/skyvern/forge/sdk/copilot/tools/_shared.py
+++ b/skyvern/forge/sdk/copilot/tools/_shared.py
@@ -11,6 +11,7 @@ import structlog
import yaml
from typing_extensions import TypedDict
+from skyvern.forge import app
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal
from skyvern.forge.sdk.copilot.composition_browser_expressions import (
COMPOSITION_STRIPPED_HTML_EXPRESSION as _COMPOSITION_STRIPPED_HTML_EXPRESSION,
@@ -35,7 +36,9 @@ from skyvern.forge.sdk.copilot.enforcement import (
TOTAL_TIMEOUT_SECONDS,
_elapsed_run_seconds,
_requested_output_labels_by_path,
+ proxy_hop_failure_reason,
)
+from skyvern.forge.sdk.copilot.nav_attribution import proxy_owns_nav_codes
from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
effective_browser_session_id,
@@ -50,6 +53,7 @@ from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.schemas.proxy_location import ProxyLocationInput
from skyvern.schemas.workflows import BlockType
from skyvern.utils.yaml_loader import safe_load_no_dates
@@ -608,12 +612,72 @@ async def _discovery_navigate(
nav_args["timeout"] = int(timeout_seconds * 1000)
cap = timeout_seconds + 5
try:
- return await asyncio.wait_for(
+ result = await asyncio.wait_for(
server.call_internal_tool("skyvern_navigate", nav_args),
timeout=cap,
)
except TimeoutError:
return {"ok": False, "error": f"skyvern_navigate timed out after {timeout_seconds:g}s"}
+ return await attribute_navigation_failure(ctx, result)
+
+
+async def browser_session_hop_proxy(
+ ctx: AgentContext, session_id: str | None = None
+) -> tuple[bool, ProxyLocationInput]:
+ """Whether a browser session made this hop, and the proxy it was given.
+
+ The session's answer governs even when it is None. The browser layer reuses an attached session's
+ existing state instead of applying the workflow's declared proxy, so falling back to that
+ declaration would name a location the hop never used.
+ """
+ session_id = session_id or effective_browser_session_id(ctx)
+ if not session_id:
+ return False, None
+ try:
+ session = await app.PERSISTENT_SESSIONS_MANAGER.get_session(session_id, ctx.organization_id)
+ except Exception:
+ LOG.warning(
+ "Could not read the browser session's proxy for failure attribution",
+ organization_id=ctx.organization_id,
+ exc_info=True,
+ )
+ return True, None
+ return True, session.proxy_location if session is not None else None
+
+
+async def attribute_navigation_failure(ctx: AgentContext, result: dict[str, Any]) -> dict[str, Any]:
+ """Name Skyvern's proxy hop in a failed navigation before anything downstream renders it.
+
+ Scouting has no run row to read codes from, so the code comes off the call that failed and the
+ proxy off the browser state that made the hop. The failure text is rendered, never inspected --
+ an MCP error string is as reproducible as any other prose.
+ """
+ if result.get("ok") or not isinstance(result.get("error"), str):
+ return result
+ # Only the code this call reported. The browser state's code is cleared by a successful
+ # state-managed navigation, which an MCP hop never performs, so reading it here would let an
+ # earlier failure's code attach to a later call that reported none of its own.
+ #
+ # Asked before the state is resolved: every other failure then leaves this seam without paying
+ # for a session lookup, and a lookup that fails cannot replace a failure it was only labelling.
+ if not proxy_owns_nav_codes([result.get("nav_error_code")]):
+ return result
+ if not effective_browser_session_id(ctx):
+ return result
+ try:
+ browser_state = await resolve_browser_state_for_context(ctx)
+ except Exception: # noqa: BLE001 - an unreadable session costs the proxy name, not the failure.
+ LOG.warning("Could not resolve the browser state to name the proxy hop", exc_info=True)
+ browser_state = None
+ # With no state the proxy is unknown, and proxy_hop_failure_reason drops the parenthetical
+ # rather than naming one the hop may not have used.
+ attributed = proxy_hop_failure_reason(
+ ctx,
+ result["error"],
+ browser_state.built_with_proxy_location if browser_state is not None else None,
+ session_made_hop=True,
+ )
+ return {**result, "error": attributed}
async def _discovery_get_html(ctx: CopilotContext) -> dict[str, Any]:
diff --git a/skyvern/forge/sdk/copilot/tools/composition_capture.py b/skyvern/forge/sdk/copilot/tools/composition_capture.py
index 7f355bc74..a713e0199 100644
--- a/skyvern/forge/sdk/copilot/tools/composition_capture.py
+++ b/skyvern/forge/sdk/copilot/tools/composition_capture.py
@@ -33,9 +33,13 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
)
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import author_time_levers
-from skyvern.forge.sdk.copilot.enforcement import _RECENT_TOOL_OUTPUT_CHAR_CAP, _requested_output_labels_by_path
+from skyvern.forge.sdk.copilot.enforcement import (
+ _RECENT_TOOL_OUTPUT_CHAR_CAP,
+ _requested_output_labels_by_path,
+)
from skyvern.forge.sdk.copilot.llm_config import resolve_fast_copilot_handler
from skyvern.forge.sdk.copilot.output_extraction_plan import _exact_path, _value_witness_bindings
+from skyvern.forge.sdk.copilot.run_outcome import run_outcome_display_reason
from skyvern.forge.sdk.copilot.runtime import (
SENSITIVE_ORIGIN_ACTIVE_RUN_PAGE_ERROR,
SENSITIVE_ORIGIN_PAGE_ERROR,
@@ -450,6 +454,11 @@ async def _composition_evidence_after_navigation_failure(
navigation_error: str,
requested_reads: tuple[AdmittedOutputRead, ...] = (),
) -> tuple[dict[str, Any], CapturedFrame | None] | None:
+ # The capture succeeds on Chrome's error page, so without the error the packet is the interstitial.
+ # The text is model-facing, so it takes the same redaction and URL-to-origin rewrite as a run reason.
+ displayed_error = run_outcome_display_reason(navigation_error) or ""
+ before_html_capture = f"navigation_error_before_html_capture: {displayed_error}"
+ before_evidence_capture = f"navigation_error_before_evidence_capture: {displayed_error}"
current_url, _ = await _fallback_page_info(ctx)
current_url = current_url or inspected_url
requested_targets = _seeded_capture_targets(ctx, requested_reads)
@@ -462,7 +471,7 @@ async def _composition_evidence_after_navigation_failure(
if structured is not None and has_bounded_page_schema(structured):
evidence = _composition_add_inspection_warning(
structured,
- "navigation_error_before_html_capture",
+ before_html_capture,
)
frame = None
if page_evidence_needs_visual_fallback(evidence):
@@ -475,7 +484,7 @@ async def _composition_evidence_after_navigation_failure(
evidence = parse_composition_html("", inspected_url=inspected_url, current_url=current_url)
evidence = _composition_add_inspection_warning(
evidence,
- "navigation_error_before_evidence_capture",
+ before_evidence_capture,
)
evidence = _composition_add_inspection_warning(
evidence,
@@ -495,7 +504,7 @@ async def _composition_evidence_after_navigation_failure(
)
evidence = _composition_add_inspection_warning(
evidence,
- "navigation_error_before_html_capture",
+ before_html_capture,
)
if html_truncated:
evidence = _composition_add_inspection_warning(evidence, "html_sliced_at_cap")
@@ -508,7 +517,7 @@ async def _composition_evidence_after_navigation_failure(
evidence = parse_composition_html("", inspected_url=inspected_url, current_url=current_url)
evidence = _composition_add_inspection_warning(
evidence,
- "navigation_error_before_evidence_capture",
+ before_evidence_capture,
)
evidence = _composition_add_inspection_warning(
evidence,
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index b15e806af..03f8a8f41 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -75,6 +75,7 @@ from ._shared import (
_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
_composition_get_structured_evidence,
_fallback_page_info,
+ attribute_navigation_failure,
)
from .banned_blocks import (
_CODE_ONLY_TARGET_EVIDENCE_KEYS,
@@ -894,7 +895,7 @@ async def _navigate_post_hook(
source_tool="navigate_browser",
captured_url=source_url,
)
- return result
+ return await attribute_navigation_failure(ctx, result)
async def _navigate_pre_hook(
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 87f68eddc..a2a470431 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -113,11 +113,22 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
DiagnosisRepairContract,
build_diagnosis_repair_contract,
)
+from skyvern.forge.sdk.copilot.enforcement import (
+ proxy_hop_failure_reason,
+)
from skyvern.forge.sdk.copilot.failure_tracking import _blocks_by_label, block_shape_hashes_by_label
from skyvern.forge.sdk.copilot.frontier_provenance_dump import frontier_dump_root, trust_snapshot, write_packet
from skyvern.forge.sdk.copilot.narration import _TERMINAL_BLOCK_STATUSES, NarratorState
from skyvern.forge.sdk.copilot.narration import handler_available as narration_handler_available
from skyvern.forge.sdk.copilot.narration import narrator_poll_tick
+from skyvern.forge.sdk.copilot.nav_attribution import (
+ block_nav_error_codes,
+ driver_nav_code_positions,
+ iter_failure_reason_codes,
+ proxy_owns_nav_codes,
+ restore_driver_nav_codes,
+ target_owns_nav_codes,
+)
from skyvern.forge.sdk.copilot.outcome_verification_trace import record_gate_decision
from skyvern.forge.sdk.copilot.output_utils import (
_INTERNAL_GOAL_PATH_OMISSIONS_KEY,
@@ -176,6 +187,7 @@ from skyvern.forge.sdk.copilot.screenshot_utils import (
)
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.secret_scrub import (
+ is_registered_scrub_value,
register_matching_origin_run_redaction_values,
register_secret_scrub_values_from_structure,
scrub_secrets_from_structure,
@@ -209,11 +221,11 @@ from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, Wo
from skyvern.forge.sdk.workflow.runtime_completion import contract_from_request_criteria
from skyvern.forge.sdk.workflow.runtime_secret_bridge import consume_copilot_runtime_secret_values
from skyvern.forge.sdk.workflow.service import run_selection_is_partial
+from skyvern.schemas.proxy_location import runtime_proxy_location
from skyvern.schemas.workflows import BlockStatus, BlockType
from skyvern.utils.files import initialize_skyvern_state_file
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus
-from skyvern.webeye.navigation import is_skip_inner_retry_error
from skyvern.webeye.utils.page import SkyvernFrame
from ._shared import (
@@ -228,6 +240,7 @@ from ._shared import (
_valid_runtime_anchor_url,
_workflow_definition_block_labels,
_workflow_verification_evidence,
+ browser_session_hop_proxy,
)
from .banned_blocks import _copilot_block_authoring_policy
from .blockers import (
@@ -3053,6 +3066,10 @@ async def _run_blocks_and_collect_debug(
ctx.last_frontier_start_label = frontier_start_label
ctx.last_run_blocks_block_ids = []
ctx.last_run_blocks_block_labels = []
+ # Only a dispatched run sets this below; cleared here so a turn that bails before dispatch
+ # cannot label its recorded failure with the previous run's proxy.
+ ctx.last_run_proxy_location = None
+ ctx.last_run_proxy_from_session = False
# Verified state is NOT invalidated pre-run. On a failed / partial run we
# want the prior verified prefix preserved so the next edit can still use
# the optimization. YAML-diff-based invalidation for edited/downstream
@@ -3489,6 +3506,13 @@ async def _run_blocks_and_collect_debug(
"error": "The pending Copilot proposal changed before the test started; reload and try again.",
}
ctx.dispatched_run_ids_this_turn.add(workflow_run.workflow_run_id)
+ # The browser session the run attaches overrides the run row's proxy in the browser layer,
+ # so the proxy this run acts through is the session's whenever it declares one.
+ session_made_hop, run_session_proxy_location = await browser_session_hop_proxy(ctx, run_session_id)
+ ctx.last_run_proxy_from_session = session_made_hop
+ ctx.last_run_proxy_location = (
+ run_session_proxy_location if session_made_hop else runtime_proxy_location(workflow_run.proxy_location)
+ )
# The ordinary Track-A producer owns this registry at run creation. Keeping the run id and
# serialized values in one immutable carrier prevents a later context from vouching for it.
@@ -4620,20 +4644,42 @@ def _terminal_challenge_completion_verification(
)
-# 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; update the tuple if that wording changes.
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.
- Same set is_skip_inner_retry_error uses at the browser layer, so the copilot
- classifies on exactly the patterns that already short-circuit retries in
- navigate_with_retry (skyvern/webeye/navigation.py)."""
- return next((reason for reason in iter_failure_reasons(result) if is_skip_inner_retry_error(reason)), None)
+ """Return the failure_reason the driver blamed on the target (DNS / cert / SSL / invalid URL).
+
+ Ownership comes from the codes the driver reported for that reason, the same channel proxy
+ ownership uses, never from the reason text: failure_reason is model-authored on some paths, so a
+ quoted code is a sentence about a verdict rather than the verdict. A resolver-corroborated dead
+ host is no exception: UnresolvableNavigationHost carries NO_ADDRESS_RECORD_NAV_ERROR_CODE as its
+ own driver code, so it reaches target_owns_nav_codes through the same channel as any other.
+ """
+ return next(
+ (reason for reason, codes in iter_failure_reason_codes(result) if target_owns_nav_codes(codes)),
+ None,
+ )
+
+
+def _proxy_attributed_failure_reason(
+ copilot_ctx: CopilotContext, reason: str | None, result: dict[str, Any]
+) -> str | None:
+ """Name Skyvern's proxy hop in the recorded reason, so the run observation and every later reply
+ that renders it inherit the attribution. A run the target also failed keeps its own reason: the
+ stop decision owns that one.
+
+ Ownership comes from the codes the driver reported on the result, never from ``reason`` itself:
+ a task's failure_reason can be model-authored verbatim."""
+ if (
+ not reason
+ or copilot_ctx.last_test_non_retriable_nav_error is not None
+ or not proxy_owns_nav_codes(block_nav_error_codes(result, reason))
+ ):
+ return reason
+ return proxy_hop_failure_reason(
+ copilot_ctx,
+ reason,
+ copilot_ctx.last_run_proxy_location,
+ session_made_hop=copilot_ctx.last_run_proxy_from_session,
+ )
def _infrastructure_runner_error_codes(result: dict[str, Any]) -> list[str]:
@@ -4765,6 +4811,9 @@ def _record_run_blocks_result(
copilot_ctx.last_test_anti_bot = None
copilot_ctx.last_failure_category_top = None
copilot_ctx.last_test_non_retriable_nav_error = None
+ # Cleared per run beside its sibling: the flag is only assigned past the success-path return, so
+ # without this one proxy failure would hold authoring repair off for the rest of the session.
+ copilot_ctx.last_test_proxy_owned_failure = False
copilot_ctx.last_infrastructure_tool_error = None
copilot_ctx.post_run_page_observation_tool = None
copilot_ctx.post_run_page_observation_url = None
@@ -4969,15 +5018,21 @@ def _record_run_blocks_result(
# User-facing surfaces read this; the result dict keeps the run's own reason for the
# repair signature, the failure summary and loop detection.
copilot_ctx.last_test_failure_reason = connect_failure_reason
+ # Scoped to the reason a reader will see, exactly as the attribution below is: a run whose first
+ # block timed out and whose second hit the proxy shows the timeout, so calling that run
+ # proxy-owned would put egress copy on it and hold authoring repair off the block that failed.
+ copilot_ctx.last_test_proxy_owned_failure = proxy_owns_nav_codes(
+ block_nav_error_codes(result, copilot_ctx.last_test_failure_reason)
+ )
+ copilot_ctx.last_test_failure_reason = _proxy_attributed_failure_reason(
+ copilot_ctx, copilot_ctx.last_test_failure_reason, result
+ )
_update_verification_evidence_from_run_result(copilot_ctx, result)
+ displayed_failure_reason = copilot_ctx.last_test_failure_reason or str(result.get("error") or "The run failed.")
recorded_outcome = RecordedRunOutcome(
verdict="not_demonstrated",
reason_code="blocker_reported",
- display_reason=run_outcome_display_reason(
- connect_failure_reason
- or copilot_ctx.last_test_failure_reason
- or str(result.get("error") or "The run failed.")
- ),
+ display_reason=run_outcome_display_reason(displayed_failure_reason),
workflow_run_id=run_id if isinstance(run_id, str) else None,
run_completed=False,
)
@@ -4988,15 +5043,26 @@ def _record_run_blocks_result(
_EXECUTED_BLOCK_STATUSES = frozenset(status.value for status in BlockStatus if status != BlockStatus.skipped)
+def _preserved_driver_nav_codes(copilot_ctx: CopilotContext, result: dict[str, Any]) -> list[tuple[int, int, str]]:
+ """The driver codes to put back after scrubbing: a code that is itself a registered value stays scrubbed."""
+ return [
+ position
+ for position in driver_nav_code_positions(result)
+ if not is_registered_scrub_value(copilot_ctx, position[2])
+ ]
+
+
def _commit_run_blocks_record(copilot_ctx: CopilotContext, result: dict[str, Any]) -> RecordedRunOutcome | None:
"""Commit the run's structured outcome once, marking the result so the shared seam does not redo it.
The browser-loss stamp runs here rather than at the shared seam: the commit happens upstream of
that seam, so a stamp applied there would never reach the committed record."""
+ driver_codes = _preserved_driver_nav_codes(copilot_ctx, result)
sanitized = scrub_secrets_from_structure(copilot_ctx, result)
if sanitized is not result:
result.clear()
result.update(sanitized)
+ restore_driver_nav_codes(result, driver_codes)
connect_failure_reason = _stamp_run_side_connect_failure(copilot_ctx, result)
recorded = _record_run_blocks_result(
copilot_ctx, result, completion_verification=None, connect_failure_reason=connect_failure_reason
@@ -6127,14 +6193,28 @@ def finalize_build_test_result(
"challenge_notices": challenge_notices(contract.challenge, list(contract.levers)),
}
)
- data[BUILD_TEST_PACKET_KEY] = scrub_secrets_from_structure(
- copilot_ctx,
- packet.model_dump(mode="json", exclude_none=True),
- )
+ # Both scrubs below reach the model, so the driver codes the run commit restored are restored again:
+ # in the result, and in the packet's copy of the failed block's codes.
+ driver_codes = _preserved_driver_nav_codes(copilot_ctx, result)
+ driver_code_values = {code for _, _, code in driver_codes}
+ packet_payload = packet.model_dump(mode="json", exclude_none=True)
+ packet_failure = packet_payload.get("failure")
+ packet_codes = packet_failure.get("error_codes") if isinstance(packet_failure, dict) else None
+ packet_driver_codes = [(index, code) for index, code in enumerate(packet_codes or []) if code in driver_code_values]
+ data[BUILD_TEST_PACKET_KEY] = scrub_secrets_from_structure(copilot_ctx, packet_payload)
sanitized = scrub_secrets_from_structure(copilot_ctx, result)
if sanitized is not result:
result.clear()
result.update(sanitized)
+ restore_driver_nav_codes(result, driver_codes)
+ scrubbed_data = result.get("data")
+ scrubbed_packet = scrubbed_data.get(BUILD_TEST_PACKET_KEY) if isinstance(scrubbed_data, dict) else None
+ scrubbed_failure = scrubbed_packet.get("failure") if isinstance(scrubbed_packet, dict) else None
+ scrubbed_codes = scrubbed_failure.get("error_codes") if isinstance(scrubbed_failure, dict) else None
+ if isinstance(scrubbed_codes, list):
+ for index, code in packet_driver_codes:
+ if index < len(scrubbed_codes):
+ scrubbed_codes[index] = code
return result
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 3e51e65d9..d98741802 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -316,6 +316,10 @@ class SkyvernContext:
# unbiased secure-vs-legacy comparison. Left None when no genuine assignment was made (no browser
# session, provider unreachable) so a degraded provider never biases the legacy arm.
codeblock_execution_path: str | None = None
+ # The driver's navigation error code for a task whose failure was handled rather than raised,
+ # keyed by task id. Keyed rather than last-one-wins because one browser state serves every block
+ # in a run: a later block that fails without navigating must not inherit an earlier block's code.
+ task_nav_error_codes: dict[str, str] = field(default_factory=dict)
navigation_goal: str | None = None
navigation_payload: dict[str, Any] | list | str | None = None
complete_criterion_is_untrusted: bool = False
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index a47755e3d..f5c2a7e23 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -106,6 +106,7 @@ from skyvern.exceptions import (
UnexpectedTaskStatus,
UnresolvableHost,
WorkflowNotFound,
+ WorkflowRunContextNotInitialized,
get_user_facing_exception_message,
)
from skyvern.forge import app
@@ -310,6 +311,7 @@ from skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnos
from skyvern.webeye.cdp_download_interceptor import normalize_download_filename, settle_browser_downloads_for_context
from skyvern.webeye.navigation import (
default_navigation_settle,
+ driver_nav_error_code,
is_egress_attributable_navigation_failure,
navigate_with_retry,
redact_url_secrets,
@@ -813,6 +815,9 @@ def build_user_defined_error_output(error_code: str, reasoning: str) -> dict[str
"failure_reason": reasoning,
"errors": [error.model_dump(mode="json")],
"failure_category": user_defined_failure_category(error),
+ # Names the code as the author's own, so a reader deciding who owns a failure can tell it
+ # from one a driver reported. Both land in the block's error_codes.
+ "declared_error_code": error_code,
}
@@ -1747,13 +1752,28 @@ class Block(BaseModel, abc.ABC):
workflow_run_id, current_index, include_missing_value_guard=True
)
+ error_codes = self.get_failure_error_codes()
+ # The driver's verdict, carried as a code rather than left only in failure_reason: that
+ # text can be model-authored, so a consumer reading it cannot tell a real browser error
+ # from a sentence describing one.
+ if isinstance(e, FailedToNavigateToUrl) and e.nav_error_code:
+ # Looked up inside the failure handler, so a run torn down while this block awaited
+ # must not raise here and lose the failure being reported. Without the run's secrets
+ # the code cannot be cleared for reporting, so it is left off.
+ try:
+ nav_run_context = self.get_workflow_run_context(workflow_run_id)
+ except WorkflowRunContextNotInitialized:
+ nav_run_context = None
+ if nav_run_context is not None and not is_registered_secret(e.nav_error_code, nav_run_context):
+ error_codes = [*error_codes, e.nav_error_code]
+
return await self.build_block_result(
success=False,
failure_reason=failure_reason,
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
- error_codes=self.get_failure_error_codes() or None,
+ error_codes=error_codes or None,
)
@abc.abstractmethod
@@ -2471,6 +2491,10 @@ class BaseTaskBlock(Block):
status=block_status_mapping[updated_task.status],
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ # A task that terminates right after a failed navigation ends on that failure.
+ error_codes=None
+ if success
+ else _recorded_task_nav_error_codes(updated_task.task_id, workflow_run_context),
)
elif updated_task.status == TaskStatus.canceled:
LOG.info(
@@ -2584,6 +2608,7 @@ class BaseTaskBlock(Block):
status=block_status_mapping[updated_task.status],
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ error_codes=_recorded_task_nav_error_codes(updated_task.task_id, workflow_run_context),
)
await self.record_output_parameter_value(workflow_run_context, workflow_run_id)
@@ -2597,9 +2622,22 @@ class BaseTaskBlock(Block):
),
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ error_codes=(
+ _recorded_task_nav_error_codes(current_running_task.task_id, workflow_run_context)
+ if current_running_task
+ else None
+ ),
)
+def _recorded_task_nav_error_codes(task_id: str, workflow_run_context: WorkflowRunContext) -> list[str] | None:
+ context = skyvern_context.current()
+ code = context.task_nav_error_codes.get(task_id) if context is not None else None
+ if not code or is_registered_secret(code, workflow_run_context):
+ return None
+ return [code]
+
+
class TaskBlock(BaseTaskBlock):
# There is a mypy bug with Literal. Without the type: ignore, mypy will raise an error:
# Parameter 1 of Literal[...] cannot be of type "Any"
@@ -4707,6 +4745,16 @@ def _code_block_safe_print(
print(app.AGENT_FUNCTION.redact_codeblock_parameter_values(rendered.getvalue(), parameters), end="", flush=flush)
+def is_registered_secret(value: str, workflow_run_context: WorkflowRunContext) -> bool:
+ """Whether this exact string is one of the run's registered secret values.
+
+ A driver code is kept through masking, because an ordinary value occurring inside one ("net")
+ would otherwise cut the verdict out of it, and a workflow may legitimately hold a code-shaped
+ literal. A code that *is* a secret is the one case where reporting it would store that secret.
+ """
+ return value in Block._registered_secret_values(workflow_run_context)
+
+
def _redact_codeblock_failure_text(
value: str | None,
parameters: dict[str, Any],
@@ -4724,8 +4772,65 @@ def _redact_codeblock_failure_text(
return redacted
+# Bounded like the runner's own walk rather than recursive: this runs inside failure handling, where
+# a raise would replace the failure being reported.
+_PARAMETER_STRING_WALK_LIMIT = 10_000
+
+
+def parameter_strings(parameters: object) -> set[str] | None:
+ """Every string a parameter carries, keys included, or None when the walk did not finish.
+
+ An unfinished walk cannot answer whether a code is one of those strings, and answering from a
+ partial set would preserve a code that should have been masked.
+ """
+ strings: set[str] = set()
+ stack: list[object] = [parameters]
+ visited = 0
+ while stack:
+ if visited >= _PARAMETER_STRING_WALK_LIMIT:
+ return None
+ node = stack.pop()
+ visited += 1
+ if isinstance(node, str):
+ strings.add(node)
+ elif isinstance(node, dict):
+ stack.extend(node.keys())
+ stack.extend(node.values())
+ elif isinstance(node, (list, tuple, set, frozenset)):
+ stack.extend(node)
+ return strings
+
+
+def _declared_error_code_of(result: BlockResult) -> str | None:
+ """The code this block's author declared, which is theirs to spell and so never preserved."""
+ output = result.output_parameter_value
+ declared = output.get("declared_error_code") if isinstance(output, dict) else None
+ return declared if isinstance(declared, str) and declared else None
+
+
def _redact_codeblock_result(result: BlockResult, parameters: dict[str, Any]) -> BlockResult:
+ # A driver code survives masking whole: a parameter value occurring inside one ("net") would cut
+ # the verdict out of it, and the code carries nothing of its own to mask. A code that *is* a
+ # parameter value is left to the mask, which is the one case where keeping it would disclose.
+ carried_strings = parameter_strings(parameters)
+ declared = _declared_error_code_of(result)
+ preserved = (
+ {}
+ if carried_strings is None
+ else {
+ index: code
+ for index, code in enumerate(result.error_codes or [])
+ if isinstance(code, str)
+ and driver_nav_error_code(code) == code
+ and code != declared
+ and code not in carried_strings
+ }
+ )
redacted_error_codes = app.AGENT_FUNCTION.redact_codeblock_parameter_values(result.error_codes, parameters)
+ if isinstance(redacted_error_codes, list):
+ for index, code in preserved.items():
+ if index < len(redacted_error_codes):
+ redacted_error_codes[index] = code
return replace(
result,
failure_reason=_redact_codeblock_failure_text(result.failure_reason, parameters),
@@ -8423,6 +8528,10 @@ async def wrapper({default_args}):
secure_failure_reason = scrub_failure_reason(runner_reason, fallback=runner_reason) or ""
secure_error_code = scrub_failure_reason(secure_failure.error_code, fallback="")
secure_error_codes = [secure_error_code] if secure_error_code else []
+ if secure_failure.nav_error_code and not is_registered_secret(
+ secure_failure.nav_error_code, workflow_run_context
+ ):
+ secure_error_codes.append(secure_failure.nav_error_code)
failure_output = build_block_failure_output(secure_failure_reason, secure_error_codes)
if secure_failure_page_state:
failure_output["failure_page_state"] = secure_failure_page_state
@@ -8877,6 +8986,14 @@ async def wrapper({default_args}):
),
)
+ # ``e`` is unbound once the except block exits, so the driver's code is captured here
+ # rather than read inside the deferred closure below. It comes from the recorder, never
+ # from ``e``: authored code can rewrite the exception, or raise a fresh one, before it lands.
+ inline_nav_code = recording_page.failure_nav_error_code(e)
+ if inline_nav_code and is_registered_secret(inline_nav_code, workflow_run_context):
+ inline_nav_code = None
+ driver_nav_codes = [inline_nav_code] if inline_nav_code else None
+
async def build_legacy_failure_result() -> BlockResult:
failure_output = None
if inline_failure_page_state:
@@ -8911,6 +9028,10 @@ async def wrapper({default_args}):
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
+ # This block catches its own failures, so the driver's code never reaches the
+ # wrapper that stamps it. A consumer reading only failure_reason cannot tell a
+ # real browser error from a sentence describing one.
+ error_codes=driver_nav_codes,
)
return await self._resolve_failure_with_heal(
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index 4b8332d28..eb5d6e386 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -20,6 +20,7 @@ from skyvern.forge.sdk.workflow.models.credential_release import CredentialRelea
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus, SelectOption
from skyvern.webeye.actions.handler_utils import strategy_aware_input
+from skyvern.webeye.navigation import reported_nav_error_code
from skyvern.webeye.playwright_input import PlaywrightInputDefaults
LOG = structlog.get_logger()
@@ -152,6 +153,13 @@ _HIGH_LEVEL_ACTION_MAP: dict[str, ActionType] = {
}
# High-level methods whose natural-language `prompt` (positional or keyword) is the
# reader-facing description; mirrors code_block_steps._PROMPT_POSITIONAL_METHODS.
+# reload/go_back/go_forward navigate without naming a destination, and their failures carry driver
+# codes just as a goto's do.
+_NAVIGATION_ACTION_TYPES = frozenset(
+ {ActionType.GOTO_URL, ActionType.GO_BACK, ActionType.GO_FORWARD, ActionType.RELOAD_PAGE}
+)
+
+
_PROMPT_METHODS: frozenset[str] = frozenset({"complete", "solve_captcha", "verification_code"})
OnAction = Callable[[Action], Awaitable[None]]
@@ -377,6 +385,12 @@ class _Recorder:
self.last_exception: BaseException | None = None
self.failed_locator: Locator | None = None
self.failed_locator_exception: BaseException | None = None
+ self.failed_nav_error_code: str | None = None
+ self.failed_nav_error_code_exception: BaseException | None = None
+ # One proxy per page of the run, shared by every wrapper: a page reached from a second tab
+ # has to be the same object, or identity comparisons fail and the worker hands out a
+ # second handle for the page it already registered.
+ self.page_proxies: dict[int, tuple[Any, Any]] = {}
self.failure_operation_generation = 0
self._next_action_order = 0
self._on_action = on_action
@@ -440,6 +454,8 @@ class _Recorder:
self.failure_operation_generation += 1
self.failed_locator_exception = None
self.failed_locator = None
+ self.failed_nav_error_code_exception = None
+ self.failed_nav_error_code = None
return self.failure_operation_generation
def _reserve_action_order(self) -> int:
@@ -520,6 +536,11 @@ class _Recorder:
if generation == self.failure_operation_generation:
self.failed_locator_exception = exc
self.failed_locator = failure_locator
+ if action_type in _NAVIGATION_ACTION_TYPES:
+ self.failed_nav_error_code_exception = exc
+ self.failed_nav_error_code = await reported_nav_error_code(
+ exc, _navigation_target_url(action_type, args, kwargs)
+ )
raise
finally:
if pending_handle is not None:
@@ -538,22 +559,38 @@ class _Recorder:
return result
-def _wrap_recording_result(value: Any, recorder: _Recorder, selector: str | None) -> Any:
+def _wrap_recording_result(
+ value: Any, recorder: _Recorder, selector: str | None, owner: RecordingPage | None = None
+) -> Any:
if isinstance(value, list):
- return [_wrap_recording_result(item, recorder, selector) for item in value]
- if type(value).__module__.startswith("playwright.") and type(value).__name__ in _RECORDABLE_HANDLE_TYPE_NAMES:
+ return [_wrap_recording_result(item, recorder, selector, owner) for item in value]
+ if not type(value).__module__.startswith("playwright."):
+ return value
+ type_name = type(value).__name__
+ if type_name in _RECORDABLE_HANDLE_TYPE_NAMES:
return RecordingLocator(value, recorder, selector)
+ # A call can hand back a page or a frame too -- page.frame(name=...), page.opener(), a popup --
+ # and navigating through one of those has to be recorded like any other. ``owner`` is the page
+ # the call was made on, so a frame from a second tab is bound to that tab rather than the first.
+ if owner is not None and type_name == "Frame":
+ return owner._wrap_frame(value)
+ if owner is not None and type_name == "Page":
+ return owner._wrap_page(value)
return value
-def _wrap_call_result(value: Any, recorder: _Recorder, selector: str | None, call_name: str) -> Any:
+def _wrap_call_result(
+ value: Any, recorder: _Recorder, selector: str | None, call_name: str, owner: RecordingPage | None = None
+) -> Any:
if inspect.isawaitable(value):
async def resolve() -> Any:
- return _wrap_recording_result(await recorder.await_pending_aware(value, call_name), recorder, selector)
+ return _wrap_recording_result(
+ await recorder.await_pending_aware(value, call_name), recorder, selector, owner
+ )
return resolve()
- return _wrap_recording_result(value, recorder, selector)
+ return _wrap_recording_result(value, recorder, selector, owner)
class RecordingLocator:
@@ -710,14 +747,94 @@ class RecordingKeyboard:
return recorded
+# Page-level waits that yield another page. ``expect_event`` is included because the canonical
+# popup flow is spelled both ways.
+_PAGE_EVENT_CONTEXT_METHODS = frozenset({"expect_popup", "expect_event"})
+
+
+class _RecordingEventInfo:
+ """Wraps the ``EventInfo`` an ``expect_*`` block yields, so the page it resolves to is recorded.
+
+ Only ``value`` is answered here; everything else is the real object's.
+ """
+
+ def __init__(self, info: Any, wrap: Callable[[Any], Any]) -> None:
+ self.__info = info
+ self.__wrap = wrap
+
+ @property
+ def value(self) -> Any:
+ async def resolve() -> Any:
+ return self.__wrap(await self.__info.value)
+
+ return resolve()
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self.__info, name)
+
+
+class _RecordingExpectContext:
+ """The async context manager ``expect_page()`` returns, yielding a recorded ``EventInfo``."""
+
+ def __init__(self, manager: Any, wrap: Callable[[Any], Any]) -> None:
+ self.__manager = manager
+ self.__wrap = wrap
+
+ async def __aenter__(self) -> Any:
+ return _RecordingEventInfo(await self.__manager.__aenter__(), self.__wrap)
+
+ async def __aexit__(self, *exc_info: Any) -> Any:
+ return await self.__manager.__aexit__(*exc_info)
+
+
class RecordingBrowserContext:
- def __init__(self, context: BrowserContext, recorder: _Recorder) -> None:
+ def __init__(
+ self,
+ context: BrowserContext,
+ recorder: _Recorder,
+ wrap_page: Callable[[Any], Any],
+ intercept_timeout: bool,
+ ) -> None:
self.__context = context
self.__recorder = recorder
+ self.__wrap_page = wrap_page
+ self.__intercept_timeout = intercept_timeout
def __getattr__(self, name: str) -> Any:
attr = getattr(self.__context, name)
- if name != "set_default_timeout" or not callable(attr):
+ # Another tab is still this block's page: navigating through one has to be recorded, or its
+ # failure reports no destination and the driver's code is refused.
+ if name == "pages":
+ return [self.__wrap_page(page) for page in attr]
+ if name == "new_page" and callable(attr):
+
+ async def new_page(*args: Any, **kwargs: Any) -> Any:
+ return self.__wrap_page(await attr(*args, **kwargs))
+
+ return new_page
+ # A popup arrives through an event wait rather than a call that names it, and navigating
+ # through one has to be recorded like any other page.
+ if name in ("expect_page", "expect_event") and callable(attr):
+
+ def expect_page(*args: Any, **kwargs: Any) -> Any:
+ # expect_event also yields downloads, requests and the like, so only a page is
+ # wrapped; expect_page always yields one.
+ wrap = (
+ self.__wrap_page
+ if name == "expect_page"
+ else lambda value: self.__wrap_page(value) if type(value).__name__ == "Page" else value
+ )
+ return _RecordingExpectContext(attr(*args, **kwargs), wrap)
+
+ return expect_page
+ if name == "wait_for_event" and callable(attr):
+
+ async def wait_for_event(*args: Any, **kwargs: Any) -> Any:
+ awaited = await attr(*args, **kwargs)
+ return self.__wrap_page(awaited) if type(awaited).__name__ == "Page" else awaited
+
+ return wait_for_event
+ if name != "set_default_timeout" or not callable(attr) or not self.__intercept_timeout:
return attr
def set_default_timeout(timeout: float) -> None:
@@ -727,12 +844,101 @@ class RecordingBrowserContext:
return set_default_timeout
+class RecordingFrame:
+ """Passes Frame calls through, recording only navigation.
+
+ Inline code can navigate through ``page.main_frame`` or ``page.frames[n]``. Those calls never
+ reach the page proxy, so without this a frame navigation records no destination and its failure
+ carries no driver code.
+ """
+
+ # Brokerable like the raw Frame it replaces: the worker registers a handle for it and the
+ # sandbox receives only the opaque marker (PlaywrightPageOperationBroker).
+ _skyvern_brokerable_handle = True
+
+ def _skyvern_page_operation_argument(self) -> Any:
+ return self.__frame
+
+ def __init__(self, frame: Any, recorder: _Recorder, wrap: Callable[[Any], Any], page: Any) -> None:
+ self.__frame = frame
+ self.__recorder = recorder
+ self.__wrap = wrap
+ self.__page = page
+
+ def __getattr__(self, name: str) -> Any:
+ # Answered before the underlying attribute is read: this is the page the proxy was built
+ # for, not something forwarded, so it must not depend on the raw frame exposing it.
+ if name == "page":
+ return self.__page
+ attr = getattr(self.__frame, name)
+ # A frame reached through another frame navigates the same way, so the wrapping has to
+ # follow the tree rather than stop at the one frame the page handed out.
+ if name == "child_frames":
+ return [self.__wrap(frame) for frame in attr]
+ if name == "parent_frame":
+ return self.__wrap(attr) if attr is not None else None
+ # A frame hands back the page that owns it, and navigating through that page has to be
+ # recorded like any other: returning the raw one reopens the hole this proxy closes.
+ if name != "goto" or not callable(attr):
+ return attr
+
+ async def goto(*args: Any, **kwargs: Any) -> Any:
+ async def call() -> Any:
+ return await attr(*args, **kwargs)
+
+ return await self.__recorder.record(ActionType.GOTO_URL, "frame.goto", None, call, args, kwargs)
+
+ return goto
+
+
+def _navigation_target_url(action_type: ActionType, args: tuple[Any, ...], kwargs: dict[str, Any]) -> str | None:
+ # Only goto names its target. Back, forward and reload move within history the browser already
+ # reached, where a host that never resolved is not the failure being explained.
+ if action_type != ActionType.GOTO_URL:
+ return None
+ return _string_value(kwargs.get("url", _arg(args, 0)))
+
+
class RecordingPage:
"""Proxy that records mapped Playwright calls as Actions.
Recordings are telemetry, not a tamper-proof audit trail.
"""
+ # Brokerable like the raw Page it replaces, for a page handed back by another page of the run.
+ _skyvern_brokerable_handle = True
+
+ @classmethod
+ def _sharing_recorder(cls, page: Any, recorder: _Recorder) -> RecordingPage:
+ """A proxy over another page of the same run, writing into the same recorder."""
+ proxy = cls.__new__(cls)
+ proxy.__page = page
+ proxy.__frame_proxies = {}
+ proxy.__recorder = recorder
+ recorder.page_proxies[id(page)] = (page, proxy)
+ return proxy
+
+ def _wrap_frame(self, frame: Any) -> Any:
+ return self.__recording_frame(frame)
+
+ def _wrap_page(self, page: Any) -> Any:
+ return self.__recording_page(page)
+
+ def __recording_page(self, page: Any) -> Any:
+ if page is self.__page:
+ return self
+ cached = self.__recorder.page_proxies.get(id(page))
+ if cached is None:
+ return RecordingPage._sharing_recorder(page, self.__recorder)
+ return cached[1]
+
+ def __recording_frame(self, frame: Any) -> Any:
+ cached = self.__frame_proxies.get(id(frame))
+ if cached is None:
+ cached = (frame, RecordingFrame(frame, self.__recorder, self.__recording_frame, self))
+ self.__frame_proxies[id(frame)] = cached
+ return cached[1]
+
def __init__(
self,
page: Any,
@@ -743,6 +949,10 @@ class RecordingPage:
playwright_input_defaults: PlaywrightInputDefaults | None = None,
) -> None:
self.__page = page
+ # One proxy per underlying frame, so callers comparing page.main_frame with page.frames[0]
+ # still see the same object. Keyed by identity rather than the frame itself, which is not
+ # required to be hashable; the stored frame keeps that identity from being reused.
+ self.__frame_proxies: dict[int, tuple[Any, Any]] = {}
self.__recorder = _Recorder(
on_action,
credential_release_guard,
@@ -750,6 +960,7 @@ class RecordingPage:
strategy_aware_typing=strategy_aware_typing,
playwright_input_defaults=playwright_input_defaults,
)
+ self.__recorder.page_proxies[id(page)] = (page, self)
@property
def _underlying_page(self) -> Page:
@@ -785,6 +996,15 @@ class RecordingPage:
def failure_locator(self, exception: BaseException) -> Locator | None:
return self.__recorder.failed_locator if self.__recorder.failed_locator_exception is exception else None
+ def failure_nav_error_code(self, exception: BaseException) -> str | None:
+ """The driver code of the navigation that raised ``exception``, or None.
+
+ Bound to the exception rather than to the page so an earlier navigation's code cannot attach
+ to a later failure that never navigated.
+ """
+ recorder = self.__recorder
+ return recorder.failed_nav_error_code if recorder.failed_nav_error_code_exception is exception else None
+
async def _record_solve_captcha(
self,
call: Callable[[], Awaitable[bool]],
@@ -871,7 +1091,26 @@ class RecordingPage:
def __getattr__(self, name: str) -> Any:
attr = getattr(self.__page, name)
if name == "context" and self.__recorder.strategy_aware_typing:
- return RecordingBrowserContext(attr, self.__recorder)
+ return RecordingBrowserContext(attr, self.__recorder, self.__recording_page, True)
+ # The canonical popup flow is `async with page.expect_popup() as info`, whose value is a
+ # page. Left unwrapped, navigating that popup skips the recorder like any other raw page.
+ if name in _PAGE_EVENT_CONTEXT_METHODS and callable(attr):
+
+ def expect_event_context(*args: Any, **kwargs: Any) -> Any:
+ # expect_event also yields downloads, requests and the like, so only a page is
+ # wrapped; expect_popup always yields one.
+ wrap = (
+ self.__recording_page
+ if name == "expect_popup"
+ else lambda value: self.__recording_page(value) if type(value).__name__ == "Page" else value
+ )
+ return _RecordingExpectContext(attr(*args, **kwargs), wrap)
+
+ return expect_event_context
+ if name == "main_frame":
+ return self.__recording_frame(attr)
+ if name == "frames":
+ return [self.__recording_frame(frame) for frame in attr]
if name == "set_default_timeout" and self.__recorder.strategy_aware_typing and callable(attr):
def set_default_timeout(timeout: float) -> None:
@@ -895,7 +1134,7 @@ class RecordingPage:
def forwarded(*args: Any, **kwargs: Any) -> Any:
self.__recorder.begin_failure_operation()
return _wrap_call_result(
- attr(*args, **kwargs), self.__recorder, _factory_selector(name, args), f"page.{name}"
+ attr(*args, **kwargs), self.__recorder, _factory_selector(name, args), f"page.{name}", self
)
return forwarded
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index fc4ba0b2b..bf8cc674b 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -214,7 +214,7 @@ from skyvern.webeye.cdp_download_interceptor import (
settle_browser_downloads_for_context,
)
from skyvern.webeye.main_world_eval import evaluate_in_main_world
-from skyvern.webeye.navigation import revalidate_redirect_chain
+from skyvern.webeye.navigation import reported_nav_error_code, revalidate_redirect_chain
from skyvern.webeye.scraper.scraped_page import (
CleanupElementTreeFunc,
ElementTreeBuilder,
@@ -4516,6 +4516,11 @@ class ScopedXhrDownloadCapture:
self._status_observation_deadline = None
+# Terminate and complete are how a task ends, so a navigation failure before one of them is the
+# failure the task reports rather than something it moved past.
+_TASK_ENDING_ACTION_TYPES = frozenset({ActionType.TERMINATE, ActionType.COMPLETE})
+
+
class ActionHandler:
_handled_action_types: dict[
ActionType,
@@ -4585,6 +4590,11 @@ class ActionHandler:
# browser, chooses the download-capturing path or persists a row.
preflight_action(action, page, site="handle_action")
action.started_at = naive_utc_now()
+ # A later action running means the earlier navigation failure did not end the task, so its
+ # code no longer describes the failure this task will report. Terminate and complete are the
+ # exception: they are how a task ends, so the navigation before them is what it ends on.
+ if action.action_type not in _TASK_ENDING_ACTION_TYPES:
+ _clear_task_nav_error_code(task)
# Hydrated/cached actions can arrive with a prior finished_at; clear it so the
# exceptional-exit fallback below stamps this execution, not the previous one.
action.finished_at = None
@@ -10642,6 +10652,35 @@ async def handle_left_mouse_action(
return [ActionSuccess()]
+async def _record_task_nav_error_code(task: Task, error: BaseException, url: str | None = None) -> None:
+ """Keep the driver's code for a navigation action that failed.
+
+ These actions call the driver directly, so their failure becomes an ``ActionFailure`` and never
+ reaches the typed navigation error. Without this the code is gone by the time anything decides
+ who owned the failure, and an egress fault reads as a defect in the run.
+ """
+ context = skyvern_context.current()
+ if context is None:
+ return
+ # Dropped before the current attempt is read, not only on success: an attempt that reports no
+ # code of its own would otherwise be judged on the one before it.
+ context.task_nav_error_codes.pop(task.task_id, None)
+ code = await reported_nav_error_code(error, url)
+ if code:
+ context.task_nav_error_codes[task.task_id] = code
+
+
+def _clear_task_nav_error_code(task: Task) -> None:
+ """Drop a code kept from an earlier attempt once this task navigates successfully.
+
+ A retry that succeeds leaves the failure behind it, so a later failure of a different kind would
+ otherwise inherit the old code and be reported as a network fault.
+ """
+ context = skyvern_context.current()
+ if context is not None:
+ context.task_nav_error_codes.pop(task.task_id, None)
+
+
@traced(name="skyvern.agent.action.goto_url")
async def handle_goto_url_action(
action: actions.GotoUrlAction,
@@ -10651,8 +10690,13 @@ async def handle_goto_url_action(
step: Step,
) -> list[ActionResult]:
validated_url = await asyncio.to_thread(validate_fetch_url, action.url)
- response = await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
- await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
+ try:
+ response = await page.goto(validated_url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ await revalidate_redirect_chain(response, validate_fetch_url, page.goto)
+ except Exception as navigation_error:
+ await _record_task_nav_error_code(task, navigation_error, url=validated_url)
+ raise
+ _clear_task_nav_error_code(task)
# Navigation invalidates the current scraped page's element ids; stop the batch so the
# next step re-scrapes before any later actions run against the new DOM.
result = ActionSuccess()
@@ -10667,7 +10711,12 @@ async def handle_go_back_action(
task: Task,
step: Step,
) -> list[ActionResult]:
- await page.go_back(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ try:
+ await page.go_back(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ except Exception as navigation_error:
+ await _record_task_nav_error_code(task, navigation_error)
+ raise
+ _clear_task_nav_error_code(task)
return [ActionSuccess()]
@@ -10678,7 +10727,12 @@ async def handle_go_forward_action(
task: Task,
step: Step,
) -> list[ActionResult]:
- await page.go_forward(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ try:
+ await page.go_forward(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ except Exception as navigation_error:
+ await _record_task_nav_error_code(task, navigation_error)
+ raise
+ _clear_task_nav_error_code(task)
return [ActionSuccess()]
@@ -10689,7 +10743,14 @@ async def handle_reload_page_action(
task: Task,
step: Step,
) -> list[ActionResult]:
- await page.reload(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ try:
+ await page.reload(timeout=settings.BROWSER_LOADING_TIMEOUT_MS)
+ except Exception as navigation_error:
+ # Unlike back and forward, whose target is a history entry rather than this URL, a reload
+ # names the page it is on -- so the resolver can be asked about the right host.
+ await _record_task_nav_error_code(task, navigation_error, url=page.url)
+ raise
+ _clear_task_nav_error_code(task)
# Reloading re-renders the DOM and invalidates the scraped page's element ids; stop the
# batch so the next step re-scrapes before any later actions run.
result = ActionSuccess()
@@ -10743,6 +10804,7 @@ async def handle_new_tab_action(
try:
await browser_state.navigate_to_url(page=new_page, url=validated_url)
except Exception as e:
+ await _record_task_nav_error_code(task, e, url=validated_url)
# Don't leave a blank/failed tab as the newest page — the next scrape would fail it.
try:
await new_page.close()
diff --git a/skyvern/webeye/browser_state.py b/skyvern/webeye/browser_state.py
index b8ac6b0e5..d54f1b11a 100644
--- a/skyvern/webeye/browser_state.py
+++ b/skyvern/webeye/browser_state.py
@@ -32,6 +32,9 @@ class BrowserState(Protocol):
# HTTP status of the most recent navigate_to_url (None until one runs, or when it produced no
# response). The Task V3 loop reads it to classify a dead/removed starting URL.
last_navigation_status: int | None
+ # The proxy this browser was actually built with. A consumer reading a flattened failure
+ # sentence cannot tell which hop it went through; this carries that fact from where it is known.
+ built_with_proxy_location: ProxyLocationInput
def add_on_close(self, callback: Callable[[], Awaitable[None]]) -> None: ...
diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.py
index ac00160ca..5562f825d 100644
--- a/skyvern/webeye/navigation.py
+++ b/skyvern/webeye/navigation.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import re
import time
from collections.abc import Awaitable, Callable
from typing import Literal
@@ -15,6 +16,7 @@ from skyvern.constants import (
SKIP_INNER_NAV_RETRY_ERRORS,
)
from skyvern.exceptions import (
+ NO_ADDRESS_RECORD_NAV_ERROR_CODE,
BlockedHost,
BlockedNavigationDestination,
FailedToNavigateToUrl,
@@ -120,6 +122,23 @@ _DEGRADATION_MAP: dict[str, list[str]] = {
}
+# Where the driver writes its code: Playwright leads with it ("Page.goto: net::ERR_X at <url>") and the raw-CDP
+# engine ends with it ("navigation to <url> failed: net::ERR_X"). Anywhere else, such as a URL in the call log or
+# in an interrupted-navigation message, is text a page or an author chose.
+_PLAYWRIGHT_NAV_ERROR_CODE = re.compile(r"(?:[\w.]*: )?(net::ERR_[A-Z0-9_]+)")
+_SKYCDP_NAV_ERROR_CODE = re.compile(r"navigation to .* failed: (net::ERR_[A-Z0-9_]+)", re.DOTALL)
+
+
+def driver_nav_error_code(error_message: str) -> str | None:
+ """The ``net::ERR_*`` code the browser reported, read from the driver's own exception message.
+
+ Callers must pass the message of the exception the driver raised, never a value copied out of a run
+ or block row: those carry model- and page-authored text that can reproduce any code.
+ """
+ match = _PLAYWRIGHT_NAV_ERROR_CODE.match(error_message) or _SKYCDP_NAV_ERROR_CODE.fullmatch(error_message)
+ return match.group(1) if match else None
+
+
def is_skip_inner_retry_error(error_message: str) -> bool:
return any(pattern in error_message for pattern in SKIP_INNER_NAV_RETRY_ERRORS)
@@ -164,6 +183,34 @@ async def _unresolvable_navigation_host(url: str, error_message: str) -> str | N
return host if await asyncio.to_thread(host_has_no_address_record, host) else None
+async def reported_nav_error_code(error: BaseException, url: str | None) -> str | None:
+ """The driver's code for a navigation raised outside ``navigate_with_retry``.
+
+ A raw driver navigation never reaches the resolver corroboration above, so a target with no
+ address record arrives as the run proxy failing to open a tunnel. Corroborating it here answers
+ with the dead-host code, which keeps the target's verdict instead of our egress being blamed for
+ it -- and instead of the verdict being dropped, which would cost the run its terminal stop.
+ """
+ if isinstance(error, FailedToNavigateToUrl):
+ return error.nav_error_code
+ # A user-defined __str__ can raise or return a non-str, and this runs while a failure is being
+ # reported: losing the code is survivable, replacing the failure is not.
+ try:
+ message = str(error)
+ code = driver_nav_error_code(message)
+ except BaseException:
+ return None
+ if code is None or url is None:
+ return code
+ try:
+ dead_host = await _unresolvable_navigation_host(url, message)
+ return NO_ADDRESS_RECORD_NAV_ERROR_CODE if dead_host else code
+ # Exception, not BaseException: a resolver lookup that fails costs the corroboration, but a
+ # cancelled run has to stay cancelled rather than be reported as a navigation verdict.
+ except Exception:
+ return code
+
+
def redact_url_secrets(url: str) -> str:
"""Reduce a URL to scheme and host for display.
@@ -267,9 +314,11 @@ async def navigate_with_retry(
url=display_url,
error=safe_error_str,
)
- raise FailedToNavigateToUrl(url=display_url, error_message=safe_error_str) from (
- None if redacting else error
- )
+ raise FailedToNavigateToUrl(
+ url=display_url,
+ error_message=safe_error_str,
+ nav_error_code=driver_nav_error_code(error_str),
+ ) from (None if redacting else error)
if attempt >= retry_times - 1:
# Terminal navigation failure is re-raised as FailedToNavigateToUrl and surfaced
@@ -282,9 +331,11 @@ async def navigate_with_retry(
error=safe_error_str,
exc_info=not redacting,
)
- raise FailedToNavigateToUrl(url=display_url, error_message=safe_error_str) from (
- None if redacting else error
- )
+ raise FailedToNavigateToUrl(
+ url=display_url,
+ error_message=safe_error_str,
+ nav_error_code=driver_nav_error_code(error_str),
+ ) from (None if redacting else error)
LOG.warning(
"Error while navigating to url, retrying",
diff --git a/skyvern/webeye/real_browser_manager.py b/skyvern/webeye/real_browser_manager.py
index 44ef46dcd..ebb4993ef 100644
--- a/skyvern/webeye/real_browser_manager.py
+++ b/skyvern/webeye/real_browser_manager.py
@@ -738,7 +738,7 @@ class RealBrowserManager(BrowserManager):
exc_info=True,
)
raise
- return RealBrowserState(
+ state = RealBrowserState(
pw=pw,
browser_context=browser_context,
page=None,
@@ -748,6 +748,10 @@ class RealBrowserManager(BrowserManager):
engine_selection=selection,
browser_context_route_policy_url=url,
)
+ # The proxy this context was actually built with. A reader naming the hop that failed
+ # cannot recover it from anywhere else once the context exists.
+ state.built_with_proxy_location = proxy_location
+ return state
# At most two attempts: a fallback-eligible (Rustwright) selection degrades EXACTLY ONCE to its
# classical boot fallback before any usable context; the classical has none, so it then propagates.
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index 1deaf88e4..698cbfd09 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -165,6 +165,9 @@ class RealBrowserState(BrowserState):
# HTTP status of the most recent navigate_to_url (None until one runs, or when it produced no
# response). Read by the Task V3 loop to classify a dead/removed starting URL; v1 ignores it.
self.last_navigation_status: int | None = None
+ # The proxy this browser was actually built with. Downstream layers see only a flattened
+ # sentence, which cannot say which hop it went through.
+ self.built_with_proxy_location: ProxyLocationInput = None
self._ever_connected = browser_context is not None
self._close_requested = False
if browser_context is not None:
@@ -395,6 +398,7 @@ class RealBrowserState(BrowserState):
_reconcile_persistent_init_scripts=reconcile_persistent_init_scripts,
_sessionless_init_script_registrations=tuple(sessionless_init_script_registrations),
)
+ self.built_with_proxy_location = proxy_location
self.browser_context = browser_context
self.browser_context_route_policy_url = effective_route_policy_url
self.browser_artifacts = browser_artifacts
diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.py
index e27c5ee2b..b2364fe6c 100644
--- a/tests/unit/copilot_test_helpers.py
+++ b/tests/unit/copilot_test_helpers.py
@@ -44,6 +44,8 @@ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatReques
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameter
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.schemas.proxy_location import ProxyLocationInput
+from skyvern.schemas.runs import ProxyLocation
from skyvern.schemas.workflows import BlockType
from skyvern.services import workflow_service as workflow_service_module
from skyvern.webeye.actions.action_types import ActionType
@@ -136,6 +138,13 @@ def stub_artifact_app(
return retrieved_ids
+_RUN_SESSION_ID = "pbs_run"
+_CHAT_SESSION_ID = "pbs_chat"
+# The chat session answers with a different proxy than the run session, so a lookup that reads the
+# wrong session shows up as the wrong label instead of passing.
+_CHAT_SESSION_PROXY_LOCATION = ProxyLocation.RESIDENTIAL_ZA
+
+
def _fake_workflow_run(status: str) -> SimpleNamespace:
return SimpleNamespace(
status=WorkflowRunStatus(status),
@@ -255,6 +264,8 @@ async def install_run_blocks_harness(
dispatch_to_worker: bool = False,
terminal_blocks: list[WorkflowRunBlock] | None = None,
recent_actions: list[MagicMock] | None = None,
+ run_proxy_location: ProxyLocationInput = None,
+ run_session_proxy_location: ProxyLocationInput = None,
) -> dict[str, Any]:
"""Stub the collaborators an inline ``_run_blocks_and_collect_debug`` call reaches, with the
polled run parked on ``polled_status`` so the watchdog decides the exit."""
@@ -314,9 +325,17 @@ async def install_run_blocks_harness(
workflow_run_id="wr_paused",
workflow_id="w_source",
sequential_credential_id=None,
+ proxy_location=run_proxy_location,
+ runnable_id=None,
)
monkeypatch.setattr(workflow_service_module, "prepare_workflow", AsyncMock(return_value=workflow_run))
+ async def _get_session(session_id: str, _organization_id: str | None = None) -> SimpleNamespace:
+ proxy_location = run_session_proxy_location if session_id == _RUN_SESSION_ID else _CHAT_SESSION_PROXY_LOCATION
+ return SimpleNamespace(proxy_location=proxy_location, runnable_id=None)
+
+ monkeypatch.setattr(forge_app.PERSISTENT_SESSIONS_MANAGER, "get_session", _get_session)
+
polled_run = _fake_workflow_run(status=polled_status)
async def _read_progress(_ctx: CopilotContext, _run_id: str) -> tuple[Any, Any, Any]:
@@ -329,8 +348,8 @@ async def install_run_blocks_harness(
association = ActiveRunSessionAssociation(
organization_id="org-1",
workflow_permanent_id="wfp-1",
- debug_browser_session_id="pbs_chat",
- run_browser_session_id="pbs_run",
+ debug_browser_session_id=_CHAT_SESSION_ID,
+ run_browser_session_id=_RUN_SESSION_ID,
workflow_run_id="wr_paused",
turn_id="turn-1",
generation="gen-1",
diff --git a/tests/unit/test_code_block_heal_engine_classification.py b/tests/unit/test_code_block_heal_engine_classification.py
index 50b7d05be..8e7aa1bd4 100644
--- a/tests/unit/test_code_block_heal_engine_classification.py
+++ b/tests/unit/test_code_block_heal_engine_classification.py
@@ -54,6 +54,7 @@ def _block() -> CodeBlock:
def _recording_page(recorded_exception: Exception | None) -> MagicMock:
page = MagicMock()
page.last_recorded_exception.return_value = recorded_exception
+ page.failure_nav_error_code.return_value = None
return page
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 5c30722ed..97e86121f 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -32,6 +32,8 @@ from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot import runtime as runtime_module
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.agent import (
+ _FAILURE_FOLLOW_UP,
+ _SKYVERN_EGRESS_FOLLOW_UP,
_build_goal_satisfied_exit_result,
_format_chat_history,
_resolve_wrapped_exception_exit_result,
@@ -107,7 +109,7 @@ from skyvern.forge.sdk.copilot.request_slots import PROMPT_NAME as REQUEST_SLOTS
from skyvern.forge.sdk.copilot.review_gate import workflow_block_fingerprints
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, interim_run_start_outcome
from skyvern.forge.sdk.copilot.runtime_authoring_repair import REPAIR_INSTRUCTION_MAX_CHARS
-from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug
+from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result, _run_blocks_and_collect_debug
from skyvern.forge.sdk.copilot.tools import credentials as credentials_module
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.completion import (
@@ -144,6 +146,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.forge.sdk.services.google_oauth_service import GOOGLE_SHEETS_DATA_SCOPE
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.schemas.proxy_location import ProxyLocation
from skyvern.schemas.workflows import BlockType
from skyvern.services import workflow_service as workflow_service_module
from skyvern.utils.yaml_loader import safe_load_no_dates
@@ -255,6 +258,34 @@ def _challenge_effects_contract() -> DiagnosisRepairContract:
)
+_PROXY_HOP_NAVIGATION_FAILURE = (
+ "Failed to navigate to url https://x.test. Error message: net::ERR_TUNNEL_CONNECTION_FAILED"
+)
+
+
+def _record_failed_navigation_run(
+ ctx: CopilotContext, failure_reason: str, driver_codes: list[str] | None = None
+) -> None:
+ """``driver_codes`` is what the browser reported; the sentence alone attributes nothing."""
+ ctx.test_after_update_done = True
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "open_page",
+ "status": "failed",
+ "failure_reason": failure_reason,
+ "error_codes": driver_codes or [],
+ }
+ ]
+ },
+ },
+ )
+
+
def _challenge_failure_ctx() -> CopilotContext:
return _ctx(
last_workflow=object(),
@@ -458,6 +489,32 @@ class TestFailedTestResponseNormalization:
assert "tested it" not in rewritten
assert "test failed" not in rewritten
+ def test_a_proxy_hop_failure_keeps_its_label_when_the_page_also_detected_a_challenge(self) -> None:
+ # The challenge path returns before the follow-up, so the label has to be on the
+ # recorded-run sentence itself or a walled page silently hides who owned the failure.
+ ctx = _challenge_failure_ctx()
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ _record_failed_navigation_run(ctx, _PROXY_HOP_NAVIGATION_FAILURE, ["net::ERR_TUNNEL_CONNECTION_FAILED"])
+ ctx.latest_diagnosis_repair_contract = _challenge_effects_contract()
+ ctx.last_failure_category_top = "ANTI_BOT_DETECTION"
+ model_reply = "The proxy hop died before the page loaded. I can retry from another location."
+
+ rewritten = _rewrite_failed_test_response(model_reply, ctx)
+
+ assert "Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES)" in rewritten
+ assert model_reply in rewritten
+
+ def test_prose_quoting_a_proxy_code_never_blames_our_own_egress(self) -> None:
+ ctx = _challenge_failure_ctx()
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ _record_failed_navigation_run(ctx, "The page said net::ERR_TUNNEL_CONNECTION_FAILED, so I stopped.")
+ ctx.latest_diagnosis_repair_contract = _challenge_effects_contract()
+ ctx.last_failure_category_top = "ANTI_BOT_DETECTION"
+
+ rewritten = _rewrite_failed_test_response("I could not continue.", ctx)
+
+ assert "Skyvern proxy hop failed" not in rewritten
+
def test_without_challenge_effects_the_base_follow_up_template_is_unchanged(self) -> None:
no_contract_ctx = _challenge_failure_ctx()
empty_recourse_ctx = _challenge_failure_ctx()
@@ -465,7 +522,7 @@ class TestFailedTestResponseNormalization:
expected = (
"I created a draft workflow with 2 blocks and tested it, but the test failed. "
- "Failure: Verify you are human. Want me to retry with a different proxy location?"
+ "Failure: Verify you are human. Want me to retry?"
" Keep the draft to iterate on, or discard."
)
assert _rewrite_failed_test_response("The site blocked me.", no_contract_ctx) == expected
@@ -489,9 +546,30 @@ class TestFailedTestResponseNormalization:
assert "test failed" in rewritten.lower()
assert "Call log:" not in rewritten
- def test_failed_run_does_not_clear_last_workflow_state(self) -> None:
- from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result
+ @pytest.mark.parametrize("failure_category", ["NAVIGATION_FAILURE", "PAGE_LOAD_TIMEOUT"])
+ def test_proxy_transport_failure_reply_does_not_blame_the_url(self, failure_category: str) -> None:
+ ctx = _ctx(
+ last_update_block_count=1,
+ last_test_ok=False,
+ effective_workflow_proxy_location=ProxyLocation.RESIDENTIAL_ES,
+ )
+ _record_failed_navigation_run(
+ ctx,
+ "Failed to execute code block. Reason: Error: Page.goto: "
+ "net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/catalogue",
+ ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ )
+ ctx.last_failure_category_top = failure_category
+ rewritten = _rewrite_failed_test_response("The test failed.", ctx)
+
+ assert "confirm the URL" not in rewritten
+ assert "Can you confirm the URL is correct?" not in rewritten
+ assert "Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES)" in rewritten
+ assert _SKYVERN_EGRESS_FOLLOW_UP.strip() in rewritten
+ assert _FAILURE_FOLLOW_UP["PROXY_ERROR"].strip() not in rewritten
+
+ def test_failed_run_does_not_clear_last_workflow_state(self) -> None:
sentinel_workflow = object()
ctx = MagicMock()
ctx.last_workflow = sentinel_workflow
@@ -518,8 +596,6 @@ class TestFailedTestResponseNormalization:
assert ctx.last_test_failure_reason == "net::ERR_NAME_NOT_RESOLVED"
def test_current_state_block_run_records_partial_verification_evidence(self) -> None:
- from skyvern.forge.sdk.copilot.tools import _record_run_blocks_result
-
ctx = _ctx(
last_workflow_yaml="""
workflow_definition:
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index f78890d41..4c9b8c26f 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -1274,7 +1274,14 @@ def test_runtime_authoring_repair_context_ignores_policy_verdict_but_respects_st
"data": {
"workflow_run_id": "wr_stop",
"overall_status": "failed",
- "blocks": [{"label": "open", "status": "failed", "failure_reason": "net::ERR_NAME_NOT_RESOLVED"}],
+ "blocks": [
+ {
+ "label": "open",
+ "status": "failed",
+ "failure_reason": "net::ERR_NAME_NOT_RESOLVED",
+ "error_codes": ["net::ERR_NAME_NOT_RESOLVED"],
+ }
+ ],
},
},
)
@@ -2301,7 +2308,14 @@ def test_stop_and_no_change_decisions_preserve_current_behavior_shadow_only() ->
"ok": False,
"data": {
"overall_status": "failed",
- "blocks": [{"label": "open", "status": "failed", "failure_reason": "net::ERR_NAME_NOT_RESOLVED"}],
+ "blocks": [
+ {
+ "label": "open",
+ "status": "failed",
+ "failure_reason": "net::ERR_NAME_NOT_RESOLVED",
+ "error_codes": ["net::ERR_NAME_NOT_RESOLVED"],
+ }
+ ],
},
},
ctx=stop_ctx,
diff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.py
index aeaa4f6ed..9b4d7b3c6 100644
--- a/tests/unit/test_copilot_discovery.py
+++ b/tests/unit/test_copilot_discovery.py
@@ -32,6 +32,7 @@ from skyvern.forge.sdk.copilot.tools import (
_rank_discovery_entrypoint_candidates,
_resolve_discovery_entry_url,
)
+from skyvern.forge.sdk.copilot.tools import _shared as shared_module
from skyvern.forge.sdk.copilot.tools.discovery import (
_credential_entry_url,
_discovery_build_result,
@@ -40,6 +41,7 @@ from skyvern.forge.sdk.copilot.tools.discovery import (
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatSender
+from skyvern.schemas.runs import ProxyLocation
_VALID_PNG_B64 = (
"iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAIAAAACUFjqAAAAE0lEQVR4nGP8z4APMOGVZRip0gBBLAETee26JgAAAABJRU5ErkJggg=="
@@ -60,6 +62,9 @@ class _Ctx:
self.workflow_verification_evidence = WorkflowVerificationEvidence()
self.browser_session_id = None
self.last_run_blocks_browser_session_id = None
+ self.organization_id = "o_test"
+ self.effective_workflow_proxy_location = None
+ self.last_workflow = None
self.request_policy = None
self.org_credentials_for_turn = None
self.supports_vision = True
@@ -332,6 +337,32 @@ class _CurrentPageServer:
raise AssertionError(f"unexpected tool: {tool_name}")
+class _ProxyRejectedNavigationServer:
+ """A dead proxy hop: skyvern_navigate fails, and the capture that follows reads Chrome's own
+ error page rather than the target."""
+
+ def __init__(self, navigation_error: str, driver_code: str | None = None) -> None:
+ self.calls: list[str] = []
+ self.navigation_error = navigation_error
+ self.driver_code = driver_code
+
+ async def call_internal_tool(self, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
+ self.calls.append(tool_name)
+ if tool_name == "skyvern_navigate":
+ # The shape mcp_to_copilot produces: the driver's code survives the flattening as a
+ # value beside the sentence, which is the only thing attribution reads.
+ failure: dict[str, Any] = {"ok": False, "error": self.navigation_error}
+ if self.driver_code:
+ failure["nav_error_code"] = self.driver_code
+ return failure
+ if tool_name == "skyvern_evaluate":
+ assert arguments["expression"] == COMPOSITION_STRUCTURED_EVIDENCE_EXPRESSION
+ return {"ok": True, "data": {"result": _structured_search_page()}}
+ if tool_name == "skyvern_get_html":
+ return {"ok": True, "data": {"html": "<html><body></body></html>"}}
+ raise AssertionError(f"unexpected tool: {tool_name}")
+
+
class _GenericBarrierServer:
def __init__(self) -> None:
self.calls: list[str] = []
@@ -1180,3 +1211,49 @@ class TestCredentialEntryUrl:
def test_credentials_without_a_login_page_resolve_nothing(self) -> None:
assert _credential_entry_url(self._ctx(None), "example") is None
+
+
+_TUNNEL_NAVIGATION_ERROR = (
+ "Failed to navigate to url https://www.example.com/search. Error message: net::ERR_TUNNEL_CONNECTION_FAILED"
+)
+_DNS_NAVIGATION_ERROR = (
+ "Failed to navigate to url https://www.example.invalid/. Error message: net::ERR_NAME_NOT_RESOLVED"
+)
+
+
+def _proxy_scout_ctx(monkeypatch: pytest.MonkeyPatch, navigation_error: str, driver_code: str | None) -> _Ctx:
+ """``navigation_error`` is the sentence the tool returned; ``driver_code`` is what the browser
+ reported for that call. Only the second one decides who owns the failure."""
+ ctx = _Ctx(_ProxyRejectedNavigationServer(navigation_error, driver_code))
+ ctx.browser_session_id = "pbs_scout"
+ browser_state = SimpleNamespace(built_with_proxy_location=ProxyLocation.RESIDENTIAL_ES)
+ monkeypatch.setattr(shared_module, "resolve_browser_state_for_context", AsyncMock(return_value=browser_state))
+ return ctx
+
+
+async def test_proxy_rejected_inspection_names_the_proxy_hop_in_the_packet(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _proxy_scout_ctx(monkeypatch, _TUNNEL_NAVIGATION_ERROR, "net::ERR_TUNNEL_CONNECTION_FAILED")
+
+ result = await _inspect_page_for_composition_impl(ctx, "https://www.example.com/search")
+
+ warnings = result["data"]["inspection_warnings"]
+ assert any(
+ "Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES)" in warning
+ and "net::ERR_TUNNEL_CONNECTION_FAILED" in warning
+ for warning in warnings
+ )
+
+
+async def test_target_owned_navigation_failure_leaves_the_packet_unattributed(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _proxy_scout_ctx(monkeypatch, _DNS_NAVIGATION_ERROR, "net::ERR_NAME_NOT_RESOLVED")
+
+ result = await _inspect_page_for_composition_impl(ctx, "https://www.example.invalid/")
+
+ warnings = result["data"]["inspection_warnings"]
+ assert not any("Skyvern proxy hop failed" in warning for warning in warnings)
diff --git a/tests/unit/test_copilot_failure_publication.py b/tests/unit/test_copilot_failure_publication.py
index 465c9ade7..abc22548b 100644
--- a/tests/unit/test_copilot_failure_publication.py
+++ b/tests/unit/test_copilot_failure_publication.py
@@ -400,7 +400,9 @@ async def test_cancel_capture_joins_owned_task_before_preserving_caller_cancella
async def test_successful_self_heal_never_starts_failure_capture(monkeypatch: pytest.MonkeyPatch) -> None:
block = _block()
context = _context()
- recorder = SimpleNamespace(recording_page=SimpleNamespace(), finalize=AsyncMock())
+ recorder = SimpleNamespace(
+ recording_page=SimpleNamespace(failure_nav_error_code=lambda _exception: None), finalize=AsyncMock()
+ )
healed = BlockResult(
success=True,
output_parameter=block.output_parameter,
@@ -459,7 +461,9 @@ async def test_outer_deadline_during_staging_still_publishes_the_healable_failur
still reach the caller."""
block = _block()
context = _context()
- recorder = SimpleNamespace(recording_page=SimpleNamespace(), finalize=AsyncMock())
+ recorder = SimpleNamespace(
+ recording_page=SimpleNamespace(failure_nav_error_code=lambda _exception: None), finalize=AsyncMock()
+ )
staging_entered = asyncio.Event()
published: list[str] = []
screenshot_attempts = 0
@@ -536,7 +540,9 @@ async def test_healable_failure_is_not_held_behind_a_stalled_frame(
heal proceeds without a frame."""
block = _block()
context = _context()
- recorder = SimpleNamespace(recording_page=SimpleNamespace(), finalize=AsyncMock())
+ recorder = SimpleNamespace(
+ recording_page=SimpleNamespace(failure_nav_error_code=lambda _exception: None), finalize=AsyncMock()
+ )
heal_reached = asyncio.Event()
async def stalled_screenshot(**_: object) -> bytes:
@@ -590,7 +596,9 @@ async def test_healable_failure_is_not_held_behind_a_stalled_frame(
async def test_failed_self_heal_is_not_persisted_twice_before_capture(monkeypatch: pytest.MonkeyPatch) -> None:
block = _block()
context = _context()
- recorder = SimpleNamespace(recording_page=SimpleNamespace(), finalize=AsyncMock())
+ recorder = SimpleNamespace(
+ recording_page=SimpleNamespace(failure_nav_error_code=lambda _exception: None), finalize=AsyncMock()
+ )
failed = BlockResult(
success=False,
failure_reason="specific healed-attempt failure",
diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.py
index d02b25d57..1853c8e9c 100644
--- a/tests/unit/test_copilot_mcp_adapter.py
+++ b/tests/unit/test_copilot_mcp_adapter.py
@@ -42,6 +42,7 @@ from skyvern.forge.sdk.copilot.runtime import (
)
from skyvern.forge.sdk.copilot.secret_scrub import (
clear_session_scrub_values,
+ register_secret_scrub_value,
)
from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS
from skyvern.forge.sdk.copilot.tools.mcp_hooks import _build_skyvern_mcp_overlays, get_skyvern_mcp_alias_map
@@ -114,6 +115,109 @@ def test_scrub_tool_result_redacts_encoded_matching_origin_values(monkeypatch: p
assert seen_parameters == [{"magic_link": secret}]
+def test_a_driver_navigation_code_survives_a_scrubbed_value_that_spells_part_of_it() -> None:
+ """Workflow parameter values are registered for scrubbing with no minimum length, so "net" is enough
+ to corrupt the token before it is lifted, and a proxy outage then reads as a target failure."""
+ ctx = make_copilot_ctx()
+ register_secret_scrub_value(ctx, "net")
+ raw = {
+ "ok": False,
+ "error": {
+ "code": "ACTION_FAILED",
+ "message": "Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/",
+ "hint": "",
+ "details": {"nav_error_code": "net::ERR_TUNNEL_CONNECTION_FAILED"},
+ },
+ }
+
+ flattened = mcp_to_copilot(mcp_adapter.scrub_model_facing_tool_result(ctx, raw, tool_name="skyvern_navigate"))
+
+ assert flattened["nav_error_code"] == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ assert "net::" not in flattened["error"]
+ # The flattened shape is scrubbed again on its way to the model.
+ rescrubbed = mcp_adapter.scrub_model_facing_tool_result(ctx, flattened, tool_name="skyvern_navigate")
+ assert rescrubbed["nav_error_code"] == flattened["nav_error_code"]
+
+ # A scrub that fails closed stays empty: a code written into it would turn a failed call into a success.
+ register_secret_scrub_value(ctx, "target")
+ fail_closed = mcp_adapter.scrub_model_facing_tool_result(
+ ctx, {**flattened, "target": {"page": 0}}, tool_name="skyvern_navigate"
+ )
+ assert fail_closed == {}
+
+
+ ("code", "registered", "tool_name", "survives"),
+ [
+ # Every code the driver writes reaches the model intact, not only the ones ownership reads.
+ pytest.param("net::ERR_CONNECTION_REFUSED", "net", "skyvern_navigate", True, id="a_code_holding_a_value"),
+ pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", "net", "skyvern_navigate", True, id="a_proxy_code"),
+ # Only the navigation tool reports a code. Another tool echoing an argument into the field
+ # would otherwise have the whole token written back over the scrub.
+ pytest.param("net::ERR_HUNTER2", "HUNTER2", "skyvern_evaluate", False, id="another_tool_echoed_a_secret"),
+ pytest.param(
+ "net::ERR_CERT_HUNTER2", "net::ERR_CERT_HUNTER2", "skyvern_navigate", False, id="the_code_is_the_secret"
+ ),
+ pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", "net", None, False, id="a_result_with_no_provenance"),
+ ],
+)
+def test_the_model_facing_scrub_keeps_driver_codes_only_where_the_driver_reports_them(
+ code: str, registered: str, tool_name: str | None, survives: bool
+) -> None:
+ ctx = make_copilot_ctx()
+ register_secret_scrub_value(ctx, registered)
+
+ scrubbed = mcp_adapter.scrub_model_facing_tool_result(
+ ctx, {"ok": False, "nav_error_code": code}, tool_name=tool_name
+ )
+
+ assert (scrubbed.get("nav_error_code") == code) is survives
+ assert (registered in str(scrubbed)) is (survives and registered in code)
+
+
+ ("parameter_value", "survives"),
+ [
+ # The run's redaction parameters are a second vocabulary the scrub applies. A parameter that
+ # IS a code would be redacted by that pass and written back whole by the restore.
+ pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", False, id="a_parameter_that_is_the_code"),
+ # An ordinary parameter occurring inside a code must still not cost the model the code.
+ pytest.param("net", True, id="a_parameter_inside_the_code"),
+ ],
+)
+def test_the_model_facing_scrub_reads_the_run_parameters_before_restoring_a_code(
+ monkeypatch: pytest.MonkeyPatch, parameter_value: str, survives: bool
+) -> None:
+ """A redaction parameter never registered with the exact-value scrubber is still redacted, so the
+ restore has to consult it too or it hands back what the parameter pass was hiding."""
+
+ def redact(value: object, parameters: dict[str, object]) -> object:
+ secret = str(next(iter(parameters.values())))
+
+ def walk(node: object) -> object:
+ if isinstance(node, str):
+ return node.replace(secret, "[redacted]")
+ if isinstance(node, dict):
+ return {key: walk(item) for key, item in node.items()}
+ if isinstance(node, list):
+ return [walk(item) for item in node]
+ return node
+
+ return walk(value)
+
+ monkeypatch.setattr(mcp_adapter.app.AGENT_FUNCTION, "redact_codeblock_parameter_values", redact)
+ code = "net::ERR_TUNNEL_CONNECTION_FAILED"
+ ctx = make_copilot_ctx()
+ ctx.codeblock_redaction_parameters = {"site": parameter_value}
+
+ scrubbed = mcp_adapter.scrub_model_facing_tool_result(
+ ctx, {"ok": False, "nav_error_code": code}, tool_name="skyvern_navigate"
+ )
+
+ assert (scrubbed.get("nav_error_code") == code) is survives
+ assert (parameter_value in str(scrubbed)) is survives
+
+
class TestRequestedOutputPathChoices:
def test_the_turn_s_requested_paths_become_the_choices(self) -> None:
# Live shape (SKY-13226): a free-form path let the model name its own purpose, so the read
diff --git a/tests/unit/test_copilot_non_retriable_nav.py b/tests/unit/test_copilot_non_retriable_nav.py
index deb4490f0..d45420684 100644
--- a/tests/unit/test_copilot_non_retriable_nav.py
+++ b/tests/unit/test_copilot_non_retriable_nav.py
@@ -1,32 +1,77 @@
"""Tests for non-retriable navigation error handling in the copilot layer.
-Covers SKY-9136: when the browser layer raises ``FailedToNavigateToUrl`` with
-a DNS / cert / SSL / invalid-URL pattern (``SKIP_INNER_NAV_RETRY_ERRORS``),
-the copilot must surface the real error instead of "Unknown error", must not
-keep retrying, and must fail deterministically even if the model tries to
-narrate a completion.
+A failure blaming the target (DNS / cert / SSL / invalid URL) must surface the real error
+instead of "Unknown error", must not keep retrying, and must fail deterministically even if
+the model tries to narrate a completion. A failure inside Skyvern's own proxy hop must not.
"""
from __future__ import annotations
+from datetime import UTC, datetime
from types import SimpleNamespace
+from unittest import mock
+from unittest.mock import AsyncMock
import pytest
+import skyvern.forge.sdk.workflow.models.block as block_module
from skyvern.config import settings
+from skyvern.constants import SKIP_INNER_NAV_RETRY_ERRORS
+from skyvern.exceptions import (
+ NO_ADDRESS_RECORD_NAV_ERROR_CODE,
+ FailedToNavigateToUrl,
+ WorkflowRunContextNotInitialized,
+)
from skyvern.forge.sdk.copilot import agent as agent_module
from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext
+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
+ DiagnosisFailureType,
+ RepairNextAction,
+ _next_action,
+ author_time_levers,
+)
from skyvern.forge.sdk.copilot.enforcement import (
CopilotNonRetriableNavError,
_extract_url_from_nav_error,
_maybe_raise_non_retriable_nav,
+ proxy_hop_failure_reason,
)
+from skyvern.forge.sdk.copilot.nav_attribution import (
+ PROXY_TRANSPORT_NAV_ERROR_CODES,
+ TERMINAL_NAV_ERROR_CODES,
+ block_nav_error_codes,
+ 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.runtime import mcp_to_copilot
+from skyvern.forge.sdk.copilot.runtime_authoring_repair import _error_text_requires_stop
+from skyvern.forge.sdk.copilot.secret_scrub import register_secret_scrub_value
from skyvern.forge.sdk.copilot.tools import (
_detect_non_retriable_nav_error,
_record_run_blocks_result,
_record_workflow_update_result,
)
+from skyvern.forge.sdk.copilot.tools import _shared as shared_module
+from skyvern.forge.sdk.copilot.tools import mcp_hooks as mcp_hooks_module
+from skyvern.forge.sdk.copilot.tools._shared import _discovery_navigate
+from skyvern.forge.sdk.copilot.tools.mcp_hooks import _navigate_post_hook
+from skyvern.forge.sdk.copilot.tools.run_execution import (
+ _commit_run_blocks_record,
+ _run_blocks_and_collect_debug,
+ finalize_build_test_result,
+)
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
+from skyvern.forge.sdk.schemas.tasks import TaskStatus
+from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
+from skyvern.schemas.proxy_location import GeoTarget, ProxyLocationInput
from skyvern.schemas.runs import ProxyLocation
+from skyvern.schemas.workflows import BlockType
+from 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.force_stub_app import admit_block_dispatch
+from tests.unit.test_missing_starter_url import _mock_block_execute_deps, _output_parameter
_DNS_FAILURE_REASON = (
"Failed to navigate to url https://www.example.invalid/path. Error message: net::ERR_NAME_NOT_RESOLVED"
@@ -49,12 +94,108 @@ _CERT_FAILURE_WITH_PROXY_TOKEN_IN_URL = (
"Failed to navigate to url https://example.test/net::ERR_SOCKS_CONNECTION_FAILED. "
"Error message: net::ERR_CERT_DATE_INVALID"
)
+# The task-level failure_reason skyvern/forge/agent.py builds from FailedToNavigateToUrl. Its
+# separator differs from the exception's own, and it is the reason a TaskBlock reports.
+_TASK_FAILURE_REASON_TUNNEL = (
+ "Failed to navigate to URL. URL:https://proxy.example, Error:net::ERR_TUNNEL_CONNECTION_FAILED"
+)
+_TASK_FAILURE_REASON_DNS = (
+ "Failed to navigate to URL. URL:https://www.example.invalid, Error:net::ERR_NAME_NOT_RESOLVED"
+)
+# A wrapped navigation failure quotes an inner one; the code the outer producer reports is the one it
+# ends on, and a proxy code planted in the quoted URL is not the machine's verdict.
+_WRAPPED_FAILURE_QUOTING_A_PROXY_CODE_EARLIER = (
+ "Failed to navigate to url https://a.test. Error message: "
+ "Failed to navigate to url https://b.test/net::ERR_TUNNEL_CONNECTION_FAILED. "
+ "Error message: net::ERR_ABORTED"
+)
+
+_DRIVER_CODE_BY_REASON = {
+ _TUNNEL_FAILURE_REASON: "net::ERR_TUNNEL_CONNECTION_FAILED",
+ _SOCKS_FAILURE_REASON: "net::ERR_SOCKS_CONNECTION_FAILED",
+ _SOCKS_HOST_UNREACHABLE_REASON: "net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE",
+ _DNS_FAILURE_REASON: "net::ERR_NAME_NOT_RESOLVED",
+ _CERT_FAILURE_REASON: "net::ERR_CERT_DATE_INVALID",
+ # The planted token is in the requested URL; the driver's verdict is the code it ended on.
+ _DNS_FAILURE_WITH_PROXY_TOKEN_IN_URL: "net::ERR_NAME_NOT_RESOLVED",
+ _CERT_FAILURE_WITH_PROXY_TOKEN_IN_URL: "net::ERR_CERT_DATE_INVALID",
+ _TASK_FAILURE_REASON_TUNNEL: "net::ERR_TUNNEL_CONNECTION_FAILED",
+ _TASK_FAILURE_REASON_DNS: "net::ERR_NAME_NOT_RESOLVED",
+}
+
+
+_TARGET_CODE_PLANTED_IN_THE_URL = (
+ "Failed to navigate to url https://example.test/net::ERR_NAME_NOT_RESOLVED. "
+ "Error message: net::ERR_TUNNEL_CONNECTION_FAILED"
+)
+
+
+def _proxy_hop_label(proxy_location: ProxyLocation | str | None) -> str:
+ if not proxy_location:
+ return "Skyvern proxy hop failed: "
+ name = proxy_location.value if isinstance(proxy_location, ProxyLocation) else proxy_location
+ return f"Skyvern proxy hop failed (proxy_location={name}): "
+
+
+_SHARED_FAILURE_REASON = "The step did not complete."
+
+
+def _driver_codes_for(reason: str) -> list[str]:
+ """The code the driver would have reported for a fixture reason, and nothing for the rest."""
+ code = _DRIVER_CODE_BY_REASON.get(reason)
+ return [code] if code else []
+
+
_GENERIC_FAILURE_REASON = "Timeout waiting for element #submit"
+# A page can put this text in front of the model, and the model's finish text becomes the run's
+# failure_reason, so prose quoting the code must never mint blame on our own egress.
+_MODEL_PROSE_QUOTING_A_PROXY_CODE = (
+ "The page reported net::ERR_TUNNEL_CONNECTION_FAILED, so I stopped before filling the form."
+)
+# Every separator a producer uses is ordinary punctuation a page or a model also writes, so prose
+# carrying one must not mint the attribution at any site that reads the reason.
+_PROSE_QUOTING_A_TASK_SEPARATOR = "The site said: Connection error, Error: net::ERR_TUNNEL_CONNECTION_FAILED"
+_PROSE_QUOTING_A_GOTO_SEPARATOR = (
+ 'I stopped because the page rendered the text "Page.goto: net::ERR_SOCKS_CONNECTION_FAILED"'
+)
+_PROSE_QUOTING_A_NAV_SEPARATOR = "Terminated: the banner read. Error message: net::ERR_TUNNEL_CONNECTION_FAILED"
+# A task's failure_reason can be model-authored prose verbatim (skyvern/forge/agent.py assigns
+# persisted_action.reasoning to it), so a bare code carries no provenance: a page that renders one
+# must not be able to blame Skyvern's egress and suppress the authoring repair the block deserves.
+_BARE_PROXY_CODE_WITHOUT_A_PRODUCER = "net::ERR_TUNNEL_CONNECTION_FAILED"
+_PROSE_QUOTING_THE_ATTRIBUTION_PREFIX = (
+ "Skyvern proxy hop failed (proxy_location=US): the page said net::ERR_TUNNEL_CONNECTION_FAILED"
+)
+# The reply site reads a reason the run seam already attributed, so the prefix is a producer wrapper.
+_ALREADY_ATTRIBUTED_TUNNEL_FAILURE = f"Skyvern proxy hop failed (proxy_location=US): {_TUNNEL_FAILURE_REASON}"
+
+# The proxy code leads and the target-owned code trails past both display clamps (240 in the chat
+# reply, 160 in the run observation), so a predicate reading clamped text would mislabel this.
+_MIXED_CODE_TARGET_CODE_PAST_THE_CLAMPS = (
+ "Failed to navigate to url https://proxy.example. Error message: net::ERR_TUNNEL_CONNECTION_FAILED "
+ + "retrying the connect hop " * 12
+ + "net::ERR_CERT_DATE_INVALID"
+)
-_PROXY_FAILURE_REPLY = (
- "The site could not be reached through Skyvern's browser network. Error: {reason}. "
- "Please try again later, or contact Skyvern Support if the problem continues."
+# A long path pushes the proxy code past the clamp while the origin rewrite pulls it back inside, so
+# a predicate reading clamped text would drop a label the displayed sentence still has room for.
+_PROXY_CODE_PAST_THE_CLAMP = (
+ "Failed to navigate to url "
+ "https://shop.example/catalog/category/outdoor/tents/four-season/filters?sort=price&page=12&session=abcdef. "
+ "Error message: net::ERR_TUNNEL_CONNECTION_FAILED"
)
+
+_PROXY_RUN_WORKFLOW_YAML = """
+title: proxy run example
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: navigation
+ label: open_page
+ url: https://proxy.example
+ navigation_goal: open the page
+"""
+
_NON_PROXY_FAILURE_REPLY = "The target URL could not be reached. Error: {reason}. Please verify the URL and try again."
# A host with no address record still carries the proxy's error code, because a proxied browser
# delegates resolution to the proxy. UnresolvableNavigationHost prefixes the real cause.
@@ -79,7 +220,9 @@ def _fresh_context() -> CopilotContext:
)
-def _record_and_render_terminal_reply(reason: str, *, block_type: str) -> tuple[CopilotContext, AgentResult]:
+def _record_and_render_terminal_reply(
+ reason: str, *, block_type: str, codes: list[str] | None = None
+) -> tuple[CopilotContext, AgentResult]:
ctx = _fresh_context()
ctx.test_after_update_done = True
_record_run_blocks_result(
@@ -93,6 +236,7 @@ def _record_and_render_terminal_reply(reason: str, *, block_type: str) -> tuple[
"block_type": block_type,
"status": "failed",
"failure_reason": reason,
+ "error_codes": _driver_codes_for(reason) if codes is None else codes,
}
]
},
@@ -109,37 +253,71 @@ def _record_and_render_terminal_reply(reason: str, *, block_type: str) -> tuple[
# ---------------------------------------------------------------------------
+# Each arm declares the code its driver reported. Deriving it from the reason text here would
+# reproduce the step this module exists to remove, and the test would pass either way.
+_TARGET_OWNED_ARMS = [
+ pytest.param(_DNS_FAILURE_REASON, "net::ERR_NAME_NOT_RESOLVED", id="dns_standard_format"),
+ pytest.param(
+ "Failed to navigate to url not-a-url. Error message: net::ERR_INVALID_URL",
+ "net::ERR_INVALID_URL",
+ id="invalid_url_standard_format",
+ ),
+ pytest.param(
+ "net::ERR_NAME_RESOLUTION_FAILED happened mid-flight",
+ "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",
+ "net::ERR_CERT_DATE_INVALID",
+ id="proxy_code_alongside_cert",
+ ),
+]
+
+
[email protected](("reason", "code"), _TARGET_OWNED_ARMS)
+def test_detect_matches_error_in_block_failure_reason(reason: str, code: str) -> None:
+ result = {"ok": False, "data": {"blocks": [{"failure_reason": reason, "error_codes": [code]}]}}
+ assert _detect_non_retriable_nav_error(result) == reason
+
+
[email protected](("reason", "code"), _TARGET_OWNED_ARMS)
+def test_a_failure_sentence_alone_cannot_mint_a_terminal_stop(reason: str, code: str) -> None:
+ """The same sentences, with no code from the driver behind them.
+
+ A terminal stop discards the user's staged workflow and tells them to check a URL, so a page or
+ a model that reproduces this wording must not be able to trigger one.
+ """
+ del code
+ result = {"ok": False, "data": {"blocks": [{"failure_reason": reason}]}}
+ assert _detect_non_retriable_nav_error(result) is None
+
+
+def test_detect_matches_cert_error_in_run_level_failure_reason() -> None:
+ result = {
+ "ok": False,
+ "data": {
+ "failure_reason": _CERT_FAILURE_REASON,
+ "error_codes": ["net::ERR_CERT_DATE_INVALID"],
+ "blocks": [],
+ },
+ }
+ assert _detect_non_retriable_nav_error(result) == _CERT_FAILURE_REASON
+
+
@pytest.mark.parametrize(
"reason",
[
- pytest.param(_DNS_FAILURE_REASON, id="dns_standard_format"),
- pytest.param(
- "Failed to navigate to url not-a-url. Error message: net::ERR_INVALID_URL",
- id="invalid_url_standard_format",
- ),
- pytest.param("net::ERR_NAME_RESOLUTION_FAILED happened mid-flight", id="name_resolution_mid_string"),
- pytest.param("SSL error: net::ERR_SSL_PROTOCOL_ERROR", id="ssl_prefixed"),
+ pytest.param(_GENERIC_FAILURE_REASON, id="generic"),
pytest.param(_TUNNEL_FAILURE_REASON, id="tunnel_connection_failed"),
pytest.param(_SOCKS_FAILURE_REASON, id="socks_connection_failed"),
- pytest.param(_NO_ADDRESS_RECORD_FAILURE_REASON, id="no_dns_address_record"),
- pytest.param(
- "Failed to navigate to url https://x.test. Error message: net::ERR_SOCKS_CONNECTION_HOST_UNREACHABLE",
- id="socks_host_unreachable",
- ),
+ pytest.param(_SOCKS_HOST_UNREACHABLE_REASON, id="socks_host_unreachable"),
],
)
-def test_detect_matches_error_in_block_failure_reason(reason: str) -> None:
+def test_detect_returns_none_for_generic_failure(reason: str) -> None:
result = {"ok": False, "data": {"blocks": [{"failure_reason": reason}]}}
- assert _detect_non_retriable_nav_error(result) == reason
-
-
-def test_detect_matches_cert_error_in_run_level_failure_reason() -> None:
- result = {"ok": False, "data": {"failure_reason": _CERT_FAILURE_REASON, "blocks": []}}
- assert _detect_non_retriable_nav_error(result) == _CERT_FAILURE_REASON
-
-
-def test_detect_returns_none_for_generic_failure() -> None:
- result = {"ok": False, "data": {"blocks": [{"failure_reason": _GENERIC_FAILURE_REASON}]}}
assert _detect_non_retriable_nav_error(result) is None
@@ -158,7 +336,8 @@ def test_detect_prefers_run_level_over_block_level() -> None:
"ok": False,
"data": {
"failure_reason": _DNS_FAILURE_REASON,
- "blocks": [{"failure_reason": _CERT_FAILURE_REASON}],
+ "error_codes": ["net::ERR_NAME_NOT_RESOLVED"],
+ "blocks": [{"failure_reason": _CERT_FAILURE_REASON, "error_codes": ["net::ERR_CERT_DATE_INVALID"]}],
},
}
assert _detect_non_retriable_nav_error(result) == _DNS_FAILURE_REASON
@@ -176,7 +355,9 @@ def test_record_sets_flag_on_dns_failure() -> None:
ctx,
{
"ok": False,
- "data": {"blocks": [{"failure_reason": _DNS_FAILURE_REASON}]},
+ "data": {
+ "blocks": [{"failure_reason": _DNS_FAILURE_REASON, "error_codes": ["net::ERR_NAME_NOT_RESOLVED"]}]
+ },
},
)
assert ctx.last_test_non_retriable_nav_error == _DNS_FAILURE_REASON
@@ -372,20 +553,20 @@ def test_exception_carries_url_and_error_message() -> None:
@pytest.mark.parametrize(
- "reason",
+ ("reason", "code"),
[
- pytest.param(_DNS_FAILURE_REASON, id="dns"),
- pytest.param(_SOCKS_FAILURE_REASON, id="socks_connection_failed"),
+ pytest.param(_DNS_FAILURE_REASON, "net::ERR_NAME_NOT_RESOLVED", id="dns"),
+ pytest.param(_CERT_FAILURE_REASON, "net::ERR_CERT_DATE_INVALID", id="certificate"),
],
)
-def test_full_flow_record_then_check_then_raise(reason: str) -> None:
+def test_full_flow_record_then_check_then_raise(reason: str, code: str) -> None:
ctx = _fresh_context()
ctx.test_after_update_done = True
_record_run_blocks_result(
ctx,
{
"ok": False,
- "data": {"blocks": [{"failure_reason": reason}]},
+ "data": {"blocks": [{"failure_reason": reason, "error_codes": [code]}]},
},
)
assert ctx.last_test_non_retriable_nav_error == reason
@@ -422,6 +603,33 @@ def test_full_flow_cleared_after_successful_run() -> None:
_maybe_raise_non_retriable_nav(ctx) # must not raise
+def test_proxy_codes_are_subtracted_from_the_browser_skip_set() -> None:
+ """Renaming one of these in skyvern/constants.py would silently make the proxy family terminal again,
+ or drop a target-owned code out of the stop set entirely."""
+ assert set(PROXY_TRANSPORT_NAV_ERROR_CODES) <= set(SKIP_INNER_NAV_RETRY_ERRORS)
+ assert set(TERMINAL_NAV_ERROR_CODES).isdisjoint(PROXY_TRANSPORT_NAV_ERROR_CODES)
+ assert set(TERMINAL_NAV_ERROR_CODES) | set(PROXY_TRANSPORT_NAV_ERROR_CODES) == set(SKIP_INNER_NAV_RETRY_ERRORS)
+
+
+ ("codes", "proxy_owned"),
+ [
+ pytest.param(["net::ERR_TUNNEL_CONNECTION_FAILED"], True, id="driver_reported_a_proxy_code"),
+ pytest.param(["net::ERR_SOCKS_CONNECTION_FAILED"], True, id="driver_reported_socks"),
+ pytest.param(["net::ERR_NAME_NOT_RESOLVED"], False, id="driver_reported_a_target_code"),
+ pytest.param(
+ ["net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_CERT_DATE_INVALID"],
+ False,
+ id="a_target_code_alongside_disqualifies",
+ ),
+ pytest.param(["FILE_PARSER_ERROR"], False, id="an_unrelated_block_code"),
+ pytest.param([], False, id="the_driver_reported_nothing"),
+ ],
+)
+def test_ownership_comes_from_the_codes_the_driver_reported(codes: list[str], proxy_owned: bool) -> None:
+ assert proxy_owns_nav_codes(codes) is proxy_owned
+
+
@pytest.mark.parametrize(
("reason", "block_type"),
[
@@ -430,29 +638,506 @@ def test_full_flow_cleared_after_successful_run() -> None:
pytest.param(_SOCKS_HOST_UNREACHABLE_REASON, "code", id="secure_runner_goto_host_unreachable"),
],
)
-def test_proxy_transport_full_flow_uses_browser_network_reply(reason: str, block_type: str) -> None:
- ctx, result = _record_and_render_terminal_reply(reason, block_type=block_type)
+def test_proxy_transport_run_keeps_proposal_and_reaches_repair(reason: str, block_type: str) -> None:
+ ctx = _fresh_context()
+ 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"
+ outcome = _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "failed_navigation",
+ "block_type": block_type,
+ "status": "failed",
+ "failure_reason": reason,
+ "error_codes": _driver_codes_for(reason),
+ }
+ ]
+ },
+ },
+ )
- assert result.user_response == _PROXY_FAILURE_REPLY.format(reason=reason)
- assert "verify the URL" not in result.user_response
- assert result.updated_workflow is None
- assert result.workflow_yaml is None
+ assert ctx.last_test_non_retriable_nav_error is None
+ _maybe_raise_non_retriable_nav(ctx)
+ assert _next_action(DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE, ctx, {}, None) is RepairNextAction.REPAIR
+ # The turn stays repairable, but the block is not what broke: authoring repair must not rewrite
+ # working code to chase a fault in Skyvern's own egress.
+ assert _error_text_requires_stop(ctx, {"failure_reason": reason}) is True
+ assert ctx.has_staged_proposal is True
+ assert ctx.staged_workflow_yaml == "title: staged"
+ assert ctx.last_test_ok is False
+ assert ctx.last_full_workflow_test_ok is False
+ assert ctx.verified_terminal_proposal_ready is False
+
+ result = agent_module._make_agent_result(
+ ctx,
+ narrative_payload={},
+ user_response="Skyvern's proxy hop failed; re-testing on another node.",
+ updated_workflow=SimpleNamespace(workflow_id="wf"),
+ workflow_yaml="title: staged",
+ )
+ assert result.updated_workflow is not None
+ assert result.proposal_disposition == "review_untested"
+
+ proxy_prefix = "Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES): "
+ assert outcome.display_reason is not None
+ assert outcome.display_reason.startswith(proxy_prefix)
+ assert len(outcome.display_reason) <= _DISPLAY_REASON_MAX_CHARS
+ error_code = reason.rsplit(" ", 1)[-1]
+ assert error_code.startswith("net::ERR_")
+ assert error_code in outcome.display_reason
+ assert "verify the URL" not in outcome.display_reason
+
+
+ ("blocks", "run_codes", "connect_failure_reason", "proxy_location", "labelled", "displayed", "stop"),
+ [
+ pytest.param(
+ [{"failure_reason": _GENERIC_FAILURE_REASON}],
+ ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ _TUNNEL_FAILURE_REASON,
+ ProxyLocation.RESIDENTIAL_ES,
+ True,
+ None,
+ None,
+ id="a_connect_failure_outside_any_block_carries_the_runs_code",
+ ),
+ pytest.param(
+ [{"failure_reason": _SOCKS_FAILURE_REASON, "error_codes": ["net::ERR_SOCKS_CONNECTION_FAILED"]}],
+ [],
+ None,
+ None,
+ True,
+ None,
+ None,
+ id="an_unresolvable_proxy_location_still_names_the_hop",
+ ),
+ pytest.param(
+ [{"failure_reason": _PROXY_CODE_PAST_THE_CLAMP, "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"]}],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ True,
+ None,
+ None,
+ id="the_proxy_code_trails_past_the_display_clamp",
+ ),
+ pytest.param(
+ [
+ {
+ "label": "failed_navigation",
+ "block_type": "navigation",
+ "status": "failed",
+ "failure_reason": _TARGET_CODE_PLANTED_IN_THE_URL,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ }
+ ],
+ [],
+ None,
+ None,
+ True,
+ None,
+ None,
+ id="a_target_code_planted_in_the_requested_url_is_not_the_verdict",
+ ),
+ pytest.param(
+ [
+ {
+ "label": "first",
+ "failure_reason": _TUNNEL_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ },
+ {"label": "second", "failure_reason": _GENERIC_FAILURE_REASON},
+ ],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ False,
+ _GENERIC_FAILURE_REASON,
+ None,
+ id="a_later_unrelated_block_is_never_labelled_as_the_hop",
+ ),
+ pytest.param(
+ [{"label": "first", "failure_reason": _GENERIC_FAILURE_REASON}],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ False,
+ _GENERIC_FAILURE_REASON,
+ None,
+ id="an_unrelated_failure_alone",
+ ),
+ pytest.param(
+ [{"label": "first", "failure_reason": _TUNNEL_FAILURE_REASON}],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ False,
+ _TUNNEL_FAILURE_REASON,
+ None,
+ id="the_producers_own_sentence_without_a_code_attributes_nothing",
+ ),
+ *(
+ pytest.param(
+ [{"label": "first", "failure_reason": reason}],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ False,
+ reason,
+ None,
+ id=f"prose_quoting_a_proxy_code_{index}",
+ )
+ for index, reason in enumerate(
+ (
+ _MODEL_PROSE_QUOTING_A_PROXY_CODE,
+ _PROSE_QUOTING_A_TASK_SEPARATOR,
+ _PROSE_QUOTING_A_GOTO_SEPARATOR,
+ _PROSE_QUOTING_A_NAV_SEPARATOR,
+ )
+ )
+ ),
+ *(
+ pytest.param(
+ [
+ {"label": "first", "failure_reason": first, "error_codes": _driver_codes_for(first)},
+ {"label": "second", "failure_reason": second, "error_codes": _driver_codes_for(second)},
+ ],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL_ES,
+ False,
+ None,
+ _CERT_FAILURE_REASON,
+ id=f"a_target_owned_sibling_block_refuses_the_label_{order}",
+ )
+ for order, (first, second) in enumerate(
+ ((_CERT_FAILURE_REASON, _TUNNEL_FAILURE_REASON), (_TUNNEL_FAILURE_REASON, _CERT_FAILURE_REASON))
+ )
+ ),
+ pytest.param(
+ [
+ {
+ "label": "first",
+ "failure_reason": _TUNNEL_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ }
+ ],
+ [],
+ None,
+ ProxyLocation.RESIDENTIAL.value,
+ True,
+ None,
+ None,
+ id="a_plain_string_proxy_location_still_labels_the_hop",
+ ),
+ ],
+)
+def test_the_run_observation_labels_only_a_hop_the_driver_reported(
+ blocks: list[dict[str, object]],
+ run_codes: list[str],
+ connect_failure_reason: str | None,
+ proxy_location: ProxyLocation | str | None,
+ labelled: bool,
+ displayed: str | None,
+ stop: str | None,
+) -> None:
+ """The label and the terminal stop both key on the codes the driver reported, never on the
+ sentence a model or page can write."""
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ ctx.effective_workflow_proxy_location = proxy_location
+
+ outcome = _record_run_blocks_result(
+ ctx,
+ {"ok": False, "data": {"blocks": blocks, "error_codes": run_codes}},
+ connect_failure_reason=connect_failure_reason,
+ )
+
+ display_reason = outcome.display_reason or ""
+ assert display_reason.startswith(_proxy_hop_label(proxy_location)) is labelled
+ assert display_reason.startswith("Skyvern proxy hop failed") is labelled
+ assert ctx.last_test_non_retriable_nav_error == stop
+ if displayed is not None:
+ assert display_reason == displayed
+ if labelled:
+ # The label drives the reply copy and holds authoring repair off the block it names.
+ assert ctx.last_test_proxy_owned_failure is True
+ # The clamp shortens the sentence, so the code has to survive it whole for the label to mean
+ # anything: a truncated token names no verdict.
+ reported = [*run_codes, *(code for block in blocks for code in block.get("error_codes") or [])]
+ assert any(code in display_reason for code in reported)
+ assert len(display_reason) <= _DISPLAY_REASON_MAX_CHARS
+ elif stop is None:
+ # An unlabelled run with no stop is nobody's: it must not be recorded as proxy-owned either.
+ assert ctx.last_test_proxy_owned_failure is False
+ if connect_failure_reason is not None:
+ assert _GENERIC_FAILURE_REASON not in display_reason
+
+
+ ("reason", "driver_code", "session_proxy", "workflow_proxy", "expected_error"),
+ [
+ *(
+ pytest.param(
+ reason,
+ _DRIVER_CODE_BY_REASON[reason],
+ ProxyLocation.RESIDENTIAL_ES,
+ None,
+ f"Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES): {reason}",
+ id=f"the_driver_reported_the_hop_{index}",
+ )
+ for index, reason in enumerate(
+ (_TUNNEL_FAILURE_REASON, _SOCKS_FAILURE_REASON, _SOCKS_HOST_UNREACHABLE_REASON)
+ )
+ ),
+ pytest.param(
+ _TUNNEL_FAILURE_REASON,
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ None,
+ None,
+ f"Skyvern proxy hop failed: {_TUNNEL_FAILURE_REASON}",
+ id="an_unreadable_proxy_label_keeps_the_attribution",
+ ),
+ pytest.param(
+ _TUNNEL_FAILURE_REASON,
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ ProxyLocation.RESIDENTIAL,
+ ProxyLocation.RESIDENTIAL_ES,
+ f"Skyvern proxy hop failed (proxy_location=RESIDENTIAL): {_TUNNEL_FAILURE_REASON}",
+ id="the_session_proxy_wins_over_the_declared_workflow_proxy",
+ ),
+ *(
+ pytest.param(reason, None, ProxyLocation.RESIDENTIAL_ES, None, reason, id=f"unattributable_{index}")
+ for index, reason in enumerate(
+ (
+ _DNS_FAILURE_REASON,
+ _CERT_FAILURE_REASON,
+ _DNS_FAILURE_WITH_PROXY_TOKEN_IN_URL,
+ _MIXED_CODE_TARGET_CODE_PAST_THE_CLAMPS,
+ _MODEL_PROSE_QUOTING_A_PROXY_CODE,
+ _PROSE_QUOTING_A_TASK_SEPARATOR,
+ _PROSE_QUOTING_A_GOTO_SEPARATOR,
+ _PROSE_QUOTING_A_NAV_SEPARATOR,
+ _GENERIC_FAILURE_REASON,
+ )
+ )
+ ),
+ ],
+)
+async def test_a_scout_navigation_failure_names_only_a_hop_the_driver_reported(
+ monkeypatch: pytest.MonkeyPatch,
+ reason: str,
+ driver_code: str | None,
+ session_proxy: ProxyLocation | None,
+ workflow_proxy: ProxyLocation | None,
+ expected_error: str,
+) -> None:
+ ctx = _scout_ctx(monkeypatch, nav_error=reason, session_proxy=session_proxy, driver_code=driver_code)
+ if workflow_proxy is not None:
+ ctx.effective_workflow_proxy_location = workflow_proxy
+
+ result = await _discovery_navigate(ctx, "https://example.test/")
+
+ assert result["error"] == expected_error
+
+
+ ("reason", "driver_code", "expected_error"),
+ [
+ pytest.param(
+ _TUNNEL_FAILURE_REASON,
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ f"Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES): {_TUNNEL_FAILURE_REASON}",
+ id="the_driver_reported_the_hop",
+ ),
+ *(
+ pytest.param(reason, None, reason, id=f"unattributable_{index}")
+ for index, reason in enumerate(
+ (
+ _DNS_FAILURE_REASON,
+ _MODEL_PROSE_QUOTING_A_PROXY_CODE,
+ _PROSE_QUOTING_A_TASK_SEPARATOR,
+ _PROSE_QUOTING_A_GOTO_SEPARATOR,
+ _PROSE_QUOTING_A_NAV_SEPARATOR,
+ )
+ )
+ ),
+ ],
+)
+async def test_a_model_navigation_failure_names_only_a_hop_the_driver_reported(
+ monkeypatch: pytest.MonkeyPatch, reason: str, driver_code: str | None, expected_error: str
+) -> None:
+ ctx = _scout_ctx(monkeypatch, nav_error=reason, session_proxy=ProxyLocation.RESIDENTIAL_ES, driver_code=driver_code)
+ monkeypatch.setattr(mcp_hooks_module, "_capture_post_interaction_screenshot", AsyncMock(return_value=None))
+ tool_result: dict[str, object] = {"ok": False, "error": reason}
+ if driver_code:
+ tool_result["nav_error_code"] = driver_code
+
+ result = await _navigate_post_hook(tool_result, {}, ctx)
+
+ assert result["error"] == expected_error
+
+
+ "reason",
+ [
+ pytest.param(_MODEL_PROSE_QUOTING_A_PROXY_CODE, id="prose_without_a_separator"),
+ pytest.param(_PROSE_QUOTING_A_TASK_SEPARATOR, id="prose_quoting_the_task_separator"),
+ pytest.param(_PROSE_QUOTING_A_GOTO_SEPARATOR, id="prose_quoting_the_goto_separator"),
+ pytest.param(_PROSE_QUOTING_A_NAV_SEPARATOR, id="prose_quoting_the_navigation_separator"),
+ ],
+)
+def test_prose_quoting_a_proxy_code_still_blames_the_target_in_the_terminal_reply(reason: str) -> None:
+ reply = agent_module._non_retriable_nav_reply(reason)
+
+ assert reply == _NON_PROXY_FAILURE_REPLY.format(reason=reason)
+
+
+def test_mixed_code_run_stops_on_the_target_owned_code() -> None:
+ reason = (
+ "Failed to navigate to url https://x.test. "
+ "Error message: net::ERR_SOCKS_CONNECTION_FAILED after net::ERR_CERT_DATE_INVALID"
+ )
+ ctx, result = _record_and_render_terminal_reply(
+ reason,
+ block_type="navigation",
+ codes=["net::ERR_SOCKS_CONNECTION_FAILED", "net::ERR_CERT_DATE_INVALID"],
+ )
+
+ assert ctx.last_test_non_retriable_nav_error == reason
+ assert result.user_response == _NON_PROXY_FAILURE_REPLY.format(reason=reason)
assert result.turn_outcome is not None
assert result.turn_outcome.terminal_reason == "non_retriable_nav"
assert result.proposal_disposition == "no_proposal"
assert result.updated_workflow is None
- assert ctx.last_test_non_retriable_nav_error == reason
+ assert ctx.last_run_outcome is not None
+ assert not (ctx.last_run_outcome.display_reason or "").startswith("Skyvern proxy hop failed")
-def test_a_host_with_no_address_record_is_not_answered_with_contact_support() -> None:
- # The proxy error code is still in the reason, so without the marker check this renders the
- # browser-network reply and sends the user to Support over a URL only they can fix.
- _, result = _record_and_render_terminal_reply(_NO_ADDRESS_RECORD_FAILURE_REASON, block_type="navigation")
+def test_chat_reply_refuses_the_proxy_label_when_the_target_code_trails_past_the_clamp() -> None:
+ reason = _MIXED_CODE_TARGET_CODE_PAST_THE_CLAMPS
+ assert "net::ERR_CERT_DATE_INVALID" not in agent_module._normalize_failure_reason(reason)
+ ctx = _fresh_context()
+ ctx.last_test_ok = False
+ ctx.last_update_block_count = 2
+ ctx.last_workflow = SimpleNamespace(workflow_id="wf")
+ ctx.last_workflow_yaml = "title: draft"
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ ctx.last_failure_category_top = "NAVIGATION_FAILURE"
+ ctx.last_test_failure_reason = reason
+
+ reply = agent_module._rewrite_failed_test_response("model text", ctx)
+
+ assert "Skyvern proxy hop failed" not in reply
+
+
+def test_run_observation_refuses_the_proxy_label_when_the_target_code_trails_past_the_clamp() -> None:
+ reason = _MIXED_CODE_TARGET_CODE_PAST_THE_CLAMPS
+ # Both codes were reported; the target one is only clamped out of the displayed sentence, and
+ # attribution reads the codes rather than that sentence.
+ ctx, result = _record_and_render_terminal_reply(
+ reason,
+ block_type="navigation",
+ codes=["net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_CERT_DATE_INVALID"],
+ )
- assert result.user_response == _NO_ADDRESS_RECORD_REPLY.format(reason=_NO_ADDRESS_RECORD_FAILURE_REASON)
- assert "Skyvern Support" not in result.user_response
- assert result.turn_outcome is not None
- assert result.turn_outcome.terminal_reason == "non_retriable_nav"
+ assert ctx.last_run_outcome is not None
+ assert not (ctx.last_run_outcome.display_reason or "").startswith("Skyvern proxy hop failed")
+ assert result.user_response == _NON_PROXY_FAILURE_REPLY.format(reason=reason)
+
+
+ ("failure_category", "failure_reason", "driver_codes", "expects_proxy_label"),
+ [
+ pytest.param(
+ "PROXY_ERROR",
+ "no proxy available for location RESIDENTIAL_ES",
+ [],
+ False,
+ id="no_proxy_available",
+ ),
+ pytest.param(
+ "PROXY_ERROR",
+ "The page displayed: Proxy unavailable, please contact your administrator.",
+ [],
+ False,
+ id="page_prose_matching_the_proxy_keywords",
+ ),
+ pytest.param(
+ "PROXY_ERROR",
+ _PROSE_QUOTING_A_TASK_SEPARATOR,
+ [],
+ False,
+ id="prose_quoting_the_task_separator",
+ ),
+ pytest.param(
+ "PROXY_ERROR",
+ _PROSE_QUOTING_A_GOTO_SEPARATOR,
+ [],
+ False,
+ id="prose_quoting_the_goto_separator",
+ ),
+ pytest.param(
+ "PROXY_ERROR",
+ _PROSE_QUOTING_A_NAV_SEPARATOR,
+ [],
+ False,
+ id="prose_quoting_the_navigation_separator",
+ ),
+ pytest.param(
+ "NAVIGATION_FAILURE",
+ _TUNNEL_FAILURE_REASON,
+ ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ True,
+ id="the_driver_reported_the_proxy_code",
+ ),
+ pytest.param("DATA_EXTRACTION_FAILURE", _GENERIC_FAILURE_REASON, [], False, id="unrelated_block_failure"),
+ ],
+)
+def test_the_proxy_label_requires_a_code_the_driver_reported(
+ failure_category: str, failure_reason: str, driver_codes: list[str], expects_proxy_label: bool
+) -> None:
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ ctx.last_update_block_count = 2
+ ctx.last_workflow = SimpleNamespace(workflow_id="wf")
+ ctx.last_workflow_yaml = "title: draft"
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "open_page",
+ "status": "failed",
+ "failure_reason": failure_reason,
+ "error_codes": driver_codes,
+ }
+ ]
+ },
+ },
+ )
+ ctx.last_failure_category_top = failure_category
+
+ reply = agent_module._rewrite_failed_test_response("model text", ctx)
+
+ assert ("Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES)" in reply) is expects_proxy_label
+ assert (agent_module._SKYVERN_EGRESS_FOLLOW_UP.strip() in reply) is expects_proxy_label
+ expects_neutral_ask = not expects_proxy_label and failure_category == "PROXY_ERROR"
+ assert (agent_module._FAILURE_FOLLOW_UP["PROXY_ERROR"].strip() in reply) is expects_neutral_ask
+ assert "verify the URL" not in reply
+ assert "confirm the URL is correct" not in reply
+ assert ctx.last_test_non_retriable_nav_error is None
@pytest.mark.parametrize(
@@ -474,6 +1159,703 @@ def test_non_proxy_full_flow_preserves_existing_reply(reason: str) -> None:
assert result.turn_outcome.terminal_reason == "non_retriable_nav"
-# ---------------------------------------------------------------------------
-# Within-turn fail-fast guard — _tool_loop_error
-# ---------------------------------------------------------------------------
+ ("run_proxy_location", "run_session_proxy_location", "expected_label"),
+ [
+ pytest.param(
+ ProxyLocation.RESIDENTIAL_ES,
+ ProxyLocation.RESIDENTIAL,
+ "RESIDENTIAL",
+ id="the_attached_session_overrides_the_run_row",
+ ),
+ pytest.param(
+ ProxyLocation.RESIDENTIAL_ES,
+ None,
+ None,
+ id="a_session_naming_no_proxy_is_not_papered_over_by_the_run_row",
+ ),
+ pytest.param(
+ None,
+ None,
+ None,
+ id="a_session_naming_no_proxy_does_not_borrow_the_runtime_default",
+ ),
+ ],
+)
+async def test_test_run_only_turn_labels_the_proxy_the_run_acted_through(
+ monkeypatch: pytest.MonkeyPatch,
+ run_proxy_location: ProxyLocation | None,
+ run_session_proxy_location: ProxyLocation | None,
+ expected_label: str | None,
+) -> None:
+ monkeypatch.setattr(settings, "RUNTIME_PROXY_DEFAULT_NONE_ENABLED", False)
+ harness = await install_run_blocks_harness(
+ monkeypatch,
+ workflow_yaml=_PROXY_RUN_WORKFLOW_YAML,
+ polled_status="failed",
+ run_proxy_location=run_proxy_location,
+ run_session_proxy_location=run_session_proxy_location,
+ terminal_blocks=[
+ WorkflowRunBlock(
+ label="open_page",
+ block_type=BlockType.NAVIGATION,
+ status="failed",
+ failure_reason=_TUNNEL_FAILURE_REASON,
+ error_codes=["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ workflow_run_block_id="wrb_open_page",
+ workflow_run_id="wr_paused",
+ organization_id="org-1",
+ created_at=datetime(2026, 4, 21, 12, 5, tzinfo=UTC),
+ modified_at=datetime(2026, 4, 21, 12, 5, tzinfo=UTC),
+ )
+ ],
+ )
+ ctx = make_copilot_ctx(browser_session_id="pbs_chat")
+ ctx.staged_workflow = harness["workflow"]
+ ctx.frontier_resume_session_id = "pbs_run"
+ assert ctx.effective_workflow_proxy_location is None
+ assert ctx.last_workflow is None
+
+ await _run_blocks_and_collect_debug({"block_labels": ["open_page"], "parameters": {}}, ctx)
+
+ assert ctx.last_workflow is None
+ outcome = ctx.last_run_outcome
+ assert outcome is not None
+ assert outcome.display_reason is not None
+ expected_hop = (
+ "Skyvern proxy hop failed: "
+ if expected_label is None
+ else f"Skyvern proxy hop failed (proxy_location={expected_label}): "
+ )
+ assert outcome.display_reason.startswith(expected_hop)
+ proxy_lever = next(lever for lever in author_time_levers(ctx) if lever.mechanism == "proxy_location")
+ assert ctx.effective_workflow_proxy_location is None
+ assert proxy_lever.availability is None
+
+
+def test_a_budget_exit_reports_the_proxy_hop_the_recorded_run_named() -> None:
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "open_page",
+ "status": "failed",
+ "failure_reason": _TUNNEL_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ }
+ ]
+ },
+ },
+ )
+
+ reason, _ = agent_module._recorded_failure_summary(ctx)
+
+ assert reason.startswith("Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES): ")
+
+
+# A proxy code left on the browser state by an earlier hop. Nothing in an MCP call clears it.
+_STALE_BROWSER_STATE_CODE = "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+
+def _scout_ctx(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ nav_error: str,
+ session_proxy: ProxyLocationInput,
+ driver_code: str | None = None,
+) -> CopilotContext:
+ """A scout turn whose navigation failed.
+
+ ``nav_error`` is the sentence the tool returned and ``driver_code`` is what the browser itself
+ reported for this call. They are separate arguments because that is the whole contract: a page
+ or a model can write the sentence, only the driver can set the code.
+
+ The browser state carries a different, stale code on purpose. It is cleared only by a successful
+ state-managed navigation, which an MCP hop never performs, so a reader that consults it would
+ attach an earlier failure's verdict to this call.
+ """
+ ctx = make_copilot_ctx(browser_session_id="pbs_scout")
+ tool_result: dict[str, object] = {"ok": False, "error": nav_error}
+ if driver_code:
+ tool_result["nav_error_code"] = driver_code
+ ctx.discovery_mcp_server = SimpleNamespace(call_internal_tool=AsyncMock(return_value=tool_result))
+ browser_state = SimpleNamespace(
+ last_navigation_error_code=_STALE_BROWSER_STATE_CODE,
+ built_with_proxy_location=session_proxy,
+ )
+ monkeypatch.setattr(shared_module, "resolve_browser_state_for_context", AsyncMock(return_value=browser_state))
+ return ctx
+
+
+ ("proxy_location", "expected_hop_label", "expected_lever_label"),
+ [
+ pytest.param(
+ {"url": "http://user:[email protected]:8080"},
+ "custom proxy",
+ "custom proxy",
+ id="custom_proxy_dict",
+ ),
+ pytest.param({"country": "US", "subdivision": "CA"}, "custom proxy", "custom proxy", id="geo_shaped_dict"),
+ pytest.param(
+ GeoTarget(country="US", subdivision="CA", city="San Jose"), "US", "US-CA-San Jose", id="geo_target"
+ ),
+ pytest.param(ProxyLocation.RESIDENTIAL_ES, "RESIDENTIAL_ES", "RESIDENTIAL_ES", id="proxy_location_enum"),
+ pytest.param(ProxyLocation.NONE, None, None, id="no_proxy"),
+ ],
+)
+def test_the_repair_lever_keeps_the_geo_detail_the_hop_label_drops(
+ proxy_location: ProxyLocationInput,
+ expected_hop_label: str | None,
+ expected_lever_label: str | None,
+) -> None:
+ ctx = _fresh_context()
+ ctx.last_test_anti_bot = "Extracted data reported anti-bot blocker: Verify you are human"
+ ctx.effective_workflow_proxy_location = proxy_location
+
+ hop_reason = proxy_hop_failure_reason(ctx, _TUNNEL_FAILURE_REASON)
+ lever = next(lever for lever in author_time_levers(ctx) if lever.mechanism == "proxy_location")
+
+ assert lever.availability == expected_lever_label
+ if expected_hop_label is None:
+ assert hop_reason.startswith("Skyvern proxy hop failed: ")
+ else:
+ assert hop_reason.startswith(f"Skyvern proxy hop failed (proxy_location={expected_hop_label}): ")
+ assert "hunter2" not in hop_reason
+ assert "hunter2" not in (lever.availability or "")
+
+
+def test_a_proxy_failure_on_a_challenge_page_carries_both_facts_to_the_model() -> None:
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ ctx.last_test_anti_bot = "Extracted data reported anti-bot blocker: Verify you are human"
+ ctx.captcha_solver_available = True
+ ctx.effective_workflow_proxy_location = ProxyLocation.RESIDENTIAL_ES
+ result = {
+ "ok": False,
+ "data": {
+ "workflow_run_id": "wr_proxy_challenge",
+ "overall_status": "failed",
+ "failure_reason": _TUNNEL_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ "failure_categories": [{"category": "ANTI_BOT_DETECTION", "evidence_source": "challenge_state"}],
+ "blocks": [],
+ },
+ }
+
+ outcome = _record_run_blocks_result(ctx, result)
+ finalize_build_test_result(ctx, source_tool="update_and_run_blocks", result=result, workflow_updated=True)
+ packet = result["data"][BUILD_TEST_PACKET_KEY]
+
+ assert ctx.last_test_non_retriable_nav_error is None
+ assert outcome.display_reason is not None
+ assert outcome.display_reason.startswith("Skyvern proxy hop failed (proxy_location=RESIDENTIAL_ES): ")
+ assert packet["challenge"] is not None
+ proxy_lever = next(lever for lever in packet["levers"] if lever["mechanism"] == "proxy_location")
+ assert proxy_lever["availability"] == "RESIDENTIAL_ES"
+ assert packet["challenge_notices"]
+ assert ctx.last_full_workflow_test_ok is not True
+
+
+DRIVER_NAV_MESSAGES = [
+ # Where the drivers write a code (message shapes: Playwright 1.58 on Chromium, skycdp facade).
+ ("Page.goto: net::ERR_NAME_NOT_RESOLVED at https://x.test/net::ERR_CERT_REVOKED", "net::ERR_NAME_NOT_RESOLVED"),
+ ("Page.reload: net::ERR_ABORTED; maybe frame was detached?", "net::ERR_ABORTED"),
+ (": net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/", "net::ERR_TUNNEL_CONNECTION_FAILED"),
+ (
+ "navigation to https://x.test/?e=net::ERR_CERT_REVOKED failed: net::ERR_TUNNEL_CONNECTION_FAILED",
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ ),
+ # Codes spelled by a URL a page or an author chose, with no driver verdict behind them.
+ ("Page.goto: Timeout 30000ms exceeded at https://x.test/?q=net::ERR_TUNNEL_CONNECTION_FAILED", None),
+ (
+ 'Page.reload: Timeout 30000ms exceeded.\nCall log:\n - navigated to "https://x.test/?e=net::ERR_CERT_REVOKED"\n',
+ None,
+ ),
+ (
+ 'Page.goto: Navigation to "https://x.test/login" is interrupted by another navigation to '
+ '"https://x.test/login net::ERR_NAME_NOT_RESOLVED"',
+ None,
+ ),
+ # Chromium strips tabs from the requested URL, joining a code the author split across them.
+ ('Page.goto: Timeout 1ms exceeded.\nCall log:\n - navigating to "about:blank net::ERR_CERT_REVOKED"\n', None),
+ ("navigation to https://x.test/ failed: net::ERR_CERT_REVOKED failed: Cannot navigate to invalid URL", None),
+]
+
+
[email protected](("message", "expected"), DRIVER_NAV_MESSAGES)
+def test_a_code_counts_only_where_the_driver_writes_it(message: str, expected: str | None) -> None:
+ assert driver_nav_error_code(message) == expected
+
+
+def test_a_driver_code_survives_the_run_commit_scrub_of_a_value_that_spells_part_of_it() -> None:
+ """Workflow parameter values are registered for scrubbing whole, so "net" is enough to corrupt the
+ block's code before the ownership checks read it, and a proxy outage then reads as a code defect."""
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ register_secret_scrub_value(ctx, "net")
+ register_secret_scrub_value(ctx, "482913")
+ # A registered value spelled like a code stays scrubbed: the position is not a licence to write a
+ # secret back, and the certificate family is a prefix rather than a closed list.
+ register_secret_scrub_value(ctx, "net::ERR_CERT_HUNTER2")
+ result = {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "nav",
+ "status": "failed",
+ "failure_reason": "Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/",
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ # Code-shaped text anywhere else is still scrubbed: the exemption is the position.
+ "output": {"result": "net::ERR_482913"},
+ },
+ {"label": "earlier", "error_codes": ["net::ERR_CERT_HUNTER2"]},
+ ]
+ },
+ }
+
+ _commit_run_blocks_record(ctx, result)
+ assert ctx.last_test_proxy_owned_failure is True
+ # The model reads the finalized result and packet, which are scrubbed again.
+ finalize_build_test_result(ctx, source_tool="update_and_run_blocks", result=result, workflow_updated=True)
+
+ block = result["data"]["blocks"][0]
+ assert block["error_codes"] == ["net::ERR_TUNNEL_CONNECTION_FAILED"]
+ assert result["data"][BUILD_TEST_PACKET_KEY]["failure"]["error_codes"] == ["net::ERR_TUNNEL_CONNECTION_FAILED"]
+ assert "net::" not in block["failure_reason"]
+ assert "482913" not in str(result)
+ assert "HUNTER2" not in str(result)
+
+
+def test_a_proxy_failure_does_not_latch_authoring_repair_off_for_later_runs() -> None:
+ """The flag is only assigned past the success-path return, so it has to be cleared per run:
+ otherwise one proxy failure holds authoring repair off every later failure in the session."""
+ ctx = _fresh_context()
+ ctx.test_after_update_done = True
+ _record_run_blocks_result(
+ ctx,
+ {
+ "ok": False,
+ "data": {
+ "blocks": [
+ {
+ "label": "nav",
+ "failure_reason": _TUNNEL_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ }
+ ]
+ },
+ },
+ )
+ assert ctx.last_test_proxy_owned_failure is True
+
+ # A later run that SUCCEEDS returns before the flag is reassigned, so only a per-run clear
+ # releases it. A failing run would reassign and hide the leak.
+ _record_run_blocks_result(ctx, {"ok": True, "data": {"blocks": [{"label": "nav", "status": "completed"}]}})
+
+ assert ctx.last_test_proxy_owned_failure is False
+
+
+def test_a_handled_navigation_failure_is_keyed_to_the_task_that_raised_it() -> None:
+ """A task block that handles the failure instead of raising still has to report the code.
+
+ Keyed by task rather than last-one-wins because one browser state serves every block in a run: a
+ later block that fails without navigating must not inherit an earlier block's code and be
+ reported as a network failure.
+ """
+ context = SkyvernContext(run_id="wr_1")
+ context.task_nav_error_codes["tsk_navigated"] = "net::ERR_NAME_NOT_RESOLVED"
+
+ run_context = SimpleNamespace(secrets={})
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ assert block_module._recorded_task_nav_error_codes("tsk_navigated", run_context) == [
+ "net::ERR_NAME_NOT_RESOLVED"
+ ]
+ assert block_module._recorded_task_nav_error_codes("tsk_never_navigated", run_context) is None
+ # A code that is a stored credential is never carried onto the block row.
+ secret_context = SimpleNamespace(secrets={"login": "net::ERR_NAME_NOT_RESOLVED"})
+ assert block_module._recorded_task_nav_error_codes("tsk_navigated", secret_context) is None
+
+
+ ("parameter_value", "expected"),
+ [
+ # The mask replaces every occurrence, so a value inside a code cuts the verdict out of it
+ # before any later reader sees it: no proxy attribution, no terminal stop.
+ pytest.param("net", ["net::ERR_TUNNEL_CONNECTION_FAILED"], id="a_value_inside_the_code"),
+ # A code that is itself a parameter value is left to the mask.
+ pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", ["[redacted]"], id="a_value_that_is_the_code"),
+ ],
+)
+def test_a_driver_code_survives_the_code_block_result_scrub(
+ monkeypatch: pytest.MonkeyPatch, parameter_value: str, expected: list[str]
+) -> None:
+ """The heal path masks the whole block result before the run result is assembled."""
+
+ def redact(value: object, parameters: dict[str, object]) -> object:
+ secret = str(next(iter(parameters.values())))
+
+ def walk(node: object) -> object:
+ if isinstance(node, str):
+ return node.replace(secret, "[redacted]")
+ if isinstance(node, list):
+ return [walk(item) for item in node]
+ return node
+
+ return walk(value)
+
+ monkeypatch.setattr(block_module.app.AGENT_FUNCTION, "redact_codeblock_parameter_values", redact)
+ result = block_module.BlockResult(
+ success=False,
+ failure_reason="Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED",
+ error_codes=["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ status=block_module.BlockStatus.failed,
+ output_parameter=_output_parameter(),
+ workflow_run_block_id="wrb_test",
+ )
+
+ scrubbed = block_module._redact_codeblock_result(result, {"site": parameter_value})
+
+ assert scrubbed.error_codes == expected
+
+
+ ("status", "expected"),
+ [(TaskStatus.terminated, ["net::ERR_NAME_NOT_RESOLVED"]), (TaskStatus.completed, None)],
+)
+async def test_a_task_that_terminates_after_a_failed_navigation_reports_its_code(
+ status: TaskStatus, expected: list[str] | None
+) -> None:
+ """The action handler keeps the code when the agent terminates right after a failed navigation; the
+ block has to carry it too, or Copilot never sees the verdict the task ended on."""
+ block = block_module.TaskBlock(
+ label="open", output_parameter=_output_parameter(), title="open", url="https://x.test/"
+ )
+ context = SkyvernContext(run_id="wr_missing_starter_url_test")
+ context.task_nav_error_codes["tsk_test"] = "net::ERR_NAME_NOT_RESOLVED"
+ built: dict[str, object] = {}
+
+ async def build_block_result(_self: object, **kwargs: object) -> SimpleNamespace:
+ built.update(kwargs)
+ return SimpleNamespace(**kwargs)
+
+ with _mock_block_execute_deps(working_page_url="https://x.test/") as deps:
+ deps["tasks_db"].get_task = AsyncMock(
+ return_value=SimpleNamespace(
+ task_id="tsk_test", status=status, failure_reason="The site cannot be reached."
+ )
+ )
+ block_module.app.WORKFLOW_SERVICE.get_recent_task_screenshot_artifacts = AsyncMock(return_value=[])
+ block_module.app.WORKFLOW_SERVICE.get_recent_workflow_screenshot_artifacts = AsyncMock(return_value=[])
+ block_module.app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+ block_module.app.STORAGE.get_current_attempt_downloaded_files = AsyncMock(return_value=[])
+ with (
+ mock.patch.object(skyvern_context, "current", return_value=context),
+ mock.patch.object(block_module.Block, "build_block_result", build_block_result),
+ mock.patch.object(block_module.Block, "record_output_parameter_value", AsyncMock()),
+ mock.patch.object(block_module.TaskOutput, "from_task", return_value=mock.MagicMock(model_dump=dict)),
+ ):
+ await block.execute(
+ workflow_run_id="wr_missing_starter_url_test", workflow_run_block_id="wrb", organization_id="o_test"
+ )
+
+ assert built["error_codes"] == expected
+
+
+async def test_an_unreadable_session_costs_the_proxy_name_not_the_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Resolving the session is how the hop gets named, not how the failure is reported.
+
+ A session store that is down must not replace the navigation failure with its own exception: the
+ model would lose the fault entirely and see a lookup error instead.
+ """
+ ctx = _scout_ctx(
+ monkeypatch,
+ nav_error=_TUNNEL_FAILURE_REASON,
+ session_proxy=ProxyLocation.RESIDENTIAL_ES,
+ driver_code="net::ERR_TUNNEL_CONNECTION_FAILED",
+ )
+ monkeypatch.setattr(
+ shared_module,
+ "resolve_browser_state_for_context",
+ AsyncMock(side_effect=RuntimeError("session store unavailable")),
+ )
+
+ attributed = await shared_module.attribute_navigation_failure(
+ ctx,
+ {"ok": False, "error": _TUNNEL_FAILURE_REASON, "nav_error_code": "net::ERR_TUNNEL_CONNECTION_FAILED"},
+ )
+
+ assert _TUNNEL_FAILURE_REASON in attributed["error"]
+ assert "Skyvern proxy hop failed" in attributed["error"]
+ assert "proxy_location=" not in attributed["error"]
+
+
+ ("blocks", "expected_stop"),
+ [
+ pytest.param(
+ [
+ {
+ "failure_reason": _CERT_FAILURE_REASON,
+ "error_codes": ["net::ERR_CERT_DATE_INVALID"],
+ "output": {"declared_error_code": "net::ERR_CERT_DATE_INVALID"},
+ }
+ ],
+ None,
+ id="a_code_the_block_author_declared_is_not_a_browser_verdict",
+ ),
+ pytest.param(
+ [
+ {
+ "label": "first",
+ "failure_reason": _SHARED_FAILURE_REASON,
+ "error_codes": ["net::ERR_CERT_DATE_INVALID"],
+ },
+ {
+ "label": "second",
+ "failure_reason": _SHARED_FAILURE_REASON,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ },
+ ],
+ _SHARED_FAILURE_REASON,
+ id="two_blocks_sharing_a_sentence_are_judged_on_their_own_codes",
+ ),
+ ],
+)
+def test_the_terminal_stop_reads_each_blocks_own_codes(
+ blocks: list[dict[str, object]], expected_stop: str | None
+) -> None:
+ """Reason text neither identifies a block nor says who wrote it: a sentence can repeat across
+ blocks, and an author can declare a code that spells a browser verdict."""
+ assert _detect_non_retriable_nav_error({"ok": False, "data": {"blocks": blocks}}) == expected_stop
+
+
+def test_a_run_level_reason_answers_with_the_block_the_run_ended_on() -> None:
+ """A block that continued on failure leaves its verdict behind it. Reading every code the result
+ carries would stop the run against a sentence whose own block never had that code, and repair
+ would never reach the block that actually ended the run."""
+ result = {
+ "ok": False,
+ "data": {
+ "failure_reason": _GENERIC_FAILURE_REASON,
+ "blocks": [
+ {
+ "label": "first",
+ "failure_reason": _CERT_FAILURE_REASON,
+ "error_codes": ["net::ERR_CERT_DATE_INVALID"],
+ },
+ {"label": "second", "failure_reason": _GENERIC_FAILURE_REASON},
+ ],
+ },
+ }
+
+ # Neither sentence answers with the other's code, and a block the run continued past does not
+ # stop a run that ended somewhere else.
+ assert _detect_non_retriable_nav_error(result) is None
+
+ # A run whose newest row is a tail the runner appended answers with the newest block that has a
+ # reason, so the stop and the sentence a reader is shown come from the same block.
+ result["data"]["blocks"] = [
+ {"label": "nav", "failure_reason": _CERT_FAILURE_REASON, "error_codes": ["net::ERR_CERT_DATE_INVALID"]},
+ {"label": "tail", "status": "skipped"},
+ ]
+ assert _detect_non_retriable_nav_error(result) == _CERT_FAILURE_REASON
+
+ # A block that ended the run with a code but no sentence of its own is still answered for: the
+ # run's sentence carries its verdict, or the stop is lost and nothing reports the failure.
+ result["data"]["blocks"] = [{"label": "nav", "error_codes": ["net::ERR_CERT_DATE_INVALID"]}]
+ assert _detect_non_retriable_nav_error(result) == _GENERIC_FAILURE_REASON
+
+
+ ("details", "expected_code"),
+ [
+ pytest.param(
+ {"nav_error_code": "net::ERR_TUNNEL_CONNECTION_FAILED"},
+ "net::ERR_TUNNEL_CONNECTION_FAILED",
+ id="the_driver_reported_a_code",
+ ),
+ pytest.param({"nav_error_code": None}, None, id="the_message_only_quotes_one"),
+ ],
+)
+def test_the_mcp_flattener_carries_only_a_code_the_driver_reported(
+ details: dict[str, object], expected_code: str | None
+) -> None:
+ """``mcp_to_copilot`` flattens the error to a sentence, so a code left only in that message is
+ lost and any reader of it is reading prose."""
+ flattened = mcp_to_copilot(
+ {
+ "ok": False,
+ "error": {
+ "code": "ACTION_FAILED",
+ "message": "Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/",
+ "hint": "Check that the URL is valid and accessible",
+ "details": details,
+ },
+ }
+ )
+
+ assert flattened.get("nav_error_code") == expected_code
+ # Absent rather than present-and-empty: a reader that tests the key must not see one.
+ assert ("nav_error_code" in flattened) is (expected_code is not None)
+ assert proxy_owns_nav_codes([flattened.get("nav_error_code")]) is (expected_code is not None)
+
+
+ ("block", "expected_codes"),
+ [
+ pytest.param(
+ {"error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"]},
+ ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ id="the_driver_reported_it",
+ ),
+ pytest.param(
+ {
+ "label": "extract",
+ "failure_reason": "The catalogue page did not list a price.",
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ "output": {
+ "status": "failed",
+ "failure_reason": "The catalogue page did not list a price.",
+ "failure_category": [{"category": "user_defined"}],
+ "declared_error_code": "net::ERR_TUNNEL_CONNECTION_FAILED",
+ },
+ },
+ [],
+ id="the_block_author_declared_it",
+ ),
+ pytest.param(
+ {
+ "label": "login",
+ "block_type": "TASK",
+ "failure_reason": _TASK_FAILURE_REASON_TUNNEL,
+ "error_codes": ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ # Every failed task carries a failure_category, so treating that as the mark of an
+ # authored code would discard the driver codes this change exists to carry.
+ "output": {
+ "status": "failed",
+ "failure_reason": _TASK_FAILURE_REASON_TUNNEL,
+ "failure_category": [{"category": "unknown"}],
+ },
+ },
+ ["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ id="a_failed_task_block_still_reports_its_driver_code",
+ ),
+ ],
+)
+def test_a_blocks_codes_exclude_only_the_one_its_author_declared(
+ block: dict[str, object], expected_codes: list[str]
+) -> None:
+ result = {"ok": False, "data": {"blocks": [block]}}
+
+ assert block_nav_error_codes(result) == expected_codes
+ assert proxy_owns_nav_codes(block_nav_error_codes(result)) is bool(expected_codes)
+
+
+async def test_a_torn_down_run_still_reports_the_navigation_failure() -> None:
+ """The run's secrets are what clear a code for reporting, and they are read inside the failure
+ handler -- so a run torn down while the block awaited must degrade to reporting the failure
+ without the code, never to raising in place of the failure it was handling."""
+ block = block_module.TaskBlock(
+ label="open", output_parameter=_output_parameter(), title="open", url="https://x.test/"
+ )
+ navigation_failure = FailedToNavigateToUrl(
+ url="https://x.test/",
+ error_message="Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/",
+ nav_error_code="net::ERR_TUNNEL_CONNECTION_FAILED",
+ )
+
+ # The run is alive when the block starts and gone by the time it fails. Recorded output is what
+ # sends the handler past _invalidate_stale_output_on_failure, whose own context read would
+ # otherwise raise first and hide which guard is under test.
+ async def fail_after_recording_output(self: block_module.Block, *args: object, **kwargs: object) -> None:
+ self._output_recorded_this_execution = True
+ raise navigation_failure
+
+ live_context = mock.MagicMock(secrets={})
+ live_context.cancel_failure_evidence_capture = AsyncMock()
+ reads: list[str] = []
+
+ def read_run_context(workflow_run_id: str) -> object:
+ reads.append(workflow_run_id)
+ if len(reads) > 1:
+ raise WorkflowRunContextNotInitialized(workflow_run_id)
+ return live_context
+
+ with (
+ mock.patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ mock.patch.object(block_module.BaseTaskBlock, "execute", fail_after_recording_output),
+ mock.patch.object(block_module.Block, "_generate_workflow_run_block_description", new_callable=AsyncMock),
+ ):
+ mock_app.DATABASE.observer.create_workflow_run_block = AsyncMock(return_value=mock.MagicMock())
+ mock_app.DATABASE.observer.update_workflow_run_block = AsyncMock()
+ mock_app.DATABASE.workflow_runs.admit_workflow_run_block_dispatch = admit_block_dispatch()
+ mock_app.BROWSER_MANAGER.get_for_workflow_run.return_value = None
+ mock_app.WORKFLOW_CONTEXT_MANAGER.artifact_redaction_enabled = lambda *_a, **_k: False
+ mock_app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context.side_effect = read_run_context
+
+ result = await block.execute_safe(workflow_run_id="wr_test", current_index=None)
+
+ assert result.success is False
+ assert result.status == block_module.BlockStatus.failed
+ assert "x.test" in (result.failure_reason or "")
+ assert "net::ERR_TUNNEL_CONNECTION_FAILED" not in (result.error_codes or [])
+ assert len(reads) > 1
+
+
+def test_a_parameter_walk_that_runs_out_leaves_every_code_to_the_mask(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Preservation asks whether a code is one of the run's parameter values. A walk that hits its cap
+ cannot answer that, and a partial answer would keep a code the mask was right to remove."""
+ deep: dict[str, object] = {"leaf": "net::ERR_TUNNEL_CONNECTION_FAILED"}
+ for _ in range(block_module._PARAMETER_STRING_WALK_LIMIT):
+ deep = {"next": deep}
+
+ def redact(value: object, parameters: dict[str, object]) -> object:
+ if isinstance(value, list):
+ return ["[redacted]" for _ in value]
+ return value
+
+ monkeypatch.setattr(block_module.app.AGENT_FUNCTION, "redact_codeblock_parameter_values", redact)
+ result = block_module.BlockResult(
+ success=False,
+ failure_reason="Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED",
+ error_codes=["net::ERR_TUNNEL_CONNECTION_FAILED"],
+ status=block_module.BlockStatus.failed,
+ output_parameter=_output_parameter(),
+ workflow_run_block_id="wrb_test",
+ )
+
+ assert block_module.parameter_strings({"deep": deep}) is None
+ assert block_module._redact_codeblock_result(result, {"deep": deep}).error_codes == ["[redacted]"]
+
+
+def test_a_host_with_no_address_record_is_not_answered_with_contact_support() -> None:
+ """UnresolvableNavigationHost carries its own typed code (exceptions.py), never derived from
+ the reason text: the driver's borrowed tunnel code never reaches error_codes for this case."""
+ _, result = _record_and_render_terminal_reply(
+ _NO_ADDRESS_RECORD_FAILURE_REASON,
+ block_type="navigation",
+ codes=[NO_ADDRESS_RECORD_NAV_ERROR_CODE],
+ )
+
+ assert result.user_response == _NO_ADDRESS_RECORD_REPLY.format(reason=_NO_ADDRESS_RECORD_FAILURE_REASON)
+ assert "Skyvern Support" not in result.user_response
+ assert result.turn_outcome is not None
+ assert result.turn_outcome.terminal_reason == "non_retriable_nav"
+
+
+def test_the_no_address_record_marker_alone_cannot_mint_a_terminal_stop() -> None:
+ """A page or model quoting the marker text, with no typed code behind it, must not stop the run."""
+ result = {"ok": False, "data": {"blocks": [{"failure_reason": _NO_ADDRESS_RECORD_FAILURE_REASON}]}}
+ assert _detect_non_retriable_nav_error(result) is None
diff --git a/tests/unit/test_navigation_action_handlers.py b/tests/unit/test_navigation_action_handlers.py
index 3db435bc0..73771b851 100644
--- a/tests/unit/test_navigation_action_handlers.py
+++ b/tests/unit/test_navigation_action_handlers.py
@@ -1,12 +1,17 @@
"""Tests for the GOTO_URL / RELOAD_PAGE action handlers."""
from types import SimpleNamespace
+from unittest import mock
from unittest.mock import AsyncMock, MagicMock, call
import pytest
+import skyvern.webeye.actions.handler as handler_module
+import skyvern.webeye.navigation as navigation_module
from skyvern.config import settings
from skyvern.exceptions import BlockedHost
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.webeye.actions import actions
from skyvern.webeye.actions.handler import handle_goto_url_action, handle_reload_page_action
from skyvern.webeye.actions.responses import ActionSuccess
@@ -99,3 +104,144 @@ async def test_goto_url_allows_a_public_redirect_chain(monkeypatch: pytest.Monke
"https://example.test/page",
timeout=settings.BROWSER_LOADING_TIMEOUT_MS,
)
+
+
+async def test_a_failed_goto_action_records_the_drivers_code(monkeypatch: pytest.MonkeyPatch) -> None:
+ """These actions call the driver directly, so their failure becomes an ActionFailure and never
+ reaches the typed navigation error. Without capturing here the code is gone by the time anything
+ decides who owned the failure, and an egress fault reads as a defect in the run.
+
+ The requested destination is excluded: it is chosen by whoever asked for the navigation, so a
+ code spelled inside it is not the browser's verdict.
+ """
+ planted = "https://x.test/net::ERR_TUNNEL_CONNECTION_FAILED"
+ monkeypatch.setattr(handler_module, "validate_fetch_url", lambda url: url)
+ # Corroboration does a real DNS lookup by default; this test is about destination exclusion, not
+ # about the .test fixture host resolving, so pin it to "has an address record".
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: False)
+ page = SimpleNamespace(
+ goto=AsyncMock(side_effect=RuntimeError(f"Page.goto: net::ERR_NAME_NOT_RESOLVED at {planted}"))
+ )
+ task = _task()
+ task.task_id = "tsk_nav"
+ context = SkyvernContext(run_id="wr_nav")
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ with pytest.raises(RuntimeError):
+ await handle_goto_url_action(actions.GotoUrlAction(url=planted), page, MagicMock(), task, MagicMock())
+
+ assert context.task_nav_error_codes == {"tsk_nav": "net::ERR_NAME_NOT_RESOLVED"}
+
+
+async def test_a_successful_retry_drops_the_earlier_navigation_code(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A retry that succeeds leaves the failure behind it.
+
+ Keeping the code would let a later failure of a different kind inherit it and be reported as a
+ network fault -- the same staleness the keyed carrier exists to avoid.
+ """
+ monkeypatch.setattr(handler_module, "validate_fetch_url", lambda url: url)
+ monkeypatch.setattr(handler_module, "revalidate_redirect_chain", AsyncMock())
+ task = _task()
+ task.task_id = "tsk_retry"
+ context = SkyvernContext(run_id="wr_retry")
+ context.task_nav_error_codes["tsk_retry"] = "net::ERR_NAME_NOT_RESOLVED"
+ page = SimpleNamespace(goto=AsyncMock(return_value=None))
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ await handle_goto_url_action(
+ actions.GotoUrlAction(url="https://x.test/ok"), page, MagicMock(), task, MagicMock()
+ )
+
+ assert context.task_nav_error_codes == {}
+
+
+async def test_a_failed_reload_records_the_drivers_code() -> None:
+ """Reload navigates too, and its failure becomes an ActionFailure like the others."""
+ task = _task()
+ task.task_id = "tsk_reload"
+ context = SkyvernContext(run_id="wr_reload")
+ page = SimpleNamespace(
+ url="https://x.test/catalogue",
+ reload=AsyncMock(side_effect=RuntimeError("Page.reload: net::ERR_CERT_DATE_INVALID")),
+ )
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ with pytest.raises(RuntimeError):
+ await handle_reload_page_action(actions.ReloadPageAction(), page, MagicMock(), task, MagicMock())
+
+ assert context.task_nav_error_codes == {"tsk_reload": "net::ERR_CERT_DATE_INVALID"}
+
+
+async def test_a_later_failure_without_a_code_is_not_judged_on_the_earlier_one(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A retry that fails differently still leaves the first attempt's verdict behind.
+
+ Clearing only on success is not enough: a timeout carries no net:: token, so the tunnel code
+ from the attempt before it would be attached to this failure and blamed on our egress.
+ """
+ monkeypatch.setattr(handler_module, "validate_fetch_url", lambda url: url)
+ task = _task()
+ task.task_id = "tsk_second"
+ context = SkyvernContext(run_id="wr_second")
+ context.task_nav_error_codes["tsk_second"] = "net::ERR_TUNNEL_CONNECTION_FAILED"
+ page = SimpleNamespace(goto=AsyncMock(side_effect=RuntimeError("Page.goto: Timeout 30000ms exceeded")))
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ with pytest.raises(RuntimeError):
+ await handle_goto_url_action(
+ actions.GotoUrlAction(url="https://x.test/slow"), page, MagicMock(), task, MagicMock()
+ )
+
+ assert context.task_nav_error_codes == {}
+
+
+async def test_a_later_action_retires_the_navigation_code(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A task can fail a navigation, keep going, and end on something else entirely.
+
+ The code describes the navigation that recorded it, so it must not be attached to whatever
+ failure the task finally reports -- an unrelated click failure blamed on our egress suppresses
+ repair of the block that actually broke.
+ """
+ task = _task()
+ task.task_id = "tsk_later"
+ context = SkyvernContext(run_id="wr_later")
+ context.task_nav_error_codes["tsk_later"] = "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+ monkeypatch.setattr(handler_module, "preflight_action", lambda *a, **k: None)
+ monkeypatch.setattr(handler_module.app.BROWSER_MANAGER, "get_for_task", MagicMock(return_value=None), raising=False)
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ await handler_module.ActionHandler.handle_action(
+ MagicMock(), task, MagicMock(order=1), MagicMock(), MagicMock()
+ )
+
+ assert context.task_nav_error_codes == {}
+
+
+async def test_terminating_after_a_failed_navigation_keeps_the_code(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Terminate and complete dispatch through handle_action like any other action.
+
+ They are how a task ends, so retiring the code on them erases it in exactly the case this change
+ exists for: the page would not load, so the agent gave up.
+ """
+ task = _task()
+ task.task_id = "tsk_terminate"
+ context = SkyvernContext(run_id="wr_terminate")
+ context.task_nav_error_codes["tsk_terminate"] = "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+ monkeypatch.setattr(handler_module, "preflight_action", lambda *a, **k: None)
+ monkeypatch.setattr(handler_module.app.BROWSER_MANAGER, "get_for_task", MagicMock(return_value=None), raising=False)
+ terminate = MagicMock()
+ terminate.action_type = handler_module.ActionType.TERMINATE
+
+ with mock.patch.object(skyvern_context, "current", return_value=context):
+ await handler_module.ActionHandler.handle_action(MagicMock(), task, MagicMock(order=2), MagicMock(), terminate)
+
+ assert context.task_nav_error_codes == {"tsk_terminate": "net::ERR_TUNNEL_CONNECTION_FAILED"}
diff --git a/tests/unit/test_tab_action_handlers.py b/tests/unit/test_tab_action_handlers.py
index 273549e71..45b77e44f 100644
--- a/tests/unit/test_tab_action_handlers.py
+++ b/tests/unit/test_tab_action_handlers.py
@@ -4,6 +4,9 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from skyvern.exceptions import FailedToNavigateToUrl
+from skyvern.forge.sdk.core import skyvern_context
+from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.webeye.actions import actions
from skyvern.webeye.actions.handler import (
handle_close_page_action,
@@ -58,17 +61,31 @@ async def test_new_tab_closes_tab_and_fails_when_navigation_fails() -> None:
new_page.close = AsyncMock()
browser_state = MagicMock()
browser_state.new_page = AsyncMock(return_value=new_page)
- browser_state.navigate_to_url = AsyncMock(side_effect=Exception("net::ERR_NAME_NOT_RESOLVED"))
+ # The browser state navigates through navigate_with_retry, which raises the typed error with the
+ # driver's code already read; its message leads with Skyvern's sentence, not the driver's.
+ browser_state.navigate_to_url = AsyncMock(
+ side_effect=FailedToNavigateToUrl(
+ url="https://does-not-exist.test",
+ error_message="Page.goto: net::ERR_NAME_NOT_RESOLVED at https://does-not-exist.test/",
+ nav_error_code="net::ERR_NAME_NOT_RESOLVED",
+ )
+ )
browser_state.set_active_page = AsyncMock()
action = actions.NewTabAction(url="https://does-not-exist.test")
+ task = _task()
+ task.task_id = "tsk_new_tab"
+ context = SkyvernContext(run_id="wr_new_tab")
with patch("skyvern.webeye.actions.handler.app", _mock_app(browser_state)):
- result = await handle_new_tab_action(action, MagicMock(), MagicMock(), _task(), MagicMock())
+ with patch.object(skyvern_context, "current", return_value=context):
+ result = await handle_new_tab_action(action, MagicMock(), MagicMock(), task, MagicMock())
assert isinstance(result[0], ActionFailure)
# The failed/blank tab must be closed so the next scrape doesn't fail the task.
new_page.close.assert_awaited_once()
browser_state.set_active_page.assert_not_awaited()
+ # Opening a tab navigates, so its failure carries the driver's verdict like any other.
+ assert context.task_nav_error_codes == {"tsk_new_tab": "net::ERR_NAME_NOT_RESOLVED"}
@pytest.mark.asyncio
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index fa6ab94f3..e0129abd1 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -731,6 +731,7 @@ def _install_db_fakes(
def _recording_page(exception: Exception | None, *, url: object = "http://example.test/home") -> MagicMock:
page = MagicMock()
page.last_recorded_exception = MagicMock(return_value=exception)
+ page.failure_nav_error_code = MagicMock(return_value=None)
page.url = url
return page
@@ -753,6 +754,7 @@ class FakeRecorder:
def __init__(self, **kwargs: Any) -> None:
self.recording_page = MagicMock()
self.recording_page.last_recorded_exception = MagicMock(return_value=self._next_last_exception)
+ self.recording_page.failure_nav_error_code = MagicMock(return_value=None)
self._actions: list[Any] = []
self.finalized_success: bool | None = None
self.__class__.instances.append(self)
@@ -1112,6 +1114,8 @@ async def test_inline_declared_error_without_download_keeps_typed_output(monkeyp
"reasoning": "report generation failed",
}
],
+ # Names the code as the author's own, so a reader can tell it from a driver's verdict.
+ "declared_error_code": "report_unavailable",
}
assert result.output_parameter_value == expected_output
assert "downloaded_files" not in result.output_parameter_value
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index 07c6041e2..37989562c 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -13,12 +13,16 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock, call
import pytest
-from playwright.async_api import BrowserContext, Locator, Page
+from playwright.async_api import BrowserContext
+from playwright.async_api import Error as PlaywrightError
+from playwright.async_api import Locator, Page
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from sqlalchemy import select
+import skyvern.webeye.navigation as navigation_module
from skyvern.constants import TEXT_PRESS_MAX_LENGTH
from skyvern.core.script_generations.skyvern_page import SkyvernPage
+from skyvern.exceptions import NO_ADDRESS_RECORD_NAV_ERROR_CODE, FailedToNavigateToUrl
from skyvern.forge import app
from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.copilot.code_block_steps import _METHOD_ACTION_TYPES
@@ -53,7 +57,13 @@ from skyvern.forge.sdk.workflow.models.credential_release import (
CodeBlockCredentialReleaseError,
CredentialReleaseGuard,
)
-from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter, OutputParameter, ParameterType
+from skyvern.forge.sdk.workflow.models.parameter import (
+ CredentialParameter,
+ OutputParameter,
+ ParameterType,
+ WorkflowParameter,
+ WorkflowParameterType,
+)
from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import (
@@ -236,6 +246,16 @@ async def _recorded_action_db() -> AsyncIterator[AgentDB]:
await db.engine.dispose()
[email protected](autouse=True)
+def target_host_resolves(monkeypatch: pytest.MonkeyPatch) -> None:
+ """These tests navigate to reserved .test hostnames, which genuinely have no address record.
+
+ Without this the resolver corroboration reads every fixture host as a dead target and drops the
+ code under test. Tests that are ABOUT that corroboration set the answer themselves.
+ """
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: False)
+
+
async def _record_timed_action() -> Action:
recorder = _Recorder()
@@ -2616,6 +2636,374 @@ async def test_execute_arms_the_guard_from_a_credential_parameter(monkeypatch: p
assert not any(call.startswith("fill:") for call in page.inner.calls)
+async def test_failure_nav_error_code_tracks_the_exception_that_navigated() -> None:
+ """Inline execution forwards authored navigation to raw Playwright, so the driver's own error
+ arrives instead of the typed one and the code has to come from the recorded call.
+
+ Bound to the exception, not the page: a later failure that never navigated must not inherit an
+ earlier navigation's code.
+ """
+ page = FakePage()
+ failure = PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/catalogue")
+ page.goto = AsyncMock(side_effect=failure) # type: ignore[method-assign]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.goto("https://x.test/catalogue")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ assert recording.failure_nav_error_code(PlaywrightError("unrelated")) is None
+
+
+async def test_block_code_cannot_reword_the_navigation_error_it_catches(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Block code holds the driver's exception before the block does, so the code it reports has to be
+ the one the navigation raised, not whatever the block re-raises."""
+ page = FakePage()
+ page.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/")) # type: ignore[method-assign]
+ _patch_execute_environment(monkeypatch, page, FakeWorkflowRunContext())
+ block = _make_code_block(
+ 'try:\n await page.goto("https://x.test/")\n'
+ 'except Exception as e:\n e.args = ("net::ERR_NAME_NOT_RESOLVED",)\n raise'
+ )
+
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is False
+ assert result.error_codes == ["net::ERR_TUNNEL_CONNECTION_FAILED"]
+
+
+ ("secret_value", "reported"),
+ [
+ # A secret occurring inside a code must not cut the verdict out of it.
+ pytest.param("net", ["net::ERR_TUNNEL_CONNECTION_FAILED"], id="a_secret_inside_the_code"),
+ # A secret that is the code would be stored on the block row and the output parameter.
+ pytest.param("net::ERR_TUNNEL_CONNECTION_FAILED", [], id="a_secret_that_is_the_code"),
+ ],
+)
+async def test_a_driver_code_that_is_a_registered_secret_is_not_persisted(
+ monkeypatch: pytest.MonkeyPatch, secret_value: str, reported: list[str]
+) -> None:
+ page = FakePage()
+ page.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/")) # type: ignore[method-assign]
+ context = FakeWorkflowRunContext()
+ context.secrets = {"site": secret_value}
+ _patch_execute_environment(monkeypatch, page, context)
+ block = _make_code_block('await page.goto("https://x.test/")')
+ block.parameters = [
+ WorkflowParameter(
+ workflow_parameter_type=WorkflowParameterType.STRING,
+ key="site",
+ workflow_parameter_id="wp_site",
+ workflow_id="w_test",
+ created_at=datetime.now(timezone.utc),
+ modified_at=datetime.now(timezone.utc),
+ )
+ ]
+
+ result = await block.execute(workflow_run_id="wr_test", workflow_run_block_id="wrb_test", organization_id="o_test")
+
+ assert result.success is False
+ assert result.error_codes == reported
+
+
+async def test_a_frame_navigation_records_its_destination() -> None:
+ """Inline code can navigate through page.main_frame or page.frames[n].
+
+ Those calls never reach the page proxy, so without recording them a frame navigation failure
+ carries no driver code: the proxy goes unattributed and a target failure loses its stop.
+ """
+ page = FakePage()
+ frame = SimpleNamespace(goto=AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED")))
+ page.main_frame = frame # type: ignore[attr-defined]
+ page.frames = [frame] # type: ignore[attr-defined]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.main_frame.goto("https://x.test/catalogue")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ # The same underlying frame reached either way is the same object, so code comparing the two
+ # accessors keeps working.
+ assert recording.frames[0] is recording.main_frame
+
+
+async def test_a_nested_frame_navigation_records_its_destination() -> None:
+ """A frame reached through another frame navigates the same way.
+
+ Stopping the wrapping at the frame the page handed out leaves
+ ``page.main_frame.child_frames[0].goto(...)`` calling a raw Frame, so its failure records no
+ destination: the proxy goes unattributed and a target failure loses its stop.
+ """
+ child = SimpleNamespace(goto=AsyncMock(side_effect=PlaywrightError("net::ERR_CERT_DATE_INVALID")), child_frames=[])
+ parent = SimpleNamespace(goto=AsyncMock(), child_frames=[child])
+ page = FakePage()
+ page.main_frame = parent # type: ignore[attr-defined]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.main_frame.child_frames[0].goto("https://x.test/deep")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_CERT_DATE_INVALID"
+ # The same underlying frame stays one object however it is reached.
+ assert recording.main_frame.child_frames[0] is recording.main_frame.child_frames[0]
+
+
+async def test_a_navigation_through_a_frames_owning_page_is_recorded() -> None:
+ """``page.main_frame.page`` hands back the page that owns the frame.
+
+ Forwarding the raw one lets a navigation through it skip the recorder entirely, which is the
+ hole this proxy exists to close.
+ """
+ page = FakePage()
+ page.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_NAME_NOT_RESOLVED")) # type: ignore[method-assign]
+ page.main_frame = SimpleNamespace(goto=AsyncMock(), child_frames=[], page=page) # type: ignore[attr-defined]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.main_frame.page.goto("https://x.test/owner")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_NAME_NOT_RESOLVED"
+
+
+async def test_a_page_reached_from_another_tab_is_the_same_proxy() -> None:
+ """Block code traverses back: ``(await page.context.new_page()).context.pages[0]`` is this page.
+
+ A second proxy for the same live page fails the identity comparisons authored code makes, and the
+ worker registers a second handle for a page it already holds.
+ """
+ page = FakePage()
+ other = FakePage()
+ page.context = SimpleNamespace(pages=[page, other])
+ other.context = page.context
+ recording = RecordingPage(page, strategy_aware_typing=True)
+
+ other_proxy = recording.context.pages[1]
+
+ assert other_proxy.context.pages[0] is recording
+ assert other_proxy.context.pages[1] is other_proxy
+ assert recording.context.pages[1] is other_proxy
+
+
+async def test_a_navigation_through_another_context_page_is_recorded() -> None:
+ """Another tab is still this block's page.
+
+ Forwarding ``page.context.pages`` raw lets a navigation through one skip the recorder, so its
+ failure reports no destination and the driver's code is refused.
+ """
+ page = FakePage()
+ other = FakePage()
+ other.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED")) # type: ignore[method-assign]
+ page.context = SimpleNamespace(pages=[page, other])
+ # The context proxy is what carries this; platform code reads the raw context off the page, so
+ # wrapping it unconditionally breaks download settling.
+ recording = RecordingPage(page, strategy_aware_typing=True)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.context.pages[1].goto("https://x.test/second-tab")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ # The page this proxy already wraps comes back as itself rather than a second proxy.
+ assert recording.context.pages[0] is recording
+
+
+async def test_a_frame_handed_back_by_a_call_is_recorded() -> None:
+ """``page.frame(name=...)`` returns a frame from a call rather than a property.
+
+ Wrapping only the properties leaves that frame raw, so navigating through it records no
+ destination and the driver's code is refused.
+ """
+
+ class Frame:
+ __module__ = "playwright.async_api"
+
+ def __init__(self) -> None:
+ self.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED"))
+ self.child_frames: list[object] = []
+
+ named = Frame()
+ page = FakePage()
+ page.frame = lambda **_kwargs: named # type: ignore[attr-defined]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.frame(name="checkout").goto("https://x.test/checkout")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+
+async def test_a_frame_from_a_second_tab_belongs_to_that_tab() -> None:
+ """The owning page of a wrapped frame decides what ``frame.page`` navigates.
+
+ Binding the wrapper to the page that created the recorder rather than the page the call was made
+ on sends ``frame.page.goto(...)`` to the wrong tab -- it navigates somewhere the author never
+ asked for, which is worse than losing attribution.
+ """
+
+ class Frame:
+ __module__ = "playwright.async_api"
+
+ def __init__(self) -> None:
+ self.child_frames: list[object] = []
+
+ first = FakePage()
+ second = FakePage()
+ second_frame = Frame()
+ second.frame = lambda **_kwargs: second_frame # type: ignore[attr-defined]
+ first.context = SimpleNamespace(pages=[first, second])
+ recording = RecordingPage(first, strategy_aware_typing=True)
+
+ second_proxy = recording.context.pages[1]
+ reached = second_proxy.frame(name="checkout")
+
+ assert reached.page is second_proxy
+ assert reached.page is not recording
+
+
+async def test_a_popup_page_from_an_event_wait_is_recorded() -> None:
+ """The supported popup flow awaits ``opened.value`` inside ``async with context.expect_page()``.
+
+ That page never passes through a call the proxy names, so leaving it raw means a navigation on
+ the popup skips the recorder: no destination, and the driver's code is refused.
+ """
+ popup = FakePage()
+ popup.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED")) # type: ignore[method-assign]
+
+ class EventInfo:
+ @property
+ def value(self): # noqa: ANN202 - mirrors Playwright's awaitable property
+ async def resolve(): # noqa: ANN202
+ return popup
+
+ return resolve()
+
+ class Expect:
+ async def __aenter__(self): # noqa: ANN204
+ return EventInfo()
+
+ async def __aexit__(self, *_exc): # noqa: ANN204
+ return False
+
+ page = FakePage()
+ page.context = SimpleNamespace(expect_page=lambda *a, **k: Expect())
+ recording = RecordingPage(page, strategy_aware_typing=True)
+
+ async with recording.context.expect_page() as opened:
+ opened_page = await opened.value
+
+ with pytest.raises(PlaywrightError) as caught:
+ await opened_page.goto("https://x.test/popup")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+
+async def test_a_popup_from_a_page_level_event_context_is_recorded() -> None:
+ """The canonical flow is ``async with page.expect_popup() as info``, alongside the context form.
+
+ The event context is neither a page nor a frame, so the result wrapper leaves it alone; without
+ handling it the popup arrives raw and its navigation skips the recorder.
+ """
+ popup = FakePage()
+ popup.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_CERT_DATE_INVALID")) # type: ignore[method-assign]
+
+ class EventInfo:
+ @property
+ def value(self): # noqa: ANN202 - mirrors Playwright's awaitable property
+ async def resolve(): # noqa: ANN202
+ return popup
+
+ return resolve()
+
+ class Expect:
+ async def __aenter__(self): # noqa: ANN204
+ return EventInfo()
+
+ async def __aexit__(self, *_exc): # noqa: ANN204
+ return False
+
+ page = FakePage()
+ page.expect_popup = lambda *a, **k: Expect() # type: ignore[attr-defined]
+ recording = RecordingPage(page)
+
+ async with recording.expect_popup() as info:
+ opened = await info.value
+
+ with pytest.raises(PlaywrightError) as caught:
+ await opened.goto("https://x.test/page-popup")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_CERT_DATE_INVALID"
+
+
+async def test_a_popup_from_a_context_expect_event_is_recorded() -> None:
+ """``context.expect_event("page")`` is the other spelling of the same popup wait."""
+
+ # Named Page because expect_event yields downloads and requests too, and only a page is wrapped.
+ class Page(FakePage):
+ pass
+
+ popup = Page()
+ popup.goto = AsyncMock(side_effect=PlaywrightError("net::ERR_SOCKS_CONNECTION_FAILED")) # type: ignore[method-assign]
+
+ class EventInfo:
+ @property
+ def value(self): # noqa: ANN202 - mirrors Playwright's awaitable property
+ async def resolve(): # noqa: ANN202
+ return popup
+
+ return resolve()
+
+ class Expect:
+ async def __aenter__(self): # noqa: ANN204
+ return EventInfo()
+
+ async def __aexit__(self, *_exc): # noqa: ANN204
+ return False
+
+ page = FakePage()
+ page.context = SimpleNamespace(expect_event=lambda *a, **k: Expect())
+ recording = RecordingPage(page, strategy_aware_typing=True)
+
+ async with recording.context.expect_event("page") as info:
+ opened = await info.value
+
+ with pytest.raises(PlaywrightError) as caught:
+ await opened.goto("https://x.test/ctx-event")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_SOCKS_CONNECTION_FAILED"
+
+
+async def test_a_non_navigation_failure_records_no_destination() -> None:
+ """The destination is what gates reading a code out of the message at all.
+
+ Sandbox code is model-authored, so a block raising a string that spells a driver code must not
+ be read as a driver verdict. No destination recorded means the message is never scanned.
+ """
+ page = FakePage()
+ page.click = AsyncMock(side_effect=PlaywrightError("net::ERR_NAME_NOT_RESOLVED")) # type: ignore[method-assign]
+ recording = RecordingPage(page)
+
+ # A page-level call whose first argument is a string, so a gate keyed on anything weaker than
+ # "this was a navigation" would hand that selector back as the destination.
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.click("#submit")
+
+ assert recording.failure_nav_error_code(caught.value) is None
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("operation", ["click", "wait_for"])
async def test_failure_locator_tracks_exact_exception_without_reparsing_selector(operation: str) -> None:
@@ -2710,3 +3098,78 @@ async def test_later_page_operation_invalidates_an_inflight_failure_locator():
with pytest.raises(PlaywrightTimeoutError):
await pending
assert recording.failure_locator(failure) is None
+
+
+ ("host_is_dead", "reported"),
+ [
+ # A browser behind a proxy hands the hostname to the proxy, so a target whose address record
+ # is gone comes back as the proxy failing to open a tunnel. Reporting that code would blame
+ # our egress for a site that no longer exists; dropping it would cost the run its stop.
+ pytest.param(True, NO_ADDRESS_RECORD_NAV_ERROR_CODE, id="a_target_with_no_address_record"),
+ pytest.param(False, "net::ERR_TUNNEL_CONNECTION_FAILED", id="a_target_that_resolves"),
+ ],
+)
+async def test_a_code_block_navigation_reports_a_proxy_code_only_for_a_live_target(
+ monkeypatch: pytest.MonkeyPatch, host_is_dead: bool, reported: str | None
+) -> None:
+ """A code block navigates the raw driver, so it never reaches the resolver corroboration in
+ navigate_with_retry; the code it records has to carry that corroboration itself."""
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: host_is_dead)
+ page = FakePage()
+ failure = PlaywrightError("net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/catalogue")
+ page.goto = AsyncMock(side_effect=failure) # type: ignore[method-assign]
+ recording = RecordingPage(page)
+
+ with pytest.raises(PlaywrightError) as caught:
+ await recording.goto("https://x.test/catalogue")
+
+ assert recording.failure_nav_error_code(caught.value) == reported
+
+
+async def test_a_dead_target_still_reports_a_code_the_driver_typed(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The corroboration answers only for a raw driver error. A typed navigation failure already
+ carries the verdict of the layer that raised it, and re-deciding it here would discard one."""
+ monkeypatch.setattr(navigation_module, "host_has_no_address_record", lambda host: True)
+ page = FakePage()
+ failure = FailedToNavigateToUrl(
+ url="https://x.test/catalogue",
+ error_message="Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED",
+ nav_error_code="net::ERR_TUNNEL_CONNECTION_FAILED",
+ )
+ page.goto = AsyncMock(side_effect=failure) # type: ignore[method-assign]
+ recording = RecordingPage(page)
+
+ with pytest.raises(FailedToNavigateToUrl) as caught:
+ await recording.goto("https://x.test/catalogue")
+
+ assert recording.failure_nav_error_code(caught.value) == "net::ERR_TUNNEL_CONNECTION_FAILED"
+
+
+async def test_a_cancelled_run_is_not_reported_as_a_navigation_verdict(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The corroboration awaits a resolver lookup, so a run cancelled mid-lookup unwinds through it.
+
+ Swallowing that would answer with a code and let the cancelled work carry on; a resolver that
+ simply fails still has to cost only the corroboration.
+ """
+
+ async def cancelled(url: str, message: str) -> str | None:
+ raise asyncio.CancelledError()
+
+ async def unavailable(url: str, message: str) -> str | None:
+ raise RuntimeError("resolver unavailable")
+
+ failure = PlaywrightError("Page.goto: net::ERR_TUNNEL_CONNECTION_FAILED at https://x.test/")
+
+ monkeypatch.setattr(navigation_module, "_unresolvable_navigation_host", cancelled)
+ with pytest.raises(asyncio.CancelledError):
+ await navigation_module.reported_nav_error_code(failure, "https://x.test/")
+
+ monkeypatch.setattr(navigation_module, "_unresolvable_navigation_host", unavailable)
+ assert (
+ await navigation_module.reported_nav_error_code(failure, "https://x.test/")
+ == "net::ERR_TUNNEL_CONNECTION_FAILED"
+ )