Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11181 hard halt on terminal challenge evidence (#6714)
Andrew Neilsona0f2c5d60e12
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.pyindex e829c2542..573fb70a5 100644--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Anyfrom pydantic import BaseModel, ConfigDict, Field+from skyvern.forge.sdk.copilot.composition_evidence import interactive_challenge_controlsfrom skyvern.forge.sdk.copilot.failure_tracking import (ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,RepairRootCauseIdentity,@@ -12,6 +13,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import ()from skyvern.forge.sdk.copilot.output_policy import url_originfrom skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt+from skyvern.forge.sdk.copilot.run_outcome import trusted_terminal_challenge_category_namefrom skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_REif TYPE_CHECKING:@@ -25,6 +27,7 @@ _FAILED_STATUSES = {"failed", "terminated", "canceled", "timed_out"}_CREDENTIAL_INPUT_MISSING_SKIP_REASONS = {"workflow_credential_inputs_unbound", "credential_name_unresolved"}_PRE_RUN_CREDENTIAL_FAILURE_CATEGORIES = {"CREDENTIAL_ERROR", "PARAMETER_BINDING_ERROR"}_REPAIRABLE_RUNTIME_CATEGORIES = {"AUTH_FAILURE", "OUTCOME_UNVERIFIED"}+_TERMINAL_ANTI_BOT_TERMS = ("captcha", "challenge", "verification", "anti-bot", "anti bot", "turnstile")class StrictModel(BaseModel):@@ -35,6 +38,7 @@ class DiagnosisFailureType(StrEnum):NO_FAILURE = "no_failure"FAILED_RUN = "failed_run"SUSPICIOUS_SUCCESS = "suspicious_success"+ TERMINAL_CHALLENGE_BLOCKER = "terminal_challenge_blocker"MISSING_CREDENTIAL_OR_INIT = "missing_credential_or_init"REPAIRABLE_BLOCK_FAILURE = "repairable_block_failure"ACTIVE_RUN_TERMINAL_EVIDENCE = "active_run_terminal_evidence"@@ -145,6 +149,7 @@ def build_diagnosis_repair_contract(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)run_status = _safe_str(data.get("overall_status"))workflow_run_id = _safe_str(data.get("workflow_run_id"))summary = _failure_summary(result, data, blocks)@@ -155,12 +160,25 @@ def build_diagnosis_repair_contract(blocks=[block for block in blocks if isinstance(block, dict)],detected_challenge=bool(getattr(ctx, "last_test_anti_bot", None)),)- failure_type = _failure_type(run_ok, suspicious, failed_blocks, categories, result, data)+ failure_type = _failure_type(+ run_ok,+ suspicious,+ failed_blocks,+ categories,+ terminal_challenge_categories,+ result,+ data,+ )next_action = _next_action(failure_type, ctx, data)frontier = _safe_str(data.get("frontier_start_label"))target_blocks = failed_blocks or ([frontier] if frontier else []) if next_action == RepairNextAction.REPAIR else []user_goal_satisfied, completion_contract_satisfied = _verification_satisfaction(- run_ok, suspicious, run_status, getattr(ctx, "completion_verification_result", None), data+ run_ok,+ suspicious,+ run_status,+ getattr(ctx, "completion_verification_result", None),+ data,+ failure_type,)confidence = (0.9@@ -183,6 +201,10 @@ def build_diagnosis_repair_contract(}.get(next_action, _safe_text(f"Repair the workflow based on: {summary}", _SUMMARY_MAX))if next_action == RepairNextAction.REPAIR and failure_type == DiagnosisFailureType.SUSPICIOUS_SUCCESS:decision_summary = "Repair the data-producing block so completion is proven by meaningful output."+ elif failure_type == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER:+ decision_summary = (+ "Stop retrying because structured evidence shows the workflow path is blocked by a site challenge."+ )elif failure_type == DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE:decision_summary = ("Stop the current retry loop: the active run reached the requested browser state, "@@ -308,6 +330,21 @@ 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 []+ return list(+ dict.fromkeys(+ category+ for entry in raw[:_MAX_ITEMS]+ if isinstance(entry, dict)+ for category in [trusted_terminal_challenge_category_name(entry)]+ if category+ )+ )++def _failed_block_labels(blocks: list[Any]) -> list[str]:return list(dict.fromkeys(@@ -334,12 +371,18 @@ def _failure_type(suspicious: bool,failed_blocks: list[str],categories: list[str],+ terminal_challenge_categories: list[str],result: dict[str, Any],data: dict[str, Any],) -> DiagnosisFailureType:skip_reason = _safe_str(data.get("skip_reason"))if skip_reason in _CREDENTIAL_INPUT_MISSING_SKIP_REASONS:return DiagnosisFailureType.MISSING_CREDENTIAL_OR_INIT+ # Trusted challenge categories win over a clean-looking run status because+ # verified challenge evidence means the apparent success is not usable.+ if terminal_challenge_categories:+ return DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER+ category_set = set(categories)if run_ok:return DiagnosisFailureType.SUSPICIOUS_SUCCESS if suspicious else DiagnosisFailureType.NO_FAILUREerror_text = " ".join(@@ -347,7 +390,6 @@ def _failure_type(for value in (result.get("error"), data.get("failure_reason"), data.get("skip_reason"))if value)- category_set = set(categories)if ("UNRECOVERABLE_TOOL_ERROR" in categoriesor "browser session not found" in error_text@@ -387,9 +429,11 @@ def _next_action(failure_type: DiagnosisFailureType, ctx: CopilotContext, data:return RepairNextAction.STOPif failure_type == DiagnosisFailureType.ACTIVE_RUN_TERMINAL_EVIDENCE:return RepairNextAction.STOP+ if failure_type == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER:+ return RepairNextAction.STOPif ctx.last_test_non_retriable_nav_error:return RepairNextAction.STOP- if getattr(ctx, "last_test_anti_bot", None) and failure_type in {+ if _last_test_anti_bot_is_terminal(ctx, data) and failure_type in {DiagnosisFailureType.FAILED_RUN,DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE,DiagnosisFailureType.SUSPICIOUS_SUCCESS,@@ -407,13 +451,49 @@ def _next_action(failure_type: DiagnosisFailureType, ctx: CopilotContext, data:return RepairNextAction.ESCALATE+def _last_test_anti_bot_is_terminal(ctx: CopilotContext, data: dict[str, Any]) -> bool:+ anti_bot_reason = getattr(ctx, "last_test_anti_bot", None)+ if not isinstance(anti_bot_reason, str) or not anti_bot_reason.strip():+ return False++ evidence = getattr(ctx, "composition_page_evidence", None)+ if isinstance(evidence, dict) and evidence.get("observed_after_workflow_run") is True:+ challenge_state = evidence.get("challenge_state")+ if isinstance(challenge_state, dict) and (+ challenge_state.get("requires_human_verification") is True+ or challenge_state.get("gates_submit_controls") is True+ ):+ return True+ controls = evidence.get("challenge_controls")+ if isinstance(controls, list) and interactive_challenge_controls(controls):+ return True++ failure_reason = getattr(ctx, "last_test_failure_reason", None)+ if not isinstance(failure_reason, str) or not failure_reason.strip():+ failure_reason = _safe_str(data.get("failure_reason"))+ reason_lower = anti_bot_reason.lower()+ failure_lower = str(failure_reason or "").lower()+ combined = f"{reason_lower} {failure_lower}"+ has_challenge_term = any(term in combined for term in _TERMINAL_ANTI_BOT_TERMS)+ if not has_challenge_term:+ return False+ if "challenge-gated disabled submit/search control" in reason_lower and "disabled" in failure_lower:+ return True+ return ("blocker" in combined or "blocked" in combined) and (+ "verify" in combined or "human" in combined or "captcha" in combined or "challenge" in combined+ )++def _verification_satisfaction(run_ok: bool,suspicious: bool,run_status: str | None,completion_verification: CompletionVerificationResult | None = None,data: dict[str, Any] | None = None,+ failure_type: DiagnosisFailureType | None = None,) -> tuple[bool | None, bool | None]:+ if failure_type == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER:+ return False, Falseif isinstance(data, dict) and data.get("active_run_terminal_evidence_detected") is True:trace = data.get("active_run_terminal_completion_verification")fully_satisfied = isinstance(trace, dict) and trace.get("fully_satisfied") is Truediff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex b1f61e9f8..88adcfee0 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -26,6 +26,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (render_synthesized_offer_text,synthesize_code_block,)+from skyvern.forge.sdk.copilot.composition_evidence import interactive_challenge_controlsfrom skyvern.forge.sdk.copilot.config import (DEFAULT_ENFORCEMENT_NUDGES,DEFAULT_TOKEN_BUDGET,@@ -67,6 +68,13 @@ from skyvern.forge.sdk.copilot.output_utils import (looks_like_workflow_delivery_claim,parse_final_response,)+from skyvern.forge.sdk.copilot.run_outcome import (+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ TERMINAL_CHALLENGE_USER_FACING_REASON,+ RecordedRunOutcome,+ run_outcome_display_reason,+)from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntryfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_spanfrom skyvern.forge.sdk.copilot.turn_halt import (@@ -302,6 +310,162 @@ def repair_ceiling_stop_signal()+def _typed_terminal_challenge_outcome(ctx: Any) -> RecordedRunOutcome | None:+ outcome = getattr(ctx, "last_run_outcome", None)+ if not isinstance(outcome, RecordedRunOutcome):+ return None+ if outcome.reason_code != TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE:+ return None+ return outcome+++def _structured_page_challenge_reason(ctx: Any, evidence: dict[str, Any] | None = None) -> str | None:+ if evidence is None:+ evidence = getattr(ctx, "composition_page_evidence", None)+ if not isinstance(evidence, dict):+ return None+ challenge_state = evidence.get("challenge_state")+ if isinstance(challenge_state, dict) and challenge_state.get("detected") is True:+ # This raw page kind is folded into an internal reason here; halt+ # metadata sanitizes it through run_outcome_display_reason below.+ kind = str(challenge_state.get("kind") or "site challenge").replace("_", " ")+ if challenge_state.get("requires_human_verification") is True:+ if "verification" in kind.lower() or "captcha" in kind.lower():+ return f"{kind} requires manual completion"+ return f"{kind} requires human verification"+ if challenge_state.get("gates_submit_controls") is True:+ return f"{kind} gates the submit/search controls"+ controls = evidence.get("challenge_controls")+ if isinstance(controls, list) and interactive_challenge_controls(controls):+ return "interactive challenge controls are visible on the page"+ return None+++def _terminal_challenge_halt_signal(+ ctx: Any,+ *,+ evidence_source: str,+ evidence_reason: str,+ blocked_tool: str = "update_and_run_blocks",+) -> CopilotToolBlockerSignal:+ workflow_run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)+ safe_evidence_reason = (+ run_outcome_display_reason(evidence_reason) or "Structured challenge evidence reported a terminal blocker."+ )+ return CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text=(+ "Structured challenge evidence confirms this path is blocked: "+ f"{safe_evidence_reason}. Do NOT retry block-running tools, do NOT try a proxy/location switch "+ "in this turn, and do NOT claim the workflow is verified end-to-end. Reply with the blocker."+ ),+ user_facing_reason=TERMINAL_CHALLENGE_USER_FACING_REASON,+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ preserves_workflow_draft=True,+ renders_final_reply=True,+ internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ blocked_tool=blocked_tool,+ extra={+ "run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ "evidence_source": evidence_source,+ "evidence_reason": safe_evidence_reason,+ "workflow_run_id": workflow_run_id if isinstance(workflow_run_id, str) else None,+ },+ )+++def terminal_challenge_blocker_signal_from_page_evidence(+ ctx: Any,+ *,+ blocked_tool: str,+ evidence_source: str = "page_evidence",+ evidence: dict[str, Any] | None = None,+) -> CopilotToolBlockerSignal | None:+ page_reason = _structured_page_challenge_reason(ctx, evidence)+ if page_reason is None:+ return None+ return _terminal_challenge_halt_signal(+ ctx,+ evidence_source=evidence_source,+ evidence_reason=page_reason,+ blocked_tool=blocked_tool,+ )+++def _current_page_challenge_requires_stop(evidence: dict[str, Any]) -> bool:+ challenge_state = evidence.get("challenge_state")+ if isinstance(challenge_state, dict) and (+ challenge_state.get("requires_human_verification") is True+ or challenge_state.get("gates_submit_controls") is True+ ):+ return True+ controls = evidence.get("challenge_controls")+ return isinstance(controls, list) and bool(interactive_challenge_controls(controls))+++def _current_page_evidence_candidates(ctx: Any) -> list[dict[str, Any]]:+ candidates: list[dict[str, Any]] = []+ for entry in reversed(getattr(ctx, "flow_evidence", None) or []):+ if not isinstance(entry, dict):+ continue+ packet = entry.get("evidence")+ if isinstance(packet, dict):+ candidates.append(packet)+ single = getattr(ctx, "composition_page_evidence", None)+ if isinstance(single, dict):+ candidates.append(single)+ return candidates+++def terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx: Any,+ *,+ blocked_tool: str,+ evidence_source: str = "page_evidence",+) -> CopilotToolBlockerSignal | None:+ if getattr(ctx, "last_failure_category_top", None) == PER_TOOL_BUDGET_FAILURE_CATEGORY:+ return None+ for evidence in _current_page_evidence_candidates(ctx):+ if evidence.get("observed_after_workflow_run") is not True:+ continue+ if not _current_page_challenge_requires_stop(evidence):+ continue+ signal = terminal_challenge_blocker_signal_from_page_evidence(+ ctx,+ blocked_tool=blocked_tool,+ evidence_source=evidence_source,+ evidence=evidence,+ )+ if signal is not None:+ return signal+ return None+++def _maybe_stash_terminal_challenge_halt(ctx: Any) -> None:+ if getattr(ctx, "turn_halt", None) is not None:+ return+ 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)+ stash_blocker_signal(ctx, signal)+ stash_turn_halt_from_blocker_signal(ctx, signal, source="enforcement")+ return+ # `last_test_ok is False` is the failed-run sentinel for this backstop.+ # Free-standing visible challenge hints remain diagnostic until a run/test+ # also records anti-bot evidence.+ if getattr(ctx, "last_test_ok", None) is not False:+ return+ if not getattr(ctx, "last_test_anti_bot", None):+ return+ page_signal = terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks")+ if page_signal is None:+ return+ stash_blocker_signal(ctx, page_signal)+ stash_turn_halt_from_blocker_signal(ctx, page_signal, source="enforcement")++class CopilotTotalTimeoutError(Exception):"""Raised when the copilot agent exceeds the total allowed runtime."""@@ -927,6 +1091,8 @@ def _post_run_observed_reply_can_finalize(ctx: AgentContext, result: RunResultStdef _needs_suspicious_success_nudge(ctx: Any) -> bool:"""Return True when the last test 'completed' but data blocks had no output."""+ if _typed_terminal_challenge_outcome(ctx) is not None:+ return False# A non-retriable nav failure cannot be "suspiciously successful" — defer# to the dedicated stop path rather than competing for the nudge slot.if getattr(ctx, "last_test_non_retriable_nav_error", None):@@ -1074,6 +1240,9 @@ def _check_enforcement(if _post_run_observed_reply_can_finalize(ctx, result):return None+ _maybe_stash_terminal_challenge_halt(ctx)+ raise_if_turn_halt(ctx)+# If the last run had confirmed challenge evidence, do not misdiagnose a# challenge-solving loop as a long-chain budgeting problem.if _needs_failed_test_nudge(ctx) and getattr(ctx, "last_test_anti_bot", None):diff --git a/skyvern/forge/sdk/copilot/failure_tracking.py b/skyvern/forge/sdk/copilot/failure_tracking.pyindex dda2e5053..7aba3e4c5 100644--- a/skyvern/forge/sdk/copilot/failure_tracking.py+++ b/skyvern/forge/sdk/copilot/failure_tracking.py@@ -56,6 +56,16 @@ _ROOT_CAUSE_CATEGORY_ALIASES = {"PARAMETER_BINDING_ERROR": "PARAMETER_BINDING_ERROR",PER_TOOL_BUDGET_FAILURE_CATEGORY: PER_TOOL_BUDGET_FAILURE_CATEGORY,}+ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES = frozenset(+ {+ ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY,+ *(+ category+ for category, normalized in _ROOT_CAUSE_CATEGORY_ALIASES.items()+ if normalized == ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY+ ),+ }+)_CATEGORY_ONLY_ROOT_CAUSES = frozenset({ANTI_BOT_CHALLENGE_ROOT_CAUSE_CATEGORY,diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.pyindex e4488ecd2..5feda112d 100644--- a/skyvern/forge/sdk/copilot/mcp_adapter.py+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py@@ -28,6 +28,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (stash_blocker_signal,)from skyvern.forge.sdk.copilot.build_phase import _phase_blocker_signal+from skyvern.forge.sdk.copilot.enforcement import terminal_challenge_blocker_signal_from_current_page_evidencefrom skyvern.forge.sdk.copilot.loop_detection import (detect_failed_tool_step_loop_for_ctx,detect_tool_loop,@@ -106,6 +107,18 @@ class SchemaOverlay:LOG = structlog.get_logger()_INTERNAL_TOOL_ARG_KEYS = frozenset({"_summarized"})+_CURRENT_PAGE_TERMINAL_CHALLENGE_MCP_TOOLS = frozenset(+ {+ "click",+ "evaluate",+ "get_browser_screenshot",+ "navigate_browser",+ "press_key",+ "scroll",+ "select_option",+ "type_text",+ }+)def _stash_and_emit_loop_blocker(ctx: Any, loop_message: str, tool_name: str) -> str:@@ -115,6 +128,19 @@ def _stash_and_emit_loop_blocker(ctx: Any, loop_message: str, tool_name: str) ->return payload+def _stash_and_emit_current_page_terminal_challenge_blocker(ctx: Any, tool_name: str) -> str | None:+ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool=tool_name,+ evidence_source="mcp_page_evidence",+ )+ if signal is None:+ return None+ payload = stash_blocker_signal(ctx, signal)+ stash_turn_halt_from_blocker_signal(ctx, signal, source="mcp_current_page_terminal_challenge")+ return payload++def _apply_schema_overlay(input_schema: dict[str, Any],overlay: SchemaOverlay,@@ -270,6 +296,18 @@ class SkyvernOverlayMCPServer(MCPServer):return _copilot_to_call_tool_result({"ok": False, "error": payload})refresh_held_loop_blocker_evidence(copilot_ctx)+ if tool_name in _CURRENT_PAGE_TERMINAL_CHALLENGE_MCP_TOOLS:+ terminal_challenge_payload = _stash_and_emit_current_page_terminal_challenge_blocker(+ copilot_ctx,+ tool_name,+ )+ if terminal_challenge_payload is not None:+ LOG.warning(+ "Current page terminal challenge detected, skipping MCP browser tool",+ tool_name=tool_name,+ )+ return _copilot_to_call_tool_result({"ok": False, "error": terminal_challenge_payload})+loop_error = detect_failed_tool_step_loop_for_ctx(copilot_ctx, tool_name, arguments)if loop_error:LOG.warning(diff --git a/skyvern/forge/sdk/copilot/output_policy.py b/skyvern/forge/sdk/copilot/output_policy.pyindex 6dacdb787..0d273ff90 100644--- a/skyvern/forge/sdk/copilot/output_policy.py+++ b/skyvern/forge/sdk/copilot/output_policy.py@@ -12,11 +12,13 @@ from skyvern.forge.sdk.copilot.output_utils import (looks_like_workflow_yaml_in_chat,)from skyvern.forge.sdk.copilot.request_policy import (- RAW_SECRET_PATTERNS,- SECRET_KEYWORD_ASSIGNMENT_PATTERN,RequestPolicy,contains_email_password_pair,)+from skyvern.forge.sdk.copilot.secret_redaction import (+ RAW_SECRET_PATTERNS,+ SECRET_KEYWORD_ASSIGNMENT_PATTERN,+)from skyvern.forge.sdk.copilot.workflow_credential_utils import (block_credential_ids,credential_params,diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex 1afe7bb75..c9baba697 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -8,7 +8,6 @@ from typing import Any, Literal, cast, get_argsfrom urllib.parse import urlparseimport structlog-from email_validator import EmailNotValidError, validate_emailfrom skyvern.config import settingsfrom skyvern.forge import app@@ -16,6 +15,11 @@ from skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.copilot.context import StructuredContextfrom skyvern.forge.sdk.copilot.llm_errors import is_retriable_llm_errorfrom skyvern.forge.sdk.copilot.output_utils import parse_final_response+from skyvern.forge.sdk.copilot.secret_redaction import (+ RAW_SECRET_PATTERNS,+ contains_email_password_pair,+ redact_raw_secrets_for_prompt,+)from skyvern.forge.sdk.copilot.tracing_setup import copilot_spanfrom skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_credential_ids, workflow_credential_originsfrom skyvern.forge.sdk.schemas.credentials import Credential@@ -120,23 +124,6 @@ _WORKFLOW_CREDENTIAL_INPUTS_UNBOUND_QUESTION = ("I couldn't find the required credentials for the existing workflow. "f"Please add them via the Credentials UI and I can try again. {_CREDENTIALS_UI_DIRECTIONS}")-SECRET_KEYWORD_ASSIGNMENT_PATTERN = re.compile(- r"\b(?:password|passcode|api[_ -]?key|secret|token|bearer|authorization)\s*[:=]\s*\S+", re.I-)-_RAW_SECRET_PATTERNS = (- SECRET_KEYWORD_ASSIGNMENT_PATTERN,- re.compile(- r"\b(?:otp|totp|mfa|2fa|verification|auth(?:entication)? code)(?:\s+code)?\s*(?:is|[:=])?\s*\d{6,8}\b",- re.I,- ),- re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),- re.compile(r"\bsk-[A-Za-z0-9_-]{16,}\b"),- re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),-)-# Reused by output-policy guardrails as syntactic leak backstops.-RAW_SECRET_PATTERNS = _RAW_SECRET_PATTERNS-_COLON_DELIMITED_SECRET_SEGMENT_SEPARATORS = (",", ";", "|")-_COLON_DELIMITED_SECRET_EDGE_CHARS = "\"'`()[]{}<>"_INVALID_CONDITIONAL_CONTAINER_MARKERS = ("into the conditional","inside the conditional",@@ -420,57 +407,7 @@ def _canonicalize_credential_ref(ref: str) -> str:def _raw_secret_detected(text: str) -> bool:- return any(pattern.search(text or "") for pattern in _RAW_SECRET_PATTERNS) or contains_email_password_pair(text)---def _candidate_secret_segments(text: str) -> list[str]:- segments: list[str] = []- for raw_token in (text or "").split():- token_segments = [raw_token]- for separator in _COLON_DELIMITED_SECRET_SEGMENT_SEPARATORS:- token_segments = [part for segment in token_segments for part in segment.split(separator)]- segments.extend(segment.strip(_COLON_DELIMITED_SECRET_EDGE_CHARS) for segment in token_segments)- return [segment for segment in segments if segment]---def _is_valid_account_row_email(value: str) -> bool:- if any(char.isspace() for char in value) or "/" in value or ":" in value:- return False- try:- validate_email(value, check_deliverability=False, test_environment=True)- except EmailNotValidError:- return False- return True---def _looks_like_colon_delimited_secret_value(value: str) -> bool:- if len(value) < 4:- return False- if any(char.isspace() for char in value):- return False- if any(char in value for char in ("/", "?", "#")):- return False- if value.isdigit() and len(value) <= 5:- return False- return True---def _email_password_pair_segments(text: str) -> list[str]:- pairs: list[str] = []- for segment in _candidate_secret_segments(text):- email, separator, secret_value = segment.partition(":")- if not separator:- continue- if _is_valid_account_row_email(email) and _looks_like_colon_delimited_secret_value(secret_value):- pairs.append(segment)- return pairs---def contains_email_password_pair(text: str) -> bool:- # Privacy backstop for pasted account dumps. The request-policy classifier- # owns ambiguous credential semantics; this parser keeps high-confidence raw- # values out of model prompts and output surfaces without a broad regex rule.- return bool(_email_password_pair_segments(text))+ return any(pattern.search(text or "") for pattern in RAW_SECRET_PATTERNS) or contains_email_password_pair(text)_MIN_RAW_SECRET_EVIDENCE_CHARS = 4@@ -496,15 +433,6 @@ def _coerce_raw_secret_handling(value: Any) -> RawSecretHandling:return "none"-def redact_raw_secrets_for_prompt(text: str) -> str:- redacted = text or ""- for pattern in _RAW_SECRET_PATTERNS:- redacted = pattern.sub("[REDACTED_SECRET]", redacted)- for segment in _email_password_pair_segments(redacted):- redacted = redacted.replace(segment, "[REDACTED_SECRET]")- return redacted--def _coerce_classifier_payload(raw: Any) -> dict[str, Any] | None:if isinstance(raw, str):raw = parse_final_response(raw)diff --git a/skyvern/forge/sdk/copilot/run_outcome.py b/skyvern/forge/sdk/copilot/run_outcome.pyindex 798197de3..1287f4484 100644--- a/skyvern/forge/sdk/copilot/run_outcome.py+++ b/skyvern/forge/sdk/copilot/run_outcome.py@@ -3,12 +3,34 @@ surfaces consume it instead of re-deriving success from raw block status."""from __future__ import annotations+import math+from collections.abc import Mappingfrom dataclasses import dataclass-from typing import Literal+from typing import Any, Literal++from skyvern.forge.sdk.copilot.failure_tracking import ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES+from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt+from skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE, url_originRunOutcomeVerdict = Literal["evaluating", "demonstrated", "not_demonstrated", "not_evaluated"]RecordedRunOutcomeVerdict = Literal["demonstrated", "not_demonstrated", "not_evaluated"]-RunOutcomeReasonCode = Literal["blocker_reported", "no_meaningful_output", "outcome_not_demonstrated"]+RunOutcomeReasonCode = Literal[+ "blocker_reported",+ "terminal_challenge_blocker",+ "no_meaningful_output",+ "outcome_not_demonstrated",+]++TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE: RunOutcomeReasonCode = "terminal_challenge_blocker"+TERMINAL_CHALLENGE_BLOCKER_REASON_CODE = "tool_error_terminal_challenge_blocker"+# Alias the root-cause classifier set so newly added anti-bot challenge aliases+# automatically participate in the terminal-challenge gate.+TERMINAL_CHALLENGE_FAILURE_CATEGORIES = ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES+TERMINAL_CHALLENGE_FAILURE_CATEGORY_MIN_CONFIDENCE = 0.7+TERMINAL_CHALLENGE_USER_FACING_REASON = (+ "The page is gated by a site verification challenge, so I stopped instead of retrying the same path. "+ "The draft workflow is preserved, but it is not verified end-to-end."+)_DISPLAY_REASON_MAX_CHARS = 160@@ -24,4 +46,21 @@ class RecordedRunOutcome:def run_outcome_display_reason(text: str | None) -> str | None:if not isinstance(text, str) or not text.strip():return None- return " ".join(text.split())[:_DISPLAY_REASON_MAX_CHARS]+ reason = redact_raw_secrets_for_prompt(" ".join(text.split()))+ reason = URL_CANDIDATE_RE.sub(lambda match: url_origin(match.group(0)) or "[URL]", reason)+ return reason[:_DISPLAY_REASON_MAX_CHARS]+++def trusted_terminal_challenge_category_name(entry: Mapping[str, Any]) -> str | None:+ category = entry.get("category")+ if not isinstance(category, str) or category not in TERMINAL_CHALLENGE_FAILURE_CATEGORIES:+ return None+ confidence = entry.get("confidence_float")+ if isinstance(confidence, (int, float)) and not isinstance(confidence, bool):+ numeric_confidence = float(confidence)+ if (+ not math.isfinite(numeric_confidence)+ or numeric_confidence < TERMINAL_CHALLENGE_FAILURE_CATEGORY_MIN_CONFIDENCE+ ):+ return None+ return categorydiff --git a/skyvern/forge/sdk/copilot/secret_redaction.py b/skyvern/forge/sdk/copilot/secret_redaction.pynew file mode 100644index 000000000..570d5bf82--- /dev/null+++ b/skyvern/forge/sdk/copilot/secret_redaction.py@@ -0,0 +1,80 @@+from __future__ import annotations++import re++from email_validator import EmailNotValidError, validate_email++SECRET_KEYWORD_ASSIGNMENT_PATTERN = re.compile(+ r"\b(?:password|passcode|api[_ -]?key|secret|token|bearer|authorization)\s*[:=]\s*\S+", re.I+)+RAW_SECRET_PATTERNS = (+ SECRET_KEYWORD_ASSIGNMENT_PATTERN,+ re.compile(+ r"\b(?:otp|totp|mfa|2fa|verification|auth(?:entication)? code)(?:\s+code)?\s*(?:is|[:=])?\s*\d{6,8}\b",+ re.I,+ ),+ re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"),+ re.compile(r"\bsk-[A-Za-z0-9_-]{16,}\b"),+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),+)+_COLON_DELIMITED_SECRET_SEGMENT_SEPARATORS = (",", ";", "|")+_COLON_DELIMITED_SECRET_EDGE_CHARS = "\"'`()[]{}<>"+++def _candidate_secret_segments(text: str) -> list[str]:+ segments: list[str] = []+ for raw_token in (text or "").split():+ token_segments = [raw_token]+ for separator in _COLON_DELIMITED_SECRET_SEGMENT_SEPARATORS:+ token_segments = [part for segment in token_segments for part in segment.split(separator)]+ segments.extend(segment.strip(_COLON_DELIMITED_SECRET_EDGE_CHARS) for segment in token_segments)+ return [segment for segment in segments if segment]+++def _is_valid_account_row_email(value: str) -> bool:+ if any(char.isspace() for char in value) or "/" in value or ":" in value:+ return False+ try:+ validate_email(value, check_deliverability=False, test_environment=True)+ except EmailNotValidError:+ return False+ return True+++def _looks_like_colon_delimited_secret_value(value: str) -> bool:+ if len(value) < 4:+ return False+ if any(char.isspace() for char in value):+ return False+ if any(char in value for char in ("/", "?", "#")):+ return False+ if value.isdigit() and len(value) <= 5:+ return False+ return True+++def _email_password_pair_segments(text: str) -> list[str]:+ pairs: list[str] = []+ for segment in _candidate_secret_segments(text):+ email, separator, secret_value = segment.partition(":")+ if not separator:+ continue+ if _is_valid_account_row_email(email) and _looks_like_colon_delimited_secret_value(secret_value):+ pairs.append(segment)+ return pairs+++def contains_email_password_pair(text: str) -> bool:+ # Privacy backstop for pasted account dumps. The request-policy classifier+ # owns ambiguous credential semantics; this parser keeps high-confidence raw+ # values out of model prompts and output surfaces without a broad regex rule.+ return bool(_email_password_pair_segments(text))+++def redact_raw_secrets_for_prompt(text: str) -> str:+ redacted = text or ""+ for pattern in RAW_SECRET_PATTERNS:+ redacted = pattern.sub("[REDACTED_SECRET]", redacted)+ for segment in _email_password_pair_segments(redacted):+ redacted = redacted.replace(segment, "[REDACTED_SECRET]")+ return redacteddiff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.pyindex 21a36d6b5..2e232e556 100644--- a/skyvern/forge/sdk/copilot/tools/blockers.py+++ b/skyvern/forge/sdk/copilot/tools/blockers.py@@ -18,7 +18,10 @@ from skyvern.forge.sdk.copilot.blocker_signal import (refresh_held_loop_blocker_evidence,)from skyvern.forge.sdk.copilot.composition_evidence import interactive_challenge_controls-from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS+from skyvern.forge.sdk.copilot.enforcement import (+ TOTAL_TIMEOUT_SECONDS,+ terminal_challenge_blocker_signal_from_current_page_evidence,+)from skyvern.forge.sdk.copilot.failure_tracking import (ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,@@ -26,6 +29,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import ()from skyvern.forge.sdk.copilot.loop_detection import detect_failed_tool_step_loop_for_ctx, detect_tool_loopfrom skyvern.forge.sdk.copilot.reached_download_target import REGISTERED_DOWNLOAD_OUTPUT_KEYS+from skyvern.forge.sdk.copilot.run_outcome import trusted_terminal_challenge_category_namefrom skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatusfrom skyvern.schemas.workflows import BlockType@@ -52,6 +56,12 @@ from ._shared import (LOG = structlog.get_logger()+_CURRENT_PAGE_TERMINAL_CHALLENGE_TOOLS = (+ BLOCK_RUNNING_TOOLS+ | PAGE_INSPECTION_TOOLS+ | frozenset({"click", "navigate_browser", "press_key", "scroll", "select_option", "type_text"})+)+async def _safe_read_workflow_run(workflow_run_id: str,@@ -751,6 +761,22 @@ def _post_budget_terminal_challenge_signal(return _terminal_challenge_signal(reason=reason, arguments=arguments, tool_name=tool_name)+def _current_page_terminal_challenge_signal(+ ctx: AgentContext, arguments: dict[str, Any] | None, tool_name: str+) -> CopilotToolBlockerSignal | None:+ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool=tool_name,+ evidence_source="page_evidence",+ )+ if signal is None:+ return None+ requested_labels = _requested_block_label_set(arguments)+ if requested_labels:+ signal = signal.model_copy(update={"extra": {**dict(signal.extra), "block_labels": sorted(requested_labels)}})+ return signal++_RECONCILIATION_REQUIRES_INPUT_USER_FACING = ("The previous run was canceled. Tell me whether to retry, keep the draft as-is, or adjust the workflow first.")@@ -831,9 +857,17 @@ _ANTI_BOT_BLOCKER_TERMS: tuple[str, ...] = ("access denied","anti-bot","bot block",+ "browser access barrier",+ "browser or environment port block",+ "browser port forbidden",+ "browser refused to render",+ "browser_port_forbidden",+ "browser_or_environment_port_block","captcha","challenge","human verification",+ "port-forbidden",+ "requested port","verify you are human",)# Multi-word anti-bot phrases only: the bare tokens ``captcha``/``challenge`` are@@ -907,10 +941,6 @@ def _structured_blocker_message(or (scan_all_values_for_anti_bot and _looks_like_anti_bot_phrase(item))):return item.strip()[:240]- if include_flag_keys:- flagged = _blocker_flag_or_status_message(value)- if flagged:- return flaggedfor item in value.values():nested = _structured_blocker_message(item,@@ -922,6 +952,10 @@ def _structured_blocker_message()if nested:return nested+ if include_flag_keys:+ flagged = _blocker_flag_or_status_message(value)+ if flagged:+ return flaggedelif isinstance(value, list):for item in value:nested = _structured_blocker_message(@@ -1413,6 +1447,11 @@ def _challenge_gated_anti_bot_rerun_signal(def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any] | None = None) -> str | None:refresh_held_loop_blocker_evidence(ctx)+ if tool_name in _CURRENT_PAGE_TERMINAL_CHALLENGE_TOOLS:+ current_page_challenge_signal = _current_page_terminal_challenge_signal(ctx, arguments, tool_name)+ if current_page_challenge_signal is not None:+ return _emit_tool_blocker_signal(ctx, current_page_challenge_signal)+detected = detect_failed_tool_step_loop_for_ctx(ctx, tool_name, arguments or {})if detected is not None:return _emit_tool_blocker_signal(@@ -1576,7 +1615,7 @@ def _analyze_run_blocks(precomputed_categories = data.get("failure_categories")if isinstance(precomputed_categories, list) and precomputed_categories:for cat in precomputed_categories:- if isinstance(cat, dict) and cat.get("category") == "ANTI_BOT_DETECTION":+ if isinstance(cat, dict) and trusted_terminal_challenge_category_name(cat) is not None:anti_bot_match = cat.get("reasoning", "anti-bot pattern detected")breakreturn anti_bot_match, False, precomputed_categoriesdiff --git a/skyvern/forge/sdk/copilot/tools/page_observation.py b/skyvern/forge/sdk/copilot/tools/page_observation.pyindex 1f94ad95c..69eaaab94 100644--- a/skyvern/forge/sdk/copilot/tools/page_observation.py+++ b/skyvern/forge/sdk/copilot/tools/page_observation.py@@ -36,6 +36,25 @@ def _bounded_observation_text(value: object, limit: int = 240) -> str:return " ".join(str(value or "").split())[:limit]+def _nested_observation_text(value: object, *, depth: int = 0) -> str:+ if depth > 4:+ return ""+ if isinstance(value, str):+ return _bounded_observation_text(value, 500)+ if isinstance(value, dict):+ parts: list[str] = []+ for key, item in list(value.items())[:40]:+ parts.append(_bounded_observation_text(key, 120))+ parts.append(_nested_observation_text(item, depth=depth + 1))+ return _bounded_observation_text(" ".join(part for part in parts if part), 2500)+ if isinstance(value, list):+ return _bounded_observation_text(+ " ".join(part for item in value[:40] if (part := _nested_observation_text(item, depth=depth + 1))),+ 2500,+ )+ return ""++@dataclass(frozen=True)class _ObservedFieldEvidence:name: str@@ -192,7 +211,7 @@ def _normalize_evaluate_challenge_state(anti_bot_indicators: list[str],) -> dict[str, Any]:detected = bool(anti_bot_indicators)- gated_controls: list[dict[str, Any]] = []+ gated_controls = _disabled_submit_controls(observed_data)for key, value in observed_data.items():normalized_key = str(key).strip().lower().replace("_", " ").replace("-", " ")if "disabled" not in normalized_key or value is not True:@@ -216,21 +235,74 @@ def _normalize_evaluate_challenge_state(kind = "human_verification"else:kind = "none"+ gates_submit_controls = bool(detected and gated_controls)return {"detected": detected,"kind": kind,"source": "mcp_evaluate" if detected else "","indicators": anti_bot_indicators[:8],- "requires_human_verification": detected,+ "requires_human_verification": gates_submit_controls,"visual_location": "",- "gates_submit_controls": bool(detected and gated_controls),+ "gates_submit_controls": gates_submit_controls,"gated_submit_controls": gated_controls[:5] if detected else [],}+def _disabled_submit_controls(observed_data: object) -> list[dict[str, Any]]:+ controls: list[dict[str, Any]] = []++ def visit(value: object, depth: int = 0) -> None:+ if depth > 4 or len(controls) >= 5:+ return+ if isinstance(value, list):+ for item in value[:40]:+ visit(item, depth + 1)+ return+ if not isinstance(value, dict):+ return++ disabled = value.get("disabled") is True or value.get("ariaDisabled") is True+ text_parts: list[str] = []+ for key in (+ "text",+ "label",+ "name",+ "id",+ "selector",+ "value",+ "aria_label",+ "aria-label",+ "title",+ "type",+ "role",+ ):+ item = value.get(key)+ if isinstance(item, str):+ text_parts.append(item)+ label = _bounded_observation_text(" ".join(text_parts), 160)+ normalized = label.lower().replace("_", " ").replace("-", " ")+ if disabled and any(token in normalized for token in ("submit", "search", "button", "btn")):+ controls.append(+ {+ "text": label,+ "id": _bounded_observation_text(value.get("id"), 120),+ "name": _bounded_observation_text(value.get("name"), 120),+ "selector": _bounded_observation_text(value.get("selector"), 160),+ "disabled": True,+ }+ )++ for item in value.values():+ visit(item, depth + 1)++ visit(observed_data)+ return controls[:5]++def _evaluate_anti_bot_indicators(observed_data: dict[str, Any], text: str) -> list[str]:key_text = " ".join(str(key) for key in observed_data.keys()).lower()- combined = f"{text} {key_text}"+ nested_text = _nested_observation_text(observed_data).lower()+ combined = f"{text} {key_text} {nested_text}"[:5000]return [pattern for pattern in _DISCOVERY_ANTI_BOT_PATTERNS if pattern in combined]diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex aeda447af..3124c89bf 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -6,7 +6,7 @@ import jsonimport timefrom collections import defaultdictfrom collections.abc import Mapping-from dataclasses import replace+from dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom typing import Any, Literalfrom urllib.parse import urlparse@@ -68,10 +68,14 @@ from skyvern.forge.sdk.copilot.reached_download_target import ()from skyvern.forge.sdk.copilot.reached_download_target import guidance_for as _reached_download_guidance_forfrom skyvern.forge.sdk.copilot.run_outcome import (+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ TERMINAL_CHALLENGE_USER_FACING_REASON,RecordedRunOutcome,RunOutcomeReasonCode,RunOutcomeVerdict,run_outcome_display_reason,+ trusted_terminal_challenge_category_name,)from skyvern.forge.sdk.copilot.runtime import (AgentContext,@@ -1559,6 +1563,101 @@ def _composition_anti_bot_reason(copilot_ctx: object) -> str | None:return f"Observed anti-bot challenge evidence before the run: {details}"+@dataclass(frozen=True)+class TerminalChallengeEvidence:+ source: str+ reason: str+ workflow_run_id: str | None = None+ block_labels: tuple[str, ...] = ()+++def _trusted_terminal_challenge_category_names(failure_categories: list[dict] | None) -> tuple[str, ...]:+ if not isinstance(failure_categories, list):+ return ()+ names: list[str] = []+ for category in failure_categories:+ if not isinstance(category, dict):+ continue+ name = trusted_terminal_challenge_category_name(category)+ if isinstance(name, str) and name:+ names.append(name)+ return tuple(dict.fromkeys(names))+++def _ensure_terminal_challenge_category(data: dict[str, Any]) -> None:+ categories = data.get("failure_categories")+ if not isinstance(categories, list):+ categories = []+ if not any(+ isinstance(category, dict) and trusted_terminal_challenge_category_name(category) for category in categories+ ):+ categories = [+ *categories,+ {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.9,+ "reasoning": "Structured challenge evidence reported a terminal blocker.",+ },+ ]+ data["failure_categories"] = categories+++def _block_labels_from_result_data(data: Mapping[str, object]) -> tuple[str, ...]:+ blocks = data.get("blocks")+ if not isinstance(blocks, list):+ return ()+ labels: list[str] = []+ for block in blocks:+ if not isinstance(block, dict):+ continue+ label = block.get("label")+ if isinstance(label, str) and label.strip():+ labels.append(label.strip())+ return tuple(dict.fromkeys(labels))+++def _terminal_challenge_evidence(+ result: dict[str, Any],+ *,+ failure_categories: list[dict] | None,+ structured_blocker: str | None,+ anti_bot_match: str | None = None,+) -> TerminalChallengeEvidence | None:+ data = result.get("data")+ result_data = data if isinstance(data, dict) else {}+ workflow_run_id = result_data.get("workflow_run_id")+ run_id = workflow_run_id if isinstance(workflow_run_id, str) and workflow_run_id.strip() else None+ block_labels = _block_labels_from_result_data(result_data)+ challenge_categories = _trusted_terminal_challenge_category_names(failure_categories)+ if isinstance(structured_blocker, str) and (+ _looks_like_anti_bot_blocker(structured_blocker) or isinstance(anti_bot_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()+ and not _looks_like_anti_bot_blocker(structured_blocker)+ ):+ reason = f"{anti_bot_match}; {reason}"+ return TerminalChallengeEvidence(+ source="structured_blocker",+ reason=reason,+ 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]}"+ return TerminalChallengeEvidence(+ source="failure_category",+ reason=reason,+ workflow_run_id=run_id,+ block_labels=block_labels,+ )+ return None++# 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@@ -1752,6 +1851,13 @@ def _record_run_blocks_result(if isinstance(data, dict):data["failure_categories"] = failure_categories+ terminal_challenge = _terminal_challenge_evidence(+ result,+ failure_categories=failure_categories,+ structured_blocker=structured_blocker,+ anti_bot_match=anti_bot_match,+ )+artifact_reason, artifact_labels, artifact_classes = _artifact_health_blocker_from_result(result)if artifact_reason is not None:copilot_ctx.last_artifact_health_blocker_reason = artifact_reason@@ -1772,9 +1878,44 @@ def _record_run_blocks_result(stash_blocker_signal(copilot_ctx, signal)stash_turn_halt_from_blocker_signal(copilot_ctx, signal, source="run_execution")+ if terminal_challenge is not None:+ # A structured challenge is the more actionable terminal blocker when+ # artifact-health evidence and challenge evidence appear in the same run.+ _mark_page_inspected(copilot_ctx)+ result["ok"] = False+ result.setdefault("error", terminal_challenge.reason)+ data = result.get("data")+ if isinstance(data, dict):+ data.setdefault("failure_reason", terminal_challenge.reason)+ _ensure_terminal_challenge_category(data)+ copilot_ctx.last_failure_category_top = "ANTI_BOT_DETECTION"+ copilot_ctx.last_test_ok = False+ copilot_ctx.last_test_suspicious_success = False+ copilot_ctx.last_test_failure_reason = terminal_challenge.reason+ copilot_ctx.last_test_anti_bot = terminal_challenge.reason+ copilot_ctx.last_full_workflow_test_ok = False+ copilot_ctx.last_failed_workflow_yaml = getattr(copilot_ctx, "workflow_yaml", None)+ signal = _terminal_challenge_blocker_signal(terminal_challenge, tool_name="update_and_run_blocks")+ stash_blocker_signal(copilot_ctx, signal)+ stash_turn_halt_from_blocker_signal(copilot_ctx, signal, source="run_execution")+ update_repeated_failure_state(copilot_ctx, result)+ _update_verification_evidence_from_run_result(copilot_ctx, result)+ return _stash_recorded_run_outcome(+ copilot_ctx,+ RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code=TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ display_reason=run_outcome_display_reason(terminal_challenge.reason),+ workflow_run_id=terminal_challenge.workflow_run_id,+ ),+ )+if run_ok:_mark_page_inspected(copilot_ctx)if structured_blocker:+ # Terminal anti-bot blockers are handled before run_ok; this branch+ # remains for non-challenge structured blockers that still make a+ # completed run suspicious.failure_reason = f"Run completed, but extracted data reported a blocker: {structured_blocker}"result["ok"] = Falseresult.setdefault("error", failure_reason)@@ -1782,26 +1923,9 @@ def _record_run_blocks_result(copilot_ctx.last_test_suspicious_success = Truecopilot_ctx.last_test_failure_reason = failure_reasoncopilot_ctx.last_failed_workflow_yaml = getattr(copilot_ctx, "workflow_yaml", None)- if not copilot_ctx.last_test_anti_bot and _looks_like_anti_bot_blocker(structured_blocker):- copilot_ctx.last_test_anti_bot = f"Extracted data reported anti-bot blocker: {structured_blocker[:160]}"data = result.get("data")if isinstance(data, dict):data.setdefault("failure_reason", failure_reason)- if copilot_ctx.last_test_anti_bot and not failure_categories:- anti_bot_category = {- "category": "ANTI_BOT_DETECTION",- "confidence_float": 0.7,- "reasoning": "Structured extracted data reported an anti-bot blocker.",- }- data["failure_categories"] = [anti_bot_category]- if _looks_like_anti_bot_blocker(structured_blocker):- signal = _run_output_terminal_blocker_signal(- structured_blocker=structured_blocker,- failure_reason=failure_reason,- tool_name="update_and_run_blocks",- )- stash_blocker_signal(copilot_ctx, signal)- stash_turn_halt_from_blocker_signal(copilot_ctx, signal, source="run_output_content_gate")update_repeated_failure_state(copilot_ctx, result)_update_verification_evidence_from_run_result(copilot_ctx, result)return _stash_recorded_run_outcome(@@ -2081,38 +2205,60 @@ def _record_diagnosis_repair_contract(return contract-def _run_output_terminal_blocker_signal(+def _terminal_challenge_blocker_signal(+ evidence: TerminalChallengeEvidence,*,- structured_blocker: str,- failure_reason: str,tool_name: str,) -> CopilotToolBlockerSignal:- agent_steering = (- "The workflow run completed with structured anti-bot or challenge blocker evidence: "- f"{structured_blocker[:240]}. Do NOT call "- f"{tool_name} again in this turn. Reply from the recorded blocker and preserved draft; "- "do not claim the workflow is verified end-to-end."+ safe_evidence_reason = (+ run_outcome_display_reason(evidence.reason) or "Structured challenge evidence reported a terminal blocker.")- user_facing = (- "The page is gated by a site verification challenge, so I stopped instead of retrying the same path. "- "The draft workflow is preserved, but it is not verified end-to-end."+ agent_steering = (+ "The latest run produced structured anti-bot or challenge evidence: "+ f"{safe_evidence_reason}. Do NOT call "+ f"{tool_name} again in this turn, do NOT try another proxy/location in this turn, and "+ "do NOT claim the workflow is verified end-to-end. Reply from the recorded blocker and preserved draft.")return CopilotToolBlockerSignal(blocker_kind="tool_error",agent_steering_text=agent_steering,- user_facing_reason=user_facing,+ user_facing_reason=TERMINAL_CHALLENGE_USER_FACING_REASON,recovery_hint="report_blocker_to_user",cleared_by_tools=frozenset(),preserves_workflow_draft=True,renders_final_reply=True,- internal_reason_code="tool_error_run_output_terminal_blocker",+ internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,blocked_tool=tool_name,- extra={"failure_reason": failure_reason[:240]},+ extra={+ "run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ "evidence_source": evidence.source,+ "evidence_reason": safe_evidence_reason,+ "workflow_run_id": evidence.workflow_run_id,+ "block_labels": list(evidence.block_labels),+ },)def _diagnosis_repair_tool_error(copilot_ctx: Any, source_tool: str, error: str) -> str:result = {"ok": False, "error": error}+ blocker_signal = getattr(copilot_ctx, "blocker_signal", None)+ if (+ isinstance(blocker_signal, CopilotToolBlockerSignal)+ and blocker_signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ ):+ reason = blocker_signal.extra.get("evidence_reason")+ if not isinstance(reason, str) or not reason.strip():+ reason = blocker_signal.user_facing_reason+ result["data"] = {+ "failure_reason": reason,+ "failure_categories": [+ {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.9,+ "reasoning": "Structured page challenge evidence reported a terminal blocker.",+ }+ ],+ }record_consecutive_tool_result_boundary_for_ctx(copilot_ctx, source_tool, result)_record_diagnosis_repair_contract(copilot_ctx, source_tool=source_tool, result=result)return json.dumps(result)diff --git a/skyvern/forge/sdk/copilot/turn_halt.py b/skyvern/forge/sdk/copilot/turn_halt.pyindex 7e6b4b492..f6fdc25a8 100644--- a/skyvern/forge/sdk/copilot/turn_halt.py+++ b/skyvern/forge/sdk/copilot/turn_halt.py@@ -11,6 +11,7 @@ import structlogfrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.blocker_signal import to_trace_data as blocker_signal_to_trace_datafrom skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE+from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODELOG = structlog.get_logger()@@ -37,6 +38,8 @@ _LOOP_TERMINAL_REASON_CODES = frozenset(_ACTIVE_TERMINAL_CHALLENGE_REASON_CODES = frozenset({ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ # Back-compat sentinel for pre-TERMINAL_CHALLENGE_BLOCKER traces."tool_error_run_output_terminal_blocker","tool_error_post_budget_challenge_blocker","tool_error_challenge_gated_submit_disabled",@@ -84,7 +87,7 @@ def turn_halt_from_blocker_signal(signal: object, *, source: str) -> TurnHalt |kind=kind,blocker_signal=signal,draft_state={"preserves_workflow_draft": signal.preserves_workflow_draft},- extra={"source": source},+ extra={**signal.extra, "source": source},)diff --git a/skyvern/forge/sdk/copilot/workflow_credential_utils.py b/skyvern/forge/sdk/copilot/workflow_credential_utils.pyindex da9866b6e..f70ad3d64 100644--- a/skyvern/forge/sdk/copilot/workflow_credential_utils.py+++ b/skyvern/forge/sdk/copilot/workflow_credential_utils.py@@ -20,11 +20,19 @@ def parse_workflow_yaml(workflow_yaml: str) -> Any:def url_origin(url: str) -> str | None:parsed = urlparse(url if "://" in url else f"https://{url}")- if not parsed.netloc:+ if not parsed.netloc or not parsed.hostname:return None+ host = parsed.hostname.lower()+ if ":" in host and not host.startswith("["):+ host = f"[{host}]"+ try:+ port = parsed.port+ except ValueError:+ port = None+ netloc = f"{host}:{port}" if port is not None else host# Keep scheme in the origin. http:// and https:// are different security# contexts, so crossing between them is treated as scope broadening.- return f"{parsed.scheme.lower()}://{parsed.netloc.lower()}"+ return f"{parsed.scheme.lower()}://{netloc}"def credential_params(parameters: Any) -> dict[str, str]:diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex 773be572c..2f142cd1d 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -6,6 +6,7 @@ from unittest.mock import AsyncMockimport pytest+from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdictfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.diagnosis_repair_contract import (@@ -13,6 +14,10 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (RepairNextAction,build_diagnosis_repair_contract,)+from skyvern.forge.sdk.copilot.run_outcome import (+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+)from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode@@ -309,10 +314,140 @@ def test_anti_bot_suspicious_success_contract_stops_instead_of_repairing() -> Noworkflow_updated=True,)- assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.SUSPICIOUS_SUCCESS+ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKERassert contract.repair_decision.next_action == RepairNextAction.STOPassert contract.verification_result.user_goal_satisfied is False+ assert contract.verification_result.completion_contract_satisfied is Falseassert "Verify you are human" in contract.verification_result.remaining_blocker+ assert contract.to_trace_data()["failure_type"] == "terminal_challenge_blocker"+++def test_challenge_category_preempts_clean_run_ok_contract() -> None:+ ctx = _ctx()+ ctx.last_test_anti_bot = "Typed run analysis reported an anti-bot challenge."+ ctx.last_test_failure_reason = "Run output reported a blocker: Verify you are human."++ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result={+ "ok": True,+ "data": {+ "workflow_run_id": "wr_blocked",+ "overall_status": "completed",+ "failure_reason": ctx.last_test_failure_reason,+ "failure_categories": [{"category": "ANTI_BOT_DETECTION"}],+ "blocks": [+ {+ "label": "extract",+ "block_type": "EXTRACTION",+ "status": "completed",+ }+ ],+ },+ },+ ctx=ctx,+ workflow_updated=True,+ )++ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER+ assert contract.repair_decision.next_action == RepairNextAction.STOP+ assert contract.verification_result.user_goal_satisfied is False+++def test_low_confidence_challenge_category_does_not_preempt_clean_run_ok_contract() -> None:+ ctx = _ctx()++ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result={+ "ok": True,+ "data": {+ "workflow_run_id": "wr_clean",+ "overall_status": "completed",+ "failure_categories": [+ {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.2,+ "reasoning": "Low-confidence upstream category.",+ }+ ],+ "blocks": [+ {+ "label": "extract",+ "block_type": "EXTRACTION",+ "status": "completed",+ }+ ],+ },+ },+ ctx=ctx,+ workflow_updated=True,+ )++ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.NO_FAILURE+ assert contract.repair_decision.next_action == RepairNextAction.NO_CHANGE+++def test_pre_run_challenge_observation_does_not_force_stop_on_repairable_failure() -> None:+ ctx = _ctx()+ ctx.last_test_anti_bot = (+ "Observed anti-bot challenge evidence before the run: challenge-gated disabled submit/search control: Search"+ )+ ctx.last_test_failure_reason = "The search button selector changed before submit."++ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result={+ "ok": False,+ "data": {+ "workflow_run_id": "wr_repair",+ "overall_status": "failed",+ "failure_reason": ctx.last_test_failure_reason,+ "blocks": [{"label": "submit_search", "block_type": "NAVIGATION", "status": "failed"}],+ },+ },+ ctx=ctx,+ workflow_updated=True,+ )++ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE+ assert contract.repair_decision.next_action == RepairNextAction.REPAIR+++def test_post_run_gated_challenge_observation_forces_stop_on_repairable_failure() -> None:+ ctx = _ctx()+ ctx.last_test_anti_bot = (+ "Observed anti-bot challenge evidence before the run: challenge-gated disabled submit/search control: Search"+ )+ ctx.last_test_failure_reason = "The Search button remains disabled after verification."+ ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }++ contract = build_diagnosis_repair_contract(+ source_tool="update_and_run_blocks",+ result={+ "ok": False,+ "data": {+ "workflow_run_id": "wr_terminal",+ "overall_status": "failed",+ "failure_reason": ctx.last_test_failure_reason,+ "blocks": [{"label": "submit_search", "block_type": "NAVIGATION", "status": "failed"}],+ },+ },+ ctx=ctx,+ workflow_updated=True,+ )++ assert contract.diagnosis_result.suspected_failure_type == DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE+ assert contract.repair_decision.next_action == RepairNextAction.STOPdef test_user_goal_urls_are_reduced_to_origins() -> None:@@ -469,3 +604,35 @@ async def test_update_workflow_failure_records_diagnosis_contract(monkeypatch: passert recorded == [("update_workflow", {"ok": False, "error": error}, "code_block_synthesis_ambiguous_bare_selector")]+++def test_diagnosis_tool_error_preserves_terminal_challenge_blocker_category() -> None:+ from skyvern.forge.sdk.copilot.tools.run_execution import _diagnosis_repair_tool_error++ ctx = _ctx()+ ctx.blocker_signal = CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text="terminal challenge",+ user_facing_reason="The page is gated by a site verification challenge.",+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ preserves_workflow_draft=True,+ renders_final_reply=True,+ internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ blocked_tool="update_and_run_blocks",+ extra={+ "run_outcome_reason_code": TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ "evidence_source": "page_evidence",+ "evidence_reason": "human verification requires human verification",+ },+ )++ 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 ctx.latest_diagnosis_repair_contract is not None+ assert (+ ctx.latest_diagnosis_repair_contract.diagnosis_result.suspected_failure_type+ == DiagnosisFailureType.TERMINAL_CHALLENGE_BLOCKER+ )+ assert ctx.latest_diagnosis_repair_contract.repair_decision.next_action == RepairNextAction.STOPdiff --git a/tests/unit/test_copilot_evaluate_page_evidence.py b/tests/unit/test_copilot_evaluate_page_evidence.pyindex ce0a2cea0..4f095120a 100644--- a/tests/unit/test_copilot_evaluate_page_evidence.py+++ b/tests/unit/test_copilot_evaluate_page_evidence.py@@ -12,6 +12,7 @@ from skyvern.forge.sdk.copilot.tools import (_inspect_page_for_composition_impl,_mark_pending_browser_interaction_observation,)+from skyvern.forge.sdk.copilot.tools.blockers import _tool_loop_errorfrom skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode@@ -105,12 +106,74 @@ async def test_evaluate_turnstile_key_records_challenge_observation_step() -> Noassert evidence["source_tool"] == "evaluate"assert evidence["challenge_state"]["detected"] is Trueassert evidence["challenge_state"]["kind"] == "captcha"+ assert evidence["challenge_state"]["requires_human_verification"] is Trueassert evidence["challenge_state"]["gates_submit_controls"] is Trueassert evidence["challenge_state"]["gated_submit_controls"][0]["disabled"] is Trueassert "turnstile" in evidence["anti_bot_indicators"]assert ctx.composition_page_evidence is evidence+async def test_evaluate_nested_challenge_payload_does_not_block_before_attempt() -> None:+ ctx = _ctx()++ result = {+ "ok": True,+ "data": {+ "url": "https://example.test/certificant-search",+ "title": "Certificant Search",+ "buttons": [{"text": "Search", "disabled": True, "selector": "#search-button"}],+ "fields": [+ {+ "label": "Verification code",+ "name": "captcha_response",+ "placeholder": "Enter verification code",+ }+ ],+ },+ }++ await _evaluate_post_hook(result, raw={}, ctx=ctx)++ evidence = ctx.composition_page_evidence+ assert evidence is not None+ assert evidence["source_tool"] == "evaluate"+ assert evidence["challenge_state"]["detected"] is True+ assert evidence["challenge_state"]["requires_human_verification"] is True+ assert evidence["challenge_state"]["gates_submit_controls"] is True+ assert evidence["challenge_state"]["gated_submit_controls"][0]["disabled"] is True++ msg = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["search_lookup"]})++ assert msg is None+ assert ctx.turn_halt is None+++async def test_evaluate_text_only_challenge_payload_stays_diagnostic() -> None:+ ctx = _ctx()++ result = {+ "ok": True,+ "data": {+ "url": "https://example.test/certificant-search",+ "title": "Certificant Search",+ "text": "Verify you are human before searching.",+ "turnstile": True,+ },+ }++ await _evaluate_post_hook(result, raw={}, ctx=ctx)++ evidence = ctx.composition_page_evidence+ assert evidence is not None+ assert evidence["source_tool"] == "evaluate"+ assert evidence["challenge_state"]["detected"] is True+ assert evidence["challenge_state"]["requires_human_verification"] is False+ assert evidence["challenge_state"]["gates_submit_controls"] is False+ assert evidence["challenge_state"]["gated_submit_controls"] == []++@pytest.mark.asyncioasync def test_target_url_inspection_does_not_navigate_away_from_interaction_evidence(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_copilot_failure_tracking.py b/tests/unit/test_copilot_failure_tracking.pyindex 3fa33391a..004f8a61f 100644--- a/tests/unit/test_copilot_failure_tracking.py+++ b/tests/unit/test_copilot_failure_tracking.py@@ -6,11 +6,13 @@ from typing import Anyimport pytestfrom skyvern.forge.sdk.copilot.failure_tracking import (+ ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES,compute_failure_signature,compute_frontier_fingerprint,compute_repair_root_cause_signature,update_repeated_failure_state,)+from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_FAILURE_CATEGORIESclass _Block:@@ -131,6 +133,10 @@ def test_category_only_and_code_imposition_root_causes_collapse_noise() -> None:assert first.error_class == "code_block_synthesis_ambiguous_bare_selector"+def test_terminal_challenge_categories_follow_anti_bot_root_cause_aliases() -> None:+ assert TERMINAL_CHALLENGE_FAILURE_CATEGORIES == ANTI_BOT_CHALLENGE_FAILURE_CATEGORIES++def test_fingerprint_empty_without_workflow_definition() -> None:assert compute_frontier_fingerprint(["open"], None) == ""diff --git a/tests/unit/test_copilot_loop_detection_blocker.py b/tests/unit/test_copilot_loop_detection_blocker.pyindex 1808d83eb..ab4210067 100644--- a/tests/unit/test_copilot_loop_detection_blocker.py+++ b/tests/unit/test_copilot_loop_detection_blocker.py@@ -1,5 +1,6 @@from __future__ import annotations+import jsonfrom types import SimpleNamespaceimport pytest@@ -14,9 +15,9 @@ from skyvern.forge.sdk.copilot.blocker_signal import (loop_blocker_evidence_from_ctx,)from skyvern.forge.sdk.copilot.context import CopilotContext-from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServer, _stash_and_emit_loop_blocker+from skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlay, SkyvernOverlayMCPServer, _stash_and_emit_loop_blockerfrom skyvern.forge.sdk.copilot.output_policy import CopilotOutputKind, evaluate_output_policy-from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome+from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE, RecordedRunOutcomefrom skyvern.forge.sdk.copilot.tools import _build_loop_blocker_signal, _tool_loop_errorfrom skyvern.forge.sdk.copilot.tools.mcp_hooks import get_skyvern_mcp_alias_mapfrom skyvern.forge.sdk.copilot.turn_halt import TurnHaltKind@@ -44,6 +45,22 @@ def _ctx(return ctx+def _current_page_challenge_evidence(*, observed_after_workflow_run: bool = True) -> dict[str, object]:+ evidence: dict[str, object] = {+ "current_url": "https://example.test/search",+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }+ if observed_after_workflow_run:+ evidence["observed_after_workflow_run"] = True+ return evidence++@pytest.mark.parametrize(("loop_message", "expected_reason"),[@@ -412,6 +429,69 @@ def test_native_and_mcp_paths_carry_equivalent_evidence_bearing_signals() -> Nonassert mcp_signal.blocked_tool == native_signal.blocked_tool+def test_native_tool_loop_error_terminal_challenge_preempts_same_tool_loop() -> None:+ ctx = _ctx(consecutive_tool_tracker=["evaluate", "evaluate"])+ ctx.composition_page_evidence = _current_page_challenge_evidence()++ payload = _tool_loop_error(ctx, "evaluate", {"expression": "document.body.innerText"})++ assert payload is not None+ signal = ctx.blocker_signal+ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ assert signal.blocked_tool == "evaluate"+ assert signal.extra["evidence_source"] == "page_evidence"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+++def test_native_tool_loop_error_does_not_preempt_on_pre_attempt_challenge() -> None:+ ctx = _ctx(consecutive_tool_tracker=["evaluate", "evaluate"])+ ctx.composition_page_evidence = _current_page_challenge_evidence(observed_after_workflow_run=False)++ payload = _tool_loop_error(ctx, "evaluate", {"expression": "document.body.innerText"})++ assert payload is not None+ signal = ctx.blocker_signal+ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == "loop_detected_consecutive_same_tool"+ assert signal.blocked_tool == "evaluate"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.LOOP_DETECTED+++async def test_mcp_browser_tool_terminal_challenge_preempts_same_tool_loop() -> None:+ ctx = _ctx(consecutive_tool_tracker=["evaluate", "evaluate"])+ ctx.composition_page_evidence = _current_page_challenge_evidence()++ class _UnexpectedClient:+ async def call_tool(self, name: str, args: dict, raise_on_error: bool = False) -> object:+ raise AssertionError("terminal challenge blocker should skip MCP execution")++ server = SkyvernOverlayMCPServer(+ transport=None,+ overlays={"evaluate": SchemaOverlay(requires_browser=True)},+ alias_map={},+ allowlist=frozenset({"evaluate"}),+ context_provider=lambda: ctx,+ )+ server._client = _UnexpectedClient() # type: ignore[assignment]++ result = await server.call_tool("evaluate", {"expression": "document.body.innerText"})++ parsed = json.loads(result.content[0].text)+ assert result.isError is True+ assert parsed["ok"] is False+ signal = ctx.blocker_signal+ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ assert signal.blocked_tool == "evaluate"+ assert signal.extra["evidence_source"] == "mcp_page_evidence"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE++def test_tool_loop_error_entry_refreshes_stale_held_loop_signal() -> None:ctx = _ctx()stale = _build_loop_blocker_signal(_BRANCH_MESSAGES["loop_detected_consecutive_same_tool"], tool_name="evaluate")diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.pyindex c8837fb3e..752cf4454 100644--- a/tests/unit/test_copilot_per_tool_budget.py+++ b/tests/unit/test_copilot_per_tool_budget.py@@ -44,6 +44,10 @@ from skyvern.forge.sdk.copilot.failure_tracking import (PER_TOOL_BUDGET_FAILURE_CATEGORY,compute_failure_signature,)+from skyvern.forge.sdk.copilot.run_outcome import (+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+)from skyvern.forge.sdk.copilot.tools import (ACTIVE_RUN_TERMINAL_EVIDENCE_FAILURE_CATEGORY,WatchdogExitReason,@@ -61,6 +65,7 @@ from skyvern.forge.sdk.copilot.tools import (_tool_loop_error,_watchdog_user_failure_reason,)+from skyvern.forge.sdk.copilot.turn_halt import CopilotTurnHalt, TurnHaltKinddef _fresh_context() -> CopilotContext:@@ -148,6 +153,7 @@ def test_record_preserves_pre_run_anti_bot_evidence_on_budget_trip() -> None:def test_composition_anti_bot_reason_reads_typed_challenge_state_without_legacy_indicators() -> None:ctx = _fresh_context()ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,"challenge_state": {"detected": True,"kind": "human_verification",@@ -164,6 +170,72 @@ def test_composition_anti_bot_reason_reads_typed_challenge_state_without_legacy_assert "challenge-gated disabled submit/search control: Search" in reason+def test_block_running_halts_on_current_page_terminal_challenge_before_repair_loop() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }++ msg = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["search_lookup"]})++ assert msg is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ assert ctx.blocker_signal.extra["run_outcome_reason_code"] == TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE+ assert ctx.blocker_signal.extra["evidence_source"] == "page_evidence"+ assert ctx.blocker_signal.extra["block_labels"] == ["search_lookup"]+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+++def test_block_running_does_not_halt_current_page_challenge_when_results_are_present() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": False,+ "gates_submit_controls": False,+ },+ "result_containers": [{"selector": "#results", "row_count": 1, "sample_rows": ["Visible result row"]}],+ }++ assert _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["search_lookup"]}) is None+ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None+++def test_block_running_halts_current_page_challenge_with_empty_result_shell() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ "result_containers": [{"selector": "#results", "text_excerpt": "Results"}],+ }++ msg = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["search_lookup"]})++ assert msg is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE++def test_block_running_after_budget_current_url_requires_inspection_first() -> None:ctx = _fresh_context()ctx.post_budget_page_inspection_required = True@@ -290,19 +362,49 @@ def test_check_enforcement_emits_budget_nudge_before_failed_test() -> None:assert ctx.per_tool_budget_nudge_count == 1-def test_check_enforcement_emits_anti_bot_nudge_before_budget_when_challenge_observed() -> None:+def test_check_enforcement_halts_before_budget_when_structured_challenge_observed() -> None:ctx = _fresh_context()ctx.update_workflow_called = Truectx.test_after_update_done = Truectx.last_test_ok = Falsectx.last_failure_category_top = PER_TOOL_BUDGET_FAILURE_CATEGORYctx.last_test_anti_bot = "Observed anti-bot challenge evidence before the run: human-verification"+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "human_verification password=topsecret",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }++ with pytest.raises(CopilotTurnHalt) as exc_info:+ _check_enforcement(ctx)++ assert exc_info.value.halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+ assert exc_info.value.halt.extra["run_outcome_reason_code"] == "terminal_challenge_blocker"+ assert exc_info.value.halt.extra["evidence_source"] == "page_evidence"+ assert "[REDACTED_SECRET]" in exc_info.value.halt.extra["evidence_reason"]+ assert "topsecret" not in exc_info.value.halt.extra["evidence_reason"]+ assert ctx.failed_test_nudge_count == 0+ assert ctx.per_tool_budget_nudge_count == 0+++def test_check_enforcement_keeps_text_only_anti_bot_diagnostic_non_terminal() -> None:+ ctx = _fresh_context()+ ctx.update_workflow_called = True+ ctx.test_after_update_done = True+ ctx.last_test_ok = False+ ctx.last_failure_category_top = PER_TOOL_BUDGET_FAILURE_CATEGORY+ ctx.last_test_anti_bot = "possible challenge mentioned in free text"nudge = _check_enforcement(ctx)assert nudge == POST_ANTI_BOT_FAILED_TEST_NUDGEassert ctx.failed_test_nudge_count == 1assert ctx.per_tool_budget_nudge_count == 0+ assert ctx.turn_halt is Nonedef test_final_reply_after_post_run_observation_bypasses_stale_budget_and_anti_bot_nudges() -> None:@@ -674,6 +776,7 @@ workflow_definition:"The required Search button remains disabled after verification, and there is no enabled alternative.")ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,"challenge_state": {"detected": True,"kind": "human_verification",@@ -692,14 +795,13 @@ workflow_definition:)assert msg is not None- assert "anti-bot challenge" in msg- assert "disabled submit/search control" in msg+ assert "Structured challenge evidence confirms this path is blocked" in msgassert ctx.blocker_signal is not None- assert ctx.blocker_signal.internal_reason_code == "tool_error_challenge_gated_submit_disabled"+ assert ctx.blocker_signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODEassert ctx.blocker_signal.renders_final_reply is True-def test_tool_loop_error_allows_challenge_gated_retry_with_changed_proxy_location() -> None:+def test_tool_loop_error_blocks_current_page_challenge_with_changed_proxy_location() -> None:ctx = _fresh_context()ctx.last_failed_workflow_yaml = """title: Registry standard credential lookup@@ -714,6 +816,7 @@ workflow_definition:)ctx.last_test_failure_reason = "The required Search button remains disabled after verification."ctx.composition_page_evidence = {+ "observed_after_workflow_run": True,"challenge_state": {"detected": True,"kind": "human_verification",@@ -731,18 +834,20 @@ workflow_definition:url: https://example.com/registry/search"""- assert (- _tool_loop_error(- ctx,- "update_and_run_blocks",- {- "workflow_yaml": changed_proxy_yaml,- "block_labels": ["fill_sample_record_search"],- },- )- is None+ msg = _tool_loop_error(+ ctx,+ "update_and_run_blocks",+ {+ "workflow_yaml": changed_proxy_yaml,+ "block_labels": ["fill_sample_record_search"],+ },)- assert ctx.challenge_gated_proxy_retry_count == 1++ assert msg is not None+ assert "do NOT try a proxy/location switch" in msg+ assert ctx.challenge_gated_proxy_retry_count == 0+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODEdef test_tool_loop_error_blocks_post_budget_challenge_even_with_changed_proxy_location() -> None:@@ -872,7 +977,7 @@ 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_failed_test() -> None:+def test_record_run_blocks_treats_structured_anti_bot_blocker_as_terminal_challenge() -> None:ctx = _fresh_context()ctx.workflow_yaml = "workflow_definition: {blocks: []}"result = {@@ -880,6 +985,7 @@ def test_record_run_blocks_treats_structured_anti_bot_blocker_as_failed_test() -"data": {"workflow_run_id": "wr_blocked","overall_status": "completed",+ "failure_categories": [{"category": "PARAMETER_BINDING_ERROR", "confidence_float": 0.95}],"blocks": [{"label": "extract_sample_credentials",@@ -901,14 +1007,142 @@ def test_record_run_blocks_treats_structured_anti_bot_blocker_as_failed_test() -_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_suspicious_success is Falseassert ctx.last_test_anti_bot is not Noneassert "Verify you are human" in ctx.last_test_failure_reasonassert ctx.last_failed_workflow_yaml == "workflow_definition: {blocks: []}"- assert result["data"]["failure_reason"] == (- "Run completed, but extracted data reported a blocker: Verify you are human"- )+ 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 ctx.last_failure_category_top == "ANTI_BOT_DETECTION"+ assert ctx.last_run_outcome is not None+ assert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"+ assert ctx.turn_halt is not None+++def test_record_run_blocks_treats_structured_browser_access_blocker_as_terminal_challenge() -> None:+ ctx = _fresh_context()+ ctx.workflow_yaml = "workflow_definition: {blocks: []}"+ result = {+ "ok": True,+ "data": {+ "workflow_run_id": "wr_blocked",+ "overall_status": "completed",+ "blocks": [+ {+ "label": "search_sample_records",+ "block_type": "CODE",+ "status": "completed",+ "extracted_data": {+ "status": "blocked",+ "blocker_type": "browser_port_forbidden",+ "blocker_evidence": (+ "The browser refused to render the requested localhost port before the search page loaded."+ ),+ "records": [],+ "record_count": 0,+ },+ }+ ],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_ok is False+ assert ctx.last_test_suspicious_success is False+ assert ctx.last_test_anti_bot is not None+ assert result["data"]["failure_reason"] == "Run output reported a blocker: browser_port_forbidden"assert result["data"]["failure_categories"][0]["category"] == "ANTI_BOT_DETECTION"+ assert ctx.last_failure_category_top == "ANTI_BOT_DETECTION"+ assert ctx.last_run_outcome is not None+ assert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+++def test_record_run_blocks_prefers_nested_port_blocker_over_status_shell() -> None:+ ctx = _fresh_context()+ result = {+ "ok": True,+ "data": {+ "workflow_run_id": "wr_blocked",+ "overall_status": "completed",+ "blocks": [+ {+ "label": "search_sample_records",+ "block_type": "CODE",+ "status": "completed",+ "extracted_data": {+ "status": "blocked",+ "query": "Sample",+ "records": [],+ "record_count": 0,+ "blocker": {+ "type": "browser_or_environment_port_block",+ "message": "The page shows a port-forbidden error instead of the target search UI.",+ },+ "evidence_text": "Requested port 8900 is forbidden",+ },+ }+ ],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_ok is False+ assert ctx.last_failure_category_top == "ANTI_BOT_DETECTION"+ assert ctx.last_run_outcome is not None+ assert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"+ assert ctx.turn_halt is not None+ assert "Requested port" in ctx.turn_halt.extra["evidence_reason"]+++def test_record_run_blocks_combines_status_blocked_with_page_challenge_evidence() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "captcha",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ "anti_bot_indicators": ["captcha", "verify you are human"],+ }+ result = {+ "ok": True,+ "data": {+ "workflow_run_id": "wr_blocked",+ "overall_status": "completed",+ "blocks": [+ {+ "label": "search_sample_records",+ "block_type": "CODE",+ "status": "completed",+ "extracted_data": {+ "status": "blocked",+ "records": [],+ "record_count": 0,+ },+ }+ ],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_ok is False+ assert ctx.last_test_suspicious_success is False+ assert ctx.last_failure_category_top == "ANTI_BOT_DETECTION"+ assert ctx.last_run_outcome is not None+ assert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+ assert "challenge-gated disabled submit/search control: Search" in ctx.turn_halt.extra["evidence_reason"]+ assert "Run output reported" in ctx.turn_halt.extra["evidence_reason"]def test_tool_loop_error_blocks_upstream_replay_after_post_budget_page_evidence() -> None:diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pyindex 61b4735c1..af5c16881 100644--- a/tests/unit/test_copilot_run_outcome_event.py+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -7,6 +7,7 @@ result rows; domains and person names are generic placeholders.from __future__ import annotationsimport inspect+import reimport timefrom types import SimpleNamespacefrom typing import Any@@ -92,6 +93,29 @@ def _blocked_run_result() -> dict[str, Any]:)+def _challenge_failure_result() -> dict[str, Any]:+ result = _run_result([], ok=False)+ result["error"] = "The run stopped on a terminal site challenge."+ result["data"]["workflow_run_id"] = "wr_challenge"+ result["data"]["failure_reason"] = "Human verification challenge blocked the search."+ result["data"]["failure_categories"] = [+ {+ "category": "ANTI_BOT_DETECTION",+ "confidence_float": 0.95,+ "reasoning": "Typed run analysis reported an anti-bot challenge.",+ }+ ]+ result["data"]["blocks"] = [+ {+ "label": "search_registry_person",+ "block_type": "CODE",+ "status": "failed",+ "failure_reason": "Human verification challenge blocked the search.",+ }+ ]+ return result++def _clean_run_result() -> dict[str, Any]:return _run_result([@@ -126,12 +150,12 @@ async def test_blocker_run_emits_hold_then_not_demonstrated() -> None:frames = _run_outcome_frames(ctx.stream) # type: ignore[arg-type]assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]final = frames[-1]- assert final.reason_code == "blocker_reported"+ assert final.reason_code == "terminal_challenge_blocker"assert final.workflow_run_id == "wr_test"assert final.workflow_run_block_ids == ["wrb_open_registry_search", "wrb_search_registry_person"]assert final.block_labels == ["open_registry_search", "search_registry_person"]assert final.display_reason is not None and "human verification challenge" in final.display_reason- assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_suspicious_success is Falseassert ctx.last_run_outcome == RecordedRunOutcome(verdict=final.verdict,reason_code=final.reason_code,@@ -141,6 +165,53 @@ async def test_blocker_run_emits_hold_then_not_demonstrated() -> None:assert ctx.last_run_outcome_block_labels == final.block_labels+def test_challenge_failure_records_terminal_blocker_outcome() -> None:+ result = _challenge_failure_result()+ ctx = _ctx(result["data"]["blocks"])++ outcome = _record_run_blocks_result(ctx, result, completion_verification=None)++ assert outcome == RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code="terminal_challenge_blocker",+ display_reason=run_outcome_display_reason(+ "Run output reported a blocker: Human verification challenge blocked the search."+ ),+ workflow_run_id="wr_challenge",+ )+ assert ctx.last_run_outcome == outcome+ assert ctx.last_test_ok is False+ assert ctx.last_test_suspicious_success is False+ assert ctx.last_test_anti_bot is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "tool_error_terminal_challenge_blocker"+ assert ctx.blocker_signal.extra["run_outcome_reason_code"] == "terminal_challenge_blocker"+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.extra["evidence_source"] == "structured_blocker"+++def test_challenge_failure_sanitizes_halt_metadata_reason() -> None:+ result = _challenge_failure_result()+ raw_reason = (+ "Human verification challenge blocked https://user:[email protected]/path?token=abc "+ "after password=topsecret was submitted."+ )+ result["data"]["failure_reason"] = raw_reason+ result["data"]["blocks"][0]["failure_reason"] = raw_reason+ ctx = _ctx(result["data"]["blocks"])++ _record_run_blocks_result(ctx, result, completion_verification=None)++ assert ctx.turn_halt is not None+ evidence_reason = ctx.turn_halt.extra["evidence_reason"]+ assert re.search(r"https://example\.com", evidence_reason) is not None+ assert "[REDACTED_SECRET]" in evidence_reason+ assert "user:secret" not in evidence_reason+ assert "password=" not in evidence_reason+ assert "topsecret" not in evidence_reason+ assert "token=abc" not in evidence_reason++@pytest.mark.asyncioasync def test_empty_data_run_emits_no_meaningful_output() -> None:result = _run_result([_code_block("search_registry_person", {"records": [], "result_count": 0})])@@ -350,6 +421,20 @@ def test_display_reason_collapses_whitespace_and_caps_length() -> None:assert run_outcome_display_reason(None) is None+def test_display_reason_redacts_secrets_and_url_credentials() -> None:+ reason = run_outcome_display_reason(+ "Blocked at https://user:[email protected]/path?token=abc after password=topsecret was submitted."+ )++ assert reason is not None+ assert re.search(r"https://example\.com", reason) is not None+ assert "[REDACTED_SECRET]" in reason+ assert "user:secret" not in reason+ assert "password=" not in reason+ assert "topsecret" not in reason+ assert "token=abc" not in reason++def _payload_ctx() -> CopilotContext:ctx = _ctx()workflow_blocks = [diff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.pyindex 1c3c583dd..f6b5b539c 100644--- a/tests/unit/test_copilot_run_output_content_gate.py+++ b/tests/unit/test_copilot_run_output_content_gate.py@@ -253,7 +253,7 @@ def test_blocked_flag_run_reports_structured_blocker() -> None:assert "human verification challenge" in blocker-def test_blocked_flag_run_records_suspicious_success() -> None:+def test_blocked_flag_run_records_terminal_challenge() -> None:result = _blocked_flag_run_result()ctx = _ctx(result["data"]["blocks"])@@ -262,16 +262,18 @@ def test_blocked_flag_run_records_suspicious_success() -> None:assert result["ok"] is Falseassert result["error"] == ctx.last_test_failure_reasonassert ctx.last_test_ok is False- assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_suspicious_success is Falseassert ctx.last_full_workflow_test_ok is Falseassert "reported a blocker" in (ctx.last_test_failure_reason or "")assert ctx.last_failed_workflow_yaml == "blocks: []"categories = result["data"]["failure_categories"]assert any(category["category"] == "ANTI_BOT_DETECTION" for category in categories)assert ctx.blocker_signal is not None- assert ctx.blocker_signal.internal_reason_code == "tool_error_run_output_terminal_blocker"+ assert ctx.blocker_signal.internal_reason_code == "tool_error_terminal_challenge_blocker"assert ctx.turn_halt is not Noneassert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+ assert ctx.last_run_outcome is not None+ assert ctx.last_run_outcome.reason_code == "terminal_challenge_blocker"assert verified_goal_satisfied_context(ctx) is Falseassert _verified_workflow_or_none(ctx) == (None, None)snapshot = getattr(ctx, "outcome_verification_trace_snapshot", {})@@ -294,7 +296,7 @@ def test_candidacy_and_recording_agree_on_blocked_run() -> None:_record_run_blocks_result(ctx, result, completion_verification=None)assert ctx.last_test_ok is False- assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_suspicious_success is False@pytest.mark.parametrize("block_type", ["CODE", "code"])@@ -310,11 +312,11 @@ def test_blocked_status_value_rejected_deterministically(block_type: str) -> Non_record_run_blocks_result(ctx, result, completion_verification=None)assert result["ok"] is Falseassert ctx.blocker_signal is not None- assert ctx.blocker_signal.internal_reason_code == "tool_error_run_output_terminal_blocker"+ assert ctx.blocker_signal.internal_reason_code == "tool_error_terminal_challenge_blocker"assert ctx.turn_halt is not Noneassert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGEassert ctx.last_test_ok is False- assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_suspicious_success is Falseassert ctx.last_full_workflow_test_ok is Falsediff --git a/tests/unit/test_copilot_turn_halt.py b/tests/unit/test_copilot_turn_halt.pyindex c8f4306a6..3efcdff10 100644--- a/tests/unit/test_copilot_turn_halt.py+++ b/tests/unit/test_copilot_turn_halt.py@@ -5,8 +5,18 @@ from types import SimpleNamespaceimport pytestfrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal-from skyvern.forge.sdk.copilot.enforcement import _check_enforcement+from skyvern.forge.sdk.copilot.enforcement import (+ _check_enforcement,+ _maybe_stash_terminal_challenge_halt,+ terminal_challenge_blocker_signal_from_current_page_evidence,+ terminal_challenge_blocker_signal_from_page_evidence,+)from skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE+from skyvern.forge.sdk.copilot.run_outcome import (+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ RecordedRunOutcome,+)from skyvern.forge.sdk.copilot.turn_halt import (CopilotTurnHalt,TurnHaltKind,@@ -21,6 +31,7 @@ def _signal(blocker_kind: str = "tool_error",internal_reason_code: str = ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,renders_final_reply: bool = True,+ extra: dict[str, object] | None = None,) -> CopilotToolBlockerSignal:return CopilotToolBlockerSignal(blocker_kind=blocker_kind,@@ -32,6 +43,7 @@ def _signal(renders_final_reply=renders_final_reply,internal_reason_code=internal_reason_code,blocked_tool="update_and_run_blocks",+ extra=extra or {},)@@ -50,6 +62,10 @@ def _signal(_signal(internal_reason_code="tool_error_run_output_terminal_blocker"),TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE,),+ (+ _signal(internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE),+ TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE,+ ),(_signal(internal_reason_code="probable_site_block_stop"), TurnHaltKind.PROBABLE_SITE_BLOCK),],)@@ -84,3 +100,205 @@ def test_enforcement_backstop_converts_existing_terminal_blocker_signal() -> Nonassert ctx.turn_halt is exc_info.value.haltassert exc_info.value.halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE+++def test_terminal_challenge_halt_preserves_signal_extra() -> None:+ ctx = SimpleNamespace(turn_halt=None)+ signal = _signal(+ internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ extra={+ "run_outcome_reason_code": "terminal_challenge_blocker",+ "evidence_source": "failure_category",+ "source": "signal_extra",+ },+ )++ halt = stash_turn_halt_from_blocker_signal(ctx, signal, source="run_execution")++ assert halt is not None+ assert halt.extra["source"] == "run_execution"+ assert halt.extra["run_outcome_reason_code"] == "terminal_challenge_blocker"+ assert halt.extra["evidence_source"] == "failure_category"+++def test_terminal_challenge_backstop_preserves_existing_halt() -> None:+ signal = _signal(internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE)+ existing_halt = turn_halt_from_blocker_signal(signal, source="run_execution")+ ctx = SimpleNamespace(+ turn_halt=existing_halt,+ blocker_signal=None,+ latest_tool_blocker_signal=None,+ last_run_outcome=RecordedRunOutcome(+ verdict="not_demonstrated",+ reason_code=TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE,+ display_reason="Challenge detected.",+ ),+ )++ _maybe_stash_terminal_challenge_halt(ctx)++ assert ctx.turn_halt is existing_halt+ assert ctx.blocker_signal is None+++def test_page_challenge_signal_records_explicit_terminal_blocker() -> None:+ ctx = SimpleNamespace(+ last_run_blocks_workflow_run_id=None,+ composition_page_evidence={+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ },+ )++ signal = terminal_challenge_blocker_signal_from_page_evidence(ctx, blocked_tool="update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+ assert signal.extra["run_outcome_reason_code"] == TERMINAL_CHALLENGE_RUN_OUTCOME_REASON_CODE+ assert signal.extra["evidence_source"] == "page_evidence"+ assert signal.extra["evidence_reason"] == "human verification requires manual completion"+ assert signal.extra["workflow_run_id"] is None+ assert signal.blocked_tool == "update_and_run_blocks"+++def test_current_page_challenge_signal_does_not_halt_before_bounded_attempt() -> None:+ ctx = SimpleNamespace(+ last_failure_category_top=None,+ last_run_blocks_workflow_run_id=None,+ composition_page_evidence={+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ },+ )++ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool="update_and_run_blocks",+ )++ assert signal is None+++def test_current_page_challenge_signal_does_not_defer_to_empty_result_shell() -> None:+ ctx = SimpleNamespace(+ last_failure_category_top=None,+ last_run_blocks_workflow_run_id=None,+ composition_page_evidence={+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ "result_containers": [{"selector": "#results", "text_excerpt": "Results"}],+ },+ )++ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool="evaluate",+ )++ assert signal is not None+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+++def test_current_page_challenge_signal_does_not_defer_to_form_container_text() -> None:+ ctx = SimpleNamespace(+ last_failure_category_top=None,+ last_run_blocks_workflow_run_id=None,+ composition_page_evidence={+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "captcha",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ "result_containers": [+ {+ "tag": "form",+ "selector": "#record-search",+ "text_excerpt": (+ "First name Last name Results No records are available because the anti-bot "+ "challenge prevented the search from running."+ ),+ }+ ],+ },+ )++ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool="update_and_run_blocks",+ )++ assert signal is not None+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+++def test_current_page_challenge_signal_reads_flow_evidence_packets() -> None:+ ctx = SimpleNamespace(+ flow_evidence=[+ {+ "observation_step": 1,+ "evidence": {+ "observed_after_workflow_run": True,+ "challenge_state": {+ "detected": True,+ "kind": "captcha",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ "result_containers": [{"selector": "#results", "text_excerpt": "Results"}],+ },+ }+ ],+ last_failure_category_top=None,+ last_run_blocks_workflow_run_id=None,+ )++ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool="update_and_run_blocks",+ )++ assert signal is not None+ assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE+++def test_current_page_challenge_signal_defers_to_populated_result_container_evidence() -> None:+ ctx = SimpleNamespace(+ last_failure_category_top=None,+ last_run_blocks_workflow_run_id=None,+ composition_page_evidence={+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": False,+ "gates_submit_controls": False,+ },+ "result_containers": [{"selector": "#results", "row_count": 1, "sample_rows": ["Visible result row"]}],+ },+ )++ signal = terminal_challenge_blocker_signal_from_current_page_evidence(+ ctx,+ blocked_tool="evaluate",+ )++ assert signal is None