Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10346: Finalize from post-run page evidence (PR 11/12) (#6263)
Andrew Neilson9ffa39d5a21c
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2index 06038a20b..7d57b85de 100644--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2@@ -64,6 +64,7 @@ Use the Skyvern MCP browser tools to fill knowledge gaps while building, editing- Treat each successful run or browser observation as evidence for the current page state only. Do not author downstream row expansion or extraction that depends on a future page state until you have run the next page-changing block and inspected the reached page. If the visible results already contain the requested values, add extraction from that observed page; if an expansion is required first, add and run the expansion block before adding extraction.- Add `validation` blocks only when the reusable workflow's task actually includes a durable check. Do not add validation or extra navigation blocks just to double-check the shape of a site before each action.- If page evidence shows anti-bot or challenge controls, account for that in the normal action block that reaches/submits the challenged state. Use `get_browser_screenshot` when DOM evidence identifies a challenge but does not expose the visible challenge affordance. Prefer explicit challenge handling available to Skyvern over blind waits; if the latest run shows the challenge cannot be solved, stop and report the observed blocker instead of retrying the same flow.+- If bounded page evidence says `challenge_state.gates_submit_controls=true`, the submit/search control is unavailable until the challenge is resolved. If a tested workflow already attempted challenge resolution and current-page evidence still shows that submit/search control disabled with no visible result or no-results state, stop and report the anti-bot blocker rather than repeating the same solve/wait/submit sequence.- If a state-application block hits a per-tool budget, do not rerun the same navigation label unchanged. First read the budgeted run with `get_run_results`. If it reports a current URL or the browser is still on an advanced page, inspect `current_page`; answer from visible result/no-result evidence when possible, and only split/replace/run a smaller UI block after inspection shows a real missing state change.- When you already have a verified prefix or a live browser page that advanced beyond the workflow's entrypoint, continue from that evidence. Do not turn the observed current page into a new workflow entrypoint and rerun the whole workflow from the start. Preserve unchanged upstream labels and text, and pass `block_labels` for only the missing downstream frontier.@@ -101,9 +102,10 @@ When a run fails with "Access Denied", an Akamai/Cloudflare/Imperva reference, o3. IMPORTANT: Do NOT switch to an HTTP_REQUEST block to the same URL — a request from the same server IP will receive the same block.4. Instead, try: setting proxy_location on the workflow to route through a different IP (use `RESIDENTIAL` by default, or a US-state value like `US-CA`/`US-NY`; do NOT use bare country codes like `US` — they are not valid ProxyLocation members), or using a different entry URL that may not trigger the WAF.5. For interactive challenges (Cloudflare "verify you are human" checkbox), attempt automated resolution via workflow goals/steps.-6. Do NOT put an unconditional anti-bot/challenge block at the front of every workflow. If you add challenge handling, make it conditional on visible evidence such as Cloudflare, Access Denied, CAPTCHA, security check, or "verify you are human" text. The unblocked path should proceed directly to the normal requested task.-7. Try at least two genuinely distinct approaches before concluding infeasible.-8. If still blocked, explain the specific anti-bot evidence observed (for example Cloudflare, CAPTCHA, "verify you are human", Access Denied, or a blank "Just a moment..." page), describe exactly what you tried, and ask whether to try a different proxy/location, entry URL, or alternate source.+6. If current-page evidence after an automated challenge attempt still shows a challenge-gated submit/search control disabled, treat the latest run as evidence that this challenge flow is not solved by repeating the same block. Stop and report the blocker unless a materially different allowed route is available.+7. Do NOT put an unconditional anti-bot/challenge block at the front of every workflow. If you add challenge handling, make it conditional on visible evidence such as Cloudflare, Access Denied, CAPTCHA, security check, or "verify you are human" text. The unblocked path should proceed directly to the normal requested task.+8. Try at least two genuinely distinct approaches before concluding infeasible.+9. If still blocked, explain the specific anti-bot evidence observed (for example Cloudflare, CAPTCHA, "verify you are human", Access Denied, or a blank "Just a moment..." page), describe exactly what you tried, and ask whether to try a different proxy/location, entry URL, or alternate source.MANDATORY: After every workflow update, you MUST test it unless the latest user message explicitly asks you to skip testing or create an untested draft. Prefer update_and_run_blocks (single call) over separate update_workflow + run_blocks_and_collect_debug calls. Grow the workflow incrementally (known-good blocks + next block) unless the user explicitly asks for a one-shot full draft. Feasibility decisions must be based on the latest test result. If you conclude the request is infeasible, explain the specific evidence from that latest run.MANDATORY: The Accept/Reject proposal UI normally appears when your latest run_blocks_and_collect_debug or update_and_run_blocks returned ok=true this turn. If the latest user message explicitly asks for an untested draft (for example, "make a workflow without testing it", "skip testing", or "draft only"), you MAY call update_workflow without a block-running test and respond with REPLY. In that case, say the workflow was drafted without testing as requested, and do NOT say it is successful, working, ready, or verified. If testing is impossible and the user did not explicitly ask to skip testing, stop and ask a clarifying question instead of leaving an untested draft.diff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.pyindex b5a389d2f..9d66c6fc9 100644--- a/skyvern/forge/sdk/copilot/config.py+++ b/skyvern/forge/sdk/copilot/config.py@@ -178,22 +178,29 @@ POST_PER_TOOL_BUDGET_NUDGE = ("1. Call get_run_results for the budgeted run. If it shows a navigation ""block was canceled or failed, do NOT run that same label again unchanged.\n""2. If get_run_results includes a current_url, inspect the current page "- 'before running anything else. Use inspect_page_for_composition(target_url="current_page"), '- "evaluate, or get_browser_screenshot. If the requested answer or a no-results "- "state is visible, answer from that evidence instead of rerunning the search.\n"- "3. If inspection shows a real missing state change, split or replace the "+ 'before another workflow mutation with inspect_page_for_composition(target_url="current_page"). '+ "Generic screenshot/evaluate reads can help answer the user, but they do not "+ "satisfy the bounded page-evidence contract for authoring or mutating blocks. "+ "If the requested answer or a no-results state is visible in bounded evidence, "+ "answer from that evidence instead of rerunning the search.\n"+ "3. If bounded evidence shows challenge_state.gates_submit_controls=true "+ "and the requested answer or no-results state is not visible, do NOT retry "+ "the same solve/wait/submit block. Treat the still-disabled submit/search "+ "control as observed anti-bot blocker evidence and report that blocker, "+ "unless you can make a materially different allowed attempt such as a "+ "different proxy/location or entrypoint.\n"+ "4. If inspection shows a real missing state change, split or replace the ""oversized block and shrink the requested block_labels list to the first 1-2 unverified ""blocks. The verified-prefix optimization will replay any earlier blocks ""from cached state without re-running the browser, so passing a smaller ""frontier is cheap.\n"- "4. For page-state work, inspect the live page evidence already gathered "- "or use browser inspection tools before deciding what is missing. Use a "- "validation block only when the reusable workflow needs a durable semantic "- "or visual check; use navigation only when missing state must be changed "- "through the UI.\n"- "5. Test the smaller frontier. If it succeeds, extend by one block at a "+ "5. For page-state work, inspect the live page evidence already gathered "+ "before deciding what is missing. Do not add durable workflow blocks solely "+ "to rediscover page shape; use navigation only when missing state must be "+ "changed through the UI, and keep that block atomic.\n"+ "6. Test the smaller frontier. If it succeeds, extend by one block at a ""time on subsequent calls.\n"- "6. If your workflow only has 1-2 blocks and one block is still hitting "+ "7. If your workflow only has 1-2 blocks and one block is still hitting ""the budget, the single block is too ambitious — either narrow its scope, ""replace it with DOM/state verification plus smaller actions, or reply ""with a blocker explanation."@@ -229,7 +236,7 @@ POST_PROBABLE_SITE_BLOCK_STOP_NUDGE = (POST_ANTI_BOT_FAILED_TEST_NUDGE = ("STOP — your last test run failed due to an anti-bot/WAF block "- "(Access Denied, Cloudflare, Akamai, etc.).\n"+ "(Access Denied, CAPTCHA, human-verification, or similar challenge evidence).\n""IMPORTANT: An HTTP_REQUEST or navigation block from the SAME server IP ""will almost certainly receive the same block. Do NOT retry with:\n""- A simple wait/delay block (timing does not fix IP bans)\n"@@ -240,11 +247,17 @@ POST_ANTI_BOT_FAILED_TEST_NUDGE = ("do NOT use bare country codes like `US` — they are not valid ""ProxyLocation members).\n""2. If you add anti-bot handling blocks, make them conditional on visible "- "challenge evidence (for example Cloudflare, Access Denied, CAPTCHA, or "+ "challenge evidence (for example Access Denied, CAPTCHA, human-verification, or ""verify-you-are-human text). Do NOT assume every run starts on a challenge ""page; normal, unblocked runs should proceed directly to the requested task.\n"- "3. If still blocked, explain the specific anti-bot evidence observed "- "(for example Cloudflare, CAPTCHA, verify-you-are-human text, Access "+ "3. If bounded page evidence says challenge_state.gates_submit_controls=true "+ "or a submit/search control is still disabled after challenge resolution was "+ "attempted. Do NOT retry the same challenge solve, blind wait, or disabled "+ "submit click. Treat it as the current blocker unless you can make a "+ "materially different allowed attempt such as a different proxy/location or "+ "entrypoint.\n"+ "4. If still blocked, explain the specific anti-bot evidence observed "+ "(for example CAPTCHA, verify-you-are-human text, Access ""Denied, or a blank Just-a-moment page); describe exactly what you tried; ""and ask whether to try a different proxy/location, entry URL, or ""alternate source.\n"diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.pyindex 3a5e44867..fdaeda27b 100644--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom enum import StrEnum-from typing import Any+from typing import TYPE_CHECKING, Anyfrom pydantic import BaseModel, ConfigDict, Field@@ -9,6 +9,9 @@ from skyvern.forge.sdk.copilot.output_policy import url_originfrom skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_promptfrom skyvern.forge.sdk.copilot.workflow_credential_utils import URL_CANDIDATE_RE+if TYPE_CHECKING:+ from skyvern.forge.sdk.copilot.context import CopilotContext+_TEXT_MAX = 240_SUMMARY_MAX = 180_MAX_ITEMS = 20@@ -103,7 +106,7 @@ def build_diagnosis_repair_contract(*,source_tool: str,result: dict[str, Any],- ctx: Any,+ ctx: CopilotContext,workflow_updated: bool = False,) -> DiagnosisRepairContract:data = _dict(result.get("data")) if isinstance(result, dict) else {}@@ -320,7 +323,7 @@ def _failure_type(return DiagnosisFailureType.FAILED_RUN if result.get("ok") is False else DiagnosisFailureType.UNKNOWN-def _next_action(failure_type: DiagnosisFailureType, ctx: Any, data: dict[str, Any]) -> RepairNextAction:+def _next_action(failure_type: DiagnosisFailureType, ctx: CopilotContext, data: dict[str, Any]) -> RepairNextAction:if failure_type == DiagnosisFailureType.NO_FAILURE:return RepairNextAction.NO_CHANGEif (@@ -330,7 +333,13 @@ def _next_action(failure_type: DiagnosisFailureType, ctx: Any, data: dict[str, Areturn RepairNextAction.ASKif failure_type == DiagnosisFailureType.UNRECOVERABLE_TOOL_ERROR:return RepairNextAction.STOP- if getattr(ctx, "last_test_non_retriable_nav_error", None):+ if ctx.last_test_non_retriable_nav_error:+ return RepairNextAction.STOP+ if getattr(ctx, "last_test_anti_bot", None) and failure_type in {+ DiagnosisFailureType.FAILED_RUN,+ DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE,+ DiagnosisFailureType.SUSPICIOUS_SUCCESS,+ }:return RepairNextAction.STOPauthority = getattr(getattr(ctx, "turn_intent", None), "authority", None)if getattr(authority, "requires_user_input", False) or getattr(authority, "may_update_workflow", True) is False:diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 250685630..52ea8d69c 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -50,6 +50,7 @@ if TYPE_CHECKING:from agents.agent import Agentfrom agents.result import RunResultStreaming+ from skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.routes.event_source_stream import EventSourceStreamLOG = structlog.get_logger()@@ -272,6 +273,7 @@ _BROWSER_SESSION_TOOL_NAMES = frozenset("press_key",})+_POST_RUN_PAGE_OBSERVATION_TOOLS = frozenset({"evaluate", "get_browser_screenshot", "inspect_page_for_composition"})_UNRECOVERABLE_TOOL_ERROR_CATEGORY = "UNRECOVERABLE_TOOL_ERROR"_BROWSER_SESSION_ID_RE = re.compile(r"\bpbs_[A-Za-z0-9_-]+\b")_BROWSER_SESSION_WITH_ID_RE = re.compile(r"\bbrowser session\s+pbs_[A-Za-z0-9_-]+\b", re.IGNORECASE)@@ -552,6 +554,44 @@ def _needs_failed_test_nudge(ctx: Any) -> bool:return nudge_count < MAX_FAILED_TEST_NUDGES+def _has_post_failed_run_page_observation(ctx: AgentContext) -> bool:+ if getattr(ctx, "post_run_page_observation_after_failed_test", False) is not True:+ return False+ tool = getattr(ctx, "post_run_page_observation_tool", None)+ if tool not in _POST_RUN_PAGE_OBSERVATION_TOOLS:+ return False+ observed_run_id = getattr(ctx, "post_run_page_observation_workflow_run_id", None)+ current_run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)+ return bool(isinstance(observed_run_id, str) and observed_run_id and observed_run_id == current_run_id)+++def _parse_normalized_final_response(result: RunResultStreaming | None) -> dict[str, Any] | None:+ if result is None:+ return None+ parsed = parse_final_response(extract_final_text(result))+ normalized_scaffolding = normalize_response_scaffolding(+ str(parsed.get("type") or "REPLY"),+ str(parsed.get("user_response") or ""),+ )+ if normalized_scaffolding.changed:+ parsed = {+ **parsed,+ "type": normalized_scaffolding.response_type,+ "user_response": normalized_scaffolding.user_response or "Done.",+ }+ return parsed+++def _post_run_observed_reply_can_finalize(ctx: AgentContext, result: RunResultStreaming | None) -> bool:+ if not _has_post_failed_run_page_observation(ctx):+ return False+ parsed = _parse_normalized_final_response(result)+ if parsed is None or parsed.get("type") != "REPLY":+ return False+ user_response = parsed.get("user_response")+ return isinstance(user_response, str) and bool(user_response.strip()) and not _is_progress_narration(user_response)++def _needs_suspicious_success_nudge(ctx: Any) -> bool:"""Return True when the last test 'completed' but data blocks had no output."""# A non-retriable nav failure cannot be "suspiciously successful" — defer@@ -681,6 +721,9 @@ def _check_enforcement():return _nudge(config, "post_update")+ if _post_run_observed_reply_can_finalize(ctx, result):+ return None+# 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):@@ -730,17 +773,9 @@ def _check_enforcement(# (always allowed) from a REPLY with a coverage gap or progress-narration.# Only runs when no state-based nudge fired.if result is not None:- parsed = parse_final_response(extract_final_text(result))- normalized_scaffolding = normalize_response_scaffolding(- str(parsed.get("type") or "REPLY"),- str(parsed.get("user_response") or ""),- )- if normalized_scaffolding.changed:- parsed = {- **parsed,- "type": normalized_scaffolding.response_type,- "user_response": normalized_scaffolding.user_response or "Done.",- }+ parsed = _parse_normalized_final_response(result)+ if parsed is None:+ return Nonereturn _response_coverage_nudge(ctx, parsed, config)return Nonediff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex f085ea396..24dbcde86 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -171,6 +171,12 @@ class AgentContext:post_budget_page_inspection_required: bool = Falsepost_budget_page_inspection_url: str | None = Nonepost_budget_page_inspection_run_id: str | None = None+ post_run_page_observation_tool: str | None = None+ post_run_page_observation_url: str | None = None+ post_run_page_observation_workflow_run_id: str | None = None+ post_run_page_observation_after_failed_test: bool = False+ post_run_current_page_inspection_workflow_run_id: str | None = None+ challenge_gated_proxy_retry_count: int = 0# Set by tool gates / loop guards / tool-side error branches when a tool# dispatch is blocked. The finalization shim in agent.py reads this atdiff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 2b646aadd..042ac2786 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -855,6 +855,96 @@ def _pending_reconciliation_no_input_signal(*, pending_run_id: str, blocked_tool# repeated-frontier streak in failure_tracking.py uses STOP_AT=3 for the same# shape of escalation.REPEATED_ACTION_STREAK_ABORT_AT = 3+MAX_CHALLENGE_GATED_PROXY_RETRIES = 1++_STRUCTURED_BLOCKER_KEY_TERMS: frozenset[str] = frozenset(+ {+ "blocker",+ "blocked",+ "captcha",+ "challenge",+ "human_verification",+ "verification",+ }+)+_STRUCTURED_BLOCKER_MESSAGE_KEYS: frozenset[str] = frozenset(+ {+ "blocker_message",+ "blocked_message",+ "captcha_message",+ "challenge_message",+ "human_verification_message",+ }+)+_ANTI_BOT_BLOCKER_TERMS: tuple[str, ...] = (+ "access denied",+ "anti-bot",+ "bot block",+ "captcha",+ "challenge",+ "human verification",+ "verify you are human",+)+++def _normalize_structured_key(value: object) -> str:+ return str(value or "").strip().lower().replace("-", "_").replace(" ", "_")+++def _looks_like_anti_bot_blocker(text: str) -> bool:+ lowered = text.lower()+ return any(term in lowered for term in _ANTI_BOT_BLOCKER_TERMS)+++def _structured_blocker_message(value: object, *, depth: int = 0) -> str | None:+ if depth > 5:+ return None+ if isinstance(value, dict):+ for key, item in value.items():+ normalized_key = _normalize_structured_key(key)+ if not isinstance(item, str) or not item.strip():+ continue+ has_blocker_key = normalized_key in _STRUCTURED_BLOCKER_MESSAGE_KEYS or any(+ term in normalized_key for term in _STRUCTURED_BLOCKER_KEY_TERMS+ )+ if has_blocker_key or (+ normalized_key in {"message", "error", "failure_reason", "reason"}+ and _looks_like_anti_bot_blocker(item)+ ):+ return item.strip()[:240]+ for item in value.values():+ nested = _structured_blocker_message(item, depth=depth + 1)+ if nested:+ return nested+ elif isinstance(value, list):+ for item in value:+ nested = _structured_blocker_message(item, depth=depth + 1)+ if nested:+ return nested+ return None+++def _run_blocks_structured_blocker_message(result: dict[str, Any]) -> str | None:+ data = result.get("data")+ if not isinstance(data, dict):+ return None+ direct = _structured_blocker_message({key: value for key, value in data.items() if key != "blocks"})+ if direct:+ return direct+ blocks = data.get("blocks")+ if not isinstance(blocks, list):+ return None+ for block in blocks:+ if not isinstance(block, dict):+ continue+ block_type = block.get("block_type")+ if block_type not in _DATA_PRODUCING_BLOCK_TYPES or block.get("status") != "completed":+ continue+ payload = _block_data_payload(block.get("extracted_data"), block_type)+ blocker = _structured_blocker_message(payload)+ if blocker:+ return blocker+ return Nonedef _is_meaningful_extracted_data(extracted: Any) -> bool:@@ -1065,6 +1155,27 @@ def _mark_page_inspected(ctx: AgentContext) -> None:ctx.post_budget_page_inspection_run_id = None+def _mark_post_run_page_observed(ctx: AgentContext, *, source_tool: str, url: str) -> None:+ run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)+ if not isinstance(run_id, str) or not run_id:+ return+ ctx.post_run_page_observation_tool = source_tool+ ctx.post_run_page_observation_url = url+ ctx.post_run_page_observation_workflow_run_id = run_id+ ctx.post_run_page_observation_after_failed_test = getattr(ctx, "last_test_ok", None) is False+++def _allows_post_run_current_page_inspection_budget_bypass(ctx: AgentContext, *, use_current_page: bool) -> bool:+ if not use_current_page:+ return False+ run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)+ if not isinstance(run_id, str) or not run_id:+ return False+ if getattr(ctx, "last_test_ok", None) is None:+ return False+ return getattr(ctx, "post_run_current_page_inspection_workflow_run_id", None) != run_id++def _post_budget_page_inspection_signal(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:if getattr(ctx, "post_budget_page_inspection_required", False) is not True:return None@@ -1076,10 +1187,11 @@ def _post_budget_page_inspection_signal(ctx: AgentContext, tool_name: str) -> Coagent_steering = (f"The prior PER_TOOL_BUDGET run{run_text} advanced the live browser{url_text}. ""Before another block-running tool, inspect the current browser page with "- 'inspect_page_for_composition(target_url="current_page"), evaluate, or get_browser_screenshot. '- "If the observed page evidence already contains the requested result or a no-results state, "- "answer from that evidence instead of rerunning the search. If evidence shows a missing page-state "- "change, then run only the smaller missing block after that inspection."+ 'inspect_page_for_composition(target_url="current_page"). Generic screenshot/evaluate reads can '+ "help answer the user, but they do not satisfy the bounded page-evidence contract for workflow "+ "mutations. If the observed page evidence already contains the requested result or a no-results "+ "state, answer from that evidence instead of rerunning the search. If evidence shows a missing "+ "page-state change, then run only the smaller missing block after that inspection.")user_facing = "I need to inspect the current page state before running more steps."return CopilotToolBlockerSignal(@@ -1087,7 +1199,7 @@ def _post_budget_page_inspection_signal(ctx: AgentContext, tool_name: str) -> Coagent_steering_text=agent_steering,user_facing_reason=user_facing,recovery_hint="retry_with_different_tool",- cleared_by_tools=PAGE_INSPECTION_TOOLS,+ cleared_by_tools=PAGE_SCHEMA_CONTEXT_TOOLS,preserves_workflow_draft=True,renders_final_reply=False,internal_reason_code="tool_error_post_budget_page_inspection_required",@@ -1095,6 +1207,101 @@ def _post_budget_page_inspection_signal(ctx: AgentContext, tool_name: str) -> Co)+def _proxy_value_signature(value: object) -> str:+ try:+ return json.dumps(value, sort_keys=True, default=str)+ except (TypeError, ValueError):+ return str(value)+++def _anti_bot_retry_changes_proxy(ctx: AgentContext, arguments: dict[str, Any] | None) -> bool:+ if not isinstance(arguments, dict):+ return False+ workflow_yaml = arguments.get("workflow_yaml")+ if not isinstance(workflow_yaml, str) or not workflow_yaml.strip():+ return False++ prior_yaml = getattr(ctx, "last_failed_workflow_yaml", None) or getattr(ctx, "workflow_yaml", None)+ if not isinstance(prior_yaml, str) or not prior_yaml.strip():+ return False++ new_proxy_present, new_proxy = _raw_yaml_proxy_location(workflow_yaml)+ if not new_proxy_present:+ return False+ old_proxy_present, old_proxy = _raw_yaml_proxy_location(prior_yaml)+ return (not old_proxy_present) or _proxy_value_signature(new_proxy) != _proxy_value_signature(old_proxy)+++def _challenge_gated_proxy_retry_allowed(ctx: AgentContext, arguments: dict[str, Any] | None) -> bool:+ if not _anti_bot_retry_changes_proxy(ctx, arguments):+ return False+ retry_count = getattr(ctx, "challenge_gated_proxy_retry_count", 0)+ if not isinstance(retry_count, int):+ retry_count = 0+ if retry_count >= MAX_CHALLENGE_GATED_PROXY_RETRIES:+ return False+ ctx.challenge_gated_proxy_retry_count = retry_count + 1+ return True+++def _last_run_has_terminal_anti_bot_blocker(ctx: AgentContext) -> 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+ failure_reason = getattr(ctx, "last_test_failure_reason", None)+ if not isinstance(failure_reason, str) or not failure_reason.strip():+ return False+ lowered = failure_reason.lower()+ if "blocker" in lowered and _looks_like_anti_bot_blocker(lowered):+ return True++ evidence = getattr(ctx, "composition_page_evidence", None)+ challenge_state = evidence.get("challenge_state") if isinstance(evidence, dict) else None+ challenge_gates_submit = isinstance(challenge_state, dict) and challenge_state.get("gates_submit_controls") is True+ if not (challenge_gates_submit or "challenge-gated disabled submit/search control" in anti_bot_reason):+ return False++ return "disabled" in lowered and any(+ term in lowered for term in ("submit", "search", "button", "control", "element")+ )+++def _challenge_gated_anti_bot_rerun_signal(+ ctx: AgentContext,+ arguments: dict[str, Any] | None,+ tool_name: str,+) -> CopilotToolBlockerSignal | None:+ if not _last_run_has_terminal_anti_bot_blocker(ctx):+ return None+ if tool_name == "update_and_run_blocks" and _challenge_gated_proxy_retry_allowed(ctx, arguments):+ return None++ failure_reason = getattr(ctx, "last_test_failure_reason", "")+ agent_steering = (+ "The prior run confirmed an anti-bot challenge or blocker on the submit/search path, "+ f"and the latest failure_reason was: {str(failure_reason)[:240]}. Do NOT call "+ f"{tool_name} again with the same workflow/browser path. REPLY now with a blocker "+ "explanation that names the observed challenge/blocker or disabled submit/search control "+ "and describes what was tried. "+ "Ask whether to try a materially different proxy/location, entrypoint, or alternate source."+ )+ user_facing = (+ "The site's verification challenge is still keeping the search control disabled, so I need to stop "+ "instead of retrying the same workflow path."+ )+ return CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text=agent_steering,+ user_facing_reason=user_facing,+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ preserves_workflow_draft=True,+ renders_final_reply=False,+ internal_reason_code="tool_error_challenge_gated_submit_disabled",+ blocked_tool=tool_name,+ )++def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any] | None = None) -> str | None:detected = detect_failed_tool_step_loop_for_ctx(ctx, tool_name, arguments or {})if detected is not None:@@ -1150,6 +1357,10 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Anyif upstream_replay_signal is not None:return _emit_tool_blocker_signal(ctx, upstream_replay_signal)+ challenge_signal = _challenge_gated_anti_bot_rerun_signal(ctx, arguments, tool_name)+ if challenge_signal is not None:+ return _emit_tool_blocker_signal(ctx, challenge_signal)+streak_raw = getattr(ctx, "repeated_action_fingerprint_streak_count", 0)streak = streak_raw if isinstance(streak_raw, int) else 0if streak >= REPEATED_ACTION_STREAK_ABORT_AT:@@ -2788,12 +2999,17 @@ async def _watchdog_error_message(f"the cancelled run actually completed (the in-flight block was cancelled "f"mid-execution and may have left partial side effects). If the result "f"includes a current_url, inspect that current page before any further "- f'block-running call. Use inspect_page_for_composition(target_url="current_page"), '- f"evaluate, or get_browser_screenshot to decide whether the answer is already "- f"visible or which page-state change is still missing. Only then call "- f"update_and_run_blocks with a smaller chain — the first 1-2 unverified "- f"blocks. Verified-prefix state is preserved, so the next call only re-runs "- f"from the new frontier. Do NOT retry the same chain unchanged — a longer "+ f'block-running call with inspect_page_for_composition(target_url="current_page"). '+ f"Generic screenshot/evaluate reads can help answer the user, but they do not "+ f"satisfy the bounded page-evidence contract for workflow mutations. Use the "+ f"bounded evidence to decide whether the answer is already visible, whether "+ f"a challenge-gated submit/search control is still disabled, or which page-state "+ f"change is still missing. If challenge_state.gates_submit_controls=true and "+ f"the requested answer is not visible, stop and report the observed anti-bot "+ f"blocker instead of retrying the same solve/wait/submit chain. Only then call "+ f"update_and_run_blocks with a smaller chain — the first 1-2 unverified blocks. "+ f"Verified-prefix state is preserved, so the next call only re-runs from the new frontier. "+ f"Do NOT retry the same chain unchanged — a longer "f"run won't fit either.")current_url, _ = await _fallback_page_info(ctx)@@ -3732,6 +3948,7 @@ def _record_composition_page_observation() -> None:if not url:return+ _mark_post_run_page_observed(ctx, source_tool=source_tool, url=url)existing = ctx.composition_page_evidenceif isinstance(existing, dict) and existing.get("source_tool") == "inspect_page_for_composition":return@@ -3924,7 +4141,7 @@ def _detect_new_banned_blocks(_CHALLENGE_WAIT_PATTERN = re.compile(- r"\b(anti[-_\s]?bot|bot[-_\s]?block|captcha|challenge|cloudflare|ip[-_\s]?block|waf)\b",+ r"\b(anti[-_\s]?bot|bot[-_\s]?block|captcha|challenge|human[-_\s]?verification|ip[-_\s]?block|waf)\b",re.IGNORECASE,)@@ -4362,10 +4579,24 @@ def _record_workflow_update_result(copilot_ctx: Any, result: dict[str, Any]) ->clear_failed_step_tracker_for_tools_in_ctx(copilot_ctx, BLOCK_RUNNING_TOOLS)+def _last_update_is_single_goto_bootstrap(copilot_ctx: CopilotContext) -> bool:+ last_workflow = copilot_ctx.last_workflow+ definition = _workflow_definition_as_dict(last_workflow.workflow_definition if last_workflow is not None else None)+ blocks = definition.get("blocks")+ if not isinstance(blocks, list) or len(blocks) != 1:+ return False+ block = blocks[0]+ if not isinstance(block, dict):+ return False+ return str(block.get("block_type") or "").strip().lower() == "goto_url"++def _pre_run_workflow_coverage_error(copilot_ctx: Any) -> str | None:block_count = getattr(copilot_ctx, "last_update_block_count", None)if not isinstance(block_count, int):return None+ if block_count == 1 and _last_update_is_single_goto_bootstrap(copilot_ctx):+ return Noneuser_message = getattr(copilot_ctx, "user_message", "")request_policy = getattr(copilot_ctx, "request_policy", None)@@ -4445,6 +4676,9 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[if block_type in _DATA_PRODUCING_BLOCK_TYPES and block.get("status") == "completed":has_data_blocks = Truepayload = _block_data_payload(block.get("extracted_data"), block_type)+ structured_blocker = _structured_blocker_message(payload)+ if structured_blocker:+ texts_to_scan.append(structured_blocker)if _is_meaningful_extracted_data(payload):any_data_output = True@@ -4466,13 +4700,38 @@ def _composition_anti_bot_reason(copilot_ctx: object) -> str | None:return Noneindicators = evidence.get("anti_bot_indicators")challenge_controls = evidence.get("challenge_controls")+ challenge_state = evidence.get("challenge_state")normalized_indicators = ([str(item) for item in indicators if isinstance(item, str)] if isinstance(indicators, list) else [])control_count = len(challenge_controls) if isinstance(challenge_controls, list) else 0- if not normalized_indicators and control_count == 0:+ challenge_detected = isinstance(challenge_state, dict) and challenge_state.get("detected") is True+ if not normalized_indicators and control_count == 0 and not challenge_detected:return None- details = ", ".join(normalized_indicators[:4]) or f"{control_count} challenge control(s)"+ detail_parts = normalized_indicators[:4]+ if isinstance(challenge_state, dict):+ state_indicators = challenge_state.get("indicators")+ if isinstance(state_indicators, list):+ detail_parts.extend(str(item) for item in state_indicators if isinstance(item, str))+ challenge_kind = challenge_state.get("kind")+ if isinstance(challenge_kind, str) and challenge_kind and challenge_kind != "none":+ detail_parts.append(challenge_kind)+ gated_controls = challenge_state.get("gated_submit_controls")+ if challenge_state.get("gates_submit_controls") is True:+ gated_control_items = gated_controls if isinstance(gated_controls, list) else []+ control_labels = [+ str(item.get("text") or item.get("value") or item.get("id") or item.get("name") or item.get("selector"))+ for item in gated_control_items+ if isinstance(item, dict)+ and (+ item.get("text") or item.get("value") or item.get("id") or item.get("name") or item.get("selector")+ )+ ]+ labels = ", ".join(list(dict.fromkeys(control_labels))[:3]) or "submit/search control"+ detail_parts.append(f"challenge-gated disabled submit/search control: {labels}")+ if control_count:+ detail_parts.append(f"{control_count} challenge control(s)")+ details = ", ".join(list(dict.fromkeys(detail_parts))[:6])return f"Observed anti-bot challenge evidence before the run: {details}"@@ -4546,7 +4805,13 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:prior_budget_flag = copilot_ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORYcopilot_ctx.last_failure_category_top = Nonecopilot_ctx.last_test_non_retriable_nav_error = None+ copilot_ctx.post_run_page_observation_tool = None+ copilot_ctx.post_run_page_observation_url = None+ copilot_ctx.post_run_page_observation_workflow_run_id = None+ copilot_ctx.post_run_page_observation_after_failed_test = False+ copilot_ctx.post_run_current_page_inspection_workflow_run_id = None+ structured_blocker = _run_blocks_structured_blocker_message(result)anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result)if not anti_bot_match:anti_bot_match = _composition_anti_bot_reason(copilot_ctx)@@ -4580,6 +4845,26 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:if run_ok:_mark_page_inspected(copilot_ctx)+ if structured_blocker:+ failure_reason = f"Run completed, but extracted data reported a blocker: {structured_blocker}"+ copilot_ctx.last_test_ok = False+ copilot_ctx.last_test_suspicious_success = True+ copilot_ctx.last_test_failure_reason = failure_reason+ copilot_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]+ update_repeated_failure_state(copilot_ctx, result)+ returnif empty_data_blocks:copilot_ctx.last_test_ok = Nonecopilot_ctx.last_test_suspicious_success = True@@ -5158,12 +5443,13 @@ _DISCOVERY_PASSWORD_INPUT_RE = re.compile(re.IGNORECASE,)_DISCOVERY_ANTI_BOT_PATTERNS = (- "cloudflare","just a moment","captcha",+ "challenge",+ "human-verification",+ "human verification","verify you are human","access denied",- "akamai","are you a robot",)@@ -5634,7 +5920,16 @@ async def _inspect_page_for_composition_impl(record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)return result- if copilot_ctx.page_inspection_calls_this_turn >= _COMPOSITION_INSPECTION_PER_TURN_BUDGET:+ use_current_page = (target_url or "").strip().lower() in _CURRENT_PAGE_INSPECTION_TARGETS+ bypass_budget_for_post_run_current_page = _allows_post_run_current_page_inspection_budget_bypass(+ copilot_ctx,+ use_current_page=use_current_page,+ )++ if (+ not bypass_budget_for_post_run_current_page+ and copilot_ctx.page_inspection_calls_this_turn >= _COMPOSITION_INSPECTION_PER_TURN_BUDGET+ ):result = {"ok": False,"data": None,@@ -5648,7 +5943,7 @@ async def _inspect_page_for_composition_impl(return resultcumulative = copilot_ctx.prior_page_inspection_calls_made + copilot_ctx.page_inspection_calls_this_turn- if cumulative >= _COMPOSITION_INSPECTION_PER_CHAT_BUDGET:+ if not bypass_budget_for_post_run_current_page and cumulative >= _COMPOSITION_INSPECTION_PER_CHAT_BUDGET:result = {"ok": False,"data": None,@@ -5657,7 +5952,6 @@ async def _inspect_page_for_composition_impl(record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)return result- use_current_page = (target_url or "").strip().lower() in _CURRENT_PAGE_INSPECTION_TARGETSentry_url: strkind: strif use_current_page:@@ -5739,8 +6033,11 @@ async def _inspect_page_for_composition_impl("workflow_run_id": run_id,"observed_after_workflow_run": True,}+ _mark_post_run_page_observed(copilot_ctx, source_tool="inspect_page_for_composition", url=current_url)copilot_ctx.page_inspection_calls_this_turn += 1+ if bypass_budget_for_post_run_current_page:+ copilot_ctx.post_run_current_page_inspection_workflow_run_id = run_idcopilot_ctx.composition_page_evidence = evidence_mark_page_inspected(copilot_ctx)result = {"ok": True, "data": evidence}@@ -6093,7 +6390,9 @@ async def inspect_page_for_composition_tool(evidence is sufficient, compose and run workflow blocks from the observed fields.If challenge_state.gates_submit_controls is true, treat challenge resolutionas a prerequisite for submit/search; do not click a submit control while the- latest inspected evidence says it is disabled.+ latest inspected evidence says it is disabled. If a later test still leaves+ that submit/search control disabled after a challenge-resolution attempt,+ report the observed anti-bot blocker rather than retrying the same flow."""result = await _inspect_page_for_composition_impl(ctx.context, target_url)return json.dumps(result)diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex cb840bffc..82a7b3358 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -112,6 +112,30 @@ class TestFailedTestResponseNormalization:assert _pre_run_workflow_coverage_error(ctx) is Noneassert ctx.coverage_nudge_count == 0+ def test_pre_run_coverage_guard_allows_single_goto_bootstrap(self) -> None:+ from skyvern.forge.sdk.copilot.tools import _pre_run_workflow_coverage_error++ ctx = _ctx(+ user_message="Go to example.com, fill the search form, and extract the results.",+ request_policy=SimpleNamespace(completion_contract="complete when result rows are extracted"),+ last_update_block_count=1,+ last_workflow=SimpleNamespace(+ workflow_definition={+ "blocks": [+ {+ "label": "open_search_page",+ "block_type": "goto_url",+ "url": "https://example.com/search",+ }+ ]+ }+ ),+ coverage_nudge_count=0,+ )++ assert _pre_run_workflow_coverage_error(ctx) is None+ assert ctx.coverage_nudge_count == 0+def test_failed_run_does_not_clear_last_workflow_state(self) -> None:from skyvern.forge.sdk.copilot.tools import _record_run_blocks_resultdiff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.pyindex 3745aa96c..5c088a1e9 100644--- a/tests/unit/test_copilot_composition_evidence.py+++ b/tests/unit/test_copilot_composition_evidence.py@@ -176,7 +176,7 @@ def test_merge_visual_composition_evidence_keeps_screenshot_bounded_and_typed()assert merged["visual_evidence_omissions"] == ["Result rows are not visible before verification."]-def test_composition_parse_html_surfaces_turnstile_challenge_controls_after_long_page_preamble() -> None:+def test_composition_parse_html_surfaces_human_verification_controls_after_long_page_preamble() -> None:parsed = parse_composition_html(f"""<html><head><title>Credential Registry</title></head><body>diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex d7135236c..db18714d3 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -116,6 +116,40 @@ def test_repairable_block_failure_contract_is_queryable_and_safe() -> None:assert "hunter2" not in contract.model_dump_json()+def test_anti_bot_suspicious_success_contract_stops_instead_of_repairing() -> None:+ ctx = _ctx()+ ctx.last_test_suspicious_success = True+ ctx.last_test_anti_bot = "Extracted data reported anti-bot blocker: Verify you are human"+ ctx.last_test_failure_reason = "Run completed, but extracted data 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.SUSPICIOUS_SUCCESS+ assert contract.repair_decision.next_action == RepairNextAction.STOP+ assert contract.verification_result.user_goal_satisfied is False+ assert "Verify you are human" in contract.verification_result.remaining_blocker++def test_user_goal_urls_are_reduced_to_origins() -> None:ctx = _ctx()ctx.turn_intent.user_goal = "Fix https://example.test/account?id=secret now"diff --git a/tests/unit/test_copilot_page_evidence_policy.py b/tests/unit/test_copilot_page_evidence_policy.pyindex 498d4da3e..4b540b0c7 100644--- a/tests/unit/test_copilot_page_evidence_policy.py+++ b/tests/unit/test_copilot_page_evidence_policy.py@@ -55,6 +55,8 @@ def test_agent_prompt_accounts_for_observed_challenges_without_blind_waits() ->assert "Use `get_browser_screenshot` when DOM evidence identifies a challenge" in renderedassert "Prefer explicit challenge handling available to Skyvern over blind waits" in renderedassert "report the observed blocker instead of retrying the same flow" in rendered+ assert "challenge_state.gates_submit_controls=true" in rendered+ assert "submit/search control disabled" in rendereddef test_agent_prompt_continues_from_observed_state_after_budgeted_runs() -> None:diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.pyindex 911e7b81c..192ff93f5 100644--- a/tests/unit/test_copilot_per_tool_budget.py+++ b/tests/unit/test_copilot_per_tool_budget.py@@ -16,6 +16,7 @@ Covers four surfaces:from __future__ import annotations+import jsonfrom types import SimpleNamespaceimport pytest@@ -36,9 +37,12 @@ from skyvern.forge.sdk.copilot.failure_tracking import ()from skyvern.forge.sdk.copilot.tools import (WatchdogExitReason,+ _composition_anti_bot_reason,+ _last_run_has_terminal_anti_bot_blocker,_mark_page_inspected,_mark_pending_reconciliation_run,_maybe_clear_reconciliation_flag,+ _record_composition_page_observation,_record_per_tool_budget_problem_blocks_from_results,_record_run_blocks_result,_record_workflow_update_result,@@ -80,6 +84,13 @@ def _budget_trip_result(workflow_run_id: str = "wr_1") -> dict:}+def _reply_result(user_response: str) -> SimpleNamespace:+ return SimpleNamespace(+ final_output=json.dumps({"type": "REPLY", "user_response": user_response}),+ new_items=[],+ )++def test_record_sets_top_category_on_per_tool_budget_result() -> None:ctx = _fresh_context()_record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))@@ -105,6 +116,13 @@ def test_record_preserves_pre_run_anti_bot_evidence_on_budget_trip() -> None:ctx.composition_page_evidence = {"anti_bot_indicators": ["challenges.cloudflare.com", "cf-turnstile"],"challenge_controls": [{"selector": "#turnstile-widget"}],+ "challenge_state": {+ "detected": True,+ "kind": "cloudflare_turnstile",+ "indicators": ["verify you are human"],+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },}_record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))@@ -112,6 +130,26 @@ def test_record_preserves_pre_run_anti_bot_evidence_on_budget_trip() -> None:assert ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORYassert ctx.last_test_anti_bot is not Noneassert "cf-turnstile" in ctx.last_test_anti_bot+ assert "challenge-gated disabled submit/search control: Search" in ctx.last_test_anti_bot+++def test_composition_anti_bot_reason_reads_typed_challenge_state_without_legacy_indicators() -> None:+ ctx = _fresh_context()+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "cloudflare_turnstile",+ "indicators": ["cf-turnstile-response"],+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }++ reason = _composition_anti_bot_reason(ctx)++ assert reason is not None+ assert "cloudflare_turnstile" in reason+ assert "challenge-gated disabled submit/search control: Search" in reasondef test_block_running_after_budget_current_url_requires_inspection_first() -> None:@@ -125,6 +163,8 @@ def test_block_running_after_budget_current_url_requires_inspection_first() -> Nassert msg is not Noneassert "inspect_page_for_composition" in msgassert "current_page" in msg+ assert "screenshot/evaluate reads" in msg+ assert "do not satisfy the bounded page-evidence contract" in msgassert "answer from that evidence" in msg@@ -244,6 +284,44 @@ def test_check_enforcement_emits_anti_bot_nudge_before_budget_when_challenge_obsassert ctx.per_tool_budget_nudge_count == 0+def test_final_reply_after_post_run_observation_bypasses_stale_budget_and_anti_bot_nudges() -> None:+ ctx = _fresh_context()+ ctx.update_workflow_called = True+ ctx.test_after_update_done = True+ ctx.composition_page_evidence = {+ "anti_bot_indicators": ["cf-turnstile"],+ "challenge_controls": [{"selector": "#turnstile-widget"}],+ }+ _record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))+ assert ctx.last_test_anti_bot is not None++ _record_composition_page_observation(+ ctx,+ source_tool="evaluate",+ url="https://certboard.example/registry/search?sendid=fixture",+ observed_data={"text": "Certification Number: CRED-000123"},+ )++ assert _check_enforcement(ctx, _reply_result("Observed result: CRED-000123 expires 01/31/2030.")) is None+++def test_progress_reply_after_post_run_observation_still_gets_anti_bot_nudge() -> None:+ ctx = _fresh_context()+ ctx.update_workflow_called = True+ ctx.test_after_update_done = True+ ctx.composition_page_evidence = {"anti_bot_indicators": ["cf-turnstile"]}+ _record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))+ _record_composition_page_observation(+ ctx,+ source_tool="evaluate",+ url="https://certboard.example/registry/search",+ )++ nudge = _check_enforcement(ctx, _reply_result("I will now proceed to inspect the result page."))++ assert nudge == POST_ANTI_BOT_FAILED_TEST_NUDGE++def test_check_enforcement_emits_budget_nudge_before_repeated_frontier_warn() -> None:"""The budget trip is structural (chain too long) and must not be silentlyconsumed by the repeated-frontier escalation, even when both signals fire@@ -318,6 +396,15 @@ def test_nudge_text_advises_splitting_chain() -> None:or "verified prefix" in POST_PER_TOOL_BUDGET_NUDGE.lower())assert "Do NOT retry the same chain" in POST_PER_TOOL_BUDGET_NUDGE+ assert "durable workflow blocks solely to rediscover page shape" in POST_PER_TOOL_BUDGET_NUDGE+ assert "challenge_state.gates_submit_controls=true" in POST_PER_TOOL_BUDGET_NUDGE+ assert "still-disabled submit/search control" in POST_PER_TOOL_BUDGET_NUDGE+++def test_anti_bot_nudge_stops_repeating_disabled_submit_challenge_flow() -> None:+ assert "challenge_state.gates_submit_controls=true" in POST_ANTI_BOT_FAILED_TEST_NUDGE+ assert "still disabled after challenge resolution was attempted" in POST_ANTI_BOT_FAILED_TEST_NUDGE+ assert "Do NOT retry the same challenge solve" in POST_ANTI_BOT_FAILED_TEST_NUDGE@pytest.mark.parametrize(@@ -534,6 +621,187 @@ def test_tool_loop_error_allows_new_smaller_label_after_budget_problem() -> None)+def test_tool_loop_error_blocks_challenge_gated_disabled_submit_rerun() -> None:+ ctx = _fresh_context()+ ctx.workflow_yaml = """+title: Sample credential registry lookup+workflow_definition:+ blocks:+ - label: open_find_certificant+ block_type: goto_url+ url: https://certboard.example/registry/search+"""+ ctx.last_failed_workflow_yaml = ctx.workflow_yaml+ 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 required Search button remains disabled after verification, and there is no enabled alternative."+ )+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "cloudflare_turnstile",+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }++ msg = _tool_loop_error(+ ctx,+ "update_and_run_blocks",+ {+ "workflow_yaml": ctx.workflow_yaml,+ "block_labels": ["fill_sample_person_credential_search"],+ },+ )++ assert msg is not None+ assert "anti-bot challenge" in msg+ assert "disabled submit/search control" in msg+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "tool_error_challenge_gated_submit_disabled"+++def test_tool_loop_error_allows_challenge_gated_retry_with_changed_proxy_location() -> None:+ ctx = _fresh_context()+ ctx.last_failed_workflow_yaml = """+title: Sample credential registry lookup+workflow_definition:+ blocks:+ - label: open_find_certificant+ block_type: goto_url+ url: https://certboard.example/registry/search+"""+ 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 required Search button remains disabled after verification."+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "cloudflare_turnstile",+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Search", "disabled": True}],+ },+ }+ changed_proxy_yaml = """+title: Sample credential registry lookup+proxy_location: RESIDENTIAL+workflow_definition:+ blocks:+ - label: open_find_certificant+ block_type: goto_url+ url: https://certboard.example/registry/search+"""++ assert (+ _tool_loop_error(+ ctx,+ "update_and_run_blocks",+ {+ "workflow_yaml": changed_proxy_yaml,+ "block_labels": ["fill_sample_person_credential_search"],+ },+ )+ is None+ )+ assert ctx.challenge_gated_proxy_retry_count == 1+++def test_tool_loop_error_blocks_second_challenge_gated_proxy_retry() -> None:+ ctx = _fresh_context()+ ctx.challenge_gated_proxy_retry_count = 1+ ctx.last_failed_workflow_yaml = """+title: Sample credential registry lookup+workflow_definition:+ blocks:+ - label: open_find_certificant+ block_type: goto_url+ url: https://certboard.example/registry/search+"""+ ctx.last_test_anti_bot = "Extracted data reported anti-bot blocker: Verify you are human"+ ctx.last_test_failure_reason = "Run completed, but extracted data reported a blocker: Verify you are human"+ changed_proxy_yaml = """+title: Sample credential registry lookup+proxy_location: US-NY+workflow_definition:+ blocks:+ - label: open_find_certificant+ block_type: goto_url+ url: https://certboard.example/registry/search+"""++ msg = _tool_loop_error(+ ctx,+ "update_and_run_blocks",+ {+ "workflow_yaml": changed_proxy_yaml,+ "block_labels": ["search_sample_person_credential"],+ },+ )++ assert msg is not None+ assert "anti-bot challenge" in msg+ assert "blocker" in msg+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "tool_error_challenge_gated_submit_disabled"+++def test_terminal_anti_bot_blocker_requires_gated_submit_evidence_for_disabled_failure() -> None:+ ctx = _fresh_context()+ ctx.last_test_anti_bot = "Observed anti-bot challenge evidence before the run: human-verification"+ ctx.last_test_failure_reason = "The page has a disabled button unrelated to the challenged search path."+ ctx.composition_page_evidence = {+ "challenge_state": {+ "detected": True,+ "kind": "human_verification",+ "gates_submit_controls": False,+ }+ }++ assert _last_run_has_terminal_anti_bot_blocker(ctx) is False+++def test_record_run_blocks_treats_structured_anti_bot_blocker_as_failed_test() -> None:+ ctx = _fresh_context()+ ctx.workflow_yaml = "workflow_definition: {blocks: []}"+ result = {+ "ok": True,+ "data": {+ "workflow_run_id": "wr_blocked",+ "overall_status": "completed",+ "blocks": [+ {+ "label": "extract_sample_person_credentials",+ "block_type": "EXTRACTION",+ "status": "completed",+ "extracted_data": {+ "extracted_information": {+ "results_exist": None,+ "credentials": [],+ "no_results_message": None,+ "blocker_message": "Verify you are human",+ }+ },+ }+ ],+ },+ }++ _record_run_blocks_result(ctx, result)++ assert ctx.last_test_ok is False+ assert ctx.last_test_suspicious_success is True+ assert ctx.last_test_anti_bot is not None+ assert "Verify you are human" in ctx.last_test_failure_reason+ assert 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_categories"][0]["category"] == "ANTI_BOT_DETECTION"++def test_tool_loop_error_blocks_upstream_replay_after_post_budget_page_evidence() -> None:ctx = _fresh_context()ctx.per_tool_budget_problem_block_labels = ["apply_filters"]