Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-11300): require a typed challenge-evidence carrier to assert any anti-bot category (#7271)
Andrew Neilsond18286807310
diff --git a/skyvern/forge/failure_classifier.py b/skyvern/forge/failure_classifier.pyindex 922be3e06..3f92d7b30 100644--- a/skyvern/forge/failure_classifier.py+++ b/skyvern/forge/failure_classifier.py@@ -68,6 +68,9 @@ def classify_from_failure_reason("category": "ANTI_BOT_DETECTION","confidence_float": 0.7,"reasoning": "Keywords matched in failure reason",+ # Provenance marker: a keyword match is not positive challenge+ # evidence, so evidence-gated consumers must not assert on it.+ "evidence_source": "keyword_only",})diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.pyindex 9c9737c61..e63e76bbe 100644--- a/skyvern/forge/sdk/copilot/build_test_outcome.py+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py@@ -12,6 +12,7 @@ import structlogimport yamlfrom pydantic import BaseModel, ConfigDict, Field+from skyvern.forge.sdk.copilot.challenge_evidence import carrier_backed_anti_bot_categoriesfrom skyvern.forge.sdk.copilot.code_block_preflight import SANDBOX_UNRESOLVED_NAME_REASON_CODEfrom skyvern.forge.sdk.copilot.completion_verification import (CompletionVerificationResult,@@ -1040,7 +1041,7 @@ def recorded_outcome_from_run_blocks_result()run_status = _safe_str(data.get("overall_status"))failure_type = _safe_str(data.get("failure_type"))- failure_categories = _failure_category_refs(data.get("failure_categories"))+ failure_categories = _failure_category_refs(carrier_backed_anti_bot_categories(data.get("failure_categories")))status = _safe_str(failed_block.get("status")) if failed_block is not None else run_statusruntime_failure_identity = _runtime_failure_identity(failed_block)if referenced_unbound_keys:diff --git a/skyvern/forge/sdk/copilot/challenge_evidence.py b/skyvern/forge/sdk/copilot/challenge_evidence.pynew file mode 100644index 000000000..7222bf3fc--- /dev/null+++ b/skyvern/forge/sdk/copilot/challenge_evidence.py@@ -0,0 +1,244 @@+"""Typed positive-evidence carrier required to assert any anti-bot challenge+category; keyword hits in prose, HTML haystacks, action traces, or code-block+values are not carriers, and a category without one is untrusted."""++from __future__ import annotations++from collections.abc import Mapping+from enum import StrEnum+from typing import Any++import structlog++LOG = structlog.get_logger()+++class ChallengeEvidenceSource(StrEnum):+ CHALLENGE_STATE = "challenge_state"+ VISION = "vision"+ ARTIFACT = "artifact"+ KEYWORD_ONLY = "keyword_only"+++CHALLENGE_EVIDENCE_SOURCE_KEY = "evidence_source"+CARRIER_CHALLENGE_EVIDENCE_SOURCES: frozenset[ChallengeEvidenceSource] = frozenset(+ {+ ChallengeEvidenceSource.CHALLENGE_STATE,+ ChallengeEvidenceSource.VISION,+ ChallengeEvidenceSource.ARTIFACT,+ }+)++ANTI_BOT_CHALLENGE_ALIAS_CATEGORIES: frozenset[str] = frozenset(+ {+ "ANTI_BOT_CHALLENGE",+ "ANTI_BOT_DETECTION",+ "CHALLENGE_DETECTION",+ "HUMAN_VERIFICATION_CHALLENGE",+ }+)++# The vision classifier's typed non-challenge obstruction kind: a consent dialog+# is dismissed, not solved, so it must never promote challenge state.+CONSENT_OBSTRUCTION_KIND = "cookie_consent"++# Tags that carry challenge-vendor markup without rendering a widget. A passive+# script/meta tag ships on every page behind some CDNs, so it can trigger the+# visual fallback but never assert human verification by itself.+_PASSIVE_CHALLENGE_TAGS: frozenset[str] = frozenset({"script", "noscript", "style", "link", "meta"})++# Exact-match boolean flag keys in run artifacts that count as a typed challenge+# marker; substring key matches and status-string values never do.+ANTI_BOT_ARTIFACT_FLAG_KEYS: frozenset[str] = frozenset(+ {+ "anti_bot",+ "anti_bot_blocked",+ "anti_bot_detected",+ "blocked_by_captcha",+ "blocked_by_challenge",+ "bot_blocked",+ "bot_detected",+ "bot_detection",+ "captcha",+ "captcha_blocked",+ "captcha_detected",+ "captcha_present",+ "captcha_required",+ "challenge",+ "challenge_blocked",+ "challenge_detected",+ "challenge_present",+ "challenge_required",+ "human_verification",+ "human_verification_blocked",+ "human_verification_detected",+ "human_verification_required",+ }+)+# Exact-match enumerated marker values (whole normalized string, never a+# substring): the same markers when an artifact encodes them as an identifier+# value instead of a boolean flag. Single bare tokens and generic values like+# "blocked" or "challenge" never match as values.+ANTI_BOT_ARTIFACT_MARKER_VALUES: frozenset[str] = frozenset(+ {+ "anti_bot_blocked",+ "anti_bot_detected",+ "blocked_by_captcha",+ "blocked_by_challenge",+ "bot_blocked",+ "bot_detected",+ "browser_or_environment_port_block",+ "browser_port_forbidden",+ "captcha_blocked",+ "captcha_detected",+ "captcha_required",+ "challenge_blocked",+ "challenge_detected",+ "challenge_required",+ "human_verification_blocked",+ "human_verification_detected",+ "human_verification_required",+ }+)+_MAX_ARTIFACT_FLAG_DEPTH = 5+++def interactive_challenge_controls(challenge_controls: list[dict[str, Any]] | None) -> list[dict[str, Any]]:+ return [+ control+ for control in challenge_controls or []+ if isinstance(control, dict) and str(control.get("tag") or "").lower() not in _PASSIVE_CHALLENGE_TAGS+ ]+++def _category_name(entry: object) -> str:+ raw = entry.get("category") if isinstance(entry, Mapping) else entry+ return str(raw or "").strip().upper()+++def challenge_evidence_source_from_entry(entry: Mapping[str, Any]) -> ChallengeEvidenceSource | None:+ raw = entry.get(CHALLENGE_EVIDENCE_SOURCE_KEY)+ if not isinstance(raw, str):+ return None+ try:+ return ChallengeEvidenceSource(raw.strip().lower())+ except ValueError:+ return None+++def is_carrier_backed_category_entry(entry: object) -> bool:+ """True for every non-anti-bot category; anti-bot aliases require a carrier+ ``evidence_source`` and an absent or unknown value fails closed."""+ if _category_name(entry) not in ANTI_BOT_CHALLENGE_ALIAS_CATEGORIES:+ return True+ if not isinstance(entry, Mapping):+ return False+ return challenge_evidence_source_from_entry(entry) in CARRIER_CHALLENGE_EVIDENCE_SOURCES+++def carrier_backed_anti_bot_categories(value: object) -> list[Any]:+ """Drop anti-bot alias category entries that are not carrier-backed; every+ other entry passes through unchanged, preserving order."""+ if not isinstance(value, list):+ return []+ kept: list[Any] = []+ for entry in value:+ if is_carrier_backed_category_entry(entry):+ kept.append(entry)+ continue+ suppressed_source = challenge_evidence_source_from_entry(entry) if isinstance(entry, Mapping) else None+ LOG.info(+ "copilot anti-bot category keyword-only-suppressed",+ category=_category_name(entry),+ suppressed_evidence_source=suppressed_source.value if suppressed_source else "absent",+ )+ return kept+++def first_carrier_backed_anti_bot_source(value: object) -> ChallengeEvidenceSource | None:+ if not isinstance(value, list):+ return None+ for entry in value:+ if not isinstance(entry, Mapping) or _category_name(entry) not in ANTI_BOT_CHALLENGE_ALIAS_CATEGORIES:+ continue+ source = challenge_evidence_source_from_entry(entry)+ if source in CARRIER_CHALLENGE_EVIDENCE_SOURCES:+ return source+ return None+++def composition_challenge_carrier(evidence: Mapping[str, Any] | None) -> ChallengeEvidenceSource | None:+ """Carrier observed in composition page evidence: a rendered interactive+ challenge control, a stamped carrier on ``challenge_state``, or an asserted+ ``requires_human_verification``. Raw indicator hits alone return ``None``."""+ if not isinstance(evidence, Mapping):+ return None+ controls = evidence.get("challenge_controls")+ if isinstance(controls, list) and interactive_challenge_controls(controls):+ return ChallengeEvidenceSource.CHALLENGE_STATE+ challenge_state = evidence.get("challenge_state")+ if not isinstance(challenge_state, Mapping):+ return None+ stamped = challenge_evidence_source_from_entry(challenge_state)+ if stamped in CARRIER_CHALLENGE_EVIDENCE_SOURCES:+ return stamped+ # gates_submit_controls is only ever derived from rendered controls or a+ # vision confirmation, so it carries the same weight as either.+ if (+ challenge_state.get("requires_human_verification") is True+ or challenge_state.get("gates_submit_controls") is True+ ):+ return ChallengeEvidenceSource.CHALLENGE_STATE+ return None+++def vision_challenge_carrier(visual_summary: Mapping[str, Any] | None) -> bool:+ if not isinstance(visual_summary, Mapping) or visual_summary.get("challenge_detected") is not True:+ return False+ obstruction_kind = str(visual_summary.get("obstruction_kind") or "").strip().lower()+ return obstruction_kind != CONSENT_OBSTRUCTION_KIND+++def _normalized_flag_key(key: object) -> str:+ return str(key or "").strip().lower().replace("-", "_").replace(" ", "_")+++def artifact_challenge_flag_key(+ value: object,+ *,+ declared_keys: frozenset[str] = frozenset(),+ depth: int = 0,+ match_marker_values: bool = True,+) -> str | None:+ """First exact-match anti-bot flag key with a ``True`` value in a run+ artifact, or ``None``. Declared goal-content keys are exempt. With+ ``match_marker_values`` off, only typed boolean flag keys count and enumerated+ string marker values are ignored — used when scanning the run envelope, whose+ string fields are prose/status (``failure_reason`` etc.), not a typed payload."""+ if depth > _MAX_ARTIFACT_FLAG_DEPTH:+ return None+ if isinstance(value, Mapping):+ for key, item in value.items():+ normalized = _normalized_flag_key(key)+ if normalized in declared_keys:+ continue+ if item is True and normalized in ANTI_BOT_ARTIFACT_FLAG_KEYS:+ return normalized+ if match_marker_values and isinstance(item, str):+ normalized_value = _normalized_flag_key(item)+ if normalized_value in ANTI_BOT_ARTIFACT_MARKER_VALUES:+ return normalized_value+ for item in value.values():+ found = artifact_challenge_flag_key(+ item, declared_keys=declared_keys, depth=depth + 1, match_marker_values=match_marker_values+ )+ if found:+ return found+ elif isinstance(value, (list, tuple)):+ for item in value:+ found = artifact_challenge_flag_key(+ item, declared_keys=declared_keys, depth=depth + 1, match_marker_values=match_marker_values+ )+ if found:+ return found+ return Nonediff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.pyindex a0d69b511..683037039 100644--- a/skyvern/forge/sdk/copilot/composition_evidence.py+++ b/skyvern/forge/sdk/copilot/composition_evidence.py@@ -16,6 +16,13 @@ except ImportError: # pragma: no cover - bs4 is a transitive dep but inspectionfrom skyvern.config import settingsfrom skyvern.forge.sdk.copilot.build_phase import BuildPhase+from skyvern.forge.sdk.copilot.challenge_evidence import (+ CHALLENGE_EVIDENCE_SOURCE_KEY,+ CONSENT_OBSTRUCTION_KIND,+ ChallengeEvidenceSource,+ interactive_challenge_controls,+ vision_challenge_carrier,+)from skyvern.forge.sdk.copilot.reached_download_target import (NAV_TARGET_DOWNLOAD_KIND_KEY,classify_download_affordance,@@ -127,20 +134,6 @@ def _challenge_kind(indicators: list[str]) -> str:return "unknown" if indicators else "none"-# Tags that carry challenge-vendor markup without rendering a widget. A passive-# script/meta tag ships on every page behind some CDNs, so it can trigger the-# visual fallback but never assert human verification by itself.-_PASSIVE_CHALLENGE_TAGS: frozenset[str] = frozenset({"script", "noscript", "style", "link", "meta"})---def interactive_challenge_controls(challenge_controls: list[dict[str, Any]] | None) -> list[dict[str, Any]]:- return [- control- for control in challenge_controls or []- if isinstance(control, dict) and str(control.get("tag") or "").lower() not in _PASSIVE_CHALLENGE_TAGS- ]--def _challenge_state(indicators: list[str],*,@@ -154,7 +147,7 @@ def _challenge_state(# asserting human verification requires a rendered challenge control or a# later vision confirmation.semantic_challenge = bool(interactive_challenge_controls(challenge_controls))- return {+ state = {"detected": detected,"kind": _challenge_kind(indicators),"source": source if detected else "",@@ -164,6 +157,9 @@ def _challenge_state("gates_submit_controls": bool(semantic_challenge and gated_controls),"gated_submit_controls": gated_controls[:5] if detected else [],}+ if semantic_challenge:+ state[CHALLENGE_EVIDENCE_SOURCE_KEY] = ChallengeEvidenceSource.CHALLENGE_STATE.value+ return statedef _control_disabled(node: Any) -> bool:@@ -260,11 +256,6 @@ def page_evidence_needs_visual_fallback(evidence: dict[str, Any]) -> bool:return bool(evidence.get("anti_bot_indicators") or evidence.get("challenge_controls"))-# The vision classifier's typed non-challenge obstruction kind: a consent dialog-# is dismissed, not solved, so it must never promote challenge state.-CONSENT_OBSTRUCTION_KIND = "cookie_consent"--def _confirmed_visual_challenge(evidence: dict[str, Any], visual_summary: dict[str, Any]) -> bool:if visual_summary.get("challenge_detected") is not True:return False@@ -313,6 +304,8 @@ def merge_visual_composition_evidence(omissions.append(bounded)challenge_state = dict(merged.get("challenge_state") or {})challenge_confirmed = _confirmed_visual_challenge(evidence, visual_summary)+ if vision_challenge_carrier(visual_summary):+ challenge_state.setdefault(CHALLENGE_EVIDENCE_SOURCE_KEY, ChallengeEvidenceSource.VISION.value)if challenge_confirmed:challenge_state["detected"] = Truechallenge_state["requires_human_verification"] = True@@ -1547,6 +1540,10 @@ def _challenge_controls(soup: Any) -> list[dict[str, Any]]:).lower()if not any(pattern in identity for pattern in _ANTI_BOT_PATTERNS):continue+ # A widget inside a hidden ancestor (solved/stale challenge markup) may+ # trigger the visual fallback but must not read as a rendered control.+ if _is_hidden_modal_candidate(node):+ continueselector = _selector_for(node)[:160]if selector in seen_selectors:continuediff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.pyindex e42536077..b42012cb0 100644--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Anyfrom pydantic import BaseModel, ConfigDict, Field, ValidationError+from skyvern.forge.sdk.copilot.challenge_evidence import carrier_backed_anti_bot_categoriesfrom skyvern.forge.sdk.copilot.completion_verification import (CompletionVerificationResult,only_structural_requested_output_abstentions,@@ -162,8 +163,9 @@ def build_diagnosis_repair_contract(run_ok = bool(result.get("ok", False))suspicious = run_ok and bool(getattr(ctx, "last_test_suspicious_success", False))failed_blocks = _failed_block_labels(blocks)- categories = _failure_categories(data)- terminal_challenge_categories = _trusted_terminal_challenge_categories(data)+ carrier_categories = carrier_backed_anti_bot_categories(data.get("failure_categories"))+ categories = _failure_categories(carrier_categories)+ terminal_challenge_categories = _trusted_terminal_challenge_categories(carrier_categories)run_status = _safe_str(data.get("overall_status"))workflow_run_id = _safe_str(data.get("workflow_run_id"))summary = _failure_summary(result, data, blocks)@@ -436,10 +438,7 @@ def _turn_intent_summary(ctx: Any) -> dict[str, Any]:return {}-def _failure_categories(data: dict[str, Any]) -> list[str]:- raw = data.get("failure_categories")- if not isinstance(raw, list):- return []+def _failure_categories(raw: list[Any]) -> list[str]:return list(dict.fromkeys(category@@ -451,10 +450,7 @@ def _failure_categories(data: dict[str, Any]) -> list[str]:)-def _trusted_terminal_challenge_categories(data: dict[str, Any]) -> list[str]:- raw = data.get("failure_categories")- if not isinstance(raw, list):- return []+def _trusted_terminal_challenge_categories(raw: list[Any]) -> list[str]:return list(dict.fromkeys(categorydiff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 1f306cb6e..aab5f4338 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -31,6 +31,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (author_time_reject_missing_output_paths,run_backed_repair_evidence_exists,)+from skyvern.forge.sdk.copilot.challenge_evidence import composition_challenge_carrierfrom skyvern.forge.sdk.copilot.code_block_synthesis import (is_durable_fallback_entry_target,is_generic_entry_opener_click,@@ -529,6 +530,7 @@ def _terminal_challenge_halt_signal(evidence_source: str,evidence_reason: str,blocked_tool: str = "update_and_run_blocks",+ challenge_evidence_source: str | None = None,) -> CopilotToolBlockerSignal:workflow_run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)safe_evidence_reason = (@@ -551,6 +553,7 @@ def _terminal_challenge_halt_signal(extra={"run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,"evidence_source": evidence_source,+ "challenge_evidence_source": challenge_evidence_source,"evidence_reason": safe_evidence_reason,"workflow_run_id": workflow_run_id if isinstance(workflow_run_id, str) else None,},@@ -567,11 +570,15 @@ def terminal_challenge_blocker_signal_from_page_evidence(page_reason = _structured_page_challenge_reason(ctx, evidence)if page_reason is None:return None+ carrier = composition_challenge_carrier(+ evidence if evidence is not None else getattr(ctx, "composition_page_evidence", None)+ )return _terminal_challenge_halt_signal(ctx,evidence_source=evidence_source,evidence_reason=page_reason,blocked_tool=blocked_tool,+ challenge_evidence_source=carrier.value if carrier else None,)@@ -630,7 +637,13 @@ def _maybe_stash_terminal_challenge_halt(ctx: Any) -> None:outcome = _typed_terminal_challenge_outcome(ctx)if outcome is not None:reason = outcome.display_reason or "Structured evidence reported a terminal site challenge."- signal = _terminal_challenge_halt_signal(ctx, evidence_source="run_outcome", evidence_reason=reason)+ carrier = composition_challenge_carrier(getattr(ctx, "composition_page_evidence", None))+ signal = _terminal_challenge_halt_signal(+ ctx,+ evidence_source="run_outcome",+ evidence_reason=reason,+ challenge_evidence_source=carrier.value if carrier else None,+ )stash_blocker_signal(ctx, signal)stash_turn_halt_from_blocker_signal(ctx, signal, source="enforcement")returndiff --git a/skyvern/forge/sdk/copilot/failure_tracking.py b/skyvern/forge/sdk/copilot/failure_tracking.pyindex 7aba3e4c5..c8ff093d3 100644--- a/skyvern/forge/sdk/copilot/failure_tracking.py+++ b/skyvern/forge/sdk/copilot/failure_tracking.py@@ -27,6 +27,11 @@ from collections.abc import Mapping, Sequencefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Any+from skyvern.forge.sdk.copilot.challenge_evidence import (+ ANTI_BOT_CHALLENGE_ALIAS_CATEGORIES,+ carrier_backed_anti_bot_categories,+)+if TYPE_CHECKING:from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResultfrom skyvern.forge.sdk.copilot.context import CopilotContext@@ -48,9 +53,7 @@ ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY = "ACTIVE_RUN_TERMINAL_EVIDENCE"ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE = "tool_error_active_run_terminal_evidence"_ROOT_CAUSE_CATEGORY_ALIASES = {- "ANTI_BOT_DETECTION": ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY,- "CHALLENGE_DETECTION": ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY,- "HUMAN_VERIFICATION_CHALLENGE": ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY,+ **{alias: ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY for alias in ANTI_BOT_CHALLENGE_ALIAS_CATEGORIES},# Self-mappings document categories whose noisy failure prose must not# affect repeat identity."PARAMETER_BINDING_ERROR": "PARAMETER_BINDING_ERROR",@@ -433,7 +436,7 @@ def update_repeated_failure_state(if isinstance(data, dict):raw_cats = data.get("failure_categories")if isinstance(raw_cats, list):- failure_categories = raw_cats+ failure_categories = carrier_backed_anti_bot_categories(raw_cats)suspicious_success_raw = getattr(ctx, "last_test_suspicious_success", False)suspicious_success = bool(suspicious_success_raw) if isinstance(suspicious_success_raw, (bool, int)) else Falsediff --git a/skyvern/forge/sdk/copilot/run_outcome.py b/skyvern/forge/sdk/copilot/run_outcome.pyindex 1287f4484..22bd60db3 100644--- a/skyvern/forge/sdk/copilot/run_outcome.py+++ b/skyvern/forge/sdk/copilot/run_outcome.py@@ -8,6 +8,7 @@ from collections.abc import Mappingfrom dataclasses import dataclassfrom typing import Any, Literal+from skyvern.forge.sdk.copilot.challenge_evidence import is_carrier_backed_category_entryfrom skyvern.forge.sdk.copilot.failure_tracking import ANTI_BOT_CHALLENGE_FAILURE_CATEGORIESfrom skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_promptfrom skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE, url_origin@@ -55,6 +56,8 @@ def trusted_terminal_challenge_category_name(entry: Mapping[str, Any]) -> str |category = entry.get("category")if not isinstance(category, str) or category not in TERMINAL_CHALLENGE_FAILURE_CATEGORIES:return None+ if not is_carrier_backed_category_entry(entry):+ return Noneconfidence = entry.get("confidence_float")if isinstance(confidence, (int, float)) and not isinstance(confidence, bool):numeric_confidence = float(confidence)diff --git a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py b/skyvern/forge/sdk/copilot/runtime_authoring_repair.pyindex 9de6e68ce..3d138007b 100644--- a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py+++ b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py@@ -5,6 +5,10 @@ from typing import Any, TypeGuardimport structlog+from skyvern.forge.sdk.copilot.challenge_evidence import (+ interactive_challenge_controls,+ is_carrier_backed_category_entry,+)from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schemafrom skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, normalize_block_authoring_policyfrom skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext@@ -207,8 +211,8 @@ def _post_run_terminal_page_evidence(evidence: dict[str, Any]) -> bool:indicators = evidence.get("anti_bot_indicators")has_indicators = isinstance(indicators, list) and any(isinstance(item, str) and item.strip() for item in indicators)controls = evidence.get("challenge_controls")- has_controls = isinstance(controls, list) and any(isinstance(item, dict) for item in controls)- return has_indicators and has_controls+ has_interactive_controls = isinstance(controls, list) and bool(interactive_challenge_controls(controls))+ return has_indicators and has_interactive_controlsdef _first_runtime_failed_block(data: dict[str, Any]) -> dict[str, Any] | None:@@ -349,7 +353,7 @@ def _result_has_terminal_or_ask_precedence(copilot_ctx: Any, data: dict[str, Any"UNRECOVERABLE_TOOL_ERROR",ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,"ANTI_BOT_DETECTION",- }:+ } and is_carrier_backed_category_entry(entry):return Trueif trusted_terminal_challenge_category_name(entry):return Truediff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.pyindex 162499c49..21d35d6a7 100644--- a/skyvern/forge/sdk/copilot/tools/blockers.py+++ b/skyvern/forge/sdk/copilot/tools/blockers.py@@ -21,6 +21,10 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (maybe_satisfy_recorded_outcome_grounding_requirement,recorded_outcome_grounding_requires_current_page,)+from skyvern.forge.sdk.copilot.challenge_evidence import (+ artifact_challenge_flag_key,+ is_carrier_backed_category_entry,+)from skyvern.forge.sdk.copilot.completion_verification import (structured_record_has_goal_content as _structured_record_candidate_has_goal_content,)@@ -1084,6 +1088,41 @@ def _run_blocks_structured_blocker_message(result: dict[str, Any], copilot_ctx:return None+def _artifact_challenge_flag_from_result(result: dict[str, Any], copilot_ctx: Any = None) -> str | None:+ """First typed anti-bot artifact marker in the run output, or ``None``. This is+ the artifact carrier; free-text scans are not. Only block outputs and registered+ output parameters are typed payloads, so their string marker values count; the+ run envelope's own string fields are prose/status (``failure_reason`` etc.) and+ are scanned for typed boolean flags only, never marker values."""+ data = result.get("data")+ if not isinstance(data, dict):+ return None+ flag = artifact_challenge_flag_key(+ {key: value for key, value in data.items() if key != "blocks"},+ match_marker_values=False,+ )+ if flag:+ return flag+ blocks = data.get("blocks")+ if isinstance(blocks, list):+ for block in blocks:+ if not isinstance(block, dict) or block.get("status") != "completed":+ continue+ declared_keys = (+ _declared_code_output_keys(copilot_ctx, block.get("label"))+ if _is_code_block_type(block.get("block_type"))+ else frozenset()+ )+ flag = artifact_challenge_flag_key(block.get("extracted_data"), declared_keys=declared_keys)+ if flag:+ return flag+ for registered in _registered_output_parameter_payloads(data):+ flag = artifact_challenge_flag_key(registered.get("value"))+ if flag:+ return flag+ return None++def _is_blocker_term_key(key: object, declared_keys: frozenset[str] = frozenset()) -> bool:normalized_key = _normalize_structured_key(key)if normalized_key in declared_keys:@@ -1856,7 +1895,13 @@ def _analyze_run_blocks(if categories:for cat in categories:if cat.get("category") == "ANTI_BOT_DETECTION":- anti_bot_match = cat.get("reasoning", "anti-bot pattern detected")+ if is_carrier_backed_category_entry(cat):+ anti_bot_match = cat.get("reasoning", "anti-bot pattern detected")+ else:+ LOG.info(+ "copilot anti-bot classifier match keyword-only-suppressed",+ workflow_run_id=data.get("workflow_run_id"),+ )breakif complete_structured_record_output:diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.pyindex a5c9f5a68..4daf0a6e4 100644--- a/skyvern/forge/sdk/copilot/tools/completion.py+++ b/skyvern/forge/sdk/copilot/tools/completion.py@@ -5,6 +5,7 @@ from typing import Any, Protocolimport structlogfrom skyvern.config import settings+from skyvern.forge.sdk.copilot.challenge_evidence import carrier_backed_anti_bot_categoriesfrom skyvern.forge.sdk.copilot.completion_criteria_store import note_adjudication_on_turn_statefrom skyvern.forge.sdk.copilot.completion_output_grounding import (grade_requested_output_criteria,@@ -74,7 +75,7 @@ from ._shared import (from .blockers import (_active_run_terminal_evidence_detected,_analyze_run_blocks,- _looks_like_anti_bot_blocker,+ _artifact_challenge_flag_from_result,_run_blocks_structured_blocker_message,)@@ -685,7 +686,7 @@ def _is_outcome_evidence_candidate(copilot_ctx: Any, result: dict[str, Any]) ->return Falsestructured_blocker = _run_blocks_structured_blocker_message(result, copilot_ctx)anti_bot, _empty_data_blocks, _categories = _analyze_run_blocks(result, copilot_ctx)- if structured_blocker and (anti_bot or _looks_like_anti_bot_blocker(structured_blocker)):+ if structured_blocker and (anti_bot or _artifact_challenge_flag_from_result(result, copilot_ctx)):return Falsereturn True@@ -709,13 +710,15 @@ def _is_unfinished_run_verification_candidate(copilot_ctx: Any, result: dict[strdef _failure_category_names(result: dict[str, Any]) -> list[str]:+ """Carrier-backed category names only: an uncorroborated anti-bot stamp must+ not count toward the artifact-health exclusion set."""data = result.get("data")data = data if isinstance(data, dict) else {}raw_categories = data.get("failure_categories")if not isinstance(raw_categories, list):return []categories: list[str] = []- for item in raw_categories:+ for item in carrier_backed_anti_bot_categories(raw_categories):if not isinstance(item, dict):continuecategory = item.get("category")diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex c05dd234f..64f1e8670 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -35,6 +35,12 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (recorded_outcome_from_run_blocks_result,run_backed_repair_evidence_exists,)+from skyvern.forge.sdk.copilot.challenge_evidence import (+ ChallengeEvidenceSource,+ carrier_backed_anti_bot_categories,+ composition_challenge_carrier,+ first_carrier_backed_anti_bot_source,+)from skyvern.forge.sdk.copilot.code_block_security import (COPILOT_CODE_SECURITY_FAILURE_CATEGORY,CodeBlockSecurityInput,@@ -154,6 +160,7 @@ from .blockers import (_active_run_terminal_evidence_detected,_active_run_terminal_evidence_signal,_analyze_run_blocks,+ _artifact_challenge_flag_from_result,_looks_like_anti_bot_blocker,_pending_reconciliation_requires_input_signal,_run_blocks_structured_blocker_message,@@ -2335,6 +2342,14 @@ def _composition_anti_bot_reason(copilot_ctx: object) -> str | None:challenge_detected = isinstance(challenge_state, dict) and challenge_state.get("detected") is Trueif not normalized_indicators and control_count == 0 and not challenge_detected:return None+ if composition_challenge_carrier(evidence) is None:+ LOG.info(+ "copilot anti-bot composition evidence keyword-only-suppressed",+ indicator_count=len(normalized_indicators),+ challenge_control_count=control_count,+ challenge_detected=challenge_detected,+ )+ return Nonedetail_parts = normalized_indicators[:4]if isinstance(challenge_state, dict):state_indicators = challenge_state.get("indicators")@@ -2366,6 +2381,7 @@ def _composition_anti_bot_reason(copilot_ctx: object) -> str | None:class TerminalChallengeEvidence:source: strreason: str+ challenge_evidence_source: strworkflow_run_id: str | None = Noneblock_labels: tuple[str, ...] = ()@@ -2383,7 +2399,7 @@ def _trusted_terminal_challenge_category_names(failure_categories: list[dict] |return tuple(dict.fromkeys(names))-def _ensure_terminal_challenge_category(data: dict[str, Any]) -> None:+def _ensure_terminal_challenge_category(data: dict[str, Any], *, challenge_evidence_source: str) -> None:categories = data.get("failure_categories")if not isinstance(categories, list):categories = []@@ -2396,6 +2412,7 @@ def _ensure_terminal_challenge_category(data: dict[str, Any]) -> None:"category": "ANTI_BOT_DETECTION","confidence_float": 0.9,"reasoning": "Structured challenge evidence reported a terminal blocker.",+ "evidence_source": challenge_evidence_source,},]data["failure_categories"] = categories@@ -2421,6 +2438,8 @@ def _terminal_challenge_evidence(failure_categories: list[dict] | None,structured_blocker: str | None,anti_bot_match: str | None = None,+ anti_bot_evidence_source: str | None = None,+ artifact_flag_key: str | None = None,) -> TerminalChallengeEvidence | None:data = result.get("data")result_data = data if isinstance(data, dict) else {}@@ -2428,29 +2447,37 @@ def _terminal_challenge_evidence(run_id = workflow_run_id if isinstance(workflow_run_id, str) and workflow_run_id.strip() else Noneblock_labels = _block_labels_from_result_data(result_data)challenge_categories = _trusted_terminal_challenge_category_names(failure_categories)+ corroborated_match = anti_bot_match if isinstance(anti_bot_evidence_source, str) else Noneif isinstance(structured_blocker, str) and (- _looks_like_anti_bot_blocker(structured_blocker) or isinstance(anti_bot_match, str)+ isinstance(artifact_flag_key, str) or isinstance(corroborated_match, str)):# Prefer the typed blocker payload over category fallback when both are# present because it carries the concrete page/run blocker text.reason = f"Run output reported a blocker: {structured_blocker}"if (- isinstance(anti_bot_match, str)- and anti_bot_match.strip()+ isinstance(corroborated_match, str)+ and corroborated_match.strip()and not _looks_like_anti_bot_blocker(structured_blocker)):- reason = f"{anti_bot_match}; {reason}"+ reason = f"{corroborated_match}; {reason}"return TerminalChallengeEvidence(source="structured_blocker",reason=reason,+ challenge_evidence_source=(+ ChallengeEvidenceSource.ARTIFACT.value if artifact_flag_key else str(anti_bot_evidence_source)+ ),workflow_run_id=run_id,block_labels=block_labels,)if challenge_categories:reason = next(iter_failure_reasons(result), None) or f"Run reported {challenge_categories[0]}"+ category_source = first_carrier_backed_anti_bot_source(failure_categories)return TerminalChallengeEvidence(source="failure_category",reason=reason,+ challenge_evidence_source=(+ category_source.value if category_source else ChallengeEvidenceSource.CHALLENGE_STATE.value+ ),workflow_run_id=run_id,block_labels=block_labels,)@@ -2710,6 +2737,9 @@ def _record_run_blocks_result(structured_blocker = _run_blocks_structured_blocker_message(result, copilot_ctx)anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result, copilot_ctx)+ artifact_flag_key = _artifact_challenge_flag_from_result(result, copilot_ctx)+ anti_bot_source = first_carrier_backed_anti_bot_source(failure_categories) if anti_bot_match else None+ anti_bot_evidence_source = anti_bot_source.value if anti_bot_source else Nonerecord_gate_decision(copilot_ctx,{@@ -2719,10 +2749,22 @@ def _record_run_blocks_result()if not anti_bot_match:anti_bot_match = _composition_anti_bot_reason(copilot_ctx)- if anti_bot_match:+ if anti_bot_match:+ composition_source = composition_challenge_carrier(copilot_ctx.composition_page_evidence)+ anti_bot_evidence_source = composition_source.value if composition_source else None+ if anti_bot_match and anti_bot_evidence_source:copilot_ctx.last_test_anti_bot = anti_bot_match+ LOG.info(+ "copilot anti-bot evidence stamp",+ anti_bot_evidence_source=anti_bot_evidence_source,+ stamp_seam="last_test_anti_bot",+ )+ elif anti_bot_match:+ LOG.info("copilot anti-bot latch keyword-only-suppressed")+ anti_bot_match = Noneif failure_categories:- top = failure_categories[0]+ carrier_categories = carrier_backed_anti_bot_categories(failure_categories)+ top = carrier_categories[0] if carrier_categories else Noneif isinstance(top, dict):top_category = top.get("category")if isinstance(top_category, str):@@ -2752,6 +2794,8 @@ def _record_run_blocks_result(failure_categories=failure_categories,structured_blocker=structured_blocker,anti_bot_match=anti_bot_match,+ anti_bot_evidence_source=anti_bot_evidence_source,+ artifact_flag_key=artifact_flag_key,)artifact_reason, artifact_labels, artifact_classes = _artifact_health_blocker_from_result(result)@@ -2792,8 +2836,15 @@ def _record_run_blocks_result(data = result.get("data")if isinstance(data, dict):data.setdefault("failure_reason", terminal_challenge.reason)- _ensure_terminal_challenge_category(data)+ _ensure_terminal_challenge_category(+ data, challenge_evidence_source=terminal_challenge.challenge_evidence_source+ )copilot_ctx.last_failure_category_top = "ANTI_BOT_DETECTION"+ LOG.info(+ "copilot anti-bot evidence stamp",+ anti_bot_evidence_source=terminal_challenge.challenge_evidence_source,+ stamp_seam="terminal_challenge",+ )copilot_ctx.last_test_ok = Falsecopilot_ctx.last_test_suspicious_success = Falsecopilot_ctx.last_test_failure_reason = terminal_challenge.reason@@ -3425,6 +3476,7 @@ def _terminal_challenge_blocker_signal(extra={"run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,"evidence_source": evidence.source,+ "challenge_evidence_source": evidence.challenge_evidence_source,"evidence_reason": safe_evidence_reason,"workflow_run_id": evidence.workflow_run_id,"block_labels": list(evidence.block_labels),@@ -3442,15 +3494,22 @@ def _diagnosis_repair_tool_error(copilot_ctx: Any, source_tool: str, error: str)reason = blocker_signal.extra.get("evidence_reason")if not isinstance(reason, str) or not reason.strip():reason = blocker_signal.user_facing_reason+ category: dict[str, Any] = {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.9,+ "reasoning": "Structured page challenge evidence reported a terminal blocker.",+ }+ carrier_source = blocker_signal.extra.get("challenge_evidence_source")+ if isinstance(carrier_source, str) and carrier_source:+ category["evidence_source"] = carrier_source+ LOG.info(+ "copilot anti-bot evidence stamp",+ anti_bot_evidence_source=carrier_source,+ stamp_seam="diagnosis_repair_tool_error",+ )result["data"] = {"failure_reason": reason,- "failure_categories": [- {- "category": "ANTI_BOT_DETECTION",- "confidence_float": 0.9,- "reasoning": "Structured page challenge evidence reported a terminal blocker.",- }- ],+ "failure_categories": [category],}record_consecutive_tool_result_boundary_for_ctx(copilot_ctx, source_tool, result)_record_diagnosis_repair_contract(copilot_ctx, source_tool=source_tool, result=result)diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.pyindex cb8760f4b..90d2366f6 100644--- a/tests/unit/test_copilot_build_test_outcome.py+++ b/tests/unit/test_copilot_build_test_outcome.py@@ -72,6 +72,46 @@ def test_run_blocks_outcome_records_requested_labels_and_shape_hashes() -> None:assert outcome.block_shape_hashes == {"open": "h1", "search": "h2", "extract": "h3"}+def _failed_run_result_with_categories(categories: list[dict]) -> dict:+ return {+ "ok": False,+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "failure_categories": categories,+ "blocks": [+ {"label": "search", "status": "failed", "failure_reason": "Timeout waiting for #results"},+ ],+ },+ }+++def test_structural_identity_ignores_keyword_only_anti_bot_categories() -> None:+ element_only = recorded_outcome_from_run_blocks_result(+ _failed_run_result_with_categories([{"category": "ELEMENT_NOT_FOUND", "confidence_float": 0.8}])+ )+ with_keyword_stamp = recorded_outcome_from_run_blocks_result(+ _failed_run_result_with_categories(+ [+ {"category": "ELEMENT_NOT_FOUND", "confidence_float": 0.8},+ {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.7, "evidence_source": "keyword_only"},+ ]+ )+ )+ with_carrier = recorded_outcome_from_run_blocks_result(+ _failed_run_result_with_categories(+ [+ {"category": "ELEMENT_NOT_FOUND", "confidence_float": 0.8},+ {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "evidence_source": "challenge_state"},+ ]+ )+ )++ assert element_only is not None and with_keyword_stamp is not None and with_carrier is not None+ assert with_keyword_stamp.structural_failure_identity == element_only.structural_failure_identity+ assert with_carrier.structural_failure_identity != element_only.structural_failure_identity++def test_structural_key_ignores_display_prose_and_workflow_run_id() -> None:first = RecordedBuildTestOutcome(phase="persisted_block_run",diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.pyindex edfd17018..db3f62732 100644--- a/tests/unit/test_copilot_completion_verification.py+++ b/tests/unit/test_copilot_completion_verification.py@@ -4389,6 +4389,49 @@ def test_artifact_health_skips_when_all_categories_are_excluded() -> None:assert failure_classes == []+def _syntax_error_result_with_anti_bot_category(evidence_source: str | None) -> dict:+ category = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9}+ if evidence_source is not None:+ category["evidence_source"] = evidence_source+ return {+ "ok": False,+ "data": {+ "workflow_run_id": "wr_failed_code",+ "overall_status": "failed",+ "failure_categories": [category],+ "blocks": [+ {+ "label": "extract_results",+ "block_type": "EXTRACTION",+ "status": "failed",+ "failure_reason": "Page.evaluate: SyntaxError: Unexpected token ')'",+ }+ ],+ },+ }+++def test_artifact_health_not_suppressed_by_keyword_only_anti_bot_category() -> None:+ result = _syntax_error_result_with_anti_bot_category("keyword_only")++ reason, failed_labels, failure_classes = _artifact_health_blocker_from_result(result)++ assert reason is not None+ assert "SyntaxError" in reason+ assert failed_labels == ["extract_results"]+ assert failure_classes == ["SyntaxError"]+++def test_artifact_health_skips_when_anti_bot_category_is_carrier_backed() -> None:+ result = _syntax_error_result_with_anti_bot_category("challenge_state")++ reason, failed_labels, failure_classes = _artifact_health_blocker_from_result(result)++ assert reason is None+ assert failed_labels == []+ assert failure_classes == []++def test_unfinished_run_verification_candidate_admits_canceled_with_evidence() -> None:ctx = _run_ctx()assert _is_unfinished_run_verification_candidate(ctx, _canceled_budget_result()) is True@@ -4649,7 +4692,9 @@ def test_terminal_challenge_contract_still_stops_when_outcome_fully_verified() -"data": {"workflow_run_id": "wr_blocked","overall_status": "failed",- "failure_categories": [{"category": "ANTI_BOT_DETECTION", "confidence_float": 1.0}],+ "failure_categories": [+ {"category": "ANTI_BOT_DETECTION", "confidence_float": 1.0, "evidence_source": "challenge_state"}+ ],},}diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.pyindex bd1d4691f..358497963 100644--- a/tests/unit/test_copilot_composition_evidence.py+++ b/tests/unit/test_copilot_composition_evidence.py@@ -15,6 +15,14 @@ import yamlfrom skyvern.config import settingsfrom skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.build_phase import BuildPhase+from skyvern.forge.sdk.copilot.challenge_evidence import (+ ChallengeEvidenceSource,+ artifact_challenge_flag_key,+ carrier_backed_anti_bot_categories,+ challenge_evidence_source_from_entry,+ composition_challenge_carrier,+ is_carrier_backed_category_entry,+)from skyvern.forge.sdk.copilot.composition_browser_expressions import (COMPOSITION_STRUCTURED_EVIDENCE_EXPRESSION,COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION,@@ -30,6 +38,8 @@ from skyvern.forge.sdk.copilot.composition_evidence import (parse_composition_html,parse_composition_structured,)+from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module+from skyvern.forge.sdk.copilot.tools.blockers import _artifact_challenge_flag_from_resultfrom skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentModefrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence@@ -617,6 +627,198 @@ def test_composition_parse_html_surfaces_human_verification_controls_after_long_]+def test_composition_parse_html_excludes_challenge_controls_inside_hidden_ancestors() -> None:+ parsed = parse_composition_html(+ """+ <html><head><title>Search</title></head><body>+ <div style="display: none;">+ <div id="turnstile-solved" class="cf-turnstile" data-sitekey="key-1"></div>+ </div>+ <div aria-hidden="true">+ <div id="challenge-stale" class="challenge-widget" data-callback="done"></div>+ </div>+ <div id="human-verification-widget" class="human-verification"></div>+ </body></html>+ """,+ inspected_url="https://example.com/search",+ current_url="https://example.com/search",+ )++ selectors = {control["selector"] for control in parsed["challenge_controls"]}+ assert "#human-verification-widget" in selectors+ assert "#turnstile-solved" not in selectors+ assert "#challenge-stale" not in selectors+ assert parsed["challenge_state"]["requires_human_verification"] is True+ assert parsed["challenge_state"]["evidence_source"] == "challenge_state"+ assert composition_challenge_carrier(parsed) == ChallengeEvidenceSource.CHALLENGE_STATE+++def test_composition_parse_html_passed_challenge_markup_escalates_without_assertion() -> None:+ parsed = parse_composition_html(+ """+ <html><head><title>Search</title></head><body>+ <div style="display:none">+ <div id="turnstile-solved" class="cf-turnstile" data-sitekey="key-1"></div>+ </div>+ <main>Verification passed. Search below.</main>+ <form><input name="q" /><input type="submit" value="Search" /></form>+ </body></html>+ """,+ inspected_url="https://example.com/search",+ current_url="https://example.com/search",+ )++ assert parsed["challenge_state"]["detected"] is True+ assert page_evidence_needs_visual_fallback(parsed) is True+ assert parsed["challenge_controls"] == []+ assert parsed["challenge_state"]["requires_human_verification"] is False+ assert "evidence_source" not in parsed["challenge_state"]+ assert composition_challenge_carrier(parsed) is None+ assert run_execution_module._composition_anti_bot_reason(SimpleNamespace(composition_page_evidence=parsed)) is None+++def test_composition_consent_modal_after_passed_check_reports_no_challenge() -> None:+ parsed = parse_composition_html(+ """+ <html><head><title>Order documents</title></head><body>+ <main>Bot check passed. Success! Continue to your order documents.</main>+ <div role="dialog" aria-modal="true" id="terms-modal">+ <p>Please accept the terms of service and privacy policy to continue.</p>+ <form id="continue-form">+ <input type="checkbox" id="accept-terms" name="accept_terms" />+ <input type="submit" id="btnContinue" value="Continue" disabled />+ </form>+ </div>+ </body></html>+ """,+ inspected_url="https://example.com/order-documents",+ current_url="https://example.com/order-documents",+ )++ assert parsed["anti_bot_indicators"] == []+ assert parsed["challenge_controls"] == []+ assert parsed["challenge_state"]["detected"] is False+ assert parsed["challenge_state"]["requires_human_verification"] is False+ assert composition_challenge_carrier(parsed) is None+ assert run_execution_module._composition_anti_bot_reason(SimpleNamespace(composition_page_evidence=parsed)) is None+++def test_merge_visual_consent_summary_never_stamps_vision_carrier() -> None:+ parsed = parse_composition_html(+ "<html><head><title>Just a moment...</title></head><body>Human verification</body></html>",+ inspected_url="https://example.com/search",+ current_url="https://example.com/search",+ )++ merged = merge_visual_composition_evidence(+ parsed,+ visual_summary={+ "summary": "A cookie consent dialog covers the page.",+ "challenge_detected": True,+ "obstruction_kind": "cookie_consent",+ },+ )++ assert merged["challenge_state"]["requires_human_verification"] is False+ assert "evidence_source" not in merged["challenge_state"]+ assert composition_challenge_carrier(merged) is None+++def test_merge_visual_challenge_summary_stamps_vision_carrier() -> None:+ parsed = parse_composition_html(+ "<html><head><title>Just a moment...</title></head><body>Human verification</body></html>",+ inspected_url="https://example.com/search",+ current_url="https://example.com/search",+ )++ merged = merge_visual_composition_evidence(+ parsed,+ visual_summary={+ "summary": "A verification card blocks the search form.",+ "challenge_detected": True,+ "obstruction_kind": "verification_panel",+ },+ )++ assert merged["challenge_state"]["requires_human_verification"] is True+ assert merged["challenge_state"]["evidence_source"] == "vision"+ assert composition_challenge_carrier(merged) == ChallengeEvidenceSource.VISION+++def test_merge_visual_consent_summary_with_visible_control_keeps_dom_carrier() -> None:+ parsed = parse_composition_html(+ """+ <html><head><title>Search</title></head><body>+ <div id="human-verification-widget" class="human-verification"></div>+ </body></html>+ """,+ inspected_url="https://example.com/search",+ current_url="https://example.com/search",+ )++ merged = merge_visual_composition_evidence(+ parsed,+ visual_summary={+ "summary": "A consent-looking dialog sits over a live challenge widget.",+ "challenge_detected": True,+ "obstruction_kind": "cookie_consent",+ },+ )++ assert merged["challenge_state"]["requires_human_verification"] is True+ assert merged["challenge_state"]["evidence_source"] == "challenge_state"+ assert composition_challenge_carrier(merged) == ChallengeEvidenceSource.CHALLENGE_STATE+++def test_challenge_evidence_carrier_wire_contract_fails_closed() -> None:+ carried = {"category": "ANTI_BOT_DETECTION", "evidence_source": "vision"}+ keyword = {"category": "CHALLENGE_DETECTION", "evidence_source": "keyword_only"}+ legacy = {"category": "HUMAN_VERIFICATION_CHALLENGE"}+ other = {"category": "PAGE_LOAD_TIMEOUT"}++ assert challenge_evidence_source_from_entry(carried) == ChallengeEvidenceSource.VISION+ assert is_carrier_backed_category_entry(carried) is True+ assert is_carrier_backed_category_entry(keyword) is False+ assert is_carrier_backed_category_entry(legacy) is False+ assert is_carrier_backed_category_entry(other) is True+ assert carrier_backed_anti_bot_categories([keyword, other, carried, legacy]) == [other, carried]+++def test_artifact_challenge_flag_requires_exact_typed_markers() -> None:+ assert artifact_challenge_flag_key({"captcha_detected": True}) == "captcha_detected"+ assert artifact_challenge_flag_key({"blocker": {"type": "browser_port_forbidden"}}) == "browser_port_forbidden"+ assert artifact_challenge_flag_key({"blocked": True}) is None+ assert artifact_challenge_flag_key({"status": "blocked"}) is None+ assert artifact_challenge_flag_key({"summary": "the captcha challenge blocked the search"}) is None+ assert (+ artifact_challenge_flag_key({"captcha_detected": True}, declared_keys=frozenset({"captcha_detected"})) is None+ )+++def test_artifact_challenge_flag_marker_values_off_ignores_string_markers() -> None:+ assert artifact_challenge_flag_key({"failure_reason": "blocked_by_challenge"}, match_marker_values=False) is None+ assert (+ artifact_challenge_flag_key({"blocker": {"type": "browser_port_forbidden"}}, match_marker_values=False) is None+ )+ # Typed boolean flags still count when marker-value matching is off.+ assert artifact_challenge_flag_key({"captcha_detected": True}, match_marker_values=False) == "captcha_detected"+++def test_artifact_carrier_ignores_run_envelope_prose_status_fields() -> None:+ # A prose/status envelope value must not be promoted as an artifact carrier.+ prose = {"data": {"failure_reason": "blocked_by_challenge", "overall_status": "challenge_detected"}}+ assert _artifact_challenge_flag_from_result(prose) is None+ # Typed block output still carries.+ typed = {+ "data": {+ "blocks": [+ {"status": "completed", "block_type": "extraction", "extracted_data": {"captcha_detected": True}}+ ]+ }+ }+ assert _artifact_challenge_flag_from_result(typed) == "captcha_detected"++def test_composition_gate_requires_page_evidence_before_page_dependent_blocks() -> None:goto_block = {"block_type": "goto_url", "label": "open_lookup", "url": "https://example.com/lookup"}search_block = {diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex 241d6ebeb..9d912e568 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -1867,7 +1867,7 @@ def test_unresolved_symbol_context_does_not_preempt_terminal_challenge_stop() ->"workflow_run_id": "wr_blocked","overall_status": "completed","failure_reason": ctx.last_test_failure_reason,- "failure_categories": [{"category": "ANTI_BOT_DETECTION"}],+ "failure_categories": [{"category": "ANTI_BOT_DETECTION", "evidence_source": "challenge_state"}],"blocks": [{"label": "extract",@@ -1967,7 +1967,7 @@ def test_terminal_challenge_preempts_clean_run_ok_contract_stops("workflow_run_id": run_id,"overall_status": "completed","failure_reason": failure_reason,- "failure_categories": [{"category": "ANTI_BOT_DETECTION"}],+ "failure_categories": [{"category": "ANTI_BOT_DETECTION", "evidence_source": "challenge_state"}],"blocks": [{"label": "extract",@@ -2003,7 +2003,7 @@ def test_terminal_challenge_preempts_failed_run_even_with_satisfied_completion_v"workflow_run_id": "wr_blocked_failed","overall_status": "failed","failure_reason": ctx.last_test_failure_reason,- "failure_categories": [{"category": "ANTI_BOT_DETECTION"}],+ "failure_categories": [{"category": "ANTI_BOT_DETECTION", "evidence_source": "challenge_state"}],"blocks": [{"label": "submit", "block_type": "NAVIGATION", "status": "failed"}],},},@@ -2018,6 +2018,33 @@ def test_terminal_challenge_preempts_failed_run_even_with_satisfied_completion_vassert contract.verification_result.remaining_blocker is not None+def test_keyword_only_challenge_category_never_reaches_contract() -> None:+ ctx = _ctx()++ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result={+ "ok": False,+ "error": "Run failed.",+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "failure_reason": "Timeout waiting for search results",+ "failure_categories": [+ {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.7, "evidence_source": "keyword_only"},+ ],+ "blocks": [{"label": "search", "block_type": "NAVIGATION", "status": "failed"}],+ },+ },+ ctx=ctx,+ )++ assert contract.diagnosis_result.suspected_failure_type != DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER+ assert "ANTI_BOT_DETECTION" not in contract.diagnosis_input.failure_categories+ assert contract.repair_decision.next_action != RepairNextAction.STOP+ assert "ANTI_BOT_CHALLENGE" not in contract.diagnosis_result.root_cause_identity.failure_categories++def test_low_confidence_challenge_category_does_not_preempt_clean_run_ok_contract() -> None:ctx = _ctx()@@ -2301,6 +2328,7 @@ def test_diagnosis_tool_error_preserves_terminal_challenge_blocker_category() ->extra={"run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,"evidence_source": "page_evidence",+ "challenge_evidence_source": "challenge_state","evidence_reason": "human verification requires human verification",},)@@ -2308,6 +2336,7 @@ def test_diagnosis_tool_error_preserves_terminal_challenge_blocker_category() ->payload = json.loads(_diagnosis_repair_tool_error(ctx, "update_and_run_blocks", "terminal challenge"))assert payload["data"]["failure_categories"][0]["category"] == "ANTI_BOT_DETECTION"+ assert payload["data"]["failure_categories"][0]["evidence_source"] == "challenge_state"assert ctx.latest_diagnosis_repair_contract is not Noneassert (ctx.latest_diagnosis_repair_contract.diagnosis_result.suspected_failure_typediff --git a/tests/unit/test_copilot_failure_tracking.py b/tests/unit/test_copilot_failure_tracking.pyindex 004f8a61f..40f382286 100644--- a/tests/unit/test_copilot_failure_tracking.py+++ b/tests/unit/test_copilot_failure_tracking.py@@ -137,6 +137,33 @@ def test_terminal_challenge_categories_follow_anti_bot_root_cause_aliases() -> Nassert TERMINAL_CHALLENGE_FAILURE_CATEGORIES == ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES+def test_update_state_ignores_keyword_only_anti_bot_categories_for_identity() -> None:+ wf = _make_workflow([_Block("open", url="https://a.test")])+ keyword_entry = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.7, "evidence_source": "keyword_only"}++ ctx_a = _make_ctx(failure_reason="Timeout waiting for #search", workflow=wf, executed_labels=["open"])+ update_repeated_failure_state(ctx_a, {"ok": False, "data": {"failure_categories": [dict(keyword_entry)]}})+ ctx_b = _make_ctx(failure_reason="ValueError: missing column 'name'", workflow=wf, executed_labels=["open"])+ update_repeated_failure_state(ctx_b, {"ok": False, "data": {"failure_categories": [dict(keyword_entry)]}})++ assert ctx_a.last_failure_signature is not None+ assert ctx_b.last_failure_signature is not None+ assert ctx_a.last_failure_signature != ctx_b.last_failure_signature+++def test_update_state_keeps_carrier_backed_anti_bot_category_identity() -> None:+ wf = _make_workflow([_Block("open", url="https://a.test")])+ carrier_entry = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "evidence_source": "challenge_state"}++ ctx_a = _make_ctx(failure_reason="Challenge page A blocked the run", workflow=wf, executed_labels=["open"])+ update_repeated_failure_state(ctx_a, {"ok": False, "data": {"failure_categories": [dict(carrier_entry)]}})+ ctx_b = _make_ctx(failure_reason="Different challenge prose on retry", workflow=wf, executed_labels=["open"])+ update_repeated_failure_state(ctx_b, {"ok": False, "data": {"failure_categories": [dict(carrier_entry)]}})++ assert ctx_a.last_failure_signature is not None+ assert ctx_a.last_failure_signature == ctx_b.last_failure_signature++def test_fingerprint_empty_without_workflow_definition() -> None:assert compute_frontier_fingerprint(["open"], None) == ""diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.pyindex cf68492f6..ca4b5d9b9 100644--- a/tests/unit/test_copilot_per_tool_budget.py+++ b/tests/unit/test_copilot_per_tool_budget.py@@ -426,7 +426,10 @@ def test_progress_reply_after_post_run_observation_still_gets_anti_bot_nudge() -ctx = _fresh_context()ctx.update_workflow_called = Truectx.test_after_update_done = True- ctx.composition_page_evidence = {"anti_bot_indicators": ["human-verification"]}+ ctx.composition_page_evidence = {+ "anti_bot_indicators": ["human-verification"],+ "challenge_controls": [{"tag": "div", "selector": "#human-verification-widget"}],+ }_record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))_record_composition_page_observation(ctx,@@ -967,10 +970,8 @@ def test_terminal_anti_bot_blocker_requires_gated_submit_evidence_for_disabled_fassert _last_run_has_terminal_anti_bot_blocker(ctx) is False-def test_record_run_blocks_treats_structured_anti_bot_blocker_as_terminal_challenge() -> None:- ctx = _fresh_context()- ctx.workflow_yaml = "workflow_definition: {blocks: []}"- result = {+def _prose_blocker_run_result() -> dict:+ return {"ok": True,"data": {"workflow_run_id": "wr_blocked",@@ -994,17 +995,40 @@ def test_record_run_blocks_treats_structured_anti_bot_blocker_as_terminal_challe},}++def test_record_run_blocks_keeps_prose_blocker_message_out_of_terminal_challenge() -> None:+ ctx = _fresh_context()+ ctx.workflow_yaml = "workflow_definition: {blocks: []}"+ result = _prose_blocker_run_result()++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_ok is False+ assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_anti_bot is None+ assert "Verify you are human" in ctx.last_test_failure_reason+ categories = result["data"]["failure_categories"]+ assert [category["category"] for category in categories] == ["PARAMETER_BINDING_ERROR"]+ assert ctx.last_failure_category_top == "PARAMETER_BINDING_ERROR"+ assert ctx.last_run_outcome is None or ctx.last_run_outcome.reason_code != "terminal_challenge_blocker"+++def test_record_run_blocks_treats_typed_anti_bot_flag_as_terminal_challenge() -> None:+ ctx = _fresh_context()+ ctx.workflow_yaml = "workflow_definition: {blocks: []}"+ result = _prose_blocker_run_result()+ result["data"]["blocks"][0]["extracted_data"]["extracted_information"]["human_verification_required"] = True+_record_run_blocks_result(ctx, result)assert ctx.last_test_ok is Falseassert ctx.last_test_suspicious_success is Falseassert ctx.last_test_anti_bot is not None- assert "Verify you are human" in ctx.last_test_failure_reasonassert ctx.last_failed_workflow_yaml == "workflow_definition: {blocks: []}"- assert result["data"]["failure_reason"] == "Run output reported a blocker: Verify you are human"categories = result["data"]["failure_categories"]assert categories[0]["category"] == "PARAMETER_BINDING_ERROR"assert categories[1]["category"] == "ANTI_BOT_DETECTION"+ assert categories[1]["evidence_source"] == "artifact"assert ctx.last_failure_category_top == "ANTI_BOT_DETECTION"assert ctx.last_run_outcome is not Noneassert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"@@ -1090,6 +1114,61 @@ def test_record_run_blocks_prefers_nested_port_blocker_over_status_shell() -> Noassert "Requested port" in ctx.turn_halt.extra["evidence_reason"]+def test_record_run_blocks_keyword_only_top_category_is_not_latched() -> None:+ ctx = _fresh_context()+ result = {+ "ok": False,+ "error": "run failed",+ "data": {+ "workflow_run_id": "wr_failed",+ "overall_status": "failed",+ "failure_reason": "Cloudflare interstitial was displayed while the page loaded.",+ "failure_categories": [+ {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.7, "evidence_source": "keyword_only"},+ {"category": "PAGE_LOAD_TIMEOUT", "confidence_float": 0.8},+ ],+ "blocks": [],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_failure_category_top == "PAGE_LOAD_TIMEOUT"+ assert ctx.last_test_anti_bot is None+ assert ctx.turn_halt is None+++def test_watchdog_cancel_with_stale_challenge_markup_is_not_promoted() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "anti_bot_indicators": ["turnstile"],+ "challenge_controls": [],+ "challenge_state": {+ "detected": True,+ "kind": "captcha",+ "requires_human_verification": False,+ "gates_submit_controls": False,+ },+ }+ result = {+ "ok": False,+ "error": "Run canceled after 90s of stagnation while a Cloudflare interstitial was displayed.",+ "data": {+ "workflow_run_id": "wr_cancelled",+ "overall_status": "canceled",+ "failure_reason": "Run canceled after stagnation.",+ "blocks": [],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_anti_bot is None+ assert ctx.last_failure_category_top != "ANTI_BOT_DETECTION"+ assert ctx.turn_halt is None+ assert ctx.blocker_signal is None++def test_record_run_blocks_combines_status_blocked_with_page_challenge_evidence() -> None:ctx = _fresh_context()ctx.composition_page_evidence = {diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pyindex 35baaf6c4..ef9d37e96 100644--- a/tests/unit/test_copilot_run_outcome_event.py+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -20,7 +20,11 @@ from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificafrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.enforcement import outcome_fully_verifiedfrom skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy-from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, run_outcome_display_reason+from skyvern.forge.sdk.copilot.run_outcome import (+ RecordedRunOutcome,+ run_outcome_display_reason,+ trusted_terminal_challenge_category_name,+)from skyvern.forge.sdk.copilot.tools import run_executionfrom skyvern.forge.sdk.copilot.tools.run_execution import (_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY,@@ -107,6 +111,7 @@ def _challenge_failure_result() -> dict[str, Any]:"category": "ANTI_BOT_DETECTION","confidence_float": 0.95,"reasoning": "Typed run analysis reported an anti-bot challenge.",+ "evidence_source": "challenge_state",}]result["data"]["blocks"] = [@@ -633,3 +638,13 @@ class TestGenuineAttemptRunStamp:assert ctx.last_test_ok is Noneassert ctx.last_run_blocks_workflow_run_id == "wr_test"assert ctx.has_genuine_workflow_attempt() is True+++def test_trusted_terminal_challenge_category_requires_carrier() -> None:+ carried = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "evidence_source": "artifact"}+ keyword = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "evidence_source": "keyword_only"}+ legacy = {"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9}++ assert trusted_terminal_challenge_category_name(carried) == "ANTI_BOT_DETECTION"+ assert trusted_terminal_challenge_category_name(keyword) is None+ assert trusted_terminal_challenge_category_name(legacy) is Nonediff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pyindex a8ba80b86..066e91e38 100644--- a/tests/unit/test_failure_classifier.py+++ b/tests/unit/test_failure_classifier.py@@ -171,6 +171,17 @@ def test_access_denied_with_auth_context_is_not_antibot() -> None:assert "ANTI_BOT_DETECTION" not in categories, reason+def test_antibot_category_is_marked_keyword_only() -> None:+ categories = classify_from_failure_reason("Cloudflare turnstile challenge blocked the page after a timeout")++ assert categories is not None+ antibot = next(category for category in categories if category["category"] == "ANTI_BOT_DETECTION")+ assert antibot["evidence_source"] == "keyword_only"+ assert all(+ "evidence_source" not in category for category in categories if category["category"] != "ANTI_BOT_DETECTION"+ )++def test_broad_blocked_and_forbidden_do_not_match_antibot() -> None:for reason in ["UI element blocked by overlay", "403 Forbidden from auth endpoint"]:result = classify_from_failure_reason(reason)