Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Require submit evidence (#8995)
Aaron Perez6c486e7f0651
diff --git a/docs/reference/configuration.mdx b/docs/reference/configuration.mdxindex aaa47b001..e7f1eb12b 100644--- a/docs/reference/configuration.mdx+++ b/docs/reference/configuration.mdx@@ -217,12 +217,6 @@ LLM_KEY=GEMINI_3_PRO| `GEMINI_3_PRO` | Recommended for primary use || `GEMINI_3.0_FLASH` | Recommended for secondary use || `GEMINI_3.1_FLASH_LITE` | Fastest, most cost-efficient |-| **Gemini 2.5** | |-| `GEMINI_2.5_PRO` | |-| `GEMINI_2.5_PRO_PREVIEW` | |-| `GEMINI_2.5_PRO_EXP_03_25` | Experimental |-| `GEMINI_2.5_FLASH` | |-| `GEMINI_2.5_FLASH_PREVIEW` | || **Gemini 2.0** | || `GEMINI_FLASH_2_0` | || `GEMINI_FLASH_2_0_LITE` | |@@ -267,12 +261,6 @@ For global endpoint access, set `VERTEX_LOCATION=global` and ensure `VERTEX_PROJ| `VERTEX_GEMINI_3_PRO` | Recommended for primary use || `VERTEX_GEMINI_3.0_FLASH` | Recommended for secondary use || `VERTEX_GEMINI_3.1_FLASH_LITE` | Fastest, most cost-efficient |-| **Gemini 2.5** | |-| `VERTEX_GEMINI_2.5_PRO` | |-| `VERTEX_GEMINI_2.5_PRO_PREVIEW` | |-| `VERTEX_GEMINI_2.5_FLASH` | |-| `VERTEX_GEMINI_2.5_FLASH_LITE` | |-| `VERTEX_GEMINI_2.5_FLASH_PREVIEW` | || **Gemini 2.0** | || `VERTEX_GEMINI_FLASH_2_0` | || **Gemini 1.5 Legacy** | |@@ -1000,7 +988,7 @@ SECONDARY_LLM_KEY=OPENAI_GPT5_4### "Context window exceeded"The page content is too large for the model's context window. Options:-- Use a model with larger context support (GPT-5.5, Gemini 2.5 Pro, or Claude 4.7 Opus)+- Use a model with larger context support (GPT-5.5, Gemini 3.1 Pro, or Claude 4.7 Opus)- Simplify your prompt to require less page analysis- Start from a more specific URL with less contentdiff --git a/docs/sdk-reference/browser-automation/page.mdx b/docs/sdk-reference/browser-automation/page.mdxindex 75ab65fe2..0406d172d 100644--- a/docs/sdk-reference/browser-automation/page.mdx+++ b/docs/sdk-reference/browser-automation/page.mdx@@ -194,7 +194,7 @@ Validation criteria or condition to check</ParamField><ParamField path={"model"} type={"dict[str, Any] | str | None"}>-Optional model configuration. Can be either: - A dict with model configuration (e.g., \{"model_name": "gemini-2.5-flash-lite", "max_tokens": 2048\}) - A string with just the model name (e.g., "gpt-4")+Optional model configuration. Can be either: - A dict with model configuration (e.g., \{"model_name": "gemini-3.0-flash", "max_tokens": 2048\}) - A string with just the model name (e.g., "gpt-4")Default: `None`</ParamField>@@ -272,7 +272,7 @@ Default: `None`</ParamField><ParamField path={"model"} type={"dict[str, Any] | str | None"}>-Optional model configuration. Can be either: - A dict with model configuration (e.g., \{"model_name": "gemini-2.5-flash-lite", "max_tokens": 2048\}) - A string with just the model name (e.g., "gemini-2.5-flash-lite")+Optional model configuration. Can be either: - A dict with model configuration (e.g., \{"model_name": "gemini-3.0-flash", "max_tokens": 2048\}) - A string with just the model name (e.g., "gemini-3.0-flash")Default: `None`</ParamField>diff --git a/skyvern-frontend/src/components/CustomLLMConfigForm.tsx b/skyvern-frontend/src/components/CustomLLMConfigForm.tsxindex 349b74ff8..c1a6a12df 100644--- a/skyvern-frontend/src/components/CustomLLMConfigForm.tsx+++ b/skyvern-frontend/src/components/CustomLLMConfigForm.tsx@@ -421,7 +421,7 @@ export function CustomLLMConfigForm() {: provider === "ollama"? "llama3.1": provider === "gemini"- ? "gemini-2.5-flash"+ ? "gemini-3-flash-preview": "mistral"}disabled={formControlsDisabled}diff --git a/skyvern-frontend/src/components/ModelSelector.test.tsx b/skyvern-frontend/src/components/ModelSelector.test.tsxindex 5894b88b7..b5585052c 100644--- a/skyvern-frontend/src/components/ModelSelector.test.tsx+++ b/skyvern-frontend/src/components/ModelSelector.test.tsx@@ -157,24 +157,6 @@ describe("ModelSelector in a read-only comparison scope", () => {expect(await screen.findByText("GPT 5.2 (deprecated)")).toBeTruthy();});- test("hides deprecated Gemini 2.5 Pro/Flash unless selected", async () => {- getMock.mockResolvedValueOnce({- data: {- models: {- "gemini-2.5-pro-preview-05-06": "Gemini 2.5 Pro",- "gemini-2.5-flash": "Gemini 2.5 Flash",- "gemini-3.6-flash": "Gemini 3.6 Flash",- },- },- });-- renderSelector(false, null);-- expect(await screen.findByText("Gemini 3.6 Flash")).toBeTruthy();- expect(screen.queryByText("Gemini 2.5 Pro (deprecated)")).toBeNull();- expect(screen.queryByText("Gemini 2.5 Flash (deprecated)")).toBeNull();- });-test("surfaces the open-source OpenRouter models", async () => {getMock.mockResolvedValueOnce({data: {diff --git a/skyvern-frontend/src/components/ModelSelector.tsx b/skyvern-frontend/src/components/ModelSelector.tsxindex fd4dc5b48..c17223bac 100644--- a/skyvern-frontend/src/components/ModelSelector.tsx+++ b/skyvern-frontend/src/components/ModelSelector.tsx@@ -28,9 +28,6 @@ const constants = {} as const;const deprecatedModelNames = new Set<string>([- "gemini-2.5-pro-preview-05-06",- "gemini-2.5-flash",- "gemini-2.5-flash-lite","gemini-3-pro-preview","gemini-3.0-flash","gemini-3.5-flash",diff --git a/skyvern/cli/llm_setup.py b/skyvern/cli/llm_setup.pyindex b225199be..d1df40d0e 100644--- a/skyvern/cli/llm_setup.py+++ b/skyvern/cli/llm_setup.py@@ -202,9 +202,6 @@ def setup_llm_providers(env_path: Path | str | None = None) -> None:"GEMINI_3.0_FLASH","GEMINI_3.5_FLASH_LITE","GEMINI_3.1_FLASH_LITE",- "GEMINI_2.5_PRO",- "GEMINI_2.5_FLASH",- "GEMINI_2.5_FLASH_LITE",])else:diff --git a/skyvern/config.py b/skyvern/config.pyindex 22880b0b3..104c86347 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -383,6 +383,14 @@ class Settings(BaseSettings):AWS_REGION: str = "us-east-1"MAX_UPLOAD_FILE_SIZE: int = 30 * 1024 * 1024 # 30 MBMAX_HTTP_DOWNLOAD_FILE_SIZE: int = 500 * 1024 * 1024 # 500 MB+ # Most memory a pdfplumber child may add (RLIMIT_AS on Linux, an RSS watchdog everywhere); rendering a 300 dpi A0+ # or A1 scan for OCR can need more than 512 MiB. A pod with less free memory than this, after a 256 MiB margin and+ # the result reserve, gets what is left, and under 128 MiB the call fails, because memory.oom.group kills the whole+ # worker at its limit.+ PDFPLUMBER_MAX_MEMORY_BYTES: int = Field(default=1536 * 1024 * 1024, gt=0)+ # Most page PNG data a pdfplumber child may hand back for OCR; text, word and page-count results have smaller caps+ # in pdf_parser. The parent holds a result outside the child's memory cap, so it reserves the decoded size.+ PDFPLUMBER_MAX_RESULT_BYTES: int = Field(default=256 * 1024 * 1024, gt=0)PRESIGNED_URL_EXPIRATION: int = 60 * 60 * 24 # 24 hours# Ceiling on the retention_days a caller may request at upload time. A cap exists so a# retention period cannot be used to pin storage indefinitely; omitting retention_days@@ -592,6 +600,9 @@ class Settings(BaseSettings):# Hold the first click or Enter after a password fill until 45 s after Task V3 started the block. Force-on term# only: runs are randomized per run by the flag of the same name, read through run_arm_enabled(LOGIN_PACE_FLAG, ...).TASK_V3_LOGIN_PACE: bool = False+ # Store the error code v3's model chose on finish instead of the post-run page guess. Off: the guess is stored+ # as before. Retry policies match on stored codes, so turning this on can change which runs retry.+ TASK_V3_ERROR_CODE_ON_FINISH: bool = False# Which browser surface the v3 loop offers: today's action tools ("off"), those plus a code# tool ("add"), or the code tool instead of them ("replace"). Three states rather than a boolean# because the benchmark separated add from replace on speed alone, not on success. The code tool@@ -1154,8 +1165,6 @@ class Settings(BaseSettings):# Gemini models: prefer Vertex when enabled, fall back to direct Gemini APIgemini_models = [- ("gemini-2.5-pro-preview-05-06", "VERTEX_GEMINI_2.5_PRO", "GEMINI_2.5_PRO", "Gemini 2.5 Pro"),- ("gemini-2.5-flash", "VERTEX_GEMINI_2.5_FLASH", "GEMINI_2.5_FLASH", "Gemini 2.5 Flash"),("gemini-3-pro-preview", "VERTEX_GEMINI_3_PRO", "GEMINI_3_PRO", "Gemini 3 Pro (Latest)"),("gemini-3.0-flash", "VERTEX_GEMINI_3.0_FLASH", "GEMINI_3.0_FLASH", "Gemini 3 Flash"),("gemini-3.5-flash", "VERTEX_GEMINI_3.5_FLASH", "GEMINI_3.5_FLASH", "Gemini 3.5 Flash"),@@ -1168,12 +1177,6 @@ class Settings(BaseSettings):"label": label,}- # Gemini Flash Lite: Vertex-only (no direct Gemini API config exists)- mapping["gemini-2.5-flash-lite"] = {- "llm_key": "VERTEX_GEMINI_2.5_FLASH_LITE",- "label": "Gemini 2.5 Flash Lite",- }-mapping["mercury-2"] = {"llm_key": "INCEPTION_MERCURY_2", "label": "Inception Mercury 2"}if self.ENABLE_XAI:diff --git a/skyvern/core/script_generations/skyvern_page.py b/skyvern/core/script_generations/skyvern_page.pyindex da5106e18..f6f5e3634 100644--- a/skyvern/core/script_generations/skyvern_page.py+++ b/skyvern/core/script_generations/skyvern_page.py@@ -1679,7 +1679,7 @@ class SkyvernPage(Page):Args:prompt: Validation criteria or condition to checkmodel: Optional model configuration. Can be either:- - A dict with model configuration (e.g., {"model_name": "gemini-2.5-flash-lite", "max_tokens": 2048})+ - A dict with model configuration (e.g., {"model_name": "gemini-3.0-flash", "max_tokens": 2048})- A string with just the model name (e.g., "gpt-4")Returns:@@ -1693,13 +1693,13 @@ class SkyvernPage(Page):# Validation with specific model (as string)is_valid = await page.validate("Check if the order was placed",- model="gemini-2.5-flash-lite"+ model="gemini-3.0-flash")# Validation with model config (as dict)is_valid = await page.validate("Check if the payment completed",- model={"model_name": "gemini-2.5-flash-lite", "max_tokens": 1024}+ model={"model_name": "gemini-3.0-flash", "max_tokens": 1024})```"""@@ -3684,8 +3684,8 @@ class SkyvernPage(Page):schema: Optional JSON schema to structure the response. If provided, the LLM responsewill be validated against this schema.model: Optional model configuration. Can be either:- - A dict with model configuration (e.g., {"model_name": "gemini-2.5-flash-lite", "max_tokens": 2048})- - A string with just the model name (e.g., "gemini-2.5-flash-lite")+ - A dict with model configuration (e.g., {"model_name": "gemini-3.0-flash", "max_tokens": 2048})+ - A string with just the model name (e.g., "gemini-3.0-flash")Returns:LLM response structured according to the schema if provided, or unstructured response otherwise.diff --git a/skyvern/errors/errors.py b/skyvern/errors/errors.pyindex 496cb601b..f9629128f 100644--- a/skyvern/errors/errors.py+++ b/skyvern/errors/errors.py@@ -57,14 +57,14 @@ def filter_to_user_defined_codes("""if not error_code_mapping:return [], [error.error_code for error in errors]- allowed = set(error_code_mapping.keys())kept: list[UserDefinedError] = []dropped: list[str] = []for error in errors:- if error.error_code in allowed:- kept.append(error)- else:+ key = resolve_error_code_mapping_key(error.error_code, error_code_mapping)+ if key is None:dropped.append(error.error_code)+ else:+ kept.append(error if key == error.error_code else error.model_copy(update={"error_code": key}))return kept, droppeddiff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex f236bf123..47668edfb 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -16,7 +16,7 @@ from copy import deepcopyfrom dataclasses import dataclass, replacefrom datetime import UTC, datetimefrom pathlib import Path-from typing import TYPE_CHECKING, Any, Awaitable, Callable, Literal, NamedTuple, Sequence, Tuple, cast+from typing import Any, Awaitable, Callable, Literal, NamedTuple, Sequence, Tuple, castimport structlogfrom openai.types.responses.response import Response as OpenAIResponse@@ -359,10 +359,6 @@ from skyvern.webeye.scraper.scraper import page_is_dead_blank, page_is_http_survfrom skyvern.webeye.utils.document import get_main_document_loader_idfrom skyvern.webeye.utils.page import OTP_INPUT_PRIVACY_JS, ScreenshotMode, SkyvernFrame, build_open_tabs_context-if TYPE_CHECKING:- # Runtime import is local to _execute_task_v3: auth_tools imports the action handler, which imports this module.- from skyvern.forge.taskv3.auth_tools import VerificationState-LOG = structlog.get_logger()BLANK_WORKFLOW_TASK_URLS = {"about:blank", ":"}RECOVERABLE_BLANK_WORKFLOW_TASK_URLS = {":"}@@ -1710,26 +1706,6 @@ def _v3_task_status(return task_status, missing_extraction-# Worded to stay clear of the classifier's credential and sign-in keywords: the customer's credentials-# were never tried with a code, so neither category is the cause.-_V3_TOTP_SOURCE_MISSING_REASON = (- "task_v3 could not produce the one-time code the page asked for: the credential has no usable TOTP "- "source for this block"-)---def _v3_totp_source_missing(task_status: TaskStatus, verification_state: "VerificationState") -> bool:- """Whether the run ended on a credential code it could not produce with no other code source at all --- the condition the step engine's MISSING_TOTP_SOURCE names."""- return (- task_status in (TaskStatus.failed, TaskStatus.terminated)- and verification_state.totp_source_missing- and verification_state.values_delivered == 0- and not verification_state.code_tool_offered- and not verification_state.source_failed- )--def _v3_failure_reason(outcome: LoopOutcome,*,@@ -1737,7 +1713,7 @@ def _v3_failure_reason(completion_rejection: str | None,missing_extraction: bool,run_secrets: Collection[str],- totp_source_missing: bool = False,+ verification_status: str | None = None,) -> str | None:if task_status in (TaskStatus.completed, TaskStatus.canceled):failure_reason = None@@ -1745,8 +1721,9 @@ def _v3_failure_reason(failure_reason = f"task_v3 reported completion but {completion_rejection}"elif missing_extraction:failure_reason = "task_v3 reported completion but returned no extracted_output for the data-extraction goal"- elif totp_source_missing:- failure_reason = _V3_TOTP_SOURCE_MISSING_REASON+ # Only the model's own give-up: a loop guard, a loop error or a spent budget ended the run for its own reason.+ elif verification_status is not None and outcome.guard is None and outcome.status in ("failed", "terminated"):+ failure_reason = f"{outcome.reason or outcome.status} (last verification code status: {verification_status})"else:failure_reason = outcome.reason or outcome.status# failure_reason is a first-class field on the task webhook payload, so the model's finish@@ -2413,6 +2390,7 @@ class ForgeAgent:)from skyvern.forge.taskv3.opaque_refs import mask_opaque_urlsfrom skyvern.forge.taskv3.tools import (+ NO_ONE_TIME_CODE_SOURCE,_document_unidentifiable,_observable_child_frames,_realm_document_id,@@ -3192,8 +3170,8 @@ class ForgeAgent:if context and credential_parameter_key is not None:context.active_credential_parameter_key = credential_parameter_keytry:- # Built AFTER the credential pin: the tool-offer gate (has_credential_totp_candidate)- # must see the pinned key, or a multi-credential context hides get_verification_code.+ # Built AFTER the credential pin: the code-source check (has_credential_totp_candidate)+ # must see the pinned key, or a multi-credential context reads as having no code source.# No page provider in page-free mode: the sign-in-link tool navigates, and a run that# structurally never touches the live DOM must not be offered it.verification_state = VerificationState(@@ -3265,13 +3243,18 @@ class ForgeAgent:)async def _completion_gate() -> bool:- return await app.AGENT_FUNCTION.gate_step_completion(- task=task,- step=step,- task_block=task_block,- page=await browser_state.get_working_page(),- browser_state=browser_state,- )+ try:+ return await app.AGENT_FUNCTION.gate_step_completion(+ task=task,+ step=step,+ task_block=task_block,+ page=await browser_state.get_working_page(),+ browser_state=browser_state,+ )+ except (CompletionGateTerminationError, StepTerminationError):+ # The gate's verdict ends the run with its own reason, not a code status the model saw earlier.+ verification_state.last_status = None+ raiseoutcome = await run_task_v3_agent_loop(page_provider=_page_provider,@@ -3289,6 +3272,7 @@ class ForgeAgent:download_attempts=_download_attempts,block_type=block_type,has_navigation_goal=bool(task.navigation_goal),+ error_code_mapping=task.error_code_mapping,extraction_requested=extraction_requested,# Only the customer's own instructions can define what counts as done. Auth and captcha# guidance are how-to, and the judge is told an outcome its instructions allow is no@@ -3332,6 +3316,8 @@ class ForgeAgent:should_cancel=_should_cancel,on_action_round=_on_action_round,on_pre_action=pre_submit_ring.capture if pre_submit_ring is not None else None,+ # A code status the model has moved past is no longer what the run ends on.+ on_page_action=verification_state.page_engaged,extra_tools=auth_tools + captcha_tools,extra_system_guidance="\n\n".join(part for part in (auth_guidance, captcha_guidance, workflow_system_guidance) if part@@ -3370,6 +3356,8 @@ class ForgeAgent:with contained_effect("task_v3 pre-submit frame persist", task_id=task.task_id):async with asyncio.timeout(30):await _persist_pre_submit_frames()+ # The model's own verdict, before a completion gate or a re-ask conversion rewrote the status.+ model_verdict = outcome.model_status or outcome.converted_from or outcome.statusLOG.info("Task V3 loop finished",task_id=task.task_id,@@ -3406,6 +3394,8 @@ class ForgeAgent:LOG.warning("task_v3 completion gate errored; accepting completion", task_id=task.task_id, exc_info=True)+ if outcome.status != "completed":+ verification_state.last_status = Noneif outcome.status == "terminated":LOG.info("task_v3 completion terminated by completion gate", task_id=task.task_id)elif outcome.status == "failed":@@ -3599,17 +3589,30 @@ class ForgeAgent:step_id=step.step_id,exc_info=True,)- totp_source_missing = _v3_totp_source_missing(task_status, verification_state)failure_reason = _v3_failure_reason(outcome,task_status=task_status,completion_rejection=completion_rejection,missing_extraction=missing_extraction,run_secrets=run_secrets,- totp_source_missing=totp_source_missing,+ verification_status=verification_state.last_status,)- # Only when that is the reason recorded: a vetoed completion or a missing extraction failed for its own.- if totp_source_missing and failure_reason == _V3_TOTP_SOURCE_MISSING_REASON:+ if verification_state.last_status is not None:+ LOG.info(+ "task_v3 ended on a verification code status",+ task_id=task.task_id,+ organization_id=task.organization_id,+ workflow_run_id=task.workflow_run_id,+ task_status=task_status.value,+ polling_spent_seconds=round(verification_state.polling_spent_seconds, 1),+ remaining_seconds=round(verification_state.remaining_budget_seconds, 1),+ values_delivered=verification_state.values_delivered,+ )+ # Only when the reason recorded carries that status: a vetoed completion or a missing extraction failed for+ # its own.+ if verification_state.last_status == NO_ONE_TIME_CODE_SOURCE and NO_ONE_TIME_CODE_SOURCE in (+ failure_reason or ""+ ):LOG.info("task_v3 attributed to a missing TOTP source", task_id=task.task_id, task_status=task_status)with contained_effect("task_v3 missing TOTP source error persist", task_id=task.task_id):await app.DATABASE.tasks.update_task(@@ -3634,7 +3637,44 @@ class ForgeAgent:completion_rejection=completion_rejection,missing_extraction=missing_extraction,)- if task.error_code_mapping and task_status in (TaskStatus.failed, TaskStatus.terminated):+ coded_failure = bool(task.error_code_mapping) and task_status in (TaskStatus.failed, TaskStatus.terminated)+ # The answer belongs to the model's own failed/terminated verdict, never to a completion demoted after the loop.+ # A conversion still standing here was ended by a deployment gate, not by the model's verdict.+ model_answered = (+ coded_failure+ and outcome.status in ("failed", "terminated")+ and outcome.converted_from is None+ and (outcome.error_code is not None or outcome.error_code_declined)+ )+ model_answer_used = False+ if model_answered:+ try:+ model_answer_used = await app.AGENT_FUNCTION.task_v3_error_code_on_finish(+ organization_id=task.organization_id+ )+ except Exception:+ LOG.warning("task_v3 error code on finish gate failed", task_id=task.task_id, exc_info=True)+ detector_codes: list[str] | None = None+ if model_answer_used and outcome.error_code:+ with contained_effect("task_v3 model-chosen error code persist", task_id=task.task_id):+ code_reasoning = outcome.reason+ if run_secrets:+ code_reasoning = redact_secrets_from_text(code_reasoning, run_secrets)+ await app.DATABASE.tasks.update_task(+ task_id=task.task_id,+ organization_id=task.organization_id,+ errors=[+ UserDefinedError(+ error_code=outcome.error_code,+ reasoning=code_reasoning[:_TASKV3_REASONING_MAX_CHARS],+ confidence_float=1.0,+ ).model_dump()+ ],+ )+ elif model_answer_used and outcome.error_code_declined:+ # An explicit "none of these" is the model's judgment, so the page guess must not override it.+ LOG.info("task_v3 user-defined error code declined by the model", task_id=task.task_id)+ elif coded_failure:try:detected_errors = await detect_user_defined_errors_for_task(task=task,@@ -3664,8 +3704,22 @@ class ForgeAgent:organization_id=task.organization_id,errors=[error.model_dump() for error in detected_errors],)+ detector_codes = [error.error_code for error in detected_errors]except Exception:LOG.warning("task_v3 user-defined error detection failed", task_id=task.task_id, exc_info=True)+ if coded_failure:+ # One line per task, so the model's code can be read against the page guess before an org relies on it.+ LOG.info(+ "task_v3 user-defined error code sources",+ task_id=task.task_id,+ task_status=task_status,+ reached_finish=outcome.guard is None and model_verdict in ("completed", "failed", "terminated"),+ model_verdict=model_verdict,+ model_error_code=outcome.error_code,+ model_declined=outcome.error_code_declined,+ detector_error_codes=detector_codes,+ model_answer_used=model_answer_used,+ )need_call_webhook = Truetry:task = await self.update_task(@@ -3800,6 +3854,7 @@ class ForgeAgent:context.task_id = task.task_idcontext.navigation_goal = task.navigation_goalcontext.navigation_payload = task.navigation_payload+ context.completion_gate_engine = engineif download_baseline_files is None:context.download_suffix_applied_files = {}context.download_suffix = task_block.download_suffix if task_block else None@@ -4018,6 +4073,9 @@ class ForgeAgent:await app.ARTIFACT_MANAGER.flush_step_archive(step.step_id)return step, detailed_output, None+ if dispatched_as_v3:+ context.completion_gate_engine = RunEngine.skyvern_v1+if workflow_owned_recovery:# A recovery on the step engine would hold the block's credential placeholders with# run-scoped credential and OTP access, so it fails instead of falling through.@@ -4059,6 +4117,7 @@ class ForgeAgent:)# Later steps recurse with this engine; pinning v1 keeps them off the gate and this write.engine = RunEngine.skyvern_v1+ context.completion_gate_engine = engineif page := await browser_state.get_working_page():await self.register_async_operations(organization, task, page)@@ -8083,8 +8142,8 @@ class ForgeAgent:cache_key = f"{EXTRACT_ACTION_CACHE_KEY_PREFIX}{variant_suffix}-{resolved_llm_key}"# Get the actual model name from LLM config to ensure correct format- # (e.g., "gemini-2.5-flash" with decimal, not "gemini-2-5-flash")- model_name = "gemini-2.5-flash" # Default+ # (e.g., "gemini-3.1-flash-lite" with decimal, not "gemini-3-1-flash-lite")+ model_name = "gemini-3-flash-preview" # Defaulttry:llm_config = LLMConfigRegistry.get_config(resolved_llm_key)@@ -8108,7 +8167,7 @@ class ForgeAgent:# Try to extract from model_name if it contains "vertex_ai/" or starts with "gemini-"if not extracted_name and hasattr(llm_config, "model_name") and isinstance(llm_config.model_name, str):if "vertex_ai/" in llm_config.model_name:- # Direct Vertex config: "vertex_ai/gemini-2.5-flash" -> "gemini-2.5-flash"+ # Direct Vertex config: "vertex_ai/gemini-3-flash-preview" -> "gemini-3-flash-preview"extracted_name = llm_config.model_name.split("/")[-1]elif llm_config.model_name.startswith("gemini-"):# Already in correct format@@ -8119,15 +8178,15 @@ class ForgeAgent:params = llm_config.litellm_paramsapi_base = getattr(params, "api_base", None)if api_base and isinstance(api_base, str) and "/models/" in api_base:- # Extract from URL: .../models/gemini-2.5-flash -> "gemini-2.5-flash"+ # Extract from URL: .../models/gemini-3-flash-preview -> "gemini-3-flash-preview"extracted_name = api_base.split("/models/")[-1]# For router configs without api_base, infer from the llm_key itselfif not extracted_name:- # Extract version from llm_key (e.g., VERTEX_GEMINI_1_5_FLASH -> "1_5" or VERTEX_GEMINI_2.5_FLASH -> "2.5")+ # Extract version from llm_key (e.g., VERTEX_GEMINI_1_5_FLASH -> "1_5" or VERTEX_GEMINI_3.0_FLASH -> "3.0")# Pattern: GEMINI_{version}_{flavor} where version can use dots, underscores, or dashesversion_match = re.search(r"GEMINI[_-](\d+[._-]\d+)", resolved_llm_key, re.IGNORECASE)- version = version_match.group(1).replace("_", ".").replace("-", ".") if version_match else "2.5"+ version = version_match.group(1).replace("_", ".").replace("-", ".") if version_match else "3"# Determine flavorif "_PRO_" in resolved_llm_key or resolved_llm_key.endswith("_PRO"):@@ -8143,7 +8202,7 @@ class ForgeAgent:except Exception as e:LOG.debug("Failed to extract model name from config, using default", error=str(e))- # Normalize model name to the canonical Vertex identifier (e.g., gemini-2.5-pro).+ # Normalize model name to the canonical Vertex identifier (e.g., gemini-3-flash-preview).# Preserve preview suffixes so we don't strip required identifiers (e.g., gemini-3-flash-preview).match = re.search(r"(gemini-\d+(?:\.\d+)?-(?:flash-lite|flash|pro)(?:-preview)?)", model_name, re.IGNORECASEdiff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 3fc75aaa8..4597eaa7e 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -1032,6 +1032,18 @@ class AgentFunction:"""Cloud raises 403 when a workflow folder denies the action; OSS has no folder ACLs."""return None+ async def enforce_workflow_delete(+ self, principal: RequestPrincipal | None, workflow_permanent_id: str, organization_id: str+ ) -> tuple[str, str | None] | None:+ """Cloud enforces RBAC and folder permissions for workflow deletion; OSS has no RBAC policy."""+ return None++ async def enforce_workflow_deletes(+ self, principal: RequestPrincipal | None, workflow_permanent_ids: set[str], organization_id: str+ ) -> None:+ for workflow_permanent_id in workflow_permanent_ids:+ await self.enforce_workflow_delete(principal, workflow_permanent_id, organization_id)+async def enforce_folder_access_for_references(self, principal: RequestPrincipal | None, action: str, payload: Mapping[str, object]) -> None:@@ -1160,6 +1172,11 @@ class AgentFunction:async def resolve_billing_tier(self, organization_id: str | None) -> BillingTier:return BillingTier.UNKNOWN+ # Whether the error code v3's model chose on finish is stored in place of the post-run page guess. The model is+ # offered the codes either way; cloud gates this per organization.+ async def task_v3_error_code_on_finish(self, *, organization_id: str) -> bool:+ return settings.TASK_V3_ERROR_CODE_ON_FINISH+# (text appended to a page-aware v3 run's task message or None, reason logged on the loop-finished line), given# the run's payload. OSS supplies no default.def task_v3_age_default(self, parameters: dict[str, Any] | None) -> tuple[str | None, str] | None:@@ -1191,6 +1208,9 @@ class AgentFunction:async def is_recognized_submit_control(self, element: SkyvernElement) -> bool:return False+ async def is_submit_control_for_completion(self, element: SkyvernElement) -> bool:+ return False+async def record_run_duration(self,run_type: str,diff --git a/skyvern/forge/sdk/api/llm/api_handler_factory.py b/skyvern/forge/sdk/api/llm/api_handler_factory.pyindex 7d7e36983..cd5a9a431 100644--- a/skyvern/forge/sdk/api/llm/api_handler_factory.py+++ b/skyvern/forge/sdk/api/llm/api_handler_factory.py@@ -941,7 +941,7 @@ def _get_primary_model_dict(router: Any, main_model_group: str) -> dict[str, Anydef _primary_deployment_label(primary_model_dict: dict[str, Any] | None) -> str | None:- """Provider label of the primary deployment (e.g. `vertex_ai/gemini-2.5-pro` -> `gemini-2.5-pro`)."""+ """Provider label of the primary deployment (e.g. `vertex_ai/gemini-3-flash-preview` -> `gemini-3-flash-preview`)."""if not primary_model_dict:return Nonelitellm_params = primary_model_dict.get("litellm_params") or {}@@ -1054,7 +1054,7 @@ def _log_vertex_cache_hit_if_needed(def _normalize_llm_model(model: str | None) -> str | None:# LiteLLM's response.model can include a provider prefix- # (e.g. "vertex_ai/gemini-2.5-flash", "openai/gpt-4.1-mini") while+ # (e.g. "vertex_ai/gemini-3-flash-preview", "openai/gpt-4.1-mini") while# config-side fallbacks tend to use the bare model name. Strip the# prefix so dbt aggregates the same model under one bucket.if not model:@@ -1297,7 +1297,7 @@ class LLMAPIHandlerFactory:def _models_equivalent(left: str | None, right: str | None) -> bool:"""Used only by `llm_api_handler_with_router_and_fallback`. Router modelgroups carry the `vertex-` prefix while LiteLLM responses return the- underlying provider label (e.g. `gemini-2.5-pro`). Stripping the prefix+ underlying provider label (e.g. `gemini-3-flash-preview`). Stripping the prefixlets us detect whether the configured primary (the router's`main_model_group`) actually served the request without replumbing everyconfig/registry reference.@@ -1575,7 +1575,7 @@ class LLMAPIHandlerFactory:)try:- # Gemini router/fallback configs (e.g., gemini-2.5-pro-gpt-5-fallback-router)+ # Gemini router/fallback configs (e.g., gemini-3-pro-gpt-5-fallback-router)# are not recognized by litellm, but they do support reasoning budgets.if not supports_reasoning and model_label:model_label_lower = model_label.lower()@@ -2667,7 +2667,7 @@ class LLMAPIHandlerFactory:cached_tokens = getattr(response.usage, "cache_read_input_tokens", 0) or 0# Prefer the actual backing model returned by LiteLLM so we don't persist the- # router group name (e.g. "GEMINI_2_5_FLASH_WITH_FALLBACK") when the router+ # router group name (e.g. "GEMINI_3_0_FLASH_WITH_FALLBACK") when the router# falls back. Mirrors the pattern in llm_api_handler/call.# Phase 1 tradeoff: last_llm_model records the most recent model used in# the step. dbt attributes the full step_cost to it, which is accuratediff --git a/skyvern/forge/sdk/api/llm/config_registry.py b/skyvern/forge/sdk/api/llm/config_registry.pyindex 84514d3d2..f0165a352 100644--- a/skyvern/forge/sdk/api/llm/config_registry.py+++ b/skyvern/forge/sdk/api/llm/config_registry.py@@ -1461,158 +1461,6 @@ if settings.ENABLE_GEMINI:max_completion_tokens=8192,),)- _register_builtin_config(- "GEMINI_2.5_PRO",- LLMConfig(- "gemini/gemini-2.5-pro",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_PRO_PREVIEW",- LLMConfig(- "gemini/gemini-2.5-pro-preview-05-06",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_PRO_EXP_03_25",- LLMConfig(- "gemini/gemini-2.5-pro-exp-03-25",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_FLASH",- LLMConfig(- "gemini/gemini-2.5-flash",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_FLASH_PREVIEW",- LLMConfig(- "gemini/gemini-2.5-flash-preview-05-20",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- # Gemini API (Google AI Studio) flex tier variants — 50% cheaper, best-effort latency.- # Docs: https://ai.google.dev/gemini-api/docs/flex-inference- _register_builtin_config(- "GEMINI_2.5_PRO_FLEX",- LLMConfig(- "gemini/gemini-2.5-pro",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- service_tier="flex",- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_FLASH_FLEX",- LLMConfig(- "gemini/gemini-2.5-flash",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- service_tier="flex",- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_FLASH_LITE",- LLMConfig(- "gemini/gemini-2.5-flash-lite",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- ),- ),- )- _register_builtin_config(- "GEMINI_2.5_FLASH_LITE_FLEX",- LLMConfig(- "gemini/gemini-2.5-flash-lite",- ["GEMINI_API_KEY"],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65536,- litellm_params=LiteLLMParams(- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- service_tier="flex",- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )_register_builtin_config("GEMINI_3.0_FLASH",LLMConfig(@@ -1680,6 +1528,8 @@ if settings.ENABLE_GEMINI:)# litellm prices the gemini/ flex tier itself (50% of standard), unlike the Vertex flex# configs whose discount is applied at the cost site in api_handler_factory.+ # Gemini API (Google AI Studio) flex tier variants — 50% cheaper, best-effort latency.+ # Docs: https://ai.google.dev/gemini-api/docs/flex-inference_register_builtin_config("GEMINI_3.1_FLASH_LITE_FLEX",LLMConfig(@@ -1892,158 +1742,6 @@ if settings.ENABLE_VERTEX_AI:if settings.VERTEX_LOCATION == "global" and settings.VERTEX_PROJECT_ID:api_base = f"https://aiplatform.googleapis.com/v1/projects/{settings.VERTEX_PROJECT_ID}/locations/global/publishers/google/models"- _register_builtin_config(- "VERTEX_GEMINI_2.5_PRO",- LLMConfig(- "vertex_ai/gemini-2.5-pro",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-pro" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_PRO_PREVIEW",- LLMConfig(- "vertex_ai/gemini-2.5-pro-preview-05-06",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-pro-preview-05-06" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_DEPRECATED",- LLMConfig(- "vertex_ai/gemini-2.5-flash",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_LITE_DEPRECATED",- LLMConfig(- "vertex_ai/gemini-2.5-flash-lite",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-lite" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_PREVIEW",- LLMConfig(- "vertex_ai/gemini-2.5-flash-preview-05-20",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-preview-05-20" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_PREVIEW_04_17",- LLMConfig(- "vertex_ai/gemini-2.5-flash-preview-04-17",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-preview-04-17" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_PREVIEW_05_20",- LLMConfig(- "vertex_ai/gemini-2.5-flash-preview-05-20",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-preview-05-20" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH",- LLMConfig(- "vertex_ai/gemini-2.5-flash",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )_register_builtin_config("VERTEX_GEMINI_3_PRO",LLMConfig(@@ -2144,25 +1842,6 @@ if settings.ENABLE_VERTEX_AI:# Bump VERTEX_GEMINI_3_PRO above when Google ships a newer version.LLMConfigRegistry.register_config_alias("VERTEX_GEMINI_3.0_PRO", "VERTEX_GEMINI_3_PRO")LLMConfigRegistry.register_config_alias("VERTEX_GEMINI_3.1_PRO", "VERTEX_GEMINI_3_PRO")- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_LITE",- LLMConfig(- "vertex_ai/gemini-2.5-flash-lite",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-lite" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )# Flex tier variants — 50% cheaper, best-effort latency (1-15 min), sheddable.# Use for latency-tolerant workloads (script gen, extraction, validation).# Falls back to standard tier via router configs.@@ -2170,72 +1849,6 @@ if settings.ENABLE_VERTEX_AI:# Without it, drop_params=True silently strips service_tier and requests go through at standard pricing.# TODO: If adding "priority" tier support, pass service_tier="priority" directly —# litellm maps "auto" to "priority", which may cause confusion.- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_FLEX",- LLMConfig(- "vertex_ai/gemini-2.5-flash",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- service_tier="SERVICE_TIER_FLEX",- extra_headers={"X-Vertex-AI-LLM-Shared-Request-Type": "flex", "X-Vertex-AI-LLM-Request-Type": "shared"},- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_LITE_FLEX",- LLMConfig(- "vertex_ai/gemini-2.5-flash-lite",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-lite" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- service_tier="SERVICE_TIER_FLEX",- extra_headers={"X-Vertex-AI-LLM-Shared-Request-Type": "flex", "X-Vertex-AI-LLM-Request-Type": "shared"},- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_PRO_FLEX",- LLMConfig(- "vertex_ai/gemini-2.5-pro",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-pro" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- service_tier="SERVICE_TIER_FLEX",- extra_headers={"X-Vertex-AI-LLM-Shared-Request-Type": "flex", "X-Vertex-AI-LLM-Request-Type": "shared"},- timeout=FLEX_EXECUTION_TIMEOUT_SECONDS,- ),- ),- )_register_builtin_config("VERTEX_GEMINI_3.1_FLASH_LITE_FLEX",@@ -2352,44 +1965,6 @@ if settings.ENABLE_VERTEX_AI:),)# Register old keys as aliases to prevent breaking existing tasks- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_PREVIEW_09_2025",- LLMConfig(- "vertex_ai/gemini-2.5-flash-preview-09-2025",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-preview-09-2025" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )- _register_builtin_config(- "VERTEX_GEMINI_2.5_FLASH_LITE_PREVIEW_09_2025",- LLMConfig(- "vertex_ai/gemini-2.5-flash-lite-preview-09-2025",- [],- supports_vision=True,- add_assistant_prefix=False,- max_completion_tokens=65535,- litellm_params=LiteLLMParams(- api_base=f"{api_base}/gemini-2.5-flash-lite-preview-09-2025" if api_base else None,- vertex_location=settings.VERTEX_LOCATION,- thinking={- "budget_tokens": settings.GEMINI_THINKING_BUDGET,- "type": "enabled" if settings.GEMINI_INCLUDE_THOUGHT else None,- },- vertex_credentials=settings.VERTEX_CREDENTIALS,- ),- ),- )_register_builtin_config("VERTEX_GEMINI_FLASH_2_0",LLMConfig(diff --git a/skyvern/forge/sdk/api/llm/vertex_cache_manager.py b/skyvern/forge/sdk/api/llm/vertex_cache_manager.pyindex 8d0bc90fe..3169e6e75 100644--- a/skyvern/forge/sdk/api/llm/vertex_cache_manager.py+++ b/skyvern/forge/sdk/api/llm/vertex_cache_manager.py@@ -91,7 +91,7 @@ class VertexCacheManager:Create a cache object using Vertex AI's /cachedContents API.Args:- model_name: Full model path (e.g., "gemini-2.5-flash")+ model_name: Full model path (e.g., "gemini-3-flash-preview")static_content: The static content to cachecache_key: Unique key to identify this cache (e.g., f"task_{task_id}")ttl_seconds: Time to live in seconds (default: 1 hour)diff --git a/skyvern/forge/sdk/copilot/model_resolver.py b/skyvern/forge/sdk/copilot/model_resolver.pyindex 0e49e67e2..1031ebada 100644--- a/skyvern/forge/sdk/copilot/model_resolver.py+++ b/skyvern/forge/sdk/copilot/model_resolver.py@@ -44,7 +44,7 @@ from skyvern.schemas.llm import LLMConfig, LLMRouterConfigLOG = structlog.get_logger()-# Shape of a Skyvern registry alias (e.g. AZURE_OPENAI_GPT5_6_SOL, VERTEX_GEMINI_2.5_PRO, or a+# Shape of a Skyvern registry alias (e.g. AZURE_OPENAI_GPT5_6_SOL, VERTEX_GEMINI_3_PRO, or a# single-token key like OLLAMA, or a hyphenated one like OPENAI_GPT-4O-2024-08-06): all-caps# alphanumeric segments, optionally joined by "-"/"_"/".", no provider prefix. Real litellm# model strings (gpt-4o, azure/gpt-4.1) never match — they are lowercase and/or provider-@@ -212,7 +212,7 @@ def _degrade_router_to_direct(llm_key: str, config: LLMRouterConfig) -> LLMConfiselected = config.model_list[0]# LLMRouterModelConfig.litellm_params carries the real litellm model string- # in its "model" key (e.g. "vertex_ai/gemini-2.5-flash"); the outer+ # in its "model" key (e.g. "vertex_ai/gemini-3-flash-preview"); the outer# entry.model_name is just a router group alias.params = dict(selected.litellm_params)direct_model_name = params.pop("model", None) or selected.model_namediff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.pyindex 9aaf2f281..fab5f9a2d 100644--- a/skyvern/forge/sdk/core/skyvern_context.py+++ b/skyvern/forge/sdk/core/skyvern_context.py@@ -720,6 +720,8 @@ class SkyvernContext:seed_generated_totp_values: dict[str, set[str]] = field(default_factory=dict, repr=False)multi_field_totp: dict[str, MultiFieldTotpAttempt] = field(default_factory=dict)multi_field_totp_rejections: dict[str, MultiFieldTotpRejection] = field(default_factory=dict)+ submit_click_evidence: dict[str, tuple[datetime.datetime, int, int, int]] = field(default_factory=dict, repr=False)+ completion_gate_engine: RunEngine | None = Nonemulti_field_totp_mask_values: dict[str, set[str]] = field(default_factory=dict, repr=False)multi_field_totp_prompt_values: dict[str, set[str]] = field(default_factory=dict, repr=False)multi_field_totp_artifact_fingerprints: dict[str, tuple[frozenset[str], tuple[tuple[frozenset[str], int], ...]]] = (diff --git a/skyvern/forge/sdk/db/repositories/folders.py b/skyvern/forge/sdk/db/repositories/folders.pyindex 89ca5a49b..6120db842 100644--- a/skyvern/forge/sdk/db/repositories/folders.py+++ b/skyvern/forge/sdk/db/repositories/folders.py@@ -26,6 +26,10 @@ class SoftDeletedFolder(NamedTuple):deleted_schedules: list[tuple[str, str | None]]+class FolderWorkflowSetChangedError(ValueError):+ """The folder's workflow membership changed after a caller authorized its cascade."""++class FoldersRepository(BaseRepository):"""Database operations for folder management."""@@ -176,12 +180,14 @@ class FoldersRepository(BaseRepository):result = await session.execute(stmt)return list(result.scalars().all())- @db_operation("soft_delete_folder")+ @db_operation("soft_delete_folder", expected_errors=(FolderWorkflowSetChangedError,))async def soft_delete_folder(self,folder_id: str,organization_id: str,delete_workflows: bool = False,+ *,+ expected_workflow_permanent_ids: set[str] | None = None,) -> SoftDeletedFolder | None:"""Soft delete a folder, its workflows and their schedules in one transaction; None when there is no folder."""async with self.Session() as session:@@ -190,12 +196,15 @@ class FoldersRepository(BaseRepository):select(FolderModel).filter_by(folder_id=folder_id, organization_id=organization_id).filter(FolderModel.deleted_at.is_(None))+ # Keep both delete modes in the folder -> workflow lock order used by workflow writers.+ .with_for_update())folder_result = await session.execute(folder_stmt)folder = folder_result.scalar_one_or_none()if not folder:return None+ now = datetime.now(timezone.utc).replace(tzinfo=None)workflow_permanent_ids: list[str] = []deleted_schedules: list[tuple[str, str | None]] = []# If delete_workflows is True, delete all workflows in the folder@@ -225,9 +234,14 @@ class FoldersRepository(BaseRepository):& (WorkflowModel.version == subquery.c.max_version),).where(WorkflowModel.folder_id == folder_id)+ .with_for_update(of=WorkflowModel))result = await session.execute(workflow_permanent_ids_stmt)workflow_permanent_ids = list(result.scalars().all())+ if expected_workflow_permanent_ids is not None and set(workflow_permanent_ids) != (+ expected_workflow_permanent_ids+ ):+ raise FolderWorkflowSetChangedError("Folder workflows changed during delete; retry the request.")# Soft delete all workflows with these permanent IDs in a single bulk updateif workflow_permanent_ids:@@ -236,14 +250,14 @@ class FoldersRepository(BaseRepository):.where(BrowserRecordingModel.workflow_permanent_id.in_(workflow_permanent_ids)).where(BrowserRecordingModel.organization_id == organization_id).where(BrowserRecordingModel.deleted_at.is_(None))- .values(deleted_at=datetime.now(timezone.utc))+ .values(deleted_at=now))update_workflows_query = (update(WorkflowModel).where(WorkflowModel.workflow_permanent_id.in_(workflow_permanent_ids)).where(WorkflowModel.organization_id == organization_id).where(WorkflowModel.deleted_at.is_(None))- .values(deleted_at=datetime.now(timezone.utc))+ .values(deleted_at=now))await session.execute(update_workflows_query)schedules_result = await session.execute(@@ -251,7 +265,7 @@ class FoldersRepository(BaseRepository):.where(WorkflowScheduleModel.workflow_permanent_id.in_(workflow_permanent_ids)).where(WorkflowScheduleModel.organization_id == organization_id).where(WorkflowScheduleModel.deleted_at.is_(None))- .values(deleted_at=datetime.now(timezone.utc))+ .values(deleted_at=now).returning(WorkflowScheduleModel.workflow_schedule_id, WorkflowScheduleModel.backend_schedule_id)@@ -263,12 +277,12 @@ class FoldersRepository(BaseRepository):update(WorkflowModel).where(WorkflowModel.folder_id == folder_id).where(WorkflowModel.organization_id == organization_id)- .values(folder_id=None, modified_at=datetime.now(timezone.utc))+ .values(folder_id=None, modified_at=now))await session.execute(update_workflows_query)# Soft delete the folder- folder.deleted_at = datetime.now(timezone.utc)+ folder.deleted_at = nowawait session.commit()return SoftDeletedFolder(workflow_permanent_ids, deleted_schedules)@@ -382,6 +396,7 @@ class FoldersRepository(BaseRepository):.where(FolderModel.folder_id == folder_id).where(FolderModel.organization_id == organization_id).where(FolderModel.deleted_at.is_(None))+ .with_for_update())if (await session.scalar(stmt)) is None:raise ValueError(f"Folder {folder_id} not found")diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.pyindex 0b623faba..bd3dbfc14 100644--- a/skyvern/forge/sdk/db/repositories/workflows.py+++ b/skyvern/forge/sdk/db/repositories/workflows.py@@ -76,6 +76,10 @@ class WorkflowCreationLockTimeout(Exception):pass+class WorkflowFolderChangedError(ValueError):+ """The workflow moved after its folder access was checked for deletion."""++@dataclass(frozen=True)class WorkflowDispatchState:run_with: str | None@@ -202,16 +206,20 @@ class WorkflowsRepository(BaseRepository):yield@asynccontextmanager- async def version_write_transaction(self) -> AsyncIterator[None]:+ async def version_write_transaction(self, workflow_permanent_id: str | None = None) -> AsyncIterator[None]:"""Bind every write in the block to one transaction.A save allocates its version row before it can build the definition that fills it (thedefinition is keyed by the new ``workflow_id``). Committing the row first publishes anempty workflow as the latest version, so every write between entering and leaving this- block becomes visible at once instead.+ block becomes visible at once instead. Updates also serialize with deletion for this workflow."""- async with self._workflow_creation_transaction():- yield+ if workflow_permanent_id is None:+ async with self._workflow_creation_transaction():+ yield+ else:+ async with self.acquire_workflow_creation_lock(workflow_permanent_id):+ yieldasync def _latest_version_definition(self, session: Any, workflow_permanent_id: str, organization_id: str | None@@ -369,9 +377,7 @@ class WorkflowsRepository(BaseRepository):workflow.workflow_id = workflow_idif version:workflow.version = version- session.add(workflow)-- # Update folder's modified_at if folder_id is provided+ # Serialize creates with folder cascades so the cascade sees this row or rejects the create.if folder_id:# Validate folder exists and belongs to the same organizationfolder_stmt = (@@ -379,14 +385,16 @@ class WorkflowsRepository(BaseRepository):.where(FolderModel.folder_id == folder_id).where(FolderModel.organization_id == organization_id).where(FolderModel.deleted_at.is_(None))+ .with_for_update())folder_model = await session.scalar(folder_stmt)if not folder_model:raise ValueError(f"Folder {folder_id} not found or does not belong to organization {organization_id}")- folder_model.modified_at = datetime.now(UTC)+ folder_model.modified_at = datetime.now(UTC).replace(tzinfo=None)+ session.add(workflow)await session.commit()await session.refresh(workflow)return convert_to_workflow(workflow, self.debug_enabled)@@ -539,6 +547,53 @@ class WorkflowsRepository(BaseRepository):)return None+ @db_operation("get_workflow_original_creators")+ async def get_workflow_original_creators(+ self, workflow_permanent_ids: set[str], organization_id: str+ ) -> dict[str, str | None]:+ if not workflow_permanent_ids:+ return {}+ async with self.Session() as session:+ workflow_ids = (+ select(WorkflowModel.organization_id, WorkflowModel.workflow_permanent_id)+ .where(+ WorkflowModel.organization_id == organization_id,+ WorkflowModel.workflow_permanent_id.in_(workflow_permanent_ids),+ )+ .group_by(WorkflowModel.organization_id, WorkflowModel.workflow_permanent_id)+ .subquery()+ )+ first_versions = (+ select(+ WorkflowModel.organization_id,+ WorkflowModel.workflow_permanent_id,+ func.min(WorkflowModel.version).label("min_version"),+ )+ .where(+ WorkflowModel.organization_id == organization_id,+ WorkflowModel.workflow_permanent_id.in_(workflow_permanent_ids),+ or_(WorkflowModel.created_by.is_(None), WorkflowModel.created_by != COPILOT_TEST_WORKFLOW_CREATOR),+ )+ .group_by(WorkflowModel.organization_id, WorkflowModel.workflow_permanent_id)+ .subquery()+ )+ result = await session.execute(+ select(workflow_ids.c.workflow_permanent_id, WorkflowModel.created_by)+ .select_from(workflow_ids)+ .outerjoin(+ first_versions,+ (workflow_ids.c.organization_id == first_versions.c.organization_id)+ & (workflow_ids.c.workflow_permanent_id == first_versions.c.workflow_permanent_id),+ )+ .outerjoin(+ WorkflowModel,+ (WorkflowModel.organization_id == workflow_ids.c.organization_id)+ & (WorkflowModel.workflow_permanent_id == workflow_ids.c.workflow_permanent_id)+ & (WorkflowModel.version == first_versions.c.min_version),+ )+ )+ return dict(result.all())+@db_operation("get_workflow_for_workflow_run")async def get_workflow_for_workflow_run(self,@@ -1553,56 +1608,76 @@ class WorkflowsRepository(BaseRepository):is_template=is_template,)- @db_operation("soft_delete_workflow_and_schedules_by_permanent_id")+ @db_operation("soft_delete_workflow_and_schedules_by_permanent_id", expected_errors=(WorkflowFolderChangedError,))async def soft_delete_workflow_and_schedules_by_permanent_id(self,workflow_permanent_id: str,organization_id: str | None = None,+ *,+ expected_folder_assignment: tuple[str, str | None] | None = None,) -> tuple[list[tuple[str, str | None]], str | None]:"""Soft-delete a workflow and its active schedules in one transaction; returns (schedule id, backend id)."""- async with self.Session() as session:- select_query = (- select(WorkflowScheduleModel.workflow_schedule_id, WorkflowScheduleModel.backend_schedule_id)- .where(WorkflowScheduleModel.workflow_permanent_id == workflow_permanent_id)- .where(WorkflowScheduleModel.deleted_at.is_(None))- )- if organization_id is not None:- select_query = select_query.where(WorkflowScheduleModel.organization_id == organization_id)- result = await session.execute(select_query)- deleted_schedules = [(row[0], row[1]) for row in result.all()]- schedule_ids = [schedule_id for schedule_id, _ in deleted_schedules]-- deleted_at = datetime.now(UTC)- if schedule_ids:- update_schedules_query = (- update(WorkflowScheduleModel)- .where(WorkflowScheduleModel.workflow_schedule_id.in_(schedule_ids))- .values(deleted_at=deleted_at)+ async with self.acquire_workflow_creation_lock(workflow_permanent_id):+ async with self.Session() as session:+ if expected_folder_assignment is not None:+ expected_workflow_id, expected_folder_id = expected_folder_assignment+ if expected_workflow_id != workflow_permanent_id:+ raise WorkflowFolderChangedError("Workflow folder changed during delete; retry the request.")+ workflow_query = (+ select(WorkflowModel)+ .where(WorkflowModel.workflow_permanent_id == workflow_permanent_id)+ .where(WorkflowModel.deleted_at.is_(None))+ )+ if organization_id is not None:+ workflow_query = workflow_query.where(WorkflowModel.organization_id == organization_id)+ current_workflow = await session.scalar(+ workflow_query.order_by(WorkflowModel.version.desc()).limit(1).with_for_update()+ )+ if current_workflow is not None and current_workflow.folder_id != expected_folder_id:+ raise WorkflowFolderChangedError("Workflow folder changed during delete; retry the request.")++ select_query = (+ select(WorkflowScheduleModel.workflow_schedule_id, WorkflowScheduleModel.backend_schedule_id)+ .where(WorkflowScheduleModel.workflow_permanent_id == workflow_permanent_id)+ .where(WorkflowScheduleModel.deleted_at.is_(None)))- await session.execute(update_schedules_query)+ if organization_id is not None:+ select_query = select_query.where(WorkflowScheduleModel.organization_id == organization_id)+ result = await session.execute(select_query)+ deleted_schedules = [(row[0], row[1]) for row in result.all()]+ schedule_ids = [schedule_id for schedule_id, _ in deleted_schedules]++ deleted_at = datetime.now(UTC)+ if schedule_ids:+ update_schedules_query = (+ update(WorkflowScheduleModel)+ .where(WorkflowScheduleModel.workflow_schedule_id.in_(schedule_ids))+ .values(deleted_at=deleted_at)+ )+ await session.execute(update_schedules_query)- update_workflow_query = (- update(WorkflowModel)- .where(WorkflowModel.workflow_permanent_id == workflow_permanent_id)- .where(WorkflowModel.deleted_at.is_(None))- )- if organization_id is not None:- update_workflow_query = update_workflow_query.filter_by(organization_id=organization_id)- workflow_result = await session.execute(- update_workflow_query.values(deleted_at=deleted_at).returning(WorkflowModel.workflow_permanent_id)- )- deleted_workflow_id = workflow_result.scalars().first()- recording_delete_query = update(BrowserRecordingModel).where(- BrowserRecordingModel.workflow_permanent_id == workflow_permanent_id,- BrowserRecordingModel.deleted_at.is_(None),- )- if organization_id is not None:- recording_delete_query = recording_delete_query.where(- BrowserRecordingModel.organization_id == organization_id+ update_workflow_query = (+ update(WorkflowModel)+ .where(WorkflowModel.workflow_permanent_id == workflow_permanent_id)+ .where(WorkflowModel.deleted_at.is_(None)))- await session.execute(recording_delete_query.values(deleted_at=deleted_at))- await session.commit()- return deleted_schedules, deleted_workflow_id+ if organization_id is not None:+ update_workflow_query = update_workflow_query.filter_by(organization_id=organization_id)+ workflow_result = await session.execute(+ update_workflow_query.values(deleted_at=deleted_at).returning(WorkflowModel.workflow_permanent_id)+ )+ deleted_workflow_id = workflow_result.scalars().first()+ recording_delete_query = update(BrowserRecordingModel).where(+ BrowserRecordingModel.workflow_permanent_id == workflow_permanent_id,+ BrowserRecordingModel.deleted_at.is_(None),+ )+ if organization_id is not None:+ recording_delete_query = recording_delete_query.where(+ BrowserRecordingModel.organization_id == organization_id+ )+ await session.execute(recording_delete_query.values(deleted_at=deleted_at))+ await session.commit()+ return deleted_schedules, deleted_workflow_id@db_operation("add_workflow_template")async def add_workflow_template(diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 461d60d23..0e6adac76 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -84,6 +84,7 @@ from skyvern.forge.sdk.db.enums import (is_job_recipe_workflow_run_trigger_type,)from skyvern.forge.sdk.db.exceptions import RunsListSearchCanceled+from skyvern.forge.sdk.db.repositories.folders import FolderWorkflowSetChangedErrorfrom skyvern.forge.sdk.db.repositories.tags import (RunTagWorkflowRunMismatch,TagValueAlreadyExists,@@ -94,7 +95,7 @@ from skyvern.forge.sdk.db.repositories.workflow_runs import (RUNS_LIST_STATEMENT_TIMEOUT_SECONDS,is_indexed_runs_list_search_key,)-from skyvern.forge.sdk.db.repositories.workflows import WorkflowCreationLockTimeout+from skyvern.forge.sdk.db.repositories.workflows import WorkflowCreationLockTimeout, WorkflowFolderChangedErrorfrom skyvern.forge.sdk.db.statement_timeout import is_statement_timeoutfrom skyvern.forge.sdk.enterprise_features import collect_enterprise_gated_run_featuresfrom skyvern.forge.sdk.executor.factory import AsyncExecutorFactory@@ -1486,6 +1487,12 @@ async def update_workflow_legacy(if 400 <= e.status_code < 500:log_save_rejected(e)raise+ except WorkflowCreationLockTimeout as exc:+ log_save_rejected(exc)+ raise HTTPException(+ status_code=http_status.HTTP_409_CONFLICT,+ detail="Workflow is being updated; retry the save request.",+ ) from excexcept Exception as e:LOG.exception("Failed to update workflow",@@ -1586,6 +1593,11 @@ async def update_workflow(except (HTTPException, SkyvernHTTPException, ValidationError) as e:# Bubble up well-formed client errors so they are not converted to 500sraise e+ except WorkflowCreationLockTimeout as exc:+ raise HTTPException(+ status_code=http_status.HTTP_409_CONFLICT,+ detail="Workflow is being updated; retry the save request.",+ ) from excexcept Exception as e:LOG.exception("Failed to update workflow",@@ -1647,9 +1659,28 @@ async def delete_workflow(current_org: Organization = Depends(org_auth_service.get_current_org),) -> None:analytics.capture("skyvern-oss-agent-workflow-delete")- deleted_schedules, deleted_workflow_id = await app.WORKFLOW_SERVICE.soft_delete_workflow_by_permanent_id(- workflow_id, current_org.organization_id+ expected_folder_assignment = await app.AGENT_FUNCTION.enforce_workflow_delete(+ get_request_principal(), workflow_id, current_org.organization_id)+ try:+ soft_delete_workflow = app.WORKFLOW_SERVICE.soft_delete_workflow_by_permanent_id+ if expected_folder_assignment is None:+ deleted_schedules, deleted_workflow_id = await soft_delete_workflow(+ workflow_id, current_org.organization_id+ )+ else:+ deleted_schedules, deleted_workflow_id = await soft_delete_workflow(+ workflow_id,+ current_org.organization_id,+ expected_folder_assignment=expected_folder_assignment,+ )+ except WorkflowFolderChangedError as exc:+ raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(exc)) from exc+ except WorkflowCreationLockTimeout as exc:+ raise HTTPException(+ status_code=http_status.HTTP_409_CONFLICT,+ detail="Workflow is being updated; retry the delete request.",+ ) from exc# Audit before the cancellable backend cleanup: the delete has already committed. Schedules are soft-deleted# even when no live workflow was, so their backend schedules are deleted either way.try:@@ -1927,11 +1958,24 @@ async def delete_folder(current_org: Organization = Depends(org_auth_service.get_current_org),) -> dict:analytics.capture("skyvern-oss-folder-delete")- deleted_folder = await app.DATABASE.folders.soft_delete_folder(- folder_id=folder_id,- organization_id=current_org.organization_id,- delete_workflows=delete_workflows,- )+ expected_workflow_permanent_ids: set[str] | None = None+ if delete_workflows:+ workflow_ids = await app.DATABASE.folders.get_workflow_permanent_ids_in_folder(+ folder_id, current_org.organization_id+ )+ expected_workflow_permanent_ids = set(workflow_ids)+ await app.AGENT_FUNCTION.enforce_workflow_deletes(+ get_request_principal(), expected_workflow_permanent_ids, current_org.organization_id+ )+ try:+ deleted_folder = await app.DATABASE.folders.soft_delete_folder(+ folder_id=folder_id,+ organization_id=current_org.organization_id,+ delete_workflows=delete_workflows,+ expected_workflow_permanent_ids=expected_workflow_permanent_ids,+ )+ except FolderWorkflowSetChangedError as exc:+ raise HTTPException(status_code=http_status.HTTP_409_CONFLICT, detail=str(exc)) from excif deleted_folder is None:raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=f"Folder {folder_id} not found")# Audit before the cancellable backend cleanup: the delete has already committed.diff --git a/skyvern/forge/sdk/routes/credentials.py b/skyvern/forge/sdk/routes/credentials.pyindex f9af2db13..04f4b3810 100644--- a/skyvern/forge/sdk/routes/credentials.py+++ b/skyvern/forge/sdk/routes/credentials.py@@ -122,6 +122,8 @@ from skyvern.forge.sdk.schemas.organizations import (AzureOrganizationAuthToken,BitwardenCredentialResponse,BitwardenCredentialSafe,+ BitwardenCredentialStatus,+ BitwardenCredentialStatusResponse,BitwardenOrganizationAuthToken,BitwardenOrganizationAuthTokenSafe,ClearOrganizationAuthTokenResponse,@@ -3979,19 +3981,19 @@ def _to_safe_bitwarden_response(auth_token: BitwardenOrganizationAuthToken) -> B@base_router.get("/credentials/bitwarden/get",- response_model=BitwardenCredentialResponse,+ response_model=BitwardenCredentialResponse | BitwardenCredentialStatusResponse,summary="Get Bitwarden credential",description="Retrieves the current Bitwarden credential for the organization. The master_password is never returned for security.",include_in_schema=False,)@base_router.get("/credentials/bitwarden/get/",- response_model=BitwardenCredentialResponse,+ response_model=BitwardenCredentialResponse | BitwardenCredentialStatusResponse,include_in_schema=False,)async def get_bitwarden_credential(current_org: Organization = Depends(org_auth_service.get_current_org_for_credential_routes),-) -> BitwardenCredentialResponse:+) -> BitwardenCredentialResponse | BitwardenCredentialStatusResponse:"""Get the current Bitwarden credential for the organization."""@@ -4006,6 +4008,16 @@ async def get_bitwarden_credential(detail="No Bitwarden credential found for this organization",)+ if await _should_redact_org_credential_secrets(current_org.organization_id):+ return BitwardenCredentialStatusResponse(+ token=BitwardenCredentialStatus(+ id=auth_token.id,+ token_type=auth_token.token_type,+ valid=auth_token.valid,+ created_at=auth_token.created_at,+ modified_at=auth_token.modified_at,+ )+ )return _to_safe_bitwarden_response(auth_token)except HTTPException:diff --git a/skyvern/forge/sdk/schemas/organizations.py b/skyvern/forge/sdk/schemas/organizations.pyindex 1ea70d414..756de7123 100644--- a/skyvern/forge/sdk/schemas/organizations.py+++ b/skyvern/forge/sdk/schemas/organizations.py@@ -130,6 +130,18 @@ class BitwardenCredentialResponse(BaseModel):)+class BitwardenCredentialStatus(BaseModel):+ id: str+ token_type: str+ valid: bool+ created_at: datetime+ modified_at: datetime+++class BitwardenCredentialStatusResponse(BaseModel):+ token: BitwardenCredentialStatus++def _twilio_error_without_inputs(error: ValidationError) -> ValidationError:# hide_input_in_errors only affects text; remove inputs from structured errors too.return ValidationError.from_exception_data(diff --git a/skyvern/forge/sdk/services/org_auth_service.py b/skyvern/forge/sdk/services/org_auth_service.pyindex 72a6910f8..bce2c2f06 100644--- a/skyvern/forge/sdk/services/org_auth_service.py+++ b/skyvern/forge/sdk/services/org_auth_service.py@@ -22,6 +22,9 @@ from skyvern.forge.sdk.db.agent_db import AgentDBfrom skyvern.forge.sdk.models import TokenPayloadfrom skyvern.forge.sdk.schemas.organizations import Organization, OrganizationAuthToken, OrganizationAuthTokenTypefrom skyvern.forge.sdk.services.request_principal import (+ AuthKind,+ get_request_principal,+ human_user_id,resolve_api_key_profile_identity,resolve_request_principal,synthetic_user_id,@@ -467,6 +470,9 @@ async def get_current_user_id_or_none(x_fern_language: Annotated[str | None, Header(include_in_schema=False)] = None,) -> str | None:"""Best-effort caller resolution for write attribution; never rejects the request."""+ principal = get_request_principal()+ if principal is not None and principal.auth_kind == AuthKind.member_api_key:+ return human_user_id(principal, principal.organization_id)try:user_id = await get_current_user_id(authorization=authorization,diff --git a/skyvern/forge/sdk/utils/capped_subprocess.py b/skyvern/forge/sdk/utils/capped_subprocess.pynew file mode 100644index 000000000..c938eacc2--- /dev/null+++ b/skyvern/forge/sdk/utils/capped_subprocess.py@@ -0,0 +1,494 @@+"""Run a function in a fresh Python process under a memory cap and a wall-clock timeout, so work that can allocate+without bound, such as parsing an untrusted file, kills only its child and raises CappedSubprocessError."""++import contextlib+import io+import math+import os+import pickle+import re+import signal+import struct+import subprocess+import sys+import threading+import time+from collections.abc import Callable, Iterator, Mapping+from typing import IO, Any, Literal, NamedTuple, NoReturn, TypeVar, TypeVarTuple, Unpack, cast++import psutil+import structlog++from skyvern.forge.sdk.utils.capped_subprocess_child import CGROUP_DIR, MEMINFO_PATH, memory_allowance++LOG = structlog.get_logger(__name__)++_T = TypeVar("_T")+_Ts = TypeVarTuple("_Ts")++CappedSubprocessFailure = Literal["error", "out_of_memory", "timeout", "crashed", "result_too_large", "no_headroom"]++# Only Linux enforces RLIMIT_AS; macOS refuses to lower it, so there the memory watchdog is the only memory guard.+MEMORY_CAP_ENFORCED = sys.platform.startswith("linux")+_NO_HEADROOM_MESSAGE = "there was not enough free memory to run it safely"+# The parent holds a result decoded, which takes more than its pickled bytes: word dicts 5.9x for real words and up+# to 6.4x for crafted ones on Python 3.11, text with astral characters up to 6x. A result of mostly bytes passes 1.+DEFAULT_RESULT_MEMORY_FACTOR = 7++# -I keeps the child from running a sitecustomize injected through PYTHONPATH (opentelemetry-instrument does this),+# so the parent's sys.path is handed over explicitly instead.+_CHILD_BOOTSTRAP = (+ "import sys; sys.path[:] = sys.argv[1:]; from skyvern.forge.sdk.utils.capped_subprocess_child import main; main()"+)+# The CPU limit only catches a child whose parent died before killing it: a single-threaded child cannot use more+# CPU time than wall time, so the parent's timer always fires first.+_CPU_LIMIT_MARGIN_SECONDS = 10+_EXIT_GRACE_SECONDS = 5+_WATCHDOG_POLL_SECONDS = 0.25+_STDERR_TAIL_BYTES = 4096+_URL_QUERY = re.compile(r"(\w+://[^\s?#]*)[?#]\S*")+++class CappedSubprocessError(Exception):+ def __init__(self, message: str, kind: CappedSubprocessFailure) -> None:+ super().__init__(message)+ self.kind = kind+++class _ResultTooLarge(Exception):+ pass+++class _NotPlainData(pickle.UnpicklingError):+ pass+++class _UnexpectedShape(Exception):+ pass+++class _BoundedReader:+ """Hands the unpickler at most limit bytes of the child's stdout. Reads ask the pipe for no more than one byte+ past what is left, and readinto refuses a buffer larger than what is left before reading into it."""++ def __init__(self, stream: io.BufferedReader, limit: int) -> None:+ self._stream = stream+ self._remaining = limit++ def read(self, size: int | None = -1) -> bytes:+ return self._counted(self._stream.read(self._clamped(size)))++ def readline(self, size: int | None = -1) -> bytes:+ return self._counted(self._stream.readline(self._clamped(size)))++ def readinto(self, buffer: Any) -> int:+ view = memoryview(buffer)+ if view.nbytes > self._remaining:+ raise _ResultTooLarge+ count = self._stream.readinto(view) or 0+ self._remaining -= count+ return count++ def _clamped(self, size: int | None) -> int:+ most = self._remaining + 1+ return most if size is None or size < 0 else min(size, most)++ def _counted(self, data: bytes) -> bytes:+ self._remaining -= len(data)+ if self._remaining < 0:+ raise _ResultTooLarge+ return data+++class _PlainDataUnpickler(pickle.Unpickler):+ """Loads the child's output, which is plain builtin data. Unpickling then cannot import or call anything: an+ output that names any class or function is refused."""++ def find_class(self, module_name: str, global_name: str, /) -> Any:+ raise _NotPlainData(f"the child sent {module_name}.{global_name}")+++_OUTCOME_STATUSES = ("ok", "error", "out_of_memory", "no_headroom", "result_too_large")+_OUTCOME_INT_FIELDS = ("allowance_bytes", "headroom_bytes")+_OUTCOME_STR_FIELDS = ("error_type", "headroom_source")+++def _checked_outcome(loaded: object) -> dict[str, Any]:+ if not isinstance(loaded, dict) or loaded.get("status") not in _OUTCOME_STATUSES:+ raise _UnexpectedShape("the outcome is not a dict with a known status")+ if loaded["status"] == "ok" and "value" not in loaded:+ raise _UnexpectedShape("an ok outcome has no value")+ if loaded["status"] == "error" and not isinstance(loaded.get("message"), str):+ raise _UnexpectedShape("an error outcome has no message")+ for name in _OUTCOME_INT_FIELDS:+ if loaded.get(name) is not None and type(loaded[name]) is not int:+ raise _UnexpectedShape(f"{name} is not an int")+ for name in _OUTCOME_STR_FIELDS:+ if loaded.get(name) is not None and not isinstance(loaded[name], str):+ raise _UnexpectedShape(f"{name} is not a string")+ return loaded+++def _checked_ready(loaded: object) -> int | None:+ if not isinstance(loaded, dict) or loaded.get("status") != "ready":+ raise _UnexpectedShape("the first message is not a ready message")+ allowance = loaded.get("allowance_bytes")+ if allowance is not None and type(allowance) is not int:+ raise _UnexpectedShape("the ready message has an allowance that is not an int")+ return allowance+++class _MemoryWatchdog:+ """Reads the child's resident memory with psutil and kills it once it has grown past its allowance from the+ baseline taken when it reported ready. RLIMIT_AS bounds a Linux child first; here it also bounds a macOS one."""++ def __init__(self, process: subprocess.Popen[bytes], allowance_bytes: int) -> None:+ self.allowance_bytes = allowance_bytes+ self.baseline_bytes: int | None = None+ self.peak_sampled_bytes: int | None = None+ self.rss_at_kill_bytes: int | None = None+ self.killed = threading.Event()+ self._process = process+ self._child: psutil.Process | None = None+ self._lock = threading.Lock()+ self._finished = threading.Event()+ self._thread = threading.Thread(target=self._watch, daemon=True)+ self._started = False++ @property+ def growth_bytes(self) -> int | None:+ if self.baseline_bytes is None or self.peak_sampled_bytes is None:+ return None+ return self.peak_sampled_bytes - self.baseline_bytes++ def start(self) -> None:+ self._thread.start()+ self._started = True++ def learn(self, allowance_bytes: int | None) -> None:+ if allowance_bytes is not None:+ self.allowance_bytes = allowance_bytes+ self.baseline_bytes = self.sample()++ def sample(self) -> int | None:+ try:+ if self._child is None:+ self._child = psutil.Process(self._process.pid)+ rss = self._child.memory_info().rss+ except psutil.Error:+ return None+ with self._lock:+ self.peak_sampled_bytes = rss if self.peak_sampled_bytes is None else max(self.peak_sampled_bytes, rss)+ return rss++ def stop(self) -> None:+ self._finished.set()+ if self._started:+ self._thread.join(timeout=2)++ def _watch(self) -> None:+ while not self._finished.wait(_WATCHDOG_POLL_SECONDS):+ baseline = self.baseline_bytes+ if baseline is None:+ continue+ rss = self.sample()+ if rss is None:+ return+ if rss > baseline + self.allowance_bytes:+ self.rss_at_kill_bytes = rss+ self.killed.set()+ self._process.kill()+ return+++class _Reservation(NamedTuple):+ allowance: int | None+ held_by_others: int+ headroom: int | None+ headroom_source: str+++_reservation_lock = threading.Lock()+_reserved_bytes = 0+++def _reserved_memory(ceiling_bytes: int, result_reserve_bytes: int) -> Iterator[_Reservation]:+ """Reserve what a child may grow by and the decoded result the parent may hold, so children running at once in+ this process are sized against each other. The allowance is None when the pod has no room for the call."""+ global _reserved_bytes+ with _reservation_lock:+ held_by_others = _reserved_bytes+ sized = memory_allowance(ceiling_bytes, result_reserve_bytes + held_by_others, CGROUP_DIR, MEMINFO_PATH)+ if sized.allowance is not None:+ _reserved_bytes += sized.allowance + result_reserve_bytes+ try:+ yield _Reservation(sized.allowance, held_by_others, sized.headroom, sized.source)+ finally:+ if sized.allowance is not None:+ with _reservation_lock:+ _reserved_bytes -= sized.allowance + result_reserve_bytes+++def run_in_capped_subprocess(+ func: Callable[[Unpack[_Ts]], _T],+ *args: Unpack[_Ts],+ memory_limit_bytes: int,+ max_result_bytes: int,+ timeout_seconds: float,+ result_memory_factor: int = DEFAULT_RESULT_MEMORY_FACTOR,+ log_fields: Mapping[str, object] | None = None,+) -> _T:+ """Call func(*args) in a child that may grow by up to memory_limit_bytes once func's module is imported, by less+ when the pod has less free memory, or not at all (no_headroom). func is pickled by reference, so it must be a+ module-level function taking plain data, and what it returns must be plain builtin data of at most+ max_result_bytes pickled, which takes result_memory_factor times that once decoded in this process."""+ target = f"{func.__module__}.{func.__qualname__}"+ if not MEMORY_CAP_ENFORCED:+ LOG.debug("Capped subprocess cannot set RLIMIT_AS on this platform", platform=sys.platform, target=target)+ return _run_child(+ func,+ args,+ allowance=None,+ reserve_bytes=0,+ memory_limit_bytes=memory_limit_bytes,+ max_result_bytes=max_result_bytes,+ timeout_seconds=timeout_seconds,+ target=target,+ log_fields=log_fields,+ )+ result_reserve_bytes = max_result_bytes * result_memory_factor+ with _reserved_memory(memory_limit_bytes, result_reserve_bytes) as reservation:+ fields = {+ **(log_fields or {}),+ "memory_headroom_bytes": reservation.headroom,+ "memory_headroom_source": reservation.headroom_source,+ }+ if reservation.allowance is None:+ _raise_failure(+ "no_headroom",+ _NO_HEADROOM_MESSAGE,+ target=target,+ memory_ceiling_bytes=memory_limit_bytes,+ reserved_by_other_calls_bytes=reservation.held_by_others,+ **fields,+ )+ return _run_child(+ func,+ args,+ allowance=reservation.allowance,+ reserve_bytes=result_reserve_bytes + reservation.held_by_others,+ memory_limit_bytes=memory_limit_bytes,+ max_result_bytes=max_result_bytes,+ timeout_seconds=timeout_seconds,+ target=target,+ log_fields=fields,+ )+++def _run_child(+ func: Callable[[Unpack[_Ts]], _T],+ args: tuple[Unpack[_Ts]],+ *,+ allowance: int | None,+ reserve_bytes: int,+ memory_limit_bytes: int,+ max_result_bytes: int,+ timeout_seconds: float,+ target: str,+ log_fields: Mapping[str, object] | None,+) -> _T:+ request = pickle.dumps(+ {+ "allowance": allowance,+ "reserve_bytes": reserve_bytes,+ "cgroup_dir": os.fspath(CGROUP_DIR),+ "meminfo_path": os.fspath(MEMINFO_PATH),+ "cpu_seconds": math.ceil(timeout_seconds) + _CPU_LIMIT_MARGIN_SECONDS,+ "payload": pickle.dumps((func, args)),+ },+ protocol=pickle.HIGHEST_PROTOCOL,+ )+ started = time.monotonic()+ process = subprocess.Popen(+ [sys.executable, "-I", "-c", _CHILD_BOOTSTRAP, *sys.path],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ )+ stdin, stdout, stderr = (cast(IO[bytes], stream) for stream in (process.stdin, process.stdout, process.stderr))+ stderr_tail = bytearray()+ timed_out = threading.Event()+ drain: threading.Thread | None = None+ timer: threading.Timer | None = None+ watchdog = _MemoryWatchdog(process, allowance if allowance is not None else memory_limit_bytes)+ outcome: dict[str, Any] | None = None+ result_error: str | None = None+ result_problem: str | None = None+ result_too_large = False++ def _kill_on_timeout() -> None:+ timed_out.set()+ process.kill()++ try:+ draining = threading.Thread(target=_keep_tail, args=(stderr, stderr_tail), daemon=True)+ draining.start()+ drain = draining+ timer = threading.Timer(timeout_seconds, _kill_on_timeout)+ timer.daemon = True+ timer.start()+ watchdog.start()+ # A child that died before reading its request closes the pipe; reading its exit below reports that. Stdin+ # stays open until the child's memory has been read, because the child waits for it to close before it exits.+ with contextlib.suppress(BrokenPipeError):+ stdin.write(struct.pack("<Q", len(request)) + request)+ stdin.flush()+ try:+ reader = _BoundedReader(cast(io.BufferedReader, stdout), max_result_bytes)+ loaded = _PlainDataUnpickler(reader).load()+ if isinstance(loaded, dict) and loaded.get("status") == "ready":+ watchdog.learn(_checked_ready(loaded))+ # A new unpickler per message, because one unpickler numbers its memo across the messages it loads.+ loaded = _PlainDataUnpickler(reader).load()+ outcome = _checked_outcome(loaded)+ watchdog.sample()+ except _ResultTooLarge:+ result_too_large = True+ except _NotPlainData as exc:+ result_problem, result_error = "is not plain data", str(exc)[:200]+ except _UnexpectedShape as exc:+ result_problem, result_error = "has an unexpected shape", str(exc)[:200]+ except Exception as exc:+ result_error = type(exc).__name__+ finally:+ if timer is not None:+ timer.cancel()+ watchdog.stop()+ if outcome is None and process.poll() is None:+ process.kill()+ with contextlib.suppress(OSError):+ stdin.close()+ returncode = _wait_for_exit(process)+ if drain is not None:+ drain.join(timeout=5)+ stdout.close()+ stderr.close()++ duration_seconds = round(time.monotonic() - started, 2)+ applied_allowance = outcome.get("allowance_bytes", allowance) if outcome is not None else allowance+ memory_fields = {+ "rss_baseline_bytes": watchdog.baseline_bytes,+ "rss_peak_sampled_bytes": watchdog.peak_sampled_bytes,+ "rss_growth_sampled_bytes": watchdog.growth_bytes,+ "recheck_headroom_bytes": outcome.get("headroom_bytes") if outcome is not None else None,+ "recheck_headroom_source": outcome.get("headroom_source") if outcome is not None else None,+ }+ if outcome is not None and outcome["status"] == "ok":+ LOG.info(+ "Capped subprocess finished",+ target=target,+ duration_seconds=duration_seconds,+ memory_budget_bytes=applied_allowance,+ **memory_fields,+ **(log_fields or {}),+ )+ return outcome["value"]++ kind: CappedSubprocessFailure+ status = outcome["status"] if outcome is not None else None+ if result_too_large or status == "result_too_large":+ kind = "result_too_large"+ message = f"returned more than the {_describe_bytes(max_result_bytes)} a result may hold"+ elif outcome is not None and status == "error":+ kind = "error"+ message = outcome["message"]+ elif status == "out_of_memory":+ kind = "out_of_memory"+ limit_mib = (applied_allowance or memory_limit_bytes) // (1024 * 1024)+ message = f"ran out of memory: it needed more than the {limit_mib} MiB it may use"+ elif status == "no_headroom":+ kind = "no_headroom"+ message = _NO_HEADROOM_MESSAGE+ elif watchdog.killed.is_set():+ kind = "out_of_memory"+ message = (+ f"ran out of memory: it needed more than the {watchdog.allowance_bytes // (1024 * 1024)} MiB it may use"+ )+ elif result_problem is not None:+ kind = "crashed"+ message = f"returned a result that {result_problem}"+ elif timed_out.is_set() or (sys.platform != "win32" and returncode == -signal.SIGXCPU):+ kind = "timeout"+ message = f"did not finish within {_describe_seconds(timeout_seconds)} and was stopped"+ else:+ kind = "crashed"+ message = f"its process exited without a result ({_describe_exit(returncode)})"+ _raise_failure(+ kind,+ message,+ target=target,+ error_type=outcome.get("error_type") if outcome is not None else None,+ result_error=result_error,+ returncode=returncode,+ duration_seconds=duration_seconds,+ memory_budget_bytes=applied_allowance,+ memory_ceiling_bytes=memory_limit_bytes,+ timeout_seconds=timeout_seconds,+ stderr_tail=_scrubbed_tail(stderr_tail),+ killed_by_memory_watchdog=watchdog.killed.is_set(),+ rss_at_kill_bytes=watchdog.rss_at_kill_bytes,+ **memory_fields,+ **(log_fields or {}),+ )+++def _wait_for_exit(process: subprocess.Popen[bytes]) -> int:+ # A child that has handed over its outcome exits at once; one that does not is not allowed to hold the call.+ try:+ return process.wait(timeout=_EXIT_GRACE_SECONDS)+ except subprocess.TimeoutExpired:+ process.kill()+ return process.wait()+++def _raise_failure(kind: CappedSubprocessFailure, message: str, **log_fields: object) -> NoReturn:+ LOG.warning("Capped subprocess failed", failure=kind, **log_fields)+ raise CappedSubprocessError(message, kind=kind)+++def _describe_bytes(count: int) -> str:+ return f"{count // (1024 * 1024)} MiB" if count >= 1024 * 1024 else f"{count // 1024} KiB"+++def _keep_tail(stream: IO[bytes], tail: bytearray) -> None:+ while chunk := os.read(stream.fileno(), 65536):+ tail += chunk+ del tail[:-_STDERR_TAIL_BYTES]+++def _scrubbed_tail(tail: bytearray) -> str | None:+ text = tail.decode("utf-8", errors="replace")+ if len(tail) >= _STDERR_TAIL_BYTES:+ # The cut can land inside a URL's query string, where the scrub below would no longer recognise it.+ text = text.partition("\n")[2]+ return _URL_QUERY.sub(r"\1", text) or None+++def _describe_seconds(seconds: float) -> str:+ rounded = round(seconds)+ return "1 second" if rounded == 1 else f"{rounded} seconds"+++def _describe_exit(returncode: int) -> str:+ if returncode >= 0:+ return f"exit status {returncode}"+ number = -returncode+ try:+ name = signal.Signals(number).name+ except ValueError:+ name = f"signal {number}"+ # PDFium aborts a failed allocation through FX_OutOfMemoryTerminate, which dies as SIGTRAP or SIGSEGV, so under+ # the cap a signal death is most likely the memory limit.+ likely_cause = ", likely out of memory" if MEMORY_CAP_ENFORCED else ""+ return f"killed by {name} (signal {number}{likely_cause})"diff --git a/skyvern/forge/sdk/utils/capped_subprocess_child.py b/skyvern/forge/sdk/utils/capped_subprocess_child.pynew file mode 100644index 000000000..21acd28b5--- /dev/null+++ b/skyvern/forge/sdk/utils/capped_subprocess_child.py@@ -0,0 +1,221 @@+"""The child side of capped_subprocess. It imports only the stdlib, because every capped call pays for its imports+again in a fresh interpreter. The free-memory arithmetic lives here so the parent and the child apply the same rule."""++import faulthandler+import os+import pickle+import struct+import sys+from typing import Any, NamedTuple++if sys.platform != "win32":+ import resource++CGROUP_DIR = "/sys/fs/cgroup"+MEMINFO_PATH = "/proc/meminfo"+# cgroup v2 with memory.oom.group kills the whole container at memory.max, so a child stays this far below it.+CGROUP_HEADROOM_MARGIN_BYTES = 256 * 1024 * 1024+# Less free memory than this fails the call outright instead of spending the pod's last memory on it.+MIN_MEMORY_BUDGET_BYTES = 128 * 1024 * 1024++# cgroup v1 reports "no limit" as a number just under 2^63.+_CGROUP_V1_NO_LIMIT_BYTES = 1 << 62+_MAX_EXCEPTION_CHAIN = 16+_MAX_MESSAGE_CHARS = 4096+++class _NoHeadroom(Exception):+ pass+++class ResultTooLarge(Exception):+ """Raised by the work to say that its result cannot fit the size the parent allows."""+++def main() -> None:+ # The pickled outcome owns the real stdout; anything the work prints goes to stderr, whose tail the parent logs.+ result_stream = os.fdopen(os.dup(1), "wb")+ os.dup2(2, 1)+ # -I ignores PYTHONFAULTHANDLER, and a native crash in PDFium otherwise leaves nothing in that tail.+ faulthandler.enable(file=sys.stderr)+ allowance: int | None = None+ recheck = MemoryAllowance(None, None, "none")+ outcome: dict[str, Any]+ try:+ (request_size,) = struct.unpack("<Q", sys.stdin.buffer.read(8))+ request = pickle.loads(sys.stdin.buffer.read(request_size))+ # Unpickling imports func's module, so a cap set after it leaves the imports out of the call's budget.+ func, args = pickle.loads(request["payload"])+ allowance = request["allowance"]+ if allowance is not None:+ # The parent sized the allowance before this interpreter and func's imports took their share of the pod.+ recheck = memory_allowance(+ allowance, request["reserve_bytes"], request["cgroup_dir"], request["meminfo_path"]+ )+ allowance = recheck.allowance+ if allowance is None:+ raise _NoHeadroom+ _apply_limits(allowance, request["cpu_seconds"])+ # The parent reads this process's resident memory when it gets this message, so growth counts from here.+ pickle.dump({"status": "ready", "allowance_bytes": allowance}, result_stream, protocol=pickle.HIGHEST_PROTOCOL)+ result_stream.flush()+ outcome = {"status": "ok", "value": func(*args)}+ except _NoHeadroom:+ outcome = {"status": "no_headroom"}+ except ResultTooLarge as exc:+ outcome = {"status": "result_too_large", "message": str(exc)[:_MAX_MESSAGE_CHARS]}+ except BaseException as exc:+ if caused_by_memory_error(exc):+ outcome = {"status": "out_of_memory"}+ else:+ outcome = {"status": "error", "error_type": type(exc).__name__, "message": str(exc)[:_MAX_MESSAGE_CHARS]}+ outcome["allowance_bytes"] = allowance+ outcome["headroom_bytes"] = recheck.headroom+ outcome["headroom_source"] = recheck.source+ exit_code = 0+ try:+ pickle.dump(outcome, result_stream, protocol=pickle.HIGHEST_PROTOCOL)+ result_stream.flush()+ # The parent reads this process's memory once it has the outcome and then closes stdin; exiting sooner would+ # leave it nothing to read.+ sys.stdin.buffer.read(1)+ except BaseException:+ exit_code = 1+ sys.stdout.flush()+ sys.stderr.flush()+ # Interpreter teardown after a large parse can take seconds and serves no purpose here.+ os._exit(exit_code)+++class MemoryAllowance(NamedTuple):+ allowance: int | None+ headroom: int | None+ source: str+++def memory_allowance(+ ceiling_bytes: int,+ reserve_bytes: int,+ cgroup_dir: str | os.PathLike[str] = CGROUP_DIR,+ meminfo_path: str | os.PathLike[str] = MEMINFO_PATH,+) -> MemoryAllowance:+ """Size how far a child may grow: ceiling_bytes, lowered to the free memory less the margin and reserve_bytes.+ The allowance is None when that safe amount is under the floor, since crossing memory.max kills the worker."""+ headroom, source = cgroup_headroom_bytes(cgroup_dir), "cgroup"+ if headroom is None:+ headroom, source = cgroup_v1_headroom_bytes(cgroup_dir), "cgroup_v1"+ if headroom is None:+ # Without a container limit, such as a Fargate task whose limit is set above the container, the kernel's+ # estimate of what can be allocated without swapping is the best bound left.+ headroom, source = meminfo_available_bytes(meminfo_path), "meminfo"+ if headroom is None:+ return MemoryAllowance(ceiling_bytes, None, "none")+ safe_bytes = headroom - CGROUP_HEADROOM_MARGIN_BYTES - reserve_bytes+ return MemoryAllowance(+ min(ceiling_bytes, safe_bytes) if safe_bytes >= MIN_MEMORY_BUDGET_BYTES else None, headroom, source+ )+++def cgroup_headroom_bytes(cgroup_dir: str | os.PathLike[str]) -> int | None:+ """Return memory.max less the memory the cgroup holds that cannot be reclaimed, or None when it sets no limit.+ Once there is a limit, anything unreadable counts against the caller, never for it."""+ try:+ limit = _read_file(os.path.join(cgroup_dir, "memory.max"))+ limit_bytes = None if limit == "max" else int(limit)+ except (OSError, ValueError):+ return None+ if limit_bytes is None:+ return None+ try:+ used = int(_read_file(os.path.join(cgroup_dir, "memory.current")))+ except (OSError, ValueError):+ return 0+ # Inactive page cache is reclaimed before the OOM killer runs, so it counts as free, as in kubelet's working set.+ inactive_file = _stat_value(_read_text_or_empty(os.path.join(cgroup_dir, "memory.stat")), "inactive_file")+ return limit_bytes - (used - (inactive_file or 0))+++def cgroup_v1_headroom_bytes(cgroup_dir: str | os.PathLike[str]) -> int | None:+ """The same for cgroup v1, where the memory controller has its own directory and files."""+ v1_dir = os.path.join(cgroup_dir, "memory")+ stat = _read_text_or_empty(os.path.join(v1_dir, "memory.stat"))+ candidates = [_stat_value(stat, "hierarchical_memory_limit")]+ try:+ candidates.append(int(_read_file(os.path.join(v1_dir, "memory.limit_in_bytes"))))+ except (OSError, ValueError):+ pass+ limits = [limit for limit in candidates if limit is not None and limit < _CGROUP_V1_NO_LIMIT_BYTES]+ if not limits:+ return None+ try:+ used = int(_read_file(os.path.join(v1_dir, "memory.usage_in_bytes")))+ except (OSError, ValueError):+ return 0+ return min(limits) - (used - (_stat_value(stat, "total_inactive_file") or 0))+++def meminfo_available_bytes(meminfo_path: str | os.PathLike[str]) -> int | None:+ try:+ for line in _read_file(meminfo_path).splitlines():+ if line.startswith("MemAvailable:"):+ return int(line.split()[1]) * 1024+ except (OSError, ValueError, IndexError):+ return None+ return None+++def caused_by_memory_error(exc: BaseException) -> bool:+ # pdfplumber re-raises every pdfminer failure as PdfminerException, which keeps the MemoryError only as context.+ current: BaseException | None = exc+ for _ in range(_MAX_EXCEPTION_CHAIN):+ if current is None:+ return False+ if isinstance(current, MemoryError):+ return True+ current = current.__cause__ or current.__context__+ return False+++def _read_file(path: str | os.PathLike[str]) -> str:+ with open(path) as file:+ return file.read().strip()+++def _read_text_or_empty(path: str | os.PathLike[str]) -> str:+ try:+ return _read_file(path)+ except OSError:+ return ""+++def _stat_value(stat: str, name: str) -> int | None:+ for line in stat.splitlines():+ if line.startswith(f"{name} "):+ try:+ return int(line.split()[1])+ except (ValueError, IndexError):+ return None+ return None+++def _address_space_bytes() -> int:+ with open("/proc/self/statm") as statm:+ return int(statm.read().split()[0]) * os.sysconf("SC_PAGE_SIZE")+++def _apply_limits(memory_budget: int | None, cpu_seconds: int) -> None:+ if sys.platform == "win32":+ return+ _, core_hard = resource.getrlimit(resource.RLIMIT_CORE)+ resource.setrlimit(resource.RLIMIT_CORE, (0, core_hard))+ _, cpu_hard = resource.getrlimit(resource.RLIMIT_CPU)+ if cpu_hard != resource.RLIM_INFINITY:+ cpu_seconds = min(cpu_seconds, cpu_hard)+ resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_hard))+ if memory_budget is not None:+ _, as_hard = resource.getrlimit(resource.RLIMIT_AS)+ as_limit = _address_space_bytes() + memory_budget+ if as_hard != resource.RLIM_INFINITY:+ as_limit = min(as_limit, as_hard)+ # A hard limit equal to the soft one keeps a child that runs foreign code from raising its own cap.+ resource.setrlimit(resource.RLIMIT_AS, (as_limit, as_limit))diff --git a/skyvern/forge/sdk/utils/pdf_parser.py b/skyvern/forge/sdk/utils/pdf_parser.pyindex 190bc9a47..3f513302d 100644--- a/skyvern/forge/sdk/utils/pdf_parser.py+++ b/skyvern/forge/sdk/utils/pdf_parser.py@@ -9,21 +9,49 @@ is non-empty but glyph-scrambled needs the same OCR fallback; scrambled_text_layidentifies it."""-import io+import time+from collections.abc import Callable, Collectionfrom types import FrameType+from typing import Any, NamedTuple, TypeVar, TypeVarTuple, Unpack-import pdfplumberimport structlogfrom pypdf import PdfReader, get_configurationfrom pypdf.errors import LimitReachedError-from skyvern.constants import MAX_FILE_PARSE_INPUT_TOKENS, MAX_PDF_OCR_PAGES+from skyvern.config import settings+from skyvern.constants import FILE_PARSE_STEP_TIMEOUT_SECONDS, MAX_FILE_PARSE_INPUT_TOKENS, MAX_PDF_OCR_PAGESfrom skyvern.exceptions import PDFParsingError+from skyvern.forge.sdk.utils import pdfplumber_child+from skyvern.forge.sdk.utils.capped_subprocess import CappedSubprocessError, run_in_capped_subprocessfrom skyvern.forge.sdk.utils.sanitization import sanitize_postgres_textfrom skyvern.utils.token_counter import count_tokensLOG = structlog.get_logger(__name__)+_T = TypeVar("_T")+_Ts = TypeVarTuple("_Ts")++# o200k averages about 4 characters a token in English prose, so a child that stops reading pages at 8 characters+# per allowed token still returns every page the token cap keeps; the exact cut happens in the parent.+_CHARS_PER_TOKEN_STOP = 8+++class _ResultLimit(NamedTuple):+ max_bytes: int+ memory_factor: int+++# A result is capped in pickled bytes, but the parent holds it decoded: word dicts take 5.9x for real words and up to+# 6.4x for crafted ones on Python 3.11, text with astral characters up to 6x, and page PNGs 1x because they are read+# straight into their final buffer.+_PAGE_COUNT_RESULT = _ResultLimit(64 * 1024, 6)+_PAGE_TEXTS_RESULT = _ResultLimit(32 * 1024 * 1024, 6)+_UPRIGHT_WORDS_RESULT = _ResultLimit(32 * 1024 * 1024, 7)+_PAGE_IMAGES_MEMORY_FACTOR = 1+# Fallback text is read up to this many characters; the child also stops before a page that would push the pickled+# text past _PAGE_TEXTS_RESULT, so the page that crosses a limit is cut instead of failing the whole parse.+_PAGE_TEXTS_CHAR_LIMIT = _PAGE_TEXTS_RESULT.max_bytes // 4+# A font whose ToUnicode map is wrong substitutes its glyphs out of an unrelated Unicode# block. Latin Extended-A/B and the private-use area are where those substitutions land;# a Latin-script document's own characters only appear there as in-word diacritics.@@ -193,6 +221,37 @@ def _size_limit_failure(identifier: str, pypdf_error: Exception) -> PDFParsingEr)+def _run_pdfplumber(+ func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts], result: _ResultLimit, log_identifier: str, started_at: float+) -> _T:+ # pdfminer, which pdfplumber parses with, decodes streams with no size limit, so a crafted PDF can grow memory+ # until the pod is OOM-killed. The child is capped and gets what is left of the caller's parse budget.+ return run_in_capped_subprocess(+ func,+ *args,+ memory_limit_bytes=settings.PDFPLUMBER_MAX_MEMORY_BYTES,+ max_result_bytes=result.max_bytes,+ result_memory_factor=result.memory_factor,+ timeout_seconds=max(1.0, FILE_PARSE_STEP_TIMEOUT_SECONDS - (time.monotonic() - started_at)),+ log_fields={"file_identifier": log_identifier},+ )+++def _join_within_token_limit(page_texts: list[str], max_tokens: int) -> tuple[str, int | None]:+ """Join page texts until the next one would pass max_tokens; also return that page's index, if any."""+ extracted_text = ""+ current_tokens = 0+ for i, page_text in enumerate(page_texts):+ if page_text:+ if max_tokens:+ page_tokens = count_tokens(page_text)+ if current_tokens + page_tokens > max_tokens:+ return extracted_text, i+ current_tokens += page_tokens+ extracted_text += page_text + "\n"+ return extracted_text, None++def extract_pdf_file(file_path: str,file_identifier: str | None = None,@@ -224,6 +283,7 @@ def extract_pdf_file("""identifier = file_identifier or file_pathlog_identifier = identifier.partition("?")[0]+ started_at = time.monotonic()# Try pypdf firsttry:@@ -271,41 +331,76 @@ def extract_pdf_file(# Fallback to pdfplumbertry:- with pdfplumber.open(file_path) as pdf:- extracted_text = ""- current_tokens = 0- page_count = len(pdf.pages)-- for i, page in enumerate(pdf.pages):- try:- page_text = page.extract_text()- finally:- page.close()- if page_text:- if max_tokens:- page_tokens = count_tokens(page_text)- if current_tokens + page_tokens > max_tokens:- LOG.warning(- "PDF text exceeds token limit, truncating at page boundary",- file_identifier=log_identifier,- pages_included=i,- total_pages=page_count,- max_tokens=max_tokens,- )- break- current_tokens += page_tokens- extracted_text += page_text + "\n"-- # Sanitize text to remove characters that cannot be stored in PostgreSQL- extracted_text = sanitize_postgres_text(extracted_text)-- LOG.info(- "Successfully parsed PDF with pdfplumber",+ # Only text averaging over 8 characters a token, such as long runs of one symbol, stops at this limit+ # before the token cap; the second pass then reads on to the most text a result may hold.+ first_char_limit = (+ min(max_tokens * _CHARS_PER_TOKEN_STOP, _PAGE_TEXTS_CHAR_LIMIT)+ if max_tokens+ else _PAGE_TEXTS_CHAR_LIMIT+ )+ page_texts, page_count, read_every_page = _run_pdfplumber(+ pdfplumber_child.page_texts,+ file_path,+ first_char_limit,+ _PAGE_TEXTS_RESULT.max_bytes,+ result=_PAGE_TEXTS_RESULT,+ log_identifier=log_identifier,+ started_at=started_at,+ )+ extracted_text, truncated_at_page = _join_within_token_limit(page_texts, max_tokens)+ read_on_failed = False+ if truncated_at_page is None and not read_every_page and first_char_limit < _PAGE_TEXTS_CHAR_LIMIT:+ try:+ more_texts, more_page_count, more_read_every_page = _run_pdfplumber(+ pdfplumber_child.page_texts,+ file_path,+ _PAGE_TEXTS_CHAR_LIMIT,+ _PAGE_TEXTS_RESULT.max_bytes,+ result=_PAGE_TEXTS_RESULT,+ log_identifier=log_identifier,+ started_at=started_at,+ )+ except CappedSubprocessError as read_on_error:+ # The first pass already holds usable text, so a second pass that fails does not lose it.+ read_on_failed = True+ LOG.warning(+ "Reading the rest of the PDF with pdfplumber failed, keeping the pages already read",+ file_identifier=log_identifier,+ failure=read_on_error.kind,+ error=str(read_on_error),+ pages_included=len(page_texts),+ total_pages=page_count,+ )+ else:+ page_texts, page_count, read_every_page = more_texts, more_page_count, more_read_every_page+ extracted_text, truncated_at_page = _join_within_token_limit(page_texts, max_tokens)+ if truncated_at_page is not None:+ LOG.warning(+ "PDF text exceeds token limit, truncating at page boundary",+ file_identifier=log_identifier,+ pages_included=truncated_at_page,+ total_pages=page_count,+ max_tokens=max_tokens,+ )+ elif not read_every_page and not read_on_failed:+ LOG.warning(+ "PDF text exceeds the size limit for a fallback parse, truncating at page boundary",file_identifier=log_identifier,- page_count=page_count,- text_length=len(extracted_text),+ pages_included=len(page_texts),+ total_pages=page_count,+ char_limit=_PAGE_TEXTS_CHAR_LIMIT,)- return extracted_text++ # Sanitize text to remove characters that cannot be stored in PostgreSQL+ extracted_text = sanitize_postgres_text(extracted_text)++ LOG.info(+ "Successfully parsed PDF with pdfplumber",+ file_identifier=log_identifier,+ page_count=page_count,+ text_length=len(extracted_text),+ )+ return extracted_textexcept Exception as pdfplumber_error:LOG.error(@@ -349,6 +444,7 @@ def validate_pdf_file("""identifier = file_identifier or file_pathlog_identifier = identifier.partition("?")[0]+ started_at = time.monotonic()# Try pypdf firsttry:@@ -372,8 +468,13 @@ def validate_pdf_file(# Fallback to pdfplumbertry:- with pdfplumber.open(file_path) as pdf:- _ = len(pdf.pages)+ _run_pdfplumber(+ pdfplumber_child.page_count,+ file_path,+ result=_PAGE_COUNT_RESULT,+ log_identifier=log_identifier,+ started_at=started_at,+ )LOG.info("PDF validation: pypdf failed but pdfplumber succeeded",@@ -411,23 +512,23 @@ def render_pdf_pages_as_images("""identifier = file_identifier or file_pathlog_identifier = identifier.partition("?")[0]- page_images: list[bytes] = []-- with pdfplumber.open(file_path) as pdf:- pages_to_render = len(pdf.pages) if max_pages is None else min(len(pdf.pages), max_pages)- if pages_to_render < len(pdf.pages):- LOG.warning(- "PDF has more pages than max_pages for image rendering, truncating",- file_identifier=log_identifier,- total_pages=len(pdf.pages),- max_pages=max_pages,- )-- for page in pdf.pages[:pages_to_render]:- img = page.to_image(resolution=resolution)- buf = io.BytesIO()- img.original.save(buf, format="PNG")- page_images.append(buf.getvalue())+ page_images, total_pages = _run_pdfplumber(+ pdfplumber_child.page_images,+ file_path,+ max_pages,+ resolution,+ settings.PDFPLUMBER_MAX_RESULT_BYTES,+ result=_ResultLimit(settings.PDFPLUMBER_MAX_RESULT_BYTES, _PAGE_IMAGES_MEMORY_FACTOR),+ log_identifier=log_identifier,+ started_at=time.monotonic(),+ )+ if len(page_images) < total_pages:+ LOG.warning(+ "PDF has more pages than max_pages for image rendering, truncating",+ file_identifier=log_identifier,+ total_pages=total_pages,+ max_pages=max_pages,+ )LOG.info("Rendered PDF pages as images for vision-LLM fallback",@@ -435,3 +536,15 @@ def render_pdf_pages_as_images(pages_rendered=len(page_images),)return page_images+++def extract_upright_pdf_words(file_path: str, page_indexes: Collection[int]) -> dict[int, list[dict[str, Any]]]:+ """Map each requested 0-based page index to pdfplumber's upright words on that page."""+ return _run_pdfplumber(+ pdfplumber_child.upright_words,+ file_path,+ sorted(page_indexes),+ result=_UPRIGHT_WORDS_RESULT,+ log_identifier=file_path,+ started_at=time.monotonic(),+ )diff --git a/skyvern/forge/sdk/utils/pdfplumber_child.py b/skyvern/forge/sdk/utils/pdfplumber_child.pynew file mode 100644index 000000000..875402c64--- /dev/null+++ b/skyvern/forge/sdk/utils/pdfplumber_child.py@@ -0,0 +1,86 @@+"""pdfplumber calls that pdf_parser runs in a capped child process. Imports stay to the stdlib, pdfplumber and the+child's own bootstrap, because every call pays for them again in a fresh interpreter."""++import io+from typing import Any++import pdfplumber++from skyvern.forge.sdk.utils.capped_subprocess_child import ResultTooLarge+++class PageImagesTooLarge(Exception):+ pass+++# Room kept under the result cap for the rest of the pickle: the page count, the flag and framing.+_RESULT_MARGIN_BYTES = 1024 * 1024+# What pickling a str adds to its UTF-8 bytes, rounded up.+_PAGE_OVERHEAD_BYTES = 16+++def page_texts(file_path: str, char_limit: int | None, max_bytes: int) -> tuple[list[str], int, bool]:+ """Return the page texts in order, the page count, and whether every page was read. Reading stops once char_limit+ characters are collected, or before a page that would push the pickled texts past max_bytes less a margin, and a+ first page that does not fit is a result that is too large."""+ budget = max_bytes - min(_RESULT_MARGIN_BYTES, max_bytes // 2)+ texts: list[str] = []+ chars = 0+ pickled_bytes = 0+ with pdfplumber.open(file_path) as pdf:+ page_count = len(pdf.pages)+ for page in pdf.pages:+ if char_limit is not None and chars > char_limit:+ return texts, page_count, False+ page_text = page.extract_text() or ""+ page.close()+ utf8_bytes = len(page_text) if page_text.isascii() else len(page_text.encode("utf-8", "surrogatepass"))+ if pickled_bytes + utf8_bytes + _PAGE_OVERHEAD_BYTES > budget:+ if not texts:+ raise ResultTooLarge("the text of the first page passes the limit on page texts")+ return texts, page_count, False+ texts.append(page_text)+ chars += len(page_text)+ pickled_bytes += utf8_bytes + _PAGE_OVERHEAD_BYTES+ return texts, page_count, True+++def page_count(file_path: str) -> int:+ with pdfplumber.open(file_path) as pdf:+ return len(pdf.pages)+++def page_images(+ file_path: str, max_pages: int | None, resolution: int, max_total_bytes: int+) -> tuple[list[bytes], int]:+ """Return a PNG per rendered page and the page count, failing once the PNGs pass max_total_bytes in all."""+ images: list[bytes] = []+ total_bytes = 0+ with pdfplumber.open(file_path) as pdf:+ total_pages = len(pdf.pages)+ pages_to_render = total_pages if max_pages is None else min(total_pages, max_pages)+ for page in pdf.pages[:pages_to_render]:+ img = page.to_image(resolution=resolution)+ buf = io.BytesIO()+ img.original.save(buf, format="PNG")+ page.close()+ total_bytes += buf.tell()+ if total_bytes > max_total_bytes:+ raise PageImagesTooLarge(+ f"the first {len(images) + 1} rendered pages pass the "+ f"{max_total_bytes // (1024 * 1024)} MiB limit on page images"+ )+ images.append(buf.getvalue())+ return images, total_pages+++def upright_words(file_path: str, page_indexes: list[int]) -> dict[int, list[dict[str, Any]]]:+ wanted = set(page_indexes)+ words_by_page: dict[int, list[dict[str, Any]]] = {}+ with pdfplumber.open(file_path) as pdf:+ for page_index, page in enumerate(pdf.pages):+ if page_index in wanted:+ words = page.extract_words(extra_attrs=["upright"])+ words_by_page[page_index] = [w for w in words if w.get("upright", True)]+ page.close()+ return words_by_pagediff --git a/skyvern/forge/sdk/workflow/models/pdf_fill_block.py b/skyvern/forge/sdk/workflow/models/pdf_fill_block.pyindex 2318b156f..7b9ae5827 100644--- a/skyvern/forge/sdk/workflow/models/pdf_fill_block.py+++ b/skyvern/forge/sdk/workflow/models/pdf_fill_block.py@@ -14,7 +14,6 @@ from typing import Any, ClassVar, Literal, castfrom urllib.parse import urlparseimport aiofiles-import pdfplumberimport structlogfrom pypdf import PdfReader, PdfWriterfrom pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject@@ -40,7 +39,11 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.db.exceptions import NotFoundErrorfrom skyvern.forge.sdk.experimentation.llm_prompt_config import get_llm_handler_for_prompt_typefrom skyvern.forge.sdk.schemas.files import FileInfo-from skyvern.forge.sdk.utils.pdf_parser import render_pdf_pages_as_images, validate_pdf_file+from skyvern.forge.sdk.utils.pdf_parser import (+ extract_upright_pdf_words,+ render_pdf_pages_as_images,+ validate_pdf_file,+)from skyvern.forge.sdk.utils.tesseract_languages import DEFAULT_FLAT_FILL_OCR_LANGUAGESfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.forge.sdk.workflow.loop_download_filter import filter_downloaded_files_for_current_iteration@@ -307,6 +310,11 @@ class PdfFillBlock(Block):return "checkbox"return "text"+ def _read_pdf_and_inventory(self, pdf_path: str) -> tuple[PdfReader, dict[str, PdfFieldInventory]]:+ validate_pdf_file(pdf_path, file_identifier=self.file_url)+ reader = PdfReader(pdf_path)+ return reader, self._extract_field_inventory(reader, pdf_path)+def _extract_field_inventory(self, reader: PdfReader, pdf_path: str | None = None) -> dict[str, PdfFieldInventory]:fields = reader.get_fields() or {}if not fields:@@ -354,11 +362,7 @@ class PdfFillBlock(Block):if not leaf_rects:return {}- with pdfplumber.open(pdf_path) as pdf:- words_by_page = {- pi: [w for w in pg.extract_words(extra_attrs=["upright"]) if w.get("upright", True)]- for pi, pg in enumerate(pdf.pages)- }+ words_by_page = extract_upright_pdf_words(pdf_path, {rect[0] for rect in leaf_rects.values()})labels: dict[str, str] = {}for leaf, (page_index, fx0, ftop, fx1, fbot, is_button) in leaf_rects.items():@@ -563,7 +567,8 @@ class PdfFillBlock(Block):return shutil.which("tesseract") is not Noneasync def _extract_flat_anchors(self, pdf_path: str) -> list[FlatPdfAnchor]:- page_images = render_pdf_pages_as_images(+ page_images = await asyncio.to_thread(+ render_pdf_pages_as_images,pdf_path,file_identifier=self.file_url,max_pages=FLAT_FILL_MAX_PAGES,@@ -1091,9 +1096,7 @@ class PdfFillBlock(Block):try:try:- validate_pdf_file(source_pdf_path, file_identifier=self.file_url)- reader = PdfReader(source_pdf_path)- inventory = self._extract_field_inventory(reader, source_pdf_path)+ reader, inventory = await asyncio.to_thread(self._read_pdf_and_inventory, source_pdf_path)except PDFParsingError as e:return await self._record_failure(workflow_run_context,diff --git a/skyvern/forge/sdk/workflow/models/split_pdf_block.py b/skyvern/forge/sdk/workflow/models/split_pdf_block.pyindex f539aca9d..1cab81a11 100644--- a/skyvern/forge/sdk/workflow/models/split_pdf_block.py+++ b/skyvern/forge/sdk/workflow/models/split_pdf_block.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport ioimport jsonimport os@@ -454,7 +455,7 @@ class SplitPdfBlock(Block):try:try:- validate_pdf_file(source_pdf_path, file_identifier=self.file_url)+ await asyncio.to_thread(validate_pdf_file, source_pdf_path, file_identifier=self.file_url)reader = PdfReader(source_pdf_path)total_pages = len(reader.pages)except PDFParsingError as e:diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 167b43905..bcda1a89e 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -11888,16 +11888,23 @@ class WorkflowService:self,workflow_permanent_id: str,organization_id: str | None = None,+ *,+ expected_folder_assignment: tuple[str, str | None] | None = None,) -> tuple[list[tuple[str, str | None]], str | None]:"""Soft-delete a workflow and its schedules in one transaction; the caller owes `delete_backend_schedules`."""# One transaction so we do not leave the workflow active if a process exits between separate commits.- (- deleted_schedules,- deleted_workflow_id,- ) = await app.DATABASE.workflows.soft_delete_workflow_and_schedules_by_permanent_id(- workflow_permanent_id=workflow_permanent_id,- organization_id=organization_id,- )+ delete = app.DATABASE.workflows.soft_delete_workflow_and_schedules_by_permanent_id+ if expected_folder_assignment is None:+ deleted_schedules, deleted_workflow_id = await delete(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ else:+ deleted_schedules, deleted_workflow_id = await delete(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ expected_folder_assignment=expected_folder_assignment,+ )if deleted_schedules:LOG.info("Cascade-deleted schedules during workflow deletion",@@ -17117,36 +17124,31 @@ class WorkflowService:is_saved_task=runtime_workflow.is_saved_task,)- placeholder = await self._insert_next_workflow_version(- workflow_permanent_id=runtime_workflow.workflow_permanent_id,- version=await next_version(),- insert=insert_placeholder,- next_version_after_conflict=next_version,- )- try:- self._regenerate_dispatch_draft_parameter_ids(dispatch_definition, placeholder.workflow_id)- return await self.update_workflow_definition(- workflow_id=placeholder.workflow_id,- organization_id=organization_id,- workflow_definition=dispatch_definition,- validate_code_block_templates=False,- )- except Exception:- # The placeholder row already exists as the latest version; if definition- # persistence fails, soft-delete it so it does not linger as the latest pointer.- try:- await app.DATABASE.workflows.soft_delete_workflow_by_id(- workflow_id=placeholder.workflow_id,+ # Let concurrent dispatches reach the lock after reading the same candidate; allocation is refreshed under it.+ next_workflow_version = await next_version()++ async def insert_and_persist_dispatch_version(_candidate_version: int) -> Workflow:+ async with app.DATABASE.workflows.acquire_workflow_creation_lock(runtime_workflow.workflow_permanent_id):+ # A deletion that won the lock must not be undone by this stale dispatch.+ await self.get_workflow_by_permanent_id(+ workflow_permanent_id=runtime_workflow.workflow_permanent_id,organization_id=organization_id,)- except Exception:- LOG.warning(- "Failed to clean up partial copilot dispatch version after persistence error",+ placeholder = await insert_placeholder(await next_version())+ self._regenerate_dispatch_draft_parameter_ids(dispatch_definition, placeholder.workflow_id)+ return await self.update_workflow_definition(workflow_id=placeholder.workflow_id,organization_id=organization_id,- exc_info=True,+ workflow_definition=dispatch_definition,+ validate_code_block_templates=False,)- raise++ return await self._insert_next_workflow_version(+ workflow_permanent_id=runtime_workflow.workflow_permanent_id,+ version=next_workflow_version,+ insert=insert_and_persist_dispatch_version,+ next_version_after_conflict=next_version,+ )async def make_workflow_definition(self,@@ -17486,7 +17488,7 @@ class WorkflowService:)async def persist_version_with_definition(- insert_version_row: Callable[[], Awaitable[Workflow]],+ insert_version_row: Callable[[int], Awaitable[Workflow]],) -> tuple[Workflow, WorkflowDefinition]:"""Allocate the new version row and fill in its definition as one transaction.@@ -17496,8 +17498,24 @@ class WorkflowService:and a save precondition checked against it would reject a valid draft over a versionthat validation is about to discard."""- async with app.DATABASE.workflows.version_write_transaction():- allocated_workflow = await insert_version_row()+ async with app.DATABASE.workflows.version_write_transaction(+ workflow_permanent_id=(+ existing_latest_workflow.workflow_permanent_id if existing_latest_workflow is not None else None+ )+ ):+ if existing_latest_workflow is not None:+ if getattr(existing_latest_workflow, "deleted_at", None) is None:+ # Deletion shares this lock; reject a stale save that got here after it committed.+ await self.get_workflow_by_permanent_id(+ workflow_permanent_id=existing_latest_workflow.workflow_permanent_id,+ organization_id=organization_id,+ )+ # A writer may have committed since the earlier allocation read. Refresh under+ # the lock so a stale insert cannot abort this transaction on the unique constraint.+ version = await next_version_from_same_settings()+ else:+ version = 1+ allocated_workflow = await insert_version_row(version)built_definition = await self.make_workflow_definition(allocated_workflow.workflow_id,request.workflow_definition,@@ -17627,8 +17645,8 @@ class WorkflowService:raise WorkflowVersionConflict(existing_latest_workflow.workflow_permanent_id)return latest_version + 1- async def insert_version_with_definition(version: int) -> tuple[Workflow, WorkflowDefinition]:- return await persist_version_with_definition(lambda: insert_version(version))+ async def insert_version_with_definition(_version: int) -> tuple[Workflow, WorkflowDefinition]:+ return await persist_version_with_definition(insert_version)updated_workflow, workflow_definition = await self._insert_next_workflow_version(workflow_permanent_id=existing_latest_workflow.workflow_permanent_id,@@ -17642,7 +17660,7 @@ class WorkflowService:# literal "***" placeholder from a misbehaving client.new_cdp_connect_headers = merge_masked_headers(request.cdp_connect_headers, None)updated_workflow, workflow_definition = await persist_version_with_definition(- lambda: self._create_initial_workflow_from_request(+ lambda _version: self._create_initial_workflow_from_request(organization_id=organization_id,request=request,title=title,diff --git a/skyvern/forge/taskv3/auth_tools.py b/skyvern/forge/taskv3/auth_tools.pyindex b40c00f6f..f49d03f63 100644--- a/skyvern/forge/taskv3/auth_tools.py+++ b/skyvern/forge/taskv3/auth_tools.py@@ -72,27 +72,30 @@ _PER_CALL_WAIT_SECONDS = 120.0# The poll loop fetches once per 10s sleep, so a slice shorter than that would never fetch; a tail# that small counts as spent._MIN_SLICE_SECONDS = 10.0-# How long a "not yet" answer keeps the give-up gate armed. Past it the run has moved on and a-# non-complete verdict is about something else; same idiom (and duration order) as the loop's-# FAILURE_EVIDENCE_WINDOW_TURNS recency, expressed in seconds because the budget is.+# How long a "no sign-in link yet" answer keeps the give-up hold armed. Past it the run has moved on and a+# non-complete verdict is about something else._NOT_YET_RECENCY_SECONDS = 180.0-# Termination is guaranteed by the budget shrinking under every productive deferral, but a slice may-# advance spend by as little as _MIN_SLICE_SECONDS, which would admit ~90 holds. 8 >= ceil(900/120),-# so this never binds on the healthy path.+# Termination is guaranteed by the budget shrinking under every productive deferral, but a slice may advance+# spend by as little as _MIN_SLICE_SECONDS. 8 >= ceil(900/120), so this never binds on the healthy path._MAX_GIVEUP_DEFERRALS = 8# A body-less landing must not hold the tool for a full navigation timeout._BODY_TEXT_TIMEOUT_MS = 5000-_BUDGET_EXHAUSTED = (- "verification code polling budget exhausted: no code arrived from the configured verification "- "source. Do not call get_verification_code again; finish the task as failed and say the "- "verification code never became available."+_CODE_BUDGET_SPENT = "the verification code polling time is spent; no code arrived from the configured source."++_CREDENTIAL_HAS_NO_CODE_SECRET = (+ "this credential has no usable one-time-code secret, so no code can be generated for it; "+ "get_verification_code fetches codes from this task's code source."+)++_CODE_CREDENTIAL_NOT_IN_USE = (+ "more than one saved credential in this task has a one-time-code field and none of them is in use yet; "+ "a code is generated for the credential in use.")_COMPLETION_BLOCKED = (- "the verification step never completed: no verification code was received and no sign-in link was "- "successfully opened (the source errored, refused, delivered nothing usable, or the polling budget "- "ran out). Finish with status=failed and say the verification step never completed."+ "the sign-in link step never completed: no sign-in link was opened and no verification code was "+ "received (the source errored, refused, delivered nothing usable, or the polling budget ran out).")_LINK_BUDGET_EXHAUSTED = (@@ -101,14 +104,10 @@ _LINK_BUDGET_EXHAUSTED = ("link never became available.")-_MAGIC_LINK_UNSUPPORTED = (- "the verification source returned a sign-in link, which this engine cannot follow. Do not call "- "get_verification_code again; finish the task as failed and say the site verifies by sign-in link."-)+_SIGN_IN_LINK_INSTEAD_OF_CODE = "it sent a sign-in link, which this run cannot open"_MAGIC_LINK_REDIRECT = (- "the verification source returned a sign-in link, not a code. Call open_verification_link to open "- "it; do not call get_verification_code again unless the page then asks for a code."+ "the verification source returned a sign-in link, not a code; open_verification_link opens it in this tab.")_CODE_INSTEAD_OF_LINK = (@@ -125,16 +124,6 @@ _NO_LINK_ONCE = ("open). If the page sent one, call open_verification_link again.")-_NO_CODE_AVAILABLE = (- "no verification code is available for this task (the verification source returned nothing). "- "Finish the task as failed and say the verification code never became available."-)--_NO_CODE_ONCE = (- "no verification code available for this task right now (the verification source returned nothing). "- "If the page asked for one, call get_verification_code again."-)-_LINK_OPENED = ("opened the sign-in link in this tab. Observe the page to continue: it may be signed in already, it ""may still ask for a verification code (then call get_verification_code), or it may have rejected "@@ -162,12 +151,6 @@ _GUIDANCE = ("`type` the returned value into the field. Never invent or guess a code.")-_NO_CODE_SOURCE_GUIDANCE = (- "\n- If the page asks for a one-time / 2FA / verification code, type only a code this task gives you "- "(a credential's TOTP placeholder, or a code in the task's own instructions); if there is none, finish "- "as failed and say a verification code source is missing. Never invent or guess a code."-)-_LINK_GUIDANCE = ("\n- If the page says it sent / emailed a sign-in LINK (not a code), call `open_verification_link`; ""do not ask for a code and never try to read or type the link yourself."@@ -178,6 +161,26 @@ def _tool_name(expected_otp_type: OTPType) -> str:return _LINK_TOOL if expected_otp_type == OTPType.MAGIC_LINK else _CODE_TOOL+def _budget_spent(remaining_seconds: float) -> bool:+ return remaining_seconds <= 0 or remaining_seconds < _MIN_SLICE_SECONDS+++def _time_left(remaining_seconds: float) -> str:+ if _budget_spent(remaining_seconds):+ return "no polling time remains"+ return f"about {remaining_seconds / 60.0:.1f} minutes of polling time remain"+++def _code_not_yet(remaining_seconds: float) -> str:+ if _budget_spent(remaining_seconds):+ return _CODE_BUDGET_SPENT+ return f"no verification code has arrived yet; {_time_left(remaining_seconds)}."+++def _code_source_error(detail: str, remaining_seconds: float) -> str:+ return f"the verification code source returned an error ({detail}); {_time_left(remaining_seconds)}."++def _is_token_shaped(value: str) -> bool:return (len(value) >= _MIN_REDACTED_QUERY_VALUE_CHARS@@ -292,11 +295,8 @@ async def _cookie_jar(page: Any) -> list[tuple[str, str, str, str]] | None:class VerificationFailure(StrEnum):- """Every condition that arms the completion refusal. This closes the VOCABULARY, which is what the- earlier hand-kept inventory could not do — it was missing six sites. Members are not one-per-site:- BUDGET_EXHAUSTED is written both where a slice spends the last of the budget and where a later- call finds it already spent. Closing the vocabulary is what this buys; a member-to-site bijection- is not, and nothing here depends on one."""+ """Every condition `arm` narrates. Members are not one-per-site: BUDGET_EXHAUSTED is written both+ where a slice spends the last of the budget and where a later call finds it already spent."""BUDGET_EXHAUSTED = "budget_exhausted"NO_CODE_TWICE = "no_code_twice"@@ -316,19 +316,9 @@ class VerificationFailure(StrEnum):@dataclassclass VerificationState:- """Lets the finish tool refuse a completed verdict once the source terminally failed to deliver, and- hold a non-complete one while the run is still awaiting a code it has unspent budget for.-- The latch is armed by every terminal non-delivery answer (budget exhaustion, repeated lookup- empty answers, refused or unopenable link), never by a retryable "not yet" or by a link failure- that may have received a response (the URL moved, a cookie landed, or the jar could not be read).- Only the tools count as delivery, so a code read off the page after the source failed still- blocks; a value delivered at any point wins.-- `source_failed` is derived from the recorded reason rather than settable on its own, so arming is- only reachable through `arm`, which narrates. The step engine narrates the same failure with the- same fields (`skyvern/forge/agent.py`, "TOTP polling timed out — terminating task"); without this- the v3 side latched silently and the failure could not be found in production at all."""+ """Verification facts for one task: the polling budget, deliveries, and the last status the code tool+ reported. It gives the model no orders about codes; it refuses a completion on a run whose sign-in link+ never arrived or opened, and holds a give-up while the run still waits on a sign-in link."""# Excluded from the repr: the bound `block_finish` handed to the loop would otherwise carry# the task's navigation payload into any message that formats the callback.@@ -336,41 +326,37 @@ class VerificationState:# A credential-generated code with less than this left in its TOTP step waits for the next step.totp_min_remaining_seconds: int = 0values_delivered: int = field(default=0, init=False)- # Whether `build_auth_tools` offered get_verification_code with a source that could produce a code.- code_tool_offered: bool = field(default=False, init=False)- # A credential one-time-code placeholder was refused because no code could be generated for it.- totp_source_missing: bool = field(default=False, init=False)- # The shared polling budget the tools draw down, lifted onto the state so the finish gate can- # read it. `build_auth_tools` advances `polling_spent_seconds` from its poll accounting.+ # The last code-tool answer that carried no code, or the type tool's refusal on a task with no code source. A+ # verification tool call, a delivery or a page action clears it; a model give-up reports it as its reason.+ last_status: str | None = field(default=None, init=False)+ # The block's credential scope, set by `build_auth_tools`; the type tool's refusal reads it.+ allowed_credential_parameter_keys: Sequence[str] | None = field(default=None, init=False)+ # Set when the latest verification answer asked the model to keep waiting for a sign-in link.+ link_wait_since: float | None = field(default=None, init=False)+ giveup_deferrals: int = field(default=0, init=False)+ # A finish that arrives with spend unchanged since the last hold means the model did not re-poll, so it stands.+ spend_at_last_giveup_deferral: float | None = field(default=None, init=False, repr=False)+ # The shared polling budget the tools draw down. `build_auth_tools` advances `polling_spent_seconds`+ # from its poll accounting.budget_seconds: float = field(default_factory=lambda: settings.VERIFICATION_CODE_POLLING_TIMEOUT_MINS * 60.0, init=False)polling_spent_seconds: float = field(default=0.0, init=False)- # Monotonic timestamp of the last answer that invited another call, cleared where the source- # produces a value. Written by the two retryable answers -- "not yet", and a first empty or- # errored lookup -- so "the run is awaiting a code right now" is a tool-call fact rather than a- # reading of the page. An arming does NOT clear it: `source_failed` is the conjunct that stops a- # hold once the source is judged, and it has to keep working when a later poll re-arms this latch.- awaiting_code_since: float | None = field(default=None, init=False)- # Which tool the latch belongs to. Both tools drain one source and share the budget, so a- # magic-link run must not be sent back to `get_verification_code`.- awaiting_code_tool: str = field(default=_CODE_TOOL, init=False)- giveup_deferrals: int = field(default=0, init=False)- # Spend at the previous honored deferral. A finish that arrives with spend unchanged means the- # model did not re-poll, so the next give-up stands rather than ping-ponging against the gate.- spend_at_last_giveup_deferral: float | None = field(default=None, init=False, repr=False)- _armings: list[VerificationFailure] = field(default_factory=list, init=False, repr=False)+ # Set by the link tool's retryable answers and cleared when the source produces a value, so a re-ask+ # conversion can tell a sign-in link screen that may still be waiting from one the site skipped.+ awaiting_link_since: float | None = field(default=None, init=False)+ _armings: list[tuple[VerificationFailure, str]] = field(default_factory=list, init=False, repr=False)@property- def source_failed(self) -> bool:- return bool(self._armings)+ def link_failed(self) -> bool:+ return any(tool == _LINK_TOOL for _, tool in self._armings)@propertydef remaining_budget_seconds(self) -> float:return self.budget_seconds - self.polling_spent_secondsdef arm(self, reason: VerificationFailure, tool: str) -> None:- self._armings.append(reason)+ self._armings.append((reason, tool))try:LOG.warning("task_v3 verification source failed",@@ -384,27 +370,26 @@ class VerificationState:# The count at THIS arming, not a verdict: a value delivered later unblocks the run,# and no record is written when that happens. Reads as a bound, not as an outcome.values_delivered=self.values_delivered,- # Every arming reports, so this is the true running total. The record this replaces- # was gated to one per task and could not be counted at all.arming_count=len(self._armings),# Masked to **** by `log_redaction.SENSITIVE_FIELDS` before rendering, as v1's is.# Carried for field parity with the step engine; the stripped URL is the triage handle.totp_identifier=self.task.totp_identifier,totp_verification_url=_loggable_url(self.task.totp_verification_url),# `strip_query_params` answers "" for a scheme-less or host-less string, which is- # indistinguishable from an absent URL; this pair keeps the two apart.- # Separates a source with no URL configured from one whose URL cannot be parsed —- # a malformed polling URL is a plausible root cause of the source never delivering.+ # indistinguishable from an absent URL; this keeps a malformed polling URL visible.totp_verification_url_configured=bool(self.task.totp_verification_url),)except Exception:- # The latch is already set above. Narration must never cost the tool its answer: an- # escape here would reach the model as a bare tool_error, dropping both the "finish as- # failed" guidance and the page-state payload the link paths attach.+ # Narration must never cost the tool its answer: an escape here would reach the model as a+ # bare tool_error, dropping the status and the page-state payload the link paths attach.pass+ def page_engaged(self) -> None:+ self.last_status = None+def record_delivery(self, tool: str) -> None:self.values_delivered += 1+ self.last_status = NoneLOG.info("task_v3 verification value delivered",task_id=self.task.task_id,@@ -419,9 +404,9 @@ class VerificationState:async def resolve_totp_placeholder(self, placeholder: str, authorize: TotpCodeAuthorizer | None = None) -> str:"""Turn a credential's TOTP placeholder, which resolves to a vault marker rather than a code, intothe code its secret generates now. Like the step engine, any run credential's placeholder qualifies:- the block's credential scope bounds the code tools, not typing. Refuses (and records the missing- source) when the credential holds no usable TOTP secret. A code `authorize` refuses is neither- registered nor counted as delivered."""+ the block's credential scope bounds the code tools, not typing. Refuses when the credential holds no+ usable TOTP secret, with the no-source status only when the task has no other code source. A code+ `authorize` refuses is neither registered nor counted as delivered."""code: str | None = Noneworkflow_run_id = self.task.workflow_run_idusable = False@@ -443,7 +428,6 @@ class VerificationState:except NoTOTPSecretFound:code = Noneif code is None:- self.totp_source_missing = TrueLOG.warning("task_v3 credential one-time code unavailable",task_id=self.task.task_id,@@ -451,6 +435,10 @@ class VerificationState:workflow_run_id=workflow_run_id,credential_usable=usable,)+ allowed = self.allowed_credential_parameter_keys+ if _code_source_can_produce(self.task, allowed) or _code_credential_not_in_use(self.task, allowed):+ raise ToolRefusal(_CREDENTIAL_HAS_NO_CODE_SECRET, error_class="no_one_time_code_source")+ self.last_status = NO_ONE_TIME_CODE_SOURCEraise ToolRefusal(NO_ONE_TIME_CODE_SOURCE, error_class="no_one_time_code_source")if authorize is not None and owner_key is not None:await authorize(code, owner_key)@@ -462,23 +450,26 @@ class VerificationState:self.record_delivery("type")return code- async def block_completion(self) -> str | None:- if self.source_failed and self.values_delivered == 0:+ async def block_finish(self, status: str) -> str | None:+ """Refuses a completed claim once the sign-in link source terminally failed, and a re-ask conversion+ also while a sign-in link is still awaited; a value delivered at any point lifts both. Any other+ verdict is a give-up, held while a sign-in link is still awaited."""+ if status not in ("completed", CONVERSION_VERIFICATION_STATUS):+ return self._hold_link_giveup(status)+ if self.values_delivered:+ return None+ if self.link_failed or (status == CONVERSION_VERIFICATION_STATUS and self.awaiting_link_since is not None):return _COMPLETION_BLOCKEDreturn None- async def block_giveup(self, status: str) -> str | None:- """Defer a non-complete verdict exactly while the run is actively awaiting a verification- code it has unspent budget for. The first four conditions operationalize that one invariant;- the last two bound the hold, so a model that ignores the deferral still ends within two- finishes and one that polls minimally within `_MAX_GIVEUP_DEFERRALS`."""+ def _hold_link_giveup(self, status: str) -> str | None:+ if self.link_wait_since is None:+ return Noneremaining = self.remaining_budget_secondsreason: str | None = None- if self.awaiting_code_since is None:- reason = "not_awaiting"- elif self.source_failed:+ if self._armings:reason = "source_failed"- elif time.monotonic() - self.awaiting_code_since > _NOT_YET_RECENCY_SECONDS:+ elif time.monotonic() - self.link_wait_since > _NOT_YET_RECENCY_SECONDS:reason = "stale"elif remaining < _MIN_SLICE_SECONDS:reason = "budget_spent"@@ -489,76 +480,42 @@ class VerificationState:and self.polling_spent_seconds <= self.spend_at_last_giveup_deferral):reason = "unproductive"- if reason is not None:- self._record_giveup(held=False, reason=reason, remaining=remaining, status=status)- return None- self.giveup_deferrals += 1- self.spend_at_last_giveup_deferral = self.polling_spent_seconds- self._record_giveup(held=True, reason="held", remaining=remaining, status=status)- # Both tools drain one source, so the artifact has to come off the same latch the tool does:- # telling a run that polled for a sign-in link that "the code has not arrived" contradicts the- # page and the answer the tool just gave it.- subject = "sign-in link" if self.awaiting_code_tool == _LINK_TOOL else "verification code"- return (- f"about {remaining / 60.0:.1f} minutes of {subject} polling budget remain and the "- f"{subject} has not arrived yet. Call {self.awaiting_code_tool} again to keep waiting for "- "it. If the page never sent one you may re-request it; otherwise do not act on the page "- "for this. Once the budget is spent the tool will say so; finish then and the verdict "- "will stand."- )-- async def block_finish(self, status: str) -> str | None:- """The one verification gate the finish tool consults, for every verdict: a completed claim is- refused once the source terminally failed, a non-complete one is deferred while budget the- run is still waiting on remains."""- if status == "completed":- return await self.block_completion()- if status == CONVERSION_VERIFICATION_STATUS:- return self.block_conversion()- return await self.block_giveup(status)-- def block_conversion(self) -> str | None:- """A re-ask may not turn a give-up into completed once the run asked for a verification code it never got:- the skipped screen may be the code screen still waiting."""- asked = self.awaiting_code_since is not None or self.source_failed or self.totp_source_missing- if asked and self.values_delivered == 0:- return _COMPLETION_BLOCKED- return None-- def _record_giveup(self, *, held: bool, reason: str, remaining: float, status: str) -> None:- # The pre-registered probe: today the unspent residual at a give-up is only reconstructible by- # differencing poll timestamps, so it cannot be counted directly. `finish_status` is carried- # because failed and terminated are separate populations in that read and the record is the- # only place they can be told apart.- # A run offered the code tool that never polled is kept: it is the "offered, never called" give-up.- if not held and self.polling_spent_seconds <= 0 and not self.code_tool_offered:- return+ if reason is None:+ self.giveup_deferrals += 1+ self.spend_at_last_giveup_deferral = self.polling_spent_secondstry:LOG.info("task_v3 verification give-up gate",task_id=self.task.task_id,organization_id=self.task.organization_id,workflow_run_id=self.task.workflow_run_id,- held=held,- reason=reason,+ tool=_LINK_TOOL,+ held=reason is None,+ reason=reason or "held",finish_status=status,polling_spent_seconds=round(self.polling_spent_seconds, 1),remaining_seconds=round(remaining, 1),budget_seconds=self.budget_seconds,giveup_deferrals=self.giveup_deferrals,- code_tool_offered=self.code_tool_offered,values_delivered=self.values_delivered,- source_failed=self.source_failed,)except Exception:- # Narration must never cost the gate its verdict, for the same reason `arm` swallows.+ # Narration must never cost the hold its verdict, for the same reason `arm` swallows.pass+ if reason is not None:+ return None+ return (+ f"about {remaining / 60.0:.1f} minutes of sign-in link polling budget remain and the sign-in link has "+ f"not arrived yet. Call {_LINK_TOOL} again to keep waiting for it. If the page never sent one you may "+ "re-request it; otherwise do not act on the page for this. Once the budget is spent the tool will say "+ "so; finish then and the verdict will stand."+ )def _offered_code_source_can_produce(task: Task, allowed_credential_parameter_keys: Sequence[str] | None) -> bool:- """Whether the code tool `has_otp_source` offered has a source that could yield a code: a payload- code, a polling source, or a credential TOTP backed by a parseable secret. `has_otp_source` checks- only the credential's shape, which a missing or invalid seed still passes."""+ """Whether the code source `has_otp_source` found could yield a code: a payload code, a polling+ source, or a credential TOTP backed by a parseable secret. `has_otp_source` checks only the+ credential's shape, which a missing or invalid seed still passes."""payload_otp_value = extract_totp_from_navigation_inputs(task.navigation_payload)if payload_otp_value is not None and payload_otp_value.get_otp_type() == OTPType.TOTP:return True@@ -586,37 +543,65 @@ def _offered_code_source_can_produce(task: Task, allowed_credential_parameter_ke)+def _code_source_can_produce(task: Task, allowed_credential_parameter_keys: Sequence[str] | None) -> bool:+ return has_otp_source(+ task, expected_otp_type=OTPType.TOTP, allowed_credential_parameter_keys=allowed_credential_parameter_keys+ ) and _offered_code_source_can_produce(task, allowed_credential_parameter_keys)+++def _code_credential_not_in_use(task: Task, allowed_credential_parameter_keys: Sequence[str] | None) -> bool:+ """Several credentials in scope carry a TOTP field and none is active, so `has_otp_source` picks none of them,+ yet at least one could produce a code once it is the credential in use."""+ workflow_run_id = task.workflow_run_id+ if not workflow_run_id or not app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(workflow_run_id):+ return False+ context = skyvern_context.current()+ active_key = context.active_credential_parameter_key if context else None+ if active_key is not None and (+ allowed_credential_parameter_keys is None or active_key in allowed_credential_parameter_keys+ ):+ return False+ workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(workflow_run_id)+ placeholders = [+ value["totp"]+ for key, value in workflow_run_context.values.items()+ if isinstance(value, dict)+ and isinstance(value.get("totp"), str)+ and workflow_run_context.is_registered_credential_parameter_key(key)+ and (allowed_credential_parameter_keys is None or key in allowed_credential_parameter_keys)+ ]+ return len(placeholders) > 1 and any(+ is_usable_credential_totp_placeholder(+ workflow_run_context,+ placeholder,+ active_credential_parameter_key=None,+ allowed_credential_parameter_keys=allowed_credential_parameter_keys,+ )+ for placeholder in placeholders+ )++def build_auth_tools(task: Task,page_provider: PageProvider | None = None,state: VerificationState | None = None,allowed_credential_parameter_keys: Sequence[str] | None = None,) -> tuple[list[ToolSpec], str]:- """Return (tools, system-prompt guidance) for verification handling. A task with no verification source- configured gets no tools (so they aren't offered needlessly) but still gets the never-invent guidance.- The link tool also needs a page to navigate, so a page-free run never gets it. `state`, if given, is mutated as the tools- poll and deliver values; pass its `block_finish` to `make_finish_tool` to gate every finish verdict- on it. A caller with no use for that gate can omit `state` entirely."""+ """Return (tools, system-prompt guidance) for verification handling. The code tool is always offered and+ answers with a status when no code source can produce a code; the link tool needs a link source and a+ page to navigate. `state`, if given, is mutated as the tools poll and deliver values; pass its+ `block_finish` to `make_finish_tool`. A caller with no use for that gate can omit `state` entirely."""if state is None:state = VerificationState(task=task)- offer_code_tool = has_otp_source(- task, expected_otp_type=OTPType.TOTP, allowed_credential_parameter_keys=allowed_credential_parameter_keys- )+ state.allowed_credential_parameter_keys = allowed_credential_parameter_keysoffer_link_tool = page_provider is not None and has_otp_source(task, expected_otp_type=OTPType.MAGIC_LINK, allowed_credential_parameter_keys=allowed_credential_parameter_keys)- state.code_tool_offered = offer_code_tool and _offered_code_source_can_produce(- task, allowed_credential_parameter_keys- )- if not offer_code_tool and not offer_link_tool:- return [], _NO_CODE_SOURCE_GUIDANCE# The model re-calls after every empty answer, so the cumulative polling across this task's calls- # is capped at VERIFICATION_CODE_POLLING_TIMEOUT_MINS (the step engine's single poll window) and- # then the tools refuse with stop guidance. One budget for both tools: they drain one source; it- # lives on `state` so the finish gate can see what is left of it. Re-derived here rather than- # taken from the state's default because a caller may have built the state before the setting was- # read, and the budget must be the one in force where it is actually drawn down.+ # is capped at VERIFICATION_CODE_POLLING_TIMEOUT_MINS (the step engine's single poll window). One+ # budget for both tools: they drain one source. Re-derived here rather than taken from the state's+ # default because a caller may have built the state before the setting was read.# Scope is this task, so each block of a workflow run draws its own budget. Deliberate, not# emergent: v1's poll sites start a fresh full window on every invocation (`poll_otp_value`# callers pass no `max_wait_seconds`), so a per-run cap here would be stricter than v1.@@ -631,72 +616,72 @@ def build_auth_tools(# verdict on it. Shared by both tools, like the budget, because they drain one source.empty_answer_streak = 0+ def _code_answer(text: str, *, arm: VerificationFailure | None = None) -> ToolResult:+ """A code-tool status that carries no code. Stays a ToolResult.error: the loop sends the model+ `content` only, and the error status routes a call that blocked for up to 120s through the+ batch-poisoning check, so a stale queued click cannot dispatch against a page that moved."""+ if arm is not None:+ state.arm(arm, _CODE_TOOL)+ state.last_status = text+ return ToolResult.error(text)+def _budget_exhausted(expected_otp_type: OTPType) -> ToolResult:- state.arm(VerificationFailure.BUDGET_EXHAUSTED, _tool_name(expected_otp_type))- if expected_otp_type == OTPType.MAGIC_LINK:- return ToolResult.error(_LINK_BUDGET_EXHAUSTED)- return ToolResult.error(_BUDGET_EXHAUSTED)+ if expected_otp_type == OTPType.TOTP:+ return _code_answer(_CODE_BUDGET_SPENT, arm=VerificationFailure.BUDGET_EXHAUSTED)+ state.arm(VerificationFailure.BUDGET_EXHAUSTED, _LINK_TOOL)+ return ToolResult.error(_LINK_BUDGET_EXHAUSTED)def _failed(message: str, *, reason: VerificationFailure, tool: str, data: dict[str, Any] | None = None) -> ToolResult:- """A terminal non-delivery answer: the finish tool must refuse a completed verdict from here on."""+ """A terminal link-tool answer: the finish tool refuses a completed verdict from here on."""state.arm(reason, tool)return ToolResult.error(message, data=data)- def _not_yet(expected_otp_type: OTPType, detail: str, elapsed_seconds: float) -> ToolResult:- """A healthy source that has not delivered yet: the run is still awaiting a code, and the- message says how much budget is left to wait with — the old one gave no indication any- remained. Stays a ToolResult.error: the status is never serialized to the model (the loop- sends `content` only), and it is what routes a call that blocked for up to 120s through the- batch-poisoning check, so flipping it would let a stale queued click dispatch against a page- that moved during the wait. `elapsed_seconds` is this slice's wait, which the caller's- `finally` has not yet added to the running spend."""- state.awaiting_code_since = time.monotonic()- state.awaiting_code_tool = _tool_name(expected_otp_type)+ def _not_yet(expected_otp_type: OTPType, detail: str, elapsed_seconds: float, *, errored: bool) -> ToolResult:+ """A slice that timed out with nothing to hand over. `elapsed_seconds` is this slice's wait, which+ the caller's `finally` has not yet added to the running spend."""spent = state.polling_spent_seconds + elapsed_secondsremaining = max(0.0, state.budget_seconds - spent)+ tool = _tool_name(expected_otp_type)LOG.warning("task_v3 verification poll slice timed out",task_id=task.task_id,organization_id=task.organization_id,workflow_run_id=task.workflow_run_id,- tool=_tool_name(expected_otp_type),+ tool=tool,polling_spent_seconds=round(spent, 1),remaining_seconds=round(remaining, 1),budget_seconds=state.budget_seconds,)- tool = _tool_name(expected_otp_type)- subject = "sign-in link" if expected_otp_type == OTPType.MAGIC_LINK else "verification code"- if remaining < _MIN_SLICE_SECONDS:- # Nothing left to buy: the next call refuses without polling, so inviting one would spend- # a tool call and a turn to be told that -- and near the loop's own limits that trades a- # truthful verification failure for a generic budget-exhausted exit. Terminal, so it arms:- # the budget is exhausted here whether or not the model makes that pointless call, and- # leaving the latch to be set by the call itself is what let a model that obeys the- # instruction go on to claim the verification step completed.+ spent_out = _budget_spent(remaining)+ if expected_otp_type == OTPType.TOTP:+ text = _code_source_error(detail, remaining) if errored else _code_not_yet(remaining)+ return _code_answer(text, arm=VerificationFailure.BUDGET_EXHAUSTED if spent_out else None)+ state.awaiting_link_since = state.link_wait_since = time.monotonic()+ if spent_out:return _failed(- f"no {subject} available yet ({detail}), and the polling budget is now spent. Do not "- f"call {tool} again; finish the task as failed and say the {subject} never arrived.",+ f"no sign-in link available yet ({detail}), and the polling budget is now spent. Do not "+ f"call {tool} again; finish the task as failed and say the sign-in link never arrived.",reason=VerificationFailure.BUDGET_EXHAUSTED,tool=tool,)return ToolResult.error(- f"no {subject} available yet ({detail}); about {remaining / 60.0:.1f} minutes of polling "+ f"no sign-in link available yet ({detail}); about {remaining / 60.0:.1f} minutes of polling "f"budget remain. If the page has not sent one, trigger it first, then call {tool} again.")- def _empty_answer(once: str, terminal: str, *, reason: VerificationFailure, tool: str) -> ToolResult:+ def _code_empty(text: str, *, reason: VerificationFailure) -> ToolResult:+ nonlocal empty_answer_streak+ empty_answer_streak += 1+ return _code_answer(text, arm=reason if empty_answer_streak > 1 else None)++ def _empty_answer(once: str, terminal: str, *, reason: VerificationFailure) -> ToolResult:nonlocal empty_answer_streakempty_answer_streak += 1if empty_answer_streak > 1:- return _failed(terminal, reason=reason, tool=tool)- # Retryable, so it arms the give-up gate for the same reason `_not_yet` does: this answer- # invites another call, and a run that gives up right after it has exactly as much unspent- # budget as one that gave up after a "not yet". Arming only the "not yet" path would leave the- # gate holding on one of the four answers that ask the model to wait.- state.awaiting_code_since = time.monotonic()- state.awaiting_code_tool = tool+ return _failed(terminal, reason=reason, tool=_LINK_TOOL)+ state.awaiting_link_since = state.link_wait_since = time.monotonic()return ToolResult.error(once)async def _poll(expected_otp_type: OTPType) -> ToolResult | OTPValue:@@ -707,14 +692,20 @@ def build_auth_tools(return _budget_exhausted(expected_otp_type)if first_poll_started_at is None:first_poll_started_at = datetime.utcnow()+ is_code = expected_otp_type == OTPType.TOTP# A code poll may hand back a sign-in link stored for this run since this task began, but only when- # the link tool can open it; without a page the link would end the run as unsupported.+ # the link tool can open it.surface_magic_link = (MagicLinkSurfacing(created_after=task.created_at, spent_values=frozenset(spent_links))- if expected_otp_type == OTPType.TOTP and offer_link_tool+ if is_code and offer_link_toolelse None)started = time.monotonic()++ def _charged() -> float:+ # An instant answer still costs a slice, so repeated calls reach the spent status in a bounded number.+ return max(time.monotonic() - started, _MIN_SLICE_SECONDS)+try:otp_value = await resolve_otp_value(task,@@ -726,28 +717,21 @@ def build_auth_tools(surface_magic_link=surface_magic_link,)if otp_value is None:- if expected_otp_type == OTPType.MAGIC_LINK:- return _empty_answer(- _NO_LINK_ONCE,- _NO_LINK_AVAILABLE,- reason=VerificationFailure.NO_LINK_TWICE,- tool=_tool_name(expected_otp_type),+ if is_code:+ return _code_empty(+ _code_not_yet(state.remaining_budget_seconds - _charged()),+ reason=VerificationFailure.NO_CODE_TWICE,)- return _empty_answer(- _NO_CODE_ONCE,- _NO_CODE_AVAILABLE,- reason=VerificationFailure.NO_CODE_TWICE,- tool=_tool_name(expected_otp_type),- )+ return _empty_answer(_NO_LINK_ONCE, _NO_LINK_AVAILABLE, reason=VerificationFailure.NO_LINK_TWICE)empty_answer_streak = 0# Cleared here, not at delivery: several paths reach a value that is never handed to the# model -- a link when a code was asked for, a code when a link was, a link the browser- # could not open -- and on all of them the run has stopped waiting on the SOURCE. Holding- # a give-up there would contradict the very answer those paths return.- state.awaiting_code_since = None+ # could not open -- and on all of them the run has stopped waiting on the SOURCE.+ state.awaiting_link_since = Nonereturn otp_valueexcept (NoTOTPVerificationCodeFound, FailedToGetTOTPVerificationCode) as exc:- if state.polling_spent_seconds + (time.monotonic() - started) >= state.budget_seconds:+ elapsed = _charged()+ if not is_code and state.polling_spent_seconds + elapsed >= state.budget_seconds:return _budget_exhausted(expected_otp_type)detail = type(exc).__name__if isinstance(exc, FailedToGetTOTPVerificationCode):@@ -755,18 +739,21 @@ def build_auth_tools(# source, not a "not yet" from a healthy one.if exc.reason:detail = f"{detail}: {exc.reason}"+ if is_code:+ return _code_empty(+ _code_source_error(detail, state.remaining_budget_seconds - elapsed),+ reason=VerificationFailure.SOURCE_ERRORED_TWICE,+ )return _empty_answer(- f"the verification source errored ({detail}). Call {_tool_name(expected_otp_type)} again; "- "do not re-trigger the page.",+ f"the verification source errored ({detail}). Call {_LINK_TOOL} again; do not re-trigger the page.",f"the verification source kept failing ({detail}). Finish the task as failed and say the ""verification step never completed.",reason=VerificationFailure.SOURCE_ERRORED_TWICE,- tool=_tool_name(expected_otp_type),)empty_answer_streak = 0if exc.webhook_diagnostics:detail = f"{detail}: {exc.webhook_diagnostics}"- return _not_yet(expected_otp_type, detail, time.monotonic() - started)+ return _not_yet(expected_otp_type, detail, elapsed, errored=bool(exc.webhook_diagnostics))except Exception as exc:LOG.warning("task_v3 verification tool lookup failed",@@ -775,30 +762,38 @@ def build_auth_tools(exc_info=True,)message = f"verification lookup failed: {type(exc).__name__}"- retry_hint = (- "If the page is waiting on a sign-in link, call open_verification_link again."- if expected_otp_type == OTPType.MAGIC_LINK- else "If the page asked for a code, call get_verification_code again."- )+ if is_code:+ return _code_empty(+ _code_source_error(message, state.remaining_budget_seconds - _charged()),+ reason=VerificationFailure.LOOKUP_FAILED_TWICE,+ )return _empty_answer(- f"{message}. {retry_hint}",+ f"{message}. If the page is waiting on a sign-in link, call open_verification_link again.",f"{message} repeatedly. Finish the task as failed and say the verification step never completed.",reason=VerificationFailure.LOOKUP_FAILED_TWICE,- tool=_tool_name(expected_otp_type),)finally:- state.polling_spent_seconds += time.monotonic() - started+ state.polling_spent_seconds += _charged()++ def _new_verification_call() -> None:+ state.last_status = None+ state.link_wait_since = Noneasync def _get_verification_code(args: dict[str, Any]) -> ToolResult:nonlocal cached_otp_value+ _new_verification_call()+ # Per call, not at build time: the active credential can change between calls.+ if not _code_source_can_produce(task, allowed_credential_parameter_keys):+ if _code_credential_not_in_use(task, allowed_credential_parameter_keys):+ return _code_answer(_CODE_CREDENTIAL_NOT_IN_USE)+ return _code_answer(NO_ONE_TIME_CODE_SOURCE)cached = cached_otp_valueif cached is not None:if cached.get_otp_type() == OTPType.MAGIC_LINK:if not offer_link_tool:- return _failed(- _MAGIC_LINK_UNSUPPORTED,- reason=VerificationFailure.MAGIC_LINK_UNSUPPORTED_CACHED,- tool="get_verification_code",+ return _code_answer(+ _code_source_error(_SIGN_IN_LINK_INSTEAD_OF_CODE, state.remaining_budget_seconds),+ arm=VerificationFailure.MAGIC_LINK_UNSUPPORTED_CACHED,)# Asked for a code again instead of opening the link: the page may want a code after all, so# poll for one rather than repeat the redirect, which would starve a code that arrives later.@@ -830,12 +825,14 @@ def build_auth_tools(tool="get_verification_code",otp_type=OTPType.MAGIC_LINK.value,)- return _failed(- _MAGIC_LINK_UNSUPPORTED, reason=VerificationFailure.MAGIC_LINK_UNSUPPORTED, tool="get_verification_code"+ return _code_answer(+ _code_source_error(_SIGN_IN_LINK_INSTEAD_OF_CODE, state.remaining_budget_seconds),+ arm=VerificationFailure.MAGIC_LINK_UNSUPPORTED,)if otp_value.get_otp_type() != OTPType.TOTP:- return _failed(- _NO_CODE_AVAILABLE, reason=VerificationFailure.VALUE_NOT_A_CODE, tool="get_verification_code"+ return _code_answer(+ _code_source_error("it returned a value that is not a code", state.remaining_budget_seconds),+ arm=VerificationFailure.VALUE_NOT_A_CODE,)return _deliver_code(otp_value.value)@@ -849,6 +846,7 @@ def build_auth_tools(async def _open_verification_link(args: dict[str, Any]) -> ToolResult:nonlocal cached_otp_value, first_poll_started_at+ _new_verification_call()otp_value: OTPValue | None = cached_otp_valueif otp_value is None:polled = await _poll(OTPType.MAGIC_LINK)@@ -992,23 +990,22 @@ def build_auth_tools(state.record_delivery("open_verification_link")return ToolResult.ok(_LINK_OPENED, data={"page_state_changed": True})- tools: list[ToolSpec] = []- if offer_code_tool:- tools.append(- ToolSpec(- name="get_verification_code",- description=(- "Fetch the one-time / 2FA verification code for this task (from the connected email inbox, "- "the configured verification webhook, or the saved credential's authenticator). Call this "- "after the page has sent or asked for a verification / OTP / 2FA code, then type the returned "- "value. The call waits up to a couple of minutes for the code to arrive and the total wait per "- "task is limited, so do not call it before the code has been requested. Never invent a code."- ),- parameters={"type": "object", "properties": {}},- handler=_get_verification_code,- billable=False,- )+ tools: list[ToolSpec] = [+ ToolSpec(+ name="get_verification_code",+ description=(+ "Fetch the one-time / 2FA verification code for this task (from the connected email inbox, "+ "the configured verification webhook, or the saved credential's authenticator). A call waits up "+ "to a couple of minutes for the code and the total wait per task is limited. It returns the "+ "code, or says that no code has arrived yet (with the polling time left), that no code source "+ "is configured, that the polling time is spent, or that the code source returned an error. "+ "Never invent or guess a code."+ ),+ parameters={"type": "object", "properties": {}},+ handler=_get_verification_code,+ billable=False,)+ ]if offer_link_tool:tools.append(ToolSpec(@@ -1030,7 +1027,4 @@ def build_auth_tools(engages_page=True,))- guidance = (_GUIDANCE if offer_code_tool else _NO_CODE_SOURCE_GUIDANCE) + (- _LINK_GUIDANCE if offer_link_tool else ""- )- return tools, guidance+ return tools, _GUIDANCE + (_LINK_GUIDANCE if offer_link_tool else "")diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex abe91726f..d90a8dc71 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -266,6 +266,7 @@ async def run_task_v3_agent_loop(should_cancel: Callable[[], Awaitable[bool]] | None = None,on_action_round: ActionRoundSink | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,+ on_page_action: Callable[[], None] | None = None,extra_tools: list[ToolSpec] | None = None,extra_system_guidance: str = "",max_tokens: int | None = DEFAULT_MAX_TOKENS,@@ -298,6 +299,7 @@ async def run_task_v3_agent_loop(download_attempts: Callable[[], int | None] | None = None,block_type: str | None = None,has_navigation_goal: bool = False,+ error_code_mapping: dict[str, str] | None = None,extraction_requested: bool = False,# Customer instructions that can redefine what "done" means, shown to the goal judge with the goal.goal_instructions: str = "",@@ -614,6 +616,7 @@ async def run_task_v3_agent_loop(document_identity=None if page_free else document_identity,completion_gate=None if page_free else completion_gate,download_facts=failure_watch.facts if failure_watch is not None else None,+ error_code_mapping=error_code_mapping,)tools = browser_tools + (extra_tools or []) + [finish_tool]# The COMPLETE dispatch list, not just the browser tools: auth / captcha / code tools and finish@@ -686,6 +689,7 @@ async def run_task_v3_agent_loop(should_cancel=should_cancel,on_action_round=on_action_round,on_pre_action=on_pre_action,+ on_page_action=on_page_action,max_tokens=max_tokens,prefix_ref_tokens=PREFIX_REF_TOKENS,max_raw_tokens=MAX_RAW_TOKENS,diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.pyindex 376f485d5..9a8593098 100644--- a/skyvern/forge/taskv3/loop.py+++ b/skyvern/forge/taskv3/loop.py@@ -29,6 +29,7 @@ from urllib.parse import urlsplitimport structlog+from skyvern.errors.errors import resolve_error_code_mapping_keyfrom skyvern.exceptions import CompletionGateTerminationError, SkyvernContextWindowExceededError, StepTerminationErrorfrom skyvern.forge.sdk.api.llm.exceptions import LLMContentFilteredErrorfrom skyvern.forge.sdk.core import skyvern_context@@ -43,6 +44,7 @@ from skyvern.forge.taskv3.goal_check import ()from skyvern.forge.taskv3.handoff_redaction import MAX_HANDOFF_URL_CHARS, normalized_url, sanitize_published_urlfrom skyvern.forge.taskv3.target_label import describe_target+from skyvern.schemas.workflows import ERROR_CODE_MAPPING_MAX_ENTRIES, ERROR_CODE_MAPPING_MAX_UTF8_BYTESfrom skyvern.webeye.navigation import clear_task_nav_error_code, redact_url_secretsLOG = structlog.get_logger()@@ -596,7 +598,7 @@ class ActionRoundSink(Protocol):DownloadWait = Callable[[], Awaitable[None]]DownloadSettle = Callable[[frozenset[str]], Awaitable[str | None]]# Consulted from finish for EVERY verdict, unlike DownloadSettle: it takes the finish status and-# gates on state the caller already tracks (e.g. a verification-code budget), not on staged+# gates on state the caller already tracks (e.g. a sign-in link polling budget), not on staged# downloads. One callback, because a completed claim made on a blank verification step and a# non-complete verdict given up with polling budget still unspent are the same concern seen from two# sides; splitting them into two hooks would scatter it.@@ -749,6 +751,12 @@ class LoopOutcome:unlisted_reask: dict[str, Any] | None = None# The finish tool's completion gate approved this verdict, so the caller must not consult it again.gate_passed: bool = False+ # The model's own user-defined error code on a failed/terminated finish, re-validated against the mapping.+ error_code: str | None = None+ # The model explicitly answered that none of the user's codes describes the failure.+ error_code_declined: bool = False+ # The status the model finished with, when the completion gate replaced it inside the loop.+ model_status: str | None = Nonedef _get(obj: Any, key: str, default: Any = None) -> Any:@@ -2269,6 +2277,7 @@ OBSERVE_SUMMARY_FIELDS = frozenset("elements_truncated","icons_listed","icons_truncated",+ "unnamed_not_icon","elements_truncated_in_components","elements_dropped","elements_truncated_by_page_cap",@@ -2553,6 +2562,67 @@ def _non_completed(status: object) -> NonCompletedStatus | None:return None+NO_MATCHING_ERROR_CODE = "NONE_OF_THESE"+# Each customer description is cut here; the enum always carries every code.+_ERROR_CODE_DESCRIPTION_MAX_CHARS = 1000+++def _offerable_code(code: str) -> bool:+ # A key spelled like the sentinel would turn every "none of these" into that code.+ return bool(code.strip()) and code.strip().upper() != NO_MATCHING_ERROR_CODE+++def _offered_error_codes(error_code_mapping: dict[str, str] | None) -> dict[str, str] | None:+ """The codes `finish` offers, or None to leave the whole mapping to the post-run detector.++ A mapping past the workflow caps would ride on every turn, and one with no offerable code could only decline."""+ if not error_code_mapping or len(error_code_mapping) > ERROR_CODE_MAPPING_MAX_ENTRIES:+ return None+ size = sum(len(code.encode()) + len(str(description).encode()) for code, description in error_code_mapping.items())+ if size > ERROR_CODE_MAPPING_MAX_UTF8_BYTES:+ return None+ return {code: description for code, description in error_code_mapping.items() if _offerable_code(code)} or None+++def _error_code_schema(error_code_mapping: dict[str, str]) -> dict[str, Any]:+ codes = "\n".join(+ f"- {code}: {str(description)[:_ERROR_CODE_DESCRIPTION_MAX_CHARS]}"+ for code, description in sorted(error_code_mapping.items())+ )+ return {+ "type": "string",+ "enum": [*sorted(error_code_mapping), NO_MATCHING_ERROR_CODE],+ "description": (+ "Required when status is failed or terminated; ignored when completed. The user's code whose "+ f"description is what actually happened, or {NO_MATCHING_ERROR_CODE} when none of them describes it."+ f"\nThe user's codes:\n{codes}"+ ),+ }+++def _finish_error_code(status: Any, raw: Any, error_code_mapping: dict[str, str] | None) -> tuple[str | None, bool]:+ """The mapping key the model chose and whether it explicitly chose none; both empty unless the run did not succeed.++ A code on a completed run would make a successful run carry errors, which consumers read as a failure."""+ if not error_code_mapping or status not in ("failed", "terminated"):+ return None, False+ answer = raw.strip() if isinstance(raw, str) else raw+ declined = isinstance(answer, str) and answer.upper() == NO_MATCHING_ERROR_CODE+ code = None+ if not declined:+ code = resolve_error_code_mapping_key(raw, error_code_mapping)+ code = code or resolve_error_code_mapping_key(answer, error_code_mapping)+ LOG.info(+ "taskv3 finish user-defined error code",+ status=status,+ chosen_error_code=code,+ declined=declined,+ # Never the rejected value itself: a non-strict answer can carry page text or a secret.+ rejected_error_code=code is None and not declined and raw is not None,+ )+ return code, declined++def make_finish_tool(page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,max_settle_deferrals: int = DEFAULT_MAX_SETTLE_DEFERRALS,@@ -2573,6 +2643,7 @@ def make_finish_tool(unseen_text: UnseenPageText | None = None,terminate_premise: TerminatePremiseCheck | None = None,download_facts: DownloadFailureFacts | None = None,+ error_code_mapping: dict[str, str] | None = None,) -> ToolSpec:"""`page_fingerprint` samples an opaque fingerprint of the page's rendered content (None when nopage is available). A finish(completed) is deferred (bounded by `max_settle_deferrals`, then@@ -2589,8 +2660,8 @@ def make_finish_tool(because async submissions and captcha protocols otherwise produce false-negative verdicts.`verification_blocker` is the one gate consulted for EVERY verdict: it refuses a completed claim- once the verification source terminally failed, and holds a failed OR terminated one while the- run is still awaiting a code it has unspent polling budget for -- a give-up at one 120s slice of+ once the sign-in link source terminally failed, and holds a failed OR terminated one while the+ run is still awaiting a sign-in link it has unspent polling budget for -- a give-up at one 120s slice ofa 15-minute budget throws away minutes of waiting the run already owns. The hold is bounded bythe callee (the budget shrinks under every productive hold) and refused here without the deadlineheadroom to fund the blocking poll slice it asks for. Apart from that gate, terminated is@@ -2619,6 +2690,7 @@ def make_finish_tool(carried, or a result in the finish's own batch carried page text or download lines.`terminate_premise` checks every terminated finish past the holds above, alongside any re-ask, and changes nothing."""+ error_code_mapping = _offered_error_codes(error_code_mapping)deferrals = 0stale_holds = 0failure_deferrals = 0@@ -2773,6 +2845,8 @@ def make_finish_tool()if result is None or not result.converted:return None+ # The original verdict's code: a post-loop veto of this conversion restores that verdict.+ error_code, error_code_declined = _finish_error_code(original, args.get("error_code"), error_code_mapping)return ToolResult.ok(content="Task attempt ended. No further actions are permitted.",data={@@ -2781,6 +2855,8 @@ def make_finish_tool("extracted_output": args.get("extracted_output"),"converted_from": original,"converted_from_reason": reason,+ "error_code": error_code,+ "error_code_declined": error_code_declined,},)@@ -2850,7 +2926,7 @@ def make_finish_tool(# Fail closed: an exception here must not let a blank verification step read as done.LOG.warning("taskv3 verification_blocker failed; failing closed", exc_info=True)return ToolResult.error(- "Could not verify that the verification-code step completed cleanly; retry "+ "Could not verify that the sign-in link step completed cleanly; retry ""finish(status=completed) once verified, or finish with the non-completed ""status the finish tool's own rule gives this outcome.")@@ -2932,6 +3008,7 @@ def make_finish_tool("status": "terminated","reason": termination.reason,"extracted_output": args.get("extracted_output"),+ "model_status": status,},)except StepTerminationError as exhausted:@@ -2941,6 +3018,7 @@ def make_finish_tool("status": "failed","reason": exhausted.message or "","extracted_output": args.get("extracted_output"),+ "model_status": status,},)except Exception:@@ -3059,6 +3137,7 @@ def make_finish_tool(no_file_line = [DOWNLOAD_NO_FILE_FACT]# Drained only here: a held finish leaves the failures for the next tool result to show.download_lines = no_file_line + (download_facts.deliver() if download_facts is not None else [])+ error_code, error_code_declined = _finish_error_code(status, args.get("error_code"), error_code_mapping)return ToolResult.ok(content="\n".join(["Task attempt ended. No further actions are permitted.", *download_lines]),data={@@ -3066,6 +3145,8 @@ def make_finish_tool("reason": args.get("reason") or "","extracted_output": args.get("extracted_output"),"gate_passed": gate_passed,+ "error_code": error_code,+ "error_code_declined": error_code_declined,},)@@ -3078,6 +3159,7 @@ def make_finish_tool("status": {"type": "string", "enum": ["completed", "failed", "terminated"]},"reason": {"type": "string", "maxLength": 2000},"extracted_output": {"description": "Structured output requested by the goal, if any."},+ **({"error_code": _error_code_schema(error_code_mapping)} if error_code_mapping else {}),},"required": ["status", "reason"],},@@ -3469,6 +3551,8 @@ async def run_agent_tool_loop(should_cancel: Callable[[], Awaitable[bool]] | None = None,on_action_round: ActionRoundSink | None = None,on_pre_action: Callable[[str, dict[str, Any]], Awaitable[None]] | None = None,+ # Called before each page-touching tool call is dispatched.+ on_page_action: Callable[[], None] | None = None,max_tokens: int | None = None,# The fixed input re-sent on every call is charged against max_tokens only up to this size, so a large task# payload does not shrink the turn horizon. None charges every call in full.@@ -4790,6 +4874,8 @@ async def run_agent_tool_loop(# task ends on; reads and finish keep it, since a run that ends there ended on that navigation.if spec is not None and spec.touches_page and dispatch_ctx is not None and dispatch_ctx.task_id:clear_task_nav_error_code(dispatch_ctx.task_id)+ if spec is not None and spec.touches_page and on_page_action is not None:+ on_page_action()tool_started_at = time.monotonic()st.event_seq += 1dispatch_seq = st.event_seq@@ -5329,6 +5415,9 @@ async def run_agent_tool_loop(converted_from=_non_completed(data.get("converted_from")),converted_from_reason=data.get("converted_from_reason", ""),gate_passed=bool(data.get("gate_passed")),+ error_code=data.get("error_code"),+ error_code_declined=bool(data.get("error_code_declined")),+ model_status=data.get("model_status"),# The model's own verdict wins whether or not it landed on the granted final turn;# cap_trip just records the fact that a cap forced this to be the last turn.cap_trip=st.cap_trip_pending if st.final_turn_granted else None,diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex f97d9d325..4cfeff860 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -1436,6 +1436,24 @@ OBSERVE_POINTER_ROOT_CAP = 40# do not count toward it._POINTER_ROOT_SCAN_CEILING = 400+# A color paints nothing only when its ALPHA is zero. Parse the alpha channel, never a trailing ",0)",+# which also matches an opaque color whose last channel is 0 (`rgb(0,0,0)`, `rgb(255,0,0)`). A form that+# cannot be parsed is treated as paint, so the failure mode is under-suppression, not over.+_OPAQUE_PAINT_JS = r"""(color) => {+ const c = (color || '').replace(/\s+/g, '').toLowerCase();+ if (!c || c === 'transparent') return false;+ const hex = c.match(/^#([\da-f]+)$/);+ if (hex && (hex[1].length === 4 || hex[1].length === 8)) {+ return parseInt(hex[1].slice(-1 * (hex[1].length === 4 ? 1 : 2)), 16) !== 0;+ }+ const m = c.match(/^(?:rgba?|hsla?)\((.*)\)$/);+ if (!m) return true;+ const parts = m[1].split(',');+ const alpha = m[1].includes('/') ? parseFloat(m[1].slice(m[1].lastIndexOf('/') + 1))+ : parts.length >= 4 ? parseFloat(parts[parts.length - 1]) : 1;+ return !(alpha === 0);+}"""+# v1's off-canvas test (isElementVisible, domUtils.js): a box whose horizontal centre sits left of the# page is off screen, unless a horizontally scrolled overflow ancestor explains it._OFF_CANVAS_JS = r"""(el, r) => {@@ -1461,6 +1479,117 @@ _OFF_CANVAS_JS = r"""(el, r) => {# not a root when the reading already covers it: it is or is inside a control `listable` keeps, or its# pointer parent is itself a root or covered. One that holds such a control is a holder: at most one# named, control-free pointer descendant is listed for it, recorded in `state.held`.+_SCROLL_GEOMETRY_JS = r"""+ const flowNegative = (cs) => {+ const wm = cs.writingMode || 'horizontal-tb';+ const rtl = cs.direction === 'rtl';+ const vertical = wm.indexOf('horizontal') !== 0;+ // `sideways-lr` is the one vertical mode whose inline axis runs bottom-to-top.+ const inlineSign = vertical ? ((wm === 'sideways-lr') !== rtl ? -1 : 1) : (rtl ? -1 : 1);+ const blockSign = vertical ? (/-rl$/.test(wm) ? -1 : 1) : 1;+ const inlineIsX = !vertical;+ let xSign = inlineIsX ? inlineSign : blockSign;+ let ySign = inlineIsX ? blockSign : inlineSign;+ const display = cs.display || '';+ if (display === 'flex' || display === 'inline-flex') {+ // A flex container lays content out along main/cross, not inline/block: `*-reverse` flips the+ // main axis and `wrap-reverse` flips the cross axis.+ const fd = cs.flexDirection || 'row';+ const mainIsInline = fd.indexOf('row') === 0;+ const mainSign = (mainIsInline ? inlineSign : blockSign) * (/-reverse$/.test(fd) ? -1 : 1);+ const crossSign =+ (mainIsInline ? blockSign : inlineSign) * (cs.flexWrap === 'wrap-reverse' ? -1 : 1);+ const mainIsX = mainIsInline === inlineIsX;+ xSign = mainIsX ? mainSign : crossSign;+ ySign = mainIsX ? crossSign : mainSign;+ }+ return { x: xSign < 0, y: ySign < 0 };+ };+ // PER AXIS, the scale the ancestry applies to this container -- or `null` where the box ratio+ // cannot express it. Rects are transformed viewport pixels; scroll offsets and computed lengths+ // stay untransformed CSS units, and the conversion between them is only sound where the mapping+ // is a positive, axis-aligned scale that actually changes scale. Each of the four answers this+ // rules out is a way the ratio does harm rather than good:+ // scale 1 -- the two spaces COINCIDE, so the ratio carries only `offsetHeight`'s integer+ // rounding: an untransformed 30.5px scroller reports 31, and that 1.6% names+ // a collapsed panel for a control Playwright clicks. Composed, not remembered+ // as a flag, because an outer `scale(2)` under an inner `scale(.5)` cancels.+ // per axis -- a `scaleX(2)` ancestor leaves the VERTICAL spaces coinciding, so a shared+ // answer would feed that same rounding into `scaleY`.+ // not axis-aligned -- under a rotation, a skew or a perspective the rect is an axis-aligned+ // BOUND of the box, not a scaled copy: a 2deg tilt on a 600px strip reads+ // 1.52 at scale 1, which shrinks the distance asked for below a scroll-back+ // that cannot reach the control.+ // reflected -- `rect.width / offsetWidth` is unsigned, so a mirrored mapping would convert+ // by the magnitude while the scroll that recovers the point runs the other+ // way. `flowNegative` reverses flow, not geometry; nothing reverses this.+ // Every `null` falls back to comparing the two spaces unconverted, which is what this branch did+ // before the conversion existed -- a no-change, never a new guess.+ const axisAligned = (m) =>+ m.m12 === 0 && m.m13 === 0 && m.m14 === 0+ && m.m21 === 0 && m.m23 === 0 && m.m24 === 0+ && m.m31 === 0 && m.m32 === 0 && m.m34 === 0;+ // An explicit `rotate: 0deg` is an identity an author writes to give a later transition something+ // to animate from; excluded by the string alone it would disable the conversion for the whole+ // chain.+ const zeroAngle = (v) => {+ const m = /(-?[0-9.]+)(deg|grad|rad|turn)\s*$/.exec(v || '');+ return !!m && parseFloat(m[1]) === 0;+ };+ const flowScale = (start) => {+ const none = { x: null, y: null };+ const svgNs = 'http://www.w3.org/2000/svg';+ let sx = 1, sy = 1;+ for (+ let p = start, hops = 0;+ p && p !== document && hops < 60;+ hops++, p = p.assignedSlot || p.parentNode || p.host || null+ ) {+ if (p.nodeType !== 1) continue;+ // From a foreignObject up, the browser composes the whole mapping itself -- viewBox,+ // `preserveAspectRatio`, nested viewports, `<g>` transforms and every CSS transform and `zoom`+ // above the `<svg>` -- against the RENDERED viewport, which the `width` attribute is not once CSS+ // sizes the `<svg>`. `getScreenCTM` is that whole product, so it ends the walk.+ if (p.namespaceURI === svgNs && p.localName === 'foreignObject') {+ let c;+ try { c = p.getScreenCTM(); } catch (e) { return none; }+ if (!c || c.b !== 0 || c.c !== 0) return none;+ sx *= c.a;+ sy *= c.d;+ break;+ }+ let ps;+ try { ps = getComputedStyle(p); } catch (e) { return none; }+ // `zoom` DOES apply on inline and `display: contents` boxes, so it is read before the skip.+ const z = parseFloat(ps.zoom);+ if (Number.isFinite(z) && z > 0) { sx *= z; sy *= z; }+ // A boxless element is not in the mapping, yet Chromium still reports its `rotate`/`scale` (a+ // `display: contents` wrapper's `rotate: 45deg` would refuse a control under a real `scale(2)`).+ // Inline `<svg>`/`<g>` transforms DO apply, hence the namespace.+ if (ps.display === 'contents' || (ps.display === 'inline' && p.namespaceURI !== svgNs)) continue;+ if (ps.rotate && ps.rotate !== 'none' && !zeroAngle(ps.rotate)) return none;+ if (ps.scale && ps.scale !== 'none') {+ const parts = String(ps.scale).trim().split(/\s+/).map((v) => parseFloat(v));+ if (!parts.length || parts.some((v) => !Number.isFinite(v))) return none;+ sx *= parts[0];+ sy *= parts.length > 1 ? parts[1] : parts[0];+ }+ if (ps.transform && ps.transform !== 'none') {+ let m;+ try { m = new DOMMatrix(ps.transform); } catch (e) { return none; }+ if (!axisAligned(m)) return none;+ // A homogeneous matrix scales by `m11 / m44`: `matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,.5)`+ // doubles everything while its `m11` reads 1.+ if (!(m.m44 > 0)) return none;+ sx *= m.m11 / m.m44;+ sy *= m.m22 / m.m44;+ }+ }+ const usable = (v) => (v > 0 && Math.abs(v - 1) > 1e-9 ? v : null);+ return { x: usable(sx), y: usable(sy) };+ };+"""+_WITH_POINTER_ROOTS_JS = (r"""(root, q, semantic, state, emit, listable) => {// A linked list, not an array: a page that poisons Array.prototype.push or its index setters@@ -1472,31 +1601,651 @@ _WITH_POINTER_ROOTS_JS = (return d && d.get ? d.get : function () { return this[name]; };};const parentOf = getter(Node.prototype, 'parentElement');+ const nodeTypeOf = getter(Node.prototype, 'nodeType');const localNameOf = getter(Element.prototype, 'localName');const innerTextOf = getter(HTMLElement.prototype, 'innerText');const textContentOf = getter(Node.prototype, 'textContent');+ const createTreeWalker = Document.prototype.createTreeWalker;const textOf = (el) => { try { return String(innerTextOf.call(el) || '').trim(); } catch (e) { return ''; } };+"""+ + _SCROLL_GEOMETRY_JS+ + r"""+ let cursorRules = null;+ let cursorRuleOrder = 0;+ const splitSelectors = (selector) => {+ const parts = [];+ let start = 0, parens = 0, brackets = 0, quote = '', escaped = false;+ for (let i = 0; i < selector.length; i++) {+ const c = selector[i];+ if (escaped) { escaped = false; continue; }+ if (c === '\\') { escaped = true; continue; }+ if (quote) { if (c === quote) quote = ''; continue; }+ if (c === '"' || c === "'") { quote = c; continue; }+ if (c === '(') parens++;+ else if (c === ')') parens--;+ else if (c === '[') brackets++;+ else if (c === ']') brackets--;+ else if (c === ',' && !parens && !brackets) { parts.push(selector.slice(start, i).trim()); start = i + 1; }+ }+ parts.push(selector.slice(start).trim());+ return parts.filter(Boolean);+ };+ const selectorSpecificity = (selector) => {+ let ids = 0, classes = 0, elements = 0, compoundStart = true;+ const skipName = (text, start) => {+ let i = start;+ while (i < text.length) {+ if (text[i] === '\\') {+ i++;+ if (/[\da-f]/i.test(text[i] || '')) {+ for (let digits = 0; digits < 6 && /[\da-f]/i.test(text[i] || ''); digits++) i++;+ if (/\s/.test(text[i] || '')) i++;+ } else i++;+ } else if (/[-_\da-z]/i.test(text[i]) || text.charCodeAt(i) >= 128) i++;+ else break;+ }+ return i;+ };+ const matchingParen = (text, start) => {+ let depth = 0, quote = '', escaped = false;+ for (let i = start; i < text.length; i++) {+ const c = text[i];+ if (escaped) { escaped = false; continue; }+ if (c === '\\') { escaped = true; continue; }+ if (quote) { if (c === quote) quote = ''; continue; }+ if (c === '"' || c === "'") { quote = c; continue; }+ if (c === '(') depth++;+ else if (c === ')' && --depth === 0) return i;+ }+ return text.length;+ };+ const addMax = (text) => {+ let best = null;+ for (const part of splitSelectors(text)) {+ const candidate = selectorSpecificity(part);+ if (!best || candidate[0] > best[0]+ || (candidate[0] === best[0] && candidate[1] > best[1])+ || (candidate[0] === best[0] && candidate[1] === best[1] && candidate[2] > best[2])) best = candidate;+ }+ if (best) { ids += best[0]; classes += best[1]; elements += best[2]; }+ };+ for (let i = 0; i < selector.length;) {+ const c = selector[i];+ if (/\s/.test(c) || c === '>' || c === '+' || c === '~') { compoundStart = true; i++; continue; }+ if (c === '#') { ids++; i = skipName(selector, i + 1); compoundStart = false; continue; }+ if (c === '.') { classes++; i = skipName(selector, i + 1); compoundStart = false; continue; }+ if (c === '[') {+ classes++;+ let end = i + 1, quote = '', escaped = false;+ for (; end < selector.length; end++) {+ const ch = selector[end];+ if (escaped) { escaped = false; continue; }+ if (ch === '\\') { escaped = true; continue; }+ if (quote) { if (ch === quote) quote = ''; continue; }+ if (ch === '"' || ch === "'") quote = ch;+ else if (ch === ']') break;+ }+ i = end + 1; compoundStart = false; continue;+ }+ if (c === ':') {+ const pseudoElement = selector[i + 1] === ':';+ const nameStart = i + (pseudoElement ? 2 : 1);+ const nameEnd = skipName(selector, nameStart);+ const name = selector.slice(nameStart, nameEnd).toLowerCase();+ let end = nameEnd, args = '';+ if (selector[end] === '(') {+ const close = matchingParen(selector, end);+ args = selector.slice(end + 1, close);+ end = close + 1;+ }+ if (name === 'is' || name === 'not' || name === 'has' || name === 'host' || name === 'host-context') {+ if (args) addMax(args);+ if (name === 'host' || name === 'host-context') classes++;+ } else if (name === 'nth-child' || name === 'nth-last-child') {+ classes++;+ const of = args.match(/\bof\s+(.+)$/i);+ if (of) addMax(of[1]);+ } else if (name !== 'where') {+ if (pseudoElement || ['before', 'after', 'first-line', 'first-letter'].includes(name)) elements++;+ else classes++;+ if (pseudoElement && name === 'slotted' && args) addMax(args);+ }+ i = end; compoundStart = false; continue;+ }+ if (c === '|' && selector[i + 1] === '|') { i += 2; compoundStart = true; continue; }+ if (c === '*' || c === '|') {+ if (compoundStart && c === '*' && selector[i + 1] === '|') {+ i += 2;+ if (selector[i] === '*') i++;+ else { i = skipName(selector, i); elements++; }+ } else if (compoundStart && c === '|' && selector[i + 1] !== '|') {+ i++;+ if (selector[i] === '*') i++;+ else { i = skipName(selector, i); elements++; }+ } else i++;+ compoundStart = false; continue;+ }+ if (c === '\\' || /[-_a-z]/i.test(c) || selector.charCodeAt(i) >= 128) {+ const end = skipName(selector, i);+ if (compoundStart) {+ if (selector[end] === '|' && selector[end + 1] !== '|') {+ i = end + 1;+ if (selector[i] === '*') i++;+ else { i = skipName(selector, i); elements++; }+ } else { elements++; i = end; }+ } else i = end;+ compoundStart = false; continue;+ }+ if (c === '(') i = matchingParen(selector, i) + 1;+ else i++;+ }+ return [ids, classes, elements];+ };+ const compareSpecificity = (a, b) => {+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] - b[i];+ return 0;+ };+ const directPointerCache = new WeakMap();+ const ownPointerCursor = (el) => {+ if (!isPointer(el)) return false;+ const cached = directPointerCache.get(el);+ if (cached !== undefined) return cached;+ let direct = false;+ try {+ if (cursorRules === null) {+ cursorRules = [];+ let scanned = 0;+ const collect = (rules, parentSelector = '', uncertainLayerContext = false, uncertainScopeContext = false) => {+ for (const rule of rules) {+ // shortcut: stop after 2048 rules; raise the cap if larger stylesheets hide row actions.+ if (++scanned > 2048) break;+ try {+ if (rule.media && rule.media.mediaText && !matchMedia(rule.media.mediaText).matches) continue;+ if (typeof CSSSupportsRule !== 'undefined' && rule instanceof CSSSupportsRule+ && !CSS.supports(rule.conditionText)) continue;+ // shortcut: skip container-query cursor provenance until its condition can be matched per candidate.+ if (typeof CSSContainerRule !== 'undefined' && rule instanceof CSSContainerRule) continue;+ const layerContext = uncertainLayerContext+ || (typeof CSSLayerBlockRule !== 'undefined' && rule instanceof CSSLayerBlockRule)+ || (typeof CSSImportRule !== 'undefined' && rule instanceof CSSImportRule+ && rule.layerName !== undefined && rule.layerName !== null);+ const scopeContext = uncertainScopeContext+ || (typeof CSSScopeRule !== 'undefined' && rule instanceof CSSScopeRule)+ || /^@scope\b/i.test(rule.cssText || '') && !rule.selectorText;+ const uncertainContext = layerContext || scopeContext;+ const selector = rule.selectorText+ ? parentSelector+ ? splitSelectors(rule.selectorText).map((part) => part.includes('&')+ ? part.replaceAll('&', `:is(${parentSelector})`)+ : `:is(${parentSelector}) ${part}`).join(', ')+ : rule.selectorText+ : parentSelector;+ if (rule.style && selector) {+ const cursor = rule.style.getPropertyValue('cursor').trim();+ if (cursor) {+ const order = cursorRuleOrder++;+ for (const part of splitSelectors(selector)) {+ cursorRules.push({+ selector: part,+ cursor,+ important: rule.style.getPropertyPriority('cursor') === 'important',+ specificity: [0, ...selectorSpecificity(part)],+ order,+ uncertainContext,+ uncertainLayerContext: layerContext,+ });+ }+ }+ }+ if (typeof CSSImportRule !== 'undefined' && rule instanceof CSSImportRule) {+ collect(rule.styleSheet.cssRules, '', layerContext, scopeContext);+ }+ if (rule.cssRules) {+ collect(rule.cssRules, rule.selectorText ? selector : parentSelector, layerContext, scopeContext);+ }+ } catch (e) { /* inaccessible or invalid rules cannot establish an independent target */ }+ }+ };+ let sheets = [];+ try { sheets = Array.from(root.styleSheets || []); } catch (e) {}+ try { sheets.push(...(root.adoptedStyleSheets || [])); } catch (e) {}+ if (root.nodeType === 11) {+ try {+ for (const node of root.querySelectorAll('style,link[rel~="stylesheet"]')) {+ if (node.sheet) sheets.push(node.sheet);+ }+ } catch (e) {}+ }+ for (const sheet of sheets) {+ try { if (!sheet.disabled) collect(sheet.cssRules); } catch (e) { /* cross-origin stylesheet */ }+ }+ }+ const wins = (candidate, current) => {+ if (!current) return true;+ if (candidate.important !== current.important) return candidate.important;+ const specificity = compareSpecificity(candidate.specificity, current.specificity);+ return specificity ? specificity > 0 : candidate.order > current.order;+ };+ // shortcut: matched @layer/@scope rules fail closed unless the inline declaration provably outranks them.+ // Only the cascade winner establishes independent cursor styling; a losing pointer rule is not provenance.+ let winner = null;+ let unknownContext = false, unknownImportant = false, unknownLayerImportant = false;+ const consider = (candidate) => { if (wins(candidate, winner)) winner = candidate; };+ for (const rule of cursorRules) {+ try {+ if (matches.call(el, rule.selector)) {+ if (rule.uncertainContext) {+ unknownContext = true;+ unknownImportant ||= rule.important;+ unknownLayerImportant ||= rule.uncertainLayerContext && rule.important;+ }+ else consider(rule);+ }+ } catch (e) { /* unsupported selector */ }+ }+ const inline = el.style && el.style.getPropertyValue('cursor').trim();+ const inlineCandidate = inline ? {+ cursor: inline,+ important: el.style.getPropertyPriority('cursor') === 'important',+ specificity: [1, 0, 0, 0],+ order: cursorRuleOrder,+ } : null;+ if (inlineCandidate) consider(inlineCandidate);+ // Inline author styling beats uncertain normal rules; an uncertain !important rule may still win.+ if (unknownContext && (!inlineCandidate || winner !== inlineCandidate+ || (unknownImportant && !inlineCandidate.important)+ || (unknownLayerImportant && inlineCandidate.important))) {+ directPointerCache.set(el, false);+ return false;+ }+ if (winner && !/^(inherit|initial|unset|revert(?:-layer)?)$/i.test(winner.cursor)) {+ direct = true;+ }+ } catch (e) { direct = false; }+ directPointerCache.set(el, direct);+ return direct;+ };// An unnamed root drawing exactly one rendered graphic is an icon control, listed unnamed like an unnamed <button>,// up to the scan ceiling. A wrapper drawing two (copy and trash) is not one control: a click lands between them.- const drawsOneGraphic = (el) => {- const graphic = 'svg,img,canvas,[role="img" i]';- if (matches.call(el, graphic)) return true;- const checkVisibility = Element.prototype.checkVisibility;- let drawn = 0;- const found = qsa.call(el, graphic);- for (const g of found) {- if (checkVisibility && !checkVisibility.call(g, { opacityProperty: true, visibilityProperty: true })) continue;- // An icon font's <span role="img"><svg> is one graphic: one nested in another counts with it.- const outer = closest.call(parentOf.call(g), graphic);- if (outer && Array.prototype.indexOf.call(found, outer) >= 0) continue;- if (++drawn > 1) return false;+ const GRAPHIC_SELECTOR = 'svg,img,canvas,[role="img" i]';+ const graphicCounts = new WeakMap();+ const drawsOneGraphic = (el) => matches.call(el, GRAPHIC_SELECTOR) || graphicCounts.get(el) === 1;+ // The closed paint-channel invariant is: a glyph-sized root has ink via background color/image, border, outline,+ // box-shadow, text glyphs, generated ::before/::after content, or replaced content (SVG/image/canvas/role=img).+ // Two conditions are needed: a glyph-sized box, since a bigger region's centre may miss its control, and visible+ // paint on one of those channels, since an empty box is only a bare hit-target.+ const ICON_BOX_MAX = 48, ICON_BOX_MIN = 6;+ const opaquePaint = """+ + _OPAQUE_PAINT_JS+ + r""";+ const visibleStyle = (cs) => cs && cs.display !== 'none' && cs.visibility === 'visible' && Number(cs.opacity) > 0;+ const zeroOpacityFilter = (filter) => {+ for (const match of String(filter || '').matchAll(/opacity\(\s*([^)]+?)\s*\)/gi)) {+ if (Number(match[1].trim().replace(/%$/, '')) === 0) return true;+ }+ return false;+ };+ const visibleElement = (el) => {+ try {+ for (let current = el; current; current = flatParent(current)) {+ if (nodeTypeOf.call(current) === 1 && zeroOpacityFilter(getComputedStyle(current).filter)) return false;+ }+ const cs = getComputedStyle(el);+ const check = Element.prototype.checkVisibility;+ return visibleStyle(cs)+ && (!check || check.call(el, { opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true }));+ } catch (e) { return false; }+ };+ const imagePaints = (image) => {+ if (!image || image === 'none') return false;+ const gradient = /gradient\(/i.test(image);+ const colors = image.match(/url\([^)]*\)|(?:rgba?|hsla?)\([^)]*\)|#[\da-f]{3,8}\b|\btransparent\b/gi) || [];+ for (const color of colors) {+ if (/^url\(/i.test(color) || opaquePaint(color)) return true;+ }+ return !gradient;+ };+ const shadowPaints = (shadow) => {+ if (!shadow || shadow === 'none') return false;+ const colors = shadow.match(/(?:rgba?|hsla?)\([^)]*\)|#[\da-f]{3,8}\b|\btransparent\b/gi) || [];+ if (colors.length && !colors.some(opaquePaint)) return false;+ const lengths = shadow.replace(/(?:rgba?|hsla?)\([^)]*\)/gi, '').match(/-?(?:\d+\.?\d*|\.\d+)px/g) || [];+ return lengths.some((length) => parseFloat(length) !== 0);+ };+ const textShadowPaints = (shadow) => {+ if (!shadow || shadow === 'none') return false;+ const colors = shadow.match(/(?:rgba?|hsla?)\([^)]*\)|#[\da-f]{3,8}\b|\btransparent\b/gi) || [];+ return colors.some(opaquePaint);+ };+ const inked = (el, cs, pseudo = false) => {+ if (!cs) return false;+ for (const mask of [cs.maskImage, cs.webkitMaskImage]) {+ if (mask && mask !== 'none' && !imagePaints(mask)) return false;+ }+ if (imagePaints(cs.backgroundImage)) return true;+ if (textOf(el) && (opaquePaint(cs.webkitTextFillColor || cs.color) || textShadowPaints(cs.textShadow))) return true;+ if (shadowPaints(cs.boxShadow) || (pseudo && glyphContent(cs.content) && textShadowPaints(cs.textShadow))) return true;+ if (opaquePaint(cs.backgroundColor)) return true;+ for (const side of ['Top', 'Right', 'Bottom', 'Left']) {+ const style = cs['border' + side + 'Style'];+ if (style !== 'none' && style !== 'hidden' && parseFloat(cs['border' + side + 'Width'] || '0') > 0+ && opaquePaint(cs['border' + side + 'Color'])) return true;}- return drawn === 1;+ if (cs.outlineStyle !== 'none' && cs.outlineStyle !== 'hidden' && parseFloat(cs.outlineWidth || '0') > 0+ && opaquePaint(cs.outlineColor)) return true;+ return false;+ };+ const glyphContent = (c) => !!c && c !== 'none' && c !== 'normal' && !/^(['"])\s*\1$/.test(c);+ const generatedContent = (c) => !!c && c !== 'none' && c !== 'normal';+ const clipHides = (target, cs, pseudo = false) => {+ const clip = cs.clipPath || '';+ const rect = bcr.call(target);+ const extent = (axis, fallback, sides) => {+ if (!pseudo) return fallback;+ const size = parseFloat(cs[axis]);+ if (!Number.isFinite(size)) return fallback;+ if (cs.boxSizing === 'border-box') return size;+ return size + sides.reduce((sum, side) => sum + parseFloat(cs[side] || '0'), 0);+ };+ const width = extent('width', rect.width, ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']);+ const height = extent('height', rect.height, ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']);+ const inset = clip.match(/^inset\(([^)]+)\)/i);+ if (inset) {+ const edges = inset[1].split(/\s+round\s+/i)[0].trim().split(/\s+/);+ const [top, right = top, bottom = top, left = right] = edges;+ const px = (value, size) => value.endsWith('%') ? parseFloat(value) * size / 100+ : value.endsWith('px') ? parseFloat(value) : 0;+ return px(top, height) + px(bottom, height) >= height+ || px(right, width) + px(left, width) >= width;+ }+ const zero = (value) => /^[-+]?0(?:\.0*)?(?:px|%)?$/i.test(value);+ const circle = clip.match(/^circle\(\s*([^\s)]+)/i);+ if (circle && zero(circle[1])) return true;+ const ellipse = clip.match(/^ellipse\(\s*([^\s)]+)\s+([^\s)]+)/i);+ if (ellipse && (zero(ellipse[1]) || zero(ellipse[2]))) return true;+ const polygon = clip.match(/^polygon\((.*)\)$/i);+ if (polygon) {+ const points = polygon[1].replace(/^\s*(?:evenodd|nonzero)\s*,/i, '').split(',').map((point) => {+ const coords = point.trim().split(/\s+/);+ if (coords.length !== 2) return null;+ const length = (value, size) => {+ const m = value.match(/^([-+]?(?:\d+\.?\d*|\.\d+))(px|%)?$/i);+ if (!m || (!m[2] && Number(m[1]) !== 0)) return null;+ return Number(m[1]) * (m[2] === '%' ? size / 100 : 1);+ };+ const x = length(coords[0], width), y = length(coords[1], height);+ return x === null || y === null ? null : [x, y];+ });+ if (points.length >= 3 && points.every(Boolean)) {+ const first = points[0];+ const second = points.find((point) => point[0] !== first[0] || point[1] !== first[1]);+ if (!second || points.every((point) => Math.abs((second[0] - first[0]) * (point[1] - first[1])+ - (second[1] - first[1]) * (point[0] - first[0])) < 1e-7)) return true;+ }+ }+ return false;+ };+ const clipContainsPoint = (el, cs, x, y) => {+ const clip = String(cs.clipPath || '').trim();+ if (!clip || clip === 'none') return true;+ const shape = clip.match(/^(inset|circle|ellipse|polygon)\((.*)\)(?:\s+(.*))?$/i);+ // shortcut: rounded insets, unsupported shapes/boxes, and transforms fail closed; extend if icon controls rely on them.+ if (!shape || (shape[3] && shape[3].trim() !== 'border-box') || (cs.transform && cs.transform !== 'none')) return false;+ const rect = bcr.call(el);+ const length = (value, size) => {+ const match = String(value).trim().match(/^([-+]?(?:\d+\.?\d*|\.\d+))(px|%)?$/i);+ if (!match || (!match[2] && Number(match[1]) !== 0)) return null;+ return Number(match[1]) * (match[2] === '%' ? size / 100 : 1);+ };+ if (/^inset$/i.test(shape[1])) {+ if (/\s+round\s+/i.test(shape[2])) return false;+ const edges = shape[2].trim().split(/\s+/);+ if (edges.length > 4) return false;+ const [top, right = top, bottom = top, left = right] = edges;+ const t = length(top, rect.height), r = length(right, rect.width);+ const b = length(bottom, rect.height), l = length(left, rect.width);+ return t !== null && r !== null && b !== null && l !== null+ && x >= rect.left + l && x <= rect.right - r && y >= rect.top + t && y <= rect.bottom - b;+ }+ if (/^polygon$/i.test(shape[1])) {+ let body = shape[2].trim(), fill = 'nonzero';+ const rule = body.match(/^(evenodd|nonzero)\s*,/i);+ if (rule) { fill = rule[1].toLowerCase(); body = body.slice(rule[0].length); }+ const points = body.split(',').map((point) => {+ const coords = point.trim().split(/\s+/);+ if (coords.length !== 2) return null;+ const px = length(coords[0], rect.width), py = length(coords[1], rect.height);+ return px === null || py === null ? null : [rect.left + px, rect.top + py];+ });+ if (points.length < 3 || points.some((point) => !point)) return false;+ let crossings = 0, winding = 0;+ for (let i = 0, j = points.length - 1; i < points.length; j = i++) {+ const [xi, yi] = points[i], [xj, yj] = points[j];+ if ((yi > y) !== (yj > y)) {+ const crossingX = xi + (y - yi) * (xj - xi) / (yj - yi);+ if (x < crossingX) crossings++;+ }+ const side = (xj - xi) * (y - yi) - (x - xi) * (yj - yi);+ if (yi <= y && yj > y && side > 0) winding++;+ else if (yi > y && yj <= y && side < 0) winding--;+ }+ return fill === 'evenodd' ? crossings % 2 === 1 : winding !== 0;+ }+ const parts = shape[2].trim().split(/\s+at\s+/i);+ const radiusText = parts[0].trim() || 'closest-side';+ const position = parts[1] ? parts[1].trim().split(/\s+/) : ['50%', '50%'];+ if (position.length === 1) {+ if (/^(top|bottom)$/i.test(position[0])) position.unshift('50%');+ else position.push('50%');+ }+ if (position.length !== 2) return false;+ if (/^(top|bottom)$/i.test(position[0]) && /^(left|right)$/i.test(position[1])) position.reverse();+ const coordinate = (value, start, size) => {+ if (/^(center)$/i.test(value)) return start + size / 2;+ if (/^(left|top)$/i.test(value)) return start;+ if (/^(right|bottom)$/i.test(value)) return start + size;+ const offset = length(value, size);+ return offset === null ? null : start + offset;+ };+ const cx = coordinate(position[0], rect.left, rect.width);+ const cy = coordinate(position[1], rect.top, rect.height);+ if (cx === null || cy === null) return false;+ const radius = (value, size, axis) => {+ if (value === 'closest-side') return Math.min(axis === 'x' ? cx - rect.left : cy - rect.top,+ axis === 'x' ? rect.right - cx : rect.bottom - cy);+ if (value === 'farthest-side') return Math.max(axis === 'x' ? cx - rect.left : cy - rect.top,+ axis === 'x' ? rect.right - cx : rect.bottom - cy);+ if (value === 'closest-corner' || value === 'farthest-corner') {+ if (axis !== 'circle') return null;+ const corners = [[rect.left, rect.top], [rect.right, rect.top], [rect.left, rect.bottom], [rect.right, rect.bottom]];+ const distances = corners.map(([px, py]) => Math.hypot(px - cx, py - cy));+ return value === 'closest-corner' ? Math.min(...distances) : Math.max(...distances);+ }+ if (axis === 'circle') {+ const match = String(value).match(/^([-+]?(?:\d+\.?\d*|\.\d+))(px|%)?$/i);+ if (!match || (!match[2] && Number(match[1]) !== 0)) return null;+ return Number(match[1]) * (match[2] === '%' ? Math.hypot(rect.width, rect.height) / Math.SQRT2 / 100 : 1);+ }+ return length(value, size);+ };+ let rx, ry;+ if (/^circle$/i.test(shape[1])) {+ rx = ry = radius(radiusText, rect.width, 'circle');+ } else {+ const radii = radiusText.split(/\s+/);+ if (radii.length > 2) return false;+ rx = radius(radii[0] || 'closest-side', rect.width, 'x');+ ry = radius(radii[1] || radii[0] || 'closest-side', rect.height, 'y');+ }+ return rx !== null && ry !== null && rx > 0 && ry > 0+ && ((x - cx) / rx) ** 2 + ((y - cy) / ry) ** 2 <= 1;+ };+ const clipHidesBox = (el, cs = getComputedStyle(el), pseudo = false) => {+ const rect = bcr.call(el), x = rect.left + rect.width / 2, y = rect.top + rect.height / 2;+ if (!clipContainsPoint(el, cs, x, y) || clipHides(el, cs, pseudo)) return true;+ // A pseudo-element is clipped by its originating element as well as by its own clip path.+ if (pseudo) {+ const own = getComputedStyle(el);+ if (!clipContainsPoint(el, own, x, y) || clipHides(el, own)) return true;+ }+ // Ancestor clip paths constrain descendant ink at the same centre point the click targets.+ for (let ancestor = flatParent(el), i = 0; ancestor && i < 64; ancestor = flatParent(ancestor), i++) {+ if (nodeTypeOf.call(ancestor) === 1) {+ const ancestorStyle = getComputedStyle(ancestor);+ if (!clipContainsPoint(ancestor, ancestorStyle, x, y) || clipHides(ancestor, ancestorStyle)) return true;+ const clipX = ancestorStyle.overflowX === 'hidden' || ancestorStyle.overflowX === 'clip';+ const clipY = ancestorStyle.overflowY === 'hidden' || ancestorStyle.overflowY === 'clip';+ if (clipX || clipY) {+ const bounds = bcr.call(ancestor), width = (v) => parseFloat(v) || 0;+ const clipAxisX = ancestorStyle.overflowX === 'clip';+ const clipAxisY = ancestorStyle.overflowY === 'clip';+ const marginText = clipAxisX || clipAxisY ? ancestorStyle.overflowClipMargin || '' : '';+ const marginMatch = marginText.match(/(\d+(?:\.\d+)?)px/);+ const margin = marginMatch ? parseFloat(marginMatch[1]) : 0;+ const toBorderBox = marginText.includes('border-box');+ const toContentBox = marginText.includes('content-box');+ const inset = (isClip, border, padding) => !isClip ? width(border)+ : toBorderBox ? 0 : width(border) + (toContentBox ? width(padding) : 0);+ const left = bounds.left + inset(clipAxisX, ancestorStyle.borderLeftWidth, ancestorStyle.paddingLeft)+ - (clipAxisX ? margin : 0);+ const right = bounds.right - inset(clipAxisX, ancestorStyle.borderRightWidth, ancestorStyle.paddingRight)+ + (clipAxisX ? margin : 0);+ const top = bounds.top + inset(clipAxisY, ancestorStyle.borderTopWidth, ancestorStyle.paddingTop)+ - (clipAxisY ? margin : 0);+ const bottom = bounds.bottom - inset(clipAxisY, ancestorStyle.borderBottomWidth, ancestorStyle.paddingBottom)+ + (clipAxisY ? margin : 0);+ const outsideX = clipX && (x < left || x >= right);+ const outsideY = clipY && (y < top || y >= bottom);+ if (outsideX || outsideY) {+ // `hidden` can recover a clipped target by scrolling; `clip` cannot. Preserve only points+ // the remaining scroll range can actually bring inside, not merely any overflowing box.+ let flow = null, scale = null;+ const canScroll = (axis, before, distance) => {+ const isX = axis === 'x';+ if (ancestorStyle[isX ? 'overflowX' : 'overflowY'] !== 'hidden') return false;+ const client = ancestor[isX ? 'clientWidth' : 'clientHeight'];+ if (!client) return false;+ if (!flow) flow = flowNegative(ancestorStyle);+ if (!scale) scale = flowScale(ancestor);+ const span = Math.max(0, ancestor[isX ? 'scrollWidth' : 'scrollHeight'] - client);+ const inverted = flow[axis];+ const min = inverted ? -span : 0, max = inverted ? 0 : span;+ const offset = ancestor[isX ? 'scrollLeft' : 'scrollTop'];+ const available = before ? offset - min : max - offset;+ return before ? available >= distance / (scale[axis] || 1)+ : available > distance / (scale[axis] || 1);+ };+ if ((outsideX && !canScroll('x', x < left, x < left ? left - x : x - right))+ || (outsideY && !canScroll('y', y < top, y < top ? top - y : y - bottom))) return true;+ }+ }+ }+ }+ return false;+ };+ const pseudoHasArea = (cs) => {+ const dimension = (axis, sides) => {+ const value = parseFloat(cs[axis]);+ if (!Number.isFinite(value)) return null;+ return cs.boxSizing === 'border-box' ? value+ : value + sides.reduce((sum, side) => sum + (parseFloat(cs[side]) || 0), 0);+ };+ const width = dimension('width', ['paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth']);+ const height = dimension('height', ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']);+ return (width === null || width > 0) && (height === null || height > 0);+ };+ const paintsPseudo = (el, pseudo) => {+ const cs = getComputedStyle(el, pseudo);+ if (!visibleElement(el) || clipHidesBox(el, cs, true) || !visibleStyle(cs) || zeroOpacityFilter(cs.filter)+ || !generatedContent(cs.content) || (!glyphContent(cs.content) && !pseudoHasArea(cs))) return false;+ if (inked(el, cs, true)) return true;+ return glyphContent(cs.content) && (/^url\(/i.test(cs.content) || opaquePaint(cs.webkitTextFillColor || cs.color));+ };+ const paintCache = new WeakMap();+ const ownPaint = (el) => {+ const cached = paintCache.get(el);+ if (cached !== undefined) return cached;+ const paint = { visible: false, ink: false };+ try {+ paint.visible = visibleElement(el) && !clipHidesBox(el);+ if (paint.visible) {+ paint.ink = inked(el, getComputedStyle(el));+ for (const pseudo of ['::before', '::after']) if (!paint.ink && paintsPseudo(el, pseudo)) paint.ink = true;+ }+ } catch (e) {}+ paintCache.set(el, paint);+ return paint;+ };+ const inkCache = new WeakMap();+ const paintsInk = (el) => {+ const cached = inkCache.get(el);+ if (cached !== undefined) return cached;+ let ink = false;+ try {+ const own = ownPaint(el);+ if (!own.visible) {+ inkCache.set(el, false);+ return false;+ }+ ink = own.ink;+ // The glyph is often painted by a child (three dot <span>s, a styled bar). Bounded: an icon's+ // subtree is tiny, and the scan already walks up to 400 elements.+ if (!ink) {+ const rootRect = bcr.call(el);+ for (const kid of firstDescendants(el, 32)) {+ const rect = bcr.call(kid);+ if (!(rect.width > 0 && rect.height > 0) || rect.right <= rootRect.left || rect.left >= rootRect.right+ || rect.bottom <= rootRect.top || rect.top >= rootRect.bottom) continue;+ const childPaint = ownPaint(kid);+ if (childPaint.visible && childPaint.ink) { ink = true; break; }+ }+ }+ } catch (e) { ink = false; }+ inkCache.set(el, ink);+ return ink;+ };+ const hasSeveralPointerInkChildren = (el) => {+ let found = 0;+ for (const kid of firstDescendants(el, 32)) {+ const r = bcr.call(kid);+ if (r.width < ICON_BOX_MIN || r.height < ICON_BOX_MIN) continue;+ if (ownPointerCursor(kid) && (drawsOneGraphic(kid) || paintsInk(kid)) && ++found > 1) return true;+ }+ return false;+ };+ const iconKind = (el, r) => {+ if (graphicCounts.get(el) > 1) return 'multiple';+ const graphic = drawsOneGraphic(el);+ if (graphic && clipHidesBox(el)) return null;+ const cssSized = r.width >= ICON_BOX_MIN && r.height >= ICON_BOX_MIN+ && r.width <= ICON_BOX_MAX && r.height <= ICON_BOX_MAX;+ const ink = cssSized && paintsInk(el);+ if ((graphic || ink) && hasSeveralPointerInkChildren(el)) return 'multiple';+ if (graphic) return 'graphic';+ return ink ? 'css' : null;};const shadowRootOf = getter(Element.prototype, 'shadowRoot');const closest = Element.prototype.closest;const matches = Element.prototype.matches;const qsa = Element.prototype.querySelectorAll;+ const firstElementChildOf = getter(Element.prototype, 'firstElementChild');+ const nextElementSiblingOf = getter(Element.prototype, 'nextElementSibling');+ const firstDescendants = (el, limit) => {+ const found = [];+ let child = firstElementChildOf.call(el);+ while (child && found.length < limit) {+ found.push(child);+ const first = firstElementChildOf.call(child);+ if (first) { child = first; continue; }+ while (child && child !== el) {+ const next = nextElementSiblingOf.call(child);+ if (next) { child = next; break; }+ child = parentOf.call(child);+ }+ if (child === el) child = null;+ }+ return found;+ };const getAttr = Element.prototype.getAttribute;const bcr = Element.prototype.getBoundingClientRect;const follows = Node.prototype.compareDocumentPosition;@@ -1539,6 +2288,7 @@ _WITH_POINTER_ROOTS_JS = (// A component's wrapper around slotted light-DOM content that is already listed, as a root (it// inherits the cursor through the flat tree, and its root was walked first) or as a control.const heldBySlot = (el) => {+ if (!hasSlotDescendant.has(el)) return false;for (const slot of qsa.call(el, 'slot')) {for (const a of slot.assignedElements({ flatten: true })) {if (state.roots.has(a) || inListable(a) || anyListable(qsa.call(a, q))) return true;@@ -1595,8 +2345,59 @@ _WITH_POINTER_ROOTS_JS = (const clip = (n) => !!n && /hidden|clip/.test(getComputedStyle(n).overflowX);return clip(document.documentElement) || clip(document.body) || scrollWidthOf.call(se) <= window.innerWidth;};+ const countNotIcon = (el) => {+ for (let a = flatParent(el), i = 0; a && i < 64 && isPointer(a); a = flatParent(a), i++) {+ if (state.notIconRoots.has(a)) return;+ }+ state.notIconRoots.add(el);+ state.notIcon++;+ };+ const hasSlotDescendant = new WeakSet();+ const hasListableDescendant = new WeakSet();+ const listableElements = new WeakSet();+ const namedElements = new WeakSet();+ const hasNamedDescendant = new WeakSet();+ const hasTextDescendant = new WeakSet();let all = [];try { all = root.querySelectorAll('*'); } catch (e) { all = []; }+ try {+ for (const slot of root.querySelectorAll('slot')) {+ for (let parent = parentOf.call(slot); parent; parent = parentOf.call(parent)) hasSlotDescendant.add(parent);+ }+ for (const control of root.querySelectorAll(q)) {+ if (listable(control)) {+ listableElements.add(control);+ }+ }+ for (const named of root.querySelectorAll('[aria-label],[title]')) namedElements.add(named);+ const walker = createTreeWalker.call(document, root, NodeFilter.SHOW_TEXT);+ for (let text = walker.nextNode(); text; text = walker.nextNode()) {+ const parent = parentOf.call(text);+ if (parent && String(textContentOf.call(text) || '').trim()) hasTextDescendant.add(parent);+ }+ for (let i = all.length - 1; i >= 0; i--) {+ const el = all[i];+ const parent = parentOf.call(el);+ if (parent) {+ if (listableElements.has(el) || hasListableDescendant.has(el)) hasListableDescendant.add(parent);+ if (namedElements.has(el) || hasNamedDescendant.has(el)) hasNamedDescendant.add(parent);+ if (hasTextDescendant.has(el)) hasTextDescendant.add(parent);+ }+ }+ } catch (e) {}+ try {+ const checkVisibility = Element.prototype.checkVisibility;+ for (const graphic of root.querySelectorAll(GRAPHIC_SELECTOR)) {+ if (checkVisibility && !checkVisibility.call(graphic, { opacityProperty: true, visibilityProperty: true })) continue;+ let outerGraphic = null;+ for (let parent = parentOf.call(graphic); parent; parent = parentOf.call(parent)) {+ if (matches.call(parent, GRAPHIC_SELECTOR)) { outerGraphic = parent; break; }+ }+ for (let parent = parentOf.call(graphic); parent && parent !== outerGraphic; parent = parentOf.call(parent)) {+ graphicCounts.set(parent, (graphicCounts.get(parent) || 0) + 1);+ }+ }+ } catch (e) {}// A failure here costs the pointer roots only, never the semantic list merged below.try {for (const el of all) {@@ -1613,7 +2414,7 @@ _WITH_POINTER_ROOTS_JS = (// A control the reading drops is not a root, but its pointer children may be.if (matches.call(el, q)) { if (listable(el)) state.covered.add(el); continue; }const sr = shadowRootOf.call(el);- const holds = anyListable(qsa.call(el, q));+ const holds = hasListableDescendant.has(el);if (inListable(parentOf.call(el)) || (sr && sr.nodeType === 11 && (holds || anyListable(fragQsa.call(sr, q))))|| heldBySlot(el)// A label bound to a control names that control, which is listed (or skinned) on its own.@@ -1628,18 +2429,23 @@ _WITH_POINTER_ROOTS_JS = (}// An icon in a pointer card is its own control (the card's trash), not a stand-in for the card, so a card// already represented still lists it.- const iconInCard = holder !== null && drawsOneGraphic(el) && !textOf(el);- if (holder && !iconInCard && (state.represented.has(holder) || state.heldCount >= state.heldCap)) {+ const r = bcr.call(el);+ if (!(r.width > 0 && r.height > 0)) continue;+ if (getComputedStyle(el).visibility !== 'visible' || offCanvas(el, r)) continue;+ if (!painted(el, r) || offRight(el, r)) continue;+ const kind = iconKind(el, r);+ const directPointer = kind === 'graphic' || ownPointerCursor(el);+ const iconInCard = holder !== null && (kind === 'graphic' || (kind === 'css' && directPointer)) && !textOf(el);+ if (holder && kind !== 'multiple' && !iconInCard && (state.represented.has(holder) || state.heldCount >= state.heldCap)) {state.covered.add(el);continue;}// A decorative child (an icon font's ligature) does not name the row.if (holder && closest.call(el, '[aria-hidden="true"]')) continue;- const r = bcr.call(el);- if (!(r.width > 0 && r.height > 0)) continue;- if (getComputedStyle(el).visibility !== 'visible' || offCanvas(el, r)) continue;let name = '';- try { name = String(innerTextOf.call(el) || '').trim(); } catch (e) { name = ''; }+ if (hasTextDescendant.has(el)) {+ try { name = String(innerTextOf.call(el) || '').trim(); } catch (e) { name = ''; }+ }if (!name) name = String(getAttr.call(el, 'aria-label') || getAttr.call(el, 'title') || '').trim();// innerText stops at a <slot>, so a component's wrapper is named by the rendered text slotted in.if (!name) {@@ -1660,15 +2466,20 @@ _WITH_POINTER_ROOTS_JS = (if (name) break;}}- const icon = !name && state.iconCount < state.ceiling && drawsOneGraphic(el)- && !qsa.call(el, '[aria-label],[title]').length;- if (!name && !icon) continue;+ const iconCandidate = !name && (kind === 'graphic' || (kind === 'css' && (holder === null || directPointer)))+ && !hasNamedDescendant.has(el);+ const icon = iconCandidate && state.iconCount < state.ceiling;+ if (!name && kind === 'multiple') continue;+ // shortcut: cross-origin CSSOM hides cursor provenance, relax with a safe action-vs-decoration signal.+ if (!name && holder && kind === 'css' && !directPointer) continue;+ if (!name && iconCandidate && !icon) { state.iconOverflow++; state.covered.add(el); continue; }+ // Only a distinct unnamed pointer root is a miss; its inherited-cursor descendants are one region.+ if (!name && !icon) { countNotIcon(el); continue; }// A named child of a card is the card's stand-in, not its icon, so it keeps the represented and cap rule.if (iconInCard && !icon && (state.represented.has(holder) || state.heldCount >= state.heldCap)) {state.covered.add(el);continue;}- if (!painted(el, r) || offRight(el, r)) continue;// An icon names itself through its graphic (an <img alt>, an <svg><title>). Read only as the icon's label:// as a name it would move the icon out of the icon budget and into the 40 slots named roots share.let graphicName = '';@@ -4829,7 +5640,9 @@ _INTERACTIVE_HIT_SEL = ('[role~="scrollbar" i], [draggable="true" i]')-_PAINT_VISIBLE_JS = r"""+_PAINT_VISIBLE_JS = (+ _SCROLL_GEOMETRY_JS+ + r"""// forPaint asks "would a person SEE this", not "could a person interact with it": a scrim with// pointer-events:none is still seen even though clicks pass through it, so the paint scan// (layerShowsPaint) passes forPaint=true to keep such a child in view. Every other caller omits it@@ -4926,6 +5739,7 @@ _PAINT_VISIBLE_JS = r"""return true;};"""+)_OWN_LABEL_HIT_JS = (r"""@@ -5101,114 +5915,6 @@ _TYPE_TARGET_PROBE_JS = (// offset and a diagnosis must not move the page it is about to describe -- checked against// assigned-scroll ground truth over the whole writing-mode x direction x display x flex-direction// x flex-wrap matrix.- const flowNegative = (cs) => {- const wm = cs.writingMode || 'horizontal-tb';- const rtl = cs.direction === 'rtl';- const vertical = wm.indexOf('horizontal') !== 0;- // `sideways-lr` is the one vertical mode whose inline axis runs bottom-to-top.- const inlineSign = vertical ? ((wm === 'sideways-lr') !== rtl ? -1 : 1) : (rtl ? -1 : 1);- const blockSign = vertical ? (/-rl$/.test(wm) ? -1 : 1) : 1;- const inlineIsX = !vertical;- let xSign = inlineIsX ? inlineSign : blockSign;- let ySign = inlineIsX ? blockSign : inlineSign;- const display = cs.display || '';- if (display === 'flex' || display === 'inline-flex') {- // A flex container lays content out along main/cross, not inline/block: `*-reverse` flips the- // main axis and `wrap-reverse` flips the cross axis.- const fd = cs.flexDirection || 'row';- const mainIsInline = fd.indexOf('row') === 0;- const mainSign = (mainIsInline ? inlineSign : blockSign) * (/-reverse$/.test(fd) ? -1 : 1);- const crossSign =- (mainIsInline ? blockSign : inlineSign) * (cs.flexWrap === 'wrap-reverse' ? -1 : 1);- const mainIsX = mainIsInline === inlineIsX;- xSign = mainIsX ? mainSign : crossSign;- ySign = mainIsX ? crossSign : mainSign;- }- return { x: xSign < 0, y: ySign < 0 };- };- // PER AXIS, the scale the ancestry applies to this container -- or `null` where the box ratio- // cannot express it. Rects are transformed viewport pixels; scroll offsets and computed lengths- // stay untransformed CSS units, and the conversion between them is only sound where the mapping- // is a positive, axis-aligned scale that actually changes scale. Each of the four answers this- // rules out is a way the ratio does harm rather than good:- // scale 1 -- the two spaces COINCIDE, so the ratio carries only `offsetHeight`'s integer- // rounding: an untransformed 30.5px scroller reports 31, and that 1.6% names- // a collapsed panel for a control Playwright clicks. Composed, not remembered- // as a flag, because an outer `scale(2)` under an inner `scale(.5)` cancels.- // per axis -- a `scaleX(2)` ancestor leaves the VERTICAL spaces coinciding, so a shared- // answer would feed that same rounding into `scaleY`.- // not axis-aligned -- under a rotation, a skew or a perspective the rect is an axis-aligned- // BOUND of the box, not a scaled copy: a 2deg tilt on a 600px strip reads- // 1.52 at scale 1, which shrinks the distance asked for below a scroll-back- // that cannot reach the control.- // reflected -- `rect.width / offsetWidth` is unsigned, so a mirrored mapping would convert- // by the magnitude while the scroll that recovers the point runs the other- // way. `flowNegative` reverses flow, not geometry; nothing reverses this.- // Every `null` falls back to comparing the two spaces unconverted, which is what this branch did- // before the conversion existed -- a no-change, never a new guess.- const axisAligned = (m) =>- m.m12 === 0 && m.m13 === 0 && m.m14 === 0- && m.m21 === 0 && m.m23 === 0 && m.m24 === 0- && m.m31 === 0 && m.m32 === 0 && m.m34 === 0;- // An explicit `rotate: 0deg` is an identity an author writes to give a later transition something- // to animate from; excluded by the string alone it would disable the conversion for the whole- // chain.- const zeroAngle = (v) => {- const m = /(-?[0-9.]+)(deg|grad|rad|turn)\s*$/.exec(v || '');- return !!m && parseFloat(m[1]) === 0;- };- const flowScale = (start) => {- const none = { x: null, y: null };- const svgNs = 'http://www.w3.org/2000/svg';- let sx = 1, sy = 1;- for (- let p = start, hops = 0;- p && p !== document && hops < 60;- hops++, p = p.assignedSlot || p.parentNode || p.host || null- ) {- if (p.nodeType !== 1) continue;- // From a foreignObject up, the browser composes the whole mapping itself -- viewBox,- // `preserveAspectRatio`, nested viewports, `<g>` transforms and every CSS transform and `zoom`- // above the `<svg>` -- against the RENDERED viewport, which the `width` attribute is not once CSS- // sizes the `<svg>`. `getScreenCTM` is that whole product, so it ends the walk.- if (p.namespaceURI === svgNs && p.localName === 'foreignObject') {- let c;- try { c = p.getScreenCTM(); } catch (e) { return none; }- if (!c || c.b !== 0 || c.c !== 0) return none;- sx *= c.a;- sy *= c.d;- break;- }- let ps;- try { ps = getComputedStyle(p); } catch (e) { return none; }- // `zoom` DOES apply on inline and `display: contents` boxes, so it is read before the skip.- const z = parseFloat(ps.zoom);- if (Number.isFinite(z) && z > 0) { sx *= z; sy *= z; }- // A boxless element is not in the mapping, yet Chromium still reports its `rotate`/`scale` (a- // `display: contents` wrapper's `rotate: 45deg` would refuse a control under a real `scale(2)`).- // Inline `<svg>`/`<g>` transforms DO apply, hence the namespace.- if (ps.display === 'contents' || (ps.display === 'inline' && p.namespaceURI !== svgNs)) continue;- if (ps.rotate && ps.rotate !== 'none' && !zeroAngle(ps.rotate)) return none;- if (ps.scale && ps.scale !== 'none') {- const parts = String(ps.scale).trim().split(/\s+/).map((v) => parseFloat(v));- if (!parts.length || parts.some((v) => !Number.isFinite(v))) return none;- sx *= parts[0];- sy *= parts.length > 1 ? parts[1] : parts[0];- }- if (ps.transform && ps.transform !== 'none') {- let m;- try { m = new DOMMatrix(ps.transform); } catch (e) { return none; }- if (!axisAligned(m)) return none;- // A homogeneous matrix scales by `m11 / m44`: `matrix3d(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,.5)`- // doubles everything while its `m11` reads 1.- if (!(m.m44 > 0)) return none;- sx *= m.m11 / m.m44;- sy *= m.m22 / m.m44;- }- }- const usable = (v) => (v > 0 && Math.abs(v - 1) > 1e-9 ? v : null);- return { x: usable(sx), y: usable(sy) };- };// A native control's own <label> is a sibling, not an ancestor, so related()'s composed walk never// reaches it on its own -- check the control's genuine labels (and the reverse, a LABEL's genuine// control), resolved by nativeLabelsOf/nativeControlOf rather than trusting `.labels`/`.control`.@@ -5565,18 +6271,9 @@ _TYPE_TARGET_PROBE_JS = (};// Does an element draw a surface a person can see -- a non-transparent background, an image, a// border, or a shadow? The alpha-0 forms of a color (`transparent`, `rgba(...,0)`) paint nothing.- // A color is invisible only when its ALPHA is zero -- parse the alpha channel, never a trailing- // ",0)", which also matches an opaque color whose blue channel is 0 (rgb(0,0,0), rgb(255,0,0)).- // A form we can't parse is treated as paint, so the failure mode is under-suppression, not over.- const opaquePaint = (color) => {- const c = (color || '').replace(/\s+/g, '');- if (!c || c === 'transparent') return false;- const m = c.match(/^rgba?\(([\d.,-]+)\)$/);- if (!m) return true;- const comps = m[1].split(',');- const alpha = comps.length >= 4 ? parseFloat(comps[3]) : 1;- return !(alpha === 0);- };+ const opaquePaint = """+ + _OPAQUE_PAINT_JS+ + r""";// A replaced/embedded element paints pixels with no CSS surface of its own -- an icon-only spinner// or logo (img/svg/canvas/video/iframe) is plainly visible even though backgroundColor/border are// empty, so it must count as paint or such a layer reads as an invisible ghost. The caller filters@@ -9131,7 +9828,7 @@ async (__tv3TextArgs) => {const _screenListable = (el) => {try { return _screen(el, false).why === null; } catch (e) { return false; }};- const _pointerState = { pointer: new Map(), covered: new Set(), roots: new Map(), holders: new Set(), represented: new Set(), held: new Set(), icons: new Set(), iconCount: 0, heldCount: 0, heldCap: """+ const _pointerState = { pointer: new Map(), covered: new Set(), roots: new Map(), holders: new Set(), represented: new Set(), held: new Set(), icons: new Set(), iconCount: 0, iconOverflow: 0, notIcon: 0, notIconRoots: new Set(), heldCount: 0, heldCap: """+ str(OBSERVE_POINTER_ROOT_CAP)+ r""", count: 0, retain: _RETAIN_WIDTH, ceiling: """+ str(_POINTER_ROOT_SCAN_CEILING)@@ -10979,7 +11676,7 @@ async (__tv3TextArgs) => {} catch (e) { /* a count the page broke is not worth the reading */ }let readyState = '';try { readyState = String(_getter(Document.prototype, 'readyState').call(document)); } catch (e) { readyState = ''; }- const payload = _ownStringify({ textDelta: textDelta, refsFresh: refsFresh, flutter: __OBSERVE_FLUTTER__, url: location.href, title: document.title, text: texts, textFull: texts.map((t) => { const f = fullText.get(t); return f && f !== t ? f : null; }), textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, frameCensus: frameCensus, dropped: dropped, truncated: truncated, iconsTruncated: iconsTruncated, truncatedInComponents: truncatedInComponents, pointerCapped: pointerCapped, pointerTruncated: pointerTruncated, pointerDropped: pointerDropped, pointerListed: pointerListed, pointerScanStopped: _pointerState.scanStopped ? 1 : 0, pointerScanFailed: _pointerState.scanFailed ? 1 : 0, unreadableRoot: sawUnreadableRoot, undiscoveredRoots: undiscoveredRoots, rootCount: allRoots.length - 1, hiddenListed: hiddenListed, hiddenDropped: hiddenDropped, hiddenDroppedOffCanvas: hiddenDroppedOffCanvas, hiddenDroppedVisibility: hiddenDroppedVisibility, hiddenDroppedZeroRect: hiddenDroppedZeroRect, hiddenDroppedOffViewport: hiddenDroppedOffViewport, offViewportUnreachableUnnamed: offViewportUnreachableUnnamed, offViewportUnnamedHostExempt: offViewportUnnamedHostExempt, phantomDropped: phantomDropped, markersMinted: markersWritten, markersReused: markersReused, pageMutated: mutated, modalOpen: modalOpen, modalListed: modalListed, modalTruncated: modalTruncated, readyState: readyState, elements: out });+ const payload = _ownStringify({ textDelta: textDelta, refsFresh: refsFresh, unnamedNotIcon: _pointerState.notIcon, flutter: __OBSERVE_FLUTTER__, url: location.href, title: document.title, text: texts, textFull: texts.map((t) => { const f = fullText.get(t); return f && f !== t ? f : null; }), textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, frameCensus: frameCensus, dropped: dropped, truncated: truncated, iconsTruncated: iconsTruncated + _pointerState.iconOverflow, truncatedInComponents: truncatedInComponents, pointerCapped: pointerCapped, pointerTruncated: pointerTruncated, pointerDropped: pointerDropped, pointerListed: pointerListed, pointerScanStopped: _pointerState.scanStopped ? 1 : 0, pointerScanFailed: _pointerState.scanFailed ? 1 : 0, unreadableRoot: sawUnreadableRoot, undiscoveredRoots: undiscoveredRoots, rootCount: allRoots.length - 1, hiddenListed: hiddenListed, hiddenDropped: hiddenDropped, hiddenDroppedOffCanvas: hiddenDroppedOffCanvas, hiddenDroppedVisibility: hiddenDroppedVisibility, hiddenDroppedZeroRect: hiddenDroppedZeroRect, hiddenDroppedOffViewport: hiddenDroppedOffViewport, offViewportUnreachableUnnamed: offViewportUnreachableUnnamed, offViewportUnnamedHostExempt: offViewportUnnamedHostExempt, phantomDropped: phantomDropped, markersMinted: markersWritten, markersReused: markersReused, pageMutated: mutated, modalOpen: modalOpen, modalListed: modalListed, modalTruncated: modalTruncated, readyState: readyState, elements: out });return __OBSERVE_RETURN__;}"""@@ -12326,6 +13023,7 @@ _OBSERVE_SUMMED_KEYS = ("dropped","truncated","iconsTruncated",+ "unnamedNotIcon","truncatedInComponents","pointerCapped","pointerTruncated",@@ -12533,9 +13231,7 @@ async def _probe_evaluate(target: Any, js: str, selector: str, arg: dict[str, An# Never echoes the placeholder, the vault marker, or a code: it reaches the model verbatim.NO_ONE_TIME_CODE_SOURCE = (- "this credential has no usable one-time-code (TOTP) secret, so no verification code can be generated "- "for it. Call get_verification_code if it is offered; otherwise finish as failed and state that a "- "verification code source is missing. Never invent or guess a code."+ "no code source is configured for this credential: no one-time code can be fetched or generated for it.")ONE_TIME_CODE_PLACEHOLDER_NOT_ALONE = ("a one-time-code placeholder must be typed alone as the whole text; it cannot be combined with other "@@ -13536,6 +14232,8 @@ def build_browser_tools("icons_listed": sum(1 for e in elements if e.get("icon")),# Icons the budget left over cut, apart from `elements_truncated`, whose denominator leaves icons out."icons_truncated": int(data.get("iconsTruncated") or 0),+ # Distinct unnamed pointer roots rejected by the icon heuristic, separate from budget and selector drops.+ "unnamed_not_icon": int(data.get("unnamedNotIcon") or 0),"pointer_roots_listed": sum(1 for e in elements if e.get("pointerRoot")),"pointer_capped": int(data.get("pointerCapped") or 0),"pointer_truncated": int(data.get("pointerTruncated") or 0),diff --git a/skyvern/services/error_detection_service.py b/skyvern/services/error_detection_service.pyindex b539e82a5..47beb14ba 100644--- a/skyvern/services/error_detection_service.py+++ b/skyvern/services/error_detection_service.py@@ -21,7 +21,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.models import Stepfrom skyvern.forge.sdk.schemas.tasks import Taskfrom skyvern.services.action_service import get_action_history-from skyvern.webeye.actions.handler import extract_user_defined_errors+from skyvern.webeye.actions.handler import _match_user_defined_error_from_reasoning, extract_user_defined_errorsfrom skyvern.webeye.browser_state import BrowserStateLOG = structlog.get_logger()@@ -58,28 +58,26 @@ async def detect_user_defined_errors_for_task()return []+ detected: list[UserDefinedError] = []try:- # Try to use full page-based detection if browser state is available- if browser_state is not None:- page = await browser_state.get_working_page()- if page is not None:- LOG.info(- "Using page-based error detection",- task_id=task.task_id,- step_id=step.step_id,- url=page.url,- )- return await _detect_errors_from_page(task, step, page, browser_state, failure_reason)-- # Fall back to context-based detection when page is not available- LOG.info(- "Browser state or page not available, using context-based error detection",- task_id=task.task_id,- step_id=step.step_id,- has_browser_state=browser_state is not None,- has_failure_reason=failure_reason is not None,- )- return await _detect_errors_from_context(task, step, failure_reason)+ page = await browser_state.get_working_page() if browser_state is not None else None+ if browser_state is not None and page is not None:+ LOG.info(+ "Using page-based error detection",+ task_id=task.task_id,+ step_id=step.step_id,+ url=page.url,+ )+ detected = await _detect_errors_from_page(task, step, page, browser_state, failure_reason)+ else:+ LOG.info(+ "Browser state or page not available, using context-based error detection",+ task_id=task.task_id,+ step_id=step.step_id,+ has_browser_state=browser_state is not None,+ has_failure_reason=failure_reason is not None,+ )+ detected = await _detect_errors_from_context(task, step, failure_reason)except asyncio.CancelledError:# Don't swallow cancellation - let it propagate@@ -93,7 +91,11 @@ async def detect_user_defined_errors_for_task(step_id=step.step_id,exc_info=True,)- return []+ if not detected and failure_reason:+ # Also overrides a model that read the reason and answered no code, as the page path's own match already does.+ # Only a single code named verbatim counts; a description substring is too loose to stand on its own.+ detected = _match_user_defined_error_from_reasoning(task, step, failure_reason, codes_only=True)+ return detectedasync def _detect_errors_from_page(diff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.pyindex 04bcd2fa2..220ccb855 100644--- a/skyvern/services/otp_service.py+++ b/skyvern/services/otp_service.py@@ -872,7 +872,7 @@ def has_otp_source(return Truehas_polling_source = bool((task.totp_verification_url or task.totp_identifier) and task.organization_id)if not has_polling_source:- # This False withholds the v3 code tool entirely, which is otherwise invisible in logs.+ # This False makes the v3 code tool answer that no code source is configured._warn_if_scope_suppresses_legacy_credential(task, expected_otp_type, allowed_credential_parameter_keys)return has_polling_sourcediff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 34493cf9b..612141c36 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -2662,32 +2662,6 @@ class CustomSingleSelectResult:return not await self.skyvern_frame.get_element_visible(self.dropdown_menu.get_locator())-def is_ul_or_listbox_element_factory(- incremental_scraped: IncrementalScrapePage, task: Task, step: Step-) -> Callable[[dict], Awaitable[bool]]:- async def wrapper(element_dict: dict) -> bool:- element_id: str = element_dict.get("id", "")- try:- element = await SkyvernElement.create_from_incremental(incremental_scraped, element_id)- except Exception:- LOG.debug(- "Failed to element in the incremental page",- element_id=element_id,- exc_info=True,- )- return False-- if element.get_tag_name() == "ul":- return True-- if await element.get_attr("role") == "listbox":- return True-- return False-- return wrapper--CheckFilterOutElementIDFunc = Callable[[dict, Page | Frame], Awaitable[bool]]@@ -7489,6 +7463,37 @@ async def _apply_desired_click_state(return None+async def _is_submit_control_for_completion(element: SkyvernElement) -> bool:+ if skyvern_context.current() is None:+ return False+ try:+ return await app.AGENT_FUNCTION.is_submit_control_for_completion(element)+ except Exception:+ LOG.debug("Submit-control detection failed before click", element_id=element.get_id(), exc_info=True)+ return False+++def _record_submit_click_evidence(action: actions.Action, task: Task, step: Step) -> None:+ context = skyvern_context.current()+ if context is None:+ return+ action_order = action.action_order+ if action_order is None:+ action_order = len(step.output.actions_and_results or []) if step.output is not None else 0+ context.submit_click_evidence[task.task_id] = (+ datetime.now(UTC),+ step.order,+ step.retry_index,+ action_order,+ )+ LOG.info(+ "Submit-control click recorded for completion evidence",+ task_id=task.task_id,+ step_id=step.step_id,+ action_order=action_order,+ )++@traced(name="skyvern.agent.action.click")async def handle_click_action(action: actions.ClickAction,@@ -7532,6 +7537,22 @@ async def handle_click_action(if skyvern_element := await dom.safe_get_skyvern_element_by_id(element_id):if await skyvern_element.navigate_to_a_href(page=page):return [ActionSuccess()]+ submit_control = await _is_submit_control_for_completion(skyvern_element)+ if submit_control:+ try:+ # A dispatched coordinate click on a disabled button is not submit evidence.+ submit_control = await skyvern_element.get_locator().is_enabled()+ except Exception:+ LOG.debug(+ "Submit-control enabled-state lookup failed before coordinate click",+ element_id=skyvern_element.get_id(),+ exc_info=True,+ )+ submit_control = False+ else:+ submit_control = False+ else:+ submit_control = Falseawait EventStrategyFactory.move_cursor(page, action.x, action.y)if action.repeat == 1:@@ -7543,6 +7564,9 @@ async def handle_click_action(else:raise ValueError(f"Invalid repeat value: {action.repeat}")+ if submit_control:+ _record_submit_click_evidence(action, task, step)+return [ActionSuccess()]action_phase.mark_action_phase(ActionPhase.RESOLVE_ELEMENT)@@ -7664,7 +7688,10 @@ async def handle_click_action()if action.download:+ submit_control = await _is_submit_control_for_completion(skyvern_element)results = await handle_click_to_download_file_action(action, page, scraped_page, task, step)+ if results and results[-1].success and submit_control:+ _record_submit_click_evidence(action, task, step)elif action.file_url:upload_file_action = UploadFileAction(@@ -7676,6 +7703,7 @@ async def handle_click_action(preflight_derived_action(upload_file_action, page, parent=action, site="click_to_upload")return await handle_upload_file_action(upload_file_action, page, scraped_page, task, step)else:+ submit_control = await _is_submit_control_for_completion(skyvern_element)incremental_scraped: IncrementalScrapePage | None = None# Inside a file-download block, a non-download click authorized as a false-click candidate can# still mint the file. If it does, the post-click dropdown/custom-select rescrape below is dead@@ -7715,6 +7743,8 @@ async def handle_click_action(incremental_scraped=incremental_scraped,skyvern_frame=skyvern_frame,)+ if results and results[-1].success and submit_control:+ _record_submit_click_evidence(action, task, step)action_phase.mark_action_phase(ActionPhase.POST_CLICK)if page.url != original_url:return results@@ -15362,8 +15392,6 @@ async def select_from_dropdown(potential_scrollable_element = await try_to_find_potential_scrollable_element(skyvern_element=dropdown_menu_element,incremental_scraped=incremental_scraped,- step=step,- task=task,)if await skyvern_frame.get_element_scrollable(await potential_scrollable_element.get_element_handler()):@@ -15708,8 +15736,6 @@ async def select_from_dropdown_by_value(potential_scrollable_element = await try_to_find_potential_scrollable_element(skyvern_element=dropdown_menu_element,incremental_scraped=incremental_scraped,- task=task,- step=step,)if not await skyvern_frame.get_element_scrollable(await potential_scrollable_element.get_element_handler()):return _no_element_matched_failure(@@ -15825,8 +15851,8 @@ async def locate_dropdown_menu()continue- ul_or_listbox_element_id = await head_element.find_children_element_id_by_callback(- cb=is_ul_or_listbox_element_factory(incremental_scraped=incremental_scraped, task=task, step=step),+ ul_or_listbox_element_id = await incremental_scraped.find_option_list_element_id(+ head_element.get_element_dict())if ul_or_listbox_element_id:@@ -15898,17 +15924,13 @@ async def locate_dropdown_menu(async def try_to_find_potential_scrollable_element(skyvern_element: SkyvernElement,incremental_scraped: IncrementalScrapePage,- task: Task,- step: Step,) -> SkyvernElement:"""check any <ul> or <role="listbox"> element in the chidlren.if yes, return the found element,else, return the orginal one"""- found_element_id = await skyvern_element.find_children_element_id_by_callback(- cb=is_ul_or_listbox_element_factory(incremental_scraped=incremental_scraped, task=task, step=step),- )+ found_element_id = await incremental_scraped.find_option_list_element_id(skyvern_element.get_element_dict())if found_element_id and found_element_id != skyvern_element.get_id():LOG.debug("Found 'ul or listbox' element in children list",@@ -16951,7 +16973,9 @@ async def _get_input_or_select_context(return input_or_select_context-def _match_user_defined_error_from_reasoning(task: Task, step: Step, reasoning: str) -> list[UserDefinedError]:+def _match_user_defined_error_from_reasoning(+ task: Task, step: Step, reasoning: str, codes_only: bool = False+) -> list[UserDefinedError]:# If the LLM returns no structured errors but its terminate reasoning# explicitly mentions a configured code or description, preserve that# machine-readable code for task/run/webhook error aggregation.@@ -16963,7 +16987,9 @@ def _match_user_defined_error_from_reasoning(task: Task, step: Step, reasoning:code_matches = ("_" in error_code and re.search(rf"\b{re.escape(error_code.lower())}\b", normalized_reasoning) is not None)- description_matches = isinstance(error_description, str) and error_description.lower() in normalized_reasoning+ description_matches = (+ not codes_only and isinstance(error_description, str) and error_description.lower() in normalized_reasoning+ )if code_matches or description_matches:matched_errors.append(UserDefinedError(@@ -16972,6 +16998,9 @@ def _match_user_defined_error_from_reasoning(task: Task, step: Step, reasoning:confidence_float=1.0,))+ if codes_only and len(matched_errors) > 1:+ # Naming several codes is weighing them, not concluding one.+ return []if matched_errors:if len(matched_errors) > 1:LOG.warning(diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.pyindex 9503e3628..c0b765561 100644--- a/skyvern/webeye/scraper/scraper.py+++ b/skyvern/webeye/scraper/scraper.py@@ -60,6 +60,34 @@ if TYPE_CHECKING:LOG = structlog.get_logger()MAX_LOGGED_FRAME_COLLISION_PAIRS = 10+# Reads every stamped element's live tag name, role and match count in one pass, open shadow roots+# included, so a caller can resolve a whole subtree without a round trip per element.+LIVE_ELEMENT_PROBE_JS = """(attrName) => {+ // Element ids come from page attributes and can collide with Object.prototype keys.+ const probes = Object.create(null);+ const pending = [document.documentElement];+ while (pending.length) {+ const node = pending.pop();+ if (!node) continue;+ const elementId = node.getAttribute ? node.getAttribute(attrName) : null;+ if (elementId) {+ const probe = probes[elementId];+ if (probe === undefined) {+ probes[elementId] = {+ count: 1,+ tagName: node.tagName ? node.tagName.toLowerCase() : "",+ role: node.getAttribute("role"),+ };+ } else {+ probe.count += 1;+ }+ }+ for (const child of node.children || []) pending.push(child);+ if (node.shadowRoot) pending.push(node.shadowRoot);+ }+ return probes;+}"""+async def build_scraping_failed_reason(browser_state: BrowserState, requested_url: str, *, timed_out: bool = False, canvas_app: bool = False@@ -1042,6 +1070,7 @@ class IncrementalScrapePage(ElementTreeBuilder):# native analysis timeout; None (default) preserves the stock Playwright timeout identity.self.engine_selection = engine_selectionself.last_used_element_tree_html: str | None = None+ self._live_element_probes: dict[str, dict] | None = Nonedef set_element_tree_trimmed(self, element_tree_trimmed: list[dict]) -> None:self.element_tree_trimmed = element_tree_trimmed@@ -1077,6 +1106,7 @@ class IncrementalScrapePage(ElementTreeBuilder):self.id_to_css_dict, self.id_to_element_dict, _, _, _ = build_element_dict(incremental_elements)self.elements = incremental_elements+ self._live_element_probes = Noneincremental_tree = await cleanup_element_tree(frame, frame.url, _deepcopy_element_tree(incremental_tree))trimmed_element_tree = trim_element_tree(_deepcopy_element_tree(incremental_tree))@@ -1131,6 +1161,49 @@ class IncrementalScrapePage(ElementTreeBuilder):}"""return await SkyvernFrame.evaluate(frame=self.skyvern_frame.get_frame(), expression=js_script)+ async def _get_live_element_probes(self) -> dict[str, dict]:+ """Live tag name, role and match count of every stamped element in the frame, keyed by element id.++ Read in one pass instead of a locator resolve plus an attribute read per element: an opened+ dropdown menu can hold hundreds of elements, and each round trip to a remote browser costs+ a fraction of a second. Cached until the next incremental scrape replaces the element tree.+ """+ cached = self._live_element_probes+ if cached is not None:+ return cached++ probes: dict[str, dict] = await SkyvernFrame.evaluate(+ frame=self.skyvern_frame.get_frame(), expression=LIVE_ELEMENT_PROBE_JS, arg=SKYVERN_ID_ATTR+ )+ self._live_element_probes = probes+ return probes++ async def find_option_list_element_id(self, root_element: dict) -> str | None:+ """Id of the first <ul> or role="listbox" element in the subtree, the root element included."""+ try:+ probes = await self._get_live_element_probes()+ except Exception:+ # Same outcome the per-element reads had when the page wouldn't answer: no match.+ LOG.debug("Failed to read the live element tree, no option list element found", exc_info=True)+ return None++ queue = [root_element]+ index = 0+ while index < len(queue):+ element = queue[index]+ index += 1+ element_id: str = element.get("id", "")+ probe = probes.get(element_id)+ # An id matching no element, or more than one, is not addressable by its selector.+ if probe is not None and probe.get("count") == 1:+ if element.get("tagName") == "ul":+ return element_id+ # The role may change after the scrape, so use the live probe as authoritative.+ if probe.get("role") == "listbox":+ return element_id+ queue.extend(element.get("children", []))+ return None+async def __validate_element_by_value(self, value: str, element: dict) -> tuple[Locator | None, bool]:"""Locator: the locator of the matched element. None if no valid element to interact;diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.pyindex a69102af2..69ed773a7 100644--- a/skyvern/webeye/utils/dom.py+++ b/skyvern/webeye/utils/dom.py@@ -951,23 +951,6 @@ class SkyvernElement:entries.sort(key=lambda x: len(x[0]), reverse=True)return entries[0][1]- async def find_children_element_id_by_callback(- self, cb: typing.Callable[[dict], typing.Awaitable[bool]]- ) -> str | None:- index = 0- queue = [self.get_element_dict()]- while index < len(queue):- item = queue[index]- if await cb(item):- return item.get("id", "")-- children: list[dict] = item.get("children", [])- for child in children:- queue.append(child)-- index += 1- return None-async def find_label_for(self, dom: DomUtil, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS) -> SkyvernElement | None:diff --git a/tests/unit/conftest.py b/tests/unit/conftest.pyindex 971471a9f..afec2ddf0 100644--- a/tests/unit/conftest.py+++ b/tests/unit/conftest.py@@ -220,6 +220,46 @@ def setup_forge_stub_app():yield+def cancel_leftover_tasks(loop: asyncio.AbstractEventLoop) -> None:+ # A task left suspended in a SQLAlchemy session on a closed loop is later finalized by a garbage collection+ # inside another test's session, which fails that test with GeneratorExit and stops all later collections.+ cancelled: set[asyncio.Task[Any]] = set()+ for _ in range(3):+ leftover = {task for task in asyncio.all_tasks(loop) if not task.done()}+ if not leftover:+ break+ for task in leftover:+ task.cancel()+ cancelled |= leftover+ # Bounded and repeated, as asyncio.run is not: a task that swallows one cancel must not hang teardown.+ loop.run_until_complete(asyncio.wait(leftover, timeout=2))+ for task in cancelled:+ # Reading the exception also marks it retrieved, so the loop handler reports it once.+ if task.done() and not task.cancelled() and task.exception() is not None:+ loop.call_exception_handler(+ {+ "message": "unhandled exception during test loop teardown",+ "exception": task.exception(),+ "task": task,+ }+ )+ for task in asyncio.all_tasks(loop):+ loop.call_exception_handler(+ {"message": "task still pending after cancellation at test loop teardown", "task": task}+ )+++def event_loop() -> Iterator[asyncio.AbstractEventLoop]:+ # pytest-asyncio's default loop closes without cancelling the tasks a test left running.+ loop = asyncio.new_event_loop()+ yield loop+ if not loop.is_closed():+ cancel_leftover_tasks(loop)+ loop.run_until_complete(loop.shutdown_asyncgens())+ loop.close()++@pytest.fixture(autouse=True)def reset_collapse_xp_assignment_memo():# The collapse umbrella memo is process-global by design; without clearing it,diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.pyindex e764a73d3..adc1de17e 100644--- a/tests/unit/force_stub_app.py+++ b/tests/unit/force_stub_app.py@@ -23,7 +23,7 @@ def released_session_stub() -> SimpleNamespace:def version_write_transaction_stub() -> MagicMock:"""The save path's version/definition transaction, for workflow repositories faked without an engine."""- return MagicMock(side_effect=lambda: nullcontext())+ return MagicMock(side_effect=lambda workflow_permanent_id=None: nullcontext())def create_forge_stub_app() -> ForgeApp:diff --git a/tests/unit/services/test_org_auth_optional_user.py b/tests/unit/services/test_org_auth_optional_user.pyindex 662bfe62f..106f8b4bd 100644--- a/tests/unit/services/test_org_auth_optional_user.py+++ b/tests/unit/services/test_org_auth_optional_user.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom skyvern.forge.sdk.services import org_auth_service+from skyvern.forge.sdk.services.request_principal import AuthKind, RequestPrincipal@pytest.mark.asyncio@@ -33,6 +34,18 @@ async def test_returns_none_without_credentials() -> None:assert result is None+async def test_returns_member_id_for_member_bound_api_key_attribution() -> None:+ principal = RequestPrincipal("o_123", AuthKind.member_api_key, "user_member", "org:member")+ with patch("skyvern.forge.sdk.services.org_auth_service.get_request_principal", return_value=principal):+ result = await org_auth_service.get_current_user_id_or_none(+ authorization=None,+ x_api_key="member-api-key",+ x_user_agent=None,+ )+ assert result == "user_member"++@pytest.mark.asyncioasync def test_returns_none_for_invalid_bearer() -> None:with patch("skyvern.forge.sdk.services.org_auth_service.app") as mock_app:diff --git a/tests/unit/test_agent_protocol_idempotency.py b/tests/unit/test_agent_protocol_idempotency.pyindex 78b31facd..d18691a67 100644--- a/tests/unit/test_agent_protocol_idempotency.py+++ b/tests/unit/test_agent_protocol_idempotency.py@@ -813,9 +813,9 @@ async def test_nonterminal_finally_validation_rolls_back_before_version_commit(original_validate = WorkflowDefinition.validate@asynccontextmanager- async def track_version_write_transaction() -> AsyncIterator[None]:+ async def track_version_write_transaction(workflow_permanent_id: str | None = None) -> AsyncIterator[None]:nonlocal transaction_open- async with original_version_write_transaction():+ async with original_version_write_transaction(workflow_permanent_id):transaction_open = Truetry:yielddiff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex 383c8d0d6..13a94637c 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -22,12 +22,13 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom structlog.testing import capture_logs-from skyvern.config import settings+from skyvern.config import Settings, settingsfrom skyvern.errors.errors import UserDefinedErrorfrom skyvern.exceptions import CompletionGateTerminationError, MissingBrowserStatePage, StepTerminationErrorfrom skyvern.forge import agent as agent_modulefrom skyvern.forge import appfrom skyvern.forge.agent import ForgeAgent+from skyvern.forge.agent_functions import AgentFunctionfrom skyvern.forge.sdk.artifact.manager import ArtifactManagerfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import EnrichTreeMode, SkyvernContext@@ -82,16 +83,18 @@ from skyvern.forge.taskv3.loop import (NAV_DEAD_END_GUARD,LoopOutcome,RoundAction,+ ToolResult,ToolSpec,_dead_end_reason,make_finish_tool,+ run_agent_tool_loop,)from skyvern.forge.taskv3.run_arms import (DATE_SEGMENT_AIM_FLAG,LOGIN_PACE_FLAG,run_arm_enabled,)-from skyvern.forge.taskv3.tools import PageProvider, _record_frame_work+from skyvern.forge.taskv3.tools import NO_ONE_TIME_CODE_SOURCE, PageProvider, _record_frame_workfrom skyvern.schemas.llm import LLMConfigfrom skyvern.schemas.runs import RunEnginefrom skyvern.schemas.workflows import BlockType@@ -124,6 +127,7 @@ from tests.unit.helpers import (make_task,)from tests.unit.scoped_asyncio import ScopedAsyncio+from tests.unit.test_taskv3_loop import _ScriptedCallerasync def _run_execute_task_v3(@@ -4440,96 +4444,104 @@ async def test_execute_task_v3_detects_user_defined_errors_on_failure(@pytest.mark.asyncio[email protected]("finish_status", [TaskStatus.failed, TaskStatus.terminated])- "scenario",- [- "no_code_delivered",- "code_delivered",- "code_tool_offered",- "source_failed",- "credential_seed_missing",- "credential_seed_invalid",- "credential_seed_valid",- ],-)-async def test_execute_task_v3_attributes_a_run_whose_credential_had_no_usable_totp_source(- monkeypatch: pytest.MonkeyPatch, finish_status: TaskStatus, scenario: str-) -> None:- # The model narrates the symptom -- a rejected sign-in -- which classifies as the customer's- # credentials failing. When the run was refused a one-time code because its credential has no usable- # TOTP source and never got one, the run carries the same typed error the step engine records, and- # a reason that names the missing source instead. Like the step engine's error, it means NO code- # source at all: a run offered a polling source, or whose source failed, is not attributed. A code- # tool offered only for a credential whose TOTP seed is missing or invalid is not a source.- credential_seed = {- "credential_seed_missing": None,- "credential_seed_invalid": "not a totp secret!",- "credential_seed_valid": "JBSWY3DPEHPK3PXP",- }- uses_credential = scenario in credential_seed- run_overrides: dict[str, Any] = {}- task_block = _make_block(NavigationBlock, navigation_goal="Sign in")- if uses_credential:- run_context = _stub_recovery_run_context(monkeypatch, tested_url=None)- run_context.parameters["portal_credential"] = _make_credential_parameter("portal_credential")- run_context.values["portal_credential"]["totp"] = "placeholder_Zz9_totp"- run_context.secrets["placeholder_Zz9_totp"] = "BW_TOTP"- if credential_seed[scenario] is not None:- run_context.secrets[run_context.totp_secret_value_key("placeholder_Zz9_totp")] = credential_seed[scenario]- task_block = _make_block(- NavigationBlock, navigation_goal="Sign in", parameters=[_make_credential_parameter("portal_credential")]- )- run_overrides = {"workflow_run_id": "wr_test", "real_credential_totp_candidate": True}[email protected]("finish_status", [TaskStatus.failed, TaskStatus.terminated, TaskStatus.completed])[email protected]("last_status", ["no_source", "source_error", "none"])+async def test_execute_task_v3_reports_the_last_code_tool_status_as_the_failure_reason(+ monkeypatch: pytest.MonkeyPatch, finish_status: TaskStatus, last_status: str+) -> None:+ # A failed run keeps the model's reason and carries the last status the code tool reported. Only the no-source+ # status carries the step engine's typed MISSING_TOTP_SOURCE error, and a completed run carries neither.+ status_text = {+ "no_source": NO_ONE_TIME_CODE_SOURCE,+ "source_error": "the verification code source returned an error (lookup failed); no polling time remains.",+ "none": None,+ }[last_status]errors_update = AsyncMock()monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)seen: dict[str, Any] = {}- def _refused_a_code(kwargs: dict[str, Any]) -> None:+ def _reported(kwargs: dict[str, Any]) -> None:state = kwargs["verification_blocker"].__self__- seen["state"] = state- seen["resolver"] = kwargs["resolve_totp_placeholder"]seen["tools"] = kwargs["extra_tools"]- state.totp_source_missing = True- if scenario == "code_delivered":- state.values_delivered = 1- if scenario == "source_failed":- state.arm(VerificationFailure.BUDGET_EXHAUSTED, "get_verification_code")+ seen["resolver"] = kwargs["resolve_totp_placeholder"]+ seen["state"] = state+ state.last_status = status_textmodel_reason = "Login failed: the MFA code was rejected"- outcome = LoopOutcome(status=finish_status.value, reason=model_reason, billable_actions=[])- _step, task, loop_mock, _post = await _run_execute_task_v3(+ _step, task, _loop_mock, _post = await _run_execute_task_v3(monkeypatch,- outcome,- task_block=task_block,- on_loop=_refused_a_code,+ LoopOutcome(status=finish_status.value, reason=model_reason, billable_actions=[]),+ task_block=_make_block(NavigationBlock, navigation_goal="Sign in"),+ on_loop=_reported,data_extraction_goal=None,extracted_information_schema=None,- totp_identifier="[email protected]" if scenario == "code_tool_offered" else None,- **run_overrides,)state = seen["state"]- assert state.code_tool_offered is (scenario in ("code_tool_offered", "credential_seed_valid"))- if uses_credential:- # The tool stays offered to the model either way; only the attribution input changes.- offered = [tool.name for tool in seen["tools"]]- assert "get_verification_code" in offered+ assert "get_verification_code" in [tool.name for tool in seen["tools"]]assert seen["resolver"] == state.resolve_totp_placeholderassert state.totp_min_remaining_seconds == settings.TOTP_MULTI_FIELD_MIN_REMAINING_SECONDSwritten = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]assert task.status == finish_status- category = loop_mock.update_task_kwargs.get("failure_category") or []- if scenario not in ("no_code_delivered", "credential_seed_missing", "credential_seed_invalid"):- assert written == []- assert task.failure_reason == model_reason+ if finish_status == TaskStatus.completed:+ assert task.failure_reason is None and written == []return- assert [error["error_code"] for error in written] == ["MISSING_TOTP_SOURCE"]- reason = (task.failure_reason or "").lower()- assert "one-time code" in reason and "totp" in reason- assert not any(word in reason for word in ("mfa", "password", "login fail", "authentication fail", "auth fail"))- assert all(entry["category"] not in ("AUTH_FAILURE", "CREDENTIAL_ERROR") for entry in category)- if finish_status == TaskStatus.failed:- assert category+ assert task.failure_reason is not None and model_reason in task.failure_reason+ assert status_text in task.failure_reason if status_text else task.failure_reason == model_reason+ assert [error["error_code"] for error in written] == (["MISSING_TOTP_SOURCE"] if last_status == "no_source" else [])++[email protected]("clicked_after", [True, False], ids=["page_action_after_status", "status_last"])+async def test_execute_task_v3_a_code_status_the_model_acted_past_is_not_the_failure_reason(+ monkeypatch: pytest.MonkeyPatch, clicked_after: bool+) -> None:+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ model_reason = "the portal rejected the sign-in"+ seen: dict[str, Any] = {}++ async def _click(_args: dict[str, Any]) -> ToolResult:+ return ToolResult.ok("clicked")++ async def _real_loop(kwargs: dict[str, Any]) -> None:+ click = ToolSpec(name="click", description="click", parameters={}, handler=_click, billable=True)+ script = [[("get_verification_code", {})]]+ if clicked_after:+ script.append([("click", {"selector": "#skip"})])+ script.append([("finish", {"status": "failed", "reason": model_reason})])+ seen["outcome"] = await run_agent_tool_loop(+ llm_caller=_ScriptedCaller(script),+ system_prompt="sys",+ user_prompt="goal",+ tools=kwargs["extra_tools"] + [click, make_finish_tool()],+ max_turns=10,+ max_tool_calls=20,+ on_page_action=kwargs["on_page_action"],+ )++ _step, task, _loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ LoopOutcome(status="failed", reason=model_reason, billable_actions=[]),+ task_block=_make_block(NavigationBlock, navigation_goal="Sign in"),+ on_loop_async=_real_loop,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ code_answers = [+ m["content"]+ for m in seen["outcome"].messages+ if m.get("role") == "tool" and m.get("name") == "get_verification_code"+ ]+ assert code_answers == [NO_ONE_TIME_CODE_SOURCE]+ assert (seen["outcome"].status, seen["outcome"].reason) == ("failed", model_reason)+ written = [+ error["error_code"] for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []+ ]+ if clicked_after:+ assert task.failure_reason == model_reason and "MISSING_TOTP_SOURCE" not in written+ else:+ assert task.failure_reason is not None and model_reason in task.failure_reason+ assert NO_ONE_TIME_CODE_SOURCE in task.failure_reason and written == ["MISSING_TOTP_SOURCE"]@pytest.mark.asyncio@@ -4541,7 +4553,7 @@ async def test_execute_task_v3_a_vetoed_completion_is_not_attributed_to_a_missinmonkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)def _refused_a_code(kwargs: dict[str, Any]) -> None:- kwargs["verification_blocker"].__self__.totp_source_missing = True+ kwargs["verification_blocker"].__self__.last_status = NO_ONE_TIME_CODE_SOURCE_step, task, _loop_mock, _post = await _run_execute_task_v3(monkeypatch,@@ -4559,11 +4571,76 @@ async def test_execute_task_v3_a_vetoed_completion_is_not_attributed_to_a_missin@pytest.mark.asyncio-async def test_execute_task_v3_keeps_the_codes_out_of_the_loop_and_the_goal(+ "outcome",+ [+ LoopOutcome(status="loop_error", reason="llm_call_failed: TimeoutError: slow", billable_actions=[]),+ LoopOutcome(status="budget_exhausted", reason="the run reached its turn limit", billable_actions=[]),+ LoopOutcome(status="terminated", reason="the page stopped responding", guard=ACTION_LOOP_GUARD),+ ],+ ids=["loop_error", "budget_exhausted", "loop_guard"],+)+async def test_execute_task_v3_a_run_the_loop_ended_keeps_its_own_reason_over_a_code_status(+ monkeypatch: pytest.MonkeyPatch, outcome: LoopOutcome+) -> None:+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)++ def _no_source(kwargs: dict[str, Any]) -> None:+ kwargs["verification_blocker"].__self__.last_status = NO_ONE_TIME_CODE_SOURCE++ _step, task, _loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=_make_block(NavigationBlock, navigation_goal="Sign in"),+ on_loop=_no_source,+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ assert task.failure_reason and NO_ONE_TIME_CODE_SOURCE not in task.failure_reason+ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert all(error["error_code"] != "MISSING_TOTP_SOURCE" for error in written)++[email protected]("gate_runs", ["in_loop", "after_loop"])+async def test_execute_task_v3_a_completion_gate_termination_keeps_the_gates_reason_over_a_code_status(+ monkeypatch: pytest.MonkeyPatch, gate_runs: str+) -> None:+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ gate_reason = "the application was already submitted"++ async def _claims_completion(kwargs: dict[str, Any]) -> None:+ kwargs["verification_blocker"].__self__.last_status = NO_ONE_TIME_CODE_SOURCE+ if gate_runs == "in_loop":+ with pytest.raises(CompletionGateTerminationError):+ await kwargs["completion_gate"]()++ outcome = (+ LoopOutcome(status="terminated", reason=gate_reason, billable_actions=[])+ if gate_runs == "in_loop"+ else LoopOutcome(status="completed", reason="signed in", billable_actions=[])+ )+ _step, task, _loop_mock, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ task_block=_make_block(NavigationBlock, navigation_goal="Sign in"),+ on_loop_async=_claims_completion,+ completion_gate_raises=CompletionGateTerminationError(gate_reason),+ data_extraction_goal=None,+ extracted_information_schema=None,+ )+ assert task.status == TaskStatus.terminated+ assert task.failure_reason == gate_reason+ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert all(error["error_code"] != "MISSING_TOTP_SOURCE" for error in written)+++async def test_execute_task_v3_gives_the_codes_to_the_finish_tool_not_the_goal(monkeypatch: pytest.MonkeyPatch,) -> None:- # v3 never shows the model the customer's codes: they reach neither the loop nor the goal, and- # the detector after the loop is what assigns one.mapping = {"COVERAGE_NOT_ACTIVE": "The member has no active plan today."}outcome = LoopOutcome(status="completed", reason="ok", billable_actions=[])block = _make_block(NavigationBlock, navigation_goal="Go", error_code_mapping=mapping)@@ -4575,18 +4652,249 @@ async def test_execute_task_v3_keeps_the_codes_out_of_the_loop_and_the_goal(data_extraction_goal=None,extracted_information_schema=None,)- assert "error_code_mapping" not in loop_mock.await_args.kwargs+ assert loop_mock.await_args.kwargs["error_code_mapping"] == mappingassert "COVERAGE_NOT_ACTIVE" not in loop_mock.await_args.kwargs["goal"]assert "The member has no active plan today." not in loop_mock.await_args.kwargs["goal"]+ ("outcome", "persisted_code", "detector_runs", "vetoed"),+ [+ (+ LoopOutcome(status="failed", reason="password rejected", error_code="COVERAGE_NOT_ACTIVE"),+ "COVERAGE_NOT_ACTIVE",+ False,+ False,+ ),+ (LoopOutcome(status="terminated", reason="no such member", error_code_declined=True), None, False, False),+ (LoopOutcome(status="failed", reason="step budget used up"), "DETECTED", True, False),+ (LoopOutcome(status="budget_exhausted", reason="max_turns (40) reached"), "DETECTED", True, False),+ # A code must never make a successful run carry errors: consumers read errors as "did not succeed".+ (LoopOutcome(status="completed", reason="done", error_code="COVERAGE_NOT_ACTIVE"), None, False, False),+ # A conversion that stood, then failed for its missing extraction: the code answered a verdict that did not stand.+ (+ LoopOutcome(+ status="completed",+ reason="the site skipped a screen",+ converted_from="failed",+ converted_from_reason="password rejected",+ error_code="COVERAGE_NOT_ACTIVE",+ ),+ "DETECTED",+ True,+ False,+ ),+ # A completion vetoed after the loop was never asked for a code, so the page guess decides.+ (LoopOutcome(status="completed", reason="done"), "DETECTED", True, True),+ # A vetoed re-ask conversion restores the model's failed verdict, and with it the code it chose.+ (+ LoopOutcome(+ status="completed",+ reason="the site skipped a screen",+ converted_from="failed",+ converted_from_reason="password rejected",+ error_code="COVERAGE_NOT_ACTIVE",+ ),+ "COVERAGE_NOT_ACTIVE",+ False,+ True,+ ),+ ],+)+async def test_execute_task_v3_the_models_finish_answer_replaces_the_page_guess(+ monkeypatch: pytest.MonkeyPatch, outcome: LoopOutcome, persisted_code: str | None, detector_runs: bool, vetoed: bool+) -> None:+ monkeypatch.setattr(+ "skyvern.forge.agent.app.AGENT_FUNCTION.task_v3_error_code_on_finish", AsyncMock(return_value=True)+ )+ detect_mock = AsyncMock(+ return_value=[UserDefinedError(error_code="DETECTED", reasoning="page guess", confidence_float=0.5)]+ )+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ mapping = {"COVERAGE_NOT_ACTIVE": "x", "DETECTED": "y"}+ _step, task, _loop, _post = await _run_execute_task_v3(+ monkeypatch,+ outcome,+ error_code_mapping=mapping,+ data_extraction_goal="Extract the member id" if persisted_code == "DETECTED" and not vetoed else None,+ extracted_information_schema=None,+ completion_gate_vetoes=vetoed,+ )++ assert detect_mock.await_count == (1 if detector_runs else 0)+ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert [error["error_code"] for error in written] == ([persisted_code] if persisted_code else [])+ if persisted_code == "COVERAGE_NOT_ACTIVE":+ assert written[0]["reasoning"] == (outcome.converted_from_reason or outcome.reason)+++async def test_execute_task_v3_a_missing_code_source_and_the_models_code_are_both_stored(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "skyvern.forge.agent.app.AGENT_FUNCTION.task_v3_error_code_on_finish", AsyncMock(return_value=True)+ )+ detect_mock = AsyncMock(return_value=[])+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)++ def _no_source(kwargs: dict[str, Any]) -> None:+ kwargs["verification_blocker"].__self__.last_status = NO_ONE_TIME_CODE_SOURCE++ await _run_execute_task_v3(+ monkeypatch,+ LoopOutcome(status="terminated", reason="no code was delivered", error_code="COVERAGE_NOT_ACTIVE"),+ task_block=_make_block(NavigationBlock, navigation_goal="Sign in"),+ on_loop=_no_source,+ error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},+ data_extraction_goal=None,+ extracted_information_schema=None,+ )++ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert [error["error_code"] for error in written] == ["MISSING_TOTP_SOURCE", "COVERAGE_NOT_ACTIVE"]+ assert detect_mock.await_count == 0+++async def test_execute_task_v3_a_conversion_a_deployment_gate_terminates_goes_to_the_detector(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ detect_mock = AsyncMock(+ return_value=[UserDefinedError(error_code="DETECTED", reasoning="page guess", confidence_float=0.5)]+ )+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ outcome = LoopOutcome(+ status="completed",+ reason="the site skipped a screen",+ converted_from="failed",+ converted_from_reason="password rejected",+ error_code="COVERAGE_NOT_ACTIVE",+ )+ await _run_execute_task_v3(+ monkeypatch,+ outcome,+ error_code_mapping={"COVERAGE_NOT_ACTIVE": "x", "DETECTED": "y"},+ data_extraction_goal=None,+ extracted_information_schema=None,+ completion_gate_raises=CompletionGateTerminationError("already applied to this job"),+ )++ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert [error["error_code"] for error in written] == ["DETECTED"]++[email protected]("enabled", [False, True])+async def test_the_open_source_gate_follows_its_setting_and_is_off_by_default(+ monkeypatch: pytest.MonkeyPatch, enabled: bool+) -> None:+ assert Settings.model_fields["TASK_V3_ERROR_CODE_ON_FINISH"].default is False+ monkeypatch.setattr(settings, "TASK_V3_ERROR_CODE_ON_FINISH", enabled)+ assert await AgentFunction().task_v3_error_code_on_finish(organization_id="org-1") is enabled+++async def test_execute_task_v3_gate_off_stores_the_page_guess_and_logs_both_codes(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ "skyvern.forge.agent.app.AGENT_FUNCTION.task_v3_error_code_on_finish", AsyncMock(return_value=False)+ )+ detect_mock = AsyncMock(+ return_value=[UserDefinedError(error_code="DETECTED", reasoning="page guess", confidence_float=0.5)]+ )+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ outcome = LoopOutcome(status="terminated", reason="password rejected", error_code="COVERAGE_NOT_ACTIVE")+ with capture_logs() as logs:+ await _run_execute_task_v3(+ monkeypatch, outcome, error_code_mapping={"COVERAGE_NOT_ACTIVE": "x", "DETECTED": "y"}+ )++ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert [error["error_code"] for error in written] == ["DETECTED"]+ (line,) = (log for log in logs if log["event"] == "task_v3 user-defined error code sources")+ assert (line["model_error_code"], line["detector_error_codes"]) == ("COVERAGE_NOT_ACTIVE", ["DETECTED"])+ assert line["reached_finish"] is True and line["model_answer_used"] is False+++async def test_execute_task_v3_a_gate_error_falls_back_to_the_page_guess(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "skyvern.forge.agent.app.AGENT_FUNCTION.task_v3_error_code_on_finish",+ AsyncMock(side_effect=RuntimeError("flag service down")),+ )+ detect_mock = AsyncMock(+ return_value=[UserDefinedError(error_code="DETECTED", reasoning="page guess", confidence_float=0.5)]+ )+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)+ errors_update = AsyncMock()+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", errors_update)+ outcome = LoopOutcome(status="failed", reason="password rejected", error_code="COVERAGE_NOT_ACTIVE")+ await _run_execute_task_v3(monkeypatch, outcome, error_code_mapping={"COVERAGE_NOT_ACTIVE": "x", "DETECTED": "y"})++ written = [error for call in errors_update.await_args_list for error in call.kwargs.get("errors") or []]+ assert [error["error_code"] for error in written] == ["DETECTED"]+++async def test_execute_task_v3_a_gate_demoted_completion_is_not_logged_as_a_model_answer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ gate = AsyncMock(return_value=True)+ monkeypatch.setattr("skyvern.forge.agent.app.AGENT_FUNCTION.task_v3_error_code_on_finish", gate)+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", AsyncMock(return_value=[]))+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", AsyncMock())+ outcome = LoopOutcome(status="completed", reason="done")+ with capture_logs() as logs:+ await _run_execute_task_v3(+ monkeypatch,+ outcome,+ error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"},+ data_extraction_goal=None,+ extracted_information_schema=None,+ completion_gate_raises=CompletionGateTerminationError("already applied to this job"),+ )++ gate.assert_not_awaited()+ (line,) = (log for log in logs if log["event"] == "task_v3 user-defined error code sources")+ assert line["model_verdict"] == "completed" and line["model_answer_used"] is False+++async def test_execute_task_v3_a_completion_the_gate_ended_inside_the_loop_logs_the_models_verdict(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", AsyncMock(return_value=[]))+ monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.tasks.update_task", AsyncMock())+ outcome = LoopOutcome(status="terminated", reason="already applied", model_status="completed")+ with capture_logs() as logs:+ await _run_execute_task_v3(monkeypatch, outcome, error_code_mapping={"COVERAGE_NOT_ACTIVE": "x"})++ (line,) = (log for log in logs if log["event"] == "task_v3 user-defined error code sources")+ assert line["model_verdict"] == "completed"++@pytest.mark.asyncioasync def test_execute_task_v3_vetoed_completion_still_reaches_the_detector(monkeypatch: pytest.MonkeyPatch,) -> None:# A completion the gate vetoes is demoted to failed, and the detector runs on the demoted status,# not on the model's own "completed".- detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]+ detected = [+ SimpleNamespace(+ model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, error_code="COVERAGE_NOT_ACTIVE", reasoning=""+ )+ ]detect_mock = AsyncMock(return_value=detected)monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)errors_update = AsyncMock()@@ -4807,7 +5115,11 @@ async def test_execute_task_v3_leaves_unasked_failures_to_the_detector() -> None:# The scope guard: a failed v3 run on a task with a mapping hands the code to the detector,# exactly as v1's fail_task does.- detected = [SimpleNamespace(model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, reasoning="")]+ detected = [+ SimpleNamespace(+ model_dump=lambda: {"error_code": "COVERAGE_NOT_ACTIVE"}, error_code="COVERAGE_NOT_ACTIVE", reasoning=""+ )+ ]detect_mock = AsyncMock(return_value=detected)monkeypatch.setattr("skyvern.forge.agent.detect_user_defined_errors_for_task", detect_mock)errors_update = AsyncMock()@@ -4866,8 +5178,6 @@ async def test_execute_task_v3_router_selected_data_only_validation_goes_page_frasync def test_execute_task_v3_hands_the_loop_the_live_verification_gate(monkeypatch: pytest.MonkeyPatch) -> None:# The finish gate the loop receives must be the same VerificationState the auth tools mutate;# a fresh or detached state would let a refused source false-complete despite the blocker.- from skyvern.forge.taskv3.auth_tools import VerificationFailure-seen_states: list[Any] = []def capturing_build(@@ -4885,7 +5195,7 @@ async def test_execute_task_v3_hands_the_loop_the_live_verification_gate(monkeypassert blocker is not Noneassert len(seen_states) == 1 and blocker.__self__ is seen_states[0]assert await blocker("completed") is None- seen_states[0].arm(VerificationFailure.NO_CODE_TWICE, "get_verification_code")+ seen_states[0].arm(VerificationFailure.LINK_REFUSED, "open_verification_link")assert await blocker("completed") is not Nonediff --git a/tests/unit/test_api_handler_cached_content_fix.py b/tests/unit/test_api_handler_cached_content_fix.pyindex b1fa5b8a6..87f760668 100644--- a/tests/unit/test_api_handler_cached_content_fix.py+++ b/tests/unit/test_api_handler_cached_content_fix.py@@ -17,7 +17,7 @@ forge_module.app.EXPERIMENTATION_PROVIDER = MagicMock()@pytest.mark.asyncioasync def test_cached_content_removed_from_non_extract_prompts() -> None:mock_config = MagicMock(spec=LLMConfig)- mock_config.model_name = "gemini-2.5-pro"+ mock_config.model_name = "gemini-3.1-pro-preview"mock_config.litellm_params = {}mock_config.supports_vision = Falsemock_config.add_assistant_prefix = False@@ -62,7 +62,7 @@ async def test_cached_content_removed_from_non_extract_prompts() -> None:mock_builder.return_value = [{"role": "user", "content": "test"}]mock_acompletion.return_value = mock_response- handler = LLMAPIHandlerFactory.get_llm_api_handler("gemini-2.5-pro")+ handler = LLMAPIHandlerFactory.get_llm_api_handler("gemini-3.1-pro-preview")context = SkyvernContext()context.cached_static_prompt = "some static prompt"diff --git a/tests/unit/test_api_handler_factory.py b/tests/unit/test_api_handler_factory.pyindex 189e53264..09b155247 100644--- a/tests/unit/test_api_handler_factory.py+++ b/tests/unit/test_api_handler_factory.py@@ -1342,7 +1342,7 @@ def test_uses_only_anthropic_models_rejects_openai_claude_proxy() -> None:def test_normalize_llm_model_strips_provider_prefix() -> None:"""LiteLLM returns model names with provider prefixes; dbt expects the bare name."""- assert api_handler_factory._normalize_llm_model("vertex_ai/gemini-2.5-flash") == "gemini-2.5-flash"+ assert api_handler_factory._normalize_llm_model("vertex_ai/gemini-3-flash-preview") == "gemini-3-flash-preview"assert api_handler_factory._normalize_llm_model("openai/gpt-4.1-mini") == "gpt-4.1-mini"assert api_handler_factory._normalize_llm_model("gpt-4") == "gpt-4"assert api_handler_factory._normalize_llm_model(None) is None@@ -1436,7 +1436,7 @@ async def test_handler_persists_response_model_not_router_group(monkeypatch: pytcontext.task_id = Nonellm_config = LLMConfig(- model_name="GEMINI_2_5_FLASH_WITH_FALLBACK", # router group name, not what response.model returns+ model_name="TEST_GEMINI_ROUTER_GROUP", # router group name, not what response.model returnsrequired_env_vars=[],supports_vision=True,add_assistant_prefix=False,@@ -1456,7 +1456,7 @@ async def test_handler_persists_response_model_not_router_group(monkeypatch: pyt# LiteLLM returns the actual backing model with its provider prefixasync def mock_acompletion(*args, **kwargs):- return FakeLLMResponse("vertex_ai/gemini-2.5-flash")+ return FakeLLMResponse("vertex_ai/gemini-3-flash-preview")monkeypatch.setattr(api_handler_factory.litellm, "acompletion", AsyncMock(side_effect=mock_acompletion))@@ -1488,17 +1488,17 @@ async def test_handler_persists_response_model_not_router_group(monkeypatch: pytorganization_id="org_test",)- handler = LLMAPIHandlerFactory.get_llm_api_handler("GEMINI_2_5_FLASH_WITH_FALLBACK")+ handler = LLMAPIHandlerFactory.get_llm_api_handler("TEST_GEMINI_ROUTER_GROUP")await handler(prompt="test prompt", prompt_name=EXTRACT_ACTION_PROMPT_NAME, step=step)# The persisted model should be the bare response.model, not the router group key- assert captured_kwargs.get("last_llm_model") == "gemini-2.5-flash"+ assert captured_kwargs.get("last_llm_model") == "gemini-3-flash-preview"@pytest.mark.asyncioasync def test_single_handler_maps_an_unparseable_body_to_retryable(monkeypatch: pytest.MonkeyPatch) -> None:llm_config = LLMConfig(- model_name="vertex_ai/gemini-2.5-flash",+ model_name="vertex_ai/gemini-3-flash-preview",required_env_vars=[],supports_vision=False,add_assistant_prefix=False,@@ -1771,23 +1771,6 @@ def _gemini_3_flash_router() -> LLMRouterConfig:)-def _gemini_2_5_flash_router() -> LLMRouterConfig:- return LLMRouterConfig(- model_name="gemini-2.5-flash-gpt-5-mini-fallback-router",- required_env_vars=[],- supports_vision=True,- add_assistant_prefix=False,- model_list=[- LLMRouterModelConfig(- model_name="vertex-gemini-2.5-flash",- litellm_params={"model": "vertex_ai/gemini-2.5-flash"},- ),- ],- main_model_group="vertex-gemini-2.5-flash",- fallback_model_group="gpt-5-mini-fallback",- )--class TestGemini3ReasoningEffortExperiment:"""SKY-9785 experiment. Grouped under a class so the autouse reset doesn'tcouple unrelated tests in this module to the new class-level override."""@@ -1803,9 +1786,6 @@ class TestGemini3ReasoningEffortExperiment:"""Router primary `main_model_group` carries the gemini-3 substring."""assert LLMAPIHandlerFactory._is_gemini_3_model(_gemini_3_flash_router()) is True- def test_is_gemini_3_model_rejects_gemini_2(self) -> None:- assert LLMAPIHandlerFactory._is_gemini_3_model(_gemini_2_5_flash_router()) is False-def test_is_gemini_3_model_detects_direct_config(self) -> None:cfg = LLMConfig(model_name="vertex_ai/gemini-3-flash-preview",@@ -1840,17 +1820,6 @@ class TestGemini3ReasoningEffortExperiment:assert params["reasoning_effort"] == "low"assert "thinking" not in params- def test_apply_gemini_thinking_optimization_leaves_gemini_2_5_alone(self) -> None:- """The experiment only rewrites Gemini 3 calls. Gemini 2.5 keeps the strict- `thinking={budget_tokens:N}` path that Vertex 2.5 honors."""- LLMAPIHandlerFactory.set_gemini_3_reasoning_effort_override("low")- params: dict[str, Any] = {}- LLMAPIHandlerFactory._apply_gemini_thinking_optimization(- params, new_budget=1024, llm_config=_gemini_2_5_flash_router(), prompt_name="extract-actions"- )- assert "reasoning_effort" not in params- assert params["thinking"]["budget_tokens"] == 1024-def test_apply_gemini_thinking_optimization_control_leaves_gemini_3_alone(self) -> None:"""Override unset (control arm) — Gemini 3 keeps today's behavior so we have aclean comparison baseline."""@@ -1892,21 +1861,6 @@ class TestGemini3ReasoningEffortExperiment:assert "thinking_level" not in paramsassert "thinking" not in params- def test_apply_gemini_thinking_optimization_keeps_guard_for_gemini_2_5_with_thinking_level(self) -> None:- """Override is set, but model is Gemini 2.5 — the override doesn't apply,- and the legacy thinking_level guard fires as before (preserves the historic- behavior that Gemini 2.5 routes with a thinking_level config field never- get a budget_tokens write)."""- LLMAPIHandlerFactory.set_gemini_3_reasoning_effort_override("medium")- params: dict[str, Any] = {"thinking_level": "minimal"}- LLMAPIHandlerFactory._apply_gemini_thinking_optimization(- params, new_budget=1024, llm_config=_gemini_2_5_flash_router(), prompt_name="extract-actions"- )- # Override didn't fire (not gemini-3), guard fired, nothing else changed.- assert "reasoning_effort" not in params- assert "thinking" not in params- assert params["thinking_level"] == "minimal"-class TestThinkingBudgetOptimization:@pytest.mark.parametrize("reasoning_effort", ["medium", "high"])@@ -2938,7 +2892,7 @@ async def test_non_speculative_cancelled_error_propagates(monkeypatch: pytest.Modef test_get_api_parameters_injects_safety_settings_for_gemini_direct_config() -> None:llm_config = LLMConfig(- model_name="vertex_ai/gemini-2.5-flash",+ model_name="vertex_ai/gemini-3-flash-preview",required_env_vars=[],supports_vision=True,add_assistant_prefix=False,@@ -2951,7 +2905,7 @@ def test_get_api_parameters_injects_safety_settings_for_gemini_direct_config() -def test_get_api_parameters_omits_safety_settings_for_gemini_router_config() -> None:# Router configs must NOT carry safety_settings at the request level — it would ride along# to the non-Gemini fallback deployment and 400. Injection happens per-deployment instead.- params = LLMAPIHandlerFactory.get_api_parameters(_gemini_2_5_flash_router())+ params = LLMAPIHandlerFactory.get_api_parameters(_gemini_3_flash_router())assert "safety_settings" not in params@@ -2959,7 +2913,7 @@ def test_inject_gemini_safety_settings_targets_only_gemini_deployments() -> None# Reproduces incident #646: a Gemini primary + Azure fallback in one router. safety_settings# must land on the Gemini deployment and stay off the Azure one so the fallback hop survives.model_list = [- {"model_name": "vertex-gemini-2.5-flash-lite", "litellm_params": {"model": "vertex_ai/gemini-2.5-flash-lite"}},+ {"model_name": "vertex-gemini-3.1-flash-lite", "litellm_params": {"model": "vertex_ai/gemini-3.1-flash-lite"}},{"model_name": "gpt-5-mini-fallback", "litellm_params": {"model": "azure/gpt-5-mini"}},]result = api_handler_factory._inject_gemini_safety_settings(model_list)@@ -3607,7 +3561,7 @@ async def test_router_speculative_call_cost_reaches_its_step(monkeypatch: pytest@pytest.mark.asyncioasync def test_single_model_speculative_call_cost_reaches_its_step(monkeypatch: pytest.MonkeyPatch) -> None:llm_config = LLMConfig(- model_name="vertex_ai/gemini-2.5-flash",+ model_name="vertex_ai/gemini-3-flash-preview",required_env_vars=[],supports_vision=False,add_assistant_prefix=False,@@ -3622,7 +3576,7 @@ async def test_single_model_speculative_call_cost_reaches_its_step(monkeypatch:monkeypatch.setattr(api_handler_factory.litellm,"acompletion",- AsyncMock(return_value=FakeLLMResponse("vertex_ai/gemini-2.5-flash")),+ AsyncMock(return_value=FakeLLMResponse("vertex_ai/gemini-3-flash-preview")),)costs = _record_step_cost_writes(monkeypatch)diff --git a/tests/unit/test_capped_subprocess.py b/tests/unit/test_capped_subprocess.pynew file mode 100644index 000000000..6961fd4e7--- /dev/null+++ b/tests/unit/test_capped_subprocess.py@@ -0,0 +1,503 @@+import os+import resource+import signal+import subprocess+import sys+import threading+import time+from collections.abc import Callable+from pathlib import Path+from types import SimpleNamespace+from typing import Any++import psutil+import pytest+import structlog+from pdfplumber.utils.exceptions import PdfminerException++from skyvern.forge.sdk.utils import capped_subprocess+from skyvern.forge.sdk.utils.capped_subprocess import (+ MEMORY_CAP_ENFORCED,+ CappedSubprocessError,+ run_in_capped_subprocess,+)+from skyvern.forge.sdk.utils.capped_subprocess_child import memory_allowance++MIB = 1024 * 1024+++def _raise_memory_error_wrapped_like_pdfplumber() -> None:+ try:+ raise MemoryError+ except MemoryError as exc:+ raise PdfminerException(exc)+++def _ignore(*args: object) -> None:+ return None+++def _text_of(length: int) -> str:+ return "a" * length+++def _address_space_limit() -> tuple[int, int]:+ return resource.getrlimit(resource.RLIMIT_AS)+++def _hold_memory_then_wait(megabytes: int) -> int:+ held = b"x" * (megabytes * MIB)+ time.sleep(20)+ return len(held)+++def _raise_a_long_error() -> None:+ raise ValueError("x" * 100_000)+++_KEPT: list[bytes] = []+++def _keep_memory_and_return(megabytes: int) -> int:+ _KEPT.append(b"x" * (megabytes * MIB))+ return len(_KEPT)+++class _CountingStream:+ def __init__(self, stream: Any) -> None:+ self._stream = stream+ self.bytes_read = 0++ def read(self, size: int = -1) -> bytes:+ data = self._stream.read(size)+ self.bytes_read += len(data)+ return data++ def readline(self, size: int = -1) -> bytes:+ data = self._stream.readline(size)+ self.bytes_read += len(data)+ return data++ def readinto(self, buffer: Any) -> int:+ count = self._stream.readinto(buffer)+ self.bytes_read += count or 0+ return count+++class _RunsCodeWhenUnpickled:+ def __init__(self, marker: Path) -> None:+ self.marker = marker++ def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:+ return Path.write_text, (self.marker, "ran")+++def _return_a_value_that_runs_code_when_unpickled(marker: Path) -> _RunsCodeWhenUnpickled:+ return _RunsCodeWhenUnpickled(marker)+++def _fake_cgroup(directory: Path, max_mib: int, current_mib: int, inactive_file_mib: int | None = None) -> Path:+ (directory / "memory.max").write_text(f"{max_mib * MIB}\n")+ (directory / "memory.current").write_text(f"{current_mib * MIB}\n")+ if inactive_file_mib is not None:+ (directory / "memory.stat").write_text(f"anon {MIB}\ninactive_file {inactive_file_mib * MIB}\n")+ return directory+++ ("func", "args", "expected_exit"),+ [+ (os._exit, (3,), "exit status 3"),+ (signal.raise_signal, (signal.SIGKILL,), "killed by SIGKILL"),+ ],+)+def test_a_child_that_dies_without_a_result_fails_the_call(+ func: Callable[..., Any], args: tuple[Any, ...], expected_exit: str+) -> None:+ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(func, *args, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60)++ assert excinfo.value.kind == "crashed"+ assert expected_exit in str(excinfo.value)+++def test_a_memory_error_pdfplumber_wrapped_is_reported_as_out_of_memory() -> None:+ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ _raise_memory_error_wrapped_like_pdfplumber,+ memory_limit_bytes=256 * MIB,+ max_result_bytes=MIB,+ timeout_seconds=60,+ )++ assert excinfo.value.kind == "out_of_memory"+ assert "ran out of memory" in str(excinfo.value)+++ ("make_oversized_item", "most_bytes_read"),+ [+ pytest.param(os.urandom, 4096, id="bytes are refused before any of them is read"),+ pytest.param(_text_of, MIB + 1, id="str is read no further than the cap"),+ ],+)+def test_a_result_past_max_result_bytes_is_refused_without_reading_it_in_full(+ monkeypatch: pytest.MonkeyPatch, make_oversized_item: Callable[[int], bytes | str], most_bytes_read: int+) -> None:+ streams: list[_CountingStream] = []+ bounded_reader = capped_subprocess._BoundedReader++ def counting_reader(stream: Any, limit: int) -> Any:+ streams.append(_CountingStream(stream))+ return bounded_reader(streams[-1], limit)++ monkeypatch.setattr(capped_subprocess, "_BoundedReader", counting_reader)++ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ make_oversized_item, 4 * MIB, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60+ )++ assert excinfo.value.kind == "result_too_large"+ assert "more than the 1 MiB" in str(excinfo.value)+ assert streams[0].bytes_read <= most_bytes_read+++def test_a_child_that_outgrows_its_allowance_is_killed_and_reported_out_of_memory() -> None:+ """RLIMIT_AS stops it on Linux, and the parent's memory watchdog on macOS, where the limit cannot be set."""+ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ _hold_memory_then_wait, 400, memory_limit_bytes=64 * MIB, max_result_bytes=MIB, timeout_seconds=60+ )++ assert excinfo.value.kind == "out_of_memory"+ assert "ran out of memory" in str(excinfo.value)+++def test_the_growth_of_a_child_is_measured_by_the_parent_before_the_child_exits() -> None:+ with structlog.testing.capture_logs() as logs:+ run_in_capped_subprocess(+ _keep_memory_and_return, 50, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60+ )++ (finished,) = (log for log in logs if log["event"] == "Capped subprocess finished")+ assert 40 * MIB <= finished["rss_growth_sampled_bytes"] <= 120 * MIB+++def test_a_child_on_a_platform_without_resource_limits_still_succeeds(monkeypatch: pytest.MonkeyPatch) -> None:+ """Windows has no resource module and no RLIMIT_AS to apply; a call there must not need either."""+ bootstrap = capped_subprocess._CHILD_BOOTSTRAP.replace("; main()", "; sys.platform = 'win32'; main()")+ assert "win32" in bootstrap+ monkeypatch.setattr(capped_subprocess, "_CHILD_BOOTSTRAP", bootstrap)++ assert (+ run_in_capped_subprocess(os.getpid, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60)+ != os.getpid()+ )+++def test_a_parent_that_cannot_read_the_childs_memory_still_gets_its_result(monkeypatch: pytest.MonkeyPatch) -> None:+ def refuse(pid: int) -> None:+ raise psutil.AccessDenied(pid)++ monkeypatch.setattr(capped_subprocess.psutil, "Process", refuse)++ with structlog.testing.capture_logs() as logs:+ result = run_in_capped_subprocess(+ _ignore, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60+ )++ assert result is None+ (finished,) = (log for log in logs if log["event"] == "Capped subprocess finished")+ assert finished["rss_growth_sampled_bytes"] is None+++def test_a_long_error_message_is_cut_in_the_child_instead_of_failing_the_result_cap() -> None:+ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ _raise_a_long_error, memory_limit_bytes=256 * MIB, max_result_bytes=8 * 1024, timeout_seconds=60+ )++ assert excinfo.value.kind == "error"+ assert 0 < len(str(excinfo.value)) <= 4096+++def test_a_result_that_is_not_plain_data_is_refused_not_run(tmp_path: Path) -> None:+ marker = tmp_path / "marker"++ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ _return_a_value_that_runs_code_when_unpickled,+ marker,+ memory_limit_bytes=256 * MIB,+ max_result_bytes=MIB,+ timeout_seconds=60,+ )++ assert excinfo.value.kind == "crashed"+ assert "not plain data" in str(excinfo.value)+ assert not marker.exists()+++ "outcome",+ [+ pytest.param(["ok"], id="not a dict"),+ pytest.param({"status": "unknown"}, id="unknown status"),+ pytest.param({"status": "ok"}, id="ok without a value"),+ pytest.param({"status": "error", "message": 3}, id="error without a text message"),+ pytest.param({"status": "ok", "value": 1, "allowance_bytes": "big"}, id="a size that is not an int"),+ pytest.param({"status": "ok", "value": 1, "headroom_source": 4}, id="a source that is not text"),+ ],+)+def test_an_outcome_of_the_wrong_shape_fails_the_call_not_the_parent(+ monkeypatch: pytest.MonkeyPatch, outcome: object+) -> None:+ child = f"import pickle, sys; sys.stdout.buffer.write(pickle.dumps({outcome!r})); sys.stdout.flush()"+ monkeypatch.setattr(capped_subprocess, "_CHILD_BOOTSTRAP", child)++ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(_ignore, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60)++ assert excinfo.value.kind == "crashed"+ assert "unexpected shape" in str(excinfo.value)+++_V1_UNLIMITED = "9223372036854771712\n"+++ ("cgroup", "meminfo_mib", "reserve_mib", "expected_mib", "source"),+ [+ pytest.param(None, None, 256, 1536, "none", id="nothing readable"),+ pytest.param(None, 4096, 256, 1536, "meminfo", id="meminfo room"),+ pytest.param(None, 700, 256, 188, "meminfo", id="meminfo tight, reserve subtracted"),+ pytest.param(None, 600, 256, None, "meminfo", id="meminfo under the floor"),+ pytest.param(+ {"memory.max": "max\n", "memory.current": f"{900 * MIB}\n"}, 700, 256, 188, "meminfo", id="v2 no limit"+ ),+ pytest.param({"memory.current": f"{900 * MIB}\n"}, 700, 256, 188, "meminfo", id="v2 limit file missing"),+ pytest.param((6144, 1024), 50, 256, 1536, "cgroup", id="cgroup room, meminfo ignored"),+ pytest.param((6144, 5284), None, 0, 604, "cgroup", id="tight"),+ pytest.param((6144, 5000), None, 256, 632, "cgroup", id="tight with the result reserved"),+ pytest.param((6144, 3000), None, 1000, 1536, "cgroup", id="room despite other calls' reservations"),+ pytest.param((6144, 3000, 0), None, 2760, 128, "cgroup", id="exactly the floor"),+ pytest.param((6144, 3000, 0), None, 2761, None, "cgroup", id="a MiB under the floor"),+ pytest.param((6144, 6000), None, 256, None, "cgroup", id="under the margin and the reserve"),+ pytest.param((6144, 5284, 2000), None, 256, 1536, "cgroup", id="inactive page cache counts as free"),+ pytest.param(+ {"memory.max": f"{6144 * MIB}\n", "memory.current": f"{1024 * MIB}\n", "memory.stat": "inactive_file x\n"},+ 4096,+ 256,+ 1536,+ "cgroup",+ id="a limit with an unparseable memory.stat counts no inactive cache, not meminfo",+ ),+ pytest.param(+ {"memory.max": f"{6144 * MIB}\n"},+ 16384,+ 0,+ None,+ "cgroup",+ id="a limit with unreadable usage refuses the call, not meminfo",+ ),+ pytest.param(+ {+ "memory/memory.stat": f"hierarchical_memory_limit {8192 * MIB}\ntotal_inactive_file {512 * MIB}\n",+ "memory/memory.limit_in_bytes": f"{2048 * MIB}\n",+ "memory/memory.usage_in_bytes": f"{1536 * MIB}\n",+ },+ 50,+ 256,+ 512,+ "cgroup_v1",+ id="v1 takes the smaller limit and discounts inactive cache",+ ),+ pytest.param(+ {+ "memory/memory.stat": f"hierarchical_memory_limit {2048 * MIB}\n",+ "memory/memory.limit_in_bytes": _V1_UNLIMITED,+ "memory/memory.usage_in_bytes": f"{1024 * MIB}\n",+ },+ 16384,+ 256,+ 512,+ "cgroup_v1",+ id="v1 limit from the hierarchy alone",+ ),+ pytest.param(+ {"memory/memory.limit_in_bytes": f"{2048 * MIB}\n"},+ 16384,+ 0,+ None,+ "cgroup_v1",+ id="v1 limit with unreadable usage refuses the call",+ ),+ pytest.param(+ {+ "memory/memory.stat": f"hierarchical_memory_limit {_V1_UNLIMITED}",+ "memory/memory.limit_in_bytes": _V1_UNLIMITED,+ "memory/memory.usage_in_bytes": f"{1024 * MIB}\n",+ },+ 700,+ 256,+ 188,+ "meminfo",+ id="v1 without a limit falls through to meminfo",+ ),+ ],+)+def test_memory_allowance_follows_the_pods_free_memory(+ tmp_path: Path,+ cgroup: dict[str, str] | tuple[int, ...] | None,+ meminfo_mib: int | None,+ reserve_mib: int,+ expected_mib: int | None,+ source: str,+) -> None:+ if isinstance(cgroup, tuple):+ _fake_cgroup(tmp_path, *cgroup)+ elif cgroup:+ for name, content in cgroup.items():+ (tmp_path / name).parent.mkdir(exist_ok=True)+ (tmp_path / name).write_text(content)+ if meminfo_mib is not None:+ (tmp_path / "meminfo").write_text(f"MemTotal: 16777216 kB\nMemAvailable: {meminfo_mib * 1024} kB\n")++ sized = memory_allowance(1536 * MIB, reserve_mib * MIB, cgroup_dir=tmp_path, meminfo_path=tmp_path / "meminfo")++ assert (sized.allowance, sized.source) == (None if expected_mib is None else expected_mib * MIB, source)+++class _TakesMemoryWhenUnpickled:+ """Stands in for the imports that take memory from the pod while the child unpickles its request."""++ def __init__(self, memory_current: Path) -> None:+ self.memory_current = memory_current++ def __reduce__(self) -> tuple[Any, tuple[Any, ...]]:+ return Path.write_text, (self.memory_current, f"{5344 * MIB}\n")++[email protected]("pod_is_tight_at_the_start", [True, False], ids=["parent refuses", "child refuses"])+def test_a_pod_without_headroom_fails_the_call_instead_of_risking_the_worker(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, pod_is_tight_at_the_start: bool+) -> None:+ cgroup = _fake_cgroup(tmp_path, max_mib=6144, current_mib=6000 if pod_is_tight_at_the_start else 1024)+ monkeypatch.setattr(capped_subprocess, "MEMORY_CAP_ENFORCED", True)+ monkeypatch.setattr(capped_subprocess, "CGROUP_DIR", str(cgroup))+ if pod_is_tight_at_the_start:++ def popen_must_not_run(*args: object, **kwargs: object) -> None:+ raise AssertionError("a child was started in a pod with no headroom")++ monkeypatch.setattr(capped_subprocess.subprocess, "Popen", popen_must_not_run)++ with pytest.raises(CappedSubprocessError) as excinfo:+ run_in_capped_subprocess(+ _ignore,+ _TakesMemoryWhenUnpickled(cgroup / "memory.current"),+ memory_limit_bytes=1536 * MIB,+ max_result_bytes=128 * MIB,+ timeout_seconds=60,+ )++ assert excinfo.value.kind == "no_headroom"+ assert "not enough free memory" in str(excinfo.value)+++def test_calls_running_at_once_are_sized_against_each_other(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(capped_subprocess, "CGROUP_DIR", str(_fake_cgroup(tmp_path, max_mib=1024, current_mib=0)))+ reserve = capped_subprocess._reserved_memory++ with (+ reserve(512 * MIB, 16 * MIB) as first,+ reserve(512 * MIB, 16 * MIB) as second,+ reserve(512 * MIB, 16 * MIB) as third,+ ):+ sizes = [(r.allowance, r.held_by_others) for r in (first, second, third)]+ assert sizes == [(512 * MIB, 0), (224 * MIB, 528 * MIB), (None, 768 * MIB)]+ with reserve(512 * MIB, 16 * MIB) as after_release:+ assert (after_release.allowance, after_release.held_by_others) == (512 * MIB, 0)++[email protected](("memory_factor", "is_refused"), [(6, True), (1, False)])+def test_the_result_is_reserved_at_its_decoded_size(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, memory_factor: int, is_refused: bool+) -> None:+ class ChildStarted(Exception):+ pass++ def start_child(*args: object, **kwargs: object) -> None:+ raise ChildStarted++ cgroup = _fake_cgroup(tmp_path, max_mib=1024, current_mib=0)+ monkeypatch.setattr(capped_subprocess, "MEMORY_CAP_ENFORCED", True)+ monkeypatch.setattr(capped_subprocess, "CGROUP_DIR", str(cgroup))+ monkeypatch.setattr(capped_subprocess.subprocess, "Popen", start_child)++ def call() -> None:+ run_in_capped_subprocess(+ _ignore,+ memory_limit_bytes=512 * MIB,+ max_result_bytes=128 * MIB,+ result_memory_factor=memory_factor,+ timeout_seconds=60,+ )++ if is_refused:+ with pytest.raises(CappedSubprocessError) as excinfo:+ call()+ assert excinfo.value.kind == "no_headroom"+ else:+ with pytest.raises(ChildStarted):+ call()+++def test_a_child_is_killed_when_the_call_cannot_finish_starting_it(monkeypatch: pytest.MonkeyPatch) -> None:+ class ThreadThatCannotStart:+ def __init__(self, *args: object, **kwargs: object) -> None:+ pass++ def start(self) -> None:+ raise RuntimeError("can't start new thread")++ processes: list[subprocess.Popen[bytes]] = []++ def recording_popen(*args: Any, **kwargs: Any) -> subprocess.Popen[bytes]:+ processes.append(subprocess.Popen(*args, **kwargs))+ return processes[-1]++ monkeypatch.setattr(+ capped_subprocess,+ "subprocess",+ SimpleNamespace(Popen=recording_popen, PIPE=subprocess.PIPE, TimeoutExpired=subprocess.TimeoutExpired),+ )+ monkeypatch.setattr(+ capped_subprocess,+ "threading",+ SimpleNamespace(+ Thread=ThreadThatCannotStart, Timer=threading.Timer, Event=threading.Event, Lock=threading.Lock+ ),+ )++ with pytest.raises(RuntimeError):+ run_in_capped_subprocess(time.sleep, 60, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60)++ assert processes[0].poll() is not None+++def test_a_child_that_does_not_exit_after_its_result_is_killed(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(capped_subprocess, "_EXIT_GRACE_SECONDS", 0.2)+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])++ assert capped_subprocess._wait_for_exit(process) == -signal.SIGKILL++[email protected](not MEMORY_CAP_ENFORCED, reason="only Linux enforces RLIMIT_AS; elsewhere the child is uncapped")+def test_the_child_cannot_raise_its_own_memory_cap() -> None:+ soft, hard = run_in_capped_subprocess(+ _address_space_limit, memory_limit_bytes=256 * MIB, max_result_bytes=MIB, timeout_seconds=60+ )++ assert soft == hard != resource.RLIM_INFINITYdiff --git a/tests/unit/test_config_registry.py b/tests/unit/test_config_registry.pyindex af5771b95..fa761ee90 100644--- a/tests/unit/test_config_registry.py+++ b/tests/unit/test_config_registry.py@@ -85,7 +85,7 @@ def test_copilot_router_provider_model_retains_only_its_source_provenance(monkeypatch: pytest.MonkeyPatch, builtin: bool) -> None:monkeypatch.setattr(config_registry.LLMConfigRegistry, "_configs", {})- provider_model = "vertex_ai/gemini-2.5-flash"+ provider_model = "vertex_ai/gemini-3-flash-preview"credential = "synthetic-test-key"parameters = {"model": provider_model, "api_key": credential}config = llm_schemas.LLMRouterConfig(@@ -100,7 +100,7 @@ def test_copilot_router_provider_model_retains_only_its_source_provenance(config_registry._register_builtin_config if builtin else config_registry.LLMConfigRegistry.register_config)register("TEST_ROUTER", config)- with skyvern_context.scoped(SkyvernContext(runtime_secret_values={"5", credential})):+ with skyvern_context.scoped(SkyvernContext(runtime_secret_values={"3", credential})):model_name, run_config, _, _ = resolve_model_config(None, llm_key_override="TEST_ROUTER")model = run_config.model_provider.get_model(model_name)with capture_runtime_logs() as events:@@ -116,7 +116,7 @@ def test_copilot_router_provider_model_retains_only_its_source_provenance(structlog.get_logger().info("Caller parameters", payload=parameters)records = json.loads(json.dumps(events))usage = next(record for record in records if record.get("log_code") == "copilot_model_usage")- redacted = f"vertex_ai/gemini-2.{REDACTED_SECRET_PLACEHOLDER}-flash"+ redacted = f"vertex_ai/gemini-{REDACTED_SECRET_PLACEHOLDER}-flash-preview"assert usage["gen_ai.request.model"] == (provider_model if builtin else redacted)assert usage["gen_ai.response.model"] == redactedassert usage["gen_ai.usage.input_tokens"] == 15 and type(usage["gen_ai.usage.input_tokens"]) is intdiff --git a/tests/unit/test_copilot_model_resolver.py b/tests/unit/test_copilot_model_resolver.pyindex 6936be48e..f73cf3c9e 100644--- a/tests/unit/test_copilot_model_resolver.py+++ b/tests/unit/test_copilot_model_resolver.py@@ -66,9 +66,9 @@ class TestModelResolver:from skyvern.schemas.llm import LLMRouterConfig, LLMRouterModelConfigmain = LLMRouterModelConfig(- model_name="vertex-gemini-2.5-flash", # router group alias+ model_name="vertex-gemini-3-flash-preview", # router group aliaslitellm_params={- "model": "vertex_ai/gemini-2.5-flash",+ "model": "vertex_ai/gemini-3-flash-preview","api_base": "https://vertex.example.com","timeout": 900.0,},@@ -82,22 +82,22 @@ class TestModelResolver:litellm_params={"model": "anthropic/claude-sonnet-4-20250514"},)router_config = LLMRouterConfig(- model_name="gemini-2.5-flash-fallback-router",+ model_name="gemini-3-flash-preview-fallback-router",model_list=[main, fallback, final_fallback],required_env_vars=["VERTEX_CREDENTIALS"],supports_vision=True,add_assistant_prefix=False,- main_model_group="vertex-gemini-2.5-flash",+ main_model_group="vertex-gemini-3-flash-preview",fallback_model_group=["gpt-4-1-mini-fallback", "claude-fallback"],temperature=0.3,max_completion_tokens=8192,)- handler = _install_config(monkeypatch, router_config, "GEMINI_2_5_FLASH_WITH_FALLBACK")+ handler = _install_config(monkeypatch, router_config, "GEMINI_3_0_FLASH_WITH_FALLBACK")model_name, run_config, llm_key, supports_vision = resolve_model_config(handler)- assert model_name == "vertex_ai/gemini-2.5-flash"- assert llm_key == "GEMINI_2_5_FLASH_WITH_FALLBACK"+ assert model_name == "vertex_ai/gemini-3-flash-preview"+ assert llm_key == "GEMINI_3_0_FLASH_WITH_FALLBACK"assert supports_vision is Trueassert run_config.model_settings is not Noneassert run_config.model_settings.temperature == 0.3@@ -209,7 +209,7 @@ class TestModelResolver:entry = LLMRouterModelConfig(model_name="some-group",- litellm_params={"model": "vertex_ai/gemini-2.5-flash"},+ litellm_params={"model": "vertex_ai/gemini-3-flash-preview"},)router_config = LLMRouterConfig(model_name="misconfigured-router",@@ -224,7 +224,7 @@ class TestModelResolver:with capture_logs() as logs:model_name, _, _, _ = resolve_model_config(handler)- assert model_name == "vertex_ai/gemini-2.5-flash"+ assert model_name == "vertex_ai/gemini-3-flash-preview"joined = " ".join(str(record.get("event", "")) for record in logs)assert "main_model_group has no matching" in joineddiff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.pyindex 6a535e7d4..adcbbd2dc 100644--- a/tests/unit/test_copilot_model_telemetry.py+++ b/tests/unit/test_copilot_model_telemetry.py@@ -1562,7 +1562,7 @@ async def test_browser_ablation_timeout_reports_active_model_and_browser_work(assert result.browser_ablation_metadata["tool_activity"] == [{"tool_name": "navigate_browser", "success": True}]-_GEMINI = "vertex_ai/gemini-2.5-flash"+_GEMINI = "vertex_ai/gemini-3-flash-preview"_SCHEMA_CALL = ResponseFunctionToolCall(type="function_call",call_id="call_schema",@@ -1821,7 +1821,7 @@ def _tool_text(messages: list[dict[str, Any]]) -> str:def _gemini_function_responses(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:contents = _gemini_convert_messages_with_history(messages=cast(Any, [message for message in messages if message["role"] != "system"]),- model="gemini-2.5-flash",+ model="gemini-3-flash-preview",custom_llm_provider="vertex_ai",)return [diff --git a/tests/unit/test_copilot_model_usage.py b/tests/unit/test_copilot_model_usage.pyindex 34324cc8e..abb1fb7a2 100644--- a/tests/unit/test_copilot_model_usage.py+++ b/tests/unit/test_copilot_model_usage.py@@ -88,8 +88,8 @@ def test_direct_event_preserves_zeroes_and_omits_unavailable_optional_fields() -def test_direct_event_is_a_closed_content_free_scalar_schema() -> None:logger = CapturingLogger()event = CopilotModelUsageEvent(- request_model="vertex_ai/gemini-2.5-flash",- response_model="gemini-2.5-flash",+ request_model="vertex_ai/gemini-3-flash-preview",+ response_model="gemini-3-flash-preview",provider_name="vertex_ai",input_tokens=12,output_tokens=3,@@ -281,7 +281,7 @@ def test_unrelated_direct_event_does_not_log() -> None:@pytest.mark.parametrize(("provider_name", "model", "expected"),[- ("vertex_ai", "gemini-2.5-flash", "gcp.vertex_ai"),+ ("vertex_ai", "gemini-3-flash-preview", "gcp.vertex_ai"),("bedrock", "anthropic.claude", "aws.bedrock"),("Azure", "gpt-5.6", "azure.ai.openai"),("Cloudflare", "anthropic/claude-sonnet-4-6", "anthropic"),diff --git a/tests/unit/test_custom_llms.py b/tests/unit/test_custom_llms.pyindex 02588b57e..d2b228325 100644--- a/tests/unit/test_custom_llms.py+++ b/tests/unit/test_custom_llms.py@@ -298,7 +298,7 @@ async def test_custom_llm_masks_and_preserves_secret_extra_headers(config=CustomLLMConfig(display_name="Gemini Flex",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={"service_tier": "flex", "extra_headers": dict(secret_headers)},)@@ -327,7 +327,7 @@ async def test_custom_llm_masks_and_preserves_secret_extra_headers(config=CustomLLMConfig(display_name="Gemini Flex",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key=CUSTOM_LLM_API_KEY_MASK,extra_parameters={"service_tier": "flex", "extra_headers": dict(masked_headers)},)@@ -941,7 +941,7 @@ def test_task_v2_selected_non_custom_model_override_is_intentional(monkeypatch:workflow_permanent_id="wpid_non_custom",prompt="Use the selected non-custom model",url=None,- model={"model_name": "gemini-2.5-flash"},+ model={"model_name": "gemini-3.0-flash"},created_at=now,modified_at=now,)@@ -972,7 +972,7 @@ def test_custom_llm_extra_parameters_flow_into_litellm_params() -> None:CustomLLMConfig(display_name="Gemini Flex",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={"service_tier": "flex",@@ -987,7 +987,7 @@ def test_custom_llm_extra_parameters_flow_into_litellm_params() -> None:finally:deregister_custom_llm_config(custom_llm_id)- assert llm_config.model_name == "gemini/gemini-2.5-flash"+ assert llm_config.model_name == "gemini/gemini-3-flash-preview"assert llm_config.litellm_paramsassert llm_config.litellm_params["service_tier"] == "flex"assert llm_config.litellm_params["thinking"] == {"type": "enabled", "budget_tokens": 1024}@@ -1001,7 +1001,7 @@ def test_gemini_provider_requires_api_key() -> None:CustomLLMConfig(display_name="Gemini",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",)@@ -1014,7 +1014,7 @@ def test_custom_llm_extra_parameters_reject_reserved_keys(reserved_key: str) ->CustomLLMConfig(display_name="Reserved",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={reserved_key: "value"},)@@ -1025,7 +1025,7 @@ def test_custom_llm_extra_parameters_reject_too_many() -> None:CustomLLMConfig(display_name="Too Many",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={f"param_{index}": index for index in range(31)},)@@ -1036,7 +1036,7 @@ def test_custom_llm_extra_parameters_reject_oversized() -> None:CustomLLMConfig(display_name="Too Big",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={"blob": "x" * 11_000},)@@ -1065,7 +1065,7 @@ def test_custom_gemini_thinking_budget_is_owned_and_not_overwritten() -> None:CustomLLMConfig(display_name="Gemini Thinking",provider="gemini",- model_name="gemini-2.5-flash",+ model_name="gemini-3-flash-preview",api_key="test-key",extra_parameters={"thinking": {"type": "enabled", "budget_tokens": 4096}},),@@ -1096,7 +1096,7 @@ def test_custom_gemini_thinking_budget_is_owned_and_not_overwritten() -> None:def test_non_custom_key_never_owns_thinking() -> None:assert (- LLMAPIHandlerFactory._custom_llm_owns_thinking("GEMINI_2_5_FLASH", {"thinking": {"budget_tokens": 1}}) is False+ LLMAPIHandlerFactory._custom_llm_owns_thinking("GEMINI_3_0_FLASH", {"thinking": {"budget_tokens": 1}}) is False)diff --git a/tests/unit/test_dropdown_option_list_search.py b/tests/unit/test_dropdown_option_list_search.pynew file mode 100644index 000000000..a742b0e29--- /dev/null+++ b/tests/unit/test_dropdown_option_list_search.py@@ -0,0 +1,169 @@+"""Regression tests for the batched option-list search behind custom dropdown selection (SKY-18709).++Finding the ``<ul>``/``role="listbox"`` inside an opened menu used to resolve a locator and read an+attribute per visited element, and the menu-locating pass and the scroll-container pass each walked+the subtree. On a menu with hundreds of options, over a remote browser, that was minutes per field.+The search now reads the whole frame once and answers both passes from that single read.+"""++from __future__ import annotations++import json+import shutil+import subprocess+import tempfile+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock++import pytest++import skyvern.webeye.scraper.scraper as scraper_mod+from skyvern.webeye.scraper.scraper import LIVE_ELEMENT_PROBE_JS, IncrementalScrapePage++_NODE = shutil.which("node")++# A dropdown menu rendered by a web component lives in an open shadow root, and a widget that+# clones its rows leaves one id matching several elements. Both decide whether the real snippet+# finds the option list, so the shipped expression is the one exercised here.+_PROBE_DRIVER_JS = """+const probe = %s;+const node = (tag, attrs, children, shadowChildren) => ({+ tagName: tag,+ children: children || [],+ getAttribute: (name) => (attrs && name in attrs ? attrs[name] : null),+ shadowRoot: shadowChildren ? { children: shadowChildren } : null,+});++const menu = node("UL", { unique_id: "menu" });+const host = node("DIV", { unique_id: "host" }, [], [menu]);+const clonedRow = node("LI", { unique_id: "row", role: "option" });+const specialIdListbox = node("UL", { unique_id: "__proto__", role: "listbox" });+const root = node("HTML", {}, [host, clonedRow, node("DIV", {}, [clonedRow]), specialIdListbox]);++global.document = { documentElement: root };+console.log(JSON.stringify({+ probes: probe("unique_id"),+ objectPrototypeHasCount: Object.prototype.hasOwnProperty.call(Object.prototype, "count"),+}));+"""+++def _menu_element_tree() -> dict:+ return {+ "id": "menu",+ "tagName": "div",+ "attributes": {},+ "children": [+ {"id": "header", "tagName": "div", "attributes": {}, "children": []},+ {+ "id": "options-wrapper",+ "tagName": "div",+ "attributes": {},+ "children": [+ {"id": "options", "tagName": "div", "attributes": {"role": "listbox"}, "children": []},+ ],+ },+ ],+ }+++def _probes_for_menu() -> dict[str, dict]:+ return {+ "menu": {"count": 1, "tagName": "div", "role": None},+ "header": {"count": 1, "tagName": "div", "role": None},+ "options-wrapper": {"count": 1, "tagName": "div", "role": None},+ "options": {"count": 1, "tagName": "div", "role": "listbox"},+ }+++def _incremental_page(monkeypatch: pytest.MonkeyPatch, evaluate: AsyncMock) -> IncrementalScrapePage:+ monkeypatch.setattr(scraper_mod.SkyvernFrame, "evaluate", evaluate)+ skyvern_frame = MagicMock()+ skyvern_frame.get_frame.return_value = MagicMock()+ skyvern_frame.get_incremental_element_tree = AsyncMock(return_value=([], []))+ return IncrementalScrapePage(skyvern_frame=skyvern_frame)++[email protected](_NODE is None, reason="node not on PATH")+def test_probe_reads_shadow_roots_and_handles_special_ids() -> None:+ with tempfile.TemporaryDirectory() as workdir:+ driver = Path(workdir) / "driver.mjs"+ driver.write_text(_PROBE_DRIVER_JS % LIVE_ELEMENT_PROBE_JS)+ result = subprocess.run([str(_NODE), str(driver)], capture_output=True, text=True, timeout=30)++ assert result.returncode == 0, f"{result.stdout}\n{result.stderr}"+ result_data = json.loads(result.stdout)+ probes = result_data["probes"]+ assert probes["menu"] == {"count": 1, "tagName": "ul", "role": None}+ assert probes["host"]["count"] == 1+ assert probes["row"] == {"count": 2, "tagName": "li", "role": "option"}+ assert probes["__proto__"] == {"count": 1, "tagName": "ul", "role": "listbox"}+ assert result_data["objectPrototypeHasCount"] is False+++async def test_option_list_search_reads_the_page_once_for_repeated_walks(monkeypatch: pytest.MonkeyPatch) -> None:+ evaluate = AsyncMock(return_value=_probes_for_menu())+ page = _incremental_page(monkeypatch, evaluate)+ tree = _menu_element_tree()++ assert await page.find_option_list_element_id(tree) == "options"+ # The scroll-container pass walks the same subtree right after the menu-locating pass.+ assert await page.find_option_list_element_id(tree) == "options"++ assert evaluate.await_count == 1+++async def test_option_list_search_skips_an_id_matching_more_than_one_element(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ probes = _probes_for_menu()+ probes["options"]["count"] = 2+ page = _incremental_page(monkeypatch, AsyncMock(return_value=probes))++ assert await page.find_option_list_element_id(_menu_element_tree()) is None+++async def test_option_list_search_uses_a_role_set_after_the_scrape(monkeypatch: pytest.MonkeyPatch) -> None:+ probes = _probes_for_menu()+ probes["options-wrapper"]["role"] = "listbox"+ page = _incremental_page(monkeypatch, AsyncMock(return_value=probes))++ # The scraped attributes hold no role for the wrapper, so the live one decides, and the wrapper+ # is reached before the nested listbox.+ assert await page.find_option_list_element_id(_menu_element_tree()) == "options-wrapper"+++async def test_option_list_search_prefers_live_role_over_stale_scraped_role(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ tree = _menu_element_tree()+ tree["children"][1]["attributes"]["role"] = "option"+ probes = _probes_for_menu()+ probes["options-wrapper"]["role"] = "listbox"+ page = _incremental_page(monkeypatch, AsyncMock(return_value=probes))++ assert await page.find_option_list_element_id(tree) == "options-wrapper"+++async def test_option_list_search_survives_an_unreadable_page(monkeypatch: pytest.MonkeyPatch) -> None:+ page = _incremental_page(monkeypatch, AsyncMock(side_effect=RuntimeError("page is gone")))++ assert await page.find_option_list_element_id(_menu_element_tree()) is None+++async def test_a_new_incremental_element_tree_drops_the_cached_page_read(monkeypatch: pytest.MonkeyPatch) -> None:+ """A cascading select re-scrapes between levels, so a read cached from the previous level must go."""+ evaluate = AsyncMock(return_value=_probes_for_menu())+ page = _incremental_page(monkeypatch, evaluate)++ assert await page.find_option_list_element_id(_menu_element_tree()) == "options"+ await page.get_incremental_element_tree(AsyncMock(return_value=[]))+ assert await page.find_option_list_element_id(_menu_element_tree()) == "options"++ assert evaluate.await_count == 2diff --git a/tests/unit/test_element_engine_selection_threading.py b/tests/unit/test_element_engine_selection_threading.pyindex 7f2663fb4..06b21c74d 100644--- a/tests/unit/test_element_engine_selection_threading.py+++ b/tests/unit/test_element_engine_selection_threading.py@@ -330,7 +330,7 @@ async def test_dropdown_screenshot_uses_frame_selection_and_skips_selected_timeocandidate = MagicMock(get_locator=MagicMock(return_value=locator),is_next_to_element=AsyncMock(return_value=True),- find_children_element_id_by_callback=AsyncMock(return_value=None),+ get_element_dict=MagicMock(return_value={"id": "candidate"}),get_attr=AsyncMock(return_value=None),)frame = MagicMock(@@ -339,7 +339,11 @@ async def test_dropdown_screenshot_uses_frame_selection_and_skips_selected_timeoget_scroll_x_y=AsyncMock(return_value=(4, 8)),safe_scroll_to_x_y=AsyncMock(),)- incremental = MagicMock(skyvern_frame=frame, element_tree=[{"id": "candidate"}])+ incremental = MagicMock(+ skyvern_frame=frame,+ element_tree=[{"id": "candidate"}],+ find_option_list_element_id=AsyncMock(return_value=None),+ )anchor = MagicMock(is_visible=AsyncMock(return_value=True))monkeypatch.setattr(handler.SkyvernElement, "create_from_incremental", AsyncMock(return_value=candidate))llm = AsyncMock()diff --git a/tests/unit/test_error_detection_service.py b/tests/unit/test_error_detection_service.pyindex 57ea3a331..a62028d53 100644--- a/tests/unit/test_error_detection_service.py+++ b/tests/unit/test_error_detection_service.py@@ -344,3 +344,57 @@ async def test_detect_errors_empty_llm_response(mock_browser_state, mock_step):)assert detected_errors == []++[email protected]("path", ["no_page", "scrape_fails", "detector_raises", "page_lookup_raises"])+ ("failure_reason", "expected"),+ [+ ("The bank answered payment_failed at checkout.", ["payment_failed"]),+ # A description substring is too loose to stand on its own, and naming two codes is not concluding one.+ ("The bank said: Credit card was declined.", []),+ ("Either payment_failed or address_invalid; the page did not say.", []),+ ],+)+async def test_every_empty_detection_path_falls_back_to_a_single_code_the_reason_names(+ mock_step, path: str, failure_reason: str, expected: list[str]+) -> None:+ now = datetime.now()+ task = make_task(+ now,+ make_organization(now),+ error_code_mapping={"payment_failed": "Credit card was declined", "address_invalid": "Bad address"},+ )+ browser_state = MagicMock()+ page = MagicMock()+ page.url = "https://example.com"+ browser_state.get_working_page = AsyncMock(+ return_value=None if path == "no_page" else page,+ side_effect=Exception("browser gone") if path == "page_lookup_raises" else None,+ )+ browser_state.scrape_website = AsyncMock(+ side_effect=Exception("down") if path == "scrape_fails" else None,+ return_value=MagicMock() if path == "detector_raises" else None,+ )++ with (+ patch(+ "skyvern.services.error_detection_service._detect_errors_from_context",+ new_callable=AsyncMock,+ return_value=[],+ ),+ patch(+ "skyvern.services.error_detection_service.extract_user_defined_errors",+ new_callable=AsyncMock,+ side_effect=Exception("llm down"),+ ),+ ):+ detected = await detect_user_defined_errors_for_task(+ task=task,+ step=mock_step,+ browser_state=browser_state,+ failure_reason=failure_reason,+ )++ assert [error.error_code for error in detected] == expecteddiff --git a/tests/unit/test_explicit_submit_sequential_click_bypass.py b/tests/unit/test_explicit_submit_sequential_click_bypass.pyindex 53d3fe7ae..4aa462f15 100644--- a/tests/unit/test_explicit_submit_sequential_click_bypass.py+++ b/tests/unit/test_explicit_submit_sequential_click_bypass.py@@ -18,6 +18,8 @@ import pytestimport skyvern.webeye.actions.handler as handler_modulefrom skyvern.forge.agent_functions import AgentFunction+from skyvern.forge.sdk.core import skyvern_context+from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions.actions import ActionStatus, ActionType, ClickActionfrom skyvern.webeye.actions.handler import (@@ -402,6 +404,67 @@ class TestHandleClickActionIntegration:incremental.stop_listen_dom_increment.assert_awaited_once()assert isinstance(results[-1], ActionSuccess)+ @pytest.mark.asyncio+ async def test_successful_submit_click_is_recorded_outside_the_bypass_path(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(now, organization)+ step = make_step(now, task, step_id="step-1", status=StepStatus.running, order=2, retry_index=1, output=None)+ element = self._clickable_element(tag_name="button", type_value="button")+ chain_click_mock, sequential_mock, _ = self._wire_handler(monkeypatch, element)+ # This button is recognized for completion evidence, but not by the existing narrow+ # submit-bypass hook; the ordinary dropdown path still runs after the successful click.+ monkeypatch.setattr(+ handler_module.app.AGENT_FUNCTION,+ "is_submit_control_for_completion",+ AsyncMock(return_value=True),+ raising=False,+ )+ context = SkyvernContext()+ action = ClickAction(element_id="E1", action_order=4)++ with skyvern_context.scoped(context):+ await handle_click_action(action, self._page(), MagicMock(), task, step)++ chain_click_mock.assert_awaited_once()+ sequential_mock.assert_awaited_once()+ assert context.submit_click_evidence[task.task_id][1:] == (2, 1, 4)++ @pytest.mark.asyncio+ async def test_disabled_coordinate_submit_click_is_not_recorded(self, monkeypatch: pytest.MonkeyPatch) -> None:+ now = datetime.now(UTC)+ organization = make_organization(now)+ task = make_task(now, organization)+ step = make_step(now, task, step_id="step-1", status=StepStatus.running, order=2, output=None)+ element = self._clickable_element(tag_name="button", type_value="submit")+ element.navigate_to_a_href = AsyncMock(return_value=False) # type: ignore[method-assign]+ element.get_locator().is_enabled = AsyncMock(return_value=False) # type: ignore[method-assign]+ dom = MagicMock()+ dom.safe_get_skyvern_element_by_id = AsyncMock(return_value=element)+ monkeypatch.setattr(handler_module, "DomUtil", MagicMock(return_value=dom))+ monkeypatch.setattr(handler_module, "get_or_create_wait_config", AsyncMock(return_value=MagicMock()))+ monkeypatch.setattr(handler_module.EventStrategyFactory, "move_cursor", AsyncMock())+ monkeypatch.setattr(+ handler_module.app.AGENT_FUNCTION,+ "is_submit_control_for_completion",+ AsyncMock(return_value=True),+ raising=False,+ )+ page = self._page()+ page.evaluate = AsyncMock(return_value="E1")+ page.mouse.click = AsyncMock()+ context = SkyvernContext()++ with skyvern_context.scoped(context):+ result = await handle_click_action(ClickAction(element_id="E1", x=10, y=10), page, MagicMock(), task, step)++ assert isinstance(result[-1], ActionSuccess)+ page.mouse.click.assert_awaited_once()+ element.get_locator().is_enabled.assert_awaited_once()+ assert task.task_id not in context.submit_click_evidence+class _FakePage:"""Minimal Playwright-page stand-in that records event listeners and can emitdiff --git a/tests/unit/test_failure_classifier.py b/tests/unit/test_failure_classifier.pyindex 55bc00fa4..89bc4c46f 100644--- a/tests/unit/test_failure_classifier.py+++ b/tests/unit/test_failure_classifier.py@@ -323,7 +323,7 @@ def test_words_that_merely_end_in_rate_are_not_a_site_throttle() -> None:[pytest.param("navigation block failed. failure reason: "- + str(ProviderLLMError("GEMINI_2_5_FLASH", cause=RateLimitError("Rate limit reached for the model"))),+ + str(ProviderLLMError("GEMINI_3_0_FLASH", cause=RateLimitError("Rate limit reached for the model"))),None,id="provider-error-text",),diff --git a/tests/unit/test_filter_user_defined_codes.py b/tests/unit/test_filter_user_defined_codes.pyindex d9e123208..203fedd7a 100644--- a/tests/unit/test_filter_user_defined_codes.py+++ b/tests/unit/test_filter_user_defined_codes.py@@ -60,15 +60,14 @@ def test_filter_handles_empty_errors_input() -> None:assert dropped == []-def test_filter_is_case_sensitive() -> None:- """Codes must match exactly — mapping is case-sensitive by design."""- errors = [_make_error("data_unavailable")]- mapping = {"DATA_UNAVAILABLE": "x"}+def test_filter_returns_the_mapping_key_for_a_case_variant_and_drops_an_ambiguous_one() -> None:+ errors = [_make_error("data_unavailable"), _make_error("Website_Down")]+ mapping = {"DATA_UNAVAILABLE": "x", "website_down": "y", "WEBSITE_DOWN": "z"}kept, dropped = filter_to_user_defined_codes(errors, mapping)- assert kept == []- assert dropped == ["data_unavailable"]+ assert [error.error_code for error in kept] == ["DATA_UNAVAILABLE"]+ assert dropped == ["Website_Down"]@pytest.mark.parametrize(diff --git a/tests/unit/test_image_token_estimator.py b/tests/unit/test_image_token_estimator.pyindex 48cee3cde..11774631e 100644--- a/tests/unit/test_image_token_estimator.py+++ b/tests/unit/test_image_token_estimator.py@@ -22,17 +22,17 @@ def _png(width: int, height: int) -> bytes:def test_empty_or_none_screenshots_are_zero() -> None:- assert estimate_image_tokens(None, "gemini-2.5-flash") == 0- assert estimate_image_tokens([], "gemini-2.5-flash") == 0+ assert estimate_image_tokens(None, "gemini-3-flash-preview") == 0+ assert estimate_image_tokens([], "gemini-3-flash-preview") == 0def test_gemini_tiling_scales_with_resolution() -> None:# 1920x1080 -> ceil(1920/768)=3 * ceil(1080/768)=2 = 6 tiles * 258- assert estimate_image_tokens([_png(1920, 1080)], "gemini-2.5-flash-lite") == 6 * 258+ assert estimate_image_tokens([_png(1920, 1080)], "gemini-3.1-flash-lite") == 6 * 258# 1280x720 -> 2 * 1 = 2 tiles * 258assert estimate_image_tokens([_png(1280, 720)], "vertex_ai/gemini-3-flash") == 2 * 258# both sides <= 384 -> flat 258- assert estimate_image_tokens([_png(300, 300)], "gemini-2.5-flash") == 258+ assert estimate_image_tokens([_png(300, 300)], "gemini-3-flash-preview") == 258def test_openai_tile_models_normalize_short_side_to_768() -> None:@@ -68,8 +68,8 @@ def test_anthropic_caps_large_images() -> None:def test_multiple_screenshots_sum() -> None:- one = estimate_image_tokens([_png(1280, 720)], "gemini-2.5-flash")- three = estimate_image_tokens([_png(1280, 720)] * 3, "gemini-2.5-flash")+ one = estimate_image_tokens([_png(1280, 720)], "gemini-3-flash-preview")+ three = estimate_image_tokens([_png(1280, 720)] * 3, "gemini-3-flash-preview")assert three == 3 * onediff --git a/tests/unit/test_llm_handler_parity_characterization.py b/tests/unit/test_llm_handler_parity_characterization.pyindex 09920682e..b0a672d4e 100644--- a/tests/unit/test_llm_handler_parity_characterization.py+++ b/tests/unit/test_llm_handler_parity_characterization.py@@ -698,31 +698,31 @@ async def test_zero_usage_records_none_token_fields_on_both(span_exporter: InMemasync def test_provider_prefixed_response_model(span_exporter: InMemorySpanExporter) -> None:direct = await _run_direct(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- model_name="gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ model_name="gemini-3-flash-preview",step=_make_step(),parameters={},)router = await _run_router(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- main_model_group="vertex-gemini-2.5-flash",- litellm_model="vertex_ai/gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ main_model_group="vertex-gemini-3-flash-preview",+ litellm_model="vertex_ai/gemini-3-flash-preview",step=_make_step(),parameters={},)assert direct.error is None and router.error is None# Both variants normalize the persisted model to the bare name.- assert direct.update_step_calls[0]["last_llm_model"] == "gemini-2.5-flash"- assert router.update_step_calls[0]["last_llm_model"] == "gemini-2.5-flash"+ assert direct.update_step_calls[0]["last_llm_model"] == "gemini-3-flash-preview"+ assert router.update_step_calls[0]["last_llm_model"] == "gemini-3-flash-preview"# drift: the router span/event record the raw provider-prefixed response.model while# the direct handler records the normalized bare name.- assert direct.span_attrs["llm_model"] == "gemini-2.5-flash"- assert direct.event_attrs["model"] == "gemini-2.5-flash"- assert router.span_attrs["llm_model"] == "vertex_ai/gemini-2.5-flash"- assert router.event_attrs["model"] == "vertex_ai/gemini-2.5-flash"+ assert direct.span_attrs["llm_model"] == "gemini-3-flash-preview"+ assert direct.event_attrs["model"] == "gemini-3-flash-preview"+ assert router.span_attrs["llm_model"] == "vertex_ai/gemini-3-flash-preview"+ assert router.event_attrs["model"] == "vertex_ai/gemini-3-flash-preview"@pytest.mark.parametrize(@@ -861,17 +861,17 @@ async def test_vertex_cache_attached_for_gemini_extract_actions(span_exporter: Idirect = await _run_direct(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- model_name="gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ model_name="gemini-3-flash-preview",context=cached_context(),prompt_name=EXTRACT_ACTION_PROMPT_NAME,parameters={},)router = await _run_router(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- main_model_group="vertex-gemini-2.5-flash",- litellm_model="vertex_ai/gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ main_model_group="vertex-gemini-3-flash-preview",+ litellm_model="vertex_ai/gemini-3-flash-preview",context=cached_context(),prompt_name=EXTRACT_ACTION_PROMPT_NAME,parameters={},@@ -884,8 +884,8 @@ async def test_vertex_cache_attached_for_gemini_extract_actions(span_exporter: Iassert len(router.completion_calls) == 1 and not router.router_callsassert direct.completion_calls[0]["cached_content"] == cache_nameassert router.completion_calls[0]["cached_content"] == cache_name- assert direct.completion_calls[0]["model"] == "gemini-2.5-flash"- assert router.completion_calls[0]["model"] == "vertex_ai/gemini-2.5-flash"+ assert direct.completion_calls[0]["model"] == "gemini-3-flash-preview"+ assert router.completion_calls[0]["model"] == "vertex_ai/gemini-3-flash-preview"assert direct.completion_calls[0]["timeout"] == settings.LLM_CONFIG_TIMEOUTassert router.completion_calls[0]["timeout"] == settings.LLM_CONFIG_TIMEOUT@@ -899,17 +899,17 @@ async def test_no_vertex_cache_when_prompt_caching_disabled(span_exporter: InMemdirect = await _run_direct(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- model_name="gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ model_name="gemini-3-flash-preview",context=uncached_context(),prompt_name=EXTRACT_ACTION_PROMPT_NAME,parameters={},)router = await _run_router(span_exporter,- responses=[ParityResponse("vertex_ai/gemini-2.5-flash")],- main_model_group="vertex-gemini-2.5-flash",- litellm_model="vertex_ai/gemini-2.5-flash",+ responses=[ParityResponse("vertex_ai/gemini-3-flash-preview")],+ main_model_group="vertex-gemini-3-flash-preview",+ litellm_model="vertex_ai/gemini-3-flash-preview",context=uncached_context(),prompt_name=EXTRACT_ACTION_PROMPT_NAME,parameters={},diff --git a/tests/unit/test_llm_prompt_config.py b/tests/unit/test_llm_prompt_config.pyindex 83eb7a055..b4087205c 100644--- a/tests/unit/test_llm_prompt_config.py+++ b/tests/unit/test_llm_prompt_config.py@@ -127,8 +127,8 @@ async def test_prompt_type_missing_from_config_returns_none_without_warning(These fall back to the default app handler; warning was incorrect."""config = {- "extract-information": "GEMINI_2_5_FLASH_WITH_FALLBACK",- "normal-select": "GEMINI_2_5_FLASH_WITH_FALLBACK",+ "extract-information": "GEMINI_3_0_FLASH_WITH_FALLBACK",+ "normal-select": "GEMINI_3_0_FLASH_WITH_FALLBACK",}monkeypatch.setattr(module,@@ -154,7 +154,7 @@ async def test_prompt_type_missing_from_config_returns_none_without_warning(@pytest.mark.asyncioasync def test_prompt_type_in_config_returns_handler(monkeypatch: pytest.MonkeyPatch) -> None:"""Config contains prompt type → LLMAPIHandlerFactory is called, handler returned."""- config = {"extract-information": "GEMINI_2_5_FLASH_WITH_FALLBACK"}+ config = {"extract-information": "GEMINI_3_0_FLASH_WITH_FALLBACK"}monkeypatch.setattr(module,"get_llm_config_by_prompt_type",diff --git a/tests/unit/test_org_auth_credential_clear_routes.py b/tests/unit/test_org_auth_credential_clear_routes.pyindex 50b57edc0..bfcd320cf 100644--- a/tests/unit/test_org_auth_credential_clear_routes.py+++ b/tests/unit/test_org_auth_credential_clear_routes.py@@ -1,18 +1,22 @@from collections.abc import Awaitable, Callable-from datetime import datetime, timezone+from datetime import UTC, datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import AsyncMock, callimport pytest-from fastapi import HTTPException+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClientfrom skyvern.forge.sdk.db.enums import OrganizationAuthTokenTypefrom skyvern.forge.sdk.routes import credentials as routesfrom skyvern.forge.sdk.schemas.organizations import (+ BitwardenCredential,+ BitwardenOrganizationAuthToken,CreateOnePasswordTokenRequest,Organization,OrganizationAuthToken,)+from skyvern.forge.sdk.services import org_auth_serviceclass FakeOrganizationsRepository:@@ -130,6 +134,54 @@ async def test_clear_org_auth_credential_succeeds_without_existing_token(assert len(fake_organizations.invalidate_calls) == 1[email protected]("redact", [True, False], ids=["status-only", "email-authorized"])+async def test_get_bitwarden_credential_redacts_email_without_vault_read(+ monkeypatch: pytest.MonkeyPatch,+ redact: bool,+) -> None:+ organization = _org()+ now = datetime.now(UTC)+ token = BitwardenOrganizationAuthToken(+ id="oat_bitwarden",+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.bitwarden_credential,+ valid=True,+ created_at=now,+ modified_at=now,+ credential=BitwardenCredential(email="[email protected]", master_password="test-password"),+ )+ get_token = AsyncMock(return_value=token)+ monkeypatch.setattr(+ routes.app,+ "DATABASE",+ SimpleNamespace(organizations=SimpleNamespace(get_valid_org_auth_token=get_token)),+ )+ should_redact = AsyncMock(return_value=redact)+ monkeypatch.setattr(routes, "_should_redact_org_credential_secrets", should_redact)+ app = FastAPI()+ app.add_api_route("/bitwarden", routes.get_bitwarden_credential, methods=["GET"])+ app.dependency_overrides[org_auth_service.get_current_org_for_credential_routes] = lambda: organization++ with TestClient(app) as client:+ response = client.get("/bitwarden")++ assert response.status_code == 200, response.text+ get_token.assert_awaited_once_with(+ organization_id=organization.organization_id,+ token_type=OrganizationAuthTokenType.bitwarden_credential.value,+ )+ should_redact.assert_awaited_once_with(organization.organization_id)+ if redact:+ redacted_token = response.json()["token"]+ assert set(redacted_token) == {"id", "token_type", "valid", "created_at", "modified_at"}+ assert redacted_token["id"] == "oat_bitwarden"+ assert redacted_token["token_type"] == OrganizationAuthTokenType.bitwarden_credential.value+ assert redacted_token["valid"] is True+ else:+ assert response.json()["token"]["credential"]["email"] == "[email protected]"++@pytest.mark.asyncioasync def test_clear_onepassword_without_existing_token_does_not_capture_success_event(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.pyindex e7edab0f4..b143cfd9b 100644--- a/tests/unit/test_otp_service.py+++ b/tests/unit/test_otp_service.py@@ -1345,7 +1345,7 @@ class TestParseOtpLogin:from skyvern.services import otp_serviceasync def failing_handler(*_args: object, **_kwargs: object) -> dict[str, object]:- raise LLMProviderError("gemini-2.5-flash")+ raise LLMProviderError("gemini-3-flash-preview")charge = AsyncMock()monkeypatch.setattr(otp_service.prompt_engine, "load_prompt", lambda *a, **k: "prompt")@@ -1401,7 +1401,7 @@ class TestParseOtpLogin:from skyvern.services import otp_serviceasync def failing_handler(*_args: object, **_kwargs: object) -> dict[str, object]:- raise LLMProviderError("gemini-2.5-flash")+ raise LLMProviderError("gemini-3-flash-preview")monkeypatch.setattr(otp_service.prompt_engine, "load_prompt", lambda *a, **k: "prompt")monkeypatch.setattr(otp_service.app, "SECONDARY_LLM_API_HANDLER", failing_handler, raising=False)diff --git a/tests/unit/test_pdf_fill_block.py b/tests/unit/test_pdf_fill_block.pyindex d107fe6a1..bde54a0c6 100644--- a/tests/unit/test_pdf_fill_block.py+++ b/tests/unit/test_pdf_fill_block.py@@ -25,6 +25,7 @@ from pypdf.generic import (from skyvern.forge import appfrom skyvern.forge.sdk.api import files+from skyvern.forge.sdk.utils.capped_subprocess import CappedSubprocessErrorfrom skyvern.forge.sdk.utils.tesseract_languages import tesseract_language_arg, tesseract_ocr_packagesfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.forge.sdk.workflow.models import pdf_fill_block@@ -383,6 +384,26 @@ def test_extract_field_labels_on_fillable_fixture(tmp_path: Path) -> None:assert isinstance(labels, dict)+def test_fields_keep_their_names_when_the_word_lookup_is_refused(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ source_pdf = tmp_path / "labelled.pdf"+ _write_fillable_pdf(source_pdf)+ lookups: list[object] = []++ def refuse_the_lookup(*args: object, **kwargs: object) -> None:+ lookups.append(args)+ raise CappedSubprocessError("returned more than the 32 MiB a result may hold", kind="result_too_large")++ monkeypatch.setattr(pdf_fill_block, "extract_upright_pdf_words", refuse_the_lookup)++ inventory = _make_block()._extract_field_inventory(PdfReader(str(source_pdf)), str(source_pdf))++ assert lookups+ assert set(inventory) == set(PdfReader(str(source_pdf)).get_fields())+ assert all(field.context_label == "" for field in inventory.values())++def test_checkbox_without_known_state_is_skipped_not_silently_unchecked() -> None:block = _make_block()inventory = {diff --git a/tests/unit/test_taskv3_auth_tools.py b/tests/unit/test_taskv3_auth_tools.pyindex d42bf4c74..b5833d61e 100644--- a/tests/unit/test_taskv3_auth_tools.py+++ b/tests/unit/test_taskv3_auth_tools.py@@ -33,7 +33,7 @@ from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager, Wfrom skyvern.forge.sdk.workflow.models.parameter import CredentialParameterfrom skyvern.forge.taskv3 import auth_toolsfrom skyvern.forge.taskv3 import loop as taskv3_loop-from skyvern.forge.taskv3.tools import OBSERVE_URL_MAX_CHARS+from skyvern.forge.taskv3.tools import NO_ONE_TIME_CODE_SOURCE, OBSERVE_URL_MAX_CHARSfrom skyvern.services import otp_servicefrom skyvern.services.otp_service import OTPValuefrom skyvern.utils.secret_redaction import redact_secrets_from_bytes@@ -56,18 +56,12 @@ def _task(**overrides: Any) -> SimpleNamespace:return SimpleNamespace(**base)-def test_build_auth_tools_absent_without_code_source(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)- tools, guidance = auth_tools.build_auth_tools(_task())- assert tools == [] and "get_verification_code" not in guidance--def test_build_auth_tools_bare_task_no_workflow_lookup() -> None:- # Unmocked: a bare task (workflow_run_id=None) with no code source returns no tool without any- # workflow-run-context lookup — has_credential_totp_candidate short-circuits on the falsy run id and- # never reaches the getter that raises when a context isn't registered.+ # Unmocked: a bare task (workflow_run_id=None) builds without any workflow-run-context lookup --+ # has_credential_totp_candidate short-circuits on the falsy run id and never reaches the getter+ # that raises when a context isn't registered.tools, guidance = auth_tools.build_auth_tools(_task())- assert tools == [] and "get_verification_code" not in guidance+ assert [t.name for t in tools] == ["get_verification_code"] and "get_verification_code" in guidancedef test_has_credential_totp_candidate_unregistered_context_returns_false(monkeypatch: pytest.MonkeyPatch) -> None:@@ -121,8 +115,8 @@ _OTP_SOURCE_CASES: list[tuple[str, dict[str, Any], bool]] = [async def test_build_auth_tools_offered_iff_resolve_otp_value_has_a_source(monkeypatch: pytest.MonkeyPatch, case: str, overrides: dict[str, Any], expected: bool) -> None:- # The offering condition and the resolver must not desync: the tool is offered exactly when- # resolve_otp_value yields a TOTP value or polls for one. Each row exercises both sides against+ # The tool's per-call source check and the resolver must not desync: has_otp_source is True exactly+ # when resolve_otp_value yields a TOTP value or polls for one. Each row exercises both sides against# the same task, so adding a source to one and not the other fails here.task = _task(**overrides)has_credential = case == "credential"@@ -147,7 +141,7 @@ async def test_build_auth_tools_offered_iff_resolve_otp_value_has_a_source(resolved = await otp_service.resolve_otp_value(task, expected_otp_type=OTPType.TOTP)resolver_has_source = poll.await_count > 0 or (resolved is not None and resolved.get_otp_type() == OTPType.TOTP)- assert (len(tools) == 1) is expected+ assert [t.name for t in tools] == ["get_verification_code"]assert resolver_has_source is expectedassert otp_service.has_otp_source(task, expected_otp_type=OTPType.TOTP) is expected@@ -158,8 +152,8 @@ async def test_get_verification_code_polling_budget_bounds_a_never_answering_sou) -> None:# A source that never answers must not let the model re-poll for N x the poll window: each call# polls for at most the per-call cap and returns "not yet", the cumulative polling is capped at- # VERIFICATION_CODE_POLLING_TIMEOUT_MINS, and once spent the tool refuses with stop guidance- # without awaiting the resolver again.+ # VERIFICATION_CODE_POLLING_TIMEOUT_MINS, and once spent the tool says so without awaiting the+ # resolver again.monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=1 / 60))monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)monkeypatch.setattr(auth_tools, "_MIN_SLICE_SECONDS", 0.0)@@ -180,8 +174,8 @@ async def test_get_verification_code_polling_budget_bounds_a_never_answering_souwith capture_logs() as logs:results = [await handler({}) for _ in range(30)]- not_yet = [r for r in results if "available yet" in r.content]- exhausted = [r for r in results if "budget exhausted" in r.content]+ not_yet = [r for r in results if "code has arrived yet" in r.content]+ exhausted = [r for r in results if r.content == auth_tools._CODE_BUDGET_SPENT]assert all(r.status == "error" for r in results)assert len(not_yet) >= 1 and not_yet[0] is results[0]assert len(exhausted) >= 2 and exhausted[-1] is results[-1]@@ -198,51 +192,6 @@ async def test_get_verification_code_polling_budget_bounds_a_never_answering_souassert all(cap <= 0.05 for cap in caps) and sum(caps) <= 1.0 + 0.05-async def test_verification_state_blocks_completion_only_when_the_budget_ran_dry_empty(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # A budget exhaustion that delivered nothing must block a completed verdict; a code delivered- # first (even from an otherwise-exhausted source) must not.- monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=1 / 60))- monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)- monkeypatch.setattr(auth_tools, "_MIN_SLICE_SECONDS", 0.0)-- async def _never_answers(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:- await asyncio.sleep(max_wait_seconds)- raise NoTOTPVerificationCodeFound(task_id="tsk_1")-- monkeypatch.setattr(auth_tools, "resolve_otp_value", _never_answers)- task = _task(totp_verification_url="https://totp.example")- state = auth_tools.VerificationState(task=task)- tools, _ = auth_tools.build_auth_tools(task, state=state)- handler = tools[0].handler-- result = None- for _ in range(30):- result = await handler({})- if "budget exhausted" in result.content:- break- assert result is not None and "budget exhausted" in result.content- assert await state.block_completion() == auth_tools._COMPLETION_BLOCKED-- delivered_task = _task(totp_identifier="[email protected]")- delivered_state = auth_tools.VerificationState(task=delivered_task)- monkeypatch.setattr(- auth_tools, "resolve_otp_value", AsyncMock(return_value=OTPValue(value="123456", type=OTPType.TOTP))- )- delivered_tools, _ = auth_tools.build_auth_tools(delivered_task, state=delivered_state)- ctx = SkyvernContext(task_id="tsk_1")- skyvern_context.set(ctx)- try:- delivered_result = await delivered_tools[0].handler({})- finally:- skyvern_context.reset()- assert delivered_result.status == "ok"- delivered_state.arm(auth_tools.VerificationFailure.NO_CODE_TWICE, "get_verification_code")- assert await delivered_state.block_completion() is None--@pytest.mark.asyncio@pytest.mark.parametrize("case",@@ -259,12 +208,11 @@ async def test_verification_state_blocks_completion_only_when_the_budget_ran_dry"webhook_failing_streak",],)-async def test_verification_state_blocks_completion_after_a_refused_or_errored_source(+async def test_only_a_terminal_link_answer_refuses_a_completed_verdict(monkeypatch: pytest.MonkeyPatch, case: str) -> None:- # Every terminal non-delivery answer must arm the finish gate, not only budget exhaustion: a source- # that keeps erroring or returning nothing, or hands over a link the browser could not be sent to,- # has delivered nothing, so a completed verdict after it is the same false completion.+ # A link the source never sent, or one the browser could not be sent to, refuses a completed verdict.+ # The code tool's answers never do: it reports, and the model decides with the page in front of it.monkeypatch.setattr(auth_tools,"settings",@@ -318,8 +266,8 @@ async def test_verification_state_blocks_completion_after_a_refused_or_errored_scode_tool = case in {"lookup_error_streak", "no_code_streak", "webhook_failing_streak"}handler = handlers["get_verification_code" if code_tool else "open_verification_link"]expected = {- "lookup_error_streak": "lookup failed: RuntimeError repeatedly",- "no_code_streak": auth_tools._NO_CODE_AVAILABLE,+ "lookup_error_streak": "returned an error (verification lookup failed: RuntimeError)",+ "no_code_streak": "no verification code has arrived yet","no_link_streak": auth_tools._NO_LINK_AVAILABLE,"page_unavailable": auth_tools._PAGE_UNAVAILABLE,"link_rejected": "rejected the sign-in link (HTTP 410)",@@ -327,20 +275,20 @@ async def test_verification_state_blocks_completion_after_a_refused_or_errored_s"link_unvalidatable": "nothing was signed in","link_unreachable": "nothing was signed in","link_unreachable_while_origin_page_keeps_fetching": "nothing was signed in",- "webhook_failing_streak": "kept failing (FailedToGetTOTPVerificationCode: HTTP 500)",+ "webhook_failing_streak": "returned an error (FailedToGetTOTPVerificationCode: HTTP 500)",}[case]- assert await state.block_completion() is None+ assert await state.block_finish("completed") is Noneresult = await handler({})assert result.status == "error"if case.endswith("_streak"):# A single empty answer is a blip, not a verdict on the source; the second in a row is.- assert "again" in result.content and "trigger it first" not in result.content- assert await state.block_completion() is None+ assert await state.block_finish("completed") is Noneresult = await handler({})assert result.status == "error"assert expected in result.content- assert await state.block_completion() == auth_tools._COMPLETION_BLOCKED+ expected_refusal = None if code_tool else auth_tools._COMPLETION_BLOCKED+ assert await state.block_finish("completed") == expected_refusal# Every condition the module can arm with, and the record each must produce. `source_failed` is written@@ -460,10 +408,8 @@ async def test_every_arming_narrates_the_condition_that_armed_the_latch(monkeypatch: pytest.MonkeyPatch, case: str, reason: str, tool: str, records: int) -> None:# V1 narrates this failure with the org and the identifier attached- # (skyvern/forge/agent.py, "TOTP polling timed out — terminating task"); V3 latched a completion- # refusal and said nothing, so a run that died on a silent verification source could not be found- # in production at all. Every arming must now emit exactly one record naming WHICH condition armed- # it — "the latch armed" without the reason does not answer the question support actually asks.+ # (skyvern/forge/agent.py, "TOTP polling timed out — terminating task"). Every arming must emit+ # exactly one record naming WHICH condition armed it.task = _task(totp_verification_url="https://totp.example/poll?key=abc",totp_identifier="[email protected]",@@ -475,12 +421,12 @@ async def test_every_arming_narrates_the_condition_that_armed_the_latch(with capture_logs() as logs:for _ in range(calls):- # The cached-magic-link site is only reachable on a call AFTER the latch already armed.- if state.source_failed and case != "magic_link_unsupported_cached":+ armed = any(entry.get("event") == "task_v3 verification source failed" for entry in logs)+ # The cached-magic-link site is only reachable on a call AFTER the first arming.+ if armed and case != "magic_link_unsupported_cached":breakawait handler({})- assert state.source_failed, f"{case} did not arm the latch, so it proves nothing about narration"armings = [entry for entry in logs if entry.get("event") == "task_v3 verification source failed"]assert len(armings) == records, f"{case} emitted {len(armings)} records, expected {records}"record = armings[-1]@@ -491,8 +437,8 @@ async def test_every_arming_narrates_the_condition_that_armed_the_latch(assert type(record["reason"]) is strassert record["tool"] == toolassert record["log_level"] == "warning"- # Nothing was delivered in any of these, so every one of them blocks a completed verdict.assert record["values_delivered"] == 0+ assert state.link_failed is (tool == _LINK_TOOL)# The identifying fields V1 carries, so the two engines' failures are triaged the same way. These# are the raw kwargs: `capture_logs` swaps out the processor chain, so what production actually# renders is pinned by test_the_rendered_record_masks_the_identifier_and_keeps_the_endpoint.@@ -536,9 +482,7 @@ async def test_every_arming_is_counted_not_collapsed(monkeypatch: pytest.MonkeyP@pytest.mark.asyncioasync def test_an_arming_a_later_delivery_unblocks_is_still_narrated(monkeypatch: pytest.MonkeyPatch) -> None:# `values_delivered` on the record is the count at THAT arming, not a verdict on the run: a value- # arriving afterwards unblocks the completed verdict and writes no record of its own. The event- # says the source failed, which stays true — but a reader treating the field as "this run was- # blocked" would be wrong, so the direction is pinned here rather than left to the comment.+ # arriving afterwards writes no record of its own, and clears the status the run would fail with.task = _task(totp_verification_url="https://totp.example")state = auth_tools.VerificationState(task=task)monkeypatch.setattr(@@ -566,56 +510,52 @@ async def test_an_arming_a_later_delivery_unblocks_is_still_narrated(monkeypatcharmings = [entry for entry in logs if entry.get("event") == "task_v3 verification source failed"]assert [entry["values_delivered"] for entry in armings] == [0]- assert delivered.status == "ok"- assert state.source_failed is True and await state.block_completion() is None+ assert delivered.status == "ok" and state.last_status is None- # The other order is the one the field exists to separate: a source that delivered and THEN failed- # arms, narrates, and does not block. Without this the field is only ever observed as 0, so a- # regression to a constant would read as green.+ # The other order is the one the field exists to separate. Without this the field is only ever+ # observed as 0, so a regression to a constant would read as green.monkeypatch.setattr(auth_tools, "resolve_otp_value", AsyncMock(return_value=None))with capture_logs() as after_delivery:await handler({})await handler({})late = [entry for entry in after_delivery if entry.get("event") == "task_v3 verification source failed"]assert [entry["values_delivered"] for entry in late] == [1]- assert await state.block_completion() is None+ assert await state.block_finish("completed") is Nonedef test_the_latch_cannot_be_armed_without_narrating_a_named_condition() -> None:- # The coverage claim is structural, not an inventory: `source_failed` is derived from the recorded- # armings rather than settable on its own, the arming list is not an __init__ parameter, and the- # reason is a closed type rather than a string. A future site therefore cannot latch silently. The- # inventory has already been wrong once (by six sites), which is why this is enforced, not documented.+ # `link_failed` is derived from the recorded armings rather than settable on its own, the arming+ # list is not an __init__ parameter, and the reason is a closed type, so no site can latch silently.state = auth_tools.VerificationState(task=_task(navigation_payload={"ssn": "000-00-0000"}))- assert state.source_failed is False- # `block_completion` is handed to the loop as a bound method, so anything formatting that callback+ # `block_finish` is handed to the loop as a bound method, so anything formatting that callback# renders this repr; the task must not be in it.- assert "ssn" not in repr(state) and "ssn" not in repr(state.block_completion)+ assert "ssn" not in repr(state) and "ssn" not in repr(state.block_finish)with pytest.raises(AttributeError):- state.source_failed = True # type: ignore[misc]+ state.link_failed = True # type: ignore[misc]with pytest.raises(TypeError):auth_tools.VerificationState(task=_task(), _armings=[]) # type: ignore[call-arg]- assert state.source_failed is Falsewith capture_logs() as logs:+ state.arm(auth_tools.VerificationFailure.NO_CODE_TWICE, "get_verification_code")+ assert state.link_failed is Falsestate.arm(auth_tools.VerificationFailure.PAGE_UNAVAILABLE, "open_verification_link")- assert state.source_failed is True+ assert state.link_failed is Trueassert [entry["reason"] for entry in logs if entry.get("event") == "task_v3 verification source failed"] == [- "page_unavailable"+ "no_code_twice",+ "page_unavailable",]def test_narration_never_costs_the_tool_its_answer(monkeypatch: pytest.MonkeyPatch) -> None:# A record that could raise would leave the latch set, the failure unnarrated, and the model- # holding a bare tool_error instead of the "finish as failed" guidance — the exact silent failure- # this whole change removes, reintroduced by the fix for it. Behaviour outranks observability.+ # holding a bare tool_error instead of the tool's status. Behaviour outranks observability.def _explode(*_args: Any, **_kwargs: Any) -> None:raise RuntimeError("log pipeline down")monkeypatch.setattr(auth_tools.LOG, "warning", _explode)state = auth_tools.VerificationState(task=_task())- state.arm(auth_tools.VerificationFailure.BUDGET_EXHAUSTED, "get_verification_code")- assert state.source_failed is True+ state.arm(auth_tools.VerificationFailure.LINK_REFUSED, "open_verification_link")+ assert state.link_failed is Truedef test_a_polling_url_the_parser_rejects_costs_the_field_not_the_record() -> None:@@ -679,45 +619,6 @@ def test_every_condition_the_module_can_arm_with_is_covered_by_a_driven_case() -assert {reason for _case, reason, _tool, _records in _ARMING_CASES} == set(auth_tools.VerificationFailure)-async def test_verification_state_does_not_block_after_a_retryable_not_yet(monkeypatch: pytest.MonkeyPatch) -> None:- # "Not yet" and a lone lookup error are retryable, not a source failure: a speculative poll on a- # page that never ends up asking for a code must not turn a legitimate completion into a failure.- # A later delivery also disarms a gate an error streak had armed.- monkeypatch.setattr(- auth_tools,- "settings",- SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=5, BROWSER_LOADING_TIMEOUT_MS=1000),- )- monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)- task = _task(totp_verification_url="https://totp.example")- state = auth_tools.VerificationState(task=task)- answers: list[Any] = [- NoTOTPVerificationCodeFound(task_id="tsk_1"),- RuntimeError("boom"),- NoTOTPVerificationCodeFound(task_id="tsk_1"),- RuntimeError("boom"),- RuntimeError("boom"),- OTPValue(value="123456", type=OTPType.TOTP),- ]- monkeypatch.setattr(auth_tools, "resolve_otp_value", AsyncMock(side_effect=answers))- tools, _ = auth_tools.build_auth_tools(task, state=state)- handler = tools[0].handler-- assert "available yet" in (await handler({})).content- assert await state.block_completion() is None- assert "lookup failed" in (await handler({})).content- assert await state.block_completion() is None- # A healthy answer in between resets the streak.- assert "available yet" in (await handler({})).content- assert "lookup failed" in (await handler({})).content- assert await state.block_completion() is None- assert "lookup failed" in (await handler({})).content- assert await state.block_completion() == auth_tools._COMPLETION_BLOCKED- assert (await handler({})).status == "ok"- assert await state.block_completion() is None--@pytest.mark.asyncioasync def test_lookup_error_streak_resets_on_a_usable_answer_that_is_not_a_delivery(monkeypatch: pytest.MonkeyPatch,@@ -744,11 +645,13 @@ async def test_lookup_error_streak_resets_on_a_usable_answer_that_is_not_a_deliv)handlers = {t.name: t.handler for t in tools}- assert "lookup failed" in (await handlers["get_verification_code"]({})).content- assert (await handlers["get_verification_code"]({})).content == auth_tools._MAGIC_LINK_REDIRECT- assert "failed to open" in (await handlers["open_verification_link"]({})).content- assert "lookup failed" in (await handlers["get_verification_code"]({})).content- assert await state.block_completion() is None+ with capture_logs() as logs:+ assert "lookup failed" in (await handlers["get_verification_code"]({})).content+ assert (await handlers["get_verification_code"]({})).content == auth_tools._MAGIC_LINK_REDIRECT+ assert "failed to open" in (await handlers["open_verification_link"]({})).content+ assert "lookup failed" in (await handlers["get_verification_code"]({})).content+ assert [e for e in logs if e.get("event") == "task_v3 verification source failed"] == []+ assert await state.block_finish("completed") is None@pytest.mark.asyncio@@ -809,7 +712,7 @@ async def test_open_verification_link_failure_after_a_possible_sign_in_keeps_comresult = await handler({})assert result.status == "error" and expected in result.content- assert await state.block_completion() is None+ assert await state.block_finish("completed") is None@pytest.mark.asyncio@@ -833,8 +736,9 @@ async def test_get_verification_code_tail_shorter_than_a_poll_interval_counts_astools, _ = auth_tools.build_auth_tools(_task(totp_verification_url="https://totp.example"))first = await tools[0].handler({})second = await tools[0].handler({})- assert "available yet" in first.content and "http_status=204x3" in first.content- assert "budget exhausted" in second.content+ assert "returned an error" in first.content and "http_status=204x3" in first.content+ assert "no polling time remains" in first.content+ assert second.content == auth_tools._CODE_BUDGET_SPENTassert resolver_calls == 1@@ -860,8 +764,8 @@ async def test_get_verification_code_slices_share_the_first_polls_email_anchor(@pytest.mark.asyncioasync def test_get_verification_code_inner_timeout_does_not_spend_the_budget(monkeypatch: pytest.MonkeyPatch) -> None:- # A timeout raised inside the resolver (DB, HTTP) reads as a lookup failure, not as this tool's- # wait cap or budget exhaustion: the first invites a retry, the second in a row is terminal.+ # A timeout raised inside the resolver (DB, HTTP) reads as a source error, not as this tool's wait+ # cap or budget exhaustion.async def _inner_timeout(*_a: Any, **_k: Any) -> OTPValue | None:raise TimeoutError("pool acquire")@@ -869,8 +773,8 @@ async def test_get_verification_code_inner_timeout_does_not_spend_the_budget(montools, _ = auth_tools.build_auth_tools(_task(totp_verification_url="https://totp.example"))first = await tools[0].handler({})second = await tools[0].handler({})- assert "lookup failed: TimeoutError" in first.content and "call get_verification_code again" in first.content- assert "lookup failed: TimeoutError repeatedly" in second.content+ for result in (first, second):+ assert "lookup failed: TimeoutError" in result.content and "minutes of polling time remain" in result.contentdef test_build_auth_tools_present_with_totp_identifier() -> None:@@ -888,22 +792,6 @@ def test_build_auth_tools_present_with_payload_only_totp_source(monkeypatch: pytassert "verification code" in guidance.lower()-def test_build_auth_tools_absent_with_no_code_source_at_all(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)- tools, guidance = auth_tools.build_auth_tools(_task(navigation_payload={"unrelated_field": "value"}))- assert tools == [] and "get_verification_code" not in guidance---def test_build_auth_tools_absent_with_magic_link_only_payload_source(monkeypatch: pytest.MonkeyPatch) -> None:- # A payload-embedded URL resolves to a magic link, not a TOTP code; get_verification_code hard-rejects- # non-TOTP values, so offering the tool here would be guaranteed to error.- monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)- tools, guidance = auth_tools.build_auth_tools(- _task(navigation_payload={"verification_link": "https://example.test/x"})- )- assert tools == [] and "get_verification_code" not in guidance--@pytest.mark.asyncioasync def test_get_verification_code_resolves_and_registers_for_redaction(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(@@ -937,9 +825,9 @@ async def test_get_verification_code_no_code_returns_error(monkeypatch: pytest.M@pytest.mark.asyncioasync def test_get_verification_code_fails_fast_on_a_magic_link(monkeypatch: pytest.MonkeyPatch) -> None:- # A sign-in link is not a code and this engine cannot follow it: the tool must say so on the first- # call (not burn the poll budget as "no code yet"), count it with one structured warning, and never- # let the URL reach the model, the logs, or the secret registry.+ # A sign-in link is not a code and a page-free run cannot follow it: the tool must say so on the+ # first call (not burn the poll budget as "no code yet"), count it with one structured warning, and+ # never let the URL reach the model, the logs, or the secret registry.link = "https://example.com/signin?token=abc"resolver = AsyncMock(return_value=OTPValue(value=link, type=None))monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)@@ -952,7 +840,7 @@ async def test_get_verification_code_fails_fast_on_a_magic_link(monkeypatch: pytsecond = await tools[0].handler({})finally:skyvern_context.reset()- assert first.status == "error" and "sign-in link" in first.content and "finish" in first.content+ assert first.status == "error" and "sign-in link" in first.content and "returned an error" in first.contentassert second.content == first.content and resolver.await_count == 1assert link not in first.content and "token=abc" not in str(logs)warnings = [e for e in logs if e.get("event") == "task_v3 verification source returned a magic link"]@@ -1153,19 +1041,25 @@ async def test_a_sign_in_link_poll_never_waits_on_a_credential_totp_window(monke@pytest.mark.asyncio@pytest.mark.parametrize(- ("seed", "owned_by_credential"),- [(None, True), ("not a totp secret!", True), (_VALID_SEED, False)],- ids=["no_secret", "unparseable_secret", "no_owning_credential"],+ ("seed", "owned_by_credential", "polling_source"),+ [+ (None, True, False),+ ("not a totp secret!", True, False),+ (_VALID_SEED, False, False),+ (None, True, True),+ ],+ ids=["no_secret", "unparseable_secret", "no_owning_credential", "no_secret_but_a_polling_source"],)-async def test_a_totp_placeholder_with_no_usable_source_is_refused_and_recorded(- monkeypatch: pytest.MonkeyPatch, seed: str | None, owned_by_credential: bool+async def test_a_totp_placeholder_with_no_usable_secret_is_refused_as_no_source_only_when_the_task_has_none(+ monkeypatch: pytest.MonkeyPatch, seed: str | None, owned_by_credential: bool, polling_source: bool) -> None:_clock_in_step(monkeypatch, 3)run_context = _credential_totp_context(seed=seed)if not owned_by_credential:run_context.values["login"] = {}_install_run(monkeypatch, run_context)- state = auth_tools.VerificationState(task=_task(workflow_run_id="wr_test"))+ task = _task(workflow_run_id="wr_test", totp_verification_url="https://totp.example" if polling_source else None)+ state = auth_tools.VerificationState(task=task)ctx = SkyvernContext(task_id="tsk_1", workflow_run_id="wr_test")skyvern_context.set(ctx)try:@@ -1173,29 +1067,26 @@ async def test_a_totp_placeholder_with_no_usable_source_is_refused_and_recorded(await state.resolve_totp_placeholder(_TOTP_FIELD)finally:skyvern_context.reset()- assert state.totp_source_missing is True+ if polling_source:+ assert str(excinfo.value) == auth_tools._CREDENTIAL_HAS_NO_CODE_SECRET+ assert "can be fetched" not in str(excinfo.value)+ assert state.last_status is None+ else:+ assert str(excinfo.value) == NO_ONE_TIME_CODE_SOURCE+ assert state.last_status == NO_ONE_TIME_CODE_SOURCEassert state.values_delivered == 0assert ctx.runtime_secret_values == set()- assert "Never invent or guess a code" in str(excinfo.value)assert _TOTP_FIELD not in str(excinfo.value) and _TOTP_FIELD not in str(logs)assert "BW_TOTP" not in str(excinfo.value) and "BW_TOTP" not in str(logs)-def test_the_never_invent_guidance_reaches_a_run_offered_no_code_tool(monkeypatch: pytest.MonkeyPatch) -> None:- # The rule that keeps a model from typing a made-up code must not depend on a code source being- # configured -- that is exactly the run with no real code to type. It must not point at a tool- # the run was not given, and must stay true on a run whose credential placeholder still yields a- # code without the tool (several TOTP credentials, none pinned), so it names that placeholder.+def test_the_guidance_is_one_line_whatever_code_source_the_run_has(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)- tools, guidance = auth_tools.build_auth_tools(_task())- assert tools == []- assert "Never invent or guess a code" in guidance- assert "get_verification_code" not in guidance- assert "TOTP placeholder" in guidance- assert "No verification-code source is configured" not in guidance- offered_tools, offered_guidance = auth_tools.build_auth_tools(_task(totp_identifier="[email protected]"))- assert [t.name for t in offered_tools] == ["get_verification_code"]- assert "Never invent or guess a code" in offered_guidance and "get_verification_code" in offered_guidance+ _, without_source = auth_tools.build_auth_tools(_task())+ _, with_source = auth_tools.build_auth_tools(_task(totp_identifier="[email protected]"))+ assert without_source == with_source == auth_tools._GUIDANCE+ assert "Never invent or guess a code" in with_source and "get_verification_code" in with_source+ assert "finish" not in with_sourcedef test_get_secret_values_for_run_standalone_task_respects_disabled_global_artifact_redaction(@@ -1792,7 +1683,7 @@ async def test_code_tool_hands_a_stored_run_scoped_sign_in_link_to_the_link_toolassert redirect.status == "error" and redirect.content == auth_tools._MAGIC_LINK_REDIRECTassert opened.status == "ok"- assert "available yet" in after_open.content+ assert "code has arrived yet" in after_open.contentassert page.goto_calls == [_RESENT_ACTIVATION_LINK]@@ -1842,13 +1733,13 @@ async def test_code_tool_called_again_instead_of_opening_the_link_polls_for_a_copytest.param([_stored_row("otp_link", _ACTIVATION_LINK, OTPType.MAGIC_LINK, _TASK_CREATED_AT - timedelta(seconds=60))],True,- "available yet",+ "code has arrived yet",id="run_scoped_link_from_before_this_task",),pytest.param([_stored_row("otp_link", _ACTIVATION_LINK, OTPType.MAGIC_LINK, _TASK_CREATED_AT + timedelta(seconds=40))],False,- "available yet",+ "code has arrived yet",id="page_free_run_cannot_open_a_link",),],@@ -1861,7 +1752,7 @@ async def test_code_tool_never_redirects_to_a_stored_link_this_task_must_not_fol# or a terminal "unsupported link", and a code the page asked for is still delivered.page = _FakePage()handlers = _stored_code_tools(monkeypatch, rows, page, page_offered=page_offered)- if expected == "available yet":+ if expected == "code has arrived yet":monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", _TIMEOUT_SLICE_SECONDS)skyvern_context.set(SkyvernContext(task_id="tsk_1"))try:@@ -1895,7 +1786,7 @@ async def test_verification_tools_share_one_polling_budget(monkeypatch: pytest.Massert "budget exhausted" in spent.contentcalls_after_link_tool = resolver_callscode_result = await handlers["get_verification_code"]({})- assert code_result.status == "error" and "budget exhausted" in code_result.content+ assert code_result.status == "error" and code_result.content == auth_tools._CODE_BUDGET_SPENTassert resolver_calls == calls_after_link_tool@@ -1918,75 +1809,224 @@ def test_block_credential_parameter_keys_script_mode_returns_none(monkeypatch: passert agent_module.block_credential_parameter_keys(NS(parameters=[]), "wr_test") == [][email protected]("awaiting", [True, False], ids=["awaiting", "not_awaiting"])[email protected]("armed", [True, False], ids=["source_failed", "source_healthy"])[email protected]("stale", [True, False], ids=["stale", "recent"])[email protected]("spent", [True, False], ids=["budget_spent", "budget_left"])+_ORDER_WORDS = re.compile(r"\b(finish|call|do not|don't|must|should|trigger)\b", re.IGNORECASE)+++def _two_credential_context(*, seed_a: str | None, seed_b: str | None) -> WorkflowRunContext:+ workflow_run_context = WorkflowRunContext(+ workflow_title="t",+ workflow_id="w_test",+ workflow_permanent_id="wp_test",+ workflow_run_id="wr_test",+ aws_client=MagicMock(),+ )+ for key, seed in (("cred_a", seed_a), ("cred_b", seed_b)):+ placeholder = f"placeholder_{key}_totp"+ workflow_run_context.parameters[key] = _credential_parameter(key)+ workflow_run_context.values[key] = {"totp": placeholder}+ workflow_run_context.secrets[placeholder] = "BW_TOTP"+ if seed is not None:+ workflow_run_context.secrets[workflow_run_context.totp_secret_value_key(placeholder)] = seed+ return workflow_run_context+++_STATUS_CASES: list[tuple[str, Any, str]] = [+ ("empty_answer_from_a_working_source", None, "no verification code has arrived yet; about"),+ ("timed_out_slice", NoTOTPVerificationCodeFound(task_id="tsk_1"), "no verification code has arrived yet; about"),+ (+ "webhook_answering_http_500",+ NoTOTPVerificationCodeFound(task_id="tsk_1", webhook_diagnostics="http_status=500x12"),+ "returned an error (NoTOTPVerificationCodeFound: http_status=500x12); about",+ ),+ (+ "transport_error",+ FailedToGetTOTPVerificationCode(task_id="tsk_1", reason="request failed exception_type=ConnectError"),+ "returned an error (FailedToGetTOTPVerificationCode: request failed exception_type=ConnectError); about",+ ),+ ("lookup_raised", RuntimeError("boom"), "returned an error (verification lookup failed: RuntimeError); about"),+ (+ "link_with_no_link_tool",+ OTPValue(value="https://example.test/magic?token=abc", type=OTPType.MAGIC_LINK),+ "returned an error (it sent a sign-in link, which this run cannot open); about",+ ),+]++@pytest.mark.asyncio-async def test_giveup_gate_holds_exactly_while_awaiting_a_code_it_has_budget_for(- awaiting: bool, armed: bool, stale: bool, spent: bool[email protected](("case", "answer", "expected"), _STATUS_CASES, ids=[c[0] for c in _STATUS_CASES])+async def test_each_code_tool_answer_is_one_plain_status_the_run_keeps_as_its_last(+ monkeypatch: pytest.MonkeyPatch, case: str, answer: Any, expected: str) -> None:- # The invariant in one sentence: a non-complete finish is held exactly while the run is actively- # awaiting a verification code it has purchased-but-unspent budget for. The four conjuncts are- # that sentence's operationalization, so this asserts the BICONDITIONAL over the whole- # (awaiting, armed, recency, spend) space rather than four example negative controls -- an- # enumerated field list cannot close a class, and a conjunct silently dropped from the gate would- # leave every example that does not exercise it green.- state = auth_tools.VerificationState(task=_task())- state.budget_seconds = 900.0- state.polling_spent_seconds = 900.0 - (auth_tools._MIN_SLICE_SECONDS / 2 if spent else 600.0)- if awaiting:- state.awaiting_code_since = time.monotonic() - (auth_tools._NOT_YET_RECENCY_SECONDS + 1 if stale else 0.0)- if armed:- # Through `arm`, not by poking the latch: it is the only way the latch is reachable in- # production, so a state built any other way would not be one this gate can actually see.- state.arm(auth_tools.VerificationFailure.NO_CODE_TWICE, "get_verification_code")+ monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))+ resolver = AsyncMock(side_effect=answer) if isinstance(answer, Exception) else AsyncMock(return_value=answer)+ monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)- should_hold = awaiting and not armed and not stale and not spent- message = await state.block_giveup("failed")+ result = await tools[0].handler({})- assert (message is not None) is should_hold- if should_hold:- assert "get_verification_code" in message- # It must send the model back to the TOOL, not onto the page: holding a `terminated` verdict- # keeps a run alive on a page the model declared blocked, and the hold must not widen that.- assert "do not act on the page" in message- # A completed verdict is a separate question the same primitive answers, and unspent budget is- # never a reason to refuse one.- assert await state.block_finish("completed") == await state.block_completion()- assert await state.block_finish("failed") == await state.block_giveup("failed")+ assert result.status == "error" and expected in result.content+ assert not _ORDER_WORDS.search(result.content)+ assert state.last_status == result.content+ assert await state.block_finish("completed") is None@pytest.mark.asyncio[email protected]("asked", ["awaiting", "source_missing", "none"])-async def test_a_reask_conversion_is_refused_while_a_requested_code_was_never_delivered(asked: str) -> None:- # A code awaited or refused for want of a source is not source_failed, so block_completion lets it through.- state = auth_tools.VerificationState(task=_task())- if asked == "awaiting":- state.awaiting_code_since = time.monotonic()- elif asked == "source_missing":- state.totp_source_missing = True- assert await state.block_completion() is None+async def test_a_spent_polling_budget_is_reported_without_polling_again(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))+ resolver = AsyncMock(return_value=None)+ monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)+ state.polling_spent_seconds = state.budget_seconds- blocked = await state.block_finish(taskv3_loop.CONVERSION_VERIFICATION_STATUS)+ result = await tools[0].handler({})- assert (blocked is not None) is (asked != "none")- state.record_delivery("get_verification_code")- assert await state.block_finish(taskv3_loop.CONVERSION_VERIFICATION_STATUS) is None+ assert result.content == auth_tools._CODE_BUDGET_SPENT and not _ORDER_WORDS.search(result.content)+ assert state.last_status == auth_tools._CODE_BUDGET_SPENT+ resolver.assert_not_awaited()+++async def test_a_source_that_answers_at_once_still_spends_the_polling_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=1))+ resolver = AsyncMock(return_value=None)+ monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)++ answers = [(await tools[0].handler({})).content for _ in range(8)]++ assert answers[-1] == auth_tools._CODE_BUDGET_SPENT+ assert resolver.await_count <= 60 / auth_tools._MIN_SLICE_SECONDS+++ "case",+ [+ "bare_task_with_no_source",+ "magic_link_only_payload",+ "credential_seed_unusable",+ "two_credentials_no_usable_seed",+ ],+)+async def test_a_run_with_no_code_source_is_told_so_at_once_without_polling(+ monkeypatch: pytest.MonkeyPatch, case: str+) -> None:+ resolver = AsyncMock(return_value=OTPValue(value="123456", type=OTPType.TOTP))+ monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)+ task = _task()+ if case == "magic_link_only_payload":+ task = _task(navigation_payload={"verification_link": "https://example.test/x"})+ elif case == "credential_seed_unusable":+ _install_run(monkeypatch, _credential_totp_context(seed="not a totp secret!"))+ task = _task(workflow_run_id="wr_test")+ elif case == "two_credentials_no_usable_seed":+ _install_run(monkeypatch, _two_credential_context(seed_a=None, seed_b="not a totp secret!"))+ task = _task(workflow_run_id="wr_test")+ state = auth_tools.VerificationState(task=task)+ tools, guidance = auth_tools.build_auth_tools(task, state=state)+ skyvern_context.set(SkyvernContext(task_id="tsk_1", workflow_run_id=task.workflow_run_id))+ try:+ result = await tools[0].handler({})+ finally:+ skyvern_context.reset()++ assert [t.name for t in tools] == ["get_verification_code"] and "get_verification_code" in guidance+ assert result.status == "error" and result.content == NO_ONE_TIME_CODE_SOURCE+ assert state.last_status == NO_ONE_TIME_CODE_SOURCE+ assert state.polling_spent_seconds == 0.0+ resolver.assert_not_awaited()++[email protected]("seed_b", [_VALID_SEED, None], ids=["both_seeded", "one_seeded"])+async def test_several_code_credentials_with_none_in_use_are_not_reported_as_no_code_source(+ monkeypatch: pytest.MonkeyPatch, seed_b: str | None+) -> None:+ resolver = AsyncMock(return_value=OTPValue(value="123456", type=OTPType.TOTP))+ monkeypatch.setattr(auth_tools, "resolve_otp_value", resolver)+ _install_run(monkeypatch, _two_credential_context(seed_a=_VALID_SEED, seed_b=seed_b))+ task = _task(workflow_run_id="wr_test")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)+ skyvern_context.set(SkyvernContext(task_id="tsk_1", workflow_run_id="wr_test"))+ try:+ result = await tools[0].handler({})+ refusal = None+ if seed_b is None:+ with pytest.raises(taskv3_loop.ToolRefusal) as refused:+ await state.resolve_totp_placeholder("placeholder_cred_b_totp")+ refusal = str(refused.value)+ finally:+ skyvern_context.reset()++ assert result.status == "error" and result.content == auth_tools._CODE_CREDENTIAL_NOT_IN_USE+ assert state.last_status != NO_ONE_TIME_CODE_SOURCE+ assert refusal == (None if seed_b else auth_tools._CREDENTIAL_HAS_NO_CODE_SECRET)+ assert state.polling_spent_seconds == 0.0+ resolver.assert_not_awaited()@pytest.mark.asyncio-async def test_a_not_yet_answer_arms_the_giveup_gate_and_says_what_budget_is_left(+async def test_the_code_source_is_judged_per_call_as_the_active_credential_changes(monkeypatch: pytest.MonkeyPatch,) -> None:- # Untestable through the scripted loop test, which finishes regardless of what the tool returned.- # The old message gave no indication that any budget remained, so "call it again" was prose the- # task prompt's own "do not retry" instruction could simply outweigh. The STATUS deliberately- # stays `error`: it is never serialized to the model, and it is what routes a call that blocked- # for up to 120s through the loop's batch-poisoning check.+ _install_run(monkeypatch, _two_credential_context(seed_a=_VALID_SEED, seed_b=None))+ task = _task(workflow_run_id="wr_test")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)+ handler = tools[0].handler++ answers = []+ for active in ("cred_a", "cred_b", "cred_a"):+ skyvern_context.set(+ SkyvernContext(task_id="tsk_1", workflow_run_id="wr_test", active_credential_parameter_key=active)+ )+ try:+ answers.append((await handler({}), state.last_status))+ finally:+ skyvern_context.reset()++ (first, after_first), (second, after_second), (third, after_third) = answers+ assert first.status == "ok" and first.content.startswith("verification_code: ") and after_first is None+ assert second.content == NO_ONE_TIME_CODE_SOURCE and after_second == NO_ONE_TIME_CODE_SOURCE+ assert third.status == "ok" and after_third is None+ assert state.values_delivered == 2++[email protected]("handoff", [True, False], ids=["link_handoff", "no_handoff"])+async def test_a_code_status_does_not_outlive_a_later_link_failure(+ monkeypatch: pytest.MonkeyPatch, handoff: bool+) -> None:+ link = OTPValue(value="https://example.test/magic?token=abc", type=OTPType.MAGIC_LINK)+ monkeypatch.setattr(auth_tools, "resolve_otp_value", AsyncMock(side_effect=[None, link if handoff else None]))+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, page_provider=AsyncMock(return_value=None), state=state)+ handlers = {t.name: t.handler for t in tools}++ not_yet = await handlers["get_verification_code"]({})+ assert state.last_status == not_yet.content+ if handoff:+ redirect = await handlers["get_verification_code"]({})+ assert redirect.content == auth_tools._MAGIC_LINK_REDIRECT and not _ORDER_WORDS.search(redirect.content)+ failed = await handlers["open_verification_link"]({})++ assert failed.content == (auth_tools._PAGE_UNAVAILABLE if handoff else auth_tools._NO_LINK_AVAILABLE)+ assert state.last_status is None+ assert await state.block_finish("failed") is None+++async def test_a_not_yet_reports_the_polling_time_left_at_that_call(monkeypatch: pytest.MonkeyPatch) -> None:+ # Two slices far enough apart that the recorded spends differ at the record's own resolution.monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))- # Two slices far enough apart that the recorded spends differ at the record's own resolution;- # a shorter wait would let a constant "remaining" pass the tracking assertion below.monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.2)async def _not_yet(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:@@ -1994,180 +2034,148 @@ async def test_a_not_yet_answer_arms_the_giveup_gate_and_says_what_budget_is_lefraise NoTOTPVerificationCodeFound(task_id="tsk_1")monkeypatch.setattr(auth_tools, "resolve_otp_value", _not_yet)- state = auth_tools.VerificationState(task=_task(totp_verification_url="https://totp.example"))- tools, _ = auth_tools.build_auth_tools(_task(totp_verification_url="https://totp.example"), state=state)+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)with capture_logs() as logs:first = await tools[0].handler({})second = await tools[0].handler({})- assert first.status == "error" and second.status == "error"- # A retryable answer must not arm the terminal latch, or the completed-side gate would fire on it.- assert state.source_failed is False- assert await state.block_completion() is None- # It DOES arm the give-up gate: this is the state the run is in when it throws its budget away.- assert state.awaiting_code_since is not None- assert await state.block_giveup("failed") is not None-- # The spend curve is only reconstructible today by differencing poll timestamps; the probe that- # sizes this fix in production needs it emitted directly, and v3-only (otp_service is v1's path).slices = [e for e in logs if e.get("event") == "task_v3 verification poll slice timed out"]- assert len(slices) == 2assert [e["tool"] for e in slices] == ["get_verification_code", "get_verification_code"]assert slices[0]["polling_spent_seconds"] < slices[1]["polling_spent_seconds"]- for record in slices:- assert record["budget_seconds"] == 600.0- assert record["polling_spent_seconds"] + record["remaining_seconds"] == pytest.approx(600.0, abs=0.1)-- # The message carries the remaining budget as a NUMBER, and the number is the budget MINUS THE- # SPEND AT THAT CALL -- checked against two different spends, so a constant (or a stale one that- # ignores the slice it just paid for) fails. An unquantified "you may retry" is prose competing- # with the "do not retry" prose in the task prompt; a number is not.- def _minutes(content: str) -> float:- return float(re.search(r"about ([\d.]+) minutes of polling budget remain", content).group(1))-for result, record in zip((first, second), slices):- assert _minutes(result.content) == pytest.approx((600.0 - record["polling_spent_seconds"]) / 60.0, abs=0.05)+ assert record["polling_spent_seconds"] + record["remaining_seconds"] == pytest.approx(600.0, abs=0.1)+ minutes = float(re.search(r"about ([\d.]+) minutes of polling time remain", result.content).group(1))+ assert minutes == pytest.approx((600.0 - record["polling_spent_seconds"]) / 60.0, abs=0.05)+ assert state.awaiting_link_since is None+ assert [e for e in logs if e.get("event") == "task_v3 verification source failed"] == []@pytest.mark.asyncio-async def test_the_giveup_gate_records_both_the_hold_and_the_budget_it_let_go(+async def test_a_slice_that_spends_the_budget_says_so_and_narrates_without_refusing_completion(monkeypatch: pytest.MonkeyPatch,) -> None:- # Gate 7's prod probe reads these records, so they have to exist and carry the residual. Today a- # give-up with budget left is invisible: nothing logs at a non-complete finish at all.- state = auth_tools.VerificationState(task=_task())- state.budget_seconds = 900.0- state.polling_spent_seconds = 120.0- state.awaiting_code_since = time.monotonic()-- with capture_logs() as logs:- held = await state.block_giveup("failed")- # Same finish again with no polling in between: the model ignored the hold, so the next- # verdict stands and the residual it walks away from is recorded.- released = await state.block_giveup("failed")-- assert held is not None and released is None- records = [e for e in logs if e.get("event") == "task_v3 verification give-up gate"]- assert [e["held"] for e in records] == [True, False]- assert [e["reason"] for e in records] == ["held", "unproductive"]- assert all(e["polling_spent_seconds"] == 120.0 and e["remaining_seconds"] == 780.0 for e in records)- assert [e["giveup_deferrals"] for e in records] == [1, 1]- # The probe splits held-vs-honored by finish verdict, and this record is the only place the two- # populations can be told apart -- without it both verdicts produce identical records.- assert all(e["finish_status"] == "failed" for e in records)- state.spend_at_last_giveup_deferral = None- with capture_logs() as terminated_logs:- assert await state.block_giveup("terminated") is not None- terminated = [e for e in terminated_logs if e.get("event") == "task_v3 verification give-up gate"]- assert [e["finish_status"] for e in terminated] == ["terminated"]+ monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=0.55 / 60))+ monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.2)+ monkeypatch.setattr(auth_tools, "_MIN_SLICE_SECONDS", 0.5)+ async def _not_yet(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:+ await asyncio.sleep(max_wait_seconds)+ raise NoTOTPVerificationCodeFound(task_id="tsk_1")-async def test_a_giveup_that_never_polled_is_recorded_only_when_the_code_tool_was_offered() -> None:- # The "offered a code tool, never called it" give-up. Gated on the offer: a give-up on a run with no code- # tool is every failed v3 finish, and logging those would bury the population this read is for.- offered = auth_tools.VerificationState(task=_task())- offered.code_tool_offered = True- not_offered = auth_tools.VerificationState(task=_task())+ monkeypatch.setattr(auth_tools, "resolve_otp_value", _not_yet)+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, state=state)with capture_logs() as logs:- assert await offered.block_giveup("failed") is None- assert await not_offered.block_giveup("failed") is None-- records = [e for e in logs if e.get("event") == "task_v3 verification give-up gate"]- assert len(records) == 1- assert records[0]["code_tool_offered"] is True- # Together these separate "never called" from a call that failed or answered instantly.- assert (records[0]["polling_spent_seconds"], records[0]["values_delivered"], records[0]["source_failed"]) == (- 0,- 0,- False,- )- assert (records[0]["held"], records[0]["reason"]) == (False, "not_awaiting")+ first = await tools[0].handler({})+ second = await tools[0].handler({})++ assert 0 < state.remaining_budget_seconds < auth_tools._MIN_SLICE_SECONDS+ assert first.content == second.content == auth_tools._CODE_BUDGET_SPENT+ armings = [e for e in logs if e.get("event") == "task_v3 verification source failed"]+ assert [e["reason"] for e in armings] == ["budget_exhausted", "budget_exhausted"]+ assert await state.block_finish("completed") is None@pytest.mark.asyncio-async def test_a_delivered_code_disarms_the_giveup_gate(monkeypatch: pytest.MonkeyPatch) -> None:- # (b) in the negative controls: a run that got its code and later fails for an unrelated reason- # must end on its first verdict. The disarm has to happen at the delivery site, not be inferred.[email protected]("resolver_result", ["returns_nothing", "source_errored", "lookup_raised"])+async def test_only_the_link_tool_holds_a_conversion_and_a_give_up_and_refuses_a_completion(+ monkeypatch: pytest.MonkeyPatch, resolver_result: str+) -> None:monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))- state = auth_tools.VerificationState(task=_task(totp_verification_url="https://totp.example"))- state.awaiting_code_since = time.monotonic()- monkeypatch.setattr(- auth_tools, "resolve_otp_value", AsyncMock(return_value=OTPValue(value="123456", type=OTPType.TOTP))- )- tools, _ = auth_tools.build_auth_tools(_task(totp_verification_url="https://totp.example"), state=state)+ monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)- with capture_logs() as logs:- result = await tools[0].handler({})+ async def _answer(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:+ await asyncio.sleep(max_wait_seconds)+ if resolver_result == "returns_nothing":+ return None+ if resolver_result == "source_errored":+ raise FailedToGetTOTPVerificationCode(task_id="tsk_1", reason="http_status=500")+ raise RuntimeError("resolver exploded")- assert result.status == "ok" and "123456" in result.content- assert state.awaiting_code_since is None- assert await state.block_giveup("failed") is None- delivered = [e for e in logs if e.get("event") == "task_v3 verification value delivered"]- assert len(delivered) == 1 and delivered[0]["values_delivered"] == 1+ monkeypatch.setattr(auth_tools, "resolve_otp_value", _answer)+ monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)+ converted = taskv3_loop.CONVERSION_VERIFICATION_STATUS+ for tool_name in ("get_verification_code", "open_verification_link"):+ task = _task(totp_verification_url="https://totp.example")+ state = auth_tools.VerificationState(task=task)+ tools, _ = auth_tools.build_auth_tools(task, page_provider=AsyncMock(), state=state)+ handler = {t.name: t.handler for t in tools}[tool_name]+ link = tool_name == "open_verification_link"++ await handler({})+ assert (await state.block_finish(converted) is not None) is link+ assert await state.block_finish("completed") is None+ held = await state.block_finish("failed")+ assert (held is not None) is link+ if link:+ assert "open_verification_link" in held and "do not act on the page" in held+ await handler({})+ assert (await state.block_finish("completed") is not None) is link+ assert await state.block_finish("failed") is None+ state.record_delivery(tool_name)+ assert await state.block_finish("completed") is None and await state.block_finish(converted) is None[email protected]("awaiting", [True, False], ids=["awaiting", "not_awaiting"])[email protected]("armed", [True, False], ids=["source_failed", "source_healthy"])[email protected]("stale", [True, False], ids=["stale", "recent"])[email protected]("spent", [True, False], ids=["budget_spent", "budget_left"])@pytest.mark.asyncio-async def test_a_not_yet_after_a_terminal_failure_does_not_rearm_the_giveup_gate() -> None:- # The ordering that makes `source_failed` a real conjunct rather than a restatement of- # `awaiting_code_since is None`: the source can terminally fail (two empty answers, say) and a- # LATER call still land on the healthy-source "not yet" path, which sets the awaiting latch- # again. Clearing the latch inside `arm` would look equivalent and would hold this run, which is- # exactly wrong -- the source has already been judged.+async def test_a_give_up_is_held_exactly_while_a_sign_in_link_it_has_budget_for_is_awaited(+ awaiting: bool, armed: bool, stale: bool, spent: bool+) -> None:state = auth_tools.VerificationState(task=_task())state.budget_seconds = 900.0- state.polling_spent_seconds = 120.0- state.arm(auth_tools.VerificationFailure.NO_CODE_TWICE, "get_verification_code")- state.awaiting_code_since = time.monotonic()+ state.polling_spent_seconds = 900.0 - (auth_tools._MIN_SLICE_SECONDS / 2 if spent else 600.0)+ if awaiting:+ state.link_wait_since = time.monotonic() - (auth_tools._NOT_YET_RECENCY_SECONDS + 1 if stale else 0.0)+ if armed:+ state.arm(auth_tools.VerificationFailure.NO_LINK_TWICE, "open_verification_link")++ held = await state.block_finish("failed")- assert state.source_failed is True- assert state.awaiting_code_since is not None- assert await state.block_giveup("failed") is None+ assert (held is not None) is (awaiting and not armed and not stale and not spent)@pytest.mark.asyncio-async def test_the_hold_names_the_tool_the_run_is_actually_waiting_on(monkeypatch: pytest.MonkeyPatch) -> None:- # Both tools drain one source and share one budget, so the latch has to remember which one armed- # it. A magic-link run told to "call get_verification_code again" is being sent to the wrong tool.+async def test_a_code_call_after_a_link_wait_releases_the_give_up_hold(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)-- async def _not_yet(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:- await asyncio.sleep(max_wait_seconds)- raise NoTOTPVerificationCodeFound(task_id="tsk_1")-- monkeypatch.setattr(auth_tools, "resolve_otp_value", _not_yet)monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)+ monkeypatch.setattr(+ auth_tools, "resolve_otp_value", AsyncMock(side_effect=[None, NoTOTPVerificationCodeFound(task_id="tsk_1")])+ )task = _task(totp_verification_url="https://totp.example")state = auth_tools.VerificationState(task=task)tools, _ = auth_tools.build_auth_tools(task, page_provider=AsyncMock(), state=state)+ handlers = {t.name: t.handler for t in tools}++ await handlers["open_verification_link"]({})+ assert state.link_wait_since is not None+ await handlers["get_verification_code"]({})++ assert state.link_wait_since is None+ assert await state.block_finish("terminated") is None- link_tool = next(t for t in tools if t.name == "open_verification_link")- await link_tool.handler({})- assert state.awaiting_code_tool == "open_verification_link"- message = await state.block_giveup("failed")- assert message is not None and "open_verification_link" in message- assert "get_verification_code" not in message+def test_the_give_up_headroom_reservation_still_covers_a_whole_poll_slice() -> None:+ # loop.py cannot import auth_tools (auth_tools imports loop), so the relation is pinned here.+ assert taskv3_loop.VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS == (+ auth_tools._PER_CALL_WAIT_SECONDS + taskv3_loop.FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS+ )@pytest.mark.asyncio-async def test_a_value_that_arrives_but_is_not_delivered_still_disarms_the_giveup_gate(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # The latch means "the source has not produced anything yet", so it has to clear when the source- # produces something -- not when the model is handed something. Several paths reach a value without- # a delivery (a link when a code was asked for, a code when a link was, a link the browser could- # not open), and on all of them the run is done waiting on the SOURCE. Holding a give-up there- # would contradict the very answer the tool just returned, and would send the model back to- # re-poll for a value it already has.+async def test_a_value_that_arrives_but_is_not_delivered_stops_the_link_wait(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))task = _task(totp_verification_url="https://totp.example")state = auth_tools.VerificationState(task=task)- state.awaiting_code_since = time.monotonic()- state.polling_spent_seconds = 120.0+ state.awaiting_link_since = time.monotonic()monkeypatch.setattr(auth_tools,"resolve_otp_value",@@ -2177,74 +2185,13 @@ async def test_a_value_that_arrives_but_is_not_delivered_still_disarms_the_giveuresult = await next(t for t in tools if t.name == "get_verification_code").handler({})- assert result.status == "error" and result.content == auth_tools._MAGIC_LINK_REDIRECT- assert state.values_delivered == 0 # nothing was handed to the model...- assert state.awaiting_code_since is None # ...but the source is no longer being waited on- assert await state.block_giveup("failed") is None---async def test_a_not_yet_with_less_than_one_slice_left_says_so_instead_of_inviting_a_refused_call(- monkeypatch: pytest.MonkeyPatch,-) -> None:- # A slice can end with budget left but not enough to buy another one, because the tail is checked- # before the poll and consumed by it. Reporting "about 0.0 minutes remain ... call it again" would- # send the model into a call that answers _BUDGET_EXHAUSTED -- and the whole argument for putting a- # number in this message is that a number beats prose the task prompt can outweigh.- monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=0.55 / 60))- monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.2)- monkeypatch.setattr(auth_tools, "_MIN_SLICE_SECONDS", 0.5)-- async def _not_yet(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:- await asyncio.sleep(max_wait_seconds)- raise NoTOTPVerificationCodeFound(task_id="tsk_1")-- monkeypatch.setattr(auth_tools, "resolve_otp_value", _not_yet)- task = _task(totp_verification_url="https://totp.example")- state = auth_tools.VerificationState(task=task)- tools, _ = auth_tools.build_auth_tools(task, state=state)-- first = await tools[0].handler({})- second = await tools[0].handler({})-- assert 0 < state.remaining_budget_seconds < auth_tools._MIN_SLICE_SECONDS- assert first.status == "error"- assert "the polling budget is now spent" in first.content- assert "minutes of polling budget remain" not in first.content- # ...and it must not invite the call it just said is pointless. The next call really is refused- # without polling, so an invitation costs a tool call and a turn to be told so -- and near the- # loop's limits that trades this truthful failure for a generic budget-exhausted exit.- assert "Do not call get_verification_code again" in first.content- assert "trigger it first" not in first.content- assert second.content == auth_tools._BUDGET_EXHAUSTED- # ...and it is a TERMINAL answer, so it arms. The budget is exhausted at this point whether or- # not the model makes the call that used to be the only thing that armed the latch -- and a model- # that obeys "do not call it again" must not thereby be free to claim the step completed.- assert state.source_failed is True- assert await state.block_completion() == auth_tools._COMPLETION_BLOCKED- # Giving up IS correct now, so the give-up gate releases rather than holding.- assert await state.block_giveup("failed") is None---def test_the_giveup_headroom_reservation_still_covers_a_whole_poll_slice() -> None:- # The 180s is not a round number: it is one blocking poll slice plus the re-finish cycle the- # pre-existing holds already reserve. loop.py cannot import auth_tools to say so (auth_tools- # imports loop), and asserting only that it exceeds the 60s reservation still passes at 61 --- # which would under-fund the hold and convert an honest failure into budget_exhausted, the exact- # conversion the constant exists to prevent. This file imports both, so it can pin the relation.- from skyvern.forge.taskv3 import loop as loop_module-- assert loop_module.VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS == (- auth_tools._PER_CALL_WAIT_SECONDS + loop_module.FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS- )+ assert result.content == auth_tools._MAGIC_LINK_REDIRECT and state.values_delivered == 0+ assert state.awaiting_link_since is None+ assert await state.block_finish(taskv3_loop.CONVERSION_VERIFICATION_STATUS) is None@pytest.mark.asyncioasync def test_the_spent_budget_answer_names_the_link_tool_on_a_link_run(monkeypatch: pytest.MonkeyPatch) -> None:- # The point of building this message from `_tool_name` is that a magic-link run polls the OTHER- # tool, so telling it to stop calling `get_verification_code` names something it never called.- # Every other assertion on this message runs the code tool, so without this one the whole- # parameterisation can be replaced by the literal and the file stays green.monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=20 / 60))clock = [0.0]monkeypatch.setattr(auth_tools, "time", SimpleNamespace(monotonic=lambda: clock[0]))@@ -2264,86 +2211,4 @@ async def test_the_spent_budget_answer_names_the_link_tool_on_a_link_run(monkeypassert "no sign-in link available yet" in result.contentassert "Do not call open_verification_link again" in result.contentassert "get_verification_code" not in result.content- assert state.source_failed is True---async def test_a_terminally_failed_source_is_recorded_as_such_not_as_a_spent_budget() -> None:- # The give-up record's `reason` feeds a production probe, and `block_giveup` checks `source_failed`- # ahead of both the recency window and the budget -- so once the source is armed, a give-up is- # labelled `source_failed` whether the budget ran out or the latch went stale. Nothing pinned that- # label, so the shift was invisible to the tests that do pin the held-vs-honored split.- state = auth_tools.VerificationState(task=_task())- state.budget_seconds = 900.0- state.polling_spent_seconds = 895.0- state.awaiting_code_since = time.monotonic()- state.arm(auth_tools.VerificationFailure.BUDGET_EXHAUSTED, "get_verification_code")-- with capture_logs() as logs:- assert await state.block_giveup("failed") is None- record = next(e for e in logs if e.get("event") == "task_v3 verification give-up gate")- assert record["reason"] == "source_failed"- # Still an honored give-up, which is what the probe's held-vs-honored split actually counts.- assert record["held"] is False--[email protected]("link_run", [False, True], ids=["code_tool", "link_tool"])- "resolver_result",- ["returns_nothing", "source_errored", "lookup_raised"],-)-async def test_every_retryable_answer_arms_the_giveup_gate_not_just_a_not_yet(- monkeypatch: pytest.MonkeyPatch, resolver_result: str, link_run: bool-) -> None:- # Four answers ask the model to call again: "not yet", a bare None, a source that errored, and a- # lookup that raised. Arming on only the first left the gate holding on one of them, so a run that- # gave up right after any of the other three discarded its budget exactly as it did before this- # change -- the same defect, on sibling paths.- monkeypatch.setattr(auth_tools, "settings", SimpleNamespace(VERIFICATION_CODE_POLLING_TIMEOUT_MINS=10))- monkeypatch.setattr(auth_tools, "_PER_CALL_WAIT_SECONDS", 0.05)-- async def _answer(*_a: Any, max_wait_seconds: float, **_k: Any) -> OTPValue | None:- await asyncio.sleep(max_wait_seconds)- if resolver_result == "returns_nothing":- return None- if resolver_result == "source_errored":- raise FailedToGetTOTPVerificationCode(task_id="tsk_1", reason="http_status=500")- raise RuntimeError("resolver exploded")-- monkeypatch.setattr(auth_tools, "resolve_otp_value", _answer)- if link_run:- monkeypatch.setattr(otp_service, "has_credential_totp_candidate", lambda *_a, **_k: False)- task = _task(totp_verification_url="https://totp.example")- state = auth_tools.VerificationState(task=task)- tools, _ = auth_tools.build_auth_tools(task, page_provider=AsyncMock() if link_run else None, state=state)- # Both tools drain one source, so the tool the latch records is load-bearing here and cannot be- # checked on the code run alone -- "get_verification_code" is also the field's default, so an- # assertion that only ever sees that value passes whether or not the tool is recorded at all.- expected_tool = "open_verification_link" if link_run else "get_verification_code"- handler = {t.name: t.handler for t in tools}[expected_tool]-- first = await handler({})-- # Retryable, not terminal: it invites another call and must not arm the completion refusal.- assert first.status == "error"- assert state.source_failed is False- assert await state.block_completion() is None- # ...and it holds a give-up, which is the whole point.- assert state.awaiting_code_since is not None- assert state.awaiting_code_tool == expected_tool- held = await state.block_giveup("failed")- assert held is not None and expected_tool in held- # The hold must name the right ARTIFACT as well as the right tool: telling a run that polled for- # a sign-in link that "the verification code has not arrived" contradicts both the page and the- # answer the tool just gave it. Asserted on the link run too, because "verification code" is the- # wording a hardcoded default would produce and the code run alone cannot tell them apart.- if link_run:- assert "sign-in link" in held and "verification code" not in held- else:- assert "verification code" in held and "sign-in link" not in held-- # The SECOND occurrence is terminal, and then giving up is correct again.- await handler({})- assert state.source_failed is True- assert await state.block_giveup("failed") is None+ assert state.link_failed is Truediff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex 54efe0449..73107cc23 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -1870,6 +1870,27 @@ async def _run_to_finish(caller: _ScriptedCaller) -> None:skyvern_context.reset()+async def test_the_model_is_offered_the_users_error_codes_on_finish() -> None:+ caller = _ScriptedCaller(+ [[("finish", {"status": "failed", "reason": "password rejected", "error_code": "invalid_credentials"})]]+ )+ skyvern_context.set(SkyvernContext(task_id="tsk_codes"))+ try:+ outcome = await run_task_v3_agent_loop(+ page_provider=_fixed_page_provider(_FakePage()),+ llm_caller=caller,+ goal="Sign in.",+ error_code_mapping={"invalid_credentials": "The site rejected the password."},+ )+ finally:+ skyvern_context.reset()++ (finish,) = (t for t in caller.sent_tools or [] if t["function"]["name"] == "finish")+ assert "invalid_credentials" in finish["function"]["parameters"]["properties"]["error_code"]["enum"]+ assert outcome.error_code == "invalid_credentials"++@pytest.mark.asyncioasync def test_code_tool_surface_off_never_asks_the_deployment_for_a_code_tool(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_taskv3_goal_check.py b/tests/unit/test_taskv3_goal_check.pyindex a99f842c9..61e777635 100644--- a/tests/unit/test_taskv3_goal_check.py+++ b/tests/unit/test_taskv3_goal_check.py@@ -5,6 +5,7 @@ import itertoolsimport reimport timefrom pathlib import Path+from types import SimpleNamespacefrom typing import Anyimport jinja2@@ -14,6 +15,7 @@ from structlog.testing import capture_logsfrom skyvern.forge.sdk.api.llm.exceptions import InvalidLLMResponseFormatfrom skyvern.forge.sdk.workflow.context_manager import RANDOM_SECRET_ID_PREFIXfrom skyvern.forge.taskv3 import loop as taskv3_loop+from skyvern.forge.taskv3.auth_tools import VerificationFailure, VerificationStatefrom skyvern.forge.taskv3.goal_check import (GoalJudge,NonCompletedStatus,@@ -780,6 +782,21 @@ async def test_a_completed_finish_never_reaches_the_reask(pending: bool, blockedassert control_spy.calls == [("terminated", "no PIN screen")]+async def test_a_reask_conversion_keeps_the_original_verdicts_error_code_for_a_post_loop_veto() -> None:+ finish = make_finish_tool(+ **_gate_kwargs(pending=False, blocked=False, unsettled=False),+ unlisted_reask=_ReaskSpy(),+ error_code_mapping={"invalid_credentials": "The site rejected the password."},+ )+ result = await finish.handler(+ {"status": "failed", "reason": "password rejected", "error_code": "invalid_credentials"}+ )+ assert result.data is not None+ assert (result.data["status"], result.data["converted_from"]) == ("completed", "failed")+ assert result.data["error_code"] == "invalid_credentials"++@pytest.mark.asyncio@pytest.mark.parametrize("status", ["terminated", "failed"])async def test_a_grounded_reask_completes_once_and_a_completed_side_veto_keeps_the_models_verdict(@@ -794,6 +811,8 @@ async def test_a_grounded_reask_completes_once_and_a_completed_side_veto_keeps_t"extracted_output": None,"converted_from": status,"converted_from_reason": "no PIN screen",+ "error_code": None,+ "error_code_declined": False,}for veto in ("pending", "blocked", "unsettled"):@@ -822,6 +841,32 @@ async def test_a_grounded_reask_completes_once_and_a_completed_side_veto_keeps_tassert len(spy.calls) == 1[email protected]("verification", ["link_armed", "link_awaited", "code_armed", "code_not_yet"])+async def test_a_reask_conversion_is_vetoed_only_while_a_sign_in_link_never_arrived(verification: str) -> None:+ state = VerificationState(+ task=SimpleNamespace(task_id="tsk_1", organization_id="o_1", workflow_run_id=None) # type: ignore[arg-type]+ )+ if verification == "link_armed":+ state.arm(VerificationFailure.NO_LINK_TWICE, "open_verification_link")+ elif verification == "link_awaited":+ state.awaiting_link_since = time.monotonic()+ elif verification == "code_armed":+ state.arm(VerificationFailure.BUDGET_EXHAUSTED, "get_verification_code")+ else:+ state.last_status = "no verification code has arrived yet; about 13.0 minutes of polling time remain."+ kwargs = {**_gate_kwargs(pending=False, blocked=False, unsettled=False), "verification_blocker": state.block_finish}+ finish = make_finish_tool(**kwargs, unlisted_reask=_ReaskSpy())++ with capture_logs() as logs:+ result = await finish.handler({"status": "terminated", "reason": "no PIN screen"})++ vetoed = verification.startswith("link")+ assert result.data is not None and result.data["status"] == ("terminated" if vetoed else "completed")+ (line,) = (log for log in logs if log["event"] == "taskv3 finish unlisted reask")+ assert line["veto"] == ("verification_blocker" if vetoed else None)++class _SettleWindowPage:"""Fingerprint pairs settle on the samples `settles` marks; the document identity moves once `moves_after`settle samples have been taken (None: never)."""diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.pyindex 085be9c43..7f16a0954 100644--- a/tests/unit/test_taskv3_loop.py+++ b/tests/unit/test_taskv3_loop.py@@ -31,7 +31,7 @@ from skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.taskv3 import loop as loop_modulefrom skyvern.forge.taskv3 import tools as taskv3_tools_module-from skyvern.forge.taskv3.auth_tools import VerificationFailure, VerificationState+from skyvern.forge.taskv3.auth_tools import _MAX_GIVEUP_DEFERRALS, VerificationFailure, VerificationStatefrom skyvern.forge.taskv3.engine import MAX_TOKENS_CEILING, MAX_TOKENS_PER_ACTION_STEP, taskv3_runaway_backstopsfrom skyvern.forge.taskv3.goal_check import GoalVerdict, ToolTrail, run_goal_checkfrom skyvern.forge.taskv3.handoff_redaction import ELIDED_URL_PATH, caller_known_published_urls@@ -76,6 +76,7 @@ from skyvern.forge.taskv3.loop import (TOKEN_BUDGET_EXTENSION_REFUSED_EVENT,UNCHARGED_REFUSAL_GRACE,VERDICT_URL_MAX_CHARS,+ VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS,ActivityRecency,DownloadFailureFacts,LoopOutcome,@@ -301,6 +302,67 @@ async def test_finish_terminates_with_status_and_output() -> None:assert observe_calls == [("observe", {})]+_UNMAPPED_FINISH_SCHEMA_SHA256 = "7d3bd060a60aa326dedb4cd5474b0bf4b9e7f25ea19ea60ddfb9f19375cd8d33"+++def test_finish_schema_is_unchanged_for_a_task_without_error_codes() -> None:+ # finish is on every v3 run, so a task without codes must see exactly the schema it saw before codes existed.+ spec = make_finish_tool(error_code_mapping=None)+ blob = json.dumps({"description": spec.description, "parameters": spec.parameters}, sort_keys=True)+ assert hashlib.sha256(blob.encode()).hexdigest() == _UNMAPPED_FINISH_SCHEMA_SHA256+ assert make_finish_tool(error_code_mapping={}).parameters == spec.parameters+++def test_finish_offers_exactly_the_users_codes_plus_none_of_these() -> None:+ mapping = {"invalid_credentials": "The site rejected the username or password.", "account_locked": "Locked."}+ spec = make_finish_tool(error_code_mapping=mapping)+ error_code = spec.parameters["properties"]["error_code"]+ assert error_code["enum"] == ["account_locked", "invalid_credentials", loop_module.NO_MATCHING_ERROR_CODE]+ assert "The site rejected the username or password." in error_code["description"]+ assert "error_code" not in spec.parameters["required"]+ assert spec.description == make_finish_tool().description++ colliding = make_finish_tool(error_code_mapping={"none_of_these": "x", "": "y", "invalid_credentials": "z"})+ assert colliding.parameters["properties"]["error_code"]["enum"] == [+ "invalid_credentials",+ loop_module.NO_MATCHING_ERROR_CODE,+ ]+ # Nothing to offer, or too much to send on every turn: the post-run detector keeps the mapping.+ for unoffered in ({"none_of_these": "x", " ": "y"}, {f"code_{i}": "d" for i in range(65)}, {"big": "x" * 40_000}):+ assert make_finish_tool(error_code_mapping=unoffered).parameters == make_finish_tool().parameters+++ ("status", "answer", "code", "declined"),+ [+ ("failed", "INVALID_CREDENTIALS", "invalid_credentials", False),+ ("terminated", "invalid_credentials", "invalid_credentials", False),+ ("failed", "none_of_these", None, True),+ ("failed", "PAYMENT_DECLINED", None, False),+ ("failed", " invalid_credentials ", "invalid_credentials", False),+ ("failed", None, None, False),+ ("completed", "invalid_credentials", None, False),+ ],+)+async def test_finish_carries_only_a_validated_code_on_a_run_that_did_not_succeed(+ status: str, answer: str | None, code: str | None, declined: bool+) -> None:+ mapping = {"invalid_credentials": "The site rejected the username or password."}+ args: dict[str, Any] = {"status": status, "reason": "the site said the password is wrong"}+ if answer is not None:+ args["error_code"] = answer+ tools = [make_finish_tool(error_code_mapping=mapping)]+ with capture_logs() as logs:+ outcome, _ = await _run([[("finish", args)]], tools)++ assert outcome.status == status+ assert outcome.error_code == code+ assert outcome.error_code_declined is declined+ if answer == "PAYMENT_DECLINED":+ assert all(answer not in str(log) for log in logs)++@pytest.mark.asyncio@pytest.mark.parametrize(("next_tool", "code_kept"), [("observe", True), ("click", False)])async def test_a_failed_navigation_code_survives_reads_but_not_a_later_action(next_tool: str, code_kept: bool) -> None:@@ -8739,6 +8801,7 @@ async def test_completion_gate_raise_ends_the_run_with_the_gates_reason(assert outcome.status == statusassert reason in outcome.reasonassert not outcome.gate_passed+ assert outcome.model_status == "completed"assert caller.calls == 1@@ -11139,110 +11202,77 @@ async def test_a_renumbered_mark_does_not_alias_with_its_pre_renumber_history()assert [e for e in logs if e.get("event") == CANONICAL_LOOP_EVENT] == []-def _awaiting_verification_state(*, spent: float = 120.0, budget: float = 900.0) -> Any:- """A VerificationState in the exact shape the bug produces: a healthy source that answered "not- yet" one 120s slice ago, with most of the 900s budget still unspent."""-- state = VerificationState(+def _verification_state() -> VerificationState:+ return VerificationState(task=SimpleNamespace(task_id="tsk_1", organization_id="o_1", workflow_run_id=None) # type: ignore[arg-type])- state.budget_seconds = budget- state.polling_spent_seconds = spent- state.awaiting_code_since = time.monotonic()- return state---def _spend_tool(state: Any, per_call_seconds: float) -> ToolSpec:- """Stands in for get_verification_code: the only thing the loop can see it do is draw the budget- down, which is exactly what the gate's monotone bound is keyed on."""- async def _handler(args: dict[str, Any]) -> ToolResult:- state.polling_spent_seconds += per_call_seconds- state.awaiting_code_since = time.monotonic()- return ToolResult.ok("no verification code available yet")- return ToolSpec(name="get_verification_code", description="poll", parameters={"type": "object"}, handler=_handler)+def _awaiting_link_state(*, spent: float = 120.0) -> VerificationState:+ state = _verification_state()+ state.polling_spent_seconds = spent+ state.awaiting_link_since = state.link_wait_since = time.monotonic()+ return state@pytest.mark.parametrize("status", ["failed", "terminated"])@pytest.mark.asyncio-async def test_giveup_with_unspent_verification_budget_is_deferred(status: str) -> None:- # The defect: a run that has spent one 120s slice of a 900s budget on a source that has not- # answered yet ends on the model's first non-complete verdict, throwing away ~13 minutes of- # polling it already owns. Both non-complete verdicts, not just `failed` -- `terminated` was- # gated by nothing at all.- state = _awaiting_verification_state()+async def test_a_non_complete_verdict_stands_while_a_code_is_awaited(status: str) -> None:+ # The model decides from the code statuses it was given; the finish tool does not hold that give-up.+ state = _verification_state()+ state.polling_spent_seconds = 120.0+ state.last_status = "no verification code has arrived yet; about 13.0 minutes of polling time remain."tools = [make_finish_tool(verification_blocker=state.block_finish, activity=ActivityRecency())]- script = [- [("finish", {"status": status, "reason": "the code never arrived"})],- [("finish", {"status": status, "reason": "the code never arrived"})],- ]- outcome, _ = await _run(script, tools)+ script = [[("finish", {"status": status, "reason": "the code never arrived"})]]+ outcome, caller = await _run(script, tools)- finish_messages = [m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"]- assert any("polling budget remain" in m for m in finish_messages)- # The number is the point: an unquantified "keep waiting" is the prose the customer's own "do not- # retry" instruction competes with. 900 - 120 = 780s = 13.0 minutes.- assert any("13.0 minutes" in m for m in finish_messages)- assert state.giveup_deferrals == 1- # ...and the hold is a hold, not a trap: the verdict still lands.assert outcome.status == status+ assert caller.calls == 1[email protected]("status", ["failed", "terminated"])@pytest.mark.asyncio-async def test_a_model_that_ignores_the_giveup_deferral_ends_on_its_second_verdict() -> None:- # Bounded termination for the model that refuses to re-poll. Asserted on the run's TERMINAL- # STATUS, not on a deferral counter: without the unproductive-deferral bound this run ping-pongs- # against the gate until the budget is exhausted, and the assertion that catches that is the run- # never reaching `failed`.- state = _awaiting_verification_state()+async def test_a_give_up_while_a_sign_in_link_is_awaited_is_held_once_then_stands(status: str) -> None:+ state = _awaiting_link_state()tools = [make_finish_tool(verification_blocker=state.block_finish, activity=ActivityRecency())]- script = [[("finish", {"status": "failed", "reason": "no code"})] for _ in range(6)]+ script = [[("finish", {"status": status, "reason": "the link never arrived"})] for _ in range(4)]outcome, caller = await _run(script, tools)- assert outcome.status == "failed"+ finish_messages = [m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"]+ # 900 - 120 = 780s of budget left.+ assert any("13.0 minutes of sign-in link polling budget remain" in m for m in finish_messages)+ assert outcome.status == statusassert caller.calls == 2assert state.giveup_deferrals == 1@pytest.mark.asyncio-async def test_a_model_that_polls_minimally_ends_within_the_absolute_deferral_cap() -> None:- # The monotone-budget bound alone does not terminate: a slice may advance spend by as little as- # _MIN_SLICE_SECONDS, so 10s polls would buy ~90 deferrals out of a 900s budget. The absolute cap- # is what ends this run, and the assertion is again the terminal status -- a run that never- # reaches `failed` here is one the gate trapped.- from skyvern.forge.taskv3.auth_tools import _MAX_GIVEUP_DEFERRALS+async def test_a_model_that_polls_for_a_link_minimally_ends_within_the_deferral_cap() -> None:+ state = _awaiting_link_state(spent=0.0)++ async def _poll(args: dict[str, Any]) -> ToolResult:+ state.polling_spent_seconds += 10.0+ state.link_wait_since = time.monotonic()+ return ToolResult.error("no sign-in link available yet")- state = _awaiting_verification_state(spent=0.0)tools = [- _spend_tool(state, 10.0),+ ToolSpec(name="open_verification_link", description="poll", parameters={"type": "object"}, handler=_poll),make_finish_tool(verification_blocker=state.block_finish, activity=ActivityRecency()),]script: list[list[tuple[str, dict[str, Any]]]] = []for _ in range(15):- script.append([("get_verification_code", {})])- script.append([("finish", {"status": "failed", "reason": "no code"})])+ script.append([("open_verification_link", {})])+ script.append([("finish", {"status": "failed", "reason": "no link"})])outcome, _ = await _run(script, tools, max_turns=60, max_tool_calls=200)assert outcome.status == "failed"assert state.giveup_deferrals == _MAX_GIVEUP_DEFERRALS- # The cap, not the budget, is what bound this run: 8 x 10s of polling leaves the budget nearly full.assert state.remaining_budget_seconds > 800.0@pytest.mark.asyncio-async def test_giveup_deferral_is_refused_without_the_deadline_headroom_to_fund_a_poll_slice() -> None:- # A deferral asks for a 120s BLOCKING poll on top of the re-finish cycle. Deferring with less- # than that leaves the run to die on the wall clock as budget_exhausted -- converting the- # model's honest verdict into an unmapped one, the exact conversion the headroom gates exist to- # prevent. The failure-evidence gate's 60s reservation is not enough to cover a poll slice.- from skyvern.forge.taskv3.loop import (- FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS,- VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS,- )-- assert VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS > FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS- state = _awaiting_verification_state()+async def test_a_link_give_up_is_not_held_without_the_deadline_headroom_to_fund_a_poll_slice() -> None:+ state = _awaiting_link_state()tools = [make_finish_tool(verification_blocker=state.block_finish,@@ -11250,66 +11280,42 @@ async def test_giveup_deferral_is_refused_without_the_deadline_headroom_to_fund_deadline_at=time.monotonic() + (VERIFICATION_GIVEUP_MIN_DEADLINE_HEADROOM_SECONDS - 5.0),)]- script = [[("finish", {"status": "failed", "reason": "no code"})]]- with capture_logs() as logs:- outcome, caller = await _run(script, tools)+ script = [[("finish", {"status": "failed", "reason": "no link"})]]+ outcome, caller = await _run(script, tools)assert outcome.status == "failed"assert caller.calls == 1assert state.giveup_deferrals == 0- # The gate is not consulted at all here, so it writes nothing. That is a KNOWN LIMIT of the- # probe, asserted rather than papered over: a give-up refused for want of hold budget is not- # directly counted, because only the gate knows whether the run was awaiting a code and this is- # the one case where the gate is not asked.- assert [e for e in logs if e.get("event") == "task_v3 verification give-up gate"] == []@pytest.mark.asyncio-async def test_a_completed_verdict_is_never_held_for_unspent_verification_budget() -> None:- # The widened primitive answers all three verdicts from one branch, so the completed side has to- # be shown unchanged: unspent budget is a reason to keep WAITING, never a reason to refuse a- # success the model can see on the page.- state = _awaiting_verification_state()+async def test_a_completed_verdict_after_a_failed_code_source_stands() -> None:+ state = _verification_state()+ state.arm(VerificationFailure.NO_CODE_TWICE, "get_verification_code")+ state.arm(VerificationFailure.BUDGET_EXHAUSTED, "get_verification_code")tools = [make_finish_tool(verification_blocker=state.block_finish, activity=ActivityRecency())]script = [[("finish", {"status": "completed", "reason": "signed in"})]]outcome, caller = await _run(script, tools)assert outcome.status == "completed"assert caller.calls == 1- assert state.giveup_deferrals == 0@pytest.mark.asyncio-async def test_a_completion_blocked_run_still_escapes_via_failed_at_production_wiring() -> None:- # The escape hatch `test_verification_blocker_refuses_completed_but_not_failed` protects, pinned- # where it actually has to hold. That test passes a bare mock and no `activity`, so the widened- # primitive is consulted for `completed` only and the give-up side is never exercised -- but- # engine.py always passes an ActivityRecency, so the production configuration DOES reach the- # give-up side. What makes the escape safe there is not the missing accounting, it is that a- # terminally-failed source returns None from `block_giveup` by construction: giving up IS the- # correct answer once the source has been judged. Asserted against the real VerificationState,- # not a mock that cannot disagree with the gate it is standing in for.-- state = VerificationState(- task=SimpleNamespace(task_id="tsk_1", organization_id="o_1", workflow_run_id=None) # type: ignore[arg-type]- )- state.polling_spent_seconds = 120.0- state.awaiting_code_since = time.monotonic()- state.arm(VerificationFailure.NO_CODE_TWICE, "get_verification_code")-+async def test_a_completion_refused_after_a_failed_sign_in_link_still_escapes_via_failed() -> None:+ state = _verification_state()+ state.arm(VerificationFailure.NO_LINK_TWICE, "open_verification_link")tools = [make_finish_tool(verification_blocker=state.block_finish, activity=ActivityRecency())]script = [[("finish", {"status": "completed", "reason": "signed in"})],- [("finish", {"status": "failed", "reason": "the code never arrived"})],+ [("finish", {"status": "failed", "reason": "the link never arrived"})],]outcome, caller = await _run(script, tools)finish_messages = [m["content"] for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "finish"]- assert any("the verification step never completed" in m for m in finish_messages)- # On its FIRST failed verdict, with no hold in between -- two LLM turns total.+ assert any("the sign-in link step never completed" in m for m in finish_messages)assert outcome.status == "failed"assert caller.calls == 2- assert state.giveup_deferrals == 0@pytest.mark.asynciodiff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.pyindex aa5ce1609..505d235f2 100644--- a/tests/unit/test_taskv3_tools.py+++ b/tests/unit/test_taskv3_tools.py@@ -92,6 +92,7 @@ from skyvern.forge.taskv3.tools import (DOWNLOAD_NO_FILE_THIS_ACTION,DOWNLOAD_NO_SESSION_FILE_YET,NAVIGATION_DEAD_END_STATUSES,+ NO_ONE_TIME_CODE_SOURCE,OBSERVE_DISPLAY_WIDTHS,OBSERVE_POINTER_ROOT_CAP,OBSERVE_RETAIN_WIDTH_MIN,@@ -2110,7 +2111,7 @@ async def test_type_of_a_credential_totp_placeholder_enters_a_real_code(monkeypaassert typed[0] in {totp.at(before), totp.at(after)}assert re.fullmatch(r"\d{6}", typed[0])assert run.state.values_delivered == 1- assert run.state.totp_source_missing is False+ assert run.state.last_status is Noneassert typed[0] in run.context.runtime_secret_valuesassert "BW_TOTP" not in result.content and _TOTP_PLACEHOLDER not in result.content@@ -2139,10 +2140,10 @@ async def test_type_of_a_totp_placeholder_with_no_usable_secret_types_nothing(type_messages = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "type"]assert len(type_messages) == 1content = type_messages[0]["content"]- assert "one-time" in content and "Never invent or guess a code" in content+ assert NO_ONE_TIME_CODE_SOURCE in contentassert "BW_TOTP" not in content and _TOTP_PLACEHOLDER not in content and "tool_error" not in contentassert not re.search(r"\d", content)- assert run.state.totp_source_missing is True+ assert run.state.last_status == NO_ONE_TIME_CODE_SOURCEassert run.state.values_delivered == 0@@ -2216,7 +2217,7 @@ async def test_type_enters_the_code_of_a_credential_other_than_the_blocks_pinnedtyped = [c[1]["text"] for c in run.page.calls if c[0] == "fill"]assert len(typed) == 1 and re.fullmatch(r"\d{6}", typed[0])assert run.state.values_delivered == 1- assert run.state.totp_source_missing is False+ assert run.state.last_status is None@pytest.mark.asyncio@@ -2279,7 +2280,7 @@ async def test_a_totp_placeholder_not_typed_alone_is_refused_without_blaming_theassert "typed alone" in refused.contentassert "no usable" not in refused.content and "BW_TOTP" not in refused.contentassert [c for c in run.page.calls if c[0] == "fill"] == []- assert run.state.totp_source_missing is False+ assert run.state.last_status is Noneassert run.state.values_delivered == 0@@ -3688,6 +3689,7 @@ async def test_observe_result_carries_count_only_summary_for_the_call_record() -"ready_state_when_empty","icons_listed","icons_truncated",+ "unnamed_not_icon",}assert all(type(v) is int for v in summary.values())assert summary["invalid_fields"] == 1@@ -12475,6 +12477,851 @@ async def test_observe_lists_every_unnamed_icon_control_and_its_ref_clicks_it()assert await page.evaluate("() => window.__deleted") == [str(last)]+# A "more actions" kebab drawn without a graphic element: a font ligature in a ::before, a background+# image, and three styled dots. None holds an svg/img/canvas and none carries a name, so the icon rule+# is the only thing that can list them -- and a reading that requires a graphic drops all three while+# listing the row's link, which is the neighbour the model then clicks instead.+_CSS_KEBAB_HTML = (+ "<!doctype html><html><head><style>"+ ".kebab{cursor:pointer;display:inline-block;width:24px;height:24px}"+ ".kebab.glyph::before{content:'\\22EE';font-size:18px}"+ ".kebab.bg{background-image:url('data:image/gif;base64,"+ "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');background-repeat:no-repeat}"+ ".kebab.dots span{cursor:pointer;display:block;width:4px;height:4px;border-radius:50%;background:#333;margin:2px auto}"+ ".curtain{cursor:pointer;width:320px;height:220px;background:#ddd}"+ ".curtain span{display:inline-block;width:2px;height:2px}"+ ".too-small{cursor:pointer;width:4px;height:4px;background:#333}"+ ".blank-icon{cursor:pointer;display:inline-block;width:24px;height:24px}"+ "</style></head><body><table>"+ # One tag for all three, as a real table repeats: the lines are identical but for the row they sit+ # in, so this exercises the row qualifier the listing needs to tell them apart as well.+ '<tr><td><a href="/b/1">Bill 1</a></td><td><div class="kebab glyph"></div></td></tr>'+ '<tr><td><a href="/b/2">Bill 2</a></td><td><div class="kebab bg"></div></td></tr>'+ '<tr><td><a href="/b/3">Bill 3</a></td><td><div class="kebab dots">'+ "<span></span><span></span><span></span></div></td></tr>"+ "</table>"+ # Unnamed, clickable, and far bigger than a glyph: its centre need not be on any control, so it+ # stays unlisted and is counted instead.+ '<div>Large curtain <div id="curtain" class="curtain"><span></span><span></span><span></span></div></div>'+ '<div>Tiny target <div id="too-small" class="too-small"></div></div>'+ '<div>Blank target <div id="blank" class="blank-icon"></div></div>'+ "<script>window.__opened = [];document.addEventListener('click', (e) => {"+ " const k = e.target.closest('.kebab');"+ " if (k) window.__opened.push(k.closest('tr').querySelector('a').textContent); });</script>"+ "</body></html>"+)+++@_skip_no_browser+async def test_observe_lists_an_icon_control_however_the_page_draws_its_glyph() -> None:+ async with _live_page(_CSS_KEBAB_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ r = await _tool(tools, "observe").handler({})+ assert r.status == "ok"+ lines = [line for line in r.content.splitlines() if line.startswith("ref=")]+ # One unnamed icon line per row, each told apart by the row it sits in.+ icons = [line for line in lines if " '' in='Bill " in line]+ assert len(icons) == 3, r.content+ assert r.data["summary"]["icons_listed"] == 3, r.data["summary"]+ assert r.data["summary"]["duplicate_digest_lines"] == 0, r.data["summary"]+ # The inked curtain fails only the 48px ceiling, the inkless 24px box fails only ink, and+ # the 4px inked control fails only the 6px floor. Nested layout spans count as one rejected root.+ assert r.data["summary"]["unnamed_not_icon"] == 3, r.data["summary"]+ listed = [line for line in r.content.splitlines() if line.startswith("ref=")]+ assert not any("in='Large curtain'" in line for line in listed), r.content+ assert not any("in='Tiny target'" in line for line in listed), r.content+ assert not any("in='Blank target'" in line for line in listed), r.content+ # The ref opens the row's own menu, not the link beside it.+ third = next(line for line in icons if "in='Bill 3'" in line)+ click = await _tool(tools, "click").handler({"selector": _ref_line(third, "div ''")})+ assert click.status == "ok", click.content+ assert await page.evaluate("() => window.__opened") == ["Bill 3"]+++@_skip_no_browser+async def test_observe_lists_nested_css_action_in_a_clickable_row() -> None:+ html = """<!doctype html><html><head><style>+ .row {+ cursor: pointer;+ .action {+ cursor: pointer;+ display: inline-block;+ width: 24px;+ height: 24px;+ background: #333;+ }+ }+ .outside { cursor:pointer; width:120px; height:40px }+ .outside .action { display:inline-block; width:24px; height:24px; background:#333 }+ </style></head><body>+ <div class="row"><a href="#invoice">Invoice 9</a><div class="action" id="inside"></div></div>+ <div class="outside"><a href="#other">Other</a><div class="action" id="outside"></div></div>+ <script>+ document.getElementById('inside').addEventListener('click', () => window.__clicked = 'inside');+ document.getElementById('outside').addEventListener('click', () => window.__clicked = 'outside');+ </script>+ </body></html>"""+ async with _live_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ assert result.status == "ok", result.content+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ icon = next(line for line in lines if "div ''" in line)+ click = await _tool(tools, "click").handler({"selector": _ref_line(icon, "div ''")})+ clicked = await page.evaluate("() => window.__clicked")++ assert sum("div ''" in line for line in result.content.splitlines()) == 1, result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+ assert not any("id='outside'" in line for line in lines), result.content+ assert click.status == "ok", click.content+ assert clicked == "inside"+++@_skip_no_browser+async def test_nested_selector_list_scopes_each_pointer_rule_branch() -> None:+ html = """<!doctype html><html><head><style>+ .row {+ display:flex; cursor:pointer; width:300px; height:36px; align-items:center;+ &.selected, .action { cursor:pointer; }+ }+ .other-row { display:flex; cursor:pointer; width:300px; height:36px; align-items:center }+ .action { display:inline-block; width:22px; height:20px; background:#333 }+ </style></head><body>+ <div class="row selected"><input type="checkbox"><a href="#selected">Selected</a>+ <span id="real-action" class="action" onclick="window.__realAction=true"></span></div>+ <div class="other-row"><input type="checkbox"><a href="#other">Other</a>+ <span id="decorative-action" class="action"></span></div>+ <script>window.__realAction=false;</script>+ </body></html>"""+ async with _live_page(html) as page:+ # Expose the raw implicit branch form that some CSSOMs return for nested selector lists.+ patched = await page.evaluate(+ """() => {+ const descriptor = Object.getOwnPropertyDescriptor(CSSStyleRule.prototype, 'selectorText');+ if (!descriptor?.get || !descriptor.configurable) return false;+ Object.defineProperty(CSSStyleRule.prototype, 'selectorText', {+ configurable: true,+ get() {+ const selector = descriptor.get.call(this);+ return selector === '&.selected, & .action' ? '&.selected, .action' : selector;+ },+ });+ return true;+ }"""+ )+ cursors = await page.evaluate(+ "() => ['real-action','decorative-action'].map(id => getComputedStyle(document.getElementById(id)).cursor)"+ )+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ action_lines = [line for line in result.content.splitlines() if line.startswith("ref=") and "span ''" in line]+ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+ assert len(action_lines) == 1, result.content+ click = await _tool(tools, "click").handler({"selector": _ref_line(action_lines[0], "span ''")})+ clicked = await page.evaluate("() => window.__realAction")++ assert patched, "could not expose the unexpanded nested selector text to the collector"+ assert cursors == ["pointer", "pointer"], cursors+ assert click.status == "ok" and clicked is True, (click.content, clicked)+++@_skip_no_browser+async def test_observe_lists_cursor_action_from_imported_stylesheet() -> None:+ html = """<!doctype html><html><head><style>+ .row { cursor:pointer; width:200px; height:40px }+ .action { display:inline-block; width:24px; height:24px; background:#333 }+ </style></head><body>+ <div class="row"><a href="#invoice">Invoice 9</a><div class="action"></div></div>+ <script>+ const css = new Blob(['.row .action { cursor:pointer }'], {type:'text/css'});+ const url = URL.createObjectURL(css);+ const imported = document.createElement('style');+ imported.id = 'imported-style';+ imported.textContent = `@import url("${url}");`;+ document.head.append(imported);+ document.querySelector('.action').addEventListener('click', () => window.__clicked = true);+ </script>+ </body></html>"""+ async with _live_page(html) as page:+ await page.wait_for_function(+ """() => {+ const rule = document.querySelector('#imported-style').sheet.cssRules[0];+ return rule.styleSheet?.cssRules?.length === 1+ && getComputedStyle(document.querySelector('.action')).cursor === 'pointer';+ }"""+ )+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ icon = next(line for line in lines if "div ''" in line)+ click = await _tool(tools, "click").handler({"selector": _ref_line(icon, "div ''")})+ clicked = await page.evaluate("() => window.__clicked")++ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+ assert click.status == "ok", click.content+ assert clicked+++@_skip_no_browser+async def test_css_painted_wrapper_with_multiple_graphics_is_not_an_icon() -> None:+ html = """<!doctype html><html><head><style>+ .wrapper { cursor:pointer; display:inline-flex; width:24px; height:24px; background:#333 }+ svg { width:8px; height:8px }+ </style></head><body>+ <div class="wrapper"><svg id="first"><rect width="8" height="8"></rect></svg>+ <svg id="second"><rect width="8" height="8"></rect></svg></div>+ <script>+ window.__hits = [];+ for (const id of ['first', 'second']) {+ document.getElementById(id).addEventListener('click', () => window.__hits.push(id));+ }+ </script>+ </body></html>"""+ async with _live_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ graphics = [line for line in lines if " svg ''" in line]+ clicks = [await _tool(tools, "click").handler({"selector": _ref_line(line, "svg ''")}) for line in graphics]+ hits = await page.evaluate("() => window.__hits")++ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 2, result.data["summary"]+ assert len(graphics) == 2, result.content+ assert all(click.status == "ok" for click in clicks), [click.content for click in clicks]+ assert sorted(hits) == ["first", "second"]+++@_skip_no_browser+async def test_observe_ignores_cursor_rules_under_inactive_conditions() -> None:+ html = """<!doctype html><html><head><style>+ .container { container-type:inline-size; width:100px }+ .row { cursor:pointer }+ .row .paint { display:inline-block; width:24px; height:24px; background:#333 }+ @supports (display: unsupported-value) {+ .row { .unsupported { cursor:pointer } }+ }+ @container (min-width: 800px) {+ .row { .container-inactive { cursor:pointer } }+ }+ @media screen {+ .row { .media-active { cursor:pointer } }+ }+ </style></head><body>+ <div class="container"><div class="row">+ <a href="#invoice">Invoice 9</a>+ <div class="paint unsupported"></div>+ <div class="paint container-inactive"></div>+ <div class="paint media-active" id="media-active"></div>+ </div></div>+ </body></html>"""+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+++@_skip_no_browser+async def test_unnamed_pointer_miss_dedup_stops_at_cursor_default() -> None:+ html = """<!doctype html><html><head><style>+ #outer, #inner { cursor:pointer; display:block; width:64px; height:64px; background:#333 }+ #boundary { cursor:default; width:80px; height:80px }+ </style></head><body>+ <div id="outer"><div id="boundary"><div id="inner"></div></div></div>+ </body></html>"""+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ assert result.data["summary"]["unnamed_not_icon"] == 2, result.data["summary"]+++@_skip_no_browser+async def test_observe_does_not_list_a_slot_wrapper_for_its_light_dom_control() -> None:+ html = """<!doctype html><html><body>+ <x-action><button slot="action">Save</button></x-action>+ <script>+ customElements.define('x-action', class extends HTMLElement {+ constructor() {+ super();+ this.attachShadow({mode: 'open'}).innerHTML =+ '<div style="cursor:pointer"><slot name="action"></slot></div>';+ }+ });+ </script>+ </body></html>"""+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ save_lines = [line for line in result.content.splitlines() if line.startswith("ref=") and "'Save'" in line]+ assert len(save_lines) == 1, result.content+ assert "button/submit 'Save'" in save_lines[0], result.content+++@_skip_no_browser+async def test_observe_uses_native_treewalker_when_document_name_shadows_it() -> None:+ html = """<!doctype html><html><body>+ <div style="cursor:pointer">Invoice 9</div>+ <img name="createTreeWalker" src="data:,">+ </body></html>"""+ async with _live_page(html) as page:+ assert await page.evaluate("() => document.createTreeWalker.tagName") == "IMG"+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ assert any("div 'Invoice 9'" in line for line in result.content.splitlines()), result.content+++_CSS_ICON_PAINT_HTML = (+ "<!doctype html><html><head><style>"+ ".icon{cursor:pointer;display:inline-block;width:24px;height:24px}"+ "#border-top{border-top:2px solid rgb(30,60,90)}"+ "#border-right{border-right:2px solid rgb(30,60,90)}"+ "#border-bottom{border-bottom:2px solid rgb(30,60,90)}"+ "#border-left{border-left:2px solid rgb(30,60,90)}"+ "#outline{outline:2px solid rgb(30,60,90)}"+ "#shadow{box-shadow:0 0 3px 1px rgb(30,60,90)}"+ "#gradient{background-image:linear-gradient(rgb(30,60,90),rgb(90,60,30))}"+ "#pseudo::before{content:'\\22EE';color:rgb(30,60,90)}"+ "#text-shadow-pseudo::before{content:'\\22EE';color:transparent;text-shadow:0 0 #333}"+ "#empty-content-pseudo::before{content:'';display:block;width:8px;height:8px;background:#333}"+ "#zero-area-pseudo::before{content:'';display:block;width:0;height:0;background:#333}"+ "#whitespace-text-shadow-pseudo::before{content:' ';color:transparent;text-shadow:0 0 #333}"+ "#transparent-border{border:2px solid rgba(0,0,0,0)}"+ "#transparent-outline{outline:2px solid rgba(0,0,0,0)}"+ "#transparent-shadow{box-shadow:0 0 0 0 rgba(0,0,0,0)}"+ "#transparent-gradient{background-image:linear-gradient(transparent,transparent)}"+ "#clip-hidden{background:#333;clip-path:inset(50%)}"+ "#clip-circle-hidden{background:#333;clip-path:circle(0)}"+ "#clip-ellipse-hidden{background:#333;clip-path:ellipse(0 50% at 50% 50%)}"+ "#clip-polygon-hidden{background:#333;clip-path:polygon(0 0,100% 100%,50% 50%)}"+ "#clip-polygon-visible{background:#333;clip-path:polygon(50% 0,100% 100%,0 100%)}"+ ".child{display:inline-block;width:8px;height:8px;background:#f00}"+ "#outside-descendant{position:relative}"+ "#outside-descendant .child{position:absolute;left:32px;cursor:default}"+ "#display-none .child{display:none}"+ "#visibility-hidden .child{visibility:hidden}"+ "#opacity-zero .child{opacity:0}"+ "#transparent-pseudo::before{content:'\\22EE';color:transparent}"+ "#hidden-pseudo::before{content:'\\22EE';visibility:hidden;color:#333}"+ "#no-content-pseudo::before{content:normal;display:block;width:8px;height:8px;background:#333}"+ "#whitespace-content-pseudo::before{content:' ';color:#333}"+ "#clipped-pseudo::before{content:'';display:block;width:8px;height:8px;background:#333;clip-path:inset(50%)}"+ "#zero-size-child .child{width:0;height:0}"+ "</style></head><body>"+ '<div>Paint border-top <div id="border-top" class="icon"></div></div>'+ '<div>Paint border-right <div id="border-right" class="icon"></div></div>'+ '<div>Paint border-bottom <div id="border-bottom" class="icon"></div></div>'+ '<div>Paint border-left <div id="border-left" class="icon"></div></div>'+ '<div>Paint outline <div id="outline" class="icon"></div></div>'+ '<div>Paint shadow <div id="shadow" class="icon"></div></div>'+ '<div>Paint gradient <div id="gradient" class="icon"></div></div>'+ '<div>Paint pseudo <div id="pseudo" class="icon"></div></div>'+ '<div>Paint text-shadow-pseudo <div id="text-shadow-pseudo" class="icon"></div></div>'+ '<div>Paint empty-content-pseudo <div id="empty-content-pseudo" class="icon"></div></div>'+ '<div>Paint zero-area-pseudo <div id="zero-area-pseudo" class="icon"></div></div>'+ '<div>Paint whitespace-text-shadow-pseudo <div id="whitespace-text-shadow-pseudo" class="icon"></div></div>'+ '<div>Paint transparent-border <div id="transparent-border" class="icon"></div></div>'+ '<div>Paint transparent-outline <div id="transparent-outline" class="icon"></div></div>'+ '<div>Paint transparent-shadow <div id="transparent-shadow" class="icon"></div></div>'+ '<div>Paint transparent-gradient <div id="transparent-gradient" class="icon"></div></div>'+ '<div>Paint clip-hidden <div id="clip-hidden" class="icon"></div></div>'+ '<div>Paint clip-circle-hidden <div id="clip-circle-hidden" class="icon"></div></div>'+ '<div>Paint clip-ellipse-hidden <div id="clip-ellipse-hidden" class="icon"></div></div>'+ '<div>Paint clip-polygon-hidden <div id="clip-polygon-hidden" class="icon"></div></div>'+ '<div>Paint clip-polygon-visible <div id="clip-polygon-visible" class="icon"></div></div>'+ '<div>Paint outside-descendant <div id="outside-descendant" class="icon"><span class="child"></span></div></div>'+ '<div>Paint display-none <div id="display-none" class="icon"><span class="child"></span></div></div>'+ '<div>Paint visibility-hidden <div id="visibility-hidden" class="icon"><span class="child"></span></div></div>'+ '<div>Paint opacity-zero <div id="opacity-zero" class="icon"><span class="child"></span></div></div>'+ '<div>Paint transparent-pseudo <div id="transparent-pseudo" class="icon"></div></div>'+ '<div>Paint hidden-pseudo <div id="hidden-pseudo" class="icon"></div></div>'+ '<div>Paint no-content-pseudo <div id="no-content-pseudo" class="icon"></div></div>'+ '<div>Paint whitespace-content-pseudo <div id="whitespace-content-pseudo" class="icon"></div></div>'+ '<div>Paint clipped-pseudo <div id="clipped-pseudo" class="icon"></div></div>'+ '<div>Paint zero-size-child <div id="zero-size-child" class="icon"><span class="child"></span></div></div>'+ "</body></html>"+)+++@_skip_no_browser+async def test_css_icon_detection_requires_visible_ink() -> None:+ async with _live_page(_CSS_ICON_PAINT_HTML) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ summary = result.data["summary"]+ visible = {+ "border-top",+ "border-right",+ "border-bottom",+ "border-left",+ "outline",+ "shadow",+ "gradient",+ "pseudo",+ "text-shadow-pseudo",+ "empty-content-pseudo",+ "clip-polygon-visible",+ }+ invisible = {+ "transparent-border",+ "transparent-outline",+ "transparent-shadow",+ "transparent-gradient",+ "clip-hidden",+ "clip-circle-hidden",+ "clip-ellipse-hidden",+ "clip-polygon-hidden",+ "outside-descendant",+ "display-none",+ "visibility-hidden",+ "opacity-zero",+ "transparent-pseudo",+ "zero-area-pseudo",+ "hidden-pseudo",+ "no-content-pseudo",+ "whitespace-content-pseudo",+ "whitespace-text-shadow-pseudo",+ "clipped-pseudo",+ "zero-size-child",+ }+ assert summary["icons_listed"] == len(visible), summary+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ assert all(any(f"id='{id}'" in line for line in lines) for id in visible), result.content+ assert all(not any(f"id='{id}'" in line for line in lines) for id in invisible), result.content+++@_skip_no_browser+async def test_css_icon_detection_covers_the_closed_paint_channel_set() -> None:+ image = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16'%3E%3Crect width='16' height='16' fill='red'/%3E%3C/svg%3E"+ html = f"""<!doctype html><html><head><style>+ .channel {{ display:inline-block; cursor:pointer; width:24px; height:24px; margin:2px }}+ #background-color {{ background-color:#333 }}+ #background-image {{ background-image:linear-gradient(#333,#666) }}+ #border {{ border:1px solid #333 }}+ #outline {{ outline:1px solid #333 }}+ #box-shadow {{ box-shadow:1px 1px 0 #333 }}+ #before::before {{ content:'⋮'; color:#333; font-size:18px }}+ #after::after {{ content:''; display:block; width:8px; height:8px; background:#333 }}+ #text-glyph {{ color:#333; font-size:18px }}+ #replaced {{ width:24px; height:24px }}+ </style></head><body>+ <span id="background-color" class="channel"></span>+ <span id="background-image" class="channel"></span>+ <span id="border" class="channel"></span>+ <span id="outline" class="channel"></span>+ <span id="box-shadow" class="channel"></span>+ <span id="before" class="channel"></span>+ <span id="after" class="channel"></span>+ <span id="text-glyph" class="channel">⋮</span>+ <img id="replaced" class="channel" alt="" src="{image}">+ </body></html>"""+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]++ assert result.status == "ok", result.content+ names = (+ "background-color",+ "background-image",+ "border",+ "outline",+ "box-shadow",+ "before",+ "after",+ )+ listed = [name for name in names if any(f"id='{name}'" in line for line in lines)]+ assert result.data["summary"]["icons_listed"] == 8, result.data["summary"]+ assert len(listed) == len(names), (result.content, listed)+ assert len(lines) == 9 and any("span '⋮'" in line for line in lines), result.content+ assert any("img ''" in line for line in lines), result.content+++@_skip_no_browser+async def test_transparent_pointer_overlay_is_not_listed_or_clicked_as_an_icon() -> None:+ html = """<!doctype html><html><head><style>+ #pay, #overlay { position:absolute; left:0; top:0; width:40px; height:40px }+ #overlay { cursor:pointer; border:2px solid transparent; z-index:1 }+ </style></head><body>+ <button id="pay">Pay</button>+ <div id="overlay"></div>+ <script>window.__clicks=[];document.addEventListener('click',e=>window.__clicks.push(e.target.id));</script>+ </body></html>"""+ async with _live_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ pay = next(line for line in lines if "button/submit 'Pay'" in line)+ click = await _tool(tools, "click").handler({"selector": _ref_line(pay, "button/submit 'Pay'")})+ clicks = await page.evaluate("() => window.__clicks")++ assert result.status == "ok", result.content+ assert not any("id='overlay'" in line for line in lines), result.content+ assert click.status == "error", click.content+ assert "covered by" in click.content, click.content+ assert clicks == []+++@_skip_no_browser+async def test_css_icon_detection_rejects_fully_clipped_ancestor() -> None:+ html = """<!doctype html><html><head><style>+ #pay, #clipper { position:absolute; left:0; top:0; width:24px; height:24px }+ #clipper { clip-path:circle(0); z-index:1 }+ #icon { cursor:pointer; width:24px; height:24px; background:#333 }+ </style></head><body>+ <button id="pay">Pay</button>+ <div id="clipper"><div id="icon"></div></div>+ </body></html>"""+ async with _live_page(html) as page:+ facts = await page.evaluate(+ "() => ({"+ "clip:getComputedStyle(document.querySelector('#clipper')).clipPath,"+ "visible:document.querySelector('#icon').checkVisibility(),"+ "hit:document.elementFromPoint(12,12)?.id})"+ )+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]++ assert facts["clip"].startswith("circle(0"), facts+ assert facts["visible"] is True, facts+ assert facts["hit"] == "pay", facts+ assert result.status == "ok", result.content+ assert any("button/submit 'Pay'" in line for line in lines), result.content+ assert not any("id='icon'" in line for line in lines), result.content+++@_skip_no_browser+async def test_css_icon_detection_respects_clip_edges_and_hidden_scroll_reachability() -> None:+ html = """<!doctype html><html><head><style>+ #pay { position:absolute; left:0; top:0; width:300px; height:210px }+ #clipper, #overflow-hidden, #overflow-clip, #overflow-margin, #overflow-scrollable, #overflow-unreachable {+ position:absolute; left:0; width:100px; height:24px; z-index:1+ }+ #clipper { top:0; clip-path:inset(0 50% 0 0) }+ #icon { position:absolute; left:70px; cursor:pointer; width:24px; height:24px; background:#333 }+ #svg-icon { position:absolute; left:70px; top:0; cursor:pointer; width:24px; height:24px }+ #overflow-hidden { top:30px; overflow:hidden }+ #overflow-clip { top:60px; overflow:clip }+ #overflow-margin { top:90px; overflow:clip; overflow-clip-margin:padding-box 30px }+ #overflow-scrollable { top:120px; overflow:hidden }+ #overflow-unreachable { top:150px; left:80px; overflow:hidden }+ #hidden-icon, #clip-icon, #partial-clip-icon, #margin-icon, #scroll-icon, #unreachable-icon {+ position:absolute; top:0; cursor:pointer; width:24px; height:24px; background:#333+ }+ #hidden-icon, #clip-icon, #margin-icon { left:110px }+ #partial-clip-icon { left:90px }+ #scroll-content, #unreachable-content { position:relative; width:220px; height:24px }+ #scroll-icon { left:90px }+ #unreachable-icon { left:-30px }+ </style></head><body>+ <button id="pay">Pay</button>+ <div id="clipper"><div id="icon"></div><svg id="svg-icon" viewBox="0 0 24 24"><path fill="#333" d="M0 0h24v24H0z"/></svg></div>+ <div id="overflow-hidden"><div id="hidden-icon"></div></div>+ <div id="overflow-clip"><div id="clip-icon"></div><div id="partial-clip-icon"></div></div>+ <div id="overflow-margin"><div id="margin-icon"></div></div>+ <div id="overflow-scrollable"><div id="scroll-content"><div id="scroll-icon"></div></div></div>+ <div id="overflow-unreachable"><div id="unreachable-content"><div id="unreachable-icon"></div></div></div>+ </body></html>"""+ async with _live_page(html) as page:+ facts = await page.evaluate(+ "() => ({clip:getComputedStyle(document.querySelector('#clipper')).clipPath,"+ "clipMargin:getComputedStyle(document.querySelector('#overflow-margin')).overflowClipMargin,"+ "scroll:[document.querySelector('#overflow-scrollable').scrollWidth,"+ "document.querySelector('#overflow-scrollable').clientWidth],"+ "unreachable:[document.querySelector('#overflow-unreachable').scrollWidth,"+ "document.querySelector('#overflow-unreachable').clientWidth],"+ "hits:[document.elementFromPoint(82,12)?.id,document.elementFromPoint(122,42)?.id,"+ "document.elementFromPoint(122,72)?.id,document.elementFromPoint(102,72)?.id,"+ "document.elementFromPoint(122,102)?.id,document.elementFromPoint(102,132)?.id,"+ "document.elementFromPoint(62,162)?.id]})"+ )+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]++ assert facts["clip"].startswith("inset("), facts+ assert facts["clipMargin"] == "30px", facts+ assert facts["scroll"][0] > facts["scroll"][1], facts+ assert facts["unreachable"][0] > facts["unreachable"][1], facts+ assert facts["hits"] == ["pay", "pay", "pay", "pay", "margin-icon", "pay", "pay"], facts+ assert result.status == "ok", result.content+ assert any("button/submit 'Pay'" in line for line in lines), result.content+ assert not any("id='icon'" in line for line in lines), result.content+ assert not any("id='svg-icon'" in line for line in lines), result.content+ assert not any("id='clip-icon'" in line for line in lines), result.content+ assert not any("id='partial-clip-icon'" in line for line in lines), result.content+ assert not any("id='unreachable-icon'" in line for line in lines), result.content+ assert any("id='hidden-icon'" in line for line in lines), result.content+ assert any("id='margin-icon'" in line for line in lines), result.content+ assert any("id='scroll-icon'" in line for line in lines), result.content+++@_skip_no_browser+async def test_css_icon_detection_rejects_zero_opacity_filters() -> None:+ html = """<!doctype html><html><head><style>+ .target { cursor:pointer; display:inline-block; width:24px; height:24px; background:#333 }+ #filtered-child span { filter:opacity(0); background:#333; display:inline-block; width:8px; height:8px }+ #filtered-pseudo::before { content:'\\22EE'; filter:opacity(0); background:#333 }+ #hidden-ancestor { filter:opacity(0) }+ </style></head><body>+ <div id="filtered-target" class="target" style="filter:opacity(0)"></div>+ <div id="filtered-child" class="target" style="background:none"><span></span></div>+ <div id="filtered-pseudo" class="target" style="background:none"></div>+ <div id="hidden-ancestor"><div id="filtered-descendant" class="target"></div></div>+ <x-hidden><div id="filtered-slotted" slot="target" class="target"></div></x-hidden>+ <script>+ customElements.define('x-hidden', class extends HTMLElement {+ constructor() {+ super();+ this.attachShadow({mode:'open'}).innerHTML =+ '<div style="filter:opacity(0)"><slot name="target"></slot></div>';+ }+ });+ </script>+ </body></html>"""+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ assert result.data["summary"]["icons_listed"] == 0, result.data["summary"]+ assert not any(+ f"id='{id}'" in line+ for line in lines+ for id in ("filtered-target", "filtered-child", "filtered-pseudo", "filtered-descendant", "filtered-slotted")+ ), result.content+++@_skip_no_browser+async def test_nested_pointer_scan_work_is_bounded() -> None:+ count = 200+ html = (+ "<!doctype html><html><head><style>"+ ".pointer{cursor:pointer;display:block;width:24px;height:24px}"+ "</style></head><body>" + '<div class="pointer">' * count + "</div>" * count + "</body></html>"+ )+ async with _live_page(html) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ started = time.monotonic()+ result = await _tool(tools, "observe").handler({})+ elapsed = time.monotonic() - started++ assert result.status == "ok", result.content+ assert elapsed < 5, f"nested pointer scan took {elapsed:.2f}s"+++@_skip_no_browser+async def test_nested_pointer_scan_caches_each_descendants_pseudo_ink_result() -> None:+ count = 12+ html = (+ "<!doctype html><html><head><style>"+ ".pointer{cursor:pointer;display:block;width:24px;height:24px}"+ "#ink::before{content:'\\22EE';color:transparent}"+ "</style></head><body>"+ + '<div class="pointer">' * count+ + '<span id="ink"></span>'+ + "</div>" * count+ + "</body></html>"+ )+ async with _live_page(html) as page:+ await page.evaluate(+ """() => {+ const native = window.getComputedStyle;+ window.__inkPseudoReads = 0;+ window.getComputedStyle = function (element, pseudo) {+ if (element.id === 'ink' && pseudo === '::before') window.__inkPseudoReads++;+ return native.call(window, element, pseudo);+ };+ }"""+ )+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})+ reads = await page.evaluate("() => window.__inkPseudoReads")++ assert result.status == "ok", result.content+ assert reads == 1, f"descendant pseudo ink was recomputed {reads} times"+++@_skip_no_browser+async def test_icon_budget_overflow_is_not_reported_as_an_ink_miss() -> None:+ icons = "".join(f'<span id="icon-{i}" class="icon"></span>' for i in range(400))+ icons += "<span id=icon-400 class=icon><svg width=24 height=24><rect width=24 height=24></rect></svg></span>"+ html = (+ "<!doctype html><html><head><style>"+ ".icon{cursor:pointer;display:inline-block;width:24px;height:24px;background:#333}"+ "</style></head><body>" + icons + "</body></html>"+ )+ async with _live_page(html) as page:+ result = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})++ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 250, result.data["summary"]+ assert result.data["summary"]["unnamed_not_icon"] == 0, result.data["summary"]+ assert result.data["summary"]["icons_truncated"] == 151, result.data["summary"]+++_ROW_CSS_ACTIONS_HTML = (+ "<!doctype html><html><head><style>"+ ".row{display:flex;cursor:pointer;width:300px;height:36px;align-items:center}"+ ".status-dot{display:inline-block;width:10px;height:10px;border-radius:50%;background:#e33}"+ ".actions{display:inline-flex;cursor:pointer;width:44px;height:20px}"+ ".action{display:inline-block;cursor:pointer;width:22px;height:20px}"+ ".action::before{color:#333;font-size:12px}"+ ".copy::before{content:'C'}.delete::before{content:'D'}"+ "</style></head><body>"+ '<div class="row"><input type="checkbox"><span id="status-dot" class="status-dot"></span>'+ '<span>Invoice</span><div id="actions" class="actions">'+ '<span id="copy-action" class="action copy"></span>'+ '<span id="delete-action" class="action delete"></span></div></div>'+ "<script>window.__actions=[];document.addEventListener('click',e=>{"+ "const a=e.target.closest('.action');if(a)window.__actions.push(a.id);});</script>"+ "</body></html>"+)+++@_skip_no_browser+async def test_css_icons_in_clickable_rows_skip_decorations_and_keep_separate_actions() -> None:+ async with _live_page(_ROW_CSS_ACTIONS_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ assert result.status == "ok", result.content+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ action_lines = [line for line in lines if "id='copy-action'" in line or "id='delete-action'" in line]++ assert result.data["summary"]["icons_listed"] == 2, (result.data["summary"], result.content)+ assert len(action_lines) == 2, result.content+ assert not any("id='actions'" in line or "id='status-dot'" in line for line in lines), result.content+ for line in action_lines:+ click = await _tool(tools, "click").handler({"selector": _ref_line(line, "span ''")})+ assert click.status == "ok", click.content+ actions = await page.evaluate("() => window.__actions")++ assert actions == ["copy-action", "delete-action"]+++@_skip_no_browser+async def test_css_icon_cursor_uses_the_winning_declaration() -> None:+ html = """<!doctype html><html><head><style>+ .row { display:flex; cursor:pointer; width:300px; height:36px; align-items:center }+ .action { display:inline-block; cursor:pointer; width:22px; height:20px; background:#333 }+ #real-action { cursor:pointer }+ .row .action { cursor:inherit }+ </style></head><body>+ <div class="row"><input type="checkbox"><span>Invoice</span>+ <span id="decorative-action" class="action"></span>+ <span id="real-action" class="action"></span>+ </div>+ <script>window.__action=false;document.addEventListener('click',e=>{+ if(e.target.id==='real-action')window.__action=true;+ });</script>+ </body></html>"""+ async with _live_page(html) as page:+ assert await page.locator("#decorative-action").evaluate("el => getComputedStyle(el).cursor") == "pointer"+ assert await page.locator("#real-action").evaluate("el => getComputedStyle(el).cursor") == "pointer"+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ lines = [line for line in result.content.splitlines() if line.startswith("ref=")]+ action_lines = [line for line in lines if "span ''" in line]+ assert len(action_lines) == 1, result.content+ click = await _tool(tools, "click").handler({"selector": _ref_line(action_lines[0], "span ''")})+ action = await page.evaluate("() => window.__action")++ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+ assert click.status == "ok", click.content+ assert action is True+++@_skip_no_browser+async def test_css_icon_cursor_fails_closed_for_layer_and_scope_rules() -> None:+ html = """<!doctype html><html><head><style>+ @layer early { #row .layered { cursor:pointer } }+ @layer late { .row .layered { cursor:inherit } }+ @scope (#outside) { .scoped { cursor:pointer } }+ .row { display:flex; cursor:pointer; width:300px; height:36px; align-items:center }+ .action { display:inline-block; width:22px; height:20px; background:#333 }+ </style></head><body>+ <div id="outside"></div>+ <div id="row" class="row">+ <input type="checkbox"><a href="/invoice">Invoice</a>+ <span id="layered" class="action layered"></span>+ <span id="scoped" class="action scoped"></span>+ <span id="real-action" class="action layered scoped" style="cursor:pointer" onclick="window.__realAction=true"></span>+ </div>+ <script>window.__realAction=false;</script>+ </body></html>"""+ async with _live_page(html) as page:+ cursors = await page.evaluate(+ "() => ['layered','scoped','real-action'].map(id => getComputedStyle(document.getElementById(id)).cursor)"+ )+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ action_lines = [line for line in result.content.splitlines() if line.startswith("ref=") and "span ''" in line]+ click = await _tool(tools, "click").handler({"selector": _ref_line(action_lines[0], "span ''")})+ clicked = await page.evaluate("() => window.__realAction")++ assert cursors == ["pointer", "pointer", "pointer"], cursors+ assert result.status == "ok", result.content+ assert result.data["summary"]["icons_listed"] == 1, result.data["summary"]+ assert len(action_lines) == 1, result.content+ assert click.status == "ok" and clicked is True, (click.content, clicked)+++_SHADOW_ROW_CSS_ACTION_HTML = (+ "<!doctype html><html><body>"+ '<div class="row" style="display:flex;cursor:pointer;width:300px;height:36px;align-items:center">'+ '<a href="/invoice">Invoice</a><x-menu></x-menu></div>'+ "<script>window.__shadowAction=false;customElements.define('x-menu',class extends HTMLElement{"+ "constructor(){super();const root=this.attachShadow({mode:'open'});"+ "root.innerHTML='<style>.action{cursor:pointer;display:inline-block;width:24px;height:24px}"+ '.action::before{content:"⋮";color:#333}</style><span id="shadow-action" class="action"></span>\';'+ "root.getElementById('shadow-action').addEventListener('click',()=>window.__shadowAction=true);}});</script>"+ "</body></html>"+)+++@_skip_no_browser+async def test_shadow_root_stylesheet_cursor_keeps_css_action_in_clickable_row() -> None:+ async with _live_page(_SHADOW_ROW_CSS_ACTION_HTML) as page:+ tools = build_browser_tools(_fixed_page_provider(page))+ result = await _tool(tools, "observe").handler({})+ assert result.status == "ok", result.content+ actions = [line for line in result.content.splitlines() if line.startswith("ref=") and " span ''" in line]+ assert len(actions) == 1, result.content+ action = actions[0]+ click = await _tool(tools, "click").handler({"selector": _ref_line(action, "span ''")})+ hit = await page.evaluate("() => window.__shadowAction")++ assert click.status == "ok", click.content+ assert hit is True++@_skip_no_browser@pytest.mark.asyncioasync def test_observe_labels_an_icon_by_its_graphic_without_spending_a_named_root_slot() -> None:@@ -13433,7 +14280,14 @@ async def _code_with_no_resolver(page: Any, mp: pytest.MonkeyPatch) -> tuple[lisasync def _code_with_no_secret(page: Any, mp: pytest.MonkeyPatch) -> tuple[list[Any], str, dict[str, Any]]:- task = SimpleNamespace(task_id="tsk_otp", organization_id="o_1", workflow_run_id=None)+ task = SimpleNamespace(+ task_id="tsk_otp",+ organization_id="o_1",+ workflow_run_id=None,+ totp_verification_url=None,+ totp_identifier=None,+ navigation_payload=None,+ )tools = build_browser_tools(_fixed_page_provider(page),resolve_typed_text=lambda text: "BW_TOTP",diff --git a/tests/unit/test_text_prompt_block.py b/tests/unit/test_text_prompt_block.pyindex 96b74a81b..9bbc32fdd 100644--- a/tests/unit/test_text_prompt_block.py+++ b/tests/unit/test_text_prompt_block.py@@ -85,7 +85,7 @@ def test_block_explicit_llm_key_wins_over_org_default(monkeypatch: pytest.Monkey@pytest.mark.asyncio@pytest.mark.parametrize("model_name",- ["gemini-2.5-flash", "gemini-3-pro-preview"],+ ["gemini-3.0-flash", "gemini-3-pro-preview"],)async def test_text_prompt_block_uses_selected_model(monkeypatch, model_name):# Reset SettingsManager to base settings so cloud overrides from earlier tests don't leak@@ -982,7 +982,7 @@ async def test_text_prompt_block_non_transient_db_error_not_retried(monkeypatch)async def test_text_prompt_block_uses_fallback_llm_key_when_available(monkeypatch):"""send_prompt upgrades the block's key to a fallback-capable key when one exists."""block = _make_text_prompt_block(prompt="Summarize status.")- block.llm_key = "VERTEX_GEMINI_2.5_FLASH"+ block.llm_key = "VERTEX_GEMINI_3.0_FLASH"captured: dict[str, str | None] = {}handler = AsyncMock(return_value={"llm_response": "ok"})@@ -998,13 +998,13 @@ async def test_text_prompt_block_uses_fallback_llm_key_when_available(monkeypatcmonkeypatch.setattr(block_module.app.AGENT_FUNCTION,"get_fallback_llm_key",- lambda llm_key: "GEMINI_2_5_FLASH_WITH_FALLBACK",+ lambda llm_key: "GEMINI_3_0_FLASH_WITH_FALLBACK",raising=False,)await block.send_prompt(block.prompt, workflow_run_id="wr", organization_id="org-1")- assert captured["llm_key"] == "GEMINI_2_5_FLASH_WITH_FALLBACK"+ assert captured["llm_key"] == "GEMINI_3_0_FLASH_WITH_FALLBACK"@pytest.mark.asyncio@@ -1014,7 +1014,7 @@ async def test_text_prompt_block_org_default_derives_key_for_fallback(monkeypatcblock.llm_key = Nonecaptured: dict[str, str | None] = {}handler = AsyncMock(return_value={"llm_response": "ok"})- handler.llm_key = "VERTEX_GEMINI_2.5_FLASH"+ handler.llm_key = "VERTEX_GEMINI_3.0_FLASH"async def fake_resolve(*args, **kwargs):return handler@@ -1034,7 +1034,7 @@ async def test_text_prompt_block_org_default_derives_key_for_fallback(monkeypatcawait block.send_prompt(block.prompt, workflow_run_id="wr", organization_id="org-1")- assert captured["llm_key"] == "VERTEX_GEMINI_2.5_FLASH_WITH_FALLBACK"+ assert captured["llm_key"] == "VERTEX_GEMINI_3.0_FLASH_WITH_FALLBACK"def test_workflow_request_deserialization_strips_invalid_text_prompt_llm_key() -> None:diff --git a/tests/unit/test_text_prompt_block_yaml.py b/tests/unit/test_text_prompt_block_yaml.pyindex 5a67bedba..87eacb00b 100644--- a/tests/unit/test_text_prompt_block_yaml.py+++ b/tests/unit/test_text_prompt_block_yaml.py@@ -21,16 +21,16 @@ class TestTextPromptBlockYAMLNormalization:def test_converts_known_llm_key_to_model(self, monkeypatch) -> None:monkeypatch.setattr(SettingsManager, "_SettingsManager__instance", base_settings)- # Use the actual llm_key that base_settings maps gemini-2.5-flash to- # (VERTEX_GEMINI_2.5_FLASH when ENABLE_VERTEX_AI=True, GEMINI_2.5_FLASH otherwise)- actual_llm_key = base_settings.get_model_name_to_llm_key()["gemini-2.5-flash"]["llm_key"]+ # Use the actual llm_key that base_settings maps gemini-3.0-flash to+ # (VERTEX_GEMINI_3.0_FLASH when ENABLE_VERTEX_AI=True, GEMINI_3.0_FLASH otherwise)+ actual_llm_key = base_settings.get_model_name_to_llm_key()["gemini-3.0-flash"]["llm_key"]block = TextPromptBlockYAML(label="summarize",prompt="Summarize the data.",llm_key=actual_llm_key,)- assert block.model == {"model_name": "gemini-2.5-flash"}+ assert block.model == {"model_name": "gemini-3.0-flash"}assert block.llm_key is Nonedef test_clears_invalid_llm_key_to_use_default_model(self, monkeypatch) -> None:diff --git a/tests/unit/test_update_workflow_route.py b/tests/unit/test_update_workflow_route.pyindex 169565cb0..b9728204c 100644--- a/tests/unit/test_update_workflow_route.py+++ b/tests/unit/test_update_workflow_route.py@@ -18,7 +18,8 @@ from fastapi.responses import JSONResponsefrom fastapi.testclient import TestClientfrom skyvern.exceptions import SkyvernHTTPException-from skyvern.forge.sdk.routes.routers import base_router+from skyvern.forge.sdk.db.repositories.workflows import WorkflowCreationLockTimeout+from skyvern.forge.sdk.routes.routers import base_router, legacy_base_routerfrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.services import org_auth_servicefrom skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowDefinition@@ -43,6 +44,7 @@ def client() -> TestClient:app = FastAPI()app.include_router(base_router, prefix="/v1")+ app.include_router(legacy_base_router, prefix="/v1")# Mirror api_app.py so a raised SkyvernHTTPException renders as its own status code# (e.g. the pre-fix FailedToUpdateWorkflow would render as 500 here, not be re-raised).@@ -63,6 +65,30 @@ def test_update_workflow_without_definition_returns_422(client: TestClient) -> Nassert "json" in resp.json()["detail"].lower()[email protected]("legacy", [False, True], ids=["current", "legacy"])+def test_workflow_save_lock_timeout_returns_retryable_conflict(client: TestClient, legacy: bool) -> None:+ mock_app = MagicMock()+ mock_app.WORKFLOW_SERVICE.create_workflow_from_request = AsyncMock(side_effect=WorkflowCreationLockTimeout())+ yaml_definition = "title: t\nworkflow_definition:\n parameters: []\n blocks: []\n"+ with (+ patch("skyvern.forge.sdk.routes.agent_protocol.app", mock_app),+ patch("skyvern.forge.sdk.routes.agent_protocol._authorize_definition_references", AsyncMock()),+ patch("skyvern.forge.sdk.routes.agent_protocol.analytics.capture", lambda *_: None),+ ):+ if legacy:+ response = client.put(+ "/v1/workflows/wpid_test",+ content=yaml_definition,+ headers={"Content-Type": "application/x-yaml"},+ )+ else:+ response = client.post("/v1/workflows/wpid_test", json={"yaml_definition": yaml_definition})++ assert response.status_code == 409, response.text+ assert "retry" in response.json()["detail"].lower()+ mock_app.WORKFLOW_SERVICE.create_workflow_from_request.assert_awaited_once()++def _stored_workflow() -> Workflow:now = dt.datetime.now(dt.timezone.utc)return Workflow(diff --git a/tests/unit/test_workflow_browser_profile_id.py b/tests/unit/test_workflow_browser_profile_id.pyindex f6318e991..bc106d63c 100644--- a/tests/unit/test_workflow_browser_profile_id.py+++ b/tests/unit/test_workflow_browser_profile_id.py@@ -709,6 +709,7 @@ def _make_workflow_update_service() -> tuple[WorkflowService, SimpleNamespace]:service = WorkflowService()existing_workflow = SimpleNamespace(+ workflow_id="wf_existing",version=2,proxy_location=None,totp_identifier=None,diff --git a/tests/unit/workflow/test_enterprise_feature_gating.py b/tests/unit/workflow/test_enterprise_feature_gating.pyindex c11d7c98a..89bff1b82 100644--- a/tests/unit/workflow/test_enterprise_feature_gating.py+++ b/tests/unit/workflow/test_enterprise_feature_gating.py@@ -138,7 +138,7 @@ def test_collects_conditional_branch_target_gated_blocks() -> None:def test_ignores_non_enterprise_models_and_engines() -> None:workflow = _workflow([_navigation_block("standard", model={"model_name": "gpt-4o"})],- model={"model_name": "gemini-2.5-flash"},+ model={"model_name": "gemini-3.0-flash"},)assert _collect_enterprise_gated_workflow_features(workflow) == set()diff --git a/tests/unit/workflow/test_file_parser_block.py b/tests/unit/workflow/test_file_parser_block.pyindex 2656c6b98..3336e44e5 100644--- a/tests/unit/workflow/test_file_parser_block.py+++ b/tests/unit/workflow/test_file_parser_block.py@@ -32,13 +32,24 @@ import structlogfrom pypdf import PdfReader, apply_configurationfrom pypdf.errors import LimitReachedError, PdfReadError+import skyvern.forge.sdk.utils.capped_subprocess as capped_subprocess_module+import skyvern.forge.sdk.utils.pdf_parser as pdf_parser_moduleimport skyvern.forge.sdk.workflow.models.block as block_module+from skyvern.config import settingsfrom skyvern.core.script_generations.generate_script import _build_file_url_parser_statementfrom skyvern.exceptions import PDFParsingErrorfrom skyvern.forge import appfrom skyvern.forge.forge_app_initializer import start_forge_appfrom skyvern.forge.sdk.api.llm.exceptions import InvalidLLMResponseFormat-from skyvern.forge.sdk.utils.pdf_parser import extract_pdf_file, scrambled_text_layer_reason, validate_pdf_file+from skyvern.forge.sdk.utils.capped_subprocess import MEMORY_CAP_ENFORCED, CappedSubprocessError+from skyvern.forge.sdk.utils.capped_subprocess_child import MIN_MEMORY_BUDGET_BYTES+from skyvern.forge.sdk.utils.pdf_parser import (+ extract_pdf_file,+ extract_upright_pdf_words,+ render_pdf_pages_as_images,+ scrambled_text_layer_reason,+ validate_pdf_file,+)from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.forge.sdk.workflow.exceptions import FileParseTimeout, InvalidFileType, WorksheetNotFoundfrom skyvern.forge.sdk.workflow.models.block import BlockType, FileParserBlock, PDFParserBlock@@ -1764,6 +1775,245 @@ class TestParsingDoesNotBlockEventLoop:assert ticks > 0+def _build_inflating_pdf(inflated_mib: int) -> bytes:+ """One text page, no xref table, and an object stream inflating to inflated_mib MiB of zeros.+ Past pypdf's 75 MB decompression limit pypdf cannot find the catalog, so the pdfplumber fallback gets the file."""+ compressor = zlib.compressobj(9)+ zeros = b"\x00" * (16 << 20)+ stream = compressor.compress(b"10 0 ") + b"".join(compressor.compress(zeros) for _ in range(inflated_mib // 16))+ stream += compressor.flush()+ content = b"BT /F1 12 Tf 72 720 Td (Invoice Total 1234.56 GBP) Tj ET"+ objects = [+ b"<< /Type /Catalog /Pages 2 0 R >>",+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 4 0 R >> >> "+ b"/Contents 5 0 R >>",+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ b"<< /Length %d >>\nstream\n" % len(content) + content + b"\nendstream",+ b"<< /Type /ObjStm /N 1 /First 5 /Filter /FlateDecode /Length %d >>\nstream\n" % len(stream)+ + stream+ + b"\nendstream",+ ]+ out = bytearray(b"%PDF-1.7\n")+ for number, payload in enumerate(objects, start=1):+ out += b"%d 0 obj\n" % number + payload + b"\nendobj\n"+ out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (len(objects) + 1, len(out))+ return bytes(out)+++def _build_letter_pdf(pages: int, lines: tuple[str, ...] = _INVOICE_LINES) -> bytes:+ """A Letter-size PDF with the same few lines of text on each page."""+ content = ("BT /F1 12 Tf 72 720 Td 16 TL\n" + "".join(f"({line}) Tj T*\n" for line in lines) + "ET").encode()+ objects = [+ b"<< /Type /Catalog /Pages 2 0 R >>",+ b"<< /Type /Pages /Kids [%s] /Count %d >>" % (b" ".join(b"%d 0 R" % (5 + i) for i in range(pages)), pages),+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ b"<< /Length %d >>\nstream\n" % len(content) + content + b"\nendstream",+ ]+ objects += [+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "+ b"/Resources << /Font << /F1 3 0 R >> >> /Contents 4 0 R >>"+ ] * pages+ out = bytearray(b"%PDF-1.4\n")+ offsets = []+ for number, payload in enumerate(objects, start=1):+ offsets.append(len(out))+ out += b"%d 0 obj\n" % number + payload + b"\nendobj\n"+ xref_at = len(out)+ out += b"xref\n0 %d\n" % (len(objects) + 1) + b"0000000000 65535 f \n"+ out += b"".join(b"%010d 00000 n \n" % offset for offset in offsets)+ out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (len(objects) + 1, xref_at)+ return bytes(out)+++class _RejectingPdfReader:+ def __init__(self, *args: object, **kwargs: object) -> None:+ raise ValueError("pypdf rejected the file")++[email protected](scope="module")+def inflating_pdf(tmp_path_factory: pytest.TempPathFactory) -> Path:+ path = tmp_path_factory.mktemp("inflating") / "inflating.pdf"+ path.write_bytes(_build_inflating_pdf(128))+ return path+++class TestPdfplumberFallbackIsContained:+ """pdfplumber's parser has no decoded-size limit, so a hostile PDF must fail alone, not OOM-kill the pod."""++ def test_fallback_that_outlives_the_parse_budget_fails_the_pdf(+ self, inflating_pdf: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(pdf_parser_module, "FILE_PARSE_STEP_TIMEOUT_SECONDS", 1)++ with pytest.raises(PDFParsingError, match="did not finish within 1 second"):+ extract_pdf_file(str(inflating_pdf))++ @pytest.mark.skipif(+ not MEMORY_CAP_ENFORCED, reason="only Linux enforces RLIMIT_AS; elsewhere the child is uncapped"+ )+ def test_fallback_that_outgrows_its_memory_cap_fails_the_pdf(+ self, inflating_pdf: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(settings, "PDFPLUMBER_MAX_MEMORY_BYTES", 16 * 1024 * 1024)++ with pytest.raises(PDFParsingError, match="ran out of memory"):+ extract_pdf_file(str(inflating_pdf))++ def test_words_past_the_word_cap_fail_the_lookup_instead_of_filling_the_pod(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Every glyph here is its own word, so a small file decodes to many times its pickled size in the parent."""+ crowded_pdf = tmp_path / "crowded.pdf"+ crowded_pdf.write_bytes(_build_letter_pdf(1, ("a " * 30,) * 20))+ monkeypatch.setattr(pdf_parser_module, "_UPRIGHT_WORDS_RESULT", pdf_parser_module._ResultLimit(16 * 1024, 6))++ with pytest.raises(CappedSubprocessError) as excinfo:+ extract_upright_pdf_words(str(crowded_pdf), {0})++ assert excinfo.value.kind == "result_too_large"++ def test_fallback_in_a_pod_without_free_memory_fails_the_pdf_before_parsing(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ cgroup = tmp_path / "cgroup"+ cgroup.mkdir()+ (cgroup / "memory.max").write_text(str(6144 * 1024 * 1024))+ (cgroup / "memory.current").write_text(str(6000 * 1024 * 1024))+ letter_pdf = tmp_path / "letter.pdf"+ letter_pdf.write_bytes(_build_letter_pdf(1))+ monkeypatch.setattr(capped_subprocess_module, "MEMORY_CAP_ENFORCED", True)+ monkeypatch.setattr(capped_subprocess_module, "CGROUP_DIR", str(cgroup))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)++ with pytest.raises(PDFParsingError, match="not enough free memory"):+ extract_pdf_file(str(letter_pdf))++ def test_page_images_past_the_result_cap_fail_the_render(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ letter_pdf = tmp_path / "letter.pdf"+ letter_pdf.write_bytes(_build_letter_pdf(3))+ monkeypatch.setattr(settings, "PDFPLUMBER_MAX_RESULT_BYTES", 16 * 1024)++ with pytest.raises(CappedSubprocessError, match="limit on page images"):+ render_pdf_pages_as_images(str(letter_pdf))++ @pytest.mark.skipif(+ not MEMORY_CAP_ENFORCED, reason="only Linux enforces RLIMIT_AS; elsewhere the child is uncapped"+ )+ @pytest.mark.parametrize(+ ("memory_ceiling", "letter_pages"),+ [+ pytest.param(None, 10, id="default ceiling"),+ pytest.param(MIN_MEMORY_BUDGET_BYTES, 1, id="budget floor"),+ ],+ )+ def test_ordinary_pdfs_fit_the_memory_budget(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, memory_ceiling: int | None, letter_pages: int+ ) -> None:+ if memory_ceiling is not None:+ monkeypatch.setattr(settings, "PDFPLUMBER_MAX_MEMORY_BYTES", memory_ceiling)+ text_pdf = tmp_path / "invoice.pdf"+ text_pdf.write_bytes(_build_pdf(_ITEMISED_INVOICE_LINES))+ letter_pdf = tmp_path / "letter.pdf"+ letter_pdf.write_bytes(_build_letter_pdf(letter_pages))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)++ with structlog.testing.capture_logs() as logs:+ text = extract_pdf_file(str(text_pdf))+ images = render_pdf_pages_as_images(str(letter_pdf))++ assert "Invoice Total: 1234.56 GBP" in text+ assert len(images) == letter_pages and all(image.startswith(b"\x89PNG") for image in images)+ finished = {+ log["target"].rpartition(".")[2]: log for log in logs if log["event"] == "Capped subprocess finished"+ }+ assert set(finished) == {"page_texts", "page_images"}+ for log in finished.values():+ assert log["memory_budget_bytes"] <= (memory_ceiling or settings.PDFPLUMBER_MAX_MEMORY_BYTES)+ assert 0 <= log["rss_growth_sampled_bytes"] < log["memory_budget_bytes"]+++class TestPdfplumberFallbackTokenLimit:+ def test_pages_the_character_stop_skipped_are_still_read_up_to_the_token_limit(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """A long run of one symbol is a few tokens, so the first pass stops at its character limit with the token+ cap not yet reached and the pages that fit must be read in a second pass."""+ symbols_pdf = tmp_path / "symbols.pdf"+ symbols_pdf.write_bytes(_build_letter_pdf(3, ("=" * 60,) * 3))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)++ text = extract_pdf_file(str(symbols_pdf), max_tokens=14)++ # Each page is 3 lines and 6 tokens: two pages fit under 14 tokens, the third does not.+ assert text.count("=" * 60) == 6++ def test_text_past_the_character_limit_is_cut_at_a_page_boundary(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ symbols_pdf = tmp_path / "symbols.pdf"+ symbols_pdf.write_bytes(_build_letter_pdf(6, ("=" * 60,) * 3))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)+ monkeypatch.setattr(pdf_parser_module, "_PAGE_TEXTS_CHAR_LIMIT", 500)++ with structlog.testing.capture_logs() as logs:+ text = extract_pdf_file(str(symbols_pdf), max_tokens=40)++ # Pages are 182 characters, so the read goes on to the third page, which takes it past 500.+ assert text.count("=" * 60) == 9+ assert any("exceeds the size limit" in log["event"] for log in logs)++ def test_a_second_pass_that_fails_keeps_the_pages_the_first_pass_read(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ symbols_pdf = tmp_path / "symbols.pdf"+ symbols_pdf.write_bytes(_build_letter_pdf(6, ("=" * 60,) * 3))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)+ run_in_capped_subprocess = pdf_parser_module.run_in_capped_subprocess+ passes: list[int] = []++ def time_out_on_the_second_pass(*args: Any, **kwargs: Any) -> Any:+ passes.append(1)+ if len(passes) == 2:+ raise CappedSubprocessError("did not finish within 1 second and was stopped", kind="timeout")+ return run_in_capped_subprocess(*args, **kwargs)++ monkeypatch.setattr(pdf_parser_module, "run_in_capped_subprocess", time_out_on_the_second_pass)++ with structlog.testing.capture_logs() as logs:+ text = extract_pdf_file(str(symbols_pdf), max_tokens=40)++ assert text.count("=" * 60) == 6+ (warning,) = (log for log in logs if "failed, keeping the pages already read" in log["event"])+ assert warning["failure"] == "timeout"++ def test_the_page_that_crosses_the_result_cap_is_cut_instead_of_failing_the_parse(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ symbols_pdf = tmp_path / "symbols.pdf"+ symbols_pdf.write_bytes(_build_letter_pdf(6, ("=" * 60,) * 3))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)+ monkeypatch.setattr(pdf_parser_module, "_PAGE_TEXTS_RESULT", pdf_parser_module._ResultLimit(2048, 6))++ text = extract_pdf_file(str(symbols_pdf), max_tokens=0)++ # The child keeps 1024 of the 2048 bytes for the text and counts 198 for each page, so the sixth is cut.+ assert text.count("=" * 60) == 15++ def test_a_first_page_that_does_not_fit_the_result_cap_fails_the_parse(+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ symbols_pdf = tmp_path / "symbols.pdf"+ symbols_pdf.write_bytes(_build_letter_pdf(2, ("=" * 60,) * 3))+ monkeypatch.setattr(pdf_parser_module, "PdfReader", _RejectingPdfReader)+ monkeypatch.setattr(pdf_parser_module, "_PAGE_TEXTS_RESULT", pdf_parser_module._ResultLimit(300, 6))++ with pytest.raises(PDFParsingError, match="a result may hold"):+ extract_pdf_file(str(symbols_pdf), max_tokens=0)++@pytest.mark.asyncioclass TestParseStepTimeout:"""A pathological document must fail its own block instead of consuming the whole run."""